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 |
|---|---|---|---|---|---|---|
tests/chem/test_mol.py | ShantamShorewala/aizynthfinder | 219 | 39400 | import pytest
from rdkit import Chem
from aizynthfinder.chem import MoleculeException, Molecule
def test_no_input():
with pytest.raises(MoleculeException):
Molecule()
def test_create_with_mol():
rd_mol = Chem.MolFromSmiles("O")
mol = Molecule(rd_mol=rd_mol)
assert mol.smiles == "O"
def ... | 2.453125 | 2 |
agents/agent_loader.py | JCKing97/Agents4Asteroids | 1 | 39401 | <gh_stars>1-10
from typing import List, Type
from game.agent import Agent
import os
from importlib import import_module
import inspect
def load_agents() -> List[Type[Agent]]:
"""
:return: all available agent types currently in the system.
"""
agents: List[Type[Agent]] = []
agent_dir = os.path.dirn... | 2.921875 | 3 |
src/qa_data_augmentation_script/random_data_split.py | zxgx/Graph2Seq-for-KGQG | 24 | 39402 | <reponame>zxgx/Graph2Seq-for-KGQG<gh_stars>10-100
import argparse
import random
import os
import json
def load_ndjson(file):
data = []
try:
with open(file, 'r') as f:
for line in f:
data.append(json.loads(line.strip()))
except Exception as e:
raise e
return ... | 2.609375 | 3 |
MultiRatMaze.py | MarcusRainbow/Maze | 0 | 39403 | <filename>MultiRatMaze.py
from typing import List, Set, Optional, Tuple
from random import randrange, shuffle, random
from RatInterface import Rat, MazeInfo
from SimpleRats import AlwaysLeftRat, RandomRat
from SimpleMaze import random_maze, render_graph, validate_edges
from Localizer import Localizer, NonLocalLoca... | 3.296875 | 3 |
splinter/cmstest/resourcePlatform/order.py | zhaopiandehuiyiforsang/python_test | 0 | 39404 | <gh_stars>0
# -*- coding:utf-8 -*-
import init_env
import time
from splinter import Browser
class Order:
"""创建订单
"""
def __init__(self, browser=None):
self.browser = browser
# 1.创建订单
self.create()
# 2.提交订单并生效
self.active()
def create(self):
"""创建订单
... | 2.53125 | 3 |
day13/1.py | lvrcek/advent-of-code-2020 | 2 | 39405 | <filename>day13/1.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Advent of Code 2020
Day 13, Part 1
"""
def main():
with open('in.txt') as f:
lines = f.readlines()
arrival = int(lines[0].strip())
bus_ids = []
for n in lines[1].strip().split(','):
if n == 'x':
conti... | 3.734375 | 4 |
autorest/multiapi/models/config.py | qwordy/autorest.python | 0 | 39406 | # -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
import jso... | 1.960938 | 2 |
mail/models.py | drscream/kumquat | 12 | 39407 | <filename>mail/models.py
from django.db import models
from django.utils.translation import ugettext_lazy as _
from passlib.hash import sha512_crypt
from kumquat.models import Domain
default_length = 255
class Account(models.Model):
name = models.CharField(max_length=default_length)
domain = models.Foreign... | 2.265625 | 2 |
src/nets.py | zpreisler/spectral | 0 | 39408 | <filename>src/nets.py<gh_stars>0
import torch
from torch import nn,optim
from torch.utils.data import Dataset,DataLoader
from torch.optim import Adam
from matplotlib.pyplot import show,figure,imshow,draw,ion,pause,subplots,subplots_adjust
from numpy import log,array,asarray,save
class Skip(nn.Module):
def __init_... | 2.25 | 2 |
RNN/data/gru_loadNtest.py | aroongta/Pedestrian_Trajectory_Prediction | 24 | 39409 | <filename>RNN/data/gru_loadNtest.py
#Script to load GRU model trained on all datasets and test
# import relevant libraries
import torch
import torch.nn as nn
import torch.optim as optim
import matplotlib
import numpy as np
import trajectories
import loader
import argparse
import gc
import logging
import os
import sys
i... | 2.453125 | 2 |
rdbtools3/__init__.py | popravich/rdbtools3 | 3 | 39410 | <reponame>popravich/rdbtools3
from .parser import parse_rdb_stream, RDBItem
from .exceptions import FileFormatError, RDBValueError
__version__ = '0.1.2'
(RDBItem, parse_rdb_stream,
FileFormatError, RDBValueError) # pragma: no cover
| 1.03125 | 1 |
vis_imagine_static_voxels/resize_voxel.py | mihirp1998/EmbLang | 3 | 39411 | import tensorflow as tf
def sum():
return tf.ones([2,2,2])
def resize_by_axis(image, dim_1, dim_2, ax):
resized_list = []
unstack_img_depth_list = tf.unstack(image, axis = ax)
for i in unstack_img_depth_list:
resized_list.append(tf.image.resize(i, [dim_1, dim_2]))
stack_img = tf.stack(resized_list, axis=ax)
... | 2.671875 | 3 |
PassInstrument/inference/SpeedupEvaluation/RunSpeedupEval.py | JaredCJR/ThesisTools | 1 | 39412 | #!/usr/bin/env python3
import os, sys, signal
import multiprocessing
import subprocess as sp
import shutil
import shlex
import psutil
import time
import csv
import json
import pytz
from datetime import datetime
import Lib as lib
sys.path.append('/home/jrchang/workspace/gym-OptClang/gym_OptClang/envs/')
import RemoteWo... | 1.929688 | 2 |
pylith/problems/__init__.py | joegeisz/pylith | 1 | 39413 | #!/usr/bin/env python
#
# ----------------------------------------------------------------------
#
# <NAME>, U.S. Geological Survey
# <NAME>, GNS Science
# <NAME>, University of Chicago
#
# This code was developed as part of the Computational Infrastructure
# for Geodynamics (http://geodynamics.org).
#
# Copyright (c) ... | 2.046875 | 2 |
examples/cp/misorientation.py | ajey091/neml | 6 | 39414 | #!/usr/bin/env python3
import sys
sys.path.append('../..')
import numpy as np
from neml.cp import crystallography
from neml.math import rotations
import matplotlib.pyplot as plt
if __name__ == "__main__":
N = 300
orientations = rotations.random_orientations(N)
sgroup = crystallography.SymmetryGroup("432")
... | 2.6875 | 3 |
valid triangle.py | Tanuka-Mondal/Competi | 1 | 39415 | t = int(input())
while (t!=0):
a,b,c = map(int,input().split())
if (a+b+c == 180):
print('YES')
else:
print('NO')
t-=1
| 3.15625 | 3 |
proper_forms/fields/email.py | jpsca/pforms | 2 | 39416 | from .text import Text
from ..ftypes import type_email
__all__ = ("Email", )
class Email(Text):
"""Validates and normalize an email address using the
JoshData/python-email-validator library.
Even if the format is valid, it cannot guarantee that the email is real, so the
purpose of this function is ... | 3.546875 | 4 |
dm/preprocessing/step5.py | NeilKleistGao/Dejavu | 2 | 39417 | import numpy
import pandas as pd
# 替换异常值
if __name__ == '__main__':
df = pd.read_csv("../dataset/temp4.csv")
df.replace(to_replace='-', value=0.5, inplace=True)
print(df.head(3))
df.to_csv("../dataset/temp5.csv", index=False)
| 2.953125 | 3 |
src/memoprop/__about__.py | lewisacidic/memoized-property | 1 | 39418 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2019 <NAME>
# License: MIT license
"""Metadata for memoprop."""
# guard import
# in setup.py we use run this with runpy so the import will fail
try:
from ._version import get_versions
__version__ = get_versions()["version"]
del get_versions
ex... | 1.585938 | 2 |
cblaster/gui/main.py | bramvanwersch/cblaster | 0 | 39419 | <reponame>bramvanwersch/cblaster<filename>cblaster/gui/main.py
"""A basic GUI for cblaster."""
import sys
import builtins
import PySimpleGUI as sg
from cblaster import __version__
from cblaster import main, extract as cb_extract
from cblaster.gui import search, makedb, citation, gne, extract
sg.theme("Lightgrey1")... | 2.421875 | 2 |
MRTasks/parsingTasks/listS3Files.py | ArulselvanMadhavan/Artist_Recognition_from_Audio_Features | 1 | 39420 | <reponame>ArulselvanMadhavan/Artist_Recognition_from_Audio_Features<filename>MRTasks/parsingTasks/listS3Files.py
import sys
__author__ = 'arul'
from boto.s3.connection import S3Connection
if __name__ == '__main__':
access_key = sys.argv[1]
access_secret = sys.argv[2]
conn = S3Connection(access_key,acces... | 2.125 | 2 |
TestMain/cool.py | ppcrong/TestMain | 0 | 39421 | <filename>TestMain/cool.py
# cool.py
def cool_func():
print('cool_func(): Super Cool!')
print('__name__:', __name__)
if __name__ == '__main__':
print('Call it locally')
cool_func()
| 2.0625 | 2 |
superlists/apps.py | cidyoon/django-blog | 0 | 39422 | from django.apps import AppConfig
class SuperlistsConfig(AppConfig):
name = 'superlists'
| 1.0625 | 1 |
alembic/versions/0b7ccbfa8f7c_add_order_and_hide_from_menu_to_page_.py | matslindh/kimochi | 0 | 39423 | <filename>alembic/versions/0b7ccbfa8f7c_add_order_and_hide_from_menu_to_page_.py
"""Add order and hide_from_menu to Page model
Revision ID: 0b7ccbfa8f7c
Revises: <KEY>
Create Date: 2016-03-23 16:33:44.047433
"""
# revision identifiers, used by Alembic.
revision = '0b7ccbfa8f7c'
down_revision = '<KEY>'
branch_labels ... | 1.328125 | 1 |
Analytic/plots.py | benvchurch/project-eva | 1 | 39424 | from __future__ import division
import numpy as np
from scipy import special
from numpy import log, exp, sin ,cos, pi, log10, sqrt
from scipy.integrate import quad, dblquad, cumtrapz
from matplotlib import pyplot as plt
import time
import CDM_SubHalo_Potential
import FDM_SubHalo_Potential
#integral precision
p = 2
... | 2.09375 | 2 |
operationGenerationTests.py | moritz155/GeneticPy | 11 | 39425 | import unittest
import datetime
import genetic
import random
class Node:
Value = None
Left = None
Right = None
def __init__(self, value, left=None, right=None):
self.Value = value
self.Left = left
self.Right = right
def isFunction(self):
return self.Left is not No... | 3.09375 | 3 |
src/schema/create_minio_bucket.py | mdpham/minio-loompy-graphene | 0 | 39426 | from graphene import Schema, Mutation, String, Field, ID, List
from minio import Minio
from minio.error import ResponseError
from .minio_bucket import MinioBucket
from minio_client.client import minio_client
class CreateMinioBucket(Mutation):
# Use minio bucket type definition to be returned when created
Output ... | 2.609375 | 3 |
tests/unit/schema/test_links.py | eyadgaran/openapi-core | 0 | 39427 | import mock
import pytest
from openapi_core.schema.links.models import Link
from openapi_core.schema.servers.models import Server
class TestLinks(object):
@pytest.fixture
def link_factory(self):
def link_factory(request_body, server):
parameters = {
'par1': mock.sentinel.... | 2.4375 | 2 |
ex105.py | erikamaylim/Python-CursoemVideo | 0 | 39428 | <reponame>erikamaylim/Python-CursoemVideo
"""Faça um programa que tenha uma função notas() que pode receber várias notas de alunos
e vai retornar um dicionário com as seguintes informações:
– Quantidade de notas
- A maior nota
– A menor nota
– A média da turma
– A situação (opcional)"""
def notas(* num, s=False):
... | 4.03125 | 4 |
swigwin-3.0.12/Examples/test-suite/python/swigobject_runme.py | bostich83/atomic_swig | 0 | 39429 | <filename>swigwin-3.0.12/Examples/test-suite/python/swigobject_runme.py
from swigobject import *
a = A()
a1 = a_ptr(a)
a2 = a_ptr(a)
if a1.this != a2.this:
raise RuntimeError
lthis = long(a.this)
# match pointer value, but deal with leading zeros on 8/16 bit systems and
# different C++ compilers interpretati... | 2.34375 | 2 |
com/LimePencil/Q2164/Main.py | LimePencil/baekjoonProblems | 2 | 39430 | import sys
from collections import deque
n = int(sys.stdin.readline())
deck = deque(list(range(1, n+1)))
for i in range(n-1):
deck.popleft()
deck.append(deck.popleft())
print(str(deck.pop()))
| 3.25 | 3 |
contrib/mypy/examples/src/python/mypy_plugin/settings.py | anthonyjpratti/pants | 1 | 39431 | # Copyright 2019 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from django.urls import URLPattern
DEBUG: bool = True
DEFAULT_FROM_EMAIL: str = '<EMAIL>'
SECRET_KEY: str = 'not so secret'
MY_SETTING: URLPattern = URLPattern(pattern='foo', callback=l... | 1.757813 | 2 |
function/python/brightics/function/statistics/__init__.py | janrenz/studio | 0 | 39432 | from .profile_table import profile_table
from .correlation import correlation
from .pairplot import pairplot
from .anova import bartletts_test
from .anova import oneway_anova
from .anova import tukeys_range_test | 1.007813 | 1 |
modules/hello-world/dags/hello_world.py | nalin-adhikari/apache-airflow | 0 | 39433 | import json
from datetime import timedelta, datetime
from requests import get
from airflow import DAG
from airflow.models import Variable
from airflow.operators.python_operator import PythonOperator
# Config variables
# dag_config = Variable.get("hello_world_variables", deserialize_json=True)
default_args = {
'o... | 2.796875 | 3 |
src/thex/apps/utils/signal_utils.py | harris-2374/THEx | 0 | 39434 | from pathlib import Path
import dash_core_components as dcc
import dash_bootstrap_components as dbc
import dash_html_components as html
import plotly
import plotly.express as px
import plotly.graph_objects as go
from plotly.subplots import make_subplots
# -------------------- Graphing Functions --------------------
... | 2.765625 | 3 |
tests/unit/test_ncit.py | cancervariants/disease-normalization | 0 | 39435 | <reponame>cancervariants/disease-normalization
"""Test NCIt source."""
import pytest
from disease.schemas import MatchType, SourceName
from disease.query import QueryHandler
@pytest.fixture(scope='module')
def ncit():
"""Build NCIt ETL test fixture."""
class QueryGetter:
def __init__(self):
... | 2.375 | 2 |
pytglib/api/types/message.py | iTeam-co/pytglib | 6 | 39436 | <gh_stars>1-10
from ..utils import Object
class Message(Object):
"""
Describes a message
Attributes:
ID (:obj:`str`): ``Message``
Args:
id (:obj:`int`):
Message identifier, unique for the chat to which the message belongs
sender_user_id (:obj:`int`):
... | 2.546875 | 3 |
trainer/migrations/0023_userpretest.py | tthelen/interpunct | 2 | 39437 | <reponame>tthelen/interpunct
# -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2018-05-18 08:55
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('trainer', '0022_auto_20180517_14... | 1.65625 | 2 |
CsvToDynamo.py | cushind/csv-to-dynamodb | 2 | 39438 | import boto3
import csv
import json
import argparse
'''
You need to have aws configured with access tokens prior to running this script (use aws configure)
'''
def batch_create(table, csv_file_name, column_names):
'''
Can Handle many puts at one time. Boto3 gives an example of 50, even though
max batch s... | 2.859375 | 3 |
qcdb/molecule/parker.py | loriab/qccddb | 8 | 39439 | <gh_stars>1-10
import math
import numpy as np
import qcelemental as qcel
BOND_FACTOR = 1.2 # fudge factor for bond length threshold
_expected_bonds = {
'H': 1,
'C': 4,
'N': 3,
'O': 2,
'F': 1,
'P': 3,
'S': 2,
}
def xyz2mol(self):
"""Returns a string of Molecule formatted for mol2.
... | 2.59375 | 3 |
Projects/CS_VQE/UnitaryPartitioning_myriad_on_FULL_H_LCU.py | AlexisRalli/VQE-code | 1 | 39440 | import numpy as np
import scipy as sp
import ast
import os
from quchem.Unitary_Partitioning.Graph import Clique_cover_Hamiltonian
import quchem.Misc_functions.conversion_scripts as conv_scr
from copy import deepcopy
from quchem.Unitary_Partitioning.Unitary_partitioning_LCU_method import LCU_linalg_Energy
from openf... | 1.796875 | 2 |
notebooks/00-00-inspect-orig-files.py | will-henney/teresa-pn-ou5 | 0 | 39441 | # ---
# jupyter:
# jupytext:
# formats: ipynb,py:light
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.13.0
# kernelspec:
# display_name: Python 3 (ipykernel)
# language: python
# name: python3
# ---
# # PN Ou 5:... | 2.390625 | 2 |
common/create_public_vn.py | vkolli/contrail-test-perf | 1 | 39442 | import project_test
from common.contrail_test_init import ContrailTestInit
from common.connections import ContrailConnections
import os
import fixtures
from test import BaseTestCase
import time
from floating_ip import *
from vn_test import *
from control_node import *
from common import isolated_creds
from tcutils.util... | 1.90625 | 2 |
aiotdlib/api/functions/get_voice_chat_available_participants.py | jraylan/aiotdlib | 0 | 39443 | # =============================================================================== #
# #
# This file has been generated automatically!! Do not change this manually! #
# ... | 2.75 | 3 |
tests/test_tree.py | tgragnato/geneva | 1,182 | 39444 | import logging
import os
from scapy.all import IP, TCP
import actions.tree
import actions.drop
import actions.tamper
import actions.duplicate
import actions.utils
import layers.packet
def test_init():
"""
Tests initialization
"""
print(actions.action.Action.get_actions("out"))
def test_count_leaves... | 2.5625 | 3 |
l2address/formatter.py | EgorBlagov/l2address | 1 | 39445 | <reponame>EgorBlagov/l2address
import re
from abc import ABC, abstractmethod
from .utils import parse_hex, per_join
class Formatter(ABC):
def _to_clean_str(self, value, max_value):
value_str = str(hex(value))[2:]
full_mac_str = '0' * (self._hex_digits_count(max_value) -
... | 2.828125 | 3 |
pytests/ent_backup_restore/provider/s3.py | couchbaselabs/testrunner-bharath | 0 | 39446 | #!/usr/bin/python3
import json
import re
import boto3
import botocore
from . import provider
class S3(provider.Provider):
def __init__(self, access_key_id, bucket, cacert, endpoint, no_ssl_verify, region, secret_access_key, staging_directory):
"""Create a new S3 provider which allows interaction with S3... | 2.34375 | 2 |
pythonProject/05al137Random/rd.py | D-Wolter/PycharmProjects | 0 | 39447 | import random
import string
# Gera um número inteiro entra A e B
# inteiro = random.randint(10, 20)
# Gera um número de ponto flutuante entra A e B
# flutuante = random.uniform(10, 20)
# Gera um número de ponto flutuante entre 0.0 e 1.0
flutuante = random.random()
# Gerar um número aleatório usando a função range()... | 3.953125 | 4 |
chris_backend/users/tests/test_serializers.py | PintoGideon/ChRIS_ultron_backEnd | 0 | 39448 |
import logging
from django.test import TestCase
from rest_framework import serializers
from users.serializers import UserSerializer
class UserSerializerTests(TestCase):
"""
Generic user view tests' setup and tearDown
"""
def setUp(self):
# avoid cluttered console output (for instance logg... | 2.828125 | 3 |
pegtree/optimizer.py | Caterpie-poke/pegtree | 1 | 39449 | from .peg import *
# # PRange Utilities
def bitsetRange(chars, ranges):
cs = 0
for c in chars:
cs |= 1 << ord(c)
r = ranges
while len(r) > 1:
for c in range(ord(r[0]), ord(r[1])+1):
cs |= 1 << c
r = r[2:]
return cs
def stringfyRange(bits):
c = 0
s = N... | 2.703125 | 3 |
lib/ipc/async_emitter.py | stevenman42/architus | 0 | 39450 | import json
from aio_pika import Message, DeliveryMode, ExchangeType
from lib.ipc.util import poll_for_async_connection
class Emitter:
def __init__(self):
self.connection = None
self.event_exchange = None
async def connect(self, loop):
# Perform connection
self.connection = a... | 2.5625 | 3 |
pys/classes/annotations.py | Xithrius/Examples | 0 | 39451 | import typing as t
def test0(a: t.Union[str, int]) -> t.Any:
pass
| 2.171875 | 2 |
day_4/day_4_improvements/tests/test_user_edit.py | dmchu/Pytest_REST_API_with_Allure | 0 | 39452 | <gh_stars>0
import allure
from day_4.day_4_improvements.lib.base_case import BaseCase
from day_4.day_4_improvements.lib.assersions import Assertions as AS
from day_4.day_4_improvements.lib.my_requests import MyRequests as MR
from day_4.day_4_improvements.lib.helpers import Helpers as HP
@allure.epic("User Profile Edi... | 2.46875 | 2 |
test/example/__init__.py | fieldOfView/izzyPythonPlugin | 6 | 39453 | from .example import *
| 1.210938 | 1 |
backend/models/__init__.py | Hori1234/gastech-project | 0 | 39454 |
from .users import User
__all__ = [
'User']
| 1.15625 | 1 |
bandit_github_formatter/formatter.py | epsylabs/action-bandit | 8 | 39455 | <filename>bandit_github_formatter/formatter.py
r"""
==============
GitHub Formatter
==============
This formatter outputs the issues as plain text.
:Example:
.. code-block:: none
>> Issue: [B301:blacklist_calls] Use of unsafe yaml load. Allows
instantiation of arbitrary objects. Consider yaml.safe_load()... | 2.640625 | 3 |
usecase/usecase-cordova-android-tests/samples/SharedModeLibraryDownload4.x/res/test.py | JianfengXu/crosswalk-test-suite | 0 | 39456 | <gh_stars>0
import os
import commands
import sys
import json
from optparse import OptionParser
global CROSSWALK_VERSION
with open("../../tools/VERSION", "rt") as pkg_version_file:
pkg_version_raw = pkg_version_file.read()
pkg_version_file.close()
pkg_version_json = json.loads(pkg_version_raw)
CROSSWALK_... | 2.359375 | 2 |
examples/python/simple_triangulation_3.py | chrisidefix/cgal-bindings | 33 | 39457 | <gh_stars>10-100
from CGAL.CGAL_Kernel import Point_3
from CGAL.CGAL_Triangulation_3 import Delaunay_triangulation_3
from CGAL.CGAL_Triangulation_3 import Delaunay_triangulation_3_Cell_handle
from CGAL.CGAL_Triangulation_3 import Delaunay_triangulation_3_Vertex_handle
from CGAL.CGAL_Triangulation_3 import Ref_Locate_ty... | 2.15625 | 2 |
lims/inventory/views.py | sqilz/LIMS-Backend | 12 | 39458 | <reponame>sqilz/LIMS-Backend
import io
import json
from django.core.exceptions import ObjectDoesNotExist
from pint import UnitRegistry
import django_filters
from rest_framework import viewsets
from rest_framework.response import Response
from rest_framework.decorators import detail_route, list_route
from rest_frame... | 1.851563 | 2 |
python/xfr/models/vggface.py | rwe0214/xfr | 52 | 39459 | # Copyright 2019 Systems & Technology Research, LLC
# Use of this software is governed by the license.txt file.
import os
import numpy as np
import torch
import torch.nn as nn
import torchvision.transforms as transforms
import torch.nn.functional as F
from PIL import ImageFilter
def prepare_vggface_image(img):
... | 2.203125 | 2 |
easy/1356-Sort Integers by The Number of 1 Bits.py | Davidxswang/leetcode | 2 | 39460 | """
https://leetcode.com/problems/sort-integers-by-the-number-of-1-bits/
Given an integer array arr. You have to sort the integers in the array in ascending order by the number of 1's in their binary representation and in case of two or more integers have the same number of 1's you have to sort them in ascending order.... | 4.09375 | 4 |
server/plugins/machine_detail_ard_info/scripts/ard_info.py | gregneagle/sal | 2 | 39461 | #!/usr/bin/python
import os
import sys
sys.path.append("/usr/local/munki/munkilib")
import FoundationPlist
RESULTS_PATH = "/usr/local/sal/plugin_results.plist"
def main():
ard_path = "/Library/Preferences/com.apple.RemoteDesktop.plist"
if os.path.exists(ard_path):
ard_prefs = FoundationPlist.read... | 2.0625 | 2 |
biquad_filter_original.py | ignaciodsimon/optimised_biquad_filter | 0 | 39462 | <gh_stars>0
'''
Standard implementation of a biquad filter
<NAME> 2018.
'''
import math
from enum import Enum
class BiquadFilterCoefficients():
def __init__(self, b0=1.0, b1=0, b2=0, a0=0, a1=0, a2=0):
self.b0 = b0
self.b1 = b1
self.b2 = b2
self.a0 = a0
... | 2.75 | 3 |
util/training.py | NeuralVFX/facial-pose-estimation-pytorch-v2 | 5 | 39463 | <reponame>NeuralVFX/facial-pose-estimation-pytorch-v2
import math
import numpy as np
import torch
############################################################################
# Learning Rate
############################################################################
def set_lr_sched(epochs, iters, mult):
""" ... | 2.796875 | 3 |
components/fatfs/test_fatfsgen/test_fatfsparse.py | fbucafusco/esp-idf | 0 | 39464 | #!/usr/bin/env python
# SPDX-FileCopyrightText: 2021-2022 Espressif Systems (Shanghai) CO LTD
# SPDX-License-Identifier: Apache-2.0
import os
import shutil
import sys
import unittest
from subprocess import STDOUT, run
from test_utils import compare_folders, fill_sector, generate_local_folder_structure, generate_test_... | 2.296875 | 2 |
tests/test_tasks.py | rzuris/python-harvest_apiv2 | 0 | 39465 |
# Copyright 2020 Bradbase
import os, sys
import unittest
import configparser
from dataclasses import asdict
from requests_oauthlib import OAuth2Session
from oauthlib.oauth2 import MobileApplicationClient, WebApplicationClient
import httpretty
import warnings
from dacite import from_dict
import json
sys.path.insert(0... | 2.171875 | 2 |
db_models/deckentry.py | Teplitsa/false-security-1 | 1 | 39466 | <reponame>Teplitsa/false-security-1
from globals import db
import db_models.game
from db_models.card import Card
class DeckEntry(db.Model):
#__table_args__ = {'extend_existing': True}
__tablename__ = 'deckentry'
id = db.Column(db.Integer, primary_key=True)
# TODO: Undo nullable
cardId = db.Column(d... | 2.46875 | 2 |
fisher_py/data/file_error.py | abdelq/fisher_py | 3 | 39467 | from fisher_py.net_wrapping import NetWrapperBase
class FileError(NetWrapperBase):
@property
def has_error(self) -> bool:
"""
Gets a value indicating whether this file has detected an error. If this is false:
Other error properties in this interface have no meaning. Applications s... | 2.71875 | 3 |
05-data_acquisition/scrap.py | sachinpr0001/data_science | 0 | 39468 | import bs4
import requests
import os
str = input()
input_str = str
str = str.replace(" ", "&20")
url = "https://www.snapdeal.com/search?keyword={}&santizedKeyword=&catId=&categoryId=0&suggested=false&vertical=&noOfResults=20&searchState=&clickSrc=go_header&lastKeyword=&prodCatId=&changeBackToAll=false&foundInAll=false... | 2.765625 | 3 |
slixmpp/__init__.py | marconfus/slixmpp | 0 | 39469 | """
Slixmpp: The Slick XMPP Library
Copyright (C) 2010 <NAME>
This file is part of Slixmpp.
See the file LICENSE for copying permission.
"""
import logging
logging.getLogger(__name__).addHandler(logging.NullHandler())
import asyncio
# Required for python < 3.7 to use the old ssl implementation
# and... | 1.453125 | 1 |
model_wrappers/errors.py | SelfHacked/django-model-wrappers | 0 | 39470 | class FieldDoesNotExist(Exception):
def __init__(self, **kwargs):
super().__init__(f"{self.__class__.__name__}: {kwargs}")
self.kwargs = kwargs
| 2.171875 | 2 |
ois_api_client/v3_0/deserialization/deserialize_user_header.py | peterkulik/ois_api_client | 7 | 39471 | from typing import Optional
import xml.etree.ElementTree as ET
from ...xml.XmlReader import XmlReader as XR
from ..namespaces import COMMON
from ..dto.UserHeader import UserHeader
from .deserialize_crypto import deserialize_crypto
def deserialize_user_header(element: ET.Element) -> Optional[UserHeader]:
if elemen... | 2.3125 | 2 |
src/test.py | kevin3314/gcn_ppi | 0 | 39472 | from collections import defaultdict
from pathlib import Path
from typing import Dict, List, Optional
import hydra
import numpy as np
import pandas as pd
from omegaconf import DictConfig, OmegaConf
from pytorch_lightning import (
Callback,
LightningDataModule,
LightningModule,
Trainer,
seed_everythi... | 2.265625 | 2 |
source_code/main.py | Sehannnnnnn/shortest-path | 0 | 39473 | from agent import Qnet
from agent import ReplayBuffer
from agent import train
q = Qnet()
q_target = Qnet()
q_target.load_state_dict(q.state_dict())
memory = ReplayBuffer()
print_interval = 20
score = 0.0
optimizer = optim.Adam(q.parameters(), lr=learning_rate)
score_history= []
for n_epi in range(30... | 2.28125 | 2 |
ide/tests/test_import_archive.py | Ramonrlb/cloudpebble | 147 | 39474 | """ These tests check basic operation of ide.tasks.archive.do_import_archive """
import mock
from django.core.exceptions import ValidationError
from ide.tasks.archive import do_import_archive, InvalidProjectArchiveException
from ide.utils.cloudpebble_test import CloudpebbleTestCase, make_package, make_appinfo, build_... | 2.375 | 2 |
src/features/build_features.py | weasysolutions/skin-lesion-dataset-cookiecutter | 0 | 39475 | # -*- coding: utf-8 -*-
import click
import os
import logging
import sys
import pandas as pd
import os, sys, inspect
cmd_subfolder = os.path.realpath(os.path.abspath(os.path.join(os.path.split(inspect.getfile( inspect.currentframe() ))[0],"images_in_features_subdirs")))
if cmd_subfolder not in sys.path:
sys.path... | 2.375 | 2 |
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/hsa/hlc/hlc.py | jeikabu/lumberyard | 8 | 39476 | <gh_stars>1-10
# A temporary wrapper to connect to the HLC LLVM binaries.
# Currently, connect to commandline interface.
from __future__ import print_function, absolute_import
import sys
from subprocess import check_call
import tempfile
import os
from collections import namedtuple
from numba import config
from .utils ... | 2.140625 | 2 |
lensit/ffs_iterators/bfgs.py | Sebastian-Belkner/LensIt | 0 | 39477 | from __future__ import print_function
import numpy as np
import os
class BFGS_Hessian(object):
"""
Class to evaluate the update to inverse Hessian matrix in the L-BFGS scheme.
(see wikipedia article if nothing else).
H is B^-1 form that article.
B_k+1 = B + yy^t / (y^ts) - B s s^t B / (s^t Bk s)... | 2.875 | 3 |
annotations/migrations/0015_organization_description.py | alexliyihao/auto-annotation-web | 1 | 39478 | <reponame>alexliyihao/auto-annotation-web
# Generated by Django 3.2.8 on 2021-11-11 02:06
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('annotations', '0014_auto_20211110_2007'),
]
operations = [
migrations.AddField(
model_... | 1.804688 | 2 |
paper/figures/make_photometry_table.py | abostroem/asassn15oz | 0 | 39479 | <reponame>abostroem/asassn15oz
# coding: utf-8
# Creates a table of all imaging observations in the database for paper:
# * lc_obs.tex
# In[1]:
import numpy as np
from astropy import table
from astropy.table import Table
from astropy.time import Time
from utilities_az import supernova, connect_to_sndavis
... | 2.015625 | 2 |
flask_resources/parsers/__init__.py | inveniosoftware/flask-resources | 2 | 39480 | # -*- coding: utf-8 -*-
#
# Copyright (C) 2020-2021 CERN.
# Copyright (C) 2020-2021 Northwestern University.
#
# Flask-Resources is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""Request parser for the body, headers, query string and ... | 1.617188 | 2 |
analyze_tagged_corpus.py | kevincobain2000/nltk-trainer | 1 | 39481 | <reponame>kevincobain2000/nltk-trainer
#!/usr/bin/python
import argparse
import nltk.corpus
from nltk.corpus.util import LazyCorpusLoader
from nltk.probability import FreqDist
from nltk.tag.simplify import simplify_wsj_tag
from nltk_trainer import load_corpus_reader
########################################
## command ... | 2.21875 | 2 |
service/example_config.py | w1kke/example-service | 0 | 39482 | <gh_stars>0
# Copyright 2018 Ocean Protocol Foundation
# SPDX-License-Identifier: Apache-2.0
import logging
import os
import sys
from squid_py import Config
def get_variable_value(variable):
if os.getenv(variable) is None:
logging.error(f'you should provide a {variable}')
sys.exit(1)
else:... | 2.234375 | 2 |
02_Variables/Variable types/tests.py | dannymeijer/level-up-with-python | 0 | 39483 | <filename>02_Variables/Variable types/tests.py
from lessons.test_helper import run_common_tests, get_answer_placeholders, passed, failed
def test_type_used():
window = get_answer_placeholders()[0]
if "type" in window and "float_number" in window:
passed()
else:
failed("Use the type() funct... | 2.4375 | 2 |
rssexample.py | nhtnhan/CMPUT404-Web-Mining | 1 | 39484 | import feedparser
import difflib
import json
cbc = feedparser.parse("http://rss.cbc.ca/lineup/topstories.xml")
print(json.dumps(cbc))
print("\n\n################################################\n\n")
cnn = feedparser.parse("http://rss.cnn.com/rss/cnn_topstories.rss")
print(json.dumps(cnn))
print("\n\n##################... | 2.6875 | 3 |
dump_to_json.py | saqib-nadeem/sample_python_scripts | 0 | 39485 | """
Usage Example:
cat imesh_sample.txt | python dump_to_json.py -o imesh.json -e imesh_hashes.json
"""
import sys
import json
import argparse
import traceback
from os.path import dirname, abspath
project_folder = dirname(dirname(abspath('.')))
if project_folder not in sys.path:
sys.path.append(project_folder)
... | 2.984375 | 3 |
src/setprogramoptions/unittests/test_SetProgramOptionsCMake.py | sandialabs/SetProgramOptions | 1 | 39486 | #!/usr/bin/env python3
# -*- mode: python; py-indent-offset: 4; py-continuation-offset: 4 -*-
#===============================================================================
#
# License (3-Clause BSD)
# ----------------------
# Copyright 2021 National Technology & Engineering Solutions of Sandia,
# LLC (NTESS). Under ... | 1.203125 | 1 |
accelRF/rep/base.py | nexuslrf/Accel-RF | 0 | 39487 | <reponame>nexuslrf/Accel-RF
from typing import Tuple
import torch.nn as nn
from torch import Tensor
class Explicit3D(nn.Module):
# corner_points: Tensor
center_points: Tensor
center2corner: Tensor
n_voxels: int
n_corners: int
grid_shape: Tensor
voxel_size: float
occupancy: Tensor
d... | 2.046875 | 2 |
URLSHORT/lib.py | its-mr-monday/Url-Shortener | 0 | 39488 | import random
import string
import requests
def SQL_SYNTAX_CHECK(input: str) -> bool:
bad_char = ['*',';','SELECT ',' FROM ', ' TRUE ', ' WHERE ']
for char in bad_char:
if char in input:
return False
return True
def validateRegistration(name, uname, email, password, confirm):
if l... | 3.234375 | 3 |
main.py | hamolicious/Python-Word-Search-Generator | 0 | 39489 |
from random import choice, randint
import os
def generate_grid(w, h):
global width, height
alphabet = 'qwertyuiopasdfghjklzxcvbnm'
grid = []
for i in range(h):
row = []
for j in range(w):
row.append(' ')
grid.append(row)
return grid
def popul... | 3.640625 | 4 |
Scripts/HLS_Stream_Dowloader/hls_dowloader.py | WilliamMokoena/portfolio | 0 | 39490 | import sys, os, asyncio, shutil
import wget
from ffmpeg import FFmpeg
# Func calls wget to download the file given in url arg
def webget(url):
wget.download(url)
# Fuc calls ffmpeg to transcode .m3u8 to .mp4
def transcode(ffmpeg):
@ffmpeg.on('stderr')
def on_stderr(line):
print(line)
@ffmpeg.... | 2.890625 | 3 |
fairlearn/metrics/__init__.py | alliesaizan/fairlearn | 1,142 | 39491 | <filename>fairlearn/metrics/__init__.py
# Copyright (c) Microsoft Corporation and Fairlearn contributors.
# Licensed under the MIT License.
"""Functionality for computing metrics, with a particular focus on disaggregated metrics.
For our purpose, a metric is a function with signature
``f(y_true, y_pred, ....)``
where... | 2.578125 | 3 |
detector/ssd/ssd.py | Senyaaa/detection-experiments | 5 | 39492 | import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from detector.ssd.utils import box_utils
from nn.separable_conv_2d import SeparableConv2d
from fpn.extension import Extension
from detector.ssd.to_predictions import ToPredictions
class SSD(nn.Module):
def __init__(self, num_cl... | 2.484375 | 2 |
commands/serverinfo.py | Stereo528/Osmium | 2 | 39493 | <filename>commands/serverinfo.py
import discord
from discord.ext import commands
from main import getAlias
class Util(commands.Cog):
def __init__(self, client):
self.client = client
@commands.command(aliases=getAlias("serverinfo"))
async def serverinfo(self, ctx):
embed = discord.Embed(
... | 2.484375 | 2 |
sklearn_pipeline_enhancements/shared/transformers.py | Kgoetsch/sklearn_pipeline_enhancements | 11 | 39494 | <reponame>Kgoetsch/sklearn_pipeline_enhancements
import numpy as np
import pandas as pd
from patsy.highlevel import dmatrix
from sklearn.base import TransformerMixin, BaseEstimator
from sklearn.pipeline import _name_estimators, Pipeline
__author__ = 'kgoetsch'
def make_dataframeunion(steps):
return DataFrameUnio... | 2.734375 | 3 |
exercises/exercise7.py | AsBeeb/DistributedExercisesAAU | 4 | 39495 | import math
import random
import threading
import time
from emulators.Medium import Medium
from emulators.Device import Device
from emulators.MessageStub import MessageStub
class Vote(MessageStub):
def __init__(self, sender: int, destination: int, vote: int, decided: bool):
super().__init__(sender, dest... | 2.671875 | 3 |
pait/util/_pydantic_util.py | so1n/pa | 19 | 39496 | <reponame>so1n/pa
from typing import TYPE_CHECKING, Any, Dict, Optional, Set, Type, Union
from pydantic.schema import (
default_ref_template,
get_flat_models_from_model,
get_long_model_name,
get_model,
get_schema_ref,
model_process_schema,
normalize_name,
)
if TYPE_CHECKING:
from pydan... | 2.515625 | 3 |
experimental/plotlyDelaunay3D.py | FYP-DES5/deepscan-core | 0 | 39497 | <filename>experimental/plotlyDelaunay3D.py
import plotly.plotly as py
from plotly.graph_objs import *
import numpy as np
import matplotlib.cm as cm
from scipy.spatial import Delaunay
u=np.linspace(0,2*np.pi, 24)
v=np.linspace(-1,1, 8)
u,v=np.meshgrid(u,v)
u=u.flatten()
v=v.flatten()
#evaluate the parameterization at... | 2.96875 | 3 |
src/sardana/taurus/qt/qtcore/tango/sardana/pool.py | marc2332/sardana | 43 | 39498 | #!/usr/bin/env python
##############################################################################
##
# This file is part of Sardana
##
# http://www.sardana-controls.org/
##
# Copyright 2011 CELLS / ALBA Synchrotron, Bellaterra, Spain
##
# Sardana is free software: you can redistribute it and/or modify
# it under th... | 1.59375 | 2 |
basics_data_structure/queue.py | corenel/algorithm-exercises | 0 | 39499 | <filename>basics_data_structure/queue.py
"""
Queue
https://algorithm.yuanbin.me/zh-hans/basics_data_structure/queue.html
"""
| 1.046875 | 1 |