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 |
|---|---|---|---|---|---|---|---|---|---|---|
electrondiffraction/__init__.py | drix00/ElectronDiffraction | 1 | 2500 | # -*- coding: utf-8 -*-
__author__ = """<NAME>"""
__email__ = '<EMAIL>'
__version__ = '0.1.0'
| # -*- coding: utf-8 -*-
__author__ = """<NAME>"""
__email__ = '<EMAIL>'
__version__ = '0.1.0'
| en | 0.674552 | # -*- coding: utf-8 -*- <NAME> | 1.052987 | 1 |
storelet.py | markembling/storelet | 1 | 2501 | import os
import logging
from tempfile import mkstemp, mkdtemp
from shutil import rmtree
from zipfile import ZipFile, ZIP_DEFLATED
from datetime import datetime
from boto.s3.connection import S3Connection
from boto.s3.key import Key
__version__ = "0.1.8"
__author__ = "<NAME>"
__email__ = "<EMAIL>"
logger = logging.ge... | import os
import logging
from tempfile import mkstemp, mkdtemp
from shutil import rmtree
from zipfile import ZipFile, ZIP_DEFLATED
from datetime import datetime
from boto.s3.connection import S3Connection
from boto.s3.key import Key
__version__ = "0.1.8"
__author__ = "<NAME>"
__email__ = "<EMAIL>"
logger = logging.ge... | en | 0.908464 | Convenience function for setting up some sane logging defaults A compressed ZIP file backup Note: large inclusion operations can sometimes take time as files are compressed on the fly. This prevents all the files being copied to a temporary location (and using unnecessary extra space) and storing up... | 2.49759 | 2 |
apps/delivery/migrations/0001_initial.py | jimforit/lagou | 2 | 2502 | # Generated by Django 2.0.2 on 2019-03-08 13:03
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Delivery',
fields=[
('create_time', models.... | # Generated by Django 2.0.2 on 2019-03-08 13:03
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Delivery',
fields=[
('create_time', models.... | en | 0.781297 | # Generated by Django 2.0.2 on 2019-03-08 13:03 | 1.886327 | 2 |
elementary/date-and-time-convertor.py | vargad/exercises | 1 | 2503 | #!/usr/bin/env python3
def date_time(time):
months = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"]
hour, minute = int(time[11:13]), int(time[14:16])
return f"{int(time[0:2])} {months[int(time[3:5])-1]} {time[6:10]} year {h... | #!/usr/bin/env python3
def date_time(time):
months = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"]
hour, minute = int(time[11:13]), int(time[14:16])
return f"{int(time[0:2])} {months[int(time[3:5])-1]} {time[6:10]} year {h... | fr | 0.221828 | #!/usr/bin/env python3 | 4.152859 | 4 |
lbry/wallet/server/peer.py | snapperVibes/lbry-sdk | 2 | 2504 | <reponame>snapperVibes/lbry-sdk
# Copyright (c) 2017, <NAME>
#
# All rights reserved.
#
# The MIT License (MIT)
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, includin... | # Copyright (c) 2017, <NAME>
#
# All rights reserved.
#
# The MIT License (MIT)
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the right... | en | 0.860631 | # Copyright (c) 2017, <NAME> # # All rights reserved. # # The MIT License (MIT) # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the right... | 1.708304 | 2 |
tests/components/deconz/test_diagnostics.py | aomann/core | 0 | 2505 | """Test deCONZ diagnostics."""
from unittest.mock import patch
from pydeconz.websocket import STATE_RUNNING
from homeassistant.const import Platform
from .test_gateway import DECONZ_CONFIG, setup_deconz_integration
from tests.components.diagnostics import get_diagnostics_for_config_entry
async def test_entry_dia... | """Test deCONZ diagnostics."""
from unittest.mock import patch
from pydeconz.websocket import STATE_RUNNING
from homeassistant.const import Platform
from .test_gateway import DECONZ_CONFIG, setup_deconz_integration
from tests.components.diagnostics import get_diagnostics_for_config_entry
async def test_entry_dia... | en | 0.582065 | Test deCONZ diagnostics. Test config entry diagnostics. | 2.005238 | 2 |
jax_md/partition.py | l1zp/jax-md | 0 | 2506 | <filename>jax_md/partition.py
# Copyright 2019 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... | <filename>jax_md/partition.py
# Copyright 2019 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... | en | 0.844052 | # Copyright 2019 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, ... | 2.349307 | 2 |
rhucrl_experiments/evaluate/launch_evaluate_mass.py | sebascuri/rhucrl | 1 | 2507 | <filename>rhucrl_experiments/evaluate/launch_evaluate_mass.py<gh_stars>1-10
"""Run from rhucrl_experiments.evaluate folder."""
import socket
from lsf_runner import init_runner, make_commands
from rhucrl_experiments.evaluate.utilities import ENVIRONMENTS
RARL_DIR = "../../runs/RARLAgent"
ZERO_SUM_DIR = "../../runs/Ze... | <filename>rhucrl_experiments/evaluate/launch_evaluate_mass.py<gh_stars>1-10
"""Run from rhucrl_experiments.evaluate folder."""
import socket
from lsf_runner import init_runner, make_commands
from rhucrl_experiments.evaluate.utilities import ENVIRONMENTS
RARL_DIR = "../../runs/RARLAgent"
ZERO_SUM_DIR = "../../runs/Ze... | en | 0.776694 | Run from rhucrl_experiments.evaluate folder. | 1.842102 | 2 |
src/sentry/api/endpoints/project_tags.py | seukjung/sentry-custom | 1 | 2508 | <filename>src/sentry/api/endpoints/project_tags.py
from __future__ import absolute_import
import six
from rest_framework.response import Response
from sentry.api.bases.project import ProjectEndpoint
from sentry.models import TagKey, TagKeyStatus
class ProjectTagsEndpoint(ProjectEndpoint):
def get(self, request... | <filename>src/sentry/api/endpoints/project_tags.py
from __future__ import absolute_import
import six
from rest_framework.response import Response
from sentry.api.bases.project import ProjectEndpoint
from sentry.models import TagKey, TagKeyStatus
class ProjectTagsEndpoint(ProjectEndpoint):
def get(self, request... | none | 1 | 2.063293 | 2 | |
examples/02 - callbacks/callbacks.py | TensorTom/async-Eel | 9 | 2509 | from __future__ import print_function # For Py2/3 compatibility
import async_eel
import random
import asyncio
loop = asyncio.get_event_loop()
@async_eel.expose
async def py_random():
return random.random()
async def print_num(n):
"""callback of js_random"""
print('Got this from Javascript:', n)
asyn... | from __future__ import print_function # For Py2/3 compatibility
import async_eel
import random
import asyncio
loop = asyncio.get_event_loop()
@async_eel.expose
async def py_random():
return random.random()
async def print_num(n):
"""callback of js_random"""
print('Got this from Javascript:', n)
asyn... | en | 0.578105 | # For Py2/3 compatibility callback of js_random # Call Javascript function, and pass explicit callback function # Do the same with an inline callback | 3.106273 | 3 |
datacube/index/_api.py | AMA-AC/datacube-core | 2 | 2510 | <reponame>AMA-AC/datacube-core
# coding=utf-8
"""
Access methods for indexing datasets & products.
"""
import logging
from datacube.config import LocalConfig
from datacube.drivers import index_driver_by_name, index_drivers
from .index import Index
_LOG = logging.getLogger(__name__)
def index_connect(local_config=N... | # coding=utf-8
"""
Access methods for indexing datasets & products.
"""
import logging
from datacube.config import LocalConfig
from datacube.drivers import index_driver_by_name, index_drivers
from .index import Index
_LOG = logging.getLogger(__name__)
def index_connect(local_config=None, application_name=None, val... | en | 0.671449 | # coding=utf-8 Access methods for indexing datasets & products. # type: (LocalConfig, str, bool) -> Index Create a Data Cube Index that can connect to a PostgreSQL server It contains all the required connection parameters, but doesn't actually check that the server is available. :param application_name: A... | 3.072006 | 3 |
pgarchives/loader/load_message.py | WeilerWebServices/PostgreSQL | 0 | 2511 | <filename>pgarchives/loader/load_message.py
#!/usr/bin/env python3
#
# load_message.py - takes a single email or mbox formatted
# file on stdin or in a file and reads it into the database.
#
import os
import sys
from optparse import OptionParser
from configparser import ConfigParser
import psycopg2
from lib.storage... | <filename>pgarchives/loader/load_message.py
#!/usr/bin/env python3
#
# load_message.py - takes a single email or mbox formatted
# file on stdin or in a file and reads it into the database.
#
import os
import sys
from optparse import OptionParser
from configparser import ConfigParser
import psycopg2
from lib.storage... | en | 0.865675 | #!/usr/bin/env python3 # # load_message.py - takes a single email or mbox formatted # file on stdin or in a file and reads it into the database. # # We also put the data in the db. This happens in the main transaction # so if the whole script dies, it goes away... # Take an advisory lock to force serialization. # We co... | 2.688035 | 3 |
shop/migrations/0009_auto_20200310_1430.py | manson800819/test | 0 | 2512 | <filename>shop/migrations/0009_auto_20200310_1430.py
# -*- coding: utf-8 -*-
# Generated by Django 1.11.29 on 2020-03-10 14:30
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('shop'... | <filename>shop/migrations/0009_auto_20200310_1430.py
# -*- coding: utf-8 -*-
# Generated by Django 1.11.29 on 2020-03-10 14:30
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('shop'... | en | 0.680465 | # -*- coding: utf-8 -*- # Generated by Django 1.11.29 on 2020-03-10 14:30 | 1.357308 | 1 |
lib/dataset/iNaturalist.py | jrcai/ACE | 18 | 2513 | from dataset.baseset import BaseSet
import random, cv2
import numpy as np
class iNaturalist(BaseSet):
def __init__(self, mode='train', cfg=None, transform=None):
super(iNaturalist, self).__init__(mode, cfg, transform)
random.seed(0)
self.class_dict = self._get_class_dict()
... | from dataset.baseset import BaseSet
import random, cv2
import numpy as np
class iNaturalist(BaseSet):
def __init__(self, mode='train', cfg=None, transform=None):
super(iNaturalist, self).__init__(mode, cfg, transform)
random.seed(0)
self.class_dict = self._get_class_dict()
... | none | 1 | 2.586764 | 3 | |
tests/test_conferences.py | mattclark/osf.io | 0 | 2514 | # -*- coding: utf-8 -*-
import mock
from nose.tools import * # noqa (PEP8 asserts)
import hmac
import hashlib
from StringIO import StringIO
from django.core.exceptions import ValidationError
from django.db import IntegrityError
import furl
from framework.auth import get_or_create_user
from framework.auth.core impo... | # -*- coding: utf-8 -*-
import mock
from nose.tools import * # noqa (PEP8 asserts)
import hmac
import hashlib
from StringIO import StringIO
from django.core.exceptions import ValidationError
from django.db import IntegrityError
import furl
from framework.auth import get_or_create_user
from framework.auth.core impo... | en | 0.812902 | # -*- coding: utf-8 -*- # noqa (PEP8 asserts) # inject bad data # Delete only contributor # in order to access m2m fields, e.g. tags # in order to access m2m fields, e.g. tags # user's shouldn't be able to use email as fullname, so we use the guid. # Create conference nodes # Create conference nodes # Create a non-conf... | 2.011069 | 2 |
socket_tentacles/__init__.py | innovationgarage/socket-tentacles | 0 | 2515 | import socketserver
import socket
import sys
import threading
import json
import queue
import time
import datetime
import traceback
class TCPServer(socketserver.ThreadingMixIn, socketserver.TCPServer):
def server_bind(self):
self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.soc... | import socketserver
import socket
import sys
import threading
import json
import queue
import time
import datetime
import traceback
class TCPServer(socketserver.ThreadingMixIn, socketserver.TCPServer):
def server_bind(self):
self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.soc... | en | 0.797855 | self.conn is a socket object, self.file a file wrapper for that socket | 2.716665 | 3 |
G5/DerivedData/ParameterProbing/checkme.py | shooking/ZoomPedalFun | 9 | 2516 | # -*- coding: ascii -*-
import sys
import json
def check(data):
OnOffstart = data.find(b"OnOff")
if OnOffstart != -1:
fxName=""
OnOffblockSize = 0x30
for j in range(12):
if data[OnOffstart + j + OnOffblockSize] == 0x00:
break
fxName ... | # -*- coding: ascii -*-
import sys
import json
def check(data):
OnOffstart = data.find(b"OnOff")
if OnOffstart != -1:
fxName=""
OnOffblockSize = 0x30
for j in range(12):
if data[OnOffstart + j + OnOffblockSize] == 0x00:
break
fxName ... | en | 0.271779 | # -*- coding: ascii -*- #print("OnOffStart at {}".format(OnOffstart)) # this is WAY too large, let except break the loop if not ( data[OnOffstart + (j+1) * OnOffblockSize - 1] == 0x00
and data[OnOffstart + (j+1) * OnOffblockSize - 2] == 0x00):
# ZD2 format has a length and P... | 2.56817 | 3 |
leehao/learn63.py | pilihaotian/pythonlearning | 1 | 2517 | # 随机6位密码 a-zA-Z0-9下划线
import random
source = ''
lower_char = [chr(x) for x in range(ord('a'), ord('z') + 1)]
upper_char = [chr(x) for x in range(ord('A'), ord('Z') + 1)]
number_char = [chr(x) for x in range(ord('0'), ord('9') + 1)]
source += "".join(lower_char)
source += "".join(upper_char)
source += "".join(number_ch... | # 随机6位密码 a-zA-Z0-9下划线
import random
source = ''
lower_char = [chr(x) for x in range(ord('a'), ord('z') + 1)]
upper_char = [chr(x) for x in range(ord('A'), ord('Z') + 1)]
number_char = [chr(x) for x in range(ord('0'), ord('9') + 1)]
source += "".join(lower_char)
source += "".join(upper_char)
source += "".join(number_ch... | zh | 0.917812 | # 随机6位密码 a-zA-Z0-9下划线 # 随机取出20位字符串,包括下划线 | 3.607636 | 4 |
gbic/tests.py | fga-eps-mds/2017.2-SiGI-Op_API | 6 | 2518 | from django.test import TestCase
from rest_framework.test import APIRequestFactory
from .models import GBIC, GBICType
from .views import GBICListViewSet
# Create your tests here.
class GBICTest(TestCase):
def test_gbic_view_set(self):
request = APIRequestFactory().get("")
gbic_detail = GBICListVi... | from django.test import TestCase
from rest_framework.test import APIRequestFactory
from .models import GBIC, GBICType
from .views import GBICListViewSet
# Create your tests here.
class GBICTest(TestCase):
def test_gbic_view_set(self):
request = APIRequestFactory().get("")
gbic_detail = GBICListVi... | en | 0.95562 | # Create your tests here. | 2.125281 | 2 |
fruits/core/fruit.py | alienkrieg/fruits | 4 | 2519 | import inspect
from typing import List, Union, Set, Any
import numpy as np
from fruits.cache import Cache, CoquantileCache
from fruits.scope import force_input_shape, FitTransform
from fruits.core.callback import AbstractCallback
from fruits.signature.iss import SignatureCalculator, CachePlan
from fruits.words.word i... | import inspect
from typing import List, Union, Set, Any
import numpy as np
from fruits.cache import Cache, CoquantileCache
from fruits.scope import force_input_shape, FitTransform
from fruits.core.callback import AbstractCallback
from fruits.signature.iss import SignatureCalculator, CachePlan
from fruits.words.word i... | en | 0.760513 | Feature Extractor using iterated sums. A Fruit consists of a number of :class:`~fruits.core.fruit.FruitBranch` objects. At the end of the pipeline, each branch returns their own features and they will be concatenated by this class. A simple example (using two branches): .. code-block:: python... | 2.540952 | 3 |
workoutizer/__main__.py | pa3kDaWae/workoutizer | 0 | 2520 | <filename>workoutizer/__main__.py<gh_stars>0
import os
import argparse
import subprocess
import socket
import sys
import click
from django.core.management import execute_from_command_line
from workoutizer.settings import WORKOUTIZER_DIR, WORKOUTIZER_DB_PATH, TRACKS_DIR
from workoutizer import __version__
BASE_DIR = ... | <filename>workoutizer/__main__.py<gh_stars>0
import os
import argparse
import subprocess
import socket
import sys
import click
from django.core.management import execute_from_command_line
from workoutizer.settings import WORKOUTIZER_DIR, WORKOUTIZER_DB_PATH, TRACKS_DIR
from workoutizer import __version__
BASE_DIR = ... | en | 0.976594 | # we remove blanks around keys, as is logical | 2.291528 | 2 |
bcbio/bam/trim.py | matanhofree/bcbio-nextgen | 1 | 2521 | """Provide trimming of input reads from Fastq or BAM files.
"""
import os
import sys
import tempfile
from bcbio.utils import (file_exists, safe_makedir,
replace_suffix, append_stem, is_pair,
replace_directory, map_wrap)
from bcbio.log import logger
from bcbio.bam impor... | """Provide trimming of input reads from Fastq or BAM files.
"""
import os
import sys
import tempfile
from bcbio.utils import (file_exists, safe_makedir,
replace_suffix, append_stem, is_pair,
replace_directory, map_wrap)
from bcbio.log import logger
from bcbio.bam impor... | en | 0.908106 | Provide trimming of input reads from Fastq or BAM files. # fall back on Cutadapt if AlienTrimmer is not installed # XXX: remove after it has been live for a while for small insert sizes, the read length can be longer than the insert resulting in the reverse complement of the 3' adapter being sequenced. this tak... | 2.069131 | 2 |
FEniCSUI/AnalysesHub/views.py | nasserarbabi/FEniCSUI-dev | 0 | 2522 | <filename>FEniCSUI/AnalysesHub/views.py
from rest_framework.response import Response
from rest_framework.views import APIView
from django.shortcuts import get_object_or_404
from dashboard.models import projects
from .models import AnalysisConfig, SolverResults, SolverProgress, DockerLogs
from rest_framework.parsers imp... | <filename>FEniCSUI/AnalysesHub/views.py
from rest_framework.response import Response
from rest_framework.views import APIView
from django.shortcuts import get_object_or_404
from dashboard.models import projects
from .models import AnalysisConfig, SolverResults, SolverProgress, DockerLogs
from rest_framework.parsers imp... | en | 0.80479 | return a list of entries within a given category create a new category for solver configuration # if request does not contain a name # if there is no category similar to the user request # check if the entry with the same name exists Edit an existing category entry's data # if request does not contain a name # check if... | 2.295377 | 2 |
fs/opener/appfs.py | EnjoyLifeFund/macHighSierra-py36-pkgs | 0 | 2523 | <reponame>EnjoyLifeFund/macHighSierra-py36-pkgs<gh_stars>0
# coding: utf-8
"""``AppFS`` opener definition.
"""
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
from .base import Opener
from .errors import OpenerError
from ..subfs import ClosingSubFS
... | # coding: utf-8
"""``AppFS`` opener definition.
"""
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
from .base import Opener
from .errors import OpenerError
from ..subfs import ClosingSubFS
from .. import appfs
class AppFSOpener(Opener):
"""``... | en | 0.821998 | # coding: utf-8 ``AppFS`` opener definition. ``AppFS`` opener. | 2.277975 | 2 |
scripts/modeling_toolbox/evaluation.py | cyberj0g/verification-classifier | 8 | 2524 | import numpy as np
from sklearn.metrics import fbeta_score, roc_curve, auc, confusion_matrix
from sklearn.decomposition import PCA
from sklearn import random_projection
from sklearn import svm
from sklearn.ensemble import IsolationForest
import matplotlib.pyplot as plt
from keras.layers import Dense, Input, Dropout
fro... | import numpy as np
from sklearn.metrics import fbeta_score, roc_curve, auc, confusion_matrix
from sklearn.decomposition import PCA
from sklearn import random_projection
from sklearn import svm
from sklearn.ensemble import IsolationForest
import matplotlib.pyplot as plt
from keras.layers import Dense, Input, Dropout
fro... | en | 0.464201 | # SVM Hyper-parameters # Fit classifier with PCA reduced data # Fit classifier with RP reduced data # Isolation Forest Hyper-parameters # Random forest Hyper-parameters # AdaBoost Hyper-parameters # SVC Hyper-parameters # XGBoost Hyper-parameters | 2.303746 | 2 |
tests/test_notifo_message.py | mrtazz/notifo.py | 3 | 2525 | # encoding: utf-8
import unittest
import os
import sys
sys.path.append(os.getcwd())
from notifo import Notifo, send_message
class TestNotifyUser(unittest.TestCase):
def setUp(self):
self.provider = "test_provider"
self.provider_banned = "test_provider_msg_banned"
self.user = "test_user"
... | # encoding: utf-8
import unittest
import os
import sys
sys.path.append(os.getcwd())
from notifo import Notifo, send_message
class TestNotifyUser(unittest.TestCase):
def setUp(self):
self.provider = "test_provider"
self.provider_banned = "test_provider_msg_banned"
self.user = "test_user"
... | en | 0.83829 | # encoding: utf-8 | 2.535823 | 3 |
geoist/cattools/Smoothing.py | wqqpp007/geoist | 1 | 2526 | <filename>geoist/cattools/Smoothing.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
import numpy as np
import .Selection as Sel
import .Exploration as Exp
import .CatUtils as CU
#-----------------------------------------------------------------------------------------
def GaussWin (Dis, Sig):
return np.exp(-(... | <filename>geoist/cattools/Smoothing.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
import numpy as np
import .Selection as Sel
import .Exploration as Exp
import .CatUtils as CU
#-----------------------------------------------------------------------------------------
def GaussWin (Dis, Sig):
return np.exp(-(... | en | 0.230635 | #!/usr/bin/env python # -*- coding: utf-8 -*- # #----------------------------------------------------------------------------------------- #----------------------------------------------------------------------------------------- # Catalogue selection # Creating the mesh grid # Unwrapping coordinates # Scaling and norm... | 2.219085 | 2 |
hebsafeharbor/identifier/signals/lexicon_based_recognizer.py | dkarmon/HebSafeHarbor | 3 | 2527 | from typing import List
from presidio_analyzer import EntityRecognizer, RecognizerResult, AnalysisExplanation
from presidio_analyzer.nlp_engine import NlpArtifacts
from hebsafeharbor.common.terms_recognizer import TermsRecognizer
class LexiconBasedRecognizer(EntityRecognizer):
"""
A class which extends the E... | from typing import List
from presidio_analyzer import EntityRecognizer, RecognizerResult, AnalysisExplanation
from presidio_analyzer.nlp_engine import NlpArtifacts
from hebsafeharbor.common.terms_recognizer import TermsRecognizer
class LexiconBasedRecognizer(EntityRecognizer):
"""
A class which extends the E... | en | 0.89866 | A class which extends the EntityRecognizer (@Presidio) and recognize entities based on a lexicon # expected confidence level for this recognizer Initializes Hebrew LexiconBasedRecognizer :param name: recognizer's name :param supported_entity: entity type to be associated with the entities recognized by... | 2.939862 | 3 |
my_plugins/YouCompleteMe/third_party/ycmd/ycmd/tests/clangd/subcommands_test.py | cyx233/vim_config | 0 | 2528 | # encoding: utf-8
#
# Copyright (C) 2018 ycmd contributors
#
# This file is part of ycmd.
#
# ycmd is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any lat... | # encoding: utf-8
#
# Copyright (C) 2018 ycmd contributors
#
# This file is part of ycmd.
#
# ycmd is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any lat... | en | 0.66152 | # encoding: utf-8 # # Copyright (C) 2018 ycmd contributors # # This file is part of ycmd. # # ycmd is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any lat... | 1.486765 | 1 |
sentiment/config.py | TheRensselaerIDEA/covid19_tweet_ids | 0 | 2529 | """
Config class containing all the settings for running sentiment scoring tool
"""
import jsonpickle
class Config(object):
"""Container for sentiment scoring tool settings.
"""
def __init__(self):
"""Initializes the Config instance.
"""
#Elasticsearch settings
self.elasti... | """
Config class containing all the settings for running sentiment scoring tool
"""
import jsonpickle
class Config(object):
"""Container for sentiment scoring tool settings.
"""
def __init__(self):
"""Initializes the Config instance.
"""
#Elasticsearch settings
self.elasti... | en | 0.742513 | Config class containing all the settings for running sentiment scoring tool Container for sentiment scoring tool settings. Initializes the Config instance. #Elasticsearch settings #Processing settings Loads the config from a JSON file. Args: filepath: path of the JSON file. | 3.020799 | 3 |
tests/ut/python/dataset/test_invert.py | GuoSuiming/mindspore | 4 | 2530 | # Copyright 2020 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to... | # Copyright 2020 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to... | en | 0.717384 | # Copyright 2020 Huawei Technologies Co., Ltd # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to... | 2.124586 | 2 |
puzzle/tests/test_candy.py | aliciawyy/dmining | 0 | 2531 | from parameterized import parameterized
from numpy.testing import TestCase
from .. import candy
class TestCollectCandies(TestCase):
@parameterized.expand(
[(5, 5, 12,
[[2, 1, 1, 1, 1], [2, 2, 1, 1, 1], [1, 2, 1, 1, 1],
[2, 2, 1, 1, 3], [2, 2, 2, 2, 2]])]
)
def test_candy(self... | from parameterized import parameterized
from numpy.testing import TestCase
from .. import candy
class TestCollectCandies(TestCase):
@parameterized.expand(
[(5, 5, 12,
[[2, 1, 1, 1, 1], [2, 2, 1, 1, 1], [1, 2, 1, 1, 1],
[2, 2, 1, 1, 3], [2, 2, 2, 2, 2]])]
)
def test_candy(self... | none | 1 | 2.581135 | 3 | |
audio.py | fernandoq/quiz-show | 0 | 2532 | import time
import subprocess
import os
print os.uname()
if not os.uname()[0].startswith("Darw"):
import pygame
pygame.mixer.init()
# Plays a song
def playSong(filename):
print "play song"
if not os.uname()[0].startswith("Darw"):
pygame.mixer.music.fadeout(1000) #fadeout current music over 1 sec.
pygame.m... | import time
import subprocess
import os
print os.uname()
if not os.uname()[0].startswith("Darw"):
import pygame
pygame.mixer.init()
# Plays a song
def playSong(filename):
print "play song"
if not os.uname()[0].startswith("Darw"):
pygame.mixer.music.fadeout(1000) #fadeout current music over 1 sec.
pygame.m... | en | 0.799617 | # Plays a song #fadeout current music over 1 sec. | 2.562445 | 3 |
tests/test_dynamodbHandler.py | unfoldingWord-dev/python-aws-tools | 1 | 2533 | from __future__ import absolute_import, unicode_literals, print_function
import mock
import unittest
import d43_aws_tools as aws_tools
from boto3.dynamodb.conditions import Attr
class DynamoDBHandlerTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
with mock.patch("d43_aws_tools.dynamodb_han... | from __future__ import absolute_import, unicode_literals, print_function
import mock
import unittest
import d43_aws_tools as aws_tools
from boto3.dynamodb.conditions import Attr
class DynamoDBHandlerTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
with mock.patch("d43_aws_tools.dynamodb_han... | en | 0.738572 | Test a successful invocation of `get_item`. Test an unsuccessful invocation of `get_item`. Test a successful invocation of `insert_item`. Test a successful invocation of `update_item`. # ignore whitespace and order of assignments Test a successful invocation of `delete_item`. Test a successful invocation of `query_item... | 2.658939 | 3 |
app.py | sbustamante/heroku_app | 0 | 2534 | <filename>app.py
from dash import Dash, html, dcc
import plotly.express as px
import pandas as pd
app = Dash(__name__)
server = app.server
# assume you have a "long-form" data frame
# see https://plotly.com/python/px-arguments/ for more options
df = pd.DataFrame({
"Fruit": ["Apples", "Oranges", "Bananas", "Apples... | <filename>app.py
from dash import Dash, html, dcc
import plotly.express as px
import pandas as pd
app = Dash(__name__)
server = app.server
# assume you have a "long-form" data frame
# see https://plotly.com/python/px-arguments/ for more options
df = pd.DataFrame({
"Fruit": ["Apples", "Oranges", "Bananas", "Apples... | en | 0.683289 | # assume you have a "long-form" data frame # see https://plotly.com/python/px-arguments/ for more options Dash: A web application framework for your data. | 3.474497 | 3 |
peter_sslers/web/lib/form_utils.py | aptise/peter_sslers | 35 | 2535 | <filename>peter_sslers/web/lib/form_utils.py
# pypi
import six
# local
from ...lib import db as lib_db
from ...lib import utils
from ...model import objects as model_objects
from ...model import utils as model_utils
from . import formhandling
# ========================================================================... | <filename>peter_sslers/web/lib/form_utils.py
# pypi
import six
# local
from ...lib import db as lib_db
from ...lib import utils
from ...model import objects as model_objects
from ...model import utils as model_utils
from . import formhandling
# ========================================================================... | en | 0.52059 | # pypi # local # ============================================================================== support for Python2/3 # standardized mapping for `model_utils.DomainsChallenged` to a formStash An AcmeAccount may be uploaded multiple ways: * a single PEM file * an intra-associated three file triplet from a Certbo... | 2.051684 | 2 |
AI_Engine_Development/Feature_Tutorials/07-AI-Engine-Floating-Point/Utils/GenerationLib.py | jlamperez/Vitis-Tutorials | 1 | 2536 | <reponame>jlamperez/Vitis-Tutorials<filename>AI_Engine_Development/Feature_Tutorials/07-AI-Engine-Floating-Point/Utils/GenerationLib.py
#
# Copyright 2020–2021 Xilinx, 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 ob... | #
# Copyright 2020–2021 Xilinx, 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 agreed to in w... | en | 0.813207 | # # Copyright 2020–2021 Xilinx, 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 agreed to in w... | 1.901108 | 2 |
Object Oriented Programming/Lecture 01/Intro.py | ashish-ad/Python-Projects | 1 | 2537 | item1='phone'
item1_price = 100
item1_quantity = 5
item1_price_total = item1_price * item1_quantity
print(type(item1)) # str
print(type(item1_price)) # int
print(type(item1_quantity)) # int
print(type(item1_price_total)) # int
# output:
# <class 'str'>
# <class 'int'>
# ... | item1='phone'
item1_price = 100
item1_quantity = 5
item1_price_total = item1_price * item1_quantity
print(type(item1)) # str
print(type(item1_price)) # int
print(type(item1_quantity)) # int
print(type(item1_price_total)) # int
# output:
# <class 'str'>
# <class 'int'>
# ... | en | 0.127676 | # str # int # int # int # output: # <class 'str'> # <class 'int'> # <class 'int'> # <class 'int'> | 3.834587 | 4 |
configs/deepim/ycbvPbrSO/FlowNet512_1.5AugCosyAAEGray_NoiseRandom_AggressiveR_ClipGrad_fxfy1_Dtw01_LogDz_PM10_Flat_ycbvPbr_SO/FlowNet512_1.5AugCosyAAEGray_NoiseRandom_AggressiveR_ClipGrad_fxfy1_Dtw01_LogDz_PM10_Flat_Pbr_16_36WoodBlock.py | THU-DA-6D-Pose-Group/self6dpp | 33 | 2538 | <gh_stars>10-100
_base_ = "./FlowNet512_1.5AugCosyAAEGray_NoiseRandom_AggressiveR_ClipGrad_fxfy1_Dtw01_LogDz_PM10_Flat_Pbr_01_02MasterChefCan.py"
OUTPUT_DIR = "output/deepim/ycbvPbrSO/FlowNet512_1.5AugCosyAAEGray_NoiseRandom_AggressiveR_ClipGrad_fxfy1_Dtw01_LogDz_PM10_Flat_ycbvPbr_SO/16_36WoodBlock"
DATASETS = dict(TRA... | _base_ = "./FlowNet512_1.5AugCosyAAEGray_NoiseRandom_AggressiveR_ClipGrad_fxfy1_Dtw01_LogDz_PM10_Flat_Pbr_01_02MasterChefCan.py"
OUTPUT_DIR = "output/deepim/ycbvPbrSO/FlowNet512_1.5AugCosyAAEGray_NoiseRandom_AggressiveR_ClipGrad_fxfy1_Dtw01_LogDz_PM10_Flat_ycbvPbr_SO/16_36WoodBlock"
DATASETS = dict(TRAIN=("ycbv_036_woo... | none | 1 | 1.326778 | 1 | |
sqlakeyset/__init__.py | jhihruei/sqlakeyset | 0 | 2539 | <filename>sqlakeyset/__init__.py
from .columns import OC
from .paging import get_page, select_page, process_args
from .results import serialize_bookmark, unserialize_bookmark, Page, Paging
__all__ = [
'OC',
'get_page',
'select_page',
'serialize_bookmark',
'unserialize_bookmark',
'Page',
'P... | <filename>sqlakeyset/__init__.py
from .columns import OC
from .paging import get_page, select_page, process_args
from .results import serialize_bookmark, unserialize_bookmark, Page, Paging
__all__ = [
'OC',
'get_page',
'select_page',
'serialize_bookmark',
'unserialize_bookmark',
'Page',
'P... | none | 1 | 1.701587 | 2 | |
low_rank_local_connectivity/models/simple_model.py | shaun95/google-research | 1 | 2540 | # coding=utf-8
# Copyright 2022 The Google Research Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicab... | # coding=utf-8
# Copyright 2022 The Google Research Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicab... | en | 0.860291 | # coding=utf-8 # Copyright 2022 The Google Research Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicab... | 2.695649 | 3 |
adafruit_circuitpython_libs/adafruit-circuitpython-bundle-py-20210214/examples/icm20x_icm20948_gyro_data_rate_test.py | jacoblb64/pico_rgb_keypad_hid | 47 | 2541 | <reponame>jacoblb64/pico_rgb_keypad_hid
# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries
# SPDX-License-Identifier: MIT
import time
import board
import busio
from adafruit_icm20x import ICM20948
cycles = 200
i2c = busio.I2C(board.SCL, board.SDA)
icm = ICM20948(i2c)
# Cycle between two data rates
# Best... | # SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries
# SPDX-License-Identifier: MIT
import time
import board
import busio
from adafruit_icm20x import ICM20948
cycles = 200
i2c = busio.I2C(board.SCL, board.SDA)
icm = ICM20948(i2c)
# Cycle between two data rates
# Best viewed in the Mu serial plotter where y... | en | 0.733456 | # SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries # SPDX-License-Identifier: MIT # Cycle between two data rates # Best viewed in the Mu serial plotter where you can see how # the data rate affects the resolution of the data # minimum # maximum | 2.933779 | 3 |
1186.py | TheLurkingCat/TIOJ | 0 | 2542 | <gh_stars>0
a = int(input())
while a:
for x in range(a-1):
out = '*' + ' ' * (a-x-2) + '*' + ' ' * (a-x-2) + '*'
print(out.center(2*a-1))
print('*' * (2 * a - 1))
for x in range(a-1):
out = '*' + ' ' * x + '*' + ' ' * x + '*'
print(out.center(2*a-1))
a = int(input())
| a = int(input())
while a:
for x in range(a-1):
out = '*' + ' ' * (a-x-2) + '*' + ' ' * (a-x-2) + '*'
print(out.center(2*a-1))
print('*' * (2 * a - 1))
for x in range(a-1):
out = '*' + ' ' * x + '*' + ' ' * x + '*'
print(out.center(2*a-1))
a = int(input()) | none | 1 | 3.795035 | 4 | |
utils/common.py | initialed85/eds-cctv-system | 0 | 2543 | import datetime
import json
import os
from pathlib import Path
from types import SimpleNamespace
from typing import List
from typing import NamedTuple, Union, Optional, Callable
from uuid import uuid3, NAMESPACE_DNS
from dateutil.parser import parse
_VIDEO_SUFFIXES = [".mkv", ".mp4"]
_IMAGE_SUFFIXES = [".jpg"]
_PERMI... | import datetime
import json
import os
from pathlib import Path
from types import SimpleNamespace
from typing import List
from typing import NamedTuple, Union, Optional, Callable
from uuid import uuid3, NAMESPACE_DNS
from dateutil.parser import parse
_VIDEO_SUFFIXES = [".mkv", ".mp4"]
_IMAGE_SUFFIXES = [".jpg"]
_PERMI... | en | 0.332867 | # in Go: # eventId := uuid.NewSHA1( # uuid.NameSpaceDNS, # []byte(fmt.Sprintf("%v, %v, %v, %v, %v", timestamp, highResImagePath, lowResImagePath, highResVideoPath, lowResVideoPath)), # ) | 2.602717 | 3 |
schoolio/migrations/0005_auto_20190927_1423.py | schoolio-co/schoolio_site | 0 | 2544 | # Generated by Django 2.2.1 on 2019-09-27 14:23
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('schoolio', '0004_auto_20190927_0405'),
]
operations = [
migrations.AlterField(
model_name='student_assessment',
name... | # Generated by Django 2.2.1 on 2019-09-27 14:23
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('schoolio', '0004_auto_20190927_0405'),
]
operations = [
migrations.AlterField(
model_name='student_assessment',
name... | en | 0.683525 | # Generated by Django 2.2.1 on 2019-09-27 14:23 | 1.509377 | 2 |
taattack/_datasets/dataset.py | linerxliner/ValCAT | 0 | 2545 | <gh_stars>0
class Dataset:
_data = None
_first_text_col = 'text'
_second_text_col = None
_label_col = 'label'
def __init__(self):
self._idx = 0
if self._data is None:
raise Exception('Dataset is not loaded')
def __iter__(self):
return self
def __next__(... | class Dataset:
_data = None
_first_text_col = 'text'
_second_text_col = None
_label_col = 'label'
def __init__(self):
self._idx = 0
if self._data is None:
raise Exception('Dataset is not loaded')
def __iter__(self):
return self
def __next__(self):
... | none | 1 | 2.987323 | 3 | |
scripts/extract_gs_citations.py | akhilpandey95/scholarlyimpact | 0 | 2546 | <filename>scripts/extract_gs_citations.py
#!/usr/bin/env python3
# This Source Code Form is subject to the terms of the MIT
# License. If a copy of the same was not distributed with this
# file, You can obtain one at
# https://github.com/akhilpandey95/scholarlyimpact/blob/master/LICENSE.
import os
import csv
import g... | <filename>scripts/extract_gs_citations.py
#!/usr/bin/env python3
# This Source Code Form is subject to the terms of the MIT
# License. If a copy of the same was not distributed with this
# file, You can obtain one at
# https://github.com/akhilpandey95/scholarlyimpact/blob/master/LICENSE.
import os
import csv
import g... | en | 0.668965 | #!/usr/bin/env python3 # This Source Code Form is subject to the terms of the MIT # License. If a copy of the same was not distributed with this # file, You can obtain one at # https://github.com/akhilpandey95/scholarlyimpact/blob/master/LICENSE. # class definition for Rate limiting Class object for putting a rate limi... | 2.672435 | 3 |
dist-packages/reportlab/pdfgen/pathobject.py | Jianwei-Wang/python2.7_lib | 51 | 2547 | <filename>dist-packages/reportlab/pdfgen/pathobject.py
#Copyright ReportLab Europe Ltd. 2000-2012
#see license.txt for license details
#history http://www.reportlab.co.uk/cgi-bin/viewcvs.cgi/public/reportlab/trunk/reportlab/pdfgen/pathobject.py
__version__=''' $Id$ '''
__doc__="""
PDFPathObject is an efficient way to d... | <filename>dist-packages/reportlab/pdfgen/pathobject.py
#Copyright ReportLab Europe Ltd. 2000-2012
#see license.txt for license details
#history http://www.reportlab.co.uk/cgi-bin/viewcvs.cgi/public/reportlab/trunk/reportlab/pdfgen/pathobject.py
__version__=''' $Id$ '''
__doc__="""
PDFPathObject is an efficient way to d... | en | 0.816183 | #Copyright ReportLab Europe Ltd. 2000-2012 #see license.txt for license details #history http://www.reportlab.co.uk/cgi-bin/viewcvs.cgi/public/reportlab/trunk/reportlab/pdfgen/pathobject.py $Id$ PDFPathObject is an efficient way to draw paths on a Canvas. Do not instantiate directly, obtain one from the Canvas instead.... | 2.711154 | 3 |
client/modules/Wikipedia.py | devagul93/Jarvis-System | 0 | 2548 | import wikipedia
import re
import TCPclient as client
WORDS = ["WIKIPEDIA","SEARCH","INFORMATION"]
def handle(text,mic,profile):
# SEARCH ON WIKIPEDIA
# ny = wikipedia.summary("New York",sentences=3);
# mic.say("%s"% ny)
#mic.say("What you want to search about")
#text = mic.activeListen()
print "entering wik... | import wikipedia
import re
import TCPclient as client
WORDS = ["WIKIPEDIA","SEARCH","INFORMATION"]
def handle(text,mic,profile):
# SEARCH ON WIKIPEDIA
# ny = wikipedia.summary("New York",sentences=3);
# mic.say("%s"% ny)
#mic.say("What you want to search about")
#text = mic.activeListen()
print "entering wik... | en | 0.334342 | # SEARCH ON WIKIPEDIA # ny = wikipedia.summary("New York",sentences=3); # mic.say("%s"% ny) #mic.say("What you want to search about") #text = mic.activeListen() #mic.say(answer) | 3.633089 | 4 |
Madlibs/madlibs.py | nikhil-amin/python-mini-project | 2 | 2549 | import random
print("Title : Eat, Drink, And Be Sick")
noun = []
for i in range(4):
n = input("Enter noun : ")
noun.append(n)
plural = []
for i in range(6):
pn = input("Enter plural noun : ")
plural.append(pn)
adjective = []
for i in range(2):
a = input("Enter adjective : ")
adjective.append(a)
... | import random
print("Title : Eat, Drink, And Be Sick")
noun = []
for i in range(4):
n = input("Enter noun : ")
noun.append(n)
plural = []
for i in range(6):
pn = input("Enter plural noun : ")
plural.append(pn)
adjective = []
for i in range(2):
a = input("Enter adjective : ")
adjective.append(a)
... | none | 1 | 3.927975 | 4 | |
scripts/transpose.py | saikrishnarallabandi/python_connectionist | 0 | 2550 | import numpy
g = open('/home/srallaba/mgc/transposed/arctic_a0404.mgc','w')
x = numpy.loadtxt('/home/srallaba/mgc_spaces/arctic_a0404.mgc')
numpy.savetxt(g, numpy.transpose(x))
g.close()
| import numpy
g = open('/home/srallaba/mgc/transposed/arctic_a0404.mgc','w')
x = numpy.loadtxt('/home/srallaba/mgc_spaces/arctic_a0404.mgc')
numpy.savetxt(g, numpy.transpose(x))
g.close()
| none | 1 | 2.234442 | 2 | |
tests/zone_api_test/core/zone_manager_test.py | yfaway/zone-apis | 1 | 2551 | <gh_stars>1-10
from zone_api.core.zone_manager import ZoneManager
from zone_api import platform_encapsulator as pe
from zone_api.core.zone import Zone
from zone_api.core.zone_event import ZoneEvent
from zone_api.core.devices.dimmer import Dimmer
from zone_api.core.devices.switch import Fan, Light, Switch
from zone_api... | from zone_api.core.zone_manager import ZoneManager
from zone_api import platform_encapsulator as pe
from zone_api.core.zone import Zone
from zone_api.core.zone_event import ZoneEvent
from zone_api.core.devices.dimmer import Dimmer
from zone_api.core.devices.switch import Fan, Light, Switch
from zone_api.core.devices.i... | en | 0.775917 | Unit tests for zone_manager.py. | 2.27917 | 2 |
meiduo_mall/meiduo_mall/apps/orders/views.py | Zasling/meiduo_mall33 | 1 | 2552 | from rest_framework.response import Response
from rest_framework.views import APIView
from django_redis import get_redis_connection
from goods.models import SKU
from decimal import Decimal
from rest_framework.generics import CreateAPIView,ListAPIView
from rest_framework.mixins import ListModelMixin
from orders.serializ... | from rest_framework.response import Response
from rest_framework.views import APIView
from django_redis import get_redis_connection
from goods.models import SKU
from decimal import Decimal
from rest_framework.generics import CreateAPIView,ListAPIView
from rest_framework.mixins import ListModelMixin
from orders.serializ... | zh | 0.931723 | # 展示订单信息 # 获取用户对象 # 建立redis连接 # 获取hash数据sku_id ,count # {10:1} # 将byte类型数据转为整形 # 获取集合数据 # 查询所有选中状态的数据对象 # 商品对象添加count属性(sku表中没有count字段,要手动添加属性) # 生成运费 # 序列化返回商品对象 # 保存订单信息 # 订单列表数据获取 # 评论-获取商品信息 # 保存评论 # 商品详情中的评论展示 # 从kwargs中获取sku_id # 获取商品信息 # 获取用户名,判断是否匿名 | 1.987966 | 2 |
src/streamlink_cli/main.py | melmorabity/streamlink | 0 | 2553 | import argparse
import errno
import logging
import os
import platform
import signal
import sys
from collections import OrderedDict
from contextlib import closing
from distutils.version import StrictVersion
from functools import partial
from gettext import gettext
from itertools import chain
from pathlib import Path
fro... | import argparse
import errno
import logging
import os
import platform
import signal
import sys
from collections import OrderedDict
from contextlib import closing
from distutils.version import StrictVersion
from functools import partial
from gettext import gettext
from itertools import chain
from pathlib import Path
fro... | en | 0.817619 | # Not windows Checks if file already exists and ask the user if it should be overwritten if it does. Decides where to write the stream. Depending on arguments it can be one of these: - The stdout pipe - A subprocess' stdin pipe - A named pipe that the subprocess reads from - A regular file ... | 1.860107 | 2 |
dbaccesslibUserMailInfo.py | Koushik-ks/FlaskAPP | 0 | 2554 | from io import BytesIO
from io import StringIO
import json
from bson.dbref import DBRef
import datetime
from bson import json_util
import logging
import base64
jsonCode ={
"building":{
"Essae Vaishnavi Solitaire": {
"id": "B1",
"division": {
"SS"... | from io import BytesIO
from io import StringIO
import json
from bson.dbref import DBRef
import datetime
from bson import json_util
import logging
import base64
jsonCode ={
"building":{
"Essae Vaishnavi Solitaire": {
"id": "B1",
"division": {
"SS"... | en | 0.373063 | #Create and configure logger #Creating an object #Setting the threshold of logger to DEBUG #img = qrcode.make(colorCode) #img.save(colorCode+".png") #mydb.mltable.insert({"code":jsonData["code"],"tags": tags,"status":"Keep","user_id":1,"otherdbref":newDbref}) Actual Code #Test code to be removed #end_date = scan_date ... | 2.293309 | 2 |
src/test/dags/bq_to_cm_dag_test.py | google/cc4d | 0 | 2555 | # python3
# coding=utf-8
# 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 ... | # python3
# coding=utf-8
# 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 ... | en | 0.827359 | # python3 # coding=utf-8 # 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 ... | 1.846216 | 2 |
talentmap_api/common/management/commands/load_xml.py | burgwyn/State-TalentMAP-API | 5 | 2556 | from django.core.management.base import BaseCommand
import logging
import re
from talentmap_api.common.xml_helpers import XMLloader, strip_extra_spaces, parse_boolean, parse_date, get_nested_tag
from talentmap_api.language.models import Language, Proficiency
from talentmap_api.position.models import Grade, Skill, Pos... | from django.core.management.base import BaseCommand
import logging
import re
from talentmap_api.common.xml_helpers import XMLloader, strip_extra_spaces, parse_boolean, parse_date, get_nested_tag
from talentmap_api.language.models import Language, Proficiency
from talentmap_api.position.models import Grade, Skill, Pos... | en | 0.795303 | # Set / update the collision behavior # Run the post load function, if it exists # Update relationships # Regional code setting is done automatically by DOS Webservices, so # we now only need this logic when loading from our sample XML files # Array of regional codes # Connect new locations to applicable posts | 1.93345 | 2 |
gluon/tests/test_recfile.py | oscarfonts/web2py | 0 | 2557 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Unit tests for gluon.recfile
"""
import unittest
import os
import shutil
import uuid
from .fix_path import fix_sys_path
fix_sys_path(__file__)
from gluon import recfile
class TestRecfile(unittest.TestCase):
def setUp(self):
os.mkdir('tests')
d... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Unit tests for gluon.recfile
"""
import unittest
import os
import shutil
import uuid
from .fix_path import fix_sys_path
fix_sys_path(__file__)
from gluon import recfile
class TestRecfile(unittest.TestCase):
def setUp(self):
os.mkdir('tests')
d... | en | 0.361501 | #!/usr/bin/env python # -*- coding: utf-8 -*- Unit tests for gluon.recfile | 2.557695 | 3 |
configLambdas.py | cfrome77/liquid-stats | 4 | 2558 | <filename>configLambdas.py
import json
import os
import subprocess
from dotenv import load_dotenv
from subprocess import check_output, Popen, PIPE
load_dotenv()
# Accessing variables.
CLIENT_ID = os.environ.get('CLIENT_ID')
CLIENT_SECRET = os.environ.get('CLIENT_SECRET')
USERNAME = os.environ.get('USERNAME')
BUCKET_... | <filename>configLambdas.py
import json
import os
import subprocess
from dotenv import load_dotenv
from subprocess import check_output, Popen, PIPE
load_dotenv()
# Accessing variables.
CLIENT_ID = os.environ.get('CLIENT_ID')
CLIENT_SECRET = os.environ.get('CLIENT_SECRET')
USERNAME = os.environ.get('USERNAME')
BUCKET_... | en | 0.363694 | # Accessing variables. | 2.159943 | 2 |
microbitAnim.py | SaitoYutaka/microbitAnim | 0 | 2559 | <reponame>SaitoYutaka/microbitAnim<filename>microbitAnim.py
# -*- coding: utf-8 -*-
###########################################################################
## Python code generated with wxFormBuilder (version Aug 8 2018)
## http://www.wxformbuilder.org/
##
## PLEASE DO *NOT* EDIT THIS FILE!
#####################... | # -*- coding: utf-8 -*-
###########################################################################
## Python code generated with wxFormBuilder (version Aug 8 2018)
## http://www.wxformbuilder.org/
##
## PLEASE DO *NOT* EDIT THIS FILE!
###########################################################################
impo... | de | 0.597989 | # -*- coding: utf-8 -*- ########################################################################### ## Python code generated with wxFormBuilder (version Aug 8 2018) ## http://www.wxformbuilder.org/ ## ## PLEASE DO *NOT* EDIT THIS FILE! ########################################################################### #######... | 1.782309 | 2 |
src/dependencies/contrib/celery.py | nicoddemus/dependencies | 0 | 2560 | <reponame>nicoddemus/dependencies
"""
dependencies.contrib.celery
---------------------------
This module implements injectable Celery task.
:copyright: (c) 2016-2020 by dry-python team.
:license: BSD, see LICENSE for more details.
"""
from _dependencies.contrib.celery import shared_task
from _dependencies.contrib.ce... | """
dependencies.contrib.celery
---------------------------
This module implements injectable Celery task.
:copyright: (c) 2016-2020 by dry-python team.
:license: BSD, see LICENSE for more details.
"""
from _dependencies.contrib.celery import shared_task
from _dependencies.contrib.celery import task
__all__ = ["sha... | en | 0.637317 | dependencies.contrib.celery --------------------------- This module implements injectable Celery task. :copyright: (c) 2016-2020 by dry-python team. :license: BSD, see LICENSE for more details. | 1.306418 | 1 |
yolo3/utils.py | gaxu/keras-yolo3 | 0 | 2561 | """Miscellaneous utility functions."""
from functools import reduce
from PIL import Image
import numpy as np
from matplotlib.colors import rgb_to_hsv, hsv_to_rgb
def compose(*funcs):
"""Compose arbitrarily many functions, evaluated left to right.
Reference: https://mathieularose.com/function-composition-in-... | """Miscellaneous utility functions."""
from functools import reduce
from PIL import Image
import numpy as np
from matplotlib.colors import rgb_to_hsv, hsv_to_rgb
def compose(*funcs):
"""Compose arbitrarily many functions, evaluated left to right.
Reference: https://mathieularose.com/function-composition-in-... | zh | 0.275103 | Miscellaneous utility functions. Compose arbitrarily many functions, evaluated left to right. Reference: https://mathieularose.com/function-composition-in-python/ # return lambda x: reduce(lambda v, f: f(v), funcs, x) resize image with unchanged aspect ratio using padding random preprocessing for real-time data au... | 3.08494 | 3 |
text_classification/config.py | MardanovTimur/kaggle | 0 | 2562 | <gh_stars>0
import logging
import pathlib
logging.basicConfig(level=logging.INFO)
# Dirs
ROOT_DIR = pathlib.Path(__file__).parent.absolute()
DUMP_DIR = ROOT_DIR / 'dumps'
| import logging
import pathlib
logging.basicConfig(level=logging.INFO)
# Dirs
ROOT_DIR = pathlib.Path(__file__).parent.absolute()
DUMP_DIR = ROOT_DIR / 'dumps' | none | 1 | 1.833755 | 2 | |
sportsreference/ncaaf/rankings.py | JosephDErwin/sportsreference | 0 | 2563 | import re
from pyquery import PyQuery as pq
from .. import utils
from .constants import RANKINGS_SCHEME, RANKINGS_URL
from six.moves.urllib.error import HTTPError
class Rankings:
"""
Get all Associated Press (AP) rankings on a week-by-week basis.
Grab a list of the rankings published by the Associated Pr... | import re
from pyquery import PyQuery as pq
from .. import utils
from .constants import RANKINGS_SCHEME, RANKINGS_URL
from six.moves.urllib.error import HTTPError
class Rankings:
"""
Get all Associated Press (AP) rankings on a week-by-week basis.
Grab a list of the rankings published by the Associated Pr... | en | 0.894047 | Get all Associated Press (AP) rankings on a week-by-week basis. Grab a list of the rankings published by the Associated Press to easily query the hierarchy of teams each week. The results expose the current and previous rankings as well as the movement for each team in the list. Parameters -------... | 3.221932 | 3 |
ding/hpc_rl/wrapper.py | davide97l/DI-engine | 1 | 2564 | <filename>ding/hpc_rl/wrapper.py
import importlib
from ditk import logging
from collections import OrderedDict
from functools import wraps
import ding
'''
Overview:
`hpc_wrapper` is the wrapper for functions which are supported by hpc. If a function is wrapped by it, we will
search for its hpc type and return t... | <filename>ding/hpc_rl/wrapper.py
import importlib
from ditk import logging
from collections import OrderedDict
from functools import wraps
import ding
'''
Overview:
`hpc_wrapper` is the wrapper for functions which are supported by hpc. If a function is wrapped by it, we will
search for its hpc type and return t... | en | 0.6833 | Overview: `hpc_wrapper` is the wrapper for functions which are supported by hpc. If a function is wrapped by it, we will search for its hpc type and return the function implemented by hpc. We will use the following code as a sample to introduce `hpc_wrapper`: ``` @hpc_wrapper(shape_fn=shape_fn_dntd,... | 2.419759 | 2 |
CodeWars/2016/NumberOfOccurrences-7k.py | JLJTECH/TutorialTesting | 0 | 2565 | #Return the count of int(s) in passed array.
def number_of_occurrences(s, xs):
return xs.count(s) | #Return the count of int(s) in passed array.
def number_of_occurrences(s, xs):
return xs.count(s) | en | 0.802236 | #Return the count of int(s) in passed array. | 2.789112 | 3 |
telethon_generator/parsers/tlobject.py | islam-200555/Telethon | 2 | 2566 | import re
from zlib import crc32
from ..utils import snake_to_camel_case
CORE_TYPES = (
0xbc799737, # boolFalse#bc799737 = Bool;
0x997275b5, # boolTrue#997275b5 = Bool;
0x3fedd339, # true#3fedd339 = True;
0x1cb5c415, # vector#1cb5c415 {t:Type} # [ t ] = Vector t;
)
# https://github.com/telegramde... | import re
from zlib import crc32
from ..utils import snake_to_camel_case
CORE_TYPES = (
0xbc799737, # boolFalse#bc799737 = Bool;
0x997275b5, # boolTrue#997275b5 = Bool;
0x3fedd339, # true#3fedd339 = True;
0x1cb5c415, # vector#1cb5c415 {t:Type} # [ t ] = Vector t;
)
# https://github.com/telegramde... | en | 0.730368 | # boolFalse#bc799737 = Bool; # boolTrue#997275b5 = Bool; # true#3fedd339 = True; # vector#1cb5c415 {t:Type} # [ t ] = Vector t; # https://github.com/telegramdesktop/tdesktop/blob/4bf66cb6e93f3965b40084771b595e93d0b11bcd/Telegram/SourceFiles/codegen/scheme/codegen_scheme.py#L57-L62 # 0 represents any layer Initializes a... | 2.29507 | 2 |
dotnet/private/actions/resx_core.bzl | purkhusid/rules_dotnet | 143 | 2567 | <reponame>purkhusid/rules_dotnet
"Actions for compiling resx files"
load(
"@io_bazel_rules_dotnet//dotnet/private:providers.bzl",
"DotnetResourceInfo",
)
def _make_runner_arglist(dotnet, source, output, resgen):
args = dotnet.actions.args()
if type(source) == "Target":
args.add_all(source.fil... | "Actions for compiling resx files"
load(
"@io_bazel_rules_dotnet//dotnet/private:providers.bzl",
"DotnetResourceInfo",
)
def _make_runner_arglist(dotnet, source, output, resgen):
args = dotnet.actions.args()
if type(source) == "Target":
args.add_all(source.files)
else:
args.add(so... | en | 0.63335 | The function adds an action that compiles a single .resx file into .resources file. Returns [DotnetResourceInfo](api.md#dotnetresourceinfo). Args: dotnet: [DotnetContextInfo](api.md#dotnetcontextinfo). name: name of the file to generate. src: The .resx source file that is transformed i... | 2.328755 | 2 |
test/jit/test_modules.py | xiaohanhuang/pytorch | 183 | 2568 | # Owner(s): ["oncall: jit"]
import torch
import os
import sys
from torch.testing._internal.jit_utils import JitTestCase
# Make the helper files in test/ importable
pytorch_test_dir = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
sys.path.append(pytorch_test_dir)
if __name__ == '__main__':
raise Ru... | # Owner(s): ["oncall: jit"]
import torch
import os
import sys
from torch.testing._internal.jit_utils import JitTestCase
# Make the helper files in test/ importable
pytorch_test_dir = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
sys.path.append(pytorch_test_dir)
if __name__ == '__main__':
raise Ru... | en | 0.908901 | # Owner(s): ["oncall: jit"] # Make the helper files in test/ importable Test that a module that has __constants__ set to something that is not a set can be scripted. # torch.nn.Linear has a __constants__ attribute defined # and intialized to a list. | 2.216685 | 2 |
pixelate_task_1.py | Swayamshu/Pixelate_Sample_Arena | 0 | 2569 | <filename>pixelate_task_1.py
import gym
import pix_sample_arena
import time
import pybullet as p
import pybullet_data
import cv2
if __name__ == "__main__":
env = gym.make("pix_sample_arena-v0")
x = 0
while True:
p.stepSimulation()
time.sleep(100) | <filename>pixelate_task_1.py
import gym
import pix_sample_arena
import time
import pybullet as p
import pybullet_data
import cv2
if __name__ == "__main__":
env = gym.make("pix_sample_arena-v0")
x = 0
while True:
p.stepSimulation()
time.sleep(100) | none | 1 | 1.941719 | 2 | |
tests/test_timeparser.py | vgoehler/python-i3-battery-block | 0 | 2570 | <gh_stars>0
from datetime import time
import pytest
from i3_battery_block_vgg.timeparser import __parse_time_manually
from i3_battery_block_vgg.timeparser import parse_time
@pytest.mark.parametrize(
"time_input, expected",
[
("12:13", time(hour=12, minute=13)),
("12:13:14", time(hour=12, min... | from datetime import time
import pytest
from i3_battery_block_vgg.timeparser import __parse_time_manually
from i3_battery_block_vgg.timeparser import parse_time
@pytest.mark.parametrize(
"time_input, expected",
[
("12:13", time(hour=12, minute=13)),
("12:13:14", time(hour=12, minute=13, seco... | none | 1 | 2.759168 | 3 | |
frontends/PyCDE/test/polynomial.py | fyquah/circt | 0 | 2571 | <filename>frontends/PyCDE/test/polynomial.py
# RUN: %PYTHON% %s 2>&1 | FileCheck %s
from __future__ import annotations
import mlir
import pycde
from pycde import (Input, Output, Parameter, module, externmodule, generator,
types, dim)
from circt.dialects import comb, hw
@module
def PolynomialComp... | <filename>frontends/PyCDE/test/polynomial.py
# RUN: %PYTHON% %s 2>&1 | FileCheck %s
from __future__ import annotations
import mlir
import pycde
from pycde import (Input, Output, Parameter, module, externmodule, generator,
types, dim)
from circt.dialects import comb, hw
@module
def PolynomialComp... | en | 0.348693 | # RUN: %PYTHON% %s 2>&1 | FileCheck %s Module to compute ax^3 + bx^2 + cx + d for design-time coefficients # Evaluate polynomial for 'x'. coefficients is in 'd' -> 'a' order. Implement this module for input 'x'. # Final output # CHECK-LABEL: digraph "top" # CHECK: label="top"; # CHECK: [shape=record,label="{hw.constant... | 2.697124 | 3 |
python/examples/service_discovery.py | davidgcameron/arc | 0 | 2572 | #! /usr/bin/env python
import arc
import sys
import os
def retrieve(uc, endpoints):
# The ComputingServiceRetriever needs the UserConfig to know which credentials
# to use in case of HTTPS connections
retriever = arc.ComputingServiceRetriever(uc, endpoints)
# the constructor of the ComputingServiceRetr... | #! /usr/bin/env python
import arc
import sys
import os
def retrieve(uc, endpoints):
# The ComputingServiceRetriever needs the UserConfig to know which credentials
# to use in case of HTTPS connections
retriever = arc.ComputingServiceRetriever(uc, endpoints)
# the constructor of the ComputingServiceRetr... | en | 0.738727 | #! /usr/bin/env python # The ComputingServiceRetriever needs the UserConfig to know which credentials # to use in case of HTTPS connections # the constructor of the ComputingServiceRetriever returns immediately # here we want to wait until all the results arrive # Creating a UserConfig object with the user's proxy # an... | 2.509087 | 3 |
core/domain/rights_manager.py | netajik/oppia | 0 | 2573 | <reponame>netajik/oppia<gh_stars>0
# coding: utf-8
#
# Copyright 2014 The Oppia 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/li... | # coding: utf-8
#
# Copyright 2014 The Oppia 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 requi... | en | 0.809848 | # coding: utf-8 # # Copyright 2014 The Oppia 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 requi... | 1.618868 | 2 |
pkg_resources/_vendor/packaging/_typing.py | GDGSNF/setuptools | 0 | 2574 | """For neatly implementing static typing in packaging.
`mypy` - the static type analysis tool we use - uses the `typing` module, which
provides core functionality fundamental to mypy's functioning.
Generally, `typing` would be imported at runtime and used in that fashion -
it acts as a no-op at runtime and does not h... | """For neatly implementing static typing in packaging.
`mypy` - the static type analysis tool we use - uses the `typing` module, which
provides core functionality fundamental to mypy's functioning.
Generally, `typing` would be imported at runtime and used in that fashion -
it acts as a no-op at runtime and does not h... | en | 0.902996 | For neatly implementing static typing in packaging. `mypy` - the static type analysis tool we use - uses the `typing` module, which provides core functionality fundamental to mypy's functioning. Generally, `typing` would be imported at runtime and used in that fashion - it acts as a no-op at runtime and does not have... | 2.568184 | 3 |
selfdrive/car/toyota/carcontroller.py | aolin480/openpilot | 70 | 2575 | <filename>selfdrive/car/toyota/carcontroller.py
from cereal import car
from common.numpy_fast import clip, interp
from selfdrive.car import apply_toyota_steer_torque_limits, create_gas_interceptor_command, make_can_msg
from selfdrive.car.toyota.toyotacan import create_steer_command, create_ui_command, \
... | <filename>selfdrive/car/toyota/carcontroller.py
from cereal import car
from common.numpy_fast import clip, interp
from selfdrive.car import apply_toyota_steer_torque_limits, create_gas_interceptor_command, make_can_msg
from selfdrive.car.toyota.toyotacan import create_steer_command, create_ui_command, \
... | en | 0.807138 | # gas and brake # RAV4 has very sensitive gas pedal # offset for creep and windbrake # steer torque # Cut steering while we're in a known fault state (2s) # TODO: probably can delete this. CS.pcm_acc_status uses a different signal # than CS.cruiseState.enabled. confirm they're not meaningfully different # on entering s... | 2.217978 | 2 |
app/auth/__init__.py | louisenje/Pitches | 0 | 2576 | from flask import Blueprint
auth=Blueprint('auth',__name__)
from .import views,forms | from flask import Blueprint
auth=Blueprint('auth',__name__)
from .import views,forms | none | 1 | 1.410178 | 1 | |
forms/QRGenerator.py | Rono-Barto-Co/Project-QR | 3 | 2577 | <gh_stars>1-10
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField, SelectField
from wtforms.validators import DataRequired
class QRGenerator(FlaskForm):
code_content = StringField('Content', validators=[DataRequired()])
code_size = SelectField('Size', choices=[('15', 'Size'),
... | from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField, SelectField
from wtforms.validators import DataRequired
class QRGenerator(FlaskForm):
code_content = StringField('Content', validators=[DataRequired()])
code_size = SelectField('Size', choices=[('15', 'Size'),
... | none | 1 | 2.55711 | 3 | |
Quiz/m2_advanced_quants/l5_volatility/volatility_estimation.py | jcrangel/AI-for-Trading | 0 | 2578 | import pandas as pd
import numpy as np
def estimate_volatility(prices, l):
"""Create an exponential moving average model of the volatility of a stock
price, and return the most recent (last) volatility estimate.
Parameters
----------
prices : pandas.Series
A series of adjusted closing... | import pandas as pd
import numpy as np
def estimate_volatility(prices, l):
"""Create an exponential moving average model of the volatility of a stock
price, and return the most recent (last) volatility estimate.
Parameters
----------
prices : pandas.Series
A series of adjusted closing... | en | 0.664954 | Create an exponential moving average model of the volatility of a stock price, and return the most recent (last) volatility estimate. Parameters ---------- prices : pandas.Series A series of adjusted closing prices for a stock. l : float The 'lambda' parameter of the ex... | 3.907061 | 4 |
jp.atcoder/abc122/abc122_c/9516079.py | kagemeka/atcoder-submissions | 1 | 2579 | import sys
n, q = map(int, sys.stdin.readline().split())
s = '$' + sys.stdin.readline().rstrip()
lr = zip(*[map(int, sys.stdin.read().split())] * 2)
def main():
res = [None] * (n + 1); res[0] = 0
prev = '$'
for i in range(1, n+1):
res[i] = res[i-1]
res[i] += (prev == 'A' and s[i... | import sys
n, q = map(int, sys.stdin.readline().split())
s = '$' + sys.stdin.readline().rstrip()
lr = zip(*[map(int, sys.stdin.read().split())] * 2)
def main():
res = [None] * (n + 1); res[0] = 0
prev = '$'
for i in range(1, n+1):
res[i] = res[i-1]
res[i] += (prev == 'A' and s[i... | none | 1 | 2.714479 | 3 | |
Decoder.py | gokulsg/Attention-is-all-you-need-implementation-from-scratch | 1 | 2580 | <filename>Decoder.py
import torch
import torch.nn as nn
from DecoderLayer import DecoderLayer
import math
class Decoder(nn.Module):
def __init__(self, output_dim, embed_dim, num_layers, num_heads, expand_dim, dropout, device, max_length = 30):
super().__init__()
self.tok_embedding = nn.Embe... | <filename>Decoder.py
import torch
import torch.nn as nn
from DecoderLayer import DecoderLayer
import math
class Decoder(nn.Module):
def __init__(self, output_dim, embed_dim, num_layers, num_heads, expand_dim, dropout, device, max_length = 30):
super().__init__()
self.tok_embedding = nn.Embe... | en | 0.470582 | #self.pos_embedding = nn.Embedding(max_length, embed_dim) #trg = [batch size, trg len] #enc_src = [batch size, src len, embed dim] #trg_mask = [batch size, 1, trg len, trg len] #src_mask = [batch size, 1, 1, src len] #pos = [batch size, trg len] #trg = [batch size, trg len, embed dim] #trg = [batch size, trg len, embed... | 2.730085 | 3 |
salt/grains/nxos.py | babs/salt | 9,425 | 2581 | <gh_stars>1000+
"""
Grains for Cisco NX-OS minions
.. versionadded:: 2016.11.0
For documentation on setting up the nxos proxy minion look in the documentation
for :mod:`salt.proxy.nxos<salt.proxy.nxos>`.
"""
import logging
import salt.utils.nxos
import salt.utils.platform
from salt.exceptions import NxosClientError... | """
Grains for Cisco NX-OS minions
.. versionadded:: 2016.11.0
For documentation on setting up the nxos proxy minion look in the documentation
for :mod:`salt.proxy.nxos<salt.proxy.nxos>`.
"""
import logging
import salt.utils.nxos
import salt.utils.platform
from salt.exceptions import NxosClientError
log = logging.... | en | 0.246991 | Grains for Cisco NX-OS minions .. versionadded:: 2016.11.0 For documentation on setting up the nxos proxy minion look in the documentation for :mod:`salt.proxy.nxos<salt.proxy.nxos>`. | 2.031586 | 2 |
tmsproviderapisdk/tms_device.py | tvip/tmsproviderapisdk | 0 | 2582 | <gh_stars>0
from typing import List, Optional, Tuple
from tmsproviderapisdk.tms_extended_model import TmsExtendedModel
class TmsDevice(TmsExtendedModel):
_path_url = "/devices/"
def __init__(self, unique_id: str, account: int, device_id: int = None, ipaddr: str = None, mac: str = None,
remot... | from typing import List, Optional, Tuple
from tmsproviderapisdk.tms_extended_model import TmsExtendedModel
class TmsDevice(TmsExtendedModel):
_path_url = "/devices/"
def __init__(self, unique_id: str, account: int, device_id: int = None, ipaddr: str = None, mac: str = None,
remote_custom_fie... | en | 0.406749 | id:{}, ipaddr:{}, mac:{}, unique_id:{}, remote_custom_field: {}, comment: {}, last_online: {}, \ last_fw_ver: {}, first_online: {}, use_nat: {}, operation_system: {}, \ udpxy_addr: {}, device_type: {}, provider: {}, account: {} | 2.274289 | 2 |
fealty/fields.py | eddiejessup/fealty | 0 | 2583 | """
A class hierarchy relating to fields of all kinds.
"""
from __future__ import print_function, division
import numpy as np
from ciabatta.meta import make_repr_str
from fealty import lattice, field_numerics, walled_field_numerics
class Space(object):
def __init__(self, L, dim):
self.L = L
self.... | """
A class hierarchy relating to fields of all kinds.
"""
from __future__ import print_function, division
import numpy as np
from ciabatta.meta import make_repr_str
from fealty import lattice, field_numerics, walled_field_numerics
class Space(object):
def __init__(self, L, dim):
self.L = L
self.... | en | 0.845988 | A class hierarchy relating to fields of all kinds. # Make field zero-valued where obstructed # Note, inheritance order matters to get walled grad & laplacian call # (see diamond problem on wikipedia and how python handles it) | 3.14795 | 3 |
examples/example_django/example_django/asgi.py | cpascariello/aleph-vm | 19 | 2584 | """
ASGI config for example_django project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault("DJANG... | """
ASGI config for example_django project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault("DJANG... | en | 0.669853 | ASGI config for example_django project. It exposes the ASGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/3.2/howto/deployment/asgi/ | 1.897332 | 2 |
lectures/extensions/hyperbolic_discounting/replication_code/src/analysis/get_bivariate_distr_data.py | loikein/ekw-lectures | 4 | 2585 | <filename>lectures/extensions/hyperbolic_discounting/replication_code/src/analysis/get_bivariate_distr_data.py
"""Generate values of Method of Simulated Moments criterion function.
Given observed moments and weighting matrix in `OUT_ANALYSIS`, "msm_estimation",
generate values of Method of Simulated Moments criterion ... | <filename>lectures/extensions/hyperbolic_discounting/replication_code/src/analysis/get_bivariate_distr_data.py
"""Generate values of Method of Simulated Moments criterion function.
Given observed moments and weighting matrix in `OUT_ANALYSIS`, "msm_estimation",
generate values of Method of Simulated Moments criterion ... | en | 0.61688 | Generate values of Method of Simulated Moments criterion function. Given observed moments and weighting matrix in `OUT_ANALYSIS`, "msm_estimation", generate values of Method of Simulated Moments criterion function for combinations of discount factor and present bias values. The goal is to study the bivariate distribu... | 2.828328 | 3 |
space_game/events/KeyPressedEvent.py | Iwomichu/probable-giggle | 1 | 2586 | from dataclasses import dataclass
from space_game.domain_names import KeyId
from space_game.events.Event import Event
@dataclass
class KeyPressedEvent(Event):
key_id: KeyId
| from dataclasses import dataclass
from space_game.domain_names import KeyId
from space_game.events.Event import Event
@dataclass
class KeyPressedEvent(Event):
key_id: KeyId
| none | 1 | 1.859726 | 2 | |
src/oncall/messengers/teams_messenger.py | navoday-91/oncall | 857 | 2587 | <gh_stars>100-1000
import pymsteams
import logging
from oncall.constants import TEAMS_SUPPORT
class teams_messenger(object):
supports = frozenset([TEAMS_SUPPORT])
def __init__(self, config):
self.webhook = config['webhook']
def send(self, message):
heading = message.get("subject")
... | import pymsteams
import logging
from oncall.constants import TEAMS_SUPPORT
class teams_messenger(object):
supports = frozenset([TEAMS_SUPPORT])
def __init__(self, config):
self.webhook = config['webhook']
def send(self, message):
heading = message.get("subject")
final_message = "... | none | 1 | 2.255557 | 2 | |
python/chronos/src/bigdl/chronos/autots/model/auto_prophet.py | Laniakea94/BigDL | 3 | 2588 | # +
#
# Copyright 2016 The BigDL Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to... | # +
#
# Copyright 2016 The BigDL Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to... | en | 0.740268 | # + # # Copyright 2016 The BigDL Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to... | 2.234169 | 2 |
nf/flows.py | arita37/normalizing-flows | 1 | 2589 | <filename>nf/flows.py
import math
import numpy as np
import scipy as sp
import scipy.linalg
import torch
import torch.nn as nn
import torch.nn.init as init
import torch.nn.functional as F
from nf.utils import unconstrained_RQS
# supported non-linearities: note that the function must be invertible
functional_derivative... | <filename>nf/flows.py
import math
import numpy as np
import scipy as sp
import scipy.linalg
import torch
import torch.nn as nn
import torch.nn.init as init
import torch.nn.functional as F
from nf.utils import unconstrained_RQS
# supported non-linearities: note that the function must be invertible
functional_derivative... | en | 0.705607 | # supported non-linearities: note that the function must be invertible Planar flow. z = f(x) = x + u h(wᵀx + b) [<NAME> Mohamed, 2015] Given x, returns z and the log-determinant log|df/dx|. Returns ------- Radial flow. z = f(x) = = x + β h(α, r)(z − z0) [Rezende and Mohamed ... | 2.450191 | 2 |
ioos_qc/config_creator/fx_parser.py | HakaiInstitute/ioos_qc | 0 | 2590 | # module pyparsing.py
#
# Copyright (c) 2003-2019 <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify... | # module pyparsing.py
#
# Copyright (c) 2003-2019 <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify... | en | 0.681503 | # module pyparsing.py # # Copyright (c) 2003-2019 <NAME> # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify... | 2.692974 | 3 |
scanlogger.py | pythonhacker/pyscanlogd | 1 | 2591 | # -- coding: utf-8
#!/usr/bin/env python
"""
pyscanlogger: Port scan detector/logger tool, inspired
by scanlogd {http://www.openwall.com/scanlogd} but with
added ability to log slow port-scans.
Features
1. Detects all stealth (half-open) and full-connect scans.
2. Detects Idle scan and logs it correctly usi... | # -- coding: utf-8
#!/usr/bin/env python
"""
pyscanlogger: Port scan detector/logger tool, inspired
by scanlogd {http://www.openwall.com/scanlogd} but with
added ability to log slow port-scans.
Features
1. Detects all stealth (half-open) and full-connect scans.
2. Detects Idle scan and logs it correctly usi... | en | 0.854254 | # -- coding: utf-8 #!/usr/bin/env python pyscanlogger: Port scan detector/logger tool, inspired
by scanlogd {http://www.openwall.com/scanlogd} but with
added ability to log slow port-scans.
Features
1. Detects all stealth (half-open) and full-connect scans.
2. Detects Idle scan and logs it correctly using corr... | 2.363149 | 2 |
src/util/util.py | ashleylst/DSDmodel | 1 | 2592 | from itertools import combinations
import copy
def get_reverse(n):
if n == 1:
return 0
else:
return 1
def get_edge_info(e):
v = [0 for i in range(2)]
n = [0 for i in range(2)]
t = 0
for x in e:
v[t], n[t] = x
t += 1
return v, n
def sort_e_by_domain(val)... | from itertools import combinations
import copy
def get_reverse(n):
if n == 1:
return 0
else:
return 1
def get_edge_info(e):
v = [0 for i in range(2)]
n = [0 for i in range(2)]
t = 0
for x in e:
v[t], n[t] = x
t += 1
return v, n
def sort_e_by_domain(val)... | en | 0.349269 | :param edges: :return: :param domain1: :param domain2: :return: :param target: :param domains: :return: :param target1: :param target2: :param domains1: :param domains2: :return: :return: | 2.633469 | 3 |
examples/question_answering/qa_sparse_train.py | ebell495/nn_pruning | 250 | 2593 | # coding=utf-8
# Copyright 2020 The HuggingFace Team All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless require... | # coding=utf-8
# Copyright 2020 The HuggingFace Team All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless require... | en | 0.897788 | # coding=utf-8 # Copyright 2020 The HuggingFace Team All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless require... | 1.92112 | 2 |
ironic/drivers/modules/ilo/raid.py | armohamm/ironic | 2 | 2594 | <reponame>armohamm/ironic
# Copyright 2018 Hewlett Packard Enterprise Development LP
#
# 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
#
# Un... | # Copyright 2018 Hewlett Packard Enterprise Development LP
#
# 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 applicabl... | en | 0.764879 | # Copyright 2018 Hewlett Packard Enterprise Development LP # # 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 applicabl... | 1.714976 | 2 |
src/petronia/aid/bootstrap/__init__.py | groboclown/petronia | 19 | 2595 |
"""
Common Petronia imports for bootstrap parts of an extension.
This should be imported along with the `simp` module.
"""
from ...base.bus import (
EventBus,
ListenerRegistrar,
ListenerSetup,
QueuePriority,
ExtensionMetadataStruct,
register_event,
EVENT_WILDCARD,
TARGET_WILDCARD,
... |
"""
Common Petronia imports for bootstrap parts of an extension.
This should be imported along with the `simp` module.
"""
from ...base.bus import (
EventBus,
ListenerRegistrar,
ListenerSetup,
QueuePriority,
ExtensionMetadataStruct,
register_event,
EVENT_WILDCARD,
TARGET_WILDCARD,
... | en | 0.862534 | Common Petronia imports for bootstrap parts of an extension. This should be imported along with the `simp` module. # These are generally just bootstrap events. | 1.567415 | 2 |
examples/dump-properties.py | zachjweiner/pyopencl | 7 | 2596 | <filename>examples/dump-properties.py
import pyopencl as cl
from optparse import OptionParser
parser = OptionParser()
parser.add_option("-s", "--short", action="store_true",
help="don't print all device properties")
(options, args) = parser.parse_args()
def print_info(obj, info_cls):
for info_... | <filename>examples/dump-properties.py
import pyopencl as cl
from optparse import OptionParser
parser = OptionParser()
parser.add_option("-s", "--short", action="store_true",
help="don't print all device properties")
(options, args) = parser.parse_args()
def print_info(obj, info_cls):
for info_... | en | 0.087468 | #cl.mem_flags.READ_WRITE, #cl.mem_flags.WRITE_ONLY | 2.468776 | 2 |
interfaces/acados_template/acados_template/acados_ocp_solver.py | jgillis/acados | 1 | 2597 | # -*- coding: future_fstrings -*-
#
# Copyright 2019 <NAME>, <NAME>, <NAME>,
# <NAME>, <NAME>, <NAME>, <NAME>,
# <NAME>, <NAME>, <NAME>, <NAME>,
# <NAME>, <NAME>, <NAME>, <NAME>, <NAME>
#
# This file is part of acados.
#
# The 2-Clause BSD License
#
# Redistribution and use in source and binary forms, with or without
#... | # -*- coding: future_fstrings -*-
#
# Copyright 2019 <NAME>, <NAME>, <NAME>,
# <NAME>, <NAME>, <NAME>, <NAME>,
# <NAME>, <NAME>, <NAME>, <NAME>,
# <NAME>, <NAME>, <NAME>, <NAME>, <NAME>
#
# This file is part of acados.
#
# The 2-Clause BSD License
#
# Redistribution and use in source and binary forms, with or without
#... | en | 0.601831 | # -*- coding: future_fstrings -*- # # Copyright 2019 <NAME>, <NAME>, <NAME>, # <NAME>, <NAME>, <NAME>, <NAME>, # <NAME>, <NAME>, <NAME>, <NAME>, # <NAME>, <NAME>, <NAME>, <NAME>, <NAME> # # This file is part of acados. # # The 2-Clause BSD License # # Redistribution and use in source and binary forms, with or without #... | 1.147131 | 1 |
noise/estimation/PCA/analyticNoiseEstimation_PCA.py | MaikWischow/Camera-Condition-Monitoring | 3 | 2598 | <reponame>MaikWischow/Camera-Condition-Monitoring<gh_stars>1-10
import numpy as np
import cv2
import sys
import os
import glob
def im2patch(im, pch_size, stride=1):
'''
Transform image to patches.
Input:
im: 3 x H x W or 1 X H x W image, numpy format
pch_size: (int, int) tuple or integer
... | import numpy as np
import cv2
import sys
import os
import glob
def im2patch(im, pch_size, stride=1):
'''
Transform image to patches.
Input:
im: 3 x H x W or 1 X H x W image, numpy format
pch_size: (int, int) tuple or integer
stride: (int, int) tuple or integer
'''
if isinsta... | en | 0.605101 | Transform image to patches. Input: im: 3 x H x W or 1 X H x W image, numpy format pch_size: (int, int) tuple or integer stride: (int, int) tuple or integer Implement of noise level estimation of the following paper: <NAME> , <NAME> , <NAME> . An Efficient Statistical Method for Image Noi... | 2.878555 | 3 |
src/biotite/application/application.py | claudejrogers/biotite | 0 | 2599 | # This source code is part of the Biotite package and is distributed
# under the 3-Clause BSD License. Please see 'LICENSE.rst' for further
# information.
__name__ = "biotite.application"
__author__ = "<NAME>"
__all__ = ["Application", "AppStateError", "TimeoutError", "VersionError",
"AppState", "requires_s... | # This source code is part of the Biotite package and is distributed
# under the 3-Clause BSD License. Please see 'LICENSE.rst' for further
# information.
__name__ = "biotite.application"
__author__ = "<NAME>"
__all__ = ["Application", "AppStateError", "TimeoutError", "VersionError",
"AppState", "requires_s... | en | 0.822165 | # This source code is part of the Biotite package and is distributed # under the 3-Clause BSD License. Please see 'LICENSE.rst' for further # information. This enum type represents the app states of an application. A decorator for methods of :class:`Application` subclasses that raises an :class:`AppStateError` in c... | 2.624662 | 3 |