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 interationCount = 0;
/**
* Generates a color from the specified name
* @param name String value used to generate a color
* @return RGB color in the form of #RRGGBB
*/
export function generateColor(name: string): string {
|
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 || "").length; i++) {
value += id.charCodeAt(i) * (i + 1);
}
return "#" + allColors[value % allColors.length];
}
| 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 interationCount = 0;
/**
* Generates a color from the specified name
* @param name String value used to generate a color
* @return RGB color in the form of #RRGGBB
*/
export function generateColor(name: string): string {
if (name === "currentIteration") {
return currentIterationColor;
}
if (name === "otherIteration") {
|
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 interationCount = 0;
/**
* Generates a color from the specified name
* @param name String value used to generate a color
* @return RGB color in the form of #RRGGBB
*/
export function generateColor(name: string): string {
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 || "").length; i++) {
value += id.charCodeAt(i) * (i + 1);
}
return "#" + allColors[value % allColors.length];
} | 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.unloading = true;
}
$scope.loadProgress = function(key,per){
$scope.$broadcast("pie",per);
}
$scope.loadComplete = function(data){
restAPI.getImageUrl.get({key:data.key},function(res){
data.url = res.url;
$scope.unloading = false;
$scope.imgList.push(data);
});
}
$scope.deleteList = function(key){
angular.forEach($scope.imgList,function(item,index){
if (item.key==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){
$scope.unloading = true;
}
$scope.loadProgress = function(key,per){
$scope.$broadcast("pie",per);
}
$scope.loadComplete = function(data){
restAPI.getImageUrl.get({key:data.key},function(res){
data.url = res.url;
$scope.unloading = false;
$scope.imgList.push(data);
});
}
$scope.deleteList = function(key){
angular.forEach($scope.imgList,function(item,index){
if (item.key==key) {
$scope.imgList = | 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.picklable_threading import RLock
logger = logging.getLogger(__name__)
CacheKey = TypeVar('CacheKey')
CacheReturn = TypeVar('CacheReturn')
CacheFunc = TypeVar('CacheFunc', bound=Callable[..., Any])
class Cache:
@classmethod
def decor(
cls,
obj_store: Callable[[str], ObjectStore[CacheKey, CacheReturn]],
hit_msg: bool = False, miss_msg: bool = False, suffix: str = '',
) -> Callable[[CacheFunc], CacheFunc]:
'''Decorator that creates a cached function
>>> @Cache.decor(ObjectStore())
>>> def foo():
... pass
'''
def decor_(function: CacheFunc) -> CacheFunc:
return cast(
CacheFunc,
functools.wraps(function)(
cls(obj_store, function, hit_msg, miss_msg, suffix)
)
)
return decor_
disabled: bool
#pylint: disable=too-many-arguments
def __init__(
self,
obj_store: Callable[[str], ObjectStore[CacheKey, CacheReturn]],
function: CacheFunc,
hit_msg: bool = False, miss_msg: bool = False, suffix: str = ''
) -> None:
'''Cache a function.
Note this uses `function.__qualname__` to determine the file
name. If this is not unique within your program, define
suffix.
Note this uses `function.version` when defined, so objects of
the same functions of different versions will not collide.
'''
self.function = function
self.name = '-'.join(filter(bool, [
self.function.__qualname__,
suffix,
getattr(self.function, 'version', ''),
]))
self.obj_store = obj_store(self.name)
self.hit_msg = hit_msg
self.miss_msg = miss_msg
self.sem = RLock()
self.__qualname__ = f'Cache({self.name})'
self.disabled = False
def __call__(self, *pos_args: Any, **kwargs: Any) -> Any:
if self.disabled:
return self.function(*pos_args, **kwargs)
else:
with self.sem:
args_key = self.obj_store.args2key(pos_args, kwargs)
if args_key in self.obj_store:
if self.hit_msg:
logger.info('hit %s with %s, %s',
self.name, pos_args, kwargs)
res = self.obj_store[args_key]
else:
if self.miss_msg:
logger.info('miss %s with %s, %s',
self.name, pos_args, kwargs)
res = self.function(*pos_args, **kwargs)
self.obj_store[args_key] = res
return res
def clear(self) -> None:
'''Removes all cached items'''
self.obj_store.clear()
def __str__(self) -> str:
store_type = type(self.obj_store).__name__
return f'Cache of {self.name} with {store_type}'
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]]:
'''Curried init. Name will be applied later.'''
@functools.wraps(cls)
def create_(name: str) -> ObjectStore[ObjectStoreKey, ObjectStoreValue]:
return cls(*args, name=name, **kwargs) # type: ignore
return create_
def __init__(self, name: str) -> None:
super().__init__()
self.name = name
@abc.abstractmethod
def args2key(self, args: Tuple[Any, ...], kwargs: Dict[str, Any]) -> ObjectStoreKey:
# pylint: disable=unused-argument,no-self-use
...
class MemoryStore(ObjectStore[Hashable, Any]):
def __init__(self, name: str):
# pylint: disable=non-parent-init-called
ObjectStore.__init__(self, name)
def args2key(self, args: Tuple[Any, ...], kwargs: Dict[str, Any]) -> Hashable:
# pylint: disable=no-self-use
return to_hashable((args, kwargs))
class FileStore(MemoryStore):
'''An obj_store that persists at ./${CACHE_PATH}/${FUNCTION_NAME}_cache.pickle'''
def __init__(
self, cache_path: PathLike, name: str, serializer: Optional[Serializer] = None,
):
# pylint: disable=non-parent-init-called,super-init-not-called
ObjectStore.__init__(self, name)
if serializer is None:
import pickle
self.serializer = cast(Serializer, pickle)
else:
self.serializer = serializer
self.cache_path = pathify(cache_path) / (self.name + '_cache.pickle')
self.loaded = False
self.data = {}
def load_if_not_loaded(self) -> None:
if not self.loaded:
self.loaded = True
if self.cache_path.exists():
with self.cache_path.open('rb') as fil:
self.data = self.serializer.load(fil)
else:
self.cache_path.parent.mkdir(parents=True, exist_ok=True)
self.data = {}
def args2key(self, args: Tuple[Any, ...], kwargs: Dict[str, Any]) -> Hashable:
# pylint: disable=no-self-use
return to_hashable((args, kwargs))
def commit(self) -> None:
self.load_if_not_loaded()
if self.data:
with self.cache_path.open('wb') as fil:
self.serializer.dump(self.data, fil)
else:
if self.cache_path.exists():
print('deleting ', self.cache_path)
self.cache_path.unlink()
def __setitem__(self, key: Hashable, obj: Any) -> None:
self.load_if_not_loaded()
super().__setitem__(key, obj)
self.commit()
def __delitem__(self, key: Hashable) -> None:
self.load_if_not_loaded()
super().__delitem__(key)
self.commit()
def clear(self) -> None:
self.load_if_not_loaded()
super().clear()
self.commit()
class DirectoryStore(ObjectStore[PathLike, Any]):
'''Stores objects at ./${CACHE_PATH}/${FUNCTION_NAME}/${urlencode(args)}.pickle'''
def | (
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, pickle)
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', safe='')
return self.cache_path / fname
def __setitem__(self, path: PathLike, obj: Any) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
with path.open('wb') as fil:
self.serializer.dump(obj, fil)
def __delitem__(self, path: PathLike) -> None:
path.unlink()
def __getitem__(self, path: PathLike) -> Any:
with path.open('rb') as fil:
return self.serializer.load(fil)
def __contains__(self, path: Any) -> bool:
if hasattr(path, 'exists'):
return bool(path.exists())
else:
return False
def clear(self) -> None:
print('deleting')
if hasattr(self.cache_path, 'rmtree'):
cast(Any, self.cache_path).rmtree()
else:
shutil.rmtree(str(self.cache_path))
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 to equal things
# sorted(..., key=hash)
return tuple(sorted(
[(keyf, to_hashable(val)) for keyf, val in obj.items()],
key=hash
))
elif hasattr(obj, '__iter__'):
# turn iterables into tuples
return tuple(to_hashable(val) for val in obj)
else:
raise TypeError(f"I don't know how to hash {obj} ({type(obj)})")
else:
return cast(Hashable, obj)
def safe_str(obj: Any) -> str:
'''
Safe names are compact, unique, urlsafe, and equal when the objects are equal
str does not work because x == y does not imply str(x) == str(y).
>>> a = dict(d=1, e=1)
>>> b = dict(e=1, d=1)
>>> a == b
True
>>> str(a) == str(b)
False
>>> safe_str(a) == safe_str(b)
True
'''
if isinstance(obj, int):
ret = str(obj)
elif isinstance(obj, float):
ret = str(round(obj, 3))
elif isinstance(obj, str):
ret = repr(obj)
elif isinstance(obj, list):
ret = '[' + ','.join(map(safe_str, obj)) + ']'
elif isinstance(obj, tuple):
ret = '(' + ','.join(map(safe_str, obj)) + ')'
elif isinstance(obj, dict):
ret = '{' + ','.join(sorted(
safe_str(key) + ':' + safe_str(val)
for key, val in obj.items()
)) + '}'
else:
raise TypeError()
return urllib.parse.quote(ret, safe='')
def pathify(obj: Union[str, PathLike]) -> PathLike:
if isinstance(obj, str):
return Path(obj)
else:
return obj
| __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.picklable_threading import RLock
logger = logging.getLogger(__name__)
CacheKey = TypeVar('CacheKey')
CacheReturn = TypeVar('CacheReturn')
CacheFunc = TypeVar('CacheFunc', bound=Callable[..., Any])
class Cache:
@classmethod
def decor(
cls,
obj_store: Callable[[str], ObjectStore[CacheKey, CacheReturn]],
hit_msg: bool = False, miss_msg: bool = False, suffix: str = '',
) -> Callable[[CacheFunc], CacheFunc]:
'''Decorator that creates a cached function
>>> @Cache.decor(ObjectStore())
>>> def foo():
... pass
'''
def decor_(function: CacheFunc) -> CacheFunc:
return cast(
CacheFunc,
functools.wraps(function)(
cls(obj_store, function, hit_msg, miss_msg, suffix)
)
)
return decor_
disabled: bool
#pylint: disable=too-many-arguments
def __init__(
self,
obj_store: Callable[[str], ObjectStore[CacheKey, CacheReturn]],
function: CacheFunc,
hit_msg: bool = False, miss_msg: bool = False, suffix: str = ''
) -> None:
'''Cache a function.
Note this uses `function.__qualname__` to determine the file
name. If this is not unique within your program, define
suffix.
Note this uses `function.version` when defined, so objects of
the same functions of different versions will not collide.
'''
self.function = function
self.name = '-'.join(filter(bool, [
self.function.__qualname__,
suffix,
getattr(self.function, 'version', ''),
]))
self.obj_store = obj_store(self.name)
self.hit_msg = hit_msg
self.miss_msg = miss_msg
self.sem = RLock()
self.__qualname__ = f'Cache({self.name})'
self.disabled = False
def __call__(self, *pos_args: Any, **kwargs: Any) -> Any:
if self.disabled:
return self.function(*pos_args, **kwargs)
else:
with self.sem:
args_key = self.obj_store.args2key(pos_args, kwargs)
if args_key in self.obj_store:
if self.hit_msg:
logger.info('hit %s with %s, %s',
self.name, pos_args, kwargs)
res = self.obj_store[args_key]
else:
if self.miss_msg:
logger.info('miss %s with %s, %s',
self.name, pos_args, kwargs)
res = self.function(*pos_args, **kwargs)
self.obj_store[args_key] = res
return res
def clear(self) -> None:
'''Removes all cached items'''
self.obj_store.clear()
|
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]]:
'''Curried init. Name will be applied later.'''
@functools.wraps(cls)
def create_(name: str) -> ObjectStore[ObjectStoreKey, ObjectStoreValue]:
return cls(*args, name=name, **kwargs) # type: ignore
return create_
def __init__(self, name: str) -> None:
super().__init__()
self.name = name
@abc.abstractmethod
def args2key(self, args: Tuple[Any, ...], kwargs: Dict[str, Any]) -> ObjectStoreKey:
# pylint: disable=unused-argument,no-self-use
...
class MemoryStore(ObjectStore[Hashable, Any]):
def __init__(self, name: str):
# pylint: disable=non-parent-init-called
ObjectStore.__init__(self, name)
def args2key(self, args: Tuple[Any, ...], kwargs: Dict[str, Any]) -> Hashable:
# pylint: disable=no-self-use
return to_hashable((args, kwargs))
class FileStore(MemoryStore):
'''An obj_store that persists at ./${CACHE_PATH}/${FUNCTION_NAME}_cache.pickle'''
def __init__(
self, cache_path: PathLike, name: str, serializer: Optional[Serializer] = None,
):
# pylint: disable=non-parent-init-called,super-init-not-called
ObjectStore.__init__(self, name)
if serializer is None:
import pickle
self.serializer = cast(Serializer, pickle)
else:
self.serializer = serializer
self.cache_path = pathify(cache_path) / (self.name + '_cache.pickle')
self.loaded = False
self.data = {}
def load_if_not_loaded(self) -> None:
if not self.loaded:
self.loaded = True
if self.cache_path.exists():
with self.cache_path.open('rb') as fil:
self.data = self.serializer.load(fil)
else:
self.cache_path.parent.mkdir(parents=True, exist_ok=True)
self.data = {}
def args2key(self, args: Tuple[Any, ...], kwargs: Dict[str, Any]) -> Hashable:
# pylint: disable=no-self-use
return to_hashable((args, kwargs))
def commit(self) -> None:
self.load_if_not_loaded()
if self.data:
with self.cache_path.open('wb') as fil:
self.serializer.dump(self.data, fil)
else:
if self.cache_path.exists():
print('deleting ', self.cache_path)
self.cache_path.unlink()
def __setitem__(self, key: Hashable, obj: Any) -> None:
self.load_if_not_loaded()
super().__setitem__(key, obj)
self.commit()
def __delitem__(self, key: Hashable) -> None:
self.load_if_not_loaded()
super().__delitem__(key)
self.commit()
def clear(self) -> None:
self.load_if_not_loaded()
super().clear()
self.commit()
class DirectoryStore(ObjectStore[PathLike, Any]):
'''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)
if serializer is None:
import pickle
self.serializer = cast(Serializer, pickle)
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', safe='')
return self.cache_path / fname
def __setitem__(self, path: PathLike, obj: Any) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
with path.open('wb') as fil:
self.serializer.dump(obj, fil)
def __delitem__(self, path: PathLike) -> None:
path.unlink()
def __getitem__(self, path: PathLike) -> Any:
with path.open('rb') as fil:
return self.serializer.load(fil)
def __contains__(self, path: Any) -> bool:
if hasattr(path, 'exists'):
return bool(path.exists())
else:
return False
def clear(self) -> None:
print('deleting')
if hasattr(self.cache_path, 'rmtree'):
cast(Any, self.cache_path).rmtree()
else:
shutil.rmtree(str(self.cache_path))
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 to equal things
# sorted(..., key=hash)
return tuple(sorted(
[(keyf, to_hashable(val)) for keyf, val in obj.items()],
key=hash
))
elif hasattr(obj, '__iter__'):
# turn iterables into tuples
return tuple(to_hashable(val) for val in obj)
else:
raise TypeError(f"I don't know how to hash {obj} ({type(obj)})")
else:
return cast(Hashable, obj)
def safe_str(obj: Any) -> str:
'''
Safe names are compact, unique, urlsafe, and equal when the objects are equal
str does not work because x == y does not imply str(x) == str(y).
>>> a = dict(d=1, e=1)
>>> b = dict(e=1, d=1)
>>> a == b
True
>>> str(a) == str(b)
False
>>> safe_str(a) == safe_str(b)
True
'''
if isinstance(obj, int):
ret = str(obj)
elif isinstance(obj, float):
ret = str(round(obj, 3))
elif isinstance(obj, str):
ret = repr(obj)
elif isinstance(obj, list):
ret = '[' + ','.join(map(safe_str, obj)) + ']'
elif isinstance(obj, tuple):
ret = '(' + ','.join(map(safe_str, obj)) + ')'
elif isinstance(obj, dict):
ret = '{' + ','.join(sorted(
safe_str(key) + ':' + safe_str(val)
for key, val in obj.items()
)) + '}'
else:
raise TypeError()
return urllib.parse.quote(ret, safe='')
def pathify(obj: Union[str, PathLike]) -> PathLike:
if isinstance(obj, str):
return Path(obj)
else:
return obj | 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.picklable_threading import RLock
logger = logging.getLogger(__name__)
CacheKey = TypeVar('CacheKey')
CacheReturn = TypeVar('CacheReturn')
CacheFunc = TypeVar('CacheFunc', bound=Callable[..., Any])
class Cache:
@classmethod
def decor(
cls,
obj_store: Callable[[str], ObjectStore[CacheKey, CacheReturn]],
hit_msg: bool = False, miss_msg: bool = False, suffix: str = '',
) -> Callable[[CacheFunc], CacheFunc]:
'''Decorator that creates a cached function
>>> @Cache.decor(ObjectStore())
>>> def foo():
... pass
'''
def decor_(function: CacheFunc) -> CacheFunc:
return cast(
CacheFunc,
functools.wraps(function)(
cls(obj_store, function, hit_msg, miss_msg, suffix)
)
)
return decor_
disabled: bool
#pylint: disable=too-many-arguments
def __init__(
self,
obj_store: Callable[[str], ObjectStore[CacheKey, CacheReturn]],
function: CacheFunc,
hit_msg: bool = False, miss_msg: bool = False, suffix: str = ''
) -> None:
'''Cache a function.
Note this uses `function.__qualname__` to determine the file
name. If this is not unique within your program, define
suffix.
Note this uses `function.version` when defined, so objects of
the same functions of different versions will not collide.
'''
self.function = function
self.name = '-'.join(filter(bool, [
self.function.__qualname__,
suffix,
getattr(self.function, 'version', ''),
]))
self.obj_store = obj_store(self.name)
self.hit_msg = hit_msg
self.miss_msg = miss_msg
self.sem = RLock()
self.__qualname__ = f'Cache({self.name})'
self.disabled = False
def __call__(self, *pos_args: Any, **kwargs: Any) -> Any:
if self.disabled:
return self.function(*pos_args, **kwargs)
else:
with self.sem:
args_key = self.obj_store.args2key(pos_args, kwargs)
if args_key in self.obj_store:
if self.hit_msg:
logger.info('hit %s with %s, %s',
self.name, pos_args, kwargs)
res = self.obj_store[args_key]
else:
if self.miss_msg:
logger.info('miss %s with %s, %s',
self.name, pos_args, kwargs)
res = self.function(*pos_args, **kwargs)
self.obj_store[args_key] = res
return res
def clear(self) -> None:
'''Removes all cached items'''
self.obj_store.clear()
def __str__(self) -> str:
store_type = type(self.obj_store).__name__
return f'Cache of {self.name} with {store_type}'
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]]:
'''Curried init. Name will be applied later.'''
@functools.wraps(cls)
def create_(name: str) -> ObjectStore[ObjectStoreKey, ObjectStoreValue]:
return cls(*args, name=name, **kwargs) # type: ignore
return create_
def __init__(self, name: str) -> None:
super().__init__()
self.name = name
@abc.abstractmethod
def args2key(self, args: Tuple[Any, ...], kwargs: Dict[str, Any]) -> ObjectStoreKey:
# pylint: disable=unused-argument,no-self-use
...
class MemoryStore(ObjectStore[Hashable, Any]):
def __init__(self, name: str):
# pylint: disable=non-parent-init-called
ObjectStore.__init__(self, name)
def args2key(self, args: Tuple[Any, ...], kwargs: Dict[str, Any]) -> Hashable:
# pylint: disable=no-self-use
return to_hashable((args, kwargs))
class FileStore(MemoryStore):
'''An obj_store that persists at ./${CACHE_PATH}/${FUNCTION_NAME}_cache.pickle'''
def __init__(
self, cache_path: PathLike, name: str, serializer: Optional[Serializer] = None,
):
# pylint: disable=non-parent-init-called,super-init-not-called
ObjectStore.__init__(self, name)
if serializer is None:
import pickle
self.serializer = cast(Serializer, pickle)
else:
self.serializer = serializer
self.cache_path = pathify(cache_path) / (self.name + '_cache.pickle')
self.loaded = False
self.data = {}
def load_if_not_loaded(self) -> None:
if not self.loaded:
self.loaded = True
if self.cache_path.exists():
with self.cache_path.open('rb') as fil:
self.data = self.serializer.load(fil)
else:
self.cache_path.parent.mkdir(parents=True, exist_ok=True)
self.data = {}
def args2key(self, args: Tuple[Any, ...], kwargs: Dict[str, Any]) -> Hashable:
# pylint: disable=no-self-use
return to_hashable((args, kwargs))
def commit(self) -> None:
self.load_if_not_loaded()
if self.data:
with self.cache_path.open('wb') as fil:
self.serializer.dump(self.data, fil)
else:
if self.cache_path.exists():
print('deleting ', self.cache_path)
self.cache_path.unlink()
def __setitem__(self, key: Hashable, obj: Any) -> None:
self.load_if_not_loaded()
super().__setitem__(key, obj)
self.commit()
def __delitem__(self, key: Hashable) -> None:
self.load_if_not_loaded()
super().__delitem__(key)
self.commit()
def clear(self) -> None:
self.load_if_not_loaded()
super().clear()
self.commit()
class DirectoryStore(ObjectStore[PathLike, Any]):
'''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)
if serializer is None:
|
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', safe='')
return self.cache_path / fname
def __setitem__(self, path: PathLike, obj: Any) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
with path.open('wb') as fil:
self.serializer.dump(obj, fil)
def __delitem__(self, path: PathLike) -> None:
path.unlink()
def __getitem__(self, path: PathLike) -> Any:
with path.open('rb') as fil:
return self.serializer.load(fil)
def __contains__(self, path: Any) -> bool:
if hasattr(path, 'exists'):
return bool(path.exists())
else:
return False
def clear(self) -> None:
print('deleting')
if hasattr(self.cache_path, 'rmtree'):
cast(Any, self.cache_path).rmtree()
else:
shutil.rmtree(str(self.cache_path))
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 to equal things
# sorted(..., key=hash)
return tuple(sorted(
[(keyf, to_hashable(val)) for keyf, val in obj.items()],
key=hash
))
elif hasattr(obj, '__iter__'):
# turn iterables into tuples
return tuple(to_hashable(val) for val in obj)
else:
raise TypeError(f"I don't know how to hash {obj} ({type(obj)})")
else:
return cast(Hashable, obj)
def safe_str(obj: Any) -> str:
'''
Safe names are compact, unique, urlsafe, and equal when the objects are equal
str does not work because x == y does not imply str(x) == str(y).
>>> a = dict(d=1, e=1)
>>> b = dict(e=1, d=1)
>>> a == b
True
>>> str(a) == str(b)
False
>>> safe_str(a) == safe_str(b)
True
'''
if isinstance(obj, int):
ret = str(obj)
elif isinstance(obj, float):
ret = str(round(obj, 3))
elif isinstance(obj, str):
ret = repr(obj)
elif isinstance(obj, list):
ret = '[' + ','.join(map(safe_str, obj)) + ']'
elif isinstance(obj, tuple):
ret = '(' + ','.join(map(safe_str, obj)) + ')'
elif isinstance(obj, dict):
ret = '{' + ','.join(sorted(
safe_str(key) + ':' + safe_str(val)
for key, val in obj.items()
)) + '}'
else:
raise TypeError()
return urllib.parse.quote(ret, safe='')
def pathify(obj: Union[str, PathLike]) -> PathLike:
if isinstance(obj, str):
return Path(obj)
else:
return obj
| 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.picklable_threading import RLock
logger = logging.getLogger(__name__)
CacheKey = TypeVar('CacheKey')
CacheReturn = TypeVar('CacheReturn')
CacheFunc = TypeVar('CacheFunc', bound=Callable[..., Any])
class Cache:
@classmethod
def decor(
cls,
obj_store: Callable[[str], ObjectStore[CacheKey, CacheReturn]],
hit_msg: bool = False, miss_msg: bool = False, suffix: str = '',
) -> Callable[[CacheFunc], CacheFunc]:
'''Decorator that creates a cached function
>>> @Cache.decor(ObjectStore())
>>> def foo():
... pass
'''
def decor_(function: CacheFunc) -> CacheFunc:
return cast(
CacheFunc,
functools.wraps(function)(
cls(obj_store, function, hit_msg, miss_msg, suffix)
)
)
return decor_
disabled: bool
#pylint: disable=too-many-arguments
def __init__(
self,
obj_store: Callable[[str], ObjectStore[CacheKey, CacheReturn]],
function: CacheFunc,
hit_msg: bool = False, miss_msg: bool = False, suffix: str = ''
) -> None:
'''Cache a function.
Note this uses `function.__qualname__` to determine the file
name. If this is not unique within your program, define
suffix.
Note this uses `function.version` when defined, so objects of
the same functions of different versions will not collide.
'''
self.function = function
self.name = '-'.join(filter(bool, [
self.function.__qualname__,
suffix,
getattr(self.function, 'version', ''),
]))
self.obj_store = obj_store(self.name)
self.hit_msg = hit_msg
self.miss_msg = miss_msg
self.sem = RLock()
self.__qualname__ = f'Cache({self.name})'
self.disabled = False
def __call__(self, *pos_args: Any, **kwargs: Any) -> Any:
if self.disabled:
return self.function(*pos_args, **kwargs)
else:
with self.sem:
args_key = self.obj_store.args2key(pos_args, kwargs)
if args_key in self.obj_store:
if self.hit_msg:
logger.info('hit %s with %s, %s',
self.name, pos_args, kwargs)
res = self.obj_store[args_key]
else:
if self.miss_msg:
logger.info('miss %s with %s, %s',
self.name, pos_args, kwargs)
res = self.function(*pos_args, **kwargs)
self.obj_store[args_key] = res
return res
def clear(self) -> None:
'''Removes all cached items'''
self.obj_store.clear()
def __str__(self) -> str:
store_type = type(self.obj_store).__name__
return f'Cache of {self.name} with {store_type}'
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]]:
'''Curried init. Name will be applied later.'''
@functools.wraps(cls)
def create_(name: str) -> ObjectStore[ObjectStoreKey, ObjectStoreValue]:
return cls(*args, name=name, **kwargs) # type: ignore
return create_
def __init__(self, name: str) -> None:
super().__init__()
self.name = name
@abc.abstractmethod
def args2key(self, args: Tuple[Any, ...], kwargs: Dict[str, Any]) -> ObjectStoreKey:
# pylint: disable=unused-argument,no-self-use
...
class MemoryStore(ObjectStore[Hashable, Any]):
def __init__(self, name: str):
# pylint: disable=non-parent-init-called
ObjectStore.__init__(self, name)
def args2key(self, args: Tuple[Any, ...], kwargs: Dict[str, Any]) -> Hashable:
# pylint: disable=no-self-use
return to_hashable((args, kwargs))
class FileStore(MemoryStore):
'''An obj_store that persists at ./${CACHE_PATH}/${FUNCTION_NAME}_cache.pickle'''
def __init__(
self, cache_path: PathLike, name: str, serializer: Optional[Serializer] = None,
):
# pylint: disable=non-parent-init-called,super-init-not-called
ObjectStore.__init__(self, name)
if serializer is None:
import pickle
self.serializer = cast(Serializer, pickle)
else:
self.serializer = serializer
self.cache_path = pathify(cache_path) / (self.name + '_cache.pickle')
self.loaded = False
self.data = {}
def load_if_not_loaded(self) -> None:
if not self.loaded:
self.loaded = True
if self.cache_path.exists():
with self.cache_path.open('rb') as fil:
self.data = self.serializer.load(fil)
else:
self.cache_path.parent.mkdir(parents=True, exist_ok=True)
self.data = {}
def args2key(self, args: Tuple[Any, ...], kwargs: Dict[str, Any]) -> Hashable:
# pylint: disable=no-self-use
return to_hashable((args, kwargs))
def commit(self) -> None:
self.load_if_not_loaded()
if self.data:
with self.cache_path.open('wb') as fil:
self.serializer.dump(self.data, fil)
else:
if self.cache_path.exists():
print('deleting ', self.cache_path)
self.cache_path.unlink()
def __setitem__(self, key: Hashable, obj: Any) -> None:
self.load_if_not_loaded()
super().__setitem__(key, obj)
self.commit()
def __delitem__(self, key: Hashable) -> None:
self.load_if_not_loaded()
super().__delitem__(key)
self.commit()
def clear(self) -> None:
self.load_if_not_loaded()
super().clear()
self.commit()
class DirectoryStore(ObjectStore[PathLike, Any]):
|
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 to equal things
# sorted(..., key=hash)
return tuple(sorted(
[(keyf, to_hashable(val)) for keyf, val in obj.items()],
key=hash
))
elif hasattr(obj, '__iter__'):
# turn iterables into tuples
return tuple(to_hashable(val) for val in obj)
else:
raise TypeError(f"I don't know how to hash {obj} ({type(obj)})")
else:
return cast(Hashable, obj)
def safe_str(obj: Any) -> str:
'''
Safe names are compact, unique, urlsafe, and equal when the objects are equal
str does not work because x == y does not imply str(x) == str(y).
>>> a = dict(d=1, e=1)
>>> b = dict(e=1, d=1)
>>> a == b
True
>>> str(a) == str(b)
False
>>> safe_str(a) == safe_str(b)
True
'''
if isinstance(obj, int):
ret = str(obj)
elif isinstance(obj, float):
ret = str(round(obj, 3))
elif isinstance(obj, str):
ret = repr(obj)
elif isinstance(obj, list):
ret = '[' + ','.join(map(safe_str, obj)) + ']'
elif isinstance(obj, tuple):
ret = '(' + ','.join(map(safe_str, obj)) + ')'
elif isinstance(obj, dict):
ret = '{' + ','.join(sorted(
safe_str(key) + ':' + safe_str(val)
for key, val in obj.items()
)) + '}'
else:
raise TypeError()
return urllib.parse.quote(ret, safe='')
def pathify(obj: Union[str, PathLike]) -> PathLike:
if isinstance(obj, str):
return Path(obj)
else:
return obj
| '''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)
if serializer is None:
import pickle
self.serializer = cast(Serializer, pickle)
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', safe='')
return self.cache_path / fname
def __setitem__(self, path: PathLike, obj: Any) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
with path.open('wb') as fil:
self.serializer.dump(obj, fil)
def __delitem__(self, path: PathLike) -> None:
path.unlink()
def __getitem__(self, path: PathLike) -> Any:
with path.open('rb') as fil:
return self.serializer.load(fil)
def __contains__(self, path: Any) -> bool:
if hasattr(path, 'exists'):
return bool(path.exists())
else:
return False
def clear(self) -> None:
print('deleting')
if hasattr(self.cache_path, 'rmtree'):
cast(Any, self.cache_path).rmtree()
else:
shutil.rmtree(str(self.cache_path)) | 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_variables)]
pub trait Resource {
/// Duplicate the resource
fn dup(&self) -> Result<Box<Resource>> {
Err(Error::new(EBADF))
}
/// 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 | (&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 all buffers
fn sync(&mut self) -> Result<()> {
Err(Error::new(EBADF))
}
/// Truncate to the given length
fn truncate(&mut self, len: usize) -> Result<()> {
Err(Error::new(EBADF))
}
}
| 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_variables)]
pub trait Resource {
/// Duplicate the resource
fn dup(&self) -> Result<Box<Resource>> {
Err(Error::new(EBADF)) | /// 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]) -> 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 all buffers
fn sync(&mut self) -> Result<()> {
Err(Error::new(EBADF))
}
/// Truncate to the given length
fn truncate(&mut self, len: usize) -> Result<()> {
Err(Error::new(EBADF))
}
} | }
| 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_variables)]
pub trait Resource {
/// Duplicate the resource
fn dup(&self) -> Result<Box<Resource>> |
/// 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]) -> 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 all buffers
fn sync(&mut self) -> Result<()> {
Err(Error::new(EBADF))
}
/// Truncate to the given length
fn truncate(&mut self, len: usize) -> Result<()> {
Err(Error::new(EBADF))
}
}
| {
Err(Error::new(EBADF))
} | identifier_body |
index.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2013 Radim Rehurek <[email protected]>
# 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 gensim.models.doc2vec import Doc2Vec
from gensim.models.word2vec import Word2Vec
try:
from annoy import AnnoyIndex
except ImportError:
raise ImportError("Annoy has not been installed, if you wish to use the annoy indexer, please run `pip install annoy`")
class AnnoyIndexer(object):
def __init__(self, model=None, num_trees=None):
self.index = None
self.labels = None
self.model = model
self.num_trees = num_trees
if model and num_trees:
if isinstance(self.model, Doc2Vec):
|
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.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(self, fname):
fname_dict = fname+'.d'
if not (os.path.exists(fname) and os.path.exists(fname_dict)):
raise IOError(
"Can't find index files '%s' and '%s' - Unable to restore AnnoyIndexer state." % (fname, fname_dict))
else:
with smart_open(fname_dict) as f:
d = _pickle.loads(f.read())
self.num_trees = d['num_trees']
self.index = AnnoyIndex(d['f'])
self.index.load(fname)
self.labels = d['labels']
def build_from_word2vec(self):
"""Build an Annoy index using word vectors from a Word2Vec model"""
self.model.init_sims()
return self._build_from_model(self.model.wv.syn0norm, self.model.index2word
, self.model.vector_size)
def build_from_doc2vec(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_size)
def _build_from_model(self, vectors, labels, num_features):
index = AnnoyIndex(num_features)
for vector_num, vector in enumerate(vectors):
index.add_item(vector_num, vector)
index.build(self.num_trees)
self.index = index
self.labels = labels
def most_similar(self, vector, num_neighbors):
"""Find the top-N most similar items"""
ids, distances = self.index.get_nns_by_vector(
vector, num_neighbors, include_distances=True)
return [(self.labels[ids[i]], 1 - distances[i] / 2) for i in range(len(ids))]
| self.build_from_doc2vec() | conditional_block |
index.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2013 Radim Rehurek <[email protected]>
# 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 gensim.models.doc2vec import Doc2Vec
from gensim.models.word2vec import Word2Vec
try:
from annoy import AnnoyIndex
except ImportError:
raise ImportError("Annoy has not been installed, if you wish to use the annoy indexer, please run `pip install annoy`")
class AnnoyIndexer(object):
def __init__(self, model=None, num_trees=None):
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_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.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(self, fname):
fname_dict = fname+'.d'
if not (os.path.exists(fname) and os.path.exists(fname_dict)):
raise IOError(
"Can't find index files '%s' and '%s' - Unable to restore AnnoyIndexer state." % (fname, fname_dict))
else:
with smart_open(fname_dict) as f:
d = _pickle.loads(f.read())
self.num_trees = d['num_trees']
self.index = AnnoyIndex(d['f'])
self.index.load(fname)
self.labels = d['labels']
def build_from_word2vec(self):
"""Build an Annoy index using word vectors from a Word2Vec model"""
self.model.init_sims()
return self._build_from_model(self.model.wv.syn0norm, self.model.index2word
, self.model.vector_size)
def | (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_size)
def _build_from_model(self, vectors, labels, num_features):
index = AnnoyIndex(num_features)
for vector_num, vector in enumerate(vectors):
index.add_item(vector_num, vector)
index.build(self.num_trees)
self.index = index
self.labels = labels
def most_similar(self, vector, num_neighbors):
"""Find the top-N most similar items"""
ids, distances = self.index.get_nns_by_vector(
vector, num_neighbors, include_distances=True)
return [(self.labels[ids[i]], 1 - distances[i] / 2) for i in range(len(ids))]
| build_from_doc2vec | identifier_name |
index.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2013 Radim Rehurek <[email protected]>
# 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 gensim.models.doc2vec import Doc2Vec
from gensim.models.word2vec import Word2Vec
try:
from annoy import AnnoyIndex
except ImportError:
raise ImportError("Annoy has not been installed, if you wish to use the annoy indexer, please run `pip install annoy`")
class AnnoyIndexer(object):
def __init__(self, model=None, num_trees=None):
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_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.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(self, fname):
fname_dict = fname+'.d'
if not (os.path.exists(fname) and os.path.exists(fname_dict)):
raise IOError(
"Can't find index files '%s' and '%s' - Unable to restore AnnoyIndexer state." % (fname, fname_dict))
else:
with smart_open(fname_dict) as f:
d = _pickle.loads(f.read())
self.num_trees = d['num_trees']
self.index = AnnoyIndex(d['f'])
self.index.load(fname)
self.labels = d['labels']
def build_from_word2vec(self):
"""Build an Annoy index using word vectors from a Word2Vec model"""
self.model.init_sims()
return self._build_from_model(self.model.wv.syn0norm, self.model.index2word
, self.model.vector_size)
def build_from_doc2vec(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_size)
def _build_from_model(self, vectors, labels, num_features):
index = AnnoyIndex(num_features)
for vector_num, vector in enumerate(vectors):
index.add_item(vector_num, vector)
index.build(self.num_trees)
self.index = index
self.labels = labels
def most_similar(self, vector, num_neighbors):
"""Find the top-N most similar items"""
ids, distances = self.index.get_nns_by_vector(
vector, num_neighbors, include_distances=True)
| 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 <[email protected]>
# 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 gensim.models.doc2vec import Doc2Vec
from gensim.models.word2vec import Word2Vec
try:
from annoy import AnnoyIndex
except ImportError:
raise ImportError("Annoy has not been installed, if you wish to use the annoy indexer, please run `pip install annoy`")
class AnnoyIndexer(object):
def __init__(self, model=None, num_trees=None):
|
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(self, fname):
fname_dict = fname+'.d'
if not (os.path.exists(fname) and os.path.exists(fname_dict)):
raise IOError(
"Can't find index files '%s' and '%s' - Unable to restore AnnoyIndexer state." % (fname, fname_dict))
else:
with smart_open(fname_dict) as f:
d = _pickle.loads(f.read())
self.num_trees = d['num_trees']
self.index = AnnoyIndex(d['f'])
self.index.load(fname)
self.labels = d['labels']
def build_from_word2vec(self):
"""Build an Annoy index using word vectors from a Word2Vec model"""
self.model.init_sims()
return self._build_from_model(self.model.wv.syn0norm, self.model.index2word
, self.model.vector_size)
def build_from_doc2vec(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_size)
def _build_from_model(self, vectors, labels, num_features):
index = AnnoyIndex(num_features)
for vector_num, vector in enumerate(vectors):
index.add_item(vector_num, vector)
index.build(self.num_trees)
self.index = index
self.labels = labels
def most_similar(self, vector, num_neighbors):
"""Find the top-N most similar items"""
ids, distances = self.index.get_nns_by_vector(
vector, num_neighbors, include_distances=True)
return [(self.labels[ids[i]], 1 - distances[i] / 2) for i in range(len(ids))]
| 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_word2vec()
else:
raise ValueError("Only a Word2Vec or Doc2Vec instance can be used") | 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 reduced mod `m`.
///
/// $f(x, m) = y$, where $x, y < m$ and $-x \equiv y \mod m$.
///
/// # Worst-case complexity
/// Constant time and additional memory.
///
/// # Examples
/// See the documentation of the `num::arithmetic::mod_neg` module.
///
/// This is nmod_neg from nmod_vec.h, FLINT 2.7.1.
#[inline]
fn mod_neg(self, m: $t) -> $t {
mod_neg(self, m)
}
}
impl ModNegAssign for $t {
/// Replaces `self` with `-self` mod `m`. Assumes the input is already reduced mod `m`.
///
/// $x \gets y$, where $x, y < m$ and $-x \equiv y \mod m$.
///
/// # Worst-case complexity
/// Constant time and additional memory.
///
/// # Examples
/// See the documentation of the `num::arithmetic::mod_neg` module.
///
/// This is nmod_neg from nmod_vec.h, FLINT 2.7.1, where the output is assigned to a.
#[inline]
fn mod_neg_assign(&mut self, m: $t) {
mod_neg_assign(self, m)
}
}
};
}
apply_to_unsigneds!(impl_mod_neg);
| {
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 mod `m`.
///
/// $f(x, m) = y$, where $x, y < m$ and $-x \equiv y \mod m$.
///
/// # Worst-case complexity
/// Constant time and additional memory.
///
/// # Examples
/// See the documentation of the `num::arithmetic::mod_neg` module.
///
/// This is nmod_neg from nmod_vec.h, FLINT 2.7.1.
#[inline]
fn mod_neg(self, m: $t) -> $t {
mod_neg(self, m)
}
}
impl ModNegAssign for $t {
/// Replaces `self` with `-self` mod `m`. Assumes the input is already reduced mod `m`.
///
/// $x \gets y$, where $x, y < m$ and $-x \equiv y \mod m$.
///
/// # Worst-case complexity
/// Constant time and additional memory.
///
/// # Examples
/// See the documentation of the `num::arithmetic::mod_neg` module.
///
/// This is nmod_neg from nmod_vec.h, FLINT 2.7.1, where the output is assigned to a.
#[inline]
fn mod_neg_assign(&mut self, m: $t) {
mod_neg_assign(self, m)
}
}
};
}
apply_to_unsigneds!(impl_mod_neg);
| {
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) => {
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
/// Constant time and additional memory.
///
/// # Examples
/// See the documentation of the `num::arithmetic::mod_neg` module.
///
/// This is nmod_neg from nmod_vec.h, FLINT 2.7.1.
#[inline]
fn mod_neg(self, m: $t) -> $t {
mod_neg(self, m)
}
}
impl ModNegAssign for $t {
/// Replaces `self` with `-self` mod `m`. Assumes the input is already reduced mod `m`.
///
/// $x \gets y$, where $x, y < m$ and $-x \equiv y \mod m$.
///
/// # Worst-case complexity
/// Constant time and additional memory.
///
/// # Examples
/// See the documentation of the `num::arithmetic::mod_neg` module.
///
/// This is nmod_neg from nmod_vec.h, FLINT 2.7.1, where the output is assigned to a.
#[inline]
fn mod_neg_assign(&mut self, m: $t) {
mod_neg_assign(self, m)
}
}
};
}
apply_to_unsigneds!(impl_mod_neg);
| 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, m: T) {
if *x != T::ZERO {
*x = m - *x;
} | ($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
/// Constant time and additional memory.
///
/// # Examples
/// See the documentation of the `num::arithmetic::mod_neg` module.
///
/// This is nmod_neg from nmod_vec.h, FLINT 2.7.1.
#[inline]
fn mod_neg(self, m: $t) -> $t {
mod_neg(self, m)
}
}
impl ModNegAssign for $t {
/// Replaces `self` with `-self` mod `m`. Assumes the input is already reduced mod `m`.
///
/// $x \gets y$, where $x, y < m$ and $-x \equiv y \mod m$.
///
/// # Worst-case complexity
/// Constant time and additional memory.
///
/// # Examples
/// See the documentation of the `num::arithmetic::mod_neg` module.
///
/// This is nmod_neg from nmod_vec.h, FLINT 2.7.1, where the output is assigned to a.
#[inline]
fn mod_neg_assign(&mut self, m: $t) {
mod_neg_assign(self, m)
}
}
};
}
apply_to_unsigneds!(impl_mod_neg); | }
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 {
/// The dynamic library interface has occured an error.
DynamicFail(CompositerError),
/// The graphic interface has occured an error.
GraphicFail(ManagerError),
/// The shell interface has occured an error.
ShellFail(ShellError),
}
impl fmt::Display for NekoError {
/// The function `fmt` formats the value using
/// the given formatter.
fn | (&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\
occured an error.",
NekoError::GraphicFail(_) => "The graphic interface has\
occured an error.",
NekoError::ShellFail(_) => "The shell interface has occured an error",
}
}
/// The function `cause` returns the lower-level cause of
/// this error if any.
fn cause(&self) -> Option<&Error> {
match *self {
NekoError::DynamicFail(ref why) => Some(why),
NekoError::GraphicFail(ref why) => Some(why),
NekoError::ShellFail(ref why) => Some(why),
}
}
}
| 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 {
/// The dynamic library interface has occured an error.
DynamicFail(CompositerError),
/// The graphic interface has occured an error.
GraphicFail(ManagerError),
/// The shell interface has occured an error.
ShellFail(ShellError),
}
impl fmt::Display for NekoError {
/// The function `fmt` formats the value using
/// the given formatter. | 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::GraphicFail(_) => "The graphic interface has\
occured an error.",
NekoError::ShellFail(_) => "The shell interface has occured an error",
}
}
/// The function `cause` returns the lower-level cause of
/// this error if any.
fn cause(&self) -> Option<&Error> {
match *self {
NekoError::DynamicFail(ref why) => Some(why),
NekoError::GraphicFail(ref why) => Some(why),
NekoError::ShellFail(ref why) => Some(why),
}
}
} | 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 = 'B';
var C = 'C';
var D = 'D'
goTo.marker(B);
edit.insert('constructor(val: T) { }');
verify.quickInfos({
Asig: "constructor A<string>(): A<string>",
Bsig: "constructor B<string>(val: string): B<string>",
Csig: "constructor C<string>(val: string): C<string>",
Dsig: "constructor D<string>(val: string): D<string>" // Cannot resolve signature. Still fill in generics based on explicit type arguments.
});
| 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: string): D<string>" // Cannot resolve signature
});
goTo.marker(D);
edit.deleteAtCaret("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>(): D<string>"
}); | 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 (parent) route
export default {
path: '/',
// Keep in mind, routes are evaluated in order
children: [
require('./home/index').default,
require('./contact/index').default,
require('./login/index').default,
require('./register/index').default,
require('./admin/index').default,
// Wildcard routes, e.g. { path: '*', ... } (must go last)
require('./content/index').default,
require('./notFound/index').default,
],
async action({ 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;
}, | 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 (parent) route
export default {
path: '/',
// Keep in mind, routes are evaluated in order
children: [
require('./home/index').default,
require('./contact/index').default,
require('./login/index').default,
require('./register/index').default,
require('./admin/index').default,
// Wildcard routes, e.g. { path: '*', ... } (must go last)
require('./content/index').default,
require('./notFound/index').default,
],
async a | { 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, routes are evaluated in order
children: [
require('./home/index').default,
require('./contact/index').default,
require('./login/index').default,
require('./register/index').default,
require('./admin/index').default,
// Wildcard routes, e.g. { path: '*', ... } (must go last)
require('./content/index').default,
require('./notFound/index').default,
],
async action({ 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;
},
}; | * 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::layout_and_value_strategy, Value};
use std::io::Cursor;
#[derive(Clone, Debug, Default)]
pub struct ValueTarget;
| 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 currently serialized are not self-describing, so store a serialized form of the
// layout + kind info along with the value as well.
let layout_blob = bcs::to_bytes(&layout).unwrap();
let value_blob = value.simple_serialize(&layout).expect("must serialize");
let mut blob = vec![];
// Prefix the layout blob with its length.
blob.write_u64::<BigEndian>(layout_blob.len() as u64)
.expect("writing should work");
blob.extend_from_slice(&layout_blob);
blob.extend_from_slice(&value_blob);
Some(blob)
}
fn fuzz(&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(struct_layout) => {
if struct_layout.fields().is_empty() {
return false;
}
struct_layout.fields().iter().all(is_valid_layout)
}
}
}
fn deserialize(data: &[u8]) -> Result<()> {
let mut data = Cursor::new(data);
// Read the length of the layout blob.
let layout_len = data.read_u64::<BigEndian>()? as usize;
let position = data.position() as usize;
let data = &data.into_inner()[position..];
if data.len() < layout_len {
bail!("too little data");
}
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 as
// false positives.
if !is_valid_layout(&layout) {
bail!("bad layout")
}
let _ = Value::simple_deserialize(value_data, &layout);
Ok(())
} | 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::layout_and_value_strategy, Value};
use std::io::Cursor;
#[derive(Clone, Debug, Default)]
pub struct ValueTarget;
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 currently serialized are not self-describing, so store a serialized form of the
// layout + kind info along with the value as well.
let layout_blob = bcs::to_bytes(&layout).unwrap();
let value_blob = value.simple_serialize(&layout).expect("must serialize");
let mut blob = vec![];
// Prefix the layout blob with its length.
blob.write_u64::<BigEndian>(layout_blob.len() as u64)
.expect("writing should work");
blob.extend_from_slice(&layout_blob);
blob.extend_from_slice(&value_blob);
Some(blob)
}
fn fuzz(&self, data: &[u8]) |
}
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_empty() {
return false;
}
struct_layout.fields().iter().all(is_valid_layout)
}
}
}
fn deserialize(data: &[u8]) -> Result<()> {
let mut data = Cursor::new(data);
// Read the length of the layout blob.
let layout_len = data.read_u64::<BigEndian>()? as usize;
let position = data.position() as usize;
let data = &data.into_inner()[position..];
if data.len() < layout_len {
bail!("too little data");
}
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 as
// false positives.
if !is_valid_layout(&layout) {
bail!("bad layout")
}
let _ = Value::simple_deserialize(value_data, &layout);
Ok(())
}
| {
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::layout_and_value_strategy, Value};
use std::io::Cursor;
#[derive(Clone, Debug, Default)]
pub struct ValueTarget;
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 currently serialized are not self-describing, so store a serialized form of the
// layout + kind info along with the value as well.
let layout_blob = bcs::to_bytes(&layout).unwrap();
let value_blob = value.simple_serialize(&layout).expect("must serialize");
let mut blob = vec![];
// Prefix the layout blob with its length.
blob.write_u64::<BigEndian>(layout_blob.len() as u64)
.expect("writing should work");
blob.extend_from_slice(&layout_blob);
blob.extend_from_slice(&value_blob);
Some(blob)
}
fn | (&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(struct_layout) => {
if struct_layout.fields().is_empty() {
return false;
}
struct_layout.fields().iter().all(is_valid_layout)
}
}
}
fn deserialize(data: &[u8]) -> Result<()> {
let mut data = Cursor::new(data);
// Read the length of the layout blob.
let layout_len = data.read_u64::<BigEndian>()? as usize;
let position = data.position() as usize;
let data = &data.into_inner()[position..];
if data.len() < layout_len {
bail!("too little data");
}
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 as
// false positives.
if !is_valid_layout(&layout) {
bail!("bad layout")
}
let _ = Value::simple_deserialize(value_data, &layout);
Ok(())
}
| 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::layout_and_value_strategy, Value};
use std::io::Cursor;
#[derive(Clone, Debug, Default)]
pub struct ValueTarget;
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 currently serialized are not self-describing, so store a serialized form of the
// layout + kind info along with the value as well.
let layout_blob = bcs::to_bytes(&layout).unwrap();
let value_blob = value.simple_serialize(&layout).expect("must serialize");
let mut blob = vec![];
// Prefix the layout blob with its length.
blob.write_u64::<BigEndian>(layout_blob.len() as u64)
.expect("writing should work");
blob.extend_from_slice(&layout_blob);
blob.extend_from_slice(&value_blob);
Some(blob)
}
fn fuzz(&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(struct_layout) => {
if struct_layout.fields().is_empty() {
return false;
}
struct_layout.fields().iter().all(is_valid_layout)
}
}
}
fn deserialize(data: &[u8]) -> Result<()> {
let mut data = Cursor::new(data);
// Read the length of the layout blob.
let layout_len = data.read_u64::<BigEndian>()? as usize;
let position = data.position() as usize;
let data = &data.into_inner()[position..];
if data.len() < layout_len |
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 as
// false positives.
if !is_valid_layout(&layout) {
bail!("bad layout")
}
let _ = Value::simple_deserialize(value_data, &layout);
Ok(())
}
| {
bail!("too little data");
} | conditional_block |
acrobot.py | __author__ = 'Frank Sehnke, [email protected]'
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.__init__(self, renderer, realtime, ip, port, buf)
# load model file
self.loadXODE(imp.find_module('pybrain')[1] + "/rl/environments/ode/models/acrobot.xode") |
#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.stepCounter == 1000: w.reset() |
# standard sensors and actuators
self.addSensor(sensors.JointSensor())
self.addSensor(sensors.JointVelocitySensor())
self.addActuator(actuators.JointActuator()) | random_line_split |
acrobot.py | __author__ = 'Frank Sehnke, [email protected]'
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
self.addSensor(sensors.JointSensor())
self.addSensor(sensors.JointVelocitySensor())
self.addActuator(actuators.JointActuator())
#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.stepCounter == 1000: w.reset()
| __init__ | identifier_name |
acrobot.py | __author__ = 'Frank Sehnke, [email protected]'
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.__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
self.addSensor(sensors.JointSensor())
self.addSensor(sensors.JointVelocitySensor())
self.addActuator(actuators.JointActuator())
#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.stepCounter == 1000: | w.reset() | conditional_block |
|
acrobot.py | __author__ = 'Frank Sehnke, [email protected]'
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 and actuators
self.addSensor(sensors.JointSensor())
self.addSensor(sensors.JointVelocitySensor())
self.addActuator(actuators.JointActuator())
#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 | 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 words, an industrial design award from 2013casj and
2010cmp will be of award type AwardType.INDUSTRIAL_DESIGN.
An award type must be enumerated for every type of award ever awarded.
ONCE A TYPE IS ENUMERATED, IT MUST NOT BE CHANGED.
Award types don't care about what type of event (Regional, District,
District Championship, Championship Division, Championship Finals, etc.)
the award is from. In other words, RCA and CCA are of the same award type.
"""
CHAIRMANS = 0
WINNER = 1
FINALIST = 2
WOODIE_FLOWERS = 3
DEANS_LIST = 4
VOLUNTEER = 5
FOUNDERS = 6
BART_KAMEN_MEMORIAL = 7
MAKE_IT_LOUD = 8
ENGINEERING_INSPIRATION = 9
ROOKIE_ALL_STAR = 10
GRACIOUS_PROFESSIONALISM = 11
COOPERTITION = 12
JUDGES = 13 | 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
MEDIA_AND_TECHNOLOGY = 28
INNOVATION_IN_CONTROL = 29
SPIRIT = 30
WEBSITE = 31
VISUALIZATION = 32
AUTODESK_INVENTOR = 33
FUTURE_INNOVATOR = 34
RECOGNITION_OF_EXTRAORDINARY_SERVICE = 35
OUTSTANDING_CART = 36
WSU_AIM_HIGHER = 37
LEADERSHIP_IN_CONTROL = 38
NUM_1_SEED = 39
INCREDIBLE_PLAY = 40
PEOPLES_CHOICE_ANIMATION = 41
VISUALIZATION_RISING_STAR = 42
BEST_OFFENSIVE_ROUND = 43
BEST_PLAY_OF_THE_DAY = 44
FEATHERWEIGHT_IN_THE_FINALS = 45
MOST_PHOTOGENIC = 46
OUTSTANDING_DEFENSE = 47
POWER_TO_SIMPLIFY = 48
AGAINST_ALL_ODDS = 49
RISING_STAR = 50
CHAIRMANS_HONORABLE_MENTION = 51
CONTENT_COMMUNICATION_HONORABLE_MENTION = 52
TECHNICAL_EXECUTION_HONORABLE_MENTION = 53
REALIZATION = 54
REALIZATION_HONORABLE_MENTION = 55
DESIGN_YOUR_FUTURE = 56
DESIGN_YOUR_FUTURE_HONORABLE_MENTION = 57
SPECIAL_RECOGNITION_CHARACTER_ANIMATION = 58
HIGH_SCORE = 59
TEACHER_PIONEER = 60
BEST_CRAFTSMANSHIP = 61
BEST_DEFENSIVE_MATCH = 62
PLAY_OF_THE_DAY = 63
PROGRAMMING = 64
PROFESSIONALISM = 65
GOLDEN_CORNDOG = 66
MOST_IMPROVED_TEAM = 67
WILDCARD = 68
CHAIRMANS_FINALIST = 69
OTHER = 70
AUTONOMOUS = 71
INNOVATION_CHALLENGE_SEMI_FINALIST = 72
ROOKIE_GAME_CHANGER = 73
SKILLS_COMPETITION_WINNER = 74
SKILLS_COMPETITION_FINALIST = 75
ROOKIE_DESIGN = 76
ENGINEERING_DESIGN = 77
DESIGNERS = 78
CONCEPT = 79
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,
AwardType.DEANS_LIST,
AwardType.VOLUNTEER,
AwardType.FOUNDERS,
AwardType.BART_KAMEN_MEMORIAL,
AwardType.MAKE_IT_LOUD,
}
# awards not used in the district point model
NON_JUDGED_NON_TEAM_AWARDS: Set[AwardType] = {
AwardType.HIGHEST_ROOKIE_SEED,
AwardType.WOODIE_FLOWERS,
AwardType.DEANS_LIST,
AwardType.VOLUNTEER,
AwardType.WINNER,
AwardType.FINALIST,
AwardType.WILDCARD,
}
NORMALIZED_NAMES = {
AwardType.CHAIRMANS: {None: "Chairman's Award"},
AwardType.CHAIRMANS_FINALIST: {None: "Chairman's Award Finalist"},
AwardType.WINNER: {None: "Winner"},
AwardType.WOODIE_FLOWERS: {
None: "Woodie Flowers Finalist Award",
EventType.CMP_FINALS: "Woodie Flowers Award",
},
}
# Only searchable awards. Obscure & old awards not listed
SEARCHABLE: Dict[AwardType, str] = {
AwardType.CHAIRMANS: "Chairman's",
AwardType.CHAIRMANS_FINALIST: "Chairman's Finalist",
AwardType.ENGINEERING_INSPIRATION: "Engineering Inspiration",
AwardType.COOPERTITION: "Coopertition",
AwardType.CREATIVITY: "Creativity",
AwardType.ENGINEERING_EXCELLENCE: "Engineering Excellence",
AwardType.ENTREPRENEURSHIP: "Entrepreneurship",
AwardType.DEANS_LIST: "Dean's List",
AwardType.BART_KAMEN_MEMORIAL: "Bart Kamen Memorial",
AwardType.GRACIOUS_PROFESSIONALISM: "Gracious Professionalism",
AwardType.HIGHEST_ROOKIE_SEED: "Highest Rookie Seed",
AwardType.IMAGERY: "Imagery",
AwardType.INDUSTRIAL_DESIGN: "Industrial Design",
AwardType.SAFETY: "Safety",
AwardType.INNOVATION_IN_CONTROL: "Innovation in Control",
AwardType.QUALITY: "Quality",
AwardType.ROOKIE_ALL_STAR: "Rookie All Star",
AwardType.ROOKIE_INSPIRATION: "Rookie Inspiration",
AwardType.SPIRIT: "Spirit",
AwardType.VOLUNTEER: "Volunteer",
AwardType.WOODIE_FLOWERS: "Woodie Flowers",
AwardType.JUDGES: "Judges'",
}
# Prioritized sort order for certain awards
SORT_ORDER: Dict[AwardType, int] = {
AwardType.CHAIRMANS: 0,
AwardType.FOUNDERS: 1,
AwardType.ENGINEERING_INSPIRATION: 2,
AwardType.ROOKIE_ALL_STAR: 3,
AwardType.WOODIE_FLOWERS: 4,
AwardType.VOLUNTEER: 5,
AwardType.DEANS_LIST: 6,
AwardType.WINNER: 7,
AwardType.FINALIST: 8,
} | 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,
AwardType.DEANS_LIST,
AwardType.VOLUNTEER,
AwardType.FOUNDERS,
AwardType.BART_KAMEN_MEMORIAL,
AwardType.MAKE_IT_LOUD,
}
# awards not used in the district point model
NON_JUDGED_NON_TEAM_AWARDS: Set[AwardType] = {
AwardType.HIGHEST_ROOKIE_SEED,
AwardType.WOODIE_FLOWERS,
AwardType.DEANS_LIST,
AwardType.VOLUNTEER,
AwardType.WINNER,
AwardType.FINALIST,
AwardType.WILDCARD,
}
NORMALIZED_NAMES = {
AwardType.CHAIRMANS: {None: "Chairman's Award"},
AwardType.CHAIRMANS_FINALIST: {None: "Chairman's Award Finalist"},
AwardType.WINNER: {None: "Winner"},
AwardType.WOODIE_FLOWERS: {
None: "Woodie Flowers Finalist Award",
EventType.CMP_FINALS: "Woodie Flowers Award",
},
}
# Only searchable awards. Obscure & old awards not listed
SEARCHABLE: Dict[AwardType, str] = {
AwardType.CHAIRMANS: "Chairman's",
AwardType.CHAIRMANS_FINALIST: "Chairman's Finalist",
AwardType.ENGINEERING_INSPIRATION: "Engineering Inspiration",
AwardType.COOPERTITION: "Coopertition",
AwardType.CREATIVITY: "Creativity",
AwardType.ENGINEERING_EXCELLENCE: "Engineering Excellence",
AwardType.ENTREPRENEURSHIP: "Entrepreneurship",
AwardType.DEANS_LIST: "Dean's List",
AwardType.BART_KAMEN_MEMORIAL: "Bart Kamen Memorial",
AwardType.GRACIOUS_PROFESSIONALISM: "Gracious Professionalism",
AwardType.HIGHEST_ROOKIE_SEED: "Highest Rookie Seed",
AwardType.IMAGERY: "Imagery",
AwardType.INDUSTRIAL_DESIGN: "Industrial Design",
AwardType.SAFETY: "Safety",
AwardType.INNOVATION_IN_CONTROL: "Innovation in Control",
AwardType.QUALITY: "Quality",
AwardType.ROOKIE_ALL_STAR: "Rookie All Star",
AwardType.ROOKIE_INSPIRATION: "Rookie Inspiration",
AwardType.SPIRIT: "Spirit",
AwardType.VOLUNTEER: "Volunteer",
AwardType.WOODIE_FLOWERS: "Woodie Flowers",
AwardType.JUDGES: "Judges'",
}
# Prioritized sort order for certain awards
SORT_ORDER: Dict[AwardType, int] = {
AwardType.CHAIRMANS: 0,
AwardType.FOUNDERS: 1,
AwardType.ENGINEERING_INSPIRATION: 2,
AwardType.ROOKIE_ALL_STAR: 3,
AwardType.WOODIE_FLOWERS: 4,
AwardType.VOLUNTEER: 5,
AwardType.DEANS_LIST: 6,
AwardType.WINNER: 7,
AwardType.FINALIST: 8,
}
| """
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 enumerated for every type of award ever awarded.
ONCE A TYPE IS ENUMERATED, IT MUST NOT BE CHANGED.
Award types don't care about what type of event (Regional, District,
District Championship, Championship Division, Championship Finals, etc.)
the award is from. In other words, RCA and CCA are of the same award type.
"""
CHAIRMANS = 0
WINNER = 1
FINALIST = 2
WOODIE_FLOWERS = 3
DEANS_LIST = 4
VOLUNTEER = 5
FOUNDERS = 6
BART_KAMEN_MEMORIAL = 7
MAKE_IT_LOUD = 8
ENGINEERING_INSPIRATION = 9
ROOKIE_ALL_STAR = 10
GRACIOUS_PROFESSIONALISM = 11
COOPERTITION = 12
JUDGES = 13
HIGHEST_ROOKIE_SEED = 14
ROOKIE_INSPIRATION = 15
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
MEDIA_AND_TECHNOLOGY = 28
INNOVATION_IN_CONTROL = 29
SPIRIT = 30
WEBSITE = 31
VISUALIZATION = 32
AUTODESK_INVENTOR = 33
FUTURE_INNOVATOR = 34
RECOGNITION_OF_EXTRAORDINARY_SERVICE = 35
OUTSTANDING_CART = 36
WSU_AIM_HIGHER = 37
LEADERSHIP_IN_CONTROL = 38
NUM_1_SEED = 39
INCREDIBLE_PLAY = 40
PEOPLES_CHOICE_ANIMATION = 41
VISUALIZATION_RISING_STAR = 42
BEST_OFFENSIVE_ROUND = 43
BEST_PLAY_OF_THE_DAY = 44
FEATHERWEIGHT_IN_THE_FINALS = 45
MOST_PHOTOGENIC = 46
OUTSTANDING_DEFENSE = 47
POWER_TO_SIMPLIFY = 48
AGAINST_ALL_ODDS = 49
RISING_STAR = 50
CHAIRMANS_HONORABLE_MENTION = 51
CONTENT_COMMUNICATION_HONORABLE_MENTION = 52
TECHNICAL_EXECUTION_HONORABLE_MENTION = 53
REALIZATION = 54
REALIZATION_HONORABLE_MENTION = 55
DESIGN_YOUR_FUTURE = 56
DESIGN_YOUR_FUTURE_HONORABLE_MENTION = 57
SPECIAL_RECOGNITION_CHARACTER_ANIMATION = 58
HIGH_SCORE = 59
TEACHER_PIONEER = 60
BEST_CRAFTSMANSHIP = 61
BEST_DEFENSIVE_MATCH = 62
PLAY_OF_THE_DAY = 63
PROGRAMMING = 64
PROFESSIONALISM = 65
GOLDEN_CORNDOG = 66
MOST_IMPROVED_TEAM = 67
WILDCARD = 68
CHAIRMANS_FINALIST = 69
OTHER = 70
AUTONOMOUS = 71
INNOVATION_CHALLENGE_SEMI_FINALIST = 72
ROOKIE_GAME_CHANGER = 73
SKILLS_COMPETITION_WINNER = 74
SKILLS_COMPETITION_FINALIST = 75
ROOKIE_DESIGN = 76
ENGINEERING_DESIGN = 77
DESIGNERS = 78
CONCEPT = 79 | 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 type must be enumerated for every type of award ever awarded.
ONCE A TYPE IS ENUMERATED, IT MUST NOT BE CHANGED.
Award types don't care about what type of event (Regional, District,
District Championship, Championship Division, Championship Finals, etc.)
the award is from. In other words, RCA and CCA are of the same award type.
"""
CHAIRMANS = 0
WINNER = 1
FINALIST = 2
WOODIE_FLOWERS = 3
DEANS_LIST = 4
VOLUNTEER = 5
FOUNDERS = 6
BART_KAMEN_MEMORIAL = 7
MAKE_IT_LOUD = 8
ENGINEERING_INSPIRATION = 9
ROOKIE_ALL_STAR = 10
GRACIOUS_PROFESSIONALISM = 11
COOPERTITION = 12
JUDGES = 13
HIGHEST_ROOKIE_SEED = 14
ROOKIE_INSPIRATION = 15
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
MEDIA_AND_TECHNOLOGY = 28
INNOVATION_IN_CONTROL = 29
SPIRIT = 30
WEBSITE = 31
VISUALIZATION = 32
AUTODESK_INVENTOR = 33
FUTURE_INNOVATOR = 34
RECOGNITION_OF_EXTRAORDINARY_SERVICE = 35
OUTSTANDING_CART = 36
WSU_AIM_HIGHER = 37
LEADERSHIP_IN_CONTROL = 38
NUM_1_SEED = 39
INCREDIBLE_PLAY = 40
PEOPLES_CHOICE_ANIMATION = 41
VISUALIZATION_RISING_STAR = 42
BEST_OFFENSIVE_ROUND = 43
BEST_PLAY_OF_THE_DAY = 44
FEATHERWEIGHT_IN_THE_FINALS = 45
MOST_PHOTOGENIC = 46
OUTSTANDING_DEFENSE = 47
POWER_TO_SIMPLIFY = 48
AGAINST_ALL_ODDS = 49
RISING_STAR = 50
CHAIRMANS_HONORABLE_MENTION = 51
CONTENT_COMMUNICATION_HONORABLE_MENTION = 52
TECHNICAL_EXECUTION_HONORABLE_MENTION = 53
REALIZATION = 54
REALIZATION_HONORABLE_MENTION = 55
DESIGN_YOUR_FUTURE = 56
DESIGN_YOUR_FUTURE_HONORABLE_MENTION = 57
SPECIAL_RECOGNITION_CHARACTER_ANIMATION = 58
HIGH_SCORE = 59
TEACHER_PIONEER = 60
BEST_CRAFTSMANSHIP = 61
BEST_DEFENSIVE_MATCH = 62
PLAY_OF_THE_DAY = 63
PROGRAMMING = 64
PROFESSIONALISM = 65
GOLDEN_CORNDOG = 66
MOST_IMPROVED_TEAM = 67
WILDCARD = 68
CHAIRMANS_FINALIST = 69
OTHER = 70
AUTONOMOUS = 71
INNOVATION_CHALLENGE_SEMI_FINALIST = 72
ROOKIE_GAME_CHANGER = 73
SKILLS_COMPETITION_WINNER = 74
SKILLS_COMPETITION_FINALIST = 75
ROOKIE_DESIGN = 76
ENGINEERING_DESIGN = 77
DESIGNERS = 78
CONCEPT = 79
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,
AwardType.DEANS_LIST,
AwardType.VOLUNTEER,
AwardType.FOUNDERS,
AwardType.BART_KAMEN_MEMORIAL,
AwardType.MAKE_IT_LOUD,
}
# awards not used in the district point model
NON_JUDGED_NON_TEAM_AWARDS: Set[AwardType] = {
AwardType.HIGHEST_ROOKIE_SEED,
AwardType.WOODIE_FLOWERS,
AwardType.DEANS_LIST,
AwardType.VOLUNTEER,
AwardType.WINNER,
AwardType.FINALIST,
AwardType.WILDCARD,
}
NORMALIZED_NAMES = {
AwardType.CHAIRMANS: {None: "Chairman's Award"},
AwardType.CHAIRMANS_FINALIST: {None: "Chairman's Award Finalist"},
AwardType.WINNER: {None: "Winner"},
AwardType.WOODIE_FLOWERS: {
None: "Woodie Flowers Finalist Award",
EventType.CMP_FINALS: "Woodie Flowers Award",
},
}
# Only searchable awards. Obscure & old awards not listed
SEARCHABLE: Dict[AwardType, str] = {
AwardType.CHAIRMANS: "Chairman's",
AwardType.CHAIRMANS_FINALIST: "Chairman's Finalist",
AwardType.ENGINEERING_INSPIRATION: "Engineering Inspiration",
AwardType.COOPERTITION: "Coopertition",
AwardType.CREATIVITY: "Creativity",
AwardType.ENGINEERING_EXCELLENCE: "Engineering Excellence",
AwardType.ENTREPRENEURSHIP: "Entrepreneurship",
AwardType.DEANS_LIST: "Dean's List",
AwardType.BART_KAMEN_MEMORIAL: "Bart Kamen Memorial",
AwardType.GRACIOUS_PROFESSIONALISM: "Gracious Professionalism",
AwardType.HIGHEST_ROOKIE_SEED: "Highest Rookie Seed",
AwardType.IMAGERY: "Imagery",
AwardType.INDUSTRIAL_DESIGN: "Industrial Design",
AwardType.SAFETY: "Safety",
AwardType.INNOVATION_IN_CONTROL: "Innovation in Control",
AwardType.QUALITY: "Quality",
AwardType.ROOKIE_ALL_STAR: "Rookie All Star",
AwardType.ROOKIE_INSPIRATION: "Rookie Inspiration",
AwardType.SPIRIT: "Spirit",
AwardType.VOLUNTEER: "Volunteer",
AwardType.WOODIE_FLOWERS: "Woodie Flowers",
AwardType.JUDGES: "Judges'",
}
# Prioritized sort order for certain awards
SORT_ORDER: Dict[AwardType, int] = {
AwardType.CHAIRMANS: 0,
AwardType.FOUNDERS: 1,
AwardType.ENGINEERING_INSPIRATION: 2,
AwardType.ROOKIE_ALL_STAR: 3,
AwardType.WOODIE_FLOWERS: 4,
AwardType.VOLUNTEER: 5,
AwardType.DEANS_LIST: 6,
AwardType.WINNER: 7,
AwardType.FINALIST: 8,
}
| 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/core';
import {NgClassImpl, NgClassImplProvider} from './ng_class_impl';
/*
* NgClass (as well as NgStyle) behaves differently when loaded in the VE and when not.
*
* If the VE is present (which is for older versions of Angular) then NgClass will inject
* the legacy diffing algorithm as a service and delegate all styling changes to that.
*
* If the VE is not present then NgStyle will normalize (through the injected service) and
* then write all styling changes to the `[style]` binding directly (through a host binding).
* Then Angular will notice the host binding change and treat the changes as styling
* changes and apply them via the core styling instructions that exist within Angular.
*/
// used when the VE is present
export const ngClassDirectiveDef__PRE_R3__ = undefined;
// used when the VE is not present (note the directive will
// never be instantiated normally because it is apart of a
// base class)
export const ngClassDirectiveDef__POST_R3__ = ΔdefineDirective({
type: function() {} as any,
selectors: null as any,
factory: () => {},
hostBindings: function(rf: ɵRenderFlags, ctx: any, elIndex: number) {
if (rf & ɵRenderFlags.Create) {
Δstyling();
}
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 container for non-VE code to setup
* a link to the `[class]` host binding (via the static
* `ngDirectiveDef` property on the class).
*
* Note that the `ngDirectiveDef` property's code is switched
* depending if VE is present or not (this allows for the
* binding code to be set only for newer versions of Angular).
*
* @publicApi
*/
export class NgClassBase {
static ngDirectiveDef: any = ngClassDirectiveDef;
constructor(protected _delegate: NgClassImpl) {}
getValue() { | 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}">...</some-element>
*
* <some-element [ngClass]="stringExp|arrayExp|objExp">...</some-element>
*
* <some-element [ngClass]="{'class1 class2 class3' : true}">...</some-element>
* ```
*
* @description
*
* Adds and removes CSS classes on an HTML element.
*
* The CSS classes are updated as follows, depending on the type of the expression evaluation:
* - `string` - the CSS classes listed in the string (space delimited) are added,
* - `Array` - the CSS classes declared as Array elements are added,
* - `Object` - keys are CSS classes that get added when the expression given in the value
* evaluates to a truthy value, otherwise they are removed.
*
* @publicApi
*/
@Directive({selector: '[ngClass]', providers: [NgClassImplProvider]})
export class NgClass extends NgClassBase implements DoCheck {
constructor(delegate: NgClassImpl) { super(delegate); }
@Input('class')
set klass(value: string) { this._delegate.setClass(value); }
@Input('ngClass')
set ngClass(value: string|string[]|Set<string>|{[klass: string]: any}) {
this._delegate.setNgClass(value);
}
ngDoCheck() { this._delegate.applyChanges(); }
}
| 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/core';
import {NgClassImpl, NgClassImplProvider} from './ng_class_impl';
/*
* NgClass (as well as NgStyle) behaves differently when loaded in the VE and when not.
*
* If the VE is present (which is for older versions of Angular) then NgClass will inject
* the legacy diffing algorithm as a service and delegate all styling changes to that.
*
* If the VE is not present then NgStyle will normalize (through the injected service) and
* then write all styling changes to the `[style]` binding directly (through a host binding).
* Then Angular will notice the host binding change and treat the changes as styling
* changes and apply them via the core styling instructions that exist within Angular.
*/
// used when the VE is present
export const ngClassDirectiveDef__PRE_R3__ = undefined;
// used when the VE is not present (note the directive will
// never be instantiated normally because it is apart of a
// base class)
export const ngClassDirectiveDef__POST_R3__ = ΔdefineDirective({
type: function() {} as any,
selectors: null as any,
factory: () => {}, | 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 container for non-VE code to setup
* a link to the `[class]` host binding (via the static
* `ngDirectiveDef` property on the class).
*
* Note that the `ngDirectiveDef` property's code is switched
* depending if VE is present or not (this allows for the
* binding code to be set only for newer versions of Angular).
*
* @publicApi
*/
export class NgClassBase {
static ngDirectiveDef: any = ngClassDirectiveDef;
constructor(protected _delegate: NgClassImpl) {}
getValue() { return 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}">...</some-element>
*
* <some-element [ngClass]="stringExp|arrayExp|objExp">...</some-element>
*
* <some-element [ngClass]="{'class1 class2 class3' : true}">...</some-element>
* ```
*
* @description
*
* Adds and removes CSS classes on an HTML element.
*
* The CSS classes are updated as follows, depending on the type of the expression evaluation:
* - `string` - the CSS classes listed in the string (space delimited) are added,
* - `Array` - the CSS classes declared as Array elements are added,
* - `Object` - keys are CSS classes that get added when the expression given in the value
* evaluates to a truthy value, otherwise they are removed.
*
* @publicApi
*/
@Directive({selector: '[ngClass]', providers: [NgClassImplProvider]})
export class NgClass extends NgClassBase implements DoCheck {
constructor(delegate: NgClassImpl) { super(delegate); }
@Input('class')
set klass(value: string) { this._delegate.setClass(value); }
@Input('ngClass')
set ngClass(value: string|string[]|Set<string>|{[klass: string]: any}) {
this._delegate.setNgClass(value);
}
ngDoCheck() { this._delegate.applyChanges(); }
} | 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/core';
import {NgClassImpl, NgClassImplProvider} from './ng_class_impl';
/*
* NgClass (as well as NgStyle) behaves differently when loaded in the VE and when not.
*
* If the VE is present (which is for older versions of Angular) then NgClass will inject
* the legacy diffing algorithm as a service and delegate all styling changes to that.
*
* If the VE is not present then NgStyle will normalize (through the injected service) and
* then write all styling changes to the `[style]` binding directly (through a host binding).
* Then Angular will notice the host binding change and treat the changes as styling
* changes and apply them via the core styling instructions that exist within Angular.
*/
// used when the VE is present
export const ngClassDirectiveDef__PRE_R3__ = undefined;
// used when the VE is not present (note the directive will
// never be instantiated normally because it is apart of a
// base class)
export const ngClassDirectiveDef__POST_R3__ = ΔdefineDirective({
type: function() {} as any,
selectors: null as any,
factory: () => {},
hostBindings: function(rf: ɵRenderFlags, ctx: any, elIndex: number) {
if (rf & ɵRenderFlags.Create) {
Δstyling();
}
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 container for non-VE code to setup
* a link to the `[class]` host binding (via the static
* `ngDirectiveDef` property on the class).
*
* Note that the `ngDirectiveDef` property's code is switched
* depending if VE is present or not (this allows for the
* binding code to be set only for newer versions of Angular).
*
* @publicApi
*/
export class NgClassBase {
static ngDirectiveDef: any = ngClassDirectiveDef;
constructor(protected _delegate: NgClassImpl) {}
getValue() { return 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}">...</some-element>
*
* <some-element [ngClass]="stringExp|arrayExp|objExp">...</some-element>
*
* <some-element [ngClass]="{'class1 class2 class3' : true}">...</some-element>
* ```
*
* @description
*
* Adds and removes CSS classes on an HTML element.
*
* The CSS classes are updated as follows, depending on the type of the expression evaluation:
* - `string` - the CSS classes listed in the string (space delimited) are added,
* - `Array` - the CSS classes declared as Array elements are added,
* - `Object` - keys are CSS classes that get added when the expression given in the value
* evaluates to a truthy value, otherwise they are removed.
*
* @publicApi
*/
@Directive({selector: '[ngClass]', providers: [NgClassImplProvider]})
export class NgClass extends NgClassBase implements DoCheck {
constructor(delegate: NgClassImpl) { super(delegate); }
@Input('class')
set klass(value: string) { this._delegate.setClass(value); }
@Input('ngClass')
set ngClass(value: string|string[]|Set<string>|{[klass: string]: any}) {
this._ | 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/core';
import {NgClassImpl, NgClassImplProvider} from './ng_class_impl';
/*
* NgClass (as well as NgStyle) behaves differently when loaded in the VE and when not.
*
* If the VE is present (which is for older versions of Angular) then NgClass will inject
* the legacy diffing algorithm as a service and delegate all styling changes to that.
*
* If the VE is not present then NgStyle will normalize (through the injected service) and
* then write all styling changes to the `[style]` binding directly (through a host binding).
* Then Angular will notice the host binding change and treat the changes as styling
* changes and apply them via the core styling instructions that exist within Angular.
*/
// used when the VE is present
export const ngClassDirectiveDef__PRE_R3__ = undefined;
// used when the VE is not present (note the directive will
// never be instantiated normally because it is apart of a
// base class)
export const ngClassDirectiveDef__POST_R3__ = ΔdefineDirective({
type: function() {} as any,
selectors: null as any,
factory: () => {},
hostBindings: function(rf: ɵRenderFlags, ctx: any, elIndex: number) {
if (rf & ɵRenderFlags.Create) {
| 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 container for non-VE code to setup
* a link to the `[class]` host binding (via the static
* `ngDirectiveDef` property on the class).
*
* Note that the `ngDirectiveDef` property's code is switched
* depending if VE is present or not (this allows for the
* binding code to be set only for newer versions of Angular).
*
* @publicApi
*/
export class NgClassBase {
static ngDirectiveDef: any = ngClassDirectiveDef;
constructor(protected _delegate: NgClassImpl) {}
getValue() { return 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}">...</some-element>
*
* <some-element [ngClass]="stringExp|arrayExp|objExp">...</some-element>
*
* <some-element [ngClass]="{'class1 class2 class3' : true}">...</some-element>
* ```
*
* @description
*
* Adds and removes CSS classes on an HTML element.
*
* The CSS classes are updated as follows, depending on the type of the expression evaluation:
* - `string` - the CSS classes listed in the string (space delimited) are added,
* - `Array` - the CSS classes declared as Array elements are added,
* - `Object` - keys are CSS classes that get added when the expression given in the value
* evaluates to a truthy value, otherwise they are removed.
*
* @publicApi
*/
@Directive({selector: '[ngClass]', providers: [NgClassImplProvider]})
export class NgClass extends NgClassBase implements DoCheck {
constructor(delegate: NgClassImpl) { super(delegate); }
@Input('class')
set klass(value: string) { this._delegate.setClass(value); }
@Input('ngClass')
set ngClass(value: string|string[]|Set<string>|{[klass: string]: any}) {
this._delegate.setNgClass(value);
}
ngDoCheck() { this._delegate.applyChanges(); }
}
| Δ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, // %REMOVE_LINE_CORE%
requires: 'embedbase',
onLoad: function() {
this.registerOembedTag();
},
init: function( editor ) {
var widgetDefinition = CKEDITOR.plugins.embedBase.createWidgetBaseDefinition( editor ),
origInit = widgetDefinition.init;
CKEDITOR.tools.extend( widgetDefinition, {
// Use a dialog exposed by the embedbase plugin.
dialog: 'embedBase',
button: editor.lang.embedbase.button,
allowedContent: 'oembed',
requiredContent: 'oembed',
styleableElements: 'oembed',
// Share config with the embed plugin.
providerUrl: new CKEDITOR.template(
editor.config.embed_provider ||
'//ckeditor.iframe.ly/api/oembed?url={url}&callback={callback}'
),
init: function() {
var that = this;
origInit.call( this );
// Need to wait for #ready with the initial content loading, because on #init there's no data yet.
this.once( 'ready', function() {
// When widget is created using dialog, the dialog's code will handle loading the content
// (because it handles success and error), so do load the content only when loading data.
if ( this.data.loadOnReady ) |
} );
},
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 CKEDITOR.htmlParser.element( 'div' );
element.replaceWith( div );
// Transfer widget classes from data to widget element (https://dev.ckeditor.com/ticket/13199).
div.attributes[ 'class' ] = element.attributes[ 'class' ];
return div;
}
},
downcast: function( element ) {
var ret = new CKEDITOR.htmlParser.element( 'oembed' );
ret.add( new CKEDITOR.htmlParser.text( this.data.url ) );
// Transfer widget classes from widget element back to data (https://dev.ckeditor.com/ticket/13199).
if ( element.attributes[ 'class' ] ) {
ret.attributes[ 'class' ] = element.attributes[ 'class' ];
}
return ret;
}
}, true );
editor.widgets.add( 'embedSemantic', widgetDefinition );
},
// Extends CKEDITOR.dtd so editor accepts <oembed> tag.
registerOembedTag: function() {
var dtd = CKEDITOR.dtd,
name;
// The oembed tag may contain text only.
dtd.oembed = { '#': 1 };
// Register oembed tag as allowed child, in each tag that can contain a div.
// It also registers the oembed tag in objects like $block, $blockLimit, etc.
for ( name in dtd ) {
if ( dtd[ name ].div ) {
dtd[ name ].oembed = 1;
}
}
}
} );
} )();
| {
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 not loaded (an error occurred or someone
// undid/copied sth to fast) the content will be loaded on the next initialization.
that.setData( 'loadOnReady', false );
editor.fire( 'updateSnapshot' );
}
} );
} | 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, // %REMOVE_LINE_CORE%
requires: 'embedbase',
onLoad: function() {
this.registerOembedTag();
},
init: function( editor ) {
var widgetDefinition = CKEDITOR.plugins.embedBase.createWidgetBaseDefinition( editor ),
origInit = widgetDefinition.init;
CKEDITOR.tools.extend( widgetDefinition, {
// Use a dialog exposed by the embedbase plugin.
dialog: 'embedBase',
button: editor.lang.embedbase.button,
allowedContent: 'oembed',
requiredContent: 'oembed',
styleableElements: 'oembed',
// Share config with the embed plugin.
providerUrl: new CKEDITOR.template(
editor.config.embed_provider ||
'//ckeditor.iframe.ly/api/oembed?url={url}&callback={callback}'
),
init: function() {
var that = this;
origInit.call( this );
// Need to wait for #ready with the initial content loading, because on #init there's no data yet.
this.once( 'ready', function() {
// When widget is created using dialog, the dialog's code will handle loading the content
// (because it handles success and error), so do load the content only when loading data.
if ( this.data.loadOnReady ) {
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 not loaded (an error occurred or someone
// undid/copied sth to fast) the content will be loaded on the next initialization.
that.setData( 'loadOnReady', false );
editor.fire( 'updateSnapshot' );
}
} );
}
} );
},
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 CKEDITOR.htmlParser.element( 'div' );
element.replaceWith( div );
// Transfer widget classes from data to widget element (https://dev.ckeditor.com/ticket/13199).
div.attributes[ 'class' ] = element.attributes[ 'class' ];
return div;
}
},
downcast: function( element ) {
var ret = new CKEDITOR.htmlParser.element( 'oembed' );
ret.add( new CKEDITOR.htmlParser.text( this.data.url ) );
// Transfer widget classes from widget element back to data (https://dev.ckeditor.com/ticket/13199).
if ( element.attributes[ 'class' ] ) {
ret.attributes[ 'class' ] = element.attributes[ 'class' ];
}
return ret;
}
}, true );
editor.widgets.add( 'embedSemantic', widgetDefinition );
},
// Extends CKEDITOR.dtd so editor accepts <oembed> tag.
registerOembedTag: function() {
var dtd = CKEDITOR.dtd,
name;
// The oembed tag may contain text only.
dtd.oembed = { '#': 1 };
// Register oembed tag as allowed child, in each tag that can contain a div.
// It also registers the oembed tag in objects like $block, $blockLimit, etc.
for ( name in dtd ) { | 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: TypeContext<PredictorEntity> }> {
render() {
const ctx = this.props.ctx.subCtx({ formGroupStyle: "SrOnly" });
return (
<fieldset>
<legend>Regression</legend>
<table className="table table-sm" style={{ width: "initial" }}>
<thead>
<tr>
<th></th>
<th>Training</th>
<th>Validation</th>
</tr>
</thead>
<tbody>
{this.renderRow(ctx, a => a.meanError)}
{this.renderRow(ctx, a => a.meanAbsoluteError)}
{this.renderRow(ctx, a => a.meanSquaredError)}
{this.renderRow(ctx, a => a.rootMeanSquareError)}
{this.renderRow(ctx, a => a.meanPercentageError)}
{this.renderRow(ctx, a => a.meanAbsolutePercentageError)}
</tbody>
</table>
</fieldset>
);
}
renderRow(ctx: TypeContext<PredictorEntity>, property: (val: PredictorRegressionMetricsEmbedded) => number | null | undefined) {
const ctxT = ctx.subCtx(a => a.regressionTraining!);
const ctxV = ctx.subCtx(a => a.regressionValidation!);
var unit = ctxT.subCtx(property).propertyRoute.member!.unit;
return (
<tr>
<th>{ctxT.niceName(property)}{unit && " (" + unit + ")"}</th>
<td><ValueLine ctx={ctxT.subCtx(property)} unitText="" /></td>
<td><ValueLine ctx={ctxV.subCtx(property)} unitText="" /></td>
</tr>
| }
} | );
| 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 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.
from urllib import parse as urllib
from oslo_serialization import jsonutils as json
from tempest.lib.common import rest_client
class ProtocolsClient(rest_client.RestClient):
def add_protocol_to_identity_provider(self, idp_id, protocol_id,
**kwargs):
"""Add protocol to 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#add-protocol-to-identity-provider
"""
post_body = json.dumps({'protocol': kwargs})
resp, body = self.put(
'OS-FEDERATION/identity_providers/%s/protocols/%s'
% (idp_id, protocol_id), post_body)
self.expected_success(201, resp.status)
body = json.loads(body)
return rest_client.ResponseBody(resp, body)
def list_protocols_of_identity_provider(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-FEDERATION/identity_providers/%s/protocols' % idp_id
if kwargs:
|
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 available parameters, please refer to the official
API reference:
https://docs.openstack.org/api-ref/identity/v3-ext/index.html#get-protocol-for-identity-provider
"""
resp, body = self.get(
'OS-FEDERATION/identity_providers/%s/protocols/%s'
% (idp_id, protocol_id))
self.expected_success(200, resp.status)
body = json.loads(body)
return rest_client.ResponseBody(resp, body)
def update_mapping_for_identity_provider(self, idp_id, protocol_id,
**kwargs):
"""Update attribute mapping 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#update-attribute-mapping-for-identity-provider
"""
post_body = json.dumps({'protocol': kwargs})
resp, body = self.patch(
'OS-FEDERATION/identity_providers/%s/protocols/%s'
% (idp_id, protocol_id), post_body)
self.expected_success(200, resp.status)
body = json.loads(body)
return rest_client.ResponseBody(resp, body)
def delete_protocol_from_identity_provider(self, idp_id, protocol_id):
"""Delete a protocol from 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#delete-a-protocol-from-identity-provider
"""
resp, body = self.delete(
'OS-FEDERATION/identity_providers/%s/protocols/%s'
% (idp_id, protocol_id))
self.expected_success(204, resp.status)
return rest_client.ResponseBody(resp, body)
| 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 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.
from urllib import parse as urllib
from oslo_serialization import jsonutils as json
from tempest.lib.common import rest_client
class ProtocolsClient(rest_client.RestClient):
def add_protocol_to_identity_provider(self, idp_id, protocol_id,
**kwargs):
"""Add protocol to 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#add-protocol-to-identity-provider
"""
post_body = json.dumps({'protocol': kwargs})
resp, body = self.put(
'OS-FEDERATION/identity_providers/%s/protocols/%s'
% (idp_id, protocol_id), post_body)
self.expected_success(201, resp.status)
body = json.loads(body)
return rest_client.ResponseBody(resp, body)
def list_protocols_of_identity_provider(self, idp_id, **kwargs): | """
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)
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-provider
"""
resp, body = self.get(
'OS-FEDERATION/identity_providers/%s/protocols/%s'
% (idp_id, protocol_id))
self.expected_success(200, resp.status)
body = json.loads(body)
return rest_client.ResponseBody(resp, body)
def update_mapping_for_identity_provider(self, idp_id, protocol_id,
**kwargs):
"""Update attribute mapping 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#update-attribute-mapping-for-identity-provider
"""
post_body = json.dumps({'protocol': kwargs})
resp, body = self.patch(
'OS-FEDERATION/identity_providers/%s/protocols/%s'
% (idp_id, protocol_id), post_body)
self.expected_success(200, resp.status)
body = json.loads(body)
return rest_client.ResponseBody(resp, body)
def delete_protocol_from_identity_provider(self, idp_id, protocol_id):
"""Delete a protocol from 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#delete-a-protocol-from-identity-provider
"""
resp, body = self.delete(
'OS-FEDERATION/identity_providers/%s/protocols/%s'
% (idp_id, protocol_id))
self.expected_success(204, resp.status)
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 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.
from urllib import parse as urllib
from oslo_serialization import jsonutils as json
from tempest.lib.common import rest_client
class ProtocolsClient(rest_client.RestClient):
def add_protocol_to_identity_provider(self, idp_id, protocol_id,
**kwargs):
"""Add protocol to 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#add-protocol-to-identity-provider
"""
post_body = json.dumps({'protocol': kwargs})
resp, body = self.put(
'OS-FEDERATION/identity_providers/%s/protocols/%s'
% (idp_id, protocol_id), post_body)
self.expected_success(201, resp.status)
body = json.loads(body)
return rest_client.ResponseBody(resp, body)
def | (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-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)
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-provider
"""
resp, body = self.get(
'OS-FEDERATION/identity_providers/%s/protocols/%s'
% (idp_id, protocol_id))
self.expected_success(200, resp.status)
body = json.loads(body)
return rest_client.ResponseBody(resp, body)
def update_mapping_for_identity_provider(self, idp_id, protocol_id,
**kwargs):
"""Update attribute mapping 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#update-attribute-mapping-for-identity-provider
"""
post_body = json.dumps({'protocol': kwargs})
resp, body = self.patch(
'OS-FEDERATION/identity_providers/%s/protocols/%s'
% (idp_id, protocol_id), post_body)
self.expected_success(200, resp.status)
body = json.loads(body)
return rest_client.ResponseBody(resp, body)
def delete_protocol_from_identity_provider(self, idp_id, protocol_id):
"""Delete a protocol from 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#delete-a-protocol-from-identity-provider
"""
resp, body = self.delete(
'OS-FEDERATION/identity_providers/%s/protocols/%s'
% (idp_id, protocol_id))
self.expected_success(204, resp.status)
return rest_client.ResponseBody(resp, body)
| 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 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.
from urllib import parse as urllib
from oslo_serialization import jsonutils as json
from tempest.lib.common import rest_client
class ProtocolsClient(rest_client.RestClient):
def add_protocol_to_identity_provider(self, idp_id, protocol_id,
**kwargs):
"""Add protocol to 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#add-protocol-to-identity-provider
"""
post_body = json.dumps({'protocol': kwargs})
resp, body = self.put(
'OS-FEDERATION/identity_providers/%s/protocols/%s'
% (idp_id, protocol_id), post_body)
self.expected_success(201, resp.status)
body = json.loads(body)
return rest_client.ResponseBody(resp, body)
def list_protocols_of_identity_provider(self, idp_id, **kwargs):
|
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-provider
"""
resp, body = self.get(
'OS-FEDERATION/identity_providers/%s/protocols/%s'
% (idp_id, protocol_id))
self.expected_success(200, resp.status)
body = json.loads(body)
return rest_client.ResponseBody(resp, body)
def update_mapping_for_identity_provider(self, idp_id, protocol_id,
**kwargs):
"""Update attribute mapping 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#update-attribute-mapping-for-identity-provider
"""
post_body = json.dumps({'protocol': kwargs})
resp, body = self.patch(
'OS-FEDERATION/identity_providers/%s/protocols/%s'
% (idp_id, protocol_id), post_body)
self.expected_success(200, resp.status)
body = json.loads(body)
return rest_client.ResponseBody(resp, body)
def delete_protocol_from_identity_provider(self, idp_id, protocol_id):
"""Delete a protocol from 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#delete-a-protocol-from-identity-provider
"""
resp, body = self.delete(
'OS-FEDERATION/identity_providers/%s/protocols/%s'
% (idp_id, protocol_id))
self.expected_success(204, resp.status)
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
"""
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) | 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.
*/
export function degrees(radians:number):number
{
return radians * 180 / Math.PI;
}
/**
* Normalizes radians to the standard range (-Math.PI - Math.PI).
* @param radians The radians to normalize.
* Returns the normalized radians.
*/
export function normalizeRadians(radians:number):number
{
return Math.atan2(Math.sin(radians), Math.cos(radians));
}
/**
* Rotates an angle (radians) towards an angle (radians) by the shortest way.
* @param source The source angle (radians) to rotate.
* @param target The target angle (radians) to rotate to.
* @param step How many radians to advance towards the target rotation.
* Returns the result angle (radians).
*/
export function rotateTowards(source, target, step)
{
var diff = Math.abs(source - target);
var result = source;
if(diff < Math.PI && target > source)
{
result = source + step;
}
else if(diff < Math.PI && target < source)
{
result = source - step;
}
else if(diff > Math.PI && target > source)
{ | 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 > target))
{
result = target;
}
return result;
}
/**
* Maps a value from a range to another range linearly.
* @param value The value to map.
* @param fromRangeMin The source range minimum (beginning) value.
* @param fromRangeMax The source range maximum (end) value.
* @param toRangeMin The target range minimum (beginning) value.
* @param toRangeMax The target range maximum (end) value.
* Returns the result mapped value.
*/
export function map(value:number, fromRangeMin:number, fromRangeMax:number, toRangeMin:number, toRangeMax:number):number
{
return (value - fromRangeMin) * (toRangeMax - toRangeMin) / (fromRangeMax - fromRangeMin) + toRangeMin;
}
/**
* Linearly interpolates a value towards a target value by a step percentage.
* @param value The value to interpolate.
* @param targetValue The value to interpolate towards.
* @param stepPercentage How big chunk of the difference is taken.
* Returns the linearly interpolated result value.
*/
export function lerp(value:number, targetValue:number, stepPercentage:number):number
{
return value * (1 - stepPercentage) + targetValue * stepPercentage;
}
/**
* 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 clamp(value:number, min:number, max:number)
{
if (value < min)
{
return min;
}
else if(value > max)
{
return value;
}
else
{
return value;
}
}
/**
* Calculates the hypotenuse of a right triangle based on the 2 shorter vertices.
* @param a Vertice a length.
* @param b Vertice b length.
* Returns the length of the hypotenuse.
*/
export function hypot(a:number, b:number)
{
return Math.sqrt(Math.pow(a, 2) + Math.pow(b, 2));
}
/**
* Returns the smallest value occurring in the collection.
* @param selector Selector used to get the comparable number value.
* @param items Source items to iterate over.
* Returns the smallest occurring number value.
*/
export function min<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.
*/
export function max<T>(selector:(o:T) => number, items:T[]):number
{
return _minOrMax(false, selector, items);
}
/**
* Inner function used as the repeating part for min and max functions.
* @param min If true, smallest value is returned. If set to false, largest.
* @param selector Selector used to get the comparable number value.
* @param items Source items to iterate over.
* Returns the smallest or the largest value.
*/
function _minOrMax<T>(min:boolean, selector:(o:T) => number, items:T[]):number
{
let result = min ? Number.MAX_VALUE : Number.MIN_VALUE;
let item:T;
for(let i = 0; i < items.length; i++)
{
item = items[i];
let value = selector(item);
if (min)
{
if (value < result)
{
result = value;
}
}
else
{
if (value > result)
{
result = value;
}
}
}
return result;
}
/**
* Checks if a polygon (an array of {x, y} objects) contains a position ({x, y} object).
* @param vertices The array of {x, y} objects that form the polygon.
* @param vector The position to check.
* Returns true if the position is inside the polygon.
*/
export function polygon_intersects(vertices: {x: number, y: number}[], vector: {x: number, y: number}): boolean
{
// ray-casting algorithm based on
// http://www.ecse.rpi.edu/Homepages/wrf/Research/Short_Notes/pnpoly.html
var x = vector.x, y = vector.y;
var inside = false;
for (var i = 0, j = vertices.length - 1; i < vertices.length; j = i++)
{
var xi = vertices[i].x, yi = vertices[i].y;
var xj = vertices[j].x, yj = vertices[j].y;
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; |
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.
*/
export function degrees(radians:number):number
{
return radians * 180 / Math.PI;
}
/**
* Normalizes radians to the standard range (-Math.PI - Math.PI).
* @param radians The radians to normalize.
* Returns the normalized radians.
*/
export function normalizeRadians(radians:number):number
{
return Math.atan2(Math.sin(radians), Math.cos(radians));
}
/**
* Rotates an angle (radians) towards an angle (radians) by the shortest way.
* @param source The source angle (radians) to rotate.
* @param target The target angle (radians) to rotate to.
* @param step How many radians to advance towards the target rotation.
* Returns the result angle (radians).
*/
export function rotateTowards(source, target, step)
{
var diff = Math.abs(source - target);
var result = source;
if(diff < Math.PI && target > source)
{
result = source + step;
}
else if(diff < Math.PI && target < source)
{
result = source - step;
}
else if(diff > Math.PI && target > source)
{
result = source - step;
}
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 > target))
{
result = target;
}
return result;
}
/**
* Maps a value from a range to another range linearly.
* @param value The value to map.
* @param fromRangeMin The source range minimum (beginning) value.
* @param fromRangeMax The source range maximum (end) value.
* @param toRangeMin The target range minimum (beginning) value.
* @param toRangeMax The target range maximum (end) value.
* Returns the result mapped value.
*/
export function map(value:number, fromRangeMin:number, fromRangeMax:number, toRangeMin:number, toRangeMax:number):number
{
return (value - fromRangeMin) * (toRangeMax - toRangeMin) / (fromRangeMax - fromRangeMin) + toRangeMin;
}
/**
* Linearly interpolates a value towards a target value by a step percentage.
* @param value The value to interpolate.
* @param targetValue The value to interpolate towards.
* @param stepPercentage How big chunk of the difference is taken.
* Returns the linearly interpolated result value.
*/
export function lerp(value:number, targetValue:number, stepPercentage:number):number
{ | /**
* 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 clamp(value:number, min:number, max:number)
{
if (value < min)
{
return min;
}
else if(value > max)
{
return value;
}
else
{
return value;
}
}
/**
* Calculates the hypotenuse of a right triangle based on the 2 shorter vertices.
* @param a Vertice a length.
* @param b Vertice b length.
* Returns the length of the hypotenuse.
*/
export function hypot(a:number, b:number)
{
return Math.sqrt(Math.pow(a, 2) + Math.pow(b, 2));
}
/**
* Returns the smallest value occurring in the collection.
* @param selector Selector used to get the comparable number value.
* @param items Source items to iterate over.
* Returns the smallest occurring number value.
*/
export function min<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.
*/
export function max<T>(selector:(o:T) => number, items:T[]):number
{
return _minOrMax(false, selector, items);
}
/**
* Inner function used as the repeating part for min and max functions.
* @param min If true, smallest value is returned. If set to false, largest.
* @param selector Selector used to get the comparable number value.
* @param items Source items to iterate over.
* Returns the smallest or the largest value.
*/
function _minOrMax<T>(min:boolean, selector:(o:T) => number, items:T[]):number
{
let result = min ? Number.MAX_VALUE : Number.MIN_VALUE;
let item:T;
for(let i = 0; i < items.length; i++)
{
item = items[i];
let value = selector(item);
if (min)
{
if (value < result)
{
result = value;
}
}
else
{
if (value > result)
{
result = value;
}
}
}
return result;
}
/**
* Checks if a polygon (an array of {x, y} objects) contains a position ({x, y} object).
* @param vertices The array of {x, y} objects that form the polygon.
* @param vector The position to check.
* Returns true if the position is inside the polygon.
*/
export function polygon_intersects(vertices: {x: number, y: number}[], vector: {x: number, y: number}): boolean
{
// ray-casting algorithm based on
// http://www.ecse.rpi.edu/Homepages/wrf/Research/Short_Notes/pnpoly.html
var x = vector.x, y = vector.y;
var inside = false;
for (var i = 0, j = vertices.length - 1; i < vertices.length; j = i++)
{
var xi = vertices[i].x, yi = vertices[i].y;
var xj = vertices[j].x, yj = vertices[j].y;
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; |
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.
*/
export function degrees(radians:number):number
{
return radians * 180 / Math.PI;
}
/**
* Normalizes radians to the standard range (-Math.PI - Math.PI).
* @param radians The radians to normalize.
* Returns the normalized radians.
*/
export function normalizeRadians(radians:number):number
{
return Math.atan2(Math.sin(radians), Math.cos(radians));
}
/**
* Rotates an angle (radians) towards an angle (radians) by the shortest way.
* @param source The source angle (radians) to rotate.
* @param target The target angle (radians) to rotate to.
* @param step How many radians to advance towards the target rotation.
* Returns the result angle (radians).
*/
export function rotateTowards(source, target, step)
{
var diff = Math.abs(source - target);
var result = source;
if(diff < Math.PI && target > source)
{
result = source + step;
}
else if(diff < Math.PI && target < source)
{
result = source - step;
}
else if(diff > Math.PI && target > source)
{
result = source - step;
}
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 > target))
{
result = target;
}
return result;
}
/**
* Maps a value from a range to another range linearly.
* @param value The value to map.
* @param fromRangeMin The source range minimum (beginning) value.
* @param fromRangeMax The source range maximum (end) value.
* @param toRangeMin The target range minimum (beginning) value.
* @param toRangeMax The target range maximum (end) value.
* Returns the result mapped value.
*/
export function map(value:number, fromRangeMin:number, fromRangeMax:number, toRangeMin:number, toRangeMax:number):number
{
return (value - fromRangeMin) * (toRangeMax - toRangeMin) / (fromRangeMax - fromRangeMin) + toRangeMin;
}
/**
* Linearly interpolates a value towards a target value by a step percentage.
* @param value The value to interpolate.
* @param targetValue The value to interpolate towards.
* @param stepPercentage How big chunk of the difference is taken.
* Returns the linearly interpolated result value.
*/
export function lerp(value:number, targetValue:number, stepPercentage:number):number
{
return value * (1 - stepPercentage) + targetValue * stepPercentage;
}
/**
* 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 clamp(value:number, min:number, max:number)
{
if (value < min)
{
return min;
}
else if(value > max)
{
return value;
}
else
{
return value;
}
}
/**
* Calculates the hypotenuse of a right triangle based on the 2 shorter vertices.
* @param a Vertice a length.
* @param b Vertice b length.
* Returns the length of the hypotenuse.
*/
export function hypot(a:number, b:number)
{
return Math.sqrt(Math.pow(a, 2) + Math.pow(b, 2));
}
/**
* Returns the smallest value occurring in the collection.
* @param selector Selector used to get the comparable number value.
* @param items Source items to iterate over.
* Returns the smallest occurring number value.
*/
export function min<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.
*/
export function max<T>(selector:(o:T) => number, items:T[]):number
{
return _minOrMax(false, selector, items);
}
/**
* Inner function used as the repeating part for min and max functions.
* @param min If true, smallest value is returned. If set to false, largest.
* @param selector Selector used to get the comparable number value.
* @param items Source items to iterate over.
* Returns the smallest or the largest value.
*/
function _minOrMax<T>(min:boolean, selector:(o:T) => number, items:T[]):number
{
let result = min ? Number.MAX_VALUE : Number.MIN_VALUE;
let item:T;
for(let i = 0; i < items.length; i++)
{
item = items[i];
let value = selector(item);
if (min)
{
if (value < result)
{
result = value;
}
}
else
{
if (value > result)
{
result = value;
}
}
}
return result;
}
/**
* Checks if a polygon (an array of {x, y} objects) contains a position ({x, y} object).
* @param vertices The array of {x, y} objects that form the polygon.
* @param vector The position to check.
* Returns true if the position is inside the polygon.
*/
export function polygon_intersects(vertices: {x: number, y: number}[], vector: {x: number, y: number}): boolean
{
// ray-casting algorithm based on
// http://www.ecse.rpi.edu/Homepages/wrf/Research/Short_Notes/pnpoly.html
var x = vector.x, y = vector.y;
var inside = false;
for (var i = 0, j = vertices.length - 1; i < vertices.length; j = i++)
{
var xi = vertices[i].x, yi = vertices[i].y;
var xj = vertices[j].x, yj = vertices[j].y; | 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.
*/
export function degrees(radians:number):number
{
return radians * 180 / Math.PI;
}
/**
* Normalizes radians to the standard range (-Math.PI - Math.PI).
* @param radians The radians to normalize.
* Returns the normalized radians.
*/
export function normalizeRadians(radians:number):number
{
return Math.atan2(Math.sin(radians), Math.cos(radians));
}
/**
* Rotates an angle (radians) towards an angle (radians) by the shortest way.
* @param source The source angle (radians) to rotate.
* @param target The target angle (radians) to rotate to.
* @param step How many radians to advance towards the target rotation.
* Returns the result angle (radians).
*/
export function rotateTowards(source, target, step)
{
var diff = Math.abs(source - target);
var result = source;
if(diff < Math.PI && target > source)
{
result = source + step;
}
else if(diff < Math.PI && target < source)
{
result = source - step;
}
else if(diff > Math.PI && target > source)
{
result = source - step;
}
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 > target))
{
result = target;
}
return result;
}
/**
* Maps a value from a range to another range linearly.
* @param value The value to map.
* @param fromRangeMin The source range minimum (beginning) value.
* @param fromRangeMax The source range maximum (end) value.
* @param toRangeMin The target range minimum (beginning) value.
* @param toRangeMax The target range maximum (end) value.
* Returns the result mapped value.
*/
export function map(value:number, fromRangeMin:number, fromRangeMax:number, toRangeMin:number, toRangeMax:number):number
{
return (value - fromRangeMin) * (toRangeMax - toRangeMin) / (fromRangeMax - fromRangeMin) + toRangeMin;
}
/**
* Linearly interpolates a value towards a target value by a step percentage.
* @param value The value to interpolate.
* @param targetValue The value to interpolate towards.
* @param stepPercentage How big chunk of the difference is taken.
* Returns the linearly interpolated result value.
*/
export function lerp(value:number, targetValue:number, stepPercentage:number):number
{
return value * (1 - stepPercentage) + targetValue * stepPercentage;
}
/**
* 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 clamp(value:number, min:number, max:number)
{
if (value < min)
{
return min;
}
else if(value > max)
{
return value;
}
else
{
return value;
}
}
/**
* Calculates the hypotenuse of a right triangle based on the 2 shorter vertices.
* @param a Vertice a length.
* @param b Vertice b length.
* Returns the length of the hypotenuse.
*/
export function hypot(a:number, b:number)
{
return Math.sqrt(Math.pow(a, 2) + Math.pow(b, 2));
}
/**
* Returns the smallest value occurring in the collection.
* @param selector Selector used to get the comparable number value.
* @param items Source items to iterate over.
* Returns the smallest occurring number value.
*/
export function m | 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.
*/
export function max<T>(selector:(o:T) => number, items:T[]):number
{
return _minOrMax(false, selector, items);
}
/**
* Inner function used as the repeating part for min and max functions.
* @param min If true, smallest value is returned. If set to false, largest.
* @param selector Selector used to get the comparable number value.
* @param items Source items to iterate over.
* Returns the smallest or the largest value.
*/
function _minOrMax<T>(min:boolean, selector:(o:T) => number, items:T[]):number
{
let result = min ? Number.MAX_VALUE : Number.MIN_VALUE;
let item:T;
for(let i = 0; i < items.length; i++)
{
item = items[i];
let value = selector(item);
if (min)
{
if (value < result)
{
result = value;
}
}
else
{
if (value > result)
{
result = value;
}
}
}
return result;
}
/**
* Checks if a polygon (an array of {x, y} objects) contains a position ({x, y} object).
* @param vertices The array of {x, y} objects that form the polygon.
* @param vector The position to check.
* Returns true if the position is inside the polygon.
*/
export function polygon_intersects(vertices: {x: number, y: number}[], vector: {x: number, y: number}): boolean
{
// ray-casting algorithm based on
// http://www.ecse.rpi.edu/Homepages/wrf/Research/Short_Notes/pnpoly.html
var x = vector.x, y = vector.y;
var inside = false;
for (var i = 0, j = vertices.length - 1; i < vertices.length; j = i++)
{
var xi = vertices[i].x, yi = vertices[i].y;
var xj = vertices[j].x, yj = vertices[j].y;
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; | 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 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('):
sx, sy = [float(x) for x in parse_list(string[6:-1])]
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] + self.values[5])
def __str__(self):
return str(self.values)
def to_mat4(self):
v = self.values
return [v[0], v[1], 0.0, 0.0,
v[2], v[3], 0.0, 0.0,
0.0, 0.0, 1.0, 0.0,
v[4], v[5], 0.0, 1.0]
def inverse(self):
d = float(self.values[0]*self.values[3] - self.values[1]*self.values[2])
return Matrix([self.values[3]/d, -self.values[1]/d, -self.values[2]/d, self.values[0]/d,
(self.values[2]*self.values[5] - self.values[3]*self.values[4])/d,
(self.values[1]*self.values[4] - self.values[0]*self.values[5])/d])
def __mul__(self, other):
|
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):
return str(self.values)
def to_mat4(self):
v = self.values
return [v[0], v[1], 0.0, 0.0,
v[2], v[3], 0.0, 0.0,
0.0, 0.0, 1.0, 0.0,
v[4], v[5], 0.0, 1.0]
def inverse(self):
d = float(self.values[0]*self.values[3] - self.values[1]*self.values[2])
return Matrix([self.values[3]/d, -self.values[1]/d, -self.values[2]/d, self.values[0]/d,
(self.values[2]*self.values[5] - self.values[3]*self.values[4])/d,
(self.values[1]*self.values[4] - self.values[0]*self.values[5])/d])
def __mul__(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.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) ) | 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('):
sx, sy = [float(x) for x in parse_list(string[6:-1])]
self.values = [sx, 0, 0, sy, 0, 0] | 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 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('):
sx, sy = [float(x) for x in parse_list(string[6:-1])] | 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] + self.values[5])
def __str__(self):
return str(self.values)
def to_mat4(self):
v = self.values
return [v[0], v[1], 0.0, 0.0,
v[2], v[3], 0.0, 0.0,
0.0, 0.0, 1.0, 0.0,
v[4], v[5], 0.0, 1.0]
def inverse(self):
d = float(self.values[0]*self.values[3] - self.values[1]*self.values[2])
return Matrix([self.values[3]/d, -self.values[1]/d, -self.values[2]/d, self.values[0]/d,
(self.values[2]*self.values[5] - self.values[3]*self.values[4])/d,
(self.values[1]*self.values[4] - self.values[0]*self.values[5])/d])
def __mul__(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.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) ) | 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 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('):
sx, sy = [float(x) for x in parse_list(string[6:-1])]
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] + self.values[5])
def __str__(self):
return str(self.values)
def to_mat4(self):
v = self.values
return [v[0], v[1], 0.0, 0.0,
v[2], v[3], 0.0, 0.0,
0.0, 0.0, 1.0, 0.0,
v[4], v[5], 0.0, 1.0]
def inverse(self):
d = float(self.values[0]*self.values[3] - self.values[1]*self.values[2])
return Matrix([self.values[3]/d, -self.values[1]/d, -self.values[2]/d, self.values[0]/d,
(self.values[2]*self.values[5] - self.values[3]*self.values[4])/d,
(self.values[1]*self.values[4] - self.values[0]*self.values[5])/d])
def | (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.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) ) | __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", null ],
[ "filter", "pcl__arm__filter__srv_8cpp.html#a62d45b46a7caeab39f53ca574bb2d06f", null ],
[ "main", "pcl__arm__filter__srv_8cpp.html#a3c04138a5bfe5d72780bb7e82a18e627", null ],
[ "cropFilter", "pcl__arm__filter__srv_8cpp.html#aeb82dd78a6dd9961f37215018fa75eb9", null ],
[ "elbowMaxValue", "pcl__arm__filter__srv_8cpp.html#a338077c8c5be4000bad261d71636489a", null ],
[ "elbowMinValue", "pcl__arm__filter__srv_8cpp.html#ae6035812b8bac346e387528c918bf89b", null ],
[ "forearmMaxValue", "pcl__arm__filter__srv_8cpp.html#ab7ce5712ed01d5b0493fa15673b7e983", null ],
[ "forearmMinValue", "pcl__arm__filter__srv_8cpp.html#a7f47885731f8cd105ee36bba21169d80", null ],
[ "left_lower_elbow_frame", "pcl__arm__filter__srv_8cpp.html#ae9b406a81134a444f264cc1e13cdc22b", null ],
[ "left_lower_forearm_frame", "pcl__arm__filter__srv_8cpp.html#a03bbdf8543233b1c12921461687df69f", null ],
[ "pitch", "pcl__arm__filter__srv_8cpp.html#a34c057a0378030db67bd6a129f37d938", null ],
[ "right_lower_elbow_frame", "pcl__arm__filter__srv_8cpp.html#a1f57372612334e34a394bfb273c55e81", null ],
[ "right_lower_forearm_frame", "pcl__arm__filter__srv_8cpp.html#a096616fea0057d98b09e63fdc9684613", null ],
[ "roll", "pcl__arm__filter__srv_8cpp.html#a1d3228afa3a1d6773954f40c1e519eb9", null ],
[ "rotation", "pcl__arm__filter__srv_8cpp.html#a84cf1f449714525e255aa53d26b62ecf", null ],
[ "rotMat", "pcl__arm__filter__srv_8cpp.html#abc3338eed95d1aec56b3049915a96aff", null ],
[ "rotQuat", "pcl__arm__filter__srv_8cpp.html#aacea208b467add8c9197eab918214974", null ], | ]; | [ "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_8cpp.html#a21cd490f6191f66678f55b4c242a10cf", null ] | 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();
}
`;
describe("project search", () => {
const emptyResults = [];
it("throws on lack of source", () => {
const needle = "test";
const source: any = null;
const matches = () => findSourceMatches(source, needle);
expect(matches).toThrow(TypeError);
});
it("handles empty source object", () => {
const needle = "test";
const source: any = {};
const matches = findSourceMatches(source, needle);
expect(matches).toEqual(emptyResults);
});
it("finds matches", () => {
const needle = "foo";
const source: any = {
text,
loadedState: "loaded",
id: "bar.js",
url: "http://example.com/foo/bar.js"
};
const matches = findSourceMatches(source, needle); | 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='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.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 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 Org.objects.filter(msgs__created_on__gte=last_week).distinct('pk'):
|
@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.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 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 Org.objects.filter(msgs__created_on__gte=last_week).distinct('pk'):
start = time.time()
org._calculate_credit_caches()
print " -- recalculated credits for %s in %0.2f seconds" % (org.name, time.time() - start)
@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() | 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='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.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():
|
@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 Org.objects.filter(msgs__created_on__gte=last_week).distinct('pk'):
start = time.time()
org._calculate_credit_caches()
print " -- recalculated credits for %s in %0.2f seconds" % (org.name, time.time() - start) | 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='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 | (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 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 Org.objects.filter(msgs__created_on__gte=last_week).distinct('pk'):
start = time.time()
org._calculate_credit_caches()
print " -- recalculated credits for %s in %0.2f seconds" % (org.name, time.time() - start)
@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()
| 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, remove_dir};
/// use std::path::{Path, PathBuf};
///
/// let path_name = format!("/tmp/.muxed-{}/", random::<u16>());
/// let path = Path::new(&path_name);
/// assert!(!path.exists());
///
/// check_first_run(path);
///
/// assert!(path.exists());
///
/// let _ = remove_dir(path);
/// ```
pub fn check_first_run(muxed_dir: &Path) -> Result<(), String> {
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 directory: `{}`", muxed_dir.display());
println!("Creating that now \u{1F44C}\n")
};
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();
|
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, remove_dir};
/// use std::path::{Path, PathBuf};
///
/// let path_name = format!("/tmp/.muxed-{}/", random::<u16>());
/// let path = Path::new(&path_name);
/// assert!(!path.exists());
///
/// check_first_run(path);
///
/// assert!(path.exists());
///
/// let _ = remove_dir(path);
/// ```
pub fn check_first_run(muxed_dir: &Path) -> Result<(), String> {
if !muxed_dir.exists() | ;
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!(path.exists());
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);
}
}
| {
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.display());
println!("Creating that now \u{1F44C}\n")
} | 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, remove_dir};
/// use std::path::{Path, PathBuf};
///
/// let path_name = format!("/tmp/.muxed-{}/", random::<u16>());
/// let path = Path::new(&path_name);
/// assert!(!path.exists());
///
/// check_first_run(path);
///
/// assert!(path.exists());
///
/// let _ = remove_dir(path);
/// ```
pub fn check_first_run(muxed_dir: &Path) -> Result<(), String> |
#[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());
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);
}
}
| {
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 directory: `{}`", muxed_dir.display());
println!("Creating that now \u{1F44C}\n")
};
Ok(())
} | 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, remove_dir};
/// use std::path::{Path, PathBuf};
///
/// let path_name = format!("/tmp/.muxed-{}/", random::<u16>());
/// let path = Path::new(&path_name);
/// assert!(!path.exists());
///
/// check_first_run(path);
///
/// assert!(path.exists());
///
/// let _ = remove_dir(path);
/// ```
pub fn check_first_run(muxed_dir: &Path) -> Result<(), String> {
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 directory: `{}`", muxed_dir.display());
println!("Creating that now \u{1F44C}\n")
};
Ok(())
}
#[cfg(test)]
mod test {
use super::*;
use rand_names;
use std::fs::remove_dir;
#[test]
fn | () {
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();
let _ = create_dir(&path);
assert!(check_first_run(&path).is_ok());
let _ = remove_dir(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 { FeatureSetItem_setItem } from "v2/__generated__/FeatureSetItem_setItem.graphql"
export interface FeatureSetItemProps {
setItem: FeatureSetItem_setItem
size: ComponentProps<typeof FeatureFeaturedLink>["size"]
}
export const FeatureSetItem: React.FC<FeatureSetItemProps> = ({
setItem,
size,
}) => {
switch (setItem.__typename) {
case "FeaturedLink":
return (
<FeatureFeaturedLink
size={size}
key={setItem.id}
featuredLink={setItem}
/>
)
case "Artwork":
return (
<Box key={setItem.id} pb={6} maxWidth={400} mx="auto">
<GridItem artwork={setItem} />
</Box>
)
default:
console.warn("Feature pages only support FeaturedLinks and Artworks")
return null
}
}
export const FeatureSetItemFragmentContainer = createFragmentContainer(
FeatureSetItem,
{
setItem: graphql`
fragment FeatureSetItem_setItem on OrderedSetItem {
__typename
... on FeaturedLink {
id
}
... on Artwork {
id
}
...GridItem_artwork | }
) | ...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 = LodashModuleReplacementPlugin;
declare class | 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;
exotics?: boolean;
flattening?: boolean;
guards?: boolean;
memoizing?: boolean;
metadata?: boolean;
paths?: boolean;
placeholders?: boolean;
shorthands?: boolean;
unicode?: boolean;
}
}
| 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 = LodashModuleReplacementPlugin;
declare class LodashModuleReplacementPlugin 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;
exotics?: boolean; | 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(|(i, &x)| x + transform[i % y1]).collect())
} else {
&vec[0] + &vec[1]
}
}
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 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(1, y1), vector_grad)]
} 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>>) -> Node<T> where T: Copy + Mul<Output=T> + Add<Output=T> {
Node::new(node_id, operation, operation_prime, vec![a, b], calc_dim)
} | 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 + transform[i % y1]).collect())
} else {
&vec[0] + &vec[1]
}
}
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 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(1, y1), vector_grad)]
} 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>>) -> Node<T> where T: Copy + Mul<Output=T> + Add<Output=T> {
Node::new(node_id, operation, operation_prime, vec![a, b], calc_dim)
}
| 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 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(1, y1), vector_grad)]
} 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>>) -> Node<T> where T: Copy + Mul<Output=T> + Add<Output=T> {
Node::new(node_id, operation, operation_prime, vec![a, b], calc_dim)
}
| {
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 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]
}
}
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 | 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>>) -> Node<T> where T: Copy + Mul<Output=T> + Add<Output=T> {
Node::new(node_id, operation, operation_prime, vec![a, b], calc_dim)
}
| {
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(1, y1), vector_grad)]
} | 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
#
# 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.
from troveclient import base
from troveclient import common
class Cluster(base.Resource):
"""A Cluster is an opaque cluster used to store Database clusters."""
def __repr__(self):
return "<Cluster: %s>" % self.name
def delete(self):
"""Delete the cluster."""
self.manager.delete(self)
class Clusters(base.ManagerWithFind):
"""Manage :class:`Cluster` resources."""
resource_class = Cluster
def create(self, name, datastore, datastore_version, instances=None,
locality=None):
"""Create (boot) a new cluster."""
body = {"cluster": {
"name": name
}}
datastore_obj = {
"type": datastore,
"version": datastore_version
}
body["cluster"]["datastore"] = datastore_obj
if instances:
body["cluster"]["instances"] = instances
if locality:
body["cluster"]["locality"] = locality
return self._create("/clusters", body, "cluster")
def list(self, limit=None, marker=None):
"""Get a list of all clusters.
:rtype: list of :class:`Cluster`.
""" | 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 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, 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['cluster'], loaded=True)
return body
def add_shard(self, cluster):
"""Adds a shard to the specified cluster.
:param cluster: The cluster to add a shard to
"""
url = "/clusters/%s" % base.getid(cluster)
body = {"add_shard": {}}
resp, body = self.api.client.post(url, body=body)
common.check_for_exceptions(resp, body, url)
if body:
return self.resource_class(self, body, loaded=True)
return body
def grow(self, cluster, instances=None):
"""Grow a cluster.
:param cluster: The cluster to grow
:param instances: List of instances to add
"""
body = {"grow": instances}
return self._action(cluster, body)
def shrink(self, cluster, instances=None):
"""Shrink a cluster.
:param cluster: The cluster to shrink
:param instances: List of instances to drop
"""
body = {"shrink": instances}
return self._action(cluster, body)
class ClusterStatus(object):
ACTIVE = "ACTIVE"
BUILD = "BUILD"
FAILED = "FAILED"
SHUTDOWN = "SHUTDOWN" | 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
#
# 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.
from troveclient import base
from troveclient import common
class Cluster(base.Resource):
"""A Cluster is an opaque cluster used to store Database clusters."""
def __repr__(self):
return "<Cluster: %s>" % self.name
def delete(self):
"""Delete the cluster."""
self.manager.delete(self)
class Clusters(base.ManagerWithFind):
"""Manage :class:`Cluster` resources."""
resource_class = Cluster
def create(self, name, datastore, datastore_version, instances=None,
locality=None):
"""Create (boot) a new cluster."""
body = {"cluster": {
"name": name
}}
datastore_obj = {
"type": datastore,
"version": datastore_version
}
body["cluster"]["datastore"] = datastore_obj
if instances:
body["cluster"]["instances"] = instances
if locality:
body["cluster"]["locality"] = locality
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):
|
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, 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['cluster'], loaded=True)
return body
def add_shard(self, cluster):
"""Adds a shard to the specified cluster.
:param cluster: The cluster to add a shard to
"""
url = "/clusters/%s" % base.getid(cluster)
body = {"add_shard": {}}
resp, body = self.api.client.post(url, body=body)
common.check_for_exceptions(resp, body, url)
if body:
return self.resource_class(self, body, loaded=True)
return body
def grow(self, cluster, instances=None):
"""Grow a cluster.
:param cluster: The cluster to grow
:param instances: List of instances to add
"""
body = {"grow": instances}
return self._action(cluster, body)
def shrink(self, cluster, instances=None):
"""Shrink a cluster.
:param cluster: The cluster to shrink
:param instances: List of instances to drop
"""
body = {"shrink": instances}
return self._action(cluster, body)
class ClusterStatus(object):
ACTIVE = "ACTIVE"
BUILD = "BUILD"
FAILED = "FAILED"
SHUTDOWN = "SHUTDOWN"
| """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
#
# 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.
from troveclient import base
from troveclient import common
class Cluster(base.Resource):
"""A Cluster is an opaque cluster used to store Database clusters."""
def __repr__(self):
return "<Cluster: %s>" % self.name
def delete(self):
"""Delete the cluster."""
self.manager.delete(self)
class Clusters(base.ManagerWithFind):
"""Manage :class:`Cluster` resources."""
resource_class = Cluster
def create(self, name, datastore, datastore_version, instances=None,
locality=None):
"""Create (boot) a new cluster."""
body = {"cluster": {
"name": name
}}
datastore_obj = {
"type": datastore,
"version": datastore_version
}
body["cluster"]["datastore"] = datastore_obj
if instances:
body["cluster"]["instances"] = instances
if locality:
body["cluster"]["locality"] = locality
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 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 delete
"""
url = "/clusters/%s" % base.getid(cluster)
resp, body = self.api.client.delete(url)
common.check_for_exceptions(resp, body, url)
def | (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['cluster'], loaded=True)
return body
def add_shard(self, cluster):
"""Adds a shard to the specified cluster.
:param cluster: The cluster to add a shard to
"""
url = "/clusters/%s" % base.getid(cluster)
body = {"add_shard": {}}
resp, body = self.api.client.post(url, body=body)
common.check_for_exceptions(resp, body, url)
if body:
return self.resource_class(self, body, loaded=True)
return body
def grow(self, cluster, instances=None):
"""Grow a cluster.
:param cluster: The cluster to grow
:param instances: List of instances to add
"""
body = {"grow": instances}
return self._action(cluster, body)
def shrink(self, cluster, instances=None):
"""Shrink a cluster.
:param cluster: The cluster to shrink
:param instances: List of instances to drop
"""
body = {"shrink": instances}
return self._action(cluster, body)
class ClusterStatus(object):
ACTIVE = "ACTIVE"
BUILD = "BUILD"
FAILED = "FAILED"
SHUTDOWN = "SHUTDOWN"
| _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
#
# 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.
from troveclient import base
from troveclient import common
class Cluster(base.Resource):
"""A Cluster is an opaque cluster used to store Database clusters."""
def __repr__(self):
return "<Cluster: %s>" % self.name
def delete(self):
"""Delete the cluster."""
self.manager.delete(self)
class Clusters(base.ManagerWithFind):
"""Manage :class:`Cluster` resources."""
resource_class = Cluster
def create(self, name, datastore, datastore_version, instances=None,
locality=None):
"""Create (boot) a new cluster."""
body = {"cluster": {
"name": name
}}
datastore_obj = {
"type": datastore,
"version": datastore_version
}
body["cluster"]["datastore"] = datastore_obj
if instances:
body["cluster"]["instances"] = instances
if locality:
|
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 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 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, 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['cluster'], loaded=True)
return body
def add_shard(self, cluster):
"""Adds a shard to the specified cluster.
:param cluster: The cluster to add a shard to
"""
url = "/clusters/%s" % base.getid(cluster)
body = {"add_shard": {}}
resp, body = self.api.client.post(url, body=body)
common.check_for_exceptions(resp, body, url)
if body:
return self.resource_class(self, body, loaded=True)
return body
def grow(self, cluster, instances=None):
"""Grow a cluster.
:param cluster: The cluster to grow
:param instances: List of instances to add
"""
body = {"grow": instances}
return self._action(cluster, body)
def shrink(self, cluster, instances=None):
"""Shrink a cluster.
:param cluster: The cluster to shrink
:param instances: List of instances to drop
"""
body = {"shrink": instances}
return self._action(cluster, body)
class ClusterStatus(object):
ACTIVE = "ACTIVE"
BUILD = "BUILD"
FAILED = "FAILED"
SHUTDOWN = "SHUTDOWN"
| 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, disambig, _encoding)
except AttributeError:
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig)
class Ui_VisualizarTransportadora(object):
def | (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")), QtGui.QIcon.Normal, QtGui.QIcon.Off)
VisualizarTransportadora.setWindowIcon(icon)
self.tblTransportadora = QtGui.QTableWidget(VisualizarTransportadora)
self.tblTransportadora.setGeometry(QtCore.QRect(0, 0, 401, 300))
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Maximum, QtGui.QSizePolicy.Maximum)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.tblTransportadora.sizePolicy().hasHeightForWidth())
self.tblTransportadora.setSizePolicy(sizePolicy)
self.tblTransportadora.setMaximumSize(QtCore.QSize(541, 300))
self.tblTransportadora.setAutoFillBackground(False)
self.tblTransportadora.setFrameShape(QtGui.QFrame.StyledPanel)
self.tblTransportadora.setFrameShadow(QtGui.QFrame.Sunken)
self.tblTransportadora.setLineWidth(1)
self.tblTransportadora.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.tblTransportadora.setEditTriggers(QtGui.QAbstractItemView.NoEditTriggers)
self.tblTransportadora.setSelectionBehavior(QtGui.QAbstractItemView.SelectRows)
self.tblTransportadora.setShowGrid(True)
self.tblTransportadora.setGridStyle(QtCore.Qt.SolidLine)
self.tblTransportadora.setWordWrap(True)
self.tblTransportadora.setCornerButtonEnabled(True)
self.tblTransportadora.setObjectName(_fromUtf8("tblTransportadora"))
self.tblTransportadora.setColumnCount(2)
self.tblTransportadora.setRowCount(0)
item = QtGui.QTableWidgetItem()
self.tblTransportadora.setHorizontalHeaderItem(0, item)
item = QtGui.QTableWidgetItem()
self.tblTransportadora.setHorizontalHeaderItem(1, item)
self.tblTransportadora.horizontalHeader().setVisible(True)
self.tblTransportadora.horizontalHeader().setCascadingSectionResizes(False)
self.tblTransportadora.horizontalHeader().setDefaultSectionSize(200)
self.tblTransportadora.horizontalHeader().setSortIndicatorShown(False)
self.tblTransportadora.horizontalHeader().setStretchLastSection(False)
self.tblTransportadora.verticalHeader().setVisible(False)
self.tblTransportadora.verticalHeader().setHighlightSections(True)
self.retranslateUi(VisualizarTransportadora)
QtCore.QMetaObject.connectSlotsByName(VisualizarTransportadora)
def retranslateUi(self, VisualizarTransportadora):
VisualizarTransportadora.setWindowTitle(_translate("VisualizarTransportadora", "Visualizar Transportadora", None))
self.tblTransportadora.setSortingEnabled(False)
item = self.tblTransportadora.horizontalHeaderItem(0)
item.setText(_translate("VisualizarTransportadora", "Id", None))
item = self.tblTransportadora.horizontalHeaderItem(1)
item.setText(_translate("VisualizarTransportadora", "Nome", None))
| 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)
except AttributeError:
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig)
class Ui_VisualizarTransportadora(object):
def setupUi(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")), QtGui.QIcon.Normal, QtGui.QIcon.Off)
VisualizarTransportadora.setWindowIcon(icon)
self.tblTransportadora = QtGui.QTableWidget(VisualizarTransportadora)
self.tblTransportadora.setGeometry(QtCore.QRect(0, 0, 401, 300))
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Maximum, QtGui.QSizePolicy.Maximum)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.tblTransportadora.sizePolicy().hasHeightForWidth())
self.tblTransportadora.setSizePolicy(sizePolicy)
self.tblTransportadora.setMaximumSize(QtCore.QSize(541, 300))
self.tblTransportadora.setAutoFillBackground(False)
self.tblTransportadora.setFrameShape(QtGui.QFrame.StyledPanel)
self.tblTransportadora.setFrameShadow(QtGui.QFrame.Sunken)
self.tblTransportadora.setLineWidth(1)
self.tblTransportadora.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.tblTransportadora.setEditTriggers(QtGui.QAbstractItemView.NoEditTriggers)
self.tblTransportadora.setSelectionBehavior(QtGui.QAbstractItemView.SelectRows)
self.tblTransportadora.setShowGrid(True)
self.tblTransportadora.setGridStyle(QtCore.Qt.SolidLine)
self.tblTransportadora.setWordWrap(True)
self.tblTransportadora.setCornerButtonEnabled(True)
self.tblTransportadora.setObjectName(_fromUtf8("tblTransportadora"))
self.tblTransportadora.setColumnCount(2)
self.tblTransportadora.setRowCount(0)
item = QtGui.QTableWidgetItem()
self.tblTransportadora.setHorizontalHeaderItem(0, item)
item = QtGui.QTableWidgetItem()
self.tblTransportadora.setHorizontalHeaderItem(1, item)
self.tblTransportadora.horizontalHeader().setVisible(True)
self.tblTransportadora.horizontalHeader().setCascadingSectionResizes(False)
self.tblTransportadora.horizontalHeader().setDefaultSectionSize(200)
self.tblTransportadora.horizontalHeader().setSortIndicatorShown(False)
self.tblTransportadora.horizontalHeader().setStretchLastSection(False)
self.tblTransportadora.verticalHeader().setVisible(False)
self.tblTransportadora.verticalHeader().setHighlightSections(True)
self.retranslateUi(VisualizarTransportadora)
QtCore.QMetaObject.connectSlotsByName(VisualizarTransportadora)
def retranslateUi(self, VisualizarTransportadora):
VisualizarTransportadora.setWindowTitle(_translate("VisualizarTransportadora", "Visualizar Transportadora", None))
self.tblTransportadora.setSortingEnabled(False)
item = self.tblTransportadora.horizontalHeaderItem(0)
item.setText(_translate("VisualizarTransportadora", "Id", None))
item = self.tblTransportadora.horizontalHeaderItem(1)
item.setText(_translate("VisualizarTransportadora", "Nome", None)) | # -*- 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, disambig, _encoding)
except AttributeError:
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig)
class Ui_VisualizarTransportadora(object):
def setupUi(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")), QtGui.QIcon.Normal, QtGui.QIcon.Off)
VisualizarTransportadora.setWindowIcon(icon)
self.tblTransportadora = QtGui.QTableWidget(VisualizarTransportadora)
self.tblTransportadora.setGeometry(QtCore.QRect(0, 0, 401, 300))
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Maximum, QtGui.QSizePolicy.Maximum)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.tblTransportadora.sizePolicy().hasHeightForWidth())
self.tblTransportadora.setSizePolicy(sizePolicy)
self.tblTransportadora.setMaximumSize(QtCore.QSize(541, 300))
self.tblTransportadora.setAutoFillBackground(False)
self.tblTransportadora.setFrameShape(QtGui.QFrame.StyledPanel)
self.tblTransportadora.setFrameShadow(QtGui.QFrame.Sunken)
self.tblTransportadora.setLineWidth(1)
self.tblTransportadora.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.tblTransportadora.setEditTriggers(QtGui.QAbstractItemView.NoEditTriggers)
self.tblTransportadora.setSelectionBehavior(QtGui.QAbstractItemView.SelectRows)
self.tblTransportadora.setShowGrid(True)
self.tblTransportadora.setGridStyle(QtCore.Qt.SolidLine)
self.tblTransportadora.setWordWrap(True)
self.tblTransportadora.setCornerButtonEnabled(True)
self.tblTransportadora.setObjectName(_fromUtf8("tblTransportadora"))
self.tblTransportadora.setColumnCount(2)
self.tblTransportadora.setRowCount(0)
item = QtGui.QTableWidgetItem()
self.tblTransportadora.setHorizontalHeaderItem(0, item)
item = QtGui.QTableWidgetItem()
self.tblTransportadora.setHorizontalHeaderItem(1, item)
self.tblTransportadora.horizontalHeader().setVisible(True)
self.tblTransportadora.horizontalHeader().setCascadingSectionResizes(False)
self.tblTransportadora.horizontalHeader().setDefaultSectionSize(200)
self.tblTransportadora.horizontalHeader().setSortIndicatorShown(False)
self.tblTransportadora.horizontalHeader().setStretchLastSection(False)
self.tblTransportadora.verticalHeader().setVisible(False)
self.tblTransportadora.verticalHeader().setHighlightSections(True)
self.retranslateUi(VisualizarTransportadora)
QtCore.QMetaObject.connectSlotsByName(VisualizarTransportadora)
def retranslateUi(self, VisualizarTransportadora):
| VisualizarTransportadora.setWindowTitle(_translate("VisualizarTransportadora", "Visualizar Transportadora", None))
self.tblTransportadora.setSortingEnabled(False)
item = self.tblTransportadora.horizontalHeaderItem(0)
item.setText(_translate("VisualizarTransportadora", "Id", None))
item = self.tblTransportadora.horizontalHeaderItem(1)
item.setText(_translate("VisualizarTransportadora", "Nome", None)) | 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(ValidatorError.prototype, 'properties', {
enumerable: false,
writable: true,
value: null
});
/*!
* Formats error messages
*/
ValidatorError.prototype.formatMessage = function(msg, properties) {
if (typeof msg === 'function') {
return msg(properties);
}
const propertyNames = Object.keys(properties);
for (let i = 0; i < propertyNames.length; ++i) {
const propertyName = propertyNames[i];
if (propertyName === 'message') {
continue;
}
msg = msg.replace('{' + propertyName.toUpperCase() + '}', properties[propertyName]);
}
return msg;
};
/*!
* toString helper
*/
ValidatorError.prototype.toString = function() {
return this.message;
};
/*!
* exports
*/
module.exports = ValidatorError;
| {
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.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;
} | 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.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
*/
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(ValidatorError.prototype, 'properties', {
enumerable: false,
writable: true,
value: null
});
/*!
* Formats error messages
*/
ValidatorError.prototype.formatMessage = function(msg, properties) {
if (typeof msg === 'function') {
return msg(properties);
}
const propertyNames = Object.keys(properties);
for (let i = 0; i < propertyNames.length; ++i) {
const propertyName = propertyNames[i];
if (propertyName === 'message') {
continue;
}
msg = msg.replace('{' + propertyName.toUpperCase() + '}', properties[propertyName]);
}
return msg;
};
/*!
* toString helper
*/
ValidatorError.prototype.toString = function() {
return this.message;
};
/*!
* exports
*/
module.exports = ValidatorError;
| 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.general.default;
}
const message = this.formatMessage(msg, properties);
MongooseError.call(this, message); | 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
*/
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(ValidatorError.prototype, 'properties', {
enumerable: false,
writable: true,
value: null
});
/*!
* Formats error messages
*/
ValidatorError.prototype.formatMessage = function(msg, properties) {
if (typeof msg === 'function') {
return msg(properties);
}
const propertyNames = Object.keys(properties);
for (let i = 0; i < propertyNames.length; ++i) {
const propertyName = propertyNames[i];
if (propertyName === 'message') {
continue;
}
msg = msg.replace('{' + propertyName.toUpperCase() + '}', properties[propertyName]);
}
return msg;
};
/*!
* toString helper
*/
ValidatorError.prototype.toString = function() {
return this.message;
};
/*!
* exports
*/
module.exports = ValidatorError; |
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.general.default;
}
const message = this.formatMessage(msg, properties);
MongooseError.call(this, message);
properties = Object.assign({}, properties, { message: message });
this.name = 'ValidatorError';
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
*/
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(ValidatorError.prototype, 'properties', {
enumerable: false,
writable: true,
value: null
});
/*!
* Formats error messages
*/
ValidatorError.prototype.formatMessage = function(msg, properties) {
if (typeof msg === 'function') {
return msg(properties);
}
const propertyNames = Object.keys(properties);
for (let i = 0; i < propertyNames.length; ++i) {
const propertyName = propertyNames[i];
if (propertyName === 'message') |
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 INodeAuthOptions {
/** The secret for encrypting and decrypting the JWT */
secretKey: string;
/**
* Lifetime of the token expressed in a string as a timespan, default 1 day ('1d'),
* e.g. '60', '1d', '24h', '2 days'. See https://github.com/zeit/ms.
*/
expiresIn?: string;
/**
* By default, all users that are not authenticated (they have no valid token) will be blocked and an UNAUTHORIZED error is returned.
* However, sometimes you may wish to let them through anyways, and verify them in your own code. In that case, set this property to false,
* which will clear any user preoperty of the request object.
* NOTE: Even when set to false, all api/* (except api/login and api/signup) routes will be blocked from unauthenticated access.
*
* @type {boolean}
* @memberOf INodeAuthOptions (default true)
*/
blockUnauthenticatedUser?: boolean;
/** The API route, default /api. */
api?: string;
/** The login route, default /api/login. If false, don't create it. */
login?: string | boolean;
/** The signup route, default /api/signup. If false, don't create it. */
signup?: string | boolean;
/** The profile route, default /api/profile. If false, don't create it. */
profile?: string | boolean;
/** The authorization route, default /api/authorizations. If false, don't create it. */
authorizations?: string | boolean;
/** Required only if you would like to use /api/authorizations */
policyStore?: IPolicyStore;
/** List of all users (only accessible to admins), default /api/users. If false, don't create it. */
users?: string;
/**
* Callback function, is called when the user is changed (before we save the user).
* If you return an IUser object, the properties verified, admin and data can be overwritten.
*/
onUserChanged?: (user: IUser, req: Request, change: CRUD) => IUser | void;
/** If supplied, verify the account's email */
verify?: {
/** Verification route */
route?: string | boolean;
/** Base URL for verification emails, e.g. www.mydomain.com/api/activate */
baseUrl: string; | verifyMailOptions: {
from: 'Do Not Reply <[email protected]>',
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><p>${URL}</p>',
text: 'Please verify your account by clicking the following link, or by copying and pasting it into your browser: ${URL}'
},
*/
verifyMailOptions: SendMailOptions;
/**
confirmMailOptions: {
from: 'Do Not Reply <[email protected]>',
subject: 'Successfully verified!',
html: '<p>Your account has been successfully verified.</p>',
text: 'Your account has been successfully verified.'
},
*/
confirmMailOptions: SendMailOptions;
verificationMessageSendCallback?: (err: Error, info: SentMessageInfo) => void;
confirmationMessageSendCallback?: (err: Error, info: SentMessageInfo) => void;
};
} | /** 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 _createElement = doc.createElement;
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(addNwmatcher(this.ownerDocument).select(selector, this));
};
element.matchesSelector = function(selector) {
return addNwmatcher(this.ownerDocument).match(this, selector);
};
return element;
};
};
| {
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 = function(selector) {
return new dom.NodeList(addNwmatcher(this).select(selector, this));
};
var _createElement = doc.createElement;
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(addNwmatcher(this.ownerDocument).select(selector, this));
};
element.matchesSelector = function(selector) {
return addNwmatcher(this.ownerDocument).match(this, selector);
};
return element;
};
};
| 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(this).first(selector, this);
};
doc.querySelectorAll = function(selector) {
return new dom.NodeList(addNwmatcher(this).select(selector, this));
}; | 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(addNwmatcher(this.ownerDocument).select(selector, this));
};
element.matchesSelector = function(selector) {
return addNwmatcher(this.ownerDocument).match(this, selector);
};
return element;
};
}; |
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;
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(addNwmatcher(this.ownerDocument).select(selector, this));
};
element.matchesSelector = function(selector) {
return addNwmatcher(this.ownerDocument).match(this, selector);
};
return element;
};
};
| {
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_iter(&stdout).next() {
Some(m) => {
match m.get(1) {
Some(s) => {
Some(s.as_str().to_owned())
},
None => None
}
},
None => None
}
}
pub fn is_os_x() -> bool {
match Command::new("sw_vers").output() {
Ok(output) => output.status.success(),
Err(_) => false
}
}
pub fn retrieve() -> Option<SwVers> {
let output = match Command::new("sw_vers").output() {
Ok(output) => output, | 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+)").unwrap();
SwVers {
product_name: extract_from_regex(&version_str, product_name_regex),
product_version: extract_from_regex(&version_str, product_version_regex),
build_version: extract_from_regex(&version_str, build_number_regex),
}
} | 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_iter(&stdout).next() {
Some(m) => {
match m.get(1) {
Some(s) => {
Some(s.as_str().to_owned())
},
None => None
}
},
None => None
}
}
pub fn is_os_x() -> bool {
match Command::new("sw_vers").output() {
Ok(output) => output.status.success(),
Err(_) => false
}
}
pub fn retrieve() -> Option<SwVers> |
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 {
product_name: extract_from_regex(&version_str, product_name_regex),
product_version: extract_from_regex(&version_str, product_version_regex),
build_version: extract_from_regex(&version_str, build_number_regex),
}
}
| {
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
}
}
pub fn is_os_x() -> bool {
match Command::new("sw_vers").output() {
Ok(output) => output.status.success(),
Err(_) => false
}
}
pub fn retrieve() -> Option<SwVers> {
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()))
}
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 {
product_name: extract_from_regex(&version_str, product_name_regex),
product_version: extract_from_regex(&version_str, product_version_regex),
build_version: extract_from_regex(&version_str, build_number_regex),
}
}
| 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, PyPath};
use types::hgid::HgId;
pub fn init_module(py: Python, package: &str) -> PyResult<PyModule> |
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)))?
};
bookmarkstore::create_instance(py, RefCell::new(bm_store))
}
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)
.map_err(|e| PyErr::new::<exc::ValueError, _>(py, format!("{}", e)))?;
Ok(PyNone)
}
def remove(&self, bookmark: &str) -> PyResult<PyNone> {
let mut bm_store = self.bm_store(py).borrow_mut();
bm_store.remove(bookmark)
.map_err(|e| PyErr::new::<exc::KeyError, _>(py, format!("{}", e)))?;
Ok(PyNone)
}
def lookup_bookmark(&self, bookmark: &str) -> PyResult<Option<PyBytes>> {
let bm_store = self.bm_store(py).borrow();
match bm_store.lookup_bookmark(bookmark) {
Some(node) => Ok(Some(PyBytes::new(py, node.as_ref()))),
None => Ok(None),
}
}
def lookup_node(&self, node: PyBytes) -> PyResult<Option<PyList>> {
let bm_store = self.bm_store(py).borrow();
let hgid = HgId::from_slice(node.data(py))
.map_err(|e| PyErr::new::<exc::ValueError, _>(py, format!("{}", e)))?;
match bm_store.lookup_hgid(&hgid) {
Some(bms) => {
let bms: Vec<_> = bms.iter()
.map(|bm| PyString::new(py, bm).into_object())
.collect();
Ok(Some(PyList::new(py, bms.as_slice())))
}
None => Ok(None),
}
}
def flush(&self) -> PyResult<PyNone> {
let mut bm_store = self.bm_store(py).borrow_mut();
bm_store
.flush()
.map_err(|e| PyErr::new::<exc::IOError, _>(py, format!("{}", e)))?;
Ok(PyNone)
}
});
| {
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, PyPath};
use types::hgid::HgId;
pub fn init_module(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) -> PyResult<bookmarkstore> {
let bm_store = { |
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)
.map_err(|e| PyErr::new::<exc::ValueError, _>(py, format!("{}", e)))?;
Ok(PyNone)
}
def remove(&self, bookmark: &str) -> PyResult<PyNone> {
let mut bm_store = self.bm_store(py).borrow_mut();
bm_store.remove(bookmark)
.map_err(|e| PyErr::new::<exc::KeyError, _>(py, format!("{}", e)))?;
Ok(PyNone)
}
def lookup_bookmark(&self, bookmark: &str) -> PyResult<Option<PyBytes>> {
let bm_store = self.bm_store(py).borrow();
match bm_store.lookup_bookmark(bookmark) {
Some(node) => Ok(Some(PyBytes::new(py, node.as_ref()))),
None => Ok(None),
}
}
def lookup_node(&self, node: PyBytes) -> PyResult<Option<PyList>> {
let bm_store = self.bm_store(py).borrow();
let hgid = HgId::from_slice(node.data(py))
.map_err(|e| PyErr::new::<exc::ValueError, _>(py, format!("{}", e)))?;
match bm_store.lookup_hgid(&hgid) {
Some(bms) => {
let bms: Vec<_> = bms.iter()
.map(|bm| PyString::new(py, bm).into_object())
.collect();
Ok(Some(PyList::new(py, bms.as_slice())))
}
None => Ok(None),
}
}
def flush(&self) -> PyResult<PyNone> {
let mut bm_store = self.bm_store(py).borrow_mut();
bm_store
.flush()
.map_err(|e| PyErr::new::<exc::IOError, _>(py, format!("{}", e)))?;
Ok(PyNone)
}
}); | 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, PyPath};
use types::hgid::HgId;
pub fn | (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) -> PyResult<bookmarkstore> {
let bm_store = {
BookmarkStore::new(path.as_path())
.map_err(|e| PyErr::new::<exc::IOError, _>(py, format!("{}", e)))?
};
bookmarkstore::create_instance(py, RefCell::new(bm_store))
}
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)
.map_err(|e| PyErr::new::<exc::ValueError, _>(py, format!("{}", e)))?;
Ok(PyNone)
}
def remove(&self, bookmark: &str) -> PyResult<PyNone> {
let mut bm_store = self.bm_store(py).borrow_mut();
bm_store.remove(bookmark)
.map_err(|e| PyErr::new::<exc::KeyError, _>(py, format!("{}", e)))?;
Ok(PyNone)
}
def lookup_bookmark(&self, bookmark: &str) -> PyResult<Option<PyBytes>> {
let bm_store = self.bm_store(py).borrow();
match bm_store.lookup_bookmark(bookmark) {
Some(node) => Ok(Some(PyBytes::new(py, node.as_ref()))),
None => Ok(None),
}
}
def lookup_node(&self, node: PyBytes) -> PyResult<Option<PyList>> {
let bm_store = self.bm_store(py).borrow();
let hgid = HgId::from_slice(node.data(py))
.map_err(|e| PyErr::new::<exc::ValueError, _>(py, format!("{}", e)))?;
match bm_store.lookup_hgid(&hgid) {
Some(bms) => {
let bms: Vec<_> = bms.iter()
.map(|bm| PyString::new(py, bm).into_object())
.collect();
Ok(Some(PyList::new(py, bms.as_slice())))
}
None => Ok(None),
}
}
def flush(&self) -> PyResult<PyNone> {
let mut bm_store = self.bm_store(py).borrow_mut();
bm_store
.flush()
.map_err(|e| PyErr::new::<exc::IOError, _>(py, format!("{}", e)))?;
Ok(PyNone)
}
});
| 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" + (n == 1? "e" : "i"); },
formatInputTooLong: function (input, max) { var n = input.length - max; return "Inserisci " + n + " caratter" + (n == 1? "e" : "i") + " in meno"; },
formatSelectionTooBig: function (limit) { return "Puoi selezionare solo " + limit + " element" + (limit == 1 ? "o" : "i"); }, | 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 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.
#
# Generated code. DO NOT EDIT!
#
# Snippet for DeployModel
# NOTE: This snippet has been automatically generated for illustrative purposes only.
# It may require modifications to work in your environment.
# To install the latest published package dependency, execute the following:
# python3 -m pip install google-cloud-aiplatform
# [START aiplatform_v1beta1_generated_EndpointService_DeployModel_async]
from google.cloud import aiplatform_v1beta1
async def | ():
# 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.DeployModelRequest(
endpoint="endpoint_value",
deployed_model=deployed_model,
)
# Make the request
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]
| 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 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.
#
# Generated code. DO NOT EDIT!
#
# Snippet for DeployModel
# NOTE: This snippet has been automatically generated for illustrative purposes only.
# It may require modifications to work in your environment.
# To install the latest published package dependency, execute the following:
# python3 -m pip install google-cloud-aiplatform
# [START aiplatform_v1beta1_generated_EndpointService_DeployModel_async]
from google.cloud import aiplatform_v1beta1
async def sample_deploy_model():
# Create a client
|
# [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(
endpoint="endpoint_value",
deployed_model=deployed_model,
)
# Make the request
operation = client.deploy_model(request=request)
print("Waiting for operation to complete...")
response = await operation.result()
# Handle the response
print(response) | 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 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.
#
# Generated code. DO NOT EDIT!
#
# Snippet for DeployModel
# NOTE: This snippet has been automatically generated for illustrative purposes only.
# It may require modifications to work in your environment.
# To install the latest published package dependency, execute the following:
# python3 -m pip install google-cloud-aiplatform
# [START aiplatform_v1beta1_generated_EndpointService_DeployModel_async]
from google.cloud import aiplatform_v1beta1
async def sample_deploy_model():
# 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.DeployModelRequest( | 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 += thread_rng().gen_range(40, 1000);
let mut m: MT = SeedableRng::from_seed(time as u32);
let output = m.gen::<u32>();
for seed in get_time().sec + 2000 .. 0 {
let mut checker: MT = SeedableRng::from_seed(seed as u32);
if checker.gen::<u32>() == output {
assert_eq!(seed, time);
break;
}
}
}
#[test]
fn test_untemper() {
let mut m: MT = SeedableRng::from_seed(314159);
for i in 0 .. 624 {
let output = m.gen::<u32>();
assert_eq!(untemper(output), m.state[i]);
}
}
#[test]
fn test_rng_clone_from_output() {
let mut m: MT = SeedableRng::from_seed(314159);
let mut state = [0; 624];
for i in 0 .. 624 {
state[i] = untemper(m.gen::<u32>());
}
let mut cloned = MT { state: state, index: 624 };
for _ in 0 .. 1024 {
assert_eq!(cloned.gen::<u32>(), m.gen::<u32>());
}
} | use time::{get_time};
| random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.