text string | size int64 | token_count int64 |
|---|---|---|
#!/usr/bin/env python
from bs4 import BeautifulSoup
from urllib.parse import urlsplit
import json
import sys
import utils
url = sys.argv[1]
path = sys.argv[2]
url = urlsplit(url)
host = url.netloc
if not host.endswith('kattis.com'):
exit(1)
name = url.path.rstrip('/').split('/')[-1] # /problems/skiresort
with op... | 841 | 313 |
import pdb
from torch.nn.modules.loss import _Loss
from torch.autograd import Variable
import math
import torch
import time
import numpy as np
import torch.nn as nn
import random
import torch.backends.cudnn as cudnn
import torch.nn.functional as F
import torch.distributions as tdist
import copy
import pymesh
import pyv... | 18,756 | 7,748 |
#!/usr/bin/env python
import sys
from setuptools import setup, find_packages
from os import path
this_directory = path.abspath(path.dirname(__file__))
with open(path.join(this_directory, 'README.md'), encoding='utf-8') as f:
long_description = f.read()
install_requires = [
"datapipelines>=1.0.7",
"mera... | 1,789 | 604 |
import time
import numpy as np
from cvxopt import matrix, solvers
from sympy import pprint
solvers.options['show_progress'] = False
solvers.options['maxiters'] = 1
def getSolution(code_gen, x_0, u_0, x_ref, u_ref, params):
A = code_gen.A_mat(x_0[:,0:1], x_0, u_0, params)
b = code_gen.b_mat(x_0[:,0:1], x_0, u_0, para... | 710 | 341 |
# -*- coding: utf-8 -*-
"""
Profile: https://www.hl7.org/fhir/DSTU2/enrollmentrequest.html
Release: DSTU2
Version: 1.0.2
Revision: 7202
"""
from typing import List as ListType
from pydantic import Field
from . import domainresource, fhirtypes
class EnrollmentRequest(domainresource.DomainResource):
"""Enroll in ... | 3,460 | 912 |
from django.conf.urls import patterns, include, url
from django.contrib import admin
from django.contrib.auth import views as auth_views
from newsy import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^accounts/register/$', views.register_user),
url(r'^accounts/register_success/$', views.re... | 537 | 188 |
def setup_ntupler(process, cms):
print '=' * 60
print "Setting up NTupler"
print '=' * 60
######################################################################################################
################################## nTuple Configuration ##############################################
... | 2,954 | 880 |
from base_b import convert
from random import randint
DATA_DIR = "../data/"
def get_prime(partition):
primes = list()
#filename = glob.glob(DATA_DIR + "primes" + str(partition))
filename = DATA_DIR + "primes" + str(partition)
with open(filename, "r") as f:
content = f.readlines()
line... | 799 | 264 |
from __future__ import absolute_import
import redisext.models.abc
class Queue(redisext.models.abc.Model):
def pop(self):
'''
Pop item from queue.
:returns: item from queue
'''
item = self.connect_to_master().rpop(self.key)
return self.decode(item)
def push(se... | 1,477 | 467 |
def write_notification(email: str, mensagem=''):
with open('log.txt', mode='a') as email_file:
conteudo = f'Email: {email} - msg: {mensagem}\n'
email_file.write(conteudo) | 190 | 66 |
import matplotlib.pyplot as plt
import numpy as np
import pickle
import tensorflow as tf
import UVGenerator
class DataLoader():
def __init__(self,pg,sampleFile=None):
self.pg = pg
self.numV = np.sum(self.pg.active)
pg.setPose(pg.defaultPose)
self.neutral = pg.getVertices()[pg.acti... | 6,947 | 2,236 |
# -*- coding: utf-8 -*-
import smtplib
from smtplib import SMTPException
from email.mime.text import MIMEText
import csv
import codecs
import logging
from logging import StreamHandler
from logging.handlers import RotatingFileHandler
import sys
import time
LOGGER = 'logger'
user = "robot.artsiom.mishuta"
password = "r... | 2,105 | 710 |
from __future__ import absolute_import
from rest_framework import generics
from taggit.models import Tag
from rest_api.filters import MayanObjectPermissionsFilter
from rest_api.permissions import MayanPermission
from .permissions import PERMISSION_TAG_VIEW
from .serializers import TagSerializer
class APITagView(ge... | 857 | 263 |
import numpy as np
import cv2
import matplotlib.pyplot as plt
import json
import os
pose_point_pair_ver1 = [[1, 2], [2, 3], [3, 4], [1, 5], [5, 6], [6, 7], [1, 9], [9, 8], [8, 12], [12, 1]]
pose_point_pair_ver2 = [[1, 2], [2, 3], [3, 4], [1, 5], [5, 6], [6, 7], [2, 9], [9, 8], [8, 12], [12, 5]]
face_point_pair = [
... | 2,191 | 1,247 |
from __future__ import absolute_import
from django.utils.translation import ugettext_lazy as _
from permissions.models import PermissionNamespace, Permission
namespace = PermissionNamespace('scheduler', _(u'Scheduler'))
PERMISSION_VIEW_JOB_LIST = Permission.objects.register(namespace, 'jobs_list', _(u'View the inter... | 336 | 99 |
# Generated by Django 2.0 on 2020-02-04 08:42
from django.db import migrations, models
import django.db.models.manager
class Migration(migrations.Migration):
dependencies = [
('django_dramatiq', '0002_auto_20191104_1354'),
]
operations = [
migrations.AlterModelManagers(
name... | 765 | 250 |
#%%
"""
- Wiggle Sort
- https://leetcode.com/problems/wiggle-sort/
- Medium
Given an unsorted array nums, reorder it in-place such that nums[0] <= nums[1] >= nums[2] <= nums[3]....
Example:
Input: nums = [3,5,2,1,6,4]
Output: One possible answer is [3,5,1,6,2,4]
"""
#%%
##
class S1:
def wiggleSort(self, nums):
... | 717 | 286 |
from setuptools import setup
setup(
name="pytest-mockito",
version='0.0.4',
description='Base fixtures for mockito',
long_description=open('README.rst').read(),
license='MIT',
author='herr kaste',
author_email='herr.kaste@gmail.com',
url='https://github.com/kaste/pytest-mockito',
pl... | 1,017 | 323 |
## Add modules that are necessary
import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
from sympy import *
import matplotlib.pyplot as plt
import operator
from IPython.core.display import display
import torch
from torch.autograd import Variable
import torch.utils.da... | 4,843 | 1,669 |
import numpy as np
import pytest
from ..context import zeropdk # noqa
from zeropdk.layout.waveguides import waveguide_dpolygon
from zeropdk.layout import insert_shape
import klayout.db as kdb
@pytest.fixture
def top_cell():
def _top_cell():
layout = kdb.Layout()
layout.dbu = 0.001
TOP = ... | 890 | 360 |
"""Custom exception where the builin exceptions won't suffice"""
# Invalid user in the configfile (non-numeric UserID with no "@")
class InvalidUser(Exception):
def __init__(self, userid):
self.bad_id = userid
# No Token or empty token defined
class MissingTelegramToken(Exception):
pass
# No users... | 1,258 | 363 |
import atexit
import json
import os
import pickle
import re
import shutil
import subprocess
import tempfile
import time
import urllib.error
import urllib.request
import sys
from pathlib import Path
from CraftCore import CraftCore, AutoImport
from Blueprints.CraftVersion import CraftVersion
from CraftOS.osutils import... | 9,072 | 2,489 |
from func.db_mongo import *
# Индекс следующего элемента
try:
id = db['test'].find().sort('id', -1)[0]['id'] + 1
except:
id = 1
print(id) | 141 | 63 |
urlString = 'https://google.com'
pathUsedWhenPathStringAndDefaultPathStringAndDefault2PathStringIsNotFound = 'nevermind'
logPathString = "/tmp/log.txt";
logsPathString = "logs/subdir/output";
b_fileRead = True
class IBaseArray(object): pass
work = 0
jump = 2
parse = 42
flower = True
termination = False
findPath... | 3,213 | 971 |
"""
Django settings for web3 project.
Generated by 'django-admin startproject' using Django 1.10.1.
For more information on this file, see
https://docs.djangoproject.com/en/1.10/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.10/ref/settings/
"""
import os
... | 6,260 | 2,270 |
#!/usr/bin/env python
# encoding: utf-8
"""Usage:
visualize.py gecko (<hypotheses_path>|<database.task.protocol>) <uri> [--map --tag_na --database.task.protocol=<database.task.protocol> --embeddings=<embeddings>]
visualize.py speakers (<hypotheses_path>|<database.task.protocol>) <uri>
visualize.py update_distanc... | 8,425 | 2,588 |
from __future__ import division
import rospy
import tf2_ros
from threading import Event
from Queue import Queue, Empty
from hopper_controller.srv import MoveLegsToPosition, MoveCoreToPosition, MoveLegsUntilCollision, MoveLegsToRelativePosition, MoveBodyRelative, ReadCurrentLegPositions, ReadCurrentLegPositionsRespons... | 16,003 | 5,158 |
import numpy
import os
class GraphFeatures:
def __init__(self, CONFIG):
self.BASE = CONFIG['BASE']
self.EMBED_DIM = 200
self.authors = {}
with open(os.path.join(self.BASE, 'resources', 'authors.txt')) as authors:
for line in authors.readlines():
text_i... | 1,004 | 323 |
# Copyright 2019 NEC Corporation
#
# 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... | 4,314 | 1,604 |
# -*- coding: utf-8 -*-
#
# Database mixins
#
# ------------------------------------------------
# imports
# -------
from flask import current_app
# helpers
# -------
def current_db():
return current_app.extensions['sqlalchemy'].db
# mixins
# ------
class ModelMixin(object):
"""
Example database mixin... | 6,077 | 1,631 |
# Generated by Django 3.0.5 on 2020-04-07 10:34
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('inv', '0006_auto_20200407_1033'),
]
operations = [
migrations.AlterField(
model_name='product',
name='stock',
... | 392 | 144 |
from django.db.models.signals import post_save
from django.dispatch import receiver
from ephios.core import mail
from ephios.core.models import LocalParticipation
from ephios.core.plugins import PluginSignal
# PluginSignals are only send out to enabled plugins.
register_consequence_handlers = PluginSignal()
"""
This... | 2,577 | 726 |
# -*- coding: utf-8 -*-
import pytest
from group import Group
from application import Application
@pytest.fixture
def app(request):
fixture = Application()
request.addfinalizer(fixture.destroy)
return fixture
def test_one(app):
app.open_catalog_page()
app.open_autorisation()
app.autorisation(G... | 401 | 135 |
"""
byceps.services.shop.order.actions.create_ticket_bundles
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2021 Jochen Kupperschmidt
:License: Revised BSD (see `LICENSE` file for details)
"""
from .....typing import UserID
from ....ticketing.dbmodels.ticket_bundle import TicketBundle
from... | 2,116 | 681 |
# Generated by Django 3.0.7 on 2020-06-11 01:01
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
("track", "0005_auto_20200610_2246"),
]
operations = [
migrations.RenameModel(
old_name="TrackPoint",
new_name="Point",
... | 450 | 158 |
from cgi import escape
from wtforms import widgets
from wtforms.compat import text_type
from wtforms.widgets.core import html_params, HTMLString
class CheckboxSelectWidget(widgets.Select):
""" Select widget that is a list of checkboxes
"""
def __call__(self, field, **kwargs):
if 'id' in kwargs:
... | 1,108 | 327 |
# MIT License
#
# Copyright (c) 2021 Soohwan Kim and Sangchun Ha and Soyoung Cho
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights... | 6,702 | 2,128 |
import os
import json
import time
import base64
from io import StringIO
from tornado import websocket, web, ioloop, gen, escape
# list of clients to push the data to
clients = []
class BaseHandler(web.RequestHandler):
def get_current_user(self):
return self.get_secure_cookie("user")
class AudubonHandler... | 4,540 | 1,397 |
# -*- coding: utf-8 -*-
"""
Test base class with commonly used methods and variables
"""
import json
import re
import unittest
import httpretty
class TestGithubBase(unittest.TestCase):
"""Test Github actions and backing library."""
OAUTH2_TOKEN = '12345'
ORG = 'NOT_REAL'
URL = 'http://localhost/'
... | 11,233 | 3,389 |
#!/usr/bin/env python3
import re
import subprocess
import nanodurationpy as durationpy
import csv
import time
import datetime
import os
import shutil
import shlex
import json
# output paths should be mounted docker volumes
RESULT_CSV_OUTPUT_PATH = "/evmraceresults"
RESULT_CSV_FILENAME = "evm_benchmarks_evmone384.csv... | 4,799 | 2,173 |
# This file is part of the Etsin service
#
# Copyright 2017-2018 Ministry of Education and Culture, Finland
#
# :author: CSC - IT Center for Science Ltd., Espoo Finland <servicedesk@csc.fi>
# :license: MIT
from etsin_finder_search.reindexing_log import get_logger
from etsin_finder_search.utils import \
catalog_rec... | 17,755 | 5,398 |
# Copyright 2018 Google LLC
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | 3,350 | 937 |
# coding: utf-8 -*-
import pathlib
from tkinter.filedialog import askopenfilename
from tkinter import Tk
import os
import re
import textwrap
import easyocr
import string
reader = easyocr.Reader(['de','en', 'pt'])
erlaubtezeichen = string.ascii_letters+string.digits
from pdf2jpg import pdf2jpg
wrapper = textwrap.TextWra... | 5,074 | 1,812 |
# Lint as: python3
'''
Policy class for computing action from weights and observation vector.
Horia Mania --- hmania@berkeley.edu
Aurelia Guy
Benjamin Recht
'''
"""Policy class for computing action from weights and observation vector.
It is a modified policy class from third_party/py/ARS/code/policies.py.
"""
i... | 8,371 | 2,729 |
# Generated by Django 3.0.4 on 2020-04-18 10:22
import core.managers
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('pos... | 1,363 | 446 |
import datetime
from unittest import TestCase, mock
from airflow import DAG, configuration
from airflow_dbt.hooks.dbt_hook import DbtCliHook
from airflow_dbt.operators.dbt_operator import (
DbtSeedOperator,
DbtSnapshotOperator,
DbtRunOperator,
DbtTestOperator
)
class TestDbtOperator(TestCase):
def... | 1,657 | 560 |
# -*- coding: utf-8 -*-
"""
Jacob Ashcraft
RSA Algorithm 2
Advanced Algorithms
Professor Teichert
"""
import math
###################### Constants ######################
primes = [110487089277121433970806926710031676468486143869889341376537597422615205558243704080712263653321436167325483283204907700784269778678235765... | 4,122 | 2,805 |
from transformers import pipeline
nlp = pipeline("ner")
sequence = """Hugging Face Inc. is a company based in New York City. Its headquarters are in DUMBO, therefore very
close to the Manhattan Bridge which is visible from the window."""
print(nlp(sequence))
#[
# {'word': 'Hu', 'score': 0.999563276767730... | 2,966 | 1,216 |
from pyvision.misc.mtcnn import MTCNN
from pyvision.misc.mtcnn.utils.visualize import show_boxes, _show_boxes
from PIL import Image
import cv2
from glob import glob
a = [glob("tests/misc/mtcnn/images/*.{}".format(s)) for s in ["jpg", "jpeg", "png"]]
imgs = [i for ai in a for i in ai]
mtcnn = MTCNN()
for img in imgs:... | 476 | 193 |
from ..core import Niche
from .model import Model, simulate
from .env import minigridhard_custom, Env_config
from collections import OrderedDict
DEFAULT_ENV = Env_config(
name='default_env',
lava_prob=[0., 0.1],
obstacle_lvl=[0., 1.],
box_to_ball_prob=[0., 0.3],
door_prob=[0., 0... | 2,723 | 856 |
# SPDX-License-Identifier: GPL-2.0+
# Copyright (c) 2016 Google, Inc
# Written by Simon Glass <sjg@chromium.org>
#
# Entry-type module for Intel Chip Microcode binary blob
#
from binman.etype.blob_ext import Entry_blob_ext
class Entry_intel_cmc(Entry_blob_ext):
"""Entry containing an Intel Chipset Micro Code (CMC... | 704 | 236 |
from model.address import Address
testdata = [
Address(firstname="", lastname="", address="", homephone="", mobile="", workphone="", secondaryphone="",
email="", email2="", email3=""),
Address(firstname="address1", lastname="address1", address="address1",
homephone="address1", mobile="... | 697 | 190 |
from . import views
from django.conf.urls import url
from django.conf.urls.static import static
from django.conf import settings
urlpatterns=[
url(r'^$', views.home,name='home'),
url(r'^award/',views.add_student, name='student'),
url(r'^awards/',views.awards,name='awards'),
url(r'students/',views.my_st... | 447 | 157 |
import os
import tempfile
import string
from bs4 import BeautifulSoup
from shutil import copyfile
from rq_settings import prefix, debug_mode_flag
from app_settings.app_settings import AppSettings
from general_tools.file_utils import write_file, remove_tree, get_files
from converters.converter import Converter
from tx_... | 7,176 | 1,978 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Legacy migration stream information.
Documentation and record structures for legacy migration, for both libxc
and libxl.
"""
"""
Libxc:
SAVE/RESTORE/MIGRATE PROTOCOL
=============================
The general form of a stream of chunks is a header followed by a
body... | 11,764 | 3,664 |
from __future__ import print_function, division, absolute_import
import re
import numpy as np
re_posvel = re.compile(r'position=<(.+),(.+)> velocity=<(.+),(.+)>')
np.set_printoptions(linewidth=1024, edgeitems=1000)
def parse(s):
"""
Parse out the positions and velocities.
"""
match = (re_posvel.sear... | 2,102 | 791 |
from rockstar import RockStar
swift_code = "print('Hello world')"
rock_it_bro = RockStar(days=1900, file_name='hello.swift', code=swift_code)
rock_it_bro.make_me_a_rockstar() | 179 | 69 |
# Copyright (c) OpenMMLab. All rights reserved.
from .eval_hooks import DistEvalIterHook, EvalIterHook
from .inceptions import FID, KID, InceptionV3
from .metrics import (L1Evaluation, connectivity, gradient_error, mse, niqe,
psnr, reorder_image, sad, ssim)
__all__ = [
'mse', 'sad', 'psnr', '... | 476 | 183 |
# -*-coding:utf8;-*-
""" `Regular Expression Search Algorithm`_
After playing with `Thompson's construction`_ in `C`_ and `x86`_, I decided to take
another look in python many years later. Tokenization and conversion to postfix are
lifted almost verbatim from the C implementation apart for the fact they rely on
pytho... | 9,638 | 3,046 |
#!/usr/bin/python
#
# Copyright 2021 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required b... | 2,785 | 850 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from typing import Optional
from pydantic import BaseModel
from epicteller.core.util.enum import CampaignState
class Campaign(BaseModel):
id: int
url_token: str
room_id: int
name: str
description: str
owner_id: int
state: CampaignState
is... | 404 | 137 |
#from django.shortcuts import render
# Create your views here.
from django.http import HttpResponse,HttpResponseRedirect
#from django.template import loader
from django.shortcuts import get_object_or_404,render
from django.urls import reverse
from django.views import generic
from .models import Question, Cho... | 2,206 | 706 |
n,m=map(int,input().split())
mod=10**9+7
sum=(n%mod)*(m%mod)
i=1
j=1
res=0
while j<=n:
res+=(n//j)*j
i+=1
j=i
print((sum-res)%mod) | 152 | 91 |
"""
BinningProcessSketch testing.
"""
# Guillermo Navas-Palencia <g.navas.palencia@gmail.com>
# Copyright (C) 2021
import pandas as pd
from pytest import approx, raises
from optbinning import BinningProcessSketch
from optbinning import OptimalBinningSketch
from optbinning.exceptions import NotSolvedError
from optbi... | 5,103 | 1,903 |
from math import pi, sin, cos
from direct.showbase.DirectObject import DirectObject
from direct.showbase.ShowBase import ShowBase
from direct.gui.DirectGui import *
from direct.interval.IntervalGlobal import *
from panda3d.core import lookAt
from panda3d.core import GeomVertexFormat, GeomVertexData
from panda3d.core i... | 8,798 | 3,073 |
# Copyright 2000-2001, Dalke Scientific Software, LLC
# Distributed under the Biopython License Agreement (see the LICENSE file).
"""Converts a regular expression pattern string into an Expression tree.
This is not meant to be an externally usable module.
This works by using msre_parse.py to parse the pattern. The ... | 8,485 | 2,602 |
# -*- coding: utf-8 -*-
__author__ = ["Junhao Wen", "Simona Bottani", "Jorge Samper-Gonzalez"]
__copyright__ = "Copyright 2016-2018 The Aramis Lab Team"
__credits__ = ["Junhao Wen"]
__license__ = "See LICENSE.txt file"
__version__ = "0.1.0"
__status__ = "Development"
import numpy as np
import pandas as pd
import os
d... | 2,633 | 1,028 |
from flask import current_app
def send_log_message(text):
try:
log = current_app.extensions['sentry'].captureMessage(text)
except:
pass
| 162 | 50 |
#!/usr/bin/env python
import pytest
from blastsight.model.elements.nullelement import NullElement
from blastsight.view.glprograms.shaderprogram import ShaderProgram
from blastsight.view.drawables import GLDrawable
class TestShaderProgram:
@property
def base_program(self):
return ShaderProgram()
... | 1,301 | 374 |
from numpy.random import randint
from core import BeamR, Propagator, SweepDiffractionExecutorR, BeamVisualizer, xlsx_to_df
from tests.diffraction.test_diffraction import TestDiffraction
NAME = 'diffraction_r_vortex'
class TestDiffractionRVortex(TestDiffraction):
def __init__(self, *args, **kwargs):
supe... | 2,102 | 661 |
__author__ = 'mourad'
| 22 | 11 |
# -*- coding: utf-8 -*-
from DB import DB
from wordcloud import WordCloud
import jieba
# class WordCloud(object):
if __name__ == '__main__':
db = DB()
db.connect()
result = db.readAllTitle()
titles = ''
for title in result:
titles += title[0]
words = " ".join(jieba.cut(titles))
... | 506 | 176 |
"""
This module is deprecated and will be removed in version 1.0. Please use :mod:`~granola.breakfast_cereal` instead
"""
from granola.breakfast_cereal import Cereal
from granola.utils import deprecation
class MockSerial(Cereal):
"""
Deprecated version of :class:`~granola.breakfast_cereal.Cereal`. Will be re... | 6,611 | 1,901 |
from declry import site
from declry.apps import Application
class FormacaoAdmin(Application):
list_display = ('nome','modulo','local','data_inicio','data_fim','coordenador')
list_filter = ('data_inicio',)
search_fields = ('nome','modulo','local')
| 261 | 81 |
"""requests_log
Revision ID: 20e98a16ad20
Revises: 8fa4d8f2277c
Create Date: 2019-07-30 13:49:17.702589
"""
import sqlalchemy as sa
from alembic import op
from sqlalchemy.dialects import mysql
# revision identifiers, used by Alembic.
revision = "20e98a16ad20"
down_revision = "8fa4d8f2277c"
branch_labels = None
depen... | 1,998 | 704 |
import numpy as np
import pandas as pd
from pandas import DataFrame, Series
import random
import time
import math
import datetime as dt
import random
import copy
from datetime import datetime
from time import mktime
import os
import json
from functools import cmp_to_key
import numpy as np
import matp... | 7,156 | 3,175 |
#!/usr/bin/env python
# Copyright 2013 Mirantis, 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 a... | 4,654 | 1,226 |
from cmtf import CompressiveTransformer
from cmtf_ar_wrapper import AutoregressiveWrapper
import argparse
import random
import tqdm
import gzip
import numpy as np
import torch
import torch.optim as optim
from torch.nn import functional as F
from torch.utils.data import DataLoader, Dataset
# constants
def parse_args(... | 6,314 | 2,100 |
#!/usr/bin/python3
## template_file.py for cpp-maker in /home/aracthor/programs/projects/cpp-maker
##
## Made by Aracthor
##
## Started on Mon Sep 7 12:03:26 2015 Aracthor
## Last Update Wed Sep 9 10:27:36 2015 Aracthor
##
from files import File
class TemplateFile(File):
def __init__(self, path, project):
... | 1,094 | 348 |
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 19 15:32:04 2016
@author: ibackus
"""
import utils
import randomNormalSnap
import ppdgrid
import analyze
import makeICs
import plot | 179 | 75 |
########################################################################
#
# Defaults for django settings
# - See: https://docs.djangoproject.com/en/dev/ref/settings/
#
########################################################################
import os
import devilry
from .projectspecific_settings import * # noqa
from... | 6,692 | 2,270 |
import write_proof
write_proof.reset()
write_proof.write_all_known_proofs() | 75 | 26 |
import gym
import numpy as np
from context import robolearn_envs
all_envs = gym.envs.registry.all()
robolearn_env_ids = [env_spec.id for env_spec in all_envs
if env_spec.id.startswith('RoboLearn-')]
for env_id in robolearn_env_ids:
print('-'*15)
print("Environment: %s" % env_id)
env ... | 592 | 230 |
import numpy as np
from tqdm import tqdm
from . import mutation, recombination, selection
class GeneticAlgorithm:
"""
Genetic algorithm for TSP.
"""
def __init__(self, lower_bound=-5, upper_bound=5, alpha=0.5, num_iterations=1000, population_size=100, offspring_size=20, mutation_rate=0.2,
... | 7,468 | 2,127 |
from django.apps import AppConfig
class E7gzlyConfig(AppConfig):
name = 'e7gzly'
| 87 | 32 |
import transaction
from pyramid.httpexceptions import HTTPInternalServerError
from pyramid.view import view_config
from pyramid_sacrud.security import (PYRAMID_SACRUD_DELETE,
PYRAMID_SACRUD_UPDATE)
from sacrud.common import pk_to_list
from . import CONFIG_MODELS, PS_TREE_GET_TREE,... | 2,185 | 728 |
'''
Author: Amitrajit Bose
Problem: Facebook HackerCup Qualification Round
'''
with open("Output.txt", "w") as text_file:
testcase=int(input())
for _ in range(testcase):
#entire program will be contained here now
n,k,v=[int(x) for x in input().strip().split()]
citynames=[]
#citydict={}
out=[]
for i in ra... | 1,068 | 495 |
class MaxStack:
def __init__(self):
self.stack = []
self.max_stack = []
def push(self, val):
self.stack.append(val)
if(not self.max_stack or val > self.stack[self.max_stack[-1]]):
self.max_stack.append(len(self.stack) - 1)
def pop(self):
if(not self.stac... | 904 | 341 |
import logging
import argparse
from beat import beat
from definitions import path_log
# LOGGING CONFIGURATION
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s %(message)s',
datefmt='%m/%d/%Y %I:%M:%S %p'
)
logging.root.addHandler(logging.FileHandler(path_log, mode='w', encoding='UTF-8'))
loggin... | 1,635 | 506 |
class Interval(object):
def __init__(self, start_time, end_time):
self.start_time = start_time
self.end_time = end_time
| 141 | 47 |
from __future__ import absolute_import
import os
import pytest
import checkout_sdk
from checkout_sdk.common.common import Address, CustomerRequest, Phone
from checkout_sdk.common.common_four import Product
from checkout_sdk.common.enums import Currency, Country
from checkout_sdk.payments.payment_apm_four import Requ... | 5,678 | 1,646 |
import FWCore.ParameterSet.Config as cms
from DQM.TrackingMonitorSource.pset4GenericTriggerEventFlag_cfi import *
# Clone for TrackingMonitor for all PDs but MinBias ###
from DQM.TrackingMonitor.TrackerCollisionTrackingMonitor_cfi import *
TrackerCollisionTrackMonCommon = TrackerCollisionTrackMon.clone(
genericTr... | 1,877 | 614 |
from Jumpscale import j
from .SSHClient import SSHClient
from .SSHClientParamiko import SSHClientParamiko
from .SSHClientBase import SSHClientBase
class SSHClientFactory(j.baseclasses.object_config_collection_testtools):
__jslocation__ = "j.clients.ssh"
_CHILDCLASS = SSHClientBase
_SCHEMATEXT = _CHILDCLA... | 4,524 | 1,609 |
from collections import MutableMapping as DictMixin
def query(connection, *args):
cursor = connection.cursor()
cursor.execute(*args)
return cursor
class SQLiteDict(DictMixin):
"""A dict facade for an SQLite table"""
def __init__(self, connection, commit=True, **kwargs):
self.connection ... | 2,094 | 654 |
"""
Translates TAXSIM-27 input file to Tax-Calculator tc input file.
"""
# CODING-STYLE CHECKS:
# pycodestyle prepare_tc_input.py
# pylint --disable=locally-disabled prepare_tc_input.py
import argparse
import os
import sys
import numpy as np
import pandas as pd
def main():
"""
High-level logic.
"""
#... | 4,316 | 1,691 |
# ***************************************************************************
# * Copyright (c) 2013 GigaSpaces Technologies Ltd. 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 ... | 1,510 | 426 |
# Generated by Django 3.1.3 on 2020-12-09 13:41
from django.db import migrations, models
import segmentation.models
class Migration(migrations.Migration):
dependencies = [
('segmentation', '0007_segmentedimage_ori_article_name'),
]
operations = [
migrations.AddField(
model_n... | 520 | 164 |
from aws_cdk import (
core,
aws_ec2 as ec2
)
class VpcStack(core.Stack):
def __init__(self, scope: core.Construct, id: str,
vpc_cidr,
**kwargs
) -> None:
super().__init__(scope, id, **kwargs)
# SubnetType.ISOLATED used as we don't want Internet traffic possible for t... | 914 | 299 |
#!/usr/bin/env python
# ===============================================================================
# Copyright (c) 2014 Geoscience Australia
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
... | 112,783 | 37,890 |
# encoding: utf-8
__all__ = ["BotConfig", "BotLoggingConfig"]
from typing import Any, Dict, List, Optional, Union
from lifesaver.config import Config
YES_EMOJI = "\N{WHITE HEAVY CHECK MARK}"
NO_EMOJI = "\N{CROSS MARK}"
OK_EMOJI = "\N{OK HAND SIGN}"
DEFAULT_EMOJIS = {
"generic": {"yes": YES_EMOJI, "no": NO_EMOJ... | 2,266 | 766 |