text
string
size
int64
token_count
int64
#The MIT License # #Copyright (c) 2020 DATA Lab at Texas A&M University #Copyright (c) 2016 OpenAI (https://openai.com) # #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, inclu...
4,714
1,562
import random import math from functools import partial import json import pysndfx import librosa import numpy as np import torch from ops.audio import ( read_audio, compute_stft, trim_audio, mix_audio_and_labels, shuffle_audio, cutout ) SAMPLE_RATE = 44100 class Augmentation: """A base class for data...
8,573
2,656
#!/usr/env/bin python import os # os.environ['OMP_NUM_THREADS'] = '1' from newpoisson import poisson import numpy as np from fenics import set_log_level, File, RectangleMesh, Point mesh = RectangleMesh(Point(0,0), Point(1,1), 36, 36) # comm = mesh.mpi_comm() set_log_level(40) # ERROR=40 # from mpi4py import MPI # com...
2,011
708
""" Irreduzibilitätskriterien Implementiert wurden das Eisenstein- und das Perronkriterium Quellen: https://rms.unibuc.ro/bulletin/pdf/53-3/perron.pdf http://math-www.uni-paderborn.de/~chris/Index33/V/par5.pdf Übergeben werden Polynome vom Typ Polynomial, keine direkten Listen von Koeff...
3,606
1,267
# # Copyright (c) 2017 Intel Corporation # SPDX-License-Identifier: BSD-2-Clause # import copy import numpy as np from llvmlite import ir as lir from numba.core import types, typing, utils, ir, config, ir_utils, registry from numba.core.typing.templates import (CallableTemplate, signature, ...
39,763
10,891
import numpy as np import pydrake.symbolic as ps import torch import time from irs_lqr.dynamical_system import DynamicalSystem class BicycleDynamics(DynamicalSystem): def __init__(self, h): super().__init__() """ x = [x pos, y pos, heading, speed, steering_angle] u = [acceleration,...
3,754
1,348
import streamlit as st import math from scipy.stats import * import pandas as pd import numpy as np from plotnine import * def app(): # title of the app st.subheader("Proportions") st.sidebar.subheader("Proportion Settings") prop_choice = st.sidebar.radio("",["One Proportion","Two Proportions"]) ...
6,504
2,371
import logging import unittest from config_test import build_client_from_configuration _logger = logging.getLogger(__name__) class TestServiceInstances(unittest.TestCase): def test_create_update_delete(self): client = build_client_from_configuration() result = client.v2.service_instances.create(...
1,263
380
"""Runway providers."""
24
9
#!/usr/bin/env python """ This sample application is a server that supports COV notification services. The console accepts commands that change the properties of an object that triggers the notifications. """ import time from threading import Thread from bacpypes.debugging import bacpypes_debugging, ModuleLogger fro...
13,265
3,947
import os import platform import subprocess from django.http import HttpResponse from django.conf import settings def add(request, friend): phantomjs = os.path.join(settings.PROJECT_PATH, 'glassface', 'facebookfriender', platform.system(), 'phantomjs') script = os.path.join(settings.PROJECT_PATH, 'glassface'...
973
288
import random import numpy as np import pandas as pd import streamlit as st from sklearn.naive_bayes import GaussianNB from sklearn.model_selection import train_test_split from yellowbrick.classifier import classification_report from yellowbrick.target import FeatureCorrelation from yellowbrick.target import ClassBalan...
5,187
1,442
from flask import request import random import re from flask import current_app, jsonify from flask import g from flask import make_response from flask import redirect from flask import render_template from flask import request from flask import session from flask import url_for import time from info import constants, ...
14,566
5,213
#Answer Generation import csv import os import numpy as np from keras.models import * from keras.models import Model from keras.preprocessing import text def load_model(): print('\nLoading model...') # load json and create model json_file = open('models/MODEL.json', 'r') loaded_model_json = json_file...
2,839
938
# -*- coding: UTF-8 -*- from socket import * def client(): #實驗室電腦 # serverip='120.126.151.182' # serverport=8887 #在自己電腦測試 serverip='127.0.0.1' serverport=8888 client=socket(AF_INET,SOCK_STREAM) client.connect((serverip,serverport)) address_file = open('tools/address.txt', 'r')...
716
338
"""Non-linear SPDE model on a periodic 1D spatial domain for laminar wave fronts. Based on the Kuramato--Sivashinsky PDE model [1, 2] which exhibits spatio-temporally chaotic dynamics. References: 1. Kuramoto and Tsuzuki. Persistent propagation of concentration waves in dissipative media far from thermal ...
13,039
3,877
"""Utiltiy functions for working with Myo Armband data.""" from setuptools import setup, find_packages setup(name='myo_helper', version='0.1', description='Utiltiy functions for working with Myo Armband data', author='Lif3line', author_email='adamhartwell2@gmail.com', license='MIT', ...
553
171
# -*-encoding:utf-8-*- import os from karlooper.web.application import Application from karlooper.web.request import Request class UsersHandler(Request): def get(self): return self.render("/user-page.html") class UserInfoHandler(Request): def post(self): print(self.get_http_request_message(...
1,030
337
import random import math class LoopPadding(object): def __init__(self, size): self.size = size def __call__(self, frame_indices): out = frame_indices for index in out: if len(out) >= self.size: break out.append(index) return out cl...
4,154
1,285
from waiter.action import process_kill_request from waiter.util import guard_no_cluster, check_positive def kill(clusters, args, _, __): """Kills the service(s) using the given token name.""" guard_no_cluster(clusters) token_name_or_service_id = args.get('token-or-service-id') is_service_id = args.get...
1,206
373
"""The main module of the Analytics API Load Tests tool. Copyright (c) 2019 Red Hat Inc. 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 late...
3,338
992
# See LICENSE.incore file for details import os,re import multiprocessing as mp import time import shutil from riscv_ctg.log import logger import riscv_ctg.utils as utils import riscv_ctg.constants as const from riscv_isac.cgf_normalize import expand_cgf from riscv_ctg.generator import Generator from math import * fr...
3,568
1,223
from collections import namedtuple MainTimer = namedtuple('MainTimer', 'new_time_joined, end_period, new_weekday, days') def add_time(start, duration, start_weekday=None): weekdays = [ 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday' ] start_time, period ...
2,146
747
from .analyze_logs import AnalyzeLogs from .search_interface import SearchInterface from .detail_interface import DetailInterface from .user_interface import UserInterface from .visualize_log_detail import VisualizeLogDetail
225
56
import matplotlib.pyplot as plt import numpy as np import sys sys.path.append('../../../software/models/') import dftModel as DFT import math k0 = 8.5 N = 64 w = np.ones(N) x = np.cos(2*np.pi*k0/N*np.arange(-N/2,N/2)) mX, pX = DFT.dftAnal(x, w, N) y = DFT.dftSynth(mX, pX, N) plt.figure(1, figsize=(9.5, 5)) plt.subpl...
816
432
# setup.py as described in: # https://stackoverflow.com/questions/27494758/how-do-i-make-a-python-script-executable # to install on your system, run: # > pip install -e . from setuptools import setup, find_packages setup( name='typobs', version='0.0.3', entry_points={ 'console_scripts': [ ...
1,421
446
""" decoded AUTH_HEADER (newlines added for readability): { "identity": { "account_number": "1234", "internal": { "org_id": "5678" }, "type": "User", "user": { "email": "test@example.com", "first_name": "Firstname", "is_active":...
5,775
3,248
#####Time Flow Simulation###### import numpy as np import pandas as pd import matplotlib.pyplot as plt from datetime import timedelta import datetime import csv data=pd.read_excel('CF66-all.xlsx') data.sort_values(by=['WBL_AUD_DT'],ascending=True,inplace=True) or_data=pd.read_excel('CF66-ordinary.xlsx') rul...
3,200
1,783
import pytest import numpy as np from fanok.selection import adaptive_significance_threshold @pytest.mark.parametrize( "w, q, offset, expected", [ ([1, 2, 3, 4, 5], 0.1, 0, 1), ([-1, 2, -3, 4, 5], 0.1, 0, 4), ([-3, -2, -1, 0, 1, 2, 3], 0.1, 0, np.inf), ([-3, -2, -1, 0, 1, 2, ...
776
415
#!/usr/bin/python # Copyright 2019 Christopher Schmidt # # 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...
7,256
2,738
from .main import Matrix
25
7
import os import sys import json import datetime import numpy as np import glob import skimage from PIL import Image as pil_image import cv2 import cv2 def locationToMask(locations=None,height=None,width=None): mask = np.zeros([height, width, len(locations)], dtype=np.uint8) for ...
2,348
841
#!/usr/bin/env python3 # -*- coding: utf-8 -*- #Author:Winston.Wang import requests from bs4 import BeautifulSoup print(dir(BeautifulSoup)) url = 'http://www.baidu.com'; with requests.get(url) as r: r.encoding='utf-8' soup = BeautifulSoup(r.text) #格式化 pret = soup.prettify(); u = soup.select('#u1 a') for i in u: ...
371
166
from django.urls import path, include from . import views urlpatterns = [ path("", views.newsView, name="home"), path("createBlog", views.CreateBlogView.as_view(), name="createBlog"), path("myBlogs", views.PostListView.as_view(), name="myBlogs"), path("single/<int:pk>", views.PostDetailView.as_view(), ...
869
289
#!/usr/bin/python _author_ = "Matthew Zheng" _purpose_ = "Sets up the unit class" class Unit: '''This is a class of lists''' def __init__(self): self.baseUnits = ["m", "kg", "A", "s", "K", "mol", "cd", "sr", "rad"] self.derivedUnits = ["Hz", "N", "Pa", "J", "W", "C", "V", "F", "ohm", "S", "Wb",...
3,133
879
# -*- coding: utf-8 -*- """ Created on Wed Feb 26 22:23:07 2020 @author: Neal LONG Try to construct URL with string.format """ base_url = "http://quotes.money.163.com/service/gszl_{:>06}.html?type={}" stock = "000002" api_type = 'cp' print("http://quotes.money.163.com/service/gszl_"+stock+".html?type="...
918
396
from conans.server.launcher import ServerLauncher from conans.util.env_reader import get_env launcher = ServerLauncher(server_dir=get_env("CONAN_SERVER_HOME")) app = launcher.server.root_app def main(*args): launcher.launch() if __name__ == "__main__": main()
274
96
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may ...
153,586
43,990
# # This module builds upon Cycles nodes work licensed as # Copyright 2011-2013 Blender Foundation # # 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...
69,123
25,428
import configparser import numpy as np import os class Config: def _select_val(self, section: str, key: str = None): if section in self._custom and key in self._custom[section]: return self._custom[section][key] elif section in self._config: return self._config[se...
9,981
3,378
# Copyright 2019 Jian Wu # License: Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0) import math import numpy as np import torch as th import torch.nn as nn import torch.nn.functional as tf import librosa.filters as filters from aps.const import EPSILON from typing import Optional, Union, Tuple def init_win...
19,446
6,372
# Copyright 2019 Graphcore Ltd. from models.resnet_base import ResNet import tensorflow.compat.v1 as tf import tensorflow.contrib as contrib from tensorflow.python.ipu import normalization_ops # This is all written for: NHWC class TensorflowResNet(ResNet): def __init__(self, *args, **kwargs): self.dtype...
3,427
1,126
# Generated by Django 3.1.4 on 2020-12-05 18:46 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('app', '0020_auto_20201204_2324'), ] operations = [ migrations.AlterField( model_name='profile', name='profileBankAcc...
613
207
#!/usr/bin/env python3 import time import os import tempfile import shutil import logging from enum import Enum from argparse import ArgumentParser, Namespace, FileType from netCDF4 import Dataset, MFDataset import geopandas as gpd import numpy as np domain_nodes_shp = "gis/ssm domain nodes.shp" masked_nodes_txt = "g...
8,942
2,989
from logging import getLogger from libcity.executor.abstract_tradition_executor import AbstractTraditionExecutor from libcity.utils import get_evaluator class MapMatchingExecutor(AbstractTraditionExecutor): def __init__(self, config, model): self.model = model self.config = config self.ev...
1,075
344
# Generated by Django 2.2.5 on 2020-04-08 00:08 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('budget', '0004_auto_20200407_2356'), ] operations = [ migrations.DeleteModel( name='HiddenStatus_Budget', ), ]
307
121
# 대신증권 API # 데이터 요청 방법 2가지 BlockRequest 와 Request 방식 비교 예제 # 플러스 API 에서 데이터를 요청하는 방법은 크게 2가지가 있습니다 # # BlockRequest 방식 - 가장 간단하게 데이터 요청해서 수신 가능 # Request 호출 후 Received 이벤트로 수신 받기 # # 아래는 위 2가지를 비교할 수 있도록 만든 예제 코드입니다 # 일반적인 데이터 요청에는 BlockRequest 방식이 가장 간단합니다 # 다만, BlockRequest 함수 내에서도 동일 하게 메시지펌핑을 하고 있어 해당 ...
3,548
1,704
#%% import numpy as np import copy import matplotlib.pyplot as plt import time def split_cluster_new(tree,local_density,dc_eps,closest_denser_nodes_id,mixin_near_matrix): ''' dc_eps: density_connectivity 阈值 使用父子节点的直接距离,与子节点与兄弟节点的连通距离进行聚簇划分; 使用平均密度划分outlier 返回: outlier_f...
18,439
6,765
from __future__ import print_function import sys sys.path.append('.') import os from typing import Optional, Union import cv2 import numpy as np import PIL.Image as Image import pickle import torch from torch.utils import data __all__ = ["TAO"] class TAO(data.Dataset): r"""A torch Dataset for loading in `the TA...
10,280
2,990
from typing import TYPE_CHECKING if TYPE_CHECKING: from Platforms.Web.main_web import PhaazebotWeb import json from aiohttp.web import Response from Utils.Classes.extendedrequest import ExtendedRequest async def apiDiscordConfigsQuoteDisabledChannelExists(cls:"PhaazebotWeb", WebRequest:ExtendedRequest, **kwargs) -> ...
2,572
896
import torch import torch.nn as nn class EstimatorCV(): def __init__(self, feature_num, class_num): super(EstimatorCV, self).__init__() self.class_num = class_num self.CoVariance = torch.zeros(class_num, feature_num, feature_num)#.cuda() self.Ave = torch.zeros(class_num, feature_nu...
3,853
1,514
""" Module for plotting analyses """ import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np from copy import deepcopy import pickle, json import os from matplotlib.offsetbox import AnchoredOffsetbox try: basestring except NameError: basestring = str colorList = [[0.42, 0.67, 0.84], [0....
22,828
7,294
from mo_parsing.helpers import QuotedString wikiInput = """ Here is a simple Wiki input: *This is in italics.* **This is in bold!** ***This is in bold italics!*** Here's a URL to {{Pyparsing's Wiki Page->https://site-closed.wikispaces.com}} """ def convertToHTML(opening, closing): def convers...
1,069
395
import pytest import re from typing import Any, Tuple from dataclasses import dataclass from app_settings_dict import Settings def test_simple_settings() -> None: settings = Settings( settings_file_path="C:/Users/chris/Documents/sample_settings_file_name.json", default_factories={ "key...
9,885
3,095
import os import time import cv2 import sys sys.path.append('..') import numpy as np from math import cos, sin from lib.FSANET_model import * import numpy as np from keras.layers import Average def draw_axis(img, yaw, pitch, roll, tdx=None, tdy=None, size = 50): print(yaw,roll,pitch) pitch = pitch * np.pi /...
5,910
2,475
import discord from discord.commands import option bot = discord.Bot(debug_guilds=[...]) COLORS = ["red", "orange", "yellow", "green", "blue", "indigo", "violet"] LOTS_OF_COLORS = [ "aliceblue", "antiquewhite", "aqua", "aquamarine", "azure", "beige", "bisque", "blueviolet", "brown...
5,118
1,673
from _thread import start_new_thread from bitcoin.messages import * from bitcoin.net import CAddress from bitcoin.core import CBlock from io import BytesIO as _BytesIO import atexit import bitcoin import fcntl import hashlib import json import os import random import re import socket import struct import sys import tim...
11,522
4,408
#!python3 ''' 数据库操作类 author: justZero email: alonezero@foxmail.com date: 2017-8-6 ''' import time import pandas as pd import numpy as np import pymysql import pymysql.cursors import pprint class MySQLdb(object): def __init__(self): self.conn = pymysql.connect( host='localho...
1,638
560
import ezff from ezff.interfaces import gulp, qchem # Define ground truths gt_gs = qchem.read_structure('ground_truths/optCHOSx.out') gt_gs_energy = qchem.read_energy('ground_truths/optCHOSx.out') gt_scan = qchem.read_structure('ground_truths/scanCHOSx.out') gt_scan_energy = qchem.read_energy('ground_truths/scanCHOSx....
2,077
743
import logging from testing_func import testing_func, test_logger from unit_parse import logger, Unit, Q from unit_parse.utils import * test_logger.setLevel(logging.DEBUG) logger.setLevel(logging.DEBUG) test_split_list = [ # positive control (changes) [["fish","pig", "cow"], ["f", "is", "h", "pig", "cow"], ...
2,288
1,067
import sys from Crypto.Signature import pkcs1_15 from Crypto.Hash import SHA256 from Crypto.PublicKey import RSA def sign_data(key, data, output_file): with open(key, 'r', encoding='utf-8') as keyFile: rsakey = RSA.importKey(keyFile.read()) signer = pkcs1_15.new(rsakey) digest = SHA256.new...
594
231
from typing import Any, Callable, NamedTuple, Optional, Union from pandas import DataFrame from freqtrade.exceptions import OperationalException from freqtrade.strategy.strategy_helper import merge_informative_pair PopulateIndicators = Callable[[Any, DataFrame, dict], DataFrame] class InformativeData(NamedTuple):...
5,302
1,481
from functools import partial from selenium.webdriver import Firefox from selenium.webdriver.support.ui import ( WebDriverWait ) def esperar_elemento(elemento, webdriver): print(f'Tentando encontrar "{elemento}"') if webdriver.find_elements_by_css_selector(elemento): return True return False ...
835
297
import torch from torch import nn from prae.distances import square_dist, HingedSquaredEuclidean class Loss(nn.Module): """ """ def __init__(self, hinge, neg=True, rew=True): """ """ super().__init__() self.reward_loss = square_dist # If False, no negative sampling ...
1,470
513
""" Handles most general questions (including math!) Requires: - WolframAlpha API key Usage Examples: - "How tall is Mount Everest?" - "What is the derivative of y = 2x?" """ import wolframalpha from orion.classes.module import Module from orion.classes.task import ActiveTask from orion i...
845
285
from polymatch import PolymorphicMatcher class ExactMatcher(PolymorphicMatcher): def compile_pattern(self, raw_pattern): return raw_pattern def compile_pattern_cs(self, raw_pattern): return raw_pattern def compile_pattern_ci(self, raw_pattern): return raw_pattern.lower() def...
1,035
311
""" Django settings for project. """ # Build paths inside the project like this: os.path.join(BASE_DIR, ...) import os # Debug #DEBUG = False DEBUG = True TEMPLATE_DEBUG = DEBUG INFORMIX_DEBUG = "debug" ADMINS = ( ('', ''), ) MANAGERS = ADMINS SECRET_KEY = '' ALLOWED_HOSTS = [] LANGUAGE_CODE = 'en-us' TIME_ZONE...
6,530
2,415
__author__ = 'Aaron Yang' __email__ = 'byang971@usc.edu' __date__ = '12/9/2020 4:18 PM' from abc import abstractmethod class Product(object): @abstractmethod def setMsg(self, msg="default info"): self.msg = msg @abstractmethod def info(self): print(self.msg) class DefaultObj(Produ...
956
331
import uuid from typing import AsyncGenerator import pytest from sqlalchemy import exc from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine from sqlalchemy.orm import sessionmaker from sqlmodel import Session, SQLModel, create_engine from fastapi_users_db_sqlmodel import ( NotSetOAuthAccountTableE...
7,064
2,373
#! /usr/bin/env python3 import os from os import path root_dir = path.dirname(path.realpath(__file__)) local_reg_dir = path.join(root_dir, 'registry') os.makedirs(local_reg_dir, exist_ok=True) def copy_reg(reg_dir, files): import shutil for f in files: file_path = path.join(reg_dir, f) if not...
623
235
import numpy as np import pandas as pd import scipy.stats as st #from medical_ML import Experiment import matplotlib.pyplot as plt import xgboost as xgb from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier from sklearn.dummy import DummyClassifier from sklearn.tree import DecisionTreeClassif...
22,653
7,609
import json import logging import re import susepubliccloudinfoclient.infoserverrequests as ifsrequest import yaml import sys RELEASE_DATE = re.compile('^.*-v(\d{8})-*.*') def get_caasp_release_version(): """Return the version from os-release""" os_release = open('/etc/os-release', 'r').readlines() for e...
4,377
1,200
# Copyright (C) 2015-2016 The bitcoin-blockchain-parser developers # # This file is part of bitcoin-blockchain-parser. # # It is subject to the license terms in the LICENSE file found in the top-level # directory of this distribution. # # No part of bitcoin-blockchain-parser, including this file, may be copied, # modif...
2,219
829
''' DNA++ (c) DNA++ 2017 All rights reserved. @author: neilswainston '''
75
35
import os import pandas as pd import pytest from user_similarity_model.config.core import DATASET_DIR, config @pytest.fixture() def sample_local_data(): """AI is creating summary for sample_local_data Returns: [Dict]: This function returns a dictionary with CSV files which in dataset folder...
600
176
from django.apps import AppConfig import logging logger = logging.getLogger(__name__) class WeatherConfig(AppConfig): name = 'weather' def ready(self): from forecastUpdater import updater updater.start()
232
69
import filer import tests
26
8
""" ============ Pass Network ============ This example shows how to plot passes between players in a set formation. """ import pandas as pd from mplsoccer.pitch import Pitch from matplotlib.colors import to_rgba import numpy as np from mplsoccer.statsbomb import read_event, EVENT_SLUG ##############################...
8,063
2,482
__all__ = ['Factory'] import jsfiddle_build import jsfiddle_github import jsfiddle_generator import jsfiddle_readme_generator import getdirs import getfiles import os import popd import yaml @popd.popd def _build(path): os.chdir(path) jsfiddle_build.Build().save("build.html") @popd.popd def _init(path): ...
2,786
897
import logging import os from datetime import datetime from inspect import signature, Parameter from pathlib import Path from pprint import pprint from textwrap import dedent from typing import Optional, Union import fire import tensorflow as tf from tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint, Te...
5,774
1,796
# Copyright 2020 The Flax Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
3,711
1,285
# -*- coding: utf-8 -*- from django.utils import translation from django.db.models import ObjectDoesNotExist from pybb import util from pybb.signals import user_saved class PybbMiddleware(object): def process_request(self, request): if request.user.is_authenticated(): try: # ...
1,273
306
from enum import Enum class CustomEnum(Enum): @classmethod def has_value(cls, value): return any(value == item.value for item in cls) @classmethod def from_value(cls, value): found_element = None if cls.has_value(value): found_element = cls(value) retu...
691
286
import fileinput counts = {} for line in fileinput.input(): line = line.strip() p1, p2 = line.split('>') p1 = p1[:-2] x1, y1 = p1.split(',') x1 = int(x1) y1 = int(y1) p2 = p2[1:] x2, y2 = p2.split(',') x2 = int(x2) y2 = int(y2) if x1 == x2: dx = 0 elif x1 > x2:...
716
322
import logging from web3 import Web3 import sys import time import meditation.meditation as meditation if __name__ == "__main__": log_format = '%(asctime)s|%(name)s|%(levelname)s: %(message)s' logger = logging.getLogger("DFK-meditation") logger.setLevel(logging.DEBUG) logging.basicConfig(level=loggin...
1,635
564
import time class Interval(object): def __init__(self, delay_time: int): self.delay_time = delay_time self.current_time = 0 @staticmethod def now(): return time.gmtime().tm_sec def should_run(self) -> bool: if self.current_time == 0: self.current_time = In...
669
203
''' Copyright (c) The Dojo Foundation 2011. All Rights Reserved. Copyright (c) IBM Corporation 2008, 2011. All Rights Reserved. ''' # tornado import tornado.ioloop # std lib import logging import time import weakref import functools # coweb from .base import BotWrapperBase log = logging.getLogger('coweb.bot') class O...
2,329
673
import pygame import random pygame.init() clock = pygame.time.Clock() fps = 60 #game window bottom_panel = 150 screen_width = 800 screen_height = 400 + bottom_panel screen = pygame.display.set_mode((screen_width, screen_height)) pygame.display.set_caption('Battle') #define game variables current_fighter = 1 total...
6,193
2,609
matriz = [[0, 0, 0], [0, 0, 0], [0, 0, 0]] soma = col3 = maior = 0 for l in range(0, 3): for c in range(0, 3): matriz[l][c] = int(input(f'[{l}][{c}]: ')) for l in range(0, 3): for c in range(0, 3): print(f'[{matriz[l][c]:^5}]', end='') if matriz[l][c] % 2 == 0: soma += matriz...
651
305
import onvif import os import asyncio import urllib.parse from onvif import ONVIFCamera from pytapo import Tapo from .const import ENABLE_MOTION_SENSOR, DOMAIN, LOGGER, CLOUD_PASSWORD from homeassistant.const import CONF_IP_ADDRESS, CONF_USERNAME, CONF_PASSWORD from homeassistant.components.onvif.event import EventMana...
6,777
2,112
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # ---------------------------------------------------------------------------- # Name: test_uidattr # Purpose: Test driver for module 'uidattr' # # Author: Michael Amrhein (michael@adrhinum.de) # # Copyright: (c) 2018 Michael Amrhein # -------------------...
1,652
530
import requests import time from bs4 import BeautifulSoup def get_web_page(url): resp = requests.get( url=url, ) if resp.status_code != 200: print('Invalid url:', resp.url) return None else: return resp.text def get_articles(dom): soup = BeautifulSoup(dom, 'html.p...
883
297
import uuid from abc import ABC, abstractmethod from collections import defaultdict from typing import Union from boto3.dynamodb.conditions import Attr as BotoAttr from boto3.dynamodb.conditions import Key as BotoKey from awstin.dynamodb.utils import from_decimal, to_decimal class NotSet: """ A value of an ...
21,493
5,733
from .supervise import * def get_losses(name, **kwargs): name = name.lower() if name == 'rhloss': loss = RHLoss(**kwargs) elif name == 'xtloss': loss = XTLoss(**kwargs) else: raise NotImplementedError('Loss [{:s}] is not supported.'.format(name)) return loss
310
106
import torch import torch.nn as nn from torch.nn.parameter import Parameter from torch.nn.utils.rnn import pad_packed_sequence as unpack from torch.nn.utils.rnn import pack_padded_sequence as pack from .my_optim import weight_norm as WN # TODO: use system func to bind ~ RNN_MAP = {'lstm': nn.LSTM, 'gru': nn.GR...
6,766
2,457
#!//anaconda/envs/py36/bin/python # # File name: kmc_pld.py # Date: 2018/08/03 09:07 # Author: Lukas Vlcek # # Description: # import numpy as np from collections import Counter class EventTree: """ Class maintaining a binary tree for random event type lookup and arrays for choosing specific...
2,810
932
# -*- coding: utf-8 -*- # Copyright (C) 2006-2007 Søren Roug, European Environment Agency # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at you...
2,181
742
import os os.environ['CUDA_VISIBLE_DEVICES'] = '2' import torch torch.rand(10) import torch.nn as nn import torch.nn.functional as F import glob from tqdm import tqdm, trange print(torch.cuda.is_available()) print(torch.cuda.get_device_name()) print(torch.cuda.current_device()) device = torch.device('cuda' if torch.cu...
7,293
2,927
"""Mock responses for recommendations.""" SEARCH_REQ = { "criteria": { "policy_type": ['reputation_override'], "status": ['NEW', 'REJECTED', 'ACCEPTED'], "hashes": ['111', '222'] }, "rows": 50, "sort": [ { "field": "impact_score", "order": "DESC" ...
5,712
2,452
# Copyright 2015 Carnegie Mellon University # # Author: Han Chen <hanc@andrew.cmu.edu> # # 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 # # ...
7,351
2,064