file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
app.module.ts | import { NgModule, ApplicationRef } from '@angular/core';
import { AppComponent } from './app.component';
import { removeNgStyles, createNewHosts } from '@angularclass/hmr';
import { BrowserModule } from '@angular/platform-browser';
import { CommonModule } from '@angular/common';
import { J3ComponentsModule } from '..... | (private appRef: ApplicationRef) { }
hmrOnDestroy(store) {
const cmpLocation = this.appRef.components.map(cmp => cmp.location.nativeElement);
store.disposeOldHosts = createNewHosts(cmpLocation);
removeNgStyles();
}
hmrAfterDestroy(store) {
store.disposeOldHosts();
delete store.disposeOldHost... | constructor | identifier_name |
app.module.ts | import { NgModule, ApplicationRef } from '@angular/core';
import { AppComponent } from './app.component';
import { removeNgStyles, createNewHosts } from '@angularclass/hmr';
import { BrowserModule } from '@angular/platform-browser'; | import { J3ComponentsModule } from '../src';
import { AccordionDemoComponent } from './components/accordion.component';
@NgModule({
imports: [
CommonModule,
BrowserModule,
J3ComponentsModule
],
declarations: [
AppComponent,
AccordionDemoComponent
],
bootstrap: [AppComponent]
})
export cla... | import { CommonModule } from '@angular/common'; | random_line_split |
newExperiment.py | # -*- coding: utf-8 -*-
"""
@author: Jeff Cavner
@contact: jcavner@ku.edu
@license: gpl2
@copyright: Copyright (C) 2014, University of Kansas Center for Research
Lifemapper Project, lifemapper [at] ku [dot] edu,
Biodiversity Institute,
1345 Jayhawk Boulevard, Lawrence, Kansas, 66045, US... | project path associated with that id. If there is a project path, it
triggers a save project. If there is no path, it asks a save as, and sets
the project path for the id. The last thing it does is to open a new
qgis project
"""
s = QSettings()
currentExpId = s.value("... |
def checkExperiments(self):
"""
@summary: gets the current expId, if there is one it gets the current | random_line_split |
newExperiment.py | # -*- coding: utf-8 -*-
"""
@author: Jeff Cavner
@contact: jcavner@ku.edu
@license: gpl2
@copyright: Copyright (C) 2014, University of Kansas Center for Research
Lifemapper Project, lifemapper [at] ku [dot] edu,
Biodiversity Institute,
1345 Jayhawk Boulevard, Lawrence, Kansas, 66045, US... |
elif buttonValue == "Empty":
pass
elif buttonValue == "ListBuckets":
d = ListBucketsDialog(self.interface, inputs=inputs,
client= self.client, epsg=self.expEPSG,
mapunits=self.mapunits... | d = UploadDialog(self.interface,
inputs = inputs,
client = self.client,
epsg=self.expEPSG,
experimentname=experimentname,
mapunits=self.mapunits)
d.exec_()
self... | conditional_block |
newExperiment.py | # -*- coding: utf-8 -*-
"""
@author: Jeff Cavner
@contact: jcavner@ku.edu
@license: gpl2
@copyright: Copyright (C) 2014, University of Kansas Center for Research
Lifemapper Project, lifemapper [at] ku [dot] edu,
Biodiversity Institute,
1345 Jayhawk Boulevard, Lawrence, Kansas, 66045, US... | (self,buttonValue):
inputs = {'expId':self.expId}
experimentname = self.keyvalues['name']
if buttonValue == "Grid":
self.constructGridDialog = ConstructGridDialog( self.interface,
inputs = inputs,
... | openNewDialog | identifier_name |
newExperiment.py | # -*- coding: utf-8 -*-
"""
@author: Jeff Cavner
@contact: jcavner@ku.edu
@license: gpl2
@copyright: Copyright (C) 2014, University of Kansas Center for Research
Lifemapper Project, lifemapper [at] ku [dot] edu,
Biodiversity Institute,
1345 Jayhawk Boulevard, Lawrence, Kansas, 66045, US... |
# ..............................................................................
def validate(self):
valid = True
message = ""
self.keyvalues['epsgCode'] = self.epsgEdit.text()
self.keyvalues['name'] = self.expNameEdit.text()
self.keyvalues['description'] = self.desc... | valid = self.validate()
if self.expId is not None:
self.openNewDialog(buttonValue)
elif valid and self.expId is None:
try:
print self.keyvalues
exp = self.client.rad.postExperiment(**self.keyvalues)
except Exception, e:
message = "E... | identifier_body |
vdom-my.js | export function Fragment(props, ...children) {
return collect(children);
}
const ATTR_PROPS = '_props';
function collect(children) {
const ch = [];
const push = (c) => {
if (c !== null && c !== undefined && c !== '' && c !== false) {
ch.push((typeof c === 'function' || typeof c === 'obje... | (oldProps, newProps) {
newProps['class'] = newProps['class'] || newProps['className'];
delete newProps['className'];
const props = {};
if (oldProps)
Object.keys(oldProps).forEach(p => props[p] = null);
if (newProps)
Object.keys(newProps).forEach(p => props[p] = newProps[p]);
retu... | mergeProps | identifier_name |
vdom-my.js | export function Fragment(props, ...children) {
return collect(children);
}
const ATTR_PROPS = '_props';
function collect(children) |
export function createElement(tag, props, ...children) {
const ch = collect(children);
if (typeof tag === 'string')
return { tag, props, children: ch };
else if (Array.isArray(tag))
return tag; // JSX fragments - babel
else if (tag === undefined && children)
return ch; // JSX fr... | {
const ch = [];
const push = (c) => {
if (c !== null && c !== undefined && c !== '' && c !== false) {
ch.push((typeof c === 'function' || typeof c === 'object') ? c : `${c}`);
}
};
children && children.forEach(c => {
if (Array.isArray(c)) {
c.forEach(i =>... | identifier_body |
vdom-my.js | export function Fragment(props, ...children) {
return collect(children);
}
const ATTR_PROPS = '_props';
function collect(children) {
const ch = [];
const push = (c) => {
if (c !== null && c !== undefined && c !== '' && c !== false) {
ch.push((typeof c === 'function' || typeof c === 'obje... | }
}
else if (name.startsWith('xlink')) {
const xname = name.replace('xlink', '').toLowerCase();
if (value == null || value === false) {
element.removeAttributeNS('http://www.w3.org/1999/xlink', xname);
}
else {
e... | random_line_split | |
compress.rs | extern crate env_logger;
extern crate handlebars_iron as hbs;
extern crate iron;
extern crate router;
extern crate serde;
extern crate serde_json;
#[macro_use]
extern crate serde_derive;
#[macro_use]
extern crate maplit;
extern crate flate2;
use hbs::handlebars::{Context, Handlebars, Helper, Output, RenderContext, Ren... |
hbse.handlebars_mut().register_helper(
"some_helper",
Box::new(
|_: &Helper,
_: &Handlebars,
_: &Context,
_: &mut RenderContext,
_: &mut dyn Output|
-> Result<(), RenderError> { Ok(()) },
),
);
let mut ro... | {
panic!("{}", r);
} | conditional_block |
compress.rs | extern crate env_logger;
extern crate handlebars_iron as hbs;
extern crate iron;
extern crate router;
extern crate serde;
extern crate serde_json;
#[macro_use]
extern crate serde_derive;
#[macro_use]
extern crate maplit;
extern crate flate2;
use hbs::handlebars::{Context, Handlebars, Helper, Output, RenderContext, Ren... |
}
use data::*;
/// the handlers
fn index(_: &mut Request) -> IronResult<Response> {
let mut resp = Response::new();
let data = make_data();
resp.set_mut(Template::new("some/path/hello", data))
.set_mut(status::Ok);
Ok(resp)
}
fn memory(_: &mut Request) -> IronResult<Response> {
let mut r... | {
let mut data = Map::new();
data.insert("year".to_string(), to_json(&"2015".to_owned()));
let teams = vec![
Team {
name: "Jiangsu Sainty".to_string(),
pts: 43u16,
},
Team {
name: "Beijing Guoan".to_string(),
... | identifier_body |
compress.rs | extern crate env_logger;
extern crate handlebars_iron as hbs;
extern crate iron;
extern crate router;
extern crate serde;
extern crate serde_json;
#[macro_use]
extern crate serde_derive;
#[macro_use]
extern crate maplit;
extern crate flate2;
use hbs::handlebars::{Context, Handlebars, Helper, Output, RenderContext, Ren... | // an example compression middleware
pub struct GzMiddleware;
impl AfterMiddleware for GzMiddleware {
fn after(&self, _: &mut Request, mut resp: Response) -> IronResult<Response> {
let compressed_bytes = resp.body.as_mut().map(|b| {
let mut encoder = GzEncoder::new(Vec::new(), Compression::Best... | random_line_split | |
compress.rs | extern crate env_logger;
extern crate handlebars_iron as hbs;
extern crate iron;
extern crate router;
extern crate serde;
extern crate serde_json;
#[macro_use]
extern crate serde_derive;
#[macro_use]
extern crate maplit;
extern crate flate2;
use hbs::handlebars::{Context, Handlebars, Helper, Output, RenderContext, Ren... | (_: &mut Request) -> IronResult<Response> {
let mut resp = Response::new();
let data = make_data();
resp.set_mut(Template::with(
include_str!("templates/some/path/hello.hbs"),
data,
))
.set_mut(status::Ok);
Ok(resp)
}
fn plain(_: &mut Request) -> IronResult<Response> {
Ok(Re... | temp | identifier_name |
cedar.js | 'use strict';
/**
* Cedar
*
* Generic charting / visualization library for the ArcGIS Platform
* that leverages vega + d3 internally.
*/
/**
* Constructor
* @param {object} options Cedar options
*/
var Cedar = function Cedar(options){
//close over this for use in callbacks
var self = this;
//ensure an ... | else if(typeof opts.specification === 'string' ){
//assume it's a url (relative or abs) and fetch the template object
this._pendingXhr = true;
Cedar.getJson(opts.specification, function(err,data){
self._pendingXhr = false;
self._definition.specification = data;
self._purgeMet... | {
//hold onto the template
this._definition.specification = opts.specification;
} | conditional_block |
cedar.js | 'use strict';
/**
* Cedar
*
* Generic charting / visualization library for the ArcGIS Platform
* that leverages vega + d3 internally.
*/
/**
* Constructor
* @param {object} options Cedar options
*/
var Cedar = function Cedar(options){
//close over this for use in callbacks
var self = this;
//ensure an ... | }
}
if(opts.override) {
this._definition.override = opts.override;
}
//template
if(opts.specification){
//is it an object or string(assumed to be url)
if(typeof opts.specification === 'object'){
//hold onto the template
this._definition.specification = opts.specification;
}e... | self._definition = data;
self._purgeMethodQueue();
});
}else{
throw new Error('parameter definition must be an object or string (url)'); | random_line_split |
plot_label_foci.py | """
=======================
Generate Surface Labels
=======================
Define a label that is centered on a specific vertex in the surface mesh. Plot
that label and the focus that defines its center.
"""
print __doc__
from surfer import Brain, utils
subject_id = "fsaverage"
"""
Bring up the visualization.
"""... | Set the camera position to show the extent of the labels.
"""
brain.show_view(dict(elevation=40, distance=430)) | random_line_split | |
hero-search.component.ts | import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';
// Observable class extensions
import 'rxjs/add/observable/of';
// Observable operators | @Component({
selector: 'hero-search',
templateUrl: './hero-search.component.html',
styleUrls: [ './hero-search.component.css' ],
providers: [HeroSearchService]
})
export class HeroSearchComponent implements OnInit {
heroes: Observable<Hero[]>;
private searchTerms = new Subject<string>();
constructor(
... | import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/debounceTime';
import 'rxjs/add/operator/distinctUntilChanged';
import { HeroSearchService } from './hero-search.service';
import { Hero } from './hero'; | random_line_split |
hero-search.component.ts | import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';
// Observable class extensions
import 'rxjs/add/observable/of';
// Observable operators
import 'rxjs/add/operator... | (term: string): void {
this.searchTerms.next(term);
}
ngOnInit(): void {
this.heroes = this.searchTerms
.debounceTime(300) // wait 300ms after each keystroke before considering the term
.distinctUntilChanged() // ignore if next search term is same as previous
.switchMap(term => te... | search | identifier_name |
hero-search.component.ts | import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';
// Observable class extensions
import 'rxjs/add/observable/of';
// Observable operators
import 'rxjs/add/operator... |
// Push a search term into the observable stream.
search(term: string): void {
this.searchTerms.next(term);
}
ngOnInit(): void {
this.heroes = this.searchTerms
.debounceTime(300) // wait 300ms after each keystroke before considering the term
.distinctUntilChanged() // ignore if nex... | {} | identifier_body |
conftest.py | #! /usr/bin/python
# -*- coding: UTF-8 -*-
# Copyright 2018-2019 Luiko Czub, TestLink-API-Python-client developers
#
# 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.ap... |
@pytest.fixture(scope='session')
def api_client(api_client_class, api_helper_class):
''' Init Testlink API Client class defined in fixtures api_client_class with
connection parameters defined in environment variables
TESTLINK_API_PYTHON_DEVKEY and TESTLINK_API_PYTHON_DEVKEY
Tests ... | ''' all variations of Testlink API Client classes '''
return request.param | identifier_body |
conftest.py | #! /usr/bin/python
# -*- coding: UTF-8 -*-
# Copyright 2018-2019 Luiko Czub, TestLink-API-Python-client developers
#
# 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.ap... | def api_client_class(request):
''' all variations of Testlink API Client classes '''
return request.param
@pytest.fixture(scope='session')
def api_client(api_client_class, api_helper_class):
''' Init Testlink API Client class defined in fixtures api_client_class with
connection parameters defined... | @pytest.fixture(scope='session', params=[TestlinkAPIGeneric, TestlinkAPIClient]) | random_line_split |
conftest.py | #! /usr/bin/python
# -*- coding: UTF-8 -*-
# Copyright 2018-2019 Luiko Czub, TestLink-API-Python-client developers
#
# 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.ap... | (api_helper_class):
''' Init TestlinkAPIClient Client with connection parameters defined in
environment variables
TESTLINK_API_PYTHON_DEVKEY and TESTLINK_API_PYTHON_DEVKEY
'''
return api_helper_class().connect(TestlinkAPIClient)
@pytest.fixture(scope='session', params=[TestlinkAPIGeneric,... | api_general_client | identifier_name |
mips.rs | // Copyright 2012-2015 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... | {
return target_strs::t {
module_asm: "".to_string(),
data_layout: match target_os {
abi::OsMacos => {
"E-p:32:32:32\
-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64\
-f32:32:32-f64:64:64\
-v64:64:64-v128:64:128\
-a:... | identifier_body | |
mips.rs | // Copyright 2012-2015 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... |
abi::OsFreebsd | abi::OsDragonfly | abi::OsBitrig | abi::OsOpenbsd => {
"E-p:32:32:32\
-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64\
-f32:32:32-f64:64:64\
-v64:64:64-v128:64:128\
-a:0:64-n32".to_string()
}
},
... | {
"E-p:32:32:32\
-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64\
-f32:32:32-f64:64:64\
-v64:64:64-v128:64:128\
-a:0:64-n32".to_string()
} | conditional_block |
mips.rs | // Copyright 2012-2015 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... | },
target_triple: target_triple,
cc_args: Vec::new(),
};
} | -f32:32:32-f64:64:64\
-v64:64:64-v128:64:128\
-a:0:64-n32".to_string()
} | random_line_split |
mips.rs | // Copyright 2012-2015 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... | (target_triple: String, target_os: abi::Os) -> target_strs::t {
return target_strs::t {
module_asm: "".to_string(),
data_layout: match target_os {
abi::OsMacos => {
"E-p:32:32:32\
-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64\
-f32:32:32-f64:64:6... | get_target_strs | identifier_name |
app.module.ts | import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { BrowserModule } from '@angular/platform-browser';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { RouterModule } from '@angular/router';
import { HttpModule } from '@angular/http';... | ],
providers: [
/**
* The `RouterStateSnapshot` provided by the `Router` is a large complex structure.
* A custom RouterStateSerializer is used to parse the `RouterStateSnapshot` provided
* by `@ngrx/router-store` to include only the desired pieces of the snapshot.
*/
{ provide: RouterSt... | random_line_split | |
app.module.ts | import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { BrowserModule } from '@angular/platform-browser';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { RouterModule } from '@angular/router';
import { HttpModule } from '@angular/http';... | {}
| AppModule | identifier_name |
inferno-server.js | /*!
* inferno-server vundefined
* (c) 2016 Dominic Gannaway
* Released under the MPL-2.0 License.
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global.InfernoServer = ... |
return;
}
var value = node.attrs && node.attrs.value;
if (!values[value]) {
return;
}
node.attrs = node.attrs || {};
node.attrs.selected = "selected";
}
/**
* WORK IN PROGRESS
*
* Need to run tests for this one!!
*
* */
function renderMarkupForStyles(styles, component... | {
populateOptions(node.children[i], values);
} | conditional_block |
inferno-server.js | /*!
* inferno-server vundefined
* (c) 2016 Dominic Gannaway
* Released under the MPL-2.0 License.
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global.InfernoServer = ... |
var isArray = (function (x) {
return x.constructor === Array;
})
var isStringOrNumber = (function (x) {
return typeof x === 'string' || typeof x === 'number';
})
var noop = (function () {})
var canUseDOM = !!(typeof window !== 'undefined' &&
// Nwjs doesn't add document as a global in their n... | {
return {
create: function create() {
return html;
}
};
} | identifier_body |
inferno-server.js | * inferno-server vundefined
* (c) 2016 Dominic Gannaway
* Released under the MPL-2.0 License.
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global.InfernoServer = fact... | /*! | random_line_split | |
inferno-server.js | /*!
* inferno-server vundefined
* (c) 2016 Dominic Gannaway
* Released under the MPL-2.0 License.
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global.InfernoServer = ... | (strings) {
var i = 0;
var character = undefined;
while (i <= strings.length) {
character = strings[i];
if (!isNaN(character * 1)) {
return false;
} else {
if (character == character.toUpperCase()) {
return false;
}
if (character === character.toLowerCase()) {
retur... | isValidAttribute | identifier_name |
sksl-constants.ts | // CodeMirror likes mode definitions as maps to bools, but a string of space
// separated words is easier to edit, so we convert our strings into a map here.
function | (str: string) {
const obj: Record<string, boolean> = {};
str.split(' ').forEach((word: string) => { obj[word] = true; });
return obj;
}
// See the design doc for the list of keywords. http://go/shaders.skia.org
export const keywords = words(
'const attribute uniform varying break continue '
+ 'discard retu... | words | identifier_name |
sksl-constants.ts | // CodeMirror likes mode definitions as maps to bools, but a string of space
// separated words is easier to edit, so we convert our strings into a map here.
function words(str: string) {
const obj: Record<string, boolean> = {};
str.split(' ').forEach((word: string) => { obj[word] = true; });
return obj;
}
// Se... | export const atoms = words('sk_FragCoord true false');
export const builtins = words(
'radians degrees '
+ 'sin cos tan asin acos atan '
+ 'pow exp log exp2 log2 '
+ 'sqrt inversesqrt '
+ 'abs sign floor ceil fract mod '
+ 'min max clamp saturate '
+ 'mix step smoothstep '
+ 'length distance dot cros... | random_line_split | |
sksl-constants.ts | // CodeMirror likes mode definitions as maps to bools, but a string of space
// separated words is easier to edit, so we convert our strings into a map here.
function words(str: string) |
// See the design doc for the list of keywords. http://go/shaders.skia.org
export const keywords = words(
'const attribute uniform varying break continue '
+ 'discard return for while do if else struct in out inout uniform layout');
export const blockKeywords = words('case do else for if switch while struct en... | {
const obj: Record<string, boolean> = {};
str.split(' ').forEach((word: string) => { obj[word] = true; });
return obj;
} | identifier_body |
handlers.rs | //! Handlers for the server.
use std::collections::BTreeMap;
use rustc_serialize::json::{Json, ToJson};
use iron::prelude::*;
use iron::{status, headers, middleware};
use iron::modifiers::Header;
use router::Router;
use redis::ConnectionInfo;
use urlencoded;
use ::api;
use ::api::optional::Optional;
use ::sensors;
... | // Set headers
.set(Header(headers::ContentType("application/json; charset=utf-8".parse().unwrap())))
.set(Header(headers::CacheControl(vec![headers::CacheDirective::NoCache])))
.set(Header(headers::AccessControlAllowOrigin::Any))
}
}
impl middleware::Handler for Up... | /// Build an error response with the specified `error_code` and the specified `reason` text.
fn err_response(&self, error_code: status::Status, reason: &str) -> Response {
let error = ErrorResponse { reason: reason.to_string() };
Response::with((error_code, error.to_json().to_string())) | random_line_split |
handlers.rs | //! Handlers for the server.
use std::collections::BTreeMap;
use rustc_serialize::json::{Json, ToJson};
use iron::prelude::*;
use iron::{status, headers, middleware};
use iron::modifiers::Header;
use router::Router;
use redis::ConnectionInfo;
use urlencoded;
use ::api;
use ::api::optional::Optional;
use ::sensors;
... | (&self, error_code: status::Status, reason: &str) -> Response {
let error = ErrorResponse { reason: reason.to_string() };
Response::with((error_code, error.to_json().to_string()))
// Set headers
.set(Header(headers::ContentType("application/json; charset=utf-8".parse().unwrap()))... | err_response | identifier_name |
dropdown.js | angular.module('ai.common.directives.dropdown', [])
.directive('aiDropdown', function() {
return {
restrict: 'EA',
require: 'ngModel',
scope: {
ngModel: '=',
list: '='
},
link: function(scope, elem, attrs, ngModel) ... | }, function() {
scope.selected = scope.ngModel;
});
},
template: '<button type="button" class="btn-dropdown full-width" bs-dropdown="data" html="true"> {{selected}} </button>'
};
})
; |
scope.$watch(function () {
return ngModel.$modelValue; | random_line_split |
Utils.py | #!/usr/bin/env python
# Meran - MERAN UNLP is a ILS (Integrated Library System) wich provides Catalog,
# Circulation and User's Management. It's written in Perl, and uses Apache2
# Web-Server, MySQL database and Sphinx 2 indexing.
# Copyright (C) 2009-2013 Grupo de desarrollo de Meran CeSPI-UNLP
#
# This file is part ... |
def locate_error(self):
stack = traceback.extract_stack()
stack.reverse()
for frame in stack:
file_name = os.path.basename(frame[0])
is_wscript = (file_name == WSCRIPT_FILE or file_name == WSCRIPT_BUILD_FILE)
if is_wscript:
return (frame[0], frame[1])
return (None, None)
indicator = is_win32 an... | if wscript_file:
self.wscript_file = wscript_file
self.wscript_line = None
else:
try:
(self.wscript_file, self.wscript_line) = self.locate_error()
except:
(self.wscript_file, self.wscript_line) = (None, None)
msg_file_line = ''
if self.wscript_file:
msg_file_line = "%s:" % self.wscript_fil... | identifier_body |
Utils.py | #!/usr/bin/env python
# Meran - MERAN UNLP is a ILS (Integrated Library System) wich provides Catalog,
# Circulation and User's Management. It's written in Perl, and uses Apache2
# Web-Server, MySQL database and Sphinx 2 indexing.
# Copyright (C) 2009-2013 Grupo de desarrollo de Meran CeSPI-UNLP
#
# This file is part ... |
try:
p = pproc.Popen(cmd, **kw)
output = p.communicate()[0]
except OSError, e:
raise ValueError(str(e))
if p.returncode:
if not silent:
msg = "command execution failed: %s -> %r" % (cmd, str(output))
raise ValueError(msg)
output = ''
return output
reg_subst = re.compile(r"(\\\\)|(\$\$)|\$\{([^}]... | kw['stderr'] = pproc.PIPE | conditional_block |
Utils.py | #!/usr/bin/env python
# Meran - MERAN UNLP is a ILS (Integrated Library System) wich provides Catalog,
# Circulation and User's Management. It's written in Perl, and uses Apache2
# Web-Server, MySQL database and Sphinx 2 indexing.
# Copyright (C) 2009-2013 Grupo de desarrollo de Meran CeSPI-UNLP
#
# This file is part ... | (path):
return (path.strip().find(' ') > 0 and '"%s"' % path or path).replace('""', '"')
def trimquotes(s):
if not s: return ''
s = s.rstrip()
if s[0] == "'" and s[-1] == "'": return s[1:-1]
return s
def h_list(lst):
m = md5()
m.update(str(lst))
return m.digest()
def h_fun(fun):
try:
return fun.code
exce... | quote_whitespace | identifier_name |
Utils.py | #!/usr/bin/env python
# Meran - MERAN UNLP is a ILS (Integrated Library System) wich provides Catalog,
# Circulation and User's Management. It's written in Perl, and uses Apache2
# Web-Server, MySQL database and Sphinx 2 indexing.
# Copyright (C) 2009-2013 Grupo de desarrollo de Meran CeSPI-UNLP
#
# This file is part ... | kw['stdout'] = kw['stderr'] = kw['log']
del(kw['log'])
kw['shell'] = isinstance(s, str)
try:
proc = pproc.Popen(s, **kw)
return proc.wait()
except OSError:
return -1
if is_win32:
def exec_command(s, **kw):
if 'log' in kw:
kw['stdout'] = kw['stderr'] = kw['log']
del(kw['log'])
kw['shell'] = isi... | if key not in self.allkeys: self.allkeys.append(key)
UserDict.__setitem__(self, key, item)
def exec_command(s, **kw):
if 'log' in kw: | random_line_split |
ticker.rs | // Copyright (c) 2015-2017 Ivo Wetzel
| // 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.
// STD Dependencies... | random_line_split | |
ticker.rs | // Copyright (c) 2015-2017 Ivo Wetzel
// 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 accordi... | (&mut self) {
// Actual time taken by the tick
let time_taken = nanos_from_duration(self.tick_start.elapsed());
// Required delay reduction to keep tick rate
let mut reduction = cmp::min(time_taken, self.tick_delay);
if self.tick_overflow_recovery {
// Keep track ... | end_tick | identifier_name |
ticker.rs | // Copyright (c) 2015-2017 Ivo Wetzel
// 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 accordi... |
pub fn set_config(&mut self, config: Config) {
self.tick_overflow_recovery = config.tick_overflow_recovery;
self.tick_overflow_recovery_rate = config.tick_overflow_recovery_rate;
self.tick_delay = 1000000000 / config.send_rate
}
pub fn begin_tick(&mut self) {
self.tick_sta... | {
Ticker {
tick_start: Instant::now(),
tick_overflow: 0,
tick_overflow_recovery: config.tick_overflow_recovery,
tick_overflow_recovery_rate: config.tick_overflow_recovery_rate,
tick_delay: 1000000000 / config.send_rate
}
} | identifier_body |
ticker.rs | // Copyright (c) 2015-2017 Ivo Wetzel
// 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 accordi... |
thread::sleep(Duration::new(0, (self.tick_delay - reduction) as u32));
}
}
// Helpers ---------------------------------------------------------------------
fn nanos_from_duration(d: Duration) -> u64 {
d.as_secs() * 1000 * 1000000 + d.subsec_nanos() as u64
}
| {
// Keep track of how much additional time the current tick required
self.tick_overflow += time_taken - reduction;
// Try to reduce the existing overflow by reducing the reduction time
// for the current frame.
let max_correction = (self.tick_delay - reduct... | conditional_block |
BulletCtrl.ts | const { ccclass, property } = cc._decorator;
import Global from "./Global" | export default class NewClass extends cc.Component {
@property({
default: NaN
})
public speed: number = NaN;
public speedX: number = 0;
public speedY: number = 0;
onLoad() {
// init logic
var manager = cc.director.getCollisionManager();
manager.enabled = true;... |
@ccclass | random_line_split |
BulletCtrl.ts | const { ccclass, property } = cc._decorator;
import Global from "./Global"
@ccclass
export default class NewClass extends cc.Component {
@property({
default: NaN
})
public speed: number = NaN;
public speedX: number = 0;
public speedY: number = 0;
| () {
// init logic
var manager = cc.director.getCollisionManager();
manager.enabled = true;
}
update(dt) {
this.node.x += this.speedX * dt;
this.node.y += this.speedY * dt;
this.checkOffScreen(dt);
}
onCollisionEnter (other, self) {
// this.node... | onLoad | identifier_name |
BulletCtrl.ts | const { ccclass, property } = cc._decorator;
import Global from "./Global"
@ccclass
export default class NewClass extends cc.Component {
@property({
default: NaN
})
public speed: number = NaN;
public speedX: number = 0;
public speedY: number = 0;
onLoad() {
// init logic
... |
}
}
| {
this.node.dispatchEvent(new cc.Event.EventCustom(Global.EventType.BulletOffScreen, true));
} | conditional_block |
zero_out_3_test.py | """Test for version 3 of the zero_out op."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow.python.platform
import tensorflow as tf
from tensorflow.g3doc.how_tos.adding_an_op import gen_zero_out_op_3
class ZeroOut3Test(tf.test.TestCase... | tf.test.main() | conditional_block | |
zero_out_3_test.py | """Test for version 3 of the zero_out op."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow.python.platform
import tensorflow as tf
from tensorflow.g3doc.how_tos.adding_an_op import gen_zero_out_op_3
class ZeroOut3Test(tf.test.TestCase... | tf.test.main() | random_line_split | |
zero_out_3_test.py | """Test for version 3 of the zero_out op."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow.python.platform
import tensorflow as tf
from tensorflow.g3doc.how_tos.adding_an_op import gen_zero_out_op_3
class ZeroOut3Test(tf.test.TestCase... |
def testNegative(self):
with self.test_session():
result = gen_zero_out_op_3.zero_out([5, 4, 3, 2, 1], preserve_index=-1)
with self.assertRaisesOpError("Need preserve_index >= 0, got -1"):
result.eval()
def testLarge(self):
with self.test_session():
result = gen_zero_out_op_3.ze... | with self.test_session():
result = gen_zero_out_op_3.zero_out([5, 4, 3, 2, 1], preserve_index=3)
self.assertAllEqual(result.eval(), [0, 0, 0, 2, 0]) | identifier_body |
zero_out_3_test.py | """Test for version 3 of the zero_out op."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow.python.platform
import tensorflow as tf
from tensorflow.g3doc.how_tos.adding_an_op import gen_zero_out_op_3
class | (tf.test.TestCase):
def test(self):
with self.test_session():
result = gen_zero_out_op_3.zero_out([5, 4, 3, 2, 1])
self.assertAllEqual(result.eval(), [5, 0, 0, 0, 0])
def testAttr(self):
with self.test_session():
result = gen_zero_out_op_3.zero_out([5, 4, 3, 2, 1], preserve_index=3)
... | ZeroOut3Test | identifier_name |
plugin_xmlio_pl.ts | <?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS>
<TS version="2.0" language="pl_PL">
<context>
<name>XmlForms::Internal::XmlFormIO</name>
<message>
<location filename="../../plugins/xmlioplugin/xmlformio.cpp" line="143"/>
<source>Invalid form file detected: %1</source>
<translation t... | </message>
</context>
</TS> | random_line_split | |
cpuid.rs |
use std::str;
use std::slice;
use std::mem;
use byteorder::{LittleEndian, WriteBytesExt};
const VENDOR_INFO: u32 = 0x0;
const FEATURE_INFO: u32 = 0x1;
const EXT_FEATURE_INFO: u32 = 0x7;
const EXT_PROCESSOR_INFO: u32 = 0x80000001;
#[cfg(target_arch = "x86_64")]
pub fn cpuid(func: u32) -> CpuIdInfo {
let (rax, rb... | {
pub highest_func_param: u32,
pub vendor_info: CpuIdInfo,
pub feature_info: CpuIdInfo,
pub ext_feature_info: CpuIdInfo,
pub ext_processor_info: CpuIdInfo
}
impl CpuId {
pub fn detect() -> CpuId {
CpuId {
highest_func_param: cpuid(VENDOR_INFO).rax,
vendor_info:... | CpuId | identifier_name |
cpuid.rs | use std::str;
use std::slice;
use std::mem;
use byteorder::{LittleEndian, WriteBytesExt};
const VENDOR_INFO: u32 = 0x0;
const FEATURE_INFO: u32 = 0x1;
const EXT_FEATURE_INFO: u32 = 0x7;
const EXT_PROCESSOR_INFO: u32 = 0x80000001;
#[cfg(target_arch = "x86_64")]
pub fn cpuid(func: u32) -> CpuIdInfo {
let (rax, rbx... | pub rcx: u32,
pub rdx: u32,
}
pub struct CpuId {
pub highest_func_param: u32,
pub vendor_info: CpuIdInfo,
pub feature_info: CpuIdInfo,
pub ext_feature_info: CpuIdInfo,
pub ext_processor_info: CpuIdInfo
}
impl CpuId {
pub fn detect() -> CpuId {
CpuId {
highest_func_... | random_line_split | |
element_binder.ts | import {AST} from 'angular2/src/change_detection/change_detection';
import {isBlank, isPresent, BaseException} from 'angular2/src/facade/lang';
import * as eiModule from './element_injector';
import {DirectiveBinding} from './element_injector';
import {List, StringMap} from 'angular2/src/facade/collection';
import * as... |
}
hasStaticComponent(): boolean {
return isPresent(this.componentDirective) && isPresent(this.nestedProtoView);
}
hasEmbeddedProtoView(): boolean {
return !isPresent(this.componentDirective) && isPresent(this.nestedProtoView);
}
}
| {
throw new BaseException('null index not allowed.');
} | conditional_block |
element_binder.ts | import {AST} from 'angular2/src/change_detection/change_detection';
import {isBlank, isPresent, BaseException} from 'angular2/src/facade/lang';
import * as eiModule from './element_injector';
import {DirectiveBinding} from './element_injector';
import {List, StringMap} from 'angular2/src/facade/collection';
import * as... | (): boolean {
return !isPresent(this.componentDirective) && isPresent(this.nestedProtoView);
}
}
| hasEmbeddedProtoView | identifier_name |
element_binder.ts | import {AST} from 'angular2/src/change_detection/change_detection';
import {isBlank, isPresent, BaseException} from 'angular2/src/facade/lang';
import * as eiModule from './element_injector';
import {DirectiveBinding} from './element_injector';
import {List, StringMap} from 'angular2/src/facade/collection';
import * as... |
hasStaticComponent(): boolean {
return isPresent(this.componentDirective) && isPresent(this.nestedProtoView);
}
hasEmbeddedProtoView(): boolean {
return !isPresent(this.componentDirective) && isPresent(this.nestedProtoView);
}
}
| {
if (isBlank(index)) {
throw new BaseException('null index not allowed.');
}
} | identifier_body |
element_binder.ts | import {AST} from 'angular2/src/change_detection/change_detection';
import {isBlank, isPresent, BaseException} from 'angular2/src/facade/lang';
import * as eiModule from './element_injector';
import {DirectiveBinding} from './element_injector';
import {List, StringMap} from 'angular2/src/facade/collection';
import * as... | return isPresent(this.componentDirective) && isPresent(this.nestedProtoView);
}
hasEmbeddedProtoView(): boolean {
return !isPresent(this.componentDirective) && isPresent(this.nestedProtoView);
}
} | }
}
hasStaticComponent(): boolean { | random_line_split |
accessible_views_view.js | (function() {
define(function() {
var AccessibleViewItemView, AccessibleViewsView;
AccessibleViewItemView = Backbone.View.extend({
tagName: 'div',
events: {
"click": "clicked",
"mouseover": "mousedover",
"mouseout": "mousedout"
},
render: function() {
t... | return this.model.trigger('accessible-selected', this.model);
}
});
AccessibleViewsView = Backbone.View.extend({
el: $('#accessible-views'),
initialize: function() {
this.collection = new Backbone.Collection;
return this.collection.on('reset', _.bind(this.render, this))... | },
clicked: function() { | random_line_split |
completer.rs | use rustyline;
use rustyline::line_buffer::LineBuffer;
pub struct CustomCompletion {
commands: Vec<&'static str>,
hinter: rustyline::hint::HistoryHinter,
}
impl CustomCompletion {
pub fn new() -> Self {
let commands: Vec<&str> = vec!["help", "items", "projs", "quit"];
Self {
... |
}
Ok((pos, completions))
}
fn update(&self, line: &mut LineBuffer, start: usize, elected: &str) {
line.update(elected, start);
}
}
impl rustyline::hint::Hinter for CustomCompletion {
type Hint = String;
fn hint(&self, line: &str, pos: usize, ctx: &rustyline... | {
completions.push(command.to_string());
} | conditional_block |
completer.rs | use rustyline;
use rustyline::line_buffer::LineBuffer;
pub struct CustomCompletion {
commands: Vec<&'static str>,
hinter: rustyline::hint::HistoryHinter,
}
impl CustomCompletion {
pub fn new() -> Self {
| hinter: rustyline::hint::HistoryHinter {},
}
}
}
impl rustyline::completion::Completer for CustomCompletion {
type Candidate = String;
fn complete(
&self,
line: &str,
pos: usize,
_ctx: &rustyline::Context<'_>,
) -> rustyline::Result<(usi... | let commands: Vec<&str> = vec!["help", "items", "projs", "quit"];
Self {
commands,
| random_line_split |
completer.rs | use rustyline;
use rustyline::line_buffer::LineBuffer;
pub struct CustomCompletion {
commands: Vec<&'static str>,
hinter: rustyline::hint::HistoryHinter,
}
impl CustomCompletion {
pub fn new() -> Self {
let commands: Vec<&str> = vec!["help", "items", "projs", "quit"];
Self {
... | () {
// Verify that the completion for h completes to help.
verify_completion("h", "help");
verify_completion("he", "help");
}
#[test]
fn completion_test_projects() {
// Verify that the completion for p completes to projs.
verify_completion("p", "projs");
verify_completion("pro", "pro... | completion_test_help | identifier_name |
completer.rs | use rustyline;
use rustyline::line_buffer::LineBuffer;
pub struct CustomCompletion {
commands: Vec<&'static str>,
hinter: rustyline::hint::HistoryHinter,
}
impl CustomCompletion {
pub fn new() -> Self {
let commands: Vec<&str> = vec!["help", "items", "projs", "quit"];
Self {
... |
#[test]
fn completion_test_projects() {
// Verify that the completion for p completes to projs.
verify_completion("p", "projs");
verify_completion("pro", "projs");
}
| {
// Verify that the completion for h completes to help.
verify_completion("h", "help");
verify_completion("he", "help");
} | identifier_body |
test_models.py | # 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 https://mozilla.org/MPL/2.0/.
from bedrock.mozorg.tests import TestCase
from bedrock.sitemaps.models import NO_LOCALE, SitemapURL
class TestSitemap... | def test_absolute_url(self):
obj = SitemapURL(path="/firefox/", locale="de")
assert obj.get_absolute_url() == "https://www.mozilla.org/de/firefox/"
# none locale
obj = SitemapURL(path="/firefox/", locale=NO_LOCALE)
assert obj.get_absolute_url() == "https://www.mozilla.org/firefox... | identifier_body | |
test_models.py | # 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 https://mozilla.org/MPL/2.0/.
from bedrock.mozorg.tests import TestCase
from bedrock.sitemaps.models import NO_LOCALE, SitemapURL
class TestSitemap... | de_paths = [str(o) for o in SitemapURL.objects.all_for_locale("de")]
# should contain no fr URL and be in alphabetical order
assert de_paths == ["/de/", "/de/about/", "/de/firefox/"]
def test_all_locales(self):
SitemapURL.objects.create(path="/firefox/", locale="de")
Sitemap... | def test_all_for_locale(self):
SitemapURL.objects.create(path="/firefox/", locale="de")
SitemapURL.objects.create(path="/firefox/", locale="fr")
SitemapURL.objects.create(path="/", locale="de")
SitemapURL.objects.create(path="/about/", locale="de") | random_line_split |
test_models.py | # 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 https://mozilla.org/MPL/2.0/.
from bedrock.mozorg.tests import TestCase
from bedrock.sitemaps.models import NO_LOCALE, SitemapURL
class TestSitemap... | (self):
obj = SitemapURL(path="/firefox/", locale="de")
assert obj.get_absolute_url() == "https://www.mozilla.org/de/firefox/"
# none locale
obj = SitemapURL(path="/firefox/", locale=NO_LOCALE)
assert obj.get_absolute_url() == "https://www.mozilla.org/firefox/"
def test_all_... | test_absolute_url | identifier_name |
types.ts | /*
* Copyright 2022 ThoughtWorks, 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 agr... |
remove(envVar: T) {
this.splice(this.indexOf(envVar), 1);
}
toJSON() {
return this.map((envVar) => envVar.toJSON());
}
}
applyMixins(EnvironmentVariables, ValidatableMixin);
export interface EnvironmentEnvironmentVariableJSON extends EnvironmentVariableJSON {
origin: OriginJSON;
}
export class E... | {
return new EnvironmentVariables<T>(...this.filter((envVar) => !envVar.secure()));
} | identifier_body |
types.ts | /*
* Copyright 2022 ThoughtWorks, 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 agr... | this.secure = Stream(secure || false);
this.name = Stream(name);
this.value = Stream(value);
this.encryptedValue = Stream(new EncryptedValue(!_.isEmpty(encryptedValue) ? {cipherText: encryptedValue} : {clearText: value}));
this.validatePresenceOf("name", {condition: () =>... |
constructor(name: string, value?: string, secure?: boolean, encryptedValue?: string) {
super(); | random_line_split |
types.ts | /*
* Copyright 2022 ThoughtWorks, 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 agr... |
}
equals(environmentVariable: EnvironmentVariable): boolean {
return this.name() === environmentVariable.name()
&& this.value() === environmentVariable.value()
&& this.encryptedValue().value() === environmentVariable.encryptedValue().value();
}
}
//tslint:disable-next-line
export interface Envi... | {
return {
name: this.name(),
encrypted_value: this.encryptedValue().value(),
secure: this.secure()
};
} | conditional_block |
types.ts | /*
* Copyright 2022 ThoughtWorks, 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 agr... | extends EnvironmentVariable {
readonly origin: Stream<Origin>;
constructor(name: string, origin: Origin, value?: string, secure?: boolean, encryptedValue?: string) {
super(name, value, secure, encryptedValue);
this.origin = Stream(origin);
}
static fromJSON(data: EnvironmentEnvironmentVariableJSON) {... | EnvironmentVariableWithOrigin | identifier_name |
conference.py | #!/usr/bin/env python
"""
conference.py -- Udacity conference server-side Python App Engine API;
uses Google Cloud Endpoints
$Id: conference.py,v 1.25 2014/05/24 23:42:19 wesc Exp wesc $
created by wesc on 2014 apr 21
"""
__author__ = 'wesc+api@google.com (Wesley Chun)'
from datetime import datetime
import ... | (self, save_request=None):
"""Get user Profile and return to user, possibly updating it first."""
# get user Profile
prof = self._getProfileFromUser()
# if saveProfile(), process user-modifyable fields
if save_request:
for field in ('displayName', 'teeShirtSize'):
... | _doProfile | identifier_name |
conference.py | #!/usr/bin/env python
"""
conference.py -- Udacity conference server-side Python App Engine API;
uses Google Cloud Endpoints
$Id: conference.py,v 1.25 2014/05/24 23:42:19 wesc Exp wesc $
created by wesc on 2014 apr 21
"""
__author__ = 'wesc+api@google.com (Wesley Chun)'
from datetime import datetime
import ... |
pf.check_initialized()
return pf
def _getProfileFromUser(self):
"""Return user Profile from datastore, creating new one if non-existent."""
user = endpoints.get_current_user()
if not user:
raise endpoints.UnauthorizedException('Authorization required')
... | if field.name == 'teeShirtSize':
setattr(pf, field.name, getattr(TeeShirtSize, getattr(prof, field.name)))
else:
setattr(pf, field.name, getattr(prof, field.name)) | conditional_block |
conference.py | #!/usr/bin/env python
"""
conference.py -- Udacity conference server-side Python App Engine API;
uses Google Cloud Endpoints
$Id: conference.py,v 1.25 2014/05/24 23:42:19 wesc Exp wesc $
created by wesc on 2014 apr 21 |
"""
__author__ = 'wesc+api@google.com (Wesley Chun)'
from datetime import datetime
import endpoints
from protorpc import messages
from protorpc import message_types
from protorpc import remote
from google.appengine.ext import ndb
from models import Profile
from models import ProfileMiniForm
from models import Pr... | random_line_split | |
conference.py | #!/usr/bin/env python
"""
conference.py -- Udacity conference server-side Python App Engine API;
uses Google Cloud Endpoints
$Id: conference.py,v 1.25 2014/05/24 23:42:19 wesc Exp wesc $
created by wesc on 2014 apr 21
"""
__author__ = 'wesc+api@google.com (Wesley Chun)'
from datetime import datetime
import ... |
@endpoints.method(ProfileMiniForm, ProfileForm,
path='profile', http_method='POST', name='saveProfile')
def saveProfile(self, request):
"""Update & return user profile."""
return self._doProfile(request)
# registers API
api = endpoints.api_server([ConferenceApi])
| """Return user profile."""
return self._doProfile() | identifier_body |
index.d.ts | // Generated by typings
// Source: https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/56295f5058cac7ae458540423c50ac2dcf9fc711/gulp-util/gulp-util.d.ts
// Type definitions for gulp-util v3.0.x
// Project: https://github.com/gulpjs/gulp-util
// Definitions by: jedmao <https://github.com/jedmao>
// Definit... | (now?: Date, mask?: string, convertLocalTimeToUTC?: boolean): any;
(date?: string, mask?: string, convertLocalTimeToUTC?: boolean): any;
masks: any;
};
/**
* Logs stuff. Already prefixed with [gulp] and all that. Use the right colors
* for values. If you pass in multiple arguments it will join them by a spac... |
export var date: { | random_line_split |
index.d.ts | // Generated by typings
// Source: https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/56295f5058cac7ae458540423c50ac2dcf9fc711/gulp-util/gulp-util.d.ts
// Type definitions for gulp-util v3.0.x
// Project: https://github.com/gulpjs/gulp-util
// Definitions by: jedmao <https://github.com/jedmao>
// Definit... | implements Error, PluginErrorOptions {
constructor(options?: PluginErrorOptions);
constructor(pluginName: string, options?: PluginErrorOptions);
constructor(pluginName: string, message: string, options?: PluginErrorOptions);
constructor(pluginName: string, message: Error, options?: PluginErrorOptions);
/**
... | PluginError | identifier_name |
arrayConfigurationTools.py | #!/usr/bin/python
"""
S. Leon @ ALMA
Classes, functions to be used for the array configuration evaluation with CASA
HISTORY:
2011.11.06:
- class to create the Casas pads file from a configuration file
2011.11.09:
- Class to compute statistics on the baselines
2012.03.07L... | if __name__=="__main__":
" main program"
## a=ArrayConfigurationCasaFile()
## a.createCasaConfig("/home/stephane/alma/ArrayConfig/Cycle1/configurations/cycle1_config.txt") |
########################Main program#################################### | random_line_split |
arrayConfigurationTools.py | #!/usr/bin/python
"""
S. Leon @ ALMA
Classes, functions to be used for the array configuration evaluation with CASA
HISTORY:
2011.11.06:
- class to create the Casas pads file from a configuration file
2011.11.09:
- Class to compute statistics on the baselines
2012.03.07L... | (self,visname):
self.visname = visname
########################Main program####################################
if __name__=="__main__":
" main program"
## a=ArrayConfigurationCasaFile()
## a.createCasaConfig("/home/stephane/alma/A... | __init__ | identifier_name |
arrayConfigurationTools.py | #!/usr/bin/python
"""
S. Leon @ ALMA
Classes, functions to be used for the array configuration evaluation with CASA
HISTORY:
2011.11.06:
- class to create the Casas pads file from a configuration file
2011.11.09:
- Class to compute statistics on the baselines
2012.03.07L... |
dump=padFile.readline()
padFile.close()
def createCasaConfig(self,configurationFile,listPads = []):
"""
If listPads is not empty, it will use configurationFile to create the CASA file.
"""
... | padsplt=dump.split()
self.pad[padsplt[4]]=[padsplt[0],padsplt[1],padsplt[2],padsplt[3]] | conditional_block |
arrayConfigurationTools.py | #!/usr/bin/python
"""
S. Leon @ ALMA
Classes, functions to be used for the array configuration evaluation with CASA
HISTORY:
2011.11.06:
- class to create the Casas pads file from a configuration file
2011.11.09:
- Class to compute statistics on the baselines
2012.03.07L... |
def __readPadPosition__(self):
"Read the position of all the Pads and put them in a Dictionary"
padFile=open(self.padPositionFile,"r")
dump=padFile.readline()
while(dump != ""):
if dump[0] !="#":
... | self.padPositionFile = padPositionFile
self.pad={}
self.__readPadPosition__() | identifier_body |
windows.rs |
use std::{io, mem, ptr};
use std::ffi::OsStr;
use std::path::Path;
use std::os::windows::ffi::OsStrExt;
use std::os::windows::io::{AsRawHandle, RawHandle};
use winapi::um::fileapi::{CreateFileW, OPEN_EXISTING};
use winapi::um::memoryapi::{CreateFileMappingW, MapViewOfFile, UnmapViewOfFile, VirtualQuery, FILE_MAP_READ... | (&self) -> &[u8] {
unsafe { &*self.bytes }
}
}
impl Drop for FileMap {
fn drop(&mut self) {
unsafe {
UnmapViewOfFile((*self.bytes).as_ptr() as LPVOID);
CloseHandle(self.handle);
}
}
}
| as_ref | identifier_name |
windows.rs |
use std::{io, mem, ptr};
use std::ffi::OsStr;
use std::path::Path;
use std::os::windows::ffi::OsStrExt;
use std::os::windows::io::{AsRawHandle, RawHandle};
use winapi::um::fileapi::{CreateFileW, OPEN_EXISTING};
use winapi::um::memoryapi::{CreateFileMappingW, MapViewOfFile, UnmapViewOfFile, VirtualQuery, FILE_MAP_READ... |
// Create the memory file mapping
let map = CreateFileMappingW(file, ptr::null_mut(), PAGE_READONLY, 0, 0, ptr::null());
CloseHandle(file);
if map == NULL {
return Err(io::Error::last_os_error());
}
// Map view of the file
let view = MapViewOfFile(map, FILE_MAP_READ, 0, 0, 0);
if view == ptr::null_m... | {
return Err(io::Error::last_os_error());
} | conditional_block |
windows.rs | use std::{io, mem, ptr};
use std::ffi::OsStr;
use std::path::Path;
use std::os::windows::ffi::OsStrExt;
use std::os::windows::io::{AsRawHandle, RawHandle};
use winapi::um::fileapi::{CreateFileW, OPEN_EXISTING};
use winapi::um::memoryapi::{CreateFileMappingW, MapViewOfFile, UnmapViewOfFile, VirtualQuery, FILE_MAP_READ,... | CloseHandle(self.handle);
}
}
}
//----------------------------------------------------------------
/// Memory mapped file.
pub struct FileMap {
handle: HANDLE,
bytes: *mut [u8],
}
impl FileMap {
/// Maps the whole file into memory.
pub fn open<P: AsRef<Path> + ?Sized>(path: &P) -> io::Result<FileMap> {
un... | }
impl Drop for ImageMap {
fn drop(&mut self) {
unsafe {
UnmapViewOfFile((*self.bytes).as_ptr() as LPVOID); | random_line_split |
windows.rs |
use std::{io, mem, ptr};
use std::ffi::OsStr;
use std::path::Path;
use std::os::windows::ffi::OsStrExt;
use std::os::windows::io::{AsRawHandle, RawHandle};
use winapi::um::fileapi::{CreateFileW, OPEN_EXISTING};
use winapi::um::memoryapi::{CreateFileMappingW, MapViewOfFile, UnmapViewOfFile, VirtualQuery, FILE_MAP_READ... |
}
//----------------------------------------------------------------
/// Memory mapped file.
pub struct FileMap {
handle: HANDLE,
bytes: *mut [u8],
}
impl FileMap {
/// Maps the whole file into memory.
pub fn open<P: AsRef<Path> + ?Sized>(path: &P) -> io::Result<FileMap> {
unsafe { Self::_open(path.as_ref()) }... | {
unsafe {
UnmapViewOfFile((*self.bytes).as_ptr() as LPVOID);
CloseHandle(self.handle);
}
} | identifier_body |
Connector.js | OAUTH_PARMS_CLASS = require('../common/OAuthParameters');
PARSE_STRING = require('xml2js').parseString;
var util = require('util');
var namespaceUtil = require('../common/NamespaceUtil');
AMP = '&';
OAUTH_START_STRING = 'OAuth ';
ERROR_STATUS_BOUNDARY = 300;
USER_AGENT = 'MC API OAuth Framework v1.0-node';
CRYPTO = r... |
// CLASS METHODS
/**
* "private method" to generate the signature base string from the URL, request method, and parameters
* @param url - URL to connect to
* @param requestMethod - HTTP request method
* @param oauthParms - parameters containing authorization information
* @returns {string|*} - signature base st... | {
this.consumerKey = consumerKey;
this.privateKey = privateKey;
this.callback = callback;
this.setCallback = function(callback){
this.callback = callback;
};
/**
* Method that service classes should call in order to execute a request against MasterCard's servers
* @param url - URL including que... | identifier_body |
Connector.js | OAUTH_PARMS_CLASS = require('../common/OAuthParameters');
PARSE_STRING = require('xml2js').parseString;
var util = require('util');
var namespaceUtil = require('../common/NamespaceUtil');
AMP = '&';
OAUTH_START_STRING = 'OAuth ';
ERROR_STATUS_BOUNDARY = 300;
USER_AGENT = 'MC API OAuth Framework v1.0-node';
CRYPTO = r... | else {
parm = parm + delim + nameArr[i] + '=' + oauthHash[nameArr[i]];
}
delim = AMP;
}
return parm;
};
_postProcessSignatureBaseString = function(signatureBaseString){
signatureBaseString = signatureBaseString.replace(/%20/g, '%2520');
return signatureBaseString.replace('!','%21');
};
module.... | {
parm = parm + delim + nameArr[i] + '=' + qstringHash[nameArr[i]];
} | conditional_block |
Connector.js | OAUTH_PARMS_CLASS = require('../common/OAuthParameters');
PARSE_STRING = require('xml2js').parseString;
var util = require('util');
var namespaceUtil = require('../common/NamespaceUtil');
AMP = '&';
OAUTH_START_STRING = 'OAuth ';
ERROR_STATUS_BOUNDARY = 300;
USER_AGENT = 'MC API OAuth Framework v1.0-node';
CRYPTO = r... |
function Connector(consumerKey, privateKey, callback){
this.consumerKey = consumerKey;
this.privateKey = privateKey;
this.callback = callback;
this.setCallback = function(callback){
this.callback = callback;
};
/**
* Method that service classes should call in order to execute a request against Ma... | */ | random_line_split |
Connector.js | OAUTH_PARMS_CLASS = require('../common/OAuthParameters');
PARSE_STRING = require('xml2js').parseString;
var util = require('util');
var namespaceUtil = require('../common/NamespaceUtil');
AMP = '&';
OAUTH_START_STRING = 'OAuth ';
ERROR_STATUS_BOUNDARY = 300;
USER_AGENT = 'MC API OAuth Framework v1.0-node';
CRYPTO = r... | (consumerKey, privateKey, callback){
this.consumerKey = consumerKey;
this.privateKey = privateKey;
this.callback = callback;
this.setCallback = function(callback){
this.callback = callback;
};
/**
* Method that service classes should call in order to execute a request against MasterCard's servers
... | Connector | identifier_name |
player_state.rs | use rocket::request::{self, FromRequest};
use rocket::{Request, State, Outcome};
use game_state;
use quest::Quest;
use rocket::http::Cookies;
use thread_safe::Ts;
use battle::Battle;
use enemy::Enemy;
pub struct AcceptedQuest {
quest_id: i32,
enemy_id: i32,
name: String,
enemies_killed: i32,
req_enemies_kill... | (&mut self, quest: &Quest) {
println!("accepting quest {}", quest.id());
self.accepted_quests.push(AcceptedQuest::new(quest))
}
pub fn accepted_quests(&self) -> &Vec<AcceptedQuest> {
&self.accepted_quests
}
pub fn init_battle(&mut self, enemy: Enemy) -> &Battle {
self.current_battle = Some(Bat... | accept_quest | identifier_name |
player_state.rs | use rocket::request::{self, FromRequest};
use rocket::{Request, State, Outcome};
use game_state;
use quest::Quest;
use rocket::http::Cookies;
use thread_safe::Ts;
use battle::Battle;
use enemy::Enemy;
pub struct AcceptedQuest {
quest_id: i32,
enemy_id: i32,
name: String,
enemies_killed: i32,
req_enemies_kill... | return &self.username;
}
pub fn accept_quest(&mut self, quest: &Quest) {
println!("accepting quest {}", quest.id());
self.accepted_quests.push(AcceptedQuest::new(quest))
}
pub fn accepted_quests(&self) -> &Vec<AcceptedQuest> {
&self.accepted_quests
}
pub fn init_battle(&mut self, enemy: E... | PlayerState { username: username, accepted_quests: vec![], current_battle: None }
}
pub fn username(&self) -> &String { | random_line_split |
player_state.rs | use rocket::request::{self, FromRequest};
use rocket::{Request, State, Outcome};
use game_state;
use quest::Quest;
use rocket::http::Cookies;
use thread_safe::Ts;
use battle::Battle;
use enemy::Enemy;
pub struct AcceptedQuest {
quest_id: i32,
enemy_id: i32,
name: String,
enemies_killed: i32,
req_enemies_kill... |
pub fn accept_quest(&mut self, quest: &Quest) {
println!("accepting quest {}", quest.id());
self.accepted_quests.push(AcceptedQuest::new(quest))
}
pub fn accepted_quests(&self) -> &Vec<AcceptedQuest> {
&self.accepted_quests
}
pub fn init_battle(&mut self, enemy: Enemy) -> &Battle {
self.cu... | {
return &self.username;
} | identifier_body |
player_state.rs | use rocket::request::{self, FromRequest};
use rocket::{Request, State, Outcome};
use game_state;
use quest::Quest;
use rocket::http::Cookies;
use thread_safe::Ts;
use battle::Battle;
use enemy::Enemy;
pub struct AcceptedQuest {
quest_id: i32,
enemy_id: i32,
name: String,
enemies_killed: i32,
req_enemies_kill... | else {
BattleState::Fight(self.current_battle.as_ref().unwrap())
}
}
}
pub type TsPlayerState = Ts<PlayerState>;
impl<'a, 'r> FromRequest<'a, 'r> for TsPlayerState {
type Error = ();
fn from_request(request: &'a Request<'r>) -> request::Outcome<TsPlayerState, ()> {
let cookies = request.... | {
let enemy_id = self.current_battle.as_mut().unwrap().enemy.id;
self.on_enemy_killed(enemy_id);
self.current_battle = None;
BattleState::End(BattleReward{})
} | conditional_block |
main.rs | #![feature(plugin, custom_derive)]
#![plugin(rocket_codegen)]
extern crate rocket;
extern crate rocket_contrib;
extern crate uuid;
#[cfg(test)] mod tests;
use std::collections::HashMap;
use std::sync::Mutex;
use rocket::State;
use rocket_contrib::Template;
use rocket::response::{Failure, Redirect};
use rocket::http:... | (pizza_order_form: Form<PizzaOrder>, database: State<PizzaOrderDatabase>) -> Result<Redirect, Failure> {
let pizza_order = pizza_order_form.get();
let pizza_name = &pizza_order.name;
let pizzas: Vec<String> = PIZZAS.iter().map(|p| p.to_string().to_lowercase()).collect();
if pizzas.contains(&pizza_name.to_lo... | order_pizza | identifier_name |
main.rs | #![feature(plugin, custom_derive)]
#![plugin(rocket_codegen)]
extern crate rocket;
extern crate rocket_contrib;
extern crate uuid;
#[cfg(test)] mod tests;
use std::collections::HashMap;
use std::sync::Mutex;
use rocket::State;
use rocket_contrib::Template;
use rocket::response::{Failure, Redirect};
use rocket::http:... | fn show_pizza_ordered(order_id: String, database: State<PizzaOrderDatabase>) -> Result<Template, Failure> {
match Uuid::parse_str(order_id.as_str()) {
Ok(order_id) => {
match database.lock().unwrap().get(&order_id) {
Some(..) => {
let mut context = HashMap::new();
... | Template::render("pizza_menu", &context)
}
#[get("/pizza/order/<order_id>")] | random_line_split |
main.rs | #![feature(plugin, custom_derive)]
#![plugin(rocket_codegen)]
extern crate rocket;
extern crate rocket_contrib;
extern crate uuid;
#[cfg(test)] mod tests;
use std::collections::HashMap;
use std::sync::Mutex;
use rocket::State;
use rocket_contrib::Template;
use rocket::response::{Failure, Redirect};
use rocket::http:... | ,
None => {
println!("Pizza order id not found: {}", &order_id);
Err(Failure(Status::NotFound))
}
}
},
Err(..) => {
println!("Pizza order id not valid: {}", &order_id);
Err(Failure(Status::NotFound))
},
}
}
#[derive(... | {
let mut context = HashMap::new();
context.insert("order_id", order_id);
Ok(Template::render("pizza_ordered", &context))
} | conditional_block |
main.rs | #![feature(plugin, custom_derive)]
#![plugin(rocket_codegen)]
extern crate rocket;
extern crate rocket_contrib;
extern crate uuid;
#[cfg(test)] mod tests;
use std::collections::HashMap;
use std::sync::Mutex;
use rocket::State;
use rocket_contrib::Template;
use rocket::response::{Failure, Redirect};
use rocket::http:... | {
mount_rocket().launch();
} | identifier_body | |
udp-multicast.rs | use std::{env, str};
use std::net::{UdpSocket, Ipv4Addr};
fn | () {
let mcast_group: Ipv4Addr = "239.0.0.1".parse().unwrap();
let port: u16 = 6000;
let any = "0.0.0.0".parse().unwrap();
let mut buffer = [0u8; 1600];
if env::args().count() > 1 {
let socket = UdpSocket::bind((any, port)).expect("Could not bind client socket");
socket.join_... | main | identifier_name |
udp-multicast.rs | use std::{env, str};
use std::net::{UdpSocket, Ipv4Addr}; | let any = "0.0.0.0".parse().unwrap();
let mut buffer = [0u8; 1600];
if env::args().count() > 1 {
let socket = UdpSocket::bind((any, port)).expect("Could not bind client socket");
socket.join_multicast_v4(&mcast_group, &any).expect("Could not join multicast group");
socket... |
fn main() {
let mcast_group: Ipv4Addr = "239.0.0.1".parse().unwrap();
let port: u16 = 6000; | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.