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
query_string_parser.py
################################################################################################### # # query_string_parser.py # Extracts the query string from a URL and prints each parameter and value. # # Plugin Author: Your Name Here (ryan@obsidianforensics.com) # ##################################################...
(analysis_session=None): import urllib.parse # Setting up our return variable global parsedItems parsedItems = 0 for item in analysis_session.parsed_artifacts: # For each item that Hindsight has parsed, if item.row_type.startswith(artifactTypes): # if the row if of...
plugin
identifier_name
query_string_parser.py
################################################################################################### # # query_string_parser.py # Extracts the query string from a URL and prints each parameter and value.
# Plugin Author: Your Name Here (ryan@obsidianforensics.com) # ################################################################################################### # Config friendlyName = "Query String Parser" description = "Extracts the query string from a URL and prints each field and value." artifactTypes = ("url", ...
#
random_line_split
UserRepository.ts
import { IRepository, RetrieveOptions } from "../data/IRepository"; import { AbstractRepository } from "./AbstractRepository"; import { IUserEntity, UserEntity } from "../entities/UserEntity"; import { UserDocument } from "../entities/documents/UserDocument"; import { UserSchema } from "./schemas/UserSchema"; import * ...
(document: UserDocument): IUserEntity { return UserEntity.toEntity(document); } /** * Converts an user document array to an * array of user entities. * * @param documentArray user document array. * @returns an user entity array. */ protected convertToEntityArray(docum...
convertToEntity
identifier_name
UserRepository.ts
import { IRepository, RetrieveOptions } from "../data/IRepository"; import { AbstractRepository } from "./AbstractRepository"; import { IUserEntity, UserEntity } from "../entities/UserEntity"; import { UserDocument } from "../entities/documents/UserDocument"; import { UserSchema } from "./schemas/UserSchema"; import * ...
}
{ return { id: item.id }; }
identifier_body
UserRepository.ts
import { IRepository, RetrieveOptions } from "../data/IRepository"; import { AbstractRepository } from "./AbstractRepository"; import { IUserEntity, UserEntity } from "../entities/UserEntity"; import { UserDocument } from "../entities/documents/UserDocument"; import { UserSchema } from "./schemas/UserSchema"; import * ...
* @returns an user entity. */ findByLogin(login: string): Promise<IUserEntity>; } /** * User Repository class. * * @author Mario Juez <mario[at]mjuez.com> */ export class UserRepository extends AbstractRepository<IUserEntity, UserDocument> implements IUserRepository { /** MongoDB collection na...
* @param login User login.
random_line_split
events.py
# Copyright 2012 OpenStack Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requ...
(base.Resource): def __repr__(self): return "<Event %s>" % self._info def update(self, **fields): self.manager.update(self, **fields) def delete(self): return self.manager.delete(self) def data(self, **kwargs): return self.manager.data(self, **kwargs) class EventMana...
Event
identifier_name
events.py
# Copyright 2012 OpenStack Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requ...
def data(self, **kwargs): return self.manager.data(self, **kwargs) class EventManager(stacks.StackChildManager): resource_class = Event def list(self, stack_id, resource_name=None, **kwargs): """Get a list of events. :param stack_id: ID of stack the events belong to :pa...
return self.manager.delete(self)
identifier_body
events.py
# Copyright 2012 OpenStack Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requ...
if resource_name is None: url = '/stacks/%s/events' % stack_id else: stack_id = self._resolve_stack_id(stack_id) url = '/stacks/%s/resources/%s/events' % ( parse.quote(stack_id, ''), parse.quote(encodeutils.safe_encode(resource_name),...
if value: params[key] = value
conditional_block
events.py
# Copyright 2012 OpenStack Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain
# Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under th...
# a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #
random_line_split
setup.py
#!/usr/bin/env python # # 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 (th...
license="Apache License v2", url="https://bloodhound.apache.org/", requires=['trac', 'BloodhoundMultiProduct'], packages=['bhsetup'], entry_points=""" [console_scripts] bloodhound_setup = bhsetup.bloodhound_setup:run """, long_description=DESC, )
author="Apache Bloodhound",
random_line_split
server.js
import express from 'express'; import path from 'path'; import logger from 'morgan'; import bodyParser from 'body-parser';
if (process.env.DEBUG) { app.use(logger('combined')); } app.use(express.static(path.resolve(__dirname, '../fixtures'))); app.use(bodyParser.json()); app.get('/ping', (req, res) => { res.sendStatus(200); }); app.get('/401', (req, res) => { res.status(401).send({ errors: ['unauthorized req'] }); }); app.post('/...
const app = express();
random_line_split
server.js
import express from 'express'; import path from 'path'; import logger from 'morgan'; import bodyParser from 'body-parser'; const app = express(); if (process.env.DEBUG)
app.use(express.static(path.resolve(__dirname, '../fixtures'))); app.use(bodyParser.json()); app.get('/ping', (req, res) => { res.sendStatus(200); }); app.get('/401', (req, res) => { res.status(401).send({ errors: ['unauthorized req'] }); }); app.post('/products', (req, res) => { res.send({ data: req.body, me...
{ app.use(logger('combined')); }
conditional_block
gensky.py
# coding=utf-8 from _commandbase import RadianceCommand from ..datatype import RadiancePath, RadianceTuple from ..parameters.gensky import GenskyParameters import os class Gensky(RadianceCommand): u""" gensky - Generate an annual Perez sky matrix from a weather tape. The attributes for this class and th...
from honeybee.radiance.command.gensky import GenSky # create and modify genskyParameters. In this case a sunny with no sun # will be generated. gnskyParam = GenSkyParameters() gnskyParam.sunnySkyNoSun = True # create the gensky Command. gnsky = GenSky(monthDayHo...
Usage: from honeybee.radiance.parameters.gensky import GenSkyParameters
random_line_split
gensky.py
# coding=utf-8 from _commandbase import RadianceCommand from ..datatype import RadiancePath, RadianceTuple from ..parameters.gensky import GenskyParameters import os class Gensky(RadianceCommand): u""" gensky - Generate an annual Perez sky matrix from a weather tape. The attributes for this class and th...
elif skyType == 5: _skyParameters.uniformCloudySky = True return cls(outputName=outputName, monthDayHour=monthDayHour, genskyParameters=_skyParameters) @classmethod def createUniformSkyfromIlluminanceValue(cls, outputName="untitled", ...
_skyParameters.cloudySky = True
conditional_block
gensky.py
# coding=utf-8 from _commandbase import RadianceCommand from ..datatype import RadiancePath, RadianceTuple from ..parameters.gensky import GenskyParameters import os class Gensky(RadianceCommand): u""" gensky - Generate an annual Perez sky matrix from a weather tape. The attributes for this class and th...
(self, genskyParam): self.__genskyParameters = genskyParam if genskyParam is not None \ else GenskyParameters() assert hasattr(self.genskyParameters, "isRadianceParameters"), \ "input genskyParameters is not a valid parameters type." def toRadString(self, relativePath=False...
genskyParameters
identifier_name
gensky.py
# coding=utf-8 from _commandbase import RadianceCommand from ..datatype import RadiancePath, RadianceTuple from ..parameters.gensky import GenskyParameters import os class Gensky(RadianceCommand): u""" gensky - Generate an annual Perez sky matrix from a weather tape. The attributes for this class and th...
@classmethod def fromSkyType(cls, outputName='untitled', monthDayHour=(1, 21, 12), skyType=0, latitude=None, longitude=None, meridian=None): """Create a sky by sky type. Args: outputName: An optional name for output file name (Default: 'untitled'). ...
"""Init command.""" RadianceCommand.__init__(self) self.outputFile = outputName if outputName.lower().endswith(".sky") \ else outputName + ".sky" """results file for sky (Default: untitled)""" self.monthDayHour = monthDayHour self.genskyParameters = genskyParameter...
identifier_body
task-comm-11.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
(tx: &Sender<Sender<isize>>) { let (tx2, _rx) = channel(); tx.send(tx2).unwrap(); } pub fn main() { let (tx, rx) = channel(); let _child = thread::scoped(move|| { start(&tx) }); let _tx = rx.recv().unwrap(); }
start
identifier_name
task-comm-11.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
pub fn main() { let (tx, rx) = channel(); let _child = thread::scoped(move|| { start(&tx) }); let _tx = rx.recv().unwrap(); }
{ let (tx2, _rx) = channel(); tx.send(tx2).unwrap(); }
identifier_body
task-comm-11.rs
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // pretty-expanded ...
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. //
random_line_split
percentage.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/. */ //! Computed percentages. use std::fmt; use style_traits::{CssWriter, ToCss};
use values::animated::ToAnimatedValue; use values::generics::NonNegative; /// A computed percentage. #[cfg_attr(feature = "servo", derive(Deserialize, Serialize))] #[derive(Animate, Clone, ComputeSquaredDistance, Copy, Debug, Default, MallocSizeOf, PartialEq, PartialOrd, SpecifiedValueInfo, ToAnimate...
use values::{serialize_percentage, CSSFloat};
random_line_split
percentage.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/. */ //! Computed percentages. use std::fmt; use style_traits::{CssWriter, ToCss}; use values::{serialize_percentage, ...
(animated: Self::AnimatedValue) -> Self { NonNegative(animated.clamp_to_non_negative()) } }
from_animated_value
identifier_name
percentage.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/. */ //! Computed percentages. use std::fmt; use style_traits::{CssWriter, ToCss}; use values::{serialize_percentage, ...
#[inline] fn from_animated_value(animated: Self::AnimatedValue) -> Self { NonNegative(animated.clamp_to_non_negative()) } }
{ self.0 }
identifier_body
modules_position_spec.js
const helpers = require("./global-setup"); const path = require("path"); const request = require("request"); const expect = require("chai").expect; const describe = global.describe; const it = global.it; const beforeEach = global.beforeEach; const afterEach = global.afterEach; describe("Position of modules", functio...
it("show text in " + position, function () { return app.client.waitUntilWindowLoaded() .getText("." + className).should.eventually.equal("Text in " + position); }); } }); });
for (idx in positions) { position = positions[idx]; className = position.replace("_", ".");
random_line_split
test_unit_outdated.py
import datetime import os import sys from contextlib import contextmanager import freezegun import pretend import pytest from pip._vendor import lockfile from pip._internal.index import InstallationCandidate from pip._internal.utils import outdated class MockPackageFinder(object): BASE_URL = 'https://pypi.pyth...
# See that we saved the correct version elif check_if_upgrade_required: assert fake_state.save.calls == [ pretend.call(new_ver, datetime.datetime(1970, 1, 9, 10, 00, 00)), ] else: # Make sure no Exceptions assert not outdated.logger.debug.calls # See that...
assert not latest_pypi_version
conditional_block
test_unit_outdated.py
import datetime import os import sys from contextlib import contextmanager import freezegun import pretend import pytest from pip._vendor import lockfile from pip._internal.index import InstallationCandidate from pip._internal.utils import outdated class MockPackageFinder(object): BASE_URL = 'https://pypi.pyth...
(filename, mode='r'): yield fake_file monkeypatch.setattr(outdated, 'open', fake_open, raising=False) @pretend.call_recorder @contextmanager def fake_lock(filename): yield monkeypatch.setattr(outdated, "check_path_owner", lambda p: True) monkeypatch.setattr(lockfile, 'LockFil...
fake_open
identifier_name
test_unit_outdated.py
import datetime import os import sys from contextlib import contextmanager import freezegun import pretend import pytest from pip._vendor import lockfile from pip._internal.index import InstallationCandidate from pip._internal.utils import outdated class MockPackageFinder(object): BASE_URL = 'https://pypi.pyth...
assert fake_state.save.calls == [] # Ensure we warn the user or not if check_warn_logs: assert len(outdated.logger.warning.calls) == 1 else: assert len(outdated.logger.warning.calls) == 0 def test_virtualenv_state(monkeypatch): CONTENT = '{"last_check": "1970-01-02T11:00:00Z",...
# See that save was not called
random_line_split
test_unit_outdated.py
import datetime import os import sys from contextlib import contextmanager import freezegun import pretend import pytest from pip._vendor import lockfile from pip._internal.index import InstallationCandidate from pip._internal.utils import outdated class MockPackageFinder(object): BASE_URL = 'https://pypi.pyth...
def _options(): ''' Some default options that we pass to outdated.pip_version_check ''' return pretend.stub( find_links=False, extra_index_urls=[], index_url='default_url', pre=False, trusted_hosts=False, process_dependency_links=False, ) @pytest.mark.parametrize( [ 'stored_...
return self.INSTALLATION_CANDIDATES
identifier_body
06.py
# THREE GOLD STARS # Sudoku [http://en.wikipedia.org/wiki/Sudoku] # is a logic puzzle where a game # is defined by a partially filled # 9 x 9 square of digits where each square # contains one of the digits 1,2,3,4,5,6,7,8,9. # For this question we will generalize # and simplify the game. # Define a procedure, check_s...
(grid): for ii, row in enumerate(grid): column = [] for jj in range(len(row)): column.append(grid[jj][ii]) for jj in range(len(grid)): if jj+1 not in row or jj+1 not in column: return False return True print check_sudoku(incorrect) #>>> F...
check_sudoku
identifier_name
06.py
# THREE GOLD STARS # Sudoku [http://en.wikipedia.org/wiki/Sudoku] # is a logic puzzle where a game # is defined by a partially filled # 9 x 9 square of digits where each square # contains one of the digits 1,2,3,4,5,6,7,8,9. # For this question we will generalize # and simplify the game. # Define a procedure, check_s...
return True print check_sudoku(incorrect) #>>> False print check_sudoku(correct) #>>> True print check_sudoku(incorrect2) #>>> False print check_sudoku(incorrect3) #>>> False print check_sudoku(incorrect4) #>>> False print check_sudoku(incorrect5) #>>> False
return False
conditional_block
06.py
# THREE GOLD STARS # Sudoku [http://en.wikipedia.org/wiki/Sudoku] # is a logic puzzle where a game # is defined by a partially filled # 9 x 9 square of digits where each square # contains one of the digits 1,2,3,4,5,6,7,8,9. # For this question we will generalize # and simplify the game. # Define a procedure, check_s...
print check_sudoku(incorrect) #>>> False print check_sudoku(correct) #>>> True print check_sudoku(incorrect2) #>>> False print check_sudoku(incorrect3) #>>> False print check_sudoku(incorrect4) #>>> False print check_sudoku(incorrect5) #>>> False
for ii, row in enumerate(grid): column = [] for jj in range(len(row)): column.append(grid[jj][ii]) for jj in range(len(grid)): if jj+1 not in row or jj+1 not in column: return False return True
identifier_body
fast_impl.py
################################################################################ # Copyright (c) 2015-2018 Skymind, Inc. # # This program and the accompanying materials are made available under the # terms of the Apache License, Version 2.0 which is available at # https://www.apache.org/licenses/LICENSE-2.0. # # Unless...
java_rdd = java_sc.parallelize(jdescriptors) java_rdd = spark_utils.getDataSetRDD(java_rdd) return java_rdd
global spark_utils if spark_utils is None: spark_utils = get_spark_utils() ### pydatasets = py_rdd.collect() jdatasets = ArrayList() for pyds in pydatasets: pydesc = ds2desc(pyds) jdesc = py2j_ds_desc(pydesc) jds = jdesc.getDataSet() jdatasets.add(jds) ...
identifier_body
fast_impl.py
################################################################################ # Copyright (c) 2015-2018 Skymind, Inc. #
# # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. # ...
# This program and the accompanying materials are made available under the # terms of the Apache License, Version 2.0 which is available at # https://www.apache.org/licenses/LICENSE-2.0.
random_line_split
fast_impl.py
################################################################################ # Copyright (c) 2015-2018 Skymind, Inc. # # This program and the accompanying materials are made available under the # terms of the Apache License, Version 2.0 which is available at # https://www.apache.org/licenses/LICENSE-2.0. # # Unless...
if JDatasetDescriptor is None: JDatasetDescriptor = getDatasetDescriptor() jdatasets = java_rdd.collect() num_ds = jdatasets.size() pydatasets = [] for i in range(num_ds): jds = jdatasets.get(i) jdesc = JDatasetDescriptor(jds) pydesc = j2py_ds_desc(jdesc) pyd...
spark_utils = get_spark_utils()
conditional_block
fast_impl.py
################################################################################ # Copyright (c) 2015-2018 Skymind, Inc. # # This program and the accompanying materials are made available under the # terms of the Apache License, Version 2.0 which is available at # https://www.apache.org/licenses/LICENSE-2.0. # # Unless...
(java_rdd, py_sc): global spark_utils, JDatasetDescriptor if spark_utils is None: spark_utils = get_spark_utils() if JDatasetDescriptor is None: JDatasetDescriptor = getDatasetDescriptor() jdatasets = java_rdd.collect() num_ds = jdatasets.size() pydatasets = [] for i in range...
java2pyDatasetRDD
identifier_name
index.js
/** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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 a...
*/ // MODULES // var main = require( './main.js' ); // EXPORTS // module.exports = main;
* @example * var enumerablePropertiesIn = require( '@stdlib/utils/enumerable-properties-in' ); * * var props = enumerablePropertiesIn( [] ); * // returns [...]
random_line_split
ctables.py
# Copyright (c) 2014,2015,2017 MetPy Developers. # Distributed under the terms of the BSD 3-Clause License. # SPDX-License-Identifier: BSD-3-Clause """Work with custom color tables. Contains a tools for reading color tables from files, and creating instances based on a specific set of constraints (e.g. step size) for ...
(fobj): r"""Read colortable information from a file. Reads a colortable, which consists of one color per line of the file, where a color can be one of: a tuple of 3 floats, a string with a HTML color name, or a string with a HTML hex color. Parameters ---------- fobj : a file-like object ...
read_colortable
identifier_name
ctables.py
# Copyright (c) 2014,2015,2017 MetPy Developers. # Distributed under the terms of the BSD 3-Clause License. # SPDX-License-Identifier: BSD-3-Clause """Work with custom color tables. Contains a tools for reading color tables from files, and creating instances based on a specific set of constraints (e.g. step size) for ...
def scan_dir(self, path): r"""Scan a directory on disk for color table files and add them to the registry. Parameters ---------- path : str The path to the directory with the color tables """ for fname in glob.glob(os.path.join(path, '*' + TABLE_EXT)):...
r"""Scan a resource directory for colortable files and add them to the registry. Parameters ---------- pkg : str The package containing the resource directory path : str The path to the directory with the color tables """ for fname in resource_li...
identifier_body
ctables.py
# Copyright (c) 2014,2015,2017 MetPy Developers. # Distributed under the terms of the BSD 3-Clause License. # SPDX-License-Identifier: BSD-3-Clause """Work with custom color tables. Contains a tools for reading color tables from files, and creating instances based on a specific set of constraints (e.g. step size) for ...
return ret except (SyntaxError, ValueError): raise RuntimeError('Malformed colortable.') def convert_gempak_table(infile, outfile): r"""Convert a GEMPAK color table to one MetPy can read. Reads lines from a GEMPAK-style color table file, and writes them to another file in a format th...
literal = _parse(line) if literal: ret.append(mcolors.colorConverter.to_rgb(literal))
conditional_block
ctables.py
# Copyright (c) 2014,2015,2017 MetPy Developers. # Distributed under the terms of the BSD 3-Clause License. # SPDX-License-Identifier: BSD-3-Clause """Work with custom color tables. Contains a tools for reading color tables from files, and creating instances based on a specific set of constraints (e.g. step size) for ...
""" for line in infile: if not line.startswith('!') and line.strip(): r, g, b = map(int, line.split()) outfile.write('({0:f}, {1:f}, {2:f})\n'.format(r / 255, g / 255, b / 255)) class ColortableRegistry(dict): r"""Manages the collection of color tables. Provides acces...
---------- infile : file-like object The file-like object to read from outfile : file-like object The file-like object to write to
random_line_split
share_iscsi.py
""" Copyright (c) 2012-2013 RockStor, Inc. <http://rockstor.com> This file is part of RockStor. RockStor 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 2 of the License, or (at your option) any la...
pool_device = Disk.objects.filter(pool=share.pool)[0].name mnt_pt = '/mnt2/' + share.name mount_share(share.name, pool_device, mnt_pt) dev_name = mnt_pt + '/' + options['dev_name'] export_iscsi(options['tid'], options['tname'], options['tid'], ...
try: options['tid'] = int(request.data['tid']) except: raise Exception('tid must be an integer')
conditional_block
share_iscsi.py
""" Copyright (c) 2012-2013 RockStor, Inc. <http://rockstor.com> This file is part of RockStor. RockStor 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 2 of the License, or (at your option) any la...
(self, request, sname): try: share = Share.objects.get(name=sname) iscsi_target = IscsiTarget.objects.get(share=share) iscsi_target.delete() return Response() except Exception, e: handle_exception(e, request)
delete
identifier_name
share_iscsi.py
""" Copyright (c) 2012-2013 RockStor, Inc. <http://rockstor.com> This file is part of RockStor. RockStor 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 2 of the License, or (at your option) any la...
try: options['tid'] = int(request.data['tid']) except: raise Exception('tid must be an integer') pool_device = Disk.objects.filter(pool=share.pool)[0].name mnt_pt = '/mnt2/' + share.name mount_share(share.name, ...
try: share = Share.objects.get(name=sname) if (SambaShare.objects.filter(share=share).exists()): raise Exception('Already exported via Samba') if (NFSExport.objects.filter(share=share).exists()): raise Exception('Already exported via nfs') ...
identifier_body
share_iscsi.py
""" Copyright (c) 2012-2013 RockStor, Inc. <http://rockstor.com> This file is part of RockStor. RockStor is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. """ from rest_framework.views import APIView from rest_framework.response im...
by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. RockStor is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
random_line_split
utils.js
'use strict'; var deoopfy = require('deoopfy'); /** * Returns the available model names for a mongoose Connection. * * @param {mongoose.Connection} connection * @return {Array.<String>} model_names. */ exports.getModelNames = function getModelNames(connection) { if(connection === connection.base.connection) { ...
return ret; }; /** * Filters an array, based on a predicate function, which should take value, * index and array as its arguments, and return a Boolean. If the predicate * returns true, the item is kept, else, it's discarted from the return array. * * @param {Function} fn A predicate function. * @param {Arra...
{ var key = keys[i], value = obj[key]; ret[key] = cb(value, key, obj); }
conditional_block
utils.js
'use strict'; var deoopfy = require('deoopfy'); /** * Returns the available model names for a mongoose Connection. * * @param {mongoose.Connection} connection * @return {Array.<String>} model_names. */ exports.getModelNames = function getModelNames(connection) { if(connection === connection.base.connection) { ...
return function() { var allargs = sliceF(arguments); for(var i = 0; i < len; i++) allargs.unshift(args[i]); return fn.apply(this, allargs); }; };
var len = args.length;
random_line_split
findAllRefsThisKeyword.ts
/// <reference path='fourslash.ts' /> // @noLib: true ////[|this|]; ////function f([|{| "isWriteAccess": true, "isDefinition": true |}this|]) { //// return [|this|]; //// function g([|{| "isWriteAccess": true, "isDefinition": true |}this|]) { return [|this|]; } ////} ////class C { //// static x() { ...
const [global, f0, f1, g0, g1, x, y, constructor, method, propDef, propUse] = test.ranges(); verify.referencesOf(global, [global]); verify.referenceGroups(f0, [{ definition: "(parameter) this: any", ranges: [f0, f1] }]); verify.referenceGroups(f1, [{ definition: "this: any", ranges: [f0, f1] }]); verify.referenceGr...
random_line_split
mopidy-playlist.service.ts
import { Injectable } from '@angular/core'; import { JsonRpcService } from '../json-rpc/json-rpc.service'; import { Ref } from './models/ref'; import { Playlist } from './models/playlist'; @Injectable() export class MopidyPlaylistService {
( private jsonRpcService: JsonRpcService ) {} getUriSchemes = () => this.jsonRpcService.rpcRequest<string[]>("core.playlists.get_uri_schemes"); getPlaylist = (uri: string) => this.jsonRpcService.rpcRequest<Playlist>("core.playlists.lookup"); getPlaylists = () => this.jsonRpcService.rpcRequest<Ref[]>("core....
constructor
identifier_name
mopidy-playlist.service.ts
@Injectable() export class MopidyPlaylistService { constructor( private jsonRpcService: JsonRpcService ) {} getUriSchemes = () => this.jsonRpcService.rpcRequest<string[]>("core.playlists.get_uri_schemes"); getPlaylist = (uri: string) => this.jsonRpcService.rpcRequest<Playlist>("core.playlists.lookup"); ...
import { Injectable } from '@angular/core'; import { JsonRpcService } from '../json-rpc/json-rpc.service'; import { Ref } from './models/ref'; import { Playlist } from './models/playlist';
random_line_split
errors.py
"""HTTP related errors.""" from asyncio import TimeoutError __all__ = ( 'DisconnectedError', 'ClientDisconnectedError', 'ServerDisconnectedError', 'HttpProcessingError', 'BadHttpMessage', 'HttpMethodNotAllowed', 'HttpBadRequest', 'HttpProxyError', 'BadStatusLine', 'LineTooLong', 'InvalidHeader', ...
self.headers = headers self.message = message super().__init__("%s, message='%s'" % (self.code, message)) class WSServerHandshakeError(HttpProcessingError): """websocket server handshake error.""" class HttpProxyError(HttpProcessingError): """HTTP proxy error. Raised in :class...
self.code = code
conditional_block
errors.py
"""HTTP related errors.""" from asyncio import TimeoutError __all__ = ( 'DisconnectedError', 'ClientDisconnectedError', 'ServerDisconnectedError', 'HttpProcessingError', 'BadHttpMessage', 'HttpMethodNotAllowed', 'HttpBadRequest', 'HttpProxyError', 'BadStatusLine', 'LineTooLong', 'InvalidHeader', ...
(self): return '<{} expected={} got={} host={} port={}>'.format( self.__class__.__name__, self.expected, self.got, self.host, self.port)
__repr__
identifier_name
errors.py
"""HTTP related errors.""" from asyncio import TimeoutError __all__ = ( 'DisconnectedError', 'ClientDisconnectedError', 'ServerDisconnectedError', 'HttpProcessingError', 'BadHttpMessage', 'HttpMethodNotAllowed', 'HttpBadRequest', 'HttpProxyError', 'BadStatusLine', 'LineTooLong', 'InvalidHeader', ...
class ClientHttpProcessingError(ClientError): """Base class for client HTTP processing errors.""" class ClientRequestError(ClientHttpProcessingError): """Connection error during sending request.""" class ClientResponseError(ClientHttpProcessingError): """Connection error during reading response.""" ...
"""Base class for client connection errors."""
identifier_body
errors.py
"""HTTP related errors.""" from asyncio import TimeoutError __all__ = ( 'DisconnectedError', 'ClientDisconnectedError', 'ServerDisconnectedError', 'HttpProcessingError', 'BadHttpMessage', 'HttpMethodNotAllowed', 'HttpBadRequest', 'HttpProxyError', 'BadStatusLine', 'LineTooLong', 'InvalidHeader', ...
class ClientConnectionError(ClientError): """Base class for client socket errors.""" class ClientOSError(ClientConnectionError, OSError): """OSError error.""" class ClientTimeoutError(ClientConnectionError, TimeoutError): """Client connection timeout error.""" class ProxyConnectionError(ClientConnect...
"""Connection error during reading response."""
random_line_split
ConsecutiveKPrimes.rs
fn n_prime(mut n: i32) -> i32 { let mut result = 0; for i in 2..((n as f64).sqrt() as i32) + 1 { while n%i == 0 { result += 1; n /= i; } } if n > 1 { result += 1; } result } fn consec_kprimes(k: i32, arr: Vec<i32>) -> i32 { let mut count ...
(k: i32, arr: Vec<i32>, exp: i32) -> () { assert_eq!(consec_kprimes(k, arr), exp) } fn main() { testing(2, vec![10081, 10071, 10077, 10065, 10060,10070, 10086, 10083, 10078, 10076, 10089, 10085, 10063, 10074, 10068, 10073, 10072, 10075], 2); testing(6, vec![10064], 0...
testing
identifier_name
ConsecutiveKPrimes.rs
fn n_prime(mut n: i32) -> i32 { let mut result = 0; for i in 2..((n as f64).sqrt() as i32) + 1 { while n%i == 0 { result += 1; n /= i; } } if n > 1 { result += 1; } result } fn consec_kprimes(k: i32, arr: Vec<i32>) -> i32
fn testing(k: i32, arr: Vec<i32>, exp: i32) -> () { assert_eq!(consec_kprimes(k, arr), exp) } fn main() { testing(2, vec![10081, 10071, 10077, 10065, 10060,10070, 10086, 10083, 10078, 10076, 10089, 10085, 10063, 10074, 10068, 10073, 10072, 10075], 2); testing(6, ve...
{ let mut count = 0; let mut was_prev = false; for num in arr { if n_prime(num) == k { if was_prev { count += 1; } was_prev = true; } else { was_prev = false; } } count }
identifier_body
ConsecutiveKPrimes.rs
fn n_prime(mut n: i32) -> i32 { let mut result = 0; for i in 2..((n as f64).sqrt() as i32) + 1 { while n%i == 0 { result += 1;
} } if n > 1 { result += 1; } result } fn consec_kprimes(k: i32, arr: Vec<i32>) -> i32 { let mut count = 0; let mut was_prev = false; for num in arr { if n_prime(num) == k { if was_prev { count += 1; } was_prev ...
n /= i;
random_line_split
ConsecutiveKPrimes.rs
fn n_prime(mut n: i32) -> i32 { let mut result = 0; for i in 2..((n as f64).sqrt() as i32) + 1 { while n%i == 0 { result += 1; n /= i; } } if n > 1
result } fn consec_kprimes(k: i32, arr: Vec<i32>) -> i32 { let mut count = 0; let mut was_prev = false; for num in arr { if n_prime(num) == k { if was_prev { count += 1; } was_prev = true; } else { was_prev = false; ...
{ result += 1; }
conditional_block
validatePostData.test.js
import validatePostData from './validatePostData' describe('validatePostData', () => { var user, inGroup, notInGroup before(function () { inGroup = new Group({slug: 'foo', name: 'Foo', group_data_type: 1 }) notInGroup = new Group({slug: 'bar', name: 'Bar', group_data_type: 1 }) user = new User({name: ...
it('fails if an invalid type is provided', () => { const fn = () => validatePostData(null, {name: 't', type: 'thread'}) expect(fn).to.throw(/not a valid type/) }) it('fails if no group_ids are provided', () => { const fn = () => validatePostData(null, {name: 't'}) expect(fn).to.throw(/no communit...
random_line_split
name.rs
use super::errors::{ErrorKind, Result}; use failchain::{bail, ensure}; use serde::de::{Deserialize, Deserializer, Error as SerdeDeError}; use std::borrow::Borrow; use std::fmt; use std::fmt::Debug; use std::fmt::Display; use std::ops::Deref; use std::result::Result as StdResult; use std::str::{self, FromStr}; #[derive...
(&self) -> &[u8; 8] { self.deref() } } impl AsRef<str> for WadName { fn as_ref(&self) -> &str { str::from_utf8(self.deref()).expect("wad name is not valid utf-8") } } impl<'de> Deserialize<'de> for WadName { fn deserialize<D>(deserializer: D) -> StdResult<Self, D::Error> where ...
borrow
identifier_name
name.rs
use super::errors::{ErrorKind, Result}; use failchain::{bail, ensure}; use serde::de::{Deserialize, Deserializer, Error as SerdeDeError}; use std::borrow::Borrow; use std::fmt; use std::fmt::Debug; use std::fmt::Display; use std::ops::Deref; use std::result::Result as StdResult; use std::str::{self, FromStr}; #[derive...
} impl<'de> Deserialize<'de> for WadName { fn deserialize<D>(deserializer: D) -> StdResult<Self, D::Error> where D: Deserializer<'de>, { WadName::from_bytes(&<[u8; 8]>::deserialize(deserializer)?).map_err(D::Error::custom) } } pub trait IntoWadName { fn into_wad_name(self) -> Resu...
{ str::from_utf8(self.deref()).expect("wad name is not valid utf-8") }
identifier_body
name.rs
use super::errors::{ErrorKind, Result}; use failchain::{bail, ensure}; use serde::de::{Deserialize, Deserializer, Error as SerdeDeError}; use std::borrow::Borrow; use std::fmt; use std::fmt::Debug; use std::fmt::Display; use std::ops::Deref; use std::result::Result as StdResult; use std::str::{self, FromStr}; #[derive...
} } impl PartialEq<[u8; 8]> for WadName { fn eq(&self, rhs: &[u8; 8]) -> bool { self.deref() == rhs } } impl Borrow<[u8; 8]> for WadName { fn borrow(&self) -> &[u8; 8] { self.deref() } } impl AsRef<str> for WadName { fn as_ref(&self) -> &str { str::from_utf8(self.deref...
write!( formatter, "WadName({:?})", str::from_utf8(&self[..]).unwrap() )
random_line_split
utils.rs
use crate::string_utils::{CaseOperations, WordIterator}; use itertools::Itertools; use std::path::PathBuf; #[test] fn join() { let a1 = vec!["a", "b", "c"]; assert_eq!(a1.join(""), "abc"); assert_eq!(a1.join("_"), "a_b_c"); let a2 = Vec::<String>::new(); assert_eq!(a2.join(""), ""); assert_eq!...
let s6 = "toBase64".to_string(); assert_eq!(s6.to_class_case(), "ToBase64"); assert_eq!(s6.to_snake_case(), "to_base64"); let s7 = "too_many__underscores".to_string(); assert_eq!(s7.to_class_case(), "TooManyUnderscores"); assert_eq!(s7.to_snake_case(), "too_many_underscores"); let s8 = "O...
{ let s1 = "first_second_last".to_string(); assert_eq!(s1.to_class_case(), "FirstSecondLast"); assert_eq!(s1.to_snake_case(), "first_second_last"); let s2 = "FirstSecondLast".to_string(); assert_eq!(s2.to_class_case(), "FirstSecondLast"); assert_eq!(s2.to_snake_case(), "first_second_last"); ...
identifier_body
utils.rs
use crate::string_utils::{CaseOperations, WordIterator}; use itertools::Itertools; use std::path::PathBuf; #[test] fn join() { let a1 = vec!["a", "b", "c"]; assert_eq!(a1.join(""), "abc"); assert_eq!(a1.join("_"), "a_b_c"); let a2 = Vec::<String>::new(); assert_eq!(a2.join(""), ""); assert_eq!...
() { let string = "RustIsAwesome".to_string(); let mut a1 = WordIterator::new(&string); assert_eq!(a1.next(), Some("Rust")); assert_eq!(a1.next(), Some("Is")); assert_eq!(a1.next(), Some("Awesome")); assert_eq!(a1.next(), None); } fn split_to_words(s: &'static str) -> Vec<&'static str> { Wo...
word_iterator2
identifier_name
utils.rs
use crate::string_utils::{CaseOperations, WordIterator}; use itertools::Itertools; use std::path::PathBuf; #[test] fn join() { let a1 = vec!["a", "b", "c"]; assert_eq!(a1.join(""), "abc"); assert_eq!(a1.join("_"), "a_b_c"); let a2 = Vec::<String>::new(); assert_eq!(a2.join(""), ""); assert_eq!...
assert_eq!(s1.to_snake_case(), "first_second_last"); let s2 = "FirstSecondLast".to_string(); assert_eq!(s2.to_class_case(), "FirstSecondLast"); assert_eq!(s2.to_snake_case(), "first_second_last"); let s3 = "First_Second_last".to_string(); assert_eq!(s3.to_class_case(), "FirstSecondLast"); ...
#[test] fn case_operations() { let s1 = "first_second_last".to_string(); assert_eq!(s1.to_class_case(), "FirstSecondLast");
random_line_split
test.ts
/* * @license Apache-2.0 * * Copyright (c) 2020 The Stdlib Authors. * * 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 ap...
*/ import rampf = require( './index' ); // TESTS // // The function returns a number... { rampf( 2 ); // $ExpectType number } // The function does not compile if provided a value other than a number... { rampf( true ); // $ExpectError rampf( false ); // $ExpectError rampf( null ); // $ExpectError rampf( undef...
* See the License for the specific language governing permissions and * limitations under the License.
random_line_split
view.d.ts
import { Type } from 'angular2/src/facade/lang'; /** * Declares the available HTML templates for an application. * * Each angular component requires a single `@Component` and at least one `@View` annotation. The * `@View` annotation specifies the HTML template to use, and lists the directives that are active
* * For details on the `@Component` annotation, see {@link Component}. * * ## Example * * ``` * @Component({ * selector: 'greet' * }) * @View({ * template: 'Hello {{name}}!', * directives: [GreetUser, Bold] * }) * class Greet { * name: string; * * constructor() { * this.name = 'World'; ...
* within the template. * * When a component is instantiated, the template is loaded into the component's shadow root, and * the expressions and statements in the template are evaluated against the component.
random_line_split
view.d.ts
import { Type } from 'angular2/src/facade/lang'; /** * Declares the available HTML templates for an application. * * Each angular component requires a single `@Component` and at least one `@View` annotation. The * `@View` annotation specifies the HTML template to use, and lists the directives that are active * wit...
{ /** * Specifies a template URL for an angular component. * * NOTE: either `templateUrl` or `template` should be used, but not both. */ templateUrl: string; /** * Specifies an inline template for an angular component. * * NOTE: either `templateUrl` or `template` should b...
View
identifier_name
index.js
/** * @module lib/tool/native */ import Tool from 'lib/tool/base'; import os from 'os'; /** * @class * @extends Tool */ class
extends Tool { /** * Creates a native tool */ constructor() { super(); this.command = 'echo'; } /** * Generates a native command given a string array * @param {string[]} command */ set nativeCommand(command) { this.command = command[0]; this...
Native
identifier_name
index.js
/** * @module lib/tool/native */ import Tool from 'lib/tool/base'; import os from 'os'; /** * @class * @extends Tool */ class Native extends Tool { /** * Creates a native tool */ constructor() { super(); this.command = 'echo'; } /** * Generates a native command give...
} const runStep = (native || psuedo || notNativeButNative); let working = process.cwd(); if (runStep.working) { working = runStep.working; } if (runStep.acceptsArgs) { runStep.command.push(...process.argv); ...
{ switch (os.platform()) { case "darwin": case "freebsd": case "linux": case "openbsd": universal = 'native-nix'; break; case 'win32': universal = 'native-win'; ...
conditional_block
index.js
/** * @module lib/tool/native */ import Tool from 'lib/tool/base'; import os from 'os'; /** * @class * @extends Tool */ class Native extends Tool { /** * Creates a native tool */ constructor() { super(); this.command = 'echo'; } /** * Generates a native command give...
export default Native;
return true; } }
random_line_split
brightcove.py
# encoding: latin-1 import re import json import xml.etree.ElementTree from .common import InfoExtractor from ..utils import ( compat_urllib_parse, find_xpath_attr, compat_urlparse, ExtractorError, ) class BrightcoveIE(InfoExtractor): _VALID_URL = r'https?://.*brightcove\.com/(services|viewer).*...
def _real_extract(self, url): mobj = re.match(self._VALID_URL, url) query_str = mobj.group('query') query = compat_urlparse.parse_qs(query_str) videoPlayer = query.get('@videoPlayer') if videoPlayer: return self._get_video_info(videoPlayer[0], query_str) else...
Build a Brightcove url from a xml string containing <object class="BrightcoveExperience">{params}</object> """ object_doc = xml.etree.ElementTree.fromstring(object_str) assert u'BrightcoveExperience' in object_doc.attrib['class'] params = {'flashID': object_doc.attrib['id']...
identifier_body
brightcove.py
# encoding: latin-1 import re import json import xml.etree.ElementTree from .common import InfoExtractor from ..utils import ( compat_urllib_parse, find_xpath_attr, compat_urlparse, ExtractorError, ) class BrightcoveIE(InfoExtractor): _VALID_URL = r'https?://.*brightcove\.com/(services|viewer).*...
renditions = video_info.get('renditions') if renditions: renditions = sorted(renditions, key=lambda r: r['size']) best_format = renditions[-1] info.update({ 'url': best_format['defaultURL'], 'ext': 'mp4', }) elif vi...
'title': video_info['displayName'], 'description': video_info.get('shortDescription'), 'thumbnail': video_info.get('videoStillURL') or video_info.get('thumbnailURL'), 'uploader': video_info.get('publisherName'), }
random_line_split
brightcove.py
# encoding: latin-1 import re import json import xml.etree.ElementTree from .common import InfoExtractor from ..utils import ( compat_urllib_parse, find_xpath_attr, compat_urlparse, ExtractorError, ) class BrightcoveIE(InfoExtractor): _VALID_URL = r'https?://.*brightcove\.com/(services|viewer).*...
player_key): playlist_info = self._download_webpage(self._PLAYLIST_URL_TEMPLATE % player_key, player_key, u'Downloading playlist information') playlist_info = json.loads(playlist_info)['videoList'] videos = [self._extract_video_info(video_info) fo...
laylist_info(self,
identifier_name
brightcove.py
# encoding: latin-1 import re import json import xml.etree.ElementTree from .common import InfoExtractor from ..utils import ( compat_urllib_parse, find_xpath_attr, compat_urlparse, ExtractorError, ) class BrightcoveIE(InfoExtractor): _VALID_URL = r'https?://.*brightcove\.com/(services|viewer).*...
else: raise ExtractorError(u'Unable to extract video url for %s' % info['id']) return info
pdate({ 'url': video_info['FLVFullLengthURL'], 'ext': 'flv', })
conditional_block
rest.py
from django.db.models import Count from django.http import HttpResponse from rest_framework.generics import ListAPIView from rest_framework.views import APIView from rest_framework.authentication import TokenAuthentication from prometheus_client import generate_latest from core import models from core import serializ...
result = '# HELP ansible_manager_template_last_task_success show success or fail last task\n' result += '# TYPE ansible_manager_template_last_task_success gauge\n' for template in models.TaskTemplate.objects.exclude(cron=''): completed_tasks = template.tasks.filter(status__in=consts.NOT_RUN_...
identifier_body
rest.py
from django.db.models import Count from django.http import HttpResponse from rest_framework.generics import ListAPIView from rest_framework.views import APIView from rest_framework.authentication import TokenAuthentication from prometheus_client import generate_latest from core import models from core import serializ...
last_log_id = self.request.GET.get('last_log_id', 0) return self.model.objects.filter(task_id=self.kwargs['task_id'], id__gt=last_log_id) task_logs = TaskLogs.as_view() class DjangoMetrics(APIView): authentication_classes = (tokenBearer,) def get(self, request): result = generate_late...
def get_queryset(self):
random_line_split
rest.py
from django.db.models import Count from django.http import HttpResponse from rest_framework.generics import ListAPIView from rest_framework.views import APIView from rest_framework.authentication import TokenAuthentication from prometheus_client import generate_latest from core import models from core import serializ...
return HttpResponse(result, content_type='text/plain; charset=utf-8')
result += 'ansible_manager_tasks_completed_total{id="%s", name="%s", status="%s"} %s\n' % ( template_id, template_name, status, count )
conditional_block
rest.py
from django.db.models import Count from django.http import HttpResponse from rest_framework.generics import ListAPIView from rest_framework.views import APIView from rest_framework.authentication import TokenAuthentication from prometheus_client import generate_latest from core import models from core import serializ...
(ListAPIView): model = models.TaskLog serializer_class = serializers.TaskLogSerializer def get_queryset(self): last_log_id = self.request.GET.get('last_log_id', 0) return self.model.objects.filter(task_id=self.kwargs['task_id'], id__gt=last_log_id) task_logs = TaskLogs.as_view() class Dja...
TaskLogs
identifier_name
roles-modal.js
define(function(require, exports, module) { var Notify = require('common/bootstrap-notify'); exports.run = function() { var $form = $("#user-roles-form"), isTeacher = $form.find('input[value=ROLE_TEACHER]').prop('checked'), currentUser = $form.data('currentuser'), edit...
var user_name = $('#change-user-roles-btn').data('user') ; Notify.danger('用户必须拥有'+user_name+'角色'); return false; } if (isTeacher && $.inArray('ROLE_TEACHER', roles) < 0) { if (!confirm('取消该用户的教师角色,同时将收回该用户所有教授的课程的教师权限。您真的要这么做吗?')) ...
if ($.inArray('ROLE_USER', roles) < 0) {
random_line_split
roles-modal.js
define(function(require, exports, module) { var Notify = require('common/bootstrap-notify'); exports.run = function() { var $form = $("#user-roles-form"), isTeacher = $form.find('input[value=ROLE_TEACHER]').prop('checked'), currentUser = $form.data('currentuser'), edit...
ange-user-roles-btn').button('submiting').addClass('disabled'); $.post($form.attr('action'), $form.serialize(), function(html) { $modal.modal('hide'); Notify.success('用户组保存成功'); var $tr = $(html); $('#' + $tr.attr('id')).replaceWith($tr); ...
R_ADMIN]').removeAttr('disabled'); $('#ch
conditional_block
protocol.py
') class Protocol: def __init__(self, error_states, max_size=2048): # any init information? global error self.p_ID = 0 self.p_ctr = 0 error = error_states # dictionary of party types (each type gets an identifier) self.partyTypes = {} self.party = {} s...
else: # first receive message, call state function # then send call response input = self.recv_msg() if type(input) == dict: # print("input db :=>", input)
output = func.__call__() if type(output) == dict: self.db.update(output) self.send_msg(output)
conditional_block
protocol.py
protocol') class Protocol: def __init__(self, error_states, max_size=2048): # any init information? global error self.p_ID = 0 self.p_ctr = 0 error = error_states # dictionary of party types (each type gets an identifier) self.partyTypes = {} self.party = {} ...
for i in keys: if _type == tuple: ret.append(self.db[i]) else: # dict ret[ i ] = self.db[i] # return data if _type == tuple: return tuple(ret) return ret def store(self, *args): ...
# get the data
random_line_split
protocol.py
') class
: def __init__(self, error_states, max_size=2048): # any init information? global error self.p_ID = 0 self.p_ctr = 0 error = error_states # dictionary of party types (each type gets an identifier) self.partyTypes = {} self.party = {} self._serialize = ...
Protocol
identifier_name
protocol.py
') class Protocol: def __init__(self, error_states, max_size=2048): # any init information? global error self.p_ID = 0 self.p_ctr = 0 error = error_states # dictionary of party types (each type gets an identifier) self.partyTypes = {} self.party = {} s...
# # def addValidTransitions(self, trans_map): # if isinstance(trans_map, dict): # self.trans_map = trans_map def listStates(self, partyID): # check if a member parameter is defined if partyID < self.p_ctr: return self.party[partyID]['states'] ret...
ExistingTypeFound = False # see if type already exists. break and return if so for i in self.partyTypes.keys(): if self.partyTypes[i]['type'] == type: ExistingTypeFound = True break # means we are adding a new type if not ExistingTypeFound:...
identifier_body
theming.py
from django import template # from kilonull.conf import BlogConf from kilonull.models import Menu, MenuItem from kilonull.settings import SETTINGS import re register = template.Library() @register.simple_tag def blog_title():
# Generate HTML for the header menu. # Use a regex (path) to check if the current page is in the menu. If it is, # apply the active class. @register.simple_tag def get_menu(menu_slug, curr_page): html = "" menu_items = MenuItem.objects.filter(menu__slug=menu_slug) \ .order_by("order") path = re.c...
return SETTINGS['BLOG_TITLE']
identifier_body
theming.py
from django import template # from kilonull.conf import BlogConf from kilonull.models import Menu, MenuItem from kilonull.settings import SETTINGS import re register = template.Library() @register.simple_tag def blog_title(): return SETTINGS['BLOG_TITLE'] # Generate HTML for the header menu. # Use a regex (pat...
(menu_slug, curr_page): html = "" menu_items = MenuItem.objects.filter(menu__slug=menu_slug) \ .order_by("order") path = re.compile("%s(.*)" % SETTINGS['BLOG_SITE_URL']) for item in menu_items: html += "<li" match = path.match(item.link_url) if match and match.group(1) ==...
get_menu
identifier_name
theming.py
from django import template # from kilonull.conf import BlogConf
from kilonull.settings import SETTINGS import re register = template.Library() @register.simple_tag def blog_title(): return SETTINGS['BLOG_TITLE'] # Generate HTML for the header menu. # Use a regex (path) to check if the current page is in the menu. If it is, # apply the active class. @register.simple_tag def...
from kilonull.models import Menu, MenuItem
random_line_split
theming.py
from django import template # from kilonull.conf import BlogConf from kilonull.models import Menu, MenuItem from kilonull.settings import SETTINGS import re register = template.Library() @register.simple_tag def blog_title(): return SETTINGS['BLOG_TITLE'] # Generate HTML for the header menu. # Use a regex (pat...
html += "><a href='%s'>%s</a></li>" % (item.link_url, item.link_text) return html
html += " class='active'"
conditional_block
tutorial_pyPandora.py
#!/usr/bin/python3 import os, sys, random pandoraPath = os.getenv('PANDORAPATH', '/usr/local/pandora') sys.path.append(pandoraPath+'/bin') sys.path.append(pandoraPath+'/lib') from pyPandora import Config, World, Agent, SizeInt class MyAgent(Agent): gatheredResources = 0 def __init__(self, id): Age...
(self, config): World.__init__( self, config) print('constructing MyWorld') def createRasters(self): print('creating rasters') self.registerDynamicRaster("resources", 1) self.getDynamicRaster("resources").setInitValues(0, 10, 0) return def createAgents(self)...
__init__
identifier_name
tutorial_pyPandora.py
#!/usr/bin/python3 import os, sys, random pandoraPath = os.getenv('PANDORAPATH', '/usr/local/pandora') sys.path.append(pandoraPath+'/bin') sys.path.append(pandoraPath+'/lib') from pyPandora import Config, World, Agent, SizeInt class MyAgent(Agent): gatheredResources = 0 def __init__(self, id): Age...
main()
random_line_split
tutorial_pyPandora.py
#!/usr/bin/python3 import os, sys, random pandoraPath = os.getenv('PANDORAPATH', '/usr/local/pandora') sys.path.append(pandoraPath+'/bin') sys.path.append(pandoraPath+'/lib') from pyPandora import Config, World, Agent, SizeInt class MyAgent(Agent): gatheredResources = 0 def __init__(self, id): Age...
def main(): print('getting started with pyPandora') numTimeSteps = 10 worldSize = SizeInt(64,64) myConfig = Config(worldSize, numTimeSteps) myWorld = MyWorld(myConfig) myWorld.initialize() myWorld.run() print('simulation finished') if __name__ == "__main__": main()
newAgent = MyAgent('MyAgent_'+str(i)) self.addAgent(newAgent) newAgent.setRandomPosition()
conditional_block
tutorial_pyPandora.py
#!/usr/bin/python3 import os, sys, random pandoraPath = os.getenv('PANDORAPATH', '/usr/local/pandora') sys.path.append(pandoraPath+'/bin') sys.path.append(pandoraPath+'/lib') from pyPandora import Config, World, Agent, SizeInt class MyAgent(Agent): gatheredResources = 0 def __init__(self, id): Age...
if __name__ == "__main__": main()
print('getting started with pyPandora') numTimeSteps = 10 worldSize = SizeInt(64,64) myConfig = Config(worldSize, numTimeSteps) myWorld = MyWorld(myConfig) myWorld.initialize() myWorld.run() print('simulation finished')
identifier_body
hex-color-picker.component.spec.ts
import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { HexColorPickerComponent } from './...
declarations: [ HexColorPickerComponent ], schemas: [ CUSTOM_ELEMENTS_SCHEMA ] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(HexColorPickerComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', ()...
BrowserAnimationsModule, FormsModule, ReactiveFormsModule ],
random_line_split
waker_ref.rs
use super::arc_wake::{ArcWake}; use super::waker::waker_vtable; use alloc::sync::Arc; use core::mem::ManuallyDrop; use core::marker::PhantomData; use core::ops::Deref; use core::task::{Waker, RawWaker}; /// A [`Waker`] that is only valid for a given lifetime. /// /// Note: this type implements [`Deref<Target = Waker>`...
(&self) -> &Waker { &self.waker } } /// Creates a reference to a [`Waker`] from a reference to `Arc<impl ArcWake>`. /// /// The resulting [`Waker`] will call /// [`ArcWake.wake()`](ArcWake::wake) if awoken. #[inline] pub fn waker_ref<W>(wake: &Arc<W>) -> WakerRef<'_> where W: ArcWake { // simply co...
deref
identifier_name
waker_ref.rs
use super::arc_wake::{ArcWake}; use super::waker::waker_vtable; use alloc::sync::Arc; use core::mem::ManuallyDrop; use core::marker::PhantomData; use core::ops::Deref; use core::task::{Waker, RawWaker}; /// A [`Waker`] that is only valid for a given lifetime. /// /// Note: this type implements [`Deref<Target = Waker>`...
WakerRef::new_unowned(waker) }
random_line_split
waker_ref.rs
use super::arc_wake::{ArcWake}; use super::waker::waker_vtable; use alloc::sync::Arc; use core::mem::ManuallyDrop; use core::marker::PhantomData; use core::ops::Deref; use core::task::{Waker, RawWaker}; /// A [`Waker`] that is only valid for a given lifetime. /// /// Note: this type implements [`Deref<Target = Waker>`...
} /// Creates a reference to a [`Waker`] from a reference to `Arc<impl ArcWake>`. /// /// The resulting [`Waker`] will call /// [`ArcWake.wake()`](ArcWake::wake) if awoken. #[inline] pub fn waker_ref<W>(wake: &Arc<W>) -> WakerRef<'_> where W: ArcWake { // simply copy the pointer instead of using Arc::into_raw...
{ &self.waker }
identifier_body
TestTrivialABI.py
""" Test that we work properly with classes with the trivial_abi attribute """ import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil class TestTrivialABI(TestBase): mydir = TestBase.compute_mydir(__file__) NO_DEBUG_INFO_TESTCASE = Tru...
# Now continue to the same thing without the trivial_abi and see if we get that right: threads = lldbutil.continue_to_breakpoint(process, bkpt) self.assertEqual(len(threads), 1, "Hit my breakpoint the second time.") self.check_frame(threads[0])
self.check_frame(thread) return
conditional_block
TestTrivialABI.py
""" Test that we work properly with classes with the trivial_abi attribute """ import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil class TestTrivialABI(TestBase): mydir = TestBase.compute_mydir(__file__) NO_DEBUG_INFO_TESTCASE = Tru...
self.check_value(outVal_ret, 30) def expr_test(self, trivial): (target, process, thread, bkpt) = lldbutil.run_to_source_breakpoint(self, "Set a breakpoint here", self.main_source_file) # Stop in a function that takes a trivial value, and try both frame va...
thread.StepOut() outVal_ret = thread.GetStopReturnValue()
random_line_split
TestTrivialABI.py
""" Test that we work properly with classes with the trivial_abi attribute """ import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil class TestTrivialABI(TestBase): mydir = TestBase.compute_mydir(__file__) NO_DEBUG_INFO_TESTCASE = Tru...
(self): """Test that we can print a variable & call a function on the same class w/o the trivial ABI marker.""" self.build() self.main_source_file = lldb.SBFileSpec("main.cpp") self.expr_test(False) def check_value(self, test_var, ivar_value): self.assertTrue(test_var.GetErr...
test_call_nontrivial
identifier_name
TestTrivialABI.py
""" Test that we work properly with classes with the trivial_abi attribute """ import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil class TestTrivialABI(TestBase): mydir = TestBase.compute_mydir(__file__) NO_DEBUG_INFO_TESTCASE = Tru...
(target, process, thread, bkpt) = lldbutil.run_to_source_breakpoint(self, "Set a breakpoint here", self.main_source_file) # Stop in a function that takes a trivial value, and try both frame var & expr to get its value: if trivial: self.check_frame(thread) ...
identifier_body
pystone.py
, 10/84 pg. 1013. Translated from ADA to C by Rick Richardson. Every method to preserve ADA-likeness has been used, at the expense of C-ness. Translated from C to Python by Guido van Rossum. Version History: Version 1.1 corrects two bug...
else: if StrParI1 > StrParI2: IntLoc = IntLoc + 7 return TRUE else: return FALSE def Func3(EnumParIn): EnumLoc = EnumParIn if EnumLoc == Ident3
return TRUE
random_line_split