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 |
|---|---|---|---|---|
test_predict.py | """
Tests that deepchem models make deterministic predictions.
"""
__author__ = "Bharath Ramsundar"
__copyright__ = "Copyright 2016, Stanford University"
__license__ = "MIT"
import os
import tempfile
import numpy as np
import unittest
import sklearn
import shutil
import deepchem as dc
try:
import tensorflow as tf
... | (unittest.TestCase):
"""
Test that models make deterministic predictions
These tests guard against failures like having dropout turned on at
test time.
"""
def setUp(self):
super(TestPredict, self).setUp()
self.current_dir = os.path.dirname(os.path.abspath(__file__))
'''
def test_tf_progress... | TestPredict | identifier_name |
test_predict.py | """
Tests that deepchem models make deterministic predictions.
"""
__author__ = "Bharath Ramsundar"
__copyright__ = "Copyright 2016, Stanford University"
__license__ = "MIT"
import os
import tempfile
import numpy as np
import unittest
import sklearn
import shutil
import deepchem as dc
try:
import tensorflow as tf
... | # Generate dummy dataset
ids = np.arange(n_samples)
X = np.random.rand(n_samples, n_features)
y = np.zeros((n_samples, n_tasks))
w = np.ones((n_samples, n_tasks))
dataset = dc.data.NumpyDataset(X, y, w, ids)
regression_metric = dc.metrics.Metric(
dc.metrics.mean_squared_error, task... | """
Test that models make deterministic predictions
These tests guard against failures like having dropout turned on at
test time.
"""
def setUp(self):
super(TestPredict, self).setUp()
self.current_dir = os.path.dirname(os.path.abspath(__file__))
'''
def test_tf_progressive_regression_predict(... | identifier_body |
test_predict.py | """
Tests that deepchem models make deterministic predictions.
"""
__author__ = "Bharath Ramsundar"
__copyright__ = "Copyright 2016, Stanford University"
__license__ = "MIT"
import os
import tempfile
import numpy as np
import unittest
import sklearn
import shutil
import deepchem as dc
try:
import tensorflow as tf
... |
'''
def test_tf_progressive_regression_predict(self):
"""Test tf progressive multitask makes deterministic predictions."""
np.random.seed(123)
n_tasks = 9
n_samples = 10
n_features = 3
n_classes = 2
# Generate dummy dataset
ids = np.arange(n_samples)
X = np.random.rand(n_sample... |
def setUp(self):
super(TestPredict, self).setUp()
self.current_dir = os.path.dirname(os.path.abspath(__file__)) | random_line_split |
ui-grid.language.sv.js | /*!
* ui-grid - v4.8.2 - 2019-10-07
* Copyright (c) 2019 ; License: MIT
*/
(function () {
angular.module('ui.grid').config(['$provide', function($provide) {
$provide.decorator('i18nService', ['$delegate', function($delegate) {
$delegate.add('sv', {
headerCell: {
aria: {
de... | },
groupPanel: {
description: 'Dra en kolumnrubrik hit och släpp den för att gruppera efter den kolumnen.'
},
search: {
aria: {
selected: 'Rad är vald',
notSelected: 'Rad är inte vald'
},
placeholder: 'Sök...',
sho... | aggregate: {
label: 'Poster' | random_line_split |
app.py | # -*- coding: utf-8 -*-
'''The app module, containing the app factory function.'''
from flask import Flask, render_template
from cheapr.settings import ProdConfig
from cheapr.assets import assets
from cheapr.extensions import (
bcrypt,
cache,
db,
login_manager,
migrate,
debug_toolbar,
)
from ch... |
return None
| app.errorhandler(errcode)(render_error) | conditional_block |
app.py | # -*- coding: utf-8 -*-
'''The app module, containing the app factory function.'''
from flask import Flask, render_template
from cheapr.settings import ProdConfig
from cheapr.assets import assets
from cheapr.extensions import (
bcrypt,
cache,
db,
login_manager,
migrate,
debug_toolbar,
)
from ch... | (app):
assets.init_app(app)
bcrypt.init_app(app)
cache.init_app(app)
db.init_app(app)
login_manager.init_app(app)
debug_toolbar.init_app(app)
migrate.init_app(app, db)
return None
def register_blueprints(app):
app.register_blueprint(public.views.blueprint)
app.register_blueprin... | register_extensions | identifier_name |
app.py | # -*- coding: utf-8 -*-
'''The app module, containing the app factory function.'''
from flask import Flask, render_template
from cheapr.settings import ProdConfig
from cheapr.assets import assets
from cheapr.extensions import (
bcrypt,
cache,
db,
login_manager,
migrate,
debug_toolbar,
)
from ch... | app = Flask(__name__)
app.config.from_object(config_object)
register_extensions(app)
register_blueprints(app)
register_errorhandlers(app)
app.secret_key = 'Google'
app.images_cache='static/cache/images'
#https://medium.com/@5hreyans/the-one-weird-trick-that-cut-our-flask-page-load-time-b... | http://flask.pocoo.org/docs/patterns/appfactories/
:param config_object: The configuration object to use.
''' | random_line_split |
app.py | # -*- coding: utf-8 -*-
'''The app module, containing the app factory function.'''
from flask import Flask, render_template
from cheapr.settings import ProdConfig
from cheapr.assets import assets
from cheapr.extensions import (
bcrypt,
cache,
db,
login_manager,
migrate,
debug_toolbar,
)
from ch... |
def register_extensions(app):
assets.init_app(app)
bcrypt.init_app(app)
cache.init_app(app)
db.init_app(app)
login_manager.init_app(app)
debug_toolbar.init_app(app)
migrate.init_app(app, db)
return None
def register_blueprints(app):
app.register_blueprint(public.views.blueprint)... | '''An application factory, as explained here:
http://flask.pocoo.org/docs/patterns/appfactories/
:param config_object: The configuration object to use.
'''
app = Flask(__name__)
app.config.from_object(config_object)
register_extensions(app)
register_blueprints(app)
register_errorhan... | identifier_body |
new_entry_point_file_writer.ts |
/**
* @license
* Copyright Google LLC 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 {absoluteFromSourceFile, AbsoluteFsPath, FileSystem, isLocalRelativePath} from '../../../src/ngtsc/file_system... |
protected copyBundle(
bundle: EntryPointBundle, packagePath: AbsoluteFsPath, ngccFolder: AbsoluteFsPath,
transformedFiles: FileToWrite[]) {
const doNotCopy = new Set(transformedFiles.map(f => f.path));
bundle.src.program.getSourceFiles().forEach(sourceFile => {
const originalPath = absolut... | {
// IMPLEMENTATION NOTE:
//
// The changes made by `copyBundle()` are not reverted here. The non-transformed copied files
// are identical to the original ones and they will be overwritten when re-processing the
// entry-point anyway.
//
// This way, we avoid the overhead of having to infor... | identifier_body |
new_entry_point_file_writer.ts |
/**
* @license
* Copyright Google LLC 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 {absoluteFromSourceFile, AbsoluteFsPath, FileSystem, isLocalRelativePath} from '../../../src/ngtsc/file_system... | (entryPoint: EntryPoint, formatProperties: EntryPointJsonProperty[]) {
if (formatProperties.length === 0) {
// No format properties need reverting.
return;
}
const packageJson = entryPoint.packageJson;
const packageJsonPath = this.fs.join(entryPoint.path, 'package.json');
// Revert all... | revertPackageJson | identifier_name |
new_entry_point_file_writer.ts |
/**
* @license
* Copyright Google LLC 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 {absoluteFromSourceFile, AbsoluteFsPath, FileSystem, isLocalRelativePath} from '../../../src/ngtsc/file_system... | else {
const relativePath = this.fs.relative(packagePath, file.path);
const newFilePath = this.fs.resolve(ngccFolder, relativePath);
this.fs.ensureDir(this.fs.dirname(newFilePath));
this.fs.writeFile(newFilePath, file.contents);
}
}
protected revertFile(filePath: AbsoluteFsPath, packag... | {
// This is either `.d.ts` or `.d.ts.map` file
super.writeFileAndBackup(file);
} | conditional_block |
new_entry_point_file_writer.ts | /**
* @license
* Copyright Google LLC 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 {absoluteFromSourceFile, AbsoluteFsPath, FileSystem, isLocalRelativePath} from '../../../src/ngtsc/file_system'... | this.fs.removeFile(newFilePath);
}
}
protected updatePackageJson(
entryPoint: EntryPoint, formatProperties: EntryPointJsonProperty[],
ngccFolder: AbsoluteFsPath) {
if (formatProperties.length === 0) {
// No format properties need updating.
return;
}
const packageJson ... | // This is either `.d.ts` or `.d.ts.map` file
super.revertFileAndBackup(filePath);
} else if (this.fs.exists(filePath)) {
const relativePath = this.fs.relative(packagePath, filePath);
const newFilePath = this.fs.resolve(packagePath, NGCC_DIRECTORY, relativePath); | random_line_split |
mod.rs | , |_| self.gen())
}
/// Generate a random primitive integer in the range [`low`,
/// `high`). Fails if `low >= high`.
///
/// This gives a uniform distribution (assuming this RNG is itself
/// uniform), even for edge cases like `gen_integer_range(0u8,
/// 170)`, which a naive modulo operati... | (&mut self, n: uint) -> bool {
n == 0 || self.gen_integer_range(0, n) == 0
}
/// Return a random string of the specified length composed of
/// A-Z,a-z,0-9.
///
/// # Example
///
/// ```rust
/// use std::rand;
/// use std::rand::Rng;
///
/// fn main() {
/// pr... | gen_weighted_bool | identifier_name |
mod.rs | is very fast. If you do not know for sure that it fits your
/// requirements, use a more secure one such as `IsaacRng`.
pub struct XorShiftRng {
priv x: u32,
priv y: u32,
priv z: u32,
priv w: u32,
}
impl Rng for XorShiftRng {
#[inline]
fn next_u32(&mut self) -> u32 {
let x = self.x;
... | random_line_split | ||
mod.rs | /// println!("{}", rng.choose_weighted(x));
/// }
/// ```
fn choose_weighted<T:Clone>(&mut self, v: &[Weighted<T>]) -> T {
self.choose_weighted_option(v).expect("Rng.choose_weighted: total weight is 0")
}
/// Choose Some(item) respecting the relative weights, returning none if
/... | {
XorShiftRng::new()
} | identifier_body | |
example.rs | pub fn verse(n: i32) -> String {
match n {
0 => "No more bottles of beer on the wall, no more bottles of beer.\n\
Go to the store and buy some more, 99 bottles of beer on the wall.\n".to_string(),
1 => "1 bottle of beer on the wall, 1 bottle of beer.\n\
Take it down and ... | pub fn sing(start: i32, end: i32) -> String {
let mut song = Vec::new();
for n in (end .. start + 1).rev() {
song.push(verse(n))
}
song.connect("\n")
} | }
}
| random_line_split |
example.rs | pub fn verse(n: i32) -> String |
pub fn sing(start: i32, end: i32) -> String {
let mut song = Vec::new();
for n in (end .. start + 1).rev() {
song.push(verse(n))
}
song.connect("\n")
}
| {
match n {
0 => "No more bottles of beer on the wall, no more bottles of beer.\n\
Go to the store and buy some more, 99 bottles of beer on the wall.\n".to_string(),
1 => "1 bottle of beer on the wall, 1 bottle of beer.\n\
Take it down and pass it around, no more bottles... | identifier_body |
example.rs | pub fn | (n: i32) -> String {
match n {
0 => "No more bottles of beer on the wall, no more bottles of beer.\n\
Go to the store and buy some more, 99 bottles of beer on the wall.\n".to_string(),
1 => "1 bottle of beer on the wall, 1 bottle of beer.\n\
Take it down and pass it arou... | verse | identifier_name |
CustomDataIndicatorExtensionsAlgorithm.py | # QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
# Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
#
# 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 Lice... | elif self.ratio.Current.Value < 1:
self.Liquidate()
# In CBOE/VIX data, there is a "vix close" column instead of "close" which is the
# default column namein LEAN Quandl custom data implementation.
# This class assigns new column name to match the the external datasource setting.
class QuandlVi... | lf.MarketOrder(self.vix, 100)
| conditional_block |
CustomDataIndicatorExtensionsAlgorithm.py | # QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
# Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License. | # Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
fro... | # You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
# | random_line_split |
CustomDataIndicatorExtensionsAlgorithm.py | # QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
# Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
#
# 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 Lice... | elf, data):
# Wait for all indicators to fully initialize
if not (self.vix_sma.IsReady and self.vxv_sma.IsReady and self.ratio.IsReady): return
if not self.Portfolio.Invested and self.ratio.Current.Value > 1:
self.MarketOrder(self.vix, 100)
elif self.ratio.Current.Va... | Data(s | identifier_name |
CustomDataIndicatorExtensionsAlgorithm.py | # QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
# Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
#
# 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 Lice... | f __init__(self):
self.ValueColumnName = "VIX Close" | identifier_body | |
Eat.ts | import * as Big from "bignumber.js";
import {Frame, ResponseContext, ResponseModel} from "../definitions/Handler";
import {Attributes, RequestContext} from "../definitions/SkillContext";
import {Humanize} from "../resources/humanize";
import {getNextUpgrades, getPurchaseableItems} from "../resources/store";
import {re... | };
let actionMap = {};
new Frame("Eat", entry, redirect, actionMap); | random_line_split | |
Eat.ts | import * as Big from "bignumber.js";
import {Frame, ResponseContext, ResponseModel} from "../definitions/Handler";
import {Attributes, RequestContext} from "../definitions/SkillContext";
import {Humanize} from "../resources/humanize";
import {getNextUpgrades, getPurchaseableItems} from "../resources/store";
import {re... |
attr.Upgrades = getPurchaseableItems(attr.CookieCounter, attr.Inventory);
attr.NextUpgrades = getNextUpgrades(attr.Inventory);
model.cookieCount = attr.CookieCounter;
model.upgrades = attr.Upgrades;
attr.Model = model;
return new ResponseContext(model);
};
let actionMap = {};
new Frame("E... | {
attr.CookieCounter = new Big(attr.CookieCounter).minus(eatCount);
attr.CookiesEaten = new Big(attr.CookiesEaten).plus(eatCount);
model.speech = `You ate ${Humanize(eatCount)} cookies. You have eaten ${Humanize(attr.CookiesEaten, 3)} cookies.`;
model.reprompt = `You have ${Humanize(att... | conditional_block |
unboxed-closures-blanket-fn-mut.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT | // 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 http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except accordin... | // file at the top-level directory of this distribution and at | random_line_split |
unboxed-closures-blanket-fn-mut.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 b(f: &mut FnMut() -> i32) -> i32 {
a(f)
}
fn c<F:FnMut() -> i32>(f: &mut F) -> i32 {
a(f)
}
fn main() {
let z: isize = 7;
let x = b(&mut || 22);
assert_eq!(x, 22);
let x = c(&mut || 22);
assert_eq!(x, 22);
}
| {
f()
} | identifier_body |
unboxed-closures-blanket-fn-mut.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 ... | (f: &mut FnMut() -> i32) -> i32 {
a(f)
}
fn c<F:FnMut() -> i32>(f: &mut F) -> i32 {
a(f)
}
fn main() {
let z: isize = 7;
let x = b(&mut || 22);
assert_eq!(x, 22);
let x = c(&mut || 22);
assert_eq!(x, 22);
}
| b | identifier_name |
Keyboard.js | 'use strict';
// Collects keyboard inputs state collection of keycodes that currently pressed,
// if its not true then it false and its up
// -----------------------------------------
(function () {
var state = {},
defaultHidState = {
down: 0,
up: 0
};
window.document.a... | component: function () {
return state;
}
});
})(); | dependencies: [],
| random_line_split |
candle.js | import d3 from 'd3'
import logger from '../logger'
const formatCandleData = (data) => data.map(d => ({
begins_at: d.begins_at,
open_price: parseFloat(d.open_price),
close_price: parseFloat(d.close_price),
high_price: parseFloat(d.high_price),
low_price: parseFloat(d.low_price),
volume: d.volume,
interpol... |
return ''
}
const tickValues = getTickValues(metadata.data, inputTimeFormat)
const start = metadata.data[0].begins_at
const end = metadata.data[totalItems - 1].begins_at
logger.log(
`start date: ${inputTimeFormat.parse(start)}, end date: ${inputTimeFormat.parse(end)}`)
const x = d3.scale.linear()
... | {
const item = metadata.data[i]
return xAxisOutputFormat(inputTimeFormat.parse(item.begins_at))
} | conditional_block |
candle.js | import d3 from 'd3'
import logger from '../logger'
const formatCandleData = (data) => data.map(d => ({
begins_at: d.begins_at,
open_price: parseFloat(d.open_price),
close_price: parseFloat(d.close_price),
high_price: parseFloat(d.high_price),
low_price: parseFloat(d.low_price),
volume: d.volume,
interpol... | const formatXAxis = (i) => {
if (i >= 0 && i < totalItems) {
const item = metadata.data[i]
return xAxisOutputFormat(inputTimeFormat.parse(item.begins_at))
}
return ''
}
const tickValues = getTickValues(metadata.data, inputTimeFormat)
const start = metadata.data[0].begins_at
const end =... | const xAxisOutputFormat = d3.time.format('%b %Y')
// Label to be displayed on X axis by converting the data item into a formatted date | random_line_split |
quote-delete-dialog.component.ts | import { Component, OnInit, OnDestroy } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { NgbActiveModal, NgbModal, NgbModalRef } from '@ng-bootstrap/ng-bootstrap';
import { JhiEventManager } from 'ng-jhipster';
import { IQuote } from 'app/shared/model/quotes/quote.model';
impor... | (id: number) {
this.quoteService.delete(id).subscribe(response => {
this.eventManager.broadcast({
name: 'quoteListModification',
content: 'Deleted an quote'
});
this.activeModal.dismiss(true);
});
}
}
@Component({
selector: 'jh... | confirmDelete | identifier_name |
quote-delete-dialog.component.ts | import { Component, OnInit, OnDestroy } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { NgbActiveModal, NgbModal, NgbModalRef } from '@ng-bootstrap/ng-bootstrap';
import { JhiEventManager } from 'ng-jhipster';
import { IQuote } from 'app/shared/model/quotes/quote.model';
impor... | result => {
this.router.navigate([{ outlets: { popup: null } }], { replaceUrl: true, queryParamsHandling: 'merge' });
this.ngbModalRef = null;
},
reason => {
this.router.navigate([{ outlet... | this.ngbModalRef.componentInstance.quote = quote;
this.ngbModalRef.result.then( | random_line_split |
login.service.ts | import { Injectable } from '@angular/core';
import { JhiLanguageService } from 'ng-jhipster';
import { Principal } from '../auth/principal.service';
import { AuthServerProvider } from '../auth/auth-jwt.service';
@Injectable()
export class LoginService {
| (
private languageService: JhiLanguageService,
private principal: Principal,
private authServerProvider: AuthServerProvider
) {}
login(credentials, callback?) {
const cb = callback || function() {};
return new Promise((resolve, reject) => {
this.authServerPr... | constructor | identifier_name |
login.service.ts | import { Injectable } from '@angular/core';
import { JhiLanguageService } from 'ng-jhipster';
import { Principal } from '../auth/principal.service';
import { AuthServerProvider } from '../auth/auth-jwt.service';
@Injectable()
export class LoginService {
constructor(
private languageService: JhiLanguageSe... |
login(credentials, callback?) {
const cb = callback || function() {};
return new Promise((resolve, reject) => {
this.authServerProvider.login(credentials).subscribe((data) => {
this.principal.identity(true).then((account) => {
// After the login the... | {} | identifier_body |
login.service.ts | import { Injectable } from '@angular/core';
import { JhiLanguageService } from 'ng-jhipster';
import { Principal } from '../auth/principal.service';
import { AuthServerProvider } from '../auth/auth-jwt.service';
@Injectable()
export class LoginService {
constructor(
private languageService: JhiLanguageSe... | // After the login the language will be changed to
// the language selected by the user during his registration
if (account !== null) {
this.languageService.changeLanguage(account.langKey);
}
reso... | return new Promise((resolve, reject) => {
this.authServerProvider.login(credentials).subscribe((data) => {
this.principal.identity(true).then((account) => { | random_line_split |
login.service.ts | import { Injectable } from '@angular/core';
import { JhiLanguageService } from 'ng-jhipster';
import { Principal } from '../auth/principal.service';
import { AuthServerProvider } from '../auth/auth-jwt.service';
@Injectable()
export class LoginService {
constructor(
private languageService: JhiLanguageSe... |
resolve(data);
});
return cb();
}, (err) => {
this.logout();
reject(err);
return cb(err);
});
});
}
logout() {
this.authServerProvider.logout().subscribe();
this.... | {
this.languageService.changeLanguage(account.langKey);
} | conditional_block |
text.js | (function ($) {
"use strict";
/**
* Auto-hide summary textarea if empty and show hide and unhide links.
*/
Drupal.behaviors.textSummary = {
attach: function (context, settings) {
$(context).find('.text-summary').once('text-summary', function () {
var $widget = $(this).closest('.text-format-wrapper');
... |
});
}
};
})(jQuery);
| {
$link.click();
} | conditional_block |
text.js | (function ($) {
"use strict";
/**
* Auto-hide summary textarea if empty and show hide and unhide links.
*/
Drupal.behaviors.textSummary = {
attach: function (context, settings) {
$(context).find('.text-summary').once('text-summary', function () {
var $widget = $(this).closest('.text-format-wrapper');
... | function (e) {
e.preventDefault();
$summary.show();
$a.html(Drupal.t('Hide summary'));
$link.appendTo($summaryLabel);
}
).appendTo($summaryLabel);
// If no summary is set, hide the summary field.
if ($widget.find('.text-summary').val() === '') {... | e.preventDefault();
$summary.hide();
$a.html(Drupal.t('Edit summary'));
$link.appendTo($fullLabel);
}, | random_line_split |
api.py | PermissionsError(
'User with this mail does not exist in LDAP.')
if obj['op'] == 'add':
try:
self._add_user_permissions(user,
[obj['action']],
... | """Commit file to the record."""
record.files[filename].file.set_contents(
response,
default_location=record.files.bucket.location.uri,
size=total
)
db.session.commit() | identifier_body | |
api.py | 'general_title',
'$schema'
)
DEPOSIT_ACTIONS = [
'deposit-read',
'deposit-update',
'deposit-admin',
]
def DEPOSIT_ACTIONS_NEEDS(id):
"""Method to construct action needs."""
return {
'deposit-read': DepositReadActionNeed(str(id)),
'deposit-update': DepositUpdateActionNeed(s... | (self, pid=None, *args, **kwargs):
"""Upload action for file/repository."""
with UpdateDepositPermission(self).require(403):
data = request.get_json()
fileinfo = self._construct_fileinfo(data['url'],
data['type'])
if re... | upload | identifier_name |
api.py | 'general_title',
'$schema'
)
DEPOSIT_ACTIONS = [
'deposit-read',
'deposit-update',
'deposit-admin',
]
def DEPOSIT_ACTIONS_NEEDS(id):
"""Method to construct action needs."""
return {
'deposit-read': DepositReadActionNeed(str(id)),
'deposit-update': DepositUpdateActionNeed(s... | except NoResultFound:
raise UpdateDepositPermissionsError(
'Permission does not exist.')
elif obj['type'] == 'egroup':
try:
role = get_existing_or_register_role(obj['email'])... | try:
user = get_existing_or_register_user(obj['email'])
except DoesNotExistInLDAP:
raise UpdateDepositPermissionsError(
'User with this mail does not exist in LDAP.')
if obj['op'] == 'add':
... | conditional_block |
api.py |
import copy
import shutil
import tempfile
from copy import deepcopy
from functools import wraps
import requests
from celery import shared_task
from flask import current_app, request
from flask_login import current_user
from invenio_access.models import ActionRoles, ActionUsers
from invenio_db import db
from invenio_d... | from __future__ import absolute_import, print_function | random_line_split | |
index.js | "use strict";
module.exports = {
componentDidMount: function () {
this._thm_isEnabled = (
this.props.initialTarget &&
this.props.encodeTarget &&
this.props.decodeTarget);
if (this._thm_isEnabled) {
var target = (
this.props.decodeTarget(location.hash) ||
this.props.ini... |
},
onPopState: function (event) {
if (this._thm_isEnabled) {
var target = (
(event.state && event.state.target) ||
this.props.decodeTarget(location.hash));
if (target) {
this._thm_currentTarget = target;
this._thm_isPushedTarget = false;
if (this.onPopTarget... | {
removeEventListener("popstate", this.onPopState);
} | conditional_block |
index.js | "use strict";
module.exports = {
componentDidMount: function () {
this._thm_isEnabled = (
this.props.initialTarget &&
this.props.encodeTarget &&
this.props.decodeTarget);
if (this._thm_isEnabled) {
var target = (
this.props.decodeTarget(location.hash) ||
this.props.ini... | this._thm_isPushedTarget = true;
}
},
getCurrentTarget: function () {
return this._thm_currentTarget;
}
}; | target: target
}, "", hash);
}
this._thm_currentTarget = target; | random_line_split |
move.xd.js | /*
Copyright (c) 2004-2008, The Dojo Foundation All Rights Reserved.
Available via Academic Free License >= 2.1 OR the modified BSD license.
see: http://dojotoolkit.org/license for details
*/
dojo._xdResourceLoaded(function(dojo, dijit, dojox){
return {depends: [["provide", "dojox.gfx.move"],
["require", "dojox.gf... | dojo.require("dojox.gfx.Mover");
dojo.require("dojox.gfx.Moveable");
}
}};}); | dojo.provide("dojox.gfx.move");
| random_line_split |
move.xd.js | /*
Copyright (c) 2004-2008, The Dojo Foundation All Rights Reserved.
Available via Academic Free License >= 2.1 OR the modified BSD license.
see: http://dojotoolkit.org/license for details
*/
dojo._xdResourceLoaded(function(dojo, dijit, dojox){
return {depends: [["provide", "dojox.gfx.move"],
["require", "dojox.gf... |
}};});
| { //_hasResource checks added by build. Do not use _hasResource directly in your code.
dojo._hasResource["dojox.gfx.move"] = true;
dojo.provide("dojox.gfx.move");
dojo.require("dojox.gfx.Mover");
dojo.require("dojox.gfx.Moveable");
} | conditional_block |
retry.ts | import "./concat";
import "./endonerror";
import "./filter";
import "./flatmap";
import Exception from "./exception";
import _ from "./_";
import { Desc } from "./describe";
import Observable from "./observable";
import { EventStream } from "./observable";
import { Error, Event, hasValue, isError } from "./event";
impo... | });
}
if (finished) {
return undefined;
} else if (errorEvent) {
var context = {
error: errorEvent.error,
retriesDone
};
var pause: EventStream<V> = silence(delay(context));
retriesDone++
return pause.concat(once(<any>null).flatMap(valueStream));
... | if (hasValue(event)) {
errorEvent = null;
finished = true;
}
return sink(event);
}
| conditional_block |
retry.ts | import "./concat";
import "./endonerror";
import "./filter";
import "./flatmap";
import Exception from "./exception";
import _ from "./_";
import { Desc } from "./describe";
import Observable from "./observable";
import { EventStream } from "./observable";
import { Error, Event, hasValue, isError } from "./event";
impo... | if (finished) {
return undefined;
} else if (errorEvent) {
var context = {
error: errorEvent.error,
retriesDone
};
var pause: EventStream<V> = silence(delay(context));
retriesDone++
return pause.concat(once(<any>null).flatMap(valueStream));
} else {
... | return source(count).endOnError().transform(function (event: Event<V>, sink: EventSink<V>): Reply {
if (isError(event)) {
errorEvent = event;
if (!(isRetryable(errorEvent.error) && (retries === 0 || retriesDone < retries))) {
finished = true;
return sink(event);... | identifier_body |
retry.ts | import "./concat";
import "./endonerror";
import "./filter";
import "./flatmap";
import Exception from "./exception";
import _ from "./_";
import { Desc } from "./describe";
import Observable from "./observable";
import { EventStream } from "./observable";
import { Error, Event, hasValue, isError } from "./event";
impo... | >(options: RetryOptions<V>): EventStream<V> {
if (!_.isFunction(options.source)) {
throw new Exception("'source' option has to be a function");
}
var source = options.source;
var retries = options.retries || 0;
var retriesDone = 0
var delay = options.delay || function() {
return 0;
};
var isRetr... | try<V | identifier_name |
retry.ts | import "./concat";
import "./endonerror";
import "./filter";
import "./flatmap";
import Exception from "./exception";
import _ from "./_";
import { Desc } from "./describe";
import Observable from "./observable";
import { EventStream } from "./observable";
import { Error, Event, hasValue, isError } from "./event";
impo... | error: any
retriesDone: number
}
/**
* Options object for [Bacon.retry](../globals.html#retry).
*/
export interface RetryOptions<V> {
/**
* Required. A function that produces an Observable. The function gets attempt number (starting from zero) as its argument.
*/
source: (attemptNumber: number) => Obs... | import once from "./once";
export interface RetryContext { | random_line_split |
exam.component.ts | import { Component, OnInit, Output, EventEmitter, Input } from '@angular/core';
import { Subscription } from 'rxjs/Rx';
import { Question } from '../question';
import { Task } from '../../tasks/task';
import { QuestionService } from '../question.service';
@Component({
selector: 'xp-admin-assessments-exam',
te... |
/**
* When the questionsService data is changed, we need to update
* the questions @Input we're passing to the child components,
* so they have fresh data too.
*/
this.subscription = this.questionService.dataChanged.subscribe(
() => this.setMode()
... |
ngOnInit() {
this.setMode(); | random_line_split |
exam.component.ts | import { Component, OnInit, Output, EventEmitter, Input } from '@angular/core';
import { Subscription } from 'rxjs/Rx';
import { Question } from '../question';
import { Task } from '../../tasks/task';
import { QuestionService } from '../question.service';
@Component({
selector: 'xp-admin-assessments-exam',
te... |
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
handleExamChange(value) {
this.onExamChange.emit(value);
}
}
| {
this.currentMode = this.modes.CREATE;
} | conditional_block |
exam.component.ts | import { Component, OnInit, Output, EventEmitter, Input } from '@angular/core';
import { Subscription } from 'rxjs/Rx';
import { Question } from '../question';
import { Task } from '../../tasks/task';
import { QuestionService } from '../question.service';
@Component({
selector: 'xp-admin-assessments-exam',
te... | () {
this.subscription.unsubscribe();
}
handleExamChange(value) {
this.onExamChange.emit(value);
}
}
| ngOnDestroy | identifier_name |
exam.component.ts | import { Component, OnInit, Output, EventEmitter, Input } from '@angular/core';
import { Subscription } from 'rxjs/Rx';
import { Question } from '../question';
import { Task } from '../../tasks/task';
import { QuestionService } from '../question.service';
@Component({
selector: 'xp-admin-assessments-exam',
te... |
/**
* When component task / question is changed,
* not always the component is re-rendered.
* In some cases we just need to update it,
* without going through the ngOnInit.
* Otherwise, we end up with not-updated values (set in ngOnInit).
*/
ngOnChanges() {
this.setMode()... | {
this.setMode();
/**
* When the questionsService data is changed, we need to update
* the questions @Input we're passing to the child components,
* so they have fresh data too.
*/
this.subscription = this.questionService.dataChanged.subscribe(
()... | identifier_body |
index.ts | /**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import {setFlagsFromString} from 'v8';
import {runInNewContext} from 'vm';
import prettyFormat = require('pre... | () {
const isGarbageCollectorHidden = !global.gc;
// GC is usually hidden, so we have to expose it before running.
setFlagsFromString('--expose-gc');
runInNewContext('gc')();
// The GC was not initially exposed, so let's hide it again.
if (isGarbageCollectorHidden) {
setFlagsFromString('... | _runGarbageCollector | identifier_name |
index.ts | /**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import {setFlagsFromString} from 'v8';
import {runInNewContext} from 'vm';
import prettyFormat = require('pre... |
throw new Error(
'The leaking detection mechanism requires the "weak-napi" package to be installed and work. ' +
'Please install it as a dependency on your main project',
);
}
weak(value as object, () => (this._isReferenceBeingHeld = false));
this._isReferenceBeingHeld = tru... | {
throw err;
} | conditional_block |
index.ts | /**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import {setFlagsFromString} from 'v8';
import {runInNewContext} from 'vm';
import prettyFormat = require('pre... |
private _runGarbageCollector() {
const isGarbageCollectorHidden = !global.gc;
// GC is usually hidden, so we have to expose it before running.
setFlagsFromString('--expose-gc');
runInNewContext('gc')();
// The GC was not initially exposed, so let's hide it again.
if (isGarbageCollectorHidd... | {
this._runGarbageCollector();
return new Promise(resolve =>
setImmediate(() => resolve(this._isReferenceBeingHeld)),
);
} | identifier_body |
index.ts | /**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import {setFlagsFromString} from 'v8';
import {runInNewContext} from 'vm';
import prettyFormat = require('pre... | // GC is usually hidden, so we have to expose it before running.
setFlagsFromString('--expose-gc');
runInNewContext('gc')();
// The GC was not initially exposed, so let's hide it again.
if (isGarbageCollectorHidden) {
setFlagsFromString('--no-expose-gc');
}
}
} | }
private _runGarbageCollector() {
const isGarbageCollectorHidden = !global.gc;
| random_line_split |
conf.py | # -*- coding: utf-8 -*-
#
# Pikacon documentation build configuration file, created by
# sphinx-quickstart on Wed Apr 3 22:19:40 2013.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All... |
# -- Options for HTML output ---------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = 'default'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of opti... | #modindex_common_prefix = []
# If true, keep warnings as "system message" paragraphs in the built documents.
#keep_warnings = False | random_line_split |
simd.rs | // Copyright 2013-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-MI... |
#[inline(never)]
fn zzz() { () } |
zzz();
} | random_line_split |
simd.rs | // Copyright 2013-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-MI... | () { () }
| zzz | identifier_name |
simd.rs | // Copyright 2013-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-MI... |
#[inline(never)]
fn zzz() { () }
| {
let i8x16 = i8x16(0i8, 1i8, 2i8, 3i8, 4i8, 5i8, 6i8, 7i8,
8i8, 9i8, 10i8, 11i8, 12i8, 13i8, 14i8, 15i8);
let i16x8 = i16x8(16i16, 17i16, 18i16, 19i16, 20i16, 21i16, 22i16, 23i16);
let i32x4 = i32x4(24i32, 25i32, 26i32, 27i32);
let i64x2 = i64x2(28i64, 29i64);
let u8x16 = u... | identifier_body |
package.py | e6a0131c8408c555f6b58ef3cb7')
version('8.0.1', sha256='49107352923dea6de05a7b4c3906aaf98ef39c91ad81c383136e768dcf304069')
version('7.1.0', sha256='5f3ea001204d4f714be972a810a62c0f2277fbb9d8d2f8df39562988ca37497a')
version('7.0.0', sha256='78a990a15ead79cdc752e86b83cfab7dbf5b7ef51ba409db02570dbdd9ec32c3')
... | (self, version):
url = "http://www.vtk.org/files/release/{0}/VTK-{1}.tar.gz"
return url.format(version.up_to(2), version)
def setup_build_environment(self, env):
# VTK has some trouble finding freetype unless it is set in
# the environment
env.set('FREETYPE_DIR', self.spec['... | url_for_version | identifier_name |
package.py | with both osmesa and qt, but as of
# VTK 8.1, that should change
conflicts('+osmesa', when='+qt')
extends('python', when='+python')
# Acceptable python versions depend on vtk version
# We need vtk at least 8.0.1 for python@3,
# and at least 9.0 for python@3.8
depends_on('python@2.7:2.9', ... | cmake_args.extend(["-DModule_vtkIOParallelXdmf3:BOOL=ON"]) | conditional_block | |
package.py | 4e6a0131c8408c555f6b58ef3cb7')
version('8.0.1', sha256='49107352923dea6de05a7b4c3906aaf98ef39c91ad81c383136e768dcf304069')
version('7.1.0', sha256='5f3ea001204d4f714be972a810a62c0f2277fbb9d8d2f8df39562988ca37497a')
version('7.0.0', sha256='78a990a15ead79cdc752e86b83cfab7dbf5b7ef51ba409db02570dbdd9ec32c3')
... | if '+qt' in spec:
qt | cmake_args.extend([
'-DCMAKE_MACOSX_RPATH=ON'
])
| random_line_split |
package.py | 4e6a0131c8408c555f6b58ef3cb7')
version('8.0.1', sha256='49107352923dea6de05a7b4c3906aaf98ef39c91ad81c383136e768dcf304069')
version('7.1.0', sha256='5f3ea001204d4f714be972a810a62c0f2277fbb9d8d2f8df39562988ca37497a')
version('7.0.0', sha256='78a990a15ead79cdc752e86b83cfab7dbf5b7ef51ba409db02570dbdd9ec32c3')
... | # Allow downstream codes (e.g. VisIt) to override VTK's classes
'-DVTK_ALL_NEW_OBJECT_FACTORY:BOOL=ON',
# Disable wrappers for other languages.
'-DVTK_WRAP_JAVA=OFF',
'-DVTK_WRAP_TCL=OFF',
]
# Some variable names have changed
if spec.... | spec = self.spec
opengl_ver = 'OpenGL{0}'.format('2' if '+opengl2' in spec else '')
cmake_args = [
'-DBUILD_SHARED_LIBS=ON',
'-DVTK_RENDERING_BACKEND:STRING={0}'.format(opengl_ver),
# In general, we disable use of VTK "ThirdParty" libs, preferring
# spa... | identifier_body |
library.py | # Copyright 2015-2016 Open Source Robotics Foundation, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicabl... | tag_data['GitCommit'] = commit_sha
tag_data['Directory'] = commit_path
if not at_least_one_tag:
del manifest['release_names'][release_name]
return manifest
| print('os_code_name: ', os_code_name)
if os_code_data['tag_names']:
at_least_one_tag = True
for tag_name, tag_data in os_code_data['tag_names'].items():
print('tag_name: ', tag_name)
tags = []
... | conditional_block |
library.py | # Copyright 2015-2016 Open Source Robotics Foundation, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicabl... | commit_sha = latest_commit_sha(repo, commit_path)
print('tags: ', tags)
tag_data['Tags'] = tags
tag_data['Architectures'] = os_code_data['archs']
tag_data['GitCommit'] = commit_sha
... | repo_name, release_name,
os_name, os_code_name, tag_name) | random_line_split |
library.py | # Copyright 2015-2016 Open Source Robotics Foundation, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicabl... | tags.append(alias)
commit_path = os.path.join(
repo_name, release_name,
os_name, os_code_name, tag_name)
commit_sha = latest_commit_sha(repo, commit_path)
print('ta... | for release_name, release_data in list(manifest['release_names'].items()):
print('release_name: ', release_name)
# For each os supported
at_least_one_tag = False
for os_name, os_data in list(release_data['os_names'].items()):
print('os_name: ', os_name)
# For each... | identifier_body |
library.py | # Copyright 2015-2016 Open Source Robotics Foundation, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicabl... | (manifest, repo, repo_name):
# For each release
for release_name, release_data in list(manifest['release_names'].items()):
print('release_name: ', release_name)
# For each os supported
at_least_one_tag = False
for os_name, os_data in list(release_data['os_names'].items()):
... | parse_manifest | identifier_name |
cli.py | # Copyright (c) 2010 by Dan Jacob.
#
# Some rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and t... |
def prompt_bool(name, default=False, yes_choices=None, no_choices=None):
"""
Grabs user input from command line and converts to boolean
value.
:param name: prompt text
:param default: default value if no input provided.
:param yes_choices: default 'y', 'yes', '1', 'on', 'true', 't'
:para... | """
Grabs hidden (password) input from command line.
:param name: prompt text
:param default: default value if no input provided.
"""
prompt = name + (default and ' [%s]' % default or '')
prompt += name.endswith('?') and ' ' or ': '
while True:
rv = getpass.getpass(prompt)
... | identifier_body |
cli.py | # Copyright (c) 2010 by Dan Jacob.
#
# Some rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and t... | (name, choices, default=None, no_choice=('none',)):
"""
Grabs user input from command line from set of provided choices.
:param name: prompt text
:param choices: list or tuple of available choices.
:param default: default value if no input provided.
:param no_choice: acceptable list of strings ... | prompt_choices | identifier_name |
cli.py | # Copyright (c) 2010 by Dan Jacob.
#
# Some rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and t... | while True:
rv = raw_input(prompt)
if rv:
return rv
if default is not None:
return default
def prompt_pass(name, default=None):
"""
Grabs hidden (password) input from command line.
:param name: prompt text
:param default: default value if no input p... | prompt += name.endswith('?') and ' ' or ': ' | random_line_split |
cli.py | # Copyright (c) 2010 by Dan Jacob.
#
# Some rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and t... |
def prompt_pass(name, default=None):
"""
Grabs hidden (password) input from command line.
:param name: prompt text
:param default: default value if no input provided.
"""
prompt = name + (default and ' [%s]' % default or '')
prompt += name.endswith('?') and ' ' or ': '
while True:
... | return default | conditional_block |
logger.ts | import assert = require('assert')
import { resolve } from 'path'
import { PluginTypes } from '@microfleet/utils'
import { NotFoundError } from 'common-errors'
import { pino, PrettyOptions } from 'pino'
import type { SentryTransportConfig } from './logger/streams/sentry'
import { defaultsDeep } from '@microfleet/utils'
... | () {
return
}
}
/**
* Plugin init function.
* @param opts - Logger configuration.
*/
export function attach(this: Microfleet, opts: Partial<LoggerConfig> = {}): PluginInterface {
const { version, config: { name: applicationName } } = this
assert(this.hasPlugin('validator'), new NotFoundError('validato... | close | identifier_name |
logger.ts | import assert = require('assert')
import { resolve } from 'path'
import { PluginTypes } from '@microfleet/utils'
import { NotFoundError } from 'common-errors'
import { pino, PrettyOptions } from 'pino'
import type { SentryTransportConfig } from './logger/streams/sentry'
import { defaultsDeep } from '@microfleet/utils'
... |
if (streamName === 'pretty') {
return {
level: options.level || 'debug',
target: 'pino-pretty',
options,
}
}
return options
}
/**
* Plugin Type
*/
export const type = PluginTypes.essential
/**
* Relative priority inside the same plugin group type
*/
export const priority = 10
/... | {
return {
level: options.level || 'info',
target: resolve(__dirname, '../lib/logger/streams/sentry-worker'),
options,
}
} | conditional_block |
logger.ts | import assert = require('assert')
import { resolve } from 'path'
import { PluginTypes } from '@microfleet/utils'
import { NotFoundError } from 'common-errors'
import { pino, PrettyOptions } from 'pino'
import type { SentryTransportConfig } from './logger/streams/sentry'
import { defaultsDeep } from '@microfleet/utils'
... |
/**
* Enables default logger to stdout
*/
defaultLogger: true,
// there are no USER env variable in docker image
// so we can set default value based on its absence
// NOTE: not intended for production usage
prettifyDefaultLogger: !(process.env.NODE_ENV === 'production' || !process.env.USER),
nam... | const defaultConfig: LoggerConfig = {
/**
* anything thats not production will include extra logs
*/
debug: process.env.NODE_ENV !== 'production', | random_line_split |
logger.ts | import assert = require('assert')
import { resolve } from 'path'
import { PluginTypes } from '@microfleet/utils'
import { NotFoundError } from 'common-errors'
import { pino, PrettyOptions } from 'pino'
import type { SentryTransportConfig } from './logger/streams/sentry'
import { defaultsDeep } from '@microfleet/utils'
... |
/**
* Plugin Type
*/
export const type = PluginTypes.essential
/**
* Relative priority inside the same plugin group type
*/
export const priority = 10
/**
* Plugin Name
*/
export const name = 'logger'
export interface StreamConfiguration {
sentry?: SentryTransportConfig;
pretty?: PrettyOptions;
[stream... | {
if (streamName === 'sentry') {
return {
level: options.level || 'info',
target: resolve(__dirname, '../lib/logger/streams/sentry-worker'),
options,
}
}
if (streamName === 'pretty') {
return {
level: options.level || 'debug',
target: 'pino-pretty',
options,
}
... | identifier_body |
main.py | from snowball.utils import SnowMachine
from snowball.climate import WeatherProbe
# Note: multiline import limits line length
from snowball.water.phases import (
WaterVapor, IceCrystal, SnowFlake | Makes it snow, using a SnowMachine when weather doesn't allow it.
Returns a list of SnowFlakes.
Example::
>>> let_it_snow()
The snow machine is broken. No snow today. :/
[]
>>> let_it_snow()
[<snowball.water.phases.SnowFlake object at 0x101dbc210>,
<snowball... | )
def let_it_snow():
""" | random_line_split |
main.py | from snowball.utils import SnowMachine
from snowball.climate import WeatherProbe
# Note: multiline import limits line length
from snowball.water.phases import (
WaterVapor, IceCrystal, SnowFlake
)
def let_it_snow():
| """
# Create a WeatherProbe
weather_probe = WeatherProbe()
if weather_probe.temperature < 0 and weather_probe.clouds:
# There's clouds and it's cold enough
# Create necessary components
vapor = WaterVapor()
ice = IceCrystal()
# Start with empty list of flakes
... | """
Makes it snow, using a SnowMachine when weather doesn't allow it.
Returns a list of SnowFlakes.
Example::
>>> let_it_snow()
The snow machine is broken. No snow today. :/
[]
>>> let_it_snow()
[<snowball.water.phases.SnowFlake object at 0x101dbc210>,
<snow... | identifier_body |
main.py | from snowball.utils import SnowMachine
from snowball.climate import WeatherProbe
# Note: multiline import limits line length
from snowball.water.phases import (
WaterVapor, IceCrystal, SnowFlake
)
def | ():
"""
Makes it snow, using a SnowMachine when weather doesn't allow it.
Returns a list of SnowFlakes.
Example::
>>> let_it_snow()
The snow machine is broken. No snow today. :/
[]
>>> let_it_snow()
[<snowball.water.phases.SnowFlake object at 0x101dbc210>,
... | let_it_snow | identifier_name |
main.py | from snowball.utils import SnowMachine
from snowball.climate import WeatherProbe
# Note: multiline import limits line length
from snowball.water.phases import (
WaterVapor, IceCrystal, SnowFlake
)
def let_it_snow():
"""
Makes it snow, using a SnowMachine when weather doesn't allow it.
Returns a list... | snow_machine = SnowMachine()
snow_flakes = snow_machine.let_it_snow()
return snow_flakes | conditional_block | |
resources.py | # Copyright (c) 2013 Rackspace, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wr... | """Process Verification."""
LOG.debug('Verification id is {0}'.format(verification_id))
task = resources.PerformVerification()
try:
task.process(verification_id, keystone_id)
except Exception:
LOG.exception(">>>>> Task exception seen, but simulating async "
"reporti... | identifier_body | |
resources.py | # Copyright (c) 2013 Rackspace, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wr... | task.process(verification_id, keystone_id)
except Exception:
LOG.exception(">>>>> Task exception seen, but simulating async "
"reporting via the Verification entity on the "
"worker side.") | try: | random_line_split |
resources.py | # Copyright (c) 2013 Rackspace, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wr... | (order_id, keystone_id):
"""Process Order."""
LOG.debug('Order id is {0}'.format(order_id))
task = resources.BeginOrder()
try:
task.process(order_id, keystone_id)
except Exception:
LOG.exception(">>>>> Task exception seen, but simulating async "
"reporting via t... | process_order | identifier_name |
wal.rs | // CITA
// Copyright 2016-2017 Cryptape Technologies LLC.
// This program is free software: you can redistribute it
// and/or modify it under the terms of the GNU General Public
// License as published by the Free Software Foundation,
// either version 3 of the License, or (at your option) any
// later version.
// Th... | use std::str;
pub struct Wal {
fs: File,
dir: String,
}
impl Wal {
pub fn new(dir: &str) -> Result<Wal, io::Error> {
let mut tmp = OsString::new();
let mut big_path = PathBuf::new();
let mut fss = read_dir(&dir);
if fss.is_err() {
DirBuilder::new().recursive(tr... | use std::path::{PathBuf, Path}; | random_line_split |
wal.rs | // CITA
// Copyright 2016-2017 Cryptape Technologies LLC.
// This program is free software: you can redistribute it
// and/or modify it under the terms of the GNU General Public
// License as published by the Free Software Foundation,
// either version 3 of the License, or (at your option) any
// later version.
// Th... |
Ok(())
}
pub fn save(&mut self, mtype: u8, msg: &Vec<u8>) -> io::Result<usize> {
let mlen = msg.len() as u32;
if mlen == 0 {
return Ok(0);
}
let len_bytes: [u8; 4] = unsafe { transmute(mlen.to_le()) };
let type_bytes: [u8; 1] = unsafe { transmute(mty... | {
let mut delname = (height - 2).to_string();
delname = delname + ".log";
let delfilename = pathname + &*delname;
let _ = ::std::fs::remove_file(delfilename);
} | conditional_block |
wal.rs | // CITA
// Copyright 2016-2017 Cryptape Technologies LLC.
// This program is free software: you can redistribute it
// and/or modify it under the terms of the GNU General Public
// License as published by the Free Software Foundation,
// either version 3 of the License, or (at your option) any
// later version.
// Th... | }
}
if fnum == 0 {
tmp = OsString::from("1");
let fpath = dir.to_string() + "/1.log";
big_path = Path::new(&*fpath).to_path_buf();
}
let fs = OpenOptions::new().read(true).create(true).write(true).open(big_path)?;
let hstr = tmp.i... | {
let mut tmp = OsString::new();
let mut big_path = PathBuf::new();
let mut fss = read_dir(&dir);
if fss.is_err() {
DirBuilder::new().recursive(true).create(dir).unwrap();
fss = read_dir(&dir);
}
let mut fnum = 0;
for dir_entry in fss? {
... | identifier_body |
wal.rs | // CITA
// Copyright 2016-2017 Cryptape Technologies LLC.
// This program is free software: you can redistribute it
// and/or modify it under the terms of the GNU General Public
// License as published by the Free Software Foundation,
// either version 3 of the License, or (at your option) any
// later version.
// Th... | (&mut self, mtype: u8, msg: &Vec<u8>) -> io::Result<usize> {
let mlen = msg.len() as u32;
if mlen == 0 {
return Ok(0);
}
let len_bytes: [u8; 4] = unsafe { transmute(mlen.to_le()) };
let type_bytes: [u8; 1] = unsafe { transmute(mtype.to_le()) };
self.fs.seek(io... | save | identifier_name |
topicMappingView.js | if (typeof Mapmaker === 'undefined') Mapmaker = {};
Mapmaker.TopicMappingView = (function($, famous) {
var Engine = famous.core.Engine;
var Surface = famous.core.Surface;
var ImageSurface = famous.surfaces.ImageSurface;
var Modifier = famous.core.Modifier;
var StateModifier = famous.modifiers.StateModifier;
var ... | Private.createNameSurface.call(this);
var cancelHandler = function(event) {
Private.cancelClick.call(self, event);
};
Engine.on("mouseup", cancelHandler);
var mousemoveHandler = function(event) {
Handlers.mousemove.call(self, event);
};
Engine.on("mousemove", mousemoveHandler);
this.mouseIsDown... | Private.createImageSurface.call(this); | random_line_split |
topicMappingView.js | if (typeof Mapmaker === 'undefined') Mapmaker = {};
Mapmaker.TopicMappingView = (function($, famous) {
var Engine = famous.core.Engine;
var Surface = famous.core.Surface;
var ImageSurface = famous.surfaces.ImageSurface;
var Modifier = famous.core.Modifier;
var StateModifier = famous.modifiers.StateModifier;
var ... |
},
mousemove: function(event) {
var m = this.mapping;
var newX, newY;
if (this.mouseIsDown) {
if (!this.hasMoved) this.hasMoved = true;
newX = this.topicParticle.getTransform()[12] + event.movementX;
newY = this.topicParticle.getTransform()[13] + event.movementY;
// modify the mapping, t... | {
$(document).trigger(Mapmaker.TopicMappingView.events.doubleClick, [this]);
} | conditional_block |
top-navigation.component.ts | import { Component, Input, OnInit, OnDestroy, ChangeDetectionStrategy, ViewChild, ElementRef } from '@angular/core';
import { USER_GET, USER_GET_SUCCESS, USER_CREATE, USER_LOGOUT, USER_CREATE_SUCCESS, USER_LOGOUT_SUCCESS } from '../../store/profile/profile.actions';
import { ProfileEffects } from '../../store/profile/p... |
ngOnDestroy() {
this.subs.forEach(sub => {
sub.unsubscribe();
});
}
toggle() {
this.topnav.nativeElement.classList.toggle(['responsive']);
}
}
| {
this.store.dispatch({
type: USER_GET
});
} | identifier_body |
top-navigation.component.ts | import { Component, Input, OnInit, OnDestroy, ChangeDetectionStrategy, ViewChild, ElementRef } from '@angular/core';
import { USER_GET, USER_GET_SUCCESS, USER_CREATE, USER_LOGOUT, USER_CREATE_SUCCESS, USER_LOGOUT_SUCCESS } from '../../store/profile/profile.actions';
import { ProfileEffects } from '../../store/profile/p... | () {
this.topnav.nativeElement.classList.toggle(['responsive']);
}
}
| toggle | identifier_name |
top-navigation.component.ts | import { Component, Input, OnInit, OnDestroy, ChangeDetectionStrategy, ViewChild, ElementRef } from '@angular/core';
import { USER_GET, USER_GET_SUCCESS, USER_CREATE, USER_LOGOUT, USER_CREATE_SUCCESS, USER_LOGOUT_SUCCESS } from '../../store/profile/profile.actions';
import { ProfileEffects } from '../../store/profile/p... | constructor(private store: Store<IAppState>, private profileEffects: ProfileEffects) {
this.profileStore$ = store.select('profile');
this.profile$ = this.profileStore$.map((profile) => profile);
this.subs = [];
// this.subs.push(
// this.profileEffects.userCreate$
// .filter(action => a... | random_line_split | |
ln-CF.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
*/
// THIS CODE IS GENERATED - DO NOT MODIFY
// See angular/tools/gulp-tasks/cldr/extract.js
const u = undefined;
fun... | (n: number): number {
if (n === Math.floor(n) && n >= 0 && n <= 1) return 1;
return 5;
}
export default [
'ln-CF', [['ntɔ́ngɔ́', 'mpókwa'], u, u], u,
[
['e', 'y', 'm', 'm', 'm', 'm', 'p'], ['eye', 'ybo', 'mbl', 'mst', 'min', 'mtn', 'mps'],
[
'eyenga', 'mokɔlɔ mwa yambo', 'mokɔlɔ mwa míbalé', 'mok... | plural | identifier_name |
ln-CF.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
*/
// THIS CODE IS GENERATED - DO NOT MODIFY
// See angular/tools/gulp-tasks/cldr/extract.js
const u = undefined;
fun... |
export default [
'ln-CF', [['ntɔ́ngɔ́', 'mpókwa'], u, u], u,
[
['e', 'y', 'm', 'm', 'm', 'm', 'p'], ['eye', 'ybo', 'mbl', 'mst', 'min', 'mtn', 'mps'],
[
'eyenga', 'mokɔlɔ mwa yambo', 'mokɔlɔ mwa míbalé', 'mokɔlɔ mwa mísáto',
'mokɔlɔ ya mínéi', 'mokɔlɔ ya mítáno', 'mpɔ́sɔ'
],
['eye', 'y... | {
if (n === Math.floor(n) && n >= 0 && n <= 1) return 1;
return 5;
} | identifier_body |
ln-CF.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
*/
// THIS CODE IS GENERATED - DO NOT MODIFY
// See angular/tools/gulp-tasks/cldr/extract.js
const u = undefined;
fun... | [',', '.', ';', '%', '+', '-', 'E', '×', '‰', '∞', 'NaN', ':'],
['#,##0.###', '#,##0%', '#,##0.00 ¤', '#E0'], 'FCFA', 'Falánga CFA BEAC',
{'CDF': ['FC'], 'JPY': ['JP¥', '¥'], 'USD': ['US$', '$']}, plural
]; | random_line_split | |
setup.py | from __future__ import print_function
from glob import glob
import os
import sys
from setuptools import setup, Extension
from Cython.Build import cythonize
if sys.version_info[:2] < (2, 7):
print(
'nxcpy requires Python version 2.7 or later' +
' ({}.{} detected).'.format(*sys.version_info[:2]))
... | #!/usr/bin/env python
# -*- coding: utf-8 -*- | random_line_split | |
setup.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
from glob import glob
import os
import sys
from setuptools import setup, Extension
from Cython.Build import cythonize
if sys.version_info[:2] < (2, 7):
|
libraries = [
('nxcpy', {'sources': glob('src/*.c') + glob('src/*/*.c'),
'depends': glob('src/*.h') + glob('src/*/*.h'),
'include_dirs': ['src']})]
ext_modules = cythonize([
Extension('*.*', ['*/*.pyx'],
include_dirs=['src'],
libraries=['nxcpy']),
Extension('... | print(
'nxcpy requires Python version 2.7 or later' +
' ({}.{} detected).'.format(*sys.version_info[:2]))
# Because networkx does
sys.exit(-1) | conditional_block |
retiredminer.py | import parole
from parole.colornames import colors
from parole.display import interpolateRGB
import pygame, random
import sim_creatures, main, random
from util import *
description = \
"""
This guy should really look into another line of work.
"""
nagLines = [
'*sigh*',
"It's not been the same 'round... |
#========================================
thingClass = NPCClass
| super(NPCClass, self).listen(event)
if random.random() < 0.9:
return
if not visible(self):
return
if event.id == 'enter tile':
eObj, ePos, eMap = event.args
if eMap is self.parentTile.map and eObj is main.player:
self.say(random.ch... | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.