text string | size int64 | token_count int64 |
|---|---|---|
import re
import datetime
def sub(message, regex):
regex=re.split("(?<!\\\\)/",regex)
if len(regex)>3:
regex[3] = regex[3].strip()
if not regex[3]:
count = 1
elif "g" in regex[3]:
count = 0
elif regex[3].isdigit():
count = int(regex[3])
el... | 2,098 | 743 |
s = 'abc'; print(s.isupper(), s)
s = 'Abc'; print(s.isupper(), s)
s = 'aBc'; print(s.isupper(), s)
s = 'abC'; print(s.isupper(), s)
s = 'abc'; print(s.isupper(), s)
s = 'ABC'; print(s.isupper(), s)
s = 'abc'; print(s.capitalize().isupper(), s.capitalize())
| 257 | 118 |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
import unittest
from pyes import scriptfields
class ScriptFieldsTest(unittest.TestCase):
def test_scriptfieldserror_imported(self):
self.assertTrue(hasattr(scriptfields, 'ScriptFieldsError'))
def test_ignore_failure(self):
fields =... | 562 | 174 |
"""FlowMeter URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-bas... | 1,049 | 336 |
################################################################################
######## Google Cloud Platform Utilities ########
################################################################################
#Importing required libraries and dependancies
import numpy as np
import pan... | 15,033 | 4,444 |
# import libraries
import time
import datetime
from argparse import ArgumentParser
from datetime import date
import re
import json
import numpy as np
import pandas as pd
import django
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_c... | 6,033 | 1,739 |
from django.urls import path
#from api.views import company_list, company_details, company_vacancies, vacancies_list, vacancy_detail
from api.views import company_list, company_details
urlpatterns = [
path('companies/', company_list),
path('companies/<int:company_id>/', company_details),
#path('companies/<... | 468 | 166 |
from logging import getLogger
from lottery_config import LotteryConfig
from main import draw_lottery
logger = getLogger()
def test_draw_lottery():
for test_count in range(10000):
draw_results = draw_lottery()
logger.info(f'Test #{str(test_count).ljust(4)} Draw Results : {draw_results}')
... | 904 | 261 |
import requests
import io
import dask
from bs4 import BeautifulSoup as BS
import nltk
import pandas
import numpy as np
def News(ticker):
B = BS(requests.get(f"https://www.wsj.com/market-data/quotes/{ticker}", headers={'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) ... | 1,308 | 509 |
from pytest import raises
from glom import glom, Path, S, T, A, PathAccessError, GlomError, BadSpec
def test_list_path_access():
assert glom(list(range(10)), Path(1)) == 1
def test_path():
_obj = object()
target = {'a': {'b.b': [None, {_obj: [None, None, 'd']}]}}
assert glom(target, Path('a', 'b.b... | 6,587 | 2,506 |
from dissononce.dh import private
class PrivateKey(private.PrivateKey):
pass
| 83 | 25 |
from pygame import *
from random import randint
import json
#fonts and captions
font.init()
font1 = font.SysFont('Comic Sans', 60)
win = font1.render('Dam you actually poggers', True, (255, 255, 255))
lose = font1.render('Yeah you suck, you lost', True, (180, 0, 0))
font2 = font.SysFont('Comic Sans', 36)
ammo_lose ... | 6,850 | 2,581 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import logging
from ...utils.database import Generic_Table
class ROAs_Table(Generic_Table):
"""Announcements table class"""
__slots__ = []
name = "roas"
columns = ["asn", "prefix", "max_length", "created_at"]
def _create_tables(self):
"""... | 863 | 268 |
# 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... | 5,880 | 1,670 |
from CodeGenerator import *
class MonkeyInterpreter:
def __init__(self, prog, filename="", identify="", base_path=""):
self.prog = prog
self.func_table = {}
self.code_str = ''
self.filename = filename
self.url = ''
self.driver = ''
self.indent = 0
self... | 4,665 | 1,442 |
"""Matplotlib Density Comparison plot."""
import matplotlib.pyplot as plt
import numpy as np
from ...distplot import plot_dist
from ...plot_utils import _scale_fig_size
from . import backend_kwarg_defaults, backend_show
def plot_dist_comparison(
ax,
nvars,
ngroups,
figsize,
dc_plotters,
legen... | 3,619 | 1,111 |
"""empty message
Revision ID: 1a869ac514c
Revises: 52887f8e06b
Create Date: 2015-09-29 11:06:57.293537
"""
# revision identifiers, used by Alembic.
revision = '1a869ac514c'
down_revision = '52887f8e06b'
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated by Alembic - plea... | 1,027 | 397 |
##############################################################################
#
# Copyright (c) 2003-2018 by The University of Queensland
# http://www.uq.edu.au
#
# Primary Business: Queensland, Australia
# Licensed under the Apache License, version 2.0
# http://www.apache.org/licenses/LICENSE-2.0
#
# Development unti... | 6,213 | 2,196 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
import re
try:
from setuptools import setup, find_packages
except ImportError:
from distutils.core import setup, find_packages
# Backwards compatibility for Python 2.x
try:
from itertools import ifilter
filter = ifilter
except Impor... | 2,708 | 828 |
from sys import argv
G = [
"00000000",
"11010010",
"01010101",
"10000111",
"10011001",
"01001011",
"11001100",
"00011110",
"11100001",
"00110011",
"10110100",
"01100110",
"01111000",
"10101010",
"00101101",
"11111111",
]
errors = 0
def from_hamming(bit... | 1,791 | 745 |
import unittest
from kfdata.attributes import Attribute, NumberAttribute, BooleanAttribute
class AttributeTests(unittest.TestCase):
def setUp(self):
self.attribute = Attribute(name='firstName', is_indexed=True, is_optional=False)
def test_creation(self):
self.assertEqual(self.attribute.name,... | 1,520 | 448 |
import threading # 多线程模块
import queue # 队列模块
import requests
import time
import random
import json
import os
import re
import traceback
from urllib.parse import quote
from config import fakeVisitorCount
from config import startUserID
from config import spreadToken
from config import UAs
from config import province
from... | 8,589 | 2,792 |
import os
from django.test import TransactionTestCase
from django.contrib.auth.models import Group
from django.conf import settings
from hs_core import hydroshare
from hs_core.models import BaseResource
from hs_core.hydroshare.utils import resource_file_add_process, resource_file_add_pre_process
from hs_core.views.ut... | 5,973 | 1,677 |
# -*- coding: utf-8 -*-
import pytest
def test_camel_case_aliases(testdir):
testdir.makepyfile('''
import logging
logger = logging.getLogger(__name__)
def test_foo(caplog):
caplog.setLevel(logging.INFO)
logger.debug('boo!')
with caplog.atLevel(logging... | 2,310 | 754 |
import click
from trello.client import Client
key = "0581b1db0a42258051a8a25fb301e247"
token = "e6985b1a4afdfb4168814ca486e76ff704e171d5751ce9db8c96731f8b1cc0cb"
client = Client(key, token)
show_help = """ \n
TEXT=all show all boards.\n
TEXT=first show first board.\n
TEXT=last show last board.\n
"""
@click.command... | 968 | 378 |
from sqlite3 import dbapi2 as sqlite3
from libliquor import Actuator,Ranger,Mixer
config = dict(
DEBUG=True,
DATABASE='/tmp/flaskr.db',
)
# Setup objects
if not config["DEBUG"]:
motor = Actuator(10)
piston = Actuator(11)
valves = [Actuator(12), Actuator(13)]
rangers = [Ranger(0), Ranger(1)... | 1,706 | 607 |
# conftest.py
import pytest
import os
from myapp import create_app, create_contentful
from dotenv import load_dotenv
load_dotenv()
SPACE_ID = os.getenv("SPACE_ID")
DELIVERY_API_KEY = os.getenv("DELIVERY_API_KEY")
TESTING_ENV = "circle_testing"
@pytest.fixture
def app():
app = create_app(SPACE_ID, DELIVERY_API_K... | 572 | 213 |
#!/usr/bin/python3.6
import sqlite3
def make_connect():
conn = sqlite3.connect("bot.db")
cursor = conn.cursor()
return conn, cursor
def create_tables():
conn, cursor = make_connect()
try:
cursor.execute("CREATE TABLE users(user_id INTEGER, bal FLOAT, count_games INTEGER, sum_games FLOAT, ref... | 1,454 | 473 |
# -*- coding: utf-8 -*-
"""
:copyright: Copyright 2020-2022 Sphinx Confluence Builder Contributors (AUTHORS)
:license: BSD-2-Clause (LICENSE)
"""
from tests.lib.testcase import ConfluenceTestCase
from tests.lib.testcase import setup_builder
from tests.lib import parse
import os
class TestConfluenceRstLists(Confluenc... | 4,561 | 1,336 |
#!/usr/bin/env python
'''
Global Variables convention:
* start with UpperCase
* have no _ character
* may have mid UpperCase words
'''
Debug = True
Silent = True
Verbose = False
CustomerName = 'customer_name'
AuthHeader = {'Content-Type': 'application/json'}
BaseURL = "https://firewall-api.d-zone.ca"
... | 422 | 143 |
import os
os.system("pip install tqsdk -i https://pypi.tuna.tsinghua.edu.cn/simple")
os.system("pip install numba -i https://pypi.tuna.tsinghua.edu.cn/simple")
os.system("pip install janus -i https://pypi.tuna.tsinghua.edu.cn/simple")
os.system("pip install redis -i https://pypi.tuna.tsinghua.edu.cn/simple")
os... | 652 | 275 |
import smartystreets_python_sdk as smarty
from smartystreets_python_sdk.us_street import Client as USStreetClient
from smartystreets_python_sdk.us_zipcode import Client as USZIPClient
from smartystreets_python_sdk.us_extract import Client as USExtractClient
from smartystreets_python_sdk.us_autocomplete import Client as... | 5,776 | 1,655 |
"""Utility functions for Object Detection Networks"""
from __future__ import division
import cv2
import torch
import numpy as np
from PIL import Image, ImageDraw
def xyxy2xywh(box: torch.Tensor) -> torch.Tensor:
"""
Returns the xywh format of the input bounding box tensor
Arguments:
... | 14,294 | 4,948 |
import torch
import torch.nn as nn
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# Precomputed coordinate grids dictionary, with (tensor device, tensor size) as the keys.
backwarp_tenGrid = {}
# backwarp and multiwarp are doing backward warping using the forward flow.
# backwarp feature maps a... | 5,512 | 2,222 |
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import AbstractUser
class Author(models.Model):
username = models.CharField(max_length=50, unique=True)
display_name = models.CharField(max_length=50, null=True, blank=True)
email = models.EmailField(null=True, b... | 1,302 | 413 |
from collections import defaultdict
from miniworld.errors import InterfaceUnknown
from miniworld.model.Objects import Objects
from miniworld.model.network.interface.Interface import INTERFACE_NORMAL_CLASSES_TYPES, INTERFACE_NAME_TYPE_MAPPING, AP, Mesh
__author__ = 'Nils Schmidt'
class Interfaces(Objects):
"""
... | 3,705 | 1,067 |
from __future__ import absolute_import, print_function, unicode_literals
import unittest
from doozerlib import distgit
class TestDistgitConvertSourceURLToHTTPS(unittest.TestCase):
def test_conversion_from_ssh_source(self):
source = "git@github.com:myorg/myproject.git"
actual = distgit.convert_so... | 1,354 | 435 |
import requests
import ssl
from requests.adapters import HTTPAdapter, PoolManager
class MyAdapter(HTTPAdapter):
def init_poolmanager(self, connections, maxsize):
super(MyAdapter, self).__init__()
self.poolmanager = PoolManager(num_pools=connections, maxsize=maxsize, ssl_version=ssl.PROTOCOL_SSLv3)... | 441 | 150 |
"""Base observer class for weighmail operations.
"""
class BaseObserver(object):
"""Base observer class; does nothing."""
def searching(self, label):
"""Called when the search process has started for a label"""
pass
def labeling(self, label, count):
"""Called when the labelling p... | 798 | 200 |
from django.apps import AppConfig
class BanksConfig(AppConfig):
name = 'banks'
class DatatableView(AppConfig):
name = 'datatableview'
| 145 | 47 |
# Generated by Django 3.0.2 on 2020-04-29 20:22
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('assessment', '0009_auto_20200426_1103'),
]
operations = [
migrations.AddField(
model_name='assessment',
name='open_s... | 426 | 151 |
from opyoid.bindings.binding import Binding
from opyoid.bindings.binding_to_provider_adapter import BindingToProviderAdapter
from opyoid.bindings.registered_binding import RegisteredBinding
from opyoid.injection_context import InjectionContext
from opyoid.provider import Provider
from opyoid.utils import InjectedT
from... | 950 | 245 |
from pymongo.database import Database
from asset_manager.data.repos.base import MongoRepository
from asset_manager.data.schemas.license import LicenseMongo
class LicenseRepository(MongoRepository[LicenseMongo]):
def __init__(self, db: Database):
super().__init__(db, "licenses", LicenseMongo)
| 307 | 88 |
# -*- coding: utf-8 -*-
"""
salt_utils.py
Description: Utility methods for configuration of Salt Cloud.
Written by: maharg101 on 27th March 2018
"""
import io
import yaml
def generate_openstack_conf(params):
"""
Generate an openstack.conf file-like given the supplied params dict.
:param params: A dicti... | 1,347 | 394 |
# -*- coding: utf-8 -*-
import json
import math
import random
import argparse
import networkx as nx
class Node:
def __init__ (self, nodeNumber, nodeType):
self.nodeNumber = nodeNumber
self.nodeType = nodeType
def add_vm (self, vm):
if not hasattr(self,'vms'):
self.vms = []
self.vms.append(vm)
class VM:... | 6,102 | 2,718 |
"""
Weighted correlation of NES vectors. The idea is to weight positive values on either vector. Positive values
"""
import pandas as pd
import numpy as np
from scipy.spatial.distance import pdist
from scipy.spatial.distance import squareform
def m(x, w):
"""Weighted Mean"""
return np.sum(x * w) / np.sum(w)
... | 9,698 | 3,890 |
from django.contrib.contenttypes.fields import GenericRelation
from django.db import models
from django.utils.timezone import now
class TimeWizardInlineMixin(models.Model):
"""
Mixin for the inline support of PeriodModel.
"""
periods = GenericRelation(
'time_wizard.PeriodModel',
)
cla... | 1,138 | 338 |
#!/usr/bin/python
import twython, time, pprint, traceback, os, sys
import config
from twython import TwythonStreamer, TwythonError, TwythonRateLimitError
import urllib, json, glob, re
import thread
queuelock = thread.allocate_lock()
watchlock = thread.allocate_lock()
import logging
logging.basicConfig(filename='highea... | 16,807 | 5,171 |
"""Creates the bet table and associates it with users.
Revision ID: 8b9f5b081137
Revises: 19cabd29fb71
Create Date: 2016-08-27 17:29:41.137566
"""
# revision identifiers, used by Alembic.
revision = '8b9f5b081137'
down_revision = '19cabd29fb71'
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects... | 1,833 | 664 |
from os import path
from os import system
if (not path.exists("../Relex12.github.io/")):
raise FileNotFoundError("Relex12.github.io directory not found")
if (not path.exists("../Markdown-Table-of-Contents/")):
raise FileNotFoundError("Markdown-Table-of-Contents directory not found")
##################... | 6,847 | 2,415 |
from utils import callo
import os
import subprocess
import re
import logging
logger = logging.getLogger("clang-format")
class Repo(object):
"""Class encapsulates all knowledge about a git repository, and its metadata
to run clang-format.
"""
def __init__(self, path, custom_regex="", dirs_in=[], dirs... | 11,286 | 3,232 |
"""Simple Bot to reply to Telegram messages.
This is built on the API wrapper, see echobot2.py to see the same example built
on the telegram.ext bot framework.
This program is dedicated to the public domain under the CC0 license.
"""
import logging
import telegram
import requests, json
import traceback
from time import... | 5,909 | 2,396 |
"""
This module exports a Log class that wraps the logging python package
Uses the standard python logging utilities, just provides
nice formatting out of the box.
Usage:
from apertools.log import get_log
logger = get_log()
logger.info("Something happened")
logger.warning("Something concerning happe... | 3,509 | 1,082 |
# 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 writing, software
# distributed u... | 2,387 | 698 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2021/12/4 22:00
# @Author : weihuchao
def insert_sort(data):
"""
从前往后遍历, 假定前面部分已经有序, 查看当前元素应该在前面部分的哪个位置
"""
for idx in range(1, len(data)):
tmp = data[idx]
j = idx - 1
while j >= 0 and tmp < data[j]:
data[j ... | 383 | 195 |
#!/usr/bin/python3
import tensorflow as tf
import numpy as np
BASE = 'GraphDefs'
def writeg(name):
session = tf.Session()
session.run(tf.initialize_all_variables())
tf.train.write_graph(session.graph_def, BASE, name + '.txt', True)
tf.train.write_graph(session.graph_def, BASE, name, False)
tf.re... | 884 | 421 |
from moviepy.editor import *
from moviepy import Clip
import sys
import os
"""
This is a simple script that can only snip your code and return it back in one video
This script requires moviepy.py
Is can be obtained through pip:
pip install moviepy
Output file can be '.mp4', 'ogv', 'webm'
You can mod... | 8,254 | 2,696 |
# Copyright (c) 2014 Evalf
#
# 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
# to use, copy, modify, merge, publish, distribute, s... | 20,551 | 6,971 |
from subprocess import run
# configuration defaults tools
update = ['brew', 'update']
install = ['brew', 'install', 'git']
class Installer:
def func_update(self):
run(update)
def func_install(self):
run(install)
| 239 | 73 |
import cv2
import numpy as np
def hex_to_bgr(hx):
hx = hx.lstrip('#')
return tuple(int(hx[i:i + 2], 16) for i in (0, 2, 4))[::-1]
class Rectangle:
def __init__(self, x, y, width, height, max_height, min_db, max_db, color, thickness, reverse):
self.rev = -1 if reverse else 1
self.x = x
... | 5,951 | 2,036 |
import torch.nn as nn
import torch.nn.functional as F
import torchvision
from auto_LiRPA import BoundedModule, BoundedTensor
from auto_LiRPA.perturbations import *
import models
## Step 1: Define computational graph by implementing forward()
class Flatten(nn.Module):
def forward(self, x):
return x.view(x.s... | 2,772 | 1,028 |
#
# PySNMP MIB module FUNI-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/FUNI-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 19:03:03 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:1... | 15,796 | 7,584 |
"""Plaza
Items (in particular, Things and Rooms) representing the setting of Lost One."""
__author__ = 'Nick Montfort'
__copyright__ = 'Copyright 2011 Nick Montfort'
__license__ = 'ISC'
__version__ = '0.5.0.0'
__status__ = 'Development'
from item_model import Room, Thing
items = [
Room('@plaza_center',
... | 10,337 | 3,519 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import shutil
import sys
import tempfile
from observations.r.us_pop import us_pop
def test_us_pop():
"""Test module us_pop.py by downloading
us_pop.csv and testing shape of
extracted data has 22 rows... | 508 | 173 |
from pathlib import Path
from typing import List
FILE_DIR = Path(__file__).parent
def create_boards(boards: List[str]) -> List[str]:
defined_boards = []
for board in boards:
b = board.split('\n')
d_board = [db.split() for db in b]
defined_boards.append(d_board)
return defined_boar... | 2,407 | 766 |
from flask import Flask, render_template, jsonify
import random as r
import csv
app = Flask(__name__)
# define global words dictionary
words = {}
words["easy"] = []
words["medium"] = []
words["hard"] = []
# load words (russian and english)
with open('words.csv', newline='\n', encoding="UTF8") as csvfile:
wordrea... | 1,804 | 645 |
from setuptools import setup, find_packages
with open("README.md", "r") as fh:
long_description = fh.read()
setup(
name='cexpay',
version='2.0.4',
description="A support bot for CEX Pay's products. See more https://developers.cexpay.io/.",
long_description=long_description,
long_description_co... | 1,046 | 329 |
# File #1: Fragment, FragmentId
# File #2: fragmentid, docid, date, domain, fragmentposition
import configparser
from typing import Dict, List, Tuple
import csv
import nltk.data
import string
def process_sentences(config: configparser.SectionProxy):
csv.field_size_limit(2**23)
fin = open(config['Intermediate... | 2,471 | 826 |
import pytest
from reconcile.utils.ocm import OCM
@pytest.fixture
def ocm(mocker):
mocker.patch("reconcile.utils.ocm.OCM._init_access_token")
mocker.patch("reconcile.utils.ocm.OCM._init_request_headers")
mocker.patch("reconcile.utils.ocm.OCM._init_clusters")
mocker.patch("reconcile.utils.ocm.OCM._init... | 1,394 | 558 |
# -*- coding: utf-8 -*-
import datetime
import os
import pickle
import random
from copy import deepcopy
from time import sleep
import numpy as np
from test_agent.ai_interface import AIInterface
from test_agent.utils.wait_calc import WaitCalc
from test_agent.utils.win_calc import WinCalc
from client.mahjong_meld impor... | 97,317 | 34,146 |
import fnmatch
import json
import os
import os.path
import jupyter_core.paths
from io import open
from datetime import datetime
from notebook.utils import url_path_join
from notebook.base.handlers import IPythonHandler
DATE_FORMAT = "%Y-%m-%d"
TIME_FORMAT = "%H:%M:%S"
DEFAULT_USERNAME = "anonymous"
USERNAME_TEMPLATE ... | 5,418 | 1,610 |
# -*- coding:utf-8 -*-
# --------------------------------------------------------
# Copyright (C), 2016-2020, lizhe, All rights reserved
# --------------------------------------------------------
# @Name: serial_actions.py
# @Author: lizhe
# @Created: 2021/5/2 - 0:02
# ----------------------------------... | 3,633 | 1,312 |
# Permite usar o modulo do Sense HAT
from sense_hat import SenseHat
from mcpi.minecraft import Minecraft
from time import sleep
sense = SenseHat()
mc = Minecraft.create()
# blocos
grass = 2
water = 9
sand = 12
air = 0
# cores
white = (255, 255, 255)
green = (0, 255, 0)
blue = (0, 0, 255)
yellow = (255, 255, 0)
blac... | 1,446 | 539 |
import sys
import os
import re
def main():
# Check input for the program.
checker = ArgsChecker()
if not checker.checkInputArgsAreCorrect():
return 1
if checker.processMode == checker.PROCESS_FROM_DIR:
dirProcesser = FromDirProcesser()
dirProcesser.process(checker.csvFilePath)... | 12,674 | 3,839 |
import xml.etree.ElementTree as ElementTree
import os
class CARISObject:
"""A generic CARIS object with a name"""
def __init__(self):
"""Initialize with empty name"""
self.name = ''
def __init__(self, name):
"""Initialize with a name provided"""
self.name = name
def ... | 7,858 | 2,330 |
#!/usr/bin/env python3
import re
print(re.sub("ch|o|k|u", "", input()) and "NO" or "YES") | 89 | 38 |
from simple_salesforce import Salesforce
from airflow.hooks.base_hook import BaseHook
import json
from airflow.utils.log.logging_mixin import LoggingMixin
from airflow.models import BaseOperator
from airflow.plugins_manager import AirflowPlugin
from airflow.utils.decorators import apply_defaults
import csv
from tempfil... | 8,393 | 2,343 |
from django.contrib.auth.decorators import login_required
from django.shortcuts import render, get_object_or_404
from .models import BlogPost
from .forms import BlogPostModelForm
# render intial html page of list of published blogs
def blog_post_list_view(request):
qs = BlogPost.objects.all().published() # queryse... | 1,928 | 614 |
from PyQt5.QtCore import QTimer, QTime
from PyQt5 import QtGui, QtWidgets
import time
import random
import os
import datetime
import requests
import sqlite3 as sql
import database_impl as db
from date_tools import dt
def datetime_diff(old_datetime, new_datetime, dates_are_strings=True):
"""
String dates shoul... | 6,863 | 2,372 |
from abc import ABCMeta, abstractmethod
from functools import partial
from typing import Tuple, Union
import numexpr
import numpy as np
from scipy import sparse, special
from tabmat import MatrixBase, StandardizedMatrix
from ._functions import (
binomial_logit_eta_mu_deviance,
binomial_logit_rowwise_gradient_... | 38,243 | 11,924 |
from django.db import models
from apps.core.models import Patient, Person
from django_extensions.db.fields import AutoSlugField
from apps.core.utils import STYLE_IMG_MIN
from apps.pharmacy.models import SupplyAssignControl
class Medicalcontrol(models.Model):
name = models.CharField(max_length=100)
natural_key... | 2,733 | 878 |
#!/usr/bin/env python
#
# Sample i3module in python
#
from icecube.icetray import *
from I3Tray import *
tray = I3Tray()
# generate empty frames
tray.AddModule("BottomlessSource","bottomless")
def make_counter(base):
class ShouldCounter(base):
def __init__(self, context):
base.__init__(self... | 908 | 290 |
#!/usr/bin/env python
import os, sys
temp=list();
header=1;
sys.path.append('../../Libs/Python')
from BiochemPy import Reactions, Compounds
ReactionsHelper = Reactions()
Reactions_Dict = ReactionsHelper.loadReactions()
CompoundsHelper = Compounds()
Compounds_Dict = CompoundsHelper.loadCompounds()
Compound_To_Merge_... | 3,405 | 1,203 |
import math
import pandas as pd
data = pd.read_csv("works.csv").dropna()
count_people = 0
for (jobTitle, qualification) in zip(data['jobTitle'], data['qualification']):
if jobTitle != qualification:
count_people += 1
print(f"У {count_people} человек профессия и должность не совпадают")
meneger... | 1,110 | 389 |
import json
import os
import pathlib
from datetime import datetime
from io import BytesIO
from pikepdf import Pdf, Encryption
import click
import pytz
from examtool.api.database import get_exam, get_roster
from examtool.api.utils import sanitize_email
from examtool.api.scramble import scramble
from examtool.api.gen_l... | 3,439 | 1,086 |
from decimal import Decimal
from unittest.mock import patch
from django.test import TestCase
from django.urls import reverse
from django.contrib import auth
from main.models import Product, User, Address
from main.forms import UserCreationForm
class TestPage(TestCase):
def test_home_page_works(self):
re... | 5,020 | 1,491 |
from loguru import logger
from multifile02 import sum_ab
def run():
logger.add("log_multifile.log")
logger.info("="*30)
logger.info("start run")
sum_ab(5, 7)
logger.info("end run")
def main():
run()
logger.success('Complete.')
if __name__ == "__main__":
main()
| 299 | 114 |
# -*- coding: utf-8 -*-
from pythonperlin.perlin import perlin
from pkg_resources import get_distribution
__version__ = get_distribution('pythonperlin').version | 162 | 50 |
# coding=utf-8
"""
Django settings for reservas project.
Generated by 'django-admin startproject' using Django 1.8.5.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
... | 4,903 | 1,784 |
#!/usr/bin/env python
import collections
# import itertools
import numpy as np
# from sklearn import linear_model as linear # for VAR
# from .utils import sliding_window as window
# from .utils.distance import kmeans, dists_sq
# from .utils import distance as dist
# from python import compress
# ===============... | 27,684 | 9,683 |
from app.factory import create_app, celery_app
app = create_app(config_name="DEVELOPMENT")
app.app_context().push()
if __name__ == "__main__":
app.run()
| 159 | 60 |
#!/usr/bin/env python
#-*- encoding: utf-8 -*-
"""Command line interpreter right version."""
import sys
import cmd
import random
import os
import pyglet.media
import webbrowser
import time
gachidict = []
with open('gachicmd' + os.sep + 'gachidict.txt') as f:
gachidict = f.read().splitlines()
he... | 4,405 | 1,592 |
# pylint: disable=print-call
import importlib
import pkgutil
import dagster
import sqlalchemy as sa
def check_schema_compat(schema):
"""We run this check to ensure that we don't have any schema columns that are incompatible with
MySQL.
"""
for name in dir(schema):
obj = getattr(schema, name)
... | 1,571 | 436 |
#
# Copyright 2021 XEBIALABS
#
# 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 to use, copy, modify, merge, publish, distribute, subli... | 2,206 | 677 |
from django.template.context import RequestContext
def get_context_dict(context):
"""
Contexts in django version 1.9+ must be dictionaries. As xadmin has a legacy with older versions of django,
the function helps the transition by converting the [RequestContext] object to the dictionary when necessary.
... | 527 | 135 |
'''
pyburstlib
:author: drownedcoast
:date: 4-26-2018
'''
import pytest
from pyburstlib.wallet_api.models.mining import *
from tests.base import BaseTest
from tests.config import PyBurstLibConfig
@pytest.mark.api
class TestMiningApi(BaseTest):
def setup(self):
self.TEST_ACCOUNT_NUMERIC = PyBurstLibConfig.... | 2,144 | 718 |
from nltk.stem.snowball import SnowballStemmer
letter = [u'kissassa']
for word in letter:
print word, SnowballStemmer("finnish").stem(word)
# read file (get a string)
# detect charset (UTF-8)
# decode (get a Unicode code point presentation)
# tokenize
# try out the Snowball stemmer
| 291 | 101 |
#!/usr/bin/env python
# coding: utf-8
# # Project Data Science Desired Skills
#
# this project will Answer the question of what are the most desired skills for Data Science in Egypt and UAE.
# * Extract data from Linked in Via webscrapping or Manually.
# * Perform data wrangling ( image recognition or NLP).
# * Segme... | 5,979 | 2,272 |
x = 5
x |= 3
print(x)
| 26 | 22 |
import argparse
import os
import re
import sys
try:
import pypff
except ImportError:
print("[+] Install the libpff Python bindings to use this script")
sys.exit(1)
message_list = []
messages = 0
def main(pst_file, output_dir):
print("[+] Accessing {} PST file".format(pst_file))
pst = pypff.open(p... | 3,424 | 1,110 |