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
__init__.py
# This file is part of Indico. # Copyright (C) 2002 - 2016 European Organization for Nuclear Research (CERN). # # Indico is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 3 of the # License, or (a...
(RHRoomBookingBase): """ Adds admin authorization. All classes that implement admin tasks should be derived from this class. """ def _checkProtection(self): if session.user is None: self._checkSessionUser() elif not rb_is_admin(session.user): raise Forbidden(...
RHRoomBookingAdminBase
identifier_name
__init__.py
# This file is part of Indico. # Copyright (C) 2002 - 2016 European Organization for Nuclear Research (CERN). # # Indico is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 3 of the # License, or (a...
""" Adds admin authorization. All classes that implement admin tasks should be derived from this class. """ def _checkProtection(self): if session.user is None: self._checkSessionUser() elif not rb_is_admin(session.user): raise Forbidden(_('You are not authorized...
identifier_body
vrtogglebutton.ts
import {ToggleButton, ToggleButtonConfig} from './togglebutton'; import {UIInstanceManager} from '../uimanager'; /** * A button that toggles the video view between normal/mono and VR/stereo. */ export class VRToggleButton extends ToggleButton<ToggleButtonConfig> { constructor(config: ToggleButtonConfig = {}) { ...
} else { if (player.getVRStatus().isStereo) { player.setVRStereo(false); } else { player.setVRStereo(true); } } }); // Set startup visibility vrButtonVisibilityHandler(); } }
{ console.log('No VR content'); }
conditional_block
vrtogglebutton.ts
import {ToggleButton, ToggleButtonConfig} from './togglebutton'; import {UIInstanceManager} from '../uimanager'; /** * A button that toggles the video view between normal/mono and VR/stereo. */ export class VRToggleButton extends ToggleButton<ToggleButtonConfig> { constructor(config: ToggleButtonConfig = {}) { ...
}; let isVRStereoAvailable = () => { return player.getVRStatus().contentType !== 'none'; }; let vrStateHandler = () => { if (isVRConfigured() && isVRStereoAvailable()) { this.show(); // show button in case it is hidden if (player.getVRStatus().isStereo) { this.on...
// available at UI initialization. As an alternative, we check the VR settings in the config. // TODO use getVRStatus() through isVRStereoAvailable() once the player has been rewritten and the status is // available in ON_READY let config = player.getConfig(); return config.source && confi...
random_line_split
vrtogglebutton.ts
import {ToggleButton, ToggleButtonConfig} from './togglebutton'; import {UIInstanceManager} from '../uimanager'; /** * A button that toggles the video view between normal/mono and VR/stereo. */ export class VRToggleButton extends ToggleButton<ToggleButtonConfig> { constructor(config: ToggleButtonConfig = {}) { ...
(player: bitmovin.PlayerAPI, uimanager: UIInstanceManager): void { super.configure(player, uimanager); let isVRConfigured = () => { // VR availability cannot be checked through getVRStatus() because it is asynchronously populated and not // available at UI initialization. As an alternative, we chec...
configure
identifier_name
Log.ts
/** * This is a static Logger class, it is allows you to disable the client side * application logging at runtime. * Set the DEBUG property false (default value is true) to disable the client side logging. * * * @author Gabor Kokeny */ class Log { static DEBUG: boolean = true; /** * * @...
if (console) { console.debug(message, params); } return this; } static groupStart(title?: string): Log { if (!Log.DEBUG) { return; } if (console) { console.groupCollapsed(title); } return this; } static groupEnd(): Log { ...
{ return; }
conditional_block
Log.ts
/** * This is a static Logger class, it is allows you to disable the client side * application logging at runtime. * Set the DEBUG property false (default value is true) to disable the client side logging. * * * @author Gabor Kokeny */ class Log { static DEBUG: boolean = true; /** * * @...
(message: string, ...params: any[]): Log { if (!Log.DEBUG) { return; } if (console) { console.warn(message, params); } return this; } static debug(message: string, ...params: any[]): Log { if (!Log.DEBUG) { return; } if (console) { consol...
warn
identifier_name
Log.ts
/** * This is a static Logger class, it is allows you to disable the client side * application logging at runtime. * Set the DEBUG property false (default value is true) to disable the client side logging. * * * @author Gabor Kokeny */ class Log { static DEBUG: boolean = true; /** * * @pa...
if (console) { console.info(message, params); } return this; } static error(message: string, ...params: any[]): Log { if (!Log.DEBUG) { return; } if (console) { console.error(message, params); } return this; } static war...
if (!Log.DEBUG) { return; }
random_line_split
Log.ts
/** * This is a static Logger class, it is allows you to disable the client side * application logging at runtime. * Set the DEBUG property false (default value is true) to disable the client side logging. * * * @author Gabor Kokeny */ class Log { static DEBUG: boolean = true; /** * * @...
}
{ if (!Log.DEBUG) { return; } if (console) { console.groupEnd(); } return this; }
identifier_body
connection.py
############################################################################### ## ## Copyright (C) 2014-2016, New York University. ## Copyright (C) 2011-2014, NYU-Poly. ## Copyright (C) 2006-2011, University of Utah. ## All rights reserved. ## Contact: contact@vistrails.org ## ## This file is part of VisTrails. ## ## ...
(self): """Tests sane initialization of empty connection""" c = Connection() self.assertEquals(c.source.endPoint, PortEndPoint.Source) self.assertEquals(c.destination.endPoint, PortEndPoint.Destination) if __name__ == '__main__': unittest.main()
testEmptyConnection
identifier_name
connection.py
############################################################################### ## ## Copyright (C) 2014-2016, New York University. ## Copyright (C) 2011-2014, NYU-Poly. ## Copyright (C) 2006-2011, University of Utah. ## All rights reserved. ## Contact: contact@vistrails.org ## ## This file is part of VisTrails. ## ## ...
return cp ########################################################################## @staticmethod def convert(_connection): # print "ports: %s" % _Connection._get_ports(_connection) if _connection.__class__ == Connection: return _connection.__class__ = Connecti...
Port.convert(port)
conditional_block
connection.py
############################################################################### ## ## Copyright (C) 2014-2016, New York University. ## Copyright (C) 2011-2014, NYU-Poly. ## Copyright (C) 2006-2011, University of Utah. ## All rights reserved. ## Contact: contact@vistrails.org ## ## This file is part of VisTrails. ## ## ...
def __init__(self, *args, **kwargs): """__init__() -> Connection Initializes source and destination ports. """ DBConnection.__init__(self, *args, **kwargs) if self.id is None: self.db_id = -1 if not len(self.ports) > 0: self.sour...
conn.source.endPoint = PortEndPoint.Source conn.destination.endPoint = PortEndPoint.Destination return conn
random_line_split
connection.py
############################################################################### ## ## Copyright (C) 2014-2016, New York University. ## Copyright (C) 2011-2014, NYU-Poly. ## Copyright (C) 2006-2011, University of Utah. ## All rights reserved. ## Contact: contact@vistrails.org ## ## This file is part of VisTrails. ## ## ...
def __ne__(self, other): return not self.__eq__(other) def __eq__(self, other): if type(other) != type(self): return False return (self.source == other.source and self.dest == other.dest) def equals_no_id(self, other): """Checks equality up to ...
"""__str__() -> str - Returns a string representation of a Connection object. """ rep = "<connection id='%s'>%s%s</connection>" return rep % (str(self.id), str(self.source), str(self.destination))
identifier_body
0008_auto_20210519_1117.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration):
dependencies = [ ('servicos', '0007_auto_20210416_0841'), ] operations = [ migrations.AlterField( model_name='servico', name='data_ultimo_uso', field=models.DateField(help_text='Data em que o servi\xe7o foi utilizado pela Casa Legislativa pela \xfaltima vez',...
identifier_body
0008_auto_20210519_1117.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('servicos', '0007_auto_20210416_0841'), ] operations = [ migrations.AlterField( model_name='servico', ...
model_name='tiposervico', name='modo', field=models.CharField(max_length=1, verbose_name='modo de presta\xe7\xe3o do servi\xe7o', choices=[(b'H', 'Hospedagem'), (b'R', 'Registro')]), preserve_default=True, ), migrations.AlterField( model_name='...
), migrations.AlterField(
random_line_split
0008_auto_20210519_1117.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class
(migrations.Migration): dependencies = [ ('servicos', '0007_auto_20210416_0841'), ] operations = [ migrations.AlterField( model_name='servico', name='data_ultimo_uso', field=models.DateField(help_text='Data em que o servi\xe7o foi utilizado pela Casa Leg...
Migration
identifier_name
xfixes.py
# Xlib.ext.xfixes -- XFIXES extension module # # Copyright (C) 2010-2011 Outpost Embedded, LLC # Forest Bond <forest.bond@rapidrollout.com> #
# This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public License # as published by the Free Software Foundation; either version 2.1 # of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be use...
random_line_split
xfixes.py
# Xlib.ext.xfixes -- XFIXES extension module # # Copyright (C) 2010-2011 Outpost Embedded, LLC # Forest Bond <forest.bond@rapidrollout.com> # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public License # as published by the Free Software F...
(self): ShowCursor(display=self.display, opcode=self.display.get_extension_major(extname), window=self) def init(disp, info): disp.extension_add_method('display', 'xfixes_query_version', query_version) disp.extension_add_method('window', 'xfixes_hide_cursor', hide_cursor) ...
show_cursor
identifier_name
xfixes.py
# Xlib.ext.xfixes -- XFIXES extension module # # Copyright (C) 2010-2011 Outpost Embedded, LLC # Forest Bond <forest.bond@rapidrollout.com> # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public License # as published by the Free Software F...
class HideCursor(rq.Request): _request = rq.Struct(rq.Card8('opcode'), rq.Opcode(29), rq.RequestLength(), rq.Window('window') ) def hide_cursor(self): HideCursor(display=self.display, opcode=se...
return QueryVersion(display=self.display, opcode=self.display.get_extension_major(extname), major_version=4, minor_version=0)
identifier_body
CrawlChart.js
import React from 'react'; import PropTypes from 'prop-types'; import _get from 'lodash.get'; import _words from 'lodash.words'; import { VictoryAxis, VictoryBar, VictoryChart, VictoryTheme } from 'victory';
export class CrawlChart extends React.Component { constructor(props) { super(props); this.state = { data: [ {movie: 1, word_count: 0}, {movie: 2, word_count: 0}, {movie: 3, word_count: 0}, {movie: 4, word_count: 0}, {movie: 5, word_count: 0}, {movie: 6, w...
random_line_split
CrawlChart.js
import React from 'react'; import PropTypes from 'prop-types'; import _get from 'lodash.get'; import _words from 'lodash.words'; import { VictoryAxis, VictoryBar, VictoryChart, VictoryTheme } from 'victory'; export class CrawlChart extends React.Component { constructor(props) { super(props); this.st...
render() { return ( <div> <h3>Opening Crawl Word Count</h3> <VictoryChart // adding the material theme provided with Victory animate={{duration: 500}} theme={VictoryTheme.material} domainPadding={20} > <VictoryAxis tickF...
{ let movieCrawls = nextProps.movies.map((m) => _get(m, 'opening_crawl', '')); let newState = { data: movieCrawls.map((c, i) => { return { movie: i+1, word_count: _words(c).length}; }) }; this.setState(newState); }
identifier_body
CrawlChart.js
import React from 'react'; import PropTypes from 'prop-types'; import _get from 'lodash.get'; import _words from 'lodash.words'; import { VictoryAxis, VictoryBar, VictoryChart, VictoryTheme } from 'victory'; export class CrawlChart extends React.Component {
(props) { super(props); this.state = { data: [ {movie: 1, word_count: 0}, {movie: 2, word_count: 0}, {movie: 3, word_count: 0}, {movie: 4, word_count: 0}, {movie: 5, word_count: 0}, {movie: 6, word_count: 0}, {movie: 7, word_count: 0} ] };...
constructor
identifier_name
animations.rs
//! Animation effects embedded in the game world. use crate::{location::Location, world::World}; use calx::{ease, project, CellSpace, ProjectVec, Space}; use calx_ecs::Entity; use euclid::{vec2, Vector2D, Vector3D}; use serde::{Deserialize, Serialize}; /// Location with a non-integer offset delta. /// /// Use for twe...
(&self, e: Entity) -> Option<LerpLocation> { if let Some(location) = self.location(e) { Some(LerpLocation { location, offset: self.lerp_offset(e), }) } else { None } } pub fn lerp_offset(&self, e: Entity) -> PhysicsVect...
lerp_location
identifier_name
animations.rs
use euclid::{vec2, Vector2D, Vector3D}; use serde::{Deserialize, Serialize}; /// Location with a non-integer offset delta. /// /// Use for tweened animations. #[derive(Copy, Clone, PartialEq, Debug, Default)] pub struct LerpLocation { pub location: Location, pub offset: PhysicsVector, } impl From<Location> fo...
//! Animation effects embedded in the game world. use crate::{location::Location, world::World}; use calx::{ease, project, CellSpace, ProjectVec, Space}; use calx_ecs::Entity;
random_line_split
animations.rs
//! Animation effects embedded in the game world. use crate::{location::Location, world::World}; use calx::{ease, project, CellSpace, ProjectVec, Space}; use calx_ecs::Entity; use euclid::{vec2, Vector2D, Vector3D}; use serde::{Deserialize, Serialize}; /// Location with a non-integer offset delta. /// /// Use for twe...
} pub fn lerp_offset(&self, e: Entity) -> PhysicsVector { if let Some(location) = self.location(e) { if let Some(anim) = self.anim(e) { let frame = (self.get_anim_tick() - anim.tween_start) as u32; if frame < anim.tween_duration { if let ...
{ None }
conditional_block
window.js
var WINDOW = {
ms_Callbacks: { 70: "WINDOW.toggleFullScreen()" // Toggle fullscreen }, initialize: function initialize() { this.updateSize(); // Create callbacks from keyboard $(document).keydown(function(inEvent) { WINDOW.callAction(inEvent.keyCode); }) ; $(window).resize(function(inEvent) { WINDOW.updateSize()...
ms_Width: 0, ms_Height: 0,
random_line_split
window.js
var WINDOW = { ms_Width: 0, ms_Height: 0, ms_Callbacks: { 70: "WINDOW.toggleFullScreen()" // Toggle fullscreen }, initialize: function initialize() { this.updateSize(); // Create callbacks from keyboard $(document).keydown(function(inEvent) { WINDOW.callAction(inEvent.keyCode); }) ; $(window).resiz...
}, toggleFullScreen: function toggleFullScreen() { if(!document.fullscreenElement && !document.mozFullScreenElement && !document.webkitFullscreenElement) { if(document.documentElement.requestFullscreen) document.documentElement.requestFullscreen(); else if(document.documentElement.mozRequestFullScreen) ...
{ eval(this.ms_Callbacks[inId]); return false ; }
conditional_block
test.py
from trie import Trie #constructs a tree of this shape ('*' means root) # # * # /|\ # a i o # / /|\ # n f n u # | |\ # e r t # #The LOUDS bit-string is then #[1, 0, 1, 1, 1, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0] words = ['an', 'i', 'of', 'one', 'our', 'out'] test_set =...
##parent [0, 0, 1, 1, 1, 1, 2, 2, 3, 4, 4, 4, 4, 5, 6, 7, 7, 8, 8, 8, 9, 0, 1] ##bit_array [1, 0, 1, 1, 1, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0] ##child [1, -, 2, 3, 4, -, 5, -, -, 6, 7, 8, -, -, -, 9, -, 0, 1, -, -, -, -] ##index [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,...
result = trie.search(query) print("query: {!s:>5} result: {!s:>5} answer: {!s:>5}".format( query, result, answer))
conditional_block
test.py
# # * # /|\ # a i o # / /|\ # n f n u # | |\ # e r t # #The LOUDS bit-string is then #[1, 0, 1, 1, 1, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0] words = ['an', 'i', 'of', 'one', 'our', 'out'] test_set = { 'out': 11, #'t' in 'out' is at 11th node in the tree 'our': ...
from trie import Trie #constructs a tree of this shape ('*' means root)
random_line_split
prod_setting.py
########################################################### # # Copyright (c) 2005, Southpaw Technology # All Rights Reserved # # PROPRIETARY INFORMATION. This software is proprietary to # Southpaw Technology, and is not to be reproduced, transmitted, # or disclosed in any way without written permi...
(SObject): '''Defines all of the settings for a given production''' SEARCH_TYPE = "config/prod_setting" # FIXME: what is this for? def get_app_tabs(my): '''This controls what tabs are visible''' return ["3D Asset", "Checkin", "Sets", "Anim Loader", "Anim Checkin", "Layer Loader", "Lay...
ProdSetting
identifier_name
prod_setting.py
########################################################### # # Copyright (c) 2005, Southpaw Technology # All Rights Reserved # # PROPRIETARY INFORMATION. This software is proprietary to # Southpaw Technology, and is not to be reproduced, transmitted, # or disclosed in any way without written permi...
ProdSetting.clear_cache() setting = ProdSetting.get_by_key(key, search_type) if not setting: setting= SObjectFactory.create( ProdSetting.SEARCH_TYPE ) setting.set_value("key", key) setting.set_value("value", value) setting.set_value(...
return None
conditional_block
prod_setting.py
########################################################### # # Copyright (c) 2005, Southpaw Technology # All Rights Reserved # # PROPRIETARY INFORMATION. This software is proprietary to # Southpaw Technology, and is not to be reproduced, transmitted, # or disclosed in any way without written permi...
'''Defines all of the settings for a given production''' SEARCH_TYPE = "config/prod_setting" # FIXME: what is this for? def get_app_tabs(my): '''This controls what tabs are visible''' return ["3D Asset", "Checkin", "Sets", "Anim Loader", "Anim Checkin", "Layer Loader", "Layer Checkin", "S...
identifier_body
prod_setting.py
########################################################### # # Copyright (c) 2005, Southpaw Technology # All Rights Reserved # # PROPRIETARY INFORMATION. This software is proprietary to # Southpaw Technology, and is not to be reproduced, transmitted, # or disclosed in any way without written permi...
def get_dict_by_key(cls, key, search_type=None): ''' this is to retrieve an unordered dict''' seq = [] dict = {} value = cls.get_value_by_key(key, search_type) if value: seq = value.split("|") for item in seq: try: key, value =...
raise TacticException('ProdSettings should be formated like &lt;key1&gt;:&lt;value1&gt;|&lt;key2&gt;:&lt;value2&gt;|...') return map get_map_by_key = classmethod(get_map_by_key)
random_line_split
components.ts
import { Reflection, Type } from "../models"; import type { Serializer } from "./serializer"; import type { ModelToObject } from "./schema"; /** * Represents Serializer plugin component. * * Like {@link Converter} plugins each {@link Serializer} plugin defines a predicate that instructs if an * object can be seri...
/** * Set when the SerializerComponent is added to the serializer. */ protected owner: Serializer; /** * A high-level predicate filtering which group this serializer belongs to. * This is a high-level filter before the {@link SerializerComponent.supports} predicate filter. * *...
this.owner = owner; }
random_line_split
components.ts
import { Reflection, Type } from "../models"; import type { Serializer } from "./serializer"; import type { ModelToObject } from "./schema"; /** * Represents Serializer plugin component. * * Like {@link Converter} plugins each {@link Serializer} plugin defines a predicate that instructs if an * object can be seri...
}
{ return instance instanceof Type; }
identifier_body
components.ts
import { Reflection, Type } from "../models"; import type { Serializer } from "./serializer"; import type { ModelToObject } from "./schema"; /** * Represents Serializer plugin component. * * Like {@link Converter} plugins each {@link Serializer} plugin defines a predicate that instructs if an * object can be seri...
(instance: unknown): boolean { return instance instanceof Type; } }
serializeGroup
identifier_name
test_vm_rest.py
# -*- coding: utf-8 -*- import fauxfactory import pytest from cfme import test_requirements from cfme.rest.gen_data import a_provider as _a_provider from cfme.rest.gen_data import vm as _vm from cfme.utils import error from cfme.utils.rest import assert_response, delete_resources_from_collection from cfme.utils.wait i...
(vm_name, appliance): vm = appliance.rest_api.collections.vms.get(name=vm_name) collection = appliance.rest_api.collections.vms delete_resources_from_collection(collection, [vm], not_found=True, num_sec=300, delay=10)
test_delete_vm_from_collection
identifier_name
test_vm_rest.py
# -*- coding: utf-8 -*- import fauxfactory import pytest from cfme import test_requirements from cfme.rest.gen_data import a_provider as _a_provider from cfme.rest.gen_data import vm as _vm from cfme.utils import error from cfme.utils.rest import assert_response, delete_resources_from_collection from cfme.utils.wait i...
@pytest.mark.tier(3) def test_delete_vm_from_collection(vm_name, appliance): vm = appliance.rest_api.collections.vms.get(name=vm_name) collection = appliance.rest_api.collections.vms delete_resources_from_collection(collection, [vm], not_found=True, num_sec=300, delay=10)
vm = appliance.rest_api.collections.vms.get(name=vm_name) del_action = getattr(vm.action.delete, method.upper()) del_action() assert_response(appliance) wait_for( lambda: not appliance.rest_api.collections.vms.find_by(name=vm_name), num_sec=300, delay=10) with error.expected('ActiveRecord::R...
identifier_body
test_vm_rest.py
# -*- coding: utf-8 -*- import fauxfactory import pytest from cfme import test_requirements from cfme.rest.gen_data import a_provider as _a_provider from cfme.rest.gen_data import vm as _vm from cfme.utils import error from cfme.utils.rest import assert_response, delete_resources_from_collection from cfme.utils.wait i...
) vm.reload() assert vm.description == edited.description == record[0].description @pytest.mark.tier(3) @pytest.mark.parametrize('method', ['post', 'delete'], ids=['POST', 'DELETE']) def test_delete_vm_from_detail(vm_name, appliance, method): vm = appliance.rest_api.collections.vms.get(name=vm_name) ...
num_sec=100, delay=5,
random_line_split
test_vm_rest.py
# -*- coding: utf-8 -*- import fauxfactory import pytest from cfme import test_requirements from cfme.rest.gen_data import a_provider as _a_provider from cfme.rest.gen_data import vm as _vm from cfme.utils import error from cfme.utils.rest import assert_response, delete_resources_from_collection from cfme.utils.wait i...
record, __ = wait_for( lambda: appliance.rest_api.collections.vms.find_by( description=new_description) or False, num_sec=100, delay=5, ) vm.reload() assert vm.description == edited.description == record[0].description @pytest.mark.tier(3) @pytest.mark.parametrize...
payload.update(vm._ref_repr()) edited = appliance.rest_api.collections.vms.action.edit(payload) assert_response(appliance) edited = edited[0]
conditional_block
patches_matrix.py
import numpy as np import math def get_patches(mat, patch_size=(4,4)): if mat.ndim == 1: dim = math.sqrt(mat.shape[0]) mat.reshape((dim, dim)) mat_rows = mat.shape[0] mat_cols = mat.shape[1] patches = None for i in xrange(mat_rows / patch_size[0]): for j in xrange(mat_cols...
else: patches = np.vstack(([patches], [patch])) return patches arr = np.array(xrange(32 * 32)).reshape(32, 32) patches = get_patches(arr) print patches
patches = np.vstack((patches, [patch]))
conditional_block
patches_matrix.py
import numpy as np import math def
(mat, patch_size=(4,4)): if mat.ndim == 1: dim = math.sqrt(mat.shape[0]) mat.reshape((dim, dim)) mat_rows = mat.shape[0] mat_cols = mat.shape[1] patches = None for i in xrange(mat_rows / patch_size[0]): for j in xrange(mat_cols / patch_size[1]): print patches ...
get_patches
identifier_name
patches_matrix.py
import numpy as np import math def get_patches(mat, patch_size=(4,4)): if mat.ndim == 1: dim = math.sqrt(mat.shape[0]) mat.reshape((dim, dim)) mat_rows = mat.shape[0] mat_cols = mat.shape[1] patches = None for i in xrange(mat_rows / patch_size[0]): for j in xrange(mat_cols...
patches = np.vstack(([patches], [patch])) return patches arr = np.array(xrange(32 * 32)).reshape(32, 32) patches = get_patches(arr) print patches
random_line_split
patches_matrix.py
import numpy as np import math def get_patches(mat, patch_size=(4,4)):
arr = np.array(xrange(32 * 32)).reshape(32, 32) patches = get_patches(arr) print patches
if mat.ndim == 1: dim = math.sqrt(mat.shape[0]) mat.reshape((dim, dim)) mat_rows = mat.shape[0] mat_cols = mat.shape[1] patches = None for i in xrange(mat_rows / patch_size[0]): for j in xrange(mat_cols / patch_size[1]): print patches patch = mat[i * pat...
identifier_body
server.js
/*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */ import 'babel-core/polyfill'; import path from 'path'; import express from 'express'; import React from 'react'; import ReactDOM from 'react-dom/server'; import Router from './routes'; import Html from './components/Html'; import assets from './a...
/* eslint-disable no-console */ console.log(`The server is running at http://localhost:${port}/`); });
// // Launch the server // ----------------------------------------------------------------------------- server.listen(port, () => {
random_line_split
messages.js
/* * Licensed Materials - Property of IBM * (C) Copyright IBM Corp. 2010, 2017 * US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA ADP Schedule Contract with IBM Corp. */ define({ // NLS_CHARSET=UTF-8 // configuration configuration_pane_aspera_url: "Adresa URL servera ...
send_dialog_title_label: "Názov:", send_dialog_note_label: "Pridajte správu.", send_dialog_earPassphrase_label: "Heslo pre šifrovanie:", send_dialog_earPassphrase_textfield_hover_help: "Zadajte heslo pre zašifrovanie súborov na serveri. Toto heslo budú musieť príjemcovia zadať, aby mohli dešifrovať chránené súb...
send_dialog_recipients_textfield_hover_help: "E-mailové adresy alebo mená užívateľov oddeľte čiarkou. Napríklad, zadajte: 'adresa1, adresa2, meno_užívateľa1, meno_užívateľa2'.", send_dialog_missing_recipients_message: "Zadajte aspoň jednu e-mailovú adresu alebo meno užívateľa.",
random_line_split
location_providers.ts
/** * @license * Copyright Google Inc. 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 */ import {Injector, NgZone, PLATFORM_INITIALIZER, Provider} from '@angular/core'; import {ɵBrowserPlatformLocation as...
injector: Injector): () => void { return () => { const zone = injector.get(NgZone); zone.runGuarded(() => injector.get(MessageBasedPlatformLocation).start()); }; }
nitUiLocation(
identifier_name
location_providers.ts
/** * @license * Copyright Google Inc. 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 */ import {Injector, NgZone, PLATFORM_INITIALIZER, Provider} from '@angular/core';
/** * A list of {@link Provider}s. To use the router in a Worker enabled application you must * include these providers when setting up the render thread. * @experimental */ export const WORKER_UI_LOCATION_PROVIDERS: Provider[] = [ MessageBasedPlatformLocation, BrowserPlatformLocation, {provide: PLATFORM_INIT...
import {ɵBrowserPlatformLocation as BrowserPlatformLocation} from '@angular/platform-browser'; import {MessageBasedPlatformLocation} from './platform_location';
random_line_split
location_providers.ts
/** * @license * Copyright Google Inc. 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 */ import {Injector, NgZone, PLATFORM_INITIALIZER, Provider} from '@angular/core'; import {ɵBrowserPlatformLocation as...
return () => { const zone = injector.get(NgZone); zone.runGuarded(() => injector.get(MessageBasedPlatformLocation).start()); }; }
identifier_body
_videoplayerApp.js
/* jshint -W117 */ /* Copyright 2016 Herko ter Horst __________________________________________________________________________ Filename: _videoplayerApp.js __________________________________________________________________________ */ log.addSrcFile("_videoplayerApp.js", "_videoplayer"); function _videoplayerAp...
}; /** * ========================= * Framework register * Tell framework this .js file has finished loading * ========================= */ framework.registerAppLoaded("_videoplayer", null, false);
{ setTimeout(function() { if (framework.getCurrentApp() === 'usbaudio') { framework.sendEventToMmui('Common', 'Global.Pause'); framework.sendEventToMmui('Common', 'Global.GoBack'); this.musicIsPaused = true; // Only run this once } }, 100); }
conditional_block
_videoplayerApp.js
/* jshint -W117 */ /* Copyright 2016 Herko ter Horst __________________________________________________________________________ Filename: _videoplayerApp.js __________________________________________________________________________ */ log.addSrcFile("_videoplayerApp.js", "_videoplayer"); function _videoplayerAp...
} }, 100); } }; /** * ========================= * Framework register * Tell framework this .js file has finished loading * ========================= */ framework.registerAppLoaded("_videoplayer", null, false);
this.musicIsPaused = true; // Only run this once
random_line_split
_videoplayerApp.js
/* jshint -W117 */ /* Copyright 2016 Herko ter Horst __________________________________________________________________________ Filename: _videoplayerApp.js __________________________________________________________________________ */ log.addSrcFile("_videoplayerApp.js", "_videoplayer"); function _videoplayerAp...
// load jQuery Globally (if needed) if (!window.jQuery) { utility.loadScript("addon-common/jquery.min.js"); } /********************************* * App Init is standard function * * called by framework * *********************************/ /* * Called just after the app is instantiated by framework. *...
{ log.debug("Constructor called."); // Base application functionality is provided in a common location via this call to baseApp.init(). // See framework/js/BaseApp.js for details. baseApp.init(this, uiaId); }
identifier_body
_videoplayerApp.js
/* jshint -W117 */ /* Copyright 2016 Herko ter Horst __________________________________________________________________________ Filename: _videoplayerApp.js __________________________________________________________________________ */ log.addSrcFile("_videoplayerApp.js", "_videoplayer"); function
(uiaId) { log.debug("Constructor called."); // Base application functionality is provided in a common location via this call to baseApp.init(). // See framework/js/BaseApp.js for details. baseApp.init(this, uiaId); } // load jQuery Globally (if needed) if (!window.jQuery) { utility.loadScript("addon-common/...
_videoplayerApp
identifier_name
notifications.js
// add new post notification callback on post submit postAfterSubmitMethodCallbacks.push(function (post) { var adminIds = _.pluck(Meteor.users.find({'isAdmin': true}, {fields: {_id:1}}).fetch(), '_id'); var notifiedUserIds = _.pluck(Meteor.users.find({'profile.notifications.posts': 1}, {fields: {_id:1}}).fetch(), ...
(user) { // set notifications default preferences user.profile.notifications = { users: false, posts: false, comments: true, replies: true }; return user; } userCreatedCallbacks.push(setNotificationDefaults);
setNotificationDefaults
identifier_name
notifications.js
// add new post notification callback on post submit postAfterSubmitMethodCallbacks.push(function (post) { var adminIds = _.pluck(Meteor.users.find({'isAdmin': true}, {fields: {_id:1}}).fetch(), '_id'); var notifiedUserIds = _.pluck(Meteor.users.find({'profile.notifications.posts': 1}, {fields: {_id:1}}).fetch(), ...
} return comment; }); var emailNotifications = { propertyName: 'emailNotifications', propertySchema: { type: Boolean, optional: true, defaultValue: true, autoform: { group: 'notifications_fieldset', instructions: 'Enable email notifications for new posts and new comments (requir...
{ // remove userIds of users that have already been notified // and of comment author (they could be replying in a thread they're subscribed to) var subscriberIdsToNotify = _.difference(post.subscribers, userIdsNotified, [comment.userId]); Herald.createNotification(subscriberIdsToNotify, {couri...
conditional_block
notifications.js
// add new post notification callback on post submit postAfterSubmitMethodCallbacks.push(function (post) { var adminIds = _.pluck(Meteor.users.find({'isAdmin': true}, {fields: {_id:1}}).fetch(), '_id'); var notifiedUserIds = _.pluck(Meteor.users.find({'profile.notifications.posts': 1}, {fields: {_id:1}}).fetch(), ...
comments: true, replies: true }; return user; } userCreatedCallbacks.push(setNotificationDefaults);
user.profile.notifications = { users: false, posts: false,
random_line_split
notifications.js
// add new post notification callback on post submit postAfterSubmitMethodCallbacks.push(function (post) { var adminIds = _.pluck(Meteor.users.find({'isAdmin': true}, {fields: {_id:1}}).fetch(), '_id'); var notifiedUserIds = _.pluck(Meteor.users.find({'profile.notifications.posts': 1}, {fields: {_id:1}}).fetch(), ...
userCreatedCallbacks.push(setNotificationDefaults);
{ // set notifications default preferences user.profile.notifications = { users: false, posts: false, comments: true, replies: true }; return user; }
identifier_body
errors.rs
use rstest::*; #[fixture] pub fn fixture() -> u32 { 42 } #[fixture] fn error_inner(fixture: u32) { let a: u32 = ""; } #[fixture] fn error_cannot_resolve_fixture(no_fixture: u32) { } #[fixture] fn error_fixture_wrong_type(fixture: String) { } #[fixture(not_a_fixture(24))] fn error_inject_an_invalid_fixture(fixt...
#[fixture] #[once] async fn error_async_once_fixture() { } #[fixture] #[once] fn error_generics_once_fixture<T: std::fmt::Debug>() -> T { 42 } #[fixture] #[once] fn error_generics_once_fixture() -> impl Iterator<Item: u32> { std::iter::once(42) }
{ }
identifier_body
errors.rs
use rstest::*; #[fixture] pub fn fixture() -> u32 { 42 } #[fixture] fn error_inner(fixture: u32) { let a: u32 = ""; } #[fixture] fn error_cannot_resolve_fixture(no_fixture: u32) { } #[fixture] fn error_fixture_wrong_type(fixture: String) { } #[fixture(not_a_fixture(24))] fn error_inject_an_invalid_fixture(fixt...
fn error_generics_once_fixture() -> impl Iterator<Item: u32> { std::iter::once(42) }
} #[fixture] #[once]
random_line_split
errors.rs
use rstest::*; #[fixture] pub fn fixture() -> u32 { 42 } #[fixture] fn error_inner(fixture: u32) { let a: u32 = ""; } #[fixture] fn error_cannot_resolve_fixture(no_fixture: u32) { } #[fixture] fn error_fixture_wrong_type(fixture: String) { } #[fixture(not_a_fixture(24))] fn error_inject_an_invalid_fixture(fixt...
(name: &str) -> String { name.to_owned() } #[fixture(f("first"), f("second"))] fn error_inject_a_fixture_more_than_once(f: String) { } #[fixture] #[once] async fn error_async_once_fixture() { } #[fixture] #[once] fn error_generics_once_fixture<T: std::fmt::Debug>() -> T { 42 } #[fixture] #[once] fn error_ge...
f
identifier_name
multipart.rs
use std::fmt; use std::fs::File; use std::io::Read; use std::io::Write; use std::path::PathBuf; use mime_guess; use crate::error::Result; use crate::http::plus::random_alphanumeric; const BOUNDARY_LEN: usize = 32; fn gen_boundary() -> String { random_alphanumeric(BOUNDARY_LEN) } use crate::http::mime::{self, M...
} #[derive(Debug)] struct Field<'a> { name: String, data: Data<'a>, } enum Data<'a> { Text(String), File(PathBuf), Stream(Stream<'a>), } impl<'a> fmt::Debug for Data<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { Data::Text(ref value) => write!...
{ let mut boundary = format!("\r\n--{}", gen_boundary()); let mut buf: Vec<u8> = Vec::new(); for field in self.fields.drain(..) { match field.data { Data::Text(value) => { write!( buf, "{}\r\nConten...
identifier_body
multipart.rs
use std::fmt; use std::fs::File; use std::io::Read; use std::io::Write; use std::path::PathBuf; use mime_guess; use crate::error::Result; use crate::http::plus::random_alphanumeric; const BOUNDARY_LEN: usize = 32; fn gen_boundary() -> String { random_alphanumeric(BOUNDARY_LEN) } use crate::http::mime::{self, M...
<'a> { Text(String), File(PathBuf), Stream(Stream<'a>), } impl<'a> fmt::Debug for Data<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { Data::Text(ref value) => write!(f, "Data::Text({:?})", value), Data::File(ref path) => write!(f, "Data::File(...
Data
identifier_name
multipart.rs
use std::fmt; use std::fs::File; use std::io::Read; use std::io::Write; use std::path::PathBuf; use mime_guess; use crate::error::Result; use crate::http::plus::random_alphanumeric; const BOUNDARY_LEN: usize = 32; fn gen_boundary() -> String { random_alphanumeric(BOUNDARY_LEN) } use crate::http::mime::{self, M...
V: Into<String>, { let filed = Field { name: name.into(), data: Data::Text(value.into()), }; self.fields.push(filed); self } /// Add file into `Multipart`. /// /// # Examples /// /// ```no_test /// use sincere::http::plus...
where
random_line_split
multipart.rs
use std::fmt; use std::fs::File; use std::io::Read; use std::io::Write; use std::path::PathBuf; use mime_guess; use crate::error::Result; use crate::http::plus::random_alphanumeric; const BOUNDARY_LEN: usize = 32; fn gen_boundary() -> String { random_alphanumeric(BOUNDARY_LEN) } use crate::http::mime::{self, M...
Data::File(path) => { let (content_type, filename) = mime_filename(&path); let mut file = File::open(&path)?; write!( buf, "{}\r\nContent-Disposition: form-data; name=\"{}\"", ...
{ write!( buf, "{}\r\nContent-Disposition: form-data; name=\"{}\"\r\n\r\n{}", boundary, field.name, value )?; }
conditional_block
reimport_knowls_and_userdb.sage.py
# This file was *autogenerated* from the file reimport_knowls_and_userdb.sage from sage.all_cmdline import * # import sage library _sage_const_0 = Integer(0) os.chdir("/home/edgarcosta/lmfdb/") import lmfdb db = lmfdb.db_backend.db DelayCommit = lmfdb.db_backend.DelayCommit load("/home/edgarcosta/lmfdb-gce/transiti...
def import_users(): with DelayCommit(db, silence=True): try: conn = db.conn cur = conn.cursor() # delete rows of usersdb.users "DELETE FROM userdb.users;" with open('/scratch/importing/users.txt') as F: cur.copy_from(F, 'userd...
from psycopg2.sql import SQL cur = db.conn.cursor() tablenames = ['kwl_history', 'kwl_deleted', 'kwl_knowls']; with DelayCommit(db, silence=True): try: # rename old tables for name in tablenames: cur.execute("ALTER TABLE IF EXISTS %s DROP CONSTRAINT IF EXISTS ...
identifier_body
reimport_knowls_and_userdb.sage.py
# This file was *autogenerated* from the file reimport_knowls_and_userdb.sage from sage.all_cmdline import * # import sage library _sage_const_0 = Integer(0) os.chdir("/home/edgarcosta/lmfdb/") import lmfdb db = lmfdb.db_backend.db DelayCommit = lmfdb.db_backend.DelayCommit load("/home/edgarcosta/lmfdb-gce/transitio...
except DatabaseError as err: conn.rollback() print "Failure in importing users" print err print "Successfully imported users" export_knowls() export_users() backup() import_knowls() import_users()
random_line_split
reimport_knowls_and_userdb.sage.py
# This file was *autogenerated* from the file reimport_knowls_and_userdb.sage from sage.all_cmdline import * # import sage library _sage_const_0 = Integer(0) os.chdir("/home/edgarcosta/lmfdb/") import lmfdb db = lmfdb.db_backend.db DelayCommit = lmfdb.db_backend.DelayCommit load("/home/edgarcosta/lmfdb-gce/transiti...
# create tables cur.execute("CREATE TABLE kwl_knowls (id text, cat text, title text, content text, authors jsonb, last_author text, quality text, timestamp timestamp, _keywords jsonb, history jsonb)") cur.execute("CREATE TABLE kwl_deleted (id text, cat text, title text, content tex...
cur.execute("ALTER TABLE IF EXISTS %s DROP CONSTRAINT IF EXISTS %s_pkey" % (name, name)); cur.execute("DROP TABLE IF EXISTS %s" % name);
conditional_block
reimport_knowls_and_userdb.sage.py
# This file was *autogenerated* from the file reimport_knowls_and_userdb.sage from sage.all_cmdline import * # import sage library _sage_const_0 = Integer(0) os.chdir("/home/edgarcosta/lmfdb/") import lmfdb db = lmfdb.db_backend.db DelayCommit = lmfdb.db_backend.DelayCommit load("/home/edgarcosta/lmfdb-gce/transiti...
(): import subprocess timestamp = datetime.now().strftime("%Y%m%d-%H%M") userdbdump="/scratch/postgres-backup/userdb-backup-%s.tar" % timestamp knowlsdump="/scratch/postgres-backup/knowls-backup-%s.tar" % timestamp a = subprocess.check_call(["sudo", "-u", "postgres", "pg_dump", "--clean", "--if-exis...
backup
identifier_name
grover_example.py
#!/usr/bin/env python """Grover's quantum search algorithm example.""" from sympy import pprint from sympy.physics.quantum import qapply from sympy.physics.quantum.qubit import IntQubit from sympy.physics.quantum.grover import (OracleGate, superposition_basis, WGate, grover_iteration) def demo_vgate_app(v):...
print('WGate or w = WGate(%r)' % nqubits) print('On a 2 Qubit system like psi, 1 iteration is enough to yield |1>') print('qapply(w*v*psi)') pprint(qapply(w*v*psi)) print() nqubits = 3 print('On a 3 Qubit system, it requires 2 iterations to achieve') print('|1> with high enough probabil...
print('qapply(v*psi)') pprint(qapply(v*psi)) print() w = WGate(nqubits)
random_line_split
grover_example.py
#!/usr/bin/env python """Grover's quantum search algorithm example.""" from sympy import pprint from sympy.physics.quantum import qapply from sympy.physics.quantum.qubit import IntQubit from sympy.physics.quantum.grover import (OracleGate, superposition_basis, WGate, grover_iteration) def demo_vgate_app(v):...
(): print() print('Demonstration of Grover\'s Algorithm') print('The OracleGate or V Gate carries the unknown function f(x)') print('> V|x> = ((-1)^f(x))|x> where f(x) = 1 when x = a (True in our case)') print('> and 0 (False in our case) otherwise') print() nqubits = 2 print('nqubits =...
main
identifier_name
grover_example.py
#!/usr/bin/env python """Grover's quantum search algorithm example.""" from sympy import pprint from sympy.physics.quantum import qapply from sympy.physics.quantum.qubit import IntQubit from sympy.physics.quantum.grover import (OracleGate, superposition_basis, WGate, grover_iteration) def demo_vgate_app(v):...
main()
conditional_block
grover_example.py
#!/usr/bin/env python """Grover's quantum search algorithm example.""" from sympy import pprint from sympy.physics.quantum import qapply from sympy.physics.quantum.qubit import IntQubit from sympy.physics.quantum.grover import (OracleGate, superposition_basis, WGate, grover_iteration) def demo_vgate_app(v):...
def black_box(qubits): return True if qubits == IntQubit(1, nqubits=qubits.nqubits) else False def main(): print() print('Demonstration of Grover\'s Algorithm') print('The OracleGate or V Gate carries the unknown function f(x)') print('> V|x> = ((-1)^f(x))|x> where f(x) = 1 when x = a (True in ...
for i in range(2**v.nqubits): print('qapply(v*IntQubit(%i, %r))' % (i, v.nqubits)) pprint(qapply(v*IntQubit(i, nqubits=v.nqubits))) qapply(v*IntQubit(i, nqubits=v.nqubits))
identifier_body
default.rs
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
fn default_substructure(cx: &mut ExtCtxt, trait_span: Span, substr: &Substructure) -> P<Expr> { let default_ident = vec!( cx.ident_of_std("core"), cx.ident_of("default"), cx.ident_of("Default"), cx.ident_of("default") ); let default_call = |span| cx.expr_call_global(span, d...
{ let inline = cx.meta_word(span, InternedString::new("inline")); let attrs = vec!(cx.attribute(span, inline)); let trait_def = TraitDef { span: span, attributes: Vec::new(), path: path_std!(cx, core::default::Default), additional_bounds: Vec::new(), generics: Lifetim...
identifier_body
default.rs
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
StaticEnum(..) => { cx.span_err(trait_span, "`Default` cannot be derived for enums, only structs"); // let compilation continue cx.expr_usize(trait_span, 0) } _ => cx.span_bug(trait_span, "Non-static method in `derive(Default)`") }; }
{ match *summary { Unnamed(ref fields) => { if fields.is_empty() { cx.expr_ident(trait_span, substr.type_ident) } else { let exprs = fields.iter().map(|sp| default_call(*sp)).collect(); ...
conditional_block
default.rs
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
use ext::deriving::generic::*; use ext::deriving::generic::ty::*; use parse::token::InternedString; use ptr::P; pub fn expand_deriving_default<F>(cx: &mut ExtCtxt, span: Span, mitem: &MetaItem, item: &Item, ...
random_line_split
default.rs
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
<F>(cx: &mut ExtCtxt, span: Span, mitem: &MetaItem, item: &Item, push: F) where F: FnOnce(P<Item>), { let inline = cx.meta_word(span, InternedString::new("inline")); let at...
expand_deriving_default
identifier_name
pipes.py
from cgi import escape import gzip as gzip_module import re import time import types import uuid from cStringIO import StringIO def resolve_content(response): rv = "".join(item for item in response.iter_content()) if type(rv) == unicode: rv = rv.encode(response.encoding) return rv class Pipeline...
elif char == ",": return ("argument", rv) elif char == ")": self.state = self.func_name_state return ("argument", rv) else: rv += char def get_escape(self): char = self.get_char() escapes = {"n": "\...
rv += self.get_escape() if rv is None: #This should perhaps be an error instead return ("argument", rv)
conditional_block
pipes.py
from cgi import escape import gzip as gzip_module import re import time import types import uuid from cStringIO import StringIO def resolve_content(response): rv = "".join(item for item in response.iter_content()) if type(rv) == unicode: rv = rv.encode(response.encoding) return rv class Pipeline...
def inner(request, response, *args): if not (self.min_args <= len(args) <= self.max_args): raise ValueError("Expected between %d and %d args, got %d" % (self.min_args, self.max_args, len(args))) arg_values = tuple(f(x) for f, x in zip(self...
if not isinstance(item, opt): raise ValueError("Non-optional argument cannot follow optional argument") def __call__(self, f):
random_line_split
pipes.py
from cgi import escape import gzip as gzip_module import re import time import types import uuid from cStringIO import StringIO def resolve_content(response): rv = "".join(item for item in response.iter_content()) if type(rv) == unicode: rv = rv.encode(response.encoding) return rv class Pipeline...
(self): rv = "" while True: char = self.get_char() if char is None: self.state = None return ("argument", rv) elif char == "\\": rv += self.get_escape() if rv is None: #This should per...
argument_state
identifier_name
pipes.py
from cgi import escape import gzip as gzip_module import re import time import types import uuid from cStringIO import StringIO def resolve_content(response): rv = "".join(item for item in response.iter_content()) if type(rv) == unicode: rv = rv.encode(response.encoding) return rv class Pipeline...
return inner def boolean(arg): if arg.lower() in ("true", "1"): return True elif arg.lower() in ("false", "0"): return False raise ValueError @pipe(int) def status(request, response, code): """Alter the status code. :param code: Status code to use for the response.""" r...
if arg.lower() == "null": return None else: return func(arg)
identifier_body
mixcloud.js
import React from 'react' import Icon from 'react-icon-base' const FaMixcloud = props => (
<Icon viewBox="0 0 40 40" {...props}> <g><path d="m28.8 23.5q0-1-0.6-1.8t-1.5-1.2q-0.1 0.8-0.4 1.6-0.1 0.4-0.5 0.6t-0.8 0.3q-0.2 0-0.4-0.1-0.5-0.1-0.8-0.6t-0.1-1.1q0.4-1.2 0.4-2.5 0-2.1-1-3.9t-2.9-2.9-4-1.1q-2.4 0-4.3 1.3t-3 3.4q1.9 0.5 3.3 1.8 0.4 0.4 0.4 1t-0.4 0.9-0.9 0.4-1-0.4q-1.3-1.3-3.1-1.3-1.9 0-3.2...
random_line_split
hostproof_auth.js
function supports_html5_storage() { try { return 'localStorage' in window && window['localStorage'] !== null; } catch (e) { return false; } } function randomString(length)
function register(baseUrl, username, email, password) { var deferred = new $.Deferred(); if (username && email && password) { challenge = randomString(10) encrypted_challenge = sjcl.encrypt(password, challenge) $.when( $.ajax({ type: "POST", ...
{ var text = ""; var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; for(var i=0; i < length; i++) { text += chars.charAt(Math.floor(Math.random() * chars.length)); } return text; }
identifier_body
hostproof_auth.js
function supports_html5_storage() {
} function randomString(length) { var text = ""; var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; for(var i=0; i < length; i++) { text += chars.charAt(Math.floor(Math.random() * chars.length)); } return text; } function register(baseUrl, username, email, passwo...
try { return 'localStorage' in window && window['localStorage'] !== null; } catch (e) { return false; }
random_line_split
hostproof_auth.js
function supports_html5_storage() { try { return 'localStorage' in window && window['localStorage'] !== null; } catch (e) { return false; } } function randomString(length) { var text = ""; var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; for(var i=0;...
return text; } function register(baseUrl, username, email, password) { var deferred = new $.Deferred(); if (username && email && password) { challenge = randomString(10) encrypted_challenge = sjcl.encrypt(password, challenge) $.when( $.ajax({ type: "POST...
{ text += chars.charAt(Math.floor(Math.random() * chars.length)); }
conditional_block
hostproof_auth.js
function
() { try { return 'localStorage' in window && window['localStorage'] !== null; } catch (e) { return false; } } function randomString(length) { var text = ""; var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; for(var i=0; i < length; i++) { tex...
supports_html5_storage
identifier_name
utils.py
# Copyright 2015 Palo Alto Networks, Inc # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agre...
(self): self.w.release() self.m2.acquire() self.num_writers -= 1 if self.num_writers == 0: self.r.release() self.m2.release() def rlock(self): self.m3.acquire() self.r.acquire() self.m1.acquire() self.num_readers += 1 if...
unlock
identifier_name
utils.py
# Copyright 2015 Palo Alto Networks, Inc # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agre...
return v1 RESERVED_ATTRIBUTES = { 'sources': _merge_array, 'first_seen': functools.partial(_merge_atomic_values, operator.gt), 'last_seen': functools.partial(_merge_atomic_values, operator.lt), 'type': functools.partial(_merge_atomic_values, operator.eq), 'direction': functools.partial(_merge...
if e not in v1: v1.append(e)
conditional_block
utils.py
# Copyright 2015 Palo Alto Networks, Inc # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agre...
def age_out_in_millisec(val): multipliers = { '': 1000, 'm': 60000, 'h': 3600000, 'd': 86400000 } mo = re.match("([0-9]+)([dmh]?)", val) if mo is None: return None return int(mo.group(1))*multipliers[mo.group(2)] def _merge_atomic_values(op, v1, v2): ...
if isinstance(val, int): return val multipliers = { '': 1, 'm': 60, 'h': 3600, 'd': 86400 } mo = re.match("([0-9]+)([dmh]?)", val) if mo is None: return None return int(mo.group(1))*multipliers[mo.group(2)]
identifier_body
utils.py
# Copyright 2015 Palo Alto Networks, Inc # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agre...
self.m1.release() def __enter__(self): self.rlock() def __exit__(self, type, value, traceback): self.runlock() _AGE_OUT_BASES = ['last_seen', 'first_seen'] def parse_age_out(s, age_out_bases=None, default_base=None): if s is None: return None if age_out_bases is N...
self.w.release()
random_line_split
htmlCombinatorCommentBody.js
'use strict'; exports.__esModule = true; var _postcssSelectorParser = require('postcss-selector-parser'); var _postcssSelectorParser2 = _interopRequireDefault(_postcssSelectorParser); var _exists = require('../exists'); var _exists2 = _interopRequireDefault(_exists); var _isMixin = require('../isMixin'); var _is...
var _browsers = require('../dictionary/browsers'); var _identifiers = require('../dictionary/identifiers'); var _postcss = require('../dictionary/postcss'); var _tags = require('../dictionary/tags'); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function analyse(ct...
var _plugin2 = _interopRequireDefault(_plugin);
random_line_split
htmlCombinatorCommentBody.js
'use strict'; exports.__esModule = true; var _postcssSelectorParser = require('postcss-selector-parser'); var _postcssSelectorParser2 = _interopRequireDefault(_postcssSelectorParser); var _exists = require('../exists'); var _exists2 = _interopRequireDefault(_exists); var _isMixin = require('../isMixin'); var _is...
(ctx, rule) { return function (selectors) { selectors.each(function (selector) { if ((0, _exists2.default)(selector, 0, _tags.HTML) && ((0, _exists2.default)(selector, 1, '>') || (0, _exists2.default)(selector, 1, '~')) && selector.at(2) && selector.at(2).type === 'comment' && (0, _exists2.defau...
analyse
identifier_name
htmlCombinatorCommentBody.js
'use strict'; exports.__esModule = true; var _postcssSelectorParser = require('postcss-selector-parser'); var _postcssSelectorParser2 = _interopRequireDefault(_postcssSelectorParser); var _exists = require('../exists'); var _exists2 = _interopRequireDefault(_exists); var _isMixin = require('../isMixin'); var _is...
}); }; } exports.default = (0, _plugin2.default)([_browsers.IE_5_5, _browsers.IE_6, _browsers.IE_7], [_postcss.RULE], function (rule) { if ((0, _isMixin2.default)(rule)) { return; } if (rule.raws.selector && rule.raws.selector.raw) { (0, _postcssSelectorParser2.default)(analyse...
{ ctx.push(rule, { identifier: _identifiers.SELECTOR, hack: selector.toString() }); }
conditional_block
htmlCombinatorCommentBody.js
'use strict'; exports.__esModule = true; var _postcssSelectorParser = require('postcss-selector-parser'); var _postcssSelectorParser2 = _interopRequireDefault(_postcssSelectorParser); var _exists = require('../exists'); var _exists2 = _interopRequireDefault(_exists); var _isMixin = require('../isMixin'); var _is...
function analyse(ctx, rule) { return function (selectors) { selectors.each(function (selector) { if ((0, _exists2.default)(selector, 0, _tags.HTML) && ((0, _exists2.default)(selector, 1, '>') || (0, _exists2.default)(selector, 1, '~')) && selector.at(2) && selector.at(2).type === 'comment' && ...
{ return obj && obj.__esModule ? obj : { default: obj }; }
identifier_body
05_ExampleDoc.py
#ImportModules import ShareYourSystem as SYS #figure MyPyploter=SYS.PyploterClass( ).mapSet( { '-Charts': { '|a':{ '-Draws':[ ('|0',{ 'PyplotingDrawVariable': [ ( 'plot', { '#liarg':[ [1,2,3], [2,6,3] ], ...
'PyplotingDrawVariable': [ ( 'plot', { '#liarg':[ [0,1,2], [2,3,4] ], '#kwarg':{ 'linestyle':"--", 'color':'r' } } ) ], }) ], 'PyplotingChartVariable': ...
('|1',{
random_line_split
cmd.rs
use std::f32; use std::sync::Arc; use std::sync::Mutex; use std::fs::File; use std::time::{Duration, Instant}; use std::io::{BufRead, BufReader}; use std::io::{Read, Write}; use std::net::{TcpListener, TcpStream}; use crate::eval_paths::EvalPaths; use crate::debug_path::DebugPath; use crate::graph::Graph; use crate::...
(out: &mut std::fmt::Write) -> Result<(), MyError> { for item in COMMANDS { if item.1 != Cid::Error { writeln!(out, "{}", item.0)?; } } Ok(()) } fn cmd_handler(out: &mut std::fmt::Write, sim: &mut GlobalState, input: &str, call: AllowRecursiveCall) -> Result<(), MyError> { let mut mark_links : Option<Graph>...
print_help
identifier_name
cmd.rs
use std::f32; use std::sync::Arc; use std::sync::Mutex; use std::fs::File; use std::time::{Duration, Instant}; use std::io::{BufRead, BufReader}; use std::io::{Read, Write}; use std::net::{TcpListener, TcpStream}; use crate::eval_paths::EvalPaths; use crate::debug_path::DebugPath; use crate::graph::Graph; use crate::...
sim.test.show_progress(sim.show_progress); run_test(out, &mut sim.test, &sim.graph, &sim.algorithm, samples)?; }, Command::Debug(from, to) => { let node_count = sim.graph.node_count() as u32; if (from < node_count) && (from < node_count) { sim.debug_path.init(from, to); writeln!(out, "Init path...
{ test.clear(); test.run_samples(graph, |p| algo.route(&p), samples as usize); writeln!(out, "samples: {}, arrived: {:.1}, stretch: {}, duration: {}", samples, test.arrived(), test.stretch(), fmt_duration(test.duration()) ) }
identifier_body
cmd.rs
use std::f32; use std::sync::Arc; use std::sync::Mutex; use std::fs::File; use std::time::{Duration, Instant}; use std::io::{BufRead, BufReader}; use std::io::{Read, Write}; use std::net::{TcpListener, TcpStream}; use crate::eval_paths::EvalPaths; use crate::debug_path::DebugPath; use crate::graph::Graph; use crate::p...
("tree <node_count> [<inter_count>] Add a tree structure of nodes with interconnections", Cid::AddTree), ("lattice4 <x_xount> <y_count> Create a lattice structure of squares.", Cid::AddLattice4), ("lattice8 <x_xount> <y_count> Create a lattice structure of squares and diagonal connections.", Cid::AddLat...
("line <node_count> [<create_loop>] Add a line of nodes. Connect ends to create a loop.", Cid::AddLine), ("star <edge_count> Add star structure of nodes.", Cid::AddStar),
random_line_split
app.module.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 */ import {Component, NgModule, ViewEncapsulation} from '@angular/core'; import {BrowserModule} from '@angular/platform-...
() { this.isTwoVisible = true; } hideTwo() { this.isTwoVisible = false; } showTen() { this.isTenVisible = true; } hideTen() { this.isTenVisible = false; } } @NgModule({ declarations: [RadioBenchmarkApp], imports: [ BrowserModule, MatRadioModule, ], bootstrap: [RadioBenchmarkApp], }) export class...
showTwo
identifier_name
app.module.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 */ import {Component, NgModule, ViewEncapsulation} from '@angular/core'; import {BrowserModule} from '@angular/platform-...
hideTwo() { this.isTwoVisible = false; } showTen() { this.isTenVisible = true; } hideTen() { this.isTenVisible = false; } } @NgModule({ declarations: [RadioBenchmarkApp], imports: [ BrowserModule, MatRadioModule, ], bootstrap: [RadioBenchmarkApp], }) export class AppModule {}
{ this.isTwoVisible = true; }
identifier_body
app.module.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 */ import {Component, NgModule, ViewEncapsulation} from '@angular/core';
/** component: mat-radio-button */ @Component({ selector: 'app-root', template: ` <button id="show-two" (click)="showTwo()">Show Two</button> <button id="hide-two" (click)="hideTwo()">Hide Two</button> <button id="show-ten" (click)="showTen()">Show Ten</button> <button id="hide-ten" (click)="hideT...
import {BrowserModule} from '@angular/platform-browser'; import {MatRadioModule} from '@angular/material/radio';
random_line_split