text
string
size
int64
token_count
int64
# Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html # For details: https://github.com/PyCQA/astroid/blob/main/LICENSE # Copyright (c) https://github.com/PyCQA/astroid/blob/main/CONTRIBUTORS.txt __version__ = "2.11.2" version = __version__
274
115
def method1(X, Y): m = len(X) n = len(Y) L = [[None] * (n + 1) for i in range(m + 1)] for i in range(m + 1): for j in range(n + 1): if i == 0 or j == 0: L[i][j] = 0 elif X[i - 1] == Y[j - 1]: L[i][j] = L[i - 1][j - 1] + 1 els...
921
450
def combination(n, r): r = min(n - r, r) result = 1 for i in range(n, n - r, -1): result *= i for i in range(1, r + 1): result //= i return result N, A, B = map(int, input().split()) v_list = list(map(int, input().split())) v_list.sort(reverse=True) mean_max = sum(v_list[:A]) / A ...
661
292
import behave @behave.when(u"I list triggers") def step_impl(context): context.trigger_list = context.service.triggers.list() @behave.then(u'I receive a Trigger list of "{count}" objects') def step_impl(context, count): assert context.trigger_list.items_count == int(count) if int(count) > 0: for...
545
164
# Combinatoric selections # https://projecteuler.net/problem=53 from collections import defaultdict from copy import deepcopy from itertools import permutations from math import fmod, sqrt, factorial from time import time start = time() f = [factorial(i) for i in range(101)] ans = 0 for n in range(1, 101): for r...
437
165
from .smpl_flow import SMPLFlow from .skeleton_flow import SkeletonFlow from .fc_head import FCHead
99
34
""" Module for demo abstract class """ from abc import ABC, abstractmethod class DemoAbstract(ABC): """ Demo abstract class for testing purposes """ @abstractmethod def demo_abstract_method(self): """ Demo abstract method """ def demo_method(self): """ Demo concrete method """ ...
327
80
# The client program connects to server and sends data to other connected # clients through the server import socket import thread import sys def recv_data(): "Receive data from other clients connected to server" while 1: try: recv_data = client_socket.recv(4096) ...
1,953
636
import numpy as np import matplotlib.pyplot as plt import matplotlib.cm as cm import matplotlib.animation as animation class animacija2D: def __init__(self, f, xInterval, yInterval, fN=20): """ Priprava grafa in skiciranje funkcije. """ self.f = f self.xlim = xInterval self.ylim = y...
4,487
1,726
# External Modules import numpy as np from sklearn.ensemble import GradientBoostingClassifier from sklearn.model_selection import train_test_split from sklearn.model_selection import GridSearchCV from sklearn.ensemble import VotingClassifier from sklearn.metrics import accuracy_score # Internal Modules import Helpers....
2,452
744
''' 本模块用于数据预处理 This module is used for data preproccessing ''' import numpy as np from maysics.utils import e_distances from matplotlib import pyplot as plt plt.rcParams['font.sans-serif'] = ['FangSong'] plt.rcParams['axes.unicode_minus'] = False from io import BytesIO from lxml import etree import base64 import math ...
22,847
8,953
from .Styles import NoStyle class GridArea: def __init__(self, position_marker): self.style = NoStyle() self.position = position_marker def reset(self): self.style = NoStyle() def current_state(self): print(self.style.display(), end="", flush=True) def grid_area_sty...
756
213
#!/usr/bin/env python3 # # Copyright (c) 2015-2017 Nest Labs, 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/lice...
2,140
706
import requests from bs4 import BeautifulSoup from time import sleep headers = { 'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36' } def parse(url): print('Parsing..' + url) return 'Parsed..' + url def pull(category_...
2,383
749
import os from pprint import pprint import json def main(): patterns = { "l_pentomino": '[{"30":[30,31],"31":[30],"32":[30],"33":[30]}]', "flower_pentomino": '[{"30":[31],"31":[30,31],"32":[32],"33":[31]}]', "kite_heptomino": '[{"30":[30,31],"31":[30],"32":[30,31],"33":[32]}]', "bo...
2,700
1,411
import sys sys.path.append("../../") from appJar import gui def press(btn): if btn == "FIRST": app.firstFrame("Pages") elif btn == "NEXT": app.nextFrame("Pages") elif btn == "PREV": app.prevFrame("Pages") elif btn == "LAST": app.lastFrame("Pages") def changed(): msg = "Changed from: " + str(app....
935
322
import logging from django.conf import settings from django.db.models import Case, F, Prefetch, Q, Sum, When from drf_spectacular.types import OpenApiTypes from drf_spectacular.utils import ( OpenApiExample, OpenApiParameter, extend_schema, extend_schema_view, ) from rest_framework import serializers f...
5,557
1,541
import os from flask import current_app from flask import _app_ctx_stack as stack class ConfigWriter(object): def __init__(self, app=None, consul=None, vault=None): self.app = app self.consul = consul self.vault = vault if app is not None: self.init_app(app, consul, v...
2,704
782
variable1 = input('Variable 1:') variable2 = input('Variable 2:') variable1, variable2 = variable2, variable1 print(f"Variable 1: {variable1}") print(f"Variable 2: {variable2}")
177
60
# -*- coding: utf-8 -*- import os import sys import re import settings from auth.connector import TrelloConnector from stats import summary from stats.trelloboardconfiguration import TrelloBoardConfiguration def extract_stats(configuration_file_path): """ Extract stats for a given configuration file that de...
1,748
528
"""Convenience file to help start the game when the repo is cloned from git rather than installed via pip This was required as we needed to run the script from the same level as the housie/ package in order for the imports to work correctly. """ from housie.game import display_main_menu display_main_menu()
310
80
#!/usr/bin/python # -*- coding: utf-8 -*- from copy import deepcopy from .query_tree import Operator, OperatorFactory, Operand, And, Or, Not from .query import Query from .term_parser import Term class QueryParserError(Exception): pass class QueryParser(object): def __init__(self, grammar): self._g...
4,076
1,128
import json import sys import urllib.parse import urllib.request import os import zipfile import io import csv import re from html.parser import HTMLParser code_list = {} with open('data/codepoints.csv') as f: reader = csv.reader(f) for row in reader: d1,d2,d3 = row[0].split('-') d1 = int(d1) ...
3,244
1,109
#!/usr/bin/env python """ setup.py file for SWIG Interface of Ext """ import os import platform import re import subprocess import sys from distutils.version import LooseVersion from os import walk import numpy import wget from setuptools import Extension from setuptools import setup, find_packages from setuptools.co...
3,677
1,150
import discord import subprocess import os, random, re, requests, json import asyncio from datetime import datetime from discord.ext import commands class Economy(commands.Cog): def __init__(self, bot): self.bot = bot @commands.Cog.listener() async def on_ready(self): print('[+] Trashmoney Code AC...
2,442
902
# Copyright 2014 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 ...
1,738
591
from __future__ import absolute_import, unicode_literals from celery import shared_task from asgiref.sync import async_to_sync from channels.layers import get_channel_layer import requests import csv @shared_task def getStockQuote(room_group_name, stock_code): url = 'https://stooq.com/q/l/?s=%s&f=sd2t2ohlcv&h&e=cs...
1,515
421
from summarize import Summarizer def test_person_summary(): s = Summarizer() people = [ { "gender": "F", "image": "https://example.com/image1", "party": [{"name": "Democratic"}, {"name": "Democratic", "end_date": "1990"}], }, { "gender":...
1,397
495
"""Exercício Python 091: Crie um programa onde 4 jogadores joguem um dado e tenham resultados aleatórios. Guarde esses resultados em um dicionário em Python. No final, coloque esse dicionário em ordem, sabendo que o vencedor tirou o maior número no dado.""" from random import randint from time import sleep from operato...
853
319
# Submit to spark using # spark-submit /Users/anurag/hdproject/eclipse/chapt3/transfrauddetect.py # You need the full path of the python script from pyspark import SparkContext from pyspark import SparkConf from pyspark.mllib.clustering import KMeans, KMeansModel from pyspark.streaming import StreamingContext from pys...
1,499
469
def main(): # Manage input file input = open(r"C:\Users\lawht\Desktop\Github\ROSALIND\Bioinformatics Stronghold\Complementing a Stand of DNA\Complementing a Stand of DNA\rosalind_revc.txt","r") DNA_string = input.readline(); # take first line of input file for counting # Take in input file of DNA stri...
904
294
""" Given a binary tree, return the postorder traversal of its nodes' values. For example: Given binary tree {1,#,2,3}, 1 \ 2 / 3 return [3,2,1]. """ # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # ...
950
290
import yaml class BaseTest(object): def setUp(self): with open("properties.yaml") as f: self.cfg = yaml.safe_load(f) self.general = self.cfg['general'] self.reseller = self.cfg['reseller'] self.client = self.cfg['client'] self.service_zimbra = self.cfg['service_zimbra'] self.serv...
687
245
from jobbergate import appform def mainflow(data): return [appform.Const("val", default=10)]
99
34
from django.apps import AppConfig class OsoricrawlerapiConfig(AppConfig): name = 'osoriCrawlerAPI'
105
36
# coding: utf-8 from lxml import html from django.test import TestCase from django.test.client import Client from quotes.tests.utils import create_test_quote class HomePageTestCase(TestCase): def setUp(self): self.client = Client() self.quote = create_test_quote() self.dom = '' ...
2,186
686
from numpy import char from function_support import * def confirm(n,e,d): s = 'i have publicKey' temp = "" encode = [] #encrypt for i in s: c = powermod(ord(i),e,n) encode.append(c) #decrypt for i in encode: m = powermod(i,d,n) print(m) temp = temp + ...
414
149
# -*- coding: utf-8 -*- import re __author__ = 'luckydonald' __all__ = [ 'USERNAME_REGEX', '_USERNAME_REGEX', 'USER_AT_REGEX', '_USER_AT_REGEX', 'FULL_USERNAME_REGEX', '_FULL_USERNAME_REGEX' ] _USERNAME_REGEX = '[a-zA-Z](?:[a-zA-Z0-9]|_(?!_)){3,30}[a-zA-Z0-9]' # https://regex101.com/r/nZdOHS/2 USERNAME_REGEX...
678
339
# 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 from ... import _utilities, _tables from...
42,439
11,835
from datetime import datetime, timedelta import pytest from django.test import TestCase from tests.models import Org, Sub, Widget data_org = {"name": "Acme Widgets"} class FieldTestCase(TestCase): def setUp(self): self.org = Org.objects.create(**data_org) self.created = datetime.now() s...
809
257
from flask import Flask, render_template, request, redirect, url_for, Markup, \ flash # Imports Flask and all required modules import databasemanager # Provides the functionality to load stuff from the database app = Flask(__name__) import errormanager # Enum for types of errors # DECLARE datamanager as...
6,888
2,031
import scipy.sparse as ssp import scipy.sparse.csgraph as csgraph import networkx as nx import pylab as pl import pygraphviz as pgv from itertools import product, chain class DiGraph(ssp.lil_matrix): """ An implementation of a directed graph with a Sparse Matrix representation using Scipy's sparse module. ...
8,108
2,536
import sys import json import time import os.path import subprocess # Current working directory cwd = os.path.dirname(os.path.realpath(__file__)) # Boolean flag that tells the program whether the user enabled text notifications txt_notifs = True # Clear terminal screeen os.system('cls' if os.name == 'nt...
9,487
3,227
from ansible.errors import AnsibleFilterError def container2volumes(container, vol_type="all"): vol_types = ["generated", "persistent", "volatile"] catch_all_type = "all" if vol_type != catch_all_type and vol_type not in vol_types: raise AnsibleFilterError( f"container2volumes: {vol_ty...
1,312
394
import datetime import json import re import time from decimal import Decimal import httpx from cryptofeed_werks.controllers import HTTPX_ERRORS, iter_api from cryptofeed_werks.lib import parse_datetime from .constants import API_URL, MAX_RESULTS, MIN_ELAPSED_PER_REQUEST, MONTHS def get_bitmex_api_url(url, paginat...
4,593
1,434
import sys def lowest_unique_number(line): numbers = sorted(map(int, line.split())) for e in numbers: if numbers.count(e) == 1: return line.index(str(e))//2+1 return 0 def main(): with open(sys.argv[1]) as input_file: for line in input_file: print(lowest_unique_...
381
130
""" A simple game for English language development students in primary school. English sentences are presented with a scrambled word order. Students click each word to put it in correct English order (e.g., adjectives come before nouns). """ import config import flask from flask import request from flask import s...
3,247
998
""" Test the Model class. Notes ----- o The specific test values were computed using the MatLab code from the "Object Based Analytic Elements" project. Author ------ Dr. Randal J. Barnes Department of Civil, Environmental, and Geo- Engineering University of Minnesota Version ------- 09 May 2020...
3,717
2,331
# This is python2 version. def FizzBuzzWhizz(args): """args[0] = Fizz, Buzz, Whizz args[1]= 3, 5, 7""" def FBW(Number): return Number%args[1] and Number or args[0] return FBW def sayWhat(l_sayWhat,Number): return l_sayWhat.count(Number)<3 and "".join([s for s in l_sayWhat if type(s) is...
830
351
import matplotlib.pyplot as plt import numpy as np from kalman import * def kf_trace(F,g,P,H,j,Q,Xmean,Xvar,Z): if not isinstance(F,np.ndarray): F = np.array([[F]]) if not isinstance(g,np.ndarray): g = np.array([g]) if not isinstance(P,np.ndarray): P = np.array([[P]]) if H is not None: if not i...
3,022
1,481
## ## Software PI-Net: Pose Interacting Network for Multi-Person Monocular 3D Pose Estimation ## Copyright Inria and UPC ## Year 2021 ## Contact : wen.guo@inria.fr ## ## The software PI-Net is provided under MIT License. ## #used in train for skeleton input import os import os.path as osp import numpy as np import mat...
6,687
2,681
from django.conf.urls import url from .views import do_search, filter urlpatterns = [ url(r'^$', do_search, name='search'), url(r'^filter/', filter, name='filter') ]
174
61
import discord import slash_util class SampleCog(slash_util.Cog): @slash_util.slash_command(guild_id=123) async def pog(self, ctx: slash_util.Context): await ctx.send("pog", ephemeral=True) @slash_util.message_command(guild_id=123) async def quote(self, ctx: slash_util.Context, message: discor...
693
250
# encoding=utf-8 # Elkatip import os import imp # main class class Elkatip(): api = None gui = None def __init__(self): self.modulePath = os.path.dirname(__file__) pass def toExt(self, text): if not self.api: api = imp.load_source("api", self.modulePath + "/api.p...
1,047
386
from __future__ import absolute_import from sklearn.exceptions import NotFittedError from sklearn.neighbors import KernelDensity from sklearn.linear_model import LinearRegression, LogisticRegression import pickle import os import matplotlib.pylab as plt from sklearn.externals import joblib import numpy as np from sklea...
7,704
2,523
""" Crie um programa que leia vários números inteiros pelo teclado. No final da execução, mostre a média entre todos os valores e qual foi o maior e o menor valores lidos. O programa deve perguntar ao usuário se ele quer ou não continuar a digitar valores. """ resposta = 'S' cont = soma = maior = menor = media = 0 whi...
998
331
import tpdp class PythonModifier(tpdp.ModifierSpec): def AddHook(self, eventType, eventKey, callbackFcn, argsTuple ): self.add_hook(eventType, eventKey, callbackFcn, argsTuple) def ExtendExisting(self, condName): self.extend_existing(condName) def AddItemForceRemoveHandler(self): # in charg...
1,329
442
import torch import torch.nn as nn import torch.nn.functional as F import math # --1.2.1 class one_conv(nn.Module): def __init__(self, in_ch, out_ch, normaliz=False): super(one_conv, self).__init__() ops = [] ops += [nn.Conv2d(in_ch, out_ch, 3, padding=1)] # ops += [nn....
7,279
3,016
ADMIN_THEME = "admin" DEFAULT_THEME = "core"
45
20
import json from flask import Flask, request from pymongo import MongoClient, ASCENDING, DESCENDING from pymongo.errors import ConnectionFailure, ConfigurationError, OperationFailure, AutoReconnect app = Flask(__name__) mongo_connections = {} @app.route('/_connect', methods=['POST']) def connect(): name = request...
6,865
2,087
""" ========================================= Robust line model estimation using RANSAC ========================================= In this example we see how to robustly fit a line model to faulty data using the RANSAC (random sample consensus) algorithm. Firstly the data are generated by adding a gaussian noise to a ...
4,147
1,369
def fibonacci(n, res=[0,1]): if len(res)<=n: res.append(fibonacci(n-1)+fibonacci(n-2)) return res[n]
116
56
all_591_cities = [ { "city": "台北市", "id": "1" }, { "city": "新北市", "id": "3" }, { "city": "桃園市", "id": "6" }, { "city": "新竹市", "id": "4" }, { "city": "新竹縣", "id": "5" }, { "city": "基隆市", "id": "2" }, { "city": "宜蘭縣", "id": "21" }, { ...
915
575
# -*- coding: UTF-8 -*- import os import json import logging from googleapiclient.discovery import build from tqdm import tqdm from data import get_classes_ordered logging.getLogger('googleapicliet.discovery_cache').setLevel(logging.ERROR) variables_file = 'variables.json' with open(variables_file) as f: config = ...
7,178
2,180
#!/usr/bin/env python3 # -*- coding: utf-8 -*- def part_1(program): i = 0 while i < len(program): opcode, a, b, dest = program[i:i+4] i += 4 assert opcode in {1, 2, 99}, f'Unexpected opcode: {opcode}' if opcode == 1: val = program[a] + program[b] elif opcod...
1,041
412
# Copyright 2021 Duan-JM, Sun Aries # 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...
1,493
515
from bs4 import BeautifulSoup import urllib.request import xml.etree.ElementTree as ET from tqdm import tqdm from time import sleep #Try With This Website http://igm.univ-mlv.fr/ LinksList = [] def progress(rang): for i in tqdm(rang, desc ="Progress : "): sleep(.1) var=input("Enter a Websit...
1,712
634
from flask import Flask, request, jsonify import os, sys import helpers, escape_helpers import logging import config from rdflib.namespace import Namespace ############## # INIT CONFIG ############## CONFIG = config.load_config(os.environ.get('ENVIRONMENT', "DEBUG")) app = Flask(__name__) handler = logging.StreamHan...
3,237
1,118
""" This file illustrates a few examples of using pgmock with pytest. A postgres testing database from pytest-pgsql (https://github.com/CloverHealth/pytest-pgsql) is used and a fixture is created for using the mock context manager. This is the preferred way of using pgmock, but it's also possible to render SQL yoursel...
2,406
794
# -*- coding: utf-8 -*- __author__ = 'Matthias Uschok <dev@uschok.de>' import json import BaseHTTPServer import threading from urlparse import parse_qs, urlparse import status callbacks = dict() class JsonHandler(BaseHTTPServer.BaseHTTPRequestHandler): def do_GET(self): print("path:", self.path) ...
3,019
951
from django.contrib.auth.models import Permission, Group from rest_framework import viewsets, mixins, response, status from rest_framework.generics import get_object_or_404 from .serializer import PermissionSerializer from .common import get_permission_obj from .filter import PermissionFilter class PermissionsViews...
4,456
1,323
#!/usr/bin/env python # -*- coding: utf-8 -*- import base64 import simplejson as json from collections import Counter import jsonpickle from mrtarget.common import require_all from mrtarget.common.connection import new_redis_client jsonpickle.set_preferred_backend('simplejson') import logging import uuid import datet...
4,267
1,370
from typing import * import discord from helpers.exceptions import ModuleNotActivatedException from webserver import Page if TYPE_CHECKING: from helpers.module_manager import ModuleManager from helpers.spark_module import SparkModule class ModuleApiPagesManager: def __init__(self, module_manager: 'Modu...
2,133
570
# Generated by Django 3.2 on 2021-05-16 05:09 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('app', '0005_auto_20210515_1932'), ] operations = [ migrations.AddField( model_name='housing', name='description', ...
401
145
''' Module with helper classes to create new persistables ''' from abc import ABCMeta, abstractmethod from simpleml.persistables.meta_registry import SIMPLEML_REGISTRY from simpleml.datasets.base_dataset import Dataset from simpleml.pipelines.base_pipeline import Pipeline from simpleml.models.base_model import Model fr...
14,313
3,561
#!/usr/bin/env python """Generates a poller file that will be used as input to runsinglehap.py, hapsequencer.py, runmultihap.py or hapmultisequencer.py based on the files or rootnames listed user-specified list file. USAGE >>> python drizzlepac/haputils/make_poller_files.py <input filename> -[ost] - input fil...
13,068
3,698
# -*- encoding: utf-8 -*- # Copyright (c) 2019 Dantali0n # # 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 ...
2,118
636
# Copyright (C) 2007-2012 Red Hat # see file 'COPYING' for use and warranty information # # policygentool is a tool for the initial generation of SELinux policy # # 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 ...
3,932
1,529
"""A module dedicated to writing data to a workbook.""" import logging from contextlib import contextmanager import openpyxl.styles from htmxl.compose.cell import Cell from htmxl.compose.recording import Recording from htmxl.compose.style import style_range from htmxl.compose.write import elements logger = logging.g...
5,909
1,726
""" Compartmentalize: [ ascii art input ] --------------- | maybe some | | sort of auxillary | | drawing program | | | \ / v [ lex/parser ] --> [ translater ] --------- ---------- | grammar | | notes literals| | to numerical | ...
820
222
import unittest from ...scenes import Scene class TestSceneMethods(unittest.TestCase): def test_scene(self): scene = Scene() if __name__ == "__main__": unittest.main()
189
64
import sys import numpy as np sys.path.append("./") from vedo import screenshot from vedo.shapes import Tube from myterial import salmon from manifold import embeddings, Plane from manifold.visualize import Visualizer from manifold import visualize from manifold.rnn import RNN """ 3D viisualization of an RNN's...
1,545
667
############################################################################### '''''' ############################################################################### from functools import cached_property from collections import OrderedDict from collections.abc import Sequence from .channel import DataChannel from .sp...
2,567
718
""" Endpoint Entity Module """ # Django from django.contrib.auth.models import User # local Django from app.models import Endpoint from app.models import Namespace from app.models import Endpoint_Meta from app.modules.util.helpers import Helpers class Endpoint_Entity(): GET = "get" POST = "post" HEADE ...
3,591
1,024
# The MIT License (MIT) # Copyright (c) 2021 Tom J. Sun # 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, ...
12,005
3,815
#!/usr/bin/env python3.5 """CTMR list scanner""" __author__ = "Fredrik Boulund" __date__ = "2018" __version__ = "0.4.0b" from datetime import datetime from pathlib import Path import sys from fbs_runtime.application_context import ApplicationContext, cached_property from PyQt5 import QtCore from PyQt5.QtWidgets impor...
21,705
6,496
# # Default loader that doesn't do anything special # # Copyright (c) 2020, Arm Limited. All rights reserved. # SPDX-License-Identifier: BSD-3-Clause # from .. import loaders import os @loaders.loader class NoOpLoader(loaders.Loader): """ A loader that does nothing, allowing execution in the specified fla...
4,411
1,261
# -*- coding: utf-8 -*- # # Copyright 2019-2020 - Swiss Data Science Center (SDSC) # A partnership between École Polytechnique Fédérale de Lausanne (EPFL) and # Eidgenössische Technische Hochschule Zürich (ETHZ). # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in c...
8,007
2,879
#!/usr/bin/evn python3 # coding=utf-8 import logging import redis from typing import Any from conf import dev_conf as conf from util import singleton @singleton class Config: """ 根据指定的配置文件,把conf文件转换成字典 默认情况下使用 conf 中的配置 """ def __init__(self): self.config = conf self.redis_db = N...
2,458
882
import json import os script_path = os.path.abspath(__file__) script_dir = os.path.split(script_path)[0] def get_config(): rel_path = 'resources/config.json' path = os.path.join(script_dir, rel_path) with open(path, 'r') as f: config = json.loads(f.read()) return config def get_submissions...
1,340
500
import unittest from reamber.algorithms.convert.OsuToQua import OsuToQua from reamber.osu.OsuMap import OsuMap from tests.test.RSC_PATHS import * # import logging # # logging.basicConfig(filename="event.log", filemode="w+", level=logging.DEBUG) class TestOsuToQua(unittest.TestCase): # @profile def test_os...
907
362
from flask import g from flask_socketio import SocketIO, emit from logic.game_manager import GameManager from logic.player_manager import PlayerManager from logic.player_logic import PlayerLogic from globals import socketio, db from session import SessionHelper, SessionKeys from utils.response import Response from uti...
1,644
502
# TC2008B. Sistemas Multiagentes y Gráficas Computacionales # Python flask server to interact with Unity. Based on the code provided by Sergio Ruiz. # Octavio Navarro. October 2021 from flask import Flask, request, jsonify from RandomAgents import * # Size of the board: number_agents = 10 width = 28 height = 28 traff...
1,943
630
from django.contrib import admin from .models import Rating # Register your models here. @admin.register(Rating) class RatingAdmin(admin.ModelAdmin): date_hierarchy = 'created_on' search_fields = ['user_id__username', 'value'] list_display = ('user_id', 'value',) list_filter = ('user_id', 'value', 'is...
331
108
from __future__ import division from scitbx.examples import immoptibox_ports from scitbx.math import gaussian from scitbx.array_family import flex from libtbx.test_utils import approx_equal, eps_eq from libtbx.utils import format_cpu_times try: import cPickle as pickle except ImportError: import pickle from cString...
20,406
10,497
import discpy from discpy import commands bot = commands.Bot(command_prefix='!') # you can set "arg" keyword argument to the name of argument that represents the option in the command function # and then change the option name as desired. @bot.slash_command() @discpy.application.option('sentence', arg='text', descrip...
575
166
from huaweisms.api.common import get_from_url, ApiCtx from .config import API_URL def status(ctx: ApiCtx): url = "{}/monitoring/status".format(API_URL) return get_from_url(url, ctx)
192
72
# Generated by Django 3.1.4 on 2021-01-04 01:29 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('accounts', '0004_auto_20210103_1820'), ] operations = [ migrations.RenameField( model_name='order', old_name='products', ...
366
135
"""add role Revision ID: 221ccee39de7 Revises: ba9704e35cb2 Create Date: 2021-05-13 23:51:53.241485 """ import sqlalchemy as sa from alembic import op from sqlalchemy.dialects import postgresql # revision identifiers, used by Alembic. revision = "221ccee39de7" down_revision = "ba9704e35cb2" branch_labels = None depe...
1,708
602
#!/usr/bin/env python3 # coding: utf-8 # Copyright 2016 Abram Hindle, https://github.com/tywtyw2002, and https://github.com/treedust # # 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 # # ...
5,101
1,680