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 |
|---|---|---|---|---|
snack-bar.component.ts | import { Component, Inject, EventEmitter } from '@angular/core';
import { MAT_SNACK_BAR_DATA, MatSnackBarRef } from '@angular/material/snack-bar';
import { SnackType } from '../types';
@Component({
selector: 'lib-snack-bar',
templateUrl: './snack-bar.component.html',
styleUrls: ['./snack-bar.component.scss'],
})... |
get icon() {
switch (this.data.snackType) {
case SnackType.Success:
return 'done';
case SnackType.Error:
return 'clear';
case SnackType.Warning:
return 'warning';
case SnackType.Info:
return 'info';
default:
return 'warning';
}
}
dis... | {} | identifier_body |
snack-bar.component.ts | import { Component, Inject, EventEmitter } from '@angular/core';
import { MAT_SNACK_BAR_DATA, MatSnackBarRef } from '@angular/material/snack-bar';
import { SnackType } from '../types';
@Component({
selector: 'lib-snack-bar',
templateUrl: './snack-bar.component.html',
styleUrls: ['./snack-bar.component.scss'],
})... | () {
this.snackBarRef.dismiss();
}
}
| dismiss | identifier_name |
snack-bar.component.ts | import { Component, Inject, EventEmitter } from '@angular/core';
import { MAT_SNACK_BAR_DATA, MatSnackBarRef } from '@angular/material/snack-bar';
import { SnackType } from '../types';
@Component({
selector: 'lib-snack-bar',
templateUrl: './snack-bar.component.html',
styleUrls: ['./snack-bar.component.scss'],
}) | public snackBarRef: MatSnackBarRef<SnackBarComponent>,
@Inject(MAT_SNACK_BAR_DATA) public data: any,
) {}
get icon() {
switch (this.data.snackType) {
case SnackType.Success:
return 'done';
case SnackType.Error:
return 'clear';
case SnackType.Warning:
return 'wa... | export class SnackBarComponent {
constructor( | random_line_split |
DevMenuView.tsx | import React from 'react';
import { Clipboard, PixelRatio, StyleSheet } from 'react-native';
import { StyledView } from '../components/Views';
import DevMenuBottomSheetContext, { Context } from './DevMenuBottomSheetContext';
import DevMenuButton from './DevMenuButton';
import DevMenuCloseButton from './DevMenuCloseBut... |
}
collapse = async () => {
if (this.context) {
await this.context.collapse();
}
};
collapseAndCloseDevMenuAsync = async () => {
await this.collapse();
await DevMenu.closeAsync();
};
loadStateAsync = async () => {
this.setState({ isLoaded: false });
const [enableDevMenuTool... | {
this.loadStateAsync();
} | conditional_block |
DevMenuView.tsx | import React from 'react';
import { Clipboard, PixelRatio, StyleSheet } from 'react-native';
import { StyledView } from '../components/Views';
import DevMenuBottomSheetContext, { Context } from './DevMenuBottomSheetContext';
import DevMenuButton from './DevMenuButton';
import DevMenuCloseButton from './DevMenuCloseBut... | (props, context) {
super(props, context);
this.state = {
enableDevMenuTools: false,
devMenuItems: {},
isOnboardingFinished: false,
isLoaded: false,
};
}
componentDidMount() {
this.loadStateAsync();
}
componentDidUpdate(prevProps: Props) {
if (this.props.uuid !== pr... | constructor | identifier_name |
DevMenuView.tsx | import React from 'react';
import { Clipboard, PixelRatio, StyleSheet } from 'react-native';
import { StyledView } from '../components/Views';
import DevMenuBottomSheetContext, { Context } from './DevMenuBottomSheetContext';
import DevMenuButton from './DevMenuButton';
import DevMenuCloseButton from './DevMenuCloseBut... |
collapse = async () => {
if (this.context) {
await this.context.collapse();
}
};
collapseAndCloseDevMenuAsync = async () => {
await this.collapse();
await DevMenu.closeAsync();
};
loadStateAsync = async () => {
this.setState({ isLoaded: false });
const [enableDevMenuTools, d... | {
if (this.props.uuid !== prevProps.uuid) {
this.loadStateAsync();
}
} | identifier_body |
DevMenuView.tsx | import React from 'react';
import { Clipboard, PixelRatio, StyleSheet } from 'react-native';
import { StyledView } from '../components/Views';
import DevMenuBottomSheetContext, { Context } from './DevMenuBottomSheetContext';
import DevMenuButton from './DevMenuButton';
import DevMenuCloseButton from './DevMenuCloseBut... | onPressDevMenuButton = key => {
DevMenu.selectItemWithKeyAsync(key);
};
onOnboardingFinished = () => {
DevMenu.setOnboardingFinishedAsync(true);
this.setState({ isOnboardingFinished: true });
};
maybeRenderDevMenuTools() {
const devMenuItems = Object.keys(this.state.devMenuItems).sort(
... | onGoToHome = () => {
this.collapse();
DevMenu.goToHomeAsync();
};
| random_line_split |
webpack.config.js | // Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in ... | module.exports = {
entry: './index.ts',
resolve: {
extensions: ['.ts', '.js', '.json'],
fallback: {
crypto: false,
child_process: false,
fs: false,
http2: false,
buffer: 'browserify',
process: false,
os: false,
querystring: false,
path: false,
stre... | random_line_split | |
s004_cpu_reconstruction.py | # -----------------------------------------------------------------------
# Copyright: 2010-2022, imec Vision Lab, University of Antwerp
# 2013-2022, CWI, Amsterdam
#
# Contact: astra@astra-toolbox.com
# Website: http://www.astra-toolbox.com/
#
# This file is part of the ASTRA Toolbox.
#
#
# The ASTRA Toolbo... |
# Run 20 iterations of the algorithm
# This will have a runtime in the order of 10 seconds.
astra.algorithm.run(alg_id, 20)
# Get the result
rec = astra.data2d.get(rec_id)
pylab.figure(3)
pylab.imshow(rec)
pylab.show()
# Clean up.
astra.algorithm.delete(alg_id)
astra.data2d.delete(rec_id)
astra.data2d.delete(sinogra... | random_line_split | |
mod.rs | use bytecode::{ByteCodeModule};
use bytecode::function::{ByteCodeFunction};
mod emptyblocks;
mod unusedfunctions;
mod returnvalueoptimization;
use self::emptyblocks::remove_empty_blocks;
use self::unusedfunctions::eliminate_unused_functions;
use self::returnvalueoptimization::return_value_optimization;
#[derive(Clon... | for func in module.functions.values_mut() {
if !func.external {
optimize_function(func, lvl);
}
}
}
#[cfg(test)]
mod test
{
use super::*;
use bytecode::test::generate_byte_code;
use bytecode::instruction::Instruction;
use bytecode::function::ByteCodeFunction;
use... | pub fn optimize_module(module: &mut ByteCodeModule, lvl: OptimizationLevel)
{
eliminate_unused_functions(module);
return_value_optimization(module); | random_line_split |
mod.rs | use bytecode::{ByteCodeModule};
use bytecode::function::{ByteCodeFunction};
mod emptyblocks;
mod unusedfunctions;
mod returnvalueoptimization;
use self::emptyblocks::remove_empty_blocks;
use self::unusedfunctions::eliminate_unused_functions;
use self::returnvalueoptimization::return_value_optimization;
#[derive(Clon... |
}
}
#[cfg(test)]
mod test
{
use super::*;
use bytecode::test::generate_byte_code;
use bytecode::instruction::Instruction;
use bytecode::function::ByteCodeFunction;
use ast::{sig, Type};
use span::Span;
#[test]
fn test_block_elimination()
{
let func_sig = sig("foo", Typ... | {
optimize_function(func, lvl);
} | conditional_block |
mod.rs | use bytecode::{ByteCodeModule};
use bytecode::function::{ByteCodeFunction};
mod emptyblocks;
mod unusedfunctions;
mod returnvalueoptimization;
use self::emptyblocks::remove_empty_blocks;
use self::unusedfunctions::eliminate_unused_functions;
use self::returnvalueoptimization::return_value_optimization;
#[derive(Clon... | (module: &mut ByteCodeModule, lvl: OptimizationLevel)
{
eliminate_unused_functions(module);
return_value_optimization(module);
for func in module.functions.values_mut() {
if !func.external {
optimize_function(func, lvl);
}
}
}
#[cfg(test)]
mod test
{
use super::*;
us... | optimize_module | identifier_name |
utils.test.js | /* eslint-env jest */
import { actionReducer } from './utils'
describe('actionReducer', () => {
const counter = actionReducer(0, {
INCREMENT (state, action) {
return state + 1
},
DECREMENT (state, action) | ,
SET_VALUE (state, action) {
return action.value
},
})
it('returns initial state on no action', () => {
expect(counter(undefined, {})).toEqual(0)
})
it('utilizes initial state for known action', () => {
expect(counter(undefined, { type: 'INCREMENT' })).toEqual(1)
})
it('utilizes cu... | {
return state - 1
} | identifier_body |
utils.test.js | /* eslint-env jest */
import { actionReducer } from './utils'
describe('actionReducer', () => {
const counter = actionReducer(0, {
INCREMENT (state, action) {
return state + 1
},
DECREMENT (state, action) {
return state - 1
},
SET_VALUE (state, action) {
return action.value
... | it('enables action handlers to consume action parameters', () => {
expect(counter(5, { type: 'SET_VALUE', value: 7 })).toEqual(7)
})
}) | random_line_split | |
utils.test.js | /* eslint-env jest */
import { actionReducer } from './utils'
describe('actionReducer', () => {
const counter = actionReducer(0, {
| (state, action) {
return state + 1
},
DECREMENT (state, action) {
return state - 1
},
SET_VALUE (state, action) {
return action.value
},
})
it('returns initial state on no action', () => {
expect(counter(undefined, {})).toEqual(0)
})
it('utilizes initial state for kn... | INCREMENT | identifier_name |
heuristics.py | import polyglot
import yaml
class Heuristics (object):
""" The Heuristics class receives a path to the file that is trying to be
identified and an array of possible languages for that file. The disambiguate
method will find the array with unambiguous strings of syntax for each language
and check the file in ques... |
else:
for string in self.syntaxBits [lang]:
if string in sourceCode.read():
return lang
sourceCode.seek (0) #re-reads from the beginning of the file
return None
| continue #there are no stored syntax strings for that language | conditional_block |
heuristics.py | import polyglot
import yaml
class Heuristics (object):
""" The Heuristics class receives a path to the file that is trying to be
identified and an array of possible languages for that file. The disambiguate
method will find the array with unambiguous strings of syntax for each language
and check the file in ques... | with open (path) as sourceCode:
for lang in possibleLanguages:
if lang not in self.syntaxBits.keys():
continue #there are no stored syntax strings for that language
else:
for string in self.syntaxBits [lang]:
if string in sourceCode.read():
return lang
sourceCode.seek (0)... | identifier_body | |
heuristics.py | import polyglot |
""" The Heuristics class receives a path to the file that is trying to be
identified and an array of possible languages for that file. The disambiguate
method will find the array with unambiguous strings of syntax for each language
and check the file in question for those strings. If a match occurrs then the file... | import yaml
class Heuristics (object): | random_line_split |
heuristics.py | import polyglot
import yaml
class Heuristics (object):
""" The Heuristics class receives a path to the file that is trying to be
identified and an array of possible languages for that file. The disambiguate
method will find the array with unambiguous strings of syntax for each language
and check the file in ques... | (self, path, possibleLanguages):
self.syntaxFile = polyglot.Polyglot.tryOpenFile ('syntax.yml')
# {language1: [bits_of_syntax1, bits_of_syntax2], language2: [bits_of_syntax3, bits_of_syntax4]}
self.syntaxBits = yaml.safe_load (self.syntaxFile)
self.disambiguate(path, possibleLanguages)
def disambiguate(self,... | __init__ | identifier_name |
collection.ts | /**
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to i... | implements Schema.Collection {
/**
* How the image backgrounds of collection items will be filled. Optional.
*/
imageFill: Schema.ImageFill
/**
* min: 2 max: 10
*/
items: Schema.CollectionItem[]
/**
* Subtitle of the collection.
* Optional.
*/
subtitle: string
/**
* Overall title ... | Collection | identifier_name |
collection.ts | /**
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to i... | * ```
*
* @see {@link https://developers.google.com/assistant/conversational/prompts-selection#collection | Developer Documentation}
*/
export class Collection implements Schema.Collection {
/**
* How the image backgrounds of collection items will be filled. Optional.
*/
imageFill: Schema.ImageFill
/**
... | random_line_split | |
unittest_plugin.py | This file is part of PyBuilder
#
# Copyright 2011-2015 PyBuilder Team
#
# 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
#
# Unles... | with test_proxy_for(project).and_test_name(test_name) as | random_line_split | |
unittest_plugin.py | This file is part of PyBuilder
#
# Copyright 2011-2015 PyBuilder Team
#
# 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
#
# Unles... |
def _get_make_result_method_name(runner_generator):
if (isinstance(runner_generator, list) or isinstance(runner_generator, tuple)) and len(runner_generator) > 1:
method = runner_generator[1]
if type(method) == MethodType or type(method) == FunctionType:
method = method.__name__
el... | if (isinstance(runner_generator, list) or isinstance(runner_generator, tuple)) and len(runner_generator) > 1:
runner_generator = runner_generator[0]
if not hasattr(runner_generator, '__call__'):
runner_generator = reduce(getattr, runner_generator.split("."), sys.modules[__name__])
return runner_... | identifier_body |
unittest_plugin.py | 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, software
# distributed under th... | test.fails(result.failed_test_names_and_reasons.get(test_name)) | conditional_block | |
unittest_plugin.py | This file is part of PyBuilder
#
# Copyright 2011-2015 PyBuilder Team
#
# 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
#
# Unles... | (self, test):
self.test_names.append(test)
self.logger.debug("starting %s", test)
old_startTest(test)
def addError(self, test, err):
exception_type, exception, traceback = err
self.failed_test_names_and_reasons[test] = '{0}: {1}'.format(exception_type, exception).replace('\'... | startTest | identifier_name |
speedboat.js | 'use strict';
var exec = require('child_process').exec,
MotorBoat = require('motorboat'),
CommandError = require('./command/command-error');
function SpeedBoat(options) {
MotorBoat.call(this, options);
}
| SpeedBoat.prototype.plot = function (boxId, cmd, cb) {
var self = this;
var plot = function (cb) {
console.log('running command:', cmd);
self.runInstanceCommand(boxId, cmd, function (err, result) {
if (err) {
var error = new CommandError('unable to run command: ' + er... | SpeedBoat.prototype = Object.create(MotorBoat.prototype);
SpeedBoat.prototype.constructor = SpeedBoat;
| random_line_split |
speedboat.js | 'use strict';
var exec = require('child_process').exec,
MotorBoat = require('motorboat'),
CommandError = require('./command/command-error');
function SpeedBoat(options) {
MotorBoat.call(this, options);
}
SpeedBoat.prototype = Object.create(MotorBoat.prototype);
SpeedBoat.prototype.constructor = SpeedBoat;... |
/*
* If we don't have a callback, the plot will be used
* elsewhere (e.g., in an async.* method)
*/
return plot;
};
SpeedBoat.prototype.purgeKnownHost = function (ipAddress, knownHostsPath, cb) {
var cmd = ('ssh-keygen -f "%s" -R %s')
.replace('%s', knownHostsPath)
.replace... | {
return plot(cb);
} | conditional_block |
speedboat.js | 'use strict';
var exec = require('child_process').exec,
MotorBoat = require('motorboat'),
CommandError = require('./command/command-error');
function | (options) {
MotorBoat.call(this, options);
}
SpeedBoat.prototype = Object.create(MotorBoat.prototype);
SpeedBoat.prototype.constructor = SpeedBoat;
SpeedBoat.prototype.plot = function (boxId, cmd, cb) {
var self = this;
var plot = function (cb) {
console.log('running command:', cmd);
self.... | SpeedBoat | identifier_name |
speedboat.js | 'use strict';
var exec = require('child_process').exec,
MotorBoat = require('motorboat'),
CommandError = require('./command/command-error');
function SpeedBoat(options) |
SpeedBoat.prototype = Object.create(MotorBoat.prototype);
SpeedBoat.prototype.constructor = SpeedBoat;
SpeedBoat.prototype.plot = function (boxId, cmd, cb) {
var self = this;
var plot = function (cb) {
console.log('running command:', cmd);
self.runInstanceCommand(boxId, cmd, function (err, re... | {
MotorBoat.call(this, options);
} | identifier_body |
utils.js | /**
* joola.io
*
* Copyright Joola Smart Solutions, Ltd. <info@joo.la>
*
* Licensed under GNU General Public License 3.0 or later.
* Some rights reserved. See LICENSE, AUTHORS.
*
* @license GPL-3.0+ <http://spdx.org/licenses/GPL-3.0+>
*/
Date.prototype.format = function (formatString) {
var formatDate ... | var yyyy = formatDate.getFullYear();
var yy = yyyy.toString().substring(2);
var m = formatDate.getMonth() + 1;
var mm = m < 10 ? "0" + m : m;
var mmm = months[m - 1];
var d = formatDate.getDate();
var dd = d < 10 ? "0" + d : d;
var h = formatDate.getHours();
var hh = h < 10 ? "0" + h : h;
var n = f... | random_line_split | |
PersistentBuffer.py | # -*- coding: utf-8 -*-
# Copyright (c) 2018 Ericsson AB
#
# 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 ... |
return value
if self._value :
# There is a value to read
return True
elif self._changed :
# Something has changed, try to pop a value
self._changed = False
q = self.db.runInteraction(pop)
q.addCallback(done)
... | db.execute("DELETE FROM queue WHERE rowid in (SELECT rowid FROM queue ORDER BY rowid LIMIT (?))",
(len(value),)) | conditional_block |
PersistentBuffer.py | # -*- coding: utf-8 -*-
# Copyright (c) 2018 Ericsson AB
#
# 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 ... | (response):
# A count response; [(cnt,)]
if response[0][0] == 0:
try:
os.remove(self.db_path)
except:
# Failed for some reason
_log.warning("Could not remove db file {}".format(self._dbpath))
q = ... | done | identifier_name |
PersistentBuffer.py | # -*- coding: utf-8 -*-
# Copyright (c) 2018 Ericsson AB
#
# 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 ... | self._statlogging = None
def ready(length):
def log_stats():
_log.info("{} : pushed {}, popped {} (latest timestamp: {}) ".format(self.db_name, self._pushed_values, self._popped_values, self._latest_timestamp))
self._statlogging.reset()
self._cha... | self._pushed_values = 0
self._popped_values = 0
self._latest_timestamp = 0
self._value = None
self._changed = None | random_line_split |
PersistentBuffer.py | # -*- coding: utf-8 -*-
# Copyright (c) 2018 Ericsson AB
#
# 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 ... |
def can_read(self):
def error(e):
_log.warning("Error during read: {}".format(e))
done()
def done(value=None):
if value:
self._changed = True # alert can_read that the database has changed
self._value = value
self.sc... | def error(e):
_log.warning("Error during write: {}".format(e))
done() # Call done to wake scheduler, not sure this is a good idea
def done(unused=None):
self._changed = True # Let can_read know there may be something new to read
self.scheduler_wakeup()
s... | identifier_body |
config.py | import json
from util import d
import os
__home = os.path.expanduser("~").replace('\\', '/') + "/PixelWeb/"
BASE_SERVER_CONFIG = d({
"id":"server_config",
"display": "server_config",
"preconfig": False,
"presets":[],
"params": [{
"id": "exter... | "default": False,
"help":"Show BiblioPixel debug in server console (not in main UI)."
},{
"id": "mod_dirs",
"label": "Module Directories",
"type": "str_multi",
"default": [],
"help":"Directories f... | "label": "Show Debug in Console",
"type": "bool", | random_line_split |
config.py | import json
from util import d
import os
__home = os.path.expanduser("~").replace('\\', '/') + "/PixelWeb/"
BASE_SERVER_CONFIG = d({
"id":"server_config",
"display": "server_config",
"preconfig": False,
"presets":[],
"params": [{
"id": "exter... | (home):
global __home
__home = home
def genDefaultConfig(params):
c = {}
for p in params:
p = d(p)
c[p.id] = p.default
return c
def initConfig():
try:
if not os.path.exists(__home):
print "Creating {}".format(__home)
os.makedirs(__home)
exc... | setHome | identifier_name |
config.py | import json
from util import d
import os
__home = os.path.expanduser("~").replace('\\', '/') + "/PixelWeb/"
BASE_SERVER_CONFIG = d({
"id":"server_config",
"display": "server_config",
"preconfig": False,
"presets":[],
"params": [{
"id": "exter... |
def paramsToDict(params):
data = {}
for p in params:
if "default" not in p:
p.default = None
data[p.id] = p.default
return data
def readServerConfig():
data = readConfig("config", path=__home)
base = paramsToDict(BASE_SERVER_CONFIG.params)
if len(data.keys()) == 0... | if not path:
path = __home
base = data
if key:
base = readConfig(file, path=path)
base[key] = data
with open(path + "/" + file + ".json", "w") as fp:
json.dump(base, fp, indent=4, sort_keys=True) | identifier_body |
config.py | import json
from util import d
import os
__home = os.path.expanduser("~").replace('\\', '/') + "/PixelWeb/"
BASE_SERVER_CONFIG = d({
"id":"server_config",
"display": "server_config",
"preconfig": False,
"presets":[],
"params": [{
"id": "exter... |
data = {}
try:
with open(path + "/" + file + ".json", "r") as fp:
data = json.load(fp, encoding='utf-8')
if key:
if key in data:
data = data[key]
else:
data = {}
except Exception, e:
pass
re... | path = __home | conditional_block |
str_suffix.rs | #![allow(unused)]
use std::{mem, str};
/// Str-like type where the first 0-2 bytes may point into a UTF-8 characters but all bytes
/// following those are guaranteed to represent a valid UTF-8 string (`str`). Relying on this
/// property we can iterate over the `StrSuffix` byte-by-byte as we would on a `[u8]` without... | (&self) -> &[u8] {
&self.0
}
pub fn iter(&self) -> Iter {
Iter(self)
}
}
pub struct Iter<'a>(&'a StrSuffix);
impl<'a> Iterator for Iter<'a> {
type Item = u8;
fn next(&mut self) -> Option<u8> {
if let Some((b, rest)) = self.0.split_first() {
self.0 = rest;
... | as_bytes | identifier_name |
str_suffix.rs | #![allow(unused)]
use std::{mem, str};
/// Str-like type where the first 0-2 bytes may point into a UTF-8 characters but all bytes
/// following those are guaranteed to represent a valid UTF-8 string (`str`). Relying on this
/// property we can iterate over the `StrSuffix` byte-by-byte as we would on a `[u8]` without... |
pub fn split_first(&self) -> Option<(u8, &Self)> {
if self.is_empty() {
None
} else {
Some((self.0[0], self.suffix(1)))
}
}
pub fn try_as_str(&self) -> Option<&str> {
self.get(0)
}
fn get(&self, index: usize) -> Option<&str> {
if se... | {
self.0.first().cloned()
} | identifier_body |
str_suffix.rs | #![allow(unused)]
use std::{mem, str};
/// Str-like type where the first 0-2 bytes may point into a UTF-8 characters but all bytes
/// following those are guaranteed to represent a valid UTF-8 string (`str`). Relying on this
/// property we can iterate over the `StrSuffix` byte-by-byte as we would on a `[u8]` without... |
fn bytes_prefix(&self) -> &[u8] {
for i in 0..(self.len().min(3)) {
if Self::is_char_boundary_byte(self.0[i]) {
return &self.0[..i];
}
}
&self.0[..0]
}
pub fn restore_char(&self, prefix: &[u8]) -> char {
assert!(prefix.len() <= 4);
... | } | random_line_split |
as_unsigned.rs | #![feature(core)]
extern crate core;
#[cfg(test)]
mod tests {
use core::slice::IntSliceExt;
// pub trait IntSliceExt<U, S> {
// /// Converts the slice to an immutable slice of unsigned integers with the same width.
// fn as_unsigned<'a>(&'a self) -> &'a [U];
// /// Converts the slice t... | () {
let slice: &[T] = &[0xffffffff];
let as_unsigned: &[U] = slice.as_unsigned();
assert_eq!(as_unsigned[0], 4294967295);
}
}
| as_unsigned_test1 | identifier_name |
as_unsigned.rs | #![feature(core)]
extern crate core;
#[cfg(test)]
mod tests {
use core::slice::IntSliceExt;
// pub trait IntSliceExt<U, S> {
// /// Converts the slice to an immutable slice of unsigned integers with the same width.
// fn as_unsigned<'a>(&'a self) -> &'a [U];
// /// Converts the slice t... |
}
| {
let slice: &[T] = &[0xffffffff];
let as_unsigned: &[U] = slice.as_unsigned();
assert_eq!(as_unsigned[0], 4294967295);
} | identifier_body |
as_unsigned.rs | #![feature(core)]
extern crate core;
#[cfg(test)]
mod tests {
use core::slice::IntSliceExt;
// pub trait IntSliceExt<U, S> {
// /// Converts the slice to an immutable slice of unsigned integers with the same width.
// fn as_unsigned<'a>(&'a self) -> &'a [U];
// /// Converts the slice t... | // }
// }
// impl_int_slices! { u32, i32 }
type U = u32;
type S = i32;
type T = S;
#[test]
#[allow(overflowing_literals)]
fn as_unsigned_test1() {
let slice: &[T] = &[0xffffffff];
let as_unsigned: &[U] = slice.as_unsigned();
assert_eq!(as_unsigned[0], 4294967295);
}
} | // impl_int_slice! { $u, $s, $u }
// impl_int_slice! { $u, $s, $s } | random_line_split |
compile.rs | use std::{
fs,
ffi::OsStr,
io,
path::Path,
};
use walkdir::WalkDir;
#[test]
fn fail() {
prepare_stderr_files("tests/compile-fail").unwrap();
let t = trybuild::TestCases::new();
t.compile_fail("tests/compile-fail/**/*.rs");
}
#[test]
fn pass() {
let t = trybuild::TestCases::new();
... |
#[rustversion::beta]
fn rename_beta_stderr(from: impl AsRef<Path>, to: impl AsRef<Path>) -> io::Result<()> {
fs::copy(from, to)?;
Ok(())
}
#[rustversion::not(beta)]
fn rename_beta_stderr(_: impl AsRef<Path>, _: impl AsRef<Path>) -> io::Result<()> {
Ok(())
}
| {
for entry in WalkDir::new(path) {
let entry = entry?;
if entry.path().extension().and_then(OsStr::to_str) == Some("beta") {
let renamed = entry.path().with_extension("");
// Unconditionally remove a corresponding `.stderr` file for a `.stderr.beta`
// file if ... | identifier_body |
compile.rs | use std::{
fs,
ffi::OsStr,
io,
path::Path,
};
use walkdir::WalkDir;
#[test]
fn fail() {
prepare_stderr_files("tests/compile-fail").unwrap();
let t = trybuild::TestCases::new();
t.compile_fail("tests/compile-fail/**/*.rs");
}
#[test]
fn pass() {
let t = trybuild::TestCases::new();
... | (_: impl AsRef<Path>, _: impl AsRef<Path>) -> io::Result<()> {
Ok(())
}
| rename_beta_stderr | identifier_name |
compile.rs | use std::{
fs,
ffi::OsStr,
io,
path::Path,
};
use walkdir::WalkDir;
#[test]
fn fail() {
prepare_stderr_files("tests/compile-fail").unwrap();
let t = trybuild::TestCases::new();
t.compile_fail("tests/compile-fail/**/*.rs");
}
#[test]
fn pass() {
let t = trybuild::TestCases::new();
... |
rename_beta_stderr(entry.path(), renamed)?;
}
}
Ok(())
}
#[rustversion::beta]
fn rename_beta_stderr(from: impl AsRef<Path>, to: impl AsRef<Path>) -> io::Result<()> {
fs::copy(from, to)?;
Ok(())
}
#[rustversion::not(beta)]
fn rename_beta_stderr(_: impl AsRef<Path>, _: impl AsRef... | {
fs::remove_file(&renamed)?;
} | conditional_block |
compile.rs | use std::{
fs,
ffi::OsStr,
io,
path::Path,
};
use walkdir::WalkDir;
#[test]
fn fail() {
prepare_stderr_files("tests/compile-fail").unwrap();
let t = trybuild::TestCases::new();
t.compile_fail("tests/compile-fail/**/*.rs");
}
#[test]
fn pass() {
let t = trybuild::TestCases::new();
... | //
// The approach we use is to run the test on all compilers, but only check stderr
// output on beta (which is the next stable release). We do this by default ignoring
// any `.stderr` files in the `compile-fail` directory, and copying `.stderr.beta` files
// when we happen to be running on a beta compiler.
fn prepa... | // having some message to check makes sure user-facing errors are sensical. | random_line_split |
protobuf_gen.py | @classmethod
def global_subsystems(cls):
return super(ProtobufGen, cls).global_subsystems() + (BinaryUtil.Factory,)
@classmethod
def register_options(cls, register):
super(ProtobufGen, cls).register_options(register)
# The protoc version and the plugin names are used as proxies for the identity of... | result = process.wait()
if result != 0:
raise TaskError('{0} ... exited non-zero ({1})'.format(self.protobuf_binary, result))
def _calculate_sources(self, targets):
gentargets = OrderedSet()
def add_to_gentargets(target):
if self.is_gentarget(target):
gentargets.add(target)
s... |
self.context.log.debug('Executing: {0}'.format('\\\n '.join(args)))
process = subprocess.Popen(args, env=protoc_environ) | random_line_split |
protobuf_gen.py | @classmethod
def global_subsystems(cls):
return super(ProtobufGen, cls).global_subsystems() + (BinaryUtil.Factory,)
@classmethod
def register_options(cls, register):
super(ProtobufGen, cls).register_options(register)
# The protoc version and the plugin names are used as proxies for the identity of... |
if not self.validate_sources_present(sources, targets):
return
bases = OrderedSet(sources_by_base.keys())
bases.update(self._proto_path_imports(targets))
check_duplicate_conflicting_protos(self, sources_by_base, sources, self.context.log)
for target in targets:
# NB(gm): If the strat... | sources = OrderedSet(itertools.chain.from_iterable(sources_by_base.values())) | conditional_block |
protobuf_gen.py | .
register('--version', advanced=True, fingerprint=True,
help='Version of protoc. Used to create the default --javadeps and as part of '
'the path to lookup the tool with --pants-support-baseurls and '
'--pants-bootstrapdir. When changing this parameter you may als... | """Perform a comparison of the two files"""
with open(a, 'rb') as fp_a, open(b, 'rb') as fp_b:
return fp_a.read() == fp_b.read() | identifier_body | |
protobuf_gen.py | @classmethod
def global_subsystems(cls):
return super(ProtobufGen, cls).global_subsystems() + (BinaryUtil.Factory,)
@classmethod
def register_options(cls, register):
super(ProtobufGen, cls).register_options(register)
# The protoc version and the plugin names are used as proxies for the identity of... | (self, target):
"""Extracts and maps jars to directories containing their contents.
:returns: a set of filepaths to directories containing the contents of jar.
"""
files = set()
jar_import_products = self.context.products.get_data(JarImportProducts)
imports = jar_import_products.imports(target)... | _jars_to_directories | identifier_name |
TripleStoreExplorer.py | #! /usr/bin/env python3
# -*- coding: utf-8 -*-
import logging
from askomics.libaskomics.ParamManager import ParamManager
from askomics.libaskomics.rdfdb.SparqlQueryBuilder import SparqlQueryBuilder
from askomics.libaskomics.rdfdb.QueryLauncher import QueryLauncher
class TripleStoreExplorer(ParamManager):
"""
... | query = sqb.load_from_file(sparql_template, { 'OwlProperty' : 'owl:ObjectProperty'}).query
results = ql.process_query(query)
data['relations'] = results
for elt in results:
if not elt['object'] in listEntities:
listEntities[elt['object']]=0
if no... | """
Get the user abstraction (relation and entity as subject and object)
:return:
:rtype:
"""
data = {}
listEntities = {}
self.log.debug(" =========== TripleStoreExplorer:getUserAbstraction ===========")
nodes_startpoint = self.get_start_points()
... | identifier_body |
TripleStoreExplorer.py | #! /usr/bin/env python3
# -*- coding: utf-8 -*-
import logging
from askomics.libaskomics.ParamManager import ParamManager
from askomics.libaskomics.rdfdb.SparqlQueryBuilder import SparqlQueryBuilder
from askomics.libaskomics.rdfdb.QueryLauncher import QueryLauncher
class TripleStoreExplorer(ParamManager):
"""
... | (self):
"""
Get the possible starting points for your graph.
:return: List of starting points
:rtype: Node list
"""
self.log.debug(" =========== TripleStoreExplorer:get_start_points ===========")
nodes = []
sqb = SparqlQueryBuilder(self.settings, self.se... | get_start_points | identifier_name |
TripleStoreExplorer.py | #! /usr/bin/env python3
# -*- coding: utf-8 -*-
import logging
from askomics.libaskomics.ParamManager import ParamManager
from askomics.libaskomics.rdfdb.SparqlQueryBuilder import SparqlQueryBuilder
from askomics.libaskomics.rdfdb.QueryLauncher import QueryLauncher
class TripleStoreExplorer(ParamManager):
"""
... |
else:
raise ValueError("buildRecursiveBlock:: constraint malformed :"+str(elt))
return req
return ""
def build_sparql_query_from_json(self,variates,constraintesRelations,limit,sendRequestToTPS):
self.log.debug("variates")
self.log.debug(vari... | req+= self.buildRecursiveBlock(tabul,elt[0]) | conditional_block |
TripleStoreExplorer.py | #! /usr/bin/env python3
# -*- coding: utf-8 -*-
import logging
from askomics.libaskomics.ParamManager import ParamManager
from askomics.libaskomics.rdfdb.SparqlQueryBuilder import SparqlQueryBuilder
from askomics.libaskomics.rdfdb.QueryLauncher import QueryLauncher
class TripleStoreExplorer(ParamManager):
"""
... | sparql_template = self.get_template_sparql(self.ASKOMICS_abstractionRelationUser)
query = sqb.load_from_file(sparql_template, { 'OwlProperty' : 'owl:ObjectProperty'}).query
results = ql.process_query(query)
data['relations'] = results
for elt in results:
if not elt[... |
sqb = SparqlQueryBuilder(self.settings, self.session)
ql = QueryLauncher(self.settings, self.session)
| random_line_split |
angular-resource.js |
/**
* @ngdoc overview
* @name ngResource
* @description
*
* # ngResource
*
* The `ngResource` module provides interaction support with RESTful services
* via the $resource service.
*
* {@installModule resource}
*
* <div doc-module-components="ngResource"></div>
*
* See {@link ngResource.$resource `$reso... | {
dst = dst || {};
angular.forEach(dst, function(value, key){
delete dst[key];
});
for (var key in src) {
if (src.hasOwnProperty(key) && !(key.charAt(0) === '$' && key.charAt(1) === '$')) {
dst[key] = src[key];
}
}
return dst;
} | identifier_body | |
angular-resource.js | - **`action`** – {string} – The name of action. This name becomes the name of the method on
* your resource object.
* - **`method`** – {string} – HTTP request method. Valid methods are: `GET`, `POST`, `PUT`,
* `DELETE`, and `JSONP`.
* - **`params`** – {Object=} – Optional set of pre-bound parameters fo... | * requests with credentials} for more information.
* - **`responseType`** - `{string}` - see {@link
* https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest#responseType requestType}.
* - **`interceptor`** - `{Object=}` - The interceptor object has two optional methods -
* `response` and `resp... | * - **`withCredentials`** - `{boolean}` - whether to set the `withCredentials` flag on the
* XHR object. See {@link https://developer.mozilla.org/en/http_access_control#section_5 | random_line_split |
angular-resource.js | (obj, path) {
if (!isValidDottedPath(path)) {
throw $resourceMinErr('badmember', 'Dotted member path "@{0}" is invalid.', path);
}
var keys = path.split('.');
for (var i = 0, ii = keys.length; i < ii && obj !== undefined; i++) {
var key = keys[i];
obj = (obj !== null) ? obj[key] : undefined;
}
r... | lookupDottedPath | identifier_name | |
mean_log_merger_bimbo.py | from __future__ import division
__author__ = 'Vladimir Iglovikov'
'''
Merges prediction for https://www.kaggle.com/c/grupo-bimbo-inventory-demand competition
Expm1(Mean([Log1p(x), Log1p(y)]))
'''
import os
import numpy as np
import sys
import pandas as pd
import time
files = sys.argv[1:]
try:
files.remove('mean_l... |
submission['Demanda_uni_equil'] = np.expm1(result.mean(axis=1))
submission['id'] = ids
submission.to_csv('{timestamp}.csv'.format(timestamp=time.time()), index=False) | result[ind] = np.log1p(df['Demanda_uni_equil'])
ind += 1 | conditional_block |
mean_log_merger_bimbo.py | from __future__ import division
__author__ = 'Vladimir Iglovikov'
'''
Merges prediction for https://www.kaggle.com/c/grupo-bimbo-inventory-demand competition
Expm1(Mean([Log1p(x), Log1p(y)]))
'''
import os
import numpy as np
import sys
import pandas as pd
import time
files = sys.argv[1:]
try:
files.remove('mean_l... | for df in data:
result[ind] = np.log1p(df['Demanda_uni_equil'])
ind += 1
submission['Demanda_uni_equil'] = np.expm1(result.mean(axis=1))
submission['id'] = ids
submission.to_csv('{timestamp}.csv'.format(timestamp=time.time()), index=False) |
result = pd.DataFrame()
submission = pd.DataFrame()
ind = 0 | random_line_split |
common.rs | use std::{
borrow::Cow,
collections::HashMap,
};
use parse_wiki_text::Node;
use crate::{Parameters, OtherTemplate};
// Why? Because MediaWiki (and thus Wikipedia) titles are case-sensitive in all
// but the first character.
pub fn uppercase_first_letter(string: &str) -> Cow<'_, str> {
if let Some(first_c... | }
fn remove_final_utc(timestamp: &str) -> &str {
if timestamp.ends_with(" (UTC)") {
×tamp[..timestamp.len() - 6]
} else {
timestamp
}
}
pub fn fuzzy_parse_timestamp(timestamp: &str) -> Result<chrono::naive::NaiveDateTime, dtparse::ParseError> {
dtparse::parse(remove_final_utc(time... | } | random_line_split |
common.rs | use std::{
borrow::Cow,
collections::HashMap,
};
use parse_wiki_text::Node;
use crate::{Parameters, OtherTemplate};
// Why? Because MediaWiki (and thus Wikipedia) titles are case-sensitive in all
// but the first character.
pub fn uppercase_first_letter(string: &str) -> Cow<'_, str> {
if let Some(first_c... |
pub fn fuzzy_parse_timestamp(timestamp: &str) -> Result<chrono::naive::NaiveDateTime, dtparse::ParseError> {
dtparse::parse(remove_final_utc(timestamp)).map(|(date, _time)| date)
}
pub fn make_map(params: &[(&str, &str)]) -> HashMap<String, String> {
params.iter().map(|(k, v)| (k.to_string(), v.to_string()))... | {
if timestamp.ends_with(" (UTC)") {
×tamp[..timestamp.len() - 6]
} else {
timestamp
}
} | identifier_body |
common.rs | use std::{
borrow::Cow,
collections::HashMap,
};
use parse_wiki_text::Node;
use crate::{Parameters, OtherTemplate};
// Why? Because MediaWiki (and thus Wikipedia) titles are case-sensitive in all
// but the first character.
pub fn uppercase_first_letter(string: &str) -> Cow<'_, str> {
if let Some(first_c... | <'a, 'b>(template: &'a OtherTemplate, key1: impl Into<Cow<'b, str>>) -> &'a str {
template.named.get(key1.into().as_ref()).map_or("", String::as_ref).trim()
}
#[derive(Clone, Copy)]
pub enum WikitextTransform { RequirePureText, GetTextContent, KeepMarkup }
pub fn nodes_to_text<'a>(nodes: &[Node<'a>], transform: W... | get_template_param | identifier_name |
views.py | from django.core.urlresolvers import reverse
from django.core.mail import send_mail
from django.shortcuts import render, redirect
from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required
from .models import ActivateCode
import uuid
import os
from django.http import HttpRespo... |
def activate(request, code):
query = ActivateCode.objects.filter(code=code,
expire_timestamp__gte=datetime.datetime.now())
if query.count() > 0:
code_record = query[0]
code_record.owner.is_active = True
code_record.owner.save()
return HttpRespon... | [email],
fail_silently=False)
else:
return render(request, "user_register.html", {"error": error})
return HttpResponse("请查收邮件激活帐户!") | random_line_split |
views.py | from django.core.urlresolvers import reverse
from django.core.mail import send_mail
from django.shortcuts import render, redirect
from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required
from .models import ActivateCode
import uuid
import os
from django.http import HttpRespo... | .user.userprofile
avatar_file = request.FILES.get("avatar", None)
if not avatar_file:
return HttpResponse("未选择文件")
file_name = request.user.username + avatar_file.name
if avatar_file.size > 50000:
return HttpResponse("图片大小不能超过500KB")
file_path = os.path.jo... | identifier_body | |
views.py | from django.core.urlresolvers import reverse
from django.core.mail import send_mail
from django.shortcuts import render, redirect
from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required
from .models import ActivateCode
import uuid
import os
from django.http import HttpRespo... | expire_timestamp__gte=datetime.datetime.now())
if query.count() > 0:
code_record = query[0]
code_record.owner.is_active = True
code_record.owner.save()
return HttpResponse("激活成功")
else:
return HttpResponse("激活失败")
@login_required
def upload_avatar(request):
if requ... | identifier_name | |
views.py | from django.core.urlresolvers import reverse
from django.core.mail import send_mail
from django.shortcuts import render, redirect
from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required
from .models import ActivateCode
import uuid
import os
from django.http import HttpRespo... |
else:
username = request.POST['username'].strip()
email = request.POST['email'].strip()
password = request.POST['password'].strip()
re_password = request.POST['re_password'].strip()
if not username or not password or not email:
error = "任何字段都不能为空"
if pass... | return render(request, "user_register.html") | conditional_block |
db.py | # -*- coding: utf-8 -*-
"""Database connection class."""
import psycopg2
class | (object):
"""A database connection class """
def __init__(self, dbname, host, port, user, password):
self.dbname = dbname
self.host = host
self.port = port
self.user = user
self.password = password
try:
self.conn = psycopg2.connect(
"d... | db | identifier_name |
db.py | # -*- coding: utf-8 -*-
"""Database connection class."""
import psycopg2
class db(object):
"""A database connection class """
def __init__(self, dbname, host, port, user, password):
self.dbname = dbname
self.host = host
self.port = port
self.user = user
self.password... | Parameters
----------
query : str
SQL query
Returns
-------
psycopg2 resultset
"""
with self.conn:
with self.conn.cursor() as cur:
cur.execute(query)
return(cur.fetchall())
def vacuum(self, sc... | cur.execute(query)
def getQuery(self, query):
"""DB query where the results need to return (e.g. SELECT)
| random_line_split |
db.py | # -*- coding: utf-8 -*-
"""Database connection class."""
import psycopg2
class db(object):
"""A database connection class """
def __init__(self, dbname, host, port, user, password):
self.dbname = dbname
self.host = host
self.port = port
self.user = user
self.password... | """ """
self.conn.close() | identifier_body | |
plugin.js | /*
* Copyright (c) 2012-2015 S-Core Co., Ltd.
*
* 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... | else {
store.put({name: title, paas: tab, id: 'paas-store' + title, logo: logo});
}
}
var paas = {
initPaaSTab: function () {
var exts = pm.getExtensions('webida.deploy.paas:tab');
exts.forEach(function (ext) {
require([ext.module], functio... | {
dojo.connect(combo, 'onChange', function () {
showSelectPaas(combo, container);
console.log('change');
});
store.put({name: title, paas: tab, id: 'paas-store' + title, logo: logo});
combo.set('value', title);
} | conditional_block |
plugin.js | /*
* Copyright (c) 2012-2015 S-Core Co., Ltd.
*
* 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... | }
function cbGetTab(tab) {
var container = reg.byId('paas-stack-container');
if (!container) {
return;
}
container.addChild(tab);
var combo = reg.byId('paas-selet-combo');
var store = combo.get('store');
var title = tab.get('title');
... | random_line_split | |
plugin.js | /*
* Copyright (c) 2012-2015 S-Core Co., Ltd.
*
* 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... | });
combo.set('store', store);
combo.set('value', title);
} else if (store.data.length === 0) {
dojo.connect(combo, 'onChange', function () {
showSelectPaas(combo, container);
console.log('change');
});
stor... | {
var container = reg.byId('paas-stack-container');
if (!container) {
return;
}
container.addChild(tab);
var combo = reg.byId('paas-selet-combo');
var store = combo.get('store');
var title = tab.get('title');
var logo = tab.get('logo');
... | identifier_body |
plugin.js | /*
* Copyright (c) 2012-2015 S-Core Co., Ltd.
*
* 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... | (tab) {
var container = reg.byId('paas-stack-container');
if (!container) {
return;
}
container.addChild(tab);
var combo = reg.byId('paas-selet-combo');
var store = combo.get('store');
var title = tab.get('title');
var logo = tab.get('logo');
... | cbGetTab | identifier_name |
AnimatedInterpolation.js | ] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProp... | * against this possibility.
*/
value.match(stringShapeRegex).forEach(function (number, i) {
outputRanges[i].push(+number);
});
});
/* $FlowFixMe(>=0.18.0): `outputRange[0].match()` can return `null`. Need to
* guard against this possibility.
*/
var interpolations = outputRange[0].ma... | });
outputRange.forEach(function (value) {
/* $FlowFixMe(>=0.18.0): `value.match()` can return `null`. Need to guard | random_line_split |
AnimatedInterpolation.js | : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.definePrope... | else {
result = result * (outputMax - outputMin) + outputMin;
}
return result;
}
function colorToRgba(input) {
var int32Color = (0, _normalizeCssColor.default)(input);
if (int32Color === null) {
return input;
}
int32Color = int32Color || 0;
var r = (int32Color & 0xff000000) >>> 24;
var g = ... | {
result = result + outputMin;
} | conditional_block |
AnimatedInterpolation.js | (subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(obje... | _inheritsLoose | identifier_name | |
AnimatedInterpolation.js | : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.definePrope... |
function checkPattern(arr) {
var pattern = arr[0].replace(stringShapeRegex, '');
for (var i = 1; i < arr.length; ++i) {
(0, _invariant.default)(pattern === arr[i].replace(stringShapeRegex, ''), 'invalid pattern ' + arr[0] + ' and ' + arr[i]);
}
}
function findRange(input, inputRange) {
var i;
for (i ... | {
return typeof range === 'string' && range.startsWith('rgb');
} | identifier_body |
ip.py | from charmhelpers.core.hookenv import (
config,
unit_get,
)
from charmhelpers.contrib.network.ip import (
get_address_in_network,
is_address_in_network,
is_ipv6,
get_ipv6_addr,
)
from charmhelpers.contrib.hahelpers.cluster import is_clustered
PUBLIC = 'public'
INTERNAL = 'int'
ADMIN = 'admin'... | (endpoint_type=PUBLIC):
resolved_address = None
if is_clustered():
if config(_address_map[endpoint_type]['config']) is None:
# Assume vip is simple and pass back directly
resolved_address = config('vip')
else:
for vip in config('vip').split():
... | resolve_address | identifier_name |
ip.py | from charmhelpers.core.hookenv import (
config,
unit_get,
)
from charmhelpers.contrib.network.ip import (
get_address_in_network,
is_address_in_network,
is_ipv6,
get_ipv6_addr,
)
from charmhelpers.contrib.hahelpers.cluster import is_clustered
PUBLIC = 'public'
INTERNAL = 'int'
ADMIN = 'admin'... |
else:
fallback_addr = unit_get(_address_map[endpoint_type]['fallback'])
resolved_address = get_address_in_network(
config(_address_map[endpoint_type]['config']), fallback_addr)
if resolved_address is None:
raise ValueError('Unable to resolve a suitable IP address'
... | fallback_addr = get_ipv6_addr() | conditional_block |
ip.py | from charmhelpers.core.hookenv import (
config,
unit_get,
) | is_ipv6,
get_ipv6_addr,
)
from charmhelpers.contrib.hahelpers.cluster import is_clustered
PUBLIC = 'public'
INTERNAL = 'int'
ADMIN = 'admin'
_address_map = {
PUBLIC: {
'config': 'os-public-network',
'fallback': 'public-address'
},
INTERNAL: {
'config': 'os-internal-network... |
from charmhelpers.contrib.network.ip import (
get_address_in_network,
is_address_in_network, | random_line_split |
ip.py | from charmhelpers.core.hookenv import (
config,
unit_get,
)
from charmhelpers.contrib.network.ip import (
get_address_in_network,
is_address_in_network,
is_ipv6,
get_ipv6_addr,
)
from charmhelpers.contrib.hahelpers.cluster import is_clustered
PUBLIC = 'public'
INTERNAL = 'int'
ADMIN = 'admin'... | raise ValueError('Unable to resolve a suitable IP address'
' based on charm state and configuration')
else:
return resolved_address
| resolved_address = None
if is_clustered():
if config(_address_map[endpoint_type]['config']) is None:
# Assume vip is simple and pass back directly
resolved_address = config('vip')
else:
for vip in config('vip').split():
if is_address_in_network(
... | identifier_body |
settings.py | """
Django settings for dts_test_project project.
For more information on this file, see
https://docs.djangoproject.com/en/1.6/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.6/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR... |
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'cl1)b#c&xmm36z3e(quna-vb@ab#&gpjtdjtpyzh!qn%bc^xxn'
# SECURITY WARNING: don't run with debug turned o... | sys.path.insert(0, BASE_DIR) | random_line_split |
unicode.py | """Utility commands to work Unicode data."""
import unicodedata
from plumeria.command import commands
from plumeria.util.command import string_filter
@commands.create('unicode escape', 'unicodeescape', category='Development')
@string_filter
def unicode_escape(text):
"""
Escapes unicode characters in the giv... | (text):
"""
Finds the Unicode code points for the given characters, up to 10 characters.
"""
return "\n".join("{} **{}**".format(s, ord(s)) for s in text[:10])
def setup():
commands.add(unicode_escape)
commands.add(unicode_name)
commands.add(unicode_code)
| unicode_code | identifier_name |
unicode.py | """Utility commands to work Unicode data."""
import unicodedata
from plumeria.command import commands
from plumeria.util.command import string_filter
@commands.create('unicode escape', 'unicodeescape', category='Development')
@string_filter
def unicode_escape(text):
"""
Escapes unicode characters in the giv... |
"""
return "\n".join("{} **{}**".format(s, ord(s)) for s in text[:10])
def setup():
commands.add(unicode_escape)
commands.add(unicode_name)
commands.add(unicode_code) | random_line_split | |
unicode.py | """Utility commands to work Unicode data."""
import unicodedata
from plumeria.command import commands
from plumeria.util.command import string_filter
@commands.create('unicode escape', 'unicodeescape', category='Development')
@string_filter
def unicode_escape(text):
"""
Escapes unicode characters in the giv... |
def setup():
commands.add(unicode_escape)
commands.add(unicode_name)
commands.add(unicode_code)
| """
Finds the Unicode code points for the given characters, up to 10 characters.
"""
return "\n".join("{} **{}**".format(s, ord(s)) for s in text[:10]) | identifier_body |
gyro_plot.py | # This is an example of popping a packet from the Emotiv class's packet queue
# and printing the gyro x and y values to the console.
from emokit.emotiv import Emotiv
import platform
if platform.system() == "Windows":
import socket # Needed to prevent gevent crashing on Windows. (surfly / gevent issue #459)
impor... | (rb):
print "Animation!"
print rb
line.set_ydata(rb)
return line,
def counter():
i = 0
while is_running:
yield i
i = i + 1
ani = animation.FuncAnimation(fig, animate, evt_wrapper(), init_func=init, interval=20, blit=True)
plt.show()
# gevent.Greenlet.spawn(evt_main, test_buf)
... | animate | identifier_name |
gyro_plot.py | # This is an example of popping a packet from the Emotiv class's packet queue
# and printing the gyro x and y values to the console.
from emokit.emotiv import Emotiv
import platform
if platform.system() == "Windows":
import socket # Needed to prevent gevent crashing on Windows. (surfly / gevent issue #459)
impor... |
except KeyboardInterrupt:
headset.close()
finally:
is_running = False
headset.close()
x = np.linspace(0, 1023, 1024)
test_buf = np.zeros(1024)
fig, ax = plt.subplots()
line, = ax.plot(x, test_buf)
plt.axis([0, 1024, -100, 100])
def evt_wrapper():
def gen():
return evt_mai... | packet = headset.dequeue()
print packet.gyro_x, packet.gyro_y
ring_buf[pos] = packet.gyro_x
if pos % 4 == 0:
yield ring_buf
pos = (pos + 1) % 1024
gevent.sleep(0) | conditional_block |
gyro_plot.py | # This is an example of popping a packet from the Emotiv class's packet queue
# and printing the gyro x and y values to the console.
from emokit.emotiv import Emotiv
import platform
if platform.system() == "Windows":
import socket # Needed to prevent gevent crashing on Windows. (surfly / gevent issue #459)
impor... |
def counter():
i = 0
while is_running:
yield i
i = i + 1
ani = animation.FuncAnimation(fig, animate, evt_wrapper(), init_func=init, interval=20, blit=True)
plt.show()
# gevent.Greenlet.spawn(evt_main, test_buf)
while True:
gevent.sleep(0)
| print "Animation!"
print rb
line.set_ydata(rb)
return line, | identifier_body |
gyro_plot.py | # This is an example of popping a packet from the Emotiv class's packet queue
# and printing the gyro x and y values to the console.
from emokit.emotiv import Emotiv
import platform
if platform.system() == "Windows":
import socket # Needed to prevent gevent crashing on Windows. (surfly / gevent issue #459)
impor... | try:
while True:
packet = headset.dequeue()
print packet.gyro_x, packet.gyro_y
ring_buf[pos] = packet.gyro_x
if pos % 4 == 0:
yield ring_buf
pos = (pos + 1) % 1024
gevent.sleep(0)
except KeyboardInterrupt:
... | gevent.spawn(headset.setup)
gevent.sleep(0)
pos = 0 | random_line_split |
index.d.ts | // Generated by typings
// Source: https://raw.githubusercontent.com/aurelia/path/master/dist/aurelia-path.d.ts
declare module 'aurelia-path' {
/**
* Calculates a path relative to a file.
*
* @param name The relative path.
* @param file The file path.
* @return The calculated path.
*/
export function relativeToFile(na... | */
export function parseQueryString(queryString: string): Object;
} | /**
* Parse a query string.
*
* @param queryString The query string to parse.
* @returns Object with keys and values mapped from the query string. | random_line_split |
ProxyViewList.js | import React from 'react';
import PropTypes from 'prop-types';
import { FormattedMessage } from 'react-intl';
import { Headline } from '@folio/stripes/components';
import css from './ProxyViewList.css';
| const items = records.map((record, index) => (
<ComponentToRender key={`item-${index}`} record={record} stripes={stripes} />
));
const noSponsorsFound = <FormattedMessage id="ui-users.permissions.noSponsorsFound" />;
const noProxiesFound = <FormattedMessage id="ui-users.permissions.noProxiesFound" />;
con... | const ProxyViewList = ({ records, name, label, itemComponent, stripes }) => {
const ComponentToRender = itemComponent; | random_line_split |
ease.js | import "../arrays/map";
import "../core/array";
import "../core/identity";
import "../math/trigonometry";
var d3_ease_default = function() { return d3_identity; };
var d3_ease = d3.map({
linear: d3_ease_default,
poly: d3_ease_poly,
quad: function() { return d3_ease_quad; },
cubic: function() { return d3_ease_... | return t * t * ((s + 1) * t - s);
};
}
function d3_ease_bounce(t) {
return t < 1 / 2.75 ? 7.5625 * t * t
: t < 2 / 2.75 ? 7.5625 * (t -= 1.5 / 2.75) * t + 0.75
: t < 2.5 / 2.75 ? 7.5625 * (t -= 2.25 / 2.75) * t + 0.9375
: 7.5625 * (t -= 2.625 / 2.75) * t + 0.984375;
} | return function(t) { | random_line_split |
ease.js | import "../arrays/map";
import "../core/array";
import "../core/identity";
import "../math/trigonometry";
var d3_ease_default = function() { return d3_identity; };
var d3_ease = d3.map({
linear: d3_ease_default,
poly: d3_ease_poly,
quad: function() { return d3_ease_quad; },
cubic: function() { return d3_ease_... | (t) {
return t * t;
}
function d3_ease_cubic(t) {
return t * t * t;
}
// Optimized clamp(reflect(poly(3))).
function d3_ease_cubicInOut(t) {
if (t <= 0) return 0;
if (t >= 1) return 1;
var t2 = t * t, t3 = t2 * t;
return 4 * (t < 0.5 ? t3 : 3 * (t - t2) + t3 - 0.75);
}
function d3_ease_poly(e) {
return... | d3_ease_quad | identifier_name |
ease.js | import "../arrays/map";
import "../core/array";
import "../core/identity";
import "../math/trigonometry";
var d3_ease_default = function() { return d3_identity; };
var d3_ease = d3.map({
linear: d3_ease_default,
poly: d3_ease_poly,
quad: function() { return d3_ease_quad; },
cubic: function() { return d3_ease_... | return t < 1 / 2.75 ? 7.5625 * t * t
: t < 2 / 2.75 ? 7.5625 * (t -= 1.5 / 2.75) * t + 0.75
: t < 2.5 / 2.75 ? 7.5625 * (t -= 2.25 / 2.75) * t + 0.9375
: 7.5625 * (t -= 2.625 / 2.75) * t + 0.984375;
}
| identifier_body | |
index.ts | import { noCache } from "../utils/constants";
/** Tell the service worker to skip waiting. Resolves once the controller has changed. */
export async function skipWaiting() {
const reg = await navigator.serviceWorker.getRegistration();
if (!reg || !reg.waiting) {
return;
}
reg.waiting.postMessage("skip-wait... |
async function watchForUpdate() {
const hasController = !!navigator.serviceWorker.controller;
// If we don't have a controller, we don't need to check for updates – we've just loaded from the
// network.
if (!hasController) {
return;
}
const reg = await navigator.serviceWorker.getRegistration();
/... | {
if (reg.installing) {
return reg.installing;
}
return new Promise<ServiceWorker>(resolve => {
reg.addEventListener("updatefound", () => resolve(reg.installing!), {
once: true
});
});
} | identifier_body |
index.ts | import { noCache } from "../utils/constants";
/** Tell the service worker to skip waiting. Resolves once the controller has changed. */
export async function skipWaiting() {
const reg = await navigator.serviceWorker.getRegistration();
if (!reg || !reg.waiting) {
return;
}
reg.waiting.postMessage("skip-wait... | }
});
});
updateReady = true;
}
/** Set up the service worker and monitor changes */
export async function init() {
if (noCache) {
const reg = await navigator.serviceWorker.getRegistration();
if (reg) {
await reg.unregister();
location.reload();
}
return;
}
await navig... | const installing = await installingWorker(reg);
await new Promise<void>(resolve => {
installing.addEventListener("statechange", () => {
if (installing.state === "installed") {
resolve(); | random_line_split |
index.ts | import { noCache } from "../utils/constants";
/** Tell the service worker to skip waiting. Resolves once the controller has changed. */
export async function skipWaiting() {
const reg = await navigator.serviceWorker.getRegistration();
if (!reg || !reg.waiting) {
return;
}
reg.waiting.postMessage("skip-wait... | () {
const hasController = !!navigator.serviceWorker.controller;
// If we don't have a controller, we don't need to check for updates – we've just loaded from the
// network.
if (!hasController) {
return;
}
const reg = await navigator.serviceWorker.getRegistration();
// Service worker not registered... | watchForUpdate | identifier_name |
index.ts | import { noCache } from "../utils/constants";
/** Tell the service worker to skip waiting. Resolves once the controller has changed. */
export async function skipWaiting() {
const reg = await navigator.serviceWorker.getRegistration();
if (!reg || !reg.waiting) {
return;
}
reg.waiting.postMessage("skip-wait... |
return new Promise<ServiceWorker>(resolve => {
reg.addEventListener("updatefound", () => resolve(reg.installing!), {
once: true
});
});
}
async function watchForUpdate() {
const hasController = !!navigator.serviceWorker.controller;
// If we don't have a controller, we don't need to check for up... | {
return reg.installing;
} | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.