text string | size int64 | token_count int64 |
|---|---|---|
#!/usr/bin/python
# -*- coding:utf-8 -*-
import os
from flask import Flask, request, jsonify, send_from_directory, redirect # , send_file
from flask_cors import CORS
from flask_httpauth import HTTPBasicAuth
import lng
import pdf
import storage
import services
app = Flask(__name__)
auth = HTTPBasicAuth()
CORS(app)
... | 1,837 | 630 |
class Solution:
def isIsomorphic(self, s: str, t: str) -> bool:
lookup = {}
out = []
i = 0
for l1 in s:
if l1 not in lookup:
lookup[l1] = i
i += 1
out.append(lookup[l1])
lookup2 = {}
i = 0
out2 =... | 510 | 159 |
from codecs import open
import re
from setuptools import setup, find_packages
setup(
name='kleroteria',
# this version doesn't really mean anything since this ships as an app.
# it's also hardcoded in the requirements files.
version='0.0.1',
description='An email lottery and spiritual successor to ... | 683 | 212 |
import argparse
import os
import socket
import gym
import numpy as np
import torch
import DDPG
import TD3
import DISCOVER_DDPG
import DISCOVER_TD3
import utils
# DDPG tuned hyper-parameters are imported from
# OpenAI Baselines3 Zoo: https://github.com/DLR-RM/rl-baselines3-zoo
def hyper_parameter_dict_DDPG(args):
... | 8,596 | 2,760 |
import os
from setuptools import setup, find_packages
source_location = os.path.abspath(os.path.dirname(__file__))
def get_version():
with open(os.path.join(source_location, "VERSION")) as version:
return version.readline().strip()
setup(
name="sqlalchemy-greenplum",
version=get_version(),
li... | 1,590 | 505 |
#!/usr/bin/env python
#
# MIT License
#
# (C) Copyright 2019-2022 Hewlett Packard Enterprise Development LP
#
# 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 wi... | 4,976 | 1,526 |
"""
Network abstraction
"""
import logging
from random import choice
from netaddr import IPNetwork, IPAddress
from boto.ec2.networkinterface import (
NetworkInterfaceSpecification,
NetworkInterfaceCollection
)
from boto.exception import EC2ResponseError
from boto.vpc import VPCConnection
import boto3
from di... | 25,986 | 7,471 |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
Example with a single node (ACA CCD temperature) with solar heating
(2 bins).
"""
import xija
name = __file__[:-3]
model = xija.XijaModel(name, start='2015:001', stop='2015:050')
model.add(xija.Node, 'aacccdpt')
model.add(xija.Pitch)
model.add(xi... | 602 | 256 |
# https://technovechno.com/creating-graphs-in-python-using-matplotlib-flask-framework-pythonanywhere/
# https://stackoverflow.com/questions/50728328/python-how-to-show-matplotlib-in-flask
from flask import Flask, render_template
from graph import build_graph
app = Flask(__name__)
@app.route('/') # Change U... | 856 | 398 |
# encoding: utf-8
"""
open booking connect
Copyright (c) 2021, binary butterfly GmbH
Use of this source code is governed by an MIT-style license that can be found in the LICENSE file.
"""
from .common.database import QuartDatabase
db = QuartDatabase()
from .common.logger import Logger
logger = Logger()
from .common... | 594 | 188 |
import argparse
import boto3
from botocore.exceptions import ClientError
from urllib.parse import unquote
import time
from smart_open import open
import os
import sys
s3 = boto3.resource('s3')
parser = argparse.ArgumentParser(
description="Analyze Inventory Files")
parser.add_argument('--inventory_file', '-i',
... | 2,687 | 816 |
from enum import Enum
from random import randint
from faker import Faker
from faker_extensions.abstract_providers import WeightedProvider
from faker_extensions.common_categories import Gender
from faker_extensions.distinguishing_features_provider import BodyArea
class TattooProvider(WeightedProvider):
""" Eye we... | 999 | 316 |
from sys import argv
script, filename = argv
# First we open the file that was created in the normal excercise
textfile = open(filename)
#Next we print its contents
print textfile.read()
# Now we close the damn thing
textfile.close()
| 238 | 72 |
from dbas.database import DBDiscussionSession
from dbas.database.discussion_model import ShortLinks
from dbas.helper.query import set_user_language, generate_short_url
from dbas.tests.utils import TestCaseWithConfig
class QueryHelperTest(TestCaseWithConfig):
def test_set_german_language(self):
result = s... | 1,626 | 522 |
from sensorSimulation import sweeper
from System.Timers import Timer
eventTimer = Timer(1000)
sweepCadence = sweeper()
sweepCadence.minValue = 0.0
sweepCadence.maxValue = 254.0
sweepCadence.sweepTime = 60
sweepCadence.constantTime = 5.0
eventCount = 1
logScriptEvent("Sweeping Instantaneous Power & Ins... | 1,029 | 369 |
import os
import parser
import models
import data
import data_test
import numpy as np
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from sklearn.metrics import accuracy_score
import skimage
from mean_iou_evaluate import mean_iou_score
# import torch library
import torch
# model... | 4,036 | 1,230 |
import logging
import asyncio
import voluptuous as vol
import homeassistant.helpers.config_validation as cv
from homeassistant.components.fan import (
FanEntity, PLATFORM_SCHEMA, SPEED_OFF, SUPPORT_SET_SPEED, SUPPORT_OSCILLATE, SPEED_LOW, SPEED_MEDIUM, SPEED_HIGH)
from homeassistant.const import (
CONF_NAME, ... | 7,028 | 2,269 |
# NubeliU Billing SDK
# @autor: Sergio Colinas
from stevedore import extension
from billingclient import client as ckclient
from billingclient.openstack.common.apiclient import client
from billingclient.v1 import chart
from billingclient.v1 import core
from billingclient.v1 import metric
from billingclient.v1.rating.g... | 2,405 | 669 |
# This init is required for each cog.
# Import your main class from the cog's folder.
from .stackoverflow import StackOverflow
def setup(bot):
# Add the cog to the bot.
bot.add_cog(StackOverflow())
| 208 | 64 |
from PyQt5.QtCore import QObject
import socket
import struct
import base64
from Module.Packages import ClassBroadcastFlag
class ClassBroadcast(QObject):
current_ip = None
socket_ip = None
socket_port = None
socket_buffer_size = None
socket_obj = None
def __init__(self, config):
super(... | 2,658 | 893 |
#!/usr/bin/env python
# coding: utf-8
# In[ ]:
# pip install pypdf2
# conda install -c conda-forge pypdf2
# In[ ]:
import os
import re
import pandas as pd
import PyPDF2
# In[ ]:
INP_PATH = './input/'
OUT_PATH = './output/'
# In[ ]:
def load_pdf_files(file_path:str):
'''
Loads pdf files and into P... | 3,572 | 1,119 |
# Copyright (C) 2009 Stijn Cole
# Copyright (C) 2010-2011 Richard Lincoln
#
# 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 require... | 8,913 | 4,026 |
# -*- coding:utf-8 -*-
__author__ = 'harumonia'
import requests
import cookiejar as cookielib
import re
def zhihulogin(account,pwd):
if re.match("1\d{10}",account):
print("shoujihaomadenglu")
url_post='https://www.zhihu.com/signin'
req=requests.get() | 279 | 112 |
from abc import abstractmethod
from typing import List
class BaseTokenizer(object):
"""tokenizer meta class"""
@abstractmethod
def tokenize(self, text: str) -> List[str]:
pass
| 188 | 56 |
from configvars import database_url
from sqlalchemy import *
from sqlalchemy.orm import relationship
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm.session import sessionmaker
engine = create_engine(database_url)
Session = sessionmaker(bind=engine)
session = Session()
# # now session is a... | 1,898 | 642 |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/ads/googleads_v6/proto/services/google_ads_service.proto
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from g... | 288,902 | 106,663 |
import praw
import datetime
from ConfigParser import ConfigParser
import OAuth2Util
import os
import markdown
import bleach
import sys
import mysql.connector
from mysql.connector import errorcode
reload(sys)
sys.setdefaultencoding('utf8')
config = ConfigParser()
config.read("./subreddit-grabber.cfg")
subredditName = ... | 6,668 | 2,022 |
import unittest
import jmap
class TestModule(unittest.TestCase):
def test_module_semantic_version(self):
ver_info = jmap.VERSION.split('.')
self.assertGreaterEqual(len(ver_info), 3)
| 205 | 69 |
from flask import Flask,render_template,request
from flask.globals import request
from flask.helpers import url_for
from werkzeug.utils import redirect
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////Users/Zeliha/Desktop/TodoApp/todo.db'
db = SQLAlchem... | 2,120 | 771 |
#coding=utf-8
import os
import math
import collections
class KdNode(object):
"""docstring for KdNode"""
def __init__(self, train_set):
super(KdNode, self).__init__()
self.train_set = train_set
self.dot = None
self.dimension = None
self.left_set = None
self.left_... | 4,558 | 1,542 |
"""
Following https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/blob/master/datasets/combine_A_and_B.py
"""
import os
import cv2
import numpy as np
from tqdm import tqdm
import sys
sys.path.append(".")
from models import networks
from options.options import Options
from utils.util import create_dir, load_coef,... | 3,488 | 1,415 |
from lit_nlp import dev_server
from lit_nlp import server_flags
from absl import app
from lit_classes import GectorBertModel, GeceProdigyData
def main(_):
models = {"gector": GectorBertModel('bert_0_gector.th')}
datasets = {"test_data": GeceProdigyData('test_sample.jsonl')}
# Start the LIT server. See s... | 502 | 175 |
# coding=UTF-8
# ex:ts=4:sw=4:et=on
# Copyright (c) 2013, Mathijs Dumon
# All rights reserved.
# Complete license can be found in the LICENSE file.
import zipfile
from pyxrd.generic.io import get_case_insensitive_glob, COMPRESSION
from pyxrd.file_parsers.json_parser import JSONParser
from pyxrd.file_parsers.registr... | 666 | 232 |
import random
from typing import Dict, Any, Union, List
from src.genotype.mutagen import mutagen as MutagenFile
from src.genotype.mutagen.mutagen import Mutagen
from src.genotype.neat.operators.mutators.mutation_report import MutationReport
class _Null:
"""Default current value, allows for an option to be None""... | 5,650 | 1,645 |
# Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.
#
# You may assume that the array is non-empty and the majority element always exist in the array.
#
# Example 1:
#
#
# Input: [3,2,3]
# Output: 3
#
# Example 2:
#
#
# Input: [2,2,1,1,1... | 1,351 | 514 |
from django.http import Http404
from django.db.models import Q
from rest_framework.response import Response
from rest_framework import status, generics, viewsets
from django_filters.rest_framework import DjangoFilterBackend
# from rest_framework_filters.backends import DjangoFilterBackend as rsf_DjangoFilterBackend
... | 1,709 | 596 |
#This python script acts a function library used by the other files to the generate phases.
# coding: utf-8
# In[13]:
#inport nessessary libraries.
import os
import numpy as np
import librosa
# In[9]:
#Polar to read convertion of numpy matricies
def polar2real(mag, angle):
#Matrix of magnitudes * the exponent ... | 3,972 | 1,324 |
import inspect
import logging
import re
import sys
from .runtime.qualname import get_qualname
from .runtime.decorated import get_decorated
try: # py2/3 compatibility
basestring
except NameError:
basestring = (str, bytes)
try:
import builtins
except ImportError:
import __builtin__ as builtins
_PY3 =... | 8,145 | 2,370 |
# Copyright 2021-2022 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agre... | 3,929 | 1,383 |
import sys
n=int(raw_input())
a=[]
a=map(int,sys.stdin)
a.sort()
for _ in a:
print _
| 99 | 51 |
"""Config flow for IRegul integration."""
from __future__ import annotations
import logging
from typing import Any
import voluptuous as vol
from homeassistant import config_entries
from homeassistant.core import HomeAssistant
from .const import CONF_HOST
from .const import CONF_PASSWORD
from .const import CONF_USERN... | 1,846 | 585 |
# pylint: disable=too-many-arguments, too-many-locals, too-many-statements, too-many-instance-attributes, too-many-branches, no-member, no-name-in-module, anomalous-backslash-in-string, too-many-function-args, no-self-use
"""VPN Update"""
import time
import urllib.request
from configparser import ConfigParser
from... | 4,940 | 1,602 |
import puzzleinput
x = 0
y = 0
x_direction = 1
y_direction = 0
for line in puzzleinput.lines:
action = line[0]
value = int(line[1:])
if action == "F":
x += x_direction * value
y += y_direction * value
if action == "N":
y -= value
if action == "S":
y += value
if a... | 1,297 | 389 |
"""
Still empty, but will keep you updated
""" | 47 | 16 |
import json
from pandelytics import search
if __name__ == "__main__":
news = search.search("jhu", "Data")
if news:
print(json.dumps(news, indent=4))
| 167 | 60 |
#!/usr/bin/env python3
import numpy as np
import matplotlib.pyplot as plt
import os
linear = np.arange(1, 20)
square = linear ** 2
log = np.log(linear)
random = np.random.randint(0, 100, 20)
fig, axes = plt.subplots(2, 1, figsize=(5, 5))
# In order to decorate plots we can set the title, the x/y label and the ticks... | 900 | 349 |
import os
from settings import STYLES_DIR
class CssStyles:
bar_style = os.path.join(STYLES_DIR, "bar-style.css")
divider_style = os.path.join(STYLES_DIR, "divider-style.css")
simple_style = os.path.join(STYLES_DIR, "simple-style.css")
default_style = simple_style
@staticmethod
def stylenames... | 772 | 265 |
from common.util.constant import TIMESTAMP
FORECAST_VALUE = 'forecastValue'
CONFIDENCE = 'confidence'
UPPER_BOUNDARY = 'upperBoundary'
LOWER_BOUNDARY = 'lowerBoundary'
class UnivariateForecastItem:
def __init__(self, forecast_value, lower_boundary, upper_boundary, confidence, timestamp):
self.forecast_val... | 783 | 266 |
"""
Data base save and recall motor positions
Author: Friedrich Schotte
Date created: 2013-11-29
Date last modified: 2019-05-28
"""
__version__ = "4.1.2" # "%s.line%d.%s" % (..,int(row),..): ValueError: cannot convert float NaN to integer
from logging import debug,info,warn,error
import numpy
numpy.warnings.filterwarn... | 33,075 | 9,740 |
# global variables
x = "awesome"
def myfunc():
print("Python is " + x)
myfunc()
print("Python is " + x)
# Global Keyword
def func():
global x
x = "fantastic"
func() | 191 | 83 |
import numpy as np
from glypy import GlycanComposition
from glycan_profiling.database.composition_network import (
CompositionGraphNode, NeighborhoodWalker)
from glycan_profiling.task import log_handle
from .constants import (
DEFAULT_LAPLACIAN_REGULARIZATION,
NORMALIZATION,
DEFAULT_RHO,
RESET_T... | 19,911 | 5,652 |
# A function is a block of organized, reusable code that is used to perform a single, related action.
# Functions provide better modularity for your application and a high degree of code reusing.
# As you already know, Python gives you many built-in functions like print(),
# etc. but you can also create your own func... | 626 | 159 |
from django.urls import path
from . import views
app_name='baixa'
urlpatterns = [
path('log/', views.log_baixa, name='log_baixa'),
path('<int:pk>/produto/', views.baixa_produto, name='baixa_produto')
] | 204 | 79 |
from office365.sharepoint.base_entity import BaseEntity
class SPListRule(BaseEntity):
pass
| 97 | 31 |
class things(object):
def test(hi):
print "Hi"
t = things()
t.test("hello world")
| 95 | 34 |
import signal as s
from aerial import Feed, wrappers as w
def test_feed_init():
""" Confirm feed is initialized if it is None """
w.feed = None
w.received(s.SIGINT)
assert isinstance(w.feed, Feed)
def test_received_false():
""" Confirm the method returns False if no signal recieved """
asser... | 1,497 | 547 |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
from os import path
from codecs import open
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
here = path.abspath(path.dirname(__file__))
with open(path.join(here, 'README.md'), encoding='utf-8') as f:
long_description =... | 923 | 327 |
import csv
import itertools
import sys
PROBS = {
# Unconditional probabilities for having gene
"gene": {
2: 0.01,
1: 0.03,
0: 0.96
},
"trait": {
# Probability of trait given two copies of gene
2: {
True: 0.65,
False: 0.35
},
... | 7,230 | 2,148 |
import pickle
from Repositories.BaseRepository import Repository
class PickleRepo(Repository):
'''
A generic class for a repository for a given class
'''
def __init__(self, fileName, name):
'''
The constructor of the Repository class
:param fileName: the ... | 2,977 | 823 |
#Copyright 2018 Julio Navarro
#Built at the University of Strasbourg (France). CSTB team @ ICube laboratory
# -*- coding: utf-8 -*-
import sys
sys.path.insert(0,'../')
sys.path.insert(0,'../database_queries/')
from database_queries_biblio import *
import bibtexparser
import codecs
import unidecode
def recover_acce... | 5,322 | 1,841 |
#!/usr/bin/python3
"""
(C) Copyright 2020-2021 Intel Corporation.
SPDX-License-Identifier: BSD-2-Clause-Patent
"""
import os
import security_test_base as secTestBase
from cont_security_test_base import ContSecurityTestBase
from pool_security_test_base import PoolSecurityTestBase
class DaosContainterSecurityTest(C... | 9,565 | 2,814 |
#!/usr/bin/env python3
"""
Extract all links from a web page
=================================
Author: Laszlo Szathmary, 2011 (jabba.laci@gmail.com)
Website: https://pythonadventures.wordpress.com/2011/03/10/extract-all-links-from-a-web-page/
GitHub: https://github.com/jabbalaci/Bash-Utils
Given a webpage, extract ... | 1,205 | 447 |
#!/usr/bin/python
#-*- coding: utf-8 -*-
from texas.annotations.AnnotationSet import AnnotationSet
from texas.views.AnnotationView import AnnotationView
from texas.views.CharView import CharView
from texas.views.TokenView import TokenView
from texas.views.SpanView import SpanView
from texas.views.RelationView import R... | 2,563 | 727 |
import pymongo
from zeroservices import ResourceService, ZeroMQMedium
from zeroservices.backend.mongodb import MongoDBCollection, MongoDBResource
from zeroservices.memory import MemoryCollection, MemoryCollection
from zeroservices.resources import is_callable
import sys
from zmq.eventloop import ioloop, zmqstream
iol... | 1,496 | 441 |
# -*- coding: utf-8 -*-
"""
Views
"""
import random
from django.db.models import Count
from django import template
from django.views.generic.detail import DetailView
from django.utils.safestring import mark_safe
from slideshows.models import Slideshow, DEFAULT_SLIDESHOWS_TEMPLATE, DEFAULT_SLIDESHOWS_RANDOM_SLIDE_TEMP... | 2,743 | 817 |
import sys
import xml.etree.ElementTree as ET
import string
from xml.sax.saxutils import escape
# set to maintain unique coref labels across all entities
corefSet = set()
def processEvents(root, triggerDict, argDict):
if root.tag == "event":
eventType = root.attrib["TYPE"]
eventSubtype = root.attr... | 12,212 | 3,449 |
import os
import yaml
import json
import modules.file_utils as file_utils
from .instance_handler import InstanceHandler
from .instances.experiment import Experiment
from .instances.dataset import Dataset
from .cache import Cache
class DataHandler:
def __init__(self, data_directory):
self.experiments_direct... | 2,737 | 713 |
"""MethodMock class that keeps method data.
"""
import inspect
import functools
from vmock import matchers
from vmock.mockerrors import CallSequenceError
from vmock.mockerrors import InterfaceError
from vmock.mockerrors import UnexpectedCall
class MethodMock(object):
"""Method mock.
Method mock object rec... | 7,512 | 2,139 |
#!/usr/bin/env python3
from __future__ import unicode_literals
import yt_dlp
import json
import sys
import os
class MyLogger(object):
def __init__(self):
self.vidmeta = {}
def debug(self, msg):
if msg.startswith('{"'):
self.vidmeta = json.loads(msg)
return
print... | 2,532 | 863 |
class NoSuchPlayerInGame(Exception):
pass
class GameIsFull(Exception):
pass
class NoSuchColor(Exception):
pass
class ThisPieceCantMoveThere(Exception):
pass
class InvalidStringCoordinates(Exception):
pass
class NoSuchPieceSubtype(Exception):
pass
class NotThisColorsTurn(Exception):
pas... | 321 | 100 |
# -*- coding: utf-8 -*-
import openpyxl
import os
from reportlab.lib import colors
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.platypus import Paragraph, SimpleDocTemplate, Table
from ossreport.proto.proto import Component, File, Level, Risk
risk_head = {
"A": Risk.__name__.capitalize()... | 4,579 | 1,498 |
# script for reading in dmap strings over a socket into a dictionary
# 7/1/2015
# jon klein, jtklein@alaska.edu
import numpy as np
import pdb
import socket
import time
import json
import datetime
import time
DATACODE = 33
DATACHAR = 1
DATASHORT = 2
DATAINT = 3
DATAFLOAT = 4
DATADOUBLE = 8
DATASTRING = 9
DATALONG = 1... | 3,411 | 1,211 |
import pandas as pd
import sys
def output_predictions(test_path, pred_path, out_path, topic):
test = pd.read_csv(test_path, delimiter='\t', header=0, encoding = "latin-1")
if topic is not None:
test = test.loc[test["Target"] == topic].reset_index()
def clean_ascii(text):
# function to remov... | 1,179 | 439 |
from typing import Any, Dict, Type, TypeVar, Union
import attr
from ..types import UNSET, Unset
T = TypeVar("T", bound="Category")
@attr.s(auto_attribs=True)
class Category:
""" """
category: str
source: Union[Unset, str] = UNSET
weight: Union[Unset, float] = UNSET
page_id: Union[Unset, int] =... | 1,333 | 421 |
import sys
import math
from itertools import islice
radius = 1
def get_line_number(phrase, file_name):
with open(file_name) as f:
for i, line in enumerate(f, 1):
if phrase in line:
return i
return False
def read_weights(file_name, ln, size=1):
content = []
with... | 12,890 | 4,799 |
# Generated by Django 2.2.8 on 2020-07-03 09:06
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('library', '0010_onlinecourse_course_url'),
]
operations = [
migrations.AlterField(
model_name='onlinecourse',
name='... | 451 | 153 |
#!/usr/bin/env python3
import argparse
import os
from lxml import etree
from SAFEcomments import annotation
from SAFEcomments import archive_handler
from SAFEcomments import compare
from SAFEcomments import odt_namespaces
exact_similarity = 0.6
fuzzy_similarity = 0.6
parser = argparse.ArgumentParser(description='T... | 10,568 | 3,284 |
import time
import argparse
from copy import deepcopy
from progress.bar import IncrementalBar
import numpy as np
import torch
from torch import nn
import torch.nn.functional as F
import torch.optim as optim
from torchvision import utils as vutils
from itertools import chain
from gan.generator import MuseGenerator
from ... | 18,997 | 6,435 |
from setuptools import setup
setup(name='pIRC',
version='0.5.5',
description='A light, customizable python-based IRC bot library.',
url='https://github.com/techborn/pIRC',
author='Techborn',
author_email='unborntech@pm.me',
license='Custom',
packages=['pIRC'])
| 304 | 100 |
from django.db.models import signals
from unittest import mock
from unittest.mock import ANY, Mock
import factory
import pytest
from django.conf import settings
from company.email import CollaboratorNotification, OwnershipChangeNotification
from .factories import CollaboratorInviteFactory, OwnershipInviteFactory
@p... | 2,880 | 891 |
import yaml
import _thread
from . import server
import time
config = yaml.load(open("config/game.yaml"))['game']
def main_loop():
for player in list(server.players.values()):
player.update(time.time() - main_loop.last_tick)
main_loop.last_tick = time.time()
time.sleep(1)
main_loop.last_tick = tim... | 523 | 178 |
import cv2
import numpy as np
import math
import sys
from .Utils import *
def getEllipseLineIntersection(Ellipse, lines_seg, image_proc_img):
x = Ellipse.x
y = Ellipse.y
a = Ellipse.a
b = Ellipse.b
angle = (Ellipse.angle) * math.pi / 180
# build transformation matrix http://math.stac... | 14,266 | 5,419 |
import rospy
# Wraps Rate so that the hz parameter can be retrieved
'''
class RateWrapper(rospy.Rate):
def __init__(self, rate):
self.super(self, RateWrapper).__init__(rate)
self._hz = rate
@attr.getter
def Rate(self):
return self._hz
''' | 279 | 100 |
# !/usr/bin/env python
# coding: utf-8
__author__ = 'zhouhenglc'
class DmsException(Exception):
code = 500
message = ''
def __init__(self, detail=None, *args, **kwargs):
self.msg = self.message % kwargs
if detail is None:
self.detail = self.msg
else:
self... | 720 | 245 |
from output.models.nist_data.atomic.any_uri.schema_instance.nistschema_sv_iv_atomic_any_uri_pattern_1_xsd.nistschema_sv_iv_atomic_any_uri_pattern_1 import NistschemaSvIvAtomicAnyUriPattern1
__all__ = [
"NistschemaSvIvAtomicAnyUriPattern1",
]
| 247 | 99 |
from koala.typing import *
from koala.message.base import JsonMessage
from dataclasses import dataclass
@dataclass
class RpcRequest(JsonMessage):
service_name: str = ""
method_name: str = ""
actor_id: ActorID = ""
reentrant_id: int = 0
request_id: int = 0
# server_id为0, 那么就不强制校验server_id
#... | 1,011 | 392 |
from flask import Flask, request
app = Flask(__name__)
@app.route('/login', methods=['POST', 'GET'])
def login():
error = None
if request.method == 'POST':
if valid_login(request.form['username'],
request.form['password']):
return log_the_user_in(request.form['usern... | 389 | 110 |
# Given an N by M matrix consisting only of 1's and 0's, find the largest
# rectangle containing only 1's and return its area.
# For example, given the following matrix:
# [[1, 0, 0, 0],
# [1, 0, 1, 1],
# [1, 0, 1, 1],
# [0, 1, 0, 0]]
# Return 4.
def largest_rectangle(matrix):
if not matrix or... | 1,261 | 528 |
import os
import uuid
from django.db import models
from django.conf import settings
from django.utils import timezone
class SourceManager(models.Manager):
def take(self, name, **kwargs):
if not name:
return None
try:
o = self.get(name=name)
except Source.DoesNotE... | 7,207 | 2,169 |
# -*- coding: utf-8 -*-
'''
# Model admin <= https://docs.djangoproject.com/es/1.10/_modules/django/contrib/admin/options/#ModelAdmin
In the after link, see you all configuration and options about model admin.
Is very important understand the getters:
+ e.g.:
get_form(self, request, obj=None,... | 2,675 | 757 |
# Copyright 2013 Rackspace
#
# 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... | 2,098 | 563 |
from fastapi import APIRouter, Body, Depends, HTTPException, Response, status
from fastapi.encoders import jsonable_encoder
from app.core.security import cookie_is_none, oauth2_scheme
from app.logs import logger
from app.models.car import Car as ModelCar
from app.models.user import User as ModelUser
from app.schemas.c... | 5,146 | 1,566 |
from output.models.ms_data.regex.re_e13_xsd.re_e13 import (
Regex,
Doc,
)
__all__ = [
"Regex",
"Doc",
]
| 121 | 58 |
# Copyright (c) 2018 PaddlePaddle 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 appli... | 15,170 | 4,679 |
from utils import lazy_iterator, iterator
import sys
if("-s" in sys.argv):
lazy_iterator()
else:
iterator() | 117 | 39 |
#!python3
import os, sys
print(sys.executable)
from winsys import fs, dialogs
print(dialogs.dialog("abc", ("def", ["1", "2", "3"])))
| 133 | 51 |
# Generated by Django 3.0.5 on 2020-07-29 04:34
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('cubes', '0007_auto_20200729_1232'),
]
operations = [
migrations.AlterField(
model_name='cubecomment',
name='created_... | 555 | 188 |
from rest_framework import permissions, viewsets
from mpdb_api.filters import CustomSearchFilter
from users.models import CustomUser
from mpdb_api.models import Comment, Movie, Watchlist, Favorite, UserRating
from mpdb_api.permissions import IsOwnerOrReadOnly, IsAdminOrReadOnly
from mpdb_api.serializers import (
C... | 4,438 | 1,259 |
num1=1
num2=2
num3=3
num4=4
num5=100
| 37 | 28 |
import SocketServer
class Server(SocketServer.BaseRequestHandler):
clients = 0
def setup(self):
print "Received connection from " + self.client_address[0] + ":" + str(self.client_address[1])
self.lost = False
self.shutdown = False
if Server.clients > 1:
print "Server is full!"
self.request.send("S... | 1,359 | 539 |