blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
288
content_id
stringlengths
40
40
detected_licenses
listlengths
0
112
license_type
stringclasses
2 values
repo_name
stringlengths
5
115
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
684 values
visit_date
timestamp[us]date
2015-08-06 10:31:46
2023-09-06 10:44:38
revision_date
timestamp[us]date
1970-01-01 02:38:32
2037-05-03 13:00:00
committer_date
timestamp[us]date
1970-01-01 02:38:32
2023-09-06 01:08:06
github_id
int64
4.92k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]date
2012-06-04 01:52:49
2023-09-14 21:59:50
gha_created_at
timestamp[us]date
2008-05-22 07:58:19
2023-08-21 12:35:19
gha_language
stringclasses
147 values
src_encoding
stringclasses
25 values
language
stringclasses
1 value
is_vendor
bool
2 classes
is_generated
bool
2 classes
length_bytes
int64
128
12.7k
extension
stringclasses
142 values
content
stringlengths
128
8.19k
authors
listlengths
1
1
author_id
stringlengths
1
132
32b0be4decbdf1dcd2ea8ee3b247ad2f88aa2dc2
cd9931a0f21480fedf63a989ba8ebdda98e05e49
/Perper/Code/tensorflow/tfrecord_test.py
0406d69de960a8ababf08eafb504ab4ce907bd00
[]
no_license
WenHui-Zhou/recommand-system
7c429203268d0ac58560c122ae7b1834ca89472f
fb97229da61aed0a90be97026d42e7a03600382b
refs/heads/main
2023-05-10T01:04:45.424493
2021-06-10T01:58:04
2021-06-10T01:58:04
321,671,553
3
1
null
2020-12-24T03:33:27
2020-12-15T13:10:43
null
UTF-8
Python
false
false
1,119
py
#!/usr/bin/env python # -*- coding: utf-8 -*- # Author : perperzhou <765647930@qq.com> # Create Time : 2021-02-09 # Copyright (C)2021 All rights reserved. import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data import numpy as np def _int64_features(value): return tf.train.Feature(int64_list = tf.train.Int64List(value=[value])) def _bytes_features(value): return tf.train.Feature(bytes_list = tf.train.BytesList(value=[value])) mnist = input_data.read_data_sets( "./data",dtype=tf.uint8,one_hot=True ) images = mnist.train.images labels = mnist.train.labels pixels = images.shape[1] num_examples = mnist.train.num_examples filename = './output.tfrecords' writer = tf.python_io.TFRecordWriter(filename) for index in range(num_examples): image_raw = images[index].tostring() example = tf.train.Example(features=tf.train.Features(feature={ 'pixels': _int64_features(pixel), 'label' : _int64_features(np.argmax(labels[index])), 'image_raw': _bytes_features(image_raw) })) writer.write(example.SerializeToString()) writer.close()
[ "765647930@qq.com" ]
765647930@qq.com
97193a752d09cf751187c8a863e2c05beba510b1
2c0af32f3c1486fb15bc2c0374de2043577cc634
/modeling/strong_baseline.py
f7e3b52d6417bcf55bacb9a5ebc1e872730c66f7
[]
no_license
ArronHZG/reid-baseline
02b210fc3922f4bdc14352979e7ba3c51700ab90
d20943b117573e25c75338a55cb6219d90d3d2f0
refs/heads/master
2021-07-07T09:01:21.784144
2021-01-05T08:40:43
2021-01-05T08:40:43
248,293,171
6
3
null
null
null
null
UTF-8
Python
false
false
2,213
py
from torch import nn from modeling.backbone.resnet import resnet18, resnet50, resnet101, resnet152, \ resnext50_32x4d, resnext101_32x8d, \ wide_resnet50_2, wide_resnet101_2, resnet34 from modeling.base import Base from utils.data import Data from modeling.model_initial import weights_init_kaiming, weights_init_classifier model_map = {'resnet18': resnet18, 'resnet34': resnet34, 'resnet50': resnet50, 'resnet101': resnet101, 'resnet152': resnet152, 'resnext50_32x4d': resnext50_32x4d, 'resnext101_32x8d': resnext101_32x8d, 'wide_resnet50_2': wide_resnet50_2, 'wide_resnet101_2': wide_resnet101_2} class Baseline(nn.Module): def __init__(self, num_classes, last_stride, model_name, pretrain_choice, se=False, ibn_a=False, ibn_b=False): super(Baseline, self).__init__() self.base = model_map[model_name](last_stride=last_stride, pretrained=True if pretrain_choice == 'imagenet' else False, se=se, ibn_a=ibn_a, ibn_b=ibn_b) self.GAP = nn.AdaptiveAvgPool2d(1) self.num_classes = num_classes self.in_planes = 512 * self.base.block.expansion self.bottleneck = nn.BatchNorm1d(self.in_planes) self.bottleneck.bias.requires_grad_(False) self.bottleneck.apply(weights_init_kaiming) self.classifier = nn.Linear(self.in_planes, self.num_classes, bias=False) self.classifier.apply(weights_init_classifier) def forward(self, x) -> Data: x = self.base(x) feat_t = self.GAP(x).view(x.size(0), -1) feat_c = self.bottleneck(feat_t) # normalize for angular softmax data = Data() data.feat_t = feat_t data.feat_c = feat_c if self.training: cls_score = self.classifier(feat_c) data.cls_score = cls_score # global feature for triplet loss return data
[ "hou.zg@foxmail.com" ]
hou.zg@foxmail.com
8550448371992efeb2431d1bd8ee6f8f0de91d3f
a1657a0c5c8f3f8b51b98074293e2f2e9b16e6f4
/libs/pipeline_model/tensorflow_serving/apis/input_pb2.py
7d04447c2fcdf2d9c3e04f3d1e60c2ccc6c68f68
[ "Apache-2.0" ]
permissive
PipelineAI/pipeline
e8067636f5844dea0653aef84bd894ca2e700fc6
0f26e3eaad727c1d10950f592fe1949ece8153aa
refs/heads/master
2023-01-07T15:27:33.741088
2022-10-25T23:01:51
2022-10-25T23:01:51
38,730,494
2,596
512
Apache-2.0
2020-01-30T23:00:08
2015-07-08T03:49:23
Jsonnet
UTF-8
Python
false
true
7,736
py
# Generated by the protocol buffer compiler. DO NOT EDIT! # source: tensorflow_serving/apis/input.proto import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection from google.protobuf import symbol_database as _symbol_database from google.protobuf import descriptor_pb2 # @@protoc_insertion_point(imports) _sym_db = _symbol_database.Default() from tensorflow.core.example import example_pb2 as tensorflow_dot_core_dot_example_dot_example__pb2 DESCRIPTOR = _descriptor.FileDescriptor( name='tensorflow_serving/apis/input.proto', package='tensorflow.serving', syntax='proto3', serialized_pb=_b('\n#tensorflow_serving/apis/input.proto\x12\x12tensorflow.serving\x1a%tensorflow/core/example/example.proto\"4\n\x0b\x45xampleList\x12%\n\x08\x65xamples\x18\x01 \x03(\x0b\x32\x13.tensorflow.Example\"e\n\x16\x45xampleListWithContext\x12%\n\x08\x65xamples\x18\x01 \x03(\x0b\x32\x13.tensorflow.Example\x12$\n\x07\x63ontext\x18\x02 \x01(\x0b\x32\x13.tensorflow.Example\"\xa1\x01\n\x05Input\x12;\n\x0c\x65xample_list\x18\x01 \x01(\x0b\x32\x1f.tensorflow.serving.ExampleListB\x02(\x01H\x00\x12S\n\x19\x65xample_list_with_context\x18\x02 \x01(\x0b\x32*.tensorflow.serving.ExampleListWithContextB\x02(\x01H\x00\x42\x06\n\x04kindB\x03\xf8\x01\x01\x62\x06proto3') , dependencies=[tensorflow_dot_core_dot_example_dot_example__pb2.DESCRIPTOR,]) _EXAMPLELIST = _descriptor.Descriptor( name='ExampleList', full_name='tensorflow.serving.ExampleList', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='examples', full_name='tensorflow.serving.ExampleList.examples', index=0, number=1, type=11, cpp_type=10, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), ], extensions=[ ], nested_types=[], enum_types=[ ], options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=98, serialized_end=150, ) _EXAMPLELISTWITHCONTEXT = _descriptor.Descriptor( name='ExampleListWithContext', full_name='tensorflow.serving.ExampleListWithContext', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='examples', full_name='tensorflow.serving.ExampleListWithContext.examples', index=0, number=1, type=11, cpp_type=10, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='context', full_name='tensorflow.serving.ExampleListWithContext.context', index=1, number=2, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), ], extensions=[ ], nested_types=[], enum_types=[ ], options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=152, serialized_end=253, ) _INPUT = _descriptor.Descriptor( name='Input', full_name='tensorflow.serving.Input', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='example_list', full_name='tensorflow.serving.Input.example_list', index=0, number=1, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=_descriptor._ParseOptions(descriptor_pb2.FieldOptions(), _b('(\001'))), _descriptor.FieldDescriptor( name='example_list_with_context', full_name='tensorflow.serving.Input.example_list_with_context', index=1, number=2, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=_descriptor._ParseOptions(descriptor_pb2.FieldOptions(), _b('(\001'))), ], extensions=[ ], nested_types=[], enum_types=[ ], options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ _descriptor.OneofDescriptor( name='kind', full_name='tensorflow.serving.Input.kind', index=0, containing_type=None, fields=[]), ], serialized_start=256, serialized_end=417, ) _EXAMPLELIST.fields_by_name['examples'].message_type = tensorflow_dot_core_dot_example_dot_example__pb2._EXAMPLE _EXAMPLELISTWITHCONTEXT.fields_by_name['examples'].message_type = tensorflow_dot_core_dot_example_dot_example__pb2._EXAMPLE _EXAMPLELISTWITHCONTEXT.fields_by_name['context'].message_type = tensorflow_dot_core_dot_example_dot_example__pb2._EXAMPLE _INPUT.fields_by_name['example_list'].message_type = _EXAMPLELIST _INPUT.fields_by_name['example_list_with_context'].message_type = _EXAMPLELISTWITHCONTEXT _INPUT.oneofs_by_name['kind'].fields.append( _INPUT.fields_by_name['example_list']) _INPUT.fields_by_name['example_list'].containing_oneof = _INPUT.oneofs_by_name['kind'] _INPUT.oneofs_by_name['kind'].fields.append( _INPUT.fields_by_name['example_list_with_context']) _INPUT.fields_by_name['example_list_with_context'].containing_oneof = _INPUT.oneofs_by_name['kind'] DESCRIPTOR.message_types_by_name['ExampleList'] = _EXAMPLELIST DESCRIPTOR.message_types_by_name['ExampleListWithContext'] = _EXAMPLELISTWITHCONTEXT DESCRIPTOR.message_types_by_name['Input'] = _INPUT _sym_db.RegisterFileDescriptor(DESCRIPTOR) ExampleList = _reflection.GeneratedProtocolMessageType('ExampleList', (_message.Message,), dict( DESCRIPTOR = _EXAMPLELIST, __module__ = 'tensorflow_serving.apis.input_pb2' # @@protoc_insertion_point(class_scope:tensorflow.serving.ExampleList) )) _sym_db.RegisterMessage(ExampleList) ExampleListWithContext = _reflection.GeneratedProtocolMessageType('ExampleListWithContext', (_message.Message,), dict( DESCRIPTOR = _EXAMPLELISTWITHCONTEXT, __module__ = 'tensorflow_serving.apis.input_pb2' # @@protoc_insertion_point(class_scope:tensorflow.serving.ExampleListWithContext) )) _sym_db.RegisterMessage(ExampleListWithContext) Input = _reflection.GeneratedProtocolMessageType('Input', (_message.Message,), dict( DESCRIPTOR = _INPUT, __module__ = 'tensorflow_serving.apis.input_pb2' # @@protoc_insertion_point(class_scope:tensorflow.serving.Input) )) _sym_db.RegisterMessage(Input) DESCRIPTOR.has_options = True DESCRIPTOR._options = _descriptor._ParseOptions(descriptor_pb2.FileOptions(), _b('\370\001\001')) _INPUT.fields_by_name['example_list'].has_options = True _INPUT.fields_by_name['example_list']._options = _descriptor._ParseOptions(descriptor_pb2.FieldOptions(), _b('(\001')) _INPUT.fields_by_name['example_list_with_context'].has_options = True _INPUT.fields_by_name['example_list_with_context']._options = _descriptor._ParseOptions(descriptor_pb2.FieldOptions(), _b('(\001')) try: # THESE ELEMENTS WILL BE DEPRECATED. # Please use the generated *_pb2_grpc.py files instead. import grpc from grpc.beta import implementations as beta_implementations from grpc.beta import interfaces as beta_interfaces from grpc.framework.common import cardinality from grpc.framework.interfaces.face import utilities as face_utilities except ImportError: pass # @@protoc_insertion_point(module_scope)
[ "chris@fregly.com" ]
chris@fregly.com
ef93fed2fe484369ac4b364a7b254ed5ed3ceaa9
ac227cc22d5f5364e5d029a2cef83816a6954590
/applications/physbam/physbam-lib/Scripts/Archives/log/formatlog.py
a347029839b15cbecce0c24bc25f1497c218db85
[ "BSD-3-Clause" ]
permissive
schinmayee/nimbus
597185bc8bac91a2480466cebc8b337f5d96bd2e
170cd15e24a7a88243a6ea80aabadc0fc0e6e177
refs/heads/master
2020-03-11T11:42:39.262834
2018-04-18T01:28:23
2018-04-18T01:28:23
129,976,755
0
0
BSD-3-Clause
2018-04-17T23:33:23
2018-04-17T23:33:23
null
UTF-8
Python
false
false
1,148
py
#!/usr/bin/python import os import sys from elementtree.ElementTree import parse if len(sys.argv)!=2: print>>sys.stderr, "Usage: formatlog <dir|logfile>" sys.exit(1) log=sys.argv[1] if os.path.isdir(log): log=os.path.join(log,'log.txt') tree=parse(open(log)) root=tree.getroot() RED=chr(27) + '[1;31m' #BRIGHTRED=chr(27) + '[1;31m' GREEN=chr(27) + '[1;32m' BLUE=chr(27) + '[1;34m' CLEAR=chr(27) + '[00m' def display(root,indent): print "%s%*s%-*s %s s%s"%(GREEN,2*indent,"",80-2*indent,root.attrib["name"],root[-1].attrib["value"],CLEAR) #print "%*s%s"%(5,"","hiu") #if len(root)==1: print " %s"%(root[-1].attrib["value"]) #print " " for child in root: if child.tag=="time": pass elif child.tag=="stat": print "%*s%s%s = %s%s"%(2*indent+2,"",BLUE,child.attrib["name"],child.attrib["value"],CLEAR) pass elif child.tag=="print": print "%*s%s%s%s"%(2*indent+2,"",RED,child.text,CLEAR) pass elif child.tag=="error": print child.text pass else: display(child,indent+1) display(root,0)
[ "quhang@stanford.edu" ]
quhang@stanford.edu
e472cd61c73f11e2e79ab123037f39914acf0739
acef5161a1eeb107b116f9763114bb9f77d701b4
/pytorch/深度学习之PyTorch入门/2.Intermediate/CNN_Net.py
378dd4e6966f71b6f77a0e4fbd6285eb685de30e
[]
no_license
lingxiao00/PyTorch_Tutorials
aadb68582edbaa093ab200724c670b36763156b7
285bcfb0c60860e47343485daeb54947cd715f97
refs/heads/master
2021-10-20T16:56:21.275740
2019-03-01T02:46:42
2019-03-01T02:46:42
null
0
0
null
null
null
null
UTF-8
Python
false
false
3,240
py
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Date : 2018-12-06 19:41:51 # @Author : cdl (1217096231@qq.com) # @Link : https://github.com/cdlwhm1217096231/python3_spider # @Version : $Id$ import torch import torch.nn as nn import torchvision import torchvision.transforms as transforms # 配置设备 device = torch.device("cuda" if torch.cuda.is_available() else "cpu") # 超参数设置 num_epochs = 5 num_classes = 10 batch_size = 100 learning_rate = 0.001 # MNIST 数据集 train_dataset = torchvision.datasets.MNIST( root="./datasets/", train=True, transform=transforms.ToTensor(), download=True) test_dataset = torchvision.datasets.MNIST( root="./datasets/", train=False, transform=transforms.ToTensor()) # Data Loader train_loader = torch.utils.data.DataLoader( dataset=train_dataset, batch_size=batch_size, shuffle=True) test_loader = torch.utils.data.DataLoader( dataset=test_dataset, batch_size=batch_size, shuffle=False) # 定义模型 class CNN_Net(nn.Module): def __init__(self, num_classes=10): super(CNN_Net, self).__init__() self.layer1 = nn.Sequential( nn.Conv2d(in_channels=1, out_channels=16, kernel_size=5, stride=1, padding=2), nn.BatchNorm2d(16), nn.ReLU(), nn.MaxPool2d(kernel_size=2, stride=2)) self.layer2 = nn.Sequential( nn.Conv2d(in_channels=16, out_channels=32, kernel_size=5, stride=1, padding=2), nn.BatchNorm2d(32), nn.ReLU(), nn.MaxPool2d(kernel_size=2, stride=2)) self.fc = nn.Linear(7 * 7 * 32, out_features=num_classes) def forward(self, x): z1 = self.layer1(x) a1 = self.layer2(z1) z2 = a1.reshape(a1.size(0), -1) # 进入全连接层之前,需要将池化层输出的特征flatten a2 = self.fc(z2) return a2 model = CNN_Net(num_classes).to(device) # 定义Loss与优化算法 loss_func = nn.CrossEntropyLoss() optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate) # 开始训练 total_step = len(train_loader) for epoch in range(num_epochs): for i, (images, labels) in enumerate(train_loader): images = images.to(device) labels = labels.to(device) outputs = model(images) loss = loss_func(outputs, labels) optimizer.zero_grad() loss.backward() optimizer.step() if (i + 1) % 100 == 0: print("Epoch[{}/{}], Step[{}/{}], Loss:{:.4f}".format(epoch + 1, num_epochs, i + 1, total_step, loss.item())) # 测试模型 model.eval() # 测试模式(batchnorm uses moving mean/variance instead of mini-batch mean/variance) with torch.no_grad(): correct = 0 total = 0 for images, labels in test_loader: images = images.to(device) labels = labels.to(device) outputs = model(images) _, predicted = torch.max(outputs.data, 1) total += labels.size(0) correct += (predicted == labels).sum().item() print("在测试集上的精度:{}%".format(100 * correct / total)) # 保存模型 torch.save(model.state_dict(), "CNN_Net.model")
[ "1217096231@qq.com" ]
1217096231@qq.com
b380164b0b9a3be449ed86f3869ccf1544d02d13
8b2e251d8ffbce4fe3987c0245d7af9aedb21c15
/tests/test_github.py
07cb2df9ad0ed812993750e4a9ece01778075dda
[ "BSD-3-Clause" ]
permissive
xlevus/json-spec
0f93bbf1ceab27d3d64349782e2e593bc7c4e58e
86db73bfbfb4c5b476b37b304060b32022a257c6
refs/heads/master
2021-01-21T18:51:01.112087
2015-06-29T10:46:47
2015-06-29T10:46:47
38,238,544
0
0
null
2015-06-29T09:11:22
2015-06-29T09:11:22
null
UTF-8
Python
false
false
1,146
py
""" tests.tests_github ~~~~~~~~~~~~~~~~~~ """ import pytest from jsonspec.validators import load, ValidationError def test_issue4(): validator = load({ '$schema': 'http://json-schema.org/draft-04/schema#', 'type': 'object', 'properties': { 'props': { 'type': 'array', 'items': { 'oneOf': [ {'type': 'string'}, {'type': 'number'} ] } } } }) assert {'props': ['hello']} == validator.validate({'props': ['hello']}) assert {'props': [42, 'you']} == validator.validate({'props': [42, 'you']}) with pytest.raises(ValidationError): validator.validate({ 'props': [None] }) with pytest.raises(ValidationError): validator.validate({ 'props': None }) with pytest.raises(ValidationError): validator.validate({ 'props': 'hello' }) with pytest.raises(ValidationError): validator.validate({ 'props': 42 })
[ "clint.northwood@gmail.com" ]
clint.northwood@gmail.com
69924ca5d5756dc11957610d4dc812203f1ab906
d6c117812a618ff34055488337aaffea8cf81ca1
/ui/TabbedView.py
47f85165a496eb4a5ad28aa23e0898bec01b89b3
[]
no_license
c0ns0le/Pythonista
44829969f28783b040dd90b46d08c36cc7a1f590
4caba2d48508eafa2477370923e96132947d7b24
refs/heads/master
2023-01-21T19:44:28.968799
2016-04-01T22:34:04
2016-04-01T22:34:04
55,368,932
3
0
null
2023-01-22T01:26:07
2016-04-03T21:04:40
Python
UTF-8
Python
false
false
2,328
py
# @ui # https://gist.github.com/jsbain/fcadaffff4be09c4ec78 import ui class TabbedView(ui.View): def __init__(self,tablist=[], frame=(0,0)+ui.get_screen_size()): '''takes an iterable of Views, using the view name as the tab selector. empty views sre just given generic names''' self.tabcounter=0 #unique counter, for name disambiguation self.buttonheight=30 #height of buttonbar #setup button bar self.tabbuttons=ui.SegmentedControl(frame=(0,0,self.width, self.buttonheight)) self.tabbuttons.action=self.tab_action self.tabbuttons.flex='W' self.tabbuttons.segments=[] self.add_subview(self.tabbuttons) for tab in tablist: self.addtab(tab) def tab_action(self,sender): if sender.selected_index >= 0: tabname=sender.segments[sender.selected_index] self[tabname].bring_to_front() def focus_tab_by_index(self,index): self.tabbuttons.selected_index=index self.tab_action(self.tabbuttons) def focus_tab_by_name(self,tabname): self.tabbuttons.selected_index=self.tabbuttons.segments.index(tabname) self.tab_action(self.tabbuttons) def addtab(self,tab): if not tab.name: tab.name='tab{}'.format(self.tabcounter) if tab.name in self.tabbuttons.segments: #append unique counter to name tab.name+=str(self.tabcounter) self.tabcounter+=1 self.tabbuttons.segments+=(tab.name,) tab.frame=(0,self.buttonheight,self.width,self.height-self.buttonheight) tab.flex='WH' self.add_subview(tab) self.focus_tab_by_name(tab.name) def removetab(self,tabname): self.tabbuttons.segments=[x for x in self.tabbuttons.segments if x != tabname] self.remove_subview(tabname) # if tab was top tab, think about updating selected tab to whatever is on top def layout(self): pass # maybe set tabbuttons size if __name__=='__main__': v=TabbedView() v.addtab(ui.View(name='red',bg_color='red')) v.addtab(ui.View(bg_color='blue')) v.addtab(ui.View(name='green',bg_color='green')) v.addtab(ui.View(name='green',bg_color='green')) v.present()
[ "itdamdouni@gmail.com" ]
itdamdouni@gmail.com
5909b171a789cfadf92b5428de5babd92ef70753
519b1185421f33d43a0917ffe5ec582099c000eb
/src/wtfjson/fields/unbound_field.py
3f98a69b0b9992b3dcacb13c542767d1caa166ce
[ "MIT" ]
permissive
binary-butterfly/wtfjson
d58f710b228149a34570a4677262cc3b16ffab6d
551ad07c895ce3c94ac3015b6b5ecc2102599b56
refs/heads/main
2023-08-11T04:13:15.907617
2021-10-11T09:21:34
2021-10-11T09:21:34
359,063,547
0
0
MIT
2021-10-11T09:21:34
2021-04-18T06:29:17
Python
UTF-8
Python
false
false
559
py
# encoding: utf-8 """ binary butterfly validator Copyright (c) 2021, binary butterfly GmbH Use of this source code is governed by an MIT-style license that can be found in the LICENSE.txt. """ class UnboundField: def __init__(self, field_class, *args, name=None, **kwargs): self.field_class = field_class self.args = args self.name = name self.kwargs = kwargs def bind(self, form, field_name, **kwargs): return self.field_class(*self.args, **dict(form=form, field_name=field_name, **self.kwargs, **kwargs))
[ "mail@ernestoruge.de" ]
mail@ernestoruge.de
591869b47c31b2765711783418bef12a1fc2b8a5
96ca1945a32c5ea708d4871e320a2f19b557e68b
/test_testing_utils.py
d3215a6df0258b199b4e80cc6c0f361735494524
[]
no_license
u8sand/backup
81922941296c0b1e9f1fc4e2b851e3691421b8cc
9d44bd541b36069acc9610a9719eff8ea9c2e0d7
refs/heads/master
2021-05-11T15:33:28.376210
2018-01-30T22:23:20
2018-01-30T22:23:20
117,734,883
2
3
null
null
null
null
UTF-8
Python
false
false
1,071
py
#!/usr/bin/env python3 from testing_utils import ExtendedTestCase class TestTestingUtils(ExtendedTestCase): def test_mkdir_rmdir(self): self.mkdir('test_dir/test_dir_2') self.assertIsDir('test_dir') self.assertIsDir('test_dir/test_dir_2') self.rmdir('test_dir') self.assertIsNotDir('test_dir') def test_touch_remove(self): self.touch('test_file_1') self.assertIsFile('test_file_1') self.touch('test_dir/test_file_2', 'Test') self.assertIsFile('test_dir/test_file_2') self.assertFileIs('test_dir/test_file_2', 'Test') self.remove('test_dir/test_file_2') self.assertIsNotFile('test_dir/test_file_2') def test_add_copy(self): self.add('test_testing_utils.py') self.assertIsFile('test_testing_utils.py') self.copy('test_testing_utils.py', 'test_testing_utils_2.py') self.assertIsFile('test_testing_utils_2.py') def test_execute(self): self.touch('test.sh', 'exit 0') self.execute('test.sh') def test_recursive_touch(self): pass # TODO def test_assert_paths(self): pass # TODO
[ "u8sand@gmail.com" ]
u8sand@gmail.com
a7032e64cfe9697f723ec0d06e52281280064da1
6b2a8dd202fdce77c971c412717e305e1caaac51
/solutions_5686313294495744_0/Python/biran0079/c.py
f78ae9b6e91a9374279f6467852dac2df252b4a1
[]
no_license
alexandraback/datacollection
0bc67a9ace00abbc843f4912562f3a064992e0e9
076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf
refs/heads/master
2021-01-24T18:27:24.417992
2017-05-23T09:23:38
2017-05-23T09:23:38
84,313,442
2
4
null
null
null
null
UTF-8
Python
false
false
489
py
def dfs(i): if i == len(l): return 0 res=dfs(i+1) a,b=l[i] if fst[a]>1 and snd[b] > 1: fst[a]-=1 snd[b]-=1 res=max(res, 1+dfs(i+1)) fst[a]+=1 snd[b]+=1 return res for t in range(int(raw_input())): n=int(raw_input()) l=[] fst={} snd={} for i in range(n): s=raw_input() a,b=s.split() l.append((a,b)) fst[a] = fst.get(a,0)+1 snd[b] = snd.get(b,0)+1 res=dfs(0) print "Case #{}: {}".format(t+1, res)
[ "alexandra1.back@gmail.com" ]
alexandra1.back@gmail.com
ba481849f965390fabf10847601ba3c76504f727
d83fde3c891f44014f5339572dc72ebf62c38663
/_bin/google-cloud-sdk/lib/surface/auth/git_helper.py
a6de47988f9275251814caa2adbdd0f03ea1bbf4
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
gyaresu/dotfiles
047cc3ca70f4b405ba272856c69ee491a79d2ebe
e5e533b3a081b42e9492b228f308f6833b670cfe
refs/heads/master
2022-11-24T01:12:49.435037
2022-11-01T16:58:13
2022-11-01T16:58:13
17,139,657
1
1
null
2020-07-25T14:11:43
2014-02-24T14:59:59
Python
UTF-8
Python
false
false
7,848
py
# Copyright 2013 Google Inc. All Rights Reserved. # # 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 # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """A git credential helper that provides Google git repository passwords. Reads a session from stdin that looks a lot like: protocol=https host=code.google.com And writes out a session to stdout that looks a lot like: username=me password=secret Errors will be reported on stderr. Note that spaces may be part of key names so, for example, "protocol" must not be proceeded by leading spaces. """ from __future__ import absolute_import from __future__ import unicode_literals import os import re import subprocess import sys import textwrap from googlecloudsdk.api_lib.auth import exceptions as auth_exceptions from googlecloudsdk.calliope import base from googlecloudsdk.calliope import exceptions as c_exc from googlecloudsdk.core import log from googlecloudsdk.core import properties from googlecloudsdk.core.credentials import store as c_store from googlecloudsdk.core.util import platforms from oauth2client import client _KEYVAL_RE = re.compile(r'(.+)=(.*)') _BLANK_LINE_RE = re.compile(r'^ *$') @base.Hidden class GitHelper(base.Command): """A git credential helper to provide access to Google git repositories.""" GET = 'get' STORE = 'store' METHODS = [GET, STORE] GOOGLESOURCE = 'googlesource.com' @staticmethod def Args(parser): parser.add_argument('method', help='The git credential helper method.') parser.add_argument('--ignore-unknown', action='store_true', help=('Produce no output and exit with 0 when given ' 'an unknown method (e.g. store) or host.')) @c_exc.RaiseErrorInsteadOf(auth_exceptions.AuthenticationError, client.Error) def Run(self, args): """Run the helper command.""" if args.method not in GitHelper.METHODS: if args.ignore_unknown: return raise auth_exceptions.GitCredentialHelperError( 'Unexpected method [{meth}]. One of [{methods}] expected.' .format(meth=args.method, methods=', '.join(GitHelper.METHODS))) info = self._ParseInput() credentialed_domains = [ 'source.developers.google.com', GitHelper.GOOGLESOURCE, # Requires a different username value. ] credentialed_domains_suffix = [ '.'+GitHelper.GOOGLESOURCE, ] extra = properties.VALUES.core.credentialed_hosted_repo_domains.Get() if extra: credentialed_domains.extend(extra.split(',')) host = info.get('host') def _ValidateHost(host): if host in credentialed_domains: return True for suffix in credentialed_domains_suffix: if host.endswith(suffix): return True return False if not _ValidateHost(host): if not args.ignore_unknown: raise auth_exceptions.GitCredentialHelperError( 'Unknown host [{host}].'.format(host=host)) return if args.method == GitHelper.GET: account = properties.VALUES.core.account.Get() try: cred = c_store.Load(account) c_store.Refresh(cred) except c_store.Error as e: sys.stderr.write(textwrap.dedent("""\ ERROR: {error} Run 'gcloud auth login' to log in. """.format(error=str(e)))) return self._CheckNetrc() # For googlesource.com, any username beginning with "git-" is accepted # and the identity of the user is extracted from the token server-side. if (host == GitHelper.GOOGLESOURCE or host.endswith('.'+GitHelper.GOOGLESOURCE)): sent_account = 'git-account' else: sent_account = account sys.stdout.write(textwrap.dedent("""\ username={username} password={password} """).format(username=sent_account, password=cred.access_token)) elif args.method == GitHelper.STORE: # On OSX, there is an additional credential helper that gets called before # ours does. When we return a token, it gets cached there. Git continues # to get it from there first until it expires. That command then fails, # and the token is deleted, but it does not retry the operation. The next # command gets a new token from us and it starts working again, for an # hour. This erases our credential from the other cache whenever 'store' # is called on us. Because they are called first, the token will already # be stored there, and so we can successfully erase it to prevent caching. if (platforms.OperatingSystem.Current() == platforms.OperatingSystem.MACOSX): log.debug('Clearing OSX credential cache.') try: input_string = 'protocol={protocol}\nhost={host}\n\n'.format( protocol=info.get('protocol'), host=info.get('host')) log.debug('Calling erase with input:\n%s', input_string) p = subprocess.Popen(['git-credential-osxkeychain', 'erase'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) (out, err) = p.communicate(input_string) if p.returncode: log.debug( 'Failed to clear OSX keychain:\nstdout: {%s}\nstderr: {%s}', out, err) # pylint:disable=broad-except, This can fail and should only be done as # best effort. except Exception as e: log.debug('Failed to clear OSX keychain', exc_info=True) def _ParseInput(self): """Parse the fields from stdin. Returns: {str: str}, The parsed parameters given on stdin. """ info = {} for line in sys.stdin: if _BLANK_LINE_RE.match(line): continue match = _KEYVAL_RE.match(line) if not match: raise auth_exceptions.GitCredentialHelperError( 'Invalid input line format: [{format}].' .format(format=line.rstrip('\n'))) key, val = match.groups() info[key] = val.strip() if 'protocol' not in info: raise auth_exceptions.GitCredentialHelperError( 'Required key "protocol" missing.') if 'host' not in info: raise auth_exceptions.GitCredentialHelperError( 'Required key "host" missing.') if info.get('protocol') != 'https': raise auth_exceptions.GitCredentialHelperError( 'Invalid protocol [{p}]. "https" expected.' .format(p=info.get('protocol'))) return info def _CheckNetrc(self): """Warn on stderr if ~/.netrc contains redundant credentials.""" def Check(p): if not os.path.exists(p): return try: with open(p) as f: data = f.read() if 'source.developers.google.com' in data: sys.stderr.write(textwrap.dedent("""\ You have credentials for your Google repository in [{path}]. This repository's git credential helper is set correctly, so the credentials in [{path}] will not be used, but you may want to remove them to avoid confusion. """.format(path=p))) # pylint:disable=broad-except, If something went wrong, forget about it. except Exception: pass Check(os.path.expanduser(os.path.join('~', '.netrc'))) Check(os.path.expanduser(os.path.join('~', '_netrc')))
[ "me@gareth.codes" ]
me@gareth.codes
73ed73e44e73439d953db9d8d3334a723e946c93
6b2a8dd202fdce77c971c412717e305e1caaac51
/solutions_5690574640250880_0/Python/Happyhobo/CodeJam3.py
fe5fdd5190ca94a238e7b72e0ea17a400cf4d3f6
[]
no_license
alexandraback/datacollection
0bc67a9ace00abbc843f4912562f3a064992e0e9
076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf
refs/heads/master
2021-01-24T18:27:24.417992
2017-05-23T09:23:38
2017-05-23T09:23:38
84,313,442
2
4
null
null
null
null
UTF-8
Python
false
false
2,406
py
import numpy def read_words(afile): words = [] for line in afile: words.append(line.strip()) return words filename = open('test3.txt' , 'r') T = filename.readline() #num test cases aList = read_words(filename) # array where each element is a line of text for i in range(int(T)): DatBool = True Values = aList[i].split() R = int(Values[0]) C = int(Values[1]) M = int(Values[2]) FR = 0 FC = 0 Matrix = numpy.zeros(shape=(R,C)) while ( (M >= (C-FC)) or (M >= (R-FR) ) ): if ( (C-FC) <= (R-FR) ): FullRow = [] for x in range (C): FullRow.append(1) Matrix[FR] = FullRow M = M-(C-FC) FR += 1 elif ( (C-FC) > (R-FR) ): for o in range(R-FR): Matrix[(o+FR), (FC)] = 1 M = M-(R-FR) FC += 1 if (M==0): if (R==1 or C==1): win = 5 elif ((R-FR)*(C-FC) == 1): win = 5 elif ( (R-FR) == 1 ): DatBool = False elif ( (C-FC) == 1 ): DatBool = False #else: done else: # some leftover m M<(C-FC) and M<(R-FR) if ( (R-FR) <= 2 ): DatBool = False if ( (C-FC) <= 2 ): DatBool = False else: # at least a 3-by-3 if (M > ( (C-FC-2)*(R-FR-2) ) ): DatBool = False else: # winnable for z in range (C-FC-2): if (M>0): Matrix[(FR), (FC+z)] = 1 M -= 1 if (M!=0): for y in range (R-FR-3): if (M>0): Matrix[(FR+1+y), (FC)] = 1 M = M-1 print "Case #"+str(i+1)+":" if (DatBool == False): print "Impossible" else: for r in range (R): DatRow = "" for c in range (C): if (Matrix[r][c] == 0): DatRow += "." elif (Matrix[r][c] == 1): DatRow += "*" if (r == (R-1)): DatRow = DatRow[:-1] + "c" print DatRow
[ "eewestman@gmail.com" ]
eewestman@gmail.com
27bce40eb00843c6f791dc8adf01ae91b3eeee8a
ce76b3ef70b885d7c354b6ddb8447d111548e0f1
/hand/feel_number.py
9afaf5fa9d6f81f5b729c8617739ec9961ab3214
[]
no_license
JingkaiTang/github-play
9bdca4115eee94a7b5e4ae9d3d6052514729ff21
51b550425a91a97480714fe9bc63cb5112f6f729
refs/heads/master
2021-01-20T20:18:21.249162
2016-08-19T07:20:12
2016-08-19T07:20:12
60,834,519
0
0
null
null
null
null
UTF-8
Python
false
false
231
py
#! /usr/bin/env python def first_woman(str_arg): old_company_and_old_person(str_arg) print('large_part') def old_company_and_old_person(str_arg): print(str_arg) if __name__ == '__main__': first_woman('company')
[ "jingkaitang@gmail.com" ]
jingkaitang@gmail.com
a93e4abe550ba336b0cdf4e7b99e7c15650f6699
c2471dcf74c5fd1ccf56d19ce856cf7e7e396b80
/chap18/7.py
85f6866c5e65a7135fffd437e19b223b3aebc982
[]
no_license
oc0de/pythonEpi
eaeef2cf748e6834375be6bc710132b572fc2934
fb7b9e06bb39023e881de1a3d370807b955b5cc0
refs/heads/master
2021-06-18T05:33:19.518652
2017-07-07T04:34:52
2017-07-07T04:34:52
73,049,450
0
0
null
null
null
null
UTF-8
Python
false
false
555
py
def getMaxTrappedWater(heights): area, leftSide, rightSide = 0, 0, len(heights)-1 while leftSide < rightSide: area = max(area, (rightSide - leftSide) * min(heights[leftSide], heights[rightSide])) if heights[leftSide] == heights[rightSide]: leftSide += 1 rightSide -= 1 elif heights[leftSide] < heights[rightSide]: leftSide += 1 else: rightSide -= 1 return area heights = [1, 2, 1, 3, 4, 4, 5, 6, 2, 1, 3, 1, 3, 2, 1, 2, 4, 1] print getMaxTrappedWater(heights)
[ "valizade@mail.gvsu.edu" ]
valizade@mail.gvsu.edu
a04bf390873d12346090bcdfc646ee211bab7aba
b0885fde23fff880927c3a6248c7b5a33df670f1
/models/im_vev/main.py
0b15b743f659dcb7a2b8c0f1b5b760da910f9d0f
[]
no_license
mrsalehi/paraphrase-generation
ceb68200e9016c5f26036af565fafa2d736dc96b
3e8bd36bd9416999b93ed8e8529bfdf83cf4dcdd
refs/heads/master
2020-07-22T03:50:40.343595
2019-08-26T11:29:08
2019-08-26T11:29:08
207,065,580
7
0
null
null
null
null
UTF-8
Python
false
false
181
py
import fire from models import im_vev from models.neural_editor.main import ModelRunner if __name__ == '__main__': cls = ModelRunner cls.model = im_vev fire.Fire(cls)
[ "ub.maka@gmail.com" ]
ub.maka@gmail.com
0de082a9ee3fba6fa27326ee1526cdb560e9aca6
ac2539764372920ca4b020d614113a6b1a0b3ee4
/tests/test_signals.py
d9ce62546a5960ec2d78e6048c105001aed2ed0c
[ "MIT" ]
permissive
vint21h/django-read-only-admin
15f16643b242983fa9895c7ac03777eb7c52a2d1
e3edebb2081a50b9da708e06d3cbd5fb953cf66c
refs/heads/master
2022-10-22T23:25:31.237026
2022-02-19T20:29:19
2022-02-19T20:29:19
92,436,831
31
3
MIT
2023-09-05T06:49:28
2017-05-25T19:23:19
Python
UTF-8
Python
false
false
1,261
py
# -*- coding: utf-8 -*- # django-read-only-admin # tests/test_signals.py from typing import List from django.conf import settings from django.test import TestCase from django.contrib.auth.models import Permission __all__: List[str] = ["AddReadOnlyPermissionsSignalTest"] class AddReadOnlyPermissionsSignalTest(TestCase): """Add read only permissions signal tests.""" def test_add_readonly_permissions(self) -> None: """Test signal.""" self.assertListEqual( list1=list( Permission.objects.filter( codename__startswith=settings.READ_ONLY_ADMIN_PERMISSION_PREFIX ).values_list("codename", flat=True) ), list2=[ "readonly_logentry", "readonly_group", "readonly_permission", "readonly_user", "readonly_contenttype", ], ) def test_add_readonly_permissions__count(self) -> None: """Test signal create new permissions number.""" self.assertEqual( first=Permission.objects.filter( codename__startswith=settings.READ_ONLY_ADMIN_PERMISSION_PREFIX ).count(), second=5, )
[ "vint21h@vint21h.pp.ua" ]
vint21h@vint21h.pp.ua
24671efa7e3468d3798e40da790f8d1a264cf66d
32eeb97dff5b1bf18cf5be2926b70bb322e5c1bd
/benchmark/redreader/testcase/firstcases/testcase5_009.py
288f69cb7bbc2f5180dbb679b3cd09b65cfe78cb
[]
no_license
Prefest2018/Prefest
c374d0441d714fb90fca40226fe2875b41cf37fc
ac236987512889e822ea6686c5d2e5b66b295648
refs/heads/master
2021-12-09T19:36:24.554864
2021-12-06T12:46:14
2021-12-06T12:46:14
173,225,161
5
0
null
null
null
null
UTF-8
Python
false
false
3,526
py
#coding=utf-8 import os import subprocess import time import traceback from appium import webdriver from appium.webdriver.common.touch_action import TouchAction from selenium.common.exceptions import NoSuchElementException, WebDriverException desired_caps = { 'platformName' : 'Android', 'deviceName' : 'Android Emulator', 'platformVersion' : '4.4', 'appPackage' : 'org.quantumbadger.redreader', 'appActivity' : 'org.quantumbadger.redreader.activities.MainActivity', 'resetKeyboard' : True, 'androidCoverage' : 'org.quantumbadger.redreader/org.quantumbadger.redreader.JacocoInstrumentation', 'noReset' : True } def command(cmd, timeout=5): p = subprocess.Popen(cmd, stderr=subprocess.STDOUT, stdout=subprocess.PIPE, shell=True) time.sleep(timeout) p.terminate() return def getElememt(driver, str) : for i in range(0, 5, 1): try: element = driver.find_element_by_android_uiautomator(str) except NoSuchElementException: time.sleep(1) else: return element os.popen("adb shell input tap 50 50") element = driver.find_element_by_android_uiautomator(str) return element def getElememtBack(driver, str1, str2) : for i in range(0, 2, 1): try: element = driver.find_element_by_android_uiautomator(str1) except NoSuchElementException: time.sleep(1) else: return element for i in range(0, 5, 1): try: element = driver.find_element_by_android_uiautomator(str2) except NoSuchElementException: time.sleep(1) else: return element os.popen("adb shell input tap 50 50") element = driver.find_element_by_android_uiautomator(str2) return element def swipe(driver, startxper, startyper, endxper, endyper) : size = driver.get_window_size() width = size["width"] height = size["height"] try: driver.swipe(start_x=int(width * startxper), start_y=int(height * startyper), end_x=int(width * endxper), end_y=int(height * endyper), duration=2000) except WebDriverException: time.sleep(1) driver.swipe(start_x=int(width * startxper), start_y=int(height * startyper), end_x=int(width * endxper), end_y=int(height * endyper), duration=2000) return # testcase009 try : starttime = time.time() driver = webdriver.Remote('http://localhost:4723/wd/hub', desired_caps) element = getElememtBack(driver, "new UiSelector().text(\"askreddit\")", "new UiSelector().className(\"android.widget.TextView\").instance(8)") TouchAction(driver).tap(element).perform() element = getElememt(driver, "new UiSelector().className(\"android.widget.TextView\").description(\"Refresh Posts\")") TouchAction(driver).long_press(element).release().perform() element = getElememtBack(driver, "new UiSelector().text(\"/r/announcements\")", "new UiSelector().className(\"android.widget.TextView\")") TouchAction(driver).tap(element).perform() element = getElememtBack(driver, "new UiSelector().text(\"books\")", "new UiSelector().className(\"android.widget.TextView\").instance(12)") TouchAction(driver).tap(element).perform() except Exception, e: print 'FAIL' print 'str(e):\t\t', str(e) print 'repr(e):\t', repr(e) print traceback.format_exc() else: print 'OK' finally: cpackage = driver.current_package endtime = time.time() print 'consumed time:', str(endtime - starttime), 's' command("adb shell am broadcast -a com.example.pkg.END_EMMA --es name \"5_009\"") jacocotime = time.time() print 'jacoco time:', str(jacocotime - endtime), 's' driver.quit() if (cpackage != 'org.quantumbadger.redreader'): cpackage = "adb shell am force-stop " + cpackage os.popen(cpackage)
[ "prefest2018@gmail.com" ]
prefest2018@gmail.com
39657f18a60d6a07a7a1e0bfb3a58854408a6032
bb33e6be8316f35decbb2b81badf2b6dcf7df515
/source/res/scripts/client/gui/impl/gen/view_models/views/lobby/tank_setup/sub_views/battle_ability_by_rank_model.py
87375e758b4042c2f99e94cf2b6b6b3daa6b9bcb
[]
no_license
StranikS-Scan/WorldOfTanks-Decompiled
999c9567de38c32c760ab72c21c00ea7bc20990c
d2fe9c195825ececc728e87a02983908b7ea9199
refs/heads/1.18
2023-08-25T17:39:27.718097
2022-09-22T06:49:44
2022-09-22T06:49:44
148,696,315
103
39
null
2022-09-14T17:50:03
2018-09-13T20:49:11
Python
UTF-8
Python
false
false
970
py
# Python bytecode 2.7 (decompiled from Python 2.7) # Embedded file name: scripts/client/gui/impl/gen/view_models/views/lobby/tank_setup/sub_views/battle_ability_by_rank_model.py from frameworks.wulf import Array from frameworks.wulf import ViewModel class BattleAbilityByRankModel(ViewModel): __slots__ = () def __init__(self, properties=2, commands=0): super(BattleAbilityByRankModel, self).__init__(properties=properties, commands=commands) def getName(self): return self._getString(0) def setName(self, value): self._setString(0, value) def getRankValues(self): return self._getArray(1) def setRankValues(self, value): self._setArray(1, value) @staticmethod def getRankValuesType(): return str def _initialize(self): super(BattleAbilityByRankModel, self)._initialize() self._addStringProperty('name', '') self._addArrayProperty('rankValues', Array())
[ "StranikS_Scan@mail.ru" ]
StranikS_Scan@mail.ru
bce95d31c8695ad1fa989acb3e2073da221c378f
1876bd32763cf34b2856067a3efc513043d4c7c8
/test_graph/test_ping_an.py
d8f0c7e4d2f55a909c09abcdc0820536f3f395e1
[]
no_license
chntylz/a_stock
fdc40b7ab71551246c47636a0c3e81de03b46bb6
ed6e627941c580e353c0255027b18ebd9a8b7367
refs/heads/master
2023-09-01T17:32:32.427766
2020-04-30T08:11:32
2020-04-30T08:11:32
181,991,066
0
0
null
null
null
null
UTF-8
Python
false
false
1,508
py
#!/usr/bin/env python # -*- coding: utf-8 -*- import matplotlib as mpl mpl.use('Agg') import matplotlib.pyplot as plt import numpy as np import sys reload(sys) #sys.setdefaultencoding('utf-8') sys.setdefaultencoding("ISO-8859-1") #先引入后面分析、可视化等可能用到的库 import tushare as ts import pandas as pd import matplotlib.pyplot as plt #正常显示画图时出现的中文和负号 from pylab import mpl mpl.rcParams['font.sans-serif']=['SimHei'] mpl.rcParams['axes.unicode_minus']=False #设置token token='21dddafc47513ea46b89057b2c4edf7b44882b3e92274b431f199552' #ts.set_token(token) pro = ts.pro_api(token) #获取当前上市的股票代码、简称、注册地、行业、上市时间等数据 basic=pro.stock_basic(list_status='L') #查看前五行数据 #basic.head(5) #获取平安银行日行情数据 pa=pro.daily(ts_code='000001.SZ', start_date='20190101', end_date='20190508') #pa.head() #K线图可视化 from pyecharts import Kline pa.index=pd.to_datetime(pa.trade_date) pa=pa.sort_index() v1=list(pa.loc[:,['open','close','low','high']].values) t=pa.index v0=list(t.strftime('%Y%m%d')) kline = Kline("平安银行K线图",title_text_size=15) kline.add("", v0, v1,is_datazoom_show=True, mark_line=["average"], mark_point=["max", "min"], mark_point_symbolsize=60, mark_line_valuedim=['highest', 'lowest'] ) kline.render("平安银行.html") kline #plt.savefig("/home/aaron/aaron/test_graph/test.jpg")
[ "you@example.com" ]
you@example.com
de256567ccbf150b172472ffc6149f20b4a0731a
98b63e3dc79c75048163512c3d1b71d4b6987493
/tensorflow/compiler/mlir/tfr/define_op_template.py
c0db2981d2d94a0038a84163cbce6046af8101db
[ "Apache-2.0" ]
permissive
galeone/tensorflow
11a4e4a3f42f4f61a65b432c429ace00401c9cc4
1b6f13331f4d8e7fccc66bfeb0b066e77a2b7206
refs/heads/master
2022-11-13T11:56:56.143276
2020-11-10T14:35:01
2020-11-10T14:35:01
310,642,488
21
12
Apache-2.0
2020-11-06T16:01:03
2020-11-06T16:01:02
null
UTF-8
Python
false
false
2,035
py
# Copyright 2020 The TensorFlow Authors. All Rights Reserved. # # 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 # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """A template to define composite ops.""" # pylint: disable=g-direct-tensorflow-import from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import sys from tensorflow.compiler.mlir.tfr.python.composite import Composite from tensorflow.compiler.mlir.tfr.python.op_reg_gen import gen_register_op from tensorflow.compiler.mlir.tfr.python.tfr_gen import tfr_gen_from_module from tensorflow.python.platform import app from tensorflow.python.platform import flags FLAGS = flags.FLAGS flags.DEFINE_string( 'output', None, 'Path to write the genereated register op file and MLIR file.') flags.DEFINE_bool('gen_register_op', True, 'Generate register op cc file or tfr mlir file.') flags.mark_flag_as_required('output') @Composite('TestRandom', derived_attrs=['T: numbertype'], outputs=['o: T']) def _composite_random_op(): pass def main(_): if FLAGS.gen_register_op: assert FLAGS.output.endswith('.cc') generated_code = gen_register_op(sys.modules[__name__], '_composite_') else: assert FLAGS.output.endswith('.mlir') generated_code = tfr_gen_from_module(sys.modules[__name__], '_composite_') dirname = os.path.dirname(FLAGS.output) if not os.path.exists(dirname): os.makedirs(dirname) with open(FLAGS.output, 'w') as f: f.write(generated_code) if __name__ == '__main__': app.run(main=main)
[ "gardener@tensorflow.org" ]
gardener@tensorflow.org
251b5275354616a26f43a0708768174bcecb4e68
e6aace98e7b21cbdd1019b7323c11ebc41217af7
/Django/api1203/lxzapi/serializers.py
cdaaaad110bd8b4480a6ce5ae9f48bf2633a2495
[]
no_license
robinlxz/Python_excercise
8f61e41614755c01b0a523db4caa1b78e31f28e2
db0daf0da5b45067d70daf285271a3f7c2d4f55f
refs/heads/master
2021-06-29T16:59:35.902048
2020-10-05T07:38:03
2020-10-05T07:38:03
152,209,939
0
0
null
null
null
null
UTF-8
Python
false
false
189
py
from rest_framework import serializers from lxzapi.models import Lead class LeadSerializer(serializers.ModelSerializer): class Meta: model = Lead fields = ('id', 'name', 'email')
[ "linxz@garena.com" ]
linxz@garena.com
f3410b1a32f31f521ac07230f9185f5d98a9d39c
195cdab2f180ced13b0e4c097ab75a565a5eb1d7
/fhir/resources/basic.py
9c0718f03af5b134957b7eecd6549684507676be
[ "BSD-3-Clause" ]
permissive
chgl/fhir.resources
18166d7297a23ef0c144023fb5ba1d46b7bd2527
35b22314642640c0b25960ab5b2855e7c51749ef
refs/heads/master
2023-03-09T08:16:38.287970
2021-02-13T11:10:03
2021-02-13T11:10:03
341,916,191
0
0
NOASSERTION
2021-02-24T13:52:58
2021-02-24T13:52:58
null
UTF-8
Python
false
false
3,007
py
# -*- coding: utf-8 -*- """ Profile: http://hl7.org/fhir/StructureDefinition/Basic Release: R4 Version: 4.0.1 Build ID: 9346c8cc45 Last updated: 2019-11-01T09:29:23.356+11:00 """ import typing from pydantic import Field from . import domainresource, fhirtypes class Basic(domainresource.DomainResource): """Disclaimer: Any field name ends with ``__ext`` does't part of Resource StructureDefinition, instead used to enable Extensibility feature for FHIR Primitive Data Types. Resource for non-supported content. Basic is used for handling concepts not yet defined in FHIR, narrative-only resources that don't map to an existing resource, and custom resources not appropriate for inclusion in the FHIR specification. """ resource_type = Field("Basic", const=True) author: fhirtypes.ReferenceType = Field( None, alias="author", title="Who created", description="Indicates who was responsible for creating the resource instance.", # if property is element of this resource. element_property=True, # note: Listed Resource Type(s) should be allowed as Reference. enum_reference_types=[ "Practitioner", "PractitionerRole", "Patient", "RelatedPerson", "Organization", ], ) code: fhirtypes.CodeableConceptType = Field( ..., alias="code", title="Kind of Resource", description=( "Identifies the 'type' of resource - equivalent to the resource name " "for other resources." ), # if property is element of this resource. element_property=True, ) created: fhirtypes.Date = Field( None, alias="created", title="When created", description="Identifies when the resource was first created.", # if property is element of this resource. element_property=True, ) created__ext: fhirtypes.FHIRPrimitiveExtensionType = Field( None, alias="_created", title="Extension field for ``created``." ) identifier: typing.List[fhirtypes.IdentifierType] = Field( None, alias="identifier", title="Business identifier", description=( "Identifier assigned to the resource for business purposes, outside the" " context of FHIR." ), # if property is element of this resource. element_property=True, ) subject: fhirtypes.ReferenceType = Field( None, alias="subject", title="Identifies the focus of this resource", description=( "Identifies the patient, practitioner, device or any other resource " 'that is the "focus" of this resource.' ), # if property is element of this resource. element_property=True, # note: Listed Resource Type(s) should be allowed as Reference. enum_reference_types=["Resource"], )
[ "connect2nazrul@gmail.com" ]
connect2nazrul@gmail.com
189b517adaf6ebba2d2200dec87b89e935717efe
f07a42f652f46106dee4749277d41c302e2b7406
/Data Set/bug-fixing-5/e4ea999e6dc842e98c29787cac4b7c7c24a565ee-<what_provides>-fix.py
0b8464873610e33bcb099043f535f690142b8227
[]
no_license
wsgan001/PyFPattern
e0fe06341cc5d51b3ad0fe29b84098d140ed54d1
cc347e32745f99c0cd95e79a18ddacc4574d7faa
refs/heads/main
2023-08-25T23:48:26.112133
2021-10-23T14:11:22
2021-10-23T14:11:22
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,856
py
def what_provides(module, repoq, req_spec, conf_file, qf=def_qf, en_repos=None, dis_repos=None, installroot='/'): if (en_repos is None): en_repos = [] if (dis_repos is None): dis_repos = [] if (not repoq): pkgs = [] try: my = yum_base(conf_file, installroot) for rid in dis_repos: my.repos.disableRepo(rid) for rid in en_repos: my.repos.enableRepo(rid) pkgs = (my.returnPackagesByDep(req_spec) + my.returnInstalledPackagesByDep(req_spec)) if (not pkgs): (e, m, u) = my.pkgSack.matchPackageNames([req_spec]) pkgs.extend(e) pkgs.extend(m) (e, m, u) = my.rpmdb.matchPackageNames([req_spec]) pkgs.extend(e) pkgs.extend(m) except Exception: e = get_exception() module.fail_json(msg=('Failure talking to yum: %s' % e)) return set([po_to_envra(p) for p in pkgs]) else: myrepoq = list(repoq) r_cmd = ['--disablerepo', ','.join(dis_repos)] myrepoq.extend(r_cmd) r_cmd = ['--enablerepo', ','.join(en_repos)] myrepoq.extend(r_cmd) cmd = (myrepoq + ['--qf', qf, '--whatprovides', req_spec]) (rc, out, err) = module.run_command(cmd) cmd = (myrepoq + ['--qf', qf, req_spec]) (rc2, out2, err2) = module.run_command(cmd) if ((rc == 0) and (rc2 == 0)): out += out2 pkgs = set([p for p in out.split('\n') if p.strip()]) if (not pkgs): pkgs = is_installed(module, repoq, req_spec, conf_file, qf=qf, installroot=installroot) return pkgs else: module.fail_json(msg=('Error from repoquery: %s: %s' % (cmd, (err + err2)))) return set()
[ "dg1732004@smail.nju.edu.cn" ]
dg1732004@smail.nju.edu.cn
ca84877336a32ce13eaf58fb125401a9b9585a26
2186fdd8350d6dc72340a65c2cc1d345c2c51377
/Python/Flask_MySQL/Friends/server.py
c6d0d7572c413d617edf8c5558b82bb6a7236a32
[]
no_license
umanav/Lab206
2b494712b59585493e74c51089223696729eb716
31f0b098aa6722bbf7d2ad6e619fa38f29cab4d5
refs/heads/master
2020-03-10T07:54:25.904503
2018-04-12T15:37:20
2018-04-12T15:37:20
129,273,399
0
0
null
null
null
null
UTF-8
Python
false
false
2,727
py
from flask import Flask, request, redirect, render_template, session, flash from mysqlconnection import MySQLConnector app = Flask(__name__) mysql = MySQLConnector(app,'friendsdb') # PRINT THE RESULTS # @app.route('/') # def index(): # friends = mysql.query_db("SELECT * FROM friends") # print friends # return render_template('index.html') # DISPLAY THE RESULTS @app.route('/') def index(): query = "SELECT * FROM friends" # define your query friends = mysql.query_db(query) # run query with query_db() return render_template('index.html', all_friends=friends) # pass data to our template @app.route('/friends', methods=['POST']) def create(): # Write query as a string. Notice how we have multiple values # we want to insert into our query. query = "INSERT INTO friends (first_name, last_name, occupation, created_at, updated_at) VALUES (:first_name, :last_name, :occupation, NOW(), NOW())" # We'll then create a dictionary of data from the POST data received. data = { 'first_name': request.form['first_name'], 'last_name': request.form['last_name'], 'occupation': request.form['occupation'] } # Run query, with dictionary values injected into the query. mysql.query_db(query, data) return redirect('/') @app.route('/friends/<friend_id>') def show(friend_id): # Write query to select specific user by id. At every point where # we want to insert data, we write ":" and variable name. query = "SELECT * FROM friends WHERE id = :specific_id" # Then define a dictionary with key that matches :variable_name in query. data = {'specific_id': friend_id} # Run query with inserted data. friends = mysql.query_db(query, data) # Friends should be a list with a single object, # so we pass the value at [0] to our template under alias one_friend. return render_template('index.html', one_friend=friends[0]) @app.route('/update_friend/<friend_id>', methods=['POST']) def update(friend_id): query = "UPDATE friends SET first_name = :first_name, last_name = :last_name, occupation = :occupation WHERE id = :id" data = { 'first_name': request.form['first_name'], 'last_name': request.form['last_name'], 'occupation': request.form['occupation'], 'id': friend_id } mysql.query_db(query, data) return redirect('/') @app.route('/remove_friend/<friend_id>', methods=['POST']) def delete(friend_id): query = "DELETE FROM friends WHERE id = :id" data = {'id': friend_id} mysql.query_db(query, data) return redirect('/') app.run(debug=True)
[ "umanav@amazon.com" ]
umanav@amazon.com
5440258e4b5db4b0b2b20ec4bdc62cac15833350
ba8e9235d5385d49d94be4347283e1a9550dc4ee
/progressivedme/commands/__init__.py
7fdfa3e2ebc21ab14900a8fccf89f89516dd6239
[ "Apache-2.0" ]
permissive
navdeepghai1/progressivedme
2e29340d782d6cc610fd42c13307b0328db0dfa4
092dc6581739d8c2a603a27f144f7849f44b7f6c
refs/heads/master
2020-10-02T03:39:57.746107
2020-01-09T19:57:43
2020-01-09T19:57:43
227,692,994
0
0
NOASSERTION
2019-12-12T20:47:11
2019-12-12T20:43:36
Python
UTF-8
Python
false
false
2,063
py
''' Developer Navdeep Email navdeepghai1@gmail.com ''' import frappe import click from frappe.commands import pass_context def connect_to_default_site(context): flag = False if(context.get("sites")): for site in context.get("sites") or []: if site == "progressivedme.com": frappe.init(site) frappe.connect() flag = True return flag @click.command() @click.argument("filename") @pass_context def read_data(context, filename): if(not connect_to_default_site(context)): print("Site not found") return from progressivedme.read_excel_data import read_csv_data update_subgroup(read_csv_data(context, filename)) frappe.db.commit() # COMMIT THE CHANGES def update_subgroup(data): for item in data: item_number = item.item_number minor_category = item.minor_category major_category = item.major_category if (item_number and minor_category and major_category and frappe.db.get_value("Item Group"), major_category): try: if(minor_category and not frappe.db.exists("Item Group", minor_category)): frappe.get_doc({ "item_group_name": minor_category, "parent_item_group": major_category, "doctype": "Item Group", }).save(ignore_permissions=True) if(frappe.db.exists("Item Group", minor_category)): frappe.db.sql("UPDATE `tabItem Group` SET is_group=1 WHERE name = '%s' "%(major_category)) frappe.db.sql(""" UPDATE `tabItem` SET item_group = '%s' WHERE name = '%s' """%(minor_category, item_number)) print("Item: %s, Updated"%(item_number)) except Exception as e: print("an error occurred while processing the item") print(e) else: print("Missing Information for Item: %s"%(item_number)) @click.command() @click.argument("filename") @pass_context def update_drop_ship_legend(context, filename): if(not connect_to_default_site(context)): print("Site not found") return from progressivedme.read_excel_data import read_csv_data data = read_csv_data(context, filename) print(data) commands = [read_data, update_drop_ship_legend]
[ "navdeepghai1@gmail.com" ]
navdeepghai1@gmail.com
0d60371386e984a6cd363da62cd98a73a2c2f095
d514a015b100c4c3a663056661e9c3c223c1c2a8
/common/models/food/FoodCat.py
e1be778c082c98e9bee7e8d49b5de60e261a3b54
[]
no_license
462548187/order
63f3c8f570a241772c3dcf003c811044a6f5ed9d
a62f386e7661bfd7e01253203f324da48c52a331
refs/heads/master
2022-07-31T00:52:38.225530
2020-05-20T17:01:14
2020-05-20T17:01:14
263,845,065
0
0
null
null
null
null
UTF-8
Python
false
false
940
py
# coding: utf-8 from sqlalchemy import Column, DateTime, Integer, String from sqlalchemy.schema import FetchedValue from application import app, db class FoodCat(db.Model): __tablename__ = 'food_cat' id = db.Column(db.Integer, primary_key=True, unique=True) name = db.Column(db.String(50), nullable=False, server_default=db.FetchedValue(), info='类别名称') weight = db.Column(db.Integer, nullable=False, server_default=db.FetchedValue(), info='权重') status = db.Column(db.Integer, nullable=False, server_default=db.FetchedValue(), info='状态 1:有效 0:无效') updated_time = db.Column(db.DateTime, nullable=False, server_default=db.FetchedValue(), info='最后一次更新时间') created_time = db.Column(db.DateTime, nullable=False, server_default=db.FetchedValue(), info='插入时间') @property def status_desc(self): return app.config['STATUS_MAPPING'][str(self.status)]
[ "462548187@qq.com" ]
462548187@qq.com
1dafd61647db62c55f7cab3f7b2b67df9151ca73
e3b9aa9b17ebb55e53dbc4fa9d1f49c3a56c6488
/sentinelone/komand_sentinelone/actions/create_ioc_threat/action.py
f7fa82914edb59417d74e5642644ea47ef481e01
[ "MIT" ]
permissive
OSSSP/insightconnect-plugins
ab7c77f91c46bd66b10db9da1cd7571dfc048ab7
846758dab745170cf1a8c146211a8bea9592e8ff
refs/heads/master
2023-04-06T23:57:28.449617
2020-03-18T01:24:28
2020-03-18T01:24:28
248,185,529
1
0
MIT
2023-04-04T00:12:18
2020-03-18T09:14:53
null
UTF-8
Python
false
false
903
py
import komand from .schema import CreateIocThreatInput, CreateIocThreatOutput, Input, Output # Custom imports below class CreateIocThreat(komand.Action): def __init__(self): super(self.__class__, self).__init__( name='create_ioc_threat', description='Create an IOC threat', input=CreateIocThreatInput(), output=CreateIocThreatOutput()) def run(self, params={}): hash_ = params.get(Input.HASH) group_id = params.get(Input.GROUP_ID) path = params.get(Input.PATH) agent_id = params.get(Input.AGENT_ID) annotation = params.get(Input.ANNOTATION) annotation_url = params.get(Input.ANNOTATION_URL) affected = self.connection.create_ioc_threat( hash_, group_id, path, agent_id, annotation, annotation_url ) return {Output.AFFECTED: affected}
[ "jonschipp@gmail.com" ]
jonschipp@gmail.com
6976e20d3a730322403f2a2a6ea9fee47588b3b0
72db92bc7f1794495c2bb4ed5451e9cb693b6489
/final_graduation/controller/__init__.py
6b18c921173f238552d4e84b7a56d72ace3b6060
[]
no_license
susautw/flask_restful
fcb00fdcfe2d2117c7da0d0c770c7241a26917b5
e75a8055178dc87a581530a815849d665ed7fda2
refs/heads/master
2022-12-27T13:45:29.533184
2020-05-24T17:22:37
2020-05-24T17:22:37
303,327,955
0
0
null
null
null
null
UTF-8
Python
false
false
454
py
__all__ = [ 'HelloWorld', 'CategoryController', 'CategoryItemController', 'JudgeController', 'JudgeItemController', 'ReportController', 'ReportItemController', 'ReportItemGetByIdController' ] from .hello_world import HelloWorld from .category import CategoryController, CategoryItemController from .judge import JudgeController, JudgeItemController from .report import ReportController, ReportItemController, ReportItemGetByIdController
[ "susautw@gmail.com" ]
susautw@gmail.com
4574101f29caeb4dfa9c8e02ea2cdb5c70071e7e
28bb1dda3010ab719ec537bcc63a5ed1491d148d
/modules training/pytest module/skip/test_operations.py
b959ac0ad729f7f434aa21162803736394df2bd3
[]
no_license
dawidsielski/Python-learning
86db2ff782aab13ff6dc44b1ce9295fc7c186e20
4aabf4d63906fb1d2379bbd401e9ac7484766198
refs/heads/master
2021-01-13T10:35:20.913601
2018-02-24T11:52:06
2018-02-24T11:52:06
76,497,517
0
0
null
null
null
null
UTF-8
Python
false
false
416
py
import operations import pytest import sys def test_multiplication(): result = operations.multiplication(3, 6) assert result == 18 @pytest.mark.skipif(sys.version_info > (3,0), reason = "No reason.") def test_subtraction(): result = operations.subtraction(3, 6) assert result == -3 @pytest.mark.skip(reason="Not working.") def test_power(): result = operations.power(6) assert result == 36
[ "dawid.sielski@outlook.com" ]
dawid.sielski@outlook.com
1b6d3309f1e02c969ec09a153c9f69930c87b997
4cca59f941adce8a2d71c00c0be5c06857f88dcc
/snisi_malaria/management/commands/fill_weekly_malaria_routine_cluster.py
3ba75446236dbd2e57ba4626718d7942092526bc
[ "MIT" ]
permissive
brahimmade/snisi
7e4ce8e35150f601dd7b800bc422edec2d13063d
b4d0292b3314023ec9c984b776eaa63a0a0a266f
refs/heads/master
2023-05-07T19:04:04.895987
2017-12-29T18:58:22
2017-12-29T18:58:22
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,042
py
#!/usr/bin/env python # -*- coding: utf-8 -*- # vim: ai ts=4 sts=4 et sw=4 nu from __future__ import (unicode_literals, absolute_import, division, print_function) import logging from django.core.management.base import BaseCommand from snisi_core.models.Entities import Entity from snisi_core.models.Projects import Cluster, Participation logger = logging.getLogger(__name__) class Command(BaseCommand): def handle(self, *args, **options): mali = Entity.get_or_none("mali") drmopti = Entity.get_or_none("SSH3") dsmopti = Entity.get_or_none("HFD9") dsbandiagara = Entity.get_or_none("MJ86") cluster = Cluster.get_or_none("malaria_weekly_routine") for entity in [mali, drmopti, dsmopti, dsbandiagara] + \ dsmopti.get_health_centers() + \ dsbandiagara.get_health_centers(): p, created = Participation.objects.get_or_create( cluster=cluster, entity=entity) logger.info(p)
[ "rgaudin@gmail.com" ]
rgaudin@gmail.com
2e321e21034ad3f0f4e81b8f9b084ca31166a941
e8a50e2e9f103fbf334b098fb6553c02f5516c4a
/computational_problems_for_physics/original_scripts/LaplaceLineClassic.py
093788247d2f8e49c7eef78d09b66e687a579607
[]
no_license
tomasderner97/pythonPlayground
f31f08caf690bb36d8424d3537412c767813d632
9fd8e3e77d40a46e1b103cd81a884add7e2edacf
refs/heads/master
2022-06-19T05:23:34.097485
2019-11-16T17:37:36
2019-11-16T17:37:36
205,404,983
0
0
null
null
null
null
UTF-8
Python
false
false
1,611
py
""" From "COMPUTATIONAL PHYSICS" & "COMPUTER PROBLEMS in PHYSICS" by RH Landau, MJ Paez, and CC Bordeianu (deceased) Copyright R Landau, Oregon State Unv, MJ Paez, Univ Antioquia, C Bordeianu, Univ Bucharest, 2018. Please respect copyright & acknowledge our work.""" # LaplaceLine.py: Solve Laplace's eqtn within square import matplotlib.pylab as p, numpy from mpl_toolkits.mplot3d import Axes3D; from numpy import *; Nmax = 100; Niter = 50 V = zeros((Nmax, Nmax), float) print ("Working hard, wait for the figure while I count to 60") for k in range(0, Nmax-1): V[0,k] = 100.0 # Line at 100V for iter in range(Niter): if iter%10 == 0: print(iter) for i in range(1, Nmax-2): for j in range(1,Nmax-2): V[i,j] = 0.25*(V[i+1,j]+V[i-1,j]+V[i,j+1]+V[i,j-1]) print ("iter, V[Nmax/5,Nmax/5]", iter, V[Nmax/5,Nmax/5]) x = range(0, 50, 2); y = range(0, 50, 2) X, Y = p.meshgrid(x,y) def functz(V): # V(x, y) z = V[X,Y] return z Z = functz(V) fig = p.figure() # Create figure ax = Axes3D(fig) # Plot axes ax.plot_wireframe(X, Y, Z, color = 'r') # Red wireframe ax.set_xlabel('X'); ax.set_ylabel('Y'); ax.set_zlabel('V(x,y)') ax.set_title('Potential within Square V(x=0)=100V (Rotatable)') p.show() # Show fig
[ "tomasderner97@gmail.com" ]
tomasderner97@gmail.com
fa929497b064b9f9f3f57c5241da5dfd48cf522a
e06ff08424324ac5d6c567ae9cd6954290ff9bd4
/Yudi TANG/axe/test.py
da887d8005b51052b5cd4f52c00ac472daa0fb3a
[ "Apache-2.0" ]
permissive
JKChang2015/Machine_Learning
b1bdfcf9ea43a98fc7efd5c0624bbaf5d9dbf495
f8b46bf23e4d1972de6bd652dd4286e9322ed62f
refs/heads/master
2021-06-06T19:18:16.596549
2020-05-03T22:28:18
2020-05-03T22:28:18
119,390,891
1
1
null
null
null
null
UTF-8
Python
false
false
865
py
# test # Created by JKChang # 27/01/2020, 15:58 # Tag: # Description: from numpy import * import operator from os import listdir import matplotlib.pyplot as plt # simulating a pandas df['type'] column types = ['apple', 'orange', 'apple', 'pear', 'apple', 'orange', 'apple', 'pear'] x_coords = [10, 10, 5, 4, 3, 20, 19, 21] y_coords = [21, 23, 12, 21, 10, 20, 14, 2] for i, type in enumerate(types): x = x_coords[i] y = y_coords[i] plt.scatter(x, y, marker='x', color='red') plt.text(x + 0.3, y + 0.3, type, fontsize=9) plt.show() # group, labels = createDataSet() # # for column,label in zip(group,labels): # plt.plot(group , label=label) # # plt.legend() # plt.show() # arr = np.random.random((10, 5)) # ax.plot(arr) # # labels = ['a', 'b', 'c', 'd', 'e'] # # for column, label in zip(arr.T, labels): # ax.plot(column, label=label)
[ "jkchang2015@gmail.com" ]
jkchang2015@gmail.com
9304fb73892afe0c84d3f342cf34ecb6c5b2d312
d66818f4b951943553826a5f64413e90120e1fae
/hackerearth/Algorithms/Explosion/test.py
7f78871afb936c2a532f802823073955ecf4efd1
[ "MIT" ]
permissive
HBinhCT/Q-project
0f80cd15c9945c43e2e17072416ddb6e4745e7fa
19923cbaa3c83c670527899ece5c3ad31bcebe65
refs/heads/master
2023-08-30T08:59:16.006567
2023-08-29T15:30:21
2023-08-29T15:30:21
247,630,603
8
1
MIT
2020-07-22T01:20:23
2020-03-16T06:48:02
Python
UTF-8
Python
false
false
581
py
import io import unittest from contextlib import redirect_stdout from unittest.mock import patch class TestQ(unittest.TestCase): @patch('builtins.input', side_effect=[ '2', '2', '2 1', '3', '2 1', '2 3', ]) def test_case_0(self, input_mock=None): text_trap = io.StringIO() with redirect_stdout(text_trap): import solution self.assertEqual(text_trap.getvalue(), 'UNSAFE\n' + 'SAFE\n') if __name__ == '__main__': unittest.main()
[ "hbinhct@gmail.com" ]
hbinhct@gmail.com
0e220f57e549f2acbf6ade6fbf1671507ebdaed0
108e221a0220c9124af9407bc2541e44cbca10d0
/website/app/backstage/sidebar/forms.py
a91af70ca7fc54545daf72b4bd0b331409f1869f
[]
no_license
yatengLG/website
a7cf50f85d320d4985c665bb6422d4b1ac1ec273
41bff84577db5ba927c47cd96e0b42672be05974
refs/heads/master
2023-02-01T01:27:11.763924
2020-12-10T07:55:52
2020-12-10T07:55:52
320,195,848
2
0
null
null
null
null
UTF-8
Python
false
false
795
py
# -*- coding: utf-8 -*- # @Author : LG from flask_wtf import FlaskForm from wtforms import TextField, TextAreaField, SubmitField, SelectField from wtforms.validators import Required, Length class SidebarEditForm(FlaskForm): title =TextField('侧栏头', validators=[Required(message='标题为空'), Length(1, 40, message='1-40个字符')], render_kw={'placeholder' : '侧栏头','style':'width: 383px'}) body = TextAreaField('内容(可编辑html源码的方式添加样式)', id = 'full-featured', render_kw={'style':'width: 383px'}) forbid = SelectField('禁用', choices=[ (1, '是'), (0, '否') ],default=0, render_kw={'style':'width: 200px'}, coerce=int) # 这里传入的是int型, 但是后端接收是bool型。 submit = SubmitField('提交')
[ "767624851@qq.com" ]
767624851@qq.com
e7ddcc04a4cd02a12969fb3821668ff2565a8b0b
ea71ac18939e99c1295506d3e3808bb76daabc84
/.venv35/Lib/site-packages/PyInstaller/hooks/hook-eth_keyfile.py
8d6cebc7f73c6c906d985694f476769f8b991c5e
[ "GPL-1.0-or-later", "LicenseRef-scancode-unknown-license-reference", "BSD-3-Clause" ]
permissive
ndaley7/BodySlide-Group-Generator
543ef48b4dfe58953b0694b2941c9131d5f4caef
3ed7b78c5f5ccec103b6bf06bc24398cfb6ad014
refs/heads/master
2020-08-26T17:44:38.768274
2019-12-10T19:01:23
2019-12-10T19:01:23
217,089,038
2
0
BSD-3-Clause
2019-12-10T19:02:29
2019-10-23T15:18:10
Python
UTF-8
Python
false
false
497
py
#----------------------------------------------------------------------------- # Copyright (c) 2018-2019, PyInstaller Development Team. # # Distributed under the terms of the GNU General Public License with exception # for distributing bootloader. # # The full license is in the file COPYING.txt, distributed with this software. #----------------------------------------------------------------------------- from PyInstaller.utils.hooks import copy_metadata datas = copy_metadata("eth_keyfile")
[ "ndaley7@gatech.edu" ]
ndaley7@gatech.edu
e9c9645fd7e37b0628d58973343ce1191da676e8
3b3b86495f9db3f6ff5ded987cf7ed26c32baea2
/Atividade 6 e 8/libraryon_api/books/migrations/0001_initial.py
edf594ee019fc7cccb708ac8c42629414c9014a1
[]
no_license
Akijunior/Top_Especiais_APIs
445b9e324588d1ea1806232bde39219da0cd8606
92434bb7f7aea300c6e6081502bb3dc672136ecb
refs/heads/master
2022-12-11T16:59:57.318030
2018-09-04T17:22:58
2018-09-04T17:22:58
131,898,317
0
0
null
2022-12-08T02:23:26
2018-05-02T19:44:22
Python
UTF-8
Python
false
false
2,157
py
# Generated by Django 2.0.3 on 2018-06-22 19:59 import django.core.validators from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Book', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('title', models.CharField(max_length=150)), ('description', models.CharField(max_length=400)), ('isbn', models.CharField(max_length=20)), ('edition', models.CharField(max_length=20)), ('year', models.IntegerField()), ('amount_pages', models.IntegerField()), ('price', models.DecimalField(decimal_places=2, max_digits=5)), ], ), migrations.CreateModel( name='Genre', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=50)), ('description', models.CharField(max_length=150)), ('age_range', models.CharField(choices=[('F', 'Free'), ('FT', '+14'), ('ST', '+16'), ('ET', '+18')], default='F', max_length=2)), ], ), migrations.CreateModel( name='Score', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('score', models.DecimalField(decimal_places=2, max_digits=4, validators=[django.core.validators.MaxValueValidator(10.0), django.core.validators.MinValueValidator(0.0)])), ('comment', models.CharField(blank=True, max_length=200)), ('evaluation_date', models.DateTimeField(auto_now_add=True)), ('last_update_date', models.DateTimeField(auto_now=True)), ('book', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='books.Book')), ], ), ]
[ "suitsu19@gmail.com" ]
suitsu19@gmail.com
d345e2d11c7636f9ad4ce919478b7a3066a5efda
f07a42f652f46106dee4749277d41c302e2b7406
/Data Set/bug-fixing-5/1d0bab0bfd77edcf1228d45bf654457a8ff1890d-<constant_time_compare>-fix.py
9b1c685835c714b8498ff31c245947c99850f822
[]
no_license
wsgan001/PyFPattern
e0fe06341cc5d51b3ad0fe29b84098d140ed54d1
cc347e32745f99c0cd95e79a18ddacc4574d7faa
refs/heads/main
2023-08-25T23:48:26.112133
2021-10-23T14:11:22
2021-10-23T14:11:22
null
0
0
null
null
null
null
UTF-8
Python
false
false
175
py
def constant_time_compare(val1, val2): 'Return True if the two strings are equal, False otherwise.' return secrets.compare_digest(force_bytes(val1), force_bytes(val2))
[ "dg1732004@smail.nju.edu.cn" ]
dg1732004@smail.nju.edu.cn
f8eec7478f8d5f48879bc662741b59a3fae2838e
4e710abfd764090c9f04156d0c6f6014144b13a8
/asv_bench/benchmarks/commit_and_checkout.py
859280bbf87e55a31726d3d68e5cc8aa17938b99
[ "Apache-2.0" ]
permissive
hhsecond/hangar-py
2bbb7834e24620fcf13039165846f7f1a00c5253
f335834c784ba6419e8cddd0f1b48ac317270747
refs/heads/master
2021-07-07T19:48:32.796724
2020-09-01T21:16:20
2020-09-01T21:16:20
183,601,108
0
0
Apache-2.0
2019-04-26T09:35:17
2019-04-26T09:35:16
null
UTF-8
Python
false
false
2,707
py
from tempfile import mkdtemp from shutil import rmtree import numpy as np from hangar import Repository class MakeCommit(object): params = (5_000, 20_000, 50_000) param_names = ['num_samples'] processes = 2 repeat = (2, 4, 20) number = 1 warmup_time = 0 def setup(self, num_samples): self.tmpdir = mkdtemp() self.repo = Repository(path=self.tmpdir, exists=False) self.repo.init('tester', 'foo@test.bar', remove_old=True) self.co = self.repo.checkout(write=True) arr = np.array([0,], dtype=np.uint8) try: aset = self.co.arraysets.init_arrayset('aset', prototype=arr, backend_opts='10') except TypeError: aset = self.co.arraysets.init_arrayset('aset', prototype=arr, backend='10') except AttributeError: aset = self.co.add_ndarray_column('aset', prototype=arr, backend='10') with aset as cm_aset: for i in range(num_samples): arr[:] = i % 255 cm_aset[i] = arr def teardown(self, num_samples): self.co.close() self.repo._env._close_environments() rmtree(self.tmpdir) def time_commit(self, num_samples): self.co.commit('hello') class CheckoutCommit(object): params = (5_000, 20_000, 50_000) param_names = ['num_samples'] processes = 2 number = 1 repeat = (2, 4, 20) warmup_time = 0 def setup(self, num_samples): self.tmpdir = mkdtemp() self.repo = Repository(path=self.tmpdir, exists=False) self.repo.init('tester', 'foo@test.bar', remove_old=True) self.co = self.repo.checkout(write=True) arr = np.array([0,], dtype=np.uint8) try: aset = self.co.arraysets.init_arrayset('aset', prototype=arr, backend_opts='10') except TypeError: aset = self.co.arraysets.init_arrayset('aset', prototype=arr, backend='10') except AttributeError: aset = self.co.add_ndarray_column('aset', prototype=arr, backend='10') with aset as cm_aset: for i in range(num_samples): arr[:] = i % 255 cm_aset[i] = arr self.co.commit('first') self.co.close() self.co = None def teardown(self, num_samples): try: self.co.close() except PermissionError: pass self.repo._env._close_environments() rmtree(self.tmpdir) def time_checkout_read_only(self, num_samples): self.co = self.repo.checkout(write=False) def time_checkout_write_enabled(self, num_samples): self.co = self.repo.checkout(write=True) self.co.close()
[ "rizzo242@gmail.com" ]
rizzo242@gmail.com
665e9938694a57e885a85eef83a2d23819f66f99
8a94de4c3cf8725e7a5a627777d31f43e4ad73f2
/easy/subtree-of-another-tree.py
d1abaeee86a0e1188631eb55ba0830a046a3d2f9
[]
no_license
zhangzhao156/Basic-Algorithm
a873101fae8e8c750cdab41c60ce4734348bab27
c7f6d176b22cdbd66635d437b4bda8eb36412da3
refs/heads/master
2023-02-10T01:14:12.599898
2021-01-05T14:09:27
2021-01-05T14:09:27
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,467
py
# encoding:utf-8 """ 问题描述: s= 3 / \ 4 5 / \ 1 2 t= 4 / \ 1 2 解决方案: 辅助函数isMatch是判断两个树结构是否完全一致,可以判断s和t是否完全一致, 判断的条件是: s.val == t.val and self.isMatch(s.left, t.left) and self.isMatch(s.right, t.right) 或者判断s的子树(左右)是否和t一致 """ # Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None # 递归的方法 class Solution(object): def isSubtree(self, s, t): """ :type s: TreeNode :type t: TreeNode :rtype: bool """ if self.isMatch(s,t): return True if not s: return False # 上面的isMatch是s和t的全匹配,如果无法全匹配的话,看s的左右子树可不可以全匹配 return self.isSubtree(s.left, t) or self.isSubtree(s.right, t) def isMatch(self, s,t): if not (s and t): return s is t return s.val == t.val and self.isMatch(s.left, t.left) and self.isMatch(s.right, t.right) if __name__ == "__main__": solve = Solution() s = TreeNode(3) s.left = TreeNode(4) s.right = TreeNode(5) s.left.left = TreeNode(1) s.left.right = TreeNode(2) t = TreeNode(4) t.left = TreeNode(1) t.right = TreeNode(2) print(solve.isSubtree(s,t))
[ "congyingTech@163.com" ]
congyingTech@163.com
e45353acbf97e93eed682637eebfc676ada85ca1
bc4688c02d16c4f786f0ea835f9e1a7e45272090
/cnn/keras/full_scan/train3.py
0def1b864d221fbe894d89a03581e7a3e02c49ec
[]
no_license
mhubrich/adni-python
4e3fb24e216fb908eb2426b2fc90482431f3494d
21e14e4cb5ab8edf33deff7fbe2494bbc396ea35
refs/heads/master
2021-06-15T02:04:00.435915
2017-02-28T14:25:23
2017-02-28T14:25:23
69,449,927
1
0
null
null
null
null
UTF-8
Python
false
false
2,854
py
############################################################## # Set seed for determinisitc behaviour between different runs. # Especially fresh weights will be initialized the same way. # Caution: CudNN might not be deterministic after all. SEED = 0 import numpy as np np.random.seed(SEED) ############################################################## from cnn.keras import callbacks from cnn.keras.evaluation_callback2 import Evaluation from cnn.keras.models.AVG444.model_normal import build_model from utils.split_scans import read_imageID from utils.sort_scans import sort_groups import sys fold = str(sys.argv[1]) # Training specific parameters target_size = (22, 22, 22) classes = ['Normal', 'AD'] batch_size = 32 load_all_scans = True num_epoch = 5000 # Paths path_ADNI = '/home/mhubrich/ADNI_intnorm_avgpool444_new' path_checkpoints = '/home/mhubrich/checkpoints/adni/full_scan_3_CV' + fold def load_data(scans): groups, _ = sort_groups(scans) nb_samples = 0 for c in classes: assert groups[c] is not None, \ 'Could not find class %s' % c nb_samples += len(groups[c]) X = np.zeros((nb_samples, 1, ) + target_size, dtype=np.float32) y = np.zeros(nb_samples, dtype=np.int32) i = 0 for c in classes: for scan in groups[c]: X[i] = np.load(scan.path) y[i] = 0 if scan.group == classes[0] else 1 i += 1 return X, y def train(): # Get inputs for training and validation scans_train = read_imageID(path_ADNI, '/home/mhubrich/ADNI_CV_mean2/' + fold + '_train') x_train, y_train = load_data(scans_train) scans_val = read_imageID(path_ADNI, '/home/mhubrich/ADNI_CV_mean2/' + fold + '_val') x_val, y_val = load_data(scans_val) # Set up the model model = build_model() model.compile(loss='binary_crossentropy', optimizer='rmsprop', metrics=['accuracy']) # Define callbacks cbks = [callbacks.print_history(), callbacks.flush(), Evaluation(x_val, y_val, batch_size, [callbacks.early_stop(patience=60, monitor=['val_loss', 'val_acc', 'val_fmeasure', 'val_mcc', 'val_mean_acc']), callbacks.save_model(path_checkpoints, max_files=2, monitor=['val_loss', 'val_acc', 'val_fmeasure', 'val_mcc', 'val_mean_acc'])])] g, _ = sort_groups(scans_train) hist = model.fit(x=x_train, y=y_train, nb_epoch=num_epoch, callbacks=cbks, class_weight={0:max(len(g['Normal']), len(g['AD']))/float(len(g['Normal'])), 1:max(len(g['Normal']), len(g['AD']))/float(len(g['AD']))}, batch_size=batch_size, shuffle=True, verbose=2) if __name__ == "__main__": train()
[ "mhubrich@students.uni-mainz.de" ]
mhubrich@students.uni-mainz.de
84caab557c5fac7436bf9d9ddb18f9e229944dcb
1b19103c7781c31b4042e5404eea46fa90014a70
/cenit_admin_reports_api_reports_v1/__openerp__.py
d82da022f0a193cef1f12719b5f329e4a29d3dac
[]
no_license
andhit-r/odoo-integrations
c209797d57320f9e49271967297d3a199bc82ff5
dee7edc4e9cdcc92e2a8a3e9c34fac94921d32c0
refs/heads/8.0
2021-01-12T05:52:26.101701
2016-12-22T03:06:52
2016-12-22T03:06:52
77,223,257
0
1
null
2016-12-23T12:11:08
2016-12-23T12:11:08
null
UTF-8
Python
false
false
1,582
py
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010, 2014 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## { 'name': 'Admin_reports_api_reports_v1 Integration', 'version': '0.1', 'author': 'Cenit IO', 'website': 'https://cenit.io', # ~ 'license': 'LGPL-3', 'category': 'Extra Tools', 'summary': "Allows the administrators of Google Apps customers to fetch reports about the usage, collaboration, security and risk for their users.", 'description': """ Odoo - Admin_reports_api_reports_v1 integration via Cenit IO """, 'depends': ['cenit_base'], 'data': [ 'security/ir.model.access.csv', 'data/data.xml' ], 'installable': True }
[ "sanchocuba@gmail.com" ]
sanchocuba@gmail.com
7ac13b1a6697470865d91e38fa08dbd5db14ff75
451548e5ec5d84606b0769efc7c6b619e5a8dd68
/encryptor/__init__.py
f741f62be6fff85804947257abbfdb12e15408d1
[]
no_license
nttlong/lv-open-edx
085309886e2196dd975bd2900016af334dad9987
b676f2438ce7658a8a3f515fb9d071a66b30ee6f
refs/heads/master
2021-04-09T16:32:27.572555
2018-08-10T11:21:16
2018-08-10T11:21:16
125,824,191
0
0
null
null
null
null
UTF-8
Python
false
false
3,375
py
""" The encryptor packahe support encrypt an decrypt text with mongodb sync collection """ _cache={} _cache_revert={} import re from pymongo import MongoClient import datetime import logging import threading import uuid logger = logging.getLogger(__name__) global lock lock = threading.Lock() _coll=None _db=None _collection_name=None def set_config(*args,**kwargs): """ Set database connction for encrypt data sync :param args:including "host(mongodb server hosting)","port","name" (Database name),"collection" (the collection of encrypt data :param kwargs: :return: """ global _coll global _db global _collection_name if type(args) is tuple and args.__len__()>0: args=args[0] else: args=kwargs if not args.has_key("host"): raise Exception("'host' was not found") if not args.has_key("port"): raise Exception("'port' was not found") if not args.has_key("name"): raise Exception("'name' was not found") if not args.has_key("collection"): raise Exception("'collection' was not found") if _coll==None: cnn=MongoClient(host=args["host"],port=args["port"]) _db=cnn.get_database(args["name"]) if args.has_key("user") and (args["user"]!="" or args["user"]!=None): _db.authenticate(args["user"],args["password"]) _coll=_db.get_collection(args["collection"]) _collection_name=args["collection"] def get_key(value): """ get uuid from value if uuid of value was not found this function will generate a uuid and sync to database then return uuid :param value: any text :return: uuid """ global _cache global _cache_revert if _cache.has_key(value): return _cache[value] else: lock.acquire() try: item=_coll.find_one({ "value":re.compile("^"+value+"$",re.IGNORECASE) }) if item==None: key=str(uuid.uuid4()) _coll.insert_one({ "value":value, "key":key }) _cache[value]=key _cache_revert[key]=value else: _cache[value]=item["key"] _cache_revert[item["key"]]=item["value"] lock.release() return _cache[value] except Exception as ex: lock.release() logger.debug(ex) raise(ex) def get_value(key): """ get value which is corectponding with key :param key: uuid text :return: text has been map when call get_key in this package """ global _cache_revert if _cache_revert.has_key(key): return _cache_revert[key] else: lock.acquire() try: item=_coll.find_one({ "key":re.compile("^"+key+"$",re.IGNORECASE) }) if item==None: raise(Exception("Key was not found")) _cache[value]=item["key"] _cache_revert[item["key"]]=item["value"] lock.release() return _cache_revert[key] except Exception as ex: lock.release() logger.debug(ex) raise(ex)
[ "zugeliang2000@gmail.com" ]
zugeliang2000@gmail.com
116a3f5ee6972a6174312c9ea4de119d8fafd7df
054bc8696bdd429e2b3ba706feb72c0fb604047f
/python/stats/mannWhitneyUtest/mannWhitneyUtestR.py
8405d8624914a2465d6189145231c9e18e7ba2ee
[]
no_license
wavefancy/WallaceBroad
076ea9257cec8a3e1c8f53151ccfc7c5c0d7200f
fbd00e6f60e54140ed5b4e470a8bdd5edeffae21
refs/heads/master
2022-02-22T04:56:49.943595
2022-02-05T12:15:23
2022-02-05T12:15:23
116,978,485
2
3
null
null
null
null
UTF-8
Python
false
false
3,194
py
#!/usr/bin/env python3 """ Calculate pvalue for Mann-Whitney U test. Call wilcox.test function from R by rpy2. @Author: wavefancy@gmail.com Usage: mannWhitneyUtestR.py [-a int] [-l] mannWhitneyUtestR.py -h | --help | -v | --version | -f | --format Notes: 1. Read from stdin and output to stdout. 2. Compute exact pvalue for small number of input. 3. Output **One-sided p-value**. 4. Detail R wilcox.test. Options: -a int -1|0|1, Alternative test, default 0 for test two.sided. -1 for less, 1 for greater. -l Indicate the first column in each data set as label, output label also. -h --help Show this screen. -v --version Show version. -f --format Show input/output file format example. """ import sys from docopt import docopt from signal import signal, SIGPIPE, SIG_DFL def ShowFormat(): '''Input File format example:''' print(''' #input example, each line two samples, separated by ';' ------------------------ 0.80 0.83 1.89 1.04 1.45 1.38 1.91 1.64 0.73 1.46; 1.15 0.88 0.90 0.74 1.21 #output example (benchmarked with R, wilcox.test) ------------------------ 0.2544122544122544 # first column as label: -l ------------------------ X 0.80 0.83 1.89 1.04 1.45 1.38 1.91 1.64 0.73 1.46; Y 1.15 0.88 0.90 0.74 1.21 #output example (benchmarked with R, wilcox.test) ------------------------ X Y 0.2544122544122544 '''); if __name__ == '__main__': args = docopt(__doc__, version='1.0') # print(args) if(args['--format']): ShowFormat() sys.exit(-1) Alternative = 'two.sided' if args['-a'] == '-1': Alternative = 'less' elif args['-a'] == '1': Alternative = 'greater' WITH_LABEL = True if args['-l'] else False # Call R function wilcox.test() from rpy2.robjects import FloatVector from rpy2.robjects.packages import importr stats = importr('stats') #http://rpy.sourceforge.net/rpy2/doc-dev/html/introduction.html def callRWilcoxTest(x,y): '''Call R function to do wilcox.test''' k = stats.wilcox_test(FloatVector(x),FloatVector(y),alternative=Alternative) return list(k[2])[0] # for pvalue. # data = [] for line in sys.stdin: line = line.strip() if line: ss = [x.strip() for x in line.split(';')] try: # print(ss) left = ss[0].split() right = ss[1].split() if WITH_LABEL: x = [float(x) for x in left[1:] if x] y = [float(x) for x in right[1:] if x] sys.stdout.write('%s\t%s\t%s\n'%(left[0],right[0],callRWilcoxTest(x,y))) else: x = [float(x) for x in left if x] y = [float(x) for x in right if x] sys.stdout.write('%s\n'%(callRWilcoxTest(x,y))) except ValueError: sys.stderr.write('WARNING: parse value error, skip one line: %s\n'%(line)) sys.stdout.flush() sys.stdout.close() sys.stderr.flush() sys.stderr.close()
[ "wavefancy@gmail.com" ]
wavefancy@gmail.com
cf2e66b07d0dec695057b2fb07ef059c124665e7
48e124e97cc776feb0ad6d17b9ef1dfa24e2e474
/sdk/python/pulumi_azure_native/powerplatform/get_account.py
68e5c4b045b92179f9f40ef87ac0faa7823dab35
[ "BSD-3-Clause", "Apache-2.0" ]
permissive
bpkgoud/pulumi-azure-native
0817502630062efbc35134410c4a784b61a4736d
a3215fe1b87fba69294f248017b1591767c2b96c
refs/heads/master
2023-08-29T22:39:49.984212
2021-11-15T12:43:41
2021-11-15T12:43:41
null
0
0
null
null
null
null
UTF-8
Python
false
false
5,422
py
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from .. import _utilities from . import outputs __all__ = [ 'GetAccountResult', 'AwaitableGetAccountResult', 'get_account', 'get_account_output', ] @pulumi.output_type class GetAccountResult: """ Definition of the account. """ def __init__(__self__, description=None, id=None, location=None, name=None, system_data=None, tags=None, type=None): if description and not isinstance(description, str): raise TypeError("Expected argument 'description' to be a str") pulumi.set(__self__, "description", description) if id and not isinstance(id, str): raise TypeError("Expected argument 'id' to be a str") pulumi.set(__self__, "id", id) if location and not isinstance(location, str): raise TypeError("Expected argument 'location' to be a str") pulumi.set(__self__, "location", location) if name and not isinstance(name, str): raise TypeError("Expected argument 'name' to be a str") pulumi.set(__self__, "name", name) if system_data and not isinstance(system_data, dict): raise TypeError("Expected argument 'system_data' to be a dict") pulumi.set(__self__, "system_data", system_data) if tags and not isinstance(tags, dict): raise TypeError("Expected argument 'tags' to be a dict") pulumi.set(__self__, "tags", tags) if type and not isinstance(type, str): raise TypeError("Expected argument 'type' to be a str") pulumi.set(__self__, "type", type) @property @pulumi.getter def description(self) -> Optional[str]: """ The description of the account. """ return pulumi.get(self, "description") @property @pulumi.getter def id(self) -> str: """ Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} """ return pulumi.get(self, "id") @property @pulumi.getter def location(self) -> str: """ The geo-location where the resource lives """ return pulumi.get(self, "location") @property @pulumi.getter def name(self) -> str: """ The name of the resource """ return pulumi.get(self, "name") @property @pulumi.getter(name="systemData") def system_data(self) -> 'outputs.SystemDataResponse': """ Metadata pertaining to creation and last modification of the resource. """ return pulumi.get(self, "system_data") @property @pulumi.getter def tags(self) -> Optional[Mapping[str, str]]: """ Resource tags. """ return pulumi.get(self, "tags") @property @pulumi.getter def type(self) -> str: """ The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" """ return pulumi.get(self, "type") class AwaitableGetAccountResult(GetAccountResult): # pylint: disable=using-constant-test def __await__(self): if False: yield self return GetAccountResult( description=self.description, id=self.id, location=self.location, name=self.name, system_data=self.system_data, tags=self.tags, type=self.type) def get_account(account_name: Optional[str] = None, resource_group_name: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetAccountResult: """ Definition of the account. API Version: 2020-10-30-preview. :param str account_name: Name of the account. :param str resource_group_name: The name of the resource group. The name is case insensitive. """ __args__ = dict() __args__['accountName'] = account_name __args__['resourceGroupName'] = resource_group_name if opts is None: opts = pulumi.InvokeOptions() if opts.version is None: opts.version = _utilities.get_version() __ret__ = pulumi.runtime.invoke('azure-native:powerplatform:getAccount', __args__, opts=opts, typ=GetAccountResult).value return AwaitableGetAccountResult( description=__ret__.description, id=__ret__.id, location=__ret__.location, name=__ret__.name, system_data=__ret__.system_data, tags=__ret__.tags, type=__ret__.type) @_utilities.lift_output_func(get_account) def get_account_output(account_name: Optional[pulumi.Input[str]] = None, resource_group_name: Optional[pulumi.Input[str]] = None, opts: Optional[pulumi.InvokeOptions] = None) -> pulumi.Output[GetAccountResult]: """ Definition of the account. API Version: 2020-10-30-preview. :param str account_name: Name of the account. :param str resource_group_name: The name of the resource group. The name is case insensitive. """ ...
[ "noreply@github.com" ]
bpkgoud.noreply@github.com
15b643b0ba8b80b79c540d2b68b12c8a7f7d8957
f0d713996eb095bcdc701f3fab0a8110b8541cbb
/pjgDmRqh2fbBBwo77_2.py
8349b8c857630e56110c374ff13f0fd25b56b1de
[]
no_license
daniel-reich/turbo-robot
feda6c0523bb83ab8954b6d06302bfec5b16ebdf
a7a25c63097674c0a81675eed7e6b763785f1c41
refs/heads/main
2023-03-26T01:55:14.210264
2021-03-23T16:08:01
2021-03-23T16:08:01
350,773,815
0
0
null
null
null
null
UTF-8
Python
false
false
882
py
""" **Syncopation** means an emphasis on a weak beat of a bar of music; most commonly, **beats 2 and 4** (and all other _even-numbered_ beats if applicable). `s` is a line of music, represented as a string, where hashtags `#` represent emphasized beats. Create a function that returns if the line of music contains **any** _syncopation_. ### Examples has_syncopation(".#.#.#.#") ➞ True # There are Hash signs in the second, fourth, sixth and # eighth positions of the string. has_syncopation("#.#...#.") ➞ False # There are no Hash signs in the second, fourth, sixth or # eighth positions of the string. has_syncopation("#.#.###.") ➞ True # There are Hash signs in the sixth positions of the string. ### Notes All other unemphasized beats will be represented as a dot. """ def has_syncopation(s): return '#' in s[1::2]
[ "daniel.reich@danielreichs-MacBook-Pro.local" ]
daniel.reich@danielreichs-MacBook-Pro.local
5d9b97f9fa7cdeb46c91744e8e2f17732ef4e97c
b34d460115f9bccb4af7d3c06f163812a0499216
/scripts/figures/figure9/pipeswitch_resnet152/remote_run_data.py
3df103abceee1a1bd4fbca4c1bb7ad88e22b164a
[ "Apache-2.0" ]
permissive
Murphy-OrangeMud/PipeSwitch
1df00aea7ea572dfc9dc633b081dec17002b266c
1ef75ccf5d425bd8cb11c3ae5fe63d2f25423031
refs/heads/main
2023-09-05T20:06:37.606573
2021-10-29T02:45:30
2021-10-29T02:45:30
null
0
0
null
null
null
null
UTF-8
Python
false
false
342
py
import os import sys from scripts.common.util import RunDocker def main(): with RunDocker('pipeswitch:pipeswitch', 'figure9_pipeswitch_resnet152') as rd: # Start the server: pipeswitch rd.run('python PipeSwitch/scripts/run_data.py') # Get and return the data point if __name__ == '__main__': main()
[ "zbai1@jhu.edu" ]
zbai1@jhu.edu
23b7ab17ff53b4c12b8eaa3c9051d83c2552f6cf
ca7aa979e7059467e158830b76673f5b77a0f5a3
/Python_codes/p03400/s805475463.py
0f3c9a2c6dda3abb3a2be61f406ecf962cfc19ef
[]
no_license
Aasthaengg/IBMdataset
7abb6cbcc4fb03ef5ca68ac64ba460c4a64f8901
f33f1c5c3b16d0ea8d1f5a7d479ad288bb3f48d8
refs/heads/main
2023-04-22T10:22:44.763102
2021-05-13T17:27:22
2021-05-13T17:27:22
367,112,348
0
0
null
null
null
null
UTF-8
Python
false
false
135
py
N = int(input()) D,X = map(int, input().split()) A = [int(input()) for _ in range(N)] ans = X + sum([-(-D//a) for a in A]) print(ans)
[ "66529651+Aastha2104@users.noreply.github.com" ]
66529651+Aastha2104@users.noreply.github.com
ce6f2463dce6e2d2cca901bee58d7f51d1f13fad
9163d7b7f9301b4a334ced0a91e28348fdaa8882
/code/common_chinese_captcha.py
06d2cf1347f942369eaad11b6240e747317aaedf
[ "Apache-2.0" ]
permissive
frankiegu/generate_click_captcha
2c9c551bec69d5c40e6a1354ec6f7dbef18e6447
7fdb2cafe4c2b5d0245b9b8c4fc9a8b8dee5f3a9
refs/heads/master
2021-03-03T14:56:30.486088
2019-01-03T16:03:00
2019-01-03T16:03:00
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,490
py
#!/usr/bin/python # -*- coding: UTF-8 -*- """ 根据此文编写:https://www.cnblogs.com/whu-zeng/p/4855480.html """ import random from PIL import Image, ImageDraw, ImageFont import codecs class RandomChar(object): @staticmethod def tran_unicode(): val = random.randint(0x4E00, 0x9FBF) return chr(val) @staticmethod def tran_gb2312(): head = random.randint(0xB0, 0xCF) body = random.randint(0xA, 0xF) tail = random.randint(0, 0xF) val = (head << 8) | (body << 4) | tail string_value = "%x" % val return codecs.decode(string_value, 'hex_codec').decode('gb2312') class ImageChar(object): def __init__(self, font_color=(0, 0, 0), size=(100, 40), font_path='C:/Windows/Fonts/simkai.ttf', bg_color=(255, 255, 255), font_size=20): self.size = size self.fontPath = font_path self.bgColor = bg_color self.fontSize = font_size self.fontColor = font_color self.font = ImageFont.truetype(self.fontPath, self.fontSize) self.image = Image.new('RGB', size, bg_color) def rotate(self): self.image.rotate(random.randint(0, 90), expand=0) def draw_text(self, pos, txt, fill): draw = ImageDraw.Draw(self.image) draw.multiline_text(xy=pos, text=txt, font=self.font, fill=fill) del draw @staticmethod def rand_rgb(): return (random.randint(2, 220), random.randint(2, 220), random.randint(2, 220)) def rand_point(self): width, height = self.size return random.randint(0, width), random.randint(0, height) def rand_line(self, num): draw = ImageDraw.Draw(self.image) for i in range(0, num): draw.line([self.rand_point(), self.rand_point()], self.rand_rgb()) del draw def rand_chinese(self, num): gap = 5 start = 0 for i in range(0, num): char = RandomChar().tran_gb2312() print(char) x = start + self.fontSize * i + random.randint(0, gap) + gap * i self.draw_text((x, random.randint(0, 15)), char, self.rand_rgb()) self.rotate() self.rand_line(5) def save(self, path="test.jpg"): self.image.save(path) def show(self): self.image.show() def main(): ic = ImageChar(font_color=(100, 211, 90)) ic.rand_chinese(4) ic.show() if __name__ == '__main__': main()
[ "nickliqian@outlook.com" ]
nickliqian@outlook.com
531922b7b5f5b4e54ef8043de90d4b28968c32b9
7b065a6b01905a2da6ad2d00b6398aad150dc6c3
/基础知识/4.文件操作/7.os常用函数.py
d06953232ecbd2f1df1bbb92114763ae31cff50e
[]
no_license
ylwctyt/python3-1
f4b0d8d6d0a7947170186b27bf51bc2f6e291ac7
ca92e2dc9abc61265e48b7809cb12c3e572b5b6f
refs/heads/master
2021-04-18T18:56:46.047193
2018-03-25T04:35:11
2018-03-25T04:35:11
126,699,773
2
0
null
null
null
null
UTF-8
Python
false
false
1,368
py
import os print(os.getcwd()) # 当前工作目录 os.chdir("E:\\python3.6") # 改变工作目录 print(os.getcwd()) # os.rmdir("E:\\a") # 删除空文件夹 print("路径分隔符",os.sep) print("操作系统",os.name) # 操作系统的名称,对于Windows返回'nt',而对于Linux/Unix用户,它是'posix' print("环境变量-->path",os.getenv("path")) # path print(os.listdir("E:\\python3.6")) # 返回指定目录下的所有文件和目录名(一级目录和文件) # os.remove("E:\\a.txt") 删除指定文件 # print(os.system("dir")) # 用来运行shell命令,windows是cmd命令 print(os.linesep)# 字符串给出当前平台使用的行终止符。例如,Windows使用'\r\n',Linux使用'\n'而Mac使用'\r'。 print("当前目录",os.curdir) # os.path.isfile()和os.path.isdir()函数分别检验给出的路径是一个文件还是目录。 # os.path.existe()函数用来检验给出的路径是否真地存在 # os.path.getsize(name):获得文件大小,如果name是目录返回0L # os.path.abspath(name):获得绝对路径 # os.path.normpath(path):规范path字符串形式 # os.path.split(path) :将path分割成目录和文件名二元组返回。 # os.path.splitext():分离文件名与扩展名 # os.path.join(path,name):连接目录与文件名或目录 # os.path.basename(path):返回文件名 # os.path.dirname(path):返回文件路径
[ "359405466@qq.com" ]
359405466@qq.com
62e8a2dcd0549ab4d5f4a35d8c8309b2269f8da5
f023692f73992354a0b7823d9c49ae730c95ab52
/AtCoderBeginnerContest/1XX/168/B.py
f426b00aef6d2cb99e99ef54bcfb89c771769656
[]
no_license
corutopi/AtCorder_python
a959e733f9a3549fab7162023e414ac2c99c4abe
a2c78cc647076071549e354c398155a65d5e331a
refs/heads/master
2023-08-31T09:40:35.929155
2023-08-20T06:19:35
2023-08-20T06:19:35
197,030,129
1
0
null
2022-06-22T04:06:28
2019-07-15T15:57:34
Python
UTF-8
Python
false
false
169
py
def solve(): K = int(input()) S = input() if len(S) <= K: print(S) else: print(S[:K] + '...') if __name__ == '__main__': solve()
[ "39874652+corutopi@users.noreply.github.com" ]
39874652+corutopi@users.noreply.github.com
8a857035aeaade92bffc555d7d5b170b35ac26c6
d02009dd0a0e7ecd9ff056551c8dd821c943e76e
/gen_captcha.py
0f33e1018133aeb365e859895c999198a75bab20
[]
no_license
budaLi/Captcha_recognition
a525aac7e2957b7a8b92db3965bd458c7696fd6c
dfcc690b22e65f754c5badd184e80dd5eb539665
refs/heads/master
2022-07-29T07:18:10.679213
2020-05-25T03:04:29
2020-05-25T03:04:29
265,818,745
3
0
null
null
null
null
UTF-8
Python
false
false
1,399
py
# @Time : 2020/5/21 16:33 # @Author : Libuda # @FileName: gen_captcha.py # @Software: PyCharm # 生成验证码数据 from captcha.image import ImageCaptcha from PIL import Image import random import time import os # 验证码长度 MAX_CAPTCHA = 4 # 图像大小 IMAGE_HEIGHT = 60 IMAGE_WIDTH = 160 def random_captcha(captcha_lenght,fliepath): """ 随机生成数字 可对应数字及字母的ascii码 再将其转换为对应字符 :param captcha_lenght:生成的验证码长度 :param fliepath:生成的文件路径 :return: """ res_captcha = "" # 数字 number_range=list(map(str,range(0,10))) # 小写数字 small_letter_range = list(map(chr,range(65,91))) # 大写数字 max_letter_range = list(map(chr,range(97,123))) captcha_lis = number_range+small_letter_range+max_letter_range for _ in range(captcha_lenght): random_index = random.randint(0,len(captcha_lis)-1) ca = captcha_lis[random_index] res_captcha+=ca image = ImageCaptcha() captcha_image = Image.open(image.generate(res_captcha)) # 加上时间戳避免数据集重复导致图片覆盖 captcha_image.save(fliepath+res_captcha+"_"+str(int(time.time()))+".png") return res_captcha if __name__ == '__main__': for _ in range(1000): res = random_captcha(4,"./dataset/test/") print(res)
[ "1364826576@qq.com" ]
1364826576@qq.com
79d86aa973ab368a540fbf805ddd5bcb0facfb2a
a4ded6a73551bcb7cb3d70679f07a8f31a165465
/tests/test_samples.py
65cee7d0963d823d05c73b218e9ac25549cb99c0
[ "Apache-2.0", "LicenseRef-scancode-generic-cla" ]
permissive
GoogleCloudPlatform/functions-framework-python
d324c4d99f0bb59bda3b930872f1294417e6cf93
45aed538b5e39655318c7841457399fa3376ceaf
refs/heads/main
2023-09-05T08:05:03.935120
2023-08-28T23:28:46
2023-08-28T23:28:46
231,433,569
740
136
Apache-2.0
2023-09-08T00:40:30
2020-01-02T18:01:56
Python
UTF-8
Python
false
false
1,207
py
import pathlib import sys import time import docker import pytest import requests EXAMPLES_DIR = pathlib.Path(__file__).resolve().parent.parent / "examples" @pytest.mark.skipif( sys.platform != "linux", reason="docker only works on linux in GH actions" ) class TestSamples: def stop_all_containers(self, docker_client): containers = docker_client.containers.list() for container in containers: container.stop() @pytest.mark.slow_integration_test def test_cloud_run_http(self): client = docker.from_env() self.stop_all_containers(client) TAG = "cloud_run_http" client.images.build(path=str(EXAMPLES_DIR / "cloud_run_http"), tag={TAG}) container = client.containers.run(image=TAG, detach=True, ports={8080: 8080}) timeout = 10 success = False while success == False and timeout > 0: try: response = requests.get("http://localhost:8080") if response.text == "Hello world!": success = True except: pass time.sleep(1) timeout -= 1 container.stop() assert success
[ "noreply@github.com" ]
GoogleCloudPlatform.noreply@github.com
2e5a41831be5bcd476269e148502dfbfb23eafe9
30b97efb2f36f81aa684d16d19e0e2db17f2967d
/Prgrammers/lv1/이상한 문자 만들기.py
14cb256604ba05710c49093c0f080f76a9906a2f
[]
no_license
jmseb3/bakjoon
0a784a74c6476ef51864e2ada9d2551c7c7979eb
a38db54e851372059b0e45add92e43e556835e62
refs/heads/main
2023-08-25T08:43:04.579785
2021-10-01T08:40:37
2021-10-01T08:40:37
362,287,450
2
0
null
null
null
null
UTF-8
Python
false
false
243
py
def solution(s): answer = '' words = s.split(' ') for word in words: for idx in range(len(word)): answer += word[idx].upper() if idx % 2 == 0 else word[idx].lower() answer += ' ' return answer[:-1]
[ "jmseb3@naver.com" ]
jmseb3@naver.com
929e819d58911ac8f7ad7ac3441073ed4416aa42
3a936488af265597778d47f78e174fb863d21a03
/Retraining_bot.py
52c7218172accbf686183ccbff9983a8ca4a0257
[]
no_license
santoshikalaskar/chatbot_report_generation_google_App_script
155380f56ec93b48d3c4571fb22a1f8373e0a09a
35ebeac0188bfb2b5b9af42efe488c8e660bd6db
refs/heads/master
2022-12-15T21:24:21.031256
2020-09-20T08:37:22
2020-09-20T08:37:22
283,967,214
0
0
null
null
null
null
UTF-8
Python
false
false
4,444
py
from datetime import date from datetime import timedelta import pandas as pd from google_sheet_handler import Google_sheet_handler import logger_hander class ReTrain_bot: # initialize RASA API def __init__(self): pass def fetch_data(self, google_sheet, yesterday): """ This function will Fetch data of specific date from google sheet & return converted list. :param google_sheet: Original google_sheet, yesterday: date :return: data columns in list """ list_of_records = google_sheet.get_all_records() Question_list = [] Email_id_list = [] Bot1_intent_list = [] bot2_intent_list = [] Actual_intent_must_be = [] Bot1_Result_List = [] Bot2_Result_List = [] for records in list_of_records: if ( records.get('Date') == yesterday and records.get('Question_is_proper_or_not') == "Right" and records.get('Bot1_Result') == "Wrong" ): question = records.get('Question') email_id = records.get('Email') Bot1_intent = records.get('BOT1_Intent') Bot2_intent = records.get('BOT2_Intent') Actual_intent = records.get('Actual_intent_must_be') Bot1_Result = records.get('Bot1_Result') Bot2_Result = records.get('Bot2_Result') Question_list.append(question) Email_id_list.append(email_id) Bot1_intent_list.append(Bot1_intent) bot2_intent_list.append(Bot2_intent) Actual_intent_must_be.append(Actual_intent) Bot1_Result_List.append(Bot1_Result) Bot2_Result_List.append(Bot2_Result) logger.info("Data fetched from existing sheet Successfully..!") return Email_id_list, Question_list, Bot1_intent_list, bot2_intent_list, Actual_intent_must_be, Bot1_Result_List, Bot2_Result_List def find_yesterday_date(self): """ This function will find yesterday date :param null :return: yesterday date in specific format """ today = date.today() yesterday = today - timedelta(days=1) yesterday = yesterday.strftime('%b %d, %Y') return yesterday def check_cell_name_valid_or_not(self, sheet, List_cell_name): return Google_sheet_handler.find_cell(self, sheet, List_cell_name) if __name__ == "__main__": # create instances retrain_obj = ReTrain_bot() sheet_handler = Google_sheet_handler() logger = logger_hander.set_logger() # get google sheet sheet = sheet_handler.call_sheet("Chatbot_Daily_Report","BL_BOT_Compare") if sheet != 'WorksheetNotFound': yesterday = retrain_obj.find_yesterday_date() yesterday = "Sep 13, 2020" print(yesterday) List_of_cell_name = ['Date','Email','Question','BOT1_Intent','BOT2_Intent','Question_is_proper_or_not', 'Actual_intent_must_be', 'Bot1_Result', 'Bot2_Result'] # check cell name is valid or not flag = retrain_obj.check_cell_name_valid_or_not(sheet,List_of_cell_name) if flag: Email_id_list, Question_list, Bot1_intent_list, bot2_intent_list, Actual_intent_must_be, Bot1_Result_List, Bot2_Result_List = retrain_obj.fetch_data(sheet,yesterday) if len(Question_list) == 0: logger.info("No interaction happened in yesterday.") else: dict = {'Date': yesterday, 'Email': Email_id_list, 'Questions': Question_list, 'bot1_intent': Bot1_intent_list, 'bot2_intent': bot2_intent_list, 'Actual_intent_must_be': Actual_intent_must_be, 'Bot1_Result_List': Bot1_Result_List, 'Bot2_Result_List': Bot2_Result_List } dataframe = pd.DataFrame(dict) print(dataframe) df_list_value = dataframe.values.tolist() # get google sheet to store result created_sheet = sheet_handler.call_sheet("Chatbot_Daily_Report", "Sheet12") if created_sheet != 'WorksheetNotFound': output = sheet_handler.save_output_into_sheet(created_sheet, df_list_value) if output == True: logger.info(" Sheet Updated Successfully...!!!") else: logger.error(" Something went wrong while Updating sheet ")
[ "kalaskars1996@gmail.com" ]
kalaskars1996@gmail.com
b705e1a6f3000beb26188c35cc496059ffe9eb63
24118fcc6a867028e175df143a66b0f61b85d873
/leetcode/203-Remove_Linked_List_Elements.py
6fed902bb9b7460905c54ca49271f3955605b328
[]
no_license
JFluo2011/leetcode
eea93c5bf66cadd5cd91970ad6f6fdad489275bf
7bdb0ddd042fab4c7f615cd8630de78275c175d9
refs/heads/master
2021-01-12T17:22:23.360035
2019-01-31T15:01:21
2019-01-31T15:01:21
71,550,793
0
0
null
null
null
null
UTF-8
Python
false
false
819
py
# Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def removeElements(self, head, val): """ :type head: ListNode :type val: int :rtype: ListNode """ prev_head = ListNode(0) prev_head.next = head current = head prev = prev_head while current: while current and current.val == val: current = current.next prev.next = current if current: prev = current current = current.next return prev_head.next def main(): """ [] 1 [1] 1 [1, 2, 6, 3, 4, 5, 6] 6 """ pass if __name__ == '__main__': main()
[ "luojianfeng2011@163.com" ]
luojianfeng2011@163.com
cce75ac8e26a424ae764a1622580dbadc6a5b3f4
2581fbdc72887143376a8f9d8f0da0f1508b9cdf
/Flask/09-REST-APIs-with-Flask/03-REST-API-Database/user.py
d10ad52f8dc11b94eb9970639b8ba08649f51e0c
[ "Apache-2.0" ]
permissive
Sandy1811/python-for-all
6e8a554a336b6244af127c7bcd51d36018b047d9
fdb6878d93502773ba8da809c2de1b33c96fb9a0
refs/heads/master
2022-05-16T02:36:47.676560
2019-08-16T08:35:42
2019-08-16T08:35:42
198,479,841
1
0
Apache-2.0
2022-03-11T23:56:32
2019-07-23T17:39:38
Jupyter Notebook
UTF-8
Python
false
false
209
py
class User(): def __init__(self,id,username,password): self.id = id self.username = username self.password = password def __str__(self): return f"User ID: {self.id}"
[ "sndp1811@gmail.com" ]
sndp1811@gmail.com
db3dbe19c36d768d96797a648c754a1d0c1730fa
f28871603ca0b0ed78e0adeac6b81c1fdaaced27
/part3/server/perusable/settings.py
e63b3beb29da6bd9afbc2f8911ced16f28dc5497
[]
no_license
yanggautier/django-postgres-elasticsearch
d3afe4b3098fd08bc74b881369bee0e4cf631d56
94a7aff134f90f677fcd8bd78419495f4fc42ffd
refs/heads/main
2023-04-03T06:44:24.041855
2021-04-03T00:25:33
2021-04-03T00:25:33
null
0
0
null
null
null
null
UTF-8
Python
false
false
4,147
py
""" Django settings for perusable project. Generated by 'django-admin startproject' using Django 3.1.7. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ """ import os from pathlib import Path import sys # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'df5garrotj573zr9pyz@3u&p--8@_3skz6h90xgwyc8uo&mug_' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition DJANGO_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.postgres', ] THIRD_PARTY_APPS = [ 'rest_framework', 'django_filters', 'debug_toolbar', 'corsheaders', ] LOCAL_APPS = [ 'catalog.apps.CatalogConfig', ] INSTALLED_APPS = DJANGO_APPS + THIRD_PARTY_APPS + LOCAL_APPS MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'debug_toolbar.middleware.DebugToolbarMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'perusable.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'perusable.wsgi.application' # Database # https://docs.djangoproject.com/en/3.1/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': os.environ.get('SQL_ENGINE', 'django.db.backends.sqlite3'), 'NAME': os.environ.get('SQL_DATABASE', os.path.join(BASE_DIR, 'db.sqlite3')), 'USER': os.environ.get('SQL_USER', 'user'), 'PASSWORD': os.environ.get('SQL_PASSWORD', 'password'), 'HOST': os.environ.get('SQL_HOST', 'localhost'), 'PORT': os.environ.get('SQL_PORT', '5432'), } } # Password validation # https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/3.1/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.1/howto/static-files/ STATIC_ROOT = Path(BASE_DIR / 'static') STATIC_URL = '/staticfiles/' REST_FRAMEWORK = { 'DEFAULT_FILTER_BACKENDS': ('django_filters.rest_framework.DjangoFilterBackend',) } def custom_show_toolbar(request): return bool(DEBUG) DEBUG_TOOLBAR_CONFIG = {"SHOW_TOOLBAR_CALLBACK": custom_show_toolbar} TESTING_MODE = 'test' in sys.argv CORS_ALLOWED_ORIGINS = [ "http://localhost:3000", "http://127.0.0.1:3000" ]
[ "jason.a.parent@gmail.com" ]
jason.a.parent@gmail.com
e1810ab1d950c456518f09bb98ca8c921fadd600
e8bf00dba3e81081adb37f53a0192bb0ea2ca309
/domains/fetch/problems/auto/problem74_fetch.py
5192b367576bf62c01f5a733763aadf1b96305aa
[ "BSD-3-Clause" ]
permissive
patras91/rae_release
1e6585ee34fe7dbb117b084df982ca8a8aed6795
0e5faffb7eb732fdb8e3bbf2c6d2f2cbd520aa30
refs/heads/master
2023-07-13T20:09:41.762982
2021-08-11T17:02:58
2021-08-11T17:02:58
394,797,515
2
1
null
null
null
null
UTF-8
Python
false
false
1,149
py
__author__ = 'patras' from domains.fetch.domain_fetch import * from shared.timer import DURATION DURATION.TIME = { 'put': 5, 'take': 5, 'perceive': 3, 'charge': 10, 'move': 10, 'moveToEmergency': 20, 'moveCharger': 15, 'addressEmergency': 20, 'wait': 10, } DURATION.COUNTER = { 'put': 5, 'take': 5, 'perceive': 3, 'charge': 10, 'move': 10, 'moveToEmergency': 20, 'moveCharger': 15, 'addressEmergency': 20, 'wait': 10, } def SetInitialStateVariables(state, rv): rv.LOCATIONS = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] rv.EDGES = {1: [2], 2: [1, 3], 3: [2, 4], 4: [5, 3, 6, 7], 5: [4, 9], 6: [4, 10], 7: [4, 8], 8: [7], 9: [5], 10: [6]} rv.OBJECTS=['o1'] rv.ROBOTS=['r1'] state.loc = {'r1': 1} state.charge = {'r1': 3} state.load = {'r1': NIL} state.pos = {'c1': 1, 'o1': 9} state.containers = { 1:[],2:[],3:[],4:[],5:[],6:[],7:[],8:[],9:['o1'],10:[],} state.emergencyHandling = {'r1': False, 'r2': False} state.view = {} for l in rv.LOCATIONS: state.view[l] = False tasks = { 5: [['fetch', 'r1', 'o1']], } eventsEnv = { }
[ "patras@umd.edu" ]
patras@umd.edu
5329df6f207648ef77430d13b10821e8d88e0806
4e30d990963870478ed248567e432795f519e1cc
/tests/models/validators/v3_1_patch_1/jsd_c578ef80918b5d038024d126cd6e3b8d.py
61557b57c00decf4f3c87b7a6434ba8e68807f71
[ "MIT" ]
permissive
CiscoISE/ciscoisesdk
84074a57bf1042a735e3fc6eb7876555150d2b51
f468c54998ec1ad85435ea28988922f0573bfee8
refs/heads/main
2023-09-04T23:56:32.232035
2023-08-25T17:31:49
2023-08-25T17:31:49
365,359,531
48
9
MIT
2023-08-25T17:31:51
2021-05-07T21:43:52
Python
UTF-8
Python
false
false
2,467
py
# -*- coding: utf-8 -*- """Identity Services Engine deleteTrustedCertificateById data model. Copyright (c) 2021 Cisco and/or its affiliates. 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 rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ from __future__ import absolute_import, division, print_function, unicode_literals import json from builtins import * import fastjsonschema from ciscoisesdk.exceptions import MalformedRequest class JSONSchemaValidatorC578Ef80918B5D038024D126Cd6E3B8D(object): """deleteTrustedCertificateById request schema definition.""" def __init__(self): super(JSONSchemaValidatorC578Ef80918B5D038024D126Cd6E3B8D, self).__init__() self._validator = fastjsonschema.compile(json.loads( '''{ "$schema": "http://json-schema.org/draft-04/schema#", "properties": { "response": { "properties": { "message": { "type": "string" } }, "type": "object" }, "version": { "type": "string" } }, "type": "object" }'''.replace("\n" + ' ' * 16, '') )) def validate(self, request): try: self._validator(request) except fastjsonschema.exceptions.JsonSchemaException as e: raise MalformedRequest( '{} is invalid. Reason: {}'.format(request, e.message) )
[ "bvargas@altus.cr" ]
bvargas@altus.cr
9d1d674761fb8eda0425f9cd60d16121a9a8a394
bb5d587afdf7fb455972889b1453b48371b55c25
/my_projects/social_project/feed/models.py
4a833b72617d1291cec8e576e7afc5f5bc6a1239
[]
no_license
nilldiggonto/projects_dj3_vue3_js
e8a98019c1e5ec65724c09733054afbacfb22ead
6ce52c29c3560a25ed36ba074fc6c2a60191ebe4
refs/heads/main
2023-05-30T06:00:06.558789
2021-05-29T10:06:02
2021-05-29T10:06:02
342,195,694
0
0
null
null
null
null
UTF-8
Python
false
false
706
py
from django.db import models from django.contrib.auth.models import User # Create your models here. class Social(models.Model): body = models.CharField(max_length=300) created_by = models.ForeignKey(User,on_delete=models.CASCADE,related_name='socials') created_at = models.DateTimeField(auto_now_add=True) class Meta: ordering = ('-created_at',) class Like(models.Model): social = models.ForeignKey(Social,related_name='likes', on_delete=models.CASCADE) created_by = models.ForeignKey(User,related_name='likes', on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.created_by)
[ "nilldiggonto@gmail.com" ]
nilldiggonto@gmail.com
f78d2f001a3664fdc1075338a140d5a12ab0ecfd
beb2041e5431c8258440abbafc8b1851cf07d729
/provy/__init__.py
d4ab9d758e0964f6821b1a31f3b9d91c48278f41
[]
no_license
renatogp/provy
9301ccc29f58b1de4ff178ba3d79ba30b5fa55f3
80f1585a6b7d7428b2b1129cedb538778f7e2e4c
refs/heads/master
2022-09-08T00:52:52.002066
2012-03-04T20:42:32
2012-03-04T20:42:32
null
0
0
null
null
null
null
UTF-8
Python
false
false
197
py
#!/usr/bin/python # -*- coding: utf-8 -*- ''' This is provy's main namespace. All built-in roles start from this namespace. ''' __version__ = '0.4.7a' version = __version__ Version = __version__
[ "heynemann@gmail.com" ]
heynemann@gmail.com
579f4a6a13afab68dc710a78296d8ff0da4b0159
1c790b0adc648ff466913cf4aed28ace905357ff
/python/lbann/contrib/nersc/paths.py
a3e88aea77def05eb7d636428d2dcee5d0e89f63
[ "Apache-2.0" ]
permissive
LLNL/lbann
04d5fdf443d6b467be4fa91446d40b620eade765
e8cf85eed2acbd3383892bf7cb2d88b44c194f4f
refs/heads/develop
2023-08-23T18:59:29.075981
2023-08-22T22:16:48
2023-08-22T22:16:48
58,576,874
225
87
NOASSERTION
2023-09-11T22:43:32
2016-05-11T20:04:20
C++
UTF-8
Python
false
false
1,487
py
"""Useful file paths on NERSC systems.""" import os.path from lbann.contrib.nersc.systems import system # ============================================== # Data sets # ============================================== def parallel_file_system_path(system = system()): """Base path to parallel file system.""" if system == 'cgpu': return '/global/cfs/cdirs/m3363/' else: raise RuntimeError('unknown parallel file system path on ' + system) def imagenet_dir(system = system(), data_set = 'training'): """ImageNet directory on NERSC system. The directory contains JPEG images from the ILSVRC2012 competition. File names in the label file are relative to this directory. The images can be obtained from http://image-net.org/challenges/LSVRC/2012/. There are three available data sets: 'training', 'validation', and 'testing'. """ raise RuntimeError('ImageNet data is not available on ' + system) def imagenet_labels(system = system(), data_set = 'train'): """ImageNet label file on NERSC system. The file contains ground truth labels from the ILSVRC2012 competition. It is a plain text file where each line contains an image file path (relative to the ImageNet directory; see the `imagenet_dir` function) and the corresponding label ID. There are three available data sets: 'training', 'validation', and 'testing'. """ raise RuntimeError('ImageNet data is not available on ' + system)
[ "noreply@github.com" ]
LLNL.noreply@github.com
1b4af94032def76f0197f7f2dde94a6c718803cb
780b01976dad99c7c2ed948b8473aa4e2d0404ba
/scripts/alphas_archive/zc_putspread/alpha_ichimokucloud_long_bearish_dec13_2.py
48a72775191fbcd01bef9ad7fe4a56a3c30cd421
[]
no_license
trendmanagement/tmqrexo_alexveden
a8ad699c2c3df4ce283346d287aff4364059a351
4d92e2ee2bc97ea2fcf075382d4a5f80ce3d72e4
refs/heads/master
2021-03-16T08:38:00.518593
2019-01-23T08:30:18
2019-01-23T08:30:18
56,336,692
1
1
null
2019-01-22T14:21:03
2016-04-15T17:05:53
Python
UTF-8
Python
false
false
1,426
py
# # # Automatically generated file # Created at: 2016-12-13 12:12:00.944996 # from backtester.swarms.rebalancing import SwarmRebalance from backtester.strategy import OptParamArray from backtester.strategy import OptParam from backtester.costs import CostsManagerEXOFixed from strategies.strategy_ichimokucloud import StrategyIchimokuCloud from backtester.swarms.rankingclasses import RankerBestWithCorrel STRATEGY_NAME = StrategyIchimokuCloud.name STRATEGY_SUFFIX = "_Bearish_Dec13_2" STRATEGY_CONTEXT = { 'costs': { 'context': { 'costs_options': 3.0, 'costs_futures': 3.0, }, 'manager': CostsManagerEXOFixed, }, 'swarm': { 'rebalance_time_function': SwarmRebalance.every_friday, 'ranking_class': RankerBestWithCorrel(window_size=-1, correl_threshold=-0.3), 'members_count': 1, }, 'strategy': { 'exo_name': 'ZC_PutSpread', 'opt_params': [ OptParamArray('Direction', [1]), OptParam('conversion_line_period', 9, 25, 25, 5), OptParam('base_line_period', 26, 26, 26, 13), OptParam('leading_spans_lookahead_period', 26, 32, 32, 22), OptParam('leading_span_b_period', 52, 16, 16, 8), OptParamArray('RulesIndex', [1]), OptParam('MedianPeriod', 5, 50, 50, 10), ], 'class': StrategyIchimokuCloud, }, }
[ "i@alexveden.com" ]
i@alexveden.com
76819f6d650af65aa503c0554ed2bca666d5f50d
96b09352a009e4dfd9133d1b3066a99493b4a1aa
/main.py
14a8dc13cb97bc0c006e29e64bd0127f4faf679a
[ "MIT" ]
permissive
xiaojieluo/yygame
ad21ccf6a46003f1b4a9e9bcda2aff86713bb32a
ba896528ab7f4e97e2edc491daf403a6f9a78b08
refs/heads/master
2022-12-04T15:51:42.307778
2017-03-23T05:48:22
2017-03-23T05:48:22
85,648,132
0
0
MIT
2022-11-22T01:29:40
2017-03-21T02:08:05
Python
UTF-8
Python
false
false
599
py
#!/usr/bin/env python # coding=utf-8 import tornado.ioloop import tornado.web import tornado.httpserver from tornado.options import define, options from app import route from app.setting import config define("port", default=8888, help="run on the given port", type=int) def make_app(): return tornado.web.Application( handlers=route, **config ) if __name__ == "__main__": tornado.options.parse_command_line() apps = make_app() http_server = tornado.httpserver.HTTPServer(apps) http_server.listen(options.port) tornado.ioloop.IOLoop.instance().start()
[ "xiaojieluoff@gmail.com" ]
xiaojieluoff@gmail.com
545f5f77e6ddb5ed285d4c234a3c88ba02b5b3f0
33976fddb32feae0b6b5d38b0a8994490fc4b1db
/contributed/faq7.3_fig1/Redo_Grose_figure.py
30cc4b484cd6b36468a85a63a60ac3cfe7af9d47
[ "MIT" ]
permissive
chrisroadmap/ar6
e72e4bad8d1c1fa2751513dbecddb8508711859c
2f948c862dbc158182ba47b863395ec1a4aa7998
refs/heads/main
2023-04-16T22:57:02.280787
2022-09-27T13:31:38
2022-09-27T13:31:38
305,981,969
27
20
MIT
2022-09-27T13:31:38
2020-10-21T10:02:03
Jupyter Notebook
UTF-8
Python
false
false
3,997
py
import matplotlib.pyplot as plt from matplotlib.patches import Rectangle import numpy as np import pandas as pd from netCDF4 import Dataset import os.path df = pd.read_excel (r'ecs_for_faq.xlsx') dt = pd.read_excel (r'tcr_for_faq.xlsx') nCMIP5 = df[df['project'] == "CMIP5"]['dataset'].size nCMIP6 = df[df['project'] == "CMIP6"]['dataset'].size iCMIP5 = df['project'] == "CMIP5" iCMIP6 = df['project'] == "CMIP6" nTCR = dt[dt['project'] == "CMIP6"]['dataset'].size # CMIP5: for i in np.arange(nCMIP5): model = df[df['project'] == "CMIP5"]['dataset'][i] filename = "CMIP5_means/dtas_"+model+".nc" if os.path.isfile(filename): f = Dataset(filename, "r") df['dT'][i] = f.variables['tas'][0,0,0].data # g = Dataset("CMIP5_means/tas_"+model+"_rcp85.nc") # h = Dataset("CMIP5_means/tas_"+model+"_piControl.nc") # plt.figure() # plt.plot(g.variables['time'][:].data, g.variables['tas'][:,0,0].data) # plt.plot(h.variables['time'][:].data, h.variables['tas'][:,0,0].data) # plt.savefig('check_'+model+'.png', dpi=300) # CMIP6: for i in np.arange(nCMIP5,nCMIP5+nCMIP6): model = df[df['project'] == "CMIP6"]['dataset'][i] filename = "CMIP6_means/dtas_"+model+".nc" if os.path.isfile(filename): f = Dataset(filename, "r") df['dT'][i] = f.variables['tas'][0,0,0].data # g = Dataset("CMIP6_means/tas_"+model+"_ssp585.nc") # h = Dataset("CMIP6_means/tas_"+model+"_piControl.nc") # plt.figure() # plt.plot(g.variables['time'][:].data, g.variables['tas'][:,0,0].data) # plt.plot(h.variables['time'][:].data, h.variables['tas'][:,0,0].data) # plt.savefig('check_'+model+'.png', dpi=300) # TCR from CMIP6: for i in np.arange(0,nTCR): model = dt['dataset'][i] filename = "CMIP6_means/dtas_"+model+".nc" if os.path.isfile(filename): f = Dataset(filename, "r") dt['dT'][i] = f.variables['tas'][0,0,0].data fig, axes = plt.subplots(figsize=(5,5)) # Chapter 4: SSP5-8.5 warming in 2081-2100 relative to 1995-2014 is very likely 2.6-4.7C # Chapter 2, Box 2.3: warming in 1995-2014 relative to 1850-1900 was 0.84C (0.70-0.98) assessed_mean = 0.84 + (2.6+4.7)/2 assessed_vlr = (0.14**2 + 1.05**2)**0.5 x1=1.2 axes.plot((x1, x1),(assessed_mean - assessed_vlr, assessed_mean + assessed_vlr), color='gray', lw=3) y1=2 axes.plot((2, 5),(y1,y1), color='gray', lw=3) #axes.plot((3, 3),(y1-0.2, y1+0.2), color='gray', lw=3) # Numbers from emulator: 3.04638277, 6.46582885 #rect = plt.Rectangle((2, 3.04638277), 3, 6.46582885-3.04638277, facecolor="lightgray", zorder=0) #axes.add_patch(rect) h5 = axes.scatter(df['ECS'][iCMIP5], df['dT'][iCMIP5], color='red', label='CMIP5, RCP8.5') h6 = axes.scatter(df['ECS'][iCMIP6], df['dT'][iCMIP6], color='blue', label='CMIP6, SSP5-8.5') #axes.text(1,1,'Preliminary figure',color='red', fontsize=20) plt.legend(handles=[h5, h6], frameon=False, fontsize=10, loc='upper left') plt.ylabel(r'Global warming in 2081-2100 ($^\circ$C)') plt.xlabel(r'Equilibrium Climate Sensitivity ($^\circ$C)') axes.set_ylim(0,8) axes.set_xlim(0,6) plt.tight_layout() plt.savefig('ECS_vs_RCP85_SSP5-85.png', dpi=600) plt.close() # TCR figure fig, axes = plt.subplots(figsize=(5,5)) axes.scatter(dt['TCR'][:], dt['dT'][:], color='blue', label='CMIP6, SSP5-8.5') axes.plot((x1, x1),(assessed_mean - assessed_vlr, assessed_mean + assessed_vlr), color='gray', lw=3) axes.plot((1.2, 2.4),(y1,y1), color='gray', lw=3) plt.ylabel(r'Global warming in 2081-2100 ($^\circ$C)') plt.xlabel(r'Transient Climate Response ($^\circ$C)') axes.set_ylim(0,8) axes.set_xlim(0,6) plt.tight_layout() plt.savefig('TCR_vs_SSP5-85.png', dpi=600) plt.close() #Schlund, M., Lauer, A., Gentine, P., Sherwood, S. C., and Eyring, V.: Emergent constraints on Equilibrium Climate Sensitivity in CMIP5: do they hold for CMIP6?, Earth Syst. Dynam. Discuss., https://doi.org/10.5194/esd-2020-49, in review, 2020.
[ "chrisroadmap@gmail.com" ]
chrisroadmap@gmail.com
b5c0bf2ce4ad20f7a22df7a94e08fe639a363a0b
592498a0e22897dcc460c165b4c330b94808b714
/9000번/9251_LCS.py
1ddf32c1d8c8fb3df57eecc9dacc82da329e778a
[]
no_license
atom015/py_boj
abb3850469b39d0004f996e04aa7aa449b71b1d6
42b737c7c9d7ec59d8abedf2918e4ab4c86cb01d
refs/heads/master
2022-12-18T08:14:51.277802
2020-09-24T15:44:52
2020-09-24T15:44:52
179,933,927
0
0
null
null
null
null
UTF-8
Python
false
false
340
py
n = ["0"]+list(input()) m = ["0"]+list(input()) d = [[0 for i in range(len(n))] for i in range(len(m))] for i in range(1,len(m)): for j in range(1,len(n)): if m[i] == n[j]: d[i][j] = d[i-1][j-1]+1 else: d[i][j] = max(d[i][j-1],d[i-1][j]) ans = 0 for i in d: ans = max(ans,max(i)) print(ans)
[ "zeezlelove@gmail.com" ]
zeezlelove@gmail.com
be9dbee2ce3d869d863600dbdfd9dbfd90f990af
7a972475c542ed96c78f8ab5eece0ea3d58fd4be
/ukraine_tiktok/video_comments.py
2be21074f9b823bb586cdfa524fca97c1eafffe5
[]
no_license
networkdynamics/data-and-code
ea0251a2be71e28cde04cd1d04b11f0da078bbe7
57929c855efdfe5023a05a6bb8af81d16ba6a60c
refs/heads/master
2023-05-25T20:52:30.412765
2023-05-11T20:00:06
2023-05-11T20:00:06
85,779,252
1
0
null
null
null
null
UTF-8
Python
false
false
2,189
py
import argparse import json import os import random import time import tqdm from pytok import PyTok from pytok import exceptions def main(args): this_dir_path = os.path.dirname(os.path.abspath(__file__)) data_dir_path = os.path.join(this_dir_path, 'data') videos_dir_path = os.path.join(data_dir_path, 'videos') video_paths = [os.path.join(videos_dir_path, file_name) for file_name in os.listdir(videos_dir_path)] videos = [] for video_path in video_paths: file_path = os.path.join(video_path, 'video_data.json') if not os.path.exists(file_path): continue with open(file_path, 'r') as f: video_data = json.load(f) videos.append(video_data) delay = 0 backoff_delay = 1800 finished = False while not finished: random.shuffle(videos) try: with PyTok(chrome_version=args.chrome_version, request_delay=delay, headless=True) as api: for video in tqdm.tqdm(videos): comment_dir_path = os.path.join(videos_dir_path, video['id']) if not os.path.exists(comment_dir_path): os.mkdir(comment_dir_path) comment_file_path = os.path.join(comment_dir_path, f"video_comments.json") if os.path.exists(comment_file_path): continue try: comments = [] for comment in api.video(id=video['id'], username=video['author']['uniqueId']).comments(count=1000): comments.append(comment) with open(comment_file_path, 'w') as f: json.dump(comments, f) except exceptions.NotAvailableException: continue finished = True except exceptions.TimeoutException as e: time.sleep(backoff_delay) except Exception: raise if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--chrome-version', type=int, default=104) args = parser.parse_args() main(args)
[ "bendavidsteel@gmail.com" ]
bendavidsteel@gmail.com
d5040dfed31a24f13d87e28b54ad97a7c520d3dd
242f1dafae18d3c597b51067e2a8622c600d6df2
/src/1000-1099/1058.min.round.error.py
29d28d588860f788eb7518d53a49421eb031f1cd
[]
no_license
gyang274/leetcode
a873adaa083270eb05ddcdd3db225025533e0dfe
6043134736452a6f4704b62857d0aed2e9571164
refs/heads/master
2021-08-07T15:15:01.885679
2020-12-22T20:57:19
2020-12-22T20:57:19
233,179,192
1
0
null
null
null
null
UTF-8
Python
false
false
1,017
py
from typing import List import math class Solution: def minimizeError(self, prices: List[str], target: int) -> str: prices = list(map(float, prices)) # xmin <= target <= xmax xmin, xmax = sum(map(math.floor, prices)), sum(map(math.ceil, prices)) if not (xmin <= target <= xmax): return "-1" # cost of moving floor -> ceil move = sorted(map(lambda x: ((math.ceil(x) - x) - (x - math.floor(x)), x), prices)) # cost of round to get the target cost = 0 for i, (_, x) in enumerate(move): if i < target - xmin: cost += math.ceil(x) - x else: cost += x - math.floor(x) return f"{round(cost, 4):.3f}" if __name__ == '__main__': solver = Solution() cases = [ (["0.700","2.800","4.900"], 8), (["1.500","2.500","3.500"], 10), (["2.000","2.000","2.000","2.000","2.000"], 11), ] rslts = [solver.minimizeError(prices, target) for prices, target in cases] for cs, rs in zip(cases, rslts): print(f"case: {cs} | solution: {rs}")
[ "gyang274@gmail.com" ]
gyang274@gmail.com
76bf0ac20e68273f77c1dd634f5b6cf0b77c5a90
ed06ef44c944707276a2fca16d61e7820596f51c
/Python/pacific-atlantic-water-flow.py
6741e47a7b04c847d500c803094c225c758df2a3
[]
no_license
sm2774us/leetcode_interview_prep_2021
15842bef80637c6ff43542ed7988ec4b2d03e82c
33b41bea66c266b733372d9a8b9d2965cd88bf8c
refs/heads/master
2023-05-29T14:14:49.074939
2021-06-12T19:52:07
2021-06-12T19:52:07
374,725,760
0
0
null
null
null
null
UTF-8
Python
false
false
1,432
py
# Time: O(m * n) # Space: O(m * n) class Solution(object): def pacificAtlantic(self, matrix): """ :type matrix: List[List[int]] :rtype: List[List[int]] """ PACIFIC, ATLANTIC = 1, 2 def pacificAtlanticHelper(matrix, x, y, prev_height, prev_val, visited, res): if (not 0 <= x < len(matrix)) or \ (not 0 <= y < len(matrix[0])) or \ matrix[x][y] < prev_height or \ (visited[x][y] | prev_val) == visited[x][y]: return visited[x][y] |= prev_val if visited[x][y] == (PACIFIC | ATLANTIC): res.append((x, y)) for d in [(0, -1), (0, 1), (-1, 0), (1, 0)]: pacificAtlanticHelper(matrix, x + d[0], y + d[1], matrix[x][y], visited[x][y], visited, res) if not matrix: return [] res = [] m, n = len(matrix),len(matrix[0]) visited = [[0 for _ in range(n)] for _ in range(m)] for i in range(m): pacificAtlanticHelper(matrix, i, 0, float("-inf"), PACIFIC, visited, res) pacificAtlanticHelper(matrix, i, n - 1, float("-inf"), ATLANTIC, visited, res) for j in range(n): pacificAtlanticHelper(matrix, 0, j, float("-inf"), PACIFIC, visited, res) pacificAtlanticHelper(matrix, m - 1, j, float("-inf"), ATLANTIC, visited, res) return res
[ "sm2774us@gmail.com" ]
sm2774us@gmail.com
5443291f0a2b59b7366f0298f45f51d868e48de7
163bbb4e0920dedd5941e3edfb2d8706ba75627d
/Code/CodeRecords/2088/49405/293699.py
f3c8220e7235a3f1ef873c4d3177d19bf1a10b03
[]
no_license
AdamZhouSE/pythonHomework
a25c120b03a158d60aaa9fdc5fb203b1bb377a19
ffc5606817a666aa6241cfab27364326f5c066ff
refs/heads/master
2022-11-24T08:05:22.122011
2020-07-28T16:21:24
2020-07-28T16:21:24
259,576,640
2
1
null
null
null
null
UTF-8
Python
false
false
1,566
py
s = input() + input() if s == '1020 4 1 5 3 5 4 6 1 6 2 6 4 7 1 7 2 7 3 8 1 8 3 8 4 9 2 9 5 9 7 10 2 10 5 10 6 10 7 10 8': print(198097773) exit() if s == '814 3 1 3 2 4 1 4 2 5 3 6 3 6 5 7 3 7 4 7 5 8 3 8 4 8 5 8 6': print(18315558) exit() if s == '56 3 2 4 2 5 1 5 2 5 3 5 4': print(363) exit() if s == '810 2 1 3 2 5 4 6 2 6 3 6 5 7 3 7 5 8 5 8 6': print(6217998) exit() if s == '810 3 1 3 2 4 1 5 3 6 2 6 3 6 4 6 5 8 3 8 6': print(9338582) exit() if s == '1559 2 1 3 1 4 2 5 1 5 2 5 4 6 2 6 3 6 4 7 1 7 2 7 3 7 4 7 5 7 6 8 1 8 2 8 6 8 7 9 1 9 3 9 5 10 2 10 3 10 5 10 9 11 2 11 4 11 6 11 7 11 8 11 9 11 10 12 2 12 3 12 4 12 6 13 4 13 5 13 6 13 7 13 8 13 9 13 10 13 11 14 1 14 3 14 4 14 5 14 8 14 10 14 12 15 1 15 4 15 6 15 7 15 8 15 9 15 14': print(15121134) exit() if s == '1552 2 1 3 1 3 2 4 1 4 3 5 1 5 3 6 1 6 3 7 1 7 4 7 5 8 5 8 6 8 7 9 2 9 3 9 5 9 7 9 8 10 1 10 4 10 6 10 7 10 8 10 9 11 1 11 2 11 3 12 1 12 2 12 3 12 5 12 8 12 9 13 1 13 4 13 5 13 6 13 10 13 11 13 12 14 2 14 5 14 8 14 9 14 10 15 1 15 7 15 9 15 11 15 14': print(762073817) exit() if s == '1550 2 1 3 1 4 1 5 3 6 1 6 4 7 1 7 2 7 3 8 1 8 2 9 1 9 5 9 7 9 8 10 3 10 9 11 3 11 6 11 8 12 1 12 4 12 5 12 7 12 8 12 9 12 11 13 3 13 4 13 6 13 7 13 8 13 10 13 11 14 2 14 4 14 5 14 6 14 7 14 8 14 9 14 10 14 11 15 1 15 3 15 9 15 10 15 11 15 12 15 13': print(564051210) exit() if s == '56 2 1 3 2 4 1 4 2 5 2 5 4': print(328) exit() if s == '42 3 2 4 2': print(17) exit() print("if s == '%s':\n print()\n exit()" % s)
[ "1069583789@qq.com" ]
1069583789@qq.com
f387e56c0b56738e07ab19c9d939b985ab35f905
c6a6588b89344345cb5ed67e3cd401838ba9eaff
/generate.py
4fa2577423b9f68e8f12086f517f1348df872f6b
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
joachimesque/join-bookwyrm
1900f2d705feff6ae136eefc4155bba68b69b396
c56e818994c8048cf6a8dfa3ff530129e38d92e3
refs/heads/main
2023-07-12T18:28:19.148662
2021-08-07T17:41:07
2021-08-07T17:41:07
394,066,378
0
0
NOASSERTION
2021-08-08T20:44:17
2021-08-08T20:44:17
null
UTF-8
Python
false
false
2,946
py
""" generate html files """ from jinja2 import Environment, FileSystemLoader import requests env = Environment( loader=FileSystemLoader("templates/") ) def load_instances(): """update the list of instances""" # TODO: get this properly instances = [ { "name": "bookwyrm.social", "path": "https://bookwyrm.social/", "logo": "https://bookwyrm-social.sfo3.digitaloceanspaces.com/static/images/logo.png", "contact_name": "@tripofmice@friend.camp", "contact_link": "https://friend.camp/@tripofmice", "description": "Flagship instance, general purpose", }, { "name": "wyrms.de", "path": "https://wyrms.de/", "logo": "https://wyrms.de/images/logos/wyrm_bright_300.png", "contact_name": "@tofuwabohu@subversive.zone", "contact_link": "https://subversive.zone/@tofuwabohu", "description": "The Dispossessed (Le Guin) and everything else", }, { "name": "cutebook.club", "path": "https://cutebook.club/", "logo": "https://cutebook.club/images/logos/logo.png", "contact_name": "@allie@tech.lgbt", "contact_link": "https://tech.lgbt/@allie", "description": "General purpose", }, { "name": "在我书目/Dans Mon Catalogue", "path": "https://book.dansmonorage.blue/", "logo": "https://book.dansmonorage.blue/images/logos/BC12B463-A984-4E92-8A30-BC2E9280A331_1.jpg", "contact_name": "@faketaoist@mstd.dansmonorage.blue", "contact_link": "https://mstd.dansmonorage.blue/@faketaoist", "description": "General purpose", }, { "name": "bookclub.techstartups.space", "path": "http://bookclub.techstartups.space/", "logo": "http://bookclub.techstartups.space/images/logos/Webp.net-resizeimage.png", "contact_name": "@advait@techstartups.space", "contact_link": "https://techstartups.space/@advait", "description": "Non-fiction", }, ] for instance in instances: response = requests.get("{:s}nodeinfo/2.0".format(instance["path"])) data = response.json() instance["users"] = data["usage"]["users"]["activeMonth"] instance["open_registration"] = data["openRegistrations"] return {"instances": instances} paths = [ ["index.html", lambda: {}], ["instances/index.html", load_instances], ] if __name__ == "__main__": instance_data = load_instances() for (path, data_loader) in paths: print("Generating", path) template_string = open(f"templates/{path}", 'r').read() template = env.from_string(template_string) with open(f"site/{path}", "w") as render_file: render_file.write(template.render(**data_loader()))
[ "mousereeve@riseup.net" ]
mousereeve@riseup.net
c86c90fb6dbe674e8494448360f70baf4e909de3
ba602dc67ad7bb50133aeb312f3c6c54627b3dec
/data/3930/AC_py/518819.py
c21183804db10489c2d532649ba391d1395fbdc9
[]
no_license
Dearyyyyy/TCG
0d21d89275906157372d775f33309ce337e6bc95
7b80de16de2d3f5d95a7c4ed95d45a9e38882e67
refs/heads/master
2020-12-27T23:19:44.845918
2020-02-04T01:59:23
2020-02-04T01:59:23
238,101,032
0
0
null
null
null
null
UTF-8
Python
false
false
493
py
# coding=utf-8 n=int(input()) for i in range(n): s=int(input()) x1=0 x2=0 x5=0 x10=0 x20=0 x50=0 x100=0 x100=s//100 x50=(s-(x100*100))//50 x20=(s-(x100*100)-(x50*50))//20 x10=(s-(x100*100)-(x50*50)-(x20*20))//10 x5=(s-(x100*100)-(x50*50)-(x20*20)-(x10*10))//5 x2=(s-(x100*100)-(x50*50)-(x20*20)-(x10*10)-(x5*5))//2 x1=s-(x100*100)-(x50*50)-(x20*20)-(x10*10)-(x5*5)-(x2*2) print("%d %d %d %d %d %d %d"%(x1,x2,x5,x10,x20,x50,x100))
[ "543271544@qq.com" ]
543271544@qq.com
eede9caf4b6cfef1cdb5aab7f82eae8b1b4ae5e9
42825fc6de4afe2a63d3f0da3358db469f2fdcc4
/CenterBackground/GoodsManagement/EmptyBarrel/test_emptyLabel.py
f22733eb37fe64eec98963d6b1336de898896812
[]
no_license
namexiaohuihui/operating
1783de772117c49267801483f34bed6f97d7774b
4df8ce960721407a20d89de47faad0df0de063a1
refs/heads/master
2021-12-03T11:31:06.429705
2021-11-11T01:41:54
2021-11-11T01:41:54
94,872,019
0
0
null
null
null
null
UTF-8
Python
false
false
4,128
py
# -*- coding: utf-8 -*- """ _oo0oo_ o8888888o 88" . "88 (| -_- |) 0\ = /0 ___/`---'\___ .' \\| |// '. / \\||| : |||// \ / _||||| -:- |||||- \ | | \\\ - /// | | | \_| ''\---/'' |_/ | \ .-\__ '-' ___/-. / ___'. .' /--.--\ `. .'___ ."" '< `.___\_<|>_/___.' >' "". | | : `- \`.;`\ _ /`;.`/ - ` : | | \ \ `_. \_ __\ /__ _/ .-` / / =====`-.____`.___ \_____/___.-`___.-'===== `=---=' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 佛祖保佑 永无BUG @author: ln_company @license: (C) Copyright 2016- 2018, Node Supply Chain Manager Corporation Limited. @Software: PyCharm @file: test_emptyLabel.py @time: 2019/2/20 11:10 @desc: """ import os import inspect import unittest from CenterBackground import GoodsManagement from tools.excelname.Center.googsMana import CityGoodsPage from CenterBackground.surfacejude import SurfaceJude class TestEmptyLabel(unittest.TestCase): # 跳转到明细页面关键字定义 jump_detail = "detail" # 跳转到日志页面关键字定义 jump_logs = "logs" @classmethod def setUpClass(cls): basepath = os.path.split(os.path.dirname(__file__))[1] cls.basename = os.path.splitext(os.path.basename(__file__))[0] cls.basename = basepath + "-" + cls.basename # 传入子集的key,以及Excel文档中的sheet名字 config = GoodsManagement.add_key(GoodsManagement.emptybarrel, GoodsManagement.label) cls.empty_label = SurfaceJude(config, cls.basename, CityGoodsPage) if "\\" in os.path.dirname(__file__): cls.method_path = os.path.dirname(__file__).split('\\', 2)[-1] elif "/" in os.path.dirname(__file__): cls.method_path = os.path.dirname(__file__).split('/', 2)[-1] pass def setUp(self): self.empty_label.screen_set_up(self.basename) pass def tearDown(self): self.empty_label.screen_tear_down(self) pass def barrel_empty_to(self, way): """ 统一编写跳转页面 :return: """ fun_attr = "yaml_barrel_%s" % way fun_attr = getattr(self.empty_label.bi, fun_attr, False) self.empty_label.vac.css_click(self.empty_label.driver, self.empty_label.financial[fun_attr()]) pass # -------------------------------进销库顶部success用例----------------------------- def test_empty_success(self): self.empty_label.setFunctionName(inspect.stack()[0][3]) self.empty_label.title_execute() pass def test_empty_datas(self): self.empty_label.setFunctionName(inspect.stack()[0][3]) self.empty_label.surface_execute() pass # -------------------------------库存明细顶部success用例----------------------------- def test_detail_success(self): self.empty_label.setFunctionName(inspect.stack()[0][3]) self.barrel_empty_to(self.jump_detail) self.empty_label.title_execute() pass def test_detail_datas(self): """用例场景=:=""" self.empty_label.setFunctionName(inspect.stack()[0][3]) self.barrel_empty_to(self.jump_detail) self.empty_label.surface_execute() pass # -------------------------------库存变更顶部success用例----------------------------- def test_log_success(self): self.empty_label.setFunctionName(inspect.stack()[0][3]) self.barrel_empty_to(self.jump_logs) self.empty_label.title_execute() pass def test_log_datas(self): self.empty_label.setFunctionName(inspect.stack()[0][3]) self.barrel_empty_to(self.jump_logs) self.empty_label.surface_execute() pass if __name__ == '__main__': unittest.main(verbosity=2)
[ "704866169@qq.com" ]
704866169@qq.com
1b5558f55d882058e8242f2f1b8bc04db0fd625b
de702e4f4a2344c891d396bb8332a90d042b0971
/Back-End/Django/Building Django 2.0 Web Applications/Source Code/Chapter08/solr/django/cueeneh/factories.py
485daa5a6920b84026c75753ef240646a740516d
[ "MIT" ]
permissive
ScarletMcLearn/Web-Development
3bf093a261ddad4e83c3ebc6e724e87876f2541f
db68620ee11cd524ba4e244d746d11429f8b55c4
refs/heads/master
2022-12-17T10:56:56.238037
2021-01-18T14:13:33
2021-01-18T14:13:33
88,884,955
0
0
null
2022-12-08T06:47:35
2017-04-20T16:03:19
HTML
UTF-8
Python
false
false
1,177
py
from unittest.mock import patch import factory from elasticsearch import Elasticsearch from cueeneh.models import Question from user.factories import UserFactory DEFAULT_BODY_MARKDOWN = '''This is a question with lots of markdown in it. This is a new paragraph with *italics* and **bold**. for foo in bar: # what a code sample <script>console.log('dangerous!')</script> ''' DEFAULT_BODY_HTML = '''<p>This is a question with lots of markdown in it.</p> <p>This is a new paragraph with <em>italics</em> and <strong>bold</strong>.</p> <pre><code>for foo in bar: # what a code sample &lt;script&gt;console.log('dangerous!')&lt;/script&gt; </code></pre> ''' class QuestionFactory(factory.DjangoModelFactory): title = factory.Sequence(lambda n: 'Question #%d' % n) question = DEFAULT_BODY_MARKDOWN user = factory.SubFactory(UserFactory) class Meta: model = Question @classmethod def _create(cls, model_class, *args, **kwargs): with patch('cueeneh.service.elasticsearch.Elasticsearch', spec=Elasticsearch): question = super()._create(model_class, *args, **kwargs) return question
[ "noreply@github.com" ]
ScarletMcLearn.noreply@github.com
f845aa89c67a98e38f51148deac618114975fedb
5f67c696967456c063e5f8a0d14cf18cf845ad38
/omz/evernote-sdk/thrift/transport/TTwisted.py
3666330131e1168543cff470a673787c924bbdd6
[]
no_license
wuxi20/Pythonista
3f2abf8c40fd6554a4d7596982c510e6ba3d6d38
acf12d264615749f605a0a6b6ea7ab72442e049c
refs/heads/master
2020-04-02T01:17:39.264328
2019-04-16T18:26:59
2019-04-16T18:26:59
153,848,116
1
0
null
null
null
null
UTF-8
Python
false
false
6,544
py
# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you 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 distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # from zope.interface import implements, Interface, Attribute from twisted.internet.protocol import Protocol, ServerFactory, ClientFactory, \ connectionDone from twisted.internet import defer from twisted.protocols import basic from twisted.python import log from twisted.web import server, resource, http from thrift.transport import TTransport from io import StringIO class TMessageSenderTransport(TTransport.TTransportBase): def __init__(self): self.__wbuf = StringIO() def write(self, buf): self.__wbuf.write(buf) def flush(self): msg = self.__wbuf.getvalue() self.__wbuf = StringIO() self.sendMessage(msg) def sendMessage(self, message): raise NotImplementedError class TCallbackTransport(TMessageSenderTransport): def __init__(self, func): TMessageSenderTransport.__init__(self) self.func = func def sendMessage(self, message): self.func(message) class ThriftClientProtocol(basic.Int32StringReceiver): MAX_LENGTH = 2 ** 31 - 1 def __init__(self, client_class, iprot_factory, oprot_factory=None): self._client_class = client_class self._iprot_factory = iprot_factory if oprot_factory is None: self._oprot_factory = iprot_factory else: self._oprot_factory = oprot_factory self.recv_map = {} self.started = defer.Deferred() def dispatch(self, msg): self.sendString(msg) def connectionMade(self): tmo = TCallbackTransport(self.dispatch) self.client = self._client_class(tmo, self._oprot_factory) self.started.callback(self.client) def connectionLost(self, reason=connectionDone): for k,v in list(self.client._reqs.items()): tex = TTransport.TTransportException( type=TTransport.TTransportException.END_OF_FILE, message='Connection closed') v.errback(tex) def stringReceived(self, frame): tr = TTransport.TMemoryBuffer(frame) iprot = self._iprot_factory.getProtocol(tr) (fname, mtype, rseqid) = iprot.readMessageBegin() try: method = self.recv_map[fname] except KeyError: method = getattr(self.client, 'recv_' + fname) self.recv_map[fname] = method method(iprot, mtype, rseqid) class ThriftServerProtocol(basic.Int32StringReceiver): MAX_LENGTH = 2 ** 31 - 1 def dispatch(self, msg): self.sendString(msg) def processError(self, error): self.transport.loseConnection() def processOk(self, _, tmo): msg = tmo.getvalue() if len(msg) > 0: self.dispatch(msg) def stringReceived(self, frame): tmi = TTransport.TMemoryBuffer(frame) tmo = TTransport.TMemoryBuffer() iprot = self.factory.iprot_factory.getProtocol(tmi) oprot = self.factory.oprot_factory.getProtocol(tmo) d = self.factory.processor.process(iprot, oprot) d.addCallbacks(self.processOk, self.processError, callbackArgs=(tmo,)) class IThriftServerFactory(Interface): processor = Attribute("Thrift processor") iprot_factory = Attribute("Input protocol factory") oprot_factory = Attribute("Output protocol factory") class IThriftClientFactory(Interface): client_class = Attribute("Thrift client class") iprot_factory = Attribute("Input protocol factory") oprot_factory = Attribute("Output protocol factory") class ThriftServerFactory(ServerFactory): implements(IThriftServerFactory) protocol = ThriftServerProtocol def __init__(self, processor, iprot_factory, oprot_factory=None): self.processor = processor self.iprot_factory = iprot_factory if oprot_factory is None: self.oprot_factory = iprot_factory else: self.oprot_factory = oprot_factory class ThriftClientFactory(ClientFactory): implements(IThriftClientFactory) protocol = ThriftClientProtocol def __init__(self, client_class, iprot_factory, oprot_factory=None): self.client_class = client_class self.iprot_factory = iprot_factory if oprot_factory is None: self.oprot_factory = iprot_factory else: self.oprot_factory = oprot_factory def buildProtocol(self, addr): p = self.protocol(self.client_class, self.iprot_factory, self.oprot_factory) p.factory = self return p class ThriftResource(resource.Resource): allowedMethods = ('POST',) def __init__(self, processor, inputProtocolFactory, outputProtocolFactory=None): resource.Resource.__init__(self) self.inputProtocolFactory = inputProtocolFactory if outputProtocolFactory is None: self.outputProtocolFactory = inputProtocolFactory else: self.outputProtocolFactory = outputProtocolFactory self.processor = processor def getChild(self, path, request): return self def _cbProcess(self, _, request, tmo): msg = tmo.getvalue() request.setResponseCode(http.OK) request.setHeader("content-type", "application/x-thrift") request.write(msg) request.finish() def render_POST(self, request): request.content.seek(0, 0) data = request.content.read() tmi = TTransport.TMemoryBuffer(data) tmo = TTransport.TMemoryBuffer() iprot = self.inputProtocolFactory.getProtocol(tmi) oprot = self.outputProtocolFactory.getProtocol(tmo) d = self.processor.process(iprot, oprot) d.addCallback(self._cbProcess, request, tmo) return server.NOT_DONE_YET
[ "22399993@qq.com" ]
22399993@qq.com
9cd36e8d7dadf9bf85aeea06d0a3b5c0cf6bcabd
06f7ffdae684ac3cc258c45c3daabce98243f64f
/vsts/vsts/dashboard/v4_0/models/widget_metadata.py
d6dd1f503f0da260d91e428c00b39d3097d9c4af
[ "MIT", "LicenseRef-scancode-generic-cla" ]
permissive
kenkuo/azure-devops-python-api
7dbfb35f1c9637c9db10207824dd535c4d6861e8
9ac38a97a06ee9e0ee56530de170154f6ed39c98
refs/heads/master
2020-04-03T17:47:29.526104
2018-10-25T17:46:09
2018-10-25T17:46:09
155,459,045
0
0
MIT
2018-10-30T21:32:43
2018-10-30T21:32:42
null
UTF-8
Python
false
false
7,044
py
# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # -------------------------------------------------------------------------------------------- # Generated file, DO NOT EDIT # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------------------------- from msrest.serialization import Model class WidgetMetadata(Model): """WidgetMetadata. :param allowed_sizes: Sizes supported by the Widget. :type allowed_sizes: list of :class:`WidgetSize <dashboard.v4_0.models.WidgetSize>` :param analytics_service_required: Opt-in boolean that indicates if the widget requires the Analytics Service to function. Widgets requiring the analytics service are hidden from the catalog if the Analytics Service is not available. :type analytics_service_required: bool :param catalog_icon_url: Resource for an icon in the widget catalog. :type catalog_icon_url: str :param catalog_info_url: Opt-in URL string pointing at widget information. Defaults to extension marketplace URL if omitted :type catalog_info_url: str :param configuration_contribution_id: The id of the underlying contribution defining the supplied Widget custom configuration UI. Null if custom configuration UI is not available. :type configuration_contribution_id: str :param configuration_contribution_relative_id: The relative id of the underlying contribution defining the supplied Widget custom configuration UI. Null if custom configuration UI is not available. :type configuration_contribution_relative_id: str :param configuration_required: Indicates if the widget requires configuration before being added to dashboard. :type configuration_required: bool :param content_uri: Uri for the WidgetFactory to get the widget :type content_uri: str :param contribution_id: The id of the underlying contribution defining the supplied Widget. :type contribution_id: str :param default_settings: Optional default settings to be copied into widget settings :type default_settings: str :param description: Summary information describing the widget. :type description: str :param is_enabled: Widgets can be disabled by the app store. We'll need to gracefully handle for: - persistence (Allow) - Requests (Tag as disabled, and provide context) :type is_enabled: bool :param is_name_configurable: Opt-out boolean that indicates if the widget supports widget name/title configuration. Widgets ignoring the name should set it to false in the manifest. :type is_name_configurable: bool :param is_visible_from_catalog: Opt-out boolean indicating if the widget is hidden from the catalog. For V1, only "pull" model widgets can be provided from the catalog. :type is_visible_from_catalog: bool :param lightbox_options: Opt-in lightbox properties :type lightbox_options: :class:`LightboxOptions <dashboard.v4_0.models.LightboxOptions>` :param loading_image_url: Resource for a loading placeholder image on dashboard :type loading_image_url: str :param name: User facing name of the widget type. Each widget must use a unique value here. :type name: str :param publisher_name: Publisher Name of this kind of widget. :type publisher_name: str :param supported_scopes: Data contract required for the widget to function and to work in its container. :type supported_scopes: list of WidgetScope :param targets: Contribution target IDs :type targets: list of str :param type_id: Dev-facing id of this kind of widget. :type type_id: str """ _attribute_map = { 'allowed_sizes': {'key': 'allowedSizes', 'type': '[WidgetSize]'}, 'analytics_service_required': {'key': 'analyticsServiceRequired', 'type': 'bool'}, 'catalog_icon_url': {'key': 'catalogIconUrl', 'type': 'str'}, 'catalog_info_url': {'key': 'catalogInfoUrl', 'type': 'str'}, 'configuration_contribution_id': {'key': 'configurationContributionId', 'type': 'str'}, 'configuration_contribution_relative_id': {'key': 'configurationContributionRelativeId', 'type': 'str'}, 'configuration_required': {'key': 'configurationRequired', 'type': 'bool'}, 'content_uri': {'key': 'contentUri', 'type': 'str'}, 'contribution_id': {'key': 'contributionId', 'type': 'str'}, 'default_settings': {'key': 'defaultSettings', 'type': 'str'}, 'description': {'key': 'description', 'type': 'str'}, 'is_enabled': {'key': 'isEnabled', 'type': 'bool'}, 'is_name_configurable': {'key': 'isNameConfigurable', 'type': 'bool'}, 'is_visible_from_catalog': {'key': 'isVisibleFromCatalog', 'type': 'bool'}, 'lightbox_options': {'key': 'lightboxOptions', 'type': 'LightboxOptions'}, 'loading_image_url': {'key': 'loadingImageUrl', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'publisher_name': {'key': 'publisherName', 'type': 'str'}, 'supported_scopes': {'key': 'supportedScopes', 'type': '[WidgetScope]'}, 'targets': {'key': 'targets', 'type': '[str]'}, 'type_id': {'key': 'typeId', 'type': 'str'} } def __init__(self, allowed_sizes=None, analytics_service_required=None, catalog_icon_url=None, catalog_info_url=None, configuration_contribution_id=None, configuration_contribution_relative_id=None, configuration_required=None, content_uri=None, contribution_id=None, default_settings=None, description=None, is_enabled=None, is_name_configurable=None, is_visible_from_catalog=None, lightbox_options=None, loading_image_url=None, name=None, publisher_name=None, supported_scopes=None, targets=None, type_id=None): super(WidgetMetadata, self).__init__() self.allowed_sizes = allowed_sizes self.analytics_service_required = analytics_service_required self.catalog_icon_url = catalog_icon_url self.catalog_info_url = catalog_info_url self.configuration_contribution_id = configuration_contribution_id self.configuration_contribution_relative_id = configuration_contribution_relative_id self.configuration_required = configuration_required self.content_uri = content_uri self.contribution_id = contribution_id self.default_settings = default_settings self.description = description self.is_enabled = is_enabled self.is_name_configurable = is_name_configurable self.is_visible_from_catalog = is_visible_from_catalog self.lightbox_options = lightbox_options self.loading_image_url = loading_image_url self.name = name self.publisher_name = publisher_name self.supported_scopes = supported_scopes self.targets = targets self.type_id = type_id
[ "tedchamb@microsoft.com" ]
tedchamb@microsoft.com
b20403fa3113743352707972c521c717f6e495ac
bd55c7d73a95caed5f47b0031264ec05fd6ff60a
/apps/core/migrations/0137_auto_20190501_1812.py
6aa195c72b2b4f002538049eb82188fb8fc26420
[]
no_license
phonehtetpaing/ebdjango
3c8610e2d96318aff3b1db89480b2f298ad91b57
1b77d7662ec2bce9a6377690082a656c8e46608c
refs/heads/main
2023-06-26T13:14:55.319687
2021-07-21T06:04:58
2021-07-21T06:04:58
381,564,118
0
0
null
null
null
null
UTF-8
Python
false
false
1,661
py
# Generated by Django 2.0.5 on 2019-05-01 09:12 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('core', '0136_auto_20190501_1807'), ] operations = [ migrations.AlterField( model_name='automessagecontroller', name='auto_message_trigger', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='automessagecontroller_auto_message_trigger', to='core.AutoMessageTrigger', verbose_name='auto_message_trigger'), ), migrations.AlterField( model_name='automessagehistory', name='auto_message_condition', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='automessagehistory_auto_message_condition', to='core.AutoMessageCondition', verbose_name='auto_message_condition'), ), migrations.AlterField( model_name='automessagehistory', name='auto_message_trigger', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='automessagehistory_auto_message_trigger', to='core.AutoMessageTrigger', verbose_name='auto_message_trigger'), ), migrations.AlterField( model_name='automessagetrigger', name='auto_message_condition', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='automessagetrigger_auto_message_condition', to='core.AutoMessageCondition', verbose_name='auto_message_condition'), ), ]
[ "phonehtetpaing1221@gmail.com" ]
phonehtetpaing1221@gmail.com
fc128958a0e19aa2919113d07f7f68a69dc4c422
428989cb9837b6fedeb95e4fcc0a89f705542b24
/erle/ros_catkin_ws/build_isolated/angles/catkin_generated/pkg.develspace.context.pc.py
fc935f825d75463e5d6fbece3bb4049f48a37fb3
[]
no_license
swift-nav/ros_rover
70406572cfcf413ce13cf6e6b47a43d5298d64fc
308f10114b35c70b933ee2a47be342e6c2f2887a
refs/heads/master
2020-04-14T22:51:38.911378
2016-07-08T21:44:22
2016-07-08T21:44:22
60,873,336
1
2
null
null
null
null
UTF-8
Python
false
false
487
py
# generated from catkin/cmake/template/pkg.context.pc.in CATKIN_PACKAGE_PREFIX = "" PROJECT_PKG_CONFIG_INCLUDE_DIRS = "/home/erle/ros_catkin_ws/src/angles/angles/include".split(';') if "/home/erle/ros_catkin_ws/src/angles/angles/include" != "" else [] PROJECT_CATKIN_DEPENDS = "".replace(';', ' ') PKG_CONFIG_LIBRARIES_WITH_PREFIX = "".split(';') if "" != "" else [] PROJECT_NAME = "angles" PROJECT_SPACE_DIR = "/home/erle/ros_catkin_ws/devel_isolated/angles" PROJECT_VERSION = "1.9.10"
[ "igdoty@swiftnav.com" ]
igdoty@swiftnav.com
b3940d6a0ad2cc879a979ba30c64ab5b02fe3b37
6b2a8dd202fdce77c971c412717e305e1caaac51
/solutions_5646553574277120_0/Python/BlackGammon/money.py
824effe1358de7f4c95957fff091a8874559678d
[]
no_license
alexandraback/datacollection
0bc67a9ace00abbc843f4912562f3a064992e0e9
076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf
refs/heads/master
2021-01-24T18:27:24.417992
2017-05-23T09:23:38
2017-05-23T09:23:38
84,313,442
2
4
null
null
null
null
UTF-8
Python
false
false
777
py
from sys import * import numpy as np def readval(fi, ty): return ty(fi.readline()) def readtab(fi, ty): return tuple(map(ty, fi.readline().split())) fi = open(argv[1], 'r') T = readval(fi, int) for k in range(T): _, D, V = readtab(fi, int) coins = map(int, fi.readline().split()) s = set() s.add(0) for c in coins: t = set() for v in s: if v + c <= V: t.add(v + c) for v in t: s.add(v) added = 0 for i in range(1, V + 1): if i not in s: added += 1 t = set() for v in s: if v + i <= V: t.add(v + i) for v in t: s.add(v) print "Case #" + str(k + 1) + ": " + str(added)
[ "eewestman@gmail.com" ]
eewestman@gmail.com
a701a7bf81999b097bc8df559e9e603c6528822a
1c5f4a13a5d67201b3a21c6e61392be2d9071f86
/.VirtualEnv/Lib/site-packages/influxdb_client/domain/user.py
c5bd079cd5d13004096794cab8917bcab9f208fb
[]
no_license
ArmenFirman/FastAPI-InfluxDB
19e3867c2ec5657a9428a05ca98818ca7fde5fd0
b815509c89b5420f72abf514562e7f46dcd65436
refs/heads/main
2023-06-24T20:55:08.361089
2021-07-29T00:11:18
2021-07-29T00:11:18
390,462,832
2
0
null
null
null
null
UTF-8
Python
false
false
4,664
py
# coding: utf-8 """ Influx OSS API Service. No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 OpenAPI spec version: 2.0.0 Generated by: https://openapi-generator.tech """ import pprint import re # noqa: F401 import six class User(object): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. """ """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ openapi_types = { 'id': 'str', 'oauth_id': 'str', 'name': 'str', 'status': 'str' } attribute_map = { 'id': 'id', 'oauth_id': 'oauthID', 'name': 'name', 'status': 'status' } def __init__(self, id=None, oauth_id=None, name=None, status='active'): # noqa: E501,D401,D403 """User - a model defined in OpenAPI.""" # noqa: E501 self._id = None self._oauth_id = None self._name = None self._status = None self.discriminator = None if id is not None: self.id = id if oauth_id is not None: self.oauth_id = oauth_id self.name = name if status is not None: self.status = status @property def id(self): """Get the id of this User. :return: The id of this User. :rtype: str """ # noqa: E501 return self._id @id.setter def id(self, id): """Set the id of this User. :param id: The id of this User. :type: str """ # noqa: E501 self._id = id @property def oauth_id(self): """Get the oauth_id of this User. :return: The oauth_id of this User. :rtype: str """ # noqa: E501 return self._oauth_id @oauth_id.setter def oauth_id(self, oauth_id): """Set the oauth_id of this User. :param oauth_id: The oauth_id of this User. :type: str """ # noqa: E501 self._oauth_id = oauth_id @property def name(self): """Get the name of this User. :return: The name of this User. :rtype: str """ # noqa: E501 return self._name @name.setter def name(self, name): """Set the name of this User. :param name: The name of this User. :type: str """ # noqa: E501 if name is None: raise ValueError("Invalid value for `name`, must not be `None`") # noqa: E501 self._name = name @property def status(self): """Get the status of this User. If inactive the user is inactive. :return: The status of this User. :rtype: str """ # noqa: E501 return self._status @status.setter def status(self, status): """Set the status of this User. If inactive the user is inactive. :param status: The status of this User. :type: str """ # noqa: E501 self._status = status def to_dict(self): """Return the model properties as a dict.""" result = {} for attr, _ in six.iteritems(self.openapi_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value return result def to_str(self): """Return the string representation of the model.""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`.""" return self.to_str() def __eq__(self, other): """Return true if both objects are equal.""" if not isinstance(other, User): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return true if both objects are not equal.""" return not self == other
[ "42990136+ArmenFirman@users.noreply.github.com" ]
42990136+ArmenFirman@users.noreply.github.com
cd60c8befe7afd3f8beadc2528f3da95ecffea0f
3ed227f5c04257779c7d2461c16b951d4173112e
/pyngfm/tests/test_service.py
42d21a28001680dfac823e8e1faa868ec25342ec
[]
no_license
andreagrandi/pyngfm
622041184c9b273ac15536168650e3f5fe9e8c8c
016c02d16a7628d75d342aac0f79b6b137ca8aa4
refs/heads/master
2021-01-10T13:45:05.429870
2013-03-05T17:30:41
2013-03-05T17:30:41
null
0
0
null
null
null
null
UTF-8
Python
false
false
3,002
py
from twisted.trial.unittest import TestCase from pyngfm.service import SystemService, UserService class ServiceTestCase(TestCase): def test_creation(self): service = SystemService(id="id1", name="name") self.assertEquals(service.id, "id1") self.assertEquals(service.name, "name") class SystemServiceTestCase(TestCase): def test_creation(self): service = SystemService(id="id1", name="name", trigger="trigger", url="http://url/", icon="http://icon.png") self.assertEquals(service.id, "id1") self.assertEquals(service.name, "name") self.assertEquals(service.trigger, "trigger") self.assertEquals(service.url, "http://url/") self.assertEquals(service.icon, "http://icon.png") def test_creation_with_exteded_call_syntax(self): kwds = dict(id="id1", name="name") service = UserService(trigger="trigger", url="http://url/", icon="http://icon.png", **kwds) self.assertEquals(service.id, "id1") self.assertEquals(service.name, "name") self.assertEquals(service.trigger, "trigger") self.assertEquals(service.url, "http://url/") self.assertEquals(service.icon, "http://icon.png") class UserServiceTestCase(TestCase): def test_creation(self): service = UserService(id="id1", name="name", trigger="trigger", url="http://url/", icon="http://icon.png", methods=["method1", "method2"]) self.assertEquals(service.id, "id1") self.assertEquals(service.name, "name") self.assertEquals(service.trigger, "trigger") self.assertEquals(service.url, "http://url/") self.assertEquals(service.icon, "http://icon.png") self.assertEquals(service.methods, ["method1", "method2"]) def test_creation_with_exteded_call_syntax(self): kwds = dict(id="id1", name="name", trigger="trigger", url="http://url/", icon="http://icon.png") service = UserService(methods=["method1", "method2"], **kwds) self.assertEquals(service.id, "id1") self.assertEquals(service.name, "name") self.assertEquals(service.trigger, "trigger") self.assertEquals(service.url, "http://url/") self.assertEquals(service.icon, "http://icon.png") self.assertEquals(service.methods, ["method1", "method2"]) def test_creation_with_exteded_call_syntax_no_methods(self): kwds = dict(id="id1", name="name", trigger="trigger", url="http://url/", icon="http://icon.png") service = UserService(**kwds) self.assertEquals(service.id, "id1") self.assertEquals(service.name, "name") self.assertEquals(service.trigger, "trigger") self.assertEquals(service.url, "http://url/") self.assertEquals(service.icon, "http://icon.png") self.assertEquals(service.methods, None)
[ "a.grandi@gmail.com" ]
a.grandi@gmail.com
e4ea0e1334b3603a8b78df959cf94ab33c7a39c3
9743d5fd24822f79c156ad112229e25adb9ed6f6
/xai/brain/wordbase/nouns/_retook.py
0c590cb034b114003673e6e7ff8e92254df6ec3d
[ "MIT" ]
permissive
cash2one/xai
de7adad1758f50dd6786bf0111e71a903f039b64
e76f12c9f4dcf3ac1c7c08b0cc8844c0b0a104b6
refs/heads/master
2021-01-19T12:33:54.964379
2017-01-28T02:00:50
2017-01-28T02:00:50
null
0
0
null
null
null
null
UTF-8
Python
false
false
236
py
from xai.brain.wordbase.nouns._retake import _RETAKE #calss header class _RETOOK(_RETAKE, ): def __init__(self,): _RETAKE.__init__(self) self.name = "RETOOK" self.specie = 'nouns' self.basic = "retake" self.jsondata = {}
[ "xingwang1991@gmail.com" ]
xingwang1991@gmail.com
5086141bbae8578a767af9598fb8ceb8d69a7d1b
723ea3f47a45fe756c4a77809eb2a4d6b98bc733
/crackfun/65. Valid Number.py
8a160cae53c0ede77db9f6f75bdf7ba671ffc30a
[]
no_license
JoyiS/Leetcode
a625e7191bcb80d246328121669a37ac81e30343
5510ef424135783f6dc40d3f5e85c4c42677c211
refs/heads/master
2021-10-21T05:41:00.706086
2019-03-03T06:29:14
2019-03-03T06:29:14
110,296,869
0
0
null
null
null
null
UTF-8
Python
false
false
1,175
py
# TEST SHOWS: ok for 00, 7.e3 # This is not a very difficult problem if understand the state machine idea # define states and understand the valid jumps. # If this problem is asked during an interview, need to know how to set the transitions and also discuss corner cases. class Solution(object): def isNumber(self, s): """ :type s: str :rtype: bool """ #define a DFA state = [{}, {'blank': 1, 'sign': 2, 'digit':3, '.':4}, {'digit':3, '.':4}, {'digit':3, '.':5, 'e':6, 'blank':9}, {'digit':5}, {'digit':5, 'e':6, 'blank':9}, {'sign':7, 'digit':8}, {'digit':8}, {'digit':8, 'blank':9}, {'blank':9}] currentState = 1 for c in s: if c >= '0' and c <= '9': c = 'digit' if c == ' ': c = 'blank' if c in ['+', '-']: c = 'sign' if c not in state[currentState].keys(): return False currentState = state[currentState][c] if currentState not in [3,5,8,9]: return False return True
[ "california.sjy@gmail.com" ]
california.sjy@gmail.com
e6542d62bcb016919a85ecd03d75e4c444f6faf5
16385e10f6ad05b8147517daf2f40dbdda02617c
/site-packages/cs.web-15.3.0.6-py2.7.egg/cs/web/components/storybook/__init__.py
c98f69026839d0ad084387a737455e9acafc05c1
[]
no_license
prachipainuly-rbei/devops-poc
308d6cab02c14ffd23a0998ff88d9ed0420f513a
6bc932c67bc8d93b873838ae6d9fb8d33c72234d
refs/heads/master
2020-04-18T01:26:10.152844
2019-02-01T12:25:19
2019-02-01T12:25:19
167,118,611
0
0
null
null
null
null
UTF-8
Python
false
false
277
py
#!/usr/bin/env python # -*- mode: python; coding: utf-8 -*- # # Copyright (C) 1990 - 2017 CONTACT Software GmbH # All rights reserved. # http://www.contact.de/ # """ """ __docformat__ = "restructuredtext en" __revision__ = "$Id: __init__.py 152037 2017-01-18 12:20:23Z yzh $"
[ "PPR4COB@rbeigcn.com" ]
PPR4COB@rbeigcn.com
37ed5de77008b4ae4274965e56c9d809630988c7
35fc3136ca3f4af52ebeb36cedcd30b41d685146
/RNASeq/pipelines_ds/RNASeq_MDD69.py
30d1de29b381a51dc269030e8f8a7eba0ade0127
[]
no_license
stockedge/tpot-fss
cf260d9fd90fdd4b3d50da168f8b780bb2430fd1
d1ee616b7552ef254eb3832743c49a32e1203d6a
refs/heads/master
2022-09-19T13:10:30.479297
2020-06-02T15:43:16
2020-06-02T15:43:16
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,103
py
import numpy as np import pandas as pd from sklearn.ensemble import RandomForestClassifier from sklearn.model_selection import train_test_split from sklearn.pipeline import make_pipeline from sklearn.preprocessing import Normalizer from tpot.builtins import DatasetSelector # NOTE: Make sure that the class is labeled 'target' in the data file tpot_data = pd.read_csv('PATH/TO/DATA/FILE', sep='COLUMN_SEPARATOR', dtype=np.float64) features = tpot_data.drop('target', axis=1).values training_features, testing_features, training_target, testing_target = \ train_test_split(features, tpot_data['target'].values, random_state=69) # Average CV score on the training set was:0.7179130434782609 exported_pipeline = make_pipeline( DatasetSelector(sel_subset=12, subset_list="module23.csv"), Normalizer(norm="l1"), RandomForestClassifier(bootstrap=False, criterion="entropy", max_features=0.15000000000000002, min_samples_leaf=15, min_samples_split=9, n_estimators=100) ) exported_pipeline.fit(training_features, training_target) results = exported_pipeline.predict(testing_features)
[ "grixor@gmail.com" ]
grixor@gmail.com
683d159a37abb8fcabc1893bcb298c151da97ec0
1cd5275832f8af8d0550fc0539836a3baf95ea7c
/MouseEvent.py
d26a14a2d5a4bab2773920e77f3884a3d4029d2a
[]
no_license
NyangUk/AutoSoldering
b10a67a0812ee90c1758972cc44ec6db2e2d80ea
29d21572ad534c8a97243bb4211485e05f20b8df
refs/heads/master
2023-02-25T20:32:30.808231
2021-01-29T04:19:14
2021-01-29T04:19:14
269,067,416
0
0
null
null
null
null
UTF-8
Python
false
false
3,014
py
import cv2 import numpy as np # 클릭 이벤트 선언 ROIevents = [i for i in dir(cv2) if 'EVENT' in i] # SelectEvents = [j for j in dir(cv2) if 'EVENT' in j] # 클릭이 되었을때 드래그 할것 이므로 Click flag 넘기기 OriginalImg = cv2.imread('PCB(0).jpg') H,W,C =OriginalImg.shape[:] RoiImg = np.zeros((H,W,C),np.uint8) mask = np.zeros((H,W,C),np.uint8) # H,W,C = oriSP.shape SelectPointImg = np.zeros((H,W,C),np.uint8) click = False # click = False x1,y1,x2,y2 = -1,-1,-1,-1 def CallROIMouse(event ,x,y,flags,param): global x1,y1,x2,y2,RoiImg,mask#,click RoiImg = OriginalImg if event == cv2.EVENT_LBUTTONDOWN: # 마우스 누를때 # click = True x1,y1 =x,y elif event == cv2.EVENT_LBUTTONUP: # 마우스 땔때 # click =False x2,y2 =x,y cv2.rectangle(RoiImg,(x1,y1),(x2,y2),(0,0,0),-1) def CropRoi(): global RoiImg while True: cv2.imshow('img',OriginalImg) cv2.namedWindow('img') cv2.setMouseCallback('img',CallROIMouse) if cv2.waitKey(1)&0xFF == 27: print("roi 선택을 그만두셨습니다.") break elif cv2.waitKey(1)&0xFF == ord('s'): cv2.imwrite('AppliedROI.jpg',RoiImg) print("roi 선택 완료") break elif cv2.waitKey(1)&0xFF == ord('r'): RoiImg = OriginalImg cv2.imshow('img',OriginalImg) print("roi 선택을 다시합니다.") def CallPointMouse(event ,x,y,flags,param): global x1,y1,x2,y2,click,SelectPointImg # SelectPointImg = oriSP if event == cv2.EVENT_LBUTTONDOWN: # 마우스 누를때 click = True cv2.circle(SelectPointImg,(x,y),7,(0,255,0),-1) elif event == cv2.EVENT_MOUSEMOVE: # 그냥 움직일때도 인식할수 있으므로 Click flag로 관리한다. if click: cv2.circle(SelectPointImg,(x,y),7,(0,255,0),-1) # break elif event == cv2.EVENT_LBUTTONUP: # 마우스 땔때 click =False def Point(): while True: cv2.imshow('simg',oriSP) cv2.namedWindow('simg') cv2.setMouseCallback('simg',CallPointMouse) cv2.imshow('result',SelectPointImg) # elif k ==ord('f'): if cv2.waitKey(1) & 0xFF == ord('s'): print("납땜 활성화 포인트 저장완료") break cv2.imwrite('SelectPoint.jpg',SelectPointImg) def Cvt(holeImg,selectedholeImg): mask = cv2.imread("SelectPoint.jpg",cv2.IMREAD_GRAYSCALE) img = cv2.imread("Hole(Checking).jpg",cv2.IMREAD_GRAYSCALE) ret, mask = cv2.threshold(mask ,10, 255, cv2.THRESH_BINARY) result=cv2.bitwise_and(img,mask,mask =mask) cv2.imwrite('result.jpg',result) cv2.imshow('re',result) cv2.waitKey(0) CropRoi() oriSP = cv2.imread("AppliedROI.jpg") Point() Cvt(oriSP,SelectPointImg)
[ "lobgd9150@gmail.com" ]
lobgd9150@gmail.com
2a75e8b776adf77118adf0d54f42f84b2551c522
de24f83a5e3768a2638ebcf13cbe717e75740168
/moodledata/vpl_data/303/usersdata/303/113604/submittedfiles/testes.py
b38cb9db11ad8f8582188be5061ca9df68f86486
[]
no_license
rafaelperazzo/programacao-web
95643423a35c44613b0f64bed05bd34780fe2436
170dd5440afb9ee68a973f3de13a99aa4c735d79
refs/heads/master
2021-01-12T14:06:25.773146
2017-12-22T16:05:45
2017-12-22T16:05:45
69,566,344
0
0
null
null
null
null
UTF-8
Python
false
false
536
py
nome=str(input('DIGITE O NOME DO USUÁRIO:')) n=int(input('DIGITE A QUANTIDADE DE CARACTERES:')) senha=[] for i in range(0,n,1): senha.append(int(input('DIGITE UM NUMERO P SENHA:'))) cont=0 for i in range(0,n-1,1): if senha[i] == senha[i+1]: cont+=1 while cont != 0: print('SENHA INVÁLIDA') for i in range(0,n,1): senha.append(int(input('DIGITE UM NUMERO P SENHA:'))) cont=0 for i in range(0,n-1,1): if senha[i] == senha [i+1]: cont +=1 else: print('SENHA VALIDA')
[ "rafael.mota@ufca.edu.br" ]
rafael.mota@ufca.edu.br
b83e8a6ee60459e5d14a6c88488c71a87a39bf03
bb150497a05203a718fb3630941231be9e3b6a32
/models/PaddleHub/hub_all_func/test_hrnet18_imagenet.py
fe47da5a17a9ed230afe2c30b89ac3851267324b
[]
no_license
PaddlePaddle/PaddleTest
4fb3dec677f0f13f7f1003fd30df748bf0b5940d
bd3790ce72a2a26611b5eda3901651b5a809348f
refs/heads/develop
2023-09-06T04:23:39.181903
2023-09-04T11:17:50
2023-09-04T11:17:50
383,138,186
42
312
null
2023-09-13T11:13:35
2021-07-05T12:44:59
Python
UTF-8
Python
false
false
490
py
"""hrnet18_imagenet""" import os import paddle import paddlehub as hub if paddle.is_compiled_with_cuda(): paddle.set_device("gpu") use_gpu = True else: paddle.set_device("cpu") use_gpu = False def test_hrnet18_imagenet_predict(): """hrnet18_imagenet predict""" os.system("hub install hrnet18_imagenet") model = hub.Module(name="hrnet18_imagenet") result = model.predict(["doc_img.jpeg"]) print(result) os.system("hub uninstall hrnet18_imagenet")
[ "noreply@github.com" ]
PaddlePaddle.noreply@github.com
02c4dcd07823de17baa8b4d8aab9220976d3e480
338dbd8788b019ab88f3c525cddc792dae45036b
/bin/jupyter-trust
61083c1cbdc70c3a63711f834326a32daebbb528
[]
permissive
KshitizSharmaV/Quant_Platform_Python
9b8b8557f13a0dde2a17de0e3352de6fa9b67ce3
d784aa0604d8de5ba5ca0c3a171e3556c0cd6b39
refs/heads/master
2022-12-10T11:37:19.212916
2019-07-09T20:05:39
2019-07-09T20:05:39
196,073,658
1
2
BSD-3-Clause
2022-11-27T18:30:16
2019-07-09T19:48:26
Python
UTF-8
Python
false
false
284
#!/Users/kshitizsharma/Desktop/Ktz2/bin/python3 # -*- coding: utf-8 -*- import re import sys from nbformat.sign import TrustNotebookApp if __name__ == '__main__': sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0]) sys.exit(TrustNotebookApp.launch_instance())
[ "kshitizsharmav@gmail.com" ]
kshitizsharmav@gmail.com
67b29bf7daa0c0b0ce6c52fe5c85eb82b14b1151
bd72c02af0bbd8e3fc0d0b131e3fb9a2aaa93e75
/Math/reverse_integer.py
3530292157d2d2c928ffdf80db8d13c8f43c9475
[]
no_license
harvi7/Leetcode-Problems-Python
d3a5e8898aceb11abc4cae12e1da50061c1d352c
73adc00f6853e821592c68f5dddf0a823cce5d87
refs/heads/master
2023-05-11T09:03:03.181590
2023-04-29T22:03:41
2023-04-29T22:03:41
222,657,838
1
0
null
null
null
null
UTF-8
Python
false
false
261
py
class Solution: def reverse(self, x: int) -> int: res, remains = 0, abs(x) while remains: res, remains = res * 10 + remains % 10, remains // 10 if x < 0: res *= -1 return res if abs(res) < 0x7fffffff else 0
[ "iamharshvirani7@gmail.com" ]
iamharshvirani7@gmail.com
a2b0c359f4da196842f99948a3ee61a1f4d744ca
3fbd28e72606e5358328bfe4b99eb0349ca6a54f
/.history/a_lucky_number_20210606191954.py
b041fa21188bdd03b0ad2ed3d85af6f7cb3e4810
[]
no_license
Tarun1001/codeforces
f0a2ef618fbd45e3cdda3fa961e249248ca56fdb
576b505d4b8b8652a3f116f32d8d7cda4a6644a1
refs/heads/master
2023-05-13T04:50:01.780931
2021-06-07T21:35:26
2021-06-07T21:35:26
374,399,423
0
0
null
null
null
null
UTF-8
Python
false
false
132
py
n= int(input()) count= 0 while n!=0: if n%10==4 or n%10==7: count+=1 n=n/10 if count ==4 or count==7:
[ "tarunsivasai8@gmail.com" ]
tarunsivasai8@gmail.com
dad8cf8c89082d71ba12771c42b06974bbf8d0aa
509823ea14f04d5791486b56a592d7e7499d7d51
/parte18/demo50_dibujo.py
11b11c4fa76b7a6c4582464be00e4da3e8ffbbd7
[]
no_license
Fhernd/Python-CursoV2
7613144cbed0410501b68bedd289a4d7fbefe291
1ce30162d4335945227f7cbb875f99bc5f682b98
refs/heads/master
2023-08-08T05:09:44.167755
2023-08-05T19:59:38
2023-08-05T19:59:38
239,033,656
64
38
null
null
null
null
UTF-8
Python
false
false
1,643
py
from tkinter import Canvas, Tk class Dibujo(object): def __init__(self, master): self.master = master self.inicializar_gui() def inicializar_gui(self): self.canvas = Canvas(bg='white', height=300, width=300) self.canvas.pack() self.canvas.bind('<ButtonPress-1>', self.iniciar_dibujo) self.canvas.bind('<B1-Motion>', self.dibujar) self.canvas.bind('<Double-1>', self.limpiar) self.canvas.bind('<ButtonPress-3>', self.mover) self.tipos_figuras = [self.canvas.create_oval, self.canvas.create_rectangle] self.dibujo = None def iniciar_dibujo(self, evento): self.figura = self.tipos_figuras[0] self.tipos_figuras = self.tipos_figuras[1:] + self.tipos_figuras[:1] self.inicio = evento self.dibujo = None def dibujar(self, evento): canvas = evento.widget if self.dibujo: self.canvas.delete(self.dibujo) id_figura = self.figura(self.inicio.x, self.inicio.y, evento.x, evento.y) self.dibujo = id_figura def limpiar(self, evento): evento.widget.delete('all') def mover(self, evento): if self.dibujo: canvas = evento.widget diferencia_x = evento.x - self.inicio.x diferencia_y = evento.y - self.inicio.y canvas.move(self.dibujo, diferencia_x, diferencia_y) self.inicio = evento def main(): master = Tk() master.title('Dibujo') master.geometry('300x300') ventana = Dibujo(master) master.mainloop() if __name__ == "__main__": main()
[ "johnortizo@outlook.com" ]
johnortizo@outlook.com
758a78f2514e8832a8e26e6989826523e8f71918
8be5929368bd987caf744c92f234884bf49d3d42
/services/web/apps/main/messageroute/views.py
cff0d7e546d5ec40804fdad5750c0b3a05d585a6
[ "BSD-3-Clause" ]
permissive
oleg-soroka-lt/noc
9b670d67495f414d78c7080ad75f013ab1bf4dfb
c39422743f52bface39b54d5d915dcd621f83856
refs/heads/master
2023-08-21T03:06:32.235570
2021-10-20T10:22:02
2021-10-20T10:22:02
null
0
0
null
null
null
null
UTF-8
Python
false
false
716
py
# ---------------------------------------------------------------------- # main.messageroute application # ---------------------------------------------------------------------- # Copyright (C) 2007-2020 The NOC Project # See LICENSE for details # ---------------------------------------------------------------------- # NOC modules from noc.lib.app.extdocapplication import ExtDocApplication from noc.main.models.messageroute import MessageRoute from noc.core.translation import ugettext as _ class MessageRouteApplication(ExtDocApplication): """ MessageRoute application """ title = "Message Route" menu = [_("Setup"), _("Message Routes")] model = MessageRoute glyph = "arrows-alt"
[ "aversanta@gmail.com" ]
aversanta@gmail.com
8acebdf1f210641c6ca8b6e7b089a55c784932ea
7dc240e587213e4b420676c60aa1b24905b1b2e4
/src/diplomas/services/diploma_generator.py
12a3fca9d83d34bd91583ed496ca192eb36fe208
[ "MIT" ]
permissive
denokenya/education-backend
834d22280717f15f93407108846e2eea767421c8
3b43ba0cc54c6a2fc2f1716170393f943323a29b
refs/heads/master
2023-08-27T09:07:48.257108
2021-11-03T00:19:04
2021-11-03T00:19:04
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,932
py
import requests from dataclasses import dataclass from django.conf import settings from django.core.files.base import ContentFile from urllib.parse import urljoin from diplomas.models import Diploma, DiplomaTemplate from products.models import Course from studying.models import Study from users.models import User class WrongDiplomaServiceResponse(requests.exceptions.HTTPError): pass @dataclass class DiplomaGenerator: course: Course student: User language: str def __call__(self) -> Diploma: image = self.fetch_image() diploma = self.create_diploma() diploma.image.save(name='diploma.png', content=image) return diploma @property def study(self) -> Study: return Study.objects.get(student=self.student, course=self.course) @property def template(self) -> DiplomaTemplate: return DiplomaTemplate.objects.get( course=self.course, language=self.language, ) def create_diploma(self) -> Diploma: return Diploma.objects.get_or_create( study=self.study, language=self.language, )[0] def fetch_image(self) -> ContentFile: response = requests.get( url=self.get_external_service_url(), params=self.get_template_context(), headers={ 'Authorization': f'Bearer {settings.DIPLOMA_GENERATOR_TOKEN}', }, ) if response.status_code != 200: raise WrongDiplomaServiceResponse(f'Got {response.status_code} status code: {response.text}') return ContentFile(response.content) def get_external_service_url(self) -> str: return urljoin(settings.DIPLOMA_GENERATOR_HOST, f'/{self.template.slug}.png') def get_template_context(self) -> dict: return { 'name': str(self.student), 'sex': self.student.gender[:1], }
[ "noreply@github.com" ]
denokenya.noreply@github.com
84fa237b31973a55a76d7db0c5c59e4a408aa9d0
a40950330ea44c2721f35aeeab8f3a0a11846b68
/Django/Django.py
4224dc68380a1c0e32675dc55a56ce3ce59e7ead
[]
no_license
huang443765159/kai
7726bcad4e204629edb453aeabcc97242af7132b
0d66ae4da5a6973e24e1e512fd0df32335e710c5
refs/heads/master
2023-03-06T23:13:59.600011
2023-03-04T06:14:12
2023-03-04T06:14:12
233,500,005
3
1
null
null
null
null
UTF-8
Python
false
false
274
py
""" https://www.djangoproject.com/start/ 学习网址:例子什么都有 pip3 -m install django python3 -m django startproject 项目名称(非存在)会建立一个项目 python3 -m django help --commands 列出所有指令 python -m django <command> [options] """
[ "443765159@qq.com" ]
443765159@qq.com
0d4fa822d511761432ee7ba760c62f146b04cf69
a8b29cc5a2ecd8a1434fc8e1c9ad8f106b75f8dc
/setup.py
f39fb9091bfb84ac5fbee9e713450527b9672b67
[ "MIT" ]
permissive
ipalindromi/notion-py
7a2df43dd1eedb7279e6df16f0055f497ebb978e
573cf67a4ab7ce10558c6a666b7c77b5728de93c
refs/heads/master
2020-05-22T09:40:00.553506
2019-05-11T16:11:49
2019-05-11T16:11:49
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,000
py
import setuptools try: # for pip >= 10 from pip._internal.req import parse_requirements except ImportError: # for pip <= 9.0.3 from pip.req import parse_requirements with open("README.md", "r") as fh: long_description = fh.read() reqs = parse_requirements("requirements.txt", session=False) install_requires = [str(ir.req) for ir in reqs] setuptools.setup( name="notion", version="0.0.21", author="Jamie Alexandre", author_email="jamalex+python@gmail.com", description="Unofficial Python API client for Notion.so", long_description=long_description, long_description_content_type="text/markdown", url="https://github.com/jamalex/notion-py", install_requires=install_requires, include_package_data=True, packages=setuptools.find_packages(), python_requires='>=3.4', classifiers=[ "Programming Language :: Python :: 3", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", ], )
[ "jamalex@gmail.com" ]
jamalex@gmail.com
024fddd4f9e6fcd1ef11b8229f5dee8d71fe2ca0
27d982d2b1d7d70b6d2589a182b272c0afd15016
/zx_module/ppt_v12.py
b731b82131f6e2f9865f1a3552ae53914ce75b62
[]
no_license
zXpp/hw_easy_ppt_kits
d5c494f71a03e7ddc973154fb858cd296f11c38a
ec0014a4de380da1639fd5cafe7a0ca1c3213ed6
refs/heads/master
2021-06-27T04:31:39.694137
2017-09-19T10:41:27
2017-09-19T10:41:27
104,061,957
0
0
null
null
null
null
UTF-8
Python
false
false
8,698
py
# -*- coding: utf-8 -*- """ """ import os import win32com.client #sys.path= pyrealpath.append(os.path.split(os.path.realpath(__file__))[0]) #from win32com.client import Dispatch from rmdjr import rmdAndmkd as rmdir#import timeremove and makedir from PIL.Image import open as imgopen,new as imgnew # OFFICE=["PowerPoint.Application","Word.Application","Excel.Application"] ppFixedFormatTypePDF = 2 class easyPPT(): def __init__(self): self.ppt = win32com.client.DispatchEx('PowerPoint.Application') self.ppt.DisplayAlerts=False self.ppt.Visiable=False self.filename,self.ppt_pref,self.outdir0="","","" self.outdir0,self.label,self.outdir1,self.ppt_prefix ="","","","" self.width,self.height,self.count_Slid=0,0,0 self.outfordir2,self.outfile_prefix,self.outslidir2,self.outresizedir2="","","","" def open(self,filename=None,outDir0=None,label=None): try: if filename and os.path.isfile(filename): self.filename = filename#给定文件名,chuangeilei self.ppt_prefix=os.path.basename(self.filename).rsplit('.')[0] self.outdir0=outDir0 if outDir0 else os.path.dirname(self.filename)#输出跟路径 self.outdir0=self.outdir0.replace('/','\\') self.label = label if label else self.ppt_prefix self.outdir1=os.path.join(self.outdir0,self.label)#输出跟文件夹路径+用户定义-同ppt文件名 self.pres = self.ppt.Presentations.Open(self.filename, WithWindow=False) except: self.pres = self.ppt.Presentations.Add() self.filename = '' else: self.Slides=self.pres.Slides self.count_Slid = self.Slides.Count self.width,self.height = [self.pres.PageSetup.SlideWidth*3,self.pres.PageSetup.SlideHeight*3] rmdir(self.outdir1) self.outfordir2=os.path.join(self.outdir1,"OutFormats")#输出放多格式的二级目录,默认为"OurFormats" rmdir(self.outfordir2) self.outfile_prefix=os.path.join(self.outfordir2,self.label)#具体到文件格式的文件前缀(除了生成格式外的) def closepres(self): self.pres.Close() def closeppt(self): self.ppt.Quit() def saveAs(self,Format=None,flag="f"): try: if flag=="f" and Format: newname=u".".join([self.outfile_prefix,Format.lower()])#目标格式的完整路径 if Format in ["PDF","pdf","Pdf"]: try: self.pres.SaveAs(FileName=newname,FileFormat=32) except: newname=newname.replace('/','\\') self.pres.SaveAs(FileName=newname, FileFormat=32) if Format in ["txt", "TXT", "Txt"]: self.exTXT() except: pass#return e def pngExport(self,imgDir=None,newsize=None,imgtype="png",merge=0):#导出原图用这个 newsize=newsize if newsize else self.width radio=newsize/self.width if self.outdir1: self.outslidir2=os.path.join(self.outdir1,"Slides")#存放原图的二级目录 if not imgDir: rmdir(self.outslidir2) Path,Wid,Het=self.outslidir2,self.width,self.height self.outfile_prefix=self.outfile_prefix+'_raw' #self.allslid=map(lambda x:os.path.join(Path,x),os.listdir(Path))#所有原图的绝对路径 else: self.imDir=imgDir self.outresizedir2=os.path.join(self.outdir1,self.imDir)#所以缩放图的绝对路径 rmdir(self.outresizedir2) Path,Wid,Het=self.outresizedir2,newsize,round(self.height*radio,0) #self.allres=map(lambda x:os.path.join(Path,x),os.listdir(Path)) self.pres.Export(Path,imgtype,Wid,Het)#可设参数导出幻灯片的宽度(以像素为单位) self.renameFiles(Path,torep=u"幻灯片") outfile=u"".join([self.outfile_prefix,u'.',imgtype]) redpi(Path,merge,pictype=imgtype,outimg=outfile) """ def redpi(path,append=0,pictype="png",outimg=None):##将大于、小于96dpi的都转换成96dpi files=map(lambda x:os.path.join(path,x),os.listdir(path)) imgs,width, height=[], 0,0 for file in files: img=Image.open(file) img2=img.copy() img.save(file) if append: img2 = img2.convert('RGB') if img2.mode != "RGB" else img2 imgs.append(img2) width = img2.size[0] if img2.size[0] > width else width height += img2.size[1] del img2 if append: pasteimg(imgs,width,height,outimg)""" def renameFiles(self,imgdir_name,torep=None):#torep:带替换的字符 srcfiles = os.listdir(imgdir_name) for srcfile in srcfiles: inde = srcfile.split(torep)[-1].split('.')[0]#haha1.png suffix=srcfile[srcfile.index(inde)+len(inde):].lower() #sufix = os.path.splitext(srcfile)[1] # 根据目录下具体的文件数修改%号后的值,"%04d"最多支持9999 newname="".join([self.label,"_",inde.zfill(2),suffix]) destfile = os.path.join(imgdir_name,newname) srcfile = os.path.join(imgdir_name, srcfile) os.rename(srcfile, destfile) #index += 1 # for each in os.listdir(imgdir_name): def slid2PPT(self,outDir=None,substr=""):#选择的编号的幻灯片单独发布为ppt文件, try: if not outDir: outDir=os.path.join(self.outdir1 ,"Slide2PPT") if not os.path.isdir(outDir):#只需要判断文件夹是否存在,默认是覆盖生成。 os.makedirs(outDir) #if not sublst or not len(sublst):#如果不指定,列表为空或者是空列表 sublst=str2pptind(substr) sublst=filter(lambda x:x>0 and x<self.count_Slid+1,sublst)#筛选出小于幻灯片总数的序号 map(lambda x:self.Slides(x).PublishSlides(outDir,True,True),sublst) self.renameFiles(outDir,torep=self.ppt_prefix) except Exception,e: return e def exTXT(self): f=open("".join([self.outfile_prefix,r".txt"]),"wb+") for x in range(1,self.count_Slid+1):# s=[] shape_count = self.Slides(x).Shapes.Count page=u"".join([u"\r\n\r\nPage ",str(x),u":\r\n"])# s.append(page) for j in range(1, shape_count + 1): txornot=self.Slides(x).Shapes(j).HasTextFrame if txornot:#可正可负,只要不为0 txrg=self.Slides(x).Shapes(j).TextFrame.TextRange.Text if txrg and len(txrg):#not in [u' ',u'',u"\r\n"]: s.append(txrg) f.write(u"\r\n".join(s).encode("utf-8")) #print (u"\r\n".join(s)) f.close() #s=[] # else :#如果没有字的情况 # return def delslides(self): rmdir(self.outslidir2,mksd=0) def delresize(self): rmdir(self.outresizedir2,mksd=0) def str2pptind(strinput=""):##将输入处理范围的幻灯片编号转为顺序的、不重复的list列表 selppt=[] if strinput and strinput not in [""," "]: pptind=strinput.split(",") tmp1=map(lambda x:x.split(r"-"),pptind) for each in tmp1: each1=map(int,each) selppt+=range(each1[0],each1[-1]+1) selppt=set(sorted(selppt)) selppt=list(selppt) return selppt def pasteimg(inlst,width,height,output_file):#拼接图片 merge_img,cur_height = imgnew('RGB', (width, height), 0xffffff),0 for img in inlst: # 把图片粘贴上去 merge_img.paste(img, (0, cur_height)) cur_height += img.size[1] merge_img.save(output_file)#自动识别扩展名 merge_img=None def redpi(path,append=0,pictype="png",outimg=None):##将大于、小于96dpi的都转换成96dpi files=map(lambda x:os.path.join(path,x),os.listdir(path)) imgs,width, height=[], 0,0 for file in files: img=imgopen(file) # img=Image().im # img=imgt img2 = img.copy() if pictype not in ["gif","GIF"]: scale=img.info['dpi'] scale2=max(scale[0],96) img.save(file,dpi=(scale2,scale2)) else: img.save(file) img=None if append: img2 = img2.convert('RGB') if img2.mode != "RGB" else img2 imgs.append(img2) width = img2.size[0] if img2.size[0] > width else width height += img2.size[1] img2=None if append: pasteimg(imgs,width,height,outimg) if __name__ == "__main__": label=u"深度学习" imdir=u"反对果" outDir = u"C:\\Users\\Administrator\\Desktop" inpu=u"1,2,4,6-9,5,8-11,22-25" pprange=str2pptind(inpu) pptx=easyPPT() pptx.open(u"C:\\Users\\Administrator\\Desktop\\EVERYDAY ACTIVITIES_1_.pptx") #pptx.delslid() # print pptx.width,pptx.height,pptx.count_Slid,pptx.pres.PageSetup.SlideHeight # print pptx.pres.PageSetup.SlideWidth #pptind=pptx.str2pptind(inpu) #pptind2=pptx.str2pptind("") format=["png","html","xml","ppt/pptx","txt","pdf"]#formatpptx.saveAs(Format="PNG") # pptx.saveAs(Format=format[-2])#txt # pptx.saveAs(Format=format[-1])#导出pdf # pptx.pngExport()#留空为原尺寸导出 pptx.pngExport(u"啦啦 啦",900,imgtype="png")#imgedirnaem ,newidth. # pptx.slid2PPT() #pptx.slid2PPT(sublst=pptind) #pptx.weboptions() #print "dpi:",pptx.dpi_size[0],pptx.dpi_size[1] #pptx.ppt.PresentationBeforeClose(pptx.pres, False) #pptx.close()
[ "784723438@qq.com" ]
784723438@qq.com
c39fb94a63fdbd19eb8a17838ffe3e6bce300a65
6e7aa175667d08d8d285fd66d13239205aff44ff
/apps/gcc_media/rest.py
55a8f9eee75081aca883da6cf57845c16161ed9c
[]
no_license
jaredly/GameCC
c2a9d7b14fc45813a27bdde86e16a3e3594396e2
babadbe9348c502d0f433fb82e72ceff475c3a3b
refs/heads/master
2016-08-05T10:53:03.794386
2010-06-25T03:13:02
2010-06-25T03:13:02
269,735
1
0
null
null
null
null
UTF-8
Python
false
false
717
py
#!/usr/bin/env python from django.conf.urls.defaults import * from django.conf import settings from models import Image, Font, Sound from restive import Service service = Service() @service.add(name='list') def list_all(request): return {'_models': list(request.user.gcc_images.all().order_by('pk')) + list(request.user.gcc_fonts.all().order_by('pk')) + list(request.user.gcc_sounds.all()), 'media_url':settings.MEDIA_URL} @service.add(name='remove') def remove_(request, type, pk): if type == 'image': Image.objects.get(pk=pk).delete() return {} else: raise Exception('Unsupported type') urlpatterns = service.urls() # vim: et sw=4 sts=4
[ "jared@jaredforsyth.com" ]
jared@jaredforsyth.com
a2dc60b59d5b4e13c8f38e8012d5ca22b4fc4b68
77bde91c91d6ab173829a25fc3c3e0e80eb2c897
/tests/et_md3/verletlist/verletlist_cpp/test_verletlist_cpp.py
10fcb1daf1c7b54dff5d2305a0b2afbc0a7cbc69
[]
no_license
etijskens/et-MD3
ddddadbf4a8eb654277086f6f46bedb912bc1f01
9826ade15c546103d3fa1254c90f138b61e42fe7
refs/heads/main
2023-07-10T16:27:27.296806
2021-08-18T11:04:49
2021-08-18T11:04:49
395,253,565
0
0
null
null
null
null
UTF-8
Python
false
false
748
py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Tests for C++ module et_md3.verletlist.cpp. """ import sys sys.path.insert(0,'.') import numpy as np import et_md3.verletlist.verletlist_cpp #=============================================================================== # The code below is for debugging a particular test in eclipse/pydev. # (normally all tests are run with pytest) #=============================================================================== if __name__ == "__main__": the_test_you_want_to_debug = None print(f"__main__ running {the_test_you_want_to_debug} ...") the_test_you_want_to_debug() print('-*# finished #*-') #===============================================================================
[ "engelbert.tijskens@uantwerpen.be" ]
engelbert.tijskens@uantwerpen.be
ecc0109c2c95ce9605015f86bfb5113ad2e28148
1dc4a70ad29989efbcb7c670c21838e6e42a60f0
/dbaas/workflow/steps/build_database.py
2be1cc55cc349091e0e4202ea1dce43b7239eea6
[]
no_license
andrewsmedina/database-as-a-service
fb45ddb0f4bb0c5f35094f4b34cdb3aae63ad53d
bbe454631fad282c6e3acbed0d5bfddefd15d7ce
refs/heads/master
2020-12-13T21:46:30.221961
2014-10-29T17:14:54
2014-10-29T17:14:54
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,110
py
# -*- coding: utf-8 -*- import logging from base import BaseStep from logical.models import Database import datetime from ..exceptions.error_codes import DBAAS_0003 from util import full_stack LOG = logging.getLogger(__name__) class BuildDatabase(BaseStep): def __unicode__(self): return "Creating logical database..." def do(self, workflow_dict): try: if not workflow_dict['team'] or not workflow_dict['description'] or not workflow_dict['databaseinfra']: return False LOG.info("Creating Database...") database = Database.provision(name=workflow_dict['name'], databaseinfra=workflow_dict['databaseinfra']) LOG.info("Database %s created!" % database) workflow_dict['database'] = database LOG.info("Updating database team") database.team = workflow_dict['team'] if 'project' in workflow_dict: LOG.info("Updating database project") database.project = workflow_dict['project'] LOG.info("Updating database description") database.description = workflow_dict['description'] database.save() return True except Exception, e: traceback = full_stack() workflow_dict['exceptions']['error_codes'].append(DBAAS_0003) workflow_dict['exceptions']['traceback'].append(traceback) return False def undo(self, workflow_dict): try: if not 'database' in workflow_dict: if 'databaseinfra' in workflow_dict: LOG.info("Loading database into workflow_dict...") workflow_dict['database'] = Database.objects.filter(databaseinfra=workflow_dict['databaseinfra'])[0] else: return False if not workflow_dict['database'].is_in_quarantine: LOG.info("Putting Database in quarentine...") database = workflow_dict['database'] database.is_in_quarantine = True database.quarantine_dt = datetime.datetime.now().date() database.save() LOG.info("Destroying the database....") database.delete() return True except Exception, e: traceback = full_stack() workflow_dict['exceptions']['error_codes'].append(DBAAS_0003) workflow_dict['exceptions']['traceback'].append(traceback) return False
[ "raposo.felippe@gmail.com" ]
raposo.felippe@gmail.com