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 |
|---|---|---|---|---|---|---|---|---|---|---|
model_compression_toolkit/keras/quantizer/gradient_ptq/utils.py | eladc-git/model_optimization | 0 | 3500 | <filename>model_compression_toolkit/keras/quantizer/gradient_ptq/utils.py<gh_stars>0
# Copyright 2021 Sony Semiconductors Israel, 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 th... | <filename>model_compression_toolkit/keras/quantizer/gradient_ptq/utils.py<gh_stars>0
# Copyright 2021 Sony Semiconductors Israel, 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 th... | en | 0.75817 | # Copyright 2021 Sony Semiconductors Israel, 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 b... | 2.122413 | 2 |
pygments/lexers/tnt.py | btashton/pygments | 1 | 3501 | <filename>pygments/lexers/tnt.py<gh_stars>1-10
# -*- coding: utf-8 -*-
"""
pygments.lexers.tnt
~~~~~~~~~~~~~~~~~~~
Lexer for Typographic Number Theory.
:copyright: Copyright 2019-2020 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
import re
from pygments.lexer impor... | <filename>pygments/lexers/tnt.py<gh_stars>1-10
# -*- coding: utf-8 -*-
"""
pygments.lexers.tnt
~~~~~~~~~~~~~~~~~~~
Lexer for Typographic Number Theory.
:copyright: Copyright 2019-2020 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
import re
from pygments.lexer impor... | en | 0.742402 | # -*- coding: utf-8 -*- pygments.lexers.tnt ~~~~~~~~~~~~~~~~~~~ Lexer for Typographic Number Theory. :copyright: Copyright 2019-2020 by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details. Lexer for Typographic Number Theory, as described in the book <NAME>, by <NAME>, or as... | 2.24608 | 2 |
contacts/urls.py | cheradenine/Django-CRM | 2 | 3502 | <filename>contacts/urls.py
from django.urls import path
from contacts.views import (
ContactsListView, CreateContactView, ContactDetailView,
UpdateContactView, RemoveContactView,
GetContactsView, AddCommentView, UpdateCommentView,
DeleteCommentView, AddAttachmentsView, DeleteAttachmentsView)
app_name =... | <filename>contacts/urls.py
from django.urls import path
from contacts.views import (
ContactsListView, CreateContactView, ContactDetailView,
UpdateContactView, RemoveContactView,
GetContactsView, AddCommentView, UpdateCommentView,
DeleteCommentView, AddAttachmentsView, DeleteAttachmentsView)
app_name =... | none | 1 | 2.222111 | 2 | |
windows/winobject/network.py | marpie/PythonForWindows | 1 | 3503 | import windows
import ctypes
import socket
import struct
from windows import winproxy
import windows.generated_def as gdef
from windows.com import interfaces as cominterfaces
from windows.generated_def.winstructs import *
from windows.generated_def.windef import *
class TCP4Connection(MIB_TCPROW_OWNER_PID):
"""A... | import windows
import ctypes
import socket
import struct
from windows import winproxy
import windows.generated_def as gdef
from windows.com import interfaces as cominterfaces
from windows.generated_def.winstructs import *
from windows.generated_def.windef import *
class TCP4Connection(MIB_TCPROW_OWNER_PID):
"""A... | en | 0.660982 | A TCP4 socket (connected or listening) ``True`` if connection is established else it's a listening socket :type: :class:`int` :type: :class:`int` Local address IP (x.x.x.x) :type: :class:`str` remote address IP (x.x.x.x) :type: :class:`str` Identification of the protocol associated with the remote por... | 2.439379 | 2 |
LIM_scripts/func_curry.py | Bhare8972/LOFAR-LIM | 3 | 3504 | #!/usr/bin/env python3
# Coded by <NAME>, 2012.
#
# - Thanks to b49P23TIvg for suggesting that I should use a set operation
# instead of repeated membership tests.
# - Thanks to <NAME> for pointing out that
# - "minArgs = None" is better than "minArgs = -1",
# - "if args" is better than "if len(args)", and... | #!/usr/bin/env python3
# Coded by <NAME>, 2012.
#
# - Thanks to b49P23TIvg for suggesting that I should use a set operation
# instead of repeated membership tests.
# - Thanks to <NAME> for pointing out that
# - "minArgs = None" is better than "minArgs = -1",
# - "if args" is better than "if len(args)", and... | en | 0.825252 | #!/usr/bin/env python3 # Coded by <NAME>, 2012. # # - Thanks to b49P23TIvg for suggesting that I should use a set operation # instead of repeated membership tests. # - Thanks to <NAME> for pointing out that # - "minArgs = None" is better than "minArgs = -1", # - "if args" is better than "if len(args)", and ... | 2.860062 | 3 |
src/messages.py | Ewpratten/chat | 0 | 3505 | greeting = """
--------------- BEGIN SESSION ---------------
You have connected to a chat server. Welcome!
:: About
Chat is a small piece of server software
written by <NAME> to allow people to
talk to eachother from any computer as long
as it has an internet connection. (Even an
arduino!). Check out the project at:... | greeting = """
--------------- BEGIN SESSION ---------------
You have connected to a chat server. Welcome!
:: About
Chat is a small piece of server software
written by <NAME> to allow people to
talk to eachother from any computer as long
as it has an internet connection. (Even an
arduino!). Check out the project at:... | en | 0.877851 | --------------- BEGIN SESSION --------------- You have connected to a chat server. Welcome! :: About Chat is a small piece of server software written by <NAME> to allow people to talk to eachother from any computer as long as it has an internet connection. (Even an arduino!). Check out the project at: https://github... | 2.549462 | 3 |
Prediction.py | khayam-hafezi/CRNN-keras-persian | 0 | 3506 | <reponame>khayam-hafezi/CRNN-keras-persian
import cv2
import itertools, os, time
import numpy as np
from Model import get_Model
from parameter import letters
import argparse
from keras import backend as K
K.set_learning_phase(0)
Region = {"A": "서울 ", "B": "경기 ", "C": "인천 ", "D": "강원 ", "E": "충남 ", "F": "대전 ",
... | import cv2
import itertools, os, time
import numpy as np
from Model import get_Model
from parameter import letters
import argparse
from keras import backend as K
K.set_learning_phase(0)
Region = {"A": "서울 ", "B": "경기 ", "C": "인천 ", "D": "강원 ", "E": "충남 ", "F": "대전 ",
"G": "충북 ", "H": "부산 ", "I": "울산 ", "J": ... | en | 0.27207 | # out : (1, 32, 42) # get max index -> len = 32 # remove overlap value # eng -> hangul # Get CRNN model # print('Predicted: %s / True: %s / net_out_value: %s / ' % (label_to_hangul(pred_texts), label_to_hangul(test_img[0:-4]))) # cv2.rectangle(img, (0,0), (150, 30), (0,0,0), -1) # cv2.putText(img, pred_texts, (5, 20)... | 2.009922 | 2 |
torcharrow/_interop.py | OswinC/torcharrow | 0 | 3507 | # Copyright (c) Facebook, Inc. and its affiliates.
from typing import List, Optional, cast
# Skipping analyzing 'numpy': found module but no type hints or library stubs
import numpy as np # type: ignore
import numpy.ma as ma # type: ignore
# Skipping analyzing 'pandas': found module but no type hints or library stu... | # Copyright (c) Facebook, Inc. and its affiliates.
from typing import List, Optional, cast
# Skipping analyzing 'numpy': found module but no type hints or library stubs
import numpy as np # type: ignore
import numpy.ma as ma # type: ignore
# Skipping analyzing 'pandas': found module but no type hints or library stu... | en | 0.496581 | # Copyright (c) Facebook, Inc. and its affiliates. # Skipping analyzing 'numpy': found module but no type hints or library stubs # type: ignore # type: ignore # Skipping analyzing 'pandas': found module but no type hints or library stubs # type: ignore # type: ignore " Convert arrow table to a torcharrow dataframe.... | 2.503985 | 3 |
research/gan/image_compression/eval.py | jdavidagudelo/tensorflow-models | 1 | 3508 | # Copyright 2017 The TensorFlow 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 applica... | # Copyright 2017 The TensorFlow 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 applica... | en | 0.803842 | # Copyright 2017 The TensorFlow 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 applica... | 1.969707 | 2 |
source/dump_query_results.py | CheyenneNS/metrics | 0 | 3509 | <reponame>CheyenneNS/metrics
#!/usr/local/bin/python
import os
import mysql.connector as mysql
metrics_mysql_password = os.environ['METRICS_MYSQL_PWD']
sql_host = os.environ['SQL_HOST']
metrics = os.environ['QUERY_ON']
def dump_query_results():
"""
This is a simple SQL table dump of a given query so we ... | #!/usr/local/bin/python
import os
import mysql.connector as mysql
metrics_mysql_password = os.environ['METRICS_MYSQL_PWD']
sql_host = os.environ['SQL_HOST']
metrics = os.environ['QUERY_ON']
def dump_query_results():
"""
This is a simple SQL table dump of a given query so we can supply users with custom ... | en | 0.784745 | #!/usr/local/bin/python This is a simple SQL table dump of a given query so we can supply users with custom tables. Note that the SQL query itself and column headers portion need to be changed if you want to change the query/results. Otherwise it is good to go. It can be called simply with the bin shell s... | 2.861194 | 3 |
desktop_local_tests/windows/test_windows_packet_capture_disrupt_force_public_dns_servers.py | UAEKondaya1/expressvpn_leak_testing | 219 | 3510 | <reponame>UAEKondaya1/expressvpn_leak_testing
from desktop_local_tests.local_packet_capture_test_case_with_disrupter import LocalPacketCaptureTestCaseWithDisrupter
from desktop_local_tests.windows.windows_dns_force_public_dns_servers_disrupter import WindowsDNSForcePublicDNSServersDisrupter
class TestWindowsPacketCapt... | from desktop_local_tests.local_packet_capture_test_case_with_disrupter import LocalPacketCaptureTestCaseWithDisrupter
from desktop_local_tests.windows.windows_dns_force_public_dns_servers_disrupter import WindowsDNSForcePublicDNSServersDisrupter
class TestWindowsPacketCaptureDisruptForcePublicDNSServers(LocalPacketCap... | en | 0.637774 | # TODO: Make the packet capture here DNS specific? | 1.765371 | 2 |
kivy/loader.py | geojeff/kivy | 1 | 3511 | '''
Asynchronous data loader
========================
This is the Asynchronous Loader. You can use it to load an image
and use it, even if data are not yet available. You must specify a default
loading image for using a such loader::
from kivy import *
image = Loader.image('mysprite.png')
You can also load i... | '''
Asynchronous data loader
========================
This is the Asynchronous Loader. You can use it to load an image
and use it, even if data are not yet available. You must specify a default
loading image for using a such loader::
from kivy import *
image = Loader.image('mysprite.png')
You can also load i... | en | 0.790929 | Asynchronous data loader ======================== This is the Asynchronous Loader. You can use it to load an image and use it, even if data are not yet available. You must specify a default loading image for using a such loader:: from kivy import * image = Loader.image('mysprite.png') You can also load image... | 3.508637 | 4 |
Season 01 - Intro to Python/Episode 13 - Join.py | Pythobit/Python-tutorial | 3 | 3512 | # 13. Join
# it allows to print list a bit better
friends = ['Pythobit','boy','Pythoman']
print(f'My friends are {friends}.') # Output - My friends are ['Pythobit', 'boy', 'Pythoman'].
# So, the Output needs to be a bit clearer.
friends = ['Pythobit','boy','Pythoman']
friend = ', '.join(friends)
print(f'My friend... | # 13. Join
# it allows to print list a bit better
friends = ['Pythobit','boy','Pythoman']
print(f'My friends are {friends}.') # Output - My friends are ['Pythobit', 'boy', 'Pythoman'].
# So, the Output needs to be a bit clearer.
friends = ['Pythobit','boy','Pythoman']
friend = ', '.join(friends)
print(f'My friend... | en | 0.829704 | # 13. Join # it allows to print list a bit better # Output - My friends are ['Pythobit', 'boy', 'Pythoman']. # So, the Output needs to be a bit clearer. # Output - My friends are Pythobit, boy, Pythoman # Here (, ) comma n space is used as separator, but you can use anything. | 4.237928 | 4 |
buildsettings.py | randomizax/polygon-label | 0 | 3513 | # settings file for builds.
# if you want to have custom builds, copy this file to "localbuildsettings.py" and make changes there.
# possible fields:
# resourceBaseUrl - optional - the URL base for external resources (all resources embedded in standard IITC)
# distUrlBase - optional - the base URL to use for update c... | # settings file for builds.
# if you want to have custom builds, copy this file to "localbuildsettings.py" and make changes there.
# possible fields:
# resourceBaseUrl - optional - the URL base for external resources (all resources embedded in standard IITC)
# distUrlBase - optional - the base URL to use for update c... | en | 0.791427 | # settings file for builds. # if you want to have custom builds, copy this file to "localbuildsettings.py" and make changes there. # possible fields: # resourceBaseUrl - optional - the URL base for external resources (all resources embedded in standard IITC) # distUrlBase - optional - the base URL to use for update che... | 1.873101 | 2 |
osaka/storage/sftp.py | riverma/osaka | 2 | 3514 | <filename>osaka/storage/sftp.py
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from __future__ import absolute_import
from builtins import int
from future import standard_library
standard_library.install_aliases()
import os
import os.path
import stat
imp... | <filename>osaka/storage/sftp.py
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from __future__ import absolute_import
from builtins import int
from future import standard_library
standard_library.install_aliases()
import os
import os.path
import stat
imp... | en | 0.757462 | A backend used to handle stfp using parimiko @author starchmd SFTP handling for Osaka Constructor Connect to this storage medium. All data is parsed out of the url and may be None scheme: @param host - may be None, host to connect to implementor must handle defaulting ... | 2.717888 | 3 |
thesis/pettingzoo/butterfly/cooperative_pong/cake_paddle.py | heavenlysf/thesis | 0 | 3515 | import os
os.environ["PYGAME_HIDE_SUPPORT_PROMPT"] = "hide"
import pygame
RENDER_RATIO = 2
class CakePaddle(pygame.sprite.Sprite):
def __init__(self, speed=12):
# surf is the right-most (largest) tier of the cake
self.surf = pygame.Surface((30 // RENDER_RATIO, 120 // RENDER_RATIO))
self.... | import os
os.environ["PYGAME_HIDE_SUPPORT_PROMPT"] = "hide"
import pygame
RENDER_RATIO = 2
class CakePaddle(pygame.sprite.Sprite):
def __init__(self, speed=12):
# surf is the right-most (largest) tier of the cake
self.surf = pygame.Surface((30 // RENDER_RATIO, 120 // RENDER_RATIO))
self.... | en | 0.556213 | # surf is the right-most (largest) tier of the cake # self.rect is set from envs class # action: 1 - up, 2 - down # move other rects too Parameters ---------- b_rect : Ball rect dx, dy : Ball speed along single axis b_speed : Ball speed ignore paddle type Returns ... | 3.023581 | 3 |
src/internal_representation_analysis/decoder/StateDataset.py | aidkilda/understanding-drl-navigation | 0 | 3516 | <filename>src/internal_representation_analysis/decoder/StateDataset.py
import random
from internal_representation_analysis.network import ActorCriticFFNetwork
from internal_representation_analysis.scene_loader import THORDiscreteEnvironment as Environment
from internal_representation_analysis.constants import MINI_BA... | <filename>src/internal_representation_analysis/decoder/StateDataset.py
import random
from internal_representation_analysis.network import ActorCriticFFNetwork
from internal_representation_analysis.scene_loader import THORDiscreteEnvironment as Environment
from internal_representation_analysis.constants import MINI_BA... | none | 1 | 2.261403 | 2 | |
test_dataset_model.py | ferrine/PerceptualSimilarity | 0 | 3517 | <filename>test_dataset_model.py
import numpy as np
from models import dist_model as dm
from data import data_loader as dl
import argparse
from IPython import embed
parser = argparse.ArgumentParser()
parser.add_argument("--dataset_mode", type=str, default="2afc", help="[2afc,jnd]")
parser.add_argument(
"--datasets"... | <filename>test_dataset_model.py
import numpy as np
from models import dist_model as dm
from data import data_loader as dl
import argparse
from IPython import embed
parser = argparse.ArgumentParser()
parser.add_argument("--dataset_mode", type=str, default="2afc", help="[2afc,jnd]")
parser.add_argument(
"--datasets"... | en | 0.376213 | # initialize model # model.initialize(model=opt.model,net=opt.net,colorspace=opt.colorspace,model_path=opt.model_path,use_gpu=opt.use_gpu) # embed() # initialize data loader # evaluate model on data # print results | 2.223431 | 2 |
plotter.py | StrangeTcy/pathnet-pytorch | 86 | 3518 | import argparse
import os
import pickle
import numpy as np
import matplotlib.pyplot as plt
plt.style.use('ggplot')
parser = argparse.ArgumentParser(description='PyTorch MNIST Example')
parser.add_argument('--mnist', action='store_true', default=False,
help='open mnist result')
args = parser.parse_a... | import argparse
import os
import pickle
import numpy as np
import matplotlib.pyplot as plt
plt.style.use('ggplot')
parser = argparse.ArgumentParser(description='PyTorch MNIST Example')
parser.add_argument('--mnist', action='store_true', default=False,
help='open mnist result')
args = parser.parse_a... | none | 1 | 2.667265 | 3 | |
kindler/solver/optimizer.py | mingruimingrui/kindler | 0 | 3519 | <reponame>mingruimingrui/kindler
import torch
def make_sgd_optimizer(
model,
base_lr=0.001,
bias_lr_factor=2.0,
momentum=0.9,
weight_decay=0.0005,
weight_decay_bias=0.0,
):
params = []
for key, value in model.named_parameters():
if not value.requires_grad:
continue
... | import torch
def make_sgd_optimizer(
model,
base_lr=0.001,
bias_lr_factor=2.0,
momentum=0.9,
weight_decay=0.0005,
weight_decay_bias=0.0,
):
params = []
for key, value in model.named_parameters():
if not value.requires_grad:
continue
param_lr = base_lr
... | none | 1 | 2.485523 | 2 | |
platypus/tests/test_operators.py | sctiwari/EZFF_ASE | 2 | 3520 | <gh_stars>1-10
# Copyright 2015-2018 <NAME>
#
# This file is part of Platypus, a Python module for designing and using
# evolutionary algorithms (EAs) and multiobjective evolutionary algorithms
# (MOEAs).
#
# Platypus is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public... | # Copyright 2015-2018 <NAME>
#
# This file is part of Platypus, a Python module for designing and using
# evolutionary algorithms (EAs) and multiobjective evolutionary algorithms
# (MOEAs).
#
# Platypus is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as pub... | en | 0.838573 | # Copyright 2015-2018 <NAME> # # This file is part of Platypus, a Python module for designing and using # evolutionary algorithms (EAs) and multiobjective evolutionary algorithms # (MOEAs). # # Platypus is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as pub... | 2.774652 | 3 |
fusion_net/bilinear_sampler.py | ClovisChen/LearningCNN | 0 | 3521 | <gh_stars>0
#!/usr/bin/env python
# -*- coding: utf-8 -*-are not covered by the UCLB ACP-A Licence,
from __future__ import absolute_import, division, print_function
import tensorflow as tf
def bilinear_sampler_1d_h(input_images, x_offset, wrap_mode='border', name='bilinear_sampler', **kwargs):
'''
一维双线性采样: x_... | #!/usr/bin/env python
# -*- coding: utf-8 -*-are not covered by the UCLB ACP-A Licence,
from __future__ import absolute_import, division, print_function
import tensorflow as tf
def bilinear_sampler_1d_h(input_images, x_offset, wrap_mode='border', name='bilinear_sampler', **kwargs):
'''
一维双线性采样: x_offset--输入X上... | zh | 0.214569 | #!/usr/bin/env python # -*- coding: utf-8 -*-are not covered by the UCLB ACP-A Licence, 一维双线性采样: x_offset--输入X上偏移量的图 重复函数 : 先将一维的x后面扩展一个维度, 然后在扩展的维度上复制相应的值, 随后将其转成一维的值, exsamples:[1,2,3] --> [1,1,2,2,3,3] #插值函数 # handle both texture border types # 如果包围方式是border, 那么边界长度是1, 在h和w维两侧加一排0 # 修剪偏移量x, 让它在0到width-1+2*edge_s... | 2.069165 | 2 |
Supernovae.py | adamamiller/iptf16hvw-1 | 0 | 3522 | <filename>Supernovae.py
#import relevant libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from astropy.io import ascii
import json
from IPython.display import display, Image
from specutils import Spectrum1D
from astropy import units
from scipy.optimize import curve_fit
from scipy.interpo... | <filename>Supernovae.py
#import relevant libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from astropy.io import ascii
import json
from IPython.display import display, Image
from specutils import Spectrum1D
from astropy import units
from scipy.optimize import curve_fit
from scipy.interpo... | en | 0.667103 | #import relevant libraries #speed of light (km/s) #Define class to hold releveant information for spectra data #Initialization function Spectra (string) - path to JSON formatted spectra file epoch (float) - MJD date z (float) - redshift of corresponding SN MJD_max (float) - date of B band maximu... | 2.765696 | 3 |
userbot/plugins/alive.py | iraqis1/irqis | 0 | 3523 | """Check if userbot alive. If you change these, you become the gayest gay such that even the gay world will disown you."""
import asyncio
from telethon import events
from telethon.tl.types import ChannelParticipantsAdmins
from platform import uname
from userbot import ALIVE_NAME
from userbot.utils import admin_cm... | """Check if userbot alive. If you change these, you become the gayest gay such that even the gay world will disown you."""
import asyncio
from telethon import events
from telethon.tl.types import ChannelParticipantsAdmins
from platform import uname
from userbot import ALIVE_NAME
from userbot.utils import admin_cm... | en | 0.874974 | Check if userbot alive. If you change these, you become the gayest gay such that even the gay world will disown you. For .alive command, check if the bot is running. | 2.636775 | 3 |
connector/ADBConnector.py | qiutongxue/ArknightsAutoHelper | 1 | 3524 | import os
import logging.config
from random import randint
import zlib
import struct
import socket
import time
from PIL import Image
import config
# from config import ADB_ROOT, ADB_HOST, SCREEN_SHOOT_SAVE_PATH, ShellColor, CONFIG_PATH,enable_adb_host_auto_detect, ADB_SERVER
from .ADBClientSession import ADBClientSes... | import os
import logging.config
from random import randint
import zlib
import struct
import socket
import time
from PIL import Image
import config
# from config import ADB_ROOT, ADB_HOST, SCREEN_SHOOT_SAVE_PATH, ShellColor, CONFIG_PATH,enable_adb_host_auto_detect, ADB_SERVER
from .ADBClientSession import ADBClientSes... | en | 0.318389 | # from config import ADB_ROOT, ADB_HOST, SCREEN_SHOOT_SAVE_PATH, ShellColor, CONFIG_PATH,enable_adb_host_auto_detect, ADB_SERVER # from numpy import average, dot, linalg # os.chdir(ADB_ROOT) returns PNG bytes returns (width, height, pixels) pixels in RGBA/RGBX format returns (width, height, pixels) pixe... | 2.13229 | 2 |
redshift_upload/base_utilities.py | douglassimonsen/redshift_upload | 0 | 3525 | import inspect
import os
from pathlib import Path
class change_directory:
"""
A class for changing the working directory using a "with" statement.
It takes the directory to change to as an argument. If no directory is given,
it takes the directory of the file from which this function was call... | import inspect
import os
from pathlib import Path
class change_directory:
"""
A class for changing the working directory using a "with" statement.
It takes the directory to change to as an argument. If no directory is given,
it takes the directory of the file from which this function was call... | en | 0.930473 | A class for changing the working directory using a "with" statement.
It takes the directory to change to as an argument. If no directory is given,
it takes the directory of the file from which this function was called. # type: ignore | 3.6835 | 4 |
main.py | Gloriel621/MgallManager | 9 | 3526 | import sys
from PyQt5.QtWidgets import QApplication
from gui import MgallManager
def main():
app = QApplication(sys.argv)
ex = MgallManager()
app.aboutToQuit.connect(ex.ExitHandler)
sys.exit(app.exec_())
if __name__ == "__main__":
main()
| import sys
from PyQt5.QtWidgets import QApplication
from gui import MgallManager
def main():
app = QApplication(sys.argv)
ex = MgallManager()
app.aboutToQuit.connect(ex.ExitHandler)
sys.exit(app.exec_())
if __name__ == "__main__":
main()
| none | 1 | 2.39096 | 2 | |
utils/src/adventofcode/utils/Point3D.py | dh256/adventofcode | 0 | 3527 | <gh_stars>0
class Point3D:
def __init__(self,x,y,z):
self.x = x
self.y = y
self.z = z
'''
Returns the distance between two 3D points
'''
def distance(self, value):
return abs(self.x - value.x) + abs(self.y - value.y) + abs(self.z - value.z)
def __eq__(self, valu... | class Point3D:
def __init__(self,x,y,z):
self.x = x
self.y = y
self.z = z
'''
Returns the distance between two 3D points
'''
def distance(self, value):
return abs(self.x - value.x) + abs(self.y - value.y) + abs(self.z - value.z)
def __eq__(self, value):
... | en | 0.927241 | Returns the distance between two 3D points | 3.875045 | 4 |
pysc2/lib/actions.py | javierrcc522/starcraft2_api_machineLear | 2 | 3528 | <filename>pysc2/lib/actions.py
# Copyright 2017 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... | <filename>pysc2/lib/actions.py
# Copyright 2017 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... | en | 0.812354 | # Copyright 2017 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 by applicable law or ... | 2.113762 | 2 |
pywick/meters/aucmeter.py | ashishpatel26/pywick | 2 | 3529 | <reponame>ashishpatel26/pywick
import numbers
from . import meter
import numpy as np
import torch
class AUCMeter(meter.Meter):
"""
The AUCMeter measures the area under the receiver-operating characteristic
(ROC) curve for binary classification problems. The area under the curve (AUC)
can be interprete... | import numbers
from . import meter
import numpy as np
import torch
class AUCMeter(meter.Meter):
"""
The AUCMeter measures the area under the receiver-operating characteristic
(ROC) curve for binary classification problems. The area under the curve (AUC)
can be interpreted as the probability that, give... | en | 0.864636 | The AUCMeter measures the area under the receiver-operating characteristic (ROC) curve for binary classification problems. The area under the curve (AUC) can be interpreted as the probability that, given a randomly selected positive example and a randomly selected negative example, the positive example is ... | 3.367991 | 3 |
homeassistant/components/zha/core/channels/lighting.py | liangleslie/core | 30,023 | 3530 | """Lighting channels module for Zigbee Home Automation."""
from __future__ import annotations
from contextlib import suppress
from zigpy.zcl.clusters import lighting
from .. import registries
from ..const import REPORT_CONFIG_DEFAULT
from .base import ClientChannel, ZigbeeChannel
@registries.ZIGBEE_CHANNEL_REGISTR... | """Lighting channels module for Zigbee Home Automation."""
from __future__ import annotations
from contextlib import suppress
from zigpy.zcl.clusters import lighting
from .. import registries
from ..const import REPORT_CONFIG_DEFAULT
from .base import ClientChannel, ZigbeeChannel
@registries.ZIGBEE_CHANNEL_REGISTR... | en | 0.718006 | Lighting channels module for Zigbee Home Automation. Ballast channel. Color client channel. Color channel. Return color capabilities of the light. Return cached value of the color_mode attribute. Return cached value of the color_loop_active attribute. Return cached value of color temperature. Return cached value of the... | 2.1547 | 2 |
pf/queue.py | PiRAT4/py-pf | 0 | 3531 | """Classes to represent Packet Filter's queueing schedulers and statistics."""
import pf._struct
from pf._base import PFObject
from pf.constants import *
from pf._utils import rate2str
__all__ = ["ServiceCurve",
"FlowQueue",
"PFQueue",
"PFQueueStats"]
class ServiceCurve(PFObject):
... | """Classes to represent Packet Filter's queueing schedulers and statistics."""
import pf._struct
from pf._base import PFObject
from pf.constants import *
from pf._utils import rate2str
__all__ = ["ServiceCurve",
"FlowQueue",
"PFQueue",
"PFQueueStats"]
class ServiceCurve(PFObject):
... | en | 0.822318 | Classes to represent Packet Filter's queueing schedulers and statistics. | 2.66665 | 3 |
sdk/python/pulumi_azure_native/labservices/v20181015/__init__.py | pulumi-bot/pulumi-azure-native | 0 | 3532 | # coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
# Export this package's modules as members:
from ._enums import *
from .environment import *
from .environment_setting import *
from .gallery_image imp... | # coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
# Export this package's modules as members:
from ._enums import *
from .environment import *
from .environment_setting import *
from .gallery_image imp... | en | 0.955671 | # coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** # Export this package's modules as members: | 1.570436 | 2 |
servicedirectory/src/sd-api/users/tests/tests_serializers.py | ealogar/servicedirectory | 0 | 3533 | '''
(c) Copyright 2013 Telefonica, I+D. Printed in Spain (Europe). All Rights
Reserved.
The copyright to the software program(s) is property of Telefonica I+D.
The program(s) may be used and or copied only with the express written
consent of Telefonica I+D or in accordance with the terms and conditions
stipulated in t... | '''
(c) Copyright 2013 Telefonica, I+D. Printed in Spain (Europe). All Rights
Reserved.
The copyright to the software program(s) is property of Telefonica I+D.
The program(s) may be used and or copied only with the express written
consent of Telefonica I+D or in accordance with the terms and conditions
stipulated in t... | en | 0.879511 | (c) Copyright 2013 Telefonica, I+D. Printed in Spain (Europe). All Rights Reserved. The copyright to the software program(s) is property of Telefonica I+D. The program(s) may be used and or copied only with the express written consent of Telefonica I+D or in accordance with the terms and conditions stipulated in the a... | 1.981538 | 2 |
Web/notifyXAPI/app/src/users/views.py | abs0lut3pwn4g3/RootersCTF2019-challenges | 14 | 3534 | ''' User views '''
from datetime import timedelta
from flask import request, jsonify, make_response, redirect, json, render_template
from flask_jwt_extended import (create_access_token, jwt_required)
from flask_restful import Resource
from flask_login import login_user, current_user
from sqlalchemy.exc import Integrit... | ''' User views '''
from datetime import timedelta
from flask import request, jsonify, make_response, redirect, json, render_template
from flask_jwt_extended import (create_access_token, jwt_required)
from flask_restful import Resource
from flask_login import login_user, current_user
from sqlalchemy.exc import Integrit... | en | 0.884088 | User views | 2.522884 | 3 |
querybuilder/tests/window_tests.py | wesokes/django-query-builder | 110 | 3535 | <reponame>wesokes/django-query-builder<filename>querybuilder/tests/window_tests.py<gh_stars>100-1000
from querybuilder.fields import (
RankField, RowNumberField, DenseRankField, PercentRankField, CumeDistField, NTileField, LagField,
LeadField, FirstValueField, LastValueField, NthValueField, NumStdDevField
)
fro... | from querybuilder.fields import (
RankField, RowNumberField, DenseRankField, PercentRankField, CumeDistField, NTileField, LagField,
LeadField, FirstValueField, LastValueField, NthValueField, NumStdDevField
)
from querybuilder.query import QueryWindow, Query
from querybuilder.tests.models import Order
from query... | none | 1 | 2.279145 | 2 | |
emoji/coffee.py | wbprice/ojimoji | 0 | 3536 | <reponame>wbprice/ojimoji
import numpy
h = .25
s = 1
bitmap = numpy.array([
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,1,1,1,1,1,1,1,1,1,0,0,0,0,0],
[0,0,1,1,1,1,1,1,1,1,1,1,1,1,0,0],
[0,0,1,1,1,0,1,0,1,1,1,0,0,1,0,0],
[0,0,... | import numpy
h = .25
s = 1
bitmap = numpy.array([
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,1,1,1,1,1,1,1,1,1,0,0,0,0,0],
[0,0,1,1,1,1,1,1,1,1,1,1,1,1,0,0],
[0,0,1,1,1,0,1,0,1,1,1,0,0,1,0,0],
[0,0,1,1,0,1,0,1,0,1,1,0,0,1,0,... | none | 1 | 2.71848 | 3 | |
dumpcode/npzbdt.py | gkfthddk/keras | 0 | 3537 | import numpy as np
from sklearn.model_selection import RandomizedSearchCV, GridSearchCV
from sklearn.metrics import roc_auc_score
from sklearn.model_selection import StratifiedKFold
from sklearn.model_selection import KFold
import scipy.stats as sts
import xgboost as xgb
from xiter import *
import pandas as pd
import a... | import numpy as np
from sklearn.model_selection import RandomizedSearchCV, GridSearchCV
from sklearn.metrics import roc_auc_score
from sklearn.model_selection import StratifiedKFold
from sklearn.model_selection import KFold
import scipy.stats as sts
import xgboost as xgb
from xiter import *
import pandas as pd
import a... | en | 0.246138 | #skf = StratifiedKFold(n_splits=folds, shuffle = True, random_state = 1001) # Here we go # timing starts from this point for "start_time" variable #print(random_search.predict(X[:10])) #print('\n All results:') #print(random_search.cv_results_) #print('\n Best estimator:') #print(random_search.best_estimator_) #print('... | 2.08914 | 2 |
rlenv/StockTradingEnv0.py | watchsea/RL-Stock | 0 | 3538 | import random
import json
import gym
from gym import spaces
import pandas as pd
import numpy as np
MAX_ACCOUNT_BALANCE = 2147483647
MAX_NUM_SHARES = 2147483647
MAX_SHARE_PRICE = 5000
MAX_VOLUME = 1000e8
MAX_AMOUNT = 3e10
MAX_OPEN_POSITIONS = 5
MAX_STEPS = 20000
MAX_DAY_CHANGE = 1
INITIAL_ACCOUNT_BALANCE = 10000
DATA... | import random
import json
import gym
from gym import spaces
import pandas as pd
import numpy as np
MAX_ACCOUNT_BALANCE = 2147483647
MAX_NUM_SHARES = 2147483647
MAX_SHARE_PRICE = 5000
MAX_VOLUME = 1000e8
MAX_AMOUNT = 3e10
MAX_OPEN_POSITIONS = 5
MAX_STEPS = 20000
MAX_DAY_CHANGE = 1
INITIAL_ACCOUNT_BALANCE = 10000
DATA... | en | 0.782757 | # position constant # no position # buy position # sell position # action constant A stock trading environment for OpenAI gym # show the trade info # brokage commission # Actions of the format Buy x%, Sell x%, Hold, etc. # self.action_space = spaces.Box( # low=np.array([0, 0]), high=np.array([3, 1]), dtype=np.flo... | 2.887733 | 3 |
processing/manager.py | mrfleap/us-population-heatmap | 0 | 3539 | import json
import os
import pathlib
import time
from tqdm import tqdm
from aggregator import aggregate
from download import DOWNLOAD_PATH, download_files, unzip_files
from tqdm.contrib.concurrent import process_map
def main():
start = time.time()
# print("Downloading files...")
# download_files()
#... | import json
import os
import pathlib
import time
from tqdm import tqdm
from aggregator import aggregate
from download import DOWNLOAD_PATH, download_files, unzip_files
from tqdm.contrib.concurrent import process_map
def main():
start = time.time()
# print("Downloading files...")
# download_files()
#... | en | 0.335999 | # print("Downloading files...") # download_files() # print("Unzipping shapefiles...") # unzip_files() # print("Computing population JSON heatmaps...") # compute_json_heatmaps(state_ids) {"type": "FeatureCollection", "features": [ # state_ids = state_ids[:2] | 2.466993 | 2 |
gen_data.py | kshoji6011/vehicleai | 0 | 3540 | from PIL import Image
import os, glob
import numpy as np
from sklearn import model_selection
classes = ["car", "bycycle", "motorcycle", "pedestrian"]
num_class = len(classes)
image_size = 50
# 画像の読み込み
X = []
Y = []
for index, classlabel in enumerate(classes):
photos_dir = "./" + classlabel
files = glob.glob... | from PIL import Image
import os, glob
import numpy as np
from sklearn import model_selection
classes = ["car", "bycycle", "motorcycle", "pedestrian"]
num_class = len(classes)
image_size = 50
# 画像の読み込み
X = []
Y = []
for index, classlabel in enumerate(classes):
photos_dir = "./" + classlabel
files = glob.glob... | none | 1 | 2.961784 | 3 | |
app/main.py | immortel32/Sword_Sorcery_Story_Generator | 2 | 3541 | <reponame>immortel32/Sword_Sorcery_Story_Generator
from services import waypoint_scenarios, quest_scenarios
from services.build_campaign import Campaign
from log_setup import log
if __name__ == "__main__":
number_waypoint_scenario = waypoint_scenarios.get_number_of_waypoint_scenarios()
log.info(f"We have {numb... | from services import waypoint_scenarios, quest_scenarios
from services.build_campaign import Campaign
from log_setup import log
if __name__ == "__main__":
number_waypoint_scenario = waypoint_scenarios.get_number_of_waypoint_scenarios()
log.info(f"We have {number_waypoint_scenario} waypoint available")
numb... | none | 1 | 2.011658 | 2 | |
tests/test-recipes/metadata/ignore_some_prefix_files/run_test.py | mbargull/conda-build | 0 | 3542 | <filename>tests/test-recipes/metadata/ignore_some_prefix_files/run_test.py
import os
pkgs = os.path.join(os.environ["ROOT"], "pkgs")
info_dir = os.path.join(pkgs, "conda-build-test-ignore-some-prefix-files-1.0-0", "info")
has_prefix_file = os.path.join(info_dir, "has_prefix")
print(info_dir)
assert os.path.isfile(has_... | <filename>tests/test-recipes/metadata/ignore_some_prefix_files/run_test.py
import os
pkgs = os.path.join(os.environ["ROOT"], "pkgs")
info_dir = os.path.join(pkgs, "conda-build-test-ignore-some-prefix-files-1.0-0", "info")
has_prefix_file = os.path.join(info_dir, "has_prefix")
print(info_dir)
assert os.path.isfile(has_... | none | 1 | 2.535012 | 3 | |
distill.py | Lukeming-tsinghua/Interpretable-NN-for-IBD-diagnosis | 0 | 3543 | <filename>distill.py
import os
from collections import namedtuple
import torch
import torch.nn as nn
import torch.nn.functional as F
from sklearn.metrics import classification_report
from torch.optim import Adam
from tqdm import tqdm
from data import DataIteratorDistill
from loss import FocalLoss
from model import CN... | <filename>distill.py
import os
from collections import namedtuple
import torch
import torch.nn as nn
import torch.nn.functional as F
from sklearn.metrics import classification_report
from torch.optim import Adam
from tqdm import tqdm
from data import DataIteratorDistill
from loss import FocalLoss
from model import CN... | en | 0.396667 | #print(loss_f.item(), loss_kv.item()) | 2.346733 | 2 |
tests/TALTests/HTMLTests/TALAttributesTestCases.py | janbrohl/SimpleTAL | 5 | 3544 | #!/usr/bin/python
# -*- coding: iso-8859-1 -*-
# Copyright (c) 2016, <NAME> <<EMAIL>>
# All rights reserved.
# See LICENSE.txt
# Copyright (c) 2004 <NAME> (http://www.owlfish.com/)
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are pe... | #!/usr/bin/python
# -*- coding: iso-8859-1 -*-
# Copyright (c) 2016, <NAME> <<EMAIL>>
# All rights reserved.
# See LICENSE.txt
# Copyright (c) 2004 <NAME> (http://www.owlfish.com/)
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are pe... | en | 0.625088 | #!/usr/bin/python # -*- coding: iso-8859-1 -*- # Copyright (c) 2016, <NAME> <<EMAIL>> # All rights reserved. # See LICENSE.txt # Copyright (c) 2004 <NAME> (http://www.owlfish.com/) # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are perm... | 1.518482 | 2 |
iseq_prof/fasta.py | EBI-Metagenomics/iseq-prof | 0 | 3545 | from pathlib import Path
from typing import List
from fasta_reader import FASTAItem, FASTAWriter, read_fasta
__all__ = ["downsample"]
def downsample(infile: Path, outfile: Path, size: int, random):
targets: List[FASTAItem] = list(read_fasta(infile))
if size > len(targets):
raise ValueError("Size is ... | from pathlib import Path
from typing import List
from fasta_reader import FASTAItem, FASTAWriter, read_fasta
__all__ = ["downsample"]
def downsample(infile: Path, outfile: Path, size: int, random):
targets: List[FASTAItem] = list(read_fasta(infile))
if size > len(targets):
raise ValueError("Size is ... | none | 1 | 3.274956 | 3 | |
src/data_settings.py | DhruvSrikanth/TSLA-React | 0 | 3546 | # API keys
# YF_API_KEY = "<KEY>" # yahoo finance api key
TICKER = "TSLA"
INTERVAL = "1m"
PERIOD = "1d"
LOOK_BACK = 30 # hard limit to not reach rate limit of 100 per day | # API keys
# YF_API_KEY = "<KEY>" # yahoo finance api key
TICKER = "TSLA"
INTERVAL = "1m"
PERIOD = "1d"
LOOK_BACK = 30 # hard limit to not reach rate limit of 100 per day | en | 0.571924 | # API keys # YF_API_KEY = "<KEY>" # yahoo finance api key # hard limit to not reach rate limit of 100 per day | 1.441632 | 1 |
ymir/backend/src/ymir_controller/controller/utils/invoker_mapping.py | phoenix-xhuang/ymir | 64 | 3547 | from controller.invoker import (
invoker_cmd_branch_checkout,
invoker_cmd_branch_commit,
invoker_cmd_branch_create,
invoker_cmd_branch_delete,
invoker_cmd_branch_list,
invoker_cmd_evaluate,
invoker_cmd_filter,
invoker_cmd_gpu_info,
invoker_cmd_inference,
invoker_cmd_init,
inv... | from controller.invoker import (
invoker_cmd_branch_checkout,
invoker_cmd_branch_commit,
invoker_cmd_branch_create,
invoker_cmd_branch_delete,
invoker_cmd_branch_list,
invoker_cmd_evaluate,
invoker_cmd_filter,
invoker_cmd_gpu_info,
invoker_cmd_inference,
invoker_cmd_init,
inv... | none | 1 | 1.546168 | 2 | |
tests/utils/date_utils.py | asuol/worky | 0 | 3548 | <filename>tests/utils/date_utils.py
from datetime import datetime, timedelta
due_date_format = '%Y-%m-%d'
datepicker_date_format = '%m%d%Y'
def current_date():
return datetime.utcnow().strftime(due_date_format)
def datepicker_current_date():
return datetime.utcnow().strftime(datepicker_date_format)
def ... | <filename>tests/utils/date_utils.py
from datetime import datetime, timedelta
due_date_format = '%Y-%m-%d'
datepicker_date_format = '%m%d%Y'
def current_date():
return datetime.utcnow().strftime(due_date_format)
def datepicker_current_date():
return datetime.utcnow().strftime(datepicker_date_format)
def ... | none | 1 | 2.677532 | 3 | |
numba/roc/tests/hsapy/test_gufuncbuilding.py | luk-f-a/numba | 76 | 3549 | <reponame>luk-f-a/numba
import numpy as np
from numba.roc.vectorizers import HsaGUFuncVectorize
from numba.roc.dispatch import HSAGenerializedUFunc
from numba import guvectorize
import unittest
def ufunc_add_core(a, b, c):
for i in range(c.size):
c[i] = a[i] + b[i]
class TestGUFuncBuilding(unittest.Tes... | import numpy as np
from numba.roc.vectorizers import HsaGUFuncVectorize
from numba.roc.dispatch import HSAGenerializedUFunc
from numba import guvectorize
import unittest
def ufunc_add_core(a, b, c):
for i in range(c.size):
c[i] = a[i] + b[i]
class TestGUFuncBuilding(unittest.TestCase):
def test_guf... | en | 0.54126 | # Test integer version # Test integer version with 2D inputs # Test integer version with 3D inputs # Test real version # Test real version with 2D inputs | 2.398551 | 2 |
server/form/mongo.py | SRM-IST-KTR/ossmosis | 6 | 3550 | import os
from pymongo import MongoClient
from dotenv import load_dotenv
def database_entry(data):
try:
load_dotenv()
mongo_string = os.getenv('MONGODB_AUTH_URI')
client = MongoClient(mongo_string)
database = client[os.getenv('MONGODB_DB')]
col = database['users']
c... | import os
from pymongo import MongoClient
from dotenv import load_dotenv
def database_entry(data):
try:
load_dotenv()
mongo_string = os.getenv('MONGODB_AUTH_URI')
client = MongoClient(mongo_string)
database = client[os.getenv('MONGODB_DB')]
col = database['users']
c... | none | 1 | 2.333981 | 2 | |
control-flow/solution/file_hosts.py | giserh/book-python | 1 | 3551 | FILE = r'../src/etc-hosts.txt'
hostnames = []
try:
with open(FILE, encoding='utf-8') as file:
content = file.readlines()
except FileNotFoundError:
print('File does not exist')
except PermissionError:
print('Permission denied')
for line in content:
if line.startswith('#'):
continue
... | FILE = r'../src/etc-hosts.txt'
hostnames = []
try:
with open(FILE, encoding='utf-8') as file:
content = file.readlines()
except FileNotFoundError:
print('File does not exist')
except PermissionError:
print('Permission denied')
for line in content:
if line.startswith('#'):
continue
... | none | 1 | 3.056287 | 3 | |
zindi/docs/utils/n_subimissions_per_day.py | eaedk/testing-zindi-package | 6 | 3552 | def n_subimissions_per_day( url, headers ):
"""Get the number of submissions we can make per day for the selected challenge.
Parameters
----------
url : {'prize', 'points', 'knowledge' , 'all'}, default='all'
The reward of the challenges for top challengers.
headers : dictionary ,
T... | def n_subimissions_per_day( url, headers ):
"""Get the number of submissions we can make per day for the selected challenge.
Parameters
----------
url : {'prize', 'points', 'knowledge' , 'all'}, default='all'
The reward of the challenges for top challengers.
headers : dictionary ,
T... | en | 0.632167 | Get the number of submissions we can make per day for the selected challenge. Parameters ---------- url : {'prize', 'points', 'knowledge' , 'all'}, default='all' The reward of the challenges for top challengers. headers : dictionary , The headers of the request. Returns ------- ... | 3.279548 | 3 |
algo/test/test_maximum_cut.py | ssavinash1/Algorithm_stanford | 24 | 3553 | # -*- coding: utf-8 -*-
import unittest
from src.graph import Graph
from src.maximum_cut import maximum_cut, maximum_cut_for_bipartite_graph
class MaximumCut(unittest.TestCase):
def test_maximum_cut_for_bipartite_graphs(self):
""" Given the following bipartite graph.
(a)-----(b)
... | # -*- coding: utf-8 -*-
import unittest
from src.graph import Graph
from src.maximum_cut import maximum_cut, maximum_cut_for_bipartite_graph
class MaximumCut(unittest.TestCase):
def test_maximum_cut_for_bipartite_graphs(self):
""" Given the following bipartite graph.
(a)-----(b)
... | en | 0.612526 | # -*- coding: utf-8 -*- Given the following bipartite graph. (a)-----(b) \ \----(c) (d)-----(e) / (f)----/ \ \----(g) A sligthly larger graph: (a) (c) | \ /| | x | | ... | 3.657941 | 4 |
gdb/print-avs-rbtree.py | kemonats/avs_commons | 4 | 3554 | <filename>gdb/print-avs-rbtree.py
# -*- coding: utf-8 -*-
#
# Copyright 2021 AVSystem <<EMAIL>>
#
# 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-... | <filename>gdb/print-avs-rbtree.py
# -*- coding: utf-8 -*-
#
# Copyright 2021 AVSystem <<EMAIL>>
#
# 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-... | en | 0.814398 | # -*- coding: utf-8 -*- # # Copyright 2021 AVSystem <<EMAIL>> # # 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 applica... | 2.336662 | 2 |
hour17/PythonGroup.py | sampx/mongodb-practice | 0 | 3555 | from pymongo import MongoClient
def displayGroup(results):
for result in results:
print (result)
def firstIsALastIsVowel(collection):
key = {'first' : True, "last" : True}
cond = {'first' : 'a', 'last' :
{'$in' : ["a","e","i","o","u"]}}
initial = {'count' : 0}
red... | from pymongo import MongoClient
def displayGroup(results):
for result in results:
print (result)
def firstIsALastIsVowel(collection):
key = {'first' : True, "last" : True}
cond = {'first' : 'a', 'last' :
{'$in' : ["a","e","i","o","u"]}}
initial = {'count' : 0}
red... | none | 1 | 3.139892 | 3 | |
packnet_sfm/models/model_utils.py | pection/packnet-sfm | 1 | 3556 | # Copyright 2020 Toyota Research Institute. All rights reserved.
from packnet_sfm.utils.image import flip_lr, interpolate_scales
from packnet_sfm.utils.misc import filter_dict
from packnet_sfm.utils.types import is_tensor, is_list, is_numpy
def flip(tensor, flip_fn):
"""
Flip tensors or list of tensors base... | # Copyright 2020 Toyota Research Institute. All rights reserved.
from packnet_sfm.utils.image import flip_lr, interpolate_scales
from packnet_sfm.utils.misc import filter_dict
from packnet_sfm.utils.types import is_tensor, is_list, is_numpy
def flip(tensor, flip_fn):
"""
Flip tensors or list of tensors base... | en | 0.589126 | # Copyright 2020 Toyota Research Institute. All rights reserved. Flip tensors or list of tensors based on a function Parameters ---------- tensor : torch.Tensor or list[torch.Tensor] or list[list[torch.Tensor]] Tensor to be flipped flip_fn : Function Flip function Returns ----... | 2.229118 | 2 |
utils/stg/min_jerk_traj.py | dgerod/more-dmps | 7 | 3557 | '''
Created on 25.07.2012
@author: karl
'''
def trajectory(start, goal, duration, delta_t):
traj = []
# inital values
t, td, tdd = start, 0, 0
for i in range(int(2 * duration / delta_t)):
try:
t, td, tdd = _min_jerk_step(t, td, tdd, goal, duration - i * delta_t, delta_t)
except:
break
... | '''
Created on 25.07.2012
@author: karl
'''
def trajectory(start, goal, duration, delta_t):
traj = []
# inital values
t, td, tdd = start, 0, 0
for i in range(int(2 * duration / delta_t)):
try:
t, td, tdd = _min_jerk_step(t, td, tdd, goal, duration - i * delta_t, delta_t)
except:
break
... | en | 0.798798 | Created on 25.07.2012 @author: karl # inital values #function [x,xd,xdd] = min_jerk_step(x,xd,xdd,goal,tau, dt) computes # the update of x,xd,xdd for the next time step dt given that we are # currently at x,xd,xdd, and that we have tau until we want to reach # the goal # ported from matlab dmp toolbox | 2.957655 | 3 |
tests/__init__.py | karanrampal/triplet-loss | 0 | 3558 | <gh_stars>0
# To make directory as a python package
| # To make directory as a python package | en | 0.901133 | # To make directory as a python package | 1.151998 | 1 |
orthoexon/tests/test_util.py | jessicalettes/orthoexon | 0 | 3559 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
test_orthoexon
----------------------------------
Tests for `orthoexon` module.
"""
import os
import pytest
@pytest.fixture
def exon_id_with_quotes():
return "'ENSE00001229068.1'"
@pytest.fixture
def exon_id():
return "ENSE00001229068.1"
def test_separate_... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
test_orthoexon
----------------------------------
Tests for `orthoexon` module.
"""
import os
import pytest
@pytest.fixture
def exon_id_with_quotes():
return "'ENSE00001229068.1'"
@pytest.fixture
def exon_id():
return "ENSE00001229068.1"
def test_separate_... | en | 0.322933 | #!/usr/bin/env python # -*- coding: utf-8 -*- test_orthoexon ---------------------------------- Tests for `orthoexon` module. # def test_getsequence(exon, human_gtf_database): # from orthoexon.util import getsequence # # test = getsequence(exon, human_gtf_database) # true = 'ATGGCCGAAGACGCAGACATGCGCAATGAGC... | 2.217114 | 2 |
predict_recognition.py | yeyupiaoling/Kersa-Speaker-Recognition | 42 | 3560 | <filename>predict_recognition.py
import argparse
import os
import shutil
import time
import numpy as np
from utils import model, utils
from utils.record import RecordAudio
parser = argparse.ArgumentParser()
parser.add_argument('--audio_db', default='audio_db/', type=str, help='音频库的路径')
parser.add_a... | <filename>predict_recognition.py
import argparse
import os
import shutil
import time
import numpy as np
from utils import model, utils
from utils.record import RecordAudio
parser = argparse.ArgumentParser()
parser.add_argument('--audio_db', default='audio_db/', type=str, help='音频库的路径')
parser.add_a... | zh | 0.93298 | # 获取模型 # 加载预训练模型 # 预测获取声纹特征 # 加载要识别的音频库 # 识别声纹 # 计算相识度 # 声纹注册 | 2.581378 | 3 |
cubedash/_product.py | vconrado/datacube-explorer | 0 | 3561 | <reponame>vconrado/datacube-explorer
import logging
from datetime import timedelta
from flask import Blueprint, Response, abort, redirect, url_for
from cubedash import _model, _utils, _utils as utils
_LOG = logging.getLogger(__name__)
bp = Blueprint("product", __name__)
@bp.route("/about.csv")
def legacy_about_csv... | import logging
from datetime import timedelta
from flask import Blueprint, Response, abort, redirect, url_for
from cubedash import _model, _utils, _utils as utils
_LOG = logging.getLogger(__name__)
bp = Blueprint("product", __name__)
@bp.route("/about.csv")
def legacy_about_csv():
return redirect(".storage_csv... | en | 0.71389 | Get the product storage table as a CSV # This is useful for bash scripts when we want to loop products :) # This is useful for bash scripts when we want to loop them :) If people remove the name from a "/product/<name>" url, take them somewhere useful # Add Explorer ID to the download filename if they have one. # Add E... | 2.204335 | 2 |
litex_boards/platforms/sipeed_tang_nano.py | ozbenh/litex-boards | 0 | 3562 | #
# This file is part of LiteX-Boards.
#
# Copyright (c) 2021 <NAME> <<EMAIL>>
# SPDX-License-Identifier: BSD-2-Clause
# Board diagram/pinout:
# https://user-images.githubusercontent.com/1450143/133655492-532d5e9a-0635-4889-85c9-68683d06cae0.png
# http://dl.sipeed.com/TANG/Nano/HDK/Tang-NANO-2704(Schematic).pdf
from ... | #
# This file is part of LiteX-Boards.
#
# Copyright (c) 2021 <NAME> <<EMAIL>>
# SPDX-License-Identifier: BSD-2-Clause
# Board diagram/pinout:
# https://user-images.githubusercontent.com/1450143/133655492-532d5e9a-0635-4889-85c9-68683d06cae0.png
# http://dl.sipeed.com/TANG/Nano/HDK/Tang-NANO-2704(Schematic).pdf
from ... | en | 0.312429 | # # This file is part of LiteX-Boards. # # Copyright (c) 2021 <NAME> <<EMAIL>> # SPDX-License-Identifier: BSD-2-Clause # Board diagram/pinout: # https://user-images.githubusercontent.com/1450143/133655492-532d5e9a-0635-4889-85c9-68683d06cae0.png # http://dl.sipeed.com/TANG/Nano/HDK/Tang-NANO-2704(Schematic).pdf # IOs -... | 1.54324 | 2 |
nm_cavia/rl/metalearner.py | anon-6994/nm-metarl | 0 | 3563 | import torch
from torch.distributions.kl import kl_divergence
from torch.nn.utils.convert_parameters import (vector_to_parameters,
parameters_to_vector)
from rl_utils.optimization import conjugate_gradient
from rl_utils.torch_utils import (weighted_mean, detach_distributi... | import torch
from torch.distributions.kl import kl_divergence
from torch.nn.utils.convert_parameters import (vector_to_parameters,
parameters_to_vector)
from rl_utils.optimization import conjugate_gradient
from rl_utils.torch_utils import (weighted_mean, detach_distributi... | en | 0.763309 | Meta-learner The meta-learner is responsible for sampling the trajectories/episodes (before and after the one-step adaptation), compute the inner loss, compute the updated parameters based on the inner-loss, and perform the meta-update. [1] <NAME>, <NAME>, <NAME>, "Model-Agnostic Meta-Learn... | 2.487306 | 2 |
request/management/commands/purgerequests.py | hramezani/django-request | 373 | 3564 | from datetime import timedelta
from dateutil.relativedelta import relativedelta
from django.core.management.base import BaseCommand, CommandError
from django.utils import timezone
from ...models import Request
DURATION_OPTIONS = {
'hours': lambda amount: timezone.now() - timedelta(hours=amount),
'days': lamb... | from datetime import timedelta
from dateutil.relativedelta import relativedelta
from django.core.management.base import BaseCommand, CommandError
from django.utils import timezone
from ...models import Request
DURATION_OPTIONS = {
'hours': lambda amount: timezone.now() - timedelta(hours=amount),
'days': lamb... | en | 0.886255 | # to keep backward Python 2 compatibility # Check we have the correct values # If its not plural, make it plural You have requested a database reset. This will IRREVERSIBLY DESTROY any requests created before {0} {1} ago. That is a total of {2} requests. Are you sure you want to do this? Type 'yes' to continue, or 'no... | 2.235569 | 2 |
tests/test_crypto.py | kimtaehong/PythonForWindows | 0 | 3565 | import pytest
import windows.crypto
import windows.generated_def as gdef
import windows.crypto.generation
from .pfwtest import *
pytestmark = pytest.mark.usefixtures('check_for_gc_garbage')
TEST_CERT = b"""
<KEY>"""
## Cert info:
# Name: PythonForWindowsTest
# Serial: '1b 8e 94 cb 0b 3e eb b6 41 39 f3 c9 09 b1 6... | import pytest
import windows.crypto
import windows.generated_def as gdef
import windows.crypto.generation
from .pfwtest import *
pytestmark = pytest.mark.usefixtures('check_for_gc_garbage')
TEST_CERT = b"""
<KEY>"""
## Cert info:
# Name: PythonForWindowsTest
# Serial: '1b 8e 94 cb 0b 3e eb b6 41 39 f3 c9 09 b1 6... | en | 0.730133 | <KEY> ## Cert info: # Name: PythonForWindowsTest # Serial: '1b 8e 94 cb 0b 3e eb b6 41 39 f3 c9 09 b1 6b 46' <KEY> Generate a cert / pfx. Based on samples\crypto\encryption_demo.py # Create a TMP context that will hold our newly generated key-pair # Generate a key-pair that is exportable # It does NOT destroy the key... | 2.100436 | 2 |
cdci_data_analysis/analysis/plot_tools.py | andreatramacere/cdci_data_analysis | 0 | 3566 | from __future__ import absolute_import, division, print_function
from builtins import (bytes, str, open, super, range,
zip, round, input, int, pow, object, map, zip)
__author__ = "<NAME>"
import numpy as np
from astropy import wcs
from bokeh.layouts import row, widgetbox,gridplot
from bokeh... | from __future__ import absolute_import, division, print_function
from builtins import (bytes, str, open, super, range,
zip, round, input, int, pow, object, map, zip)
__author__ = "<NAME>"
import numpy as np
from astropy import wcs
from bokeh.layouts import row, widgetbox,gridplot
from bokeh... | en | 0.158875 | # print attr,old,new #import plotly #import plotly.graph_objs as go #from plotly.graph_objs import Layout # print('vmin,vmax',vmin,vmax) #fig, (ax) = plt.subplots(1, 1, figsize=(4, 3), subplot_kw={'projection': WCS(self.header)}) #im = ax.imshow(self.data, # origin='lower', # zorder=1, # ... | 2.008855 | 2 |
test/unit/test_testaid_unit_pathlist.py | RebelCodeBase/testaid | 17 | 3567 | from pathlib import Path
from testaid.pathlist import PathList
def test_testaid_unit_pathlist_roles_blacklist(testvars_roles_blacklist):
assert testvars_roles_blacklist is not None
def test_testaid_unit_pathlist_roles_whitelist(testvars_roles_whitelist):
assert testvars_roles_whitelist is not None
def tes... | from pathlib import Path
from testaid.pathlist import PathList
def test_testaid_unit_pathlist_roles_blacklist(testvars_roles_blacklist):
assert testvars_roles_blacklist is not None
def test_testaid_unit_pathlist_roles_whitelist(testvars_roles_whitelist):
assert testvars_roles_whitelist is not None
def tes... | none | 1 | 2.398455 | 2 | |
tests/unit/zhmcclient/test_hba.py | vkpro-forks/python-zhmcclient | 0 | 3568 | <filename>tests/unit/zhmcclient/test_hba.py<gh_stars>0
# Copyright 2016-2017 IBM Corp. 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/licens... | <filename>tests/unit/zhmcclient/test_hba.py<gh_stars>0
# Copyright 2016-2017 IBM Corp. 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/licens... | en | 0.810761 | # Copyright 2016-2017 IBM Corp. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or... | 2.033145 | 2 |
compiler-rt/test/asan/TestCases/Windows/lit.local.cfg.py | medismailben/llvm-project | 2,338 | 3569 | def getRoot(config):
if not config.parent:
return config
return getRoot(config.parent)
root = getRoot(config)
# We only run a small set of tests on Windows for now.
# Override the parent directory's "unsupported" decision until we can handle
# all of its tests.
if root.host_os in ['Windows']:
config.unsuppo... | def getRoot(config):
if not config.parent:
return config
return getRoot(config.parent)
root = getRoot(config)
# We only run a small set of tests on Windows for now.
# Override the parent directory's "unsupported" decision until we can handle
# all of its tests.
if root.host_os in ['Windows']:
config.unsuppo... | en | 0.945685 | # We only run a small set of tests on Windows for now. # Override the parent directory's "unsupported" decision until we can handle # all of its tests. | 2.544445 | 3 |
Lib/test/libregrtest/utils.py | oskomorokhov/cpython | 5 | 3570 | <filename>Lib/test/libregrtest/utils.py
import math
import os.path
import sys
import textwrap
from test import support
def format_duration(seconds):
ms = math.ceil(seconds * 1e3)
seconds, ms = divmod(ms, 1000)
minutes, seconds = divmod(seconds, 60)
hours, minutes = divmod(minutes, 60)
parts = []
... | <filename>Lib/test/libregrtest/utils.py
import math
import os.path
import sys
import textwrap
from test import support
def format_duration(seconds):
ms = math.ceil(seconds * 1e3)
seconds, ms = divmod(ms, 1000)
minutes, seconds = divmod(seconds, 60)
hours, minutes = divmod(minutes, 60)
parts = []
... | en | 0.743281 | # 2 min 1 sec # 1.0 sec Print the elements of iterable x to stdout. Optional arg width (default 70) is the maximum line length. Optional arg indent (default 4) is the number of blanks with which to begin each line. # Print the sorted list: 'x' may be a '--random' list or a set() # Clear the warnings regist... | 2.668457 | 3 |
efetch_server/plugins/fa_sqlite/fa_sqlite_ajax.py | Syrkadian/efetch | 38 | 3571 | """
AJAX for SQLite Viewer plugin
"""
from yapsy.IPlugin import IPlugin
from flask import Response, jsonify
import json
import logging
import sqlite3
class FaSqliteAjax(IPlugin):
def __init__(self):
self.display_name = 'SQLite Ajax'
self.popularity = 0
self.cache = True
self.fast ... | """
AJAX for SQLite Viewer plugin
"""
from yapsy.IPlugin import IPlugin
from flask import Response, jsonify
import json
import logging
import sqlite3
class FaSqliteAjax(IPlugin):
def __init__(self):
self.display_name = 'SQLite Ajax'
self.popularity = 0
self.cache = True
self.fast ... | en | 0.658589 | AJAX for SQLite Viewer plugin Checks if the file is compatible with this plugin Returns the mimetype of this plugins get command Returns the result of this plugin to be displayed in a browser # Master Table # Tables # Views # Indexes # Triggers # TODO REPLACE WITH DICTIONARY AND JSONIFY, SEE: http://stackoverflow.com/q... | 2.378193 | 2 |
raspagem/random/lista_cidades.py | sslppractice/propython | 0 | 3572 | <filename>raspagem/random/lista_cidades.py
import requests, json
url = 'http://educacao.dadosabertosbr.com/api/cidades/ce'
cidades = requests.get(url).content
cidades = cidades.decode('utf-8')
cidades = json.loads(cidades)
for cidade in cidades:
codigo, nome = cidade.split(':')
print(nome)
| <filename>raspagem/random/lista_cidades.py
import requests, json
url = 'http://educacao.dadosabertosbr.com/api/cidades/ce'
cidades = requests.get(url).content
cidades = cidades.decode('utf-8')
cidades = json.loads(cidades)
for cidade in cidades:
codigo, nome = cidade.split(':')
print(nome)
| none | 1 | 2.831644 | 3 | |
mezzanine/__init__.py | startupgrind/mezzanine | 0 | 3573 | <reponame>startupgrind/mezzanine
__version__ = "4.3.1.post1"
| __version__ = "4.3.1.post1" | none | 1 | 0.984262 | 1 | |
src/autonomous/purepursuit.py | Sloomey/DeepSpace2019 | 0 | 3574 | import math
from constants import Constants
from utils import vector2d
from wpilib import SmartDashboard as Dash
from autonomous import pursuitpoint
class PurePursuit():
"""An implementation of the Pure Pursuit path tracking algorithm."""
def __init__(self, path):
self.path = path
self.pursui... | import math
from constants import Constants
from utils import vector2d
from wpilib import SmartDashboard as Dash
from autonomous import pursuitpoint
class PurePursuit():
"""An implementation of the Pure Pursuit path tracking algorithm."""
def __init__(self, path):
self.path = path
self.pursui... | en | 0.699523 | An implementation of the Pure Pursuit path tracking algorithm. Compute the velocities along the path. # Compute the velocities along the path using the curvature and Constants.CURVE_VELOCITY # Limit the acceleration of the velocities Update the lookahead point given the current robot state. Uses the minimum ... | 3.093786 | 3 |
esphome/voluptuous_schema.py | TheEggi/esphomeyaml | 0 | 3575 | <gh_stars>0
import difflib
import itertools
import voluptuous as vol
from esphome.py_compat import string_types
class ExtraKeysInvalid(vol.Invalid):
def __init__(self, *arg, **kwargs):
self.candidates = kwargs.pop('candidates')
vol.Invalid.__init__(self, *arg, **kwargs)
def ensure_multiple_inv... | import difflib
import itertools
import voluptuous as vol
from esphome.py_compat import string_types
class ExtraKeysInvalid(vol.Invalid):
def __init__(self, *arg, **kwargs):
self.candidates = kwargs.pop('candidates')
vol.Invalid.__init__(self, *arg, **kwargs)
def ensure_multiple_invalid(err):
... | en | 0.897447 | # pylint: disable=protected-access, unidiomatic-typecheck Custom cv.Schema that prints similar keys on error. # List of extra schemas to apply after validation # Should be used sparingly, as it's not a very voluptuous-way/clean way of # doing things. # Check some things that ESPHome's schemas do not allow # mostly to k... | 2.31327 | 2 |
semisupervised/DensityPeaks.py | dpr1005/Semisupervised-learning-and-instance-selection-methods | 3 | 3576 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Filename: DensityPeaks.py
# @Author: <NAME>
# @Time: 5/3/22 09:55
# @Version: 4.0
import math
from collections import defaultdict
import numpy as np
import pandas as pd
from sklearn.neighbors import KNeighborsClassifier, NearestNeighbors
from sklearn.... | #!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Filename: DensityPeaks.py
# @Author: <NAME>
# @Time: 5/3/22 09:55
# @Version: 4.0
import math
from collections import defaultdict
import numpy as np
import pandas as pd
from sklearn.neighbors import KNeighborsClassifier, NearestNeighbors
from sklearn.... | en | 0.862317 | #!/usr/bin/env python # -*- coding:utf-8 -*- # @Filename: DensityPeaks.py # @Author: <NAME> # @Time: 5/3/22 09:55 # @Version: 4.0 <NAME>., <NAME>., & <NAME>. (2019). A self-training method based on density peaks and an extended parameter-free local noise filter for k nearest neighbor. Knowled... | 2.734278 | 3 |
N-aryTreeLevelOrderTraversal429.py | Bit64L/LeetCode-Python- | 0 | 3577 | """
# Definition for a Node.
"""
class TreeNode(object):
def __init__(self, val, children):
self.val = val
self.children = children
class Solution(object):
def levelOrder(self, root):
"""
:type root: Node
:rtype: List[List[int]]
"""
if root is None:
... | """
# Definition for a Node.
"""
class TreeNode(object):
def __init__(self, val, children):
self.val = val
self.children = children
class Solution(object):
def levelOrder(self, root):
"""
:type root: Node
:rtype: List[List[int]]
"""
if root is None:
... | en | 0.226483 | # Definition for a Node. :type root: Node :rtype: List[List[int]] | 3.712801 | 4 |
plugin.video.team.milhanos/websocket/_core.py | akuala/REPO.KUALA | 2 | 3578 | <reponame>akuala/REPO.KUALA
"""
websocket - WebSocket client library for Python
Copyright (C) 2010 <NAME>(liris)
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version... | """
websocket - WebSocket client library for Python
Copyright (C) 2010 <NAME>(liris)
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at ... | en | 0.669962 | websocket - WebSocket client library for Python Copyright (C) 2010 <NAME>(liris) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your... | 2.633582 | 3 |
vaccine_card/logistic/models.py | Unanimad/lais_046_2020_etapa_2 | 0 | 3579 | from django.db import models
from vaccine_card.vaccination.models import Vaccine
class State(models.Model):
name = models.CharField(max_length=20, verbose_name='Nome')
class Meta:
verbose_name = 'Unidade Federativa'
def __str__(self):
return self.name
class City(models.Model):
nam... | from django.db import models
from vaccine_card.vaccination.models import Vaccine
class State(models.Model):
name = models.CharField(max_length=20, verbose_name='Nome')
class Meta:
verbose_name = 'Unidade Federativa'
def __str__(self):
return self.name
class City(models.Model):
nam... | en | 0.538392 | # state = models.ForeignKey(State, on_delete=models.CASCADE, verbose_name=State._meta.verbose_name) | 2.072497 | 2 |
test/test_rimuhosting.py | shenoyn/libcloud | 1 | 3580 | <reponame>shenoyn/libcloud
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# libcloud.org licenses this file to You under the Apache License, Version 2.0
# (... | # Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# libcloud.org licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not... | en | 0.443065 | # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # libcloud.org licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not... | 1.889344 | 2 |
tests/base_tests/polygon_tests/test_contains.py | lycantropos/gon | 10 | 3581 | <gh_stars>1-10
from typing import Tuple
from hypothesis import given
from gon.base import (Point,
Polygon)
from tests.utils import (equivalence,
implication)
from . import strategies
@given(strategies.polygons)
def test_vertices(polygon: Polygon) -> None:
assert al... | from typing import Tuple
from hypothesis import given
from gon.base import (Point,
Polygon)
from tests.utils import (equivalence,
implication)
from . import strategies
@given(strategies.polygons)
def test_vertices(polygon: Polygon) -> None:
assert all(vertex in pol... | none | 1 | 2.897435 | 3 | |
easyidp/core/tests/test_class_reconsproject.py | HowcanoeWang/EasyIDP | 0 | 3582 | import os
import numpy as np
import pytest
import easyidp
from easyidp.core.objects import ReconsProject, Points
from easyidp.io import metashape
module_path = os.path.join(easyidp.__path__[0], "io/tests")
def test_init_reconsproject():
attempt1 = ReconsProject("agisoft")
assert attempt1.software == "metash... | import os
import numpy as np
import pytest
import easyidp
from easyidp.core.objects import ReconsProject, Points
from easyidp.io import metashape
module_path = os.path.join(easyidp.__path__[0], "io/tests")
def test_init_reconsproject():
attempt1 = ReconsProject("agisoft")
assert attempt1.software == "metash... | en | 0.47259 | # test for single point # pro_api_out = np.asarray([2218.883386793118, 1991.4709388015149]) # test for multiple points # camera_label = 'DJI_0057' | 2.050781 | 2 |
withings_api/const.py | tiloc/python_withings_api | 0 | 3583 | <gh_stars>0
"""Constant values."""
STATUS_SUCCESS = (0,)
STATUS_AUTH_FAILED = (100, 101, 102, 200, 401)
STATUS_INVALID_PARAMS = (
201,
202,
203,
204,
205,
206,
207,
208,
209,
210,
211,
212,
213,
216,
217,
218,
220,
221,
223,
225,
227... | """Constant values."""
STATUS_SUCCESS = (0,)
STATUS_AUTH_FAILED = (100, 101, 102, 200, 401)
STATUS_INVALID_PARAMS = (
201,
202,
203,
204,
205,
206,
207,
208,
209,
210,
211,
212,
213,
216,
217,
218,
220,
221,
223,
225,
227,
228,
... | fr | 0.21898 | Constant values. | 1.825928 | 2 |
examples/canvas/bezier.py | sirpercival/kivy | 2 | 3584 | #!/usr/bin/env python
from kivy.app import App
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.slider import Slider
from kivy.graphics import Color, Bezier, Line
class BezierTest(FloatLayout):
def __init__(self, points=[], loop=False, *args, **kwargs):
super(BezierTest, self).__init__(*args, *... | #!/usr/bin/env python
from kivy.app import App
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.slider import Slider
from kivy.graphics import Color, Bezier, Line
class BezierTest(FloatLayout):
def __init__(self, points=[], loop=False, *args, **kwargs):
super(BezierTest, self).__init__(*args, *... | en | 0.701434 | #!/usr/bin/env python # effect to reduce length while increase offset # effect to reduce length while increase offset # Pacman ! | 3.036511 | 3 |
tests/bugs/core_6489_test.py | reevespaul/firebird-qa | 0 | 3585 | <filename>tests/bugs/core_6489_test.py<gh_stars>0
#coding:utf-8
#
# id: bugs.core_6489
# title: User without ALTER ANY ROLE privilege can use COMMENT ON ROLE
# decription:
# Test creates two users: one of them has no any rights, second is granted with 'alter any role' privilege.
# ... | <filename>tests/bugs/core_6489_test.py<gh_stars>0
#coding:utf-8
#
# id: bugs.core_6489
# title: User without ALTER ANY ROLE privilege can use COMMENT ON ROLE
# decription:
# Test creates two users: one of them has no any rights, second is granted with 'alter any role' privilege.
# ... | en | 0.675445 | #coding:utf-8 # # id: bugs.core_6489 # title: User without ALTER ANY ROLE privilege can use COMMENT ON ROLE # decription: # Test creates two users: one of them has no any rights, second is granted with 'alter any role' privilege. # First user ('junior') must not have a... | 1.428019 | 1 |
utils/utils_bbox.py | MasoonZhang/FasterRConvMixer | 0 | 3586 | <reponame>MasoonZhang/FasterRConvMixer
import numpy as np
import torch
from torch.nn import functional as F
from torchvision.ops import nms
def loc2bbox(src_bbox, loc):
if src_bbox.size()[0] == 0:
return torch.zeros((0, 4), dtype=loc.dtype)
src_width = torch.unsqueeze(src_bbox[:, 2] - src_bbox[:, 0... | import numpy as np
import torch
from torch.nn import functional as F
from torchvision.ops import nms
def loc2bbox(src_bbox, loc):
if src_bbox.size()[0] == 0:
return torch.zeros((0, 4), dtype=loc.dtype)
src_width = torch.unsqueeze(src_bbox[:, 2] - src_bbox[:, 0], -1)
src_height = torch.unsqueez... | zh | 0.178789 | #-----------------------------------------------------------------# # 把y轴放前面是因为方便预测框和图像的宽高进行相乘 #-----------------------------------------------------------------# #--------------------------------# # batch_size, num_rois, 4 #--------------------------------# #--------------------------------------------------------... | 2.196774 | 2 |
lib/python/test/__init__.py | woozhijun/cat | 17,318 | 3587 | #!/usr/bin/env python
# encoding: utf-8
import sys
reload(sys)
sys.setdefaultencoding("utf-8") | #!/usr/bin/env python
# encoding: utf-8
import sys
reload(sys)
sys.setdefaultencoding("utf-8") | en | 0.349253 | #!/usr/bin/env python # encoding: utf-8 | 1.411967 | 1 |
tests/test_pyclipper.py | odidev/pyclipper | 0 | 3588 | <filename>tests/test_pyclipper.py<gh_stars>0
#!/usr/bin/python
"""
Tests for Pyclipper wrapper library.
"""
from __future__ import print_function
from unittest2 import TestCase, main
import sys
if sys.version_info < (3,):
integer_types = (int, long)
else:
integer_types = (int,)
import pyclipper
# Example po... | <filename>tests/test_pyclipper.py<gh_stars>0
#!/usr/bin/python
"""
Tests for Pyclipper wrapper library.
"""
from __future__ import print_function
from unittest2 import TestCase, main
import sys
if sys.version_info < (3,):
integer_types = (int, long)
else:
integer_types = (int,)
import pyclipper
# Example po... | en | 0.876917 | #!/usr/bin/python Tests for Pyclipper wrapper library. # Example polygons from http://www.angusj.com/delphi/clipper.php # square, orientation is False # triangle # square # greek letter sigma # less than 2 vertices # area less than 0 because orientation is False # on polygon # in polygon # outside of polygon # empty co... | 2.391972 | 2 |
imageproc_OE_IF_quant/2_annotate_extracted_cells.py | hshayya/2022_Shayya_UPR_Guidance | 0 | 3589 | <filename>imageproc_OE_IF_quant/2_annotate_extracted_cells.py
import xml.etree.ElementTree as ET
import csv
import os
import re
from ij import IJ
from loci.plugins.in import ImporterOptions
from loci.plugins import BF
from ij.plugin import ImagesToStack
from ij import io
#Records metadata (x,y location) for cells that... | <filename>imageproc_OE_IF_quant/2_annotate_extracted_cells.py
import xml.etree.ElementTree as ET
import csv
import os
import re
from ij import IJ
from loci.plugins.in import ImporterOptions
from loci.plugins import BF
from ij.plugin import ImagesToStack
from ij import io
#Records metadata (x,y location) for cells that... | en | 0.823535 | #Records metadata (x,y location) for cells that were extracted with 1_find_extract_cells.py #metadata will be used in subsequent analysis to cluster cells from similar locations on the section -> semi-quantiative, local, analysis Parse Cell-Counter Xml file to Dictionary Inputs: fpath (str) path to xml file on disk ... | 1.935411 | 2 |
MAEnv/env_SingleCatchPigs/test_SingleCatchPigs.py | Abluceli/Multi-agent-Reinforcement-Learning-Algorithms | 5 | 3590 | <reponame>Abluceli/Multi-agent-Reinforcement-Learning-Algorithms
from env_SingleCatchPigs import EnvSingleCatchPigs
import random
env = EnvSingleCatchPigs(7)
max_iter = 10000
env.set_agent_at([2, 2], 0)
env.set_pig_at([4, 4], 0)
for i in range(max_iter):
print("iter= ", i)
env.render()
action = random.rand... | from env_SingleCatchPigs import EnvSingleCatchPigs
import random
env = EnvSingleCatchPigs(7)
max_iter = 10000
env.set_agent_at([2, 2], 0)
env.set_pig_at([4, 4], 0)
for i in range(max_iter):
print("iter= ", i)
env.render()
action = random.randint(0, 4)
print('action is', action)
reward, done = env.s... | none | 1 | 2.600466 | 3 | |
eust/tables/data.py | rasmuse/eust | 1 | 3591 | <filename>eust/tables/data.py
# -*- coding: utf-8 -*-
import re
import gzip
import pandas as pd
import numpy as np
from eust.core import _download_file, conf
_DIMENSION_NAME_RE = re.compile(r"^[a-z_0-9]+$")
_YEAR_RE = re.compile(r"^(1|2)[0-9]{3}$")
def _is_valid_dimension_name(s: str) -> bool:
return bool(_D... | <filename>eust/tables/data.py
# -*- coding: utf-8 -*-
import re
import gzip
import pandas as pd
import numpy as np
from eust.core import _download_file, conf
_DIMENSION_NAME_RE = re.compile(r"^[a-z_0-9]+$")
_YEAR_RE = re.compile(r"^(1|2)[0-9]{3}$")
def _is_valid_dimension_name(s: str) -> bool:
return bool(_D... | en | 0.847066 | # -*- coding: utf-8 -*- # no duplicates # cannot handle multidimensional column labels # Replace empty flags by None (issue #3) # # Doing it at this point so that the null flag is saved in the HDF # file as a string, for performance reasons. # This is a pandas PerformanceWarning: # "your performance may suffer as PyTab... | 2.645304 | 3 |
utils.py | fatemehtd/Echo-SyncNet | 6 | 3592 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from config import CONFIG
import json
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt # pylint: disable=g-import-not-at-top
import io
import math
import os
import time
from absl i... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from config import CONFIG
import json
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt # pylint: disable=g-import-not-at-top
import io
import math
import os
import time
from absl i... | en | 0.810077 | # pylint: disable=g-import-not-at-top Visualizes a batch. Visualize nearest neighbours in embedding space. # Set learning_phase to False to use models in inference mode. # Convert sim_matrix to float32 as summary_image doesn't take float64 # Generate m random permuations of range (0, n) # NumPy version: np.random.rand(... | 2.304542 | 2 |
UnityPy/classes/Sprite.py | dblack2056/UnityPy | 0 | 3593 | from enum import IntEnum
from .Mesh import BoneWeights4, SubMesh, VertexData
from .NamedObject import NamedObject
from .PPtr import PPtr, save_ptr
from ..export import SpriteHelper
from ..enums import SpriteMeshType
from ..streams import EndianBinaryWriter
class Sprite(NamedObject):
@property
def image(self)... | from enum import IntEnum
from .Mesh import BoneWeights4, SubMesh, VertexData
from .NamedObject import NamedObject
from .PPtr import PPtr, save_ptr
from ..export import SpriteHelper
from ..enums import SpriteMeshType
from ..streams import EndianBinaryWriter
class Sprite(NamedObject):
@property
def image(self)... | en | 0.847023 | # 4.5 and up # 5.4.1p3 and up # 5.3 and up # 2017 and up # GUID # SpriteAtlas # 2017 and up # 2018 and up # 4.5 and up # 5.4.1p3 and up # 5.3 and up # 2017 and up # GUID # SpriteAtlas # 2017 and up # 2018 and up # Texture2D # 1 # 1 # 4 # 1 # rest of the bits are reserved # 4.3 and down # 4.3 and down # Texture2D # 5.2 ... | 2.261391 | 2 |
eazy/filters.py | albertfxwang/eazy-py | 0 | 3594 | <filename>eazy/filters.py
import numpy as np
import os
from astropy.table import Table
from . import utils
__all__ = ["FilterDefinition", "FilterFile", "ParamFilter"]
VEGA_FILE = os.path.join(utils.path_to_eazy_data(),
'alpha_lyr_stis_008.fits')
VEGA = Table.read(VE... | <filename>eazy/filters.py
import numpy as np
import os
from astropy.table import Table
from . import utils
__all__ = ["FilterDefinition", "FilterFile", "ParamFilter"]
VEGA_FILE = os.path.join(utils.path_to_eazy_data(),
'alpha_lyr_stis_008.fits')
VEGA = Table.read(VE... | en | 0.565718 | Bandpass object Parameters ---------- name : str Label name wave : array Wavelength array, in `astropy.units.Angstrom`. throughput : array Throughput, arbitrary normalization bp : optional, `pysynphot... | 2.420922 | 2 |
LeetCode/106.py | KevinTMtz/CompetitiveProgramming | 1 | 3595 | <reponame>KevinTMtz/CompetitiveProgramming
#
# LeetCode
#
# Problem - 106
# URL - https://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/
#
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# ... | #
# LeetCode
#
# Problem - 106
# URL - https://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/
#
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = ri... | en | 0.539257 | # # LeetCode # # Problem - 106 # URL - https://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/ # # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = rig... | 3.834814 | 4 |
evalml/automl/automl_search.py | skvorekn/evalml | 0 | 3596 | import copy
import time
from collections import defaultdict
import cloudpickle
import numpy as np
import pandas as pd
import woodwork as ww
from sklearn.model_selection import BaseCrossValidator
from .pipeline_search_plots import PipelineSearchPlots
from evalml.automl.automl_algorithm import IterativeAlgorithm
from ... | import copy
import time
from collections import defaultdict
import cloudpickle
import numpy as np
import pandas as pd
import woodwork as ww
from sklearn.model_selection import BaseCrossValidator
from .pipeline_search_plots import PipelineSearchPlots
from evalml.automl.automl_algorithm import IterativeAlgorithm
from ... | en | 0.799635 | Automated Pipeline search. # Necessary for "Plotting" documentation, since Sphinx does not work well with instance attributes. Automated pipeline search Arguments: X_train (pd.DataFrame, ww.DataTable): The input training data of shape [n_samples, n_features]. Required. y_train (pd.Seri... | 1.895289 | 2 |
graphql_social_auth/mutations.py | deepsourcelabs/django-graphql-social-auth | 1 | 3597 | import graphene
from graphql_jwt.decorators import setup_jwt_cookie
from . import mixins, types
from .decorators import social_auth
class SocialAuthMutation(mixins.SocialAuthMixin, graphene.Mutation):
social = graphene.Field(types.SocialType)
class Meta:
abstract = True
class Arguments:
... | import graphene
from graphql_jwt.decorators import setup_jwt_cookie
from . import mixins, types
from .decorators import social_auth
class SocialAuthMutation(mixins.SocialAuthMixin, graphene.Mutation):
social = graphene.Field(types.SocialType)
class Meta:
abstract = True
class Arguments:
... | en | 0.577017 | Social Auth Mutation Social Auth for JSON Web Token (JWT) | 2.393601 | 2 |
yellowbrick/regressor/base.py | Juan0001/yellowbrick-docs-zh | 20 | 3598 | <reponame>Juan0001/yellowbrick-docs-zh
# yellowbrick.regressor.base
# Base classes for regressor Visualizers.
#
# Author: <NAME> <<EMAIL>>
# Author: <NAME> <<EMAIL>>
# Created: Fri Jun 03 10:30:36 2016 -0700
#
# Copyright (C) 2016 District Data Labs
# For license information, see LICENSE.txt
#
# ID: base.py [7d3f5... | # yellowbrick.regressor.base
# Base classes for regressor Visualizers.
#
# Author: <NAME> <<EMAIL>>
# Author: <NAME> <<EMAIL>>
# Created: Fri Jun 03 10:30:36 2016 -0700
#
# Copyright (C) 2016 District Data Labs
# For license information, see LICENSE.txt
#
# ID: base.py [7d3f5e6] <EMAIL> $
"""
Base classes for reg... | de | 0.336404 | # yellowbrick.regressor.base # Base classes for regressor Visualizers. # # Author: <NAME> <<EMAIL>> # Author: <NAME> <<EMAIL>> # Created: Fri Jun 03 10:30:36 2016 -0700 # # Copyright (C) 2016 District Data Labs # For license information, see LICENSE.txt # # ID: base.py [7d3f5e6] <EMAIL> $ Base classes for regresso... | 1.789115 | 2 |
contrib/stack/stripmapStack/crossmul.py | falkamelung/isce2 | 0 | 3599 | #!/usr/bin/env python3
import os
import argparse
import logging
import isce
import isceobj
from components.stdproc.stdproc import crossmul
from iscesys.ImageUtil.ImageUtil import ImageUtil as IU
def createParser():
'''
Command Line Parser.
'''
parser = argparse.ArgumentParser( description='Generat... | #!/usr/bin/env python3
import os
import argparse
import logging
import isce
import isceobj
from components.stdproc.stdproc import crossmul
from iscesys.ImageUtil.ImageUtil import ImageUtil as IU
def createParser():
'''
Command Line Parser.
'''
parser = argparse.ArgumentParser( description='Generat... | en | 0.880681 | #!/usr/bin/env python3 Command Line Parser. #right now imageSlc1 and 2 are just text files, need to open them as image Main driver. | 2.324581 | 2 |