hexsha stringlengths 40 40 | size int64 5 2.06M | ext stringclasses 11 values | lang stringclasses 1 value | max_stars_repo_path stringlengths 3 251 | max_stars_repo_name stringlengths 4 130 | max_stars_repo_head_hexsha stringlengths 40 78 | max_stars_repo_licenses listlengths 1 10 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 3 251 | max_issues_repo_name stringlengths 4 130 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 10 | max_issues_count int64 1 116k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 251 | max_forks_repo_name stringlengths 4 130 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 10 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 1 1.05M | avg_line_length float64 1 1.02M | max_line_length int64 3 1.04M | alphanum_fraction float64 0 1 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
622058c389457c7cd876a630d6f12b0ece1a7dc1 | 1,342 | py | Python | pelicanconf.py | ChrisAD/attack-website | 222c03f17ea13375753b7323cc7327430974890b | [
"Apache-2.0"
] | 9 | 2020-05-05T22:23:53.000Z | 2021-10-15T18:13:17.000Z | pelicanconf.py | ChrisAD/attack-website | 222c03f17ea13375753b7323cc7327430974890b | [
"Apache-2.0"
] | null | null | null | pelicanconf.py | ChrisAD/attack-website | 222c03f17ea13375753b7323cc7327430974890b | [
"Apache-2.0"
] | 2 | 2020-05-19T05:38:02.000Z | 2021-01-27T12:12:34.000Z | #!/usr/bin/env python
# -*- coding: utf-8 -*- #
from __future__ import unicode_literals
import json
import uuid
import sys
# import plugins
PLUGIN_PATHS = ['plugins']
PLUGINS = ['assets']
AUTHOR = 'MITRE'
SITENAME = 'ATT&CK'
SITEURL = ''
PATH = 'content'
TIMEZONE = 'America/New_York'
DEFAULT_LANG = 'en'
THEME = 'attack-theme'
# Feed generation is usually not desired when developing
FEED_ALL_ATOM = None
CATEGORY_FEED_ATOM = None
TRANSLATION_FEED_ATOM = None
AUTHOR_FEED_ATOM = None
AUTHOR_FEED_RSS = None
DEFAULT_PAGINATION = False
STATIC_PATHS = ['docs']
ARTICLE_PATHS = ['pages/updates']
# Uncomment following line if you want document-relative URLs when developing
RELATIVE_URLS = False
# custom jinja filters
# remove index.html from end of a path, add / if not at beginning
# get a flattened tree of the "paths" of all children of a tree of objects.
# used in sidenav
JINJA_FILTERS = {
'from_json':json.loads,
'flatten_tree': flatten_tree,
'clean_path': clean_path
} | 23.137931 | 77 | 0.698957 |
62219b03355dbbadf9063de4f0e77f3db6e7d6b9 | 1,810 | py | Python | playbooks/roles/configure-vlan-for-ucsm-baremetal/configure_vlan_on_ucsm_bm.py | CiscoSystems/project-config-third-party | 4f9ca3048d8701db673eaf13714f2b7f529a1831 | [
"Apache-2.0"
] | 2 | 2017-09-19T15:52:22.000Z | 2017-10-30T11:19:05.000Z | playbooks/roles/configure-vlan-for-ucsm-baremetal/configure_vlan_on_ucsm_bm.py | CiscoSystems/project-config-third-party | 4f9ca3048d8701db673eaf13714f2b7f529a1831 | [
"Apache-2.0"
] | 24 | 2017-10-31T11:36:04.000Z | 2018-11-30T17:19:50.000Z | playbooks/roles/configure-vlan-for-ucsm-baremetal/configure_vlan_on_ucsm_bm.py | CiscoSystems/project-config-third-party | 4f9ca3048d8701db673eaf13714f2b7f529a1831 | [
"Apache-2.0"
] | 4 | 2017-09-18T16:02:34.000Z | 2018-05-24T14:58:16.000Z | import argparse
from ucsmsdk.ucshandle import UcsHandle
from ucsmsdk.mometa.vnic.VnicEtherIf import VnicEtherIf
from ucsmsdk.mometa.fabric.FabricVlan import FabricVlan
parser = argparse.ArgumentParser()
parser.add_argument('ucsm_ip')
parser.add_argument('username')
parser.add_argument('password')
parser.add_argument('sp_name')
parser.add_argument('vlan')
parser.add_argument('--remove', action='store_true',
help=("Remove the service profile with name"))
if __name__ == '__main__':
args = parser.parse_args()
handle = connect_to_ucsm(args)
assign_vlan_to_sp_vnic(handle, args)
| 33.518519 | 77 | 0.674033 |
6221a46e082c35a5b882386742c5234fe505e8f6 | 9,529 | py | Python | test/propagation_warn_only_test.py | lechat/jenkinsflow | 87396069dda4f0681829e5d4e264e4f09ae34131 | [
"BSD-3-Clause"
] | null | null | null | test/propagation_warn_only_test.py | lechat/jenkinsflow | 87396069dda4f0681829e5d4e264e4f09ae34131 | [
"BSD-3-Clause"
] | null | null | null | test/propagation_warn_only_test.py | lechat/jenkinsflow | 87396069dda4f0681829e5d4e264e4f09ae34131 | [
"BSD-3-Clause"
] | null | null | null | # Copyright (c) 2012 - 2015 Lars Hupfeldt Nielsen, Hupfeldt IT
# All rights reserved. This work is under a BSD license, see LICENSE.TXT.
from pytest import raises
from jenkinsflow.flow import serial, parallel, FailedChildJobException, FailedChildJobsException, Propagation, BuildResult
from .framework import api_select
from .framework.utils import pre_existing_fake_cli
| 50.68617 | 149 | 0.683702 |
6221e9086b65f59966870eca97102d109aabb9a1 | 3,458 | py | Python | RestPy/ixnetwork_restpy/testplatform/sessions/ixnetwork/vport/interface/dhcpv4discoveredinfo/dhcpv4discoveredinfo.py | ralfjon/IxNetwork | c0c834fbc465af69c12fd6b7cee4628baba7fff1 | [
"MIT"
] | null | null | null | RestPy/ixnetwork_restpy/testplatform/sessions/ixnetwork/vport/interface/dhcpv4discoveredinfo/dhcpv4discoveredinfo.py | ralfjon/IxNetwork | c0c834fbc465af69c12fd6b7cee4628baba7fff1 | [
"MIT"
] | null | null | null | RestPy/ixnetwork_restpy/testplatform/sessions/ixnetwork/vport/interface/dhcpv4discoveredinfo/dhcpv4discoveredinfo.py | ralfjon/IxNetwork | c0c834fbc465af69c12fd6b7cee4628baba7fff1 | [
"MIT"
] | null | null | null |
# Copyright 1997 - 2018 by IXIA Keysight
#
# 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 ixnetwork_restpy.base import Base
from ixnetwork_restpy.files import Files
| 34.58 | 217 | 0.738577 |
62232ec4709e08c7148a5e26f3dac3505151c613 | 17,678 | py | Python | ThreeBotPackages/radicaleserver/radicale/config.py | jimbertools/jumpscaleX_threebot | 9909aa270a1f5d04350c440ad787d755b905c456 | [
"Apache-2.0"
] | null | null | null | ThreeBotPackages/radicaleserver/radicale/config.py | jimbertools/jumpscaleX_threebot | 9909aa270a1f5d04350c440ad787d755b905c456 | [
"Apache-2.0"
] | null | null | null | ThreeBotPackages/radicaleserver/radicale/config.py | jimbertools/jumpscaleX_threebot | 9909aa270a1f5d04350c440ad787d755b905c456 | [
"Apache-2.0"
] | null | null | null | # This file is part of Radicale Server - Calendar Server
# Copyright 2008-2017 Guillaume Ayoub
# Copyright 2008 Nicolas Kandel
# Copyright 2008 Pascal Halter
# Copyright 2017-2019 Unrud <unrud@outlook.com>
#
# This library is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This library 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 General Public License for more details.
#
"""
Radicale configuration module.
Give a configparser-like interface to read and write configuration.
"""
import math
import os
from collections import OrderedDict
from configparser import RawConfigParser
from radicale import auth, rights, storage, web
from radicale.log import logger
from Jumpscale import j
DEFAULT_CONFIG_PATH = os.pathsep.join(["?/etc/radicale/config", "?~/.config/radicale/config"])
# Default configuration
DEFAULT_CONFIG_SCHEMA = OrderedDict(
[
(
"server",
OrderedDict(
[
(
"hosts",
{
"value": "127.0.0.1:5232",
"help": "set server hostnames including ports",
"aliases": ["-H", "--hosts"],
"type": list_of_ip_address,
},
),
(
"max_connections",
{"value": "8", "help": "maximum number of parallel connections", "type": positive_int},
),
(
"max_content_length",
{"value": "100000000", "help": "maximum size of request body in bytes", "type": positive_int},
),
("timeout", {"value": "30", "help": "socket timeout", "type": positive_int}),
(
"ssl",
{
"value": "False",
"help": "use SSL connection",
"aliases": ["-s", "--ssl"],
"opposite": ["-S", "--no-ssl"],
"type": bool,
},
),
(
"certificate",
{
"value": "/sandbox/cfg/ssl/radicale.cert.pem",
"help": "set certificate file",
"aliases": ["-c", "--certificate"],
"type": filepath,
},
),
(
"key",
{
"value": "/sandbox/cfg/ssl/radicale.key.pem",
"help": "set private key file",
"aliases": ["-k", "--key"],
"type": filepath,
},
),
(
"certificate_authority",
{
"value": "",
"help": "set CA certificate for validating clients",
"aliases": ["--certificate-authority"],
"type": filepath,
},
),
("protocol", {"value": "PROTOCOL_TLSv1_2", "help": "SSL protocol used", "type": str}),
("ciphers", {"value": "", "help": "available ciphers", "type": str}),
(
"dns_lookup",
{"value": "True", "help": "use reverse DNS to resolve client address in logs", "type": bool},
),
]
),
),
(
"encoding",
OrderedDict(
[
("request", {"value": "utf-8", "help": "encoding for responding requests", "type": str}),
("stock", {"value": "utf-8", "help": "encoding for storing local collections", "type": str}),
]
),
),
(
"auth",
OrderedDict(
[
(
"type",
{
"value": "none",
"help": "authentication method",
"type": str,
"internal": auth.INTERNAL_TYPES,
},
),
(
"htpasswd_filename",
{"value": "/etc/radicale/users", "help": "htpasswd filename", "type": filepath},
),
("htpasswd_encryption", {"value": "bcrypt", "help": "htpasswd encryption method", "type": str}),
(
"realm",
{
"value": "Radicale - Password Required",
"help": "message displayed when a password is needed",
"type": str,
},
),
("delay", {"value": "1", "help": "incorrect authentication delay", "type": positive_float}),
]
),
),
(
"rights",
OrderedDict(
[
(
"type",
{
"value": "owner_only",
"help": "rights backend",
"type": str,
"internal": rights.INTERNAL_TYPES,
},
),
(
"file",
{
"value": "/etc/radicale/rights",
"help": "file for rights management from_file",
"type": filepath,
},
),
]
),
),
(
"storage",
OrderedDict(
[
(
"type",
{
"value": "multifilesystem",
"help": "storage backend",
"type": str,
"internal": storage.INTERNAL_TYPES,
},
),
(
"filesystem_folder",
{
"value": "/var/lib/radicale/collections",
"help": "path where collections are stored",
"type": filepath,
},
),
(
"max_sync_token_age",
{
"value": "2592000", # 30 days
"help": "delete sync token that are older",
"type": positive_int,
},
),
("hook", {"value": "", "help": "command that is run after changes to storage", "type": str}),
]
),
),
(
"web",
OrderedDict(
[
(
"type",
{
"value": "internal",
"help": "web interface backend",
"type": str,
"internal": web.INTERNAL_TYPES,
},
)
]
),
),
(
"logging",
OrderedDict(
[
("level", {"value": "warning", "help": "threshold for the logger", "type": logging_level}),
("mask_passwords", {"value": "True", "help": "mask passwords in logs", "type": bool}),
]
),
),
("headers", OrderedDict([("_allow_extra", True)])),
(
"internal",
OrderedDict(
[
("_internal", True),
(
"filesystem_fsync",
{"value": "True", "help": "sync all changes to filesystem during requests", "type": bool},
),
("internal_server", {"value": "False", "help": "the internal server is used", "type": bool}),
]
),
),
]
)
def parse_compound_paths(*compound_paths):
"""Parse a compound path and return the individual paths.
Paths in a compound path are joined by ``os.pathsep``. If a path starts
with ``?`` the return value ``IGNORE_IF_MISSING`` is set.
When multiple ``compound_paths`` are passed, the last argument that is
not ``None`` is used.
Returns a dict of the format ``[(PATH, IGNORE_IF_MISSING), ...]``
"""
compound_path = ""
for p in compound_paths:
if p is not None:
compound_path = p
paths = []
for path in compound_path.split(os.pathsep):
ignore_if_missing = path.startswith("?")
if ignore_if_missing:
path = path[1:]
path = filepath(path)
if path:
paths.append((path, ignore_if_missing))
return paths
def load(paths=()):
"""Load configuration from files.
``paths`` a list of the format ``[(PATH, IGNORE_IF_MISSING), ...]``.
"""
configuration = Configuration(DEFAULT_CONFIG_SCHEMA)
for path, ignore_if_missing in paths:
parser = RawConfigParser()
config_source = "config file %r" % path
try:
if not parser.read(path):
config = Configuration.SOURCE_MISSING
if not ignore_if_missing:
raise j.exceptions.Base("No such file: %r" % path)
else:
config = {s: {o: parser[s][o] for o in parser.options(s)} for s in parser.sections()}
except Exception as e:
raise j.exceptions.Base("Failed to load %s: %s" % (config_source, e)) from e
configuration.update(config, config_source, internal=False)
return configuration
| 37.060797 | 119 | 0.461195 |
6224e1d3f02d7b9dda37a271e14789ceeccd2dd5 | 574 | py | Python | code_hashers/attendant.py | ksajan/iis-ms-del | 6339f639d674fedb88454b43dcd64493be2a4558 | [
"MIT"
] | 2 | 2019-12-24T13:32:22.000Z | 2019-12-26T11:26:08.000Z | code_hashers/attendant.py | ksajan/iis-ms-del | 6339f639d674fedb88454b43dcd64493be2a4558 | [
"MIT"
] | 1 | 2019-12-26T07:53:34.000Z | 2019-12-26T07:53:34.000Z | code_hashers/attendant.py | ksajan/iis-ms-del | 6339f639d674fedb88454b43dcd64493be2a4558 | [
"MIT"
] | 35 | 2019-12-22T05:05:43.000Z | 2019-12-22T07:16:56.000Z |
# def getDetails():
| 24.956522 | 76 | 0.651568 |
622711071eb4006f1628d4e6d3019ab6f40c0b83 | 1,773 | py | Python | projects/nano_det/net/header.py | yunshangyue71/mycodes | 54b876004c32d38d9c0363fd292d745fee8dff3c | [
"Apache-2.0"
] | null | null | null | projects/nano_det/net/header.py | yunshangyue71/mycodes | 54b876004c32d38d9c0363fd292d745fee8dff3c | [
"Apache-2.0"
] | null | null | null | projects/nano_det/net/header.py | yunshangyue71/mycodes | 54b876004c32d38d9c0363fd292d745fee8dff3c | [
"Apache-2.0"
] | null | null | null | import torch
from torch import nn
from net.init_net import xavier_init
from net.basic_cnn import DWConvBnReluPool
"""
DW-DW-PW
"""
if __name__ == '__main__':
from torchsummary import summary
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
net = Head().to(device)
summary(net, (96, 320, 320))
# net = nanodet_PAN(cfg)
# import netron
# import os
#
# x = torch.rand(2,58,320,320)
# net(x)
# name = os.path.basename(__file__)
# name = name.split('.')[0]
# onnx_path = '/media/q/deep/me/model/pytorch_script_use/'+name+'.onnx'
# torch.onnx.export(net, x, onnx_path)
# netron.start(onnx_path)
| 30.050847 | 96 | 0.5815 |
622719ea6c5735ec54aa9dbdf7b5a6d8d0c52ce7 | 1,115 | py | Python | hard-gists/1191457/snippet.py | jjhenkel/dockerizeme | eaa4fe5366f6b9adf74399eab01c712cacaeb279 | [
"Apache-2.0"
] | 21 | 2019-07-08T08:26:45.000Z | 2022-01-24T23:53:25.000Z | hard-gists/1191457/snippet.py | jjhenkel/dockerizeme | eaa4fe5366f6b9adf74399eab01c712cacaeb279 | [
"Apache-2.0"
] | 5 | 2019-06-15T14:47:47.000Z | 2022-02-26T05:02:56.000Z | hard-gists/1191457/snippet.py | jjhenkel/dockerizeme | eaa4fe5366f6b9adf74399eab01c712cacaeb279 | [
"Apache-2.0"
] | 17 | 2019-05-16T03:50:34.000Z | 2021-01-14T14:35:12.000Z | #!/usr/bin/env python
import urllib
import sys
import json
from mwlib import parser
from mwlib.refine import compat
if __name__ == "__main__":
params = urllib.urlencode({
"format": "json",
"action": "query",
"prop": "revisions",
"rvprop": "content",
"titles": "ISO_3166-1",
"rvsection": "4",
})
wc = urllib.urlopen("http://en.wikipedia.org/w/api.php?%s" % params)
if wc.getcode() != 200:
print "Fail!"
sys.exit(2)
raw = wc.read()
rdata = json.loads(raw)
wc.close()
page = rdata['query']['pages'].itervalues().next()
if not page:
print "NO page found"
sys.exit(3)
revision = page['revisions'][0]
if not revision:
print "NO revision found"
sys.exit(4)
content = revision[str(revision.keys()[0])]
parsed = compat.parse_txt(content)
table = parsed.find(parser.Table)[0]
if not table:
print "Table not found"
sys.exit(5)
for row in table.children:
cells = row.find(parser.Cell)
print cells[0].asText().replace("}}", "").replace("{{", "").strip() + \
" || " + cells[1].asText().strip() + " || " + cells[2].asText().strip() \
+ " || " + cells[3].asText().strip()
| 22.755102 | 75 | 0.625112 |
6228f1664df5b9ec6866831755970b61d71b6d58 | 3,058 | py | Python | ECC_main/platform/slack.py | dongh9508/ECC-main | 904110b70ba3e459d92c6d21a5ad1693b4ee726a | [
"MIT"
] | 2 | 2019-01-23T00:04:18.000Z | 2019-02-01T10:09:15.000Z | ECC_main/platform/slack.py | dongh9508/ECC-main | 904110b70ba3e459d92c6d21a5ad1693b4ee726a | [
"MIT"
] | 26 | 2018-07-11T07:59:46.000Z | 2021-02-08T20:21:46.000Z | ECC_main/platform/slack.py | dongh9508/ECC-main | 904110b70ba3e459d92c6d21a5ad1693b4ee726a | [
"MIT"
] | 2 | 2018-08-31T14:08:19.000Z | 2018-08-31T15:14:29.000Z | from .platformBase import PlatformBase
from django.http import HttpResponse, JsonResponse
from ECC_main.baseRequest import BaseRequest
import ECC_main.settings
import threading
import requests | 35.149425 | 95 | 0.624591 |
62291b009a583ae54f27aedb9899f9e284646d88 | 598 | py | Python | Classes/ex17.py | oDallas/PythomBR | 7d3b3bcefe05ce483f6aa664bbc4962a1e0fd285 | [
"MIT"
] | 1 | 2019-06-02T18:59:18.000Z | 2019-06-02T18:59:18.000Z | Classes/ex17.py | oDallas/PythonBR | 7d3b3bcefe05ce483f6aa664bbc4962a1e0fd285 | [
"MIT"
] | null | null | null | Classes/ex17.py | oDallas/PythonBR | 7d3b3bcefe05ce483f6aa664bbc4962a1e0fd285 | [
"MIT"
] | null | null | null | """"
Crie uma Fazenda de Bichinhos instanciando vrios objetos bichinho e mantendo o controle deles atravs de uma lista.
Imite o funcionamento do programa bsico, mas ao invs de exigis que o usurio tome conta de um nico bichinho,
exija que ele tome conta da fazenda inteira. Cada opo do menu deveria permitir que o usurio executasse
uma ao para todos os bichinhos (alimentar todos os bichinhos, brincar com todos os bichinhos, ou ouvir a todos os
bichinhos). Para tornar o programa mais interessante, d para cada bichinho um nivel inicial aleatrio de fome e tdio.
"""
# todo: terminar
| 59.8 | 119 | 0.797659 |
6229642233706b071d8517f87c02f6fac096a7c6 | 10,468 | py | Python | train.py | Thanh-Hoo/Custom_train_PanNet | aa50df0e32991d35112f3de6627baea963f0827a | [
"MIT"
] | null | null | null | train.py | Thanh-Hoo/Custom_train_PanNet | aa50df0e32991d35112f3de6627baea963f0827a | [
"MIT"
] | null | null | null | train.py | Thanh-Hoo/Custom_train_PanNet | aa50df0e32991d35112f3de6627baea963f0827a | [
"MIT"
] | null | null | null | '''
THis is the main training code.
'''
import os
os.environ["CUDA_VISIBLE_DEVICES"] = "0" # set GPU id at the very begining
import argparse
import random
import math
import numpy as np
import torch
import torch.nn.parallel
import torch.optim as optim
import torch.utils.data
import torch.nn.functional as F
from torch.multiprocessing import freeze_support
import json
import sys
import time
import pdb
# internal package
from dataset import ctw1500, totaltext, synthtext, msra, ic15, custom
from models.pan import PAN
from loss.loss import loss
from utils.helper import adjust_learning_rate, upsample
from utils.average_meter import AverageMeter
torch.set_num_threads(2)
# main function:
if __name__ == '__main__':
freeze_support()
parser = argparse.ArgumentParser()
parser.add_argument(
'--batch', type=int, default=16, help='input batch size')
parser.add_argument(
'--worker', type=int, default=4, help='number of data loading workers')
parser.add_argument(
'--epoch', type=int, default=601, help='number of epochs')
parser.add_argument('--output', type=str, default='outputs', help='output folder name')
parser.add_argument('--model', type=str, default='', help='model path')
parser.add_argument('--dataset_type', type=str, default='ctw', help="dataset type - ctw | tt | synthtext | msra | ic15 | custom")
parser.add_argument('--gpu', type=bool, default=False, help="GPU being used or not")
opt = parser.parse_args()
print(opt)
opt.manualSeed = random.randint(1, 10000) # fix seed
print("Random Seed:", opt.manualSeed)
random.seed(opt.manualSeed)
torch.manual_seed(opt.manualSeed)
torch.cuda.manual_seed(opt.manualSeed)
np.random.seed(opt.manualSeed)
# turn on GPU for models:
if opt.gpu == False:
device = torch.device("cpu")
print("CPU being used!")
else:
if torch.cuda.is_available() == True and opt.gpu == True:
device = torch.device("cuda")
print("GPU being used!")
else:
device = torch.device("cpu")
print("CPU being used!")
# set training parameters
batch_size = opt.batch
neck_channel = (64, 128, 256, 512)
pa_in_channels = 512
hidden_dim = 128
num_classes = 6
loss_text_weight = 1.0
loss_kernel_weight = 0.5
loss_emb_weight = 0.25
opt.optimizer = 'Adam'
opt.lr = 1e-3
opt.schedule = 'polylr'
epochs = opt.epoch
worker = opt.worker
dataset_type = opt.dataset_type
output_path = opt.output
trained_model_path = opt.model
# create dataset
print("Create dataset......")
if dataset_type == 'ctw': # ctw dataset
train_dataset = ctw1500.PAN_CTW(split='train',
is_transform=True,
img_size=640,
short_size=640,
kernel_scale=0.7,
report_speed=False)
elif dataset_type == 'tt': # totaltext dataset
train_dataset = totaltext.PAN_TT(split='train',
is_transform=True,
img_size=640,
short_size=640,
kernel_scale=0.7,
with_rec=False,
report_speed=False)
elif dataset_type == 'synthtext': # synthtext dataset
train_dataset = synthtext.PAN_Synth(is_transform=True,
img_size=640,
short_size=640,
kernel_scale=0.5,
with_rec=False)
elif dataset_type == 'msra': # msra dataset
train_dataset = msra.PAN_MSRA(split='train',
is_transform=True,
img_size=736,
short_size=736,
kernel_scale=0.7,
report_speed=False)
elif dataset_type == 'ic15': # msra dataset
train_dataset = ic15.PAN_IC15(split='train',
is_transform=True,
img_size=736,
short_size=736,
kernel_scale=0.5,
with_rec=False)
elif dataset_type == 'custom': # msra dataset
train_dataset = custom.PAN_CTW(split='train',
is_transform=True,
img_size=640,
short_size=640,
kernel_scale=0.7,
report_speed=False)
else:
print("Not supported yet!")
exit(1)
# make dataloader
train_dataloader = torch.utils.data.DataLoader(
train_dataset,
batch_size=batch_size,
shuffle=True,
num_workers=int(worker),
drop_last=True,
pin_memory=True)
print("Length of train dataset is:", len(train_dataset))
# make model output folder
try:
os.makedirs(output_path)
except OSError:
pass
# create model
print("Create model......")
model = PAN(pretrained=False, neck_channel=neck_channel, pa_in_channels=pa_in_channels, hidden_dim=hidden_dim, num_classes=num_classes)
if trained_model_path != '':
if torch.cuda.is_available() == True and opt.gpu == True:
model.load_state_dict(torch.load(trained_model_path, map_location=lambda storage, loc: storage), strict=False)
model = torch.nn.DataParallel(model).to(device)
else:
model.load_state_dict(torch.load(trained_model_path, map_location=lambda storage, loc: storage), strict=False)
else:
if torch.cuda.is_available() == True and opt.gpu == True:
model = torch.nn.DataParallel(model).to(device)
else:
model = model.to(device)
if opt.optimizer == 'SGD':
optimizer = optim.SGD(model.parameters(), lr=opt.lr, momentum=0.99, weight_decay=5e-4)
elif opt.optimizer == 'Adam':
optimizer = optim.Adam(model.parameters(), lr=opt.lr)
else:
print("Error: Please specify correct optimizer!")
exit(1)
# train, evaluate, and save model
print("Training starts......")
start_epoch = 0
for epoch in range(start_epoch, epochs):
print('Epoch: [%d | %d]' % (epoch + 1, epochs))
model.train()
# meters
losses = AverageMeter()
losses_text = AverageMeter()
losses_kernels = AverageMeter()
losses_emb = AverageMeter()
losses_rec = AverageMeter()
ious_text = AverageMeter()
ious_kernel = AverageMeter()
for iter, data in enumerate(train_dataloader):
# adjust learning rate
adjust_learning_rate(optimizer, train_dataloader, epoch, iter, opt.schedule, opt.lr, epochs)
outputs = dict()
# forward for detection output
det_out = model(data['imgs'].to(device))
det_out = upsample(det_out, data['imgs'].size())
# retreive ground truth labels
gt_texts = data['gt_texts'].to(device)
gt_kernels = data['gt_kernels'].to(device)
training_masks = data['training_masks'].to(device)
gt_instances = data['gt_instances'].to(device)
gt_bboxes = data['gt_bboxes'].to(device)
# calculate total loss
det_loss = loss(det_out, gt_texts, gt_kernels, training_masks, gt_instances, gt_bboxes, loss_text_weight, loss_kernel_weight, loss_emb_weight)
outputs.update(det_loss)
# detection loss
loss_text = torch.mean(outputs['loss_text'])
losses_text.update(loss_text.item())
loss_kernels = torch.mean(outputs['loss_kernels'])
losses_kernels.update(loss_kernels.item())
loss_emb = torch.mean(outputs['loss_emb'])
losses_emb.update(loss_emb.item())
loss_total = loss_text + loss_kernels + loss_emb
iou_text = torch.mean(outputs['iou_text'])
ious_text.update(iou_text.item())
iou_kernel = torch.mean(outputs['iou_kernel'])
ious_kernel.update(iou_kernel.item())
losses.update(loss_total.item())
# backward
optimizer.zero_grad()
loss_total.backward()
optimizer.step()
# print log
#print("batch: {} / total batch: {}".format(iter+1, len(train_dataloader)))
if iter % 20 == 0:
output_log = '({batch}/{size}) LR: {lr:.6f} | ' \
'Loss: {loss:.3f} | ' \
'Loss (text/kernel/emb): {loss_text:.3f}/{loss_kernel:.3f}/{loss_emb:.3f} ' \
'| IoU (text/kernel): {iou_text:.3f}/{iou_kernel:.3f}'.format(
batch=iter + 1,
size=len(train_dataloader),
lr=optimizer.param_groups[0]['lr'],
loss_text=losses_text.avg,
loss_kernel=losses_kernels.avg,
loss_emb=losses_emb.avg,
loss=losses.avg,
iou_text=ious_text.avg,
iou_kernel=ious_kernel.avg,
)
print(output_log)
sys.stdout.flush()
with open(os.path.join(output_path,'statistics.txt'), 'a') as f:
f.write("{} {} {} {} {} {}\n".format(losses_text.avg, losses_kernels.avg, losses_emb.avg, losses.avg, ious_text.avg, ious_kernel.avg))
if epoch % 20 == 0:
print("Save model......")
if torch.cuda.is_available() == True and opt.gpu == True:
torch.save(model.module.state_dict(), '%s/model_epoch_%s.pth' % (output_path, str(epoch)))
else:
torch.save(model.state_dict(), '%s/model_epoch_%s.pth' % (output_path, str(epoch))) | 40.261538 | 154 | 0.545472 |
6229671a08873684c79e48db6345c98847757965 | 3,070 | py | Python | bioprocs/scripts/chipseq/pPeakToRegPotential.py | pwwang/biopipen | d53b78aa192fd56a5da457463b099b2aa833b284 | [
"MIT"
] | 2 | 2021-09-10T00:17:52.000Z | 2021-10-10T09:53:09.000Z | bioprocs/scripts/chipseq/pPeakToRegPotential.py | pwwang/biopipen | d53b78aa192fd56a5da457463b099b2aa833b284 | [
"MIT"
] | 1 | 2021-12-02T07:54:09.000Z | 2021-12-02T07:54:09.000Z | bioprocs/scripts/chipseq/pPeakToRegPotential.py | pwwang/biopipen | d53b78aa192fd56a5da457463b099b2aa833b284 | [
"MIT"
] | 2 | 2021-09-10T00:17:54.000Z | 2021-10-10T09:56:40.000Z | import math, gzip
peakfile = "{{peakfile}}"
genefile = "{{genefile}}"
arg_inst = {{args.signal | repr}}
arg_gf = "{{args.genefmt}}"
arg_pf = "{{args.peakfmt}}"
arg_wd = int({{args.window | repr}})
d0 = arg_wd / 2
assert (isinstance(arg_inst, bool))
assert (arg_gf in ['ucsc', 'bed', 'ucsc+gz', 'bed+gz'])
assert (arg_pf in ['peak', 'bed', 'peak+gz', 'bed+gz'])
open_gf = open_pf = open
if arg_gf.endswith ('+gz'):
arg_gf = arg_gf[:-3]
open_gf = gzip.open
if arg_pf.endswith ('+gz'):
arg_pf = arg_pf[:-3]
open_pf = gzip.open
# read genes
genes = {}
if arg_gf == 'bed':
with open_gf (genefile) as f:
for line in f:
line = line.strip()
if not line or line.startswith('track') or line.startswith('#'): continue
items = line.split("\t")
chr = items[0]
start = int(items[1])
end = int(items[2])
gene = items[3]
strand = '-' if len(items)>5 and items[5] == '-' else '+'
tss = start if strand == '+' else end
rstart = tss - d0
rend = tss + d0
genes[gene] = [chr, start, end, tss, rstart, rend]
else:
with open_gf (genefile) as f:
for line in f:
line = line.strip()
if not line or line.startswith('track') or line.startswith('#'): continue
items = line.split("\t")
chr = items[2]
start = int(items[4])
end = int(items[5])
gene = items[12]
strand = items[3]
tss = start if strand == '+' else end
rstart = tss - d0
rend = tss + d0
genes[gene] = [chr, start, end, tss, rstart, rend]
# read peaks
peaks = {}
if arg_pf == 'peak':
with open_pf (peakfile) as f:
for line in f:
line = line.strip()
if not line or line.startswith('track') or line.startswith('#'): coninue
items = line.split("\t")
chr = items[0]
start = int(items[1])
end = int(items[2])
signal = float(items[6])
if peaks.has_key(chr):
peaks[chr].append ([start, end, (start+end) / 2, signal])
else:
peaks[chr] = [[start, end, (start+end) / 2, signal]]
else:
with open_pf (peakfile) as f:
for line in f:
line = line.strip()
if not line or line.startswith('track') or line.startswith('#'): coninue
items = line.split("\t")
chr = items[0]
start = int(items[1])
end = int(items[2])
signal = float(items[4])
if peaks.has_key(chr):
peaks[chr].append ([start, end, (start+end) / 2, signal])
else:
peaks[chr] = [[start, end, (start+end) / 2, signal]]
for key, val in peaks.iteritems():
peaks[key] = sorted (val, cmp = lambda x, y: x[0] - y[0])
rp = {}
for gene, ginfo in genes.iteritems():
(gchr, gstart, gend, gtss, grstart, grend) = ginfo
rp[gene] = 0
if not peaks.has_key(gchr): continue
for pinfo in peaks[gchr]:
(pstart, pend, pcenter, psignal) = pinfo
if pcenter < grstart: continue
if pcenter > grend: break
score = psignal if arg_inst else 1
score *= math.exp (-(.5 + 4*abs(pcenter - tss)/d0))
rp[gene] += score
with open ("{{outfile}}", 'w') as f:
for key in sorted (rp, key=rp.get, reverse = True):
f.write ("%s\t%.3f\n" % (key, rp[key]))
| 29.238095 | 76 | 0.587948 |
622a87127bb1d17eed572fa385184b37ffbcf8bc | 1,549 | py | Python | parsifal/reviews/migrations/0014_auto_20150710_1445.py | michelav/parsifal | 6633699ad64fd354ddef27f8802a76b7ec7c4ef8 | [
"MIT"
] | 1 | 2020-11-12T08:36:41.000Z | 2020-11-12T08:36:41.000Z | parsifal/reviews/migrations/0014_auto_20150710_1445.py | michelav/parsifal | 6633699ad64fd354ddef27f8802a76b7ec7c4ef8 | [
"MIT"
] | 7 | 2019-11-06T12:44:12.000Z | 2022-01-13T01:48:22.000Z | parsifal/reviews/migrations/0014_auto_20150710_1445.py | michelav/parsifal | 6633699ad64fd354ddef27f8802a76b7ec7c4ef8 | [
"MIT"
] | 3 | 2019-10-05T04:16:59.000Z | 2021-04-20T05:00:50.000Z | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
| 37.780488 | 164 | 0.586185 |
622afea05f222949c88d139d2a220b387b5d925a | 58,968 | py | Python | lua_protobuf/generator.py | JoJo2nd/lua-protobuf | f3fc8d451d4b43152e28a9a1eaa98aa744dcd0f5 | [
"Apache-2.0"
] | null | null | null | lua_protobuf/generator.py | JoJo2nd/lua-protobuf | f3fc8d451d4b43152e28a9a1eaa98aa744dcd0f5 | [
"Apache-2.0"
] | null | null | null | lua_protobuf/generator.py | JoJo2nd/lua-protobuf | f3fc8d451d4b43152e28a9a1eaa98aa744dcd0f5 | [
"Apache-2.0"
] | null | null | null | # Copyright 2011 Gregory Szorc
#
# 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.
# Modified by James Moran 2014
# Updated to work with Lua 5.2. Fixing windows platform issues.
# Added wrapper classes for CodedInput/OutputStream(s)
from google.protobuf.descriptor import FieldDescriptor
import re
RE_BARE_BEGIN_BRACKET = re.compile(r'^\s*{\s*$')
RE_BEGIN_BRACKET = re.compile(r'{\s*$')
RE_END_BRACKET = re.compile(r'^\s*};?\s*$')
FIELD_LABEL_MAP = {
FieldDescriptor.LABEL_OPTIONAL: 'optional',
FieldDescriptor.LABEL_REQUIRED: 'required',
FieldDescriptor.LABEL_REPEATED: 'repeated'
}
FIELD_TYPE_MAP = {
FieldDescriptor.TYPE_DOUBLE: 'double',
FieldDescriptor.TYPE_FLOAT: 'float',
FieldDescriptor.TYPE_INT64: 'int64',
FieldDescriptor.TYPE_UINT64: 'uint64',
FieldDescriptor.TYPE_INT32: 'int32',
FieldDescriptor.TYPE_FIXED64: 'fixed64',
FieldDescriptor.TYPE_FIXED32: 'fixed32',
FieldDescriptor.TYPE_BOOL: 'bool',
FieldDescriptor.TYPE_STRING: 'string',
FieldDescriptor.TYPE_GROUP: 'group',
FieldDescriptor.TYPE_MESSAGE: 'message',
FieldDescriptor.TYPE_BYTES: 'bytes',
FieldDescriptor.TYPE_UINT32: 'uint32',
FieldDescriptor.TYPE_ENUM: 'enum',
FieldDescriptor.TYPE_SFIXED32: 'sfixed32',
FieldDescriptor.TYPE_SFIXED64: 'sfixed64',
FieldDescriptor.TYPE_SINT32: 'sint32',
FieldDescriptor.TYPE_SINT64: 'sint64',
}
def lua_protobuf_header():
'''Returns common header included by all produced files'''
return '''
#ifndef LUA_PROTOBUF_H
#define LUA_PROTOBUF_H
#include <google/protobuf/message.h>
#ifdef __cplusplus
extern "C" {
#endif
#include <lua.h>
#ifdef WINDOWS
#define LUA_PROTOBUF_EXPORT __declspec(dllexport)
#else
#define LUA_PROTOBUF_EXPORT
#endif
// type for callback function that is executed before Lua performs garbage
// collection on a message instance.
// if called function returns 1, Lua will free the memory backing the object
// if returns 0, Lua will not free the memory
typedef int (*lua_protobuf_gc_callback)(::google::protobuf::MessageLite *msg, void *userdata);
// __index and __newindex functions for enum tables
LUA_PROTOBUF_EXPORT int lua_protobuf_enum_index(lua_State *L);
LUA_PROTOBUF_EXPORT int lua_protobuf_enum_newindex(lua_State *L);
// GC callback function that always returns true
LUA_PROTOBUF_EXPORT int lua_protobuf_gc_always_free(::google::protobuf::MessageLite *msg, void *userdata);
// A minimal Lua interface for coded input/output protobuf streams
int lua_protobuf_coded_streams_open(lua_State* L);
#ifdef __cplusplus
}
#endif
#endif
'''
def lua_protobuf_source():
'''Returns source for common code'''
return '''
#include "lua-protobuf.h"
#ifdef __cplusplus
extern "C" {
#endif
#include <lauxlib.h>
#ifdef __cplusplus
}
#endif
int lua_protobuf_enum_index(lua_State *L)
{
return luaL_error(L, "attempting to access undefined enumeration value: %s", lua_tostring(L, 2));
}
int lua_protobuf_enum_newindex(lua_State *L)
{
return luaL_error(L, "cannot modify enumeration tables");
}
int lua_protobuf_gc_always_free(::google::protobuf::MessageLite *msg, void *ud)
{
return 1;
}
#include "google/protobuf/io/coded_stream.h"
#include "google/protobuf/io/zero_copy_stream_impl.h"
#include "google/protobuf/io/zero_copy_stream_impl_lite.h"
#include <fcntl.h>
#include <sys/stat.h>
#if defined (_MSC_VER)
# include <io.h> // for open
#else
# include <sys/types.h>
# define O_BINARY (0)
#endif
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
int lua_protobuf_coded_input_stream_new(lua_State* L) {
const char* filepath = luaL_checkstring(L, 1);
int fd = open(filepath, O_RDONLY | O_BINARY, S_IREAD);
if (fd == -1) {
return luaL_error(L, "Failed to open file %s", filepath);
}
char* udataptr = (char*)lua_newuserdata(L, sizeof(::google::protobuf::io::CodedInputStream)+sizeof(::google::protobuf::io::FileInputStream));
auto instream = new (udataptr+sizeof(::google::protobuf::io::FileInputStream)) ::google::protobuf::io::FileInputStream(fd);
instream->SetCloseOnDelete(true);
auto codestream = new (udataptr) ::google::protobuf::io::CodedInputStream(instream);
luaL_setmetatable(L, "protobuf_.CodedInputStream");
return 1;
}
int lua_protobuf_coded_input_stream_gc(lua_State* L) {
::google::protobuf::io::CodedInputStream* codestream = (::google::protobuf::io::CodedInputStream*)luaL_checkudata(L, 1, "protobuf_.CodedInputStream");
::google::protobuf::io::FileInputStream* filestream = (::google::protobuf::io::FileInputStream*)(codestream+1);
codestream->~CodedInputStream();
filestream->~FileInputStream();
return 0;
}
int lua_protobuf_coded_input_stream_skip(lua_State* L) {
::google::protobuf::io::CodedInputStream* codestream = (::google::protobuf::io::CodedInputStream*)luaL_checkudata(L, 1, "protobuf_.CodedInputStream");
int count = luaL_checkint(L, 2);
codestream->Skip(count);
return 0;
}
int lua_protobuf_coded_input_stream_push_limit(lua_State* L) {
::google::protobuf::io::CodedInputStream* codestream = (::google::protobuf::io::CodedInputStream*)luaL_checkudata(L, 1, "protobuf_.CodedInputStream");
int limit = luaL_checkint(L, 2);
limit = codestream->PushLimit(limit);
lua_pushinteger(L, limit);
return 1;
}
int lua_protobuf_coded_input_stream_pop_limit(lua_State* L) {
::google::protobuf::io::CodedInputStream* codestream = (::google::protobuf::io::CodedInputStream*)luaL_checkudata(L, 1, "protobuf_.CodedInputStream");
int limit = luaL_checkint(L, 2);
codestream->PopLimit(limit);
return 0;
}
int lua_protobuf_coded_input_stream_current_position(lua_State* L) {
::google::protobuf::io::CodedInputStream* codestream = (::google::protobuf::io::CodedInputStream*)luaL_checkudata(L, 1, "protobuf_.CodedInputStream");
lua_pushinteger(L, codestream->CurrentPosition());
return 1;
}
int lua_protobuf_coded_input_stream_read_raw(lua_State* L) {
::google::protobuf::io::CodedInputStream* codestream = (::google::protobuf::io::CodedInputStream*)luaL_checkudata(L, 1, "protobuf_.CodedInputStream");
int count = luaL_checkint(L, 2);
char* buf = new char[count];
bool success = codestream->ReadRaw(buf, count);
if (success) {
lua_pushlstring(L, buf, count);
} else {
lua_pushnil(L);
}
delete buf;
return 1;
}
int lua_protobuf_coded_input_stream_read_varint_32(lua_State* L) {
::google::protobuf::io::CodedInputStream* codestream = (::google::protobuf::io::CodedInputStream*)luaL_checkudata(L, 1, "protobuf_.CodedInputStream");
::google::protobuf::uint32 val;
bool success = codestream->ReadVarint32(&val);
lua_pushboolean(L, success);
if (success) {
lua_pushinteger(L, val);
} else {
lua_pushnil(L);
}
return 1;
}
int lua_protobuf_coded_input_stream_read_varint_64(lua_State* L) {
::google::protobuf::io::CodedInputStream* codestream = (::google::protobuf::io::CodedInputStream*)luaL_checkudata(L, 1, "protobuf_.CodedInputStream");
::google::protobuf::uint64 val;
bool success = codestream->ReadVarint64(&val);
lua_pushboolean(L, success);
if (success) {
lua_pushinteger(L, val);
} else {
lua_pushnil(L);
}
return 1;
}
int lua_protobuf_coded_input_stream_read_little_endian_32(lua_State* L) {
::google::protobuf::io::CodedInputStream* codestream = (::google::protobuf::io::CodedInputStream*)luaL_checkudata(L, 1, "protobuf_.CodedInputStream");
::google::protobuf::uint32 val;
bool success = codestream->ReadLittleEndian32(&val);
lua_pushboolean(L, success);
if (success) {
lua_pushinteger(L, val);
} else {
lua_pushnil(L);
}
return 1;
}
int lua_protobuf_coded_input_stream_read_little_endian_64(lua_State* L) {
::google::protobuf::io::CodedInputStream* codestream = (::google::protobuf::io::CodedInputStream*)luaL_checkudata(L, 1, "protobuf_.CodedInputStream");
::google::protobuf::uint64 val;
bool success = codestream->ReadLittleEndian64(&val);
lua_pushboolean(L, success);
if (success) {
lua_pushinteger(L, val);
} else {
lua_pushnil(L);
}
return 1;
}
static const struct luaL_Reg CodedInputStream_functions [] = {
{"new", lua_protobuf_coded_input_stream_new},
{NULL, NULL}
};
static const struct luaL_Reg CodedInputStream_methods [] = {
{"__gc", lua_protobuf_coded_input_stream_gc},
{"Skip", lua_protobuf_coded_input_stream_skip},
{"PushLimit", lua_protobuf_coded_input_stream_push_limit},
{"PopLimit", lua_protobuf_coded_input_stream_pop_limit},
{"CurrentPosition", lua_protobuf_coded_input_stream_current_position},
{"ReadRaw", lua_protobuf_coded_input_stream_read_raw},
{"ReadVarint32", lua_protobuf_coded_input_stream_read_varint_32},
{"ReadVarint64", lua_protobuf_coded_input_stream_read_varint_64},
{"ReadLittleEndian32", lua_protobuf_coded_input_stream_read_little_endian_32},
{"ReadLittleEndian64", lua_protobuf_coded_input_stream_read_little_endian_64},
{NULL, NULL},
};
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
int lua_protobuf_coded_output_stream_new(lua_State* L) {
const char* filepath = luaL_checkstring(L, 1);
int fd = open(filepath, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, S_IREAD | S_IWRITE);
if (fd == -1) {
return luaL_error(L, "Failed to open file %s", filepath);
}
char* udataptr = (char*)lua_newuserdata(L, sizeof(::google::protobuf::io::CodedOutputStream)+sizeof(::google::protobuf::io::FileOutputStream));
auto outstream = new(udataptr+sizeof(::google::protobuf::io::CodedOutputStream)) ::google::protobuf::io::FileOutputStream(fd);
outstream->SetCloseOnDelete(true);
auto codestream = new (udataptr) ::google::protobuf::io::CodedOutputStream(outstream);
luaL_setmetatable(L, "protobuf_.CodedOutputStream");
return 1;
}
int lua_protobuf_coded_output_stream_gc(lua_State* L) {
::google::protobuf::io::CodedOutputStream* codestream = (::google::protobuf::io::CodedOutputStream*)luaL_checkudata(L, 1, "protobuf_.CodedOutputStream");
::google::protobuf::io::FileOutputStream* filestream = (::google::protobuf::io::FileOutputStream*)(codestream+1);
codestream->~CodedOutputStream();
filestream->~FileOutputStream();
return 0;
}
int lua_protobuf_coded_output_stream_skip(lua_State* L) {
::google::protobuf::io::CodedOutputStream* codestream = (::google::protobuf::io::CodedOutputStream*)luaL_checkudata(L, 1, "protobuf_.CodedOutputStream");
int count = luaL_checkint(L, 2);
codestream->Skip(count);
return 0;
}
int lua_protobuf_coded_output_stream_byte_count(lua_State* L) {
::google::protobuf::io::CodedOutputStream* codestream = (::google::protobuf::io::CodedOutputStream*)luaL_checkudata(L, 1, "protobuf_.CodedOutputStream");
lua_pushinteger(L, codestream->ByteCount());
return 1;
}
int lua_protobuf_coded_output_stream_write_raw(lua_State* L) {
::google::protobuf::io::CodedOutputStream* codestream = (::google::protobuf::io::CodedOutputStream*)luaL_checkudata(L, 1, "protobuf_.CodedOutputStream");
size_t count;
const char* buf = luaL_checklstring(L, 2, &count);
codestream->WriteRaw(buf, (int)count);
return 0;
}
int lua_protobuf_coded_output_stream_write_varint_32(lua_State* L) {
::google::protobuf::io::CodedOutputStream* codestream = (::google::protobuf::io::CodedOutputStream*)luaL_checkudata(L, 1, "protobuf_.CodedOutputStream");
::google::protobuf::uint32 val = luaL_checkunsigned(L, 2);
codestream->WriteVarint32(val);
return 0;
}
int lua_protobuf_coded_output_stream_write_varint_64(lua_State* L) {
::google::protobuf::io::CodedOutputStream* codestream = (::google::protobuf::io::CodedOutputStream*)luaL_checkudata(L, 1, "protobuf_.CodedOutputStream");
::google::protobuf::uint64 val = luaL_checkunsigned(L, 2);
codestream->WriteVarint64(val);
return 0;
}
int lua_protobuf_coded_output_stream_write_little_endian_32(lua_State* L) {
::google::protobuf::io::CodedOutputStream* codestream = (::google::protobuf::io::CodedOutputStream*)luaL_checkudata(L, 1, "protobuf_.CodedOutputStream");
::google::protobuf::uint32 val = luaL_checkunsigned(L, 2);
codestream->WriteLittleEndian32(val);
return 0;
}
int lua_protobuf_coded_output_stream_write_little_endian_64(lua_State* L) {
::google::protobuf::io::CodedOutputStream* codestream = (::google::protobuf::io::CodedOutputStream*)luaL_checkudata(L, 1, "protobuf_.CodedOutputStream");
::google::protobuf::uint64 val = luaL_checkunsigned(L, 2);
codestream->WriteLittleEndian64(val);
return 0;
}
static const struct luaL_Reg CodedOutputStream_functions [] = {
{"new", lua_protobuf_coded_output_stream_new},
{NULL, NULL}
};
static const struct luaL_Reg CodedOutputStream_methods [] = {
{"__gc", lua_protobuf_coded_output_stream_gc},
{"Skip", lua_protobuf_coded_output_stream_skip},
{"ByteCount", lua_protobuf_coded_output_stream_byte_count},
{"WriteRaw", lua_protobuf_coded_output_stream_write_raw},
{"WriteVarint32", lua_protobuf_coded_output_stream_write_varint_32},
{"WriteVarint64", lua_protobuf_coded_output_stream_write_varint_64},
{"WriteLittleEndian32", lua_protobuf_coded_output_stream_write_little_endian_32},
{"WriteLittleEndian64", lua_protobuf_coded_output_stream_write_little_endian_64},
{NULL, NULL},
};
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
static const struct luaL_Reg CodedInputStream_lib_functions [] = {
{NULL, NULL}
};
int lua_protobuf_coded_streams_open(lua_State* L) {
luaL_checktype(L, -1, LUA_TTABLE);
luaL_newmetatable(L, "protobuf_.CodedInputStream");
lua_pushvalue(L, -1);
lua_setfield(L, -2, "__index");
luaL_setfuncs(L, CodedInputStream_methods, 0);
lua_pop(L, 1);//pop the metatable
luaL_newmetatable(L, "protobuf_.CodedOutputStream");
lua_pushvalue(L, -1);
lua_setfield(L, -2, "__index");
luaL_setfuncs(L, CodedOutputStream_methods, 0);
lua_pop(L, 1);//pop the metatable
// add create funcs and tables
luaL_newlib(L, CodedInputStream_functions);
lua_setfield(L, -2, "CodedInputStream");
luaL_newlib(L, CodedOutputStream_functions);
lua_setfield(L, -2, "CodedOutputStream");
return 0;
}
#ifdef __cplusplus
extern "C" {
#endif
const char *luaEXT_findtable (lua_State *L, const char *fname, int idx, int szhint) {
const char *e;
if (idx) lua_pushvalue(L, idx);
do {
e = strchr(fname, '.');
if (e == NULL) e = fname + strlen(fname);
lua_pushlstring(L, fname, e - fname);
lua_rawget(L, -2);
if (lua_isnil(L, -1)) { /* no such field? */
lua_pop(L, 1); /* remove this nil */
lua_createtable(L, 0, (*e == '.' ? 1 : szhint)); /* new table for field */
lua_pushlstring(L, fname, e - fname);
lua_pushvalue(L, -2);
lua_settable(L, -4); /* set new table into field */
}
else if (!lua_istable(L, -1)) { /* field has a non-table value? */
lua_pop(L, 2); /* remove table and value */
return fname; /* return problematic part of the name */
}
lua_remove(L, -2); /* remove previous table */
fname = e + 1;
} while (*e == '.');
return NULL;
}
#ifdef __cplusplus
}
#endif
'''
def source_header(filename, package, file_descriptor):
'''Returns lines that begin a source file'''
lines = []
lines.extend( [
'// Generated by the lua-protobuf compiler',
'// You shouldn\'t edit this file manually',
'//',
'// source proto file: %s' % filename,
'',
])
lines.append('#include "%s.pb.lua.h"' % filename.replace('.proto', ''))
for type in file_descriptor.dependency:
lines.append('#include "%s.pb.lua.h"' % type.replace('.proto', ''))
lines.extend( ['',
'#ifdef __cplusplus',
'extern "C" { // make sure functions treated with C naming',
'#endif',
'',
'#include <lauxlib.h>',
'',
'#ifdef __cplusplus',
'}',
'#endif',
'',
'#include <string>',
'',
'// this represents Lua udata for a protocol buffer message',
'// we record where a message came from so we can GC it properly',
'typedef struct msg_udata { // confuse over-simplified pretty-printer',
' ::google::protobuf::MessageLite * msg;',
' bool lua_owns;',
' lua_protobuf_gc_callback gc_callback;',
' void * callback_data;',
'} msg_udata;',
'',])
return lines
def message_open_function_name(package, message):
'''Returns function name that registers the Lua library for a message type'''
return '%sopen' % message_function_prefix(package, message)
def cpp_class(package, message = None):
'''Returns the fully qualified class name for a message type'''
if not message:
return package.replace('.', '::')
return '::%s::%s' % ( package.replace('.', '::'), message )
def field_function_name(package, message, prefix, field):
'''Obtain the function name of a field accessor/mutator function'''
return '%s%s_%s' % ( message_function_prefix(package, message), prefix, field )
def field_function_start(package, message, prefix, field):
'''Obtain the start of function for a field accessor function'''
return [
'int %s(lua_State *L)' % field_function_name(package, message, prefix, field.lower()),
'{',
]
def lua_libname(package, message):
'''Returns the Lua library name for a specific message'''
return 'protobuf.%s.%s' % (package, message)
def metatable(package, message):
'''Returns Lua metatable for protocol buffer message type'''
return 'protobuf_.%s.%s' % (package, message)
def obtain_message_from_udata(package, message=None, index=1, varname='m'):
'''Statement that obtains a message from userdata'''
c = cpp_class(package, message)
return [
'msg_udata * %sud = (msg_udata *)%s;' % ( varname, check_udata(package, message, index) ),
'%s *%s = (%s *)%sud->msg;' % ( c, varname, c, varname ),
]
def check_udata(package, message, index=1):
'''Validates a udata is instance of protocol buffer message
By default, it validates udata at top of the stack
'''
return 'luaL_checkudata(L, %d, "%s")' % ( index, metatable(package, message) )
def has_body(package, message, field):
'''Returns the function body for a has_<field> function'''
lines = []
lines.extend(obtain_message_from_udata(package, message))
lines.append('lua_pushboolean(L, m->has_%s());' % field.lower())
lines.append('return 1;')
return lines
def clear_body(package, message, field):
'''Returns the function body for a clear_<field> function'''
lines = []
lines.extend(obtain_message_from_udata(package, message))
lines.append('m->clear_%s();' % field.lower())
lines.append('return 0;')
return lines
def size_body(package, message, field):
'''Returns the function body for a size_<field> function'''
lines = []
lines.extend(obtain_message_from_udata(package, message))
lines.append('int size = m->%s_size();' % field.lower())
lines.append('lua_pushinteger(L, size);')
lines.append('return 1;')
return lines
def add_body(package, message, field, type_name):
'''Returns the function body for the add_<field> function for repeated embedded messages'''
lines = []
lines.extend(obtain_message_from_udata(package, message))
lines.extend([
'%s *msg_new = m->add_%s();' % ( cpp_class(type_name), field.lower() ),
# since the message is allocated out of the containing message, Lua
# does not need to do GC
'lua_protobuf%s_pushreference(L, msg_new, NULL, NULL);' % type_name.replace('.', '_'),
'return 1;',
])
return lines
def field_get(package, message, field_descriptor):
'''Returns function definition for a get_<field> function'''
name = field_descriptor.name
type = field_descriptor.type
type_name = field_descriptor.type_name
label = field_descriptor.label
repeated = label == FieldDescriptor.LABEL_REPEATED
lines = []
lines.extend(field_function_start(package, message, 'get', name))
lines.extend(obtain_message_from_udata(package, message))
# the logic is significantly different depending on if the field is
# singular or repeated.
# for repeated, we have an argument which points to the numeric index to
# retrieve. in true Lua convention, we index starting from 1, which is
# different from protocol buffers, which indexes from 0
if repeated:
lines.extend([
'if (lua_gettop(L) != 2) {',
'return luaL_error(L, "missing required numeric argument");',
'}',
'lua_Integer index = luaL_checkinteger(L, 2);',
'if (index < 1 || index > m->%s_size()) {' % name.lower(),
# TODO is returning nil the more Lua way?
'return luaL_error(L, "index must be between 1 and current size: %%d", m->%s_size());' % name.lower(),
'}',
])
# TODO float and double types are not equivalent. don't treat them as such
# TODO figure out how to support 64 bit integers properly
if repeated:
if type in [ FieldDescriptor.TYPE_STRING, FieldDescriptor.TYPE_BYTES ]:
lines.extend([
'string s = m->%s(index - 1);' % name.lower(),
'lua_pushlstring(L, s.c_str(), s.size());',
])
elif type == FieldDescriptor.TYPE_BOOL:
lines.append('lua_pushboolean(L, m->%s(index-1));' % name.lower())
elif type in [FieldDescriptor.TYPE_INT32, FieldDescriptor.TYPE_UINT32,
FieldDescriptor.TYPE_FIXED32, FieldDescriptor.TYPE_SFIXED32, FieldDescriptor.TYPE_SINT32]:
lines.append('lua_pushinteger(L, m->%s(index-1));' % name.lower())
elif type in [ FieldDescriptor.TYPE_INT64, FieldDescriptor.TYPE_UINT64,
FieldDescriptor.TYPE_FIXED64, FieldDescriptor.TYPE_SFIXED64, FieldDescriptor.TYPE_SINT64]:
lines.append('lua_pushinteger(L, m->%s(index-1));' % name.lower())
elif type == FieldDescriptor.TYPE_FLOAT or type == FieldDescriptor.TYPE_DOUBLE:
lines.append('lua_pushnumber(L, m->%s(index-1));' % name.lower())
elif type == FieldDescriptor.TYPE_ENUM:
lines.append('lua_pushnumber(L, m->%s(index-1));' % name.lower())
elif type == FieldDescriptor.TYPE_MESSAGE:
lines.extend([
'%s * got_msg = m->mutable_%s(index-1);' % ( type_name.replace('.', '::'), name.lower() ),
'lua_protobuf%s_pushreference(L, got_msg, NULL, NULL);' % type_name.replace('.', '_'),
])
else:
lines.append('return luaL_error(L, "lua-protobuf does not support this field type");')
else:
# for scalar fields, we push nil if the value is not defined
# this is the Lua way
if type == FieldDescriptor.TYPE_STRING or type == FieldDescriptor.TYPE_BYTES:
lines.append('string s = m->%s();' % name.lower())
lines.append('if (m->has_%s()) lua_pushlstring(L, s.c_str(), s.size()); else lua_pushnil(L);' % name.lower())
elif type == FieldDescriptor.TYPE_BOOL:
lines.append('if (m->has_%s()) lua_pushboolean(L, m->%s()); else lua_pushnil(L);' % ( name.lower(), name.lower() ))
elif type in [FieldDescriptor.TYPE_INT32, FieldDescriptor.TYPE_UINT32,
FieldDescriptor.TYPE_FIXED32, FieldDescriptor.TYPE_SFIXED32, FieldDescriptor.TYPE_SINT32]:
lines.append('if (m->has_%s()) lua_pushinteger(L, m->%s()); else lua_pushnil(L);' % ( name.lower(), name.lower() ))
elif type in [ FieldDescriptor.TYPE_INT64, FieldDescriptor.TYPE_UINT64,
FieldDescriptor.TYPE_FIXED64, FieldDescriptor.TYPE_SFIXED64, FieldDescriptor.TYPE_SINT64]:
lines.append('if (m->has_%s()) lua_pushinteger(L, m->%s()); else lua_pushnil(L);' % ( name.lower(), name.lower() ))
elif type == FieldDescriptor.TYPE_FLOAT or type == FieldDescriptor.TYPE_DOUBLE:
lines.append('if (m->has_%s()) lua_pushnumber(L, m->%s()); else lua_pushnil(L);' % ( name.lower(), name.lower() ))
elif type == FieldDescriptor.TYPE_ENUM:
lines.append('if (m->has_%s()) lua_pushinteger(L, m->%s()); else lua_pushnil(L);' % ( name.lower(), name.lower() ))
elif type == FieldDescriptor.TYPE_MESSAGE:
lines.extend([
'if (!m->has_%s()) {' % name.lower(),
'lua_pushnil(L);',
'}',
# we push the message as userdata
# since the message is allocated out of the parent message, we
# don't need to do garbage collection
'%s * got_msg = m->mutable_%s();' % ( type_name.replace('.', '::'), name.lower() ),
'lua_protobuf%s_pushreference(L, got_msg, NULL, NULL);' % type_name.replace('.', '_'),
])
else:
# not supported yet :(
lines.append('return luaL_error(L, "lua-protobuf does not support this field type");')
lines.append('return 1;')
lines.append('}\n')
return lines
def field_set(package, message, field_descriptor):
'''Returns function definition for a set_<field> function'''
name = field_descriptor.name
type = field_descriptor.type
type_name = field_descriptor.type_name
label = field_descriptor.label
repeated = label == FieldDescriptor.LABEL_REPEATED
lines = []
lines.extend(field_function_start(package, message, 'set', name.lower()))
lines.extend(obtain_message_from_udata(package, message, 1))
# we do things differently depending on if this is a singular or repeated field
# for singular fields, the new value is the first argument
# for repeated fields, the index is arg1 and the value is arg2
if repeated:
lines.extend([
'if (lua_gettop(L) != 3) {',
' return luaL_error(L, "required 2 arguments not passed to function");',
'}',
'lua_Integer index = luaL_checkinteger(L, 2);',
'int current_size = m->%s_size();' % name.lower(),
'if (index < 1 || index > current_size + 1) {',
'return luaL_error(L, "index must be between 1 and %d", current_size + 1);',
'}',
# we don't support the automagic nil clears value... yet
'if (lua_isnil(L, 3)) {',
'return luaL_error(L, "cannot assign nil to repeated fields (yet)");',
'}',
])
# TODO proper 64 bit handling
# now move on to the assignment
if repeated:
if type in [ FieldDescriptor.TYPE_STRING, FieldDescriptor.TYPE_BYTES ]:
lines.extend([
'size_t length = 0;',
'const char *s = luaL_checklstring(L, 3, &length);',
])
lines.extend(field_set_assignment(name, 's, length'))
elif type == FieldDescriptor.TYPE_BOOL:
lines.append('bool b = !!lua_toboolean(L, 3);')
lines.extend(field_set_assignment(name, 'b'))
elif type in [ FieldDescriptor.TYPE_DOUBLE, FieldDescriptor.TYPE_FLOAT ]:
lines.append('double d = lua_tonumber(L, 3);')
lines.extend(field_set_assignment(name, 'd'))
elif type in [ FieldDescriptor.TYPE_INT32, FieldDescriptor.TYPE_FIXED32,
FieldDescriptor.TYPE_UINT32, FieldDescriptor.TYPE_SFIXED32, FieldDescriptor.TYPE_SINT32 ]:
lines.append('lua_Integer i = lua_tointeger(L, 3);')
lines.extend(field_set_assignment(name, 'i'))
elif type in [ FieldDescriptor.TYPE_INT64, FieldDescriptor.TYPE_UINT64,
FieldDescriptor.TYPE_FIXED64, FieldDescriptor.TYPE_SFIXED64, FieldDescriptor.TYPE_SINT64]:
lines.append('lua_Integer i = lua_tointeger(L, 3);')
lines.extend(field_set_assignment(name, 'i'))
elif type == FieldDescriptor.TYPE_ENUM:
lines.append('lua_Integer i = lua_tointeger(L, 3);')
lines.extend(field_set_assignment(name, '(%s)i' % type_name.replace('.', '::')))
elif type == FieldDescriptor.TYPE_MESSAGE:
lines.append('return luaL_error(L, "to manipulate embedded messages, fetch the embedded message and modify it");')
else:
lines.append('return luaL_error(L, "field type not yet supported");')
lines.append('return 0;')
else:
# if they call set() with nil, we interpret as a clear
# this is the Lua way, after all
lines.extend([
'if (lua_isnil(L, 2)) {',
'm->clear_%s();' % name.lower(),
'return 0;',
'}',
'',
])
if type in [ FieldDescriptor.TYPE_STRING, FieldDescriptor.TYPE_BYTES ]:
lines.extend([
'if (!lua_isstring(L, 2)) return luaL_error(L, "passed value is not a string");',
'size_t len;',
'const char *s = lua_tolstring(L, 2, &len);',
'if (!s) {',
'luaL_error(L, "could not obtain string on stack. weird");',
'}',
'm->set_%s(s, len);' % name.lower(),
'return 0;',
])
elif type in [ FieldDescriptor.TYPE_DOUBLE, FieldDescriptor.TYPE_FLOAT ]:
lines.extend([
'if (!lua_isnumber(L, 2)) return luaL_error(L, "passed value cannot be converted to a number");',
'lua_Number n = lua_tonumber(L, 2);',
'm->set_%s(n);' % name.lower(),
'return 0;',
])
elif type in [ FieldDescriptor.TYPE_INT32, FieldDescriptor.TYPE_FIXED32,
FieldDescriptor.TYPE_UINT32, FieldDescriptor.TYPE_SFIXED32, FieldDescriptor.TYPE_SINT32 ]:
lines.extend([
'lua_Integer v = luaL_checkinteger(L, 2);',
'm->set_%s(v);' % name.lower(),
'return 0;',
])
elif type in [ FieldDescriptor.TYPE_INT64, FieldDescriptor.TYPE_UINT64,
FieldDescriptor.TYPE_FIXED64, FieldDescriptor.TYPE_SFIXED64, FieldDescriptor.TYPE_SINT64]:
lines.extend([
'lua_Integer i = luaL_checkinteger(L, 2);',
'm->set_%s(i);' % name.lower(),
'return 0;',
])
elif type == FieldDescriptor.TYPE_BOOL:
lines.extend([
'bool b = !!lua_toboolean(L, 2);',
'm->set_%s(b);' % name.lower(),
'return 0;',
])
elif type == FieldDescriptor.TYPE_ENUM:
lines.extend([
'lua_Integer i = luaL_checkinteger(L, 2);',
'm->set_%s((%s)i);' % ( name.lower(), type_name.replace('.', '::') ),
'return 0;',
])
elif type == FieldDescriptor.TYPE_MESSAGE:
lines.append('return luaL_error(L, "to manipulate embedded messages, obtain the embedded message and manipulate it");')
else:
lines.append('return luaL_error(L, "field type is not yet supported");')
lines.append('}\n')
return lines
def new_message(package, message):
'''Returns function definition for creating a new protocol buffer message'''
lines = []
lines.append('int %snew(lua_State *L)' % message_function_prefix(package, message))
lines.append('{')
c = cpp_class(package, message)
lines.append('msg_udata * ud = (msg_udata *)lua_newuserdata(L, sizeof(msg_udata));')
lines.append('ud->lua_owns = true;')
lines.append('ud->msg = new %s();' % c)
lines.append('ud->gc_callback = NULL;')
lines.append('ud->callback_data = NULL;')
lines.append('luaL_getmetatable(L, "%s");' % metatable(package, message))
lines.append('lua_setmetatable(L, -2);')
lines.append('return 1;')
lines.append('}\n')
return lines
def message_pushcopy_function(package, message):
'''Returns function definition for pushing a copy of a message to the stack'''
return [
'bool %spushcopy(lua_State *L, const %s &from)' % ( message_function_prefix(package, message), cpp_class(package, message) ),
'{',
'msg_udata * ud = (msg_udata *)lua_newuserdata(L, sizeof(msg_udata));',
'ud->lua_owns = true;',
'ud->msg = new %s(from);' % cpp_class(package, message),
'ud->gc_callback = NULL;',
'ud->callback_data = NULL;',
'luaL_getmetatable(L, "%s");' % metatable(package, message),
'lua_setmetatable(L, -2);',
'return true;',
'}',
]
def message_getcopy_function(package, message):
'''Returns function definition for getting a copy of a message from the stack'''
return [
'void %sgetcopy(lua_State *L, int index, %s &to)' % ( message_function_prefix(package, message), cpp_class(package, message) ),
'{',
'msg_udata * ud = (msg_udata *)luaL_checkudata(L, index, "%s")' % ( metatable(package, message) ),
'to->CopyFrom(*ud->msg);',
'}',
]
def message_pushreference_function(package, message):
'''Returns function definition for pushing a reference of a message on the stack'''
return [
'bool %spushreference(lua_State *L, %s *msg, lua_protobuf_gc_callback f, void *data)' % ( message_function_prefix(package, message), cpp_class(package, message) ),
'{',
'msg_udata * ud = (msg_udata *)lua_newuserdata(L, sizeof(msg_udata));',
'ud->lua_owns = false;',
'ud->msg = msg;',
'ud->gc_callback = f;',
'ud->callback_data = data;',
'luaL_getmetatable(L, "%s");' % metatable(package, message),
'lua_setmetatable(L, -2);',
'return true;',
'}',
]
def parsefromstring_message_function(package, message):
'''Returns function definition for parsing a message from a serialized string'''
lines = []
lines.append('int %sparsefromstring(lua_State *L)' % message_function_prefix(package, message))
c = cpp_class(package, message)
lines.extend([
'{',
'if (lua_gettop(L) != 1) {',
'return luaL_error(L, "parsefromstring() requires a string argument. none given");',
'}',
'size_t len;',
'const char *s = luaL_checklstring(L, -1, &len);',
'%s * msg = new %s();' % ( c, c ),
'if (!msg->ParseFromArray((const void *)s, len)) {',
'return luaL_error(L, "error deserializing message");',
'}',
'msg_udata * ud = (msg_udata *)lua_newuserdata(L, sizeof(msg_udata));',
'ud->lua_owns = true;',
'ud->msg = msg;',
'ud->gc_callback = NULL;',
'ud->callback_data = NULL;',
'luaL_getmetatable(L, "%s");' % metatable(package, message),
'lua_setmetatable(L, -2);',
'return 1;',
'}',
])
return lines
def descriptor_message_function(package, message, descriptor):
''' Return a function that builds a table that describes message. Returns table to Lua for inspection'''
lines = []
lines.extend([
'int %sdescriptor(lua_State* L)' % message_function_prefix(package, message),
'{',
' lua_newtable(L);',
' ',
]);
for fields_descriptor in descriptor.field:
lines.extend([
' // Field: default_value = %s' % fields_descriptor.default_value,
' lua_newtable(L);',
' lua_pushstring(L, "%s");' % fields_descriptor.name,
' lua_setfield(L, -2, "name");',
' lua_pushstring(L, "%s");' % label_to_string(fields_descriptor.label),
' lua_setfield(L, -2, "label");',
' lua_pushnumber(L, %s);' % fields_descriptor.number,
' lua_setfield(L, -2, "number");',
' lua_pushstring(L, "%s");' % type_to_string(fields_descriptor.type),
' lua_setfield(L, -2, "type");',
' lua_pushstring(L, "%s");' % (fields_descriptor.type_name) if fields_descriptor.type_name else '',
' lua_setfield(L, -2, "type_name");' if fields_descriptor.type_name else '',
' lua_setfield(L, -2, "%s");' % fields_descriptor.name,
]);
lines.extend([
'',
' return 1;',
'}',
])
return lines
def gc_message_function(package, message):
'''Returns function definition for garbage collecting a message'''
lines = [
'int %sgc(lua_State *L)' % message_function_prefix(package, message),
'{',
]
lines.extend(obtain_message_from_udata(package, message, 1))
# if Lua "owns" the message, we delete it
# else, we delete only if a callback exists and it says it is OK
lines.extend([
'if (mud->lua_owns) {',
'delete mud->msg;',
'mud->msg = NULL;',
'return 0;',
'}',
'if (mud->gc_callback && mud->gc_callback(m, mud->callback_data)) {',
'delete mud->msg;',
'mud->msg = NULL;',
'return 0;',
'}',
'return 0;',
'}',
])
return lines
def clear_message_function(package, message):
'''Returns the function definition for clearing a message'''
lines = [
'int %sclear(lua_State *L)' % message_function_prefix(package, message),
'{'
]
lines.extend(obtain_message_from_udata(package, message, 1))
lines.extend([
'm->Clear();',
'return 0;',
'}',
])
return lines
def serialized_message_function(package, message):
'''Returns the function definition for serializing a message and its length'''
lines = [
'int %sserialized(lua_State *L)' % message_function_prefix(package, message),
'{'
]
lines.extend(obtain_message_from_udata(package, message, 1))
lines.extend([
'string s;',
'if (!m->SerializeToString(&s)) {',
'return luaL_error(L, "error serializing message");',
'}',
'lua_pushlstring(L, s.c_str(), s.length());',
'lua_pushnumber(L, s.length());',
'return 2;',
'}',
])
return lines
def message_function_array(package, message):
'''Defines functions for Lua object type
These are defined on the Lua metatable for the message type.
These are basically constructors and static methods in Lua land.
'''
return [
'static const struct luaL_Reg %s_functions [] = {' % message,
'{"new", %snew},' % message_function_prefix(package, message),
'{"parsefromstring", %sparsefromstring},' % message_function_prefix(package, message),
'{"descriptor", %sdescriptor},' % message_function_prefix(package, message),
'{NULL, NULL}',
'};\n',
]
def message_method_array(package, descriptor):
'''Defines functions for Lua object instances
These are functions available to each instance of a message.
They take the object userdata as the first parameter.
'''
message = descriptor.name
fp = message_function_prefix(package, message)
lines = []
lines.append('static const struct luaL_Reg %s_methods [] = {' % message)
lines.append('{"serialized", %sserialized},' % fp)
lines.append('{"clear", %sclear},' % fp)
lines.append('{"__gc", %sgc},' % message_function_prefix(package, message))
for fd in descriptor.field:
name = fd.name
label = fd.label
type = fd.type
lines.append('{"clear_%s", %s},' % ( name.lower(), field_function_name(package, message, 'clear', name.lower()) ))
lines.append('{"get_%s", %s},' % ( name.lower(), field_function_name(package, message, 'get', name.lower()) ))
lines.append('{"set_%s", %s},' % ( name.lower(), field_function_name(package, message, 'set', name.lower()) ))
if label in [ FieldDescriptor.LABEL_REQUIRED, FieldDescriptor.LABEL_OPTIONAL ]:
lines.append('{"has_%s", %s},' % ( name.lower(), field_function_name(package, message, 'has', name.lower()) ))
if label == FieldDescriptor.LABEL_REPEATED:
lines.append('{"size_%s", %s},' % ( name.lower(), field_function_name(package, message, 'size', name.lower()) ))
if type == FieldDescriptor.TYPE_MESSAGE:
lines.append('{"add_%s", %s},' % ( name.lower(), field_function_name(package, message, 'add', name.lower()) ))
lines.append('{NULL, NULL},')
lines.append('};\n')
return lines
def message_open_function(package, descriptor):
'''Function definition for opening/registering a message type'''
message = descriptor.name
lines = [
'int %s(lua_State *L)' % message_open_function_name(package, message),
'{',
'luaL_checktype(L, -1, LUA_TTABLE);', #
'luaL_newmetatable(L, "%s");' % metatable(package, message),
'lua_pushvalue(L, -1);',
'lua_setfield(L, -2, "__index");',
'luaL_setfuncs(L, %s_methods, 0);' % message, ##'luaL_register(L, NULL, %s_methods);' % message,
'lua_pop(L, 1); // remove the metatable', #
'if (luaEXT_findtable(L, "%s", -1, 1)) { ' % package, #
' return luaL_error(L, "Error finding correct table");',
'}',
'luaL_newlib(L, %s_functions);' % message, ##'luaL_register(L, "%s", %s_functions);' % (lua_libname(package, message), message),
'lua_setfield(L, -2, "%s");' % message, #
'lua_pop(L, 1); //remove the returned table from findtable' #
]
for enum_descriptor in descriptor.enum_type:
lines.extend(enum_source(enum_descriptor))
lines.extend([
# this is wrong if we are calling through normal Lua module load means
#'lua_pop(L, 1);',
'return 0;',#'return 1;',
'}',
'\n',
])
return lines
def message_header(package, message_descriptor):
'''Returns the lines for a header definition of a message'''
message_name = message_descriptor.name
lines = []
lines.append('// Message %s' % message_name)
function_prefix = 'lua_protobuf_' + package.replace('.', '_') + '_'
c = cpp_class(package, message_name)
lines.extend([
'// registers the message type with Lua',
'LUA_PROTOBUF_EXPORT int %s(lua_State *L);\n' % message_open_function_name(package, message_name),
'',
'// push a copy of the message to the Lua stack',
'// caller is free to use original message however she wants, but changes will not',
'// be reflected in Lua and vice-verse',
'LUA_PROTOBUF_EXPORT bool %s%s_pushcopy(lua_State *L, const %s &msg);' % ( function_prefix, message_name, c),
'',
'// push a reference of the message to the Lua stack',
'// the 3rd and 4th arguments define a callback that can be invoked just before Lua',
'// garbage collects the message. If the 3rd argument is NULL, Lua will *NOT* free',
'// memory. If the second argument points to a function, that function is called when',
'// Lua garbage collects the object. The function is sent a pointer to the message being',
'// collected and the 4th argument to this function. If the function returns true,',
'// Lua will free the memory. If false (0), Lua will not free the memory.',
'LUA_PROTOBUF_EXPORT bool %s%s_pushreference(lua_State *L, %s *msg, lua_protobuf_gc_callback callback, void *data);' % ( function_prefix, message_name, c ),
'',
'// get a copy of the message from the Lua stack',
'// caller is free to use the new message however she wants, but changes will not',
'// be reflected in Lua and vice-verse',
'LUA_PROTOBUF_EXPORT bool %s%s_getcopy(lua_State *L, int index, %s &msg);' % ( function_prefix, message_name, c),
'',
'',
'// The following functions are called by Lua. Many people will not need them,',
'// but they are exported for those that do.',
'',
'',
'// constructor called from Lua',
'LUA_PROTOBUF_EXPORT int %s%s_new(lua_State *L);' % ( function_prefix, message_name ),
'',
'// obtain instance from a serialized string',
'LUA_PROTOBUF_EXPORT int %s%s_parsefromstring(lua_State *L);' % ( function_prefix, message_name ),
'',
'// obtain table of fields in this message',
'LUA_PROTOBUF_EXPORT int %s%s_descriptor(lua_State* L);' % ( function_prefix, message_name),
'',
'// garbage collects message instance in Lua',
'LUA_PROTOBUF_EXPORT int %s%s_gc(lua_State *L);' % ( function_prefix, message_name ),
'',
'// obtain serialized representation of instance',
'LUA_PROTOBUF_EXPORT int %s%s_serialized(lua_State *L);' % ( function_prefix, message_name ),
'',
'// clear all fields in the message',
'LUA_PROTOBUF_EXPORT int %s%s_clear(lua_State *L);' % ( function_prefix, message_name ),
'',
])
# each field defined in the message
for field_descriptor in message_descriptor.field:
field_name = field_descriptor.name
field_number = field_descriptor.number
field_label = field_descriptor.label
field_type = field_descriptor.type
field_default = field_descriptor.default_value
if field_label not in FIELD_LABEL_MAP.keys():
raise Exception('unknown field label constant: %s' % field_label)
field_label_s = FIELD_LABEL_MAP[field_label]
if field_type not in FIELD_TYPE_MAP.keys():
raise Exception('unknown field type: %s' % field_type)
field_type_s = FIELD_TYPE_MAP[field_type]
lines.append('// %s %s %s = %d' % (field_label_s, field_type_s, field_name, field_number))
lines.append('LUA_PROTOBUF_EXPORT int %s%s_clear_%s(lua_State *L);' % (function_prefix, message_name, field_name.lower()))
lines.append('LUA_PROTOBUF_EXPORT int %s%s_get_%s(lua_State *L);' % (function_prefix, message_name, field_name.lower()))
# TODO I think we can get rid of this for message types
lines.append('LUA_PROTOBUF_EXPORT int %s%s_set_%s(lua_State *L);' % (function_prefix, message_name, field_name.lower()))
if field_label in [ FieldDescriptor.LABEL_REQUIRED, FieldDescriptor.LABEL_OPTIONAL ]:
lines.append('LUA_PROTOBUF_EXPORT int %s%s_has_%s(lua_State *L);' % (function_prefix, message_name, field_name.lower()))
if field_label == FieldDescriptor.LABEL_REPEATED:
lines.append('LUA_PROTOBUF_EXPORT int %s%s_size_%s(lua_State *L);' % (function_prefix, message_name, field_name.lower()))
if field_type == FieldDescriptor.TYPE_MESSAGE:
lines.append('LUA_PROTOBUF_EXPORT int %s%s_add_%s(lua_State *L);' % ( function_prefix, message_name, field_name.lower()))
lines.append('')
lines.append('// end of message %s\n' % message_name)
return lines
def message_source(package, message_descriptor):
'''Returns lines of source code for an individual message type'''
lines = []
message = message_descriptor.name
lines.extend(message_function_array(package, message))
lines.extend(message_method_array(package, message_descriptor))
lines.extend(message_open_function(package, message_descriptor))
lines.extend(message_pushcopy_function(package, message))
lines.extend(message_pushreference_function(package, message))
lines.extend(message_getcopy_function(package, message))
lines.extend(new_message(package, message))
lines.extend(parsefromstring_message_function(package, message))
lines.extend(descriptor_message_function(package, message, message_descriptor))
lines.extend(gc_message_function(package, message))
lines.extend(clear_message_function(package, message))
lines.extend(serialized_message_function(package, message))
for descriptor in message_descriptor.field:
name = descriptor.name
# clear() is in all label types
lines.extend(field_function_start(package, message, 'clear', name))
lines.extend(clear_body(package, message, name))
lines.append('}\n')
lines.extend(field_get(package, message, descriptor))
lines.extend(field_set(package, message, descriptor))
if descriptor.label in [FieldDescriptor.LABEL_OPTIONAL, FieldDescriptor.LABEL_REQUIRED]:
# has_<field>()
lines.extend(field_function_start(package, message, 'has', name))
lines.extend(has_body(package, message, name))
lines.append('}\n')
if descriptor.label == FieldDescriptor.LABEL_REPEATED:
# size_<field>()
lines.extend(field_function_start(package, message, 'size', name))
lines.extend(size_body(package, message, name))
lines.append('}\n')
if descriptor.type == FieldDescriptor.TYPE_MESSAGE:
lines.extend(field_function_start(package, message, 'add', name))
lines.extend(add_body(package, message, name, descriptor.type_name))
lines.append('}\n')
return lines
def enum_source(descriptor):
'''Returns source code defining an enumeration type'''
# this function assumes the module/table the enum should be assigned to
# is at the top of the stack when it is called
name = descriptor.name
# enums are a little funky
# at the core, there is a table whose keys are the enum string names and
# values corresponding to the respective integer values. this table also
# has a metatable with __index to throw errors when unknown enumerations
# are accessed
#
# this table is then wrapped in a proxy table. the proxy table is empty
# but has a metatable with __index and __newindex set. __index is the
# table that actually contains the values. __newindex is a function that
# always throws an error.
#
# we need the proxy table so we can intercept all requests for writes.
# __newindex is only called for new keys, so we need an empty table so
# all writes are sent to __newindex
lines = [
'// %s enum' % name,
'lua_newtable(L); // proxy table',
'lua_newtable(L); // main table',
]
# assign enumerations to the table
for value in descriptor.value:
k = value.name
v = value.number
lines.extend([
'lua_pushnumber(L, %d);' % v,
'lua_setfield(L, -2, "%s");' % k
])
# assign the metatable
lines.extend([
'// define metatable on main table',
'lua_newtable(L);',
'lua_pushcfunction(L, lua_protobuf_enum_index);',
'lua_setfield(L, -2, "__index");',
'lua_setmetatable(L, -2);',
'',
'// define metatable on proxy table',
'lua_newtable(L);',
# proxy meta: -1; main: -2; proxy: -3
'lua_pushvalue(L, -2);',
'lua_setfield(L, -2, "__index");',
'lua_pushcfunction(L, lua_protobuf_enum_newindex);',
'lua_setfield(L, -2, "__newindex");',
'lua_remove(L, -2);',
'lua_setmetatable(L, -2);',
# proxy at top of stack now
# assign to appropriate module
'lua_setfield(L, -2, "%s");' % name,
'// end %s enum' % name
])
return lines
def file_source(file_descriptor):
'''Obtains the source code for a FileDescriptor instance'''
filename = file_descriptor.name
package = file_descriptor.package
lines = []
lines.extend(source_header(filename, package, file_descriptor))
lines.append('using ::std::string;\n')
lines.extend([
'int %sopen(lua_State *L)' % proto_function_open_name(filename),
'{',
])
# we populate enumerations as tables inside the protobuf global
# variable/module
# this is a little tricky, because we need to ensure all the parent tables
# are present
# i.e. protobuf.package.foo.enum => protobuf['package']['foo']['enum']
# we interate over all the tables and create missing ones, as necessary
# we cheat here and use the undocumented/internal luaL_findtable function
# we probably shouldn't rely on an "internal" API, so
# TODO don't use internal API call
lines.extend([
'luaL_checktype(L, -1, LUA_TTABLE);',
'const char *table = luaEXT_findtable(L, "%s", -1, 1);' % package,
'if (table) {',
'return luaL_error(L, "could not create parent Lua tables");',
'}',
'if (!lua_istable(L, -1)) {',
'return luaL_error(L, "could not create parent Lua tables");',
'}',
])
for descriptor in file_descriptor.enum_type:
lines.extend(enum_source(descriptor))
lines.extend([
# don't need main table on stack any more
'lua_pop(L, 1);',
# and we register this package as a module, complete with enumerations
#'luaL_Reg funcs [] = { { NULL, NULL } };',
#'luaL_register(L, "protobuf.%s", funcs);' % package,
])
for descriptor in file_descriptor.message_type:
lines.append('%s(L);' % message_open_function_name(package, descriptor.name))
lines.append('return 0;')
lines.append('}')
lines.append('\n')
for descriptor in file_descriptor.message_type:
lines.extend(message_source(package, descriptor))
# perform some hacky pretty-printing
formatted = []
indent = 0
for line in lines:
if RE_BARE_BEGIN_BRACKET.search(line):
formatted.append((' ' * indent) + line)
indent += 4
elif RE_BEGIN_BRACKET.search(line):
formatted.append((' ' * indent) + line)
indent += 4
elif RE_END_BRACKET.search(line):
if indent >= 4:
indent -= 4
formatted.append((' ' * indent) + line)
else:
formatted.append((' ' * indent) + line)
return '\n'.join(formatted)
| 38.692913 | 171 | 0.633734 |
622c20a0f1ed0a0cb3f5825e401509f63208a68b | 6,303 | py | Python | autoimpute/AutoImpute.py | milescsmith/AutoImpute | b327283f6fe4efc9528052218ad7dbf094c8962c | [
"MIT"
] | null | null | null | autoimpute/AutoImpute.py | milescsmith/AutoImpute | b327283f6fe4efc9528052218ad7dbf094c8962c | [
"MIT"
] | null | null | null | autoimpute/AutoImpute.py | milescsmith/AutoImpute | b327283f6fe4efc9528052218ad7dbf094c8962c | [
"MIT"
] | null | null | null | import os
import numpy as np
import scipy.io
import tensorflow as tf
from sklearn.metrics import mean_absolute_error, mean_squared_error
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
def autoimpute(data: str, debug: bool = True, debug_display_step: int = 1,
hidden_units: int = 2000, lambda_val: int = 1, initial_learning_rate: float = 0.0001, iterations: int = 7000,
threshold: int = 0.0001,
masked_matrix_test: bool = False,
masking_percentage: float = 10,
log_file: str = 'log.txt',
load_saved: bool = False):
"""
# Print debug statements
debug: type = bool, default=True, Want debug statements
debug_display_step: type=int, default=1, Display loss after
# Hyper-parameters
hidden_units: type=int, default=2000, Size of hidden layer or latent space dimensions
lambda_val: type=int, default=1, Regularization coefficient, to control the contribution of regularization term in the cost function
initial_learning_rate: type=float, default=0.0001, Initial value of learning rate
iterations: type=int, default=7000, Number of iterations to train the model for
threshold: type=int, default=0.0001, To stop gradient descent after the change in loss function value in consecutive iterations is less than the threshold, implying convergence
# Data
data: type = str, default='blakeley.csv', help = "Dataset to run the script on. In the paper we choose from : ['blakeley.csv', 'jurkat-293T.mat', 'kolodziejczyk.csv', 'PBMC.csv', 'preimplantation.mat', 'quake.csv', 'usoskin.csv', 'zeisel.csv']
# Run the masked matrix recovery test
masked_matrix_test: type = bool, default=False, nargs = '+', help = "Run the masked matrix recovery test?
masking_percentage: type = float, default=10, nargs = '+', help = "Percentage of masking required. Like 10, 20, 12.5 etc
# Model save and restore options
save_model_location: type=str, default='checkpoints/model1.ckpt', Location to save the learnt model
load_model_location: type=str, default='checkpoints/model0.ckpt', Load the saved model from.
log_file: type=str, default='log.txt', text file to save training logs
load_saved: type=bool, default=False, flag to indicate if a saved model will be loaded
# masked and imputed matrix save location / name
imputed_save: type=str, default='imputed_matrix', save the imputed matrix as
masked_save: type=str, default='masked_matrix', save the masked matrix as
"""
# reading dataset
if(type(data) == np.ndarray):
processed_count_matrix = data
elif(type(data) != np.ndarray):
if(type(data) == str & data[-3:-1] == "csv"):
processed_count_matrix = np.loadtxt(data, delimiter=',')
elif(type(data) == str & data[-3:-1] == "mtx"):
processed_count_matrix = scipy.io.mmread(data)
processed_count_matrix = processed_count_matrix.toarray()
processed_count_matrix = np.array(processed_count_matrix)
if(masked_matrix_test):
masking_percentage = masking_percentage/100.0
idxi, idxj = np.nonzero(processed_count_matrix)
ix = np.random.choice(len(idxi), int(np.floor(masking_percentage * len(idxi))), replace = False)
store_for_future = processed_count_matrix[idxi[ix], idxj[ix]]
indices = idxi[ix], idxj[ix]
processed_count_matrix[idxi[ix], idxj[ix]] = 0 # making masks 0
matrix_mask = processed_count_matrix.copy()
matrix_mask[matrix_mask.nonzero()] = 1
mae = []
rmse = []
nmse = []
# finding number of genes and cells.
genes = processed_count_matrix.shape[1]
cells = processed_count_matrix.shape[0]
print(f"[info] Genes : {genes}, Cells : {cells}")
# placeholder definitions
X = tf.placeholder("float32", [None, genes])
mask = tf.placeholder("float32", [None, genes])
matrix_mask = processed_count_matrix.copy()
matrix_mask[matrix_mask.nonzero()] = 1
print(f"[info] Hyper-parameters"
f"\n\t Hidden Units : {hidden_units}"
f"\n\t Lambda : {lambda_val}"
f"\n\t Threshold : {threshold}"
f"\n\t Iterations : {iterations}"
f"\n\t Initial learning rate : {initial_learning_rate}")
# model definition
weights = {
'encoder_h': tf.Variable(tf.random_normal([genes, hidden_units])),
'decoder_h': tf.Variable(tf.random_normal([hidden_units, genes])),
}
biases = {
'encoder_b': tf.Variable(tf.random_normal([hidden_units])),
'decoder_b': tf.Variable(tf.random_normal([genes])),
}
encoder_op = encoder(X)
decoder_op = decoder(encoder_op)
# loss definition
y_pred = decoder_op
y_true = X
rmse_loss = tf.pow(tf.norm(y_true - y_pred * mask), 2)
regularization = tf.multiply(tf.constant(lambda_val/2.0, dtype="float32"), tf.add(tf.pow(tf.norm(weights['decoder_h']), 2), tf.pow(tf.norm(weights['encoder_h']), 2)))
loss = tf.add(tf.reduce_mean(rmse_loss), regularization)
optimizer = tf.train.RMSPropOptimizer(initial_learning_rate).minimize(loss)
init = tf.global_variables_initializer()
saver = tf.train.Saver()
with tf.Session() as sess:
if(load_saved):
saver.restore(sess, load_model_location)
print("[info] model restored.")
else:
sess.run(init)
prev_loss = 0
for k in range(1, iterations+1):
_, loss = sess.run([optimizer, rmse_loss], feed_dict={X: processed_count_matrix, mask: matrix_mask})
lpentry = loss/cells
change = abs(prev_loss - lpentry)
if ( change <= threshold ):
print("Reached the threshold value.")
break
prev_loss = lpentry
if(debug):
if (k - 1) % debug_display_step == 0:
print(f'Step {k} : Total loss: {loss}, Loss per Cell : {lpentry}, Change : {change}')
with open(log_file, 'a') as log:
log.write('{0}\t{1}\t{2}\t{3}\n'.format(
k,
loss,
lpentry,
change
))
# if((k-1) % 5 == 0):
# save_path = saver.save(sess, save_model_location)
imputed_count_matrix = sess.run([y_pred], feed_dict={X: processed_count_matrix, mask: matrix_mask})
if(masked_matrix_test):
predictions = []
for idx, value in enumerate(store_for_future):
prediction = imputed_count_matrix[0][indices[0][idx], indices[1][idx]]
predictions.append(prediction)
else:
predictions = None
return imputed_count_matrix, predictions | 38.668712 | 245 | 0.712201 |
622e6af5c7a24d6c89c506a8003134f044a4178c | 6,358 | py | Python | began/train.py | imironhead/ml_gan | f6c3bbb8de9d487cbf8ff821117768ffed04278e | [
"MIT"
] | 8 | 2017-06-11T05:03:30.000Z | 2019-02-13T14:16:47.000Z | began/train.py | imironhead/ml_gan | f6c3bbb8de9d487cbf8ff821117768ffed04278e | [
"MIT"
] | null | null | null | began/train.py | imironhead/ml_gan | f6c3bbb8de9d487cbf8ff821117768ffed04278e | [
"MIT"
] | null | null | null | """
"""
import began
import glob
import os
import tensorflow as tf
FLAGS = tf.app.flags.FLAGS
def sanity_check():
"""
"""
if not os.path.isdir(FLAGS.portraits_dir_path):
raise Exception('invalid portraits directory')
def build_dataset_reader():
"""
"""
paths_png_wildcards = os.path.join(FLAGS.portraits_dir_path, '*.png')
paths_png = glob.glob(paths_png_wildcards)
file_name_queue = tf.train.string_input_producer(paths_png)
reader = tf.WholeFileReader()
reader_key, reader_val = reader.read(file_name_queue)
image = tf.image.decode_png(reader_val, channels=3, dtype=tf.uint8)
# assume the size of input images are either 128x128x3 or 64x64x3.
if FLAGS.crop_image:
image = tf.image.crop_to_bounding_box(
image,
FLAGS.crop_image_offset_y,
FLAGS.crop_image_offset_x,
FLAGS.crop_image_size_m,
FLAGS.crop_image_size_m)
image = tf.random_crop(
image, size=[FLAGS.crop_image_size_n, FLAGS.crop_image_size_n, 3])
image = tf.image.resize_images(image, [FLAGS.image_size, FLAGS.image_size])
image = tf.image.random_flip_left_right(image)
image = tf.cast(image, dtype=tf.float32) / 127.5 - 1.0
return tf.train.batch(
tensors=[image],
batch_size=FLAGS.batch_size,
capacity=FLAGS.batch_size)
def reshape_batch_images(batch_images):
"""
"""
batch_size = FLAGS.batch_size
image_size = FLAGS.image_size
# build summary for generated fake images.
grid = \
tf.reshape(batch_images, [1, batch_size * image_size, image_size, 3])
grid = tf.split(grid, FLAGS.summary_row_size, axis=1)
grid = tf.concat(grid, axis=2)
grid = tf.saturate_cast(grid * 127.5 + 127.5, tf.uint8)
return grid
def build_summaries(gan):
"""
"""
summaries = {}
# build generator summary
summaries['generator'] = \
tf.summary.scalar('generator loss', gan['generator_loss'])
# build discriminator summaries
d_summaries = []
scalar_table = [
('convergence_measure', 'convergence measure'),
('discriminator_loss', 'discriminator loss'),
('learning_rate', 'learning rate'),
]
for scalar in scalar_table:
d_summaries.append(tf.summary.scalar(scalar[1], gan[scalar[0]]))
summaries['discriminator_part'] = tf.summary.merge(d_summaries)
# build image summaries
image_table = [
('real', 'real image'),
('fake', 'generated image'),
('ae_output_real', 'autoencoder real'),
('ae_output_fake', 'autoencoder fake')
]
for table in image_table:
grid = reshape_batch_images(gan[table[0]])
d_summaries.append(tf.summary.image(table[1], grid, max_outputs=4))
summaries['discriminator_plus'] = tf.summary.merge(d_summaries)
return summaries
def train():
"""
"""
# tensorflow
checkpoint_source_path = tf.train.latest_checkpoint(
FLAGS.checkpoints_dir_path)
checkpoint_target_path = os.path.join(
FLAGS.checkpoints_dir_path, 'model.ckpt')
# the input batch (uniform z) for the generator.
seed = tf.random_uniform(
shape=[FLAGS.batch_size, FLAGS.seed_size], minval=-1.0, maxval=1.0)
# the input batch (real data) for the discriminator.
real = build_dataset_reader()
gan_graph = began.build_began(seed, real)
summaries = build_summaries(gan_graph)
reporter = tf.summary.FileWriter(FLAGS.logs_dir_path)
with tf.Session() as session:
if checkpoint_source_path is None:
session.run(tf.global_variables_initializer())
else:
tf.train.Saver().restore(session, checkpoint_source_path)
# give up overlapped old data
global_step = session.run(gan_graph['global_step'])
reporter.add_session_log(
tf.SessionLog(status=tf.SessionLog.START),
global_step=global_step)
# make dataset reader work
coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(coord=coord)
while True:
# discriminator
fetches = {
'temp_0': gan_graph['next_k'],
'temp_1': gan_graph['discriminator_trainer'],
}
if global_step % 500 == 0:
fetches['summary'] = summaries['discriminator_plus']
else:
fetches['summary'] = summaries['discriminator_part']
fetched = session.run(fetches)
reporter.add_summary(fetched['summary'], global_step)
# generator
fetches = {
'global_step': gan_graph['global_step'],
'temp_0': gan_graph['generator_trainer'],
'summary': summaries['generator'],
}
fetched = session.run(fetches)
global_step = fetched['global_step']
reporter.add_summary(fetched['summary'], global_step)
if global_step % 70000 == 0:
session.run(gan_graph['decay_learning_rate'])
if global_step % 100 == 0:
print('step {}'.format(global_step))
if global_step % 5000 == 0:
tf.train.Saver().save(
session,
checkpoint_target_path,
global_step=gan_graph['global_step'])
coord.request_stop()
coord.join(threads)
def main(_):
"""
"""
began.sanity_check()
sanity_check()
train()
if __name__ == '__main__':
"""
"""
tf.app.flags.DEFINE_string('portraits-dir-path', '', '')
tf.app.flags.DEFINE_string('logs-dir-path', '', '')
tf.app.flags.DEFINE_string('checkpoints-dir-path', '', '')
tf.app.flags.DEFINE_boolean('crop-image', False, '')
tf.app.flags.DEFINE_integer('crop-image-offset-x', 25, '')
tf.app.flags.DEFINE_integer('crop-image-offset-y', 50, '')
tf.app.flags.DEFINE_integer('crop-image-size-m', 128, '')
tf.app.flags.DEFINE_integer('crop-image-size-n', 128, '')
tf.app.flags.DEFINE_integer('summary-row-size', 4, '')
tf.app.flags.DEFINE_integer('summary-col-size', 4, '')
# arXiv:1703.10717
# we typically used a batch size of n = 16.
tf.app.flags.DEFINE_integer('batch-size', 16, '')
tf.app.run()
| 27.764192 | 79 | 0.619063 |
622f35e7c59c0030afa33973573d5f2d9c50a69c | 2,771 | py | Python | custom/abt/reports/tests/test_fixture_utils.py | dimagilg/commcare-hq | ea1786238eae556bb7f1cbd8d2460171af1b619c | [
"BSD-3-Clause"
] | 471 | 2015-01-10T02:55:01.000Z | 2022-03-29T18:07:18.000Z | custom/abt/reports/tests/test_fixture_utils.py | dimagilg/commcare-hq | ea1786238eae556bb7f1cbd8d2460171af1b619c | [
"BSD-3-Clause"
] | 14,354 | 2015-01-01T07:38:23.000Z | 2022-03-31T20:55:14.000Z | custom/abt/reports/tests/test_fixture_utils.py | dimagilg/commcare-hq | ea1786238eae556bb7f1cbd8d2460171af1b619c | [
"BSD-3-Clause"
] | 175 | 2015-01-06T07:16:47.000Z | 2022-03-29T13:27:01.000Z | import doctest
from nose.tools import assert_equal, assert_true
from corehq.apps.fixtures.models import (
FieldList,
FixtureDataItem,
FixtureItemField,
)
from custom.abt.reports import fixture_utils
from custom.abt.reports.fixture_utils import (
dict_values_in,
fixture_data_item_to_dict,
)
| 26.644231 | 59 | 0.512811 |
622f4213fd755d69fc4b1a99782a6a2eaed6ce0c | 1,223 | py | Python | test/test_edit_contact.py | Lenchik13/Testing | fce156bfb639773056745ab1be19a840770739d4 | [
"Apache-2.0"
] | null | null | null | test/test_edit_contact.py | Lenchik13/Testing | fce156bfb639773056745ab1be19a840770739d4 | [
"Apache-2.0"
] | null | null | null | test/test_edit_contact.py | Lenchik13/Testing | fce156bfb639773056745ab1be19a840770739d4 | [
"Apache-2.0"
] | null | null | null | from model.contact import Contact
import random
| 42.172414 | 123 | 0.611611 |
622f91861f9e766601a659b3e6368f910237afb0 | 159 | py | Python | Source Codes Testing/list1.py | urstrulykkr/Python | 098ed5d391f0e62d4950ca80cc57a032c65d1637 | [
"MIT"
] | null | null | null | Source Codes Testing/list1.py | urstrulykkr/Python | 098ed5d391f0e62d4950ca80cc57a032c65d1637 | [
"MIT"
] | null | null | null | Source Codes Testing/list1.py | urstrulykkr/Python | 098ed5d391f0e62d4950ca80cc57a032c65d1637 | [
"MIT"
] | null | null | null | lst1=list()
lst1.append('K')
lst1.append('A')
lst2=['U', 'S', 'H', 'I', 'K']
print(lst1+lst2)
print(lst2[0] +lst2[1]+lst1[1])
for i in lst1+lst2:
print(i)
| 14.454545 | 32 | 0.578616 |
6231b011e60ef30120a9f211ba32d24a861eec6c | 17,825 | py | Python | sintel_GANs/flow_cgan_sintel_ssim_uv.py | tanlinc/opticalFlowGAN | f568e531265029f2f25f223ee92e1f53c0bb52f6 | [
"MIT"
] | 1 | 2018-07-24T05:40:44.000Z | 2018-07-24T05:40:44.000Z | sintel_GANs/flow_cgan_sintel_ssim_uv.py | tanlinc/opticalFlowGAN | f568e531265029f2f25f223ee92e1f53c0bb52f6 | [
"MIT"
] | null | null | null | sintel_GANs/flow_cgan_sintel_ssim_uv.py | tanlinc/opticalFlowGAN | f568e531265029f2f25f223ee92e1f53c0bb52f6 | [
"MIT"
] | null | null | null | import os, sys
sys.path.append(os.getcwd())
import time
import numpy as np
import tensorflow as tf
import tflib as lib
import tflib.ops.linear
import tflib.ops.conv2d
import tflib.ops.batchnorm
import tflib.ops.deconv2d
import tflib.save_images
import tflib.plot
import tflib.flow_handler as fh
import tflib.SINTELdata as sintel
MODE = 'wgan-gp' # Valid options are dcgan, wgan, or wgan-gp
DIM = 64 # This overfits substantially; you're probably better off with 64 # or 128?
LAMBDA = 10 # Gradient penalty lambda hyperparameter
CRITIC_ITERS = 5 # How many critic iterations per generator iteration
BATCH_SIZE = 64 # Batch size
ITERS = 100000 # How many generator iterations to train for # 200000 takes too long
IM_DIM = 32 # number of pixels along x and y (square assumed)
SQUARE_IM_DIM = IM_DIM*IM_DIM # 32*32 = 1024
OUTPUT_DIM = IM_DIM*IM_DIM*3 # Number of pixels (3*32*32) - rgb color
OUTPUT_DIM_FLOW = IM_DIM*IM_DIM*2 # Number of pixels (2*32*32) - uv direction
CONTINUE = False # Default False, set True if restoring from checkpoint
START_ITER = 0 # Default 0, set accordingly if restoring from checkpoint (100, 200, ...)
CURRENT_PATH = "sintel/flowcganuv5"
restore_path = "/home/linkermann/opticalFlow/opticalFlowGAN/results/" + CURRENT_PATH + "/model.ckpt"
lib.print_model_settings(locals().copy())
if(CONTINUE):
tf.reset_default_graph()
cond_data_int = tf.placeholder(tf.int32, shape=[BATCH_SIZE, 2*OUTPUT_DIM]) # cond input for G and D, 2 frames!
cond_data = 2*((tf.cast(cond_data_int, tf.float32)/255.)-.5) #normalized [-1,1]!
#real_data_int = tf.placeholder(tf.int32, shape=[BATCH_SIZE, OUTPUT_DIM_FLOW]) # real data is flow, dim 2!
real_data = tf.placeholder(tf.float32, shape=[BATCH_SIZE, OUTPUT_DIM_FLOW]) #already float, normalized [-1,1]!
fake_data = Generator(BATCH_SIZE, cond_data)
disc_real = Discriminator(real_data, cond_data)
disc_fake = Discriminator(fake_data, cond_data)
gen_params = lib.params_with_name('Generator')
disc_params = lib.params_with_name('Discriminator')
if MODE == 'wgan':
gen_cost = -tf.reduce_mean(disc_fake)
disc_cost = tf.reduce_mean(disc_fake) - tf.reduce_mean(disc_real)
gen_train_op = tf.train.RMSPropOptimizer(learning_rate=5e-5).minimize(gen_cost, var_list=gen_params)
disc_train_op = tf.train.RMSPropOptimizer(learning_rate=5e-5).minimize(disc_cost, var_list=disc_params)
clip_ops = []
for var in disc_params:
clip_bounds = [-.01, .01]
clip_ops.append(
tf.assign(
var,
tf.clip_by_value(var, clip_bounds[0], clip_bounds[1])
)
)
clip_disc_weights = tf.group(*clip_ops)
elif MODE == 'wgan-gp':
# Standard WGAN loss
gen_cost = -tf.reduce_mean(disc_fake)
disc_cost = tf.reduce_mean(disc_fake) - tf.reduce_mean(disc_real)
# Gradient penalty
alpha = tf.random_uniform(
shape=[BATCH_SIZE,1],
minval=0.,
maxval=1.
)
differences = fake_data - real_data
interpolates = real_data + (alpha*differences)
gradients = tf.gradients(Discriminator(interpolates, cond_data), [interpolates])[0] #added cond here
slopes = tf.sqrt(tf.reduce_sum(tf.square(gradients), reduction_indices=[1]))
gradient_penalty = tf.reduce_mean((slopes-1.)**2)
disc_cost += LAMBDA*gradient_penalty
gen_train_op = tf.train.AdamOptimizer(learning_rate=1e-4, beta1=0.5, beta2=0.9).minimize(gen_cost, var_list=gen_params)
disc_train_op = tf.train.AdamOptimizer(learning_rate=1e-4, beta1=0.5, beta2=0.9).minimize(disc_cost, var_list=disc_params)
elif MODE == 'dcgan':
gen_cost = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(disc_fake, tf.ones_like(disc_fake)))
disc_cost = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(disc_fake, tf.zeros_like(disc_fake)))
disc_cost += tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(disc_real, tf.ones_like(disc_real)))
disc_cost /= 2.
gen_train_op = tf.train.AdamOptimizer(learning_rate=2e-4, beta1=0.5).minimize(gen_cost,
var_list=lib.params_with_name('Generator'))
disc_train_op = tf.train.AdamOptimizer(learning_rate=2e-4, beta1=0.5).minimize(disc_cost,
var_list=lib.params_with_name('Discriminator.'))
# Dataset iterators
gen = sintel.load_train_gen(BATCH_SIZE, (IM_DIM,IM_DIM,3), (IM_DIM,IM_DIM,2)) # batch size, im size, im size flow
dev_gen = sintel.load_test_gen(BATCH_SIZE, (IM_DIM,IM_DIM,3), (IM_DIM,IM_DIM,2))
# For generating samples: define fixed noise and conditional input
fixed_cond_samples, fixed_flow_samples = next(gen) # shape: (batchsize, 3072)
fixed_cond_data_int = fixed_cond_samples[:,0:2*OUTPUT_DIM] # earlier frames as condition, cond samples shape (64,3*3072)
fixed_real_data = fixed_flow_samples[:,OUTPUT_DIM_FLOW:] # later flow for discr, flow samples shape (64,2048)
fixed_real_data_norm01 = tf.cast(fixed_real_data+1.0, tf.float32)/2.0 # [0,1]
fixed_cond_data_normalized = 2*((tf.cast(fixed_cond_data_int, tf.float32)/255.)-.5) #normalized [-1,1]!
fixed_viz_data_int = fixed_cond_samples[:,OUTPUT_DIM:2*OUTPUT_DIM] # each later frame for viz
if(CONTINUE):
fixed_noise = tf.get_variable("noise", shape=[BATCH_SIZE, SQUARE_IM_DIM]) # take same noise like saved model
else:
fixed_noise = tf.Variable(tf.random_normal(shape=[BATCH_SIZE, SQUARE_IM_DIM], dtype=tf.float32), name='noise') #variable: saved, for additional channel
fixed_noise_samples = Generator(BATCH_SIZE, fixed_cond_data_normalized, noise=fixed_noise) # Generator(n_samples,conds, noise):
init_op = tf.global_variables_initializer() # op to initialize the variables.
saver = tf.train.Saver() # ops to save and restore all the variables.
# Train loop
with tf.Session() as session:
if(CONTINUE):
# Restore variables from disk.
saver.restore(session, restore_path)
print("Model restored.")
lib.plot.restore(START_ITER) # does not fully work, but makes plots start from newly started iteration
else:
session.run(init_op)
for iteration in range(START_ITER, ITERS): # START_ITER: 0 or from last checkpoint
start_time = time.time()
# Train generator
if iteration > 0:
_data, _ = next(gen) # shape: (batchsize, 6144), double output_dim now # flow as second argument not needed
_cond_data = _data[:, 0:2*OUTPUT_DIM] # earlier frames as conditional data, # flow for disc not needed here
_ = session.run(gen_train_op, feed_dict={cond_data_int: _cond_data})
# Train critic
if MODE == 'dcgan':
disc_iters = 1
else:
disc_iters = CRITIC_ITERS
for i in range(disc_iters):
_data, _flow = next(gen) # shape: (batchsize, 6144), double output_dim now # flow as second argument
_cond_data = _data[:, 0:2*OUTPUT_DIM] # earlier 2 frames as conditional data,
_real_data = _flow[:,OUTPUT_DIM_FLOW:] # later flow as real data for discriminator
_disc_cost, _ = session.run([disc_cost, disc_train_op], feed_dict={real_data: _real_data, cond_data_int: _cond_data})
if MODE == 'wgan':
_ = session.run(clip_disc_weights)
lib.plot.plot('train disc cost', _disc_cost)
lib.plot.plot('time', time.time() - start_time)
# Calculate dev loss and generate samples every 100 iters
if iteration % 100 == 99:
dev_disc_costs = []
_data, _flow = next(gen) # shape: (batchsize, 6144), double output_dim now # flow as second argument
_cond_data = _data[:, 0:2*OUTPUT_DIM] # earlier 2 frames as conditional data
_real_data = _flow[:,OUTPUT_DIM_FLOW:] # later flow as real data for discriminator
_dev_disc_cost = session.run(disc_cost, feed_dict={real_data: _real_data, cond_data_int: _cond_data})
dev_disc_costs.append(_dev_disc_cost)
lib.plot.plot('dev disc cost', np.mean(dev_disc_costs))
generate_image(iteration, _data)
# Save the variables to disk.
save_path = saver.save(session, restore_path)
print("Model saved in path: %s" % save_path)
# chkp.print_tensors_in_checkpoint_file("model.ckpt", tensor_name='', all_tensors=True)
# Save logs every 100 iters
if (iteration < 5) or (iteration % 100 == 99):
lib.plot.flush()
lib.plot.tick()
| 52.272727 | 176 | 0.675792 |
6232533ff943a823cead2f8d5e39f9cced275e1a | 872 | py | Python | Development/Scripts/sobel_edge_regular.py | simonsimon006/tensorflow-wavelets | 21a095bf0048ae2488ca5ae4961d2cbfe94263a9 | [
"MIT"
] | null | null | null | Development/Scripts/sobel_edge_regular.py | simonsimon006/tensorflow-wavelets | 21a095bf0048ae2488ca5ae4961d2cbfe94263a9 | [
"MIT"
] | 1 | 2021-11-11T14:47:43.000Z | 2021-11-11T14:52:51.000Z | Development/Scripts/sobel_edge_regular.py | simonsimon006/tensorflow-wavelets | 21a095bf0048ae2488ca5ae4961d2cbfe94263a9 | [
"MIT"
] | 1 | 2021-11-11T12:18:21.000Z | 2021-11-11T12:18:21.000Z | import cv2
# Read the original image
img = cv2.imread('../input/LennaGrey.png', 1)
# Display original image
cv2.imshow('Original', img)
cv2.waitKey(0)
# Convert to graycsale
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Blur the image for better edge detection
img_blur = cv2.GaussianBlur(img_gray, (3,3), 0)
# Sobel Edge Detection
sobelx = cv2.Sobel(src=img_blur, ddepth=cv2.CV_64F, dx=1, dy=0, ksize=5) # Sobel Edge Detection on the X axis
sobely = cv2.Sobel(src=img_blur, ddepth=cv2.CV_64F, dx=0, dy=1, ksize=5) # Sobel Edge Detection on the Y axis
sobelxy = cv2.Sobel(src=img_blur, ddepth=cv2.CV_64F, dx=1, dy=1, ksize=5) # Combined X and Y Sobel Edge Detection
# Display Sobel Edge Detection Images
cv2.imshow('Sobel X', sobelx)
cv2.waitKey(0)
cv2.imshow('Sobel Y', sobely)
cv2.waitKey(0)
cv2.imshow('Sobel X Y using Sobel() function', sobelxy)
cv2.waitKey(0) | 36.333333 | 113 | 0.738532 |
6232c87d0d4107ba98750270bdd408dd5d0b9dfa | 1,389 | py | Python | src/python/pants/backend/terraform/target_types.py | danxmoran/pants | 7fafd7d789747c9e6a266847a0ccce92c3fa0754 | [
"Apache-2.0"
] | null | null | null | src/python/pants/backend/terraform/target_types.py | danxmoran/pants | 7fafd7d789747c9e6a266847a0ccce92c3fa0754 | [
"Apache-2.0"
] | 22 | 2022-01-27T09:59:50.000Z | 2022-03-30T07:06:49.000Z | src/python/pants/backend/terraform/target_types.py | danxmoran/pants | 7fafd7d789747c9e6a266847a0ccce92c3fa0754 | [
"Apache-2.0"
] | null | null | null | # Copyright 2021 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import annotations
from dataclasses import dataclass
from pants.engine.rules import collect_rules
from pants.engine.target import (
COMMON_TARGET_FIELDS,
Dependencies,
FieldSet,
MultipleSourcesField,
Target,
generate_multiple_sources_field_help_message,
)
from pants.util.strutil import softwrap
def rules():
return collect_rules()
| 26.711538 | 92 | 0.735781 |
623385600c5a7bc996eaff731400e30ab4f95471 | 4,462 | py | Python | src/mdns_client/util.py | bgamari/micropython-mdns | b1a9473cd5200e97ee578be4c623bbd610f46b6c | [
"MIT"
] | 22 | 2021-01-06T02:52:35.000Z | 2022-03-18T00:28:01.000Z | src/mdns_client/util.py | bgamari/micropython-mdns | b1a9473cd5200e97ee578be4c623bbd610f46b6c | [
"MIT"
] | 3 | 2021-04-19T15:44:09.000Z | 2021-08-31T19:17:24.000Z | src/mdns_client/util.py | bgamari/micropython-mdns | b1a9473cd5200e97ee578be4c623bbd610f46b6c | [
"MIT"
] | 5 | 2021-03-10T10:24:46.000Z | 2021-10-11T15:57:24.000Z | import struct
import uasyncio
from mdns_client.constants import REPEAT_TYPE_FLAG, TYPE_CNAME, TYPE_MX, TYPE_NS, TYPE_PTR, TYPE_SOA, TYPE_SRV
def dotted_ip_to_bytes(ip: str) -> bytes:
"""
Convert a dotted IPv4 address string into four bytes, with
some sanity checks
"""
ip_ints = [int(i) for i in ip.split(".")]
if len(ip_ints) != 4 or any(i < 0 or i > 255 for i in ip_ints):
raise ValueError
return bytes(ip_ints)
def bytes_to_dotted_ip(a: "Iterable[int]") -> str:
"""
Convert four bytes into a dotted IPv4 address string, without any
sanity checks
"""
return ".".join(str(i) for i in a)
def check_name(n: str) -> "List[bytes]":
"""
Ensure that a name is in the form of a list of encoded blocks of
bytes, typically starting as a qualified domain name
"""
if isinstance(n, str):
n = n.split(".")
if n[-1] == "":
n = n[:-1]
n = [i.encode("UTF8") if isinstance(i, str) else i for i in n]
return n
def pack_name(buffer: bytes, string: "List[bytes]") -> None:
"""
Pack a string into the start of the buffer
We don't support writing with name compression, BIWIOMS
"""
output_index = 0
for part in string:
part_length = len(part)
buffer[output_index] = part_length
after_size_next_index = output_index + 1
end_of_pack_name_index = after_size_next_index + part_length
buffer[after_size_next_index:end_of_pack_name_index] = part
output_index += part_length + 1
buffer[output_index] = 0
def end_index_of_name(buffer: bytes, offset: int) -> int:
"""
Expects the offset to be in the beginning of a name and
scans through the buffer. It returns the last index of the
string representation.
"""
while offset < len(buffer):
string_part_length = buffer[offset]
if string_part_length & REPEAT_TYPE_FLAG == REPEAT_TYPE_FLAG:
# Repeat type flags are always at the end. Meaning the reference
# should be dereferenced and then the name is completed
return offset + 2
elif string_part_length == 0x00:
return offset + 1
offset += string_part_length
raise IndexError("Could not idenitfy end of index")
| 29.163399 | 110 | 0.64814 |
6235e26627f5dd8b3c591b34af122e6dd4fe2d7f | 1,029 | py | Python | algorithms/selection_sort.py | maneeshd/Algorithms-and-DataStructures | 5c50de586657f0135edaa2e624dfe2648c9c4eef | [
"MIT"
] | null | null | null | algorithms/selection_sort.py | maneeshd/Algorithms-and-DataStructures | 5c50de586657f0135edaa2e624dfe2648c9c4eef | [
"MIT"
] | null | null | null | algorithms/selection_sort.py | maneeshd/Algorithms-and-DataStructures | 5c50de586657f0135edaa2e624dfe2648c9c4eef | [
"MIT"
] | null | null | null | """
@author: Maneesh D
@date: 11-Jul-17
@intepreter: Python 3.6
Worst Case Analysis: Selection Sort -> O(n^2)
"""
from timeit import Timer, default_timer
from random import shuffle
ARR = list()
def selection_sort(data):
"""Selection sort implementation"""
for i in range(len(data)):
min_pos = i
for j in range(i + 1, len(data)):
if data[j] < data[min_pos]:
min_pos = j
data[i], data[min_pos] = data[min_pos], data[i]
def main():
"""Main Driver Function"""
start = default_timer()
shuffle(ARR)
print("Input Array:", ARR)
selection_sort(ARR)
print("Sorted Array:", ARR)
print("Sorting Time: %f Seconds\n" % (default_timer() - start))
if __name__ == "__main__":
print("Selection Sort")
print("-" * len("Selection Sort"))
ARR = list(range(25, 0, -1)) # Worst Case Input(Reverse Sorted)
t = Timer(main)
print(
"\nAverage sorting time for 25 elements in 3 runs = %f Seconds"
% (t.timeit(3) / 3)
)
| 23.386364 | 71 | 0.595724 |
623654c971708305dfa901f1772fac7478631021 | 917 | py | Python | image_repo/migrations/0002_auto_20210505_1448.py | elena-kolomeets/Django-Repo | f326b058dc70562a6815248df1b7550c0b634a73 | [
"MIT"
] | null | null | null | image_repo/migrations/0002_auto_20210505_1448.py | elena-kolomeets/Django-Repo | f326b058dc70562a6815248df1b7550c0b634a73 | [
"MIT"
] | null | null | null | image_repo/migrations/0002_auto_20210505_1448.py | elena-kolomeets/Django-Repo | f326b058dc70562a6815248df1b7550c0b634a73 | [
"MIT"
] | null | null | null | # Generated by Django 3.2 on 2021-05-05 12:48
from django.db import migrations, models
| 26.970588 | 75 | 0.555071 |
6236a853e217ec41f065c4c8899eb05e1e528ac1 | 21,375 | py | Python | ToricLearning/ising.py | danielfreeman11/thermal-toric-code | 3718f1b16737dfae09443466f6cfb65036faaa89 | [
"MIT"
] | 6 | 2017-11-15T00:54:13.000Z | 2021-11-21T02:08:21.000Z | ToricLearning/ising.py | danielfreeman11/thermal-toric-code | 3718f1b16737dfae09443466f6cfb65036faaa89 | [
"MIT"
] | null | null | null | ToricLearning/ising.py | danielfreeman11/thermal-toric-code | 3718f1b16737dfae09443466f6cfb65036faaa89 | [
"MIT"
] | null | null | null | """
Ising model one-shot dynamics simulation.
From C. Daniel Freeman (2016 http://arxiv.org/abs/1603.05005)
"""
import logging
import math
import gym
from gym import spaces
from gym.utils import seeding
import numpy as np
#import isingutils.py
import random
from random import choice
import copy
import sys
from compiler.ast import flatten
from numpy import *
logger = logging.getLogger(__name__)
| 34.364952 | 215 | 0.705076 |
62379999fae8c7604ac402164b9ffd7d1051d067 | 41,940 | py | Python | pkg/vtreat/vtreat_impl.py | sthagen/pyvtreat | 01cd9a70a6e1af779057fea90a9a43c2822cceb2 | [
"BSD-3-Clause"
] | 1 | 2019-12-23T19:53:27.000Z | 2019-12-23T19:53:27.000Z | pkg/vtreat/vtreat_impl.py | sthagen/pyvtreat | 01cd9a70a6e1af779057fea90a9a43c2822cceb2 | [
"BSD-3-Clause"
] | null | null | null | pkg/vtreat/vtreat_impl.py | sthagen/pyvtreat | 01cd9a70a6e1af779057fea90a9a43c2822cceb2 | [
"BSD-3-Clause"
] | null | null | null | # -*- coding: utf-8 -*-
"""
Created on Sat Jul 20 12:07:57 2019
@author: johnmount
"""
from abc import ABC
import math
import pprint
import warnings
import numpy
import pandas
import vtreat.util
import vtreat.transform
def fit_clean_code(*, incoming_column_name, x, params, imputation_map):
if not vtreat.util.numeric_has_range(x):
return None
replacement = params['missingness_imputation']
try:
replacement = imputation_map[incoming_column_name]
except KeyError:
pass
if vtreat.util.can_convert_v_to_numeric(replacement):
replacement_value = 0.0 + replacement
elif callable(replacement):
replacement_value = vtreat.util.summarize_column(x, fn=replacement)
else:
raise TypeError("unexpected imputation type " + str(type(replacement)) + " (" + incoming_column_name + ")")
if pandas.isnull(replacement_value) or math.isnan(replacement_value) or math.isinf(replacement_value):
raise ValueError("replacement was bad " + incoming_column_name + ": " + str(replacement_value))
return CleanNumericTransform(
incoming_column_name=incoming_column_name, replacement_value=replacement_value
)
def fit_regression_impact_code(*, incoming_column_name, x, y, extra_args, params):
sf = vtreat.util.grouped_by_x_statistics(x, y)
if sf.shape[0] <= 1:
return None
if params["use_hierarchical_estimate"]:
sf["_impact_code"] = sf["_hest"] - sf["_gm"]
else:
sf["_impact_code"] = sf["_group_mean"] - sf["_gm"]
sf = sf.loc[:, ["x", "_impact_code"]].copy()
newcol = incoming_column_name + "_impact_code"
sf.columns = [incoming_column_name, newcol]
return YAwareMappedCodeTransform(
incoming_column_name=incoming_column_name,
derived_column_name=newcol,
treatment="impact_code",
code_book=sf,
refitter=fit_regression_impact_code,
extra_args=extra_args,
params=params,
)
def fit_regression_deviation_code(*, incoming_column_name, x, y, extra_args, params):
sf = vtreat.util.grouped_by_x_statistics(x, y)
if sf.shape[0] <= 1:
return None
sf["_deviation_code"] = numpy.sqrt(sf["_var"])
sf = sf.loc[:, ["x", "_deviation_code"]].copy()
newcol = incoming_column_name + "_deviation_code"
sf.columns = [incoming_column_name, newcol]
return YAwareMappedCodeTransform(
incoming_column_name=incoming_column_name,
derived_column_name=newcol,
treatment="deviation_code",
code_book=sf,
refitter=fit_regression_deviation_code,
extra_args=extra_args,
params=params,
)
def fit_binomial_impact_code(*, incoming_column_name, x, y, extra_args, params):
outcome_target = (extra_args["outcome_target"],)
var_suffix = extra_args["var_suffix"]
y = numpy.asarray(numpy.asarray(y) == outcome_target, dtype=float)
sf = vtreat.util.grouped_by_x_statistics(x, y)
if sf.shape[0] <= 1:
return None
eps = 1.0e-3
if params["use_hierarchical_estimate"]:
sf["_logit_code"] = numpy.log((sf["_hest"] + eps) / (sf["_gm"] + eps))
else:
sf["_logit_code"] = numpy.log((sf["_group_mean"] + eps) / (sf["_gm"] + eps))
sf = sf.loc[:, ["x", "_logit_code"]].copy()
newcol = incoming_column_name + "_logit_code" + var_suffix
sf.columns = [incoming_column_name, newcol]
return YAwareMappedCodeTransform(
incoming_column_name=incoming_column_name,
derived_column_name=newcol,
treatment="logit_code",
code_book=sf,
refitter=fit_binomial_impact_code,
extra_args=extra_args,
params=params,
)
# noinspection PyPep8Naming
# noinspection PyPep8Naming
# noinspection PyPep8Naming
# noinspection PyPep8Naming
def pre_prep_frame(x, *, col_list, cols_to_copy):
"""Create a copy of pandas.DataFrame x restricted to col_list union cols_to_copy with col_list - cols_to_copy
converted to only string and numeric types. New pandas.DataFrame has trivial indexing. If col_list
is empty it is interpreted as all columns."""
if cols_to_copy is None:
cols_to_copy = []
if (col_list is None) or (len(col_list) <= 0):
col_list = [co for co in x.columns]
x_set = set(x.columns)
col_set = set(col_list)
for ci in cols_to_copy:
if (ci in x_set) and (ci not in col_set):
col_list = col_list + [ci]
col_set = set(col_list)
missing_cols = col_set - x_set
if len(missing_cols) > 0:
raise KeyError("referred to not-present columns " + str(missing_cols))
cset = set(cols_to_copy)
if len(col_list) <= 0:
raise ValueError("no variables")
x = x.loc[:, col_list]
x = x.reset_index(inplace=False, drop=True)
for c in x.columns:
if c in cset:
continue
bad_ind = vtreat.util.is_bad(x[c])
if vtreat.util.can_convert_v_to_numeric(x[c]):
x[c] = vtreat.util.safe_to_numeric_array(x[c])
else:
# https://stackoverflow.com/questions/22231592/pandas-change-data-type-of-series-to-string
x[c] = numpy.asarray(x[c].apply(str), dtype=str)
x.loc[bad_ind, c] = numpy.nan
return x
# val_list is a list single column Pandas data frames
# assumes each y-aware variable produces one derived column
# also clears out refitter_ values to None
| 38.869323 | 115 | 0.612375 |
62383bc8933f1f4eaa948064e8b702400552ae83 | 428 | py | Python | resqs/core/urls.py | UMass-Rescue/moto | 3aa52aca28c622be9708da5fd31a8c8b92801634 | [
"Apache-2.0"
] | null | null | null | resqs/core/urls.py | UMass-Rescue/moto | 3aa52aca28c622be9708da5fd31a8c8b92801634 | [
"Apache-2.0"
] | null | null | null | resqs/core/urls.py | UMass-Rescue/moto | 3aa52aca28c622be9708da5fd31a8c8b92801634 | [
"Apache-2.0"
] | null | null | null | from __future__ import unicode_literals
from .responses import MotoAPIResponse
url_bases = ["https?://motoapi.amazonaws.com"]
response_instance = MotoAPIResponse()
url_paths = {
"{0}/resqs-api/$": response_instance.dashboard,
"{0}/resqs-api/data.json": response_instance.model_data,
"{0}/resqs-api/reset": response_instance.reset_response,
"{0}/resqs-api/reset-auth": response_instance.reset_auth_response,
}
| 30.571429 | 70 | 0.752336 |
6238442b97ca6a6ef8a0ad9749bdaae56317f29d | 1,305 | py | Python | hammer/tracker.py | mizerlou/hammer | 353f176bffff4a6b7726361cdafb986fe2302f19 | [
"Apache-2.0"
] | 1 | 2016-06-06T20:22:13.000Z | 2016-06-06T20:22:13.000Z | hammer/tracker.py | mizerlou/hammer | 353f176bffff4a6b7726361cdafb986fe2302f19 | [
"Apache-2.0"
] | null | null | null | hammer/tracker.py | mizerlou/hammer | 353f176bffff4a6b7726361cdafb986fe2302f19 | [
"Apache-2.0"
] | null | null | null | import anydbm, os.path, time, bsddb, sys
| 27.1875 | 68 | 0.514943 |
623beafade5cf281facce9b0ef0d77606bd2dfcb | 1,353 | py | Python | code/glove_bot.py | AmanPriyanshu/Bavardez | 221980add10a8bea69db4d3357660d27a8d6cdb3 | [
"MIT"
] | 1 | 2021-12-28T13:16:17.000Z | 2021-12-28T13:16:17.000Z | glove_bot.py | AmanPriyanshu/Bavardez | 221980add10a8bea69db4d3357660d27a8d6cdb3 | [
"MIT"
] | null | null | null | glove_bot.py | AmanPriyanshu/Bavardez | 221980add10a8bea69db4d3357660d27a8d6cdb3 | [
"MIT"
] | null | null | null | import random
import torch
import pandas as pd
import numpy as np
from glove_model import get_model
from intent_initializer import read_all_intents, read_all_responses
from GloVe_helper import GloVeLoader
PATH = './config/'
BOT_NAME = 'Bavardez'
if __name__ == '__main__':
main() | 27.06 | 107 | 0.725795 |
623c5e03f30d1e94a196a72edaa4010032eb29e4 | 984 | py | Python | tests/coworks/biz/test_biz_ms.py | sidneyarcidiacono/coworks | 7f51b83e8699ced991d16a5a43ad19e569b6e814 | [
"MIT"
] | null | null | null | tests/coworks/biz/test_biz_ms.py | sidneyarcidiacono/coworks | 7f51b83e8699ced991d16a5a43ad19e569b6e814 | [
"MIT"
] | null | null | null | tests/coworks/biz/test_biz_ms.py | sidneyarcidiacono/coworks | 7f51b83e8699ced991d16a5a43ad19e569b6e814 | [
"MIT"
] | null | null | null | import pytest
import requests
from tests.coworks.biz.biz_ms import BizMS
from tests.coworks.tech.test_ms import SimpleMS
| 30.75 | 85 | 0.642276 |
623d0484a6ad38e8b613031601faa989033dfbd4 | 1,030 | py | Python | d3rlpy/iterators/random_iterator.py | YangRui2015/d3rlpy | da778b2a2b0afbafe25395296baecd0d4d0cd0d5 | [
"MIT"
] | 1 | 2021-05-08T06:21:05.000Z | 2021-05-08T06:21:05.000Z | d3rlpy/iterators/random_iterator.py | YangRui2015/d3rlpy | da778b2a2b0afbafe25395296baecd0d4d0cd0d5 | [
"MIT"
] | null | null | null | d3rlpy/iterators/random_iterator.py | YangRui2015/d3rlpy | da778b2a2b0afbafe25395296baecd0d4d0cd0d5 | [
"MIT"
] | null | null | null | from typing import List, cast
import numpy as np
from ..dataset import Episode, Transition
from .base import TransitionIterator
| 26.410256 | 76 | 0.635922 |
623e6cd0ebfab7a2fa9506ea275e7ff09e80964a | 420 | py | Python | src/logger.py | Electronya/rc-mission-operator | 2e1571a68df9df82629ebc4eebb248c055fe6066 | [
"MIT"
] | null | null | null | src/logger.py | Electronya/rc-mission-operator | 2e1571a68df9df82629ebc4eebb248c055fe6066 | [
"MIT"
] | 8 | 2021-09-02T23:58:28.000Z | 2021-11-20T22:49:16.000Z | src/logger.py | Electronya/rc-mission-operator | 2e1571a68df9df82629ebc4eebb248c055fe6066 | [
"MIT"
] | null | null | null | import logging
import os
def initLogger() -> object:
"""
Initialize the logger.
"""
logger_level = logging.INFO
if 'APP_ENV' in os.environ:
if os.environ['APP_ENV'] == 'dev':
logger_level = logging.DEBUG
logging.basicConfig(level=logger_level,
format='%(asctime)s %(levelname)s:'
'%(name)s:%(message)s')
return logging
| 21 | 59 | 0.552381 |
623f19da861cce44fb9bf0964c673c92b5ac9b2f | 713 | py | Python | learn_big_data_on_aws/config.py | MacHu-GWU/learn_big_data_on_aws-project | 0db78c35a1712fdd905763fd299663982e44601c | [
"MIT"
] | null | null | null | learn_big_data_on_aws/config.py | MacHu-GWU/learn_big_data_on_aws-project | 0db78c35a1712fdd905763fd299663982e44601c | [
"MIT"
] | null | null | null | learn_big_data_on_aws/config.py | MacHu-GWU/learn_big_data_on_aws-project | 0db78c35a1712fdd905763fd299663982e44601c | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
from s3pathlib import S3Path
config = Config()
| 24.586207 | 67 | 0.695652 |
623f3e0f81181826dc28972fa527ecf69b25e1f9 | 15,091 | py | Python | tests/test_plotter_utils.py | natter1/GEDFReader | 360454c80d7aef375d3d5a825e51073ab8bc3d98 | [
"MIT"
] | null | null | null | tests/test_plotter_utils.py | natter1/GEDFReader | 360454c80d7aef375d3d5a825e51073ab8bc3d98 | [
"MIT"
] | 2 | 2021-05-03T22:04:17.000Z | 2021-05-04T10:33:32.000Z | tests/test_plotter_utils.py | natter1/gdef_reader | 360454c80d7aef375d3d5a825e51073ab8bc3d98 | [
"MIT"
] | null | null | null | """
This file contains tests for plotter_utils.py.
@author: Nathanael Jhrmann
"""
import matplotlib.pyplot as plt
import numpy as np
import pytest
from matplotlib.figure import Figure
from gdef_reporter.plotter_styles import get_plotter_style_histogram
from gdef_reporter.plotter_utils import plot_to_ax, create_plot, plot_z_histogram_to_ax, create_z_histogram_plot, \
_extract_ndarray_and_pixel_width, save_figure, create_rms_plot, create_rms_with_error_plot, create_summary_plot
from tests.conftest import AUTO_SHOW
ORIGINAL_FIGURE_SIZE = (4, 3.5)
ORIGINAL_DPI = 300
# tests for functions to plot a 2D area map
| 49.316993 | 120 | 0.673514 |
62407f44181f5ecd79d5e3e000c96c7ee62ec644 | 3,590 | py | Python | eahub/profiles/tests/test_tags_api.py | walambert/eahub.org | 21b6111b2626e4739c249d0881d16fbc818094cb | [
"MIT"
] | 36 | 2019-02-22T23:07:14.000Z | 2022-02-10T13:24:27.000Z | eahub/profiles/tests/test_tags_api.py | walambert/eahub.org | 21b6111b2626e4739c249d0881d16fbc818094cb | [
"MIT"
] | 717 | 2019-02-21T22:07:55.000Z | 2022-02-26T15:17:49.000Z | eahub/profiles/tests/test_tags_api.py | walambert/eahub.org | 21b6111b2626e4739c249d0881d16fbc818094cb | [
"MIT"
] | 19 | 2019-04-14T14:37:56.000Z | 2022-02-14T22:05:16.000Z | from typing import Tuple
from rest_framework.test import APITestCase
from eahub.profiles.models import Profile, ProfileTag, ProfileTagTypeEnum
from eahub.tests.cases import EAHubTestCase
| 40.795455 | 77 | 0.659331 |
62416172cffe17c94f2ee1ae5b11d654511779a9 | 279 | py | Python | Task1/chapter14.py | shkhaider2015/AI_Lab_Task | 642a0d5e30515dac6972da194741b829cdc63f30 | [
"Unlicense"
] | null | null | null | Task1/chapter14.py | shkhaider2015/AI_Lab_Task | 642a0d5e30515dac6972da194741b829cdc63f30 | [
"Unlicense"
] | null | null | null | Task1/chapter14.py | shkhaider2015/AI_Lab_Task | 642a0d5e30515dac6972da194741b829cdc63f30 | [
"Unlicense"
] | null | null | null | # addition will takes place after multiplication and addition
num1 = 1 + 4 * 3 / 2;
# same as 5 * 3 /2
num2 = (1 + 4) * 3 / 2;
# same as 1+12/2
num3 = 1 + (4 * 3) / 2;
print("python follow precedence rules");
# this should produce 7.5
print(num1);
print(num2);
print(num3); | 18.6 | 61 | 0.620072 |
6242dfa1c761870f2a85f43957247c13b7b53277 | 173 | py | Python | cosypose/simulator/__init__.py | ompugao/cosypose | 4e471c16f19d5ee632668cd52eaa57b562f287d6 | [
"MIT"
] | 202 | 2020-08-19T19:28:03.000Z | 2022-03-29T07:10:47.000Z | cosypose/simulator/__init__.py | ompugao/cosypose | 4e471c16f19d5ee632668cd52eaa57b562f287d6 | [
"MIT"
] | 66 | 2020-08-24T09:28:05.000Z | 2022-03-31T07:11:06.000Z | cosypose/simulator/__init__.py | ompugao/cosypose | 4e471c16f19d5ee632668cd52eaa57b562f287d6 | [
"MIT"
] | 66 | 2020-08-19T19:28:05.000Z | 2022-03-18T20:47:55.000Z | from .body import Body
from .camera import Camera
from .base_scene import BaseScene
from .caching import BodyCache, TextureCache
from .textures import apply_random_textures
| 28.833333 | 44 | 0.843931 |
62434c56ee7f47b918c8fe7743e7266baa6b6971 | 2,186 | py | Python | python/scorecard/Config.py | opme/SurgeonScorecard | 788f63fd4f906b27435d18565675553c7b738830 | [
"Apache-2.0"
] | 6 | 2016-11-25T02:01:54.000Z | 2021-08-01T21:54:46.000Z | python/scorecard/Config.py | opme/SurgeonScorecard | 788f63fd4f906b27435d18565675553c7b738830 | [
"Apache-2.0"
] | null | null | null | python/scorecard/Config.py | opme/SurgeonScorecard | 788f63fd4f906b27435d18565675553c7b738830 | [
"Apache-2.0"
] | 2 | 2018-02-20T15:13:25.000Z | 2020-02-16T07:56:06.000Z | import os
import sys
import configparser
| 39.745455 | 96 | 0.515554 |
624457e04a90c3819a6cdb9b28bb79d1ea2ace26 | 726 | py | Python | message_passing_nn/utils/loss_function/loss_functions.py | mathisi-ai/message-passing-neural-network | d6e27fcf05d06268a461e5f9d9cf81b7e3a5dc09 | [
"MIT"
] | null | null | null | message_passing_nn/utils/loss_function/loss_functions.py | mathisi-ai/message-passing-neural-network | d6e27fcf05d06268a461e5f9d9cf81b7e3a5dc09 | [
"MIT"
] | 1 | 2020-12-13T10:37:03.000Z | 2020-12-13T10:37:03.000Z | message_passing_nn/utils/loss_function/loss_functions.py | mathisi-ai/message-passing-neural-network | d6e27fcf05d06268a461e5f9d9cf81b7e3a5dc09 | [
"MIT"
] | null | null | null | from torch import nn
loss_functions = {
"MSE": nn.MSELoss,
"MSEPenalty": nn.MSELoss,
"L1": nn.L1Loss,
"CrossEntropy": nn.CrossEntropyLoss,
"CTC": nn.CTCLoss,
"NLL": nn.NLLLoss,
"PoissonNLL": nn.PoissonNLLLoss,
"KLDiv": nn.KLDivLoss,
"BCE": nn.BCELoss,
"BCEWithLogits": nn.BCEWithLogitsLoss,
"MarginRanking": nn.MarginRankingLoss,
"HingeEmbedding": nn.HingeEmbeddingLoss,
"MultiLabelMargin": nn.MultiLabelMarginLoss,
"SmoothL1": nn.SmoothL1Loss,
"SoftMargin": nn.SoftMarginLoss,
"MultiLabelSoftMargin": nn.MultiLabelSoftMarginLoss,
"CosineEmbedding": nn.CosineEmbeddingLoss,
"MultiMargin": nn.MultiMarginLoss,
"TripletMargin": nn.TripletMarginLoss
}
| 30.25 | 56 | 0.69697 |
6244eae08f282f33089c904acc046111406cab02 | 234 | py | Python | ex15.py | phyupyarko/python-exercises | f231ca8c8c1f2614bb166cc72ce45860eff88c1d | [
"MIT"
] | null | null | null | ex15.py | phyupyarko/python-exercises | f231ca8c8c1f2614bb166cc72ce45860eff88c1d | [
"MIT"
] | null | null | null | ex15.py | phyupyarko/python-exercises | f231ca8c8c1f2614bb166cc72ce45860eff88c1d | [
"MIT"
] | null | null | null | from sys import argv
script, filename=argv
txt = open(filename)
print(f"Here's your file {filename}:")
print(txt.read())
print("Type the filename again:")
file_again = input("> ")
txt_again = open (file_again)
print(txt_again.read())
| 23.4 | 38 | 0.726496 |
624637a865a05ff1c7e0a5862f34089e64e6bb76 | 4,042 | py | Python | samples/vsphere/vcenter/setup/datacenter.py | restapicoding/VMware-SDK | edc387a76227be1ad7c03e5eeaf603351574f70c | [
"MIT"
] | 589 | 2017-03-09T19:01:22.000Z | 2022-03-23T08:18:32.000Z | samples/vsphere/vcenter/setup/datacenter.py | restapicoding/VMware-SDK | edc387a76227be1ad7c03e5eeaf603351574f70c | [
"MIT"
] | 244 | 2017-03-09T19:37:36.000Z | 2022-03-29T07:14:21.000Z | samples/vsphere/vcenter/setup/datacenter.py | restapicoding/VMware-SDK | edc387a76227be1ad7c03e5eeaf603351574f70c | [
"MIT"
] | 304 | 2017-03-09T19:15:01.000Z | 2022-03-31T04:26:59.000Z | """
* *******************************************************
* Copyright (c) VMware, Inc. 2016-2018. All Rights Reserved.
* SPDX-License-Identifier: MIT
* *******************************************************
*
* DISCLAIMER. THIS PROGRAM IS PROVIDED TO YOU "AS IS" WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, WHETHER ORAL OR WRITTEN,
* EXPRESS OR IMPLIED. THE AUTHOR SPECIFICALLY DISCLAIMS ANY IMPLIED
* WARRANTIES OR CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY,
* NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE.
"""
__author__ = 'VMware, Inc.'
from com.vmware.vcenter_client import (Datacenter, Folder)
def detect_datacenter(context, datacenter_name):
"""Find the datacenter with the given name"""
names = set([datacenter_name])
datacenter_summaries = context.client.vcenter.Datacenter.list(
Datacenter.FilterSpec(names=names))
if len(datacenter_summaries) > 0:
datacenter = datacenter_summaries[0].datacenter
print("Detected Datacenter '{}' as {}".
format(datacenter_name, datacenter))
context.testbed.entities['DATACENTER_IDS'][datacenter_name] = datacenter
return True
else:
print("Datacenter '{}' missing".format(datacenter_name))
return False
def detect_datacenters(context):
"""Find datacenters to run the vcenter samples"""
context.testbed.entities['DATACENTER_IDS'] = {}
# Look for the two datacenters
datacenter1_name = context.testbed.config['DATACENTER1_NAME']
datacenter2_name = context.testbed.config['DATACENTER2_NAME']
return (detect_datacenter(context, datacenter1_name) and
detect_datacenter(context, datacenter2_name))
def cleanup_datacenters(context):
"""Cleanup datacenters after sample run"""
# Look for the two datacenters
datacenter1_name = context.testbed.config['DATACENTER1_NAME']
datacenter2_name = context.testbed.config['DATACENTER2_NAME']
names = set([datacenter1_name, datacenter2_name])
datacenter_summaries = context.client.vcenter.Datacenter.list(
Datacenter.FilterSpec(names=names))
print("Found {} Datacenters matching names {}".
format(len(datacenter_summaries), ", ".
join(["'{}'".format(n) for n in names])))
for datacenter_summary in datacenter_summaries:
datacenter = datacenter_summary.datacenter
print("Deleting Datacenter '{}' ({})".
format(datacenter, datacenter_summary.name))
context.client.vcenter.Datacenter.delete(datacenter, force=True)
def setup_datacenters(context):
"""Create datacenters for running vcenter samples"""
# Find a Folder in which to put the Datacenters
folder_summaries = folder_list_datacenter_folder(context)
folder = folder_summaries[0].folder
print("Creating datacenters in Folder '{}' ({})".
format(folder, folder_summaries[0].name))
# Create first datacenter
datacenter1_name = context.testbed.config['DATACENTER1_NAME']
datacenter1 = context.client.vcenter.Datacenter.create(
Datacenter.CreateSpec(name=datacenter1_name, folder=folder)
)
print("Created Datacenter '{}' ({})".format(datacenter1, datacenter1_name))
# Create second datacenter
datacenter2_name = context.testbed.config['DATACENTER2_NAME']
datacenter2 = context.client.vcenter.Datacenter.create(
Datacenter.CreateSpec(name=datacenter2_name, folder=folder)
)
print("Created Datacenter '{}' ({})".format(datacenter2, datacenter2_name))
# Save datacenter name to identifier mappings for later use
context.testbed.entities['DATACENTER_IDS'] = {
datacenter1_name: datacenter1,
datacenter2_name: datacenter2
}
| 36.414414 | 93 | 0.700643 |
6247004e81f0b5ed0a8cf58645c7483019728044 | 2,622 | py | Python | chesstab/samples/chessboard.py | RogerMarsh/chesstab | 01d375dc6bf025b621612a84513e55c4640a78ad | [
"BSD-3-Clause"
] | null | null | null | chesstab/samples/chessboard.py | RogerMarsh/chesstab | 01d375dc6bf025b621612a84513e55c4640a78ad | [
"BSD-3-Clause"
] | null | null | null | chesstab/samples/chessboard.py | RogerMarsh/chesstab | 01d375dc6bf025b621612a84513e55c4640a78ad | [
"BSD-3-Clause"
] | null | null | null | # chessboard.py
# Copyright 2008 Roger Marsh
# Licence: See LICENCE (BSD licence)
"""Demonstrate chess board class and methods to draw position on board."""
if __name__ == "__main__":
import tkinter
from pgn_read.core.piece import Piece
from pgn_read.core.constants import (
FEN_WHITE_KING,
FEN_WHITE_QUEEN,
FEN_WHITE_ROOK,
FEN_WHITE_BISHOP,
FEN_WHITE_KNIGHT,
FEN_WHITE_PAWN,
FEN_BLACK_KING,
FEN_BLACK_QUEEN,
FEN_BLACK_ROOK,
FEN_BLACK_BISHOP,
FEN_BLACK_KNIGHT,
FEN_BLACK_PAWN,
)
from ..gui import fonts
from ..gui.board import Board
from ..core.constants import NOPIECE
root = tkinter.Tk()
root.wm_title("Demonstrate Board")
f = fonts.make_chess_fonts(root, preferred_pieces=("Chess Lucena",))
b = Board(root, boardborder=10)
del f
b.get_top_widget().pack(fill=tkinter.BOTH, expand=tkinter.TRUE)
b.get_top_widget().pack_propagate(False)
b.set_board(
{
"a8": Piece(FEN_BLACK_ROOK, "a8"),
"b8": Piece(FEN_BLACK_KNIGHT, "b8"),
"c8": Piece(FEN_BLACK_BISHOP, "c8"),
"d8": Piece(FEN_BLACK_QUEEN, "d8"),
"e8": Piece(FEN_BLACK_KING, "e8"),
"f8": Piece(FEN_BLACK_BISHOP, "f8"),
"g8": Piece(FEN_BLACK_KNIGHT, "g8"),
"h8": Piece(FEN_BLACK_ROOK, "h8"),
"a7": Piece(FEN_BLACK_PAWN, "a7"),
"b7": Piece(FEN_BLACK_PAWN, "b7"),
"c7": Piece(FEN_BLACK_PAWN, "c7"),
"d7": Piece(FEN_BLACK_PAWN, "d7"),
"e7": Piece(FEN_BLACK_PAWN, "e7"),
"f7": Piece(FEN_BLACK_PAWN, "f7"),
"g7": Piece(FEN_BLACK_PAWN, "g7"),
"h7": Piece(FEN_BLACK_PAWN, "h7"),
"a2": Piece(FEN_WHITE_PAWN, "a2"),
"b2": Piece(FEN_WHITE_PAWN, "b2"),
"c2": Piece(FEN_WHITE_PAWN, "c2"),
"d2": Piece(FEN_WHITE_PAWN, "d2"),
"e2": Piece(FEN_WHITE_PAWN, "e2"),
"f2": Piece(FEN_WHITE_PAWN, "f2"),
"g2": Piece(FEN_WHITE_PAWN, "g2"),
"h2": Piece(FEN_WHITE_PAWN, "h2"),
"a1": Piece(FEN_WHITE_ROOK, "a1"),
"b1": Piece(FEN_WHITE_KNIGHT, "b1"),
"c1": Piece(FEN_WHITE_BISHOP, "c1"),
"d1": Piece(FEN_WHITE_QUEEN, "d1"),
"e1": Piece(FEN_WHITE_KING, "e1"),
"f1": Piece(FEN_WHITE_BISHOP, "f1"),
"g1": Piece(FEN_WHITE_KNIGHT, "g1"),
"h1": Piece(FEN_WHITE_ROOK, "h1"),
}
)
del b
root.pack_propagate(False)
root.mainloop()
| 33.615385 | 74 | 0.561022 |
624ae61e4b1438e943cbf012e0b99192c749fb82 | 3,694 | py | Python | Pandas/8_GroupingAndAggregating .py | ErfanRasti/PythonCodes | 5e4569b760b60c9303d5cc68650a2448c9065b6d | [
"MIT"
] | 1 | 2021-10-01T09:59:22.000Z | 2021-10-01T09:59:22.000Z | Pandas/8_GroupingAndAggregating .py | ErfanRasti/PythonCodes | 5e4569b760b60c9303d5cc68650a2448c9065b6d | [
"MIT"
] | null | null | null | Pandas/8_GroupingAndAggregating .py | ErfanRasti/PythonCodes | 5e4569b760b60c9303d5cc68650a2448c9065b6d | [
"MIT"
] | null | null | null | # %%
"""
Let's get familiar with Grouping and Aggregating.
Aggregating means combining multiple pieces of data into a single result.
Mean, median or the mod are aggregating functions.
"""
import pandas as pd
# %%
df = pd.read_csv(
"developer_survey_2019/survey_results_public.csv", index_col="Respondent")
schema_df = pd.read_csv(
"developer_survey_2019/survey_results_schema.csv", index_col="Column")
# %%
pd.set_option('display.max_columns', 85)
pd.set_option('display.max_rows', 85)
# %%
df.head()
# %%
"""In this column NaN means they ignore this question
and don't answer to that."""
df["ConvertedComp"].head(15)
# %%
df["ConvertedComp"].median()
# %%
df.median()
# %%
"""df.describe() gives us count, mean, std, min, max and
some quantiles(25%, 50%, 75%)."""
df.describe()
# %%
df["ConvertedComp"].count()
# %%
df["Hobbyist"]
# %%
df["Hobbyist"].value_counts()
# %%
df["SocialMedia"]
# %%
schema_df.loc["SocialMedia"]
# %%
df["SocialMedia"].value_counts()
# %%
"""Percentage form"""
df["SocialMedia"].value_counts(normalize=True)
# %%
"""
grouping our data:
A group by operation involves some combination of splitting up
our object applying a function and then combining those results
1_Splitting
2_Apply function
3_Combining the results
"""
df["Country"]
# %%
df["Country"].value_counts()
# %%
df.groupby(["Country"])
# %%
country_grp = df.groupby(["Country"])
# %%
country_grp.get_group("United States")
# %%
"""Finding the most popular socialmedia in each country"""
filt = df["Country"] == "United States"
df.loc[filt]["SocialMedia"].value_counts()
# %%
country_grp["SocialMedia"].value_counts()
# %%
country_grp["SocialMedia"].value_counts().head(50)
# %%
"""country_grp method is better than filt way to doing this.
Because we don't need reload filter over and over."""
country_grp["SocialMedia"].value_counts().loc["United States"]
# %%
country_grp["ConvertedComp"].median()
# %%
country_grp["ConvertedComp"].median().loc["Germany"]
# %%
"""agg: Aggregating Methods"""
country_grp["ConvertedComp"].agg(["median", "mean"])
# %%
country_grp["ConvertedComp"].agg(["median", "mean"]).loc["Canada"]
# %%
filt = (df["Country"] == "India")
df.loc[filt]["LanguageWorkedWith"]
# %%
df.loc[filt]["LanguageWorkedWith"].str.contains("Python")
# %%
"""
True : 1
False : 0
"""
df.loc[filt]["LanguageWorkedWith"].str.contains("Python").sum()
# %%
"""
It will raise an error.
country_grp["LanguageWorkedWith"].str.contains("Python").sum()
AttributeError: 'SeriesGroupBy' object has no attribute 'str'
"""
country_grp["LanguageWorkedWith"].apply(
lambda x: x.str.contains("Python").sum())
# %%
country_respondents = df["Country"].value_counts()
country_respondents
# %%
country_uses_python = country_grp["LanguageWorkedWith"].apply(
lambda x: x.str.contains("Python").sum())
country_uses_python
# %%
"""Concatenate two columns to make a new dataframe."""
python_df = pd.concat(
[country_respondents, country_uses_python], axis="columns", sort=False)
python_df
# %%
python_df.rename(columns={"Country": "NumRespondants",
"LanguageWorkedWith": "NumKnowsPython"},
inplace=True)
# %%
python_df
# %%
python_df["PctKnowsPython"] = (
python_df["NumKnowsPython"]/python_df["NumRespondants"]*100)
# %%
python_df
# %%
python_df.sort_values(by="PctKnowsPython", ascending=False, inplace=True)
# %%
python_df
# %%
python_df.head(50)
# %%
python_df.loc["Japan"]
# %%
python_df.sort_values(
by=["NumRespondants", "PctKnowsPython"], ascending=False, inplace=True)
# %%
python_df.head(50)
# %%
| 25.475862 | 79 | 0.666486 |
624cbb34ddb09a80deca0b22d3e463f92b89210a | 13,077 | py | Python | code/cantera_tools.py | goldmanm/RMG_isotopes_paper_data | 234bd5266de71d6ec9179cb3a7ff490cb56ef91a | [
"MIT"
] | null | null | null | code/cantera_tools.py | goldmanm/RMG_isotopes_paper_data | 234bd5266de71d6ec9179cb3a7ff490cb56ef91a | [
"MIT"
] | null | null | null | code/cantera_tools.py | goldmanm/RMG_isotopes_paper_data | 234bd5266de71d6ec9179cb3a7ff490cb56ef91a | [
"MIT"
] | null | null | null | import numpy as np
import pandas as pd
import re
import warnings
import copy
import cantera as ct
def run_simulation(solution, times, conditions=None,
condition_type = 'adiabatic-constant-volume',
output_species = True,
output_reactions = True,
atol = 1e-15,
rtol = 1e-9,
temperature_values=None):
"""
This method iterates through the cantera solution object and outputs information
about the simulation as a pandas.DataFrame object.
This method returns a dictionary with the reaction conditions data, species data,
net reaction data, forward/reverse reaction data, and the rate of production
and consumption (or `None` if a variable not specified).
`solution` = Cantera.Solution object
`conditions` = tuple of temperature, pressure, and mole fraction initial
species (will be deprecated. Set parameters before running)
`times` = an iterable of times which you would like to store information in
`condition_type` = string describing the run type
`output_species` = output a DataFrame of species' concentrations
`output_reactions` = output a DataFrame of net reaction rates
condition_types supported
#########################
'adiabatic-constant-volume' - assumes no heat transfer and no volume change
'constant-temperature-and-pressure' - no solving energy equation or changing
rate constants
'constant-temperature-and-volume' - no solving energy equation but allows
for pressure to change with reactions
'specified-temperature-constant-volume' - the temperature profile specified
`temperature_values`, which corresponds to the
input `times`, alters the temperature right before
the next time step is taken. Constant volume is assumed.
"""
if conditions is not None:
solution.TPX = conditions
if condition_type == 'adiabatic-constant-volume':
reactor = ct.IdealGasReactor(solution)
elif condition_type == 'constant-temperature-and-pressure':
reactor = ct.IdealGasConstPressureReactor(solution, energy='off')
elif condition_type == 'constant-temperature-and-volume':
reactor = ct.IdealGasReactor(solution, energy='off')
elif condition_type == 'specified-temperature-constant-volume':
reactor = ct.IdealGasReactor(solution, energy='off')
if temperature_values is None:
raise AttributeError('Must specify temperature with `temperature_values` parameter')
elif len(times) != len(temperature_values):
raise AttributeError('`times` (len {0}) and `temperature_values` (len {1}) must have the same length.'.format(len(times),len(temperature_values)))
else:
supported_types = ['adiabatic-constant-volume','constant-temperature-and-pressure',
'constant-temperature-and-volume','specified-temperature-constant-volume']
raise NotImplementedError('only {0} are supported. {1} input'.format(supported_types, condition_type))
simulator = ct.ReactorNet([reactor])
solution = reactor.kinetics
simulator.atol = atol
simulator.rtol = rtol
# setup data storage
outputs = {}
outputs['conditions'] = pd.DataFrame()
if output_species:
outputs['species'] = pd.DataFrame()
if output_reactions:
outputs['net_reactions'] = pd.DataFrame()
for time_index, time in enumerate(times):
if condition_type == 'specified-temperature-constant-volume':
solution.TD = temperature_values[time_index], solution.density
reactor = ct.IdealGasReactor(solution, energy='off')
simulator = ct.ReactorNet([reactor])
solution = reactor.kinetics
simulator.atol = atol
simulator.rtol = rtol
if time_index > 0:
simulator.set_initial_time(times[time_index-1])
simulator.advance(time)
# save data
outputs['conditions'] = outputs['conditions'].append(
get_conditions_series(simulator,reactor,solution),
ignore_index = True)
if output_species:
outputs['species'] = outputs['species'].append(
get_species_series(solution),
ignore_index = True)
if output_reactions:
outputs['net_reactions'] = outputs['net_reactions'].append(
get_reaction_series(solution),
ignore_index = True)
# set indexes as time
time_vector = outputs['conditions']['time (s)']
for output in outputs.values():
output.set_index(time_vector,inplace=True)
return outputs
def run_simulation_till_conversion(solution, species, conversion,conditions=None,
condition_type = 'adiabatic-constant-volume',
output_species = True,
output_reactions = True,
skip_data = 150,
atol = 1e-15,
rtol = 1e-9,):
"""
This method iterates through the cantera solution object and outputs information
about the simulation as a pandas.DataFrame object.
This method returns a dictionary with the reaction conditions data, species data,
net reaction data, forward/reverse reaction data, and the rate of production
and consumption (or `None` if a variable not specified) at the specified conversion value.
`solution` = Cantera.Solution object
`conditions` = tuple of temperature, pressure, and mole fraction initial
species
`species` = a string of the species label (or list of strings) to be used in conversion calculations
`conversion` = a float of the fraction conversion to stop the simulation at
`condition_type` = string describing the run type, currently supports
'adiabatic-constant-volume' and 'constant-temperature-and-pressure'
`output_species` = output a Series of species' concentrations
`output_reactions` = output a Series of net reaction rates
`skip_data` = an integer which reduces storing each point of data.
storage space scales as 1/`skip_data`
"""
if conditions is not None:
solution.TPX = conditions
if condition_type == 'adiabatic-constant-volume':
reactor = ct.IdealGasReactor(solution)
if condition_type == 'constant-temperature-and-pressure':
reactor = ct.IdealGasConstPressureReactor(solution, energy='off')
else:
raise NotImplementedError('only adiabatic constant volume is supported')
simulator = ct.ReactorNet([reactor])
solution = reactor.kinetics
simulator.atol = atol
simulator.rtol = rtol
# setup data storage
outputs = {}
outputs['conditions'] = pd.DataFrame()
if output_species:
outputs['species'] = pd.DataFrame()
if output_reactions:
outputs['net_reactions'] = pd.DataFrame()
if isinstance(species,str):
target_species_indexes = [solution.species_index(species)]
else: # must be a list or tuple
target_species_indexes = [solution.species_index(s) for s in species]
starting_concentration = sum([solution.concentrations[target_species_index] for target_species_index in target_species_indexes])
proper_conversion = False
new_conversion = 0
skip_count = 1e8
while not proper_conversion:
error_count = 0
while error_count >= 0:
try:
simulator.step()
error_count = -1
except:
error_count += 1
if error_count > 10:
print('Might not be possible to achieve conversion at T={0}, P={1}, with concentrations of {2} obtaining a conversion of {3} at time {4} s.'.format(solution.T,solution.P,zip(solution.species_names,solution.X), new_conversion,simulator.time))
raise
new_conversion = 1-sum([solution.concentrations[target_species_index] for target_species_index in target_species_indexes])/starting_concentration
if new_conversion > conversion:
proper_conversion = True
# save data
if skip_count > skip_data or proper_conversion:
skip_count = 0
outputs['conditions'] = outputs['conditions'].append(
get_conditions_series(simulator,reactor,solution),
ignore_index = True)
if output_species:
outputs['species'] = outputs['species'].append(
get_species_series(solution),
ignore_index = True)
if output_reactions:
outputs['net_reactions'] = outputs['net_reactions'].append(
get_reaction_series(solution),
ignore_index = True)
skip_count += 1
# set indexes as time
time_vector = outputs['conditions']['time (s)']
for output in outputs.values():
output.set_index(time_vector,inplace=True)
return outputs
def get_conditions_series(simulator, reactor, solution,
basics= ['time','temperature','pressure','density','volume','enthalpy','internal energy']):
"""
returns the current conditions of a Solution object contianing ReactorNet
object (simulator) as a pd.Series.
simulator = the ReactorNet object of the simulation
solution = solution object to pull values from
basics =a list of state variables to save
The following are enabled for the conditions:
* time
* temperature
* pressure
* density
* volume
* cp (constant pressure heat capacity)
* cv (constant volume heat capacity)
* enthalpy
"""
conditions = pd.Series()
# add regular conditions
if 'time' in basics:
conditions['time (s)'] = simulator.time
if 'temperature' in basics:
conditions['temperature (K)'] = solution.T
if 'pressure' in basics:
conditions['pressure (Pa)'] = solution.P
if 'density' in basics:
conditions['density (kmol/m3)'] = solution.density_mole
if 'volume' in basics:
conditions['volume (m3)'] = reactor.volume
if 'cp' in basics:
conditions['heat capacity, cp (J/kmol/K)'] = solution.cp_mole
if 'cv' in basics:
conditions['heat capacity, cv (J/kmol/K)'] = solution.cv_mole
if 'enthalpy' in basics:
conditions['enthalpy (J/kg)'] = solution.enthalpy_mass
if 'internal energy' in basics:
conditions['internal energy (J/kg)'] = solution.int_energy_mass
return conditions
def get_species_series(solution, species_names = 'all'):
"""
returns a pandas.Series of the desired species' concentrations
solution = the cantera.Solution object for the simulation
species_names = list of species names to be saved (default is all)
"""
series = pd.Series()
if species_names=='all':
species_recorded = solution.species_names
else:
species_recorded = species_names
mole_fractions = solution.mole_fraction_dict()
for name in species_recorded:
try:
series[name] = mole_fractions[name] * solution.density_mole
except KeyError:
series[name] = 0
# sends warning if user typed species incorrectly
if name not in solution.species_names:
warnings.warn('{} is not listed in the mole fraction dictionary and may be mispelled.'.format(name))
return series
def get_reaction_series(solution, reaction_names = 'all'):
"""
returns a pandas.Series of the desired reactions' net rates
solution = the cantera.Solution object for the simulation
species_names = list of reaction names to be saved (default is all)
"""
series = pd.Series()
if reaction_names=='all':
reaction_names = solution.reaction_equations()
reaction_rates = __get_rxn_rate_dict(solution.reaction_equations(),solution.net_rates_of_progress)
for name in reaction_names:
try:
series[name] = reaction_rates[name]
except KeyError:
series[name] = 0
warnings.warn('{} is not listed in the reaction names.'.format(name))
return series
def __get_rxn_rate_dict(reaction_equations, net_rates):
"""
makes a dictionary out of the two inputs. If identical reactions are encountered,
called duplicates in Cantera, the method will merge them and sum the rate together
"""
rxn_dict = {}
for equation, rate in zip(reaction_equations, net_rates):
try:
rxn_dict[equation] += rate
except KeyError:
rxn_dict[equation] = rate
return rxn_dict
| 44.030303 | 261 | 0.640132 |
624d1459e0b41f6ddd69ef8b0b14aebd60ee00c3 | 4,495 | py | Python | chariquisitor.py | strycore/chariquisitor | 539dcbf5e051222371e747547a8b1e8805db4366 | [
"WTFPL"
] | 1 | 2017-09-26T09:59:54.000Z | 2017-09-26T09:59:54.000Z | chariquisitor.py | strycore/chariquisitor | 539dcbf5e051222371e747547a8b1e8805db4366 | [
"WTFPL"
] | null | null | null | chariquisitor.py | strycore/chariquisitor | 539dcbf5e051222371e747547a8b1e8805db4366 | [
"WTFPL"
] | null | null | null | import json
from collections import defaultdict
SEGMENTS = ['workings', 'shinies', 'controls', 'fun']
REVIEWERS = ['venn', 'jordan', 'pedro']
if __name__ == '__main__':
games_totals = get_totals_per_game()
print("%i full reviews available" % len(games_totals))
print_top_games(games_totals)
print_top_games(games_totals, top=False)
print_score_fairness(games_totals)
print_score_fairness(games_totals, fair=False)
print()
print_reviewers_stats()
| 34.844961 | 115 | 0.588877 |
624d23bb02f0a1700a789fe03a84f9cdb053398e | 2,970 | py | Python | dense_main.py | Ale-Ba2lero/CNN-FromScratch | 8337db42f3aa0eae878a2724f382039c27498d70 | [
"MIT"
] | 1 | 2021-09-17T17:06:16.000Z | 2021-09-17T17:06:16.000Z | dense_main.py | Ale-Ba2lero/CNN-FromScratch | 8337db42f3aa0eae878a2724f382039c27498d70 | [
"MIT"
] | null | null | null | dense_main.py | Ale-Ba2lero/CNN-FromScratch | 8337db42f3aa0eae878a2724f382039c27498d70 | [
"MIT"
] | null | null | null | import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import minmax_scale
import matplotlib.pyplot as plt
from model.loss import CategoricalCrossEntropy
from model.layers.dense import Dense
from model.layers.relu import LeakyReLU
from model.layers.softmax import Softmax
from model.neural_network import NeuralNetwork
# ------------------------------------ DATASET
N = 200 # number of points per class
D = 2 # dimensionality
K = 3 # number of classes
X, y = spiral_data(points=N, classes=K)
print("Scale values")
print('Min: %.3f, Max: %.3f' % (X.min(), X.max()))
X = minmax_scale(X, feature_range=(0, 1))
print('Min: %.3f, Max: %.3f' % (X.min(), X.max()))
# plt.scatter(X[:, 0], X[:, 1], c=y, s=40, cmap=plt.cm.Spectral)
# plt.show()
# ------------------------------------ SPLIT DATA
"""X_train, X_test, y_train, y_test = train_test_split(X,
y,
test_size=0.1,
random_state=65)"""
# ------------------------------------ HYPER PARAMETERS
STEP_SIZE = 1e-1
N_EPOCHS = 2000
BATCH_SIZE = 32
# ------------------------------------ BUILD THE MODEL
nn = NeuralNetwork([
Dense(200), LeakyReLU(),
Dense(100), LeakyReLU(),
Dense(50), LeakyReLU(),
Dense(K), Softmax()
], CategoricalCrossEntropy())
# ------------------------------------ FIT THE MODEL
nn.train(dataset=X,
labels=y,
epochs=N_EPOCHS,
batch_size=BATCH_SIZE,
step_size=STEP_SIZE)
# ------------------------------------ EVALUATE THE MODEL
train_loss = nn.metrics.history['train_loss']
val_loss = nn.metrics.history['val_loss']
epochs = range(0, N_EPOCHS)
plt.plot(epochs, train_loss, 'g', label='Training loss')
plt.plot(epochs, val_loss, 'b', label='validation loss')
plt.title('Training and Validation loss')
plt.xlabel('Epochs')
plt.ylabel('Loss')
plt.legend()
plt.show()
print(f"train loss: {train_loss}")
print(f"val loss: {val_loss}")
train_acc = nn.metrics.history['train_acc']
val_acc = nn.metrics.history['val_acc']
epochs = range(0, N_EPOCHS)
plt.plot(epochs, train_acc, 'g', label='Training accuracy')
plt.plot(epochs, val_acc, 'b', label='validation accuracy')
plt.title('Training and Validation accuracy')
plt.xlabel('Epochs')
plt.ylabel('Accuracy')
plt.legend()
plt.show()
print(f"train acc: {train_acc}")
print(f"val acc: {val_acc}")
| 31.595745 | 105 | 0.596633 |
624dc465ea933ab310312f6e6dd327e58c7d9b64 | 3,156 | py | Python | Tools/Scripts/webkitpy/common/interrupt_debugging.py | jacadcaps/webkitty | 9aebd2081349f9a7b5d168673c6f676a1450a66d | [
"BSD-2-Clause"
] | 6 | 2021-07-05T16:09:39.000Z | 2022-03-06T22:44:42.000Z | Tools/Scripts/webkitpy/common/interrupt_debugging.py | jacadcaps/webkitty | 9aebd2081349f9a7b5d168673c6f676a1450a66d | [
"BSD-2-Clause"
] | 7 | 2022-03-15T13:25:39.000Z | 2022-03-15T13:25:44.000Z | Tools/Scripts/webkitpy/common/interrupt_debugging.py | jacadcaps/webkitty | 9aebd2081349f9a7b5d168673c6f676a1450a66d | [
"BSD-2-Clause"
] | null | null | null | # Copyright (C) 2019 Apple Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR
# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import linecache
import logging
import os
import signal
import sys
_log = logging.getLogger(__name__)
| 36.697674 | 131 | 0.701521 |
624ded040b53f88852fd60dd292b8fb6fb23b421 | 1,164 | py | Python | django_watermark_images/items/migrations/0001_initial.py | abarto/django-watermark-images | 5f01c8f0da7359c4d96650029d5beb70938fbe47 | [
"MIT"
] | 11 | 2016-12-05T01:12:46.000Z | 2021-05-05T21:41:14.000Z | django_watermark_images/items/migrations/0001_initial.py | abarto/django-watermark-images | 5f01c8f0da7359c4d96650029d5beb70938fbe47 | [
"MIT"
] | 1 | 2020-11-30T13:26:06.000Z | 2020-12-05T11:44:59.000Z | django_watermark_images/items/migrations/0001_initial.py | abarto/django-watermark-images | 5f01c8f0da7359c4d96650029d5beb70938fbe47 | [
"MIT"
] | 3 | 2017-02-07T03:36:42.000Z | 2020-08-10T00:16:04.000Z | # -*- coding: utf-8 -*-
# Generated by Django 1.10 on 2016-09-10 16:15
from __future__ import unicode_literals
from django.db import migrations, models
import django_extensions.db.fields
import items.models
| 35.272727 | 124 | 0.630584 |
62508c428e962c8534fc320110d894864b15ebbe | 11,380 | py | Python | cadnano/views/documentwindow.py | mctrinh/cadnano2.5 | d8254f24eef5fd77b4fb2b1a9642a8eea2e3c736 | [
"BSD-3-Clause"
] | 1 | 2022-03-27T14:37:32.000Z | 2022-03-27T14:37:32.000Z | cadnano/views/documentwindow.py | mctrinh/cadnano2.5 | d8254f24eef5fd77b4fb2b1a9642a8eea2e3c736 | [
"BSD-3-Clause"
] | null | null | null | cadnano/views/documentwindow.py | mctrinh/cadnano2.5 | d8254f24eef5fd77b4fb2b1a9642a8eea2e3c736 | [
"BSD-3-Clause"
] | 1 | 2021-01-22T02:29:38.000Z | 2021-01-22T02:29:38.000Z | from PyQt5.QtCore import Qt
from PyQt5.QtCore import QSettings
from PyQt5.QtCore import QPoint, QSize
from PyQt5.QtWidgets import QGraphicsScene
from PyQt5.QtWidgets import QMainWindow
from PyQt5.QtWidgets import QGraphicsItem
from PyQt5.QtWidgets import QAction, QApplication, QWidget
from cadnano import app
from cadnano.gui.mainwindow import ui_mainwindow
from cadnano.proxies.cnenum import OrthoViewType
from cadnano.views.gridview.gridrootitem import GridRootItem
from cadnano.views.gridview.tools.gridtoolmanager import GridToolManager
from cadnano.views.pathview.colorpanel import ColorPanel
from cadnano.views.pathview.pathrootitem import PathRootItem
from cadnano.views.pathview.tools.pathtoolmanager import PathToolManager
from cadnano.views.sliceview.slicerootitem import SliceRootItem
from cadnano.views.sliceview.tools.slicetoolmanager import SliceToolManager
# from PyQt5.QtOpenGL import QGLWidget
# # check out https://github.com/baoboa/pyqt5/tree/master/examples/opengl
# # for an example of the QOpenGlWidget added in Qt 5.4
# end class
| 39.79021 | 102 | 0.675747 |
6250a79068b77c4892032d50b57910bd5cac5d15 | 42,245 | py | Python | uhd_restpy/testplatform/sessions/ixnetwork/topology/ospfv3_c029fd7cd4a9e9897b7b4e4547458751.py | Vibaswan/ixnetwork_restpy | 239fedc7050890746cbabd71ea1e91c68d9e5cad | [
"MIT"
] | null | null | null | uhd_restpy/testplatform/sessions/ixnetwork/topology/ospfv3_c029fd7cd4a9e9897b7b4e4547458751.py | Vibaswan/ixnetwork_restpy | 239fedc7050890746cbabd71ea1e91c68d9e5cad | [
"MIT"
] | null | null | null | uhd_restpy/testplatform/sessions/ixnetwork/topology/ospfv3_c029fd7cd4a9e9897b7b4e4547458751.py | Vibaswan/ixnetwork_restpy | 239fedc7050890746cbabd71ea1e91c68d9e5cad | [
"MIT"
] | null | null | null | # MIT LICENSE
#
# Copyright 1997 - 2020 by IXIA Keysight
#
# 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 uhd_restpy.base import Base
from uhd_restpy.files import Files
def add(self, ConnectedVia=None, Multiplier=None, Name=None, StackedLayers=None):
"""Adds a new ospfv3 resource on the server and adds it to the container.
Args
----
- ConnectedVia (list(str[None | /api/v1/sessions/1/ixnetwork/topology/.../*])): List of layers this layer is used to connect with to the wire.
- Multiplier (number): Number of layer instances per parent instance (multiplier)
- Name (str): Name of NGPF element, guaranteed to be unique in Scenario
- StackedLayers (list(str[None | /api/v1/sessions/1/ixnetwork/topology/.../*])): List of secondary (many to one) child layer protocols
Returns
-------
- self: This instance with all currently retrieved ospfv3 resources using find and the newly added ospfv3 resources available through an iterator or index
Raises
------
- ServerError: The server has encountered an uncategorized error condition
"""
return self._create(self._map_locals(self._SDM_ATT_MAP, locals()))
def remove(self):
"""Deletes all the contained ospfv3 resources in this instance from the server.
Raises
------
- NotFoundError: The requested resource does not exist on the server
- ServerError: The server has encountered an uncategorized error condition
"""
self._delete()
def find(self, ConnectedVia=None, Count=None, DescriptiveName=None, Errors=None, LocalRouterID=None, Multiplier=None, Name=None, Ospfv3IfaceState=None, Ospfv3NeighborState=None, SessionInfo=None, SessionStatus=None, StackedLayers=None, StateCounts=None, Status=None):
"""Finds and retrieves ospfv3 resources from the server.
All named parameters are evaluated on the server using regex. The named parameters can be used to selectively retrieve ospfv3 resources from the server.
To retrieve an exact match ensure the parameter value starts with ^ and ends with $
By default the find method takes no parameters and will retrieve all ospfv3 resources from the server.
Args
----
- ConnectedVia (list(str[None | /api/v1/sessions/1/ixnetwork/topology/.../*])): List of layers this layer is used to connect with to the wire.
- Count (number): Number of elements inside associated multiplier-scaled container object, e.g. number of devices inside a Device Group.
- DescriptiveName (str): Longer, more descriptive name for element. It's not guaranteed to be unique like -name-, but may offer more context.
- Errors (list(dict(arg1:str[None | /api/v1/sessions/1/ixnetwork//.../*],arg2:list[str]))): A list of errors that have occurred
- LocalRouterID (list(str)): Router ID
- Multiplier (number): Number of layer instances per parent instance (multiplier)
- Name (str): Name of NGPF element, guaranteed to be unique in Scenario
- Ospfv3IfaceState (list(str[backup | down | dr | drOther | pointToPoint | unrecognized | waiting])): Logs additional information about the Interface State
- Ospfv3NeighborState (list(str[attempt | down | exchange | exStart | full | init | loading | multiNeighbor | none | twoWay])): Logs additional information about the Neighbor State
- SessionInfo (list(str[ifaceSessInfoAllNbrIn2Way | ifaceSessInfoAllNbrInattempt | ifaceSessInfoAllNbrInDown | ifaceSessInfoAllNbrInExchange | ifaceSessInfoAllNbrInExStart | ifaceSessInfoAllNbrInInit | ifaceSessInfoAllNbrInLoading | ifaceSessInfoFsmNotStarted | ifaceSessInfoSameNbrId | iPAddressNotRcvd | none])): Logs additional information about the session state
- SessionStatus (list(str[down | notStarted | up])): Current state of protocol session: Not Started - session negotiation not started, the session is not active yet. Down - actively trying to bring up a protocol session, but negotiation is didn't successfully complete (yet). Up - session came up successfully.
- StackedLayers (list(str[None | /api/v1/sessions/1/ixnetwork/topology/.../*])): List of secondary (many to one) child layer protocols
- StateCounts (dict(total:number,notStarted:number,down:number,up:number)): A list of values that indicates the total number of sessions, the number of sessions not started, the number of sessions down and the number of sessions that are up
- Status (str(configured | error | mixed | notStarted | started | starting | stopping)): Running status of associated network element. Once in Started state, protocol sessions will begin to negotiate.
Returns
-------
- self: This instance with matching ospfv3 resources retrieved from the server available through an iterator or index
Raises
------
- ServerError: The server has encountered an uncategorized error condition
"""
return self._select(self._map_locals(self._SDM_ATT_MAP, locals()))
def read(self, href):
"""Retrieves a single instance of ospfv3 data from the server.
Args
----
- href (str): An href to the instance to be retrieved
Returns
-------
- self: This instance with the ospfv3 resources from the server available through an iterator or index
Raises
------
- NotFoundError: The requested resource does not exist on the server
- ServerError: The server has encountered an uncategorized error condition
"""
return self._read(href)
def get_device_ids(self, PortNames=None, Active=None, AdjSID=None, AreaId=None, AreaIdIp=None, AuthAlgo=None, BFlag=None, DeadInterval=None, DemandCircuit=None, EnableAdjSID=None, EnableAuthentication=None, EnableBfdRegistration=None, EnableFastHello=None, EnableIgnoreDbDescMtu=None, ExternalCapability=None, GFlag=None, HelloInterval=None, HelloMultiplier=None, InstanceId=None, Key=None, LFlag=None, LinkMetric=None, NetworkType=None, NssaCapability=None, PFlag=None, Priority=None, Router=None, SaId=None, TypeAreaId=None, V6=None, VFlag=None, Weight=None):
"""Base class infrastructure that gets a list of ospfv3 device ids encapsulated by this object.
Use the optional regex parameters in the method to refine the list of device ids encapsulated by this object.
Args
----
- PortNames (str): optional regex of port names
- Active (str): optional regex of active
- AdjSID (str): optional regex of adjSID
- AreaId (str): optional regex of areaId
- AreaIdIp (str): optional regex of areaIdIp
- AuthAlgo (str): optional regex of authAlgo
- BFlag (str): optional regex of bFlag
- DeadInterval (str): optional regex of deadInterval
- DemandCircuit (str): optional regex of demandCircuit
- EnableAdjSID (str): optional regex of enableAdjSID
- EnableAuthentication (str): optional regex of enableAuthentication
- EnableBfdRegistration (str): optional regex of enableBfdRegistration
- EnableFastHello (str): optional regex of enableFastHello
- EnableIgnoreDbDescMtu (str): optional regex of enableIgnoreDbDescMtu
- ExternalCapability (str): optional regex of externalCapability
- GFlag (str): optional regex of gFlag
- HelloInterval (str): optional regex of helloInterval
- HelloMultiplier (str): optional regex of helloMultiplier
- InstanceId (str): optional regex of instanceId
- Key (str): optional regex of key
- LFlag (str): optional regex of lFlag
- LinkMetric (str): optional regex of linkMetric
- NetworkType (str): optional regex of networkType
- NssaCapability (str): optional regex of nssaCapability
- PFlag (str): optional regex of pFlag
- Priority (str): optional regex of priority
- Router (str): optional regex of router
- SaId (str): optional regex of saId
- TypeAreaId (str): optional regex of typeAreaId
- V6 (str): optional regex of v6
- VFlag (str): optional regex of vFlag
- Weight (str): optional regex of weight
Returns
-------
- list(int): A list of device ids that meets the regex criteria provided in the method parameters
Raises
------
- ServerError: The server has encountered an uncategorized error condition
"""
return self._get_ngpf_device_ids(locals())
def Abort(self, *args, **kwargs):
"""Executes the abort operation on the server.
Abort CPF control plane (equals to demote to kUnconfigured state).
The IxNetwork model allows for multiple method Signatures with the same name while python does not.
abort(SessionIndices=list)
--------------------------
- SessionIndices (list(number)): This parameter requires an array of session numbers 1 2 3
abort(SessionIndices=string)
----------------------------
- SessionIndices (str): This parameter requires a string of session numbers 1-4;6;7-12
Raises
------
- NotFoundError: The requested resource does not exist on the server
- ServerError: The server has encountered an uncategorized error condition
"""
payload = { "Arg1": self }
for i in range(len(args)): payload['Arg%s' % (i + 2)] = args[i]
for item in kwargs.items(): payload[item[0]] = item[1]
return self._execute('abort', payload=payload, response_object=None)
def ClearAllLearnedInfo(self, *args, **kwargs):
"""Executes the clearAllLearnedInfo operation on the server.
Clear All Learned Info
The IxNetwork model allows for multiple method Signatures with the same name while python does not.
clearAllLearnedInfo(SessionIndices=list)
----------------------------------------
- SessionIndices (list(number)): This parameter requires an array of session numbers 1 2 3
clearAllLearnedInfo(SessionIndices=string)
------------------------------------------
- SessionIndices (str): This parameter requires a string of session numbers 1-4;6;7-12
Raises
------
- NotFoundError: The requested resource does not exist on the server
- ServerError: The server has encountered an uncategorized error condition
"""
payload = { "Arg1": self }
for i in range(len(args)): payload['Arg%s' % (i + 2)] = args[i]
for item in kwargs.items(): payload[item[0]] = item[1]
return self._execute('clearAllLearnedInfo', payload=payload, response_object=None)
def ClearAllLearnedInfoInClient(self, *args, **kwargs):
"""Executes the clearAllLearnedInfoInClient operation on the server.
Clears ALL routes from GUI grid for the selected OSPFv3 router.
clearAllLearnedInfoInClient(Arg2=list)list
------------------------------------------
- Arg2 (list(number)): List of indices into the protocol plugin. An empty list indicates all instances in the plugin.
- Returns list(str): ID to associate each async action invocation
Raises
------
- NotFoundError: The requested resource does not exist on the server
- ServerError: The server has encountered an uncategorized error condition
"""
payload = { "Arg1": self.href }
for i in range(len(args)): payload['Arg%s' % (i + 2)] = args[i]
for item in kwargs.items(): payload[item[0]] = item[1]
return self._execute('clearAllLearnedInfoInClient', payload=payload, response_object=None)
def GetBasicLearnedInfo(self, *args, **kwargs):
"""Executes the getBasicLearnedInfo operation on the server.
Get Basic Learned Info
The IxNetwork model allows for multiple method Signatures with the same name while python does not.
getBasicLearnedInfo(SessionIndices=list)
----------------------------------------
- SessionIndices (list(number)): This parameter requires an array of session numbers 1 2 3
getBasicLearnedInfo(SessionIndices=string)
------------------------------------------
- SessionIndices (str): This parameter requires a string of session numbers 1-4;6;7-12
getBasicLearnedInfo(Arg2=list)list
----------------------------------
- Arg2 (list(number)): List of indices into the protocol plugin. An empty list indicates all instances in the plugin.
- Returns list(str): ID to associate each async action invocation
Raises
------
- NotFoundError: The requested resource does not exist on the server
- ServerError: The server has encountered an uncategorized error condition
"""
payload = { "Arg1": self }
for i in range(len(args)): payload['Arg%s' % (i + 2)] = args[i]
for item in kwargs.items(): payload[item[0]] = item[1]
return self._execute('getBasicLearnedInfo', payload=payload, response_object=None)
def GetDetailedLearnedInfo(self, *args, **kwargs):
"""Executes the getDetailedLearnedInfo operation on the server.
Get Detailed Learned Info
The IxNetwork model allows for multiple method Signatures with the same name while python does not.
getDetailedLearnedInfo(SessionIndices=list)
-------------------------------------------
- SessionIndices (list(number)): This parameter requires an array of session numbers 1 2 3
getDetailedLearnedInfo(SessionIndices=string)
---------------------------------------------
- SessionIndices (str): This parameter requires a string of session numbers 1-4;6;7-12
getDetailedLearnedInfo(Arg2=list)list
-------------------------------------
- Arg2 (list(number)): List of indices into the protocol plugin. An empty list indicates all instances in the plugin.
- Returns list(str): ID to associate each async action invocation
Raises
------
- NotFoundError: The requested resource does not exist on the server
- ServerError: The server has encountered an uncategorized error condition
"""
payload = { "Arg1": self }
for i in range(len(args)): payload['Arg%s' % (i + 2)] = args[i]
for item in kwargs.items(): payload[item[0]] = item[1]
return self._execute('getDetailedLearnedInfo', payload=payload, response_object=None)
def RestartDown(self, *args, **kwargs):
"""Executes the restartDown operation on the server.
Stop and start interfaces and sessions that are in Down state.
The IxNetwork model allows for multiple method Signatures with the same name while python does not.
restartDown(SessionIndices=list)
--------------------------------
- SessionIndices (list(number)): This parameter requires an array of session numbers 1 2 3
restartDown(SessionIndices=string)
----------------------------------
- SessionIndices (str): This parameter requires a string of session numbers 1-4;6;7-12
Raises
------
- NotFoundError: The requested resource does not exist on the server
- ServerError: The server has encountered an uncategorized error condition
"""
payload = { "Arg1": self }
for i in range(len(args)): payload['Arg%s' % (i + 2)] = args[i]
for item in kwargs.items(): payload[item[0]] = item[1]
return self._execute('restartDown', payload=payload, response_object=None)
def ResumeHello(self, *args, **kwargs):
"""Executes the resumeHello operation on the server.
Resume sending OSPFv3 Hellos
The IxNetwork model allows for multiple method Signatures with the same name while python does not.
resumeHello(SessionIndices=list)
--------------------------------
- SessionIndices (list(number)): This parameter requires an array of session numbers 1 2 3
resumeHello(SessionIndices=string)
----------------------------------
- SessionIndices (str): This parameter requires a string of session numbers 1-4;6;7-12
Raises
------
- NotFoundError: The requested resource does not exist on the server
- ServerError: The server has encountered an uncategorized error condition
"""
payload = { "Arg1": self }
for i in range(len(args)): payload['Arg%s' % (i + 2)] = args[i]
for item in kwargs.items(): payload[item[0]] = item[1]
return self._execute('resumeHello', payload=payload, response_object=None)
def Resumehello(self, *args, **kwargs):
"""Executes the resumehello operation on the server.
Starts the protocol state machine for the given protocol session instances.
resumehello(Arg2=list)list
--------------------------
- Arg2 (list(number)): List of indices into the protocol plugin. An empty list indicates all instances in the plugin.
- Returns list(str): ID to associate each async action invocation
Raises
------
- NotFoundError: The requested resource does not exist on the server
- ServerError: The server has encountered an uncategorized error condition
"""
payload = { "Arg1": self.href }
for i in range(len(args)): payload['Arg%s' % (i + 2)] = args[i]
for item in kwargs.items(): payload[item[0]] = item[1]
return self._execute('resumehello', payload=payload, response_object=None)
def Start(self, *args, **kwargs):
"""Executes the start operation on the server.
Start CPF control plane (equals to promote to negotiated state).
The IxNetwork model allows for multiple method Signatures with the same name while python does not.
start(SessionIndices=list)
--------------------------
- SessionIndices (list(number)): This parameter requires an array of session numbers 1 2 3
start(SessionIndices=string)
----------------------------
- SessionIndices (str): This parameter requires a string of session numbers 1-4;6;7-12
Raises
------
- NotFoundError: The requested resource does not exist on the server
- ServerError: The server has encountered an uncategorized error condition
"""
payload = { "Arg1": self }
for i in range(len(args)): payload['Arg%s' % (i + 2)] = args[i]
for item in kwargs.items(): payload[item[0]] = item[1]
return self._execute('start', payload=payload, response_object=None)
def Stop(self, *args, **kwargs):
"""Executes the stop operation on the server.
Stop CPF control plane (equals to demote to PreValidated-DoDDone state).
The IxNetwork model allows for multiple method Signatures with the same name while python does not.
stop(SessionIndices=list)
-------------------------
- SessionIndices (list(number)): This parameter requires an array of session numbers 1 2 3
stop(SessionIndices=string)
---------------------------
- SessionIndices (str): This parameter requires a string of session numbers 1-4;6;7-12
Raises
------
- NotFoundError: The requested resource does not exist on the server
- ServerError: The server has encountered an uncategorized error condition
"""
payload = { "Arg1": self }
for i in range(len(args)): payload['Arg%s' % (i + 2)] = args[i]
for item in kwargs.items(): payload[item[0]] = item[1]
return self._execute('stop', payload=payload, response_object=None)
def StopHello(self, *args, **kwargs):
"""Executes the stopHello operation on the server.
Stop sending OSPFv3 Hellos
The IxNetwork model allows for multiple method Signatures with the same name while python does not.
stopHello(SessionIndices=list)
------------------------------
- SessionIndices (list(number)): This parameter requires an array of session numbers 1 2 3
stopHello(SessionIndices=string)
--------------------------------
- SessionIndices (str): This parameter requires a string of session numbers 1-4;6;7-12
Raises
------
- NotFoundError: The requested resource does not exist on the server
- ServerError: The server has encountered an uncategorized error condition
"""
payload = { "Arg1": self }
for i in range(len(args)): payload['Arg%s' % (i + 2)] = args[i]
for item in kwargs.items(): payload[item[0]] = item[1]
return self._execute('stopHello', payload=payload, response_object=None)
def Stophello(self, *args, **kwargs):
"""Executes the stophello operation on the server.
Stops the protocol state machine for the given protocol session instances.
stophello(Arg2=list)list
------------------------
- Arg2 (list(number)): List of indices into the protocol plugin. An empty list indicates all instances in the plugin.
- Returns list(str): ID to associate each async action invocation
Raises
------
- NotFoundError: The requested resource does not exist on the server
- ServerError: The server has encountered an uncategorized error condition
"""
payload = { "Arg1": self.href }
for i in range(len(args)): payload['Arg%s' % (i + 2)] = args[i]
for item in kwargs.items(): payload[item[0]] = item[1]
return self._execute('stophello', payload=payload, response_object=None)
| 41.951341 | 565 | 0.639981 |
6251e5f75335276f9c6c9626a85c2811646b3967 | 1,970 | py | Python | train/loss/mss_loss.py | jdasam/ddsp-pytorch | cefa59881331e0f76eb073317a311c867e331ac2 | [
"MIT"
] | 88 | 2020-02-26T16:37:53.000Z | 2022-03-16T23:27:17.000Z | train/loss/mss_loss.py | hihunjin/my_ddsp-pytorch | 2f7f9222b20ba34b3976a8f78c8efa696b4665c5 | [
"MIT"
] | 3 | 2020-07-25T05:03:17.000Z | 2022-03-23T17:37:38.000Z | train/loss/mss_loss.py | hihunjin/my_ddsp-pytorch | 2f7f9222b20ba34b3976a8f78c8efa696b4665c5 | [
"MIT"
] | 17 | 2020-06-03T09:11:10.000Z | 2021-11-25T10:24:25.000Z | """
Implementation of Multi-Scale Spectral Loss as described in DDSP,
which is originally suggested in NSF (Wang et al., 2019)
"""
import torch
import torch.nn as nn
import torchaudio
import torch.nn.functional as F
| 28.142857 | 99 | 0.618274 |
6255b36ebec98e609bf24f715546b55d46c7815b | 8,889 | py | Python | tests/test_triton_server.py | jishminor/model_analyzer | 8593a473bcc923f90a892cffe59fa9980b55c27f | [
"Apache-2.0"
] | null | null | null | tests/test_triton_server.py | jishminor/model_analyzer | 8593a473bcc923f90a892cffe59fa9980b55c27f | [
"Apache-2.0"
] | null | null | null | tests/test_triton_server.py | jishminor/model_analyzer | 8593a473bcc923f90a892cffe59fa9980b55c27f | [
"Apache-2.0"
] | null | null | null | # Copyright (c) 2020-2021, NVIDIA CORPORATION. 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.
import unittest
from .mocks.mock_server_docker import MockServerDockerMethods
from .mocks.mock_server_local import MockServerLocalMethods
from .common import test_result_collector as trc
from model_analyzer.triton.server.server_factory import TritonServerFactory
from model_analyzer.triton.server.server_config import TritonServerConfig
from model_analyzer.model_analyzer_exceptions \
import TritonModelAnalyzerException
# Test parameters
MODEL_REPOSITORY_PATH = 'test_repo'
TRITON_LOCAL_BIN_PATH = 'test_bin_path/tritonserver'
TRITON_DOCKER_BIN_PATH = 'tritonserver'
TRITON_IMAGE = 'test_image'
CONFIG_TEST_ARG = 'exit-on-error'
CLI_TO_STRING_TEST_ARGS = {
'allow-grpc': True,
'min-supported-compute-capability': 7.5,
'metrics-port': 8000,
'model-repository': MODEL_REPOSITORY_PATH
}
if __name__ == '__main__':
unittest.main()
| 38.986842 | 79 | 0.673304 |
625618420b8b42e1290ca8d84b7cf2668f7fc56c | 5,490 | py | Python | modules/help_urls/help_urls.py | xochilt/cousebuilder | 50c524ad1406b77288efdc616812877e0c85aeb5 | [
"Apache-2.0"
] | null | null | null | modules/help_urls/help_urls.py | xochilt/cousebuilder | 50c524ad1406b77288efdc616812877e0c85aeb5 | [
"Apache-2.0"
] | null | null | null | modules/help_urls/help_urls.py | xochilt/cousebuilder | 50c524ad1406b77288efdc616812877e0c85aeb5 | [
"Apache-2.0"
] | null | null | null | # Copyright 2015 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.
"""Help URL resolver.
Help URLs are of the form <base>/<version>/<suffix> where
1) <base> is the base help URL, which defaults to _BASE_URL below.
2) <version> is derived from the GCB_PRODUCT_VERSION environment variable. If
the patch version is zero, it and its leading dot are stripped (so '1.0.0'
becomes '1.0').
3) <suffix> is a string from topics._ALL, which contains a mapping from a
topic_id to a URL suffix.
URLs are normalized to contain correct slashes. To set a help URL, edit
topics.py's _ALL variable.
The flow is:
1) Use services.help_urls.make_learn_more_message() to make a message for
display in the UI.
2) This composes a link with the href set to _REDIRECT_HANDLER_URL, and passes
the topic_id passed in the call to make_learn_more_message().
3) The redirect handler validates the topic_id, then redirects the user to the
real help URL, calculated from the value in topics._ALL.
This allows us control over the help URLs, opening up the ability to version
them, or to have different doc sets for different runtime configurations. It
also gathers the URLs into one place (topics._ALL) rather than scattering them
throughout the codebase.
"""
__author__ = [
'John Cox (johncox@google.com)',
]
import logging
import os
from common import safe_dom
from controllers import utils
from models import custom_modules
from models import services
from modules.help_urls import topics
_BASE_URL = 'https://www.google.com/edu/openonline/course-builder/docs'
# Legacy documentation URL. Fall through to this whenever an item is in
# topics._ALL but its value is topics._DEFAULT.
# TODO(johncox): remove this once topics._ALL is fully populated.
_DEFAULT_URL = 'https://code.google.com/p/course-builder/wiki/Dashboard'
_LOG = logging.getLogger('modules.help_urls.help_urls')
logging.basicConfig()
_REDIRECT_HANDLER_URL = '/modules/help_urls/redirect'
custom_module = None
| 31.193182 | 79 | 0.67541 |
625670c4163cea1c3e5232cab52845847be981b8 | 4,584 | py | Python | imm/samplers/noncollapsed.py | tscholak/imm | cbf588800ddb3b3b57843d85a92d881f43fd5702 | [
"Apache-2.0"
] | 9 | 2016-02-15T00:40:18.000Z | 2020-05-14T10:22:53.000Z | imm/samplers/noncollapsed.py | tscholak/imm | cbf588800ddb3b3b57843d85a92d881f43fd5702 | [
"Apache-2.0"
] | null | null | null | imm/samplers/noncollapsed.py | tscholak/imm | cbf588800ddb3b3b57843d85a92d881f43fd5702 | [
"Apache-2.0"
] | 2 | 2016-01-29T17:46:42.000Z | 2020-11-18T04:57:20.000Z | # -*- coding: utf-8 -*-
"""
Non-collapsed samplers.
"""
import numpy as np
from .generic import (GenericGibbsSampler, GenericRGMSSampler,
GenericSAMSSampler, GenericSliceSampler)
from ..models import (CollapsedConjugateGaussianMixture,
ConjugateGaussianMixture, NonconjugateGaussianMixture)
from ..models import DP, MFM
| 34.208955 | 77 | 0.662522 |
62578dce0eabf4b8ae7fad7a5b39c7aa9bac6caa | 393 | py | Python | api/urls.py | Emmastro/medmer-api | c17366a92506b6ac1bdedc85ad0c29c3d2b36b5d | [
"Apache-2.0"
] | null | null | null | api/urls.py | Emmastro/medmer-api | c17366a92506b6ac1bdedc85ad0c29c3d2b36b5d | [
"Apache-2.0"
] | 1 | 2021-07-12T06:32:14.000Z | 2021-07-12T06:32:14.000Z | api/urls.py | Emmastro/medmer | c17366a92506b6ac1bdedc85ad0c29c3d2b36b5d | [
"Apache-2.0"
] | null | null | null | from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('accounts/', include('django.contrib.auth.urls')),
path('', include('home.urls')),
path('admin/', admin.site.urls),
path('registration/medic', include('medic.urls')),
path('registration/patient', include('patient.urls')),
path('help-request/', include('helprequest.urls')),
]
| 32.75 | 59 | 0.676845 |
6258836d166a8d6c1882a706cc1e2bf3153eda25 | 55 | py | Python | src/evolvepy/integrations/__init__.py | EltonCN/evolvepy | 4489264d6c03ea4f3c23ea665fdf12fe4ead1ccc | [
"MIT"
] | 1 | 2022-01-13T21:11:53.000Z | 2022-01-13T21:11:53.000Z | src/evolvepy/integrations/__init__.py | EltonCN/evolvepy | 4489264d6c03ea4f3c23ea665fdf12fe4ead1ccc | [
"MIT"
] | null | null | null | src/evolvepy/integrations/__init__.py | EltonCN/evolvepy | 4489264d6c03ea4f3c23ea665fdf12fe4ead1ccc | [
"MIT"
] | null | null | null | '''
EvolvePy's integrations with other modules.
''' | 18.333333 | 47 | 0.672727 |
62588608a3f5e4881c91b92770889c28b45edea4 | 587 | py | Python | subdomain.py | ouldevloper/subDomainFinder | 3b888e8267d8b89401a468d2622edd6716a88293 | [
"MIT"
] | null | null | null | subdomain.py | ouldevloper/subDomainFinder | 3b888e8267d8b89401a468d2622edd6716a88293 | [
"MIT"
] | null | null | null | subdomain.py | ouldevloper/subDomainFinder | 3b888e8267d8b89401a468d2622edd6716a88293 | [
"MIT"
] | null | null | null | import requests
import re
url=input("Enter Url [ex: example.com]: ")
getSubDomain(url) | 34.529412 | 95 | 0.524702 |
62592611062846e8ddc9453d08b3f9cc749f88fa | 129 | py | Python | Python/Courses/Python-Tutorials.Telusko/02.Miscellaneous/20.03-File-handling.py | shihab4t/Books-Code | b637b6b2ad42e11faf87d29047311160fe3b2490 | [
"Unlicense"
] | null | null | null | Python/Courses/Python-Tutorials.Telusko/02.Miscellaneous/20.03-File-handling.py | shihab4t/Books-Code | b637b6b2ad42e11faf87d29047311160fe3b2490 | [
"Unlicense"
] | null | null | null | Python/Courses/Python-Tutorials.Telusko/02.Miscellaneous/20.03-File-handling.py | shihab4t/Books-Code | b637b6b2ad42e11faf87d29047311160fe3b2490 | [
"Unlicense"
] | null | null | null | file = open("text.txt", "r")
file2 = open("text2.txt", "w")
for data in file:
file2.write(data)
file.close()
file2.close()
| 14.333333 | 30 | 0.620155 |
625a19aeeb78d1a163e46b551accd53b6ef2d20c | 532 | py | Python | torch2trt/__init__.py | SnowMasaya/torch2trt | d526b2473805f9b9a704a201bef3ce5be25d284f | [
"MIT"
] | 2 | 2020-07-10T06:26:03.000Z | 2020-07-10T07:38:08.000Z | torch2trt/__init__.py | SnowMasaya/torch2trt | d526b2473805f9b9a704a201bef3ce5be25d284f | [
"MIT"
] | 1 | 2020-02-16T09:43:35.000Z | 2020-02-16T09:43:35.000Z | torch2trt/__init__.py | SnowMasaya/torch2trt | d526b2473805f9b9a704a201bef3ce5be25d284f | [
"MIT"
] | 1 | 2019-10-14T01:11:23.000Z | 2019-10-14T01:11:23.000Z | from .torch2trt import *
from .converters import *
import tensorrt as trt
try:
load_plugins()
PLUGINS_LOADED = True
except OSError:
PLUGINS_LOADED = False
| 24.181818 | 103 | 0.716165 |
625bb84667ccfd99b5f46c321c52127e25ca0ad0 | 4,614 | py | Python | ediel-parser/lib/cli/com.py | sun-labs/ediclue | 22836afc3eca6eebd800cf5d843166656ceaeaae | [
"MIT"
] | 3 | 2020-05-30T09:15:40.000Z | 2021-11-17T20:06:27.000Z | ediel-parser/lib/cli/com.py | sun-labs/ediclue | 22836afc3eca6eebd800cf5d843166656ceaeaae | [
"MIT"
] | null | null | null | ediel-parser/lib/cli/com.py | sun-labs/ediclue | 22836afc3eca6eebd800cf5d843166656ceaeaae | [
"MIT"
] | 1 | 2020-12-25T16:37:13.000Z | 2020-12-25T16:37:13.000Z | import os
from lib.EDICommunicator import EDICommunicator
from lib.EDIParser import EDIParser
import lib.cli.tools as tools
from types import SimpleNamespace | 39.435897 | 117 | 0.657781 |
625c8a42b10a793670359b3599bb4463084222aa | 154 | py | Python | 04_working_with_list/4_2_animals.py | simonhoch/python_basics | 4ecf12c074e641e3cdeb0a6690846eb9133f96af | [
"MIT"
] | null | null | null | 04_working_with_list/4_2_animals.py | simonhoch/python_basics | 4ecf12c074e641e3cdeb0a6690846eb9133f96af | [
"MIT"
] | null | null | null | 04_working_with_list/4_2_animals.py | simonhoch/python_basics | 4ecf12c074e641e3cdeb0a6690846eb9133f96af | [
"MIT"
] | null | null | null | animals = ['cat', 'dog', 'pig']
for animal in animals :
print (animal + 'would make a great pet.')
print ('All of those animals would makea great pet')
| 30.8 | 53 | 0.668831 |
625d706044520dc3362905ca933c2db2e59ae151 | 145 | py | Python | backend/mytutorials/telegrambot/urls.py | mahmoodDehghan/MyTests | a67693e14eda2257490f295909d17b6f3f962543 | [
"MIT"
] | null | null | null | backend/mytutorials/telegrambot/urls.py | mahmoodDehghan/MyTests | a67693e14eda2257490f295909d17b6f3f962543 | [
"MIT"
] | null | null | null | backend/mytutorials/telegrambot/urls.py | mahmoodDehghan/MyTests | a67693e14eda2257490f295909d17b6f3f962543 | [
"MIT"
] | null | null | null | from django.urls import path
from .views import start_bot, end_bot
urlpatterns = [
path('startbot/', start_bot),
path('endbot/', end_bot),
] | 20.714286 | 37 | 0.717241 |
62602e529718a96dbd2a4603b293f7ef9ea48276 | 420 | py | Python | tests/performance/cte-arm/tests/csvm_ijcnn1.py | alexbarcelo/dislib | 989f81f235ae30b17410a8d805df258c7d931b38 | [
"Apache-2.0"
] | 36 | 2018-10-22T19:21:14.000Z | 2022-03-22T12:10:01.000Z | tests/performance/cte-arm/tests/csvm_ijcnn1.py | alexbarcelo/dislib | 989f81f235ae30b17410a8d805df258c7d931b38 | [
"Apache-2.0"
] | 329 | 2018-11-22T18:04:57.000Z | 2022-03-18T01:26:55.000Z | tests/performance/cte-arm/tests/csvm_ijcnn1.py | alexbarcelo/dislib | 989f81f235ae30b17410a8d805df258c7d931b38 | [
"Apache-2.0"
] | 21 | 2019-01-10T11:46:39.000Z | 2022-03-17T12:59:45.000Z | import performance
import dislib as ds
from dislib.classification import CascadeSVM
if __name__ == "__main__":
main()
| 22.105263 | 66 | 0.697619 |
6261861dfa046a0934777f8f23b5ec284278ef51 | 1,115 | py | Python | py_connect/exceptions.py | iparaskev/py_connect | 43476cddfb25130d058fcf59928454f867af8feb | [
"BSD-3-Clause"
] | 5 | 2021-03-19T07:05:50.000Z | 2021-03-31T22:53:52.000Z | py_connect/exceptions.py | iparaskev/py_connect | 43476cddfb25130d058fcf59928454f867af8feb | [
"BSD-3-Clause"
] | null | null | null | py_connect/exceptions.py | iparaskev/py_connect | 43476cddfb25130d058fcf59928454f867af8feb | [
"BSD-3-Clause"
] | null | null | null | """Exceptions of the library"""
| 24.23913 | 67 | 0.744395 |
6261f7a9c9b18a89ffbec87fba08c79cb2839e13 | 1,151 | py | Python | code/glucocheck/homepage/migrations/0007_auto_20210315_1807.py | kmcgreg5/Glucocheck | 4ab4ada7f967ae41c1241c94523d14e693e05dd4 | [
"FSFAP"
] | null | null | null | code/glucocheck/homepage/migrations/0007_auto_20210315_1807.py | kmcgreg5/Glucocheck | 4ab4ada7f967ae41c1241c94523d14e693e05dd4 | [
"FSFAP"
] | null | null | null | code/glucocheck/homepage/migrations/0007_auto_20210315_1807.py | kmcgreg5/Glucocheck | 4ab4ada7f967ae41c1241c94523d14e693e05dd4 | [
"FSFAP"
] | null | null | null | # Generated by Django 3.1.7 on 2021-03-15 22:07
from django.db import migrations, models
| 34.878788 | 338 | 0.600348 |
6262bae7dfc3df2c02ba7e5efae6983d3daa02cb | 1,826 | py | Python | models/SnapshotTeam.py | Fa1c0n35/RootTheBoxs | 4f2a9886c8eedca3039604b93929c8c09866115e | [
"Apache-2.0"
] | 1 | 2019-06-29T08:40:54.000Z | 2019-06-29T08:40:54.000Z | models/SnapshotTeam.py | Fa1c0n35/RootTheBoxs | 4f2a9886c8eedca3039604b93929c8c09866115e | [
"Apache-2.0"
] | null | null | null | models/SnapshotTeam.py | Fa1c0n35/RootTheBoxs | 4f2a9886c8eedca3039604b93929c8c09866115e | [
"Apache-2.0"
] | null | null | null | # -*- coding: utf-8 -*-
"""
Created on Mar 11, 2012
@author: moloch
Copyright 2012 Root the Box
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.
"""
from sqlalchemy import Column, ForeignKey
from sqlalchemy.orm import relationship, backref
from sqlalchemy.types import Integer
from models import dbsession
from models.Team import Team
from models.Relationships import snapshot_team_to_flag, snapshot_team_to_game_level
from models.BaseModels import DatabaseObject
| 29.451613 | 83 | 0.7092 |
6263cf2679c6dfa1a07724e0812c51922a103bc9 | 2,544 | py | Python | src/train.py | DanCh11/virtual-assistant | b6601f20bd851864f4a76dd4c73c8c5266a0014f | [
"MIT"
] | null | null | null | src/train.py | DanCh11/virtual-assistant | b6601f20bd851864f4a76dd4c73c8c5266a0014f | [
"MIT"
] | null | null | null | src/train.py | DanCh11/virtual-assistant | b6601f20bd851864f4a76dd4c73c8c5266a0014f | [
"MIT"
] | null | null | null | import json
import numpy as np
import torch
import torch.nn as nn
from torch.utils.data import Dataset, DataLoader
from model import NeuralNetwork
from nltk_utils import stem, tokenize, bag_of_words
with open('./data/data.json', 'r') as f:
data = json.load(f)
all_words = []
tags = []
xy = []
for intents in data['intents']:
tag = intents['tag']
tags.append(tag)
for pattern in intents['patterns']:
w = tokenize(pattern)
all_words.extend(w)
xy.append((w, tag))
ignore_words = ['?', '!', '.', ',']
all_words = [stem(w) for w in all_words if w not in ignore_words]
all_words = sorted(set(all_words))
tags = sorted(set(tags))
print(tags)
x_train = []
y_train = []
for (pattern_sentence, tag) in xy:
bag = bag_of_words(pattern_sentence, all_words)
x_train.append(bag)
label = tags.index(tag)
y_train.append(label)
x_train = np.array(x_train)
y_train = np.array(y_train)
# Hyperparams
batch_size = 8
hidden_size = 8
output_size = len(tags)
input_size = len(x_train[0])
learning_rate = 0.001
num_epochs = 1000
dataset = ChatDataset()
train_loader = DataLoader(dataset=dataset, batch_size=batch_size, shuffle=True, num_workers=2)
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
model = NeuralNetwork(input_size, hidden_size, output_size).to(device)
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)
for epoch in range(num_epochs):
for (words, labels) in train_loader:
words = words.to(device)
labels = labels.to(device)
outputs = model(words)
loss = criterion(outputs, labels)
optimizer.zero_grad()
loss.backward()
optimizer.step()
if (epoch+1) % 100 == 0:
print(f'epoch [{epoch+1}/{num_epochs}], loss: {loss.item():.4f}')
print(f'final loss: {loss.item():.4f}')
data = {
"model_state": model.state_dict(),
"input_size": input_size,
"output_size": output_size,
"hidden_size": hidden_size,
"all_words": all_words,
"tags": tags
}
FILE = './data/data.pth'
torch.save(data, FILE)
print(f'training complete. file saved to {FILE}')
print(x_train) | 22.315789 | 94 | 0.66195 |
62643e087525aca4ccc614812b7bfd674336652f | 411 | py | Python | pythonexercicios/ex101-funcvotacao.py | marroni1103/exercicios-pyton | 734162cc4b63ed30d754a6efe4c5622baaa1a50b | [
"MIT"
] | null | null | null | pythonexercicios/ex101-funcvotacao.py | marroni1103/exercicios-pyton | 734162cc4b63ed30d754a6efe4c5622baaa1a50b | [
"MIT"
] | null | null | null | pythonexercicios/ex101-funcvotacao.py | marroni1103/exercicios-pyton | 734162cc4b63ed30d754a6efe4c5622baaa1a50b | [
"MIT"
] | null | null | null |
print('-' * 30)
anonasc = int(input('Em que ano voc nasceu? '))
print(voto(anonasc))
| 25.6875 | 52 | 0.610706 |
62665baa3c795d7ea68ea728720da3de2371a899 | 4,289 | py | Python | map_objects/tile.py | matteobarbieri/libtcod-tutorial | 2be59978483d1c754b736a0fe96c9554e9ba8547 | [
"MIT"
] | 1 | 2019-03-09T14:20:51.000Z | 2019-03-09T14:20:51.000Z | map_objects/tile.py | matteobarbieri/libtcod-tutorial | 2be59978483d1c754b736a0fe96c9554e9ba8547 | [
"MIT"
] | null | null | null | map_objects/tile.py | matteobarbieri/libtcod-tutorial | 2be59978483d1c754b736a0fe96c9554e9ba8547 | [
"MIT"
] | null | null | null | import random
import libtcodpy as libtcod
GRAY_PALETTE = [
# libtcod.Color(242, 242, 242),
libtcod.Color(204, 204, 204),
libtcod.Color(165, 165, 165),
libtcod.Color(127, 127, 127),
libtcod.Color(89, 89, 89),
]
class Floor(Tile):
"""
A block representing traversable terrain
"""
class Door(Tile):
"""
A door
"""
# def create(base_color=libtcod.Color(159, 89, 66), color_variance=20):
# # Extract colors
# b, g, r = base_color.b, base_color.g, base_color.r
# # Slightly alter them
# b += random.randint(-color_variance, color_variance)
# b = max(0, b)
# b = min(255, b)
# g += random.randint(-color_variance, color_variance)
# g = max(0, g)
# g = min(255, g)
# r += random.randint(-color_variance, color_variance)
# r = max(0, r)
# r = min(255, r)
# return Wall(libtcod.Color(b, g, r))
| 24.508571 | 75 | 0.569597 |
62668c6700d6f2b1513772cf655859cb23f0af9f | 16,717 | py | Python | src/mrnet/utils/reaction.py | hpatel1567/mrnet | b9989b63ba7aa39cfaf484e78d872ba2cc2d2a20 | [
"BSD-3-Clause-LBNL"
] | 9 | 2020-11-06T23:02:29.000Z | 2021-04-28T01:49:34.000Z | src/mrnet/utils/reaction.py | hpatel1567/mrnet | b9989b63ba7aa39cfaf484e78d872ba2cc2d2a20 | [
"BSD-3-Clause-LBNL"
] | 118 | 2020-11-09T06:49:10.000Z | 2021-07-05T01:16:32.000Z | src/mrnet/utils/reaction.py | hpatel1567/mrnet | b9989b63ba7aa39cfaf484e78d872ba2cc2d2a20 | [
"BSD-3-Clause-LBNL"
] | 8 | 2020-11-06T23:02:36.000Z | 2021-04-20T00:39:52.000Z | # coding: utf-8
# Copyright (c) Pymatgen Development Team.
# Distributed under the terms of the MIT License.
from collections import defaultdict
from typing import Dict, List, Optional, Tuple, Union
import numpy as np
from mip import BINARY, CBC, MINIMIZE, Model, xsum
from mrnet.core.mol_entry import MoleculeEntry
__author__ = "Mingjian Wen"
__maintainer__ = "Mingjian Wen"
__email__ = "mjwen@lbl.gov"
__version__ = "0.2"
__status__ = "Alpha"
__date__ = "April, 2021"
# typing
Bond = Tuple[int, int]
AtomMappingDict = Dict[int, int]
def get_reaction_atom_mapping(
reactants: List[MoleculeEntry],
products: List[MoleculeEntry],
max_bond_change: int = 10,
msg: bool = False,
threads: int = 1,
) -> Tuple[List[AtomMappingDict], List[AtomMappingDict], int]:
"""
Get the atom mapping between the reactants and products of a reaction.
This works for reactions with any number of reactant/product molecules, provided
that the reaction is stoichiometrically balanced. This implementation respects atom
type and the connection between atoms, and ignore other information like bond type
(e.g. single vs double) as well and stereo centers.
There could be multiple mappings (due to, e.g. symmetry in molecules and the fact
that bond type is not considered), and this function only returns one such mapping.
The algorithm treats the reactants as a single disjoint graph (same for the products)
and using integer programming to find the smallest number of bond edits to transform
the reactant graph to the product graph. See the paper in `Reference` for details of
the algorithm.
Args:
reactants: reactant molecules
products: product molecules
max_bond_change: maximum number of allowed bond changes (break and form) between
the reactants and products.
msg: whether to show the integer programming solver running message to stdout.
threads: number of threads for the integer programming solver.
Returns:
reactants_map_number: rdkit style atom map number for the reactant molecules
(starting from 1 in rdkit but from 0 here). Each dict holds the map number
for one molecule {atom_index: map_number}. This should be used together
with `products_map_number` to determine the correspondence of atoms.
Atoms in the reactants and products having the same map number corresponds
to each other in the reaction. For example, given
`reactants_map_number=[{0:3, 1:0}, {0:2, 1:1}]` and
`products_map_number = [{0:1}, {0:0, 1:2, 2:3}]`, we can conclude that
atom 0 in reactant molecule 0 maps to atom 2 in product molecule 1 (both
with map number 3);
atom 1 in reactant molecule 0 maps to atom 0 in product molecule 1 (both
with map number 0);
atom 0 in reactant molecule 1 maps to atom 1 in product molecule 1 (both
with map number 2);
atom 1 in reactant molecule 1 maps to atom 0 in product molecule 0 both
with map number 1).
products_map_number: rdkit style atom map number for the product molecules.
See `reactants_map_number` for more.
num_bond_change: number of changed bond in the reaction
References:
`Stereochemically Consistent Reaction Mapping and Identification of Multiple
Reaction Mechanisms through Integer Linear Optimization`,
J. Chem. Inf. Model. 2012, 52, 8492, https://doi.org/10.1021/ci200351b
"""
# preliminary check
# check 1: reactants and products have the same atom counts
rct_species = defaultdict(int) # type: Dict[str, int]
prdt_species = defaultdict(int) # type: Dict[str, int]
for m in reactants:
for s in m.species:
rct_species[s] += 1
for m in products:
for s in m.species:
prdt_species[s] += 1
if rct_species != prdt_species:
raise ReactionMappingError(
"Expect reactants and products to have the same atom count, "
f"but got {dict(rct_species)} and {dict(prdt_species)}."
)
# check 2: number of bond change smaller than allowed maximum
# This only checks the number of bonds and thus actual num changes could be larger,
# which will be checked later.
num_bond_change = abs(
sum(len(m.bonds) for m in reactants) - sum(len(m.bonds) for m in products)
)
if num_bond_change > max_bond_change:
raise ReactionMappingError(
f"Number of changed bond is at least {num_bond_change}, larger than allowed "
f"maximum {max_bond_change}"
)
# local and global atom index mapping
(
reactant_species,
reactant_bonds,
_,
reactant_idx_mapping,
) = get_local_global_atom_index_mapping(reactants)
(
product_species,
product_bonds,
_,
product_idx_mapping,
) = get_local_global_atom_index_mapping(products)
# solve integer programming problem to get atom mapping
if len(reactant_bonds) != 0 and len(product_bonds) != 0:
num_bond_change, r2p_mapping, p2r_mapping = solve_integer_programing(
reactant_species,
product_species,
reactant_bonds,
product_bonds,
msg,
threads,
)
else:
# corner case that integer programming cannot handle
out = get_atom_mapping_no_bonds(
reactant_species, product_species, reactant_bonds, product_bonds
)
num_bond_change, r2p_mapping, p2r_mapping = out # type: ignore
# final check
if num_bond_change > max_bond_change:
raise ReactionMappingError(
f"Number of bond change {num_bond_change} larger than allowed maximum number "
f"of bond change {max_bond_change}."
)
if None in r2p_mapping:
global_idx = r2p_mapping.index(None)
mol_idx, atom_idx = reactant_idx_mapping[global_idx]
raise ReactionMappingError(
f"Cannot find mapping for atom {atom_idx} of reactant molecule {mol_idx}."
)
if None in p2r_mapping:
global_idx = p2r_mapping.index(None)
mol_idx, atom_idx = product_idx_mapping[global_idx]
raise ReactionMappingError(
f"Cannot find mapping for atom {atom_idx} of product molecule {mol_idx}."
)
# Everything is alright, create atom map number.
# Atoms in reactants will have their global index as map number.
# Map number for atoms in products are determined accordingly based on the results
# of integer programming
reactants_map_number = [
{} for _ in range(len(reactants))
] # type: List[Dict[int,int]]
products_map_number = [
{} for _ in range(len(products))
] # type: List[Dict[int,int]]
for rct_idx, prdt_idx in enumerate(r2p_mapping):
map_number = rct_idx
mol_idx, atom_idx = reactant_idx_mapping[rct_idx] # type: ignore
reactants_map_number[mol_idx][atom_idx] = map_number
mol_idx, atom_idx = product_idx_mapping[prdt_idx] # type: ignore
products_map_number[mol_idx][atom_idx] = map_number
return reactants_map_number, products_map_number, num_bond_change
def get_local_global_atom_index_mapping(
molecules: List[MoleculeEntry],
) -> Tuple[List[str], List[Bond], List[List[int]], List[Tuple[int, int]]]:
"""
Map the local and global indices of atoms in a sequence of molecules.
This is a utility function for `get_reaction_atom_mapping()`.
Think of this as combining a sequence of molecules into a single molecule and then
relabelling the atom index in each mol to form a consecutive global index in the
combined molecule.
Local indices for atoms in each mol are [0, ..., N-1], where N is the number of
atoms in the corresponding atoms.
Global indices for atoms in the 1st mol is [0, ..., N1-1],
in the 2nd mol is [N1, ..., N1+N2-1],
in the 3rd mol is [N1+N2, ..., N1+N2+N3-1]
...
where N1, N2, and N3 are the number of atoms in molecules 1, 2, and 3.
Args:
molecules: A sequence of molecule entry.
Returns:
global_species: species of atoms in the combined molecule.
global_bonds: all bonds in the combine molecule; each bond is specified by a
tuple of global atom index.
local_to_global: local atom index to global atom index. Each inner list holds
the global atom indexes of a molecule. E.g. local_to_global[0][2] gives 4,
meaning atom 2 of molecule 0 has a global index of 4.
global_to_local: global atom index to local atom index. Each tuple
(mol_index, atom_index) is for one atom, with `mol_index` the index of the
molecule from which the atom is from and `atom_index` the local index of the
atom in the molecule. E.g. global[4] gives a tuple (0, 2), meaning atom with
global index 4 corresponds to atom 2 in molecule 0.
"""
global_species = []
global_bonds = []
local_to_global = []
global_to_local = []
n = 0
for i, m in enumerate(molecules):
global_species.extend(m.species)
bonds = [(b[0] + n, b[1] + n) for b in m.bonds]
global_bonds.extend(bonds)
mp_l2g = [j + n for j in range(m.num_atoms)]
local_to_global.append(mp_l2g)
mp_g2l = [(i, j) for j in range(m.num_atoms)]
global_to_local.extend(mp_g2l)
n += m.num_atoms
return global_species, global_bonds, local_to_global, global_to_local
def solve_integer_programing(
reactant_species: List[str],
product_species: List[str],
reactant_bonds: List[Bond],
product_bonds: List[Bond],
msg: bool = True,
threads: Optional[int] = None,
) -> Tuple[int, List[Union[int, None]], List[Union[int, None]]]:
"""
Solve an integer programming problem to get atom mapping between reactants and
products.
This is a utility function for `get_reaction_atom_mapping()`.
Args:
reactant_species: species string of reactant atoms
product_species: species string of product atoms
reactant_bonds: bonds in reactant
product_bonds: bonds in product
msg: whether to show the solver running message to stdout.
threads: number of threads for the solver. `None` to use default.
Returns:
objective: minimized objective value. This corresponds to the number of changed
bonds (both broken and formed) in the reaction.
r2p_mapping: mapping of reactant atom to product atom, e.g. r2p_mapping[0]
giving 3 means that reactant atom 0 maps to product atom 3. A value of
`None` means a mapping cannot be found for the reactant atom.
p2r_mapping: mapping of product atom to reactant atom, e.g. p2r_mapping[3]
giving 0 means that product atom 3 maps to reactant atom 0. A value of
`None` means a mapping cannot be found for the product atom.
Reference:
`Stereochemically Consistent Reaction Mapping and Identification of Multiple
Reaction Mechanisms through Integer Linear Optimization`,
J. Chem. Inf. Model. 2012, 52, 8492, https://doi.org/10.1021/ci200351b
"""
atoms = list(range(len(reactant_species)))
# init model and variables
model = Model(name="Reaction_Atom_Mapping", sense=MINIMIZE, solver_name=CBC)
model.emphasis = 1
if threads is not None:
model.threads = threads
if msg:
model.verbose = 1
else:
model.verbose = 0
y_vars = {
(i, k): model.add_var(var_type=BINARY, name=f"y_{i}_{k}")
for i in atoms
for k in atoms
}
alpha_vars = {
(i, j, k, l): model.add_var(var_type=BINARY, name=f"alpha_{i}_{j}_{k}_{l}")
for (i, j) in reactant_bonds
for (k, l) in product_bonds
}
# add constraints
# constraint 2: each atom in the reactants maps to exactly one atom in the products
# constraint 3: each atom in the products maps to exactly one atom in the reactants
for i in atoms:
model += xsum([y_vars[(i, k)] for k in atoms]) == 1
for k in atoms:
model += xsum([y_vars[(i, k)] for i in atoms]) == 1
# constraint 4: allows only atoms of the same type to map to one another
for i in atoms:
for k in atoms:
if reactant_species[i] != product_species[k]:
model += y_vars[(i, k)] == 0
# constraints 5 and 6: define each alpha_ijkl variable, permitting it to take the
# value of one only if the reactant bond (i,j) maps to the product bond (k,l)
for (i, j) in reactant_bonds:
for (k, l) in product_bonds:
model += alpha_vars[(i, j, k, l)] <= y_vars[(i, k)] + y_vars[(i, l)]
model += alpha_vars[(i, j, k, l)] <= y_vars[(j, k)] + y_vars[(j, l)]
# create objective
obj1 = xsum(
1 - xsum(alpha_vars[(i, j, k, l)] for (k, l) in product_bonds)
for (i, j) in reactant_bonds
)
obj2 = xsum(
1 - xsum(alpha_vars[(i, j, k, l)] for (i, j) in reactant_bonds)
for (k, l) in product_bonds
)
obj = obj1 + obj2
# solve the problem
try:
model.objective = obj
model.optimize()
except Exception:
raise ReactionMappingError("Failed solving integer programming.")
if not model.num_solutions:
raise ReactionMappingError("Failed solving integer programming.")
# get atom mapping between reactant and product
r2p_mapping = [None for _ in atoms] # type: List[Union[int, None]]
p2r_mapping = [None for _ in atoms] # type: List[Union[int, None]]
for (i, k), v in y_vars.items():
if v.x == 1:
r2p_mapping[i] = k
p2r_mapping[k] = i
objective = model.objective_value # type: int
return objective, r2p_mapping, p2r_mapping
def get_atom_mapping_no_bonds(
reactant_species: List[str],
product_species: List[str],
reactant_bonds: List[Bond],
product_bonds: List[Bond],
) -> Tuple[int, List[int], List[int]]:
"""
Get the atom mapping for reaction where there is no bonds in either the reactants
or products. For example, a reaction C-O -> C + O.
This is a complement function to `solve_integer_programing()`, which cannot deal
with the case where there is no bonds in the reactants or products.
The arguments and returns are the same as `solve_integer_programing()`.
"""
if len(reactant_bonds) != 0 and len(product_bonds) != 0:
raise ReactionMappingError(
"Expect either reactants or products has 0 bonds, but reactants has "
f"{len(reactant_bonds)} and products has {len(product_bonds)}."
)
# the only thing we need to do is to match species
product_species_to_index = defaultdict(list)
for i, s in enumerate(product_species):
product_species_to_index[s].append(i)
r2p_mapping = []
for s in reactant_species:
r2p_mapping.append(product_species_to_index[s].pop())
p2r_mapping = [r2p_mapping.index(i) for i in range(len(product_species))]
# objective, i.e. number of bond change
objective = abs(len(reactant_bonds) - len(product_bonds))
return objective, r2p_mapping, p2r_mapping
def generate_atom_mapping_1_1(
node_mapping: Dict[int, int]
) -> Tuple[AtomMappingDict, AtomMappingDict]:
"""
Generate rdkit style atom mapping for reactions with one reactant and one product.
For example, given `node_mapping = {0:2, 1:0, 2:1}`, which means atoms 0, 1,
and 2 in the reactant maps to atoms 2, 0, and 1 in the product, respectively,
the atom mapping number for reactant atoms are simply set to their index,
and the atom mapping number for product atoms are determined accordingly.
As a result, this function gives: `({0:0, 1:1, 2:2}, {0:1 1:2 2:0})` as the output.
Atoms in the reactant and product with the same atom mapping number
(keys in the dicts) are corresponding to each other.
Args:
node_mapping: node mapping from reactant to product
Returns:
reactant_atom_mapping: rdkit style atom mapping for the reactant
product_atom_mapping: rdkit style atom mapping for the product
"""
reactant_atom_mapping = {k: k for k in node_mapping}
product_atom_mapping = {v: k for k, v in node_mapping.items()}
return reactant_atom_mapping, product_atom_mapping
| 38.166667 | 90 | 0.664413 |
6266929bceaa00edbf464b5a4d2470f14089186d | 16,271 | py | Python | test/test_info_api.py | fattureincloud/fattureincloud-python-sdk | f3a40fac345751014ea389680efdaef90f03bac1 | [
"MIT"
] | 2 | 2022-02-17T08:33:17.000Z | 2022-03-22T09:27:00.000Z | test/test_info_api.py | fattureincloud/fattureincloud-python-sdk | f3a40fac345751014ea389680efdaef90f03bac1 | [
"MIT"
] | null | null | null | test/test_info_api.py | fattureincloud/fattureincloud-python-sdk | f3a40fac345751014ea389680efdaef90f03bac1 | [
"MIT"
] | null | null | null | """
Fatture in Cloud API v2 - API Reference
Connect your software with Fatture in Cloud, the invoicing platform chosen by more than 400.000 businesses in Italy. The Fatture in Cloud API is based on REST, and makes possible to interact with the user related data prior authorization via OAuth2 protocol. # noqa: E501
The version of the OpenAPI document: 2.0.9
Contact: info@fattureincloud.it
Generated by: https://openapi-generator.tech
"""
import unittest
import fattureincloud_python_sdk
from fattureincloud_python_sdk.rest import RESTResponse
import functions
from fattureincloud_python_sdk.api.info_api import InfoApi
from fattureincloud_python_sdk.model.city import City
from fattureincloud_python_sdk.model.currency import Currency
from fattureincloud_python_sdk.model.document_template import DocumentTemplate
from fattureincloud_python_sdk.model.language import Language
from fattureincloud_python_sdk.model.list_archive_categories_response import ListArchiveCategoriesResponse
from fattureincloud_python_sdk.model.list_cities_response import ListCitiesResponse
from fattureincloud_python_sdk.model.detailed_country import DetailedCountry
from fattureincloud_python_sdk.model.list_detailed_countries_response import ListDetailedCountriesResponse
from fattureincloud_python_sdk.model.list_cost_centers_response import ListCostCentersResponse
from fattureincloud_python_sdk.model.list_countries_response import ListCountriesResponse
from fattureincloud_python_sdk.model.list_currencies_response import ListCurrenciesResponse
from fattureincloud_python_sdk.model.list_delivery_notes_default_causals_response import ListDeliveryNotesDefaultCausalsResponse
from fattureincloud_python_sdk.model.list_languages_response import ListLanguagesResponse
from fattureincloud_python_sdk.model.list_payment_accounts_response import ListPaymentAccountsResponse
from fattureincloud_python_sdk.model.list_payment_methods_response import ListPaymentMethodsResponse
from fattureincloud_python_sdk.model.list_product_categories_response import ListProductCategoriesResponse
from fattureincloud_python_sdk.model.list_received_document_categories_response import ListReceivedDocumentCategoriesResponse
from fattureincloud_python_sdk.model.list_revenue_centers_response import ListRevenueCentersResponse
from fattureincloud_python_sdk.model.list_templates_response import ListTemplatesResponse
from fattureincloud_python_sdk.model.list_units_of_measure_response import ListUnitsOfMeasureResponse
from fattureincloud_python_sdk.model.list_vat_types_response import ListVatTypesResponse
from fattureincloud_python_sdk.model.payment_account import PaymentAccount
from fattureincloud_python_sdk.model.payment_account_type import PaymentAccountType
from fattureincloud_python_sdk.model.payment_method import PaymentMethod
from fattureincloud_python_sdk.model.payment_method_details import PaymentMethodDetails
from fattureincloud_python_sdk.model.payment_method_type import PaymentMethodType
from fattureincloud_python_sdk.model.vat_type import VatType
if __name__ == '__main__':
unittest.main()
| 49.606707 | 587 | 0.685698 |
62691bca9ef85cd31b36e1e397faed73d833bd04 | 2,992 | py | Python | tests/test_year_2018.py | l0pht511/jpholiday | 083145737b61fad3420c066968c4329d17dc3baf | [
"MIT"
] | 179 | 2017-10-05T12:41:10.000Z | 2022-03-24T22:18:25.000Z | tests/test_year_2018.py | l0pht511/jpholiday | 083145737b61fad3420c066968c4329d17dc3baf | [
"MIT"
] | 17 | 2018-10-23T00:51:13.000Z | 2021-11-22T11:40:06.000Z | tests/test_year_2018.py | l0pht511/jpholiday | 083145737b61fad3420c066968c4329d17dc3baf | [
"MIT"
] | 17 | 2018-10-19T11:13:07.000Z | 2022-01-29T08:05:56.000Z | # coding: utf-8
import datetime
import unittest
import jpholiday
| 53.428571 | 94 | 0.684492 |
6269876471cdc3a3de7a8b8ea2665c1065be9cdf | 222 | py | Python | src/server_3D/API/Rice/miscellaneous/tools.py | robertpardillo/Funnel | f45e419f55e085bbb95e17c47b4c94a7c625ba9b | [
"MIT"
] | 1 | 2021-05-18T16:10:49.000Z | 2021-05-18T16:10:49.000Z | src/server_3D/API/Rice/miscellaneous/tools.py | robertpardillo/Funnel | f45e419f55e085bbb95e17c47b4c94a7c625ba9b | [
"MIT"
] | null | null | null | src/server_3D/API/Rice/miscellaneous/tools.py | robertpardillo/Funnel | f45e419f55e085bbb95e17c47b4c94a7c625ba9b | [
"MIT"
] | null | null | null |
import numpy
__author__ = 'roberto'
| 17.076923 | 35 | 0.581081 |
6269ffcac7da3b6435494d0d70dbe0aa69f6f55f | 324 | py | Python | conjur_api/__init__.py | cyberark/conjur-api-python | 7dd1819bf68042620a06f38e395c3eb2989202a9 | [
"Apache-2.0"
] | 1 | 2022-03-09T18:25:29.000Z | 2022-03-09T18:25:29.000Z | conjur_api/__init__.py | cyberark/conjur-api-python | 7dd1819bf68042620a06f38e395c3eb2989202a9 | [
"Apache-2.0"
] | null | null | null | conjur_api/__init__.py | cyberark/conjur-api-python | 7dd1819bf68042620a06f38e395c3eb2989202a9 | [
"Apache-2.0"
] | null | null | null | """
conjur_api
Package containing classes that are responsible for communicating with the Conjur server
"""
__version__ = "0.0.5"
from conjur_api.client import Client
from conjur_api.interface import CredentialsProviderInterface
from conjur_api import models
from conjur_api import errors
from conjur_api import providers
| 24.923077 | 88 | 0.83642 |
626aa70e6e3d3a3eb14c59bc2e95240dc23ccc35 | 9,346 | py | Python | examples/test_BoxCutter.py | pompiduskus/pybox2d | 4393bc93df4828267d2143327abd76de6f146750 | [
"Zlib"
] | null | null | null | examples/test_BoxCutter.py | pompiduskus/pybox2d | 4393bc93df4828267d2143327abd76de6f146750 | [
"Zlib"
] | null | null | null | examples/test_BoxCutter.py | pompiduskus/pybox2d | 4393bc93df4828267d2143327abd76de6f146750 | [
"Zlib"
] | null | null | null | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# C++ version Copyright (c) 2006-2007 Erin Catto http://www.box2d.org
# Python version by Ken Lauer / sirkne at gmail dot com
#
# This software is provided 'as-is', without any express or implied
# warranty. In no event will the authors be held liable for any damages
# arising from the use of this software.
# Permission is granted to anyone to use this software for any purpose,
# including commercial applications, and to alter it and redistribute it
# freely, subject to the following restrictions:
# 1. The origin of this software must not be misrepresented; you must not
# claim that you wrote the original software. If you use this software
# in a product, an acknowledgment in the product documentation would be
# appreciated but is not required.
# 2. Altered source versions must be plainly marked as such, and must not be
# misrepresented as being the original software.
# 3. This notice may not be removed or altered from any source distribution.
# Original C++ version by Daid
# http://www.box2d.org/forum/viewtopic.php?f=3&t=1473
# - Written for pybox2d 2.1 by Ken
from framework import *
from math import sin, cos, pi
import sys
LASER_HALF_WIDTH=2
LASER_SPLIT_SIZE=0.1
LASER_SPLIT_TAG='can_cut'
if __name__=="__main__":
main(BoxCutter)
| 35.267925 | 105 | 0.591162 |
626b51aefb27ae8f4702b720697fa00e55d0360c | 1,309 | py | Python | robot_simulator/grid/positioning.py | darshikaf/toy-robot-simulator | 408d160033728d65e9bac376d3af7fc84c520f31 | [
"MIT"
] | null | null | null | robot_simulator/grid/positioning.py | darshikaf/toy-robot-simulator | 408d160033728d65e9bac376d3af7fc84c520f31 | [
"MIT"
] | null | null | null | robot_simulator/grid/positioning.py | darshikaf/toy-robot-simulator | 408d160033728d65e9bac376d3af7fc84c520f31 | [
"MIT"
] | null | null | null | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import annotations
import math
| 27.270833 | 71 | 0.578304 |
626ba702d88f0299279f562b39bddc29df5ddcaa | 6,128 | py | Python | src/utils/zarr_to_netcdf.py | jhkennedy/itslive | 68b89b337548fe4e86a3d066c3fb2e4c2aaeed70 | [
"MIT"
] | 8 | 2021-02-19T02:29:29.000Z | 2021-11-10T05:26:30.000Z | src/utils/zarr_to_netcdf.py | jhkennedy/itslive | 68b89b337548fe4e86a3d066c3fb2e4c2aaeed70 | [
"MIT"
] | 11 | 2021-03-29T02:15:38.000Z | 2021-11-18T23:29:33.000Z | src/utils/zarr_to_netcdf.py | jhkennedy/itslive | 68b89b337548fe4e86a3d066c3fb2e4c2aaeed70 | [
"MIT"
] | 3 | 2021-12-06T06:05:34.000Z | 2022-03-13T16:44:44.000Z | """
Script to convert Zarr store to the NetCDF format file.
Usage:
python zarr_to_netcdf.py -i ZarrStoreName -o NetCDFFileName
Convert Zarr data stored in ZarrStoreName to the NetCDF file NetCDFFileName.
"""
import argparse
import timeit
import warnings
import xarray as xr
from itscube_types import Coords, DataVars
if __name__ == '__main__':
warnings.filterwarnings('ignore')
# Command-line arguments parser
parser = argparse.ArgumentParser(epilog='\n'.join(__doc__.split('\n')[1:]),
formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument('-i', '--input', type=str, required=True,
help="Input Zarr store directory.")
parser.add_argument('-o', '--output', type=str, required=True,
help="NetCDF filename to store data to.")
parser.add_argument('-e', '--engine', type=str, required=False, default='h5netcdf',
help="NetCDF engine to use to store NetCDF data to the file.")
args = parser.parse_args()
start_time = timeit.default_timer()
# Don't decode time delta's as it does some internal conversion based on
# provided units
ds_zarr = xr.open_zarr(args.input, decode_timedelta=False)
# print(f"mid_date: {ds_zarr.mid_date}")
# print(f"x: {ds_zarr.x.attrs}")
# print(f"y: {ds_zarr.y.attrs}")
# This is just a work around for coordinates attributes not being written
# to the Zarr store (submit xarray ticket?)
ds_zarr.mid_date.attrs = {
DataVars.STD_NAME: Coords.STD_NAME[Coords.MID_DATE],
DataVars.DESCRIPTION_ATTR: Coords.DESCRIPTION[Coords.MID_DATE]
}
ds_zarr.x.attrs = {
DataVars.STD_NAME: Coords.STD_NAME[Coords.X],
DataVars.DESCRIPTION_ATTR: Coords.DESCRIPTION[Coords.X]
}
ds_zarr.y.attrs = {
DataVars.STD_NAME: Coords.STD_NAME[Coords.Y],
DataVars.DESCRIPTION_ATTR: Coords.DESCRIPTION[Coords.Y]
}
time_delta = timeit.default_timer() - start_time
print(f"Read Zarr {args.input} (took {time_delta} seconds)")
compression = {"zlib": True, "complevel": 2, "shuffle": True}
encoding = {}
encoding = {
'map_scale_corrected': {'_FillValue': 0.0, 'dtype': 'byte'},
'interp_mask': {'_FillValue': 0.0, 'dtype': 'ubyte'},
'flag_stable_shift': {'dtype': 'long'},
'chip_size_height': {'_FillValue': 0.0, 'dtype': 'ushort'},
'chip_size_width': {'_FillValue': 0.0, 'dtype': 'ushort'},
'v_error': {'_FillValue': -32767.0, 'dtype': 'short'},
'v': {'_FillValue': -32767.0, 'dtype': 'short'},
'vx': {'_FillValue': -32767.0, 'dtype': 'short'},
'vx_error': {'_FillValue': -32767.0, 'dtype': 'double'},
'vx_stable_shift': {'_FillValue': -32767.0, 'dtype': 'double'},
'vy': {'_FillValue': -32767.0, 'dtype': 'short'},
'vy_error': {'_FillValue': -32767.0, 'dtype': 'double'},
'vy_stable_shift': {'_FillValue': -32767.0, 'dtype': 'double'},
'va': {'_FillValue': -32767.0, 'dtype': 'short'},
'va_error': {'_FillValue': -32767.0, 'dtype': 'double'},
'va_stable_shift': {'_FillValue': -32767.0, 'dtype': 'double'},
'vr': {'_FillValue': -32767.0, 'dtype': 'short'},
'vr_error': {'_FillValue': -32767.0, 'dtype': 'double'},
'vr_stable_shift': {'_FillValue': -32767.0, 'dtype': 'double'},
'vxp': {'_FillValue': -32767.0, 'dtype': 'short'},
'vxp_error': {'_FillValue': -32767.0, 'dtype': 'double'},
'vxp_stable_shift': {'_FillValue': -32767.0, 'dtype': 'double'},
'vyp': {'_FillValue': -32767.0, 'dtype': 'short'},
'vyp_error': {'_FillValue': -32767.0, 'dtype': 'double'},
'vyp_stable_shift': {'_FillValue': -32767.0, 'dtype': 'double'},
'vp': {'_FillValue': -32767.0, 'dtype': 'short'},
'vp_error': {'_FillValue': -32767.0, 'dtype': 'short'},
'acquisition_img1': {'units': 'days since 1970-01-01'},
'acquisition_img2': {'units': 'days since 1970-01-01'},
'date_center': {'_FillValue': None, 'units': 'days since 1970-01-01'},
'mid_date': {'_FillValue': None, 'units': 'days since 1970-01-01'},
'autoRIFT_software_version': {'_FillValue': None},
'stable_count': {'_FillValue': None},
'date_dt': {'_FillValue': None},
'x': {'_FillValue': None},
'y': {'_FillValue': None}
}
encode_data_vars = (
'v',
'v_error',
'map_scale_corrected',
'vx',
'vx_error',
'vx_stable_shift',
'flag_stable_shift',
'vy',
'vy_error',
'vy_stable_shift',
'chip_size_height',
'chip_size_width',
'interp_mask',
'va',
'va_error',
'va_stable_shift',
'vp',
'vp_error',
'vr',
'vr_error',
'vr_stable_shift',
'vxp',
'vxp_error',
'vxp_stable_shift',
'vyp',
'vyp_error',
'vyp_stable_shift',
'mission_img1',
'sensor_img1',
'satellite_img1',
'acquisition_img1',
'mission_img2',
'sensor_img2',
'satellite_img2',
'acquisition_img2',
'date_dt',
'date_center',
'roi_valid_percentage',
'autoRIFT_software_version'
)
# Set up compression for each of the data variables
for each in encode_data_vars:
encoding.setdefault(each, {}).update(compression)
start_time = timeit.default_timer()
ds_zarr.to_netcdf(
args.output,
engine=args.engine,
encoding = encoding
)
time_delta = timeit.default_timer() - start_time
print(f"Wrote dataset to NetCDF file {args.output} (took {time_delta} seconds)")
| 39.535484 | 90 | 0.557115 |
626c09d5e7442d6e48e408bb35182589e7d6f723 | 87 | py | Python | tests/periodicities/Business_Day/Cycle_Business_Day_200_B_24.py | jmabry/pyaf | afbc15a851a2445a7824bf255af612dc429265af | [
"BSD-3-Clause"
] | null | null | null | tests/periodicities/Business_Day/Cycle_Business_Day_200_B_24.py | jmabry/pyaf | afbc15a851a2445a7824bf255af612dc429265af | [
"BSD-3-Clause"
] | 1 | 2019-11-30T23:39:38.000Z | 2019-12-01T04:34:35.000Z | tests/periodicities/Business_Day/Cycle_Business_Day_200_B_24.py | jmabry/pyaf | afbc15a851a2445a7824bf255af612dc429265af | [
"BSD-3-Clause"
] | null | null | null | import pyaf.tests.periodicities.period_test as per
per.buildModel((24 , 'B' , 200));
| 17.4 | 50 | 0.724138 |
626c365969d9ff73eed75430ed790344b66ecdd6 | 932 | py | Python | conanfile.py | maurodelazeri/conan-cpp-httplib | 1a6ce1f1a79eb43071e8dc1bb6f84fba010aabd3 | [
"MIT"
] | null | null | null | conanfile.py | maurodelazeri/conan-cpp-httplib | 1a6ce1f1a79eb43071e8dc1bb6f84fba010aabd3 | [
"MIT"
] | null | null | null | conanfile.py | maurodelazeri/conan-cpp-httplib | 1a6ce1f1a79eb43071e8dc1bb6f84fba010aabd3 | [
"MIT"
] | 1 | 2019-12-03T19:35:48.000Z | 2019-12-03T19:35:48.000Z | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from conans import ConanFile, CMake, tools
import os
| 32.137931 | 88 | 0.651288 |
626ca157c2ac9db263365279311bac86dc999674 | 328 | py | Python | backmarker/api/viewsets/driver_viewset.py | jmp/backmarker | e12a094d92dec798ad10aa8890fabe84f946c303 | [
"MIT"
] | null | null | null | backmarker/api/viewsets/driver_viewset.py | jmp/backmarker | e12a094d92dec798ad10aa8890fabe84f946c303 | [
"MIT"
] | null | null | null | backmarker/api/viewsets/driver_viewset.py | jmp/backmarker | e12a094d92dec798ad10aa8890fabe84f946c303 | [
"MIT"
] | null | null | null | from rest_framework.viewsets import ReadOnlyModelViewSet
from backmarker.api.serializers.driver_serializer import DriverSerializer
from backmarker.models.driver import Driver
| 29.818182 | 73 | 0.829268 |
626cc4db6e624b921fb50a7db02432aa617a9dbd | 215 | py | Python | shell/response.py | YorkSu/deepgo | 2f22ad50d2958a4f1c7dfc0af6fcd448f5e7e18d | [
"Apache-2.0"
] | null | null | null | shell/response.py | YorkSu/deepgo | 2f22ad50d2958a4f1c7dfc0af6fcd448f5e7e18d | [
"Apache-2.0"
] | null | null | null | shell/response.py | YorkSu/deepgo | 2f22ad50d2958a4f1c7dfc0af6fcd448f5e7e18d | [
"Apache-2.0"
] | null | null | null | # -*- coding: utf-8 -*-
"""Response
======
Response Class
"""
from deepgo.core.kernel.popo import VO
| 11.315789 | 38 | 0.609302 |
626d65ee956ce1cac3af4218ef107258e83fd84e | 4,793 | py | Python | src/python/pants/option/options_fingerprinter_test.py | bastianwegge/pants | 43f0b90d41622bee0ed22249dbaffb3ff4ad2eb2 | [
"Apache-2.0"
] | 1,806 | 2015-01-05T07:31:00.000Z | 2022-03-31T11:35:41.000Z | src/python/pants/option/options_fingerprinter_test.py | bastianwegge/pants | 43f0b90d41622bee0ed22249dbaffb3ff4ad2eb2 | [
"Apache-2.0"
] | 9,565 | 2015-01-02T19:01:59.000Z | 2022-03-31T23:25:16.000Z | src/python/pants/option/options_fingerprinter_test.py | ryanking/pants | e45b00d2eb467b599966bca262405a5d74d27bdd | [
"Apache-2.0"
] | 443 | 2015-01-06T20:17:57.000Z | 2022-03-31T05:28:17.000Z | # Copyright 2015 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from pathlib import Path
import pytest
from pants.option.custom_types import (
DictValueComponent,
ListValueComponent,
UnsetBool,
dict_with_files_option,
dir_option,
file_option,
)
from pants.option.options_fingerprinter import OptionsFingerprinter
from pants.testutil.rule_runner import RuleRunner
| 31.741722 | 99 | 0.636345 |
626e4c17d238ffdd4b719fcf03cef903734ecb10 | 201 | py | Python | secondstring.py | Kokouvi/reversorder | 157e39eaf424d816715080dbce0850670836e8fd | [
"MIT"
] | null | null | null | secondstring.py | Kokouvi/reversorder | 157e39eaf424d816715080dbce0850670836e8fd | [
"MIT"
] | null | null | null | secondstring.py | Kokouvi/reversorder | 157e39eaf424d816715080dbce0850670836e8fd | [
"MIT"
] | null | null | null | str = "The quick brown fox jumps over the lazy dog." # initial string
reversed = "".join(reversed(str)) #.join() method merges all of the charactera
print(reversed[0:43:2]) # print the reversed string
| 50.25 | 78 | 0.731343 |
626e9153453be95674085a5a9f6b92944cbfbd68 | 1,660 | py | Python | image_extractor.py | IstoVisio/script_image_extractor | dda8c8bb96a16d1ffe5d52af198b66bd619edc4f | [
"MIT"
] | null | null | null | image_extractor.py | IstoVisio/script_image_extractor | dda8c8bb96a16d1ffe5d52af198b66bd619edc4f | [
"MIT"
] | null | null | null | image_extractor.py | IstoVisio/script_image_extractor | dda8c8bb96a16d1ffe5d52af198b66bd619edc4f | [
"MIT"
] | null | null | null | import os
import sys
import syglass as sy
from syglass import pyglass
import numpy as np
import tifffile
import subprocess
if __name__== "__main__":
main() | 29.642857 | 79 | 0.704217 |
627004517552f92e1e2ec8fa749130e02a42b77f | 7,531 | py | Python | scaffoldgraph/analysis/enrichment.py | trumanw/ScaffoldGraph | a594e5c5effe6c5e45c0061a235ccbeb64e416f9 | [
"MIT"
] | 121 | 2019-12-12T15:30:16.000Z | 2022-02-28T02:00:54.000Z | scaffoldgraph/analysis/enrichment.py | trumanw/ScaffoldGraph | a594e5c5effe6c5e45c0061a235ccbeb64e416f9 | [
"MIT"
] | 8 | 2020-04-04T15:37:26.000Z | 2021-11-17T07:30:31.000Z | scaffoldgraph/analysis/enrichment.py | trumanw/ScaffoldGraph | a594e5c5effe6c5e45c0061a235ccbeb64e416f9 | [
"MIT"
] | 28 | 2019-12-16T11:58:53.000Z | 2021-11-19T09:57:46.000Z | """
scaffoldgraph.analysis.enrichment
Module contains an implementation of Compound Set Enrichment from the papers:
- Compound Set Enrichment: A Novel Approach to Analysis of Primary HTS Data.
- Mining for bioactive scaffolds with scaffold networks: Improved compound set enrichment from primary screening data.
"""
from networkx import set_node_attributes
from scipy.stats import ks_2samp, binom_test
from loguru import logger
def _btp(scaffoldgraph, activity_key, alternative, pd):
"""CSE - binomial test (used in cse functions)."""
result, active, total = {}, 0, 0
for m, a in scaffoldgraph.get_molecule_nodes(activity_key):
if int(a) == 1:
active += 1
total += 1
if pd is None:
pd = active / total
logger.debug(f'(BTP) Total: {total}, Active: {active}, pd: {pd}')
for scaffold in scaffoldgraph.get_scaffold_nodes():
mols, acts = zip(*scaffoldgraph.get_molecules_for_scaffold(scaffold, activity_key))
N, K = len(mols), acts.count(1)
pval = binom_test(K, N, pd, alternative=alternative)
logger.debug(f'(BTP) {scaffold}, {K}, {N}, {pval}')
result[scaffold] = {'pval': pval, '_active': K, '_total': N}
return result
def _ksp(scaffoldgraph, activity_key, alternative):
"""CSE - Kolmogorov-Smirnov test (used in cse functions)."""
result, background = {}, []
for _, activity in scaffoldgraph.get_molecule_nodes(activity_key):
background.append(activity)
for scaffold in scaffoldgraph.get_scaffold_nodes():
mols, acts = zip(*scaffoldgraph.get_molecules_for_scaffold(scaffold, activity_key))
N = len(mols)
dmax, pval = ks_2samp(acts, background, alternative, 'auto')
logger.debug(f'(KSP) {scaffold}, {N}, {dmax}, {pval}')
result[scaffold] = {'pval': pval, 'dmax': dmax, '_total': N}
return result
def bonferroni_correction(scaffoldgraph, crit):
"""Returns bonferroni corrected significance level for each hierarchy.
Parameters
----------
scaffoldgraph : ScaffoldGraph
A ScaffoldGraph object to query.
crit : float
The critical significance value to apply bonferroni correction at
each scaffold hierarchy.
Returns
-------
dict
A dictionary containing the corrected critical significance value
at each scaffold hierarchy {hierarchy: crit}.
"""
hier = scaffoldgraph.get_hierarchy_sizes()
return {k: crit / v for k, v in hier.items()}
def calc_scaffold_enrichment(scaffoldgraph, activity, mode='ks', alternative='greater', p=None):
"""
Calculate scaffold enrichment using the Kolmogorov-Smirnov or binomal test.
Parameters
----------
scaffoldgraph : ScaffoldGraph
A ScaffoldGraph object to query.
activity : str
A scaffold node attribute key corresponding to an activity value.
If the test is binomial this value should be a binary attribute
(0 or 1 / True or False).
mode : {'ks', 'b'}, optional
A string specifying the statistical test to perform. 'ks' specifies a
Kolmogorov-Smirnov test and 'b' or 'binomial' specifies a binomial test.
The default is 'ks'.
alternative : {'two-sided', 'less', 'greater'}, optional
Defines the alternative hypothesis.
The following options are available:
* 'two-sided'
* 'less': one-sided
* 'greater': one-sided
The default is 'greater'.
p : float, None, optional
The hypothesized probability of success. 0 <= p <= 1. Used in binomial mode.
If not specified p is set automatically (number of active / total compounds).
The default is None.
Returns
-------
dict
A dict of dicts in the format {scaffold: {results}} where results is the set
of results returned by the statistical test and scaffold is a scaffold node
key corresponding to a scaffold in the ScaffoldGraph object.
See Also
--------
scaffoldgraph.analysis.enrichment.compound_set_enrichment
References
----------
.. [1] Varin, T., Schuffenhauer, A., Ertl, P., and Renner, S. (2011). Mining for bioactive scaffolds
with scaffold networks: Improved compound set enrichment from primary screening data.
Journal of Chemical Information and Modeling, 51(7), 15281538.
.. [2] Varin, T., Gubler, H., Parker, C., Zhang, J., Raman, P., Ertl, P. and Schuffenhauer, A. (2010)
Compound Set Enrichment: A Novel Approach to Analysis of Primary HTS Data.
Journal of Chemical Information and Modeling, 50(12), 2067-2078.
"""
if mode == 'binomial' or mode == 'b':
return _btp(scaffoldgraph, activity, alternative, p)
elif mode == 'ks' or mode == 'k':
return _ksp(scaffoldgraph, activity, alternative)
else:
raise ValueError(f'scaffold enrichment mode: {mode}, not implemented')
def compound_set_enrichment(scaffoldgraph, activity, mode='ks', alternative='greater', crit=0.01, p=None):
"""
Perform compound set enrichment (CSE), calculating scaffolds enriched for bioactivity.
Parameters
----------
scaffoldgraph : ScaffoldGraph
A ScaffoldGraph object to query.
activity : str
A scaffold node attribute key corresponding to an activity value.
If the test is binomial this value should be a binary attribute
(0 or 1 / True or False).
mode : {'ks', 'b'}, optional
A string specifying the statistical test to perform. 'ks' specifies a
Kolmogorov-Smirnov test and 'b' or 'binomial' specifies a binomial test.
The default is 'ks'.
alternative : {'two-sided', 'less', 'greater'}, optional
Defines the alternative hypothesis.
The following options are available:
* 'two-sided'
* 'less': one-sided
* 'greater': one-sided
The default is 'greater'.
crit : float, optional
The critical significance level. The default is 0.01
p : float, None, optional
The hypothesized probability of success. 0 <= p <= 1. Used in binomial mode.
If not specified p is set automatically (number of active / total compounds).
The default is None.
Returns
-------
A tuple of 'enriched' scaffold classes in the format: (scaffold, {data}) where data
is the corresponding node attributes for the returned scaffold.
Notes
-----
P-values are added as node attributes with the key 'pval'.
References
----------
.. [1] Varin, T., Schuffenhauer, A., Ertl, P., and Renner, S. (2011). Mining for bioactive scaffolds
with scaffold networks: Improved compound set enrichment from primary screening data.
Journal of Chemical Information and Modeling, 51(7), 15281538.
.. [2] Varin, T., Gubler, H., Parker, C., Zhang, J., Raman, P., Ertl, P. and Schuffenhauer, A. (2010)
Compound Set Enrichment: A Novel Approach to Analysis of Primary HTS Data.
Journal of Chemical Information and Modeling, 50(12), 2067-2078.
"""
set_node_attributes(scaffoldgraph, calc_scaffold_enrichment(scaffoldgraph, activity, mode, alternative, p))
bonferroni = bonferroni_correction(scaffoldgraph, crit)
result = []
for scaffold, data in scaffoldgraph.get_scaffold_nodes(True):
if data['pval'] < bonferroni[data['hierarchy']]:
result.append((scaffold, data))
return tuple(sorted(result, key=lambda x: x[1]['pval']))
| 41.379121 | 118 | 0.659673 |
62711db72244e06a03957f6f565656dd9ee94885 | 803 | py | Python | ejercicio_fichero/ejercicio_fichero1/fichero.py | Ironwilly/python | f6d42c685b4026b018089edb4ae8cc0ca9614e86 | [
"CC0-1.0"
] | null | null | null | ejercicio_fichero/ejercicio_fichero1/fichero.py | Ironwilly/python | f6d42c685b4026b018089edb4ae8cc0ca9614e86 | [
"CC0-1.0"
] | null | null | null | ejercicio_fichero/ejercicio_fichero1/fichero.py | Ironwilly/python | f6d42c685b4026b018089edb4ae8cc0ca9614e86 | [
"CC0-1.0"
] | null | null | null | # Lee el fichero y procsalo de tal manera que sea capaz de mostrar
# la temperatura mxima para una ciudad dada. Esa ciudad la debe poder
# recibir como un argumento de entrada. Si la ciudad no existe, se deber
# manejar a travs de una excepcin.
import csv
provincia = input('Diga el nombre de la ciudad: ')
with open("climatologia.csv", encoding="utf-8") as csvfile:
reader = csv.reader(csvfile, delimiter=",")
try:
for row in reader:
if (provincia == row[2]):
temperatura_maxima = row[3]
print(f"provincia: '{provincia}' con temperatura maxima de {temperatura_maxima}")
else:
raise Exception("No existe ninguna ciudad: " + provincia)
except Exception as cityNotFound:
print(cityNotFound)
| 29.740741 | 97 | 0.655044 |
62728052af8201aa2645d7c22783e76db3275ed8 | 4,059 | py | Python | python/brunel/magics.py | Ross1503/Brunel | c6b6323fa6525c2e1b5f83dc6f97bdeb237e3b06 | [
"Apache-2.0"
] | 306 | 2015-09-03T18:04:21.000Z | 2022-02-12T15:15:39.000Z | python/brunel/magics.py | Ross1503/Brunel | c6b6323fa6525c2e1b5f83dc6f97bdeb237e3b06 | [
"Apache-2.0"
] | 313 | 2015-09-09T14:20:14.000Z | 2020-09-14T02:00:05.000Z | python/brunel/magics.py | Ross1503/Brunel | c6b6323fa6525c2e1b5f83dc6f97bdeb237e3b06 | [
"Apache-2.0"
] | 88 | 2015-09-11T16:45:22.000Z | 2021-11-28T12:35:48.000Z | # Copyright (c) 2015 IBM Corporation and others.
#
# 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.
from IPython.core.magic import Magics, magics_class, line_magic, cell_magic, line_cell_magic
import pandas as pd
import brunel.brunel_main as brunel
ipy = get_ipython()
# Register with IPython
ipy.register_magics(BrunelMagics)
| 34.692308 | 105 | 0.584134 |
62735fa3cb9b4a375ffe477b83e79ab29f0e085c | 537 | py | Python | plugs_newsletter/emails.py | solocompt/plugs-newsletter | 57b9aa2caf9ed5bd5adf25839dbf52b85c0afa53 | [
"MIT"
] | 1 | 2017-01-10T23:24:55.000Z | 2017-01-10T23:24:55.000Z | plugs_newsletter/emails.py | solocompt/plugs-newsletter | 57b9aa2caf9ed5bd5adf25839dbf52b85c0afa53 | [
"MIT"
] | 1 | 2017-01-08T00:01:21.000Z | 2017-01-08T00:01:21.000Z | plugs_newsletter/emails.py | solocompt/plugs-newsletter | 57b9aa2caf9ed5bd5adf25839dbf52b85c0afa53 | [
"MIT"
] | null | null | null | """
Plugs Newsletter Emails
"""
from plugs_mail.mail import PlugsMail
| 26.85 | 76 | 0.748603 |
6273ea53c245381a5adf539a8b0c5e691d335b8c | 4,526 | py | Python | modules/smsapi/proxy.py | kamilpp/iwm-project | d3d816b5a30047e4ec7c7e17d1f71e189858190a | [
"MIT"
] | null | null | null | modules/smsapi/proxy.py | kamilpp/iwm-project | d3d816b5a30047e4ec7c7e17d1f71e189858190a | [
"MIT"
] | null | null | null | modules/smsapi/proxy.py | kamilpp/iwm-project | d3d816b5a30047e4ec7c7e17d1f71e189858190a | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
import os
import sys
import mimetypes
from io import BytesIO
try:
from urllib2 import Request, urlopen, URLError
from urllib import urlencode
except ImportError:
from urllib.request import Request, urlopen
from urllib.parse import urlencode
from urllib.error import URLError
try:
from mimetools import choose_boundary
except ImportError:
from uuid import uuid4
if sys.version_info[0] == 3:
text_type = str
else:
text_type = unicode
| 26.623529 | 117 | 0.532037 |
62753c5006150ce17ceda04507da80a31675516b | 775 | py | Python | maverick_api/modules/base/mission/util/srtm/make_dict.py | deodates-dev/UAV-maverick-api | 15cf9e0bac6faf4b9361f060395f656575304097 | [
"MIT"
] | 4 | 2018-02-10T01:00:35.000Z | 2019-07-03T04:21:28.000Z | maverick_api/modules/base/mission/util/srtm/make_dict.py | deodates-dev/UAV-maverick-api | 15cf9e0bac6faf4b9361f060395f656575304097 | [
"MIT"
] | 244 | 2018-02-01T22:39:51.000Z | 2021-07-29T05:58:48.000Z | maverick_api/modules/base/mission/util/srtm/make_dict.py | deodates-dev/UAV-maverick-api | 15cf9e0bac6faf4b9361f060395f656575304097 | [
"MIT"
] | 6 | 2018-02-12T10:58:05.000Z | 2020-09-09T13:41:04.000Z | #!/usr/bin/python
import fileinput
import json
url_base = "https://dds.cr.usgs.gov/srtm/version2_1/SRTM3"
regions = [
"Africa",
"Australia",
"Eurasia",
"Islands",
"North_America",
"South_America",
]
srtm_dict = {}
srtm_directory = "srtm.json"
for region in regions:
print("Processing", region)
f = fileinput.input(region)
for name in f:
name = name.strip()
url = url_base + "/" + region + "/" + name
key = name.replace(".hgt.zip", "")
srtm_dict[key] = url
try:
print("Writing", srtm_directory)
f = open(srtm_directory, "w")
json.dump(srtm_dict, f, indent=2, sort_keys=True)
f.close()
except IOError as e:
print("Save srtm_dict(): I/O error({0}): {1}".format(e.errno, e.strerror))
| 20.945946 | 78 | 0.606452 |
62758b3a2a4619c1b6d03498fcd2b870db5024e4 | 495 | py | Python | gail/crowd_sim/configs/icra_benchmark/sarl.py | ben-milanko/PyTorch-RL | 4d7be8a7f26f21b490c93191dca1844046a092df | [
"MIT"
] | null | null | null | gail/crowd_sim/configs/icra_benchmark/sarl.py | ben-milanko/PyTorch-RL | 4d7be8a7f26f21b490c93191dca1844046a092df | [
"MIT"
] | null | null | null | gail/crowd_sim/configs/icra_benchmark/sarl.py | ben-milanko/PyTorch-RL | 4d7be8a7f26f21b490c93191dca1844046a092df | [
"MIT"
] | null | null | null | from configs.icra_benchmark.config import BaseEnvConfig, BasePolicyConfig, BaseTrainConfig, Config
| 27.5 | 98 | 0.733333 |
62781a4622485a3c3996f4345f375edf051908c6 | 83 | py | Python | backend/bios/apps.py | juanrmv/torre-test | 39c4f8928f6f51e462975ef5f89c7a9b5bb05733 | [
"Apache-2.0"
] | null | null | null | backend/bios/apps.py | juanrmv/torre-test | 39c4f8928f6f51e462975ef5f89c7a9b5bb05733 | [
"Apache-2.0"
] | null | null | null | backend/bios/apps.py | juanrmv/torre-test | 39c4f8928f6f51e462975ef5f89c7a9b5bb05733 | [
"Apache-2.0"
] | null | null | null | from django.apps import AppConfig
| 13.833333 | 33 | 0.73494 |
62785d99c24915bf064dcffd95ccc1f5a52eab27 | 3,982 | py | Python | tests/snuba/eventstream/test_eventstream.py | pierredup/sentry | 0145e4b3bc0e775bf3482fe65f5e1a689d0dbb80 | [
"BSD-3-Clause"
] | null | null | null | tests/snuba/eventstream/test_eventstream.py | pierredup/sentry | 0145e4b3bc0e775bf3482fe65f5e1a689d0dbb80 | [
"BSD-3-Clause"
] | null | null | null | tests/snuba/eventstream/test_eventstream.py | pierredup/sentry | 0145e4b3bc0e775bf3482fe65f5e1a689d0dbb80 | [
"BSD-3-Clause"
] | null | null | null | from __future__ import absolute_import
from datetime import datetime, timedelta
import six
import time
import logging
from sentry.utils.compat.mock import patch, Mock
from sentry.event_manager import EventManager
from sentry.eventstream.kafka import KafkaEventStream
from sentry.eventstream.snuba import SnubaEventStream
from sentry.testutils import SnubaTestCase, TestCase
from sentry.utils import snuba, json
| 35.238938 | 94 | 0.619789 |
627cfb04842724bdfb5432c95eabf0e23e11ea54 | 470 | py | Python | modulo.py | Alex9808/py101 | 18c585c1433e8ec6f5e4962e556a781e0c3c3cd5 | [
"MIT"
] | 25 | 2018-08-14T22:13:13.000Z | 2021-07-23T04:14:06.000Z | modulo.py | Alex9808/py101 | 18c585c1433e8ec6f5e4962e556a781e0c3c3cd5 | [
"MIT"
] | 1 | 2021-05-21T23:46:42.000Z | 2021-05-21T23:46:42.000Z | modulo.py | Alex9808/py101 | 18c585c1433e8ec6f5e4962e556a781e0c3c3cd5 | [
"MIT"
] | 34 | 2018-07-30T20:48:17.000Z | 2022-02-04T19:01:27.000Z | #! /bin/bash/python3
'''Ejemplo de un script que puede ser importado como mdulo.'''
titulo = "Espacio muestral"
datos = (76, 81, 75, 77, 80, 75, 76, 79, 75)
def promedio(encabezado, muestra):
'''Despliega el contenido de encabezado,as como el clculo del promedio de muestra, ingresado en una lista o tupla.'''
print("El promedio de %s con %d elementos es %f." % (encabezado, len(muestra), sum(muestra) / len(muestra)))
promedio(titulo, datos) | 39.166667 | 126 | 0.678723 |
627d2e10dedbd895286404f157c63ff39dd0589c | 368 | py | Python | experiments/duet_dataloader/input_file_generator.py | 18praveenb/ss-vq-vae | 89e76d69d6127b27ae4cc066a1a1f9c4147fb020 | [
"Apache-2.0"
] | null | null | null | experiments/duet_dataloader/input_file_generator.py | 18praveenb/ss-vq-vae | 89e76d69d6127b27ae4cc066a1a1f9c4147fb020 | [
"Apache-2.0"
] | null | null | null | experiments/duet_dataloader/input_file_generator.py | 18praveenb/ss-vq-vae | 89e76d69d6127b27ae4cc066a1a1f9c4147fb020 | [
"Apache-2.0"
] | null | null | null | genres = ['blues', 'classical', 'country', 'disco', 'hiphop', 'jazz', 'metal', 'pop', 'reggae', 'rock']
num_files = 100
with open(f'INPUT_FULL', 'w') as f:
for genre in genres:
for i in range(num_files):
for j in range(6):
f.write(f'/datasets/duet/genres/{genre}.{i:05d}.{j}.wav /datasets/duet/genres/{genre}.{i:05d}.{j}.wav\n') | 52.571429 | 121 | 0.578804 |
627df994c37f89a314b88935ba858af233d102af | 549 | py | Python | generate_nginx_config.py | AppScale/appscake | 615597765e835015c1e8d8bc70921a655f8aa86a | [
"BSD-3-Clause"
] | null | null | null | generate_nginx_config.py | AppScale/appscake | 615597765e835015c1e8d8bc70921a655f8aa86a | [
"BSD-3-Clause"
] | 1 | 2021-06-08T09:51:49.000Z | 2021-06-08T09:51:49.000Z | generate_nginx_config.py | isabella232/appscake | 615597765e835015c1e8d8bc70921a655f8aa86a | [
"BSD-3-Clause"
] | 1 | 2021-06-08T09:48:33.000Z | 2021-06-08T09:48:33.000Z | import jinja2
import os
import socket
my_public_ip = os.popen("curl -L http://metadata/computeMetadata/v1beta1/instance/network-interfaces/0/access-configs/0/external-ip").read()
my_private_ip = socket.gethostbyname(socket.gethostname())
template_contents = open('/root/appscake/nginx_config').read()
template = jinja2.Template(template_contents)
rendered_template = template.render(my_private_ip=my_private_ip, my_public_ip=my_public_ip)
with open('/etc/nginx/sites-available/default', 'w') as file_handle:
file_handle.write(rendered_template) | 42.230769 | 140 | 0.812386 |
627e2692036a975d4c6bc119811af70c6ad6b162 | 909 | py | Python | VisualizedSorting/Controller.py | lachieggg/Misc | 066149309e3e4634cded168687c7dfc3a3a4d6f3 | [
"MIT"
] | null | null | null | VisualizedSorting/Controller.py | lachieggg/Misc | 066149309e3e4634cded168687c7dfc3a3a4d6f3 | [
"MIT"
] | null | null | null | VisualizedSorting/Controller.py | lachieggg/Misc | 066149309e3e4634cded168687c7dfc3a3a4d6f3 | [
"MIT"
] | null | null | null | #!/usr/bin/env python3
import sys
from Window import Window
from Constants import *
from Algorithms.MergeSort import MergeSort
from Algorithms.QuickSort import QuickSort
from Algorithms.BubbleSort import BubbleSort
from Algorithms.InsertionSort import InsertionSort
from Algorithms.SelectionSort import SelectionSort
if(__name__ == "__main__"):
print("Click to begin the algorithm.")
try:
c = Controller()
c.main()
except KeyboardInterrupt:
print('\nExiting.')
| 22.725 | 50 | 0.664466 |
627e4b8f24eb8ffa6dd2d71640b1a2b1b78cf92a | 3,688 | py | Python | openslides_backend/presenter/get_forwarding_meetings.py | MJJojo97/openslides-backend | af0d1edb0070e352d46f285a1ba0bbe3702d49ae | [
"MIT"
] | 5 | 2020-01-20T13:57:15.000Z | 2021-03-27T14:14:44.000Z | openslides_backend/presenter/get_forwarding_meetings.py | MJJojo97/openslides-backend | af0d1edb0070e352d46f285a1ba0bbe3702d49ae | [
"MIT"
] | 859 | 2020-01-11T22:58:37.000Z | 2022-03-30T14:54:06.000Z | openslides_backend/presenter/get_forwarding_meetings.py | MJJojo97/openslides-backend | af0d1edb0070e352d46f285a1ba0bbe3702d49ae | [
"MIT"
] | 16 | 2020-01-04T20:28:57.000Z | 2022-02-10T12:06:54.000Z | from typing import Any
import fastjsonschema
from ..permissions.permission_helper import has_perm
from ..permissions.permissions import Permissions
from ..shared.exceptions import PermissionDenied, PresenterException
from ..shared.patterns import Collection, FullQualifiedId
from ..shared.schema import required_id_schema, schema_version
from .base import BasePresenter
from .presenter import register_presenter
get_forwarding_meetings_schema = fastjsonschema.compile(
{
"$schema": schema_version,
"type": "object",
"title": "get_forwarding_meetings",
"description": "get forwarding meetings",
"properties": {
"meeting_id": required_id_schema,
},
}
)
| 36.88 | 119 | 0.574837 |
627e648e181ccec154beb32ed33085244d73a0fd | 638 | py | Python | settings.py | gyyang/olfaction_evolution | 434baa85b91f450e1ab63c6b9eafb8d370f1df96 | [
"MIT"
] | 9 | 2021-10-11T01:16:23.000Z | 2022-01-13T14:07:08.000Z | settings.py | gyyang/olfaction_evolution | 434baa85b91f450e1ab63c6b9eafb8d370f1df96 | [
"MIT"
] | 1 | 2021-10-30T09:49:08.000Z | 2021-10-30T09:49:08.000Z | settings.py | gyyang/olfaction_evolution | 434baa85b91f450e1ab63c6b9eafb8d370f1df96 | [
"MIT"
] | null | null | null | """User specific settings."""
import matplotlib as mpl
import matplotlib.pyplot as plt
mpl.rcParams['font.size'] = 7
mpl.rcParams['pdf.fonttype'] = 42
mpl.rcParams['ps.fonttype'] = 42
mpl.rcParams['font.family'] = 'arial'
mpl.rcParams['mathtext.fontset'] = 'stix'
seqcmap = mpl.cm.cool_r
try:
import seaborn as sns
plt.rcParams['axes.prop_cycle'] = plt.cycler(color=sns.color_palette('deep'))
# seqcmap = sns.color_palette("crest_r", as_cmap=True)
except ImportError as e:
print('Seaborn not available, default to matplotlib color scheme')
use_torch = True
cluster_path = '/share/ctn/users/gy2259/olfaction_evolution'
| 29 | 81 | 0.731975 |