content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
import bs4
print("BlockDMask")
print(3 + 4)
| python |
from collections import Counter,defaultdict
import numpy as np
import os
import pandas as pd
import time
start_time=time.time()
def time_passed():
return time.time() - start_time
scores={}
num_row_ids=8607230
def update_tally(preds,preds_per_row_id,weight):
for i in range(len(preds)):
if preds[i] i... | python |
from django.conf.urls import patterns, url
urlpatterns = patterns(
'',
url(r'^(?P<slug>[-\w]+)/$', 'blog.views.show_post', name='post'),
)
| python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# time: 2020-8-9 23:11:00
# version: 1.0
# __author__: zhilong
import pymysql
def main():
conn = pymysql.connect(host='localhost', user='root', password='rootpwd', db='novelsite')
cursor = conn.cursor()
sql = 'create table novel(novelid int primary key auto_incr... | python |
import simuvex
from simuvex.s_type import SimTypeFd, SimTypeInt
from claripy import BVV
######################################
# getc
######################################
class _IO_getc(simuvex.SimProcedure):
# pylint:disable=arguments-differ
def run(self, f_p):
#additional code
trace_dat... | python |
import matplotlib.pyplot as plt
import numpy as np
plt.style.use('_mpl-gallery')
def get_data(filename):
with open(filename) as f:
lines = f.readlines()
data=[[],[]]
for line in lines:
curr_line=line[0:-2]
x,y=curr_line.split(" ");
x=float(x)
y=float(y)
data[0].append(x)
data[1].append(y)
... | python |
"""Multi-consumer multi-producer dispatching mechanism
Originally based on pydispatch (BSD) http://pypi.python.org/pypi/PyDispatcher/2.0.1
See license.txt for original license.
Heavily modified for Django's purposes.
"""
from .dispatcher import Signal, receiver # NOQA
from .tasks import register_tasks, set_task_name... | python |
import requests
import pathlib
import shutil
from typing import Dict, Tuple, List, Optional
import xml.etree.ElementTree as ET
HERE = pathlib.Path(__file__).absolute().parent
GL_XML_URL = 'https://raw.githubusercontent.com/KhronosGroup/OpenGL-Registry/master/xml/gl.xml' # noqa: E501
class Command:
def ... | python |
"""Refactor candidates table
Revision ID: fbf89710dead
Revises: d67d42b06b11
Create Date: 2020-11-12 16:34:25.642126
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'fbf89710dead'
down_revision = '73ca57416d1c'
branch_labels = None
depends_on = None
def upgra... | python |
from django.template import RequestContext, loader
from django.conf import settings
from django.core.exceptions import PermissionDenied
from django.http import HttpResponseForbidden
class Http403(Exception):
pass
def render_to_403(*args, **kwargs):
"""
Returns a HttpResponseForbidden whose content i... | python |
# Copyright (C) 2019 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
"""Mixins for entities."""
# pylint: disable=too-few-public-methods
class Reviewable(object):
"""A mixin for reviewable objects."""
def update_review(self, new_review):
"""Update obj review dict an... | python |
from time import sleep
x = 10
while x >= 0:
print(x)
sleep(0.5)
x -= 1
print('Fogo!!')
| python |
from django.conf.urls import url
from . import views
urlpatterns = [
url(r"^login/(?P<service>\w+)/$", views.oauth_login, name="oauth_access_login"),
url(r"^callback/(?P<service>\w+)/$", views.oauth_callback, name="oauth_access_callback"),
url(r"^finish_signup/(?P<service>\w+)/$", views.finish_signup, na... | python |
import typing
import bs4
__author__ = "Jérémie Lumbroso <lumbroso@cs.princeton.edu>"
__all__ = [
"split_name",
"extract_text",
]
CS_SCRAPING_LABEL_CLASS = "person-label"
def split_name(name: str) -> typing.Tuple[str, str]:
"""
Returns a likely `(first, last)` split given a full name. This uses
... | python |
from django.contrib import admin
from reviews import models
class CompanyAdmin(admin.ModelAdmin):
form = models.CompanyForm
list_display = ('name',)
exclude = ()
class CityAdmin(admin.ModelAdmin):
form = models.CityForm
list_display = ('name',)
exclude = ()
class PersonAdmin(admin.ModelAdm... | python |
# coding: utf-8
"""
qTest Manager API Version 8.6 - 9.1
qTest Manager API Version 8.6 - 9.1
OpenAPI spec version: 8.6 - 9.1
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from pprint import pformat
from six import iteritems
import re
class CommentQuery... | python |
#!/usr/bin/env python
import rospy
import sys
import time
import math
import tf
import tf2_ros
import serial
import csv
from rugby_lib.imu_gy85 import GY85
from geometry_msgs.msg import Twist, TransformStamped
from rugby.msg import *
from nav_msgs.msg import Odometry
from std_msgs.msg import String
from std_msgs.msg ... | python |
#########################################################################
# Walks through a file system tree and execute a command on files #
# Jean-Louis Dessalles 2012 #
#########################################################################
"""
Walks through ... | python |
#!/usr/bin/env python3
import sys
import re
txt = sys.stdin.read()
def logger(msg):
sys.stderr.write("{}\n".format(msg))
txt = txt.replace("’", "'")
lines = txt.split("\n")
lines = [line.strip() for line in lines]
lines = [line for line in lines if len(line)]
row = None
num = 0
tmpl = "MarketVendor.where(mark... | python |
#!/usr/bin/env python
############################################################################
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The A... | python |
import json
import requests
import secrets
sld = "pleasenoban2011"
tlds = []
with open('tlds.txt') as _tlds:
_tlds = _tlds.readlines()
for _tld in _tlds:
_tld = _tld.strip("\n")
tlds.append(f"{sld}.{_tld}")
# split list in half
_len_half = len(tlds) // 2
tlds_first_set = tlds[:len(tlds) // ... | python |
# coding=utf-8
import re
from sqlalchemy.orm.exc import NoResultFound
from ultros_site.base_sink import BaseSink
from ultros_site.database.schema.news_post import NewsPost
from ultros_site.decorators import render_api
__author__ = "Gareth Coles"
class APINewsRoute(BaseSink):
route = re.compile(r"/api/v1/news/(... | python |
class api_response:
def __init__(self, status, info, data):
self.status = status
self.info = info
self.data = data
def get_api_response(self):
return {
"status": self.status,
"info": self.info,
"data": s... | python |
# -*- coding: utf-8 -*-
def get_file_content(filename):
"""
读取文件, 返回一个生成器对象
:param filename:
:return:
"""
with open(filename, encoding='utf-8') as f:
while True:
line = f.read(512)
if line:
yield line
else: # 如果line为None, 那么说明已经读取到文... | python |
from django.urls import path
from .views import ProfileUpdateView, ProfileDetailView
urlpatterns = [
path('<slug:slug>/', ProfileDetailView.as_view(), name='profile-detail'),
path('<slug:slug>/edit/', ProfileUpdateView.as_view(), name='profile-settings'),
] | python |
#!/usr/bin/env python
#-*- coding: utf-8 -*-
# Python 3.7
#
# @Author: Jxtopher
# @License: CC-BY-NC-SA
# @Date: 2019-04
# @Version: 1
# @Purpose:
# see https://packages.debian.org/jessie/wordlist
# see /usr/share/dict/
#
import numpy as np
from itertools import cycle
import matplotlib
matplotlib... | python |
from odoo.tests.common import TransactionCase
class TestComputeDomain(TransactionCase):
at_install = True
post_install = True
def setUp(self):
super(TestComputeDomain, self).setUp()
self.demo_user = self.env.ref("base.user_demo")
self.env["ir.rule"].create(
{
... | python |
#%%
import os, glob
import numpy as np
import tensorflow as tf
# from myDataset import *
# from myconfig import cfg
# from yoloNet import *
# model = yoloNetModle()
# tf.keras.utils.plot_model(model, show_shapes=True, show_layer_names=True)
# weight_reader = WeightReader('yolo.weights')
# print(weight_reader.all_we... | python |
class Cliente:
def __init__(self, nome, email, plano):
self.nome = nome
self.email = email
self.lista_planos = ["basic", "premium"]#se fosse uma variavel somente pra essa funcao, nao precisaria do self.
if plano in self.lista_planos:
self.plano = plano
else:
... | python |
import sys
f=open(sys.argv[1],'r')
patch_no=sys.argv[2]
#g=open('/Volumes/Unnamed/patched_function_old/'+patch_no,'r')
#method=g.readline().strip()
from unidiff import PatchSet
import os
def get_patched_class(patch_no):
patchfile=os.path.join('../../patches',patch_no)
patch = PatchSet.from_filename(patchfile,en... | python |
# -*- coding: utf-8 -*-
"""Concrete VeiL api objects."""
from .cluster import VeilCluster
from .controller import VeilController
from .data_pool import VeilDataPool
from .domain import (DomainBackupConfiguration, DomainConfiguration, DomainTcpUsb,
DomainUpdateConfiguration, VeilDomain, VeilGuestAge... | python |
from unittest import mock
from py.test.tools import (
BaseTestCase,
)
from py.src.match.model.data import (
GlobalRankedData,
)
from py.src.view_model import (
GlobalViewModelCache,
)
class GlobalIntegrationTest(BaseTestCase):
@classmethod
def setUpChildClass(cls):
cls.matches = cls.sam... | python |
"""
Miscellanea utilities
"""
from __future__ import ( division, absolute_import, print_function, unicode_literals )
import sys, os, tempfile, logging
if sys.version_info >= (3,):
import urllib.request as urllib2
import urllib.parse as urlparse
else:
import urllib2
import urlparse
# Courtesy of http... | python |
'''
Author= 'Parampreet Singh'
Project= 'https://github.com/paramsingh96/TensorFlow-Tutorials'
Simple tutorial for understanding MNIST Data Sets
'''
# Importing different libraries
import tensorflow as tf
import matplotlib.pyplot as plt
import numpy as np
import tensorflow.examples.tutorials.mnist.inp... | python |
import concurrent.futures
import datetime
import itertools
import json
import logging
import os
from typing import Dict, Iterable, List
import kafka
from finitestate.common.retry_utils import retry
from finitestate.common.timer import CodeTimer
from finitestate.firmware.datasets import Dataset, Density, Format, Granu... | python |
#!/usr/bin/env python
import sys, os
import errno
import arsdkparser
from common import *
#===============================================================================
# root file that includes all generated c files
#===============================================================================
def gen_root_jni(c... | python |
# Generated by Django 3.2.2 on 2021-05-18 19:03
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Email',
fields=[
('id', mod... | python |
# -*- coding: utf-8 -*-
__author__ = "Frank Becker <fb@alien8.de>"
__copyright__ = "Frank Becker"
__license__ = "mit"
import importlib
def test_module_imports():
"""Test if all modules can be imported."""
modules = ["api", "auth", "awattar", "cli", "config", "defaults", "poller", "utils", "weather"]
for... | python |
class Queue:
def __init__(self):
self.storage = []
def size(self):
return len(self.storage)
def enqueue(self, item):
self.storage.append(item)
def dequeue(self):
return self.storage.pop(0)
| python |
# yellowbrick.utils
# Utility functions and helpers for the Yellowbrick library.
#
# Author: Jason Keung <jason.s.keung@gmail.com>
# Author: Patrick O'Melveny <pvomelveny@gmail.com>
# Author: Benjamin Bengfort <bbengfort@districtdatalabs.com>
# Author: Rebecca Bilbro <rbilbro@districtdatalabs.com>
# Created: T... | python |
# Generated by Django 3.2.7 on 2021-11-26 08:30
from django.db import migrations
# Migration that creates a user group called "Download approved user"
def create_barrier_search_download_approved_group(apps, schema_editor):
Group = apps.get_model("auth", "Group")
Group.objects.create(name="Download approved u... | python |
import numpy as np
#
# class Decoration:
# def __init__(self, s0, s1, s2, r0, r1, r2):
# self.s0 = s0
# self.s1 = s1
# self.s2 = s2
# self.r0 = r0
# self.r1 = r1
# self.r2 = r2
# assert len(s0) == 3, "s0 not a valid R^3 vector"
# assert len(s1) == 3, "... | python |
# -*- coding: utf-8 -*-
# Copyright 2019 Cohesity Inc.
import cohesity_management_sdk.models.agent_information
import cohesity_management_sdk.models.datastore_information
import cohesity_management_sdk.models.vmware_object_id
import cohesity_management_sdk.models.vmware_tag_attributes
import cohesity_management_sdk.mo... | python |
from adv_finance.multiprocess.multiprocess import mp_pandas_obj, process_jobs, process_jobs_
| python |
import pytest
from icevision.all import *
@pytest.fixture
def coco_bbox_parser(coco_dir):
return parsers.COCOBBoxParser(coco_dir / "annotations.json", coco_dir / "images")
@pytest.fixture
def coco_mask_parser(coco_dir):
return parsers.COCOMaskParser(coco_dir / "annotations.json", coco_dir / "images")
def ... | python |
################################################################################
#
# Package : AlphaPy
# Module : analysis
# Created : July 11, 2013
#
# Copyright 2017 ScottFree Analytics LLC
# Mark Conway & Robert D. Scott II
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use ... | python |
import asyncio
import discord
from common import botcolour, botname, db, logo, prefix
from discord.ext import commands
from modules.utils import getChannel, isAdmin, system_notification
class New(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command(name="new", aliases=['create'])... | python |
import math
import random
import numpy as np
import quaternion
from scipy import integrate
import cv2
from scipy.interpolate import RegularGridInterpolator, NearestNDInterpolator
from scipy.interpolate.interpnd import LinearNDInterpolator
from visnav.algo.image import ImageProc
from visnav.algo import tool... | python |
import os
import pickle
import json
import numpy as np
from sklearn.externals import joblib
from sklearn.linear_model import Ridge
from inference_schema.schema_decorators import input_schema, output_schema
from inference_schema.parameter_types.numpy_parameter_type import NumpyParameterType
def init():
global mod... | python |
import SimpleHTTPServer
import SocketServer
import sys
import time
class MyHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
def handle_one_request(self):
time.sleep(0.1)
return SimpleHTTPServer.SimpleHTTPRequestHandler.handle_one_request(self)
print("Serving local directory")
httpd = SocketServer.TC... | python |
"""
Support to interface with LGE ThinQ Devices.
"""
__version__ = "0.23.0"
PROJECT_URL = "https://github.com/ollo69/ha-smartthinq-sensors/"
ISSUE_URL = "{}issues".format(PROJECT_URL)
DOMAIN = "smartthinq_sensors"
MIN_HA_MAJ_VER = 2022
MIN_HA_MIN_VER = 5
__min_ha_version__ = f"{MIN_HA_MAJ_VER}.{MIN_HA_MIN_VER}.0"
C... | python |
# coding: utf-8
from sqlalchemy import CHAR, Column, Date, Float, ForeignKey, Integer, LargeBinary, SmallInteger, String, Table, Text, text
from sqlalchemy.orm import relationship
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
metadata = Base.metadata
class Category(Base):
__ta... | python |
from art import logo, vs
from data import data
import random
print(logo)
my_score = 0
missed = True
while missed:
random_data1 = random.choice(data)
score_1 = random_data1["follower_count"]
random_data2 = random.choice(data)
score_2 = random_data2["follower_count"]
print(f"Compare A: {rando... | python |
from typing import List, Optional
from aws_cdk.aws_lambda import Runtime
from aws_cdk.core import Stack
from b_cfn_lambda_layer.lambda_layer import LambdaLayer
class OpensearchIndexLayer(LambdaLayer):
def __init__(
self,
scope: Stack,
name: str
) -> None:
super().__init__(
... | python |
import no_pda_exceptions as e
class NOPDA(object):
def __init__(self, rules, input_alphabet, states,
initial_states, terminate_states):
self.rules = rules
self.input_alphabet = input_alphabet
self.states = states
self.current_state = initial_states
self.ter... | python |
# Generated by Django 3.1.13 on 2022-05-28 00:03
from django.db import migrations, models
import uuid
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Course',
fields=[
('id', model... | python |
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 21 16:29:21 2020
@author: willi
"""
import re
try:
from snapgene_reader import snapgene_file_to_dict, snapgene_file_to_seqrecord
except:
pass
try:
from Bio import SeqIO
from Bio import Entrez
except:
pass
import os
class FileParser():
'''
Cl... | python |
#!/usr/bin/python3.8
import time
from flask import render_template, flash, redirect, url_for, request
from flask_login import login_user, current_user, logout_user, login_required
from werkzeug.utils import secure_filename
from webapp import app, config, db, db_manager, bcrypt
from webapp.models import User
from webap... | python |
import numpy as np
from config import Config
def compute_challenge_metric_custom(res,lbls,normalize=True):
normal_class = '426783006'
normal_index=Config.HASH_TABLE[0][normal_class]
lbls=lbls>0
res=res>0
weights = Config.loaded_weigths
observed_score=np.sum(weights*get_... | python |
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt
import copy
import frappe
import frappe.share
from frappe import _, msgprint
from frappe.utils import cint
rights = ("select", "read", "write", "create", "delete", "submit", "cancel", "amend",
"print", "email", "repor... | python |
#!/usr/bin/python
import os,sys
import lcm
import time
home_dir =os.getenv("HOME")
#print home_dir
sys.path.append(home_dir + "/drc/software/build/lib/python2.7/site-packages")
sys.path.append(home_dir + "/drc/software/build/lib/python2.7/dist-packages")
from ipab.pause_command_message_t import pause_command_message_... | python |
from exporters.logger.base_logger import TransformLogger
from exporters.pipeline.base_pipeline_item import BasePipelineItem
class BaseTransform(BasePipelineItem):
"""
This module receives a batch and writes it where needed. It can implement the following methods:
"""
def __init__(self, options, metad... | python |
from Acccount import Account
class Drive(Account):
type = int
activo = int
def __init__(self, name, document, type, activo):
super().__init__(name, document)
self.type = type
self.activo = activo | python |
import unittest
from app.models import Source
class SourceTest(unittest.TestCase):
'''
Test Class to test the behaviour of the Source class
'''
def setUp(self):
'''
Set up method that will run before every Test
'''
self.new_source = Source(1,"Washington Post", "Leading ... | python |
"""
opstate.py
"Specification of the OpState class."
@author: Johan Monster (https://github.com/Hans-Bananendans/)
"""
class OpState:
"""This class represents a separate operational state, and can be used
to calculate used power values and separate these by channel."""
def __init__(self, device_powe... | python |
# Copyright 2021 The TensorFlow Authors. 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 applica... | python |
# -*- coding: utf-8 -*-
from ..setup.constants import NETWORK_DEVICE, SERIAL_DEVICE
from ..user import User, UserDetail
from ..settings import Setting
from ..certificate import Certificate
from ..notifications import Notification, NotificationSetting
from ..zones import Zone
from ..keypad import KeypadButton
HOSTS_FI... | python |
################################################################################
#
# Copyright (C) 2013-2015, Michele Cappellari
# E-mail: michele.cappellari_at_physics.ox.ac.uk
#
# Updated versions of the software are available from my web page
# http://purl.org/cappellari/software
#
# This software is provide... | python |
from typing import Optional
from asserts import (
assert_equal,
assert_false,
assert_raises,
assert_succeeds,
assert_true,
)
from dectest import TestCase, test
from dbupgrade.args import Arguments
from dbupgrade.files import FileInfo
from dbupgrade.filter import (
MAX_API_LEVEL,
MAX_VERSIO... | python |
# -*- coding: utf-8 -*-
from django.core.management import CommandError, call_command
from django.test import TestCase
from django.test.utils import override_settings
from six import StringIO
try:
from unittest import mock
except ImportError:
import mock
class ResetSchemaExceptionsTests(TestCase):
"""Tes... | python |
from django.db.models.manager import BaseManager
from .querysets import LocationQuerySet
class LocationManager(BaseManager.from_queryset(LocationQuerySet)):
"""
Manager class for location models constructed from LocationQuerySet.
Uses miles as distance unit.
"""
| python |
from django.db import models
from django.contrib.auth.models import AbstractBaseUser,BaseUserManager
from panel.models import Discount
from product.models import Product,ProductDetail
# Create your models here.
class MyAccountManager(BaseUserManager):
def create_user(self,email,first_name,last_name,password):
... | python |
#!/pxrpythonsubst
#
# Copyright 2020 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
... | python |
#! /usr/bin/env python3
# Copyright 2019 Samsung Research America
#
# 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 app... | python |
import discord
import youtube_dl
import os
#import ffprobe
from discord.ext import commands
from discord.utils import get
from discord import FFmpegPCMAudio
from os import system
from packages.CRITICAL.CLIENT import client
from packages.CRITICAL.VERSION import EJ_DJ_VERSION
import asyncio
import subprocess
import urlli... | python |
from applications_superstaq._init_vars import API_URL, API_VERSION
from applications_superstaq.superstaq_exceptions import (
SuperstaQException,
SuperstaQModuleNotFoundException,
SuperstaQNotFoundException,
SuperstaQUnsuccessfulJobException,
)
from . import converters
from . import finance
from . import... | python |
# -*- coding: utf-8 -*-
#------------------------------------------------------------------------------
# pycreviewer: source_file_parser.py
# Dromar [https://github.com/dromar-soft]
# License: MIT
#------------------------------------------------------------------------------
from pycparser import parse_file, c_genera... | python |
import random
import sc2
from sc2 import Race, Difficulty
from sc2.constants import *
from sc2.player import Bot, Computer
from sc2.position import Point2, Point3
class RampWallBot(sc2.BotAI):
async def on_step(self, iteration):
cc = self.units(COMMANDCENTER)
if not cc.exists:
return
... | python |
from django.conf import settings
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.db import models
from django.utils.encoding import force_str
from django.utils.translation import gettext_lazy as _
from .managers import MetaTagManag... | python |
import torch
import torch.nn as nn
def weights_init(m):
if isinstance(m, nn.Conv2d) or isinstance(m, nn.Linear):
nn.init.xavier_uniform_(m.weight.data)
nn.init.constant_(m.bias, 0.1)
class PNet(nn.Module):
''' PNet '''
def __init__(self, ):
super(PNet, self).__init__()
# ... | python |
from bayesnet.tensor.constant import Constant
from bayesnet.tensor.tensor import Tensor
from bayesnet.function import Function
class Negative(Function):
"""
element-wise negative
y = -x
"""
def forward(self, x):
x = self._convert2tensor(x)
self.x = x
if isinstance(self.x, ... | python |
"""
This script takes the LIRICAL output TSV and converts it to a format that can be uploaded
to seqr (pending implementation of https://github.com/broadinstitute/seqr/issues/2742).
"""
import argparse
import pandas as pd
import re
from utils.gene_ids import get_entrez_to_ensembl_id_map
def main():
p = argparse... | python |
import discord
from discord.ext import commands
from discord.ext.commands import cooldown
from discord.ext.commands.cooldowns import BucketType
import time
import asyncio
import asyncpg
from datetime import datetime, timedelta
from random import randint
from random import choice
import psutil
import os
import sys
colo... | python |
from numbers import Number
class TresholdEqual:
""" Implementation of numeric objects considered equal when within a
specified tolerance. The optional 'tolerance' parameter defaults to 1.
Only comparison operators are implemented. Attempt to compare with
objects of different types raises Ty... | python |
# -*- coding: utf-8 -*-
"""
Created on Tue Dec 24 20:43:09 2019
@author: elif.ayvali
"""
import sys
import gym
import pandas as pd
import numpy as np
import matplotlib.collections as mc
import matplotlib.pyplot as plt
from helpers import create_uniform_grid,discretize,visualize_samples
class QLearningAgent:
"""Q... | python |
import numpy as np
from dgl.frame import Frame, FrameRef
from dgl.utils import Index, toindex
import backend as F
import dgl
import unittest
N = 10
D = 5
def check_fail(fn):
try:
fn()
return False
except:
return True
def create_test_data(grad=False):
c1 = F.randn((N, D))
c2 = ... | python |
# Open The Text File & 'Read' It
# Insert The File Path Between The Brackets & Quotation Marks
with open(" ", "r") as file:
# Read The File & Write The First Replace Method
remove_1 = file.read().replace(" .", ".")
# Remaining Replace Methods
remove_2 = remove_1.replace(" , ", ", ")
remove_3 = remove_... | python |
import os,re,sys
# initializing bad_chars_list
bad_chars = [',', ';', ':', '!', '.', '(', ')', '"', "*"]
#filename="mat2vec-1a5b3240-abstracts-head.csv"
filename=sys.argv[1] #"mat2vec-1a5b3240-abstracts.csv"
print(filename)
filename_w="cleaned_"+filename
with open( filename_w, 'a+') as corpus_w:
with open(filena... | python |
### INTERACTIVE NAPLPS DEMO ###
### Interact with NAPLPS Client (PP3) over a serial connection ###
### John Durno, January 2017 ###
### Added auto-advance April 2017 ###
### Added chunks April 2017 ###
### Added quit (q) April 2017 ###
### Added timeout (auto=M) May 2017 ###
## Imports ###
import collections
import se... | python |
from flask import Flask, abort, jsonify, request
from flask_restful import Resource, reqparse
from flask_cors import CORS
app = Flask(__name__)
CORS(app)
## DUMMY DATA ##
currencies = [
{
"name": "btc",
"balance": "0.65448",
"address": "1BvBMSEYstWetqTFn5Au4m4GFg7xJaNVN2",
"seeds":... | python |
import os
import copy
import random
import functools
from datetime import datetime
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import torch.utils.data as data
import torch.utils.tensorboard as tensorboard
from core.model import NAC
from core.metric import AverageMe... | python |
from crowd_sim.envs.utils.agent import Agent
from crowd_sim.envs.utils.state import JointState
class Human(Agent):
# see Agent class in agent.py for details!!!
def __init__(self, config, section):
super().__init__(config, section)
self.isObstacle = False # whether the human is a static obstac... | python |
# _*_ coding: utf-8 _*_
import multiprocessing
from gensim.test.utils import datapath
from gensim.models.word2vec import LineSentence
from gensim.models.word2vec import PathLineSentences
from gensim.models import word2vec
from gensim.models import Word2Vec
from gensim.models import KeyedVectors
from gensim.utils.util... | python |
"""
This package contains utilities that are only used when developing drms in a
copy of the source repository.
These files are not installed, and should not be assumed to exist at
runtime.
"""
| python |
#!/usr/bin/env python
##
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# ... | python |
/home/runner/.cache/pip/pool/9d/74/0a/c53d742787105b6eebdef5c502cadfb8aaf2c96273099593c4c552f563 | python |
from .tictactoe import *
from .connectfour import *
| python |
from django.urls import path
from . import views
urlpatterns = [
path('users/', views.usersView.get, name='usersUrl'),
path('users/search', views.usersView.search, name='usersSearchUrl'),
path('users/<str:username>/', views.usersView.selected, name="selectedUserUrl"),
path('repos/', views.reposView... | python |
import argparse
from core import compat, app, utils, colors
from core.ctrl import api
compat.check_version()
app.mode = 'cli'
parser = argparse.ArgumentParser(
description="CTRL command line tool",
epilog="All accessible arguments listed above"
)
parser.add_argument('method', help="Specify API method")
parse... | python |
from k5test import *
plugin = os.path.join(buildtop, "plugins", "hostrealm", "test",
"hostrealm_test.so")
# Disable the "dns" module (we can't easily test TXT lookups) and
# arrange the remaining modules in an order which makes sense for most
# tests.
conf = {'plugins': {'hostrealm': {'module': ... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.