max_stars_repo_path stringlengths 4 286 | max_stars_repo_name stringlengths 5 119 | max_stars_count int64 0 191k | id stringlengths 1 7 | content stringlengths 6 1.03M | content_cleaned stringlengths 6 1.03M | language stringclasses 111
values | language_score float64 0.03 1 | comments stringlengths 0 556k | edu_score float64 0.32 5.03 | edu_int_score int64 0 5 |
|---|---|---|---|---|---|---|---|---|---|---|
assets/puppeteer.py | KTibow/scorecard | 2 | 6631451 | import pytest
from pyppeteer import launch, errors as pyppeteer_errors
from os import remove, removedirs, mkdir
from os.path import exists
from glob import glob
from json import load
import asyncio
# Test every endpoint
try:
mkdir("pytest_screenshots")
except FileExistsError:
screenshots = glob(r"pytest_scree... | import pytest
from pyppeteer import launch, errors as pyppeteer_errors
from os import remove, removedirs, mkdir
from os.path import exists
from glob import glob
from json import load
import asyncio
# Test every endpoint
try:
mkdir("pytest_screenshots")
except FileExistsError:
screenshots = glob(r"pytest_scree... | en | 0.730902 | # Test every endpoint # Do initial add # New id # After adding # First add # Second add # After adding # TODO: Check whether the card buttons are accessible # Getting the tabs ready # Adding them to group # Marking them as ready # Doing the thing # TODO: Test backend seperately # TODO: Check every single line of code | 2.179875 | 2 |
project_crudname/core/admin.py | omher1105/example-django-tests | 0 | 6631452 | from django.contrib import admin
class AbstractChoiceAdmin(admin.ModelAdmin):
"""
Admin options for AbstractChoice abstract model.
"""
list_display = ['id', 'name', 'code']
class AuditAdminMixin:
ordering = ['pk']
def get_merge_fields(self, origin_fields, fields):
fields = list(fiel... | from django.contrib import admin
class AbstractChoiceAdmin(admin.ModelAdmin):
"""
Admin options for AbstractChoice abstract model.
"""
list_display = ['id', 'name', 'code']
class AuditAdminMixin:
ordering = ['pk']
def get_merge_fields(self, origin_fields, fields):
fields = list(fiel... | en | 0.397551 | Admin options for AbstractChoice abstract model. | 2.160959 | 2 |
_python/recursive_print_dict.py | luizeleno/pyjupiter | 0 | 6631453 | import re
import unidecode
def RecursivePrintDict(dictio, of, indent=0, start='- '):
for k, v in dictio.items():
key = re.sub(r'\s+', '_', f'{k}')
key = unidecode.unidecode(key)
if isinstance(v, dict):
of.write(' ' * indent + f'{start}{key}:\n')
if k == 'requisitos'... | import re
import unidecode
def RecursivePrintDict(dictio, of, indent=0, start='- '):
for k, v in dictio.items():
key = re.sub(r'\s+', '_', f'{k}')
key = unidecode.unidecode(key)
if isinstance(v, dict):
of.write(' ' * indent + f'{start}{key}:\n')
if k == 'requisitos'... | none | 1 | 3.549197 | 4 | |
librex/_symsets.py | matpuk/testjb | 0 | 6631454 | #
# Symbol sets implementation
#
from typing import Text, Callable
def sym_is_any(sym: Text) -> bool:
return True
def sym_is_digit(sym: Text) -> bool:
return sym.isdigit()
def sym_is_not_digit(sym: Text) -> bool:
return not sym_is_digit(sym)
def sym_is_space(sym: Text) -> bool:
return sym.isspac... | #
# Symbol sets implementation
#
from typing import Text, Callable
def sym_is_any(sym: Text) -> bool:
return True
def sym_is_digit(sym: Text) -> bool:
return sym.isdigit()
def sym_is_not_digit(sym: Text) -> bool:
return not sym_is_digit(sym)
def sym_is_space(sym: Text) -> bool:
return sym.isspac... | en | 0.741542 | # # Symbol sets implementation # | 3.417306 | 3 |
tests/fixtures/dashboard.py | us88/LF_Flask-MonitoringDashboard | 0 | 6631455 | <filename>tests/fixtures/dashboard.py
import pytest
import pytz
from flask import Flask
import lemonadefashion_flask_monitoringdashboard
@pytest.fixture
def config(colors=None, group_by=None):
lemonadefashion_flask_monitoringdashboard.config.colors = colors or {'endpoint': '[0, 1, 2]'}
lemonadefashion_flask_... | <filename>tests/fixtures/dashboard.py
import pytest
import pytz
from flask import Flask
import lemonadefashion_flask_monitoringdashboard
@pytest.fixture
def config(colors=None, group_by=None):
lemonadefashion_flask_monitoringdashboard.config.colors = colors or {'endpoint': '[0, 1, 2]'}
lemonadefashion_flask_... | en | 0.863306 | Returns a testing application that can be used for testing the endpoints. | 2.146729 | 2 |
test/other/generate_pairwise_relative_data.py | xuebingwu/xtools | 0 | 6631456 | <filename>test/other/generate_pairwise_relative_data.py
l2n = {'A':1.0, 'C':2.0, 'G':3.0, 'T':4.0}
f=open('')
for line in f:
flds = line.strip().split()
line2 = f.readline()
flds2 = line2.strip().split()
print flds[0]+"\t"+str(l2n[flds[0][29]]/l2n[flds2[0][29]])
print flds[0]+"\t1.0"
f.close()
| <filename>test/other/generate_pairwise_relative_data.py
l2n = {'A':1.0, 'C':2.0, 'G':3.0, 'T':4.0}
f=open('')
for line in f:
flds = line.strip().split()
line2 = f.readline()
flds2 = line2.strip().split()
print flds[0]+"\t"+str(l2n[flds[0][29]]/l2n[flds2[0][29]])
print flds[0]+"\t1.0"
f.close()
| none | 1 | 2.606705 | 3 | |
core/cooggerapp/views/home.py | bisguzar/coogger | 0 | 6631457 | <reponame>bisguzar/coogger
from django.conf import settings
from django.contrib import messages
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.auth.models import User
from django.db.models import Q
from django.http import Http404
from django.shortcuts import get_object_or_404, redirect, r... | from django.conf import settings
from django.contrib import messages
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.auth.models import User
from django.db.models import Q
from django.http import Http404
from django.shortcuts import get_object_or_404, redirect, render
from django.urls impo... | en | 0.81002 | # TODO just pc # TODO this class must be improved # make a new model for this op | 1.998434 | 2 |
sync_dl_ytapi/commands.py | PrinceOfPuppers/sync-dl-ytapi | 0 | 6631458 | import os
import sys
import shelve
import sync_dl.config as cfg
from sync_dl_ytapi.helpers import getPlId,pushOrderMoves
from sync_dl_ytapi.credentials import getCredentials,revokeTokens
from sync_dl_ytapi.ytapiWrappers import getItemIds,moveSong
# actual commands
def pushLocalOrder(plPath):
credJson = getCr... | import os
import sys
import shelve
import sync_dl.config as cfg
from sync_dl_ytapi.helpers import getPlId,pushOrderMoves
from sync_dl_ytapi.credentials import getCredentials,revokeTokens
from sync_dl_ytapi.ytapiWrappers import getItemIds,moveSong
# actual commands
def pushLocalOrder(plPath):
credJson = getCr... | es | 0.774279 | # actual commands | 2.115407 | 2 |
tests/unit/utils/test_base_api_client.py | primitybio/cellengine-python-toolk | 4 | 6631459 | <gh_stars>1-10
import pytest
import requests
import responses
from cellengine.utils.api_client.APIError import APIError
MOCK_DATA = {"data": "some fake data"}
BASE_URL = "http://fake/"
SESSION = requests.Session()
def test_api_client(client):
assert client._API_NAME == "CellEngine Python Toolkit"
@responses.... | import pytest
import requests
import responses
from cellengine.utils.api_client.APIError import APIError
MOCK_DATA = {"data": "some fake data"}
BASE_URL = "http://fake/"
SESSION = requests.Session()
def test_api_client(client):
assert client._API_NAME == "CellEngine Python Toolkit"
@responses.activate
def te... | none | 1 | 2.328032 | 2 | |
lightly/embedding/embedding.py | shruti-shyam/lightly | 0 | 6631460 | """ Embedding Strategies """
# Copyright (c) 2020. Lightly AG and its affiliates.
# All Rights Reserved
import time
import torch
import lightly
from lightly.embedding._base import BaseEmbedding
from tqdm import tqdm
if lightly._is_prefetch_generator_available():
from prefetch_generator import BackgroundGenerato... | """ Embedding Strategies """
# Copyright (c) 2020. Lightly AG and its affiliates.
# All Rights Reserved
import time
import torch
import lightly
from lightly.embedding._base import BaseEmbedding
from tqdm import tqdm
if lightly._is_prefetch_generator_available():
from prefetch_generator import BackgroundGenerato... | en | 0.701483 | Embedding Strategies # Copyright (c) 2020. Lightly AG and its affiliates. # All Rights Reserved Implementation of self-supervised embedding models. Implements an embedding strategy based on self-supervised learning. A model backbone, self-supervised criterion, optimizer, and dataloader are passed to the co... | 2.515184 | 3 |
hmlvaraus/migrations/0001_initial.py | haltu/hmlvaraus-backend | 1 | 6631461 | <filename>hmlvaraus/migrations/0001_initial.py<gh_stars>1-10
# -*- coding: utf-8 -*-
# Generated by Django 1.10.3 on 2017-05-09 05:10
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
depen... | <filename>hmlvaraus/migrations/0001_initial.py<gh_stars>1-10
# -*- coding: utf-8 -*-
# Generated by Django 1.10.3 on 2017-05-09 05:10
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
depen... | en | 0.768267 | # -*- coding: utf-8 -*- # Generated by Django 1.10.3 on 2017-05-09 05:10 | 1.589183 | 2 |
src/pyaides/functools/__init__.py | okomestudio/pyaides | 0 | 6631462 | from .cache import cachetofile # noqa
| from .cache import cachetofile # noqa
| none | 1 | 1.01291 | 1 | |
modules/rltrain.py | SaeedNajafi/tagger | 9 | 6631463 | <filename>modules/rltrain.py
from itertools import *
import torch
import numpy as np
import torch.nn as nn
from torch.nn import init
from torch.autograd import Variable
hasCuda = torch.cuda.is_available()
class RLTrain(nn.Module):
"""
This module applies biased actor-critic training to the decoder RNN.
""... | <filename>modules/rltrain.py
from itertools import *
import torch
import numpy as np
import torch.nn as nn
from torch.nn import init
from torch.autograd import Variable
hasCuda = torch.cuda.is_available()
class RLTrain(nn.Module):
"""
This module applies biased actor-critic training to the decoder RNN.
""... | en | 0.738731 | This module applies biased actor-critic training to the decoder RNN. #Critic: #Critic approximates the state-value function of a state. #Do not back propagate through S! #We do not apply any dropout layer as this is a regression model #and the optimizer will apply L2 regularization on the weights. #H3 is now scaler bet... | 3.081838 | 3 |
07_gashlycrumb/solution1.py | sidsid14/tiny_python_projects | 742 | 6631464 | <gh_stars>100-1000
#!/usr/bin/env python3
"""Lookup tables"""
import argparse
# --------------------------------------------------
def get_args():
"""get command-line arguments"""
parser = argparse.ArgumentParser(
description='Gashlycrumb',
formatter_class=argparse.ArgumentDefaultsHelpFormat... | #!/usr/bin/env python3
"""Lookup tables"""
import argparse
# --------------------------------------------------
def get_args():
"""get command-line arguments"""
parser = argparse.ArgumentParser(
description='Gashlycrumb',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.ad... | en | 0.154716 | #!/usr/bin/env python3 Lookup tables # -------------------------------------------------- get command-line arguments # -------------------------------------------------- Make a jazz noise here # -------------------------------------------------- | 3.818656 | 4 |
example3.py | MWedl/python-logstash | 1 | 6631465 | <reponame>MWedl/python-logstash
import logging
import logstash
import sys
host = '127.0.0.1'
test_logger = logging.getLogger('python-logstash-logger')
test_logger.setLevel(logging.INFO)
test_logger.addHandler(logstash.HTTPLogstashHandler(host, 1337, ssl=True, verify=True, username="user", password="pw"))
# test_logge... | import logging
import logstash
import sys
host = '127.0.0.1'
test_logger = logging.getLogger('python-logstash-logger')
test_logger.setLevel(logging.INFO)
test_logger.addHandler(logstash.HTTPLogstashHandler(host, 1337, ssl=True, verify=True, username="user", password="pw"))
# test_logger.addHandler(logstash.TCPLogstas... | en | 0.213432 | # test_logger.addHandler(logstash.TCPLogstashHandler(host, 5959, version=1)) # add extra field to logstash message | 2.645701 | 3 |
My Phrases/chrome_firefox_view_history.py | yasapurnama/autokey-osx-ify | 0 | 6631466 | import re
window = window.get_active_class()
is_chrome = re.search('chrome', window, re.IGNORECASE)
is_firefox = re.search('firefox', window, re.IGNORECASE)
if is_chrome or is_firefox:
keys = "<ctrl>+h"
keyboard.send_keys(keys)
| import re
window = window.get_active_class()
is_chrome = re.search('chrome', window, re.IGNORECASE)
is_firefox = re.search('firefox', window, re.IGNORECASE)
if is_chrome or is_firefox:
keys = "<ctrl>+h"
keyboard.send_keys(keys)
| none | 1 | 2.764446 | 3 | |
programs/beep.py | ckumpe/robot-inventor-tools | 11 | 6631467 | <filename>programs/beep.py
from mindstorms import MSHub, Motor, MotorPair, ColorSensor, DistanceSensor, App
from mindstorms.control import wait_for_seconds, wait_until, Timer
from mindstorms.operator import greater_than, greater_than_or_equal_to, less_than, less_than_or_equal_to, equal_to, not_equal_to
import math
hu... | <filename>programs/beep.py
from mindstorms import MSHub, Motor, MotorPair, ColorSensor, DistanceSensor, App
from mindstorms.control import wait_for_seconds, wait_until, Timer
from mindstorms.operator import greater_than, greater_than_or_equal_to, less_than, less_than_or_equal_to, equal_to, not_equal_to
import math
hu... | none | 1 | 2.660846 | 3 | |
packages/pytest-simcore/src/pytest_simcore/docker_compose.py | colinRawlings/osparc-simcore | 25 | 6631468 | <reponame>colinRawlings/osparc-simcore<filename>packages/pytest-simcore/src/pytest_simcore/docker_compose.py<gh_stars>10-100
# pylint:disable=unused-variable
# pylint:disable=unused-argument
# pylint:disable=redefined-outer-name
""" Fixtures to create docker-compose.yaml configururation files (as in Makefile)
... | # pylint:disable=unused-variable
# pylint:disable=unused-argument
# pylint:disable=redefined-outer-name
""" Fixtures to create docker-compose.yaml configururation files (as in Makefile)
Basically runs `docker-compose config
"""
import os
import shutil
import sys
from copy import deepcopy
from pathli... | en | 0.805252 | # pylint:disable=unused-variable # pylint:disable=unused-argument # pylint:disable=redefined-outer-name Fixtures to create docker-compose.yaml configururation files (as in Makefile)
Basically runs `docker-compose config Loads and extends .env-devel returning
all environment variables key=value # get from en... | 1.992369 | 2 |
api/urls.py | catveloper/dynamic_form_generator | 0 | 6631469 | from django.urls import path, include
from drf_spectacular.views import SpectacularJSONAPIView, SpectacularAPIView, SpectacularSwaggerView, \
SpectacularRedocView
from rest_framework import routers
from api.viewset import *
app_name = 'api'
router = routers.DefaultRouter()
router.register(r'users', viewset=UserV... | from django.urls import path, include
from drf_spectacular.views import SpectacularJSONAPIView, SpectacularAPIView, SpectacularSwaggerView, \
SpectacularRedocView
from rest_framework import routers
from api.viewset import *
app_name = 'api'
router = routers.DefaultRouter()
router.register(r'users', viewset=UserV... | en | 0.431594 | # Auto Generate API # Custom API # Spectacular Document API | 2.026158 | 2 |
home/admin.py | georgiawang5332/meatFoodManager | 0 | 6631470 | <reponame>georgiawang5332/meatFoodManager
from django.contrib import admin
from .models import *
#
# # Register your models here.
# admin.site.register(UserProfile) # 店家(餐廳)
class UserProfileAdmin(admin.ModelAdmin):
list_display = ('user', 'user_info', 'phone', 'email', 'city', 'website')
def user_info(self, o... | from django.contrib import admin
from .models import *
#
# # Register your models here.
# admin.site.register(UserProfile) # 店家(餐廳)
class UserProfileAdmin(admin.ModelAdmin):
list_display = ('user', 'user_info', 'phone', 'email', 'city', 'website')
def user_info(self, obj):
return obj.description
def get... | en | 0.215187 | # # # Register your models here. # admin.site.register(UserProfile) # 店家(餐廳) # list_display = ('user', 'image', 'phone', 'email', 'city', 'website', 'description') # list_filter = ('phone',) # search_fields = ('phone',) # fields = ('user', 'image', 'phone', 'email', 'city', 'website', # 'description'... | 2.08734 | 2 |
train_pointnet.py | BowenRaymone/KaggleLyftCompetition | 2 | 6631471 | <gh_stars>1-10
from abc import ABC
from pathlib import Path
from numcodecs import blosc
import pandas as pd, numpy as np
import os
import bisect
import itertools as it
from tqdm import tqdm
import logzero
import torch
from torch import nn, optim
import torch.nn.functional as F
from torch.autograd import Variable
fr... | from abc import ABC
from pathlib import Path
from numcodecs import blosc
import pandas as pd, numpy as np
import os
import bisect
import itertools as it
from tqdm import tqdm
import logzero
import torch
from torch import nn, optim
import torch.nn.functional as F
from torch.autograd import Variable
from pytorch_ligh... | en | 0.695805 | # last_checkpoint = get_last_checkpoint(ROOT) # print(model) | 1.905018 | 2 |
config.py | ominatechnologies/frozendict | 0 | 6631472 | # Single-sourced project configuration values:
# The full version, including alpha/beta/rc tags:
release = "2021.11.30"
version = release
# Distribution package name:
name = "frozendict"
# Capitalized label:
project = "Frozendict"
description = "A modern implementation of FrozenDict."
author = "<NAME>"
author_email... | # Single-sourced project configuration values:
# The full version, including alpha/beta/rc tags:
release = "2021.11.30"
version = release
# Distribution package name:
name = "frozendict"
# Capitalized label:
project = "Frozendict"
description = "A modern implementation of FrozenDict."
author = "<NAME>"
author_email... | en | 0.70752 | # Single-sourced project configuration values: # The full version, including alpha/beta/rc tags: # Distribution package name: # Capitalized label: | 0.984577 | 1 |
mesh_tensorflow/auto_mtf/layout_optimizer.py | merrymercy/mesh | 1,264 | 6631473 | # coding=utf-8
# Copyright 2021 The Mesh TensorFlow Authors.
#
# 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 applicab... | # coding=utf-8
# Copyright 2021 The Mesh TensorFlow Authors.
#
# 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 applicab... | en | 0.833885 | # coding=utf-8 # Copyright 2021 The Mesh TensorFlow Authors. # # 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 applicab... | 2.978304 | 3 |
Source/A_Star_Search.py | TranPhu1999/Search_algorithm_with_visuallization | 0 | 6631474 | <filename>Source/A_Star_Search.py<gh_stars>0
import numpy as np
from Support import visualize_maze, heuristic_euclidean, heuristic_manhatan, heuristic_euclidean_2
def a_star_search(maze_map,start,end, bonus = None):
visited = []
queue = [(start[0],start[1])] # (x, y, heuristic + path cost, path cost)
... | <filename>Source/A_Star_Search.py<gh_stars>0
import numpy as np
from Support import visualize_maze, heuristic_euclidean, heuristic_manhatan, heuristic_euclidean_2
def a_star_search(maze_map,start,end, bonus = None):
visited = []
queue = [(start[0],start[1])] # (x, y, heuristic + path cost, path cost)
... | en | 0.755473 | # (x, y, heuristic + path cost, path cost) # find the block with the lowest cost to go to the End in the queue # store coordinate of visited block for visuallize # ^ > v < # if neighbor is not wall and not in visited list # if neighbor is emty or have shorter path from the start # save the coordinate of the current blo... | 3.468321 | 3 |
torchwt/engine/utils/model_input.py | frankhart2018/torchwt | 2 | 6631475 | <filename>torchwt/engine/utils/model_input.py
from dataclasses import dataclass
@dataclass
class ModelInput:
model_spec_file: str
hyperparameter_spec_file: str | <filename>torchwt/engine/utils/model_input.py
from dataclasses import dataclass
@dataclass
class ModelInput:
model_spec_file: str
hyperparameter_spec_file: str | none | 1 | 1.610036 | 2 | |
tests/integration/data/customers.py | el-dot/securionpay-python | 7 | 6631476 | from tests.integration import random_email
def valid_customer_req(email=random_email(), card=None):
req = {"email": email}
if card is not None:
req["card"] = card
return req
| from tests.integration import random_email
def valid_customer_req(email=random_email(), card=None):
req = {"email": email}
if card is not None:
req["card"] = card
return req
| none | 1 | 2.49195 | 2 | |
test_looper_tests/test_manager_include_semantics.py | ufora/test-looper | 3 | 6631477 | <reponame>ufora/test-looper<filename>test_looper_tests/test_manager_include_semantics.py
import unittest
import os
import logging
import test_looper_tests.common as common
import test_looper_tests.TestYamlFiles as TestYamlFiles
import test_looper_tests.TestManagerTestHarness as TestManagerTestHarness
import test_loope... | import unittest
import os
import logging
import test_looper_tests.common as common
import test_looper_tests.TestYamlFiles as TestYamlFiles
import test_looper_tests.TestManagerTestHarness as TestManagerTestHarness
import test_looper.data_model.BranchPinning as BranchPinning
import test_looper.data_model.ImportExport as... | en | 0.548165 | looper_version: 4 environments: ${env_name}: platform: linux image: dockerfile_contents: hi variables: ${vname}: ${vdef} looper_version: 4 repos: include_from: refere... | 2.14716 | 2 |
beets/autotag/hooks.py | Thynix/beets | 1 | 6631478 | <gh_stars>1-10
# This file is part of beets.
# Copyright 2011, <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,... | # This file is part of beets.
# Copyright 2011, <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, ... | en | 0.830135 | # This file is part of beets. # Copyright 2011, <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, ... | 1.777026 | 2 |
commands/relpath.py | dtebbs/tzbuild | 0 | 6631479 | <filename>commands/relpath.py<gh_stars>0
from os.path import relpath as path_relpath
from sys import argv
def usage():
print "Usage: %s <path> [<path> ...]"
print ""
def relpath():
args = argv[1:]
if 0 == len(args):
usage()
exit(1)
for a in args:
print path_relpath(a, "."... | <filename>commands/relpath.py<gh_stars>0
from os.path import relpath as path_relpath
from sys import argv
def usage():
print "Usage: %s <path> [<path> ...]"
print ""
def relpath():
args = argv[1:]
if 0 == len(args):
usage()
exit(1)
for a in args:
print path_relpath(a, "."... | none | 1 | 3.049256 | 3 | |
flag_engine/features/models.py | Flagsmith/flagsmith-engine | 4 | 6631480 | <reponame>Flagsmith/flagsmith-engine<filename>flag_engine/features/models.py
import typing
import uuid
from dataclasses import dataclass, field
from flag_engine.utils.hashing import get_hashed_percentage_for_object_ids
@dataclass
class FeatureModel:
id: int
name: str
type: str
def __eq__(self, other... | import typing
import uuid
from dataclasses import dataclass, field
from flag_engine.utils.hashing import get_hashed_percentage_for_object_ids
@dataclass
class FeatureModel:
id: int
name: str
type: str
def __eq__(self, other):
return self.id == other.id
def __hash__(self):
return... | en | 0.786882 | Mimick django method name to simplify serialization logic # Iterate over the mv options in order of id (so we get the same value each # time) to determine the correct value to return to the identity based on # the percentage allocations of the multivariate options. This gives us a # way to ensure that the same value is... | 2.208433 | 2 |
face_sdk/api_usage/actually_run_all.py | subin4420/doitagain | 0 | 6631481 | <reponame>subin4420/doitagain
import sys
import face_merge
sys.path.append('.')
import logging
mpl_logger = logging.getLogger('matplotlib')
mpl_logger.setLevel(logging.WARNING)
import logging.config
logging.config.fileConfig("config/logging.conf")
logger = logging.getLogger('api')
import yaml
import cv2
import numpy ... | import sys
import face_merge
sys.path.append('.')
import logging
mpl_logger = logging.getLogger('matplotlib')
mpl_logger.setLevel(logging.WARNING)
import logging.config
logging.config.fileConfig("config/logging.conf")
logger = logging.getLogger('api')
import yaml
import cv2
import numpy as np
#-----------------detect... | en | 0.182112 | #-----------------detect------------------- #-----------------align------------------- #----------------crop--------------------- #----------------------feature---------------------- # common setting for all model, need not modify. # model setting, modified along with model # load model # read image cv2.imshow("pic1", ... | 2.004989 | 2 |
tests/test_strings.py | luto/django-i18nfield | 35 | 6631482 | <filename>tests/test_strings.py
from django.utils import translation
from django.utils.translation import gettext_noop
from i18nfield.strings import LazyI18nString
def test_explicit_translation():
data = {
'de': 'Hallo',
'en': 'Hello'
}
s = LazyI18nString(data)
translation.activate('e... | <filename>tests/test_strings.py
from django.utils import translation
from django.utils.translation import gettext_noop
from i18nfield.strings import LazyI18nString
def test_explicit_translation():
data = {
'de': 'Hallo',
'en': 'Hello'
}
s = LazyI18nString(data)
translation.activate('e... | none | 1 | 2.257684 | 2 | |
library_collection/admin.py | mredar/avram | 0 | 6631483 | <reponame>mredar/avram
# -*- coding: utf-8 -*-
import datetime
from django.contrib import admin
from django import forms
from library_collection.duration_widget import MultiValueDurationField
from library_collection.models import Campus
from library_collection.models import Repository
from library_collection.models imp... | # -*- coding: utf-8 -*-
import datetime
from django.contrib import admin
from django import forms
from library_collection.duration_widget import MultiValueDurationField
from library_collection.models import Campus
from library_collection.models import Repository
from library_collection.models import Collection
from lib... | en | 0.720342 | # -*- coding: utf-8 -*- # Add is_active & date_joined to User admin list view Filter for collections where date_last_harvested + harvest_frequency is in past. Filter to find blank or filled URL fields # Parameter for the filter that will be used in the URL query. Returns a list of tuples. The first element in each ... | 1.451379 | 1 |
tools/gn/bin/roll_gn.py | google-ar/chromium | 777 | 6631484 | <gh_stars>100-1000
#!/usr/bin/env python
# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""An auto-roller for GN binaries into Chromium.
This script is used to update the GN binaries that a Chromium
chec... | #!/usr/bin/env python
# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""An auto-roller for GN binaries into Chromium.
This script is used to update the GN binaries that a Chromium
checkout uses. In order... | en | 0.888959 | #!/usr/bin/env python # Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. An auto-roller for GN binaries into Chromium. This script is used to update the GN binaries that a Chromium checkout uses. In order to ... | 2.479336 | 2 |
src/transformers/models/layoutlmv2/tokenization_layoutlmv2.py | HimashiRathnayake/adapter-transformers | 50,404 | 6631485 | # coding=utf-8
# Copyright Microsoft Research and The HuggingFace Inc. team. 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/LICENS... | # coding=utf-8
# Copyright Microsoft Research and The HuggingFace Inc. team. 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/LICENS... | en | 0.738059 | # coding=utf-8 # Copyright Microsoft Research and The HuggingFace Inc. team. 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/LICENS... | 1.76468 | 2 |
frappe-bench/apps/erpnext/erpnext/accounts/doctype/account/chart_of_accounts/chart_of_accounts.py | Semicheche/foa_frappe_docker | 0 | 6631486 | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import frappe, os, json
from frappe.utils import cstr
from unidecode import unidecode
def create_charts(company, chart_template=None, existing_company=... | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import frappe, os, json
from frappe.utils import cstr
from unidecode import unidecode
def create_charts(company, chart_template=None, existing_company=... | en | 0.768632 | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt # fill in tree starting with root accounts (those with no parent) # find children # if no children, but a group account # build a subtree for each child # start new subtree # assign account_typ... | 1.935029 | 2 |
yaojikai/20180327/h2.py | python20180319howmework/homework | 0 | 6631487 | <filename>yaojikai/20180327/h2.py
#2,随机产生一个正整数,不要使用python内置方法,求得其二进制表达,并输出
import random
l = []
num = random.randint(1,100)
numb = num
for i in range(100):
if num > 0:
res = num % 2
num//=2
l.append(res)
l.reverse()
print("随机生成的正整数为{},它的二进制表达是{}".format(numb,l))
| <filename>yaojikai/20180327/h2.py
#2,随机产生一个正整数,不要使用python内置方法,求得其二进制表达,并输出
import random
l = []
num = random.randint(1,100)
numb = num
for i in range(100):
if num > 0:
res = num % 2
num//=2
l.append(res)
l.reverse()
print("随机生成的正整数为{},它的二进制表达是{}".format(numb,l))
| zh | 0.995518 | #2,随机产生一个正整数,不要使用python内置方法,求得其二进制表达,并输出 | 3.543941 | 4 |
shadowreader/plugins/loader_middleware.py | luckymike/shadowreader | 150 | 6631488 | <gh_stars>100-1000
def _transform_uri(uri: str, base_url: str) -> str:
url = f"{base_url}{uri}"
return url
def _transform_load(load: list, base_url: str) -> list:
if "request_uri" in load[0]:
uri_key = "request_uri"
elif "uri" in load[0]:
uri_key = "uri"
for l in load:
l["... | def _transform_uri(uri: str, base_url: str) -> str:
url = f"{base_url}{uri}"
return url
def _transform_load(load: list, base_url: str) -> list:
if "request_uri" in load[0]:
uri_key = "request_uri"
elif "uri" in load[0]:
uri_key = "uri"
for l in load:
l["url"] = _transform_... | none | 1 | 2.659269 | 3 | |
sheraf/types/__init__.py | yaal-fr/sheraf | 1 | 6631489 | <filename>sheraf/types/__init__.py
"""Types are used to define the internal storage in ZODB.
There are no need to setup specific types in basic usage of sheraf
because `Model` uses `xAttribute`, not `Type`.
"""
import BTrees.Length
import BTrees.OOBTree
import persistent
import ZODB
import sheraf.tools.dicttools
f... | <filename>sheraf/types/__init__.py
"""Types are used to define the internal storage in ZODB.
There are no need to setup specific types in basic usage of sheraf
because `Model` uses `xAttribute`, not `Type`.
"""
import BTrees.Length
import BTrees.OOBTree
import persistent
import ZODB
import sheraf.tools.dicttools
f... | en | 0.855488 | Types are used to define the internal storage in ZODB. There are no need to setup specific types in basic usage of sheraf because `Model` uses `xAttribute`, not `Type`. SmallDict is a :class:`PersistentMapping` implementation with a simple conflict resolution implementation. When two different keys of the map... | 2.495205 | 2 |
utils/utils_spam.py | surrealyz/DeepBayes | 0 | 6631490 | <gh_stars>0
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import numpy as np
import sys
import warnings
import os, socket
def to_categorical(y, num_classes=None):
y = np.array(y, dtype='int').ravel()
if not... | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import numpy as np
import sys
import warnings
import os, socket
def to_categorical(y, num_classes=None):
y = np.array(y, dtype='int').ravel()
if not num_classes... | en | 0.716745 | Load and preprocess MNIST dataset :param datadir: path to folder where data should be stored :param train_start: index of first training set example :param train_end: index of last training set example :param test_start: index of first test set example :param test_end: index of last test set example... | 2.832583 | 3 |
uspto_tools/parse/patent.py | clicumu/uspto-tools | 0 | 6631491 | """ This module containt simple wrapper classes for a US-patent,
inventor, patent-reference and classification.
"""
import re
class USPatent:
""" A single patent instance. """
def __init__(self, clean_id=True, **kwargs):
self._patent_number = None
self.date = None
self.country = None... | """ This module containt simple wrapper classes for a US-patent,
inventor, patent-reference and classification.
"""
import re
class USPatent:
""" A single patent instance. """
def __init__(self, clean_id=True, **kwargs):
self._patent_number = None
self.date = None
self.country = None... | en | 0.50555 | This module containt simple wrapper classes for a US-patent, inventor, patent-reference and classification. A single patent instance. Patent inventor. Set attributes of `instance` from keywords in `kwargs.` Parameters ---------- instance : Any Target-instance. kwargs : dict Keyword-argu... | 2.672079 | 3 |
ibeatles/step3/gui_handler.py | indudhiman/bragg-edge | 0 | 6631492 | <reponame>indudhiman/bragg-edge
from ibeatles.step1.plot import Step1Plot
from ibeatles.utilities.retrieve_data_infos import RetrieveGeneralFileInfos, RetrieveSelectedFileDataInfos
class Step3GuiHandler(object):
def __init__(self, parent=None):
self.parent = parent
def load_normalized_ch... | from ibeatles.step1.plot import Step1Plot
from ibeatles.utilities.retrieve_data_infos import RetrieveGeneralFileInfos, RetrieveSelectedFileDataInfos
class Step3GuiHandler(object):
def __init__(self, parent=None):
self.parent = parent
def load_normalized_changed(self, tab_index=0):
... | en | 0.251803 | # o_step1_plot = Step1Plot(parent = self.parent) # o_step1_plot.display_2d_preview() | 2.012195 | 2 |
src/OCR/architecture/util.py | tsteffek/LicensePlateReconstructor | 2 | 6631493 | <reponame>tsteffek/LicensePlateReconstructor<gh_stars>1-10
import logging
from typing import Iterable, Any, List
import torch
from pytorch_lightning.metrics import Metric
from torch import Tensor
from torch import nn
log = logging.getLogger('pytorch_lightning').getChild(__name__)
class Img2Seq(nn.Module):
def _... | import logging
from typing import Iterable, Any, List
import torch
from pytorch_lightning.metrics import Metric
from torch import Tensor
from torch import nn
log = logging.getLogger('pytorch_lightning').getChild(__name__)
class Img2Seq(nn.Module):
def __init__(self):
super().__init__()
@staticmetho... | en | 0.467911 | # width/time step, batch, channel # # this # uniques, count = torch.unique(torch.stack((targets, predictions)), return_counts=True) # t, p = uniques.unbind() # self.mat[t, p] = self.mat[t, p] + count # # or that | 2.214712 | 2 |
sympy/thirdparty/pyglet/pyglet/lib.py | gnulinooks/sympy | 1 | 6631494 | '''Functions for loading dynamic libraries.
These extend and correct ctypes functions.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: $'
import os
import re
import sys
import ctypes
import ctypes.util
class LibraryLoader(object):
def load_library(self, *names, **kwargs):
'''Find and load a ... | '''Functions for loading dynamic libraries.
These extend and correct ctypes functions.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: $'
import os
import re
import sys
import ctypes
import ctypes.util
class LibraryLoader(object):
def load_library(self, *names, **kwargs):
'''Find and load a ... | en | 0.831032 | Functions for loading dynamic libraries. These extend and correct ctypes functions. Find and load a library. More than one name can be specified, they will be tried in order. Platform-specific library names (given as kwargs) are tried first. Raises ImportError if library is not foun... | 3.05038 | 3 |
third_party/google/apputils/tests/datelib_unittest.py | lisagorewitdecker/immaculater | 0 | 6631495 | #!/usr/bin/env python
# Copyright 2002 Google Inc. 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... | #!/usr/bin/env python
# Copyright 2002 Google Inc. 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... | en | 0.773007 | #!/usr/bin/env python # Copyright 2002 Google Inc. 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... | 2.290255 | 2 |
scenario/quadcopter.py | HKUST-JM/iLQR_Traj_Trac | 0 | 6631496 | from math import sin
import numpy as np
import sympy as sp
from .dynamic_model import DynamicModelBase
from utils.Logger import logger
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import matplotlib as mpl
import math
class QuadCopter(DynamicModelBase):
def __init__(self, is_with_constraint... | from math import sin
import numpy as np
import sympy as sp
from .dynamic_model import DynamicModelBase
from utils.Logger import logger
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import matplotlib as mpl
import math
class QuadCopter(DynamicModelBase):
def __init__(self, is_with_constraint... | en | 0.577721 | ##### Dynamic Function ######## # number of state = 12, number of action = 4, prediction horizon = 100 # sampling time # p_x p_y p_z # v_x v_y v_z # phi(6) theta(7) psi(8) # omega_x omega_y omega_z # f1 f2 f3 f4 # m # m # Dynamics params # Make constant Bc matrix ##### Objective Function ######## # x and y If logger_fo... | 2.49758 | 2 |
tests/test_funcs.py | Alcampopiano/OpenQuestion | 4 | 6631497 | import os
import threading
import time
from server_code.server_surveys import *
import anvil.server
import pytest
import uuid
from datetime import datetime
import pandas as pd
import io
# basic survey
schema={
"title": "simple survey",
"settings": {
"survey_color": "#2196F3",
"thank_you_msg": "#Thank you!"
}... | import os
import threading
import time
from server_code.server_surveys import *
import anvil.server
import pytest
import uuid
from datetime import datetime
import pandas as pd
import io
# basic survey
schema={
"title": "simple survey",
"settings": {
"survey_color": "#2196F3",
"thank_you_msg": "#Thank you!"
}... | en | 0.846137 | # basic survey Everything before "yield" is run before any tests Everything after "yield" is run after all tests have finished # kill process on port in case it is running # func to call app server # start app server on a thread, allowing the rest of the script to run # give time for the web server to spin up before ... | 2.287365 | 2 |
qiita_db/test/test_analysis.py | jlab/qiita | 96 | 6631498 | from unittest import TestCase, main
from os import remove
from os.path import exists, join, basename
from shutil import move
from biom import load_table
from pandas.util.testing import assert_frame_equal
from functools import partial
from qiita_core.util import qiita_test_checker
from qiita_core.testing import wait_f... | from unittest import TestCase, main
from os import remove
from os.path import exists, join, basename
from shutil import move
from biom import load_table
from pandas.util.testing import assert_frame_equal
from functools import partial
from qiita_core.util import qiita_test_checker
from qiita_core.testing import wait_f... | en | 0.813054 | # ----------------------------------------------------------------------------- # Copyright (c) 2014--, The Qiita Development Team. # # Distributed under the terms of the BSD 3-clause License. # # The full license is in the file LICENSE, distributed with this software. # ------------------------------------------------... | 2.028823 | 2 |
test/run/t89.py | timmartin/skulpt | 2,671 | 6631499 | print {(1,3):'OK'}[(1,3)]
| print {(1,3):'OK'}[(1,3)]
| none | 1 | 1.672862 | 2 | |
activity_service_comm/main.py | shivan1b/kivy_osc | 0 | 6631500 | '''
Activity
'''
from kivy.app import App
from kivy.utils import platform
from kivy.lib import osc
from kivy.clock import Clock
from kivy.uix.button import Button
activity_port = 8008
service_port = 8000
class MyActivity(App):
'''
Defines the actions to be performed by Activity
'''
def build(self):
... | '''
Activity
'''
from kivy.app import App
from kivy.utils import platform
from kivy.lib import osc
from kivy.clock import Clock
from kivy.uix.button import Button
activity_port = 8008
service_port = 8000
class MyActivity(App):
'''
Defines the actions to be performed by Activity
'''
def build(self):
... | en | 0.853102 | Activity Defines the actions to be performed by Activity # Listen for messages regularly Send message to the service | 3.034075 | 3 |
Python/leetcode/letterCombinationsOfPhoneNumber.py | darrencheng0817/AlgorithmLearning | 2 | 6631501 | <reponame>darrencheng0817/AlgorithmLearning<filename>Python/leetcode/letterCombinationsOfPhoneNumber.py
'''
Created on 2016年1月11日
@author: Darren
'''
'''
Given a digit string, return all possible letter combinations that the number could represent.
A mapping of digit to letters (just like on the telephone buttons) is... | '''
Created on 2016年1月11日
@author: Darren
'''
'''
Given a digit string, return all possible letter combinations that the number could represent.
A mapping of digit to letters (just like on the telephone buttons) is given below.
Input:Digit string "23"
Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
... | en | 0.577041 | Created on 2016年1月11日 @author: Darren Given a digit string, return all possible letter combinations that the number could represent. A mapping of digit to letters (just like on the telephone buttons) is given below. Input:Digit string "23" Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]. :type digits:... | 4.137035 | 4 |
0144 Binary Tree Preorder Traversal.py | MdAbedin/leetcode | 4 | 6631502 | <gh_stars>1-10
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def preorderTraversal(self, root: TreeNode) -> List[int]:
if not root or not root.val:
return []
... | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def preorderTraversal(self, root: TreeNode) -> List[int]:
if not root or not root.val:
return []
lef... | en | 0.60307 | # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None | 3.801752 | 4 |
lib/upy2/typesetting/__init__.py | friedrichromstedt/upy | 3 | 6631503 | <reponame>friedrichromstedt/upy
from upy2.typesetting.scientific import ScientificTypesetter
| from upy2.typesetting.scientific import ScientificTypesetter | none | 1 | 1.082565 | 1 | |
pelicanconf.py | yang2lalang/blog | 0 | 6631504 | <reponame>yang2lalang/blog
#!/usr/bin/env python
# -*- coding: utf-8 -*- #
from __future__ import unicode_literals
from datetime import datetime
AUTHOR = u'<NAME>'
SITENAME = u'Franklin is Blogging'
SITEURL = 'http://localhost:8000'
SITETITLE = AUTHOR
SITESUBTITLE = 'Robotics Software Engineer, Part time Trader, Cons... | #!/usr/bin/env python
# -*- coding: utf-8 -*- #
from __future__ import unicode_literals
from datetime import datetime
AUTHOR = u'<NAME>'
SITENAME = u'Franklin is Blogging'
SITEURL = 'http://localhost:8000'
SITETITLE = AUTHOR
SITESUBTITLE = 'Robotics Software Engineer, Part time Trader, Consultant'
SITEDESCRIPTION = '... | en | 0.728706 | #!/usr/bin/env python # -*- coding: utf-8 -*- # # Feed Items # Uncomment following line if you want document-relative URLs when developing # | 1.613186 | 2 |
socutils/mongo_connector/database.py | Infosecurity-LLC/socutils | 1 | 6631505 | <reponame>Infosecurity-LLC/socutils<gh_stars>1-10
from .client import Client
class Database(object):
__instance = None
def __init__(self, client: Client, label: str = None):
"""
Database object helps creating instance of mongo connector
:param client: mongo_client.Client instance tha... | from .client import Client
class Database(object):
__instance = None
def __init__(self, client: Client, label: str = None):
"""
Database object helps creating instance of mongo connector
:param client: mongo_client.Client instance that used for getting config options
:param l... | en | 0.617333 | Database object helps creating instance of mongo connector :param client: mongo_client.Client instance that used for getting config options :param label: Label of the database connected to Creates mongo_client.Database instance from specified params :param label: Label of the database connecte... | 3.363742 | 3 |
tests/test_middleware.py | camuthig/django-user-api-key | 0 | 6631506 | from datetime import timedelta
from django.contrib.auth import get_user_model
from django.test import RequestFactory
from django.test import TestCase
from django.test.utils import override_settings
from django.utils import timezone
from django_pat.middleware import PatAuthenticationMiddleware
from django_pat.models i... | from datetime import timedelta
from django.contrib.auth import get_user_model
from django.test import RequestFactory
from django.test import TestCase
from django.test.utils import override_settings
from django.utils import timezone
from django_pat.middleware import PatAuthenticationMiddleware
from django_pat.models i... | en | 0.82564 | # Access the request's user to evaluate the lazy object | 2.207871 | 2 |
features.py | yctao7/Mobile-Phone-Opening-Prediction | 0 | 6631507 | import pandas as pd
from prep import get_ratio
from datetime import datetime, timedelta
stime, etime = 'formatted_start_time', 'formatted_end_time'
dformat = '%Y-%m-%d %H:%M:%S'
def get_between_with_duration(df0, target, merge_way, s, e, duration=None):
df = df0.copy()
df[stime] = pd.to_datetim... | import pandas as pd
from prep import get_ratio
from datetime import datetime, timedelta
stime, etime = 'formatted_start_time', 'formatted_end_time'
dformat = '%Y-%m-%d %H:%M:%S'
def get_between_with_duration(df0, target, merge_way, s, e, duration=None):
df = df0.copy()
df[stime] = pd.to_datetim... | en | 0.376354 | #df_avg.drop(columns=[duration], inplace=True) #df_avg[stime] = df_avg[stime].apply(lambda s: datetime.strftime(s, dformat)) #df_avg[etime] = df_avg[etime].apply(lambda s: datetime.strftime(s, dformat)) # df = pd.read_csv('./data/db_brightness_detail.csv') # df_user = df[df['enSN'] == 'ELS000040'].reset_index(drop=True... | 2.923072 | 3 |
benchs/tao/bench_learned_termination.py | uoynac/faiss-Tao | 0 | 6631508 | <filename>benchs/tao/bench_learned_termination.py
#!/usr/bin/env python2
import os
import sys
import time
import numpy as np
import re
import pickle
import argparse
import math
from multiprocessing.dummy import Pool as ThreadPool
sys.path.append('/home/wanghongya/faiss-learned-termination-master/python/')
import fais... | <filename>benchs/tao/bench_learned_termination.py
#!/usr/bin/env python2
import os
import sys
import time
import numpy as np
import re
import pickle
import argparse
import math
from multiprocessing.dummy import Pool as ThreadPool
sys.path.append('/home/wanghongya/faiss-learned-termination-master/python/')
import fais... | en | 0.739875 | #!/usr/bin/env python2 ################################################################# # Bookkeeping ################################################################# # Where the dataset base, query, learn files are stored. # Where the ground truth files are stored. # Where the *_trained.index files are stored. # Whe... | 1.884543 | 2 |
Search_based_Planning/Search_2D/bfs.py | gtianyi/metaReasoningAnimation | 0 | 6631509 | <reponame>gtianyi/metaReasoningAnimation
"""
Breadth-first Searching_2D (BFS)
@author: <NAME>
"""
import math
import heapq
import os
import sys
sys.path.append(os.path.dirname(os.path.abspath(__file__)) +
"/../../Search_based_Planning/")
from Search_2D import plotting
from Search_2D.Astar import ASta... | """
Breadth-first Searching_2D (BFS)
@author: <NAME>
"""
import math
import heapq
import os
import sys
sys.path.append(os.path.dirname(os.path.abspath(__file__)) +
"/../../Search_based_Planning/")
from Search_2D import plotting
from Search_2D.Astar import AStar
# from collections import deque
class... | en | 0.797436 | Breadth-first Searching_2D (BFS) @author: <NAME> # from collections import deque BFS add the new visited node in the end of the openset Breadth-first Searching. :return: path, visited order # conditions for updating Cost # bfs, add new node to the end of the openset | 3.494199 | 3 |
Moving Averages/TF_Adaptive_Moving_Average.py | sofienkaabar/Trend-Following-Strategies-in-Python | 18 | 6631510 | # Base Parameters
assets = asset_list('FX')
# Trading Parameters
horizon = 'H1'
pair = 0
# Mass Imports
my_data = mass_import(pair, horizon)
# Indicator Parameters
lookback = 100
def kama(Data, what, where, lookback):
Data = adder(Data, 10)
# lookback from previous period
... | # Base Parameters
assets = asset_list('FX')
# Trading Parameters
horizon = 'H1'
pair = 0
# Mass Imports
my_data = mass_import(pair, horizon)
# Indicator Parameters
lookback = 100
def kama(Data, what, where, lookback):
Data = adder(Data, 10)
# lookback from previous period
... | en | 0.642944 | # Base Parameters # Trading Parameters # Mass Imports # Indicator Parameters # lookback from previous period # Sum of lookbacks # Volatility # Efficiency Ratio | 2.369885 | 2 |
skyscanner.py | gen2127/TK_1919 | 0 | 6631511 | <filename>skyscanner.py
import requests
import json
import urllib
import webbrowser
url = "https://skyscanner-skyscanner-flight-search-v1.p.rapidapi.com/apiservices/pricing/v1.0"
APIKey = "<KEY>"
headers={
"X-RapidAPI-Host": "skyscanner-skyscanner-flight-search-v1.p.rapidapi.com",
"X-RapidAPI-Key": APIKey,
... | <filename>skyscanner.py
import requests
import json
import urllib
import webbrowser
url = "https://skyscanner-skyscanner-flight-search-v1.p.rapidapi.com/apiservices/pricing/v1.0"
APIKey = "<KEY>"
headers={
"X-RapidAPI-Host": "skyscanner-skyscanner-flight-search-v1.p.rapidapi.com",
"X-RapidAPI-Key": APIKey,
... | en | 0.43853 | #urllib.request.urlopen(r) #r = req.headers #print(r) #print(r['Location']) #headers={ # "X-RapidAPI-Host": "skyscanner-skyscanner-flight-search-v1.p.rapidapi.com", # "X-RapidAPI-Key": APIKey, # "Content-Type": "application/json" #} #q = requests.post(r['Location'],headers = headers) #print(q) | 3.542863 | 4 |
tests/test_parallel_pool.py | srafehi/taskall | 0 | 6631512 | <gh_stars>0
from unittest import TestCase
import taskall
from taskall import parallel
import multiprocessing
class TestParallelPool(TestCase):
@staticmethod
def multiply(a, b):
return a * b
def test_pool_size_default(self):
pool = parallel.pool(pool_size=None)
self.assertEquals(po... | from unittest import TestCase
import taskall
from taskall import parallel
import multiprocessing
class TestParallelPool(TestCase):
@staticmethod
def multiply(a, b):
return a * b
def test_pool_size_default(self):
pool = parallel.pool(pool_size=None)
self.assertEquals(pool.pool_size... | none | 1 | 2.996573 | 3 | |
ilexconf/tests/examples/test_quick_start.py | vduseev/holly-config | 9 | 6631513 | import os
import pytest
from ilexconf import Config, from_json, to_json
# from ilexconf.tests.debug import debug
@pytest.fixture(scope="module")
def resulting_dict():
return {
"database": {
"connection": {
"host": "test.local",
"port": 8080,
"u... | import os
import pytest
from ilexconf import Config, from_json, to_json
# from ilexconf.tests.debug import debug
@pytest.fixture(scope="module")
def resulting_dict():
return {
"database": {
"connection": {
"host": "test.local",
"port": 8080,
"u... | en | 0.740019 | # from ilexconf.tests.debug import debug # os.putenv("AWS_DEFAULT_REGION", "us-east-1") # [create] # Empty config # Create config from json and merge it into our initial config # Let settings_json_file_path = "settings.json" where inside the file we have # { "database": { "connection": { "host": "localhost", "port": 54... | 2.274183 | 2 |
golem/test_runner/excel_runner/ExcelUtils.py | kangchenwei/keyautotest2 | 0 | 6631514 | <gh_stars>0
# import xlrd
import xlrd
import time
class ExcelUtils:
def __init__(self, filePath, driver):
self.data = xlrd.open_workbook(filePath)
self.driver = driver
def getTableData(self, tableName):
return self.data.sheet_by_name(tableName)
def getRowValues(self, tableData, r... | # import xlrd
import xlrd
import time
class ExcelUtils:
def __init__(self, filePath, driver):
self.data = xlrd.open_workbook(filePath)
self.driver = driver
def getTableData(self, tableName):
return self.data.sheet_by_name(tableName)
def getRowValues(self, tableData, rowId):
... | zh | 0.584371 | # import xlrd #默认执行第一个sheet #执行路径为filePath,sheet名字是sheetName的Excel ##这里仅仅是做了执行,如果要转换成py脚本,跟这个思路类似,略有不同 #判断关键字的类型,分别对应进行操作 # if keyAction == 'sleep': # time.sleep(keyValue) # if keyFindWay == '' or keyElement == '': # #为了节省时间,这里只考虑到常规的查找控件然后操作,对于坐标类的,启动app类的都没做考虑 # continue # element = excelUtils.getElement(... | 2.591539 | 3 |
src/cust_utils/utils.py | muiton/123MoviesRIpper | 11 | 6631515 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from . import path_util
import subprocess
def create_file(file_path, file_name, data_to_write):
if not isinstance(data_to_write, str):
data_to_write = str(data_to_write)
if not data_to_write or not str(data_to_write).strip():
print("Empty data prov... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from . import path_util
import subprocess
def create_file(file_path, file_name, data_to_write):
if not isinstance(data_to_write, str):
data_to_write = str(data_to_write)
if not data_to_write or not str(data_to_write).strip():
print("Empty data prov... | en | 0.352855 | #!/usr/bin/env python # -*- coding: utf-8 -*- | 3.076675 | 3 |
testproject/testapp/validators.py | n3rdftw/djoser | 1 | 6631516 | <reponame>n3rdftw/djoser
def is_666(value):
from rest_framework import serializers
if value == '666':
raise serializers.ValidationError('Woops, 666 is not allowed.')
| def is_666(value):
from rest_framework import serializers
if value == '666':
raise serializers.ValidationError('Woops, 666 is not allowed.') | none | 1 | 2.527579 | 3 | |
faker/providers/person/ar_AA/__init__.py | jacksmith15/faker | 1 | 6631517 | <reponame>jacksmith15/faker
from typing import Tuple
from .. import Provider as PersonProvider
class Provider(PersonProvider):
formats_female: Tuple[str, ...] = (
"{{first_name_female}} {{last_name}}",
"{{prefix_female}} {{first_name_female}} {{last_name}}",
)
formats_male: Tuple[str, ..... | from typing import Tuple
from .. import Provider as PersonProvider
class Provider(PersonProvider):
formats_female: Tuple[str, ...] = (
"{{first_name_female}} {{last_name}}",
"{{prefix_female}} {{first_name_female}} {{last_name}}",
)
formats_male: Tuple[str, ...] = (
"{{first_name... | none | 1 | 2.905559 | 3 | |
sdk/python/pulumi_gcp/spanner/_inputs.py | sisisin/pulumi-gcp | 121 | 6631518 | # coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import... | # coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import... | en | 0.919155 | # coding=utf-8 # *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** :param pulumi.Input[str] kms_key_name: Fully qualified name of the KMS key to use to encrypt this database. This key must exist ... | 1.973987 | 2 |
units/src/convert_units/measurements.py | tinnuadan/redcogs | 1 | 6631519 | import json
from typing import Dict, List
class Measure():
""" A single measure (e.g. kg). Contains the conversion to the anchor, the unit, name, aliases and the parent Measurement collection"""
def __init__(self, parent):
self.unit: str = ""
self.aliases: List = []
self.name: str = ""
self.to_an... | import json
from typing import Dict, List
class Measure():
""" A single measure (e.g. kg). Contains the conversion to the anchor, the unit, name, aliases and the parent Measurement collection"""
def __init__(self, parent):
self.unit: str = ""
self.aliases: List = []
self.name: str = ""
self.to_an... | en | 0.898162 | A single measure (e.g. kg). Contains the conversion to the anchor, the unit, name, aliases and the parent Measurement collection Holds which Measure is used as the anchor of a Measurement Holds a collection of measures (metric or imperial), which have a common anchor they can be converted to #ratio | 3.447145 | 3 |
google/cloud/forseti/scanner/audit/ke_rules_engine.py | Sandesh36/forseti-security | 0 | 6631520 | <gh_stars>0
# Copyright 2017 The Forseti Security Authors. 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 re... | # Copyright 2017 The Forseti Security Authors. 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 ap... | en | 0.787531 | # Copyright 2017 The Forseti Security Authors. 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 ap... | 1.798786 | 2 |
structmanager/optimization/sol200/cards_opt.py | saullocastro/structmanager | 1 | 6631521 | <filename>structmanager/optimization/sol200/cards_opt.py
"""
Optimization cards (:mod:`structmanager.sol200.cards_opt`)
==========================================================
.. currentmodule:: structmanager.sol200.cards_opt`
Many input cards related to the optimization problem are wrapped in this
module. The inp... | <filename>structmanager/optimization/sol200/cards_opt.py
"""
Optimization cards (:mod:`structmanager.sol200.cards_opt`)
==========================================================
.. currentmodule:: structmanager.sol200.cards_opt`
Many input cards related to the optimization problem are wrapped in this
module. The inp... | en | 0.567132 | Optimization cards (:mod:`structmanager.sol200.cards_opt`) ========================================================== .. currentmodule:: structmanager.sol200.cards_opt` Many input cards related to the optimization problem are wrapped in this module. The input cards more related to the solver are contained in module :... | 2.26457 | 2 |
leetcode/q0022-generate-parentheses/solution.py | HiAwesome/python-leetcode | 0 | 6631522 | <filename>leetcode/q0022-generate-parentheses/solution.py
"""
https://leetcode-cn.com/problems/generate-parentheses/
https://leetcode-cn.com/problems/generate-parentheses/solution/gua-hao-sheng-cheng-by-leetcode-solution/
"""
from functools import lru_cache
from typing import List
class Solution:
@lru_cache(None... | <filename>leetcode/q0022-generate-parentheses/solution.py
"""
https://leetcode-cn.com/problems/generate-parentheses/
https://leetcode-cn.com/problems/generate-parentheses/solution/gua-hao-sheng-cheng-by-leetcode-solution/
"""
from functools import lru_cache
from typing import List
class Solution:
@lru_cache(None... | en | 0.562167 | https://leetcode-cn.com/problems/generate-parentheses/ https://leetcode-cn.com/problems/generate-parentheses/solution/gua-hao-sheng-cheng-by-leetcode-solution/ | 3.352703 | 3 |
tests/geometric_types_test.py | yisibl/picosvg | 72 | 6631523 | # Copyright 2020 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2020 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | en | 0.887484 | # Copyright 2020 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 # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ... | 3.030063 | 3 |
genomic_data_service/rnaseq/commands/index_rna_seq_data.py | ENCODE-DCC/genomic-data-service | 3 | 6631524 | <reponame>ENCODE-DCC/genomic-data-service
import click
from elasticsearch import Elasticsearch as Client
from genomic_data_service.rnaseq.expressions import Expressions
from genomic_data_service.rnaseq.repository.elasticsearch import Elasticsearch
from genomic_data_service.rnaseq.remote.portal import Portal
HOST = ... | import click
from elasticsearch import Elasticsearch as Client
from genomic_data_service.rnaseq.expressions import Expressions
from genomic_data_service.rnaseq.repository.elasticsearch import Elasticsearch
from genomic_data_service.rnaseq.remote.portal import Portal
HOST = '127.0.0.1:9202'
@click.command()
@click... | none | 1 | 1.847125 | 2 | |
tests/unit/modules/readers/test_JecVariations.py | shane-breeze/zinv-analysis | 1 | 6631525 | import pytest
import mock
import os
import numpy as np
import awkward as awk
from zinv.modules.readers import JecVariations
class DummyColl(object):
pass
class DummyEvent(object):
def __init__(self):
self.iblock = 0
self.nsig = 0
self.source = ''
self.cache = {}
self.a... | import pytest
import mock
import os
import numpy as np
import awkward as awk
from zinv.modules.readers import JecVariations
class DummyColl(object):
pass
class DummyEvent(object):
def __init__(self):
self.iblock = 0
self.nsig = 0
self.source = ''
self.cache = {}
self.a... | hi | 0.069309 | #module.event(event) | 1.961872 | 2 |
Lab_5/Q7.py | Hubert-HD/Lab_ADA | 0 | 6631526 | # Q7: What is the time complexity of
import random
n = int(random.random() * 100)
i = 1
while i < n:
print(i)
i = i * 2
""""
N° iteracion value de i
1 1
2 1 * 2
3 (1 * 2) * 2
4 ((1 * 2) * 2) * 2
. .
... | # Q7: What is the time complexity of
import random
n = int(random.random() * 100)
i = 1
while i < n:
print(i)
i = i * 2
""""
N° iteracion value de i
1 1
2 1 * 2
3 (1 * 2) * 2
4 ((1 * 2) * 2) * 2
. .
... | en | 0.324162 | # Q7: What is the time complexity of "
N° iteracion value de i
1 1
2 1 * 2
3 (1 * 2) * 2
4 ((1 * 2) * 2) * 2
. .
. .
. .
k 1 * 2^(k-1)
i > n
2^(k-1... | 3.815935 | 4 |
examples/quickstart.py | tushkanin/jsondataclass | 0 | 6631527 | from dataclasses import dataclass
from jsondataclass import to_json, from_json
@dataclass
class Movie:
name: str
year: int
county: str
movie = Movie("Terminator: Dark Fate", 2019, "USA")
print(to_json(movie))
# > {"name": "Terminator: Dark Fate", "year": 2019, "county": "USA"}
json_str = '{"name": "Ter... | from dataclasses import dataclass
from jsondataclass import to_json, from_json
@dataclass
class Movie:
name: str
year: int
county: str
movie = Movie("Terminator: Dark Fate", 2019, "USA")
print(to_json(movie))
# > {"name": "Terminator: Dark Fate", "year": 2019, "county": "USA"}
json_str = '{"name": "Ter... | en | 0.541332 | # > {"name": "Terminator: Dark Fate", "year": 2019, "county": "USA"} # > Movie(name='Terminator: Dark Fate', year=2019, county='USA') | 3.703198 | 4 |
from_python_community/move_zeroes.py | ZaytsevNS/python_practice | 0 | 6631528 | # Условие:
# Ваша задача — написать функцию, которая перемещает все нули в конец списка.
# Функция принимает список с набором цифр, а ваша задача — изменить его так, что бы нули оказались в конце списка.
# Она ничего не возвращает, а лишь меняет полученный список. Порядок ненулевых чисел должен сохранится.
import u... | # Условие:
# Ваша задача — написать функцию, которая перемещает все нули в конец списка.
# Функция принимает список с набором цифр, а ваша задача — изменить его так, что бы нули оказались в конце списка.
# Она ничего не возвращает, а лишь меняет полученный список. Порядок ненулевых чисел должен сохранится.
import u... | ru | 0.996104 | # Условие: # Ваша задача — написать функцию, которая перемещает все нули в конец списка. # Функция принимает список с набором цифр, а ваша задача — изменить его так, что бы нули оказались в конце списка. # Она ничего не возвращает, а лишь меняет полученный список. Порядок ненулевых чисел должен сохранится. Should retur... | 4.381165 | 4 |
src/register.py | squidt/git-custom-commands | 0 | 6631529 | import sys
from git import Repo
# what we're doing in git terms:
#
# git config alias.<name> '!"<python.exe filepath>" "<script>"'
#
# english:
#
# Create a .bat 'in place' within the alias and make it call a python script.
# The python script can then run any amount of git commands or do whatever
# it want... | import sys
from git import Repo
# what we're doing in git terms:
#
# git config alias.<name> '!"<python.exe filepath>" "<script>"'
#
# english:
#
# Create a .bat 'in place' within the alias and make it call a python script.
# The python script can then run any amount of git commands or do whatever
# it want... | en | 0.635293 | # what we're doing in git terms: # # git config alias.<name> '!"<python.exe filepath>" "<script>"' # # english: # # Create a .bat 'in place' within the alias and make it call a python script. # The python script can then run any amount of git commands or do whatever # it wants. | 2.466906 | 2 |
ultrasonic/ultrasonic.py | pankajdahilkar/FishPondMonetor | 0 | 6631530 | import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BOARD)
TRIG = 16
ECHO = 18
i=0
GPIO.setup(TRIG,GPIO.OUT)
GPIO.setup(ECHO,GPIO.IN)
GPIO.output(TRIG, False)
print("Calibrating.....")
time.sleep(2)
print ("Place the object......")
max_water_level = 18
min_water_level = 5
try:
while True:
GPIO.output(TRI... | import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BOARD)
TRIG = 16
ECHO = 18
i=0
GPIO.setup(TRIG,GPIO.OUT)
GPIO.setup(ECHO,GPIO.IN)
GPIO.output(TRIG, False)
print("Calibrating.....")
time.sleep(2)
print ("Place the object......")
max_water_level = 18
min_water_level = 5
try:
while True:
GPIO.output(TRI... | none | 1 | 3.268334 | 3 | |
python/place_components.py | willdickson/ring_light_72mm_id_4_row_168_led | 1 | 6631531 | <reponame>willdickson/ring_light_72mm_id_4_row_168_led<filename>python/place_components.py
import os
import sys
import math
import pickle
import pcbnew
from design import RingLightDesign
def nm_to_mm(value):
return value*1.0e-6
def mm_to_nm(value):
return value*1.0e6
def rad_to_deg(value):
return 180.0*... | import os
import sys
import math
import pickle
import pcbnew
from design import RingLightDesign
def nm_to_mm(value):
return value*1.0e-6
def mm_to_nm(value):
return value*1.0e6
def rad_to_deg(value):
return 180.0*value/math.pi
def deg_to_rad(value):
return 180.0*value/math.pi
# -------------------... | en | 0.169628 | # ----------------------------------------------------------------------------- # {led_num}: {ref_str}') # Move modules to new position # Make value invisible # {r_num}: {ref_str}') #new_pos_x = led_pos[0] #new_pos_y = led_pos[1] | 2.470296 | 2 |
test/test_linting.py | druvus/bioconda-utils | 0 | 6631532 | from helpers import Recipes
from bioconda_utils import lint_functions
from bioconda_utils import linting, utils
def run_lint(
func,
should_pass,
should_fail
):
"""
Helper function to run a lint function on a set of recipes that should pass
and that should fail.
Recall each lint function t... | from helpers import Recipes
from bioconda_utils import lint_functions
from bioconda_utils import linting, utils
def run_lint(
func,
should_pass,
should_fail
):
"""
Helper function to run a lint function on a set of recipes that should pass
and that should fail.
Recall each lint function t... | en | 0.532071 | Helper function to run a lint function on a set of recipes that should pass and that should fail. Recall each lint function takes recipe path, parsed meta.yaml, and dataframe of channel info. Parameters ---------- func : function Function to test in `bioconda_utils.lint_functions` ... | 2.669441 | 3 |
monasca-log-api-2.9.0/monasca_log_api/tests/test_policy.py | scottwedge/OpenStack-Stein | 0 | 6631533 | <gh_stars>0
# Copyright 2016-2017 FUJITSU LIMITED
# Copyright 2018 OP5 AB
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requir... | # Copyright 2016-2017 FUJITSU LIMITED
# Copyright 2018 OP5 AB
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applic... | en | 0.828335 | # Copyright 2016-2017 FUJITSU LIMITED # Copyright 2018 OP5 AB # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applic... | 1.656169 | 2 |
tests/unit/test_merged_config_parser.py | jmcgill298/flake8 | 0 | 6631534 | """Unit tests for flake8.options.config.MergedConfigParser."""
import os
import mock
import pytest
from flake8.options import config
from flake8.options import manager
@pytest.fixture
def optmanager():
"""Generate an OptionManager with simple values."""
return manager.OptionManager(prog='flake8', version='3... | """Unit tests for flake8.options.config.MergedConfigParser."""
import os
import mock
import pytest
from flake8.options import config
from flake8.options import manager
@pytest.fixture
def optmanager():
"""Generate an OptionManager with simple values."""
return manager.OptionManager(prog='flake8', version='3... | en | 0.72653 | Unit tests for flake8.options.config.MergedConfigParser. Generate an OptionManager with simple values. Generate a simple ConfigFileFinder. Parse the specified config file as a cli config file. Verify the behaviour of the is_configured_by method. Verify parsing of user config files. Verify parsing of local config files.... | 2.491496 | 2 |
DailyProgrammer/DP20120709A.py | DayGitH/Python-Challenges | 2 | 6631535 | """
The Fibonacci numbers, which we are all familiar with, start like this:
0,1,1,2,3,5,8,13,21,34,...
Where each new number in the sequence is the sum of the previous two.
It turns out that by summing different Fibonacci numbers with each other, you can create every single positive integer.
In fact, a much stronger... | """
The Fibonacci numbers, which we are all familiar with, start like this:
0,1,1,2,3,5,8,13,21,34,...
Where each new number in the sequence is the sum of the previous two.
It turns out that by summing different Fibonacci numbers with each other, you can create every single positive integer.
In fact, a much stronger... | en | 0.909266 | The Fibonacci numbers, which we are all familiar with, start like this: 0,1,1,2,3,5,8,13,21,34,... Where each new number in the sequence is the sum of the previous two. It turns out that by summing different Fibonacci numbers with each other, you can create every single positive integer. In fact, a much stronger sta... | 3.983549 | 4 |
src/docs/conf.py | fractal-napari-plugins-collection/user-documentation | 0 | 6631536 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#
import os
import sys
sys.path.in... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#
import os
import sys
sys.path.in... | en | 0.630323 | #!/usr/bin/env python3 # -*- coding: utf-8 -*- # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. # # -- General configuration ------... | 1.646322 | 2 |
zeus/api/schemas/stats.py | edgerepo/zeus | 0 | 6631537 | <filename>zeus/api/schemas/stats.py
from collections import defaultdict
from marshmallow import Schema, fields, pre_dump
class CoverageStatsSchema(Schema):
lines_covered = fields.Integer()
lines_uncovered = fields.Integer()
diff_lines_covered = fields.Integer()
diff_lines_uncovered = fields.Integer()
... | <filename>zeus/api/schemas/stats.py
from collections import defaultdict
from marshmallow import Schema, fields, pre_dump
class CoverageStatsSchema(Schema):
lines_covered = fields.Integer()
lines_uncovered = fields.Integer()
diff_lines_covered = fields.Integer()
diff_lines_uncovered = fields.Integer()
... | en | 0.874127 | # should be "dumped" with a list of ItemStat instances | 2.332183 | 2 |
plugins/cisco_umbrella_investigate/komand_cisco_umbrella_investigate/actions/samples/action.py | lukaszlaszuk/insightconnect-plugins | 46 | 6631538 | import komand
from .schema import SamplesInput, SamplesOutput, Input
# Custom imports below
from komand.exceptions import PluginException
class Samples(komand.Action):
def __init__(self):
super(self.__class__, self).__init__(
name="samples",
description="Return all samples associa... | import komand
from .schema import SamplesInput, SamplesOutput, Input
# Custom imports below
from komand.exceptions import PluginException
class Samples(komand.Action):
def __init__(self):
super(self.__class__, self).__init__(
name="samples",
description="Return all samples associa... | en | 0.469003 | # Custom imports below | 2.137325 | 2 |
research/slim/plots.py | tathey1/models | 0 | 6631539 | <reponame>tathey1/models
'''
These functions provide data for ROC and confusion matrix plots from results in txt files
It is meant to read data from text files that have been produced by classify.py
'''
from sklearn.metrics import confusion_matrix, roc_curve
def conf_matrix(data_file):
'''
Args: data_file path to ... | '''
These functions provide data for ROC and confusion matrix plots from results in txt files
It is meant to read data from text files that have been produced by classify.py
'''
from sklearn.metrics import confusion_matrix, roc_curve
def conf_matrix(data_file):
'''
Args: data_file path to text file
tab delimit... | en | 0.863315 | These functions provide data for ROC and confusion matrix plots from results in txt files It is meant to read data from text files that have been produced by classify.py Args: data_file path to text file tab delimited with a single header row then subsequent rows organized as image name, [n class probabilities]... | 3.592316 | 4 |
data_importer/data_importer/util/cameradevice.py | JadeCong/HandControl_MuJoCo | 0 | 6631540 | """Basis for depth camera devices.
CameraDevice provides interface for managing depth cameras.
It can be used to retrieve basic information and read
depth and color frames.
Copyright 2015 <NAME>, ICG,
Graz University of Technology <<EMAIL>>
This file is part of DeepPrior.
DeepPrior is free software: you can redistr... | """Basis for depth camera devices.
CameraDevice provides interface for managing depth cameras.
It can be used to retrieve basic information and read
depth and color frames.
Copyright 2015 <NAME>, ICG,
Graz University of Technology <<EMAIL>>
This file is part of DeepPrior.
DeepPrior is free software: you can redistr... | en | 0.718079 | Basis for depth camera devices. CameraDevice provides interface for managing depth cameras. It can be used to retrieve basic information and read depth and color frames. Copyright 2015 <NAME>, ICG, Graz University of Technology <<EMAIL>> This file is part of DeepPrior. DeepPrior is free software: you can redistribu... | 2.28507 | 2 |
tests/snapshots/snap_test_NotebookScripter.py | breathe/NotebookScripter | 23 | 6631541 | <gh_stars>10-100
# -*- coding: utf-8 -*-
# snapshottest: v1 - https://goo.gl/zC4yUc
from __future__ import unicode_literals
from snapshottest import Snapshot
snapshots = Snapshot()
snapshots['TestNotebookExecution::test_magics_are_unregistered 1'] = 'matplotlib'
snapshots['TestNotebookExecution::test_run_notebook ... | # -*- coding: utf-8 -*-
# snapshottest: v1 - https://goo.gl/zC4yUc
from __future__ import unicode_literals
from snapshottest import Snapshot
snapshots = Snapshot()
snapshots['TestNotebookExecution::test_magics_are_unregistered 1'] = 'matplotlib'
snapshots['TestNotebookExecution::test_run_notebook 1'] = 'Hello defa... | en | 0.629015 | # -*- coding: utf-8 -*- # snapshottest: v1 - https://goo.gl/zC4yUc | 1.774753 | 2 |
ceph_installer/controllers/status.py | ceph/ceph-installer | 16 | 6631542 | from pecan import response, expose
from ceph_installer.hooks import system_checks, SystemCheckError
class StatusController(object):
@expose('json')
def index(self):
for check in system_checks:
try:
check()
except SystemCheckError as system_error:
... | from pecan import response, expose
from ceph_installer.hooks import system_checks, SystemCheckError
class StatusController(object):
@expose('json')
def index(self):
for check in system_checks:
try:
check()
except SystemCheckError as system_error:
... | none | 1 | 2.241942 | 2 | |
fat.py | JG-OLIVEIRA/math_repo | 0 | 6631543 | <reponame>JG-OLIVEIRA/math_repo
def fat(value):
if value > 1:
return value * fat(value - 1)
return 1
print(fat(5)/ fat(3) * fat(2))
print(fat(4))
print(fat(3))
print(fat(2))
print(fat(1)) | def fat(value):
if value > 1:
return value * fat(value - 1)
return 1
print(fat(5)/ fat(3) * fat(2))
print(fat(4))
print(fat(3))
print(fat(2))
print(fat(1)) | none | 1 | 3.599607 | 4 | |
summarizemultistability.py | BenNordick/HiLoop | 1 | 6631544 | import argparse
import collections
import colorsys
import copy
import cycler
import json
import matplotlib.collections as mplcollect
import matplotlib.colors as mplcolors
import matplotlib.patches as mplpatch
import matplotlib.pyplot as plt
import matplotlib.ticker as mpltick
import mpl_toolkits.axes_grid1.inset_locato... | import argparse
import collections
import colorsys
import copy
import cycler
import json
import matplotlib.collections as mplcollect
import matplotlib.colors as mplcolors
import matplotlib.patches as mplpatch
import matplotlib.pyplot as plt
import matplotlib.ticker as mpltick
import mpl_toolkits.axes_grid1.inset_locato... | en | 0.825817 | # Creates visualizations from JSON reports generated by multistability.py Determine whether the given attractor value is an oscillatory attractor. Turn the given attractor information value (which might be an oscillation) into a single list, for comparison. Caricature each species in the given attractor set (nested lis... | 2.668521 | 3 |
_08_APRIL_2020/_02_eastern_bunny.py | Andrey-V-Georgiev/PythonAdvanced | 1 | 6631545 | <gh_stars>1-10
import sys
size = int(input())
matrix = []
player_position = []
# Fill up the matrix and find player position
for i in range(size):
row_list = list(input().split())
matrix.append(row_list)
for j in range(size):
if row_list[j] == 'B':
player_position = [i, j]
player_row, ... | import sys
size = int(input())
matrix = []
player_position = []
# Fill up the matrix and find player position
for i in range(size):
row_list = list(input().split())
matrix.append(row_list)
for j in range(size):
if row_list[j] == 'B':
player_position = [i, j]
player_row, player_col = pl... | en | 0.680345 | # Fill up the matrix and find player position # check up # check down # check left # check right | 3.069986 | 3 |
src/qalgebra/core/matrix_algebra.py | anna-naden/qalgebra | 2 | 6631546 | <filename>src/qalgebra/core/matrix_algebra.py
"""Matrices of Expressions."""
import numpy as np
import sympy
from sympy import I, Symbol, sympify
from .abstract_algebra import Expression, substitute
from .abstract_quantum_algebra import QuantumExpression
from .exceptions import NoConjugateMatrix, NonSquareMatrix
from ... | <filename>src/qalgebra/core/matrix_algebra.py
"""Matrices of Expressions."""
import numpy as np
import sympy
from sympy import I, Symbol, sympify
from .abstract_algebra import Expression, substitute
from .abstract_quantum_algebra import QuantumExpression
from .exceptions import NoConjugateMatrix, NonSquareMatrix
from ... | en | 0.748907 | Matrices of Expressions. # anything not in __all__ must be in __private__ Matrix of Expressions. The shape of the matrix ``(nrows, ncols)``. For square matrices this gives the block (-diagonal) structure of the matrix as a tuple of integers that sum up to the full dimension. :rtype: tuple Are all eleme... | 3.152826 | 3 |
bokeh/tests/test_widgets.py | timelyportfolio/bokeh | 1 | 6631547 | from __future__ import absolute_import
import unittest
import inspect
def get_prop_set(class_object):
# all this does is get a list of every property implemented by the object that is not present in the baseclasses of said object
# note it wont detect overridden properties!
base_classes = list(inspect.ge... | from __future__ import absolute_import
import unittest
import inspect
def get_prop_set(class_object):
# all this does is get a list of every property implemented by the object that is not present in the baseclasses of said object
# note it wont detect overridden properties!
base_classes = list(inspect.ge... | en | 0.944783 | # all this does is get a list of every property implemented by the object that is not present in the baseclasses of said object # note it wont detect overridden properties! | 2.268935 | 2 |
xmlParser.py | isseikz/StarTracker | 0 | 6631548 | <reponame>isseikz/StarTracker
#!/usr/bin/python
# -*- coding: utf-8 -*-
import xml.etree.ElementTree as ET
import urllib.parse
def urlFromFile(filepath, debug=0):
tree = ET.parse(filepath)
root = tree.getroot()
return addrFrom(root, debug)
def urlFromXml(xml_string, debug=0):
root = ET.fromstring(xm... | #!/usr/bin/python
# -*- coding: utf-8 -*-
import xml.etree.ElementTree as ET
import urllib.parse
def urlFromFile(filepath, debug=0):
tree = ET.parse(filepath)
root = tree.getroot()
return addrFrom(root, debug)
def urlFromXml(xml_string, debug=0):
root = ET.fromstring(xml_string)
return addrFrom(... | en | 0.44423 | #!/usr/bin/python # -*- coding: utf-8 -*- | 2.428971 | 2 |
rest_notifications/tests/test_notifications.py | yeti/rest_notifications | 1 | 6631549 | <filename>rest_notifications/tests/test_notifications.py<gh_stars>1-10
from django.conf import settings
from django.contrib.auth import get_user_model
from django.contrib.contenttypes.models import ContentType
from django.core import mail
from django.core.urlresolvers import reverse
from mock import MagicMock
from mant... | <filename>rest_notifications/tests/test_notifications.py<gh_stars>1-10
from django.conf import settings
from django.contrib.auth import get_user_model
from django.contrib.contenttypes.models import ContentType
from django.core import mail
from django.core.urlresolvers import reverse
from mock import MagicMock
from mant... | en | 0.945189 | # Non-authenticated users can't create a token # Can't create token if write-only language and hwid data is missing # If receiver is the same as the reporter, a notification is not created # If the receiver and reporter are different, a notification is created # An email and a push are sent if allow_email and allow_pus... | 2.024799 | 2 |
lib/core/psp.py | TotalVariation/Flattenet | 3 | 6631550 | from collections import OrderedDict
import torch
import torch.nn as nn
import torch.nn.functional as F
from .conv import conv1x1
class PyramidPooling(nn.Module):
"""
Reference:
Zhao, Hengshuang, et al. *"Pyramid scene parsing network."*
"""
def __init__(self, in_channels, pool_sizes, norm_la... | from collections import OrderedDict
import torch
import torch.nn as nn
import torch.nn.functional as F
from .conv import conv1x1
class PyramidPooling(nn.Module):
"""
Reference:
Zhao, Hengshuang, et al. *"Pyramid scene parsing network."*
"""
def __init__(self, in_channels, pool_sizes, norm_la... | en | 0.484141 | Reference: Zhao, Hengshuang, et al. *"Pyramid scene parsing network."* # bilinear interpolation options | 2.515069 | 3 |