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 |
|---|---|---|---|---|
bert_embeddings.py | """Contains function for calculating BERT embeddings"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
import json
import re
import torch
from torch.utils.data import TensorDataset, DataLoader, SequentialSampler
from torch.utils.data.dis... | self.unique_id = unique_id
self.tokens = tokens
self.input_ids = input_ids
self.input_mask = input_mask
self.input_type_ids = input_type_ids | identifier_body | |
generate-plugin-docs.ts | /**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
*/
import fs from 'fs-extra';
import path from 'path';
const repoRoot = path.resolve(__dirname, '..');
const pluginsD... | () {
await Promise.all([fs.emptyDir(generatedPluginsDocsDir), fs.emptyDir(generatedPluginsSetupDocsDir), fs.emptyDir(generatedPluginSymlinksDir)]);
const publicDirs = (await fs.readdir(pluginsDir)).map(dir => path.join(pluginsDir, dir));
const fbDirs = process.env.FB_INTERNAL ? (await fs.readdir(fbPluginsDir)).ma... | generatePluginDocs | identifier_name |
generate-plugin-docs.ts | /**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
*/
import fs from 'fs-extra';
import path from 'path';
const repoRoot = path.resolve(__dirname, '..');
const pluginsD... | }); | random_line_split | |
generate-plugin-docs.ts | /**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
*/
import fs from 'fs-extra';
import path from 'path';
const repoRoot = path.resolve(__dirname, '..');
const pluginsD... | const id = name.replace('flipper-plugin-', '');
const generatedPluginResourcesPath = path.join(generatedPluginSymlinksDir, id);
await fs.symlink(pluginSourceDocsDir, generatedPluginResourcesPath, 'junction');
const setupDocPath = path.join(pluginSourceDocsDir, 'setup.mdx');
const set... | {
await Promise.all([fs.emptyDir(generatedPluginsDocsDir), fs.emptyDir(generatedPluginsSetupDocsDir), fs.emptyDir(generatedPluginSymlinksDir)]);
const publicDirs = (await fs.readdir(pluginsDir)).map(dir => path.join(pluginsDir, dir));
const fbDirs = process.env.FB_INTERNAL ? (await fs.readdir(fbPluginsDir)).map(d... | identifier_body |
generate-plugin-docs.ts | /**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
*/
import fs from 'fs-extra';
import path from 'path';
const repoRoot = path.resolve(__dirname, '..');
const pluginsD... | `---
id: ${id}
title: ${title} Plugin Setup
sidebar_label: ${title}
custom_edit_url: ${customEditUrl}
---
import Article from '${relativePluginSymlinksDir}/${id}/setup.mdx';
<Article />
`,
);
}
if (overviewDocsExists) {
const customEditUrl = `${repoUrl}/${path.relative(repoRoot, ... | {
console.log(`Found docs in ${pluginSourceDir}`);
const packageJson = await fs.readJson(packageJsonPath);
const name: string = packageJson.name;
const title: string = packageJson.title;
const id = name.replace('flipper-plugin-', '');
const generatedPluginResourcesPath = path.join(ge... | conditional_block |
destroy.spec.ts | import { expect } from 'chai';
const ng = require('../helpers/ng');
const tmp = require('../helpers/tmp');
const SilentError = require('silent-error');
describe('Acceptance: ng destroy', function () {
beforeEach(function () {
this.timeout(10000);
return tmp.setup('./tmp').then(function () {
process.ch... |
afterEach(function () {
return tmp.teardown('./tmp');
});
it('without args should fail', function () {
return ng(['destroy']).then(() => {
throw new SilentError('ng destroy should fail.');
}, (err: any) => {
expect(err.message).to.equal('The destroy command is not supported by Angular CL... | });
}); | random_line_split |
segment-timeline.tsx | DEFAULT_TIME_SPAN_MONTHS,
loading: true,
xScale: null,
yScale: null,
dEnd: dEnd,
dStart: dStart,
};
this.dataQueryManager =
props.dataQueryManager ||
new QueryManager({
processQuery: async ({ capabilities, timeSpan }) => {
let intervals: IntervalRow[... | random_line_split | ||
segment-timeline.tsx | end: string;
datasource: string;
count: number;
size: number;
}
const DEFAULT_TIME_SPAN_MONTHS = 3;
export class SegmentTimeline extends React.PureComponent<
SegmentTimelineProps,
SegmentTimelineState
> {
static COLORS = [
'#b33040',
'#d25c4d',
'#f2b447',
'#d9d574',
'#4FAA7E',
'#5... | count,
size,
};
})
.filter(a => beforeIso < a.start);
}),
))
.flat()
.sort((a, b) => b.start.localeCompare(a.start));
}
else {
throw new Error(... | {
const before = new Date();
before.setMonth(before.getMonth() - timeSpan);
const beforeIso = before.toISOString();
datasources = (await axios.get(`/druid/coordinator/v1/datasources`)).data;
intervals = (await Promise.all(
datasources.map(async ... | conditional_block |
segment-timeline.tsx | end: string;
datasource: string;
count: number;
size: number;
}
const DEFAULT_TIME_SPAN_MONTHS = 3;
export class SegmentTimeline extends React.PureComponent<
SegmentTimelineProps,
SegmentTimelineState
> {
static COLORS = [
'#b33040',
'#d25c4d',
'#f2b447',
'#d9d574',
'#4FAA7E',
'#5... | (data: IntervalRow[]) {
if (data === null) return [];
const countData: Record<string, any> = {};
const sizeData: Record<string, any> = {};
data.forEach(entry => {
const start = entry.start;
const day = start.split('T')[0];
const datasource = entry.datasource;
const count = entry... | processRawData | identifier_name |
segment-timeline.tsx | end: string;
datasource: string;
count: number;
size: number;
}
const DEFAULT_TIME_SPAN_MONTHS = 3;
export class SegmentTimeline extends React.PureComponent<
SegmentTimelineProps,
SegmentTimelineState
> {
static COLORS = [
'#b33040',
'#d25c4d',
'#f2b447',
'#d9d574',
'#4FAA7E',
'#5... | singleDatasourceData[dataType][datasource] = dataResult;
}
});
});
return singleDatasourceData;
}
private dataQueryManager: QueryManager<{ capabilities: Capabilities; timeSpan: number }, any>;
private chartMargin = { top: 20, right: 10, bottom: 20, left: 10 };
constructor(pro... | {
const singleDatasourceData: Record<string, Record<string, BarUnitData[]>> = {};
Object.keys(data).forEach(dataType => {
singleDatasourceData[dataType] = {};
datasources.forEach((datasource, i) => {
const currentData = data[dataType];
if (currentData.length === 0) return;
co... | identifier_body |
lib.rs | //! # Rocket - Code Generation
//!
//! This crate implements the code generation portions of Rocket. This includes
//! custom derives, custom attributes, procedural macros, and lints. The
//! documentation here is purely technical. The code generation facilities are
//! documented thoroughly in the [Rocket programming
... | //! URI_SEG := Valid HTTP URI Segment
//! DYNAMIC_PARAM := '<' IDENT '..'? '>' (string literal)
//! </pre>
//!
//! Note that the **route** attribute takes a method as its first argument,
//! while the remaining do not. That is, **route** looks like:
//!
//! #[route(GET, path = "/hello")]
//!
//! while the equivalen... | //!
//! INTEGER := isize, as defined by Rust
//! STRING := UTF-8 string literal, as defined by Rust
//! IDENT := Valid identifier, as defined by Rust
//! | random_line_split |
lib.rs | //! # Rocket - Code Generation
//!
//! This crate implements the code generation portions of Rocket. This includes
//! custom derives, custom attributes, procedural macros, and lints. The
//! documentation here is purely technical. The code generation facilities are
//! documented thoroughly in the [Rocket programming
... |
reg.register_macro("routes", macros::routes);
reg.register_macro("errors", macros::errors);
register_derives!(reg,
"derive_FromForm" => from_form_derive
);
register_decorators!(reg,
"error" => error_decorator,
"route" => route_decorator,
"get" => get_decorator,
... | {
::rocket::logger::init(::rocket::LoggingLevel::Debug);
} | conditional_block |
lib.rs | //! # Rocket - Code Generation
//!
//! This crate implements the code generation portions of Rocket. This includes
//! custom derives, custom attributes, procedural macros, and lints. The
//! documentation here is purely technical. The code generation facilities are
//! documented thoroughly in the [Rocket programming
... | "head" => head_decorator,
"patch" => patch_decorator,
"options" => options_decorator
);
register_lints!(reg, RocketLint);
}
| {
// Enable logging early if the DEBUG_ENV_VAR is set.
if env::var(DEBUG_ENV_VAR).is_ok() {
::rocket::logger::init(::rocket::LoggingLevel::Debug);
}
reg.register_macro("routes", macros::routes);
reg.register_macro("errors", macros::errors);
register_derives!(reg,
"derive_FromFo... | identifier_body |
lib.rs | //! # Rocket - Code Generation
//!
//! This crate implements the code generation portions of Rocket. This includes
//! custom derives, custom attributes, procedural macros, and lints. The
//! documentation here is purely technical. The code generation facilities are
//! documented thoroughly in the [Rocket programming
... | (reg: &mut Registry) {
// Enable logging early if the DEBUG_ENV_VAR is set.
if env::var(DEBUG_ENV_VAR).is_ok() {
::rocket::logger::init(::rocket::LoggingLevel::Debug);
}
reg.register_macro("routes", macros::routes);
reg.register_macro("errors", macros::errors);
register_derives!(reg,
... | plugin_registrar | identifier_name |
bgOtpDevicesDirective.js | /**
* @ngdoc directive
* @name bgOtpDevicesDirective
* @description
* Directive to provide otp information on scope
* @example
* <div bg-otp-devices></div>
*/
angular.module('BitGo.Common.BGOtpDevicesDirective', [])
.directive('bgOtpDevices', ['$rootScope', '$modal', '$location', '$q', 'BG_DEV', 'UtilityServi... |
$scope.twoFactorMethod = method;
// Track the method selected
var metricsData = {
method: method
};
AnalyticsProxy.track('SelectOtpMethod', metricsData);
};
/**
* UI - retrieves relevant params from scope and returns a params obj... | {
throw new Error('invalid method');
} | conditional_block |
bgOtpDevicesDirective.js | /**
* @ngdoc directive
* @name bgOtpDevicesDirective
* @description
* Directive to provide otp information on scope
* @example
* <div bg-otp-devices></div>
*/
angular.module('BitGo.Common.BGOtpDevicesDirective', [])
.directive('bgOtpDevices', ['$rootScope', '$modal', '$location', '$q', 'BG_DEV', 'UtilityServi... |
/**
* Handles error states associated with attempting to add a device
* @private
*/
function handleAddDeviceError(error) {
if (error.message === 'device is already registered') {
return Notify.error('This device is already registered');
}
... | {
if (Util.API.isOtpError(error)) {
// If the user needs to OTP, use the modal to unlock their account
return openModal({ type: BG_DEV.MODAL_TYPES.otp })
.then(function(result) {
if (result.type === 'otpsuccess') {
// automatically resubmit the... | identifier_body |
bgOtpDevicesDirective.js | /**
* @ngdoc directive
* @name bgOtpDevicesDirective
* @description
* Directive to provide otp information on scope
* @example
* <div bg-otp-devices></div>
*/
angular.module('BitGo.Common.BGOtpDevicesDirective', [])
.directive('bgOtpDevices', ['$rootScope', '$modal', '$location', '$q', 'BG_DEV', 'UtilityServi... | () {
$scope.initFormFields('removed');
$scope.setTemplate('twoStepVerificationList');
Notify.success('Two-step verification device successfully removed');
}
// Set user to the twoStepVerificationSelect page
$scope.setTwoStepVerificationSelect = function() {
... | handleRemoveDeviceSuccess | identifier_name |
bgOtpDevicesDirective.js | /**
* @ngdoc directive
* @name bgOtpDevicesDirective
* @description
* Directive to provide otp information on scope
* @example
* <div bg-otp-devices></div>
*/
angular.module('BitGo.Common.BGOtpDevicesDirective', [])
.directive('bgOtpDevices', ['$rootScope', '$modal', '$location', '$q', 'BG_DEV', 'UtilityServic... | if ($rootScope.currentUser.settings.phone.phone) {
return true;
}
return false;
};
$scope.getOtpParams = function(otpDeviceType) {
switch(otpDeviceType) {
case 'totp':
return {
type: 'totp',
o... | * @public
*/
$scope.userHasPhone = function () { | random_line_split |
0004_migrate_data_20190508.py | import re
from django.db import migrations
def add_project_member(apps, schema_editor):
# Using historical versions as recommended for RunPython
PublicDataAccess = apps.get_model("public_data", "PublicDataAccess")
DataRequestProjectMember = apps.get_model(
"private_sharing", "DataRequestProjectMe... |
for pda in PublicDataAccess.objects.using(db_alias).filter(project_membership=None):
project = id_label_to_project(pda.data_source)
drpm = DataRequestProjectMember.objects.using(db_alias).get(
project=project, member=pda.participant.member
)
pda.project_membership = drp... | project = DataRequestProject.objects.using(db_alias).get(
id=int(match.group("id"))
)
return project | conditional_block |
0004_migrate_data_20190508.py | import re
from django.db import migrations
def add_project_member(apps, schema_editor):
# Using historical versions as recommended for RunPython
PublicDataAccess = apps.get_model("public_data", "PublicDataAccess")
DataRequestProjectMember = apps.get_model(
"private_sharing", "DataRequestProjectMe... | match = re.match(r"direct-sharing-(?P<id>\d+)", id_label)
if match:
project = DataRequestProject.objects.using(db_alias).get(
id=int(match.group("id"))
)
return project
for pda in PublicDataAccess.objects.using(db_alias).filter(project_membership=... | random_line_split | |
0004_migrate_data_20190508.py | import re
from django.db import migrations
def add_project_member(apps, schema_editor):
# Using historical versions as recommended for RunPython
PublicDataAccess = apps.get_model("public_data", "PublicDataAccess")
DataRequestProjectMember = apps.get_model(
"private_sharing", "DataRequestProjectMe... | dependencies = [("public_data", "0003_auto_20190508_2341")]
operations = [migrations.RunPython(add_project_member, set_data_source)] | identifier_body | |
0004_migrate_data_20190508.py | import re
from django.db import migrations
def add_project_member(apps, schema_editor):
# Using historical versions as recommended for RunPython
PublicDataAccess = apps.get_model("public_data", "PublicDataAccess")
DataRequestProjectMember = apps.get_model(
"private_sharing", "DataRequestProjectMe... | (id_label):
match = re.match(r"direct-sharing-(?P<id>\d+)", id_label)
if match:
project = DataRequestProject.objects.using(db_alias).get(
id=int(match.group("id"))
)
return project
for pda in PublicDataAccess.objects.using(db_alias).filter(project... | id_label_to_project | identifier_name |
project.rs | use rustc_serialize::json;
use dao::ProtonDao;
use error::Error;
use project_types::{Project, SequenceData};
use utils;
/// Creates a new Proton project. Returns the public key of the root user.
pub fn new_project<PD: ProtonDao>(
dao: &PD,
name: &str,
layout_id: u32
) -> Result<String, Error> {
// C... |
println!("Channel ids loaded.");
print!("Getting data...");
// Create vector for sequence data
// Up to 512 channels per universe, plus one because DMX starts at 1
let mut seq_data = vec![vec![0; sequence.num_frames as usize]; 513];
// Get each channel's data and put ... | {
// TODO: make error
println!("No channels found");
panic!("No channels found");
} | conditional_block |
project.rs | use rustc_serialize::json;
use dao::ProtonDao;
use error::Error;
use project_types::{Project, SequenceData};
use utils;
/// Creates a new Proton project. Returns the public key of the root user.
pub fn new_project<PD: ProtonDao>(
dao: &PD,
name: &str,
layout_id: u32
) -> Result<String, Error> {
// C... | <PD: ProtonDao> (
dao: &PD,
proj_name: &str
) -> Result<String, Error> {
// Check that project exists
let project = try!(dao.get_project(proj_name));
let mut playlist_data = Vec::with_capacity(project.playlist.len());
// Go through each sequence in the playlist
for seqid in project.playli... | get_playlist_data | identifier_name |
project.rs | use rustc_serialize::json;
use dao::ProtonDao;
use error::Error;
use project_types::{Project, SequenceData};
use utils;
/// Creates a new Proton project. Returns the public key of the root user.
pub fn new_project<PD: ProtonDao>(
dao: &PD,
name: &str,
layout_id: u32
) -> Result<String, Error> {
// C... | // Get each channel's data and put it in the correct vector slot
for chanid in chan_ids {
let channel = try!(dao.get_channel(chanid));
let chan_data = try!(dao.get_data(seqid.to_owned(), chanid.to_owned()));
seq_data[channel.channel_dmx as usize] = chan_data;
... |
// Create vector for sequence data
// Up to 512 channels per universe, plus one because DMX starts at 1
let mut seq_data = vec![vec![0; sequence.num_frames as usize]; 513];
| random_line_split |
project.rs | use rustc_serialize::json;
use dao::ProtonDao;
use error::Error;
use project_types::{Project, SequenceData};
use utils;
/// Creates a new Proton project. Returns the public key of the root user.
pub fn new_project<PD: ProtonDao>(
dao: &PD,
name: &str,
layout_id: u32
) -> Result<String, Error> {
// C... |
if chan_ids.len() < 1 {
// TODO: make error
println!("No channels found");
panic!("No channels found");
}
println!("Channel ids loaded.");
print!("Getting data...");
// Create vector for sequence data
// Up to 512 channels per univer... | {
// Check that project exists
let project = try!(dao.get_project(proj_name));
let mut playlist_data = Vec::with_capacity(project.playlist.len());
// Go through each sequence in the playlist
for seqid in project.playlist.iter() {
print!("Getting sequence {}...", seqid);
// Get s... | identifier_body |
12.06.2016.updated_page_created_at_to_utc.py | """
ONE-TIME UPDATE OF converting SubredditPage.created_at, FrontPage.created_at to utc
Daylight Savings Time = Nov 6 2am
if we see the ET time Nov 6 12am, then it is EDT: EDT-->UTC = +4 = Nov 6 4am
if we see the ET time Nov 6 1-2am, then it is unclear whether it is EDT or EST; assume it is EST
> assumption is bec... |
post.created_at = created_at_utc
post.is_utc = True
num_updated_posts += 1
last_et_time_utc = max([last_et_time_utc, created_at_utc])
print("Updating created_at for {0} posts; updated created_at to UTC up to time {1}; DST found up to time {2}; num_confusing_et_times: {3}".format(num_updated_posts, last_et... | if created_at_et < DST_LIMIT_ET + datetime.timedelta(hours=1):
# if between 1am and 2am on Nov 6
num_confusing_et_times += 1
created_at_utc = created_at_et - EST_TO_UTC | conditional_block |
12.06.2016.updated_page_created_at_to_utc.py | """
ONE-TIME UPDATE OF converting SubredditPage.created_at, FrontPage.created_at to utc
Daylight Savings Time = Nov 6 2am
if we see the ET time Nov 6 12am, then it is EDT: EDT-->UTC = +4 = Nov 6 4am
if we see the ET time Nov 6 1-2am, then it is unclear whether it is EDT or EST; assume it is EST
> assumption is bec... | num_updated_posts += 1
last_et_time_utc = max([last_et_time_utc, created_at_utc])
print("Updating created_at for {0} posts; updated created_at to UTC up to time {1}; DST found up to time {2}; num_confusing_et_times: {3}".format(num_updated_posts, last_et_time_utc, last_edt_time, num_confusing_et_times))
db_sess... | post.created_at = created_at_utc
post.is_utc = True | random_line_split |
switch.py | """Support for WeMo switches."""
import asyncio
import logging
from datetime import datetime, timedelta
import requests
import async_timeout
from homeassistant.components.switch import SwitchDevice
from homeassistant.exceptions import PlatformNotReady
from homeassistant.util import convert
from homeassistant.const im... |
# Is the maker switch configured as toggle(0) or momentary (1).
if self.maker_params['switchmode']:
attr[ATTR_SWITCH_MODE] = MAKER_SWITCH_MOMENTARY
else:
attr[ATTR_SWITCH_MODE] = MAKER_SWITCH_TOGGLE
if self.insight_params or (self.coffeemake... | if self.maker_params['sensorstate']:
attr[ATTR_SENSOR_STATE] = STATE_OFF
else:
attr[ATTR_SENSOR_STATE] = STATE_ON | conditional_block |
switch.py | """Support for WeMo switches."""
import asyncio
import logging
from datetime import datetime, timedelta
import requests
import async_timeout
from homeassistant.components.switch import SwitchDevice
from homeassistant.exceptions import PlatformNotReady
from homeassistant.util import convert
from homeassistant.const im... | self.maker_params = None
self.coffeemaker_mode = None
self._state = None
self._mode_string = None
self._available = True
self._update_lock = None
self._model_name = self.wemo.model_name
self._name = self.wemo.name
self._serialnumber = self.wemo.ser... | """Initialize the WeMo switch."""
self.wemo = device
self.insight_params = None | random_line_split |
switch.py | """Support for WeMo switches."""
import asyncio
import logging
from datetime import datetime, timedelta
import requests
import async_timeout
from homeassistant.components.switch import SwitchDevice
from homeassistant.exceptions import PlatformNotReady
from homeassistant.util import convert
from homeassistant.const im... | (self):
"""Return the today total energy usage in kWh."""
if self.insight_params:
miliwatts = convert(self.insight_params['todaymw'], float, 0.0)
return round(miliwatts / (1000.0 * 1000.0 * 60), 2)
@property
def detail_state(self):
"""Return the state of the devi... | today_energy_kwh | identifier_name |
switch.py | """Support for WeMo switches."""
import asyncio
import logging
from datetime import datetime, timedelta
import requests
import async_timeout
from homeassistant.components.switch import SwitchDevice
from homeassistant.exceptions import PlatformNotReady
from homeassistant.util import convert
from homeassistant.const im... |
def turn_off(self, **kwargs):
"""Turn the switch off."""
self.wemo.off()
async def async_added_to_hass(self):
"""Wemo switch added to HASS."""
# Define inside async context so we know our event loop
self._update_lock = asyncio.Lock()
registry = SUBSCRIPTION_RE... | """Turn the switch on."""
self.wemo.on() | identifier_body |
transaction.rs | control *when* a state become active. This file is the second
// half: these identified states are grouped into transactions, which allow the
// synchronization of updates accross surfaces.
//
// There are 2 main cases when the state of multiple surfaces must be updated
// atomically:
// - synchronized subsurface must... | impl TransactionState {
fn insert(&mut self, surface: WlSurface, id: Serial) {
if let Some(place) = self.surfaces.iter_mut().find(|place| place.0 == surface) {
// the surface is already in the list, update the serial
if place.1 < id {
place.1 = id;
}
... | blockers: Vec::new(),
}
}
}
| random_line_split |
transaction.rs |
// and are all applied atomically when the transaction itself is applied. The logic for creating
// new transactions is currently the following:
//
// - Each surface has an implicit "pending" transaction, into which its newly commited state is
// recorded
// - Furthermore, on commit, the pending transaction of all s... | {
// this transaction is to be applied, yay!
self.transactions.remove(i).apply();
} | conditional_block | |
transaction.rs | *when* a state become active. This file is the second
// half: these identified states are grouped into transactions, which allow the
// synchronization of updates accross surfaces.
//
// There are 2 main cases when the state of multiple surfaces must be updated
// atomically:
// - synchronized subsurface must have th... |
pub(crate) fn is_same_as(&self, other: &PendingTransaction) -> bool {
let ptr1 = self.with_inner_state(|state| state as *const _);
let ptr2 = other.with_inner_state(|state| state as *const _);
ptr1 == ptr2
}
pub(crate) fn merge_into(&self, into: &PendingTransaction) {
if s... | {
self.with_inner_state(|state| state.blockers.push(Box::new(blocker) as Box<_>))
} | identifier_body |
transaction.rs | *when* a state become active. This file is the second
// half: these identified states are grouped into transactions, which allow the
// synchronization of updates accross surfaces.
//
// There are 2 main cases when the state of multiple surfaces must be updated
// atomically:
// - synchronized subsurface must have th... | {
surfaces: Vec<(WlSurface, Serial)>,
blockers: Vec<Box<dyn Blocker + Send>>,
}
impl Default for TransactionState {
fn default() -> Self {
TransactionState {
surfaces: Vec::new(),
blockers: Vec::new(),
}
}
}
impl TransactionState {
fn insert(&mut self, surf... | TransactionState | identifier_name |
ParameterTrackModel.js | module.exports = (function() {
function ParameterTrackModel(parameter, dataModel) | this.parameterTrack.render();
};
this.getParameter = function() {
return this.parameter;
};
this.setParameterTrack = function(parameterTrack) {
this.parameterTrack = parameterTrack;
};
this.getRange = function() {
return {
min: this.dataModel.getMin(parameter),... | {
this.parameter = parameter;
this.dataModel = dataModel;
this.graphColumn = undefined;
dataModel.addListener(this);
// Returns an array with parameter value objects
this.getParameterPath = function() {
return this.dataModel.getValuesForParameter(this.parameter);
};
this.rangeCha... | identifier_body |
ParameterTrackModel.js | module.exports = (function() {
function | (parameter, dataModel) {
this.parameter = parameter;
this.dataModel = dataModel;
this.graphColumn = undefined;
dataModel.addListener(this);
// Returns an array with parameter value objects
this.getParameterPath = function() {
return this.dataModel.getValuesForParameter(this.parameter);
... | ParameterTrackModel | identifier_name |
ParameterTrackModel.js | module.exports = (function() {
function ParameterTrackModel(parameter, dataModel) {
this.parameter = parameter;
this.dataModel = dataModel;
this.graphColumn = undefined;
dataModel.addListener(this);
// Returns an array with parameter value objects
this.getParameterPath = function() {
re... | this.parameterTrack.drawMarkerLine(yCoord);
};
};
return ParameterTrackModel;
})(); |
this.updateMarkerLine = function(yCoord) { | random_line_split |
currency.js | dojo.provide("tests.currency");
dojo.require("dojo.currency");
tests.register("tests.currency",
[
{
// Test formatting and parsing of currencies in various locales pre-built in dojo.cldr
// NOTE: we can't set djConfig.extraLocale before bootstrapping unit tests, so directly
// load resources here for spe... |
},
runTest: function(t){
t.is("\u20ac123.45", dojo.currency.format(123.45, {currency: "EUR", locale: "en-us"}));
t.is("$123.45", dojo.currency.format(123.45, {currency: "USD", locale: "en-us"}));
t.is("$1,234.56", dojo.currency.format(1234.56, {currency: "USD", locale: "en-us"}));
t.is("US$123.45... | {
dojo.requireLocalization("dojo.cldr","currency",partLocaleList[i]);
dojo.requireLocalization("dojo.cldr","number",partLocaleList[i]);
} | conditional_block |
currency.js | dojo.provide("tests.currency");
dojo.require("dojo.currency");
tests.register("tests.currency",
[
{ | // Test formatting and parsing of currencies in various locales pre-built in dojo.cldr
// NOTE: we can't set djConfig.extraLocale before bootstrapping unit tests, so directly
// load resources here for specific locales:
name: "currency",
setUp: function(){
var partLocaleList = ["en-us", "en-ca", "de... | random_line_split | |
get_variable_length_field.rs | // Copyright (c) 2015 Robert Clipsham <robert@octarineparrot.com>
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or... | fn main() {
let data = [1, 1, 1, 1, 2, 3, 4, 5, 6];
let packet = WithVariableLengthFieldPacket::new(&data[..]).unwrap();
assert_eq!(packet.get_var_length(), vec![2, 3, 4]);
} | payload: Vec<u8>
}
| random_line_split |
get_variable_length_field.rs | // Copyright (c) 2015 Robert Clipsham <robert@octarineparrot.com>
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or... | () {
let data = [1, 1, 1, 1, 2, 3, 4, 5, 6];
let packet = WithVariableLengthFieldPacket::new(&data[..]).unwrap();
assert_eq!(packet.get_var_length(), vec![2, 3, 4]);
}
| main | identifier_name |
get_variable_length_field.rs | // Copyright (c) 2015 Robert Clipsham <robert@octarineparrot.com>
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or... | {
let data = [1, 1, 1, 1, 2, 3, 4, 5, 6];
let packet = WithVariableLengthFieldPacket::new(&data[..]).unwrap();
assert_eq!(packet.get_var_length(), vec![2, 3, 4]);
} | identifier_body | |
attrib.rs | // rustfmt-wrap_comments: true
// Test attributes and doc comments are preserved.
//! Doc comment
#![attribute]
//! Crate doc comment
// Comment
// Comment on attribute
#![the(attribute)]
// Another comment
#[invalid attribute]
fn foo() {}
/// Blah blah blah.
/// Blah blah blah.
/// Blah blah blah.
/// Blah bla... |
/// Blah blah bing.
#[attrib1]
/// Blah blah bing.
#[attrib2]
// Another comment that needs rewrite because it's tooooooooooooooooooooooooooooooo loooooooooooong.
/// Blah blah bing.
fn f4(self) -> Cat {
}
// We want spaces around `=`
#[cfg(feature="nightly")]
fn f5(self)... | {
} | identifier_body |
attrib.rs | // rustfmt-wrap_comments: true
// Test attributes and doc comments are preserved.
//! Doc comment
#![attribute]
//! Crate doc comment
// Comment
// Comment on attribute
#![the(attribute)]
// Another comment
#[invalid attribute]
fn foo() {}
/// Blah blah blah.
/// Blah blah blah.
/// Blah blah blah.
/// Blah bla... | #[test]
#[should_panic(expected = "(")]
#[should_panic(expected = /* ( */ "(")]
#[should_panic(/* ((((( */expected /* ((((( */= /* ((((( */ "("/* ((((( */)]
#[should_panic(
/* (((((((( *//*
(((((((((()(((((((( */
expected = "("
// ((((((((
)]
fn foo() {}
// #1799
fn issue_1799() {
#[allow(unreachab... |
// #1777 | random_line_split |
attrib.rs | // rustfmt-wrap_comments: true
// Test attributes and doc comments are preserved.
//! Doc comment
#![attribute]
//! Crate doc comment
// Comment
// Comment on attribute
#![the(attribute)]
// Another comment
#[invalid attribute]
fn foo() {}
/// Blah blah blah.
/// Blah blah blah.
/// Blah blah blah.
/// Blah bla... | (pub u8);
| HP | identifier_name |
drawUtilities.js | /// <reference path="_reference.js" />
"use strict";
var svgNameSpace = "http://www.w3.org/2000/svg";
function createSVG(id, width, height) {
var svg = document.createElementNS(svgNameSpace, "svg");
if (id) {
svg.setAttribute("id", id);
}
svg.setAttribute("width", width );
svg.setAttribute(... | return image;
}
function createText(x, y, fontSize, fontWeight, fontFamily, fill, value) {
var text;
text = document.createElementNS(svgNameSpace, 'text');
text.setAttribute('x', x);
text.setAttribute('y', y);
text.setAttribute('font-size', fontSize);
text.setAttribute('font-weight', fontWe... | image.setAttribute('width', width);
image.setAttribute('height', height);
image.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', href); | random_line_split |
drawUtilities.js | /// <reference path="_reference.js" />
"use strict";
var svgNameSpace = "http://www.w3.org/2000/svg";
function createSVG(id, width, height) {
var svg = document.createElementNS(svgNameSpace, "svg");
if (id) {
svg.setAttribute("id", id);
}
svg.setAttribute("width", width );
svg.setAttribute(... | var rect;
rect = document.createElementNS(svgNameSpace, 'rect');
rect.setAttribute('x', x);
rect.setAttribute('y', y);
rect.setAttribute('width', width);
rect.setAttribute('height', height);
rect.setAttribute('fill', fill);
rect.setAttribute('stroke', stroke);
return rect;
} | identifier_body | |
drawUtilities.js | /// <reference path="_reference.js" />
"use strict";
var svgNameSpace = "http://www.w3.org/2000/svg";
function createSVG(id, width, height) {
var svg = document.createElementNS(svgNameSpace, "svg");
if (id) {
| svg.setAttribute("width", width );
svg.setAttribute("height", height );
return svg;
}
function createPath(points, stroke, fill, strokeWidth) {
var path;
path = document.createElementNS(svgNameSpace, 'path');
path.setAttribute('d', points);
path.setAttribute('stroke', stroke);
path.setAtt... | svg.setAttribute("id", id);
}
| conditional_block |
drawUtilities.js | /// <reference path="_reference.js" />
"use strict";
var svgNameSpace = "http://www.w3.org/2000/svg";
function createSVG(id, width, height) {
var svg = document.createElementNS(svgNameSpace, "svg");
if (id) {
svg.setAttribute("id", id);
}
svg.setAttribute("width", width );
svg.setAttribute(... | , y, r, fill) {
var circle;
circle = document.createElementNS(svgNameSpace, 'circle');
circle.setAttribute('cx', x);
circle.setAttribute('cy', y);
circle.setAttribute('r', r);
circle.setAttribute('fill', fill);
return circle;
}
function createImage(x, y, width, height, href) {
var image... | eateCircle(x | identifier_name |
regions-infer-borrow-scope-within-loop.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 ... | <'r, T>(x: &'r T) -> &'r T {x}
fn foo(cond: &fn() -> bool, box: &fn() -> @int) {
let mut y: ∫
loop {
let x = box();
// Here we complain because the resulting region
// of this borrow is the fn body as a whole.
y = borrow(x); //~ ERROR illegal borrow: cannot root managed value long enough... | borrow | identifier_name |
regions-infer-borrow-scope-within-loop.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 ... | y = borrow(x); //~ ERROR illegal borrow: cannot root managed value long enough
assert!(*x == *y);
if cond() { break; }
}
assert!(*y != 0);
}
fn main() {} | let x = box();
// Here we complain because the resulting region
// of this borrow is the fn body as a whole. | random_line_split |
regions-infer-borrow-scope-within-loop.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 ... |
fn main() {}
| {
let mut y: ∫
loop {
let x = box();
// Here we complain because the resulting region
// of this borrow is the fn body as a whole.
y = borrow(x); //~ ERROR illegal borrow: cannot root managed value long enough
assert!(*x == *y);
if cond() { break; }
}
assert!(*y !... | identifier_body |
regions-infer-borrow-scope-within-loop.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 ... |
}
assert!(*y != 0);
}
fn main() {}
| { break; } | conditional_block |
CanaryScore.tsx | import React from 'react';
import './canaryScore.component.less';
export interface ICanaryScoreProps {
score: number | string;
health?: string;
result: string;
inverse: boolean;
}
export interface ICanaryScoreState {
score: number | string;
healthLabel: string;
}
export class CanaryScore extends React.C... | : result === 'failure'
? 'failing'
: 'unknown';
return {
healthLabel,
score,
};
}
public componentWillReceiveProps(props: ICanaryScoreProps) {
this.setState(this.getLabelState(props));
}
public render() {
const className = [
this.props.inverse ? 'inve... | const healthLabel =
health === 'unhealthy'
? 'unhealthy'
: result === 'success'
? 'healthy' | random_line_split |
CanaryScore.tsx | import React from 'react';
import './canaryScore.component.less';
export interface ICanaryScoreProps {
score: number | string;
health?: string;
result: string;
inverse: boolean;
}
export interface ICanaryScoreState {
score: number | string;
healthLabel: string;
}
export class CanaryScore extends React.C... |
public render() {
const className = [
this.props.inverse ? 'inverse' : '',
'score',
'label',
'label-default',
`label-${this.state.healthLabel}`,
].join(' ');
return <span className={className}>{this.state.score}</span>;
}
}
| {
this.setState(this.getLabelState(props));
} | identifier_body |
CanaryScore.tsx | import React from 'react';
import './canaryScore.component.less';
export interface ICanaryScoreProps {
score: number | string;
health?: string;
result: string;
inverse: boolean;
}
export interface ICanaryScoreState {
score: number | string;
healthLabel: string;
}
export class CanaryScore extends React.C... | (props: ICanaryScoreProps) {
this.setState(this.getLabelState(props));
}
public render() {
const className = [
this.props.inverse ? 'inverse' : '',
'score',
'label',
'label-default',
`label-${this.state.healthLabel}`,
].join(' ');
return <span className={className}>{th... | componentWillReceiveProps | identifier_name |
issue-13058.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
fn main() {
check(&(3, 5));
}
| {
let cont_iter = cont.iter();
//~^ ERROR 24:26: 24:30: explicit lifetime required in the type of `cont` [E0621]
let result = cont_iter.fold(Some(0), |state, val| {
state.map_or(None, |mask| {
let bit = 1 << val;
if mask & bit == 0 {Some(mask|bit)} else {None}
})
});
... | identifier_body |
issue-13058.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | <'r, I: Iterator<Item=usize>, T: Itble<'r, usize, I>>(cont: &T) -> bool
{
let cont_iter = cont.iter();
//~^ ERROR 24:26: 24:30: explicit lifetime required in the type of `cont` [E0621]
let result = cont_iter.fold(Some(0), |state, val| {
state.map_or(None, |mask| {
let bit = 1 << val;
... | check | identifier_name |
issue-13058.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | fn main() {
check(&(3, 5));
} | random_line_split | |
issue-13058.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | else {None}
})
});
result.is_some()
}
fn main() {
check(&(3, 5));
}
| {Some(mask|bit)} | conditional_block |
string-tools.js | var digits = '0123456789';
var lowercase = 'abcdefghijklmnoprstuvxuyz';
var uppercase = lowercase.toUpperCase();
var special = '+/';
var base64Chars;
var base62Chars;
var base32Chars;
var generateBaseString;
module.exports = (exports = {});
base64Chars = function() {
return [digits, lowercase, uppercase, special].j... | return generateBaseString(digits, length);
}; | random_line_split | |
string-tools.js | var digits = '0123456789';
var lowercase = 'abcdefghijklmnoprstuvxuyz';
var uppercase = lowercase.toUpperCase();
var special = '+/';
var base64Chars;
var base62Chars;
var base32Chars;
var generateBaseString;
module.exports = (exports = {});
base64Chars = function() {
return [digits, lowercase, uppercase, special].j... |
return output;
};
exports.generateBase64String = function(length) {
return generateBaseString(base64Chars(), length);
};
exports.generateBase62String = function(length) {
return generateBaseString(base62Chars(), length);
};
exports.generateBase32String = function(length) {
return generateBaseString(base32C... | {
output += pool[Math.ceil(Math.random() * 100 % pool.length || 1) - 1];
} | conditional_block |
models.py | from datetime import datetime
from django.core.exceptions import ValidationError
from django.db import models
def validate_answer_to_universe(value):
if value != 42:
raise ValidationError('This is not the answer to life, universe and everything!', code='not42')
class ModelToValidate(models.Model):
... | (models.Model):
auto1 = models.AutoField(primary_key=True)
auto2 = models.AutoField(primary_key=True)
except AssertionError as exc:
assertion_error = exc
assert str(assertion_error) == "A model can't have more than one AutoField."
| MultipleAutoFields | identifier_name |
models.py | from datetime import datetime
from django.core.exceptions import ValidationError
from django.db import models
def validate_answer_to_universe(value):
if value != 42:
|
class ModelToValidate(models.Model):
name = models.CharField(max_length=100)
created = models.DateTimeField(default=datetime.now)
number = models.IntegerField(db_column='number_val')
parent = models.ForeignKey(
'self',
models.SET_NULL,
blank=True, null=True,
limit_choi... | raise ValidationError('This is not the answer to life, universe and everything!', code='not42') | conditional_block |
models.py | from datetime import datetime
from django.core.exceptions import ValidationError
from django.db import models
def validate_answer_to_universe(value):
if value != 42:
raise ValidationError('This is not the answer to life, universe and everything!', code='not42')
class ModelToValidate(models.Model):
... |
except AssertionError as exc:
assertion_error = exc
assert str(assertion_error) == "A model can't have more than one AutoField."
| auto1 = models.AutoField(primary_key=True)
auto2 = models.AutoField(primary_key=True) | identifier_body |
models.py | from datetime import datetime
from django.core.exceptions import ValidationError
from django.db import models
def validate_answer_to_universe(value):
if value != 42:
raise ValidationError('This is not the answer to life, universe and everything!', code='not42')
class ModelToValidate(models.Model):
... | efield = models.EmailField()
class Meta:
unique_together = (('ifield', 'cfield',), ['ifield', 'efield'])
class UniqueForDateModel(models.Model):
start_date = models.DateField()
end_date = models.DateTimeField()
count = models.IntegerField(unique_for_date="start_date", unique_for_year="end... | ifield = models.IntegerField() | random_line_split |
tektronixMDO3012.py | """
Python Interchangeable Virtual Instrument Library
Copyright (c) 2016 Alex Forencich
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 righ... | """
from .tektronixMDO3000 import *
class tektronixMDO3012(tektronixMDO3000):
"Tektronix MDO3012 IVI oscilloscope driver"
def __init__(self, *args, **kwargs):
self.__dict__.setdefault('_instrument_id', 'MDO3012')
super(tektronixMDO3012, self).__init__(*args, **kwargs)
self._analog_c... | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
| random_line_split |
tektronixMDO3012.py | """
Python Interchangeable Virtual Instrument Library
Copyright (c) 2016 Alex Forencich
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 righ... | (self, *args, **kwargs):
self.__dict__.setdefault('_instrument_id', 'MDO3012')
super(tektronixMDO3012, self).__init__(*args, **kwargs)
self._analog_channel_count = 2
self._digital_channel_count = 16
self._channel_count = self._analog_channel_count + self._digital_channel_count
... | __init__ | identifier_name |
tektronixMDO3012.py | """
Python Interchangeable Virtual Instrument Library
Copyright (c) 2016 Alex Forencich
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 righ... | "Tektronix MDO3012 IVI oscilloscope driver"
def __init__(self, *args, **kwargs):
self.__dict__.setdefault('_instrument_id', 'MDO3012')
super(tektronixMDO3012, self).__init__(*args, **kwargs)
self._analog_channel_count = 2
self._digital_channel_count = 16
self._channel_coun... | identifier_body | |
cepsAPIService.js | /* global angular */
angular.module("app").factory("cepsAPI", function ($http, config) {
var _getCeps = function () {
return $http.get(config.baseUrl + "DbAuditPronatec-3.2/api/ceps");
};
var _getCep = function (id) {
return $http.get(config.baseUrl + "DbAuditPronatec-3.2/api/ceps/" + id); | return $http.post(config.baseUrl + "DbAuditPronatec-3.2/api/ceps", cep);
};
var _getDelete = function (id) {
return $http.delete(config.baseUrl + "DbAuditPronatec-3.2/api/ceps/" + id);
};
var _deleteCep = function (id) {
return $http.delete(config.baseUrl + "DbAuditPronatec-3.2/api/c... | };
var _saveCep = function (cep) { | random_line_split |
spruit_atmosphere.py |
Plotting options are included in plot/mhs_plot.py
"""
import os
import numpy as np
import pysac.mhs_atmosphere as atm
import astropy.units as u
from pysac.mhs_atmosphere.parameters.model_pars import spruit as model_pars
#==============================================================================
#check whether mp... | pressure_mi, rho_mi, Fxi, Fyi, B2x, B2y =\
atm.construct_pairwise_field(
x, y, z,
xi[i], yi[i],
xi[j], yi[j], Si[i], Si[j],
... | Btensy += B2y
pressure_m += pressure_mi
rho_m += rho_mi
else: | random_line_split |
spruit_atmosphere.py | Plotting options are included in plot/mhs_plot.py
"""
import os
import numpy as np
import pysac.mhs_atmosphere as atm
import astropy.units as u
from pysac.mhs_atmosphere.parameters.model_pars import spruit as model_pars
#==============================================================================
#check whether mpi ... |
# Alfven speed proportional to Z^2 along the axis of the flux tube
elif option_pars['l_square']:
option_pars['l_B0_rootz'] = True
model_pars['chrom_scale'] *= 1.65
model_pars['p0'] *= 2e4
physical_constants['gravity'] *= 5e4
model_pars['radial_scale'] *= 1.
# Alfven speed not defined along the axis... | option_pars['l_B0_rootz'] = True
model_pars['chrom_scale'] *= 0.062
model_pars['p0'] *= 3e2
physical_constants['gravity'] *= 8e3
model_pars['radial_scale'] *= 1. | conditional_block |
mod.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | //! Useful synchronization primitives
//!
//! This module contains useful safe and unsafe synchronization primitives.
//! Most of the primitives in this module do not provide any sort of locking
//! and/or blocking at all, but rather provide the necessary tools to build
//! other types of concurrent primitives.
#![sta... | random_line_split | |
historical.ts | import axios, {AxiosResponse} from 'axios';
// import {Reading} from '../types/models/Power';
const historicalApi = axios.create({ baseURL: 'http://thanksgiving.cabin/api/historical', timeout: 5000 });
export async function getHistorical(from: number, to: number): Promise<AxiosResponse> |
export function averageNumber(arr: number[]): number {
const sum: number = arr.reduce((acc, val) => acc + val);
const avg: number = sum / arr.length;
if (avg > 0) {
return Math.floor(avg * 100) / 100;
} else {
return Math.ceil(avg * 100) / 100;
}
} | {
try {
const response = await historicalApi({
method: "get",
params: { from, to }
});
return response;
} catch (err) {
throw err;
}
} | identifier_body |
historical.ts | import axios, {AxiosResponse} from 'axios';
// import {Reading} from '../types/models/Power';
const historicalApi = axios.create({ baseURL: 'http://thanksgiving.cabin/api/historical', timeout: 5000 });
export async function getHistorical(from: number, to: number): Promise<AxiosResponse> {
try {
const resp... | (arr: number[]): number {
const sum: number = arr.reduce((acc, val) => acc + val);
const avg: number = sum / arr.length;
if (avg > 0) {
return Math.floor(avg * 100) / 100;
} else {
return Math.ceil(avg * 100) / 100;
}
} | averageNumber | identifier_name |
historical.ts | import axios, {AxiosResponse} from 'axios';
// import {Reading} from '../types/models/Power';
const historicalApi = axios.create({ baseURL: 'http://thanksgiving.cabin/api/historical', timeout: 5000 });
export async function getHistorical(from: number, to: number): Promise<AxiosResponse> {
try {
const resp... |
} | {
return Math.ceil(avg * 100) / 100;
} | conditional_block |
historical.ts | import axios, {AxiosResponse} from 'axios';
// import {Reading} from '../types/models/Power';
const historicalApi = axios.create({ baseURL: 'http://thanksgiving.cabin/api/historical', timeout: 5000 });
export async function getHistorical(from: number, to: number): Promise<AxiosResponse> {
try {
const resp... | } | if (avg > 0) {
return Math.floor(avg * 100) / 100;
} else {
return Math.ceil(avg * 100) / 100;
} | random_line_split |
sequence.py | from collections import namedtuple
def | ():
# 元组拆包
a, b, *rest = range(5)
print(a, b, rest)
a, b, *rest = range(2)
print(a, b, rest)
a, *body, c, d = range(5)
print(a, body, c, d)
*head, b, c, d = range(5)
print(head, b, c, d)
# 具名元组 page_26
City = namedtuple('City', 'name country population coordinates')
t... | game | identifier_name |
sequence.py | from collections import namedtuple
def game():
# 元组拆包
a, b, *r | LatLong = namedtuple('LatLong', 'lat long')
delhi_data = ('Delhi NCR', 'IN', 21.935, LatLong(28.613889, 77.208889))
delhi = City._make(delhi_data)
print(delhi._asdict()) # collections.OrderedDict
if __name__ =
= "__main__":
game()
| est = range(5)
print(a, b, rest)
a, b, *rest = range(2)
print(a, b, rest)
a, *body, c, d = range(5)
print(a, body, c, d)
*head, b, c, d = range(5)
print(head, b, c, d)
# 具名元组 page_26
City = namedtuple('City', 'name country population coordinates')
tokyo = City('Tokyo', 'JP', ... | identifier_body |
sequence.py | from collections import namedtuple
def game():
# 元组拆包 | print(a, b, rest)
a, b, *rest = range(2)
print(a, b, rest)
a, *body, c, d = range(5)
print(a, body, c, d)
*head, b, c, d = range(5)
print(head, b, c, d)
# 具名元组 page_26
City = namedtuple('City', 'name country population coordinates')
tokyo = City('Tokyo', 'JP', '36.933', (35.6... | a, b, *rest = range(5) | random_line_split |
sequence.py | from collections import namedtuple
def game():
# 元组拆包
a, b, *rest = range(5)
print(a, b, rest)
a, b, *rest = range(2)
print(a, b, rest)
a, *body, c, d = range(5)
print(a, body, c, d)
*head, b, c, d = range(5)
print(head, b, c, d)
# 具名元组 page_26
City = namedtuple('City',... | conditional_block | ||
NavLinkSpec.tsx | import { render } from '@testing-library/react';
import { expect } from 'chai';
import NavLink from '../src/NavLink';
describe('<NavLink>', () => { | title="content"
data-testid="test"
>
<strong>Children</strong>
</NavLink>,
);
const navLinkElem = getByTestId('test');
navLinkElem.classList.contains('nav-link').should.be.true;
navLinkElem.classList.contains('custom-class').should.be.true;
navLinkElem.getAttribut... | it('renders correctly', () => {
const { getByTestId } = render(
<NavLink
className="custom-class"
href="/some/unique-thing/" | random_line_split |
sentry.py | from __future__ import absolute_import
import mock
import os
from django.conf import settings
from sentry_sdk import Hub
TEST_ROOT = os.path.normpath(
os.path.join(os.path.dirname(__file__), os.pardir, os.pardir, os.pardir, os.pardir, "tests")
)
def pytest_configure(config):
# HACK: Only needed for testin... |
# This speeds up the tests considerably, pbkdf2 is by design, slow.
settings.PASSWORD_HASHERS = ["django.contrib.auth.hashers.MD5PasswordHasher"]
settings.AUTH_PASSWORD_VALIDATORS = []
# Replace real sudo middleware with our mock sudo middleware
# to assert that the user is always in sudo mode
... | settings.SENTRY_CACHE = "sentry.cache.django.DjangoCache"
settings.SENTRY_CACHE_OPTIONS = {} | conditional_block |
sentry.py | from __future__ import absolute_import
import mock
import os
from django.conf import settings
from sentry_sdk import Hub
TEST_ROOT = os.path.normpath(
os.path.join(os.path.dirname(__file__), os.pardir, os.pardir, os.pardir, os.pardir, "tests")
)
def pytest_configure(config):
# HACK: Only needed for testin... |
# enable draft features
settings.SENTRY_OPTIONS["mail.enable-replies"] = True
settings.SENTRY_ALLOW_ORIGIN = "*"
settings.SENTRY_TSDB = "sentry.tsdb.inmemory.InMemoryTSDB"
settings.SENTRY_TSDB_OPTIONS = {}
if settings.SENTRY_NEWSLETTER == "sentry.newsletter.base.Newsletter":
settings... | random_line_split | |
sentry.py | from __future__ import absolute_import
import mock
import os
from django.conf import settings
from sentry_sdk import Hub
TEST_ROOT = os.path.normpath(
os.path.join(os.path.dirname(__file__), os.pardir, os.pardir, os.pardir, os.pardir, "tests")
)
def pytest_configure(config):
# HACK: Only needed for testin... |
integrations.register(BitbucketIntegrationProvider)
integrations.register(ExampleIntegrationProvider)
integrations.register(AliasedIntegrationProvider)
integrations.register(GitHubIntegrationProvider)
integrations.register(GitHubEnterpriseIntegrationProvider)
integrations.register(GitlabIntegra... | from sentry.plugins import plugins
from sentry.plugins.utils import TestIssuePlugin2
plugins.register(TestIssuePlugin2)
from sentry import integrations
from sentry.integrations.bitbucket import BitbucketIntegrationProvider
from sentry.integrations.example import (
ExampleIntegrationProvide... | identifier_body |
sentry.py | from __future__ import absolute_import
import mock
import os
from django.conf import settings
from sentry_sdk import Hub
TEST_ROOT = os.path.normpath(
os.path.join(os.path.dirname(__file__), os.pardir, os.pardir, os.pardir, os.pardir, "tests")
)
def | (config):
# HACK: Only needed for testing!
os.environ.setdefault("_SENTRY_SKIP_CONFIGURATION", "1")
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "sentry.conf.server")
# override docs which are typically synchronized from an upstream server
# to ensure tests are consistent
os.environ.setdefa... | pytest_configure | identifier_name |
Dicer.js | var WritableStream = require('stream').Writable
|| require('readable-stream').Writable,
inherits = require('util').inherits;
var StreamSearch = require('streamsearch');
var PartStream = require('./PartStream'),
HeaderParser = require('./HeaderParser');
var B_ONEDASH = new Buffer('-'),
... | this._isPreamble = true;
this._justMatched = false;
this._firstWrite = true;
this._inHeader = true;
this._part = undefined;
this._cb = undefined;
this._partOpts = (typeof cfg.partHwm === 'number'
? { highWaterMark: cfg.partHwm }
: {});
this._pause = false;
this... | {
if (!(this instanceof Dicer))
return new Dicer(cfg);
WritableStream.call(this, cfg);
if (!cfg || (!cfg.headerFirst && typeof cfg.boundary !== 'string'))
throw new TypeError('Boundary required');
if (typeof cfg.boundary === 'string')
this.setBoundary(cfg.boundary);
else
this._bparser = unde... | identifier_body |
Dicer.js | var WritableStream = require('stream').Writable
|| require('readable-stream').Writable,
inherits = require('util').inherits;
var StreamSearch = require('streamsearch');
var PartStream = require('./PartStream'),
HeaderParser = require('./HeaderParser');
var B_ONEDASH = new Buffer('-'),
... | this._inHeader = true;
}
if (data && start < end) {
if (this._isPreamble || !this._inHeader) {
if (buf)
shouldWriteMore = this._part.push(buf);
shouldWriteMore = this._part.push(data.slice(start, end));
if (!shouldWriteMore)
this._pause = true;
} else if (!this._isPre... | if (!this._isPreamble) | random_line_split |
Dicer.js | var WritableStream = require('stream').Writable
|| require('readable-stream').Writable,
inherits = require('util').inherits;
var StreamSearch = require('streamsearch');
var PartStream = require('./PartStream'),
HeaderParser = require('./HeaderParser');
var B_ONEDASH = new Buffer('-'),
... | (cfg) {
if (!(this instanceof Dicer))
return new Dicer(cfg);
WritableStream.call(this, cfg);
if (!cfg || (!cfg.headerFirst && typeof cfg.boundary !== 'string'))
throw new TypeError('Boundary required');
if (typeof cfg.boundary === 'string')
this.setBoundary(cfg.boundary);
else
this._bparser ... | Dicer | identifier_name |
Dicer.js | var WritableStream = require('stream').Writable
|| require('readable-stream').Writable,
inherits = require('util').inherits;
var StreamSearch = require('streamsearch');
var PartStream = require('./PartStream'),
HeaderParser = require('./HeaderParser');
var B_ONEDASH = new Buffer('-'),
... |
// allows for "easier" testing
if (this._firstWrite) {
this._bparser.push(B_CRLF);
this._firstWrite = false;
}
this._bparser.push(data);
if (this._pause)
this._cb = cb;
else
cb();
};
Dicer.prototype.reset = function() {
this._part = undefined;
this._bparser = undefined;
this._... | {
if (!this._part) {
this._part = new PartStream(this._partOpts);
this.emit('preamble', this._part);
}
var r = this._hparser.push(data);
if (!this._inHeader && r !== undefined && r < data.length)
data = data.slice(r);
else
return cb();
} | conditional_block |
timers.rs | _handle
}
pub fn unschedule_callback(&self, handle: OneshotTimerHandle) {
let was_next = self.is_next_timer(handle);
self.timers.borrow_mut().retain(|t| t.handle != handle);
if was_next {
self.invalidate_expected_event_id();
self.schedule_timer_call();
... | remove_min_duration | identifier_name | |
timers.rs | ,
}
// This enum is required to work around the fact that trait objects do not support generic methods.
// A replacement trait would have a method such as
// `invoke<T: DomObject>(self: Box<Self>, this: &T, js_timers: &JsTimers);`.
#[derive(JSTraceable, MallocSizeOf)]
pub enum OneshotTimerCallback {
XhrTimeout... | if self.suspended_since.get().is_some() {
// The timer will be scheduled when the pipeline is fully activated.
return;
}
let timers = self.timers.borrow();
if let Some(timer) = timers.last() {
let expected_event_id = self.invalidate_expected_event_id... |
fn schedule_timer_call(&self) { | random_line_split |
curve_src.js | (function(size, angle, minimum, canvas, context, requestAnimationFrame){
context.translate(minimum(90*size, 2*canvas.width/3), minimum(45*size, 2*canvas.height/3));
context.strokeStyle = 'black';
var draw = function(){
context.beginPath();
context.moveTo(0,0);
context.lineTo(size, 0);
context.stroke();... | else {
left();
}
}
var direction = function(n){
return (((n & -n) << 1) & n) !== 0;
}
var n = 1; var max = Math.pow(2, 15);
var continous = function(){
draw();
move(direction(n++));
requestAnimationFrame(continous);
}
continous();
})(5, Math.PI/2, Math.min, a, c, requestAnimatio... | {
right();
} | conditional_block |
curve_src.js | (function(size, angle, minimum, canvas, context, requestAnimationFrame){
context.translate(minimum(90*size, 2*canvas.width/3), minimum(45*size, 2*canvas.height/3));
context.strokeStyle = 'black';
var draw = function(){
context.beginPath();
context.moveTo(0,0);
context.lineTo(size, 0);
context.stroke();... |
var n = 1; var max = Math.pow(2, 15);
var continous = function(){
draw();
move(direction(n++));
requestAnimationFrame(continous);
}
continous();
})(5, Math.PI/2, Math.min, a, c, requestAnimationFrame); | }
var direction = function(n){
return (((n & -n) << 1) & n) !== 0;
} | random_line_split |
compiler_host.d.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import { AotCompilerHost } from '@angular/compiler';
import { AngularCompilerOptions, MetadataCollector, ModuleMetada... | {
protected assumedExists: {
[fileName: string]: boolean;
};
assumeFileExists(fileName: string): void;
}
export declare class ModuleResolutionHostAdapter extends CompilerHostContextAdapter implements CompilerHostContext {
private host;
directoryExists: ((directoryName: string) => boolean) |... | CompilerHostContextAdapter | identifier_name |
compiler_host.d.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import { AotCompilerHost } from '@angular/compiler';
import { AngularCompilerOptions, MetadataCollector, ModuleMetada... | * existing file | n/a | absolute | relative(*)
*
* NOTE: (*) the relative path is computed depending on `isGenDirChildOfRootDir`.
*/
fileNameToModuleName(importedFile: string, containingFile: string): string;
private dotRelative(from, to);
/**
* Moves the path into `genDir`... | * | genDir | node_module | rootDir
* --------------+----------+-------------+----------
* generated | relative | relative | n/a | random_line_split |
IndexedTriangleStripSet.js | /* -*- Mode: JavaScript; coding: utf-8; tab-width: 3; indent-tabs-mode: tab; c-basic-offset: 3 -*-
*******************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright create3000, Scheffelstraße 31a, Leipzig, Germany 2011.
... |
IndexedTriangleStripSet .prototype = $.extend (Object .create (X3DComposedGeometryNode .prototype),
{
constructor: IndexedTriangleStripSet,
fieldDefinitions: new FieldDefinitionArray ([
new X3DFieldDefinition (X3DConstants .inputOutput, "metadata", new Fields .SFNode ()),
new X3DFieldDefinition (... |
X3DComposedGeometryNode .call (this, executionContext);
this .addType (X3DConstants .IndexedTriangleStripSet);
this .triangleIndex = [ ];
}
| identifier_body |
IndexedTriangleStripSet.js | /* -*- Mode: JavaScript; coding: utf-8; tab-width: 3; indent-tabs-mode: tab; c-basic-offset: 3 -*-
*******************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright create3000, Scheffelstraße 31a, Leipzig, Germany 2011.
... |
IndexedTriangleStripSet .prototype = $.extend (Object .create (X3DComposedGeometryNode .prototype),
{
constructor: IndexedTriangleStripSet,
fieldDefinitions: new FieldDefinitionArray ([
new X3DFieldDefinition (X3DConstants .inputOutput, "metadata", new Fields .SFNode ()),
new X3DFieldDefinition (... | } | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.