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
datastructures.rs
use std::iter; use std::ops::{Index, IndexMut}; pub type Idx = [u32; 2]; #[derive(Debug)] pub struct Matrix<T> { shape: Idx, data: Vec<Vec<T>> } impl<T: Copy> Matrix<T> { pub fn fill(shape: Idx, value: T) -> Matrix<T>
pub fn iter<'a>(&'a self) -> Box<Iterator<Item=(Idx, T)> + 'a> { Box::new((0..self.height()).flat_map(move |y| { (0..self.width()).map(move |x| ([x, y], self[[x, y]])) })) } } impl<T> Matrix<T> { pub fn width(&self) -> u32 { self.shape[0] } pub fn height(&self...
{ let data = (0..shape[0]).map(|_| { iter::repeat(value).take(shape[1] as usize) .collect::<Vec<_>>() }).collect::<Vec<_>>(); Matrix { shape: shape, data: data } }
identifier_body
partial_cmp_natural.rs
use malachite_base::num::arithmetic::traits::Sign; use malachite_base::num::basic::traits::One; use malachite_base::num::logic::traits::SignificantBits; use malachite_nz::natural::Natural; use std::cmp::Ordering; use Rational; impl PartialOrd<Natural> for Rational { /// Compares a `Rational` to a `Natural`. //...
(&self, other: &Rational) -> Option<Ordering> { other.partial_cmp(self).map(Ordering::reverse) } }
partial_cmp
identifier_name
partial_cmp_natural.rs
use malachite_base::num::arithmetic::traits::Sign; use malachite_base::num::basic::traits::One; use malachite_base::num::logic::traits::SignificantBits; use malachite_nz::natural::Natural; use std::cmp::Ordering; use Rational; impl PartialOrd<Natural> for Rational { /// Compares a `Rational` to a `Natural`. //...
let sign_cmp = self_sign.cmp(&other_sign); if sign_cmp != Ordering::Equal || self_sign == Ordering::Equal { return Some(sign_cmp); } // Then check if one is < 1 and the other is > 1 let self_cmp_one = self.numerator.cmp(&self.denominator); let other_cmp_one = ...
let other_sign = other.sign();
random_line_split
partial_cmp_natural.rs
use malachite_base::num::arithmetic::traits::Sign; use malachite_base::num::basic::traits::One; use malachite_base::num::logic::traits::SignificantBits; use malachite_nz::natural::Natural; use std::cmp::Ordering; use Rational; impl PartialOrd<Natural> for Rational { /// Compares a `Rational` to a `Natural`. //...
let first_prod_bits = self.numerator.significant_bits(); let second_prod_bits = self.denominator.significant_bits() + other.significant_bits(); if first_prod_bits < second_prod_bits - 1 { return Some(Ordering::Less); } else if first_prod_bits > second_prod_bits { ...
{ let nd_cmp = n_cmp.cmp(&d_cmp); if nd_cmp != Ordering::Equal { return Some(nd_cmp); } }
conditional_block
partial_cmp_natural.rs
use malachite_base::num::arithmetic::traits::Sign; use malachite_base::num::basic::traits::One; use malachite_base::num::logic::traits::SignificantBits; use malachite_nz::natural::Natural; use std::cmp::Ordering; use Rational; impl PartialOrd<Natural> for Rational { /// Compares a `Rational` to a `Natural`. //...
} impl PartialOrd<Rational> for Natural { /// Compares a `Natural` to a `Rational`. /// /// # Worst-case complexity /// TODO /// /// # Examples /// ``` /// extern crate malachite_nz; /// /// use malachite_nz::natural::Natural; /// use malachite_q::Rational; /// use std:...
{ // First check signs let self_sign = self.sign(); let other_sign = other.sign(); let sign_cmp = self_sign.cmp(&other_sign); if sign_cmp != Ordering::Equal || self_sign == Ordering::Equal { return Some(sign_cmp); } // Then check if one is < 1 and the ...
identifier_body
cheese.py
""" Contains CheesePreprocessor """ #----------------------------------------------------------------------------- # Copyright (c) 2013, the IPython Development Team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file COPYING.txt, distributed with this software. #----------...
(self, **kw): """ Public constructor """ super(CheesePreprocessor, self).__init__(**kw) def preprocess(self, nb, resources): """ Sphinx preprocessing to apply on each notebook. Parameters ---------- nb : NotebookNode Note...
__init__
identifier_name
cheese.py
Contains CheesePreprocessor """ #----------------------------------------------------------------------------- # Copyright (c) 2013, the IPython Development Team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file COPYING.txt, distributed with this software. #--------------...
"""
random_line_split
cheese.py
""" Contains CheesePreprocessor """ #----------------------------------------------------------------------------- # Copyright (c) 2013, the IPython Development Team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file COPYING.txt, distributed with this software. #----------...
""" Adds a cheese tag to the resources object """ def __init__(self, **kw): """ Public constructor """ super(CheesePreprocessor, self).__init__(**kw) def preprocess(self, nb, resources): """ Sphinx preprocessing to apply on each notebook. ...
identifier_body
0_setup.py
#!/usr/bin/python # # \file 0_setup.py # \brief Setup rbank # \date 2009-03-10-22-43-GMT # \author Jan Boon (Kaetemi) # Python port of game data build pipeline. # Setup rbank # # NeL - MMORPG Framework <http://dev.ryzom.com/projects/nel/> # Copyright (C) 2010 Winch Gate Property Limited # # This program is free soft...
from scripts import * from buildsite import * from process import * from tools import * from directories import * printLog(log, "") printLog(log, "-------") printLog(log, "--- Setup rbank") printLog(log, "-------") printLog(log, time.strftime("%Y-%m-%d %H:%MGMT", time.gmtime(time.time()))) printLog(log, "") # Setup s...
log = open("log.log", "w")
random_line_split
0_setup.py
#!/usr/bin/python # # \file 0_setup.py # \brief Setup rbank # \date 2009-03-10-22-43-GMT # \author Jan Boon (Kaetemi) # Python port of game data build pipeline. # Setup rbank # # NeL - MMORPG Framework <http://dev.ryzom.com/projects/nel/> # Copyright (C) 2010 Winch Gate Property Limited # # This program is free soft...
mkPath(log, LeveldesignWorldDirectory) # Setup export directories printLog(log, ">>> Setup export directories <<<") mkPath(log, ExportBuildDirectory + "/" + RBankCmbExportDirectory) mkPath(log, ExportBuildDirectory + "/" + RBankCmbTagExportDirectory) mkPath(log, ExportBuildDirectory + "/" + SmallbankExportDirectory) ...
mkPath(log, DatabaseDirectory + "/" + dir)
conditional_block
rpi_pfio.py
""" Allows to configure a switch using the PiFace Digital I/O module on a RPi. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/switch.rpi_pfio/ """ import logging import voluptuous as vol from homeassistant.components.switch import PLATFORM_SCHEMA impor...
(self): """Turn the device off.""" rpi_pfio.write_output(self._port, 1 if self._invert_logic else 0) self._state = False self.schedule_update_ha_state()
turn_off
identifier_name
rpi_pfio.py
""" Allows to configure a switch using the PiFace Digital I/O module on a RPi. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/switch.rpi_pfio/ """ import logging import voluptuous as vol from homeassistant.components.switch import PLATFORM_SCHEMA impor...
def __init__(self, port, name, invert_logic): """Initialize the pin.""" self._port = port self._name = name or DEVICE_DEFAULT_NAME self._invert_logic = invert_logic self._state = False rpi_pfio.write_output(self._port, 1 if self._invert_logic else 0) @property ...
add_devices(switches) class RPiPFIOSwitch(ToggleEntity): """Representation of a PiFace Digital Output."""
random_line_split
rpi_pfio.py
""" Allows to configure a switch using the PiFace Digital I/O module on a RPi. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/switch.rpi_pfio/ """ import logging import voluptuous as vol from homeassistant.components.switch import PLATFORM_SCHEMA impor...
"""Turn the device off.""" rpi_pfio.write_output(self._port, 1 if self._invert_logic else 0) self._state = False self.schedule_update_ha_state()
identifier_body
rpi_pfio.py
""" Allows to configure a switch using the PiFace Digital I/O module on a RPi. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/switch.rpi_pfio/ """ import logging import voluptuous as vol from homeassistant.components.switch import PLATFORM_SCHEMA impor...
add_devices(switches) class RPiPFIOSwitch(ToggleEntity): """Representation of a PiFace Digital Output.""" def __init__(self, port, name, invert_logic): """Initialize the pin.""" self._port = port self._name = name or DEVICE_DEFAULT_NAME self._invert_logic = invert_logic ...
name = port_entity[ATTR_NAME] invert_logic = port_entity[ATTR_INVERT_LOGIC] switches.append(RPiPFIOSwitch(port, name, invert_logic))
conditional_block
svh-a-change-trait-bound.rs
// Copyright 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-MIT or ...
//! The `svh-a-*.rs` files are all deviations from the base file //! svh-a-base.rs with some difference (usually in `fn foo`) that //! should not affect the strict version hash (SVH) computation //! (#14132). #![crate_name = "a"] macro_rules! three { () => { 3 } } pub trait U {} pub trait V {} impl U for () {} i...
random_line_split
svh-a-change-trait-bound.rs
// Copyright 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-MIT or ...
<T:V>(_: int) -> int { 3 } pub fn an_unused_name() -> int { 4 }
foo
identifier_name
svh-a-change-trait-bound.rs
// Copyright 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-MIT or ...
{ 4 }
identifier_body
plot_self_training_varying_threshold.py
""" ============================================= Effect of varying threshold for self-training ============================================= This example illustrates the effect of a varying threshold on self-training. The `breast_cancer` dataset is loaded, and labels are deleted such that only 50 out of 569 samples h...
ax1 = plt.subplot(211) ax1.errorbar( x_values, scores.mean(axis=1), yerr=scores.std(axis=1), capsize=2, color="b" ) ax1.set_ylabel("Accuracy", color="b") ax1.tick_params("y", colors="b") ax2 = ax1.twinx() ax2.errorbar( x_values, amount_labeled.mean(axis=1), yerr=amount_labeled.std(axis=1), capsi...
X_train = X[train_index] y_train = y[train_index] X_test = X[test_index] y_test = y[test_index] y_test_true = y_true[test_index] self_training_clf.fit(X_train, y_train) # The amount of labeled samples that at the end of fitting amount_labeled[i, fold] = ( ...
conditional_block
plot_self_training_varying_threshold.py
""" ============================================= Effect of varying threshold for self-training ============================================= This example illustrates the effect of a varying threshold on self-training. The `breast_cancer` dataset is loaded, and labels are deleted such that only 50 out of 569 samples h...
plt.show()
ax3.set_xlabel("Threshold")
random_line_split
themes.js
module.exports = { light: { background1: 'rgba(227,227,227,.95)', background2: 'rgba(204,204,204,.95)', background2hover: 'rgba(208,208,208,.95)', foreground1: 'rgba(105,105,105,.95)', text1: 'rgba(36,36,36,.95)', text2: 'rgba(87,87,87,.95)' },
background2hover: 'rgba(58,58,58,.95)', foreground1: 'rgba(112,112,112,.95)', text1: 'rgba(235,235,235,.95)', text2: 'rgba(161,161,161,.95)' } }
dark: { background1: 'rgba(35,35,35,.95)', background2: 'rgba(54,54,54,.95)',
random_line_split
ladders-challenges.ts
import type {ChallengeType} from './room-battle'; /** * A bundle of: - a ID * - a battle format * - a valid team for that format * - misc other preferences for the battle * * To start a battle, you need one of these for every player. */ export class BattleReady { readonly userid: ID; readonly formatid: strin...
(accepted?: boolean) { if (accepted) return; const room = Rooms.get(this.roomid); if (!room) return; // room expired? const battle = room.battle!; let invitesFull = true; for (const player of battle.players) { if (!player.invite && !player.id) invitesFull = false; if (player.invite === this.to) playe...
destroy
identifier_name
ladders-challenges.ts
import type {ChallengeType} from './room-battle'; /** * A bundle of: - a ID * - a battle format * - a valid team for that format * - misc other preferences for the battle * * To start a battle, you need one of these for every player. */ export class BattleReady { readonly userid: ID; readonly formatid: strin...
const to = this.getOrCreate(challenge.to); const from = this.getOrCreate(challenge.from); to.push(challenge); from.push(challenge); this.update(challenge.to, challenge.from); return true; } /** Returns false if the challenge isn't in the table */ remove(challenge: Challenge, accepted?: boolean): boolean ...
}
random_line_split
ladders-challenges.ts
import type {ChallengeType} from './room-battle'; /** * A bundle of: - a ID * - a battle format * - a valid team for that format * - misc other preferences for the battle * * To start a battle, you need one of these for every player. */ export class BattleReady { readonly userid: ID; readonly formatid: strin...
searchByRoom(userid: ID, roomid: RoomID) { const challenges = this.get(userid); if (!challenges) return null; for (const challenge of challenges) { if (challenge.roomid === roomid) return challenge; } return null; } /** * Try to accept a custom challenge, throwing `Chat.ErrorMessage` on failure, * ...
{ const challenges = this.get(userid1); if (!challenges) return null; for (const challenge of challenges) { if ( (challenge.to === userid1 && challenge.from === userid2) || (challenge.to === userid2 && challenge.from === userid1) ) { return challenge; } } return null; }
identifier_body
select-demo.ts
import {Component} from '@angular/core'; import {FormControl} from '@angular/forms'; import {MdSelectChange} from '@angular/material'; @Component({ moduleId: module.id, selector: 'select-demo', templateUrl: 'select-demo.html', styleUrls: ['select-demo.css'], }) export class SelectDemo { drinksRequire...
{value: 'coffee-4', viewValue: 'Coffee'}, {value: 'tea-5', viewValue: 'Tea'}, {value: 'juice-6', viewValue: 'Orange juice'}, {value: 'wine-7', viewValue: 'Wine'}, {value: 'milk-8', viewValue: 'Milk'}, ]; pokemon = [ {value: 'bulbasaur-0', viewValue: 'Bulbasaur'}, {value: 'charizard-1', ...
{value: 'water-2', viewValue: 'Water'}, {value: 'pepper-3', viewValue: 'Dr. Pepper'},
random_line_split
select-demo.ts
import {Component} from '@angular/core'; import {FormControl} from '@angular/forms'; import {MdSelectChange} from '@angular/material'; @Component({ moduleId: module.id, selector: 'select-demo', templateUrl: 'select-demo.html', styleUrls: ['select-demo.css'], }) export class
{ drinksRequired = false; pokemonRequired = false; drinksDisabled = false; pokemonDisabled = false; showSelect = false; currentDrink: string; currentPokemon: string[]; latestChangeEvent: MdSelectChange; floatPlaceholder: string = 'auto'; foodControl = new FormControl('pizza-1'); drinksTheme = 'pr...
SelectDemo
identifier_name
select-demo.ts
import {Component} from '@angular/core'; import {FormControl} from '@angular/forms'; import {MdSelectChange} from '@angular/material'; @Component({ moduleId: module.id, selector: 'select-demo', templateUrl: 'select-demo.html', styleUrls: ['select-demo.css'], }) export class SelectDemo { drinksRequire...
setPokemonValue() { this.currentPokemon = ['eevee-4', 'psyduck-6']; } }
{ this.foodControl.enabled ? this.foodControl.disable() : this.foodControl.enable(); }
identifier_body
compare.py
#!/usr/bin/env python import argparse import json import csv import sys sys.path.append('python') import plotting import utils from opener import opener parser = argparse.ArgumentParser() parser.add_argument('-b', action='store_true') # passed on to ROOT when plotting parser.add_argument('--outdir', required=True) ...
assert len(args.plotdirs) == len(args.names) with opener('r')(args.datadir + '/v-meta.json') as json_file: # get location of <begin> cysteine in each v region args.cyst_positions = json.load(json_file) with opener('r')(args.datadir + '/j_tryp.csv') as csv_file: # get location of <end> tryptophan in each j regi...
args.names[iname] = args.names[iname].replace('@', ' ')
conditional_block
compare.py
#!/usr/bin/env python import argparse import json import csv import sys sys.path.append('python')
import utils from opener import opener parser = argparse.ArgumentParser() parser.add_argument('-b', action='store_true') # passed on to ROOT when plotting parser.add_argument('--outdir', required=True) parser.add_argument('--plotdirs', required=True) parser.add_argument('--names', required=True) parser.add_argument('...
import plotting
random_line_split
_selinux.py
# Copyright 1999-2009 Gentoo Foundation # Distributed under the terms of the GNU General Public License v2 # Don't use the unicode-wrapped os and shutil modules here since # the whole _selinux module itself will be wrapped. import os import shutil import portage from portage import _encodings
import selinux from selinux import is_selinux_enabled def copyfile(src, dest): src = _unicode_encode(src, encoding=_encodings['fs'], errors='strict') dest = _unicode_encode(dest, encoding=_encodings['fs'], errors='strict') (rc, ctx) = selinux.lgetfilecon(src) if rc < 0: src = _unicode_decode(src, encoding=_encod...
from portage import _unicode_decode from portage import _unicode_encode from portage.localization import _
random_line_split
_selinux.py
# Copyright 1999-2009 Gentoo Foundation # Distributed under the terms of the GNU General Public License v2 # Don't use the unicode-wrapped os and shutil modules here since # the whole _selinux module itself will be wrapped. import os import shutil import portage from portage import _encodings from portage import _uni...
def symlink(target, link, reflnk): target = _unicode_encode(target, encoding=_encodings['fs'], errors='strict') link = _unicode_encode(link, encoding=_encodings['fs'], errors='strict') reflnk = _unicode_encode(reflnk, encoding=_encodings['fs'], errors='strict') (rc, ctx) = selinux.lgetfilecon(reflnk) if rc < 0: ...
selinux_type = _unicode_encode(selinux_type, encoding=_encodings['content'], errors='strict') def wrapper_func(*args, **kwargs): con = settype(selinux_type) setexec(con) try: return spawn_func(*args, **kwargs) finally: setexec() return wrapper_func
identifier_body
_selinux.py
# Copyright 1999-2009 Gentoo Foundation # Distributed under the terms of the GNU General Public License v2 # Don't use the unicode-wrapped os and shutil modules here since # the whole _selinux module itself will be wrapped. import os import shutil import portage from portage import _encodings from portage import _uni...
def spawn_wrapper(spawn_func, selinux_type): selinux_type = _unicode_encode(selinux_type, encoding=_encodings['content'], errors='strict') def wrapper_func(*args, **kwargs): con = settype(selinux_type) setexec(con) try: return spawn_func(*args, **kwargs) finally: setexec() return wrapper_func d...
ctx = _unicode_decode(ctx, encoding=_encodings['content'], errors='replace') raise OSError( _("setfscreate: Failed setting fs create context \"%s\".") % ctx)
conditional_block
_selinux.py
# Copyright 1999-2009 Gentoo Foundation # Distributed under the terms of the GNU General Public License v2 # Don't use the unicode-wrapped os and shutil modules here since # the whole _selinux module itself will be wrapped. import os import shutil import portage from portage import _encodings from portage import _uni...
(target, link, reflnk): target = _unicode_encode(target, encoding=_encodings['fs'], errors='strict') link = _unicode_encode(link, encoding=_encodings['fs'], errors='strict') reflnk = _unicode_encode(reflnk, encoding=_encodings['fs'], errors='strict') (rc, ctx) = selinux.lgetfilecon(reflnk) if rc < 0: reflnk = _u...
symlink
identifier_name
TestServer.ts
import { Type } from '@tsed/core'; import { ServerLoader, IServerSettings, OverrideService, ExpressApplication, ServerSettings } from '@tsed/common'; import { ProjectMapper, MutationTestingReportService } from '@stryker-mutator/dashboard-data-access'; import { bootstrap, inject, TestContext } from '@tsed/testing'; impo...
this.use(bodyParser.json()); } } await bootstrap(TestServer)(); await inject([ExpressApplication], (app: ExpressApplication) => { request = supertest(app); })(); return request; }
{ this.use(...middlewares); }
conditional_block
TestServer.ts
import { Type } from '@tsed/core'; import { ServerLoader, IServerSettings, OverrideService, ExpressApplication, ServerSettings } from '@tsed/common'; import { ProjectMapper, MutationTestingReportService } from '@stryker-mutator/dashboard-data-access'; import { bootstrap, inject, TestContext } from '@tsed/testing'; impo...
} public get getAllForOrganization() { return RepositoryServiceStub.getAllForOrganization; } public get update() { return RepositoryServiceStub.update; } } beforeEach(() => { ConfigurationStub.githubClientId = 'github client id'; ConfigurationStub.githubSecret = 'github secret'; ConfigurationSt...
random_line_split
TestServer.ts
import { Type } from '@tsed/core'; import { ServerLoader, IServerSettings, OverrideService, ExpressApplication, ServerSettings } from '@tsed/common'; import { ProjectMapper, MutationTestingReportService } from '@stryker-mutator/dashboard-data-access'; import { bootstrap, inject, TestContext } from '@tsed/testing'; impo...
@OverrideService(GithubRepositoryService) export class RepositoryServiceStub { public static getAllForUser: sinon.SinonStub; public static getAllForOrganization: sinon.SinonStub; public static update: sinon.SinonStub; public get getAllForUser() { return RepositoryServiceStub.getAllForUser; } public ge...
{ const token = await createToken(user, ConfigurationStub.jwtSecret); return `Bearer ${token}`; }
identifier_body
TestServer.ts
import { Type } from '@tsed/core'; import { ServerLoader, IServerSettings, OverrideService, ExpressApplication, ServerSettings } from '@tsed/common'; import { ProjectMapper, MutationTestingReportService } from '@stryker-mutator/dashboard-data-access'; import { bootstrap, inject, TestContext } from '@tsed/testing'; impo...
() { if (middlewares.length) { this.use(...middlewares); } this.use(bodyParser.json()); } } await bootstrap(TestServer)(); await inject([ExpressApplication], (app: ExpressApplication) => { request = supertest(app); })(); return request; }
$beforeRoutesInit
identifier_name
main.rs
#[macro_use] extern crate rocket; #[macro_use] extern crate rocket_contrib; mod airport_data; mod api; mod path; use airport_data::our_airports::OurAirports;
use anyhow::{Context, Result}; use rocket::config::{Config, Environment}; use rocket_contrib::serve::StaticFiles; #[rocket::main] async fn main() -> Result<()> { let config = { let env = Environment::active().context("failed to get Rocket config")?; Config::build(env) .workers(1) ...
use airport_data::AirportData;
random_line_split
main.rs
#[macro_use] extern crate rocket; #[macro_use] extern crate rocket_contrib; mod airport_data; mod api; mod path; use airport_data::our_airports::OurAirports; use airport_data::AirportData; use anyhow::{Context, Result}; use rocket::config::{Config, Environment}; use rocket_contrib::serve::StaticFiles; #[rocket::mai...
() -> Result<()> { let config = { let env = Environment::active().context("failed to get Rocket config")?; Config::build(env) .workers(1) .finalize() .context("failed to build Rocket config")? }; let mut airports_source = OurAirports::init().context("fai...
main
identifier_name
main.rs
#[macro_use] extern crate rocket; #[macro_use] extern crate rocket_contrib; mod airport_data; mod api; mod path; use airport_data::our_airports::OurAirports; use airport_data::AirportData; use anyhow::{Context, Result}; use rocket::config::{Config, Environment}; use rocket_contrib::serve::StaticFiles; #[rocket::mai...
{ let config = { let env = Environment::active().context("failed to get Rocket config")?; Config::build(env) .workers(1) .finalize() .context("failed to build Rocket config")? }; let mut airports_source = OurAirports::init().context("failed to init OurAi...
identifier_body
main.rs
#[macro_use] extern crate rocket; #[macro_use] extern crate rocket_contrib; mod airport_data; mod api; mod path; use airport_data::our_airports::OurAirports; use airport_data::AirportData; use anyhow::{Context, Result}; use rocket::config::{Config, Environment}; use rocket_contrib::serve::StaticFiles; #[rocket::mai...
; let airports = airports_source .load() .context("failed to load OurAirports data")?; println!("finished loading OurAirports data"); rocket::custom(config) .manage(airports) .mount("/", StaticFiles::from("frontend/public/")) .mount("/api", routes![api::search_rout...
{ println!("updating OurAirports data.."); airports_source.update().context("update failed")?; }
conditional_block
smoke_test.py
# # Copyright (c) 2014 ThoughtWorks Deutschland GmbH # # Pixelated is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Pixelated...
(object): def __init__(self, run_method, shutdown_method, thread_name=None): self._run_method = run_method self._shutdown_method = shutdown_method self._thread_name = thread_name self._thread = None def _start_server(self): self._thread = thre...
Server
identifier_name
smoke_test.py
# # Copyright (c) 2014 ThoughtWorks Deutschland GmbH # # Pixelated is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by
# # Pixelated is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public Lic...
# the Free Software Foundation, either version 3 of the License, or # (at your option) any later version.
random_line_split
smoke_test.py
# # Copyright (c) 2014 ThoughtWorks Deutschland GmbH # # Pixelated is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Pixelated...
def assertSuccess(self, response, body=None, json_body=None): status = response.status_code self.assertTrue(200 <= status < 300, msg='%d: %s' % (response.status_code, response.reason)) if body: self.assertEqual(body, response.content) if json_body: self.asse...
with self._dispatcher_manager(): with self._dispatcher_proxy(): # add user self.assertSuccess( self.post('https://localhost:4443/agents', json_data={'name': 'test', 'password': 'some password'})) # try to login with agent down ...
identifier_body
smoke_test.py
# # Copyright (c) 2014 ThoughtWorks Deutschland GmbH # # Pixelated is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Pixelated...
else: cookies = {'_xsrf': '2|7586b241|47c876d965112a2f547c63c95cbc44b1|1402910163'} headers = None data = form_data.copy() data['_xsrf'] = '2|7586b241|47c876d965112a2f547c63c95cbc44b1|1402910163' return method(url, data=data, headers=headers, cookies=coo...
headers = {'content-type': 'application/json'} data = json.dumps(json_data) cookies = None
conditional_block
config.rs
// Copyright (c) 2016 Nikita Pekin and the smexybot contributors // See the README.md file at the top-level directory of this distribution. // // 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 http://opensource.org/l...
(name: Option<&str>) -> Self { if let Some(name) = name { match Config::load_from_file(name) { Ok(config) => { return config; }, Err(err) => warn!("Failed for load config from \"{}\": {}", name, err), } } ...
new
identifier_name
config.rs
// Copyright (c) 2016 Nikita Pekin and the smexybot contributors // See the README.md file at the top-level directory of this distribution. // // 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 http://opensource.org/l...
}
{ Config { bot_name: "smexybot".to_owned(), command_prefix: ";".to_owned(), owners: HashSet::new(), source_url: "https://github.com/indiv0/smexybot".to_owned(), } }
identifier_body
config.rs
// Copyright (c) 2016 Nikita Pekin and the smexybot contributors // See the README.md file at the top-level directory of this distribution. // // 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 http://opensource.org/l...
command_prefix: ";".to_owned(), owners: HashSet::new(), source_url: "https://github.com/indiv0/smexybot".to_owned(), } } }
impl Default for Config { fn default() -> Config { Config { bot_name: "smexybot".to_owned(),
random_line_split
coerce-unify-return.rs
// Copyright 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-MIT or ...
; impl Foo { fn foo<T>(self, x: T) -> Option<T> { Some(x) } } pub fn main() { let _: Option<fn()> = Some(main); let _: Option<fn()> = Foo.foo(main); // The same two cases, with implicit type variables made explicit. let _: Option<fn()> = Some::<_>(main); let _: Option<fn()> = Foo.foo::<_>(main...
Foo
identifier_name
coerce-unify-return.rs
// Copyright 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-MIT or ...
let _: Option<fn()> = Foo.foo(main); // The same two cases, with implicit type variables made explicit. let _: Option<fn()> = Some::<_>(main); let _: Option<fn()> = Foo.foo::<_>(main); }
let _: Option<fn()> = Some(main);
random_line_split
coerce-unify-return.rs
// Copyright 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-MIT or ...
} pub fn main() { let _: Option<fn()> = Some(main); let _: Option<fn()> = Foo.foo(main); // The same two cases, with implicit type variables made explicit. let _: Option<fn()> = Some::<_>(main); let _: Option<fn()> = Foo.foo::<_>(main); }
{ Some(x) }
identifier_body
Elements.ts
/** * Copyright (c) 2017 ~ present NAVER Corp. * billboard.js project is licensed under the MIT license */ // @ts-nocheck import CLASS from "./classes"; import {getCentroid, isString, parseDate} from "./util"; /** * Stanford diagram plugin element class * @class ColorScale * @param {Stanford} owner Stanford inst...
yvCustom(d, xyValue): number { const $$ = this; const yScale = d.axis && d.axis === "y2" ? $$.scale.y2 : $$.scale.y; const value = xyValue ? d[xyValue] : $$.getBaseValue(d); return Math.ceil(yScale(value)); } }
{ const $$ = this; const {axis, config} = $$; let value = xyValue ? d[xyValue] : $$.getBaseValue(d); if (axis.isTimeSeries()) { value = parseDate.call($$, value); } else if (axis.isCategorized() && isString(value)) { value = config.axis_x_categories.indexOf(d.value); } return Math.ceil($$.scale.x(...
identifier_body
Elements.ts
/** * Copyright (c) 2017 ~ present NAVER Corp. * billboard.js project is licensed under the MIT license */ // @ts-nocheck import CLASS from "./classes"; import {getCentroid, isString, parseDate} from "./util"; /** * Stanford diagram plugin element class * @class ColorScale * @param {Stanford} owner Stanford inst...
return Math.ceil($$.scale.x(value)); } yvCustom(d, xyValue): number { const $$ = this; const yScale = d.axis && d.axis === "y2" ? $$.scale.y2 : $$.scale.y; const value = xyValue ? d[xyValue] : $$.getBaseValue(d); return Math.ceil(yScale(value)); } }
{ value = config.axis_x_categories.indexOf(d.value); }
conditional_block
Elements.ts
/** * Copyright (c) 2017 ~ present NAVER Corp. * billboard.js project is licensed under the MIT license */ // @ts-nocheck import CLASS from "./classes"; import {getCentroid, isString, parseDate} from "./util"; /** * Stanford diagram plugin element class * @class ColorScale * @param {Stanford} owner Stanford inst...
{ private owner; constructor(owner) { this.owner = owner; // MEMO: Avoid blocking eventRect const elements = owner.$$.$el.main.select(".bb-chart") .append("g") .attr("class", CLASS.stanfordElements); elements.append("g").attr("class", CLASS.stanfordLines); elements.append("g").attr("class", CLASS....
Elements
identifier_name
Elements.ts
/** * Copyright (c) 2017 ~ present NAVER Corp. * billboard.js project is licensed under the MIT license */ // @ts-nocheck import CLASS from "./classes"; import {getCentroid, isString, parseDate} from "./util"; /** * Stanford diagram plugin element class * @class ColorScale * @param {Stanford} owner Stanford inst...
.select("polygon") .transition() .duration(duration) .attr("points", d => d.points.map(value => [ isRotated ? yvCustom(value, "y") : xvCustom(value, "x"), isRotated ? xvCustom(value, "x") : yvCustom(value, "y") ].join(",")).join(" ")) .transition() .style("opacity", d => String(d.opacity ? ...
stanfordRegion .attr("class", d => CLASS.stanfordRegion + (d.class ? ` ${d.class}` : ""))
random_line_split
snooze-rounded.js
d: "M10 11h2.63l-3.72 4.35C8.36 16 8.82 17 9.67 17H14c.55 0 1-.45 1-1s-.45-1-1-1h-2.63l3.72-4.35c.55-.65.09-1.65-.76-1.65H10c-.55 0-1 .45-1 1s.45 1 1 1zm11.3-4.58c-.35.42-.98.48-1.41.13l-3.07-2.56c-.42-.36-.48-.99-.12-1.41.35-.42.98-.48 1.41-.13l3.07 2.56c.42.36.48.99.12 1.41zm-18.6 0c.35.43.98.48 1.4.13l3.07-2.56c.4...
import { h } from 'omi'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon(h("path", {
random_line_split
_cuda_types.py
import numpy from cupy._core._scalar import get_typename # Base class for cuda types. class TypeBase: def __str__(self): raise NotImplementedError def declvar(self, x): return f'{self} {x}' class Void(TypeBase): def __init__(self): pass def __str__(self): return '...
class ArrayBase(TypeBase): def __init__(self, child_type: TypeBase, ndim: int): assert isinstance(child_type, TypeBase) self.child_type = child_type self.ndim = ndim class CArray(ArrayBase): def __init__(self, dtype, ndim, is_c_contiguous, index_32_bits): self.dtype = dtype...
return hash(self.dtype)
identifier_body
_cuda_types.py
import numpy from cupy._core._scalar import get_typename # Base class for cuda types. class TypeBase: def __str__(self): raise NotImplementedError def declvar(self, x): return f'{self} {x}' class Void(TypeBase): def __init__(self): pass def __str__(self): return '...
(self): ctype = get_typename(self.dtype) c_contiguous = get_cuda_code_from_constant(self._c_contiguous, bool_) index_32_bits = get_cuda_code_from_constant(self._index_32_bits, bool_) return f'CArray<{ctype}, {self.ndim}, {c_contiguous}, {index_32_bits}>' def __eq__(self, other): ...
__str__
identifier_name
_cuda_types.py
import numpy from cupy._core._scalar import get_typename # Base class for cuda types. class TypeBase: def __str__(self): raise NotImplementedError def declvar(self, x): return f'{self} {x}' class Void(TypeBase): def __init__(self): pass def __str__(self): return '...
return f'{ctype}({x})'
return f'({ctype}){x}'
conditional_block
_cuda_types.py
import numpy from cupy._core._scalar import get_typename # Base class for cuda types. class TypeBase: def __str__(self): raise NotImplementedError def declvar(self, x): return f'{self} {x}' class Void(TypeBase): def __init__(self): pass def __str__(self): return '...
super().__init__(Scalar(dtype), ndim) @classmethod def from_ndarray(cls, x): return CArray(x.dtype, x.ndim, x._c_contiguous, x._index_32_bits) def __str__(self): ctype = get_typename(self.dtype) c_contiguous = get_cuda_code_from_constant(self._c_contiguous, bool_) i...
self.dtype = dtype self._c_contiguous = is_c_contiguous self._index_32_bits = index_32_bits
random_line_split
wc.dom.messageBox.test.js
define(["intern!object", "intern/chai!assert", "wc/dom/messageBox", "wc/dom/classList", "wc/ui/icon", "wc/i18n/i18n", "./resources/test.utils!"], function (registerSuite, assert, controller, classList, icon, i18n, testutils) { "use strict"; /* * Unit tests for wc/dom/messageBox */ var testHolder, testBo...
(type) { var box = document.getElementById(testBoxId), iconName, title, boxHeading; if (!box) { testHolder.insertAdjacentHTML("beforeend", testMessageBoxHTML); box = document.getElementById(testBoxId); } boxHeading = box.firstElementChild; if (type && !icon.get(boxHeading)) { classList....
getTestBox
identifier_name
wc.dom.messageBox.test.js
define(["intern!object", "intern/chai!assert", "wc/dom/messageBox", "wc/dom/classList", "wc/ui/icon", "wc/i18n/i18n", "./resources/test.utils!"], function (registerSuite, assert, controller, classList, icon, i18n, testutils) { "use strict"; /* * Unit tests for wc/dom/messageBox */ var testHolder, testBo...
} return box; } registerSuite({ name: "wc/dom/messageBox", setup: function() { testHolder = testutils.getTestHolder(); }, beforeEach: function() { testHolder.innerHTML = testContent; }, afterEach: function() { testHolder.innerHTML = ""; }, testGetWidget: function() { ...
{ icon.add(boxHeading, iconName); icon.add(boxHeading, "fa-fw"); boxHeading.insertAdjacentHTML("beforeend", "<span>" + title + "</span>"); }
conditional_block
wc.dom.messageBox.test.js
define(["intern!object", "intern/chai!assert", "wc/dom/messageBox", "wc/dom/classList", "wc/ui/icon", "wc/i18n/i18n", "./resources/test.utils!"], function (registerSuite, assert, controller, classList, icon, i18n, testutils) { "use strict"; /* * Unit tests for wc/dom/messageBox */ var testHolder, testBo...
testGet_inContainer: function() { var box = getTestBox(); // set up the box to find assert.equal(controller.get(testHolder), box); }, testGet_noContainerAll: function() { var box = getTestBox(), found = controller.get(null, true); assert.equal(found.length, 1); assert.equal(found[0], b...
},
random_line_split
wc.dom.messageBox.test.js
define(["intern!object", "intern/chai!assert", "wc/dom/messageBox", "wc/dom/classList", "wc/ui/icon", "wc/i18n/i18n", "./resources/test.utils!"], function (registerSuite, assert, controller, classList, icon, i18n, testutils) { "use strict"; /* * Unit tests for wc/dom/messageBox */ var testHolder, testBo...
registerSuite({ name: "wc/dom/messageBox", setup: function() { testHolder = testutils.getTestHolder(); }, beforeEach: function() { testHolder.innerHTML = testContent; }, afterEach: function() { testHolder.innerHTML = ""; }, testGetWidget: function() { var widget = controller....
{ var box = document.getElementById(testBoxId), iconName, title, boxHeading; if (!box) { testHolder.insertAdjacentHTML("beforeend", testMessageBoxHTML); box = document.getElementById(testBoxId); } boxHeading = box.firstElementChild; if (type && !icon.get(boxHeading)) { classList.add(box...
identifier_body
ProxyStore.js
/** * ProxyStore is a superclass of {@link Ext.data.Store} and {@link Ext.data.BufferedStore}. It's never used directly, * but offers a set of methods used by both of those subclasses. * * We've left it here in the docs for reference purposes, but unless you need to make a whole new type of Store, what * you're pr...
me.unblockLoad(doLoad); }, updateProxy: function(proxy, oldProxy) { this.proxyListeners = Ext.destroy(this.proxyListeners); }, updateTrackRemoved: function (track) { this.cleanRemoved(); this.removed = track ? [] : null; }, /** * @private */ onMet...
var me = this, doLoad = me.getAutoLoad() || me.isLoaded(); me.blockLoad(); me.callParent([state]);
random_line_split
ProxyStore.js
/** * ProxyStore is a superclass of {@link Ext.data.Store} and {@link Ext.data.BufferedStore}. It's never used directly, * but offers a set of methods used by both of those subclasses. * * We've left it here in the docs for reference purposes, but unless you need to make a whole new type of Store, what * you're pr...
// If no model, ensure that the fields config is converted to a model. else { this.getFields(); model = this.getModel() || this.createImplicitModel(); } return model; }, applyProxy: function(proxy) { var model = this.getModel(); if (prox...
{ model = Ext.data.schema.Schema.lookupEntity(model); }
conditional_block
parser.rs
extern crate dirs; use regex::Regex; use std::fs::File; use std::io::prelude::*; use std::path::Path; use {Creds, Result}; pub fn get_credentials(conf: String) -> Result<Creds> { let mut path = dirs::home_dir().ok_or("Can't get home dir")?; // Build path to config file path.push(conf); let content ...
(pattern: &str, text: &str) -> Result<String> { let re = Regex::new(pattern)?; let cap = re.captures(text).ok_or("Couldn't match")?; let xtr = cap.get(1).ok_or("No captures")?; Ok(xtr.as_str().to_string()) } fn read_config_file(path: &Path) -> Result<String> { let mut content = String::new(); l...
extract_info
identifier_name
parser.rs
extern crate dirs; use regex::Regex; use std::fs::File; use std::io::prelude::*; use std::path::Path; use {Creds, Result}; pub fn get_credentials(conf: String) -> Result<Creds> { let mut path = dirs::home_dir().ok_or("Can't get home dir")?; // Build path to config file path.push(conf); let content ...
path.push(::DB); let path_str = path.to_str() .ok_or("Can't convert path into string")?; Ok(path_str.to_string()) }
random_line_split
parser.rs
extern crate dirs; use regex::Regex; use std::fs::File; use std::io::prelude::*; use std::path::Path; use {Creds, Result}; pub fn get_credentials(conf: String) -> Result<Creds> { let mut path = dirs::home_dir().ok_or("Can't get home dir")?; // Build path to config file path.push(conf); let content ...
fn read_config_file(path: &Path) -> Result<String> { let mut content = String::new(); let mut file = File::open(&path)?; file.read_to_string(&mut content)?; Ok(content) } pub fn get_db_path() -> Result<String> { let mut path = dirs::home_dir().ok_or("Can't get home dir")?; path.push(::DB); ...
{ let re = Regex::new(pattern)?; let cap = re.captures(text).ok_or("Couldn't match")?; let xtr = cap.get(1).ok_or("No captures")?; Ok(xtr.as_str().to_string()) }
identifier_body
startSandbox.js
import express from 'express'; import unpackByOutpoint from './unpackByOutpoint'; // Polyfills and `lbry-redux` global.fetch = require('node-fetch'); global.window = global; if (typeof global.fetch === 'object') { global.fetch = global.fetch.default; } const { Lbry } = require('lbry-redux'); delete global.window; ...
}); }
{ console.log( `Server already listening at localhost:${port}. This is probably another LBRY app running. If not, games in the app will not work.` ); }
conditional_block
startSandbox.js
import express from 'express'; import unpackByOutpoint from './unpackByOutpoint'; // Polyfills and `lbry-redux` global.fetch = require('node-fetch'); global.window = global; if (typeof global.fetch === 'object') { global.fetch = global.fetch.default; } const { Lbry } = require('lbry-redux');
const sandbox = express(); sandbox.get('/set/:outpoint', async (req, res) => { const { outpoint } = req.params; const resolvedPath = await unpackByOutpoint(Lbry, outpoint); sandbox.use(`/sandbox/${outpoint}/`, express.static(resolvedPath)); res.send(`/sandbox/${outpoint}/`); }); sandbox ...
delete global.window; export default async function startSandbox() { const port = 5278;
random_line_split
startSandbox.js
import express from 'express'; import unpackByOutpoint from './unpackByOutpoint'; // Polyfills and `lbry-redux` global.fetch = require('node-fetch'); global.window = global; if (typeof global.fetch === 'object') { global.fetch = global.fetch.default; } const { Lbry } = require('lbry-redux'); delete global.window; ...
() { const port = 5278; const sandbox = express(); sandbox.get('/set/:outpoint', async (req, res) => { const { outpoint } = req.params; const resolvedPath = await unpackByOutpoint(Lbry, outpoint); sandbox.use(`/sandbox/${outpoint}/`, express.static(resolvedPath)); res.send(`/sandbox/${outpoint...
startSandbox
identifier_name
startSandbox.js
import express from 'express'; import unpackByOutpoint from './unpackByOutpoint'; // Polyfills and `lbry-redux` global.fetch = require('node-fetch'); global.window = global; if (typeof global.fetch === 'object') { global.fetch = global.fetch.default; } const { Lbry } = require('lbry-redux'); delete global.window; ...
{ const port = 5278; const sandbox = express(); sandbox.get('/set/:outpoint', async (req, res) => { const { outpoint } = req.params; const resolvedPath = await unpackByOutpoint(Lbry, outpoint); sandbox.use(`/sandbox/${outpoint}/`, express.static(resolvedPath)); res.send(`/sandbox/${outpoint}/`...
identifier_body
Ping.js
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("va...
load: _os2.default.loadavg(), uptime: _os2.default.uptime() } }; } }]); return PingMessage; }(); exports.default = PingMessage;
mem: { total: _os2.default.totalmem(), free: _os2.default.freemem() },
random_line_split
Ping.js
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("va...
_createClass(PingMessage, null, [{ key: 'construct', value: function construct(id) { return { id: id, msg: 'I am still alive!', os: { mem: { total: _os2.default.totalmem(), free: _os2.default.freemem() }, load: _os2.default....
{ _classCallCheck(this, PingMessage); }
identifier_body
Ping.js
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("va...
(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var PingMessage = function () { function PingMessage() { _classCallCheck(this, PingMessage); ...
_interopRequireDefault
identifier_name
index.js
'use strict'; const { messages, ruleName } = require('..'); testRule({ ruleName, config: [ { border: 2, '/^margin/': 1, }, ], accept: [ { code: 'a { margin: 0; }', }, { code: 'a { margin: 1px; }', }, { code: 'a { margin: var(--foo); }', description: 'deals with CSS variables', ...
line: 1, column: 5, }, { code: 'a { border: 1px solid blue; }', message: messages.rejected('border', 2), line: 1, column: 5, }, ], });
message: messages.rejected('margin', 1),
random_line_split
ctypes.rs
// Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in w...
}
random_line_split
ctypes.rs
// Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in w...
(apis: &mut Vec<Api<FnPhase>>) { let ctypes: HashMap<Ident, QualifiedName> = apis .iter() .flat_map(|api| api.deps()) .filter(|ty| known_types().is_ctype(ty)) .map(|ty| (ty.get_final_ident(), ty)) .collect(); for (id, typename) in ctypes { apis.push(Api::CType { ...
append_ctype_information
identifier_name
ctypes.rs
// Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in w...
{ let ctypes: HashMap<Ident, QualifiedName> = apis .iter() .flat_map(|api| api.deps()) .filter(|ty| known_types().is_ctype(ty)) .map(|ty| (ty.get_final_ident(), ty)) .collect(); for (id, typename) in ctypes { apis.push(Api::CType { name: ApiName::new(&...
identifier_body
test_runSimulation.py
from .. import runSimulation import pytest, os def
(): infoFile = open(os.path.dirname(__file__) + '/../EngFrJapGerm.txt') runSim1 = runSimulation.runSimulation(infoFile.readlines(), 611) infoFile.close() # These four ids are present in EngFrJapGerm: French=584, English=611, German=2253, Japanese=3856 # Check that makeSelectedSenten...
test_makeSelectedSentences
identifier_name
test_runSimulation.py
from .. import runSimulation import pytest, os def test_makeSelectedSentences():
infoFile = open(os.path.dirname(__file__) + '/../EngFrJapGerm.txt') runSim1 = runSimulation.runSimulation(infoFile.readlines(), 611) infoFile.close() # These four ids are present in EngFrJapGerm: French=584, English=611, German=2253, Japanese=3856 # Check that makeSelectedSentenceList retur...
identifier_body
test_runSimulation.py
from .. import runSimulation import pytest, os def test_makeSelectedSentences(): infoFile = open(os.path.dirname(__file__) + '/../EngFrJapGerm.txt') runSim1 = runSimulation.runSimulation(infoFile.readlines(), 611) infoFile.close() # These four ids are present in EngFrJapGerm: French=584, ...
runSim1.selectedSentences = [] runSim1.makeSelectedSentenceList() assert not runSim1.selectedSentences runSim1.targetGrammar = None runSim1.selectedSentences = [] runSim1.makeSelectedSentenceList() assert not runSim1.selectedSentences
# when given ids that don't exist in the orignal txt file runSim1.targetGrammar = 612
random_line_split
lexer.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::{errors::*, parser::syntax::make_loc, FileCommentMap, MatchedFileCommentMap}; use codespan::{ByteIndex, Span}; use move_ir_types::location::Loc; use std::{collections::BTreeMap, fmt}; #[derive(Copy, Clone, Debug, PartialEq, ...
pub fn advance(&mut self) -> Result<(), Error> { self.prev_end = self.cur_end; let text = self.text[self.cur_end..].trim_start(); self.cur_start = self.text.len() - text.len(); let (token, len) = find_token(self.file, text, self.cur_start)?; self.cur_end = self.cur_start + ...
{ let errors = self .doc_comments .iter() .map(|(span, _)| { vec![( Loc::new(self.file, *span), "documentation comment cannot be matched to a language item".to_string(), )] }) .col...
identifier_body
lexer.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::{errors::*, parser::syntax::make_loc, FileCommentMap, MatchedFileCommentMap}; use codespan::{ByteIndex, Span}; use move_ir_types::location::Loc; use std::{collections::BTreeMap, fmt}; #[derive(Copy, Clone, Debug, PartialEq, ...
True => "true", Use => "use", While => "while", LBrace => "{", Pipe => "|", PipePipe => "||", RBrace => "}", Fun => "fun", Script => "script", Const => "const", Friend => "friend", ...
Spec => "spec", Struct => "struct",
random_line_split
lexer.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::{errors::*, parser::syntax::make_loc, FileCommentMap, MatchedFileCommentMap}; use codespan::{ByteIndex, Span}; use move_ir_types::location::Loc; use std::{collections::BTreeMap, fmt}; #[derive(Copy, Clone, Debug, PartialEq, ...
(&mut self) { let start = self.previous_end_loc() as u32; let end = self.cur_start as u32; let mut matched = vec![]; let merged = self .doc_comments .range(Span::new(start, start)..Span::new(end, end)) .map(|(span, s)| { matched.push(*s...
match_doc_comments
identifier_name
tnzcore.ts
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE TS> <TS version="2.1" language="zh_CN"> <context> <name>QObject</name> <message> <source>colors</source> <translation>颜色</translation> </message> <message> <source>Unidentified Action</source> <translation>未标识的动作</translati...
<source>Thickness</source> <translation>粗细</translation> </message> </context> <context> <name>TRasterImagePatternStrokeStyle</name> <message> <source>Distance</source> <translation>距离</translation> </message> <message> <source>Rotation</source> <trans...
<message>
random_line_split
sf_tuto.py
import time import numpy from golib.config.golib_conf import gsize, B, W, E import camkifu.stone from camkifu.core import imgutil class StonesFinderTuto(camkifu.stone.StonesFinder): """ This class has been used to write a tutorial on how to create a new StonesFinder. Run Camkifu with this class as the defa...
self.bulk_update(moves) def _find_getrect(self, goban_img): """ Implementation 4 of _find() from the tutorial. """ canvas = numpy.zeros_like(goban_img) for r in range(gsize): # row index for c in range(gsize): # column index if r == c or r =...
if not self.is_empty(r, c): moves.append((E, r, c)) time.sleep(0.7)
random_line_split
sf_tuto.py
import time import numpy from golib.config.golib_conf import gsize, B, W, E import camkifu.stone from camkifu.core import imgutil class StonesFinderTuto(camkifu.stone.StonesFinder): """ This class has been used to write a tutorial on how to create a new StonesFinder. Run Camkifu with this class as the defa...
(self, _): """ Implementation 2 of _find() from the tutorial. """ # check emptiness to avoid complaints since this method will be called in a loop if self.is_empty(2, 12): # using "numpy" coordinates frame for x and y self.suggest(B, 2, 12) def _find_bulk(sel...
_find_suggest
identifier_name
sf_tuto.py
import time import numpy from golib.config.golib_conf import gsize, B, W, E import camkifu.stone from camkifu.core import imgutil class StonesFinderTuto(camkifu.stone.StonesFinder): """ This class has been used to write a tutorial on how to create a new StonesFinder. Run Camkifu with this class as the defa...
self._show(canvas) def _find_border(self, goban_img): """ Implementation 5 of _find() from the tutorial. """ canvas = numpy.zeros_like(goban_img) for r, c in self._empties_border(2): # 2 is the line height as in go vocabulary (0-based) x0, y0, x1, y1 = self.get...
if r == c or r == gsize - c - 1: x0, y0, x1, y1 = self.getrect(r, c) canvas[x0:x1, y0:y1] = goban_img[x0:x1, y0:y1]
conditional_block
sf_tuto.py
import time import numpy from golib.config.golib_conf import gsize, B, W, E import camkifu.stone from camkifu.core import imgutil class StonesFinderTuto(camkifu.stone.StonesFinder): """ This class has been used to write a tutorial on how to create a new StonesFinder. Run Camkifu with this class as the defa...
# ------------------------------------------------------ # # TUTORIAL STEPS # # ------------------------------------------------------ def _find_minimal(self, goban_img): """ Implementation 1 of _find() from the tutorial. """ imgutil.draw_str(goban_img, "...
pass
identifier_body
dhcp.rs
/* Copyright (C) 2018 Open Information Security Foundation * * You can copy, redistribute or modify this Program under the terms of * the GNU General Public License version 2 as published by the Free * Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARR...
} fn set_event(&mut self, event: DHCPEvent) { if let Some(tx) = self.transactions.last_mut() { core::sc_app_layer_decoder_events_set_event_raw( &mut tx.events, event as u8); self.events += 1; } } fn get_tx_iterator(&mut self, min_tx_id: u64, sta...
{ self.transactions.remove(index); }
conditional_block
dhcp.rs
/* Copyright (C) 2018 Open Information Security Foundation * * You can copy, redistribute or modify this Program under the terms of * the GNU General Public License version 2 as published by the Free * Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARR...
() -> DHCPState { return DHCPState { tx_id: 0, transactions: Vec::new(), events: 0, }; } pub fn parse(&mut self, input: &[u8]) -> bool { match dhcp_parse(input) { nom::IResult::Done(_, message) => { let malformed_options = ...
new
identifier_name
dhcp.rs
/* Copyright (C) 2018 Open Information Security Foundation * * You can copy, redistribute or modify this Program under the terms of * the GNU General Public License version 2 as published by the Free * Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARR...
#[no_mangle] pub extern "C" fn rs_dhcp_tx_get_logged(_state: *mut libc::c_void, tx: *mut libc::c_void) -> u32 { let tx = cast_pointer!(tx, DHCPTransaction); return tx.logged.get(); } #[no_mangle] pub extern "C" fn rs_dhcp_tx_set_logged(_state: *mut libc::c_void, tx: *m...
{ // Just unbox... let _drop: Box<DHCPState> = unsafe { transmute(state) }; }
identifier_body
dhcp.rs
/* Copyright (C) 2018 Open Information Security Foundation * * You can copy, redistribute or modify this Program under the terms of * the GNU General Public License version 2 as published by the Free * Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARR...
#[no_mangle] pub extern "C" fn rs_dhcp_state_get_events(state: *mut libc::c_void, tx_id: libc::uint64_t) -> *mut core::AppLayerDecoderEvents { let state = cast_pointer!(state, DHCPState); match state.get_tx(tx_id) { S...
tx: *mut libc::c_void, logged: libc::uint32_t) { let tx = cast_pointer!(tx, DHCPTransaction); tx.logged.set(logged); }
random_line_split
serializers.py
from rest_framework import relations, serializers import amo import mkt.carriers import mkt.regions from addons.models import Category from mkt.api.fields import SplitField, TranslationSerializerField from mkt.api.serializers import URLSerializerMixin from mkt.collections.serializers import (CollectionSerializer, Slug...
return
if getattr(obj, item_type): return item_type
conditional_block
serializers.py
from rest_framework import relations, serializers import amo import mkt.carriers import mkt.regions from addons.models import Category from mkt.api.fields import SplitField, TranslationSerializerField from mkt.api.serializers import URLSerializerMixin from mkt.collections.serializers import (CollectionSerializer, Slug...
(self, attrs): """ Ensure that at least one object type is specified. """ item_changed = any(k for k in self.Meta.item_types if k in attrs.keys()) num_defined = sum(1 for item in self.Meta.item_types if attrs.get(item)) if item_changed and num_defined != 1: me...
validate
identifier_name
serializers.py
from rest_framework import relations, serializers import amo import mkt.carriers import mkt.regions from addons.models import Category from mkt.api.fields import SplitField, TranslationSerializerField
from mkt.api.serializers import URLSerializerMixin from mkt.collections.serializers import (CollectionSerializer, SlugChoiceField, SlugModelChoiceField) from mkt.submit.serializers import PreviewSerializer from mkt.webapps.api import AppSerializer from .models import FeedApp, F...
random_line_split
serializers.py
from rest_framework import relations, serializers import amo import mkt.carriers import mkt.regions from addons.models import Category from mkt.api.fields import SplitField, TranslationSerializerField from mkt.api.serializers import URLSerializerMixin from mkt.collections.serializers import (CollectionSerializer, Slug...
class FeedItemSerializer(URLSerializerMixin, serializers.ModelSerializer): carrier = SlugChoiceField(required=False, choices_dict=mkt.carriers.CARRIER_MAP) region = SlugChoiceField(required=False, choices_dict=mkt.regions.REGION_LOOKUP) category = SlugModelChoiceField(required=False, ...
app = SplitField(relations.PrimaryKeyRelatedField(required=True), AppSerializer()) description = TranslationSerializerField(required=False) preview = SplitField(relations.PrimaryKeyRelatedField(required=False), PreviewSerializer()) pullquote_attribution = Transl...
identifier_body
extern-call.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
{ let result = fact(10u); debug!("result = %?", result); assert_eq!(result, 3628800u); }
identifier_body
extern-call.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
else { fact(data - 1u) * data } } fn fact(n: uint) -> uint { unsafe { debug!("n = %?", n); rustrt::rust_dbg_call(cb, n) } } pub fn main() { let result = fact(10u); debug!("result = %?", result); assert_eq!(result, 3628800u); }
{ data }
conditional_block