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 |
|---|---|---|---|---|
sorted-list.py | # -----------------------------------------------------------
# compares the creation of sorted lists using the python
# bisect module, and the "usual" way
#o
# (C) 2015 Frank Hofmann, Berlin, Germany
# Released under GNU Public License (GPL)
# email frank.hofmann@efho.de
# --------------------------------------------... |
# sort the list in-place
sortedNumbers.sort()
return
def sortListBisect():
# define empty list, and fill with 200000 randomized integers
sortedNumbers = []
for element in range(200000):
# choose a number between 0 and 1000
newNumber = random.randint(0, 1000)
#print ("adding %i to list ... " %newNumber)
... | newNumber = random.randint(0, 1000)
# add number to list
#print ("adding %i to list ... " %newNumber)
sortedNumbers.append(newNumber) | conditional_block |
remote-client.py | from code import InteractiveConsole
import sys
try:
import websocket
except:
print('Please install websocket_client')
raise
class InteractiveRemoteConsole(InteractiveConsole):
def __init__(self, uri=None):
if uri is None:
uri = 'ws://localhost:44445/'
InteractiveConsole.__i... |
def interact(uri=None, readfunc=None, banner=None, exitmsg=None):
console = InteractiveRemoteConsole(uri)
if readfunc is not None:
console.raw_input = readfunc
else:
try:
import readline
except ImportError:
pass
console.interact(banner, exitmsg)
if __na... | self.websocket.send(line) | identifier_body |
remote-client.py | from code import InteractiveConsole
import sys
try:
import websocket
except:
print('Please install websocket_client')
raise
class InteractiveRemoteConsole(InteractiveConsole):
def __init__(self, uri=None):
if uri is None:
uri = 'ws://localhost:44445/'
InteractiveConsole.__i... | with open(source, 'r') as sourcefile:
# Wait for initial prompt
console.recv(supress_prompt=True)
# Send lines
for line in sourcefile:
line = line.rstrip()
console.push(line)
console.recv(supress_prompt=True)
... | console = InteractiveRemoteConsole(uri) | random_line_split |
remote-client.py | from code import InteractiveConsole
import sys
try:
import websocket
except:
print('Please install websocket_client')
raise
class InteractiveRemoteConsole(InteractiveConsole):
def __init__(self, uri=None):
if uri is None:
uri = 'ws://localhost:44445/'
InteractiveConsole.__i... | (self, banner=None, exitmsg=None):
if banner is None:
self.write("Remote Python to Minecraft\n")
elif banner:
self.write("%s\n" % str(banner))
self.recv()
while 1:
try:
try:
line = self.raw_input()
ex... | interact | identifier_name |
remote-client.py | from code import InteractiveConsole
import sys
try:
import websocket
except:
print('Please install websocket_client')
raise
class InteractiveRemoteConsole(InteractiveConsole):
def __init__(self, uri=None):
if uri is None:
uri = 'ws://localhost:44445/'
InteractiveConsole.__i... | if len(sys.argv) > 1:
uri = None if len(sys.argv) <= 2 else sys.argv[2]
source = sys.argv[1]
console = InteractiveRemoteConsole(uri)
with open(source, 'r') as sourcefile:
# Wait for initial prompt
console.recv(supress_prompt=True)
# Send lines
... | conditional_block | |
express-rate-limit-tests.ts | import RateLimit = require("express-rate-limit");
const apiLimiter = new RateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100,
headers: false,
skipFailedRequests: false,
skipSuccessfulRequests: true,
});
apiLimiter.resetKey('testKey');
const apiLimiterWithMaxFn = new RateLimit({
windowMs: 15 * 6... | store: new SomeStore()
}); | random_line_split | |
express-rate-limit-tests.ts | import RateLimit = require("express-rate-limit");
const apiLimiter = new RateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100,
headers: false,
skipFailedRequests: false,
skipSuccessfulRequests: true,
});
apiLimiter.resetKey('testKey');
const apiLimiterWithMaxFn = new RateLimit({
windowMs: 15 * 6... | (key: string) { }
resetKey(key: string) { }
}
const limiterWithStore = new RateLimit({
store: new SomeStore()
});
| decrement | identifier_name |
express-rate-limit-tests.ts | import RateLimit = require("express-rate-limit");
const apiLimiter = new RateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100,
headers: false,
skipFailedRequests: false,
skipSuccessfulRequests: true,
});
apiLimiter.resetKey('testKey');
const apiLimiterWithMaxFn = new RateLimit({
windowMs: 15 * 6... |
resetKey(key: string) { }
}
const limiterWithStore = new RateLimit({
store: new SomeStore()
});
| { } | identifier_body |
wayknew.py | from json import dumps
import requests
d = {'yolar': 535, 'galaxy': 536, 'solar': 551, 'swordkeeper': 552, 'civilization': 553, 'CurvatureDrive': 554,
'singer': 555, 'hdfragments': 556, 'evans': 557, 'dagon': 558, 'di-foil': 559, 'dimension': 560, 'farmer': 562,
'hibernation': 564, 'huformation': 565, 'ment... | (repo_name, str_doc):
if repo_name not in d.keys():
print('article not in wayknew, please create a null article in wayknew!')
exit(-1)
title = repo_name + ' 线上API文档'
url = 'https://api.wayknew.com/api/articles/' + str(d[repo_name])
html_content = '<p>' + str_doc + '</p>'
request_data... | write_to_wayknew | identifier_name |
wayknew.py | from json import dumps
import requests
d = {'yolar': 535, 'galaxy': 536, 'solar': 551, 'swordkeeper': 552, 'civilization': 553, 'CurvatureDrive': 554,
'singer': 555, 'hdfragments': 556, 'evans': 557, 'dagon': 558, 'di-foil': 559, 'dimension': 560, 'farmer': 562,
'hibernation': 564, 'huformation': 565, 'ment... | int(repo_name + ' api write to wayknew success')
| p.text)
exit(rsp.status_code)
pr | conditional_block |
wayknew.py | from json import dumps
import requests
d = {'yolar': 535, 'galaxy': 536, 'solar': 551, 'swordkeeper': 552, 'civilization': 553, 'CurvatureDrive': 554,
'singer': 555, 'hdfragments': 556, 'evans': 557, 'dagon': 558, 'di-foil': 559, 'dimension': 560, 'farmer': 562,
'hibernation': 564, 'huformation': 565, 'ment... | if repo_name not in d.keys():
print('article not in wayknew, please create a null article in wayknew!')
exit(-1)
title = repo_name + ' 线上API文档'
url = 'https://api.wayknew.com/api/articles/' + str(d[repo_name])
html_content = '<p>' + str_doc + '</p>'
request_data = {'title': title, 'conte... | identifier_body | |
wayknew.py | from json import dumps
import requests
d = {'yolar': 535, 'galaxy': 536, 'solar': 551, 'swordkeeper': 552, 'civilization': 553, 'CurvatureDrive': 554,
'singer': 555, 'hdfragments': 556, 'evans': 557, 'dagon': 558, 'di-foil': 559, 'dimension': 560, 'farmer': 562,
'hibernation': 564, 'huformation': 565, 'ment... | request_data = {'title': title, 'content': str_doc, 'html_content': html_content}
rsp = requests.patch(url, dumps(request_data), headers=head)
if rsp.status_code != 200:
print(rsp.text)
exit(rsp.status_code)
print(repo_name + ' api write to wayknew success') | url = 'https://api.wayknew.com/api/articles/' + str(d[repo_name])
html_content = '<p>' + str_doc + '</p>' | random_line_split |
cmp.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 std::{cmp};
#[test]
fn min() {
test!(cmp::min(0, 1) == 0);
test!(cmp::min(0, 0) == 0);
}
|
#[test]
fn min_mut() {
test!(cmp::min_mut(&mut 0, &mut 1) == &mut 0);
test!(cmp::min_mut(&mut 0, &mut 0) == &mut 0);
}
#[test]
fn max() {
test!(cmp::max(0, 1) == 1);
test!(cmp::max(0, 0) == 0);
}
#[test]
fn max_ref() {
test!(cmp::max_ref(&0, &1) == &1);
test!(cmp::max_ref(&0, &0) == &0);
}
#... | #[test]
fn min_ref() {
test!(cmp::min_ref(&0, &1) == &0);
test!(cmp::min_ref(&0, &0) == &0);
} | random_line_split |
cmp.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 std::{cmp};
#[test]
fn min() {
test!(cmp::min(0, 1) == 0);
test!(cmp::min(0, 0) == 0);
}
#[test]
fn min... |
#[test]
fn max_ref() {
test!(cmp::max_ref(&0, &1) == &1);
test!(cmp::max_ref(&0, &0) == &0);
}
#[test]
fn max_mut() {
test!(cmp::max_mut(&mut 0, &mut 1) == &mut 1);
test!(cmp::max_mut(&mut 0, &mut 0) == &mut 0);
}
| {
test!(cmp::max(0, 1) == 1);
test!(cmp::max(0, 0) == 0);
} | identifier_body |
cmp.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 std::{cmp};
#[test]
fn min() {
test!(cmp::min(0, 1) == 0);
test!(cmp::min(0, 0) == 0);
}
#[test]
fn min... | () {
test!(cmp::max_mut(&mut 0, &mut 1) == &mut 1);
test!(cmp::max_mut(&mut 0, &mut 0) == &mut 0);
}
| max_mut | identifier_name |
scheduler.rs | use std::collections::{HashSet, VecDeque};
use std::io;
use std::path::Path;
use core::{FNV, Field, Key, TypeConstraint};
use graph::{EntryId, Graph};
use nodes::{Complete, Node, Runnable, State};
use selectors::{Selector, SelectDependencies};
use tasks::Tasks;
/**
* Represents the state of an execution of (a subgr... |
pub fn root_states(&self) -> Vec<(&Key, &TypeConstraint, Option<&Complete>)> {
self.roots.iter()
.map(|root| {
let state = self.graph.entry(root).and_then(|e| e.state());
(root.subject(), root.product(), state)
})
.collect()
}
pub fn add_root_select(&mut self, subject: Key... | {
self.roots.clear();
self.candidates.clear();
self.outstanding.clear();
} | identifier_body |
scheduler.rs | use std::collections::{HashSet, VecDeque};
use std::io;
use std::path::Path;
use core::{FNV, Field, Key, TypeConstraint};
use graph::{EntryId, Graph};
use nodes::{Complete, Node, Runnable, State};
use selectors::{Selector, SelectDependencies};
use tasks::Tasks;
/**
* Represents the state of an execution of (a subgr... | * Attempt to run a step with the currently available dependencies of the given Node. If
* a step runs, the new State of the Node will be returned.
*/
fn attempt_step(&self, id: EntryId) -> Option<State<Node>> {
if !self.graph.is_ready_entry(id) {
return None;
}
// Run a step.
let entry... | random_line_split | |
scheduler.rs | use std::collections::{HashSet, VecDeque};
use std::io;
use std::path::Path;
use core::{FNV, Field, Key, TypeConstraint};
use graph::{EntryId, Graph};
use nodes::{Complete, Node, Runnable, State};
use selectors::{Selector, SelectDependencies};
use tasks::Tasks;
/**
* Represents the state of an execution of (a subgr... | ,
None =>
// Not ready to step.
continue,
}
}
self.runnable.clear();
ready
}
}
| {
// Add the new dependencies.
self.graph.add_dependencies(entry_id, w);
let ref graph = self.graph;
let mut incomplete_deps =
self.graph.entry_for_id(entry_id).dependencies().iter()
.map(|&d| graph.entry_for_id(d))
.filter(|e| !e.is_comple... | conditional_block |
scheduler.rs | use std::collections::{HashSet, VecDeque};
use std::io;
use std::path::Path;
use core::{FNV, Field, Key, TypeConstraint};
use graph::{EntryId, Graph};
use nodes::{Complete, Node, Runnable, State};
use selectors::{Selector, SelectDependencies};
use tasks::Tasks;
/**
* Represents the state of an execution of (a subgr... | (&self) -> Vec<(&Key, &TypeConstraint, Option<&Complete>)> {
self.roots.iter()
.map(|root| {
let state = self.graph.entry(root).and_then(|e| e.state());
(root.subject(), root.product(), state)
})
.collect()
}
pub fn add_root_select(&mut self, subject: Key, product: TypeConstra... | root_states | identifier_name |
selfUpdate.js | /* eslint-disable no-param-reassign */
import Vue from 'vue';
export default {
namespaced: true,
state: {
cache: null,
},
mutations: {
setCache(state, value) {
state.cache = value;
},
},
actions: {
get({ state, commit }, cache = true) {
... | },
}; | return response.body.version;
}, | random_line_split |
selfUpdate.js | /* eslint-disable no-param-reassign */
import Vue from 'vue';
export default {
namespaced: true,
state: {
cache: null,
},
mutations: {
setCache(state, value) {
state.cache = value;
},
},
actions: {
get({ state, commit }, cache = true) | throw response;
},
).then((result) => {
commit('setCache', result);
return result;
});
}
,
async latest() {
const response = await Vue.http.get('https://download.contao.org/contao-manager/stable/con... | {
if (cache && state.cache) {
return new Promise((resolve) => {
resolve(state.cache);
});
}
return Vue.http.get('api/server/self-update').then(
response => response.body,
(response) => {
... | identifier_body |
selfUpdate.js | /* eslint-disable no-param-reassign */
import Vue from 'vue';
export default {
namespaced: true,
state: {
cache: null,
},
mutations: {
setCache(state, value) {
state.cache = value;
},
},
actions: {
get({ state, commit }, cache = true) {
... |
return Vue.http.get('api/server/self-update').then(
response => response.body,
(response) => {
if (response.status === 501) {
return {
current_version: null,
latest_version: ... | {
return new Promise((resolve) => {
resolve(state.cache);
});
} | conditional_block |
selfUpdate.js | /* eslint-disable no-param-reassign */
import Vue from 'vue';
export default {
namespaced: true,
state: {
cache: null,
},
mutations: {
setCache(state, value) {
state.cache = value;
},
},
actions: {
get({ state, commit }, cache = true) {
... | () {
const response = await Vue.http.get('https://download.contao.org/contao-manager/stable/contao-manager.version');
return response.body.version;
},
},
};
| latest | identifier_name |
igdialog.component.ts | import { Component, ElementRef, IterableDiffers, KeyValueDiffers, ChangeDetectorRef, Renderer2 } from '@angular/core';
import { IgContentControlBase } from '../igcontrolbase/igcontentcontrolbase';
@Component({
selector: 'ig-dialog',
template: '<ng-content></ng-content>',
inputs: ['widgetId', 'options', 'ch... | /**
* Minimizes the dialog if it is not minimized.
* Note: If the state of the dialog changes, then stateChanging and stateChanged events are raised.
*/
/* istanbul ignore next */
public minimize(): object { return; }
/**
* Maximizes the dialog if it is not maximized.
* ... | public open(): object { return; }
| random_line_split |
igdialog.component.ts | import { Component, ElementRef, IterableDiffers, KeyValueDiffers, ChangeDetectorRef, Renderer2 } from '@angular/core';
import { IgContentControlBase } from '../igcontrolbase/igcontentcontrolbase';
@Component({
selector: 'ig-dialog',
template: '<ng-content></ng-content>',
inputs: ['widgetId', 'options', 'ch... |
/**
* Minimizes the dialog if it is not minimized.
* Note: If the state of the dialog changes, then stateChanging and stateChanged events are raised.
*/
/* istanbul ignore next */
public minimize(): object { return; }
/**
* Maximizes the dialog if it is not maximized.
* ... | { return; } | identifier_body |
igdialog.component.ts | import { Component, ElementRef, IterableDiffers, KeyValueDiffers, ChangeDetectorRef, Renderer2 } from '@angular/core';
import { IgContentControlBase } from '../igcontrolbase/igcontentcontrolbase';
@Component({
selector: 'ig-dialog',
template: '<ng-content></ng-content>',
inputs: ['widgetId', 'options', 'ch... | (e?: object): object { return; }
/**
* Retrieves the igDialog content container or sets its content to be the new content provided.
*
* @param newContent The new html content provided as a string. If the parameter is provided then the method acts as a setter.
*/
/* istanbul ignore next ... | moveToTop | identifier_name |
push-animator.js | /*
Copyright 2013-2015 ASIAL CORPORATION
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, so... | transform: 'translate3d(0px, 0px, 0px)'
}, {
duration: this.duration,
timing: this.timing
})
.queue(callback => {
this._slidingElements = null;
super.clearTransition();
done && done();
callback();
}),
animit(thi... | animit(this._slidingElements)
.wait(this.delay)
.queue({ | random_line_split |
push-animator.js | /*
Copyright 2013-2015 ASIAL CORPORATION
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, so... | () {
const slidingElements = [this._side, this._content];
if (this._oppositeSide && this._oppositeSide.mode === 'split') {
slidingElements.push(this._oppositeSide);
}
return slidingElements;
}
translate(distance) {
if (!this._slidingElements) {
this._slidingElements = this._getSlid... | _getSlidingElements | identifier_name |
push-animator.js | /*
Copyright 2013-2015 ASIAL CORPORATION
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, so... |
animit(this._slidingElements)
.queue({
transform: `translate3d(${this.minus + distance}px, 0px, 0px)`
})
.play();
}
/**
* @param {Function} done
*/
open(done) {console.log('opening');
const max = this._side.offsetWidth;
this._slidingElements = this._getSlidingElement... | {
this._slidingElements = this._getSlidingElements();
} | conditional_block |
push-animator.js | /*
Copyright 2013-2015 ASIAL CORPORATION
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, so... |
/**
* @param {Function} done
*/
open(done) {console.log('opening');
const max = this._side.offsetWidth;
this._slidingElements = this._getSlidingElements();
animit.runAll(
animit(this._slidingElements)
.wait(this.delay)
.queue({
transform: `translate3d(${this.minu... | {
if (!this._slidingElements) {
this._slidingElements = this._getSlidingElements();
}
animit(this._slidingElements)
.queue({
transform: `translate3d(${this.minus + distance}px, 0px, 0px)`
})
.play();
} | identifier_body |
DeepMNISTKeras.py | '''Trains a simple convnet on the MNIST dataset.
Gets to 99.25% test accuracy after 12 epochs
(there is still a lot of margin for parameter tuning).
16 seconds per epoch on a GRID K520 GPU.
'''
from __future__ import print_function
import keras
from keras.datasets import mnist
from keras.models import Sequential
from... |
else:
x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, 1)
x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols, 1)
input_shape = (img_rows, img_cols, 1)
x_train = x_train.astype('float32')
x_test = x_test.astype('float32')
x_train /= 255
x_test /= 255
print('x_train shape:', x_train.... | x_train = x_train.reshape(x_train.shape[0], 1, img_rows, img_cols)
x_test = x_test.reshape(x_test.shape[0], 1, img_rows, img_cols)
input_shape = (1, img_rows, img_cols) | conditional_block |
DeepMNISTKeras.py | '''Trains a simple convnet on the MNIST dataset.
Gets to 99.25% test accuracy after 12 epochs
(there is still a lot of margin for parameter tuning).
16 seconds per epoch on a GRID K520 GPU.
'''
from __future__ import print_function
import keras
from keras.datasets import mnist
from keras.models import Sequential
from... | print('Test accuracy:', score[1]) | random_line_split | |
menu.js | 'use strict' |
const menu = (currentCat, allCats, setCat, clearCat) => yo `
<ul>
${allCats.map((cat) => {
const onClick = (e) => {
e.preventDefault()
e.stopPropagation()
if (currentCat === cat) clearCat()
else setCat(cat)
}
return yo `
<li class="${currentCat === cat ? 'active' : ''}">
<a href="#" ... |
const yo = require('yo-yo')
| random_line_split |
03_instanced_drawing.py | from glfwpy.glfw import *
import sys
import numpy as np
from OpenGL.GL import *
from OpenGL.arrays import ArrayDatatype
import ctypes
vertex = """
#version 330
in vec3 vin_position;
in vec3 vin_color;
uniform vec3 vu_displacement[2];
out vec3 vout_color;
void main(void)
{
vout_color = vin_color;
gl_Position... |
def add_shader(self, source, shader_type):
try:
shader_id = glCreateShader(shader_type)
glShaderSource(shader_id, source)
glCompileShader(shader_id)
if glGetShaderiv(shader_id, GL_COMPILE_STATUS) != GL_TRUE:
info = glGetShaderInfoLog(shader_i... | self.program_id = glCreateProgram()
vs_id = self.add_shader(vertex, GL_VERTEX_SHADER)
frag_id = self.add_shader(fragment, GL_FRAGMENT_SHADER)
glAttachShader(self.program_id, vs_id)
glAttachShader(self.program_id, frag_id)
glLinkProgram(self.program_id)
if glGetProgramiv... | identifier_body |
03_instanced_drawing.py | from glfwpy.glfw import *
import sys
import numpy as np
from OpenGL.GL import *
from OpenGL.arrays import ArrayDatatype
import ctypes
vertex = """
#version 330
in vec3 vin_position;
in vec3 vin_color;
uniform vec3 vu_displacement[2];
out vec3 vout_color;
void main(void)
{
vout_color = vin_color;
gl_Position... | glBindVertexArray(0)
SwapBuffers()
running = running and GetWindowParam(OPENED) | glBindVertexArray(vao_id)
glDrawArraysInstanced(GL_TRIANGLES, 0, 3, 2)
glUseProgram(0) | random_line_split |
03_instanced_drawing.py | from glfwpy.glfw import *
import sys
import numpy as np
from OpenGL.GL import *
from OpenGL.arrays import ArrayDatatype
import ctypes
vertex = """
#version 330
in vec3 vin_position;
in vec3 vin_color;
uniform vec3 vu_displacement[2];
out vec3 vout_color;
void main(void)
{
vout_color = vin_color;
gl_Position... | (x, y):
print 'Key: %s Action: %s pressed' % (x, y)
if __name__ == "__main__":
if not Init():
print 'GLFW initialization failed'
sys.exit(-1)
OpenWindowHint(OPENGL_VERSION_MAJOR, 3)
OpenWindowHint(OPENGL_VERSION_MINOR, 2)
OpenWindowHint(OPENGL_PROFILE, OPENGL_CORE_PROFILE)
Open... | key_callback | identifier_name |
03_instanced_drawing.py | from glfwpy.glfw import *
import sys
import numpy as np
from OpenGL.GL import *
from OpenGL.arrays import ArrayDatatype
import ctypes
vertex = """
#version 330
in vec3 vin_position;
in vec3 vin_color;
uniform vec3 vu_displacement[2];
out vec3 vout_color;
void main(void)
{
vout_color = vin_color;
gl_Position... |
SetKeyCallback(key_callback)
SetWindowTitle("Modern opengl example")
Enable(AUTO_POLL_EVENTS)
print 'Vendor: %s' % (glGetString(GL_VENDOR))
print 'Opengl version: %s' % (glGetString(GL_VERSION))
print 'GLSL Version: %s' % (glGetString(GL_SHADING_LANGUAGE_VERSION))
print 'Renderer: %s' % ... | print "OpenWindow failed"
Terminate()
sys.exit(-1) | conditional_block |
pdfoptions.js | /**
* Controller for the Convert screen
*
* @class Controllers.convert
* @uses core
* @uses FileManager
*
* CONFIG.url - remote URL to load
* CONFIG.file - local File to load
* CONFIG.html - HTML String to load
*/
var APP = require("core");
var FileManager = require("FileManager");
var CONFIG = arguments[0] ... | (e) {
try {
switch (e.row.id) {
case "a4":
$.a4.hasCheck = true;
$.letter.hasCheck = false;
Ti.App.Properties.setString("paper", "a4");
break;
default:
$.a4.hasCheck = false;
$.letter.hasCheck = true;
Ti.App.Properties.setString("paper", "letter");
break;
}
} catch(err) {
A... | doTableViewClick | identifier_name |
pdfoptions.js | /**
* Controller for the Convert screen
*
* @class Controllers.convert
* @uses core
* @uses FileManager
*
* CONFIG.url - remote URL to load
* CONFIG.file - local File to load
* CONFIG.html - HTML String to load
*/
var APP = require("core");
var FileManager = require("FileManager");
var CONFIG = arguments[0] ... | break;
default:
$.a4.hasCheck = false;
$.letter.hasCheck = true;
Ti.App.Properties.setString("paper", "letter");
break;
}
} catch(err) {
APP.error({
f : 'pdfoptions.doTableViewClick',
err : err
});
}
};
function doSave(e) {
try {
//Check the filename
var filename = $.filename.v... | random_line_split | |
pdfoptions.js | /**
* Controller for the Convert screen
*
* @class Controllers.convert
* @uses core
* @uses FileManager
*
* CONFIG.url - remote URL to load
* CONFIG.file - local File to load
* CONFIG.html - HTML String to load
*/
var APP = require("core");
var FileManager = require("FileManager");
var CONFIG = arguments[0] ... |
if ($.a4.hasCheck) {
var paper = "a4";
} else {
var paper = "letter";
}
//Fire the Event
$.options.fireEvent("save", {
filename : filename,
paper : paper
});
} catch(err) {
APP.error({
f : 'pdfoptions.doSave',
err : err
});
}
};
function doCancel(e) {
try {
//Fire the Event
$.... | {
filename += ".pdf";
} | conditional_block |
pdfoptions.js | /**
* Controller for the Convert screen
*
* @class Controllers.convert
* @uses core
* @uses FileManager
*
* CONFIG.url - remote URL to load
* CONFIG.file - local File to load
* CONFIG.html - HTML String to load
*/
var APP = require("core");
var FileManager = require("FileManager");
var CONFIG = arguments[0] ... | err : err
});
}
}
;
function doCancel(e) {
try {
//Fire the Event
$.options.fireEvent("cancel", {});
return;
} catch(err) {
APP.error({
f : 'pdfoptions.doCancel',
err : err
});
}
};
function doFileCheck(e) {
try {
//Check to see if the file exists
var filename = $.filename.value;
filen... | {
try {
//Check the filename
var filename = $.filename.value;
if (filename.indexOf(".pdf") == -1) {
filename += ".pdf";
}
if ($.a4.hasCheck) {
var paper = "a4";
} else {
var paper = "letter";
}
//Fire the Event
$.options.fireEvent("save", {
filename : filename,
paper : paper
});
} c... | identifier_body |
autoRestReportServiceForAzure.d.ts | /*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator 0.14.0.0
* Changes may cause incorrect behavior and will be lost if the code is
* regenerate... | *
* @param {object} [options] - The parameter options
*
* @param {Array} [options.filters] - Filters to be added to the request pipeline
*
* @param {object} [options.requestOptions] - Options for the underlying request object
* {@link https://github.com/request/request#requestoptions-... | *
* @param {Credentials} credentials The management credentials for Azure.
*
* @param {string} [baseUri] - The base URI of the service. | random_line_split |
autoRestReportServiceForAzure.d.ts | /*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator 0.14.0.0
* Changes may cause incorrect behavior and will be lost if the code is
* regenerate... | {
/**
* @class
* Initializes a new instance of the AutoRestReportServiceForAzure class.
* @constructor
*
* @param {Credentials} credentials The management credentials for Azure.
*
* @param {string} [baseUri] - The base URI of the service.
*
* @param {object} [options] -... | AutoRestReportServiceForAzure | identifier_name |
index.tsx | import React from "react";
import {Entity} from "generated/graphql";
import Identity from "./Identity";
import Appearance from "./Appearance";
import Location from "./Location";
import Template from "./Template";
// import Glow from "./Glow";
import "../styles.scss";
import FileExplorer from "components/views/TacticalM... | {selectedEntity.appearance?.meshType === "sphere" && (
<Light
id={selectedEntity.id}
light={selectedEntity.light || undefined}
/>
)}
{selectedEntity.stageChild && (
<Systems
id={selectedEntity.id}
e... | />
)} */} | random_line_split |
index.tsx | import React from "react";
import {Entity} from "generated/graphql";
import Identity from "./Identity";
import Appearance from "./Appearance";
import Location from "./Location";
import Template from "./Template";
// import Glow from "./Glow";
import "../styles.scss";
import FileExplorer from "components/views/TacticalM... |
return (
<div className="control-palette">
<h2>Property Palette</h2>
{selectedEntity && (
<>
{selectedEntity.identity && (
<Identity
id={selectedEntity.id}
identity={selectedEntity.identity}
/>
)}
{currentStage ... | {
return (
<div>
<h3>Select asset for {getAsset.label}</h3>
<FileExplorer
simple
directory={getAsset.dir}
selectedFiles={[getAsset.current]}
onClick={(_evt: any, container: {id: string; fullPath: string}) => {
getAsset.cb(container.fullPath);... | conditional_block |
comment4.rs | // rustfmt-normalise_comments: false
//! Doc comment
fn test() {
// comment
// comment2
code(); /* leave this comment alone!
* ok? */
/* Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec a
* diam lectus. Sed sit amet ipsum mauris. Maecenas congue ligula ac quam
... | {
} | identifier_body | |
comment4.rs | // rustfmt-normalise_comments: false
//! Doc comment
fn | () {
// comment
// comment2
code(); /* leave this comment alone!
* ok? */
/* Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec a
* diam lectus. Sed sit amet ipsum mauris. Maecenas congue ligula ac quam
* viverra nec consectetur ante hendrerit. Donec et m... | test | identifier_name |
comment4.rs | // rustfmt-normalise_comments: false
//! Doc comment |
code(); /* leave this comment alone!
* ok? */
/* Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec a
* diam lectus. Sed sit amet ipsum mauris. Maecenas congue ligula ac quam
* viverra nec consectetur ante hendrerit. Donec et mollis dolor.
* Praesent et ... | fn test() {
// comment
// comment2 | random_line_split |
util.js | var fs = require('fs');
var shell = require('shelljs'); | fs.readFile(shell.pwd() + fileLocation, 'UTF8', function(err, fileContents) {
if(err){
callback(true, err);
}else{
callback(null, JSON.parse(fileContents));
}
});
};
module.exports.writeJsonSchema = function(path, schemaName, schemaDefinition, callback) {
var jsonSchema = {
name: sch... |
module.exports.readJsonFile = function(fileLocation, callback) { | random_line_split |
util.js | var fs = require('fs');
var shell = require('shelljs');
module.exports.readJsonFile = function(fileLocation, callback) {
fs.readFile(shell.pwd() + fileLocation, 'UTF8', function(err, fileContents) {
if(err) | else{
callback(null, JSON.parse(fileContents));
}
});
};
module.exports.writeJsonSchema = function(path, schemaName, schemaDefinition, callback) {
var jsonSchema = {
name: schemaName,
fields: schemaDefinition
};
var jsonPrettified = JSON.stringify(jsonSchema, null, 4);
fs.writeFile(path, j... | {
callback(true, err);
} | conditional_block |
step3_load_model.py | #!/usr/bin/env python
# Author: Shao Zhang and Phil Saltzman
# Last Updated: 2015-03-13
#
# This tutorial is intended as a initial panda scripting lesson going over
# display initialization, loading models, placing objects, and the scene graph.
#
# Step 3: In this step, we create a function called loadPlanets, which w... | # Finally, the following line sets our new sky texture on our sky model.
# The second argument must be one or the command will be ignored.
self.sky.setTexture(self.sky_tex, 1)
# Now we load the sun.
self.sun = loader.loadModel("models/planet_sphere")
# Now we repeat our ... | self.sky = loader.loadModel("models/solar_sky_sphere")
# After the object is loaded, it must be placed in the scene. We do this by
# changing the parent of self.sky to render, which is a special NodePath.
# Each frame, Panda starts with render and renders everything attached to
# it.
... | identifier_body |
step3_load_model.py | #!/usr/bin/env python
# Author: Shao Zhang and Phil Saltzman
# Last Updated: 2015-03-13
#
# This tutorial is intended as a initial panda scripting lesson going over
# display initialization, loading models, placing objects, and the scene graph.
#
# Step 3: In this step, we create a function called loadPlanets, which w... | (self):
# This is the initialization we had before
self.title = OnscreenText( # Create the title
text="Panda3D: Tutorial 1 - Solar System",
parent=base.a2dBottomRight, align=TextNode.A_right,
style=1, fg=(1, 1, 1, 1), pos=(-0.1, 0.1), scale=.07)
base.setBack... | __init__ | identifier_name |
step3_load_model.py | #!/usr/bin/env python
# Author: Shao Zhang and Phil Saltzman
# Last Updated: 2015-03-13
#
# This tutorial is intended as a initial panda scripting lesson going over
# display initialization, loading models, placing objects, and the scene graph.
#
# Step 3: In this step, we create a function called loadPlanets, which w... | # This is the initialization we had before
self.title = OnscreenText( # Create the title
text="Panda3D: Tutorial 1 - Solar System",
parent=base.a2dBottomRight, align=TextNode.A_right,
style=1, fg=(1, 1, 1, 1), pos=(-0.1, 0.1), scale=.07)
base.setBackgroundCo... |
class World(object):
def __init__(self): | random_line_split |
setup.py | coding: utf-8 -*-
import sys
import inselect
REQUIREMENTS = [
# TODO How to specify OpenCV? 'cv2>=3.1.0',
'numpy>=1.11.1,<1.12',
'Pillow>=3.4.2,<3.5',
'python-dateutil>=2.6.0,<2.7',
'pytz>=2016.7',
'PyYAML>=3.12,<3.2',
'schematics>=1.1.1,<1.2',
'scikit-learn>=0.18.1,<0.19',
'scip... | ys.exit('Only Python >= 3.5 is supported')
| conditional_block | |
setup.py | /bin/env python3
# -*- coding: utf-8 -*-
import sys
import inselect
REQUIREMENTS = [
# TODO How to specify OpenCV? 'cv2>=3.1.0',
'numpy>=1.11.1,<1.12',
'Pillow>=3.4.2,<3.5',
'python-dateutil>=2.6.0,<2.7',
'pytz>=2016.7',
'PyYAML>=3.12,<3.2',
'schematics>=1.1.1,<1.2',
'scikit-learn>=0.... | # Qt plugins
(
site_packages.joinpath('PyQt5/Qt/plugins/platforms').joinpath(dep),
Path('platforms').joinpath(dep)
)
for dep in ('qwindows.dll',)
] + [
# PyQt extension modules
(
site_packages.joinpath('PyQt5').joinpath(dep),
... | ""Returns a list of tuples (src, dest) of Qt dependencies to be installed.
Elements are instances of Path.
site_packages should be an instance of Path to the site-packages directory.
IF we leave cx_Freeze to do its thing then the entirety of PyQt5, Qt5 and
uic are included in the installer. The only wa... | identifier_body |
setup.py | /env python3
# -*- coding: utf-8 -*-
import sys
import inselect
REQUIREMENTS = [
# TODO How to specify OpenCV? 'cv2>=3.1.0',
'numpy>=1.11.1,<1.12',
'Pillow>=3.4.2,<3.5',
'python-dateutil>=2.6.0,<2.7',
'pytz>=2016.7',
'PyYAML>=3.12,<3.2',
'schematics>=1.1.1,<1.2',
'scikit-learn>=0.18.1... | ):
"""cx_Freeze setup. Used for building Windows installers"""
import scipy
from pathlib import Path
from distutils.sysconfig import get_python_lib
from cx_Freeze import setup, Executable
from pylibdmtx import pylibdmtx
from pyzbar import pyzbar
# Useful paths
environment_root = ... | x_setup( | identifier_name |
setup.py | /bin/env python3
# -*- coding: utf-8 -*-
import sys
import inselect
REQUIREMENTS = [
# TODO How to specify OpenCV? 'cv2>=3.1.0',
'numpy>=1.11.1,<1.12',
'Pillow>=3.4.2,<3.5',
'python-dateutil>=2.6.0,<2.7',
'pytz>=2016.7',
'PyYAML>=3.12,<3.2',
'schematics>=1.1.1,<1.2',
'scikit-learn>=0.... |
# Directories as strings
include_files += [
# Fixes scipy freeze
# http://stackoverflow.com/a/32822431/1773758
str(Path(scipy.__file__).parent),
]
# Packages to exclude.
exclude_packages = [
str(p.relative_to(site_packages)).replace('\\', '.') for p in
site_... | include_files = [(str(source), str(dest)) for source, dest in include_files] | random_line_split |
views.py | from django.shortcuts import render_to_response
from django.views.generic import CreateView
from store.models import cloud_users
from django.http import HttpResponseRedirect
from django.template import RequestContext
from django.core.context_processors import csrf
from django.core.urlresolvers import reverse_lazy
from ... |
else:
formulario = AuthenticationForm()
return render_to_response('login.html',{'formulario': formulario}, context_instance=RequestContext(request))
def home(request):
return render_to_response('index.html', context_instance=RequestContext(request))
#def login(request):
# return render_to_response('login.html... | formulario = AuthenticationForm(request.POST)
if formulario.is_valid:
username = request.POST['username']
clave = request.POST['password']
acceso = authenticate(username = username, password = clave)
if acceso is not None:
if acceso.is_active:
login(request, acceso)
return HttpResponseRedire... | conditional_block |
views.py | from django.shortcuts import render_to_response
from django.views.generic import CreateView
from store.models import cloud_users
from django.http import HttpResponseRedirect
from django.template import RequestContext
from django.core.context_processors import csrf
from django.core.urlresolvers import reverse_lazy
from ... |
def iniciar_sesion(request):
if not request.user.is_anonymous():
return HttpResponseRedirect('../')
if request.method == "POST":
formulario = AuthenticationForm(request.POST)
if formulario.is_valid:
username = request.POST['username']
clave = request.POST['password']
acceso = authenticate(username = ... | template_name = 'signup.html'
model = cloud_users
success_url = reverse_lazy('signup')
def post(self,request,*args,**kwargs):
cloudUser = cloud_users()
cloudUser.cloud_user = request.POST['cloud_user']
cloudUser.enc_pass = request.POST['enc_pass']
cloudUser.ste_acc = request.POST['ste_acc']
cloudUser.ste_... | identifier_body |
views.py | from django.shortcuts import render_to_response
from django.views.generic import CreateView
from store.models import cloud_users
from django.http import HttpResponseRedirect
from django.template import RequestContext
from django.core.context_processors import csrf
from django.core.urlresolvers import reverse_lazy
from ... | else:
ctx = {'form':form}
return render_to_response('signup.html',ctx,context_instance=RequestContext(request))
ctx = {'form':form}
return render_to_response('signup.html',ctx,context_instance=RequestContext(request)) | return render_to_response('thanks_register.html',context_instance=RequestContext(request)) | random_line_split |
views.py | from django.shortcuts import render_to_response
from django.views.generic import CreateView
from store.models import cloud_users
from django.http import HttpResponseRedirect
from django.template import RequestContext
from django.core.context_processors import csrf
from django.core.urlresolvers import reverse_lazy
from ... | (request):
return render_to_response('index.html', context_instance=RequestContext(request))
#def login(request):
# return render_to_response('login.html', context_instance=RequestContext(request))
#def signup(request):
# return render_to_response('signup.html', context_instance=RequestContext(request))
def registe... | home | identifier_name |
docker.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Tests for the Docker JSON parser."""
import unittest
from plaso.lib import definitions
from plaso.parsers import docker
from tests.parsers import test_lib
class DockerJSONUnitTest(test_lib.ParserTestCase):
"""Tests for the Docker JSON parser."""
def testParseC... | (self):
"""Tests the _ParseContainerConfigJSON function."""
container_identifier = (
'e7d0b7ea5ccf08366e2b0c8afa2318674e8aefe802315378125d2bb83fe3110c')
parser = docker.DockerJSONParser()
path_segments = [
'docker', 'containers', container_identifier, 'config.json']
storage_writer =... | testParseContainerConfig | identifier_name |
docker.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Tests for the Docker JSON parser."""
import unittest
from plaso.lib import definitions
from plaso.parsers import docker
from tests.parsers import test_lib
class DockerJSONUnitTest(test_lib.ParserTestCase):
"""Tests for the Docker JSON parser."""
def testParseC... | 'log_source': 'stdout'}
for index, event in enumerate(events):
self.CheckTimestamp(event.timestamp, expected_timestamps[index])
self.CheckEventValues(storage_writer, event, expected_event_values)
def testParseContainerConfig(self):
"""Tests the _ParseContainerConfigJSON function."""
... | '/home/plaso\x07root@e7d0b7ea5ccf:/home/plaso# ls\r\n'), | random_line_split |
docker.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Tests for the Docker JSON parser."""
import unittest
from plaso.lib import definitions
from plaso.parsers import docker
from tests.parsers import test_lib
class DockerJSONUnitTest(test_lib.ParserTestCase):
"""Tests for the Docker JSON parser."""
def testParseC... | unittest.main() | conditional_block | |
docker.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Tests for the Docker JSON parser."""
import unittest
from plaso.lib import definitions
from plaso.parsers import docker
from tests.parsers import test_lib
class DockerJSONUnitTest(test_lib.ParserTestCase):
"""Tests for the Docker JSON parser."""
def testParseC... | 'date_time': '2016-01-07 16:49:08.674873'}
self.CheckEventValues(storage_writer, events[0], expected_event_values)
expected_event_values = {
'action': 'Container Created',
'container_id': container_identifier,
'container_name': 'e7d0b7ea5ccf',
'data_type': 'docker:json:... | """Tests the _ParseContainerConfigJSON function."""
container_identifier = (
'e7d0b7ea5ccf08366e2b0c8afa2318674e8aefe802315378125d2bb83fe3110c')
parser = docker.DockerJSONParser()
path_segments = [
'docker', 'containers', container_identifier, 'config.json']
storage_writer = self._Parse... | identifier_body |
sort.rs | use par_exec::{Executor, WorkAmount, JobIterBuild, ExecutorJobError, JobExecuteError};
use super::{Set, SetManager, merge};
pub trait SortManager {
type S: Set;
type E;
fn sort<SF>(&mut self, set: &mut Self::S, pred: SF) -> Result<(), Self::E> where SF: Fn(usize, usize) -> bool;
}
pub trait RetrieveSortM... | <SE, SME, SRE> {
Set(SE),
SetManager(SME),
Sort(SRE)
}
#[derive(Debug)]
pub enum Error<ExecE, SE, SME, SRE> {
EmptySet,
Executor(ExecutorJobError<ExecE, JobExecuteError<SortError<SE, SME, SRE>, merge::Error<SE, SME>>>),
}
pub fn sort<Exec, LC, S, SetM, SortM, WA, F>(amount: WA, pred: F, exec: &mut... | SortError | identifier_name |
sort.rs | use par_exec::{Executor, WorkAmount, JobIterBuild, ExecutorJobError, JobExecuteError};
use super::{Set, SetManager, merge};
pub trait SortManager {
type S: Set;
type E;
fn sort<SF>(&mut self, set: &mut Self::S, pred: SF) -> Result<(), Self::E> where SF: Fn(usize, usize) -> bool;
}
pub trait RetrieveSortM... | Err(e) => Err(Error::Executor(e)),
}
}
#[cfg(test)]
mod tests {
extern crate rand;
use std::sync::Arc;
use self::rand::Rng;
use super::{RetrieveSortManager, RetrieveSetManager, sort};
use super::super::vec;
use par_exec::{Executor, WorkAmount};
use par_exec::par::{ParallelExecu... | Ok(None) => Err(Error::EmptySet),
Ok(Some(sorted_set)) => Ok(sorted_set), | random_line_split |
index.d.ts | // Type definitions for node-canvas-text 1.0
// Project: https://github.com/kaivi/node-canvas-text#readme
// Definitions by: Gabriel Fournier <https://github.com/carboneater>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
import { Font } from "opentype.js";
export interface DrawOptions {
drawR... | textPadding: number;
vAlign: "bottom"|"center"|"top";
}
export interface DrawRectangle {
height: number;
width: number;
x: number;
y: number;
}
export default function drawText(ctx: CanvasRenderingContext2D, text: string, font: Font, rect?: DrawRectangle, options?: Partial<DrawOptions>): void; | textFillStyle: string; | random_line_split |
fields.py | # This file is part of django-ca (https://github.com/mathiasertl/django-ca).
#
# django-ca is free software: you can redistribute it and/or modify it under the terms of the GNU
# General Public License as published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version... |
try:
return x509.load_pem_x509_csr(value.encode("utf-8"))
except ValueError as ex:
raise forms.ValidationError(ex) from ex
class SubjectField(forms.MultiValueField):
"""A MultiValue field for a :py:class:`~django_ca.subject.Subject`."""
required_oids = (NameOID.COMMON... | raise forms.ValidationError(mark_safe(self.simple_validation_error)) | conditional_block |
fields.py | # This file is part of django-ca (https://github.com/mathiasertl/django-ca).
#
# django-ca is free software: you can redistribute it and/or modify it under the terms of the GNU
# General Public License as published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version... | class CertificateSigningRequestField(forms.CharField):
"""A form field for `~cg:cryptography.x509.CertificateSigningRequest` encoded as PEM."""
start = "-----BEGIN CERTIFICATE REQUEST-----"
end = "-----END CERTIFICATE REQUEST-----"
simple_validation_error = _(
"Could not parse PEM-encoded CSR. ... | if typing.TYPE_CHECKING:
from .modelfields import LazyCertificateSigningRequest
| random_line_split |
fields.py | # This file is part of django-ca (https://github.com/mathiasertl/django-ca).
#
# django-ca is free software: you can redistribute it and/or modify it under the terms of the GNU
# General Public License as published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version... | (self, value: str) -> x509.CertificateSigningRequest: # type: ignore[override]
"""Coerce given str to correct data type, raises ValidationError if not possible.
This function is called during form validation.
"""
if not value.startswith(self.start) or not value.strip().endswith(self.en... | to_python | identifier_name |
fields.py | # This file is part of django-ca (https://github.com/mathiasertl/django-ca).
#
# django-ca is free software: you can redistribute it and/or modify it under the terms of the GNU
# General Public License as published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version... | super().__init__(**kwargs)
self.widget.attrs.update({"cols": "64"})
def prepare_value(
self, value: typing.Optional[typing.Union[str, "LazyCertificateSigningRequest"]]
) -> str:
"""Prepare a value to a form that can be shown in HTML.
Unfortunately this function is not d... | """A form field for `~cg:cryptography.x509.CertificateSigningRequest` encoded as PEM."""
start = "-----BEGIN CERTIFICATE REQUEST-----"
end = "-----END CERTIFICATE REQUEST-----"
simple_validation_error = _(
"Could not parse PEM-encoded CSR. They usually look like this: <pre>%(start)s\n...\n%(end)s</... | identifier_body |
parser.js | // Copyright 2011 Traceur Authors.
//
// 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 ... |
test('Module', function() {
var program = 'export var x = 42;\n' +
'import * as M from \'url\';\n' +
'import {z} from \'x\';\n' +
'import {a as b, c} from \'M\';\n';
var sourceFile = new traceur.syntax.SourceFile('Name', program);
var parser = new tra... | traceur.options.reset();
}); | random_line_split |
simd-generics.rs | // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | (f32, f32, f32, f32);
fn add<T: ops::Add<Output=T>>(lhs: T, rhs: T) -> T {
lhs + rhs
}
impl ops::Add for f32x4 {
type Output = f32x4;
fn add(self, rhs: f32x4) -> f32x4 {
self + rhs
}
}
pub fn main() {
let lr = f32x4(1.0f32, 2.0f32, 3.0f32, 4.0f32);
// lame-o
let f32x4(x, y, z, w... | f32x4 | identifier_name |
simd-generics.rs | // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
// | // except according to those terms.
#![feature(simd)]
use std::ops;
#[simd]
#[derive(Copy, Clone)]
struct f32x4(f32, f32, f32, f32);
fn add<T: ops::Add<Output=T>>(lhs: T, rhs: T) -> T {
lhs + rhs
}
impl ops::Add for f32x4 {
type Output = f32x4;
fn add(self, rhs: f32x4) -> f32x4 {
self + rhs
... | // 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 | random_line_split |
simd-generics.rs | // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... |
impl ops::Add for f32x4 {
type Output = f32x4;
fn add(self, rhs: f32x4) -> f32x4 {
self + rhs
}
}
pub fn main() {
let lr = f32x4(1.0f32, 2.0f32, 3.0f32, 4.0f32);
// lame-o
let f32x4(x, y, z, w) = add(lr, lr);
assert_eq!(x, 2.0f32);
assert_eq!(y, 4.0f32);
assert_eq!(z, 6.... | {
lhs + rhs
} | identifier_body |
finally.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | impl<'a,A> Drop for Finallyalizer<'a,A> {
#[inline]
fn drop(&mut self) {
(self.dtor)(self.mutate);
}
}
#[test]
fn test_success() {
let mut i = 0;
try_finally(
&mut i, (),
|i, ()| {
*i = 10;
},
|i| {
assert!(!failing());
ass... | #[unsafe_destructor] | random_line_split |
finally.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () {
let closure: || -> int = || 10;
let i = closure.finally(|| { });
assert_eq!(i, 10);
}
#[test]
fn test_compact() {
fn do_some_fallible_work() {}
fn but_always_run_this_function() { }
do_some_fallible_work.finally(
but_always_run_this_function);
}
| test_retval | identifier_name |
finally.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
#[test]
#[should_fail]
fn test_fail() {
let mut i = 0;
try_finally(
&mut i, (),
|i, ()| {
*i = 10;
fail!();
},
|i| {
assert!(failing());
assert_eq!(*i, 10);
})
}
#[test]
fn test_retval() {
let closure: || -> int = || ... | {
let mut i = 0;
try_finally(
&mut i, (),
|i, ()| {
*i = 10;
},
|i| {
assert!(!failing());
assert_eq!(*i, 10);
*i = 20;
});
assert_eq!(i, 20);
} | identifier_body |
main.rs | ::interrupt::*;
use schemes::memory::*;
use schemes::test::*;
use syscall::execute::execute;
use syscall::handle::*; | /// Common std-like functionality
#[macro_use]
pub mod common;
#[macro_use]
pub mod macros;
/// Allocation
pub mod alloc_system;
/// ACPI
pub mod acpi;
/// Disk drivers
pub mod disk;
/// Various drivers
pub mod drivers;
/// Environment
pub mod env;
/// Filesystems
pub mod fs;
/// Various graphical methods
pub mod graph... |
pub use system::externs::*;
| random_line_split |
main.rs | ::interrupt::*;
use schemes::memory::*;
use schemes::test::*;
use syscall::execute::execute;
use syscall::handle::*;
pub use system::externs::*;
/// Common std-like functionality
#[macro_use]
pub mod common;
#[macro_use]
pub mod macros;
/// Allocation
pub mod alloc_system;
/// ACPI
pub mod acpi;
/// Disk drivers
pub... | : "intel", "volatile");
} else {
asm!("sti"
:
:
:
: "intel", "volatile");
}
context_switch(false);
}
}
/// Event poll loop
fn poll_loop() {
loop {
env().on_poll();
unsafe { ... | {
loop {
asm!("cli" : : : : "intel", "volatile");
let mut halt = true;
for i in env().contexts.lock().iter().skip(1) {
if i.interrupted {
halt = false;
break;
}
}
if halt {
asm!("sti
hlt... | identifier_body |
main.rs | ::interrupt::*;
use schemes::memory::*;
use schemes::test::*;
use syscall::execute::execute;
use syscall::handle::*;
pub use system::externs::*;
/// Common std-like functionality
#[macro_use]
pub mod common;
#[macro_use]
pub mod macros;
/// Allocation
pub mod alloc_system;
/// ACPI
pub mod acpi;
/// Disk drivers
pub... | () {
{
let mut console = env().console.lock();
console.instant = false;
}
let mut cmd = String::new();
loop {
loop {
let mut console = env().console.lock();
match env().events.lock().pop_front() {
Some(event) => {
if co... | event_loop | identifier_name |
phaselog.py | import numpy as np
import uncertainties.unumpy as unp
from uncertainties.unumpy import (nominal_values as noms, std_devs as stds)
import matplotlib.pyplot as plt
import matplotlib as mpl
from scipy.optimize import curve_fit
plt.rcParams['figure.figsize'] = (12, 8)
plt.rcParams['font.size'] = 13 |
# fre *= 1000
t /= 1e6
phirad = 2 * np.pi * fre * t
plt.plot(fre, phirad, 'rx', label='Messwerte')
# plt.xlim(min(fre), max(fre))
# plt.ylim(min(phirad)-1, max(phirad)+1)
plt.xlabel(r'$\mathrm{\nu} \,/\, \mathrm{Hz}$')
plt.ylabel(r'$\mathrm{\phi} \,/\, \mathrm{rad}$')
plt.xscale('log') # Funktioniert nicht!
# plt.xt... | plt.rcParams['lines.linewidth'] = 1
csfont = {'fontname': 'Times New Roman'}
fre, t = np.genfromtxt('tables/phase.txt', unpack=True, skip_header=2) | random_line_split |
math-utils.ts | /**
* @file Math Utils
* @author Alexander Rose <alexander.rose@weirdbyte.de>
* @private
*/
export function degToRad (deg: number) {
return deg * 0.01745 // deg * Math.PI / 180
}
export function | (rad: number) {
return rad * 57.29578 // rad * 180 / Math.PI
}
// http://www.broofa.com/Tools/Math.uuid.htm
const chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('')
const uuid = new Array(36)
export function generateUUID () {
let rnd = 0
let r
for (let i = 0; i < 36; i++) {
... | radToDeg | identifier_name |
math-utils.ts | /**
* @file Math Utils
* @author Alexander Rose <alexander.rose@weirdbyte.de>
* @private
*/
export function degToRad (deg: number) {
return deg * 0.01745 // deg * Math.PI / 180
}
export function radToDeg (rad: number) {
return rad * 57.29578 // rad * 180 / Math.PI
}
// http://www.broofa.com/Tools/Math.uuid... |
export function smootherstep (min: number, max: number, x: number) {
x = saturate(normalize(x, min, max))
return x * x * x * (x * (x * 6 - 15) + 10)
}
export function smootheststep (min: number, max: number, x: number) {
x = saturate(normalize(x, min, max))
return (
-20 * Math.pow(x, 7) +
70 * Math.p... | export function smoothstep (min: number, max: number, x: number) {
x = saturate(normalize(x, min, max))
return x * x * (3 - 2 * x)
} | random_line_split |
math-utils.ts | /**
* @file Math Utils
* @author Alexander Rose <alexander.rose@weirdbyte.de>
* @private
*/
export function degToRad (deg: number) {
return deg * 0.01745 // deg * Math.PI / 180
}
export function radToDeg (rad: number) {
return rad * 57.29578 // rad * 180 / Math.PI
}
// http://www.broofa.com/Tools/Math.uuid... |
export function saturate (value: number) {
return clamp(value, 0, 1)
}
export function lerp (start: number, stop: number, alpha: number) {
return start + (stop - start) * alpha
}
export function spline (p0: number, p1: number, p2: number, p3: number, t: number, tension: number) {
const v0 = (p2 - p0) * tensio... | {
return clamp(value, 0, 100)
} | identifier_body |
math-utils.ts | /**
* @file Math Utils
* @author Alexander Rose <alexander.rose@weirdbyte.de>
* @private
*/
export function degToRad (deg: number) {
return deg * 0.01745 // deg * Math.PI / 180
}
export function radToDeg (rad: number) {
return rad * 57.29578 // rad * 180 / Math.PI
}
// http://www.broofa.com/Tools/Math.uuid... | else {
if (rnd <= 0x02) rnd = 0x2000000 + (Math.random() * 0x1000000) | 0
r = rnd & 0xf
rnd = rnd >> 4
uuid[ i ] = chars[ (i === 19) ? (r & 0x3) | 0x8 : r ]
}
}
return uuid.join('')
}
export function countSetBits (i: number) {
i = i - ((i >> 1) & 0x55555555)
i = (i & 0x33333333) +... | {
uuid[ i ] = '4'
} | conditional_block |
get_backfill.rs | //! `GET /_matrix/federation/*/backfill/{roomId}`
//!
//! Endpoint to request more history from another homeserver.
pub mod v1 {
//! `/v1/` ([spec])
//!
//! [spec]: https://spec.matrix.org/v1.2/server-server-api/#get_matrixfederationv1backfillroomid
use js_int::UInt;
use ruma_common::{api::ruma_ap... |
}
impl Response {
/// Creates a new `Response` with:
/// * the `server_name` of the homeserver.
/// * the timestamp in milliseconds of when this transaction started.
/// * the list of persistent updates to rooms.
pub fn new(
origin: Box<ServerName>,
... | {
Self { room_id, v, limit }
} | identifier_body |
get_backfill.rs | //! `GET /_matrix/federation/*/backfill/{roomId}`
//!
//! Endpoint to request more history from another homeserver.
pub mod v1 {
//! `/v1/` ([spec])
//!
//! [spec]: https://spec.matrix.org/v1.2/server-server-api/#get_matrixfederationv1backfillroomid
use js_int::UInt;
use ruma_common::{api::ruma_ap... | /// POSIX timestamp in milliseconds on originating homeserver when this transaction started.
pub origin_server_ts: MilliSecondsSinceUnixEpoch,
/// List of persistent updates to rooms.
pub pdus: Vec<Box<RawJsonValue>>,
}
}
impl<'a> Request<'a> {
/... | random_line_split | |
get_backfill.rs | //! `GET /_matrix/federation/*/backfill/{roomId}`
//!
//! Endpoint to request more history from another homeserver.
pub mod v1 {
//! `/v1/` ([spec])
//!
//! [spec]: https://spec.matrix.org/v1.2/server-server-api/#get_matrixfederationv1backfillroomid
use js_int::UInt;
use ruma_common::{api::ruma_ap... | (
origin: Box<ServerName>,
origin_server_ts: MilliSecondsSinceUnixEpoch,
pdus: Vec<Box<RawJsonValue>>,
) -> Self {
Self { origin, origin_server_ts, pdus }
}
}
}
| new | identifier_name |
directory_storage_test.py | #!/usr/bin/python2
# Copyright (c) 2012 The Native Client Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Tests of directory storage adapter."""
import os
import unittest
import directory_storage
import fake_storage
import gsd_sto... | unittest.main() | conditional_block | |
directory_storage_test.py | #!/usr/bin/python2
# Copyright (c) 2012 The Native Client Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Tests of directory storage adapter."""
import os
import unittest
import directory_storage
import fake_storage
import gsd_sto... |
storage = gsd_storage.GSDStorage(
gsutil=['mygsutil'],
write_bucket='mybucket',
read_buckets=[],
call=call)
dir_storage = directory_storage.DirectoryStorageAdapter(storage)
# Check that storage exceptions come thru on failure.
with working_directory.TemporaryWorkingDirec... | return 1 | identifier_body |
directory_storage_test.py | #!/usr/bin/python2
# Copyright (c) 2012 The Native Client Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Tests of directory storage adapter."""
import os
import unittest
import directory_storage
import fake_storage
import gsd_sto... | write_bucket='mybucket',
read_buckets=[],
call=call)
dir_storage = directory_storage.DirectoryStorageAdapter(storage)
# Check that storage exceptions come thru on failure.
with working_directory.TemporaryWorkingDirectory() as work_dir:
temp1 = os.path.join(work_dir, 'temp1')
... | storage = gsd_storage.GSDStorage(
gsutil=['mygsutil'], | random_line_split |
directory_storage_test.py | #!/usr/bin/python2
# Copyright (c) 2012 The Native Client Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Tests of directory storage adapter."""
import os
import unittest
import directory_storage
import fake_storage
import gsd_sto... | (self):
# Check that PutDirectory doesn't alter its inputs.
with working_directory.TemporaryWorkingDirectory() as work_dir:
temp1 = os.path.join(work_dir, 'temp1')
hashing_tools_test.GenerateTestTree('input_untouched', temp1)
h1 = hashing_tools.StableHashPath(temp1)
self._dir_storage.Put... | test_InputUntouched | identifier_name |
settings.py | """
Django settings for finders_keepers project.
Generated by 'django-admin startproject' using Django 1.8.4.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""
# Bu... | 'django.middleware.security.SecurityMiddleware',
)
ROOT_URLCONF = 'finders_keepers.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template... | 'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware', | random_line_split |
raw.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | {
pub data: *mut (),
pub vtable: *mut (),
}
impl Copy for TraitObject {}
/// This trait is meant to map equivalences between raw structs and their
/// corresponding rust values.
pub trait Repr<T> for Sized? {
/// This function "unwraps" a rust value (without consuming it) into its raw
/// struct repr... | TraitObject | identifier_name |
raw.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | pub env: *mut (),
}
impl Copy for Closure {}
/// The representation of a Rust procedure (`proc()`)
#[repr(C)]
pub struct Procedure {
pub code: *mut (),
pub env: *mut (),
}
impl Copy for Procedure {}
/// The representation of a Rust trait object.
///
/// This struct does not have a `Repr` implementation
... | random_line_split | |
EditorFeatures.tsx | export class EditorFeatures {
editor: ChartEditor
constructor(editor: ChartEditor) {
this.editor = editor
}
@computed get chart() {
return this.editor.chart
}
@computed get customYAxisScale() {
return !this.chart.isStackedArea && !this.chart.isDiscreteBar && !this.chart... | import { computed } from 'mobx'
import { ChartEditor } from './ChartEditor'
// Responsible for determining what parts of the editor should be shown, based on the
// type of chart being edited | random_line_split | |
EditorFeatures.tsx | import { computed } from 'mobx'
import { ChartEditor } from './ChartEditor'
// Responsible for determining what parts of the editor should be shown, based on the
// type of chart being edited
export class EditorFeatures {
editor: ChartEditor
constructor(editor: ChartEditor) {
this.editor = editor
}... | () {
return this.customXAxisScale || this.customXAxisLabel
}
@computed get timeDomain() { return !this.chart.isDiscreteBar }
@computed get hideLegend() {
return this.chart.isLineChart || this.chart.isStackedArea
}
@computed get stackedArea() {
return this.chart.isStackedAr... | customXAxis | identifier_name |
EditorFeatures.tsx | import { computed } from 'mobx'
import { ChartEditor } from './ChartEditor'
// Responsible for determining what parts of the editor should be shown, based on the
// type of chart being edited
export class EditorFeatures {
editor: ChartEditor
constructor(editor: ChartEditor) {
this.editor = editor
}... |
@computed get timeDomain() { return !this.chart.isDiscreteBar }
@computed get hideLegend() {
return this.chart.isLineChart || this.chart.isStackedArea
}
@computed get stackedArea() {
return this.chart.isStackedArea
}
@computed get entityType() {
return (!this.chart.i... | {
return this.customXAxisScale || this.customXAxisLabel
} | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.