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 |
|---|---|---|---|---|
gen_mike_input_rf_linux.py | #!/home/uwcc-admin/curw_mike_data_handler/venv/bin/python3
"only she bang, root dir, output dir and filename are different from generic one"
import pymysql
from datetime import datetime, timedelta
import traceback
import json
import os
import sys
import getopt
import pandas as pd
import numpy as np
DATE_TIME_FORMAT =... | (file_name, data):
with open(file_name, 'a+') as f:
f.write('\n'.join(data))
def append_file_to_file(file_name, file_content):
with open(file_name, 'a+') as f:
f.write('\n')
f.write(file_content)
def makedir_if_not_exist_given_filepath(filename):
if not os.path.exists(os.path.dir... | append_to_file | identifier_name |
debug.rs | // Copyright 2016 Mozilla
//
// 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 in writing, software... | ;
let typed_value =
TypedValue::from_sql_value_pair(v, value_type_tag)?.map_ident(borrowed_schema);
let (value, _) = typed_value.to_edn_value_pair();
let tx: i64 = row.get(4)?;
let added: bool = row.get(5)?;
Ok(Datom {
e: Ent... | {
ValueType::Long.value_type_tag()
} | conditional_block |
debug.rs | // Copyright 2016 Mozilla
//
// 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 in writing, software... | <I>(
&mut self,
terms: I,
tempid_set: InternSet<TempId>,
) -> Result<TxReport>
where
I: IntoIterator<Item = TermWithTempIds>,
{
let details = {
// The block scopes the borrow of self.sqlite.
// We're about to write, so go straight ahead and get... | transact_simple_terms | identifier_name |
debug.rs | // Copyright 2016 Mozilla
//
// 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 in writing, software... | params: &[&dyn ToSql],
) -> Result<String> {
let mut stmt: rusqlite::Statement = conn.prepare(sql)?;
let mut tw = TabWriter::new(Vec::new()).padding(2);
writeln!(&mut tw, "{}", sql).unwrap();
for column_name in stmt.column_names() {
write!(&mut tw, "{}\t", column_name).unwrap();
}
... | sql: &str, | random_line_split |
sub_files.py | #!/usr/bin/env python
'''Take a CSV with file metadata, POST new file objects to the ENCODE DCC, upload files to the ENCODE cloud bucket'''
import os, sys, logging, urlparse, requests, csv, StringIO, re, copy, json, subprocess, hashlib, tempfile
logger = logging.getLogger(__name__)
EPILOG = '''Notes:
Examples:
%(... | main() | conditional_block | |
sub_files.py | #!/usr/bin/env python
'''Take a CSV with file metadata, POST new file objects to the ENCODE DCC, upload files to the ENCODE cloud bucket'''
import os, sys, logging, urlparse, requests, csv, StringIO, re, copy, json, subprocess, hashlib, tempfile
logger = logging.getLogger(__name__)
EPILOG = '''Notes:
Examples:
%(... | ():
import argparse
parser = argparse.ArgumentParser(
description=__doc__, epilog=EPILOG,
formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument('infile', help='CSV file metadata to POST', nargs='?', type=argparse.FileType('rU'), default=sys.stdin)
parser.add_argument('--outfile', help='CSV... | get_args | identifier_name |
sub_files.py | #!/usr/bin/env python
'''Take a CSV with file metadata, POST new file objects to the ENCODE DCC, upload files to the ENCODE cloud bucket'''
import os, sys, logging, urlparse, requests, csv, StringIO, re, copy, json, subprocess, hashlib, tempfile
logger = logging.getLogger(__name__)
EPILOG = '''Notes:
Examples:
%(... |
def input_csv(fh):
csv_args = CSV_ARGS
input_fieldnames = csv.reader(fh, **csv_args).next()
return csv.DictReader(fh, fieldnames=input_fieldnames, **csv_args)
def output_csv(fh,fieldnames):
csv_args = CSV_ARGS
additional_fields = ['accession','aws_return']
output_fieldnames = [fn for fn in fieldnames if fn] + ... | test_URI = "ENCBS000AAA"
url = urlparse.urljoin(server,test_URI)
r = requests.get(url, auth=keypair, headers=GET_HEADERS)
try:
r.raise_for_status()
except:
logger.debug('test_encode_keys got response %s' %(r.text))
return False
else:
return True | identifier_body |
sub_files.py | #!/usr/bin/env python
'''Take a CSV with file metadata, POST new file objects to the ENCODE DCC, upload files to the ENCODE cloud bucket'''
import os, sys, logging, urlparse, requests, csv, StringIO, re, copy, json, subprocess, hashlib, tempfile
logger = logging.getLogger(__name__)
EPILOG = '''Notes:
Examples:
%(... | return None
return json_payload
def main():
args = get_args()
server = args.server
keypair = (args.authid, args.authpw)
if not test_encode_keys(server, keypair):
logger.error("Invalid ENCODE server or keys: server=%s authid=%s authpw=%s" %(args.server,args.authid,args.authpw))
sys.exit(1)
try:
subp... | try:
json_payload.update({key:json.loads('"%s"' %(value))})
except:
logger.warning('Could not convert field %s value %s to JSON' %(n,key,value)) | random_line_split |
plugin.go | /*----------------------------------------------------------------
* Copyright (c) ThoughtWorks, Inc.
* Licensed under the Apache License, Version 2.0
* See LICENSE in the project root for license information.
*----------------------------------------------------------------*/
package plugin
import (
"context... | }
func startPluginsForExecution(m *manifest.Manifest) (Handler, []string) {
var warnings []string
handler := &GaugePlugins{}
envProperties := make(map[string]string)
for _, pluginID := range m.Plugins {
pd, err := GetPluginDescriptor(pluginID, "")
if err != nil {
warnings = append(warnings, fmt.Sprintf("Un... | return false | random_line_split |
plugin.go | /*----------------------------------------------------------------
* Copyright (c) ThoughtWorks, Inc.
* Licensed under the Apache License, Version 2.0
* See LICENSE in the project root for license information.
*----------------------------------------------------------------*/
package plugin
import (
"context... |
func StartPlugins(m *manifest.Manifest) Handler {
pluginHandler, warnings := startPluginsForExecution(m)
logger.HandleWarningMessages(true, warnings)
return pluginHandler
}
func PluginsWithoutScope() (infos []pluginInfo.PluginInfo) {
if plugins, err := pluginInfo.GetAllInstalledPluginsWithVersion(); err == nil {... | {
if p.gRPCConn != nil {
return p.invokeService(message)
}
messageID := common.GetUniqueID()
message.MessageId = messageID
messageBytes, err := proto.Marshal(message)
if err != nil {
return err
}
err = conn.Write(p.connection, messageBytes)
if err != nil {
return fmt.Errorf("[Warning] Failed to send mess... | identifier_body |
plugin.go | /*----------------------------------------------------------------
* Copyright (c) ThoughtWorks, Inc.
* Licensed under the Apache License, Version 2.0
* See LICENSE in the project root for license information.
*----------------------------------------------------------------*/
package plugin
import (
"context... |
}
}
return
}
// GetInstallDir returns the install directory of given plugin and a given version.
func GetInstallDir(pluginName, v string) (string, error) {
allPluginsInstallDir, err := common.GetPluginsInstallDir(pluginName)
if err != nil {
return "", err
}
pluginDir := filepath.Join(allPluginsInstallDir, p... | {
infos = append(infos, p)
} | conditional_block |
plugin.go | /*----------------------------------------------------------------
* Copyright (c) ThoughtWorks, Inc.
* Licensed under the Apache License, Version 2.0
* See LICENSE in the project root for license information.
*----------------------------------------------------------------*/
package plugin
import (
"context... | (m *manifest.Manifest) (Handler, []string) {
var warnings []string
handler := &GaugePlugins{}
envProperties := make(map[string]string)
for _, pluginID := range m.Plugins {
pd, err := GetPluginDescriptor(pluginID, "")
if err != nil {
warnings = append(warnings, fmt.Sprintf("Unable to start plugin %s. %s. To ... | startPluginsForExecution | identifier_name |
hkdf.rs | // Copyright 2023 Google 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 in w... | 34007208d5b887185865
"),
},
Test {
// Test Case 2
ikm: &hex!("
000102030405060708090a0b0c0d0e0f
101112131415161718191a1b1c1d1e1f
202122232425262728292a2b2c2d2e2f
... | random_line_split | |
hkdf.rs | // Copyright 2023 Google 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 in w... | <C: CryptoProvider>(#[case] testcase: CryptoProviderTestCase<C>) {}
const MAX_SHA256_LENGTH: usize = 255 * (256 / 8); // =8160
///
pub struct Test<'a> {
ikm: &'a [u8],
salt: &'a [u8],
info: &'a [u8],
okm: &'a [u8],
}
/// data taken from sample code in Readme of crates.io page
pub fn basic_test_hkdf<C... | hkdf_test_cases | identifier_name |
hkdf.rs | // Copyright 2023 Google 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 in w... |
}
}
}
fn run_test<K: Hkdf>(ikm: &[u8], salt: &[u8], info: &[u8], okm: &[u8]) -> Option<&'static str> {
let prk = K::new(Some(salt), ikm);
let mut got_okm = vec![0; okm.len()];
if prk.expand(info, &mut got_okm).is_err() {
return Some("prk expand");
}
if got_okm != okm {
... | {
panic!(
"\n\
Failed test {tc_id}: {desc}\n\
ikm:\t{ikm:?}\n\
salt:\t{salt:?}\n\
info:\t{info:?}\n\
okm:\t{okm:?}\n"
);
} | conditional_block |
msg.rs | use super::{nlmsg_length, nlmsg_header_length};
use std::fmt;
use std::mem::size_of;
use std::slice::from_raw_parts;
use std::io::{self, ErrorKind, Cursor};
use byteorder::{NativeEndian, ReadBytesExt};
#[derive(Clone, Copy, Debug)]
pub enum MsgType {
/// Request
Request,
/// No op
Noop,
/// Error
... | (&mut self) -> &mut NlMsgHeader {
self.flags |= GetFlags::Dump.into();
self
}
}
/*
http://linux.die.net/include/linux/netlink.h
/* Flags values */
#define NLM_F_REQUEST 1 /* It is request message. */
#define NLM_F_MULTI 2 /* Multipart message, terminated by NLMSG_DONE */
#define NL... | dump | identifier_name |
msg.rs | use super::{nlmsg_length, nlmsg_header_length};
use std::fmt;
use std::mem::size_of;
use std::slice::from_raw_parts;
use std::io::{self, ErrorKind, Cursor};
use byteorder::{NativeEndian, ReadBytesExt};
#[derive(Clone, Copy, Debug)]
pub enum MsgType {
/// Request
Request,
/// No op
Noop,
/// Error
... | nl_type: u16,
flags: u16,
seq: u32,
pid: u32,
}
impl fmt::Debug for NlMsgHeader {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
try!(write!(f,
"<NlMsgHeader len={} {:?} flags=[ ",
self.msg_length,
MsgType::from(self.nl_typ... | random_line_split | |
msg.rs | use super::{nlmsg_length, nlmsg_header_length};
use std::fmt;
use std::mem::size_of;
use std::slice::from_raw_parts;
use std::io::{self, ErrorKind, Cursor};
use byteorder::{NativeEndian, ReadBytesExt};
#[derive(Clone, Copy, Debug)]
pub enum MsgType {
/// Request
Request,
/// No op
Noop,
/// Error
... |
pub fn done() -> NlMsgHeader {
NlMsgHeader {
msg_length: nlmsg_header_length() as u32,
nl_type: MsgType::Done.into(),
flags: Flags::Multi.into(),
seq: 0,
pid: 0,
}
}
pub fn error() -> NlMsgHeader {
NlMsgHeader {
... | {
NlMsgHeader {
msg_length: nlmsg_header_length() as u32,
nl_type: MsgType::Request.into(),
flags: Flags::Request.into(),
seq: 0,
pid: 0,
}
} | identifier_body |
model_infer.py | # -*- coding:utf-8 -*-
from collections import namedtuple
import os
import tensorflow as tf
import config
from model.inits import glorot, zeros
import model.layers as layers
from model.aggregators import CrossAggregator
flags = tf.app.flags
FLAGS = flags.FLAGS
os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
os.env... | of supervised GraphSAGE."""
def __init__(self, **kwargs):
# === from model.py ===
allowed_kwargs = {'name', 'logging', 'model_size'}
for kwarg in kwargs.keys():
assert kwarg in allowed_kwargs, 'Invalid keyword argument: ' + kwarg
name = kwargs.get('name')
if not... | identifier_body | |
model_infer.py | # -*- coding:utf-8 -*-
from collections import namedtuple
import os
import tensorflow as tf
import config
from model.inits import glorot, zeros
import model.layers as layers
from model.aggregators import CrossAggregator
flags = tf.app.flags
FLAGS = flags.FLAGS
os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
os.env... |
# saver = tf.train.Saver()/
# 不能硬编码啊
save_path = "./data/model/%s.ckpt" %(self.aggregator_type)
self.saver.restore(sess, save_path)
print("Model restored from file: %s" % save_path)
# ckpt_path = './data/model/%s.ckpt'%(self.aggregator_type)
# meta_path = ckpt_p... | # saver = tf.train.Saver(var_list=self.var_list) | random_line_split |
model_infer.py | # -*- coding:utf-8 -*-
from collections import namedtuple
import os
import tensorflow as tf
import config
from model.inits import glorot, zeros
import model.layers as layers
from model.aggregators import CrossAggregator
flags = tf.app.flags
FLAGS = flags.FLAGS
os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
os.env... | run([self.preds],
feed_dict=feed_dict)
return preds
def close_sess(self):
self.sess.close()
# def save(self, sess=None):
# if not sess:
# raise AttributeError("TensorFlow session not provided.")
# saver = tf.train.Saver(var_list=... | elf, feed_dict):
preds = self.sess. | conditional_block |
model_infer.py | # -*- coding:utf-8 -*-
from collections import namedtuple
import os
import tensorflow as tf
import config
from model.inits import glorot, zeros
import model.layers as layers
from model.aggregators import CrossAggregator
flags = tf.app.flags
FLAGS = flags.FLAGS
os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
os.env... | atch_size=None,
aggregators=None, name='aggregate', concat=False, model_size="small"):
if batch_size is None:
batch_size = self.batch_size
# length: number of layers + 1
# hidden = [tf.nn.embedding_lookup(input_features, node_samples) for node_samples in samples]
... | _sizes, b | identifier_name |
plot2DlimitsAll.py | import os
import sys
import math
import ROOT
#from ROOT import TColor
from array import array
from optparse import OptionParser
from CMS_lumi import CMS_lumi
import plotting_interp as plot
import re
import json
import types
import numpy
def run(opts):
# --- read in options
model = opts.model
which = opts.... | #run
print "Making 2D limit plot for: "+options.model+" "+options.which
if options.do90: print "Using 90CL limits"
if options.dowgt: print "Weighting by 1/xsec"
if options.dosmth: print "Smoothing applied"
run(options)
if __name__=="__main__":
init() | random_line_split | |
plot2DlimitsAll.py | import os
import sys
import math
import ROOT
#from ROOT import TColor
from array import array
from optparse import OptionParser
from CMS_lumi import CMS_lumi
import plotting_interp as plot
import re
import json
import types
import numpy
def run(opts):
# --- read in options
model = opts.model
which = opts.... |
if __name__=="__main__":
init()
| parser = OptionParser("usage: %prog [options]")
parser.add_option("-O",action="store",dest="outdir",type="string",
default="",help="Output directory [default = %default]"),
parser.add_option("-m",action="store",dest="model",type="string",
default="",help="Which model (2HDM or... | identifier_body |
plot2DlimitsAll.py | import os
import sys
import math
import ROOT
#from ROOT import TColor
from array import array
from optparse import OptionParser
from CMS_lumi import CMS_lumi
import plotting_interp as plot
import re
import json
import types
import numpy
def | (opts):
# --- read in options
model = opts.model
which = opts.which
outdir = opts.outdir
do90 = opts.do90
dowgt = opts.dowgt
dosmth = opts.dosmth
smthfnc = opts.smthfnc
#if dosmth: addtxt = '_smth'
# --- read in files
indir = '/eos/cms/store/group/phys_exotica/MonoHgg/MonoH-COMBO-2... | run | identifier_name |
plot2DlimitsAll.py | import os
import sys
import math
import ROOT
#from ROOT import TColor
from array import array
from optparse import OptionParser
from CMS_lumi import CMS_lumi
import plotting_interp as plot
import re
import json
import types
import numpy
def run(opts):
# --- read in options
model = opts.model
which = opts.... |
# --- average plots to make smooth contours
fillAvg(limitPlotObs, A, Z, doFillAvgLow, False, False)
fillAvg(limitPlotObs, A, Z, False, doFillAvgHigh, False)
fillAvg(limitPlotObs, A, Z, False, False, doFillAvgRest)
if doFillAvgAll:
fillAvg(limitPlot, A, Z, doFillAvgLow, False, False)
fillAvg(... | for z in Z:
data = {}
filename = indir+'Zprime'+str(z)+'A'+str(a)+'.json'
if which=='gg' and model=='BARY': # BARY gg ONLY has DM instead of A in filename
filename = indir+'Zprime'+str(z)+'DM'+str(a)+'.json'
scale = 1.
if dowgt: scale = scaleXS(model,z,a)
if os.path.isfile(... | conditional_block |
reidtools.py | from __future__ import absolute_import
from __future__ import print_function
__all__ = ['visualize_ranked_results', 'visactmap']
import numpy as np
import os
import os.path as osp
import shutil
import cv2
from PIL import Image
import torch
from torch.nn import functional as F
from .tools import mkdir_if_missing
GR... | (src, dst, rank, prefix, matched=False):
"""
Args:
src: image path or tuple (for vidreid)
dst: target directory
rank: int, denoting ranked position, starting from 1
prefix: string
matched: bool
"""
if isinstance(src, tuple) or i... | _cp_img_to | identifier_name |
reidtools.py | from __future__ import absolute_import
from __future__ import print_function
__all__ = ['visualize_ranked_results', 'visactmap']
import numpy as np
import os
import os.path as osp
import shutil
import cv2
from PIL import Image
import torch
from torch.nn import functional as F
from .tools import mkdir_if_missing
GR... |
for q_idx in range(num_q):
item = query[q_idx]
qimg_path, qpid, qcamid = item[:3]
# qsegment_path = item[6]
qpid, qcamid = int(qpid), int(qcamid)
num_cols = topk + 1
# grid_img = 255 * np.ones((2*height+GRID_SPACING, num_cols*width+(topk-1)*GRID_SPACING+QUERY_EXTRA_... | """
Args:
src: image path or tuple (for vidreid)
dst: target directory
rank: int, denoting ranked position, starting from 1
prefix: string
matched: bool
"""
if isinstance(src, tuple) or isinstance(src, list):
if prefix == 'g... | identifier_body |
reidtools.py | from __future__ import absolute_import
from __future__ import print_function
__all__ = ['visualize_ranked_results', 'visactmap']
import numpy as np
import os
import os.path as osp
import shutil
import cv2
from PIL import Image
import torch
from torch.nn import functional as F
from .tools import mkdir_if_missing
GR... |
# forward to get convolutional feature maps
try:
# outputs = model(segments, imgs, return_featuremaps=True)
outputs = model(imgs, contours, return_featuremaps=True)
except TypeError:
raise TypeError('forward() got unexpected keyword argument "return_featurem... | imgs = imgs.cuda()
contours = contours.cuda() | conditional_block |
reidtools.py | from __future__ import absolute_import
from __future__ import print_function
__all__ = ['visualize_ranked_results', 'visactmap']
import numpy as np
import os
import os.path as osp
import shutil
import cv2
from PIL import Image
import torch
from torch.nn import functional as F
from .tools import mkdir_if_missing
GR... | outputs = (outputs ** 2).sum(1)
b, h, w = outputs.size()
outputs = outputs.view(b, h * w)
outputs = F.normalize(outputs, p=2, dim=1)
outputs = outputs.view(b, h, w)
if use_gpu:
imgs, outputs = imgs.cpu(), outputs.cpu()
for j in range(outputs.size(0))... | # compute activation maps | random_line_split |
mqtt.go | package mqttModule
import (
"github.com/eclipse/paho.mqtt.golang"
"fmt"
"time"
"crypto/hmac"
"crypto/sha1"
"encoding/hex"
"strconv"
"encoding/json"
"os"
"sync"
interfaces "github.com/gw123/GMQ/core/interfaces"
"github.com/gw123/GMQ/common/common_types"
)
const MaxMsgLen = 100
type MsgIds struct {
Ids [... | .Check(msg.MsgId) {
this.writeLog("warning", "msgId "+msg.MsgId+" Topic"+topic+" 重复消息")
return
}
event := common_types.NewEvent(msg.MsgId ,message.Payload())
this.App.Pub(event)
}
/***
* 订阅get消息
*/
func (this *Iot) SubscribeGet() {
topic := "/" + this.ProductKey + "/" + this.DeviceName + "/get"
this.Subscri... | {
this.writeLog("error", "Topic "+topic+" 消息解密失败 "+err.Error()+" Payload: "+string(message.Payload()))
return
}
if !msgIds | conditional_block |
mqtt.go | package mqttModule
import (
"github.com/eclipse/paho.mqtt.golang"
"fmt"
"time"
"crypto/hmac"
"crypto/sha1"
"encoding/hex"
"strconv"
"encoding/json"
"os"
"sync"
interfaces "github.com/gw123/GMQ/core/interfaces"
"github.com/gw123/GMQ/common/common_types"
)
const MaxMsgLen = 100
type MsgIds struct {
Ids [... | ProductKey string
ClientId string
Username string
Password string
Sign string
Conn mqtt.Client
logOut interfaces.ModuleLogger
App interfaces.App
SubDevices []Device
}
type Params struct {
ProductKey string
DeviceName string
DeviceSecret string
On... | DeviceName string | random_line_split |
mqtt.go | package mqttModule
import (
"github.com/eclipse/paho.mqtt.golang"
"fmt"
"time"
"crypto/hmac"
"crypto/sha1"
"encoding/hex"
"strconv"
"encoding/json"
"os"
"sync"
interfaces "github.com/gw123/GMQ/core/interfaces"
"github.com/gw123/GMQ/common/common_types"
)
const MaxMsgLen = 100
type MsgIds struct {
Ids [... |
this.Publish(topic, 1, false, data)
}
func (this *Iot) SyncUpgradeFile(data common_types.UpdateResponse) {
fileContent := `%s
%s
%s`
fileContent = fmt.Sprintf(fileContent, data.Data.Md5, data.Data.Url, data.Data.Version)
var file *os.File;
var err error;
flag := false
for i := 5; i > 0; i-- {
file, err = os.... | return
} | identifier_name |
mqtt.go | package mqttModule
import (
"github.com/eclipse/paho.mqtt.golang"
"fmt"
"time"
"crypto/hmac"
"crypto/sha1"
"encoding/hex"
"strconv"
"encoding/json"
"os"
"sync"
interfaces "github.com/gw123/GMQ/core/interfaces"
"github.com/gw123/GMQ/common/common_types"
)
const MaxMsgLen = 100
type MsgIds struct {
Ids [... | *Iot) SubscribeSubGet(subProductKey, subDeviceName string) {
topic := "/" + subProductKey + "/" + subDeviceName + "/get"
this.SubscribeAndCheck(topic, 0)
}
/***
* 子设备注册
*/
func (this *Iot) PublishSubRegister(subProductKey, subDeviceName string) {
data := "{'id': '%s', 'version':'1.0','params':[{'deviceName':'%s'... | ctKey + "/" + this.DeviceName + "/get"
this.SubscribeAndCheck(topic, 1)
}
/***
* 子设备
*/
func (this | identifier_body |
MapTilingScheme.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Bentley Systems, Incorporated. All rights reserved.
* See LICENSE.md in the project root for license terms and full copyright notice.
*----------------------------------------------------------------------... |
public tileYToFraction(y: number, level: number): number {
let yFraction = y / this.getNumberOfYTilesAtLevel(level);
if (this._rowZeroAtTop)
yFraction = 1.0 - yFraction;
return yFraction;
}
public tileXToLongitude(x: number, level: number) {
return this.xFractionToLongitude(th... | public tileXToFraction(x: number, level: number): number {
return x / this.getNumberOfXTilesAtLevel(level);
}
| random_line_split |
MapTilingScheme.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Bentley Systems, Incorporated. All rights reserved.
* See LICENSE.md in the project root for license terms and full copyright notice.
*----------------------------------------------------------------------... | () { return this.level >= 0; }
private static _scratchCartographic = new Cartographic();
public static createFromContentId(stringId: string) {
const idParts = stringId.split("_");
if (3 !== idParts.length) {
assert(false, "Invalid quad tree ID");
return new QuadId(-1, -1, -1);
}
... | isValid | identifier_name |
MapTilingScheme.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Bentley Systems, Incorporated. All rights reserved.
* See LICENSE.md in the project root for license terms and full copyright notice.
*----------------------------------------------------------------------... |
public yFractionToLatitude(yFraction: number): number {
const mercatorAngle = Angle.pi2Radians * (yFraction - .5);
return Angle.piOver2Radians - (2.0 * Math.atan(Math.exp(mercatorAngle)));
}
public latitudeToYFraction(latitude: number): number {
const sinLatitude = Math.sin(latitude);
retu... | {
super(numberOfLevelZeroTilesX, numberOfLevelZeroTilesY, rowZeroAtTop);
} | identifier_body |
exceptions.py | # -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making BK-BASE 蓝鲸基础平台 available.
Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved.
BK-BASE 蓝鲸基础平台 is licensed under the MIT License.
License for BK-BASE 蓝鲸基础平台:
---------------------------------------------... | MODULE_CODE = ErrorCode.BKDATA_AUTH
class AuthCode:
# 错误码映射表,目前以三元组定义,包含了错误码、描述和处理方式(可选)
SDK_PERMISSION_DENIED_ERR = ("001", _("资源访问权限不足"))
SDK_PARAM_MISS_ERR = ("002", _("认证参数缺失"), _("请查看API请求文档"))
SDK_AUTHENTICATION_ERR = ("003", _("认证不通过,请提供合法的 BKData 认证信息"), _("请查看API请求文档"))
SDK_INVALID_S... | class AuthAPIError(BaseAPIError): | random_line_split |
exceptions.py | # -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making BK-BASE 蓝鲸基础平台 available.
Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved.
BK-BASE 蓝鲸基础平台 is licensed under the MIT License.
License for BK-BASE 蓝鲸基础平台:
---------------------------------------------... | = AuthCode.REDIS_CONNECT_ERR[0]
MESSAGE = AuthCode.REDIS_CONNECT_ERR[1]
class ObjectSerilizerNoPKErr(AuthAPIError):
CODE = AuthCode.OBJECT_SERIALIZER_NO_PK_ERR[0]
MESSAGE = AuthCode.OBJECT_SERIALIZER_NO_PK_ERR[1]
class UpdateRoleErr(AuthAPIError):
CODE = AuthCode.UPDATE_ROLE_ERR[0]
MESSAGE = Au... | Error):
CODE | identifier_name |
exceptions.py | # -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making BK-BASE 蓝鲸基础平台 available.
Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved.
BK-BASE 蓝鲸基础平台 is licensed under the MIT License.
License for BK-BASE 蓝鲸基础平台:
---------------------------------------------... | MESSAGE = AuthCode.DATA_SCOPE_VALID_ERR[1]
class AppNotMatchErr(AuthAPIError):
CODE = AuthCode.APP_NOT_MATCH_ERR[0]
MESSAGE = AuthCode.APP_NOT_MATCH_ERR[1]
class PermissionObjectDoseNotExistError(AuthAPIError):
CODE = AuthCode.PERMISSION_OBJECT_DOSE_NOT_EXIST_ERR[0]
MESSAGE = AuthCode.PERMISSION_OB... | ]
class DataScopeValidErr(AuthAPIError):
CODE = AuthCode.DATA_SCOPE_VALID_ERR[0]
| identifier_body |
main.rs | // required for pest
#![recursion_limit="128"]
mod config;
mod keys;
mod metadata;
mod remote;
mod util;
mod history;
mod chunking;
extern crate ring;
extern crate untrusted;
#[macro_use]
extern crate pest;
#[macro_use]
extern crate clap;
extern crate url;
use url::Url;
use std::io::Write;
use std::error::Error;
us... | (args: &clap::ArgMatches, opts: &GlobalOptions) {
unimplemented!()
}
fn do_clean(args: &clap::ArgMatches, opts: &GlobalOptions) {
unimplemented!()
}
fn do_snap(args: &clap::ArgMatches, opts: &GlobalOptions) {
let remote = args.value_of("remote").unwrap().to_owned();
let snap_paths: Vec<&str> = args.va... | do_stat | identifier_name |
main.rs | // required for pest
#![recursion_limit="128"]
mod config;
mod keys;
mod metadata;
mod remote;
mod util;
mod history;
mod chunking;
extern crate ring;
extern crate untrusted;
#[macro_use]
extern crate pest;
#[macro_use]
extern crate clap;
extern crate url;
use url::Url;
use std::io::Write;
use std::error::Error;
us... | ("restore", Some(m)) => do_restore(m, &global_flags),
(_, _) => panic!("No subcommand handler found!")
}
} | random_line_split | |
main.rs | // required for pest
#![recursion_limit="128"]
mod config;
mod keys;
mod metadata;
mod remote;
mod util;
mod history;
mod chunking;
extern crate ring;
extern crate untrusted;
#[macro_use]
extern crate pest;
#[macro_use]
extern crate clap;
extern crate url;
use url::Url;
use std::io::Write;
use std::error::Error;
us... | {
let opt_matches = clap_app!(bkp =>
(version: "0.1")
(author: "Noah Zentzis <nzentzis@gmail.com>")
(about: "Automated system backup utility")
(@arg CONFIG: -c --config +takes_value "Specifies a config file to use")
(@arg DATADIR: -D --data-dir +takes_value "Specify the local... | identifier_body | |
show_solution.py | #!/usr/bin/env python3
import sys, os
import random
import numpy as np
import matplotlib as mpl
if os.environ.get('DISPLAY','') == '':
print('no display found. Using non-interactive Agg backend')
mpl.use('Agg')
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
import sha... |
alpha = 0.0
concave_hull = figure_utils.alpha_shape(points, alpha=alpha)
color = mycmapScalarMap.to_rgba(set_rew)
figure_utils.plot_polygon(concave_hull.buffer(25), fc=color)
else:
for set_idx in reversed(sorted(sets.keys())):
points = []
s... | node1 = nodes_w_rewards[nidx1, :]
points.append([node1[0], node1[1]])
for nidx2 in sets[set_idx]:
if(nidx1 != nidx2):
node2 = nodes_w_rewards[nidx2, :]
# plt.plot([node1[0], node2[0] ], [node1[1], node2[1] ], '-k', lw=0.2) | conditional_block |
show_solution.py | #!/usr/bin/env python3
import sys, os
import random
import numpy as np
import matplotlib as mpl
if os.environ.get('DISPLAY','') == '':
print('no display found. Using non-interactive Agg backend')
mpl.use('Agg')
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
import sha... |
elif "datasets/dop_sop_dataset/" in PROBLEM_FILE:
print("showing DOP")
problem_type = ProblemType.DOP
SAVE_TO_FIGURE = "solution_dop.png"
elif "datasets/opn_sop_dataset/" in PROBLEM_FILE:
print("showing OPN")
problem_type = ProblemType.OPN
SAVE_TO_FIGURE = "solution_opn.png"
else:
err... | print("showing SOP")
problem_type = ProblemType.SOP
SAVE_TO_FIGURE = "solution_sop.png" | random_line_split |
pager.py | #!/usr/bin/python2.7
# Copyright 2012 Room77, Inc.
# Author: Uygar Oztekin
import os
import sys
import re
import argparse
import datetime
import json
import string
class Pager:
"""
Cronable pager script for alerts. Monitors emails send to specified address.
For each email with a subject that matches the crite... | pager.monitor_pass = args.monitor_pass
pager.monitor_phone = args.monitor_phone
if args.dry_run: pager.dry_run = 1
if args.info: return pager.Info()
if args.mail_info: return pager.MailInfo(args.sender, args.receiver)
if args.call != None: return pager.SendAlert(args.msg, args.call)
return pager.Run()
... | pager.Init()
pager.offset_days = args.offset_days
pager.monitor_email = args.monitor_email | random_line_split |
pager.py | #!/usr/bin/python2.7
# Copyright 2012 Room77, Inc.
# Author: Uygar Oztekin
import os
import sys
import re
import argparse
import datetime
import json
import string
class Pager:
"""
Cronable pager script for alerts. Monitors emails send to specified address.
For each email with a subject that matches the crite... |
def Run(self):
if not os.path.exists(self.status_dir):
os.makedirs(self.status_dir)
self._ReadStatusFile()
return self._FetchMails()
def main():
# Fill in the default values relevant for you to avoid adding the flags for each run.
parser = argparse.ArgumentParser(description="Handle pager ro... | import code
from googlevoice import Voice
voice = Voice()
voice.login(self.monitor_email, self.monitor_pass)
voice.send_sms(phone, msg) # Send an SMS.
voice.call(phone, self.monitor_phone, 3) # Call the person as well.
self._sent_one = 1 | conditional_block |
pager.py | #!/usr/bin/python2.7
# Copyright 2012 Room77, Inc.
# Author: Uygar Oztekin
import os
import sys
import re
import argparse
import datetime
import json
import string
class Pager:
"""
Cronable pager script for alerts. Monitors emails send to specified address.
For each email with a subject that matches the crite... |
def _SendAlertToPhone(self, phone, msg):
if not self._sent_one:
import code
from googlevoice import Voice
voice = Voice()
voice.login(self.monitor_email, self.monitor_pass)
voice.send_sms(phone, msg) # Send an SMS.
voice.call(phone, self.monitor_phone, 3) # Ca... | days = (datetime.datetime.today() - datetime.datetime.utcfromtimestamp(0)).days + 3 + offset_days
return days // 7 % len(self._active_list) | identifier_body |
pager.py | #!/usr/bin/python2.7
# Copyright 2012 Room77, Inc.
# Author: Uygar Oztekin
import os
import sys
import re
import argparse
import datetime
import json
import string
class Pager:
"""
Cronable pager script for alerts. Monitors emails send to specified address.
For each email with a subject that matches the crite... | (self):
if not os.path.exists(self.status_dir):
os.makedirs(self.status_dir)
self._ReadStatusFile()
return self._FetchMails()
def main():
# Fill in the default values relevant for you to avoid adding the flags for each run.
parser = argparse.ArgumentParser(description="Handle pager rotations and... | Run | identifier_name |
main.go | // Copyright 2021 Optakt Labs OÜ
//
// 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
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to... | ) {
os.Exit(run())
}
func run() int {
// Signal catching for clean shutdown.
sig := make(chan os.Signal, 1)
signal.Notify(sig, os.Interrupt)
// Command line parameter initialization.
var (
flagCheckpoint string
flagData string
flagForce bool
flagIndex string
... | ain( | identifier_name |
main.go | // Copyright 2021 Optakt Labs OÜ
//
// 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
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to... | storage := storage.New(codec)
// Check if index already exists.
_, err = index.NewReader(db, storage).First()
indexExists := err == nil
if indexExists && !flagForce {
log.Error().Err(err).Msg("index already exists, manually delete it or use (-f, --force) to overwrite it")
return failure
}
// The loader com... |
size := rcrowley.NewSize("store")
mout.Register(size)
codec = metrics.NewCodec(codec, size)
}
| conditional_block |
main.go | // Copyright 2021 Optakt Labs OÜ
//
// 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
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to... |
func run() int {
// Signal catching for clean shutdown.
sig := make(chan os.Signal, 1)
signal.Notify(sig, os.Interrupt)
// Command line parameter initialization.
var (
flagCheckpoint string
flagData string
flagForce bool
flagIndex string
flagIndexAll ... |
os.Exit(run())
}
| identifier_body |
main.go | // Copyright 2021 Optakt Labs OÜ
//
// 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
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to... | // goroutine, so they can run concurrently. Afterwards, we wait for an
// interrupt signal in order to proceed with the next section.
done := make(chan struct{})
failed := make(chan struct{})
go func() {
start := time.Now()
log.Info().Time("start", start).Msg("Flow DPS Indexer starting")
err := fsm.Run()
i... | )
// This section launches the main executing components in their own | random_line_split |
fixtures.go | // Copyright 2019 Antrea 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 to ... | (tb testing.TB, data *TestData) {
exportLogs(tb, data, "beforeTeardown", true)
if empty, _ := IsDirEmpty(data.logsDirForTestCase); empty {
_ = os.Remove(data.logsDirForTestCase)
}
tb.Logf("Deleting '%s' K8s Namespace", testNamespace)
if err := data.deleteTestNamespace(defaultTimeout); err != nil {
tb.Logf("Err... | teardownTest | identifier_name |
fixtures.go | // Copyright 2019 Antrea 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 to ... | func deletePodWrapper(tb testing.TB, data *TestData, namespace, name string) {
tb.Logf("Deleting Pod '%s'", name)
if err := data.deletePod(namespace, name); err != nil {
tb.Logf("Error when deleting Pod: %v", err)
}
}
// createTestBusyboxPods creates the desired number of busybox Pods and wait for their IP addres... | random_line_split | |
fixtures.go | // Copyright 2019 Antrea 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 to ... |
tb.Logf("Checking CoreDNS deployment")
if err = testData.checkCoreDNSPods(defaultTimeout); err != nil {
return testData, v4Enabled, v6Enabled, err
}
return testData, v4Enabled, v6Enabled, nil
}
func exportLogs(tb testing.TB, data *TestData, logsSubDir string, writeNodeLogs bool) {
if tb.Skipped() {
return
... | {
return testData, v4Enabled, v6Enabled, err
} | conditional_block |
fixtures.go | // Copyright 2019 Antrea 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 to ... |
func skipIfNotIPv6Cluster(tb testing.TB) {
if clusterInfo.podV6NetworkCIDR == "" {
tb.Skipf("Skipping test as it requires IPv6 addresses but the IPv6 network CIDR is not set")
}
}
func skipIfMissingKernelModule(tb testing.TB, nodeName string, requiredModules []string) {
for _, module := range requiredModules {
... | {
if clusterInfo.podV6NetworkCIDR != "" {
tb.Skipf("Skipping test as it is not supported in IPv6 cluster")
}
} | identifier_body |
lineChart.component.ts | import 'style-loader!./lineChart.scss';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { CoreService, CoreEvent } from 'app/core/services/core.service';
import { ViewComponent } from 'app/core/components/view/view.component';
import {Component, Input, OnInit, AfterViewInit, OnDestroy} from '@angular/co... |
// This is the time portion of the API call.
this._lineChartService.getData(this, this.dataList, rrdOptions);
}
public convertTo(value, conversion){
let result;
switch(conversion){
case 'bytesToGigabytes':
result = value / 1073741824;
break;
case 'percentFloatToInteger':
... | {
rrdOptions.end = Math.floor(rrdOptions.end / 1000);
} | conditional_block |
lineChart.component.ts | import 'style-loader!./lineChart.scss';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { CoreService, CoreEvent } from 'app/core/services/core.service';
import { ViewComponent } from 'app/core/components/view/view.component';
import {Component, Input, OnInit, AfterViewInit, OnDestroy} from '@angular/co... | (){
let conf = {
interaction: {
enabled:this.interactive
},
bindto: '#' + this.controlUid,
/*color: {
pattern: this.colorPattern
},*/
data: {
columns: this.columns,
//colors: this.createColorObject(),
x: 'xValues',
//xFormat: '%H:%M'... | makeConfig | identifier_name |
lineChart.component.ts | import 'style-loader!./lineChart.scss';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { CoreService, CoreEvent } from 'app/core/services/core.service';
import { ViewComponent } from 'app/core/components/view/view.component';
import {Component, Input, OnInit, AfterViewInit, OnDestroy} from '@angular/co... |
// LifeCycle Hooks
ngOnInit() {
this.core.register({ observerClass:this, eventName:"ThemeData" }).subscribe((evt:CoreEvent)=>{
this.colorPattern = this.processThemeColors(evt.data);
if(this.linechartData){
this.render();
//this.chart.data.colors(this.createColorObject())
... | {
return 1
} | identifier_body |
lineChart.component.ts | import 'style-loader!./lineChart.scss';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { CoreService, CoreEvent } from 'app/core/services/core.service';
import { ViewComponent } from 'app/core/components/view/view.component';
import {Component, Input, OnInit, AfterViewInit, OnDestroy} from '@angular/co... | dataSeriesArray = newArray;
}
this.data.series.push(dataSeriesArray);
});
const columns: any[][] = [];
let legendLabels: string[] = [];
// xColumn
const xValues: any[] = [];
xValues.push('xValues');
this.data.labels.forEach((label) => {
xValues.push(label);
... | }); | random_line_split |
micro_updater.py | from github import Github, Repository, GitRelease, ContentFile
from loguru import logger
import configparser
import sys
import os
import wget
import hashlib
import json
from paho.mqtt.client import Client as MQTTClient, MQTTMessageInfo
from paho.mqtt.subscribe import simple as subscribe
from threading import Thread
fro... | with open(file.path, 'r') as file_opened:
content = file_opened.read()
size = os.stat(file.path)
hasher = hashlib.sha1(f'blob {len(content)}\x00{content}'.encode("utf-8"))
hash = hasher.hexdigest()
if hash == file.sha:
logger.debug('File integrity OK')
return True
else:
logger.... | logger.debug(f'Verifying {file.name} integrity...')
if self.trusted:
logger.warning(f'Skipping {file.name} integrity check')
return True
try: | random_line_split |
micro_updater.py | from github import Github, Repository, GitRelease, ContentFile
from loguru import logger
import configparser
import sys
import os
import wget
import hashlib
import json
from paho.mqtt.client import Client as MQTTClient, MQTTMessageInfo
from paho.mqtt.subscribe import simple as subscribe
from threading import Thread
fro... |
try:
if os.path.isfile(DEFAULT_COMPLETE_CONFIG_PATH):
logger.error("Can't create configuration sample, please provide a custom configuration file")
exit(1)
with open(DEFAULT_COMPLETE_CONFIG_PATH, 'w') as file:
self.config.write(file)
except Exception as e:
logger.critical(f"Can't creat... | self.config[section] = {}
for key in CONFIGURATION_LAYOUT[section]:
self.config[section][key] = f'<{key}>' | conditional_block |
micro_updater.py | from github import Github, Repository, GitRelease, ContentFile
from loguru import logger
import configparser
import sys
import os
import wget
import hashlib
import json
from paho.mqtt.client import Client as MQTTClient, MQTTMessageInfo
from paho.mqtt.subscribe import simple as subscribe
from threading import Thread
fro... |
def github_init(self):
logger.debug('Initializing github attributes...')
github = Github(self.config['github']['token'])
self.github_client = github.get_user()
self.repo_obj = self.github_client.get_repo(self.config['github']['repo'])
self.load_cached_release()
logger.debug('Github attributes initializ... | logger.debug(f'Reading configuration file "{config_path}"')
try:
self.config.read(config_path)
except Exception as e:
logger.critical(f'Error reading configuration file; {e}')
logger.critical('Closing...')
exit(1)
try:
sections = self.config.sections()
for section in CONFIGURATION_LAYOUT:
as... | identifier_body |
micro_updater.py | from github import Github, Repository, GitRelease, ContentFile
from loguru import logger
import configparser
import sys
import os
import wget
import hashlib
import json
from paho.mqtt.client import Client as MQTTClient, MQTTMessageInfo
from paho.mqtt.subscribe import simple as subscribe
from threading import Thread
fro... | (self, file: RepoFile, download_path) -> bool:
logger.debug(f'Downloading {file.name} into {download_path}...')
try:
file_path = os.path.join(download_path, file.name)
wget.download(file.download_link, out=file_path)
file.path = file_path
return True
except Exception as e:
logger.error(f"Can't down... | _download_file | identifier_name |
WaterHeaterClass.py | #Definition of Water Heater Class and Fuel Type
from scipy.stats import weibull_min
from Inputs_Energy import *
from RefrigerantCalc import Refrigerant
#a= 0.5 #shape
#b = 10 # scale
#Years of MeanLifeTIme, when all WHs are absolutely killed
#y = range(0,21)
#r= weibull_min.cdf(y,3,loc=0,scale = b)
#p... |
def payback(self, WHx,yr):
X = WHx.IC - self.IC
Y = (self.OM[0] + self.AnnualEngCost(yr)) - (WHx.OM[0] + WHx.AnnualEngCost(yr))
#print "#", X, Y, "#"
if self == WHx:
return 0
elif (X>=0 and Y<=0):
return max(self.lt, W... | return ( (self.NPVEmissions(yr)*UnitCarbonPrice + self.calcNPV(yr) ) /self.lt) | identifier_body |
WaterHeaterClass.py | #Definition of Water Heater Class and Fuel Type
from scipy.stats import weibull_min
from Inputs_Energy import *
from RefrigerantCalc import Refrigerant
#a= 0.5 #shape
#b = 10 # scale
#Years of MeanLifeTIme, when all WHs are absolutely killed
#y = range(0,21)
#r= weibull_min.cdf(y,3,loc=0,scale = b)
#p... |
elif yr >= self.vintage + self.lt + UltimYr:
return self.OrigNum
else:
return 0
def numAlive(self,yr):
return (self.OrigNum - self.deadsofar(yr))
def age(self, yr):
return (yr - self.vintage)
def annualreplacemen... | return self.weib()[yr-self.vintage] | conditional_block |
WaterHeaterClass.py | #Definition of Water Heater Class and Fuel Type
from scipy.stats import weibull_min
from Inputs_Energy import *
from RefrigerantCalc import Refrigerant
#a= 0.5 #shape
#b = 10 # scale
#Years of MeanLifeTIme, when all WHs are absolutely killed
#y = range(0,21)
#r= weibull_min.cdf(y,3,loc=0,scale = b)
#p... | def weib(self):
x = range(0, self.lt+UltimYr+1)
w = weibull_min.cdf(x,3,loc=2.5,scale = self.lt) * self.OrigNum
#print w
return(w)
def deadsofar(self, yr):
if yr > self.vintage and yr < self.vintage+ self.lt + UltimYr:
# print yr, self.vin... | def CCBreakEven(self, WH2, yr): #breakeven carbon cost
breakeven = (self.calcNPV(yr)/self.lt- WH2.calcNPV(yr)/WH2.lt)/( WH2.NPVEmissions(yr)/WH2.lt - self.NPVEmissions(yr)/self.lt )
return breakeven
| random_line_split |
WaterHeaterClass.py | #Definition of Water Heater Class and Fuel Type
from scipy.stats import weibull_min
from Inputs_Energy import *
from RefrigerantCalc import Refrigerant
#a= 0.5 #shape
#b = 10 # scale
#Years of MeanLifeTIme, when all WHs are absolutely killed
#y = range(0,21)
#r= weibull_min.cdf(y,3,loc=0,scale = b)
#p... | (self,yr): #in tons of CO2 eq
result = {}
avgleak = 0
if (self.hasRefrigerant == True):
result = self.RefLeaks(yr)
#for i in range(vint, vint+ self.lt):
# avgleak = avgleak + result[i]/(1+CCDiscRate)**(i-vint+1)
avgleak = sum(result.valu... | AvgRefLeaks | identifier_name |
indexed_set.rs | // Copyright 2012-2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | (domain_size: usize) -> Self {
HybridIdxSet::Sparse(SparseIdxSet::new(), domain_size)
}
pub fn clear(&mut self) {
let domain_size = match *self {
HybridIdxSet::Sparse(_, size) => size,
HybridIdxSet::Dense(_, size) => size,
};
*self = HybridIdxSet::new_emp... | new_empty | identifier_name |
indexed_set.rs | // Copyright 2012-2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... |
#[test]
fn test_new_filled() {
for i in 0..128 {
let idx_buf = IdxSet::new_filled(i);
let elems: Vec<usize> = idx_buf.iter().collect();
let expected: Vec<usize> = (0..i).collect();
assert_eq!(elems, expected);
}
} | assert_eq!(elems, expected);
}
}
} | random_line_split |
source_contributions.rs | extern crate clap;
extern crate csv;
extern crate reqwest;
extern crate serde;
extern crate failure;
#[macro_use]
extern crate failure_derive;
use clap::{App, Arg};
use csv::StringRecord;
use reqwest::{Client, Url};
use serde::de::DeserializeOwned;
use serde::Deserialize;
use std::{thread, time};
use std::collection... | (repo_url: &str) -> Result<(&str, &str), AppError> {
match repo_url.split('/').collect::<Vec<&str>>().as_slice() {
[_, "", "github.com", owner, repo] => Ok((owner, repo)),
_ => Err(AppError::MetadataExtractionFailed {
repo_url: repo_url.to_string(),
}),
}
}
// Extract the co... | extract_github_owner_and_repo | identifier_name |
source_contributions.rs | extern crate clap;
extern crate csv;
extern crate reqwest;
extern crate serde;
extern crate failure;
#[macro_use]
extern crate failure_derive;
use clap::{App, Arg};
use csv::StringRecord;
use reqwest::{Client, Url};
use serde::de::DeserializeOwned;
use serde::Deserialize;
use std::{thread, time};
use std::collection... |
fn deserialise_project(sr: &StringRecord) -> Option<Project> {
if let Some(Ok(pid)) = sr.get(0).map(|s: &str| s.parse::<u32>()) {
let platform = sr.get(1);
let project_name = sr.get(2);
let repository_url = sr.get(9);
let repository_fork = sr.get(24).and_then(|s: &str| match s {
... | {
let retries_left = retries.retries_num;
if retries_left == 0 {
Err(AppError::NoRetriesLeft)
} else {
let bearer = format!("Bearer {}", token);
match http_method {
HttpMethod::Get => {
let url: Url = format!("{}{}", GITHUB_BASE_URL, url_path)
... | identifier_body |
source_contributions.rs | extern crate clap;
extern crate csv;
extern crate reqwest;
extern crate serde;
extern crate failure;
#[macro_use]
extern crate failure_derive;
use clap::{App, Arg};
use csv::StringRecord;
use reqwest::{Client, Url};
use serde::de::DeserializeOwned;
use serde::Deserialize;
use std::{thread, time};
use std::collection... | match repo_url.split('/').collect::<Vec<&str>>().as_slice() {
[_, "", "github.com", owner, repo] => Ok((owner, repo)),
_ => Err(AppError::MetadataExtractionFailed {
repo_url: repo_url.to_string(),
}),
}
}
// Extract the contribution relative to this project. For now only Git... | fn extract_github_owner_and_repo(repo_url: &str) -> Result<(&str, &str), AppError> { | random_line_split |
shanten_improve.go | package util
import (
"fmt"
"sort"
"math"
"github.com/EndlessCheng/mahjong-helper/util/model"
)
// map[改良牌]进张(选择进张数最大的)
type Improves map[int]Waits
// 1/4/7/10/13 张手牌的分析结果
type WaitsWithImproves13 struct {
// 原手牌
Tiles34 []int
// 剩余牌
LeftTiles34 []int
// 是否已鸣牌
IsNaki bool
// 向听数
Shanten int
// 进张
/... | heck34[idx] = true
// }
// }
//}
//for i := 27; i < 34; i++ {
// if tiles34[i] > 0 {
// needCheck34[i] = true
// }
//}
waits = Waits{}
for i := 0; i < 34; i++ {
//if !needCheck34[i] {
// continue
//}
if tiles34[i] == 4 {
// 无法摸到这张牌
continue
}
// 摸牌
tiles34[i]++
if newShanten := Calc... | dx-2] = true
// needCheck34[idx-1] = true
// needC | conditional_block |
shanten_improve.go | package util
import (
"fmt"
"sort"
"math"
"github.com/EndlessCheng/mahjong-helper/util/model"
)
// map[改良牌]进张(选择进张数最大的)
type Improves map[int]Waits
// 1/4/7/10/13 张手牌的分析结果
type WaitsWithImproves13 struct {
// 原手牌
Tiles34 []int
// 剩余牌
LeftTiles34 []int
// 是否已鸣牌
IsNaki bool
// 向听数
Shanten int
// 进张
/... |
// map[进张牌]向听前进后的进张数(这里让向听前进的切牌选择的是使「向听前进后的进张数最大」的切牌)
NextShantenWaitsCountMap map[int]int
// 向听前进后的进张数的加权均值
AvgNextShantenWaitsCount float64
// 综合了进张与向听前进后进张的评分
MixedWaitsScore float64
// 改良:摸到这张牌虽不能让向听数前进,但可以让进张变多
// len(Improves) 即为改良的牌的种数
Improves Improves
// 改良情况数,这里计算的是有多少种使进张增加的切牌方式
ImproveWayCou... | // 若某个进张牌 4 枚都可见,则该进张的 value 值为 0
Waits Waits
// TODO: 鸣牌进张:他家打出这张牌,可以鸣牌,且能让向听数前进
//MeldWaits Waits | random_line_split |
shanten_improve.go | package util
import (
"fmt"
"sort"
"math"
"github.com/EndlessCheng/mahjong-helper/util/model"
)
// map[改良牌]进张(选择进张数最大的)
type Improves map[int]Waits
// 1/4/7/10/13 张手牌的分析结果
type WaitsWithImproves13 struct {
// 原手牌
Tiles34 []int
// 剩余牌
LeftTiles34 []int
// 是否已鸣牌
IsNaki bool
// 向听数
Shanten int
// 进张
/... | needCheck34[idx] = true
// needCheck34[idx+1] = true
// } else {
// needCheck34[idx-2] = true
// needCheck34[idx-1] = true
// needCheck34[idx] = true
// }
// }
//}
//for i := 27; i < 34; i++ {
// if tiles34[i] > 0 {
// needCheck34[i] = true
// }
//}
waits = Waits{}
for i := 0; i < 34; i++ {
... | heck34[idx-1] = true
// | identifier_name |
shanten_improve.go | package util
import (
"fmt"
"sort"
"math"
"github.com/EndlessCheng/mahjong-helper/util/model"
)
// map[改良牌]进张(选择进张数最大的)
type Improves map[int]Waits
// 1/4/7/10/13 张手牌的分析结果
type WaitsWithImproves13 struct {
// 原手牌
Tiles34 []int
// 剩余牌
LeftTiles34 []int
// 是否已鸣牌
IsNaki bool
// 向听数
Shanten int
// 进张
/... | ilterOutDiscard(cannotDiscardTile)
}
}
// 添加副露信息,用于输出
_waitsWithImproves.addOpenTile(c.SelfTiles)
_incShantenResults.addOpenTile(c.SelfTiles)
// 整理副露结果
if _shanten == minShanten {
waitsWithImproves = append(waitsWithImproves, _waitsWithImproves...)
incShantenResults = append(incShantenResults, _i... | identifier_body | |
pod_driver.go | /*
Copyright 2021 Juicedata Inc
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
d... |
// checkAnnotations
// 1. check refs in mount pod annotation
// 2. delete ref that target pod is not found
func (p *PodDriver) checkAnnotations(ctx context.Context, pod *corev1.Pod) error {
// check refs in mount pod, the corresponding pod exists or not
lock := config.GetPodLock(pod.Name)
lock.Lock()
defer lock.U... | {
if pod == nil {
return podError
}
if pod.DeletionTimestamp != nil {
return podDeleted
}
if util.IsPodError(pod) {
return podError
}
if util.IsPodReady(pod) {
return podReady
}
return podPending
} | identifier_body |
pod_driver.go | /*
Copyright 2021 Juicedata Inc
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
d... | return nil
}
// recoverTarget recovers target path
func (p *PodDriver) recoverTarget(podName, sourcePath string, ti *targetItem, mi *mountItem) {
switch ti.status {
case targetStatusNotExist:
klog.Errorf("pod %s target %s not exists, item count:%d", podName, ti.target, ti.count)
if ti.count > 0 {
// target e... | }
}
}
| random_line_split |
pod_driver.go | /*
Copyright 2021 Juicedata Inc
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
d... | (client *k8sclient.K8sClient, mounter mount.SafeFormatAndMount) *PodDriver {
driver := &PodDriver{
Client: client,
handlers: map[podStatus]podHandler{},
SafeFormatAndMount: mounter,
}
driver.handlers[podReady] = driver.podReadyHandler
driver.handlers[podError] = driver.podErrorHandler
d... | newPodDriver | identifier_name |
pod_driver.go | /*
Copyright 2021 Juicedata Inc
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
d... |
}
return nil
}
// recoverTarget recovers target path
func (p *PodDriver) recoverTarget(podName, sourcePath string, ti *targetItem, mi *mountItem) {
switch ti.status {
case targetStatusNotExist:
klog.Errorf("pod %s target %s not exists, item count:%d", podName, ti.target, ti.count)
if ti.count > 0 {
// tar... | {
mi := p.mit.resolveTarget(target)
if mi == nil {
klog.Errorf("pod %s target %s resolve fail", pod.Name, target)
continue
}
p.recoverTarget(pod.Name, mntPath, mi.baseTarget, mi)
for _, ti := range mi.subPathTarget {
p.recoverTarget(pod.Name, mntPath, ti, mi)
}
} | conditional_block |
kitti_sem_data_loader.py | import logging
import os, sys
import numpy as np
import logging
import pykitti
sys.path.insert(0, os.path.dirname(os.path.realpath(__file__))+"/../")
import third_party.parseTrackletXML as parseTrackletXML
import kitti_detection_helper
import utils
import path_def
import se3
LOGGER = logging.getLogger(__name__)... |
def generate_object_eval_path(self):
self.pr_table_dir = self.cache_path + self.kitti_dir + '/evaluation/'
if not os.path.exists(self.pr_table_dir):
os.makedirs(self.pr_table_dir)
def load_tracklet(self):
"""
# load tracklet
# to show 3D bounding box
... | self.gt_bbox_results_path = self.cache_path + self.kitti_dir + '/gt_bboxes_results/'
if not os.path.exists(self.gt_bbox_results_path):
os.makedirs(self.gt_bbox_results_path) | identifier_body |
kitti_sem_data_loader.py | import logging
import os, sys
import numpy as np
import logging
import pykitti
sys.path.insert(0, os.path.dirname(os.path.realpath(__file__))+"/../")
import third_party.parseTrackletXML as parseTrackletXML
import kitti_detection_helper
import utils
import path_def
import se3
LOGGER = logging.getLogger(__name__)... | (self):
self.pr_table_dir = self.cache_path + self.kitti_dir + '/evaluation/'
if not os.path.exists(self.pr_table_dir):
os.makedirs(self.pr_table_dir)
def load_tracklet(self):
"""
# load tracklet
# to show 3D bounding box
# need to use the groundtruth t... | generate_object_eval_path | identifier_name |
kitti_sem_data_loader.py | import logging
import os, sys
import numpy as np
import logging
import pykitti
sys.path.insert(0, os.path.dirname(os.path.realpath(__file__))+"/../")
import third_party.parseTrackletXML as parseTrackletXML
import kitti_detection_helper
import utils
import path_def
import se3
LOGGER = logging.getLogger(__name__)... | # first_pose_inv = src.se3.inversePose(first_pose)
# do not correct the orientation
# first_pose_inv[:3, :3] = np.eye(3)
# do not set first pose to identity
first_pose_inv = np.eye(4)
for o in self.dataset.oxts:
normalized_pose_original = first_pose_inv @ o... |
# set first pose to identity
# first_pose = self.dataset.oxts[0].T_w_imu | random_line_split |
kitti_sem_data_loader.py | import logging
import os, sys
import numpy as np
import logging
import pykitti
sys.path.insert(0, os.path.dirname(os.path.realpath(__file__))+"/../")
import third_party.parseTrackletXML as parseTrackletXML
import kitti_detection_helper
import utils
import path_def
import se3
LOGGER = logging.getLogger(__name__)... |
def generate_object_eval_path(self):
self.pr_table_dir = self.cache_path + self.kitti_dir + '/evaluation/'
if not os.path.exists(self.pr_table_dir):
os.makedirs(self.pr_table_dir)
def load_tracklet(self):
"""
# load tracklet
# to show 3D bounding box
... | os.makedirs(self.gt_bbox_results_path) | conditional_block |
vspheremachine_controller.go | /*
Copyright 2019 The Kubernetes 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 to in writing, ... |
func (r machineReconciler) reconcileNetwork(ctx *context.MachineContext, vm infrav1.VirtualMachine, vmService services.VirtualMachineService) (bool, error) {
expNetCount, actNetCount := len(ctx.VSphereMachine.Spec.Network.Devices), len(vm.Network)
if expNetCount != actNetCount {
return false, errors.Errorf("inval... | {
// If the VSphereMachine is in an error state, return early.
if ctx.VSphereMachine.Status.ErrorReason != nil || ctx.VSphereMachine.Status.ErrorMessage != nil {
ctx.Logger.Info("Error state detected, skipping reconciliation")
return reconcile.Result{}, nil
}
// If the VSphereMachine doesn't have our finalizer... | identifier_body |
vspheremachine_controller.go | /*
Copyright 2019 The Kubernetes 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 to in writing, ... |
// Requeue the operation until the VM is "notfound".
if vm.State != infrav1.VirtualMachineStateNotFound {
ctx.Logger.Info("vm state is not reconciled", "expected-vm-state", infrav1.VirtualMachineStateNotFound, "actual-vm-state", vm.State)
return reconcile.Result{}, nil
}
// The VM is deleted so remove the fi... | {
return reconcile.Result{}, errors.Wrapf(err, "failed to destroy VM")
} | conditional_block |
vspheremachine_controller.go | /*
Copyright 2019 The Kubernetes 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 to in writing, ... | corev1 "k8s.io/api/core/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/util/wait"
clusterv1 "sigs.k8s.io/cluster-api/api/v1alpha3"
clusterutilv1 "sigs.k8s.io/cluster-api/util"
"sigs.k8s.io/cluster-api/util/patch"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/... | "github.com/google/go-cmp/cmp/cmpopts"
"github.com/pkg/errors" | random_line_split |
vspheremachine_controller.go | /*
Copyright 2019 The Kubernetes 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 to in writing, ... | (ctx *context.MachineContext) (reconcile.Result, error) {
// If the VSphereMachine is in an error state, return early.
if ctx.VSphereMachine.Status.ErrorReason != nil || ctx.VSphereMachine.Status.ErrorMessage != nil {
ctx.Logger.Info("Error state detected, skipping reconciliation")
return reconcile.Result{}, nil
... | reconcileNormal | identifier_name |
scrape.py | from bs4 import BeautifulSoup
import csv
import copy
from collections import defaultdict
from datetime import date, timedelta
import json
import os
import re
import requests
import sys
import time
district_map = {
"TVM": "Thiruvananthapuram",
"KLM": "Kollam",
"PTA": "Pathanamthitta",
"IDK": "Idukki",
... | ():
testing_data = {}
sess = init_sess()
response = run_req(sess, TESTING_REQ_URL, None, HEADERS, "GET")
if not response:
print("response failed for today's active case details")
return
if len(response.content) < 1000:
print(len(response.content), " Actual response not reciev... | get_testing_details | identifier_name |
scrape.py | from bs4 import BeautifulSoup
import csv
import copy
from collections import defaultdict
from datetime import date, timedelta
import json
import os
import re
import requests
import sys
import time
district_map = {
"TVM": "Thiruvananthapuram",
"KLM": "Kollam",
"PTA": "Pathanamthitta",
"IDK": "Idukki",
... | if not active:
print("Active details empty for date: {}".format(d))
continue
csv_data = []
for dat in qar_data:
dist_code = dat.pop("dist_code")
dist_active = active[dist_code]
for key in CASE_HEADER:
dat[key] = dist_act... | active = active_data_pivot[d] | random_line_split |
scrape.py | from bs4 import BeautifulSoup
import csv
import copy
from collections import defaultdict
from datetime import date, timedelta
import json
import os
import re
import requests
import sys
import time
district_map = {
"TVM": "Thiruvananthapuram",
"KLM": "Kollam",
"PTA": "Pathanamthitta",
"IDK": "Idukki",
... |
if __name__ == "__main__":
if len(sys.argv) > 1:
dateargs = sys.argv[1:]
print("processing for these dates: {}".format(dateargs))
dates = [get_date(datearg) for datearg in dateargs]
get_only_curr = False
else:
dates = [date.today()]
get_only_curr = True
get... | kd, active_today, updated_date = get_active_details_today()
if not get_only_curr:
active_data = get_bulk_active_details()
else:
assert dates[0] == updated_date, "Date mismatch. Site updated till {}".format(
updated_date
)
active_data = active_today
time.sleep(2)
... | identifier_body |
scrape.py | from bs4 import BeautifulSoup
import csv
import copy
from collections import defaultdict
from datetime import date, timedelta
import json
import os
import re
import requests
import sys
import time
district_map = {
"TVM": "Thiruvananthapuram",
"KLM": "Kollam",
"PTA": "Pathanamthitta",
"IDK": "Idukki",
... |
if len(response.content) < 1000:
print(len(response.content), " Actual response not recieved")
return
print("Processing testing data")
soup = BeautifulSoup(response.content, "html.parser")
case_report = soup.find_all(text=re.compile("Daily Case Reports from", re.I))[0]
table = case_... | print("response failed for today's active case details")
return | conditional_block |
vck.py | import Tkinter
from PIL import Image
from PIL import ImageDraw
from PIL import ImageTk
#import whrandom
import random
import string
import pickle
import sys
import os
class bitmap:
"""A two-dimensional one-bit-deep bitmap suitable for VCK operations.
The coordinate system has 0,0 at NW and xmax, ymax at SE. The... | (_viewer):
"""A toplevel window with a canvas, suitable for viewing a moonfield."""
R = 9 # default radius
def __init__(self, root, mf, title="Unnamed moonfield", radius=R):
"""Precondition: the moonfield mf must be filled."""
xmax, ymax = mf.size()
_viewer.__init__(self, root, xm... | moonfieldViewer | identifier_name |
vck.py | import Tkinter
from PIL import Image
from PIL import ImageDraw
from PIL import ImageTk
#import whrandom
import random
import string
import pickle
import sys
import os
class bitmap:
"""A two-dimensional one-bit-deep bitmap suitable for VCK operations.
The coordinate system has 0,0 at NW and xmax, ymax at SE. The... | fill="Black")
def view(self, root, title="No name", radius=moonfieldViewer.R):
"""Display this image in a toplevel window (optionally with the
given title). Preconditions: the moonfield must be filled; Tk must
have been initialised (the caller must supply Tk's root
... | canvas.create_arc(
radius*2*x, radius*2*y, radius*2*(x+1)-1, radius*2*(y+1)-1,
start = self.__data[(x,y)] * self.i2d, extent = 180.0, | random_line_split |
vck.py | import Tkinter
from PIL import Image
from PIL import ImageDraw
from PIL import ImageTk
#import whrandom
import random
import string
import pickle
import sys
import os
class bitmap:
"""A two-dimensional one-bit-deep bitmap suitable for VCK operations.
The coordinate system has 0,0 at NW and xmax, ymax at SE. The... |
return result
# Doc string for the following three functions:
# Take an arbitrary number (>=1) of bitmap arguments, all of the same size,
# and return another bitmap resulting from their pixel-by-pixel AND, OR or
# XOR as appropriate.
def AND(*args): return boolean(lambda a,b:a&b, args)
def OR(*args): return bool... | for y in range(maxY):
pixel = bitmaps[0].get(x,y)
for b in bitmaps[1:]:
pixel = apply(operation, (pixel, b.get(x,y)))
result.set(x,y,pixel) | conditional_block |
vck.py | import Tkinter
from PIL import Image
from PIL import ImageDraw
from PIL import ImageTk
#import whrandom
import random
import string
import pickle
import sys
import os
class bitmap:
"""A two-dimensional one-bit-deep bitmap suitable for VCK operations.
The coordinate system has 0,0 at NW and xmax, ymax at SE. The... |
def moonfield_undump(filename):
"""Return a moonfield obtained by rebuilding the one that had been
dumped to the given file."""
return pickle.load(open(filename))
# --------------------------------------------------------------
# File-based mode of operation
def makePad(size, expandedPadFile="pad.tif", ... | """A 2d array of angles. Items in the array are indexed by integers in
0..xmax, 0..ymax, with 0,0 being the NW corner. Each angle specifies
the phase (rotation) of a black halfmoon around its centre (determined
by its place in the array) and is represented by an integer in the
range 0..509"""
# Why... | identifier_body |
lib.rs | /*!
This crate implements various macros detailed in [The Little Book of Rust Macros](https://danielkeep.github.io/tlborm/).
If you use selective macro importing, you should make sure to *always* use the `tlborm_util` macro, as most macros in this crate depend on it being present.
*/
/**
Forces the parser to interpre... |
This is typically used to replace elements of an arbitrary token sequence with some fixed expression.
See [TLBoRM: Repetition replacement](https://danielkeep.github.io/tlborm/book/pat-repetition-replacement.html).
## Examples
```rust
# #[macro_use(replace_expr, tlborm_util)] extern crate tlborm;
# fn main() {
macro... | /**
Utility macro that takes a token tree and an expression, expanding to the expression. | random_line_split |
athena_cli.py | import argparse
import atexit
import csv
import json
import os
import readline
import subprocess
import sys
import time
import uuid
import boto3
import botocore
import cmd2 as cmd
from botocore.exceptions import ClientError, ParamValidationError
from tabulate import tabulate
LESS = "less -FXRSn"
HISTORY_FILE_SIZE = 5... | }
if self.encryption:
result_configuration['EncryptionConfiguration'] = {
'EncryptionOption': 'SSE_S3'
}
return self.athena.start_query_execution(
QueryString=query,
ClientRequestToken=str(uuid.uuid4... | if not db:
raise ValueError('Schema must be specified when session schema is not set')
result_configuration = {
'OutputLocation': self.bucket, | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.