max_stars_repo_path stringlengths 3 269 | max_stars_repo_name stringlengths 4 119 | max_stars_count int64 0 191k | id stringlengths 1 7 | content stringlengths 6 1.05M | score float64 0.23 5.13 | int_score int64 0 5 |
|---|---|---|---|---|---|---|
flask01.py | pyporto/flask101 | 0 | 12777651 | <gh_stars>0
from flask import Flask
app = Flask('myapp')
if __name__ == '__main__':
app.run()
| 1.335938 | 1 |
profiles/migrations/New folder/0035_auto_20201028_0913.py | Rxavio/link | 0 | 12777652 | # Generated by Django 3.0.3 on 2020-10-28 07:13
from django.db import migrations, models
import profiles.models
class Migration(migrations.Migration):
dependencies = [
('profiles', '0034_auto_20201028_0358'),
]
operations = [
migrations.AlterField(
model_name='profile',
... | 1.484375 | 1 |
2018/day_4/star_1/star.py | j-benson/advent-of-code | 0 | 12777653 | from datetime import datetime, timedelta
def parse_line(line):
date = datetime.strptime(line[1:17], "%Y-%m-%d %H:%M")
message = line[19:]
return (date, message)
with open('data.txt') as data:
unordered_list = [parse_line(line) for line in data.readlines()]
ordered_list = sorted(unordered_list, key= lambda i ... | 3.1875 | 3 |
src/notifier/__init__.py | guydavis/chiadog | 2 | 12777654 | """Notifier package responsible for user notification
"""
import json
import logging
import re
import time
import traceback
# std
from abc import ABC, abstractmethod
from dataclasses import dataclass
from json_logic import jsonLogic
from typing import List
from enum import Enum
# Ignore Chiadog alerts about being of... | 2.734375 | 3 |
testHaarCascade.py | AriRodriguezCruz/mcfgpr | 0 | 12777655 | <reponame>AriRodriguezCruz/mcfgpr
# -*- coding: utf-8 -*-
"""
Basic test of our ability to do a Haar Cascade
"""
import cv2
haarFaceCascade = cv2.CascadeClassifier('haarcascades/haarcascade_frontalface_default.xml')
WINDOW_NAME = "preview"
def detect(img, cascade, minimumFeatureSize=(20,20)):
if casca... | 2.5625 | 3 |
2-aiohttp/aiohttp_server/app/web/config.py | rcmgn/kts-school-backend | 9 | 12777656 | import typing
from dataclasses import dataclass
import yaml
if typing.TYPE_CHECKING:
from app.web.app import Application
@dataclass
class Config:
username: str
password: str
def setup_config(app: "Application"):
with open("config/config.yaml", "r") as f:
raw_config = yaml.safe_load(f)
... | 2.5625 | 3 |
ctre/trajectorypoint.py | Ninjakow/robotpy-ctre | 0 | 12777657 | # validated: 2018-03-01 DS b3d643236ddc libraries/driver/include/ctre/phoenix/Motion/TrajectoryPoint.h
from collections import namedtuple
__all__ = ["TrajectoryPoint"]
#: Motion Profile Trajectory Point for use with pushMotionProfileTrajectory
TrajectoryPoint = namedtuple(
"TrajectoryPoint",
[
"posit... | 2.671875 | 3 |
ITC_selenium.py | bryanmiller/pyitc_gemini | 0 | 12777658 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
#import difflib
import datetime
import logging
import os
from selenium import webdriver
# from selenium.webdriver.firefox.options import Options
# from selenium import selenium
# from selenium.common.exceptions import TimeoutException
... | 2.125 | 2 |
source-code-from-author-book/Listings-for-Second-Edition/listing_5_8.py | robrac/algorithms-exercises-with-python | 0 | 12777659 | label=hashtablecodesearch,index={get,\_\_getitem\_\_,\_\_setitem\_\_},float=htb]
def get(self,key):
startslot = self.hashfunction(key,len(self.slots))
data = None
stop = False
found = False
position = startslot
while self.slots[position] != None and \
not found and not stop:
if... | 2.765625 | 3 |
src/api/domain/operation/GetDataOperationJobExecutionLogList/GetDataOperationJobExecutionLogListQueryHandler.py | PythonDataIntegrator/pythondataintegrator | 14 | 12777660 | from injector import inject
from domain.operation.GetDataOperationJobExecutionLogList.GetDataOperationJobExecutionLogListMapping import GetDataOperationJobExecutionLogListMapping
from domain.operation.GetDataOperationJobExecutionLogList.GetDataOperationJobExecutionLogListQuery import GetDataOperationJobExecutionLogList... | 2.03125 | 2 |
code/data_reader.py | matheusjohannaraujo/ML-Experiments_FuzzyClustering_ProbClassifiers | 1 | 12777661 | <reponame>matheusjohannaraujo/ML-Experiments_FuzzyClustering_ProbClassifiers<gh_stars>1-10
import pandas as pd
import parameters as params
import numpy as np
from sklearn.preprocessing import StandardScaler, MinMaxScaler
from imblearn.over_sampling import SMOTE
class DataReader:
def __init__(self):
path = ... | 2.40625 | 2 |
core/src/test/python/exception_test.py | 11bluetree/weblogic-deploy-tooling | 1 | 12777662 | """
Copyright (c) 2017, 2019, Oracle Corporation and/or its affiliates. All rights reserved.
Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl.
"""
import unittest
from wlsdeploy.exception import exception_helper
from wlsdeploy.exception.expection_types import Excep... | 2.1875 | 2 |
python/tuples_example.py | matheuskiser/pdx_code_guild | 0 | 12777663 | # Assigns a tuple of scores
scores = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
# Displays the highest and lowest value in the tuple
print "The lowest possible score is " + str(min(scores))
print "The highest possible score is " + str(max(scores))
# Goes through tuple and prints out values
for i in scores:
if i == 1:
... | 4.40625 | 4 |
setup.py | yetone/collipa | 99 | 12777664 | <gh_stars>10-100
# coding: utf-8
import re
import sys
import getopt
import MySQLdb
from pony.orm import db_session
from collipa import config
@db_session
def init_node():
from collipa.models import Node
if not Node.get(id=1):
Node(name=u'根节点', urlname='root',
description=u'一切的根源').save()... | 2.25 | 2 |
Data Structures/LinkedList/Doubly Linked List/Insertion_at_front.py | chasesagar/Python-Programming | 0 | 12777665 | # Doubly Linked List
class Node:
def __init__(self,data):
self.data = data
self.next = None
self.prev = None
class DoublyLinkedList:
def __init__(self):
self.head = None
# Main insertion function
def Push(self,new_data):
new_node = Node(new_data) # 1 & 2: All... | 4.28125 | 4 |
rwd_nhd/NHD_Rapid_Watershed_Delineation.py | WikiWatershed/RapidWatersheDelineation | 8 | 12777666 | <filename>rwd_nhd/NHD_Rapid_Watershed_Delineation.py
import sys
import os
import time
import subprocess
import gdal
import fiona
from NHD_RWD_Utilities import generate_moveoutletstostream_command, create_shape_from_point, \
extract_value_from_raster_point, extract_value_from_raster, get_gauge_watershed_command, g... | 2.25 | 2 |
konfi/__init__.py | gieseladev/konfi | 1 | 12777667 | """konfi is a config parser."""
from .converter import ComplexConverterABC, ConversionError, ConverterABC, \
ConverterFunc, ConverterType, convert_value, has_converter, \
register_converter, unregister_converter
from .field import Field, MISSING, NoDefaultValue, UnboundField, ValueFactory, field
from .loader i... | 1.8125 | 2 |
src/setFunctions.py | hpsim/OBR | 0 | 12777668 | #!/usr/bin/env python3
from subprocess import check_output
def sed(fn, in_reg_exp, out_reg_exp, inline=True):
""" wrapper around sed """
ret = check_output(["sed", "-i", "s/" + in_reg_exp + "/" + out_reg_exp + "/g", fn])
def clean_block_from_file(fn, block_starts, block_end, replace):
""" cleans everyth... | 2.703125 | 3 |
renamer/renamerView.py | UnzaiRyota/pairpro | 0 | 12777669 | <gh_stars>0
# -*- coding: utf-8 -*-
import os
from PySide2.QtWidgets import *
from PySide2.QtGui import *
from PySide2.QtCore import *
from PySide2.QtUiTools import *
absPath = os.path.dirname(__file__)
uiPath = os.path.join(absPath, "view.ui")
uiclass, baseclass = loadUiType(uiPath)
class uiClass(baseclass, uiclass)... | 2.046875 | 2 |
ml/webserver.py | Censored-Data/VK-Gaming | 3 | 12777670 | <gh_stars>1-10
from library import config, get_recomendation_games, get_recomendation_users, get_cs_team
from http.server import HTTPServer, BaseHTTPRequestHandler
from io import BytesIO
from urllib.parse import urlparse, parse_qs
import json
import pandas as pd
from sklearn.neighbors import NearestNeighbors
import pi... | 2.609375 | 3 |
tests/federation/test_pdu_codec.py | uroborus/synapse | 1 | 12777671 | # -*- coding: utf-8 -*-
# Copyright 2014 OpenMarket Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable la... | 2 | 2 |
data/utils_data.py | lmzintgraf/MultiMAuS | 14 | 12777672 | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from os.path import join, dirname, exists
from os import makedirs, pardir
FOLDER_REAL_DATA = join(dirname(__file__), 'real_data')
FOLDER_SIMULATOR_INPUT = join(dirname(__file__), 'simulator_input')
FOLDER_REAL_DATA_ANALYSIS = join(FOLDER_REAL_DATA,... | 3.0625 | 3 |
django_cat_app/models.py | NikolasE/telegram_catbot | 0 | 12777673 | <filename>django_cat_app/models.py
from django.db import models
# we simply count the number of cat images we sent to a person
# (we use first name as user_id which will create collisions, but also adds privacy by design)
class UserLog(models.Model):
user_id = models.CharField(max_length=100)
cat_count = mode... | 2.390625 | 2 |
products/admin.py | BassamMismar/store | 0 | 12777674 | <reponame>BassamMismar/store<gh_stars>0
from django.contrib import admin
from .models import Product
| 1.039063 | 1 |
scripts/const/consts.py | jiamingli9674/Intelligent-Checkout-System | 2 | 12777675 | <gh_stars>1-10
import os
SCRIPT_ROOT_DIR = os.getcwd()
ROOT_DIR = os.path.dirname(SCRIPT_ROOT_DIR)
IMAGE_DIR = os.path.join(ROOT_DIR, 'images')
ANTI_SPOOFING_MODELS_DIR = os.path.join(ROOT_DIR, "models", "anti_spoof_models")
DATA_DIR = os.path.join(ROOT_DIR, "data")
FACE_DETECTION_CAFFE_MODEL = os.path.join(ROOT_... | 1.796875 | 2 |
rvpy/__init__.py | TimothyKBook/distributions | 1 | 12777676 | <reponame>TimothyKBook/distributions
from .distribution import Distribution
from .normal import Normal, StandardNormal, LogNormal
from .binomial import Bernoulli, Binomial
from .cuniform import CUniform
from .gamma import Gamma, Exponential, ChiSq
from .beta import Beta
from .t import T
from .f import F
from .cauchy im... | 2.078125 | 2 |
KMtorch/helpers.py | mscipio/KMtorch | 1 | 12777677 | <gh_stars>1-10
import pycuda.driver as drv
import torch
import numpy as np
__all__ = ['Holder','Utils']
class Holder(drv.PointerHolderBase):
def __init__(self, t):
super(drv.PointerHolderBase, self).__init__()
self.t = t
self.gpudata = t.data_ptr()
def get_pointer(self):
retu... | 2.21875 | 2 |
invprob/optim.py | Guillaume-Garrigos/inverse-problems | 4 | 12777678 | import numpy as np
from numpy import linalg as la
import invprob.sparse as sparse
def fb_lasso(A, y, reg_param, iter_nb, x_ini=None, inertia=False, verbose=False):
''' Use the Forward-Backward algorithm to find a minimizer of:
reg_param*norm(x,1) + 0.5*norm(Ax-y,2)**2
Eventually outputs the f... | 3.1875 | 3 |
workers/convert/convert_image.py | dainst/cilantro | 3 | 12777679 | <filename>workers/convert/convert_image.py
import logging
import os
import subprocess
from PIL import Image as PilImage
import ocrmypdf
import pyocr
log = logging.getLogger(__name__)
tools = pyocr.get_available_tools()
if len(tools) == 0:
log.error("No OCR tool found")
ocr_tool = tools[0]
log.debug("Will use oc... | 2.84375 | 3 |
txgossip/scuttle.py | jrydberg/txgossip | 5 | 12777680 | # Copyright (C) 2011 <NAME>
# Copyright (C) 2010 <NAME>
#
# 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, ... | 2.0625 | 2 |
generators.py | m87/pyEM | 0 | 12777681 | <gh_stars>0
import numpy as np
import os
from scipy import linalg
from config import *
def fixed_generator(models, size, init):
clusters = len(models[WEIGHTS])
out=[]
ini = []
labels =[]
n= int(size/clusters)+1
for m in range(clusters):
w=np.random.multivariate_normal(models[MEANS][m]... | 2.25 | 2 |
parse_xml.py | WillMatthews/refmanager | 1 | 12777682 | <filename>parse_xml.py
#!/usr/bin/python3
# script to parse an EndNote XML database file, and populate a mysql database with the contents
import xml.etree.ElementTree as Etree
import pymysql
#from termcolor import colored
nums = []
count = 0;
dictList = []
stdDict = {"title":"","author":"","key":"","year":"","abstra... | 3 | 3 |
videos/HomeworkVol03/678-widcardw.py | AStarySky/manim_sandbox | 366 | 12777683 | <gh_stars>100-1000
# from widcardw
from manimlib.imports import *
class Test6(Scene):
CONFIG = {"camera_config": {"background_color": "#ffffff"}}
def construct(self):
circle0 = Circle(radius=1.5, stroke_color="#559944", plot_depth=-2)
doto = Dot(ORIGIN, color="#000000")
te... | 2.109375 | 2 |
modules/pymol/embed/epymol/__init__.py | hryknkgw/pymolwin | 2 | 12777684 |
from pymol.embed import EmbeddedPyMOL
class ePyMOL(EmbeddedPyMOL):
def __init__(self):
self.ep_init()
# initial mouse position
self.lastx = self.x = 30
self.lasty = self.y = 30
def SetSize(self, width, height):
self.ep_reshape(width,height)
def OnChar(self... | 2.765625 | 3 |
testes/teste_Conexao_Oracle.py | almirjgomes/DE_DataBaseConnect | 0 | 12777685 | <filename>testes/teste_Conexao_Oracle.py
import pandas as pd
import DE_DataBase as dtb
db = dtb.DATABASE()
def teste_ORACLE():
try:
monterey = {"database": "Oracle",
"name_conection": "MONTEREY",
"path_library": None,
"instance": None,
... | 2.484375 | 2 |
src/routers/rotas_auth.py | daianasousa/Projeto-BLX | 0 | 12777686 | <filename>src/routers/rotas_auth.py
from fastapi import APIRouter, status, Depends, HTTPException
from typing import List
from sqlalchemy.orm import Session
from src.schemas.schemas import Usuario, UsuarioSimples, LoginSucesso, LoginData
from src.infra.sqlalchemy.config.database import get_db
from src.infra.sqlalchemy.... | 2.484375 | 2 |
solution/lc033.py | sth4nothing/pyleetcode | 0 | 12777687 | class Solution(object):
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
import bisect
if not nums:
return -1
n = len(nums)
k = n
for i in range(1, n):
if nums[i - 1] > ... | 3.34375 | 3 |
assertpy/__init__.py | santunioni/assertpy | 246 | 12777688 | from __future__ import absolute_import
from .assertpy import assert_that, assert_warn, soft_assertions, fail, soft_fail, add_extension, remove_extension, WarningLoggingAdapter, __version__
from .file import contents_of
| 1.085938 | 1 |
src/practitioner/classify_ai4i2020.py | jpastorino/Data-Blind-ML | 0 | 12777689 | <gh_stars>0
import numpy as np
import sklearn as scikit
import tensorflow as tf
from preprocessing import Preprocessing
from evaluation import EvaluationClient
from sklearn.model_selection import train_test_split
# #######################################################################################################... | 2.6875 | 3 |
src/main/python/coding_problems/bs_detect_the_only_duplicate_in_list.py | ikumen/today-i-learned | 0 | 12777690 | <reponame>ikumen/today-i-learned
"""
You are given a list nums of length n + 1 picked from the range 1, 2, ..., n. By the pigeonhole principle, there must be a duplicate. Find and return it. There is guaranteed to be exactly one duplicate.
Bonus: Can you do this in \mathcal{O}(n)O(n) time and \mathcal{O}(1)O(1) space?... | 3.578125 | 4 |
rl_agents/trainer/logger.py | neskoc/rl-agents | 342 | 12777691 | <reponame>neskoc/rl-agents<gh_stars>100-1000
import json
import logging.config
from pathlib import Path
import gym
from rl_agents.configuration import Configurable
logging_config = {
"version": 1,
"disable_existing_loggers": False,
"formatters": {
"standard": {
"format": "[%(levelname)... | 2.359375 | 2 |
source/gui/test/test_1dvar.py | bucricket/projectMAScorrection | 0 | 12777692 | <reponame>bucricket/projectMAScorrection
'''
Created on May 7, 2014
@author: pascale
'''
import unittest
import rmodel
import logging
import rttovgui_unittest_class
import r1Dvar
class Test(rttovgui_unittest_class.RttovGuiUnitTest):
def setUp(self):
level_logging = logging.DEBUG
self.p = rmo... | 2.09375 | 2 |
Test/test_others.py | LinyueSong/FMLC | 0 | 12777693 | <filename>Test/test_others.py
import sys
from os import path
sys.path.append(path.dirname(path.dirname(path.abspath(__file__))))
import time
from FMLC.triggering import triggering
from FMLC.baseclasses import eFMU
from FMLC.stackedclasses import controller_stack
class testcontroller1(eFMU):
def __init__(self):
... | 2.6875 | 3 |
projects/pyside2_qml_property/main.py | jungmonster/qt_study_project | 0 | 12777694 | import sys
from PySide2.QtGui import QGuiApplication
from PySide2.QtQml import QQmlApplicationEngine
from PySide2.QtCore import QUrl
from PySide2.QtCore import QCoreApplication
from PySide2.QtCore import QObject, Signal, Slot, Property
class Number(QObject):
__val = 0
@Signal
def numberChanged(self):
... | 2.375 | 2 |
src/train_validate.py | biomed-AI/TransEPI | 3 | 12777695 | #!/usr/bin/env python3
import argparse, os, sys, time, shutil, tqdm
import warnings, json, gzip
import numpy as np
import copy
from sklearn.model_selection import GroupKFold
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
from torch.utils.data import DataLoader, ... | 2.21875 | 2 |
tests/fakes/fake_docker_api.py | delta/serverctl_daemon | 2 | 12777696 | <reponame>delta/serverctl_daemon
"""
Fake responses for the Docker API
Adapted from https://github.com/docker/docker-py/blob/master/tests/unit/fake_api.py
"""
from typing import Any, Generator
FAKE_CONTAINER_ID = "3cc2351ab11b"
FAKE_LONG_ID = "e75ccd38cba33f61b09515e05f56fc243ef40186d600a9eeb6bc0bed8e2e1508"
FAKE_LOG... | 2.28125 | 2 |
app/test/test_data_validation.py | adrianopaduam/python_flask_selenium_stock_price_api | 0 | 12777697 | import unittest
from app.main.util.data_validation import validate_region_name
class TestCorrectRegionValidation(unittest.TestCase):
def test_correct_region_validation(self):
correct_region_simple = "Argentina"
correct_region_with_spaces = "United%20Kingdom"
correct_region_with_hiphen =... | 3.484375 | 3 |
tensormonk/activations/activations.py | Tensor46/TensorMONK | 29 | 12777698 | """ TensorMONK :: layers :: Activations """
__all__ = ["Activations"]
import torch
import torch.nn as nn
import torch.nn.functional as F
def maxout(tensor: torch.Tensor) -> torch.Tensor:
if not tensor.size(1) % 2 == 0:
raise ValueError("MaxOut: tensor.size(1) must be divisible by n_splits"
... | 2.890625 | 3 |
workflow/notebooks/dev/test_patterns.py | CambridgeSemiticsLab/BH_time_collocations | 5 | 12777699 | <filename>workflow/notebooks/dev/test_patterns.py<gh_stars>1-10
patterns = [
# PREP + NOUN
"""
ph:phrase rela=NA
w1:word pdp=prep
<: w2:word pdp=subs ls#card
w1 =: ph
w2 := ph
""",
# PREP + ART + NOUN
"""
ph:phrase rela=NA
w1:word pdp=prep
<: word lex=H
<: w2:word pdp=subs ls#card
w1 =: ph
w2 :=... | 2.3125 | 2 |
src/lect06.py | luchenhua/MIT-OCW-600 | 0 | 12777700 | __author__ = 'luchenhua'
EtoF = {'bread': 'du pain', 'wine': 'du vin', 'eats': 'mange', 'drinks': 'bois', 'likes': 'aime', 1: 'un',
'6.00': '6.00'}
print(EtoF)
print(EtoF.keys())
print(EtoF.keys)
del EtoF[1]
print(EtoF)
def translateWord(word, dictionary):
if word in dictionary:
return dictionary... | 3.875 | 4 |
WideResNet.py | Stick-To/Deep_Conv_Backone_tensorflow | 12 | 12777701 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
import os
class WideResNet:
def __init__(self, nk, input_shape, num_classes, weight_decay, keep_prob, data_format='channels_last'):
assert len(nk) == 2
assert (nk[0... | 2.34375 | 2 |
setup.py | ops-utils/fresh-slack | 1 | 12777702 | # Not currently used; in case I ever turn this into a formal package
import setuptools
with open('README.md', 'r') as f:
long_description = f.read()
with open('requirements.txt') as f:
install_requires = f.read().split('\n')
install_requires = [x for x in install_requires if x != '']
setuptools.setup(
... | 1.484375 | 1 |
kkbox_developer_sdk/feature_playlist_fetcher.py | garyckhsu/django-REST | 71 | 12777703 | #!/usr/bin/env python
# encoding: utf-8
from .fetcher import *
from .territory import *
class KKBOXFeaturePlaylistFetcher(Fetcher):
'''
List all featured playlists metadata.
See `https://docs-en.kkbox.codes/v1.1/reference#featured-playlists`.
'''
@assert_access_token
def fetch_all_feature_play... | 2.4375 | 2 |
Python_Basics/Programming_in_Python/operators_and_operands.py | samyumobi/A-Complete-Python-Guide-For-Beginners | 7 | 12777704 | <reponame>samyumobi/A-Complete-Python-Guide-For-Beginners<filename>Python_Basics/Programming_in_Python/operators_and_operands.py<gh_stars>1-10
print(100 + 200) # addition
print(5 - 2) # subtraction
print(3 * 10) # multiplication
print(10 / 3) # division
print(10 // 3) # in... | 3.78125 | 4 |
Gal2Renpy/DefineSyntax/MovieDefine.py | dtysky/Gal2Renpy | 36 | 12777705 | #coding:utf-8
#################################
#Copyright(c) 2014 dtysky
#################################
import G2R,os
class MovieDefine(G2R.DefineSyntax):
def Creat(self,Flag,US,FS,DictHash):
DictHash=G2R.DefineSyntax.Creat(self,Flag,US,FS,DictHash)
if DictHash[Flag]==G2R.DHash(US.Args[Flag]):
return DictH... | 2.46875 | 2 |
Mod 01/04-2-List.py | SauloCav/CN | 0 | 12777706 | <filename>Mod 01/04-2-List.py<gh_stars>0
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
import math
def f(x):
return x**3 -x -1
def phi(x):
return (x+1)**(1/3)
x = 1.5
while f(x+10**-4)*f(x-10**-4)>= 0:
x = phi(x)
print(x)
| 3.5 | 4 |
setup.py | TheDataShed/geograpy3 | 0 | 12777707 | from setuptools import setup
import os
from collections import OrderedDict
try:
long_description = ""
with open('README.md', encoding='utf-8') as f:
long_description = f.read()
except:
print('Curr dir:', os.getcwd())
long_description = open('../../README.md').read()
setup(name='geograpy3',
... | 1.75 | 2 |
starlite/logging.py | madlad33/starlite | 0 | 12777708 | from logging import config
from typing import Any, Dict, List, Optional, Union
from pydantic import BaseModel
from typing_extensions import Literal
class LoggingConfig(BaseModel):
version: Literal[1] = 1
incremental: bool = False
disable_existing_loggers: bool = False
filters: Optional[Dict[str, Dict... | 2.25 | 2 |
app/user/tests/test_user_api.py | ClickTravel-VincentCleaver/recipe-app-api | 0 | 12777709 | from django.test import TestCase
from django.contrib.auth import get_user_model
from django.urls import reverse
from rest_framework.test import APIClient
from rest_framework import status
CREATE_USER_URL = reverse('user:create')
TOKEN_URL = reverse('user:token')
ME_URL = reverse('user:me')
def create_user(**params... | 2.84375 | 3 |
daily.py | filiptronicek/czech-weather | 1 | 12777710 | from pyowm import OWM
import csv
from datetime import datetime
from os import environ, stat, path, access, R_OK, mkdir
API_key = environ.get('API_key')
if API_key is None:
from creds import API_key
fields = ["date", "windspeed", "humidity", "temperature", "status"]
now = datetime.now()
cities = ["Praha", "Pl... | 2.78125 | 3 |
engine/admin.py | lordoftheflies/gargantula-scrapersite | 0 | 12777711 | <reponame>lordoftheflies/gargantula-scrapersite<filename>engine/admin.py
from django.contrib import admin
from django.contrib.admin import ModelAdmin
from django.utils.translation import gettext as _
from . import models
# Register your models here.
class ArgumentInline(admin.TabularInline):
model = models.Argum... | 1.992188 | 2 |
models/GenericModel.py | marioviti/nn_segmentation | 0 | 12777712 | from serialize import save_to, load_from
from keras.models import Model
class GenericModel(object):
def __init__( self, inputs, outputs, loss, metrics, optimizer, loss_weights=None, sample_weight_mode=None):
"""
params:
inputs: (tuple)
outputs: (tuple)
loss: (fu... | 2.578125 | 3 |
old_files/Parsing_justifications_dev_skdclean.py | jmhernan/NIreland_NLP | 1 | 12777713 | ################################################################
#### This is code for using regular expressions to clean / ####
#### parse text from Nvivo .txt into a workable format. ####
#### <NAME>9 ####
#### <NAME> Sarah ####
#### environment: ni_nlp ####
##############################... | 3.234375 | 3 |
yt/frontends/art/api.py | danielgrassinger/yt_new_frontend | 0 | 12777714 | <filename>yt/frontends/art/api.py<gh_stars>0
"""
API for yt.frontends.art
"""
#-----------------------------------------------------------------------------
# Copyright (c) 2013, yt Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distri... | 1.296875 | 1 |
single-use-scripts/generate-mod-eng-prose-genre-labels.py | timgianitsos/english-universal_feature_analysis | 0 | 12777715 | <filename>single-use-scripts/generate-mod-eng-prose-genre-labels.py<gh_stars>0
'''
Generate the csv of genre labels for files
'''
import os
from os.path import join, dirname
import csv
def main():
verse_dir = ('english-diachronic-corpus', 'Modern_English', 'Verse_Corpus')
prose_dir = ('english-diachronic-corpus', 'M... | 2.265625 | 2 |
srtm30_parser/map_pop_with_topo.py | marcwie/srtm30-parser | 0 | 12777716 | from sedac_gpw_parser import population
import numpy as np
from matplotlib import pyplot as plt
import matplotlib.colors as colors
import os
file_lons = np.arange(-180, 180, 40)
file_lats = np.arange(90, -20, -50)
DATA_FOLDER = os.path.expanduser("~") + "/.srtm30/"
def get_population_data(country_id):
pop = ... | 2.859375 | 3 |
api/service/update_balance.py | guisteglich/EasyPay | 0 | 12777717 | <gh_stars>0
from hashlib import new
from sqlalchemy import false
from api.extensions.mongo import update_user
def balance_update(id, value, balance):
balance_value_updated = int(value) + int(balance)
new_values = { "$set": { "balance": balance_value_updated } }
response = update_user(id, new_values)
r... | 2.734375 | 3 |
rfv_bullet.py | rfernandezv/Faster-R-CNN-bullet | 1 | 12777718 | <filename>rfv_bullet.py<gh_stars>1-10
# importing required libraries
# https://www.analyticsvidhya.com/blog/2018/11/implementation-faster-r-cnn-python-object-detection/
import pandas as pd
import matplotlib.pyplot as plt
import cv2
from matplotlib import patches
# el orden es name, bullet (type), x1, x2, y1, y2
# re... | 3.390625 | 3 |
petsi/plugins/sojourntime/__init__.py | vadaszd/petsi | 0 | 12777719 | <reponame>vadaszd/petsi
""" A plugin that collects by-place sojourn time stats.
.. rubric:: Public package interface
- Class :class:`SojournTimePlugin` (see below)
.. rubric:: Internal submodules
.. autosummary::
:template: module_reference.rst
:recursive:
:toctree:
petsi.plugins.sojourntime._sojou... | 2.421875 | 2 |
moderation_module/guild_logging/guild_logging.py | alentoghostflame/StupidAlentoBot | 1 | 12777720 | from moderation_module.guild_logging.commands import guild_logging_control, send_delete_embed, send_edit_embed, \
send_joined_embed, send_remove_embed
from moderation_module.storage import GuildLoggingConfig
from alento_bot import StorageManager
from discord.ext import commands
import moderation_module.text
import ... | 2.09375 | 2 |
src/drkns/generation/templateloading/get_generation_template_path.py | frantzmiccoli/drkns | 13 | 12777721 | import os
import re
from drkns.exception import MissingGenerationTemplateDirectoryException, \
MissingGenerationTemplateException, MultipleGenerationTemplateException
_template_directory = '.drknsgeneration'
_template_file_re = re.compile(r'^.*\.template\..*$')
def get_generation_template_path(from_path: str) ... | 2.625 | 3 |
tebas.py | Jack007notabohu/Webdav- | 0 | 12777722 | <filename>tebas.py<gh_stars>0
#create BY Jack007
#-*- coding: utf-8 -*-
try:
import requests
import os.path
import sys
except ImportError:
exit("install requests and try again ...")
banner = """
``````````
`/- ```..`.`....`..``` `//.
--h... | 2 | 2 |
make_data/traffic/make_traffic_data.py | ricosr/travel_consult_chatbot | 0 | 12777723 | # -*- coding: utf-8 -*-
from traffic_templates import *
def clean_traffic_data1(term_file):
with open(term_file, 'r', encoding="utf-8") as fpr:
terms_temp_ls = fpr.readlines()
terms_ls = [term2.strip() for term2 in terms_temp_ls]
return terms_ls
def create_traffic_data(term_file, output_file):
... | 2.78125 | 3 |
deepl/enums.py | sorbatti/deepl.py | 0 | 12777724 | <gh_stars>0
from enum import Enum
__all__ = [
'SourceLang',
'TargetLang',
'SplitSentences',
'PreserveFormatting',
'Formality'
]
class SourceLang(Enum):
Bulgarian = 'BG'
Czech = 'CS'
Danish = 'DA'
German = 'DE'
Greek = 'EL'
English = 'EN'
Spanish = 'ES'
Estonian = '... | 2.3125 | 2 |
Assignment-1/hw1_perceptron.py | ZhangShiqiu1993/CSCI-567-machine-learning | 0 | 12777725 | from __future__ import division, print_function
from typing import List, Tuple, Callable
import numpy as np
import scipy
import matplotlib.pyplot as plt
class Perceptron:
def __init__(self, nb_features=2, max_iteration=10, margin=1e-4):
'''
Args :
nb_features : Number of feature... | 3.71875 | 4 |
onmydesk/forms/__init__.py | myollie/django-onmydesk | 0 | 12777726 | from . import fields
__all__ = ('fields',)
| 1.085938 | 1 |
saleor/plugins/sendgrid/__init__.py | greentornado/saleor | 3 | 12777727 | <gh_stars>1-10
from dataclasses import dataclass
from typing import Optional
@dataclass
class SendgridConfiguration:
api_key: Optional[str]
sender_name: Optional[str]
sender_address: Optional[str]
account_confirmation_template_id: Optional[str]
account_set_customer_password_template_id: Optional[s... | 1.929688 | 2 |
modules/selfserve/files/selfserve/lib/selfserve/email.py | mshuler/infrastructure-puppet | 1 | 12777728 | <reponame>mshuler/infrastructure-puppet
#!/usr/bin/python
#
# Library logic for selfserve ss2: email.
#
# ====================================================================
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distribute... | 1.84375 | 2 |
exercise00/start.py | tschibu/hslu-ipcv-exercises | 1 | 12777729 | # -*- coding: utf-8 -*-
#!/usr/bin/python3
"""
"""
# =============================================================================
# Imports
# =============================================================================
import cv2
import numpy as np
import matplotlib as mpl
from matplotlib import pyplot as plt
# M... | 3.15625 | 3 |
kProcessor/kmerRow.py | drtamermansour/Kprocessor | 8 | 12777730 | class kmerRow():
kmer = str()
hashedKmer = int()
count = int()
def __init__(self, kmer, hashedKmer, count):
"""
kmerRow class constructor.
:param kmer: The kmer string
:type kmer: str
:param hashedKmer:
:type hashedKmer: int
:param count: The kme... | 3 | 3 |
base64N.py | thebuster0/Base64-n | 1 | 12777731 | <reponame>thebuster0/Base64-n
#cython: language_level=3
import stdbase64 as base64
def Encrypt(byte, loopTime, debug = False):
result = byte
if debug:
for time in range(1, loopTime + 1):
result = base64.b64encode(result)
print("Current loop time:", time)
else:
... | 2.875 | 3 |
2021/day14/day14.py | grecine/advent-of-code | 0 | 12777732 | import numpy as np
import os
import time
np.set_printoptions(threshold=np.inf)
def input(fname):
day_dir = os.path.realpath(__file__).split('/')[:-1]
fname = os.path.join('/',*day_dir, fname)
data = []
with open(fname) as f:
for line in f:
data.append(line.strip())
return data... | 2.625 | 3 |
PythonExercices/Semana_Python_Ocean_Marco_2021-main/Exercicios_Python_PauloSalvatore/Exercicio_8.py | Rkhwong/RHK_PYTHON_LEARNING | 0 | 12777733 | """
Exercício 8
Nome: Comparação de Números: Maior, Menor ou Igual
Objetivo: Receber dois números e exibir qual é maior, menor ou igual a quem.
Dificuldade: Principiante
1 - Escreva um programa que receba dois números, {numero1} e {numero2}:
2 - Caso o {numero1} seja maior do que o {numero2}, exiba na tela: "O número {... | 4.40625 | 4 |
nydkcd11/blog/migrations/0019_auto_20170712_2245.py | asi14/nydkc11 | 0 | 12777734 | <gh_stars>0
# -*- coding: utf-8 -*-
# Generated by Django 1.11.2 on 2017-07-12 22:45
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('blog', '0018_image_show_home'),
]
oper... | 1.59375 | 2 |
gpflow/utilities/utilities.py | HarrySpearing/GPflow | 1,724 | 12777735 | # Copyright 2017-2021 The GPflow Contributors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | 1.65625 | 2 |
app/utils/redisset.py | Maxcutex/pm_api | 0 | 12777736 | <reponame>Maxcutex/pm_api
"""RedisSet class for PM."""
from redis import Redis
from config import get_env
END_DELIMITER = "%"
class RedisSet(object):
"""
Implements a simple sorted set with Redis
"""
def __init__(self, name="redis", namespace="pm", url=None):
"""
The default connecti... | 2.90625 | 3 |
application/classes/ga360_report_response.py | isabella232/report2bq | 9 | 12777737 | <reponame>isabella232/report2bq
# Copyright 2021 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 applicab... | 2.625 | 3 |
venv/lib/python3.8/site-packages/flake8_rst_docstrings.py | trkohler/biopython | 0 | 12777738 | """Check Python docstrings validate as reStructuredText (RST).
This is a plugin for the tool flake8 tool for checking Python
soucre code.
"""
import logging
import re
import sys
import textwrap
import tokenize as tk
from itertools import chain, dropwhile
try:
from StringIO import StringIO
except ImportError: #... | 2.6875 | 3 |
chat.py | kato-im/katirc | 1 | 12777739 | import re
import os
from twisted.internet import defer
from twisted.python.failure import Failure
from kato import KatoHttpClient
from util import *
# characters that are disallowed from the channel name
CHANNEL_NAME_DISALLOWED = re.compile(r"[^a-zA-Z0-9_-]+", re.UNICODE)
# characters that are disallowed from the ni... | 2.109375 | 2 |
uqcsbot/scripts/pokemash.py | dhood/uqcsbot | 38 | 12777740 | <reponame>dhood/uqcsbot<filename>uqcsbot/scripts/pokemash.py
from uqcsbot import bot, Command
from re import match
from typing import Optional
POKEDEX = {"bulbasaur": 1,
"ivysaur": 2,
"venusaur": 3,
"charmander": 4,
"charmeleon": 5,
"charizard": 6,
"squ... | 2.109375 | 2 |
cpc/prepare_librispeech_data.py | lokhiufung/quick-and-dirty-dl | 0 | 12777741 | <reponame>lokhiufung/quick-and-dirty-dl<filename>cpc/prepare_librispeech_data.py
import argparse
import glob
import os
import json
import soundfile as sf
import pandas as pd
DATASETS = ['train-clean-100']
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('--data_root', '-D', type=str... | 2.71875 | 3 |
tests/test_youtube_sm_parser.py | shanedabes/youtube_sm_parser | 2 | 12777742 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Tests for `youtube_sm_parser` package."""
import pytest
import unittest.mock
import deepdiff
import collections
import os
import xmltodict
import json
from youtube_sm_parser import youtube_sm_parser
def rel_fn(fn):
dir_name = os.path.dirname(os.path.realpath(_... | 2.4375 | 2 |
run.py | gwanghyeongim/flask-blog | 0 | 12777743 | <filename>run.py
from flaskblog import create_app
app = create_app()
if __name__ == '__main__':
app.run(debug=False) # run this when the file is executed
| 1.976563 | 2 |
tool/gongzi.py | FlyAlCode/RCLGeolocalization-2.0 | 4 | 12777744 | # !/usr/bin/env python
# -*- coding:utf-8 -*-
age_init = 22
money_init = 16.0
ratio_1 = 1.05 # 每年增加10%
ratio_2 = 1.05
ratio_t = 0.96
# 毕业——自主
money = [money_init]
for age in range(age_init+1, age_init + 21):
money.append(money[-1] * ratio_1 * ratio_t)
# print(money[-1])
# 自主——挂掉
money_init_2 = money[-1... | 3.671875 | 4 |
sentiment/mBert.py | fajri91/minangNLP | 7 | 12777745 | <gh_stars>1-10
#!/usr/bin/env python
# coding: utf-8
# In[34]:
import json, glob, os, random
import argparse
import logging
import numpy as np
import pandas as pd
import torch
import torch.nn as nn
from sklearn.metrics import f1_score, accuracy_score
from transformers import BertTokenizer, BertModel, BertConfig
from... | 2.28125 | 2 |
SLpackage/private/pacbio/pythonpkgs/pbsvtools/lib/python2.7/site-packages/pbsv1/config.py | fanglab/6mASCOPE | 5 | 12777746 | <reponame>fanglab/6mASCOPE<filename>SLpackage/private/pacbio/pythonpkgs/pbsvtools/lib/python2.7/site-packages/pbsv1/config.py
"""
Class svconfig defines parameters for structural varation tools.
"""
from __future__ import absolute_import
import logging
import ConfigParser
import shutil
import StringIO
import traceback... | 2.171875 | 2 |
src/endplay/__init__.py | dominicprice/endplay | 4 | 12777747 | """
Endplay - A bridge tools library with generating, analysing and scoring.
Released under the MIT licence (see the LICENCE file provided with this distribution)
"""
import endplay._dds as _dds
from endplay.dds import *
from endplay.dealer import *
from endplay.interact import *
from endplay.parsers import ... | 1.210938 | 1 |
hard_coded_ground_truth.py | woctezuma/steam-descriptions | 1 | 12777748 | <gh_stars>1-10
# Objective: define a ground truth consisting of clusters of games set in the same fictional universe
import matplotlib.pyplot as plt
import steamspypi
def get_app_ids_which_app_name_contains(name_str='Half-Life'):
data_request = dict()
data_request['request'] = 'all'
data = steamspypi.do... | 2.8125 | 3 |
qpce/router.py | brunorijsman/quantum-path-computation-engine | 0 | 12777749 | """Quantum Router."""
import collections
class Router:
# TODO: Remove this when we have more methods
# pylint:disable=too-few-public-methods
"""A quantum router.
A quantum router object represents a quantum router that is part of a quantum network. Quantum
routers are interconnected by quantum li... | 3.5 | 4 |
ascii-art.py | guptaanmol184/ascii-art | 1 | 12777750 | <filename>ascii-art.py
#!/usr/bin/env python
from PIL import Image
from colorama import Fore, Back, Style, init
import os
import argparse
import subprocess
# resize to the size i want
def resize_image(im, max_width, max_height):
im.thumbnail((max_width//3, max_height)) # divide by 3 -> we draw each pixel py 3 let... | 3.4375 | 3 |