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 |
|---|---|---|---|---|---|---|---|---|---|---|
exemplo/executar_sintatico.py | AlanTaranti/CompiladorLALG | 1 | 6622951 | <filename>exemplo/executar_sintatico.py<gh_stars>1-10
# Exemplo de Execução do Analisador Sintático
#
# Desenvolvedor: <NAME>
# Main
if __name__ == "__main__":
#
# Importar Analisador
#
import sys, os
sys.path.append("..")
from analisador import Sintatico
dir = os.path.dirname(os.path.... | <filename>exemplo/executar_sintatico.py<gh_stars>1-10
# Exemplo de Execução do Analisador Sintático
#
# Desenvolvedor: <NAME>
# Main
if __name__ == "__main__":
#
# Importar Analisador
#
import sys, os
sys.path.append("..")
from analisador import Sintatico
dir = os.path.dirname(os.path.... | pt | 0.765322 | # Exemplo de Execução do Analisador Sintático # # Desenvolvedor: <NAME> # Main # # Importar Analisador # # # Ler o Arquivo # # # Inicializar o Analisador # # # Executar # | 3.218764 | 3 |
jp.atcoder/abc109/abc109_c/9351215.py | kagemeka/atcoder-submissions | 1 | 6622952 | <gh_stars>1-10
import sys
from functools import reduce
def gcd(a, b):
while b:
a, b = b, a % b
return abs(a)
n, X, *x = map(int, sys.stdin.read().split())
def main():
x.append(X)
for i in range(n):
x[i] -= x[i+1]
x[-1] -= X
return reduce(gcd, x)
if __name... | import sys
from functools import reduce
def gcd(a, b):
while b:
a, b = b, a % b
return abs(a)
n, X, *x = map(int, sys.stdin.read().split())
def main():
x.append(X)
for i in range(n):
x[i] -= x[i+1]
x[-1] -= X
return reduce(gcd, x)
if __name__ == '__main__... | none | 1 | 3.164203 | 3 | |
RenameAllFileinUEFile.py | youdrew/All-Kind-of-Language-Study | 0 | 6622953 | <reponame>youdrew/All-Kind-of-Language-Study
import os
import pypinyin
#这是一个将文件夹下所有的子文件/文件夹改成拼音的小程序
#撰写日期:20220124 Engene
def is_chinese(string):
"""
检查整个字符串是否包含中文
:param string: 需要检查的字符串
:return: bool
"""
for ch in string:
if u'\u4e00' <= ch <= u'\u9fff':
return True
... | import os
import pypinyin
#这是一个将文件夹下所有的子文件/文件夹改成拼音的小程序
#撰写日期:20220124 Engene
def is_chinese(string):
"""
检查整个字符串是否包含中文
:param string: 需要检查的字符串
:return: bool
"""
for ch in string:
if u'\u4e00' <= ch <= u'\u9fff':
return True
return False
def ADDFileName(parent, dirnam... | zh | 0.794543 | #这是一个将文件夹下所有的子文件/文件夹改成拼音的小程序 #撰写日期:20220124 Engene 检查整个字符串是否包含中文 :param string: 需要检查的字符串 :return: bool # print("parent is: " + parent) # print("filename is: " + filename) # print("dirnames is: " + dirnames) # print(os.path.join(parent, filename)) # 输出rootdir路径下所有文件(包含子文件)信息 #files_list.append([os.path.join(par... | 2.948985 | 3 |
electrum_gui/common/basic/exceptions.py | BixinKey/electrum | 12 | 6622954 | class OneKeyException(Exception):
key = "msg__unknown_error"
other_info = ""
def __init__(self, other_info=None):
if other_info is not None:
self.other_info = other_info
class UnavailablePrivateKey(OneKeyException):
key = "msg__incorrect_private_key"
class InvalidKeystoreFormat(... | class OneKeyException(Exception):
key = "msg__unknown_error"
other_info = ""
def __init__(self, other_info=None):
if other_info is not None:
self.other_info = other_info
class UnavailablePrivateKey(OneKeyException):
key = "msg__incorrect_private_key"
class InvalidKeystoreFormat(... | de | 0.77502 | ##################################### # hardware exceptions # ##################################### | 2.368125 | 2 |
python3_exercicios_feitos/Desafio043.py | LouiMaxine/python3-exercicios-cursoemvideo | 0 | 6622955 | <gh_stars>0
'''Desenvolva uma lógica que leia o peso e a altra de uma pessoa, calcule seu IMC(índice de massa corpórea) e mostre seu status, de acordo com a tabela abaixo:
- Abaixo de 18.5: Abaixo do Peso
- Entre 18.5 e 25: Peso ideal
- 25 até 30: Sobrepeso
- 30 até 40: Obesidade
- Acima de 40: Obesidade Mórbida'''
#f... | '''Desenvolva uma lógica que leia o peso e a altra de uma pessoa, calcule seu IMC(índice de massa corpórea) e mostre seu status, de acordo com a tabela abaixo:
- Abaixo de 18.5: Abaixo do Peso
- Entre 18.5 e 25: Peso ideal
- 25 até 30: Sobrepeso
- 30 até 40: Obesidade
- Acima de 40: Obesidade Mórbida'''
#from math imp... | pt | 0.93646 | Desenvolva uma lógica que leia o peso e a altra de uma pessoa, calcule seu IMC(índice de massa corpórea) e mostre seu status, de acordo com a tabela abaixo: - Abaixo de 18.5: Abaixo do Peso - Entre 18.5 e 25: Peso ideal - 25 até 30: Sobrepeso - 30 até 40: Obesidade - Acima de 40: Obesidade Mórbida #from math import pow... | 3.930295 | 4 |
pgex/gaming/animated_sprite.py | IvanFoke/pgex | 0 | 6622956 | from pgex.gaming.animation import AnimationIterator
from .base_sprite import BaseSprite
class AnimatedSprite(BaseSprite):
def __init__(self, coordinates, speed_x, speed_y, stay_images, left_images=None, right_images=None,
up_images=None, down_images=None, jump_images=None, transparent_color=None,... | from pgex.gaming.animation import AnimationIterator
from .base_sprite import BaseSprite
class AnimatedSprite(BaseSprite):
def __init__(self, coordinates, speed_x, speed_y, stay_images, left_images=None, right_images=None,
up_images=None, down_images=None, jump_images=None, transparent_color=None,... | none | 1 | 2.65287 | 3 | |
ColDocDjango/ColDocApp/migrations/0001_initial.py | mennucc/ColDoc_project | 0 | 6622957 | # Generated by Django 3.0.5 on 2020-04-30 11:12
import ColDocApp.models
import ColDocDjango.users
from django.conf import settings
import django.contrib.auth.models
import django.contrib.auth.validators
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
... | # Generated by Django 3.0.5 on 2020-04-30 11:12
import ColDocApp.models
import ColDocDjango.users
from django.conf import settings
import django.contrib.auth.models
import django.contrib.auth.validators
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
... | en | 0.795519 | # Generated by Django 3.0.5 on 2020-04-30 11:12 | 2.033889 | 2 |
scripts/portal/gPark_Portal.py | G00dBye/YYMS | 54 | 6622958 | <reponame>G00dBye/YYMS<gh_stars>10-100
if sm.getFieldID() == 956100000:
map = 224000000
portal = 32
else:
map = 956100000
portal = 3
sm.warp(map, portal)
sm.dispose()
| if sm.getFieldID() == 956100000:
map = 224000000
portal = 32
else:
map = 956100000
portal = 3
sm.warp(map, portal)
sm.dispose() | none | 1 | 1.166197 | 1 | |
answers/MridulMohanta/Day8/question1.py | arc03/30-DaysOfCode-March-2021 | 22 | 6622959 | arr = input("Enter")
nums = arr.split()
nums = [int(i) for i in nums]
unique = []
for x in nums:
if nums.count(x) > 1:
while x in nums:
nums.remove(x)
total = 0
for i in range(0 , len(nums)):
total = total + nums[i]
print(total)
| arr = input("Enter")
nums = arr.split()
nums = [int(i) for i in nums]
unique = []
for x in nums:
if nums.count(x) > 1:
while x in nums:
nums.remove(x)
total = 0
for i in range(0 , len(nums)):
total = total + nums[i]
print(total)
| none | 1 | 3.46082 | 3 | |
scripts/sources/S_FactorReplicationTest.py | dpopadic/arpmRes | 6 | 6622960 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.4'
# jupytext_version: 1.1.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # S_Fa... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.4'
# jupytext_version: 1.1.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # S_Fa... | en | 0.554366 | #!/usr/bin/env python3 # -*- coding: utf-8 -*- # --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.4' # jupytext_version: 1.1.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # S_Fac... | 2.28809 | 2 |
lqg/plotter.py | brain-research/mirage-rl | 15 | 6622961 | #!python
import os
import numpy as np
import matplotlib.pyplot as plt
plt.ion()
from matplotlib import rc
rc('text', usetex=True)
import seaborn as sns
import matplotlib.patches as mpatches
color_list = sns.color_palette("muted", 10)
sns.palplot(color_list)
def plot_trajs(s, filename, title, ylim=(-2,6), xlim=(-2,6))... | #!python
import os
import numpy as np
import matplotlib.pyplot as plt
plt.ion()
from matplotlib import rc
rc('text', usetex=True)
import seaborn as sns
import matplotlib.patches as mpatches
color_list = sns.color_palette("muted", 10)
sns.palplot(color_list)
def plot_trajs(s, filename, title, ylim=(-2,6), xlim=(-2,6))... | en | 0.38265 | #!python #fileids = [0, 150, 300, 600] #fileids = list(range(0, 700, 150)) # plot first up to first 1000 updates # plot first up to first 1000 updates #updates=%04d' % i for i in fileids] # variance plots #filenames = ['%s_traj_%04d' % (trial, i) for i in fileids] # traj plots # variance plots #outfile = 'out_%s_traj' ... | 2.6264 | 3 |
pisat/sensor/sam_m8q.py | jjj999/pisat | 1 | 6622962 | <gh_stars>1-10
from typing import Optional, Tuple, Union
from pisat.handler.i2c_handler_base import I2CHandlerBase
from pisat.handler.serial_handler_base import SerialHandlerBase
from pisat.model.datamodel import DataModelBase, loggable
from pisat.sensor.sensor_base import HandlerMismatchError, SensorBase
from pisat.... | from typing import Optional, Tuple, Union
from pisat.handler.i2c_handler_base import I2CHandlerBase
from pisat.handler.serial_handler_base import SerialHandlerBase
from pisat.model.datamodel import DataModelBase, loggable
from pisat.sensor.sensor_base import HandlerMismatchError, SensorBase
from pisat.sensor.serial_gp... | tr | 0.268247 | # TODO I2C ver. # TODO I2C ver. | 2.543579 | 3 |
tests/test_utils.py | gfalcone/mlserve | 26 | 6622963 | import unittest
import pandas as pd
from serveml.inputs import BasicFeedbackInput
from serveml.utils import (
dict_to_pandas,
pandas_to_dict,
pydantic_model_to_pandas,
)
class TestUtils(unittest.TestCase):
def test_parsing_dict_to_pandas(self):
item = {"item_id": 0, "item_name": "coconut"}
... | import unittest
import pandas as pd
from serveml.inputs import BasicFeedbackInput
from serveml.utils import (
dict_to_pandas,
pandas_to_dict,
pydantic_model_to_pandas,
)
class TestUtils(unittest.TestCase):
def test_parsing_dict_to_pandas(self):
item = {"item_id": 0, "item_name": "coconut"}
... | none | 1 | 3.110647 | 3 | |
features/steps/exporting.py | eblade/images4 | 1 | 6622964 | <filename>features/steps/exporting.py
import logging
from behave import *
from hamcrest import *
from hamcrest.library.collection.issequence_containinginanyorder import contains_inanyorder
from images import ExportJob, EXPORTABLE
from images.export_job import ExportJobDescriptor, create_export_job, get_export_jobs_by_... | <filename>features/steps/exporting.py
import logging
from behave import *
from hamcrest import *
from hamcrest.library.collection.issequence_containinginanyorder import contains_inanyorder
from images import ExportJob, EXPORTABLE
from images.export_job import ExportJobDescriptor, create_export_job, get_export_jobs_by_... | none | 1 | 1.975347 | 2 | |
apocalypse/utils/backgroundJob.py | dhoomakethu/terminator | 6 | 6622965 | import threading
from apocalypse.utils.logger import get_logger
logger = get_logger()
class BackgroundJob(threading.Thread):
def __init__(self, name, interval, function, *funcargs, **funckwargs):
threading.Thread.__init__(self)
self._name = name
self.interval = interval
s... | import threading
from apocalypse.utils.logger import get_logger
logger = get_logger()
class BackgroundJob(threading.Thread):
def __init__(self, name, interval, function, *funcargs, **funckwargs):
threading.Thread.__init__(self)
self._name = name
self.interval = interval
s... | none | 1 | 2.694097 | 3 | |
Pendulum/simple_pendulum.py | umairkarel/Beginner-Projects | 0 | 6622966 | <reponame>umairkarel/Beginner-Projects
import pygame
import math
SCREEN_WIDTH = 300
SCREEN_HEIGHT = 300
WHITE = (255, 255, 255)
BLACK = (0,0,0)
FPS = 60
pygame.init()
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
clock = pygame.time.Clock()
dragging = False
length = 95
origin = [int(SCREEN_WIDTH/2)... | import pygame
import math
SCREEN_WIDTH = 300
SCREEN_HEIGHT = 300
WHITE = (255, 255, 255)
BLACK = (0,0,0)
FPS = 60
pygame.init()
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
clock = pygame.time.Clock()
dragging = False
length = 95
origin = [int(SCREEN_WIDTH/2), 0]
bob = [int(SCREEN_WIDTH/2),length]... | none | 1 | 3.512776 | 4 | |
src/indra_cogex/client/subnetwork.py | kkaris/indra_cogex | 0 | 6622967 | """Queries that generate statement subnetworks."""
from typing import Iterable, List, Tuple
from indra.statements import Statement
from .neo4j_client import Neo4jClient, autoclient
from .queries import get_genes_for_go_term, get_genes_in_tissue
from ..representation import Relation, indra_stmts_from_relations, norm_... | """Queries that generate statement subnetworks."""
from typing import Iterable, List, Tuple
from indra.statements import Statement
from .neo4j_client import Neo4jClient, autoclient
from .queries import get_genes_for_go_term, get_genes_in_tissue
from ..representation import Relation, indra_stmts_from_relations, norm_... | en | 0.842855 | Queries that generate statement subnetworks. Return the subnetwork induced by the given nodes as a set of Relations. Parameters ---------- client : The Neo4j client. nodes : The nodes to query. Returns ------- : The subnetwork induced by the given nodes represented ... | 2.593687 | 3 |
lib/utils/AllKeywordsLibrary.py | johnxthekid/AutomationFramework | 0 | 6622968 | <gh_stars>0
import sys
import os
sys.path.append(os.path.join(os.path.dirname(__file__), '..', '..'))
from robot.api import logger
from lib.browsers.drivermanagers.BrowserManager import BrowserManager
from lib.frontend.apphelpers.SampleNotepadHelper import SampleNotepadHelper
from lib.browsers.pageobjectmodels.DemoMa... | import sys
import os
sys.path.append(os.path.join(os.path.dirname(__file__), '..', '..'))
from robot.api import logger
from lib.browsers.drivermanagers.BrowserManager import BrowserManager
from lib.frontend.apphelpers.SampleNotepadHelper import SampleNotepadHelper
from lib.browsers.pageobjectmodels.DemoMainPage impor... | none | 1 | 2.332956 | 2 | |
blueprint_spins.py | SamCHogg/Ark-Bot | 0 | 6622969 | import argparse
import random
def random_quality():
rand = random.randint(1, 101)
# 8%
if rand <= 8:
quality = 1
# 36%
elif 8 < rand <= 43:
quality = 2
# 39%
elif 43 < rand <= 82:
quality = 3
# 15%
elif 82 < rand <= 97:
quality = 5
# 2%
else:... | import argparse
import random
def random_quality():
rand = random.randint(1, 101)
# 8%
if rand <= 8:
quality = 1
# 36%
elif 8 < rand <= 43:
quality = 2
# 39%
elif 43 < rand <= 82:
quality = 3
# 15%
elif 82 < rand <= 97:
quality = 5
# 2%
else:... | en | 0.63467 | # 8% # 36% # 39% # 15% # 2% | 3.607432 | 4 |
dual_crispr/run_scoring.py | ucsd-ccbb/mali-dual-crispr-pipeline | 5 | 6622970 | <reponame>ucsd-ccbb/mali-dual-crispr-pipeline<gh_stars>1-10
# standard libraries
import argparse
import distutils.util
import os
import warnings
import ccbb_pyutils.config_loader as ns_config
import ccbb_pyutils.notebook_pipeliner as ns_pipeliner
from dual_crispr import dual_crispr_pipeliner as ns_dcpipe
__author__ ... | # standard libraries
import argparse
import distutils.util
import os
import warnings
import ccbb_pyutils.config_loader as ns_config
import ccbb_pyutils.notebook_pipeliner as ns_pipeliner
from dual_crispr import dual_crispr_pipeliner as ns_dcpipe
__author__ = '<NAME>'
__maintainer__ = "<NAME>"
__email__ = "<EMAIL>"
_... | en | 0.812984 | # standard libraries # examples: # human_readable_name = 20160627HeLaA549 # library_name = CV4 # day_timepoints_str = 3,14,20,28 # --test # load the config file # Note: the time_prefixes_str and day_timepoints_str comma-delimited string params are not being converted to lists # here--that is done in the notebook, becau... | 2.273649 | 2 |
recipes/Python/511423_8_Queens_Problem/recipe-511423.py | tdiprima/code | 2,023 | 6622971 | <filename>recipes/Python/511423_8_Queens_Problem/recipe-511423.py
def Permute(queens, row):
for i in range(8):
queens[row] = i
if Fine(queens, row):
if row == 7:
print(queens)
globals()["solutions"] = globals()["solutions"] + 1
else:
... | <filename>recipes/Python/511423_8_Queens_Problem/recipe-511423.py
def Permute(queens, row):
for i in range(8):
queens[row] = i
if Fine(queens, row):
if row == 7:
print(queens)
globals()["solutions"] = globals()["solutions"] + 1
else:
... | none | 1 | 3.421999 | 3 | |
src/data_generator/input_file_creator.py | HeartSaVioR/structured_streaming_experiments | 2 | 6622972 | # -*- coding: utf-8 -*-
import sys
import os
from time import sleep
from tempfile import mkdtemp
from uuid import uuid1
from datetime import datetime
from random import randint
TEST_DATA_FILE_PATH = "resources/test_data.txt"
def create_file(input_dir_path, dir_pattern, temp_dir_path, num_of_lines, data_lines):
... | # -*- coding: utf-8 -*-
import sys
import os
from time import sleep
from tempfile import mkdtemp
from uuid import uuid1
from datetime import datetime
from random import randint
TEST_DATA_FILE_PATH = "resources/test_data.txt"
def create_file(input_dir_path, dir_pattern, temp_dir_path, num_of_lines, data_lines):
... | en | 0.769321 | # -*- coding: utf-8 -*- | 2.814717 | 3 |
app/models/oauth/client.py | tch1bo/viaduct | 11 | 6622973 | <reponame>tch1bo/viaduct<filename>app/models/oauth/client.py
from authlib.flask.oauth2.sqla import OAuth2ClientMixin
from sqlalchemy.ext.hybrid import hybrid_property
from app import db
class OAuthClient(db.Model, OAuth2ClientMixin):
__tablename__ = 'oauth_client'
# Overwrite the mixin client_id, since we w... | from authlib.flask.oauth2.sqla import OAuth2ClientMixin
from sqlalchemy.ext.hybrid import hybrid_property
from app import db
class OAuthClient(db.Model, OAuth2ClientMixin):
__tablename__ = 'oauth_client'
# Overwrite the mixin client_id, since we want it to be the primary key.
client_id = db.Column(db.St... | en | 0.932295 | # Overwrite the mixin client_id, since we want it to be the primary key. # Creator of the client | 2.28545 | 2 |
main.py | TimO96/RE-CEM | 0 | 6622974 | # main.py -- main file with arguments
# <NAME> (11318422)
# <NAME> (11331720)
# <NAME> (11248815)
# <NAME> (11147598)
# (C) 2020 UvA FACT AI
import random
import argparse
import cem
from cem.train import search, train_model
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Contrastive Ex... | # main.py -- main file with arguments
# <NAME> (11318422)
# <NAME> (11331720)
# <NAME> (11248815)
# <NAME> (11147598)
# (C) 2020 UvA FACT AI
import random
import argparse
import cem
from cem.train import search, train_model
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Contrastive Ex... | en | 0.417639 | # main.py -- main file with arguments # <NAME> (11318422) # <NAME> (11331720) # <NAME> (11248815) # <NAME> (11147598) # (C) 2020 UvA FACT AI # Train optionally # Perform explanation or quantative evaluation | 2.478385 | 2 |
companyAPI/apps.py | colombia-immap/unicef-school-mapping-back | 0 | 6622975 | <reponame>colombia-immap/unicef-school-mapping-back
from django.apps import AppConfig
class CompanyapiConfig(AppConfig):
name = 'companyAPI'
| from django.apps import AppConfig
class CompanyapiConfig(AppConfig):
name = 'companyAPI' | none | 1 | 1.14176 | 1 | |
tests/modules/test_pulseaudio.py | kunalshetye/bumblebee-status | 5 | 6622976 | <gh_stars>1-10
# pylint: disable=C0103,C0111
import mock
import unittest
import tests.mocks as mocks
from bumblebee.input import LEFT_MOUSE, RIGHT_MOUSE, WHEEL_UP, WHEEL_DOWN
from bumblebee.modules.pulseaudio import Module
class TestPulseAudioModule(unittest.TestCase):
def setUp(self):
mocks.setup_test(... | # pylint: disable=C0103,C0111
import mock
import unittest
import tests.mocks as mocks
from bumblebee.input import LEFT_MOUSE, RIGHT_MOUSE, WHEEL_UP, WHEEL_DOWN
from bumblebee.modules.pulseaudio import Module
class TestPulseAudioModule(unittest.TestCase):
def setUp(self):
mocks.setup_test(self, Module)
... | de | 0.176571 | # pylint: disable=C0103,C0111 # vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4 | 2.409423 | 2 |
pyspi/io/plotting/spi_display.py | grburgess/pyspi | 0 | 6622977 | <filename>pyspi/io/plotting/spi_display.py
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from matplotlib.patches import RegularPolygon
from pyspi.utils.livedets import get_live_dets
NUM_REAL_DETS = 19
NUM_PSEUDO_DOUBLE_DETS = 42
NUM_PSEUDO_TRIPLE_DETS = 42
NUM_TOTAL_DETS = NUM_REAL_DETS + NUM_... | <filename>pyspi/io/plotting/spi_display.py
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from matplotlib.patches import RegularPolygon
from pyspi.utils.livedets import get_live_dets
NUM_REAL_DETS = 19
NUM_PSEUDO_DOUBLE_DETS = 42
NUM_PSEUDO_TRIPLE_DETS = 42
NUM_TOTAL_DETS = NUM_REAL_DETS + NUM_... | en | 0.734818 | # the origins of the detectors # the underscore keeps these variable from being exposed # to the user Helper function to generate double event detector list :return: # the list of double pairs # for details see: # https://heasarc.gsfc.nasa.gov/docs/integral/spi/pages/detectors.html # calculate the origins # build... | 2.383432 | 2 |
code/cartesian-product-func.py | tumuum/prog-book | 0 | 6622978 | <filename>code/cartesian-product-func.py
def product(A,B):
"""Takes two sets A and B, and returns their
cartesian product as a set of 2-tuples."""
product = set()
for x in A:
for y in B:
product.add((x,y))
"""Now it is time to return the result"""
return product
| <filename>code/cartesian-product-func.py
def product(A,B):
"""Takes two sets A and B, and returns their
cartesian product as a set of 2-tuples."""
product = set()
for x in A:
for y in B:
product.add((x,y))
"""Now it is time to return the result"""
return product
| en | 0.95597 | Takes two sets A and B, and returns their cartesian product as a set of 2-tuples. Now it is time to return the result | 3.954961 | 4 |
regex_tester.py | lparolin/python_regex_tester | 0 | 6622979 | <gh_stars>0
import re
def make_all_single_lines(in_string):
pattern = "\\\W*(?:\r\n|\n|\r)"
repl = ""
out_string = re.sub(pattern, repl, in_string)
return out_string
def get_import_lines(in_string):
pattern = "(?<=import\W).+"
return re.findall(pattern, in_string)
def get_import_items(in_list... | import re
def make_all_single_lines(in_string):
pattern = "\\\W*(?:\r\n|\n|\r)"
repl = ""
out_string = re.sub(pattern, repl, in_string)
return out_string
def get_import_lines(in_string):
pattern = "(?<=import\W).+"
return re.findall(pattern, in_string)
def get_import_items(in_list):
all_i... | none | 1 | 2.937442 | 3 | |
library/py/tde/cli.py | eblot/tde-base | 0 | 6622980 | """Simple command line wrapper"""
import os
from io import TextIOWrapper
from subprocess import Popen, DEVNULL, PIPE
from sys import stderr
from time import sleep, time as now
class Command:
"""Context manager for a shell command.
Run the command specified as a list of parameters.
The Command cons... | """Simple command line wrapper"""
import os
from io import TextIOWrapper
from subprocess import Popen, DEVNULL, PIPE
from sys import stderr
from time import sleep, time as now
class Command:
"""Context manager for a shell command.
Run the command specified as a list of parameters.
The Command cons... | en | 0.81853 | Simple command line wrapper Context manager for a shell command. Run the command specified as a list of parameters. The Command constructor accepts modifiers as keyword arguments: * ``nosignal`` (expects a boolean value) to prevent Python from forwarding signals received in the Pytho... | 2.961236 | 3 |
Python Fundamentals/9. RegEx/Exercise/03. Find Occurrences of Word in Sentence.py | a-shiro/SoftUni-Courses | 0 | 6622981 | <filename>Python Fundamentals/9. RegEx/Exercise/03. Find Occurrences of Word in Sentence.py
import re
text = input().lower()
word = input().lower()
pattern = rf"\b{word}\b"
valid_matches = len(re.findall(pattern, text))
print(valid_matches) | <filename>Python Fundamentals/9. RegEx/Exercise/03. Find Occurrences of Word in Sentence.py
import re
text = input().lower()
word = input().lower()
pattern = rf"\b{word}\b"
valid_matches = len(re.findall(pattern, text))
print(valid_matches) | none | 1 | 4.296508 | 4 | |
OpenCV/01_Canny_Edge_Detection.py | danieldfgro2000/Recycle | 0 | 6622982 | import cv2
import numpy as np
import matplotlib
matplotlib.use('TkAgg')
from matplotlib import pyplot as plt
img = cv2.imread('../elephant_gray.jpeg', 0)
edges = cv2.Canny(img, 100, 200)
plt.subplot(121), plt.imshow(img, cmap='gray')
plt.title('Original Image'), plt.xticks([]), plt.yticks([])
plt.subplot(122), plt.... | import cv2
import numpy as np
import matplotlib
matplotlib.use('TkAgg')
from matplotlib import pyplot as plt
img = cv2.imread('../elephant_gray.jpeg', 0)
edges = cv2.Canny(img, 100, 200)
plt.subplot(121), plt.imshow(img, cmap='gray')
plt.title('Original Image'), plt.xticks([]), plt.yticks([])
plt.subplot(122), plt.... | none | 1 | 2.918459 | 3 | |
experiments/rrn/models.py | nilamm/openprotein | 73 | 6622983 | <gh_stars>10-100
"""
This file is part of the OpenProtein project.
For license information, please see the LICENSE file in the root directory.
"""
import time
import torch
import torch.nn as nn
import openprotein
from util import initial_pos_from_aa_string, \
pass_messages, write_out, calc_avg_drmsd_over_minibat... | """
This file is part of the OpenProtein project.
For license information, please see the LICENSE file in the root directory.
"""
import time
import torch
import torch.nn as nn
import openprotein
from util import initial_pos_from_aa_string, \
pass_messages, write_out, calc_avg_drmsd_over_minibatch
class RrnMode... | en | 0.758843 | This file is part of the OpenProtein project. For license information, please see the LICENSE file in the root directory. # 3 dimensions * 3 coordinates for each aa # (last state + orginal state) # aa_features: msg_count * 2 * feature_count # msg_count * outputsize # aa_count * output size | 1.814609 | 2 |
netests/converters/vlan/cumulus/ssh.py | Netests/netests | 14 | 6622984 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import json
from netests.protocols.ipv4 import IPV4, IPV4Interface
from netests.protocols.ipv6 import IPV6, IPV6Interface
from netests.protocols.vlan import VLAN, ListVLAN
from netests.constants import NOT_SET
def _cumulus_vlan_ssh_converter(
hostname: str,
cmd_... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import json
from netests.protocols.ipv4 import IPV4, IPV4Interface
from netests.protocols.ipv6 import IPV6, IPV6Interface
from netests.protocols.vlan import VLAN, ListVLAN
from netests.constants import NOT_SET
def _cumulus_vlan_ssh_converter(
hostname: str,
cmd_... | en | 0.526116 | #!/usr/bin/env python3 # -*- coding: utf-8 -*- # Is an IPv6 (light I know :) | 2.723303 | 3 |
apps/portalbase/macros/page/accordion/3_accordion.py | Jumpscale/jumpscale_portal8 | 0 | 6622985 | <filename>apps/portalbase/macros/page/accordion/3_accordion.py
def main(j, args, params, tags, tasklet):
page = args.page
macrostr = args.macrostr.strip()
content = "\n".join(macrostr.split("\n")[1:-1])
panels = j.data.serializer.yaml.loads(content)
if not isinstance(panels, list):
panels... | <filename>apps/portalbase/macros/page/accordion/3_accordion.py
def main(j, args, params, tags, tasklet):
page = args.page
macrostr = args.macrostr.strip()
content = "\n".join(macrostr.split("\n")[1:-1])
panels = j.data.serializer.yaml.loads(content)
if not isinstance(panels, list):
panels... | en | 0.3611 | # hack to be able to pass yaml into the macro # the content is json serializer passed to the macro then deserialize here <div class="panel panel-default"> <div class="panel-heading" role="tab" id="%(header_id)s"> <h4 class="panel-title"> <a data-toggle="collapse" data-parent="#accord... | 1.858016 | 2 |
inquire/interactions/__init__.py | HARPLab/inquire | 0 | 6622986 | <gh_stars>0
from inquire.interactions.feedback import Query, Trajectory, Choice, Modality
from inquire.interactions.modalities import Demonstration, Correction, Preference, BinaryFeedback
__all__ = ["Modality", "Query", "Trajectory", "Choice", "Demonstration", "Correction", "Preference", "BinaryFeedback", "Feedback"]
| from inquire.interactions.feedback import Query, Trajectory, Choice, Modality
from inquire.interactions.modalities import Demonstration, Correction, Preference, BinaryFeedback
__all__ = ["Modality", "Query", "Trajectory", "Choice", "Demonstration", "Correction", "Preference", "BinaryFeedback", "Feedback"] | none | 1 | 1.081975 | 1 | |
leetcode/0405_convert_a_number_to_hexadecimal.py | chaosWsF/Python-Practice | 0 | 6622987 | <filename>leetcode/0405_convert_a_number_to_hexadecimal.py
"""
Given an integer, write an algorithm to convert it to hexadecimal. For negative integer, two’s complement method is used.
Note:
All letters in hexadecimal (a-f) must be in lowercase.
The hexadecimal string must not contain extra leading 0s. If the... | <filename>leetcode/0405_convert_a_number_to_hexadecimal.py
"""
Given an integer, write an algorithm to convert it to hexadecimal. For negative integer, two’s complement method is used.
Note:
All letters in hexadecimal (a-f) must be in lowercase.
The hexadecimal string must not contain extra leading 0s. If the... | en | 0.703183 | Given an integer, write an algorithm to convert it to hexadecimal. For negative integer, two’s complement method is used. Note: All letters in hexadecimal (a-f) must be in lowercase. The hexadecimal string must not contain extra leading 0s. If the number is zero, it is represented by a single zero charac... | 4.344935 | 4 |
laceworksdk/api/cloud_activities.py | kiddinn/python-sdk | 10 | 6622988 | # -*- coding: utf-8 -*-
"""
Lacework CloudActivities API wrapper.
"""
import logging
logger = logging.getLogger(__name__)
class CloudActivitiesAPI(object):
"""
Lacework CloudActivities API.
"""
def __init__(self, session):
"""
Initializes the CloudActivitiesAPI object.
:par... | # -*- coding: utf-8 -*-
"""
Lacework CloudActivities API wrapper.
"""
import logging
logger = logging.getLogger(__name__)
class CloudActivitiesAPI(object):
"""
Lacework CloudActivities API.
"""
def __init__(self, session):
"""
Initializes the CloudActivitiesAPI object.
:par... | en | 0.699712 | # -*- coding: utf-8 -*- Lacework CloudActivities API wrapper. Lacework CloudActivities API. Initializes the CloudActivitiesAPI object. :param session: An instance of the HttpSession class :return CloudActivitiesAPI object. A method to get CloudActivities details. :param start_time: A "%Y-%m-%... | 2.514838 | 3 |
tests/hub_test_fork.py | lbonn/eventlet | 1 | 6622989 | <filename>tests/hub_test_fork.py
# no standard tests in this file, ignore
__test__ = False
if __name__ == '__main__':
import os
import eventlet
server = eventlet.listen(('localhost', 12345))
t = eventlet.Timeout(0.01)
try:
new_sock, address = server.accept()
except eventlet.Timeout as t... | <filename>tests/hub_test_fork.py
# no standard tests in this file, ignore
__test__ = False
if __name__ == '__main__':
import os
import eventlet
server = eventlet.listen(('localhost', 12345))
t = eventlet.Timeout(0.01)
try:
new_sock, address = server.accept()
except eventlet.Timeout as t... | en | 0.626225 | # no standard tests in this file, ignore | 2.239597 | 2 |
FD_EPR_TraitComposition.py | ldykman/FD_EPR | 0 | 6622990 | <filename>FD_EPR_TraitComposition.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
FUNCTIONAL TRAIT COMPOSITION
Created on Mon Jun 11 14:23:09 2018
@author: laurendykman
Requires three input data tables:
Abundance = species as rows, sites as columns. Contains a row of temperatures and a row of
month... | <filename>FD_EPR_TraitComposition.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
FUNCTIONAL TRAIT COMPOSITION
Created on Mon Jun 11 14:23:09 2018
@author: laurendykman
Requires three input data tables:
Abundance = species as rows, sites as columns. Contains a row of temperatures and a row of
month... | en | 0.756813 | #!/usr/bin/env python3 # -*- coding: utf-8 -*- FUNCTIONAL TRAIT COMPOSITION Created on Mon Jun 11 14:23:09 2018 @author: laurendykman Requires three input data tables: Abundance = species as rows, sites as columns. Contains a row of temperatures and a row of months associated with each sample. Temperatur... | 2.482775 | 2 |
service/image.py | khromiumos/chromiumos-chromite | 0 | 6622991 | <reponame>khromiumos/chromiumos-chromite<gh_stars>0
# -*- coding: utf-8 -*-
# Copyright 2018 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""The Image API is the entry point for image functionality."""
from __future... | # -*- coding: utf-8 -*-
# Copyright 2018 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""The Image API is the entry point for image functionality."""
from __future__ import print_function
import os
from chromite.l... | en | 0.786598 | # -*- coding: utf-8 -*- # Copyright 2018 The Chromium OS Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. The Image API is the entry point for image functionality. Base module error. Invalid argument values. Error converting the image to... | 2.248806 | 2 |
test_project/gallery/models.py | c0ntribut0r/django-mptt-urls | 24 | 6622992 | <gh_stars>10-100
from django.db import models
from django.urls import reverse
from mptt.models import MPTTModel, TreeForeignKey
class Category(MPTTModel):
name = models.CharField('category name', max_length=32)
# ... some other fields
parent = TreeForeignKey('self', null=True, blank=True, on_delete=model... | from django.db import models
from django.urls import reverse
from mptt.models import MPTTModel, TreeForeignKey
class Category(MPTTModel):
name = models.CharField('category name', max_length=32)
# ... some other fields
parent = TreeForeignKey('self', null=True, blank=True, on_delete=models.CASCADE,
... | en | 0.75312 | # ... some other fields # ... some other fields | 2.227717 | 2 |
acessando_api.py | Renatoelho/consumindo-api-enderecos-python | 0 | 6622993 | #!/usr/bin/python3
import requests
lista_ceps: list = ['01153000', '20050000', '70714020']
lista_enderecos: list = []
for cep in lista_ceps:
url: str = 'https://viacep.com.br/ws/{}/json/'.format(cep)
try:
req = requests.get(url, timeout=3)
if req.status_code == 200:
# API acessa... | #!/usr/bin/python3
import requests
lista_ceps: list = ['01153000', '20050000', '70714020']
lista_enderecos: list = []
for cep in lista_ceps:
url: str = 'https://viacep.com.br/ws/{}/json/'.format(cep)
try:
req = requests.get(url, timeout=3)
if req.status_code == 200:
# API acessa... | pt | 0.752557 | #!/usr/bin/python3 # API acessada com sucesso! | 2.957082 | 3 |
NoiseMapGenerators_14.py | defzzd/TerrainGenerators | 1 | 6622994 | '''
Fractal noise map generator library.
Also includes additional non-"noise" map generators for dungeon generation purposes.
The reason for putting them in is because I want the games I make to be able to use very similar code for all the different types of maps I need. Ensuring a high level of cross-compatibility at... | '''
Fractal noise map generator library.
Also includes additional non-"noise" map generators for dungeon generation purposes.
The reason for putting them in is because I want the games I make to be able to use very similar code for all the different types of maps I need. Ensuring a high level of cross-compatibility at... | en | 0.851581 | Fractal noise map generator library. Also includes additional non-"noise" map generators for dungeon generation purposes. The reason for putting them in is because I want the games I make to be able to use very similar code for all the different types of maps I need. Ensuring a high level of cross-compatibility at the ... | 2.305477 | 2 |
project/mahjong/tests/tests_points_calculation.py | huangenyan/Lattish | 9 | 6622995 | <reponame>huangenyan/Lattish
# -*- coding: utf-8 -*-
import unittest
from mahjong.hand import FinishedHand
class PointsCalculationTestCase(unittest.TestCase):
def test_calculate_scores_and_ron(self):
hand = FinishedHand()
result = hand.calculate_scores(han=1, fu=30, is_tsumo=False, is_dealer=Fa... | # -*- coding: utf-8 -*-
import unittest
from mahjong.hand import FinishedHand
class PointsCalculationTestCase(unittest.TestCase):
def test_calculate_scores_and_ron(self):
hand = FinishedHand()
result = hand.calculate_scores(han=1, fu=30, is_tsumo=False, is_dealer=False)
self.assertEqual... | en | 0.232497 | # -*- coding: utf-8 -*- # result = hand.calculate_scores(han=1, fu=30, is_tsumo=True, is_dealer=False) # self.assertEqual(result['main'], 500) # self.assertEqual(result['additional'], 300) # # result = hand.calculate_scores(han=3, fu=30, is_tsumo=True, is_dealer=False) # self.assertEqual(result['main'], 2000) # self.as... | 3.047774 | 3 |
Leetcode/198. House Robber.py | qinyang39/daily-leetcode | 1 | 6622996 | class Solution:
def rob(self, nums: List[int]) -> int:
if not nums: return 0
if len(nums)==1: return nums[0]
dp = [0] * len(nums)
dp[0] = nums[0]
dp[1] = max(nums[0], nums[1])
for i in range(2, len(nums)):
dp[i] = max(dp[i-2]+nums[i], dp[i-1])... | class Solution:
def rob(self, nums: List[int]) -> int:
if not nums: return 0
if len(nums)==1: return nums[0]
dp = [0] * len(nums)
dp[0] = nums[0]
dp[1] = max(nums[0], nums[1])
for i in range(2, len(nums)):
dp[i] = max(dp[i-2]+nums[i], dp[i-1])... | none | 1 | 2.982303 | 3 | |
Projects/turtle.py | eshaananand/HACKTOBERFEST_2021 | 0 | 6622997 | import turtle
turtle.bgcolor("black")
turtle.pensize(2)
def curve():
for i in range(200):
turtle.right(1)
turtle.forward(1)
turtle.speed(0)
turtle.color("pink","red")
turtle.begin_fill()
turtle.left(140)
turtle.forward(111.65)
curve()
turtle.left(120)
curve()
turtle.forward(111.65)
turtle.end_fill... | import turtle
turtle.bgcolor("black")
turtle.pensize(2)
def curve():
for i in range(200):
turtle.right(1)
turtle.forward(1)
turtle.speed(0)
turtle.color("pink","red")
turtle.begin_fill()
turtle.left(140)
turtle.forward(111.65)
curve()
turtle.left(120)
curve()
turtle.forward(111.65)
turtle.end_fill... | none | 1 | 3.720345 | 4 | |
src/covid19sim/inference/server_utils.py | mila-iqia/COVI-AgentSim | 13 | 6622998 | """
Contains utility classes for remote inference inside the simulation.
"""
import datetime
# import h5py
import zarr
import numcodecs
import json
import multiprocessing
import multiprocessing.managers
import numpy as np
import os
import pickle
import platform
import subprocess
import sys
import time
import typing
im... | """
Contains utility classes for remote inference inside the simulation.
"""
import datetime
# import h5py
import zarr
import numcodecs
import json
import multiprocessing
import multiprocessing.managers
import numpy as np
import os
import pickle
import platform
import subprocess
import sys
import time
import typing
im... | en | 0.869266 | Contains utility classes for remote inference inside the simulation. # import h5py # 10MB # if on MPI-IS cluster (htcondor + raven) # if custom ipc path provided # if on slurm Spawns a single worker instance. These workers are managed by a broker class. They communicate with the broker using a backend connecti... | 1.899094 | 2 |
mempw/__init__.py | mdvthu/mempw | 0 | 6622999 | from .core import new_password # noqa: F401
| from .core import new_password # noqa: F401
| uz | 0.465103 | # noqa: F401 | 0.91197 | 1 |
6-collections/list.py | elbeg/introduction-to-python | 5 | 6623000 | squared = []
for n in range(11):
squared.append(n**2)
print(squared)
squared = [ n**2 for n in range(11) if n % 2 is 0 ]
print(squared)
| squared = []
for n in range(11):
squared.append(n**2)
print(squared)
squared = [ n**2 for n in range(11) if n % 2 is 0 ]
print(squared)
| none | 1 | 3.860917 | 4 | |
src/url_storer.py | Taekyoon/PyCrawler | 0 | 6623001 | from db_accessor import MultiThreadDBAccessor
class UrlStorer:
conn = None
def __init__(self, file_path):
UrlStorer.conn = MultiThreadDBAccessor(file_path)
@staticmethod
def create_table(table_name):
UrlStorer.conn.execute("create table if not exists %s\
... | from db_accessor import MultiThreadDBAccessor
class UrlStorer:
conn = None
def __init__(self, file_path):
UrlStorer.conn = MultiThreadDBAccessor(file_path)
@staticmethod
def create_table(table_name):
UrlStorer.conn.execute("create table if not exists %s\
... | none | 1 | 2.880289 | 3 | |
config/backup_config.py | coolexplorer/vault-script | 0 | 6623002 | import datetime
class BackUpConfig(object):
def __init__(self, option):
self.file_path = option.file_path
self.dir_path = option.dir_path
self.compress_option = option.compress_option
self.remote_address = option.remote_address
self.username = option.username
self.p... | import datetime
class BackUpConfig(object):
def __init__(self, option):
self.file_path = option.file_path
self.dir_path = option.dir_path
self.compress_option = option.compress_option
self.remote_address = option.remote_address
self.username = option.username
self.p... | none | 1 | 2.792209 | 3 | |
src/server/front_srv.py | jhchen3121/wechat_shop | 0 | 6623003 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from __future__ import absolute_import
import logging
import logging.config
import settings
import os
logger_conf = os.path.join(settings.PROJ_DIR, 'etc', 'frontend_logger.conf')
logging.config.fileConfig(logger_conf)
from core_ba... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from __future__ import absolute_import
import logging
import logging.config
import settings
import os
logger_conf = os.path.join(settings.PROJ_DIR, 'etc', 'frontend_logger.conf')
logging.config.fileConfig(logger_conf)
from core_ba... | zh | 0.622751 | #!/usr/bin/env python # -*- coding: utf-8 -*- # admin静态资源文件 # 上传至静态资源文件夹 | 1.793684 | 2 |
models/asset_transactions.py | IanMcLaughlin19/fitest | 0 | 6623004 | <reponame>IanMcLaughlin19/fitest<gh_stars>0
@dataclass
class Multisig:
subsignature: List[Dict] = field(default_factory=list)
threshold: int = field(default_factory=int)
version: int = field(default_factory=int)
@dataclass
class MultisigSignature:
subsignature: List[Dict] = field(default_factory=list)
threshold... | @dataclass
class Multisig:
subsignature: List[Dict] = field(default_factory=list)
threshold: int = field(default_factory=int)
version: int = field(default_factory=int)
@dataclass
class MultisigSignature:
subsignature: List[Dict] = field(default_factory=list)
threshold: int = field(default_factory=int)
version: i... | none | 1 | 2.302862 | 2 | |
statarb/src/config/sources/compustat_splits.py | mikimaus78/ml_monorepo | 51 | 6623005 | <reponame>mikimaus78/ml_monorepo
{
"method": "ftp",
"host": "ftp.standardandpoors.com",
"user": "limegrp",
"pass": "<PASSWORD>",
"remote_dir": "/outbound/",
"local_dir": "compustat/splits",
"regex": "future_splits.txt",
"prefix": "%Y%m%d_",
"format": "compustat_splits",
"new... | {
"method": "ftp",
"host": "ftp.standardandpoors.com",
"user": "limegrp",
"pass": "<PASSWORD>",
"remote_dir": "/outbound/",
"local_dir": "compustat/splits",
"regex": "future_splits.txt",
"prefix": "%Y%m%d_",
"format": "compustat_splits",
"new_data_frequency": 24L*60L*60L*100... | none | 1 | 0.925946 | 1 | |
Code/server_web/tk/session.py | JacksonWuxs/Traditional-Archery-Event-Management-System | 0 | 6623006 | from flask_login import UserMixin
from random import choice
from .db import database
import uuid
HomeDB = database('db/home.db')
def get_info(email=None, id=None):
if id:
return HomeDB.select('ID = %s' % id)
return HomeDB.select('Email = "%s"' % email)
class User(UserMixin):
def __init__(self, em... | from flask_login import UserMixin
from random import choice
from .db import database
import uuid
HomeDB = database('db/home.db')
def get_info(email=None, id=None):
if id:
return HomeDB.select('ID = %s' % id)
return HomeDB.select('Email = "%s"' % email)
class User(UserMixin):
def __init__(self, em... | none | 1 | 2.854653 | 3 | |
p36.py | AI-Rabbit/Python-problems | 0 | 6623007 | <gh_stars>0
# p36.py
str1 = input().split()
str2 = input().split()
str3 = input().split()
str1 = list(map(int, str1))
str2 = list(map(int, str2))
str3 = list(map(int, str3))
n = str1[0]
k = str1[1]
for i in range(1, k + 1):
if i % 2 != 0:
for j in range(0, n):
if str2[2*j] >= str3[... | # p36.py
str1 = input().split()
str2 = input().split()
str3 = input().split()
str1 = list(map(int, str1))
str2 = list(map(int, str2))
str3 = list(map(int, str3))
n = str1[0]
k = str1[1]
for i in range(1, k + 1):
if i % 2 != 0:
for j in range(0, n):
if str2[2*j] >= str3[i-1]:
... | none | 1 | 2.981081 | 3 | |
SACWebApp/mainPage/resources.py | feng-jj/SAC-Project1 | 1 | 6623008 | <reponame>feng-jj/SAC-Project1
from import_export import resources
from .models import Clinical, Clinical_VOCA, Advocacy, MAP, OV, SAFE_Clinic, Crisis_Line, Prevention, Training, Development
class ClinicalResource(resources.ModelResource):
class Meta:
model = Clinical
class ClinicalVOCAResource(resources.... | from import_export import resources
from .models import Clinical, Clinical_VOCA, Advocacy, MAP, OV, SAFE_Clinic, Crisis_Line, Prevention, Training, Development
class ClinicalResource(resources.ModelResource):
class Meta:
model = Clinical
class ClinicalVOCAResource(resources.ModelResource):
class Meta:... | none | 1 | 2.073041 | 2 | |
Blog/apps/accounts/forms.py | xinghalok/first-django-blog | 0 | 6623009 | <filename>Blog/apps/accounts/forms.py
from django import forms
from django.contrib.auth import password_validation
from django.utils.translation import gettext, gettext_lazy as _
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.forms import AuthenticationForm as BaseAuthenticationForm
fr... | <filename>Blog/apps/accounts/forms.py
from django import forms
from django.contrib.auth import password_validation
from django.utils.translation import gettext, gettext_lazy as _
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.forms import AuthenticationForm as BaseAuthenticationForm
fr... | none | 1 | 2.30109 | 2 | |
main.py | cs-aware/WP3-data-collection-twitter | 0 | 6623010 | <reponame>cs-aware/WP3-data-collection-twitter
# -*- coding: utf-8 -*-
"""
The script monitors a set of Twitter accounts and collects the latest posts. The new posts are consolidated in a CSV file and stored within AWS S3 storage.
Currently, for the CS-AWARE project, we started monitoring the accounts listed in users.j... | # -*- coding: utf-8 -*-
"""
The script monitors a set of Twitter accounts and collects the latest posts. The new posts are consolidated in a CSV file and stored within AWS S3 storage.
Currently, for the CS-AWARE project, we started monitoring the accounts listed in users.json and executed this scrip every 8 hours.
This... | en | 0.81629 | # -*- coding: utf-8 -*- The script monitors a set of Twitter accounts and collects the latest posts. The new posts are consolidated in a CSV file and stored within AWS S3 storage. Currently, for the CS-AWARE project, we started monitoring the accounts listed in users.json and executed this scrip every 8 hours. This sol... | 2.690945 | 3 |
tests/python/integration/test_int_jobs.py | music2score/music2score | 0 | 6623011 | <reponame>music2score/music2score
# from python.jobs import *
# from python.constants import *
# import unittest
# from unittest import TestCase
# import mysql.connector as conn
# class TestFetchJob(TestCase):
# def test_fetch_job(self):
# try:
# mydbobj = conn.connect(db)
# mycurs... | # from python.jobs import *
# from python.constants import *
# import unittest
# from unittest import TestCase
# import mysql.connector as conn
# class TestFetchJob(TestCase):
# def test_fetch_job(self):
# try:
# mydbobj = conn.connect(db)
# mycursor = mydbobj.cursor()
# ... | en | 0.346035 | # from python.jobs import * # from python.constants import * # import unittest # from unittest import TestCase # import mysql.connector as conn # class TestFetchJob(TestCase): # def test_fetch_job(self): # try: # mydbobj = conn.connect(db) # mycursor = mydbobj.cursor() # ... | 2.749506 | 3 |
src/kgm/training/__init__.py | mberr/ea-sota-comparison | 12 | 6623012 | # coding=utf-8
"""Training Loops."""
| # coding=utf-8
"""Training Loops."""
| en | 0.872304 | # coding=utf-8 Training Loops. | 0.99114 | 1 |
app/code/image_crop.py | LuQ232/Chessboard-Importer | 6 | 6623013 | import math
import functools
import cv2
import numpy as np
na = np.array
def image_scale(pts, scale):
"""scale to original image size"""
def __loop(x, y):
return [x[0] * y, x[1] * y]
return list(map(functools.partial(__loop, y=1/scale), pts))
def image_resize(img, height=500):
"""resize image ... | import math
import functools
import cv2
import numpy as np
na = np.array
def image_scale(pts, scale):
"""scale to original image size"""
def __loop(x, y):
return [x[0] * y, x[1] * y]
return list(map(functools.partial(__loop, y=1/scale), pts))
def image_resize(img, height=500):
"""resize image ... | en | 0.742253 | scale to original image size resize image to square area (height^2) crop original image using perspective warp cropping original image to output | 2.844913 | 3 |
libs/parse_audio.py | prateekKrOraon/song-identification | 0 | 6623014 | import os
import io
import numpy as np
from pydub import AudioSegment
from hashlib import sha1
from pydub.utils import audioop
def parse_bytes(bytes_data, format="mp3", offline=False):
"""Processes the bytes received to extract audio information.
Extracts audio channels, frame rate and SHA-1 hash digest.
... | import os
import io
import numpy as np
from pydub import AudioSegment
from hashlib import sha1
from pydub.utils import audioop
def parse_bytes(bytes_data, format="mp3", offline=False):
"""Processes the bytes received to extract audio information.
Extracts audio channels, frame rate and SHA-1 hash digest.
... | en | 0.736144 | Processes the bytes received to extract audio information. Extracts audio channels, frame rate and SHA-1 hash digest. Args: bytes_data: A bytes stream. format: Audio coding format. offline: If the file is coming from local storage. Returns: ... | 3.296856 | 3 |
pracnbastats/format.py | practicallypredictable/pracnbstats | 0 | 6623015 | <filename>pracnbastats/format.py
import numpy as np
import pandas as pd
from . import params
def season_id(df):
"""Extract season and season type from a box score season ID."""
df['season'] = df['SEASON_ID'].apply(
lambda id: params.Season.season_from_id(id).start_year
)
df['season_type'] = df[... | <filename>pracnbastats/format.py
import numpy as np
import pandas as pd
from . import params
def season_id(df):
"""Extract season and season type from a box score season ID."""
df['season'] = df['SEASON_ID'].apply(
lambda id: params.Season.season_from_id(id).start_year
)
df['season_type'] = df[... | en | 0.808239 | Extract season and season type from a box score season ID. Add more useful columns based upon matchup information. Reorder DataFrame columns by first/middle/last grouping. | 3.21152 | 3 |
nsl/ast/__init__.py | Anteru/nsl | 0 | 6623016 | import collections
import collections.abc
from nsl import op, types, Visitor
from enum import Enum
import bisect
from typing import List
class SourceMapping:
def __init__(self, source, sourceName = '<unknown>'):
self.__sourceName = sourceName
self.__lineOffsets = []
currentOffset =... | import collections
import collections.abc
from nsl import op, types, Visitor
from enum import Enum
import bisect
from typing import List
class SourceMapping:
def __init__(self, source, sourceName = '<unknown>'):
self.__sourceName = sourceName
self.__lineOffsets = []
currentOffset =... | en | 0.817938 | # trailing \n # Lines are 0 based (as are columns), and we need to offset # with +1 for display A single translation module. A module consists of types, variables and functions. # Types may depend on types which are previously defined # Ensure ordering by using an ordered dict Module ({0} variable(s), {1} func... | 2.708107 | 3 |
machine_learning/cloud_functions/collect_from_datastore.py | cyberj0g/verification-classifier | 8 | 6623017 | """
Module for collecting metrics values from GCE datastore
generated with the cloud functions located in feature_engineering
USAGE:
$python3 collect_from_datastore.py
This will create a .csv file in the current folder containing
the values of all the metrics available in the database for later
use in the jupyter not... | """
Module for collecting metrics values from GCE datastore
generated with the cloud functions located in feature_engineering
USAGE:
$python3 collect_from_datastore.py
This will create a .csv file in the current folder containing
the values of all the metrics available in the database for later
use in the jupyter not... | en | 0.68491 | Module for collecting metrics values from GCE datastore generated with the cloud functions located in feature_engineering USAGE: $python3 collect_from_datastore.py This will create a .csv file in the current folder containing the values of all the metrics available in the database for later use in the jupyter noteboo... | 2.672406 | 3 |
executors/display_functions.py | thevickypedia/jarvis | 0 | 6623018 | import os
import random
from threading import Thread
from modules.audio import speaker
from modules.conditions import conversation
from modules.models import models
from modules.utils import support
env = models.env
def brightness(phrase: str):
"""Pre-process to check the phrase received and call the appropriat... | import os
import random
from threading import Thread
from modules.audio import speaker
from modules.conditions import conversation
from modules.models import models
from modules.utils import support
env = models.env
def brightness(phrase: str):
"""Pre-process to check the phrase received and call the appropriat... | en | 0.778181 | Pre-process to check the phrase received and call the appropriate brightness function as necessary. Args: phrase: Takes the phrase spoken as an argument. Increases the brightness to maximum in macOS. osascript -e 'tell application "System Events"' -e 'key code 144' -e ' end tell' Decreases the brightness t... | 3.022237 | 3 |
tests/test_advance_compiler.py | chuanhao01/Python_Expression_Evaluator | 0 | 6623019 | import pytest
from src.advance.expression_evaluator import Evaluator
class TestAdvancedCompiler:
@pytest.mark.parametrize('text, eval', [
('1 + 1', 2),
('1', 1),
('2 - 3', -1),
("'aa' + 'bb'", 'aabb'),
('5 // 2', 2),
('5 / 2', 2.5),
('5 - 2 * 3', -1),
... | import pytest
from src.advance.expression_evaluator import Evaluator
class TestAdvancedCompiler:
@pytest.mark.parametrize('text, eval', [
('1 + 1', 2),
('1', 1),
('2 - 3', -1),
("'aa' + 'bb'", 'aabb'),
('5 // 2', 2),
('5 / 2', 2.5),
('5 - 2 * 3', -1),
... | none | 1 | 2.842417 | 3 | |
src/old_scripts/old_prob.py | s-zhang/DnDnProbabilities | 0 | 6623020 | from functools import *
from itertools import *
from math import sqrt
# from pprint import pprint
import operator
# from multipledispatch import dispatch
class Pmf(object):
"""Probability mass function"""
def __init__(self):
super(Pmf, self).__init__()
def prob(self, outcome):
raise Not... | from functools import *
from itertools import *
from math import sqrt
# from pprint import pprint
import operator
# from multipledispatch import dispatch
class Pmf(object):
"""Probability mass function"""
def __init__(self):
super(Pmf, self).__init__()
def prob(self, outcome):
raise Not... | en | 0.430247 | # from pprint import pprint # from multipledispatch import dispatch Probability mass function # print(outcome, prob, mapped_outcome) @classmethod def reduce(cls, op, pmfs, unit = None): def pmf_op(pmf1, pmf2): return cls.multimap(op, (pmf1, pmf2)) if unit == None: return redu... | 2.912823 | 3 |
src/UQpy/SampleMethods/IS.py | marrov/UQpy | 132 | 6623021 | from UQpy.Distributions import Distribution
import numpy as np
########################################################################################################################
########################################################################################################################
# ... | from UQpy.Distributions import Distribution
import numpy as np
########################################################################################################################
########################################################################################################################
# ... | en | 0.706602 | ######################################################################################################################## ######################################################################################################################## # Generating random samples inside a Si... | 2.266816 | 2 |
src/anomaly_toolbox/datasets/__init__.py | zurutech/anomaly-toolbox | 73 | 6623022 | <reponame>zurutech/anomaly-toolbox<filename>src/anomaly_toolbox/datasets/__init__.py
# Copyright 2021 Zuru Tech HK Limited. 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 a... | # Copyright 2021 Zuru Tech HK Limited. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable la... | en | 0.830674 | # Copyright 2021 Zuru Tech HK Limited. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable la... | 1.465679 | 1 |
spectator/events/migrations/0043_rename_ticket_to_thumbnail.py | philgyford/django-spectator | 36 | 6623023 | <gh_stars>10-100
# Generated by Django 3.0.5 on 2020-04-07 10:49
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
("spectator_events", "0042_auto_20200407_1039"),
]
operations = [
migrations.RenameField(
model_name="event", old_name="t... | # Generated by Django 3.0.5 on 2020-04-07 10:49
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
("spectator_events", "0042_auto_20200407_1039"),
]
operations = [
migrations.RenameField(
model_name="event", old_name="ticket", new_name=... | en | 0.833996 | # Generated by Django 3.0.5 on 2020-04-07 10:49 | 1.693672 | 2 |
engine/run_preprocess.py | fhidalgor/erdos2021-project | 1 | 6623024 | <reponame>fhidalgor/erdos2021-project
"""
Module to run the preprocessing pipeline
"""
import pandas as pd
from engine.preprocess.extract_pubmed import ExtractPubmedAbstracts
from engine.preprocess.extract_mimic import ExtractMimicNotes
from engine.preprocess.tokenize_text import Tokenize
from engine.preprocess.identif... | """
Module to run the preprocessing pipeline
"""
import pandas as pd
from engine.preprocess.extract_pubmed import ExtractPubmedAbstracts
from engine.preprocess.extract_mimic import ExtractMimicNotes
from engine.preprocess.tokenize_text import Tokenize
from engine.preprocess.identify_longforms import IdentifyLongForms
f... | en | 0.49282 | Module to run the preprocessing pipeline #obj = Tokenize('m<PASSWORD>iii') # Load short forms dataframe #obj = IdentifyLongForms('mimiciii', SUBSET_DF) #print(SUBSET_DF.columns) | 2.550356 | 3 |
src/config/device-manager/device_manager/plugins/ansible/overlay/overlay_conf.py | kaweue/contrail-controller | 0 | 6623025 | #
# Copyright (c) 2014 Juniper Networks, Inc. All rights reserved.
#
"""
This file contains implementation of abstract config generation for leafs
"""
from ansible_role_common import AnsibleRoleCommon
from abstract_device_api.abstract_device_xsd import *
class OverlayConf(AnsibleRoleCommon):
_roles = ['leaf', 's... | #
# Copyright (c) 2014 Juniper Networks, Inc. All rights reserved.
#
"""
This file contains implementation of abstract config generation for leafs
"""
from ansible_role_common import AnsibleRoleCommon
from abstract_device_api.abstract_device_xsd import *
class OverlayConf(AnsibleRoleCommon):
_roles = ['leaf', 's... | en | 0.727189 | # # Copyright (c) 2014 Juniper Networks, Inc. All rights reserved. # This file contains implementation of abstract config generation for leafs # end __init__ # end register # end push_conf # end LeafConf | 2.105291 | 2 |
platform_monitoring/base.py | neuro-inc/platform-monitoring | 0 | 6623026 | <gh_stars>0
import time
from abc import ABC, abstractmethod
from collections.abc import AsyncIterator
from dataclasses import dataclass, field
from datetime import datetime
from typing import Any, Optional
class LogReader(ABC):
last_time: Optional[datetime] = None
def __init__(self, container_runtime: str, t... | import time
from abc import ABC, abstractmethod
from collections.abc import AsyncIterator
from dataclasses import dataclass, field
from datetime import datetime
from typing import Any, Optional
class LogReader(ABC):
last_time: Optional[datetime] = None
def __init__(self, container_runtime: str, timestamps: b... | none | 1 | 2.752501 | 3 | |
Scripts/003_hackerrank/30 Days of Code/d016.py | OrangePeelFX/Python-Tutorial | 0 | 6623027 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Day 16: Exceptions - String to Integer
Source : https://www.hackerrank.com/challenges/30-exceptions-string-to-integer/problem
"""
try:
print(int(input().strip()))
except:
print("Bad String")
| #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Day 16: Exceptions - String to Integer
Source : https://www.hackerrank.com/challenges/30-exceptions-string-to-integer/problem
"""
try:
print(int(input().strip()))
except:
print("Bad String")
| en | 0.488733 | #!/usr/bin/env python3 # -*- coding: utf-8 -*- Day 16: Exceptions - String to Integer Source : https://www.hackerrank.com/challenges/30-exceptions-string-to-integer/problem | 3.437869 | 3 |
controllers/artist.py | Silve1ra/fyyur | 1 | 6623028 | <gh_stars>1-10
import sys
from flask import render_template, redirect, url_for, request, flash
from models.models import Artist, Venue, Show
from forms import ArtistForm, datetime
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
def artists():
data = Artist.query.all()
return render_template('pages/... | import sys
from flask import render_template, redirect, url_for, request, flash
from models.models import Artist, Venue, Show
from forms import ArtistForm, datetime
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
def artists():
data = Artist.query.all()
return render_template('pages/artists.html', ... | none | 1 | 2.351197 | 2 | |
run.py | Carmo-sousa/livro-flask | 0 | 6623029 | """
Responsável por rodar o programa.
"""
from app import create_app
from config import app_active, app_config
config = app_config[app_active]
config.APP = create_app(app_active)
if __name__ == "__main__":
config.APP.run(host=config.IP_HOST, port=config.PORT_HOST)
| """
Responsável por rodar o programa.
"""
from app import create_app
from config import app_active, app_config
config = app_config[app_active]
config.APP = create_app(app_active)
if __name__ == "__main__":
config.APP.run(host=config.IP_HOST, port=config.PORT_HOST)
| pt | 0.891253 | Responsável por rodar o programa. | 2.187389 | 2 |
nets/GeneralizedWF.py | Andong-Li-speech/TaylorBeamformer | 4 | 6623030 | import torch
import torch.nn as nn
from torch import Tensor
from torch.autograd import Variable
from torch_complex.tensor import ComplexTensor
import torch_complex.functional as F
from utils.utils import complex_mul, complex_conj, NormSwitch
class GeneralizedMultichannelWienerFiter(nn.Module):
def __init_... | import torch
import torch.nn as nn
from torch import Tensor
from torch.autograd import Variable
from torch_complex.tensor import ComplexTensor
import torch_complex.functional as F
from utils.utils import complex_mul, complex_conj, NormSwitch
class GeneralizedMultichannelWienerFiter(nn.Module):
def __init_... | en | 0.580407 | # Components # inv module inpt: (B,T,F,M,2) # (B,T,F,M,M,2) # (B,T,F,M,2) # derive wiener filter # (B,T,F,M) # (B,T,F,M) # (B,T,F,2) # Components inpt: (B,T,F,M,2)
return: (B,T,F,M,M,2) # (B,T,F,M) # (B,T,F,M,M) # (B,T,F,2MM) # (BF,T,2MM) inpt: (B,T,F,M,2)
return: (B,T,F,M,2) # output # (B,T,F,2) # (B... | 2.134341 | 2 |
atm90e36a/registers.py | aradian/pipdu_host | 0 | 6623031 | <reponame>aradian/pipdu_host<filename>atm90e36a/registers.py
# Status and Special Register
SoftReset = 0x00
SysStatus0 = 0x01
SysStatus1 = 0x02
FuncEn0 = 0x03
FuncEn1 = 0x04
ZXConfig = 0x07
SagTh = 0x08
PhaseLossTh = 0x09
INWarnTh0 = 0x0A
INWarnTh1 = 0x0B
THDNUTh = 0x0C
THDNITh = 0x0D
DMACtrl ... | # Status and Special Register
SoftReset = 0x00
SysStatus0 = 0x01
SysStatus1 = 0x02
FuncEn0 = 0x03
FuncEn1 = 0x04
ZXConfig = 0x07
SagTh = 0x08
PhaseLossTh = 0x09
INWarnTh0 = 0x0A
INWarnTh1 = 0x0B
THDNUTh = 0x0C
THDNITh = 0x0D
DMACtrl = 0x0E
LastSPIData = 0x0F
# Low Power Mode Register
Detec... | en | 0.651088 | # Status and Special Register # Low Power Mode Register # Configuration Registers # Calibration Registers # Fundamental/Harmonic Energy Calibration regis ters # Measurement Calibration # Energy Register # Fundamental / Harmonic Energy Register # Power and Power Factor Registers # Fundamental/ Harmonic Power and V... | 1.059526 | 1 |
app.py | rudyduvnjak/sqlalchemy-challenge | 0 | 6623032 | import numpy as np
import pandas as pd
import sqlalchemy
import datetime as dt
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm import Session
from sqlalchemy import create_engine, func
from flask import Flask, jsonify
#################################################
# Database Setup
##############... | import numpy as np
import pandas as pd
import sqlalchemy
import datetime as dt
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm import Session
from sqlalchemy import create_engine, func
from flask import Flask, jsonify
#################################################
# Database Setup
##############... | en | 0.63515 | ################################################# # Database Setup ################################################# # reflect an existing database into a new model # reflect the tables # Save reference to the table ################################################# # Flask Setup ########################################... | 2.650475 | 3 |
globagrim/boundary_conditions.py | neumannd/globagrim_project | 3 | 6623033 | from .variables import global_const, global_array
def boundary_conditions():
#
# poles
#
for j in range(0, global_const.NJ + 1):
joppos = j + int(global_const.NJ / 2)
if joppos > global_const.NJ:
joppos = joppos - global_const.NJ
global_array.ps[j, 0] = global_array... | from .variables import global_const, global_array
def boundary_conditions():
#
# poles
#
for j in range(0, global_const.NJ + 1):
joppos = j + int(global_const.NJ / 2)
if joppos > global_const.NJ:
joppos = joppos - global_const.NJ
global_array.ps[j, 0] = global_array... | de | 0.553194 | # # poles # # # east/west # ######################### | 2.239837 | 2 |
src/main/python/views/ImagePreviewDialog.py | sudoparsa/paperECG | 14 | 6623034 |
from PyQt5 import QtCore, QtGui, QtWidgets
from QtWrapper import *
from ImageUtilities import opencvImageToPixmap
class ImagePreviewDialog(QtWidgets.QDialog):
def __init__(self, image, leadId):
super().__init__()
self.pixmap = opencvImageToPixmap(image)
self.leadId = leadId
self.i... |
from PyQt5 import QtCore, QtGui, QtWidgets
from QtWrapper import *
from ImageUtilities import opencvImageToPixmap
class ImagePreviewDialog(QtWidgets.QDialog):
def __init__(self, image, leadId):
super().__init__()
self.pixmap = opencvImageToPixmap(image)
self.leadId = leadId
self.i... | none | 1 | 2.340001 | 2 | |
blackjack/hand.py | rockchalkwushock/pdx-code-labs | 0 | 6623035 | from deck import values
class Hand:
def __init__(self):
self.cards = []
self.score = 0
self.aces = 0
def __str__(self):
return f'Cards: {self.cards}\nScore: {self.score}\nAces: {self.aces}\n'
def draw_card(self, card):
self.cards.append(card)
self.score +=... | from deck import values
class Hand:
def __init__(self):
self.cards = []
self.score = 0
self.aces = 0
def __str__(self):
return f'Cards: {self.cards}\nScore: {self.score}\nAces: {self.aces}\n'
def draw_card(self, card):
self.cards.append(card)
self.score +=... | none | 1 | 3.21269 | 3 | |
app/site/views.py | perna/podigger | 5 | 6623036 | <filename>app/site/views.py
from flask import Blueprint, render_template, request, flash, Markup
from app.repository.episode import EpisodeRepository
from app.repository.podcast import PodcastRepository
from app.repository.topic_suggestion import TopicSuggestionRepository
from app.repository.term import TermRepository
... | <filename>app/site/views.py
from flask import Blueprint, render_template, request, flash, Markup
from app.repository.episode import EpisodeRepository
from app.repository.podcast import PodcastRepository
from app.repository.topic_suggestion import TopicSuggestionRepository
from app.repository.term import TermRepository
... | none | 1 | 2.138465 | 2 | |
ms_graph_exporter/celery/__init__.py | undp/MsGraphExporter | 1 | 6623037 | # -*- coding: utf-8 -*-
"""Package contains following modules.
* :mod:`ms_graph_exporter.celery.app` - Celery app and worker customizations.
* :mod:`ms_graph_exporter.celery.config` - app config objects.
* :mod:`ms_graph_exporter.celery.graph_api_base` - base class for data extraction tasks.
* :mod:`ms_graph_exporter.... | # -*- coding: utf-8 -*-
"""Package contains following modules.
* :mod:`ms_graph_exporter.celery.app` - Celery app and worker customizations.
* :mod:`ms_graph_exporter.celery.config` - app config objects.
* :mod:`ms_graph_exporter.celery.graph_api_base` - base class for data extraction tasks.
* :mod:`ms_graph_exporter.... | en | 0.56084 | # -*- coding: utf-8 -*- Package contains following modules. * :mod:`ms_graph_exporter.celery.app` - Celery app and worker customizations. * :mod:`ms_graph_exporter.celery.config` - app config objects. * :mod:`ms_graph_exporter.celery.graph_api_base` - base class for data extraction tasks. * :mod:`ms_graph_exporter.cel... | 1.196746 | 1 |
tests/web_platform/CSS2/positioning/test_position_relative_nested.py | fletchgraham/colosseum | 0 | 6623038 | <reponame>fletchgraham/colosseum<gh_stars>0
from tests.utils import W3CTestCase
class TestPositionRelativeNested(W3CTestCase):
vars().update(W3CTestCase.find_tests(__file__, 'position-relative-nested-'))
| from tests.utils import W3CTestCase
class TestPositionRelativeNested(W3CTestCase):
vars().update(W3CTestCase.find_tests(__file__, 'position-relative-nested-')) | none | 1 | 1.439668 | 1 | |
install/core/python/tank/platform/events/event_file_close.py | JoanAzpeitia/lp_sg | 0 | 6623039 | <filename>install/core/python/tank/platform/events/event_file_close.py
# Copyright (c) 2016 Shotgun Software Inc.
#
# CONFIDENTIAL AND PROPRIETARY
#
# This work is provided "AS IS" and subject to the Shotgun Pipeline Toolkit
# Source Code License included in this distribution package. See LICENSE.
# By accessing, us... | <filename>install/core/python/tank/platform/events/event_file_close.py
# Copyright (c) 2016 Shotgun Software Inc.
#
# CONFIDENTIAL AND PROPRIETARY
#
# This work is provided "AS IS" and subject to the Shotgun Pipeline Toolkit
# Source Code License included in this distribution package. See LICENSE.
# By accessing, us... | en | 0.913481 | # Copyright (c) 2016 Shotgun Software Inc. # # CONFIDENTIAL AND PROPRIETARY # # This work is provided "AS IS" and subject to the Shotgun Pipeline Toolkit # Source Code License included in this distribution package. See LICENSE. # By accessing, using, copying or modifying this work you indicate your # agreement to the S... | 2.710504 | 3 |
draugr/metrics/__init__.py | cnHeider/draugr | 3 | 6623040 | <filename>draugr/metrics/__init__.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = "<NAME>"
__doc__ = r"""
"""
from pathlib import Path
with open(Path(__file__).parent / "README.md", "r") as this_init_file:
__doc__ += this_init_file.read()
from .accumulation import *
from .meters import *
from .me... | <filename>draugr/metrics/__init__.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = "<NAME>"
__doc__ = r"""
"""
from pathlib import Path
with open(Path(__file__).parent / "README.md", "r") as this_init_file:
__doc__ += this_init_file.read()
from .accumulation import *
from .meters import *
from .me... | en | 0.308914 | #!/usr/bin/env python3 # -*- coding: utf-8 -*- | 1.661848 | 2 |
shap/maskers/_fixed.py | zduey/shap | 1 | 6623041 | from ._masker import Masker
class Fixed(Masker):
""" This leaves the input unchanged during masking, and is used for things like scoring labels.
Sometimes there are inputs to the model that we do not want to explain, but rather we want to
consider them fixed. The primary example of this is when we explai... | from ._masker import Masker
class Fixed(Masker):
""" This leaves the input unchanged during masking, and is used for things like scoring labels.
Sometimes there are inputs to the model that we do not want to explain, but rather we want to
consider them fixed. The primary example of this is when we explai... | en | 0.951966 | This leaves the input unchanged during masking, and is used for things like scoring labels. Sometimes there are inputs to the model that we do not want to explain, but rather we want to consider them fixed. The primary example of this is when we explain the loss of the model using the labels. These "true" ... | 3.548579 | 4 |
test_scripts/test_xml2yolo.py | wwdok/mask2json | 27 | 6623042 | <gh_stars>10-100
'''
lanhuage: python
Descripttion: convert xmls to yolo txts.
version: beta
Author: xiaoshuyui
Date: 2020-08-24 09:39:42
LastEditors: xiaoshuyui
LastEditTime: 2020-10-20 09:49:55
'''
import sys
sys.path.append("..")
import os
from convertmask.utils.xml2yolo.xml2yolo import x2yConvert
BASE_DIR = os.p... | '''
lanhuage: python
Descripttion: convert xmls to yolo txts.
version: beta
Author: xiaoshuyui
Date: 2020-08-24 09:39:42
LastEditors: xiaoshuyui
LastEditTime: 2020-10-20 09:49:55
'''
import sys
sys.path.append("..")
import os
from convertmask.utils.xml2yolo.xml2yolo import x2yConvert
BASE_DIR = os.path.abspath(os.pa... | en | 0.650931 | lanhuage: python Descripttion: convert xmls to yolo txts. version: beta Author: xiaoshuyui Date: 2020-08-24 09:39:42 LastEditors: xiaoshuyui LastEditTime: 2020-10-20 09:49:55 # single test # multi file test | 1.929983 | 2 |
dagmc_stats/DagmcFile.py | svalinn/dagmc_stats | 1 | 6623043 | import pandas as pd
import numpy as np
from pymoab.rng import Range
from pymoab import core, types
import warnings
class DagmcFile:
def __init__(self, filename, populate=False):
"""Constructor
inputs
------
filename : name of the file
populate : boolean value that determi... | import pandas as pd
import numpy as np
from pymoab.rng import Range
from pymoab import core, types
import warnings
class DagmcFile:
def __init__(self, filename, populate=False):
"""Constructor
inputs
------
filename : name of the file
populate : boolean value that determi... | en | 0.494838 | Constructor inputs ------ filename : name of the file populate : boolean value that determines whether or not to populate the data outputs ------- none # read file # if populate is True: # self.__populate_triangle_data(meshset) Set the class native_ranges var... | 2.498678 | 2 |
model.py | pskrunner14/face-gan | 1 | 6623044 | <filename>model.py
""" Deep Convolutional Generative Adversarial Network (DCGAN).
Using deep convolutional generative adversarial networks (DCGAN)
to generate face images from a noise distribution.
References:
- Generative Adversarial Nets. Goodfellow et al. arXiv: 1406.2661.
- Unsupervised Representation Le... | <filename>model.py
""" Deep Convolutional Generative Adversarial Network (DCGAN).
Using deep convolutional generative adversarial networks (DCGAN)
to generate face images from a noise distribution.
References:
- Generative Adversarial Nets. Goodfellow et al. arXiv: 1406.2661.
- Unsupervised Representation Le... | en | 0.648709 | Deep Convolutional Generative Adversarial Network (DCGAN). Using deep convolutional generative adversarial networks (DCGAN) to generate face images from a noise distribution. References: - Generative Adversarial Nets. Goodfellow et al. arXiv: 1406.2661. - Unsupervised Representation Learning with Deep Convol... | 2.965709 | 3 |
module/japanese_jisho.py | liangguo/ankiword | 1 | 6623045 | import urllib.request;
from urllib.parse import quote
from bs4 import BeautifulSoup
import subprocess
import platform
import datetime
import json
import wget
import re
from re import compile as _Re
_unicode_chr_splitter = _Re( '(?s)((?:[\u2e80-\u9fff])|.)' ).split
def LookUp(word, data):
result = {}
# Elimin... | import urllib.request;
from urllib.parse import quote
from bs4 import BeautifulSoup
import subprocess
import platform
import datetime
import json
import wget
import re
from re import compile as _Re
_unicode_chr_splitter = _Re( '(?s)((?:[\u2e80-\u9fff])|.)' ).split
def LookUp(word, data):
result = {}
# Elimin... | en | 0.790026 | # Eliminate the end of line delimiter # Insert the sound media into the card | 2.776248 | 3 |
tests/browser/pages/invest/landing.py | mayank-sfdc/directory-tests | 4 | 6623046 | # -*- coding: utf-8 -*-
"""Invest in Great Home Page Object."""
import logging
from typing import List
from selenium.webdriver.common.by import By
from selenium.webdriver.remote.webdriver import WebDriver
from directory_tests_shared import URLs
from directory_tests_shared.enums import PageType, Service
from pages imp... | # -*- coding: utf-8 -*-
"""Invest in Great Home Page Object."""
import logging
from typing import List
from selenium.webdriver.common.by import By
from selenium.webdriver.remote.webdriver import WebDriver
from directory_tests_shared import URLs
from directory_tests_shared.enums import PageType, Service
from pages imp... | en | 0.756747 | # -*- coding: utf-8 -*- Invest in Great Home Page Object. | 2.446408 | 2 |
designer_door_mat.py | nirobio/puzzles | 0 | 6623047 | # Hackerrank - Designer Door Mat
# repetitions of '.|.' with remaining L/R filled with '-'
# top and bottom of central 'WELCOME' belt are symmetrical (hence N//2)
N, M = map(int, input().split())
pattern = [('.|.' * (2 * i + 1)).center(M, '-') for i in range(N // 2)]
print('\n'.join(pattern + ['WELCOME'.center(M, '-')... | # Hackerrank - Designer Door Mat
# repetitions of '.|.' with remaining L/R filled with '-'
# top and bottom of central 'WELCOME' belt are symmetrical (hence N//2)
N, M = map(int, input().split())
pattern = [('.|.' * (2 * i + 1)).center(M, '-') for i in range(N // 2)]
print('\n'.join(pattern + ['WELCOME'.center(M, '-')... | en | 0.816314 | # Hackerrank - Designer Door Mat # repetitions of '.|.' with remaining L/R filled with '-' # top and bottom of central 'WELCOME' belt are symmetrical (hence N//2) | 3.10084 | 3 |
tests/use_cases/test_git_clone.py | staticdev/github-portfolio | 0 | 6623048 | """Test cases for the git clone use case."""
from typing import Any
import pytest
from pytest_mock import MockerFixture
from tests.conftest import ERROR_MSG
from tests.conftest import REPO
from tests.conftest import REPO2
from tests.conftest import REPO_NAME
import git_portfolio.responses as res
from git_portfolio.us... | """Test cases for the git clone use case."""
from typing import Any
import pytest
from pytest_mock import MockerFixture
from tests.conftest import ERROR_MSG
from tests.conftest import REPO
from tests.conftest import REPO2
from tests.conftest import REPO_NAME
import git_portfolio.responses as res
from git_portfolio.us... | en | 0.566197 | Test cases for the git clone use case. Fixture for mocking subprocess.Popen. Fixture for mocking GithubService. Fixture for mocking CommandChecker.check. It returns success messages. It returns failure with git not installed message. It returns failure with git not installed message. It returns error. | 2.438371 | 2 |
train.py | peterzheng98/fuzzy-system | 0 | 6623049 | import os
import time
import json
import numpy as np
from tqdm import tqdm
import torch
import torch.nn as nn
import torch.optim as optim
import torch.distributed as dist
import torch.multiprocessing as mp
from torch.utils.data import DataLoader
from torch.nn.parallel import DistributedDataParallel
from torch.utils.... | import os
import time
import json
import numpy as np
from tqdm import tqdm
import torch
import torch.nn as nn
import torch.optim as optim
import torch.distributed as dist
import torch.multiprocessing as mp
from torch.utils.data import DataLoader
from torch.nn.parallel import DistributedDataParallel
from torch.utils.... | en | 0.302482 | # Important Parameters #{:02d}'.format(epoch), total=len(dataloader_train), leave=False) # bar2 = tqdm(desc='(1/3)Eval In #{:02d}'.format(epoch), total=len(dataset_eval_in), leave=False) # bar3 = tqdm(desc='(2/3)Eval In #{:02d}'.format(epoch), total=len(dataset_eval_out), leave=False) # bar2.update() # bar2.close() # b... | 2.062458 | 2 |
ARC/arc001-arc050/arc043/a.py | KATO-Hiro/AtCoder | 2 | 6623050 | <reponame>KATO-Hiro/AtCoder<gh_stars>1-10
# -*- coding: utf-8 -*-
def main():
n, a, b = map(int, input().split())
s = [int(input()) for _ in range(n)]
s_max = max(s)
s_min = min(s)
if s_max == s_min:
print(-1)
else:
p = b / (s_max - s_min)
s_sum = sum(s)
... | # -*- coding: utf-8 -*-
def main():
n, a, b = map(int, input().split())
s = [int(input()) for _ in range(n)]
s_max = max(s)
s_min = min(s)
if s_max == s_min:
print(-1)
else:
p = b / (s_max - s_min)
s_sum = sum(s)
q = a - p * s_sum / n
pri... | en | 0.769321 | # -*- coding: utf-8 -*- | 2.875293 | 3 |