content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
#!/usr/local/bin/python3
import sys
import numpy as np
from tensorflow import keras
from tensorflow.keras import layers
def getMNISTData():
print("Preparing data ...")
num_classes = 10
# the data, split between train and test sets
(x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data... | python |
# Collection of supporting functions for wrapper functions
__author__ = 'AndrewAnnex'
from ctypes import c_char_p, c_bool, c_int, c_double, c_char, c_void_p, sizeof, \
POINTER, pointer, Array, create_string_buffer, create_unicode_buffer, cast, Structure, \
CFUNCTYPE, string_at
import numpy
from numpy import ct... | python |
#!/bin/python
if __name__ == "__main__":
from picomc import main
main()
| python |
import datetime
import logging
import json
import os
import socket
from config import Configuration
from io import StringIO
from loggly.handlers import HTTPSHandler as LogglyHandler
class JSONFormatter(logging.Formatter):
hostname = socket.gethostname()
fqdn = socket.getfqdn()
if len(fqdn) > len(hostname)... | python |
from genericpath import exists
import os, sys
from os.path import join
import tempfile
import shutil
import json
try:
curr_path = os.path.dirname(os.path.abspath(__file__))
teedoc_project_path = os.path.abspath(os.path.join(curr_path, "..", "..", ".."))
if os.path.basename(teedoc_project_path) == "teedoc":
... | python |
from .base_settings import *
import os
ALLOWED_HOSTS = ['*']
INSTALLED_APPS += [
'django_prometheus',
'django.contrib.humanize',
'django_user_agents',
'supporttools',
'rc_django',
]
TEMPLATES[0]['OPTIONS']['context_processors'].extend([
'supporttools.context_processors.supportools_globals'
])... | python |
'''
This script loads an already trained CNN and prepares the Qm.f notation for each layer. Weights and activation are considered.
This distribution is used by net_descriptor to build a new prototxt file to finetune the quantized weights and activations
List of functions, for further details see below
- forward_pa... | python |
from timemachines.skatertools.evaluation.evaluators import chunk_to_end
def test_chunk_from_end():
ys = [1,2,3,4,5,6,7,8]
chunks = chunk_to_end(ys,5)
assert len(chunks[0])==5
assert len(chunks)==1
assert chunks[0][0]==4 | python |
from typing import NamedTuple, Optional
class ConnectionProperties(NamedTuple):
origin: str
port: Optional[int]
| python |
"""cli.py - Command line interface related routines"""
import logging
import os
import pathlib
from itertools import chain
import click
import click_logging
from ocdsextensionregistry import ProfileBuilder
from ocdskit.util import detect_format
from spoonbill import FileAnalyzer, FileFlattener
from spoonbill.common i... | python |
# -*- coding: utf-8 -*- #
# Copyright 2018 Google LLC. 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 requir... | python |
# CSC486 - Spring 2022
# Author: Dr. Patrick Shepherd
# NOTE: This file contains several functions, some of which already do something
# when run, even before you start writing code. For your convenience, in the
# main function, you may want to comment out the functions you are not currently
# using so they are not r... | python |
import os
from PyQt5.QtCore import QThread, pyqtSignal
from lib.ffmpegRunner import Runner
from lib.logger import Log
class Controller(QThread):
output = pyqtSignal(str)
def __init__(self,):
QThread.__init__(self, parent=None)
self.__runner = None
self.__outputFile = None
def s... | python |
# https://arcade.academy/examples/array_backed_grid_sprites_1.html#array-backed-grid-sprites-1
"""
Array Backed Grid Shown By Sprites
Show how to use a two-dimensional list/array to back the display of a
grid on-screen.
This version syncs the grid to the sprite list in one go using resync_grid_with_sprites.
If Pytho... | python |
from datetime import date
def get_count_of_day(year,month,day):
"""
Function that returns the count of day (since the beginning of the year)
for a given year, month and day
Positional argument:
year -- type = integer
month -- type = integer
day -- type = integer
... | python |
#!/usr/bin/env python3
from gi.repository import Meson
if __name__ == "__main__":
s = Meson.Sample.new("Hello, meson/py!")
s.print_message()
| python |
import os
import sys
import unittest
import numpy as np
from QGrain.algorithms import *
NORMAL_PARAM_COUNT = 2
WEIBULL_PARAM_COUNT = 2
GENERAL_WEIBULL_PARAM_COUNT = 3
# the component number must be positive int value
class TestCheckComponentNumber(unittest.TestCase):
# valid cases
def test_1_to_100(self):
... | python |
# Copyright (C) 2020 University of Oxford
#
# 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 t... | python |
# SPDX-FileCopyrightText: 2017 Scott Shawcroft, written for Adafruit Industries
#
# SPDX-License-Identifier: MIT
# NOTE: Make sure you've created your secrets.py file before running this example
# https://learn.adafruit.com/adafruit-pyportal/internet-connect#whats-a-secrets-file-17-2
import board
from adafruit_pyporta... | python |
"""
weasyprint.css.descriptors
--------------------------
Validate descriptors used for some at-rules.
"""
import tinycss2
from ...logger import LOGGER
from ..utils import (
InvalidValues, comma_separated_list, get_custom_ident, get_keyword,
get_single_keyword, get_url, remove_whitespace, single... | python |
import numpy as np
import pandas as pd
import os
import h5py
from scipy import io
##########################################################
# author: tecwang
# email: tecwang@139.com
# Inspired by https://blog.csdn.net/zebralxr/article/details/78254192
# detail: Transfer mat file into csv file by python
#############... | python |
# -*- coding: utf-8 -*-
"""
Created on Tue May 23 14:40:10 2017
@author: pudutta
"""
from __future__ import absolute_import, division, print_function
import codecs
import glob
import multiprocessing
import os
import pprint
import re
import nltk
import gensim.models.word2vec as w2v
import math
import ... | python |
#!/user/bin python
# -*- coding:utf-8 -*-
'''
@Author: xiaodong
@Email: fuxd@jidongnet.com
@DateTime: 2015-11-08 19:06:43
@Description: 提取word文档信息 转换Excel
需求字段 : 姓名,职位,性别,年龄,教育程度,手机号码,邮箱,户籍,简历更新日期,工作经历,项目经历。
'''
from win32com.client import Dispatch, constants
import os,sys
import re
import chardet... | python |
def my_zip(first,secoud):
first_it=iter(first)
secoud_it=iter(secoud)
while True:
try:
yield (next(first_it),next(secoud_it))
except StopIteration:
return
a=['s','gff x','c']
b=range(15)
m= my_zip(a,b)
for pair in my_zip(a,b):
print(pair)
a,b... | python |
import sqlite3
def changeDb():
databaseFile = "app/database/alunos.db"
escolha = 0
while escolha != 4:
print("""
1 = Numero para contato
2 = Situação escolar
3 = Documentações pendentes
4 = Sair do menu
""")
escolha... | python |
#!/usr/bin/env python
# -*- coding: utf-8; py-indent-offset:4 -*-
###############################################################################
#
# Copyright (C) 2015, 2016, 2017 Daniel Rodriguez
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public Li... | python |
from confluent_kafka import Producer
import rest
import json
class BusProducer:
def __init__(self):
# Pre-shared credentials
self.credentials = json.load(open('bus_credentials.json'))
# Construct required configuration
self.configuration = {
'client.id': 'bus_producer... | python |
"""ApacheParser is a member object of the ApacheConfigurator class."""
import fnmatch
import itertools
import logging
import os
import re
import subprocess
from letsencrypt import errors
logger = logging.getLogger(__name__)
class ApacheParser(object):
"""Class handles the fine details of parsing the Apache Con... | python |
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import smtplib
__author__ = 'ipetrash'
"""Пример отсылки письма, содержащего обычный текст и html, "самому себе"."""
# http://www.tutorialspoint.com/python/python_sending_email.htm
# https://docs.python.org/3.4/library/email-example... | python |
#!/usr/bin/env python
import os
import pyfwk
from pyfi.entity.entity.db import EntityDB
# -----------------------------EXCHANGE-MODEL-----------------------------#
class TypeModel(pyfwk.Model):
model = None
dbase = None
table = None
columns = None
@staticmethod
def instance():
if no... | python |
"""Sensitive Field Type"""
# standard library
import logging
from typing import TYPE_CHECKING, Any, Callable, Dict, Optional, Union
# first-party
from tcex.input.field_types.exception import InvalidEmptyValue, InvalidLengthValue, InvalidType
if TYPE_CHECKING: # pragma: no cover
# third-party
from pydantic.fi... | python |
"""
License
-------
Copyright (C) 2021 - David Fernández Castellanos
You can use this software, redistribute it, and/or modify it under the
terms of the Creative Commons Attribution 4.0 International Public License.
Explanation
---------
This module contains the statistical model of the COVID-19 vaccination ca... | python |
import torch
import torch.fx.experimental.fx_acc.acc_ops as acc_ops
import torch.nn as nn
from torch.testing._internal.common_fx2trt import AccTestCase, InputTensorSpec
class TestSizeConverter(AccTestCase):
def test_size(self):
class Size(nn.Module):
def forward(self, x):
bs = ... | python |
from authlib.oauth2.rfc8414 import AuthorizationServerMetadata
| python |
# db_util.py
from datetime import datetime
import sqlite3
import os
import inspect
import uuid #uuid4() --> cookie
from utils import err, done,log
try:
# log(os.environ['GATEWAY_INTERFACE'])
if 'cgi' in os.environ['GATEWAY_INTERFACE'].lower():
DATABASE = 'csci4140.db'
else:
DATABASE = "csci4... | python |
from django.db.models import Choices
class ValueTypes(Choices):
PERCENTAGE = 'percentage'
FIXED_AMOUNT = 'fixed amount'
FREE_SHIPPING = 'free shipping'
| python |
import logging
from .builder import TargetBuilder
from .config import YAMLParser
from .device import RunnerFactory
from .testcase import TestCaseFactory
class TestsRunner:
"""Class responsible for loading, building and running tests"""
def __init__(self, targets, test_paths, build=True):
self.target... | python |
from base import PMLM
from models import EDMM, MLMM, MEMM, DCSMM, DEDMM, DKLMM
import utils | python |
from JumpScale import j
import sys
import fcntl
import os
import time
class Empty():
pass
class AAProcessManagerCmds():
ORDER = 100
def __init__(self, daemon=None):
self._name = "pm"
self.daemon = daemon
self._reloadtime = time.time()
if daemon is not None:
... | python |
import pandas as pd
import datetime
import pandas_datareader.data as web
import matplotlib.pyplot as plt
from matplotlib import style
start = datetime.datetime(2015, 1, 1) #Dato for onsket aksjekurs
end = datetime.datetime.now()
df = web.DataReader("ORK.OL", "yahoo", start, end) # Verdien av Orkla aksjen fra 2015 t... | python |
"""
Implementation of geo query language
""" | python |
# 第3章: 正規表現
import json
import gzip
def extract(title):
with gzip.open('jawiki-country.json.gz', 'rt', encoding='utf8') as fin:
for line in fin:
jsd = json.loads(line)
if jsd['title'] == title:
return jsd['text']
return ''
def main():
article = extract('イギリス... | python |
t = int(input())
for i in range(t):
s = str(input())
w = s.split()
s1 = 'not'
if(s1 in w):
print('Real Fancy')
else:
print("regularly fancy")
| python |
#!/usr/bin/python3
import pytest
from brownie import network, Contract, Wei, chain, reverts
@pytest.fixture(scope="module")
def requireMainnetFork():
assert (network.show_active() == "mainnet-fork" or network.show_active() == "mainnet-fork-alchemy")
@pytest.fixture(scope="module")
def iUSDC(accounts, LoanTokenL... | python |
from .database import *
def password_is_valid(password):
if len(password) < 5:
return False
return True
class Login():
def __init__(self, data_set):
self.db = self.db_create(data_set)
def db_create(self, data_set):
db = Database(data_set)
db.up_database()
ret... | python |
ls = []
for i in range(100):
if i%3==0:
ls.append(i)
print(ls)
ls = [i for i in range(100) if i%3==0] # list comprehension
print(ls)
dict1 = {i:f"item{i}" for i in range(1, 12) if i%2==0} # dictionary comprehension
print(dict1)
dict1 = {value:key for key,value in dict1.items()} # can cha... | python |
# Copyright 2017 Eun Woo Song
# 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, so... | python |
import json
import os
import hashlib
import getpass
def main():
FileStructureSetUp().set_up_files()
class ScheduleTable:
# Describes a schedule table
class Row:
def __init__(self, block_type: str = "NA", day: str = "NA", place: str = "NA", time: str = "NA"):
"""
Describes... | python |
import pytest
import python_jsonschema_objects as pjo
@pytest.fixture
def arrayClass():
schema = {
"title": "ArrayVal",
"type": "object",
"properties": {
"min": {
"type": "array",
"items": {"type": "string"},
"default": [],
... | python |
import pytesseract
import settings
def img_to_text():
pytesseract.pytesseract.tesseract_cmd = settings.WORKSPACE_DIR + r'/etc/Tesseract-OCR/tesseract.exe'
text = pytesseract.image_to_string(settings.WORKSPACE_DIR + r'/screenshots_temp/screenshot.png', lang=settings.get_language())
text = text.replace("\n"... | python |
import multiprocessing
import numpy as np
from basetrainer import BaseTrainer
from solvers import LeastSquares
from scorers import MeanAbsolute
from parallelworker import Worker, Task
# Feature selection + linear regression training and validation toolkit
class ParallelTrainer(BaseTrainer):
def __init__(self, x, ... | python |
from stack_and_queue.stack_and_queue import Node, Stack, PseudoQueue
import pytest
| python |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function, unicode_literals
from pyup.updates import Update, RequirementUpdate, InitialUpdate, SequentialUpdate, ScheduledUpdate
from unittest import TestCase
from pyup.requirements import RequirementFile
from pyup.errors import UnsupportedScheduleErr... | python |
"""
Generates JSON file that composes the game interactions
"""
import json, os, errno, random
from queue import *
from collections import defaultdict
from generation.world import ATTRIBUTES, OBJECT_TYPES, ITEMS, ROOMS, OUTSIDE, LOWER_FLOORS
from generation.notes import Notes
from generation.event import Event
def wri... | python |
# -*- coding: utf-8 -*-
"""An HTTP server as training storage browser."""
from .cli import *
from .server import *
from .snapshot import *
| python |
from .base import BaseComponent
class KojiBuilder(BaseComponent):
componentName = "koji_builder"
deploymentConfigName = "koji-builder"
def create_build(self):
self.state.apply_object_from_template(
"general/imagestream.yml",
imagename="koji-builder",
)
self... | python |
from django.db import models
class Page(models.Model):
title = models.CharField(max_length=255)
path = models.SlugField(unique=True)
body = models.TextField()
| python |
# coding=utf8
"""
@author: Yantong Lai
@date: 09/26/2019
@code description: It is a Python3 file to implement cosine similarity with TF-IDF and Word Embedding methods.
"""
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwi... | python |
import datetime
import os
if __name__ == '__main__':
# 列出当前目录文件文件夹
files = [file for file in os.listdir('.')]
print(files)
# 操作系统
print(os.name)
# print(os.uname().__str__())
# 环境变量
path=os.environ.get('path')
print('path is: ',path)
defaultEnv=os.environ.get('test','test')
... | python |
'''Expcontrol functionality that depends on psychopy.'''
import collections
import numpy
import psychopy.core
import psychopy.visual
import psychopy.logging
import psychopy.event
from psychopy.hardware.emulator import SyncGenerator
class Clock(object):
'''
Time-keeping functionality for expcontrol by wrapping ... | python |
class CEPlayground():
pass
def main():
return 0
| python |
from Module import AbstractModule
class Module(AbstractModule):
def __init__(self):
AbstractModule.__init__(self)
def run(
self, network, in_data, out_attributes, user_options, num_cores,
outfile):
import StringIO
import arrayio
from genomicode import arrayplatf... | python |
import pathlib
import setuptools
# The directory containing this file
TOPLEVEL_DIR = pathlib.Path(__file__).parent.absolute()
ABOUT_FILE = TOPLEVEL_DIR / "pokejdr" / "_version.py"
README = TOPLEVEL_DIR / "README.md"
# Information on the omc3 package
ABOUT_POKEJDR: dict = {}
with ABOUT_FILE.open("r") as f:
exec(f... | python |
# !/usr/bin/python3
# -*- coding: utf-8 -*-
# https://stackoverflow.com/a/11236372/1576803
import datetime
import pytz
def get_hora_feliz_dia():
tz = pytz.timezone("America/Argentina/Buenos_Aires")
now = datetime.datetime.now(tz).date()
midnight = tz.localize(datetime.datetime.combine(now, datetime.time... | python |
#!/usr/bin/env python
#-*- coding:utf-8 -*-
"""
disable highlight focused widget
Tested environment:
Mac OS X 10.6.8
http://stackoverflow.com/questions/1987546/qt4-stylesheets-and-focus-rect
"""
import sys
try:
from PySide import QtCore
from PySide import QtGui
except ImportError:
from PyQt4 import Q... | python |
#!/usr/bin/env python
import mysql.connector
from mysql.connector import errorcode
from ConfigParser import SafeConfigParser
__author__ = 'catalyst256'
__copyright__ = 'Copyright 2014, Honeymalt Project'
__credits__ = []
__license__ = 'GPL'
__version__ = '0.1'
__maintainer__ = 'catalyst256'
__email__ = 'catalyst256@... | python |
#!/usr/bin/env python3
import sys,os,io,base64
import pandas as pd
import psycopg2,psycopg2.extras
DBHOST = "localhost"
DBPORT = 5432
DBNAME = "refmet"
DBUSR = "www"
DBPW = "foobar"
dsn = (f"host='{DBHOST}' port='{DBPORT}' dbname='{DBNAME}' user='{DBUSR}' password='{DBPW}'")
dbcon = psycopg2.connect(dsn)
#dbcon.curs... | python |
"""
Reading and Writing of meteorological data
"""
def __clean_HDF5_PLUGIN_PATH():
"""
if the libraries from hdf5plugin are in HDF5_PLUGIN_PATH, then remove them
"""
import os
import logging
if "HDF5_PLUGIN_PATH" in os.environ:
paths = os.environ["HDF5_PLUGIN_PATH"].split(":")
k... | python |
from enum import Enum
from aoc2019.shared.intcode import IntCode
class Direction(Enum):
NORTH = 1
SOUTH = 2
WEST = 3
EAST = 4
class MoveResult(Enum):
WALL = 0
SUCCESS = 1
OXYGEN_SYSTEM = 2
def calculateMinutesToFullOxygen(oxygenSystemLocation, shipMap):
currentMinute = 0
oxygen... | python |
'''
Created on 19 okt. 2013
@author: Juice
'''
from constraints.constraint import Constraint
class NonogramConstraint(Constraint):
def __init__(self, group, initialValues):
super(NonogramConstraint, self).__init__(group, initialValues)
# def notify(self, cell):
# pass
def setAd... | python |
from typing import Dict, Union
import pyomo.environ as pyo
from oogeso import dto
from oogeso.core.devices.base import Device
class HeatPump(Device):
"""
Heat pump or electric heater (el to heat)
"""
carrier_in = ["el"]
carrier_out = ["heat"]
serial = []
def __init__(
self,
... | python |
__all__ = ["Assembly", "Collection", "Extraction", "GetSubs", "Jelly", "QFix", "Setup", "Stages", "Support"]
| python |
from dataclasses import dataclass
from collections import Counter
from math import ceil
from queue import Queue
from typing import Dict
from aocd import data
@dataclass
class Recipe:
output_reagent: str
output_amount: int
inputs: Counter
def __repr__(self):
return f"{self.inputs} => {self.ou... | python |
#!/usr/bin/env python
from ansible_collections.terryhowe.hashivault.plugins.module_utils.hashivault import hashivault_argspec
from ansible_collections.terryhowe.hashivault.plugins.module_utils.hashivault import hashivault_auth_client
from ansible_collections.terryhowe.hashivault.plugins.module_utils.hashivault import h... | python |
import os
import gzip
import pickle
import h5py
import numpy as np
import theano
from utils.misc import get_file_names_in_dir
from utils.vocab import UNK
class Loader(object):
def __init__(self, argv):
self.argv = argv
def load(self, **kwargs):
raise NotImplementedError
@staticmethod
... | python |
from unittest2 import TestCase
from os import chdir, pardir, environ
from os.path import join, dirname, exists
from shutil import rmtree, copyfile
from subprocess import check_call, PIPE, STDOUT, CalledProcessError #, check_output
import sys
from tempfile import mkdtemp
from .venvtest import VirtualenvTestCase
class... | python |
from django.db import transaction
from django.db.models.functions import Lower
from record_label.models import Band, BandLabel, MusicFestival, RecordLabel
from record_label.serializers import RecordLabelSerializer
def restructure_data(festivals_api_data):
"""A helper function to restructure the data from the fes... | python |
# visualize the networkx DiGraph using a Dash dashboard
# General warning: Note that with this dashboard, the edge arrows drawn are infact symmetrical and angled correctly.
# And are all the same distance/size they just don't always look that way because the scaling of the x-axis
# isn't the same scaling of the y-axi... | python |
#!/usr/bin/python
import sys
from socket import socket, AF_INET, SOCK_STREAM
import pymouse
import time
import numpy as np
import matplotlib.pyplot as plt
def main():
if len(sys.argv) != 3:
print "\nusage : python tcp_client.py #host #port\n"
else:
host = sys.argv[1]
port = int(sys.argv[2])
s = socket(AF_I... | python |
"""Test the particle swarm optimisation class"""
import copy
import pytest
import numpy as np
from pracopt.optimiser import ParticleSwarm
from pracopt.objective import Shubert, ObjectiveTest
from pracopt.utils import evaluate
# PSO with test objective functions
@pytest.fixture
def new_test_pso():
"""Return a new i... | python |
import untangle
import os
from os.path import join
class DroneCommandParser:
def __init__(self):
# store the commandsandsensors as they are called so you don't have to parse each time
self.command_tuple_cache = dict()
# parse the command files from XML (so we don't have to store ids and ca... | python |
import numpy as np
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers.core import Dense, Dropout, Activation
from keras.optimizers import SGD
from keras.utils import np_utils
import keras.callbacks
import keras.backend.tensorflow_backend as KTF
import tensorflow as tf
batch_size = 1... | python |
'''
Created on Aug 9, 2018
@author: fan
Generate mean, and variance covariance of key state variables from data
'''
import logging
import numpy as np
logger = logging.getLogger(__name__)
def gen_mean(df, mean_var_list,
short_mean_var_list=None,
group_by_var_list=None,
conditi... | python |
# Example module - finance.py
__all__ = ['tax1', 'tax2'] #defines the names to import when '*' is used
tax1 = 5
tax2 = 10
def cost(): return 'cost'
# Imported into code using
from finance import *
print tax1
print tax2 | python |
class Image:
def __init__(self,
source_ref,
image_shape,
class_map=None,
instance_nb=0,
scene_type=None,
weather_condition=None,
distractor=None):
"""
:param source_ref:
:pa... | python |
# This program launches Google in the browser using text from the cmd or clipboard
# 1. Figure out the URL
# The website I want to go on is formatted like this https://google.com/search?q=
# 2. Handle the command line arguments
import webbrowser, sys
import pyperclip
if len(sys.argv) > 1:
# Get addre... | python |
from django.db import models
from django.utils import simplejson as json
from jsonate.utils import jsonate
from jsonate.widgets import JsonateWidget
from jsonate.form_fields import JsonateFormField
class JsonateField(models.TextField):
__metaclass__ = models.SubfieldBase
def to_python(self, value):
if... | python |
import re
def is_valid_name(name):
regex = re.compile(r"^(?!_$)(?![-])(?!.*[_-]{2})[a-z0-9_-]+(?<![-])$", re.X)
if not re.match(regex, name):
return False
return True
| python |
# -*- coding: utf-8 -*-
"""
Setup file for automatic installation and distribution of AMfe.
Run: 'python setup.py sdist' for Source Distribution
Run: 'python setup.py install' for Installation
Run: 'python setup.py bdist_wheel' for Building Binary-Wheel
(recommended for windows-distributions)
Attention: For eve... | python |
"""
Cli
Copyright (C) 2021 Netpro Project RepoSync
"""
import logging
import socket
from pathlib import Path
import click
from .client import Client
from .core_op import apply as core_apply
from .core_op import fop
from .core_op import show as core_show
from .server import Server
logging.basicConfig()
_LOG = loggin... | python |
# Generated by Django 2.0.4 on 2019-03-27 12:31
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('protein', '0005_proteingproteinpair_g_protein_subunit'),
]
operations = [
migrations.RemoveField(
model_name='proteinconformation',
... | python |
#!/usr/bin/env python
# encoding: utf-8
"""
Created by 'bens3' on 2013-06-21.
Copyright (c) 2013 'bens3'. All rights reserved.
"""
import pylons
def is_ldap_user():
"""
Help function for determining if current user is LDAP user
@return: boolean
"""
return 'ckanext-ldap-user' in pylons.session
| python |
import os
LOG_FILE_PATH = os.path.join(os.getcwd(), "log.log")
DATABASE_PATH = os.path.join(os.getcwd(), "database.db")
ICONS_PATH = os.path.join(os.getcwd(), "icons")
CHAT_SETTINGS_PATH = os.path.join(os.getcwd(), "chat_settings")
BOTS_TXT_PATH = os.path.join(os.getcwd(), "bots.txt")
DEVICES_PATH = os.path.join(os.ge... | python |
from .enemy import Enemy
from .gnat import Gnat
from .laser import Laser
from .player import Player
from .patroller_gnat import PatrollerGnat
| python |
# Copyright (C) 2009-2012 - Curtis Hovey <sinzui.is at verizon.net>
# This software is licensed under the GNU General Public License version 2
# (see the file COPYING)."""Text formatting features for the edit menu."""
__all__ = [
'FormatPlugin',
]
from gettext import gettext as _
from gi.repository import G... | python |
from django.urls import path
from survey import views
from rest_framework import routers
from rest_framework.urlpatterns import format_suffix_patterns
urlpatterns=[
path('',views.index,name="index"),
path('constructor/',views.Constructor,name="constructor"),
path('egresados/',views.Egresados,name="egresados"),
pat... | python |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
from .pickleable_gpt2bpe_encoder import (
PickleableGPT2BPEEncoder,
)
__all__ = [
"PickleableGPT2BPEEncoder",
]
| python |
import pytest
import os
from click.testing import CliRunner
@pytest.mark.usefixtures("session")
@pytest.fixture()
def cli_runner(pushd):
# this will make sure we are back at `cwd`
# after this test is finished
pushd(os.getcwd())
yield CliRunner(mix_stderr=False)
| python |
#Copyright (c) 2021 Kason Suchow
import pygame
import imageManager
import data
class BaseCard(object):
def __init__(self):
self.x = -500
self.y = -500
self.pos = (self.x, self.y)
self.color = ''
self.name = ''
self.description = ''
self.attack = 0
... | python |
"""Tests for reviewboard.diffviewer.managers.DiffCommitManager."""
from __future__ import unicode_literals
from dateutil.parser import parse as parse_date
from kgb import SpyAgency
from reviewboard.diffviewer.models import DiffCommit, DiffSet
from reviewboard.testing.testcase import TestCase
class DiffCommitManage... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.