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 |
|---|---|---|---|---|
gru_model.py | "]
unique_intent = list(set(intent))
sentences = list(df["Sentence"])
return (intent, unique_intent, sentences)
intent, unique_intent, sentences = load_dataset("Dataset.csv")
intent
sentences
print(sentences[:10])
nltk.download("stopwords")
nltk.download("punkt")
#define stemmer
stemmer = LancasterStemme... | current_segment_id = 0
for token in tokens:
segments.append(current_segment_id)
if token == "[SEP]":
current_segment_id = 1
return segments + [0] * (max_seq_length - len(tokens))
def get_ids(self,tokens, tokenizer, max_seq_length):
"""Toke... | def __init__(self):
self.max_len = 128
bert_path = "https://tfhub.dev/tensorflow/bert_en_uncased_L-12_H-768_A-12/1"
FullTokenizer=bert.bert_tokenization.FullTokenizer
self.bert_module = hub.KerasLayer(bert_path,trainable=True)
self.vocab_file = self.bert_module... | identifier_body |
Lab01Code.py | 3 = c2.mod_mul(Bn(27),p)
c = c1.mod_add(c3,p)
try:
assert c != 0
except:
raise Exception('invalid curve')
#check if points are equal
try:
assert p1 != p2
except:
raise Exception('EC Points must not be equal')
#checking the points and different case... | ecdsa_key_gen | identifier_name | |
Lab01Code.py | y1):
| assert is_point_on_curve(a, b, p, x1, y1)
except:
raise Exception('not valid points')
#check curve 4a^3+27b^2 != 0 mod p.
c0 = a.mod_pow(Bn(3),p)
c1 = c0.mod_mul(Bn(4),p)
c2 = b.mod_pow(Bn(2),p)
c3 = c2.mod_mul(Bn(27),p)
c = c1.mod_add(c3,p)
try:
assert c != 0
... | """Define the "addition" operation for 2 EC Points.
Reminder: (xr, yr) = (xq, yq) + (xp, yp)
is defined as:
lam = yq - yp * (xq - xp)^-1 (mod p)
xr = lam^2 - xp - xq (mod p)
yr = lam * (xp - xr) - yp (mod p)
Return the point resulting from the addition. Raises an Exception if the... | identifier_body |
Lab01Code.py | 1):
"""Define the "addition" operation for 2 EC Points.
Reminder: (xr, yr) = (xq, yq) + (xp, yp)
is defined as:
lam = yq - yp * (xq - xp)^-1 (mod p)
xr = lam^2 - xp - xq (mod p)
yr = lam * (xp - xr) - yp (mod p)
Return the point resulting from the addition. Raises an Exceptio... |
else:
yp = 0;
if (xp2 != 0 and yp != 0):
#calculate gradient if the points are not zero
lam = xp2.mod_mul(yp,p)
#calculate new x coordinate
xr0 = lam.mod_pow(Bn(2),p)
xr1 = x.mod_mul(Bn(2),p)
xr = xr0.mod_s... | yp = yp0.mod_inverse(p) | conditional_block |
Lab01Code.py | y1):
"""Define the "addition" operation for 2 EC Points.
Reminder: (xr, yr) = (xq, yq) + (xp, yp)
is defined as:
lam = yq - yp * (xq - xp)^-1 (mod p)
xr = lam^2 - xp - xq (mod p)
yr = lam * (xp - xr) - yp (mod p)
Return the point resulting from the addition. Raises an Except... | return (0,0)
elif y == None or y == 0:
return (None, None)
#calculate the new point== doubled point
else:
if x == 0:
xp2 = a
else:
xp0 = x.mod_pow(Bn(2),p)
xp1 = xp0.mod_mul(Bn(3),p)
xp2 = xp1.mod_add(a,p)
yp0 = ... |
#verify the input point
if p1 == (None,None):
return (None,None)
elif p1 == (0,0): | random_line_split |
lower.rs | (),
diagnostics: vec![],
unknown_ty: TyKind::Unknown.intern(),
}
}
}
impl Index<LocalTypeRefId> for LowerTyMap {
type Output = Ty;
fn index(&self, expr: LocalTypeRefId) -> &Ty {
self.type_ref_to_type.get(expr).unwrap_or(&self.unknown_ty)
}
}
impl LowerTyMap {
... | CallableDef::Struct(s) => fn_sig_for_struct_constructor(db, s),
}
}
pub(crate) fn fn_sig_for_fn(db: &dyn HirDatabase, def: Function) -> FnSig {
let data = def.data(db.upcast());
let resolver = def.id.resolver(db.upcast());
let params = data
| random_line_split | |
lower.rs | TyMap {
/// Adds all the `LowerDiagnostic`s of the result to the `DiagnosticSink`.
pub(crate) fn add_diagnostics(
&self,
db: &dyn HirDatabase,
file_id: FileId,
source_map: &TypeRefSourceMap,
sink: &mut DiagnosticSink,
) {
self.diagnostics
.iter()
... | {
let data = def.data(db.upcast());
let resolver = def.id.resolver(db.upcast());
let params = data
.params()
.iter()
.map(|tr| Ty::from_hir(db, &resolver, data.type_ref_map(), *tr).0)
.collect::<Vec<_>>();
let ret = Ty::from_hir(db, &resolver, data.type_ref_map(), *data.r... | identifier_body | |
lower.rs | Vec<diagnostics::LowerDiagnostic>) {
let mut diagnostics = Vec::new();
let ty =
Ty::from_hir_with_diagnostics(db, resolver, type_ref_map, &mut diagnostics, type_ref);
(ty, diagnostics)
}
/// Tries to lower a HIR type reference to an actual resolved type. Takes a mutable ref... | {
TyKind::FnDef(def.into(), Substitution::empty()).intern()
} | conditional_block | |
lower.rs | (),
diagnostics: vec![],
unknown_ty: TyKind::Unknown.intern(),
}
}
}
impl Index<LocalTypeRefId> for LowerTyMap {
type Output = Ty;
fn index(&self, expr: LocalTypeRefId) -> &Ty {
self.type_ref_to_type.get(expr).unwrap_or(&self.unknown_ty)
}
}
impl LowerTyMap {
... | (self) -> bool {
matches!(self, CallableDef::Struct(_))
}
}
impl HasVisibility for CallableDef {
fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
match self {
CallableDef::Struct(strukt) => strukt.visibility(db),
CallableDef::Function(function) => function.visi... | is_struct | identifier_name |
index.ts | : message.message,
nickname: message.nickname
}
}
/**
* bitFlyerのチャットログを取り込む。
* @param fromDate 取り込む日時(YYYY-MM-DD) 日本時間
*/
async function importBitFlyerLogs(fromDate: string) {
console.log(`importBitFlyerLogs. fromDate=${fromDate}`)
const importDate = moment(fromDate)
// 保存済みかどうかのキャッシュファイルを取得
const b... | ()
const file = bucket.file(`/public/archives/${date.format('YYYY/MM/DD')}/${filename}`)
await file.save(JSON.stringify(archiveMetadata), {
gzip: true,
contentType: 'application/json',
})
return archiveMetadata
}
/**
* 定期的にチャットログを取り込むためのスケジューラー
*/
export const scheduledImportLogs = functions
.runW... | les: [],
message_num: 0,
hours: {},
}
for (const hour in metadata.hours) {
if (metadata.hours.hasOwnProperty(hour)) {
const v = metadata.hours[hour]
archiveMetadata.files = archiveMetadata.files.concat(v.files)
archiveMetadata.message_num += v.messageNum
archiveMetadata.hours[ho... | identifier_body |
index.ts | message: message.message,
nickname: message.nickname
}
}
/**
* bitFlyerのチャットログを取り込む。
* @param fromDate 取り込む日時(YYYY-MM-DD) 日本時間
*/
async function importBitFlyerLogs(fromDate: string) {
console.log(`importBitFlyerLogs. fromDate=${fromDate}`)
const importDate = moment(fromDate)
// 保存済みかどうかのキャッシュファイルを取得
... | moment(fromDate)
// bitflyerからチャットログを取得する。
const fetchDate = archiveDate.clone().add(-1, 'days').tz('Asia/Tokyo').format('YYYY-MM-DD')
const bitFlyerApiEndpoint = `https://api.bitflyer.com/v1/getchats`
const messages: Array<BitFlyerChatMessage> = await fetch(`${bitFlyerApiEndpoint}?from_date=${fetchDate}`).th... | await file.save(JSON.stringify(cache))
return messages.length
}
/**
* bitflyerのログをStorageにアーカイブする。
* @param fromDate YYYY-MM-DD 日本時間の日付
*/
async function archiveBitFlyerLogs(fromDate: string) {
console.log(`archiveBitFlyerLogs. fromDate=${fromDate}`)
const archiveDate = | conditional_block |
index.ts | : message.message,
nickname: message.nickname
}
}
/**
* bitFlyerのチャットログを取り込む。
* @param fromDate 取り込む日時(YYYY-MM-DD) 日本時間
*/
async function importBitFlyerLogs(fromDate: string) {
console.log(`importBitFlyerLogs. fromDate=${fromDate}`)
const importDate = moment(fromDate)
// 保存済みかどうかのキャッシュファイルを取得
const b... | te: Moment, metadata: ArchiveMetadata) {
const archiveMetadata: any = {
files: [],
message_num: 0,
hours: {},
}
for (const hour in metadata.hours) {
if (metadata.hours.hasOwnProperty(hour)) {
const v = metadata.hours[hour]
archiveMetadata.files = archiveMetadata.files.concat(v.files)
... | eArchiveMetadata(da | identifier_name |
index.ts | 0]))
// キャッシュデータの構造が存在しなければ初期化
cache['messageIds'] = cache['messageIds'] || {}
const cacheMessageIds = cache['messageIds'][fromDate] = cache['messageIds'][fromDate] || {}
// bitflyerからチャットログを取得する。
const fetchDate = importDate.clone().add(-1, 'days').tz('Asia/Tokyo').format('YYYY-MM-DD')
const bitFlyerApiE... | // }
//
// let fromDate = request.query.from_date || '' | random_line_split | |
goendpoints.go | volatile ("MRC p15, 0, %0, c9, c13, 0\t\n": "=r"(value));
// return value;
// }
//
// void init_perfcounters (int32_t do_reset, int32_t enable_divider)
// {
// // in general enable all counters (including cycle counter)
// int32_t value = 1;
//
// // peform reset:
// if (do_reset)
// {
// value |= 2; // reset all... | main | identifier_name | |
goendpoints.go | _GetDeviceInfo succeeded. Device is type %d.\n",
// (int)ftDevice);
//
// /* MUST set Signature1 and 2 before calling FT_EE_Read */
// Data.Signature1 = 0x00000000;
// Data.Signature2 = 0xffffffff;
// Data.Manufacturer = (char *)malloc(256); /* E.g "FTDI" */
// Data.ManufacturerId = (char *)malloc(256); /* E.g... |
defer func() {
if err | {
return nil, err
} | conditional_block |
goendpoints.go | printf("MaxPower = %d\n", Data.MaxPower);
// printf("PnP = %d\n", Data.PnP) ;
// printf("SelfPowered = %d\n", Data.SelfPowered);
// printf("RemoteWakeup = %d\n", Data.RemoteWakeup);
// if (ftDevice == FT_DEVICE_232R)
// {
// /* Rev 6 (FT232R) extensions */
// printf("232R:\n");
// printf("-----\n");
... | random_line_split | ||
goendpoints.go | printf("ProductId = 0x%04X\n", Data.ProductId);
// printf("Manufacturer = %s\n", Data.Manufacturer);
// printf("ManufacturerId = %s\n", Data.ManufacturerId);
// printf("Description = %s\n", Data.Description);
// printf("SerialNumber = %s\n", Data.SerialNumber);
// printf("MaxPower = %d\n", Data.MaxPower); ... | {
t := time.Now()
return t.Format(timeStampLayout)
} | identifier_body | |
movegen.rs | square: Square,
bitboard: BitBoard,
promotion: bool,
}
impl SquareAndBitBoard {
pub fn new(sq: Square, bb: BitBoard, promotion: bool) -> SquareAndBitBoard {
SquareAndBitBoard {
square: sq,
bitboard: bb,
promotion: promotion,
}
}
}
pub type MoveLi... | pub struct SquareAndBitBoard { | random_line_split | |
movegen.rs | ).popcnt() as usize;
}
}
result
}
}
impl Iterator for MoveGen {
type Item = ChessMove;
/// Give a size_hint to some functions that need it
fn size_hint(&self) -> (usize, Option<usize>) {
let len = self.len();
(len, Some(len))
}
/// Find the next che... | movegen_perft_22 | identifier_name | |
movegen.rs | _legal(board: &Board) -> MoveGen {
MoveGen {
moves: MoveGen::enumerate_moves(board),
promotion_index: 0,
iterator_mask: !EMPTY,
index: 0,
}
}
/// Never, ever, iterate any moves that land on the following squares
pub fn remove_mask(&mut self, m... | {
movegen_perft_test("8/5bk1/8/2Pp4/8/1K6/8/8 w - d6 0 1".to_owned(), 6, 824064);
// Invalid FEN
} | identifier_body | |
demo.js | (e, a, l) {
$("#" + e + "_slider").slider({
value: a,
min: 0,
max: 100,
step: 1,
slide: function(a, t) {
$(".btn").button("reset"), $("#" + e + "_percent").text(t.value + "%"), populateTotalPercent(t.value, e), fillInCalorieAmounts(t.value, l, e)
},
... | setupSlider | identifier_name | |
demo.js |
function validateDailyCalsValues(e) {
var a = "";
$.isNumeric($("#age").val()) || (a += "Age value must be a number\n"), $.isNumeric($("#weight").val()) || (a += "Weight value must be a number\n"), $.isNumeric($("#feet_cm").val()) || (a += e ? "Feet " : "Height ", a += "value must be a number\n");
var l =... | {
var e = "standard" === $("input[name='units']:checked").val(),
a = validateDailyCalsValues(e);
if (a) alert(a);
else {
var l = 0,
t = parseFloat($("#weight").val());
e && (t *= .453592);
var s = parseFloat($("#feet_cm").val());
e && (s = 30.48 * s + 2.54... | identifier_body | |
demo.js | 250,
"Gain 1 Pound per Week": 500,
"Gain 1.5 Pounds per Week": 750,
"Gain 2 Pounds per Week": 1e3
},
l = {
"Lose 1 Kg per Week": -1100,
"Lose 0.75 Kg per Week": -825,
"Lose 0.5 Kg per Week": -550,
"Lose 0.25 Kg per Week... | }); | random_line_split | |
inter-compute.ts | .model.atomicHierarchy.residues;
const { occupancy: occupancyA } = unitA.model.atomicConformation;
const { occupancy: occupancyB } = unitB.model.atomicConformation;
const hasOccupancy = occupancyA.isDefined && occupancyB.isDefined;
const structConn = unitA.model === unitB.model && StructConn.Provider.g... | {
const builder = new InterUnitGraph.Builder<number, StructureElement.UnitIndex, InterUnitEdgeProps>();
const hasIndexPairBonds = structure.models.some(m => IndexPairBonds.Provider.get(m));
const hasExhaustiveStructConn = structure.models.some(m => StructConn.isExhaustive(m));
if (props.noCompute || (s... | identifier_body | |
inter-compute.ts | indexB: ElementIndex) {
unitA.conformation.position(indexA, tmpDistVecA);
unitB.conformation.position(indexB, tmpDistVecB);
return v3distance(tmpDistVecA, tmpDistVecB);
}
const _imageTransform = Mat4();
const _imageA = Vec3();
function findPairBonds(unitA: Unit.Atomic, unitB: Unit.Atomic, props: BondComp... | }
}
const beI = getElementIdx(type_symbolB.value(bI)!);
const isHb = isHydrogen(beI);
if (isHa && isHb) continue;
const isMetal = (metalA || MetalsSet.has(beI)) && !(isHa || isHb);
const dist = Math.sqrt(squaredDistances[ni]);
... | random_line_split | |
inter-compute.ts | B: ElementIndex) {
unitA.conformation.position(indexA, tmpDistVecA);
unitB.conformation.position(indexB, tmpDistVecB);
return v3distance(tmpDistVecA, tmpDistVecB);
}
const _imageTransform = Mat4();
const _imageA = Vec3();
function | (unitA: Unit.Atomic, unitB: Unit.Atomic, props: BondComputationProps, builder: InterUnitGraph.Builder<number, StructureElement.UnitIndex, InterUnitEdgeProps>) {
const { maxRadius } = props;
const { elements: atomsA, residueIndex: residueIndexA } = unitA;
const { x: xA, y: yA, z: zA } = unitA.model.atomicCo... | findPairBonds | identifier_name |
update_menu.rs | ly_buttonclicked` method
/// and executing the API command manually without losing the benefit of
/// the updatemenu automatically binding to the state of the plot through
/// the specification of `method` and `args`.
///
/// Default: true
execute: Option<bool>,
/// Sets the text label to ap... | test_serialize_button | identifier_name | |
update_menu.rs | use plotly_derive::FieldSetter;
use serde::Serialize;
use serde_json::{Map, Value};
use crate::{
color::Color,
common::{Anchor, Font, Pad},
Relayout, Restyle,
};
/// Sets the Plotly method to be called on click. If the `skip` method is used,
/// the API updatemenu will function as normal but will perform ... | //! Buttons and Dropdowns.
| random_line_split | |
update_menu.rs | and will not bind automatically to state updates. This may
/// be used to create a component interface and attach to updatemenu
/// events manually via JavaScript.
method: Option<ButtonMethod>,
/// When used in a template, named items are created in the output figure in
/// addition to any items th... | {
let button = Button::new()
.args(json!([
{ "visible": [true, false] },
{ "width": 20},
]))
.args2(json!([]))
.execute(true)
.label("Label")
.method(ButtonMethod::Update)
.name("Name")
... | identifier_body | |
index_lookup.rs | ::{Fields, TermIterator, Terms};
use core::codec::{PostingIterator, PostingIteratorFlags};
use core::doc::Term;
use core::search::{Payload, NO_MORE_DOCS};
use core::util::DocId;
use error::{ErrorKind::IllegalState, Result};
use std::collections::hash_map::HashMap;
#[derive(Debug, Serialize, Deserialize)]
pub struct ... |
}
pub fn set_document(&mut self, doc_id: i32) -> Result<()> {
let mut current_doc_pos = self.current_doc();
if current_doc_pos < doc_id {
current_doc_pos = self.postings.as_mut().unwrap().advance(doc_id)?;
}
if current_doc_pos == doc_id && doc_id < NO_MORE_DOCS {
... | {
NO_MORE_DOCS
} | conditional_block |
index_lookup.rs | ::{Fields, TermIterator, Terms};
use core::codec::{PostingIterator, PostingIteratorFlags};
use core::doc::Term;
use core::search::{Payload, NO_MORE_DOCS};
use core::util::DocId;
use error::{ErrorKind::IllegalState, Result};
use std::collections::hash_map::HashMap;
#[derive(Debug, Serialize, Deserialize)]
pub struct ... |
fn current_doc(&self) -> DocId {
if let Some(ref postings) = self.postings {
postings.doc_id()
} else {
NO_MORE_DOCS
}
}
pub fn set_document(&mut self, doc_id: i32) -> Result<()> {
let mut current_doc_pos = self.current_doc();
if current_doc... | {
self.freq
} | identifier_body |
index_lookup.rs | codec::{Fields, TermIterator, Terms};
use core::codec::{PostingIterator, PostingIteratorFlags};
use core::doc::Term;
use core::search::{Payload, NO_MORE_DOCS};
use core::util::DocId;
use error::{ErrorKind::IllegalState, Result};
use std::collections::hash_map::HashMap;
#[derive(Debug, Serialize, Deserialize)]
pub st... | <T: PostingIterator> {
postings: Option<T>,
flags: u16,
iterator: LeafPositionIterator,
#[allow(dead_code)]
identifier: Term,
freq: i32,
}
impl<T: PostingIterator> LeafIndexFieldTerm<T> {
pub fn new<TI: TermIterator<Postings = T>, Tm: Terms<Iterator = TI>, F: Fields<Terms = Tm>>(
te... | LeafIndexFieldTerm | identifier_name |
index_lookup.rs | codec::{Fields, TermIterator, Terms};
use core::codec::{PostingIterator, PostingIteratorFlags};
use core::doc::Term;
use core::search::{Payload, NO_MORE_DOCS};
use core::util::DocId;
use error::{ErrorKind::IllegalState, Result};
use std::collections::hash_map::HashMap;
#[derive(Debug, Serialize, Deserialize)]
pub st... | LeafIndexFieldTerm<<<T::Terms as Terms>::Iterator as TermIterator>::Postings>,
>,
field_name: String,
doc_id: DocId,
fields: T,
}
///
// Script interface to all information regarding a field.
//
impl<T: Fields + Clone> LeafIndexField<T> {
pub fn new(field_name: &str, doc_id: DocId, fields: ... | terms: HashMap<
String, | random_line_split |
indeploopinputparser.py | inputfile' : (str, 'mast.inp', 'Input file name'),\
}
class IndepLoopInputParser(MASTObj):
"""Scans an input file for "indeploop" keyword and copies it into
many input files.
Attributes:
self.indeploop <str>: flag for independent looping
self.loop_delim <s... | realline=""
split1=""
split2=""
numlines = len(self.baseinput.data)
lidx =0
while lidx < numlines:
dataline = self.baseinput.data[lidx].strip()
if loopkey in dataline:
loopdict[lidx] = dict()
realline=dataline.split(... | random_line_split | |
indeploopinputparser.py | inputfile' : (str, 'mast.inp', 'Input file name'),\
}
class IndepLoopInputParser(MASTObj):
"""Scans an input file for "indeploop" keyword and copies it into
many input files.
Attributes:
self.indeploop <str>: flag for independent looping
self.loop_delim <s... | while lidx < numlines:
dataline = self.baseinput.data[lidx].strip()
if loopkey in dataline:
loopdict[lidx] = dict()
realline=dataline.split(' ',1)[1] #strip off indeploop
split1 = realline.split(self.loop_start)
split2 = spl... | """Scan for loops.
Args:
loopkey <str>: string for searching for loops. This is
either "indeploop" or "pegloop"
Return:
loopdict <dict>: Dictionary where loop line indices in the file
are keys, with values
... | identifier_body |
indeploopinputparser.py | inputfile' : (str, 'mast.inp', 'Input file name'),\
}
class IndepLoopInputParser(MASTObj):
"""Scans an input file for "indeploop" keyword and copies it into
many input files.
Attributes:
self.indeploop <str>: flag for independent looping
self.loop_delim <s... |
elif pegged == 1:
if len(loopkeys) == 0:
return combolist #Empty list
numloop = len(loopdict[loopkeys[0]]['looplist']) #all same len
numct=0
while numct < numloop:
flatlist=list()
for loopkey in loopkeys:
... | try:
mycomb = prod_list.next()
except StopIteration:
stopiter = 1
if stopiter == 0:
combolist.append(list(mycomb)) | conditional_block |
indeploopinputparser.py | inputfile' : (str, 'mast.inp', 'Input file name'),\
}
class IndepLoopInputParser(MASTObj):
"""Scans an input file for "indeploop" keyword and copies it into
many input files.
Attributes:
self.indeploop <str>: flag for independent looping
self.loop_delim <s... | (self, alldict, comblist):
"""Prepare looped lines from looping dictionary.
Args:
loopdict <dict>: dictionary of looping items from
scan_for_loop
Returns:
loopline_dict <dict of dict>: dictionary of different lines for
... | prepare_looped_lines | identifier_name |
concepts.ts | atua no desenvolvimento de aplicativos ou sistemas, programando nativamente ou por meio de outras linguagens, para dispositivos móveis.`,
},
{
key: `SQL`,
value: `SQL é uma linguagem declarativa de sintaxe relativamente simples, voltada a bancos de dados relacionais`,
},
{
key: `API - Interface de p... | {
key: `Linguagem de Programação`,
value: `A linguagem de programação é um método padronizado, formado por um conjunto de regras sintáticas e semânticas, de implementação de um código fonte - que pode ser compilado e transformado em um programa de computador, ou usado como script interpretado - que informará ... | {
key: `DevOps`,
value: `Na Ciência da Computação o DevOps, é uma cultura na engenharia de software que aproxima os desenvolvedores de software e os operadores do software / administradores do sistema, com característica `,
}, | random_line_split |
b-button.ts | nearest containing form, if any.
*
* The form prop lets you place a component anywhere in the document but have it included with a form elsewhere
* in the document.
*
* @see https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#htmlattrdefform
*
* @example
* ```
* < b-input :name = 'fname' ... | onFileChange | identifier_name | |
b-button.ts | (iAccess, iOpenToggle)
class bButton extends iData implements iAccess, iOpenToggle, iVisible, iWidth, iSize {
override readonly rootTag: string = 'span';
override readonly dataProvider: string = 'Provider';
override readonly defaultRequestFilter: RequestFilter = true;
/** @see [[iVisible.prototype.hideIfOffline]] ... |
if (this.hasDropdown) {
attrs['aria-controls'] = this.dom.getId('dropdown');
attrs['aria-expanded'] = this.mods.opened;
}
return attrs;
}
/** @see [[iAccess.isFocused]] */
@computed({dependencies: ['mods.focused']})
get isFocused(): boolean {
const
{button} = this.$refs;
// eslint-disable-ne... | {
attrs.type = this.type;
attrs.form = this.form;
} | conditional_block |
b-button.ts | derive(iAccess, iOpenToggle)
class bButton extends iData implements iAccess, iOpenToggle, iVisible, iWidth, iSize {
override readonly rootTag: string = 'span';
override readonly dataProvider: string = 'Provider';
override readonly defaultRequestFilter: RequestFilter = true;
/** @see [[iVisible.prototype.hideIfOffl... | /**
* A button' type to create. There can be values:
*
* 1. `button` - simple button control;
* 2. `submit` - button to send the tied form;
* 3. `file` - button to open the file uploading dialog;
* 4. `link` - hyperlink to the specified URL (to provide URL, use the `href` prop).
*
* @example
* ```
... | random_line_split | |
b-button.ts | (iAccess, iOpenToggle)
class bButton extends iData implements iAccess, iOpenToggle, iVisible, iWidth, iSize {
override readonly rootTag: string = 'span';
override readonly dataProvider: string = 'Provider';
override readonly defaultRequestFilter: RequestFilter = true;
/** @see [[iVisible.prototype.hideIfOffline]] ... |
static override readonly mods: ModsDecl = {
...iAccess.mods,
...iVisible.mods,
...iWidth.mods,
...iSize.mods,
opened: [
...iOpenToggle.mods.opened ?? [],
['false']
],
| {
return Boolean(
this.vdom.getSlot('dropdown') && (
this.isFunctional ||
this.opt.ifOnce('opened', this.m.opened !== 'false') > 0 && delete this.watchModsStore.opened
)
);
} | identifier_body |
properties.ts | ;
bgn_channels: never[];
'2_4GHz_channels': number[];
'5GHz_DFS_channels': number[];
g_only_channels: never[];
region: number;
'5GHz_channels': number[];
'5GHz_wide_channels': number[];
'2_4GHz_n_only_channels': never[];
bg_channels: never[];
an_channels: never[];
b_only_chan... | raEA: boolean;
rTSN: boolean; | random_line_split | |
main.rs | r + ox, y * r + oy);
route.push(p);
}
route.push(route[0]);
routes.push(route);
}
r -= dr;
}
routes
}
fn heart(ox: f64, oy: f64, r: f64, ang: f64) -> Vec<(f64, f64)> {
let mut route = Vec::new();
let count = (2.0 * PI * r / 0.5).floor() as usize;
for i in 0..count {
let... | () {
let opts: Opts = Opts::parse();
let groups = art(&opts);
let mut document = base_document("white", opts.width, opts.height);
for g in groups {
document = document.add(g);
}
svg::save(opts.file, &document).unwrap();
}
struct PaintMask {
mask: Vec<bool>,
precision: f64,
width: f64,
height: f... | main | identifier_name |
main.rs | r + ox, y * r + oy);
route.push(p);
}
route.push(route[0]);
routes.push(route);
}
r -= dr;
}
routes
}
fn heart(ox: f64, oy: f64, r: f64, ang: f64) -> Vec<(f64, f64)> {
let mut route = Vec::new();
let count = (2.0 * PI * r / 0.5).floor() as usize;
for i in 0..count {
let... |
passage.count_once_from(&localpassage);
}
routes = paths;
let bounds = (pad, pad, width - pad, height - pad);
let in_shape = |p: (f64, f64)| -> bool {
!mask.is_painted(p) && strictly_in_boundaries(p, bounds)
};
let does_overlap = |c: &VCircle| {
in_shape((c.x, c.y))
&& circle_route((c.... | {
paths.push(path);
} | conditional_block |
main.rs | = |c: &VCircle| {
in_shape((c.x, c.y))
&& circle_route((c.x, c.y), c.r, 8)
.iter()
.all(|&p| in_shape(p))
};
let ppad = rng.gen_range(0.4, 0.8);
let min = rng.gen_range(1.5, 2.0);
let max = min + rng.gen_range(0.0, 5.0);
let optim = rng.gen_range(1, 10);
let count = 2000;
let c... | {
let wi = (width / granularity).ceil() as usize;
let hi = (height / granularity).ceil() as usize;
let counters = vec![0; wi * hi];
Passage2DCounter {
granularity,
width,
height,
counters,
}
} | identifier_body | |
main.rs | * r + ox, y * r + oy);
route.push(p);
}
route.push(route[0]);
routes.push(route);
}
r -= dr;
}
routes
}
fn heart(ox: f64, oy: f64, r: f64, ang: f64) -> Vec<(f64, f64)> {
let mut route = Vec::new();
let count = (2.0 * PI * r / 0.5).floor() as usize;
for i in 0..count {
l... | routes.push(heart(x, y, r, ang));
}
routes
}
fn art(opts: &Opts) -> Vec<Group> {
let width = opts.width;
let height = opts.height;
let cw = width / 2.;
let ch = height / 2.;
let pad = 5.;
let cols = (width / cw).floor() as usize;
let rows = (height / ch).floor() as usize;
let offsetx = 0.0;... | PI + (c.x - width / 2.0).atan2(c.y - height / 2.0)
}; | random_line_split |
config.go | :"DRONE_SERVER_HOST" default:"localhost:8080"`
Port string `envconfig:"DRONE_SERVER_PORT" default:":8080"`
Proto string `envconfig:"DRONE_SERVER_PROTO" default:"http"`
Pprof bool `envconfig:"DRONE_PPROF_ENABLED"`
Acme bool `envconfig:"DRONE_TLS_AUTOCERT"`
Email string `envconfig:"DRONE_TLS_EMAIL"`
Cer... | IsGitHub | identifier_name | |
config.go | Secret string `envconfig:"DRONE_WEBHOOK_SECRET"`
SkipVerify bool `envconfig:"DRONE_WEBHOOK_SKIP_VERIFY"`
}
// Yaml provides the yaml webhook configuration.
Yaml struct {
Endpoint string `envconfig:"DRONE_YAML_ENDPOINT"`
Secret string `envconfig:"DRONE_YAML_SECRET"`
SkipVerify bool `envco... | {
c.Runner.OS = parts[0]
} | conditional_block | |
config.go |
Jsonnet struct {
Enabled bool `envconfig:"DRONE_JSONNET_ENABLED"`
}
// Kubernetes provides kubernetes configuration
Kubernetes struct {
Enabled bool `envconfig:"DRONE_KUBERNETES_ENABLED"`
Namespace string `envconfig:"DRONE_KUBERNETES_NAMESPACE"`
Path string `envconfig:"... | }
Agent struct {
Disabled bool `envconfig:"DRONE_AGENTS_DISABLED"`
}
// Runner provides the runner configuration.
Runner struct {
Local bool `envconfig:"DRONE_RUNNER_LOCAL"`
Image string `envconfig:"DRONE_RUNNER_IMAGE" default:"drone/controller:1"`
Platform string ... | Secret string `envconfig:"DRONE_RPC_SECRET"`
Debug bool `envconfig:"DRONE_RPC_DEBUG"`
Host string `envconfig:"DRONE_RPC_HOST"`
Proto string `envconfig:"DRONE_RPC_PROTO"`
// Hosts map[string]string `envconfig:"DRONE_RPC_EXTRA_HOSTS"` | random_line_split |
config.go | gitea client configuration.
Gitea struct {
Server string `envconfig:"DRONE_GITEA_SERVER"`
ClientID string `envconfig:"DRONE_GITEA_CLIENT_ID"`
ClientSecret string `envconfig:"DRONE_GITEA_CLIENT_SECRET"`
SkipVerify bool `envconfig:"DRONE_GITEA_SKIP_VERIFY"`
Scope []string `envconf... | {
return fmt.Sprint(*b)
} | identifier_body | |
runner.rs | map(comn::TickNum)
.collect();
if crossed_tick_nums.len() > MAX_TICKS_PER_UPDATE {
// It's possible that we have a large jump in ticks, e.g. due to a
// lag spike, or because we are running in a background tab. In this
// case, we don't want to overload ourselves... | {
let recv_tick_num = tick.diff.tick_num;
let recv_game_time = self.settings.tick_game_time(recv_tick_num);
// Keep some statistics for debugging...
self.stats.loss.record_received(recv_tick_num.0 as usize);
if let Some(my_last_input_num) = tick.your_last_input_num.as_ref() {
... | identifier_body | |
runner.rs | ) {
self.send(comn::ClientMessage::Ping(sequence_num));
}
// Determine new local game time, making sure to stay behind the receive
// stream by our desired lag time. We do this so that we have ticks
// between which we can interpolate.
//
// If we are off too... | .map(|(entity_id, entity)| (*entity_id, entity.clone())),
);
} | random_line_split | |
runner.rs | (&self) -> &Stats {
&self.stats
}
pub fn ping(&self) -> &PingEstimation {
&self.ping
}
pub fn interp_game_time(&self) -> comn::GameTime {
self.interp_game_time
}
fn target_time_lag(&self) -> comn::GameTime {
self.settings.tick_period() * 1.5
}
fn tick_... | stats | identifier_name | |
runner.rs | ) -> &Stats {
&self.stats
}
pub fn ping(&self) -> &PingEstimation {
&self.ping
}
pub fn interp_game_time(&self) -> comn::GameTime {
self.interp_game_time
}
fn target_time_lag(&self) -> comn::GameTime {
self.settings.tick_period() * 1.5
}
fn tick_num(&s... |
}
// Remove events for older ticks, we will no longer need them. Note,
// however, that the same cannot be said about the received states,
// since we may still need them as the basis for delta decoding.
// Received states are only pruned when we receive new states.
{
... | {
self.next_tick_num = Some(*min_ready_num);
} | conditional_block |
main.js | grape', 'watermelon', 'raspberry', 'blackberry', 'strawberry', 'banana', 'peach', 'pear', 'cherry', 'grapefruit', 'kiwi', 'mango', 'lemon', 'avocado', 'cantaloupe', 'apricot', 'papaya', 'fig', 'tangerine', 'pomegranate', 'coconut', 'cranberry', 'passionfruit', 'lychee', 'loquat', 'pitaya', 'jujube', 'boysenberry', 'tan... |
// convert secret arr to string
secret = secret.join('');
while (checkIndex >= 0) {
// update secret arr
secret = this.updateSecretWord(checkIndex, guess, secret);
// move to next index of word, reassign checkIndex
chec... | {
this.guessesLeft--;
this.guessedLetters.push(guess);
this.updateGuessesUI();
return false;
} | conditional_block |
main.js | grape', 'watermelon', 'raspberry', 'blackberry', 'strawberry', 'banana', 'peach', 'pear', 'cherry', 'grapefruit', 'kiwi', 'mango', 'lemon', 'avocado', 'cantaloupe', 'apricot', 'papaya', 'fig', 'tangerine', 'pomegranate', 'coconut', 'cranberry', 'passionfruit', 'lychee', 'loquat', 'pitaya', 'jujube', 'boysenberry', 'tan... | // reset guessedLetters innerHTML
guessedLettersElem.innerHTML = '';
},
showGuessInfo: function () {
this.updateGuessesUI();
// reset guessedLetters innerHTML
| });
},
hideGuessInfo: function () {
guessesLeftElem.innerHTML = ''; | random_line_split |
Genetic_algorithm.py | for i in range(0,25):
for j in range(10,20):
random_selection.append(array[j])
for i in range(0,20):
for j in range(20,30):
random_selection.append(array[j])
for i in range(0,7):
for j in range(30,40):
random_selection.append(arra... | se()
salmon = []
seabass = []
#읽어들인 txt파일을 줄단위로 읽어들여서 list에 저장한다
for line in salmon_t:
a=line.split()
salmon.append([float(a[0]),float(a[1])])
for line in seabass_t:
a=line.split()
seabass.append([float(a[0]),float(a[1])])
def runExp(popSize, elitNum, mutProb):
print 'training...' #학습 서브루틴
... | )
seabass = []
for line in seabass_t:
a = line.split()
seabass.append([float(a[0]),float(a[1])])
##### text 파일
fd1 = open('salmon_test.txt','r')
salmon_t = fd1.readlines()
fd1.close()
fd2 = open('seabass_test.txt','r')
seabass_t = fd2.readlines()
fd2.clo | identifier_body |
Genetic_algorithm.py |
for i in range(0,25):
for j in range(10,20):
random_selection.append(array[j])
for i in range(0,20):
for j in range(20,30):
random_selection.append(array[j])
for i in range(0,7):
for j in range(30,40):
random_selection.ap... | genetic_array = []
genetic_array.extend(child_array)
genetic_array.extend(elitism_array)
genetic_array.sort()
low_e = genetic_array[0][0]
print('%d%s%f%s%f%s%f' % (count,'th elit parameter =>', genetic_array[0][1],' ',genetic_array[0][2],' ',genetic_array[0][3... | #다음 세대 염색체를 리스트로 합친다 | random_line_split |
Genetic_algorithm.py | for i in range(0,25):
for j in range(10,20):
random_selection.append(array[j])
for i in range(0,20):
for j in range(20,30):
random_selection.append(array[j])
for i in range(0,7):
for j in range(30,40):
random_selection.append(arra... | i+1][3]
else:
tmp_x = array[i][1]
tmp_y = array[i][2]
tmp_z = array[i+1][3]
tmp = [0,tmp_x,tmp_y,tmp_z]
# 랜덤값이 확률값보다 작을때 뮤테이션
if(random.uniform(0,100) < mutProb*100):
tmp = Mutation(tmp)
tmp = Erroreval_simple(tmp)... | = array[ | identifier_name |
Genetic_algorithm.py | for i in range(0,25):
for j in range(10,20):
random_selection.append(array[j])
for i in range(0,20):
for j in range(20,30):
random_selection.append(array[j])
for i in range(0,7):
for j in range(30,40):
r |
for i in range(0,6):
for j in range(40,50):
random_selection.append(array[j])
for i in range(0,5):
for j in range(50,60):
random_selection.append(array[j])
for i in range(0,4):
for j in range(6... | andom_selection.append(array[j])
| conditional_block |
main.go | }
logs.Debug("etcd clientv3.New success")
defer cli.Close()
//获取key所对应的值
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
resp, err1 := cli.Get(ctx, key)
logs.Debug("etcd get key=%s sucess\n", key)
cancel()
if err1 != nil {
logs.Error("cli.Get err", err1)
err = err1
}
for _, ev := ... | conditional_block | ||
main.go | keycollect]), &CollectList)
if err != nil {
logs.Error("json Unmarshal etcdkeycollect err:%v", err)
}
for i := 0; i < len(CollectList); i++ {
if CollectList[i].update == nil {
CollectList[i].update = make(chan bool)
}
}
logs.Debug("获取的配置信息:%v", AppConfig)
//根据etcd读取配置文件 开始跟踪日志
endpoints := [... | Endpoints: endpoint,
DialTimeout: 5 * time.Second,
})
if err != nil {
fmt.Println("clientv3.New err", err)
}
defer cli.Close()
//是否需要更新etcd的值
b := false
//监听该值的变化
fmt.Println("watching keys", key)
rch := cli.Watch(context.Background(), key, clientv3.WithPrefix())
var (
k, v string
)
for wresp := r... | result := make(map[string]string, len(key))
cli, err := clientv3.New(clientv3.Config{ | random_line_split |
main.go | // //没有则创建
// err = os.MkdirAll(logpath, os.ModeDir)
// if err != nil {
// config["filename"] = `longagent.log`
// } else {
// config["filename"] = path + `\logagent\Logs\longagent.log`
// }
// //设置不同级别的分开写
// config["separate"] = []string{"error", "info", "debug"}
// //输出调用的文件名和文件行号 默认是false
// logs.Enabl... | ver revice path:%s and sendmsg to kafka:", collectionInfo.Path)
if msgsend, ok = <-lines; ok {
logs.Info("sendmsg to kafak msg is %s\n", msgsend.Text)
msg := &sarama.ProducerMessage{
Topic: collectionInfo.Topic,
Value: sarama.StringEncoder(msgsend.Text),
}
pid, offset, err = client.SendMessage(ms... | identifier_body | |
main.go | keycollect]), &CollectList)
if err != nil {
logs.Error("json Unmarshal etcdkeycollect err:%v", err)
}
for i := 0; i < len(CollectList); i++ {
if CollectList[i].update == nil {
CollectList[i].update = make(chan bool)
}
}
logs.Debug("获取的配置信息:%v", AppConfig)
//根据etcd读取配置文件 开始跟踪日志
endpoints := [... | keycollect)
}(&myConfig)
conf, err := config.NewConfig(configType, path)
if err != nil {
logs.Error("new config failed, err:", err)
}
logs.Debug("读取配置得路径是:", path)
myConfig.kafkaAddr = conf.String("kafka::addr")
if len(myConfig.kafkaAddr) == 0 {
myConfig.kafkaAddr = "127.0.0.1:9092"
err = errors.New("Not... | onfig.etcd | identifier_name |
articlesearch.py | == 200:
raw_json = json.loads(await response.read())
with open("Settings.json", "w+") as file:
json.dump(raw_json, file, indent=2)
with open("Settings.json") as file:
return json.load(file)
async def connect(host: str = "localhost", database: str = "postgres", use... |
# Date info
date_article = bs4.find("p").get_text()
date_article = datetime.datetime.strptime(date_article, "%d %b %Y")
if date_article.year >= 3300:
date_article = date_article.replace(year=(date_article.year - GAME_YEAR_OFFSET))
added.append(article)
await... | entry_title = "No Title Available"
text = unquote(bs4.find_all("p")[1].get_text().replace("'", "''")) | random_line_split |
articlesearch.py | == 200:
raw_json = json.loads(await response.read())
with open("Settings.json", "w+") as file:
json.dump(raw_json, file, indent=2)
with open("Settings.json") as file:
return json.load(file)
async def connect(host: str = "localhost", database: str = "postgres", use... |
elif "after" in option:
year = datetime.datetime.strptime(option[6:], "%Y-%m-%d").year
# Convert date to format stored in table
if year >= 3300:
converted_year = str(year - GAME_YEAR_OFFSET) + option[10:]
datebegin = da... | year = datetime.datetime.strptime(option[7:], "%Y-%m-%d").year
# Convert date to format stored table
if year >= 3300:
converted_year = str(year - GAME_YEAR_OFFSET) + option[11:]
dateend = datetime.datetime.strptime(converted_year, "%Y-%m-%d")
... | conditional_block |
articlesearch.py |
async def fetch_settings():
if not os.path.exists("Settings.json"):
async with aiohttp.ClientSession() as settings_session:
async with settings_session.get(
"https://raw.githubusercontent.com/HassanAbouelela/Galnet-Newsfeed/"
"4499a01e6b5a679b807e95697e... | old_settings = await fetch_settings()
try:
old = old_settings["version"]
except KeyError:
old = "1.0"
new_settings = await fetch_settings()
os.remove("Settings.json")
for key in old_settings.keys():
if key in new_settings.keys():
new_settings[key] = old_settings... | identifier_body | |
articlesearch.py | == 200:
raw_json = json.loads(await response.read())
with open("Settings.json", "w+") as file:
json.dump(raw_json, file, indent=2)
with open("Settings.json") as file:
return json.load(file)
async def connect(host: str = "localhost", database: str = "postgres", use... | ():
"""Looks for new articles."""
# Load Settings
settings = await fetch_settings()
table = settings["table"]
async with aiohttp.ClientSession() as session:
async with session.get("https://community.elitedangerous.com/") as response:
html = Bs4(await response.text(), "html.p... | update | identifier_name |
ppo_fetch_reach.py |
class ActorCritic(nn.Module):
'''
continous action space PG methods the actor returns tensor of lenght number of action
and those tensors are mean and covariance -- use Gaussian Distribution to Sample from action space
covarinace is used to balance exploration-exploitation problem
'''
def _... | def __init__(self):
self.actions = []
#in our case self.inputs ==> input state//goal
self.states = []
self.logprobs = []
self.rewards = []
self.is_terminals = []
def clear_memory(self):
#in ddpg you can learn from data stored from older epochs
del... | identifier_body | |
ppo_fetch_reach.py | (reversed(memory.rewards), reversed(memory.is_terminals)):
if is_terminal:
discounted_reward = 0
discounted_reward = reward + (self.gamma * discounted_reward)
#insert the new discounted reward - after completing the episode - in index number 0 and push old ones
... | local_success_rate = []
state_ = env.reset()
state = np.concatenate([state_['observation'], state_['desired_goal']])
for t in range(env._max_episode_steps):
local_timestep += 1
time_step +=1
# Running policy_old:
action ... | conditional_block | |
ppo_fetch_reach.py | anh()
)
#the output of network is the mean of actions
# critic
self.critic = nn.Sequential(
nn.Linear(state_dim, 256),
nn.ReLU(),
nn.Linear(256, 256),
nn.ReLU(),
nn.Linear(256, 256),
... | rewards = torch.tensor(rewards).to(device)
rewards = (rewards - rewards.mean()) / (rewards.std() + 1e-5)
# convert list to tensor
old_states = torch.squeeze(torch.stack(memory.states).to(device), 1).detach()
old_actions = torch.squeeze(torch.stack(memory.actions).to(devi... |
# Normalizing the rewards: | random_line_split |
ppo_fetch_reach.py | :
def __init__(self):
self.actions = []
#in our case self.inputs ==> input state//goal
self.states = []
self.logprobs = []
self.rewards = []
self.is_terminals = []
def clear_memory(self):
#in ddpg you can learn from data stored from older epochs
... | Memory | identifier_name | |
bot.js |
}else if(global.dictmode == 1){
var res = request.split(' ').map(e=>closest.request(e)).filter(e=>e.query != null && e.answer != 'false')
if(res.length == 0) return false
else return res[0].answer
}
}
};
const bot = {
lpevent, msgevent, amsgevent, dict, VK, api, colors,
status(newstat... | и об аккаунте...`);
api.call('users.get', {}).then(res =>{
authid = res[0].id
console.log(`[${il.ts()} | init]`.green,`Успешно авторизовано как ${colors.green(res[0].first_name+' '+res[0].last_name+' (ID: '+res[0].id+')')}`);
});
//Set status
api.call('status.set', {text: opts.status ? o... | `[${il.ts()} | init]`.green,`Получение информаци | identifier_body |
bot.js |
}else if(global.dictmode == 1){
var res = request.split(' ').map(e=>closest.request(e)).filter(e=>e.query != null && e.answer != 'false')
if(res.length == 0) return false
else return res[0].answer
}
}
};
const bot = {
lpevent, msgevent, amsgevent, dict, VK, api, colors,
status(newstat... | en, o)
closest.setlow(opts.dictmatch || 1)
global.dictmode = opts.dictmode || 0
closest.setlow('false');
global.botname = opts.botname.map(e => e.toLowerCase());
//Authorize user
console.log(`[${il.ts()} | init]`.green,`Получение информации об аккаунте...`);
api.call('users.get', {}).then(re... | pts.tok | identifier_name |
bot.js | Пользователь ${userid} кэширован`.green);
fs.writeFile('cache.json', JSON.stringify(global.cache, null, 2), null);
resolve({id: userid, fname: res[0].first_name, lname: res[0].last_name});
})
}
})
}
answer.forEach(function(ans){
... | bot.sendmsg('user', msgobj.id, allow.message)
}
}
})
}
};
| conditional_block | |
bot.js | , reject){ // Parses user id and saves it to cache, or returns value from cache
if(global.cache[userid]){
resolve({id: userid, fname: global.cache[userid][0], lname: global.cache[userid][1]});
}else{
api.call('users.get', {user_ids: userid}).then(res => {
... | msgevent.emit(cmd[0].toLowerCase(), msgobj);
}
} | random_line_split | |
column_extractor.py | that can be tweaked
LINE_THICKNESS = 3 # how thick to make the line around the found contours in the debug output
PADDING = 10 # padding to add around the found possible column to help account for image skew and such
CREATE_COLUMN_OUTLINE_IMAGES = True # if we detect that we didn't find all the columns. Create a debug... | if f.endswith(".jpg"):
#test(cv2.imread(os.path.join('./ocr/data/gb19gw39h/', f)), 'gb19gw39h-' + f[0])
createColumnImages(cv2.imread(os.path.join('./ocr/data/gb19gw39h/', f)), 'gb19gw39h-' + f[0], './ocr/columns/gb19gw39h/') | conditional_block | |
column_extractor.py | import sys
os.environ['OPENCV_IO_ENABLE_JASPER']='True' # has to be set before importing cv2 otherwise it won't read the variable
import numpy as np
import cv2
import subprocess
from multiprocessing import Pool
from scipy.signal import find_peaks, find_peaks_cwt
import scipy.ndimage as ndimage
from IPython.display im... | import io
from pathlib import Path | random_line_split | |
column_extractor.py | )
# Original image size
orignrows, origncols = gray.shape
# Windows size
M = int(np.floor(orignrows/16) + 1)
N = int(np.floor(origncols/16) + 1)
# Image border padding related to windows size
Mextend = round(M/2)-1
Nextend = round(N/2)-1
# Padding image
aux =cv2.copyMakeBorder(gr... |
def createColumnImages(img, basename, directory):
"""
we sum each column of the inverted image. The columns should show up as peaks in the sums
uses scipy.signal.find_peaks to find those peaks and use them as column indexes
"""
files = []
temp_img = convertToGrayscale(img)
temp_img = inver... | """
It is just opposite of erosion. Here, a pixel element is '1' if atleast one pixel under the kernel is '1'.
So it increases the white region in the image or size of foreground object increases.
Normally, in cases like noise removal, erosion is followed by dilation.
Because, erosion removes white n... | identifier_body |
column_extractor.py | (img, threshold):
# Load image
I = img
# Convert image to grayscale
gray = cv2.cvtColor(I, cv2.COLOR_BGR2GRAY)
# Original image size
orignrows, origncols = gray.shape
# Windows size
M = int(np.floor(orignrows/16) + 1)
N = int(np.floor(origncols/16) + 1)
# Image border padding rel... | adaptative_thresholding | identifier_name | |
on_initialize.rs | (unused)]
use crate::process::ShellCommand;
use crate::stdio_server::job;
use crate::stdio_server::provider::{Context, ProviderSource};
use crate::tools::ctags::ProjectCtagsCommand;
use crate::tools::rg::{RgTokioCommand, RG_EXEC_CMD};
use anyhow::Result;
use filter::SourceItem;
use printer::{DisplayLines, Printer};
use... | Ok(Err(e)) => tracing::error!(?e, "Error occurred while initializing the provider source"),
Err(_) => {
// The initialization was not super fast.
tracing::debug!(timeout = ?TIMEOUT, "Did not receive value in time");
let source_cmd: Vec<String> = ctx.vim.bare_call("pr... | {
// Skip the initialization.
match ctx.provider_id() {
"grep" | "live_grep" => return Ok(()),
_ => {}
}
if ctx.env.source_is_list {
let ctx = ctx.clone();
ctx.set_provider_source(ProviderSource::Initializing);
// Initialize the list-style providers in another ta... | identifier_body |
on_initialize.rs | (unused)]
use crate::process::ShellCommand;
use crate::stdio_server::job;
use crate::stdio_server::provider::{Context, ProviderSource};
use crate::tools::ctags::ProjectCtagsCommand;
use crate::tools::rg::{RgTokioCommand, RG_EXEC_CMD};
use anyhow::Result;
use filter::SourceItem;
use printer::{DisplayLines, Printer};
use... | (ctx: &Context, init_display: bool) -> Result<()> {
// Skip the initialization.
match ctx.provider_id() {
"grep" | "live_grep" => return Ok(()),
_ => {}
}
if ctx.env.source_is_list {
let ctx = ctx.clone();
ctx.set_provider_source(ProviderSource::Initializing);
//... | initialize_provider | identifier_name |
on_initialize.rs | allow(unused)]
use crate::process::ShellCommand;
use crate::stdio_server::job;
use crate::stdio_server::provider::{Context, ProviderSource};
use crate::tools::ctags::ProjectCtagsCommand;
use crate::tools::rg::{RgTokioCommand, RG_EXEC_CMD};
use anyhow::Result;
use filter::SourceItem;
use printer::{DisplayLines, Printer}... | };
return Ok(provider_source);
}
"help_tags" => {
let helplang: String = ctx.vim.eval("&helplang").await?;
let runtimepath: String = ctx.vim.eval("&runtimepath").await?;
let doc_tags = std::iter::once("/doc/tags".to_string()).chain(
... | }
} | random_line_split |
on_initialize.rs | (unused)]
use crate::process::ShellCommand;
use crate::stdio_server::job;
use crate::stdio_server::provider::{Context, ProviderSource};
use crate::tools::ctags::ProjectCtagsCommand;
use crate::tools::rg::{RgTokioCommand, RG_EXEC_CMD};
use anyhow::Result;
use filter::SourceItem;
use printer::{DisplayLines, Printer};
use... |
})
.collect::<Vec<_>>();
on_initialized_source(to_small_provider_source(lines), &ctx, init_display)?;
}
Ok(())
}
pub async fn initialize_provider(ctx: &Context, init_display: bool) -> Result<()> {
// Skip the initialization.
match ctx.provider_id() {
"grep" | "... | {
None
} | conditional_block |
start-router.js | ) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } }
function ownKeys(object, enumerableOnly) |
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties... | { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } | identifier_body |
start-router.js | (arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } }
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOn... | _arrayWithoutHoles | identifier_name | |
start-router.js | ) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } }
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) ... | _ref$runAllEvents = _ref.runAllEvents,
runAllEvents = _ref$runAllEvents === void 0 ? false : _ref$runAllEvents,
config = _objectWithoutProperties(_ref, ["resources", "runAllEvents"]);
var store = new _routerStore.RouterStore();
typeof rootStore === 'function' ? rootStore = rootStore(store) : root... |
var startRouter = function startRouter(views, rootStore) {
var _ref = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
var resources = _ref.resources, | random_line_split |
index.ts | (device));
return { inEndpoint, outEndpoint };
};
const initializeRNDIS = (device: usb.Device): usb.InEndpoint => {
const interfaceNumber = 0;
const iface0 = device.interface(interfaceNumber);
iface0.claim();
const iEndpoint = iface0.endpoints[0];
if (!(iEndpoint instanceof usb.InEndpoint)) {
throw new ... | transfer | identifier_name | |
index.ts | ENT=INTERFACE
const bmRequestTypeReceive = 0xa1; // USB_DATA=DeviceToHost | USB_TYPE=CLASS | USB_RECIPIENT=INTERFACE
// Sending rndis_init_msg (SEND_ENCAPSULATED_COMMAND)
device.controlTransfer(bmRequestTypeSend, 0, 0, 0, initMsg, error => {
if (error) {
throw new Error(`Control transfer error on SEND_... | {
return;
} | conditional_block | |
index.ts | throw new Error(`Control transfer error on SEND_ENCAPSULATED ${error}`);
}
});
// Receive rndis_init_cmplt (GET_ENCAPSULATED_RESPONSE)
device.controlTransfer(bmRequestTypeReceive, 0x01, 0, 0, CONTROL_BUFFER_SIZE, error => {
if (error) {
throw new Error(`Control transfer error on GET_ENCAPSULATED $... | {
this.attachedDeviceIds.delete(getDeviceId(device));
if (!isUsbBootCapableUSBDevice$(device)) {
return;
}
setTimeout(() => {
const usbBBbootDevice = this.get(device);
if (usbBBbootDevice !== undefined && usbBBbootDevice.step === UsbBBbootDevice.LAST_STEP) {
debug('device', dev... | identifier_body | |
index.ts | }
}
iface.claim();
const inEndpoint = iface.endpoints[0];
const outEndpoint = iface.endpoints[1];
if (!(inEndpoint instanceof usb.InEndpoint)) {
throw new Error('endpoint is not an usb.OutEndpoint');
}
if (!(outEndpoint instanceof usb.OutEndpoint)) {
throw new Error('endpoint is not an usb.Out... | if (serverConfig.tftp) {
if (serverConfig.tftp.blocks <= serverConfig.tftp.blocks) {
this.transfer(device, outEndpoint, request, tftpBuff, this.stepCounter++); | random_line_split | |
sudoku.go | []line
m_sets []Solver
m_cells [][]cell
}
func New(puzzle [COL_LENGTH][ROW_LENGTH]int) (*Grid, error){
var g Grid
g.Init();
g.Fill(puzzle)
return &g,nil
}
func (g *Grid) validate() bool{
for x,_ := range g.m_cells{
for y,_:= range g.m_cells[x]{
if !g.m_cells[x][y].validate(){
return false
}
... | {
var err error
for changed:=true; changed;{
changed, err = g.reducePossiblePass()
if err != nil{
return &SolveResult{nil,false},err
}
if !g.validate(){
return &SolveResult{nil,false},nil //this was probably an invalid guess, just want to stop trying to process this
}
}
solved,err := g.Solved()
... | identifier_body | |
sudoku.go | }
func (c cell) String() string {
val,err := c.Known()
if(err != nil){
return "x"
}
return strconv.Itoa(val)
}
type cellPtrSlice []*cell
func (cells cellPtrSlice) Solved() (bool, error){
for _,c := range cells{
if !c.IsKnown(){
return false,nil
}
}
return true,nil
}
func (cells cellPtrSlice) Kn... | (){
l.m_cells = make([]*cell,COL_LENGTH,COL_LENGTH)
}
func (l line) Solved() (bool,error) {
return l.m_cells.Solved()
}
func (l* line) reducePossible() (bool,error) {
known,err := l.m_cells.Known()
if err != nil {
return false,err
}
reduced, err := l.m_cells.TakeKnownFromPossible(known)
if err != nil{
... | init | identifier_name |
sudoku.go | represent one of each of the 9 squares in a Grid, each of which
//references a 3x3 collection of cells.
type square struct {
m_cells [][]*cell
}
func (s square) Solved() (bool,error) {
for _,r := range s.m_cells{
solved,err := cellPtrSlice(r).Solved()
if(err != nil){
return false,err
}
if !solved {
... | {
fmt.Println("Error during Solved() check on grid: " + err.Error())
return false,err
} | conditional_block | |
sudoku.go | }
func (c cell) String() string {
val,err := c.Known()
if(err != nil){
return "x"
}
return strconv.Itoa(val)
}
type cellPtrSlice []*cell
func (cells cellPtrSlice) Solved() (bool, error){
for _,c := range cells{
if !c.IsKnown(){
return false,nil
}
}
return true,nil
}
func (cells cellPtrSlice) Kn... | g.Init();
g.Fill(puzzle)
return &g,nil
}
func (g *Grid) validate() bool{
for x,_ := range g.m_cells{
for y,_:= range g.m_cells[x]{
if !g.m_cells[x][y].validate(){
return false
}
}
}
for i,_ := range g.m_sets{
if !g.m_sets[i].validate(){
return false
}
}
return true
}
func (g *Grid) ... | random_line_split | |
MedicalRecordsQueryForm.js | .type == "long") {
it.type = "int";
}
var f;
if (it.id == "BRZD") {
f = this.createRemoteDicField(it);
} else if (it.xtype == "combination") {
it.index = i;
f = this.createCombinationField(it);
table.items.push(f);
continue;
} else {
f = this.createFiel... | JLSJKSN.setValue();
JLSJKSN.disable();
JLSJJSN.setValue();
JLSJJSN.disable();
}
| conditional_block | |
MedicalRecordsQueryForm.js | }
break;
case "date" :
v = v.format("Y-m-d");
cnds[1] = [
'$',
"str(" + value
+ ",'yyyy-MM-dd')"];
cnds.push(['s', v]);
break;
}
}
cnd = ['and', cnd, cnds];
}
}
}
cnd = thi... | cnds[0] = 'like';
if (it.id == "BRZD") {
cnds.push(['s', '%'+v + '%']);
} else {
cnds.push(['s', v + '%']); | random_line_split | |
ParamEffectsProcessedFCD.py | 250, 300]
# [0.1, 0.2, 0.5, 1.0, 2.0, 5.0, 10.0, 20., 50.] #how many taxis in percent of the total vehicles | single element or a hole list
quota = [0.1, 0.2, 0.5, 1.0, 2.0, 5.0, 10.0, 20., 50.]
iteration = 2
vehId = 0
vehIdDict = {}
edgeDumpDict = None
vtypeDict = None
vehList = None
vehSum = None
procFcdDict = None... | vtypeDictR = procFcdDict[(period, quota)]
else:
vtypeDictR = reduceVtype(taxis)
del taxis
yield(period, quota, vtypeDictR, taxiSum)
def readEdgeDump():
"""Get for each interval all edges with corresponding speed."""
edgeDumpDict = {}
beg... | global period, quota
"""Generates all period-quota-sets (with creation of new Taxis for each set).
You can iterate over that generator and gets for each step the period and quota.
If stopByPeriod=True it stops not only in the quota block but in the period block to-> have a look at the code.
"""
if ... | identifier_body |
ParamEffectsProcessedFCD.py | 250, 300]
# [0.1, 0.2, 0.5, 1.0, 2.0, 5.0, 10.0, 20., 50.] #how many taxis in percent of the total vehicles | single element or a hole list
quota = [0.1, 0.2, 0.5, 1.0, 2.0, 5.0, 10.0, 20., 50.]
iteration = 2
vehId = 0
vehIdDict = {}
edgeDumpDict = None
vtypeDict = None
vehList = None
vehSum = None
procFcdDict = None... | (vtypeDict):
"""Collects all vehicles used in the simulation."""
vehSet = set()
for timestepList in vtypeDict.values():
for elm in timestepList:
vehSet.add(elm[0])
return list(vehSet)
def make(source, dependentOn, builder, buildNew=False, *builderParams):
"""Fills the target (a... | getVehicleList | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.