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 |
|---|---|---|---|---|
notifications.page.ts | import { Component, OnDestroy } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';
import { take } from 'rxjs/operators';
import { AppSettings, Notification } from '../app-settings';
import { LoggingService, SpeechService } from '../services';
@Component({
templateUrl: 'notifications.pa... | speak(id: string) {
this.getMessage(id).then(message => {
this.speech.speak(message);
})
}
private getMessage(id) {
if (this.notifications[id] && this.notifications[id].message) {
return Promise.resolve(this.notifications[id].message);
} else {
return this.translate.get('notific... | random_line_split | |
notifications.page.ts | import { Component, OnDestroy } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';
import { take } from 'rxjs/operators';
import { AppSettings, Notification } from '../app-settings';
import { LoggingService, SpeechService } from '../services';
@Component({
templateUrl: 'notifications.pa... | else {
return this.translate.get('notifications.' + id).toPromise();
}
}
}
| {
return Promise.resolve(this.notifications[id].message);
} | conditional_block |
canvas.react.js | // Copyright (c) 2015 Uber Technologies, Inc.
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, ... |
_redraw() {
const pixelRatio = window.devicePixelRatio || 1;
const canvas = this.refs.overlay;
const ctx = canvas.getContext('2d');
ctx.save();
ctx.scale(pixelRatio, pixelRatio);
const mercator = ViewportMercator(this.props);
this.props.redraw({
width: this.props.width,
heigh... | {
this._redraw();
} | identifier_body |
canvas.react.js | // Copyright (c) 2015 Uber Technologies, Inc.
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, ... | () {
const pixelRatio = window.devicePixelRatio || 1;
return (
<canvas
ref="overlay"
width={ this.props.width * pixelRatio }
height={ this.props.height * pixelRatio }
style={ {
width: `${this.props.width}px`,
height: `${this.props.height}px`,
p... | render | identifier_name |
canvas.react.js | // Copyright (c) 2015 Uber Technologies, Inc.
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, ... | height: PropTypes.number.isRequired,
latitude: PropTypes.number.isRequired,
longitude: PropTypes.number.isRequired,
zoom: PropTypes.number.isRequired,
redraw: PropTypes.func.isRequired,
isDragging: PropTypes.bool.isRequired
};
componentDidMount() {
this._redraw();
}
componentDidUpd... | width: PropTypes.number.isRequired, | random_line_split |
router.rs | use regex::Regex;
use hyper::Method;
use hyper::server::Request;
use context::{Context, Params, ParamType};
type Handler = fn(Context) -> ::Response;
pub struct Router {
pub routes: Vec<Route>
}
impl Router {
pub fn new() -> Router {
Router {
routes: Vec::new()
}
}
pub fn... |
// Save url params while processing
let mut params = Params::new();
for (index, token) in self.tokenized_path.iter().enumerate() {
match token {
&PathToken::Str(ref s) => {
if *s != incoming_path[index] {
return None
... | {
return None;
} | conditional_block |
router.rs | use regex::Regex;
use hyper::Method;
use hyper::server::Request;
use context::{Context, Params, ParamType};
type Handler = fn(Context) -> ::Response;
pub struct Router {
pub routes: Vec<Route>
}
impl Router {
pub fn new() -> Router {
Router {
routes: Vec::new()
}
} | }
}
#[derive(Clone)]
pub struct Route {
pub method: Method,
pub path: RoutePath,
pub handler: Handler
}
impl Route {
pub fn new(method: Method, path: &str, handler: Handler) -> Route {
Route {
method: method,
path: RoutePath::new(path),
handler: handler
... |
pub fn get(&mut self, path: &str, handler: Handler) {
self.routes.push(
Route::new(Method::Get, path, handler)
); | random_line_split |
router.rs | use regex::Regex;
use hyper::Method;
use hyper::server::Request;
use context::{Context, Params, ParamType};
type Handler = fn(Context) -> ::Response;
pub struct Router {
pub routes: Vec<Route>
}
impl Router {
pub fn new() -> Router {
Router {
routes: Vec::new()
}
}
pub fn... | () {
let route = Route::new(Method::Get, "/monkeys", generic_handler);
let path = Uri::from_str("http://example.com/nomatch").unwrap();
let request: Request = Request::new(Method::Get, path);
assert!(route.matches_request(&request).is_none());
}
#[test]
fn route_should_match... | route_should_not_be_matched | identifier_name |
setup.js | /**
* Created by
* Pratish Shrestha <pratishshrestha@lftechnology.com>
* on 4/19/16.
*/
var jsdom = require('jsdom').jsdom;
var exposedProperties = ['window', 'navigator', 'document', 'localStorage'];
global.document = jsdom('');
global.window = document.defaultView;
global.localStorage = {getItem: ()=>{}, setIt... |
});
global.navigator = {
userAgent: 'node.js'
};
//for jQuery
global.jQuery = require('jquery');
global.$ = global.jQuery;
global.window.jQuery = global.jQuery;
global.window.$ = global.jQuery;
//for jQuery plugins
require('jquery-confirm');
require('../src/custom-ui/bootstrap-colorselector'); | {
exposedProperties.push(property);
global[property] = document.defaultView[property];
} | conditional_block |
setup.js | /**
* Created by
* Pratish Shrestha <pratishshrestha@lftechnology.com>
* on 4/19/16.
*/
var jsdom = require('jsdom').jsdom;
var exposedProperties = ['window', 'navigator', 'document', 'localStorage'];
global.document = jsdom('');
global.window = document.defaultView;
global.localStorage = {getItem: ()=>{}, setIt... | }
});
global.navigator = {
userAgent: 'node.js'
};
//for jQuery
global.jQuery = require('jquery');
global.$ = global.jQuery;
global.window.jQuery = global.jQuery;
global.window.$ = global.jQuery;
//for jQuery plugins
require('jquery-confirm');
require('../src/custom-ui/bootstrap-colorselector'); | if (typeof global[property] === 'undefined') {
exposedProperties.push(property);
global[property] = document.defaultView[property]; | random_line_split |
index.js | 'use strict';
var _ = require('underscore');
var express = require('express');
var router = express.Router();
var ObjectId = require('mongoose').Types.ObjectId;
var path = require('path');
/**
* @apiDefine group Group based access
* Resource access controlled by user's groups
*/
/**
* @apiDefine access Authentica... |
res.send(result);
});
}; | {
throw err;
} | conditional_block |
index.js | 'use strict';
var _ = require('underscore');
var express = require('express');
var router = express.Router();
var ObjectId = require('mongoose').Types.ObjectId;
var path = require('path');
/**
* @apiDefine group Group based access
* Resource access controlled by user's groups
*/
/**
* @apiDefine access Authentica... | });
}; | res.send(result); | random_line_split |
phamServer_InnoDB.py | _unit
def run(self):
self.listen()
class blastServlet(phamServlet, Subscriber, Thread):
def __init__(self, logging, c, server, database, opts):
Thread.__init__(self)
phamServlet.__init__(self, logging, c)
Subscriber.__init__(self)
self.c = db_conf.db_conf(username=opts['user'], password=opts['... | update_blast_db | identifier_name | |
phamServer_InnoDB.py | initializing the pynotify module"
except:
pass
return clustalw_work_unit
def run(self):
self.listen()
class blastServlet(phamServlet, Subscriber, Thread):
def __init__(self, logging, c, server, database, opts):
Thread.__init__(self)
phamServlet.__init__(self, logging, c)
Subscr... | j = self.servSel.servers.pop(0)
self._logger.log('...' + j.name)
self.daemon.disconnect(j) | conditional_block | |
phamServer_InnoDB.py | (__file__),"pixmaps/phamerator.png"))
n.show()
else:
pass
#print "there was a problem initializing the pynotify module"
except:
pass
return clustalw_work_unit
def run(self):
self.listen()
class blastServlet(phamServlet, Subscriber, Thread):
def __init__... | def shutdown(self):
self._logger.log('Disconnecting objects from the Pyro nameserver')
self.daemon.disconnect(self.servSel)
self._logger.log('...serverSelector')
for i in range(len(self.servSel.servers)): | random_line_split | |
phamServer_InnoDB.py | , --database=<database name>: specify the name of the database to access
-i, --instances=<number_of_instances>: number of server instances to run (default=1)
-l, --logging={True or False}: whether to print out debugging info (default is True)
-a, --alignment_type={blast or clustal... |
class serverSelector(Pyro.core.SynchronizedObjBase, errorHandler):
def __init__(self, daemon, logging, c, username, password, server, database, opts):
Pyro.core.SynchronizedObjBase.__init__(self)
self._logger = logger.logger(logging)
self.logging = logging
self.servers = []
self.setPyroDaemon(da... | self._logger = logger.logger(self.logging)
while 1:
self._logger.log('looking for stale clustalw alignments...')
self.c.execute("UPDATE gene SET clustalw_status = 'avail' WHERE clustalw_status = 'stale'")
self._logger.log('looking for pending alignments...')
self.c.execute("UPDATE gene SET c... | identifier_body |
DeployInitializer.tsx | import React from 'react';
import { Modal } from 'react-bootstrap';
import { Option } from 'react-select';
import { IPromise } from 'angular';
import { groupBy, sortBy } from 'lodash';
import { AccountTag } from 'core/account';
import { Application } from 'core/application';
import { IServerGroup } from 'core/domain';... |
private buildCommandFromTemplate(serverGroup: IServerGroup): IPromise<any> {
const { application, cloudProvider } = this.props;
const commandBuilder: any = ReactInjector.providerServiceDelegate.getDelegate(
cloudProvider,
'serverGroup.commandBuilder',
);
return ServerGroupReader.getServ... | {
const { viewState } = command;
const baseCommand = this.props.command;
viewState.disableImageSelection = true;
viewState.showImageSourceSelector = true;
viewState.disableStrategySelection = baseCommand.viewState.disableStrategySelection || false;
viewState.expectedArtifacts = baseCommand.viewS... | identifier_body |
DeployInitializer.tsx | import React from 'react';
import { Modal } from 'react-bootstrap';
import { Option } from 'react-select';
import { IPromise } from 'angular';
import { groupBy, sortBy } from 'lodash';
import { AccountTag } from 'core/account';
import { Application } from 'core/application';
import { IServerGroup } from 'core/domain';... |
selectedTemplate = this.noTemplate;
const serverGroups: IServerGroup[] = props.application
.getDataSource('serverGroups')
.data.filter((s: IServerGroup) => s.cloudProvider === props.cloudProvider && s.category === 'serverGroup');
const grouped = groupBy(serverGroups, serverGroup =>
[se... | {
templates.push(this.noTemplate);
} | conditional_block |
DeployInitializer.tsx | import React from 'react';
import { Modal } from 'react-bootstrap';
import { Option } from 'react-select';
import { IPromise } from 'angular';
import { groupBy, sortBy } from 'lodash';
import { AccountTag } from 'core/account';
import { Application } from 'core/application';
import { IServerGroup } from 'core/domain';... | } | }; | random_line_split |
DeployInitializer.tsx | import React from 'react';
import { Modal } from 'react-bootstrap';
import { Option } from 'react-select';
import { IPromise } from 'angular';
import { groupBy, sortBy } from 'lodash';
import { AccountTag } from 'core/account';
import { Application } from 'core/application';
import { IServerGroup } from 'core/domain';... | (props: IDeployInitializerProps) {
super(props);
const templates: IDeployTemplate[] = [];
let selectedTemplate: IDeployTemplate;
const { viewState } = props.command;
if (!viewState.disableNoTemplateSelection) {
templates.push(this.noTemplate);
}
selectedTemplate = this.noTemplate;
... | constructor | identifier_name |
glyph-image.module.ts | // 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
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in ... |
@NgModule({
imports: [
CommonModule,
TranslateModule
],
declarations: [
GlyphImageComponent,
],
exports: [
GlyphImageComponent,
],
})
export class GlyphImageModule {} | import { GlyphImageComponent } from './glyph-image.component';
import { TranslateModule } from '@ngx-translate/core'; | random_line_split |
glyph-image.module.ts | // 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
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in ... | {}
| GlyphImageModule | identifier_name |
mod.rs | HttpVersion::Http11;
use self::listener::ListenerPool;
pub mod request;
pub mod response;
mod listener;
/// A server can listen on a TCP socket.
///
/// Once listening, it will create a `Request`/`Response` pair for each
/// incoming connection, and hand them to the provided handler.
#[derive(Debug)]
pub struct Ser... | {
let _ = self._guard.take().map(|g| g.join());
} | identifier_body | |
mod.rs | `std::io::Write` to allow writing the response body.
//!
//! ```no_run
//! use std::io;
//! use hyper::server::{Server, Request, Response};
//! use hyper::status::StatusCode;
//!
//! Server::http("0.0.0.0:0").unwrap().handle(|mut req: Request, mut res: Response| {
//! match req.method {
//! hyper::Post => ... |
}
self.handler.on_connection_end();
debug!("keep_alive loop ending for {}", addr);
}
fn set_timeouts(&self, s: &NetworkStream) -> io::Result<()> {
try!(self.set_read_timeout(s, self.timeouts.read));
self.set_write_timeout(s, self.timeouts.write)
}
#[cfg(not(f... | {
error!("set_read_timeout keep_alive {:?}", e);
break;
} | conditional_block |
mod.rs | implements `std::io::Write` to allow writing the response body.
//!
//! ```no_run
//! use std::io;
//! use hyper::server::{Server, Request, Response};
//! use hyper::status::StatusCode;
//!
//! Server::http("0.0.0.0:0").unwrap().handle(|mut req: Request, mut res: Response| {
//! match req.method {
//! hype... | (&mut self, timeout: Duration) {
self.timeouts.keep_alive = Some(timeout);
}
#[cfg(feature = "timeouts")]
pub fn set_read_timeout(&mut self, dur: Option<Duration>) {
self.timeouts.read = dur;
}
#[cfg(feature = "timeouts")]
pub fn set_write_timeout(&mut self, dur: Option<Duratio... | keep_alive | identifier_name |
mod.rs | implements `std::io::Write` to allow writing the response body.
//!
//! ```no_run
//! use std::io;
//! use hyper::server::{Server, Request, Response};
//! use hyper::status::StatusCode;
//!
//! Server::http("0.0.0.0:0").unwrap().handle(|mut req: Request, mut res: Response| {
//! match req.method {
//! hype... | use method::Method;
use net::{NetworkListener, NetworkStream, HttpListener, HttpsListener, Ssl};
use status::StatusCode;
use uri::RequestUri;
use version::HttpVersion::Http11;
use self::listener::ListenerPool;
pub mod request;
pub mod response;
mod listener;
/// A server can listen on a TCP socket.
///
/// Once lis... | random_line_split | |
cli-spinner.js | const readline = require('readline');
const Spinner = function (text = '%s') {
if ('string' == typeof text) {
text = { text };
}
this._text = text.text || '';
this._list = text.spinners || function (
spin = (t) => ['|', '/', '-', '\\'][t % 4], list = []
) {
for (let n = 0; n ... | index = ++index % this._list.length;
}, this._second);
};
Spinner.prototype.stop = function (clear) {
clearInterval(this._id);
this._id = undefined;
clear && this.clear();
};
Spinner.prototype.clear = function () {
readline.clearLine(this._output, 0);
readline.cursorTo(this._output, 0);
... | ? this._text.replace('%s', this._list[index])
: this._list[index] + ' ' + this._text); | random_line_split |
cli-spinner.js | const readline = require('readline');
const Spinner = function (text = '%s') {
if ('string' == typeof text) |
this._text = text.text || '';
this._list = text.spinners || function (
spin = (t) => ['|', '/', '-', '\\'][t % 4], list = []
) {
for (let n = 0; n < 19; n++) list.push(
`[[37m${"█".repeat(n)}[30m${".".repeat(18 - n)}[37m] ${spin(n)}`
);
for (let n = 19; n < 36... | {
text = { text };
} | conditional_block |
paths.rs | //! Path manipulation utilities
use std::env;
use std::ffi::{OsStr, OsString};
use std::fs::File;
use std::fs::OpenOptions;
use std::io::prelude::*;
use std::path::{Path, PathBuf, Component};
use util::{human, internal, CraftResult, ChainError};
pub fn join_paths<T: AsRef<OsStr>>(paths: &[T], env: &str) -> CraftResul... |
Component::ParentDir => {
ret.pop();
}
Component::Normal(c) => {
ret.push(c);
}
}
}
ret
}
pub fn without_prefix<'a>(a: &'a Path, b: &'a Path) -> Option<&'a Path> {
let mut a = a.components();
let mut b = b.componen... | {} | conditional_block |
paths.rs | //! Path manipulation utilities
use std::env;
use std::ffi::{OsStr, OsString};
use std::fs::File;
use std::fs::OpenOptions;
use std::io::prelude::*;
use std::path::{Path, PathBuf, Component};
use util::{human, internal, CraftResult, ChainError};
pub fn join_paths<T: AsRef<OsStr>>(paths: &[T], env: &str) -> CraftResul... | }
}
pub fn normalize_path(path: &Path) -> PathBuf {
let mut components = path.components().peekable();
let mut ret = if let Some(c @ Component::Prefix(..)) = components.peek()
.cloned() {
components.next();
PathBuf::from(c.as_os_str())
} else {
PathBuf::new()
};
... | random_line_split | |
paths.rs | //! Path manipulation utilities
use std::env;
use std::ffi::{OsStr, OsString};
use std::fs::File;
use std::fs::OpenOptions;
use std::io::prelude::*;
use std::path::{Path, PathBuf, Component};
use util::{human, internal, CraftResult, ChainError};
pub fn join_paths<T: AsRef<OsStr>>(paths: &[T], env: &str) -> CraftResul... | (path: &Path) -> CraftResult<&[u8]> {
match path.as_os_str().to_str() {
Some(s) => Ok(s.as_bytes()),
None => Err(human(format!("invalid non-unicode path: {}", path.display()))),
}
}
#[cfg(unix)]
pub fn bytes2path(bytes: &[u8]) -> CraftResult<PathBuf> {
use std::os::unix::prelude::*;
use... | path2bytes | identifier_name |
paths.rs | //! Path manipulation utilities
use std::env;
use std::ffi::{OsStr, OsString};
use std::fs::File;
use std::fs::OpenOptions;
use std::io::prelude::*;
use std::path::{Path, PathBuf, Component};
use util::{human, internal, CraftResult, ChainError};
pub fn join_paths<T: AsRef<OsStr>>(paths: &[T], env: &str) -> CraftResul... |
pub fn read_bytes(path: &Path) -> CraftResult<Vec<u8>> {
(|| -> CraftResult<_> {
let mut ret = Vec::new();
let mut f = File::open(path)?;
f.read_to_end(&mut ret)?;
Ok(ret)
})()
.map_err(human)
.chain_error(|| human(format!("failed to read `{}... | {
(|| -> CraftResult<_> {
let mut ret = String::new();
let mut f = File::open(path)?;
f.read_to_string(&mut ret)?;
Ok(ret)
})()
.map_err(human)
.chain_error(|| human(format!("failed to read `{}`", path.display())))
} | identifier_body |
PakFile.ts | /// <reference path="../../Common/String.ts"/>
///<reference path="../../Serialization/BinaryFileReader.ts"/>
module Yaqe.Game.Quake
{
import BinaryFileReader = Serialization.BinaryFileReader;
let fs = require('fs');
export class PakFile
{
private fileReader: BinaryFileReader;
private ... | (name: string, offset: number, size: number) {
this.name = name;
this.offset = offset;
this.size = size;
}
}
}
| constructor | identifier_name |
PakFile.ts | /// <reference path="../../Common/String.ts"/>
///<reference path="../../Serialization/BinaryFileReader.ts"/>
module Yaqe.Game.Quake
{
import BinaryFileReader = Serialization.BinaryFileReader;
let fs = require('fs');
export class PakFile
{
private fileReader: BinaryFileReader;
private ... | } | this.offset = offset;
this.size = size;
}
} | random_line_split |
PakFile.ts | /// <reference path="../../Common/String.ts"/>
///<reference path="../../Serialization/BinaryFileReader.ts"/>
module Yaqe.Game.Quake
{
import BinaryFileReader = Serialization.BinaryFileReader;
let fs = require('fs');
export class PakFile
{
private fileReader: BinaryFileReader;
private ... |
}
}
| {
this.name = name;
this.offset = offset;
this.size = size;
} | identifier_body |
PakFile.ts | /// <reference path="../../Common/String.ts"/>
///<reference path="../../Serialization/BinaryFileReader.ts"/>
module Yaqe.Game.Quake
{
import BinaryFileReader = Serialization.BinaryFileReader;
let fs = require('fs');
export class PakFile
{
private fileReader: BinaryFileReader;
private ... |
}
}
/**
* A pak file entry.
*/
export class PakFileEntry
{
name: string;
offset: number;
size: number;
constructor(name: string, offset: number, size: number) {
this.name = name;
this.offset = offset;
this.size = si... | {
let name = fileReader.readFixedNullTerminatedString(56);
let offset = fileReader.readUInt32();
let size = fileReader.readUInt32();
fileEntries.push(new PakFileEntry(name, offset, size));
} | conditional_block |
AnimatedCluster.js | The views and conclusions contained in the software and documentation are those
* of the authors and should not be interpreted as representing official policies,
* either expressed or implied, of OpenLayers Contributors.
*/
/**
* @requires OpenLayers/Strategy/Cluster.js
*/
/**
* Class: OpenLayers.Strategy.Ani... | var featureBounds = feature.geometry.getBounds();
if(!screenBounds.intersectsBounds(featureBounds)) {
continue;
}
}
if(feature.geometry) {
... | {
if(resolution != this.resolution) {
this.zoomIn = (!this.resolution || ((resolution <= this.resolution)||(resolution > this.resolution)));
}
// Store previous data if we are changing zoom level
this.previousResolution = this.resolu... | conditional_block |
AnimatedCluster.js | the clusters are animated.
* Default is 20.
*/
animationDuration: 20,
/**
* Property: animationTween
* {OpenLayers.Tween} Animated panning tween object.
*/
animationTween: null,
/**
* Property: previousResolution
* {Float} The previous resolution of the map.... | * Animates the clusters changing its position. | random_line_split | |
renderer.py | from jinja2 import Environment, PackageLoader
class BaseRenderer(object):
"""
Base Renderer class
Renderers are used to generate a string
which represents the router configuration
"""
def __init__(self, backend):
self.config = backend.config
self.backend = backend
@proper... | (self):
"""
Renders configuration by using the jinja2 templating engine
"""
# get jinja2 template
template_name = '{0}.jinja2'.format(self.get_name())
template = self.template_env.get_template(template_name)
# render template and cleanup
context = getattr(... | render | identifier_name |
renderer.py | from jinja2 import Environment, PackageLoader
class BaseRenderer(object):
"""
Base Renderer class
Renderers are used to generate a string
which represents the router configuration
"""
def __init__(self, backend):
self.config = backend.config
self.backend = backend
@proper... | """
Renders configuration by using the jinja2 templating engine
"""
# get jinja2 template
template_name = '{0}.jinja2'.format(self.get_name())
template = self.template_env.get_template(template_name)
# render template and cleanup
context = getattr(self.backend, 'i... | identifier_body | |
renderer.py | from jinja2 import Environment, PackageLoader
class BaseRenderer(object):
"""
Base Renderer class
Renderers are used to generate a string
which represents the router configuration
"""
def __init__(self, backend):
self.config = backend.config
self.backend = backend
@proper... |
@property
def template_env(self):
return Environment(
loader=PackageLoader(self.env_path, 'templates'), trim_blocks=True
)
@classmethod
def get_name(cls):
"""
Returns the name of the render class without its prefix
"""
return str(cls.__name__... | random_line_split | |
test_sys.py | )
self.assertTrue(d[0] is sys._getframe())
def test_attributes(self):
self.assertIsInstance(sys.api_version, int)
self.assertIsInstance(sys.argv, list)
self.assertIn(sys.byteorder, ("little", "big"))
self.assertIsInstance(sys.builtin_module_names, tuple)
self.assertI... | h = self.header
vh = self.vheader
size = self.calcsize
gc_header_size = self.gc_headsize
# bool objects are not gc tracked
self.assertEqual(sys.getsizeof(True), size(vh) + self.longdigit)
# but lists are
self.assertEqual(sys.getsizeof([]), size(vh + 'PP') + gc_hea... | identifier_body | |
test_sys.py | .TESTFN)
def check_sizeof(self, o, size):
result = sys.getsizeof(o)
# add GC header size
if ((type(o) == type) and (o.__flags__ & self.TPFLAGS_HEAPTYPE) or\
((type(o) != type) and (type(o).__flags__ & self.TPFLAGS_HAVE_GC))):
size += self.gc_headsize
msg = 'wr... | newsize = newsize << 1 | conditional_block | |
test_sys.py | we do a quick
# probable primality test (doesn't exclude the possibility of
# a Carmichael number)
for x in range(1, 100):
self.assertEqual(
pow(x, sys.hash_info.modulus-1, sys.hash_info.modulus),
1,
"sys.hash_info.modulus {} is a non-... | check(iter(bytearray()), size(h + 'PP'))
# cell
def get_cell(): | random_line_split | |
test_sys.py | elif sys.platform == 'win32':
expected = 'mbcs'
else:
expected = None
self.check_fsencoding(fs_encoding, expected)
class SizeofTest(unittest.TestCase):
TPFLAGS_HAVE_GC = 1<<14
TPFLAGS_HEAPTYPE = 1<<9
def setUp(self):
self.c = len(struct.pack('c', b... | setx | identifier_name | |
test_bigaddrspace.py | from test import support
from test.support import bigaddrspacetest, MAX_Py_ssize_t
import unittest
import operator
import sys
class StrTest(unittest.TestCase):
@bigaddrspacetest
def | (self):
s1 = 'x' * MAX_Py_ssize_t
self.assertRaises(OverflowError, operator.add, s1, '?')
@bigaddrspacetest
def test_optimized_concat(self):
x = 'x' * MAX_Py_ssize_t
try:
x = x + '?' # this statement uses a fast path in ceval.c
except OverflowError:
... | test_concat | identifier_name |
test_bigaddrspace.py | from test import support
from test.support import bigaddrspacetest, MAX_Py_ssize_t
import unittest
import operator
import sys
class StrTest(unittest.TestCase):
@bigaddrspacetest
def test_concat(self):
s1 = 'x' * MAX_Py_ssize_t
self.assertRaises(OverflowError, operator.add, s1, '?')
@big... | test_main() |
if __name__ == '__main__':
if len(sys.argv) > 1:
support.set_memlimit(sys.argv[1]) | random_line_split |
test_bigaddrspace.py | from test import support
from test.support import bigaddrspacetest, MAX_Py_ssize_t
import unittest
import operator
import sys
class StrTest(unittest.TestCase):
@bigaddrspacetest
def test_concat(self):
|
@bigaddrspacetest
def test_optimized_concat(self):
x = 'x' * MAX_Py_ssize_t
try:
x = x + '?' # this statement uses a fast path in ceval.c
except OverflowError:
pass
else:
self.fail("should have raised OverflowError")
try:
... | s1 = 'x' * MAX_Py_ssize_t
self.assertRaises(OverflowError, operator.add, s1, '?') | identifier_body |
test_bigaddrspace.py | from test import support
from test.support import bigaddrspacetest, MAX_Py_ssize_t
import unittest
import operator
import sys
class StrTest(unittest.TestCase):
@bigaddrspacetest
def test_concat(self):
s1 = 'x' * MAX_Py_ssize_t
self.assertRaises(OverflowError, operator.add, s1, '?')
@big... |
self.assertEquals(len(x), MAX_Py_ssize_t)
### the following test is pending a patch
# (http://mail.python.org/pipermail/python-dev/2006-July/067774.html)
#@bigaddrspacetest
#def test_repeat(self):
# self.assertRaises(OverflowError, operator.mul, 'x', MAX_Py_ssize_t + 1)
def test_mai... | self.fail("should have raised OverflowError") | conditional_block |
network.rs |
&& self.runtime.last_getdata_send_time + self.runtime.timeout < get_epoch_time_secs()
{
warn!("Timed out waiting for block data. Killing connection.");
return Err(btc_error::TimedOut);
}
if self.runtime.last_getheaders_send_time > 0
&& self.runt... | {
assert!(block_hashes.len() > 0);
let getdata_invs = block_hashes
.iter()
.map(|h| btc_message_blockdata::Inventory {
inv_type: btc_message_blockdata::InvType::Block,
hash: h.clone(),
})
.collect();
let getdata = b... | identifier_body | |
network.rs | deps::bitcoin::network::message_network as btc_message_network;
use deps::bitcoin::network::serialize as btc_serialize;
use deps::bitcoin::network::serialize::{RawDecoder, RawEncoder};
use deps::bitcoin::util::hash::Sha256dHash;
use burnchains::bitcoin::indexer::{network_id_to_bytes, BitcoinIndexer};
use burnchains:... |
btc_message::NetworkMessage::Verack => {
return self.handle_verack(message).and_then(|_r| Ok(true));
}
btc_message::NetworkMessage::Ping(..) => {
return self.handle_ping(message).and_then(|_r| Ok(true));
}
btc_message::NetworkM... | {
return self.handle_version(message).and_then(|_r| Ok(true));
} | conditional_block |
network.rs | use deps::bitcoin::network::message_network as btc_message_network;
use deps::bitcoin::network::serialize as btc_serialize;
use deps::bitcoin::network::serialize::{RawDecoder, RawEncoder};
use deps::bitcoin::util::hash::Sha256dHash;
use burnchains::bitcoin::indexer::{network_id_to_bytes, BitcoinIndexer};
use burnchai... | // propagate other network error
warn!(
"Failed to handshake with {}:{}: {:?}",
&self.config.peer_host, self.config.peer_port, &e
);
return Err(... | backoff = 2.0 * backoff + (backoff * rng.gen_range(0.0, 1.0));
}
Err(e) => { | random_line_split |
network.rs | use deps::bitcoin::network::message_network as btc_message_network;
use deps::bitcoin::network::serialize as btc_serialize;
use deps::bitcoin::network::serialize::{RawDecoder, RawEncoder};
use deps::bitcoin::util::hash::Sha256dHash;
use burnchains::bitcoin::indexer::{network_id_to_bytes, BitcoinIndexer};
use burnchai... | (&mut self) -> Result<SocketAddr, btc_error> {
self.with_socket(|ref mut sock| sock.peer_addr().map_err(btc_error::Io))
}
/// Handle and consume message we received, if we can.
/// Returns UnhandledMessage if we can't handle the given message.
pub fn handle_message<T: BitcoinMessageHandler>(
... | get_remote_sockaddr | identifier_name |
database.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import pymongo
from pymongo import MongoClient
from pymongo import errors
import re
class Database(object):
'''Database creation'''
def __init__(self, database_name):
self.client = MongoClient('mongodb://localhost,localhost:27017')
self.db_name = database_name
sel... | # backlist.append([o["url"], "backlink"])
# return
# def export_outlinks(self):
# '''Output url : outlink'''
# print "source; target"
# for n in self.db.results.find():
# for o in n["outlinks"]:
# if o is not None:
# print n['url']+";"+o
# else:
# print n["url"]+";None"
# return
... | # outlist.append([o["url"], "backlink"])
# for n in self.db.results.find():
# if n != []:
# for o in n["backlinks"]:
# if o is not None: | random_line_split |
database.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import pymongo
from pymongo import MongoClient
from pymongo import errors
import re
class Database(object):
| def show_dbs(self):
return self.client.database_names()
def create_coll(self, coll_name):
setattr(self, str(coll_name), self.db[str(coll_name)])
#print "coll : %s has been created in db:%s " %(self.__dict__[str(coll_name)], self.db_name)
return self.__dict__[str(coll_name)]
def create_colls(self, coll_name... | '''Database creation'''
def __init__(self, database_name):
self.client = MongoClient('mongodb://localhost,localhost:27017')
self.db_name = database_name
self.db = self.client[self.db_name]
#self.jobs = self.client[self.db_name].jobs
#self.results = self.db['results']
#self.queue = self.db['queue']
#sel... | identifier_body |
database.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import pymongo
from pymongo import MongoClient
from pymongo import errors
import re
class Database(object):
'''Database creation'''
def __init__(self, database_name):
self.client = MongoClient('mongodb://localhost,localhost:27017')
self.db_name = database_name
sel... |
else:
print "Unknown Type"
return False
def drop_all_dbs():
'''remove EVERY SINGLE MONGO DATABASE'''
for n in self.show_dbs():
self.use_db(n)
self.drop("database", n)
def stats(self):
'''Output the current stats of database in Terminal'''
title = "===STATS===\n"
name ="Stored results in Mon... | return self.client.drop_database(str(name)) | conditional_block |
database.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import pymongo
from pymongo import MongoClient
from pymongo import errors
import re
class Database(object):
'''Database creation'''
def __init__(self, database_name):
self.client = MongoClient('mongodb://localhost,localhost:27017')
self.db_name = database_name
sel... | (self):
return self.client.database_names()
def create_coll(self, coll_name):
setattr(self, str(coll_name), self.db[str(coll_name)])
#print "coll : %s has been created in db:%s " %(self.__dict__[str(coll_name)], self.db_name)
return self.__dict__[str(coll_name)]
def create_colls(self, coll_names=["results",... | show_dbs | identifier_name |
macros.rs | #[macro_export]
macro_rules! implement_lua_push {
($ty:ty, $cb:expr) => {
impl<L> $crate::Push<L> for Sound where L: $crate::AsMutLua {
fn push_to_lua(self, lua: L) -> $crate::PushGuard<L> {
$crate::userdata::push_userdata(self, lua, $cb)
}
}
};
}
#[macro... | unsafe { ::std::mem::transmute($crate::userdata::read_userdata::<$ty>(lua, index)) }
}
}
};
} | random_line_split | |
test_unicode_shift_jis.py | ###############################################################################
#
# Tests for XlsxWriter.
#
# SPDX-License-Identifier: BSD-2-Clause
# Copyright (c), 2013-2022, John McNamara, jmcnamara@cpan.org
#
from ..excel_comparison_test import ExcelComparisonTest
from ...workbook import Workbook
class TestCompar... | (self):
self.set_filename('unicode_shift_jis.xlsx')
self.set_text_file('unicode_shift_jis.txt')
def test_create_file(self):
"""Test example file converting Unicode text."""
# Open the input file with the correct encoding.
textfile = open(self.txt_filename, mode='r', encodi... | setUp | identifier_name |
test_unicode_shift_jis.py | ###############################################################################
#
# Tests for XlsxWriter.
#
# SPDX-License-Identifier: BSD-2-Clause
# Copyright (c), 2013-2022, John McNamara, jmcnamara@cpan.org
#
from ..excel_comparison_test import ExcelComparisonTest
from ...workbook import Workbook
class TestCompar... |
def test_create_file(self):
"""Test example file converting Unicode text."""
# Open the input file with the correct encoding.
textfile = open(self.txt_filename, mode='r', encoding='shift_jis')
# Create an new Excel file and convert the text data.
workbook = Workbook(self.... | self.set_filename('unicode_shift_jis.xlsx')
self.set_text_file('unicode_shift_jis.txt') | identifier_body |
test_unicode_shift_jis.py | ###############################################################################
#
# Tests for XlsxWriter.
#
# SPDX-License-Identifier: BSD-2-Clause
# Copyright (c), 2013-2022, John McNamara, jmcnamara@cpan.org
#
from ..excel_comparison_test import ExcelComparisonTest
from ...workbook import Workbook
class TestCompar... |
workbook.close()
textfile.close()
self.assertExcelEqual()
| if line.startswith('#'):
continue
# Write any other lines to the worksheet.
worksheet.write(row, col, line.rstrip("\n"))
row += 1 | conditional_block |
test_unicode_shift_jis.py | ###############################################################################
#
# Tests for XlsxWriter.
#
# SPDX-License-Identifier: BSD-2-Clause
# Copyright (c), 2013-2022, John McNamara, jmcnamara@cpan.org
#
from ..excel_comparison_test import ExcelComparisonTest
from ...workbook import Workbook
class TestCompar... |
def test_create_file(self):
"""Test example file converting Unicode text."""
# Open the input file with the correct encoding.
textfile = open(self.txt_filename, mode='r', encoding='shift_jis')
# Create an new Excel file and convert the text data.
workbook = Workbook(self.g... |
def setUp(self):
self.set_filename('unicode_shift_jis.xlsx')
self.set_text_file('unicode_shift_jis.txt') | random_line_split |
TaskAltSharp.js | "use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
| Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon"));
var _jsxRuntime = require("react/jsx-runtime");
var _default = (0, _createSvgIcon.default)( /*#__PURE__*/(0, _jsxRuntime.jsx)("path", {
d: "M22 5... | random_line_split | |
p137.rs | //! [Problem 137](https://projecteuler.net/problem=137) solver.
//!
//! ```math
//! A_F(x) = x F_1 + x^2 F_2 + x^3 F_3 + \dots
//! x A_F(x) = x^2 F_1 + x^3 F_2 + x^4 F_3 + \dots
//! x^2 A_F(x) = x^3 F_1 + x^4 F_2 + x^5 F_3 + \dots
//! (1 - x - x^2) A_F(x) = x F_1 + x^2 (F_2 - F_1) + x^3 (F_3 - F_2 - F_1) + \dots
... | identifier_body | ||
p137.rs | //! [Problem 137](https://projecteuler.net/problem=137) solver.
//!
//! ```math
//! A_F(x) = x F_1 + x^2 F_2 + x^3 F_3 + \dots
//! x A_F(x) = x^2 F_1 + x^3 F_2 + x^4 F_3 + \dots
//! x^2 A_F(x) = x^3 F_1 + x^4 F_2 + x^5 F_3 + \dots
//! (1 - x - x^2) A_F(x) = x F_1 + x^2 (F_2 - F_1) + x^3 (F_3 - F_2 - F_1) + \dots
... | 9));
}
}
| conditional_block | |
p137.rs | //! [Problem 137](https://projecteuler.net/problem=137) solver.
//!
//! ```math
//! A_F(x) = x F_1 + x^2 F_2 + x^3 F_3 + \dots
//! x A_F(x) = x^2 F_1 + x^3 F_2 + x^4 F_3 + \dots
//! x^2 A_F(x) = x^3 F_1 + x^4 F_2 + x^5 F_3 + \dots
//! (1 - x - x^2) A_F(x) = x F_1 + x^2 (F_2 - F_1) + x^3 (F_3 - F_2 - F_1) + \dots
... | } else {
None
}
}).nth(i).unwrap().0
}
fn solve() -> String {
compute(14).to_string()
}
problem!("1120149658760", solve);
#[cfg(test)]
mod tests {
#[test]
fn tenth_sol() {
assert_eq!(74049690, super::compute(9));
}
} | }).filter_map(|(p, q)| {
if p % 5 == 1 {
Some((p / 5, q)) | random_line_split |
p137.rs | //! [Problem 137](https://projecteuler.net/problem=137) solver.
//!
//! ```math
//! A_F(x) = x F_1 + x^2 F_2 + x^3 F_3 + \dots
//! x A_F(x) = x^2 F_1 + x^3 F_2 + x^4 F_3 + \dots
//! x^2 A_F(x) = x^3 F_1 + x^4 F_2 + x^5 F_3 + \dots
//! (1 - x - x^2) A_F(x) = x F_1 + x^2 (F_2 - F_1) + x^3 (F_3 - F_2 - F_1) + \dots
... | identifier_name | ||
esri.ts | /// <reference path="openlayers.d.ts" />
import Q = require("q");
export = esri;
module esri {
export class Request {
/**
* Perform a JSONP style get request.
*/
static GET(url:string, params:any): Q.Promise<any> {
var deferred = Q.defer<any>();
var ca... | rl: String) {
this.url = url;
this.outSpatialReference = 4326;
}
/**
* Find address candidates for the input addresses.
*/
addressToLocations(params: any): Q.Promise<esri.task.AddressCandidate[]> {
params = pa... | nstructor(u | identifier_name |
esri.ts | /// <reference path="openlayers.d.ts" />
import Q = require("q");
export = esri;
module esri {
export class Request {
/**
* Perform a JSONP style get request.
*/
static GET(url:string, params:any): Q.Promise<any> {
var deferred = Q.defer<any>();
var ca... | }
}
} | params = params.address;
params.outSR = this.outSpatialReference;
params.f = "json";
return esri.Request.GET(this.url + "/findAddressCandidates", params).then(function (response: any) {
var spatialReference = response.spatialReference.w... | identifier_body |
esri.ts | /// <reference path="openlayers.d.ts" />
import Q = require("q");
export = esri;
module esri {
export class Request {
/**
* Perform a JSONP style get request.
*/
static GET(url:string, params:any): Q.Promise<any> {
var deferred = Q.defer<any>();
var ca... | */
attributes: Object;
/**
* X- and y-coordinate of the candidate.
*/
location: OpenLayers.Geometry.Point;
/**
* Numeric score between 0 and 100 for geocode candidates. A candidate with a score of 100 means a perfect mat... | address: Object;
/**
* Name value pairs of field name and field value as defined in outFields | random_line_split |
font.js | // Copyright 2007 The Closure Library 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
//
// Unless requ... | // TODO(arv): Is this in pixels or drawing units based on the coord size?
/**
* The name of the font family to use, can be a comma separated string.
* @type {string}
*/
this.family = family;
};
/**
* Indication if text should be bolded
* @type {boolean}
*/
goog.graphics.Font.prototype.bold = false;... | this.size = size; | random_line_split |
websocket.ts | /// <reference path="..\..\jriappTS\jriapp.d.ts"/>
/// <reference path="common.ts"/>
namespace RIAPP.WEBSOCK {
//websocket client
'use strict';
var global = RIAPP.global, utils = global.utils;
export class WebSocketsVM extends BaseObject {
private _ws: WebSocket;
private _clientID: s... | return this._deffered.promise();
}
close() {
clearTimeout(this._timeOut);
this._timeOut = null;
if (!!this._deffered) {
this._deffered.reject("Websocket closed");
}
this._deffered = null;
if (!!this._ws)... | this._ws = new WebSocket(self.url);
this._ws.onopen = function (e) { self._onWsOpen(e); };
this._ws.onclose = function (e) { self._onWsClose(e); };
this._ws.onmessage = function (e) { self._onMsg(e); };
this._ws.onerror = function (e) { sel... | conditional_block |
websocket.ts | /// <reference path="..\..\jriappTS\jriapp.d.ts"/>
/// <reference path="common.ts"/>
namespace RIAPP.WEBSOCK {
//websocket client
'use strict';
var global = RIAPP.global, utils = global.utils;
export class WebSocketsVM extends BaseObject {
private _ws: WebSocket;
private _clientID: s... | vent) {
this.close();
this.raiseEvent('error', {});
var err = new Error("" + event);
this.handleError(err, this);
}
protected _onMsg(event) {
var data = JSON.parse(event.data);
if (data.Tag == "connect") {
clearTimeo... | nWsError(e | identifier_name |
websocket.ts | /// <reference path="..\..\jriappTS\jriapp.d.ts"/>
/// <reference path="common.ts"/>
namespace RIAPP.WEBSOCK {
//websocket client
'use strict';
var global = RIAPP.global, utils = global.utils;
export class WebSocketsVM extends BaseObject {
private _ws: WebSocket;
private _clientID: s... | self.close();
} finally {
super.destroy();
}
}
get ws() { return this._ws; }
get openWsCommand() { return this._openWsCommand; }
get url() { return this._url; }
set url(v) { this._url = v; }
get clientID() { return t... | try { | random_line_split |
websocket.ts | /// <reference path="..\..\jriappTS\jriapp.d.ts"/>
/// <reference path="common.ts"/>
namespace RIAPP.WEBSOCK {
//websocket client
'use strict';
var global = RIAPP.global, utils = global.utils;
export class WebSocketsVM extends BaseObject {
private _ws: WebSocket;
private _clientID: s... | } | return WEBSOCK;
};
| identifier_body |
time.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! Specified time values.
use cssparser::{Parser, Token};
use parser::{ParserContext, Parse};
use std::ascii::As... | was_calc: true,
}
}
fn parse_with_clamping_mode<'i, 't>(
context: &ParserContext,
input: &mut Parser<'i, 't>,
clamping_mode: AllowedNumericType
) -> Result<Self, ParseError<'i>> {
use style_traits::ParsingMode;
let location = input.current_source... | pub fn from_calc(seconds: CSSFloat) -> Self {
Time {
seconds: seconds,
unit: TimeUnit::Second, | random_line_split |
time.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! Specified time values.
use cssparser::{Parser, Token};
use parser::{ParserContext, Parse};
use std::ascii::As... | i, 't>(
context: &ParserContext,
input: &mut Parser<'i, 't>,
clamping_mode: AllowedNumericType
) -> Result<Self, ParseError<'i>> {
use style_traits::ParsingMode;
let location = input.current_source_location();
// FIXME: remove early returns when lifetimes are non-lex... | rse_with_clamping_mode<' | identifier_name |
time.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! Specified time values.
use cssparser::{Parser, Token};
use parser::{ParserContext, Parse};
use std::ascii::As... | fn from_computed_value(computed: &Self::ComputedValue) -> Self {
Time {
seconds: computed.seconds(),
unit: TimeUnit::Second,
was_calc: false,
}
}
}
impl Parse for Time {
fn parse<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>) -> Result<Self,... | ComputedTime::from_seconds(self.seconds())
}
| identifier_body |
module.rs | use std::fmt;
use libc;
use llvm_sys::prelude::*;
use llvm_sys::core as llvm;
use super::*;
use std::path::Path;
error_chain! {
errors {
ModulePrintFile(t: String) {
description("Error while printing module to file")
display("Error while printing module to file: '{}'", t)
... | (&mut self, name: &str) -> Option<Function> {
let c_name = CString::new(name).unwrap();
let res = unsafe {
llvm::LLVMGetNamedFunction(self.ptr, c_name.as_ptr())
};
if res.is_null() {
None
} else {
Some(Function::from_value_ref(res))
}
... | get_named_function | identifier_name |
module.rs | use std::fmt;
use libc;
use llvm_sys::prelude::*;
use llvm_sys::core as llvm;
use super::*;
use std::path::Path;
error_chain! {
errors {
ModulePrintFile(t: String) {
description("Error while printing module to file")
display("Error while printing module to file: '{}'", t)
... | len + 1,
len + 1
);
write!(f, "{}", s)
}
}
} | unsafe {
let c_str = llvm::LLVMPrintModuleToString(self.ptr);
let len = libc::strlen(c_str);
let s = String::from_raw_parts(
c_str as *mut u8, | random_line_split |
module.rs | use std::fmt;
use libc;
use llvm_sys::prelude::*;
use llvm_sys::core as llvm;
use super::*;
use std::path::Path;
error_chain! {
errors {
ModulePrintFile(t: String) {
description("Error while printing module to file")
display("Error while printing module to file: '{}'", t)
... |
pub fn get_named_function(&mut self, name: &str) -> Option<Function> {
let c_name = CString::new(name).unwrap();
let res = unsafe {
llvm::LLVMGetNamedFunction(self.ptr, c_name.as_ptr())
};
if res.is_null() {
None
} else {
Some(Function::... | {
let c_name = CString::new(name).unwrap();
let p = unsafe {
llvm::LLVMAddFunction(self.ptr, c_name.as_ptr(), func_ty.into())
};
Function {
ptr: p
}
} | identifier_body |
module.rs | use std::fmt;
use libc;
use llvm_sys::prelude::*;
use llvm_sys::core as llvm;
use super::*;
use std::path::Path;
error_chain! {
errors {
ModulePrintFile(t: String) {
description("Error while printing module to file")
display("Error while printing module to file: '{}'", t)
... | else {
Err(ErrorKind::ModulePrintFile(c_str_to_str!(em as *const i8).into()).into())
}
}
}
}
impl fmt::Display for Module {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
unsafe {
let c_str = llvm::LLVMPrintModuleToString(self.ptr);
l... | { // no error message was set
Ok(())
} | conditional_block |
unary.rs | //! Module implementing evaluation of unary operator AST nodes.
use eval::{self, api, Eval, Context, Value};
use parse::ast::UnaryOpNode;
impl Eval for UnaryOpNode {
fn eval(&self, context: &mut Context) -> eval::Result {
let arg = try!(self.arg.eval(context));
match &self.op[..] {
"+... | (arg: Value) -> eval::Result {
eval1!(arg : Integer { -arg });
eval1!(arg : Float { -arg });
UnaryOpNode::err("-", &arg)
}
/// Evaluate the "!" operator for one value.
#[inline]
fn eval_bang(arg: Value) -> eval::Result {
let arg = try!(api::conv::bool(arg)).unwrap_bool()... | eval_minus | identifier_name |
unary.rs | //! Module implementing evaluation of unary operator AST nodes.
use eval::{self, api, Eval, Context, Value};
use parse::ast::UnaryOpNode;
impl Eval for UnaryOpNode {
fn eval(&self, context: &mut Context) -> eval::Result {
let arg = try!(self.arg.eval(context));
match &self.op[..] {
"+... |
}
impl UnaryOpNode {
/// Produce an error about invalid argument for an operator.
#[inline]
fn err(op: &str, arg: &Value) -> eval::Result {
Err(eval::Error::new(&format!(
"invalid argument for `{}` operator: `{:?}`", op, arg
)))
}
}
| {
let arg = try!(api::conv::bool(arg)).unwrap_bool();
Ok(Value::Boolean(!arg))
} | identifier_body |
unary.rs | //! Module implementing evaluation of unary operator AST nodes.
use eval::{self, api, Eval, Context, Value};
use parse::ast::UnaryOpNode;
impl Eval for UnaryOpNode {
fn eval(&self, context: &mut Context) -> eval::Result {
let arg = try!(self.arg.eval(context));
match &self.op[..] {
"+... | /// Evaluate the "+" operator for one value.
fn eval_plus(arg: Value) -> eval::Result {
eval1!(arg : Integer { arg });
eval1!(arg : Float { arg });
UnaryOpNode::err("+", &arg)
}
/// Evaluate the "-" operator for one value.
fn eval_minus(arg: Value) -> eval::Result {
... | }
}
}
impl UnaryOpNode { | random_line_split |
person.rs | use std::time;
use time::Tm;
use mre::model::{Model, Error};
// Create a class to act as our model. Unfortunately Rust's classes aren't
// finished yet, and are missing a couple features that would help clean up
// models. First, there's no way to mix in implementation of functions, so we
// need to duplicate some cod... |
}
// Create a new person model.
pub fn Person(es: elasticsearch::Client, name: ~str) -> Person {
// Create a person. We'll store the model in the ES index named
// "helloeveryone", under the type "person". We'd like ES to make the index
// for us, so we leave the id blank.
let mut person = Person {
... | {
self.model.delete()
} | identifier_body |
person.rs | use std::time;
use time::Tm;
use mre::model::{Model, Error};
// Create a class to act as our model. Unfortunately Rust's classes aren't
// finished yet, and are missing a couple features that would help clean up
// models. First, there's no way to mix in implementation of functions, so we
// need to duplicate some cod... |
fn create(&self) -> Result<(~str, uint), Error> {
self.model.create()
}
fn save(&self) -> Result<(~str, uint), Error> {
self.model.save()
}
fn delete(&self) {
self.model.delete()
}
}
// Create a new person model.
pub fn Person(es: elasticsearch::Client, name: ~str) ->... | random_line_split | |
person.rs | use std::time;
use time::Tm;
use mre::model::{Model, Error};
// Create a class to act as our model. Unfortunately Rust's classes aren't
// finished yet, and are missing a couple features that would help clean up
// models. First, there's no way to mix in implementation of functions, so we
// need to duplicate some cod... | (es: elasticsearch::Client) -> ~[Person] {
// This query can be a little complicated for those who have never used
// elasticsearch. All it says is that we want to fetch 50 documents on the
// index "helloeveryone" and the type "person", sorted by time.
do mre::model::search(es) |bld| {
bld
... | last_50 | identifier_name |
reflector.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use syntax::ext::base::ExtCtxt;
use syntax::codemap::Span;
use syntax::ptr::P;
use syntax::ast::{Item, MetaItem};
... | let impl_item = quote_item!(cx,
impl ::dom::bindings::utils::Reflectable for $struct_name {
fn reflector<'a>(&'a self) -> &'a ::dom::bindings::utils::Reflector {
self.$field_name.reflector()
}
... | {
if let ast::ItemStruct(ref def, _) = item.node {
let struct_name = item.ident;
// This path has to be hardcoded, unfortunately, since we can't resolve paths at expansion time
match def.fields.iter().find(|f| match_ty_unwrap(&*f.node.ty, &["dom", "bindings", "utils", "Reflector"]).is_some()... | identifier_body |
reflector.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use syntax::ext::base::ExtCtxt;
use syntax::codemap::Span;
use syntax::ptr::P;
use syntax::ast::{Item, MetaItem};
... | (cx: &mut ExtCtxt, span: Span, _: &MetaItem, item: &Item, push: |P<Item>|) {
if let ast::ItemStruct(ref def, _) = item.node {
let struct_name = item.ident;
// This path has to be hardcoded, unfortunately, since we can't resolve paths at expansion time
match def.fields.iter().find(|f| match_t... | expand_reflector | identifier_name |
reflector.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use syntax::ext::base::ExtCtxt;
use syntax::codemap::Span;
use syntax::ptr::P;
use syntax::ast::{Item, MetaItem};
... | }
}
);
impl_item.map(|it| push(it))
}
};
} else {
cx.span_err(span, "#[dom_struct] seems to have been applied to a non-struct");
}
} | self.$field_name.reflector() | random_line_split |
reflector.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use syntax::ext::base::ExtCtxt;
use syntax::codemap::Span;
use syntax::ptr::P;
use syntax::ast::{Item, MetaItem};
... | impl ::dom::bindings::utils::Reflectable for $struct_name {
fn reflector<'a>(&'a self) -> &'a ::dom::bindings::utils::Reflector {
self.$field_name.reflector()
}
}
);
impl_i... | {
let struct_name = item.ident;
// This path has to be hardcoded, unfortunately, since we can't resolve paths at expansion time
match def.fields.iter().find(|f| match_ty_unwrap(&*f.node.ty, &["dom", "bindings", "utils", "Reflector"]).is_some()) {
// If it has a field that is a Reflec... | conditional_block |
angle.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use glutin;
use glutin::{WindowBuilder, ContextBuilder, EventsLoop, Window, CreationError};
#[cfg(not(windows))]
... |
#[cfg(windows)]
pub fn with_window(
window_builder: WindowBuilder,
context_builder: ContextBuilder,
events_loop: &EventsLoop,
) -> Result<(Window, Self), CreationError> {
use glutin::os::windows::WindowExt;
// FIXME: &context_builder.pf_reqs https://github.com/tom... | {
Err(CreationError::PlatformSpecific("ANGLE rendering is only supported on Windows".into()))
} | identifier_body |
angle.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use glutin;
use glutin::{WindowBuilder, ContextBuilder, EventsLoop, Window, CreationError};
#[cfg(not(windows))]
... | (
_: WindowBuilder,
_: ContextBuilder,
_: &EventsLoop,
) -> Result<(Window, Self), CreationError> {
Err(CreationError::PlatformSpecific("ANGLE rendering is only supported on Windows".into()))
}
#[cfg(windows)]
pub fn with_window(
window_builder: WindowBuilder,
... | with_window | identifier_name |
angle.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use glutin;
use glutin::{WindowBuilder, ContextBuilder, EventsLoop, Window, CreationError};
#[cfg(not(windows))]
... | events_loop: &EventsLoop,
) -> Result<(Window, Self), CreationError> {
use glutin::os::windows::WindowExt;
// FIXME: &context_builder.pf_reqs https://github.com/tomaka/glutin/pull/1002
let pf_reqs = &glutin::PixelFormatRequirements::default();
let gl_attr = &context_builder... | pub fn with_window(
window_builder: WindowBuilder,
context_builder: ContextBuilder, | random_line_split |
body_movie_output.py | #This macro outputs 3D plots of the x,y,z co-ordinates of the particles. Main movie script
import sys
import matplotlib.pyplot as plt
import numpy as np
import glob
import math
pi = math.pi
from mpl_toolkits.mplot3d import Axes3D
import re
from subprocess import call
def natural_key(string_):
return [int(s) if s.... | (id,N_massive):
color = 'black'
if id == 0:
color = 'yellow'
elif id <= N_massive:
color = 'red'
return color
N_massive = int(raw_input("Number of massive bodies (including sun): ")) - 1
dir = 'movie_output/'
files = glob.glob(dir+'hybridbody*.txt')
files = sorted(files, key=natural_ke... | get_color | identifier_name |
body_movie_output.py | #This macro outputs 3D plots of the x,y,z co-ordinates of the particles. Main movie script
import sys
import matplotlib.pyplot as plt
import numpy as np
import glob
import math
pi = math.pi
from mpl_toolkits.mplot3d import Axes3D
import re
from subprocess import call
def natural_key(string_):
return [int(s) if s.... | color = get_color(int(line[1]),N_massive)
ax.scatter(float(line[2]),float(line[3]),float(line[4]),c=color, lw=0)
except:
if collision[i] == 0:
print 'particle',i,' had a collision'
collision[i] = 1
#plotting details - make it all look pwett... | for i in xrange(0,N_bodies):
try:
line = data[i][iteration].split(",") | random_line_split |
body_movie_output.py | #This macro outputs 3D plots of the x,y,z co-ordinates of the particles. Main movie script
import sys
import matplotlib.pyplot as plt
import numpy as np
import glob
import math
pi = math.pi
from mpl_toolkits.mplot3d import Axes3D
import re
from subprocess import call
def natural_key(string_):
return [int(s) if s.... |
#plotting details - make it all look pwetty.
ax.set_xlim([-limit,limit])
ax.set_ylim([-limit,limit])
ax.set_zlim([-limit/4,limit/4])
ax.view_init(elev = 90, azim=100) #both are in degrees. elev = 0 or 90 is what you want
output = 't='+line[0]
ax.set_title(output)
ax.set_xlabel('x')
... | print 'particle',i,' had a collision'
collision[i] = 1 | conditional_block |
body_movie_output.py | #This macro outputs 3D plots of the x,y,z co-ordinates of the particles. Main movie script
import sys
import matplotlib.pyplot as plt
import numpy as np
import glob
import math
pi = math.pi
from mpl_toolkits.mplot3d import Axes3D
import re
from subprocess import call
def natural_key(string_):
|
def get_color(id,N_massive):
color = 'black'
if id == 0:
color = 'yellow'
elif id <= N_massive:
color = 'red'
return color
N_massive = int(raw_input("Number of massive bodies (including sun): ")) - 1
dir = 'movie_output/'
files = glob.glob(dir+'hybridbody*.txt')
files = sorted(files,... | return [int(s) if s.isdigit() else s for s in re.split(r'(\d+)', string_)] | identifier_body |
hashlist.tsx | import React, { CSSProperties } from 'react';
import TextField from './string';
import commonView from '../HOC/commonView';
import ObjectView from './object';
import IconButton from '../Components/IconButton';
import { WidgetProps } from 'jsoninput/typings/types';
import { AddStatementButton } from '../Script/Views/But... |
function onKeyChange(value: string) {
try {
alterKey(editKey, value);
} catch {
// duplicate key
}
}
return (
<div {...flex}>
<div style={{ position: 'relative', flex: 1 }}>
<TextField
id={editKey}
... | {
removeKey(editKey);
} | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.