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 |
|---|---|---|---|---|
lib.rs | Kind`) in that it has no `Auto` value.
#[repr(u8)]
#[derive(Clone, Copy, Deserialize, Eq, FromPrimitive, PartialEq, Serialize)]
pub enum Cursor {
None,
Default,
Pointer,
ContextMenu,
Help,
Progress,
Wait,
Cell,
Crosshair,
Text,
VerticalText,
Alias,
Copy,
Move,
... | pub fn send(&self, msg: (Option<TopLevelBrowsingContextId>, EmbedderMsg)) {
// Send a message and kick the OS event loop awake.
if let Err(err) = self.sender.send(msg) {
warn!("Failed to send response ({:?}).", err);
}
self.event_loop_waker.wake();
}
}
impl Clone for... |
impl EmbedderProxy { | random_line_split |
lib.rs | >, EmbedderMsg)>,
pub event_loop_waker: Box<dyn EventLoopWaker>,
}
impl EmbedderProxy {
pub fn send(&self, msg: (Option<TopLevelBrowsingContextId>, EmbedderMsg)) {
// Send a message and kick the OS event loop awake.
if let Err(err) = self.sender.send(msg) {
warn!("Failed to send res... | ositionState {
| identifier_name | |
wsgi.py | """
WSGI config for opendai_lleida_web project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APP... | middleware here, or combine a Django application with an application of another
framework.
"""
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "admin_web.settings-production")
# This application object is used by any WSGI server configured to use this
# file. This includes Django's development server, if t... | that later delegates to the Django one. For example, you could introduce WSGI | random_line_split |
Authorization.js | /*
* TeleStax, Open Source Cloud Communications Copyright 2012.
* and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser... |
Authorization.prototype = new AuthenticationHeader();
Authorization.prototype.constructor=Authorization;
Authorization.prototype.NAME = "Authorization";
Authorization.prototype.COMMA = ",";
Authorization.prototype.DIGEST = "Digest";
| {
if(logger!=undefined) logger.debug("Authorization:Authorization()");
this.classname="Authorization";
this.headerName=this.NAME;
this.parameters = new NameValueList();
this.duplicates = new DuplicateNameValueList();
this.parameters.setSeparator(this.COMMA);
this.scheme = this.DIGEST;
} | identifier_body |
Authorization.js | /*
* TeleStax, Open Source Cloud Communications Copyright 2012.
* and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser... | () {
if(logger!=undefined) logger.debug("Authorization:Authorization()");
this.classname="Authorization";
this.headerName=this.NAME;
this.parameters = new NameValueList();
this.duplicates = new DuplicateNameValueList();
this.parameters.setSeparator(this.COMMA);
this.scheme = this.DIGEST;
}
... | Authorization | identifier_name |
Authorization.js | /* | * by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* ... | * TeleStax, Open Source Cloud Communications Copyright 2012.
* and individual contributors | random_line_split |
expression.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {AST, ASTWithSource, Binary, Conditional, Interpolation, KeyedRead, LiteralArray, LiteralMap, LiteralPrimitiv... | else {
return ts.createLiteral(ast.value);
}
} else if (ast instanceof MethodCall) {
const receiver = astToTypescript(ast.receiver, maybeResolve, config);
const method = ts.createPropertyAccess(receiver, ast.name);
const args = ast.args.map(expr => astToTypescript(expr, maybeResolve, config));
... | {
return ts.createNull();
} | conditional_block |
expression.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {AST, ASTWithSource, Binary, Conditional, Interpolation, KeyedRead, LiteralArray, LiteralMap, LiteralPrimitiv... |
function safeTernary(
lhs: ts.Expression, whenNotNull: ts.Expression, whenNull: ts.Expression): ts.Expression {
const notNullComp = ts.createBinary(lhs, ts.SyntaxKind.ExclamationEqualsToken, ts.createNull());
const ternary = ts.createConditional(notNullComp, whenNotNull, whenNull);
return ts.createParen(ter... | {
// Reduce the `asts` array into a `ts.Expression`. Multiple expressions are combined into a
// `ts.BinaryExpression` with a comma separator. First make a copy of the input array, as
// it will be modified during the reduction.
const asts = astArray.slice();
return asts.reduce(
(lhs, ast) => ts.createB... | identifier_body |
expression.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {AST, ASTWithSource, Binary, Conditional, Interpolation, KeyedRead, LiteralArray, LiteralMap, LiteralPrimitiv... | const rhs = astToTypescript(ast.right, maybeResolve, config);
const op = BINARY_OPS.get(ast.operation);
if (op === undefined) {
throw new Error(`Unsupported Binary.operation: ${ast.operation}`);
}
return ts.createBinary(lhs, op as any, rhs);
} else if (ast instanceof LiteralPrimitive) {
... | const lhs = astToTypescript(ast.left, maybeResolve, config); | random_line_split |
expression.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {AST, ASTWithSource, Binary, Conditional, Interpolation, KeyedRead, LiteralArray, LiteralMap, LiteralPrimitiv... | (
ast: AST, maybeResolve: (ast: AST) => ts.Expression | null,
config: TypeCheckingConfig): ts.Expression {
const resolved = maybeResolve(ast);
if (resolved !== null) {
return resolved;
}
// Branch based on the type of expression being processed.
if (ast instanceof ASTWithSource) {
// Fall thro... | astToTypescript | identifier_name |
CalcModelEnum.js | /**
* AvaTax Brazil
* The Avatax-Brazil API exposes the most commonly services available for interacting with the AvaTax-Brazil services, allowing calculation of taxes, issuing electronic invoice documents and modifying existing transactions when allowed by tax authorities. This API is exclusively for use by busines... |
/**
* Enum class CalcModelEnum.
* @enum {}
* @readonly
*/
var exports = {
/**
* value: "rate"
* @const
*/
"rate": "rate",
/**
* value: "quantity"
* @const
*/
"quantity": "quantity" };
/**
* Returns a <code>CalcModelEnum</code> enum value from a Javas... | }
}(this, function(ApiClient) {
'use strict';
| random_line_split |
isr.rs | // Zinc, the bare metal stack for rust.
// Copyright 2014 Vladimir "farcaller" Pouzanov <farcaller@gmail.com>
//
// 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.o... | #[path="cortex_m3/isr.rs"] pub mod isr_cortex_m4;
#[cfg(feature = "mcu_lpc17xx")]
#[path="lpc17xx/isr.rs"] pub mod isr_lpc17xx;
#[cfg(feature = "mcu_k20")]
#[path="k20/isr.rs"] pub mod isr_k20;
#[cfg(feature = "mcu_tiva_c")]
#[path="tiva_c/isr.rs"] pub mod isr_tiva_c; |
#[cfg(feature = "cpu_cortex-m3")]
#[path="cortex_m3/isr.rs"] pub mod isr_cortex_m3;
#[cfg(feature = "cpu_cortex-m4")] | random_line_split |
Wait.ts |
import { } from "../typings/UserScript.d";
/// <reference path="../typings/globals/jquery/index.d.ts" />
export function WaitUntil(
check: string|string[]|CheckCallback,
cb: Callback,
nTimeout: number|boolean = 10000,
nInterval: number = 150)
{
if ('string' == typeof check) {
check = (<str... |
var timer = setInterval(() => {
if (!isReady()) {
return ;
}
clearInterval(timer);
cb.call(this);
}, nInterval);
if (nTimeout !== true) {
setTimeout(() => {
clearInterval(timer);
}, nTimeout as number);
}
}
inte... | {
isReady = () => {
try {
return (<CheckCallback>check)();
} catch (error) {
return false;
}
};
} | conditional_block |
Wait.ts |
import { } from "../typings/UserScript.d";
/// <reference path="../typings/globals/jquery/index.d.ts" />
export function WaitUntil(
check: string|string[]|CheckCallback,
cb: Callback,
nTimeout: number|boolean = 10000,
nInterval: number = 150)
| return (<CheckCallback>check)();
} catch (error) {
return false;
}
};
}
var timer = setInterval(() => {
if (!isReady()) {
return ;
}
clearInterval(timer);
cb.call(this);
}, nInterval);
... | {
if ('string' == typeof check) {
check = (<string>check).split('.');
}
var isReady: CheckCallback;
if ($.isArray(check)) {
isReady = () => {
var r: any = unsafeWindow;
for (var i = 0; i < check.length; i++) {
r = r[check[i]];
... | identifier_body |
Wait.ts | import { } from "../typings/UserScript.d";
/// <reference path="../typings/globals/jquery/index.d.ts" />
export function WaitUntil(
check: string|string[]|CheckCallback,
cb: Callback,
nTimeout: number|boolean = 10000, | }
var isReady: CheckCallback;
if ($.isArray(check)) {
isReady = () => {
var r: any = unsafeWindow;
for (var i = 0; i < check.length; i++) {
r = r[check[i]];
if (!r) return false;
}
return true
... | nInterval: number = 150)
{
if ('string' == typeof check) {
check = (<string>check).split('.'); | random_line_split |
Wait.ts |
import { } from "../typings/UserScript.d";
/// <reference path="../typings/globals/jquery/index.d.ts" />
export function | (
check: string|string[]|CheckCallback,
cb: Callback,
nTimeout: number|boolean = 10000,
nInterval: number = 150)
{
if ('string' == typeof check) {
check = (<string>check).split('.');
}
var isReady: CheckCallback;
if ($.isArray(check)) {
isReady = () => {
... | WaitUntil | identifier_name |
gamestate.rs | 000;
pub const GRID_WIDTH: i16 = 400;
pub const BLOCK_SIZE: i16 = 1;
pub const WINDOW_HEIGHT: i16 = GRID_HEIGHT * BLOCK_SIZE;
pub const WINDOW_WIDTH: i16 = GRID_WIDTH * BLOCK_SIZE;
pub const RAIN_SPARSENESS: i16 = 5;
pub const X: bool = true;
pub const o: bool = false;
#[derive(Eq, PartialEq, Clone)]
pub struct Lo... | (x: i16, y: i16) -> bool {
!(x < 0 || x >= GRID_WIDTH || y < 0 || y >= GRID_HEIGHT)
}
pub fn update(&mut self) {
// MAIN LOGIC
for (index, particle) in self.particles.iter_mut().enumerate() {
let (x, y) = (particle.x, particle.y);
let neighbours = self.map.get_ne... | is_valid | identifier_name |
gamestate.rs | 000;
pub const GRID_WIDTH: i16 = 400;
pub const BLOCK_SIZE: i16 = 1;
pub const WINDOW_HEIGHT: i16 = GRID_HEIGHT * BLOCK_SIZE;
pub const WINDOW_WIDTH: i16 = GRID_WIDTH * BLOCK_SIZE;
pub const RAIN_SPARSENESS: i16 = 5;
pub const X: bool = true;
pub const o: bool = false;
#[derive(Eq, PartialEq, Clone)]
pub struct Lo... |
}
pub fn paint_square_obstacles(&mut self, ux: i16, uy: i16, dx: i16, dy: i16) {
//if Self::is_valid(ux + dx, uy + dy) {
if Self::is_valid(ux, uy) && Self::is_valid(ux + dx, uy + dy) {
for x in ux..ux + dx {
for y in uy..uy + dy {
if !self.map.is... | {
for x in ux..ux + dx {
for y in uy..uy + dy {
self.map.remove_coord_map(x, y);
}
}
let ul = Loc { x: ux, y: uy };
let lr = Loc {
x: ux + dx,
y: uy + dy,
};
Self::... | conditional_block |
gamestate.rs | 000;
pub const GRID_WIDTH: i16 = 400;
pub const BLOCK_SIZE: i16 = 1;
pub const WINDOW_HEIGHT: i16 = GRID_HEIGHT * BLOCK_SIZE;
pub const WINDOW_WIDTH: i16 = GRID_WIDTH * BLOCK_SIZE;
pub const RAIN_SPARSENESS: i16 = 5;
pub const X: bool = true;
pub const o: bool = false;
#[derive(Eq, PartialEq, Clone)]
pub struct Lo... |
fn new() -> Map {
// casting a vector of bools into a 2d array of bools unsafely
// to avoid using unstable box_syntax
// code taken from: //https://gist.github.com/anonymous/62f21e4fb7a13867891c
let mut v: Vec<bool> = Vec::with_capacity(GRID_HEIGHT as usize * GRID_WIDTH as usize)... | {
self.map[x as usize][y as usize] = false;
} | identifier_body |
gamestate.rs | 1000;
pub const GRID_WIDTH: i16 = 400;
pub const BLOCK_SIZE: i16 = 1;
pub const WINDOW_HEIGHT: i16 = GRID_HEIGHT * BLOCK_SIZE;
pub const WINDOW_WIDTH: i16 = GRID_WIDTH * BLOCK_SIZE;
pub const RAIN_SPARSENESS: i16 = 5;
pub const X: bool = true;
pub const o: bool = false;
#[derive(Eq, PartialEq, Clone)]
pub struct L... | let neighbours = self.map.get_neighbours(x, y);
let (x_new, y_new) = match neighbours {
// 1-2-3 above 4-5 sides 6-7-8 below
(_, _, _, _, _, _, o, _) => (x, y + 1), //fall straight down if possible
(_, X, _, o, X, _, X, _) => (x - 1, y), //move sid... | // MAIN LOGIC
for (index, particle) in self.particles.iter_mut().enumerate() {
let (x, y) = (particle.x, particle.y); | random_line_split |
lib.rs | //! # Fixerio API Wrapper
//!
//! http://fixer.io
//!
//! ## Usage
//! Add the following to `Cargo.toml`:
//!
//! ```rust,ignore | //! [dependencies]
//! fixerio = "0.1.3"
//! ```
//!
//! Synchronous example:
//!
//! ```rust,no_run
//!
//! extern crate fixerio;
//!
//! use fixerio::{Config, Currency, SyncApi};
//!
//! fn main() {
//! let api = SyncApi::new().expect("Error creating API");
//!
//! let config = Config::new(Currency::USD);
//!... | random_line_split | |
traversal.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use context::{LocalStyleContext, SharedStyleContext, StyleContext};
use dom::OpaqueNode;
use gecko::context::Stand... |
fn process_preorder(&self, node: GeckoNode<'ln>) -> RestyleResult {
// FIXME(pcwalton): Stop allocating here. Ideally this should just be done by the HTML
// parser.
node.initialize_data();
recalc_style_at(&self.context, self.root, node)
}
fn process_postorder(&self, _: G... | {
// See the comment in RecalcStyleAndConstructFlows::new for an explanation of why this is
// necessary.
let shared_lc: &'lc Self::SharedContext = unsafe { mem::transmute(shared) };
RecalcStyleOnly {
context: StandaloneStyleContext::new(shared_lc),
root: root,
... | identifier_body |
traversal.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use context::{LocalStyleContext, SharedStyleContext, StyleContext};
use dom::OpaqueNode;
use gecko::context::Stand... | // parser.
node.initialize_data();
recalc_style_at(&self.context, self.root, node)
}
fn process_postorder(&self, _: GeckoNode<'ln>) {
unreachable!();
}
/// We don't use the post-order traversal for anything.
fn needs_postorder_traversal(&self) -> bool { false }
... | // FIXME(pcwalton): Stop allocating here. Ideally this should just be done by the HTML | random_line_split |
traversal.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use context::{LocalStyleContext, SharedStyleContext, StyleContext};
use dom::OpaqueNode;
use gecko::context::Stand... | (&self) -> bool { false }
fn local_context(&self) -> &LocalStyleContext {
self.context.local_context()
}
}
| needs_postorder_traversal | identifier_name |
yield-promise-reject-next-for-await-of-sync-iterator.js | // This file was procedurally generated from the following sources:
// - src/async-generators/yield-promise-reject-next-for-await-of-sync-iterator.case
// - src/async-generators/default/async-expression.template
/*---
description: yield Promise.reject(value) in for-await-of is treated as throw value (Unnamed async gene... | features: [async-iteration]
flags: [generated, async]
info: |
Async Generator Function Definitions
AsyncGeneratorExpression :
async [no LineTerminator here] function * BindingIdentifier ( FormalParameters ) {
AsyncGeneratorBody }
---*/
let error = new Error();
let iterable = [
Promise.reject(e... | esid: prod-AsyncGeneratorExpression | random_line_split |
test_lib.js | jQuery(function(){
'use strict';
var Test={};
var tests=[];
var messages={
success: 'Success',
failed: 'FAILED',
pending: 'Pending...'
};
var classes = {
success: 'success',
failed: 'danger',
pending: 'warning'
}
var row_id_prefix = 'tests_td_';
var textProperty = (document.createElement('s... |
var assertionFailed = {};
TestController.prototype._setStatus=function(status, extra){
var status_td = this._row.getElementsByTagName('td')[1];
var display_string = messages[status];
if(extra){
display_string += " (" + extra + ")";
}
status_td[textProperty] = display_string;
status_td.className = ... | {
this._row = row;
this._asserted = false;
this._status='pending';
} | identifier_body |
test_lib.js | jQuery(function(){
'use strict';
var Test={};
var tests=[];
var messages={
success: 'Success',
failed: 'FAILED',
pending: 'Pending...'
};
var classes = {
success: 'success',
failed: 'danger',
pending: 'warning'
}
var row_id_prefix = 'tests_td_';
var textProperty = (document.createElement('s... | (row){
this._row = row;
this._asserted = false;
this._status='pending';
}
var assertionFailed = {};
TestController.prototype._setStatus=function(status, extra){
var status_td = this._row.getElementsByTagName('td')[1];
var display_string = messages[status];
if(extra){
display_string += " (" + extra... | TestController | identifier_name |
test_lib.js | jQuery(function(){
'use strict';
var Test={};
var tests=[];
var messages={
success: 'Success',
failed: 'FAILED',
pending: 'Pending...'
};
var classes = {
success: 'success',
failed: 'danger',
pending: 'warning'
}
var row_id_prefix = 'tests_td_';
var textProperty = (document.createElement('s... | this._asserted = false;
this._status='pending';
}
var assertionFailed = {};
TestController.prototype._setStatus=function(status, extra){
var status_td = this._row.getElementsByTagName('td')[1];
var display_string = messages[status];
if(extra){
display_string += " (" + extra + ")";
}
status_td[te... | this._row = row; | random_line_split |
test_lib.js | jQuery(function(){
'use strict';
var Test={};
var tests=[];
var messages={
success: 'Success',
failed: 'FAILED',
pending: 'Pending...'
};
var classes = {
success: 'success',
failed: 'danger',
pending: 'warning'
}
var row_id_prefix = 'tests_td_';
var textProperty = (document.createElement('s... |
try{
func();
}catch(e){
thrown = true;
}
this.assert(thrown, desc);
};
TestController.prototype.must_not_be_called = function(desc){
var test_controller = this;
if(!desc){
desc = 'function is not called';
}
return function(){
test_controller.assert(false, desc);
};
}
Test.run = fu... | {
desc = 'expected to throw exception';
} | conditional_block |
bound.js | /**
* @copyright
* The MIT License (MIT)
*
* Copyright (c) 2014 Cosmic Dynamo LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitatio... | (execData, dataRow, variable) {
return _boolean(variable.resolve(execData, dataRow) !== null);
}
return bound;
}); | bound | identifier_name |
bound.js | /**
* @copyright
* The MIT License (MIT)
*
* Copyright (c) 2014 Cosmic Dynamo LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitatio... | */
define([
"./_boolean"
], function (_boolean) {
/**
* Returns true if var is bound to a value. Returns false otherwise. Variables with the value NaN or INF are considered bound.
* @see http://www.w3.org/TR/sparql11-query/#func-bound
* @param {Object} execData
* @param {jazzHands.query.Dat... | random_line_split | |
bound.js | /**
* @copyright
* The MIT License (MIT)
*
* Copyright (c) 2014 Cosmic Dynamo LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitatio... |
return bound;
}); | {
return _boolean(variable.resolve(execData, dataRow) !== null);
} | identifier_body |
main.rs | /*
* main.rs
* This file is part of Oblique_Projection
*
* Copyright (C) 2017 - Lilith Wynter
*
* Oblique_Projection is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
... | temp_data.push(Vec::new());
for j in 0..num_dim-1 {
if j%2 == 0 {
temp_data[i].push(final_array[i][j] as f64 + 0.5*final_array[i][num_dim-1]*angle.cos() as f64);
} else {
temp_data[i].push(final_array[i][j] as f64 + 0.5*final_array[i][num_dim-1]*angle.sin() as f64);
... | {
// Gather data from specified file
let data = read_nd_data(file);
// The standard angle in a oblique projection
let angle: f64 = 63.4;
let mut final_array = data;
// Number of points in dataset
let num_points = final_array.len();
// Number of dimensions
let mut num_dim = final_array[0].le... | identifier_body |
main.rs | /*
* main.rs
* This file is part of Oblique_Projection
*
* Copyright (C) 2017 - Lilith Wynter
*
* Oblique_Projection is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
... | () {
oblique_projection_from_nd("./data/DorotheaData.csv");
}
| main | identifier_name |
main.rs | /*
* main.rs
* This file is part of Oblique_Projection
*
* Copyright (C) 2017 - Lilith Wynter
*
* Oblique_Projection is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
... |
}
}
let mut array_2d: Vec<[f64; 2]> = Vec::new();
// Change array structure for imaging
for i in 0..num_points {
array_2d.push([final_array[i][0], final_array[i][1]]);
}
array_to_image(&mut array_2d);
}
fn main() {
oblique_projection_from_nd("./data/DorotheaData.csv");
}
| {
smaller_than_10000 = false;
} | conditional_block |
main.rs | /*
* main.rs
* This file is part of Oblique_Projection
*
* Copyright (C) 2017 - Lilith Wynter
*
* Oblique_Projection is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
... | oblique_projection_from_nd("./data/DorotheaData.csv");
} | }
fn main() {
| random_line_split |
animate_pipe_flow_byframe_experiment_intensityonly.py | #!/usr/bin/python
import numpy as np
import sys
from numpy import *
import matplotlib.pyplot as pyplot
import matplotlib.animation as anim
import h5py
from matplotlib.colors import LogNorm
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import gridspec
import string
# --------------------------------------... | for sl in sls:
axI.plot(xlims,[sl,sl],color='white',linewidth=0.5)
# end for
axI.hold(False)
# Set the window, if it hasn't been already.
axI.set_xlim(xlims) # X axis
axI.set_ylim([-1.,1.]) # Y axis
realtime = tscale*t[i]
pyplot.title('Inte... | xlims = [0.,Lscale]
timer.set_text(r'$\tau = %3.2e$'%t[i])
# Keep a smaller number of bins for the transverse direction.
binref=41
mybins=[linspace(xlims[0],xlims[1],int(binref*Lscale)),linspace(-1.,1.,binref)]
slsidx = binref/2 + np.floor(sls*binref/2)
# Change the current a... | identifier_body |
animate_pipe_flow_byframe_experiment_intensityonly.py | #!/usr/bin/python
import numpy as np
import sys
from numpy import *
import matplotlib.pyplot as pyplot
import matplotlib.animation as anim
import h5py
from matplotlib.colors import LogNorm
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import gridspec
import string
# --------------------------------------... |
# end for
axI.hold(False)
# Set the window, if it hasn't been already.
axI.set_xlim(xlims) # X axis
axI.set_ylim([-1.,1.]) # Y axis
realtime = tscale*t[i]
pyplot.title('Intensity')
#
pyplot.sca(axISl)
pyplot.cla()
axISl.hold(True)
... | axI.plot(xlims,[sl,sl],color='white',linewidth=0.5) | conditional_block |
animate_pipe_flow_byframe_experiment_intensityonly.py | #!/usr/bin/python
import numpy as np
import sys
from numpy import *
import matplotlib.pyplot as pyplot
import matplotlib.animation as anim
import h5py
from matplotlib.colors import LogNorm
from mpl_toolkits.mplot3d import Axes3D | # ------------------------------------------------
def rescale_coord(x,Pe,t):
# Transform x coordinates from local back to lab coordinates.
umean = 0.25 # Nondimensionalized lab frame average flow speed.
return (x + Pe*umean*t)
# end def
def snapshot(i,axI,axISl,xi,yi,zi,Pe,aratio,t,sls,Lscale,tscal... | from matplotlib import gridspec
import string
| random_line_split |
animate_pipe_flow_byframe_experiment_intensityonly.py | #!/usr/bin/python
import numpy as np
import sys
from numpy import *
import matplotlib.pyplot as pyplot
import matplotlib.animation as anim
import h5py
from matplotlib.colors import LogNorm
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import gridspec
import string
# --------------------------------------... | (x,Pe,t):
# Transform x coordinates from local back to lab coordinates.
umean = 0.25 # Nondimensionalized lab frame average flow speed.
return (x + Pe*umean*t)
# end def
def snapshot(i,axI,axISl,xi,yi,zi,Pe,aratio,t,sls,Lscale,tscale,mmap,timer):
# x-bounds for the axes.
xlims = [0.,Lscal... | rescale_coord | identifier_name |
mod.rs | pub use types::{Anchor, ExclusiveZone, KeyboardInteractivity, Layer, Margins};
/// The role of a wlr_layer_shell_surface
pub const LAYER_SURFACE_ROLE: &str = "zwlr_layer_surface_v1";
/// Attributes for layer surface
#[derive(Debug)]
pub struct LayerSurfaceAttributes {
surface: zwlr_layer_surface_v1::ZwlrLayerSurf... | {
known_layers: Vec<LayerSurface>,
}
impl LayerShellState {
/// Access all the shell surfaces known by this handler
pub fn layer_surfaces(&self) -> &[LayerSurface] {
&self.known_layers[..]
}
}
#[derive(Clone)]
struct ShellUserData {
_log: ::slog::Logger,
user_impl: Rc<RefCell<dyn FnMu... | LayerShellState | identifier_name |
mod.rs | state should be cloned to the current
/// during a commit.
pub last_acked: Option<LayerSurfaceState>,
/// Holds the current state of the layer after a successful
/// commit.
pub current: LayerSurfaceState,
}
impl LayerSurfaceAttributes {
fn new(surface: zwlr_layer_surface_v1::ZwlrLayerSurfaceV... | {
return Err(DeadResource);
} | conditional_block | |
mod.rs | },
};
mod handlers;
mod types;
pub use types::{Anchor, ExclusiveZone, KeyboardInteractivity, Layer, Margins};
/// The role of a wlr_layer_shell_surface
pub const LAYER_SURFACE_ROLE: &str = "zwlr_layer_surface_v1";
/// Attributes for layer surface
#[derive(Debug)]
pub struct LayerSurfaceAttributes {
surface:... | Serial, SERIAL_COUNTER, | random_line_split | |
mod.rs | pub use types::{Anchor, ExclusiveZone, KeyboardInteractivity, Layer, Margins};
/// The role of a wlr_layer_shell_surface
pub const LAYER_SURFACE_ROLE: &str = "zwlr_layer_surface_v1";
/// Attributes for layer surface
#[derive(Debug)]
pub struct LayerSurfaceAttributes {
surface: zwlr_layer_surface_v1::ZwlrLayerSurf... |
fn merge_into(self, into: &mut Self) {
*into = self;
}
}
/// Shell global state
///
/// This state allows you to retrieve a list of surfaces
/// currently known to the shell global.
#[derive(Debug)]
pub struct LayerShellState {
known_layers: Vec<LayerSurface>,
}
impl LayerShellState {
/// Acc... | {
*self
} | identifier_body |
http_server.rs | use std::thread;
use actix_web::{middleware, web, App, HttpRequest, HttpServer, Responder};
use prometheus::{Encoder, TextEncoder};
pub fn start_http_server(
addr: std::net::SocketAddr,
) -> (thread::JoinHandle<()>, actix_rt::System, actix_web::dev::Server) {
let (tx, rx) = std::sync::mpsc::channel();
l... |
async fn metrics(_req: HttpRequest) -> impl Responder {
let metric_families = prometheus::gather();
let encoder = TextEncoder::new();
let mut buffer = Vec::new();
let encode_result = encoder.encode(&metric_families, &mut buffer);
match encode_result {
Ok(_) => {}
Err(e) => error... | let server = rx_http.recv().unwrap();
(join_handle, system, server)
} | random_line_split |
http_server.rs | use std::thread;
use actix_web::{middleware, web, App, HttpRequest, HttpServer, Responder};
use prometheus::{Encoder, TextEncoder};
pub fn start_http_server(
addr: std::net::SocketAddr,
) -> (thread::JoinHandle<()>, actix_rt::System, actix_web::dev::Server) {
let (tx, rx) = std::sync::mpsc::channel();
l... | (_req: HttpRequest) -> impl Responder {
let metric_families = prometheus::gather();
let encoder = TextEncoder::new();
let mut buffer = Vec::new();
let encode_result = encoder.encode(&metric_families, &mut buffer);
match encode_result {
Ok(_) => {}
Err(e) => error!("[E02011] Error... | metrics | identifier_name |
http_server.rs | use std::thread;
use actix_web::{middleware, web, App, HttpRequest, HttpServer, Responder};
use prometheus::{Encoder, TextEncoder};
pub fn start_http_server(
addr: std::net::SocketAddr,
) -> (thread::JoinHandle<()>, actix_rt::System, actix_web::dev::Server) |
system.run().unwrap();
debug!("http server shutdown");
});
let system = rx.recv().unwrap();
let server = rx_http.recv().unwrap();
(join_handle, system, server)
}
async fn metrics(_req: HttpRequest) -> impl Responder {
let metric_families = prometheus::gather();
let encoder... | {
let (tx, rx) = std::sync::mpsc::channel();
let (tx_http, rx_http) = std::sync::mpsc::channel();
let join_handle = thread::spawn(move || {
let system = actix_rt::System::new("http_server");
let server = HttpServer::new(move || {
App::new()
.wrap(middleware::Log... | identifier_body |
message.rs | address::Address;
use network::message_network;
use network::message_blockdata;
use network::encodable::{ConsensusDecodable, ConsensusEncodable};
use network::encodable::CheckedData;
use network::serialize::{serialize, RawDecoder, SimpleEncoder, SimpleDecoder};
use util::{self, propagate_err};
/// Serializer for comma... | cmd => return Err(d.error(format!("unrecognized network command `{}`", cmd)))
};
Ok(RawNetworkMessage {
magic: magic,
payload: payload
})
}
}
#[cfg(test)]
mod test {
use super::{RawNetworkMessage, NetworkMessage, CommandString};
use network::ser... | {
let magic = try!(ConsensusDecodable::consensus_decode(d));
let CommandString(cmd): CommandString= try!(ConsensusDecodable::consensus_decode(d));
let CheckedData(raw_payload): CheckedData = try!(ConsensusDecodable::consensus_decode(d));
let mut mem_d = RawDecoder::new(Cursor::new(raw_p... | identifier_body |
message.rs | address::Address;
use network::message_network;
use network::message_blockdata;
use network::encodable::{ConsensusDecodable, ConsensusEncodable};
use network::encodable::CheckedData;
use network::serialize::{serialize, RawDecoder, SimpleEncoder, SimpleDecoder};
use util::{self, propagate_err};
/// Serializer for comma... | /// `verack`
Verack,
/// `addr`
Addr(Vec<(u32, Address)>),
/// `inv`
Inv(Vec<message_blockdata::Inventory>),
/// `getdata`
GetData(Vec<message_blockdata::Inventory>),
/// `notfound`
NotFound(Vec<message_blockdata::Inventory>),
/// `getblocks`
GetBlocks(message_blockdata::... | /// A Network message payload. Proper documentation is available on the Bitcoin
/// wiki https://en.bitcoin.it/wiki/Protocol_specification
pub enum NetworkMessage {
/// `version`
Version(message_network::VersionMessage), | random_line_split |
message.rs | address::Address;
use network::message_network;
use network::message_blockdata;
use network::encodable::{ConsensusDecodable, ConsensusEncodable};
use network::encodable::CheckedData;
use network::serialize::{serialize, RawDecoder, SimpleEncoder, SimpleDecoder};
use util::{self, propagate_err};
/// Serializer for comma... | (d: &mut D) -> Result<RawNetworkMessage, D::Error> {
let magic = try!(ConsensusDecodable::consensus_decode(d));
let CommandString(cmd): CommandString= try!(ConsensusDecodable::consensus_decode(d));
let CheckedData(raw_payload): CheckedData = try!(ConsensusDecodable::consensus_decode(d));
... | consensus_decode | identifier_name |
app.js | import React, { Component } from 'react';
import Radium from 'radium';
import { DragDropContext } from 'react-dnd';
import HTML5Backend from 'react-dnd-html5-backend';
import store from '../store.js';
import MapContainer from './map.js';
import Toolbar from './toolbar.js';
import PanelFeature from './panel-feature.js';... |
render() {
const toolbarHeight = 50;
return (
<div style={this.styles.vertical}>
<Toolbar height={toolbarHeight} />
<div style={this.styles.horizontal}>
<MapContainer height={toolbarHeight} />
<div style={this.styles.spacer}></div>
<PanelFeature />
... | {
return {
horizontal: {
display: 'flex',
flex: '1',
flexFlow: 'row nowrap',
},
spacer: { flex: '1 1 auto' },
vertical: {
display: 'flex',
flexFlow: 'column nowrap',
fontFamily: 'Roboto, sans-serif',
fontSize: '16px',
height: '1... | identifier_body |
app.js | import store from '../store.js';
import MapContainer from './map.js';
import Toolbar from './toolbar.js';
import PanelFeature from './panel-feature.js';
import PanelMarkers from './panel-markers.js';
import PanelLayers from './panel-layers.js';
import PanelTraces from './panel-traces.js';
import PanelGroups from './pan... | import React, { Component } from 'react';
import Radium from 'radium';
import { DragDropContext } from 'react-dnd';
import HTML5Backend from 'react-dnd-html5-backend'; | random_line_split | |
app.js | import React, { Component } from 'react';
import Radium from 'radium';
import { DragDropContext } from 'react-dnd';
import HTML5Backend from 'react-dnd-html5-backend';
import store from '../store.js';
import MapContainer from './map.js';
import Toolbar from './toolbar.js';
import PanelFeature from './panel-feature.js';... | () {
store.subscribe(() => this.forceUpdate());
}
get styles() {
return {
horizontal: {
display: 'flex',
flex: '1',
flexFlow: 'row nowrap',
},
spacer: { flex: '1 1 auto' },
vertical: {
display: 'flex',
flexFlow: 'column nowrap',
fontFa... | componentWillMount | identifier_name |
event.rs | use crate::Token;
use super::Ready;
pub type SysEvent = Event;
#[derive(Debug, Clone)]
pub struct Event {
token: Token,
readiness: Ready,
}
impl Event {
pub(crate) fn new(readiness: Ready, token: Token) -> Event {
Event { token, readiness }
}
pub fn token(&self) -> Token {
self.... | }
pub fn is_priority(&self) -> bool {
self.readiness.is_priority()
}
pub fn is_aio(&self) -> bool {
self.readiness.is_aio()
}
pub fn is_lio(&self) -> bool {
self.readiness.is_lio()
}
} | }
pub fn is_hup(&self) -> bool {
self.readiness.is_hup() | random_line_split |
event.rs | use crate::Token;
use super::Ready;
pub type SysEvent = Event;
#[derive(Debug, Clone)]
pub struct Event {
token: Token,
readiness: Ready,
}
impl Event {
pub(crate) fn new(readiness: Ready, token: Token) -> Event {
Event { token, readiness }
}
pub fn token(&self) -> Token {
self.... | (&self) -> bool {
self.readiness.is_readable()
}
pub fn is_writable(&self) -> bool {
self.readiness.is_writable()
}
pub fn is_error(&self) -> bool {
self.readiness.is_error()
}
pub fn is_hup(&self) -> bool {
self.readiness.is_hup()
}
pub fn is_priority... | is_readable | identifier_name |
GameScreen.js | import animate;
import event.Emitter as Emitter;
import device;
import ui.View;
import ui.ImageView;
import ui.TextView;
import src.Match3Core as Core;
import src.Utils as Utils;
//var Chance = require('chance');
//Some constants
var CoreGame = new Core();
var level = new Core();
//var chance = new Chance();
/* The G... | CoreGame.InitializeBoard();
CoreGame.CreateLevel();
//Find Initial Moves and Clusters
CoreGame.FindMoves();
CoreGame.FindClusters();
}
*/
// Starts the game
function start_game_flow() {
CoreGame.ReadyGame();
play_game(this);
}
// Game play
function play_game() {
if(CoreGame.moves.length === 0)... |
/*
function ReadyGame() { | random_line_split |
GameScreen.js | import animate;
import event.Emitter as Emitter;
import device;
import ui.View;
import ui.ImageView;
import ui.TextView;
import src.Match3Core as Core;
import src.Utils as Utils;
//var Chance = require('chance');
//Some constants
var CoreGame = new Core();
var level = new Core();
//var chance = new Chance();
/* The G... |
function emit_endgame_event() {
this.once('InputSelect', function() {
this.emit('gamescreen:end');
reset_game.call(this);
});
}
function reset_game() {}
| {
//slight delay before allowing a tap reset
setTimeout(emit_endgame_event.bind(this), 2000);
} | identifier_body |
GameScreen.js | import animate;
import event.Emitter as Emitter;
import device;
import ui.View;
import ui.ImageView;
import ui.TextView;
import src.Match3Core as Core;
import src.Utils as Utils;
//var Chance = require('chance');
//Some constants
var CoreGame = new Core();
var level = new Core();
//var chance = new Chance();
/* The G... |
}
// function tick() {}
// function update_countdown() {}
// Game End
function end_game_flow() {
//slight delay before allowing a tap reset
setTimeout(emit_endgame_event.bind(this), 2000);
}
function emit_endgame_event() {
this.once('InputSelect', function() {
this.emit('gamescreen:end');
reset_game.call(thi... | {
end_game_flow.call(this);
} | conditional_block |
GameScreen.js | import animate;
import event.Emitter as Emitter;
import device;
import ui.View;
import ui.ImageView;
import ui.TextView;
import src.Match3Core as Core;
import src.Utils as Utils;
//var Chance = require('chance');
//Some constants
var CoreGame = new Core();
var level = new Core();
//var chance = new Chance();
/* The G... | () {}
| reset_game | identifier_name |
StokesVortices.py | # Copyright (C) 2015 Jan Blechta
#
# This file is part of dolfin-tape.
#
# dolfin-tape is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later ve... |
def mu(self):
return self._mu
def g(self):
return lambda s, d, eps: Constant(1.0/(2.0*self._mu))*s - d
class StokesVortices(GeneralizedStokesProblem):
n = 4 # Number of vortices
mu = 1.0
def __init__(self, N):
mesh = UnitSquareMesh(N, N, "crossed")
constitutive_... | return 2 | identifier_body |
StokesVortices.py | # Copyright (C) 2015 Jan Blechta
#
# This file is part of dolfin-tape.
#
# dolfin-tape is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later ve... | return 2
def mu(self):
return self._mu
def g(self):
return lambda s, d, eps: Constant(1.0/(2.0*self._mu))*s - d
class StokesVortices(GeneralizedStokesProblem):
n = 4 # Number of vortices
mu = 1.0
def __init__(self, N):
mesh = UnitSquareMesh(N, N, "crossed")
... |
def r(self): | random_line_split |
StokesVortices.py | # Copyright (C) 2015 Jan Blechta
#
# This file is part of dolfin-tape.
#
# dolfin-tape is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later ve... | (self):
return lambda s, d, eps: Constant(1.0/(2.0*self._mu))*s - d
class StokesVortices(GeneralizedStokesProblem):
n = 4 # Number of vortices
mu = 1.0
def __init__(self, N):
mesh = UnitSquareMesh(N, N, "crossed")
constitutive_law = NewtonianFluid(self.mu)
# FIXME: Those e... | g | identifier_name |
from_json.rs | // Copyright 2015, 2016 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any la... | pub trait FromJson {
/// Convert a JSON value to an instance of this type.
fn from_json(json: &Json) -> Self;
}
impl FromJson for U256 {
fn from_json(json: &Json) -> Self {
match *json {
Json::String(ref s) => {
if s.len() >= 2 && &s[0..2] == "0x" {
FromStr::from_str(&s[2..]).unwrap_or_else(|_| Defaul... | }
}
/// Trait allowing conversion from a JSON value. | random_line_split |
from_json.rs | // Copyright 2015, 2016 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any la... |
}
| {
match *json {
Json::String(ref s) => {
if s.len() >= 2 && &s[0..2] == "0x" {
FromStr::from_str(&s[2..]).unwrap_or_else(|_| Default::default())
} else {
Uint::from_dec_str(s).unwrap_or_else(|_| Default::default())
}
},
Json::U64(u) => From::from(u),
Json::I64(i) => From::from(i as u... | identifier_body |
from_json.rs | // Copyright 2015, 2016 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any la... | (json: &Json) -> Self {
match *json {
Json::String(ref s) => {
if s.len() >= 2 && &s[0..2] == "0x" {
FromStr::from_str(&s[2..]).unwrap_or_else(|_| Default::default())
} else {
Uint::from_dec_str(s).unwrap_or_else(|_| Default::default())
}
},
Json::U64(u) => From::from(u),
Json::I64(i... | from_json | identifier_name |
feedback-popup.component.ts | // Copyright 2021 The Oppia Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by ap... |
ngOnDestroy(): void {
this.backgroundMaskService.deactivateMask();
}
}
| {
this.closePopover.emit();
} | identifier_body |
feedback-popup.component.ts | // Copyright 2021 The Oppia Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by ap... | this.playerPositionService.getCurrentStateName()
).then(() => {
this.feedbackSubmitted = true;
setTimeout(() => {
this.close();
}, 2000);
});
}
}
close(): void {
this.closePopover.emit();
}
ngOnDestroy(): void {
this.backgroundMaskService.deact... | this.feedbackTitle,
this.feedbackText,
!this.isSubmitterAnonymized && this.isLoggedIn, | random_line_split |
feedback-popup.component.ts | // Copyright 2021 The Oppia Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by ap... |
}
close(): void {
this.closePopover.emit();
}
ngOnDestroy(): void {
this.backgroundMaskService.deactivateMask();
}
}
| {
this.feedbackPopupBackendApiService.submitFeedbackAsync(
this.feedbackTitle,
this.feedbackText,
!this.isSubmitterAnonymized && this.isLoggedIn,
this.playerPositionService.getCurrentStateName()
).then(() => {
this.feedbackSubmitted = true;
setTimeout(() => {
... | conditional_block |
feedback-popup.component.ts | // Copyright 2021 The Oppia Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by ap... | (): void {
this.closePopover.emit();
}
ngOnDestroy(): void {
this.backgroundMaskService.deactivateMask();
}
}
| close | identifier_name |
yahoo.js | /**
* Copyright 2016 The AMP HTML Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless require... | global.yadData = data;
writeScript(global, 'https://s.yimg.com/aaq/ampad/display.js');
} | random_line_split | |
yahoo.js | /**
* Copyright 2016 The AMP HTML Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless require... | {
validateData(data, ['sid', 'site', 'sa']);
global.yadData = data;
writeScript(global, 'https://s.yimg.com/aaq/ampad/display.js');
} | identifier_body | |
yahoo.js | /**
* Copyright 2016 The AMP HTML Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless require... | (global, data) {
validateData(data, ['sid', 'site', 'sa']);
global.yadData = data;
writeScript(global, 'https://s.yimg.com/aaq/ampad/display.js');
}
| yahoo | identifier_name |
jshint_runner.js | /*
* Copyright (c) 2011-2014 YY Digital Pty Ltd. All Rights Reserved.
* Please see the LICENSE file included with this distribution for details.
*/
var jshint = require("jshint").JSHINT,
logger = require("../../server/logger"),
fs = require("fs"),
path =require("path");
exports.checkContent = function... |
});
};
| {
exports.checkContent(file, fs.readFileSync(path.join(target_path, file)).toString());
} | conditional_block |
jshint_runner.js | /*
* Copyright (c) 2011-2014 YY Digital Pty Ltd. All Rights Reserved.
* Please see the LICENSE file included with this distribution for details.
*/
var jshint = require("jshint").JSHINT,
logger = require("../../server/logger"),
fs = require("fs"),
path =require("path");
exports.checkContent = function... |
exports.checkPath = function(target_path) {
fs.getList(target_path).files.forEach(function(file) {
if (file.match("js$") || file.match("json$")) {
exports.checkContent(file, fs.readFileSync(path.join(target_path, file)).toString());
}
});
}; | }
}; | random_line_split |
util.rs | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use std::sync::Arc;
use cpython::*;
use cpython_ext::{ExtractInner, PyPath, PyPathBuf, ResultPyErrExt};
use edenapi::{Progress, ProgressCal... | <'a>(
py: Python,
keys: impl IntoIterator<Item = &'a (PyPathBuf, PyBytes)>,
) -> PyResult<Vec<Key>> {
keys.into_iter()
.map(|(path, hgid)| to_key(py, path, hgid))
.collect()
}
pub fn wrap_callback(callback: PyObject) -> ProgressCallback {
Box::new(move |progress: Progress| {
let... | to_keys | identifier_name |
util.rs | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use std::sync::Arc;
use cpython::*;
use cpython_ext::{ExtractInner, PyPath, PyPathBuf, ResultPyErrExt};
use edenapi::{Progress, ProgressCal... |
pub fn as_deltastore(py: Python, store: PyObject) -> PyResult<Arc<dyn HgIdMutableDeltaStore>> {
Ok(store.extract::<mutabledeltastore>(py)?.extract_inner(py))
}
pub fn as_historystore(py: Python, store: PyObject) -> PyResult<Arc<dyn HgIdMutableHistoryStore>> {
Ok(store.extract::<mutablehistorystore>(py)?.extr... | {
Box::new(move |progress: Progress| {
let gil = Python::acquire_gil();
let py = gil.python();
let _ = callback.call(py, progress.as_tuple(), None);
})
} | identifier_body |
util.rs | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use std::sync::Arc;
use cpython::*;
use cpython_ext::{ExtractInner, PyPath, PyPathBuf, ResultPyErrExt};
use edenapi::{Progress, ProgressCal... | .transpose()?
.unwrap_or(attributes.parents);
attributes.child_metadata = attrs
.get_item(py, "child_metadata")
.map(|v| v.extract::<bool>(py))
.transpose()?
.unwrap_or(attributes.child_metadata);
Ok(attributes)
}
pub fn to_hgids(py: Python, hgids: impl IntoIter... | .get_item(py, "parents")
.map(|v| v.extract::<bool>(py)) | random_line_split |
util.js | /**
* Util of json ajax.
* author: firstboy
* require: jquery
*/
function Jsoncallback(url, callback, method, data, loadid) {
if (loadid) $('#'+loadid).fadeIn(200);
$.ajax({
type: method,
data: data,
scriptCharset: 'UTF-8',
dataType: 'json',
url: url,
success: function(json) {
if (loadid) $('... |
function addslashes(string) {
return string.replace(/\\/g, '\\\\').
replace(/\u0008/g, '\\b').
replace(/\t/g, '\\t').
replace(/\n/g, '\\n').
replace(/\f/g, '\\f').
replace(/\r/g, '\\r').
replace(/'/g, '\\\'').
replace(/"/g, '\\"');
}
function trim(str){
re... | {
return decodeURI(
(RegExp(name + "=" + "(.+?)(&|$)").exec(location.search)||[,null])[1]
);
} | identifier_body |
util.js | /**
* Util of json ajax.
* author: firstboy
* require: jquery
*/
function Jsoncallback(url, callback, method, data, loadid) {
if (loadid) $('#'+loadid).fadeIn(200);
$.ajax({
type: method,
data: data,
scriptCharset: 'UTF-8',
dataType: 'json',
url: url,
success: function(json) {
if (loadid) $('... | alert('[ERROR] -- JSON CALLBACK:\n'
+ '[ERROR:textStatus]: ' + textStatus
+ '[ERROR:errorThrown]: ' + errorThrown
+ '[ERROR:json.responseText]: ' + json.responseText);
}
});
}
function getURLParameter(name) {
return decodeURI(
(RegExp(name + "=" + "(.+?)(&|$)").exec(location.search)||[,... | },
error: function(json, textStatus, errorThrown) {
if (loadid) $('#'+loadid).fadeOut(200); | random_line_split |
util.js | /**
* Util of json ajax.
* author: firstboy
* require: jquery
*/
function | (url, callback, method, data, loadid) {
if (loadid) $('#'+loadid).fadeIn(200);
$.ajax({
type: method,
data: data,
scriptCharset: 'UTF-8',
dataType: 'json',
url: url,
success: function(json) {
if (loadid) $('#'+loadid).fadeOut(200);
callback(json);
},
error: function(json, textStatus, error... | Jsoncallback | identifier_name |
global_gen.rs | 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 the License is distributed on an "AS IS" BASIS,
// WITHOUT WARR... | pub fn is_loaded() -> bool {{
unsafe {{ storage::{fnname}.is_loaded }}
}}
#[allow(dead_code)]
pub fn load_with<F>(loadfn: F) where F: FnMut(&str) -> *const super::__gl_imports::libc::c_void {{
unsafe {{
... | {
for c in registry.cmd_iter() {
let fallbacks = match registry.aliases.get(&c.proto.ident) {
Some(v) => {
let names = v.iter().map(|name| format!("\"{}\"", super::gen_symbol_name(ns, &name[..]))).collect::<Vec<_>>();
format!("&[{}]", names.connect(", "))
... | identifier_body |
global_gen.rs | 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 the License is distributed on an "AS IS" BASIS,
// WITHOUT WARR... | }
/// Creates all the `<enum>` elements at the root of the bindings.
fn write_enums<W>(registry: &Registry, dest: &mut W) -> io::Result<()> where W: io::Write {
for e in registry.enum_iter() {
try!(super::gen_enum_item(e, "types::", dest));
}
Ok(())
}
/// Creates the functions corresponding to th... |
writeln!(dest, "
}}
") | random_line_split |
global_gen.rs | 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 the License is distributed on an "AS IS" BASIS,
// WITHOUT WARR... | <W>(ns: &Ns, dest: &mut W) -> io::Result<()> where W: io::Write {
writeln!(dest,
"#[inline(never)]
fn missing_fn_panic() -> ! {{
panic!(\"{ns} function was not loaded\")
}}
", ns = ns)
}
/// Creates the `load_with` function.
///
/// The function calls `load_with` in each... | write_panicking_fns | identifier_name |
test_checker.py | #
# Copyright 2014 Telefonica Investigacion y Desarrollo, S.A.U
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you unde... | new_password = "stronger"
self.assertRaises(exception.ValidationError,
checker.strong_check_password(new_password)) | identifier_body | |
test_checker.py | #
# Copyright 2014 Telefonica Investigacion y Desarrollo, S.A.U
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you unde... | (tests.BaseTestCase):
def test_checker(self):
new_password = "stronger"
self.assertRaises(exception.ValidationError,
checker.strong_check_password(new_password))
| TestPasswordChecker | identifier_name |
test_checker.py | #
# Copyright 2014 Telefonica Investigacion y Desarrollo, S.A.U
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you unde... | checker.strong_check_password(new_password)) | random_line_split | |
commons.js | // Extends jQuery API
jQuery.extend({uniqueArray:function(array){
return $.grep(array, function(el, index) {
return index === $.inArray(el, array);
});
}});
function removeByValue(arr, val) {
for(var i=0; i<arr.length; i++) {
if(arr[i] == val) {
arr.splice(i, 1);
bre... | else {
return results[1];
}
}
function addBibToContext( bibnum ) {
bibnum = parseInt(bibnum, 10);
var bibnums = getContextBiblioNumbers();
bibnums.push(bibnum);
setContextBiblioNumbers( bibnums );
setContextBiblioNumbers( $.uniqueArray( bibnums ) );
}
function delBibToContext( bibnum ... | {
return "";
} | conditional_block |
commons.js | // Extends jQuery API
jQuery.extend({uniqueArray:function(array){
return $.grep(array, function(el, index) {
return index === $.inArray(el, array);
});
}});
function removeByValue(arr, val) {
for(var i=0; i<arr.length; i++) {
if(arr[i] == val) {
arr.splice(i, 1);
bre... |
function addBibToContext( bibnum ) {
bibnum = parseInt(bibnum, 10);
var bibnums = getContextBiblioNumbers();
bibnums.push(bibnum);
setContextBiblioNumbers( bibnums );
setContextBiblioNumbers( $.uniqueArray( bibnums ) );
}
function delBibToContext( bibnum ) {
var bibnums = getContextBiblioNumb... | {
param = param.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+param+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( url );
if( results == null ) {
return "";
} else {
return results[1];
}
} | identifier_body |
commons.js | // Extends jQuery API
jQuery.extend({uniqueArray:function(array){
return $.grep(array, function(el, index) {
return index === $.inArray(el, array);
});
}});
function removeByValue(arr, val) {
for(var i=0; i<arr.length; i++) {
if(arr[i] == val) {
arr.splice(i, 1);
bre... | var results = regex.exec( url );
if( results == null ) {
return "";
} else {
return results[1];
}
}
function addBibToContext( bibnum ) {
bibnum = parseInt(bibnum, 10);
var bibnums = getContextBiblioNumbers();
bibnums.push(bibnum);
setContextBiblioNumbers( bibnums );
... | var regex = new RegExp( regexS ); | random_line_split |
commons.js | // Extends jQuery API
jQuery.extend({uniqueArray:function(array){
return $.grep(array, function(el, index) {
return index === $.inArray(el, array);
});
}});
function removeByValue(arr, val) {
for(var i=0; i<arr.length; i++) {
if(arr[i] == val) {
arr.splice(i, 1);
bre... | () {
var r = $.cookie('bibs_selected');
if ( r ) {
return JSON.parse(r);
}
r = new Array();
return r;
}
function resetSearchContext() {
setContextBiblioNumbers( new Array() );
}
$(document).ready(function(){
// forms with action leading to search
$("form[action*='search.pl']").... | getContextBiblioNumbers | identifier_name |
test_quantization_mkldnn.py | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may ... | import nose
nose.runmodule()
del os.environ['ENABLE_MKLDNN_QUANTIZATION_TEST']
del os.environ['MXNET_SUBGRAPH_BACKEND'] | conditional_block | |
test_quantization_mkldnn.py | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
| #
# 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 Li... | # "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
| random_line_split |
test_zbeacon.py | import unittest
import zmq
import struct
import uuid
import socket
from pyre.zactor import ZActor
from pyre.zbeacon import ZBeacon
class ZBeaconTest(unittest.TestCase):
def | (self, *args, **kwargs):
ctx = zmq.Context()
ctx = zmq.Context()
# two beacon frames
self.transmit1 = struct.pack('cccb16sH', b'Z', b'R', b'E',
1, uuid.uuid4().bytes,
socket.htons(9999))
self.transmit2 = struct.pack('cccb16sH'... | setUp | identifier_name |
test_zbeacon.py | import unittest
import zmq
import struct
import uuid
import socket
from pyre.zactor import ZActor
from pyre.zbeacon import ZBeacon
class ZBeaconTest(unittest.TestCase):
def setUp(self, *args, **kwargs):
ctx = zmq.Context() | self.transmit2 = struct.pack('cccb16sH', b'Z', b'R', b'E',
1, uuid.uuid4().bytes,
socket.htons(9999))
self.node1 = ZActor(ctx, ZBeacon)
self.node1.send_unicode("VERBOSE")
self.node1.send_unicode("CONFIGURE", zmq.SNDMORE)
self... | ctx = zmq.Context()
# two beacon frames
self.transmit1 = struct.pack('cccb16sH', b'Z', b'R', b'E',
1, uuid.uuid4().bytes,
socket.htons(9999)) | random_line_split |
test_zbeacon.py | import unittest
import zmq
import struct
import uuid
import socket
from pyre.zactor import ZActor
from pyre.zbeacon import ZBeacon
class ZBeaconTest(unittest.TestCase):
def setUp(self, *args, **kwargs):
ctx = zmq.Context()
ctx = zmq.Context()
# two beacon frames
self.transmit1 ... | try:
unittest.main()
except Exception as a:
print(a) | conditional_block | |
test_zbeacon.py | import unittest
import zmq
import struct
import uuid
import socket
from pyre.zactor import ZActor
from pyre.zbeacon import ZBeacon
class ZBeaconTest(unittest.TestCase):
| self.node2.send(struct.pack("I", 9999))
print("Hostname 2:", self.node2.recv_unicode())
# end setUp
def tearDown(self):
self.node1.destroy()
self.node2.destroy()
# end tearDown
def test_node1(self):
self.node1.send_unicode("PUBLISH", zmq.SNDMORE)
self.no... | def setUp(self, *args, **kwargs):
ctx = zmq.Context()
ctx = zmq.Context()
# two beacon frames
self.transmit1 = struct.pack('cccb16sH', b'Z', b'R', b'E',
1, uuid.uuid4().bytes,
socket.htons(9999))
self.transmit2 = struct.pack('... | identifier_body |
session_support.py | if heartbeats are not supported by device."""
try:
# Test if we can connect in a isolated graph + session
with ops.Graph().as_default():
with _clone_session(session) as temp_session:
with ops.device(device):
heartbeat_op = tpu_ops.worker_heartbeat('')
options = config_pb2.Ru... |
def __enter__(self):
self.configure_and_run()
def __exit__(self, exc_type, exc_val, exc_tb):
self.stop()
def run(self):
# Don't fetch logs or adjust timing: just ping the watchdog.
#
# If we hit an exception, reset our session as it is likely broken.
while self._running:
try:
... | logging.info('Stopping worker watchdog.')
self._worker_manager.configure(
event_pb2.WorkerHeartbeatRequest(
watchdog_config=event_pb2.WatchdogConfig(timeout_ms=-1,),
shutdown_mode=event_pb2.NOT_CONFIGURED))
self._running = False
self.join() | identifier_body |
session_support.py | if heartbeats are not supported by device."""
try:
# Test if we can connect in a isolated graph + session
with ops.Graph().as_default():
with _clone_session(session) as temp_session:
with ops.device(device):
heartbeat_op = tpu_ops.worker_heartbeat('')
options = config_pb2.Ru... | (object):
"""Manages the status/heartbeat monitor for a set of workers."""
def __init__(self, session, devices, heartbeat_ops, request_placeholder):
"""Construct a new WorkerHeartbeatManager.
(Prefer using `WorkerHeartbeatManager.from_devices` when possible.)
Args:
session: `tf.Session`, sessio... | WorkerHeartbeatManager | identifier_name |
session_support.py | if heartbeats are not supported by device."""
try:
# Test if we can connect in a isolated graph + session
with ops.Graph().as_default():
with _clone_session(session) as temp_session:
with ops.device(device):
heartbeat_op = tpu_ops.worker_heartbeat('')
options = config_pb2.Ru... |
def shutdown(self, timeout_ms=10000):
"""Shutdown all workers after `shutdown_timeout_secs`."""
logging.info('Shutting down %s.', self)
req = event_pb2.WorkerHeartbeatRequest(
watchdog_config=event_pb2.WatchdogConfig(timeout_ms=timeout_ms))
self.configure(req)
# Wait for workers to shutd... | self._request_placeholder)
def __repr__(self):
return 'HeartbeatManager(%s)' % ','.join(self._devices) | random_line_split |
session_support.py | if heartbeats are not supported by device."""
try:
# Test if we can connect in a isolated graph + session
with ops.Graph().as_default():
with _clone_session(session) as temp_session:
with ops.device(device):
heartbeat_op = tpu_ops.worker_heartbeat('')
options = config_pb2.Ru... |
else:
logging.warning('Heartbeat support not available for %s', device)
return WorkerHeartbeatManager(session, kept_devices, heartbeat_ops,
request_placeholder)
def num_workers(self):
return len(self._devices)
def configure(self, message):
"""Configure... | kept_devices.append(device)
heartbeat_ops.append(heartbeat_op) | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.