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 |
|---|---|---|---|---|
pkgindexer.py | dbstore
from conary import versions
from conary.repository import repository
import os
import time
hiddenLabels = [
versions.Label('conary.rpath.com@rpl:rpl1'),
versions.Label('conary.rpath.com@ravenous:bugblatterbeast')
]
class PackageIndexer(scriptlibrary.SingletonScript):
db = None
cfgPath = conf... | exitcode = 0
self.db.commit()
return exitcode
class UpdatePackageIndexExternal(PackageIndexer):
logFileName = 'package-index-external.log'
def updateMark(self):
# This code exists to overcome the situation where there are no
# internal projects on the rBuilder,... | else:
self.log.info("Completed successfully: %d" % len(inserts)) | random_line_split |
pkgindexer.py | dbstore
from conary import versions
from conary.repository import repository
import os
import time
hiddenLabels = [
versions.Label('conary.rpath.com@rpl:rpl1'),
versions.Label('conary.rpath.com@ravenous:bugblatterbeast')
]
class PackageIndexer(scriptlibrary.SingletonScript):
db = None
cfgPath = conf... |
inserts = []
updates = []
for projectId, troveName, version in packageIndex:
cu.execute("""SELECT pkgId, version FROM PackageIndex
WHERE projectId=? AND name=?""",
projectId, troveName)
re... | for label in packageDict[troveName]:
packageIndex.append((labelMap[label], troveName,
max(packageDict[troveName][label]))) | conditional_block |
pkgindexer.py | store
from conary import versions
from conary.repository import repository
import os
import time
hiddenLabels = [
versions.Label('conary.rpath.com@rpl:rpl1'),
versions.Label('conary.rpath.com@ravenous:bugblatterbeast')
]
class PackageIndexer(scriptlibrary.SingletonScript):
db = None
cfgPath = config.... | (self, aLockPath = scriptlibrary.DEFAULT_LOCKPATH,
aMintServer=None):
self.cfg = config.MintConfig()
self.cfg.read(self.cfgPath)
if self.logFileName:
self.logPath = os.path.join(self.cfg.logPath, self.logFileName)
scriptlibrary.SingletonScript.__init__(self, aLoc... | __init__ | identifier_name |
pkgindexer.py | dbstore
from conary import versions
from conary.repository import repository
import os
import time
hiddenLabels = [
versions.Label('conary.rpath.com@rpl:rpl1'),
versions.Label('conary.rpath.com@ravenous:bugblatterbeast')
]
class PackageIndexer(scriptlibrary.SingletonScript):
db = None
cfgPath = conf... | labels = {}
projectIds = {}
netclients = {}
hasErrors = False
for projectId, hostname, localMirror in cu.fetchall():
try:
self.log.info("Retrieving labels from %s...", hostname)
l, repMap, userMap, entMap = labelsTable.getLabelsForProj... | self.log.info("Updating package index")
self.db = dbstore.connect(self.cfg.dbPath, driver = self.cfg.dbDriver)
self.db.connect()
self.db.loadSchema()
cu = self.db.cursor()
labelsTable = projects.LabelsTable(self.db, self.cfg)
self.db.commit()
cu = self.db.cursor... | identifier_body |
libAIRSL3Data.py | ensure_dir : check if the directory f exist. If not, it is created
'''
d = os.path.dirname(f)
if not os.path.exists(f):
os.makedirs(f)
#-----------------------------------------------------------------------------
def loc_ctio():
return(Longitude_ctio,Latitude_ctio,Altitude_ctio)
def ... |
elif obs=='lsst':
loc=loc_lsst()
elif obs=='ohp':
loc=loc_ohp()
else:
loc=loc_none()
return loc
#-------------------------------------------------------------------... | loc=loc_ctio() | conditional_block |
libAIRSL3Data.py | ensure_dir : check if the directory f exist. If not, it is created
'''
d = os.path.dirname(f)
if not os.path.exists(f):
os.makedirs(f)
#-----------------------------------------------------------------------------
def loc_ctio():
return(Longitude_ctio,Latitude_ctio,Altitude_ctio)
def ... | (X,Y,data,sizex=8,sizey=8,labelx='longitude',labely='latitude',labelz='Unit',title=''):
'''
PlotData(X,Y,data,sizex=8,sizey=8,labelx='longitude',labely='latitude',labelz='Unit',title='')
==============================================================================================
Plot in matplotlib th... | PlotData | identifier_name |
libAIRSL3Data.py | ensure_dir : check if the directory f exist. If not, it is created
'''
d = os.path.dirname(f)
if not os.path.exists(f):
os.makedirs(f)
#-----------------------------------------------------------------------------
def loc_ctio():
return(Longitude_ctio,Latitude_ctio,Altitude_ctio)
def ... |
#-----------------------------------------------------------------------------
#--------------------------------------------------------------------------------
def AreaSelect(X,Y,data,LongMin,LongMax,LatMin,LatMax):
'''
AreaSelect(X,Y,data,LongMin,LongMax,LatMin,LatMax)
==============================... | '''
GetData(file,datafield) : read the data labeled datafield in file
=================================================================
Retrieve data from a HDF file
input :
------
file : name of input file
datafield : label of required data field
output:
-----... | identifier_body |
libAIRSL3Data.py | ensure_dir : check if the directory f exist. If not, it is created
'''
d = os.path.dirname(f)
if not os.path.exists(f):
os.makedirs(f)
#-----------------------------------------------------------------------------
def loc_ctio():
return(Longitude_ctio,Latitude_ctio,Altitude_ctio)
d... | selected_Y=Y[selected_lat_indexes,:]
sel_min_long_index=np.min(selected_long_indexes)
sel_max_long_index=np.max(selected_long_indexes)
sel_min_lat_index=np.min(selected_lat_indexes)
sel_max_lat_index=np.max(selected_lat_indexes)
extracted_data=data[sel_min_lat_index:sel_max_lat_index+1,sel_m... |
(selected_lat_indexes,selected_long_indexes)=np.where(sel_flags_longlat==True) # list of indexes
selected_X=X[:,selected_long_indexes] # all selected longitudes | random_line_split |
main.go | ").Default("").String()
minBaseQFlag := app.Flag("min-base-qual", "min base quality").Default("30").Int()
minMapQFlag := app.Flag("min-map-qual", "min mapping quality").Default("30").Int()
corrResFileFlag := app.Flag("corr-res-file", "corr result file").Default("").String()
geneFileFlag := app.Flag("gene-file", "ge... | (nc *NuclCov, codonPairArray []CodonPair) {
for _, cp := range codonPairArray {
a := cp.A.Seq[2]
b := cp.B.Seq[2]
nc.Add(a, b)
}
}
func calcP2(gene *CodonGene, maxl, minDepth int, codeTable *taxonomy.GeneticCode) (p2Res []CorrResult) {
alphabet := []byte{'A', 'T', 'G', 'C'}
for i := 0; i < gene.Len(); i++ {
... | doubleCount | identifier_name |
main.go | chan GeneSamRecords
if gffFile != "" {
gffRecMap := readGffs(gffFile)
header, recordsChan = readStrainBamFile(bamFile, gffRecMap)
} else {
header, recordsChan = readPanGenomeBamFile(bamFile)
}
var geneSet map[string]bool
if geneFile != "" {
geneSet = make(map[string]bool)
lines := readLines(geneFile)
... | {
return
} | conditional_block | |
main.go | a list of reads at a gene.
func pileupCodons(geneRecords GeneSamRecords) (codonGene *CodonGene) {
codonGene = NewCodonGene()
for _, read := range geneRecords.Records {
if checkReadQuality(read) {
codonArray := getCodons(read, geneRecords.Start, geneRecords.Strand)
for _, codon := range codonArray {
if !c... | {
f, err := os.Open(filename)
if err != nil {
log.Panic(err)
}
defer f.Close()
rd := bufio.NewReader(f)
var lines []string
for {
line, err := rd.ReadString('\n')
if err != nil {
if err != io.EOF {
log.Panic(err)
}
break
}
lines = append(lines, strings.TrimSpace(line))
}
return lines | identifier_body | |
main.go | ").Default("").String()
minBaseQFlag := app.Flag("min-base-qual", "min base quality").Default("30").Int()
minMapQFlag := app.Flag("min-map-qual", "min mapping quality").Default("30").Int()
corrResFileFlag := app.Flag("corr-res-file", "corr result file").Default("").String()
geneFileFlag := app.Flag("gene-file", "ge... | for _, res := range results {
w.WriteString(fmt.Sprintf("%d,%g,%g,%d,%s,all\n",
res.Lag, res.Value, res.Variance, res.Count, res.Type))
}
}
// pileupCodons pileup codons of a list of reads at a gene.
func pileupCodons(geneRecords GeneSamRecords) (codonGene *CodonGene) {
codonGene = NewCodonGene()
for _, read ... | random_line_split | |
inih.go | _t ini_style_t
// Scalar styles.
const (
// Let the emitter choose the style.
ini_ANY_SCALAR_STYLE ini_scalar_style_t = iota
ini_PLAIN_SCALAR_STYLE // The plain scalar style.
ini_SINGLE_QUOTED_SCALAR_STYLE // The single-quoted scalar style.
ini_DOUBLE_QUOTED_SCALAR_STYLE // The double-quoted scalar style... |
ini_MAPPING_EVENT // An MAPPING event.
ini_SCALAR_EVENT // An SCALAR event.
ini_COMMENT_EVENT // A COMMENT event.
)
// The event structure.
type ini_event_t struct {
// The event type.
typ ini_event_type_t
// The start and end of the event.
start_mark, end_mark ini_mark_t
// The node value.
value ... | ini_SECTION_INHERIT_EVENT // A SECTION-INHERIT event.
ini_SECTION_ENTRY_EVENT // A SECTION-ENTRY event. | random_line_split |
inih.go | _t ini_style_t
// Scalar styles.
const (
// Let the emitter choose the style.
ini_ANY_SCALAR_STYLE ini_scalar_style_t = iota
ini_PLAIN_SCALAR_STYLE // The plain scalar style.
ini_SINGLE_QUOTED_SCALAR_STYLE // The single-quoted scalar style.
ini_DOUBLE_QUOTED_SCALAR_STYLE // The double-quoted scalar style... | () string {
switch tt {
case ini_NO_TOKEN:
return "ini_NO_TOKEN"
case ini_DOCUMENT_START_TOKEN:
return "ini_DOCUMENT_START_TOKEN"
case ini_DOCUMENT_END_TOKEN:
return "ini_DOCUMENT_END_TOKEN"
case ini_SECTION_START_TOKEN:
return "ini_SECTION_START_TOKEN"
case ini_SECTION_INHERIT_TOKEN:
return "ini_SECTIO... | String | identifier_name |
inih.go | _t ini_style_t
// Scalar styles.
const (
// Let the emitter choose the style.
ini_ANY_SCALAR_STYLE ini_scalar_style_t = iota
ini_PLAIN_SCALAR_STYLE // The plain scalar style.
ini_SINGLE_QUOTED_SCALAR_STYLE // The single-quoted scalar style.
ini_DOUBLE_QUOTED_SCALAR_STYLE // The double-quoted scalar style... | }
func (e *ini_event_t) scalar_style() ini_scalar_style_t { return ini_scalar_style_t(e.style) }
// Nodes
const (
ini_NULL_TAG = "null" // The tag 'null' with the only possible value: null.
ini_BOOL_TAG = "bool" // The tag 'bool' with the values: true and false.
ini_STR_TAG = "str" // The tag 'str' fo... | {
switch e.typ {
case ini_NO_EVENT:
return "ini_NO_EVENT"
case ini_DOCUMENT_START_EVENT:
return "ini_DOCUMENT_START_EVENT"
case ini_DOCUMENT_END_EVENT:
return "ini_DOCUMENT_END_EVENT"
case ini_SECTION_INHERIT_EVENT:
return "ini_SECTION_INHERIT_EVENT"
case ini_SECTION_ENTRY_EVENT:
return "ini_SE... | identifier_body |
AutoCapture_runtimelog.py | ()
def _send_pushd(self, directory):
(mode, size, mtime, atime) = self._read_stats(directory)
basename = asbytes(os.path.basename(directory))
if self.preserve_times:
self._send_time(mtime, atime)
self.channel.sendall(('D%s 0 ' % mode).encode('ascii') +
... | None | identifier_body | |
AutoCapture_runtimelog.py |
# use single quotes, and put single quotes into double quotes
# the string $'b is then quoted as '$'"'"'b'
return b"'" + s.replace(b"'", b"'\"'\"'") + b"'"
# Unicode conversion functions; assume UTF-8
def asbytes(s):
"""Turns unicode into bytes, if needed.
Assumes UTF-8.
"""
if isinsta... | return s | conditional_block | |
AutoCapture_runtimelog.py | recv_dir):
raise SCPException("Local path '%s' is not a directory" %
asunicode(self._recv_dir))
rcsv = (b'', b' -r')[recursive]
prsv = (b'', b' -p')[preserve_times]
self.channel = self._open()
self._pushed = 0
self.channel.settim... | buff_size = size - pos
file_hdl.write(chan.recv(buff_size))
pos = file_hdl.tell()
if self._progress:
self._progress(path, size, pos)
msg = chan.recv(512)
if msg and msg[0:1] != b'\x00':
raise... | if size - pos <= buff_size: | random_line_split |
AutoCapture_runtimelog.py | # slice off the first byte, so this compare will work in py2 and py3
if msg and msg[0:1] == b'\x00':
return
elif msg and msg[0:1] == b'\x01':
raise SCPException(asunicode(msg[1:]))
elif self.channel.recv_stderr_ready():
msg = self.channel.recv_stderr(5... | read | identifier_name | |
structure.rs | Item = StructureEntry;
fn dyn_iter(&self) -> Box<dyn Iterator<Item = &Self::Item> + '_> {
Box::new(self.0.iter().chain(self.1.iter()))
}
fn as_dyn_iter(&self) -> &dyn DynIter<Item = Self::Item> {
self
}
}
impl<'a> DynIterMut for StructureEntryIterator<'a> {
fn dyn_iter_mut(&mut sel... | impl Position {
pub fn new(x: i32, y: i32) -> Self {
Self { x, y }
}
pub(crate) fn div_mod(&self, size: i32) -> (Position, Position) {
let div = Position::new(self.x.div_euclid(size), self.y.div_euclid(size));
let mod_ = Position::new(self.x.rem_euclid(size), self.y.rem_euclid(size)... | }
| random_line_split |
structure.rs | (&self, position: &Position) -> i32 {
(position.x - self.x).abs().max((position.y - self.y).abs())
}
/// Check whether the positions are neighbors. Return false if they are exactly the same.
#[allow(dead_code)]
pub(crate) fn is_neighbor(&self, pos2: &Position) -> bool {
[[-1, 0], [0, -1... | {
Cow::from(&[][..])
} | identifier_body | |
structure.rs | Item = StructureEntry;
fn dyn_iter(&self) -> Box<dyn Iterator<Item = &Self::Item> + '_> {
Box::new(self.0.iter().chain(self.1.iter()))
}
fn as_dyn_iter(&self) -> &dyn DynIter<Item = Self::Item> {
self
}
}
impl<'a> DynIterMut for StructureEntryIterator<'a> {
fn dyn_iter_mut(&mut sel... |
}
/// Query a set of items that this structure can output. Actual output would not happen until `output()`, thus
/// this method is immutable. It should return empty Inventory if it cannot output anything.
fn can_output(&self, _structures: &StructureDynIter) -> Inventory {
Inventory::new()
... | {
false
} | conditional_block |
structure.rs | Box::new(self.0.iter().chain(self.1.iter()))
}
fn as_dyn_iter(&self) -> &dyn DynIter<Item = Self::Item> {
self
}
}
impl<'a> DynIterMut for StructureEntryIterator<'a> {
fn dyn_iter_mut(&mut self) -> Box<dyn Iterator<Item = &mut Self::Item> + '_> {
Box::new(self.0.iter_mut().chain... | add_burner_inventory | identifier_name | |
main.py | имер", "Трубы"]
zoneNames = []
DUMP_PATH = "cargo.pckl"
class DateBase():
def __init__(self):
self.rows = []
if os.path.exists(DUMP_PATH):
with open(DUMP_PATH, "rb") as f:
self.rows = pickle.load(f)
def add(self, id, name, count, zone):
for row in self.rows... | _keys[index | identifier_name | |
main.py |
import pickle
cargoNames = ["г/к рулоны", "х/к рулоны", "слябы", "профиль", "арматура", "г/к лист", "Нарезка", "Полимер", "Трубы"]
zoneNames = []
DUMP_PATH = "cargo.pckl"
class DateBase():
def __init__(self):
self.rows = []
if os.path.exists(DUMP_PATH):
with open(DUMP_PATH, "rb") as... | def createInputForm(self):
self.inputForm = QFormLayout()
self.idInput = QLineEdit()
namesCompleter = QCompleter(cargoNames)
namesCompleter.setCaseSensitivity(False)
self.nameInput = QLineEdit()
self.nameInput.setCompleter(namesCompleter)
self.addButton = ... | self.setLayout(self.inputForm)
self.resize(400, 100)
self.setWindowTitle("Add cargo title");
| random_line_split |
main.py | import pickle
cargoNames = ["г/к рулоны", "х/к рулоны", "слябы", "профиль", "арматура", "г/к лист", "Нарезка", "Полимер", "Трубы"]
zoneNames = []
DUMP_PATH = "cargo.pckl"
class DateBase():
def __init__(self):
self.rows = []
if os.path.exists(DUMP_PATH):
with open(DUMP_PATH, "rb") as ... | ink.linkActivated.connect(self.link)
mapLink.setText('<a href="file://{}">Карта</a>'.format(os.path.join(os.getcwdb().decode("utf-8") , "map.html")))
self.cancleButton = QPushButton("Отмена", self)
self.cancleButton.clicked.connect(self.closeWidget)
self.resultForm.addWidget(mapLink)
... | h open("map_template.html") as f:
map_html = f.read()
map_html = map_html.replace("%zones", str(zones).replace("'", '"'))
with open("cargo.geojson") as f:
map_html = map_html.replace("%geojson", f.read().replace("'", '"'))
with open("map.html", "w") as f:
f... | identifier_body |
main.py | self.rows = []
if os.path.exists(DUMP_PATH):
with open(DUMP_PATH, "rb") as f:
self.rows = pickle.load(f)
def add(self, id, name, count, zone):
for row in self.rows:
if row["name"] == name and row["zone"] == zone and row["id"] == id:
row["coun... | al:
r | conditional_block | |
nfo.py | : No TVDB ID was provided...")
return None
if isinstance(tvdb_id, int):
tvdb_id = str(tvdb_id)
if not self.TVDB_ID_T.match(tvdb_id) or not isinstance(tvdb_id, str):
print(f"The provided TVDB ID {tvdb_id!r} is not valid...")
print("Expected e.g., '79216', '... |
# following sub.title tree checks and supports three different language and title scenarios
# The second scenario is the recommended option to choose if you are open to choosing any
# The third scenario should be used if you have nothing unique to state about the track | random_line_split | |
nfo.py | (self, file: str, **config: Any) -> None:
self.file = file
self.media_info = MediaInfo.parse(self.file)
self.fanart_api_key = config.get("fanart_api_key")
self.source = config.get("source")
self.note = config.get("note")
self.preview = config.get("preview")
self... | set_config | identifier_name | |
nfo.py | :
general_track = self.media_info.general_tracks[0].to_data()
tvdb_id = general_track.get("tvdb")
if not tvdb_id:
print("Warning: No TVDB ID was provided...")
return None
if isinstance(tvdb_id, int):
tvdb_id = str(tvdb_id)
if not self.T... | Return a list of a brief subtitle overview per-subtitle.
e.g.
- English, Forced, SubRip (SRT)
- English, SubRip (SRT)
- English, SDH, SubRip (SRT)
- Spanish, Latin American (SDH), SubRip (SRT)
The bit of text between the Language and the Subtitle format is the T... | identifier_body | |
nfo.py | ).zfill(2)}"]
for i, x in enumerate(self.chapters.values())
)
else:
self.chapters = {}
self.chapters_numbered = False
self.imdb = self.get_imdb_id(config.get("imdb"))
self.tmdb = self.get_tmdb_id(config.get("tmdb"))
self.tvdb = self.ge... | nlink(fp)
| conditional_block | |
driver.rs | SmallVec<[(NodeId, f64); 4]>,
}
pub struct | {
id :usize,
train: Train,
authority: f64,
step: (DriverAction, f64),
connected_signals: SmallVec<[(ObjectId, f64); 4]>,
logger: Box<Fn(TrainLogEvent)>,
activation: Activation,
timestep: Option<f64>,
}
impl Driver {
pub fn new(sim: &mut Sim,
id :usize,
... | Driver | identifier_name |
driver.rs | SmallVec<[(NodeId, f64); 4]>,
}
pub struct Driver {
id :usize,
train: Train,
authority: f64,
step: (DriverAction, f64),
connected_signals: SmallVec<[(ObjectId, f64); 4]>,
logger: Box<Fn(TrainLogEvent)>,
activation: Activation,
timestep: Option<f64>,
}
impl Driver {
pub fn new(sim:... |
}
}
_ => panic!("Not a signal"),
}
}
//println!("Updated authority {}", self.authority);
// Static maximum speed profile ahead from current position
// TODO: other speed limitations
let static_speed_profile = Stat... | {
//println!("Signal red in sight dist{} self.auth{}", dist,dist-20.0);
self.authority = dist - 20.0;
if self.authority < 0.0 { self.authority = 0.0; }
break;
} | conditional_block |
driver.rs | : SmallVec<[(NodeId, f64); 4]>,
}
pub struct Driver {
id :usize,
train: Train,
authority: f64,
step: (DriverAction, f64),
connected_signals: SmallVec<[(ObjectId, f64); 4]>,
logger: Box<Fn(TrainLogEvent)>,
activation: Activation,
timestep: Option<f64>,
}
impl Driver {
pub fn new(sim... | }
false
} else {
true
}
});
{
let log = &mut self.logger;
self.connected_signals.retain(|&mut (obj, ref mut dist)| {
*dist -= update.dx;
let lost = *dist < 10.0; // If closer than 10 m, sign... | sim.start_process(p);
} | random_line_split |
lib.rs | _len);
if inner.buffer.len() == inner.config.max_buffer_len {
debug!("Reached mplex maximum buffer length");
match inner.config.max_buffer_behaviour {
MaxBufferBehaviour::CloseAll => {
inner.error = Err(IoError::new(IoErrorKind::Other, "reached maximum... | {
// There was no data packet in the buffer about this substream; maybe it's
// because it has been closed.
if inner.opened_substreams.contains(&(substream.num, substream.endpoint)) {
return Ok(Async::NotReady)
} els... | conditional_block | |
lib.rs | to_notify: Mutex::new(Default::default()),
}),
is_shutdown: false,
is_acknowledged: false,
})
}
}
}
impl Default for MplexConfig {
#[inline]
fn default() -> MplexConfig |
}
/// Behaviour when the maximum length of the buffer is reached.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum MaxBufferBehaviour {
/// Produce an error on all the substreams.
CloseAll,
/// No new message will be read from the underlying connection if the buffer is full.
///
/// This can ... | {
MplexConfig {
max_substreams: 128,
max_buffer_len: 4096,
max_buffer_behaviour: MaxBufferBehaviour::CloseAll,
split_send_size: 1024,
}
} | identifier_body |
lib.rs | (&mut self, size: usize) -> &mut Self {
let size = cmp::min(size, codec::MAX_FRAME_SIZE);
self.split_send_size = size;
self
}
#[inline]
fn upgrade<C>(self, i: C) -> Multiplex<C>
where
C: AsyncRead + AsyncWrite
{
let max_buffer_len = self.max_buffer_len;
... | split_send_size | identifier_name | |
lib.rs | to_notify: Mutex::new(Default::default()),
}),
is_shutdown: false,
is_acknowledged: false,
})
}
}
}
impl Default for MplexConfig {
#[inline]
fn default() -> MplexConfig {
MplexConfig {
max_substreams... | // Small convenience function that tries to write `elem` to the stream.
fn poll_send<C>(inner: &mut MultiplexInner<C>, elem: codec::Elem) -> Poll<(), IoError>
where C: AsyncRead + AsyncWrite
{
if inner.is_shutdown {
return Err(IoError::new(IoErrorKind:: | random_line_split | |
app.component.ts | 0; i < str.length; ++i) {
const char = str[i];
if (this.charIndices[char] == null) {
throw new Error(`Unknown character: '${char}'`);
}
buf.set(1, i, this.charIndices[char]);
}
return buf.toTensor().as2D(numRows, this.size);
}
encodeBatch(strings, numRows) {
const numExa... | (digits, trainingSize, rnnType, layers, hiddenSize) {
// Prepare training data.
const chars = '0123456789+ ';
this.charTable = new CharacterTable(chars);
console.log('Generating training data');
const data = generateData(digits, trainingSize, false);
const split = Math.floor(trainingSize * 0.9);... | constructor | identifier_name |
app.component.ts | ; i < str.length; ++i) {
const char = str[i];
if (this.charIndices[char] == null) {
throw new Error(`Unknown character: '${char}'`);
}
buf.set(1, i, this.charIndices[char]);
}
return buf.toTensor().as2D(numRows, this.size);
}
encodeBatch(strings, numRows) {
const numExam... |
function createAndCompileModel(
layers,
hiddenSize,
rnnType,
digits,
vocabularySize
) {
const maxLen = digits + 1 + digits;
const model = tf.sequential();
switch (rnnType) {
case 'SimpleRNN':
model.add(
tf.layers.simpleRNN({
units: hiddenSize,
recurrentInitialize... | {
const maxLen = digits + 1 + digits;
const questions = data.map((datum) => datum[0]);
const answers = data.map((datum) => datum[1]);
return [
charTable.encodeBatch(questions, maxLen),
charTable.encodeBatch(answers, digits + 1),
];
} | identifier_body |
app.component.ts | ; i < str.length; ++i) {
const char = str[i];
if (this.charIndices[char] == null) {
throw new Error(`Unknown character: '${char}'`);
}
buf.set(1, i, this.charIndices[char]);
}
return buf.toTensor().as2D(numRows, this.size);
}
encodeBatch(strings, numRows) {
const numExam... |
return buf.toTensor().as3D(numExamples, numRows, this.size);
}
/**
* Convert a 2D tensor into a string with the CharacterTable's vocabulary.
*
* @param x Input 2D tensor.
* @param calcArgmax Whether to perform `argMax` operation on `x` before
* indexing into the `CharacterTable`'s vocabulary.... | {
const str = strings[n];
for (let i = 0; i < str.length; ++i) {
const char = str[i];
if (this.charIndices[char] == null) {
throw new Error(`Unknown character: '${char}'`);
}
buf.set(1, n, i, this.charIndices[char]);
}
} | conditional_block |
app.component.ts | 0; i < str.length; ++i) {
const char = str[i];
if (this.charIndices[char] == null) {
throw new Error(`Unknown character: '${char}'`);
}
buf.set(1, i, this.charIndices[char]);
}
return buf.toTensor().as2D(numRows, this.size);
}
encodeBatch(strings, numRows) {
const numExa... | const trainLoss = history.history['loss'][0];
const trainAccuracy = history.history['acc'][0];
const valLoss = history.history['val_loss'][0];
const valAccuracy = history.history['val_acc'][0];
lossValues[0].push({ x: i, y: trainLoss });
lossValues[1].push({ x: i, y: valLoss });
... | const modelFitTime = elapsedMs / 1000;
| random_line_split |
lib.rs | 4, 12, 11, 15, 1],
[ 13, 6, 4, 9, 8, 15, 3, 0, 11, 1, 2, 12, 5, 10, 14, 7],
[ 1, 10, 13, 0, 6, 9, 8, 7, 4, 15, 14, 3, 11, 5, 2, 12]
],
[
[ 7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15],
[ 13, 8, 11, 5, 6, 15, 0, ... | let message_len = message.len();
let message = message_to_u64s(message); | random_line_split | |
lib.rs | 0) as u8,
((num & 0x000000FF00000000) >> 32) as u8,
((num & 0x00000000FF000000) >> 24) as u8,
((num & 0x0000000000FF0000) >> 16) as u8,
((num & 0x000000000000FF00) >> 8) as u8,
((num & 0x00000000000000FF) >> 0) as u8
]
}
/// Процедура создания 16 подключей
fn compute_subke... | 000) >> 4 | identifier_name | |
lib.rs | , 5, 6, 11, 0, 14, 9, 2],
[ 7, 11, 4, 1, 9, 12, 14, 2, 0, 6, 10, 13, 15, 3, 5, 8],
[ 2, 1, 14, 7, 4, 10, 8, 13, 15, 12, 9, 0, 3, 5, 6, 11]
]
];
let i = ((block & 0x20) >> 4 | (block & 0x01)) as usize;
let j = ((block & 0x1E) >> 1) as usize;
TABLES... | result = pc1(0b00010011_00110100_01010111_01111001_10011011_10111100_11011111_11110001);
assert_eq!(0b1111000_0110011_0010101_0101111_0101010_1011001_1001111_0001111 << 8, result);
}
#[test]
fn test_pc2() {
let result = pc2(0b1110000_1100110_0101010_1011111_1010101_0110011_0011110_0011110 <... | identifier_body | |
lib.rs | 6, 34 ,53,
46, 42, 50, 36, 29, 32
];
const OUT_SIZE: u8 = 64;
let mut result: u64 = 0;
for m in 0 .. PC_2_TABLE.len() as usize {
if PC_2_TABLE[m] > m as u8 {
result |= (key & (0x01 << OUT_SIZE - PC_2_TABLE[m])) << PC_2_TABLE[m] - (m as u8 + 1);
} else {
r... | 1)) & 0x8000000000000000) as u64;
let b2 = ((block_exp >> 1) & 0x7C00000000000000) as u64;;
let b3 = ((block_exp >> 3) & 0x03F0000000000000) as u64;;
let b4 = ((block_exp >> 5) & 0x000FC00000000000) as u64;;
let b5 = ((block_exp >> 7) ... | st RESULT_LEN: usize = 48;
let block_exp = (block as u64) << 32;
let b1 = ((block_exp << (BLOCK_LEN - | conditional_block |
functions.py | .name)
return nomes_calls
def streaming(input_ativo,input_data=[]):
"""
Retorna os dados de opções do ativo em real(se o mercado estiver aberto)
input_ativo: ativo desejado
input_data: Datas de vencimento das opções
"""
vol, preco_max = vol_e_preco_max... | tivo, tipo='c'):
"""
Retorna os payoffs da call, dado o preço da call, strike, e último preço do ativo subjacente e
se a opção foi comprada o vendida.
"""
## Gera uma array com preços do ativo subjacente baseado no preço do momento do ativo.
p_min, p_max = int(preco_ati... | preco_a | identifier_name |
functions.py | acao.Payoffs_vendido
try:
breakeven = payoff_operacao[payoff_operacao.Payoff_total == 0]
preco_breakeven = breakeven.AtivoSubjacente.item()
precos_diferenca = preco_comprado - prec... | in ativo_e_similar.keys():
historico = pd.DataFrame(mt5.copy_rates_from_pos(ativo,mt5.TIMEFRAME_D1,0,252))
historico.index = pd.to_datetime(historico['time'],unit='s')
historico.sort_index(ascending=False,inplace=True)
max_52s = historico['close'].max(... | conditional_block | |
functions.py | (s.name)
return nomes_calls
def streaming(input_ativo,input_data=[]):
"""
Retorna os dados de opções do ativo em real(se o mercado estiver aberto)
input_ativo: ativo desejado
| """
vol, preco_max = vol_e_preco_max(ativo=input_ativo)
dados = call_negociadas(ativo=input_ativo, data_do_vencimento=input_data)
# time.sleep(30) # garantir que a conexão foi garantida antes de a chamar a função de streaming
mt5.market_book_add(input_ativo)
for ticker in dados:... | input_data: Datas de vencimento das opções
| random_line_split |
functions.py | (s.name)
return nomes_calls
def streaming(input_ativo,input_data=[]):
"""
Retorna os dados de opções do ativo em real(se o mercado estiver aberto)
input_ativo: ativo desejado
input_data: Datas de vencimento das opções
"""
vol, preco_max = vol_e_preco_m... | implicita_historica_c = itm['Diferença entre Implicita e Realizada(%)'].loc[i].item()
for j in atm.index:
if atm['Preco Teorico'].loc[j].item() != 0 and atm['Vencimento em(dias)'].loc[j].item() == vencimento:
preco_vendido = atm['Preco T... | aming(input_ativo,input_data)
df = pd.DataFrame(df)
itm = df[(df['Delta'] > 0.85) & (df['Delta'] <= 1.)].copy()
atm = df[(df['Delta'] > 0.50) & (df['Delta'] <= 0.75)].copy()
dataframe = list()
ativo = itm['Ativo Subjacente'].iloc[0]
for i in itm.index:... | identifier_body |
proc_fork.rs | s the current process into a new subprocess. If the function
/// returns a zero then its the new subprocess. If it returns a positive
/// number then its the current process and the $pid represents the child.
#[instrument(level = "debug", skip_all, fields(pid = ctx.data().process.pid().raw()), ret, err)]
pub fn | <M: MemorySize>(
mut ctx: FunctionEnvMut<'_, WasiEnv>,
mut copy_memory: Bool,
pid_ptr: WasmPtr<Pid, M>,
) -> Result<Errno, WasiError> {
wasi_try_ok!(WasiEnv::process_signals_and_exit(&mut ctx)?);
// If we were just restored then we need to return the value instead
if let Some(result) = unsafe {... | proc_fork | identifier_name |
proc_fork.rs | unsafe { handle_rewind::<M, ForkResult>(&mut ctx) } {
if result.pid == 0 {
trace!("handle_rewind - i am child (ret={})", result.ret);
} else {
trace!(
"handle_rewind - i am parent (child={}, ret={})",
result.pid,
result.ret
... | {} | conditional_block | |
proc_fork.rs | s the current process into a new subprocess. If the function
/// returns a zero then its the new subprocess. If it returns a positive
/// number then its the current process and the $pid represents the child.
#[instrument(level = "debug", skip_all, fields(pid = ctx.data().process.pid().raw()), ret, err)]
pub fn proc_fo... | let mut ret: ExitCode = Errno::Success.into();
let err = if ctx.data(&store).thread.is_main() {
trace!(%pid, %tid, "re-invoking main");
let start = unsafe { ctx.data(&store).inner() }.start.clone().unwrap();
start.call(&mut store)
} else {
trace!(%pid, %tid, "re-invoking thre... | {
let env = ctx.data(&store);
let tasks = env.tasks().clone();
let pid = env.pid();
let tid = env.tid();
// If we need to rewind then do so
if let Some((rewind_state, rewind_result)) = rewind_state {
let res = rewind_ext::<M>(
ctx.env.clone().into_mut(&mut store),
... | identifier_body |
proc_fork.rs | .pid().raw()), ret, err)]
pub fn proc_fork<M: MemorySize>(
mut ctx: FunctionEnvMut<'_, WasiEnv>,
mut copy_memory: Bool,
pid_ptr: WasmPtr<Pid, M>,
) -> Result<Errno, WasiError> {
wasi_try_ok!(WasiEnv::process_signals_and_exit(&mut ctx)?);
// If we were just restored then we need to return the value ... | // Create the respawn function
let respawn = {
let tasks = tasks.clone(); | random_line_split | |
phase1b_stack.py |
def find_best_ref(all_flc_list, filt_priority=["F110W", "F105W",
"F140W", "F125W",
"F814W", "F775W",
"F606W", "F160W"]):
flc_list = []
for filt in filt_priority:
... | if type(the_filters) == type("a"):
filt_list = [copy.deepcopy(the_filters)]
else:
filt_list = copy.deepcopy(the_filters)
f125w_list = []
for item in flt_list:
f = pyfits.open(item)
if filt_list.count(get_filter(f[0].header)):
f125w_list.append(item)
return f... | identifier_body | |
phase1b_stack.py | [item.split(None) for item in lines]
lines = [item for item in lines if item != []]
bad_pix = [(int(item[0]), int(item[1])) for item in lines]
tmp_ims = []
for i in range(len(flt_list)):
f = pyfits.open(flt_list[i])
if f[0].header["INSTRUME"] == "ACS":
tmp_ims.append(flt_l... | (ims_path):
origfls = glob.glob(ims_path+'/*flt.fits')
print origfls
ims_dict = {}
for fl in origfls:
f = pyfits.open(fl)
EXPEND = int(f[0].header["EXPEND"])
FILTER = f[0].header["FILTER"]
f.close()
just_fl = fl.split('/')[-1]
print just_fl, FILTER, EXPE... | sort_ims | identifier_name |
phase1b_stack.py | [item.split(None) for item in lines]
lines = [item for item in lines if item != []]
bad_pix = [(int(item[0]), int(item[1])) for item in lines]
tmp_ims = []
for i in range(len(flt_list)):
f = pyfits.open(flt_list[i])
if f[0].header["INSTRUME"] == "ACS":
tmp_ims.append(flt_l... |
def get_fls_by_filter_date(globpath = ""):
files_by_filter_date = collections.OrderedDict()
if globpath == "":
origfls = glob.glob(data_path
+ "set_%s/orig_files/*flt.fits" % set_num)
simfls = [] #glob.glob("simulated_ims/*flt.fits")
else:
origfls = gl... | f["SCI"].data *= 1.007
f.flush()
f.close() | random_line_split |
phase1b_stack.py | [item.split(None) for item in lines]
lines = [item for item in lines if item != []]
bad_pix = [(int(item[0]), int(item[1])) for item in lines]
tmp_ims = []
for i in range(len(flt_list)):
| this_x += LTV1
this_y += LTV2
if this_x > 1 and this_x < len(tmpdata[0]) and this_y > 1 and this_y < len(tmpdata):
f["SCI"].data[int(np.around(this_y - 1)), int(np.around(this_x - 1))] = np.median(tmpdata[int(np.around(this_y - 2)): int(np.around(this... | f = pyfits.open(flt_list[i])
if f[0].header["INSTRUME"] == "ACS":
tmp_ims.append(flt_list[i].replace(".fits", "_lac.fits"))
acs = True
else:
tmp_ims.append(flt_list[i].replace(".fits", "_filter.fits"))
if flt_list[i] == tmp_ims[i]:
print "... | conditional_block |
main.rs | ,
max_locked: u64,
}
#[derive(Debug)]
struct Database(BTreeMap<Pid, Pinfo>);
impl Database {
fn new() -> Self {
Database(BTreeMap::new())
}
fn contains(&self, pid: &Pid) -> bool {
self.0.contains_key(pid)
}
fn new_child_process(&mut self, pid: Pid, pname: Pname) {
sel... |
fn table(&self) -> String {
let col1_heading = "Process Name";
let col2_heading = "Max Locked Memory (kb)";
let col1_heading_len = col1_heading.chars().count();
let col2_heading_len = col2_heading.chars().count();
let min_col2_start = col1_heading_len + COLUMN_BUFFER;
... | {
if let Some(pinfo) = self.0.get_mut(&pid) {
if kbs_locked > pinfo.max_locked {
pinfo.max_locked = kbs_locked;
}
}
} | identifier_body |
main.rs | ,
max_locked: u64,
}
#[derive(Debug)]
struct Database(BTreeMap<Pid, Pinfo>);
impl Database {
fn new() -> Self {
Database(BTreeMap::new())
}
fn contains(&self, pid: &Pid) -> bool {
self.0.contains_key(pid)
}
fn new_child_process(&mut self, pid: Pid, pname: Pname) {
sel... | {
soft: Limit,
hard: Limit,
}
fn run_prlimit() -> MlockLimit {
let output = Command::new("prlimit")
.args(&["--memlock", "--output=SOFT,HARD", "--noheadings"])
.output()
.map(|output| String::from_utf8(output.stdout).unwrap())
.unwrap_or_else(|e| panic!("Subprocess failed: ... | MlockLimit | identifier_name |
main.rs | ,
max_locked: u64,
}
#[derive(Debug)]
struct Database(BTreeMap<Pid, Pinfo>);
impl Database {
fn new() -> Self {
Database(BTreeMap::new())
}
fn contains(&self, pid: &Pid) -> bool {
self.0.contains_key(pid)
}
fn new_child_process(&mut self, pid: Pid, pname: Pname) {
sel... | cargo_test_pid: Arc<Mutex<Option<Pid>>>,
child_pids: Arc<Mutex<Vec<Pid>>>,
db: Arc<Mutex<Database>>,
done: Arc<AtomicBool>,
) -> JoinHandle<()> {
thread::spawn(move || {
while cargo_test_pid.lock().unwrap().is_none() {
thread::sleep(Duration::from_millis(1));
}
wh... | random_line_split | |
dep_cache.rs | requirement, so both of these assertions should
// never fail.
assert_eq!(s.version(), summary.version());
assert_eq!(s.name(), summary.name());
let replace = if s.source_id() == summary.source_id() {
debug!("Preventing\n{:?}\nfrom replacing\n{:?}", summ... | random_line_split | ||
dep_cache.rs | are none to ignore
None
}
Poll::Ready(Err(e)) => Some(Err(e).with_context(|| {
format!(
"failed to get `{}` as a dependency of {}",
dep.package_name(),
... | {
match self {
RequirementError::MissingFeature(feat) => {
let deps: Vec<_> = summary
.dependencies()
.iter()
.filter(|dep| dep.name_in_toml() == feat)
.collect();
if deps.is_empty() {
... | identifier_body | |
dep_cache.rs | () {
debug!("Preventing\n{:?}\nfrom replacing\n{:?}", summary, s);
None
} else {
Some(s)
};
let matched_spec = spec.clone();
// Make sure no duplicates
if let Some(&(ref spec, _)) = potential_matches.next() {
... | into_features | identifier_name | |
main.py | (self, acc1, acc2):
return acc1.union(acc2)
# An accumulator used to build the word vocabulary
class WordsDictAccumulatorParam(AccumulatorParam):
def zero(self, v):
return dict()
def addInPlace(self, acc1, acc2):
for key in acc2.keys():
try:
acc1[key] += acc2... | addInPlace | identifier_name | |
main.py | addInPlace(self, acc1, acc2):
return acc1.union(acc2)
# An accumulator used to build the word vocabulary
class WordsDictAccumulatorParam(AccumulatorParam):
def zero(self, v):
return dict()
def addInPlace(self, acc1, acc2):
for key in acc2.keys():
try:
acc1[k... |
except: None
if coordinates:
closestLoc = spatial.KDTree(latlon).query(coordinates, k=1, distance_upper_bound=9)[1]
try:
closest = latlon[closestLoc]
except:
return None
# closest = spatial.KDTree(latlon).query(coordinates, k=1, distance_upper_bound=9... | return area_dict[location] | conditional_block |
main.py | addInPlace(self, acc1, acc2):
return acc1.union(acc2)
# An accumulator used to build the word vocabulary
class WordsDictAccumulatorParam(AccumulatorParam):
def zero(self, v):
return dict()
def addInPlace(self, acc1, acc2):
for key in acc2.keys():
try:
acc1[k... | for w in xny:
# vocabulary +=[w]
vocabulary += {w: 1}
try:
wordDict[w] += 1
except:
wordDict[w] = 1
return wordDict
# function to add words to the vocabulary and count frequency of each word globally
def genVocabulary(x):
global vocabulary
arr = ... | random_line_split | |
main.py | addInPlace(self, acc1, acc2):
return acc1.union(acc2)
# An accumulator used to build the word vocabulary
class WordsDictAccumulatorParam(AccumulatorParam):
def zero(self, v):
return dict()
def addInPlace(self, acc1, acc2):
for key in acc2.keys():
try:
acc1[k... |
# function to add words to the vocabulary and count frequency of each word globally
def genVocabulary(x):
global vocabulary
arr = x[1]
if isinstance(arr, dict):
return x
else:
wordDict = dict()
for w in arr:
vocabulary += {w: 1}
try:
word... | global vocabulary
if isinstance(x, dict):
wordDict = x
xny = y
else:
wordDict = dict()
xny = x + y
for w in xny:
# vocabulary +=[w]
vocabulary += {w: 1}
try:
wordDict[w] += 1
except:
wordDict[w] = 1
return wordDict | identifier_body |
conference.ts | :00:00')
const registrationOpenUntil = hideDate
? null
: date
.clone()
.add(-1, 'd')
.startOf('day')
.add(17, 'h')
const presentationSubmissionsOpenFrom = moment('2019-06-10T08:00:00')
const presentationSubmissionsOpenUntil = moment('2019-07-14T23:59:59')
const votingOpenFrom = moment('2019-... | Sponsors: SponsorData,
Keynotes: [
{
SessionAbstract: `Having different ideas, opinions, interests can be quite lonely and lead to thinking about where you can fit especially in the fast-paced tech industry.
Coming to the industry, not by a traditional path, being the only one in the room to have a uniq... | random_line_split | |
conference.ts | 00:00')
const registrationOpenUntil = hideDate
? null
: date
.clone()
.add(-1, 'd')
.startOf('day')
.add(17, 'h')
const presentationSubmissionsOpenFrom = moment('2019-06-10T08:00:00')
const presentationSubmissionsOpenUntil = moment('2019-07-14T23:59:59')
const votingOpenFrom = moment('2019-0... |
const Conference: IConference = {
AgendaPublishedFrom: agendaPublishedFrom,
AnonymousReportFormUrl: '',
AnonymousVoting: true,
ContactEmail: 'team@dddsydney.com.au',
ChildcarePrice: '',
Date: date,
DoorsOpenTime: '8:10am',
EmergencyContactName: 'Aaron Powell',
EmergencyContactPhoneNumber: '0439 878 ... | {
importantDates.push({
Date: date,
Description: 'Conference day',
Type: 'conference',
})
} | conditional_block |
plugin.go | consul, queries), nil
}
func (td *ConsulDataSource) getConsulClient(pluginCtx backend.PluginContext) (*api.Client, error) {
instance, err := td.im.Get(pluginCtx)
if err != nil {
return nil, fmt.Errorf("could not get plugin instance: %v", err)
}
instanceSettings, ok := instance.(*instanceSettings)
if !ok {
re... |
}
return generateDataResponseWithTags(target, tagKVs)
}
func generateDataResponseFromKV(kvs []*api.KVPair) backend.DataResponse {
log.DefaultLogger.Debug("generateDataResponseFromKV", "kv", kvs)
response := backend.DataResponse{}
for _, kv := range kvs {
floatValue, err := strconv.ParseFloat(string(kv.Value)... | {
tagKVs = append(tagKVs, tagKV)
} | conditional_block |
plugin.go | consul, queries), nil
}
func (td *ConsulDataSource) getConsulClient(pluginCtx backend.PluginContext) (*api.Client, error) {
instance, err := td.im.Get(pluginCtx)
if err != nil {
return nil, fmt.Errorf("could not get plugin instance: %v", err)
}
instanceSettings, ok := instance.(*instanceSettings)
if !ok {
re... | (ctx context.Context, consul *api.Client, query queryModel) backend.DataResponse {
log.DefaultLogger.Debug("queryTimeSeries", "query", query)
if query.Format == "" {
log.DefaultLogger.Debug("format is empty. defaulting to time series")
query.Format = "timeseries"
}
if query.Type == "" {
log.DefaultLogger.Deb... | queryTimeSeries | identifier_name |
plugin.go | consul, queries), nil
}
func (td *ConsulDataSource) getConsulClient(pluginCtx backend.PluginContext) (*api.Client, error) {
instance, err := td.im.Get(pluginCtx)
if err != nil {
return nil, fmt.Errorf("could not get plugin instance: %v", err)
}
instanceSettings, ok := instance.(*instanceSettings)
if !ok {
re... | if err != nil {
return backend.DataResponse{Error: fmt.Errorf("error compiling regex %s: %v", target, err)}
}
// Calculate Prefix to execute consul.KV().Keys() on
firstStar := strings.Index(query.Target, "*")
prefix := query.Target
if firstStar > 0 {
prefix = query.Target[:firstStar]
}
// Get keys with pr... | targetRegex, err := regexp.Compile(target) | random_line_split |
plugin.go | consul, queries), nil
}
func (td *ConsulDataSource) getConsulClient(pluginCtx backend.PluginContext) (*api.Client, error) {
instance, err := td.im.Get(pluginCtx)
if err != nil {
return nil, fmt.Errorf("could not get plugin instance: %v", err)
}
instanceSettings, ok := instance.(*instanceSettings)
if !ok {
re... |
func handleKeys(ctx context.Context, consul *api.Client, target string) backend.DataResponse {
log.DefaultLogger.Debug("handleKeys", "target", target)
if !strings.HasSuffix(target, "/") {
target = target + "/"
}
keys, _, err := consul.KV().Keys(target, "/", (&api.QueryOptions{RequireConsistent: true}).WithCon... | {
log.DefaultLogger.Debug("handleGet", "target", target)
if strings.HasSuffix(target, "/") {
target = target[:len(target)-1]
}
var kvs []*api.KVPair
kv, _, err := consul.KV().Get(target, (&api.QueryOptions{RequireConsistent: true}).WithContext(ctx))
if err != nil {
return backend.DataResponse{Error: fmt.Err... | identifier_body |
util.py |
def setArray(self,arr):
self.array = np.array(arr)
def appendArray(self,num):
self.plain_arr.append(num)
def getPlainArr(self):
return self.plain_arr
def setFromPlainArr(self):
self.array = np.array(self.plain_arr)
def getavg(self):
try:
retu... | if arr:
self.array = np.array(arr)
self.plain_arr = [] | identifier_body | |
util.py | 0
def getmax(self):
try:
return np.max(self.array)
except:
return 0
def getreport(self):
f ={'avg':self.getavg, 'std':self.getstd, 'max':self.getmax, 'min':self.getmin}
ret = ""
for k, v in f.items():
ret += k+": "+ str(v())+'\n'
... | (self,fname):
terms = {}
result = []
with open(fname) as f:
for l in f.readlines():
if len(l.strip()) == 0:
sorted_x = dict(sorted(terms.items(), key=operator.itemgetter(1)))
result.append([k for k,v in sorted_x.items() if v > ... | genParaterm | identifier_name |
util.py | from tweetsManager import textManager
from random import shuffle
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn import svm
from sklearn.linear_model import SGDClassifier
from sklearn import neighbors
from sklearn import cross_validation
import string
import re
from math import *
from collectio... | import numpy as np
from scipy.stats import norm | random_line_split | |
util.py | 0
def getmax(self):
try:
return np.max(self.array)
except:
return 0
def getreport(self):
f ={'avg':self.getavg, 'std':self.getstd, 'max':self.getmax, 'min':self.getmin}
ret = ""
for k, v in f.items():
ret += k+": "+ str(v())+'\n'
... |
return result
class sentenceSimilarity:
def __init__(self):
self.WORD = re.compile(r'\w+')
def excatWordscore(self, text1, text2):
vector1 = self.text_to_vector(text1)
vector2 = self.text_to_vector(text2)
return self.get_cosine(vector1, vector2)
def groupExcatW... | try:
terms[v+" "+w] += 1
except:
terms[v+" "+w] = 1 | conditional_block |
app.py | _content_to_dict(ace_config_dir, split_by_line=False)
ace_conn = ACEAdminConnection(host=ace_config["host"], admin_port=int(ace_config["port"]), admin_https=False,
user=ace_config["user"], pw=ace_config["pw"])
user_auth = subdirs_file_content_to_dict(user_dir, split_by_line=False)
hash_dic... | (self, project_type, project, msgflow, node, terminal):
"""Returns a dictionary with all submitted queries and their processing status
:param project_type: choice between applications/services/rest-apis
:type project_type: string
:param project: name of the ACE project: Project1
... | post | identifier_name |
app.py | _content_to_dict(ace_config_dir, split_by_line=False)
ace_conn = ACEAdminConnection(host=ace_config["host"], admin_port=int(ace_config["port"]), admin_https=False,
user=ace_config["user"], pw=ace_config["pw"])
user_auth = subdirs_file_content_to_dict(user_dir, split_by_line=False)
hash_dic... | @auth.login_required
def post(self, project_type, project, msgflow, node, terminal):
"""Returns a dictionary with all submitted queries and their processing status
:param project_type: choice between applications/services/rest-apis
:type project_type: string
:param project: name... | @auth.login_required
def get(self, project_type, project, msgflow, node, terminal):
"""Returns a dictionary with all queries on disk queried by the parameters
:param project_type: choice between applications/services/rest-apis
:type project_type: string
:param project: name of the A... | identifier_body |
app.py | _content_to_dict(ace_config_dir, split_by_line=False)
ace_conn = ACEAdminConnection(host=ace_config["host"], admin_port=int(ace_config["port"]), admin_https=False,
user=ace_config["user"], pw=ace_config["pw"])
user_auth = subdirs_file_content_to_dict(user_dir, split_by_line=False)
hash_dic... | record was obtained, together with a query result dictionary.
:param records: list of ACERecord instances
:type records: list(ACERecord)
:param project_type: choice (application/services/rest-apis)
:type project_type: string
:param project: name of the ACE project
:type project: string
... | random_line_split | |
app.py | _content_to_dict(ace_config_dir, split_by_line=False)
ace_conn = ACEAdminConnection(host=ace_config["host"], admin_port=int(ace_config["port"]), admin_https=False,
user=ace_config["user"], pw=ace_config["pw"])
user_auth = subdirs_file_content_to_dict(user_dir, split_by_line=False)
hash_dic... |
return result
def perform_queries(records, project_type, project, msgflow):
"""Returns list for each ACERecord supplied, each specifying from-to which node+terminal between which this
record was obtained, together with a query result dictionary.
:param records: list of ACERecord instances
:type ... | parsed_record = etree.parse(StringIO(record.test_data_xml()))
result.update(dict((q_name, {'query': q_value,
'result': list(x.text for x in etree.ETXPath(q_value)(parsed_record))})
for q_name, q_value in touched_queries.items())) | conditional_block |
operands.go | or parse() method on the concrete operand generator.
get() string
// getNew retrieves a new instance of this type of operand. Called when an
// opener operation (with isOpener = true) needs an ID to store its output.
getNew() string
// opener returns the name of an operation generator (defined in
// operations.g... |
func (t *pastTSGenerator) closeAll() {
// No-op.
}
func (t *pastTSGenerator) toString(ts hlc.Timestamp) string {
return fmt.Sprintf("%d", ts.WallTime)
}
func (t *pastTSGenerator) parse(input string) hlc.Timestamp {
var ts hlc.Timestamp
wallTime, err := strconv.ParseInt(input, 10, 0)
if err != nil {
panic(err... | {
// Always return a non-zero count so opener() is never called.
return int(t.tsGenerator.lastTS.WallTime) + 1
} | identifier_body |
operands.go | // or parse() method on the concrete operand generator.
get() string
// getNew retrieves a new instance of this type of operand. Called when an
// opener operation (with isOpener = true) needs an ID to store its output.
getNew() string
// opener returns the name of an operation generator (defined in
// operations... | }
type txnID string
type txnGenerator struct {
rng *rand.Rand
testRunner *metaTestRunner
tsGenerator *tsGenerator
liveTxns []txnID
txnIDMap map[txnID]*roachpb.Transaction
openBatches map[txnID]map[readWriterID]struct{}
// Counts "generated" transactions - i.e. how many txn_open()s have been
// ... | func (v *valueGenerator) parse(input string) []byte {
return []byte(input) | random_line_split |
operands.go | or parse() method on the concrete operand generator.
get() string
// getNew retrieves a new instance of this type of operand. Called when an
// opener operation (with isOpener = true) needs an ID to store its output.
getNew() string
// opener returns the name of an operation generator (defined in
// operations.g... |
openBatches[w] = struct{}{}
}
func (t *txnGenerator) closeAll() {
t.liveTxns = nil
t.txnIDMap = make(map[txnID]*roachpb.Transaction)
t.openBatches = make(map[txnID]map[readWriterID]struct{})
}
type pastTSGenerator struct {
rng *rand.Rand
tsGenerator *tsGenerator
}
var _ operandGenerator = &pastTSGener... | {
t.openBatches[txn] = make(map[readWriterID]struct{})
openBatches = t.openBatches[txn]
} | conditional_block |
operands.go | or parse() method on the concrete operand generator.
get() string
// getNew retrieves a new instance of this type of operand. Called when an
// opener operation (with isOpener = true) needs an ID to store its output.
getNew() string
// opener returns the name of an operation generator (defined in
// operations.g... | () string {
return t.toString(t.tsGenerator.randomPastTimestamp(t.rng))
}
func (t *pastTSGenerator) getNew() string {
return t.get()
}
// Similar to pastTSGenerator, except it always increments the "current" timestamp
// and returns the newest one.
type nextTSGenerator struct {
pastTSGenerator
}
func (t *nextTSGe... | get | identifier_name |
benchmark.rs | ("../mjtest-rs/tests")
}
#[derive(Debug, Clone)]
struct BigTest {
minijava: PathBuf,
stdin: Option<PathBuf>,
}
fn big_tests() -> Vec<BigTest> {
let dirpath = test_folder().join("exec/big");
log::info!("test directory is {}", dirpath.display());
let dirlisting = fs::read_dir(dirpath).unwrap();
... |
Err(msg) => {
log::debug!(
"could not open file for reference benchmark of {}: {:?}",
self.file.display(),
msg
);
}
}
}
fn load_reference_from_disk(&mut self) {
if let Ok(res) = s... | {
if let Err(msg) = serde_json::ser::to_writer(&outfile, &diskformat) {
log::debug!(
"could not write file for reference benchmark of {}: {:?}",
self.file.display(),
msg
);
}
... | conditional_block |
benchmark.rs | ("../mjtest-rs/tests")
}
#[derive(Debug, Clone)]
struct BigTest {
minijava: PathBuf,
stdin: Option<PathBuf>,
}
fn big_tests() -> Vec<BigTest> {
let dirpath = test_folder().join("exec/big");
log::info!("test directory is {}", dirpath.display());
let dirlisting = fs::read_dir(dirpath).unwrap();
... |
}
fn main() {
env_logger::init();
let opts = Opts::from_args();
for big_test in &big_tests() {
if !opts.filter.is_match(&big_test.minijava.to_string_lossy()) {
log::info!("skipping {}", big_test.minijava.display());
continue;
}
let mut bench = Benchmark::n... | {
Self {
measurements: HashMap::new(),
}
} | identifier_body |
benchmark.rs | join("../mjtest-rs/tests")
}
#[derive(Debug, Clone)]
struct BigTest {
minijava: PathBuf,
stdin: Option<PathBuf>,
}
fn big_tests() -> Vec<BigTest> {
let dirpath = test_folder().join("exec/big");
log::info!("test directory is {}", dirpath.display());
let dirlisting = fs::read_dir(dirpath).unwrap();
... | (file: PathBuf) -> Self {
Self {
measurements: Vec::new(),
reference: None,
file,
}
}
pub fn add(&mut self, measurements: &[SingleMeasurement]) {
if self.measurements.is_empty() {
for measurement in measurements {
self.meas... | new | identifier_name |
benchmark.rs | join("../mjtest-rs/tests")
}
#[derive(Debug, Clone)]
struct BigTest {
minijava: PathBuf,
stdin: Option<PathBuf>,
}
fn big_tests() -> Vec<BigTest> {
let dirpath = test_folder().join("exec/big");
log::info!("test directory is {}", dirpath.display());
let dirlisting = fs::read_dir(dirpath).unwrap();
... | fn main() {
env_logger::init();
let opts = Opts::from_args();
for big_test in &big_tests() {
if !opts.filter.is_match(&big_test.minijava.to_string_lossy()) {
log::info!("skipping {}", big_test.minijava.display());
continue;
}
let mut bench = Benchmark::new(b... | }
}
}
| random_line_split |
utils.py | import os
import sys
import json
import time
import asyncio
import asyncpg
import logging
import requests
from lxml import html
from redis import StrictRedis
from datetime import datetime
from selenium.webdriver import Firefox
from selenium.webdriver.firefox.options import Options
logging.basicConfig(format='%(asctim... | return url_list, last_item
def _make_details(detail_keys, detail_values):
details = {}
for detail_key in detail_keys:
details[detail_key[:-1]] = ''
clean_values = _clean(detail_values)
for index, clean_value in enumerate(clean_values):
details[detail_keys[index][:-1]] = clean_val... | last_item = url_list[len(url_list) - 1]
| random_line_split |
utils.py | import os
import sys
import json
import time
import asyncio
import asyncpg
import logging
import requests
from lxml import html
from redis import StrictRedis
from datetime import datetime
from selenium.webdriver import Firefox
from selenium.webdriver.firefox.options import Options
logging.basicConfig(format='%(asctim... | ():
urls = requests.get(f'http://{API_HOST}:{API_PORT}/api/urls')
url_list = urls.json()
last_item = url_list[len(url_list) - 1]
return url_list, last_item
def _make_details(detail_keys, detail_values):
details = {}
for detail_key in detail_keys:
details[detail_key[:-1]] = ''
cl... | get_url_list | identifier_name |
utils.py | import os
import sys
import json
import time
import asyncio
import asyncpg
import logging
import requests
from lxml import html
from redis import StrictRedis
from datetime import datetime
from selenium.webdriver import Firefox
from selenium.webdriver.firefox.options import Options
logging.basicConfig(format='%(asctim... |
def _make_details(detail_keys, detail_values):
details = {}
for detail_key in detail_keys:
details[detail_key[:-1]] = ''
clean_values = _clean(detail_values)
for index, clean_value in enumerate(clean_values):
details[detail_keys[index][:-1]] = clean_value
return details
def _... | urls = requests.get(f'http://{API_HOST}:{API_PORT}/api/urls')
url_list = urls.json()
last_item = url_list[len(url_list) - 1]
return url_list, last_item | identifier_body |
utils.py | import os
import sys
import json
import time
import asyncio
import asyncpg
import logging
import requests
from lxml import html
from redis import StrictRedis
from datetime import datetime
from selenium.webdriver import Firefox
from selenium.webdriver.firefox.options import Options
logging.basicConfig(format='%(asctim... |
return clean_items
def _deserialize(data):
deserialized_data = []
for item in data:
deserialized_data.append(json.loads(item))
return deserialized_data
def _clear_cache():
cache = StrictRedis(host=REDIS_HOST, port=REDIS_PORT)
cache.flushall()
print('Cache cleared...')
| value = value.replace('\n', '')
value = value.replace('\t', '')
if value and not value.lower().startswith('show'):
clean_items.append(value.strip()) | conditional_block |
data_logger.py | follows:
#
# - /robot/autospeed : This program sends this to the robot. In autonomous mode,
# the robot should attempt to drive at this speed
#
# - /robot/telemetry : The robot sends this. It is a number array that contains:
# - time, battery, autospeed,
# ... | logger.info("Robot has waited long enough, beginning test")
return
last_encoder = encoder
def ramp_voltage_in_auto(self, initial_speed, ramp):
logger.info(
"Activating arm at %.1f%%, adding %.3f per 50ms", initial_speed, ramp
)
sel... | qdata = self.get_nowait()
if qdata != queue.Empty:
return qdata
now = time.monotonic()
# check the encoder position values, are they stationary?
last_data = self.last_data
try:
encoder = last_data[ENCODER_P_COL]
e... | conditional_block |
data_logger.py | follows:
#
# - /robot/autospeed : This program sends this to the robot. In autonomous mode,
# the robot should attempt to drive at this speed
#
# - /robot/telemetry : The robot sends this. It is a number array that contains:
# - time, battery, autospeed,
# ... | # set our robot to 'disabled' if the connection drops so that we can
# guarantee the data gets written to disk
if not connected:
self.valueChanged("/FMSInfo/FMSControlData", 0, False)
self.queue.put("connected" if connected else "disconnected")
def valueChanged(self, ke... | log_key = "/robot/telemetry"
matchNumber = ntproperty("/FMSInfo/MatchNumber", 0, writeDefault=False)
eventName = ntproperty("/FMSInfo/EventName", "unknown", writeDefault=False)
autospeed = ntproperty("/robot/autospeed", 0, writeDefault=True)
def __init__(self):
self.queue = queue.Queue()
... | identifier_body |
data_logger.py | follows:
#
# - /robot/autospeed : This program sends this to the robot. In autonomous mode,
# the robot should attempt to drive at this speed
#
# - /robot/telemetry : The robot sends this. It is a number array that contains:
# - time, battery, autospeed,
# ... | # Change the following constant if your robot wheels are slipping during the
# the fast test, or if the robot is not moving
ROBOT_FAST_SPEED = 0.5
from networktables import NetworkTables, __version__ as ntversion
from networktables.util import ntproperty
# Older versions of pynetworktables (and ntcore) had bugs rela... | # l_encoder_count, r_encoder_count,
# l_encoder_velocity, r_encoder_velocity
# | random_line_split |
data_logger.py | :
#
# - /robot/autospeed : This program sends this to the robot. In autonomous mode,
# the robot should attempt to drive at this speed
#
# - /robot/telemetry : The robot sends this. It is a number array that contains:
# - time, battery, autospeed,
# lmoto... | (self, initial_speed, ramp):
logger.info(
"Activating arm at %.1f%%, adding %.3f per 50ms", initial_speed, ramp
)
self.discard_data = False
self.autospeed = initial_speed
NetworkTables.flush()
try:
while True:
# check the queue i... | ramp_voltage_in_auto | identifier_name |
SpatialGP.py | =False, parametric_only=False, pad=1e-8, eps=1e-8):
X1 = self.standardize_input_array(cond)
m = X1.shape[0]
d = len(self.basisfns)
t0 = time.time()
if not parametric_only:
k = self.kernel(X1, X1, identical=include_obs)
qf = self.double_tree.quadratic_form... | random_line_split | ||
SpatialGP.py | azi_depth_distfn_deriv_log],
)
elif kernel_str == "lld":
noise_kernel = kernels.DiagonalKernel(params=params[0:1], priors = priors[0:1])
local_kernel = kernels.DistFNKernel(params=params[1:4], priors=priors[1:4],
distfn = l... | self.predict_tree = VectorTree(self.X, 1, "lld", self.dfn_params)
self.predict_tree.set_v(0, alpha_r.astype(np.float))
d = len(self.basisfns)
self.cov_tree = VectorTree(self.X, d, "lld", self.dfn_params)
HKinv = HKinv.astype(np.float)
for i in range(d):
self.cov_tre... | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.