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 |
|---|---|---|---|---|
driver_listener.py | # Copyright 2018 Rackspace, US Inc.
# Copyright 2019 Red Hat, Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unle... | (exit_event):
_cleanup_socket_file(CONF.driver_agent.get_socket_path)
server = ForkingUDSServer(CONF.driver_agent.get_socket_path,
GetRequestHandler)
server.timeout = CONF.driver_agent.get_request_timeout
server.max_children = CONF.driver_agent.get_max_processes
whil... | get_listener | identifier_name |
templateParser.ts | import * as jade from "jade";
import * as pug from "pug";
import {TemplateRootNode} from "../generator/ast";
import {Either} from "monet";
import {
asHtmlContents,
HtmlContents,
PugContents,
PugFileName,
TcatError,
TemplateParserError
} from "../core";
import {parseElement} from "./elements";
im... | const htmlNode = document.childNodes.find((node) => node.nodeName === 'html');
if (!htmlNode) {
return Either.Left([new TemplateParserError(`No HTML node found in parsed document.`)]);
} else {
return parseElement(htmlNode, directives, scopeInterfaceName);
}
} | try {
document = <AST.Default.Document> parseHtmlDocument(html);
} catch (err) {
return Either.Left([new TemplateParserError(err)]);
} | random_line_split |
templateParser.ts | import * as jade from "jade";
import * as pug from "pug";
import {TemplateRootNode} from "../generator/ast";
import {Either} from "monet";
import {
asHtmlContents,
HtmlContents,
PugContents,
PugFileName,
TcatError,
TemplateParserError
} from "../core";
import {parseElement} from "./elements";
im... | else {
html = pug.render(contents, {
filename: templateFileName
});
}
} catch (err) {
return Either.Left([new TemplateParserError(err)]);
}
return Either.Right(asHtmlContents(html));
}
export function parseHtml(html : HtmlContents, scopeInterfaceName... | {
html = jade.render(contents, {
filename: templateFileName
});
} | conditional_block |
templateParser.ts | import * as jade from "jade";
import * as pug from "pug";
import {TemplateRootNode} from "../generator/ast";
import {Either} from "monet";
import {
asHtmlContents,
HtmlContents,
PugContents,
PugFileName,
TcatError,
TemplateParserError
} from "../core";
import {parseElement} from "./elements";
im... |
export function parseHtml(html : HtmlContents, scopeInterfaceName : string, directives : DirectiveMap) : Either<TcatError[], TemplateRootNode> {
let document : AST.Default.Document;
try {
document = <AST.Default.Document> parseHtmlDocument(html);
} catch (err) {
return Either.Left([new Tem... | {
let html;
try {
// In pug files, "include" statements expect a file extension of .pug. You can work around this by explicitly
// including the file extension of .jade, but it still emits a warning message to stdout.
// So, let's just use the legacy module for old ".jade" templates.
... | identifier_body |
templateParser.ts | import * as jade from "jade";
import * as pug from "pug";
import {TemplateRootNode} from "../generator/ast";
import {Either} from "monet";
import {
asHtmlContents,
HtmlContents,
PugContents,
PugFileName,
TcatError,
TemplateParserError
} from "../core";
import {parseElement} from "./elements";
im... | (html : HtmlContents, scopeInterfaceName : string, directives : DirectiveMap) : Either<TcatError[], TemplateRootNode> {
let document : AST.Default.Document;
try {
document = <AST.Default.Document> parseHtmlDocument(html);
} catch (err) {
return Either.Left([new TemplateParserError(err)]);
... | parseHtml | identifier_name |
WrapMode.py | # encoding: utf-8
# module pango
# from /usr/lib/python2.7/dist-packages/gtk-2.0/pango.so
# by generator 1.135
# no doc
# imports
import gobject as __gobject
import gobject._gobject as __gobject__gobject
class WrapMode(__gobject.GEnum):
# no doc
def __init__(self, *args, **kwargs): # real signature unknown
... |
__weakref__ = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""list of weak references to the object (if defined)"""
__dict__ = None # (!) real value is ''
__enum_values__ = {
0: 0,
1: 1,
2: 2,
}
__gtype__ = None # (!) real value ... | pass | identifier_body |
WrapMode.py | # encoding: utf-8
# module pango
# from /usr/lib/python2.7/dist-packages/gtk-2.0/pango.so
# by generator 1.135
# no doc
# imports
import gobject as __gobject
import gobject._gobject as __gobject__gobject | def __init__(self, *args, **kwargs): # real signature unknown
pass
__weakref__ = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""list of weak references to the object (if defined)"""
__dict__ = None # (!) real value is ''
__enum_values__ = {
... |
class WrapMode(__gobject.GEnum):
# no doc | random_line_split |
WrapMode.py | # encoding: utf-8
# module pango
# from /usr/lib/python2.7/dist-packages/gtk-2.0/pango.so
# by generator 1.135
# no doc
# imports
import gobject as __gobject
import gobject._gobject as __gobject__gobject
class | (__gobject.GEnum):
# no doc
def __init__(self, *args, **kwargs): # real signature unknown
pass
__weakref__ = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""list of weak references to the object (if defined)"""
__dict__ = None # (!) real value is ''
... | WrapMode | identifier_name |
rankings.controllers.js | var app = require('../../server');
var request = require('supertest'); | var should = require('should');
var mongoose = require('mongoose');
var User = mongoose.model('User');
var Ranking = mongoose.model('Ranking');
var user, ranking;
describe('Ranking controller unit tests:', function() {
beforeEach(function(done) {
user = new User({
firstName: 'Some',
... | random_line_split | |
Picker.tsx | import React, { CSSProperties } from 'react';
import ReactDOM from 'react-dom';
import { Moment } from 'moment';
import { polyfill } from 'react-lifecycles-compat';
import createChainedFunction from 'rc-util/lib/createChainedFunction';
import KeyCode from 'rc-util/lib/KeyCode';
import Trigger from 'rc-trigger';
import... | extends React.Component<PickerProps, PickerState> {
static defaultProps = {
prefixCls: 'rc-calendar-picker',
style: {},
align: {},
placement: 'bottomLeft',
defaultOpen: false,
onChange: noop,
onOpenChange: noop,
onBlur: noop,
};
saveCalendarRef = refFn.bind(this, 'calendarInstanc... | Picker | identifier_name |
Picker.tsx | import React, { CSSProperties } from 'react';
import ReactDOM from 'react-dom';
import { Moment } from 'moment';
import { polyfill } from 'react-lifecycles-compat';
import createChainedFunction from 'rc-util/lib/createChainedFunction';
import KeyCode from 'rc-util/lib/KeyCode';
import Trigger from 'rc-trigger';
import... |
export interface PickerProps {
animation?: string;
disabled?: boolean;
transitionName?: string;
onChange?: (value: Moment) => void;
onOpenChange?: (open: boolean) => void;
getCalendarContainer?: (ref: HTMLElement) => HTMLElement;
calendar?: JSX.Element;
style?: CSSProperties;
open?: boolean;
defau... | {
this[field] = component;
} | identifier_body |
Picker.tsx | import React, { CSSProperties } from 'react';
import ReactDOM from 'react-dom';
import { Moment } from 'moment';
import { polyfill } from 'react-lifecycles-compat';
import createChainedFunction from 'rc-util/lib/createChainedFunction';
import KeyCode from 'rc-util/lib/KeyCode';
import Trigger from 'rc-trigger';
import... |
const value = props.value || props.defaultValue;
this.state = {
open,
value,
};
}
focusTimeout: number | any;
componentDidUpdate(_, prevState) {
if (!prevState.open && this.state.open) {
// setTimeout is for making sure saveCalendarRef happen before focusCalendar
this.f... | {
open = props.defaultOpen;
} | conditional_block |
Picker.tsx | import React, { CSSProperties } from 'react';
import ReactDOM from 'react-dom';
import { Moment } from 'moment';
import { polyfill } from 'react-lifecycles-compat';
import createChainedFunction from 'rc-util/lib/createChainedFunction';
import KeyCode from 'rc-util/lib/KeyCode';
import Trigger from 'rc-trigger';
import... | placement,
style,
getCalendarContainer,
align,
animation,
disabled,
dropdownClassName,
transitionName,
children,
} = this.props;
const { state } = this;
return (
<Trigger
popup={this.getCalendarElement()}
popupAlign={align}
... | prefixCls, | random_line_split |
day_5.rs | use std::boxed::Box;
use std::ptr::Shared;
use std::option::Option;
struct Node {
elem: i32,
next: Option<Box<Node>>
}
impl Node {
fn new(e: i32) -> Node {
Node {
elem: e,
next: None
}
}
}
#[derive(Default)]
pub struct Queue {
size: usize,
head: Option... | (*node).elem == e
},
None => false,
}
}
pub fn dequeue(&mut self) -> Option<i32> {
self.head.take().map(
|head| {
let h = *head;
self.head = h.next;
self.size -= 1;
h.elem
... | } | random_line_split |
day_5.rs | use std::boxed::Box;
use std::ptr::Shared;
use std::option::Option;
struct Node {
elem: i32,
next: Option<Box<Node>>
}
impl Node {
fn | (e: i32) -> Node {
Node {
elem: e,
next: None
}
}
}
#[derive(Default)]
pub struct Queue {
size: usize,
head: Option<Box<Node>>,
tail: Option<Shared<Node>>
}
#[allow(boxed_local)]
impl Queue {
pub fn new() -> Queue {
Queue {
size: 0,
... | new | identifier_name |
day_5.rs | use std::boxed::Box;
use std::ptr::Shared;
use std::option::Option;
struct Node {
elem: i32,
next: Option<Box<Node>>
}
impl Node {
fn new(e: i32) -> Node {
Node {
elem: e,
next: None
}
}
}
#[derive(Default)]
pub struct Queue {
size: usize,
head: Option... | ,
None => false,
}
}
pub fn dequeue(&mut self) -> Option<i32> {
self.head.take().map(
|head| {
let h = *head;
self.head = h.next;
self.size -= 1;
h.elem
}
)
}
}
| {
let mut node = head;
while (*node).elem != e && (*node).next.is_some() {
node = (*node).next.as_ref().unwrap();
}
(*node).elem == e
} | conditional_block |
day_5.rs | use std::boxed::Box;
use std::ptr::Shared;
use std::option::Option;
struct Node {
elem: i32,
next: Option<Box<Node>>
}
impl Node {
fn new(e: i32) -> Node {
Node {
elem: e,
next: None
}
}
}
#[derive(Default)]
pub struct Queue {
size: usize,
head: Option... |
pub fn enqueue(&mut self, e: i32) {
self.size += 1;
let mut node = Box::new(Node::new(e));
let raw: *mut _ = &mut *node;
match self.tail {
Some(share) => unsafe { (**share).next = Some(node) },
None => self.head = Some(node),
}
unsafe {
... | {
self.size
} | identifier_body |
server.rs | extern crate iron;
extern crate handlebars_iron as hbs;
extern crate rustc_serialize;
use iron::prelude::*;
use iron::{status};
use hbs::{Template, HandlebarsEngine};
use rustc_serialize::json::{ToJson, Json};
use std::collections::BTreeMap;
struct Team {
name: String,
pts: u16
}
impl ToJson for Team {
f... | m.to_json()
}
}
fn make_data () -> BTreeMap<String, Json> {
let mut data = BTreeMap::new();
data.insert("year".to_string(), "2015".to_json());
let teams = vec![ Team { name: "Jiangsu Sainty".to_string(),
pts: 43u16 },
Team { name: "Beijing Gu... | random_line_split | |
server.rs | extern crate iron;
extern crate handlebars_iron as hbs;
extern crate rustc_serialize;
use iron::prelude::*;
use iron::{status};
use hbs::{Template, HandlebarsEngine};
use rustc_serialize::json::{ToJson, Json};
use std::collections::BTreeMap;
struct Team {
name: String,
pts: u16
}
impl ToJson for Team {
f... | () -> BTreeMap<String, Json> {
let mut data = BTreeMap::new();
data.insert("year".to_string(), "2015".to_json());
let teams = vec![ Team { name: "Jiangsu Sainty".to_string(),
pts: 43u16 },
Team { name: "Beijing Guoan".to_string(),
... | make_data | identifier_name |
app-helper.service.ts | import angular from 'angular';
import autobind from 'autobind-decorator';
import DOMPurify from 'dompurify';
import { marked } from 'marked';
import { ApiServiceStatus } from '../../../shared/api/api.enum';
import { ApiService, ApiServiceInfo, ApiServiceInfoResponse } from '../../../shared/api/api.interface';
import * ... | updateServiceUrl(newServiceUrl: string): ng.IPromise<ApiServiceInfo> {
// Update service url in store and refresh service info
return this.utilitySvc.updateServiceUrl(newServiceUrl).then(() => this.formatServiceInfo());
}
} | random_line_split | |
app-helper.service.ts | import angular from 'angular';
import autobind from 'autobind-decorator';
import DOMPurify from 'dompurify';
import { marked } from 'marked';
import { ApiServiceStatus } from '../../../shared/api/api.enum';
import { ApiService, ApiServiceInfo, ApiServiceInfoResponse } from '../../../shared/api/api.interface';
import * ... |
abstract getNextScheduledSyncUpdateCheck(): ng.IPromise<Date>;
abstract getSyncQueueLength(): ng.IPromise<number>;
abstract openUrl(event?: Event, url?: string): void;
abstract removePermissions(): ng.IPromise<void>;
abstract requestPermissions(): ng.IPromise<boolean>;
switchView(view?: AppView): ng.... | {
return this.currentView;
} | identifier_body |
app-helper.service.ts | import angular from 'angular';
import autobind from 'autobind-decorator';
import DOMPurify from 'dompurify';
import { marked } from 'marked';
import { ApiServiceStatus } from '../../../shared/api/api.enum';
import { ApiService, ApiServiceInfo, ApiServiceInfoResponse } from '../../../shared/api/api.interface';
import * ... | (): AppView {
return this.currentView;
}
abstract getNextScheduledSyncUpdateCheck(): ng.IPromise<Date>;
abstract getSyncQueueLength(): ng.IPromise<number>;
abstract openUrl(event?: Event, url?: string): void;
abstract removePermissions(): ng.IPromise<void>;
abstract requestPermissions(): ng.IPromis... | getCurrentView | identifier_name |
app-helper.service.ts | import angular from 'angular';
import autobind from 'autobind-decorator';
import DOMPurify from 'dompurify';
import { marked } from 'marked';
import { ApiServiceStatus } from '../../../shared/api/api.enum';
import { ApiService, ApiServiceInfo, ApiServiceInfoResponse } from '../../../shared/api/api.interface';
import * ... |
// Render markdown and add link classes to service message
let message = response.message ? marked(response.message) : '';
if (message) {
const messageDom = new DOMParser().parseFromString(message, 'text/html');
messageDom.querySelectorAll('a').forEach((hyperlink) => {
... | {
return;
} | conditional_block |
sql2json.js | /*
* CSVJSON Application - SQL to JSON
*
* Copyright (c) 2014 Martin Drapeau
*/
APP.sql2json = function() {
var uploadUrl = "/sql2json/upload";
var $file = $('#fileupload'),
$format = $('input[type=radio][name=format]'),
$sql = $('#sql'),
$result = $('#result'),
$clear = $('#clear, a.clear'),
$conver... |
if (format == "json")
result = JSON.stringify(json, null, space);
else
result = _.reduce(json, function(result, table, name) {
return result + "var " + name + " = " + JSON.stringify(table, null, space) + ";\n";
}, '');
$result.removeClass('error').val(result).change();
});
APP.start({
$co... | // Output requested format
var format = $format.filter(':checked').val(),
space = $minify.is(':checked') ? undefined : 2,
result = ''; | random_line_split |
enphase.py | import requests, json, logging
from lxml import html
from datetime import datetime
logger = logging.getLogger(__name__)
class EnphaseAPI:
API_BASE_URL = "https://api.enphaseenergy.com/api/v2/systems/{system_id}/{function}?key={key}&user_id={user_id}"
API_BASE_URL_INDEX = "https://api.enphaseenergy.com/api/v2/... |
def _parse_production_data(self,page_html):
parsed_result = {'':datetime.now()}
for key in self._XPATH_DICT.keys():
value = page_html.xpath(self._XPATH_DICT[key])
parsed_result[key] = value[0].strip()
return parsed_result
def get_current_prod_data(self):
return self._CURRENT_DATA
=======
>>>>>>... | formated_url = self._ENVOY_URL.format(ip = self._ENVOY_IP,path = 'production')
envoy_page = requests.get(formated_url)
page_html = html.fromstring(envoy_page.text)
if envoy_page.status_code == 200:
print "API initialized getting data"
self._CURRENT_DATA = self._parse_production_data(page_html)
self._IS... | identifier_body |
enphase.py | import requests, json, logging
from lxml import html
from datetime import datetime
logger = logging.getLogger(__name__)
class EnphaseAPI:
API_BASE_URL = "https://api.enphaseenergy.com/api/v2/systems/{system_id}/{function}?key={key}&user_id={user_id}"
API_BASE_URL_INDEX = "https://api.enphaseenergy.com/api/v2/... | formatedURL = self.API_BASE_URL_INDEX.format(
key = self.KEY,
user_id = self.USER_ID,
)
response = requests.get(formatedURL)
#check that everything is good with the request here
if response.status_code == 401:
logger.err... | random_line_split | |
enphase.py | import requests, json, logging
from lxml import html
from datetime import datetime
logger = logging.getLogger(__name__)
class | :
API_BASE_URL = "https://api.enphaseenergy.com/api/v2/systems/{system_id}/{function}?key={key}&user_id={user_id}"
API_BASE_URL_INDEX = "https://api.enphaseenergy.com/api/v2/systems/?key={key}&user_id={user_id}"
FORMAT = "json"
"""
Provide API key and User Key to get started
more info here:http... | EnphaseAPI | identifier_name |
enphase.py | import requests, json, logging
from lxml import html
from datetime import datetime
logger = logging.getLogger(__name__)
class EnphaseAPI:
API_BASE_URL = "https://api.enphaseenergy.com/api/v2/systems/{system_id}/{function}?key={key}&user_id={user_id}"
API_BASE_URL_INDEX = "https://api.enphaseenergy.com/api/v2/... |
else:
logger.error("unable to initialize API error: %s"%envoy_page.status_code)
self._IS_INTIALIZED = False
def _parse_production_data(self,page_html):
parsed_result = {'':datetime.now()}
for key in self._XPATH_DICT.keys():
value = page_html.xpath(self._XPATH_DICT[key])
parsed_result[key] = value... | print "API initialized getting data"
self._CURRENT_DATA = self._parse_production_data(page_html)
self._IS_INTIALIZED = True | conditional_block |
InputBase.js | "use strict";
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard");
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = exports.InputBaseComponent = exports.InputBase... |
if (muiFormControl && muiFormControl.onBlur) {
muiFormControl.onBlur(event);
} else {
setFocused(false);
}
};
const handleChange = (event, ...args) => {
if (!isControlled) {
const element = event.target || inputRef.current;
if (element == null) {
throw new Error(p... | {
inputPropsProp.onBlur(event);
} | conditional_block |
InputBase.js | "use strict";
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard");
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = exports.InputBaseComponent = exports.InputBase... | }
}
const handleAutoFill = event => {
// Provide a fake value as Chrome might not let you access it for security reasons.
checkDirty(event.animationName === 'mui-auto-fill-cancel' ? inputRef.current : {
value: 'x'
});
};
React.useEffect(() => {
if (muiFormControl) {
muiFormCont... | random_line_split | |
urlResponseTimeDetails.ts | ///
/// Copyright 2015-2016 Red Hat, Inc. and/or its affiliates
/// and other contributors as indicated by the @author tags.
///
/// 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
///
/// ... |
}, (error) => {
this.$log.error('Error Loading Threshold data');
});
}
public refreshHistoricalChartDataForTimestamp(metricId:MetricId,
startTime?:TimestampInMillis,
endTime?:Timestam... | {
this.threshold = conditions[0].threshold;
} | conditional_block |
urlResponseTimeDetails.ts | ///
/// Copyright 2015-2016 Red Hat, Inc. and/or its affiliates
/// and other contributors as indicated by the @author tags.
///
/// 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
///
/// ... |
private getAlerts(resourceId:string, startTime:TimestampInMillis, endTime:TimestampInMillis):void {
let alertsArray:IAlert[];
let promise = this.HawkularAlertsManager.queryAlerts({
statuses: 'OPEN',
tags: 'resourceId|' + resourceId, startTime: startTime, endTime: endTime
}).then(... | {
this.startTimeStamp = data[0].getTime();
this.endTimeStamp = data[1].getTime();
this.HawkularNav.setTimestampStartEnd(this.startTimeStamp, this.endTimeStamp);
this.refreshChartDataNow(this.getMetricId());
} | identifier_body |
urlResponseTimeDetails.ts | ///
/// Copyright 2015-2016 Red Hat, Inc. and/or its affiliates
/// and other contributors as indicated by the @author tags.
///
/// 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
///
/// ... | (metricId:MetricId,
startTime?:TimestampInMillis,
endTime?:TimestampInMillis):void {
let dataPoints:IChartDataPoint[];
// calling refreshChartData without params use the model values
if (!endTime) {
endTime = this.endTimeStamp;
... | refreshSummaryData | identifier_name |
urlResponseTimeDetails.ts | ///
/// Copyright 2015-2016 Red Hat, Inc. and/or its affiliates
/// and other contributors as indicated by the @author tags.
///
/// 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
///
/// ... | }
private retrieveThreshold() {
let triggerId = this.$routeParams.resourceId + '_trigger_thres';
this.HawkularAlertsManager.getTriggerConditions(triggerId)
.then((conditions) => {
if (conditions[0]) {
this.threshold = conditions[0].threshold;
}
}, (er... | }, (error) => {
this.NotificationsService.error('Error Loading Chart Data: ' + error);
});
} | random_line_split |
plano.resource.js | (function () {
'use strict';
angular.module('SmallBIApp')
.factory('planoResource', planoResource);
function planoResource(Service) {
var service = {
listaPlanos: listaPlanos,
inserePlano:inserePlano,
alteraPlano: alteraPlano,
getPlanoById: getPlanoById,
deletePlano: deletePl... |
function inserePlano(dataParam) {
var url = 'plano/adicionar';
return Service.servicePost(dataParam, url);
}
function alteraPlano(dataParam) {
var url = 'plano/alterar';
return Service.servicePost(dataParam, url);
}
function getPlanoById(param) {
var url = 'plano/getById/';
retu... | {
var url = 'plano/listar';
return Service.serviceGet(url);
} | identifier_body |
plano.resource.js | (function () {
'use strict';
angular.module('SmallBIApp')
.factory('planoResource', planoResource);
function planoResource(Service) {
var service = {
listaPlanos: listaPlanos,
inserePlano:inserePlano,
alteraPlano: alteraPlano,
getPlanoById: getPlanoById,
deletePlano: deletePl... | return Service.serviceGetById(param, url);
}
function deletePlano(param) {
var url = 'plano/deletar/';
return Service.serviceDelete(url + param);
}
}
})(); | var url = 'plano/getById/'; | random_line_split |
plano.resource.js | (function () {
'use strict';
angular.module('SmallBIApp')
.factory('planoResource', planoResource);
function planoResource(Service) {
var service = {
listaPlanos: listaPlanos,
inserePlano:inserePlano,
alteraPlano: alteraPlano,
getPlanoById: getPlanoById,
deletePlano: deletePl... | (param) {
var url = 'plano/deletar/';
return Service.serviceDelete(url + param);
}
}
})();
| deletePlano | identifier_name |
spacialized_cone.rs | use na::{Translation, Norm, RotationMatrix, BaseFloat};
use na;
use math::{N, Vect, Matrix};
use bounding_volume::{BoundingVolume, BoundingSphere};
use math::{Scalar, Point, Vect};
// FIXME: make a structure 'cone' ?
#[derive(Debug, PartialEq, Clone, RustcEncodable, RustcDecodable)]
/// A normal cone with a bounding s... |
}
#[cfg(test)]
mod test {
use na::Vec3;
use na;
use super::SpacializedCone;
use bounding_volume::{BoundingVolume, BoundingSphere};
#[test]
#[cfg(feature = "3d")]
fn test_merge_vee() {
let sp = BoundingSphere::new(na::orig(), na::one());
let pi: N = BaseFloat::pi();
... | {
self.sphere.set_translation(v)
} | identifier_body |
spacialized_cone.rs | use na::{Translation, Norm, RotationMatrix, BaseFloat};
use na;
use math::{N, Vect, Matrix};
use bounding_volume::{BoundingVolume, BoundingSphere};
use math::{Scalar, Point, Vect};
// FIXME: make a structure 'cone' ?
#[derive(Debug, PartialEq, Clone, RustcEncodable, RustcDecodable)]
/// A normal cone with a bounding s... |
}
#[inline]
fn merged(&self, other: &SpacializedCone) -> SpacializedCone {
let mut res = self.clone();
res.merge(other);
res
}
}
impl Translation<Vect> for SpacializedCone {
#[inline]
fn translation(&self) -> Vect {
self.sphere.center().as_vec().clone()
}... | {
// This happens if alpha ~= 0 or alpha ~= pi.
if alpha > na::one() { // NOTE: 1.0 is just a randomly chosen number in-between 0 and pi.
// alpha ~= pi
self.hangle = alpha;
}
else {
// alpha ~= 0, do nothing.
}
... | conditional_block |
spacialized_cone.rs | use na::{Translation, Norm, RotationMatrix, BaseFloat};
use na;
use math::{N, Vect, Matrix};
use bounding_volume::{BoundingVolume, BoundingSphere};
use math::{Scalar, Point, Vect};
// FIXME: make a structure 'cone' ?
#[derive(Debug, PartialEq, Clone, RustcEncodable, RustcDecodable)]
/// A normal cone with a bounding s... |
let ab = a.merged(&b);
assert!(na::approx_eq(&ab.hangle, &(pi_12 * na::cast(4.0f64))))
}
} | random_line_split | |
spacialized_cone.rs | use na::{Translation, Norm, RotationMatrix, BaseFloat};
use na;
use math::{N, Vect, Matrix};
use bounding_volume::{BoundingVolume, BoundingSphere};
use math::{Scalar, Point, Vect};
// FIXME: make a structure 'cone' ?
#[derive(Debug, PartialEq, Clone, RustcEncodable, RustcDecodable)]
/// A normal cone with a bounding s... | (&self) -> Vect {
self.sphere.center().as_vec().clone()
}
#[inline]
fn inv_translation(&self) -> Vect {
-self.sphere.translation()
}
#[inline]
fn append_translation(&mut self, dv: &Vect) {
self.sphere.append_translation(dv);
}
#[inline]
fn append_translatio... | translation | identifier_name |
primitives_arrays.rs | use std::mem;
// This function borrows a slice
fn analyze_slice(slice: &[i32]) {
println!("first element of the slice: {}", slice[0]);
println!("the slice has {} elements", slice.len());
}
pub fn main() {
// Fixed-size array (type signature is superfluous)
let xs: [i32; 5] = [1, 2, 3, 4, 5];
// A... | println!("Slice: {:?}", &ps[1 .. 4]);
} |
let ps: &[i32] = &[1, 3, 5, 6, 9];
analyze_slice(&ps[1 .. 4]); | random_line_split |
primitives_arrays.rs | use std::mem;
// This function borrows a slice
fn analyze_slice(slice: &[i32]) |
pub fn main() {
// Fixed-size array (type signature is superfluous)
let xs: [i32; 5] = [1, 2, 3, 4, 5];
// All elements can be initialized to the same value
let ys: [i32; 500] = [0; 500];
println!("Array xs: {:?}", xs);
// Indexing starts at 0
println!("first element of the array: {}", ... | {
println!("first element of the slice: {}", slice[0]);
println!("the slice has {} elements", slice.len());
} | identifier_body |
primitives_arrays.rs | use std::mem;
// This function borrows a slice
fn analyze_slice(slice: &[i32]) {
println!("first element of the slice: {}", slice[0]);
println!("the slice has {} elements", slice.len());
}
pub fn | () {
// Fixed-size array (type signature is superfluous)
let xs: [i32; 5] = [1, 2, 3, 4, 5];
// All elements can be initialized to the same value
let ys: [i32; 500] = [0; 500];
println!("Array xs: {:?}", xs);
// Indexing starts at 0
println!("first element of the array: {}", xs[0]);
p... | main | identifier_name |
dom_extension.ts | /*
* Copyright (C) 2020 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without | * * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endors... | * modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer. | random_line_split |
log.rs | use std::cmp::Ordering;
use std::collections::{BinaryHeap, HashSet};
use std::fmt::Write;
use clap::{App, ArgMatches, SubCommand};
use futures::prelude::*;
use futures::stream;
use attaca::marshal::{CommitObject, ObjectHash};
use attaca::Repository;
use errors::*;
#[derive(Eq)]
struct TimeOrdered {
hash: Objec... |
}
pub fn command() -> App<'static, 'static> {
SubCommand::with_name("log").about("View repository commit history.")
}
pub fn go(repository: &mut Repository, _matches: &ArgMatches) -> Result<()> {
let mut commits = {
let ctx = repository.local(())?;
let mut commits = BinaryHeap::new();
... | {
self.commit.timestamp.cmp(&other.commit.timestamp)
} | identifier_body |
log.rs | use std::cmp::Ordering;
use std::collections::{BinaryHeap, HashSet};
use std::fmt::Write;
use clap::{App, ArgMatches, SubCommand};
use futures::prelude::*;
use futures::stream;
use attaca::marshal::{CommitObject, ObjectHash};
use attaca::Repository;
use errors::*;
#[derive(Eq)]
struct TimeOrdered {
hash: Objec... | for TimeOrdered { hash, commit } in commits.into_iter().rev() {
write!(
buf,
"\ncommit {}\nDate: {}\n\t{}\n",
hash,
commit.timestamp,
commit.message
)?;
}
print!("{}", buf);
Ok(())
} | }
| random_line_split |
log.rs | use std::cmp::Ordering;
use std::collections::{BinaryHeap, HashSet};
use std::fmt::Write;
use clap::{App, ArgMatches, SubCommand};
use futures::prelude::*;
use futures::stream;
use attaca::marshal::{CommitObject, ObjectHash};
use attaca::Repository;
use errors::*;
#[derive(Eq)]
struct TimeOrdered {
hash: Objec... | (&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for TimeOrdered {
fn cmp(&self, other: &Self) -> Ordering {
self.commit.timestamp.cmp(&other.commit.timestamp)
}
}
pub fn command() -> App<'static, 'static> {
SubCommand::with_name("log").about("View repos... | partial_cmp | identifier_name |
log.rs | use std::cmp::Ordering;
use std::collections::{BinaryHeap, HashSet};
use std::fmt::Write;
use clap::{App, ArgMatches, SubCommand};
use futures::prelude::*;
use futures::stream;
use attaca::marshal::{CommitObject, ObjectHash};
use attaca::Repository;
use errors::*;
#[derive(Eq)]
struct TimeOrdered {
hash: Objec... |
for TimeOrdered { hash, commit } in commits.into_iter().rev() {
write!(
buf,
"\ncommit {}\nDate: {}\n\t{}\n",
hash,
commit.timestamp,
commit.message
)?;
}
print!("{}", buf);
Ok(())
}
| {
write!(
buf,
"commit {} \nDate: {}\n\t{}\n",
hash,
commit.timestamp,
commit.message
)?;
} | conditional_block |
ru.js | if (typeof (WBBLANG)=="undefined") {WBBLANG = {};}
WBBLANG['ru']= CURLANG = {
bold: "Полужирный",
italic: "Курсив",
underline: "Подчеркнутый",
strike: "Зачеркнутый",
link: "Ссылка",
img: "Изображение",
sup: "Надстрочный текст",
sub: "Подстрочный текст",
justifyleft: "Текст по левому краю",
justifycenter: "Тек... | modal_video_text: "Введите URL видео",
close: "Закрыть",
save: "Сохранить",
cancel: "Отмена",
remove: "Удалить",
validation_err: "Введенные данные некорректны",
error_onupload: "Ошибка во время загрузки файла или такое расширение файла не поддерживается",
fileupload_text1: "Перетащите файл сюда",
fileupl... | add_attach: "Добавить вложение",
| random_line_split |
ru.js | if (typeof (WBBLANG)=="undefined") |
WBBLANG['ru']= CURLANG = {
bold: "Полужирный",
italic: "Курсив",
underline: "Подчеркнутый",
strike: "Зачеркнутый",
link: "Ссылка",
img: "Изображение",
sup: "Надстрочный текст",
sub: "Подстрочный текст",
justifyleft: "Текст по левому краю",
justifycenter: "Текст по центру",
justifyright: "Текст по правому кр... | {WBBLANG = {};} | conditional_block |
load-ner.js | /* Copyright 2016-2017 University of Pittsburgh
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 ... | (annotation, uriStr, email){
console.log("[INFO]: begin check for " + annotation.exact + " | " + email);
uriPost = uriStr.replace(/[\/\\\-\:\.]/g, "");
q.nfcall(
client.search(
{
index: 'annotator',
type: 'annotation',
body:{
... | loadNewAnnotation | identifier_name |
load-ner.js | /* Copyright 2016-2017 University of Pittsburgh
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 ... | body: { // annotatorJs fields for drug Mention
"email": email,
"created": datetime,
"updated": datetime,
"annotationType": "DrugMention",
"permissions": {
"read": ["group:__consumer__"]
},
... | index: 'annotator',
type: 'annotation',
id: uuid.v4(), | random_line_split |
load-ner.js | /* Copyright 2016-2017 University of Pittsburgh
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 ... |
function loadNewAnnotation(annotation, uriStr, email){
console.log("[INFO]: begin check for " + annotation.exact + " | " + email);
uriPost = uriStr.replace(/[\/\\\-\:\.]/g, "");
q.nfcall(
client.search(
{
index: 'annotator',
type: 'annotation',
... | {
for (i = 0; i < nersets.length; i++){
//for (i = 0; i < 1; i++){
subL = nersets[i];
for (j = 0; j < subL.length; j++){
//for (j = 0; j < 10; j++){
annotation = subL[j];
if (annotation){
uriStr = "";
if (sourceType == "pu... | identifier_body |
index.js | /* @flow */
import * as React from 'react';
import Link from 'amo/components/Link';
import { addParamsToHeroURL, checkInternalURL } from 'amo/utils';
import tracking from 'core/tracking';
import LoadingText from 'ui/components/LoadingText';
import type {
HeroCallToActionType,
SecondaryHeroShelfType,
} from 'amo/re... | <LoadingText width={80} />
<br />
<LoadingText width={60} />
</>
)}
</div>
{cta && (
<Link className="SecondaryHero-message-link" {...getLinkProps(cta)}>
<span className="SecondaryHero-message-linkText">{cta.text}</spa... | <div className="SecondaryHero-message-description">
{description || (
<> | random_line_split |
index.js | /* @flow */
import * as React from 'react';
import Link from 'amo/components/Link';
import { addParamsToHeroURL, checkInternalURL } from 'amo/utils';
import tracking from 'core/tracking';
import LoadingText from 'ui/components/LoadingText';
import type {
HeroCallToActionType,
SecondaryHeroShelfType,
} from 'amo/re... |
return {
...props,
href: makeCallToActionURL(link.url),
prependClientApp: false,
prependLang: false,
target: '_blank',
};
}
return {};
};
const renderedModules = [];
modules.forEach((module) => {
renderedModules.push(
<div className="Secondar... | {
return { ...props, to: makeCallToActionURL(urlInfo.relativeURL) };
} | conditional_block |
file-matcher.js | /*
Copyright (c) 2012, Yahoo! Inc. All rights reserved.
Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
*/
var fileset = require('fileset'),
path = require('path'),
seq = 0;
function | (options, callback) {
if (!callback && typeof options === 'function') {
callback = options;
options = null;
}
options = options || {};
var root = options.root,
includes = options.includes,
excludes = options.excludes,
relative = options.relative,
opts;
... | filesFor | identifier_name |
file-matcher.js | /*
Copyright (c) 2012, Yahoo! Inc. All rights reserved.
Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
*/
var fileset = require('fileset'),
path = require('path'),
seq = 0;
function filesFor(options, callback) {
if (!callback && typeof options === 'function... |
if (!relative) {
files = files.map(function (file) { return path.resolve(root, file); });
}
callback(err, files);
});
}
function matcherFor(options, callback) {
if (!callback && typeof options === 'function') {
callback = options;
options = null;
}
... | { return callback(err); } | conditional_block |
file-matcher.js | /*
Copyright (c) 2012, Yahoo! Inc. All rights reserved.
Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
*/
var fileset = require('fileset'),
path = require('path'),
seq = 0;
function filesFor(options, callback) |
function matcherFor(options, callback) {
if (!callback && typeof options === 'function') {
callback = options;
options = null;
}
options = options || {};
options.relative = false; //force absolute paths
filesFor(options, function (err, files) {
var fileMap = {},
... | {
if (!callback && typeof options === 'function') {
callback = options;
options = null;
}
options = options || {};
var root = options.root,
includes = options.includes,
excludes = options.excludes,
relative = options.relative,
opts;
root = root || pr... | identifier_body |
file-matcher.js | /*
Copyright (c) 2012, Yahoo! Inc. All rights reserved.
Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
*/
var fileset = require('fileset'),
path = require('path'),
seq = 0;
function filesFor(options, callback) {
if (!callback && typeof options === 'function... | filesFor: filesFor,
matcherFor: matcherFor
}; | random_line_split | |
mutex.rs | #[cfg(all(test, not(target_os = "emscripten")))]
mod tests;
use crate::cell::UnsafeCell;
use crate::fmt;
use crate::ops::{Deref, DerefMut};
use crate::sync::{poison, LockResult, TryLockError, TryLockResult};
use crate::sys_common::mutex as sys;
/// A mutual exclusion primitive useful for protecting shared data
///
//... |
Err(TryLockError::Poisoned(err)) => {
d.field("data", &&**err.get_ref());
}
Err(TryLockError::WouldBlock) => {
struct LockedPlaceholder;
impl fmt::Debug for LockedPlaceholder {
fn fmt(&self, f: &mut fmt::Formatter<'... | {
d.field("data", &&*guard);
} | conditional_block |
mutex.rs | #[cfg(all(test, not(target_os = "emscripten")))]
mod tests;
use crate::cell::UnsafeCell;
use crate::fmt;
use crate::ops::{Deref, DerefMut};
use crate::sync::{poison, LockResult, TryLockError, TryLockResult};
use crate::sys_common::mutex as sys;
/// A mutual exclusion primitive useful for protecting shared data
///
//... | (&mut self) -> LockResult<&mut T> {
let data = self.data.get_mut();
poison::map_result(self.poison.borrow(), |_| data)
}
}
#[stable(feature = "mutex_from", since = "1.24.0")]
impl<T> From<T> for Mutex<T> {
/// Creates a new mutex in an unlocked state ready for use.
/// This is equivalent to... | get_mut | identifier_name |
mutex.rs | #[cfg(all(test, not(target_os = "emscripten")))]
mod tests;
use crate::cell::UnsafeCell;
use crate::fmt;
use crate::ops::{Deref, DerefMut};
use crate::sync::{poison, LockResult, TryLockError, TryLockResult};
use crate::sys_common::mutex as sys;
/// A mutual exclusion primitive useful for protecting shared data
///
//... |
/// Attempts to acquire this lock.
///
/// If the lock could not be acquired at this time, then [`Err`] is returned.
/// Otherwise, an RAII guard is returned. The lock will be unlocked when the
/// guard is dropped.
///
/// This function does not block.
///
/// # Errors
///
... | {
unsafe {
self.inner.raw_lock();
MutexGuard::new(self)
}
} | identifier_body |
mutex.rs | #[cfg(all(test, not(target_os = "emscripten")))]
mod tests;
use crate::cell::UnsafeCell;
use crate::fmt;
use crate::ops::{Deref, DerefMut};
use crate::sync::{poison, LockResult, TryLockError, TryLockResult};
use crate::sys_common::mutex as sys;
/// A mutual exclusion primitive useful for protecting shared data
///
//... | #[stable(feature = "rust1", since = "1.0.0")]
pub struct MutexGuard<'a, T: ?Sized + 'a> {
lock: &'a Mutex<T>,
poison: poison::Guard,
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: ?Sized> !Send for MutexGuard<'_, T> {}
#[stable(feature = "mutexguard", since = "1.19.0")]
unsafe impl<T: ?Sized + Sync> S... | not(bootstrap),
must_not_suspend = "holding a MutexGuard across suspend \
points can cause deadlocks, delays, \
and cause Futures to not implement `Send`"
)] | random_line_split |
gpu_timeline.py | # Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import collections
import math
import sys
from telemetry.timeline import model as model_module
from telemetry.value import scalar
from telemetry.value import... |
# Calculate Mean Frame Time for the CPU side.
frame_times = []
if all_service_events:
prev_frame_end = all_service_events[0][0].start
for event_list in all_service_events:
last_service_event_in_frame = event_list[-1]
frame_times.append(last_service_event_in_frame.end - prev_fra... | tracked_events[(value, 'gpu')].append(
current_tracked_device_events[value]) | conditional_block |
gpu_timeline.py | # Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import collections
import math
import sys
from telemetry.timeline import model as model_module
from telemetry.value import scalar
from telemetry.value import... | Events:
swap - The time in milliseconds between each swap marker.
total - The amount of time spent in the renderer thread.
TRACKED_NAMES: Using the TRACKED_GL_CONTEXT_NAME dict, we
include the traces per frame for the
tracked name.
... | (EVENT_NAME1, SRC1_TYPE): [FRAME0_TIME, FRAME1_TIME...etc.],
(EVENT_NAME2, SRC2_TYPE): [FRAME0_TIME, FRAME1_TIME...etc.],
}
| random_line_split |
gpu_timeline.py | # Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import collections
import math
import sys
from telemetry.timeline import model as model_module
from telemetry.value import scalar
from telemetry.value import... | (events_per_frame, event_data_func):
"""Given a list of events per frame and a function to extract event time data,
returns a list of frame times."""
times_per_frame = []
for event_list in events_per_frame:
event_times = [event_data_func(event) for event in event_list]
times_per_frame.append(sum(even... | _CalculateFrameTimes | identifier_name |
gpu_timeline.py | # Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import collections
import math
import sys
from telemetry.timeline import model as model_module
from telemetry.value import scalar
from telemetry.value import... |
def _CPUFrameTimes(events_per_frame):
"""Given a list of events per frame, returns a list of CPU frame times."""
# CPU event frames are calculated using the event thread duration.
# Some platforms do not support thread_duration, convert those to 0.
return _CalculateFrameTimes(events_per_frame,
... | """Given a list of events per frame and a function to extract event time data,
returns a list of frame times."""
times_per_frame = []
for event_list in events_per_frame:
event_times = [event_data_func(event) for event in event_list]
times_per_frame.append(sum(event_times))
return times_per_frame | identifier_body |
pretty.rs | // Pris -- A language for designing slides
// Copyright 2017 Ruud van Asseldonk
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 3. A copy
// of the License is available in the root of the repository.
//! The string formatting prim... |
pub fn print<P: Print>(&mut self, content: P) {
content.print(self);
}
pub fn println<P: Print>(&mut self, content: P) {
for _ in 0..self.indent * 2 {
self.target.push(' ');
}
self.print(content);
}
pub fn print_hex_byte(&mut self, content: u8) {
... | {
assert!(self.indent > 0);
self.indent -= 1;
} | identifier_body |
pretty.rs | // Pris -- A language for designing slides
// Copyright 2017 Ruud van Asseldonk
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 3. A copy
// of the License is available in the root of the repository.
//! The string formatting prim... | write!(&mut f.target, "{}", self).unwrap();
}
}
impl Print for usize {
fn print(&self, f: &mut Formatter) {
write!(&mut f.target, "{}", self).unwrap();
}
}
impl Print for f64 {
fn print(&self, f: &mut Formatter) {
write!(&mut f.target, "{}", self).unwrap();
}
}
impl Format... | fn print(&self, f: &mut Formatter) { | random_line_split |
pretty.rs | // Pris -- A language for designing slides
// Copyright 2017 Ruud van Asseldonk
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 3. A copy
// of the License is available in the root of the repository.
//! The string formatting prim... | (&self, f: &mut Formatter) {
(*self).print(f);
}
}
impl<P: Print> Print for Box<P> {
fn print(&self, f: &mut Formatter) {
(**self).print(f);
}
}
impl<P: Print> Print for Rc<P> {
fn print(&self, f: &mut Formatter) {
(**self).print(f);
}
}
impl<'a> Print for &'a str {
fn... | print | identifier_name |
gulpfile.js | var fs = require('fs');
var path = require('path');
var gulp = require('gulp');
var browserSync = require('browser-sync').create();
var reload = browserSync.reload;
var sass = require('gulp-sass');
var compass = require('gulp-compass');
var watch = require('gulp-watch');
var gutil = require('gulp-util');
var conc... |
gulp.task('copy:jquery', function () {
return gulp.src(['node_modules/jquery/dist/jquery.min.js'])
.pipe(plugins.rename('jquery-' + pkg.devDependencies.jquery + '.min.js'))
.pipe(gulp.dest(dirs.dist + '/js/vendor'));
});
gulp.task('copy:license', function () {
return gulp.src('LI... | .pipe(gulp.dest(dirs.dist));
}); | random_line_split |
landed_cost_voucher.py | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe import _
from frappe.utils import flt
from frappe.model.document import Document
from erpnext.stock.doctype.serial_no.serial_no import... |
def set_total_taxes_and_charges(self):
self.total_taxes_and_charges = sum([flt(d.amount) for d in self.get("taxes")])
def set_applicable_charges_for_item(self):
based_on = self.distribute_charges_based_on.lower()
total = sum([flt(d.get(based_on)) for d in self.get("items")])
if not total:
frappe.throw(... | receipt_documents = []
for d in self.get("purchase_receipts"):
if frappe.db.get_value(d.receipt_document_type, d.receipt_document, "docstatus") != 1:
frappe.throw(_("Receipt document must be submitted"))
else:
receipt_documents.append(d.receipt_document)
for item in self.get("items"):
if not it... | identifier_body |
landed_cost_voucher.py | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe import _
from frappe.utils import flt
from frappe.model.document import Document
from erpnext.stock.doctype.serial_no.serial_no import... | (self):
for d in self.get("purchase_receipts"):
doc = frappe.get_doc(d.receipt_document_type, d.receipt_document)
# set landed cost voucher amount in pr item
doc.set_landed_cost_voucher_amount()
# set valuation amount in pr item
doc.update_valuation_rate("items")
# save will update landed_cost_vo... | update_landed_cost | identifier_name |
landed_cost_voucher.py | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe import _
from frappe.utils import flt
from frappe.model.document import Document
from erpnext.stock.doctype.serial_no.serial_no import... |
def validate(self):
self.check_mandatory()
self.validate_purchase_receipts()
self.set_total_taxes_and_charges()
if not self.get("items"):
self.get_items_from_purchase_receipts()
else:
self.set_applicable_charges_for_item()
def check_mandatory(self):
if not self.get("purchase_receipts"):
frappe... | self.set_applicable_charges_for_item() | conditional_block |
landed_cost_voucher.py | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe import _
from frappe.utils import flt
from frappe.model.document import Document
from erpnext.stock.doctype.serial_no.serial_no import... | # update stock & gl entries for cancelled state of PR
doc.docstatus = 2
doc.update_stock_ledger(allow_negative_stock=True, via_landed_cost_voucher=True)
doc.make_gl_entries_on_cancel(repost_future_gle=False)
# update stock & gl entries for submit state of PR
doc.docstatus = 1
doc.update_stock_led... | random_line_split | |
grid_builder.rs | extern crate extra;
extern crate std;
use grid::{Row, Column, alive, dead, Cell, Grid};
mod grid;
/****************************************************************************
* Something to say Ben??
****************************************************************************/
/*
* Constructs an immutable grid fr... | // fn build_from_grid
| {
let cell_value = |row: uint, column: uint| {
let ncount = count_neighbors(Row(row), Column(column), prevg);
let cv = match (prevg.inner[row][column].value, ncount) {
(dead, 3) => alive,
(alive, 2..3) => alive,
_ => dead
};
return Cell { value: cv };
};
ret... | identifier_body |
grid_builder.rs | extern crate extra;
extern crate std;
use grid::{Row, Column, alive, dead, Cell, Grid};
mod grid;
/****************************************************************************
* Something to say Ben??
****************************************************************************/
/*
* Constructs an immutable grid fr... | std::vec::from_fn(width, |column| {
assert_eq!(width, file_contents[row].len());
let file_value = file_contents[row][column];
return Cell { value: cell_value(file_value as char) };
})
})
};
} // fn build_from_file_contents
/*
Returns a count for how many neighbors of a cell i... | _ => fail!("Unexpected cell value found in file.")
};
};
return Grid {
inner: std::vec::from_fn(height, |row| { | random_line_split |
grid_builder.rs | extern crate extra;
extern crate std;
use grid::{Row, Column, alive, dead, Cell, Grid};
mod grid;
/****************************************************************************
* Something to say Ben??
****************************************************************************/
/*
* Constructs an immutable grid fr... | (Row(row): Row, Column(col): Column, grid: &Grid) -> uint {
let left_column = Column(col - 1);
let right_column = Column(col + 1);
let above_row = Row(row - 1);
let below_row = Row(row + 1);
return grid.cell_alive(Row(row), left_column) + // left
grid.cell_alive(above_row, left_column) + // le... | count_neighbors | identifier_name |
passport-linkedin-oauth2-tests.ts | /**
* Created by andrewvetovitz on 12/21/2018.
*/
import passport = require('passport');
import linkedin = require('passport-linkedin-oauth2');
// just some test model
const User = {
findOrCreate(id: string, provider: string, callback: (err: any, user: any) => void): void {
callback(null, { username: 'ja... |
done(null, user);
});
})
);
| { done(err); return; } | conditional_block |
passport-linkedin-oauth2-tests.ts | /**
* Created by andrewvetovitz on 12/21/2018.
*/
import passport = require('passport');
import linkedin = require('passport-linkedin-oauth2');
// just some test model
const User = {
| (id: string, provider: string, callback: (err: any, user: any) => void): void {
callback(null, { username: 'james' });
}
};
const callbackURL = process.env.PASSPORT_LINKEDIN_CALLBACK_URL;
const clientID = process.env.PASSPORT_LINKEDIN_CONSUMER_KEY;
const clientSecret = process.env.PASSPORT_LINKEDIN_CONSUME... | findOrCreate | identifier_name |
passport-linkedin-oauth2-tests.ts | /**
* Created by andrewvetovitz on 12/21/2018.
*/
import passport = require('passport');
import linkedin = require('passport-linkedin-oauth2');
// just some test model
const User = {
findOrCreate(id: string, provider: string, callback: (err: any, user: any) => void): void {
callback(null, { username: 'ja... | (accessToken: string, refreshToken: string, profile: linkedin.Profile, done: (error: any, user?: any) => void) => {
User.findOrCreate(profile.id, profile.provider, (err, user) => {
if (err) { done(err); return; }
done(null, user);
});
})
); | clientID,
clientSecret
}, | random_line_split |
passport-linkedin-oauth2-tests.ts | /**
* Created by andrewvetovitz on 12/21/2018.
*/
import passport = require('passport');
import linkedin = require('passport-linkedin-oauth2');
// just some test model
const User = {
findOrCreate(id: string, provider: string, callback: (err: any, user: any) => void): void |
};
const callbackURL = process.env.PASSPORT_LINKEDIN_CALLBACK_URL;
const clientID = process.env.PASSPORT_LINKEDIN_CONSUMER_KEY;
const clientSecret = process.env.PASSPORT_LINKEDIN_CONSUMER_SECRET;
if (typeof callbackURL === "undefined") {
throw new Error("callbackURL is undefined");
}
if (typeof clientID === "un... | {
callback(null, { username: 'james' });
} | identifier_body |
utils.rs | use std::fmt;
use std::path::{Path, PathBuf};
use std::fs::{self, File};
use rustc_serialize::{Encodable, Encoder};
use url::Url;
use git2::{self, ObjectType};
use core::GitReference;
use util::{CargoResult, ChainError, human, ToUrl, internal};
#[derive(PartialEq, Clone, Debug)]
pub struct GitRevision(git2::Oid);
i... |
Err(..) => {
try!(self.clone_into(into).chain_error(|| {
human(format!("failed to clone into: {}", into.display()))
}))
}
};
Ok(GitDatabase {
remote: self.clone(),
path: into.to_path_buf(),
... | {
try!(self.fetch_into(&repo).chain_error(|| {
human(format!("failed to fetch into {}", into.display()))
}));
repo
} | conditional_block |
utils.rs | use std::fmt;
use std::path::{Path, PathBuf};
use std::fs::{self, File};
use rustc_serialize::{Encodable, Encoder};
use url::Url;
use git2::{self, ObjectType};
use core::GitReference;
use util::{CargoResult, ChainError, human, ToUrl, internal};
#[derive(PartialEq, Clone, Debug)]
pub struct GitRevision(git2::Oid);
i... | (&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(&self.0, f)
}
}
/// GitRemote represents a remote repository. It gets cloned into a local
/// GitDatabase.
#[derive(PartialEq,Clone,Debug)]
pub struct GitRemote {
url: Url,
}
#[derive(PartialEq,Clone,RustcEncodable)]
struct EncodableGi... | fmt | identifier_name |
utils.rs | use std::fmt;
use std::path::{Path, PathBuf};
use std::fs::{self, File};
use rustc_serialize::{Encodable, Encoder};
use url::Url;
use git2::{self, ObjectType};
use core::GitReference;
use util::{CargoResult, ChainError, human, ToUrl, internal};
#[derive(PartialEq, Clone, Debug)]
pub struct GitRevision(git2::Oid);
i... |
fn is_fresh(&self) -> bool {
match self.repo.revparse_single("HEAD") {
Ok(ref head) if head.id() == self.revision.0 => {
// See comments in reset() for why we check this
fs::metadata(self.location.join(".cargo-ok")).is_ok()
}
_ => false,
... | {
let dirname = into.parent().unwrap();
try!(fs::create_dir_all(&dirname).chain_error(|| {
human(format!("Couldn't mkdir {}", dirname.display()))
}));
if fs::metadata(&into).is_ok() {
try!(fs::remove_dir_all(into).chain_error(|| {
human(format!("... | identifier_body |
utils.rs | use std::fmt;
use std::path::{Path, PathBuf};
use std::fs::{self, File};
use rustc_serialize::{Encodable, Encoder};
use url::Url;
use git2::{self, ObjectType};
use core::GitReference;
use util::{CargoResult, ChainError, human, ToUrl, internal};
#[derive(PartialEq, Clone, Debug)]
pub struct GitRevision(git2::Oid);
i... | // We check the `allowed` types of credentials, and we try to do as much as
// possible based on that:
//
// * Prioritize SSH keys from the local ssh agent as they're likely the most
// reliable. The username here is prioritized from the credential
// callback, then from whatever is configur... | random_line_split | |
getAllTags.ts | import DBPoolManager from "../../manager/DBPoolManager"
import RegionalEntryTagTable, {RegionalEntryTagRecord} from "../../model/db/table/RegionalEntryTagTable"
export function registGetAllTags(server) {
// getメソッドに応答
server.get("/api/getAllTags" ,(request, response, next) => {
DBPoolManager.getInstanc... | */
export default function getAllTags(dbpm: DBPoolManager): Promise<RegionalEntryTagRecord[]> {
const regionalEntryTagTable = new RegionalEntryTagTable(dbpm)
return regionalEntryTagTable.search("0=0")
} | random_line_split | |
getAllTags.ts | import DBPoolManager from "../../manager/DBPoolManager"
import RegionalEntryTagTable, {RegionalEntryTagRecord} from "../../model/db/table/RegionalEntryTagTable"
export function registGetAllTags(server) {
// getメソッドに応答
server.get("/api/getAllTags" ,(request, response, next) => {
DBPoolManager.getInstanc... | RegionalEntryTagTable(dbpm)
return regionalEntryTagTable.search("0=0")
}
| identifier_body | |
getAllTags.ts | import DBPoolManager from "../../manager/DBPoolManager"
import RegionalEntryTagTable, {RegionalEntryTagRecord} from "../../model/db/table/RegionalEntryTagTable"
export function registGetAllTags(server) {
// getメソッドに応答
server.get("/api/getAllTags" ,(request, response, next) => {
DBPoolManager.getInstanc... | ntryTagRecord[]> {
const regionalEntryTagTable = new RegionalEntryTagTable(dbpm)
return regionalEntryTagTable.search("0=0")
}
| <RegionalE | identifier_name |
models.py | import json
from django.contrib.auth.models import User
from django.core.exceptions import ValidationError
from django.urls import reverse
from django.db import models
from django.utils.html import strip_tags
from opaque_keys.edx.django.models import CourseKeyField
from six import text_type
class Note(models.Model):... |
def clean(self, json_body):
"""
Cleans the note object or raises a ValidationError.
"""
if json_body is None:
raise ValidationError('Note must have a body.')
body = json.loads(json_body)
if not isinstance(body, dict):
raise ValidationError('... | app_label = 'notes' | identifier_body |
models.py | import json
from django.contrib.auth.models import User
from django.core.exceptions import ValidationError
from django.urls import reverse
from django.db import models
from django.utils.html import strip_tags
from opaque_keys.edx.django.models import CourseKeyField
from six import text_type
class Note(models.Model):... |
def get_absolute_url(self):
"""
Returns the absolute url for the note object.
"""
kwargs = {'course_id': text_type(self.course_id), 'note_id': str(self.pk)}
return reverse('notes_api_note', kwargs=kwargs)
def as_dict(self):
"""
Returns the note object a... | self.tags = ",".join(tags) | conditional_block |
models.py | import json
from django.contrib.auth.models import User
from django.core.exceptions import ValidationError
from django.urls import reverse
from django.db import models
from django.utils.html import strip_tags
from opaque_keys.edx.django.models import CourseKeyField
from six import text_type
class Note(models.Model):... | (self):
"""
Returns the note object as a dictionary.
"""
return {
'id': self.pk,
'user_id': self.user.pk,
'uri': self.uri,
'text': self.text,
'quote': self.quote,
'ranges': [{
'start': self.range_star... | as_dict | identifier_name |
models.py | import json
from django.contrib.auth.models import User
from django.core.exceptions import ValidationError
from django.urls import reverse | from opaque_keys.edx.django.models import CourseKeyField
from six import text_type
class Note(models.Model):
"""
Stores user Notes for the LMS local Notes service.
.. pii: Legacy model for an app that edx.org hasn't used since 2013
.. pii_types: other
.. pii_retirement: retained
"""
user... | from django.db import models
from django.utils.html import strip_tags | random_line_split |
kv-grid-export.js | /*!
* @package yii2-grid
* @author Kartik Visweswaran <kartikv2@gmail.com>
* @copyright Copyright © Kartik Visweswaran, Krajee.com, 2014 - 2016
* @version 3.1.3
*
* Grid Export Validation Module for Yii's Gridview. Supports export of
* grid data as CSV, HTML, or Excel.
*
* Author: Kartik Visweswara... | else {
msg = (msg1.length && !msg2.length) ? msg1 : '';
}
}
if (msg3.length) {
msg = msg + '\n\n' + msg3;
}
if (isEmpty(msg)) {
return;
}
l... | {
msg = msg2;
} | conditional_block |
kv-grid-export.js | /*!
* @package yii2-grid
* @author Kartik Visweswaran <kartikv2@gmail.com>
* @copyright Copyright © Kartik Visweswaran, Krajee.com, 2014 - 2016
* @version 3.1.3
*
* Grid Export Validation Module for Yii's Gridview. Supports export of
* grid data as CSV, HTML, or Excel.
*
* Author: Kartik Visweswara... | }
};
//GridExport plugin definition
$.fn.gridexport = function (option) {
var args = Array.apply(null, arguments);
args.shift();
return this.each(function () {
var $this = $(this),
data = $this.data('gridexport'),
options = typeof ... | self.download('xls', xls); | random_line_split |
use-pipes.decorator.spec.ts | import { expect } from 'chai';
import { PIPES_METADATA } from '../../constants';
import { UsePipes } from '../../decorators/core/use-pipes.decorator';
import { InvalidDecoratorItemException } from '../../utils/validate-each.util';
class Pipe {
transform() |
}
describe('@UsePipes', () => {
const pipes = [new Pipe(), new Pipe()];
@UsePipes(...pipes)
class Test {}
class TestWithMethod {
@UsePipes(...pipes)
public static test() {}
}
it('should enhance class with expected pipes array', () => {
const metadata = Reflect.getMetadata(PIPES_METADATA, Te... | {} | identifier_body |
use-pipes.decorator.spec.ts | import { expect } from 'chai';
import { PIPES_METADATA } from '../../constants';
import { UsePipes } from '../../decorators/core/use-pipes.decorator';
import { InvalidDecoratorItemException } from '../../utils/validate-each.util';
class Pipe {
transform() {}
}
describe('@UsePipes', () => {
const pipes = [new Pipe... | public static test() {}
}
it('should enhance class with expected pipes array', () => {
const metadata = Reflect.getMetadata(PIPES_METADATA, Test);
expect(metadata).to.be.eql(pipes);
});
it('should enhance method with expected pipes array', () => {
const metadata = Reflect.getMetadata(PIPES_MET... |
class TestWithMethod {
@UsePipes(...pipes) | random_line_split |
use-pipes.decorator.spec.ts | import { expect } from 'chai';
import { PIPES_METADATA } from '../../constants';
import { UsePipes } from '../../decorators/core/use-pipes.decorator';
import { InvalidDecoratorItemException } from '../../utils/validate-each.util';
class | {
transform() {}
}
describe('@UsePipes', () => {
const pipes = [new Pipe(), new Pipe()];
@UsePipes(...pipes)
class Test {}
class TestWithMethod {
@UsePipes(...pipes)
public static test() {}
}
it('should enhance class with expected pipes array', () => {
const metadata = Reflect.getMetadata... | Pipe | identifier_name |
embeddings_test.py | # Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
if __name__ == '__main__':
test.main()
| def test_embedding(self):
with self.test_session():
testing_utils.layer_test(
keras.layers.Embedding,
kwargs={'output_dim': 4,
'input_dim': 10,
'input_length': 2},
input_shape=(3, 2),
input_dtype='int32',
expected_output_dty... | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.