text
string
size
int64
token_count
int64
import os from pathlib import Path import pandas as pd from lime.lime_tabular import LimeTabularExplainer from ml_editor.data_processing import get_split_by_author FEATURE_DISPLAY_NAMES = { "num_questions": "물음표 빈도", "num_periods": "마침표 빈도", "num_commas": "쉼표 빈도", "num_exclam": "느낌표 빈도", "num_quot...
4,880
2,460
""" Tests for the test utils. """ import pytest from straitlets import Serializable, Integer from straitlets.test_utils import assert_serializables_equal def test_assert_serializables_equal(): class Foo(Serializable): x = Integer() y = Integer() class Bar(Serializable): x = Integer(...
912
336
""" In the last report, "bias_categories.py" I showed that offline bias of the limited RNN cannot be improved by thresholding large relative decreases of cloud to 0. Doing so increased the bias. What about the non-limited RNNS? It turns out that these RNNs have approximately 10x smaller bias. However, they produce ne...
6,458
2,423
import numpy from fdm.geometry import create_close_point_finder def create_weights_distributor(close_point_finder): def distribute(point, value): close_points = close_point_finder(point) distance_sum = sum(close_points.values()) return dict( {p: (1. - distance/distance_sum)*va...
4,026
1,367
import unittest from csound import output, orchestra from csound.orchestra import gen08 from data import constants as c from data import get class TestSounds(unittest.TestCase): def test_simple_soundwaves(self): # Get all data place = "Madrid" mad2t = get(c.T, location=place) ma...
1,300
441
import Adafruit_DHT as dht import time from influxdb import InfluxDBClient def get_serial(): cpu_serial = "0000000000000000" try: f = open('/proc/cpuinfo', 'r') for line in f: if line[0:6] == 'Serial': cpu_serial = line[10:26] f.close() except: cp...
1,058
415
import numpy as np from scipy.sparse import issparse from scipy.sparse import vstack from sklearn.model_selection import train_test_split, RepeatedStratifiedKFold from quapy.functional import artificial_prevalence_sampling, strprev class LabelledCollection: ''' A LabelledCollection is a set of objects each w...
9,319
2,858
class FixtureException(Exception): pass class FixtureUploadError(FixtureException): pass class DuplicateFixtureTagException(FixtureUploadError): pass class ExcelMalformatException(FixtureUploadError): pass class FixtureAPIException(Exception): pass class FixtureTypeCheckError(Exception): ...
381
116
# -*- coding: utf-8 -*- from process_gram import process_grammar import codecs first_pp = ['мы', 'я', 'наш', 'мой'] second_pp = ['ты', 'вы', 'ваш', 'твой'] third_pp = ['он', 'она', 'они', 'оно', 'их', 'ee', 'его', 'ихний', 'ихним', 'ихнем'] indef_pron = ['некто', 'некого', 'некому', 'некем', 'нечто', 'нечего', 'нечему...
55,763
19,157
from .abstract_graph import AbstractGraph from .matrix_graph import MatrixGraph __all__ = [ "AbstractGraph", "MatrixGraph", ]
134
39
#!/usr/bin/env python3 # tuples is a type of list. # tuples is immutable. # the structure of a tuple: (1, "nice work", 2.3, [1,2,"hey"]) my_tuple = ("hey", 1, 2, "hey ho!", "hey", "hey") print("My tuple:", my_tuple) # to get a tuple value use it's index print("Second item in my_tuple:", my_tuple[1]) # to count how ...
856
302
#!/usr/bin/env python3 import subprocess import requests import json import os import re import argparse import logging import csv import shutil retracted_exps = "retracted_exps.csv" #Generic info list from file here. logging.basicConfig(level=logging.INFO, format='%(levelname)s: %(message)s') handle_api = "https://...
7,048
2,140
# Copyright 2015 DataStax, Inc. # # 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, s...
9,485
3,009
__author__ = "Tomasz Rybotycki" import abc from numpy import ndarray class NetworkSimulationStrategy(abc.ABC): @classmethod def __subclasshook__(cls, subclass): return hasattr(subclass, "simulate") and callable(subclass.simulate) @abc.abstractmethod def simulate(self, input_state: ndarray) ...
366
115
# Generated by Django 3.1.1 on 2020-09-23 19:48 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('core', '0019_auto_20200923_1942'), ] operations = [ migrations.AlterField( model_name='orderite...
769
261
#!/usr/bin/env python """ Nicholas' Example API code for interacting with Alienvault API. This is just Example code written by NMA.IO. There isn't really much you can do with the API just yet, so this will be a work in progress. Grab your API key here: https://www.alienvault.com/documentation/usm-anywhere/api/ali...
1,989
669
import yaml from Helper import Level from typing import List, Dict from os.path import join from ..action_information import ActionInformation class Loader: @classmethod def EnsureFolder(cls, path: str) -> [(Level, str)]: from Helper import IO validation = [] if not IO.EnsureFolder(pat...
2,768
729
from timebox.timebox import TimeBox from timebox.utils.exceptions import InvalidPandasIndexError import pandas as pd import numpy as np import unittest import os import logging class TestTimeBoxPandas(unittest.TestCase): def test_save_pandas(self): file_name = 'save_pandas.npb' df = pd.read_csv('t...
2,140
711
from typing import Any from flaskapp.models import Activities, Logs, LogsToActivities, db from sqlalchemy.sql.expression import desc, func """ Este modulo contiene funciones para escribir y leer los logs desde el chatbot """ MAX_LOGS_PER_QUERY = 5 MAX_STR_SIZE_LOGS = 128 def write_log( chatid: int, intent: ...
2,143
648
""" Luhn Algorithm """ from typing import List def is_luhn(string: str) -> bool: """ Perform Luhn validation on input string Algorithm: * Double every other digit starting from 2nd last digit. * Subtract 9 if number is greater than 9. * Sum the numbers * >>> test_cases = [79927398710, ...
1,233
500
# coding=utf-8 # /usr/bin/python gen_files.py 100 import os import sys import time from settings import * from settings_advanced import * try: import cPickle as pickle except ImportError: import pickle from content_parser import DescriptionParser from content_parser_advance import AdvancedDescriptionParser ...
2,477
874
from tkinter import * import tkFileDialog root = Tk() menubar = Menu(root) root.config(menu=menubar) root.title('Tk Menu') root.geometry('150x150') filemenu = Menu(menubar) filemenu2 = Menu(menubar) filemenu3 = Menu(menubar) menubar.add_cascade(label='Arquivo', menu=filemenu) menubar.add_cascade(label='Cores', menu=...
1,287
453
from extensions import db import datetime import json class Link(db.Document): lid = db.SequenceField(unique=True) longUrl = db.StringField() shortUrl = db.StringField() date_submitted = db.DateTimeField(default=datetime.datetime.now) usage = db.IntField(default=0) def __unicode__(self): ...
349
108
#! /usr/bin/env python # -*- coding: iso-8859-15 -*- ############################################################################## # Copyright 2003 & onward LASMEA UMR 6602 CNRS/Univ. Clermont II # Copyright 2009 & onward LRI UMR 8623 CNRS/Univ Paris Sud XI # # Distributed under the Boost ...
6,132
1,974
import requests import os, shutil import re folder = 'content/post' for filename in os.listdir(folder): file_path = os.path.join(folder, filename) try: if os.path.isfile(file_path) or os.path.islink(file_path): os.unlink(file_path) elif os.path.isdir(file_path): shutil.r...
1,159
421
def possibleHeights(parent): edges = [[] for i in range(len(parent))] height = [0 for i in range(len(parent))] isPossibleHeight = [False for i in range(len(parent))] def initGraph(parent): for i in range(1, len(parent)): edges[parent[i]].append(i) def calcHeight(v): fo...
1,530
526
# -*- coding: utf-8 -*- ######################################################################### # # Copyright (C) 2016 OSGeo # # 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 ...
21,388
6,098
# Copyright 2016-2020 Swiss National Supercomputing Centre (CSCS/ETH Zurich) # ReFrame Project Developers. See the top-level LICENSE file for details. # # SPDX-License-Identifier: BSD-3-Clause import collections.abc import json import jsonschema import os import re import tempfile import reframe import reframe.core.d...
14,203
3,810
from django import forms from django.contrib.auth import authenticate, login from django.utils.timezone import now class LoginForm(forms.Form): """ 登录表单 """ username = forms.CharField(label='用户名', max_length=100, required=False, initial='admin') password = forms.CharField(label='密码', max_length=20...
1,224
396
from django.contrib.auth import get_user_model from django.contrib.auth.models import Permission from django.db.models import Q from guardian.ctypes import get_content_type from guardian.shortcuts import get_perms, get_user_perms from guardian.utils import get_user_obj_perms_model, get_group_obj_perms_model def get_u...
3,263
920
""" ================== welly ================== """ from .project import Project from .well import Well from .header import Header from .curve import Curve from .synthetic import Synthetic from .location import Location from .crs import CRS from . import tools from . import quality def read_las(path, **kwargs): "...
2,090
592
#!/usr/bin/env python3 """ Build the demos Usage: python setup.py build_ext -i """ import numpy as np from distutils.core import setup from Cython.Build import cythonize from setuptools.extension import Extension from os.path import join extending = Extension("extending", sources=['extending.py...
784
214
#!/usr/bin/env python # encoding: utf-8 import signal import sys #import pandas as pd #import numpy as np def setGlobals(g): #print globals() globals().update(g) #print globals() def exit(): mtsExit(0) def quit(signum): sys.exit(signum) def quitNow(signum,frame): quit(signum) def initializ...
2,204
732
import prodigy from prodigy.components.preprocess import add_tokens, split_sentences from plumcot_prodigy.custom_loaders import * import requests from plumcot_prodigy.video import mkv_to_base64 from typing import Dict, List, Text, Union from typing_extensions import Literal import spacy from pathlib import Path """ An...
8,949
2,556
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.3' # jupytext_version: 0.8.6 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + import warnings import pandas as pd import numpy a...
3,326
1,262
from enum import Enum import json from SCA11H.commands.base.PostCommand import PostCommand class Command(Enum): # Restore BCG factory settings.(BCG parameters, direction and running mode) Restore = ('restore', 'restore') # Restore default BCG parameters SetDefaultParameters = ('set_default_pars', 'r...
1,694
472
import sys ''' Criado por Yuri Serrano ''' a,b = input().split() a = int(a) b = int(b) if b > a: print(b) else: print(a)
125
63
# -*- coding: utf-8 -*- # # Tencent is pleased to support the open source community by making QT4C available. # Copyright (C) 2020 THL A29 Limited, a Tencent company. All rights reserved. # QT4C is licensed under the BSD 3-Clause License, except for the third-party components listed below. # A copy of the BSD ...
14,595
5,991
import collections from npyscreen import StandardApp, apNPSApplicationEvents class PipTuiEvents(object): def __init__(self): self.interal_queue = collections.deque() super(apNPSApplicationEvents).__init__() def get(self, maximum=None): if maximum is None: maximum = -1 ...
1,168
313
import logging from django.apps import AppConfig class WebConfig(AppConfig): name = 'web' def ready(self): import web.signals
146
45
from .__main__ import STFTTransform __all__ = [ 'STFTTransform' ]
72
28
#!/usr/bin/env python3 import pandas as pd ft_input='TEMP_DIR/tmp-predictions_reformatted_gexpnn20200320allCOHORTS.tsv' df = pd.read_csv(ft_input,sep='\t') # Get all tumors present in df (ACC, BRCA, ...) temp = df['Label'].unique() u_tumor = {} #k=tumor, v=1 for t in temp: t= t.split(":")[0] if t not in u_t...
544
241
expected_output = { 'instance': { 'isp': { 'address_family': { 'IPv4 Unicast': { 'spf_log': { 1: { 'type': 'FSPF', 'time_ms': 1, 'level': 1, ...
4,291
867
# Copyright 2020 MONAI Consortium # 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, s...
2,706
819
# This file is also a independently runnable file in addition to being a module. # You can run this file to test NewRaphAlgorithm function. ''' This program demonstrates Newton Raphson Algorithm(NPA). It is advised to follow all rules of the algorithm while entering the input. (Either read rules provided in README.md ...
5,670
1,582
from __future__ import division from collections import Counter import numpy as np import glob path_input = "../GO_analysis_PPI_Brucella/2.GO_crudos_y_ancestors/" path_output = "../GO_analysis_PPI_Brucella/3.GO_proporciones/" files = glob.glob(path_input + "*CON_GEN_ID_ancestors*.txt") for f in files: # est...
1,656
567
from itertools import groupby from taxonomic import lca from taxonomic import ncbi n = ncbi.NCBI() def read_relationships(): for line in open('cold/GMGC.relationships.txt'): a,_,b = line.rstrip().split() yield a,b fr12name = {} for line in open('cold/freeze12.rename.table'): i,g,_ = li...
988
372
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import os import sys import openpyxl import csv path = os.curdir if len(sys.argv) > 1: path = sys.argv[1] for excel_file in os.listdir(path): if (not os.path.isfile(excel_file)) or not excel_file.endswith('.xlsx'): continue print('{0}: Writing to csv...
1,001
339
from gpiozero import Button from time import sleep, time import blinkt import random import requests import sys from constants import * FNT_URL = "https://api.fortnitetracker.com/v1/profile/{}/{}" FNT_REFRESH_TIME_SECS = 30 # debug shorter refresh # FNT_REFRESH_TIME_SECS = 10 class FortniteAPIError(Exception): pa...
5,132
1,911
import os, sys from uuid import uuid4 import numpy as np from pathlib import Path import xml.etree.ElementTree as ET import copy import re from urllib import request, parse from pdfminer.layout import LAParams from pdfminer.high_level import extract_text_to_fp from pdf2image import convert_from_path import matplot...
8,704
2,627
# -*- coding: utf-8 -*- from __future__ import print_function """This module installs an import hook which overrides PyQt4 imports to pull from PySide instead. Used for transitioning between the two libraries.""" import imp class PyQtImporter: def find_module(self, name, path): if name == 'PyQt4' and pa...
616
185
import FWCore.ParameterSet.Config as cms from L1TriggerConfig.DTTPGConfigProducers.L1DTTPGConfigFromDB_cff import * dtTriggerPrimitiveDigis = cms.EDProducer("DTTrigProd", debug = cms.untracked.bool(False), # DT digis input tag digiTag = cms.InputTag("muonDTDigis"), # Convert output into DTTF sector nu...
619
230
b = "r n b q k b n r p p p p p p p p".split(" ") + ['.']*32 + "p p p p p p p p r n b q k b n r".upper().split(" ") def newBoard(): b = "r n b q k b n r p p p p p p p p".split(" ") + ['.']*32 + "p p p p p p p p r n b q k b n r".upper().split(" ") def display(): #white side view c , k= 1 ...
14,774
5,754
#!/usr/bin/env python # -*- test-case-name: txosc.test.test_async -*- # Copyright (c) 2009 Alexandre Quessy, Arjan Scherpenisse # See LICENSE for details. """ Asynchronous OSC sender and receiver using Twisted """ import struct import socket from twisted.internet import defer, protocol from twisted.application.intern...
5,408
1,569
from selenium import webdriver from time import sleep # Sleep will pause the program import os # for getting the local path from json import loads dirpath = os.getcwd() # gets local path driver = webdriver.Chrome(dirpath + "/chromedriver") def login(username, password): global driver # LOGIN driver.fi...
2,740
856
''' client methods ''' import os if os.environ.has_key('PANDA_DEBUG'): print "DEBUG : importing %s" % __name__ import re import sys import time import stat import types try: import json except: import simplejson as json import random import urllib import struct import commands import cPickle as pickle i...
127,770
39,354
#!/usr/bin/env python import os.path import sys from pprint import pprint import nist_database def sort_dict(d, key=None, reverse=False): """ Returns an OrderedDict object whose keys are ordered according to their value. Args: d: Input dictionary key: functio...
6,952
2,384
""" This file retrieves Github usernames from PapersWithCode.com """ import argparse from pathlib import Path from datetime import datetime import pandas as pd from paperswithcode import PapersWithCodeClient if __name__ == '__main__': # Initiate the parser parser = argparse.ArgumentParser() # Add argum...
1,292
364
import gym import time import random import custom_envs import pprint class MCOBJ(object): def __init__(self, grid_mdp): self.env = grid_mdp # Just for pass the error. self.states = self.env.getStates() self.actions = self.env.getActions() def gen_random_pi_sample(self, num): ...
5,087
1,834
from . import models def post_load(): # use post_load to avoid overriding _get_search_domain when this module is not installed from . import controllers
163
43
#coding=utf-8 #-*- coding: utf-8 -*- import os import sys sys.path.append("../frame/") from loggingex import LOG_INFO from loggingex import LOG_ERROR from loggingex import LOG_WARNING from mysql_manager import mysql_manager class prepare_table(): def __init__(self, conn_name, table_template_name): self....
2,107
681
#!/usr/bin/env python3 print("""\ Usage: thingy [OPTIONS] -h Display this usage message -H hostname Hostname to connect to """)
175
49
# Reference: http://continuum.io/blog/the-python-and-the-complied-python #pythran export diffusePurePython(float [][], float [][], int) #runas import numpy as np;lx,ly=(2**7,2**7);u=np.zeros([lx,ly],dtype=np.double);u[int(lx/2),int(ly/2)]=1000.0;tempU=np.zeros([lx,ly],dtype=np.double);diffusePurePython(u,tempU,500) #be...
1,118
499
km = int(input()) print('{} minutos'.format(km*2))
50
20
import os import sys import pytest from random import randrange myPath = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, myPath + "/../") import src.utils.messages as msg from src.executor import executor, parser from src.git_manager.git_manager import GitManager @pytest.fixture(autouse=True) def prep...
815
262
#!/usr/bin/env python3 import sys def set_path(path: str): try: sys.path.index(path) except ValueError: sys.path.insert(0, path) # set programatically the path to 'sim-environment' directory (alternately can also set PYTHONPATH) set_path('/media/suresh/research/awesome-robotics/active-slam/cat...
1,150
415
# -*- coding: utf-8 -*- # Copyright © 2020 Damir Jelić <poljar@termina.org.uk> # # Permission to use, copy, modify, and/or 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 PR...
2,413
743
from django.contrib.auth import authenticate from django.shortcuts import render from rest_framework import serializers from rest_framework import status from rest_framework.views import APIView from rest_framework.authtoken.models import Token from rest_framework.response import Response from .models import Editor fr...
1,997
505
import argparse import os import json from torch.utils.tensorboard import SummaryWriter import random import numpy as np import zipfile import torch from transformers import AdamW, get_linear_schedule_with_warmup from LAUG.nlu.jointBERT_new.dataloader import Dataloader from LAUG.nlu.jointBERT_new.jointBERT im...
12,440
4,072
import json import time import requests import re from flask import Flask, render_template, jsonify from pyecharts.charts import Map, Timeline,Kline,Line,Bar,WordCloud from pyecharts import options as opts from pyecharts.globals import SymbolType app = Flask(__name__) #字典,受限于谷歌调用限制 cn_to_en = {'安哥拉': 'Angola', '阿富汗':...
19,361
9,071
# Generated by Django 2.2.4 on 2019-08-03 15:01 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('game', '0001_initial'), ] operations = [ migrations.CreateModel( name='Table', fields=[ ('id', model...
752
231
# coding=utf-8 import unittest from mock import patch from ddt import ddt, data from digestparser.objects import Digest import activity.activity_PostDigestJATS as activity_module from activity.activity_PostDigestJATS import activity_PostDigestJATS as activity_object import tests.activity.settings_mock as settings_mock...
10,913
3,211
import asyncio import itertools import logging import random import time from typing import List, Iterable, cast from torrent_client.algorithms.peer_manager import PeerManager from torrent_client.models import Peer, TorrentInfo from torrent_client.utils import humanize_size class Uploader: def __init__(self, tor...
3,718
1,146
from pygame import sprite, surface, Color from game.Bloques import CeldasTablero from game.Snake import Snake class AreaTablero(sprite.Sprite): def __init__(self, size, pos, bgcolor, estructura = None): sprite.Sprite.__init__(self) self.image = surface.Surface(size) self.image.fill(Color(bgcolor)) self.rect =...
1,898
788
# -*- coding: utf-8 -*- from odoo import models, fields, api from odoo.exceptions import ValidationError # Class for project management and their relationships class Projects(models.Model): # Name of table _name = "projects.project" # Simple fields of the object name = fields.Char(string="Project titl...
1,688
541
from app.shared.models import db from app.models.mixins import ModelMixin class Food(ModelMixin, db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(255), nullable=False) category_id = db.Column(db.Integer, db.ForeignKey("category.id"), nullable=False) restourant_id = db...
402
141
tree_count, tree_hinput, tree_chosen = int(input()), input().split(), 0 tree_height = [int(x) for x in tree_hinput] for each_tree in range(tree_count): if each_tree==0 and tree_height[0]>tree_height[1]:tree_chosen+=1 elif each_tree==tree_count-1 and tree_height[each_tree]>tree_height[each_tree-1]:tree_chose...
452
178
from . import datasets class DatasetManager: def __init__(self): self.available_datasets = { 'omniglot': datasets.OmniglotDataset(), 'lfw': datasets.LfwDataset(), 'clevr': datasets.ClevrDataset(), 'caltech_birds2011': datasets.CUBDataset(), ...
2,230
687
from setuptools import find_packages, setup from ticketus import __version__ as version setup( name='ticketus', version=version, license='BSD', author='Sam Kingston', author_email='sam@sjkwi.com.au', description='Ticketus is a simple, no-frills ticketing system for helpdesks.', url='https:...
1,574
479
from typing import Union, Tuple import pygame from pygame_gui._constants import UI_WINDOW_CLOSE, UI_WINDOW_MOVED_TO_FRONT, UI_BUTTON_PRESSED from pygame_gui._constants import OldType from pygame_gui.core import ObjectID from pygame_gui.core.interfaces import IContainerLikeInterface, IUIContainerInterface from pygame...
35,178
8,982
from rasa_nlu.interpreters.simple_interpreter import HelloGoodbyeInterpreter interpreter = HelloGoodbyeInterpreter() def test_samples(): samples = [ ("Hey there", {'text': "Hey there", 'intent': 'greet', 'entities': {}}), ("good bye for now", {'text': "good bye for now", 'intent': 'goodbye', 'ent...
714
183
# Create the DMatrix: housing_dmatrix housing_dmatrix = xgb.DMatrix(data=X, label=y) # Create the parameter dictionary: params params = {'objective':'reg:linear', 'max_depth':4} # Train the model: xg_reg xg_reg = xgb.train(dtrain=housing_dmatrix, params=params, num_boost_round=10) # Plot the feature importances xgb....
355
134
# -*- coding: utf-8 -*- """ Created on Sun Aug 12 13:22:02 2018 @author: Arnab Bhowmik """ import cv2 import numpy as np cap=cv2.VideoCapture(1) while True: _,frame=cap.read() hsv=cv2.cvtColor(frame,cv2.COLOR_BGR2HSV) #hsv hue sat value lower_red=np.array([0,0,0]) upper_red=np.array...
646
305
# -*- coding: utf-8 -*- # # Copyright (C) 2019 CERN. # # Invenio-Circulation is free software; you can redistribute it and/or modify # it under the terms of the MIT License; see LICENSE file for more details. """Tests for loan item resolver.""" from invenio_circulation.api import Loan def test_loan_item_resolver(ap...
811
301
#!/usr/bin/python # Copyright (c) 2011 The Native Client Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import os # # CoverageHelper # # The CoverageHelper is an object which defines lists used by the coverage # scripts for grouping ...
2,611
948
from pylayers.antprop.aarray import * import matplotlib.pyplot as plt import pdb print('--------------') print('antprop/test_subarray.py') print('--------------') fcGHz = 60 lamda = 0.3/fcGHz N1 = [ 4,4,1] N2 = [ 2,2,1] dm1 = [lamda/2.,lamda/2.,0] dm2 = [3*lamda,3*lamda,0] A1 = AntArray(fGHz=np.array([fcGHz]),N=N...
414
210
import json from requests import Request from pydantic import BaseModel from pydoc import locate from typing import List, Optional import dataclasses from dataclasses import dataclass from datetime import datetime SCHEMAS = {} class ResourceBaseSchema(BaseModel): id: Optional[str] private: Optional[bool] ...
5,789
1,514
"""This module handles the creation of an Explosion instance.""" from os import pardir, path import pygame as pg from pygame.sprite import Sprite import color # Path template for the nine explosion images. IMG = path.join(pardir, "resources/images/explosions/explosion0{}.jpg") class Explosion(Sprite): """A cl...
2,002
580
from infra.controllers.contracts import HttpResponse class NotFoundError(HttpResponse): def __init__(self, message) -> None: status_code = 404 self.message = message body = { 'message': self.message } super().__init__(body, status_code)
298
88
from uuid import uuid4 from flask_sqlalchemy import SQLAlchemy from workout_plan_server.adapters.mysql.generic_repository import GenericRepository from workout_plan_server.adapters.mysql.models.exercise_model import ExerciseModel from workout_plan_server.domain.entities.exercise import Exercise from workout_plan_serv...
696
214
from locust import HttpLocust,TaskSet,task #python crlocust.py -f mysite/test/testperform.py --no-web --run-time 5s --csv result -c 5 -r 1 from locust import events from gevent._semaphore import Semaphore import datetime '''写的钩子函数''' # from locust import Locust, TaskSet, events, task # mars_event = events.EventHook(...
2,149
826
class TypeCodes: LIST = 1
34
15
import pandas as pd import numpy as np import yaml import os import argparse from sklearn.impute import KNNImputer from logger import App_Logger file_object=open("application_logging/Loggings.txt", 'a+') logger_object=App_Logger() def read_params(config_path): with open(config_path) as yaml_file: ...
4,248
1,402
# -*- encoding:utf-8 -*- impar = lambda n : 2 * n - 1 header = """ Demostrar que es cierto: 1 + 3 + 5 + ... + (2*n)-1 = n ^ 2 Luego con este programa se busca probar dicha afirmacion. """ def suma_impares(n): suma = 0 for i in range(1, n+1): suma += impar(i) return suma def main(): print(header) num ...
680
305
from .Armor import Armor class Chest(Armor): LIFE_PER_LEVEL = 100 PROTECTION_PER_LEVEL = 5 DAMAGE_PART = 1.2 def __init__(self, owner, level:int=None, life:int=None, protection:int=None): self.name = "Chest armor" super().__init__(owner, owner.level if level is None else level, life, ...
341
127
"""This module contains helper functions used in the API""" import datetime import json import re import string import random from functools import wraps from flask import request from api_v1.models import User def name_validalidation(name, context): """Function used to validate various names""" if len(name...
2,436
690
# # Runtime.py # import types import threading #import copy from phidias.Types import * from phidias.Knowledge import * from phidias.Exceptions import * from phidias.Messaging import * DEFAULT_AGENT = "main" __all__ = [ 'DEFAULT_AGENT', 'Runtime', 'Plan' ] # ------------------------------------------------ class E...
25,099
7,339
from django.core.exceptions import ValidationError def positive_number(value): """Checking the value. Must be greater than 0.""" if value <= 0.0: raise ValidationError('Count must be greater than 0', params={'value': value},)
245
73
import sensor, image, time, pyb from pid import PID from pyb import Servo from pyb import UART uart = UART(3, 19200) usb = pyb.USB_VCP() led_red = pyb.LED(1) # Red LED = 1, Green LED = 2, Blue LED = 3, IR LEDs = 4. led_green = pyb.LED(2) pan_pid = PID(p=0.07, i=0, imax=90) #脱机运行或者禁用图像传输,使用这个PID tilt_pid = PID(p=0...
3,059
1,448
from datetime import datetime from datetime import timedelta from job import WEEKDAYS from job import Job def calculateNextExecution(job, now=datetime.now()): executionTime = now.replace() if job.executionType == "weekly": diff = WEEKDAYS.index(job.executionDay) - now.weekday() if diff < 0 an...
4,121
1,213