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 |
|---|---|---|---|---|---|---|
hal_fuzz/hal_fuzz/handlers/stm32f4_hal/stm32f4_i2c.py | diagprov/hal-fuzz | 117 | 12783451 | <filename>hal_fuzz/hal_fuzz/handlers/stm32f4_hal/stm32f4_i2c.py
import sys
from unicorn.arm_const import *
from ...util import *
import sys
from ..fuzz import fuzz_remaining, get_fuzz
from ...models.i2c import I2CModel
def HAL_I2C_Init(uc):
pass
def HAL_I2C_Mem_Read(uc):
# HAL_StatusTypeDef __fastcall HAL_I... | 2.046875 | 2 |
models/QSDM.py | rmit-ir/AnswerPassageQuality | 8 | 12783452 | """
Quality-biased ranking (Bendersky et al., 2011)
"""
import argparse
import bs4
import collections
import json
import math
# import re
import string
from smart_open import smart_open
# Module side
#
class Pipeline():
"""Feature extraction pipeline"""
def __init__(self):
self.jobs = []
def add... | 2.71875 | 3 |
tjiggle.py | beesperester/cinema4d-jiggle | 1 | 12783453 | import os
import c4d
import math
# Be sure to use a unique ID obtained from www.plugincafe.com
PLUGIN_ID = 123456790
#----begin_resource_section----
from bootstrap4c4d import Description, Assignment, Group, Container
crumb_percent_slider = [
Assignment("STEP", 1.0),
Assignment("UNIT", "PERCENT"),
Assignm... | 1.953125 | 2 |
accounts/migrations/0007_auto_20200708_2235.py | Ascensiony/Software-Dev-Project | 2 | 12783454 | <filename>accounts/migrations/0007_auto_20200708_2235.py
# Generated by Django 2.2.10 on 2020-07-08 17:05
import django.core.validators
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('accounts', '0006_user_summary'),
]
operations = [
mi... | 1.851563 | 2 |
Mortgage_Package/financial/ex_debtServiceRatio.py | ubco-mds-2020-labs/data-533-lab-4-lukavuko | 0 | 12783455 | <reponame>ubco-mds-2020-labs/data-533-lab-4-lukavuko
# To add a new cell, type '# %%'
# To add a new markdown cell, type '# %% [markdown]'
# %%
class debtServiceRatio:
"""
A class used to calculate debt service ratios and determine maximum annual and monthly mortgage payments
...
Attributes
--... | 2.140625 | 2 |
44.py | lycantropos/Project-Euler | 0 | 12783456 | from itertools import count
from utils import pentagonal
def pentagonal_number(index: int) -> int:
return index * (3 * index - 1) // 2
# TODO: improve this "bruteforcefully" working function
def pentagonal_numbers(offset: int) -> int:
for j in count(1):
p_j = pentagonal_number(j)
for s in r... | 3.40625 | 3 |
retropie/get_files.py | dmsun/Arch-Linux-Config | 0 | 12783457 | <reponame>dmsun/Arch-Linux-Config
#! /usr/bin python
import os
# change the directory to the rom hub
cwd = os.chdir("/home/pi/RetroPie/roms")
extensions = ['.srm', '.eep', '.state', '.hi', '.hs', '.fs'
'.dat', '.cfg', '.nv']
def get_files(directory=os.getcwd()):
with open("/hom... | 2.671875 | 3 |
Problem Set 3 - Student Version/reinforcement_learning.py | MuhammeedAlaa/MI-Assignemnets | 0 | 12783458 | <filename>Problem Set 3 - Student Version/reinforcement_learning.py
from typing import Callable, DefaultDict, Dict, Generic, List, Optional, Union
from agents import Agent
from environment import Environment, S, A
from helpers.mt19937 import RandomGenerator
from helpers.utils import NotImplemented
import json
from col... | 2.90625 | 3 |
utils.py | DandelionLau/NetworkCollections | 8 | 12783459 | <reponame>DandelionLau/NetworkCollections
"""
@FileName: utils.py
@Description: Implement utils
@Author : Ryuk
@CreateDate: 2019/12/26 9:28
@LastEditTime: 2019/12/26 9:28
@LastEditors: Ryuk
@Version: v0.1
"""
def getLayers(model):
"""
get each layer's name and its module
:param model:
:return: each ... | 2.578125 | 3 |
back-end/api/migrations/0009_auto_20161114_0228.py | tuftsjumbocode/bostonathleticsassociation | 2 | 12783460 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.2 on 2016-11-14 02:28
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('api', '0008_merge_20161114_0228'),
]
operations = [
migrations.AlterField(
... | 1.59375 | 2 |
tests/test_functions.py | enceladus-rex/chainer-transformer | 0 | 12783461 | from chainer_transformer.functions import generate_positional_encodings
import pytest
def test_generate_positional_encoding():
start = 0
end = 100
dim = 256
l = end - start
output = generate_positional_encodings(start, end, dim)
assert output.shape == (l, dim)
| 2.234375 | 2 |
python/gpu-enabled-multiprocessing.py | GangababuManam/tensorflow-101 | 832 | 12783462 | <reponame>GangababuManam/tensorflow-101<gh_stars>100-1000
import pandas as pd
import multiprocessing
from multiprocessing import Pool
def train(index, df):
import tensorflow as tf
import keras
from keras.models import Sequential
#------------------------------
#this block enables GPU enabled multiproc... | 2.875 | 3 |
scuole/campuses/views.py | texastribune/scuole | 1 | 12783463 | <filename>scuole/campuses/views.py
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from django.shortcuts import get_object_or_404
from django.views.generic import DetailView
from scuole.counties.models import County, CountyCohorts
from scuole.districts.models import District, District... | 2.046875 | 2 |
LEM_scripts_1.py | DavidLitwin/SpectralDiffusion | 2 | 12783464 | <reponame>DavidLitwin/SpectralDiffusion
# -*- coding: utf-8 -*-
"""
Created on Wed May 1 09:38:14 2019
@author: dgbli
Run spectral diffuser in a landscape evolution model. This code does not account
for a difference in boundary conditions between the diffusion model (periodic)
and the FastscapeEroder (fixed ... | 2.109375 | 2 |
Peach/Agent/linux.py | aleasims/Peach | 0 | 12783465 | <reponame>aleasims/Peach
#
# Copyright (c) <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, mer... | 1.914063 | 2 |
tests/unit/utils/test_context_processors.py | etienne86/oc_p13_team_spirit | 0 | 12783466 | <reponame>etienne86/oc_p13_team_spirit
"""
This module contains the unit tests related to
the context processors in app ``utils``.
"""
# from django.test import TestCase
| 1.304688 | 1 |
reviewboard/reviews/tests/test_template_tags.py | davidt/reviewboard | 1 | 12783467 | <reponame>davidt/reviewboard
from __future__ import unicode_literals
from django.contrib.auth.models import User
from django.template import Context, Template
from django.test.client import RequestFactory
from django.utils import six
from reviewboard.accounts.models import Profile
from reviewboard.testing import Test... | 2.28125 | 2 |
flan/flanintegration.py | bretlowery/flan | 3 | 12783468 | from abc import ABCMeta, abstractmethod
try:
from flan import istruthy, error, info
except:
from flan.flan import istruthy, error, info
pass
import settings
import os
import threading
import _thread as thread
def _timeout(exportname):
error('Flan->%s import timed out' % exportname)
thread.interrup... | 2.53125 | 3 |
logs/plot.py | xinyandai/distributed-compressed-sgd | 3 | 12783469 | <reponame>xinyandai/distributed-compressed-sgd
import matplotlib.pyplot as plt
import numpy as np
fontsize=44
ticksize=40
legendsize=30
plt.style.use('seaborn-white')
plt.figure(figsize=(12.8, 9.25))
def read_csv(file_name):
return np.genfromtxt(fname=file_name, delimiter=',', skip_header=1)
def _plot_setting... | 2.703125 | 3 |
test_lung_seg_scan_luna.py | Aryan98/lcprediction | 0 | 12783470 | import sys
import lasagne as nn
import numpy as np
import theano
import pathfinder
import utils
from configuration import config, set_configuration
from utils_plots import plot_slice_3d_4
import theano.tensor as T
import blobs_detection
import logger
import time
import multiprocessing as mp
import buffering
theano.con... | 1.796875 | 2 |
src/networks/lenet.py | francesco-p/FACIL | 243 | 12783471 | from torch import nn
import torch.nn.functional as F
class LeNet(nn.Module):
"""LeNet-like network for tests with MNIST (28x28)."""
def __init__(self, in_channels=1, num_classes=10, **kwargs):
super().__init__()
# main part of the network
self.conv1 = nn.Conv2d(in_channels, 6, 5)
... | 3.421875 | 3 |
shop/contexts.py | lbacon17/lb-fitness | 0 | 12783472 | from django.conf import settings
from django.shortcuts import get_object_or_404
from .models import Product
def favourites():
"""This view iterates through the favourites"""
favourite_items = []
shop_items = Product.objects.all()
for item in shop_items:
shop_item = get_object_or_404(Product, p... | 1.976563 | 2 |
mymario/level1_map.py | sriteja777/My_Mario | 1 | 12783473 | <filename>mymario/level1_map.py<gh_stars>1-10
"""
A module containing class for level 1 map
"""
from random import randrange
from irregular import print_cloud, IrregularObjects
from map import Map
from motion import MovingBridges, Enemies
from objects import Obj, Extras
import config
from music import Music
msc = Musi... | 3.40625 | 3 |
serve.py | racterub/ctfdeployer | 3 | 12783474 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Date : 2019-05-31 00:14:27
# @Author : Racter (<EMAIL>)
# @Profile : https://racterub.me
import yaml
from argparse import ArgumentParser
import os
import sys
import shutil
from subprocess import check_output
def parseParam():
parser = ArgumentParser()
... | 2.21875 | 2 |
sort-algorithm/heap_sort.py | free-free/Algorithm | 7 | 12783475 | <filename>sort-algorithm/heap_sort.py
# -*- coding:utf-8 -*-
import numpy as np
class MaxHeap(object):
def __init__(self, sz, data):
self.sz = sz
self.cnt = len(data)
self.heap = [0] * (self.sz + 1)
self.heap[1 : self.cnt] = data
self.build_heap()
def build_heap(sel... | 3.84375 | 4 |
ransac.py | vishwa91/pyimreg | 63 | 12783476 | <gh_stars>10-100
#!/usr/bin/env python
from scipy import *
from scipy.linalg import *
from scipy.special import *
from random import choice
from PIL import Image
import sys
from sift import *
from homography import *
import pdb
# New version coming soon.
def get_points(locs1, locs2, matchscores):
'''
Re... | 2.6875 | 3 |
modules/blockchain/blockchain.py | zeddo123/OpenBook | 12 | 12783477 | import copy as cp
from pprint import pprint as pp
from termcolor import colored
from modules.blockchain.block import *
from modules.blockchain.book import *
from modules.blockchain.transaction import *
class BlockChain:
"""BlockChain Object to be added to the chain
:Attributes:
:attr block_chain: All the bloc... | 3.3125 | 3 |
Fabric_socket.py | sgino209/Traffic_Simulation | 0 | 12783478 | <reponame>sgino209/Traffic_Simulation
__author__ = 'shahargino'
import simpy
class Fabric_socket:
"""This class implements the socket core of the Fabric"""
# ----------------------------------------------------------------------------------------
def __init__(self, name, params, parent, tb):
s... | 2.359375 | 2 |
scanpdf/sort.py | mjirik/scanpdf | 0 | 12783479 | <filename>scanpdf/sort.py
# /usr/bin/env python
# -*- coding: utf-8 -*-
import logging
logger = logging.getLogger(__name__)
# conda create -c conda-forge -n -c mcs07 scanpdf python=3.6 numpy scikit-image jupyter tesseract
import sys
import glob
import os.path as op
import os
import shutil
import numpy as np
from matpl... | 2.75 | 3 |
teachers_notes/api_example.py | kchiv/data_science_basics | 26 | 12783480 | <filename>teachers_notes/api_example.py
# show how product information is collected from an API
# first import packages
import urllib2
import json
import pandas as pd
# this is your api information
my_api_key = "<KEY>"
# build the api url, passing in your api key
url = "http://api.shopstyle.com/api/v2/"
ties = "{}p... | 3.703125 | 4 |
tests/test_generate.py | anthem-ai/fhir-types | 2 | 12783481 | from pathlib import Path
from tempfile import TemporaryDirectory
from typing import Any, Dict, List, Tuple
import pytest
from scripts.generate import (
CIRCULAR_PROPERTY_REFERENCES,
CIRCULAR_REFERENCES,
INT_PROPERTIES,
ObjectDefinition,
OneOfDefinition,
PrimitiveDefinition,
Property,
S... | 2.375 | 2 |
app/main.py | dogacuboh/doga-cuboh-snake | 0 | 12783482 | import json
import os
import bottle
import time
from app.api import ping_response, start_response, move_response, end_response
from app.board import update_board
from app.random_snake import random_move
from app.food_snake import food_move
from app.wall_snake import wall_move
from app.smart_snake import smart_move
f... | 2.203125 | 2 |
helpers/utils.py | mirceamironenco/GANs | 8 | 12783483 | <filename>helpers/utils.py
def print_flags(flags):
for key, value in vars(flags).items():
print("{}: {}".format(key, str(value)))
def load_mnist():
from tensorflow.examples.tutorials.mnist import input_data
return input_data.read_data_sets("./MNIST_data", one_hot=True)
| 2.53125 | 3 |
src/features/feature_selection.py | gaybro8777/data_science_for_health_unicamp | 1 | 12783484 | import os
import pandas as pd
import pdb
import seaborn as sns
import matplotlib.pyplot as plt
#import pymrmr
from scipy.stats import kendalltau, pearsonr, spearmanr
from sklearn.feature_selection import SelectKBest, mutual_info_classif, chi2, f_classif, RFE
import numpy as np
# Feature Importance Sklearn
# https://ma... | 3.390625 | 3 |
setup.py | rom1mouret/orthogonal_learning | 5 | 12783485 | <filename>setup.py
#!/usr/bin/env python
from distutils.core import setup
setup(name='orthocl',
version='0.1',
description='Orthogonal Continual Learning',
author='<NAME>',
url='https://github.com/rom1mouret/orthogonal_learning',
packages=['orthocl'],
)
| 1.171875 | 1 |
Code/EDA.py | mdevineni89/Final-Project-Group3 | 0 | 12783486 | #########
11/15/2021
#Generating a dataset for only categorical
df_categorical = df.select_dtypes(exclude=['number'])
df_categorical=df_categorical.drop(['Date.of.Birth','DisbursalDate'],axis=1)
df_categorical.head()
#Building a Dataset for numerical (continous)
df_continuous = df.select_dtypes(include=['number'])
df... | 3.25 | 3 |
tests/test_test_tools/test_test_cases.py | marcofavorito/agents-aea | 0 | 12783487 | <gh_stars>0
# -*- coding: utf-8 -*-
# ------------------------------------------------------------------------------
#
# Copyright 2018-2019 Fetch.AI Limited
#
# 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 ... | 1.773438 | 2 |
tangram/models.py | gutard/django-tangram | 0 | 12783488 | # -*- coding:utf-8 -*-
from django.db import models
from django.contrib.auth.models import User
BRANCHE_CHOICES = (
(1, u"Lutins"),
(2, u"Louveteaux"),
(3, u"Éclés"),
(4, u"Aînés"),
)
EXPLOGRAM_CHOICES = (
(1, u"Le pont des cultures"),
(2, u"On est cap !"),
(3, u"Filles/garçons"),
(4... | 2.046875 | 2 |
hello_git.py | zhengwenhong/landsat578-water | 0 | 12783489 | <gh_stars>0
print('Hello git, this is <NAME>')
print('Hello git, this is <NAME>')
print('Hello git, this is <NAME>')
print('Hello git, this is <NAME>')
print('Hello git, this is <NAME>') | 1.875 | 2 |
egg/platform_arm.py | TheMartianObserver/nsimd | 247 | 12783490 | <reponame>TheMartianObserver/nsimd<filename>egg/platform_arm.py
# Copyright (c) 2020 Agenium Scale
#
# 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 lim... | 1.648438 | 2 |
db_dump/etender2mongoscripts/dumptenderitems.py | EBRD-MoldovaOpenContracting/Moldova-Data-Load | 4 | 12783491 | import pymongo
import os
import json
import myconfig
dbEtenders = myconfig.getMongoDb()
tender_items_collection = dbEtenders.tender_items_collection
tender_items_collection.remove({})
def dumpJsonFileToDatabase(jsonfile, collection):
if(os.path.isfile(jsonfile)):
with open(jsonfile) as _file:
... | 2.9375 | 3 |
main.py | Forward-UIUC-2021F/haoxiang-sun-keyword-deduplication | 0 | 12783492 | from phrase_similarity import dedup_by_embedding, dedup_by_stemming
# Test1
result1 = dedup_by_stemming(['civilization', 'civil', 'computer'])
sol1 = ['civilization', 'computer']
if result1 == sol1:
print("Test 1 Passed")
else:
print("Test 1 Failed")
print(result1)
exit()
#Test 2
result... | 3.203125 | 3 |
employee_portal/vacation_schedule/views.py | Dmitriy200123/employee_portal | 0 | 12783493 | import xlwt
from django.shortcuts import get_object_or_404, HttpResponse
from django.urls import reverse_lazy
from django.utils.datetime_safe import datetime
from django.views.generic import DetailView, ListView, UpdateView, DeleteView, TemplateView
# Create your views here.
from employee_information_site.models import... | 2.140625 | 2 |
2020/day02/solve.py | h3ssto/advent_of_code | 0 | 12783494 | from _shared_python.aoc import *
#------------------------------------------------------------------------------#
INPUT = input_from_file(__file__)
INPUT = map_split(INPUT, r"-|\s+|:\s+")
INPUT = entries_as_tuples(INPUT, types = (int, int, str, str))
#-----------------------------------------------------------------... | 2.90625 | 3 |
code/single_scene_optimization.py | dukomoran/PESFM | 52 | 12783495 | import cv2 # DO NOT REMOVE
from datasets import SceneData, ScenesDataSet
import train
from utils import general_utils, path_utils
from utils.Phases import Phases
import torch
def train_single_model(conf, device, phase):
# Create data
scene_data = SceneData.create_scene_data(conf)
# Create model
mode... | 2.625 | 3 |
python/functest/sdk_test.py | spiralgenetics/biograph | 16 | 12783496 | <reponame>spiralgenetics/biograph<filename>python/functest/sdk_test.py
"""
sdk.py: Test the python SDK and ipython notebooks.
"""
import os
import glob
import queue
import unittest
import subprocess
import tabix
from python.functest.utils.setup import (
ftest_setup,
ftest_teardown,
ftest_module_setup
)
f... | 2.203125 | 2 |
backend/src/procyon_api/domain/exceptions/root.py | KitKod/Procyon | 0 | 12783497 | #
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not... | 1.820313 | 2 |
helpers.py | andodevel/rmbg | 0 | 12783498 | <gh_stars>0
import datetime
import os
import timeit
import cv2
import numpy as np
from config import get_logger
logger = get_logger()
class Timer:
"""Measure time used."""
def __init__(self, id: str, round_ndigits: int = 2):
self._id = id
self._round_ndigits = round_ndigits
self._s... | 2.578125 | 3 |
01-algorithm-design-and-techniques/5_dynamic_programming/knapsack.py | hamidgasmi/training.computerscience.algorithms-datastructures | 8 | 12783499 | <filename>01-algorithm-design-and-techniques/5_dynamic_programming/knapsack.py<gh_stars>1-10
import sys
def optimal_weight(W, w):
V = [[0 for j in range(W + 1)] for i in range(len(w) + 1)]
for i in range(1, len(w) + 1):
for j in range(1, W + 1):
V[i][j] = V[i - 1][j]
if w[... | 3.75 | 4 |
04.2_Comparative_MC.py | massimopizzol/B4B | 11 | 12783500 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jan 30 07:05:07 2018
@author: massimo
"""
from brightway2 import *
import pandas as pd
import numpy as np
from matplotlib import pyplot as plt
from scipy import stats
projects
projects.set_current('bw2_import_ecoinvent_3.4')
databases
db = Database("... | 2.796875 | 3 |
model_training/torch2npy.py | wurenzhi/-learned_ndv_estimator | 0 | 12783501 | from network import Regressor, Loss_gamma_0_6
import numpy as np
import skorch
from skorch import NeuralNetRegressor
from torch import optim
def load_model(load_cp, n_in=106,device='cuda'):
cp = skorch.callbacks.Checkpoint(dirname=load_cp)
net = NeuralNetRegressor(
Regressor(n_in=n_in),
criter... | 2.34375 | 2 |
Kapitel_1/_E1_int_string_adder.py | Geralonx/Classes_Tutorial | 1 | 12783502 | <filename>Kapitel_1/_E1_int_string_adder.py<gh_stars>1-10
# --- Diese Klasse soll demonstrieren, dass das 'other'-Arguemnt der 'Dunder'-Methods alles sein darf ---#
class IntStringAdder(int):
def __init__(self, number):
self.number = number
def __add__(self, other):
if isinstance(other, str):
... | 3.71875 | 4 |
odvm/cuboids.py | pmp-p/odvm | 3 | 12783503 | <reponame>pmp-p/odvm
def ijk1b_to_idx0_7( i, j, k ):
assert( 0 <= i <= 1 and 0 <= j <= 1 and 0 <= k <= 1 )
return ((k&1)<<2)|((j&1)<<1)|(i&1)
def idx0_7_to_ijk1b( idx ):
assert( 0 <= idx <= 7 )
return ( idx&1, (idx&2)>>1, (idx&4)>>2 )
def ijk2b_to_idx0_63( i, j, k ):
assert( 0 <= i <= 3 an... | 1.929688 | 2 |
offers/migrations/0002_alter_emailipo_data_sent.py | ccunhafinance/sistema | 0 | 12783504 | <reponame>ccunhafinance/sistema
# Generated by Django 3.2.5 on 2021-08-11 15:12
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('offers', '0001_initial'),
]
operations = [
migrations.AlterField(
m... | 1.40625 | 1 |
src/features/skip_gram.py | RausellLab/tiresias | 6 | 12783505 | import numpy as np
from gensim.models import Word2Vec
from src.utils import io
def run(
random_walk_files, output_file, dimensions=128, context_size=10, epochs=1, workers=1
):
"""Generates node vector embeddings from a list of files containing random
walks performed on different layers of a multilayer net... | 3.0625 | 3 |
greedy/basic/leetcode/F1282/Solution.py | ashtishad/problem-solving | 17 | 12783506 | <reponame>ashtishad/problem-solving<filename>greedy/basic/leetcode/F1282/Solution.py
# problem name: Group the People Given the Group Size They Belong To
# problem link: https://leetcode.com/problems/group-the-people-given-the-group-size-they-belong-to/
# contest link: (?)
# time: (?)
# author: ratul14
# other_tags: ... | 3.4375 | 3 |
src/bromine/utils/wait.py | Etiqa/bromine | 2 | 12783507 | <reponame>Etiqa/bromine
from selenium.webdriver.support.ui import WebDriverWait
class Wait(WebDriverWait):
def __init__(self, *args, **kwargs):
super(Wait, self).__init__(None, *args, **kwargs)
def until(self, method, message=''):
return super(Wait, self).until(lambda _: method(), message)
... | 2.625 | 3 |
python_challenges/project_euler/p034_digit_factorials.py | bruckhaus/challenges | 1 | 12783508 | import math
__author__ = 'tilmannbruckhaus'
class DigitFactorials:
"""
Digit factorials
Problem 34
145 is a curious number, as 1! + 4! + 5! = 1 + 24 + 120 = 145.
Find the sum of all numbers which are equal to the sum of the factorial of their digits.
Note: as 1! = 1 and 2! = 2 are not sums ... | 3.9375 | 4 |
GUI_tools/OpenMX_orbitals/PAO_parser.py | Hiroaki-Tanaka-0606/calcPSF | 1 | 12783509 | <reponame>Hiroaki-Tanaka-0606/calcPSF
# PAO_parser
# read .pao files (before or after optimized)
import re
import numpy as np
import math
import Config
class PAO_parser:
def __init__(self, filePath, optimized):
# variables
self.number_optpao=0
self.grid_output=0
self.maxL_pao=0
... | 2.609375 | 3 |
src/models/items/item.py | prajesh-ananthan/web-store | 0 | 12783510 | __author__ = "<NAME>"
class Item(object):
def __init__(self, name, price, url):
self.name = name
self.price = price
self.url = url
def __repr__(self):
return "<Item {} with url: {}".format(self.name, self.url)
| 3.359375 | 3 |
create_grid_layers.py | boris-fx/mocha-scripts | 6 | 12783511 | # BSD 3-Clause License
#
# Copyright (c) 2020, <NAME>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# ... | 1.226563 | 1 |
part_map/object.py | jdpatt/bga_color_map | 2 | 12783512 | """Class representing the object being modeled."""
import json
import logging
import re
from pathlib import Path
from typing import Dict, List, Tuple, Union
from natsort import natsorted
from openpyxl import load_workbook
class PartObject:
""" Load and create a part from a source """
def __init__(self, pins... | 2.859375 | 3 |
WebTree.py | Tinka8ell/Prayers-and-Readings | 0 | 12783513 | <reponame>Tinka8ell/Prayers-and-Readings
# parse html
# Read a requested web page into a "tree" and parse it.
#
# Requires a url and will take an optional dictionary of values
# to be sent as parameters on the HTTP GET.
from datetime import date
import os
from pathlib import Path
import re
... | 3.375 | 3 |
agi_ast/turbobil.py | roramirez/turbobil | 5 | 12783514 | #!/usr/bin/env python
'Turbobil agi Asterisk'
__author__ = "<NAME>"
__version__ = "0.1.2"
__email__ = "<EMAIL>"
import os
import sys
from turbodb import *
import logging
from agi import *
from dialer import *
#Type pay
PRE_PAY = 1
POST_PAY = 2
# INFO, DEBUG, WARNING, CRITICAL, ERROR
def set_logging(cfg_leve... | 2.3125 | 2 |
Python/Cracking the Coding Interview/Chapter 1_Arrays and Strings/1.6.py | honghaoz/Interview-Algorithm-in-Swift | 1 | 12783515 | # Given an image represented by NxN matrix,
# where each pixel in the image is 4 bytes,
# write a method to rotate the image by 90 degrees,
# In place?
# In place
from math import ceil
def rotate(m):
degree = len(m)
# Precondition
for eachLine in m:
if not degree == len(eachLine):
return False
# layer by la... | 3.5 | 4 |
anuga/parallel/tests/test_sequential_dist_sw_flow.py | samcom12/anuga_core | 136 | 12783516 | <reponame>samcom12/anuga_core
"""
Simple water flow example using ANUGA
Water driven up a linear slope and time varying boundary,
similar to a beach environment
This is a very simple test of the parallel algorithm using the simplified parallel API
"""
from __future__ import print_function
from __future__ import divis... | 2.65625 | 3 |
Examples/example.py | lorcan2440/SimpleTrussCalculator | 1 | 12783517 | <filename>Examples/example.py
import _import_helper # noqa
from Source import Truss_Calculator as tc
'''
It is recommended to use the factory functions to build trusses (Example 1).
However, it is also possible to directly create the objects using classes (Example 2).
'''
##########################################... | 3.296875 | 3 |
function1.py | shreya-n-kumari/python | 0 | 12783518 | <filename>function1.py
#Defining and Calling the Function in Python Script.
def list_product(my_list):
result = 1
for number in my_list:
result = result * number
return result
print(list_product([2, 3]))
print(list_product([2, 10, 15]))
def add_suffix(suffix = '.com'):
return 'g... | 3.734375 | 4 |
Cookie_Cutter.py | devcoinfet/Cookie_Inject0r | 0 | 12783519 | <reponame>devcoinfet/Cookie_Inject0r
import requests
import uuid
import subprocess
import os
import sys
import binascii
import json
from urllib3.exceptions import InsecureRequestWarning
from threading import Thread, Lock
from multiprocessing import Process, cpu_count
import telegram
from urllib.parse import urlparse
im... | 2 | 2 |
wsdet/modules/models/base/assigner/builder.py | DetectionBLWX/WSDDN.pytorch | 7 | 12783520 | '''
Function:
builder the assigner
Author:
<NAME>
'''
from .maxiouassigner import MaxIoUAssigner
'''builder the assigner'''
def BuildAssigner(cfg, **kwargs):
supported_assigners = {
'max_iou': MaxIoUAssigner,
}
assert cfg['type'] in supported_assigners, 'unsupport assigner type %s...' % cf... | 2.390625 | 2 |
Classes_and_Object_Programs/cls1.py | saratkumar17mss040/Python-lab-programs | 3 | 12783521 | # simple class - general class -1
class StudentDetails:
name = 'sam'
age = 21
college = 'ABC'
average = 9.2
# class StudentDetails object
s1 = StudentDetails()
print('Student details')
print('Name:',s1.name)
print('Age:', s1.age)
print('College', s1.college)
print('Average', s1.average)
| 3.90625 | 4 |
screen/title.py | wooky/xtremettt | 0 | 12783522 | import pygame, assets
from options import OptionsScreen
class TitleScreen:
def __init__(self, screen):
self.screen = screen
big_font = pygame.font.SysFont(assets.font, 90)
small_font = pygame.font.SysFont(assets.font, 24)
self.heading = small_font.render("Super Extreme", True, (255,255,255))
self.titl... | 2.875 | 3 |
moon.py | zhoudaxia233/icey | 0 | 12783523 | import random
import math
from PIL import Image
def sample(x, y, num_of_sample_directions=64):
s = 0.0
for i in range(num_of_sample_directions):
# random_rad = 2 * math.pi * random.uniform(0.0, 1.0)
random_rad = 2 * math.pi * (i + random.uniform(0.0, 1.0)) / num_of_sample_directions
s +... | 2.84375 | 3 |
utils/mongodb.py | josemcorderoc/twitterconstituyente | 0 | 12783524 | from pymongo.errors import BulkWriteError
import logging
import time
import tqdm
import tweepy
logging.basicConfig(format='[%(asctime)s] - %(name)s - %(funcName)s - %(levelname)s : %(message)s', level=logging.INFO)
log = logging.getLogger(__name__)
def bulk_write_to_mongo(collection, data):
to_insert = len(data)
... | 2.578125 | 3 |
main.py | VIVelev/Flappy-AI | 3 | 12783525 | <gh_stars>1-10
import numpy as np
from Game.main import Game
from NeuroEvolution.Population import Population
N_BIRDS = 15
MUTATION_RATE = 0.02
N_WINNERS = 2
pop = Population(N_BIRDS, MUTATION_RATE, n_winners=N_WINNERS)
game = Game(pop, n_birds=N_BIRDS)
game.run()
| 2.40625 | 2 |
basic/annotationtable.py | ChaitanyaArora/text2image | 10 | 12783526 | <reponame>ChaitanyaArora/text2image
import os
from common import ROOT_PATH
def niceName(qid):
return '0'if qid[1:-2] == '' else qid[1:-2]
def readAnnotations(inputfile, skip_0=True):
data = [(str.split(x)[0], int(str.split(x)[1])) for x in open(inputfile).readlines()]
names = [x[0] for x in data]
lab... | 2.703125 | 3 |
src/copy_mechanism/copy_layer.py | Ravi-0809/question-generation | 212 | 12783527 | from typing import Callable
from tensorflow.python.layers import base
from tensorflow.python.eager import context
from tensorflow.python.estimator import util as estimator_util
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import ops
from tensorflow.python.framework import tensor_sha... | 2.265625 | 2 |
tests/math/perm_test.py | muhrin/e3nn | 1 | 12783528 | import math
import pytest
from e3nn.math import perm
@pytest.mark.parametrize('n', [0, 1, 2, 3, 4, 5])
def test_inverse(n):
for p in perm.group(n):
ip = perm.inverse(p)
assert perm.compose(p, ip) == perm.identity(n)
assert perm.compose(ip, p) == perm.identity(n)
@pytest.mark.parametri... | 2.625 | 3 |
north-greenland/Elmer/4a_DIAGNOSTIC/PlotScript.py | ElmerCSC/ElmerIceCourses | 0 | 12783529 | <gh_stars>0
from paraview.simple import *
import sys
sys.path.append('../../Codes/PostProcessing')
from ToStreamLine import *
from PlotGroundingLine import *
"""
Simple script to show how to use pvpython to automatise
post processing
"""
StreamLine="../../Data/StreamLine/StreamLine.csv"
SaveFile="ResOnStreamLine.cs... | 2.21875 | 2 |
2017/day_01/day_01.py | viddrobnic/adventofcode | 0 | 12783530 | l = list(map(int, input()))
s_1, s_2 = 0, 0
for i in range(len(l)):
s_1 += l[i] if l[i] == l[(i + 1) % len(l)] else 0
s_2 += l[i] if l[i] == l[(i + len(l) // 2) % len(l)] else 0
print('Part One: {}\nPart Two: {}'.format(s_1, s_2))
| 3.3125 | 3 |
server/processes/services/schedule_checker.py | CloudReactor/task_manager | 0 | 12783531 | from typing import Generic, Optional, TypeVar
from abc import ABCMeta, abstractmethod
from datetime import datetime, timedelta
import logging
from crontab import CronTab
from dateutil.relativedelta import *
from django.db import transaction
from django.utils import timezone
from processes.common.reque... | 2.203125 | 2 |
e1.5/boot.py | vwallen/hcde539-a2020 | 0 | 12783532 | <gh_stars>0
import board
import digitalio
import storage
import os
# Make the file system writable
# Via: https://learn.adafruit.com/circuitpython-essentials/circuitpython-storage
# If the switch pin is connected to ground CircuitPython can write to the drive
# Also used this to re-enable writing after a bad boot.py e... | 3.15625 | 3 |
script/env_sds_ddpg_cont.py | cyberphantom/Selfie-Drone-Stick | 2 | 12783533 | <filename>script/env_sds_ddpg_cont.py
#!/usr/bin/env python
import time
import numpy as np
import pandas
import rospy
import tf
import cv2, os
from cv_bridge import CvBridge, CvBridgeError
from geometry_msgs.msg import Twist, Vector3Stamped, Pose, PoseWithCovarianceStamped
from sensor_msgs.msg import CompressedImage, ... | 1.820313 | 2 |
anypubsub/backends/memory.py | smarzola/anypubsub | 6 | 12783534 | <filename>anypubsub/backends/memory.py
from collections import defaultdict
from anypubsub.interfaces import PubSub, Subscriber
from six.moves.queue import Queue
from weakref import WeakSet
class MemorySubscriber(Subscriber):
def __init__(self, queue_factory):
self.messages = queue_factory(maxsize=0)
... | 2.453125 | 2 |
LED-control/software/scripts/setoff.py | jeremywrnr/life-of-the-party | 1 | 12783535 | import liblo
import time
addresses = [liblo.Address("192.168.1.3","2222"),liblo.Address("192.168.1.4","2222"),liblo.Address("192.168.1.5","2222"),liblo.Address("192.168.1.6","2222"),liblo.Address("192.168.1.7","2222"),liblo.Address("192.168.1.8","2222"),liblo.Address("192.168.1.9","2222"),liblo.Address("192.168.1.1... | 2.09375 | 2 |
tests/utils/utils.py | bossjones/ultron8 | 0 | 12783536 | <reponame>bossjones/ultron8<gh_stars>0
import logging
import random
import string
from typing import Dict
import requests
from requests.models import Response
from sqlalchemy.orm import Session
from starlette.testclient import TestClient
from ultron8.api import settings
logger = logging.getLogger(__name__)
def ra... | 2.34375 | 2 |
src/v1/views.py | Diaga/Spekit_Tech_Project | 0 | 12783537 | <reponame>Diaga/Spekit_Tech_Project
from rest_framework.viewsets import GenericViewSet, mixins
from . import models
from . import serializers
from . import filters
class TopicViewSet(GenericViewSet,
mixins.CreateModelMixin,
mixins.RetrieveModelMixin,
mixins.Li... | 1.96875 | 2 |
src/datasets/dataset_student.py | oscareriksson/FedML-master-thesis | 0 | 12783538 | <filename>src/datasets/dataset_student.py
from torch.utils.data import Dataset
class StudentData(Dataset):
def __init__(self, dataset):
self.dataset = dataset
def __getitem__(self, index):
if isinstance(index, list):
data, _ = self.dataset[[i for i in index]]
... | 3 | 3 |
shfl/differential_privacy/probability_distribution.py | joarreg/Sherpa.ai-Federated-Learning-Framework | 2 | 12783539 | import numpy as np
import abc
class ProbabilityDistribution(abc.ABC):
"""
Class representing the interface for a probability distribution
"""
@abc.abstractmethod
def sample(self, size):
"""
This method must return an array with length "size", sampling the distribution
# A... | 3.890625 | 4 |
service/user_service.py | LianGee/galio | 8 | 12783540 | <filename>service/user_service.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @File : user_service.py
# @Author: zaoshu
# @Date : 2020-02-10
# @Desc :
import json
from common.exception import ServerException
from model.user import User
class UserService:
@classmethod
def get_user_from_cas_resp(cls, r... | 2.453125 | 2 |
core/app/models/point.py | bitreport-org/Bitreport | 3 | 12783541 | <reponame>bitreport-org/Bitreport
class Point:
info = None
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
return f"Point({self.x}, {self.y}), {self.info}"
def __eq__(self, other):
return (self.x == other.x) and (self.y == other.y)
def __hash__... | 3.046875 | 3 |
GoogleAppEngine_Side/main.py | nickolyamba/android-chem-app | 0 | 12783542 | <filename>GoogleAppEngine_Side/main.py
import webapp2
from google.appengine.api import oauth
config = {'Root':'default'}
app = webapp2.WSGIApplication([
('/supplier', 'supplier.Supplier'),
('/chemical', 'chemical.Chemical'),
('/solution', 'solution.Solution'),
('/signin', 'signin.GetToken'),
], d... | 2.765625 | 3 |
morphodynamics/landscapes/analysis/save_ims.py | hcbiophys/morphodynamics | 1 | 12783543 | import tensorflow as tf
import numpy as np
import matplotlib
matplotlib.use('agg')
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import copy
from morphodynamics.landscapes.utils import get_meshgrid
from morphodynamics.landscapes.analysis.get_fields import *
from morphodynamics.landscapes.analy... | 2.21875 | 2 |
nso/test_api.py | caputomarcos/network-programmability-stream | 120 | 12783544 | <reponame>caputomarcos/network-programmability-stream
#!/usr/bin/env python3
import ncs
from ncs.maagic import Root
from typing import Iterator, Tuple
NSO_USERNAME = 'admin'
NSO_CONTEXT = 'python'
# NSO_GROUPS = ['ncsadmin']
def get_device_name(nso: Root) -> Iterator[Tuple[str, str]]:
for device in nso.devices.... | 2.0625 | 2 |
test/test_macro/test_system_macro.py | takahish/lispy | 4 | 12783545 | # Copyright 2019 <NAME>. 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 applicable law or agree... | 2.28125 | 2 |
backend/routers/timeline.py | DavidLee0216/SWOOSH | 0 | 12783546 | from flask import request, Blueprint
from controllers import timelines
from pkg.warpResponse import warpResponse
timeline = Blueprint('timeline', __name__)
@timeline.route("/", methods=['GET'])
def getAllTimelines():
resp, code = timelines.FindAll()
if resp is not None:
return warpResponse(resp)
... | 2.484375 | 2 |
glue_vaex/__init__.py | glue-viz/glue-vaex | 0 | 12783547 | from __future__ import absolute_import, division, print_function
import os
import glob
from glue.logger import logger
from glue.core.data import Data
from glue.config import data_factory
import vaex.hdf5.dataset
from .data import DataVaex
def is_vaex_file(source):
return vaex.hdf5.dataset.Hdf5MemoryMapped.can_o... | 2.40625 | 2 |
src/python/artisynth_envs/envs/point2point_env.py | amir-abdi/artisynth-rl | 4 | 12783548 | <filename>src/python/artisynth_envs/envs/point2point_env.py
import numpy as np
from common import constants as c
from common.config import setup_logger
from artisynth_envs.artisynth_base_env import ArtiSynthBase
logger = setup_logger()
class Point2PointEnv(ArtiSynthBase):
def __init__(self, goal_threshold, wait... | 2.328125 | 2 |
pyapprox/benchmarks/spectral_diffusion.py | ConnectedSystems/pyapprox | 26 | 12783549 | import numpy as np
import inspect
from scipy.linalg import qr as qr_factorization
from copy import deepcopy
from pyapprox.utilities import cartesian_product, outer_product
from pyapprox.univariate_polynomials.quadrature import gauss_jacobi_pts_wts_1D
from pyapprox.barycentric_interpolation import (
compute_barycen... | 2.1875 | 2 |
base.py | Lemma1/DPFE | 16 | 12783550 | import numpy as np
import pandas as pd
import datetime
import os
import matplotlib.pyplot as plt
import matplotlib
import networkx as nx
import pickle
from collections import OrderedDict
import copy
from scipy.sparse import csr_matrix
from scipy import io
import seaborn as sns
import joblib
class Link:
def __init_... | 2.171875 | 2 |