content stringlengths 5 1.05M |
|---|
import sys, os
import pandas as pd
from FlokAlgorithmLocal import FlokDataFrame, FlokAlgorithmLocal
import cv2
import json
import pyarrow
import time
class Batch_ImageWrite(FlokAlgorithmLocal):
def run(self, inputDataSets, params):
#这个path会从前端传入,是一个已经存在的文件夹路径,是绝对路径,图片会写入到这个路径。
path=param... |
"""Print 'Hello world' to the terminal.
RST uses single backticks or back-quotes for various
things including interpreted text roles and references.
Here `example is missing a closing backtick.
That is considered to be an error, and should fail::
$ flake8 --select RST RST215/backticks.py
RST215/backticks.py... |
#!/usr/bin/env python
"""
Performs 1D scans over all of the systematics in a pipeline (or multiple
pipelines) and saves the output. This is to check the their likelihood spaces.
"""
from __future__ import absolute_import
from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter
from collections import Orde... |
from operator import itemgetter
from rdkit import Chem
"""
create new RDKIT residue
mi = Chem.AtomPDBResidueInfo()
mi.SetResidueName('MOL')
mi.SetResidueNumber(1)
mi.SetOccupancy(0.0)
mi.SetTempFactor(0.0)
source: https://sourceforge.net/p/rdkit/mailman/message/36404394/
"""
from collections import namedtuple
PD... |
from os import name
import pandas as pd
import numpy as np
from score_table.table import Team, ScoreTable, HistoricScoreTable
from score_table.create import score_season
from team_value import set_value
if __name__ == '__main__':
df = pd.read_csv('../data/england-transformed.csv')
epl_df = pd.read_csv('../dat... |
"""
A scaled down version of the Brunel model useful for testing (see OMV files: .test.*)
"""
from brunel08 import runBrunelNetwork
from pyNN.utility import get_script_args
simulator_name = get_script_args(1)[0]
simtime = 1000
order = 100
eta = 2.0 # rel rate of external input
g = 5.0
runBru... |
"""
.. module:: COptimizerPGD
:synopsis: Optimizer using Projected Gradient Descent
.. moduleauthor:: Battista Biggio <battista.biggio@unica.it>
.. moduleauthor:: Ambra Demontis <ambra.demontis@unica.it>
"""
from secml.array import CArray
from secml.optim.optimizers import COptimizer
class COptimizerPGD(COptimiz... |
"""
Created on 16 Nov 2016
@author: Bruno Beloff (bruno.beloff@southcoastscience.com)
https://raspberrypi.stackexchange.com/questions/2086/how-do-i-get-the-serial-number
"""
import os
import re
import socket
from pathlib import Path
from subprocess import check_output, call, Popen, PIPE, DEVNULL
from scs_core.esta... |
class UserAuthenticationInfo(object):
password = None
def get_data():
return self
def set_data(data):
self.password = data["password"]
return self
def get_pass():
return self.password |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from pyautocad.types import APoint, Vector
class ALine(object):
"""3D Line work with APoint and support in draw in `AutoCAD`
Usage::
>>> l1 = ALine([10, 10], [20, 20])
Aline(APoint(10.00, 10.00, 0.00), APoint(20.00, 20.00, 0.00))
"""
def __init_... |
# -*- coding: utf-8 -*-
from django_webtest import DjangoTestApp, WebTestMixin
import pytest
from testapp.articles.factories import AuthorFactory, ArticleFactory, TeamFactory
@pytest.fixture(scope='function')
def app(request):
wtm = WebTestMixin()
wtm._patch_settings()
wtm._disable_csrf_checks()
req... |
"""
Copyright (c) 2015 Frank Lamar
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, s... |
import sys
import math
import random
class motion:
def __init__(self, call):
self.call = call
def forward_step(self, step):
data = [0x10, 0x01, 0x00, 0x00]
mm = 100
data[2] = mm//256
data[3] = mm % 256
for i in range(0, step):
self.call.blewrite(dat... |
import os
from setuptools import setup, find_packages
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name="clinto",
version="0.4.0",
packages=find_packages(),
scripts=[],
install_requires=["six"],
include_package_d... |
import os
import pandas as pd
# path to MIMIC-III as split into episodes by mimic3-benchmarks
patients_dir = 'data/mimic'
class Patient:
def __init__(self, directory, id):
self.directory = directory
self.id = id
def get_stays(self):
return pd.read_csv(os.path.join(self.directory, 'sta... |
from maze import Maze
from game_controller import GameController
def test_constructor():
g = GameController(600, 400)
m = Maze(600, 400, 150, 450,
100, 300, g)
assert m.LEFT_VERT == 150
assert m.RIGHT_VERT == 450
assert m.TOP_HORIZ == 100
assert m.BOTTOM_HORIZ == 300
assert m.... |
# Copyright (c) OpenMMLab. All rights reserved.
import io
import os
import os.path as osp
import pkgutil
import re
import time
import warnings
from collections import OrderedDict
from importlib import import_module
from tempfile import TemporaryDirectory
import torch
import torchvision
from torch.optim import Optimize... |
import logging
import os
from argparse import ArgumentParser
from pathlib import Path
from brbanks2ynab.config.initialize import init_config
from brbanks2ynab.sync.sync import sync
def _default_config_path():
return os.path.join(os.getcwd(), 'brbanks2ynab.json')
def main():
logging.basicConfig()
logger... |
import requests
from bs4 import BeautifulSoup as bsoup
import db_checker as dbchk
def get_response(url,site_tag):
aggr_urls=[]
agent = {"User-Agent":'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36'}
site_req_url = requests.get(url, headers=agen... |
#################################################################
# MET v2 Metadate Explorer Tool
#
# This Software is Open Source. See License: https://github.com/TERENA/met/blob/master/LICENSE.md
# Copyright (c) 2012, TERENA All rights reserved.
#
# This Software is based on MET v1 developed for TERENA by Yaco Sistem... |
from jsog3 import jsog
import unittest
class TestJSOG(unittest.TestCase):
def test_encode_reference(self):
inner = { "foo": "bar" }
outer = { "inner1": inner, "inner2": inner }
encoded = jsog.encode(outer)
# Python 3.7+ ensures fields are always processed in order,
# however contents of inner1 and inner2 ... |
# -*- coding: utf-8 -*-
import logging
import datetime
from pythonjsonlogger import jsonlogger
class CustomJsonFormatter(jsonlogger.JsonFormatter):
def add_fields(self, log_record, record, message_dict):
dt_now = datetime.datetime.now()
super().add_fields(log_record, record, message_dict)
... |
prompt= "\nPor favor escriba su edad: "
prompt+= "\nEscriba '-1' cuando haya terminado"
while True:
edad= int(input(prompt))
if edad == -1:
break
elif edad < 3 and edad!=0 :
print("Su entrada es gratuita")
elif edad >= 3 and edad <12:
print("Son $10 por favor")
elif edad >=... |
import math
import torch.nn as nn
import torch
import numpy as np
eps = float(np.finfo(np.float32).eps)
class PredictionLoss(nn.Module):
def __init__(self, batch_size, seq_len):
super(PredictionLoss, self).__init__()
self.batch_size = batch_size
self.seq_len = seq_len
... |
import grpc
import grpc_testing
import pytest
import random
from pymilvus.grpc_gen import milvus_pb2, schema_pb2, common_pb2
from pymilvus import Milvus, DataType
class Fields:
class NormalizedField:
def __init__(self, **kwargs):
self.name = kwargs.get("name", None)
self.is_primar... |
import torch
from torch.autograd import Variable
import numpy as np
import torch.nn.functional as F
EPSILON = np.finfo(float).eps
def concrete_neuron(logit_p, testing=False, temp=1.0 / 10.0, **kwargs):
'''
Use concrete distribution to approximate binary output. Here input is logit(keep_prob).
'''
if t... |
import logging
import os
from pathlib import Path
from typing import Optional, cast
from flask import Flask, Response, render_template, request, send_from_directory
from quiz_bot import db
from quiz_bot.admin.cloud import CloudMaker
from quiz_bot.admin.flask import get_flask_app
from quiz_bot.admin.statistics import S... |
import numpy as np
def plot_scatter_basic(viz, env, args):
title = args[0] if len(args) > 0 else None
Y = np.random.rand(100)
return viz.scatter(
X=np.random.rand(100, 2),
Y=(Y[Y > 0] + 1.5).astype(int),
opts=dict(
legend=['Didnt', 'Update'],
xtickmin=-50,
... |
import fractions
N = int( input() )
radius = list( map( int, input().split(' ') ) )
for i in range( 1, N ):
if( radius[0] % radius[i] == 0 ):
print( '%d/1 ' %( radius[0] // radius[i] ) )
else:
print( '%s ' %( fractions.Fraction( radius[0], radius[i] ) ) ) |
from ....extensions import ExtensionMixin
from ...flarum.core.discussions import DiscussionFromBulk
class RealtimeDiscussionMixin(DiscussionFromBulk):
@property
def canViewWhoTypes(self) -> bool:
"""
Whether or not you can view who is typing in real time.
"""
return self... |
from .sql import SqlBackend
__all__ = ('MySqlBackend',)
class MySqlBackend(SqlBackend):
name = 'MySQL'
reference_quote = '`'
supports_on_duplicate_key_update = True
|
# Display Module for Shmup
# Import Modules
import pygame
import consts
from os import path
# Load Background Graphics
background_img = pygame.image.load(path.join(consts.img_dir, 'background.png')).convert()
background = pygame.transform.scale(background_img, (consts.GAME_WIDTH, consts.GAME_HEIGHT))
background_rect ... |
# Generated by Django 2.1.12 on 2020-02-29 17:34
import ckeditor.fields
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Person',
fields=[
(... |
# -*- coding: utf-8 -*-
"""NEE_seq2seq.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1h9MOT9VFNffvSPgi7OBHxKQteIk0TvXf
"""
# Commented out IPython magic to ensure Python compatibility.
# %matplotlib inline
# -*- coding: utf-8 -*-
"""
Code refe... |
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import torch
from torch.autograd import Variable
from torch.utils.data import DataLoader
import brewer2mpl
bmap = brewer2mpl.get_map('Set1', 'qualitative', 3)
colors = bmap.mpl_colors
plt.style.use('ggplot')
... |
# Generated by Django 2.2.16 on 2021-09-10 08:58
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('users', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='user',
name='bio',
field=m... |
import json
import socket
from .flow import *
from .util import *
class SmartBulb(object):
def __init__(self, host, port=55443, timeout=5):
'''
Create a new Bulb instance
:param str host: host name or ip address on which the device listens
:param int port: port on which the devic... |
names = input("Enter names seperated by commas : ").split(",")
assignments = [int(x) for x in input("Enter assignment counts separated by commas : ").split(",")]
grades = [int(y) for y in input("Enter grades separated by commas : ").split(",")]
new_grades = []
for i in range(len(assignments)):
new_grades.append(gr... |
#!/usr/bin/env python
import os
import sys
import setuptools
if sys.argv[-1] == 'publish':
os.system('python setup.py sdist upload')
sys.exit()
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(name='pyflowater',
version='0.5.0',
packages=[ 'pyflowater' ],
... |
from LNMarkets import User
def test_userInformation(token):
userInfo = User.userInformation(token)
assert 'show_leaderboard' in userInfo
show_leaderboard = userInfo['show_leaderboard']
assert not User.updateUser(token, leaderboard=False)['show_leaderboard']
assert User.updateUser(token, leaderboar... |
# author: Bartlomiej "furas" Burek (https://blog.furas.pl)
# date: 2022.05.22
#
# detect click on circle button and print information
#
import tkinter as tk
# --- functions ---
def on_click(event):
#print('event:', event)
#print('x:', event.x)
#print('y:', event.y)
x1, y1, x2, y2 = can... |
import time
import playsound
import youtubesearchpython
import pytube
import random
class SongList:
# contains the id time and name of all the songs in the current playlist
songs = []
current_song_number : int
playMusicThreadObject = None
def __init__(self,
path = "./Downloads/",
... |
#!/usr/bin/env python3
# Copyright (c) 2021 The Dash Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
import time
from test_framework.mininode import logger
from test_framework.test_framework import LuckyCoinOROTest... |
"""
Mask RCNN
Configurations and data loading code for disease dataset from airport.
Copyright (c) 2020 Chienping Tsung
Licensed under the MIT License (see LICENSE for details)
Written by Chienping Tsung
--------------------------------------------------
Usage:
run from the command line as such:
# Train a n... |
from __future__ import annotations
from typing import Optional, TYPE_CHECKING
import actions
from components.base_component import BaseComponent
from components.inventory import Inventory
from components.ability import Ability
from vim_parser import VimCommandParser
import exceptions
import utils
if TYPE_CHECKING:
... |
from frappe import _
def get_data():
return [
{
"label": _("Portal"),
"items": [
{
"type": "doctype",
"name": "Homepage",
"description": _("Settings for website homepage"),
},
{
"type": "doctype",
"name": "Shopping Cart Settings",
"label": _("Shopping Cart Settings"),... |
from __future__ import absolute_import
from __future__ import unicode_literals
import os
from django.core.management.base import BaseCommand, CommandError
from corehq.apps.export.dbaccessors import get_properly_wrapped_export_instance
from corehq.apps.export.export import save_export_payload
from io import open
cla... |
#Dentro do pacote utilidadesCeV que criamos no desafio 111, temos um módulo chamado dado. Crie uma função chamada leiaDinheiro() que seja capaz de funcionar como a função imputa(), mas com uma validação de dados para aceitar apenas valores que seja monetários.
from utilidades import moeda
from utilidades import dado
p... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2019 Felix Fontein <felix@fontein.de>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
DOCUMENTATION = r'''
---
module: boot
short_descrip... |
from setuptools import setup, find_packages
import versioneer
from pathlib import Path
here = Path(__file__).resolve().parent
long_description = here.joinpath("README.md").read_text()
setup(
name="acondbs",
version=versioneer.get_version(),
cmdclass=versioneer.get_cmdclass(),
description="A GraphQL s... |
""" MIT License
https://github.com/robertchase/fsm/blob/master/LICENSE
"""
# pylint: disable=not-callable
from __future__ import absolute_import
from functools import partial
from ergaleia.load_from_path import load_lines_from_path
from ergaleia.un_comment import un_comment
import fsm.actions as fsm_actions
from fsm.... |
# FDC KM 0.1.1
#
'''
1.ustal ilość zmiennych
2.pobierz iloczyny pełne równe 1
3.zbuduj tablicę
4.wypełnij tablicę
5.POGRUPUJ
6.uporządkuj&usuń duplikaty
7.odczytaj & wypisz'''
ST = [0,1,3,2]
TK = []
TT = []; rTT=[]
def Siatka(n): #KK
if(n==8): return (4,4,4,4);
elif(n==7): return (4,... |
import numpy as np
"Code by Jinming Wang, Zuhao Yang"
class DataProcessor():
def __init__ (self, data):
""" Argument: data: the data to be processed """
self.data = data
def copy(self):
return DataProcessor(self.data.copy())
def makeSegments(self, size, stride):
"""
... |
p1 = float(input('Nota prova 1:'))
p2 = float(input('Nota prova 2:'))
m = (p1 + p2)/2
print(f'A media entre a P1 e a P2 e = {m:.1f}.')
if m < 5.0:
print('REPROVADO')
elif 5 <= m < 6.9:
print('RECUPERACAO')
elif m >= 7.0:
print('APROVADO!')
|
SUBTRAIN_VOCAB = 'tasks/R2R/data/sub_train_vocab.txt'
TRAIN_VOCAB = 'tasks/R2R/data/train_vocab.txt'
TRAINVAL_VOCAB = 'tasks/R2R/data/trainval_vocab.txt'
|
from dataloaders import cityscapes, dada, apolloscape, kitti, bdd, merge3
from torch.utils.data import DataLoader
def make_data_loader(args, **kwargs):
if args.dataset == 'cityscapesevent':
train_set = cityscapes.CityscapesRGBEvent(args, split='train')
val_set = cityscapes.CityscapesRGBEvent(args,... |
class DataPointBase(object):
def __init__(self, id, values):
pass |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Correct triangle noise wave in ES60 data
Created on Wed May 2 10:30:23 2018
@author: Alejandro Ariza, British Antarctic Survey
"""
def correct_es60triangle(Sv):
print('TODO') |
class Solution(object):
def findClosestElements(self, arr, k, x):
"""
:type arr: List[int]
:type k: int
:type x: int
:rtype: List[int]
"""
idx = bisect.bisect_left(arr, x)
l, r = idx, idx # not include r
while r - l < k:
if l == 0: ... |
from pyteal import Expr, InnerTxnBuilder, Seq, Subroutine, TealType, TxnField, TxnType
@Subroutine(TealType.none)
def axfer(receiver, asset_id, amt) -> Expr:
return Seq(
InnerTxnBuilder.Begin(),
InnerTxnBuilder.SetFields(
{
TxnField.type_enum: TxnType.AssetTransfer,
... |
from .adsdatatype import AdsDatatype
class SymbolInfo:
def __init__(self, name, indexGroup, indexOffset, adsDatatype, bitOffset = 0):
self.Name = name
self.IndexGroup = indexGroup
self.IndexOffset = indexOffset
self.AdsDatatype = adsDatatype
self.BitOffset = bitOffset
... |
import re
import base64
def to_bin_conversion(inp, form):
formatted = inp.replace(" -2b",'')
out = []
if form == "asc":
for i in formatted:
Dec = ord(i)
BinaryValues = bin(Dec)
out.append(BinaryValues[2:].zfill(8))
return(''.join(out))
elif form == "hex":
formatted = formatted.replace(' ', '')
by... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Advent of Code 2015 from http://adventofcode.com/2015/day/25
Author: James Walker
Copyright: MIT license
--- Day 25: Let It Snow ---
Merry Christmas! Santa is booting up his weather machine; looks like you
might get a white Christmas after all. The weather machin... |
from typing import List
from typing_extensions import Literal
from pydantic import BaseModel, Field
class ModuleConnection(BaseModel):
"""Model a single module connection."""
url: str = Field(
...,
description="The url (port) value the module driver should connect to. "
"For example... |
# -*- coding: utf-8 -*- <--------------采用utf-8
import io, sys, os, urllib2, shutil, time, subprocess, platform
# 全局变量
# 淘宝的接口是动态网页,不满足需求,改用chinaz
# GET_ISP_TYPE_URL = 'http://ip.taobao.com/ipSearch.php'
# GET_ISP_TYPE_URL = 'http://ip.chinaz.com/'
# 站长之家抽风,暂时此地址不可用了
GET_ISP_TYPE_URL = 'http://ip.chinaz... |
import asyncio
import re
translitDict = {
'eng': 'qwertyuiopasdfghjklzxcvbnm',
'ru': 'квертиуиопасдфжхжклзкцвбнм'
}
ending = {'m': '', 'j': 'а', 's': 'о'}
def translit(input_text):
"""Удаляет непонятные символы и транслитит английский текст на кириллицу (🚲)"""
output = []
input_text = re.sub('[^... |
import json
import requests
from flask import request
from flask_restplus import Resource
from app.extensions import api
from app.api.utils.access_decorators import requires_role_view_all
from app.api.services.orgbook_service import OrgBookService
from werkzeug.exceptions import BadRequest, InternalServerError, NotFou... |
outer_old = pd.DataFrame()
outer_new = pd.DataFrame()
for i in range(31):
with open("nist_data/conductivity/%s.json" % str(i+1)) as json_file:
#grab data, data headers (names), the salt name
json_full = json.load(json_file)
json_data = pd.DataFrame(json_full['data'])
... |
from django import forms
from .models import SuperHeroApp
# choices
RICH_POWER_CHOICES = (
('rich', 'Rich'),
('superpower', 'Superpower'),
)
# choices
SUPER_POWER_CHOICES = (
('flight', 'Flight'),
('speed', 'Speed'),
('telekenetic', 'Telekenetic'),
('healing', 'Healing'),
('invisibility', ... |
import sublime, sublime_plugin, webbrowser
try:
from .github import *
except ValueError:
from github import *
class GithubRepositoryCommand(GithubWindowCommand):
@with_repo
def run(self, repo):
webbrowser.open_new_tab(repo.repository_url())
|
import datetime
from pathlib import Path
from vantage6.common.globals import APPNAME
#
# INSTALLATION SETTINGS
#
PACAKAGE_FOLDER = Path(__file__).parent.parent.parent
DATA_FOLDER = PACAKAGE_FOLDER / APPNAME / "server" / "_data"
#
# RUNTIME SETTINGS
#
# Expiretime of JWT tokens
JWT_ACCESS_TOKEN_EXPIRES = datet... |
# -*- coding: utf-8 -*-
class Item:
def __init__(self, name, sell_in, quality):
self.name = name
self.sell_in = sell_in
self.quality = quality
def __repr__(self):
return "%s, %s, %s" % (self.name, self.sell_in, self.quality)
def _base_update(item: Item, quality_inc: int):
... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.17 on 2019-03-10 09:37
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('athenatools', '0018_auto_20190310_1506'),
]
operations = [
migrations.AddF... |
# User types list passed into dropdown of same name for user selection used
# in models.py & forms.py
USER_TYPES_CHOICES = [
('', 'Select Post Category'),
('participant', 'Participant'),
('staff', 'Staff'),
('admin', 'Admin'),
]
# LMS Modules list passed into dropdown of same name for user selection us... |
#
# Copyright 2014 David Novakovic
#
# 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 wri... |
from pathlib import Path
from urllib.parse import quote, unquote
from django.conf import settings
from django.core.files.storage import default_storage
from django.utils.text import slugify
def save_uploaded_file(prefix, uploaded_file):
name, ext = uploaded_file.name.rsplit(".", 1)
filename = "{}.{}".format(... |
from ..jsonrpc.http_taraxa import *
def dag_block_hex2int(block):
keys = ['level', 'period', 'number', 'timestamp']
for key in keys:
block[key] = hex2int(block[key])
return block
def getDagBlockByHash(hash, fullTransactions=False, **kwargs):
r = taraxa_getDagBlockByHash(hash, fullTransaction... |
import unittest
from emingora.pom.analyser.tools.RepeatedGAVS import RepeatedGAVS
from emingora.pom.analyser.utils.PomReaderUtil import PomReaderUtil
class CheckRepeatedGAVTest(unittest.TestCase):
def test_true(self):
# Arrange
pom = PomReaderUtil.read('resources/noRepeatedDependency_pom.xml')
... |
# Copyright 2021 UC Davis Plant AI and Biophysics Lab
#
# 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 ... |
import wx
def main():
for x in dir(wx):
if x.startswith('EVT'):
print(x)
if __name__ == '__main__':
main()
|
from flask_wtf import FlaskForm
from wtforms import StringField
from wtforms import TextAreaField
from wtforms.validators import DataRequired
from wtforms.validators import Email
from wtforms.validators import Length
class ContactUs(FlaskForm):
name = StringField("Name",
validators=[DataReq... |
#!/usr/bin/env python
# om is oauth-mini - a simple implementation of a useful subset of OAuth.
# It's designed to be useful and reusable but not general purpose.
#
# (c) 2011 Rdio Inc
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (... |
from django.apps import AppConfig
import actstream.registry
default_app_config = 'kitsune.questions.QuestionsConfig'
class QuestionsConfig(AppConfig):
name = 'kitsune.questions'
def ready(self):
Question = self.get_model('Question')
actstream.registry.register(Question)
Answer = se... |
#!/usr/bin/env python3
"""
Convert structural variants in a VCF to CGH (CytoSure) format
"""
import argparse
import sys
import pandas as pd
import logging
import gzip
from collections import namedtuple, defaultdict
from io import StringIO
from lxml import etree
from cyvcf2 import VCF
from constants import *
__versio... |
from typing import Container, Sequence, List
#==============================================================================
"""
Write a function that takes as input a set and returns its power set.
Alternatively, Given a collection of integers that might contain duplicates,
nums, return all possible subsets (the powe... |
import time
import datetime
SITE_NAME = "IuliiNet"
DESC = "rete wireless mesh libera e decentralizzata in friuli"
AUTHOR = "lucapost"
SRC = "/home/lucapost/repo/iuliinet/iulii.net/src"
DST = "/home/lucapost/repo/iuliinet/iulii.net/dst"
SITEMAP = "/home/lucapost/repo/iuliinet/iulii.net/dst/sitemap.xml"
URL = "http://iu... |
#stati
strDiStatRunning = "Running ..."
strDiamondsStatusGood = "Good"
strDiamondsStatusLikelihood = "Failed/Couldn't find point with better likelihood"
strDiamondsStatusCovariance = "Failed/Covariance decomposition failed"
strDiamondsStatusAssertion = "Failed/Assertion failed"
strDiamondsStatusTooManyRuns = "Failed/To... |
import csv
def unicode_csv_reader(utf8_data, dialect=csv.excel, **kwargs):
"""
UTF8 CSV Reader from: http://stackoverflow.com/q/904041/2100287
"""
csv_reader = csv.reader(utf8_data, dialect=dialect, **kwargs)
for row in csv_reader:
yield [unicode(cell, 'utf-8') for cell in row]
|
import matplotlib.pyplot as plt
from data_analysis.vldbj_data_parsing.varying_eps_statistics import *
from paper_figures.vldbj.draw_indexing_time_size import TICK_SIZE, LEGEND_SIZE, LABEL_SIZE
import json
from paper_figures.vldbj.draw_varying_c import us_to_ms_factor, large_size_plus
def get_dict(file_path):
wit... |
# -*- coding: utf-8 -*-
"""
@author: Ryan Piersma
"""
from nltk.tokenize import RegexpTokenizer
import os, fnmatch
#Some code from:
#https://stackoverflow.com/questions/15547409/how-to-get-rid-of-punctuation-using-nltk-tokenizer
#data structure for holding sequences:
# Dictionary where key = a word, value = a pair ... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from ... import _utilities
fro... |
# PROJECT JULY-SEPTEMBRE 2019
# SOLVING THE N-BODIES PROBLEM / FUNCTIONS
# By Enguerran VIDAL
# This file contains the multitude of functions used throughout this project, hence its importation in every single .py files
###############################################################
# IMPOR... |
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... |
"""
Advent of Code : Day 07
"""
import re
from os import path
def parse_input(filename):
""" Parse input file values """
script_dir = path.dirname(__file__)
file_path = path.join(script_dir, filename)
with open(file_path, "r") as file:
values = file.read().splitlines()
return values
# ... |
# Exercício 073:
'''Crie uma tupla preenchida com os 20 primeiros colocados da Tabela do Campeonato Brasileiro de Futebol,
na ordem de colocação. Depois mostre:
a) Os 5 primeiros times.
b) Os últimos 4 colocados.
c) Times em ordem alfabética.
d) Em que posição está o time da Chapecoense.'''
brasileirao = ('Atlético M... |
# coding: UTF-8
# !/usr/bin/python
import urllib
import urllib2
import json
import os
import time
import random
import cookielib
localpath="E:\\m\\"
url="https://douban.fm/j/v2/playlist"
textmod ={'sid':'1480150','client':'s:mainsite|y:3.0','channel':'0','app_name':'radio_website','version':'100','type':'s'}
header... |
#
# Simulates writing a series of images to a directory forming a tilt
# series. Used to test passive acquisition by watching a directory.
# It uses a tilt series downloaded from data.kitware.com
from . import TIFFWriter, DM3Writer
import argparse
_writer_map = {
'tiff': TIFFWriter,
'dm3': DM3Writer
}
def ... |
import toolbox.engine as engine
import toolbox.connection as conn
import toolbox.trataArquivo as trataArquivo
import pandas as pd
import numpy as np
from datetime import datetime
import os, shutil
def selectOMs():
log = open("logs/logs.txt", "a+")
try:
conection = conn.getConnection('Domain','user','pas... |
from tulius.forum.comments import models as comments
from tulius.forum.threads import models as threads
def test_comment_model(user):
obj = comments.Comment(title='foo', body='bar')
assert str(obj) == 'foo'
obj.title = ''
assert str(obj) == 'bar'
def test_thread_model(user):
obj = threads.Thread... |
import pandas as pd
pd.set_option('display.max_columns', 18)
data = pd.read_csv('../datasets/athlete_events.csv')
isnull = data.isnull()
print(isnull)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.