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 |
|---|---|---|---|---|---|---|---|---|---|---|
tests/test_util.py | Spotchi/dETaiL | 3 | 6631851 | <filename>tests/test_util.py
def save_int(int_num, filepath):
assert type(int_num) is int
with open(filepath, 'w') as fd:
fd.write(str(int_num))
def load_int(filepath):
with open(filepath, 'r') as fd:
num = int(fd.read())
return num
| <filename>tests/test_util.py
def save_int(int_num, filepath):
assert type(int_num) is int
with open(filepath, 'w') as fd:
fd.write(str(int_num))
def load_int(filepath):
with open(filepath, 'r') as fd:
num = int(fd.read())
return num
| none | 1 | 2.93745 | 3 | |
setup.py | ljstella/python_intensifies | 0 | 6631852 | from setuptools import setup
setup(
name='python_intensifies',
version='0.2.1',
author="<NAME>",
author_email="<EMAIL>",
keywords=['intensify intensifies shaking memes'],
py_modules=['intensify'],
url="https://github.com/CarvellScott/",
install_requires=[
"Pillow>=7.1.0"
],
... | from setuptools import setup
setup(
name='python_intensifies',
version='0.2.1',
author="<NAME>",
author_email="<EMAIL>",
keywords=['intensify intensifies shaking memes'],
py_modules=['intensify'],
url="https://github.com/CarvellScott/",
install_requires=[
"Pillow>=7.1.0"
],
... | none | 1 | 1.285815 | 1 | |
Demo/winApiTest.py | liuyu2022/game_robot | 1 | 6631853 | from traceback import print_tb
import win32api
import win32gui
import win32con # 导入win32api相关模块
import time
import cv2
import numpy as np
from PIL import Image
import collections
from gui_controls import Controls
def get_hwnd():
hWndList = []
win32gui.EnumWindows(lambda hWnd, param: param.appen... | from traceback import print_tb
import win32api
import win32gui
import win32con # 导入win32api相关模块
import time
import cv2
import numpy as np
from PIL import Image
import collections
from gui_controls import Controls
def get_hwnd():
hWndList = []
win32gui.EnumWindows(lambda hWnd, param: param.appen... | en | 0.201348 | # 导入win32api相关模块 # 调整目标窗口到坐标(600,300),大小设置为(600,600) # k 0x4B # j 0x4A # win32con.VK_LEFT 左 # VK_UP 上 # VK_RIGHT 右 # VK_DOWN 下 # win32api.PostMessage(8915604, win32con.WM_KEYDOWN, win32con.VK_LEFT, 0)#发送F9键 # win32api.PostMessage(8915604, win32con.WM_KEYUP, win32con.VK_LEFT, 0) # 按钮点击 # 按钮点击 # 窗口最大最小化 # 先删除 # 出发地图键m # ... | 2.55105 | 3 |
scripts/run_rec_ensemble/run_nlp_strict.py | edervishaj/spotify-recsys-challenge | 3 | 6631854 | from utils.submitter import Submitter
from utils.post_processing import eurm_to_recommendation_list_submission
from recommenders.nlp_strict import NLPStrict
import sys
import datetime
import scipy.sparse as sps
from utils.datareader import Datareader
from utils.evaluator import Evaluator
import numpy as np
from recomme... | from utils.submitter import Submitter
from utils.post_processing import eurm_to_recommendation_list_submission
from recommenders.nlp_strict import NLPStrict
import sys
import datetime
import scipy.sparse as sps
from utils.datareader import Datareader
from utils.evaluator import Evaluator
import numpy as np
from recomme... | en | 0.705276 | # Setup # Init object # Get ucm # Compute similarity (playlists x playlists) # Recommendation # Submission # Setup # Init object # Get ucm # Do not train on challenge set # Compute similarity (playlists x playlists) # Recommendation # Submission | 2.168171 | 2 |
Allura/allura/model/__init__.py | rohankumardubey/allura | 1 | 6631855 | # -*- coding: utf-8 -*-
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apach... | # -*- coding: utf-8 -*-
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apach... | en | 0.864803 | # -*- coding: utf-8 -*- # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache... | 1.032036 | 1 |
tensorflow_decision_forests/tensorflow/tf_logging.py | Hawk94/decision-forests | 412 | 6631856 | # Copyright 2021 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,... | # Copyright 2021 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,... | en | 0.792004 | # Copyright 2021 Google LLC. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing,... | 1.818107 | 2 |
Restaurant_Finder_App/restaurant_finder_app/restaurant_finder_app/authentication/utils/forms.py | midhun3112/restaurant_locator | 0 | 6631857 | from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from django.contrib.auth.forms import AuthenticationForm ,PasswordResetForm,SetPasswordForm
from django import forms
from authentication.models import User, UserProfile
from django.utils.translation import gettext as _
class UserCreationForm(UserCr... | from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from django.contrib.auth.forms import AuthenticationForm ,PasswordResetForm,SetPasswordForm
from django import forms
from authentication.models import User, UserProfile
from django.utils.translation import gettext as _
class UserCreationForm(UserCr... | en | 0.851964 | A form that creates a user, with no privileges, from the given email and password. A form for updating users. Includes all the fields on the user, but replaces the password field with admin's password hash display field. # If you don't do this you cannot use Bootstrap CSS # If you don't do this you cannot u... | 2.670113 | 3 |
gradedProject/gradedApp/migrations/0001_initial.py | cs-fullstack-2019-spring/django-models3-cw-cgarciapieto | 0 | 6631858 | <reponame>cs-fullstack-2019-spring/django-models3-cw-cgarciapieto
# Generated by Django 2.2 on 2019-02-21 17:22
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Book',
... | # Generated by Django 2.2 on 2019-02-21 17:22
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Book',
fields=[
('id', models.AutoField(auto_... | en | 0.797742 | # Generated by Django 2.2 on 2019-02-21 17:22 | 2.071491 | 2 |
python/books/introduction_to_practice/p10/exce1.py | ShenJinXiang/example | 0 | 6631859 | <reponame>ShenJinXiang/example
#!/usr/bin/env python3
try:
num = int(input('input number:'))
print('number:', num)
except Exception as err:
print("error:", err) | #!/usr/bin/env python3
try:
num = int(input('input number:'))
print('number:', num)
except Exception as err:
print("error:", err) | fr | 0.221828 | #!/usr/bin/env python3 | 3.552658 | 4 |
src/mox-inventory.py | queercat/Mox-Inventory | 0 | 6631860 | <reponame>queercat/Mox-Inventory
#!/usr/local/bin/python3
# Mox Inventory -- A Scryfall powered opensource MTG invetory utility.
import json # Handles JSON data.
import sqlite3 # Backend DB for MOXI.
import card_util # A utility for creating and handling magic cards.
import requests # Handles even more web reqs.
impor... | #!/usr/local/bin/python3
# Mox Inventory -- A Scryfall powered opensource MTG invetory utility.
import json # Handles JSON data.
import sqlite3 # Backend DB for MOXI.
import card_util # A utility for creating and handling magic cards.
import requests # Handles even more web reqs.
import flask # Awesome microservice fo... | en | 0.848729 | #!/usr/local/bin/python3 # Mox Inventory -- A Scryfall powered opensource MTG invetory utility. # Handles JSON data. # Backend DB for MOXI. # A utility for creating and handling magic cards. # Handles even more web reqs. # Awesome microservice for handling web reqs. # Creating hashes for card IDs. # Loads the DB and re... | 2.549892 | 3 |
pi/makeAudioFiles.py | kevinvu184/SmartRecipes | 1 | 6631861 | import speech_recognition as sr
import subprocess
from google.cloud import texttospeech
import os
def getAudioFile(text, name):
# Instantiates a client
client = texttospeech.TextToSpeechClient()
# Set the text input to be synthesized
synthesis_input = texttospeech.types.SynthesisInput(text=text)
... | import speech_recognition as sr
import subprocess
from google.cloud import texttospeech
import os
def getAudioFile(text, name):
# Instantiates a client
client = texttospeech.TextToSpeechClient()
# Set the text input to be synthesized
synthesis_input = texttospeech.types.SynthesisInput(text=text)
... | en | 0.782209 | # Instantiates a client # Set the text input to be synthesized # Build the voice request, select the language code ("en-US") and the ssml # voice gender ("neutral") #ssml_gender=texttospeech.enums.SsmlVoiceGender.FEM # Select the type of audio file you want returned # Perform the text-to-speech request on the text inpu... | 3.535342 | 4 |
DAY 01/SECOND HALF/main.py | joseguilhermefmoura/Advent-of-Code-2020 | 0 | 6631862 | # Define a function that multiplies all elements one by one in a list of numbers
def multiply(list_of_numbers: list) -> int:
result = 1
for number in list_of_numbers:
result = result * number
return result
def get_puzzle_answer() -> int:
file_input = open("input.txt", "r") # Read the file
... | # Define a function that multiplies all elements one by one in a list of numbers
def multiply(list_of_numbers: list) -> int:
result = 1
for number in list_of_numbers:
result = result * number
return result
def get_puzzle_answer() -> int:
file_input = open("input.txt", "r") # Read the file
... | en | 0.809527 | # Define a function that multiplies all elements one by one in a list of numbers # Read the file # Get all lines from it # For each number # Read a new number # And another one, then check: # If not solved, check it again. But if solved: | 3.915748 | 4 |
freezerbox/group_by/dependency.py | kalekundert/freezerbox | 0 | 6631863 | <reponame>kalekundert/freezerbox
#!/usr/bin/env python3
import networkx as nx
from math import inf
from copy import deepcopy
from more_itertools import pairwise
def group_by_synthesis(products):
products = list(products)
# Sort groups by order of appearance:
group_from_arg0 = {}
arg0_from_group = {}... | #!/usr/bin/env python3
import networkx as nx
from math import inf
from copy import deepcopy
from more_itertools import pairwise
def group_by_synthesis(products):
products = list(products)
# Sort groups by order of appearance:
group_from_arg0 = {}
arg0_from_group = {}
next_group = 0
for prod... | en | 0.872993 | #!/usr/bin/env python3 # Sort groups by order of appearance: # Construct a dependency graph: # Split into groups and yield intermediates: # Construct a dependency graph: # Split into groups: Arguments: deps: networkx.DiGraph A graph of the dependencies to account for. Each node should have ... | 2.54738 | 3 |
generate_iglu.py | iglu-contest/task1-starting-kit | 2 | 6631864 | <gh_stars>1-10
from argparse import Namespace
import sys
sys.path.append('./python')
from bleu import compute_bleu
from train_and_eval import generate, multinomial_generate, multinomial_generate_seq2seq
from data_loader import CwCDataset
from utils import *
from vocab import load_vocab
import os
import argparse
import ... | from argparse import Namespace
import sys
sys.path.append('./python')
from bleu import compute_bleu
from train_and_eval import generate, multinomial_generate, multinomial_generate_seq2seq
from data_loader import CwCDataset
from utils import *
from vocab import load_vocab
import os
import argparse
import torch
import pi... | en | 0.583999 | # from vocab import Vocabulary # 1. a function named creat_dataloader # 2. a class Model(): # self.init(): this function will create a model # self.generate(data=DataIGLU, output='output.txt'): this function will generte the predctions for test set ################################################# #### You can skip t... | 2.663062 | 3 |
app/__init__.py | Winnyk15/BLOG-APP | 0 | 6631865 | <reponame>Winnyk15/BLOG-APP
from flask import Flask
from flask_bootstrap import Bootstrap
from flask_login import LoginManager
from flask_mail import Mail
from flask_sqlalchemy import SQLAlchemy
from config import Config
app = Flask(__name__)
db = SQLAlchemy(app)
login_manager = LoginManager()
login_manager.init_app... | from flask import Flask
from flask_bootstrap import Bootstrap
from flask_login import LoginManager
from flask_mail import Mail
from flask_sqlalchemy import SQLAlchemy
from config import Config
app = Flask(__name__)
db = SQLAlchemy(app)
login_manager = LoginManager()
login_manager.init_app(app)
bootstrap = Bootstrap(... | none | 1 | 2.225908 | 2 | |
autosynth/synth.py | parthea/synthtool | 0 | 6631866 | #!/usr/bin/env python3
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ... | #!/usr/bin/env python3
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ... | en | 0.835779 | #!/usr/bin/env python3 # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ... | 1.899268 | 2 |
methylize/__init__.py | LifeEGX/methylize | 2 | 6631867 | import logging
from .diff_meth_pos import diff_meth_pos, volcano_plot, manhattan_plot
from .diff_meth_regions import diff_meth_regions
from .genome_browser import fetch_genes
from .helpers import to_BED
from .version import __version__
from . import cpv
logging.basicConfig(level=logging.INFO)
__all__ = [
'diff_me... | import logging
from .diff_meth_pos import diff_meth_pos, volcano_plot, manhattan_plot
from .diff_meth_regions import diff_meth_regions
from .genome_browser import fetch_genes
from .helpers import to_BED
from .version import __version__
from . import cpv
logging.basicConfig(level=logging.INFO)
__all__ = [
'diff_me... | none | 1 | 1.368694 | 1 | |
qdef2d/defects/gen_defect_supercell.py | aztan2/charged-defects-framework | 4 | 6631868 | import os
import errno
import json
import argparse
from pymatgen.io.vasp.inputs import Poscar
from qdef2d.defects.core import Defect
def generate(dir_def_main, initdef_file, q, supercell, vacuum, bulkref=False):
"""
Generate defect supercell.
Parameters
----------
dir_def_main (str): path t... | import os
import errno
import json
import argparse
from pymatgen.io.vasp.inputs import Poscar
from qdef2d.defects.core import Defect
def generate(dir_def_main, initdef_file, q, supercell, vacuum, bulkref=False):
"""
Generate defect supercell.
Parameters
----------
dir_def_main (str): path t... | en | 0.785261 | Generate defect supercell. Parameters ---------- dir_def_main (str): path to main defect directory containing unitcell POSCARs initdef_file (str): json file with details to initialize defect q (int): charge supercell (tuple of ints): supercell size as [n1,n2,n3] vacuum (int): vacuum spa... | 2.695788 | 3 |
frappe/desk/utils.py | oryxsolutions/frappe | 0 | 6631869 | <reponame>oryxsolutions/frappe
# Copyright (c) 2020, Frappe Technologies Pvt. Ltd. and Contributors
# License: MIT. See LICENSE
import frappe
def validate_route_conflict(doctype, name):
"""
Raises exception if name clashes with routes from other documents for /app routing
"""
all_names = []
for _doctype in ["P... | # Copyright (c) 2020, Frappe Technologies Pvt. Ltd. and Contributors
# License: MIT. See LICENSE
import frappe
def validate_route_conflict(doctype, name):
"""
Raises exception if name clashes with routes from other documents for /app routing
"""
all_names = []
for _doctype in ["Page", "Workspace", "DocType"]:
... | en | 0.731374 | # Copyright (c) 2020, Frappe Technologies Pvt. Ltd. and Contributors # License: MIT. See LICENSE Raises exception if name clashes with routes from other documents for /app routing | 2.232339 | 2 |
junior/process/multi_process_rw.py | Firekiss/python_learn | 0 | 6631870 | # 使用多线程进行内容的读写
from multiprocessing import Process, Queue
import time
class ReadProcess(Process):
def __init__(self, q, *args, **kwargs):
super().__init__(*args, **kwargs)
self.q = q
def run(self):
l = [
'锄禾日当午',
'汗滴禾下土',
'谁知盘中餐',
'粒粒皆辛... | # 使用多线程进行内容的读写
from multiprocessing import Process, Queue
import time
class ReadProcess(Process):
def __init__(self, q, *args, **kwargs):
super().__init__(*args, **kwargs)
self.q = q
def run(self):
l = [
'锄禾日当午',
'汗滴禾下土',
'谁知盘中餐',
'粒粒皆辛... | zh | 0.982094 | # 使用多线程进行内容的读写 | 3.805652 | 4 |
scrapli/response.py | rbraddev/scrapli | 1 | 6631871 | """scrapli.response"""
from datetime import datetime
from io import TextIOWrapper
from typing import Any, Dict, List, Optional, Union
from scrapli.helper import _textfsm_get_template, genie_parse, textfsm_parse
class Response:
def __init__(
self,
host: str,
channel_input: str,
tex... | """scrapli.response"""
from datetime import datetime
from io import TextIOWrapper
from typing import Any, Dict, List, Optional, Union
from scrapli.helper import _textfsm_get_template, genie_parse, textfsm_parse
class Response:
def __init__(
self,
host: str,
channel_input: str,
tex... | en | 0.746638 | scrapli.response Scrapli Response Store channel_input, resulting output, and start/end/elapsed time information. Attempt to determine if command was successful or not and reflect that in a failed attribute. Args: host: host that was operated on channel_input: input that... | 2.846283 | 3 |
test/inverted_owg/TestDungeons.py | KrisDavie/ALttPDoorRandomizer | 42 | 6631872 | <gh_stars>10-100
from test.inverted_owg.TestInvertedOWG import TestInvertedOWG
class TestDungeons(TestInvertedOWG):
def testFirstDungeonChests(self):
self.run_location_tests([
["Hyrule Castle - Map Chest", False, []],
["Hyrule Castle - Map Chest", True, ['Beat Agahnim 1']],
... | from test.inverted_owg.TestInvertedOWG import TestInvertedOWG
class TestDungeons(TestInvertedOWG):
def testFirstDungeonChests(self):
self.run_location_tests([
["Hyrule Castle - Map Chest", False, []],
["Hyrule Castle - Map Chest", True, ['Beat Agahnim 1']],
["Hyrule Cas... | en | 0.323858 | #todo: Qirn Jump #["Palace of Darkness - Shooter Room", True, []], #todo: Qirn Jump #["Ice Palace - Compass Chest", True, ['Fire Rod']], #["Ice Palace - Compass Chest", True, ['Bombos', 'Progressive Sword']], #todo: smarter dungeon revive logic #["Ganons Tower - Hope Room - Left", True, ['Beat Agahnim 1', 'Hookshot', '... | 2.054377 | 2 |
code/model/nell_eval.py | yuan-pku/reasoning-gan | 0 | 6631873 | from __future__ import division
import csv
from collections import defaultdict
import random
import numpy as np
def nell_eval(model_answers, correct_answers):
test_data_path = correct_answers
test_prediction_path = model_answers
f = open(test_data_path)
test_data = f.readlines()
f.close()
# lo... | from __future__ import division
import csv
from collections import defaultdict
import random
import numpy as np
def nell_eval(model_answers, correct_answers):
test_data_path = correct_answers
test_prediction_path = model_answers
f = open(test_data_path)
test_data = f.readlines()
f.close()
# lo... | en | 0.625658 | # load prediction scores # calculate MAP | 2.768452 | 3 |
gala-spider/spider/data_process/processor.py | seandong37tt4qu/jeszhengq | 0 | 6631874 | from typing import List
from abc import ABCMeta
from abc import abstractmethod
from spider.entity_mgt.models import ObserveEntity
class DataProcessor(metaclass=ABCMeta):
@abstractmethod
def get_observe_entities(self, timestamp: float = None) -> List[ObserveEntity]:
pass
| from typing import List
from abc import ABCMeta
from abc import abstractmethod
from spider.entity_mgt.models import ObserveEntity
class DataProcessor(metaclass=ABCMeta):
@abstractmethod
def get_observe_entities(self, timestamp: float = None) -> List[ObserveEntity]:
pass
| none | 1 | 2.508327 | 3 | |
TrimStreamlinesCF.py | stardustscience/ParaviewCustomModules | 1 | 6631875 | <reponame>stardustscience/ParaviewCustomModules
## ========================================================================== ##
## Copyright (c) 2019 The University of Texas at Austin. ##
## All rights reserved. ##
## ... | ## ========================================================================== ##
## Copyright (c) 2019 The University of Texas at Austin. ##
## All rights reserved. ##
## ... | en | 0.684769 | ## ========================================================================== ## ## Copyright (c) 2019 The University of Texas at Austin. ## ## All rights reserved. ## ## ... | 1.912005 | 2 |
paddlenlp/transformers/nezha/modeling.py | pangyoki/PaddleNLP | 1 | 6631876 | # Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
# Copyright 2020 Huawei Technologies Co., Ltd.
# Copyright 2018 The Google AI Language Team Authors, The HuggingFace Inc. team.
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "Li... | # Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
# Copyright 2020 Huawei Technologies Co., Ltd.
# Copyright 2018 The Google AI Language Team Authors, The HuggingFace Inc. team.
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "Li... | en | 0.674484 | # Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved. # Copyright 2020 Huawei Technologies Co., Ltd. # Copyright 2018 The Google AI Language Team Authors, The HuggingFace Inc. team. # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License... | 1.910507 | 2 |
app.py | mohammed-aladi/PyLocalHost | 0 | 6631877 | <reponame>mohammed-aladi/PyLocalHost<filename>app.py
from flask import Flask, render_template, request, url_for, session, redirect, flash
from werkzeug.utils import secure_filename
from functools import wraps
from markupsafe import escape
import os
import secrets
app = Flask(__name__)
app.secret_key = secrets.token_h... | from flask import Flask, render_template, request, url_for, session, redirect, flash
from werkzeug.utils import secure_filename
from functools import wraps
from markupsafe import escape
import os
import secrets
app = Flask(__name__)
app.secret_key = secrets.token_hex()
app.config['client_password'] = ''
# ---------... | en | 0.164461 | # --------------------------------------------------------------- # Decorators # --------------------------------------------------------------- # ADMIN SECTION # --------------------------------------------------------------- # SETUP PAGE # ------------------------------------------------------------... | 2.320508 | 2 |
pyequion2/gui/seqsolution.py | pyequion/pyequion | 0 | 6631878 | # -*- coding: utf-8 -*-
import sys
import matplotlib
matplotlib.use('Qt5Agg')
import itertools
from PyQt5.QtWidgets import (QApplication, QWidget, QLabel,
QTextEdit, QLineEdit,
QPushButton, QCheckBox,
QGridLayout, QVBoxLayout,
... | # -*- coding: utf-8 -*-
import sys
import matplotlib
matplotlib.use('Qt5Agg')
import itertools
from PyQt5.QtWidgets import (QApplication, QWidget, QLabel,
QTextEdit, QLineEdit,
QPushButton, QCheckBox,
QGridLayout, QVBoxLayout,
... | en | 0.509527 | # -*- coding: utf-8 -*- #TODO: There must be some PyQt actual solution # specie_hbox = QHBoxLayout() # conc_label = self.show_value_label(specie, self.base_solution.concentrations) # species_grid.setSpacing(0) # items = (species_grid.itemAt(i) for i in range(species_grid.count())) # for item in items: # item.widget... | 2.426636 | 2 |
junit_reporting/migrations/0010_JUnitReport_project_not_null.py | nashif/django-junit-reporting | 0 | 6631879 | <reponame>nashif/django-junit-reporting<filename>junit_reporting/migrations/0010_JUnitReport_project_not_null.py
# -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2017-10-14 15:09
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(m... | # -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2017-10-14 15:09
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('junit_reporting', '0009_wildcard_project'),
]
oper... | en | 0.739132 | # -*- coding: utf-8 -*- # Generated by Django 1.11.6 on 2017-10-14 15:09 | 1.344611 | 1 |
src/models/tests/reach_point_test.py | pasin30055/planning-evaluation-framework | 0 | 6631880 | # Copyright 2021 The Private Cardinality Estimation Framework Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required b... | # Copyright 2021 The Private Cardinality Estimation Framework Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required b... | en | 0.843606 | # Copyright 2021 The Private Cardinality Estimation Framework Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required b... | 2.092627 | 2 |
test/utils/test_feasible_volume.py | talesa/botorch | 0 | 6631881 | #! /usr/bin/env python3
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import torch
from botorch.utils.feasible_volume import (
estimate_feasible_volume,
get_feasible_samples,
... | #! /usr/bin/env python3
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import torch
from botorch.utils.feasible_volume import (
estimate_feasible_volume,
get_feasible_samples,
... | en | 0.83541 | #! /usr/bin/env python3 # Copyright (c) Meta Platforms, Inc. and affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. # -X[0]+X[1]>=1 | 1.925522 | 2 |
examples/callbacks.py | JacobKosowski/mpl-point-clicker | 3 | 6631882 | """
---------
Callbacks
---------
Demonstration of how to set up callback functions.
"""
from typing import Tuple
import matplotlib.pyplot as plt
import numpy as np
from mpl_point_clicker import clicker
image = np.load("example_image.npy")
fig, ax = plt.subplots()
ax.imshow(image, cmap='gray')
klicker = clicker(... | """
---------
Callbacks
---------
Demonstration of how to set up callback functions.
"""
from typing import Tuple
import matplotlib.pyplot as plt
import numpy as np
from mpl_point_clicker import clicker
image = np.load("example_image.npy")
fig, ax = plt.subplots()
ax.imshow(image, cmap='gray')
klicker = clicker(... | en | 0.628585 | --------- Callbacks --------- Demonstration of how to set up callback functions. | 3.163352 | 3 |
appengine/app/shared/components/user/user_manager.py | zugaldia/capitalbikeshare | 0 | 6631883 | '''
Here we wrap any operations that go beyond the UserModel. For example,
launching tasks when users get added/deleted, or the process to
reset/change a password. This logic could change from app to app.
'''
from appython.components.user.base_manager import BaseManager
from shared.components.queue.queue_manager impor... | '''
Here we wrap any operations that go beyond the UserModel. For example,
launching tasks when users get added/deleted, or the process to
reset/change a password. This logic could change from app to app.
'''
from appython.components.user.base_manager import BaseManager
from shared.components.queue.queue_manager impor... | en | 0.868906 | Here we wrap any operations that go beyond the UserModel. For example, launching tasks when users get added/deleted, or the process to reset/change a password. This logic could change from app to app. # First we check if the user already exists. (This method is safe to # call even on existing users, it won't create dup... | 2.540791 | 3 |
ko_model/start.py | Ohjiwoo-lab/News-Articles-Recommendation | 0 | 6631884 | <gh_stars>0
from recommend_engine import Process, Cluster, Sentiment, Content
import pandas as pd
from konlpy.tag import Okt
# 이 파일을 실행하세요
turn = 10 # 이것이 사용자가 본 뉴스 개수
# 사용자 클러스터화
data = pd.read_excel('news_user1.xlsx')
data = data[data['valid']==1]
lines = data['text'].tolist()
df = pd.read_csv('../output/Article... | from recommend_engine import Process, Cluster, Sentiment, Content
import pandas as pd
from konlpy.tag import Okt
# 이 파일을 실행하세요
turn = 10 # 이것이 사용자가 본 뉴스 개수
# 사용자 클러스터화
data = pd.read_excel('news_user1.xlsx')
data = data[data['valid']==1]
lines = data['text'].tolist()
df = pd.read_csv('../output/Article_IT과학_201701... | ko | 0.99743 | # 이 파일을 실행하세요 # 이것이 사용자가 본 뉴스 개수 # 사용자 클러스터화 # 500개의 뉴스만 가져옴 # 본 뉴스만 docs에 넣어서 작업 수행. # 본 뉴스의 개수가 10개가 되지 않으면 content만으로 추천이 이루어진다. # 클러스터화 한 뒤 분석 # polarity(긍정적/부정적 감정 : -1~1 사이의 값), subjectivity(객관성/주관성 : 0~1 사이의 값) # 사용자 데이터프레임 출력 # 토픽 모델링 # 전체 말뭉치에 4회 미만 등장한 단어들은 제거할 겁니다. # 공백 기준으로 단어를 나누어 model에 추가합니다. # model의 nu... | 2.692791 | 3 |
machine_learning_as_a_service/lepo/operation.py | apinf/ml-rest | 69 | 6631885 | from collections import OrderedDict
from django.utils.functional import cached_property
from lepo.utils import maybe_resolve
class Operation:
def __init__(self, router, path, method, data):
"""
:type router: lepo.router.Router
:type path: lepo.path.Path
:type method: str
... | from collections import OrderedDict
from django.utils.functional import cached_property
from lepo.utils import maybe_resolve
class Operation:
def __init__(self, router, path, method, data):
"""
:type router: lepo.router.Router
:type path: lepo.path.Path
:type method: str
... | en | 0.854597 | :type router: lepo.router.Router :type path: lepo.path.Path :type method: str :type data: dict Combined path-level and operation-level parameters. Any $refs are resolved here. Note that this implementation differs from the spec in that we only use the _name_ of a parame... | 2.054106 | 2 |
GenomicConsensus/quiver/__init__.py | RADnovogene/GenomicConsensus | 96 | 6631886 | # Author: <NAME>
from __future__ import absolute_import, division, print_function
from . import utils
from . import model
| # Author: <NAME>
from __future__ import absolute_import, division, print_function
from . import utils
from . import model
| en | 0.831508 | # Author: <NAME> | 1.085547 | 1 |
rules/repositories.bzl | cdsurfer0212/rules_ios | 0 | 6631887 | """Definitions for handling Bazel repositories used by the Apple rules."""
load(
"@bazel_tools//tools/build_defs/repo:http.bzl",
"http_archive",
)
def _maybe(repo_rule, name, **kwargs):
"""Executes the given repository rule if it hasn't been executed already.
Args:
repo_rule: The repository rul... | """Definitions for handling Bazel repositories used by the Apple rules."""
load(
"@bazel_tools//tools/build_defs/repo:http.bzl",
"http_archive",
)
def _maybe(repo_rule, name, **kwargs):
"""Executes the given repository rule if it hasn't been executed already.
Args:
repo_rule: The repository rul... | en | 0.760197 | Definitions for handling Bazel repositories used by the Apple rules. Executes the given repository rule if it hasn't been executed already. Args: repo_rule: The repository rule to be executed (e.g., `http_archive`.) name: The name of the repository to be defined by the rule. **kwargs: A... | 2.264277 | 2 |
mara_db/shell.py | leo-schick/mara-db | 0 | 6631888 | """
Shell command generation for
- running queries in databases via their command line clients
- copying data from, into and between databases
"""
import shlex
from functools import singledispatch
import sys
from mara_db import dbs, config
from mara_db.bigquery import bigquery_credentials
from multimethod import mult... | """
Shell command generation for
- running queries in databases via their command line clients
- copying data from, into and between databases
"""
import shlex
from functools import singledispatch
import sys
from mara_db import dbs, config
from mara_db.bigquery import bigquery_credentials
from multimethod import mult... | en | 0.585494 | Shell command generation for - running queries in databases via their command line clients - copying data from, into and between databases Creates a shell command that receives a sql query from stdin and executes it Args: db: The database in which to run the query (either an alias or a `dbs.DB` object ... | 3.20785 | 3 |
src/stackoverflow/49350821/Foo/bar/posts.py | mrdulin/python-codelab | 0 | 6631889 | <filename>src/stackoverflow/49350821/Foo/bar/posts.py
from collections import namedtuple
Post = namedtuple('Post', 'id text')
async def get_post(id: str):
return Post(id=int(id), text='Text for the post body.')
| <filename>src/stackoverflow/49350821/Foo/bar/posts.py
from collections import namedtuple
Post = namedtuple('Post', 'id text')
async def get_post(id: str):
return Post(id=int(id), text='Text for the post body.')
| none | 1 | 2.141926 | 2 | |
PhysEngines/ode/ode-0.13/bindings/python/setup.py | netpipe/IrrPAL | 58 | 6631890 | <reponame>netpipe/IrrPAL
#! /usr/bin/env python
from distutils.core import setup
from distutils.extension import Extension
from subprocess import Popen, PIPE, CalledProcessError
try:
from Cython.Distutils import build_ext
except ImportError:
raise SystemExit("Requires Cython (http://cython.org/)")
try:
o... | #! /usr/bin/env python
from distutils.core import setup
from distutils.extension import Extension
from subprocess import Popen, PIPE, CalledProcessError
try:
from Cython.Distutils import build_ext
except ImportError:
raise SystemExit("Requires Cython (http://cython.org/)")
try:
ode_cflags = Popen(
... | en | 0.211043 | #! /usr/bin/env python # author_email="", # maintainer="", # maintainer_email="", # download_url="https://opende.svn.sourceforge.net/svnroot/opende", # classifiers=[], # platforms=[], | 1.81 | 2 |
ege_theme/apps.py | suap-ead/lib_theme | 0 | 6631891 | from django.apps import AppConfig
class TemaConfig(AppConfig):
name = 'ege_theme'
| from django.apps import AppConfig
class TemaConfig(AppConfig):
name = 'ege_theme'
| none | 1 | 1.036399 | 1 | |
apps/combine-service/src/handlers/combine/create.py | biosimulations/Biosimulations | 7 | 6631892 | <gh_stars>1-10
from ...exceptions import BadRequestException
from ...utils import get_temp_dir
from biosimulators_utils.combine.data_model import (
CombineArchive,
CombineArchiveContent,
)
from biosimulators_utils.combine.io import (
CombineArchiveWriter,
)
from biosimulators_utils.sedml.data_model import (... | from ...exceptions import BadRequestException
from ...utils import get_temp_dir
from biosimulators_utils.combine.data_model import (
CombineArchive,
CombineArchiveContent,
)
from biosimulators_utils.combine.io import (
CombineArchiveWriter,
)
from biosimulators_utils.sedml.data_model import (
SedDocumen... | en | 0.502367 | # noqa: F401 # noqa: F401 Create a COMBINE/OMEX archive. Args: body (:obj:`dict`): dictionary with schema ``CombineArchiveSpecsAndFiles`` with the specifications of the COMBINE/OMEX archive to create files (:obj:`list` of :obj:`werkzeug.datastructures.FileStorage`, optional): files (e.g... | 2.086315 | 2 |
configuration.py | cronos23/streamlink_helper | 0 | 6631893 | <reponame>cronos23/streamlink_helper
import yaml
import requests
import os
from util import HEADERS
class Configuration:
def __init__(self):
if os.name == "posix":
directory = os.path.join(os.environ['HOME'], ".config", "streamlink_helper")
else:
directory = os.path.join(os... | import yaml
import requests
import os
from util import HEADERS
class Configuration:
def __init__(self):
if os.name == "posix":
directory = os.path.join(os.environ['HOME'], ".config", "streamlink_helper")
else:
directory = os.path.join(os.environ['APPDATA'], "streamlink_help... | none | 1 | 2.412511 | 2 | |
gnome/gnome2/gedit/plugins.symlink/FindInProject/__init__.py | icebreaker/dotfiles | 4 | 6631894 | <reponame>icebreaker/dotfiles
import gedit
from FindInProject import FindInProjectPluginInstance
class FindInProjectPlugin(gedit.Plugin):
def __init__(self):
gedit.Plugin.__init__(self)
self._instances = {}
def activate(self, window):
self._instances[window] = FindInProjectPluginInstan... | import gedit
from FindInProject import FindInProjectPluginInstance
class FindInProjectPlugin(gedit.Plugin):
def __init__(self):
gedit.Plugin.__init__(self)
self._instances = {}
def activate(self, window):
self._instances[window] = FindInProjectPluginInstance(window)
def deactivate... | none | 1 | 1.889433 | 2 | |
vcenter_operator/cmd.py | fwiesel/vcenter-operator | 5 | 6631895 | import argparse
import logging
import os
import re
import sys
from time import sleep
from kubernetes import config as k8s_config
# Import discovery before configurator as there is some monkeypatching going on
from .discovery import DnsDiscovery
from .configurator import Configurator
LOG = logging.getLogger(__name__)... | import argparse
import logging
import os
import re
import sys
from time import sleep
from kubernetes import config as k8s_config
# Import discovery before configurator as there is some monkeypatching going on
from .discovery import DnsDiscovery
from .configurator import Configurator
LOG = logging.getLogger(__name__)... | en | 0.952721 | # Import discovery before configurator as there is some monkeypatching going on | 2.099982 | 2 |
configdict.py | s-light/OLA_simple_fader | 0 | 6631896 | <filename>configdict.py
#!/usr/bin/env python
# coding=utf-8
"""
simple package to read and write configs in dict format to file.
supports two formats:
json (preferred)
ini (not implemented jet)
history:
see git commits
todo:
~ all fine :-)
"""
import sys
import os
impo... | <filename>configdict.py
#!/usr/bin/env python
# coding=utf-8
"""
simple package to read and write configs in dict format to file.
supports two formats:
json (preferred)
ini (not implemented jet)
history:
see git commits
todo:
~ all fine :-)
"""
import sys
import os
impo... | en | 0.429926 | #!/usr/bin/env python # coding=utf-8 simple package to read and write configs in dict format to file. supports two formats: json (preferred) ini (not implemented jet) history: see git commits todo: ~ all fine :-) # python3 # print("loaded python3 ConfigParser") # python2 #... | 3.370448 | 3 |
brutejudge/_http/ejudge/__init__.py | sleirsgoevy/brutejudge | 1 | 6631897 | <reponame>sleirsgoevy/brutejudge<filename>brutejudge/_http/ejudge/__init__.py
import ssl, socket, html, collections, urllib.parse, time, math
import brutejudge._http.ejudge.ej371, brutejudge._http.ejudge.ej373, brutejudge._http.html2md as html2md, brutejudge._http.types as bjtypes
from brutejudge._http.base import Back... | import ssl, socket, html, collections, urllib.parse, time, math
import brutejudge._http.ejudge.ej371, brutejudge._http.ejudge.ej373, brutejudge._http.html2md as html2md, brutejudge._http.types as bjtypes
from brutejudge._http.base import Backend
from brutejudge.error import BruteError
def _http_header_capitalize(h):
... | en | 0.250731 | #try: import requests #except ImportError: pass #else: # def do_http(url, method, headers, data=b''): # if method == 'GET': data = None # it = requests.request(method, url, data=data, headers=headers, allow_redirects=False) # return (it.status_code, it.headers, it.content) # @staticmethod # def ... | 2.824674 | 3 |
cinder/tests/test_rbd.py | cloudbau/cinder | 0 | 6631898 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012 <NAME>
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses... | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012 <NAME>
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses... | en | 0.720324 | # vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2012 <NAME> # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/... | 1.622343 | 2 |
1143. Longest Common Subsequence/1143. Longest Common Subsequence.py | JawadAsifBD/leetcode | 0 | 6631899 | class Solution:
def longestCommonSubsequence(self, text1, text2):
text1 = "!" + text1
text2 = "!" + text2
m, n = len(text1), len(text2)
dp = [[0] * n for _ in range(m)]
dp[0][0] = 1
for i, j in product(range(m), range(n)):
if text1[i] == text2[j]:
... | class Solution:
def longestCommonSubsequence(self, text1, text2):
text1 = "!" + text1
text2 = "!" + text2
m, n = len(text1), len(text2)
dp = [[0] * n for _ in range(m)]
dp[0][0] = 1
for i, j in product(range(m), range(n)):
if text1[i] == text2[j]:
... | none | 1 | 3.302524 | 3 | |
src/numerical/pure_python/rootfinding.py | wolfram74/magnetic_symmetry_project | 0 | 6631900 | <reponame>wolfram74/magnetic_symmetry_project<filename>src/numerical/pure_python/rootfinding.py
from scipy import optimize
import scipy
import symbolic_manipulations
import generate_equation
import numpy as np
import random
def find_solutions(positions, filename='Collage.png', iters=100):
# generate impo... | from scipy import optimize
import scipy
import symbolic_manipulations
import generate_equation
import numpy as np
import random
def find_solutions(positions, filename='Collage.png', iters=100):
# generate important functions
torque_function, potential_function, hessian_function = symbolic_manipula... | en | 0.916107 | # generate important functions Determine nature of a solution using the 2nd derivative (Hessian Matrix) # highly unlikely to happen # test near equality of two floats # seen_u: array of the potential energies of the solutions that have been found # seen: array of the corresponding rotations for each solution #print(sol... | 2.700298 | 3 |
tests/test_mixins.py | ejulio/web-poet | 0 | 6631901 | <reponame>ejulio/web-poet
import pytest
from web_poet.mixins import ResponseShortcutsMixin
from web_poet.page_inputs import ResponseData
class MyClass(ResponseShortcutsMixin):
def __init__(self, response: ResponseData):
self.response = response
@pytest.fixture
def my_instance(book_list_html_response):... | import pytest
from web_poet.mixins import ResponseShortcutsMixin
from web_poet.page_inputs import ResponseData
class MyClass(ResponseShortcutsMixin):
def __init__(self, response: ResponseData):
self.response = response
@pytest.fixture
def my_instance(book_list_html_response):
return MyClass(book_... | none | 1 | 2.492387 | 2 | |
tests/test_model/test_layer/test_squeeze_and_excitation_block.py | ZJCV/PyCls | 110 | 6631902 | <reponame>ZJCV/PyCls
# -*- coding: utf-8 -*-
"""
@date: 2020/12/14 下午7:14
@file: test_squeeze_and_excitation_block.py
@author: zj
@description:
"""
import torch
from zcls.model.layers.squeeze_and_excitation_block import SqueezeAndExcitationBlock1D, \
SqueezeAndExcitationBlock2D, SqueezeAndExcitationBlock3D
de... | # -*- coding: utf-8 -*-
"""
@date: 2020/12/14 下午7:14
@file: test_squeeze_and_excitation_block.py
@author: zj
@description:
"""
import torch
from zcls.model.layers.squeeze_and_excitation_block import SqueezeAndExcitationBlock1D, \
SqueezeAndExcitationBlock2D, SqueezeAndExcitationBlock3D
def test_squeeze_and_ex... | en | 0.530011 | # -*- coding: utf-8 -*- @date: 2020/12/14 下午7:14 @file: test_squeeze_and_excitation_block.py @author: zj @description: | 2.795754 | 3 |
susemanager/system.py | DreadlordGG/python-susemanager | 0 | 6631903 | <gh_stars>0
import xmlrpclib
class list:
def __init__(self, client, session):
self.session = session
self.client = client
def ActivationKeys(self, pid):
return self.client.system.listActivationKeys(self.session, sid)
@property
def ActiveSystems(self):
return self.client.system.listActiveSystem... | import xmlrpclib
class list:
def __init__(self, client, session):
self.session = session
self.client = client
def ActivationKeys(self, pid):
return self.client.system.listActivationKeys(self.session, sid)
@property
def ActiveSystems(self):
return self.client.system.listActiveSystems(self.sessi... | none | 1 | 2.277734 | 2 | |
test/id3v1.py | Taiko2k/stagger | 21 | 6631904 | #!/usr/bin/env python3
#
# id3v1.py
# From the stagger project: http://code.google.com/p/stagger/
#
# Copyright (c) 2009-2011 <NAME> <<EMAIL>>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#... | #!/usr/bin/env python3
#
# id3v1.py
# From the stagger project: http://code.google.com/p/stagger/
#
# Copyright (c) 2009-2011 <NAME> <<EMAIL>>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#... | en | 0.711061 | #!/usr/bin/env python3 # # id3v1.py # From the stagger project: http://code.google.com/p/stagger/ # # Copyright (c) 2009-2011 <NAME> <<EMAIL>> # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # ... | 1.417844 | 1 |
advanced_logger/json_encoder/django_json_encoder_copy.py | EveryMundo/python-advanced-logger | 0 | 6631905 | <reponame>EveryMundo/python-advanced-logger
"""
Copyright (c) Django Software Foundation and individual contributors.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source cod... | """
Copyright (c) Django Software Foundation and individual contributors.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
... | en | 0.7851 | Copyright (c) Django Software Foundation and individual contributors. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, ... | 1.161053 | 1 |
tests/test_dannet.py | eaksnes/dasem | 18 | 6631906 | """Test dasem.dannet."""
import pytest
from dasem.dannet import Dannet
@pytest.fixture
def dannet():
return Dannet()
def test_download(dannet):
dannet.download()
def test_glossary(dannet):
assert len(dannet.glossary('virksomhed')) == 3
| """Test dasem.dannet."""
import pytest
from dasem.dannet import Dannet
@pytest.fixture
def dannet():
return Dannet()
def test_download(dannet):
dannet.download()
def test_glossary(dannet):
assert len(dannet.glossary('virksomhed')) == 3
| de | 0.463148 | Test dasem.dannet. | 2.167121 | 2 |
tests/utils/synthetic_utils.py | hanlint/composer | 0 | 6631907 | from typing import Any, Dict, Optional, Type
import pytest
from composer.datasets import GLUEHparams, LMDatasetHparams
from composer.datasets.hparams import DatasetHparams, SyntheticHparamsMixin
from composer.datasets.synthetic_lm import generate_synthetic_tokenizer
from composer.models import (BERTForClassificationH... | from typing import Any, Dict, Optional, Type
import pytest
from composer.datasets import GLUEHparams, LMDatasetHparams
from composer.datasets.hparams import DatasetHparams, SyntheticHparamsMixin
from composer.datasets.synthetic_lm import generate_synthetic_tokenizer
from composer.models import (BERTForClassificationH... | en | 0.83342 | # configure Transformer-based models for synthetic testing # force a non-pretrained model # generate tokenizers and synthetic models # configure DeepLabV3 models for synthetic testing # prevent downloading pretrained weights during test # sync_bn throws an error when run on CPU | 2.229686 | 2 |
cycada/tools/util.py | Luodian/MADAN | 150 | 6631908 | from functools import partial
import torch
from torch.autograd import Variable
def make_variable(tensor, volatile=False, requires_grad=True):
if torch.cuda.is_available():
tensor = tensor.cuda()
if volatile:
requires_grad = False
return Variable(tensor, volatile=volatile, requires_grad=requires_grad)
def pa... | from functools import partial
import torch
from torch.autograd import Variable
def make_variable(tensor, volatile=False, requires_grad=True):
if torch.cuda.is_available():
tensor = tensor.cuda()
if volatile:
requires_grad = False
return Variable(tensor, volatile=volatile, requires_grad=requires_grad)
def pa... | none | 1 | 2.413425 | 2 | |
ml_project/tests/models/test_train_model.py | made-ml-in-prod-2021/liliyamakhmutova- | 0 | 6631909 | import os
import pickle
from typing import List, Tuple
import pandas as pd
import pytest
from py._path.local import LocalPath
from sklearn.linear_model import LogisticRegression
from src.data.make_dataset import read_data
from src.enities import TrainingParams
from src.enities.feature_params import FeatureParams
from... | import os
import pickle
from typing import List, Tuple
import pandas as pd
import pytest
from py._path.local import LocalPath
from sklearn.linear_model import LogisticRegression
from src.data.make_dataset import read_data
from src.enities import TrainingParams
from src.enities.feature_params import FeatureParams
from... | none | 1 | 2.393608 | 2 | |
common/schema.py | gtmills/Redfish-Service-Validator | 0 | 6631910 | # Copyright Notice:
# Copyright 2016-2020 DMTF. All rights reserved.
# License: BSD 3-Clause License. For full text see link: https://github.com/DMTF/Redfish-Service-Validator/blob/master/LICENSE.md
from collections import namedtuple
from bs4 import BeautifulSoup
from functools import lru_cache
import os.path
from co... | # Copyright Notice:
# Copyright 2016-2020 DMTF. All rights reserved.
# License: BSD 3-Clause License. For full text see link: https://github.com/DMTF/Redfish-Service-Validator/blob/master/LICENSE.md
from collections import namedtuple
from bs4 import BeautifulSoup
from functools import lru_cache
import os.path
from co... | en | 0.597794 | # Copyright Notice: # Copyright 2016-2020 DMTF. All rights reserved. # License: BSD 3-Clause License. For full text see link: https://github.com/DMTF/Redfish-Service-Validator/blob/master/LICENSE.md storeSchemaToLocal Moves data pulled from service/online to local schema storage Does NOT do so if preferonline... | 1.641743 | 2 |
rximp/api.py | freelancer1845/rx-imp-python | 0 | 6631911 | from rx.subject import Subject
from rx import Observable, defer, create
from rx.disposable import Disposable
from typing import Callable, Dict
from rx.operators import map, publish, filter, take_while, replay, do, share, take_until, take, do_action
import json
from types import FunctionType
from threading import Lock
... | from rx.subject import Subject
from rx import Observable, defer, create
from rx.disposable import Disposable
from typing import Callable, Dict
from rx.operators import map, publish, filter, take_while, replay, do, share, take_until, take, do_action
import json
from types import FunctionType
from threading import Lock
... | en | 0.713416 | Parameters --------- inObs : Observable<bytes> Observable<bytes> that the instance subscribes to in order to receive data packets. The Observable should emit objects of type bytes outSubject : Subject<bytes> Subscribe to the outSubject to publish messages (i. e. send the ... | 2.617522 | 3 |
core/machine/urls.py | rauanisanfelice/python-analise-credito | 2 | 6631912 | <reponame>rauanisanfelice/python-analise-credito
from django.contrib import admin
from django.urls import path, include
from django.contrib.auth import views as auth_views
from machine.views import *
urlpatterns = [
path('', index.as_view(), name='index'),
path('validacao/', validacao, name='validacao'),
]
| from django.contrib import admin
from django.urls import path, include
from django.contrib.auth import views as auth_views
from machine.views import *
urlpatterns = [
path('', index.as_view(), name='index'),
path('validacao/', validacao, name='validacao'),
] | none | 1 | 1.610818 | 2 | |
standalone/BC_plus_script.py | vwxyzjn/MineRL2021-Intro-baselines | 8 | 6631913 | <gh_stars>1-10
"""
Behavioural Cloning agent that trains on MineRLTreechop data. It is then evaluated on MineRLObtainDiamond by running it
for a certain number of steps and then switching to the scripted part that crafts a wooden_pickaxe and digs down to get
some cobblestone.
With default parameters it trains in 5-10 m... | """
Behavioural Cloning agent that trains on MineRLTreechop data. It is then evaluated on MineRLObtainDiamond by running it
for a certain number of steps and then switching to the scripted part that crafts a wooden_pickaxe and digs down to get
some cobblestone.
With default parameters it trains in 5-10 mins on a machin... | en | 0.814114 | Behavioural Cloning agent that trains on MineRLTreechop data. It is then evaluated on MineRLObtainDiamond by running it for a certain number of steps and then switching to the scripted part that crafts a wooden_pickaxe and digs down to get some cobblestone. With default parameters it trains in 5-10 mins on a machine wi... | 2.575444 | 3 |
download_alexnet_vlcs.py | belaalb/G2DM | 43 | 6631914 |
from google_drive_downloader import GoogleDriveDownloader as gdd
gdd.download_file_from_google_drive(file_id='1wUJTH1Joq2KAgrUDeKJghP1Wf7Q9w4z-',
dest_path='./alexnet_caffe.pth.tar',
unzip=False,
showsize=True... |
from google_drive_downloader import GoogleDriveDownloader as gdd
gdd.download_file_from_google_drive(file_id='1wUJTH1Joq2KAgrUDeKJghP1Wf7Q9w4z-',
dest_path='./alexnet_caffe.pth.tar',
unzip=False,
showsize=True... | en | 0.100935 | ## Download vlcs ## unzip ## Move to ./data/vlcs/prepared_data | 2.421149 | 2 |
beaker/services/image.py | allenai/beaker-py | 0 | 6631915 | <reponame>allenai/beaker-py<filename>beaker/services/image.py
from typing import TYPE_CHECKING, Dict, Optional, Union
from docker.models.images import Image as DockerImage
from ..data_model import *
from ..exceptions import *
from .service_client import ServiceClient
if TYPE_CHECKING:
from rich.progress import T... | from typing import TYPE_CHECKING, Dict, Optional, Union
from docker.models.images import Image as DockerImage
from ..data_model import *
from ..exceptions import *
from .service_client import ServiceClient
if TYPE_CHECKING:
from rich.progress import TaskID
class ImageClient(ServiceClient):
"""
Accessed... | en | 0.672215 | Accessed via :data:`Beaker.image <beaker.Beaker.image>`. Get info about an image on Beaker. :param image: The Beaker image ID or name. :raises ImageNotFound: If the image can't be found on Beaker. :raises HTTPError: Any other HTTP exception that can occur. # Could be an ID or full name, so we ... | 2.431826 | 2 |
blogtrans/blogger/BloggerImporter.py | miaout17/blogtrans | 3 | 6631916 | <filename>blogtrans/blogger/BloggerImporter.py
import codecs
import xml.etree.ElementTree as ET
from datetime import datetime
from blogtrans.data import *
# Blogger Import is not implemented yet
class BloggerImporter :
def __init__(self, filename) :
self.filename = filename
def parse(self) :
... | <filename>blogtrans/blogger/BloggerImporter.py
import codecs
import xml.etree.ElementTree as ET
from datetime import datetime
from blogtrans.data import *
# Blogger Import is not implemented yet
class BloggerImporter :
def __init__(self, filename) :
self.filename = filename
def parse(self) :
... | en | 0.5282 | # Blogger Import is not implemented yet #print entry.tag self.author = "" self.title = "" self.date = datetime.today() self.category = [] self.status = Article.PUBLISH self.allow_comments = True self.allow_pings = True #self.convert_breaks = True self.bod... | 2.886065 | 3 |
utils/feats2npy.py | roshansh-cmu/espnet | 0 | 6631917 | #!/usr/bin/env python
# coding: utf-8
import argparse
import os
import sys
from os.path import join
import numpy as np
from kaldiio import ReadHelper
def get_parser():
parser = argparse.ArgumentParser(
description="Convet kaldi-style features to numpy arrays",
formatter_class=argparse.ArgumentD... | #!/usr/bin/env python
# coding: utf-8
import argparse
import os
import sys
from os.path import join
import numpy as np
from kaldiio import ReadHelper
def get_parser():
parser = argparse.ArgumentParser(
description="Convet kaldi-style features to numpy arrays",
formatter_class=argparse.ArgumentD... | en | 0.325294 | #!/usr/bin/env python # coding: utf-8 | 3.110685 | 3 |
models/models.py | Luodian/Learning-Invariant-Representations-and-Risks | 17 | 6631918 | import torch
models = {}
__all__ = ['get_model']
def register_model(name):
def decorator(cls):
models[name] = cls
return cls
return decorator
def get_model(name, **args):
net = models[name].create(args)
if torch.cuda.is_available():
net = net.cuda()
return net
| import torch
models = {}
__all__ = ['get_model']
def register_model(name):
def decorator(cls):
models[name] = cls
return cls
return decorator
def get_model(name, **args):
net = models[name].create(args)
if torch.cuda.is_available():
net = net.cuda()
return net
| none | 1 | 2.58917 | 3 | |
test/unit/test_util.py | lukasfro/bayesopt4ros | 4 | 6631919 | #!/usr/bin/env python3
import numpy as np
import os
import pytest
import torch
from botorch.exceptions import BotorchTensorDimensionError
from botorch.utils.containers import TrainingData
from scipy.optimize import Bounds
from bayesopt4ros.data_handler import DataHandler
@pytest.fixture(params=[1, 3, 10])
def test... | #!/usr/bin/env python3
import numpy as np
import os
import pytest
import torch
from botorch.exceptions import BotorchTensorDimensionError
from botorch.utils.containers import TrainingData
from scipy.optimize import Bounds
from bayesopt4ros.data_handler import DataHandler
@pytest.fixture(params=[1, 3, 10])
def test... | en | 0.515579 | #!/usr/bin/env python3 Set up a simple dataset to test the DataHandler class. The dimensionality of the input data is specified by the fixture parameters. # Using initilizer for setting data # Using setter for setting data # Single data point # Multiple data points # Adding to empty DataHandler # Unequal number of ... | 2.362616 | 2 |
libs/QtGUI.py | haakonsh/FSR-Desktop | 0 | 6631920 | try:
import math
import sys
from PyQt4 import QtGui, QtCore
from random import randint
from time import sleep
except ImportError as ie:
print (str(ie))
# Catched if any packages are missing
missing = str(ie).split("named")[1]
print("Software needs %s installed\nPlease run pip instal... | try:
import math
import sys
from PyQt4 import QtGui, QtCore
from random import randint
from time import sleep
except ImportError as ie:
print (str(ie))
# Catched if any packages are missing
missing = str(ie).split("named")[1]
print("Software needs %s installed\nPlease run pip instal... | en | 0.717492 | # Catched if any packages are missing # 60 is added to the results in order to offset the HSV color. The HSV color RED is centered # around 0/360, this poses a problem where the minimum and maximum values are equal in color. # The fix is to offset the HSV value by 60. # saturation[j][i], 255, 255) # TODO Call HexGridWi... | 2.804955 | 3 |
src/utils/benchmark.py | krypt-n/vroom-scripts | 0 | 6631921 | # -*- coding: utf-8 -*-
import math
# TSPLIB canonic rounding.
def nint(x):
return int(x + 0.5);
def euc_2D(c1, c2, PRECISION = 1):
xd = c1[0] - c2[0]
yd = c1[1] - c2[1]
return nint(PRECISION * math.sqrt(xd * xd + yd * yd))
# Retrieve value for a one-liner TSPLIB entry.
def get_value(key, lines):
result = ... | # -*- coding: utf-8 -*-
import math
# TSPLIB canonic rounding.
def nint(x):
return int(x + 0.5);
def euc_2D(c1, c2, PRECISION = 1):
xd = c1[0] - c2[0]
yd = c1[1] - c2[1]
return nint(PRECISION * math.sqrt(xd * xd + yd * yd))
# Retrieve value for a one-liner TSPLIB entry.
def get_value(key, lines):
result = ... | en | 0.835303 | # -*- coding: utf-8 -*- # TSPLIB canonic rounding. # Retrieve value for a one-liner TSPLIB entry. # Also try with a space. # Separate index and coordinates. # Remove empty entries generated by multiple spaces. # Compute matrix based on ordered list of coordinates. | 2.759392 | 3 |
python/ray/train/checkpoint.py | johnpjust/ray | 21,382 | 6631922 | from dataclasses import dataclass
from typing import Optional
from ray.train.constants import TIMESTAMP
MAX = "max"
MIN = "min"
@dataclass
class CheckpointStrategy:
"""Configurable parameters for defining the Train checkpointing strategy.
Default behavior is to persist all checkpoints to disk. If
``num... | from dataclasses import dataclass
from typing import Optional
from ray.train.constants import TIMESTAMP
MAX = "max"
MIN = "min"
@dataclass
class CheckpointStrategy:
"""Configurable parameters for defining the Train checkpointing strategy.
Default behavior is to persist all checkpoints to disk. If
``num... | en | 0.853801 | Configurable parameters for defining the Train checkpointing strategy. Default behavior is to persist all checkpoints to disk. If ``num_to_keep`` is set, the default retention policy is to keep the checkpoints with maximum timestamp, i.e. the most recent checkpoints. Args: num_to_keep (Optiona... | 3.531015 | 4 |
doctor_visits/delphi_doctor_visits/smooth.py | qx-teo/covidcast-indicators | 8 | 6631923 | <reponame>qx-teo/covidcast-indicators
"""
This file contains various filters used to smooth the 1-d signals.
Code is courtesy of <NAME> (minor adjustments by Maria).
Author: <NAME>
Created: 2020-04-16
"""
import numpy as np
def moving_avg(x, y, k=7):
"""Smooth the y-values using a rolling window with k observa... | """
This file contains various filters used to smooth the 1-d signals.
Code is courtesy of <NAME> (minor adjustments by Maria).
Author: <NAME>
Created: 2020-04-16
"""
import numpy as np
def moving_avg(x, y, k=7):
"""Smooth the y-values using a rolling window with k observations.
Args:
x: indexing ... | en | 0.760162 | This file contains various filters used to smooth the 1-d signals. Code is courtesy of <NAME> (minor adjustments by Maria). Author: <NAME> Created: 2020-04-16 Smooth the y-values using a rolling window with k observations. Args: x: indexing array of the signal y: one dimensional signal to smooth ... | 3.571478 | 4 |
tricks/hashedEmbeddingBag/setup.py | yanzhoupan/dlrm_ssm | 3 | 6631924 | from setuptools import setup, Extension
from torch.utils.cpp_extension import BuildExtension, CUDAExtension
setup(
name='hashed_embedding_bag',
ext_modules=[CUDAExtension(
'hashed_embedding_bag',
[#'hashed_embedding_bag1.cpp',
'hashed_embedding_bag_kernel.cu'])],
py_module... | from setuptools import setup, Extension
from torch.utils.cpp_extension import BuildExtension, CUDAExtension
setup(
name='hashed_embedding_bag',
ext_modules=[CUDAExtension(
'hashed_embedding_bag',
[#'hashed_embedding_bag1.cpp',
'hashed_embedding_bag_kernel.cu'])],
py_module... | kn | 0.12984 | #'hashed_embedding_bag1.cpp', | 1.496127 | 1 |
test/mock.py | carefree0910/botorch | 0 | 6631925 | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
from collections import OrderedDict
from typing import List, Optional
import torch
from botorch.models.model import Model
from botorch.posteriors import Posterior
from torch import Tensor
EMPTY_SIZE = torch.Size()
class... | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
from collections import OrderedDict
from typing import List, Optional
import torch
from botorch.models.model import Model
from botorch.posteriors import Posterior
from torch import Tensor
EMPTY_SIZE = torch.Size()
class... | en | 0.812001 | #!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved Mock object that implements dummy methods and feeds through specified outputs Mock sample by repeating self._samples. If base_samples is provided, do a shape check but return the same mock samples. # check the base_sam... | 2.423484 | 2 |
oslo_privsep/tests/test_comm.py | mail2nsrajesh/oslo.privsep | 0 | 6631926 | # Copyright 2015 Rackspace Inc.
#
# 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 agr... | # Copyright 2015 Rackspace Inc.
#
# 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 agr... | en | 0.863705 | # Copyright 2015 Rackspace Inc. # # 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 agr... | 2.080408 | 2 |
example.py | ssmid/pewinput | 1 | 6631927 | <filename>example.py
#!/usr/bin/python3
import time
from pewinput import *
# create devices
keyboard = Device([KEY_LEFTSHIFT, KEY_SPACE, KEY_H, KEY_E, KEY_L, KEY_O, KEY_W, KEY_R, KEY_D, KEY_1, KEY_COMMA])
mouse = Mouse()
# type "Hello, World!"
keyboard.click_combination([KEY_LEFTSHIFT, KEY_H])
for key in [KEY_E, K... | <filename>example.py
#!/usr/bin/python3
import time
from pewinput import *
# create devices
keyboard = Device([KEY_LEFTSHIFT, KEY_SPACE, KEY_H, KEY_E, KEY_L, KEY_O, KEY_W, KEY_R, KEY_D, KEY_1, KEY_COMMA])
mouse = Mouse()
# type "Hello, World!"
keyboard.click_combination([KEY_LEFTSHIFT, KEY_H])
for key in [KEY_E, K... | en | 0.608465 | #!/usr/bin/python3 # create devices # type "Hello, World!" # alternatively you can simulate a key press yourself # ! # move mouse to the bottom right # move wheel # Optional, but recommended | 3.541053 | 4 |
src/tf/util/nrrdToTfrecordsLabels.py | juanprietob/gan-brain | 1 | 6631928 |
"""Converts NRRD data to TFRecords file format with Example protos."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import os
import sys
import glob
import tensorflow as tf
import nrrd
import numpy as np
from tensorflow.contrib.learn.py... |
"""Converts NRRD data to TFRecords file format with Example protos."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import os
import sys
import glob
import tensorflow as tf
import nrrd
import numpy as np
from tensorflow.contrib.learn.py... | en | 0.400848 | Converts NRRD data to TFRecords file format with Example protos. # Get the data. #label+=1 | 2.522555 | 3 |
authors/apps/authentication/tests/test_login.py | andela/ah-magnificent6 | 0 | 6631929 | """ module to test login. """
from django.urls import reverse
from rest_framework import status
from rest_framework.test import APITestCase
from authors.apps.authentication.models import User
class AuthenticationTests(APITestCase):
def setUp(self):
""" Setup data for the tests """
self.valid_user... | """ module to test login. """
from django.urls import reverse
from rest_framework import status
from rest_framework.test import APITestCase
from authors.apps.authentication.models import User
class AuthenticationTests(APITestCase):
def setUp(self):
""" Setup data for the tests """
self.valid_user... | en | 0.843727 | module to test login. Setup data for the tests Test that a user successfully logs in Test unsuccessful log in with a wrong email Test unsuccessful login for unregistered user. | 3.036034 | 3 |
projects/continual-lm/learner/static_per_domain_learner.py | germank/CommAI-env | 1 | 6631930 | <filename>projects/continual-lm/learner/static_per_domain_learner.py
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import torch
from torch import nn, optim
import model
... | <filename>projects/continual-lm/learner/static_per_domain_learner.py
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import torch
from torch import nn, optim
import model
... | en | 0.886316 | # Copyright (c) Facebook, Inc. and its affiliates. # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. # hacky way for avoiding saving all arguments :) | 1.952679 | 2 |
src/grokcore/component/tests/adapter/implementsmany.py | bielbienne/grokcore.component | 0 | 6631931 | """
Subclasses of grok.Adapter and grok.MultiAdapter must implement exactly one
interface:
>>> grok.testing.grok(__name__)
Traceback (most recent call last):
...
GrokError: <class 'grokcore.component.tests.adapter.implementsmany.Home'> is implementing
more than one interface (use grok.provides to specify w... | """
Subclasses of grok.Adapter and grok.MultiAdapter must implement exactly one
interface:
>>> grok.testing.grok(__name__)
Traceback (most recent call last):
...
GrokError: <class 'grokcore.component.tests.adapter.implementsmany.Home'> is implementing
more than one interface (use grok.provides to specify w... | en | 0.494384 | Subclasses of grok.Adapter and grok.MultiAdapter must implement exactly one interface: >>> grok.testing.grok(__name__) Traceback (most recent call last): ... GrokError: <class 'grokcore.component.tests.adapter.implementsmany.Home'> is implementing more than one interface (use grok.provides to specify which... | 2.091275 | 2 |
basic/count.py | aniketnaikdesai/anik-lib | 0 | 6631932 | def most_frequent_in_list(x):
return max(set(x), key = x.count)
| def most_frequent_in_list(x):
return max(set(x), key = x.count)
| none | 1 | 2.313483 | 2 | |
discovery-provider/src/monitors/monitoring_queue.py | atticwip/audius-protocol | 4 | 6631933 | import logging
import time
from src.monitors import monitor_names
from src.monitors.monitors import MONITORS, get_monitor_redis_key
from src.tasks.celery_app import celery
logger = logging.getLogger(__name__)
def refresh(redis, db, monitor):
"""
Refreshes the cached value for a monitor
Args:
red... | import logging
import time
from src.monitors import monitor_names
from src.monitors.monitors import MONITORS, get_monitor_redis_key
from src.tasks.celery_app import celery
logger = logging.getLogger(__name__)
def refresh(redis, db, monitor):
"""
Refreshes the cached value for a monitor
Args:
red... | en | 0.779559 | Refreshes the cached value for a monitor Args: redis: Singleton redis instance db: Singleton database instance monitor: dict The monitor dictionary qwith name, func, ttl, and type # Invoke the monitor function with kwargs for db and redis. # This allows any monitor to access the db and/or r... | 2.63873 | 3 |
venv/lib/python3.8/site-packages/tmdbv3api/objs/genre.py | lfbox7/flixster-kivy | 0 | 6631934 | <filename>venv/lib/python3.8/site-packages/tmdbv3api/objs/genre.py
from tmdbv3api.tmdb import TMDb
class Genre(TMDb):
_urls = {"movie_list": "/genre/movie/list", "tv_list": "/genre/tv/list"}
def movie_list(self):
return self._get_obj(self._call(self._urls["movie_list"], ""), key="genres")
def tv... | <filename>venv/lib/python3.8/site-packages/tmdbv3api/objs/genre.py
from tmdbv3api.tmdb import TMDb
class Genre(TMDb):
_urls = {"movie_list": "/genre/movie/list", "tv_list": "/genre/tv/list"}
def movie_list(self):
return self._get_obj(self._call(self._urls["movie_list"], ""), key="genres")
def tv... | none | 1 | 2.247025 | 2 | |
Lecture_04/hw_02_while_loop.py | YouWatanabe/fp | 0 | 6631935 | def gcd(x, y):
while y > 0:
x, y = y, x % y
return x
print(gcd(24, 32))
| def gcd(x, y):
while y > 0:
x, y = y, x % y
return x
print(gcd(24, 32))
| none | 1 | 3.516458 | 4 | |
tests/external_plugins/external_plugin.py | vbabiy/Flexget | 0 | 6631936 | <filename>tests/external_plugins/external_plugin.py
from __future__ import unicode_literals, division, absolute_import
from flexget import plugin
from flexget.entry import Entry
from flexget.event import event
class ExternalPlugin(object):
schema = {'type': 'boolean'}
def on_task_input(self, task, config):
... | <filename>tests/external_plugins/external_plugin.py
from __future__ import unicode_literals, division, absolute_import
from flexget import plugin
from flexget.entry import Entry
from flexget.event import event
class ExternalPlugin(object):
schema = {'type': 'boolean'}
def on_task_input(self, task, config):
... | none | 1 | 1.769075 | 2 | |
blog/extensions/auth/forms.py | victorcto/blog | 0 | 6631937 | import wtforms as wtf
from flask_wtf import FlaskForm
class SignInForm(FlaskForm):
username = wtf.StringField('Username', [wtf.validators.DataRequired()])
password = wtf.PasswordField('Password', [wtf.validators.DataRequired()])
remember_me = wtf.BooleanField('Remember me')
submit = wtf.SubmitField('S... | import wtforms as wtf
from flask_wtf import FlaskForm
class SignInForm(FlaskForm):
username = wtf.StringField('Username', [wtf.validators.DataRequired()])
password = wtf.PasswordField('Password', [wtf.validators.DataRequired()])
remember_me = wtf.BooleanField('Remember me')
submit = wtf.SubmitField('S... | none | 1 | 2.589349 | 3 | |
python/wx/foo.py | rha1063/misc | 0 | 6631938 | '''this is a doc string'''
class Bar:
'this is also a doc string'
def b(self):
'this is a third doc string'
def Car():
'this is a fourth doc string'
| '''this is a doc string'''
class Bar:
'this is also a doc string'
def b(self):
'this is a third doc string'
def Car():
'this is a fourth doc string'
| en | 0.762826 | this is a doc string | 2.207494 | 2 |
qrplay.py | foldedpaper/qrocodile | 0 | 6631939 | <gh_stars>0
#!/usr/bin/python
import logging
import argparse
import json
import os
import pickle
import subprocess
import sys
from time import sleep
import RPi.GPIO as GPIO
import spotipy
import spotipy.util as util
import soco
from soco.data_structures import DidlItem, DidlResource
# Set up logfile
LOG_FORMAT = '%(l... | #!/usr/bin/python
import logging
import argparse
import json
import os
import pickle
import subprocess
import sys
from time import sleep
import RPi.GPIO as GPIO
import spotipy
import spotipy.util as util
import soco
from soco.data_structures import DidlItem, DidlResource
# Set up logfile
LOG_FORMAT = '%(levelname)s %... | en | 0.847989 | #!/usr/bin/python # Set up logfile #filename = 'qrplay.log', #filemode = 'w', # check python version # set up GPIO for wired LED # make sure it's turned on # load defaults from my_defaults.txt # set spotify authentication variables # set player uuid for use in building album URIs # Parse the command line arguments # se... | 2.381895 | 2 |
paddle/dummy_provider.py | tensor-tang/DeepSpeech2 | 0 | 6631940 | #import io, os
import numpy as np
from paddle.trainer.PyDataProvider2 import *
def initHook(settings, uttLengths, counts, lblLengths, batch_size, **kwargs):
settings.uttLengths = uttLengths
settings.counts = counts
settings.lblLengths = lblLengths
settings.freqBins = kwargs.get('freqBins', 161)
set... | #import io, os
import numpy as np
from paddle.trainer.PyDataProvider2 import *
def initHook(settings, uttLengths, counts, lblLengths, batch_size, **kwargs):
settings.uttLengths = uttLengths
settings.counts = counts
settings.lblLengths = lblLengths
settings.freqBins = kwargs.get('freqBins', 161)
set... | en | 0.238235 | #import io, os # TODO: in real data should consider more # fixed dim # classes range # min_pool_size=-1, cache=CacheType.CACHE_PASS_IN_MEM) # just for more space of random table #(1500+1000, 161) # TODO: range (0~max) or (1~max-1) #print(data_table.shape, label_table.shape) # [0, len) #print ("data range", dat_start_id... | 2.087668 | 2 |
add_cookie.py | WYEEE/JDMemberCloseAccount | 0 | 6631941 | import re
from utils.config import get_config
from utils.selenium_browser import get_browser
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import WebDriverException
... | import re
from utils.config import get_config
from utils.selenium_browser import get_browser
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import WebDriverException
... | zh | 0.748964 | 用于获取手机端cookie | 2.507674 | 3 |
gir2cpp/typeref.py | sakhnik/git2cpp | 1 | 6631942 | <filename>gir2cpp/typeref.py
from .xml import Xml
from .config import Config
import xml.etree.ElementTree as ET
class TypeRef:
def __init__(self, et: ET, namespace, xml: Xml, config: Config):
self.namespace = namespace
# Pass through the output parameters for now
self.is_out = et.attrib.ge... | <filename>gir2cpp/typeref.py
from .xml import Xml
from .config import Config
import xml.etree.ElementTree as ET
class TypeRef:
def __init__(self, et: ET, namespace, xml: Xml, config: Config):
self.namespace = namespace
# Pass through the output parameters for now
self.is_out = et.attrib.ge... | en | 0.575047 | # Pass through the output parameters for now # Resolve clash with the namespace | 2.681972 | 3 |
tritam_customer/models/tritam_country_state.py | kenysmile/test_facebook | 0 | 6631943 | # -*- coding: utf-8 -*-
from odoo import models, fields, api, _
import logging
import datetime
from odoo.exceptions import UserError
class tritam_country(models.Model):
_inherit = 'res.country'
x_country_code = fields.Char('Mã tỉnh VTP')
ems_country_code = fields.Char('Mã tỉnh EMS')
class tritam_countr... | # -*- coding: utf-8 -*-
from odoo import models, fields, api, _
import logging
import datetime
from odoo.exceptions import UserError
class tritam_country(models.Model):
_inherit = 'res.country'
x_country_code = fields.Char('Mã tỉnh VTP')
ems_country_code = fields.Char('Mã tỉnh EMS')
class tritam_countr... | en | 0.769321 | # -*- coding: utf-8 -*- | 1.894623 | 2 |
imaginaire/model_utils/rename_inputs.py | hw07216/imaginaire | 3,308 | 6631944 | <filename>imaginaire/model_utils/rename_inputs.py
# Copyright (C) 2021 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
#
# This work is made available under the Nvidia Source Code License-NC.
# To view a copy of this license, check out LICENSE.md
def rename_inputs(cfg, is_inference, data):
assert hasattr(c... | <filename>imaginaire/model_utils/rename_inputs.py
# Copyright (C) 2021 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
#
# This work is made available under the Nvidia Source Code License-NC.
# To view a copy of this license, check out LICENSE.md
def rename_inputs(cfg, is_inference, data):
assert hasattr(c... | en | 0.825102 | # Copyright (C) 2021 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # # This work is made available under the Nvidia Source Code License-NC. # To view a copy of this license, check out LICENSE.md # Delete the old key. | 1.990435 | 2 |
scripts/build/check_release.py | exasol/sphinx-github-pages-generator | 0 | 6631945 | <gh_stars>0
import re
from pathlib import Path
from git import Repo
import toml
def get_git_version():
repo = Repo()
assert not repo.bare
tag_strings = [t.name for t in repo.tags]
tag_strings.sort(reverse=True)
if len(tag_strings) > 0:
latest_tag = tag_strings[0].strip()
retu... | import re
from pathlib import Path
from git import Repo
import toml
def get_git_version():
repo = Repo()
assert not repo.bare
tag_strings = [t.name for t in repo.tags]
tag_strings.sort(reverse=True)
if len(tag_strings) > 0:
latest_tag = tag_strings[0].strip()
return latest_ta... | en | 0.837452 | # Path overloads __truediv__ # Search for the FIRST pattern like: "* [0.5.0](changes_0.5.0.md)" in the changelog file. # Note that we encapsulate the [(0.5.0)] with parenthesis, which tells re to return the matching string as group # We expect that the current version in pyproject.toml is alway greater than the latest ... | 2.721006 | 3 |
tests/test_pta.py | AaronDJohnson/enterprise | 35 | 6631946 | <reponame>AaronDJohnson/enterprise
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
test_pta
----------------------------------
Tests for common signal and PTA class modules.
"""
# import os
# import pickle
import itertools
import unittest
import numpy as np
from enterprise.pulsar import Pulsar
from enterprise.s... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
test_pta
----------------------------------
Tests for common signal and PTA class modules.
"""
# import os
# import pickle
import itertools
import unittest
import numpy as np
from enterprise.pulsar import Pulsar
from enterprise.signals import gp_signals, parameter... | en | 0.854427 | #!/usr/bin/env python # -*- coding: utf-8 -*- test_pta ---------------------------------- Tests for common signal and PTA class modules. # import os # import pickle # note function is now defined in enterprise.signals.parameter Setup the Pulsar object. # two common processes, sharing basis partially # + vrn # two comm... | 2.200942 | 2 |
dependencies/rdflib/plugins/serializers/trig.py | situx/geowebannotation | 8 | 6631947 | """
Trig RDF graph serializer for RDFLib.
See <http://www.w3.org/TR/trig/> for syntax specification.
"""
from collections import defaultdict
from rdflib.plugins.serializers.turtle import TurtleSerializer, _GEN_QNAME_FOR_DT, VERB
from rdflib.term import BNode, Literal
__all__ = ['TrigSerializer']
class TrigSeriali... | """
Trig RDF graph serializer for RDFLib.
See <http://www.w3.org/TR/trig/> for syntax specification.
"""
from collections import defaultdict
from rdflib.plugins.serializers.turtle import TurtleSerializer, _GEN_QNAME_FOR_DT, VERB
from rdflib.term import BNode, Literal
__all__ = ['TrigSerializer']
class TrigSeriali... | en | 0.354563 | Trig RDF graph serializer for RDFLib. See <http://www.w3.org/TR/trig/> for syntax specification. | 2.319793 | 2 |
ss.py | MahaEzzat/Lane-Keeping-Using-Reinforcement-Learning | 0 | 6631948 | <filename>ss.py
import numpy
import pandas
import Qtable
import re
import carState
import GetState2
table = Qtable.maketable()
table.to_csv("../input_path/Qtable.csv",index=False)
print(table.loc[79][1])
| <filename>ss.py
import numpy
import pandas
import Qtable
import re
import carState
import GetState2
table = Qtable.maketable()
table.to_csv("../input_path/Qtable.csv",index=False)
print(table.loc[79][1])
| none | 1 | 2.332222 | 2 | |
multiple-languages/python/ros-cdk-fc-1.0.3/src/ros_cdk_fc/__init__.py | aliyun/Resource-Orchestration-Service-Cloud-Development-K | 15 | 6631949 | '''
## Aliyun ROS FC Construct Library
This module is part of the AliCloud ROS Cloud Development Kit (ROS CDK) project.
```python
# Example automatically generated from non-compiling source. May contain errors.
import * as FC from '@alicloud/ros-cdk-fc';
```
'''
import abc
import builtins
import datetime
import enum
... | '''
## Aliyun ROS FC Construct Library
This module is part of the AliCloud ROS Cloud Development Kit (ROS CDK) project.
```python
# Example automatically generated from non-compiling source. May contain errors.
import * as FC from '@alicloud/ros-cdk-fc';
```
'''
import abc
import builtins
import datetime
import enum
... | en | 0.657899 | ## Aliyun ROS FC Construct Library This module is part of the AliCloud ROS Cloud Development Kit (ROS CDK) project. ```python # Example automatically generated from non-compiling source. May contain errors. import * as FC from '@alicloud/ros-cdk-fc'; ``` A ROS resource type: ``ALIYUN::FC::Alias``. Create a new ``ALI... | 1.980103 | 2 |
open_spiel/python/algorithms/policy_gradient.py | asmith26/open_spiel | 0 | 6631950 | <filename>open_spiel/python/algorithms/policy_gradient.py
# Copyright 2019 DeepMind Technologies Ltd. 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.a... | <filename>open_spiel/python/algorithms/policy_gradient.py
# Copyright 2019 DeepMind Technologies Ltd. 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.a... | en | 0.836105 | # Copyright 2019 DeepMind Technologies Ltd. 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 appl... | 2.289402 | 2 |