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
merch-display.component.ts
import { Component, OnInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; import { Location } from '@angular/common'; import { Merch } from '../data/merch'; import { MerchService } from '../data/merch.service'; @Component({ selector: 'app-merch-display', templateUrl: './merch-display.co...
( private route: ActivatedRoute, private merchService: MerchService, private location: Location ) {} ngOnInit(): void { navigator.serviceWorker.ready.then( registration => { this._serviceWorker = registration.active; }); this.route.params.subscribe((routeParams) => { this.getMer...
constructor
identifier_name
document.js
/** * Module dependencies. */ var EventEmitter = require('events').EventEmitter , MongooseError = require('./error') , MixedSchema = require('./schema/mixed') , Schema = require('./schema') , ValidatorError = require('./schematype').ValidatorError , utils = require('./utils') , clone = utils.cl...
}); for (var i = 0, l = subpaths.length; i < l; i++) { subpath = subpaths[i]; if (this.isDirectModified(subpath) // earlier prefixes that are already // marked as dirty have precedence || this.get(subpath) === null) { pathToMark = su...
if (parts.length <= 1) { pathToMark = path; } else { subpaths = parts.map(function (part, i) { return parts.slice(0, i).concat(part).join('.');
random_line_split
document.js
/** * Module dependencies. */ var EventEmitter = require('events').EventEmitter , MongooseError = require('./error') , MixedSchema = require('./schema/mixed') , Schema = require('./schema') , ValidatorError = require('./schematype').ValidatorError , utils = require('./utils') , clone = utils.cl...
(instance) { MongooseError.call(this, "Validation failed"); Error.captureStackTrace(this, arguments.callee); this.name = 'ValidationError'; this.errors = instance.errors = {}; }; ValidationError.prototype.toString = function () { return this.name + ': ' + Object.keys(this.errors).map(function (key) ...
ValidationError
identifier_name
document.js
/** * Module dependencies. */ var EventEmitter = require('events').EventEmitter , MongooseError = require('./error') , MixedSchema = require('./schema/mixed') , Schema = require('./schema') , ValidatorError = require('./schematype').ValidatorError , utils = require('./utils') , clone = utils.cl...
; /** * Inherits from MongooseError. */ DocumentError.prototype.__proto__ = MongooseError.prototype; exports.Error = DocumentError;
{ MongooseError.call(this, msg); Error.captureStackTrace(this, arguments.callee); this.name = 'DocumentError'; }
identifier_body
google-apps-script.properties.d.ts
// Type definitions for Google Apps Script 2018-07-11 // Project: https://developers.google.com/apps-script/ // Definitions by: motemen <https://github.com/motemen/> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// <reference path="google-apps-script.types.d.ts" /> declare namespace GoogleAppsSc...
* scriptProperties.setProperty('SERVER_URL', 'http://www.example.com/MyWeatherService/'); * userProperties.setProperty('DISPLAY_UNITS', 'metric'); */ export interface PropertiesService { getDocumentProperties(): Properties; getScriptProperties(): Properties; getUserPropertie...
random_line_split
index.js
/** * Karp Server. * * @author James Koval & Friends <https://github.com/jakl/karp> * @license MIT? * @version 2 * * :shipit: */ "use strict"; // Pollyfil object.values because heroku is running old node.js var reduce = Function.bind.call(Function.call, Array.prototype.reduce); var isEnumerable = Function.bin...
return reduce(keys(O), (v, k) => concat(v, typeof k === 'string' && isEnumerable(O, k) ? [O[k]] : []), []); }; } const express = require('express') const app = express(); const http = require('http').Server(app); const io = require('socket.io')(http); const names = {} app.set('port', (process.env.PORT || 5000));...
var keys = Reflect.ownKeys; if (!Object.values) { Object.values = function values(O) {
random_line_split
main.rs
mod graph; mod index_type; use std::io::{BufReader, BufRead}; use std::fs::File; use std::str::FromStr; use std::fmt::Debug; use std::result::Result; use graph::{MDGraph, WeightType, Unweighted}; use index_type::{IndexType, NodeIndex, EdgeIndex, DefIndex}; fn read_sgf<NodeWt, EdgeWt, NodeIx, EdgeIx, R, I>(rd: &mut R)...
fn main() { let f = File::open("er_100_0_1.sgf").unwrap(); let mut f = BufReader::new(f); // let graph: MDGraph<f32, f32> = read_sgf(&mut f); let graph: MDGraph = read_sgf(&mut f); println!("{:?}", graph); }
{ let mut meta: Option<(bool, usize, usize)> = None; let mut graph = MDGraph::new(); for line in rd.lines() { let line = line.unwrap(); let line = line.trim(); if line.starts_with("#") { // skip comment continue; } if meta.is_none() { ...
identifier_body
main.rs
mod graph; mod index_type; use std::io::{BufReader, BufRead}; use std::fs::File; use std::str::FromStr; use std::fmt::Debug; use std::result::Result; use graph::{MDGraph, WeightType, Unweighted}; use index_type::{IndexType, NodeIndex, EdgeIndex, DefIndex}; fn
<NodeWt, EdgeWt, NodeIx, EdgeIx, R, I>(rd: &mut R) -> MDGraph<NodeWt, EdgeWt, NodeIx, EdgeIx> where NodeWt: WeightType + FromStr<Err = I>, EdgeWt: WeightType + FromStr<Err = I>, NodeIx: IndexType, EdgeIx: IndexType, I: Debug, ...
read_sgf
identifier_name
main.rs
mod graph; mod index_type; use std::io::{BufReader, BufRead}; use std::fs::File; use std::str::FromStr; use std::fmt::Debug; use std::result::Result; use graph::{MDGraph, WeightType, Unweighted}; use index_type::{IndexType, NodeIndex, EdgeIndex, DefIndex}; fn read_sgf<NodeWt, EdgeWt, NodeIx, EdgeIx, R, I>(rd: &mut R)...
_ => { panic!("Invalid format"); } }; if let Some(nw) = node_weight { *graph.get_node_weight_mut(NodeIndex::new(node_id)) = nw; } let edge_s = i.next().unwrap(); for es in edge_s.split(',') ...
{ let mut it = ns.splitn(2, ":"); let node_id: usize = it.next().unwrap().parse().unwrap(); let node_weight: Option<NodeWt> = it.next().map(|s| s.parse().unwrap()); (node_id, node_weight) }
conditional_block
main.rs
mod graph; mod index_type; use std::io::{BufReader, BufRead}; use std::fs::File; use std::str::FromStr; use std::fmt::Debug; use std::result::Result; use graph::{MDGraph, WeightType, Unweighted}; use index_type::{IndexType, NodeIndex, EdgeIndex, DefIndex}; fn read_sgf<NodeWt, EdgeWt, NodeIx, EdgeIx, R, I>(rd: &mut R)...
} if meta.is_none() { // First line is meta let mut m = line.split_whitespace(); let directed = match m.next() { Some("d") => { true } // // Some("u") => { // false ...
let line = line.trim(); if line.starts_with("#") { // skip comment continue;
random_line_split
ua.ts
import Service from '@ember/service'; import UAParser from 'ua-parser-js'; // see https://github.com/duskload/react-device-detect/blob/5d2907feeb5a010bb853bf1b884311fcf18d9883/main.js#L568 function isIPad13() { return ( window.navigator && window.navigator.platform && (window.navigator.platform.indexOf('...
} // DO NOT DELETE: this is how TypeScript knows how to look up your services. declare module '@ember/service' { interface Registry { ua: UA; } }
isAndroid() { return this.uaParser.getOS().name === 'Android'; }
random_line_split
ua.ts
import Service from '@ember/service'; import UAParser from 'ua-parser-js'; // see https://github.com/duskload/react-device-detect/blob/5d2907feeb5a010bb853bf1b884311fcf18d9883/main.js#L568 function isIPad13() { return ( window.navigator && window.navigator.platform && (window.navigator.platform.indexOf('...
} // DO NOT DELETE: this is how TypeScript knows how to look up your services. declare module '@ember/service' { interface Registry { ua: UA; } }
{ return this.uaParser.getOS().name === 'Android'; }
identifier_body
ua.ts
import Service from '@ember/service'; import UAParser from 'ua-parser-js'; // see https://github.com/duskload/react-device-detect/blob/5d2907feeb5a010bb853bf1b884311fcf18d9883/main.js#L568 function isIPad13() { return ( window.navigator && window.navigator.platform && (window.navigator.platform.indexOf('...
() { return this.uaParser.getOS().name === 'Android'; } } // DO NOT DELETE: this is how TypeScript knows how to look up your services. declare module '@ember/service' { interface Registry { ua: UA; } }
isAndroid
identifier_name
forms.py
from django import forms from .models import PassType, Registration class SignupForm(forms.ModelForm): pass_type = forms.ModelChoiceField( queryset=PassType.objects.filter(active=True), widget=forms.widgets.RadioSelect(), ) class Meta: model = Registration fields = ( ...
(self): cleaned_data = super().clean() email = cleaned_data.get("email") email_repeat = cleaned_data.get("email_repeat") ws_partner_email = cleaned_data.get("workshop_partner_email") if email != email_repeat: raise forms.ValidationError("Ensure email verfication matc...
clean
identifier_name
forms.py
from django import forms from .models import PassType, Registration class SignupForm(forms.ModelForm): pass_type = forms.ModelChoiceField( queryset=PassType.objects.filter(active=True), widget=forms.widgets.RadioSelect(), ) class Meta: model = Registration fields = ( ...
return email def clean_agree_to_terms(self): data = self.cleaned_data["agree_to_terms"] if data is False: raise forms.ValidationError("You must agree to the terms.") return data def clean(self): cleaned_data = super().clean() email = cleaned_data.g...
raise forms.ValidationError("Workshop parter already taken.")
conditional_block
forms.py
from django import forms from .models import PassType, Registration class SignupForm(forms.ModelForm): pass_type = forms.ModelChoiceField( queryset=PassType.objects.filter(active=True), widget=forms.widgets.RadioSelect(), ) class Meta: model = Registration fields = ( ...
email_repeat = forms.EmailField() agree_to_terms = forms.BooleanField(required=False) def __init__(self, *args, **kwargs): super(SignupForm, self).__init__(*args, **kwargs) self.fields["pass_type"].empty_label = None self.fields["lunch"].empty_label = None def clean_workshop...
css = {"all": ("css/forms.css",)}
identifier_body
forms.py
from django import forms from .models import PassType, Registration class SignupForm(forms.ModelForm): pass_type = forms.ModelChoiceField( queryset=PassType.objects.filter(active=True), widget=forms.widgets.RadioSelect(), ) class Meta: model = Registration fields = ( ...
"lunch": forms.widgets.RadioSelect(), } class Media: css = {"all": ("css/forms.css",)} email_repeat = forms.EmailField() agree_to_terms = forms.BooleanField(required=False) def __init__(self, *args, **kwargs): super(SignupForm, self).__init__(*args, **kwargs) ...
"workshop_partner_email", "lunch", ) widgets = { "dance_role": forms.widgets.RadioSelect(),
random_line_split
uri.js
/** * uri validator * * @link http://formvalidation.io/validators/uri/ * @author https://twitter.com/formvalidation * @copyright (c) 2013 - 2015 Nguyen Huu Phuoc * @license http://formvalidation.io/license/ */ (function($) { FormValidation.I18n = $.extend(true, FormValidation.I18n || {}, { ...
// Credit to https://gist.github.com/dperini/729294 // // Regular Expression for URL validation // // Author: Diego Perini // Updated: 2010/12/05 // // the regular expression composed & commented // could be ea...
{ return true; }
conditional_block
uri.js
/** * uri validator * * @link http://formvalidation.io/validators/uri/ * @author https://twitter.com/formvalidation * @copyright (c) 2013 - 2015 Nguyen Huu Phuoc * @license http://formvalidation.io/license/ */ (function($) { FormValidation.I18n = $.extend(true, FormValidation.I18n || {}, { ...
"(?:" + // IP address exclusion // private & local networks (allowLocal ? '' : ("(?!(?:10|127)(?:\\.\\d{1,3}){3})" + "(?!(?:169\\.254|192\\.168)(?:\\.\\d{1,3}){2})" ...
(allowEmptyProtocol ? '?' : '') + // user:pass authentication "(?:\\S+(?::\\S*)?@)?" +
random_line_split
json_serializer.py
# Copyright 2014-2016 Morgan Delahaye-Prat. All Rights Reserved. # # Licensed under the Simplified BSD License (the "License"); # you may not use this file except in compliance with the License. """JSON serializer.""" import json from datetime import tzinfo, timedelta class _simple_utc(tzinfo): # pragma: no cover ...
"""Json serializer.""" pretty_print = False if request is not None: pretty_print = request.args.get('_pprint', '').lower() in ('true', '1') indent = None if pretty_print: # pragma: no cover indent = 4 if default is None: default = encoder return json.dumps(obj, ...
def json_serializer(obj, request=None, default=None):
random_line_split
json_serializer.py
# Copyright 2014-2016 Morgan Delahaye-Prat. All Rights Reserved. # # Licensed under the Simplified BSD License (the "License"); # you may not use this file except in compliance with the License. """JSON serializer.""" import json from datetime import tzinfo, timedelta class _simple_utc(tzinfo): # pragma: no cover ...
else: return '%sT00:00:00+00:00' % obj.isoformat() # handle uuid objects if hasattr(obj, 'hex'): return str(obj) # handle serializable objects if hasattr(obj, '__serialize__'): return obj.__serialize__() raise TypeError('%s is not JSON serializable.' % repr(ob...
return obj.replace(tzinfo=_simple_utc()).isoformat()
conditional_block
json_serializer.py
# Copyright 2014-2016 Morgan Delahaye-Prat. All Rights Reserved. # # Licensed under the Simplified BSD License (the "License"); # you may not use this file except in compliance with the License. """JSON serializer.""" import json from datetime import tzinfo, timedelta class _simple_utc(tzinfo): # pragma: no cover ...
def encoder(obj): """Json encoder.""" # handle date[time] objects if hasattr(obj, 'strftime'): if hasattr(obj, 'hour'): return obj.replace(tzinfo=_simple_utc()).isoformat() else: return '%sT00:00:00+00:00' % obj.isoformat() # handle uuid objects if hasattr...
def tzname(self): return "UTC" def utcoffset(self, dt): return timedelta(0)
identifier_body
json_serializer.py
# Copyright 2014-2016 Morgan Delahaye-Prat. All Rights Reserved. # # Licensed under the Simplified BSD License (the "License"); # you may not use this file except in compliance with the License. """JSON serializer.""" import json from datetime import tzinfo, timedelta class
(tzinfo): # pragma: no cover def tzname(self): return "UTC" def utcoffset(self, dt): return timedelta(0) def encoder(obj): """Json encoder.""" # handle date[time] objects if hasattr(obj, 'strftime'): if hasattr(obj, 'hour'): return obj.replace(tzinfo=_simple_...
_simple_utc
identifier_name
border_7_1_5.py
#!/usr/bin/env python # # Copyright (c) 2019, The OpenThread Authors. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # 1. Redistributions of source code must retain the above copyright # notic...
if __name__ == '__main__': unittest.main()
role = HarnessCase.ROLE_BORDER case = '7 1 5' golden_devices_required = 3 def on_dialog(self, dialog, title): pass
identifier_body
border_7_1_5.py
#!/usr/bin/env python # # Copyright (c) 2019, The OpenThread Authors. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # 1. Redistributions of source code must retain the above copyright # notic...
unittest.main()
conditional_block
border_7_1_5.py
#!/usr/bin/env python # # Copyright (c) 2019, The OpenThread Authors. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # 1. Redistributions of source code must retain the above copyright # notic...
unittest.main()
pass if __name__ == '__main__':
random_line_split
border_7_1_5.py
#!/usr/bin/env python # # Copyright (c) 2019, The OpenThread Authors. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # 1. Redistributions of source code must retain the above copyright # notic...
(HarnessCase): role = HarnessCase.ROLE_BORDER case = '7 1 5' golden_devices_required = 3 def on_dialog(self, dialog, title): pass if __name__ == '__main__': unittest.main()
Border_7_1_5
identifier_name
shared.py
# sort def sort(layout, option): # separate layout.separator() # row row = layout.row(align=True) # sub sub = row.row(align=True) # scale x sub.scale_x = 0.2 # sort sub.prop(option, 'sort', toggle=True) # sub sub subsub = sub.row(align=True) # active subsub.ac...
layout.separator() # row row = layout.row(align=True) # sub sub = row.row(align=True) # scale sub.scale_x = 0.2 # sort sub.prop(option, 'count', toggle=True) # sub subsub = sub.row(align=True) # active subsub.active = option.count # icon icon = 'LINKED' if ...
identifier_body
shared.py
# sort def
(layout, option): # separate layout.separator() # row row = layout.row(align=True) # sub sub = row.row(align=True) # scale x sub.scale_x = 0.2 # sort sub.prop(option, 'sort', toggle=True) # sub sub subsub = sub.row(align=True) # active subsub.active = option.so...
sort
identifier_name
shared.py
# sort def sort(layout, option): # separate layout.separator() # row row = layout.row(align=True) # sub sub = row.row(align=True) # scale x sub.scale_x = 0.2 # sort sub.prop(option, 'sort', toggle=True) # sub sub subsub = sub.row(align=True) # active subsub.act...
# sort sub.prop(option, 'count', toggle=True) # sub subsub = sub.row(align=True) # active subsub.active = option.count # icon icon = 'LINKED' if option.link else 'UNLINKED' # link subsub.prop(option, 'link', text='', icon=icon) # pad subsub.prop(option, 'pad', text='...
sub = row.row(align=True) # scale sub.scale_x = 0.2
random_line_split
css.js
/* * Require-CSS RequireJS css! loader plugin * 0.1.8 * Guy Bedford 2014 * MIT */ /* * * Usage: * require(['css!./mycssFile']); * * Tested and working in (up to latest versions as of March 2013): * Android * iOS 6 * IE 6 - 10 * Chome 3 - 26 * Firefox 3.5 - 19 * Opera 10 - 12 * * browserling.com use...
if (ieCnt == 31) { createStyle(); ieCnt = 0; } } var processIeLoad = function() { ieCurCallback(); var nextLoad = ieLoads.shift(); if (!nextLoad) { ieCurCallback = null; return; } ieCurCallback = nextLoad[1]; createIeLoad(nextLoad[0]); } var importLo...
curStyle.onload = function(){ processIeLoad() }; ieCnt++;
random_line_split
derive.py
from collections import namedtuple from constraint import Problem from regparser.tree.depth import markers, rules from regparser.tree.depth.pair_rules import pair_rules from regparser.tree.struct import Node # A paragraph's type, index, depth assignment ParAssignment = namedtuple('ParAssignment', ('typ', 'idx', 'dep...
(self): return iter(self.assignment) def pretty_str(self): return "\n".join(" " * 4 * par.depth + par.typ[par.idx] for par in self.assignment) def _compress_markerless(marker_list): """Remove repeated MARKERLESS markers. This will speed up depth computations as th...
__iter__
identifier_name
derive.py
from collections import namedtuple from constraint import Problem from regparser.tree.depth import markers, rules from regparser.tree.depth.pair_rules import pair_rules from regparser.tree.struct import Node # A paragraph's type, index, depth assignment ParAssignment = namedtuple('ParAssignment', ('typ', 'idx', 'dep...
problem.addVariable(type_var, typ_opts) problem.addVariable(idx_var, idx_opts) problem.addConstraint(rules.type_match(marker), [type_var, idx_var]) all_vars.extend([type_var, idx_var, depth_var]) if idx > 0: pairs = all_vars[3 * (idx - 1):] problem.addCo...
if t[i] == marker]
random_line_split
derive.py
from collections import namedtuple from constraint import Problem from regparser.tree.depth import markers, rules from regparser.tree.depth.pair_rules import pair_rules from regparser.tree.struct import Node # A paragraph's type, index, depth assignment ParAssignment = namedtuple('ParAssignment', ('typ', 'idx', 'dep...
"""Binary search through the markers to find the point at which derive_depths no longer works""" if constraints is None: constraints = [] working, not_working = -1, len(marker_list) while working != not_working - 1: midpoint = (working + not_working) // 2 solutions = derive_dept...
identifier_body
derive.py
from collections import namedtuple from constraint import Problem from regparser.tree.depth import markers, rules from regparser.tree.depth.pair_rules import pair_rules from regparser.tree.struct import Node # A paragraph's type, index, depth assignment ParAssignment = namedtuple('ParAssignment', ('typ', 'idx', 'dep...
if not original_markers: return [] problem = Problem() marker_list = _compress_markerless(original_markers) # Depth in the tree, with an arbitrary limit of 10 problem.addVariables(["depth" + str(i) for i in range(len(marker_list))], range(10)) # Always start a...
additional_constraints = []
conditional_block
saddle-points.rs
extern crate saddle_points; use saddle_points::*; #[test] fn test_identify_single_saddle_point() { let input = vec![vec![9, 8, 7], vec![5, 3, 2], vec![6, 6, 7]]; assert_eq!(vec![(1, 0)], find_saddle_points(&input)); } #[test] #[ignore] fn
() { let input = vec![vec![], vec![], vec![]]; let expected: Vec<(usize, usize)> = Vec::new(); assert_eq!(expected, find_saddle_points(&input)); } #[test] #[ignore] fn test_identify_lack_of_saddle_point() { let input = vec![vec![1, 2, 3], vec![3, 1, 2], vec![2, 3, 1]]; let expected: Vec<(usize, usi...
test_identify_empty_matrix
identifier_name
saddle-points.rs
extern crate saddle_points; use saddle_points::*; #[test] fn test_identify_single_saddle_point() { let input = vec![vec![9, 8, 7], vec![5, 3, 2], vec![6, 6, 7]]; assert_eq!(vec![(1, 0)], find_saddle_points(&input)); } #[test] #[ignore] fn test_identify_empty_matrix() { let input = vec![vec![], vec![], ve...
#[test] #[ignore] fn test_vector_matrix() { let input = vec![vec![1], vec![3], vec![2], vec![3]]; assert_eq!(vec![(0, 0)], find_saddle_points(&input)); }
{ let input = vec![vec![8, 7, 10, 7, 9], vec![8, 7, 13, 7, 9]]; assert_eq!(vec![(0, 2)], find_saddle_points(&input)); }
identifier_body
saddle-points.rs
extern crate saddle_points; use saddle_points::*; #[test] fn test_identify_single_saddle_point() { let input = vec![vec![9, 8, 7], vec![5, 3, 2], vec![6, 6, 7]]; assert_eq!(vec![(1, 0)], find_saddle_points(&input)); } #[test] #[ignore] fn test_identify_empty_matrix() { let input = vec![vec![], vec![], ve...
} #[test] #[ignore] fn test_identify_bottom_right_saddle_point() { let input = vec![vec![8, 7, 9], vec![6, 7, 6], vec![3, 2, 5]]; assert_eq!(vec![(2, 2)], find_saddle_points(&input)); } #[test] #[ignore] fn test_non_square_matrix_high() { let input = vec![vec![1, 5], vec![3, 6], vec![2, 7], vec![3, 8]]; ...
fn test_multiple_saddle_point() { let input = vec![vec![4, 5, 4], vec![3, 5, 5], vec![1, 5, 4]]; assert_eq!(vec![(0, 1), (1, 1), (2, 1)], find_saddle_points(&input));
random_line_split
shared.service.ts
import { Injectable, ViewContainerRef, ComponentFactoryResolver, Output, EventEmitter } from '@angular/core'; import { Util } from './util/util'; @Injectable() export class SharedService { _util: Util; @Output() sendmsg: EventEmitter<any> = new EventEmitter(); constructor(private _resolver: ComponentFactoryRe...
() { return this._util; } isLoggedIn() { return this._util.isLoggedIn(); } getUserId() { return this._util.getUserId(); } validator() { return this._util.validator(); } //data access dataAccess() { return this._util.dataAccess(); } //dom dom() { return this._util.dom...
util
identifier_name
shared.service.ts
import { Injectable, ViewContainerRef, ComponentFactoryResolver, Output, EventEmitter } from '@angular/core'; import { Util } from './util/util'; @Injectable() export class SharedService { _util: Util; @Output() sendmsg: EventEmitter<any> = new EventEmitter(); constructor(private _resolver: ComponentFactoryRe...
return cmp; } util() { return this._util; } isLoggedIn() { return this._util.isLoggedIn(); } getUserId() { return this._util.getUserId(); } validator() { return this._util.validator(); } //data access dataAccess() { return this._util.dataAccess(); } //dom dom() ...
random_line_split
shared.service.ts
import { Injectable, ViewContainerRef, ComponentFactoryResolver, Output, EventEmitter } from '@angular/core'; import { Util } from './util/util'; @Injectable() export class SharedService { _util: Util; @Output() sendmsg: EventEmitter<any> = new EventEmitter(); constructor(private _resolver: ComponentFactoryRe...
addComponent(cmpType: any, config: any = {}, parentEl: ViewContainerRef, idx: number = 0) { //http://stackoverflow.com/questions/39297219/angular2-rc6-dynamically-load-component-from-module let factory = this._resolver.resolveComponentFactory(cmpType); let cmp: any = parentEl.createComponent(factory); ...
{ let cmp: any = this.addComponent(drawer, config, parentEl); if (show) cmp.instance.show(); return cmp; }
identifier_body
dynamic-nav-aid.js
/* * Waltz - Enterprise Architecture * Copyright (C) 2016, 2017, 2018, 2019 Waltz open source project * See README.md for more information * * 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 ...
(svg) { const header = svg .append("g") .classed("dna-header", true); const topBlocks = svg .append("g") .classed("dna-top-blocks", true); return { header, svg, topBlocks }; } function update(sections, model, twe...
prepareGraph
identifier_name
dynamic-nav-aid.js
/* * Waltz - Enterprise Architecture * Copyright (C) 2016, 2017, 2018, 2019 Waltz open source project * See README.md for more information * * 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 ...
controller.$inject = [ "$element", "$window", "ServiceBroker" ]; const component = { template, bindings, controller }; export default { component, id: "waltzDynamicNavAid" };
{ const vm = initialiseData(this, initialState); const svg = select($element.find("svg")[0]); const svgSections = prepareGraph(svg); const render = () => { svgSections.svg .attr("width", baseDimensions.graph.width) .attr("height", baseDimensions.graph.height); ...
identifier_body
dynamic-nav-aid.js
/* * Waltz - Enterprise Architecture * Copyright (C) 2016, 2017, 2018, 2019 Waltz open source project * See README.md for more information * * 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 ...
} function drawBlocks(section, model) { const blocks = section .selectAll(".dna-block") .data(model, d => d.id); // enter const newBlockGs = blocks .enter() .append("g") .classed("dna-block", true) .attr("transform", (d, i) => `translate(${i * 100} 0)`); ...
{ children.each(d => drawNestedBlocks(d)); }
conditional_block
dynamic-nav-aid.js
/* * Waltz - Enterprise Architecture * Copyright (C) 2016, 2017, 2018, 2019 Waltz open source project * See README.md for more information * * 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 ...
vm.$onChanges = () => debouncedRender(); vm.$onDestroy = () => angular .element($window) .off("resize", debouncedRender); } controller.$inject = [ "$element", "$window", "ServiceBroker" ]; const component = { template, bindings, controller }; export default { c...
random_line_split
PasswordInput.tsx
import * as React from 'react'; interface Props { name: string; label: string; onChange: (e: React.ChangeEvent<HTMLInputElement>) => void; onKeyUp: (e: React.KeyboardEvent<HTMLInputElement>) => void; placeholder?: string; maxLength?: number; value?: string; error?: string; } const Pass...
return ( <div className={wrapperClass}> <label htmlFor={props.name}>{props.label}</label> <div className='field'> <input type='password' name={props.name} className='form-control' value={props.value} placeholder={props.placeholder} ...
{ wrapperClass += ' ' + 'has-error'; }
conditional_block
PasswordInput.tsx
import * as React from 'react'; interface Props { name: string; label: string; onChange: (e: React.ChangeEvent<HTMLInputElement>) => void; onKeyUp: (e: React.KeyboardEvent<HTMLInputElement>) => void; placeholder?: string; maxLength?: number; value?: string; error?: string; } const Pass...
); }; export default PasswordInput;
</div>
random_line_split
closure.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
None => {} } let function_type = ty::mk_unboxed_closure(ccx.tcx(), closure_id, ty::ReStatic); let symbol = ccx.tcx().map.with_path(closure_id.node, |path| { mangle_internal_name_by_path_and_seq(pa...
{ debug!("get_or_create_declaration_if_unboxed_closure(): found \ closure"); return Some(*llfn) }
conditional_block
closure.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
(&self, ccx: &CrateContext) -> String { format!("{}({})", self.action, self.datum.to_string(ccx)) } } // Given a closure ty, emits a corresponding tuple ty pub fn mk_closure_tys(tcx: &ty::ctxt, bound_values: &[EnvValue]) -> ty::t { // determine the types of the ...
to_string
identifier_name
closure.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
fn tuplify_box_ty(tcx: &ty::ctxt, t: ty::t) -> ty::t { let ptr = ty::mk_imm_ptr(tcx, ty::mk_i8()); ty::mk_tup(tcx, vec!(ty::mk_uint(), ty::mk_nil_ptr(tcx), ptr, ptr, t)) } fn allocate_cbox<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, store: ty::TraitStore, cda...
{ // determine the types of the values in the env. Note that this // is the actual types that will be stored in the map, not the // logical types as the user sees them, so by-ref upvars must be // converted to ptrs. let bound_tys = bound_values.iter().map(|bv| { match bv.action { ...
identifier_body
closure.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
// // But sometimes, such as when cloning or freeing a closure, we need // to know the full information. That is where the type descriptor // that defines the closure comes in handy. We can use its take and // drop glue functions to allocate/free data as needed. // // ## Subtleties concerning alignment ## // // It is...
// by ptr. The routine Type::at_box().ptr_to() returns an appropriate // type for such an opaque closure; it allows access to the box fields, // but not the closure_data itself.
random_line_split
gdl90.rs
// Pitot - a customizable aviation information receiver // Copyright (C) 2017-2018 Datong Sun (dndx@idndx.com) // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the Lice...
buf[0] = 0x14; buf[1] = match e.addr.1 { AddressType::ADSBICAO | AddressType::ADSRICAO => 0, AddressType::ADSBOther | AddressType::ADSROther => 1, AddressType::TISBICAO => 2, AddressType::TISBOther => 3, _ => 3, // unknown }; ...
} } fn generate_traffic(e: &Target, clock: Instant, pres_alt_valid: bool) -> Payload { let mut buf = [0_u8; 28 + 2]; // incl CRC field
random_line_split
gdl90.rs
// Pitot - a customizable aviation information receiver // Copyright (C) 2017-2018 Datong Sun (dndx@idndx.com) // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the Lice...
(mut d: f32) -> (u8, u8, u8) { d /= LON_LAT_RESOLUTION; let wk = d.round() as i32; ( ((wk & 0xFF0000) >> 16) as u8, ((wk & 0x00FF00) >> 8) as u8, (wk & 0x0000FF) as u8, ) } fn alt_to_gdl90(mut a: f32) -> u16 { if a < -1000_f32 || a > 101350_f32 { 0xFFF } else { ...
latlon_to_gdl90
identifier_name
gdl90.rs
// Pitot - a customizable aviation information receiver // Copyright (C) 2017-2018 Datong Sun (dndx@idndx.com) // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the Lice...
} } impl GDL90 { fn generate_heartbeat(&self, utc: &Tm) -> Payload { let mut buf = [0_u8; 7 + 2]; // incl CRC field buf[0] = 0x00; // type = heartbeat buf[1] = 0x11; // UAT Initialized + ATC Services talkback if self.ownship_valid { buf[1] |= 0x80; } ...
{ self.heartbeat_counter = 0; let utc = handle.get_utc(); handle.push_data(self.generate_heartbeat(&utc)); handle.push_data(GDL90::generate_foreflight_id()); }
conditional_block
gdl90.rs
// Pitot - a customizable aviation information receiver // Copyright (C) 2017-2018 Datong Sun (dndx@idndx.com) // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the Lice...
} impl GDL90 { pub fn new() -> Box<Protocol> { Box::new(GDL90 { ownship_valid: false, heartbeat_counter: 0, ownship_counter: 0, pres_alt_valid: false, }) } } /// Given coordinate in degrees, return the GDL 90 formatted byte sequence /// From: ht...
{ let len = buf.len() - 2; let crc = buf.iter() .take(len) .scan(0_u16, |crc, b| { *crc = CRC16_TABLE[(*crc >> 8) as usize] ^ (*crc << 8) ^ (*b as u16); Some(*crc) }) .last() .unwrap(); buf[len] = (crc ...
identifier_body
diff.py
import logging from .. import exceptions from ..plan import COMPLETE, Plan from ..status import NotSubmittedStatus, NotUpdatedStatus from . import build import difflib import json logger = logging.getLogger(__name__) def diff_dictionaries(old_dict, new_dict): """Diffs two single dimension dictionaries Retu...
return result def _print_new_stack(self, stack, parameters): """Prints out the parameters & stack contents of a new stack""" print "New template parameters:" for param in sorted(parameters, key=lambda param: param['ParameterKey']): print "%s ...
result.append(line + "\n")
conditional_block
diff.py
import logging from .. import exceptions from ..plan import COMPLETE, Plan from ..status import NotSubmittedStatus, NotUpdatedStatus from . import build import difflib import json logger = logging.getLogger(__name__) def diff_dictionaries(old_dict, new_dict): """Diffs two single dimension dictionaries Retu...
def _normalize_json(self, template): """Normalizes our template for diffing Args: template(str): json string representing the template Returns: list: json representation of the parameters """ obj = json.loads(template) json_str = json.dumps(...
The plan is then used to pull the current CloudFormation template from AWS and compare it to the generated templated based on the current config. """
random_line_split
diff.py
import logging from .. import exceptions from ..plan import COMPLETE, Plan from ..status import NotSubmittedStatus, NotUpdatedStatus from . import build import difflib import json logger = logging.getLogger(__name__) def diff_dictionaries(old_dict, new_dict): """Diffs two single dimension dictionaries Retu...
(old_params, new_params): """Compares the old vs. new parameters and prints a "diff" If there are no changes, we print nothing. Args: old_params(dict): old paramters new_params(dict): new parameters Returns: list: A list of differences """ [changes, diff] = diff_dictio...
diff_parameters
identifier_name
diff.py
import logging from .. import exceptions from ..plan import COMPLETE, Plan from ..status import NotSubmittedStatus, NotUpdatedStatus from . import build import difflib import json logger = logging.getLogger(__name__) def diff_dictionaries(old_dict, new_dict):
def print_diff_parameters(parameter_diff): """Handles the printing of differences in parameters. Args: parameter_diff (list): A list dictionaries detailing the differences between two parameters returned by :func:`stacker.actions.diff.diff_dictionaries` """ print """...
"""Diffs two single dimension dictionaries Returns the number of changes and an unordered list expressing the common entries and changes. Args: old_dict(dict): old dictionary new_dict(dict): new dictionary Returns: list() int: number of changed records list: [str(<chan...
identifier_body
test_constructions.py
from collections import OrderedDict import pytest from ucca import textutil from ucca.constructions import CATEGORIES_NAME, DEFAULT, CONSTRUCTIONS, extract_candidates from .conftest import PASSAGES, loaded, loaded_valid, multi_sent, crossing, discontiguous, l1_passage, empty """Tests the constructions module functio...
(create, expected): extract_and_check(create(), constructions=CONSTRUCTIONS, expected=expected) @pytest.mark.parametrize("create", PASSAGES) @pytest.mark.parametrize("constructions", (DEFAULT, [CATEGORIES_NAME]), ids=("default", CATEGORIES_NAME)) def test_extract(create, constructions, monkeypatch): monkeypat...
test_extract_all
identifier_name
test_constructions.py
from collections import OrderedDict import pytest from ucca import textutil from ucca.constructions import CATEGORIES_NAME, DEFAULT, CONSTRUCTIONS, extract_candidates from .conftest import PASSAGES, loaded, loaded_valid, multi_sent, crossing, discontiguous, l1_passage, empty """Tests the constructions module functio...
@pytest.mark.parametrize("create, expected", ( (loaded, {'P': 1, 'remote': 1, 'E': 3, 'primary': 15, 'U': 2, 'F': 1, 'C': 3, 'A': 1, 'D': 1, 'L': 2, 'mwe': 2, 'H': 5, 'implicit': 1, 'main_rel': 1}), (loaded_valid, {'P': 1, 'remote': 1, 'E': 3, 'primary': 15, 'U': 2, 'F': 1, 'C': 3, ...
hist = {c.name: len(e) for c, e in d.items()} assert hist == expected, " != ".join(",".join(sorted(h)) for h in (hist, expected))
conditional_block
test_constructions.py
from collections import OrderedDict import pytest from ucca import textutil from ucca.constructions import CATEGORIES_NAME, DEFAULT, CONSTRUCTIONS, extract_candidates from .conftest import PASSAGES, loaded, loaded_valid, multi_sent, crossing, discontiguous, l1_passage, empty """Tests the constructions module functio...
@pytest.mark.parametrize("create", PASSAGES) @pytest.mark.parametrize("constructions", (DEFAULT, [CATEGORIES_NAME]), ids=("default", CATEGORIES_NAME)) def test_extract(create, constructions, monkeypatch): monkeypatch.setattr(textutil, "get_nlp", assert_spacy_not_loaded) extract_and_check(create(), constructi...
extract_and_check(create(), constructions=CONSTRUCTIONS, expected=expected)
identifier_body
test_constructions.py
from collections import OrderedDict import pytest from ucca import textutil from ucca.constructions import CATEGORIES_NAME, DEFAULT, CONSTRUCTIONS, extract_candidates from .conftest import PASSAGES, loaded, loaded_valid, multi_sent, crossing, discontiguous, l1_passage, empty """Tests the constructions module functio...
@pytest.mark.parametrize("create", PASSAGES) @pytest.mark.parametrize("constructions", (DEFAULT, [CATEGORIES_NAME]), ids=("default", CATEGORIES_NAME)) def test_extract(create, constructions, monkeypatch): monkeypatch.setattr(textutil, "get_nlp", assert_spacy_not_loaded) extract_and_check(create(), constructions...
random_line_split
mock-units.ts
import { Hero } from './hero'; export const HEROES: Hero[] = [ { id: 1, name: "Aragorn Elessar", unique: "Aragorn", points: 260, wargear: ['Heavy Armour', 'Anduril'], options: [ { name: "Armoured Horse", points: 15, } ], rules: [ { name: 'Migh...
Fate: '3', imageUrl: "http://i122.photobucket.com/albums/o262/Viruk_pl/Mitril/borek.jpg~original" }, { id: 5, name: "Madril, Captain of Ithilien", unique: "Madril", points: 55, wargear: ['Armour', 'Bow'], rules: [ { name: 'Master of Ambush', explanation: ` ...
Courage: '6', Might: '6', Will: '3',
random_line_split
unique-send-2.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
let mut actual = 0u; for uint::range(0u, n) |_i| { let j = p.recv(); actual += *j; } assert!(expected == actual); }
random_line_split
unique-send-2.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
() { let (p, ch) = stream(); let ch = SharedChan(ch); let n = 100u; let mut expected = 0u; for uint::range(0u, n) |i| { let ch = ch.clone(); task::spawn(|| child(&ch, i) ); expected += i; } let mut actual = 0u; for uint::range(0u, n) |_i| { let j = p.recv...
main
identifier_name
unique-send-2.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
pub fn main() { let (p, ch) = stream(); let ch = SharedChan(ch); let n = 100u; let mut expected = 0u; for uint::range(0u, n) |i| { let ch = ch.clone(); task::spawn(|| child(&ch, i) ); expected += i; } let mut actual = 0u; for uint::range(0u, n) |_i| { l...
{ c.send(~i); }
identifier_body
run_swarming_xcode_install.py
#!/usr/bin/env python # Copyright 2017 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. """ This script runs swarming_xcode_install on the bots. It should be run when we need to upgrade all the swarming testers. It: 1) ...
sys.exit(main())
conditional_block
run_swarming_xcode_install.py
#!/usr/bin/env python # Copyright 2017 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. """ This script runs swarming_xcode_install on the bots. It should be run when we need to upgrade all the swarming testers. It: 1) ...
sys.executable, os.path.join(luci_tools, 'run_on_bots.py'), '--swarming', args.swarming_server, '--isolate-server', args.isolate_server, '--priority', '20', '--batches', str(args.batches), '--tags', 'name:run_swarming_xcode_install', ] + dim_args + ['--name', 'run_swarming_xcode_install', '-...
dim_args = [] for d in dimensions: dim_args += ['--dimension'] + d cmd = [
random_line_split
run_swarming_xcode_install.py
#!/usr/bin/env python # Copyright 2017 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. """ This script runs swarming_xcode_install on the bots. It should be run when we need to upgrade all the swarming testers. It: 1) ...
(): parser = argparse.ArgumentParser( description='Run swarming_xcode_install on the bots.') parser.add_argument('--luci_path', required=True, type=os.path.abspath) parser.add_argument('--swarming-server', required=True, type=str) parser.add_argument('--isolate-server', required=True, type=str) parser.a...
main
identifier_name
run_swarming_xcode_install.py
#!/usr/bin/env python # Copyright 2017 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. """ This script runs swarming_xcode_install on the bots. It should be run when we need to upgrade all the swarming testers. It: 1) ...
if __name__ == '__main__': sys.exit(main())
parser = argparse.ArgumentParser( description='Run swarming_xcode_install on the bots.') parser.add_argument('--luci_path', required=True, type=os.path.abspath) parser.add_argument('--swarming-server', required=True, type=str) parser.add_argument('--isolate-server', required=True, type=str) parser.add_arg...
identifier_body
lib.rs
// ================================================================= // // * WARNING * // // This file is generated! // // Changes made to this file will be overwritten. If changes are // required to the generated code, the service_crategen project // must be updated to g...
mod custom; mod generated; pub use custom::*; pub use generated::*;
)] //! <p>AWS Cloud Map lets you configure public DNS, private DNS, or HTTP namespaces that your microservice applications run in. When an instance of the service becomes available, you can call the AWS Cloud Map API to register the instance with AWS Cloud Map. For public or private DNS namespaces, AWS Cloud Map automa...
random_line_split
movie_base.py
#coding: utf-8 import numpy as np class MovieBase(): def read_from_csv(self, file_path): f = open(file_path, 'r') self.matrix = np.loadtxt(f, delimiter=',') self.shape = self.matrix.shape f.close() def get_user_unseen_films(self, user_idx): if user_idx >= self.shape[...
def build_aspect_matrices(self): # user-aspect = Uk * sqrt(Sk) self.user_aspect = self.U_k.dot(np.sqrt(self.S_k)) # movie-aspect = sqrt(Sk) * Vk_t self.movie_aspect = np.sqrt(self.S_k).dot(self.Vk_t) print self.user_aspect print self.movie_aspect def get_pred...
self.U_k = self.U[:,range(k)] self.S_k = np.diag(self._S[:k]) self._S_k = np.diag(self.S_k) self.Vk_t = self.V_t[range(k)] self.R_k = self.U_k.dot(self.S_k).dot(self.Vk_t)
identifier_body
movie_base.py
#coding: utf-8 import numpy as np class MovieBase(): def read_from_csv(self, file_path): f = open(file_path, 'r') self.matrix = np.loadtxt(f, delimiter=',') self.shape = self.matrix.shape f.close() def
(self, user_idx): if user_idx >= self.shape[1]: raise ValueError(u"Matrix only has {} rows. Cannot access row {}".format(self.shape[0], user_idx)) return [i for i, rating in enumerate(self.matrix[user_idx]) if rating == 0] def normalize_base(self): self.user_means = self._get_u...
get_user_unseen_films
identifier_name
movie_base.py
#coding: utf-8 import numpy as np class MovieBase(): def read_from_csv(self, file_path): f = open(file_path, 'r') self.matrix = np.loadtxt(f, delimiter=',') self.shape = self.matrix.shape f.close() def get_user_unseen_films(self, user_idx): if user_idx >= self.shape[...
# print "_Sk: {}".format(_Sk) # print "Vk_t: {}".format(Vk_t)
random_line_split
movie_base.py
#coding: utf-8 import numpy as np class MovieBase(): def read_from_csv(self, file_path): f = open(file_path, 'r') self.matrix = np.loadtxt(f, delimiter=',') self.shape = self.matrix.shape f.close() def get_user_unseen_films(self, user_idx): if user_idx >= self.shape[...
# l_r_appr = np.zeros(self.shape) # for i in range(k): # l_r_appr += self._S[i] * np.dot(self.U.transpose()[i], self.V_t[:,i]) # print l_r_appr # Uk, _Sk, Vk_t = np.linalg.svd(l_r_appr, full_matrices=True) # print "Uk: {}".format(Uk) # print "_Sk: {}".f...
for movie in movie_list: prediction = self.get_prediction(user=user, movie=movie) print "Prediction for user {} and movie {}: {}".format(user, movie, prediction)
conditional_block
template.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """Template""" from os import path import jinja2 from jinja2 import FileSystemLoader, ChoiceLoader from jinja2.exceptions import TemplateNotFound import peanut from peanut.utils import get_resource class SmartLoader(FileSystemLoader): """A smart template loader"""...
"""Render template with name and context """ template = self.env.get_template(name) return template.render(**context)
identifier_body
template.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """Template""" from os import path import jinja2 from jinja2 import FileSystemLoader, ChoiceLoader from jinja2.exceptions import TemplateNotFound import peanut from peanut.utils import get_resource class SmartLoader(FileSystemLoader): """A smart template loader"""...
for extension in SmartLoader.available_extension: try: filename = template + extension return super(SmartLoader, self).get_source(environment, filename) except TemplateNotFound: pass raise TemplateNotFound(template) class Templ...
return super(SmartLoader, self).get_source(environment, template)
conditional_block
template.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """Template""" from os import path import jinja2 from jinja2 import FileSystemLoader, ChoiceLoader from jinja2.exceptions import TemplateNotFound import peanut from peanut.utils import get_resource class SmartLoader(FileSystemLoader): """A smart template loader"""
available_extension = ['.html', '.xml'] def get_source(self, environment, template): if template is None: raise TemplateNotFound(template) if '.' in template: return super(SmartLoader, self).get_source(environment, template) for extension in SmartLoader.availabl...
random_line_split
template.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """Template""" from os import path import jinja2 from jinja2 import FileSystemLoader, ChoiceLoader from jinja2.exceptions import TemplateNotFound import peanut from peanut.utils import get_resource class SmartLoader(FileSystemLoader): """A smart template loader"""...
(self, environment, template): if template is None: raise TemplateNotFound(template) if '.' in template: return super(SmartLoader, self).get_source(environment, template) for extension in SmartLoader.available_extension: try: filename = templa...
get_source
identifier_name
index.js
/** * Copyright (C) 2006-2020 Talend Inc. - www.talend.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required...
(req, res) { res.json(configuration); } function downloadZip(req, res) { const data = atob(req.body.project); console.log(data); const options = { root: `${__dirname}/../public/`, dotfiles: 'deny', headers: { 'x-timestamp': Date.now(), 'x-sent': true, }, }; const fileName = 'example.zip'; res.sen...
getConfiguration
identifier_name
index.js
/** * Copyright (C) 2006-2020 Talend Inc. - www.talend.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required...
module.exports = setup;
{ app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); app.get('/api/project/configuration', getConfiguration); app.post('/api/project/zip/form', downloadZip); app.post('/api/project/openapi/zip/form', downloadZip); app.post('/api/project/github', createOnGithub); }
identifier_body
index.js
/** * Copyright (C) 2006-2020 Talend Inc. - www.talend.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License.
* * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the ...
* You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0
random_line_split
index.js
/** * Copyright (C) 2006-2020 Talend Inc. - www.talend.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required...
else { console.log('Sent:', fileName); } }); } function createOnGithub(req, res) { console.log(req.body); res.json({ success: true }); } function setup(app) { app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); app.get('/api/project/configuration', getConfiguration); app.post(...
{ res.status(500).send(err); }
conditional_block
StartDialog.ts
/// <reference path="../Dialogs/DialogAction.ts" /> @DialogActionClass class StartDialog extends ActionClass { public Display(id: number, values: string[], updateFunction?: string): string { var html = "";
public Execute(values: string[], env?: CodeEnvironement): void { if (!this.Execute.caller) { play.devTools = true; world.Player.InformServer(); return; } if (!values[0]) throw "The action 'Start Dialog' requires a NPC name."; ...
html += this.Label("NPC"); html += this.OptionList(id, 0, world.NPCs.map(c => c.Name).sort(), values[0], updateFunction); return html; }
random_line_split
StartDialog.ts
/// <reference path="../Dialogs/DialogAction.ts" /> @DialogActionClass class StartDialog extends ActionClass { public Display(id: number, values: string[], updateFunction?: string): string { var html = ""; html += this.Label("NPC"); html += this.OptionList(id, 0, world.NPCs.map(c => c....
if (!values[0]) throw "The action 'Start Dialog' requires a NPC name."; var npcName = values[0]; npc.Dialogs = world.GetNPC(npcName).Dialogs; npc.currentNPC = world.GetNPC(npcName); world.Player.InDialog = true; $("#npcDialog").show(); $("#npcDialog ...
play.devTools = true; world.Player.InformServer(); return; }
conditional_block
StartDialog.ts
/// <reference path="../Dialogs/DialogAction.ts" /> @DialogActionClass class StartDialog extends ActionClass { public Di
d: number, values: string[], updateFunction?: string): string { var html = ""; html += this.Label("NPC"); html += this.OptionList(id, 0, world.NPCs.map(c => c.Name).sort(), values[0], updateFunction); return html; } public Execute(values: string[], env?: CodeEnvironement): v...
splay(i
identifier_name
test_observatory_negotiation.py
#from interface.services.icontainer_agent import ContainerAgentClient #from pyon.ion.endpoint import ProcessRPCClient from pyon.public import Container, log, IonObject from pyon.util.containers import DotDict from pyon.util.int_test import IonIntegrationTestCase from interface.services.coi.iresource_registry_service i...
(LocalContextMixin): name = '' @attr('INT', group='sa') @unittest.skip('capabilities not yet available') class TestObservatoryNegotiation(IonIntegrationTestCase): def setUp(self): # Start container self._start_container() self.container.start_rel_from_url('res/deploy/r2deploy.yml') ...
FakeProcess
identifier_name
test_observatory_negotiation.py
#from interface.services.icontainer_agent import ContainerAgentClient #from pyon.ion.endpoint import ProcessRPCClient from pyon.public import Container, log, IonObject from pyon.util.containers import DotDict from pyon.util.int_test import IonIntegrationTestCase from interface.services.coi.iresource_registry_service i...
@attr('INT', group='sa') @unittest.skip('capabilities not yet available') class TestObservatoryNegotiation(IonIntegrationTestCase): def setUp(self): # Start container self._start_container() self.container.start_rel_from_url('res/deploy/r2deploy.yml') self.rrclient = ResourceReg...
name = ''
identifier_body
test_observatory_negotiation.py
#from interface.services.icontainer_agent import ContainerAgentClient #from pyon.ion.endpoint import ProcessRPCClient from pyon.public import Container, log, IonObject from pyon.util.containers import DotDict from pyon.util.int_test import IonIntegrationTestCase from interface.services.coi.iresource_registry_service i...
@attr('INT', group='sa') @unittest.skip('capabilities not yet available') class TestObservatoryNegotiation(IonIntegrationTestCase): def setUp(self): # Start container self._start_container() self.container.start_rel_from_url('res/deploy/r2deploy.yml') self.rrclient = ResourceRegist...
random_line_split
development.js
'use strict'; module.exports = { db: 'mongodb://localhost/qaapp-dev', //db: 'mongodb://nodejitsu:e0b737c9d532fc27e1e753a25a4f823e@troup.mongohq.com:10001/nodejitsudb3924701379', mongoose: { debug: true }, app: { name: 'AskOn' }, facebook: { clientID: 'DEFAULT_APP_ID', clientSecret: 'APP_S...
mailer: { service: 'SERVICE_PROVIDER', // Gmail, SMTP auth: { user: 'EMAIL_ID', pass: 'PASSWORD' } } };
clientID: 'DEFAULT_API_KEY', clientSecret: 'SECRET_KEY', callbackURL: 'http://localhost:3000/auth/linkedin/callback' }, emailFrom: 'SENDER EMAIL ADDRESS', // sender address like ABC <abc@example.com>
random_line_split
secret_hash.py
##### import sys import inspect from pylons import config import logging import zkpylons.lib.helpers as h from pylons import request, response, session, tmpl_context as c from zkpylons.lib.helpers import redirect_to from pylons.util import class_name_from_module_name from zkpylons.model import meta from pylons.control...
# as per http://www.mail-archive.com/pylons-discuss@googlegroups.com/msg06643.html def transfer(controller = None, action = None, url = None, **kwargs): """usage: 1. result = transfer(url = "/someurl/someaction") 2. result = transfer(controller = "/controller1/sub_controller2", ac...
c.hash = URLHash.find_by_hash(hash) if c.hash is None: abort(404, "Sorry, Invalid Hash.") return self.transfer(url=c.hash.url)
identifier_body
secret_hash.py
##### import sys import inspect from pylons import config import logging import zkpylons.lib.helpers as h from pylons import request, response, session, tmpl_context as c from zkpylons.lib.helpers import redirect_to from pylons.util import class_name_from_module_name from zkpylons.model import meta from pylons.control...
# if del(match_route["controller"]) del(match_route["action"]) kwargs.update(match_route) else: controller = controller.replace("/", ".") if (action == None): action = "index" ...
action = match_route["action"]
conditional_block
secret_hash.py
##### import sys import inspect from pylons import config import logging import zkpylons.lib.helpers as h from pylons import request, response, session, tmpl_context as c from zkpylons.lib.helpers import redirect_to from pylons.util import class_name_from_module_name from zkpylons.model import meta from pylons.control...
# if if (hasattr(controller_inst, "__before__")): before_method = getattr(controller_inst, "__before__", None) #if (isinstance(before_method, types.MethodType)): # before_method(action) # if # if action_ar...
#if (not isinstance(action_method, types.MethodType)): # raise(NotImplementedError("action '%s' not found in '%s'" % (action, controller)))
random_line_split
secret_hash.py
##### import sys import inspect from pylons import config import logging import zkpylons.lib.helpers as h from pylons import request, response, session, tmpl_context as c from zkpylons.lib.helpers import redirect_to from pylons.util import class_name_from_module_name from zkpylons.model import meta from pylons.control...
(controller = None, action = None, url = None, **kwargs): """usage: 1. result = transfer(url = "/someurl/someaction") 2. result = transfer(controller = "/controller1/sub_controller2", action = "test") # kwargs will pass to action. """ if (url != None): route_map...
transfer
identifier_name
TagsServiceSpec.js
/* Copyright 2013-2016 Extended Mind Technologies Oy * * 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 applicab...
expect(tags[0].title).toBe('email'); expect(tags[1].title).toBe('secret'); expect(tags[2].title).toBe('home'); }); it('should find tag by uuid', function () { expect(TagsService.getTagInfo('81daf688-d34d-4551-9a24-564a5861ace9', testOwnerUUID).tag) .toBeDefined(); }); it('should not find t...
// Tags should be in modified order
random_line_split
storage.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::StorageBinding; use dom::bindings::codegen::Bindings::StorageBinding::Storag...
(&self, name: DOMString, value: DOMString) { self.SetItem(name, value); } fn NamedDeleter(&self, name: DOMString) { self.RemoveItem(name); } fn SupportedPropertyNames(&self) -> Vec<DOMString> { // FIXME: unimplemented (https://github.com/servo/servo/issues/7273) vec![] ...
NamedCreator
identifier_name
storage.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::StorageBinding; use dom::bindings::codegen::Bindings::StorageBinding::Storag...
reflect_dom_object(box Storage::new_inherited(global, storage_type), *global, StorageBinding::Wrap) } fn get_url(&self) -> Url { let global_root = self.global.root(); let global_ref = global_root.r(); global_ref.get_url() } fn get_storage_task(&self) -> StorageTask { ...
pub fn new(global: &GlobalRef, storage_type: StorageType) -> Root<Storage> {
random_line_split
storage.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::StorageBinding; use dom::bindings::codegen::Bindings::StorageBinding::Storag...
} // https://html.spec.whatwg.org/multipage/#dom-storage-clear fn Clear(&self) { let (sender, receiver) = ipc::channel().unwrap(); self.get_storage_task().send(StorageTaskMsg::Clear(sender, self.get_url(), self.storage_type)).unwrap(); if receiver.recv().unwrap() { sel...
{ self.broadcast_change_notification(Some(name), Some(old_value), None); }
conditional_block
storage.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::StorageBinding; use dom::bindings::codegen::Bindings::StorageBinding::Storag...
// https://html.spec.whatwg.org/multipage/#dom-storage-clear fn Clear(&self) { let (sender, receiver) = ipc::channel().unwrap(); self.get_storage_task().send(StorageTaskMsg::Clear(sender, self.get_url(), self.storage_type)).unwrap(); if receiver.recv().unwrap() { self.broa...
{ let (sender, receiver) = ipc::channel().unwrap(); let msg = StorageTaskMsg::RemoveItem(sender, self.get_url(), self.storage_type, name.clone()); self.get_storage_task().send(msg).unwrap(); if let Some(old_value) = receiver.recv().unwrap() { self.broadcast_change_notificati...
identifier_body