content stringlengths 5 1.05M |
|---|
# -*- coding: utf-8 -*-
"""
Preprocessing script
Created: 2020/03/13
Updated: 2020/03/14 : NOTES : added patient labels, hypnogram and subject loop
Updated: 2020/03/16 : NOTES : 1.saving raw EEG signals per subject,
per channel of interest, per epoch
2. Butter... |
import csv
import os
from dataclasses import dataclass
from typing import Optional, Tuple
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
from .exec_model import ExecModel, ModelObject
@dataclass
class OptimizationResults(ExecModel):
model: ModelObject
def __pos... |
import ast
import astor
def check_ast(pseutopy, python_str, pseudocode_str):
expected_ast = ast.parse(python_str)
generated_ast = pseutopy.convert_from_string(pseudocode_str)
return astor.to_source(expected_ast) == astor.to_source(generated_ast)
|
# Generated by Django 2.0.6 on 2018-12-29 18:41
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('content', '0002_contentpost_image_attribution'),
]
operations = [
migrations.RemoveField(
model_name='contentpost',
name='im... |
import os
import subprocess
from shutil import copy
from conan_inquiry.web.file_retrieval import WebFiles
def deploy():
dir = os.path.join(os.path.dirname(__file__), "../gh-pages")
print('* Deploying with dir:', dir)
def git(subcmd, *args, **kwargs):
kwargs.setdefault('cwd', os.path.join(dir, 'c... |
import sys
from collections import defaultdict
input = sys.stdin.readline
a = input()
b = input()
d = defaultdict(lambda: 0) # d = defualtdict(0)
# print(len(a))
# print(len(b))
for word in a.split():
for char in word:
d[char] += 1
for word in b.split():
for char in word:
d[char] -= 1
pr... |
# Volatility
# Copyright (C) 2007-2013 Volatility Foundation
#
# Authors:
# Michael Hale Ligh <michael.ligh@mnin.org>
#
# This file is part of Volatility.
#
# Volatility 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 Fou... |
from setuptools import setup, find_packages
contrib = [
'Raphael Ortiz',
]
# setup.
setup(name='goid',
version='0.1.1',
description='Analysis of gastruloid images',
author=', '.join(contrib),
packages=find_packages(exclude=['tests']),
install_requires=[
'numpy',
'... |
from server.orm.command import Command
from server.service.command.custom.helper import (assert_selected_items,
create_custom_command_label)
from server.service.command.custom.schema import CustomCommandProcessorSchema
from server.service.selection.selection import clea... |
from django.test import TestCase
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import Select
from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import NoAlertPresent... |
from __future__ import division
from __future__ import print_function
import glfw
from OpenGL.GL import *
from OpenGL.GLU import *
import numpy as np
from math import floor, sin, cos
def key_callback(window, key, scancode, action, mode):
if key == glfw.KEY_ESCAPE and action == glfw.PRESS:
pri... |
#Prograssão Artimética
print('Progressão Artimética')
termo = int(input('Digite o primeiro termo: '))
razao = int(input('Digite a razão da PA: '))
for c in range(0, 10):
print(termo, end=' ')
termo += razao
|
import numpy as np
import utility
import torch
import sys
sys.path.insert(0, '../UNET_EM_DATASET/UNET_EM_DATASET_BASE/')
import models as m
from torchsummary import summary
import argparse
import config
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('-c', '--config_file', help='config... |
from datetime import datetime
import discord
from discord.ext.commands import Cog
from discord.ext.commands import command
from dotenv import load_dotenv
import os
load_dotenv()
SERVER_LOG = int(os.getenv("SERVER_LOG"))
MESSAGE_LOG = int(os.getenv("MESSAGE_LOG"))
MEMBER_LOG = int(os.getenv("MEMBER_LOG"))
VOICE_LOG = ... |
import logging
import os
DEBUG = os.getenv("ENVIRONEMENT") == "DEV"
APPLICATION_ROOT = os.getenv("APPLICATION_APPLICATION_ROOT", "/api")
HOST = os.getenv("APPLICATION_HOST", "192.168.2.17")
PORT = int(os.getenv("APPLICATION_PORT", "8080"))
SQLALCHEMY_TRACK_MODIFICATIONS = False
ALPHAVANTAGE_API_KEY = os.getenv("ALPHAV... |
'''
Passar para Python
Questão A. O que o seguinte programa (dado na forma de pseucódigo) imprime?
x = 2
y = 5
se y > 8 então
y = y * 2
caso contrário,
x = x * 2
imprime (x + y)
Autor: Felipe Nogueira de Souza
'''
x = 2
y = 5
if y > 8:
y *= 2
else:
x *= 2
print(x+y)
|
import pickle, torch
from tqdm import tqdm
from fairseq.models.roberta import RobertaModel
from fairseq.data.data_utils import collate_tokens
speakers, labels, sentences, train_ids, test_ids, valid_ids = pickle.load(open('dailydialog/dailydialog.pkl', 'rb'))
roberta = RobertaModel.from_pretrained(
'checkpoints/da... |
import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name='gym-anm',
version='1.0.1',
url='http://github.com/robinhenry/gym-anm',
author='Robin Henry',
description="A framework to build Reinforcement Learning environments for Active Netw... |
import pandas as pd
import numpy as np
from sklearn.base import BaseEstimator, TransformerMixin
class MyLog1pTransformer(BaseEstimator, TransformerMixin):
""" Apply np.log1p on columns and save it as separate column
Args:
columns (List): list of column names to transform if given, else all column... |
import json
import os
import pathlib
from typing import Optional
from .exceptions import ConfigLoadException, NoConfigOptionError, \
ConfigException
from . import const
class ConfigData:
def __init__(self, data=None):
self._data = data or {}
def __getattr__(self, item: str):
if item in s... |
from Crypto.Util.Padding import pad, unpad
from Crypto.Hash import MD5
from base64 import b64encode, b64decode
from Crypto.Cipher import AES
import json
import sys
json_file = "hash.json"
github = "https://github.com/MicheleViscione/Pyxercise"
def gen_key(sol, dim=32, sol_md5=None):
sol = str(sol)
if not sol_... |
import pymath
v1 = float(input())
v2 = float(input())
t1 = float(input())
t2 = float(input())
print("acceleration = {}".format(pymath.physics.acceleration(v1, v2, t1, t2)))
|
from django.contrib import admin
from .models import *
# Register your models here.
admin_list = [HostelDetail, ]
for site in admin_list:
admin.site.register(site) |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
PostgreSQL database customizations.
"""
from __future__ import unicode_literals
from django.db.models import Func, IntegerField
from django.contrib.postgres.fields import JSONField
from django.contrib.postgres.operations import CreateExtension
class JSONArrayLength(Fu... |
from txtgamelib import say
from dice import Dice
import random
import pyutils.logsystem as logsystem
class Person:
def __init__(self):
self.name = "Person"
self.state = 'idle'
self.busy = False
self.current_activity = None
self.resource_gathering_velocity = {
... |
# Modified from
# https://github.com/tartley/gltutpy/blob/master/t01.hello-triangle/HelloTriangle.py
import sys
from OpenGL.GL import *
from OpenGL.GLUT import *
from OpenGL.GL.shaders import compileShader, compileProgram
from OpenGL.GL.ARB import vertex_array_object
from os.path import dirname, join
# Number of byte... |
import os
import time
import warnings
import pandas as pd
import torch
from torch import optim, nn
from tqdm import tqdm
import shutil
from .utils.general import create_dataloader
NCOLS = shutil.get_terminal_size().columns
class Classifier:
""" Klasa reprezentująca pojedynczy model sieci neuronowej.
Opróc... |
from mjml.core import initComponent, Component
__all__ = ['HeadComponent']
class HeadComponent(Component):
def handlerChildren(self):
def handle_children(children):
tagName = children['tagName']
component = initComponent(
name = tagName,
context = ... |
import random
class Menu(object):
"""
Handles menu options
"""
def __init__(self):
self._current_index = 0
self._keys = []
self._items = {}
def __len__(self):
return len(self._keys)
def append(self, name, item):
self._keys.append(name)
self._items[name] = item
@property
... |
import androidhelper
droid = androidhelper.Android()
droid.notify('Hello','QPython')
|
"""Test
>>> sorted(find_subset_for_sum([12, 1, 61, 5, 9, 2], 24))
[1, 2, 9, 12]
>>> find_subset_for_sum([12, 1, 61, 5, 9, 2], 1)
[1]
>>> find_subset_for_sum([12, 1, 61, 5, 9, 2], 61)
[61]
>>> find_subset_for_sum([12, 11, 10, 14], 1) == None
True
>>> sorted(find_subset_for_sum([]... |
#
# Pascal
#
# Copyright 2017, Adam Edwards
#
# 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 ... |
#/usr/bin/python
"""
Copyright 2014 The Trustees of Princeton University
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 re... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
File: guianexpr.py
Author: SpaceLis
Email: Wen.Li@tudelft.nl
Github: none
Description: A gui to anexpr.py
"""
import Tkinter as tk
import tkFileDialog as tkfd
from twhere.config import Configuration
import subprocess
import re
STRING = re.compile("^[a-zA-Z_][a-zA-Z0-9_... |
from collections import OrderedDict
from sir3d import sir_code
from sir3d.configuration import Configuration
import numpy as np
import os
import scipy.stats
import logging
import h5py
import scipy.integrate as integ
from scipy import interpolate
# from ipdb import set_trace as stop
__all__ = ['Model']
class Model(ob... |
# Copyright (C) 2018 Internet Systems Consortium.
#
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND INTERNET SYSTE... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
from __future__ import unicode_literals
import nose
from nose.tools import *
from sknano.generators import UnrolledSWNTGenerator
from sknano.testing import GeneratorTestFixtures
class TestCase(GeneratorTestFixtures):
def t... |
from __future__ import unicode_literals, print_function, division
import sys
import time
import math
import gitime.database as db
unix_now = lambda: math.floor(time.time())
class User(object):
""" Contains user data that is shared between invoices """
def __init__(self, rowid=1):
meta = db.query_user... |
def update_price_daily(
):
import pandas as pd
import FinanceDataReader as fdr
# import pickle
import os
folder = "/gcs/pipeline-dots-stock/bong_price_updated"
file_list = os.listdir(folder)
cols_to_keep = ['name', 'code', 'date', 'Prediction',
# 'high', 'low', '... |
##########################################################################
# If not stated otherwise in this file or this component's Licenses.txt
# file the following copyright and licenses apply:
#
# Copyright 2021 RDK Management
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use th... |
from __future__ import absolute_import
import pytest
from checkout_sdk.customers.customers import CustomerRequest
from checkout_sdk.exception import CheckoutApiException
from tests.checkout_test_utils import assert_response, random_email, phone
def test_should_create_and_get_customer(four_api):
email = random_e... |
import os
from django.conf import settings
from django.conf.urls.defaults import include, patterns, url
from django.conf.urls.static import static
from django.contrib import admin
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.views.generic import TemplateView
admin.autodiscover()
ur... |
def test():
# Here we can either check objects created in the solution code, or the
# string value of the solution, available as __solution__. A helper for
# printing formatted messages is available as __msg__. See the testTemplate
# in the meta.json for details.
# If an assertion fails, the messag... |
from teamgrid.minigrid import *
from teamgrid.register import register
class SwitchEnv(MiniGridEnv):
"""
Environment with a light switch to turn lights on/off
"""
def __init__(
self,
num_agents=2,
num_goals=1,
reward_switch='nneo',
reward_goal='one',
):
... |
"""The CharMLMPredicter class plus various functions needed to predict missing chars."""
from greek_char_bert.infer import CharMLMInferencer
from greek_char_bert.data_handler.processor import CharMLMPredProcessor
from farm.data_handler.dataloader import NamedDataLoader
from torch.utils.data.sampler import SequentialSam... |
import os
import time
t = time.time()
os.system("raspistill -vf -hf -o zoid.jpg -w 3280 -h 2464 -t 500")
print('pic taken', time.time() - t)
os.system("cp zoid.jpg ../")
os.chdir("../")
os.system("./du.sh upload zoid.jpg /")
|
import random
import copy
class Matrix:
def __init__(self, columns, rows):
self.columns = columns
self.rows = rows
self.MAP = self.create_map()
def create_map(self):
return [list(random.randint(0,4) for _ in range(self.columns)) for x in range(self.rows)]
# create algorithm... |
from django.shortcuts import render
from django.views import generic
from .models import Post
class ListView(generic.ListView):
template_name = 'blog/blog.html'
def get_queryset(self):
"""Return the last 25 blog post titles"""
return Post.objects.order_by('-date')[:25]
class DetailView(gen... |
import time
from typing import Dict, List, Optional, Set
import sched
from bdsim import Block, BlockDiagram, BDSimState
from bdsim.components import Clock, ClockedBlock, SinkBlock, SourceBlock
def _clocked_plans(bd: BlockDiagram):
plans: Dict[Clock, List[Block]] = {}
prev_clock_period = 0
# track to make... |
# This file is part of spot_motion_monitor.
#
# Developed for LSST System Integration, Test and Commissioning.
#
# See the LICENSE file at the top-level directory of this distribution
# for details of code ownership.
#
# Use of this source code is governed by a 3-clause BSD-style
# license that can be found in the LICE... |
from .core import (
apply,
Singleton,
Null,
interrupt_guard,
SignalHandler,
identity,
null_function,
str_or_none,
str2bool,
str_is_int,
Timer,
recurse_get_elements,
timestamp,
)
from .path import (
main_file_path,
split_path,
make_dir,
copy_file_to_d... |
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 8 12:05:54 2014
@author: Josh Siegle
Loads .kwd files
"""
import h5py
import numpy as np
def load(filename, dataset=0):
f = h5py.File(filename, "r")
assert f.attrs["kwik_version"] == 2
data = {}
recording = f["recordings"][str(dataset)]
data["inf... |
from __future__ import absolute_import
import numpy as np
from . import Operation
_row_axis = 1
_col_axis = 2
_channel_axis = 0
def quantize(x, n_bit, x_min=0., x_max=1., rescale=True):
n_discrete_values = 1 << n_bit
scale = (n_discrete_values - 1) / (x_max - x_min)
quantized = np.round(x * scale) - np.... |
import json
import os
import re
import urllib
import requests
dir_name = 'results'
with open(os.path.join(dir_name, 'genres.json')) as f:
genres = json.load(f)
animes = []
genre_not_found_animes = {}
next_page = 1
while next_page is not None:
params = {}
if 1 < next_page:
params['page'] = next... |
# Copyright 2020-2021 Canonical Ltd.
#
# 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 writi... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.17 on 2018-12-12 12:43
from __future__ import unicode_literals
import django.contrib.postgres.fields.jsonb
from django.db import migrations, models
import django.db.models.deletion
import localized_fields.fields.field
import uuid
class Migration(migrations.Migration... |
from cognite.model_hosting.schedules.schedules import ScheduleOutput, to_output
|
from django.conf.urls import url
from .views import (
AddToAllView,
AddToUserView,
InviteStatView,
InviteView,
TopOffAllView,
TopOffUserView,
)
app_name = "pinax_invitations"
urlpatterns = [
url(r"^invite/$", InviteView.as_view(), name="invite"),
url(r"^invite-stat/(?P<pk>\d+)/$", Inv... |
import tensorflow as tf
import os
from object_detection.utils import dataset_util
from tqdm import tqdm
import cv2
flags = tf.app.flags
flags.DEFINE_string('output_path', '', 'Path to output TFRecord')
flags.DEFINE_string('picture_paths', '', 'Path to the input data to serialize ')
FLAGS = flags.FLAGS
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# pylint: disable=unexpected-keyword-arg
"""
Author: Li Yuanming
Email: yli056@e.ntu.edu.sg
Date: 10/11/2020
TODO: Cover converter test from here: https://github.com/microsoft/hummingbird/tree/master/tests
"""
import lightgbm as lgb
import numpy as np
import onnx
import on... |
# -*- coding: utf-8 -*-
"""Event source attribute containers."""
from __future__ import unicode_literals
from plaso.containers import interface
from plaso.containers import manager
class EventSource(interface.AttributeContainer):
"""Event source attribute container.
The event source object contains information... |
# -*- coding: utf-8 -*-
#Copyright 2013 Brandon Nielsen
#
# This program 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.
#... |
def seperate_string_number(string):
previous_character = string[0]
groups = []
alsonumeric = [".", "-"]
newword = string[0]
for x, i in enumerate(string[1:]):
if i.isalpha() and previous_character.isalpha():
newword += i
elif (i.isnumeric() or i in alsonumeric) and (previous_character.isnumeric() or previou... |
import smart_imports
smart_imports.all()
def create_artifact_record(uuid,
level,
utg_name,
description,
type,
power_type,
mob=None,
... |
'''
@Author: Vijendra Singh
'''
import string
from datetime import datetime as dt
import cv2
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
def _bytes_feature(value):
'''
@brief: function supporting write_tfrecord function below
'''
return tf.train.Feature(bytes_list=tf.train.Bytes... |
from django.test import TestCase, Client
from django.utils import timezone
from django.conf import settings
from rest_framework.test import APIRequestFactory
from app.viewsets import UserViewSet
from app.models import Passphrase, SlackUser
from app.utils import UserRepository, regularize_guest_names
from mock import pa... |
#!/usr/bin/env python
"""rackspacestats - Munin Plugin to monitor stats for Rackspace cloud usage.
Requirements
python-cloudfiles
Wild Card Plugin - No
Multigraph Plugin - Graph Structure
- rackspace_containersize
- rackspace_containercount
Environment Variables
container: Rackspace CDN contain... |
from setuptools import setup, Extension
seqpy_module = Extension('seqpy', sources = ["seqpy.c"])
setup(
name = "seqpy",
description = "seqpy",
ext_modules = [seqpy_module])
|
import click
import os
import logging
import json
from typing import Tuple
import requests
from requests import HTTPError
from bitbucklet.token import get_access_token, BearerAuth
from bitbucklet.urls import teams_url, users_privileges_url, groups_privileges_url, repos_url
@click.group(name='repos', help = 'Managing... |
num = int(input('Informe um número (0 a 9999)'))
n = str(num)
print(f'Analisando o número {num}')
print(f'Unidade: {num // 1 % 10}')
print(f'Dezena: {num // 10 % 10}')
print(f'Centena: {num // 100 % 10}')
print(f'Milhar: {num // 1000 % 10}') |
"""
Manager and Serializer for HDCAs.
HistoryDatasetCollectionAssociations (HDCAs) are datasets contained or created in a
history.
"""
import logging
from typing import Dict
from galaxy import model
from galaxy.managers import (
annotatable,
base,
deletable,
hdas,
secured,
taggable
)
from gala... |
from rest_framework.authtoken.models import Token
def token_authenticate(api_client, user):
token, _ = Token.objects.get_or_create(user=user)
api_client.credentials(HTTP_AUTHORIZATION="Bearer " + token.key)
api_client.auth_user = user
return api_client
|
from pydantic import BaseModel # pylint: disable=E0611
class Colour(BaseModel):
"""Model for a colour."""
colour: str
|
from typing import List, Dict, Any, Tuple, Optional
import numpy as np
import tensorflow as tf
from typilus.model.components.multiheadattention import transformer_model
from typilus.model.components.tokenembedder import TokenEmbedder
from typilus.model.typeclassificationmodel import TypeClassificationModel
fr... |
from copy import deepcopy
from mediation_service.mediation.prepare_ssp_response import (
ALLERGIES_AND_ADVERSE_REACTION_LIST_CODE,
ENDED_ALLERGIES_LIST_CODE,
prepare_ssp_response,
_extract_resolved_allergies,
_select_lists_with_code,
)
import re
def test_list_selection():
fhir_res = {
... |
"""create_recipe_ingredients_table
Revision ID: 8f0a903d18dc
Revises: 9ecdc8f598bb
Create Date: 2021-01-06 10:05:20.710960
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '8f0a903d18dc'
down_revision = '9ecdc8f598bb'
branch_labels = None
depends_on = None
def... |
import socket
import socks
import threading
# "Thanks" to stem!
try:
# Added in 3.x
import queue
except ImportError:
import Queue as queue
class SimpleController(object):
_socket = None
def __init__(self):
assert (self._socket is not None), 'SimpleController is not initialized!'
sel... |
#!/usr/bin/env python3
import sys
print(f"stdout is a tty: {sys.stdout.isatty()}")
print(f"stdin is a tty: {sys.stdin.isatty()}")
|
from oic import rndstr
from oic.extension.token import JWTToken
__author__ = 'roland'
class NotAllowed(Exception):
pass
class TokenHandler(object):
def __init__(self, issuer, token_policy, token_factory=None,
refresh_token_factory=None, keyjar=None, sign_alg='RS256'):
"""
N... |
# Copyright 2014 Amazon.com, Inc. or its affiliates. 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. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompa... |
#!/usr/bin/env python
# The contents of this file are subject to the BitTorrent Open Source License
# Version 1.1 (the License). You may not copy or use this file, in either
# source code or executable form, except in compliance with the License. You
# may obtain a copy of the License at http://www.bittorrent.com/li... |
"""
This file provides internal compiler utilities that support certain special
operations with bytes and workarounds for limitations enforced in userland.
"""
from numba.extending import intrinsic
from llvmlite import ir
from numba import types, cgutils
@intrinsic
def grab_byte(typingctx, data, offset):
# retur... |
from .classifier import *
from .single_attribute_splitter_finder import *
class DecisionTree(Classifier):
def __init__(self, dataset,
min_samples_split=2,
max_depth=float('inf'),
depth=1,
splitter_finder=SingleAttributeSplitterFinder):
sel... |
import pytest
import requests
import urllib3
try:
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
# surpress Unverified HTTPS request warning, due to self signed cert
except Exception as e:
print(f'An exception has occurred while disabling warnings: {e}')
def test_helloworld():
# P... |
import time
from PunchBot import PunchBot
from datetime import datetime
from SMWinservice import SMWinservice
class Schedule(SMWinservice):
"""Classe responsável pela criação do agendamento de execução do serviço."""
# Define os dados de exibição do serviço
_svc_name_ = "MyPunchSchedule"
_svc_displa... |
from __future__ import absolute_import
from . import _agglo as __agglo
from ._agglo import *
import numpy
__all__ = []
for key in __agglo.__dict__.keys():
__all__.append(key)
try:
__agglo.__dict__[key].__module__='nifty.graph.agglo'
except:
pass
from ...tools import makeDense as __makeDen... |
import pytest
import supercollider
from supercollider.globals import ALLOCATOR_BUS_START_INDEX, ALLOCATOR_BUS_CAPACITY
from tests.shared import server
def test_bus(server):
for cls in [ supercollider.AudioBus, supercollider.ControlBus ]:
bus1 = cls(server, 2)
assert bus1.id == ALLOCATOR_BUS_START... |
# -*- coding: utf-8 -*-
# @Time : 17/11/2020 15:00
# @Author : anlei
# @File : naivebayes2.py
from sklearn.datasets import fetch_20newsgroups
from sklearn.model_selection import train_test_split
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.naive_bayes import MultinomialNB
news = fetch_... |
# -*- Python -*-
# This file is licensed under a pytorch-style license
# See frontends/pytorch/LICENSE for license information.
import typing
import torch
import torch_mlir
# RUN: %PYTHON %s | npcomp-opt | FileCheck %s
mb = torch_mlir.ModuleBuilder()
# TorchScript doesn't model object identity correctly!!!
#
# As ... |
import masterPlugin
import MatrixUtils
import os
## Wrapper fro MatrixUtils.head()
class head(masterPlugin.masterPlugin):
def __init__(this):
super().__init__()
this.command = "head"
this.aliases = None
this.commandInfo = {'requiredArguments': [[0, str, 'path']],
'optio... |
"""
SQLAlchemy models - defines table for storing scraped data.
"""
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import ForeignKey, Column, Integer, Float, String, Text, DateTime
from sqlalchemy.orm import relationship
from .util.history_meta import Versioned
Base = declarative_base()
de... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 字典
# 查找和插入的速度极快,不会随着key的增加而变慢
# 需要占用大量的内存
dic = {'name':'hong', 'age':29}
print(dic)
print(dic['age'])
# 修改
dic['age'] = 30
dic['gender'] = 'male'
print(dic)
# 删除
del dic['gender']
print(dic)
# dic.clear()
# print(dic)
# 方法
print(str(dic))
|
def join_challenge( url, headers, code=False):
"""Formated print the Zindi's challenge submission-board as table.
Parameters
----------
url : string
The url of the selected challenge.
headers : dictionary
The headers of the request to participate in a challenge.
""" |
import ast.value
import ast.qualifier
import ast.mixins.node
import ast.mixins.typed
import ast.mixins.qualified
class LValueExpression(ast.mixins.node.Node, ast.mixins.typed.Typed, ast.mixins.qualified.Qualified):
def __init__(self):
super().__init__()
self.__value: ast.value.Value or None = No... |
from django.contrib import admin
from .models import (
Dialog,
DialogMembership,
DialogMessage,
DialogMessageInfo,
)
admin.site.register(Dialog)
admin.site.register(DialogMembership)
admin.site.register(DialogMessage)
admin.site.register(DialogMessageInfo)
|
import pkg_resources
import pytest
import pyutils
def test_version() -> None:
expect = pkg_resources.get_distribution('pyutils').version
actual = pyutils.__version__
assert expect == actual
if __name__ == '__main__':
pytest.main([__file__, '-v'])
|
import pygame.sprite
class LayoutManager(pygame.sprite.LayeredDirty):
"""
.
"""
pass
|
import toml
from acrul_toolkit import __version__
def test_version():
version = toml.load("./pyproject.toml")["tool"]["poetry"]["version"]
assert __version__ == version
|
import pygame;
def score_board(highscore,current_score,highscore_board_font,score_board_font,screen):
if(highscore>=current_score):
highscore_board=highscore_board_font.render("HIGHSCORE:"+str(highscore),True,(255,0,0))
else:
highscore_board=highscore_board_font.render("HIGHSCORE:"+"PASS",True,(255,0,0))... |
from argv.iterables import peekable
from argv.flags import parse_tokens
from argv.parsers.boolean import BooleanParser, BooleanArgument
class DescriptiveArgument(BooleanArgument):
# not much more than a named tuple
def __init__(self, names, default, boolean, positional, help=None):
# names is a list o... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.