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
tgsrv.go
package main import ( "bytes" "crypto/md5" "encoding/hex" "encoding/json" "io/ioutil" "log" "net/url" "strconv" "strings" "sort" "golang.org/x/net/html" "golang.org/x/net/publicsuffix" "github.com/azhinu/Telefeed/httputils" "github.com/azhinu/Telefeed/params" "github.com/azhinu/Telefeed/vkapi" "gith...
func subs2cmds(subs map[string]bool) map[string]string { var cmds = make(map[string]string) for k, _ := range subs { log.Println(k) if strings.Contains(k, params.PubNames) { cmd := "delete https://vk.com/" + strings.Replace(k, params.PubNames, "", -1) key := "delete" + k cmds[key] = cmd } if string...
{ var err error tlgrmtoken, err := ioutil.ReadFile(params.Telefeedfile) catch(err) tgtoken := strings.Replace(strings.Replace(string(tlgrmtoken), "\n", "", -1), "\r", "", -1) bot, err = tgbotapi.NewBotAPI(tgtoken) catch(err) bot.Debug = false log.Printf("Authorized on account %s", bot.Self.UserName) u := tgb...
identifier_body
tgsrv.go
package main import ( "bytes" "crypto/md5" "encoding/hex" "encoding/json" "io/ioutil" "log" "net/url" "strconv" "strings" "sort" "golang.org/x/net/html" "golang.org/x/net/publicsuffix" "github.com/azhinu/Telefeed/httputils" "github.com/azhinu/Telefeed/params" "github.com/azhinu/Telefeed/vkapi" "gith...
json.Unmarshal(body, &channels) for _, channel := range channels { cmds["channel_!_delete_!_"+channel.UserName] = "delete @" + channel.UserName cmds["channel_!_list_!_"+channel.UserName] = "list of urls of @" + channel.UserName } msg := tgbotapi.NewMessage(update.Message.Chat.ID, "Instruction...
random_line_split
tgsrv.go
package main import ( "bytes" "crypto/md5" "encoding/hex" "encoding/json" "io/ioutil" "log" "net/url" "strconv" "strings" "sort" "golang.org/x/net/html" "golang.org/x/net/publicsuffix" "github.com/azhinu/Telefeed/httputils" "github.com/azhinu/Telefeed/params" "github.com/azhinu/Telefeed/vkapi" "gith...
) string { hash := md5.Sum([]byte(strings.TrimSpace(text))) return hex.EncodeToString(hash[:]) } func getFeedLink(link string) (feedlink string) { var defHeaders = make(map[string]string) defHeaders["User-Agent"] = "script::recoilme:v1" defHeaders["Authorization"] = "Client-ID 4191ffe3736cfcb" b := httputils.Htt...
ext string
identifier_name
cfg.rs
use anyhow::{bail, Context, Result}; use expanduser::expanduser; use log::{debug, warn}; use std::collections::HashMap; use std::default::Default; use std::fmt::Display; use std::fs::{read_dir, read_to_string}; use std::path::PathBuf; use yaml_rust::{yaml::Hash, Yaml, YamlLoader}; use percent_encoding::{utf8_percent_e...
} Ok(()) } #[cfg(test)] mod tests { use crate::util; #[test] fn load_example_config() { util::test::init().unwrap(); let cfg = crate::cfg::Config::load("example-config/asfa") .unwrap() .unwrap(); log::debug!("Loaded: {:?}", cfg); assert_eq!(&...
bail! {"Prefix needs to be between 8 and 128 characters."};
random_line_split
cfg.rs
use anyhow::{bail, Context, Result}; use expanduser::expanduser; use log::{debug, warn}; use std::collections::HashMap; use std::default::Default; use std::fmt::Display; use std::fs::{read_dir, read_to_string}; use std::path::PathBuf; use yaml_rust::{yaml::Hash, Yaml, YamlLoader}; use percent_encoding::{utf8_percent_e...
} impl Config { pub fn load<T: AsRef<str> + Display>(dir: T) -> Result<Option<Config>> { let config_dir = match expanduser(dir.as_ref()) { Ok(p) => p, Err(e) => { bail!("Error when expanding path to config file: {}", e); } }; let global =...
{ Config { auth: Auth::default(), default_host: None, expire: None, hosts: HashMap::new(), prefix_length: 32, verify_via_hash: true, } }
identifier_body
cfg.rs
use anyhow::{bail, Context, Result}; use expanduser::expanduser; use log::{debug, warn}; use std::collections::HashMap; use std::default::Default; use std::fmt::Display; use std::fs::{read_dir, read_to_string}; use std::path::PathBuf; use yaml_rust::{yaml::Hash, Yaml, YamlLoader}; use percent_encoding::{utf8_percent_e...
(alias: String, input: &Yaml) -> Result<Host> { Self::from_yaml_with_config(alias, input, &Config::default()) } fn from_yaml_with_config(alias: String, input: &Yaml, config: &Config) -> Result<Host> { log::trace!("Reading host: {}", alias); if let Yaml::Hash(dict) = input { ...
from_yaml
identifier_name
error.rs
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 use core::{convert::TryInto, fmt, ptr::NonNull, task::Poll}; use errno::{errno, Errno}; use libc::c_char; use s2n_tls_sys::*; use std::{convert::TryFrom, ffi::CStr}; #[non_exhaustive] #[derive(Debug, PartialEq...
match self.0 { Context::InvalidInput | Context::MissingWaker => ErrorType::UsageError, Context::Application(_) => ErrorType::Application, Context::Code(code, _) => unsafe { ErrorType::from(s2n_error_get_type(code)) }, } } pub fn source(&self) -> ErrorSource {...
pub fn kind(&self) -> ErrorType {
random_line_split
error.rs
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 use core::{convert::TryInto, fmt, ptr::NonNull, task::Poll}; use errno::{errno, Errno}; use libc::c_char; use s2n_tls_sys::*; use std::{convert::TryFrom, ffi::CStr}; #[non_exhaustive] #[derive(Debug, PartialEq...
} enum Context { InvalidInput, MissingWaker, Code(s2n_status_code::Type, Errno), Application(Box<dyn std::error::Error + Send + Sync + 'static>), } pub struct Error(Context); pub trait Fallible { type Output; fn into_result(self) -> Result<Self::Output, Error>; } impl Fallible for s2n_stat...
{ match input as s2n_error_type::Type { s2n_error_type::OK => ErrorType::NoError, s2n_error_type::IO => ErrorType::IOError, s2n_error_type::CLOSED => ErrorType::ConnectionClosed, s2n_error_type::BLOCKED => ErrorType::Blocked, s2n_error_type::ALERT => E...
identifier_body
error.rs
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 use core::{convert::TryInto, fmt, ptr::NonNull, task::Poll}; use errno::{errno, Errno}; use libc::c_char; use s2n_tls_sys::*; use std::{convert::TryFrom, ffi::CStr}; #[non_exhaustive] #[derive(Debug, PartialEq...
(&self) -> bool { matches!(self.kind(), ErrorType::Blocked) } } #[cfg(feature = "quic")] impl Error { /// s2n-tls does not send specific errors. /// /// However, we can attempt to map local errors into the alerts /// that we would have sent if we sent alerts. /// /// This API is cur...
is_retryable
identifier_name
_utils.py
""" Various internal utilities for Pheres """ from __future__ import annotations import functools import inspect import json import re import types import typing from contextlib import contextmanager from types import FrameType from typing import ( Annotated, Any, Callable, Generic, Iterable, L...
class Subscriptable(Generic[U, V]): """ Decorator to make a subscriptable instance from a __getitem__ function Usage: @Subscriptable def my_subscriptable(key): return key assert my_subscriptable[8] == 8 """ __slots__ = ("_func",) def __init__(self, func: Ca...
""" Mixin class to make a class non-heritable and non-instanciable """ __slots__ = ("__weakref__",) def __init__(self): raise TypeError("Cannot instanciate virtual class") def __init_subclass__(cls, *args, **kwargs): if Virtual not in cls.__bases__: raise TypeError("Ca...
identifier_body
_utils.py
""" Various internal utilities for Pheres """ from __future__ import annotations import functools import inspect import json import re import types import typing from contextlib import contextmanager from types import FrameType from typing import ( Annotated, Any, Callable, Generic, Iterable, L...
: """ Descriptor for class properties """ __slots__ = ("fget", "fset") def __init__( self, fget: Union[classmethod, staticmethod], fset: Union[classmethod, staticmethod] = None, ): self.fget = fget self.fset = fset def __get__(self, obj: U, cls: Typ...
ClassPropertyDescriptor
identifier_name
_utils.py
""" Various internal utilities for Pheres """ from __future__ import annotations import functools import inspect import json import re import types import typing from contextlib import contextmanager from types import FrameType from typing import ( Annotated, Any, Callable, Generic, Iterable, L...
) def _sig_to_def(sig: inspect.Signature) -> str: return str(sig).split("->", 1)[0].strip()[1:-1] def _sig_to_call(sig: inspect.Signature) -> str: l = [] for p in sig.parameters.values(): if p.kind is inspect.Parameter.KEYWORD_ONLY: l.append(f"{p.name}={p.name}") else: ...
random_line_split
_utils.py
""" Various internal utilities for Pheres """ from __future__ import annotations import functools import inspect import json import re import types import typing from contextlib import contextmanager from types import FrameType from typing import ( Annotated, Any, Callable, Generic, Iterable, L...
elif unused == "post": try: index = next(i for i, l in enumerate(reversed(doc)) if l.strip()) doc = doc[: len(doc) - index] except StopIteration: doc = [] if doc: first_line = doc[0] index = len(first_line) - len(first_line.lstrip()) i...
try: index = next(i for i, l in enumerate(doc) if l.strip()) doc = doc[index:] except StopIteration: doc = []
conditional_block
monotone_stack.go
package copypasta /* 单调栈 Monotone Stack 【图解单调栈】两种方法,两张图秒懂 https://leetcode.cn/problems/next-greater-node-in-linked-list/solution/tu-jie-dan-diao-zhan-liang-chong-fang-fa-v9ab/ 举例:返回每个元素两侧严格大于它的元素位置(不存在则为 -1 或 n) 如何理解:把数组想象成一列山峰,站在 a[i] 的山顶仰望两侧的山峰,是看不到高山背后的矮山的,只能看到一座座更高的山峰 这就启发我们引入一个底大顶小的单调栈,入栈时不断比较栈顶元素直到找到一...
ans { ans = area } } } return } // 全 1 矩形个数 // LC1504 https://leetcode-cn.com/problems/count-submatrices-with-all-ones/ // 参考 https://leetcode.com/problems/count-submatrices-with-all-ones/discuss/720265/Java-Detailed-Explanation-From-O(MNM)-to-O(MN)-by-using-Stack func numSubmat(mat [][]int) (ans int) { m ...
for i := range right { right[i] = n } st := []int{-1} for i, v := range a { for len(st) > 1 && a[st[len(st)-1]] >= v { // 这里是 right 小于等于 right[st[len(st)-1]] = i st = st[:len(st)-1] } left[i] = st[len(st)-1] st = append(st, i) } } // EXTRA: 求所有长为 i 的子区间的最小值的最大值 // https://codeforces....
identifier_body
monotone_stack.go
package copypasta /* 单调栈 Monotone Stack 【图解单调栈】两种方法,两张图秒懂 https://leetcode.cn/problems/next-greater-node-in-linked-list/solution/tu-jie-dan-diao-zhan-liang-chong-fang-fa-v9ab/ 举例:返回每个元素两侧严格大于它的元素位置(不存在则为 -1 或 n) 如何理解:把数组想象成一列山峰,站在 a[i] 的山顶仰望两侧的山峰,是看不到高山背后的矮山的,只能看到一座座更高的山峰 这就启发我们引入一个底大顶小的单调栈,入栈时不断比较栈顶元素直到找到一...
} { // TIPS: 如果有一侧定义成小于等于,还可以一次遍历求出 left 和 right left := make([]int, n) right := make([]int, n) for i := range right { right[i] = n } st := []int{-1} for i, v := range a { for len(st) > 1 && a[st[len(st)-1]] >= v { // 这里是 right 小于等于 right[st[len(st)-1]] = i st = st[:len(st)-1] } lef...
tot := (i - left[i]) * (right[i] - i) _ = tot //tot := (sum[r] + mod - sum[l]) % mod
random_line_split
monotone_stack.go
package copypasta /* 单调栈 Monotone Stack 【图解单调栈】两种方法,两张图秒懂 https://leetcode.cn/problems/next-greater-node-in-linked-list/solution/tu-jie-dan-diao-zhan-liang-chong-fang-fa-v9ab/ 举例:返回每个元素两侧严格大于它的元素位置(不存在则为 -1 或 n) 如何理解:把数组想象成一列山峰,站在 a[i] 的山顶仰望两侧的山峰,是看不到高山背后的矮山的,只能看到一座座更高的山峰 这就启发我们引入一个底大顶小的单调栈,入栈时不断比较栈顶元素直到找到一...
identifier_name
monotone_stack.go
package copypasta /* 单调栈 Monotone Stack 【图解单调栈】两种方法,两张图秒懂 https://leetcode.cn/problems/next-greater-node-in-linked-list/solution/tu-jie-dan-diao-zhan-liang-chong-fang-fa-v9ab/ 举例:返回每个元素两侧严格大于它的元素位置(不存在则为 -1 或 n) 如何理解:把数组想象成一列山峰,站在 a[i] 的山顶仰望两侧的山峰,是看不到高山背后的矮山的,只能看到一座座更高的山峰 这就启发我们引入一个底大顶小的单调栈,入栈时不断比较栈顶元素直到找到一...
} } l, r := -1, 0 for i := n; i > 0; i-- { for len(st) > 0 && sum[i]-sum[st[len(st)-1]] > lowerSum { j := st[len(st)-1] st = st[:len(st)-1] if l < 0 || i-j < r-l { l, r = j, i } } } r-- // 闭区间 return l, r }
, int) { n := len(a) sum := make([]int, n+1) st := []int{0} for j, v := range a { j++ sum[j] = sum[j-1] + v if sum[j] < sum[st[len(st)-1]] { st = append(st, j)
conditional_block
constants.rs
use std::os::raw::{c_int, c_uint}; // Standard return values from Symisc public interfaces const SXRET_OK: c_int = 0; /* Not an error */ const SXERR_MEM: c_int = -1; /* Out of memory */ const SXERR_IO: c_int = -2; /* IO error */ const SXERR_EMPTY: c_int = -3; /* Empty field */ const SXERR_LOCKED: c_int = -4; /* L...
pub const UNQLITE_SYNC_NORMAL: c_int = 0x00002; pub const UNQLITE_SYNC_FULL: c_int = 0x00003; pub const UNQLITE_SYNC_DATAONLY: c_int = 0x00010; // File Locking Levels // // UnQLite uses one of these integer values as the second // argument to calls it makes to the xLock() and xUnlock() methods // of an [unqlite_io_meth...
random_line_split
segment.pb.go
// Code generated by protoc-gen-gogo. DO NOT EDIT. // source: segment.proto /* Package segment is a generated protocol buffer package. It is generated from these files: segment.proto It has these top-level messages: Segment */ package segment import proto "github.com/gogo/protobuf/proto" import fmt "fmt" import m...
// road classes are based on OpenStreetMap usage of the "highway" tag. // each value of the enumeration corresponds to one value of the tag, // except for ClassServiceOther, which is used for service and other roads. type Segment_RoadClass int32 const ( Segment_ClassMotorway Segment_RoadClass = 0 Segment_ClassT...
// This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto.GoGoProtoPackageIsVersion2 // please upgrade the proto pack...
random_line_split
segment.pb.go
// Code generated by protoc-gen-gogo. DO NOT EDIT. // source: segment.proto /* Package segment is a generated protocol buffer package. It is generated from these files: segment.proto It has these top-level messages: Segment */ package segment import proto "github.com/gogo/protobuf/proto" import fmt "fmt" import m...
func (*Segment) Descriptor() ([]byte, []int) { return fileDescriptorSegment, []int{0} } func (m *Segment) GetLrps() []*Segment_LocationReference { if m != nil { return m.Lrps } return nil } type Segment_LatLng struct { // lat & lng in EPSG:4326 multiplied by 10^7 and rounded to the nearest // integer. this gi...
{}
identifier_body
segment.pb.go
// Code generated by protoc-gen-gogo. DO NOT EDIT. // source: segment.proto /* Package segment is a generated protocol buffer package. It is generated from these files: segment.proto It has these top-level messages: Segment */ package segment import proto "github.com/gogo/protobuf/proto" import fmt "fmt" import m...
() ([]byte, []int) { return fileDescriptorSegment, []int{0} } func (m *Segment) GetLrps() []*Segment_LocationReference { if m != nil { return m.Lrps } return nil } type Segment_LatLng struct { // lat & lng in EPSG:4326 multiplied by 10^7 and rounded to the nearest // integer. this gives a precision of about 1....
Descriptor
identifier_name
segment.pb.go
// Code generated by protoc-gen-gogo. DO NOT EDIT. // source: segment.proto /* Package segment is a generated protocol buffer package. It is generated from these files: segment.proto It has these top-level messages: Segment */ package segment import proto "github.com/gogo/protobuf/proto" import fmt "fmt" import m...
return nil } type Segment_LatLng struct { // lat & lng in EPSG:4326 multiplied by 10^7 and rounded to the nearest // integer. this gives a precision of about 1.1cm (7/16ths of an inch) // worst case at the equator. Lat *int32 `protobuf:"fixed32,1,opt,name=lat" json:"lat,omitempty"` Lng ...
{ return m.Lrps }
conditional_block
table-form.component.ts
import {Component, OnInit, Input, Output, EventEmitter, TemplateRef, OnDestroy, ViewChild, Host} from '@angular/core'; // import { trigger, transition, animate,style} from '@angular/animations'; import {NzTabChangeEvent, NzTableComponent} from 'ng-zorro-antd'; import { UserinfoService } from '@service/userinfo-service....
conditional_block
table-form.component.ts
import {Component, OnInit, Input, Output, EventEmitter, TemplateRef, OnDestroy, ViewChild, Host} from '@angular/core'; // import { trigger, transition, animate,style} from '@angular/animations'; import {NzTabChangeEvent, NzTableComponent} from 'ng-zorro-antd'; import { UserinfoService } from '@service/userinfo-service....
refreshStatus(); } @Input() popData: any; @Input() popTableData: any = []; @Input() searchParamFiled: any; // pop弹框调接口要传的参数名 @Input() searchParamFiledNot: any; // pop弹框调接口要传的参数名不必传 {eName:ttrue},格式 @Input() tableTitle: string|TemplateRef<void>; // 表格标题 @Input() tableFooter: string|TemplateRef<void>; // 表格...
{ //用于初始化表格中存在已选数据,选中条数的变化,想触发必须更改成不同值 this.
identifier_body
table-form.component.ts
import {Component, OnInit, Input, Output, EventEmitter, TemplateRef, OnDestroy, ViewChild, Host} from '@angular/core'; // import { trigger, transition, animate,style} from '@angular/animations'; import {NzTabChangeEvent, NzTableComponent} from 'ng-zorro-antd'; import { UserinfoService } from '@service/userinfo-service....
]) ]) ]*/ }) export class TableFormComponent implements OnInit,OnDestroy { // tempfindSet: any = { "parameter": "companyName", "parameterSend": "companyId", "name": "发票抬头", "formId": "company_pop" }; // 数据弹框传入参数配置格式 @ViewChild('nzTable') nzTableComponent: NzTableComponent; private gloPageSub: Subscri...
style({opacity:0,height:0,transform:'translate(30px,0)'}), animate('0.3s ease-in',style({opacity:1,height:'auto',transform:'translate(0,0)',background:'#fffeee'})) ]), transition(':leave',[ animate('0.3s ease-out',style({opacity:0,height:0,transform:'translate(30px,0)'}))
random_line_split
table-form.component.ts
import {Component, OnInit, Input, Output, EventEmitter, TemplateRef, OnDestroy, ViewChild, Host} from '@angular/core'; // import { trigger, transition, animate,style} from '@angular/animations'; import {NzTabChangeEvent, NzTableComponent} from 'ng-zorro-antd'; import { UserinfoService } from '@service/userinfo-service....
} @Input() popData: any; @Input() popTableData: any = []; @Input() searchParamFiled: any; // pop弹框调接口要传的参数名 @Input() searchParamFiledNot: any; // pop弹框调接口要传的参数名不必传 {eName:ttrue},格式 @Input() tableTitle: string|TemplateRef<void>; // 表格标题 @Input() tableFooter: string|TemplateRef<void>; // 表格尾部 @Input() se...
Status();
identifier_name
itemUpdates.ts
/** * @file * Support for listening in on new items */ import { Store } from 'redux'; import * as _ from 'lodash'; import { LangType } from '../api/apiUrls'; import * as schemas from '../api/schemas'; import * as equipmentSchemas from '../api/schemas/equipment'; import * as gachaSchemas from '../api/schemas/gacha...
(item: PrizeItem) { if (item.type_name === 'BEAST') { checkKnownEnlir(item, enlir.magicites); } else if (item.type_name === 'EQUIPMENT') { checkKnownEnlir(item, enlir.relics, enlir.heroArtifacts); } else if (item.type_name === 'ABILITY') { checkKnownEnlir(item, enlir.abilities); } else if ( item...
checkItem
identifier_name
itemUpdates.ts
/** * @file * Support for listening in on new items */ import { Store } from 'redux'; import * as _ from 'lodash'; import { LangType } from '../api/apiUrls'; import * as schemas from '../api/schemas'; import * as equipmentSchemas from '../api/schemas/equipment'; import * as gachaSchemas from '../api/schemas/gacha...
function checkKnownDressRecord(item: PrizeItem) { if (dressRecordsById[item.id] == null) { const match = item.image_path.match(/(\d+)\/\d+\/\d+\.png/); const buddyId = match ? +match[1] : 0; showLocalDressRecord({ dress_record_id: item.id, name: item.name, buddy_id: buddyId }); } } function checkKnow...
{ if (_.every(enlirData, (i) => i[item.id] == null)) { showUnknownItem(item); } }
identifier_body
itemUpdates.ts
/** * @file * Support for listening in on new items */ import { Store } from 'redux'; import * as _ from 'lodash'; import { LangType } from '../api/apiUrls'; import * as schemas from '../api/schemas'; import * as equipmentSchemas from '../api/schemas/equipment'; import * as gachaSchemas from '../api/schemas/gacha...
for (const i of data.series_list) { if (i.opened_at > currentTime / 1000) { continue; } for (const { equipment } of i.banner_list) { if (equipment) { equipmentList.push(equipment); } } } return equipmentList; } function getGachaProbabilitiesEquipment(data: gachaSchemas.G...
showUpdateCommands(checkedLegendMateria, 'legendMateria', callback); } function getGachaShowEquipment(data: gachaSchemas.GachaShow, currentTime: number) { const equipmentList: equipmentSchemas.Equipment[] = [];
random_line_split
goog-varint.ts
// Copyright 2008 Google Inc. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the...
/** * Read an unsigned 32 bit varint. * * See https://github.com/protocolbuffers/protobuf/blob/8a71927d74a4ce34efe2d8769fda198f52d20d12/js/experimental/runtime/kernel/buffer_decoder.js#L220 */ export function varint32read(this: ReaderLike): number { let b = this.buf[this.pos++]; let result = b & 0x7F; ...
{ if (value >= 0) { // write value as varint 32 while (value > 0x7f) { bytes.push((value & 0x7f) | 0x80); value = value >>> 7; } bytes.push(value); } else { for (let i = 0; i < 9; i++) { bytes.push(value & 127 | 128); value ...
identifier_body
goog-varint.ts
// Copyright 2008 Google Inc. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the...
// constants for binary math const TWO_PWR_32_DBL = (1 << 16) * (1 << 16); /** * Parse decimal string of 64 bit integer value as two JS numbers. * * Returns tuple: * [0]: minus sign? * [1]: low bits * [2]: high bits * * Copyright 2008 Google Inc. */ export function int64fromString(dec: string): [boolean, num...
bytes.push((hi >>> 31) & 0x01); }
random_line_split
goog-varint.ts
// Copyright 2008 Google Inc. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the...
(lo: number, hi: number, bytes: number[]): void { for (let i = 0; i < 28; i = i + 7) { const shift = lo >>> i; const hasNext = !((shift >>> 7) == 0 && hi == 0); const byte = (hasNext ? shift | 0x80 : shift) & 0xFF; bytes.push(byte); if (!hasNext) { return; ...
varint64write
identifier_name
goog-varint.ts
// Copyright 2008 Google Inc. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the...
} bytes.push((hi >>> 31) & 0x01); } // constants for binary math const TWO_PWR_32_DBL = (1 << 16) * (1 << 16); /** * Parse decimal string of 64 bit integer value as two JS numbers. * * Returns tuple: * [0]: minus sign? * [1]: low bits * [2]: high bits * * Copyright 2008 Google Inc. */ export funct...
{ return; }
conditional_block
daemon.go
// Copyright (c) 2014-2020 Canonical Ltd // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License version 3 as // published by the Free Software Foundation. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY ...
else { logger.Noticef("%s %s %s %s %d", r.RemoteAddr, r.Method, r.URL, t, ww.s) } } }) } // Init sets up the Daemon's internal workings. // Don't call more than once. func (d *Daemon) Init() error { listenerMap := make(map[string]net.Listener) if listener, err := getListener(d.normalSocketPath, listenerM...
{ logger.Debugf("%s %s %s %s %d", r.RemoteAddr, r.Method, r.URL, t, ww.s) logger.Noticef("%s %s %s %d", r.Method, r.URL, t, ww.s) }
conditional_block
daemon.go
// Copyright (c) 2014-2020 Canonical Ltd // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License version 3 as // published by the Free Software Foundation. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY ...
var ( rebootNoticeWait = 3 * time.Second rebootWaitTimeout = 10 * time.Minute rebootRetryWaitTimeout = 5 * time.Minute rebootMaxTentatives = 3 ) var shutdownTimeout = 25 * time.Second // Stop shuts down the Daemon. func (d *Daemon) Stop(sigCh chan<- os.Signal) error { if d.rebootIsMissing { // ...
{ // die when asked to restart (systemd should get us back up!) etc switch t { case state.RestartDaemon: case state.RestartSystem: // try to schedule a fallback slow reboot already here // in case we get stuck shutting down if err := reboot(rebootWaitTimeout); err != nil { logger.Noticef("%s", err) } ...
identifier_body
daemon.go
// Copyright (c) 2014-2020 Canonical Ltd // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License version 3 as // published by the Free Software Foundation. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY ...
} } rebootAt = now.Add(rebootDelay) d.state.Set("daemon-system-restart-at", rebootAt) } return rebootDelay, nil } func (d *Daemon) doReboot(sigCh chan<- os.Signal, waitTimeout time.Duration) error { rebootDelay, err := d.rebootDelay() if err != nil { return err } // ask for shutdown and wait for it to...
random_line_split
daemon.go
// Copyright (c) 2014-2020 Canonical Ltd // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License version 3 as // published by the Free Software Foundation. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY ...
(err error) { d.degradedErr = err } func (d *Daemon) addRoutes() { d.router = mux.NewRouter() for _, c := range api { c.d = d if c.PathPrefix == "" { d.router.Handle(c.Path, c).Name(c.Path) } else { d.router.PathPrefix(c.PathPrefix).Handler(c).Name(c.PathPrefix) } } // also maybe add a /favicon.ic...
SetDegradedMode
identifier_name
base.py
"""The base command class. All implemented commands should extend this class.""" from ..AgentPool import AgentPool import json import os.path from subprocess import call import paramiko from paramiko import SSHClient from paramiko.agent import AgentRequestHandler import socket import subprocess, os class Base(object)...
(self, cmd): """ Execute a command on the client in a bash shell. """ self.log.debug("Executing command in shell: " + str(cmd)) dcos_config = os.path.expanduser('~/.dcos/dcos.toml') os.environ['PATH'] = ':'.join([os.getenv('PATH'), '/src/bin']) os.environ['DCOS_CONFIG'] = dcos_config os.makedir...
shell_execute
identifier_name
base.py
"""The base command class. All implemented commands should extend this class.""" from ..AgentPool import AgentPool import json import os.path from subprocess import call import paramiko from paramiko import SSHClient from paramiko.agent import AgentRequestHandler import socket import subprocess, os class Base(object)...
elif name == "publickey": self.log.debug("Checking if public SSH key exists: " + public_filepath) if not os.path.isfile(public_filepath): self._generateSSHKey(private_filepath, public_filepath) with open(public_filepath, 'r') as sshfile: value = sshfile.read().replac...
self.log.debug("Checking if private SSH key exists: " + private_filepath) if not os.path.isfile(private_filepath): self.log.debug("Key does not exist") self._generateSSHKey(private_filepath, public_filepath) with open(private_filepath, 'r') as sshfile: self.log.debug("Key ...
conditional_block
base.py
"""The base command class. All implemented commands should extend this class.""" from ..AgentPool import AgentPool import json import os.path from subprocess import call import paramiko from paramiko import SSHClient from paramiko.agent import AgentRequestHandler import socket import subprocess, os class Base(object)...
def shell_execute(self, cmd): """ Execute a command on the client in a bash shell. """ self.log.debug("Executing command in shell: " + str(cmd)) dcos_config = os.path.expanduser('~/.dcos/dcos.toml') os.environ['PATH'] = ':'.join([os.getenv('PATH'), '/src/bin']) os.environ['DCOS_CONFIG'] = dcos_co...
random_line_split
base.py
"""The base command class. All implemented commands should extend this class.""" from ..AgentPool import AgentPool import json import os.path from subprocess import call import paramiko from paramiko import SSHClient from paramiko.agent import AgentRequestHandler import socket import subprocess, os class Base(object)...
def run(self): raise NotImplementedError("You must implement the run() method in your commands") def help(self): raise NotImplementedError("You must implement the help method. In most cases you will simply do 'print(__doc__)'") def getAgentIPs(self): # return a list of Agent IPs in this cluster ...
self.log.debug("Creating Resource Group") command = "azure group create " + self.config.get('Group', 'name') + " " + self.config.get('Group', 'region') os.system(command)
identifier_body
fetch.rs
use std::io::{self, Write}; use std::cmp::min; use std::collections::{HashMap, HashSet, VecDeque}; use std::net::SocketAddr; use std::str::from_utf8; use std::sync::{Arc, Mutex}; use std::time::{Instant, Duration}; use std::u64; use abstract_ns::Address; use futures::{Sink, Async, Stream}; use futures::future::{Future...
#[derive(Debug)] struct State { offset: u64, eof: u32, last_line: Vec<u8>, last_request: Instant, } #[derive(Debug)] struct Cursor { url: Arc<Url>, state: Option<State>, } struct Requests { cursors: VecDeque<Arc<Mutex<Cursor>>>, timeout: Timeout, } #[derive(Debug)] pub struct Request ...
#[cfg(feature="tls_rustls")] use webpki_roots;
random_line_split
fetch.rs
use std::io::{self, Write}; use std::cmp::min; use std::collections::{HashMap, HashSet, VecDeque}; use std::net::SocketAddr; use std::str::from_utf8; use std::sync::{Arc, Mutex}; use std::time::{Instant, Duration}; use std::u64; use abstract_ns::Address; use futures::{Sink, Async, Stream}; use futures::future::{Future...
fn request(cur: &Arc<Mutex<Cursor>>) -> Result<Request, Instant> { let intr = cur.lock().unwrap(); match intr.state { None => return Ok(Request { cursor: cur.clone(), range: None, }), Some(ref state) => { if state.eof == 0 { return Ok...
{ use std::io::BufReader; use std::fs::File; if urls_by_host.len() == 0 { return Box::new(ok(())); } let resolver = resolver.clone(); let tls = Arc::new({ let mut cfg = ClientConfig::new(); let read_root = File::open("/etc/ssl/certs/ca-certificates.crt") .map...
identifier_body
fetch.rs
use std::io::{self, Write}; use std::cmp::min; use std::collections::{HashMap, HashSet, VecDeque}; use std::net::SocketAddr; use std::str::from_utf8; use std::sync::{Arc, Mutex}; use std::time::{Instant, Duration}; use std::u64; use abstract_ns::Address; use futures::{Sink, Async, Stream}; use futures::future::{Future...
(resolver: &Router, urls_by_host: HashMap<String, Vec<Arc<Url>>>) -> Box<Future<Item=(), Error=()>> { let resolver = resolver.clone(); let cfg = Config::new() .keep_alive_timeout(Duration::new(25, 0)) .done(); return Box::new( join_all(urls_by_host.into_iter().map(move |(host, li...
http
identifier_name
dyn_cor_rel.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Jul 3 15:56:13 2020 @author: dean """ #functions to generate stimuli given parameter set import os, sys from tqdm import tqdm import math import numpy as np import matplotlib.pyplot as plt import torch import xarray as xr from itertools import produc...
u1, u2 = ranks.index.values[ind] inds.append([u1,u2]) plt.scatter(df['dyn'][u1,u2], df['cor'][u1,u2]**2, s=10, c='r');plt.semilogx(); #%% j=0 plt.figure(figsize=(3,8)) for ind in inds: u1, u2 = ind u1r = (da_sig.isel(unit=u1, sf=sf_ind).squeeze()**2).sum('phase')**0.5 u2r = (da_sig.isel(unit=...
random_line_split
dyn_cor_rel.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Jul 3 15:56:13 2020 @author: dean """ #functions to generate stimuli given parameter set import os, sys from tqdm import tqdm import math import numpy as np import matplotlib.pyplot as plt import torch import xarray as xr from itertools import produc...
if by2 is None: by2 = by if rg2 is None: rg2 = rg s1 = sine_chrom(nx, ny, x_0, y_0, sf, ori, phase, lum, by, rg, bg=0) s2 = sine_chrom(nx, ny, x_0, y_0, sf2, ori+rel_ori, phase2, lum2, by2, rg2) s = s1+s2 if make_window: w = window(radius, x_0, y_0,...
lum2 = lum
conditional_block
dyn_cor_rel.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Jul 3 15:56:13 2020 @author: dean """ #functions to generate stimuli given parameter set import os, sys from tqdm import tqdm import math import numpy as np import matplotlib.pyplot as plt import torch import xarray as xr from itertools import produc...
(radius, x_0, y_0, nx, ny): x_coords = np.arange(0, nx, dtype=np.float128) - x_0 y_coords = np.arange(0, ny, dtype=np.float128) - y_0 xx, yy = np.meshgrid(x_coords, y_coords) d = (xx**2 + yy**2)**0.5 w = np.zeros((int(nx), int(ny))) w[d<=radius] = 1 return w def cos_window(radius, x_0, y_0,...
window
identifier_name
dyn_cor_rel.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Jul 3 15:56:13 2020 @author: dean """ #functions to generate stimuli given parameter set import os, sys from tqdm import tqdm import math import numpy as np import matplotlib.pyplot as plt import torch import xarray as xr from itertools import produc...
def window(radius, x_0, y_0, nx, ny): x_coords = np.arange(0, nx, dtype=np.float128) - x_0 y_coords = np.arange(0, ny, dtype=np.float128) - y_0 xx, yy = np.meshgrid(x_coords, y_coords) d = (xx**2 + yy**2)**0.5 w = np.zeros((int(nx), int(ny))) w[d<=radius] = 1 return w def cos_window(radiu...
x_coords = np.arange(0, nx, dtype=np.float64) - x_0 y_coords = np.arange(0, ny, dtype=np.float64) - y_0 xx, yy = np.meshgrid(x_coords, y_coords) mu_0, nu_0 = pol2cart(sf, np.deg2rad(ori + 90)) s = np.sin(2*np.pi*(mu_0*xx + nu_0*yy) + np.deg2rad(phase + 90)) s = s + bg return s
identifier_body
Run_all_models_modified.py
from __future__ import print_function import os import sys import logging import numpy as np import matplotlib.pyplot as plt from time import time from optparse import OptionParser from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.feature_extraction.text import HashingVectorizer from sklearn.fe...
#============================================================================ # Benchmark classifiers #============================================================================ def benchmark(clf): print('_' * 80) print("Starting training: ") print(clf) init_time = time() clf.fit(X_train, y_t...
return s if len(s) <= 80 else s[:77] + "..."
identifier_body
Run_all_models_modified.py
from __future__ import print_function import os import sys import logging import numpy as np import matplotlib.pyplot as plt from time import time from optparse import OptionParser from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.feature_extraction.text import HashingVectorizer from sklearn.fe...
if names_of_features: names_of_features = np.asarray(names_of_features) def trim(s): return s if len(s) <= 80 else s[:77] + "..." #============================================================================ # Benchmark classifiers #==========================================================================...
names_of_features = vectorizer.get_feature_names()
conditional_block
Run_all_models_modified.py
from __future__ import print_function import os import sys import logging import numpy as np import matplotlib.pyplot as plt from time import time from optparse import OptionParser from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.feature_extraction.text import HashingVectorizer from sklearn.fe...
(object): def __init__(self, **kwargs): self.__dict__.update(kwargs) # output logs to stdout logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)s %(message)s') # show how to call hashing function op = OptionParser() op.add_option("--use_hashing", acti...
Bunch
identifier_name
Run_all_models_modified.py
from __future__ import print_function import os import sys import logging import numpy as np import matplotlib.pyplot as plt from time import time from optparse import OptionParser from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.feature_selection import SelectFromModel from sklearn.feature_selection import SelectKBest from sklearn.linear_model import RidgeClassifier from sklearn.linear_model import SGDClassifier from sklearn.linear_model import Perceptron from sklearn.linear_model import PassiveAggressiveClassifier from sklearn.na...
from sklearn.feature_extraction.text import HashingVectorizer
random_line_split
pod_helper.go
package flytek8s import ( "context" "fmt" "strings" "time" "github.com/flyteorg/flyteplugins/go/tasks/pluginmachinery/core/template" "github.com/flyteorg/flyteplugins/go/tasks/pluginmachinery/utils" "github.com/flyteorg/flytestdlib/logger" v1 "k8s.io/api/core/v1" v12 "k8s.io/apimachinery/pkg/apis/meta/v1" ...
message += fmt.Sprintf("\r\n[%v] terminated with exit code (%v). Reason [%v]. Message: \n%v.", c.Name, containerState.Terminated.ExitCode, containerState.Terminated.Reason, containerState.Terminated.Message) } } } return code, message } func GetLastTransitionOccurredAt(pod *v1.Pod) v12.T...
} else {
random_line_split
pod_helper.go
package flytek8s import ( "context" "fmt" "strings" "time" "github.com/flyteorg/flyteplugins/go/tasks/pluginmachinery/core/template" "github.com/flyteorg/flyteplugins/go/tasks/pluginmachinery/utils" "github.com/flyteorg/flytestdlib/logger" v1 "k8s.io/api/core/v1" v12 "k8s.io/apimachinery/pkg/apis/meta/v1" ...
} return pluginsCore.PhaseInfoSuccess(&info), nil } func DeterminePrimaryContainerPhase(primaryContainerName string, statuses []v1.ContainerStatus, info *pluginsCore.TaskInfo) pluginsCore.PhaseInfo { for _, s := range statuses { if s.Name == primaryContainerName { if s.State.Waiting != nil || s.State.Running ...
{ return pluginsCore.PhaseInfoRetryableFailure("OOMKilled", "Pod reported success despite being OOMKilled", &info), nil }
conditional_block
pod_helper.go
package flytek8s import ( "context" "fmt" "strings" "time" "github.com/flyteorg/flyteplugins/go/tasks/pluginmachinery/core/template" "github.com/flyteorg/flyteplugins/go/tasks/pluginmachinery/utils" "github.com/flyteorg/flytestdlib/logger" v1 "k8s.io/api/core/v1" v12 "k8s.io/apimachinery/pkg/apis/meta/v1" ...
(status v1.PodStatus, info pluginsCore.TaskInfo) (pluginsCore.PhaseInfo, error) { for _, status := range append( append(status.InitContainerStatuses, status.ContainerStatuses...), status.EphemeralContainerStatuses...) { if status.State.Terminated != nil && strings.Contains(status.State.Terminated.Reason, OOMKilled...
DemystifySuccess
identifier_name
pod_helper.go
package flytek8s import ( "context" "fmt" "strings" "time" "github.com/flyteorg/flyteplugins/go/tasks/pluginmachinery/core/template" "github.com/flyteorg/flyteplugins/go/tasks/pluginmachinery/utils" "github.com/flyteorg/flytestdlib/logger" v1 "k8s.io/api/core/v1" v12 "k8s.io/apimachinery/pkg/apis/meta/v1" ...
func GetLastTransitionOccurredAt(pod *v1.Pod) v12.Time { var lastTransitionTime v12.Time containerStatuses := append(pod.Status.ContainerStatuses, pod.Status.InitContainerStatuses...) for _, containerStatus := range containerStatuses { if r := containerStatus.LastTerminationState.Running; r != nil { if r.Star...
{ code = "UnknownError" message = "Pod failed. No message received from kubernetes." if len(status.Reason) > 0 { code = status.Reason } if len(status.Message) > 0 { message = status.Message } for _, c := range append( append(status.InitContainerStatuses, status.ContainerStatuses...), status.EphemeralCont...
identifier_body
searchByName.js
(function () { 'use strict'; angular .module('app.searchByName') .controller('SearchByName', SearchByName); SearchByName.$inject = ['$scope', '$ionicConfig', '$ionicNavBarDelegate', 'SuggestFactory', '$state', '$stateParams', 'CONFIG', 'JamHelperFactory', 'AnalyticsHelper', 'LoaderFactory', 'Orientation...
nction setSearchParamsObject(params) { // Suche über Was / Wen if (params.searchType == "what") { vm.searchParamsObject.was = params.selectedItem; vm.searchParamsObject.was_i = params.inputItem; vm.searchParamsObject.was_sel = (typeof params.was_sel !== 'undefined' && params.was_sel) ? params.was...
NavBarDelegate.showBar(true); // zeige Wo-Input vm.showWhereInputField = true; vm.showWhereSuggest = false; // zeige Was-Input vm.showWhatInputField = true; vm.showWhatSuggest = false; // verstecke Abbrechen Buttons vm.showWhatCancel = false; vm.showWhereCancel = false...
conditional_block
searchByName.js
(function () { 'use strict'; angular .module('app.searchByName') .controller('SearchByName', SearchByName); SearchByName.$inject = ['$scope', '$ionicConfig', '$ionicNavBarDelegate', 'SuggestFactory', '$state', '$stateParams', 'CONFIG', 'JamHelperFactory', 'AnalyticsHelper', 'LoaderFactory', 'Orientation...
if(params.searchType == 'what') { vm.searchInput.what = params.selectedItem; } if(params.searchType == 'where') { vm.searchInput.where = params.selectedItem; } // zeige alles controlInputFieldPosition('all'); } function getSuggestData(type) { /* */ // hole Daten fü...
/* */ setSearchParamsObject(params);
random_line_split
searchByName.js
(function () { 'use strict'; angular .module('app.searchByName') .controller('SearchByName', SearchByName); SearchByName.$inject = ['$scope', '$ionicConfig', '$ionicNavBarDelegate', 'SuggestFactory', '$state', '$stateParams', 'CONFIG', 'JamHelperFactory', 'AnalyticsHelper', 'LoaderFactory', 'Orientation...
$timeout(function () { var suggestScrollArea = $('ion-nav-view[name="menuContent"] ion-view[nav-view="active"] #suggest-scroll-area'); // Only on android tablets if (vm.isTablet && vm.deviceOs == 'Android') { var tmpHeight = $('ion-view[nav-view="active"] .jam-suggest-box-tablet').height(...
llHeight() {
identifier_name
searchByName.js
(function () { 'use strict'; angular .module('app.searchByName') .controller('SearchByName', SearchByName); SearchByName.$inject = ['$scope', '$ionicConfig', '$ionicNavBarDelegate', 'SuggestFactory', '$state', '$stateParams', 'CONFIG', 'JamHelperFactory', 'AnalyticsHelper', 'LoaderFactory', 'Orientation...
); $scope.$on('$ionicView.enter', function() { activateViewToForeground(); }); function activate() { // Aufruf aus dem Fachgebiete-Verzeichnis if($stateParams.what) { var params = { searchType: 'what', selectedItem: $stateParams.what, gruppe_fach_param: $stateParams.grupp...
('searchResultList', vm.searchParamsObject); } activate(
identifier_body
time.rs
//!Constants and structures from time classes //! //! This includes include/uapi/linux/time.h, //include/linux/time.h, and /include/linux/time64.h ///A structure that contains the number of seconds and nanoseconds since an epoch. /// ///If in doubt, assume we're talking about the UNIX epoch. #[repr(C)] #[derive(Debug...
///The amount of time left until expiration (Need to verify) pub it_value: timeval } ///A system-wide clock that measures time from the "real world" /// ///This clock **is** affected by discontinuous jumps in system time, NTP, and user changes pub const CLOCK_REALTIME: ::clockid_t = 0; ///A clock that me...
///The period of time this timer should run for (Need to verify) pub it_interval: timeval,
random_line_split
time.rs
//!Constants and structures from time classes //! //! This includes include/uapi/linux/time.h, //include/linux/time.h, and /include/linux/time64.h ///A structure that contains the number of seconds and nanoseconds since an epoch. /// ///If in doubt, assume we're talking about the UNIX epoch. #[repr(C)] #[derive(Debug...
{ ///The number of seconds contained in this timespec pub tv_sec: ::time_t, ///The number of nanoseconds contained in this timespec pub tv_nsec: ::c_long } impl timespec { ///Creates a new timespec with both values defaulting to zero pub fn new() -> timespec { timespec { tv_sec: ...
timespec
identifier_name
format_wav_scp.py
#!/usr/bin/env python3 import argparse import logging from io import BytesIO from pathlib import Path from typing import Optional, Tuple import humanfriendly import kaldiio import numpy as np import resampy import soundfile from tqdm import tqdm from typeguard import check_argument_types from espnet2.fileio.read_text...
fark = open(Path(args.outdir) / f"data_{args.name}.ark", "wb") fscp_out = out_wavscp.open("w") writer = None else: writer = SoundScpWriter( args.outdir, out_wavscp, format=args.audio_format, multi_columns=args.multi_columns_output, ...
if args.audio_format.endswith("ark"):
random_line_split
format_wav_scp.py
#!/usr/bin/env python3 import argparse import logging from io import BytesIO from pathlib import Path from typing import Optional, Tuple import humanfriendly import kaldiio import numpy as np import resampy import soundfile from tqdm import tqdm from typeguard import check_argument_types from espnet2.fileio.read_text...
else: array = array[int(st * rate) :] yield utt, (array, rate), None, None def main(): logfmt = "%(asctime)s (%(module)s:%(lineno)d) %(levelname)s: %(message)s" logging.basicConfig(level=logging.INFO, format=logfmt) logging.info(get_commandline_args()) parser...
array = array[int(st * rate) : int(et * rate)]
conditional_block
format_wav_scp.py
#!/usr/bin/env python3 import argparse import logging from io import BytesIO from pathlib import Path from typing import Optional, Tuple import humanfriendly import kaldiio import numpy as np import resampy import soundfile from tqdm import tqdm from typeguard import check_argument_types from espnet2.fileio.read_text...
def str2int_tuple(integers: str) -> Optional[Tuple[int, ...]]: """ >>> str2int_tuple('3,4,5') (3, 4, 5) """ assert check_argument_types() if integers.strip() in ("none", "None", "NONE", "null", "Null", "NULL"): return None return tuple(map(int, integers.strip().split(","))) de...
if value in ("none", "None", "NONE"): return None return humanfriendly.parse_size(value)
identifier_body
format_wav_scp.py
#!/usr/bin/env python3 import argparse import logging from io import BytesIO from pathlib import Path from typing import Optional, Tuple import humanfriendly import kaldiio import numpy as np import resampy import soundfile from tqdm import tqdm from typeguard import check_argument_types from espnet2.fileio.read_text...
(x, d=utt2ref_channels_dict) -> Tuple[int, ...]: chs_str = d[x] return tuple(map(int, chs_str.split())) else: utt2ref_channels = None if args.audio_format.endswith("ark") and args.multi_columns_output: raise RuntimeError("Multi columns wav.scp is not supported for ark t...
utt2ref_channels
identifier_name
cv4ag.py
#!usr/bin/env python """ Top Layer for the Computer Vision 4 Agriculture (cv4ag) framework Lukas Arnold WB-DIME Jan 30 2017 The framework consists of four parts 1. Parsing input data (parse) 2. Downloading satellite images (get_satellite) 3. Overlaying data with satellite images (overlay) 4. Training (train) 5. Appl...
elif selectedModule == 'ml': applyml.apply(\ outputFolder, inputFile, mode=mode, ignorebackground=b, epsg=epsg, compare=compare, top=top) #key=key) elif selectedModule == 'clear': clean.clear(inputFile) else: print "error - no valid option" cmdParser.print_help()
train.train(outputFolder=outputFolder, inputFile=inputFile, net=net, top=top, key=key, mode=mode, xpixel=xpixel, ypixel=ypixel, ignorebackground=b, batchsize=batchsize, maxiter=maxiter, datatype=datatype, stepsize=stepsize, initweights=initweights, createTest=test\ )
conditional_block
cv4ag.py
#!usr/bin/env python """ Top Layer for the Computer Vision 4 Agriculture (cv4ag) framework Lukas Arnold WB-DIME Jan 30 2017 The framework consists of four parts 1. Parsing input data (parse) 2. Downloading satellite images (get_satellite) 3. Overlaying data with satellite images (overlay) 4. Training (train) 5. Appl...
(argparse.ArgumentParser): # override error message to show usage def error(self, message): sys.stderr.write('error: %s\n' % message) self.print_help() sys.exit(2) cmdParser = myParse(\ description='Machine Learning Framework for Agricultural Data.', add_help=True) cmdParser.add_argument('module', me...
myParse
identifier_name
cv4ag.py
#!usr/bin/env python """ Top Layer for the Computer Vision 4 Agriculture (cv4ag) framework Lukas Arnold WB-DIME Jan 30 2017 The framework consists of four parts 1. Parsing input data (parse) 2. Downloading satellite images (get_satellite) 3. Overlaying data with satellite images (overlay) 4. Training (train) 5. Appl...
cmdParser.set_defaults(b=False) randomParser = cmdParser.add_mutually_exclusive_group(required=False) randomParser.add_argument('--random', dest='randomImages', action='store_true',help='Use random images within GIS boundary box.') randomParser.add_argument('--no-random', dest='randomImages', action='store_false',h...
cmdParser.set_defaults(test=False) backgroundParser = cmdParser.add_mutually_exclusive_group(required=False) backgroundParser.add_argument('--background', dest='b', action='store_false',help='Classify background for training (default)') backgroundParser.add_argument('--no-background', dest='b', action='store_true',...
random_line_split
cv4ag.py
#!usr/bin/env python """ Top Layer for the Computer Vision 4 Agriculture (cv4ag) framework Lukas Arnold WB-DIME Jan 30 2017 The framework consists of four parts 1. Parsing input data (parse) 2. Downloading satellite images (get_satellite) 3. Overlaying data with satellite images (overlay) 4. Training (train) 5. Appl...
cmdParser = myParse(\ description='Machine Learning Framework for Agricultural Data.', add_help=True) cmdParser.add_argument('module', metavar='OPTION', type=str,default=False, help='The modules to be loaded. OPTION: \n\ all - all modules (except clear).\n\ parse - input file parser.\n\ satellite ...
def error(self, message): sys.stderr.write('error: %s\n' % message) self.print_help() sys.exit(2)
identifier_body
movie_review_NaiveBayes.py
#!/usr/bin/env python # coding: utf-8 # In[ ]: import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import string import re from nltk.stem.porter import PorterStemmer import random from sklearn.model_selection import train_test_split import os from random import shuffle # In...
already_counted.append(word) total_words # In[ ]: # Removes words that are not inluded in at least 0.15% of the reviews removed_words = 0 for j in range(len(train_set)): words = train_set[j][0] i = 0 while i < len(words): word = words[i] word_removed = False...
if word not in already_counted: neg_word_counter[word] += 1
conditional_block
movie_review_NaiveBayes.py
#!/usr/bin/env python # coding: utf-8 # In[ ]: import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import string import re from nltk.stem.porter import PorterStemmer import random from sklearn.model_selection import train_test_split import os from random import shuffle # In...
ord): return (probability_appearing[word][0]*p_pos)/((probability_appearing[word][0]*p_pos + probability_appearing[word][1]*p_neg)) def p_is_negative_given_word(word): return (probability_appearing[word][1]*p_neg)/((probability_appearing[word][1]*p_neg + probability_appearing[word][0]*p_pos)) p_is_positive_gi...
is_positive_given_word(w
identifier_name
movie_review_NaiveBayes.py
#!/usr/bin/env python # coding: utf-8 # In[ ]: import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import string import re from nltk.stem.porter import PorterStemmer import random from sklearn.model_selection import train_test_split import os from random import shuffle # In...
most_used_words_pos = sort_dict(pos_word_counter, 25) most_used_words_neg = sort_dict(neg_word_counter, 25) most_used_words_pos # In[ ]: # Need these 4 probabilities # 1) Probability that a word appears in positive reviews # 2) Probability that a word appears in negative reviews # 3) Overall probab...
most_common_words = sorted(dicti.items(), key = lambda kv: kv[1]) most_common_words.reverse() most_common_words = most_common_words[:end] # Lager dict på formen {word: count, ...} # Vil ha dict fremfor liste med tupler, pga. senere søk return dict(most_common_words)
identifier_body
movie_review_NaiveBayes.py
#!/usr/bin/env python # coding: utf-8 # In[ ]: import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import string import re from nltk.stem.porter import PorterStemmer import random from sklearn.model_selection import train_test_split import os from random import shuffle # In...
word_removed = True removed_words += 1 if not word_removed: i += 1 j += 1 removed_words # In[ ]: def sort_dict(dicti, end): # Sorterer etter value i dict, gir liste med tupler most_common_words = sorted(dicti.items(), key = lambda kv: kv[1]) most_c...
random_line_split
tls-server.rs
// SPDX-FileCopyrightText: Copyright (c) 2017-2023 slowtec GmbH <post@slowtec.de> // SPDX-License-Identifier: MIT OR Apache-2.0 // load_certs() and particially load_keys() functions were copied from an example of the tokio tls library, available at: // https://github.com/tokio-rs/tls/blob/master/tokio-rustls/examples/...
(socket_addr: SocketAddr) -> anyhow::Result<()> { println!("Starting up server on {socket_addr}"); let listener = TcpListener::bind(socket_addr).await?; let server = Server::new(listener); let on_connected = |stream, _socket_addr| async move { let cert_path = Path::new("./pki/server.pem"); ...
server_context
identifier_name
tls-server.rs
// SPDX-FileCopyrightText: Copyright (c) 2017-2023 slowtec GmbH <post@slowtec.de> // SPDX-License-Identifier: MIT OR Apache-2.0 // load_certs() and particially load_keys() functions were copied from an example of the tokio tls library, available at: // https://github.com/tokio-rs/tls/blob/master/tokio-rustls/examples/...
Ok(values) => future::ready(Ok(Response::ReadInputRegisters(values))), Err(err) => future::ready(Err(err)), } } Request::ReadHoldingRegisters(addr, cnt) => { match register_read(&self.holding_registers.lock().unwrap(), addr,...
fn call(&self, req: Self::Request) -> Self::Future { match req { Request::ReadInputRegisters(addr, cnt) => { match register_read(&self.input_registers.lock().unwrap(), addr, cnt) {
random_line_split
tls-server.rs
// SPDX-FileCopyrightText: Copyright (c) 2017-2023 slowtec GmbH <post@slowtec.de> // SPDX-License-Identifier: MIT OR Apache-2.0 // load_certs() and particially load_keys() functions were copied from an example of the tokio tls library, available at: // https://github.com/tokio-rs/tls/blob/master/tokio-rustls/examples/...
} impl ExampleService { fn new() -> Self { // Insert some test data as register values. let mut input_registers = HashMap::new(); input_registers.insert(0, 1234); input_registers.insert(1, 5678); let mut holding_registers = HashMap::new(); holding_registers.insert(0...
{ match req { Request::ReadInputRegisters(addr, cnt) => { match register_read(&self.input_registers.lock().unwrap(), addr, cnt) { Ok(values) => future::ready(Ok(Response::ReadInputRegisters(values))), Err(err) => future::ready(Err(err)), ...
identifier_body
program.py
import discord import os import zlib import io import re import aiohttp from util import fuzzy from discord.ext import commands from pistonapi import PistonAPI piston = PistonAPI() class SphinxObjectFileReader: # Inspired by Sphinx's InventoryFileReader BUFSIZE = 16 * 1024 def __init__(self, buffer): ...
async def _run_code(self, *, lang: str, code: str): res = await self.session.post( "https://emkc.org/api/v1/piston/execute", json={"language": lang, "source": code}) return await res.json() @commands.command() async def run(self, ctx: commands.Context, *, codeblock: ...
random_line_split
program.py
import discord import os import zlib import io import re import aiohttp from util import fuzzy from discord.ext import commands from pistonapi import PistonAPI piston = PistonAPI() class SphinxObjectFileReader: # Inspired by Sphinx's InventoryFileReader BUFSIZE = 16 * 1024 def __init__(self, buffer): ...
ctx, *, obj: str = None): """Gives you a documentation link for a Python entity (Japanese).""" await self.do_rtfm(ctx, 'python-jp', obj) async def _member_stats(self, ctx, member, total_uses): e = discord.Embed(title='RTFM Stats') e.set_author(name=str(member), icon_url=member.avat...
ython_jp(self,
identifier_name
program.py
import discord import os import zlib import io import re import aiohttp from util import fuzzy from discord.ext import commands from pistonapi import PistonAPI piston = PistonAPI() class SphinxObjectFileReader: # Inspired by Sphinx's InventoryFileReader BUFSIZE = 16 * 1024 def __init__(self, buffer): ...
identifier_body
program.py
import discord import os import zlib import io import re import aiohttp from util import fuzzy from discord.ext import commands from pistonapi import PistonAPI piston = PistonAPI() class SphinxObjectFileReader: # Inspired by Sphinx's InventoryFileReader BUFSIZE = 16 * 1024 def __init__(self, buffer): ...
# This code mostly comes from the Sphinx repository. entry_regex = re.compile(r'(?x)(.+?)\s+(\S*:\S*)\s+(-?\d+)\s+(\S+)\s+(.*)') for line in stream.read_compressed_lines(): match = entry_regex.match(line.rstrip()) if not match: continue name...
raise RuntimeError('Invalid objects.inv file, not z-lib compatible.')
conditional_block
packer.rs
// Copyright 2020 The Grin Developers // // 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 agree...
/// Get Sender info. It is needed to send the response back pub fn get_recipient(&self) -> Option<DalekPublicKey> { self.recipient.clone() } /// Convert this slate back to the resulting slate. Since the slate pack contain only the change set, /// to recover the data it is required original slate to merge with...
{ self.sender.clone() }
identifier_body
packer.rs
// Copyright 2020 The Grin Developers // // 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 agree...
(&self) -> SlatePurpose { self.content.clone() } /// Get Sender info. It is needed to send the response back pub fn get_sender(&self) -> Option<DalekPublicKey> { self.sender.clone() } /// Get Sender info. It is needed to send the response back pub fn get_recipient(&self) -> Option<DalekPublicKey> { self.r...
get_content
identifier_name
packer.rs
// Copyright 2020 The Grin Developers // // 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 agree...
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, ]; let sk = SecretKey::from_slice(&bytes_32).unwrap(); let secp = Secp25...
random_line_split
json.go
// Copyright 2020 The LUCI Authors. // // 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...
() *gerritpb.ChangeMessageInfo { if cmi == nil { return nil } return &gerritpb.ChangeMessageInfo{ Id: cmi.ID, Author: cmi.Author.ToProto(), RealAuthor: cmi.RealAuthor.ToProto(), Date: timestamppb.New(cmi.Date.Time), Message: cmi.Message, Tag: cmi.Tag, } } type requirement ...
ToProto
identifier_name
json.go
// Copyright 2020 The LUCI Authors. // // 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...
type requirement struct { Status string `json:"status"` FallbackText string `json:"fallback_text"` Type string `json:"type"` } func (r *requirement) ToProto() (*gerritpb.Requirement, error) { stringVal := "REQUIREMENT_STATUS_" + r.Status numVal, found := gerritpb.Requirement_Status_value[stringVal...
{ if cmi == nil { return nil } return &gerritpb.ChangeMessageInfo{ Id: cmi.ID, Author: cmi.Author.ToProto(), RealAuthor: cmi.RealAuthor.ToProto(), Date: timestamppb.New(cmi.Date.Time), Message: cmi.Message, Tag: cmi.Tag, } }
identifier_body
json.go
// Copyright 2020 The LUCI Authors. // // 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...
if ri.Files != nil { ret.Files = make(map[string]*gerritpb.FileInfo, len(ri.Files)) for i, fi := range ri.Files { ret.Files[i] = fi.ToProto() } } if ri.Commit != nil { ret.Commit = ri.Commit.ToProto() } return ret } // https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#git-perso...
if v, ok := gerritpb.RevisionInfo_Kind_value[ri.Kind]; ok { ret.Kind = gerritpb.RevisionInfo_Kind(v) }
random_line_split
json.go
// Copyright 2020 The LUCI Authors. // // 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...
result.Reviewers = reviewers return result, nil } type projectInfo struct { ID string `json:"id,omitempty"` Parent string `json:"parent,omitempty"` Description string `json:"description,omitempty"` State string `json:"state...
{ reviewerDetails, err := x.ToProto() if err != nil { return nil, err } reviewers[i] = reviewerDetails }
conditional_block
list_conflict_files_test.go
package conflicts import ( "bytes" "context" "io" "os" "path/filepath" "testing" "github.com/stretchr/testify/require" "gitlab.com/gitlab-org/gitaly/v14/internal/git" "gitlab.com/gitlab-org/gitaly/v14/internal/git/gittest" "gitlab.com/gitlab-org/gitaly/v14/internal/git/localrepo" "gitlab.com/gitlab-org/git...
ctx := testhelper.Context(t) _, repo, _, client := SetupConflictsService(ctx, t, true, nil) testCases := []struct { desc string ourCommitOid string theirCommitOid string }{ { desc: "conflict side missing", ourCommitOid: "eb227b3e214624708c474bdab7bde7afc17cefcc", theirComm...
random_line_split
list_conflict_files_test.go
package conflicts import ( "bytes" "context" "io" "os" "path/filepath" "testing" "github.com/stretchr/testify/require" "gitlab.com/gitlab-org/gitaly/v14/internal/git" "gitlab.com/gitlab-org/gitaly/v14/internal/git/gittest" "gitlab.com/gitlab-org/gitaly/v14/internal/git/localrepo" "gitlab.com/gitlab-org/git...
(t *testing.T) { ctx := testhelper.Context(t) _, repo, _, client := SetupConflictsService(ctx, t, false, nil) ourCommitOid := "1a35b5a77cf6af7edf6703f88e82f6aff613666f" theirCommitOid := "8309e68585b28d61eb85b7e2834849dda6bf1733" conflictContent1 := `<<<<<<< encoding/codagé Content is not important, file name i...
TestSuccessfulListConflictFilesRequest
identifier_name
list_conflict_files_test.go
package conflicts import ( "bytes" "context" "io" "os" "path/filepath" "testing" "github.com/stretchr/testify/require" "gitlab.com/gitlab-org/gitaly/v14/internal/git" "gitlab.com/gitlab-org/gitaly/v14/internal/git/gittest" "gitlab.com/gitlab-org/gitaly/v14/internal/git/localrepo" "gitlab.com/gitlab-org/git...
/ Append leftover file files = append(files, currentFile) return files } func drainListConflictFilesResponse(c gitalypb.ConflictsService_ListConflictFilesClient) error { var err error for err == nil { _, err = c.Recv() } return err }
r, err := c.Recv() if err == io.EOF { break } require.NoError(t, err) for _, file := range r.GetFiles() { // If there's a header this is the beginning of a new file if header := file.GetHeader(); header != nil { if currentFile != nil { files = append(files, currentFile) } currentFile...
conditional_block
list_conflict_files_test.go
package conflicts import ( "bytes" "context" "io" "os" "path/filepath" "testing" "github.com/stretchr/testify/require" "gitlab.com/gitlab-org/gitaly/v14/internal/git" "gitlab.com/gitlab-org/gitaly/v14/internal/git/gittest" "gitlab.com/gitlab-org/gitaly/v14/internal/git/localrepo" "gitlab.com/gitlab-org/git...
nc getConflictFiles(t *testing.T, c gitalypb.ConflictsService_ListConflictFilesClient) []*conflictFile { t.Helper() var files []*conflictFile var currentFile *conflictFile for { r, err := c.Recv() if err == io.EOF { break } require.NoError(t, err) for _, file := range r.GetFiles() { // If there's...
tx := testhelper.Context(t) _, repo, _, client := SetupConflictsService(ctx, t, true, nil) ourCommitOid := "0b4bc9a49b562e85de7cc9e834518ea6828729b9" theirCommitOid := "bb5206fee213d983da88c47f9cf4cc6caf9c66dc" testCases := []struct { desc string request *gitalypb.ListConflictFilesRequest code codes....
identifier_body
reconcile.go
// // Copyright (c) 2018 Intel Corporation // // 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 a...
func (subs subresources) any(predicate func(s *subresource) bool) bool { return len(subs.filter(predicate)) > 0 } func (subs subresources) all(predicate func(s *subresource) bool) bool { return len(subs.filter(predicate)) == len(subs) } func (r *Reconciler) planAction(controllerName string, subs subresources) (*a...
{ var result subresources for _, sub := range subs { if predicate(sub) { result = append(result, sub) } } return result }
identifier_body
reconcile.go
// // Copyright (c) 2018 Intel Corporation // // 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 a...
(predicate func(s *subresource) bool) bool { return len(subs.filter(predicate)) == len(subs) } func (r *Reconciler) planAction(controllerName string, subs subresources) (*action, crd.CustomResource, error) { // If the controller name is empty, these are not our subresources; // do nothing. if controllerName == "" ...
all
identifier_name
reconcile.go
// // Copyright (c) 2018 Intel Corporation // // 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 a...
subs, ok := result[cr.Name()] if !ok { glog.Warningf("[reconcile] no sub-resources found for cr %v", cr.Name()) } // Find non-existing subresources based on the expected subresource clients. existingSubs := map[string]struct{}{} for _, sub := range subs { existingSubs[sub.client.Plural()] = struct{...
{ glog.Warningf("[reconcile] failed to assert item %v to type CustomResource", item) continue }
conditional_block
reconcile.go
// // Copyright (c) 2018 Intel Corporation // // 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 a...
// To fix the problem, we could do a List from the CR client and then iterate // over those names instead of keys from the intermediate result map we built // based on the subresources. func (r *Reconciler) groupSubresourcesByCustomResource() subresourceMap { result := subresourceMap{} // Get the list of crs. crLis...
// custom resource, result will not have the controller name as one of its // keys. //
random_line_split
GPR_stan2.py
# -*- coding: utf-8 -*- """ Created on Thu Sep 29 09:35:12 2016 @author: nigul """ import sys sys.path.append('../') import matplotlib as mpl mpl.use('Agg') mpl.rcParams['figure.figsize'] = (20, 30) import pickle import numpy as np import pylab as plt from filelock import FileLock import mw_utils import GPR_QP impor...
#import pandas as pd #num_groups = 1 #group_no = 0 #if len(sys.argv) > 1: # num_groups = int(sys.argv[1]) #if len(sys.argv) > 2: # group_no = int(sys.argv[2]) star = sys.argv[1] peak_no = int(sys.argv[2]) peak_no_str = "" if peak_no > 0: peak_no_str = str(peak_no) + "/" num_iters = 50 num_chains = 4...
from scipy.stats import gaussian_kde from sklearn.cluster import KMeans
random_line_split
GPR_stan2.py
# -*- coding: utf-8 -*- """ Created on Thu Sep 29 09:35:12 2016 @author: nigul """ import sys sys.path.append('../') import matplotlib as mpl mpl.use('Agg') mpl.rcParams['figure.figsize'] = (20, 30) import pickle import numpy as np import pylab as plt from filelock import FileLock import mw_utils import GPR_QP impor...
for downsample_iter in np.arange(0, downsample_iters): if downsample_iters > 1: downsample_iter_str = '_' + str(downsample_iter) else: downsample_iter_str = '' if down_sample_factor >= 2: #indices = np.random.choice(len(t), len(t)/down_sample_factor, replace=False, p=None) ...
down_sample_factor = max(1, n_orig / 500) downsample_iters = down_sample_factor
conditional_block
index.js
import Head from 'next/head'; import Portfolio from '../components/Portfolio'; import Link from 'next/link'; export default function
() { return ( <div> <Head> <title>PublicTrades</title> <link rel="icon" href="/favicon.ico" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.6.0/gsap.min.js"></script> </Head> <main> <> {/* This example requires Tailwind CSS v2.0+ */} <div className=...
Home
identifier_name
index.js
import Head from 'next/head'; import Portfolio from '../components/Portfolio'; import Link from 'next/link'; export default function Home()
{ return ( <div> <Head> <title>PublicTrades</title> <link rel="icon" href="/favicon.ico" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.6.0/gsap.min.js"></script> </Head> <main> <> {/* This example requires Tailwind CSS v2.0+ */} <div className="re...
identifier_body