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 |
|---|---|---|---|---|
dig.py | # coding=utf-8
#
# Copyright 2016 F5 Networks 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 a... | elf, util):
super(Dig, self).__init__(util)
self._meta_data['required_command_parameters'].update(('utilCmdArgs',))
self._meta_data['required_json_kind'] = 'tm:util:dig:runstate'
self._meta_data['allowed_commands'].append('run')
| init__(s | identifier_name |
dig.py | # coding=utf-8
#
# Copyright 2016 F5 Networks 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 a... | at the end of its URI.
"""
def __init__(self, util):
super(Dig, self).__init__(util)
self._meta_data['required_command_parameters'].update(('utilCmdArgs',))
self._meta_data['required_json_kind'] = 'tm:util:dig:runstate'
self._meta_data['allowed_commands'].append('run') | .. note::
This is an unnamed resource so it has no ~Partition~Name pattern | random_line_split |
utility.ts | /*tslint:disable:no-bitwise*/
import {InjectedRouter} from 'react-router';
import * as store from 'store';
import {EcpState} from '../store/ecp.state';
import * as session from '../login/session.model';
import * as moment from 'moment';
export class Utility {
// temporary functions (this function will only be us... |
} catch (e) {
console.log(e);
}
return state;
}
public static setEcpState(session: session.SessionState) {
try {
store.set('session', session);
} catch (e) {
console.log(e);
}
}
public static sessionIsValid(session: s... | {
state.loginReducer.sessionExpires = moment.utc(state.loginReducer.sessionExpires);
} | conditional_block |
utility.ts | /*tslint:disable:no-bitwise*/
import {InjectedRouter} from 'react-router';
import * as store from 'store';
import {EcpState} from '../store/ecp.state';
import * as session from '../login/session.model';
import * as moment from 'moment';
export class Utility {
// temporary functions (this function will only be us... | (session: session.SessionState) {
if (session && session.isLoggedIn && session.sessionExpires && session.sessionExpires > moment.utc()) {
return true;
}
return false;
}
}
export interface Baseprops {
params: any;
route: any;
routeParams: any;
router: InjectedRou... | sessionIsValid | identifier_name |
utility.ts | /*tslint:disable:no-bitwise*/
import {InjectedRouter} from 'react-router';
import * as store from 'store';
import {EcpState} from '../store/ecp.state';
import * as session from '../login/session.model';
import * as moment from 'moment';
export class Utility {
// temporary functions (this function will only be us... |
public static getEcpState() {
let state: any = {};
try {
state.loginReducer = store.get('session');
if (state.loginReducer && state.loginReducer.sessionExpires) {
state.loginReducer.sessionExpires = moment.utc(state.loginReducer.sessionExpires);
... | {
let d = new Date().getTime();
if (window.performance && typeof window.performance.now === 'function') {
d += performance.now(); // use high-precision timer if available
}
let uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
let r = (d + Ma... | identifier_body |
utility.ts | /*tslint:disable:no-bitwise*/
import {InjectedRouter} from 'react-router';
import * as store from 'store';
import {EcpState} from '../store/ecp.state';
import * as session from '../login/session.model';
import * as moment from 'moment';
export class Utility {
// temporary functions (this function will only be us... | console.log(e);
}
}
public static sessionIsValid(session: session.SessionState) {
if (session && session.isLoggedIn && session.sessionExpires && session.sessionExpires > moment.utc()) {
return true;
}
return false;
}
}
export interface Baseprops {
... | random_line_split | |
index.ts | // Base
export { Metadata } from './src/metadata/Metadata';
export { MetadataManager } from './src/metadata/MetadataManager';
export { Container } from './src/injector/Container';
export { ContainerLoader } from './src/boot/ContainerLoader';
export { AbstractPackageBoot } from './src/boot/package/AbstractPackageBoot';... | export { HttpMethods } from './src/services/http/HttpMethods';
export { HttpBridge } from './src/services/http/HttpBridge';
export { StorageBridge } from './src/services/storage/StorageBridge';
export { Model } from './src/base/model/Model';
export { Controller } from './src/base/controller/Controller';
export { View ... |
export { Bridge } from './src/services/Bridge';
export { RemoteService } from './src/services/RemoteService';
export { Service } from './src/services/Service'; | random_line_split |
peer.rs | use ::address::PublicKey;
use super::{
ffi, error, vars,
Group,
Status
};
use super::status::{ Connection, UserStatus };
/// GropuChat Peer.
#[derive(Clone, Debug)]
pub struct Peer {
pub group: Group,
pub number: i32
}
impl Peer {
pub fn from(group: &Group, number: i32) -> Peer {
Peer... | ;
let name_len = lengths[self.number as usize];
Ok(names[self.number as usize][..name_len as usize].into())
}
// fn name(&self) -> Result<Vec<u8>, error::GetStatusErr> {
// let mut name = unsafe { vec_with!(vars::TOX_MAX_NAME_LENGTH) };
// match unsafe { ffi::tox_group_peername(... | {
return Err(error::GetStatusErr::Group);
} | conditional_block |
peer.rs | use ::address::PublicKey;
use super::{
ffi, error, vars,
Group,
Status
};
use super::status::{ Connection, UserStatus };
/// GropuChat Peer.
#[derive(Clone, Debug)]
pub struct Peer {
pub group: Group,
pub number: i32
}
impl Peer {
pub fn from(group: &Group, number: i32) -> Peer {
Peer... |
}
impl Status for Peer {
fn name(&self) -> Result<Vec<u8>, error::GetStatusErr> {
let len = unsafe { ffi::tox_group_number_peers(
self.group.core,
self.group.number
) };
let mut names = unsafe { vec_with!(len as usize) };
let mut lengths = unsafe { vec_with!... | {
unsafe { ffi::tox_group_peernumber_is_ours(
self.group.core,
self.group.number,
self.number
) != 0 }
} | identifier_body |
peer.rs | use ::address::PublicKey;
use super::{
ffi, error, vars,
Group,
Status
};
use super::status::{ Connection, UserStatus };
/// GropuChat Peer.
#[derive(Clone, Debug)]
pub struct Peer {
pub group: Group,
pub number: i32
}
impl Peer {
pub fn from(group: &Group, number: i32) -> Peer {
Peer... | (&self) -> Result<PublicKey, error::GetStatusErr> {
let mut pk = unsafe { vec_with!(vars::TOX_PUBLIC_KEY_SIZE) };
match unsafe { ffi::tox_group_peer_pubkey(
self.group.core,
self.group.number,
self.number,
pk.as_mut_ptr()
) } {
-1 => Er... | publickey | identifier_name |
peer.rs | use ::address::PublicKey;
use super::{
ffi, error, vars,
Group,
Status
};
use super::status::{ Connection, UserStatus };
/// GropuChat Peer.
#[derive(Clone, Debug)]
pub struct Peer {
pub group: Group,
pub number: i32
}
impl Peer {
pub fn from(group: &Group, number: i32) -> Peer {
Peer... | };
let name_len = lengths[self.number as usize];
Ok(names[self.number as usize][..name_len as usize].into())
}
// fn name(&self) -> Result<Vec<u8>, error::GetStatusErr> {
// let mut name = unsafe { vec_with!(vars::TOX_MAX_NAME_LENGTH) };
// match unsafe { ffi::tox_group_... | random_line_split | |
TouchContext.ts | //////////////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2014-2015, Egret Technology Inc.
// All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
... | var result = stage.hitTest(x, y);
if (result) {
var obj = this.getTouchData(identifier, x, y);
obj.target = result;
this.dispatchEvent(TouchEvent.TOUCH_MOVE, obj);
}
}
public onTouchEnd(x:number, y:number, identifier:nu... | this.lastTouchX = x;
this.lastTouchY = y;
var stage = MainContext.instance.stage; | random_line_split |
TouchContext.ts | //////////////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2014-2015, Egret Technology Inc.
// All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
... | ouchBegan(x:number, y:number, identifier:number):void {
if (this.touchingIdentifiers.length == this.maxTouches) {
return;
}
var stage = MainContext.instance.stage;
var result:any = stage.hitTest(x, y);
if (result) {
var obj = th... | uchDown:boolean = (this.touchDownTarget[data.identifier] == true)
TouchEvent.dispatchTouchEvent(data.target, type, data.identifier,
data.stageX, data.stageY, false, false, false, touchDown);
}
public onT | identifier_body |
TouchContext.ts | //////////////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2014-2015, Egret Technology Inc.
// All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
... | ete this._currentTouchTarget[obj.identifier];
}
}
}
} | obj.target = obj.beginTarget;
this.dispatchEvent(TouchEvent.TOUCH_RELEASE_OUTSIDE, obj);
}
del | conditional_block |
TouchContext.ts | //////////////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2014-2015, Egret Technology Inc.
// All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
... | identifier:number):void {
if (this.touchingIdentifiers.length == this.maxTouches) {
return;
}
var stage = MainContext.instance.stage;
var result:any = stage.hitTest(x, y);
if (result) {
var obj = this.getTouchData(identifier, x... | r, y:number, | identifier_name |
jupyter-file-manager.ts | This file contains a collection of functions that call the Jupyter server APIs, and are
* wrapped in the ApiManager class. It also defines a set of interfaces to interact with
* these APIs to help with type checking.
*/
class JupyterFile extends DatalabFile {
created?: string;
format: string;
lastModified?: ... | // If the rename fails, remove the temporary item
this.delete(notebookPlaceholder);
throw error;
});
}
return createPromise;
}
public rename(oldFileId: DatalabFileId, newName: string, newContainerId?: DatalabFileId) {
const oldPath = ApiManager.getServiceUrl(Servic... | return this.rename(notebookPlaceholder, containerId.path + '/' + name);
})
.catch((error: string) => { | random_line_split |
jupyter-file-manager.ts | This file contains a collection of functions that call the Jupyter server APIs, and are
* wrapped in the ApiManager class. It also defines a set of interfaces to interact with
* these APIs to help with type checking.
*/
class JupyterFile extends DatalabFile {
created?: string;
format: string;
lastModified?: ... |
public delete(fileId: DatalabFileId) {
const path = ApiManager.getServiceUrl(ServiceId.CONTENT) + '/' + fileId.path;
const xhrOptions: XhrOptions = {
failureCodes: [400],
method: 'DELETE',
successCodes: [204],
};
return ApiManager.sendRequestAsync(path, xhrOptions);
}
public ... | {
const oldPath = ApiManager.getServiceUrl(ServiceId.CONTENT) + '/' + oldFileId.path;
let newPath = newContainerId ?
newContainerId.path : JupyterFileManager._getParentDir(oldFileId.path);
newPath += '/' + newName;
const xhrOptions: XhrOptions = {
failureCodes: [409],
method: 'PATCH'... | identifier_body |
jupyter-file-manager.ts | This file contains a collection of functions that call the Jupyter server APIs, and are
* wrapped in the ApiManager class. It also defines a set of interfaces to interact with
* these APIs to help with type checking.
*/
class JupyterFile extends DatalabFile {
created?: string;
format: string;
lastModified?: ... | (type: DatalabFileType) {
switch (type) {
case DatalabFileType.DIRECTORY: return 'directory';
case DatalabFileType.FILE: return 'file';
case DatalabFileType.NOTEBOOK: return 'notebook';
default: throw new Error('Unknown upstream file type: ' + type);
}
}
/**
* Converts an object ... | _datalabTypeToUpstreamType | identifier_name |
copy-to-clipboard.tsx | /*
* This file is part of CoCalc: Copyright © 2020 Sagemath, Inc.
* License: AGPLv3 s.t. "Commons Clause" – see LICENSE.md for details
*/
import * as copy_to_clipboard from "copy-to-clipboard";
import { CSS, React, ReactDOM, useRef, useState } from "../app-framework";
import {
Button,
FormControl,
FormGroup... | ): void {
set_show_tooltip(true);
setTimeout(close_tool_tip, 2000);
copy_to_clipboard(value);
}
function close_tool_tip() {
if (!show_tooltip) {
return;
}
set_show_tooltip(false);
}
function render_button_after() {
return (
<InputGroup.Button>
<Overlay
... | button_click(_e | identifier_name |
copy-to-clipboard.tsx | /*
* This file is part of CoCalc: Copyright © 2020 Sagemath, Inc.
* License: AGPLv3 s.t. "Commons Clause" – see LICENSE.md for details
*/
import * as copy_to_clipboard from "copy-to-clipboard";
import { CSS, React, ReactDOM, useRef, useState } from "../app-framework";
import {
Button,
FormControl,
FormGroup... | function render_button_after() {
return (
<InputGroup.Button>
<Overlay
show={show_tooltip}
target={() => ReactDOM.findDOMNode(clipboard_button_ref.current)}
placement="bottom"
>
<Tooltip id="copied">Copied!</Tooltip>
</Overlay>
<Button r... | if (!show_tooltip) {
return;
}
set_show_tooltip(false);
}
| identifier_body |
copy-to-clipboard.tsx | /*
* This file is part of CoCalc: Copyright © 2020 Sagemath, Inc.
* License: AGPLv3 s.t. "Commons Clause" – see LICENSE.md for details
*/
import * as copy_to_clipboard from "copy-to-clipboard";
import { CSS, React, ReactDOM, useRef, useState } from "../app-framework";
import {
Button,
FormControl,
FormGroup... | <Tooltip id="copied">Copied!</Tooltip>
</Overlay>
<Button ref={clipboard_button_ref} onClick={on_button_click}>
<Icon name="clipboard" />
</Button>
</InputGroup.Button>
);
}
return (
<FormGroup style={style}>
<InputGroup>
{button_before != nul... | <Overlay
show={show_tooltip}
target={() => ReactDOM.findDOMNode(clipboard_button_ref.current)}
placement="bottom"
> | random_line_split |
copy-to-clipboard.tsx | /*
* This file is part of CoCalc: Copyright © 2020 Sagemath, Inc.
* License: AGPLv3 s.t. "Commons Clause" – see LICENSE.md for details
*/
import * as copy_to_clipboard from "copy-to-clipboard";
import { CSS, React, ReactDOM, useRef, useState } from "../app-framework";
import {
Button,
FormControl,
FormGroup... | set_show_tooltip(false);
}
function render_button_after() {
return (
<InputGroup.Button>
<Overlay
show={show_tooltip}
target={() => ReactDOM.findDOMNode(clipboard_button_ref.current)}
placement="bottom"
>
<Tooltip id="copied">Copied!</Tooltip>
... | return;
}
| conditional_block |
prepareImages.js | var CanvasRenderer = require('./main');
CanvasRenderer.prototype._prepareImages = function () {
// Creating the list of images
var imagesToPrepare = [];
var symbolList = this._extractor._symbolList;
var symbols = this._extractor._symbols;
for (var s = 0; s < symbolList.length; s += 1) {
var symbolId = symbol... | 'use strict'; | random_line_split | |
prepareImages.js | 'use strict';
var CanvasRenderer = require('./main');
CanvasRenderer.prototype._prepareImages = function () {
// Creating the list of images
var imagesToPrepare = [];
var symbolList = this._extractor._symbolList;
var symbols = this._extractor._symbols;
for (var s = 0; s < symbolList.length; s += 1) {
var sym... |
var images = symbol.images;
if (images) {
for (var i = 0; i < images.length; i += 1) {
var imageData = images[i];
imagesToPrepare.push(imageData.image);
}
}
}
var nImagesToPrepare = imagesToPrepare.length;
if (nImagesToPrepare === 0) {
this._renderImages();
return;
}
var nImagesReady = ... | {
imagesToPrepare.push(symbol.swfObject);
} | conditional_block |
server.py | import os
import subprocess
import requests
import time
from urlparse import urlparse
from config import config
class Server(object):
"""
Simple helper to start/stop and interact with a tests server
TODO: add method to check what request has been send last by browser
might need this for connect-src ... |
return result
def update_log_pointer(self):
"""
Method to update log read position in case you want to get latest
logs. e.g. call it before your test to get server log's for test
"""
with open(self.logfile_name, 'r') as f:
f.seek(0, 2)
self.l... | result = True | conditional_block |
server.py | import os
import subprocess
import requests
import time
from urlparse import urlparse
from config import config
class Server(object):
"""
Simple helper to start/stop and interact with a tests server
TODO: add method to check what request has been send last by browser
might need this for connect-src ... | (self):
"""
Method to get new log messages from server log
'new' means since last call for update_log_pointer
"""
with open(self.logfile_name, 'r') as f:
f.seek(self.log_pointer)
messages = f.readlines()
self.log_pointer = f.tell()
retu... | get_new_log_messages | identifier_name |
server.py | import os
import subprocess
import requests
import time
from urlparse import urlparse
from config import config
class Server(object):
"""
Simple helper to start/stop and interact with a tests server
TODO: add method to check what request has been send last by browser
might need this for connect-src ... |
def update_log_pointer(self):
"""
Method to update log read position in case you want to get latest
logs. e.g. call it before your test to get server log's for test
"""
with open(self.logfile_name, 'r') as f:
f.seek(0, 2)
self.log_pointer = f.tell()
... | """
Method checks if request to specific url has been received by
server.
if path_only set to True, then only query string will be ignored during
comparison.
Returns True if yes otherwise returns False
"""
logs = self.get_new_log_messages()
parsed_logs = s... | identifier_body |
server.py | import os
import subprocess
import requests
import time
from urlparse import urlparse
from config import config
class Server(object):
"""
Simple helper to start/stop and interact with a tests server
TODO: add method to check what request has been send last by browser
might need this for connect-src ... | stdout=FNULL, stderr=FNULL)
self.wait_for_server_to_start()
self.clean_server_log()
def stop(self):
"""
Shutdown test server child process
"""
self.process.terminate()
def wait_for_server_to_start(self, timeout=5):
... | FNULL = open(os.devnull, 'w')
command_line = ['python', 'server/server.py']
self.process = subprocess.Popen(command_line, shell=False, | random_line_split |
bookmark.service.ts | /// <reference path="../app-reff.d.ts" />
module angularApp {
declare let window: AppWindow;
export interface IBookmarkSrvc {
getBookmarks(): Array<String>
getBookmarkMovies(): ng.IPromise<Movie[]>
getWatched(): Array<String>
getWatchedMovies(): ng.IPromise<Movie[]>
addToBookmark(imdbId: string): ng.IP... | (private $http: ng.IHttpService) {
}
getBookmarks = (): Array<String> => {
return this.bookmarks;
}
getBookmarkMovies = (): ng.IPromise<Movie[]> => {
return this.$http.get('/api/bookmarks/movie').then(this.getData);
}
getWatched = (): Array<String> => {
return this.allWatched;
}
getWatchedM... | constructor | identifier_name |
bookmark.service.ts | /// <reference path="../app-reff.d.ts" />
module angularApp {
declare let window: AppWindow;
export interface IBookmarkSrvc {
getBookmarks(): Array<String>
getBookmarkMovies(): ng.IPromise<Movie[]>
getWatched(): Array<String> | addToBookmark(imdbId: string): ng.IPromise<boolean>
removeFromBookmark(movieId: string): ng.IPromise<boolean>
addToWatched(imdbId: string): ng.IPromise<boolean>
updateBookmark(): void
}
class BookmarkSrvc implements IBookmarkSrvc {
private bookmarks: Array<String> = [];
private allWatched: Array<String>... | getWatchedMovies(): ng.IPromise<Movie[]>
| random_line_split |
test_mnist.py | """
This file tests some of the YAML files in the maxout paper
"""
import os
import pylearn2
from pylearn2.datasets import control
from pylearn2.datasets.mnist import MNIST
from pylearn2.termination_criteria import EpochCounter
from pylearn2.testing.skip import skip_if_no_gpu
from pylearn2.utils.serial import load_tra... | train.main_loop()
def test_mnist_pi():
"""
Test the mnist_pi.yaml file from the maxout
paper on random input
"""
train = load_train_file(
os.path.join(pylearn2.__path__[0],
"scripts/papers/maxout/mnist_pi.yaml")
)
# Load fake MNIST data
init_value = c... | """
Test the mnist.yaml file from the maxout
paper on random input
"""
skip_if_no_gpu()
train = load_train_file(os.path.join(pylearn2.__path__[0],
"scripts/papers/maxout/mnist.yaml"))
# Load fake MNIST data
init_value = control.load_data
control.... | identifier_body |
test_mnist.py | """
This file tests some of the YAML files in the maxout paper
"""
import os
import pylearn2
from pylearn2.datasets import control
from pylearn2.datasets.mnist import MNIST
from pylearn2.termination_criteria import EpochCounter
from pylearn2.testing.skip import skip_if_no_gpu
from pylearn2.utils.serial import load_tra... | ():
"""
Test the mnist_pi.yaml file from the maxout
paper on random input
"""
train = load_train_file(
os.path.join(pylearn2.__path__[0],
"scripts/papers/maxout/mnist_pi.yaml")
)
# Load fake MNIST data
init_value = control.load_data
control.load_data = [... | test_mnist_pi | identifier_name |
test_mnist.py | """
This file tests some of the YAML files in the maxout paper
"""
import os
import pylearn2
from pylearn2.datasets import control
from pylearn2.datasets.mnist import MNIST
from pylearn2.termination_criteria import EpochCounter
from pylearn2.testing.skip import skip_if_no_gpu
from pylearn2.utils.serial import load_tra... | # Train shortly and prevent saving
train.algorithm.termination_criterion = EpochCounter(max_epochs=1)
train.extensions.pop(0)
train.save_freq = 0
train.main_loop() | random_line_split | |
ModalHeader.js | "use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
exports.__esModule = true;
exports.default = void 0;
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
var _objectWithoutPropertiesLoose2 = _interopRequireDefault(require("@babel/runt... |
return /*#__PURE__*/_react.default.createElement(WrapTag, (0, _extends2.default)({}, attributes, {
className: classes
}), /*#__PURE__*/_react.default.createElement(Tag, {
className: (0, _utils.mapToCssModules)('modal-title', cssModule)
}, children), close || closeButton);
};
ModalHeader.propTypes = pro... | {
var closeIcon = typeof charCode === 'number' ? String.fromCharCode(charCode) : charCode;
closeButton = /*#__PURE__*/_react.default.createElement("button", {
type: "button",
onClick: toggle,
className: (0, _utils.mapToCssModules)('close', cssModule),
"aria-label": closeAriaLabel
}, ... | conditional_block |
ModalHeader.js | "use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); | exports.__esModule = true;
exports.default = void 0;
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
var _objectWithoutPropertiesLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutPropertiesLoose"));
var _react = _interopRequireDefault(require("react"));
... | random_line_split | |
test_ray.py | import os
import numpy as np
from matplotlib import pyplot as plt
from numpy import genfromtxt
from matplotlib import cm
from mpl_toolkits.mplot3d.art3d import Poly3DCollection
import matplotlib as mpl
from mpl_toolkits.mplot3d import Axes3D
def axisEqual3D(ax):
extents = np.array([getattr(ax, 'get_{}lim'.format... |
def drawBlackHole(ax, r=5):
# Draw black hole
u = np.linspace(0, 2 * np.pi, 100)
v = np.linspace(0, np.pi, 100)
x = r * np.outer(np.cos(u), np.sin(v))
y = r * np.outer(np.sin(u), np.sin(v))
z = r * np.outer(np.ones(np.size(u)), np.cos(v))
ax.plot_surface(x, y, z, rstride=4, cstride=4, c... | ax.plot((-d, d), (0, 0), (0, 0), 'grey')
ax.plot((0, 0), (-d, d), (0, 0), 'grey')
ax.plot((0, 0), (0, 0), (-d, d), 'gray') | identifier_body |
test_ray.py | import os
import numpy as np
from matplotlib import pyplot as plt
from numpy import genfromtxt
from matplotlib import cm
from mpl_toolkits.mplot3d.art3d import Poly3DCollection
import matplotlib as mpl
from mpl_toolkits.mplot3d import Axes3D
def axisEqual3D(ax):
extents = np.array([getattr(ax, 'get_{}lim'.format... | camPhi = 0
camX = camR * np.sin(camTheta) * np.cos(camPhi)
camY = camR * np.sin(camTheta) * np.sin(camPhi)
camZ = camR * np.cos(camTheta)
ax.scatter(camX, camY, camZ, s=100, c='red')
x = [1, 1, -1, -1]
y = [1, -1, -1, 1]
z = [-1, -1, -1, -1]
verts = [(x[i], y[i], z[i]) for i in r... | camR = 100
camTheta = np.pi/2 | random_line_split |
test_ray.py | import os
import numpy as np
from matplotlib import pyplot as plt
from numpy import genfromtxt
from matplotlib import cm
from mpl_toolkits.mplot3d.art3d import Poly3DCollection
import matplotlib as mpl
from mpl_toolkits.mplot3d import Axes3D
def axisEqual3D(ax):
extents = np.array([getattr(ax, 'get_{}lim'.format... | # if fileName.endswith(".csv"):
# drawRay(ax, fileName)
#
drawRay(ax, "Data/Spin00001/ray00.csv")
drawRay(ax, "Data/Spin00001/ray10.csv")
drawRay(ax, "Data/Spin00001/ray20.csv")
# drawRay(ax, "Data/Spin00001/ray30.csv")
drawRay(ax, "Data/Spin00001/ray40.csv")
drawRay(ax, ... | fig = plt.figure()
ax = fig.gca(projection='3d')
ax.set_axis_off()
ax.set_xlim3d(-25, 25)
ax.set_ylim3d(-25, 25)
ax.set_zlim3d(-25, 25)
# axisEqual3D(ax)
drawAxes(ax)
drawBlackHole(ax)
drawCamera(ax)
# drawRay(ax, "Data/rayPositions.csv")
# drawRay(ax, "Data/middleRay.cs... | conditional_block |
test_ray.py | import os
import numpy as np
from matplotlib import pyplot as plt
from numpy import genfromtxt
from matplotlib import cm
from mpl_toolkits.mplot3d.art3d import Poly3DCollection
import matplotlib as mpl
from mpl_toolkits.mplot3d import Axes3D
def axisEqual3D(ax):
extents = np.array([getattr(ax, 'get_{}lim'.format... | (ax, filePath):
# Retrieve ray points
sphericalPoints = genfromtxt(filePath, delimiter=',')
# Retrieve the actual data
r = sphericalPoints[:, 3]
theta = sphericalPoints[:, 4]
phi = sphericalPoints[:, 5]
cosT = np.cos(theta)
sinT = np.sin(theta)
cosP = np.cos(phi)
sinP = np.sin(... | drawRay | identifier_name |
statsHelpers.js | 'use strict';
const Stats = require('fast-stats').Stats,
get = require('lodash.get'),
set = require('lodash.set');
function percentileName(percentile) {
if (percentile === 0) {
return 'min';
} else if (percentile === 100) {
return 'max';
} else {
return 'p' + String(percentile).replace('.', '_')... | (target, domainTarget, path, data) {
this.pushStats(target, path, data);
this.pushStats(domainTarget, path, data);
},
/**
* Summarize stats and put result in target at path
*/
setStatsSummary(target, path, stats) {
set(target, path, this.summarizeStats(stats));
},
summarizeStats(stats, opt... | pushGroupStats | identifier_name |
statsHelpers.js | 'use strict';
const Stats = require('fast-stats').Stats,
get = require('lodash.get'),
set = require('lodash.set');
function percentileName(percentile) |
module.exports = {
/**
* Create or update a fast-stats#Stats object in target at path.
*/
pushStats(target, path, data) {
if (typeof data !== 'number')
throw new Error(`Tried to add ${data} to stats for path ${path}`);
const stats = get(target, path, new Stats());
stats.push(data);
s... | {
if (percentile === 0) {
return 'min';
} else if (percentile === 100) {
return 'max';
} else {
return 'p' + String(percentile).replace('.', '_');
}
} | identifier_body |
statsHelpers.js | 'use strict';
const Stats = require('fast-stats').Stats,
get = require('lodash.get'),
set = require('lodash.set');
function percentileName(percentile) {
if (percentile === 0) {
return 'min';
} else if (percentile === 100) {
return 'max';
} else {
return 'p' + String(percentile).replace('.', '_')... |
const stats = get(target, path, new Stats());
stats.push(data);
set(target, path, stats);
},
pushGroupStats(target, domainTarget, path, data) {
this.pushStats(target, path, data);
this.pushStats(domainTarget, path, data);
},
/**
* Summarize stats and put result in target at path
*/
... | */
pushStats(target, path, data) {
if (typeof data !== 'number')
throw new Error(`Tried to add ${data} to stats for path ${path}`); | random_line_split |
statsHelpers.js | 'use strict';
const Stats = require('fast-stats').Stats,
get = require('lodash.get'),
set = require('lodash.set');
function percentileName(percentile) {
if (percentile === 0) {
return 'min';
} else if (percentile === 100) {
return 'max';
} else {
return 'p' + String(percentile).replace('.', '_')... | else {
throw new Error('Failed to calculate ' + name + ' for stats: ' + JSON.stringify(stats, null, 2));
}
});
if (options.includeSum) {
data.sum = stats.Σ().toFixed(decimals);
}
return data;
}
};
| {
data[name] = percentile.toFixed(decimals);
} | conditional_block |
underscore.rs | use std::old_io::{stdout, stderr};
use libc::pid_t;
use argparse::{ArgumentParser};
use argparse::{StoreTrue, StoreFalse, List, StoreOption, Store};
use config::Config;
use config::command::{CommandInfo, Networking};
use container::container::Namespace::{NewUser, NewNet};
use container::nsutil::{set_namespace};
use ... | ");
ap.refer(&mut container)
.add_argument("container", Store,
"Container to run command in")
.required();
ap.refer(&mut cmdargs)
.add_argument("command", List,
"Command (with arguments) to run inside container")
... | random_line_split | |
underscore.rs | use std::old_io::{stdout, stderr};
use libc::pid_t;
use argparse::{ArgumentParser};
use argparse::{StoreTrue, StoreFalse, List, StoreOption, Store};
use config::Config;
use config::command::{CommandInfo, Networking};
use container::container::Namespace::{NewUser, NewNet};
use container::nsutil::{set_namespace};
use ... | "Command (with arguments) to run inside container")
.required();
ap.stop_on_first_argument(true);
match ap.parse(args, &mut stdout(), &mut stderr()) {
Ok(()) => {}
Err(0) => return Ok(0),
Err(_) => {
return Ok(122);
... | {
let mut cmdargs = vec!();
let mut container = "".to_string();
let mut pid = None;
{
args.insert(0, "vagga ".to_string() + cname.as_slice());
let mut ap = ArgumentParser::new();
ap.set_description(
"Run command (or shell) in one of the vagga's network namespaces");
... | identifier_body |
underscore.rs | use std::old_io::{stdout, stderr};
use libc::pid_t;
use argparse::{ArgumentParser};
use argparse::{StoreTrue, StoreFalse, List, StoreOption, Store};
use config::Config;
use config::command::{CommandInfo, Networking};
use container::container::Namespace::{NewUser, NewNet};
use container::nsutil::{set_namespace};
use ... | (config: &Config, workdir: &Path, cname: String,
mut args: Vec<String>)
-> Result<i32, String>
{
let mut cmdargs = vec!();
let mut container = "".to_string();
let mut pid = None;
{
args.insert(0, "vagga ".to_string() + cname.as_slice());
let mut ap = ArgumentParser::new();
... | run_in_netns | identifier_name |
language.js | /*
* Copyright (C) Pootle contributors.
*
* This file is a part of the Pootle project. It is distributed under the GPL3
* or later license. See the LICENSE file for a copy of the license and the
* AUTHORS file for copyright and authorship information.
*/
'use strict';
var _ = require('underscore');
var Backbone... |
return [];
},
});
var LanguageSet = Backbone.Collection.extend(
_.extend({}, AdminAPIMixin, {
model: Language,
url: l('/xhr/admin/languages/'),
}));
module.exports = {
Language: Language,
LanguageSet: LanguageSet,
};
| {
return this.fieldChoices[fieldName].map(function (field) {
// FIXME: react-select's issue #25 prevents using non-string values
return {value: field[0].toString(), label: field[1]};
});
} | conditional_block |
language.js | /*
* Copyright (C) Pootle contributors.
*
* This file is a part of the Pootle project. It is distributed under the GPL3
* or later license. See the LICENSE file for a copy of the license and the
* AUTHORS file for copyright and authorship information.
*/
'use strict';
var _ = require('underscore');
var Backbone... | // FIXME: using `gettext()` here breaks everything
[0, 'Unknown'], [1, 1], [2, 2], [3, 3], [4, 4], [5, 5], [6, 6],
],
},
urlRoot: function () {
return l('/xhr/admin/languages/');
},
getAbsoluteUrl: function () {
return l(['', this.get('code'), ''].join('/'));
},
getPermissionsUrl:... | 'nplurals': [ | random_line_split |
utils.py | # -*- coding: utf-8 -*-
import datetime
import json
import time
from oauth2client.client import AccessTokenRefreshError
from django.core.cache import cache
from django.utils.translation import get_language
from django.utils.encoding import force_str
from yawdadmin.resources import admin_site
from conf import settings a... | def get_analytics_data(http):
#try to get cached data
data = cache.get('yawdadmin_ga', None)
if data:
return data
from apiclient.discovery import build
from apiclient.errors import HttpError
end_date = datetime.datetime.now()
start_date = end_date + datetime.timedelta(-ls.ADMIN_GO... | random_line_split | |
utils.py | # -*- coding: utf-8 -*-
import datetime
import json
import time
from oauth2client.client import AccessTokenRefreshError
from django.core.cache import cache
from django.utils.translation import get_language
from django.utils.encoding import force_str
from yawdadmin.resources import admin_site
from conf import settings a... | date = date + datetime.timedelta(1)
data.append({'date': date.strftime('%A, %B %d, %Y')})
current_row = date.strftime('%Y%m%d')
if row[1] == 'New Visitor':
data[len(data)-1]['new'] = int(row[2])
else:
data[len(data)-1]['returning'] = int(row[2... | """
Format the Google Analytics data for use within an Area Chart.
"""
def update_record(record):
visits = 0
for key in ('new','returning'):
if not key in record:
record[key] = 0
visits += record[key]
record['total'] = visits
date = start... | identifier_body |
utils.py | # -*- coding: utf-8 -*-
import datetime
import json
import time
from oauth2client.client import AccessTokenRefreshError
from django.core.cache import cache
from django.utils.translation import get_language
from django.utils.encoding import force_str
from yawdadmin.resources import admin_site
from conf import settings a... |
update_record(data[len(data)-1])
return data
| data[len(data)-1]['returning'] = int(row[2]) | conditional_block |
utils.py | # -*- coding: utf-8 -*-
import datetime
import json
import time
from oauth2client.client import AccessTokenRefreshError
from django.core.cache import cache
from django.utils.translation import get_language
from django.utils.encoding import force_str
from yawdadmin.resources import admin_site
from conf import settings a... | (record):
visits = 0
for key in ('new','returning'):
if not key in record:
record[key] = 0
visits += record[key]
record['total'] = visits
date = start_date
current_row = date.strftime('%Y%m%d')
data = [{ 'date': date.strftime('%A, %B %d, %Y')}... | update_record | identifier_name |
issue-5806.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 http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// opyright 2013 Th... | // | random_line_split |
issue-5806.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 ... | {} | identifier_body | |
issue-5806.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 ... | () {}
| main | identifier_name |
types.rs | use self::ItemType::*;
use std::io;
use std::io::Write;
use str::GopherStr;
use bytes::Bytes;
/// A client-to-server message.
#[derive(Clone, Debug)]
pub struct GopherRequest {
/// Identifier of the resource to fetch. May be an empty string.
pub selector: GopherStr,
/// Search string for a full-text search... | {
pub entities: Vec<DirEntity>,
}
/// An menu item in a directory of Gopher resources.
#[derive(Clone, Debug)]
pub struct DirEntity {
/// The type of the resource
pub item_type: ItemType,
/// String to display to the user.
pub name: GopherStr,
/// Path or identifier used for requesting this re... | Menu | identifier_name |
types.rs | use self::ItemType::*;
use std::io;
use std::io::Write;
use str::GopherStr;
use bytes::Bytes;
/// A client-to-server message.
#[derive(Clone, Debug)]
pub struct GopherRequest {
/// Identifier of the resource to fetch. May be an empty string.
pub selector: GopherStr,
/// Search string for a full-text search... | /// A list of resources.
Menu(Vec<DirEntity>),
/// A text document.
TextFile(Bytes),
/// A binary file download.
BinaryFile(Bytes),
/// A single menu item enclosed in a Gopher+ protocol response.
///
/// Useful for redirecting Gopher+ clients to the standard Gopher protocol.
G... | }
/// A server-to-client message.
#[derive(Clone, Debug)]
pub enum GopherResponse { | random_line_split |
fps.rs | use time::precise_time_ns;
// FPS is smoothed with an exponentially-weighted moving average.
// This is the proportion of the old FPS to keep on each step.
const SMOOTHING: f32
= 0.9;
// How often to output FPS, in milliseconds.
const OUTPUT_INTERVAL: u64
= 5_000;
pub struct FPSTracker {
last_frame_time:... | () -> FPSTracker {
let t = precise_time_ns();
FPSTracker {
last_frame_time: t,
last_fps_output_time: t,
smoothed_fps: 0.0,
}
}
pub fn tick(&mut self) {
let this_frame_time = precise_time_ns();
let instant_fps = 1e9 / ((this_frame_time ... | new | identifier_name |
fps.rs | use time::precise_time_ns;
// FPS is smoothed with an exponentially-weighted moving average.
// This is the proportion of the old FPS to keep on each step.
const SMOOTHING: f32
= 0.9;
// How often to output FPS, in milliseconds.
const OUTPUT_INTERVAL: u64
= 5_000;
pub struct FPSTracker {
last_frame_time:... | }
}
pub fn tick(&mut self) {
let this_frame_time = precise_time_ns();
let instant_fps = 1e9 / ((this_frame_time - self.last_frame_time) as f32);
self.smoothed_fps = SMOOTHING * self.smoothed_fps
+ (1.0-SMOOTHING) * instant_fps;
self.last_frame_time =... | let t = precise_time_ns();
FPSTracker {
last_frame_time: t,
last_fps_output_time: t,
smoothed_fps: 0.0, | random_line_split |
fps.rs | use time::precise_time_ns;
// FPS is smoothed with an exponentially-weighted moving average.
// This is the proportion of the old FPS to keep on each step.
const SMOOTHING: f32
= 0.9;
// How often to output FPS, in milliseconds.
const OUTPUT_INTERVAL: u64
= 5_000;
pub struct FPSTracker {
last_frame_time:... |
}
}
| {
println!("Frames per second: {:7.2}", self.smoothed_fps);
self.last_fps_output_time = this_frame_time;
} | conditional_block |
app.component.ts | /**
* Copyright 2019, Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to... | {
title = 'Device Manager';
constructor(public authService: AngularFireAuth,
private router: Router) { }
logout() {
this.authService.auth.signOut().then(() => {
this.router.navigate(['login']);
});
}
}
| AppComponent | identifier_name |
app.component.ts | /**
* Copyright 2019, Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to... |
}
| {
this.authService.auth.signOut().then(() => {
this.router.navigate(['login']);
});
} | identifier_body |
app.component.ts | /**
* Copyright 2019, Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. | * 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 WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governi... | * You may obtain a copy of the License at
* | random_line_split |
lib.rs | // Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
#![deny(missing_docs)]
//! The library crate that defines common helper functions that are generally used in
//! conjunction with seccompiler-bin.
mod common;
use bincode::Error as BincodeError;
use binc... | () {
// Malformed bincode binary.
{
let data = "adassafvc".to_string();
assert!(deserialize_binary(data.as_bytes(), None).is_err());
}
// Test that the binary deserialization is correct, and that the thread keys
// have been lowercased.
{
... | test_deserialize_binary | identifier_name |
lib.rs | // Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
#![deny(missing_docs)]
//! The library crate that defines common helper functions that are generally used in
//! conjunction with seccompiler-bin.
mod common;
use bincode::Error as BincodeError;
use binc... |
// Binary limit too low.
assert!(matches!(
deserialize_binary(&bytes[..], Some(20)).unwrap_err(),
DeserializationError::Bincode(error)
if error.to_string() == "the size limit has been reached"
));
let mut expected_res ... | random_line_split | |
lib.rs | // Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
#![deny(missing_docs)]
//! The library crate that defines common helper functions that are generally used in
//! conjunction with seccompiler-bin.
mod common;
use bincode::Error as BincodeError;
use binc... |
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use crate::common::BpfProgram;
use std::collections::HashMap;
use std::sync::Arc;
use std::thread;
#[test]
fn test_deserialize_binary() {
// Malformed bincode binary.
{
let data = "adassafvc".t... | {
return Err(InstallationError::Prctl(*libc::__errno_location()));
} | conditional_block |
lib.rs | // Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
#![deny(missing_docs)]
//! The library crate that defines common helper functions that are generally used in
//! conjunction with seccompiler-bin.
mod common;
use bincode::Error as BincodeError;
use binc... | let bpf_prog = sock_fprog {
len: bpf_filter.len() as u16,
filter: bpf_filter.as_ptr(),
};
let bpf_prog_ptr = &bpf_prog as *const sock_fprog;
{
let rc = libc::prctl(
libc::PR_SET_SECCOMP,
libc::SECCOMP_MODE_FILTER,
... | {
// If the program is empty, don't install the filter.
if bpf_filter.is_empty() {
return Ok(());
}
// If the program length is greater than the limit allowed by the kernel,
// fail quickly. Otherwise, `prctl` will give a more cryptic error code.
if bpf_filter.len() > BPF_MAX_LEN {
... | identifier_body |
0208_create_role_executive.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.2 on 2017-11-22 07:11
from __future__ import unicode_literals
from django.core.management.sql import emit_post_migrate_signal
from django.db import migrations
def add_executive_group(apps, schema_editor):
# create group
|
class Migration(migrations.Migration):
dependencies = [
('base', '0207_auto_20171220_1035'),
]
operations = [
migrations.RunPython(add_executive_group, elidable=True),
]
| db_alias = schema_editor.connection.alias
emit_post_migrate_signal(1, False, db_alias)
Group = apps.get_model('auth', 'Group')
Permission = apps.get_model('auth', 'Permission')
executive_group, created = Group.objects.get_or_create(name='executive')
if created:
# Learning unit
can_ac... | identifier_body |
0208_create_role_executive.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.2 on 2017-11-22 07:11
from __future__ import unicode_literals
from django.core.management.sql import emit_post_migrate_signal
from django.db import migrations
def add_executive_group(apps, schema_editor):
# create group
db_alias = schema_editor.connection.al... | (migrations.Migration):
dependencies = [
('base', '0207_auto_20171220_1035'),
]
operations = [
migrations.RunPython(add_executive_group, elidable=True),
]
| Migration | identifier_name |
0208_create_role_executive.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.2 on 2017-11-22 07:11
from __future__ import unicode_literals
from django.core.management.sql import emit_post_migrate_signal
from django.db import migrations
def add_executive_group(apps, schema_editor):
# create group
db_alias = schema_editor.connection.al... |
class Migration(migrations.Migration):
dependencies = [
('base', '0207_auto_20171220_1035'),
]
operations = [
migrations.RunPython(add_executive_group, elidable=True),
]
| can_access_learningunit = Permission.objects.get(codename='can_access_learningunit')
executive_group.permissions.add(can_access_learningunit) | conditional_block |
0208_create_role_executive.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.2 on 2017-11-22 07:11
from __future__ import unicode_literals
from django.core.management.sql import emit_post_migrate_signal
from django.db import migrations
def add_executive_group(apps, schema_editor):
# create group
db_alias = schema_editor.connection.al... | executive_group.permissions.add(can_access_learningunit)
class Migration(migrations.Migration):
dependencies = [
('base', '0207_auto_20171220_1035'),
]
operations = [
migrations.RunPython(add_executive_group, elidable=True),
] | random_line_split | |
account_invoice_send.py | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models, _
from odoo.exceptions import UserError
class AccountInvoiceSend(models.TransientModel):
_name = 'account.invoice.send'
_inherit = 'account.invoice.send'
_description =... | (self):
self.partner_id = self.env['res.partner']
for wizard in self:
if wizard.invoice_ids and len(wizard.invoice_ids) == 1:
wizard.partner_id = wizard.invoice_ids.partner_id.id
@api.depends('snailmail_is_letter')
def _compute_snailmail_cost(self):
for wizar... | _get_partner | identifier_name |
account_invoice_send.py | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models, _
from odoo.exceptions import UserError |
class AccountInvoiceSend(models.TransientModel):
_name = 'account.invoice.send'
_inherit = 'account.invoice.send'
_description = 'Account Invoice Send'
partner_id = fields.Many2one('res.partner', compute='_get_partner', string='Partner')
snailmail_is_letter = fields.Boolean('Send by Post', help='A... | random_line_split | |
account_invoice_send.py | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models, _
from odoo.exceptions import UserError
class AccountInvoiceSend(models.TransientModel):
| for wizard in self:
if wizard.invoice_ids and len(wizard.invoice_ids) == 1:
wizard.partner_id = wizard.invoice_ids.partner_id.id
@api.depends('snailmail_is_letter')
def _compute_snailmail_cost(self):
for wizard in self:
wizard.snailmail_cost = len(wizard.... | _name = 'account.invoice.send'
_inherit = 'account.invoice.send'
_description = 'Account Invoice Send'
partner_id = fields.Many2one('res.partner', compute='_get_partner', string='Partner')
snailmail_is_letter = fields.Boolean('Send by Post', help='Allows to send the document by Snailmail (coventional p... | identifier_body |
account_invoice_send.py | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models, _
from odoo.exceptions import UserError
class AccountInvoiceSend(models.TransientModel):
_name = 'account.invoice.send'
_inherit = 'account.invoice.send'
_description =... |
@api.depends('invoice_ids')
def _get_partner(self):
self.partner_id = self.env['res.partner']
for wizard in self:
if wizard.invoice_ids and len(wizard.invoice_ids) == 1:
wizard.partner_id = wizard.invoice_ids.partner_id.id
@api.depends('snailmail_is_letter')
... | invalid_invoices = wizard.invoice_ids.filtered(lambda i: not self.env['snailmail.letter']._is_valid_address(i.partner_id))
wizard.invalid_invoice_ids = invalid_invoices
wizard.invalid_addresses = len(invalid_invoices) | conditional_block |
config.service.ts | // #docplaster
// #docregion , proto
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
// #enddocregion proto
import { HttpErrorResponse, HttpResponse } from '@angular/common/http';
// #docregion rxjs-imports
import { Observable } from 'rxjs/Observable';
import { ErrorObser... | () {
// #enddocregion getConfig_1, getConfig_2, getConfig_3
return this.http.get<Config>(this.configUrl)
.pipe(
retry(3), // retry a failed request up to 3 times
catchError(this.handleError) // then handle the error
);
}
// #enddocregion getConfig
getConfig_1() {
// #docregion... | getConfig | identifier_name |
config.service.ts | // #docplaster
// #docregion , proto
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
// #enddocregion proto
import { HttpErrorResponse, HttpResponse } from '@angular/common/http';
// #docregion rxjs-imports
import { Observable } from 'rxjs/Observable';
import { ErrorObser... | // #docregion proto
constructor(private http: HttpClient) { }
// #enddocregion proto
// #docregion getConfig, getConfig_1, getConfig_2, getConfig_3
getConfig() {
// #enddocregion getConfig_1, getConfig_2, getConfig_3
return this.http.get<Config>(this.configUrl)
.pipe(
retry(3), // retry a... | configUrl = 'assets/config.json';
// #enddocregion getConfig_1 | random_line_split |
config.service.ts | // #docplaster
// #docregion , proto
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
// #enddocregion proto
import { HttpErrorResponse, HttpResponse } from '@angular/common/http';
// #docregion rxjs-imports
import { Observable } from 'rxjs/Observable';
import { ErrorObser... | else {
// The backend returned an unsuccessful response code.
// The response body may contain clues as to what went wrong,
console.error(
`Backend returned code ${error.status}, ` +
`body was: ${error.error}`);
}
// return an ErrorObservable with a user-facing error message
... | {
// A client-side or network error occurred. Handle it accordingly.
console.error('An error occurred:', error.error.message);
} | conditional_block |
startup.py | from __future__ import unicode_literals
"""
product initialization stuff
"""
import os
import featuremonkey
from .composer import get_composer
from django_productline import compare_version
_product_selected = False
def select_product():
|
#bind context and compose features
context.bind_context(contextfile)
get_composer().select_equation(equationfile)
# after composition we are now able to bind composed template settings
template.bind_settings()
featuremonkey.remove_import_guard('django.conf')
featuremonkey.remove_import_gu... | """
binds the frozen context the selected features
should be called only once - calls after the first call have
no effect
"""
global _product_selected
if _product_selected:
# tss already bound ... ignore
return
_product_selected = True
from django_productline import con... | identifier_body |
startup.py | from __future__ import unicode_literals
"""
product initialization stuff
"""
import os
import featuremonkey
from .composer import get_composer
from django_productline import compare_version
_product_selected = False
def select_product():
"""
binds the frozen context the selected features
should be cal... | ():
"""
returns the wsgi application for the selected product
this function is called by featuredjango.wsgi to get the wsgi
application object
if you need to refine the wsgi application object e.g. to add
wsgi middleware please refine django.core.wsgi.get_wsgi_application directly.
"""
... | get_wsgi_application | identifier_name |
startup.py | from __future__ import unicode_literals
"""
product initialization stuff
"""
import os
import featuremonkey
from .composer import get_composer
from django_productline import compare_version
_product_selected = False
def select_product():
"""
binds the frozen context the selected features
should be cal... |
_product_selected = True
from django_productline import context, template
featuremonkey.add_import_guard('django.conf')
featuremonkey.add_import_guard('django.db')
os.environ['DJANGO_SETTINGS_MODULE'] = 'django_productline.settings'
contextfile = os.environ['PRODUCT_CONTEXT_FILENAME']
equ... | return | conditional_block |
startup.py | from __future__ import unicode_literals
"""
product initialization stuff
"""
import os
import featuremonkey
from .composer import get_composer
from django_productline import compare_version
_product_selected = False
def select_product():
"""
binds the frozen context the selected features
should be cal... | #bind context and compose features
context.bind_context(contextfile)
get_composer().select_equation(equationfile)
# after composition we are now able to bind composed template settings
template.bind_settings()
featuremonkey.remove_import_guard('django.conf')
featuremonkey.remove_import_gua... | random_line_split | |
2_13.rs | extern crate cryptopal;
extern crate hex;
use std::iter::repeat;
use std::str;
use cryptopal::oracle::{Oracle, ProfileOracle};
use cryptopal::pkcs;
use cryptopal::util;
fn string_of_n(n: usize) -> String {
repeat("B").take(n).collect::<String>()
}
fn main() {
let oracle = ProfileOracle::new();
let bloc... |
// create our composite ciphertext using the first two blocks of the C1
// ciphertext (designed to place the role= at the block edge)
// append the C2 ciphertext block which contains the isolated `admin` literal
let mut f: Vec<u8> = Vec::new();
c1_chunked[0..2].iter().for_each(|c| f.extend_from_sli... | p2.extend_from_slice(string_of_n(padding_to_block_edge).as_bytes());
p2.extend(pkcs::pad("admin".as_bytes(), block_size));
let c2 = oracle.encrypt(&p2);
let c2_chunked: Vec<&[u8]> = c2.chunks(block_size).collect(); | random_line_split |
2_13.rs | extern crate cryptopal;
extern crate hex;
use std::iter::repeat;
use std::str;
use cryptopal::oracle::{Oracle, ProfileOracle};
use cryptopal::pkcs;
use cryptopal::util;
fn string_of_n(n: usize) -> String {
repeat("B").take(n).collect::<String>()
}
fn | () {
let oracle = ProfileOracle::new();
let block_size = util::calculate_oracle_block_size(&oracle).expect("bad oracle");
let payload_length = util::calculate_total_payload_length(&oracle).expect("bad payload");
let prefix_length = util::calculate_prefix_length(&oracle).expect("bad oracle");
let su... | main | identifier_name |
2_13.rs | extern crate cryptopal;
extern crate hex;
use std::iter::repeat;
use std::str;
use cryptopal::oracle::{Oracle, ProfileOracle};
use cryptopal::pkcs;
use cryptopal::util;
fn string_of_n(n: usize) -> String |
fn main() {
let oracle = ProfileOracle::new();
let block_size = util::calculate_oracle_block_size(&oracle).expect("bad oracle");
let payload_length = util::calculate_total_payload_length(&oracle).expect("bad payload");
let prefix_length = util::calculate_prefix_length(&oracle).expect("bad oracle");
... | {
repeat("B").take(n).collect::<String>()
} | identifier_body |
Log.js | /*jslint browser: true */
// Log.js (c) 2010-2013 Loren West and other contributors
// May be freely distributed under the MIT license.
// For further details and documentation:
// http://lorenwest.github.com/monitor-min
(function(root){
// Module loading
var Monitor = root.Monitor || require('./Monitor'),
/... |
}(this));
| {
Log.on(pattern, Log.console);
} | conditional_block |
Log.js | /*jslint browser: true */
// Log.js (c) 2010-2013 Loren West and other contributors
// May be freely distributed under the MIT license.
// For further details and documentation:
// http://lorenwest.github.com/monitor-min
(function(root){
// Module loading
var Monitor = root.Monitor || require('./Monitor'),
/... | Log.on(pattern, Log.console);
}
}(this)); | random_line_split | |
comments.py | """
Spam comments to be classified by the relational model.
"""
import os
import numpy as np
class Comments:
"""Class to write comment predicate data for the relational model."""
def __init__(self, config_obj, util_obj):
"""Initializes object dependencies."""
self.config_obj = config_obj
... | temp_df = df.filter(['com_id', 'ind_pred', 'label'], axis=1)
unique_df = temp_df.drop_duplicates()
return unique_df
def write_predicates(self, df, dset, data_f):
"""Writes dataframes to csv files.
df: comments dataframe.
dset: dataset (e.g. val, test).
data_f... | df: comments dataframe.
Returns dataframe with unique rows.""" | random_line_split |
comments.py | """
Spam comments to be classified by the relational model.
"""
import os
import numpy as np
class Comments:
"""Class to write comment predicate data for the relational model."""
def __init__(self, config_obj, util_obj):
"""Initializes object dependencies."""
self.config_obj = config_obj
... |
else:
self.write_predicates(unique_df, dset, data_f)
# private
def define_file_folders(self):
"""Returns absolute path directories."""
rel_dir = self.config_obj.rel_dir
domain = self.config_obj.domain
data_f = rel_dir + 'data/' + domain + '/'
if not... | self.write_tuffy_predicates(unique_df, dset, data_f) | conditional_block |
comments.py | """
Spam comments to be classified by the relational model.
"""
import os
import numpy as np
class Comments:
"""Class to write comment predicate data for the relational model."""
def __init__(self, config_obj, util_obj):
"""Initializes object dependencies."""
self.config_obj = config_obj
... |
def write_predicates(self, df, dset, data_f):
"""Writes dataframes to csv files.
df: comments dataframe.
dset: dataset (e.g. val, test).
data_f: folder to save data to."""
fold = self.config_obj.fold
df['prior'] = 0
df.to_csv(data_f + dset + '_no_label_' + ... | """Filter out any duplicate comments using the specified columns.
df: comments dataframe.
Returns dataframe with unique rows."""
temp_df = df.filter(['com_id', 'ind_pred', 'label'], axis=1)
unique_df = temp_df.drop_duplicates()
return unique_df | identifier_body |
comments.py | """
Spam comments to be classified by the relational model.
"""
import os
import numpy as np
class Comments:
"""Class to write comment predicate data for the relational model."""
def __init__(self, config_obj, util_obj):
"""Initializes object dependencies."""
self.config_obj = config_obj
... | (self, df, dset, data_f):
"""Writes dataframes to csv files.
df: comments dataframe.
dset: dataset (e.g. val, test).
data_f: folder to save data to."""
fold = self.config_obj.fold
df['prior'] = 0
df.to_csv(data_f + dset + '_no_label_' + fold + '.tsv',
... | write_predicates | identifier_name |
SolveTSPSimulatedAnnealing.py | #==============================================================================
#description : Solves travelling salesman problem by using Hill Climbing.
#author : Yakup Cengiz
#date : 20151121
#version : 0.1
#notes :
#python_version : 3.5.0
#Reference : http://www.psy... | (prev_score,next_score,temperature):
if next_score > prev_score:
return 1.0
else:
return math.exp( -abs(next_score-prev_score)/temperature )
class ObjectiveFunction:
'''class to wrap an objective function and
keep track of the best solution evaluated'''
def __init__(self,ob... | P | identifier_name |
SolveTSPSimulatedAnnealing.py | #==============================================================================
#description : Solves travelling salesman problem by using Hill Climbing.
#author : Yakup Cengiz
#date : 20151121
#version : 0.1
#notes :
#python_version : 3.5.0
#Reference : http://www.psy... |
def ApplySimulatedAnnealing(init_function,move_operator,objective_function,max_evaluations,start_temp,alpha):
# wrap the objective function (so we record the best)
objective_function=ObjectiveFunction(objective_function)
current = init_function()
current_score = objective_function... | score=self.objective_function(solution)
if self.best is None or score > self.best_score:
self.best_score=score
self.best=solution
return score | identifier_body |
SolveTSPSimulatedAnnealing.py | #==============================================================================
#description : Solves travelling salesman problem by using Hill Climbing.
#author : Yakup Cengiz
#date : 20151121
#version : 0.1
#notes :
#python_version : 3.5.0
#Reference : http://www.psy... |
else:
copy[i+1:]=reversed(tour[:j])
copy[:j]=reversed(tour[i+1:])
if copy != tour: # no point returning the same tour
yield copy
def kirkpatrick_cooling(start_temp, alpha):
T = start_temp
while True:
yield T
T = alpha * T
... | copy[i:j+1]=reversed(tour[i:j+1]) | conditional_block |
SolveTSPSimulatedAnnealing.py | #==============================================================================
#description : Solves travelling salesman problem by using Hill Climbing.
#author : Yakup Cengiz
#date : 20151121
#version : 0.1
#notes :
#python_version : 3.5.0
#Reference : http://www.psy... | if iterationCount >= max_evaluations:
done=True
break
next_score=objective_function(next)
iterationCount+=1
# probablistically accept this solution always accepting better solutions
p = P(current_score,... | for temperature in cooling_schedule:
done = False
# examine moves around our current position
for next in move_operator(current): | random_line_split |
style.py | import numpy as np
import pandas as pd
from bokeh.plotting import *
# Define some categories
categories = [
'ousia', 'poson', 'poion', 'pros ti', 'pou',
'pote', 'keisthai', 'echein', 'poiein', 'paschein',
]
# Create data
N = 10
data = { cat : np.random.randint(10, 100, size=N) for cat in categories }
# Defin... | (data, categories):
ys = []
last = np.zeros(len(data.values()[0]))
for cat in categories:
next = last + data[cat]
ys.append(np.hstack((last[::-1], next)))
last = next
return ys
# Get the y coordinates of the stacked data
ys = stacked(data, categories)
# The x coordinates for ea... | stacked | identifier_name |
style.py | import numpy as np
import pandas as pd
from bokeh.plotting import *
# Define some categories
categories = [
'ousia', 'poson', 'poion', 'pros ti', 'pou',
'pote', 'keisthai', 'echein', 'poiein', 'paschein',
] | # Create data
N = 10
data = { cat : np.random.randint(10, 100, size=N) for cat in categories }
# Define a little function to stack series together to make polygons. Soon
# this will be built into Bokeh.
def stacked(data, categories):
ys = []
last = np.zeros(len(data.values()[0]))
for cat in categories:
... | random_line_split | |
style.py | import numpy as np
import pandas as pd
from bokeh.plotting import *
# Define some categories
categories = [
'ousia', 'poson', 'poion', 'pros ti', 'pou',
'pote', 'keisthai', 'echein', 'poiein', 'paschein',
]
# Create data
N = 10
data = { cat : np.random.randint(10, 100, size=N) for cat in categories }
# Defin... |
return ys
# Get the y coordinates of the stacked data
ys = stacked(data, categories)
# The x coordinates for each polygon are simply the series concatenated
# with its reverse.
xs = [np.hstack((categories[::-1], categories))] * len(ys)
# Pick out a color palette
colors = brewer["Spectral"][len(ys)]
# EXERCISE:... | next = last + data[cat]
ys.append(np.hstack((last[::-1], next)))
last = next | conditional_block |
style.py | import numpy as np
import pandas as pd
from bokeh.plotting import *
# Define some categories
categories = [
'ousia', 'poson', 'poion', 'pros ti', 'pou',
'pote', 'keisthai', 'echein', 'poiein', 'paschein',
]
# Create data
N = 10
data = { cat : np.random.randint(10, 100, size=N) for cat in categories }
# Defin... |
# Get the y coordinates of the stacked data
ys = stacked(data, categories)
# The x coordinates for each polygon are simply the series concatenated
# with its reverse.
xs = [np.hstack((categories[::-1], categories))] * len(ys)
# Pick out a color palette
colors = brewer["Spectral"][len(ys)]
# EXERCISE: output static... | ys = []
last = np.zeros(len(data.values()[0]))
for cat in categories:
next = last + data[cat]
ys.append(np.hstack((last[::-1], next)))
last = next
return ys | identifier_body |
tap4nodeunit.js | /*
* Copyright 2012 Mark Cavage. All rights reserved.
*
* Help nodeunit API feel like node-tap's.
*
* Usage:
* if (require.cache[__dirname + '/tap4nodeunit.js'])
* delete require.cache[__dirname + '/tap4nodeunit.js'];
* var tap4nodeunit = require('./tap4nodeunit.js');
* var after = tap... | },
test: function test(name, tester) {
module.parent.exports[name] = function _(t) {
var _done = false;
t.end = function end() {
if (!_done) {
_done = true;
... | console.error('before:\n' + e.stack);
process.exit(1);
}
}; | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.