text string | size int64 | token_count int64 |
|---|---|---|
#########################################################################
#
# perceptron.py - This file is part of the Spectral Python (SPy) package.
#
# Copyright (C) 2001-2014 Thomas Boggs
#
# Spectral Python is free software; you can redistribute it and/
# or modify it under the terms of the GNU General Publ... | 16,914 | 4,859 |
import pandas as pd
import json
from sportsdataverse.dl_utils import download
from urllib.error import URLError, HTTPError, ContentTooShortError
def espn_cfb_teams(groups=None) -> pd.DataFrame:
"""espn_cfb_teams - look up the college football teams
Args:
groups (int): Used to define different division... | 1,075 | 348 |
from typing import List
# Problem #13 [Hard]
# Good morning! Here's your coding interview problem for today.
# This problem was asked by Amazon.
# Given an integer k and a string s, find the length of the longest substring
# that contains at most k distinct characters.
# For example, given s = "abcba" and k = 2,
# ... | 407 | 114 |
import math
import numpy as np
import os
import sys
import csv
import datetime
import pandas as pd
from vnpy.app.cta_strategy.backtesting import BacktestingEngine, OptimizationSetting
from vnpy.app.cta_strategy.base import BacktestingMode
from vnpy.app.cta_strategy import (
CtaTemplate,
TickData,
TradeData... | 3,636 | 1,294 |
def check_days(weekdays, *valid_days, is_valid=True):
from dataclass_property.weekdays_list import Weekdays
if len(valid_days) == 0:
valid_days = list(Weekdays.DAYS)
elif len(valid_days) == 0 and isinstance(valid_days[0], list):
valid_days = valid_days[0]
valid_days = [Weekdays.as_attr... | 4,368 | 1,503 |
from django.core.management import BaseCommand
from thenewboston_node.core.utils.cryptography import generate_key_pair
class Command(BaseCommand):
help = 'Generate signing (private) key' # noqa: A003
def handle(self, *args, **options):
self.stdout.write(generate_key_pair().private)
| 304 | 95 |
#-*- coding: utf-8 -*-
from playhouse.sqlite_ext import SqliteExtDatabase, FTSModel
import sqlite3
from .db_initialize import initialize
from .api import parse, images, stats, status, get_chats, dashboard, delete_original_path, cancel_parse
import os
from .variables import DATASOURCE_NAME
class Routes:
def __... | 1,864 | 560 |
#!/usr/bin/python
import sys
if len(sys.argv) > 2 or len(sys.argv) < 2:
print sys.argv[0] + "accepts 1 argument"
sys.exit(1)
accounts = {}
with open(sys.argv[1],'r') as f:
for i in f:
temp = i.split(" ", 1)
accounts[temp[0]] = temp[1]
accounts.keys().sort()
print "ID Name"
for i in accounts:
print str(i... | 347 | 158 |
import aiohttp
import importlib
routes = {"/": "index",
"/users/{username}": "user",
"/rankings": "rankings",
"/level/{levelname}": "level",
"/search": "search"}
def add_all_routes(app: aiohttp.web.Application):
for route, modulename in routes.items():
modulepath = ... | 501 | 152 |
def removeDuplicates(self, nums: List[int]) -> int:
p = 0
for i in range(len(nums)):
if not nums[i] in nums[:i]:
nums[p] = nums[i]
p += 1
return p
"""
Just iterating through every element and appending every first unique element to head of the list... | 415 | 123 |
# Tile current selection with pattern inside selection.
# Author: Andrew Trevorrow (andrew@trevorrow.com), March 2006.
# Updated to use exit command, Nov 2006.
# Updated to handle multi-state patterns, Aug 2008.
from glife import *
import golly as g
selrect = rect( g.getselrect() )
if selrect.empty: g.exit("There is ... | 3,967 | 1,386 |
# -*- coding: utf-8 -*-
"""Process data to xlsx.
Here,
the input data from the previous three steps is combined and written to XLSX.
The GTEx data is merged BioMart data using an outer merge,
so as to keep all entries.
Then,
the MANE data is added using a left merge,
so as to only keep the data from the GTEx query.
""... | 968 | 355 |
import argparse
import logging
import os
import sys
from src.constants import GSLIST_CONFIGS, GAMESPY_PRINCIPALS
from src.serverlisters import GameSpyServerLister
parser = argparse.ArgumentParser(description='Retrieve a list of game servers for GameSpy-based games '
'and w... | 2,943 | 909 |
from .cs_widget import CornerstoneWidget, CornerstoneToolbarWidget
from .utils import get_bbox_handles
from ._version import get_versions
def _jupyter_nbextension_paths():
return [{
'section': 'notebook',
'src': 'static',
'dest': 'cornerstone_widget',
'require': 'cornerstone_widget... | 398 | 126 |
from uuid import uuid4
import urllib
from django.core.urlresolvers import reverse
from go.base.tests.helpers import GoDjangoTestCase, DjangoVumiApiHelper
from go.channel.views import get_channel_view_definition
class TestChannelViews(GoDjangoTestCase):
def setUp(self):
self.vumi_helper = self.add_helpe... | 4,872 | 1,549 |
import sys
from chardet.universaldetector import UniversalDetector
def parse_args(INFO):
MENU = { \
"OBF":"Obfuscated algorithm file", \
"OF":"Output file (Not implemented)"
}
for NUM in range(1,len(sys.argv)):
CURR = sys.argv[NUM]
if CURR[:2] == "--":
if CURR[2:] == "help":
print_dict(MENU)... | 4,715 | 2,321 |
from django.db import models
from orders.app import order_app
from satchless.contrib.payment.django_payments_provider.models import DjangoPaymentsPayment
class Payment(DjangoPaymentsPayment):
order = models.OneToOneField(order_app.Order,
related_name='paymentvariant')
| 309 | 83 |
import os
import subprocess
import threading
import time
import json
import sublime
import sublime_plugin
from .logger import log
from . import json_helpers
from . import global_vars
# queue module name changed from Python 2 to 3
if int(sublime.version()) < 3000:
import Queue as queue
else:
import queue
cla... | 9,184 | 2,456 |
# Command dictionary, used for the help command and the ? command
cmd_dict = {
"help": "Show help.",
"?": "Get help on a command. 1 argument required: name of the command. Example: \"? dec\"",
"dec": "Convert a number to decimal. 2 arguments required: one is the number itself, second is the base.",
... | 3,980 | 1,124 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
('auth', '0006_require_contenttypes_0002'),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),... | 1,240 | 389 |
import pandas as pd
import numpy as np
from sklearn.preprocessing import LabelEncoder
df = pd.read_csv('train(2).csv')
df2 = df[["KitchenQual" , "BldgType"]]
#LAbel Encoder
le = LabelEncoder()
data = le.fit_transform(df2["BldgType"])
print(data)
df2["BldType_l_enc"] = data
#count number of class in a column
pr... | 543 | 220 |
#!/usr/bin/python3
# Exceptions
# CodeWriter21
class APIConfigNotFoundException(Exception):
pass
class APIConfigDamagedException(Exception):
pass
class NoBotConfigFoundException(Exception):
pass
class NoBotEnabledConfigFoundException(Exception):
pass
class ButtonsNotSetException(Exception):
pass | 306 | 91 |
#!/usr/local/bin/python
# -*- coding: utf-8 -*-
#
# Copyright 2018 Mattia Benedetti
# All rights reserved.
#
# Author: Mattia Benedetti
"""
- FUNCTIONs -
Calculate the area of a circle with radius input by user
-> run on pront command <-
Note : -1 to EXIT!
"""
from math import pi
def circle_ar... | 493 | 180 |
# Copyright (c) 2013 Shotgun Software Inc.
#
# CONFIDENTIAL AND PROPRIETARY
#
# This work is provided "AS IS" and subject to the Shotgun Pipeline Toolkit
# Source Code License included in this distribution package. See LICENSE.
# By accessing, using, copying or modifying this work you indicate your
# agreement to t... | 1,143 | 335 |
from ..abstract import ErdReadWriteConverter
from ..primitives import *
from gehomesdk.erd.values.ac import *
class ErdAcTargetTemperatureConverter(ErdReadWriteConverter[int]):
def erd_decode(self, value: str) -> int:
try:
return erd_decode_int(value)
except:
return 86
... | 401 | 128 |
#
# Copyright (c) 2008-2015 Thierry Florac <tflorac AT ulthar.net>
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRAN... | 3,533 | 1,059 |
from django.test import TestCase
from django.contrib.auth.models import User
from django.core.files.uploadedfile import SimpleUploadedFile
from django.urls import reverse
from Picturedom.photo.models import Category, Photo
class TestCategoryPhotos(TestCase):
def setUp(self):
self.user = User.objects.creat... | 1,543 | 440 |
#!/usr/bin/env python
def top_three_avg(grade1, grade2, grade3, grade4):
"""
:param grade1: number
:param grade2: number
:param grade3: number
:param grade4: number
:return: number
"""
total = grade1 + grade2 + grade3 + grade4
top_three = total - min(grade1, grade2, grade3, grade4)... | 418 | 170 |
from collections import Counter
import string
print(string.digits)
def get_char_count(text):
text = str(text)
# letters = {}
# for i in text:
# if i in letters:
# letters[i] += 1
# else:
# letters[i] = 1
letters = Counter(text)
print(letters)
return lette... | 1,062 | 397 |
#!/usr/bin/env python
import logging
import os
import sys
from django.core.management import execute_from_command_line
if 'DJANGO_SETTINGS_MODULE' not in os.environ:
if len(sys.argv) > 1 and sys.argv[1] == 'test':
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings_test'
else:
os.environ.setdefau... | 2,441 | 814 |
from typing import Callable, Dict, Tuple, Text
from recommenders.datasets import Dataset
import numpy as np
import tensorflow as tf
import tensorflow_recommenders as tfrs
from pathlib import Path
SAVE_PATH = Path(__file__).resolve().parents[1] / "weights"
class RankingModel(tfrs.models.Model):
def __init__(
... | 1,636 | 508 |
"""
Utility Functions
"""
### From the Python Cookbook
## Generate a human readable 'random' password
## password will be generated in the form 'word'+digits+'word'
## eg.,nice137pass
## parameters: number of 'characters' , number of 'digits'
## Pradeep Kishore Gowda <pradeep at btbytes.com >
## License : GPL
## Da... | 1,687 | 601 |
"""
See https://github.com/deepset-ai/haystack/issues/955 for further context
"""
import os
import logging
from copy import deepcopy
from typing import Dict, Generator, List, Optional, Union
import numpy as np
from elasticsearch.helpers import bulk, scan
from tqdm.auto import tqdm
from haystack.utils import get_batche... | 32,951 | 9,027 |
import subprocess
import os
from get_answer import Fetcher
class Commander:
def __init__(self):
self.confirm = [
"yes", "affimartive", "si", "sure", "do it", "yeah", "confirm"
]
self.cancel = [
"no", "negative", "negative soldier", "don't", "wait", "cancel"
... | 886 | 268 |
#!/usr/bin/env python
import re
regex = "^(#(?P<ClaimId>[0-9]{0,}) @ (?P<FromLeftEdge>[0-9]{0,}),(?P<FromTopEdge>[0-9]{0,}): (?P<Width>[0-9]{0,4})x(?P<Height>[0-9]{0,4}).*)$"
class Claim(object):
def __init__(self, line):
match = re.search(regex, line)
self.ClaimId = match.group('ClaimId')
... | 2,073 | 692 |
from django import forms
from . import models
class CourseItemForm(forms.ModelForm):
class Meta:
model = models.CourseItem
fields = [
"published",
"episode_url",
"episode",
"episode_note",
"episode_title",
"episode_archive",
... | 736 | 207 |
from math import log
import pickle
import numpy
from numpy import array
from math import log10
# beam_search
def beam_search(data: numpy.array, k: int) -> numpy.array:
sequences = [[list(), 0.0]]
for row in data:
all_candidates = list()
for i in range(len(sequences)):
seq, score = ... | 3,962 | 1,498 |
import time
import os
for i in range(50):
print("Update data.")
with open("DATA", "wt") as f:
f.write("DATA, ")
f.write( str(time.time()) )
time.sleep(2)
| 176 | 67 |
from django.conf import settings
import graphene
from . import base
class ProtectorBackend(base.ProtectorBackend):
def __init__(self, *args, **kwargs):
if hasattr(settings, "GRAPHENE_PROTECTOR_DEPTH_LIMIT"):
kwargs.setdefault(
"depth_limit", settings.GRAPHENE_PROTECTOR_DEPTH_... | 1,125 | 361 |
import cv2
face_data = cv2.CascadeClassifier("haarcascade_frontalface_default.xml")
cap = cv2.VideoCapture(0)
while True:
ret, img = cap.read()
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_data.detectMultiScale(gray, 1.3, 5)
for x,y,w,h in faces:
cv2.rectangle(img, (... | 488 | 229 |
import torch
import torch.nn as nn
import matplotlib.pyplot as plt
import torch.nn.functional as F
from sklearn import metrics
import seaborn as sns
from torch_sparse import spspmm
import numpy as np
from src.visualization.visualize import Visualization
from src.features.link_prediction import Link_prediction
class B... | 12,446 | 4,710 |
import pyautogui
import time
pyautogui.click(300, 400)
pyautogui.hotkey('ctrl', 'f')
time.sleep(.200)
pyautogui.typewrite('email')
time.sleep(.200)
pyautogui.locateOnScreen('mail.png')
| 185 | 85 |
from pygame.display import set_mode, update, set_caption
from pygame.time import Clock
from pygame import init, quit, QUIT
from pygame.event import get as events
from GameStage import GameStages
from sys import exit as end
class window:
def __init__(self):
init()
Name = "Title"
... | 1,263 | 353 |
import inspect
import unittest
from avaland import sources
from avaland import MusicBase
from avaland.search import SearchResult
def test_search(self):
query = self.source.search.test
source = self.source({}).search(query)
self.assertIsInstance(source, SearchResult)
def test_artist_id(self):
artist... | 1,268 | 431 |
def save(self, as_async=False, callback=None, **kwargs):
""" """
if 'async' in kwargs.keys() and not as_async:
as_async = kwargs['async']
super(NUMe, self).save(as_async=as_async, callback=callback, encrypted=False)
| 236 | 80 |
from pymongo import MongoClient
import config as config
db_conn = MongoClient(config.get_setting("mongo-db-conn", "null"))
db = db_conn.restberry_api
coll_trans = db.transactions
coll_accounts = db.accounts
def stringify_ids(docs):
"""
Expects docs to be a list of documents, not a cursor.
"""
for doc... | 382 | 128 |
from flask import Flask, render_template, url_for, request, redirect, flash, jsonify
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
import datetime
from database_setup import Base, Restaurant, MenuItem
app = Flask(__name__)
engine = create_engine('sqlite:///restaurantmenu.db')
Base.metada... | 3,847 | 1,269 |
""" Graph algorithms module.
"""
from .graph import Graph, Node
from .digraph import DiGraph, DiNode
from .maskable_graph import MaskableGraph
__all__ = ('Graph', 'Node', 'DiGraph', 'DiNode', 'MaskableGraph')
| 213 | 69 |
# Copyright (c) 2020 The Regents of the University of Michigan
# All rights reserved.
# This software is licensed under the BSD 3-Clause License.
"""Abstract shape definitions used to read/write particle shapes."""
import json
import logging
import numpy as np
__all__ = [
'FallbackShape',
'Shape',
'Spher... | 19,122 | 6,111 |
# coding: utf-8
"""
ORR API Documentation
The main ORR documentation is located at: https://mmisw.org/orrdoc/ __Please note__: - The ORR API is approaching a stable version but is still work in progress. Please [let us know](https://github.com/mmisw/mmiorr-docs/issues) if you have any questions or sugges... | 24,174 | 5,811 |
import math
from .format import format_timer, pad_middle, pad_right, pad_left
from . import format
from .activities import Activity, OwnedActivities
DefaultTextCardWidth = 65
_RightColumnWidth = 14
def progress_bar(
width: int,
progress: float,
end_char: str = '|',
fill_char: str = '-',
empty_cha... | 7,146 | 2,565 |
"""
This module contains the ClientSharedObject, which is shared between the client and all objects it generates.
"""
from __future__ import annotations
from typing import TYPE_CHECKING, Optional
from .requests import Requests
from .url import URLGenerator
if TYPE_CHECKING:
from ..client import Client
fro... | 1,831 | 436 |
#!/usr/bin/env python
# coding: utf-8
# In[ ]:
import datetime as dt
import pandas as pd
import numpy as np
import sqlalchemy
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm import Session
from sqlalchemy import create_engine, func
from flask import Flask, jsonify
# Establishing a connection
e... | 3,281 | 1,061 |
import tensorflow as tf
from tqdm import tqdm
from DataProcessing import DataProcessing
# Based on MIT's introduction to Deep Learning course
class Model:
"""
LSTM model for learning from the data and generating a conversation.
The model recognizes all different possible words and map them to a number... | 6,330 | 1,761 |
# -*- coding: utf-8 -*-
import datetime
from django.conf import settings
from django.contrib.auth.models import User
from django.contrib.sites.models import Site
from ionyweb.website.models import WebSite
from ionyweb.page.models import Page
from ionyweb.page_app.page_agenda.models import PageApp_Agenda, Event
from ... | 1,989 | 586 |
"""
pygame-menu
https://github.com/ppizarror/pygame-menu
TEST DECORATOR
Decorator API.
"""
__all__ = ['DecoratorTest']
from test._utils import MenuUtils, surface, TEST_THEME, BaseTest
import copy
import pygame
import pygame_menu
import timeit
# Configure the tests
TEST_TIME_DRAW = False
class DecoratorTest(BaseTe... | 12,256 | 4,677 |
#!python3
# -*- coding:utf-8 -*-
import numpy as np
import pandas as pd
import urllib.parse
'''
This soure code is a sample of using pandas library.
Reading from external file to DataFrame.
'''
#Method of CSV Reading
df = pd.read_csv("./201704health.csv", encoding="utf-8")
print("read csv")
print(df.head(4))
prin... | 1,380 | 477 |
# -*- coding: utf-8 -*-
import os
import re
import shutil
import sys
import time
from datetime import datetime as dtime
from datetime import timedelta as tdelta
from hashlib import md5, sha1, sha256
from dateutil.parser import parse as dtparser
# Some RegExes
re_md5 = re.compile("^([0-9]|[a-f]){32}$", re.I)
re_sha1 = ... | 8,279 | 3,029 |
# (C) Copyright 1996- ECMWF.
#
# This software is licensed under the terms of the Apache Licence Version 2.0
# which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
# In applying this licence, ECMWF does not waive the privileges and immunities
# granted to it by virtue of its status as an intergovernment... | 12,364 | 3,570 |
from navygem.settings import BASE_DIR
import glob
import json
import os
class ResourceRegistrarMeta(type):
file = __file__
def __new__(cls, name, parents, dct):
if 'types' in dct:
files = {}
for root, _, filenames in os.walk(os.path.dirname(os.path.realpath(cls.file))):
... | 1,726 | 512 |
inp = map(int, [input() for _ in range(3)])
square = sorted([i ** 2 for i in inp], reverse=True)
if square[0] == sum(square[1:]):
print('YES')
else:
print('NO')
| 171 | 70 |
from copy import deepcopy
import torch
from graph_nets.data_structures.edge import Edge
from graph_nets.functions.aggregation import AvgAggregation, MaxAggregation
from graph_nets.block import GNBlock
from graph_nets.data_structures.graph import Graph
from torch import nn, Tensor
from graph_nets.functions.update impo... | 4,412 | 1,467 |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.29 on 2020-10-28 14:32
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('hs_core', '0053_auto_20200826_1629'),
]
operations = [
migrations.AlterFie... | 620 | 215 |
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import networkx as nx
from matplotlib._color_data import BASE_COLORS
from nxviz.api import CircosPlot
def save_csv(name, data, columns, index):
saving = pd.DataFrame(data=data,columns=columns,index=index)
saving.to_csv(name)
d... | 3,337 | 1,357 |
import torch
import os.path
import numpy as np
import pandas as pd
from util import preprocess
from datasets import load_file
from datasets.basic_dataset import BasicDataset
class SingleFileDataset(BasicDataset):
"""
A dataset class for single file paired omics dataset.
The data should be two single files... | 4,925 | 1,528 |
import logging
formatting = "%(levelname)s: " \
"%(asctime)s -> " \
"%(name)s - " \
"line %(lineno)d: " \
"%(message)s"
def add_stream_handler(logger: logging.Logger):
formatter = logging.Formatter(formatting)
handler = logging.StreamHandler()
handler.... | 416 | 131 |
from pyrogram import Client, filters
from pyrogram.types import Message
from db import functions as db
@Client.on_message(filters.private, group=-1)
async def check_chat(bot: Client, message: Message):
chat_id = message.chat.id
chat_type = message.chat.type
if not db.chat_exists(chat_id, chat_type):
... | 401 | 134 |
from django.db import models
class Inventory(models.Model):
for_sale = models.BooleanField(default=True)
price = models.FloatField(null=False)
digital_book = models.ForeignKey(
to='digital_books.digital_book', on_delete=models.CASCADE, default=0
)
class Meta:
verbose_name = 'Invento... | 364 | 120 |
import sys
sys.path.append('/home/user/Desktop/app') #/home/user/Desktop/app
import sys
from fastapi.testclient import TestClient
from test_database import test_engine, override_get_db
from app.main import app, pokemon, pokemon_type, user, team
from app.routers.pokemon import get_db
pokemon.Base.metadata.create_all(te... | 1,004 | 347 |
class InterfaceFilter:
def __init__(self, *args, **kwargs):
pass
def get_interfaces(self, emulation_node_x, emulation_node_y):
"""
Attributes
----------
emulation_node_x: EmulationNode
emulation_node_y: EmulationNode
Returns
-------
ge... | 1,544 | 456 |
import unittest
from mlapi.facet_extractor import FacetExtractor
from definitions import Definitions
from pathlib import Path
class TestFacetExtractor(unittest.TestCase):
TEST_FILE_A = Path(Definitions.ROOT_DIR + "/test/test_files/facets/facet_extraction_test_file_a.json")
TEST_FILE_B = Path(Definitions.ROOT_... | 1,490 | 552 |
# SQL Module
import MySQLdb
def TEST_RUN():
from config.confmain import dbconnect
db = dbconnect()
db[0].close()
def get_users(db):
get_users = "SELECT id FROM users"
db[1].execute(get_users)
return [item[0] for item in db[1].fetchall()]
def add_user(db, user, rank):
query = "INSERT INT... | 1,782 | 676 |
#!/usr/bin/python3
class Thing(object):
"""
Thing class
Attributes:
thing_type -- Thing type
symbol -- Symbol to print in terminal visualizers
bg_color -- Background color in terminal visualizers
fg_color -- Foreground color in terminal visualizers
pixel_color -- Pixel color for pixel... | 913 | 275 |
#!/usr/bin/env python
import os
def get_hash(path: str):
hashpath = os.path.dirname(path)
return os.path.basename(hashpath)
def get_cid(path: str):
idpath = os.path.dirname(os.path.dirname(path))
cidstr = os.path.basename(idpath)
cid = int(cidstr.replace('id1', '').replace('id0', ''))
return... | 1,306 | 413 |
import os
import yaml
import click
from orpheus.core.executor import Executor
from orpheus.core.user_control import UserManager
from orpheus.core.orpheus_exceptions import BadStateError, NotImplementedError, BadParametersError
from orpheus.core.orpheus_sqlparse import SQLParser
from db import DatabaseManager
class Co... | 9,428 | 2,872 |
import time
import os
import logging
import compas_slicer.utilities as utils
from compas_slicer.pre_processing import move_mesh_to_point
from compas_slicer.slicers import PlanarSlicer
from compas_slicer.post_processing import generate_brim
from compas_slicer.post_processing import generate_raft
from compas_slicer.post... | 6,150 | 1,511 |
"""
Define the implementation for Genre.
Enums have been added to Python 3.4 as described in PEP 435. It has also been
backported to 3.3, 3.2, 3.1, 2.7, 2.6, 2.5, and 2.4 on pypi.
Please install:
$> pip install enum34
@created_at 2015-05-16
@author Exequiel Fuentes Lettura <efulet@gmail.com>
"""
from enum import ... | 566 | 235 |
# coding:utf-8
# --author-- lanhua.zhou
from __future__ import print_function
import logging
from qtpy import QtWidgets, QtGui, QtCore
import zfused_api
import zfused_maya.core.record as record
import zfused_maya.core.resource as resource
import zfused_maya.widgets.widgets as widgets
from . import assetlistmodel
fr... | 2,809 | 907 |
import csv
import os, os.path
import sys
import numpy
from PyQt4.QtCore import *
from PyQt4.QtGui import *
if __name__ == "__main__":
import os, sys
projectpath=os.path.split(os.path.abspath(__file__))[0]
sys.path.append(os.path.join(projectpath,'AuxPrograms'))
from fcns_math import *
from fcns_io import ... | 12,275 | 3,908 |
# Copyright 2019 Elasticsearch BV
#
# 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 applicabl... | 2,467 | 828 |
import logging
import urllib.parse as urlparse
from urllib.parse import parse_qs
from rest_framework.exceptions import ValidationError
from rest_framework.pagination import CursorPagination
from rest_framework.response import Response
logger = logging.getLogger(__name__)
class LinkHeaderPagination(CursorPagination)... | 2,108 | 599 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
sys.path.append('/home/adam/wikt/pywikipedia')
#sys.path.append('/home/alkamid/wikt/pywikipedia')
import pywikibot
from pywikibot import Category
from pywikibot import pagegenerators
import re
from pywikibot import xmlreader
from klasa import *
def main():
dat... | 1,336 | 466 |
#!/usr/bin/env python
"""
@package mi.dataset.parser.flort_kn__stc_imodem
@file marine-integrations/mi/dataset/parser/flort_kn__stc_imodem.py
@author Emily Hahn
@brief Parser for the FLORT_KN__STC_IMODEM dataset driver (both recovered and telemetered)
Release notes:
initial release
"""
__author__ = 'Emil... | 3,901 | 1,386 |
c = get_config()
#Export all the notebooks in the current directory to the sphinx_howto format.
c.NbConvertApp.notebooks = ['Untitled.ipynb']
c.NbConvertApp.export_format = 'notebook'
#c.NbConvertApp.writer = 'stdoutwriter'
c.Exporter.default_preprocessors = ['kyper.nbconvert.preprocessors.coalesce_streams', 'kyper.nb... | 834 | 284 |
#!/usr/bin/env python
# coding: utf-8
import os
import sys
import re
import numpy as np
import pandas as pd
def extract_file(logfile, max_epoch=40):
with open(logfile) as infp:
pat = re.compile(r"Epoch = ([0-9]+) \| EM = ([0-9]+\.[0-9]+) \| F1 = ([0-9]+\.[0-9]+)")
res = []
for line in infp... | 962 | 360 |
from contextlib import closing
import pytest
import sqlalchemy
from tests.conversion.converters.inside_worker_test.conftest import slow
international_text_strings = [
('ascii', 'some normal ascii', 'some normal ascii'),
('umlaut', 'öäüüäüö', 'öäüüäüö'),
('special_chars', "*+?'^'%ç#", "*+?'^'%ç#"),
('... | 1,332 | 538 |
from django.db import models
class StockBasic(models.Model):
symbol = models.IntegerField()
name = models.CharField(max_length=150)
capital = models.IntegerField()
industry = models.CharField(max_length=150)
listed_date = models.DateField()
class StockPrice(models.Model):
date = models.Dat... | 979 | 290 |
# Copyright 2010-2018 Amazon.com, Inc. or its affiliates. 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. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file ac... | 1,123 | 382 |
from wordlistools.helpertest import AsStdinWordlist, AsWordlist, runtest
def test_simple():
runtest("sort", args=(AsStdinWordlist(["a", "b"]),), ret=AsWordlist(["a", "b"]))
runtest("sort", args=(AsStdinWordlist(["b", "a"]),), ret=AsWordlist(["a", "b"]))
def test_multiple_wordlists():
runtest(
"... | 727 | 290 |
# -*- coding: utf-8 -*-
import re
from ..base.decrypter import BaseDecrypter
class SexuriaCom(BaseDecrypter):
__name__ = "SexuriaCom"
__type__ = "decrypter"
__version__ = "0.15"
__status__ = "testing"
__pyload_version__ = "0.5"
__pattern__ = r"http://(?:www\.)?sexuria\.com/(v1/)?(Pornos_Kos... | 5,305 | 1,772 |
"""Script to make RDKit.DotNetWrapper.
Notes:
This is developed with rdkit-Release_2021_09_4.
"""
from enum import Enum
import argparse
import glob
import logging
import os
import platform
import re
import shutil
import subprocess
import sys
import typing
import xml.etree.ElementTree as ET
from os import PathLike
... | 62,700 | 21,136 |
import numpy as np
import pandas as pd
import os
from PIL import Image
from wordcloud import WordCloud, STOPWORDS, ImageColorGenerator
import matplotlib.pyplot as plt
import seaborn as sns
class GraphGenerator():
"""
A class that generates graphs to visualize data
"""
def create_wordcloud(self, freq_di... | 5,624 | 1,707 |
import subprocess
import requests
import tempfile
import tarfile
import shutil
import sys
import os
if os.name != "nt":
print("Error: Can only build pillow-simd on a Windows system")
repo_url = "https://api.github.com/repos/uploadcare/pillow-simd/tags"
tarball_url = requests.get(repo_url).json()[0]["tarball_url"]... | 2,734 | 1,009 |
"""add ambiguous affiliation flag
Revision ID: 52b38830e4f1
Revises: None
Create Date: 2014-08-23 20:08:30.702574
"""
# revision identifiers, used by Alembic.
revision = '52b38830e4f1'
down_revision = None
from alembic import op # NOQA
import sqlalchemy as sa # NOQA
def upgrade():
op.add_column(
'pu... | 559 | 224 |
#configure DSN based on the velocities of the commands
import configparser
import os
import time
import tensorflow as tf
import subprocess
import numpy as np
import cv2
import sys
import math
import matplotlib.pyplot as plt
sys.path.append("../coppelia_sim")
from API_coppeliasim import CoppeliaSim
from PIL import Ima... | 7,118 | 2,467 |
import discord
import asyncio
import sys
import random
import aiohttp
token = sys.argv[1]
tokenno = sys.argv[2]
voice_id = sys.argv[3]
useproxies = sys.argv[4] # proxies for voice chats smh
if useproxies == 'True':
proxy_list = open("proxies.txt").read().splitlines()
proxy = random.choice(proxy_... | 1,012 | 371 |
"""
The dataset can be downloaded from: https://grouplens.org/datasets/movielens/100k/
"""
# Importing Libraries
import pandas as pd
import numpy as np
# Step 1: Loading the dataset into python
# Loading users file
"""
This information is from the read me doc of the dataset
u.user -- Demographic information about... | 4,912 | 1,575 |
# 266. Palindrome Permutation
#
# Given a string, determine if a permutation of the string could form a palindrome.
#
# Example 1:
#
# Input: "code"
# Output: false
#
# Example 2:
#
# Input: "aab"
# Output: true
#
# Example 3:
#
# Input: "carerac"
# Output: true
# https://leetcode.com/articles/palindrome-permutation/
... | 673 | 245 |
#!/usr/bin/env python3
from distutils.core import setup
setup(name='Extremely Randomized Trees',
version='0.2',
description='Implementation of Extremely Randomized Trees',
author='Rodrigo',
author_email='allrod5@gmail.com',
packages=['extra_trees.ensemble', 'extra_trees.tree']
)
| 312 | 99 |
import os
import logging
import medium
from markdownify import markdownify as md
from bs4 import BeautifulSoup as bs
import requests
MAX_FILENAME_LENGTH = 30 # Ignores date and extension, e.g. 2020-10-31<-- 30 characthers -->.md
FORBIDDEN_FILENAME_CHARS = "*?"
DEFAULT_BACKUP_DIR = "backup"
DEFAULT_FORMAT = "html"
c... | 10,522 | 2,987 |