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
Color.ts
const allColors = ["0072C6", "4617B4", "8C0095", "008A17", "D24726", "008299", "AC193D", "DC4FAD", "FF8F32", "82BA00", "03B3B2", "5DB2FF"]; const currentIterationColor = "#C1E6FF"; /*Pattens Blue*/ const otherIterationColors = ["#FFDAC1", "#E6FFC1", "#FFC1E6"]; /*Negroni, Chiffon, Cotton Candy*/ var interationCou...
if (name === "currentIteration") { return currentIterationColor; } if (name === "otherIteration") { return otherIterationColors[interationCount++ % otherIterationColors.length]; } const id = name.slice().toLowerCase(); let value = 0; for (let i = 0; i < (id || ""...
identifier_body
Color.ts
const allColors = ["0072C6", "4617B4", "8C0095", "008A17", "D24726", "008299", "AC193D", "DC4FAD", "FF8F32", "82BA00", "03B3B2", "5DB2FF"]; const currentIterationColor = "#C1E6FF"; /*Pattens Blue*/ const otherIterationColors = ["#FFDAC1", "#E6FFC1", "#FFC1E6"]; /*Negroni, Chiffon, Cotton Candy*/ var interationCou...
const id = name.slice().toLowerCase(); let value = 0; for (let i = 0; i < (id || "").length; i++) { value += id.charCodeAt(i) * (i + 1); } return "#" + allColors[value % allColors.length]; }
return otherIterationColors[interationCount++ % otherIterationColors.length]; }
conditional_block
Color.ts
const allColors = ["0072C6", "4617B4", "8C0095", "008A17", "D24726", "008299", "AC193D", "DC4FAD", "FF8F32", "82BA00", "03B3B2", "5DB2FF"]; const currentIterationColor = "#C1E6FF"; /*Pattens Blue*/ const otherIterationColors = ["#FFDAC1", "#E6FFC1", "#FFC1E6"]; /*Negroni, Chiffon, Cotton Candy*/ var interationCou...
return currentIterationColor; } if (name === "otherIteration") { return otherIterationColors[interationCount++ % otherIterationColors.length]; } const id = name.slice().toLowerCase(); let value = 0; for (let i = 0; i < (id || "").length; i++) { value += id.cha...
random_line_split
controller.js
/* *图片操作的controller */ myApp.controller("imgpageCtr",['app','$scope',"restAPI",function(app,$scope,restAPI){ $scope.imgList = []; $scope.unloading = false; //获取图片列表 restAPI.getQiuniuFiles.post({bucketname:"zhugemaolu",limit:10},function(res){ $scope.imgList = res.list; }); $scope.loadStart = function(key){ $...
}]);
$scope.imgList = app.filter("curArry")($scope.imgList,index); }; }); }
random_line_split
controller.js
/* *图片操作的controller */ myApp.controller("imgpageCtr",['app','$scope',"restAPI",function(app,$scope,restAPI){ $scope.imgList = []; $scope.unloading = false; //获取图片列表 restAPI.getQiuniuFiles.post({bucketname:"zhugemaolu",limit:10},function(res){ $scope.imgList = res.list; }); $scope.loadStart = function(key){ $...
app.filter("curArry")($scope.imgList,index); }; }); } }]);
conditional_block
cache.py
from __future__ import annotations import abc import shutil import functools from pathlib import Path import urllib.parse from typing import ( Callable, Any, TypeVar, cast, Tuple, Dict, Optional, Union, Hashable, ) import logging from edgar_code.types import PathLike, Serializer, UserDict from edgar_code.util.p...
( self, object_path: PathLike, name: str, serializer: Optional[Serializer] = None ) -> None: # pylint: disable=non-parent-init-called ObjectStore.__init__(self, name) if serializer is None: import pickle self.serializer = cast(Serializer, pickl...
__init__
identifier_name
cache.py
from __future__ import annotations import abc import shutil import functools from pathlib import Path import urllib.parse from typing import ( Callable, Any, TypeVar, cast, Tuple, Dict, Optional, Union, Hashable, ) import logging from edgar_code.types import PathLike, Serializer, UserDict from edgar_code.util.p...
ObjectStoreKey = TypeVar('ObjectStoreKey') ObjectStoreValue = TypeVar('ObjectStoreValue') class ObjectStore(UserDict[ObjectStoreKey, ObjectStoreValue], abc.ABC): @classmethod def create( cls, *args: Any, **kwargs: Any ) -> Callable[[str], ObjectStore[ObjectStoreKey, ObjectStoreValue]]: ...
def __str__(self) -> str: store_type = type(self.obj_store).__name__ return f'Cache of {self.name} with {store_type}'
random_line_split
cache.py
from __future__ import annotations import abc import shutil import functools from pathlib import Path import urllib.parse from typing import ( Callable, Any, TypeVar, cast, Tuple, Dict, Optional, Union, Hashable, ) import logging from edgar_code.types import PathLike, Serializer, UserDict from edgar_code.util.p...
else: self.serializer = serializer self.cache_path = pathify(object_path) / self.name def args2key(self, args: Tuple[Any, ...], kwargs: Dict[str, Any]) -> PathLike: if kwargs: args = args + (kwargs,) fname = urllib.parse.quote(f'{safe_str(args)}.pickle', saf...
import pickle self.serializer = cast(Serializer, pickle)
conditional_block
cache.py
from __future__ import annotations import abc import shutil import functools from pathlib import Path import urllib.parse from typing import ( Callable, Any, TypeVar, cast, Tuple, Dict, Optional, Union, Hashable, ) import logging from edgar_code.types import PathLike, Serializer, UserDict from edgar_code.util.p...
def to_hashable(obj: Any) -> Hashable: '''Converts args and kwargs into a hashable type (overridable)''' try: hash(obj) except TypeError: if hasattr(obj, 'items'): # turn dictionaries into frozenset((key, val)) # sorting is necessary to make equal dictionaries map ...
'''Stores objects at ./${CACHE_PATH}/${FUNCTION_NAME}/${urlencode(args)}.pickle''' def __init__( self, object_path: PathLike, name: str, serializer: Optional[Serializer] = None ) -> None: # pylint: disable=non-parent-init-called ObjectStore.__init__(self, name) i...
identifier_body
resource.rs
use alloc::boxed::Box; use system::error::{Error, Result, EBADF}; use system::syscall::Stat; /// Resource seek #[derive(Copy, Clone, Debug)] pub enum ResourceSeek { /// Start point Start(usize), /// Current point Current(isize), /// End point End(isize), } /// A system resource #[allow(unused...
(&mut self, buf: &[u8]) -> Result<usize> { Err(Error::new(EBADF)) } /// Seek to the given offset fn seek(&mut self, pos: ResourceSeek) -> Result<usize> { Err(Error::new(EBADF)) } fn stat(&self, stat: &mut Stat) -> Result<usize> { Err(Error::new(EBADF)) } /// Sync a...
write
identifier_name
resource.rs
use alloc::boxed::Box; use system::error::{Error, Result, EBADF}; use system::syscall::Stat; /// Resource seek #[derive(Copy, Clone, Debug)] pub enum ResourceSeek { /// Start point Start(usize), /// Current point Current(isize), /// End point End(isize), } /// A system resource #[allow(unused...
/// Return the path of this resource fn path(&self, buf: &mut [u8]) -> Result<usize> { Err(Error::new(EBADF)) } /// Read data to buffer fn read(&mut self, buf: &mut [u8]) -> Result<usize> { Err(Error::new(EBADF)) } /// Write to resource fn write(&mut self, buf: &[u8]) -...
}
random_line_split
resource.rs
use alloc::boxed::Box; use system::error::{Error, Result, EBADF}; use system::syscall::Stat; /// Resource seek #[derive(Copy, Clone, Debug)] pub enum ResourceSeek { /// Start point Start(usize), /// Current point Current(isize), /// End point End(isize), } /// A system resource #[allow(unused...
/// Return the path of this resource fn path(&self, buf: &mut [u8]) -> Result<usize> { Err(Error::new(EBADF)) } /// Read data to buffer fn read(&mut self, buf: &mut [u8]) -> Result<usize> { Err(Error::new(EBADF)) } /// Write to resource fn write(&mut self, buf: &[u8])...
{ Err(Error::new(EBADF)) }
identifier_body
index.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (C) 2013 Radim Rehurek <me@radimrehurek.com> # Licensed under the GNU LGPL v2.1 - http://www.gnu.org/licenses/lgpl.html import os from smart_open import smart_open try: import cPickle as _pickle except ImportError: import pickle as _pickle from gensi...
elif isinstance(self.model, Word2Vec): self.build_from_word2vec() else: raise ValueError("Only a Word2Vec or Doc2Vec instance can be used") def save(self, fname, protocol=2): fname_dict = fname + '.d' self.index.save(fname) d = {'f': ...
self.build_from_doc2vec()
conditional_block
index.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (C) 2013 Radim Rehurek <me@radimrehurek.com> # Licensed under the GNU LGPL v2.1 - http://www.gnu.org/licenses/lgpl.html import os from smart_open import smart_open try: import cPickle as _pickle except ImportError: import pickle as _pickle from gensi...
(self): """Build an Annoy index using document vectors from a Doc2Vec model""" docvecs = self.model.docvecs docvecs.init_sims() labels = [docvecs.index_to_doctag(i) for i in range(0, docvecs.count)] return self._build_from_model(docvecs.doctag_syn0norm, labels, self.model.vector...
build_from_doc2vec
identifier_name
index.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (C) 2013 Radim Rehurek <me@radimrehurek.com> # Licensed under the GNU LGPL v2.1 - http://www.gnu.org/licenses/lgpl.html import os from smart_open import smart_open try: import cPickle as _pickle except ImportError: import pickle as _pickle from gensi...
return [(self.labels[ids[i]], 1 - distances[i] / 2) for i in range(len(ids))]
random_line_split
index.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (C) 2013 Radim Rehurek <me@radimrehurek.com> # Licensed under the GNU LGPL v2.1 - http://www.gnu.org/licenses/lgpl.html import os from smart_open import smart_open try: import cPickle as _pickle except ImportError: import pickle as _pickle from gensi...
def save(self, fname, protocol=2): fname_dict = fname + '.d' self.index.save(fname) d = {'f': self.model.vector_size, 'num_trees': self.num_trees, 'labels': self.labels} with smart_open(fname_dict, 'wb') as fout: _pickle.dump(d, fout, protocol=protocol) def load(se...
self.index = None self.labels = None self.model = model self.num_trees = num_trees if model and num_trees: if isinstance(self.model, Doc2Vec): self.build_from_doc2vec() elif isinstance(self.model, Word2Vec): self.build_from_word2ve...
identifier_body
mod_neg.rs
use num::arithmetic::traits::{ModNeg, ModNegAssign}; use num::basic::traits::Zero; use std::ops::Sub; fn mod_neg<T: Copy + Eq + Sub<T, Output = T> + Zero>(x: T, m: T) -> T { if x == T::ZERO { T::ZERO } else
} fn mod_neg_assign<T: Copy + Eq + Sub<T, Output = T> + Zero>(x: &mut T, m: T) { if *x != T::ZERO { *x = m - *x; } } macro_rules! impl_mod_neg { ($t:ident) => { impl ModNeg for $t { type Output = $t; /// Computes `-self` mod `m`. Assumes the input is already reduc...
{ m - x }
conditional_block
mod_neg.rs
use num::arithmetic::traits::{ModNeg, ModNegAssign}; use num::basic::traits::Zero; use std::ops::Sub; fn mod_neg<T: Copy + Eq + Sub<T, Output = T> + Zero>(x: T, m: T) -> T
fn mod_neg_assign<T: Copy + Eq + Sub<T, Output = T> + Zero>(x: &mut T, m: T) { if *x != T::ZERO { *x = m - *x; } } macro_rules! impl_mod_neg { ($t:ident) => { impl ModNeg for $t { type Output = $t; /// Computes `-self` mod `m`. Assumes the input is already reduced...
{ if x == T::ZERO { T::ZERO } else { m - x } }
identifier_body
mod_neg.rs
use num::arithmetic::traits::{ModNeg, ModNegAssign}; use num::basic::traits::Zero; use std::ops::Sub; fn
<T: Copy + Eq + Sub<T, Output = T> + Zero>(x: T, m: T) -> T { if x == T::ZERO { T::ZERO } else { m - x } } fn mod_neg_assign<T: Copy + Eq + Sub<T, Output = T> + Zero>(x: &mut T, m: T) { if *x != T::ZERO { *x = m - *x; } } macro_rules! impl_mod_neg { ($t:ident) => { ...
mod_neg
identifier_name
mod_neg.rs
use num::arithmetic::traits::{ModNeg, ModNegAssign}; use num::basic::traits::Zero; use std::ops::Sub; fn mod_neg<T: Copy + Eq + Sub<T, Output = T> + Zero>(x: T, m: T) -> T { if x == T::ZERO { T::ZERO } else { m - x } } fn mod_neg_assign<T: Copy + Eq + Sub<T, Output = T> + Zero>(x: &mut T, ...
($t:ident) => { impl ModNeg for $t { type Output = $t; /// Computes `-self` mod `m`. Assumes the input is already reduced mod `m`. /// /// $f(x, m) = y$, where $x, y < m$ and $-x \equiv y \mod m$. /// /// # Worst-case complexity ...
} macro_rules! impl_mod_neg {
random_line_split
err.rs
use std::error::Error; use std::fmt; use ::dynamic::CompositerError; use ::graphic::ManagerError; use ::pty_proc::shell::ShellError; pub type Result<T> = ::std::result::Result<T, NekoError>; /// The enum `NekoError` defines the possible errors /// from constructor Neko. #[derive(Debug)] pub enum NekoError { /// ...
(&self, _: &mut fmt::Formatter) -> fmt::Result { Ok(()) } } impl Error for NekoError { /// The function `description` returns a short description of /// the error. fn description(&self) -> &str { match *self { NekoError::DynamicFail(_) => "The dynamic library interface has\ ...
fmt
identifier_name
err.rs
use std::error::Error; use std::fmt; use ::dynamic::CompositerError; use ::graphic::ManagerError; use ::pty_proc::shell::ShellError; pub type Result<T> = ::std::result::Result<T, NekoError>; /// The enum `NekoError` defines the possible errors /// from constructor Neko. #[derive(Debug)] pub enum NekoError { /// ...
impl Error for NekoError { /// The function `description` returns a short description of /// the error. fn description(&self) -> &str { match *self { NekoError::DynamicFail(_) => "The dynamic library interface has\ occured an error.", NekoError::Gr...
fn fmt(&self, _: &mut fmt::Formatter) -> fmt::Result { Ok(()) } }
random_line_split
automaticConstructorToggling.ts
/// <reference path='fourslash.ts'/> ////class A<T> { } ////class B<T> {/*B*/ } ////class C<T> { /*C*/constructor(val: T) { } } ////class D<T> { constructor(/*D*/val: T) { } } //// ////new /*Asig*/A<string>(); ////new /*Bsig*/B(""); ////new /*Csig*/C(""); ////new /*Dsig*/D<string>(); var A = 'A'; var B =...
goTo.marker(C); edit.deleteAtCaret('constructor(val: T) { }'.length); verify.quickInfos({ Asig: "constructor A<string>(): A<string>", Bsig: "constructor B<string>(val: string): B<string>", Csig: "constructor C<unknown>(): C<unknown>", // Cannot resolve signature Dsig: "constructor D<string>(val: s...
random_line_split
index.js
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-2016 Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ /* eslint-disable global-require */ // The top-level (par...
};
// Execute each child route until one of them return the result const route = await next(); // Provide default values for title, description etc. route.title = `${route.title || 'Untitled Page'} - www.reactstarterkit.com`; route.description = route.description || ''; return route; },
identifier_body
index.js
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-2016 Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ /* eslint-disable global-require */ // The top-level (par...
{ next }) { // Execute each child route until one of them return the result const route = await next(); // Provide default values for title, description etc. route.title = `${route.title || 'Untitled Page'} - www.reactstarterkit.com`; route.description = route.description || ''; return route; ...
ction(
identifier_name
index.js
/**
* Copyright © 2014-2016 Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ /* eslint-disable global-require */ // The top-level (parent) route export default { path: '/', // Keep in mind, r...
* React Starter Kit (https://www.reactstarterkit.com/) *
random_line_split
move_vm.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::FuzzTargetImpl; use anyhow::{bail, Result}; use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt}; use diem_proptest_helpers::ValueGenerator; use move_core_types::value::MoveTypeLayout; use move_vm_types::values::{prop::lay...
impl FuzzTargetImpl for ValueTarget { fn description(&self) -> &'static str { "VM values + types (custom deserializer)" } fn generate(&self, _idx: usize, gen: &mut ValueGenerator) -> Option<Vec<u8>> { let (layout, value) = gen.generate(layout_and_value_strategy()); // Values as cur...
random_line_split
move_vm.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::FuzzTargetImpl; use anyhow::{bail, Result}; use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt}; use diem_proptest_helpers::ValueGenerator; use move_core_types::value::MoveTypeLayout; use move_vm_types::values::{prop::lay...
} fn is_valid_layout(layout: &MoveTypeLayout) -> bool { use MoveTypeLayout as L; match layout { L::Bool | L::U8 | L::U64 | L::U128 | L::Address | L::Signer => true, L::Vector(layout) => is_valid_layout(layout), L::Struct(struct_layout) => { if struct_layout.fields().is_e...
{ let _ = deserialize(data); }
identifier_body
move_vm.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::FuzzTargetImpl; use anyhow::{bail, Result}; use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt}; use diem_proptest_helpers::ValueGenerator; use move_core_types::value::MoveTypeLayout; use move_vm_types::values::{prop::lay...
(&self, data: &[u8]) { let _ = deserialize(data); } } fn is_valid_layout(layout: &MoveTypeLayout) -> bool { use MoveTypeLayout as L; match layout { L::Bool | L::U8 | L::U64 | L::U128 | L::Address | L::Signer => true, L::Vector(layout) => is_valid_layout(layout), L::Struct...
fuzz
identifier_name
move_vm.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::FuzzTargetImpl; use anyhow::{bail, Result}; use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt}; use diem_proptest_helpers::ValueGenerator; use move_core_types::value::MoveTypeLayout; use move_vm_types::values::{prop::lay...
let layout_data = &data[..layout_len]; let value_data = &data[layout_len..]; let layout: MoveTypeLayout = bcs::from_bytes(layout_data)?; // The fuzzer may alter the raw bytes, resulting in invalid layouts that will not // pass the bytecode verifier. We need to filter these out as they can show up...
{ bail!("too little data"); }
conditional_block
acrobot.py
__author__ = 'Frank Sehnke, sehnke@in.tum.de' from pybrain.rl.environments.ode import ODEEnvironment, sensors, actuators import imp from scipy import array class AcrobotEnvironment(ODEEnvironment): def __init__(self, renderer=True, realtime=True, ip="127.0.0.1", port="21590", buf='16384'): ODEEnvironment....
#set act- and obsLength, the min/max angles and the relative max touques of the joints self.actLen = self.indim self.obsLen = len(self.getSensors()) self.stepsPerAction = 1 if __name__ == '__main__' : w = AcrobotEnvironment() while True: w.step() if w.stepCount...
# standard sensors and actuators self.addSensor(sensors.JointSensor()) self.addSensor(sensors.JointVelocitySensor()) self.addActuator(actuators.JointActuator())
random_line_split
acrobot.py
__author__ = 'Frank Sehnke, sehnke@in.tum.de' from pybrain.rl.environments.ode import ODEEnvironment, sensors, actuators import imp from scipy import array class AcrobotEnvironment(ODEEnvironment): def
(self, renderer=True, realtime=True, ip="127.0.0.1", port="21590", buf='16384'): ODEEnvironment.__init__(self, renderer, realtime, ip, port, buf) # load model file self.loadXODE(imp.find_module('pybrain')[1] + "/rl/environments/ode/models/acrobot.xode") # standard sensors and actuators ...
__init__
identifier_name
acrobot.py
__author__ = 'Frank Sehnke, sehnke@in.tum.de' from pybrain.rl.environments.ode import ODEEnvironment, sensors, actuators import imp from scipy import array class AcrobotEnvironment(ODEEnvironment): def __init__(self, renderer=True, realtime=True, ip="127.0.0.1", port="21590", buf='16384'): ODEEnvironment....
w.reset()
conditional_block
acrobot.py
__author__ = 'Frank Sehnke, sehnke@in.tum.de' from pybrain.rl.environments.ode import ODEEnvironment, sensors, actuators import imp from scipy import array class AcrobotEnvironment(ODEEnvironment):
if __name__ == '__main__' : w = AcrobotEnvironment() while True: w.step() if w.stepCounter == 1000: w.reset()
def __init__(self, renderer=True, realtime=True, ip="127.0.0.1", port="21590", buf='16384'): ODEEnvironment.__init__(self, renderer, realtime, ip, port, buf) # load model file self.loadXODE(imp.find_module('pybrain')[1] + "/rl/environments/ode/models/acrobot.xode") # standard sensors an...
identifier_body
award_type.py
import enum from typing import Dict, Set from backend.common.consts.event_type import EventType @enum.unique class AwardType(enum.IntEnum): """ An award type defines a logical type of award that an award falls into. These types are the same across both years and competitions within a year. In other w...
INDUSTRIAL_DESIGN = 16 QUALITY = 17 SAFETY = 18 SPORTSMANSHIP = 19 CREATIVITY = 20 ENGINEERING_EXCELLENCE = 21 ENTREPRENEURSHIP = 22 EXCELLENCE_IN_DESIGN = 23 EXCELLENCE_IN_DESIGN_CAD = 24 EXCELLENCE_IN_DESIGN_ANIMATION = 25 DRIVING_TOMORROWS_TECHNOLOGY = 26 IMAGERY = 27 ...
HIGHEST_ROOKIE_SEED = 14 ROOKIE_INSPIRATION = 15
random_line_split
award_type.py
import enum from typing import Dict, Set from backend.common.consts.event_type import EventType @enum.unique class AwardType(enum.IntEnum):
AWARD_TYPES: Set[AwardType] = {a for a in AwardType} BLUE_BANNER_AWARDS: Set[AwardType] = { AwardType.CHAIRMANS, AwardType.CHAIRMANS_FINALIST, AwardType.WINNER, AwardType.WOODIE_FLOWERS, AwardType.SKILLS_COMPETITION_WINNER, } INDIVIDUAL_AWARDS: Set[AwardType] = { AwardType.WOODIE_FLOWERS,...
""" An award type defines a logical type of award that an award falls into. These types are the same across both years and competitions within a year. In other words, an industrial design award from 2013casj and 2010cmp will be of award type AwardType.INDUSTRIAL_DESIGN. An award type must be enumer...
identifier_body
award_type.py
import enum from typing import Dict, Set from backend.common.consts.event_type import EventType @enum.unique class
(enum.IntEnum): """ An award type defines a logical type of award that an award falls into. These types are the same across both years and competitions within a year. In other words, an industrial design award from 2013casj and 2010cmp will be of award type AwardType.INDUSTRIAL_DESIGN. An award...
AwardType
identifier_name
ng_class.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 {Directive, DoCheck, Input, ɵRenderFlags, ΔclassMap, ΔdefineDirective, Δstyling, ΔstylingApply} from '@angular...
this._delegate.getValue(); } } /** * @ngModule CommonModule * * @usageNotes * ``` * <some-element [ngClass]="'first second'">...</some-element> * * <some-element [ngClass]="['first', 'second']">...</some-element> * * <some-element [ngClass]="{'first': true, 'second': true, 'third': false}">...</so...
return
identifier_name
ng_class.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 {Directive, DoCheck, Input, ɵRenderFlags, ΔclassMap, ΔdefineDirective, Δstyling, ΔstylingApply} from '@angular...
if (rf & ɵRenderFlags.Update) { ΔclassMap(ctx.getValue()); ΔstylingApply(); } } }); export const ngClassDirectiveDef = ngClassDirectiveDef__PRE_R3__; /** * Serves as the base non-VE container for NgClass. * * While this is a base class that NgClass extends from, the * class itself acts as a ...
hostBindings: function(rf: ɵRenderFlags, ctx: any, elIndex: number) { if (rf & ɵRenderFlags.Create) { Δstyling(); }
random_line_split
ng_class.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 {Directive, DoCheck, Input, ɵRenderFlags, ΔclassMap, ΔdefineDirective, Δstyling, ΔstylingApply} from '@angular...
k() { this._delegate.applyChanges(); } }
delegate.setNgClass(value); } ngDoChec
identifier_body
ng_class.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 {Directive, DoCheck, Input, ɵRenderFlags, ΔclassMap, ΔdefineDirective, Δstyling, ΔstylingApply} from '@angular...
rf & ɵRenderFlags.Update) { ΔclassMap(ctx.getValue()); ΔstylingApply(); } } }); export const ngClassDirectiveDef = ngClassDirectiveDef__PRE_R3__; /** * Serves as the base non-VE container for NgClass. * * While this is a base class that NgClass extends from, the * class itself acts as a containe...
Δstyling(); } if (
conditional_block
plugin.js
/** * @license Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved. * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license */ ( function() { 'use strict'; CKEDITOR.plugins.add( 'embedsemantic', { icons: 'embedsemantic', // %REMOVE_LINE_CORE% hidpi: true, // ...
} ); }, upcast: function( element, data ) { if ( element.name != 'oembed' ) { return; } var text = element.children[ 0 ], div; if ( text && text.type == CKEDITOR.NODE_TEXT && text.value ) { data.url = text.value; data.loadOnReady = true; div = new CKEDI...
{ this.loadContent( this.data.url, { callback: function() { // Do not load the content again on widget's next initialization (e.g. after undo or paste). // Plus, this is a small trick that we change loadOnReady now, inside the callback. // It guarantees that if the content was ...
conditional_block
plugin.js
/** * @license Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved. * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license */ ( function() { 'use strict'; CKEDITOR.plugins.add( 'embedsemantic', { icons: 'embedsemantic', // %REMOVE_LINE_CORE% hidpi: true, // ...
dtd[ name ].oembed = 1; } } } } ); } )();
if ( dtd[ name ].div ) {
random_line_split
PredictorRegressionMetrics.tsx
import * as React from 'react' import { ValueLine } from '@framework/Lines' import { TypeContext } from '@framework/TypeContext' import { PredictorRegressionMetricsEmbedded, PredictorEntity } from '../Signum.Entities.MachineLearning' export default class PredictorRegressionMetrics extends React.Component<{ ctx: ...
} }
);
random_line_split
protocols_client.py
# Copyright 2020 Samsung Electronics Co., Ltd # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may not # use this file except in compliance with the License. You may obtain a copy of # the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by a...
resp, body = self.get(url) self.expected_success(200, resp.status) body = json.loads(body) return rest_client.ResponseBody(resp, body) def get_protocol_for_identity_provider(self, idp_id, protocol_id): """Get protocol for identity provider. For a full list of avail...
url += '?%s' % urllib.urlencode(kwargs)
conditional_block
protocols_client.py
# Copyright 2020 Samsung Electronics Co., Ltd # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may not # use this file except in compliance with the License. You may obtain a copy of # the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by a...
""" url = 'OS-FEDERATION/identity_providers/%s/protocols' % idp_id if kwargs: url += '?%s' % urllib.urlencode(kwargs) resp, body = self.get(url) self.expected_success(200, resp.status) body = json.loads(body) return rest_client.ResponseBody(resp, body)...
"""List protocols of identity provider. For a full list of available parameters, please refer to the official API reference: https://docs.openstack.org/api-ref/identity/v3-ext/index.html#list-protocols-of-identity-provider
random_line_split
protocols_client.py
# Copyright 2020 Samsung Electronics Co., Ltd # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may not # use this file except in compliance with the License. You may obtain a copy of # the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by a...
(self, idp_id, **kwargs): """List protocols of identity provider. For a full list of available parameters, please refer to the official API reference: https://docs.openstack.org/api-ref/identity/v3-ext/index.html#list-protocols-of-identity-provider """ url = 'OS-FEDERATI...
list_protocols_of_identity_provider
identifier_name
protocols_client.py
# Copyright 2020 Samsung Electronics Co., Ltd # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may not # use this file except in compliance with the License. You may obtain a copy of # the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by a...
def get_protocol_for_identity_provider(self, idp_id, protocol_id): """Get protocol for identity provider. For a full list of available parameters, please refer to the official API reference: https://docs.openstack.org/api-ref/identity/v3-ext/index.html#get-protocol-for-identity-pr...
"""List protocols of identity provider. For a full list of available parameters, please refer to the official API reference: https://docs.openstack.org/api-ref/identity/v3-ext/index.html#list-protocols-of-identity-provider """ url = 'OS-FEDERATION/identity_providers/%s/protocols...
identifier_body
math.ts
/** * Converts degrees (°) to radians. * @param degrees The degrees to convert. * Returns the result radians. */ export function radians(degrees:number):number { return degrees * Math.PI / 180; } /** * Converts radians (c) to degrees. * @param radians The radians to convert. * Returns the result degrees. */...
else if(diff > Math.PI && target < source) { result = source + step; } else if(diff == Math.PI) { result = source + step; } //Normalize angle result = normalizeRadians(result); if ((result > target && result - step < target) || (result < target && result + step > ta...
result = source - step; }
conditional_block
math.ts
/** * Converts degrees (°) to radians. * @param degrees The degrees to convert. * Returns the result radians. */ export function radians(degrees:number):number { return degrees * Math.PI / 180; } /** * Converts radians (c) to degrees. * @param radians The radians to convert. * Returns the result degrees. */...
/** * Clamps a value by limiting it between minimum and maximum values. * @param value The value to clamp. * @param min The miminum value. * @param max The maximum value. * Returns min if the value is less than min. Returns max if the value is larger than max. Returns the same value otherwise. */ export function ...
return value * (1 - stepPercentage) + targetValue * stepPercentage; }
identifier_body
math.ts
/** * Converts degrees (°) to radians. * @param degrees The degrees to convert. * Returns the result radians. */ export function radians(degrees:number):number { return degrees * Math.PI / 180; } /** * Converts radians (c) to degrees. * @param radians The radians to convert. * Returns the result degrees. */...
var intersect = ((yi > y) != (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi); if (intersect) inside = !inside; } return inside; } export const TWO_PI = 6.28318530718;
random_line_split
math.ts
/** * Converts degrees (°) to radians. * @param degrees The degrees to convert. * Returns the result radians. */ export function radians(degrees:number):number { return degrees * Math.PI / 180; } /** * Converts radians (c) to degrees. * @param radians The radians to convert. * Returns the result degrees. */...
T>(selector:(o:T) => number, items:T[]):number { return _minOrMax(true, selector, items); } /** * Returns the largest value occurring in the collection. * @param selector Selector used to get the comparable number value. * @param items Source items to iterate over. * Returns the largest occurring number value. ...
in<
identifier_name
matrix.py
import math import ctypes from parse import * class Matrix(object): def __init__(self, string=None): self.values = [1, 0, 0, 1, 0, 0] #Identity matrix seems a sensible default if isinstance(string, str): if string.startswith('matrix('): self.values = [float(x) for x in p...
def svg_matrix_to_gl_matrix(matrix): v = matrix.values return [v[0], v[1], 0.0, v[2], v[3], 0.0, v[4], v[5], 1.0] def as_c_matrix(values): matrix_type = ctypes.c_float * len(values) matrix = matrix_type(*values) return ctypes.cast(matrix, ctypes.POINTER(ctypes.c_float) )
a, b, c, d, e, f = self.values u, v, w, x, y, z = other.values return Matrix([a*u + c*v, b*u + d*v, a*w + c*x, b*w + d*x, a*y + c*z + e, b*y + d*z + f])
identifier_body
matrix.py
import math import ctypes from parse import * class Matrix(object): def __init__(self, string=None): self.values = [1, 0, 0, 1, 0, 0] #Identity matrix seems a sensible default if isinstance(string, str):
elif string is not None: self.values = list(string) def __call__(self, other): return (self.values[0]*other[0] + self.values[2]*other[1] + self.values[4], self.values[1]*other[0] + self.values[3]*other[1] + self.values[5]) def __str__(self): ...
if string.startswith('matrix('): self.values = [float(x) for x in parse_list(string[7:-1])] elif string.startswith('translate('): x, y = [float(x) for x in parse_list(string[10:-1])] self.values = [1, 0, 0, 1, x, y] elif string.startswith('scale(')...
conditional_block
matrix.py
import math import ctypes from parse import * class Matrix(object): def __init__(self, string=None): self.values = [1, 0, 0, 1, 0, 0] #Identity matrix seems a sensible default if isinstance(string, str): if string.startswith('matrix('): self.values = [float(x) for x in p...
self.values = [sx, 0, 0, sy, 0, 0] elif string is not None: self.values = list(string) def __call__(self, other): return (self.values[0]*other[0] + self.values[2]*other[1] + self.values[4], self.values[1]*other[0] + self.values[3]*other[1] ...
random_line_split
matrix.py
import math import ctypes from parse import * class Matrix(object): def __init__(self, string=None): self.values = [1, 0, 0, 1, 0, 0] #Identity matrix seems a sensible default if isinstance(string, str): if string.startswith('matrix('): self.values = [float(x) for x in p...
(self, other): a, b, c, d, e, f = self.values u, v, w, x, y, z = other.values return Matrix([a*u + c*v, b*u + d*v, a*w + c*x, b*w + d*x, a*y + c*z + e, b*y + d*z + f]) def svg_matrix_to_gl_matrix(matrix): v = matrix.values return [v[0], v[1], 0.0, v[2], v[3], 0.0, v[4], v[5], 1....
__mul__
identifier_name
pcl__arm__filter__srv_8cpp.js
var pcl__arm__filter__srv_8cpp = [ [ "PCLCloud", "pcl__arm__filter__srv_8cpp.html#a29f570b87ddde9c9a67921f43564b7d4", null ], [ "PCLCloudPtr", "pcl__arm__filter__srv_8cpp.html#a3088acf82e1f026966b77cf8cc8c545b", null ], [ "armFiltering", "pcl__arm__filter__srv_8cpp.html#a4b5f9e676122ea81018e287be90c84c7", n...
];
[ "tfError", "pcl__arm__filter__srv_8cpp.html#a163bafbb51ee2789c7dcc991b5a1e903", null ], [ "trans", "pcl__arm__filter__srv_8cpp.html#a82c8dace269f9b25efa4df02f0b03c22", null ], [ "translation", "pcl__arm__filter__srv_8cpp.html#a3131a4e19d28e7b521a9a9e43c614c26", null ], [ "yaw", "pcl__arm__filter__srv_...
random_line_split
project-search.spec.js
/* 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/>. */ // @flow import { findSourceMatches } from "../project-search"; const text = ` function foo() { foo(); ...
it("finds no matches in source", () => { const needle = "test"; const source: any = { text, loadedState: "loaded", id: "bar.js", url: "http://example.com/foo/bar.js" }; const matches = findSourceMatches(source, needle); expect(matches).toEqual(emptyResults); }); });
expect(matches).toMatchSnapshot(); });
random_line_split
tasks.py
from __future__ import absolute_import, unicode_literals import time from datetime import timedelta from djcelery_transactions import task from django.utils import timezone from redis_cache import get_redis_connection from .models import CreditAlert, Invitation, Org, TopUpCredits @task(track_started=True, name='sen...
@task(track_started=True, name="squash_topupcredits") def squash_topupcredits(): r = get_redis_connection() key = 'squash_topupcredits' if not r.get(key): with r.lock(key, timeout=900): TopUpCredits.squash_credits()
start = time.time() org._calculate_credit_caches() print " -- recalculated credits for %s in %0.2f seconds" % (org.name, time.time() - start)
conditional_block
tasks.py
from __future__ import absolute_import, unicode_literals import time from datetime import timedelta from djcelery_transactions import task from django.utils import timezone from redis_cache import get_redis_connection from .models import CreditAlert, Invitation, Org, TopUpCredits
@task(track_started=True, name='send_invitation_email_task') def send_invitation_email_task(invitation_id): invitation = Invitation.objects.get(pk=invitation_id) invitation.send_email() @task(track_started=True, name='send_alert_email_task') def send_alert_email_task(alert_id): alert = CreditAlert.objects...
random_line_split
tasks.py
from __future__ import absolute_import, unicode_literals import time from datetime import timedelta from djcelery_transactions import task from django.utils import timezone from redis_cache import get_redis_connection from .models import CreditAlert, Invitation, Org, TopUpCredits @task(track_started=True, name='sen...
@task(track_started=True, name="squash_topupcredits") def squash_topupcredits(): r = get_redis_connection() key = 'squash_topupcredits' if not r.get(key): with r.lock(key, timeout=900): TopUpCredits.squash_credits()
""" Repopulates the active topup and total credits for each organization that received messages in the past week. """ # get all orgs that have sent a message in the past week last_week = timezone.now() - timedelta(days=7) # for every org that has sent a message in the past week for org in O...
identifier_body
tasks.py
from __future__ import absolute_import, unicode_literals import time from datetime import timedelta from djcelery_transactions import task from django.utils import timezone from redis_cache import get_redis_connection from .models import CreditAlert, Invitation, Org, TopUpCredits @task(track_started=True, name='sen...
(alert_id): alert = CreditAlert.objects.get(pk=alert_id) alert.send_email() @task(track_started=True, name='check_credits_task') def check_credits_task(): CreditAlert.check_org_credits() @task(track_started=True, name='calculate_credit_caches') def calculate_credit_caches(): """ Repopulates the ...
send_alert_email_task
identifier_name
first_run.rs
use std::fs::create_dir; use std::path::Path; /// Used just to check for the existence of the default path. Prints out /// useful messages as to what's happening. /// /// # Examples /// /// ```rust /// extern crate rand; /// /// use common::first_run::check_first_run; /// use rand::random; /// use std::fs::{create_dir...
let _ = remove_dir(path); } #[test] fn returns_ok_if_already_exists() { let path = rand_names::project_path(); let _ = create_dir(&path); assert!(check_first_run(&path).is_ok()); let _ = remove_dir(path); } }
assert!(!path.exists()); assert!(check_first_run(&path).is_ok()); // Side effects assert!(path.exists());
random_line_split
first_run.rs
use std::fs::create_dir; use std::path::Path; /// Used just to check for the existence of the default path. Prints out /// useful messages as to what's happening. /// /// # Examples /// /// ```rust /// extern crate rand; /// /// use common::first_run::check_first_run; /// use rand::random; /// use std::fs::{create_dir...
; Ok(()) } #[cfg(test)] mod test { use super::*; use rand_names; use std::fs::remove_dir; #[test] fn creates_dir_if_not_exist() { let path = rand_names::project_path(); assert!(!path.exists()); assert!(check_first_run(&path).is_ok()); // Side effects assert!(p...
{ create_dir(muxed_dir).map_err(|e| format!("We noticed the configuration directory: `{}` didn't exist so we tried to create it, but something went wrong: {}", muxed_dir.display(), e))?; println!("Looks like this is your first time here. Muxed could't find the configuration directory: `{}`", muxed_dir.d...
conditional_block
first_run.rs
use std::fs::create_dir; use std::path::Path; /// Used just to check for the existence of the default path. Prints out /// useful messages as to what's happening. /// /// # Examples /// /// ```rust /// extern crate rand; /// /// use common::first_run::check_first_run; /// use rand::random; /// use std::fs::{create_dir...
#[cfg(test)] mod test { use super::*; use rand_names; use std::fs::remove_dir; #[test] fn creates_dir_if_not_exist() { let path = rand_names::project_path(); assert!(!path.exists()); assert!(check_first_run(&path).is_ok()); // Side effects assert!(path.exists()); ...
{ if !muxed_dir.exists() { create_dir(muxed_dir).map_err(|e| format!("We noticed the configuration directory: `{}` didn't exist so we tried to create it, but something went wrong: {}", muxed_dir.display(), e))?; println!("Looks like this is your first time here. Muxed could't find the configuration ...
identifier_body
first_run.rs
use std::fs::create_dir; use std::path::Path; /// Used just to check for the existence of the default path. Prints out /// useful messages as to what's happening. /// /// # Examples /// /// ```rust /// extern crate rand; /// /// use common::first_run::check_first_run; /// use rand::random; /// use std::fs::{create_dir...
() { let path = rand_names::project_path(); assert!(!path.exists()); assert!(check_first_run(&path).is_ok()); // Side effects assert!(path.exists()); let _ = remove_dir(path); } #[test] fn returns_ok_if_already_exists() { let path = rand_names::project_path...
creates_dir_if_not_exist
identifier_name
FeatureSetItem.tsx
import React, { ComponentProps } from "react" import { Box } from "@artsy/palette" import { createFragmentContainer, graphql } from "react-relay" import { FeatureFeaturedLinkFragmentContainer as FeatureFeaturedLink } from "../FeatureFeaturedLink" import GridItem from "v2/Components/Artwork/GridItem" import { FeatureSet...
} )
...FeatureFeaturedLink_featuredLink } `,
random_line_split
index.d.ts
// Type definitions for lodash-webpack-plugin 0.11 // Project: https://github.com/lodash/lodash-webpack-plugin#readme // Definitions by: Benjamin Lim <https://github.com/bumbleblym> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 import { Plugin } from 'webpack'; export =...
extends Plugin { constructor(options?: LodashModuleReplacementPlugin.Options); } declare namespace LodashModuleReplacementPlugin { interface Options { caching?: boolean; chaining?: boolean; cloning?: boolean; coercions?: boolean; collections?: boolean; currying?: boolean; deburring?: boolean; exotic...
LodashModuleReplacementPlugin
identifier_name
index.d.ts
// Type definitions for lodash-webpack-plugin 0.11 // Project: https://github.com/lodash/lodash-webpack-plugin#readme // Definitions by: Benjamin Lim <https://github.com/bumbleblym> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 import { Plugin } from 'webpack'; export =...
placeholders?: boolean; shorthands?: boolean; unicode?: boolean; } }
flattening?: boolean; guards?: boolean; memoizing?: boolean; metadata?: boolean; paths?: boolean;
random_line_split
add.rs
use std::string::{String}; use std::sync::{Arc};
fn operation<T>(vec: Vec<Tensor<T>>) -> Tensor<T> where T: Copy + Mul<Output=T> + Add<Output=T> { let Vec2(x1, y1) = vec[0].dim(); let Vec2(x2, _) = vec[1].dim(); if x1 != 1 && x2 == 1 { let transform = vec[1].buffer(); Tensor::from_vec(Vec2(x1, y1), vec[0].buffer().iter().enumerate().map(|(...
use std::ops::{Mul, Add}; use math::{Vec2}; use node::{Node, Graph}; use tensor::{Tensor};
random_line_split
add.rs
use std::string::{String}; use std::sync::{Arc}; use std::ops::{Mul, Add}; use math::{Vec2}; use node::{Node, Graph}; use tensor::{Tensor}; fn
<T>(vec: Vec<Tensor<T>>) -> Tensor<T> where T: Copy + Mul<Output=T> + Add<Output=T> { let Vec2(x1, y1) = vec[0].dim(); let Vec2(x2, _) = vec[1].dim(); if x1 != 1 && x2 == 1 { let transform = vec[1].buffer(); Tensor::from_vec(Vec2(x1, y1), vec[0].buffer().iter().enumerate().map(|(i, &x)| x + ...
operation
identifier_name
add.rs
use std::string::{String}; use std::sync::{Arc}; use std::ops::{Mul, Add}; use math::{Vec2}; use node::{Node, Graph}; use tensor::{Tensor}; fn operation<T>(vec: Vec<Tensor<T>>) -> Tensor<T> where T: Copy + Mul<Output=T> + Add<Output=T>
fn operation_prime<T>(gradient: &Tensor<T>, vec: Vec<&Tensor<T>>) -> Vec<Tensor<T>> where T: Copy + Mul<Output=T> + Add<Output=T> { let Vec2(x1, y1) = vec[0].dim(); let Vec2(x2, _) = vec[1].dim(); if x1 != 1 && x2 == 1 { let mut vector_grad = Vec::with_capacity(y1); for i in 0..y1 { ...
{ let Vec2(x1, y1) = vec[0].dim(); let Vec2(x2, _) = vec[1].dim(); if x1 != 1 && x2 == 1 { let transform = vec[1].buffer(); Tensor::from_vec(Vec2(x1, y1), vec[0].buffer().iter().enumerate().map(|(i, &x)| x + transform[i % y1]).collect()) } else { &vec[0] + &vec[1] } }
identifier_body
add.rs
use std::string::{String}; use std::sync::{Arc}; use std::ops::{Mul, Add}; use math::{Vec2}; use node::{Node, Graph}; use tensor::{Tensor}; fn operation<T>(vec: Vec<Tensor<T>>) -> Tensor<T> where T: Copy + Mul<Output=T> + Add<Output=T> { let Vec2(x1, y1) = vec[0].dim(); let Vec2(x2, _) = vec[1].dim(); if x...
else { vec![gradient.clone(), gradient.clone()] } } fn calc_dim(dims: Vec<Vec2>) -> Vec2 { let Vec2(x1, y1) = dims[0]; let Vec2(x2, y2) = dims[1]; assert!(x1 == 0 && x2 == 1 || x1 == x2); assert_eq!(y1, y2); dims[0] } pub fn add<T>(node_id: String, a: Arc<Graph<T>>, b: Arc<Graph<T>>) ...
{ let mut vector_grad = Vec::with_capacity(y1); for i in 0..y1 { let mut k = gradient.get(Vec2(0, i)); for j in 1..x1 { k = k + gradient.get(Vec2(j, i)); } vector_grad.push(k); } vec![gradient.clone(), Tensor::from_vec(Vec2...
conditional_block
clusters.py
# Copyright (c) 2014 eBay Software 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 # # Unl...
def get(self, cluster): """Get a specific cluster. :rtype: :class:`Cluster` """ return self._get("/clusters/%s" % base.getid(cluster), "cluster") def delete(self, cluster): """Delete the specified cluster. :param cluster: The cluster to...
return self._paginated("/clusters", "clusters", limit, marker)
random_line_split
clusters.py
# Copyright (c) 2014 eBay Software 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 # # Unl...
def delete(self, cluster): """Delete the specified cluster. :param cluster: The cluster to delete """ url = "/clusters/%s" % base.getid(cluster) resp, body = self.api.client.delete(url) common.check_for_exceptions(resp, body, url) def _action(self, cluster, bo...
"""Get a specific cluster. :rtype: :class:`Cluster` """ return self._get("/clusters/%s" % base.getid(cluster), "cluster")
identifier_body
clusters.py
# Copyright (c) 2014 eBay Software 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 # # Unl...
(self, cluster, body): """Perform a cluster "action" -- grow/shrink/etc.""" url = "/clusters/%s" % base.getid(cluster) resp, body = self.api.client.post(url, body=body) common.check_for_exceptions(resp, body, url) if body: return self.resource_class(self, body['cluste...
_action
identifier_name
clusters.py
# Copyright (c) 2014 eBay Software 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 # # Unl...
return self._create("/clusters", body, "cluster") def list(self, limit=None, marker=None): """Get a list of all clusters. :rtype: list of :class:`Cluster`. """ return self._paginated("/clusters", "clusters", limit, marker) def get(self, cluster): """Get a spe...
body["cluster"]["locality"] = locality
conditional_block
VisualizarTransportadoraView.py
# -*- coding: utf-8 -*- from PyQt4 import QtCore, QtGui try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError: def _fromUtf8(s): return s try: _encoding = QtGui.QApplication.UnicodeUTF8 def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text...
(self, VisualizarTransportadora): VisualizarTransportadora.setObjectName(_fromUtf8("VisualizarTransportadora")) VisualizarTransportadora.resize(403, 300) VisualizarTransportadora.move(550, 250) icon = QtGui.QIcon() icon.addPixmap(QtGui.QPixmap(_fromUtf8("../Icons/mdpi.png")), QtG...
setupUi
identifier_name
VisualizarTransportadoraView.py
from PyQt4 import QtCore, QtGui try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError: def _fromUtf8(s): return s try: _encoding = QtGui.QApplication.UnicodeUTF8 def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text, disambig, _encoding) e...
# -*- coding: utf-8 -*-
random_line_split
VisualizarTransportadoraView.py
# -*- coding: utf-8 -*- from PyQt4 import QtCore, QtGui try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError: def _fromUtf8(s): return s try: _encoding = QtGui.QApplication.UnicodeUTF8 def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text...
VisualizarTransportadora.setWindowTitle(_translate("VisualizarTransportadora", "Visualizar Transportadora", None)) self.tblTransportadora.setSortingEnabled(False) item = self.tblTransportadora.horizontalHeaderItem(0) item.setText(_translate("VisualizarTransportadora", "Id", None)) item =...
identifier_body
validator.js
/*! * Module dependencies. */ 'use strict'; const MongooseError = require('./'); /** * Schema validator error * * @param {Object} properties * @inherits MongooseError * @api private */ function ValidatorError(properties)
/*! * Inherits from MongooseError */ ValidatorError.prototype = Object.create(MongooseError.prototype); ValidatorError.prototype.constructor = MongooseError; /*! * The object used to define this validator. Not enumerable to hide * it from `require('util').inspect()` output re: gh-3925 */ Object.defineProperty...
{ let msg = properties.message; if (!msg) { msg = MongooseError.messages.general.default; } const message = this.formatMessage(msg, properties); MongooseError.call(this, message); properties = Object.assign({}, properties, { message: message }); this.name = 'ValidatorError'; if (Error.captureStack...
identifier_body
validator.js
/*! * Module dependencies. */ 'use strict'; const MongooseError = require('./'); /** * Schema validator error * * @param {Object} properties * @inherits MongooseError * @api private */ function
(properties) { let msg = properties.message; if (!msg) { msg = MongooseError.messages.general.default; } const message = this.formatMessage(msg, properties); MongooseError.call(this, message); properties = Object.assign({}, properties, { message: message }); this.name = 'ValidatorError'; if (Error...
ValidatorError
identifier_name
validator.js
/*! * Module dependencies. */ 'use strict'; const MongooseError = require('./'); /** * Schema validator error * * @param {Object} properties * @inherits MongooseError * @api private */ function ValidatorError(properties) { let msg = properties.message; if (!msg) { msg = MongooseError.messages.genera...
if (Error.captureStackTrace) { Error.captureStackTrace(this); } else { this.stack = new Error().stack; } this.properties = properties; this.kind = properties.type; this.path = properties.path; this.value = properties.value; this.reason = properties.reason; } /*! * Inherits from MongooseError ...
properties = Object.assign({}, properties, { message: message }); this.name = 'ValidatorError';
random_line_split
validator.js
/*! * Module dependencies. */ 'use strict'; const MongooseError = require('./'); /** * Schema validator error * * @param {Object} properties * @inherits MongooseError * @api private */ function ValidatorError(properties) { let msg = properties.message; if (!msg) { msg = MongooseError.messages.genera...
msg = msg.replace('{' + propertyName.toUpperCase() + '}', properties[propertyName]); } return msg; }; /*! * toString helper */ ValidatorError.prototype.toString = function() { return this.message; }; /*! * exports */ module.exports = ValidatorError;
{ continue; }
conditional_block
options.ts
import { SendMailOptions, SentMessageInfo, Transport } from 'nodemailer'; import { Request } from 'express'; import { IUser } from './user'; import { CRUD } from './crud'; // import { PolicyStore } from '../authorize/policy-store'; import { IPolicyStore } from '../authorize/policy-store'; export interface INodeAuthOpt...
verifyMailOptions: { from: 'Do Not Reply <user@gmail.com>', subject: 'Confirm your account', html: '<p>Please verify your account by clicking <a href="${URL}">this link</a>. If you are unable to do so, copy and ' + 'paste the following link into your browser:</p><...
/** Nodemailer transport for sending emails. Please use ${URL} as a placeholder for the verification URL. */ mailService: Transport; /**
random_line_split
index.js
var nwmatcher = require("nwmatcher"); function addNwmatcher(document) { if (!document._nwmatcher)
return document._nwmatcher; } exports.applyQuerySelector = function(doc, dom) { doc.querySelector = function(selector) { return addNwmatcher(this).first(selector, this); }; doc.querySelectorAll = function(selector) { return new dom.NodeList(addNwmatcher(this).select(selector, this)); }; var _cre...
{ document._nwmatcher = nwmatcher({ document: document }); }
conditional_block
index.js
var nwmatcher = require("nwmatcher"); function
(document) { if (!document._nwmatcher) { document._nwmatcher = nwmatcher({ document: document }); } return document._nwmatcher; } exports.applyQuerySelector = function(doc, dom) { doc.querySelector = function(selector) { return addNwmatcher(this).first(selector, this); }; doc.querySelectorAll = fu...
addNwmatcher
identifier_name
index.js
var nwmatcher = require("nwmatcher"); function addNwmatcher(document) { if (!document._nwmatcher) { document._nwmatcher = nwmatcher({ document: document }); } return document._nwmatcher; } exports.applyQuerySelector = function(doc, dom) { doc.querySelector = function(selector) { return addNwmatcher(th...
doc.createElement = function() { var element = _createElement.apply(this, arguments); element.querySelector = function(selector) { return addNwmatcher(this.ownerDocument).first(selector, this); }; element.querySelectorAll = function(selector) { return new dom.NodeList(addNwma...
var _createElement = doc.createElement;
random_line_split
index.js
var nwmatcher = require("nwmatcher"); function addNwmatcher(document)
exports.applyQuerySelector = function(doc, dom) { doc.querySelector = function(selector) { return addNwmatcher(this).first(selector, this); }; doc.querySelectorAll = function(selector) { return new dom.NodeList(addNwmatcher(this).select(selector, this)); }; var _createElement = doc.createElement; ...
{ if (!document._nwmatcher) { document._nwmatcher = nwmatcher({ document: document }); } return document._nwmatcher; }
identifier_body
sw_vers.rs
/* * Mac OS X related checks */ use std::process::Command; use regex::Regex; pub struct SwVers { pub product_name: Option<String>, pub product_version: Option<String>, pub build_version: Option<String> } fn extract_from_regex(stdout: &String, regex: Regex) -> Option<String> { match regex.captures_it...
Some(parse(stdout.to_string())) } pub fn parse(version_str: String) -> SwVers { let product_name_regex = Regex::new(r"ProductName:\s([\w\s]+)\n").unwrap(); let product_version_regex = Regex::new(r"ProductVersion:\s(\w+\.\w+\.\w+)").unwrap(); let build_number_regex = Regex::new(r"BuildVersion:\s(\w+)")....
Err(_) => return None }; let stdout = String::from_utf8_lossy(&output.stdout);
random_line_split
sw_vers.rs
/* * Mac OS X related checks */ use std::process::Command; use regex::Regex; pub struct SwVers { pub product_name: Option<String>, pub product_version: Option<String>, pub build_version: Option<String> } fn extract_from_regex(stdout: &String, regex: Regex) -> Option<String> { match regex.captures_it...
pub fn parse(version_str: String) -> SwVers { let product_name_regex = Regex::new(r"ProductName:\s([\w\s]+)\n").unwrap(); let product_version_regex = Regex::new(r"ProductVersion:\s(\w+\.\w+\.\w+)").unwrap(); let build_number_regex = Regex::new(r"BuildVersion:\s(\w+)").unwrap(); SwVers { produ...
{ let output = match Command::new("sw_vers").output() { Ok(output) => output, Err(_) => return None }; let stdout = String::from_utf8_lossy(&output.stdout); Some(parse(stdout.to_string())) }
identifier_body
sw_vers.rs
/* * Mac OS X related checks */ use std::process::Command; use regex::Regex; pub struct SwVers { pub product_name: Option<String>, pub product_version: Option<String>, pub build_version: Option<String> } fn
(stdout: &String, regex: Regex) -> Option<String> { match regex.captures_iter(&stdout).next() { Some(m) => { match m.get(1) { Some(s) => { Some(s.as_str().to_owned()) }, None => None } }, None => None...
extract_from_regex
identifier_name
lib.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ #![allow(non_camel_case_types)] use std::cell::RefCell; use cpython::*; use ::bookmarkstore::BookmarkStore; use cpython_ext::{PyNone, PyPa...
py_class!(class bookmarkstore |py| { data bm_store: RefCell<BookmarkStore>; def __new__(_cls, path: &PyPath) -> PyResult<bookmarkstore> { let bm_store = { BookmarkStore::new(path.as_path()) .map_err(|e| PyErr::new::<exc::IOError, _>(py, format!("{}", e)))? }; ...
{ let name = [package, "bookmarkstore"].join("."); let m = PyModule::new(py, &name)?; m.add_class::<bookmarkstore>(py)?; Ok(m) }
identifier_body
lib.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ #![allow(non_camel_case_types)] use std::cell::RefCell; use cpython::*; use ::bookmarkstore::BookmarkStore; use cpython_ext::{PyNone, PyPa...
def update(&self, bookmark: &str, node: PyBytes) -> PyResult<PyNone> { let mut bm_store = self.bm_store(py).borrow_mut(); let hgid = HgId::from_slice(node.data(py)) .map_err(|e| PyErr::new::<exc::ValueError, _>(py, format!("{}", e)))?; bm_store.update(bookmark, hgid) ...
BookmarkStore::new(path.as_path()) .map_err(|e| PyErr::new::<exc::IOError, _>(py, format!("{}", e)))? }; bookmarkstore::create_instance(py, RefCell::new(bm_store)) }
random_line_split
lib.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ #![allow(non_camel_case_types)] use std::cell::RefCell; use cpython::*; use ::bookmarkstore::BookmarkStore; use cpython_ext::{PyNone, PyPa...
(py: Python, package: &str) -> PyResult<PyModule> { let name = [package, "bookmarkstore"].join("."); let m = PyModule::new(py, &name)?; m.add_class::<bookmarkstore>(py)?; Ok(m) } py_class!(class bookmarkstore |py| { data bm_store: RefCell<BookmarkStore>; def __new__(_cls, path: &PyPath) -> PyR...
init_module
identifier_name
select2_locale_it-e45548dc93d14ad49b80a69023ecfd28.js
/** * Select2 Italian translation */ (function ($) { "use strict"; $.extend($.fn.select2.defaults, { formatNoMatches: function () { return "Nessuna corrispondenza trovata"; }, formatInputTooShort: function (input, min) { var n = min - input.length; return "Inserisci ancora " + n + " caratter...
formatLoadMore: function (pageNumber) { return "Caricamento in corso..."; }, formatSearching: function () { return "Ricerca..."; } }); })(jQuery);
random_line_split
aiplatform_v1beta1_generated_endpoint_service_deploy_model_async.py
# -*- coding: utf-8 -*- # Copyright 2022 Google LLC # # 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...
(): # Create a client client = aiplatform_v1beta1.EndpointServiceAsyncClient() # Initialize request argument(s) deployed_model = aiplatform_v1beta1.DeployedModel() deployed_model.dedicated_resources.min_replica_count = 1803 deployed_model.model = "model_value" request = aiplatform_v1beta1....
sample_deploy_model
identifier_name
aiplatform_v1beta1_generated_endpoint_service_deploy_model_async.py
# -*- coding: utf-8 -*- # Copyright 2022 Google LLC # # 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...
# [END aiplatform_v1beta1_generated_EndpointService_DeployModel_async]
client = aiplatform_v1beta1.EndpointServiceAsyncClient() # Initialize request argument(s) deployed_model = aiplatform_v1beta1.DeployedModel() deployed_model.dedicated_resources.min_replica_count = 1803 deployed_model.model = "model_value" request = aiplatform_v1beta1.DeployModelRequest( en...
identifier_body
aiplatform_v1beta1_generated_endpoint_service_deploy_model_async.py
# -*- coding: utf-8 -*- # Copyright 2022 Google LLC # # 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...
operation = client.deploy_model(request=request) print("Waiting for operation to complete...") response = await operation.result() # Handle the response print(response) # [END aiplatform_v1beta1_generated_EndpointService_DeployModel_async]
endpoint="endpoint_value", deployed_model=deployed_model, ) # Make the request
random_line_split
test_rng.rs
extern crate cryptopals; extern crate rand; extern crate time; use cryptopals::crypto::rng::{MT, untemper}; use rand::{Rng, SeedableRng, thread_rng};
#[test] fn test_rng_deterministic() { let mut m1: MT = SeedableRng::from_seed(314159); let mut m2: MT = SeedableRng::from_seed(314159); for _ in 0 .. 1024 { assert_eq!(m1.gen::<u32>(), m2.gen::<u32>()); } } #[test] fn test_seed_recovery_from_time() { let mut time = get_time().sec; time ...
use time::{get_time};
random_line_split