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 |
|---|---|---|---|---|---|---|---|---|---|---|
fts/fluxrss.py | AetherBlack/Veille-Informatique | 0 | 1400 | <gh_stars>0
#!/usr/bin/python3
from urllib.parse import urlparse
import feedparser
import requests
import asyncio
import discord
import hashlib
import os
from const import CHANNEL_RSS, WAIT_UNTIL_NEW_CHECK, \
SQLITE_FOLDER_NAME, SQLITE_FILE_NAME
from fts.database import Database
from fts.cleandatabase import Cle... | #!/usr/bin/python3
from urllib.parse import urlparse
import feedparser
import requests
import asyncio
import discord
import hashlib
import os
from const import CHANNEL_RSS, WAIT_UNTIL_NEW_CHECK, \
SQLITE_FOLDER_NAME, SQLITE_FILE_NAME
from fts.database import Database
from fts.cleandatabase import CleanDatabase
... | en | 0.673937 | #!/usr/bin/python3 Class of FluxRSS. Get news of the feedrss url parse in args. Initialize class @param => DiscordBot: `bot`: Discord Bot Instance. @param => str: `cwd`: Current Working Directory of main.py file. # Discord # Path # Database Get the news of the rss feed. @param => str: `url`:... | 2.790868 | 3 |
src/poke_env/player/player_network_interface.py | kiyohiro8/poke-env | 0 | 1401 | <filename>src/poke_env/player/player_network_interface.py<gh_stars>0
# -*- coding: utf-8 -*-
"""This module defines a base class for communicating with showdown servers.
"""
import json
import logging
import requests
import websockets # pyre-ignore
from abc import ABC
from abc import abstractmethod
from asyncio impo... | <filename>src/poke_env/player/player_network_interface.py<gh_stars>0
# -*- coding: utf-8 -*-
"""This module defines a base class for communicating with showdown servers.
"""
import json
import logging
import requests
import websockets # pyre-ignore
from abc import ABC
from abc import abstractmethod
from asyncio impo... | en | 0.753068 | # -*- coding: utf-8 -*- This module defines a base class for communicating with showdown servers. # pyre-ignore # pyre-ignore Network interface of a player. Responsible for communicating with showdown servers. Also implements some higher level methods for basic tasks, such as changing avatar and low-level mess... | 2.26398 | 2 |
data/external/repositories/42139/KDDCup13Track2-master/blocking.py | Keesiu/meta-kaggle | 0 | 1402 | #!/usr/bin/env python
from common import *
import csv
import argparse
from unidecode import unidecode
from nameparser import constants as npc
from collections import defaultdict
import cPickle as pickle
import re
stopwords_custom = set(['document', 'preparation', 'system', 'consortium', 'committee', 'international', '... | #!/usr/bin/env python
from common import *
import csv
import argparse
from unidecode import unidecode
from nameparser import constants as npc
from collections import defaultdict
import cPickle as pickle
import re
stopwords_custom = set(['document', 'preparation', 'system', 'consortium', 'committee', 'international', '... | en | 0.255119 | #!/usr/bin/env python # bk = bins.keys() # for b in bk: # if len(bins[b]) > max_bin_size: # del bins[b] | 2.392185 | 2 |
resources/dot_PyCharm/system/python_stubs/-762174762/PySide/QtCore/QAbstractFileEngineIterator.py | basepipe/developer_onboarding | 1 | 1403 | <reponame>basepipe/developer_onboarding<gh_stars>1-10
# encoding: utf-8
# module PySide.QtCore
# from C:\Python27\lib\site-packages\PySide\QtCore.pyd
# by generator 1.147
# no doc
# imports
import Shiboken as __Shiboken
class QAbstractFileEngineIterator(__Shiboken.Object):
# no doc
def currentFileInfo(self, ... | # encoding: utf-8
# module PySide.QtCore
# from C:\Python27\lib\site-packages\PySide\QtCore.pyd
# by generator 1.147
# no doc
# imports
import Shiboken as __Shiboken
class QAbstractFileEngineIterator(__Shiboken.Object):
# no doc
def currentFileInfo(self, *args, **kwargs): # real signature unknown
pas... | en | 0.661864 | # encoding: utf-8 # module PySide.QtCore # from C:\Python27\lib\site-packages\PySide\QtCore.pyd # by generator 1.147 # no doc # imports # no doc # real signature unknown # real signature unknown # real signature unknown # real signature unknown # real signature unknown # real signature unknown # real signature unknown ... | 1.648309 | 2 |
tests/conftest.py | priyatharsan/beyond | 0 | 1404 | <gh_stars>0
import numpy as np
from pytest import fixture, mark, skip
from unittest.mock import patch
from pathlib import Path
from beyond.config import config
from beyond.dates.eop import Eop
from beyond.frames.stations import create_station
from beyond.io.tle import Tle
from beyond.propagators.keplernum import Keple... | import numpy as np
from pytest import fixture, mark, skip
from unittest.mock import patch
from pathlib import Path
from beyond.config import config
from beyond.dates.eop import Eop
from beyond.frames.stations import create_station
from beyond.io.tle import Tle
from beyond.propagators.keplernum import KeplerNum
from be... | en | 0.651043 | Create a dummy config dict containing basic data ISS (ZARYA) 1 25544U 98067A 18124.55610684 .00001524 00000-0 30197-4 0 9997 2 25544 51.6421 236.2139 0003381 47.8509 47.6767 15.54198229111731 MOLNIYA 1-90 1 24960U 97054A 18123.22759647 .00000163 00000-0 24467-3 0 9999 2 24960 62.6812 182.7824 6470982 29... | 1.860811 | 2 |
diofant/tests/integrals/test_heurisch.py | Electric-tric/diofant | 1 | 1405 | <filename>diofant/tests/integrals/test_heurisch.py
import pytest
from diofant import (Add, Derivative, Ei, Eq, Function, I, Integral, LambertW,
Piecewise, Rational, Sum, Symbol, acos, asin, asinh,
besselj, cos, cosh, diff, erf, exp, li, log, pi, ratsimp,
r... | <filename>diofant/tests/integrals/test_heurisch.py
import pytest
from diofant import (Add, Derivative, Ei, Eq, Function, I, Integral, LambertW,
Piecewise, Rational, Sum, Symbol, acos, asin, asinh,
besselj, cos, cosh, diff, erf, exp, li, log, pi, ratsimp,
r... | en | 0.652046 | # Up to a constant, where C = 5*pi*I/12, Mathematica gives identical # result in the first case. The difference is because diofant changes # signs of expressions without any care. # XXX ^ ^ ^ is this still correct? # gives sin(x) in answer when run via setup.py and cos(x) when run via py.test # issue sympy/sympy#6926 #... | 2.277818 | 2 |
kornia/color/adjust.py | carlosb1/kornia | 0 | 1406 | from typing import Union
import torch
import torch.nn as nn
from kornia.color.hsv import rgb_to_hsv, hsv_to_rgb
from kornia.constants import pi
def adjust_saturation_raw(input: torch.Tensor, saturation_factor: Union[float, torch.Tensor]) -> torch.Tensor:
r"""Adjust color saturation of an image. Expecting input ... | from typing import Union
import torch
import torch.nn as nn
from kornia.color.hsv import rgb_to_hsv, hsv_to_rgb
from kornia.constants import pi
def adjust_saturation_raw(input: torch.Tensor, saturation_factor: Union[float, torch.Tensor]) -> torch.Tensor:
r"""Adjust color saturation of an image. Expecting input ... | en | 0.709538 | Adjust color saturation of an image. Expecting input to be in hsv format already. See :class:`~kornia.color.AdjustSaturation` for details. # unpack the hsv values # transform the hue value and appl module # pack back back the corrected hue Adjust color saturation of an image. See :class:`~kornia.color.AdjustS... | 2.641063 | 3 |
pommerman/__init__.py | rmccann01/playground | 725 | 1407 | <filename>pommerman/__init__.py
'''Entry point into the pommerman module'''
import gym
import inspect
from . import agents
from . import configs
from . import constants
from . import forward_model
from . import helpers
from . import utility
from . import network
gym.logger.set_level(40)
REGISTRY = None
def _register... | <filename>pommerman/__init__.py
'''Entry point into the pommerman module'''
import gym
import inspect
from . import agents
from . import configs
from . import constants
from . import forward_model
from . import helpers
from . import utility
from . import network
gym.logger.set_level(40)
REGISTRY = None
def _register... | en | 0.878594 | Entry point into the pommerman module # Register environments with gym Makes the pommerman env and registers it with gym # NOTE: This is IMPORTANT so that the agent character is initialized | 2.459047 | 2 |
demo/demo/accounts/urls.py | caravancoop/rest-auth-toolkit | 1 | 1408 | from django.urls import path
from .views import ProfileView
urlpatterns = [
path('', ProfileView.as_view(), name='user-profile'),
]
| from django.urls import path
from .views import ProfileView
urlpatterns = [
path('', ProfileView.as_view(), name='user-profile'),
]
| none | 1 | 1.580173 | 2 | |
test/test_pipeline/components/classification/test_passive_aggressive.py | vardaan-raj/auto-sklearn | 1 | 1409 | import sklearn.linear_model
from autosklearn.pipeline.components.classification.passive_aggressive import \
PassiveAggressive
from .test_base import BaseClassificationComponentTest
class PassiveAggressiveComponentTest(BaseClassificationComponentTest):
__test__ = True
res = dict()
res["default_iris... | import sklearn.linear_model
from autosklearn.pipeline.components.classification.passive_aggressive import \
PassiveAggressive
from .test_base import BaseClassificationComponentTest
class PassiveAggressiveComponentTest(BaseClassificationComponentTest):
__test__ = True
res = dict()
res["default_iris... | none | 1 | 2.404253 | 2 | |
tensorflow_datasets/structured/dart/dart_test.py | harsh020/datasets | 1 | 1410 | <gh_stars>1-10
# coding=utf-8
# Copyright 2020 The TensorFlow Datasets 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 r... | # coding=utf-8
# Copyright 2020 The TensorFlow Datasets 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 appl... | en | 0.79907 | # coding=utf-8 # Copyright 2020 The TensorFlow Datasets 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 appl... | 2.305525 | 2 |
exp/exp_informer_dad.py | AdamLohSg/GTA | 8 | 1411 | from data.data_loader_dad import (
NASA_Anomaly,
WADI
)
from exp.exp_basic import Exp_Basic
from models.model import Informer
from utils.tools import EarlyStopping, adjust_learning_rate
from utils.metrics import metric
from sklearn.metrics import classification_report
import numpy as np
import torch
import t... | from data.data_loader_dad import (
NASA_Anomaly,
WADI
)
from exp.exp_basic import Exp_Basic
from models.model import Informer
from utils.tools import EarlyStopping, adjust_learning_rate
from utils.metrics import metric
from sklearn.metrics import classification_report
import numpy as np
import torch
import t... | en | 0.117673 | # decoder input # encoder - decoder # decoder input # encoder - decoder # decoder input # encoder - decoder #.squeeze() #.squeeze() # result save | 2.075423 | 2 |
tests/components/mysensors/conftest.py | liangleslie/core | 30,023 | 1412 | <filename>tests/components/mysensors/conftest.py
"""Provide common mysensors fixtures."""
from __future__ import annotations
from collections.abc import AsyncGenerator, Callable, Generator
import json
from typing import Any
from unittest.mock import AsyncMock, MagicMock, patch
from mysensors import BaseSyncGateway
fr... | <filename>tests/components/mysensors/conftest.py
"""Provide common mysensors fixtures."""
from __future__ import annotations
from collections.abc import AsyncGenerator, Callable, Generator
import json
from typing import Any
from unittest.mock import AsyncMock, MagicMock, patch
from mysensors import BaseSyncGateway
fr... | en | 0.698364 | Provide common mysensors fixtures. Mock out device tracker known devices storage. Mock the MQTT integration. Patch the serial port check. Return the gateway nodes dict. Mock a serial transport. Mock the gateway features. Load nodes from via persistence. # For some reason autospeccing does not recognize these methods. M... | 2.169054 | 2 |
Detect.py | SymenYang/Vanish-Point-Detect | 2 | 1413 | import cv2 as cv
import numpy as np
import copy
import math
import Edges
import INTPoint
eps = 1e-7
votes = {}
Groups = []
VPoints = []
Centers = []
Cluster = []
voters = {}
def getEdges(image):
#moved to Edges.py
return Edges.getEdges(image)
def getLines(edges):
#moved to Edges.py
return Edges.getLin... | import cv2 as cv
import numpy as np
import copy
import math
import Edges
import INTPoint
eps = 1e-7
votes = {}
Groups = []
VPoints = []
Centers = []
Cluster = []
voters = {}
def getEdges(image):
#moved to Edges.py
return Edges.getEdges(image)
def getLines(edges):
#moved to Edges.py
return Edges.getLin... | en | 0.764908 | #moved to Edges.py #moved to Edges.py #moved to Edges.py #moved to Edges.py #moved to Edges.py #moved to Edges.py #moved to Edges.py #moved to Edges.py #moved to Edges.py #moved to Edges.py #moved to INTPoint.py #moved to Edges.py #moved to INTPoint.py #this function is fallen into disuse because of the low speed #move... | 2.4492 | 2 |
test/test_files.py | wanasit/labelling-notebook | 0 | 1414 | def test_list_example_directory(client):
response = client.get("/api/files")
assert response.status_code == 200
file_list = response.get_json()
assert len(file_list) == 5
assert file_list[0]['key'] == 'image_annotated.jpg'
assert file_list[1]['key'] == 'image.jpg'
assert file_list[2]['key']... | def test_list_example_directory(client):
response = client.get("/api/files")
assert response.status_code == 200
file_list = response.get_json()
assert len(file_list) == 5
assert file_list[0]['key'] == 'image_annotated.jpg'
assert file_list[1]['key'] == 'image.jpg'
assert file_list[2]['key']... | none | 1 | 2.512204 | 3 | |
Part-03-Understanding-Software-Crafting-Your-Own-Tools/models/edx-platform/openedx/core/djangoapps/course_groups/migrations/0001_initial.py | osoco/better-ways-of-thinking-about-software | 3 | 1415 | from django.db import migrations, models
from django.conf import settings
from opaque_keys.edx.django.models import CourseKeyField
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
... | from django.db import migrations, models
from django.conf import settings
from opaque_keys.edx.django.models import CourseKeyField
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
... | none | 1 | 1.958389 | 2 | |
kafka-rockset-integration/generate_customers_data.py | farkaskid/recipes | 21 | 1416 | <filename>kafka-rockset-integration/generate_customers_data.py
"""Generate Customer Data"""
import csv
import random
from config import MIN_CUSTOMER_ID, MAX_CUSTOMER_ID
ACQUISITION_SOURCES = [
'OrganicSearch',
'PaidSearch',
'Email',
'SocialMedia',
'Display',
'Affiliate'
'Referral'
]
def... | <filename>kafka-rockset-integration/generate_customers_data.py
"""Generate Customer Data"""
import csv
import random
from config import MIN_CUSTOMER_ID, MAX_CUSTOMER_ID
ACQUISITION_SOURCES = [
'OrganicSearch',
'PaidSearch',
'Email',
'SocialMedia',
'Display',
'Affiliate'
'Referral'
]
def... | en | 0.518567 | Generate Customer Data | 3.286564 | 3 |
parsl/tests/test_error_handling/test_resource_spec.py | MatthewBM/parsl | 0 | 1417 | <gh_stars>0
import parsl
from parsl.app.app import python_app
from parsl.tests.configs.local_threads import config
from parsl.executors.errors import UnsupportedFeatureError
from parsl.executors import WorkQueueExecutor
@python_app
def double(x, parsl_resource_specification={}):
return x * 2
def test_resource(n... | import parsl
from parsl.app.app import python_app
from parsl.tests.configs.local_threads import config
from parsl.executors.errors import UnsupportedFeatureError
from parsl.executors import WorkQueueExecutor
@python_app
def double(x, parsl_resource_specification={}):
return x * 2
def test_resource(n=2):
spe... | none | 1 | 2.390133 | 2 | |
cincan/file_tool.py | cincanproject/cincan-command | 1 | 1418 | <filename>cincan/file_tool.py
import pathlib
import re
from typing import List, Optional, Dict, Set, Tuple, Iterable
import shlex
class FileMatcher:
"""Match files based on a pattern"""
def __init__(self, match_string: str, include: bool):
self.match_string = match_string
self.exact = '*' not i... | <filename>cincan/file_tool.py
import pathlib
import re
from typing import List, Optional, Dict, Set, Tuple, Iterable
import shlex
class FileMatcher:
"""Match files based on a pattern"""
def __init__(self, match_string: str, include: bool):
self.match_string = match_string
self.exact = '*' not i... | en | 0.930179 | Match files based on a pattern Parse pattens from a list Filter uploaded files by this pattern Filter downloaded files by this pattern # matching absolute files # matching files relative to working directory Match value with this pattern Resolve files from command line arguments # Additional punctuation chars, whereas ... | 3.166571 | 3 |
aws_interface/cloud/auth/set_me.py | hubaimaster/aws-interface | 53 | 1419 |
from cloud.permission import Permission, NeedPermission
from cloud.message import error
# Define the input output format of the function.
# This information is used when creating the *SDK*.
info = {
'input_format': {
'session_id': 'str',
'field': 'str',
'value?': 'str',
},
'output_... |
from cloud.permission import Permission, NeedPermission
from cloud.message import error
# Define the input output format of the function.
# This information is used when creating the *SDK*.
info = {
'input_format': {
'session_id': 'str',
'field': 'str',
'value?': 'str',
},
'output_... | en | 0.59529 | # Define the input output format of the function. # This information is used when creating the *SDK*. # For security | 2.598321 | 3 |
doc/gallery-src/analysis/run_blockMcnpMaterialCard.py | celikten/armi | 1 | 1420 | <filename>doc/gallery-src/analysis/run_blockMcnpMaterialCard.py
"""
Write MCNP Material Cards
=========================
Here we load a test reactor and write each component of one fuel block out as
MCNP material cards.
Normally, code-specific utility code would belong in a code-specific ARMI
plugin. But in this case,... | <filename>doc/gallery-src/analysis/run_blockMcnpMaterialCard.py
"""
Write MCNP Material Cards
=========================
Here we load a test reactor and write each component of one fuel block out as
MCNP material cards.
Normally, code-specific utility code would belong in a code-specific ARMI
plugin. But in this case,... | en | 0.88825 | Write MCNP Material Cards ========================= Here we load a test reactor and write each component of one fuel block out as MCNP material cards. Normally, code-specific utility code would belong in a code-specific ARMI plugin. But in this case, the need for MCNP materials cards is so pervasive that it made it i... | 2.46433 | 2 |
life_line_chart/_autogenerate_data.py | mustaqimM/life_line_chart | 0 | 1421 | import names
import os
import datetime
from random import random
def generate_gedcom_file():
"""generate some gedcom file"""
db = {}
db['n_individuals'] = 0
db['max_individuals'] = 8000
db['n_families'] = 0
db['yougest'] = None
gedcom_content = """
0 HEAD
1 SOUR Gramps
2 VERS 3.3.0
2 N... | import names
import os
import datetime
from random import random
def generate_gedcom_file():
"""generate some gedcom file"""
db = {}
db['n_individuals'] = 0
db['max_individuals'] = 8000
db['n_families'] = 0
db['yougest'] = None
gedcom_content = """
0 HEAD
1 SOUR Gramps
2 VERS 3.3.0
2 N... | en | 0.501534 | generate some gedcom file 0 HEAD 1 SOUR Gramps 2 VERS 3.3.0 2 NAME Gramps 1 DATE {} 2 TIME 15:35:24 1 SUBM @SUBM@ 1 COPR Copyright (c) 2020 <NAME>,,,. 1 GEDC 2 VERS 5.5 1 CHAR UTF-8 1 LANG German 0 {individual_id} INDI 1 NAME {first_name} /{last_name}/ 1 SEX {sex} 1 BIRT 2 DATE {birth_date} 2 PLAC {birth_place} 1 DEAT ... | 3.364356 | 3 |
arcade/examples/sprite_bullets_enemy_aims.py | LiorAvrahami/arcade | 1 | 1422 | <filename>arcade/examples/sprite_bullets_enemy_aims.py
"""
Show how to have enemies shoot bullets aimed at the player.
If Python and Arcade are installed, this example can be run from the command line with:
python -m arcade.examples.sprite_bullets_enemy_aims
"""
import arcade
import math
import os
SCREEN_WIDTH = 800... | <filename>arcade/examples/sprite_bullets_enemy_aims.py
"""
Show how to have enemies shoot bullets aimed at the player.
If Python and Arcade are installed, this example can be run from the command line with:
python -m arcade.examples.sprite_bullets_enemy_aims
"""
import arcade
import math
import os
SCREEN_WIDTH = 800... | en | 0.883551 | Show how to have enemies shoot bullets aimed at the player. If Python and Arcade are installed, this example can be run from the command line with: python -m arcade.examples.sprite_bullets_enemy_aims Main application class # Set the working directory (where we expect to find files) to the same # directory this .py fil... | 3.821783 | 4 |
app1.py | FreakX23/EBook_Training | 0 | 1423 | <reponame>FreakX23/EBook_Training<filename>app1.py
# This Part will gather Infos and demonstrate the use of Variables.
usrName = input("What is your Name?")
usrAge = int(input("What is your Age?"))
usrGPA = float(input("What is your GPA?"))
print () #cheap way to get a new line
print ("Hello, %s" % (usrName))
print ("D... | # This Part will gather Infos and demonstrate the use of Variables.
usrName = input("What is your Name?")
usrAge = int(input("What is your Age?"))
usrGPA = float(input("What is your GPA?"))
print () #cheap way to get a new line
print ("Hello, %s" % (usrName))
print ("Did you know that in two years you will be %d years ... | en | 0.712958 | # This Part will gather Infos and demonstrate the use of Variables. #cheap way to get a new line | 3.967449 | 4 |
borze.py | AmitHasanShuvo/Programming | 8 | 1424 | <reponame>AmitHasanShuvo/Programming
a = input()
a = a.replace('--', '2')
a = a.replace('-.', '1')
a = a.replace('.', '0')
print(a)
| a = input()
a = a.replace('--', '2')
a = a.replace('-.', '1')
a = a.replace('.', '0')
print(a) | none | 1 | 3.382329 | 3 | |
distalg/message.py | charlesemurray/DistributedProgramming | 0 | 1425 | <reponame>charlesemurray/DistributedProgramming
class Message:
def __init__(self, from_channel=None, **kwargs):
self._channel = from_channel
if kwargs is not None:
for key, value in kwargs.items():
setattr(self, key, value)
@property
def carrier(self):
re... | class Message:
def __init__(self, from_channel=None, **kwargs):
self._channel = from_channel
if kwargs is not None:
for key, value in kwargs.items():
setattr(self, key, value)
@property
def carrier(self):
return self._channel
def sender(self):
... | none | 1 | 3.024378 | 3 | |
myenv/lib/python3.5/site-packages/tests/handlers/logging/logging_tests.py | rupeshparab/techscan | 1 | 1426 | <reponame>rupeshparab/techscan
import logging
from opbeat.handlers.logging import OpbeatHandler
from opbeat.utils.stacks import iter_stack_frames
from tests.helpers import get_tempstoreclient
from tests.utils.compat import TestCase
class LoggingIntegrationTest(TestCase):
def setUp(self):
self.client = ge... | import logging
from opbeat.handlers.logging import OpbeatHandler
from opbeat.utils.stacks import iter_stack_frames
from tests.helpers import get_tempstoreclient
from tests.utils.compat import TestCase
class LoggingIntegrationTest(TestCase):
def setUp(self):
self.client = get_tempstoreclient(include_paths... | en | 0.384608 | # self.assertEquals(event['message'], 'This is a test info with an exception') # self.assertEquals(event['message'], 'This is a test of args') # print event.keys() | 2.441436 | 2 |
amnesia/modules/mime/model.py | silenius/amnesia | 4 | 1427 | # -*- coding: utf-8 -*-
# pylint: disable=E1101
from sqlalchemy import sql
from sqlalchemy import orm
from sqlalchemy.orm.exc import NoResultFound
from .. import Base
# http://www.iana.org/assignments/media-types/media-types.xhtml
class MimeMajor(Base):
"""Mime major"""
def __init__(self, name):
... | # -*- coding: utf-8 -*-
# pylint: disable=E1101
from sqlalchemy import sql
from sqlalchemy import orm
from sqlalchemy.orm.exc import NoResultFound
from .. import Base
# http://www.iana.org/assignments/media-types/media-types.xhtml
class MimeMajor(Base):
"""Mime major"""
def __init__(self, name):
... | en | 0.343684 | # -*- coding: utf-8 -*- # pylint: disable=E1101 # http://www.iana.org/assignments/media-types/media-types.xhtml Mime major ########### # Filters # ########### | 2.142295 | 2 |
apps/goods/views_base.py | sunwei19910119/DjangoShop | 3 | 1428 | # encoding: utf-8
from goods.models import Goods
from django.views.generic.base import View
class GoodsListView(View):
def get(self, request):
"""
通过django的view实现商品列表页
"""
json_list = []
goods = Goods.objects.all()[:10]
# for good in goods:
# json_dict ... | # encoding: utf-8
from goods.models import Goods
from django.views.generic.base import View
class GoodsListView(View):
def get(self, request):
"""
通过django的view实现商品列表页
"""
json_list = []
goods = Goods.objects.all()[:10]
# for good in goods:
# json_dict ... | en | 0.187975 | # encoding: utf-8 通过django的view实现商品列表页 # for good in goods: # json_dict = {} # json_dict["name"] = good.name # json_dict["category"] = good.category.name # json_dict["market_price"] = good.market_price # json_dict["add_time"] = good.add_time # json_list.append(json_dict) # from django.http impor... | 2.246785 | 2 |
launcher/src/main/scripts/bin/launcher.py | iyersathya/airlift | 0 | 1429 | <filename>launcher/src/main/scripts/bin/launcher.py
#!/usr/bin/env python
import errno
import os
import platform
import sys
import traceback
from fcntl import flock, LOCK_EX, LOCK_NB
from optparse import OptionParser
from os import O_RDWR, O_CREAT, O_WRONLY, O_APPEND
from os.path import basename, dirname, exists, rea... | <filename>launcher/src/main/scripts/bin/launcher.py
#!/usr/bin/env python
import errno
import os
import platform
import sys
import traceback
from fcntl import flock, LOCK_EX, LOCK_NB
from optparse import OptionParser
from os import O_RDWR, O_CREAT, O_WRONLY, O_APPEND
from os.path import basename, dirname, exists, rea... | en | 0.721848 | #!/usr/bin/env python Find canonical parent of bin/launcher.py Create directory and all intermediate ones Load key/value pairs from a file Load lines from a file, ignoring blank or comment lines Try to open an exclusive lock (inheritable) on a file # IOError in Python 2, OSError in Python 3. Open file in read/write mod... | 2.362391 | 2 |
code/sim/test.py | vectorcrumb/Ballbot_IEE2913 | 0 | 1430 | <filename>code/sim/test.py
from direct.showbase.ShowBase import ShowBase
from direct.task import Task
from direct.actor.Actor import Actor
import numpy as np
class MyApp(ShowBase):
def __init__(self):
ShowBase.__init__(self)
# Load environment model
self.scene = self.loader.loadModel("mode... | <filename>code/sim/test.py
from direct.showbase.ShowBase import ShowBase
from direct.task import Task
from direct.actor.Actor import Actor
import numpy as np
class MyApp(ShowBase):
def __init__(self):
ShowBase.__init__(self)
# Load environment model
self.scene = self.loader.loadModel("mode... | en | 0.805298 | # Load environment model # Reparent model to render # Scale and position model # Add spinCameraTask to task manager to execute # Load and transform panda actor # Loop animation | 2.372248 | 2 |
run_locally.py | nationalarchives/tdr-service-unavailable | 0 | 1431 | <filename>run_locally.py
from app import app
app.run()
| <filename>run_locally.py
from app import app
app.run()
| none | 1 | 1.289787 | 1 | |
src/pandas_profiling/model/describe.py | briangrahamww/pandas-profiling | 0 | 1432 | """Organize the calculation of statistics for each series in this DataFrame."""
import warnings
from datetime import datetime
from typing import Optional
import pandas as pd
from tqdm.auto import tqdm
from visions import VisionsTypeset
from pandas_profiling.config import Settings
from pandas_profiling.model.correlati... | """Organize the calculation of statistics for each series in this DataFrame."""
import warnings
from datetime import datetime
from typing import Optional
import pandas as pd
from tqdm.auto import tqdm
from visions import VisionsTypeset
from pandas_profiling.config import Settings
from pandas_profiling.model.correlati... | en | 0.709202 | Organize the calculation of statistics for each series in this DataFrame. Calculate the statistics for each series in this DataFrame. Args: config: report Settings object df: DataFrame. sample: optional, dict with custom sample Returns: This function returns a dictionary contai... | 2.444009 | 2 |
maxOfferNum.py | Ruanxingzhi/King-of-Pigeon | 0 | 1433 | <gh_stars>0
import operator
class Std(object):
def __init__(self):
self.name = ''
self.offerNum = 0
self.offers = []
stds = []
stdsDict = {}
index = 0
def readStd(name,camper):
global stds
global stdsDict
global index
if name not in stdsDict:
newStd = Std()
... | import operator
class Std(object):
def __init__(self):
self.name = ''
self.offerNum = 0
self.offers = []
stds = []
stdsDict = {}
index = 0
def readStd(name,camper):
global stds
global stdsDict
global index
if name not in stdsDict:
newStd = Std()
newStd.name... | none | 1 | 3.190847 | 3 | |
tabnine-vim/third_party/ycmd/third_party/python-future/setup.py | MrMonk3y/vimrc | 2 | 1434 | #!/usr/bin/env python
from __future__ import absolute_import, print_function
import os
import os.path
import sys
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
if sys.argv[-1] == 'publish':
os.system('python setup.py sdist upload')
sys.exit()
NAME = "futur... | #!/usr/bin/env python
from __future__ import absolute_import, print_function
import os
import os.path
import sys
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
if sys.argv[-1] == 'publish':
os.system('python setup.py sdist upload')
sys.exit()
NAME = "futur... | en | 0.628085 | #!/usr/bin/env python # for future.tests.base # "future.tests.test_email", # "past.tests", # PEP 3108 stdlib moves: # * Important * # We forcibly remove the build folder to avoid breaking the # user's Py3 installation if they run "python2 setup.py # build" and then "python3 setup.py install". # If the user happens to r... | 1.68546 | 2 |
url_shortener/src/__init__.py | Andrelpoj/hire.me | 0 | 1435 | <gh_stars>0
from flask import Flask
from .extensions import db
from .routes import short
from . import config
def create_app():
""" Creates Flask App, connect to Database and register Blueprint of routes"""
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = config.DATABASE_CONNECTION_URI... | from flask import Flask
from .extensions import db
from .routes import short
from . import config
def create_app():
""" Creates Flask App, connect to Database and register Blueprint of routes"""
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = config.DATABASE_CONNECTION_URI
app.co... | en | 0.814654 | Creates Flask App, connect to Database and register Blueprint of routes | 2.570569 | 3 |
python-百度翻译调用/Baidu_translate/com/translate/baidu/stackoverflow_question_handler.py | wangchuanli001/Project-experience | 12 | 1436 | import requests
from bs4 import BeautifulSoup
import urllib.request
import os
import random
import time
def html(url):
user_agents = [
'Mozilla/5.0 (Windows; U; Windows NT 5.1; it; rv:1.8.1.11) Gecko/20071127 Firefox/2.0.0.11',
'Opera/9.25 (Windows NT 5.1; U; en)',
'Mozilla/4.0 (compatible... | import requests
from bs4 import BeautifulSoup
import urllib.request
import os
import random
import time
def html(url):
user_agents = [
'Mozilla/5.0 (Windows; U; Windows NT 5.1; it; rv:1.8.1.11) Gecko/20071127 Firefox/2.0.0.11',
'Opera/9.25 (Windows NT 5.1; U; en)',
'Mozilla/4.0 (compatible... | en | 0.20193 | # title views answersnum asked_time tag_str active_time quest_content_ text answer_content_list # updatetosql(item) | 2.85181 | 3 |
Research/data_loader.py | ALEXKIRNAS/Kaggle-C-CORE-Iceberg-Classifier-Challenge | 0 | 1437 | import os
import numpy as np
import pandas as pd
from keras.utils import to_categorical
from sklearn.model_selection import KFold, train_test_split
def load_data(path):
train = pd.read_json(os.path.join(path, "./train.json"))
test = pd.read_json(os.path.join(path, "./test.json"))
return (train, test)
... | import os
import numpy as np
import pandas as pd
from keras.utils import to_categorical
from sklearn.model_selection import KFold, train_test_split
def load_data(path):
train = pd.read_json(os.path.join(path, "./train.json"))
test = pd.read_json(os.path.join(path, "./test.json"))
return (train, test)
... | none | 1 | 2.657368 | 3 | |
polyaxon_cli/cli/experiment.py | tiagopms/polyaxon-cli | 0 | 1438 | # -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
import sys
import click
import rhea
from polyaxon_cli.cli.getters.experiment import (
get_experiment_job_or_local,
get_project_experiment_or_local
)
from polyaxon_cli.cli.upload import upload
from polyaxon_cli.client imp... | # -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
import sys
import click
import rhea
from polyaxon_cli.cli.getters.experiment import (
get_experiment_job_or_local,
get_project_experiment_or_local
)
from polyaxon_cli.cli.upload import upload
from polyaxon_cli.client imp... | en | 0.495322 | # -*- coding: utf-8 -*- # pylint:disable=redefined-outer-name # pylint:disable=redefined-outer-name Commands for experiments. Get experiment or experiment job. Uses [Caching](/references/polyaxon-cli/#caching) Examples for getting an experiment: \b ```bash $ polyaxon experiment get # if experime... | 1.942061 | 2 |
Problem_09.py | Habbo3/Project-Euler | 0 | 1439 | """
A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
a2 + b2 = c2
For example, 32 + 42 = 9 + 16 = 25 = 52.
There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc.
"""
solved = False
for a in range(1, 1000):
for b in range(1, 1000):
for c in range(... | """
A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
a2 + b2 = c2
For example, 32 + 42 = 9 + 16 = 25 = 52.
There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc.
"""
solved = False
for a in range(1, 1000):
for b in range(1, 1000):
for c in range(... | en | 0.819379 | A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, a2 + b2 = c2 For example, 32 + 42 = 9 + 16 = 25 = 52. There exists exactly one Pythagorean triplet for which a + b + c = 1000. Find the product abc. | 4.20419 | 4 |
fanscribed/apps/transcripts/tests/test_transcripts.py | fanscribed/fanscribed | 8 | 1440 | <filename>fanscribed/apps/transcripts/tests/test_transcripts.py
from decimal import Decimal
import os
from django.test import TestCase
from unipath import Path
from ....utils import refresh
from ...media import tests
from ..models import Transcript, TranscriptMedia
MEDIA_TESTDATA_PATH = Path(tests.__file__).parent.... | <filename>fanscribed/apps/transcripts/tests/test_transcripts.py
from decimal import Decimal
import os
from django.test import TestCase
from unipath import Path
from ....utils import refresh
from ...media import tests
from ..models import Transcript, TranscriptMedia
MEDIA_TESTDATA_PATH = Path(tests.__file__).parent.... | en | 0.530426 | # Process raw media. # Check length. # 5 minutes. | 2.335759 | 2 |
buildAncestryFeats.py | BurcinSayin/pf2 | 0 | 1441 | from bs4 import BeautifulSoup
import requests
import json
import datetime
import codecs
import re
featHolder = {}
featHolder['name'] = 'Pathfinder 2.0 Ancestry feat list'
featHolder['date'] = datetime.date.today().strftime("%B %d, %Y")
def get_details(link):
res = requests.get(link)
res.raise_for_status()
... | from bs4 import BeautifulSoup
import requests
import json
import datetime
import codecs
import re
featHolder = {}
featHolder['name'] = 'Pathfinder 2.0 Ancestry feat list'
featHolder['date'] = datetime.date.today().strftime("%B %d, %Y")
def get_details(link):
res = requests.get(link)
res.raise_for_status()
... | en | 0.739086 | #First we grab the content from the meta tag #Now we split it into groups of strings seperated by < >, to pull out any links #Finally, we join every other group together (passing over the link groups) into one string #print(detail) #print(row) #print("-----------------------------------") #We do next_sibling here becau... | 3.146039 | 3 |
Random_item_selector_module.py | Jahronimo/public_question_book_framework | 0 | 1442 | <reponame>Jahronimo/public_question_book_framework
import random
def Randomise(questions_lists):
import random
import secrets
secure_random = secrets.SystemRandom()# creates a secure random object.
group_of_items = questions_lists
num_qustion_t_select = num_question_to_dis... | import random
def Randomise(questions_lists):
import random
import secrets
secure_random = secrets.SystemRandom()# creates a secure random object.
group_of_items = questions_lists
num_qustion_t_select = num_question_to_display
list_of_random_item... | en | 0.953199 | # creates a secure random object. # randomly selecting from strings within each question list # I think this is where i need to add in some information but don't understand. #printing some kind of structure with numbers of question and space to answer. | 4.073956 | 4 |
python_scrape/test_functions.py | jose-marquez89/tech-job-landscape | 0 | 1443 | import unittest
import scrape
class TestScrapeFunctions(unittest.TestCase):
def test_build_url(self):
url = scrape.build_url("indeed",
"/jobs?q=Data+Scientist&l=Texas&start=10",
join_next=True)
expected = ("https://www.indeed.com/"
... | import unittest
import scrape
class TestScrapeFunctions(unittest.TestCase):
def test_build_url(self):
url = scrape.build_url("indeed",
"/jobs?q=Data+Scientist&l=Texas&start=10",
join_next=True)
expected = ("https://www.indeed.com/"
... | none | 1 | 3.127416 | 3 | |
Level1_Input_Output/10172.py | jaeheeLee17/BOJ_Algorithms | 0 | 1444 | def main():
print("|\_/|")
print("|q p| /}")
print("( 0 )\"\"\"\\")
print("|\"^\"` |")
print("||_/=\\\\__|")
if __name__ == "__main__":
main()
| def main():
print("|\_/|")
print("|q p| /}")
print("( 0 )\"\"\"\\")
print("|\"^\"` |")
print("||_/=\\\\__|")
if __name__ == "__main__":
main()
| none | 1 | 2.574683 | 3 | |
Whats Cooking/KaggleCookingComparison.py | rupakc/Kaggle-Compendium | 17 | 1445 | <reponame>rupakc/Kaggle-Compendium
# -*- coding: utf-8 -*-
"""
Created on Sat Dec 26 13:20:45 2015
Code for Kaggle What's Cooking Competition
It uses the following classifiers with tf-idf,hashvectors and bag_of_words approach
1. Adaboost
2. Extratrees
3. Bagging
4. Random Forests
@author: <NAME>
"""
import numpy as np... | # -*- coding: utf-8 -*-
"""
Created on Sat Dec 26 13:20:45 2015
Code for Kaggle What's Cooking Competition
It uses the following classifiers with tf-idf,hashvectors and bag_of_words approach
1. Adaboost
2. Extratrees
3. Bagging
4. Random Forests
@author: <NAME>
"""
import numpy as np
import time
import json
import Cla... | en | 0.789299 | # -*- coding: utf-8 -*- Created on Sat Dec 26 13:20:45 2015 Code for Kaggle What's Cooking Competition It uses the following classifiers with tf-idf,hashvectors and bag_of_words approach 1. Adaboost 2. Extratrees 3. Bagging 4. Random Forests @author: <NAME> # Create the feature extractors # Create the Classifier object... | 2.804202 | 3 |
pybook/ch10/DeckOfCards.py | YanhaoXu/python-learning | 2 | 1446 | import random
# Create a deck of cards
deck = [x for x in range(52)]
# Create suits and ranks lists
suits = ["Spades", "Hearts", "Diamonds", "Clubs"]
ranks = ["Ace", "2", "3", "4", "5", "6", "7", "8", "9",
"10", "Jack", "Queen", "King"]
# Shuffle the cards
random.shuffle(deck)
# Display the first four card... | import random
# Create a deck of cards
deck = [x for x in range(52)]
# Create suits and ranks lists
suits = ["Spades", "Hearts", "Diamonds", "Clubs"]
ranks = ["Ace", "2", "3", "4", "5", "6", "7", "8", "9",
"10", "Jack", "Queen", "King"]
# Shuffle the cards
random.shuffle(deck)
# Display the first four card... | en | 0.861778 | # Create a deck of cards # Create suits and ranks lists # Shuffle the cards # Display the first four cards | 3.723293 | 4 |
nlpgnn/gnn/RGCNConv.py | ojipadeson/NLPGNN | 263 | 1447 | <gh_stars>100-1000
#! usr/bin/env python3
# -*- coding:utf-8 -*-
"""
@Author:<NAME>
Usage:
node_embeddings = tf.random.normal(shape=(5, 3))
adjacency_lists = [
tf.constant([[0, 1], [2, 4], [2, 4]], dtype=tf.int32),
tf.constant([[0, 1], [2, 4], [2, 4]], dtype=tf.int32)
... | #! usr/bin/env python3
# -*- coding:utf-8 -*-
"""
@Author:<NAME>
Usage:
node_embeddings = tf.random.normal(shape=(5, 3))
adjacency_lists = [
tf.constant([[0, 1], [2, 4], [2, 4]], dtype=tf.int32),
tf.constant([[0, 1], [2, 4], [2, 4]], dtype=tf.int32)
]
layer = RG... | en | 0.305479 | #! usr/bin/env python3 # -*- coding:utf-8 -*- @Author:<NAME> Usage: node_embeddings = tf.random.normal(shape=(5, 3)) adjacency_lists = [ tf.constant([[0, 1], [2, 4], [2, 4]], dtype=tf.int32), tf.constant([[0, 1], [2, 4], [2, 4]], dtype=tf.int32) ] layer = RGraph... | 2.342651 | 2 |
automl/google/cloud/automl_v1beta1/gapic/auto_ml_client.py | erikwebb/google-cloud-python | 1 | 1448 | # -*- coding: utf-8 -*-
#
# Copyright 2018 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... | # -*- coding: utf-8 -*-
#
# Copyright 2018 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... | en | 0.664815 | # -*- coding: utf-8 -*- # # Copyright 2018 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... | 1.09565 | 1 |
addons/project/models/project.py | SHIVJITH/Odoo_Machine_Test | 0 | 1449 | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import ast
from datetime import timedelta, datetime
from random import randint
from odoo import api, fields, models, tools, SUPERUSER_ID, _
from odoo.exceptions import UserError, AccessError, ValidationError, RedirectWa... | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import ast
from datetime import timedelta, datetime
from random import randint
from odoo import api, fields, models, tools, SUPERUSER_ID, _
from odoo.exceptions import UserError, AccessError, ValidationError, RedirectWa... | en | 0.751098 | # -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. # retrieves all the projects with a least 1 task in that stage # a task can be in a stage even if the project is not assigned to the stage # takes all existing ratings # Project User has no write access for project. # rat... | 1.963407 | 2 |
app/config.py | Maethorin/pivocram | 5 | 1450 | <gh_stars>1-10
# -*- coding: utf-8 -*-
"""
Config File for enviroment variables
"""
import os
from importlib import import_module
class Config(object):
"""
Base class for all config variables
"""
DEBUG = False
TESTING = False
DEVELOPMENT = False
CSRF_ENABLED = True
SQLALCHEMY_DATABAS... | # -*- coding: utf-8 -*-
"""
Config File for enviroment variables
"""
import os
from importlib import import_module
class Config(object):
"""
Base class for all config variables
"""
DEBUG = False
TESTING = False
DEVELOPMENT = False
CSRF_ENABLED = True
SQLALCHEMY_DATABASE_URI = os.envi... | en | 0.722952 | # -*- coding: utf-8 -*- Config File for enviroment variables Base class for all config variables Production Config... this is the real thing Staging Config is for... staging things Development Config... this is your home developer! Test Config... You should be testing right now instead reading docs!!! Raises when the ... | 2.847929 | 3 |
initial_load.py | hongyuanChrisLi/RealEstateDBConvert | 0 | 1451 | <reponame>hongyuanChrisLi/RealEstateDBConvert
from mysql_dao.select_dao import SelectDao as MysqlSelectDao
from postgres_dao.ddl_dao import DdlDao
from postgres_dao.dml_dao import DmlDao as PsqlDmlDao
psql_ddl_dao = DdlDao()
mysql_select_dao = MysqlSelectDao()
psql_dml_dao = PsqlDmlDao()
psql_ddl_dao.create_tables()
... | from mysql_dao.select_dao import SelectDao as MysqlSelectDao
from postgres_dao.ddl_dao import DdlDao
from postgres_dao.dml_dao import DmlDao as PsqlDmlDao
psql_ddl_dao = DdlDao()
mysql_select_dao = MysqlSelectDao()
psql_dml_dao = PsqlDmlDao()
psql_ddl_dao.create_tables()
county_data = mysql_select_dao.select_all_cou... | none | 1 | 1.991066 | 2 | |
pytests/docs/docs.py | ramalingam-cb/testrunner | 0 | 1452 | import time
import logger
from basetestcase import BaseTestCase
from couchbase_helper.documentgenerator import DocumentGenerator
from membase.api.rest_client import RestConnection
from couchbase_helper.documentgenerator import BlobGenerator
class DocsTests(BaseTestCase):
def setUp(self):
super(DocsTests, ... | import time
import logger
from basetestcase import BaseTestCase
from couchbase_helper.documentgenerator import DocumentGenerator
from membase.api.rest_client import RestConnection
from couchbase_helper.documentgenerator import BlobGenerator
class DocsTests(BaseTestCase):
def setUp(self):
super(DocsTests, ... | en | 0.667948 | #docs.docs.DocsTests.test_load_memory,nodes_init=3,standard_buckets=3,memcached_buckets=1,replicas=2,quota_percent=75 1) Configure a cluster with 4 Couchbase Buckets and 1 Memcached Buckets. 2) Total memory quota allocated for Couchbase should be approx. 75% (12G) of total RAM. 3) Load initial data on all bucke... | 2.241852 | 2 |
lichthi.py | truongaxin123/lichthidtu | 0 | 1453 | from bs4 import BeautifulSoup
import requests
from urllib.request import urlretrieve
ROOT = 'http://pdaotao.duytan.edu.vn'
def get_url_sub(sub, id_, page):
all_td_tag = []
for i in range(1, page+1):
print('http://pdaotao.duytan.edu.vn/EXAM_LIST/?page={}&lang=VN'.format(i))
r = requests.get('ht... | from bs4 import BeautifulSoup
import requests
from urllib.request import urlretrieve
ROOT = 'http://pdaotao.duytan.edu.vn'
def get_url_sub(sub, id_, page):
all_td_tag = []
for i in range(1, page+1):
print('http://pdaotao.duytan.edu.vn/EXAM_LIST/?page={}&lang=VN'.format(i))
r = requests.get('ht... | en | 0.122731 | # a = get_excel_url('http://pdaotao.duytan.edu.vn/EXAM_LIST_Detail/?ID=52289&lang=VN') | 3.170243 | 3 |
appengine/uploader/main.py | isabella232/feedloader | 5 | 1454 | # coding=utf-8
# 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed ... | # coding=utf-8
# 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed ... | en | 0.859799 | # coding=utf-8 # 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 # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed ... | 1.755189 | 2 |
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/transforms.py | BadDevCode/lumberyard | 1,738 | 1455 | <filename>dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/transforms.py
"""
Implement transformation on Numba IR
"""
from __future__ import absolute_import, print_function
from collections import namedtuple, defaultdict
import logging
from numba.analysis import compute_cfg_from_blocks, find_top_level_loops
f... | <filename>dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/transforms.py
"""
Implement transformation on Numba IR
"""
from __future__ import absolute_import, print_function
from collections import namedtuple, defaultdict
import logging
from numba.analysis import compute_cfg_from_blocks, find_top_level_loops
f... | en | 0.855529 | Implement transformation on Numba IR Returns a list of loops that are candidate for loop lifting # check well-formed-ness of the loop # If the exit point has no successor, it contains an return # statement, which is not handled by the looplifting code. # Thus, this loop is not a candidate. # the check for cfg.entry_poi... | 1.916166 | 2 |
tests/test_masked_inference_wsi_dataset.py | HabibMrad/MONAI | 1 | 1456 | <filename>tests/test_masked_inference_wsi_dataset.py
import os
import unittest
from unittest import skipUnless
import numpy as np
from numpy.testing import assert_array_equal
from parameterized import parameterized
from monai.apps.pathology.datasets import MaskedInferenceWSIDataset
from monai.apps.utils import downlo... | <filename>tests/test_masked_inference_wsi_dataset.py
import os
import unittest
from unittest import skipUnless
import numpy as np
from numpy.testing import assert_array_equal
from parameterized import parameterized
from monai.apps.pathology.datasets import MaskedInferenceWSIDataset
from monai.apps.utils import downlo... | none | 1 | 2.014925 | 2 | |
manga_py/providers/doujins_com.py | paulolimac/manga-py | 1 | 1457 | <gh_stars>1-10
from manga_py.provider import Provider
from .helpers.std import Std
class DoujinsCom(Provider, Std):
img_selector = '#image-container img.doujin'
def get_archive_name(self) -> str:
return 'archive'
def get_chapter_index(self) -> str:
return '0'
def get_main_content(se... | from manga_py.provider import Provider
from .helpers.std import Std
class DoujinsCom(Provider, Std):
img_selector = '#image-container img.doujin'
def get_archive_name(self) -> str:
return 'archive'
def get_chapter_index(self) -> str:
return '0'
def get_main_content(self):
re... | es | 0.742391 | # todo meta | 2.386462 | 2 |
src/urh/ui/delegates/CheckBoxDelegate.py | awesome-archive/urh | 1 | 1458 | <reponame>awesome-archive/urh<filename>src/urh/ui/delegates/CheckBoxDelegate.py
from PyQt5.QtCore import QModelIndex, QAbstractItemModel, Qt, pyqtSlot
from PyQt5.QtWidgets import QItemDelegate, QWidget, QStyleOptionViewItem, QCheckBox
class CheckBoxDelegate(QItemDelegate):
def __init__(self, parent=None):
... | from PyQt5.QtCore import QModelIndex, QAbstractItemModel, Qt, pyqtSlot
from PyQt5.QtWidgets import QItemDelegate, QWidget, QStyleOptionViewItem, QCheckBox
class CheckBoxDelegate(QItemDelegate):
def __init__(self, parent=None):
super().__init__(parent)
self.enabled = True
def createEditor(self... | none | 1 | 2.300323 | 2 | |
neural_network/backup_casestudy/denbigh/tf_RNN.py | acceleratedmaterials/AMDworkshop_demo | 5 | 1459 | # -*- coding: utf-8 -*-
'''
Framework: Tensorflow
Training samples: 1600
Validation samples: 400
RNN with 128 units
Optimizer: Adam
Epoch: 100
Loss: Cross Entropy
Activation function: Relu for network and Soft-max for regression
Regularization: Drop-out, keep_prob = 0.8
Accuracy of Validation set: 95%
'''
from __future... | # -*- coding: utf-8 -*-
'''
Framework: Tensorflow
Training samples: 1600
Validation samples: 400
RNN with 128 units
Optimizer: Adam
Epoch: 100
Loss: Cross Entropy
Activation function: Relu for network and Soft-max for regression
Regularization: Drop-out, keep_prob = 0.8
Accuracy of Validation set: 95%
'''
from __future... | en | 0.725527 | # -*- coding: utf-8 -*- Framework: Tensorflow Training samples: 1600 Validation samples: 400 RNN with 128 units Optimizer: Adam Epoch: 100 Loss: Cross Entropy Activation function: Relu for network and Soft-max for regression Regularization: Drop-out, keep_prob = 0.8 Accuracy of Validation set: 95% #Hyperparams # Number... | 2.83303 | 3 |
code/tests/test_tile_tf.py | Nocty-chan/cs224n-squad | 2 | 1460 | import numpy as np
import tensorflow as tf
H = 2
N = 2
M = 3
BS = 10
def my_softmax(arr):
max_elements = np.reshape(np.max(arr, axis = 2), (BS, N, 1))
arr = arr - max_elements
exp_array = np.exp(arr)
print (exp_array)
sum_array = np.reshape(np.sum(exp_array, axis=2), (BS, N, 1))
return exp_arra... | import numpy as np
import tensorflow as tf
H = 2
N = 2
M = 3
BS = 10
def my_softmax(arr):
max_elements = np.reshape(np.max(arr, axis = 2), (BS, N, 1))
arr = arr - max_elements
exp_array = np.exp(arr)
print (exp_array)
sum_array = np.reshape(np.sum(exp_array, axis=2), (BS, N, 1))
return exp_arra... | en | 0.716994 | Takes masked softmax over given dimension of logits. Inputs: logits: Numpy array. We want to take softmax over dimension dim. mask: Numpy array of same shape as logits. Has 1s where there's real data in logits, 0 where there's padding dim: int. dimension over which to take softmax Re... | 3.431099 | 3 |
specutils/tests/test_smoothing.py | hamogu/specutils | 0 | 1461 | import numpy as np
import pytest
from astropy import convolution
from scipy.signal import medfilt
import astropy.units as u
from ..spectra.spectrum1d import Spectrum1D
from ..tests.spectral_examples import simulated_spectra
from ..manipulation.smoothing import (convolution_smooth, box_smooth,
... | import numpy as np
import pytest
from astropy import convolution
from scipy.signal import medfilt
import astropy.units as u
from ..spectra.spectrum1d import Spectrum1D
from ..tests.spectral_examples import simulated_spectra
from ..manipulation.smoothing import (convolution_smooth, box_smooth,
... | en | 0.754618 | There are two things to compare for each set of smoothing: 1. Compare the smoothed flux from the astropy machinery vs the smoothed flux from specutils. This is done by comparing flux_smooth1 and flux_smooth2. 2. Next we want to compare the smoothed flux to the original flux. This is a l... | 2.287879 | 2 |
modules/interpolator.py | buulikduong/1d_sgl_solver | 0 | 1462 | <reponame>buulikduong/1d_sgl_solver<gh_stars>0
"""Module interpolating mathematical functions out of support points"""
from scipy.interpolate import interp1d, lagrange, CubicSpline
def interpolator(x_sup, y_sup, method):
"""Interpolates a mathematical function from a given set of
points using either linear, ... | """Module interpolating mathematical functions out of support points"""
from scipy.interpolate import interp1d, lagrange, CubicSpline
def interpolator(x_sup, y_sup, method):
"""Interpolates a mathematical function from a given set of
points using either linear, polynomial or cubic spline for the
interpol... | en | 0.579243 | Module interpolating mathematical functions out of support points Interpolates a mathematical function from a given set of points using either linear, polynomial or cubic spline for the interpolation. Args: x_sup (list): x-coordinates of the function y_sup (list): y-coordinates of the funct... | 3.828195 | 4 |
frappe/patches/v13_0/remove_web_view.py | chentaoz/frappe | 3,755 | 1463 | <filename>frappe/patches/v13_0/remove_web_view.py
import frappe
def execute():
frappe.delete_doc_if_exists("DocType", "Web View")
frappe.delete_doc_if_exists("DocType", "Web View Component")
frappe.delete_doc_if_exists("DocType", "CSS Class") | <filename>frappe/patches/v13_0/remove_web_view.py
import frappe
def execute():
frappe.delete_doc_if_exists("DocType", "Web View")
frappe.delete_doc_if_exists("DocType", "Web View Component")
frappe.delete_doc_if_exists("DocType", "CSS Class") | none | 1 | 1.419611 | 1 | |
games.py | cpratim/DSA-Research-Paper | 0 | 1464 | import json
import matplotlib.pyplot as plt
from pprint import pprint
import numpy as np
from scipy.stats import linregress
from util.stats import *
with open('data/game_stats.json', 'r') as f:
df = json.load(f)
X, y = [], []
for match, stats in df.items():
home, away = stats['home'], stats['away']
if home['mp'] !... | import json
import matplotlib.pyplot as plt
from pprint import pprint
import numpy as np
from scipy.stats import linregress
from util.stats import *
with open('data/game_stats.json', 'r') as f:
df = json.load(f)
X, y = [], []
for match, stats in df.items():
home, away = stats['home'], stats['away']
if home['mp'] !... | none | 1 | 2.916226 | 3 | |
src/generate_data.py | gycggd/leaf-classification | 0 | 1465 | import os
import numpy as np
import pandas as pd
import tensorflow as tf
from keras.preprocessing.image import ImageDataGenerator
from keras.preprocessing.image import img_to_array, load_img
from keras.utils.np_utils import to_categorical
from sklearn.model_selection import StratifiedShuffleSplit
from sklearn.preproces... | import os
import numpy as np
import pandas as pd
import tensorflow as tf
from keras.preprocessing.image import ImageDataGenerator
from keras.preprocessing.image import img_to_array, load_img
from keras.utils.np_utils import to_categorical
from sklearn.model_selection import StratifiedShuffleSplit
from sklearn.preproces... | en | 0.494032 | # Prepare ID-to-label and ID-to-numerical dictionary # Convert label to categorical/one-hot # compression = tf.python_io.TFRecordCompressionType.GZIP # train_writer = tf.python_io.TFRecordWriter(train_data_path, options=tf.python_io.TFRecordOptions(compression)) | 2.766695 | 3 |
2650-construindo-muralhas.py | ErickSimoes/URI-Online-Judge | 0 | 1466 | <reponame>ErickSimoes/URI-Online-Judge<gh_stars>0
# -*- coding: utf-8 -*-
n, w = map(int, input().split())
for _ in range(n):
entrada = input()
last_space = entrada.rfind(' ')
if int(entrada[last_space:]) > w:
print(entrada[:last_space])
| # -*- coding: utf-8 -*-
n, w = map(int, input().split())
for _ in range(n):
entrada = input()
last_space = entrada.rfind(' ')
if int(entrada[last_space:]) > w:
print(entrada[:last_space]) | en | 0.769321 | # -*- coding: utf-8 -*- | 3.507506 | 4 |
tests/assemblers/test_ensemble.py | yarix/m2cgen | 1 | 1467 | <gh_stars>1-10
from sklearn import ensemble
from m2cgen import assemblers, ast
from tests import utils
def test_single_condition():
estimator = ensemble.RandomForestRegressor(n_estimators=2, random_state=1)
estimator.fit([[1], [2]], [1, 2])
assembler = assemblers.RandomForestModelAssembler(estimator)
... | from sklearn import ensemble
from m2cgen import assemblers, ast
from tests import utils
def test_single_condition():
estimator = ensemble.RandomForestRegressor(n_estimators=2, random_state=1)
estimator.fit([[1], [2]], [1, 2])
assembler = assemblers.RandomForestModelAssembler(estimator)
actual = ass... | none | 1 | 2.165657 | 2 | |
setup.py | Parquery/pynumenc | 1 | 1468 | <reponame>Parquery/pynumenc
"""A setuptools based setup module.
See:
https://packaging.python.org/en/latest/distributing.html
https://github.com/pypa/sampleproject
"""
import os
from setuptools import setup, find_packages, Extension
import pynumenc_meta
# pylint: disable=redefined-builtin
here = os.path.abspath(os... | """A setuptools based setup module.
See:
https://packaging.python.org/en/latest/distributing.html
https://github.com/pypa/sampleproject
"""
import os
from setuptools import setup, find_packages, Extension
import pynumenc_meta
# pylint: disable=redefined-builtin
here = os.path.abspath(os.path.dirname(__file__)) # ... | en | 0.659022 | A setuptools based setup module. See: https://packaging.python.org/en/latest/distributing.html https://github.com/pypa/sampleproject # pylint: disable=redefined-builtin # pylint: disable=invalid-name # pylint: disable=invalid-name # yapf: disable, # yapf: enable | 1.672991 | 2 |
Models/License-Plate-Recognition-Nigerian-vehicles-master/License-Plate-Recognition-Nigerian-vehicles-master/ocr.py | nipunjain099/AutoGuard | 147 | 1469 | import numpy as np
from skimage.transform import resize
from skimage import measure
from skimage.measure import regionprops
class OCROnObjects():
def __init__(self, license_plate):
character_objects = self.identify_boundary_objects(license_plate)
self.get_regions(character_objects, license_pla... | import numpy as np
from skimage.transform import resize
from skimage import measure
from skimage.measure import regionprops
class OCROnObjects():
def __init__(self, license_plate):
character_objects = self.identify_boundary_objects(license_plate)
self.get_regions(character_objects, license_pla... | en | 0.772177 | used to map out regions where the license plate charcters are the principle of connected component analysis and labelling were used Parameters: ----------- a_license_plate: 2D numpy binary image of the license plate Returns: -------- a dictionary contai... | 3.081798 | 3 |
project/server/models.py | mvlima/flask-jwt-auth | 0 | 1470 | # project/server/models.py
import jwt
import datetime
from project.server import app, db, bcrypt
class User(db.Model):
""" User Model for storing user related details """
__tablename__ = "users"
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
username = db.Column(db.String(255), uni... | # project/server/models.py
import jwt
import datetime
from project.server import app, db, bcrypt
class User(db.Model):
""" User Model for storing user related details """
__tablename__ = "users"
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
username = db.Column(db.String(255), uni... | en | 0.563352 | # project/server/models.py User Model for storing user related details Generates the Auth Token :return: string Validates the auth token :param auth_token: :return: integer|string Token Model for storing JWT tokens # Check whether auth token has been blacklisted | 2.752057 | 3 |
letsencrypt/setup.py | ccppuu/certbot | 1 | 1471 | <reponame>ccppuu/certbot
import codecs
import os
import sys
from setuptools import setup
from setuptools import find_packages
def read_file(filename, encoding='utf8'):
"""Read unicode from given file."""
with codecs.open(filename, encoding=encoding) as fd:
return fd.read()
here = os.path.abspath(os... | import codecs
import os
import sys
from setuptools import setup
from setuptools import find_packages
def read_file(filename, encoding='utf8'):
"""Read unicode from given file."""
with codecs.open(filename, encoding=encoding) as fd:
return fd.read()
here = os.path.abspath(os.path.dirname(__file__))
... | en | 0.792855 | Read unicode from given file. # This package is a simple shim around certbot | 1.891201 | 2 |
elastalert/alerts.py | dekhrekh/elastalert | 0 | 1472 | <filename>elastalert/alerts.py<gh_stars>0
# -*- coding: utf-8 -*-
import copy
import datetime
import json
import logging
import subprocess
import sys
import warnings
from email.mime.text import MIMEText
from email.utils import formatdate
from smtplib import SMTP
from smtplib import SMTP_SSL
from smtplib import SMTPAuth... | <filename>elastalert/alerts.py<gh_stars>0
# -*- coding: utf-8 -*-
import copy
import datetime
import json
import logging
import subprocess
import sys
import warnings
from email.mime.text import MIMEText
from email.utils import formatdate
from smtplib import SMTP
from smtplib import SMTP_SSL
from smtplib import SMTPAuth... | en | 0.885709 | # -*- coding: utf-8 -*- Creates a string containing fields in match for the given rule. # Support referencing other top-level rule properties # This technically may not work if there is a top-level rule property with the same name # as an es result key, since it would have been matched in the lookup_es_key call above #... | 2.185824 | 2 |
tests/unit/python/fledge/services/core/scheduler/test_scheduler.py | DDC-NDRS/fledge-iot_fledge | 69 | 1473 | <filename>tests/unit/python/fledge/services/core/scheduler/test_scheduler.py<gh_stars>10-100
# -*- coding: utf-8 -*-
# FLEDGE_BEGIN
# See: http://fledge-iot.readthedocs.io/
# FLEDGE_END
import asyncio
import datetime
import uuid
import time
import json
from unittest.mock import MagicMock, call
import sys
import copy... | <filename>tests/unit/python/fledge/services/core/scheduler/test_scheduler.py<gh_stars>10-100
# -*- coding: utf-8 -*-
# FLEDGE_BEGIN
# See: http://fledge-iot.readthedocs.io/
# FLEDGE_END
import asyncio
import datetime
import uuid
import time
import json
from unittest.mock import MagicMock, call
import sys
import copy... | en | 0.859204 | # -*- coding: utf-8 -*- # FLEDGE_BEGIN # See: http://fledge-iot.readthedocs.io/ # FLEDGE_END # Changed in version 3.8: patch() now returns an AsyncMock if the target is an async function. # GIVEN # WHEN # Check IF part # THEN # WHEN # Check ELSE part # THEN # GIVEN # WHEN # THEN # After task completion, sleep above, no... | 1.981741 | 2 |
problem_solving/python/algorithms/greedy/marcs_cakewalk.py | kcc3/hackerrank-solutions | 0 | 1474 | def marcs_cakewalk(calorie):
"""Hackerrank Problem: https://www.hackerrank.com/challenges/marcs-cakewalk/problem
Marc loves cupcakes, but he also likes to stay fit. Each cupcake has a calorie count, and Marc can walk a distance
to expend those calories. If Marc has eaten j cupcakes so far, after eating a c... | def marcs_cakewalk(calorie):
"""Hackerrank Problem: https://www.hackerrank.com/challenges/marcs-cakewalk/problem
Marc loves cupcakes, but he also likes to stay fit. Each cupcake has a calorie count, and Marc can walk a distance
to expend those calories. If Marc has eaten j cupcakes so far, after eating a c... | en | 0.927698 | Hackerrank Problem: https://www.hackerrank.com/challenges/marcs-cakewalk/problem Marc loves cupcakes, but he also likes to stay fit. Each cupcake has a calorie count, and Marc can walk a distance to expend those calories. If Marc has eaten j cupcakes so far, after eating a cupcake with c calories he must walk ... | 4.202339 | 4 |
coronaindiatracker/coronatracker/views.py | ankitgoswami23/CoronaIndiaTracker | 2 | 1475 | from django.shortcuts import render
import requests
from bs4 import BeautifulSoup
def corona_data(request):
"Testaaaa"
corona_html = requests.get("https://www.mygov.in/covid-19")
soup = BeautifulSoup(corona_html.content, 'html.parser')
state_wise_data = soup.find_all('div', class_='views-row')
inf... | from django.shortcuts import render
import requests
from bs4 import BeautifulSoup
def corona_data(request):
"Testaaaa"
corona_html = requests.get("https://www.mygov.in/covid-19")
soup = BeautifulSoup(corona_html.content, 'html.parser')
state_wise_data = soup.find_all('div', class_='views-row')
inf... | none | 1 | 2.396643 | 2 | |
compare.py | geohackweek/ghw2019_wiggles | 3 | 1476 | # Script tests GPD model using UW truth data
# Test outputs:
# - type of event tested [EQS, EQP, SUS, SUP, THS, THP, SNS, SNP, PXS, PXP]
# - phase [P, S, N] Note: N - not detected
# - model time offset (t_truth - t_model_pick)
import numpy
import math
import string
import datetime
import sys
import os
im... | # Script tests GPD model using UW truth data
# Test outputs:
# - type of event tested [EQS, EQP, SUS, SUP, THS, THP, SNS, SNP, PXS, PXP]
# - phase [P, S, N] Note: N - not detected
# - model time offset (t_truth - t_model_pick)
import numpy
import math
import string
import datetime
import sys
import os
im... | en | 0.714253 | # Script tests GPD model using UW truth data # Test outputs: # - type of event tested [EQS, EQP, SUS, SUP, THS, THP, SNS, SNP, PXS, PXP] # - phase [P, S, N] Note: N - not detected # - model time offset (t_truth - t_model_pick) # params # file dirs # ------------------ # read in UW arrival times as an arra... | 2.49683 | 2 |
ultitrackerapi/ultitrackerapi/extract_and_upload_video.py | atheheath/ultitracker-api | 0 | 1477 | import argparse
import boto3
import datetime
import json
import os
import posixpath
import re
import shutil
import tempfile
import uuid
from concurrent import futures
from multiprocessing import Pool
from ultitrackerapi import get_backend, get_logger, get_s3Client, video
backend_instance = get_backend()
logger = ... | import argparse
import boto3
import datetime
import json
import os
import posixpath
import re
import shutil
import tempfile
import uuid
from concurrent import futures
from multiprocessing import Pool
from ultitrackerapi import get_backend, get_logger, get_s3Client, video
backend_instance = get_backend()
logger = ... | en | 0.330867 | UPDATE ultitracker.game_metadata SET data = jsonb_set(data, '{{length}}', '"{video_length}"', true) WHERE game_id = '{game_id}' INSERT INTO ultitracker.img_location (img_id, img_raw_path, img_type, img_metadata, game_id, frame_number) VALUES ('{img_id}', '{img_raw_path}', '{img_type}', '{img_metadata}', '{game_... | 1.992679 | 2 |
Chapter03/scikit_soft_voting_2knn.py | PacktPublishing/Hands-On-Ensemble-Learning-with-Python | 31 | 1478 | # --- SECTION 1 ---
# Import the required libraries
from sklearn import datasets, naive_bayes, svm, neighbors
from sklearn.ensemble import VotingClassifier
from sklearn.metrics import accuracy_score
# Load the dataset
breast_cancer = datasets.load_breast_cancer()
x, y = breast_cancer.data, breast_cancer.target
... | # --- SECTION 1 ---
# Import the required libraries
from sklearn import datasets, naive_bayes, svm, neighbors
from sklearn.ensemble import VotingClassifier
from sklearn.metrics import accuracy_score
# Load the dataset
breast_cancer = datasets.load_breast_cancer()
x, y = breast_cancer.data, breast_cancer.target
... | en | 0.901689 | # --- SECTION 1 --- # Import the required libraries # Load the dataset # Split the train and test samples # --- SECTION 2 --- # Instantiate the learners (classifiers) # --- SECTION 3 --- # Instantiate the voting classifier # --- SECTION 4 --- # Fit classifier with the training data # --- SECTION 5 --- # Predict th... | 3.005414 | 3 |
API/migrations/0005_alter_news_date_time_alter_news_headline.py | kgarchie/ReSTful-Django-API | 0 | 1479 | <gh_stars>0
# Generated by Django 4.0.3 on 2022-03-23 14:31
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('API', '0004_alter_news_date_time_alter_news_headline'),
]
operations = [
migrations.AlterField(
mode... | # Generated by Django 4.0.3 on 2022-03-23 14:31
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('API', '0004_alter_news_date_time_alter_news_headline'),
]
operations = [
migrations.AlterField(
model_name='news... | en | 0.8339 | # Generated by Django 4.0.3 on 2022-03-23 14:31 | 1.659508 | 2 |
qiskit/ml/datasets/iris.py | stefan-woerner/aqua | 504 | 1480 | # This code is part of Qiskit.
#
# (C) Copyright IBM 2018, 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivat... | # This code is part of Qiskit.
#
# (C) Copyright IBM 2018, 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivat... | en | 0.857092 | # This code is part of Qiskit. # # (C) Copyright IBM 2018, 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivat... | 2.612551 | 3 |
tests/h/views/api_auth_test.py | discodavey/h | 0 | 1481 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import datetime
import json
import mock
import pytest
from oauthlib.oauth2 import InvalidRequestFatalError
from oauthlib.common import Request as OAuthRequest
from pyramid import httpexceptions
from h._compat import urlparse
from h.exceptions import O... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import datetime
import json
import mock
import pytest
from oauthlib.oauth2 import InvalidRequestFatalError
from oauthlib.common import Request as OAuthRequest
from pyramid import httpexceptions
from h._compat import urlparse
from h.exceptions import O... | en | 0.769321 | # -*- coding: utf-8 -*- | 2.261411 | 2 |
tools/build/v2/test/conditionals.py | juslee/boost-svn | 1 | 1482 | <filename>tools/build/v2/test/conditionals.py
#!/usr/bin/python
# Copyright 2003 <NAME>
# Copyright 2002, 2003, 2004 <NAME>
# Distributed under the Boost Software License, Version 1.0.
# (See accompanying file LICENSE_1_0.txt or copy at
# http://www.boost.org/LICENSE_1_0.txt)
# Test conditional properties.
import Bo... | <filename>tools/build/v2/test/conditionals.py
#!/usr/bin/python
# Copyright 2003 <NAME>
# Copyright 2002, 2003, 2004 <NAME>
# Distributed under the Boost Software License, Version 1.0.
# (See accompanying file LICENSE_1_0.txt or copy at
# http://www.boost.org/LICENSE_1_0.txt)
# Test conditional properties.
import Bo... | en | 0.709803 | #!/usr/bin/python # Copyright 2003 <NAME> # Copyright 2002, 2003, 2004 <NAME> # Distributed under the Boost Software License, Version 1.0. # (See accompanying file LICENSE_1_0.txt or copy at # http://www.boost.org/LICENSE_1_0.txt) # Test conditional properties. # Arrange a project which will build only if 'a.cpp' is co... | 1.9597 | 2 |
examples/setuptools-rust-starter/tests/test_setuptools_rust_starter.py | FriendRat/pyo3 | 1 | 1483 | <gh_stars>1-10
from setuptools_rust_starter import PythonClass, ExampleClass
def test_python_class() -> None:
py_class = PythonClass(value=10)
assert py_class.value == 10
def test_example_class() -> None:
example = ExampleClass(value=11)
assert example.value == 11
| from setuptools_rust_starter import PythonClass, ExampleClass
def test_python_class() -> None:
py_class = PythonClass(value=10)
assert py_class.value == 10
def test_example_class() -> None:
example = ExampleClass(value=11)
assert example.value == 11 | none | 1 | 2.219108 | 2 | |
spiders/juejin_spider.py | sunhailin-Leo/TeamLeoX_BlogsCrawler | 0 | 1484 | import time
from typing import Dict, List, Tuple, Optional
from utils.logger_utils import LogManager
from utils.str_utils import check_is_json
from config import LOG_LEVEL, PROCESS_STATUS_FAIL
from utils.time_utils import datetime_str_change_fmt
from utils.exception_utils import LoginException, ParseDataException
from... | import time
from typing import Dict, List, Tuple, Optional
from utils.logger_utils import LogManager
from utils.str_utils import check_is_json
from config import LOG_LEVEL, PROCESS_STATUS_FAIL
from utils.time_utils import datetime_str_change_fmt
from utils.exception_utils import LoginException, ParseDataException
from... | zh | 0.95818 | 解析用户名 :return: 结果 # 公共参数 # 重要参数持久化 # 个人数据 # TODO 后面考虑多线程进行任务拆分,并发获取数据 # logger.debug(self._like_blogs_data) # 任务末尾 | 2.005798 | 2 |
NAS/PaddleSlim/train_supernet.py | naviocean/SimpleCVReproduction | 923 | 1485 | from paddle.vision.transforms import (
ToTensor, RandomHorizontalFlip, RandomResizedCrop, SaturationTransform, Compose,
HueTransform, BrightnessTransform, ContrastTransform, RandomCrop, Normalize, RandomRotation
)
from paddle.vision.datasets import Cifar100
from paddle.io import DataLoader
from paddle.optimizer... | from paddle.vision.transforms import (
ToTensor, RandomHorizontalFlip, RandomResizedCrop, SaturationTransform, Compose,
HueTransform, BrightnessTransform, ContrastTransform, RandomCrop, Normalize, RandomRotation
)
from paddle.vision.datasets import Cifar100
from paddle.io import DataLoader
from paddle.optimizer... | en | 0.481155 | # supernet trainning 基于paddleslim模型压缩包 # https://github.com/PaddlePaddle/PaddleSlim 欢迎大家多多star # channel_list.append(random.choice([ 4, 8, 12, 16])) # channel_list.append(random.choice([ 4, 8, 12, 16, 20, 24, 28, 32])) # channel_list.append(random.choice([ 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 48, 52, 56,60, 64])) ... | 2.119939 | 2 |
slashtags/mixins/commands.py | Myst1c-a/phen-cogs | 0 | 1486 | <reponame>Myst1c-a/phen-cogs<filename>slashtags/mixins/commands.py<gh_stars>0
"""
MIT License
Copyright (c) 2020-present phenom4n4n
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 restric... | """
MIT License
Copyright (c) 2020-present phenom4n4n
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, merge, pub... | en | 0.677012 | MIT License Copyright (c) 2020-present phenom4n4n 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, merge, publish... | 1.317539 | 1 |
prgm6.py | pooja-bs-3003/Project_21 | 0 | 1487 | str1= input("enter a string :")
l1 =""
for i in str1 [::-1]:
l1 = i+l1
print(l1)
if str1 == l1:
print("string is a palindrome")
else :
print("string is not a palindrome")
| str1= input("enter a string :")
l1 =""
for i in str1 [::-1]:
l1 = i+l1
print(l1)
if str1 == l1:
print("string is a palindrome")
else :
print("string is not a palindrome")
| none | 1 | 4.149636 | 4 | |
product_spider/spiders/jk_spider.py | Pandaaaa906/product_spider | 0 | 1488 | import json
import re
from string import ascii_uppercase
from time import time
from urllib.parse import urljoin
import scrapy
from more_itertools import first
from scrapy import Request
from product_spider.items import JkProduct, JKPackage
from product_spider.utils.functions import strip
class JkPrdSpider(scrapy.Sp... | import json
import re
from string import ascii_uppercase
from time import time
from urllib.parse import urljoin
import scrapy
from more_itertools import first
from scrapy import Request
from product_spider.items import JkProduct, JKPackage
from product_spider.utils.functions import strip
class JkPrdSpider(scrapy.Sp... | none | 1 | 2.66724 | 3 | |
env/LaneChangeEnv_v2.py | byq-luo/Lane_change_RL | 4 | 1489 | import os
import sys
import random
import datetime
import gym
from gym import spaces
import numpy as np
from env.IDM import IDM
from env.Road import Road
from env.Vehicle import Vehicle
import math
# add sumo/tools into python environment
if 'SUMO_HOME' in os.environ:
tools = os.path.join(os.environ['SUMO_HOME'], ... | import os
import sys
import random
import datetime
import gym
from gym import spaces
import numpy as np
from env.IDM import IDM
from env.Road import Road
from env.Vehicle import Vehicle
import math
# add sumo/tools into python environment
if 'SUMO_HOME' in os.environ:
tools = os.path.join(os.environ['SUMO_HOME'], ... | en | 0.529136 | # add sumo/tools into python environment ###################################################################### # simulation environments # todo check traffic flow density # average 9 vehicles # average 19 vehicles # average 14 vehicles # arguments must be string, if float/int, must be converted to str(float/int), inst... | 2.31683 | 2 |
cidr/o365/o365.py | jblukach/distillery | 1 | 1490 | import boto3
import ipaddress
import json
import logging
import os
import requests
import uuid
logger = logging.getLogger()
logger.setLevel(logging.INFO)
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table(os.environ['DYNAMODB_TABLE'])
client = boto3.client('ssm')
def downloader(instance, latest, param... | import boto3
import ipaddress
import json
import logging
import os
import requests
import uuid
logger = logging.getLogger()
logger.setLevel(logging.INFO)
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table(os.environ['DYNAMODB_TABLE'])
client = boto3.client('ssm')
def downloader(instance, latest, param... | en | 0.190851 | #'+instance+'#'+cidr['serviceArea']+'#'+ip #': #': | 2.029174 | 2 |
exampleinc.py | zulip/finbot | 7 | 1491 | <reponame>zulip/finbot
#!/usr/bin/python
from money import *
c = Company("Example Inc")
c.add_flow(FixedCost("Initial Cash", -500000))
c.add_flow(FixedCost("Incorporation", 500))
c.add_flow(ConstantCost("Office", 50000))
c.add_flow(PeriodicCost("Subscription", 4000, "2012-01-05", 14))
c.add_flow(DelayedCost("2012-02-0... | #!/usr/bin/python
from money import *
c = Company("Example Inc")
c.add_flow(FixedCost("Initial Cash", -500000))
c.add_flow(FixedCost("Incorporation", 500))
c.add_flow(ConstantCost("Office", 50000))
c.add_flow(PeriodicCost("Subscription", 4000, "2012-01-05", 14))
c.add_flow(DelayedCost("2012-02-01", ConstantCost("Offic... | ru | 0.258958 | #!/usr/bin/python | 3.138536 | 3 |
guardian/validators.py | dawid1stanek/guardian | 0 | 1492 | #!/usr/bin/env python
import os
import socket
import subprocess
import argparse
import logging
LOGGER = logging.getLogger(__name__)
class ValidatorError(Exception):
pass
def ping(address):
try:
subprocess.check_call(('ping', '-c 1', '-W 1', address), stdout=subprocess.PIPE, stderr=subprocess.PIPE)... | #!/usr/bin/env python
import os
import socket
import subprocess
import argparse
import logging
LOGGER = logging.getLogger(__name__)
class ValidatorError(Exception):
pass
def ping(address):
try:
subprocess.check_call(('ping', '-c 1', '-W 1', address), stdout=subprocess.PIPE, stderr=subprocess.PIPE)... | ru | 0.26433 | #!/usr/bin/env python | 3.033657 | 3 |
tests/data/udf_noop.py | Open-EO/openeo-geopyspark-driver | 12 | 1493 | <reponame>Open-EO/openeo-geopyspark-driver
from openeo.udf import XarrayDataCube
def apply_datacube(cube: XarrayDataCube, context: dict) -> XarrayDataCube:
return cube
| from openeo.udf import XarrayDataCube
def apply_datacube(cube: XarrayDataCube, context: dict) -> XarrayDataCube:
return cube | none | 1 | 1.630896 | 2 | |
StateGoHome.py | LHGames-2017/superintelligence | 0 | 1494 | from PlayerState import *
from pathFinder import PathFinder
from StateLook4Resources import *
class StateGoHome(PlayerState):
""" State Implementation: has a resource and go back home """
def __init__(self, player):
self.player = player
self.player.setTarget(self.player.playerData.HouseLocati... | from PlayerState import *
from pathFinder import PathFinder
from StateLook4Resources import *
class StateGoHome(PlayerState):
""" State Implementation: has a resource and go back home """
def __init__(self, player):
self.player = player
self.player.setTarget(self.player.playerData.HouseLocati... | en | 0.941612 | State Implementation: has a resource and go back home # If player just gave the resource home, look 4 resources again | 2.940002 | 3 |
hoomd/mpcd/test-py/stream_slit_test.py | schwendp/hoomd-blue | 2 | 1495 | <reponame>schwendp/hoomd-blue
# Copyright (c) 2009-2019 The Regents of the University of Michigan
# This file is part of the HOOMD-blue project, released under the BSD 3-Clause License.
# Maintainer: mphoward
import unittest
import numpy as np
import hoomd
from hoomd import md
from hoomd import mpcd
# unit tests for... | # Copyright (c) 2009-2019 The Regents of the University of Michigan
# This file is part of the HOOMD-blue project, released under the BSD 3-Clause License.
# Maintainer: mphoward
import unittest
import numpy as np
import hoomd
from hoomd import md
from hoomd import mpcd
# unit tests for mpcd slit streaming geometry
... | en | 0.839692 | # Copyright (c) 2009-2019 The Regents of the University of Michigan # This file is part of the HOOMD-blue project, released under the BSD 3-Clause License. # Maintainer: mphoward # unit tests for mpcd slit streaming geometry # establish the simulation context # set the decomposition in z for mpi builds # default testin... | 2.265724 | 2 |
tests/functional/model_models.py | haoyuchen1992/CourseBuilder | 1 | 1496 | # Copyright 2013 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ... | # Copyright 2013 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ... | en | 0.849705 | # Copyright 2013 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ... | 1.965603 | 2 |
torchaudio/functional/functional.py | iseessel/audio | 0 | 1497 | # -*- coding: utf-8 -*-
import io
import math
import warnings
from typing import Optional, Tuple
import torch
from torch import Tensor
from torchaudio._internal import module_utils as _mod_utils
import torchaudio
__all__ = [
"spectrogram",
"griffinlim",
"amplitude_to_DB",
"DB_to_amplitude",
"comp... | # -*- coding: utf-8 -*-
import io
import math
import warnings
from typing import Optional, Tuple
import torch
from torch import Tensor
from torchaudio._internal import module_utils as _mod_utils
import torchaudio
__all__ = [
"spectrogram",
"griffinlim",
"amplitude_to_DB",
"DB_to_amplitude",
"comp... | en | 0.692899 | # -*- coding: utf-8 -*- Create a spectrogram or a batch of spectrograms from a raw audio signal. The spectrogram can be either magnitude-only or complex. Args: waveform (Tensor): Tensor of audio of dimension (..., time) pad (int): Two sided padding of signal window (Tensor): Window tens... | 2.443816 | 2 |
src/status_node.py | Faust-Wang/vswarm | 21 | 1498 | #!/usr/bin/env python3
from __future__ import absolute_import, division, print_function
import curses
import sys
from collections import deque
from datetime import datetime
import numpy as np
import rospy
from diagnostic_msgs.msg import DiagnosticArray, DiagnosticStatus
from geometry_msgs.msg import PoseStamped
from ... | #!/usr/bin/env python3
from __future__ import absolute_import, division, print_function
import curses
import sys
from collections import deque
from datetime import datetime
import numpy as np
import rospy
from diagnostic_msgs.msg import DiagnosticArray, DiagnosticStatus
from geometry_msgs.msg import PoseStamped
from ... | en | 0.260698 | #!/usr/bin/env python3 # StatusText # Curses setup # self.console = curses.newwin(self.rows - height_status, self.cols, 12, 2) # Hide cursor # Curses color setup # Default variables # self.statustext = StatusText() # self.statustext_sub = rospy.Subscriber('mavros/statustext/recv', StatusText, # ... | 2.13925 | 2 |
bin/boxplot_param.py | mo-schmid/MIALab | 0 | 1499 | <filename>bin/boxplot_param.py
import argparse
import os
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import pandas as pd
from pathlib import Path
class ResultParam():
"""Result Parameter"""
def __init__(self, path: Path, param_str: str):
"""Initializes a new instance of th... | <filename>bin/boxplot_param.py
import argparse
import os
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import pandas as pd
from pathlib import Path
class ResultParam():
"""Result Parameter"""
def __init__(self, path: Path, param_str: str):
"""Initializes a new instance of th... | en | 0.692495 | Result Parameter Initializes a new instance of the Result Parameter Args: path (Path): path to the desired result file param_str (str): string containing the parameters used in the postprocessing # figsize defaults to (width, height) =(6.4, 4.8), # for boxplots, we want the ratio to be ... | 3.026827 | 3 |