file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
gru_model.py | # -*- coding: utf-8 -*-
"""Intent GRU Model 90+.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1zH4GNqFS_Z4PxGEueU5Y6g_qOevCl-6d
<a href="https://colab.research.google.com/github/Dark-Sied/Intent_Classification/blob/master/Intent_classification_... | return input_ids
def create_single_input(self,sentence,maxlen):
stokens = self.tokenizer.tokenize(sentence)
stokens = stokens[:maxlen]
stokens = ["[CLS]"] + stokens + ["[SEP]"]
ids = self.get_ids(stokens, self.tokenizer, self.max_len)
masks = self.get_masks(stoken... | random_line_split | |
gru_model.py | # -*- coding: utf-8 -*-
"""Intent GRU Model 90+.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1zH4GNqFS_Z4PxGEueU5Y6g_qOevCl-6d
<a href="https://colab.research.google.com/github/Dark-Sied/Intent_Classification/blob/master/Intent_classification_... |
class PreprocessingBertData():
def prepare_data_x(self,train_sentences):
x = bert_model_obj.create_input_array(train_sentences)
return x
def prepare_data_y(self,train_labels):
y = list()
for item in train_labels:
label = item
y.append(label)
... | 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 | ############ Author:################################
# Marcin Cuber
#####################################################
# GA17 Privacy Enhancing Technologies -- Lab 01
#
# Basics of Petlib, encryption, signatures and
# an end-to-end encryption system.
#
# Run the tests through:
# $ py.test-2.7 -v Lab01Tests.py ... | ():
""" Returns an EC group, a random private key for signing
and the corresponding public key for verification"""
G = EcGroup()
priv_sign = G.order().random()
pub_verify = priv_sign * G.generator()
return (G, priv_sign, pub_verify)
def ecdsa_sign(G, priv_sign, message):
""" Sign the ... | ecdsa_key_gen | identifier_name |
Lab01Code.py | ############ Author:################################
# Marcin Cuber
#####################################################
# GA17 Privacy Enhancing Technologies -- Lab 01
#
# Basics of Petlib, encryption, signatures and
# an end-to-end encryption system.
#
# Run the tests through:
# $ py.test-2.7 -v Lab01Tests.py ... |
def point_double(a, b, p, x, y):
"""Define "doubling" an EC point.
A special case, when a point needs to be added to itself.
Reminder:
lam = 3 * x ^ 2 + a * (2 * y) ^ -1 (mod p)
xr = lam ^ 2 - 2 * xp
yr = lam * (xp - xr) - yp (mod p)
Returns the point representing the dou... | """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 | ############ Author:################################
# Marcin Cuber
#####################################################
# GA17 Privacy Enhancing Technologies -- Lab 01
#
# Basics of Petlib, encryption, signatures and
# an end-to-end encryption system.
#
# Run the tests through:
# $ py.test-2.7 -v Lab01Tests.py ... |
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 | ############ Author:################################
# Marcin Cuber
#####################################################
# GA17 Privacy Enhancing Technologies -- Lab 01
#
# Basics of Petlib, encryption, signatures and
# an end-to-end encryption system.
#
# Run the tests through:
# $ py.test-2.7 -v Lab01Tests.py ... | 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 | //! Methods for lower the HIR to types.
pub(crate) use self::diagnostics::LowerDiagnostic;
use crate::resolve::{HasResolver, TypeNs};
use crate::ty::{Substitution, TyKind};
use crate::{
arena::map::ArenaMap,
code_model::StructKind,
diagnostics::DiagnosticSink,
name_resolution::Namespace,
primitive_... | 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
.params()
.iter()
.map(|tr| Ty... | random_line_split | |
lower.rs | //! Methods for lower the HIR to types.
pub(crate) use self::diagnostics::LowerDiagnostic;
use crate::resolve::{HasResolver, TypeNs};
use crate::ty::{Substitution, TyKind};
use crate::{
arena::map::ArenaMap,
code_model::StructKind,
diagnostics::DiagnosticSink,
name_resolution::Namespace,
primitive_... |
pub(crate) fn fn_sig_for_struct_constructor(db: &dyn HirDatabase, def: Struct) -> FnSig {
let data = def.data(db.upcast());
let resolver = def.id.resolver(db.upcast());
let params = data
.fields
.iter()
.map(|(_, field)| Ty::from_hir(db, &resolver, data.type_ref_map(), field.type_r... | {
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 | //! Methods for lower the HIR to types.
pub(crate) use self::diagnostics::LowerDiagnostic;
use crate::resolve::{HasResolver, TypeNs};
use crate::ty::{Substitution, TyKind};
use crate::{
arena::map::ArenaMap,
code_model::StructKind,
diagnostics::DiagnosticSink,
name_resolution::Namespace,
primitive_... | else {
type_for_struct(db, def)
}
}
fn type_for_struct(_db: &dyn HirDatabase, def: Struct) -> Ty {
TyKind::Struct(def).intern()
}
fn type_for_type_alias(_db: &dyn HirDatabase, def: TypeAlias) -> Ty {
TyKind::TypeAlias(def).intern()
}
pub mod diagnostics {
use crate::diagnostics::{PrivateAcce... | {
TyKind::FnDef(def.into(), Substitution::empty()).intern()
} | conditional_block |
lower.rs | //! Methods for lower the HIR to types.
pub(crate) use self::diagnostics::LowerDiagnostic;
use crate::resolve::{HasResolver, TypeNs};
use crate::ty::{Substitution, TyKind};
use crate::{
arena::map::ArenaMap,
code_model::StructKind,
diagnostics::DiagnosticSink,
name_resolution::Namespace,
primitive_... | (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 | import * as functions from 'firebase-functions'
import fetch from 'node-fetch'
import { WriteBatch, Timestamp } from '@google-cloud/firestore'
import moment, { Moment } from 'moment'
import 'moment-timezone'
const admin = require('firebase-admin')
admin.initializeApp();
const firestore = admin.firestore()
const storag... | ()
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 | import * as functions from 'firebase-functions'
import fetch from 'node-fetch'
import { WriteBatch, Timestamp } from '@google-cloud/firestore'
import moment, { Moment } from 'moment'
import 'moment-timezone'
const admin = require('firebase-admin')
admin.initializeApp();
const firestore = admin.firestore()
const storag... | 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 | import * as functions from 'firebase-functions'
import fetch from 'node-fetch'
import { WriteBatch, Timestamp } from '@google-cloud/firestore'
import moment, { Moment } from 'moment'
import 'moment-timezone'
const admin = require('firebase-admin')
admin.initializeApp();
const firestore = admin.firestore()
const storag... | 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 | import * as functions from 'firebase-functions'
import fetch from 'node-fetch'
import { WriteBatch, Timestamp } from '@google-cloud/firestore'
import moment, { Moment } from 'moment'
import 'moment-timezone'
const admin = require('firebase-admin')
admin.initializeApp();
const firestore = admin.firestore()
const storag... | // // 日付が指定されていない場合は当日を指定する。
// if (!fromDate.match(/[0-9]{4}-[0-9]{2}-[0-9]{2}/)) {
// fromDate = moment().tz('Asia/Tokyo').format('YYYY-MM-DD')
// }
//
// const importedNum = await importBitFlyerLogs(fromDate)
// response.send(`Imported ${importedNum} messages. fromDate=${fromDate}`)
//})
/**
* デプロイ日時を更新するF... | // }
//
// let fromDate = request.query.from_date || '' | random_line_split |
goendpoints.go | package main
//#cgo CFLAGS: -O2
//#cgo LDFLAGS: -L. -lftd2xx -Wl,-rpath /usr/local/lib
//#include <stdint.h>
//#include <stdio.h>
//#include <stdlib.h>
//#include <sys/time.h>
//#include "ftd2xx.h"
//
//FT_STATUS ftStatus;
//FT_HANDLE ftHandle0;
//
//char * readMsg() {
// DWORD RxBytes = 64;
// DWORD BytesReceived;
//... | () {
C.setup()
//avgDelay, avgJitter := calculateDelayJitter()
calculateDelayJitter()
//fmt.Printf("Avg. Delay = %v ns\n", avgDelay)
//fmt.Printf("Avg. Jitter = %v ns\n", avgJitter)
//priority_test(f, avgDelay)
}
| main | identifier_name |
goendpoints.go | package main
//#cgo CFLAGS: -O2
//#cgo LDFLAGS: -L. -lftd2xx -Wl,-rpath /usr/local/lib
//#include <stdint.h>
//#include <stdio.h>
//#include <stdlib.h>
//#include <sys/time.h>
//#include "ftd2xx.h"
//
//FT_STATUS ftStatus;
//FT_HANDLE ftHandle0;
//
//char * readMsg() {
// DWORD RxBytes = 64;
// DWORD BytesReceived;
//... |
defer func() {
if err != nil && f != nil {
f.Close()
}
}()
fd := f.Fd()
// Set serial port 'name' to 115200/8/N/1 in RAW mode (i.e. no pre-process of received data
// and pay special attention to Cc field, this tells the serial port to not return until at
// at least syscall.VMIN bytes have been read. ... | {
return nil, err
} | conditional_block |
goendpoints.go | package main
//#cgo CFLAGS: -O2
//#cgo LDFLAGS: -L. -lftd2xx -Wl,-rpath /usr/local/lib
//#include <stdint.h>
//#include <stdio.h>
//#include <stdlib.h>
//#include <sys/time.h>
//#include "ftd2xx.h"
//
//FT_STATUS ftStatus;
//FT_HANDLE ftHandle0;
//
//char * readMsg() {
// DWORD RxBytes = 64;
// DWORD BytesReceived;
//... | t0 := parseTimestamp(p0)
t1 := parseTimestamp(p1)
t2 := parseTimestamp(p2)
t3 := parseTimestamp(p3)
delayRTT := (t3.Sub(t0) + t2.Sub(t1))
//fmt.Printf("RTT delay: %v\n", delayRTT)
return int64(delayRTT.Nanoseconds())
}
func exchangeTimestamps() int64 {
// client = coordinator, server = endpoints. We are server... | random_line_split | |
goendpoints.go | package main
//#cgo CFLAGS: -O2
//#cgo LDFLAGS: -L. -lftd2xx -Wl,-rpath /usr/local/lib
//#include <stdint.h>
//#include <stdio.h>
//#include <stdlib.h>
//#include <sys/time.h>
//#include "ftd2xx.h"
//
//FT_STATUS ftStatus;
//FT_HANDLE ftHandle0;
//
//char * readMsg() {
// DWORD RxBytes = 64;
// DWORD BytesReceived;
//... |
func parseTimestamp(timestamp string) time.Time {
t, e := time.Parse(timeStampLayout, timestamp)
if e != nil {
fmt.Printf("Parse error occured: %v\n", e)
}
return t
}
func calculateDelayRTT(p0 string, p1 string, p2 string, p3 string) int64 {
// parse time stamp string
t0 := parseTimestamp(p0)
t1 := parseTi... | {
t := time.Now()
return t.Format(timeStampLayout)
} | identifier_body |
movegen.rs | use crate::bitboard::{BitBoard, EMPTY};
use crate::board::Board;
use crate::chess_move::ChessMove;
use crate::magic::between;
use crate::movegen::piece_type::*;
use crate::piece::{Piece, NUM_PROMOTION_PIECES, PROMOTION_PIECES};
use crate::square::Square;
use arrayvec::ArrayVec;
use nodrop::NoDrop;
use std::iter::ExactS... | 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 | use crate::bitboard::{BitBoard, EMPTY};
use crate::board::Board;
use crate::chess_move::ChessMove;
use crate::magic::between;
use crate::movegen::piece_type::*;
use crate::piece::{Piece, NUM_PROMOTION_PIECES, PROMOTION_PIECES};
use crate::square::Square;
use arrayvec::ArrayVec;
use nodrop::NoDrop;
use std::iter::ExactS... | () {
movegen_perft_test("8/8/8/8/8/p7/8/k1K5 b - - 0 1".to_owned(), 6, 2217);
}
#[test]
fn movegen_perft_23() {
movegen_perft_test("8/k1P5/8/1K6/8/8/8/8 w - - 0 1".to_owned(), 7, 567584);
}
#[test]
fn movegen_perft_24() {
movegen_perft_test("8/8/8/8/1k6/8/K1p5/8 b - - 0 1".to_owned(), 7, 567584);
}
#[tes... | movegen_perft_22 | identifier_name |
movegen.rs | use crate::bitboard::{BitBoard, EMPTY};
use crate::board::Board;
use crate::chess_move::ChessMove;
use crate::magic::between;
use crate::movegen::piece_type::*;
use crate::piece::{Piece, NUM_PROMOTION_PIECES, PROMOTION_PIECES};
use crate::square::Square;
use arrayvec::ArrayVec;
use nodrop::NoDrop;
use std::iter::ExactS... |
#[test]
fn movegen_perft_2() {
movegen_perft_test("8/8/1k6/8/2pP4/8/5BK1/8 b - d3 0 1".to_owned(), 6, 824064);
// Invalid FEN
}
#[test]
fn movegen_perft_3() {
movegen_perft_test("8/8/1k6/2b5/2pP4/8/5K2/8 b - d3 0 1".to_owned(), 6, 1440467);
}
#[test]
fn movegen_perft_4() {
movegen_perft_test("8/5k2/... | {
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 | /* eslint no-alert: 0 */
'use strict';
//
// Here is how to define your module
// has dependent on mobile-angular-ui
//
function populateTotalPercent(e, a) {
if ("carb" == a) l = e + parseInt($("#protein_slider").slider("value")) + parseInt($("#fat_slider").slider("value"));
else if ("protein" == a) l = e + p... | (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 | /* eslint no-alert: 0 */
'use strict';
//
// Here is how to define your module
// has dependent on mobile-angular-ui
//
function populateTotalPercent(e, a) {
if ("carb" == a) l = e + parseInt($("#protein_slider").slider("value")) + parseInt($("#fat_slider").slider("value"));
else if ("protein" == a) l = e + p... |
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 | /* eslint no-alert: 0 */
'use strict';
//
// Here is how to define your module
// has dependent on mobile-angular-ui
//
function populateTotalPercent(e, a) {
if ("carb" == a) l = e + parseInt($("#protein_slider").slider("value")) + parseInt($("#fat_slider").slider("value"));
else if ("protein" == a) l = e + p... | }
drag.reset();
}
});
}
};
});
app.directive('dragMe', ['$drag', function($drag) {
return {
controller: function($scope, $element) {
$drag.bind($element,
{
//
// Here you can see how to limit movement
// to an element
/... | }); | random_line_split |
inter-compute.ts | /**
* Copyright (c) 2017-2023 Mol* contributors, licensed under MIT, See LICENSE file for more info.
*
* @author David Sehnal <david.sehnal@gmail.com>
* @author Alexander Rose <alexander.rose@weirdbyte.de>
*/
import { BondType, MoleculeType } from '../../../model/types';
import { Structure } from '../../structure... |
function computeInterUnitBonds(structure: Structure, props?: Partial<InterBondComputationProps>): InterUnitBonds {
const p = { ...DefaultInterBondComputationProps, ...props };
return findBonds(structure, {
...p,
validUnit: (props && props.validUnit) || (u => Unit.isAtomic(u)),
validUni... | {
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 | /**
* Copyright (c) 2017-2023 Mol* contributors, licensed under MIT, See LICENSE file for more info.
*
* @author David Sehnal <david.sehnal@gmail.com>
* @author Alexander Rose <alexander.rose@weirdbyte.de>
*/
import { BondType, MoleculeType } from '../../../model/types';
import { Structure } from '../../structure... | }
}
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 | /**
* Copyright (c) 2017-2023 Mol* contributors, licensed under MIT, See LICENSE file for more info.
*
* @author David Sehnal <david.sehnal@gmail.com>
* @author Alexander Rose <alexander.rose@weirdbyte.de>
*/
import { BondType, MoleculeType } from '../../../model/types';
import { Structure } from '../../structure... | (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 | //! Buttons and Dropdowns.
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... | () {
let button = Button::new()
.args(json!([
{ "visible": [true, false] },
{ "width": 20},
]))
.args2(json!([]))
.execute(true)
.label("Label")
.method(ButtonMethod::Update)
.name("Name")
... | 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 | //! Buttons and Dropdowns.
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... |
#[test]
fn test_button_builder() {
let expected = json!({
"args": [
{ "visible": [true, false] },
{ "title": {"text": "Hello"}, "width": 20},
],
"label": "Label",
"method": "update",
"name": "Name",
... | {
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 | // Copyright 2019 Zhizhesihai (Beijing) Technology Limited.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by a... |
}
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 | // Copyright 2019 Zhizhesihai (Beijing) Technology Limited.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by a... |
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 | // Copyright 2019 Zhizhesihai (Beijing) Technology Limited.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by a... | <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 | // Copyright 2019 Zhizhesihai (Beijing) Technology Limited.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by a... | 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 | ##############################################################
# This code is part of the MAterials Simulation Toolkit (MAST)
#
# Maintainer: Tam Mayeshiba
# Last updated: 2014-04-25
##############################################################
import os
import numpy as np
import pymatgen as pmg
from MAST.utility i... | 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 | ##############################################################
# This code is part of the MAterials Simulation Toolkit (MAST)
#
# Maintainer: Tam Mayeshiba
# Last updated: 2014-04-25
##############################################################
import os
import numpy as np
import pymatgen as pmg
from MAST.utility i... |
def get_combo_list(self, loopdict, pegged=0):
"""Prepare a combination list of looping indices.
Args:
loopdict <dict>: dictionary of looping items from
scan_for_loop
Returns:
combolist <list of str>: list of st... | """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 | ##############################################################
# This code is part of the MAterials Simulation Toolkit (MAST)
#
# Maintainer: Tam Mayeshiba
# Last updated: 2014-04-25
##############################################################
import os
import numpy as np
import pymatgen as pmg
from MAST.utility i... |
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 | ##############################################################
# This code is part of the MAterials Simulation Toolkit (MAST)
#
# Maintainer: Tam Mayeshiba
# Last updated: 2014-04-25
##############################################################
import os
import numpy as np
import pymatgen as pmg
from MAST.utility i... | (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 | import { DataFormat } from '../../helpers';
const data: DataFormat[] = [
{
key: `Algoritmo`,
value: `Em matemática e ciência da computação, um algoritmo é uma sequência finita de ações executáveis que visam obter uma solução para um determinado tipo de problema. Segundo Dasgupta, Papadimitriou e Vazirani, "a... | {
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 | /*!
* V4Fire Client Core
* https://github.com/V4Fire/Client
*
* Released under the MIT license
* https://github.com/V4Fire/Client/blob/master/LICENSE
*/
/**
* [[include:form/b-button/README.md]]
* @packageDocumentation
*/
import { derive } from 'core/functools/trait';
//#if runtime has core/data
import 'cor... | (e: Event): void {
this.emit('change', e);
}
}
export default bButton;
| onFileChange | identifier_name |
b-button.ts | /*!
* V4Fire Client Core
* https://github.com/V4Fire/Client
*
* Released under the MIT license
* https://github.com/V4Fire/Client/blob/master/LICENSE
*/
/**
* [[include:form/b-button/README.md]]
* @packageDocumentation
*/
import { derive } from 'core/functools/trait';
//#if runtime has core/data
import 'cor... |
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 | /*!
* V4Fire Client Core
* https://github.com/V4Fire/Client
*
* Released under the MIT license
* https://github.com/V4Fire/Client/blob/master/LICENSE
*/
/**
* [[include:form/b-button/README.md]]
* @packageDocumentation
*/
import { derive } from 'core/functools/trait';
//#if runtime has core/data
import 'cor... | /**
* 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 | /*!
* V4Fire Client Core
* https://github.com/V4Fire/Client
*
* Released under the MIT license
* https://github.com/V4Fire/Client/blob/master/LICENSE
*/
/**
* [[include:form/b-button/README.md]]
* @packageDocumentation
*/
import { derive } from 'core/functools/trait';
//#if runtime has core/data
import 'cor... |
static override readonly mods: ModsDecl = {
...iAccess.mods,
...iVisible.mods,
...iWidth.mods,
...iSize.mods,
opened: [
...iOpenToggle.mods.opened ?? [],
['false']
],
upper: [
'true',
'false'
]
};
protected override readonly $refs!: {
button: HTMLButtonElement;
file?: HTMLInputEl... | {
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 | type types = {
DynS: DynS;
cfpf: cfpf;
cloD: cloD;
fire: fire;
syLR: syLR;
syAR: syAR;
sySI: sySI;
CLTM: CLTM;
sPLL: sPLL;
sySt: sySt;
syIg: syIg;
timz: timz;
usrd: usrd;
stat: stat;
dSpn: dSpn;
raSL: raSL;
raSR: raSR;
WiFi: WiFi;
rCAL: rCAL;
... | /** Hidden/closed network */
raCl: boolean;
/** WPA Group Key Timeout */
raKT: number;
raWM: number;
}
export interface rCAL {
// Nothing here?
}
export interface waDI {
// TODO
}
export interface DRes {
dhcpReservations: DHCPReservation[];
}
export interface DHCPReservation {
de... | raEA: boolean;
rTSN: boolean; | random_line_split |
main.rs | use clap::*;
use gre::*;
use noise::*;
use rand::prelude::*;
use rayon::prelude::*;
use std::f64::consts::PI;
use svg::node::element::path::Data;
use svg::node::element::*;
#[derive(Parser)]
#[clap()]
pub struct Opts {
#[clap(short, long, default_value = "image.svg")]
file: String,
#[clap(short, long, default_va... | () {
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 | use clap::*;
use gre::*;
use noise::*;
use rand::prelude::*;
use rayon::prelude::*;
use std::f64::consts::PI;
use svg::node::element::path::Data;
use svg::node::element::*;
#[derive(Parser)]
#[clap()]
pub struct Opts {
#[clap(short, long, default_value = "image.svg")]
file: String,
#[clap(short, long, default_va... |
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 | use clap::*;
use gre::*;
use noise::*;
use rand::prelude::*;
use rayon::prelude::*;
use std::f64::consts::PI;
use svg::node::element::path::Data;
use svg::node::element::*;
#[derive(Parser)]
#[clap()]
pub struct Opts {
#[clap(short, long, default_value = "image.svg")]
file: String,
#[clap(short, long, default_va... |
fn index(self: &Self, (x, y): (f64, f64)) -> usize {
let wi = (self.width / self.granularity).ceil() as usize;
let hi = (self.height / self.granularity).ceil() as usize;
let xi = ((x / self.granularity).round() as usize).max(0).min(wi - 1);
let yi = ((y / self.granularity).round() as usize).max(0).mi... | {
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 | use clap::*;
use gre::*;
use noise::*;
use rand::prelude::*;
use rayon::prelude::*;
use std::f64::consts::PI;
use svg::node::element::path::Data;
use svg::node::element::*;
#[derive(Parser)]
#[clap()]
pub struct Opts {
#[clap(short, long, default_value = "image.svg")]
file: String,
#[clap(short, long, default_va... | 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 | // Copyright 2019 Drone IO, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to... | () bool {
return c.Github.ClientID != ""
}
// IsGitHubEnterprise returns true if the GitHub
// integration is activated.
func (c *Config) IsGitHubEnterprise() bool {
return c.IsGitHub() && !strings.HasPrefix(c.Github.Server, "https://github.com")
}
// IsGitLab returns true if the GitLab integration
// is activated.... | IsGitHub | identifier_name |
config.go | // Copyright 2019 Drone IO, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to... |
if len(parts) == 2 && c.Runner.Arch == "" {
c.Runner.Arch = parts[1]
}
}
func defaultSession(c *Config) {
if c.Session.Secret == "" {
c.Session.Secret = uniuri.NewLen(32)
}
}
func configureGithub(c *Config) {
if c.Github.APIServer != "" {
return
}
if c.Github.Server == "https://github.com" {
c.Github.... | {
c.Runner.OS = parts[0]
} | conditional_block |
config.go | // Copyright 2019 Drone IO, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to... | }
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 | // Copyright 2019 Drone IO, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to... |
// UserCreate stores account information used to bootstrap
// the admin user account when the system initializes.
type UserCreate struct {
Username string
Machine bool
Admin bool
Token string
}
// Decode implements a decoder that extracts user information
// from the environment variable string.
func (u *... | {
return fmt.Sprint(*b)
} | identifier_body |
runner.rs | use std::{
collections::{BTreeMap, VecDeque},
sync::Arc,
time::Duration,
};
use instant::Instant;
use log::{debug, info, warn};
use comn::util::{diff::Diff, stats, GameTimeEstimation, LossEstimation, PingEstimation};
use crate::{prediction::Prediction, webrtc};
pub struct ReceivedState {
pub game: c... |
}
| {
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 | use std::{
collections::{BTreeMap, VecDeque},
sync::Arc,
time::Duration,
};
use instant::Instant;
use log::{debug, info, warn};
use comn::util::{diff::Diff, stats, GameTimeEstimation, LossEstimation, PingEstimation};
use crate::{prediction::Prediction, webrtc};
pub struct ReceivedState {
pub game: c... | }
state
}
pub fn next_entities(&self) -> BTreeMap<comn::EntityId, (comn::GameTime, comn::Entity)> {
let mut entities = BTreeMap::new();
// Add entities from authorative state, if available.
let next_state = self
.next_tick_num
.and_then(|key| se... | .map(|(entity_id, entity)| (*entity_id, entity.clone())),
);
} | random_line_split |
runner.rs | use std::{
collections::{BTreeMap, VecDeque},
sync::Arc,
time::Duration,
};
use instant::Instant;
use log::{debug, info, warn};
use comn::util::{diff::Diff, stats, GameTimeEstimation, LossEstimation, PingEstimation};
use crate::{prediction::Prediction, webrtc};
pub struct ReceivedState {
pub game: c... | (&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 | use std::{
collections::{BTreeMap, VecDeque},
sync::Arc,
time::Duration,
};
use instant::Instant;
use log::{debug, info, warn};
use comn::util::{diff::Diff, stats, GameTimeEstimation, LossEstimation, PingEstimation};
use crate::{prediction::Prediction, webrtc};
pub struct ReceivedState {
pub game: c... |
}
// 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 | var wordElem = document.getElementById("word");
var guessedLettersElem = document.getElementById('letters-guessed');
var guessesLeftElem = document.getElementById('guesses-left');
var winLoseMsg = document.getElementById('win-or-lose-message');
var categoryUI = document.getElementById('category');
var ALPH_LENGTH = 26;... |
// 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 | var wordElem = document.getElementById("word");
var guessedLettersElem = document.getElementById('letters-guessed');
var guessesLeftElem = document.getElementById('guesses-left');
var winLoseMsg = document.getElementById('win-or-lose-message');
var categoryUI = document.getElementById('category');
var ALPH_LENGTH = 26;... | // reset guessedLetters innerHTML
guessedLettersElem.innerHTML = '';
},
showGuessInfo: function () {
this.updateGuessesUI();
// reset guessedLetters innerHTML
guessedLettersElem.innerHTML = 'Guessed Letters: ';
},
updateGuessesUI: function () {
guessesLeft... | });
},
hideGuessInfo: function () {
guessesLeftElem.innerHTML = ''; | random_line_split |
Genetic_algorithm.py | import random
import matplotlib.pyplot as plt
import numpy as np
import sys
import os.path as op
#개체 각각의 적합도 계산
#리스트의 리스트 형식일 때 사용
def Erroreval(array):
for j in range(0,len(array)):
count = 0
for i in range(0,50):
if (array[j][1]*salmon[i][0]+array[j][2]*salmon[i][1]+array[j][3])>0:
... | 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 | import random
import matplotlib.pyplot as plt
import numpy as np
import sys
import os.path as op
#개체 각각의 적합도 계산
#리스트의 리스트 형식일 때 사용
def Erroreval(array):
for j in range(0,len(array)):
count = 0
for i in range(0,50):
if (array[j][1]*salmon[i][0]+array[j][2]*salmon[i][1]+array[j][3])>0:
... | 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 | import random
import matplotlib.pyplot as plt
import numpy as np
import sys
import os.path as op
#개체 각각의 적합도 계산
#리스트의 리스트 형식일 때 사용
def Erroreval(array):
for j in range(0,len(array)):
count = 0
for i in range(0,50):
if (array[j][1]*salmon[i][0]+array[j][2]*salmon[i][1]+array[j][3])>0:
... | 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 | import random
import matplotlib.pyplot as plt
import numpy as np
import sys
import os.path as op
#개체 각각의 적합도 계산
#리스트의 리스트 형식일 때 사용
def Erroreval(array):
for j in range(0,len(array)):
count = 0
for i in range(0,50):
if (array[j][1]*salmon[i][0]+array[j][2]*salmon[i][1]+array[j][3])>0:
... |
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 | package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"os"
"sync"
"time"
"github.com/Shopify/sarama"
"github.com/astaxie/beego/config"
"github.com/astaxie/beego/logs"
"github.com/coreos/etcd/clientv3"
"github.com/coreos/etcd/mvcc/mvccpb"
"github.com/hpcloud/tail"
)
//CollectionInfo 需要收集日志的信息
ty... | conditional_block | ||
main.go | package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"os"
"sync"
"time"
"github.com/Shopify/sarama"
"github.com/astaxie/beego/config"
"github.com/astaxie/beego/logs"
"github.com/coreos/etcd/clientv3"
"github.com/coreos/etcd/mvcc/mvccpb"
"github.com/hpcloud/tail"
)
//CollectionInfo 需要收集日志的信息
ty... | 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 | package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"os"
"sync"
"time"
"github.com/Shopify/sarama"
"github.com/astaxie/beego/config"
"github.com/astaxie/beego/logs"
"github.com/coreos/etcd/clientv3"
"github.com/coreos/etcd/mvcc/mvccpb"
"github.com/hpcloud/tail"
)
//CollectionInfo 需要收集日志的信息
ty... | ok {
logs.Info("sendmsg to kafak msg is %s:", msgsend.Text)
msg := &sarama.ProducerMessage{
Topic: topic,
Value: sarama.StringEncoder(msgsend.Text),
}
pid, offset, err = client.SendMessage(msg)
if err != nil {
logs.Error("client.SendMesage err:", err)
return
}
logs.Info("sendmsg to... | 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 | package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"os"
"sync"
"time"
"github.com/Shopify/sarama"
"github.com/astaxie/beego/config"
"github.com/astaxie/beego/logs"
"github.com/coreos/etcd/clientv3"
"github.com/coreos/etcd/mvcc/mvccpb"
"github.com/hpcloud/tail"
)
//CollectionInfo 需要收集日志的信息
ty... | 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 | # Copyright (c) 2020 Hassan Abouelela
# Licensed under the MIT License
import datetime
import json
import os
import re
from urllib.parse import unquote
import aiohttp
import asyncpg
from bs4 import BeautifulSoup as Bs4
GAME_YEAR_OFFSET = 1286
async def upgrade():
old_settings = await fetch_settings()
try... |
# 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 | # Copyright (c) 2020 Hassan Abouelela
# Licensed under the MIT License
import datetime
import json
import os
import re
from urllib.parse import unquote
import aiohttp
import asyncpg
from bs4 import BeautifulSoup as Bs4
GAME_YEAR_OFFSET = 1286
async def upgrade():
old_settings = await fetch_settings()
try... |
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 | # Copyright (c) 2020 Hassan Abouelela
# Licensed under the MIT License
import datetime
import json
import os
import re
from urllib.parse import unquote
import aiohttp
import asyncpg
from bs4 import BeautifulSoup as Bs4
GAME_YEAR_OFFSET = 1286
async def upgrade():
|
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 | # Copyright (c) 2020 Hassan Abouelela
# Licensed under the MIT License
import datetime
import json
import os
import re
from urllib.parse import unquote
import aiohttp
import asyncpg
from bs4 import BeautifulSoup as Bs4
GAME_YEAR_OFFSET = 1286
async def upgrade():
old_settings = await fetch_settings()
try... | ():
"""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 | import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.distributions import MultivariateNormal
import gym
import numpy as np
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
class Memory:
|
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 | import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.distributions import MultivariateNormal
import gym
import numpy as np
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
class Memory:
def __init__(self):
self.actions = []
#in our case self.inputs =... |
return test_success_rate
if __name__ == '__main__':
launch()
np.savetxt('/home/muhyahiarl/ppo_grad_project/ppo_grad_project_handmanipulateeggfull_nepoch_350.txt',epoch_success_rate,delimiter=',')
| 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 | import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.distributions import MultivariateNormal
import gym
import numpy as np
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
class Memory:
def __init__(self):
self.actions = []
#in our case self.inputs =... | 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 | import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.distributions import MultivariateNormal
import gym
import numpy as np
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
class | :
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 | process.stdout.setEncoding('utf8');
const greet = [
'╔═════════════════════════════╗',
'║ sBot v2.3.1 Europium ║',
'║ Made by m4l3vich, 2017 ║',
'╚═════════════════════════════╝',
''
];
class events extends require('events') {}
const ievent = new events(); // Internal events
const lpevent = new e... | и об аккаунте...`);
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 | process.stdout.setEncoding('utf8');
const greet = [
'╔═════════════════════════════╗',
'║ sBot v2.3.1 Europium ║',
'║ Made by m4l3vich, 2017 ║',
'╚═════════════════════════════╝',
''
];
class events extends require('events') {}
const ievent = new events(); // Internal events
const lpevent = new e... | 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 | process.stdout.setEncoding('utf8');
const greet = [
'╔═════════════════════════════╗',
'║ sBot v2.3.1 Europium ║',
'║ Made by m4l3vich, 2017 ║',
'╚═════════════════════════════╝',
''
];
class events extends require('events') {}
const ievent = new events(); // Internal events
const lpevent = new e... | bot.sendmsg('user', msgobj.id, allow.message)
}
}
})
}
};
| conditional_block | |
bot.js | process.stdout.setEncoding('utf8');
const greet = [
'╔═════════════════════════════╗',
'║ sBot v2.3.1 Europium ║',
'║ Made by m4l3vich, 2017 ║',
'╚═════════════════════════════╝',
''
];
class events extends require('events') {}
const ievent = new events(); // Internal events
const lpevent = new e... | }
amsgevent.emit(msgobj.msg.full.toLowerCase(), msgobj);
}else if(allow instanceof Error && allow.message){
console.log(`[${il.ts()} | filter ~>] ${allow.message}`.red)
if(msgobj.type == 'conv'){
bot.sendmsg('conv', msgobj.id, bot.getAnswer(msgobj)+allow.message);
... | msgevent.emit(cmd[0].toLowerCase(), msgobj);
}
} | random_line_split |
column_extractor.py |
# https://github.com/jscancella/NYTribuneOCRExperiments/blob/master/findText_usingSums.py
import os
import io
from pathlib import Path
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 ... |
for f in os.listdir('./ocr/data/8k71pf94q/'):
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/8k71pf94q/', f)), '8k71pf94q-' + f[0], './ocr/columns/8k71pf94q/')
for f... | 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 | # https://github.com/jscancella/NYTribuneOCRExperiments/blob/master/findText_usingSums.py
import os | 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 |
# https://github.com/jscancella/NYTribuneOCRExperiments/blob/master/findText_usingSums.py
import os
import io
from pathlib import Path
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 ... |
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 |
# https://github.com/jscancella/NYTribuneOCRExperiments/blob/master/findText_usingSums.py
import os
import io
from pathlib import Path
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 ... | (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 | #![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, Print... | {
// 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 | #![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, Print... | (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, Print... | };
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 | #![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, Print... |
})
.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 | "use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.startRouter = void 0;
var _queryString = require("query-string");
var _history = require("history");
var _routerStore = require("./router-store");
var _sync = require("./sync");
var _utils = require("./utils");
var _mobx = req... |
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 | "use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.startRouter = void 0;
var _queryString = require("query-string");
var _history = require("history");
var _routerStore = require("./router-store");
var _sync = require("./sync");
var _utils = require("./utils");
var _mobx = req... | (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 | "use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.startRouter = void 0;
var _queryString = require("query-string");
var _history = require("history");
var _routerStore = require("./router-store");
var _sync = require("./sync");
var _utils = require("./utils");
var _mobx = req... | _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 | // tslint:disable:no-bitwise
import * as usb from '@balena.io/usb';
import * as _debug from 'debug';
import { EventEmitter } from 'events';
import * as _os from 'os';
import { Message } from './messages';
const platform = _os.platform();
const debug = _debug('node-beaglebone-usbboot');
const POLLING_INTERVAL_MS = 2000... | (
device: usb.Device,
outEndpoint: usb.OutEndpoint,
request: any,
response: any,
step: number,
): Promise<any> {
return new Promise((resolve, reject) => {
outEndpoint.transfer(response, (cb: any) => {
if (!cb) {
if (request === 'BOOTP') {
this.step(device, s... | transfer | identifier_name |
index.ts | // tslint:disable:no-bitwise
import * as usb from '@balena.io/usb';
import * as _debug from 'debug';
import { EventEmitter } from 'events';
import * as _os from 'os';
import { Message } from './messages';
const platform = _os.platform();
const debug = _debug('node-beaglebone-usbboot');
const POLLING_INTERVAL_MS = 2000... |
setTimeout(() => {
const usbBBbootDevice = this.get(device);
if (usbBBbootDevice !== undefined && usbBBbootDevice.step === UsbBBbootDevice.LAST_STEP) {
debug('device', devicePortId(device), 'did not reattached after', DEVICE_UNPLUG_TIMEOUT, 'ms.');
this.remove(device);
}
}, DE... | {
return;
} | conditional_block |
index.ts | // tslint:disable:no-bitwise
import * as usb from '@balena.io/usb';
import * as _debug from 'debug';
import { EventEmitter } from 'events';
import * as _os from 'os';
import { Message } from './messages';
const platform = _os.platform();
const debug = _debug('node-beaglebone-usbboot');
const POLLING_INTERVAL_MS = 2000... |
}
// tslint:disable-next-line
export class UsbBBbootDevice extends EventEmitter {
public static readonly LAST_STEP = 1124;
private STEP = 0;
constructor(public portId: string) {
super();
}
get progress() {
return Math.round((this.STEP / UsbBBbootDevice.LAST_STEP) * 100);
}
get step() {
return... | {
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 | // tslint:disable:no-bitwise
import * as usb from '@balena.io/usb';
import * as _debug from 'debug';
import { EventEmitter } from 'events';
import * as _os from 'os';
import { Message } from './messages';
const platform = _os.platform();
const debug = _debug('node-beaglebone-usbboot');
const POLLING_INTERVAL_MS = 2000... | } else {
if (platform === 'win32' || platform === 'darwin') {
rndisInEndpoint.stopPoll();
}
inEndpoint.stopPoll();
device.close();
}
}
break;
default:
debug('Reques... | if (serverConfig.tftp) {
if (serverConfig.tftp.blocks <= serverConfig.tftp.blocks) {
this.transfer(device, outEndpoint, request, tftpBuff, this.stepCounter++); | random_line_split |
sudoku.go | package sudoku
import (
"fmt"
"strconv"
"github.com/go-errors/errors"
)
//General solver error
type SolveError struct{
m_info string
}
func (e SolveError) Error() string {
return e.String()
}
func (e SolveError) String() string {
return e.m_info
}
//General solver interface
type Solver interface {
Solved() ... |
func (g *Grid) KnownEquals(puzzle [COL_LENGTH][ROW_LENGTH]int) bool{
thisPuzz := g.Puzzle()
for x,_ := range puzzle{
for y,_ := range puzzle[x]{
if puzzle[x][y] != thisPuzz[x][y]{
return false
}
}
}
return true
}
func (g Grid) String() string {
var str string
if len(g.m_cells) < COL_LENGTH{
... | {
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 | package sudoku
import (
"fmt"
"strconv"
"github.com/go-errors/errors"
)
//General solver error
type SolveError struct{
m_info string
}
func (e SolveError) Error() string {
return e.String()
}
func (e SolveError) String() string {
return e.m_info
}
//General solver interface
type Solver interface {
Solved() ... | (){
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 | package sudoku
import (
"fmt"
"strconv"
"github.com/go-errors/errors"
)
//General solver error
type SolveError struct{
m_info string
}
func (e SolveError) Error() string {
return e.String()
}
func (e SolveError) String() string {
return e.m_info
}
//General solver interface
type Solver interface {
Solved() ... |
if !solved{
return false,nil
}
}
return true,nil
}
func (g *Grid) squareExclusionReduce() (bool,error){
changed := false
/*for i,_ := range g.m_squares{
s := &g.m_squares[i]
pairs, err := s.AlignedCellOnlyPairs()
if err != nil{
return false,err
}
for _,p := range pairs{
}
}*/
... | {
fmt.Println("Error during Solved() check on grid: " + err.Error())
return false,err
} | conditional_block |
sudoku.go | package sudoku
import (
"fmt"
"strconv"
"github.com/go-errors/errors"
)
//General solver error
type SolveError struct{
m_info string
}
func (e SolveError) Error() string {
return e.String()
}
func (e SolveError) String() string {
return e.m_info
}
//General solver interface
type Solver interface {
Solved() ... | 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 | $package("phis.application.war.script")
$import("phis.script.TableForm"/*, "util.widgets.ModuleQueryField"*/)
phis.application.war.script.MedicalRecordsQueryForm = function(cfg) {
cfg.colCount = 5;
cfg.remoteUrl = 'MedicalDiagnosis';
cfg.remoteTpl = '<td width="12px" style="background-color:#deecfd">{numKey}.</td>... | }
if (box.id == "WCSJBOXN") {
var WCSJKSN = form.findField("WCSJKSN");
var WCSJJSN = form.findField("WCSJJSN");
if (flag) {
WCSJKSN.setValue();
WCSJKSN.enable();
WCSJJSN.setValue();
WCSJJSN.enable();
} else {
WCSJKSN.setValue();
WCSJKSN.disable();
WCS... | JLSJKSN.setValue();
JLSJKSN.disable();
JLSJJSN.setValue();
JLSJJSN.disable();
}
| conditional_block |
MedicalRecordsQueryForm.js | $package("phis.application.war.script")
$import("phis.script.TableForm"/*, "util.widgets.ModuleQueryField"*/)
phis.application.war.script.MedicalRecordsQueryForm = function(cfg) {
cfg.colCount = 5;
cfg.remoteUrl = 'MedicalDiagnosis';
cfg.remoteTpl = '<td width="12px" style="background-color:#deecfd">{numKey}.</td>... | }
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 | #!/usr/bin/env python
# -*- coding: Latin-1 -*-
# Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo
# Copyright (C) 2008-2017 German Aerospace Center (DLR) and others.
# This program and the accompanying materials
# are made available under the terms of the Eclipse Public License v2.0
# which acc... |
def readEdgeDump():
"""Get for each interval all edges with corresponding speed."""
edgeDumpDict = {}
begin = False
interval = 0
inputFile = open(path.FQedgeDump, 'r')
for line in inputFile:
words = line.split('"')
if not begin and words[0].find("<end>") != -1:
wor... | 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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.