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
train_nn.py
from __future__ import absolute_import import os import json import torch import argparse import torchvision import numpy as np import torch.nn as nn from DataLoader import CDATA from main_model_nn import MemN2NDialog from torch.autograd import Variable as Var from data_utils import load_candidates, load_dialog_task, v...
(object): def __init__(self, data_dir, model_dir, task_id, isInteractive=True, OOV=False, memory_size=50, random_state=None, batch_size=32, learning_rate=0.001, epsilon=1e-8, max_grad_norm=40.0, evaluation_interval=10, hops=3, epochs=200, embedding_size=20, save_model=10, ...
chatBot
identifier_name
train_nn.py
from __future__ import absolute_import import os import json import torch import argparse import torchvision import numpy as np import torch.nn as nn from DataLoader import CDATA from main_model_nn import MemN2NDialog from torch.autograd import Variable as Var from data_utils import load_candidates, load_dialog_task, v...
parser.add_argument('--epochs', default=200, type=int, help='Number of epochs to train for') parser.add_argument('--embedding_size', default=20, type=int, help='Embedding size for embedding matrices') parser.add_argument('--memory_size', default=50, type=int, help='Maximum size of me...
help='Evaluate and print results every x epochs') parser.add_argument('--batch_size', default=32, type=int, help='Batch size for training') parser.add_argument('--hops', default=3, type=int, help='Number of hops in the Memory Network')
random_line_split
train_nn.py
from __future__ import absolute_import import os import json import torch import argparse import torchvision import numpy as np import torch.nn as nn from DataLoader import CDATA from main_model_nn import MemN2NDialog from torch.autograd import Variable as Var from data_utils import load_candidates, load_dialog_task, v...
if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument('--learning_rate', default=0.001, type=float, help='Learning rate for Optimizer') parser.add_argument('--epsilon', default=1e-8, type=float, help='Epsilon value for Adam Optim...
model_dir = "task" + str(params['task_id']) + "_" + params['model_dir'] if not os.path.exists(model_dir): os.makedirs(model_dir) chatbot = chatBot(data_dir=params['data_dir'], model_dir=model_dir, task_id=params['task_id'], isInteractive=params['interactive'], OOV=params['OOV'], memory_size=params['memo...
identifier_body
01_calculate_MMR_from_draws.py
import pandas as pd import os import sys import fnmatch import numpy as np import concurrent.futures as cf try: from db_tools import dbapis, query_tools except: sys.path.append(str(os.getcwd()).rstrip('/mmr')) from db_tools import dbapis, query_tools cause_id, year_id, process_v, out_dir = sys.argv[1:5] ye...
draws = pd.concat(draw_list) draws.reset_index(inplace=True) draws = draws[draws.age_group_id.isin(ages)] draws['location_id'] = draws['location_id'].astype('int') draws['age_group_id'] = draws['age_group_id'].astype('int') draws['sex_id'] = draws['sex_id'].astype('int') draws['year_id'] = draws['year_id'].astype('in...
draw_list.append(df)
conditional_block
01_calculate_MMR_from_draws.py
import pandas as pd import os import sys import fnmatch import numpy as np import concurrent.futures as cf try: from db_tools import dbapis, query_tools except: sys.path.append(str(os.getcwd()).rstrip('/mmr')) from db_tools import dbapis, query_tools cause_id, year_id, process_v, out_dir = sys.argv[1:5] ye...
draw_list = [] with cf.ProcessPoolExecutor(max_workers=14) as e: for df in e.map(read_file, files): draw_list.append(df) draws = pd.concat(draw_list) draws.reset_index(inplace=True) draws = draws[draws.age_group_id.isin(ages)] draws['location_id'] = draws['location_id'].astype('int') draws['age_group_id'...
return pd.read_hdf(f, 'data', where=[("'cause_id'==%d & 'measure_id'==1" "& 'metric_id'==1 & 'sex_id'==2" "& 'rei_id'==0") % cause_id])
identifier_body
01_calculate_MMR_from_draws.py
import pandas as pd import os import sys import fnmatch import numpy as np import concurrent.futures as cf try: from db_tools import dbapis, query_tools except: sys.path.append(str(os.getcwd()).rstrip('/mmr')) from db_tools import dbapis, query_tools cause_id, year_id, process_v, out_dir = sys.argv[1:5] ye...
(df): df['measure_id'] = 25 df['metric_id'] = 3 df['cause_id'] = cause_id return df # get best dalynator version query = ('SELECT ' 'distinct(val) AS daly_id ' 'FROM ' 'gbd.gbd_process_version_metadata gpvm ' 'JOIN ' 'gbd.gbd_process_version USING (gbd_proc...
add_cols
identifier_name
01_calculate_MMR_from_draws.py
import pandas as pd import os import sys import fnmatch import numpy as np import concurrent.futures as cf try: from db_tools import dbapis, query_tools except: sys.path.append(str(os.getcwd()).rstrip('/mmr')) from db_tools import dbapis, query_tools cause_id, year_id, process_v, out_dir = sys.argv[1:5] ye...
summary.index.rename(['location_id', 'year_id', 'age_group_id', 'sex_id'], inplace=True) summary.reset_index(inplace=True) final_draws = draws[['births']] final_draws.reset_index(inplace=True) final_draws = final_draws.merge(summary, how='inner', on=index_cols) # calculate mean, upper, lower mmr f...
columns={'2.5%': 'lower', '97.5%': 'upper'}, inplace=True)
random_line_split
prime_field.rs
// False positive: attribute has a use #[allow(clippy::useless_attribute)] // False positive: Importing preludes is allowed #[allow(clippy::wildcard_imports)] use std::{fmt, prelude::v1::*}; use crate::{Root, SquareRoot, UInt as FieldUInt}; use std::{ hash::{Hash, Hasher}, marker::PhantomData, ops::Shr, };...
pub struct PrimeField<P: Parameters> { // TODO: un-pub. They are pub so FieldElement can have const-fn constructors. pub uint: P::UInt, pub _parameters: PhantomData<P>, } /// Required constant parameters for the prime field // TODO: Fix naming #[allow(clippy::module_name_repetitions)] // UInt can no...
// Derive fails for Clone, PartialEq, Eq, Hash
random_line_split
prime_field.rs
// False positive: attribute has a use #[allow(clippy::useless_attribute)] // False positive: Importing preludes is allowed #[allow(clippy::wildcard_imports)] use std::{fmt, prelude::v1::*}; use crate::{Root, SquareRoot, UInt as FieldUInt}; use std::{ hash::{Hash, Hasher}, marker::PhantomData, ops::Shr, };...
(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "field_element!(\"{:?}\")", self.to_uint()) } } impl<P: Parameters> Zero for PrimeField<P> { #[inline(always)] fn zero() -> Self { Self::from_montgomery(P::UInt::zero()) } #[inline(always)] fn is_zero(&self) -> bool...
fmt
identifier_name
prime_field.rs
// False positive: attribute has a use #[allow(clippy::useless_attribute)] // False positive: Importing preludes is allowed #[allow(clippy::wildcard_imports)] use std::{fmt, prelude::v1::*}; use crate::{Root, SquareRoot, UInt as FieldUInt}; use std::{ hash::{Hash, Hasher}, marker::PhantomData, ops::Shr, };...
else { None } } else { Some(Self::one()) } } } // TODO: Generalize over order type // Lint has a false positive here #[allow(single_use_lifetimes)] impl<U, P> Root<&U> for PrimeField<P> where U: FieldUInt + Binary + for<'a> DivRem<&'a U, Quotient = U, Re...
{ Some(Self::generator().pow(&q)) }
conditional_block
prime_field.rs
// False positive: attribute has a use #[allow(clippy::useless_attribute)] // False positive: Importing preludes is allowed #[allow(clippy::wildcard_imports)] use std::{fmt, prelude::v1::*}; use crate::{Root, SquareRoot, UInt as FieldUInt}; use std::{ hash::{Hash, Hasher}, marker::PhantomData, ops::Shr, };...
#[test] fn root_of_unity_definition() { let powers_of_two = (0..193).map(|n| U256::ONE << n); for n in powers_of_two { let root_of_unity = FieldElement::root(&n).unwrap(); assert_eq!(root_of_unity.pow(&n), FieldElement::one()); } } }
{ let powers_of_two = (0..193).map(|n| U256::ONE << n); let roots_of_unity: Vec<_> = powers_of_two .map(|n| FieldElement::root(&n).unwrap()) .collect(); for (smaller_root, larger_root) in roots_of_unity[1..].iter().zip(roots_of_unity.as_slice()) { ass...
identifier_body
mod.rs
// See https://github.com/apache/parquet-format/blob/master/Encodings.md#run-length-encoding--bit-packing-hybrid-rle--3 mod bitmap; mod decoder; mod encoder; pub use bitmap::{encode_bool as bitpacked_encode, BitmapIter}; pub use decoder::Decoder; pub use encoder::{encode_bool, encode_u32}; use super::bitpacking; #[de...
() { let data = vec![3]; let num_bits = 0; let decoder = HybridRleDecoder::new(&data, num_bits as u32, 2); let result = decoder.collect::<Vec<_>>(); assert_eq!(result, &[0, 0]); } }
zero_bit_width
identifier_name
mod.rs
// See https://github.com/apache/parquet-format/blob/master/Encodings.md#run-length-encoding--bit-packing-hybrid-rle--3 mod bitmap; mod decoder; mod encoder; pub use bitmap::{encode_bool as bitpacked_encode, BitmapIter}; pub use decoder::Decoder; pub use encoder::{encode_bool, encode_u32}; use super::bitpacking; #[de...
} enum State<'a> { None, Bitpacked(bitpacking::Decoder<'a>), Rle(std::iter::Take<std::iter::Repeat<u32>>), } // Decoder of Hybrid-RLE encoded values. pub struct HybridRleDecoder<'a> { decoder: Decoder<'a>, state: State<'a>, remaining: usize, } #[inline] fn read_next<'a, 'b>(decoder: &'b mut D...
Bitpacked(&'a [u8]), /// A RLE-encoded slice. The first attribute corresponds to the slice (that can be interpreted) /// the second attribute corresponds to the number of repetitions. Rle(&'a [u8], usize),
random_line_split
mod.rs
// See https://github.com/apache/parquet-format/blob/master/Encodings.md#run-length-encoding--bit-packing-hybrid-rle--3 mod bitmap; mod decoder; mod encoder; pub use bitmap::{encode_bool as bitpacked_encode, BitmapIter}; pub use decoder::Decoder; pub use encoder::{encode_bool, encode_u32}; use super::bitpacking; #[de...
#[test] fn small() { let data = vec![3, 2]; let num_bits = 3; let decoder = HybridRleDecoder::new(&data, num_bits as u32, 1); let result = decoder.collect::<Vec<_>>(); assert_eq!(result, &[2]); } #[test] fn zero_bit_width() { let data = vec![3];...
{ // data encoded from pyarrow representing (0..1000) let data = vec![ 127, 0, 4, 32, 192, 0, 4, 20, 96, 192, 1, 8, 36, 160, 192, 2, 12, 52, 224, 192, 3, 16, 68, 32, 193, 4, 20, 84, 96, 193, 5, 24, 100, 160, 193, 6, 28, 116, 224, 193, 7, 32, 132, 32, 194, 8, 36, 148, ...
identifier_body
mod.rs
// See https://github.com/apache/parquet-format/blob/master/Encodings.md#run-length-encoding--bit-packing-hybrid-rle--3 mod bitmap; mod decoder; mod encoder; pub use bitmap::{encode_bool as bitpacked_encode, BitmapIter}; pub use decoder::Decoder; pub use encoder::{encode_bool, encode_u32}; use super::bitpacking; #[de...
else { self.state = read_next(&mut self.decoder, self.remaining); self.next() } } fn size_hint(&self) -> (usize, Option<usize>) { (self.remaining, Some(self.remaining)) } } impl<'a> ExactSizeIterator for HybridRleDecoder<'a> {} #[cfg(test)] mod tests { use sup...
{ self.remaining -= 1; Some(result) }
conditional_block
framebuffer_server.rs
// Copyright 2022 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. //! This file contains for creating and serving a `Flatland` view using a `Framebuffer`. //! //! A lot of the code in this file is temporary to enable deve...
/// Spawns a thread to serve a `ViewProvider` in `outgoing_dir`. /// /// SAFETY: This function `.expect`'s a lot, because it isn't meant to be used in the long time and /// most of the failures would be unexpected and unrecoverable. pub fn spawn_view_provider( server: Arc<FramebufferServer>, outgoing_dir: fid...
{ let (collection_sender, collection_receiver) = channel(); let (allocation_sender, allocation_receiver) = channel(); // This thread is spawned to deal with the mix of asynchronous and synchronous proxies. // In particular, we want to keep Framebuffer creation synchronous, while still making use of ...
identifier_body
framebuffer_server.rs
// Copyright 2022 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. //! This file contains for creating and serving a `Flatland` view using a `Framebuffer`. //! //! A lot of the code in this file is temporary to enable deve...
{ /// The Flatland proxy associated with this server. flatland: fuicomposition::FlatlandSynchronousProxy, /// The buffer collection that is registered with Flatland. collection: fsysmem::BufferCollectionInfo2, } impl FramebufferServer { /// Returns a `FramebufferServer` that has created a scene a...
FramebufferServer
identifier_name
framebuffer_server.rs
// Copyright 2022 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. //! This file contains for creating and serving a `Flatland` view using a `Framebuffer`. //! //! A lot of the code in this file is temporary to enable deve...
.present(fuicomposition::PresentArgs { requested_presentation_time: Some( present_parameters.requested_presentation_time.into_nanos(), ), acquire_fences: None, release_fences: None, ...
random_line_split
base.py
import copy import time import random from twisted.python import log, failure from twisted.internet import defer, error, protocol, reactor from twisted.protocols import basic, policies from pn.util import url from pn.core import stream as stream_mod try: from collections import deque except ImportError: class dequ...
def _selfMaintain(self): self.maintID = None pools = self.hostsPool.values() for pool in pools: pool.maintain() self.maintID = reactor.callLater(self.maintTime, self._selfMaintain) def doRequest(self, request): if hasattr(request, 'addr'): d = self.getProtocol(getattr(request, 'addr')) else: ...
size = len(self.hostsPool) if size == 0: return None if size > 15: tries = 15 else: tries = size pools = self.hostsPool.values() idx = random.randint(1, size) for t in xrange(tries): pool = pools[idx % size] idx += 1 p = pool.get(wait) if p is not None: return p ...
identifier_body
base.py
import copy import time import random from twisted.python import log, failure from twisted.internet import defer, error, protocol, reactor from twisted.protocols import basic, policies from pn.util import url from pn.core import stream as stream_mod try: from collections import deque except ImportError: class dequ...
def getPool(self, addr): if self.hostsPool.has_key(addr): return self.hostsPool[addr] pool = self.hostsPool[addr] = ClientProtocolPool(addr, self) return pool def protocolConnectionLost(self, protocol, reason): addr = protocol.addr pool = self.getPool(addr) pool.remove(protocol) def connection...
self.hostsDead.remove(addr)
conditional_block
base.py
import copy import time import random from twisted.python import log, failure from twisted.internet import defer, error, protocol, reactor from twisted.protocols import basic, policies from pn.util import url from pn.core import stream as stream_mod try: from collections import deque except ImportError: class dequ...
def lineReceived(self, line): if not self.chanRequest: # server sending random unrequested data. self.transport.loseConnection() return self.setTimeout(None) try: self.chanRequest.lineReceived(line) self.setTimeout(self.timeOut) except Exception, err: self.chanRequest.abortWithError(failur...
self.setTimeout(self.timeOut) self.transport.writeSequence(sequence)
random_line_split
base.py
import copy import time import random from twisted.python import log, failure from twisted.internet import defer, error, protocol, reactor from twisted.protocols import basic, policies from pn.util import url from pn.core import stream as stream_mod try: from collections import deque except ImportError: class dequ...
(self, line): if not self.chanRequest: # server sending random unrequested data. self.transport.loseConnection() return self.setTimeout(None) try: self.chanRequest.lineReceived(line) self.setTimeout(self.timeOut) except Exception, err: self.chanRequest.abortWithError(failure.Failure(err)) ...
lineReceived
identifier_name
temperature_driver.py
# The MIT License (MIT) # # Copyright (c) 2017 ladyada for Adafruit Industries # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the ri...
if var1: pressure = 1048576.0 - adc pressure = ((pressure - var2 / 4096.0) * 6250.0) / var1 var1 = self._pressure_calib[8] * pressure * pressure / 2147483648.0 var2 = pressure * self._pressure_calib[7] / 32768.0 pressure = pressure + (var1 + var...
return 0
conditional_block
temperature_driver.py
# The MIT License (MIT) # # Copyright (c) 2017 ladyada for Adafruit Industries # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the ri...
class Adafruit_BME280_SPI(Adafruit_BME280): """Driver for BME280 connected over SPI""" def __init__(self, spi, cs, baudrate=100000): import adafruit_bus_device.spi_device as spi_device self._spi = spi_device.SPIDevice(spi, cs, baudrate=baudrate) super().__init__() def _rea...
"""Driver for BME280 connected over I2C""" def __init__(self, i2c, address=_BME280_ADDRESS): import adafruit_bus_device.i2c_device as i2c_device self._i2c = i2c_device.I2CDevice(i2c, address) super().__init__() def _read_register(self, register, length): with self._i2c as...
identifier_body
temperature_driver.py
# The MIT License (MIT) # # Copyright (c) 2017 ladyada for Adafruit Industries # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the ri...
(self, register, value): register &= 0x7F # Write, bit 7 low. with self._spi as spi: spi.write(bytes([register, value & 0xFF])) #pylint: disable=no-member
_write_register_byte
identifier_name
temperature_driver.py
# The MIT License (MIT) # # Copyright (c) 2017 ladyada for Adafruit Industries # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the ri...
def _read_coefficients(self): """Read & save the calibration coefficients""" coeff = self._read_register(_BME280_REGISTER_DIG_T1, 24) coeff = list(struct.unpack('<HhhHhhhhhhhh', bytes(coeff))) coeff = [float(i) for i in coeff] self._temp_calib = coeff[:3] self._...
"""The altitude based on current ``pressure`` versus the sea level pressure (``sea_level_pressure``) - which you must enter ahead of time)""" pressure = self.pressure # in Si units for hPascal return 44330 * (1.0 - math.pow(pressure / self.sea_level_pressure, 0.1903))
random_line_split
main.go
package main import ( "fmt" "net/http" "os" "regexp" "strings" "sync" "time" "golang.org/x/oauth2" "github.com/Sirupsen/logrus" "github.com/dustin/go-humanize" "github.com/gin-gonic/gin" "github.com/google/go-github/github" "github.com/parnurzeal/gorequest" "github.com/renstrom/fuzzysearch/fuzzy" "git...
name := strings.ToLower(inputName) name = regexp.MustCompile(`[^a-z0-9-]`).ReplaceAllString(name, "-") name = regexp.MustCompile(`--+`).ReplaceAllString(name, "-") name = strings.Trim(name, "-") return name } func main() { router := gin.Default() router.StaticFile("/", "./static/index.html") router.Static("/s...
func ImageCodeName(inputName string) string {
random_line_split
main.go
package main import ( "fmt" "net/http" "os" "regexp" "strings" "sync" "time" "golang.org/x/oauth2" "github.com/Sirupsen/logrus" "github.com/dustin/go-humanize" "github.com/gin-gonic/gin" "github.com/google/go-github/github" "github.com/parnurzeal/gorequest" "github.com/renstrom/fuzzysearch/fuzzy" "git...
}
{ logrus.Infof("Fetching manifest...") manifest, err := scwManifest.GetManifest() if err != nil { logrus.Errorf("Cannot get manifest: %v", err) } else { cache.Manifest = manifest logrus.Infof("Manifest fetched: %d images", len(manifest.Images)) cache.MapImages() } time.Sleep(5 * time.Minute) }
conditional_block
main.go
package main import ( "fmt" "net/http" "os" "regexp" "strings" "sync" "time" "golang.org/x/oauth2" "github.com/Sirupsen/logrus" "github.com/dustin/go-humanize" "github.com/gin-gonic/gin" "github.com/google/go-github/github" "github.com/parnurzeal/gorequest" "github.com/renstrom/fuzzysearch/fuzzy" "git...
(left string, err error) string { logrus.Warnf("Failed to get badge: %v", err) // FIXME: remove the switch and compute the left width automatically switch left { case "build": return `<svg xmlns="http://www.w3.org/2000/svg" width="115" height="20"><linearGradient id="b" x2="0" y2="100%"><stop offset="0" stop-col...
errBadge
identifier_name
main.go
package main import ( "fmt" "net/http" "os" "regexp" "strings" "sync" "time" "golang.org/x/oauth2" "github.com/Sirupsen/logrus" "github.com/dustin/go-humanize" "github.com/gin-gonic/gin" "github.com/google/go-github/github" "github.com/parnurzeal/gorequest" "github.com/renstrom/fuzzysearch/fuzzy" "git...
func imagesEndpoint(c *gin.Context) { c.JSON(http.StatusOK, gin.H{ "images": cache.Mapping.Images, }) } func bootscriptsEndpoint(c *gin.Context) { c.JSON(http.StatusOK, gin.H{ "bootscripts": cache.Api.Bootscripts, }) } func imageDockerfileEndpoint(c *gin.Context) { name := c.Param("name") image := cache.M...
{ c.JSON(http.StatusOK, gin.H{ "cache": cache, }) }
identifier_body
timeline-custom-shiny.js
var timeline = function(attrs){ this.data = attrs.data; this.parsedData = []; this.startDate = attrs.startDate; this.endDate = attrs.endDate; this.visibleFirstDate = attrs.visibileFirstDate; this.visibleLastDate = attrs.visibleLastDate; }; timeline.prototype.parseJson = function(){ var json = this.da...
}); })(jQuery); timeline.prototype.addSlider = function(){ var self = this; this.drawSliderBackground(); $("#slider-range").dragslider({ range: true, min: self.startDate, max: self.endDate, animate: true, rangeDrag: true, values: [self.visibleFirstDate, self.visibleLastDate], sli...
this._rangeStart = newVal; } } }
random_line_split
timeline-custom-shiny.js
var timeline = function(attrs){ this.data = attrs.data; this.parsedData = []; this.startDate = attrs.startDate; this.endDate = attrs.endDate; this.visibleFirstDate = attrs.visibileFirstDate; this.visibleLastDate = attrs.visibleLastDate; }; timeline.prototype.parseJson = function(){ var json = this.da...
obj.start = stringToDate(item.startDate); obj.content = html; processedDatas.push(obj); } this.parsedData = processedDatas; return this; }; timeline.prototype.drawVisualization = function() { // Create and populate a data table. options = { 'height': "200px", 'width': "100%", 'st...
{ obj.end = stringToDate(item.endDate); }
conditional_block
api_op_CreateGovCloudAccount.go
// Code generated by smithy-go-codegen DO NOT EDIT. package organizations import ( "context" "errors" "fmt" "github.com/aws/aws-sdk-go-v2/aws" awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" "github.com/aws/aws-sdk-go-v2/aws/signer/v4" internalauth "github.com/aws/aws-sdk-go-v2/internal/auth" "git...
tack *middleware.Stack, options Options) (err error) { err = stack.Serialize.Add(&awsAwsjson11_serializeOpCreateGovCloudAccount{}, middleware.After) if err != nil { return err } err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpCreateGovCloudAccount{}, middleware.After) if err != nil { return err } if e...
dOperationCreateGovCloudAccountMiddlewares(s
identifier_name
api_op_CreateGovCloudAccount.go
// Code generated by smithy-go-codegen DO NOT EDIT. package organizations import ( "context" "errors" "fmt" "github.com/aws/aws-sdk-go-v2/aws" awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" "github.com/aws/aws-sdk-go-v2/aws/signer/v4" internalauth "github.com/aws/aws-sdk-go-v2/internal/auth" "git...
authSchemes, err := internalauth.GetAuthenticationSchemes(&resolvedEndpoint.Properties) if err != nil { var nfe *internalauth.NoAuthenticationSchemesFoundError if errors.As(err, &nfe) { // if no auth scheme is found, default to sigv4 signingName := "organizations" signingRegion := m.BuiltInResolver.(*bui...
resolvedEndpoint.Headers.Get(k), ) }
random_line_split
api_op_CreateGovCloudAccount.go
// Code generated by smithy-go-codegen DO NOT EDIT. package organizations import ( "context" "errors" "fmt" "github.com/aws/aws-sdk-go-v2/aws" awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" "github.com/aws/aws-sdk-go-v2/aws/signer/v4" internalauth "github.com/aws/aws-sdk-go-v2/internal/auth" "git...
if err = addRequestIDRetrieverMiddleware(stack); err != nil { return err } if err = addResponseErrorMiddleware(stack); err != nil { return err } if err = addRequestResponseLogging(stack, options); err != nil { return err } if err = addendpointDisableHTTPSMiddleware(stack, options); err != nil { return err...
return err }
conditional_block
api_op_CreateGovCloudAccount.go
// Code generated by smithy-go-codegen DO NOT EDIT. package organizations import ( "context" "errors" "fmt" "github.com/aws/aws-sdk-go-v2/aws" awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" "github.com/aws/aws-sdk-go-v2/aws/signer/v4" internalauth "github.com/aws/aws-sdk-go-v2/internal/auth" "git...
type opCreateGovCloudAccountResolveEndpointMiddleware struct { EndpointResolver EndpointResolverV2 BuiltInResolver builtInParameterResolver } func (*opCreateGovCloudAccountResolveEndpointMiddleware) ID() string { return "ResolveEndpointV2" } func (m *opCreateGovCloudAccountResolveEndpointMiddleware) HandleSeriali...
return &awsmiddleware.RegisterServiceMetadata{ Region: region, ServiceID: ServiceID, SigningName: "organizations", OperationName: "CreateGovCloudAccount", } }
identifier_body
lib.rs
//! [![github]](https://github.com/dtolnay/paste)&ensp;[![crates-io]](https://crates.io/crates/paste)&ensp;[![docs-rs]](https://docs.rs/paste) //! //! [github]: https://img.shields.io/badge/github-8da0cb?style=for-the-badge&labelColor=555555&logo=github //! [crates-io]: https://img.shields.io/badge/crates.io-fc8d62?sty...
if string.value.contains(&['#', '\\', '.', '+'][..]) || string.value.starts_with("b'") || string.value.starts_with("b\"") || string.value.starts_with("br\"") { return Err(Error::new(string.span, "unsupported literal")); ...
continue; } } }
random_line_split
lib.rs
//! [![github]](https://github.com/dtolnay/paste)&ensp;[![crates-io]](https://crates.io/crates/paste)&ensp;[![docs-rs]](https://docs.rs/paste) //! //! [github]: https://img.shields.io/badge/github-8da0cb?style=for-the-badge&labelColor=555555&logo=github //! [crates-io]: https://img.shields.io/badge/crates.io-fc8d62?sty...
{ let mut tokens = TokenStream::new(); #[cfg(not(no_literal_fromstr))] { use proc_macro::{LexError, Literal}; use std::str::FromStr; if pasted.starts_with(|ch: char| ch.is_ascii_digit()) { let literal = match panic::catch_unwind(|| Literal::from_str(&pasted)) { ...
identifier_body
lib.rs
//! [![github]](https://github.com/dtolnay/paste)&ensp;[![crates-io]](https://crates.io/crates/paste)&ensp;[![docs-rs]](https://docs.rs/paste) //! //! [github]: https://img.shields.io/badge/github-8da0cb?style=for-the-badge&labelColor=555555&logo=github //! [crates-io]: https://img.shields.io/badge/crates.io-fc8d62?sty...
{ Init, Ident, Literal, Apostrophe, Lifetime, Colon1, Colon2, } let mut state = State::Init; for tt in input.clone() { state = match (state, &tt) { (State::Init, TokenTree::Ident(_)) => State::Ident, (State::Init, Toke...
State
identifier_name
k_means_anchor_points.py
# -*- coding: utf-8 -*- import os import numpy as np import matplotlib.pyplot as plt import matplotlib.patches as patches import xml.etree.ElementTree as ET from pycocotools.coco import COCO from utils import convert_bbox, convert_coco_bbox, BoundingBox import IO # Original code @ferada http://codereview.stackexchange...
if __name__ == "__main__": # examples # k, pascal, coco # 1, 0.30933335617, 0.252004954777 # 2, 0.45787906725, 0.365835079771 # 3, 0.53198291772, 0.453180358467 # 4, 0.57562962803, 0.500282182136 # 5, 0.58694643198, 0.522010174068 # 6, 0.61789602056, 0.549904351137 # 7, 0.63443906...
name = 'coco' data = [] for dataset in datasets: annfile = f'{source_dir}/{name}/annotations/instances_{dataset}.json' coco = COCO(annfile) cats = coco.loadCats(coco.getCatIds()) base_classes = {cat['id']: cat['name'] for cat in cats} img_id_set = set() for cat_...
identifier_body
k_means_anchor_points.py
# -*- coding: utf-8 -*- import os import numpy as np import matplotlib.pyplot as plt import matplotlib.patches as patches import xml.etree.ElementTree as ET from pycocotools.coco import COCO from utils import convert_bbox, convert_coco_bbox, BoundingBox import IO # Original code @ferada http://codereview.stackexchange...
ifs_img_ids.close() return np.array(data) def load_coco_dataset(): name = 'coco' data = [] for dataset in datasets: annfile = f'{source_dir}/{name}/annotations/instances_{dataset}.json' coco = COCO(annfile) cats = coco.loadCats(coco.getCatIds()) base_classes ...
anno_filename = f'{source_dir}/{name}/VOCdevkit/VOC{year}/Annotations/{image_id}.xml' ifs_anno = open(anno_filename) tree = ET.parse(ifs_anno) root = tree.getroot() size = root.find('size') w = int(size.find('width').text) h = int(size.find('height...
conditional_block
k_means_anchor_points.py
# -*- coding: utf-8 -*- import os import numpy as np import matplotlib.pyplot as plt import matplotlib.patches as patches import xml.etree.ElementTree as ET from pycocotools.coco import COCO from utils import convert_bbox, convert_coco_bbox, BoundingBox import IO # Original code @ferada http://codereview.stackexchange...
(): name = 'pascal' data = [] for year, image_set in datasets: img_ids_filename = f'{source_dir}/{name}/VOCdevkit/VOC{year}/ImageSets/Main/{image_set}.txt' ifs_img_ids = open(img_ids_filename) img_ids = ifs_img_ids.read().strip().split() for image_id in img_ids: ...
load_pascal_dataset
identifier_name
k_means_anchor_points.py
# -*- coding: utf-8 -*- import os import numpy as np import matplotlib.pyplot as plt
import IO # Original code @ferada http://codereview.stackexchange.com/questions/128315/k-means-clustering-algorithm-implementation def area(x): if len(x.shape) == 1: return x[0] * x[1] else: return x[:, 0] * x[:, 1] def kmeans_iou(k, centroids, points, iter_count=0, iteration_cutoff=25, fea...
import matplotlib.patches as patches import xml.etree.ElementTree as ET from pycocotools.coco import COCO from utils import convert_bbox, convert_coco_bbox, BoundingBox
random_line_split
Titanic_RandomForest_0526.py
# coding: utf-8 # In[1]: import os os.chdir(u'E:/量知/Ali/dmlib') # # Titanic问题 数据集: 变量 定义 值 Variable Definition Key survival Survival 0 = No, 1 = Yes pclass Ticket class 1 = 1st, 2 = 2nd, 3 = 3rd sex Sex Age ...
conditional_block
Titanic_RandomForest_0526.py
# coding: utf-8 # In[1]: import os os.chdir(u'E:/量知/Ali/dmlib') # # Titanic问题 数据集: 变量 定义 值 Variable Definition Key survival Survival 0 = No, 1 = Yes pclass Ticket class 1 = 1st, 2 = 2nd, 3 = 3rd sex Sex Age ...
人死亡但被预测为幸存,其他为预测正确的人数。 # In[40]: from evaluate.ClassificationEvaluate import ClassificationEvaluate ce = ClassificationEvaluate(labelColName='Survived',scoreColName='predict_score') ce.transform(predict) # fpr-横坐标,rpr-纵坐标,fpr越小越好,tpr越大越好;AUC为ROC曲线下面的面积 # In[ ]:
有8个人实际幸存了但被预测为死亡,有22个
identifier_name
Titanic_RandomForest_0526.py
# coding: utf-8 # In[1]: import os os.chdir(u'E:/量知/Ali/dmlib') # # Titanic问题 数据集: 变量 定义 值 Variable Definition Key survival Survival 0 = No, 1 = Yes pclass Ticket class 1 = 1st, 2 = 2nd, 3 = 3rd sex Sex Age ...
# In[29]: from ml.classify import RandomForest from pipeline import Pipeline from feature_engineer.randomForestImportance import RandomForestImportance alg1 = RandomForest(labelColName='Survived', featureColNames=list(testing.columns),treeNum=100,maxTreeDeep=None,randomColNum='log2',minNumObj=3) imp = RandomForestIm...
# In[28]: pd.Series(predict1).value_counts()
random_line_split
Titanic_RandomForest_0526.py
# coding: utf-8 # In[1]: import os os.chdir(u'E:/量知/Ali/dmlib') # # Titanic问题 数据集: 变量 定义 值 Variable Definition Key survival Survival 0 = No, 1 = Yes pclass Ticket class 1 = 1st, 2 = 2nd, 3 = 3rd sex Sex Age ...
40]: from evaluate.ClassificationEvaluate import ClassificationEvaluate ce = ClassificationEvaluate(labelColName='Survived',scoreColName='predict_score') ce.transform(predict) # fpr-横坐标,rpr-纵坐标,fpr越小越好,tpr越大越好;AUC为ROC曲线下面的面积 # In[ ]:
identifier_body
kube.go
// Copyright 2019 GM Cruise LLC // // 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 i...
url := m.Master + r.PathWithName() var waitDone <-chan time.Time if wait != 0 { waitDone = time.After(wait) } // retryInterval is zero so no delay before the first poll. var retryInterval time.Duration for { select { case <-time.After(retryInterval): retryInterval = waitRetryInterval obj, ok, err :=...
random_line_split
kube.go
// Copyright 2019 GM Cruise LLC // // 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 i...
(t *starlark.Thread, b *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) { if len(args) != 0 { return starlark.False, fmt.Errorf("<%v>: positional args not supported: %v", b.Name(), args) } if len(kwargs) < 1 { return starlark.False, fmt.Errorf("<%v>: expected <resource>=<...
kubeExistsFn
identifier_name
kube.go
// Copyright 2019 GM Cruise LLC // // 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 i...
if m.dryRun { return printUnifiedDiff(os.Stdout, live, msg.(runtime.Object), r.GVK, maybeNamespaced(r.Name, r.Namespace), m.diffFilters) } resp, err := m.httpClient.Do(req.WithContext(ctx)) if err != nil { return err } _, rMsg, err := parseHTTPResponse(resp) if err != nil { return err } actionMsg :=...
{ if err := printUnifiedDiff(os.Stdout, live, msg.(runtime.Object), r.GVK, maybeNamespaced(r.Name, r.Namespace), m.diffFilters); err != nil { return err } }
conditional_block
kube.go
// Copyright 2019 GM Cruise LLC // // 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 i...
// kubeGetFn is an entry point for `kube.get` built-in. func (m *kubePackage) kubeGetFn(t *starlark.Thread, b *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) { if len(args) != 0 { return nil, fmt.Errorf("<%v>: positional args not supported: %v", b.Name(), args) } if len(...
{ if len(args) != 0 { return nil, fmt.Errorf("<%v>: positional args not supported by `kube.delete': %v", b.Name(), args) } if len(kwargs) < 1 { return nil, fmt.Errorf("<%v>: expected at least <resource>=<name>", b.Name()) } resource, name, err := getResourceAndName(kwargs[0]) if err != nil { return nil, f...
identifier_body
run_model.py
#!/usr/bin/python import inspect import os import matplotlib import matplotlib.pyplot as plt import numpy as np from pymt.models import Cem, Rafem, Waves matplotlib.use("Agg") N_DAYS = 30*365 # number of days to run model Save_Daily_Timesteps = 1 # flag for saving daily information Save_Yearly_Timesteps = 0 ...
cem = Cem() raf = Rafem() waves = Waves() args = cem.setup("_run_cem", number_of_cols=120, number_of_rows=100, grid_spacing=100.0) cem.initialize(*args) args = raf.setup( "_run_rafem", n_cols=120, n_rows=100, dy=0.1, dx=0.1, time_step= 0.05, # timestep (days) sea_level_rise_rate=0.0, ...
import matplotlib.pyplot as plt from matplotlib.colors import LinearSegmentedColormap land = plt.cm.terrain(np.linspace(0.4, 1, 128)) ocean = plt.cm.ocean(np.linspace(0.5, 0.8, 128)) colors = np.vstack((ocean, land)) m = LinearSegmentedColormap.from_list("land_ocean", colors) (x, y) = np.meshg...
identifier_body
run_model.py
#!/usr/bin/python import inspect import os import matplotlib import matplotlib.pyplot as plt import numpy as np from pymt.models import Cem, Rafem, Waves matplotlib.use("Agg") N_DAYS = 30*365 # number of days to run model Save_Daily_Timesteps = 1 # flag for saving daily information Save_Yearly_Timesteps = 0 ...
(spacing, z): import matplotlib.pyplot as plt from matplotlib.colors import LinearSegmentedColormap land = plt.cm.terrain(np.linspace(0.4, 1, 128)) ocean = plt.cm.ocean(np.linspace(0.5, 0.8, 128)) colors = np.vstack((ocean, land)) m = LinearSegmentedColormap.from_list("land_ocean", colors) ...
plot_coast
identifier_name
run_model.py
#!/usr/bin/python import inspect import os import matplotlib import matplotlib.pyplot as plt import numpy as np from pymt.models import Cem, Rafem, Waves matplotlib.use("Agg") N_DAYS = 30*365 # number of days to run model Save_Daily_Timesteps = 1 # flag for saving daily information Save_Yearly_Timesteps = 0 ...
raf_z.reshape(shape[0] * shape[1]) cem.set_value("land_surface__elevation", raf_z) # update wave climate waves.update() angle = waves.get_value( "sea_surface_water_wave__azimuth_angle_of_opposite_of_phase_velocity" ) cem.set_value( "sea_surface_water_wave__azimuth_angle_o...
if raf_z[riv_j[k], riv_i[k]] < 1: if mouth_cell_count < 1: mouth_cell_count += 1 else: raf_z[riv_j[k], riv_i[k]] = 1
conditional_block
run_model.py
#!/usr/bin/python import inspect import os import matplotlib import matplotlib.pyplot as plt import numpy as np from pymt.models import Cem, Rafem, Waves matplotlib.use("Agg") N_DAYS = 30*365 # number of days to run model Save_Daily_Timesteps = 1 # flag for saving daily information Save_Yearly_Timesteps = 0 ...
### set CEM wave angle if not updating waves ### # cem.set_value("sea_surface_water_wave__azimuth_angle_of_opposite_of_phase_velocity", 0. * np.pi / 180.) grid_id = cem.get_var_grid("land_surface__elevation") spacing = cem.get_grid_spacing(grid_id) shape = cem.get_grid_shape(grid_id) z0 = raf.get_value("land_surface...
cem.set_value("sea_surface_water_wave__period", 9.0)
random_line_split
schedule.rs
// Copyright (c) 2016 DWANGO Co., Ltd. All Rights Reserved. // See the LICENSE file at the top-level directory of this distribution. use futures::{Async, Future, Poll}; use std::cell::RefCell; use std::collections::{HashMap, VecDeque}; use std::sync::atomic; use std::sync::mpsc as std_mpsc; use super::{FiberState, Sp...
let is_runnable = { CURRENT_CONTEXT.with(|context| { let mut context = context.borrow_mut(); if context .scheduler .as_ref() .map_or(true, |s| s.id != self.scheduler_id) { ...
let finished;
random_line_split
schedule.rs
// Copyright (c) 2016 DWANGO Co., Ltd. All Rights Reserved. // See the LICENSE file at the top-level directory of this distribution. use futures::{Async, Future, Poll}; use std::cell::RefCell; use std::collections::{HashMap, VecDeque}; use std::sync::atomic; use std::sync::mpsc as std_mpsc; use super::{FiberState, Sp...
Err(std_mpsc::TryRecvError::Disconnected) => unreachable!(), Ok(request) => { did_something = true; self.handle_request(request); } } // Task if let Some(fiber_id) = self.next_runnable() { ...
{}
conditional_block
schedule.rs
// Copyright (c) 2016 DWANGO Co., Ltd. All Rights Reserved. // See the LICENSE file at the top-level directory of this distribution. use futures::{Async, Future, Poll}; use std::cell::RefCell; use std::collections::{HashMap, VecDeque}; use std::sync::atomic; use std::sync::mpsc as std_mpsc; use super::{FiberState, Sp...
<'a> { scheduler: &'a mut CurrentScheduler, fiber: &'a mut FiberState, } impl<'a> Context<'a> { /// Returns the identifier of the current exeuction context. pub fn context_id(&self) -> super::ContextId { (self.scheduler.id, self.fiber.fiber_id) } /// Parks the current fiber. pub fn ...
Context
identifier_name
schedule.rs
// Copyright (c) 2016 DWANGO Co., Ltd. All Rights Reserved. // See the LICENSE file at the top-level directory of this distribution. use futures::{Async, Future, Poll}; use std::cell::RefCell; use std::collections::{HashMap, VecDeque}; use std::sync::atomic; use std::sync::mpsc as std_mpsc; use super::{FiberState, Sp...
fn next_runnable(&mut self) -> Option<fiber::FiberId> { while let Some(fiber_id) = self.run_queue.pop_front() { if let Some(fiber) = self.fibers.get_mut(&fiber_id) { fiber.in_run_queue = false; return Some(fiber_id); } } None } } ...
{ let fiber = assert_some!(self.fibers.get_mut(&fiber_id)); if !fiber.in_run_queue { self.run_queue.push_back(fiber_id); fiber.in_run_queue = true; } }
identifier_body
HttpServiceSparqlEndpoint.ts
import {LoggerPretty} from "@comunica/logger-pretty"; import * as fs from "fs"; import * as http from "http"; import EventEmitter = NodeJS.EventEmitter; import minimist = require("minimist"); import * as querystring from "querystring"; import {Writable} from "stream"; import * as url from "url"; import {newEngineDynami...
(engine: ActorInitSparql, variants: { type: string, quality: number }[], stdout: Writable, stderr: Writable, request: http.IncomingMessage, response: http.ServerResponse) { const mediaType: string = request.headers.accept && request.headers.accept !== '*/*' ...
handleRequest
identifier_name
HttpServiceSparqlEndpoint.ts
import {LoggerPretty} from "@comunica/logger-pretty"; import * as fs from "fs"; import * as http from "http"; import EventEmitter = NodeJS.EventEmitter; import minimist = require("minimist"); import * as querystring from "querystring"; import {Writable} from "stream"; import * as url from "url"; import {newEngineDynami...
} /** * Parses the body of a SPARQL POST request * @param {module:http.IncomingMessage} request Request object. * @return {Promise<string>} A promise resolving to a query string. */ public parseBody(request: http.IncomingMessage): Promise<string> { return new Promise((resolve, reject) => { ...
} try { response.end(); } catch (e) { /* ignore error */ } clearTimeout(killTimeout); }
random_line_split
HttpServiceSparqlEndpoint.ts
import {LoggerPretty} from "@comunica/logger-pretty"; import * as fs from "fs"; import * as http from "http"; import EventEmitter = NodeJS.EventEmitter; import minimist = require("minimist"); import * as querystring from "querystring"; import {Writable} from "stream"; import * as url from "url"; import {newEngineDynami...
else if (contentType.indexOf('application/x-www-form-urlencoded') >= 0) { return resolve(<string> querystring.parse(body).query || ''); } else { return resolve(body); } }); }); } } export interface IHttpServiceSparqlEndpointArgs extends IQueryOptions { context?: any; ...
{ return resolve(body); }
conditional_block
HttpServiceSparqlEndpoint.ts
import {LoggerPretty} from "@comunica/logger-pretty"; import * as fs from "fs"; import * as http from "http"; import EventEmitter = NodeJS.EventEmitter; import minimist = require("minimist"); import * as querystring from "querystring"; import {Writable} from "stream"; import * as url from "url"; import {newEngineDynami...
} export interface IHttpServiceSparqlEndpointArgs extends IQueryOptions { context?: any; timeout?: number; port?: number; invalidateCacheBeforeQuery?: boolean; }
{ return new Promise((resolve, reject) => { let body = ''; request.setEncoding('utf8'); request.on('error', reject); request.on('data', (chunk) => { body += chunk; }); request.on('end', () => { const contentType: string = request.headers['content-type']; if (contentType...
identifier_body
__init__.py
"""Handle automations.""" # Copyright 2013-2017 The Home Assistant Authors # https://github.com/home-assistant/home-assistant/blob/master/LICENSE.md # This file was modified by The Camacq Authors. import logging from collections import deque from functools import partial import voluptuous as vol from camacq.exception...
(**kwargs): """Enable or disable an automation.""" name = kwargs[NAME] automation = automations[name] enabled = kwargs.get(ENABLED, not automation.enabled) if enabled: automation.enable() else: automation.disable() toggle_action_schema = BASE_...
handle_action
identifier_name
__init__.py
"""Handle automations.""" # Copyright 2013-2017 The Home Assistant Authors # https://github.com/home-assistant/home-assistant/blob/master/LICENSE.md # This file was modified by The Camacq Authors. import logging from collections import deque from functools import partial import voluptuous as vol from camacq.exception...
else: automation.disable() toggle_action_schema = BASE_ACTION_SCHEMA.extend( { vol.Required(NAME): vol.All(vol.Coerce(str), vol.In(automations)), ENABLED: vol.Boolean(), # pylint: disable=no-value-for-parameter } ) # register action to enable/d...
automation.enable()
conditional_block
__init__.py
"""Handle automations.""" # Copyright 2013-2017 The Home Assistant Authors # https://github.com/home-assistant/home-assistant/blob/master/LICENSE.md # This file was modified by The Camacq Authors. import logging from collections import deque from functools import partial import voluptuous as vol from camacq.exception...
rendered_kwargs = action.render(variables) seconds = rendered_kwargs.get("seconds") self.delay(float(seconds), variables, waiting) else: _LOGGER.debug( "Calling action %s.%s", action.action_type, action.action_id ...
while waiting: action = waiting.popleft() if action.action_type == "automations" and action.action_id == ACTION_DELAY:
random_line_split
__init__.py
"""Handle automations.""" # Copyright 2013-2017 The Home Assistant Authors # https://github.com/home-assistant/home-assistant/blob/master/LICENSE.md # This file was modified by The Camacq Authors. import logging from collections import deque from functools import partial import voluptuous as vol from camacq.exception...
return remove_triggers class Automation: """Automation class.""" # pylint: disable=too-many-arguments def __init__( self, center, name, attach_triggers, cond_func, action_sequence, enabled=True ): """Set up instance.""" self._center = center self.name = name ...
"""Remove attached triggers.""" for remove in remove_funcs: remove()
identifier_body
cosmos.go
package relayer // DONTCOVER import ( "bytes" "context" "crypto/ecdsa" "encoding/hex" "errors" "fmt" "github.com/Sifchain/sifnode/cmd/ebrelayer/internal/symbol_translator" "log" "math/big" "os" "os/signal" "strconv" "sync" "syscall" "time" "github.com/Sifchain/sifnode/cmd/ebrelayer/contract" cosmosb...
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM) defer close(quit) var lastProcessedBlock int64 data, err := sub.DB.Get([]byte(cosmosLevelDBKey), nil) if err != nil { log.Println("Error getting the last cosmos block from level db", err) lastProcessedBlock = 0 } else { lastProcessedBlock = new(big.Int)...
quit := make(chan os.Signal, 1)
random_line_split
cosmos.go
package relayer // DONTCOVER import ( "bytes" "context" "crypto/ecdsa" "encoding/hex" "errors" "fmt" "github.com/Sifchain/sifnode/cmd/ebrelayer/internal/symbol_translator" "log" "math/big" "os" "os/signal" "strconv" "sync" "syscall" "time" "github.com/Sifchain/sifnode/cmd/ebrelayer/contract" cosmosb...
return prophecyClaimArray } // MyDecode decode data in ProphecyClaim transaction func MyDecode(data []byte) (types.ProphecyClaimUnique, error) { if len(data) < 32*7+42 { return types.ProphecyClaimUnique{}, errors.New("tx data length not enough") } src := data[64:96] dst := make([]byte, hex.EncodedLen(len(src)...
{ log.Printf("getAllProphecyClaim current blockNumber is %d\n", blockNumber) block, err := client.BlockByNumber(context.Background(), big.NewInt(blockNumber)) if err != nil { log.Printf("failed to get block from ethereum, block number is %d\n", blockNumber) blockNumber++ continue } for _, tx := ran...
conditional_block
cosmos.go
package relayer // DONTCOVER import ( "bytes" "context" "crypto/ecdsa" "encoding/hex" "errors" "fmt" "github.com/Sifchain/sifnode/cmd/ebrelayer/internal/symbol_translator" "log" "math/big" "os" "os/signal" "strconv" "sync" "syscall" "time" "github.com/Sifchain/sifnode/cmd/ebrelayer/contract" cosmosb...
(symbolTranslator *symbol_translator.SymbolTranslator, fromBlock int64, toBlock int64, ethFromBlock int64, ethToBlock int64) { // Start Ethereum client ethClient, err := ethclient.Dial(sub.EthProvider) if err != nil { log.Printf("%s \n", err.Error()) return } clientChainID, err := ethClient.NetworkID(context....
Replay
identifier_name
cosmos.go
package relayer // DONTCOVER import ( "bytes" "context" "crypto/ecdsa" "encoding/hex" "errors" "fmt" "github.com/Sifchain/sifnode/cmd/ebrelayer/internal/symbol_translator" "log" "math/big" "os" "os/signal" "strconv" "sync" "syscall" "time" "github.com/Sifchain/sifnode/cmd/ebrelayer/contract" cosmosb...
func tryInitRelayConfig(sub CosmosSub, claimType types.Event) (*ethclient.Client, *bind.TransactOpts, common.Address, error) { for i := 0; i < 5; i++ { client, auth, target, err := txs.InitRelayConfig( sub.EthProvider, sub.RegistryContractAddress, claimType, sub.PrivateKey, sub.SugaredLogger, ) ...
{ var claimType types.Event switch eventType { case types.MsgBurn.String(): claimType = types.MsgBurn case types.MsgLock.String(): claimType = types.MsgLock default: claimType = types.Unsupported } return claimType }
identifier_body
mod.rs
//! Inter-Integrated Circuit driver for Tegra210. //! //! # Description //! //! The I²C controller (I2C) implements an I²C 3.0 specification-compliant //! I²C master and slave controller. The I²C controller supports multiple //! masters and slaves. It supports Standard mode (up to 100 Kbits/s), //! Fast mode (up to 400...
evice over I²C and writes the result to the buffer. pub fn read(&self, device: u32, register: u8, buffer: &mut [u8]) -> Result<(), Error> { // Limit output size to 32-bits. if buffer.len() > 4 { return Err(Error::BufferBoundariesBlown); } // Write single byte register ID...
device. self.write(device, register, &byte.to_le_bytes()) } /// Reads a register of a d
identifier_body
mod.rs
//! Inter-Integrated Circuit driver for Tegra210. //! //! # Description //! //! The I²C controller (I2C) implements an I²C 3.0 specification-compliant //! I²C master and slave controller. The I²C controller supports multiple //! masters and slaves. It supports Standard mode (up to 100 Kbits/s), //! Fast mode (up to 400...
pub I2C_CMD_DATA2: Mmio<u32>, _0x14: Mmio<u32>, _0x18: Mmio<u32>, pub I2C_STATUS: Mmio<u32>, pub I2C_SL_CNFG: Mmio<u32>, pub I2C_SL_RCVD: Mmio<u32>, pub I2C_SL_STATUS: Mmio<u32>, pub I2C_SL_ADDR1: Mmio<u32>, pub I2C_SL_ADDR2: Mmio<u32>, pub I2C_TLOW_SEXT: Mmio<u32>, _0x38: Mm...
pub struct Registers { pub I2C_CNFG: Mmio<u32>, pub I2C_CMD_ADDR0: Mmio<u32>, pub I2C_CMD_ADDR1: Mmio<u32>, pub I2C_CMD_DATA1: Mmio<u32>,
random_line_split
mod.rs
//! Inter-Integrated Circuit driver for Tegra210. //! //! # Description //! //! The I²C controller (I2C) implements an I²C 3.0 specification-compliant //! I²C master and slave controller. The I²C controller supports multiple //! masters and slaves. It supports Standard mode (up to 100 Kbits/s), //! Fast mode (up to 400...
buffer: &mut [u8]) -> Result<(), Error> { // Limit output size to 32-bits. if buffer.len() > 4 { return Err(Error::BufferBoundariesBlown); } // Write single byte register ID to device. self.send(device, &[register])?; // Receive data and write these to the ...
u8,
identifier_name
mod.rs
//! Inter-Integrated Circuit driver for Tegra210. //! //! # Description //! //! The I²C controller (I2C) implements an I²C 3.0 specification-compliant //! I²C master and slave controller. The I²C controller supports multiple //! masters and slaves. It supports Standard mode (up to 100 Kbits/s), //! Fast mode (up to 400...
opy it back. let result = register_base.I2C_CMD_DATA1.read().to_le_bytes(); buffer.copy_from_slice(&result[..buffer.len()]); Ok(()) } /// Initializes the I²C controller. pub fn init(&self) { let register_base = unsafe { &*self.registers }; // Enable device clock. ...
::QueryFailed); } // Read result and c
conditional_block
FP.py
from tkinter import * from PIL import ImageTk from PIL import Image import os,shutil,sys import tkinter.font as tkFont from tkinter import ttk from tkinter.filedialog import askdirectory,askopenfilename import tkinter.messagebox import time,datetime import threading import imagehash_retrieval as imagehash_retrieval ...
b1=Button(frm_B1,text="average_hash",width=12,command=clicked1) b1.grid(row=1,column=2) b1=Button(frm_B1,text="dhash",width=12,command=clicked2) b1.grid(row=1,column=3) b1=Button(frm_B1,text="phash",width=12,command=clicked3) b1.grid(row=2,column=2) b1=Button(frm_B1,text="whash",width=12,command=clicked4) b1.grid(ro...
random_line_split
FP.py
from tkinter import * from PIL import ImageTk from PIL import Image import os,shutil,sys import tkinter.font as tkFont from tkinter import ttk from tkinter.filedialog import askdirectory,askopenfilename import tkinter.messagebox import time,datetime import threading import imagehash_retrieval as imagehash_retrieval ...
for index, (val, k) in enumerate(l): tv.move(k, '', index) tv.heading(col, command=lambda: treeview_sort_column1(tv, col, not reverse)) def treeview_sort_column2(tv, col, reverse):#Treeview、列名、排列方式(数字排序) l = [(tv.set(k, col), k) for k in tv.get_children('')] l.sort(key=lambda t: float(t[0]), rev...
age1_resized = resize(w, h, w_box, h_box, image1)#改成合适比例函数 image11= ImageTk.PhotoImage(image1_resized) #转成XX对象 label1.configure(image = image11) def treeview_sort_column1(tv, col, reverse):#Treeview、列名、排列方式(桶排序) l = [(tv.set(k, col), k) for k in tv.get_children('')] l.sort(reverse=reverse)
identifier_body
FP.py
from tkinter import * from PIL import ImageTk from PIL import Image import os,shutil,sys import tkinter.font as tkFont from tkinter import ttk from tkinter.filedialog import askdirectory,askopenfilename import tkinter.messagebox import time,datetime import threading import imagehash_retrieval as imagehash_retrieval ...
try: showPic3(lb.get(lb.curselection())) except: pass def LbClick2(event):#listbox双击 try: print (lb.get(lb.curselection())) #读取图像 im=Image.open(lb.get(lb.curselection())) #显示图像 im.show() except: pass def lbExecute(listT):#listbox处理 ...
1(event):#listbox点击
conditional_block
FP.py
from tkinter import * from PIL import ImageTk from PIL import Image import os,shutil,sys import tkinter.font as tkFont from tkinter import ttk from tkinter.filedialog import askdirectory,askopenfilename import tkinter.messagebox import time,datetime import threading import imagehash_retrieval as imagehash_retrieval ...
retrieval.imagehash_retrieval(var1, var2,'dhash',thred=0) print(hash_res) def clicked3(): hash_res = imagehash_retrieval.imagehash_retrieval(var1, var2,'phash',thred=0) print(hash_res) def clicked4(): hash_res = imagehash_retrieval.imagehash_retrieval(var1, var2,'whas...
agehash_
identifier_name
get_block_template.rs
//! Support functions for the `get_block_template()` RPC. use std::{collections::HashMap, iter, sync::Arc}; use jsonrpc_core::{Error, ErrorCode, Result}; use tower::{Service, ServiceExt}; use zebra_chain::{ amount::{self, Amount, NegativeOrZero, NonNegative}, block::{ self, merkle::{self, Aut...
( funding_streams: HashMap<FundingStreamReceiver, (Amount<NonNegative>, transparent::Address)>, miner_address: transparent::Address, miner_reward: Amount<NonNegative>, like_zcashd: bool, ) -> Vec<(Amount<NonNegative>, transparent::Script)> { // Combine all the funding streams with the miner reward. ...
combine_coinbase_outputs
identifier_name
get_block_template.rs
//! Support functions for the `get_block_template()` RPC. use std::{collections::HashMap, iter, sync::Arc}; use jsonrpc_core::{Error, ErrorCode, Result}; use tower::{Service, ServiceExt}; use zebra_chain::{ amount::{self, Amount, NegativeOrZero, NonNegative}, block::{ self, merkle::{self, Aut...
/// Returns the transactions that are currently in `mempool`, or None if the /// `last_seen_tip_hash` from the mempool response doesn't match the tip hash from the state. /// /// You should call `check_synced_to_tip()` before calling this function. /// If the mempool is inactive because Zebra is not synced to the tip...
{ let request = zebra_state::ReadRequest::ChainInfo; let response = state .oneshot(request.clone()) .await .map_err(|error| Error { code: ErrorCode::ServerError(0), message: error.to_string(), data: None, })?; let chain_info = match respon...
identifier_body
get_block_template.rs
//! Support functions for the `get_block_template()` RPC. use std::{collections::HashMap, iter, sync::Arc}; use jsonrpc_core::{Error, ErrorCode, Result}; use tower::{Service, ServiceExt}; use zebra_chain::{ amount::{self, Amount, NegativeOrZero, NonNegative}, block::{ self, merkle::{self, Aut...
transparent, }; use zebra_consensus::{ funding_stream_address, funding_stream_values, miner_subsidy, FundingStreamReceiver, }; use zebra_node_services::mempool; use zebra_state::GetBlockTemplateChainInfo; use crate::methods::get_block_template_rpcs::{ constants::{MAX_ESTIMATED_DISTANCE_TO_NETWORK_CHAIN_TIP...
parameters::Network, serialization::ZcashDeserializeInto, transaction::{Transaction, UnminedTx, VerifiedUnminedTx},
random_line_split
server.rs
// // Copyright (c) Pirmin Kalberer. All rights reserved. // Licensed under the MIT License. See LICENSE file in the project root for full license information. // use core::config::ApplicationCfg; use datasource_type::Datasources; use datasource::DatasourceInput; use core::grid::Grid; use core::layer::Layer; use servi...
} struct StaticFiles { files: HashMap<&'static str, (&'static [u8], MediaType)>, } impl StaticFiles { fn init() -> StaticFiles { let mut static_files = StaticFiles { files: HashMap::new(), }; static_files.add( "favicon.ico", include_bytes!("static/f...
{ let mut hasviewer = true; let layerinfos: Vec<String> = set.layers .iter() .map(|l| { let geom_type = l.geometry_type.clone().unwrap_or("UNKNOWN".to_string()); hasviewer = hasviewer && [ "POINT", ...
identifier_body
server.rs
// // Copyright (c) Pirmin Kalberer. All rights reserved. // Licensed under the MIT License. See LICENSE file in the project root for full license information. // use core::config::ApplicationCfg; use datasource_type::Datasources; use datasource::DatasourceInput; use core::grid::Grid; use core::layer::Layer; use servi...
} else { None } } None => None, }; } pub fn service_from_args(args: &ArgMatches) -> (MvtService, ApplicationCfg) { if let Some(cfgpath) = args.value_of("config") { info!("Reading configuration from '{}'", cfgpath); for argname in vec!["db...
{ Some(0) }
conditional_block
server.rs
// // Copyright (c) Pirmin Kalberer. All rights reserved. // Licensed under the MIT License. See LICENSE file in the project root for full license information. // use core::config::ApplicationCfg; use datasource_type::Datasources; use datasource::DatasourceInput; use core::grid::Grid; use core::layer::Layer; use servi...
() -> StaticFiles { let mut static_files = StaticFiles { files: HashMap::new(), }; static_files.add( "favicon.ico", include_bytes!("static/favicon.ico"), MediaType::Ico, ); static_files.add( "index.html", inc...
init
identifier_name
server.rs
// // Copyright (c) Pirmin Kalberer. All rights reserved. // Licensed under the MIT License. See LICENSE file in the project root for full license information. // use core::config::ApplicationCfg; use datasource_type::Datasources; use datasource::DatasourceInput; use core::grid::Grid; use core::layer::Layer; use servi...
serde_json::to_vec(&json).unwrap() }, ); server.get( "/:tileset/:z/:x/:y.pbf", middleware! { |req, mut res| let service: &MvtService = res.server_data(); let tileset = req.param("tileset").unwrap(); let z = req.param("z").unwrap().parse::...
let json = service.get_mbtiles_metadata(&tileset).unwrap();
random_line_split
mod.rs
pub mod dir_diff_list; use crate::cli_opt::{ApplyOpts, CliOpts, Command, TestSamplesOpts}; use crate::path_pattern::PathPattern; use crate::{error::*, SourceLoc}; use clap::Parser; use dir_diff_list::Difference; use dir_diff_list::EntryDiff; use std::fs; use std::path::{Path, PathBuf}; use tempfile::{tempdir, TempDir}...
else if crate::ui::ask_to_update_sample("Accept to add into sample ?")? { let path = self.actual_base_path.join(&self.relative_path); let is_dir = std::fs::metadata(&path)?.is_dir(); if is_dir { std::fs::create_dir_all(self.expect_base...
{ let path = self.expect_base_path.join(&self.relative_path); let is_dir = std::fs::metadata(&path)?.is_dir(); if crate::ui::ask_to_update_sample("Accept to remove from sample ?")? { if is_dir { std::fs::remo...
conditional_block
mod.rs
pub mod dir_diff_list; use crate::cli_opt::{ApplyOpts, CliOpts, Command, TestSamplesOpts}; use crate::path_pattern::PathPattern; use crate::{error::*, SourceLoc}; use clap::Parser; use dir_diff_list::Difference; use dir_diff_list::EntryDiff; use std::fs; use std::path::{Path, PathBuf}; use tempfile::{tempdir, TempDir}...
pub fn is_success(&self) -> bool { self.diffs.is_empty() } } impl std::fmt::Display for SampleRun { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "Differences: {:#?}", self.diffs) } } /// recursively copy a directory /// based on https://stackoverflow...
{ // ALTERNATIVE: fork a sub-process to run current ffizer in apply mode let destination = &sample.args.dst_folder; if sample.existing.exists() { copy(&sample.existing, destination)?; } let ctx = crate::Ctx { cmd_opt: sample.args.clone(), }; ...
identifier_body
mod.rs
pub mod dir_diff_list; use crate::cli_opt::{ApplyOpts, CliOpts, Command, TestSamplesOpts}; use crate::path_pattern::PathPattern; use crate::{error::*, SourceLoc}; use clap::Parser; use dir_diff_list::Difference; use dir_diff_list::EntryDiff; use std::fs; use std::path::{Path, PathBuf}; use tempfile::{tempdir, TempDir}...
samples_folder: B, tmp_dir: &TempDir, ) -> Result<Vec<Sample>> { let mut out = vec![]; for e in fs::read_dir(&samples_folder).map_err(|source| Error::ListFolder { path: samples_folder.as_ref().into(), source, })? { let path = e?.path(); ...
fn find_from_folder<B: AsRef<Path>>( template_loc: &SourceLoc,
random_line_split
mod.rs
pub mod dir_diff_list; use crate::cli_opt::{ApplyOpts, CliOpts, Command, TestSamplesOpts}; use crate::path_pattern::PathPattern; use crate::{error::*, SourceLoc}; use clap::Parser; use dir_diff_list::Difference; use dir_diff_list::EntryDiff; use std::fs; use std::path::{Path, PathBuf}; use tempfile::{tempdir, TempDir}...
<P: AsRef<Path>>(file: P) -> Result<Self> { let v = if file.as_ref().exists() { let cfg_str = fs::read_to_string(file.as_ref()).map_err(|source| Error::ReadFile { path: file.as_ref().into(), source, })?; serde_yaml::from_str::<SampleCfg>(&cfg_s...
from_file
identifier_name
train.py
# encoding: utf-8 from __future__ import unicode_literals, print_function import json import os import io import itertools import numpy as np import random from time import time import torch import pickle import shutil import math import evaluator import net import optimizer as optim from torchtext import data import...
bleu_score, _ = CalculateBleu(model, dev_data, 'Dev Bleu', batch=args.batchsize // 4, beam_size=args.beam_size, ...
print('Validation perplexity: %g' % valid_stats.ppl()) print('Validation accuracy: %g' % valid_stats.accuracy())
random_line_split
train.py
# encoding: utf-8 from __future__ import unicode_literals, print_function import json import os import io import itertools import numpy as np import random from time import time import torch import pickle import shutil import math import evaluator import net import optimizer as optim from torchtext import data import...
print('Train perplexity: %g' % train_stats.ppl()) print('Train accuracy: %g' % train_stats.accuracy()) print('Validation perplexity: %g' % valid_stats.ppl()) print('Validation accuracy: %g' % valid_stats.accuracy()) bleu_score, _ = Calc...
model.eval() in_arrays = utils.seq2seq_pad_concat_convert(dev_batch, -1) loss_test, stat = model(*in_arrays) valid_stats.update(stat)
conditional_block
train.py
# encoding: utf-8 from __future__ import unicode_literals, print_function import json import os import io import itertools import numpy as np import random from time import time import torch import pickle import shutil import math import evaluator import net import optimizer as optim from torchtext import data import...
(new, count, sofar): # return sofar + len(new[0]) + len(new[1]) return sofar + (2 * max(len(new[0]), len(new[1]))) def save_output(hypotheses, vocab, outf): # Save the Hypothesis to output file with io.open(outf, 'w') as fp: for sent in hypotheses: words = [vocab[y] for y in sent] ...
batch_size_func
identifier_name
train.py
# encoding: utf-8 from __future__ import unicode_literals, print_function import json import os import io import itertools import numpy as np import random from time import time import torch import pickle import shutil import math import evaluator import net import optimizer as optim from torchtext import data import...
def main(): best_score = 0 args = get_train_args() print(json.dumps(args.__dict__, indent=4)) # Reading the int indexed text dataset train_data = np.load(os.path.join(args.input, args.data + ".train.npy")) train_data = train_data.tolist() dev_data = np.load(os.path.join(args.input, args....
def __init__(self, model, test_data, key, batch=50, max_length=50, beam_size=1, alpha=0.6, max_sent=None): self.model = model self.test_data = test_data self.key = key self.batch = batch self.device = -1 self.max_length = max_length self.beam_size...
identifier_body
remotenode.go
package node import ( "bytes" "encoding/binary" "errors" "fmt" "net" "sync" "time" "github.com/gogo/protobuf/proto" "github.com/nknorg/nnet/cache" "github.com/nknorg/nnet/log" "github.com/nknorg/nnet/protobuf" "github.com/nknorg/nnet/transport" "github.com/nknorg/nnet/util" ) const ( // Max number of m...
_, found := rn.txMsgCache.Get(msg.MessageId) if found { return nil, nil } err := rn.txMsgCache.Add(msg.MessageId, struct{}{}) if err != nil { return nil, err } select { case rn.txMsgChan <- msg: default: return nil, errors.New("Tx msg chan full, discarding msg") } if hasReply { return rn.LocalNode...
if len(msg.MessageId) == 0 { return nil, errors.New("Message ID is empty") }
random_line_split
remotenode.go
package node import ( "bytes" "encoding/binary" "errors" "fmt" "net" "sync" "time" "github.com/gogo/protobuf/proto" "github.com/nknorg/nnet/cache" "github.com/nknorg/nnet/log" "github.com/nknorg/nnet/protobuf" "github.com/nknorg/nnet/transport" "github.com/nknorg/nnet/util" ) const ( // Max number of m...
// handleMsg starts a loop that handles received msg func (rn *RemoteNode) handleMsg() { var msg *protobuf.Message var remoteMsg *RemoteMessage var msgChan chan *RemoteMessage var err error keepAliveTimeoutTimer := time.NewTimer(keepAliveTimeout) for { if rn.IsStopped() { util.StopTimer(keepAliveTimeoutTi...
{ rn.StopOnce.Do(func() { if err != nil { log.Warningf("Remote node %v stops because of error: %s", rn, err) } else { log.Infof("Remote node %v stops", rn) } err = rn.NotifyStop() if err != nil { log.Warning("Notify remote node stop error:", err) } time.AfterFunc(stopGracePeriod, func() { r...
identifier_body
remotenode.go
package node import ( "bytes" "encoding/binary" "errors" "fmt" "net" "sync" "time" "github.com/gogo/protobuf/proto" "github.com/nknorg/nnet/cache" "github.com/nknorg/nnet/log" "github.com/nknorg/nnet/protobuf" "github.com/nknorg/nnet/transport" "github.com/nknorg/nnet/util" ) const ( // Max number of m...
reply, err := rn.SendMessageSync(msg) if err != nil { return nil, err } replyBody := &protobuf.GetNodeReply{} err = proto.Unmarshal(reply.Msg.Message, replyBody) if err != nil { return nil, err } return replyBody.Node, nil } // NotifyStop sends a Stop message to remote node to notify it that we will //...
{ return nil, err }
conditional_block
remotenode.go
package node import ( "bytes" "encoding/binary" "errors" "fmt" "net" "sync" "time" "github.com/gogo/protobuf/proto" "github.com/nknorg/nnet/cache" "github.com/nknorg/nnet/log" "github.com/nknorg/nnet/protobuf" "github.com/nknorg/nnet/transport" "github.com/nknorg/nnet/util" ) const ( // Max number of m...
(err error) { rn.StopOnce.Do(func() { if err != nil { log.Warningf("Remote node %v stops because of error: %s", rn, err) } else { log.Infof("Remote node %v stops", rn) } err = rn.NotifyStop() if err != nil { log.Warning("Notify remote node stop error:", err) } time.AfterFunc(stopGracePeriod, f...
Stop
identifier_name
neurosky_ecg.py
# -*- coding: utf-8 -*- """ NeuroSky ECG algorithm library This python module serves as a wrapper around the C library, giving efficent access to the library methods used to record and analyze ECG data, obtained with the NeuroSky CardioChip Created on Wed Jan 14 17:37:11 2015 @author: mpesavento """ from ctypes im...
if isreset: print "turning things back on" isreset = False D = nskECG.ecgalgAnalyzeRaw(D) ### the next two lines are examples of how to pop values from the # internal buffer and create a list of filtered ecg values. ...
random_line_split
neurosky_ecg.py
# -*- coding: utf-8 -*- """ NeuroSky ECG algorithm library This python module serves as a wrapper around the C library, giving efficent access to the library methods used to record and analyze ECG data, obtained with the NeuroSky CardioChip Created on Wed Jan 14 17:37:11 2015 @author: mpesavento """ from ctypes im...
def setHRVUpdate(self, numRRI): """ set the number of RR intervals to count between updating the HRV value """ self.HRV_UPDATE = numRRI def _parseData(self, payload): """ given the byte payload from the serial connection, parse the first byte ...
""" stops running thread """ self.connected = False
identifier_body