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 |
|---|---|---|---|---|
pago-dialog.component.ts | import { Component, OnInit, OnDestroy } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { Response } from '@angular/http';
import { NgbActiveModal, NgbModalRef } from '@ng-bootstrap/ng-bootstrap';
import { EventManager, AlertService, JhiLanguageService } from 'ng-jhipster';
import { Pag... |
private onSaveError (error) {
try {
error.json();
} catch (exception) {
error.message = error.text();
}
this.isSaving = false;
this.onError(error);
}
private onError (error) {
this.alertService.error(error.message, null, null);
}... | {
this.eventManager.broadcast({ name: 'pagoListModification', content: 'OK'});
this.isSaving = false;
this.activeModal.dismiss(result);
} | identifier_body |
pago-dialog.component.ts | import { Component, OnInit, OnDestroy } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { Response } from '@angular/http';
import { NgbActiveModal, NgbModalRef } from '@ng-bootstrap/ng-bootstrap';
import { EventManager, AlertService, JhiLanguageService } from 'ng-jhipster';
import { Pag... |
ngOnInit() {
this.isSaving = false;
this.authorities = ['ROLE_USER', 'ROLE_ADMIN'];
this.encargoService.query().subscribe(
(res: Response) => { this.encargos = res.json(); }, (res: Response) => this.onError(res.json()));
}
clear () {
this.activeModal.dismiss('can... | } | random_line_split |
pago-dialog.component.ts | import { Component, OnInit, OnDestroy } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { Response } from '@angular/http';
import { NgbActiveModal, NgbModalRef } from '@ng-bootstrap/ng-bootstrap';
import { EventManager, AlertService, JhiLanguageService } from 'ng-jhipster';
import { Pag... | else {
this.modalRef = this.pagoPopupService
.open(PagoDialogComponent);
}
});
}
ngOnDestroy() {
this.routeSub.unsubscribe();
}
}
| {
this.modalRef = this.pagoPopupService
.open(PagoDialogComponent, params['id']);
} | conditional_block |
pago-dialog.component.ts | import { Component, OnInit, OnDestroy } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { Response } from '@angular/http';
import { NgbActiveModal, NgbModalRef } from '@ng-bootstrap/ng-bootstrap';
import { EventManager, AlertService, JhiLanguageService } from 'ng-jhipster';
import { Pag... | () {
this.isSaving = false;
this.authorities = ['ROLE_USER', 'ROLE_ADMIN'];
this.encargoService.query().subscribe(
(res: Response) => { this.encargos = res.json(); }, (res: Response) => this.onError(res.json()));
}
clear () {
this.activeModal.dismiss('cancel');
}
... | ngOnInit | identifier_name |
test_init.py | """Tests for the DirecTV integration."""
from homeassistant.components.directv.const import DOMAIN
from homeassistant.config_entries import ConfigEntryState
from homeassistant.core import HomeAssistant
from tests.components.directv import setup_integration
from tests.test_util.aiohttp import AiohttpClientMocker
# pyl... | (
hass: HomeAssistant, aioclient_mock: AiohttpClientMocker
) -> None:
"""Test the DirecTV configuration entry not ready."""
entry = await setup_integration(hass, aioclient_mock, setup_error=True)
assert entry.state is ConfigEntryState.SETUP_RETRY
async def test_unload_config_entry(
hass: HomeAssi... | test_config_entry_not_ready | identifier_name |
test_init.py | """Tests for the DirecTV integration."""
from homeassistant.components.directv.const import DOMAIN
from homeassistant.config_entries import ConfigEntryState
from homeassistant.core import HomeAssistant
from tests.components.directv import setup_integration
from tests.test_util.aiohttp import AiohttpClientMocker
# pyl... | """Test the DirecTV configuration entry unloading."""
entry = await setup_integration(hass, aioclient_mock)
assert entry.entry_id in hass.data[DOMAIN]
assert entry.state is ConfigEntryState.LOADED
await hass.config_entries.async_unload(entry.entry_id)
await hass.async_block_till_done()
as... | ) -> None: | random_line_split |
test_init.py | """Tests for the DirecTV integration."""
from homeassistant.components.directv.const import DOMAIN
from homeassistant.config_entries import ConfigEntryState
from homeassistant.core import HomeAssistant
from tests.components.directv import setup_integration
from tests.test_util.aiohttp import AiohttpClientMocker
# pyl... | """Test the DirecTV configuration entry unloading."""
entry = await setup_integration(hass, aioclient_mock)
assert entry.entry_id in hass.data[DOMAIN]
assert entry.state is ConfigEntryState.LOADED
await hass.config_entries.async_unload(entry.entry_id)
await hass.async_block_till_done()
assert... | identifier_body | |
ClusterFps.py | #
# Copyright (c) 2009, Novartis Institutes for BioMedical Research Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyri... | clusters=Butina.ClusterData(uniq,len(uniq),1.-sim,False,distFunc)
print >>sys.stderr,'Sim: %.2f, nClusters: %d'%(sim,len(clusters))
for i,cluster in enumerate(clusters):
for pt in cluster:
uniq[pt].append(str(i+1))
cols.append('cluster_thresh_%d'%(int(100*sim)))
print ' '.join(cols)
... | def distFunc(a,b):
return 1.-DataStructs.DiceSimilarity(a[0],b[0])
for sim in sims: | random_line_split |
ClusterFps.py | #
# Copyright (c) 2009, Novartis Institutes for BioMedical Research Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyri... | (a,b):
return 1.-DataStructs.DiceSimilarity(a[0],b[0])
for sim in sims:
clusters=Butina.ClusterData(uniq,len(uniq),1.-sim,False,distFunc)
print >>sys.stderr,'Sim: %.2f, nClusters: %d'%(sim,len(clusters))
for i,cluster in enumerate(clusters):
for pt in cluster:
uniq[pt].append(str(i+... | distFunc | identifier_name |
ClusterFps.py | #
# Copyright (c) 2009, Novartis Institutes for BioMedical Research Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyri... |
for sim in sims:
clusters=Butina.ClusterData(uniq,len(uniq),1.-sim,False,distFunc)
print >>sys.stderr,'Sim: %.2f, nClusters: %d'%(sim,len(clusters))
for i,cluster in enumerate(clusters):
for pt in cluster:
uniq[pt].append(str(i+1))
cols.append('cluster_thresh_%d'%(int(100*sim)))
pr... | return 1.-DataStructs.DiceSimilarity(a[0],b[0]) | identifier_body |
ClusterFps.py | #
# Copyright (c) 2009, Novartis Institutes for BioMedical Research Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyri... |
def distFunc(a,b):
return 1.-DataStructs.DiceSimilarity(a[0],b[0])
for sim in sims:
clusters=Butina.ClusterData(uniq,len(uniq),1.-sim,False,distFunc)
print >>sys.stderr,'Sim: %.2f, nClusters: %d'%(sim,len(clusters))
for i,cluster in enumerate(clusters):
for pt in cluster:
... | inF = file(sys.argv[1],'r')
cols = cPickle.load(inF)
fps = cPickle.load(inF)
for row in fps:
nm,smi,fp = row[:3]
if smi not in smis:
try:
fpIdx = uFps.index(fp)
except ValueError:
fpIdx=len(uFps)
uFps.append(fp)
... | conditional_block |
user-utils.js | const $rdf = require('rdflib')
| module.exports.getName = getName
module.exports.getWebId = getWebId
module.exports.isValidUsername = isValidUsername
async function getName (webId, fetchGraph) {
const graph = await fetchGraph(webId)
const nameNode = graph.any($rdf.sym(webId), VCARD('fn'))
return nameNode.value
}
async function getWebId (accoun... | const SOLID = $rdf.Namespace('http://www.w3.org/ns/solid/terms#')
const VCARD = $rdf.Namespace('http://www.w3.org/2006/vcard/ns#')
| random_line_split |
user-utils.js | const $rdf = require('rdflib')
const SOLID = $rdf.Namespace('http://www.w3.org/ns/solid/terms#')
const VCARD = $rdf.Namespace('http://www.w3.org/2006/vcard/ns#')
module.exports.getName = getName
module.exports.getWebId = getWebId
module.exports.isValidUsername = isValidUsername
async function getName (webId, fetchGr... |
async function getWebId (accountDirectory, accountUrl, suffixMeta, fetchData) {
const metaFilePath = `${accountDirectory}/${suffixMeta}`
const metaFileUri = `${accountUrl}${suffixMeta}`
const metaData = await fetchData(metaFilePath)
const metaGraph = $rdf.graph()
$rdf.parse(metaData, metaGraph, metaFileUri,... | {
const graph = await fetchGraph(webId)
const nameNode = graph.any($rdf.sym(webId), VCARD('fn'))
return nameNode.value
} | identifier_body |
user-utils.js | const $rdf = require('rdflib')
const SOLID = $rdf.Namespace('http://www.w3.org/ns/solid/terms#')
const VCARD = $rdf.Namespace('http://www.w3.org/2006/vcard/ns#')
module.exports.getName = getName
module.exports.getWebId = getWebId
module.exports.isValidUsername = isValidUsername
async function getName (webId, fetchGr... | (accountDirectory, accountUrl, suffixMeta, fetchData) {
const metaFilePath = `${accountDirectory}/${suffixMeta}`
const metaFileUri = `${accountUrl}${suffixMeta}`
const metaData = await fetchData(metaFilePath)
const metaGraph = $rdf.graph()
$rdf.parse(metaData, metaGraph, metaFileUri, 'text/turtle')
const w... | getWebId | identifier_name |
loader.py | # Copyright 2019 Apex.AI, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing... | # This is a new-style launch_description which should contain a ReadyToTest action
ready_fn = kwargs.pop('ready_fn')
result = normalize(launch_description_fn(**kwargs))
# Fish the ReadyToTest action out of the launch description and plumb our
# ready_fn to it
... | return normalize(launch_description_fn(**kwargs))
else: | random_line_split |
loader.py | # Copyright 2019 Apex.AI, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing... | (unbound_function, arg_candidates):
function_args = inspect.signature(unbound_function).parameters
# We only want to bind the part of the context matches the test args
matching_args = {k: v for (k, v) in arg_candidates.items() if k in function_args}
return functools.partial(unbound_function, **matching_... | _partially_bind_matching_args | identifier_name |
loader.py | # Copyright 2019 Apex.AI, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing... |
def _iterate_tests_in_test_suite(test_suite):
try:
iter(test_suite)
except TypeError:
# Base case - test_suite is not iterable, so it must be an individual test method
yield test_suite
else:
# Otherwise, it's a test_suite, or a list of individual test methods. recurse
... | yield from _iterate_test_suites(test) | conditional_block |
loader.py | # Copyright 2019 Apex.AI, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing... |
# The effect of this is that every test will have `self.attr_name` available to it so that
# it can interact with ROS2 or the process exit coes, or IO or whatever data we want
for cls in _iterate_test_classes_in_test_suite(test_suite):
setattr(cls, attr_name, property(fget=_warn_getter))
def _it... | if not hasattr(self, '__warned'):
warnings.warn(
'Automatically adding attributes like self.{0} '
'to the test class will be deprecated in a future release. '
'Instead, add {0} to the test method argument list to '
'access the test object you ... | identifier_body |
monomorphized-callees-with-ty-params-3314.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 ... |
}
impl Serializer for int {
}
pub fn main() {
let foo = F { a: 1 };
foo.serialize(1);
let bar = F { a: F {a: 1 } };
bar.serialize(2);
}
| {
self.a.serialize(s);
} | identifier_body |
monomorphized-callees-with-ty-params-3314.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 foo = F { a: 1 };
foo.serialize(1);
let bar = F { a: F {a: 1 } };
bar.serialize(2);
}
| main | identifier_name |
monomorphized-callees-with-ty-params-3314.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 ... |
trait Serializable {
fn serialize<S:Serializer>(&self, s: S);
}
impl Serializable for int {
fn serialize<S:Serializer>(&self, _s: S) { }
}
struct F<A> { a: A }
impl<A:Serializable> Serializable for F<A> {
fn serialize<S:Serializer>(&self, s: S) {
self.a.serialize(s);
}
}
impl Serializer for... |
trait Serializer {
} | random_line_split |
window_builder.rs | use std::{collections::HashMap, sync::mpsc};
use super::{Shell, Window};
use crate::{
render::RenderContext2D, utils::Rectangle, window_adapter::WindowAdapter, WindowRequest,
WindowSettings,
};
/// The `WindowBuilder` is used to construct an os independent window
/// shell that will communicate with the suppo... |
let window = orbclient::Window::new_flags(
self.bounds.x() as i32,
self.bounds.y() as i32,
self.bounds.width() as u32,
self.bounds.height() as u32,
self.title.as_str(),
&flags,
)
.expect("WindowBuilder: Could not create an... | {
flags.push(orbclient::WindowFlag::Front);
} | conditional_block |
window_builder.rs | use std::{collections::HashMap, sync::mpsc};
use super::{Shell, Window};
use crate::{
render::RenderContext2D, utils::Rectangle, window_adapter::WindowAdapter, WindowRequest,
WindowSettings,
};
/// The `WindowBuilder` is used to construct an os independent window
/// shell that will communicate with the suppo... |
/// Mark window as resizeable.
pub fn resizeable(mut self, resizeable: bool) -> Self {
self.resizeable = resizeable;
self
}
/// Register a window request receiver to communicate with the
/// window shell via interprocess communication.
pub fn request_receiver(mut self, request... | {
WindowBuilder {
adapter,
always_on_top: false,
borderless: false,
bounds: Rectangle::new((0.0, 0.0), (100.0, 75.0)),
fonts: HashMap::new(),
request_receiver: None,
resizeable: false,
shell,
title: Strin... | identifier_body |
window_builder.rs | use std::{collections::HashMap, sync::mpsc};
use super::{Shell, Window};
use crate::{
render::RenderContext2D, utils::Rectangle, window_adapter::WindowAdapter, WindowRequest,
WindowSettings,
};
/// The `WindowBuilder` is used to construct an os independent window
/// shell that will communicate with the suppo... | always_on_top: settings.always_on_top,
borderless: settings.borderless,
bounds: Rectangle::new(settings.position, (settings.size.0, settings.size.1)),
fonts: settings.fonts,
request_receiver: None,
resizeable: settings.resizeable,
shell... | adapter, | random_line_split |
window_builder.rs | use std::{collections::HashMap, sync::mpsc};
use super::{Shell, Window};
use crate::{
render::RenderContext2D, utils::Rectangle, window_adapter::WindowAdapter, WindowRequest,
WindowSettings,
};
/// The `WindowBuilder` is used to construct an os independent window
/// shell that will communicate with the suppo... | (shell: &'a mut Shell<A>, adapter: A) -> Self {
WindowBuilder {
adapter,
always_on_top: false,
borderless: false,
bounds: Rectangle::new((0.0, 0.0), (100.0, 75.0)),
fonts: HashMap::new(),
request_receiver: None,
resizeable: fals... | new | identifier_name |
Widget.js | Ext.define('Ext.slider.Widget', {
extend: 'Ext.Widget',
alias: 'widget.sliderwidget',
// Required to pull in the styles
requires: [
'Ext.slider.Multi'
],
cachedConfig: {
vertical: false,
cls: Ext.baseCSSPrefix + 'slider',
baseCls: Ext.baseCSSPrefix + ... | mousedown: 'onMouseDown',
dragstart: 'cancelDrag',
drag: 'cancelDrag',
dragend: 'cancelDrag'
},
children: [{
reference: 'endEl',
cls: Ext.baseCSSPrefix + 'slider-end',
children: [{
... | reference: 'element',
cls: Ext.baseCSSPrefix + 'slider',
listeners: { | random_line_split |
Widget.js | Ext.define('Ext.slider.Widget', {
extend: 'Ext.Widget',
alias: 'widget.sliderwidget',
// Required to pull in the styles
requires: [
'Ext.slider.Multi'
],
cachedConfig: {
vertical: false,
cls: Ext.baseCSSPrefix + 'slider',
baseCls: Ext.baseCSSPrefix + ... |
}
return me;
},
/**
* Returns the current value of the slider
* @param {Number} index The index of the thumb to return a value for
* @return {Number/Number[]} The current value of the slider at the given index, or an array of all thumb values if
* no index is given.
*/... | {
// TODO this only handles a single value; need a solution for exposing multiple values to aria.
// Perhaps this should go on each thumb element rather than the outer element.
me.element.set({
'aria-valuenow': value,
'aria-valuetex... | conditional_block |
bg.js | /**
* Todo:
* - Allow hiding of trades (seperates upcoming and finished games)
* - Allow auto-retry for when bots are down
* - Allow auto-accept offers
* - Create popup for browser action (next X games, my winnings)
*/
// CONSTANTS
var GREEN = "#76EE00",
ORANGE = "#FFA500",
RED = "#FF0000",
IM... |
/**
* Perform a POST request to a url
* @param {string} url - The URL to request to
* @param {object} data - the POST data
* @param {function} callback - The function to call once the request is performed
* @param {object} headers - a header object in the format {header: value}
*/
function post(url, data, call... | {
// create xmlhttprequest instance
var xhr = new XMLHttpRequest();
// init
xhr.addEventListener("load", callback);
xhr.open("GET", url, true);
// set headers
for (var h in headers) {
if (headers.hasOwnProperty(h))
xhr.setRequestHeader(h, headers[h]);
}
// send... | identifier_body |
bg.js | /**
* Todo:
* - Allow hiding of trades (seperates upcoming and finished games)
* - Allow auto-retry for when bots are down
* - Allow auto-accept offers
* - Create popup for browser action (next X games, my winnings)
*/
// CONSTANTS
var GREEN = "#76EE00",
ORANGE = "#FFA500",
RED = "#FF0000",
IM... |
return true;
});
/**
* Get the next X games
* Can return less than X games, if no more exist
* @param {int} num - number of games to return
* @param {function} callback - callback function
* Calls callback with one parameter:
* {array} - array of match objects, each formatted as follows:
* {time... | {
chrome.tabs.highlight({tabs: [sender.tab.index]}, callback);
} | conditional_block |
bg.js | /**
* Todo:
* - Allow hiding of trades (seperates upcoming and finished games)
* - Allow auto-retry for when bots are down
* - Allow auto-accept offers
* - Create popup for browser action (next X games, my winnings)
*/
// CONSTANTS
var GREEN = "#76EE00",
ORANGE = "#FFA500",
RED = "#FF0000",
IM... | * @param {function} callback - callback function
* Calls callback with one parameter:
* {array} - array of match objects, each formatted as follows:
* {time: string,
* link: string
* team1: {
* name: string,
* percent: int,
* imgUrl: str... | * @param {int} num - number of games to return | random_line_split |
bg.js | /**
* Todo:
* - Allow hiding of trades (seperates upcoming and finished games)
* - Allow auto-retry for when bots are down
* - Allow auto-accept offers
* - Create popup for browser action (next X games, my winnings)
*/
// CONSTANTS
var GREEN = "#76EE00",
ORANGE = "#FFA500",
RED = "#FF0000",
IM... | (vals) {
if (!vals)
console.error("status_loop should only be used as callback for get_status");
var iconNum = vals.error ? 3 : // if error, change to grey
(vals.status.indexOf(ORANGE) === -1 && vals.status.indexOf(RED) === -1) ? 2 : // if good, change to green
(!val... | status_loop | identifier_name |
geometry.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 cssparser::ToCss;
use euclid::length::Length;
use euclid::num::Zero;
use euclid::point::Point2D;
use euclid::... | <T: PartialOrd + Add<T, Output=T>>(rect: Rect<T>, point: Point2D<T>) -> bool {
point.x >= rect.origin.x && point.x < rect.origin.x + rect.size.width &&
point.y >= rect.origin.y && point.y < rect.origin.y + rect.size.height
}
/// A helper function to convert a rect of `f32` pixels to a rect of app units.
pu... | rect_contains_point | identifier_name |
geometry.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 cssparser::ToCss;
use euclid::length::Length;
use euclid::num::Zero;
use euclid::point::Point2D;
use euclid::... | y: Au(0),
},
size: Size2D {
width: Au(0),
height: Au(0),
}
};
pub static MAX_RECT: Rect<Au> = Rect {
origin: Point2D {
x: Au(i32::MIN / 2),
y: Au(i32::MIN / 2),
},
size: Size2D {
width: MAX_AU,
height: MAX_AU,
}
};
pub const MIN_AU: A... | origin: Point2D {
x: Au(0), | random_line_split |
geometry.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 cssparser::ToCss;
use euclid::length::Length;
use euclid::num::Zero;
use euclid::point::Point2D;
use euclid::... | ;
}
#[inline]
pub fn from_f32_px(px: f32) -> Au {
Au((px * (AU_PER_PX as f32)) as i32)
}
#[inline]
pub fn from_pt(pt: f64) -> Au {
Au::from_f64_px(pt_to_px(pt))
}
#[inline]
pub fn from_f64_px(px: f64) -> Au {
Au((px * (AU_PER_PX as f64)) as i32)
}
}
//... | { return Au(self.0 - res) } | conditional_block |
geometry.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 cssparser::ToCss;
use euclid::length::Length;
use euclid::num::Zero;
use euclid::point::Point2D;
use euclid::... |
/// Rounds this app unit down to the previous (left or top) pixel and returns it.
#[inline]
pub fn to_prev_px(self) -> i32 {
((self.0 as f64) / (AU_PER_PX as f64)).floor() as i32
}
/// Rounds this app unit up to the next (right or bottom) pixel and returns it.
#[inline]
pub fn to_... | {
self.0 / AU_PER_PX
} | identifier_body |
AvgCacheCalc.py | #!/usr/bin/env python
#
# This file is part of the pebil project.
#
# Copyright (c) 2010, University of California Regents
# All rights reserved.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation... |
#pad a '/' to the end of the directory
if dirRead[-1] != '/':
dirRead = dirRead + '/'
except IndexError:
print "No --dir value given, please provide argument\n"
errorMsg()
except ValueError:
print "TESTING:Error with --dir argument, see usage below\n"
errorMsg()
try:
#check for app
appidx = sys.argv.i... | dirRead = sys.argv[diridx+1]
#print "TESTING: input used ***WHAT ABOUT SLASH AT END*** dir=", dirRead | conditional_block |
AvgCacheCalc.py | #!/usr/bin/env python
#
# This file is part of the pebil project.
#
# Copyright (c) 2010, University of California Regents
# All rights reserved.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation... | print "One of these two are required:"
print "\t--taskid int; eg 0001"
print "\t--sysid int; 1, 2, or 3 chars - 75\n"
print "optional"
print "\t--dir string; eg /pmaclabs/ti10/ti10_icepic_standard_0128/processed_trace/ [default=.]"
exit()
diridx = -1
sysidx = -1
taskidx = -1
sysidindexerr = 0
taskidindexerr ... | print "\t--app string; eg icepic,hycom,..."
print "\t--dataset string; eg large, standard..."
print "\t--cpu_count int; eg 256,1024,...\n" | random_line_split |
AvgCacheCalc.py | #!/usr/bin/env python
#
# This file is part of the pebil project.
#
# Copyright (c) 2010, University of California Regents
# All rights reserved.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation... |
##convert = lambda text: int(text) if text.isdigit() else text
alphanum_key = lambda key: [ convert(c) for c in re.split('([0-9]+)', key) ]
l.sort( key=alphanum_key )
#prints a usage error message and exits
def errorMsg():
print
print "Usage : ./AvgCacheCalc.py\n"
print "required:"
print "\t--app stri... | if text.isdigit():
return int(text)
else:
return text | identifier_body |
AvgCacheCalc.py | #!/usr/bin/env python
#
# This file is part of the pebil project.
#
# Copyright (c) 2010, University of California Regents
# All rights reserved.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation... | (fileNameGetAvg):
"""calcuates the average cache hits for a file"""
#print "TESTING:: file:", fileNameGetAvg
#this part is from counter_mikey.py
try:
traceFile = open(fileNameGetAvg, 'r')
fileLines = traceFile.readlines()
traceFile.close()
except IOError:
print "Warning: file" + traceFile, "not found"
... | getAvgSingle | identifier_name |
post_to_twitter.py | # -*- coding: utf-8 -*-
#
# Copyright (c) 2009 Arthur Furlan <arthur.furlan@gmail.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) an... | (sender, instance, *args, **kwargs):
"""
Post new saved objects to Twitter.
Example:
from django.db import models
class MyModel(models.Model):
text = models.CharField(max_length=255)
link = models.CharField(max_length=255)
def __unicode__(self):
... | post_to_twitter | identifier_name |
post_to_twitter.py | # -*- coding: utf-8 -*-
#
# Copyright (c) 2009 Arthur Furlan <arthur.furlan@gmail.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) an... | from django.conf import settings
from django.contrib.sites.models import Site
TWITTER_MAXLENGTH = getattr(settings, 'TWITTER_MAXLENGTH', 140)
def post_to_twitter(sender, instance, *args, **kwargs):
"""
Post new saved objects to Twitter.
Example:
from django.db import models
class MyMode... | random_line_split | |
post_to_twitter.py | # -*- coding: utf-8 -*-
#
# Copyright (c) 2009 Arthur Furlan <arthur.furlan@gmail.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) an... |
# check if there's a twitter account configured
try:
username = settings.TWITTER_USERNAME
password = settings.TWITTER_PASSWORD
except AttributeError:
print 'WARNING: Twitter account not configured.'
return False
# if the absolute url wasn't a real absolute url and does... | return False | conditional_block |
post_to_twitter.py | # -*- coding: utf-8 -*-
#
# Copyright (c) 2009 Arthur Furlan <arthur.furlan@gmail.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) an... | """
Post new saved objects to Twitter.
Example:
from django.db import models
class MyModel(models.Model):
text = models.CharField(max_length=255)
link = models.CharField(max_length=255)
def __unicode__(self):
return u'%s' % self.text
... | identifier_body | |
util.rs | /*
* Copyright 2020 Clint Byrum
*
* 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 i... | } else if input[0] == b'1' {
true
} else {
false
}
}
pub fn new_res(ptype: u32, data: Bytes) -> Packet {
Packet {
magic: PacketMagic::RES,
ptype: ptype,
psize: data.len() as u32,
data: data,
}
}
pub fn new_req(ptype: u32, data: Bytes) -> Packet {
... | pub fn bytes2bool(input: &Bytes) -> bool {
if input.len() != 1 {
false | random_line_split |
util.rs | /*
* Copyright 2020 Clint Byrum
*
* 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 i... | {
Packet {
magic: PacketMagic::TEXT,
ptype: ADMIN_RESPONSE,
psize: 0,
data: Bytes::new(),
}
} | identifier_body | |
util.rs | /*
* Copyright 2020 Clint Byrum
*
* 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 i... | (ptype: u32, data: Bytes) -> Packet {
Packet {
magic: PacketMagic::REQ,
ptype: ptype,
psize: data.len() as u32,
data: data,
}
}
pub fn next_field(buf: &mut Bytes) -> Bytes {
match buf[..].iter().position(|b| *b == b'\0') {
Some(null_pos) => {
let value = ... | new_req | identifier_name |
user.js | user = angular.module('user')
user.factory("User", ['$http', 'Alerts', function($http, Alerts) {
/*this.data = {
user: null,
authenticated: false,
};
*/
this.get = function(call) {
var promise = $http.get("/service/user/");
Alerts.handle(promise, undefine... | return promise;
};
this.signout = function( scall, ecall) {
var promise = $http.get("/service/user/signout");
var error = {
type: "error",
strong: "Failed!",
message: "Could not signout."
};
var success = {
... | random_line_split | |
user.js | user = angular.module('user')
user.factory("User", ['$http', 'Alerts', function($http, Alerts) {
/*this.data = {
user: null,
authenticated: false,
};
*/
this.get = function(call) {
var promise = $http.get("/service/user/");
Alerts.handle(promise, undefine... |
};
$scope.signin = function() {
User.signin({"NameOrEmail": $scope.data.email, "Passwd": $scope.data.password}, function(u) {
Global.user = u;
Global.authenticated = true;
$location.path('/');
});
};
$scope.signout... | {
$location.path('/signin');
} | conditional_block |
messageevent.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 dom::bindings::codegen::Bindings::EventBinding::EventMethods;
use dom::bindings::codegen::Bindings::MessageEve... | }
} | random_line_split | |
messageevent.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 dom::bindings::codegen::Bindings::EventBinding::EventMethods;
use dom::bindings::codegen::Bindings::MessageEve... |
// https://dom.spec.whatwg.org/#dom-event-istrusted
fn IsTrusted(&self) -> bool {
self.event.IsTrusted()
}
}
| {
self.lastEventId.clone()
} | identifier_body |
messageevent.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 dom::bindings::codegen::Bindings::EventBinding::EventMethods;
use dom::bindings::codegen::Bindings::MessageEve... | {
event: Event,
data: Heap<JSVal>,
origin: DOMString,
lastEventId: DOMString,
}
impl MessageEvent {
pub fn new_uninitialized(global: &GlobalScope) -> DomRoot<MessageEvent> {
MessageEvent::new_initialized(global,
HandleValue::undefined(),
... | MessageEvent | identifier_name |
WithTimeout.tsx |
import { Component, ComponentClass } from 'react';
import { Timeout } from '../../helpers/Timeout';
interface InnerProps {
timeLeft: number;
maxTime: number;
}
interface WithTimeoutProps {
maxTime: number;
onTimeUp: Function;
}
interface WithTimeoutState {
timeLeft: number;
timeUp: boo... |
}
}
}
| {
this.timeout.stop();
} | conditional_block |
WithTimeout.tsx |
import { Component, ComponentClass } from 'react';
import { Timeout } from '../../helpers/Timeout';
interface InnerProps {
timeLeft: number;
maxTime: number;
}
interface WithTimeoutProps {
maxTime: number;
onTimeUp: Function;
}
interface WithTimeoutState {
timeLeft: number;
timeUp: boo... | (): void {
if (this.timeout != null) {
this.timeout.stop();
}
}
}
}
| stopTimer | identifier_name |
WithTimeout.tsx |
import { Component, ComponentClass } from 'react';
import { Timeout } from '../../helpers/Timeout';
interface InnerProps {
timeLeft: number;
maxTime: number;
}
interface WithTimeoutProps {
maxTime: number;
onTimeUp: Function;
}
interface WithTimeoutState {
timeLeft: number;
timeUp: boo... |
isTimeUp(): boolean {
return this.state.timeUp;
}
stopTimer(): void {
if (this.timeout != null) {
this.timeout.stop();
}
}
}
}
| {
this.setState({
timeUp: true,
timeLeft: 0
});
this.props.onTimeUp();
} | identifier_body |
WithTimeout.tsx | import { Component, ComponentClass } from 'react';
import { Timeout } from '../../helpers/Timeout';
interface InnerProps {
timeLeft: number;
maxTime: number;
}
interface WithTimeoutProps {
maxTime: number;
onTimeUp: Function;
}
interface WithTimeoutState {
timeLeft: number;
timeUp: bool... |
} | }
}
} | random_line_split |
ex5.py | my_name = 'Zed A. Shaw'
my_age = 35 # not a lie
my_height = 74 # Inches
my_weight = 180 # lbs
my_eyes = 'Blue'
my_teeth = 'White'
my_hair = 'Brown'
print "Let's talk about %s." % my_name
print "He's %d inches tall." % my_height
print "He's %d pounds heavy." % my_weight | print "His teeth are usually %s depending on the coffee." % my_teeth
# this line is tricky, try to get it exactly right
print" If I add %d, %d and %d I get %d." % (my_age, my_height, my_weight, my_age + my_height + my_weight) | print "Actually that's not too heavy"
print "He's got %s eyes and %s hair." % (my_eyes, my_hair) | random_line_split |
rpcDocuments-spec.js | #!/usr/bin/env node
'use strict';
/**
* Documents RPC Prototype
*
* - TIU CREATE RECORD (MAKE^TIUSRVP)
* - TIU UPDATE RECORD (UPDATE^TIUSRVP)
* - TIU DELETE RECORD (DELETE^TIUSRVP)
* - TIU SIGN RECORD
* ... and locks
* ... key file, TIUSRVP
*
* REM: HMP set
* "TIU AUTHORIZATION",
* "TIU CREATE ADDENDU... | ],
};
const res = rpcRunner.run(rpcDefn.name, rpcDefn.args);
expect(res.result).not.toMatch(/0/);
// get result
const tiuIEN = res.result;
const descr = VDM.describe(`8925-${tiuIEN}`);
expect(descr.author_dictator.id).toEqual(bad200);
});
// ... | TEXT: formatTextLines(['This patient has had the following reactions ', 'signed-off on Mar 05, 2016@01:16:21.', '', 'CHOCOLATE', '', "Author's comments:", '', 'unfortunate fellow ', '']),
}, | random_line_split |
rpcDocuments-spec.js | #!/usr/bin/env node
'use strict';
/**
* Documents RPC Prototype
*
* - TIU CREATE RECORD (MAKE^TIUSRVP)
* - TIU UPDATE RECORD (UPDATE^TIUSRVP)
* - TIU DELETE RECORD (DELETE^TIUSRVP)
* - TIU SIGN RECORD
* ... and locks
* ... key file, TIUSRVP
*
* REM: HMP set
* "TIU AUTHORIZATION",
* "TIU CREATE ADDENDU... |
describe('testDocumentRPCs', () => {
let db; // for afterAll
let DUZ; // play with 55 to 56 ie/ different DUZ to see what defaults ...
let DUZSIG; // AUTHORSIG ie/ signature used for signing
let patientIEN;
let rpcRunner;
// "id": "8925_1-17", "label": "ADVERSE REACTION_ALLERGY"
const araD... | {
const tlines = [];
lines.forEach((line) => {
tlines.push({ 0: line });
});
return tlines;
} | identifier_body |
rpcDocuments-spec.js | #!/usr/bin/env node
'use strict';
/**
* Documents RPC Prototype
*
* - TIU CREATE RECORD (MAKE^TIUSRVP)
* - TIU UPDATE RECORD (UPDATE^TIUSRVP)
* - TIU DELETE RECORD (DELETE^TIUSRVP)
* - TIU SIGN RECORD
* ... and locks
* ... key file, TIUSRVP
*
* REM: HMP set
* "TIU AUTHORIZATION",
* "TIU CREATE ADDENDU... | (lines) {
const tlines = [];
lines.forEach((line) => {
tlines.push({ 0: line });
});
return tlines;
}
describe('testDocumentRPCs', () => {
let db; // for afterAll
let DUZ; // play with 55 to 56 ie/ different DUZ to see what defaults ...
let DUZSIG; // AUTHORSIG ie/ signature used fo... | formatTextLines | identifier_name |
test.ts | /*
* @license Apache-2.0
*
* Copyright (c) 2020 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by ap... |
// TESTS //
// The function returns a number...
{
kroneckerDeltaf( 3.14, 3.14 ); // $ExpectType number
}
// The function does not compile if provided values other than two numbers...
{
kroneckerDeltaf( true, 3 ); // $ExpectError
kroneckerDeltaf( false, 2 ); // $ExpectError
kroneckerDeltaf( '5', 1 ); // $ExpectEr... | */
import kroneckerDeltaf = require( './index' );
| random_line_split |
index.js | const spaceSeparated = require('space-separated-tokens')
const C_NEWLINE = '\n'
const C_NEWPARAGRAPH = '\n\n'
module.exports = function plugin (classNames = {}) {
const locateMarker = new RegExp(`[^\\\\]?(->|<-)`)
const endMarkers = ['->', '<-']
function alignTokenizer (eat, value, silent) {
const keep = v... |
finishedBlocks.push(linesToEat.join(C_NEWLINE))
// Check if another block is following
if (value.indexOf('->', nextIndex) !== (nextIndex + 1)) break
linesToEat = []
blockStartIndex = nextIndex + 1
}
index = nextIndex + 1
canEatLine = nextIndex !== -1
}
... |
if (endMarker === '') endMarker = lineToEat.slice(-2) | random_line_split |
index.js | const spaceSeparated = require('space-separated-tokens')
const C_NEWLINE = '\n'
const C_NEWPARAGRAPH = '\n\n'
module.exports = function plugin (classNames = {}) {
const locateMarker = new RegExp(`[^\\\\]?(->|<-)`)
const endMarkers = ['->', '<-']
function | (eat, value, silent) {
const keep = value.match(locateMarker)
if (!keep || keep.index !== 0) return
const now = eat.now()
const [, startMarker] = keep
/* istanbul ignore if - never used (yet) */
if (silent) return true
let index = 0
let linesToEat = []
const finishedBlocks = []
... | alignTokenizer | identifier_name |
index.js | const spaceSeparated = require('space-separated-tokens')
const C_NEWLINE = '\n'
const C_NEWPARAGRAPH = '\n\n'
module.exports = function plugin (classNames = {}) {
const locateMarker = new RegExp(`[^\\\\]?(->|<-)`)
const endMarkers = ['->', '<-']
function alignTokenizer (eat, value, silent) |
const Parser = this.Parser
// Inject blockTokenizer
const blockTokenizers = Parser.prototype.blockTokenizers
const blockMethods = Parser.prototype.blockMethods
blockTokenizers.alignBlocks = alignTokenizer
blockMethods.splice(blockMethods.indexOf('list') + 1, 0, 'alignBlocks')
const Compiler = this.Com... | {
const keep = value.match(locateMarker)
if (!keep || keep.index !== 0) return
const now = eat.now()
const [, startMarker] = keep
/* istanbul ignore if - never used (yet) */
if (silent) return true
let index = 0
let linesToEat = []
const finishedBlocks = []
let endMarker = ''
... | identifier_body |
bootstrap-affix.js | /* ==========================================================
* bootstrap-affix.js v2.2.2
* http://twitter.github.com/bootstrap/javascript.html#affix
* ==========================================================
* Copyright 2012 Twitter, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* y... |
Affix.prototype.checkPosition = function () {
if (!this.$element.is(':visible')) return
var scrollHeight = $(document).height()
, scrollTop = this.$window.scrollTop()
, position = this.$element.offset()
, offset = this.options.offset
, offsetBottom = offset.bottom
, offsetTop =... | .on('scroll.affix.data-api', $.proxy(this.checkPosition, this))
.on('click.affix.data-api', $.proxy(function () { setTimeout($.proxy(this.checkPosition, this), 1) }, this))
this.$element = $(element)
this.checkPosition()
} | random_line_split |
window.rs | use std::fmt;
use std::ops::Range;
use std::iter::IntoIterator;
use types::{State, BoardView};
use board::Board;
#[derive(Clone, Copy)]
pub struct Window<'a> {
pub min_x: i32,
pub min_y: i32,
pub max_x: i32,
pub max_y: i32,
board: &'a Board
}
impl<'a> Window<'a> {
pub fn new(board: &'a Board,... |
}
impl<'a> BoardView for Window<'a> {
fn cell_state(&self, x: i32, y: i32) -> State {
self.board.cell_state(x, y)
}
fn as_window<'b>(&'b self) -> Window<'b> {
*self
}
fn iter<'b>(&'b self) -> Iter<'b> {
Iter {
window: *self,
x: self.min_x,
... | {
loop {
if self.x == self.window.max_x + 1 {
return None;
}
match self.ys.next() {
Some(y) => {
let state = self.window.cell_state(self.x, y);
return Some((self.x, y, state))
},
... | identifier_body |
window.rs | use std::fmt;
use std::ops::Range;
use std::iter::IntoIterator;
use types::{State, BoardView};
use board::Board;
#[derive(Clone, Copy)]
pub struct Window<'a> {
pub min_x: i32,
pub min_y: i32,
pub max_x: i32,
pub max_y: i32,
board: &'a Board
}
impl<'a> Window<'a> {
pub fn new(board: &'a Board,... | match self.ys.next() {
Some(y) => {
let state = self.window.cell_state(self.x, y);
return Some((self.x, y, state))
},
None => {
self.ys = 0..self.window.max_y + 1;
self.x += 1;
... | if self.x == self.window.max_x + 1 {
return None;
} | random_line_split |
window.rs | use std::fmt;
use std::ops::Range;
use std::iter::IntoIterator;
use types::{State, BoardView};
use board::Board;
#[derive(Clone, Copy)]
pub struct Window<'a> {
pub min_x: i32,
pub min_y: i32,
pub max_x: i32,
pub max_y: i32,
board: &'a Board
}
impl<'a> Window<'a> {
pub fn new(board: &'a Board,... | <'b>(&'b self) -> Iter<'b> {
Iter {
window: *self,
x: self.min_x,
ys: self.min_y..self.max_y + 1
}
}
fn window<'b>(&'b self, min_x: i32, min_y: i32, max_x: i32, max_y: i32)
-> Window<'b> {
Window {
min_x: min_x,
... | iter | identifier_name |
gulpfile.js | var env = require('minimist')(process.argv.slice(2)),
gulp = require('gulp'),
plumber = require('gulp-plumber'),
browserSync = require('browser-sync'),
stylus = require('gulp-stylus'),
uglify = require('gulp-uglify'),
concat = require('gulp-concat'),
jeet = require('jeet'... | });
});
/**
* Stylus task
*/
gulp.task('stylus', function(){
gulp.src('src/styl/main.styl')
.pipe(plumber())
.pipe(stylus({
use:[koutoSwiss(), prefixer(), jeet(), rupture()],
compress: true
}))
.pipe(gulp.dest('_site/assets/css/'))
.pipe(browserSync.reload({stream:true}))
.pipe(gulp.dest('assets... | random_line_split | |
100_doors_unoptimized.rs | // Implements http://rosettacode.org/wiki/100_doors
// this is the unoptimized version that performs all 100
// passes, as per the original description of the problem
#![feature(core)]
use std::iter::range_step_inclusive;
#[cfg(not(test))]
fn | () {
// states for the 100 doors
// uses a vector of booleans,
// where state==false means the door is closed
let mut doors = [false; 100];
solve(&mut doors);
for (idx, door) in doors.iter().enumerate() {
println!("door {} open: {}", idx+1, door);
}
}
// unoptimized solution for t... | main | identifier_name |
100_doors_unoptimized.rs | // Implements http://rosettacode.org/wiki/100_doors
// this is the unoptimized version that performs all 100
// passes, as per the original description of the problem
#![feature(core)]
use std::iter::range_step_inclusive;
#[cfg(not(test))]
fn main() {
// states for the 100 doors
// uses a vector of booleans,
... |
// test that the doors with index corresponding to
// a perfect square are now open
for i in 1..11 {
assert!(doors[i*i - 1]);
}
} | fn solution() {
let mut doors = [false;100];
solve(&mut doors); | random_line_split |
100_doors_unoptimized.rs | // Implements http://rosettacode.org/wiki/100_doors
// this is the unoptimized version that performs all 100
// passes, as per the original description of the problem
#![feature(core)]
use std::iter::range_step_inclusive;
#[cfg(not(test))]
fn main() {
// states for the 100 doors
// uses a vector of booleans,
... |
#[test]
fn solution() {
let mut doors = [false;100];
solve(&mut doors);
// test that the doors with index corresponding to
// a perfect square are now open
for i in 1..11 {
assert!(doors[i*i - 1]);
}
}
| {
for pass in 1..101 {
for door in range_step_inclusive(pass, 100, pass) {
// flip the state of the door
doors[door-1] = !doors[door-1]
}
}
} | identifier_body |
fall.py | #
# Copyright (C) 2016 Dang Duong
#
# This file is part of Open Tux World.
#
# Open Tux World is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your op... | own = cont.owner
own.applyForce([0, 0, -10 * own.mass], False)
if own["health"] < 1:
return
own["hit"] = False
own.enableRigidBody()
v = Vector((own["v_x"], own["v_y"], own["v_z"]))
dv = Vector(own.worldLinearVelocity) - v
v += dv
speed = common.getDistance([dv.x, dv.y... | identifier_body | |
fall.py | #
# Copyright (C) 2016 Dang Duong
#
# This file is part of Open Tux World.
#
# Open Tux World is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your op... |
logic = common.logic
def main(cont):
own = cont.owner
own.applyForce([0, 0, -10 * own.mass], False)
if own["health"] < 1:
return
own["hit"] = False
own.enableRigidBody()
v = Vector((own["v_x"], own["v_y"], own["v_z"]))
dv = Vector(own.worldLinearVelocity) - v
v += dv... | from mathutils import Vector | random_line_split |
fall.py | #
# Copyright (C) 2016 Dang Duong
#
# This file is part of Open Tux World.
#
# Open Tux World is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your op... | (cont):
own = cont.owner
own.applyForce([0, 0, -10 * own.mass], False)
if own["health"] < 1:
return
own["hit"] = False
own.enableRigidBody()
v = Vector((own["v_x"], own["v_y"], own["v_z"]))
dv = Vector(own.worldLinearVelocity) - v
v += dv
speed = common.getDistance... | main | identifier_name |
fall.py | #
# Copyright (C) 2016 Dang Duong
#
# This file is part of Open Tux World.
#
# Open Tux World is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your op... | own.disableRigidBody()
own.worldOrientation[2] = [0.0,0.0,1.0]
own.state = logic.KX_STATE2 | conditional_block | |
secret.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any lat... |
}
| {
&self.inner
} | identifier_body |
secret.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any lat... | (key: &[u8]) -> Self {
assert_eq!(32, key.len(), "Caller should provide 32-byte length slice");
let mut h = H256::default();
h.copy_from_slice(&key[0..32]);
Secret { inner: h }
}
pub fn from_slice(key: &[u8]) -> Result<Self, Error> {
let secret = key::SecretKey::from_slice(&super::SECP256K1, key)?;
Ok(s... | from_slice_unchecked | identifier_name |
secret.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any lat... | impl fmt::Debug for Secret {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
write!(fmt, "Secret: 0x{:x}{:x}..{:x}{:x}", self.inner[0], self.inner[1], self.inner[30], self.inner[31])
}
}
impl Secret {
fn from_slice_unchecked(key: &[u8]) -> Self {
assert_eq!(32, key.len(), "Caller should provide 32-byte... | #[derive(Clone, PartialEq, Eq)]
pub struct Secret {
inner: H256,
}
| random_line_split |
package.rs | use super::module::module_from_declarations;
use crate::error::ValidationError;
use crate::parser::PackageDecl;
use crate::prelude::std_module;
use crate::repr::{ModuleIx, ModuleRepr, Package};
use crate::Location;
use cranelift_entity::PrimaryMap;
use std::collections::HashMap;
pub fn package_from_declarations(
p... |
}
}
Ok(pkg.build())
}
pub struct PackageBuilder {
name_decls: HashMap<String, (ModuleIx, Option<Location>)>,
repr: Package,
}
impl PackageBuilder {
pub fn new() -> Self {
let mut repr = Package {
names: PrimaryMap::new(),
modules: PrimaryMap::new(),
... | {
let module_ix = pkg.introduce_name(name, *location)?;
let module_repr = module_from_declarations(pkg.repr(), module_ix, &decls)?;
pkg.define_module(module_ix, module_repr);
} | conditional_block |
package.rs | use super::module::module_from_declarations;
use crate::error::ValidationError;
use crate::parser::PackageDecl;
use crate::prelude::std_module;
use crate::repr::{ModuleIx, ModuleRepr, Package};
use crate::Location;
use cranelift_entity::PrimaryMap;
use std::collections::HashMap;
pub fn package_from_declarations(
p... |
#[test]
fn no_mod_std_name() {
let err = pkg_("mod std {}").err().expect("error package");
assert_eq!(
err,
ValidationError::Syntax {
expected: "non-reserved module name",
location: Location { line: 1, column: 0 },
}
);... | let _bar = foo.datatype("bar").expect("foo::bar exists");
} | random_line_split |
package.rs | use super::module::module_from_declarations;
use crate::error::ValidationError;
use crate::parser::PackageDecl;
use crate::prelude::std_module;
use crate::repr::{ModuleIx, ModuleRepr, Package};
use crate::Location;
use cranelift_entity::PrimaryMap;
use std::collections::HashMap;
pub fn package_from_declarations(
p... |
pub fn define_module(&mut self, ix: ModuleIx, mod_repr: ModuleRepr) {
assert!(self.repr.names.is_valid(ix));
let pushed_ix = self.repr.modules.push(mod_repr);
assert_eq!(ix, pushed_ix);
}
pub fn build(self) -> Package {
self.repr
}
}
#[cfg(test)]
mod test {
use su... | {
&self.repr
} | identifier_body |
package.rs | use super::module::module_from_declarations;
use crate::error::ValidationError;
use crate::parser::PackageDecl;
use crate::prelude::std_module;
use crate::repr::{ModuleIx, ModuleRepr, Package};
use crate::Location;
use cranelift_entity::PrimaryMap;
use std::collections::HashMap;
pub fn | (
package_decls: &[PackageDecl],
) -> Result<Package, ValidationError> {
let mut pkg = PackageBuilder::new();
for decl in package_decls {
match decl {
PackageDecl::Module {
name,
location,
decls,
} => {
let modul... | package_from_declarations | identifier_name |
profile-options.component.ts | import { Component, OnInit } from '@angular/core';
import { OptionsComponent } from '../options.component';
import { takeUntil } from 'rxjs/operators';
@Component({ | })
export class ProfileOptionsComponent extends OptionsComponent implements OnInit {
ngOnInit() {
this.profile.$featureTypeChange.pipe(takeUntil(this.ngUnsubscribe)).subscribe(res => {
console.log('onFeatureTypeChange:', res);
});
}
updateSelectedFeature(feature) {
console.log('updateSelectedFe... | selector: 'app-profile-options',
templateUrl: './profile-options.component.html',
styleUrls: ['./profile-options.component.scss']
// styleUrls: ['../../options/options.component.scss', './profile-options.component.scss'] | random_line_split |
profile-options.component.ts | import { Component, OnInit } from '@angular/core';
import { OptionsComponent } from '../options.component';
import { takeUntil } from 'rxjs/operators';
@Component({
selector: 'app-profile-options',
templateUrl: './profile-options.component.html',
styleUrls: ['./profile-options.component.scss']
// styleUrls: ['... |
this.profile.updateProfileFeature(feature);
// this.seeyond.updateSeeyondFeature(feature);zz
}
dimensionsDidChange() {
console.log('dimensionsDidChange');
// this.seeyond.setMaxMinDimensions();
// this.seeyond.updateDimensions();
}
seeyondValidateOptions() {
console.log('seeyondValid... | {
if (this.router.url.indexOf('tiles') < 0) {
this.location.go(`${this.router.url}/tiles/${feature}`);
}
} | conditional_block |
profile-options.component.ts | import { Component, OnInit } from '@angular/core';
import { OptionsComponent } from '../options.component';
import { takeUntil } from 'rxjs/operators';
@Component({
selector: 'app-profile-options',
templateUrl: './profile-options.component.html',
styleUrls: ['./profile-options.component.scss']
// styleUrls: ['... |
updateSelectedFeature(feature) {
console.log('updateSelectedFeature:', feature);
if (this.profile.tilesFeatures.includes(feature)) {
if (this.router.url.indexOf('tiles') < 0) {
this.location.go(`${this.router.url}/tiles/${feature}`);
}
}
this.profile.updateProfileFeature(feature)... | {
this.profile.$featureTypeChange.pipe(takeUntil(this.ngUnsubscribe)).subscribe(res => {
console.log('onFeatureTypeChange:', res);
});
} | identifier_body |
profile-options.component.ts | import { Component, OnInit } from '@angular/core';
import { OptionsComponent } from '../options.component';
import { takeUntil } from 'rxjs/operators';
@Component({
selector: 'app-profile-options',
templateUrl: './profile-options.component.html',
styleUrls: ['./profile-options.component.scss']
// styleUrls: ['... | (feature) {
console.log('updateSelectedFeature:', feature);
if (this.profile.tilesFeatures.includes(feature)) {
if (this.router.url.indexOf('tiles') < 0) {
this.location.go(`${this.router.url}/tiles/${feature}`);
}
}
this.profile.updateProfileFeature(feature);
// this.seeyond.up... | updateSelectedFeature | identifier_name |
grove_thumb_joystick.py | #!/usr/bin/env python
#
# Jetduino Example for using the Grove Thumb Joystick (http://www.seeedstudio.com/wiki/Grove_-_Thumb_Joystick)
#
# The Jetduino connects the Jetson and Grove sensors. You can learn more about the Jetduino here: http://www.NeuroRoboticTech.com/Projects/Jetduino
#
# Have a question about t... | try:
# Get X/Y coordinates
x = jetduino.analogRead(xPin)
y = jetduino.analogRead(yPin)
# Calculate X/Y resistance
Rx = (float)(1023 - x) * 10 / x
Ry = (float)(1023 - y) * 10 / y
# Was a click detected on the X axis?
click = 1 if x >= 1020 else ... | conditional_block | |
grove_thumb_joystick.py | #!/usr/bin/env python
#
# Jetduino Example for using the Grove Thumb Joystick (http://www.seeedstudio.com/wiki/Grove_-_Thumb_Joystick)
#
# The Jetduino connects the Jetson and Grove sensors. You can learn more about the Jetduino here: http://www.NeuroRoboticTech.com/Projects/Jetduino
#
# Have a question about t... | while True:
try:
# Get X/Y coordinates
x = jetduino.analogRead(xPin)
y = jetduino.analogRead(yPin)
# Calculate X/Y resistance
Rx = (float)(1023 - x) * 10 / x
Ry = (float)(1023 - y) * 10 / y
# Was a click detected on the X axis?
click = 1 i... | # My Joystick
# Min Typ Max Click
# X 253 513 766 1020-1023
# Y 250 505 769
| random_line_split |
2-1-literals.rs | fn main() | {
// Addition with unsigned integer
println!("1 + 3 = {}", 1u32 + 3);
// Subtraction with signed integer
// Rust refuses to compile if there is an overflow
println!("1 - 3 = {}", 1i32 - 3);
// Boolean logic
println!("true AND false is {}", true && false);
println!("true OR false is {}"... | identifier_body | |
2-1-literals.rs | fn | () {
// Addition with unsigned integer
println!("1 + 3 = {}", 1u32 + 3);
// Subtraction with signed integer
// Rust refuses to compile if there is an overflow
println!("1 - 3 = {}", 1i32 - 3);
// Boolean logic
println!("true AND false is {}", true && false);
println!("true OR false is ... | main | identifier_name |
2-1-literals.rs | fn main() {
// Addition with unsigned integer | // Rust refuses to compile if there is an overflow
println!("1 - 3 = {}", 1i32 - 3);
// Boolean logic
println!("true AND false is {}", true && false);
println!("true OR false is {}", true || false);
println!("NOT false is {}", !true);
// Bitwise operations
println!("0110 AND 0011 is {:... | println!("1 + 3 = {}", 1u32 + 3);
// Subtraction with signed integer | random_line_split |
timer.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use std::time::{Duration, Instant};
use gotham::state::State;
use gotham_derive::StateData;
use hyper::{Body, Response};
use super::Middl... |
}
}
| {
let headers_duration = start.elapsed();
state.put(HeadersDuration(headers_duration));
} | conditional_block |
timer.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use std::time::{Duration, Instant};
use gotham::state::State;
use gotham_derive::StateData;
use hyper::{Body, Response};
use super::Middl... | #[async_trait::async_trait]
impl Middleware for TimerMiddleware {
async fn inbound(&self, state: &mut State) -> Option<Response<Body>> {
state.put(RequestStartTime(Instant::now()));
None
}
async fn outbound(&self, state: &mut State, _response: &mut Response<Body>) {
if let Some(Requ... | random_line_split | |
timer.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use std::time::{Duration, Instant};
use gotham::state::State;
use gotham_derive::StateData;
use hyper::{Body, Response};
use super::Middl... | (pub Instant);
#[derive(StateData, Debug, Copy, Clone)]
pub struct HeadersDuration(pub Duration);
#[derive(Clone)]
pub struct TimerMiddleware;
impl TimerMiddleware {
pub fn new() -> Self {
TimerMiddleware
}
}
#[async_trait::async_trait]
impl Middleware for TimerMiddleware {
async fn inbound(&sel... | RequestStartTime | identifier_name |
ReportView_test.ts | // Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import * as ReportView from '../../../../../front_end/ui/components/report_view/report_view.js';
import * as LitHtml from '../../../../../front_end/ui/lit... |
const slot = getElementWithinComponent(report, 'slot', HTMLSlotElement);
const keyElement = report.querySelector('devtools-report-key');
const valueElement = report.querySelector('devtools-report-value');
assert.strictEqual(slot.assignedElements()[0], keyElement);
assert.strictEqual(slot... | report);
renderElementIntoDOM(report); | random_line_split |
ChangeSet.py | # Copyright (C) 2010-2011 Richard Lincoln
#
# 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, publish... | (self, NetworkDataSets=None, ChangeItems=None, status=None, Documents=None, *args, **kw_args):
"""Initialises a new 'ChangeSet' instance.
@param NetworkDataSets:
@param ChangeItems:
@param status:
@param Documents:
"""
self._NetworkDataSets = []
self.Netw... | __init__ | identifier_name |
ChangeSet.py | # Copyright (C) 2010-2011 Richard Lincoln
#
# 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, publish... | def getChangeItems(self):
return self._ChangeItems
def setChangeItems(self, value):
for x in self._ChangeItems:
x.ChangeSet = None
for y in value:
y._ChangeSet = self
self._ChangeItems = value
ChangeItems = property(getChangeItems, setChange... | random_line_split | |
ChangeSet.py | # Copyright (C) 2010-2011 Richard Lincoln
#
# 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, publish... |
status = None
def getDocuments(self):
return self._Documents
def setDocuments(self, value):
for p in self._Documents:
filtered = [q for q in p.ChangeSets if q != self]
self._Documents._ChangeSets = filtered
for r in value:
if self not ... | for obj in ChangeItems:
obj.ChangeSet = None | identifier_body |
ChangeSet.py | # Copyright (C) 2010-2011 Richard Lincoln
#
# 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, publish... |
self._NetworkDataSets = value
NetworkDataSets = property(getNetworkDataSets, setNetworkDataSets)
def addNetworkDataSets(self, *NetworkDataSets):
for obj in NetworkDataSets:
if self not in obj._ChangeSets:
obj._ChangeSets.append(self)
self._NetworkDataSe... | if self not in r._ChangeSets:
r._ChangeSets.append(self) | conditional_block |
filter_profile.rs | #!/bin/bash
#![forbid(unsafe_code)]/* This line is ignored by bash
# This block is ignored by rustc
pushd $(dirname "$0")/../
source scripts/config.sh
RUSTC="$(pwd)/build/bin/cg_clif"
popd
PROFILE=$1 OUTPUT=$2 exec $RUSTC -Zunstable-options -Cllvm-args=mode=jit -Cprefer-dynamic $0
#*/
//! This program filters away uni... |
const FREE: &str = "free";
if let Some(index) = stack.find(FREE) {
stack = &stack[..index + FREE.len()];
}
const TYPECK_ITEM_BODIES: &str = "rustc_typeck::check::typeck_item_bodies";
if let Some(index) = stack.find(TYPECK_ITEM_BODIES) {
stack = &stack[..... | stack = &stack[..index + MALLOC.len()];
} | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.