file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
12.1k
suffix
large_stringlengths
0
12k
middle
large_stringlengths
0
7.51k
fim_type
large_stringclasses
4 values
media-change.ts
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license
export type MediaQuerySubscriber = (changes: MediaChange) => void; /** * Class instances emitted [to observers] for each mql notification */ export class MediaChange { property: string; value: any; constructor(public matches = false, // Is the mq currently activated public mediaQuery = 'al...
*/
random_line_split
media-change.ts
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ export type MediaQuerySubscriber = (changes: MediaChange) => void; /** * Class instances emitted [to observers] for ...
clone() { return new MediaChange(this.matches, this.mediaQuery, this.mqAlias, this.suffix); } }
{ }
identifier_body
media-change.ts
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ export type MediaQuerySubscriber = (changes: MediaChange) => void; /** * Class instances emitted [to observers] for ...
(public matches = false, // Is the mq currently activated public mediaQuery = 'all', // e.g. (min-width: 600px) and (max-width: 959px) public mqAlias = '', // e.g. gt-sm, md, gt-lg public suffix = '' // e.g. GtSM, Md, GtLg ) { } clone() {...
constructor
identifier_name
types.ts
undefined; loadingErrorType: ShoppingCartError | undefined; isPendingUpdate: boolean; responseCart: ResponseCart; couponStatus: CouponStatus; } type WaitForReady = () => Promise< ResponseCart >; export type ShoppingCartManagerGetState = () => ShoppingCartManagerState; export interface ShoppingCartManager { get...
tax_collected_integer: number; tax_collected_display: string; label?: string; rate: number; rate_display: string; } /** * Local schema for response cart that can contain incomplete products. This * schema is only used inside the reducer and will only differ from a * ResponseCart if the cacheStatus is invalid. ...
random_line_split
editable_table_row.js
Spree.Views.Tables.EditableTableRow = Backbone.View.extend({ events: { "select2-open": "onEdit", "focus input": "onEdit", "click [data-action=save]": "onSave", "click [data-action=cancel]": "onCancel", 'keyup input': 'onKeypress' }, onEdit: function(e) { if (this.$el.hasClass('editing')) ...
} } });
break; case this.ESC_KEY: this.onCancel(e); break;
random_line_split
test_power.py
from __future__ import division import numpy as np from numpy.testing import assert_almost_equal import pytest from acoustics.power import lw_iso3746 @pytest.mark.parametrize("background_noise, expected", [ (79, 91.153934187), (83, 90.187405234), (88, 88.153934187), ]) def test_lw_iso3746(background_no...
LpAi = np.array([90, 90, 90, 90]) LpAiB = background_noise * np.ones(4) S = 10 alpha = np.array([0.1, 0.1, 0.1, 0.1, 0.1, 0.1]) surfaces = np.array([10, 10, 10, 10, 10, 10]) calculated = lw_iso3746(LpAi, LpAiB, S, alpha, surfaces) assert_almost_equal(calculated, expected)
identifier_body
test_power.py
from __future__ import division import numpy as np from numpy.testing import assert_almost_equal import pytest from acoustics.power import lw_iso3746 @pytest.mark.parametrize("background_noise, expected", [ (79, 91.153934187), (83, 90.187405234), (88, 88.153934187), ]) def
(background_noise, expected): LpAi = np.array([90, 90, 90, 90]) LpAiB = background_noise * np.ones(4) S = 10 alpha = np.array([0.1, 0.1, 0.1, 0.1, 0.1, 0.1]) surfaces = np.array([10, 10, 10, 10, 10, 10]) calculated = lw_iso3746(LpAi, LpAiB, S, alpha, surfaces) assert_almost_equal(calculated,...
test_lw_iso3746
identifier_name
test_power.py
from __future__ import division import numpy as np
import pytest from acoustics.power import lw_iso3746 @pytest.mark.parametrize("background_noise, expected", [ (79, 91.153934187), (83, 90.187405234), (88, 88.153934187), ]) def test_lw_iso3746(background_noise, expected): LpAi = np.array([90, 90, 90, 90]) LpAiB = background_noise * np.ones(4) ...
from numpy.testing import assert_almost_equal
random_line_split
efs.py
from troposphere import Tags,FindInMap, Ref, Template, Parameter,ImportValue, Ref, Output from troposphere.efs import FileSystem, MountTarget from troposphere.ec2 import SecurityGroup, SecurityGroupRule, Instance, Subnet from create import export_ref, import_ref from create.network import AclFactory, assoc_nacl_subnet ...
efs_subnet=Subnet( title='{}{}{}{}'.format(ops.app_name, stack_name, "MountTargetSubnet", k.split("-")[-1]), AvailabilityZone=k, CidrBlock=v, VpcId=vpc_id, Tags=Tags(Name='{}-{}-{}-{}'.format(ops.app_name, stack_name, "MountTargetSubnet", k.split("-")[-1])) ...
conditional_block
efs.py
from troposphere import Tags,FindInMap, Ref, Template, Parameter,ImportValue, Ref, Output from troposphere.efs import FileSystem, MountTarget from troposphere.ec2 import SecurityGroup, SecurityGroupRule, Instance, Subnet from create import export_ref, import_ref from create.network import AclFactory, assoc_nacl_subnet ...
# EFS FS Security Groups efs_security_group=SecurityGroup( title=efs_sg, GroupDescription='Allow Access', VpcId=vpc_id, Tags=Tags(Name=efs_sg) ) template.add_resource(efs_security_group) export_ref(template, efs_sg, value=Ref(efs_sg), desc="Export for EFS Security Gro...
export_ref(template, '{}{}{}'.format(ops.app_name,stack_name,"Endpoint"), value=Ref(efs_fs), desc="Endpoint for EFS FileSystem")
random_line_split
efs.py
from troposphere import Tags,FindInMap, Ref, Template, Parameter,ImportValue, Ref, Output from troposphere.efs import FileSystem, MountTarget from troposphere.ec2 import SecurityGroup, SecurityGroupRule, Instance, Subnet from create import export_ref, import_ref from create.network import AclFactory, assoc_nacl_subnet ...
(template, ops, app_cfn_options, stack_name, stack_setup): # Variable Declarations vpc_id=ops.get('vpc_id') efs_sg = app_cfn_options.network_names['tcpstacks'][stack_name]['sg_name'] efs_acl = app_cfn_options.network_names['tcpstacks'][stack_name]['nacl_name'] # Create EFS FIleSystem efs_fs=Fi...
efs_setup
identifier_name
efs.py
from troposphere import Tags,FindInMap, Ref, Template, Parameter,ImportValue, Ref, Output from troposphere.efs import FileSystem, MountTarget from troposphere.ec2 import SecurityGroup, SecurityGroupRule, Instance, Subnet from create import export_ref, import_ref from create.network import AclFactory, assoc_nacl_subnet ...
) template.add_resource(efs_security_group) export_ref(template, efs_sg, value=Ref(efs_sg), desc="Export for EFS Security Group") # Create Network ACL for EFS Stack efs_nacl = AclFactory( template, name=efs_acl, vpc_id=ops.vpc_id, in_networks=[val for key, val in sor...
vpc_id=ops.get('vpc_id') efs_sg = app_cfn_options.network_names['tcpstacks'][stack_name]['sg_name'] efs_acl = app_cfn_options.network_names['tcpstacks'][stack_name]['nacl_name'] # Create EFS FIleSystem efs_fs=FileSystem( title='{}{}'.format(ops.app_name, stack_name), FileSystemTags=Tags...
identifier_body
event.py
""" sentry.models.event ~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2010-2014 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ from __future__ import absolute_import import warnings from collections import OrderedDict from django.db import models from django.utils import tim...
ident = self.ip_address if ident: return 'ip:%s' % (ident,) return None def get_interfaces(self): result = [] for key, data in self.data.iteritems(): try: cls = get_interface(key) except ValueError: conti...
ident = user_data.get('id') if ident: return 'id:%s' % (ident,) ident = user_data.get('email') if ident: return 'email:%s' % (ident,) ident = user_data.get('username') if ident: return 'username:%s' % (ident,)
conditional_block
event.py
""" sentry.models.event ~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2010-2014 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ from __future__ import absolute_import import warnings from collections import OrderedDict from django.db import models from django.utils import tim...
@memoize def ip_address(self): user_data = self.data.get('sentry.interfaces.User') if user_data: value = user_data.get('ip_address') if value: return value http_data = self.data.get('sentry.interfaces.Http') if http_data and 'env' in http_...
return self.data.get('version', '5')
random_line_split
event.py
""" sentry.models.event ~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2010-2014 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ from __future__ import absolute_import import warnings from collections import OrderedDict from django.db import models from django.utils import tim...
(self): warnings.warn('Event.checksum is no longer used', DeprecationWarning) return ''
checksum
identifier_name
event.py
""" sentry.models.event ~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2010-2014 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ from __future__ import absolute_import import warnings from collections import OrderedDict from django.db import models from django.utils import tim...
verbose_name = _('message') verbose_name_plural = _('messages') unique_together = (('project', 'event_id'),) index_together = (('group', 'datetime'),) __repr__ = sane_repr('project_id', 'group_id') def error(self): message = strip(self.message) if not message: ...
""" An individual event. """ __core__ = False group = FlexibleForeignKey('sentry.Group', blank=True, null=True, related_name="event_set") event_id = models.CharField(max_length=32, null=True, db_column="message_id") project = FlexibleForeignKey('sentry.Project', null=True) message = models....
identifier_body
diagnose.py
import re import json from subprocess import call, Popen, PIPE def init_parser(parser): parser.add_argument('name', type=str, help='Cluster name.') parser.add_argument('--dest', '-d', required=True, type=str, help="Directory for diagnose output -- must be local.") parser.add_argument('--hail-log', '-l', r...
if not args.no_diagnose: diagnose_tar_path = re.search(r'Diagnostic results saved in: (?P<tarfile>gs://\S+diagnostic\.tar)', str(Popen('gcloud dataproc clusters diagnose {name}'.format(name=args.name), shell=True, ...
init_cmd = ['mkdir -p {tmp}; rm -r {tmp}/*'.format(tmp=tmp)] copy_tmp_cmds = ['sudo cp -r {file} {tmp}'.format(file=file, tmp=tmp) for file in files] copy_tmp_cmds.append('sudo chmod -R 777 {tmp}'.format(tmp=tmp)) if args.compress: copy_tmp_cmds.append('sudo find ' + tmp + ' -type ...
identifier_body
diagnose.py
import re import json
def init_parser(parser): parser.add_argument('name', type=str, help='Cluster name.') parser.add_argument('--dest', '-d', required=True, type=str, help="Directory for diagnose output -- must be local.") parser.add_argument('--hail-log', '-l', required=False, type=str, default='/home/hail/hail.log', ...
from subprocess import call, Popen, PIPE
random_line_split
diagnose.py
import re import json from subprocess import call, Popen, PIPE def init_parser(parser): parser.add_argument('name', type=str, help='Cluster name.') parser.add_argument('--dest', '-d', required=True, type=str, help="Directory for diagnose output -- must be local.") parser.add_argument('--hail-log', '-l', r...
(args, pass_through_args): # pylint: disable=unused-argument print("Diagnosing cluster '{}'...".format(args.name)) is_local = not args.dest.startswith("gs://") if args.overwrite: if is_local: call('rm -r {dir}'.format(dir=args.dest), shell=True) else: call('gsutil ...
main
identifier_name
diagnose.py
import re import json from subprocess import call, Popen, PIPE def init_parser(parser): parser.add_argument('name', type=str, help='Cluster name.') parser.add_argument('--dest', '-d', required=True, type=str, help="Directory for diagnose output -- must be local.") parser.add_argument('--hail-log', '-l', r...
call(gcloud_ssh(remote, '; '.join(init_cmd + copy_tmp_cmds)), shell=True) if not is_local: copy_dest_cmd = gcloud_ssh(remote, 'gsutil -m cp -r {tmp} {dest}'.format(tmp=tmp, dest=dest)) else: copy_dest_cmd = gcloud_copy_files(remote, tmp, dest) call(copy_dest_c...
copy_tmp_cmds.append('sudo find ' + tmp + ' -type f ! -name \'*.gz\' -exec gzip "{}" \\;')
conditional_block
users.py
""" Page classes to test either the Course Team page or the Library Team page. """ from bok_choy.promise import EmptyPromise from bok_choy.page_object import PageObject from ...tests.helpers import disable_animations from . import BASE_URL def wait_for_ajax_or_reload(browser): """ Wait for all ajax requests t...
""" Is the "New Team Member" button present? """ return self.q(css='.create-user-button').present def click_add_button(self): """ Click on the "New Team Member" button """ self.q(css='.create-user-button').click() @property def new_user_form_...
random_line_split
users.py
""" Page classes to test either the Course Team page or the Library Team page. """ from bok_choy.promise import EmptyPromise from bok_choy.page_object import PageObject from ...tests.helpers import disable_animations from . import BASE_URL def wait_for_ajax_or_reload(browser): """ Wait for all ajax requests t...
(self): """ Get this user's role, as displayed. """ return self.q(css=self._bounded_selector('.flag-role .value')).text[0] @property def is_current_user(self): """ Does the UI indicate that this is the current user? """ return self.q(css=self._bounded_selector('.flag-role .msg-y...
role_label
identifier_name
users.py
""" Page classes to test either the Course Team page or the Library Team page. """ from bok_choy.promise import EmptyPromise from bok_choy.page_object import PageObject from ...tests.helpers import disable_animations from . import BASE_URL def wait_for_ajax_or_reload(browser): """ Wait for all ajax requests t...
def is_browser_on_page(self): """ Returns True iff the browser has loaded the page. """ return self.q(css='body.view-team').present @property def users(self): """ Return a list of users listed on this page. """ return self.q(css='.user-list ...
""" URL to this page - override in subclass """ raise NotImplementedError
identifier_body
request.rs
#[derive(RustcDecodable, RustcEncodable)]
Ping, } #[derive(RustcDecodable, RustcEncodable)] pub struct UserFlagPair { pub id: usize, pub flag: String, pub user: String, } impl CTFRequest { pub fn verify_flag(id: usize, flag: String, user: String) -> Self { CTFRequest::FlagOffer(UserFlagPair::new(id, flag, user)) } pub fn ...
pub enum CTFRequest { FlagOffer(UserFlagPair), Leaderboard(usize, usize),
random_line_split
request.rs
#[derive(RustcDecodable, RustcEncodable)] pub enum
{ FlagOffer(UserFlagPair), Leaderboard(usize, usize), Ping, } #[derive(RustcDecodable, RustcEncodable)] pub struct UserFlagPair { pub id: usize, pub flag: String, pub user: String, } impl CTFRequest { pub fn verify_flag(id: usize, flag: String, user: String) -> Self { CTFRequest::...
CTFRequest
identifier_name
stream.rs
use std::io::Read; use std::fmt::{self, Debug}; use response::{Response, Responder, DEFAULT_CHUNK_SIZE}; use http::Status; /// Streams a response to a client from an arbitrary `Read`er type. /// /// The client is sent a "chunked" response, where the chunk size is at most /// 4KiB. This means that at most 4KiB are sto...
/// Create a new stream from the given `reader` and sets the chunk size for /// each streamed chunk to `chunk_size` bytes. /// /// # Example /// /// Stream a response from whatever is in `stdin` with a chunk size of 10 /// bytes. Note: you probably shouldn't do this. /// /// ```rus...
{ Stream(reader, DEFAULT_CHUNK_SIZE) }
identifier_body
stream.rs
use std::io::Read; use std::fmt::{self, Debug}; use response::{Response, Responder, DEFAULT_CHUNK_SIZE}; use http::Status; /// Streams a response to a client from an arbitrary `Read`er type. /// /// The client is sent a "chunked" response, where the chunk size is at most /// 4KiB. This means that at most 4KiB are sto...
(reader: T, chunk_size: u64) -> Stream<T> { Stream(reader, chunk_size) } } impl<T: Read + Debug> Debug for Stream<T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Stream({:?})", self.0) } } /// Sends a response to the client using the "Chunked" transfer encoding. The ...
chunked
identifier_name
stream.rs
use std::io::Read; use std::fmt::{self, Debug}; use response::{Response, Responder, DEFAULT_CHUNK_SIZE}; use http::Status; /// Streams a response to a client from an arbitrary `Read`er type. /// /// The client is sent a "chunked" response, where the chunk size is at most /// 4KiB. This means that at most 4KiB are sto...
/// response is abandoned, and the response ends abruptly. An error is printed /// to the console with an indication of what went wrong. impl<'r, T: Read + 'r> Responder<'r> for Stream<T> { fn respond(self) -> Result<Response<'r>, Status> { Response::build().chunked_body(self.0, self.1).ok() } }
/// /// # Failure /// /// If reading from the input stream fails at any point during the response, the
random_line_split
match-beginning-vert.rs
// Copyright 2018 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 ...
match *foo { | A => println!("A"), | B | C if 1 < 2 => println!("BC!"), | _ => {}, } } }
fn main() { for foo in &[A, B, C, D, E] {
random_line_split
match-beginning-vert.rs
// Copyright 2018 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 ...
{ A, B, C, D, E, } use Foo::*; fn main() { for foo in &[A, B, C, D, E] { match *foo { | A => println!("A"), | B | C if 1 < 2 => println!("BC!"), | _ => {}, } } }
Foo
identifier_name
userinfo-edit.js
/** * Created by zhangjh on 2015/10/27. */ (function ($) { "use strict"; var path = $.basepath(); var newURL = path + "/system/userinfo/new"; var user_infoURL = path + "/system/userinfo/info/"; var editURL = path + "/system/userinfo/edit"; var _0URL = path + "/system/permission/user-tab/0"; ...
}); initSelectCallback(); } }(jQuery));
.val(key) .text(value) .appendTo($("#userType"));
random_line_split
userinfo-edit.js
/** * Created by zhangjh on 2015/10/27. */ (function ($) { "use strict"; var path = $.basepath(); var newURL = path + "/system/userinfo/new"; var user_infoURL = path + "/system/userinfo/info/"; var editURL = path + "/system/userinfo/edit"; var _0URL = path + "/system/permission/user-tab/0"; ...
t, $fileListLi, _data["fileinfosMap"], fileUploadURL); } /** * * @param data */ var initSelect = function (data) { $("#userType").empty(); $("<option></option>").val('').text("请选择...").appendTo($("#userType")); $.each(data, function (key, value) { $("<op...
nput($fileInpu
identifier_name
userinfo-edit.js
/** * Created by zhangjh on 2015/10/27. */ (function ($) { "use strict"; var path = $.basepath(); var newURL = path + "/system/userinfo/new"; var user_infoURL = path + "/system/userinfo/info/"; var editURL = path + "/system/userinfo/edit"; var _0URL = path + "/system/permission/user-tab/0"; ...
$.each(data, function (key, value) { $("<option></option>") .val(key) .text(value) .appendTo($("#userType")); }); initSelectCallback(); } }(jQuery));
ListLi, _data["fileinfosMap"], fileUploadURL); } /** * * @param data */ var initSelect = function (data) { $("#userType").empty(); $("<option></option>").val('').text("请选择...").appendTo($("#userType"));
identifier_body
userinfo-edit.js
/** * Created by zhangjh on 2015/10/27. */ (function ($) { "use strict"; var path = $.basepath(); var newURL = path + "/system/userinfo/new"; var user_infoURL = path + "/system/userinfo/info/"; var editURL = path + "/system/userinfo/edit"; var _0URL = path + "/system/permission/user-tab/0"; ...
ation(null, null); $.fileInputAddListenr($fileListLi, $fileInput, uploadFileInfos, doSaveAction, getIsSubmitAction); }) function getIsSubmitAction() { return isSubmitAction; } function initSelectCallback() { var natrualkey = $("#natrualkey").val(); if (natrualkey !=...
n', initSelect); //initFileLoc
conditional_block
amendments.py
''' US Amendments - tweets proposed ammendments to us constitution from: http://www.archives.gov/open/dataset-amendments.html ''' if __name__ == "__main__": import sys sys.path.append("..") import credentials from robot_core import Robot from funcs.ql import QuickList import os import time class
(Robot): handle = "USAmendments" twitter_credentials = credentials.twitter_almostamends minutes= 135 def get_amendment_link(self,row): """constructs url page""" ordinal = lambda n: "%d%s" % (n,"tsnrhtdd"[(n/10%10!=1)*(n%10<4)*n%10::4]) #adds ordinal stuff u...
AmendmentBot
identifier_name
amendments.py
''' US Amendments - tweets proposed ammendments to us constitution from: http://www.archives.gov/open/dataset-amendments.html ''' if __name__ == "__main__": import sys sys.path.append("..")
import time class AmendmentBot(Robot): handle = "USAmendments" twitter_credentials = credentials.twitter_almostamends minutes= 135 def get_amendment_link(self,row): """constructs url page""" ordinal = lambda n: "%d%s" % (n,"tsnrhtdd"[(n/10%10!=1)*(n%10<4)*n%10::4]) #...
import credentials from robot_core import Robot from funcs.ql import QuickList import os
random_line_split
amendments.py
''' US Amendments - tweets proposed ammendments to us constitution from: http://www.archives.gov/open/dataset-amendments.html ''' if __name__ == "__main__": import sys sys.path.append("..") import credentials from robot_core import Robot from funcs.ql import QuickList import os import time class ...
def tweet(self): local_loc = os.path.dirname(__file__) storage = QuickList().open(os.path.join(local_loc, "..//schedules//us-nara-amending-america-dataset-raw-2016-02-25.xls")) storage.shuffle() storage.data = sto...
handle = "USAmendments" twitter_credentials = credentials.twitter_almostamends minutes= 135 def get_amendment_link(self,row): """constructs url page""" ordinal = lambda n: "%d%s" % (n,"tsnrhtdd"[(n/10%10!=1)*(n%10<4)*n%10::4]) #adds ordinal stuff url = "https:/...
identifier_body
amendments.py
''' US Amendments - tweets proposed ammendments to us constitution from: http://www.archives.gov/open/dataset-amendments.html ''' if __name__ == "__main__": import sys sys.path.append("..") import credentials from robot_core import Robot from funcs.ql import QuickList import os import time class ...
text = text[:allowed_length-3] + "..." if link: text += " " + link return self._tweet(text) if __name__ == "__main__": AmendmentBot().populate(20)
if link: #pastebin might fail allowed_length = 141 -22
conditional_block
SVG.js
/* * L.SVG renders vector layers with SVG. All SVG-specific code goes here. */ L.SVG = L.Renderer.extend({ _initContainer: function () { this._container = L.SVG.create('svg'); // makes it possible to click through svg root; we'll reset it back in individual paths this._container.setAttribute('pointer-events...
_removePath: function (layer) { L.DomUtil.remove(layer._path); layer.removeInteractiveTarget(layer._path); }, _updatePath: function (layer) { layer._project(); layer._update(); }, _updateStyle: function (layer) { var path = layer._path, options = layer.options; if (!path) { return; } if (opti...
_addPath: function (layer) { this._container.appendChild(layer._path); layer.addInteractiveTarget(layer._path); },
random_line_split
SVG.js
/* * L.SVG renders vector layers with SVG. All SVG-specific code goes here. */ L.SVG = L.Renderer.extend({ _initContainer: function () { this._container = L.SVG.create('svg'); // makes it possible to click through svg root; we'll reset it back in individual paths this._container.setAttribute('pointer-events...
else { path.setAttribute('fill', 'none'); } path.setAttribute('pointer-events', options.pointerEvents || (options.interactive ? 'visiblePainted' : 'none')); }, _updatePoly: function (layer, closed) { this._setPath(layer, L.SVG.pointsToPath(layer._parts, closed)); }, _updateCircle: function (layer) { ...
{ path.setAttribute('fill', options.fillColor || options.color); path.setAttribute('fill-opacity', options.fillOpacity); path.setAttribute('fill-rule', options.fillRule || 'evenodd'); }
conditional_block
feature_collection.rs
// Copyright 2015 The GeoRust Developers // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed...
pub struct FeatureCollection { pub bbox: Option<Bbox>, pub crs: Option<Crs>, pub features: Vec<Feature>, } impl<'a> From<&'a FeatureCollection> for json::Object { fn from(fc: &'a FeatureCollection) -> json::Object { let mut map = BTreeMap::new(); map.insert(String::from("type"), "Featu...
#[derive(Clone, Debug, PartialEq)]
random_line_split
feature_collection.rs
// Copyright 2015 The GeoRust Developers // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed...
&self) -> json::Json { return json::Json::Object(self.into()); } }
o_json(
identifier_name
feature_collection.rs
// Copyright 2015 The GeoRust Developers // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed...
if let Some(ref bbox) = fc.bbox { map.insert(String::from("bbox"), bbox.to_json()); } return map; } } impl FromObject for FeatureCollection { fn from_object(object: &json::Object) -> Result<Self, Error> { return Ok(FeatureCollection{ bbox: try!(util::ge...
map.insert(String::from("crs"), crs.to_json()); }
conditional_block
watcherService.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
public startWatching(): () => void { let basePath: string = normalize(this.contextService.getWorkspace().folders[0].uri.fsPath); if (basePath && basePath.indexOf('\\\\') === 0 && endsWith(basePath, sep)) { // for some weird reason, node adds a trailing slash to UNC paths // we never ever want trailing sla...
{ }
identifier_body
watcherService.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
const watcher = new OutOfProcessWin32FolderWatcher( basePath, this.ignored, events => this.onRawFileEvents(events), error => this.onError(error), this.verboseLogging ); return () => { this.isDisposed = true; watcher.dispose(); }; } private onRawFileEvents(events: IRawFileChange[]): vo...
{ // for some weird reason, node adds a trailing slash to UNC paths // we never ever want trailing slashes as our base path unless // someone opens root ("/"). // See also https://github.com/nodejs/io.js/issues/1765 basePath = rtrim(basePath, sep); }
conditional_block
watcherService.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
this.isDisposed = true; watcher.dispose(); }; } private onRawFileEvents(events: IRawFileChange[]): void { if (this.isDisposed) { return; } // Emit through event emitter if (events.length > 0) { this.onFileChanges(toFileChangesEvent(events)); } } private onError(error: string): void { if...
return () => {
random_line_split
watcherService.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
{ private isDisposed: boolean; constructor( private contextService: IWorkspaceContextService, private ignored: string[], private onFileChanges: (changes: FileChangesEvent) => void, private errorLogger: (msg: string) => void, private verboseLogging: boolean ) { } public startWatching(): () => void { ...
FileWatcher
identifier_name
color.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 azure::AzFloat; use azure::azure::AzColor; #[inline] pub fn new(r: AzFloat, g: AzFloat, b: AzFloat, a: AzFloa...
#[inline] pub fn rgba(r: AzFloat, g: AzFloat, b: AzFloat, a: AzFloat) -> AzColor { AzColor { r: r, g: g, b: b, a: a } } #[inline] pub fn black() -> AzColor { AzColor { r: 0.0, g: 0.0, b: 0.0, a: 1.0 } } #[inline] pub fn transparent() -> AzColor { AzColor { r: 0.0, g: 0.0, b: 0.0, a: 0.0 } } #[inline] p...
{ AzColor { r: (r as AzFloat) / (255.0 as AzFloat), g: (g as AzFloat) / (255.0 as AzFloat), b: (b as AzFloat) / (255.0 as AzFloat), a: 1.0 as AzFloat } }
identifier_body
color.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 azure::AzFloat; use azure::azure::AzColor; #[inline] pub fn new(r: AzFloat, g: AzFloat, b: AzFloat, a: AzFloa...
pub fn black() -> AzColor { AzColor { r: 0.0, g: 0.0, b: 0.0, a: 1.0 } } #[inline] pub fn transparent() -> AzColor { AzColor { r: 0.0, g: 0.0, b: 0.0, a: 0.0 } } #[inline] pub fn white() -> AzColor { AzColor { r: 1.0, g: 1.0, b: 1.0, a: 1.0 } }
AzColor { r: r, g: g, b: b, a: a } } #[inline]
random_line_split
color.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 azure::AzFloat; use azure::azure::AzColor; #[inline] pub fn
(r: AzFloat, g: AzFloat, b: AzFloat, a: AzFloat) -> AzColor { AzColor { r: r, g: g, b: b, a: a } } #[inline] pub fn rgb(r: u8, g: u8, b: u8) -> AzColor { AzColor { r: (r as AzFloat) / (255.0 as AzFloat), g: (g as AzFloat) / (255.0 as AzFloat), b: (b as AzFloat) / (255.0 as AzFloat), ...
new
identifier_name
error_page_embed.py
from __future__ import absolute_import from django import forms from django.db import IntegrityError, transaction from django.http import HttpResponse from django.views.generic import View from django.template.loader import render_to_string from django.utils import timezone from django.utils.safestring import mark_saf...
response = HttpResponse(content, status=status, content_type='application/json') response['Access-Control-Allow-Origin'] = request.META.get('HTTP_ORIGIN', '') response['Access-Control-Allow-Methods'] = 'GET, POST, OPTIONS' response['Access-Control-Max-Age'] = '1000' response['Ac...
content = ''
conditional_block
error_page_embed.py
from __future__ import absolute_import from django import forms from django.db import IntegrityError, transaction from django.http import HttpResponse from django.views.generic import View from django.template.loader import render_to_string from django.utils import timezone from django.utils.safestring import mark_saf...
class ErrorPageEmbedView(View): def _get_project_key(self, request): try: dsn = request.GET['dsn'] except KeyError: return try: key = ProjectKey.from_dsn(dsn) except ProjectKey.DoesNotExist: return return key def _get_or...
random_line_split
error_page_embed.py
from __future__ import absolute_import from django import forms from django.db import IntegrityError, transaction from django.http import HttpResponse from django.views.generic import View from django.template.loader import render_to_string from django.utils import timezone from django.utils.safestring import mark_saf...
class ErrorPageEmbedView(View): def _get_project_key(self, request): try: dsn = request.GET['dsn'] except KeyError: return try: key = ProjectKey.from_dsn(dsn) except ProjectKey.DoesNotExist: return return key def _get_...
model = UserReport fields = ('name', 'email', 'comments')
identifier_body
error_page_embed.py
from __future__ import absolute_import from django import forms from django.db import IntegrityError, transaction from django.http import HttpResponse from django.views.generic import View from django.template.loader import render_to_string from django.utils import timezone from django.utils.safestring import mark_saf...
(View): def _get_project_key(self, request): try: dsn = request.GET['dsn'] except KeyError: return try: key = ProjectKey.from_dsn(dsn) except ProjectKey.DoesNotExist: return return key def _get_origin(self, request): ...
ErrorPageEmbedView
identifier_name
factories.py
import uuid import factory.fuzzy from django.conf import settings from .. import models from utils.factories import FuzzyMoney class UserFactory(factory.DjangoModelFactory): class Meta: model = settings.AUTH_USER_MODEL username = factory.Sequence('terminator{0}'.format) email = factory.Sequence(...
class PurchaseStatusFactory(factory.django.DjangoModelFactory): class Meta: model = models.PurchaseStatus purchase = factory.SubFactory(PurchaseFactory)
class Meta: model = models.PurchaseItem purchase = factory.SubFactory(PurchaseFactory) product_id = factory.fuzzy.FuzzyAttribute(uuid.uuid4) qty = 1 amount = FuzzyMoney(0, 1000)
identifier_body
factories.py
import uuid import factory.fuzzy from django.conf import settings
class UserFactory(factory.DjangoModelFactory): class Meta: model = settings.AUTH_USER_MODEL username = factory.Sequence('terminator{0}'.format) email = factory.Sequence('terminator{0}@skynet.com'.format) password = 'hunter2' is_superuser = False is_staff = False @classmethod de...
from .. import models from utils.factories import FuzzyMoney
random_line_split
factories.py
import uuid import factory.fuzzy from django.conf import settings from .. import models from utils.factories import FuzzyMoney class UserFactory(factory.DjangoModelFactory): class Meta: model = settings.AUTH_USER_MODEL username = factory.Sequence('terminator{0}'.format) email = factory.Sequence(...
(factory.django.DjangoModelFactory): class Meta: model = models.PurchaseStatus purchase = factory.SubFactory(PurchaseFactory)
PurchaseStatusFactory
identifier_name
vm.ts
import { createContext, isContext, Script, runInNewContext, runInThisContext, compileFunction } from 'vm'; import { inspect } from 'util'; { const sandbox = { animal: 'cat', count: 2 }; const context = createContext(sandbox, { name: 'test', origin: 'file://test.js', ...
const script = new Script('globalVar = "set"'); sandboxes.forEach((sandbox) => { script.runInNewContext(sandbox); script.runInThisContext(); }); console.log(inspect(sandboxes)); const localVar = 'initial value'; runInThisContext('localVar = "vm";'); console.log(localVar)...
console.log(inspect(sandbox)); } { const sandboxes = [{}, {}, {}];
random_line_split
vm.ts
import { createContext, isContext, Script, runInNewContext, runInThisContext, compileFunction } from 'vm'; import { inspect } from 'util'; { const sandbox = { animal: 'cat', count: 2 }; const context = createContext(sandbox, { name: 'test', origin: 'file://test.js', ...
console.log(inspect(sandbox)); runInNewContext('count += 1; name = "kitty"', sandbox); console.log(inspect(sandbox)); } { const sandboxes = [{}, {}, {}]; const script = new Script('globalVar = "set"'); sandboxes.forEach((sandbox) => { script.runInNewContext(sandbox); script...
{ script.runInContext(context); }
conditional_block
matchUsers_page_common.js
function requestDialogList(){ $.ajax({ url:"http://xunta.so:3000/v1/chat_list", type:"POST", dataType:"jsonp", jsonp:"callback", contentType: "application/json; charset=utf-8", data:{ from_user_id:userId }, async:false, success:function(d...
toUserName,//这里是为了测试 "toUserImage" : toUserImgUrl, "userid" : userId, "userName" : userName, "userImage" : userImage, "server_domain" : domain, "userAgent":userAgent, "topicPageSign":"yes" }; console.log("enterDialogPage toUserId=" + toUserId+"|toUserName="+toUserName); // openWin(topicid,'dialog_page/...
identifier_body
matchUsers_page_common.js
function requestDialogList(){ $.ajax({ url:"http://xunta.so:3000/v1/chat_list", type:"POST", dataType:"jsonp", jsonp:"callback", contentType: "application/json; charset=utf-8", data:{ from_user_id:userId }, async:false, success:function(d...
serId" : toUserId, "toUserName" : toUserName,//这里是为了测试 "toUserImage" : toUserImgUrl, "userid" : userId, "userName" : userName, "userImage" : userImage, "server_domain" : domain, "userAgent":userAgent, "topicPageSign":"yes" }; console.log("enterDialogPage toUserId=" + toUserId+"|toUserName="+toUserName...
aram = { "toU
identifier_name
matchUsers_page_common.js
function requestDialogList(){ $.ajax({ url:"http://xunta.so:3000/v1/chat_list", type:"POST", dataType:"jsonp", jsonp:"callback", contentType: "application/json; charset=utf-8", data:{ from_user_id:userId }, async:false, success:function(d...
// openWin(topicid,'dialog_page/dialog_page.html',JSON.stringify(pageParam)); openWin(toUserId,'dialog_page/dialog_page.html',JSON.stringify(pageParam)); }
"userAgent":userAgent, "topicPageSign":"yes" }; console.log("enterDialogPage toUserId=" + toUserId+"|toUserName="+toUserName);
random_line_split
createProgramFromFiles.js
define([ 'webgl/createProgram', 'webgl/shader/compileShaderFromFile' ], function( createProgram, compileShaderFromFile ) { /** * Creates a program from 2 script tags. * * @param {!WebGLRenderingContext} gl The WebGL Context. * @param {string} vertexShaderFileName The file name of the vertex shader. * @pa...
}; });
{ return createProgram(gl, compileShaderFromFile(gl, vertexShaderFileName, 'vertex'), compileShaderFromFile(gl, fragmentShaderFileName, 'fragment')); }
conditional_block
createProgramFromFiles.js
define([ 'webgl/createProgram', 'webgl/shader/compileShaderFromFile' ], function(
* * @param {!WebGLRenderingContext} gl The WebGL Context. * @param {string} vertexShaderFileName The file name of the vertex shader. * @param {string} fragmentShaderFileName The file name of the fragment shader. * @return {!WebGLProgram} A program */ return function createProgramFromScripts(gl, vertexShade...
createProgram, compileShaderFromFile ) { /** * Creates a program from 2 script tags.
random_line_split
DTD.py
#!/usr/bin/python2.7 # -*- coding: utf-8 -*- # vim:ts=4:sw=4:softtabstop=4:smarttab:expandtab # 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 ...
(self): print "done parsing. Writing file." gen = self.generator for name, value in self._allattributes.items(): gen.add_code("%s = %r" % (name, value), index=2) gen.add_instance("GENERAL_ENTITIES", self.general_entities) gen.add_comment("Cache for dynamic classes for...
dtd_end
identifier_name
DTD.py
#!/usr/bin/python2.7 # -*- coding: utf-8 -*- # vim:ts=4:sw=4:softtabstop=4:smarttab:expandtab # 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 ...
"Receives internal general entity declarations." self.general_entities[normalize_unicode(name)] = val def new_external_entity(self, ent_name, pub_id, sys_id, ndata): """Receives external general entity declarations. 'ndata' is the empty string if the entity is parsed.""" # X...
def new_external_pe(self, name, pubid, sysid): "Receives external parameter entity declarations." # these are handled internally by the DTD parser. def new_general_entity(self, name, val):
random_line_split
DTD.py
#!/usr/bin/python2.7 # -*- coding: utf-8 -*- # vim:ts=4:sw=4:softtabstop=4:smarttab:expandtab # 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 ...
# class name is capitalized to avoid clashes with Python key words. ch = self.generator.add_class(get_identifier(elem_name), tuple(parents)) ch.add_attribute("_name", elem_name) ch.add_attribute("CONTENTMODEL", _ContentModelGenerator(contentmodel)) self.elements[elem_name] = ch ...
parents.insert(0, getattr(self.mixins, mixinname))
conditional_block
DTD.py
#!/usr/bin/python2.7 # -*- coding: utf-8 -*- # vim:ts=4:sw=4:softtabstop=4:smarttab:expandtab # 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 ...
# this DTD parser consumer generates the Python source code from the DTD. class DTDConsumerForSourceGeneration(object): def __init__(self, generator, mixins=None, doctype=None): self.generator = generator self._code_index = 0 self.elements = {} self.parameter_entities = {} ...
def __repr__(self): s = ["{"] for t in self.items(): s.append("%r: %s, " % t) s.append("}") return "\n ".join(s)
identifier_body
jquery.maxsubmit.js
/** * Copyright 2013-2014 Academe Computing Ltd * Released under the MIT license * Author: Jason Judge <jason@academe.co.uk> * Version: 1.2.1 */ /** * jquery.maxsubmit.js * * Checks how many parameters a form is going to submit, and * gives the user a chance to cancel if it exceeds a set number. * ...
else { // Just return the number of elements matched. return fields.length; } }; }(jQuery));
{ // Return the full list of elements for analysis. return fields; }
conditional_block
jquery.maxsubmit.js
/** * Copyright 2013-2014 Academe Computing Ltd * Released under the MIT license * Author: Jason Judge <jason@academe.co.uk> * Version: 1.2.1 */ /** * jquery.maxsubmit.js * * Checks how many parameters a form is going to submit, and * gives the user a chance to cancel if it exceeds a set number. * ...
return confirm( settings .max_exceeded_message .replace("{max_count}", settings.max_count) .replace("{form_count}", form_count) ); } }, options); // Form elements will be passed in, so we need to trigger on // an attempt to submit that form. // First ch...
random_line_split
testgridff2.py
from Sire.IO import * from Sire.MM import * from Sire.System import * from Sire.Mol import * from Sire.Maths import * from Sire.FF import * from Sire.Move import * from Sire.Units import * from Sire.Vol import * from Sire.Qt import * import os coul_cutoff = 20 * angstrom lj_cutoff = 10 * angstrom amber = Amber() (...
system.add(swapwaters) system.add(waters) gridff = GridFF("gridff") gridff.setCombiningRules("arithmetic") print("Combining rules are %s" % gridff.combiningRules()) gridff.setBuffer(2 * angstrom) gridff.setGridSpacing( 0.5 * angstrom ) gridff.setLJCutoff(lj_cutoff) gridff.setCoulombCutoff(coul_cutoff) gridff.setShif...
waters.add(water)
conditional_block
testgridff2.py
from Sire.IO import * from Sire.MM import * from Sire.System import * from Sire.Mol import * from Sire.Maths import * from Sire.FF import * from Sire.Move import * from Sire.Units import * from Sire.Vol import * from Sire.Qt import * import os coul_cutoff = 20 * angstrom lj_cutoff = 10 * angstrom amber = Amber() (m...
gridff2.setGridSpacing( 0.5 * angstrom ) gridff2.setLJCutoff(lj_cutoff) gridff2.setCoulombCutoff(coul_cutoff) gridff2.setShiftElectrostatics(True) #gridff2.setUseAtomisticCutoff(True) #gridff2.setUseReactionField(True) gridff2.add( swapwaters, MGIdx(0) ) gridff2.addFixedAtoms(waters.molecules()) gridff2.setSpace( Cart...
gridff2.setBuffer(2*angstrom)
random_line_split
print-command.js
'use strict'; const chalk = require('chalk'); const EOL = require('os').EOL; module.exports = function(initialMargin, shouldDescriptionBeGrey) { initialMargin = initialMargin || ''; let output = ''; let options = this.anonymousOptions; // <anonymous-option-1> ... if (options.length) { output += ` ${c...
(val) { return val === '' ? '""' : val; }
formatValue
identifier_name
print-command.js
'use strict'; const chalk = require('chalk'); const EOL = require('os').EOL; module.exports = function(initialMargin, shouldDescriptionBeGrey) { initialMargin = initialMargin || ''; let output = ''; let options = this.anonymousOptions; // <anonymous-option-1> ... if (options.length) { output += ` ${c...
function formatValue(val) { return val === '' ? '""' : val; }
{ return typeof type === 'string' ? formatValue(type) : type.name; }
identifier_body
print-command.js
'use strict'; const chalk = require('chalk'); const EOL = require('os').EOL; module.exports = function(initialMargin, shouldDescriptionBeGrey) { initialMargin = initialMargin || ''; let output = ''; let options = this.anonymousOptions; // <anonymous-option-1> ... if (options.length) { output += ` ${c...
}); return output; }; function formatType(type) { return typeof type === 'string' ? formatValue(type) : type.name; } function formatValue(val) { return val === '' ? '""' : val; }
}
random_line_split
print-command.js
'use strict'; const chalk = require('chalk'); const EOL = require('os').EOL; module.exports = function(initialMargin, shouldDescriptionBeGrey) { initialMargin = initialMargin || ''; let output = ''; let options = this.anonymousOptions; // <anonymous-option-1> ... if (options.length) { output += ` ${c...
if (option.description) { output += ` ${option.description}`; } if (option.aliases && option.aliases.length) { output += `${EOL + initialMargin} ${chalk.grey( `aliases: ${option.aliases .map(a => { if (typeof a === 'string') { return (a.length > ...
{ output += ` ${chalk.cyan(`(Default: ${formatValue(option.default)})`)}`; }
conditional_block
managers.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals import copy import logging import time from collections import OrderedDict from contextlib import contextmanager import six from django.utils.functional import cached_property from .client import get_es_client logger = logging.getLogger('elasticindex') ...
yield self.model_cls(hit) @cached_property def es_client(self): """ :rtype: Elasticsearch """ return get_es_client() def get_by_id(self, id): """ Elasticsearch のIDで1件取得 :param id: :return: """ result = self.es_clie...
self.latest_raw_result = result for hit in result['hits']['hits']:
random_line_split
managers.py
coding: utf-8 -*- from __future__ import unicode_literals import copy import logging import time from collections import OrderedDict from contextlib import contextmanager import six from django.utils.functional import cached_property from .client import get_es_client logger = logging.getLogger('elasticindex') class...
anager(ElasticQuerySet) でもいいんだけど、インスタンス変数が汚れる可能性があるので クラスプロパティっぽい感じで、アクセスされるたびに新しいクエリセットを作ることにした """ def __init__(self, model_cls, body=None, **kwargs): self.model_cls = model_cls self.kwargs = kwargs def __get__(self, cls, owner): return ElasticQuerySet(self.model_cls) c...
entM
identifier_name
managers.py
-*- coding: utf-8 -*- from __future__ import unicode_literals import copy import logging import time from collections import OrderedDict from contextlib import contextmanager import six from django.utils.functional import cached_property from .client import get_es_client logger = logging.getLogger('elasticindex') c...
rom'] = offset return o def query(self, filter_query_dict): """ :param filter_query_dict: - {"match": {"product_id": 192}} - {"match_all": {}} # default - {"multi_match": { "query": query_word, "fields": [ "u...
del o.body['from'] else: o.body['f
conditional_block
managers.py
-*- coding: utf-8 -*- from __future__ import unicode_literals import copy import logging import time from collections import OrderedDict from contextlib import contextmanager import six from django.utils.functional import cached_property from .client import get_es_client logger = logging.getLogger('elasticindex') c...
def __getitem__(self, k): """ Retrieves an item or slice from the set of results. """ if not isinstance(k, (slice,) + six.integer_types): raise TypeError assert ((not isinstance(k, slice) and (k >= 0)) or (isinstance(k, slice) and (k.start is Non...
return bool(self.result_list)
identifier_body
__init__.py
# Copyright 2013 Hewlett-Packard Development Company, L.P. # # Author: Kiall Mac Innes <kiall@hp.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/L...
conf = { 'app': { 'root': 'designate.api.v2.controllers.root.RootController', 'modules': ['designate.api.v2'] } } app = pecan.deploy.deploy(conf) return app
def disabled_app(environ, start_response): status = '404 Not Found' start_response(status, []) return [] return disabled_app
conditional_block
__init__.py
# Copyright 2013 Hewlett-Packard Development Company, L.P. # # Author: Kiall Mac Innes <kiall@hp.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/L...
if not cfg.CONF['service:api'].enable_api_v2: def disabled_app(environ, start_response): status = '404 Not Found' start_response(status, []) return [] return disabled_app conf = { 'app': { 'root': 'designate.api.v2.controllers.root.RootContro...
identifier_body
__init__.py
# Copyright 2013 Hewlett-Packard Development Company, L.P. # # Author: Kiall Mac Innes <kiall@hp.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/L...
from oslo.config import cfg from designate.openstack.common import log as logging LOG = logging.getLogger(__name__) def factory(global_config, **local_conf): if not cfg.CONF['service:api'].enable_api_v2: def disabled_app(environ, start_response): status = '404 Not Found' start_res...
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from designate.api.v2 import patches # flake8: noqa import pecan.deploy
random_line_split
__init__.py
# Copyright 2013 Hewlett-Packard Development Company, L.P. # # Author: Kiall Mac Innes <kiall@hp.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/L...
(global_config, **local_conf): if not cfg.CONF['service:api'].enable_api_v2: def disabled_app(environ, start_response): status = '404 Not Found' start_response(status, []) return [] return disabled_app conf = { 'app': { 'root': 'designate...
factory
identifier_name
__init__.py
"""Multidict implementation. HTTP Headers and URL query string require specific data structure: multidict. It behaves mostly like a dict but it can have several values for the same key. """ import os __all__ = ('MultiDictProxy', 'CIMultiDictProxy', 'MultiDict', 'CIMultiDict', 'upstr', 'istr') __version__...
CIMultiDictProxy, MultiDict, CIMultiDict, upstr, istr)
MultiDict, CIMultiDict, upstr, istr) except ImportError: # pragma: no cover from ._multidict_py import (MultiDictProxy,
random_line_split
__init__.py
"""Multidict implementation. HTTP Headers and URL query string require specific data structure: multidict. It behaves mostly like a dict but it can have several values for the same key. """ import os __all__ = ('MultiDictProxy', 'CIMultiDictProxy', 'MultiDict', 'CIMultiDict', 'upstr', 'istr') __version__...
try: from ._multidict import (MultiDictProxy, CIMultiDictProxy, MultiDict, CIMultiDict, upstr, istr) except ImportError: # pragma: no cover from ._multidict_py import ...
conditional_block
entity.js
var entity = function() { this.width = 0; this.height = 0; this.scale = 1; this.x = 0; this.y = 0; this.image = null; this.imageWidth = 0; this.imageHeight = 0; }; entity.prototype = entity; entity.prototype.init = function(width, height, scale) { this.width = width; this.height = height; this.scale = sc...
} entity.prototype.moveRight = function(shift) { this.x += shift; } entity.prototype.moveLeft = function(shift) { this.x -= shift; } entity.prototype.moveUp = function(shift) { this.y -= shift; } entity.prototype.moveDown = function(shift) { this.y += shift; }
this.x = x; this.y = y;
random_line_split
security_dataset_tests.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
def test_get_dashboards__users_are_dashboards_owners(self): # arrange username = "gamma" user = security_manager.find_user(username) my_owned_dashboard = create_dashboard_to_db( dashboard_title="My Dashboard", published=False, owners=[user], ) not_my_ow...
self.assert200(get_dashboard_response)
conditional_block
security_dataset_tests.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
@pytest.fixture def load_dashboard(self): with app.app_context(): table = ( db.session.query(SqlaTable).filter_by(table_name="energy_usage").one() ) # get a slice from the allowed table slice = db.session.query(Slice).filter_by(slice_name="...
) class TestDashboardDatasetSecurity(DashboardTestCase):
random_line_split
security_dataset_tests.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
(self): # arrange user = security_manager.find_user("gamma") fav_dash_slug = f"my_favorite_dash_{random_slug()}" regular_dash_slug = f"regular_dash_{random_slug()}" favorite_dash = Dashboard() favorite_dash.dashboard_title = "My Favorite Dashboard" favorite_dash....
test_get_dashboards__users_can_view_favorites_dashboards
identifier_name
security_dataset_tests.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
hidden_dash = Dashboard() hidden_dash.dashboard_title = "Hidden Dashboard" hidden_dash.slug = pytest.hidden_dash_slug hidden_dash.slices = [slice] hidden_dash.published = False db.session.merge(published_dash) db.session.merge(hidden_...
@pytest.fixture def load_dashboard(self): with app.app_context(): table = ( db.session.query(SqlaTable).filter_by(table_name="energy_usage").one() ) # get a slice from the allowed table slice = db.session.query(Slice).filter_by(slice_name="Ener...
identifier_body
passport.js
/** * Passport configuration * * This is the configuration for your Passport.js setup and where you * define the authentication strategies you want your application to employ. * * I have tested the service with all of the providers listed below - if you * come across a provider that for some reason doesn't work,...
}, github: { name: 'GitHub', protocol: 'oauth2', strategy: require('passport-github').Strategy, options: { clientID: 'your-client-id', clientSecret: 'your-client-secret' } }, facebook: { name: 'Facebook', protocol: 'oauth2', strategy: require('passport-facebook').St...
random_line_split
inappbrowser.ts
import { Plugin, CordovaInstance } from './plugin'; import { Observable } from 'rxjs/Observable'; declare var cordova: any; export interface InAppBrowserEvent extends Event { /** the eventname, either loadstart, loadstop, loaderror, or exit. */ type: string; /** the URL that was loaded. */ url: string; /** ...
*/ @CordovaInstance({sync: true}) show(): void { } /** * Closes the InAppBrowser window. */ @CordovaInstance({sync: true}) close(): void { } /** * Injects JavaScript code into the InAppBrowser window. * @param script Details of the script to run, specifying either a file or code key. ...
* if the InAppBrowser was already visible.
random_line_split
inappbrowser.ts
import { Plugin, CordovaInstance } from './plugin'; import { Observable } from 'rxjs/Observable'; declare var cordova: any; export interface InAppBrowserEvent extends Event { /** the eventname, either loadstart, loadstop, loaderror, or exit. */ type: string; /** the URL that was loaded. */ url: string; /** ...
/** * Injects CSS into the InAppBrowser window. * @param css Details of the script to run, specifying either a file or code key. */ @CordovaInstance() insertCss(css: {file?: string, code?: string}): Promise<any> {return; } /** * A method that allows you to listen to events happening in t...
{return; }
identifier_body
inappbrowser.ts
import { Plugin, CordovaInstance } from './plugin'; import { Observable } from 'rxjs/Observable'; declare var cordova: any; export interface InAppBrowserEvent extends Event { /** the eventname, either loadstart, loadstop, loaderror, or exit. */ type: string; /** the URL that was loaded. */ url: string; /** ...
(css: {file?: string, code?: string}): Promise<any> {return; } /** * A method that allows you to listen to events happening in the browser. * @param event Event name * @returns {Observable<any>} Returns back an observable that will listen to the event on subscribe, and will stop listening to the event on...
insertCss
identifier_name
index.js
/** * Expose `parse`. */ module.exports = parse; /** * Wrap map from jquery. */ var map = { legend: [1, '<fieldset>', '</fieldset>'], tr: [2, '<table><tbody>', '</tbody></table>'], col: [2, '<table><tbody></tbody><colgroup>', '</colgroup></table>'], _default: [0, '', ''] }; map.td = map.th = [3, '<table...
map.option = map.optgroup = [1, '<select multiple="multiple">', '</select>']; map.thead = map.tbody = map.colgroup = map.caption = map.tfoot = [1, '<table>', '</table>']; map.text = map.circle = map.ellipse = map.line = map.path = map.polygon = map.polyline = map.rect = [1, '<svg xmlns="http://www.w3.org/2000/svg" ve...
random_line_split
index.js
/** * Expose `parse`. */ module.exports = parse; /** * Wrap map from jquery. */ var map = { legend: [1, '<fieldset>', '</fieldset>'], tr: [2, '<table><tbody>', '</tbody></table>'], col: [2, '<table><tbody></tbody><colgroup>', '</colgroup></table>'], _default: [0, '', ''] }; map.td = map.th = [3, '<tabl...
(html) { if ('string' != typeof html) throw new TypeError('String expected'); // tag name var m = /<([\w:]+)/.exec(html); if (!m) return document.createTextNode(html); html = html.replace(/^\s+|\s+$/g, ''); // Remove leading/trailing whitespace var tag = m[1]; // body support if (tag == 'body') { ...
parse
identifier_name
index.js
/** * Expose `parse`. */ module.exports = parse; /** * Wrap map from jquery. */ var map = { legend: [1, '<fieldset>', '</fieldset>'], tr: [2, '<table><tbody>', '</tbody></table>'], col: [2, '<table><tbody></tbody><colgroup>', '</colgroup></table>'], _default: [0, '', ''] }; map.td = map.th = [3, '<tabl...
var depth = wrap[0]; var prefix = wrap[1]; var suffix = wrap[2]; var el = document.createElement('div'); el.innerHTML = prefix + html + suffix; while (depth--) el = el.lastChild; // one element if (el.firstChild == el.lastChild) { return el.removeChild(el.firstChild); } // several elements v...
{ if ('string' != typeof html) throw new TypeError('String expected'); // tag name var m = /<([\w:]+)/.exec(html); if (!m) return document.createTextNode(html); html = html.replace(/^\s+|\s+$/g, ''); // Remove leading/trailing whitespace var tag = m[1]; // body support if (tag == 'body') { var...
identifier_body
city.rs
use iron::prelude::*; use hyper::status::StatusCode; use super::request_body; use ::proto::response::*; use ::proto::schema::NewCity; use ::db::schema::*; use ::db::*; pub fn
(_: &mut Request) -> IronResult<Response> { let query = City::select_builder().build(); let conn = get_db_connection(); info!("request GET /city"); let rows = conn.query(&query, &[]).unwrap(); let cities = rows.into_iter() .map(City::from) .collect::<Vec<City>>(); Ok(cities.as...
get_cities
identifier_name
city.rs
use iron::prelude::*; use hyper::status::StatusCode; use super::request_body; use ::proto::response::*; use ::proto::schema::NewCity; use ::db::schema::*; use ::db::*; pub fn get_cities(_: &mut Request) -> IronResult<Response> { let query = City::select_builder().build(); let conn = get_db_connection(); ...
Ok(cities.as_response()) } pub fn put_city(req: &mut Request) -> IronResult<Response> { let new_city: NewCity = request_body(req)?; info!("request PUT /city {{ {:?} }}", new_city); let conn = get_db_connection(); let query = City::insert_query(); conn.execute(&query, &[&new_city.Name]).unwr...
let rows = conn.query(&query, &[]).unwrap(); let cities = rows.into_iter() .map(City::from) .collect::<Vec<City>>();
random_line_split