file_name large_stringlengths 4 140 | prefix large_stringlengths 0 12.1k | suffix large_stringlengths 0 12k | middle large_stringlengths 0 7.51k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
utils.py | from .products.builders import products
from .responses import response, make_identity, make_error
from .static.builders import codevalues
from .users.builders import users
def fill_cache(cache, values_dict):
"""
Fill a mock cache object with some keys and values.
"""
cache.get.side_effect = lambda ... |
return self._resource_list_class
def get_resource_list_class(self):
raise NotImplementedError
def assertSameResource(self, res1, res2):
self.assertEqual(res1._location, res2._location)
def assertSameResourceList(self, list1, list2):
self.assertEqual(
[r._l... | self._resource_list_class = self.get_resource_list_class() | conditional_block |
utils.py |
from .products.builders import products
from .responses import response, make_identity, make_error
from .static.builders import codevalues
from .users.builders import users
def fill_cache(cache, values_dict):
"""
Fill a mock cache object with some keys and values.
"""
cache.get.side_effect = lambda... | response_dict.setdefault(
"http://fake.base/rest/users/current?_type=json",
response(
users.one(
email=user.email,
firstName=user.firstName,
lastName=user.lastName,
screenName=user.screenName
... | if response_dict is None:
response_dict = {}
else:
response_dict = response_dict.copy() | random_line_split |
utils.py | make_identity, make_error
from .static.builders import codevalues
from .users.builders import users
def fill_cache(cache, values_dict):
"""
Fill a mock cache object with some keys and values.
"""
cache.get.side_effect = lambda k, d=None: values_dict.get(k, d)
def setup_responses(http, response_d... | """
Generic smoke tests that will be run for all resource types.
"""
pass | identifier_body | |
jquery-collision.js | .proto.css("padding-left")) || 0;
clone.x2 -= parseInt(this.proto.css("padding-right")) || 0;
clone.x2 -= parseInt(this.proto.css("border-right")) || 0;
clone.x2 -= parseInt(this.proto.css("margin-right")) || 0;
clone.y1 += parseInt(this.proto.css("margin-top")) || 0;
... | {
this.target = targetNode;
this.obstacle = obstacleNode;
this.overlap = overlapCoords;
this.overlapType = overlapType;
} | identifier_body | |
jquery-collision.js | +
(parseInt(proto.css("padding-right")) || 0) + (parseInt(proto.css("border-right")) || 0) + (parseInt(proto.css("margin-right")) || 0);
this.y2 += this.y1;
this.y2 += (parseInt(proto.css("margin-top")) || 0) + (parseInt(proto.css("border-top")) || 0) + (parseInt(proto.css("pa... |
return clone;
}
CollisionCoords.prototype.move = function(dx, dy) {
this.x1 += dx;
this.x2 += dx;
this.y1 += dy;
this.y2 += dy;
return this;
};
CollisionCoords.prototype.update = function(obj) {
if ("x1" in obj) this.x1 = obj["x1"];
if (... | {
clone.x1 += parseInt(this.proto.css("margin-left")) || 0;
clone.x1 += parseInt(this.proto.css("border-left")) || 0;
clone.x1 += parseInt(this.proto.css("padding-left")) || 0;
clone.x2 -= parseInt(this.proto.css("padding-right")) || 0;
clone.x2 -= parseInt(th... | conditional_block |
jquery-collision.js | ) +
(parseInt(proto.css("padding-right")) || 0) + (parseInt(proto.css("border-right")) || 0) + (parseInt(proto.css("margin-right")) || 0);
this.y2 += this.y1;
this.y2 += (parseInt(proto.css("margin-top")) || 0) + (parseInt(proto.css("border-top")) || 0) + (parseInt(proto.css("p... | })];
}
}
if (hit) {
if (dirs["NW"] && dirs["NE"]) hit[0].dir = "N";
if (dirs["NE"] && dirs["SE"]) hit[0].dir = "E";
if (dirs["SE"] && dirs["SW"]) hit[0].dir = "S";
if (dirs["SW"] && dirs["NW"]) hit[0].dir = "W";
if (... | random_line_split | |
jquery-collision.js | clone.y1 += parseInt(this.proto.css("border-top")) || 0;
clone.y1 += parseInt(this.proto.css("padding-top")) || 0;
clone.y2 -= parseInt(this.proto.css("padding-bottom")) || 0;
clone.y2 -= parseInt(this.proto.css("border-bottom")) || 0;
clone.y2 -= parseInt(thi... | CollisionFactory | identifier_name | |
regex.py | import re
'''
search('r'pattern,text) : serach pattern in test, 'r' flag = raw string. which passes through backslashes without change which is very handy for regular expressions
importance of rflag
in particular, \b matches empty string specifically at the start and end of a word.
re expects the string \b, however... | ''' | random_line_split | |
regex.py | Largest
'''
## i+ = one or more i's, as many as possible.
result = re.search(r'pi+', 'piiig') # found, result.group() == "piii"
## Finds the first/leftmost solution, and within it drives the +
## as far as possible (aka 'leftmost and largest').
## In this example, note that it does not get to the second set of i's.
r... | print (email) | conditional_block | |
eth.rs | read-only, so svd2rust doens't generate bindings to
// modify them. Instead, as a workaround, we manually manipulate the
// bits
eth_mac
.mmc_tx_interrupt_mask
.modify(|r, w| w.bits(r.bits() | (1 << 27)));
eth_mac
.mmc_rx_interrupt_mask
.m... | number_packets_dropped | identifier_name | |
eth.rs | frames disable
.dis_tcp_ef()
.clear_bit()
// Forward error frames
.fep()
.clear_bit()
// Forward undersized good packets
.fup()
.clear_bit()
});
eth_mtl.mtltx_qomr.modify(|_, ... | {
let eth_dma = &*stm32::ETHERNET_DMA::ptr();
eth_dma
.dmacsr
.write(|w| w.nis().set_bit().ri().set_bit().ti().set_bit());
let _ = eth_dma.dmacsr.read();
let _ = eth_dma.dmacsr.read(); // Delay 2 peripheral clocks
} | identifier_body | |
eth.rs | DMA engine ownership
// Ensure changes to the descriptor are committed before
// DMA engine sees tail pointer store
cortex_m::asm::dsb();
// Move the tail pointer (TPR) to the next descriptor
let x = (x + 1) % TD;
unsafe {
let dma = &*stm32::ETHERNET_DMA::p... | // Contains first buffer of packet AND contains last buf of
// packet AND no errors AND not a contex descriptor
self.rdes3
& (EMAC_DES3_FD | EMAC_DES3_LD | EMAC_DES3_ES | EMAC_DES3_CTXT)
== (EMAC_DES3_FD | EMAC_DES3_LD)
}
/// Return true if this RDes is not curre... | // Write-back descriptor is valid if:
// | random_line_split |
models.py | - means a fixed day of fourth class falling on 19 Nov
"""
lang = None
def __init__(self, observance_id: str, date_: date, lang: str):
""" Build an Observance out of identifier and calendar date
:param observance_id: observance's identifier in format
<flexibility>:<... | if observance_id in [ii.id for ii in day.all]:
return date_, day | conditional_block | |
models.py | DAY_MAPPING)
from propers.parser import ProperParser
log = logging.getLogger(__name__)
class Observance:
"""
A class representing a single observance, such as "The first Friday after Pentecost" or "Assumption of Mary".
It parses observance's ID and extracts weekday, day's class/rank and human readable id... | (self) -> Union[None, str]:
if self.celebration:
return self.celebration[0].title
def get_proper(self) -> List[Tuple['Proper', 'Proper']]:
"""
Get proper that is used in today Mass. If given day does not have a dedicated proper,
use the one from the latest Sunday.
... | get_celebration_name | identifier_name |
models.py | DAY_MAPPING)
from propers.parser import ProperParser
log = logging.getLogger(__name__)
class Observance:
"""
A class representing a single observance, such as "The first Friday after Pentecost" or "Assumption of Mary".
It parses observance's ID and extracts weekday, day's class/rank and human readable id... | # "Feast of the Holy Family" replaces "First Sunday after Epiphany"; use the latter in
# following days without the own proper
return [ProperParser.parse(TEMPORA_EPI1_0A, self.calendar.lang)]
if day.celebration[0].id == TEMPORA_PENT01_0:
# "Trinity Sunday" replace... | """
Get proper that is used in today Mass. If given day does not have a dedicated proper,
use the one from the latest Sunday.
"""
if self.celebration:
try:
return [i.get_proper() for i in self.celebration]
except ProperNotFound as e:
... | identifier_body |
models.py | name: Epi2-4
Each identifier consists of three colon-separated elements:
flexibility - determines if it's a fixed (sancti) or movable (tempora) observance
identifier - a unique human readable observance identifier. In case of movable
days it's a day's name, in case of 'sancti' days it contains... | date_ = date(year, 1, 1)
while date_.year == year: | random_line_split | |
sample.go | unkItem, 64)
allStats := &SampleStats{}
statsLock := sync.Mutex{}
addStats := func(stats SampleStats) {
statsLock.Lock()
allStats.add(stats)
statsLock.Unlock()
}
t := time.Now()
excludedBatchIDs, err := db.batchesBelowValue(minBatchBalance)
if err != nil {
db.logger.Error(err, "get batches below value"... | add | identifier_name | |
sample.go | *big.Int,
) (Sample, error) {
g, ctx := errgroup.WithContext(ctx)
chunkC := make(chan reserve.ChunkItem, 64)
allStats := &SampleStats{}
statsLock := sync.Mutex{}
addStats := func(stats SampleStats) {
statsLock.Lock()
allStats.add(stats)
statsLock.Unlock()
}
t := time.Now()
excludedBatchIDs, err := db.b... | random_line_split | ||
sample.go | Nodes need to calculate the sample
// in the most optimal way and there are time restrictions. The lottery round is a
// time based round, so nodes participating in the round need to perform this
// calculation within the round limits.
// In order to optimize this we use a simple pipeline pattern:
// Iterate chunk add... | {
// Calculate transformed address from wrapped chunk
sChunk, err := soc.FromChunk(chunk)
if err != nil {
return swarm.ZeroAddress, err
}
taddrCac, err := transformedAddressCAC(hasher, sChunk.WrappedChunk())
if err != nil {
return swarm.ZeroAddress, err
}
// Hash address and transformed address to make tra... | identifier_body | |
sample.go | byte) Sample {
t.Helper()
hasher := bmt.NewTrHasher(anchor)
items := make([]SampleItem, SampleSize)
for i := 0; i < SampleSize; i++ {
ch := chunk.GenerateTestRandomChunk()
tr, err := transformedAddress(hasher, ch, swarm.ChunkTypeContentAddressed)
if err != nil {
t.Fatal(err)
}
items[i] = SampleItem... |
// Skip chunks if they are not SOC or CAC
if chItem.Type != swarm.ChunkTypeSingleOwner &&
chItem.Type != swarm.ChunkTypeContentAddressed {
wstat.RogueChunk++
continue
}
chunkLoadStart := time.Now()
chunk, err := db.ChunkStore().Get(ctx, chItem.ChunkAddress)
if err != nil {
... | {
wstat.BelowBalanceIgnored++
continue
} | conditional_block |
voxel_detection.py | cv
import numpy as np
import torch
import torch.nn as nn
from mmcv.parallel import collate, scatter
from mmdet3d.core.bbox import get_box_type
from mmdet3d.datasets.pipelines import Compose
from torch.utils.data import DataLoader, Dataset
from mmdeploy.codebase.base import BaseTask
from mmdeploy.codebase.mmdet3d.deplo... | def init_pytorch_model(self,
model_checkpoint: Optional[str] = None,
cfg_options: Optional[Dict] = None,
**kwargs) -> torch.nn.Module:
"""Initialize torch model.
Args:
model_checkpoint (str): The checkpoint... | def __init__(self, model_cfg: mmcv.Config, deploy_cfg: mmcv.Config,
device: str):
super().__init__(model_cfg, deploy_cfg, device)
def init_backend_model(self,
model_files: Sequence[str] = None,
**kwargs) -> torch.nn.Module:
"""I... | identifier_body |
voxel_detection.py | cv
import numpy as np
import torch
import torch.nn as nn
from mmcv.parallel import collate, scatter
from mmdet3d.core.bbox import get_box_type
from mmdet3d.datasets.pipelines import Compose
from torch.utils.data import DataLoader, Dataset
from mmdeploy.codebase.base import BaseTask
from mmdeploy.codebase.mmdet3d.deplo... | (self, model_cfg: mmcv.Config, deploy_cfg: mmcv.Config,
device: str):
super().__init__(model_cfg, deploy_cfg, device)
def init_backend_model(self,
model_files: Sequence[str] = None,
**kwargs) -> torch.nn.Module:
"""Initialize ba... | __init__ | identifier_name |
voxel_detection.py | import numpy as np
import torch
import torch.nn as nn
from mmcv.parallel import collate, scatter
from mmdet3d.core.bbox import get_box_type
from mmdet3d.datasets.pipelines import Compose
from torch.utils.data import DataLoader, Dataset
from mmdeploy.codebase.base import BaseTask
from mmdeploy.codebase.mmdet3d.deploy.m... | model.module.show_result(
data,
result,
out_dir='',
file_name='',
show=show,
snapshot=False,
score_thr=0.3) | conditional_block | |
bnj.go | .Mid {
if _, err = s.dao.UpdateSubMid(c, tp, v.Cid, v.Mid); err != nil {
return
}
}
}
return
}
// bnjDmCount laji bnj count
func (s *Service) bnjDmCount(c context.Context, sub *model.Subject, dm *model.DM) (err error) {
var (
dmid int64
pages []*api.Page
chosen *api.Page
choseSub *model... | dm.State = model.StateFilter
log.Info("bnj filter service delete(dmid:%d,data:+%v)", dm.ID, filterReply) | random_line_split | |
bnj.go | + 1) * 1000),
Pool: dm.Pool,
State: model.StateAdminDelete,
Ctime: dm.Ctime,
Mtime: dm.Mtime,
Content: &model.Content{
ID: dmid,
FontSize: dm.Content.FontSize,
Color: dm.Content.Color,
Mode: dm.Content.Mode,
IP: dm.Content.IP,
Plat: dm.Content.Plat,
Ms... | ig *model.BnjLiveConfig
start time.Time
)
if bnjConfig, err = s.dao.BnjConfig(c); err != nil {
log.Error("bnjLiveConfig error current:%v err:%+v", time.Now().String(), err)
return
}
if bnjConfig == nil {
log.Error("bnjLiveConfig error current:%v bnjConfig nil", time.Now().String())
return
}
if start... | identifier_body | |
bnj.go | ID
s.bnjUserLevel = s.conf.BNJ.BnjLiveDanmu.Level
if s.bnjStart, err = time.ParseInLocation(_dateFormat, s.conf.BNJ.BnjLiveDanmu.Start, time.Now().Location()); err != nil {
panic(err)
}
s.bnjCsmr = databus.New(s.conf.Databus.BnjCsmr)
log.Info("bnj init start:%v room_id:%v", s.bnjStart.String(), s.conf.BNJ.BnjLiv... | .Context, tp int32, v *model.Video) (err error) {
sub, err := s.dao.Subject(c, tp, v.Cid)
if err != nil {
return
}
if sub == nil {
if v.XCodeState >= model.VideoXcodeHDFinish {
if _, err = s.dao.AddSubject(c, tp, v.Cid, v.Aid, v.Mid, s.maxlimit(v.Duration), 0); err != nil {
return
}
}
} else {
if... | eo(c context | identifier_name |
bnj.go | ID
s.bnjUserLevel = s.conf.BNJ.BnjLiveDanmu.Level
if s.bnjStart, err = time.ParseInLocation(_dateFormat, s.conf.BNJ.BnjLiveDanmu.Start, time.Now().Location()); err != nil {
panic(err)
}
s.bnjCsmr = databus.New(s.conf.Databus.BnjCsmr)
log.Info("bnj init start:%v room_id:%v", s.bnjStart.String(), s.conf.BNJ.BnjLiv... | = &model.DM{
ID: dmid,
Type: model.SubTypeVideo,
Oid: chosen.Cid,
Mid: dm.Mid,
Progress: int32((chosen.Duration + 1) * 1000),
Pool: dm.Pool,
State: model.StateAdminDelete,
Ctime: dm.Ctime,
Mtime: dm.Mtime,
Content: &model.Content{
ID: dmid,
FontSize: dm.C... | ror("bnjDmCount genDMID() error(%v)", err)
return
}
forkDM : | conditional_block |
raw.py | Type]
unlocked: bool
unlockedTime: NumberType
getHeapStatistics: Optional[Callable[[], HeapStatType]]
getUsed: Callable[[], NumberType]
halt: Optional[Callable[[], None]]
setShardLimits: Callable[[Dict[str, NumberType]], NumberType]
unlock: Callable[[], NumberType]
generatePixel: Callable[[], NumberType]
class... |
class InterShardMemory():
getLocal: Callable[[], str]
setLocal: Callable[[str], None]
getRemote: Callable[[str], str]
class PathFinderOpts(TypedDict):
roomCallback: Optional[Callable[[str], Union[CostMatrix, bool]]]
plainCost: Optional[NumberType]
swampCost: Optional[NumberType]
flee: Optional[bool]
maxOps: ... | constructionSites: Dict[str, ConstructionSite]
cpu: CPUType
creeps: Dict[str, Creep]
flags: Dict[str, Flag]
gcl: GLType
gpl: GLType
map: Map
market: Market
powerCreeps: Dict[str, PowerCreep]
resources: ResourcesType
rooms: Dict[str, Room]
shard: ShardType
spawns: Dict[str, StructureSpawn]
structures: Dict[... | identifier_body |
raw.py | Type]
unlocked: bool
unlockedTime: NumberType
getHeapStatistics: Optional[Callable[[], HeapStatType]]
getUsed: Callable[[], NumberType]
halt: Optional[Callable[[], None]]
setShardLimits: Callable[[Dict[str, NumberType]], NumberType]
unlock: Callable[[], NumberType]
generatePixel: Callable[[], NumberType]
class... | class ShardType(TypedDict):
name: str
type: str
ptr: bool
class MultiRoomRouteOpts(TypedDict):
routeCallback: Callable[[str, str], NumberType]
class MultiRoomRouteOutput(TypedDict):
exit: NumberType
room: str
class RoomStatus(TypedDict):
status: str
timestamp: NumberType
class LineStyle(TypedDict):
width: ... | level: NumberType
progress: NumberType
progressTotal: NumberType
| random_line_split |
raw.py | Type]
unlocked: bool
unlockedTime: NumberType
getHeapStatistics: Optional[Callable[[], HeapStatType]]
getUsed: Callable[[], NumberType]
halt: Optional[Callable[[], None]]
setShardLimits: Callable[[Dict[str, NumberType]], NumberType]
unlock: Callable[[], NumberType]
generatePixel: Callable[[], NumberType]
class... | (RoomFindPathOpts):
reusePath: Optional[NumberType]
serializeMemory: Optional[bool]
noPathFinding: Optional[bool]
visualizePathStyle: Optional[RoomVisualPolyStyle]
Pos = Union[RoomObject, RoomPos]
class BaseCreep(RoomObject):
hits: NumberType
hitsMax: NumberType
id: str
memory: Any
my: bool
name: str
owner... | CreepMoveToOpts | identifier_name |
types.rs | vm::errors::VMResult;
use libra_types::access_path::AccessPath;
use serde::{Deserialize, Serialize};
/// VM representation of a struct type in Move.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "fuzzing", derive(Eq, PartialEq))]
pub struct FatStructType {
pub address: AccountAddress,
... | Signer => debug_write!(buf, "signer"),
Vector(elem_ty) => {
debug_write!(buf, "vector<")?;
elem_ty.debug_print(buf)?;
debug_write!(buf, ">")
}
Struct(struct_ty) => struct_ty.debug_print(buf),
Reference(ty) => {
... | Address => debug_write!(buf, "address"), | random_line_split |
types.rs | ::errors::VMResult;
use libra_types::access_path::AccessPath;
use serde::{Deserialize, Serialize};
/// VM representation of a struct type in Move.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "fuzzing", derive(Eq, PartialEq))]
pub struct FatStructType {
pub address: AccountAddress,
pub... | (&self) -> VMResult<bool> {
use FatType::*;
match self {
Bool | U8 | U64 | U128 | Address | Reference(_) | MutableReference(_) => Ok(false),
Signer => Ok(true),
Vector(ty) => ty.is_resource(),
Struct(struct_ty) => Ok(struct_ty.is_resource),
//... | is_resource | identifier_name |
types.rs | ::errors::VMResult;
use libra_types::access_path::AccessPath;
use serde::{Deserialize, Serialize};
/// VM representation of a struct type in Move.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "fuzzing", derive(Eq, PartialEq))]
pub struct FatStructType {
pub address: AccountAddress,
pub... | }
pub fn is_resource(&self) -> VMResult<bool> {
use FatType::*;
match self {
Bool | U8 | U64 | U128 | Address | Reference(_) | MutableReference(_) => Ok(false),
Signer => Ok(true),
Vector(ty) => ty.is_resource(),
Struct(struct_ty) => Ok(struct_t... | {
use FatType::*;
let res = match self {
Bool => TypeTag::Bool,
U8 => TypeTag::U8,
U64 => TypeTag::U64,
U128 => TypeTag::U128,
Address => TypeTag::Address,
Signer => TypeTag::Signer,
Vector(ty) => TypeTag::Vector(Box::n... | identifier_body |
hash2curve.rs | 5c353c75c576bf82ccc96adb63c094dde580021eddeafd91f8c0bfee6f636528f3d0c47fd2"),
u_0: hex!("480cb3ac2c389db7f9dac9c396d2647ae946db844598971c26d1afd53912a1491199c0a5902811e4b809c26fcd37a014"),
u_1: hex!("d28435eb34680e148bf3908536e42231cba9e1f73ae2c6902a222a89db5c49c97db2f8fa4d4cd6e424b17ac6... | {
assert_eq!(scalar.to_bytes().as_slice(), test_vector.sk_sm);
continue 'outer;
} | conditional_block | |
hash2curve.rs | 1d1392b00df0f5400c06"),
q1_x: hex!("6ad7bc8ed8b841efd8ad0765c8a23d0b968ec9aa360a558ff33500f164faa02bee6c704f5f91507c4c5aad2b0dc5b943"),
q1_y: hex!("47313cc0a873ade774048338fc34ca5313f96bbf6ae22ac6ef475d85f03d24792dc6afba8d0b4a70170c1b4f0f716629"),
},
TestVector {
... | {
struct TestVector {
dst: &'static [u8],
key_info: &'static [u8],
seed: &'static [u8],
sk_sm: &'static [u8],
}
const TEST_VECTORS: &[TestVector] = &[
TestVector {
dst: b"DeriveKeyPairVOPRF10-\x00\x00\x04",
... | identifier_body | |
hash2curve.rs |
const DST: &[u8] = b"QUUX-V01-CS02-with-P384_XMD:SHA-384_SSWU_RO_";
const TEST_VECTORS: &[TestVector] = &[
TestVector {
msg: b"",
p_x: hex!("eb9fe1b4f4e14e7140803c1d99d0a93cd823d2b024040f9c067a8eca1f5a2eeac9ad604973527a356f3fa3aeff0e4d83"),
p... | q1_x: [u8; 48],
q1_y: [u8; 48],
} | random_line_split | |
hash2curve.rs | () {
struct TestVector {
msg: &'static [u8],
p_x: [u8; 48],
p_y: [u8; 48],
u_0: [u8; 48],
u_1: [u8; 48],
q0_x: [u8; 48],
q0_y: [u8; 48],
q1_x: [u8; 48],
q1_y: [u8; 48],
}
const DST: &[u8]... | hash_to_curve | identifier_name | |
load_config.go | 2p priv key: %w", err)
}
conf.Priv = p
if err := loadListenOpts(conf, ctx); err != nil {
return nil, fmt.Errorf("failed to load p2p listen options: %w", err)
}
if err := loadDiscoveryOpts(conf, ctx); err != nil {
return nil, fmt.Errorf("failed to load p2p discovery options: %w", err)
}
if err := loadLibp2... | (p uint) (uint16, error) {
if p == 0 {
return 0, nil
}
if p >= (1 << 16) {
return 0, fmt.Errorf("port out of range: %d", p)
}
if p < 1024 {
return 0, fmt.Errorf("port is reserved for system: %d", p)
}
return uint16(p), nil
}
// loadScoringParams loads the peer scoring options from the CLI context.
func lo... | validatePort | identifier_name |
load_config.go | p priv key: %w", err)
}
conf.Priv = p
if err := loadListenOpts(conf, ctx); err != nil {
return nil, fmt.Errorf("failed to load p2p listen options: %w", err)
}
if err := loadDiscoveryOpts(conf, ctx); err != nil {
return nil, fmt.Errorf("failed to load p2p discovery options: %w", err)
}
if err := loadLibp2p... |
// loadScoringParams loads the peer scoring options from the CLI context.
func loadScoringParams(conf *p2p.Config, ctx *cli.Context, rollupCfg *rollup.Config) error {
scoringLevel := ctx.String(flags.Scoring.Name)
// Check old names for backwards compatibility
if scoringLevel == "" {
scoringLevel = ctx.String(fl... | {
if p == 0 {
return 0, nil
}
if p >= (1 << 16) {
return 0, fmt.Errorf("port out of range: %d", p)
}
if p < 1024 {
return 0, fmt.Errorf("port is reserved for system: %d", p)
}
return uint16(p), nil
} | identifier_body |
load_config.go | p priv key: %w", err)
}
conf.Priv = p
if err := loadListenOpts(conf, ctx); err != nil {
return nil, fmt.Errorf("failed to load p2p listen options: %w", err)
}
if err := loadDiscoveryOpts(conf, ctx); err != nil {
return nil, fmt.Errorf("failed to load p2p discovery options: %w", err)
}
if err := loadLibp2p... |
var err error
conf.AdvertiseTCPPort, err = validatePort(ctx.Uint(flags.AdvertiseTCPPort.Name))
if err != nil {
return fmt.Errorf("bad advertised TCP port: %w", err)
}
conf.AdvertiseUDPPort, err = validatePort(ctx.Uint(flags.AdvertiseUDPPort.Name))
if err != nil {
return fmt.Errorf("bad advertised UDP port: ... | {
conf.NoDiscovery = true
} | conditional_block |
load_config.go | 2p priv key: %w", err)
}
conf.Priv = p
if err := loadListenOpts(conf, ctx); err != nil {
return nil, fmt.Errorf("failed to load p2p listen options: %w", err)
}
if err := loadDiscoveryOpts(conf, ctx); err != nil {
return nil, fmt.Errorf("failed to load p2p discovery options: %w", err)
}
if err := loadLibp2... | if scoringLevel == "" {
scoringLevel = ctx.String(flags.PeerScoring.Name)
}
if scoringLevel == "" {
scoringLevel = ctx.String(flags.TopicScoring.Name)
}
if scoringLevel != "" {
params, err := p2p.GetScoringParams(scoringLevel, rollupCfg)
if err != nil {
return err
}
conf.ScoringParams = params
}
... |
// loadScoringParams loads the peer scoring options from the CLI context.
func loadScoringParams(conf *p2p.Config, ctx *cli.Context, rollupCfg *rollup.Config) error {
scoringLevel := ctx.String(flags.Scoring.Name)
// Check old names for backwards compatibility | random_line_split |
training.py | 0,
height=20,
max_gens=None,
n_players=None, # players per game
n_games=None, # games per round
n_rounds=None, # number of games each player will play
):
if not root_dir:
now = datetime.datetime.now()
root_dir = now.strftime("training-%Y%m%d-%H%M%S")
mkdir_p(root_dir)
... |
# print the json header and start a list of turns
game_json.write(json.dumps(game_hdr))
game_json.seek(-1, io.SEEK_CUR)
game_json.write(', "turns": [\n')
# play the game
for _board in game.run():
if game.turn_count > 0:
game_json.write(",\n"... | player = game.add_snake(snake)
game_log.write("game snake: %s func=%s\n" % (player, snake.move_func.func))
game_hdr["snakes"].append(dict(
board_id=player.board_id,
func=str(snake.move_func.func),
)) | conditional_block |
training.py | 0,
height=20,
max_gens=None,
n_players=None, # players per game
n_games=None, # games per round
n_rounds=None, # number of games each player will play
):
if not root_dir:
now = datetime.datetime.now()
root_dir = now.strftime("training-%Y%m%d-%H%M%S")
mkdir_p(root_dir)
... | height = height,
game_count = game_count,
game_round = game_round,
gen_count = gen_count,
snakes = snake_group,
))
for result in pool.map(play_game, game_infos):
for s... | width = width, | random_line_split |
training.py |
def evolve(
root_dir=None,
width=20,
height=20,
max_gens=None,
n_players=None, # players per game
n_games=None, # games per round
n_rounds=None, # number of games each player will play
):
if not root_dir:
now = datetime.datetime.now()
root_dir = now.strftime("... | errs = []
turns = []
for line in fileinput.input(training_log_path):
m = RE_LOG_WINNER.match(line)
if m:
winner = m.group('winner')
try:
w = eval(winner) # pylint: disable=eval-used
errs.append(-w['err'])
turns.append(w['t... | identifier_body | |
training.py | 1000
dgens = float(solver.gen_count - gen0)
if dgens > 0 and dt > 10:
training_log("time check: %s generations in %s sec: %s sec/gen\n" % (dgens, dt, dt/dgens))
time0 = time.clock()
gen0 = solver.gen_count
gen_count = solver.gen_count+1
tr... | mkdir_p | identifier_name | |
final.py | t = int(alpha*P1[0] + (1 - alpha)*P2[0])
s = int(alpha*P2[0] + (1 - alpha)*P1[0])
if (t >= 0 and t <= 255 and s >= 0 and s <= 255):
C1[0] = t
C2[0] = s
if tx_crossover > rand_t:
#a
t = int(alpha*P1[1] + (1 - alpha)*P2[1])
s = int(alpha*P... | _contrast_mask = np.absolute(image - blurred) < threshold
np.copyto(sharpened, image, where=low_contrast_mask)
| conditional_block | |
final.py | cv.threshold(dist_transform, 0.3*dist_transform.max(),255,0)
last_image2 = np.uint8(last_image)
cnts = cv.findContours(last_image2.copy(), cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)
cnts = imutils.grab_contours(cnts)
return len(cnts)
def check_neuron(path,treshold, contrast):
for str_file in os.... | (melhores, piores, medias):
x = [i for i in range(0,len(melhores))]
y_melhor = []
y_pior = []
y_media = []
for i in range(len(melhores)):
y_melhor.append(f_alpine02(melhores[i]))
y_media.append(f_alpine02(medias[i]))
y_pior.append(f_alpine02(piores[i]))
fig... | plot_evolucao_temporal | identifier_name |
final.py | [1])
s = int(alpha*P2[1] + (1 - alpha)*P1[1])
if (t >= 0 and t <= 130 and s >= 0 and s <= 130):
C1[1] = t
C2[1] = s
return (C1, C2)
# Metodo de selecao - roleta
def selecao_roleta(Fx, df):
posicao = 0
soma_acumulada = np.cumsum(Fx)
#tamanho = len(Fx)
... | new_image = cv.addWeighted( image, alpha_c, image, 0, gamma_c) #add contrast for image
image = unsharp_mask(new_image)
image_blur_gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
| random_line_split | |
final.py | cv.threshold(dist_transform, 0.3*dist_transform.max(),255,0)
last_image2 = np.uint8(last_image)
cnts = cv.findContours(last_image2.copy(), cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)
cnts = imutils.grab_contours(cnts)
return len(cnts)
def check_neuron(path,treshold, contrast):
for str_file in os.... |
def crossover(P1, P2, tx_crossover):
C1 = P1
C2 = P2
alpha = np.random.random()
rand_c = np.random.random()
rand_t = np.random.random()
if tx_crossover > rand_c:
#a
t = int(alpha*P1[0] + (1 - alpha)*P2[0])
s = int(alpha*P2[0] + (1 - alpha)*P1[0])
if (... | individuo_mutado = []
# como a taxa de mutacao eh entre 0 e 1, temos:
rand_treshrold = np.random.random()
if rand_treshrold < tx_mutacao:
individuo_mutado.append(np.random.randint(0, 255))
else:
individuo_mutado.append(individuo[0])
rand_contrast = np.random.random()
if rand... | identifier_body |
SCRIPTER.js | ) {
if (p[x].treasure) {
pts.push(p[x]);
}
}
// If there are more than two then move them
if (pts.length > 1) {
for (var y = 0; y < pts.length; ++y) {
pts[y].location ... |
return false;
},
AssertObjectXIsInCurrentRoom : function(obj) {
debugMes("AssertObjectXIsInCurrentRoom("+obj+")");
var o = OBJS.getTopObjectByName(obj);
if(o.location === GAME.currentRoom) {
return true;
}
return false;
},
AssertObjectXIsInCurrentRoomOrPack : function(o... | {
return true;
} | conditional_block |
SCRIPTER.js | {
if (p[x].treasure) {
pts.push(p[x]);
}
}
// If there are more than two then move them
if (pts.length > 1) {
for (var y = 0; y < pts.length; ++y) {
pts[y].location =... | var objX = OBJS.getExactObjectByName(x);
objX.location = GAME.currentRoom;
println("OK");
return true;
},
PrintScore : function () {
debugMes("PrintScore()");
var score = 0;
var obs = OBJS.getAllObjects();
for(var x=0;x<obs.length;++x) {
var ob = obs[x];
... | debugMes("MoveObjectXToCurrentRoom("+x+")");
| random_line_split |
my_finance_module.py | )})
Close = re.search('s\) " data-reactid="15">(.*?)<', inform)
if Close:
tmp = Close.group(1)
tmp = tmp.replace(",", "")
l.update({"Prev Close":float(tmp)})
Open = re.search('s\) " data-reactid="20">(.*?)<', inform)
if Open:
tmp = Open.group(1)
tmp = tmp.replac... | t=time.localtime()
mass.update({"time":str(t.tm_mday)+"-"+str(t.tm_mon)+"-"+str(t.tm_year)+" "+str(t.tm_hour)+":"+str(t.tm_min)+":"+str(t.tm_sec)})
return mass
####################################################
def preprocess_mass(strings,t,init_point):
Mass_DF={}
for str1 in strings:
# M... | tzset()
| identifier_name |
my_finance_module.py | })
Close = re.search('s\) " data-reactid="15">(.*?)<', inform)
if Close:
tmp = Close.group(1)
tmp = tmp.replace(",", "")
l.update({"Prev Close":float(tmp)})
Open = re.search('s\) " data-reactid="20">(.*?)<', inform)
if Open:
tmp = Open.group(1)
tmp = tmp.replace... | fig = plt.figure(figsize=(12, 8))
ax = fig.add_subplot(111)
text1 = acc_str + '\n' + ma_str +'\n' +mde_str
ax.text(0.02, 0.90, text1, bbox=dict(facecolor='white', alpha=0.7), transform=ax.transAxes, fontsize=12)
ax.plot(time_interval1, y_pred, 'r-', label="predict", linewidth=2)
a... | '] = time_interval['hour'].astype('str') + ":" + time_interval['minute'].astype('str') + ":" + \
time_interval['sec'].astype('str')
fmt = dates.DateFormatter("%H:%M:%S")
time_interval1 = [dt.datetime.strptime(i, "%H:%M:%S") for i in time_interval['date']]
# оцениваем качество пр... | identifier_body |
my_finance_module.py | )})
Close = re.search('s\) " data-reactid="15">(.*?)<', inform)
if Close:
tmp = Close.group(1)
tmp = tmp.replace(",", "")
l.update({"Prev Close":float(tmp)})
Open = re.search('s\) " data-reactid="20">(.*?)<', inform)
if Open:
tmp = Open.group(1)
tmp = tmp.replac... | time_interval['sec'].astype('str')
fmt = dates.DateFormatter("%H:%M:%S")
time_interval1 = [dt.datetime.strptime(i, "%H:%M:%S") for i in time_interval['date']]
# оцениваем качество предсказаний
accuracy = my_mean_sqeared_error(Y[-(test_col):] , y_pred1[-(test_col):] )
acc... | time_interval['date'] = time_interval['hour'].astype('str') + ":" + time_interval['minute'].astype('str') + ":" + \ | random_line_split |
my_finance_module.py | })
Close = re.search('s\) " data-reactid="15">(.*?)<', inform)
if Close:
tmp = Close.group(1)
tmp = tmp.replace(",", "")
l.update({"Prev Close":float(tmp)})
Open = re.search('s\) " data-reactid="20">(.*?)<', inform)
if Open:
tmp = Open.group(1)
tmp = tmp.replace... | ax.xaxis.set_major_formatter(fmt)
majorFormatter = FormatStrFormatter('%.3f%%')
ax.yaxis.set_major_formatter(majorFormatter)
minorLocator = AutoMinorLocator(n=2)
ax.xaxis.set_minor_locator(minorLocator)
ax.xaxis.set_minor_formatter(fmt)
ax.set_title('стоимость акций ' + str1... | t(facecolor='white', alpha=0.7), transform=ax.transAxes, fontsize=12)
ax.plot(time_interval1, y_pred, 'r-', label="predict", linewidth=2)
ax.plot(time_interval1[:-point_pred], Y[-(test_col + train_point_print):], 'bo--', label="averaged sample", linewidth=1)
# ax.plot(time_interval1[:-point_pred], Y[-... | conditional_block |
ante.go | (tx StdTx) StdFee {
return NewStdFee(txparam.DefaultMsgGas*uint64(len(tx.Msgs)), tx.Fee.GasPrice)
}
// NewAnteHandler returns an AnteHandler that checks and increments sequence
// numbers, checks signatures & account numbers, and deducts fees from the first
// signer.
func NewAnteHandler(ak AccountKeeper, fck FeeColl... | EstimateFee | identifier_name | |
ante.go | Tx.Fee.GasPrices", stdTx.Fee.GasPrice)
log.Debugln("NewAnteHandler:stdTx.Fee", stdTx.Fee)
if !ok {
// Set a gas meter with limit 0 as to prevent an infinite gas meter attack
// during runTx.
newCtx = SetGasMeter(simulate, ctx, 0)
return newCtx, sdk.ErrInternal("tx must be StdTx").Result(), true
}
p... |
if res := ValidateMemo(stdTx, params); !res.IsOK() {
return newCtx, res, true
}
// stdSigs contains the sequence number, account number, and signatures.
// When simulating, this would just be a 0-length slice.
signerAddrs := stdTx.GetSigners()
signerAccs := make([]Account, len(signerAddrs))
isGenesi... | {
newCtx.GasMeter().UseGas(sdk.Gas(txparam.DefaultMsgGas*uint64(len(stdTx.Msgs))), "AnteHandler")
} | conditional_block |
ante.go | stdTx.Fee.GasPrices", stdTx.Fee.GasPrice)
log.Debugln("NewAnteHandler:stdTx.Fee", stdTx.Fee)
if !ok {
// Set a gas meter with limit 0 as to prevent an infinite gas meter attack
// during runTx.
newCtx = SetGasMeter(simulate, ctx, 0)
return newCtx, sdk.ErrInternal("tx must be StdTx").Result(), true |
params := ak.GetParams(ctx)
// Ensure that the provided fees meet a minimum threshold for the validator,
// if this is a CheckTx. This is only for local mempool purposes, and thus
// is only ran on check tx.
// junying-todo, 2019-11-07
// Check if Fee.Amount > Fee.Gas * minGasPrice or not
// It can be r... | } | random_line_split |
ante.go | 019-10-24
// this is enabled again in order to handle non-htdfservice txs.
defer func() {
if r := recover(); r != nil {
switch rType := r.(type) {
case sdk.ErrorOutOfGas:
log := fmt.Sprintf(
"out of gas in location: %v; gasWanted: %d, gasUsed: %d",
rType.Descriptor, stdTx.Fee.GasWanted, ... | {
// If pubkey is not known for account, set it from the StdSignature.
pubKey := acc.GetPubKey()
if simulate {
// In simulate mode the transaction comes with no signatures, thus if the
// account's pubkey is nil, both signature verification and gasKVStore.Set()
// shall consume the largest amount, i.e. it take... | identifier_body | |
main.py | (self, exc_type, exc_val, exc_tb):
super(MyLife, self).__exit__(exc_type, exc_val, exc_tb)
def get_data(self):
"""
Takes self.url (for a general MyLife search), scrapes the site data, and adds
it to the self.data_from_website DataFrame.
MyLife keeps its full data set on... | __exit__ | identifier_name | |
main.py | (self):
"""
Takes self.url (for a general MyLife search), scrapes the site data, and adds
it to the self.data_from_website DataFrame.
MyLife keeps its full data set on the page for the specific record, so self._gather_deep_data() can be used
to pull that deeper data.
... | personal_details = [_ for _ in personal_details if len(_) == 2]
personal_details = {detail.lower().replace(' ', '_'): value for
detail, value in personal_details if value != 'Add Info'}
birth_date = personal_details.pop('date_of_birth')
if... | personal_details = personal_details.find_all(class_='item-container')
personal_details = [detail.text.split(': ') for detail in personal_details] | random_line_split |
main.py | (self):
"""
Takes self.url (for a general MyLife search), scrapes the site data, and adds
it to the self.data_from_website DataFrame.
MyLife keeps its full data set on the page for the specific record, so self._gather_deep_data() can be used
to pull that deeper data.
... | return _persons
with self.driver(self.DRIVER_DIR) as driver:
driver.get(url)
driver.fullscreen_window()
time.sleep(2)
txt = driver.page_source
soup = bs(txt, 'html.parser')
profile_data = soup.find(type="application/ld+json")
... | """
Takes a URL for a specific MyLife record, scrapes the JSON data and returns a dictionary.
:param url: url for which a deeper set of data is to be gathered.
:return:
"""
def _nested_persons(persons):
_persons = list()
for person_ in persons:
... | identifier_body |
main.py | 1]),
'familyName': name[-1],
'url': hit_url,
'address': address,
'workLocation': work_location,
'alumniOf': alumni_of,
}
def _refine_search(search_str, options):
"""
Takes a list of WebElements a... | automobile = [detail.text.split(': ') for detail in automobile.find_all(class_='item-container')]
automobile = {detail.lower().replace(' ', '_'): value for
detail, value in automobile if value != 'Add Info'}
if len(automobile) == 0:
cont... | conditional_block | |
mod.rs | is more consistent
// FIXME: Only 64-bit architectures are supported by the below values
data.insert(Type::u8, TypeTableEntry::new(1, 1));
data.insert(Type::u16, TypeTableEntry::new(2, 2));
data.insert(Type::u32, TypeTableEntry::new(4, 4));
data.insert(Type::u64, T... | // e.g.: `let x: u32 = y.a;`
// FieldAlias(),
}
pub struct AllocationTable {
// Map of ((function_name, variable name) -> variable's usage)
pub allocations: HashMap<(String, String), MemoryUsage>,
}
impl AllocationTable {
pub fn new() -> Self {
Self {
allocations: HashMap::new(... | // TODO: References an existing variable -> ??
// e.g.: `let x: &u32 = &y;`
// Borrow(&'input str),
// TODO: Aliases a field of an existing variable -> ?? | random_line_split |
mod.rs | is more consistent
// FIXME: Only 64-bit architectures are supported by the below values
data.insert(Type::u8, TypeTableEntry::new(1, 1));
data.insert(Type::u16, TypeTableEntry::new(2, 2));
data.insert(Type::u32, TypeTableEntry::new(4, 4));
data.insert(Type::u64, T... | (&mut self, name: &str) -> Result<&mut VariableData, String> {
if let Some(&index) = self.all_variables.get(name) {
return Ok(self.scopes[index].get_var_data_mut(name));
}
Err(format!("No variable `{}` in scope", name))
}
// NOTE: Program is valid at this point. No safety c... | get_variable_mut | identifier_name |
mod.rs | is more consistent
// FIXME: Only 64-bit architectures are supported by the below values
data.insert(Type::u8, TypeTableEntry::new(1, 1));
data.insert(Type::u16, TypeTableEntry::new(2, 2));
data.insert(Type::u32, TypeTableEntry::new(4, 4));
data.insert(Type::u64, T... | else {
Err(format!("Type `{}` is not valid", t))
}
}
}
}
/// Returns alignment of the type in bytes
fn alignment_of(&self, t: &Type) -> usize {
match t {
// TODO: Alignment should be same as pointer type
Type::Referenc... | {
Ok(())
} | conditional_block |
rtppacket.go | either an SR or RR
// identifier
if this.header.marker != 0 {
if this.header.payloadtype == (RTP_RTCPTYPE_SR & 127) { // don't check high bit (this was the marker!!)
return errors.New("ERR_RTP_PACKET_INVALIDPACKET")
}
if this.header.payloadtype == (RTP_RTCPTYPE_RR & 127) {
return errors.New("ERR_RTP_PACK... | GetReceiveTime | identifier_name | |
rtppacket.go | ) ParseRawPacket(rawpack *RawPacket) error {
if !rawpack.IsRTP() { // If we didn't receive it on the RTP port, we'll ignore it
return errors.New("ERR_RTP_PACKET_INVALIDPACKET")
}
this.packet = make([]byte, len(rawpack.GetData()))
copy(this.packet, rawpack.GetData())
this.header = NewRTPHeader()
if err := this... |
// We'll check if this is possibly a RTCP packet. For this to be possible
// the marker bit and payload type combined should be either an SR or RR
// identifier
if this.header.marker != 0 {
if this.header.payloadtype == (RTP_RTCPTYPE_SR & 127) { // don't check high bit (this was the marker!!)
return errors.N... | {
return errors.New("ERR_RTP_PACKET_INVALIDPACKET")
} | conditional_block |
rtppacket.go | Packet) ParseRawPacket(rawpack *RawPacket) error {
if !rawpack.IsRTP() { // If we didn't receive it on the RTP port, we'll ignore it
return errors.New("ERR_RTP_PACKET_INVALIDPACKET")
}
this.packet = make([]byte, len(rawpack.GetData()))
copy(this.packet, rawpack.GetData())
this.header = NewRTPHeader()
if err :... | } else {
numpadbytes = 0
}
payloadlength = len(this.packet) - numpadbytes - payloadoffset
if payloadlength < 0 {
return errors.New("ERR_RTP_PACKET_INVALIDPACKET")
}
return nil
}
/** Creates a new buffer for an RTP packet and fills in the fields according to the specified parameters.
* If \c maxpacksize i... | if numpadbytes > len(this.packet)-payloadoffset {
return errors.New("ERR_RTP_PACKET_INVALIDPACKET")
} | random_line_split |
rtppacket.go | ) ParseRawPacket(rawpack *RawPacket) error {
if !rawpack.IsRTP() { // If we didn't receive it on the RTP port, we'll ignore it
return errors.New("ERR_RTP_PACKET_INVALIDPACKET")
}
this.packet = make([]byte, len(rawpack.GetData()))
copy(this.packet, rawpack.GetData())
this.header = NewRTPHeader()
if err := this... |
/** Sets the extended sequence number of this packet to \c seq. */
// func (this *RTPPacket) SetExtendedSequenceNumber(seq uint32) {
// this.extseqnr = seq
// }
/** Returns the timestamp of this packet. */
func (this *RTPPacket) GetTimestamp() uint32 {
return this.header.timestamp
}
/** Returns the SSRC identifie... | {
return this.header.sequencenumber //uint16(this.extseqnr & 0x0000FFFF)
} | identifier_body |
pxer.js | w Pxer();
myPxer.initialize();
nutjs.addEve(myPxer.px.bn_run,'click',function(){
if(myPxer.just_get()){
nutjs.ll("将采用获取单图方式");
return;
}else if(myPxer.read()){//可以批量get
nutjs.ll("将采用批量获取方式");
myPxer.px.pxer_showState.style.display="block";
}else{
nutjs.le("Pxer不知道该怎么做");
};
});
if(bn === true... | myPxer=ne | identifier_name | |
pxer.js | "http://#server#.pixiv.net/img-original/img/#date#/#workid#_p#picnum#.#fx#",
"http://#server#.pixiv.net/c/1200x1200/img-master/img/#date#/#workid#_p#picnum#_master1200.jpg",
"http://#server#.pixiv.net/c/600x600/img-master/img/#date#/#workid#_p0_master1200.jpg",
""
],
'sids':["http://#server#.pixiv.net/c/6... | mp_arr=html.match(reg);
for(var i=0;i<temp_arr.length;i++){
var obj=new Object();
var arr=reg.exec(temp_arr[i]);
if(! /^\//.test(arr[1]))arr[1]="/"+arr[1];
obj.url="http://www.pixiv.net"+arr[1];
reg.lastIndex=0;//因为启用全局调用了exec
if(/ugoku\-illust/.test(arr[2])){
obj.type="zip";
}else if(/ | identifier_body | |
pxer.js | reg=/<a[^<>]*?href="([^"<>]*)"[^<>]*?class="(work\s+_work[^<>"]*)"[^<>]*>/img;
var temp_arr=html.match(reg);
for(var i=0;i<temp_arr.length;i++){
var obj=new Object();
var arr=reg.exec(temp_arr[i]);
if(! /^\//.test(arr[1]))arr[1]="/"+arr[1];
obj.url="http://www.pixiv.net"+arr[1];
reg.lastIndex=0;//因为启用全局调用了... | ion(){
var reg=/<img[^<>]*data-src[^"]"( | conditional_block | |
pxer.js | this.thread=this.px.config_thread.value;
this.maxThread = +(this.queue.length>this.thread?this.thread:this.queue.length);
//显示效果
this.px.show_wait.innerHTML=this.wait;
this.px.show_thread.innerHTML=this.maxThread;
/*显示结果*/
this.queue_show_update();
return true;
}
};
return false;
};
Pxer.pro... | this.queue.push(document.URL+"&p="+(i+1));
};
/*初始化线程数,不允许线程超过页数*/ | random_line_split | |
value.rs | <ValueWrapper>,
}
impl Default for Set {
fn default() -> Self {
Set {
mutability: IterableMutability::Mutable,
content: LinkedHashSet::new(),
}
}
}
impl Set {
pub fn empty() -> Value {
Value::new(Set::default())
}
pub fn from<V: Into<Value>>(values:... | }
}
fn get_hash(&self) -> Result<u64, ValueError> {
Ok(self
.content
.iter()
.map(|v| v.precomputed_hash)
.map(Wrapping)
.fold(Wrapping(0_u64), |acc, v| acc + v)
.0)
}
not_supported!(mul, set_at);
not_supported... | } else {
Err(ValueError::IncorrectParameterType) | random_line_split |
value.rs | Wrapper>,
}
impl Default for Set {
fn default() -> Self {
Set {
mutability: IterableMutability::Mutable,
content: LinkedHashSet::new(),
}
}
}
impl Set {
pub fn empty() -> Value {
Value::new(Set::default())
}
pub fn from<V: Into<Value>>(values: Vec<V... | else {
let mut v = v.clone();
v.downcast_apply_mut(|x: &mut Set| -> ValueResult {
x.mutability.test()?;
f(&mut x.content)
})
}
}
pub fn compare<Return>(
v1: &Value,
v2: &Value,
f: &Fn(
&LinkedHashSe... | {
Err(ValueError::IncorrectParameterType)
} | conditional_block |
value.rs | Wrapper>,
}
impl Default for Set {
fn default() -> Self {
Set {
mutability: IterableMutability::Mutable,
content: LinkedHashSet::new(),
}
}
}
impl Set {
pub fn empty() -> Value {
Value::new(Set::default())
}
pub fn from<V: Into<Value>>(values: Vec<V... |
fn is_descendant(&self, other: &TypedValue) -> bool {
self.content
.iter()
.any(|x| x.value.same_as(other) || x.value.is_descendant(other))
}
fn slice(
&self,
start: Option<Value>,
stop: Option<Value>,
stride: Option<Value>,
) -> ValueRe... | {
Ok(Value::new(
self.content.contains(&ValueWrapper::new(other.clone())?),
))
} | identifier_body |
value.rs | Wrapper>,
}
impl Default for Set {
fn | () -> Self {
Set {
mutability: IterableMutability::Mutable,
content: LinkedHashSet::new(),
}
}
}
impl Set {
pub fn empty() -> Value {
Value::new(Set::default())
}
pub fn from<V: Into<Value>>(values: Vec<V>) -> Result<Value, ValueError> {
let mut ... | default | identifier_name |
dsp.py |
self.fft_plot_filter = ExpFilter(np.tile(1e-1, n_fft_bins), alpha_decay=0.5, alpha_rise=0.99)
self.mel_gain = ExpFilter(np.tile(1e-1, n_fft_bins), alpha_decay=0.01, alpha_rise=0.99)
self.mel_smoothing = ExpFilter(np.tile(1e-1, n_fft_bins), alpha_decay=0.5, alpha_rise=0.99)
self.gain = ... | led_count = self._device_config["led_count"] | conditional_block | |
dsp.py | _decay=0.001, alpha_rise=0.99)
self.r_filt = ExpFilter(np.tile(0.01, led_count // 2), alpha_decay=0.2, alpha_rise=0.99)
self.g_filt = ExpFilter(np.tile(0.01, led_count // 2), alpha_decay=0.05, alpha_rise=0.3)
self.b_filt = ExpFilter(np.tile(0.01, led_count // 2), alpha_decay=0.1, alpha_rise=0.5)... | (self, num_bands, freq_min, freq_max, num_fft_bands):
"""
Returns centerfrequencies and band edges for a mel filter bank
Parameters
----------
num_bands : int
Number of mel bands.
freq_min : scalar
Minimum frequency for the first band.
freq... | melfrequencies_mel_filterbank | identifier_name |
dsp.py | self.b_filt = ExpFilter(np.tile(0.01, led_count // 2), alpha_decay=0.1, alpha_rise=0.5)
self.common_mode = ExpFilter(np.tile(0.01, led_count // 2), alpha_decay=0.99, alpha_rise=0.01)
self.p_filt = ExpFilter(np.tile(1, (3, led_count // 2)), alpha_decay=0.1, alpha_rise=0.99)
self.volume = ... | self._config = config
self._device_config = device_config
# Initialise filters etc. I've no idea what most of these are for but I imagine I won't be getting rid of them soon.
n_fft_bins = self._config["general_settings"]["n_fft_bins"]
min_volume_threshold = self._config["general_setting... | identifier_body | |
dsp.py | _decay=0.001, alpha_rise=0.99)
self.r_filt = ExpFilter(np.tile(0.01, led_count // 2), alpha_decay=0.2, alpha_rise=0.99)
self.g_filt = ExpFilter(np.tile(0.01, led_count // 2), alpha_decay=0.05, alpha_rise=0.3)
self.b_filt = ExpFilter(np.tile(0.01, led_count // 2), alpha_decay=0.1, alpha_rise=0.5)... | An example is shown in the following figure:
.. plot::
from pylab import plt
import melbank
f1, f2 = 1000, 8000
melmat, (melfreq, fftfreq) = melbank.compute_melmat(6, f1, f2, num_fft_bands=4097)
fig, ax = plt.subplots(figsize=(8, 3))
ax.plot(fftfreq, melmat.T)
... | """This class implements a Mel Filter Bank.
In other words it is a filter bank with triangular shaped bands
arranged on the mel frequency scale. | random_line_split |
taskGraph.py | yaml.constructor.yaml_constructors[
u'tag:yaml.org,2002:timestamp'] = \
yaml.constructor.yaml_constructors[u'tag:yaml.org,2002:str']
obj = yaml.load(f)
t = TaskGraph(obj)
return t
def export_task_speclist(self):
tlist_od = [] # task list ordered... | random_line_split | ||
taskGraph.py | (object):
def __init__(self, values):
self.values = tuple([i[1] for i in values])
self.__keys = tuple([i[0] for i in values])
self.__dict = OrderedDict(values)
def __iter__(self):
return iter(self.values)
def __getitem__(self, key):
if isinstance(key, int):
... | Results | identifier_name | |
taskGraph.py | .__tlist):
self.__index = None
raise StopIteration
task = self.__tlist[idx]
self.__index = idx + 1
return task
def __getitem__(self, key):
# FIXME: This is inconsistent. Above for __contains__, __iter__, and
# __next__, the returned object is a Ta... |
def start_labwidget(self):
from IPython.display import display
display(self.draw())
@staticmethod
def register_lab_node(module_name, class_obj):
"""
Register the node class for the Greenflowlab. It put the class_obj
into a sys.modules with `module_name`. It will re... | inode = node_in['from_node']
self.__find_roots(inode, inputs, consider_load) | conditional_block |
taskGraph.py |
def __len__(self):
return len(self.__task_list)
def __iter__(self):
self.__index = 0
self.__tlist = list(self.__task_list.values())
return self
def __next__(self):
idx = self.__index
if idx is None or idx == len(self.__tlist):
self.__index = No... | return True if task_id in self.__task_list else False | identifier_body | |
1.cifar10_classification_lightmodel.py | , and
# Geoffrey Hinton. Classes are: airplane, automobile, bird, cat, deer,
# dog, frog, horse, ship, truck
from keras.datasets import cifar10
# 1.3 Basic classes for specifying and training a neural network
# Keras has two types of models Sequential and Model Class for complex models
# ... | # exp(xi)/Sigma(exp(xk))
"""
Softmax
If we take an input of [1, 2, 3, 4, 1, 2, 3], the softmax of that
is [0.024, 0.064, 0.175, 0.475, 0.024, 0.064, 0 |
# 7.2.2 Final output layer; softmax
# About softmax: https://en.wikipedia.org/wiki/Softmax_function
| random_line_split |
1.cifar10_classification_lightmodel.py | will have 512 neurons
#%% C. Fetch cifar10 images & transform
"""
About CIFAR-10 images
Ref: https://en.wikipedia.org/wiki/CIFAR-10
The CIFAR-10 dataset (Canadian Institute For Advanced Research) is a
collection of images that are commonly used to train machine learning
and computer visi... | plot_history | identifier_name | |
1.cifar10_classification_lightmodel.py | datasets
for machine learning research. The CIFAR-10 dataset contains 60,000 32x32
color images in 10 different classes. The 10 different classes represent
airplanes, cars, birds, cats, deer, dogs, frogs, horses, ships, and trucks.
There are 6,000 images of each class. (Alex Krizhevsky)
"""
# 3. Download, u... | val_acc = history.history['val_acc']
tr_acc=history.history['acc']
epochs = range(1, len(val_acc) +1)
plt.plot(epochs,val_acc, 'b', label = "Validation accu")
plt.plot(epochs, tr_acc, 'r', label = "Training accu")
plt.title("Training and validation accuracy")
plt.legend()
plt.show() | identifier_body | |
plugin.py | #! /usr/bin/env python
# -*- coding: utf-8 -*-
"""
Module that contains Maya DCC plugin specific implementation
"""
from __future__ import print_function, division, absolute_import
import os
import json
import logging
import maya.cmds as cmds
import maya.mel as mel
import artella
from artella import dcc
from artel... |
# This can happen when local root path cannot be retrieved from Artella Drive
if isinstance(artella_local_root_path, dict):
return
artella_local_root_path = utils.clean_path(artella_local_root_path)
if utils.is_python2():
artella_local_root_path = artella_local... | logger.warning('No Project Path to setup. Skipping setup project ...')
return | conditional_block |
plugin.py | #! /usr/bin/env python
# -*- coding: utf-8 -*-
"""
Module that contains Maya DCC plugin specific implementation
"""
from __future__ import print_function, division, absolute_import
import os
import json
import logging
import maya.cmds as cmds
import maya.mel as mel
import artella
from artella import dcc
from artel... | if os.path.isfile(version_file_path):
try:
with open(version_file_path) as fh:
version_data = json.load(fh)
version_found = version_data.get('version', None)
if version_found:
... | def __init__(self, artella_drive_client):
super(ArtellaMayaPlugin, self).__init__(artella_drive_client=artella_drive_client)
self._references_found = list()
def get_version(self, force_update=False):
"""
Returns current DCC plugin version
:param bool force_update: Where or... | identifier_body |
plugin.py | #! /usr/bin/env python
# -*- coding: utf-8 -*-
"""
Module that contains Maya DCC plugin specific implementation
"""
from __future__ import print_function, division, absolute_import
import os
import json
import logging
import maya.cmds as cmds
import maya.mel as mel
import artella
from artella import dcc
from artel... | :param bool create_callbacks: Whether or not DCC callbacks should be created
:return: True if the initialization was successful; False otherwise.
:rtype: bool
"""
# Force Maya MEL stack trace on before we start using the plugin
maya_utils.force_mel_stack_trace_on()
... | :param bool show_dialogs: Whether dialogs should appear during plugin initialization or not
:param bool create_menu: Whether menu should be created or not | random_line_split |
plugin.py | #! /usr/bin/env python
# -*- coding: utf-8 -*-
"""
Module that contains Maya DCC plugin specific implementation
"""
from __future__ import print_function, division, absolute_import
import os
import json
import logging
import maya.cmds as cmds
import maya.mel as mel
import artella
from artella import dcc
from artel... | (self, *args):
"""
Internal callback function that is called after a Maya reference is loaded
:param args:
"""
if not self.is_artella_path():
return
self.validate_environment_for_callback('AfterLoadReference')
def _before_reference_check(self, maya_fil... | _after_load_reference | identifier_name |
model.py | False
After that, the "embeds" are linearly mapped to "gamma" and "bias"
These "gamma" and "bias" are applied to the outputs like in batch normalization
with affine = True (see definition of batch normalization for reference)
"""
def __init__(self, num_features: int, embed_features: int):
... | nn.ReLU(),
torch.nn.utils.spectral_norm(nn.Conv2d(min_channels, 3, 3, padding=1)),
nn.Sigmoid()
)
def forward(self, noise, labels):
# TODO
if self.use_class_condition:
noise = torch.cat((self.embed(labels), noise), dim=-1)
outputs... | super(Generator, self).__init__()
self.output_size = 4 * 2**num_blocks
# TODO
self.max_channels = max_channels
self.use_class_condition = use_class_condition
self.embed = torch.nn.Embedding(num_classes, noise_channels)
if self.use_class_condition:
noise_chan... | identifier_body |
model.py |
After that, the "embeds" are linearly mapped to "gamma" and "bias"
These "gamma" and "bias" are applied to the outputs like in batch normalization
with affine = True (see definition of batch normalization for reference)
"""
def __init__(self, num_features: int, embed_features: int):
s... |
return outputs
class Generator(nn.Module):
"""
Generator network (8 points)
TODO:
- Implement an option to condition the synthesis on trainable class embeddings
(use nn.Embedding module with noise_channels as the size of each embed)
- Concatenate input noise with class ... | outputs = self.down(outputs) | conditional_block |
model.py |
After that, the "embeds" are linearly mapped to "gamma" and "bias"
These "gamma" and "bias" are applied to the outputs like in batch normalization
with affine = True (see definition of batch normalization for reference)
"""
def __init__(self, num_features: int, embed_features: int):
s... | (self,
in_channels: int,
out_channels: int,
embed_channels: int = None,
batchnorm: bool = False,
upsample: bool = False,
downsample: bool = False):
super(PreActResBlock, self).__init__()
# TODO: define ... | __init__ | identifier_name |
model.py | False
After that, the "embeds" are linearly mapped to "gamma" and "bias"
These "gamma" and "bias" are applied to the outputs like in batch normalization
with affine = True (see definition of batch normalization for reference)
"""
def __init__(self, num_features: int, embed_features: int):
... | TODO:
- Define a convolutional part of the discriminator similarly to
the generator blocks, but in the inverse order, with downsampling, and
without batch normalization
- At the end of the convolutional part apply ReLU and sum pooling
TODO: implement projection discrim... | """
Discriminator network (8 points)
| random_line_split |
simpleLSTM.py | _weight(options['dim_proj']),
ortho_weight(options['dim_proj']),
ortho_weight(options['dim_proj']),
ortho_weight(options['dim_proj'])], axis=1)
params[_p(prefix, 'W')] = W
U = numpy.concatenate([ortho_weight(options['dim_proj']),
... |
preact = T.dot(h_, tparams[_p(prefix, 'U')]) # (4*dim)
preact += x_ # h 延时后加权的目标维数 和 Wx+b的维数相同,都是LSTM单元的个数的4倍,可以直接相加
i = T.nnet.sigmoid(_slice(preact, 0, dim_proj)) # input gate
f = T.nnet.sigmoid(_slice(preact, 1, dim_proj)) # forget gate
o = T.nnet.sigm... | c_ : 前一时刻单元的Cell值
'''
| conditional_block |
simpleLSTM.py | ortho_weight(options['dim_proj']),
ortho_weight(options['dim_proj']),
ortho_weight(options['dim_proj']),
ortho_weight(options['dim_proj'])], axis=1)
params[_p(prefix, 'W')] = W
U = numpy.concatenate([ortho_weight(options['dim_proj'... |
proj = lstm_layer(tparams, x, options,
prefix=options['encoder'])
proj = theano.tensor.reshape(proj, (proj.shape[0], proj.shape[2]))
# pred = T.tanh(T.dot(proj, tparams['U']) + tparams['b'])
pred = T.dot(proj, tparams['U']) + tparams['b']
f_pred_prob... | random_line_split | |
simpleLSTM.py | ortho_weight(options['dim_proj']),
ortho_weight(options['dim_proj']),
ortho_weight(options['dim_proj']),
ortho_weight(options['dim_proj'])], axis=1)
params[_p(prefix, 'W')] = W
U = numpy.concatenate([ortho_weight(options['dim_proj'... | U weights.
lrate=0.0001, # Learning rate for sgd (not used for adadelta and rmsprop)
n_words=10000, # Vocabulary size
optimizer=adadelta, # sgd, adadelta and rmsprop available, sgd very hard to use, not recommanded (probably need momentum and decaying learning rate).
encoder='lstm', # TODO: can be ... | ied to the | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.