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 |
|---|---|---|---|---|---|---|---|---|---|---|
tmdb_client.py | SztMar/movies_catalogue | 0 | 11200 | <gh_stars>0
import requests
import json
import os
API_TOKEN = os.environ.get("TMDB_API_TOKEN", "")
def call_tmdb_api(_endpoint):
endpoint = f"https://api.themoviedb.org/3/{_endpoint}"
full_url = f'{endpoint}?api_key={API_TOKEN}'
response = requests.get(full_url)
response.raise_for_status()
return... | import requests
import json
import os
API_TOKEN = os.environ.get("TMDB_API_TOKEN", "")
def call_tmdb_api(_endpoint):
endpoint = f"https://api.themoviedb.org/3/{_endpoint}"
full_url = f'{endpoint}?api_key={API_TOKEN}'
response = requests.get(full_url)
response.raise_for_status()
return response.js... | none | 1 | 2.796277 | 3 | |
hanibal/ans_escuela/tipo_colaborador.py | Christian-Castro/castro_odoo8 | 0 | 11201 | <reponame>Christian-Castro/castro_odoo8
# -*- coding: utf-8 -*-
from openerp.osv import fields, osv
from openerp import models, fields, api, _
class Tipo_Colaborador(models.Model):
_name = 'tipo.colaborador'
_rec_name = 'name'
name=fields.Char(string='Nombre')
active=fields.Boolean(string='A... | # -*- coding: utf-8 -*-
from openerp.osv import fields, osv
from openerp import models, fields, api, _
class Tipo_Colaborador(models.Model):
_name = 'tipo.colaborador'
_rec_name = 'name'
name=fields.Char(string='Nombre')
active=fields.Boolean(string='Activo',default=True) | en | 0.769321 | # -*- coding: utf-8 -*- | 1.936564 | 2 |
spyder/utils/tests/test_environ.py | Nicztin/spyder | 1 | 11202 | <reponame>Nicztin/spyder
# -*- coding: utf-8 -*-
#
# Copyright © Spyder Project Contributors
# Licensed under the terms of the MIT License
#
"""
Tests for environ.py
"""
# Standard library imports
import os
# Test library imports
import pytest
# Third party imports
from qtpy.QtCore import QTimer
# Local imports
fr... | # -*- coding: utf-8 -*-
#
# Copyright © Spyder Project Contributors
# Licensed under the terms of the MIT License
#
"""
Tests for environ.py
"""
# Standard library imports
import os
# Test library imports
import pytest
# Third party imports
from qtpy.QtCore import QTimer
# Local imports
from spyder.utils.test impo... | en | 0.692668 | # -*- coding: utf-8 -*- # # Copyright © Spyder Project Contributors # Licensed under the terms of the MIT License # Tests for environ.py # Standard library imports # Test library imports # Third party imports # Local imports Test the environment variables dialog. | 2.308921 | 2 |
comsole.py | MumuNiMochii/Dumb_Dump | 1 | 11203 | import math
def main():
print("""
\tComsole by MumuNiMochii version beta 1.6.23
\t\"Originally made with C\"
\tMAIN MENU
\tWhat do you want to execute and evaluate?
\t1.) Add two addends
\t2.) Subtract a minuend from its subtrahend
\t3.) Multiply a multiplicand to its multiplier
\t4.) Divide a dividend to its... | import math
def main():
print("""
\tComsole by MumuNiMochii version beta 1.6.23
\t\"Originally made with C\"
\tMAIN MENU
\tWhat do you want to execute and evaluate?
\t1.) Add two addends
\t2.) Subtract a minuend from its subtrahend
\t3.) Multiply a multiplicand to its multiplier
\t4.) Divide a dividend to its... | en | 0.732902 | \tComsole by MumuNiMochii version beta 1.6.23 \t\"Originally made with C\" \tMAIN MENU \tWhat do you want to execute and evaluate? \t1.) Add two addends \t2.) Subtract a minuend from its subtrahend \t3.) Multiply a multiplicand to its multiplier \t4.) Divide a dividend to its divisor \t5.) Raise to power a base nu... | 4.065812 | 4 |
test/test_discussions.py | fibasile/ticket-gateway | 0 | 11204 | <reponame>fibasile/ticket-gateway<gh_stars>0
import unittest
import json
from server import server
from models.abc import db
from repositories import ChannelRepository, GitlabProvider
from unittest.mock import MagicMock, Mock
# from flask import make_response
# from flask.json import jsonify
from util import test_clie... | import unittest
import json
from server import server
from models.abc import db
from repositories import ChannelRepository, GitlabProvider
from unittest.mock import MagicMock, Mock
# from flask import make_response
# from flask.json import jsonify
from util import test_client
class TestDiscussions(unittest.TestCase)... | en | 0.542898 | # from flask import make_response # from flask.json import jsonify The GET on `/api/channel/a-channel/tickets/ticket_id/discussions` # GitlabProvider.getMembers.assert_called_with('/dummy/path') POST on `/api/channel/a-channel/tickets/ticket_id/discussions` should create a comment in a bew discussion POST on `/api/chan... | 2.627709 | 3 |
cogs/music.py | ETJeanMachine/Pouty-Bot-Discord | 0 | 11205 | <gh_stars>0
"""
This is an example cog that shows how you would make use of Lavalink.py.
This example cog requires that you have python 3.6 or higher due to the
f-strings.
"""
import math
import re
import discord
import lavalink
from discord.ext import commands
from discord.ext import menus
from .utils imp... | """
This is an example cog that shows how you would make use of Lavalink.py.
This example cog requires that you have python 3.6 or higher due to the
f-strings.
"""
import math
import re
import discord
import lavalink
from discord.ext import commands
from discord.ext import menus
from .utils import checks
... | en | 0.915333 | This is an example cog that shows how you would make use of Lavalink.py.
This example cog requires that you have python 3.6 or higher due to the
f-strings. # noqa: W605 # This is essentially the same as `@commands.guild_only()` # except it saves us repeating ourselves (and also a few lines). # Ensure that the bot a... | 2.632291 | 3 |
utils/data_processing.py | LisaAnne/LocalizingMoments | 157 | 11206 | import numpy as np
import sys
import os
sys.path.append('utils/')
from config import *
from utils import *
sys.path.append(pycaffe_dir)
import time
import pdb
import random
import pickle as pkl
import caffe
from multiprocessing import Pool
from threading import Thread
import random
import h5py
import itertools
import m... | import numpy as np
import sys
import os
sys.path.append('utils/')
from config import *
from utils import *
sys.path.append(pycaffe_dir)
import time
import pdb
import random
import pickle as pkl
import caffe
from multiprocessing import Pool
from threading import Thread
import random
import h5py
import itertools
import m... | en | 0.662094 | #glove_path = 'data/glove_debug_path.txt' #for debugging Creates glove embedding object #don't have an <unk> vector. Alternatively, could map to random vector... #Methods for extracting visual features General class to extract data. #uses iteration, batch_size, data_list, and num_data to extract next batch identifiers... | 2.257738 | 2 |
old_metrics/bleu.py | Danial-Alh/fast-bleu | 21 | 11207 | <reponame>Danial-Alh/fast-bleu<filename>old_metrics/bleu.py<gh_stars>10-100
import math
import os
from collections import Counter
from fractions import Fraction
import numpy as np
from nltk import ngrams
from nltk.translate.bleu_score import SmoothingFunction
from .utils import get_ngrams, Threader
def corpus_bleu(... | import math
import os
from collections import Counter
from fractions import Fraction
import numpy as np
from nltk import ngrams
from nltk.translate.bleu_score import SmoothingFunction
from .utils import get_ngrams, Threader
def corpus_bleu(references,
hypothesis,
reference_max_counts... | en | 0.639607 | Calculate a single corpus-level BLEU score (aka. system-level BLEU) for all the hypotheses and their respective references. Instead of averaging the sentence level BLEU scores (i.e. marco-average precision), the original BLEU metric (Papineni et al. 2002) accounts for the micro-average precision (i.e. ... | 2.730281 | 3 |
setup.py | gspracklin/bwtools | 4 | 11208 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import io
import os
import re
from setuptools import setup, find_packages
# classifiers = """\
# Development Status :: 4 - Beta
# Programming Language :: Python
# Programming Language :: Python :: 3
# Programming Language :: Python :: 3.4
# Programming... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import io
import os
import re
from setuptools import setup, find_packages
# classifiers = """\
# Development Status :: 4 - Beta
# Programming Language :: Python
# Programming Language :: Python :: 3
# Programming Language :: Python :: 3.4
# Programming... | en | 0.405452 | #!/usr/bin/env python # -*- coding: utf-8 -*- # classifiers = """\ # Development Status :: 4 - Beta # Programming Language :: Python # Programming Language :: Python :: 3 # Programming Language :: Python :: 3.4 # Programming Language :: Python :: 3.5 # Programming Language :: Python :: 3.6 # ... | 1.943779 | 2 |
hoogberta/encoder.py | KateSatida/HoogBERTa_SuperAI2 | 0 | 11209 | from .trainer.models import MultiTaskTagger
from .trainer.utils import load_dictionaries,Config
from .trainer.tasks.multitask_tagging import MultiTaskTaggingModule
from fairseq.data.data_utils import collate_tokens
from attacut import tokenize
class HoogBERTaEncoder(object):
def __init__(self,layer=12,cuda=False... | from .trainer.models import MultiTaskTagger
from .trainer.utils import load_dictionaries,Config
from .trainer.tasks.multitask_tagging import MultiTaskTaggingModule
from fairseq.data.data_utils import collate_tokens
from attacut import tokenize
class HoogBERTaEncoder(object):
def __init__(self,layer=12,cuda=False... | en | 0.699453 | #tokens = self.model.bert.encode(inputList) # all_sent = [] # sentences = sentence.split(" ") # for sent in sentences: # all_sent.append(" ".join(tokenize(sent)).replace("_","[!und:]")) # sentence = " _ ".join(all_sent) # inputList = [] # for sentX in sentenceL: # sentences = sentX.split(" ") # all_sent = [... | 2.15003 | 2 |
computer_equipment_control/model/__init__.py | hugonp/Proyecto-Triples | 0 | 11210 | <gh_stars>0
from . import usuario
from . import equipo_cambio
from . import equipo_computo
from . import sucursales
from . import depto
from . import usuario
| from . import usuario
from . import equipo_cambio
from . import equipo_computo
from . import sucursales
from . import depto
from . import usuario | none | 1 | 1.144636 | 1 | |
gui/window.py | frlnx/melee | 0 | 11211 | from pyglet.window import Window as PygletWindow
from .controllers import ComponentContainerController
from .models.container import ComponentContainerModel
from .views import OrthoViewport
class Window(PygletWindow):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._m... | from pyglet.window import Window as PygletWindow
from .controllers import ComponentContainerController
from .models.container import ComponentContainerModel
from .views import OrthoViewport
class Window(PygletWindow):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._m... | none | 1 | 2.179805 | 2 | |
conductor_calculator.py | aj83854/project-lightning-rod | 0 | 11212 | from pyconductor import load_test_values, calculate_conductance
def conductance_calc():
preloaded_dict = load_test_values()
while preloaded_dict:
print(
"[1] - Show currently available materials in Material Dictionary\n"
"[2] - Add a material (will not be saved upon restart)\n"... | from pyconductor import load_test_values, calculate_conductance
def conductance_calc():
preloaded_dict = load_test_values()
while preloaded_dict:
print(
"[1] - Show currently available materials in Material Dictionary\n"
"[2] - Add a material (will not be saved upon restart)\n"... | en | 0.515746 | # TODO: add logic handling whether user wants to add missing material | 3.450974 | 3 |
compiler/python_compiler/engines/py3_8/Variable.py | unknowncoder05/app-architect | 3 | 11213 | <reponame>unknowncoder05/app-architect
from .Fragment import Fragment
from utils.flags import *
from utils.CustomLogging import CustomLogging
#from python_compiler.engines.utils.types import get_python_type_str, ANY
DEFAULT_ASSIGN_OPERATOR = "="
ASSIGN_OPERATORS = {
"=":"=",
"+=":"+=",
"-=":"-=",
"*="... | from .Fragment import Fragment
from utils.flags import *
from utils.CustomLogging import CustomLogging
#from python_compiler.engines.utils.types import get_python_type_str, ANY
DEFAULT_ASSIGN_OPERATOR = "="
ASSIGN_OPERATORS = {
"=":"=",
"+=":"+=",
"-=":"-=",
"*=":"*=",
"/=":"/=",
"//=":"//=",
... | zh | 0.116552 | #from python_compiler.engines.utils.types import get_python_type_str, ANY | 2.213482 | 2 |
test/win/vs-macros/test_exists.py | chlorm-forks/gyp | 77 | 11214 | <reponame>chlorm-forks/gyp
# Copyright (c) 2012 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import os
import sys
if not os.path.exists(sys.argv[1]):
raise Exception()
open(sys.argv[2], 'w').close()
| # Copyright (c) 2012 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import os
import sys
if not os.path.exists(sys.argv[1]):
raise Exception()
open(sys.argv[2], 'w').close() | en | 0.919293 | # Copyright (c) 2012 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. | 1.634743 | 2 |
Lib/site-packages/qwt/scale_draw.py | fochoao/cpython | 0 | 11215 | <gh_stars>0
# -*- coding: utf-8 -*-
#
# Licensed under the terms of the Qwt License
# Copyright (c) 2002 <NAME>, for the original C++ code
# Copyright (c) 2015 <NAME>, for the Python translation/optimization
# (see LICENSE file for more details)
"""
QwtAbstractScaleDraw
--------------------
.. autoclass:: QwtAbstract... | # -*- coding: utf-8 -*-
#
# Licensed under the terms of the Qwt License
# Copyright (c) 2002 <NAME>, for the original C++ code
# Copyright (c) 2015 <NAME>, for the Python translation/optimization
# (see LICENSE file for more details)
"""
QwtAbstractScaleDraw
--------------------
.. autoclass:: QwtAbstractScaleDraw
... | en | 0.668102 | # -*- coding: utf-8 -*- # # Licensed under the terms of the Qwt License # Copyright (c) 2002 <NAME>, for the original C++ code # Copyright (c) 2015 <NAME>, for the Python translation/optimization # (see LICENSE file for more details) QwtAbstractScaleDraw -------------------- .. autoclass:: QwtAbstractScaleDraw :mem... | 1.82766 | 2 |
fuzzers/LIFCL/090-sysconfig/fuzzer.py | mfkiwl/prjoxide | 80 | 11216 | from fuzzconfig import FuzzConfig
import nonrouting
import fuzzloops
import re
cfgs = [
FuzzConfig(job="SYSCONFIG40", device="LIFCL-40", sv="../shared/empty_40.v",
tiles=["CIB_R0C75:EFB_0", "CIB_R0C72:BANKREF0", "CIB_R0C77:EFB_1_OSC", "CIB_R0C79:EFB_2",
"CIB_R0C81:I2C_EFB_3", "CIB_R0C85:PMU", "CIB_... | from fuzzconfig import FuzzConfig
import nonrouting
import fuzzloops
import re
cfgs = [
FuzzConfig(job="SYSCONFIG40", device="LIFCL-40", sv="../shared/empty_40.v",
tiles=["CIB_R0C75:EFB_0", "CIB_R0C72:BANKREF0", "CIB_R0C77:EFB_1_OSC", "CIB_R0C79:EFB_2",
"CIB_R0C81:I2C_EFB_3", "CIB_R0C85:PMU", "CIB_... | none | 1 | 1.788864 | 2 | |
test.py | jdonovanCS/CS-352-Evolutionary-Computation | 0 | 11217 | import argparse
import collections
import os
import random
import json
from copy import deepcopy
import ConfigSpace
import numpy as np
# from tabular_benchmarks import FCNetProteinStructureBenchmark, FCNetSliceLocalizationBenchmark,\
# FCNetNavalPropulsionBenchmark, FCNetParkinsonsTelemonitoringBenchmark
from ta... | import argparse
import collections
import os
import random
import json
from copy import deepcopy
import ConfigSpace
import numpy as np
# from tabular_benchmarks import FCNetProteinStructureBenchmark, FCNetSliceLocalizationBenchmark,\
# FCNetNavalPropulsionBenchmark, FCNetParkinsonsTelemonitoringBenchmark
from ta... | en | 0.337929 | # from tabular_benchmarks import FCNetProteinStructureBenchmark, FCNetSliceLocalizationBenchmark,\ # FCNetNavalPropulsionBenchmark, FCNetParkinsonsTelemonitoringBenchmark | 1.030285 | 1 |
tests/test_base64_uuid.py | cds-snc/notifier-utils | 3 | 11218 | from uuid import UUID
import os
import pytest
from notifications_utils.base64_uuid import base64_to_uuid, uuid_to_base64, base64_to_bytes, bytes_to_base64
def test_bytes_to_base64_to_bytes():
b = os.urandom(32)
b64 = bytes_to_base64(b)
assert base64_to_bytes(b64) == b
@pytest.mark.parametrize(
"url... | from uuid import UUID
import os
import pytest
from notifications_utils.base64_uuid import base64_to_uuid, uuid_to_base64, base64_to_bytes, bytes_to_base64
def test_bytes_to_base64_to_bytes():
b = os.urandom(32)
b64 = bytes_to_base64(b)
assert base64_to_bytes(b64) == b
@pytest.mark.parametrize(
"url... | en | 0.940592 | # even though this has invalid padding we put extra =s on the end so this is okay | 2.601733 | 3 |
homeassistant/components/devolo_home_control/__init__.py | dummys/home-assistant | 11 | 11219 | """The devolo_home_control integration."""
from __future__ import annotations
import asyncio
from functools import partial
from types import MappingProxyType
from typing import Any
from devolo_home_control_api.exceptions.gateway import GatewayOfflineError
from devolo_home_control_api.homecontrol import HomeControl
fr... | """The devolo_home_control integration."""
from __future__ import annotations
import asyncio
from functools import partial
from types import MappingProxyType
from typing import Any
from devolo_home_control_api.exceptions.gateway import GatewayOfflineError
from devolo_home_control_api.homecontrol import HomeControl
fr... | en | 0.527149 | The devolo_home_control integration. Set up the devolo account from a config entry. # Listen when EVENT_HOMEASSISTANT_STOP is fired Unload a config entry. Configure mydevolo. | 1.786097 | 2 |
trab1/hillClimbing.py | RafaelPedruzzi/IA-2019-2 | 0 | 11220 | ## -------------------------------------------------------- ##
# Trab 1 IA 2019-2
#
# <NAME>
#
# hillClimbing.py: implements the hill climbing metaheuristic for the bag problem
#
# Python version: 3.7.4
## -------------------------------------------------------- ##
import bagProblem as bp
from time import time... | ## -------------------------------------------------------- ##
# Trab 1 IA 2019-2
#
# <NAME>
#
# hillClimbing.py: implements the hill climbing metaheuristic for the bag problem
#
# Python version: 3.7.4
## -------------------------------------------------------- ##
import bagProblem as bp
from time import time... | en | 0.492133 | ## -------------------------------------------------------- ## # Trab 1 IA 2019-2 # # <NAME> # # hillClimbing.py: implements the hill climbing metaheuristic for the bag problem # # Python version: 3.7.4 ## -------------------------------------------------------- ## # Returns True and the valid state with the bi... | 2.891374 | 3 |
ssb_pseudonymization/__init__.py | statisticsnorway/ssb-pseudonymization-py | 1 | 11221 | <filename>ssb_pseudonymization/__init__.py
"""ssb-pseudonymization - Data pseudonymization functions used by SSB"""
__version__ = '0.0.2'
__author__ = '<NAME> (ssb.no)'
__all__ = []
| <filename>ssb_pseudonymization/__init__.py
"""ssb-pseudonymization - Data pseudonymization functions used by SSB"""
__version__ = '0.0.2'
__author__ = '<NAME> (ssb.no)'
__all__ = []
| en | 0.714985 | ssb-pseudonymization - Data pseudonymization functions used by SSB | 1.069233 | 1 |
hwilib/devices/keepkey.py | cjackie/HWI | 285 | 11222 | <filename>hwilib/devices/keepkey.py
"""
Keepkey
*******
"""
from ..errors import (
DEVICE_NOT_INITIALIZED,
DeviceNotReadyError,
common_err_msgs,
handle_errors,
)
from .trezorlib import protobuf as p
from .trezorlib.transport import (
hid,
udp,
webusb,
)
from .trezor import TrezorClient, HID... | <filename>hwilib/devices/keepkey.py
"""
Keepkey
*******
"""
from ..errors import (
DEVICE_NOT_INITIALIZED,
DeviceNotReadyError,
common_err_msgs,
handle_errors,
)
from .trezorlib import protobuf as p
from .trezorlib.transport import (
hid,
udp,
webusb,
)
from .trezor import TrezorClient, HID... | en | 0.879698 | Keepkey ******* # Need to use the enumerate built-in but there's another function already named that # type: ignore # type: ignore # default=256 # default=en-US # type: ignore The `KeepkeyClient` is a `HardwareWalletClient` for interacting with the Keepkey. As Keepkeys are clones of the Trezor 1, please refer ... | 2.081364 | 2 |
sklearn_extra/cluster/_k_medoids.py | chkoar/scikit-learn-extra | 1 | 11223 | <reponame>chkoar/scikit-learn-extra<filename>sklearn_extra/cluster/_k_medoids.py
# -*- coding: utf-8 -*-
"""K-medoids clustering"""
# Authors: <NAME> <<EMAIL>>
# <NAME> <<EMAIL>>
# <NAME> <<EMAIL>>
# <NAME> <<EMAIL>>
# License: BSD 3 clause
import warnings
import numpy as np
from sklearn.... | # -*- coding: utf-8 -*-
"""K-medoids clustering"""
# Authors: <NAME> <<EMAIL>>
# <NAME> <<EMAIL>>
# <NAME> <<EMAIL>>
# <NAME> <<EMAIL>>
# License: BSD 3 clause
import warnings
import numpy as np
from sklearn.base import BaseEstimator, ClusterMixin, TransformerMixin
from sklearn.metrics.pa... | en | 0.723325 | # -*- coding: utf-8 -*- K-medoids clustering # Authors: <NAME> <<EMAIL>> # <NAME> <<EMAIL>> # <NAME> <<EMAIL>> # <NAME> <<EMAIL>> # License: BSD 3 clause k-medoids clustering. Read more in the :ref:`User Guide <k_medoids>`. Parameters ---------- n_clusters : int, optional, d... | 2.646772 | 3 |
agent.py | shukia/2048-python | 0 | 11224 | <reponame>shukia/2048-python
from logic import *
class Agent:
def __init__(self):
self.matrix = []
self.score = 0
def initialize_game(self):
self.score = 0
self.matrix = new_game(4)
self.matrix = add_two(self.matrix)
self.matrix = add_two(self.matrix)
def ... | from logic import *
class Agent:
def __init__(self):
self.matrix = []
self.score = 0
def initialize_game(self):
self.score = 0
self.matrix = new_game(4)
self.matrix = add_two(self.matrix)
self.matrix = add_two(self.matrix)
def move(self, direction):
... | none | 1 | 3.387431 | 3 | |
config/synthia_rand_cityscapes.py | BarracudaPff/code-golf-data-pythpn | 0 | 11225 | <reponame>BarracudaPff/code-golf-data-pythpn
problem_type = "segmentation"
dataset_name = "synthia_rand_cityscapes"
dataset_name2 = None
perc_mb2 = None
model_name = "resnetFCN"
freeze_layers_from = None
show_model = False
load_imageNet = True
load_pretrained = False
weights_file = "weights.hdf5"
train_model = True
tes... | problem_type = "segmentation"
dataset_name = "synthia_rand_cityscapes"
dataset_name2 = None
perc_mb2 = None
model_name = "resnetFCN"
freeze_layers_from = None
show_model = False
load_imageNet = True
load_pretrained = False
weights_file = "weights.hdf5"
train_model = True
test_model = True
pred_model = False
debug = Tru... | none | 1 | 1.556679 | 2 | |
utils/HTMLParser.py | onyb/janitor | 0 | 11226 | from bs4 import BeautifulSoup
from optimizers.AdvancedJSOptimizer import AdvancedJSOptimizer
from optimizers.CSSOptimizer import CSSOptimizer
class HTMLParser(object):
def __init__(self, html):
self.soup = BeautifulSoup(html, 'lxml')
def js_parser(self):
for script in self.soup.find_all('scri... | from bs4 import BeautifulSoup
from optimizers.AdvancedJSOptimizer import AdvancedJSOptimizer
from optimizers.CSSOptimizer import CSSOptimizer
class HTMLParser(object):
def __init__(self, html):
self.soup = BeautifulSoup(html, 'lxml')
def js_parser(self):
for script in self.soup.find_all('scri... | none | 1 | 2.66643 | 3 | |
spades/main.py | kuwv/spades | 0 | 11227 | '''Provide interface for game.'''
from typing import Any, Dict, List, Optional, Union
import flask
from flask import Blueprint, url_for
from flask_login import current_user, login_required
from flask_wtf import FlaskForm
from flask_sse import sse
from werkzeug.wrappers import Response
from wtforms import IntegerField... | '''Provide interface for game.'''
from typing import Any, Dict, List, Optional, Union
import flask
from flask import Blueprint, url_for
from flask_login import current_user, login_required
from flask_wtf import FlaskForm
from flask_sse import sse
from werkzeug.wrappers import Response
from wtforms import IntegerField... | en | 0.511717 | Provide interface for game. # from spades import exceptions # type: ignore # type: ignore # type: ignore Provide start page. Provide lobby to coordinate new games. # type: ignore # type: ignore # if games != []: # return flask.render_template( # 'lobby.html', form=form, games=mock_names # ) Publish card... | 2.656742 | 3 |
cluster-1.59/heatmap_clustering/binding.gyp | ericaflin/libheatmap | 2 | 11228 | <gh_stars>1-10
{
"targets": [
{
"target_name": "cclust",
"sources": [ "./src/heatmap_clustering_js_module.cpp" ],
'dependencies': ['bonsaiclust']
},
{
'target_name': 'bonsaiclust',
'type': 'static_library',
'sources': [ 'src/cluster.c' ],
'cflags': ['-fPIC', '-I',... | {
"targets": [
{
"target_name": "cclust",
"sources": [ "./src/heatmap_clustering_js_module.cpp" ],
'dependencies': ['bonsaiclust']
},
{
'target_name': 'bonsaiclust',
'type': 'static_library',
'sources': [ 'src/cluster.c' ],
'cflags': ['-fPIC', '-I', '-pedantic', '... | none | 1 | 0.814402 | 1 | |
pcg_gazebo/parsers/urdf/__init__.py | TForce1/pcg_gazebo | 40 | 11229 | # Copyright (c) 2019 - The Procedural Generation for Gazebo authors
# For information on the respective copyright owner see the NOTICE file
#
# 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
#
#... | # Copyright (c) 2019 - The Procedural Generation for Gazebo authors
# For information on the respective copyright owner see the NOTICE file
#
# 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
#
#... | en | 0.658913 | # Copyright (c) 2019 - The Procedural Generation for Gazebo authors # For information on the respective copyright owner see the NOTICE file # # 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 # #... | 1.937228 | 2 |
homework/supporting.py | viaviare/MyFirstRepository | 0 | 11230 | <reponame>viaviare/MyFirstRepository
from selenium.webdriver.support.wait import WebDriverWait
from selenium.common.exceptions import NoSuchElementException
class Supporting:
def __init__(self, driver):
self.driver = driver
self.wait = WebDriverWait(driver, 10)
def is_element_present(self, ... | from selenium.webdriver.support.wait import WebDriverWait
from selenium.common.exceptions import NoSuchElementException
class Supporting:
def __init__(self, driver):
self.driver = driver
self.wait = WebDriverWait(driver, 10)
def is_element_present(self, driver, *args):
try:
... | none | 1 | 2.854725 | 3 | |
vplsSinVlan.py | javicond3/mininetVPLS | 0 | 11231 | """Custom topology example
Two directly connected switches plus a host for each switch:
host --- switch --- switch --- host
Adding the 'topos' dict with a key/value pair to generate our newly defined
topology enables one to pass in '--topo=mytopo' from the command line.
"""
from mininet.topo import Topo
class M... | """Custom topology example
Two directly connected switches plus a host for each switch:
host --- switch --- switch --- host
Adding the 'topos' dict with a key/value pair to generate our newly defined
topology enables one to pass in '--topo=mytopo' from the command line.
"""
from mininet.topo import Topo
class M... | en | 0.843808 | Custom topology example Two directly connected switches plus a host for each switch: host --- switch --- switch --- host Adding the 'topos' dict with a key/value pair to generate our newly defined topology enables one to pass in '--topo=mytopo' from the command line. # Initialize topology # Add hosts and switches... | 3.94382 | 4 |
modin/engines/base/io/column_stores/feather_dispatcher.py | webclinic017/modin | 1 | 11232 | # Licensed to Modin Development Team under one or more contributor license agreements.
# See the NOTICE file distributed with this work for additional information regarding
# copyright ownership. The Modin Development Team licenses this file to you under the
# Apache License, Version 2.0 (the "License"); you may not u... | # Licensed to Modin Development Team under one or more contributor license agreements.
# See the NOTICE file distributed with this work for additional information regarding
# copyright ownership. The Modin Development Team licenses this file to you under the
# Apache License, Version 2.0 (the "License"); you may not u... | en | 0.805651 | # Licensed to Modin Development Team under one or more contributor license agreements. # See the NOTICE file distributed with this work for additional information regarding # copyright ownership. The Modin Development Team licenses this file to you under the # Apache License, Version 2.0 (the "License"); you may not u... | 2.11702 | 2 |
rnnparser/RecursiveNN/tests_npRNN/test_tree_utils.py | uphere-co/nlp-prototype | 0 | 11233 | import pytest
from npRNN.tree_utils import Node, NodeTree
def test_merge_results():
#sentence='I know a name of the cat on a hat'
sentence='a name of the cat on a hat'
words=[Node(word) for word in sentence.split()]
tree=NodeTree(words, [0, 5, 3, 1, 2, 0, 0])
assert tree.phrase.name =='(((a name) ... | import pytest
from npRNN.tree_utils import Node, NodeTree
def test_merge_results():
#sentence='I know a name of the cat on a hat'
sentence='a name of the cat on a hat'
words=[Node(word) for word in sentence.split()]
tree=NodeTree(words, [0, 5, 3, 1, 2, 0, 0])
assert tree.phrase.name =='(((a name) ... | en | 0.836474 | #sentence='I know a name of the cat on a hat' | 2.903415 | 3 |
pyrefine/script.py | jezcope/pyrefine | 27 | 11234 | """A script is a series of operations."""
import json
import os
from .ops import create
class Script(object):
"""A script is a series of operations."""
def __init__(self, s=None):
"""Parse a script from a JSON string."""
if s is not None:
self.parsed_script = json.loads(s)
... | """A script is a series of operations."""
import json
import os
from .ops import create
class Script(object):
"""A script is a series of operations."""
def __init__(self, s=None):
"""Parse a script from a JSON string."""
if s is not None:
self.parsed_script = json.loads(s)
... | en | 0.613615 | A script is a series of operations. A script is a series of operations. Parse a script from a JSON string. Return the number of operations. Execute all operations on the provided dataset. Args: data (:class:`pandas.DataFrame`): The data to transform. Not guaranteed immutable. ... | 3.610138 | 4 |
makeCourse/plastex/mhchem/__init__.py | dualspiral/makecourse | 0 | 11235 | <reponame>dualspiral/makecourse<filename>makeCourse/plastex/mhchem/__init__.py<gh_stars>0
from plasTeX import Command, Environment, sourceChildren
from plasTeX.Base.LaTeX import Math
from plasTeX.Base.TeX.Primitives import BoxCommand
# mhchem package - mostly handled by mathjax
# Overrive boxcommands inside MathJaX to... | from plasTeX import Command, Environment, sourceChildren
from plasTeX.Base.LaTeX import Math
from plasTeX.Base.TeX.Primitives import BoxCommand
# mhchem package - mostly handled by mathjax
# Overrive boxcommands inside MathJaX to avoid extra <script type="math/tex">
class MHBoxCommand(BoxCommand):
class math(Math.... | en | 0.743907 | # mhchem package - mostly handled by mathjax # Overrive boxcommands inside MathJaX to avoid extra <script type="math/tex"> | 1.943705 | 2 |
src/data_augmentation.py | pallabganguly/gestures-cnn | 1 | 11236 | """
Totally untested file. Will be removed in subsequent commits
"""
import tensorflow as tf
import matplotlib.image as mpimg
import numpy as np
from math import ceil, floor
import os
IMAGE_SIZE = 720
def central_scale_images(X_imgs, scales):
# Various settings needed for Tensorflow operation
boxes = np.zeros... | """
Totally untested file. Will be removed in subsequent commits
"""
import tensorflow as tf
import matplotlib.image as mpimg
import numpy as np
from math import ceil, floor
import os
IMAGE_SIZE = 720
def central_scale_images(X_imgs, scales):
# Various settings needed for Tensorflow operation
boxes = np.zeros... | en | 0.772153 | Totally untested file. Will be removed in subsequent commits # Various settings needed for Tensorflow operation # To scale centrally # Define Tensorflow operation for all scales but only one base image at a time # Translate left 20 percent # Translate right 20 percent # Translate top 20 percent # Translate bottom 20 pe... | 2.396042 | 2 |
link_to_the_past/hashes.py | zsquareplusc/lttp-backup | 0 | 11237 | #!/usr/bin/env python3
# encoding: utf-8
#
# (C) 2012-2016 <NAME> <<EMAIL>>
#
# SPDX-License-Identifier: BSD-3-Clause
"""\
Link To The Past - a backup tool
Hash functions and commands.
"""
import hashlib
import zlib
class CRC32(object):
"""\
CRC32 API compatible to the hashlib functions (subset used by t... | #!/usr/bin/env python3
# encoding: utf-8
#
# (C) 2012-2016 <NAME> <<EMAIL>>
#
# SPDX-License-Identifier: BSD-3-Clause
"""\
Link To The Past - a backup tool
Hash functions and commands.
"""
import hashlib
import zlib
class CRC32(object):
"""\
CRC32 API compatible to the hashlib functions (subset used by t... | en | 0.363235 | #!/usr/bin/env python3 # encoding: utf-8 # # (C) 2012-2016 <NAME> <<EMAIL>> # # SPDX-License-Identifier: BSD-3-Clause \ Link To The Past - a backup tool Hash functions and commands. \ CRC32 API compatible to the hashlib functions (subset used by this program). >>> h = CRC32() >>> h.update(b'Hello World... | 2.686507 | 3 |
Interview/langTrans.py | dnootana/Python | 1 | 11238 | <reponame>dnootana/Python<filename>Interview/langTrans.py
#!/usr/bin/env python3.8
table="".maketrans("0123456789","\N{Devanagari digit zero}\N{Devanagari digit one}"
"\N{Devanagari digit two}\N{Devanagari digit three}"
"\N{Devanagari digit four}\N{Devanagari digit five}"
"\N{Devanagari digit six}\N{Devanagari digit s... | #!/usr/bin/env python3.8
table="".maketrans("0123456789","\N{Devanagari digit zero}\N{Devanagari digit one}"
"\N{Devanagari digit two}\N{Devanagari digit three}"
"\N{Devanagari digit four}\N{Devanagari digit five}"
"\N{Devanagari digit six}\N{Devanagari digit seven}"
"\N{Devanagari digit eight}\N{Devanagari digit nine... | en | 0.160152 | #!/usr/bin/env python3.8 | 2.36043 | 2 |
cutde/opencl.py | brendanjmeade/cutde | 1 | 11239 | <gh_stars>1-10
import logging
import warnings
import pyopencl
import pyopencl.array
logger = logging.getLogger(__name__)
gpu_initialized = False
gpu_ctx = None
gpu_queue = None
def report_devices(ctx):
device_names = [d.name for d in ctx.devices]
logger.info("initializing opencl context with devices = " + ... | import logging
import warnings
import pyopencl
import pyopencl.array
logger = logging.getLogger(__name__)
gpu_initialized = False
gpu_ctx = None
gpu_queue = None
def report_devices(ctx):
device_names = [d.name for d in ctx.devices]
logger.info("initializing opencl context with devices = " + str(device_name... | en | 0.526337 | The Apple CPU OpenCL implementation is awful. Instead, we should just use PoCL. # If no other platforms were found, let's try to # find a non-CPU device like an Iris Pro. # debug_opts = ["-g", "-Werror"] # compile_options.extend(debug_opts) # '-cl-finite-math-only', # '-cl-no-signed-zeros', # '-cl-strict-aliasing' ... | 2.615528 | 3 |
tests/test_lamost_tools.py | igomezv/astroNN | 156 | 11240 | import unittest
import numpy as np
from astroNN.lamost import wavelength_solution, pseudo_continuum
class LamostToolsTestCase(unittest.TestCase):
def test_wavelength_solution(self):
wavelength_solution()
wavelength_solution(dr=5)
self.assertRaises(ValueError, wavelength_solution, dr=1)
... | import unittest
import numpy as np
from astroNN.lamost import wavelength_solution, pseudo_continuum
class LamostToolsTestCase(unittest.TestCase):
def test_wavelength_solution(self):
wavelength_solution()
wavelength_solution(dr=5)
self.assertRaises(ValueError, wavelength_solution, dr=1)
... | none | 1 | 2.351669 | 2 | |
phase-iii-client/services/aureas/views.py | williamegomez/AUREAS | 5 | 11241 | from django.http import HttpResponse
from rest_framework.decorators import api_view
from rest_framework.decorators import parser_classes
from rest_framework.parsers import JSONParser
import numpy as np
import json
import os
from .utils.spectrogram_utils import SpectrogramUtils
from .utils.feature_extraction_utils impor... | from django.http import HttpResponse
from rest_framework.decorators import api_view
from rest_framework.decorators import parser_classes
from rest_framework.parsers import JSONParser
import numpy as np
import json
import os
from .utils.spectrogram_utils import SpectrogramUtils
from .utils.feature_extraction_utils impor... | none | 1 | 2.248579 | 2 | |
PyPoll/Homework/main.py | VioletData/python-challenge | 0 | 11242 | <filename>PyPoll/Homework/main.py
# Modules
import os
import csv
#Set up path for file
csvpath=os.path.join("..", "Resources", "election_data.csv" )
#print(csvpath)
total_votes=0
#total_profit=0
#previous_value=0
#current_value=0
#list_changes=[]
print("Election Results")
print("---------------------")
#Open the cs... | <filename>PyPoll/Homework/main.py
# Modules
import os
import csv
#Set up path for file
csvpath=os.path.join("..", "Resources", "election_data.csv" )
#print(csvpath)
total_votes=0
#total_profit=0
#previous_value=0
#current_value=0
#list_changes=[]
print("Election Results")
print("---------------------")
#Open the cs... | en | 0.531113 | # Modules #Set up path for file #print(csvpath) #total_profit=0 #previous_value=0 #current_value=0 #list_changes=[] #Open the csv file #print(csvreader) #Read the header row #print(f"CSV Header: {csv_header}") #Read each row of data after the header #total_profit=total_profit+1 #current_value=int(row[1]) #monthly_diff=... | 4.062974 | 4 |
test/qa-tests/buildscripts/resmokelib/logging/__init__.py | Mrliu8023/mongo-tools | 1 | 11243 | <gh_stars>1-10
"""
Extension to the logging package to support buildlogger.
"""
# Alias the built-in logging.Logger class for type checking arguments. Those interested in
# constructing a new Logger instance should use the loggers.new_logger() function instead.
from logging import Logger
from . import config
from .... | """
Extension to the logging package to support buildlogger.
"""
# Alias the built-in logging.Logger class for type checking arguments. Those interested in
# constructing a new Logger instance should use the loggers.new_logger() function instead.
from logging import Logger
from . import config
from . import buildlo... | en | 0.709345 | Extension to the logging package to support buildlogger. # Alias the built-in logging.Logger class for type checking arguments. Those interested in # constructing a new Logger instance should use the loggers.new_logger() function instead. | 1.9597 | 2 |
cohesity_management_sdk/models/azure_cloud_credentials.py | chandrashekar-cohesity/management-sdk-python | 1 | 11244 | <gh_stars>1-10
# -*- coding: utf-8 -*-
# Copyright 2019 Cohesity Inc.
class AzureCloudCredentials(object):
"""Implementation of the 'AzureCloudCredentials' model.
Specifies the cloud credentials to connect to a Microsoft
Azure service account.
Attributes:
storage_access_key (string): Specif... | # -*- coding: utf-8 -*-
# Copyright 2019 Cohesity Inc.
class AzureCloudCredentials(object):
"""Implementation of the 'AzureCloudCredentials' model.
Specifies the cloud credentials to connect to a Microsoft
Azure service account.
Attributes:
storage_access_key (string): Specifies the access ... | en | 0.811748 | # -*- coding: utf-8 -*- # Copyright 2019 Cohesity Inc. Implementation of the 'AzureCloudCredentials' model. Specifies the cloud credentials to connect to a Microsoft Azure service account. Attributes: storage_access_key (string): Specifies the access key to use when accessing a storage... | 2.879436 | 3 |
src/solutions/01.py | NNRepos/AoC-2021-python-solutions | 0 | 11245 | from utils.utils import *
lines = get_input(__file__)
lines_as_nums = lines_to_nums(lines)
def part1(nums):
incr = 0
cur = nums[0]
for num in nums:
if num > cur:
incr += 1
cur = num
return incr
def part2():
nums = []
for i in range(len(lines_as_nums)):
if... | from utils.utils import *
lines = get_input(__file__)
lines_as_nums = lines_to_nums(lines)
def part1(nums):
incr = 0
cur = nums[0]
for num in nums:
if num > cur:
incr += 1
cur = num
return incr
def part2():
nums = []
for i in range(len(lines_as_nums)):
if... | none | 1 | 3.611672 | 4 | |
scripts/sqlite_firestore_migration.py | namuan/news-rider | 5 | 11246 | <reponame>namuan/news-rider<gh_stars>1-10
import datetime
import os
import sys
from google.cloud import firestore
from peewee import *
sys.path.append(os.getcwd())
home_dir = os.getenv('HOME')
db_file_path = os.getcwd() + '/../../data/news_rider.db'
print("Reading database from {}".format(db_file_path))
old_db = Sq... | import datetime
import os
import sys
from google.cloud import firestore
from peewee import *
sys.path.append(os.getcwd())
home_dir = os.getenv('HOME')
db_file_path = os.getcwd() + '/../../data/news_rider.db'
print("Reading database from {}".format(db_file_path))
old_db = SqliteDatabase(db_file_path)
class NewsIte... | none | 1 | 3.068013 | 3 | |
tensorforce/core/baselines/mlp_baseline.py | youlei202/tensorforce-lei | 1 | 11247 | # Copyright 2017 reinforce.io. 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 2017 reinforce.io. 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.78867 | # Copyright 2017 reinforce.io. 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.953458 | 2 |
km3pipe/utils/rtree.py | kabartay/km3pipe | 2 | 11248 | # coding=utf-8
# Filename: h5tree.py
"""
Print the ROOT file structure.
Usage:
rtree FILE
rtree (-h | --help)
rtree --version
Options:
FILE Input file.
-h --help Show this screen.
"""
from __future__ import division, absolute_import, print_function
from km3pipe.io.root import open_rfile
_... | # coding=utf-8
# Filename: h5tree.py
"""
Print the ROOT file structure.
Usage:
rtree FILE
rtree (-h | --help)
rtree --version
Options:
FILE Input file.
-h --help Show this screen.
"""
from __future__ import division, absolute_import, print_function
from km3pipe.io.root import open_rfile
_... | en | 0.576615 | # coding=utf-8 # Filename: h5tree.py Print the ROOT file structure. Usage: rtree FILE rtree (-h | --help) rtree --version Options: FILE Input file. -h --help Show this screen. | 2.964096 | 3 |
task_part1_learning.py | till-lu/cit_lcp_2020 | 0 | 11249 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
from psychopy.visual import Window, TextStim
from psychopy.core import wait, Clock, quit
from psychopy.event import clearEvents, waitKeys, Mouse
from psychopy.gui import Dlg
from time import... | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
from psychopy.visual import Window, TextStim
from psychopy.core import wait, Clock, quit
from psychopy.event import clearEvents, waitKeys, Mouse
from psychopy.gui import Dlg
from time import... | en | 0.657731 | #!/usr/bin/env python2 # -*- coding: utf-8 -*- ## for testing # True for testing, False for real recording ### # sec #formerly = #9999FF ############ MAIN ITEMS - paste from JS # EXECUTE all main functions here # prompt to input stuff # now initiate stuff # creates psychopy screen and stim objects # window opens # crea... | 2.250676 | 2 |
ansible/venv/lib/python2.7/site-packages/ansible/modules/network/f5/bigip_asm_policy_import.py | gvashchenkolineate/gvashchenkolineate_infra_trytravis | 17 | 11250 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright: (c) 2018, F5 Networks Inc.
# GNU General Public License v3.0 (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
... | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright: (c) 2018, F5 Networks Inc.
# GNU General Public License v3.0 (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
... | en | 0.673675 | #!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright: (c) 2018, F5 Networks Inc. # GNU General Public License v3.0 (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) --- module: bigip_asm_policy_import short_description: Manage BIG-IP ASM policy imports description: - Manage BIG-IP ASM policies policy impo... | 1.55738 | 2 |
Firewall/Model/Host.py | frieagle94/firewall | 0 | 11251 | <gh_stars>0
__author__ = '<NAME>'
'''
Oggetto HOST
Attributi:
- mac_address: indirizzo MAC
- port: porta a cui e' collegato
- dpid: switch a cui e' collegato
'''
class Host(object):
def __init__(self, mac_address, port, dpid):
self.mac_address = mac_address
self.port = port
self.dpid = dp... | __author__ = '<NAME>'
'''
Oggetto HOST
Attributi:
- mac_address: indirizzo MAC
- port: porta a cui e' collegato
- dpid: switch a cui e' collegato
'''
class Host(object):
def __init__(self, mac_address, port, dpid):
self.mac_address = mac_address
self.port = port
self.dpid = dpid | it | 0.837403 | Oggetto HOST Attributi: - mac_address: indirizzo MAC - port: porta a cui e' collegato - dpid: switch a cui e' collegato | 2.511624 | 3 |
docker-compose/tweet_collector/tweet_streamer.py | lorenanda/tweets | 2 | 11252 | from tweepy import OAuthHandler, Stream, API
from tweepy.streaming import StreamListener
import json
import logging
import pymongo
import config
client = pymongo.MongoClient(host='mongo_container', port=27018)
db = client.tweets_db
auth = OAuthHandler(config.CONSUMER_API_KEY, config.CONSUMER_API_SECRET)
auth.set_acc... | from tweepy import OAuthHandler, Stream, API
from tweepy.streaming import StreamListener
import json
import logging
import pymongo
import config
client = pymongo.MongoClient(host='mongo_container', port=27018)
db = client.tweets_db
auth = OAuthHandler(config.CONSUMER_API_KEY, config.CONSUMER_API_SECRET)
auth.set_acc... | en | 0.37924 | # # Function for Twitter authentication # def authenticate(): # auth = OAuthHandler(config.CONSUMER_API_KEY, config.CONSUMER_API_SECRET) # auth.set_access_token(config.ACCESS_TOKEN, config.ACCESS_TOKEN_SECRET) # return auth # Function for streaming tweets #defines what is done with every single tweet as it ... | 2.982561 | 3 |
manage_it/network/models.py | ShangShungInstitute/django-manage-it | 1 | 11253 | <reponame>ShangShungInstitute/django-manage-it
from django.db import models
from django.utils.translation import ugettext_lazy as _
from assets.models import Item
from catalog.models import Inventory
CONNECTION_TYPES = (
(1, "Ethernet 1Gb"),
(2, "Ethernet 100Mb"),
(3, "WIFI"),
(4, "Optic Fiber"),
... | from django.db import models
from django.utils.translation import ugettext_lazy as _
from assets.models import Item
from catalog.models import Inventory
CONNECTION_TYPES = (
(1, "Ethernet 1Gb"),
(2, "Ethernet 100Mb"),
(3, "WIFI"),
(4, "Optic Fiber"),
(5, "USB"),
(6, "HDMI"),
(7, "Telephone... | en | 0.736352 | ItemConnection for networked assets ItemConnection for networked assets #%s" % (self.network, self.id) | 2.223734 | 2 |
software/L1_mpu.py | roy-kruemcke/SCUTTLE-SLMP | 0 | 11254 | <filename>software/L1_mpu.py
# L1_mpu.py
# Author: <NAME> (roanoake)
# 30 NOV 2021
# Allows for the interfacing to the MPU9250 using the smbus2 i2c module
# Written for use with Raspberry Pi 4 Model B
import smbus2
import numpy as np
import data
import time
# Initialize Register Data
CONFIG = 0x1A
USER_CTRL = 0x6A
PWR... | <filename>software/L1_mpu.py
# L1_mpu.py
# Author: <NAME> (roanoake)
# 30 NOV 2021
# Allows for the interfacing to the MPU9250 using the smbus2 i2c module
# Written for use with Raspberry Pi 4 Model B
import smbus2
import numpy as np
import data
import time
# Initialize Register Data
CONFIG = 0x1A
USER_CTRL = 0x6A
PWR... | en | 0.713111 | # L1_mpu.py # Author: <NAME> (roanoake) # 30 NOV 2021 # Allows for the interfacing to the MPU9250 using the smbus2 i2c module # Written for use with Raspberry Pi 4 Model B # Initialize Register Data # Initialize Scales # +-2G # +-4G # +-8G # +-16G # +-250 deg/s # +-500 deg/s # +-1000 deg/s # +-2000 deg/s # Open I2C bus... | 2.552301 | 3 |
OpenGLWrapper_JE/venv/Lib/site-packages/OpenGL/raw/GL/EXT/paletted_texture.py | JE-Chen/je_old_repo | 0 | 11255 | <reponame>JE-Chen/je_old_repo
'''Autogenerated by xml_generate script, do not edit!'''
from OpenGL import platform as _p, arrays
# Code generation uses this
from OpenGL.raw.GL import _types as _cs
# End users want this...
from OpenGL.raw.GL._types import *
from OpenGL.raw.GL import _errors
from OpenGL.constant i... | '''Autogenerated by xml_generate script, do not edit!'''
from OpenGL import platform as _p, arrays
# Code generation uses this
from OpenGL.raw.GL import _types as _cs
# End users want this...
from OpenGL.raw.GL._types import *
from OpenGL.raw.GL import _errors
from OpenGL.constant import Constant as _C
import... | en | 0.743726 | Autogenerated by xml_generate script, do not edit! # Code generation uses this # End users want this... | 1.517928 | 2 |
backend/apps/csyllabusapi/views/university.py | CSyllabus/webapp | 3 | 11256 | <gh_stars>1-10
from rest_framework.parsers import JSONParser, FileUploadParser
from rest_framework.views import APIView
from ..models import City
from ..models import Country
from ..models import University
from ..models import Faculty
from ..models import Program
from rest_framework.decorators import api_view, permis... | from rest_framework.parsers import JSONParser, FileUploadParser
from rest_framework.views import APIView
from ..models import City
from ..models import Country
from ..models import University
from ..models import Faculty
from ..models import Program
from rest_framework.decorators import api_view, permission_classes
fr... | none | 1 | 2.120642 | 2 | |
prickly-pufferfish/python_questions/add_to_zero.py | Vthechamp22/summer-code-jam-2021 | 40 | 11257 | """
Write a function with a list of ints as a paramter. /
Return True if any two nums sum to 0. /
>>> add_to_zero([]) /
False /
>>> add_to_zero([1]) /
False /
>>> add_to_zero([1, 2, 3]) /
False /
>>> add_to_zero([1, 2, 3, -2]) /
True /
"""
| """
Write a function with a list of ints as a paramter. /
Return True if any two nums sum to 0. /
>>> add_to_zero([]) /
False /
>>> add_to_zero([1]) /
False /
>>> add_to_zero([1, 2, 3]) /
False /
>>> add_to_zero([1, 2, 3, -2]) /
True /
"""
| en | 0.358721 | Write a function with a list of ints as a paramter. / Return True if any two nums sum to 0. / >>> add_to_zero([]) / False / >>> add_to_zero([1]) / False / >>> add_to_zero([1, 2, 3]) / False / >>> add_to_zero([1, 2, 3, -2]) / True / | 3.701643 | 4 |
op_trans/asgi.py | jezzlucena/django-opp-trans | 1 | 11258 | """
ASGI config for op_trans 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.1/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
from op_trans.websocket import webs... | """
ASGI config for op_trans 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.1/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
from op_trans.websocket import webs... | en | 0.726108 | ASGI config for op_trans 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.1/howto/deployment/asgi/ | 1.925077 | 2 |
notifai_recruitment/api.py | BudzynskiMaciej/notifai_recruitment | 0 | 11259 | # -*- coding: utf-8 -*-
"""API routes config for notifai_recruitment project.
REST framework adds support for automatic URL routing to Django, and provides simple, quick and consistent
way of wiring view logic to a set of URLs.
For more information on this file, see
https://www.django-rest-framework.org/api-guide/rou... | # -*- coding: utf-8 -*-
"""API routes config for notifai_recruitment project.
REST framework adds support for automatic URL routing to Django, and provides simple, quick and consistent
way of wiring view logic to a set of URLs.
For more information on this file, see
https://www.django-rest-framework.org/api-guide/rou... | en | 0.762152 | # -*- coding: utf-8 -*- API routes config for notifai_recruitment project. REST framework adds support for automatic URL routing to Django, and provides simple, quick and consistent way of wiring view logic to a set of URLs. For more information on this file, see https://www.django-rest-framework.org/api-guide/router... | 1.65925 | 2 |
zipline/data/bundles/equities_bundle.py | walterkissling/zipline | 0 | 11260 | <reponame>walterkissling/zipline
# File to ingest an equities bundle for zipline
# Import libraries
import pandas as pd
import numpy as np
def equities_bundle(path_to_file):
# Define custom ingest function
def ingest(environ,
asset_db_writer,
minute_bar_writer,
da... | # File to ingest an equities bundle for zipline
# Import libraries
import pandas as pd
import numpy as np
def equities_bundle(path_to_file):
# Define custom ingest function
def ingest(environ,
asset_db_writer,
minute_bar_writer,
daily_bar_writer,
ad... | en | 0.547815 | # File to ingest an equities bundle for zipline # Import libraries # Define custom ingest function # Read in data #data.loc[:, 'volume'] = 100000000 #start_dt = data.index.levels[1].min() #end_dt = data.index.levels[1].max() # Create asset metadata # Create dividend and split dataframe # Create list to hold data # Loop... | 2.578543 | 3 |
model/torch_model.py | FernandoLpz/ONNX-PyTorch-TF-Caffe2 | 3 | 11261 | import torch
import torch.nn as nn
class TorchModel(nn.ModuleList):
def __init__(self):
super(TorchModel, self).__init__()
self.linear_1 = nn.Linear(2, 12)
self.linear_2 = nn.Linear(12, 1)
def forward(self, x):
out = self.linear_1(x)
out = torch.tanh(out)
out = self.linear_2(out)
out = torch.sigmo... | import torch
import torch.nn as nn
class TorchModel(nn.ModuleList):
def __init__(self):
super(TorchModel, self).__init__()
self.linear_1 = nn.Linear(2, 12)
self.linear_2 = nn.Linear(12, 1)
def forward(self, x):
out = self.linear_1(x)
out = torch.tanh(out)
out = self.linear_2(out)
out = torch.sigmo... | none | 1 | 3.116917 | 3 | |
nereid/contrib/pagination.py | advocatetax/nereid-1 | 0 | 11262 | <reponame>advocatetax/nereid-1
# -*- coding: utf-8 -*-
# This file is part of Tryton & Nereid. The COPYRIGHT file at the top level of
# this repository contains the full copyright notices and license terms.
from math import ceil
from sql import Select, Column
from sql.functions import Function
from sql.aggregate import... | # -*- coding: utf-8 -*-
# This file is part of Tryton & Nereid. The COPYRIGHT file at the top level of
# this repository contains the full copyright notices and license terms.
from math import ceil
from sql import Select, Column
from sql.functions import Function
from sql.aggregate import Count
from werkzeug.utils impo... | en | 0.746022 | # -*- coding: utf-8 -*- # This file is part of Tryton & Nereid. The COPYRIGHT file at the top level of # this repository contains the full copyright notices and license terms. General purpose paginator for doing pagination With an empty dataset assert the attributes >>> p = Pagination(1, 3, []) >>> p.count... | 2.835558 | 3 |
app.py | Arpan-206/Youtube-Downloader-Flask | 3 | 11263 | <reponame>Arpan-206/Youtube-Downloader-Flask
from flask import Flask, request, send_file, render_template, url_for
import pytube
import logging
import sys
import os
from hello import timed_delete
from threading import Timer
timed_delete()
logging.basicConfig(stream=sys.stderr, level=logging.DEBUG)
app = Flask(__name__)... | from flask import Flask, request, send_file, render_template, url_for
import pytube
import logging
import sys
import os
from hello import timed_delete
from threading import Timer
timed_delete()
logging.basicConfig(stream=sys.stderr, level=logging.DEBUG)
app = Flask(__name__)
@app.route("/")
def youtube_downloader():
... | en | 0.788985 | First pytube downloads the file locally in pythonanywhere: /home/your_username/video_name.mp4 Then use Flask's send_file() to download the video to the user's Downloads folder. | 3.031885 | 3 |
si_unit_pandas/base.py | domdfcoding/si_unit_pandas | 0 | 11264 | #!/usr/bin/env python3
#
# base.py
"""
Base functionality.
"""
#
# Copyright (c) 2020 <NAME> <<EMAIL>>
#
# Based on cyberpandas
# https://github.com/ContinuumIO/cyberpandas
# Copyright (c) 2018, Anaconda, Inc.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted pr... | #!/usr/bin/env python3
#
# base.py
"""
Base functionality.
"""
#
# Copyright (c) 2020 <NAME> <<EMAIL>>
#
# Based on cyberpandas
# https://github.com/ContinuumIO/cyberpandas
# Copyright (c) 2018, Anaconda, Inc.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted pr... | en | 0.675676 | #!/usr/bin/env python3 # # base.py Base functionality. # # Copyright (c) 2020 <NAME> <<EMAIL>> # # Based on cyberpandas # https://github.com/ContinuumIO/cyberpandas # Copyright (c) 2018, Anaconda, Inc. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided t... | 1.538456 | 2 |
agents/admin.py | HerbertRamirez/inmo_web | 0 | 11265 | <filename>agents/admin.py
from django.contrib import admin
from .models import Agent
# Register your models here.
class AgentAdmin(admin.ModelAdmin):
readonly_fields = ('created','updated')
admin.site.register(Agent) | <filename>agents/admin.py
from django.contrib import admin
from .models import Agent
# Register your models here.
class AgentAdmin(admin.ModelAdmin):
readonly_fields = ('created','updated')
admin.site.register(Agent) | en | 0.968259 | # Register your models here. | 1.687811 | 2 |
modules/DEFA/MS_Office/compoundfiles/const.py | naaya17/carpe | 56 | 11266 | <filename>modules/DEFA/MS_Office/compoundfiles/const.py
#!/usr/bin/env python
# vim: set et sw=4 sts=4 fileencoding=utf-8:
#
# A library for reading Microsoft's OLE Compound Document format
# Copyright (c) 2014 <NAME> <<EMAIL>>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this s... | <filename>modules/DEFA/MS_Office/compoundfiles/const.py
#!/usr/bin/env python
# vim: set et sw=4 sts=4 fileencoding=utf-8:
#
# A library for reading Microsoft's OLE Compound Document format
# Copyright (c) 2014 <NAME> <<EMAIL>>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this s... | en | 0.720388 | #!/usr/bin/env python # vim: set et sw=4 sts=4 fileencoding=utf-8: # # A library for reading Microsoft's OLE Compound Document format # Copyright (c) 2014 <NAME> <<EMAIL>> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Softwar... | 1.208617 | 1 |
Validation/valid_view_point_cloud.py | dtczhl/Slimmer | 0 | 11267 | """
view predication for point cloud,
Run valid_one_point_cloud first
"""
import torch
import numpy as np
import sys
import os
import pptk
# ------ Configurations ------
# path to pth file
pth_file = "../tmp/scene0015_00_vh_clean_2.pth.Random.100"
show_gt = False # show groundtruth or not; groudtruth draw ... | """
view predication for point cloud,
Run valid_one_point_cloud first
"""
import torch
import numpy as np
import sys
import os
import pptk
# ------ Configurations ------
# path to pth file
pth_file = "../tmp/scene0015_00_vh_clean_2.pth.Random.100"
show_gt = False # show groundtruth or not; groudtruth draw ... | en | 0.580984 | view predication for point cloud, Run valid_one_point_cloud first # ------ Configurations ------ # path to pth file # show groundtruth or not; groudtruth draw first, i.e., on back # --- end of configurations --- # CLASS_COLOR = [ # [138, 43, 226], [0, 128, 128], [0, 255, 0], [0, 0, 255], [255, 255, 0], # [0... | 2.306252 | 2 |
core/migrations/0009_measurement.py | Potanist/Potanist | 0 | 11268 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('core', '0008_grow_owner'),
]
operations = [
migrations.CreateModel(
name='Measurement',
fields=[
... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('core', '0008_grow_owner'),
]
operations = [
migrations.CreateModel(
name='Measurement',
fields=[
... | en | 0.769321 | # -*- coding: utf-8 -*- | 1.742089 | 2 |
mkt/purchase/models.py | muffinresearch/zamboni | 0 | 11269 | import datetime
from django.conf import settings
from django.db import models
from django.utils import translation
import tower
from babel import Locale, numbers
from jingo import env
from jinja2.filters import do_dictsort
from tower import ugettext as _
import amo
from amo.fields import DecimalCharField
from amo.he... | import datetime
from django.conf import settings
from django.db import models
from django.utils import translation
import tower
from babel import Locale, numbers
from jingo import env
from jinja2.filters import do_dictsort
from tower import ugettext as _
import amo
from amo.fields import DecimalCharField
from amo.he... | en | 0.92461 | # For in-app purchases this links to the product. # This is the external id that you can communicate to the world. # This is the internal transaction id between us and a provider, # for example paypal or solitude. # Marketplace specific. # TODO(andym): figure out what to do when we delete the user. # If this is a refun... | 1.908862 | 2 |
src/kol/request/CampgroundRestRequest.py | danheath/temppykol | 19 | 11270 | <reponame>danheath/temppykol<filename>src/kol/request/CampgroundRestRequest.py
from kol.request.GenericRequest import GenericRequest
class CampgroundRestRequest(GenericRequest):
"Rests at the user's campground."
def __init__(self, session):
super(CampgroundRestRequest, self).__init__(session)
... | from kol.request.GenericRequest import GenericRequest
class CampgroundRestRequest(GenericRequest):
"Rests at the user's campground."
def __init__(self, session):
super(CampgroundRestRequest, self).__init__(session)
self.url = session.serverURL + 'campground.php?action=rest' | none | 1 | 2.20692 | 2 | |
pdlearn/adaptor/methods.py | richlewis42/pandas-learn | 1 | 11271 | <filename>pdlearn/adaptor/methods.py
#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# This file is part of pandas-learn
# https://github.com/RichLewis42/pandas-learn
#
# Licensed under the MIT license:
# http://www.opensource.org/licenses/MIT
# Copyright (c) 2015, <NAME> <<EMAIL>>
"""
pdlearn.adaptor.methods
~~~~~~~... | <filename>pdlearn/adaptor/methods.py
#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# This file is part of pandas-learn
# https://github.com/RichLewis42/pandas-learn
#
# Licensed under the MIT license:
# http://www.opensource.org/licenses/MIT
# Copyright (c) 2015, <NAME> <<EMAIL>>
"""
pdlearn.adaptor.methods
~~~~~~~... | en | 0.61837 | #! /usr/bin/env python # -*- coding: utf-8 -*- # # This file is part of pandas-learn # https://github.com/RichLewis42/pandas-learn # # Licensed under the MIT license: # http://www.opensource.org/licenses/MIT # Copyright (c) 2015, <NAME> <<EMAIL>> pdlearn.adaptor.methods ~~~~~~~~~~~~~~~~~~~~~~~ Module implementing meth... | 3.257084 | 3 |
BroCode/lessons/13-nested_loops.py | sofiaEkn/Python_Exercises | 0 | 11272 | <filename>BroCode/lessons/13-nested_loops.py
# nested loops = The "inner loop" will finish all of it's iterations before
# finishing one iteration of the "outer loop"
rows = int(input("How many rows?: "))
columns = int(input("How many columns?: "))
symbol = input("Enter a symbol to use: ")
#symbol = int... | <filename>BroCode/lessons/13-nested_loops.py
# nested loops = The "inner loop" will finish all of it's iterations before
# finishing one iteration of the "outer loop"
rows = int(input("How many rows?: "))
columns = int(input("How many columns?: "))
symbol = input("Enter a symbol to use: ")
#symbol = int... | en | 0.839271 | # nested loops = The "inner loop" will finish all of it's iterations before # finishing one iteration of the "outer loop" #symbol = int(input("Enter a symbol to use: ")) | 4.493051 | 4 |
duct/sources/python/uwsgi.py | geostarling/duct | 12 | 11273 | <gh_stars>10-100
"""
.. module:: uwsgi
:platform: Any
:synopsis: Reads UWSGI stats
.. moduleauthor:: <NAME> <<EMAIL>>
"""
import json
try:
from StringIO import StringIO
except ImportError:
from io import StringIO
from zope.interface import implementer
from twisted.internet import defer, reactor
from ... | """
.. module:: uwsgi
:platform: Any
:synopsis: Reads UWSGI stats
.. moduleauthor:: <NAME> <<EMAIL>>
"""
import json
try:
from StringIO import StringIO
except ImportError:
from io import StringIO
from zope.interface import implementer
from twisted.internet import defer, reactor
from twisted.internet.... | en | 0.353298 | .. module:: uwsgi :platform: Any :synopsis: Reads UWSGI stats .. moduleauthor:: <NAME> <<EMAIL>> JSON line protocol Disconnect transport Connects to UWSGI Emperor stats and creates useful metrics **Configuration arguments:** :param host: Hostname (default localhost) :type host: str. :param port... | 2.099711 | 2 |
xform/utils.py | alisonamerico/Django-XForm | 3 | 11274 | <gh_stars>1-10
import datetime
import importlib
import json
import logging
import math
import mimetypes
import os
import re
import sys
import uuid
import requests
from urllib.parse import urljoin
from wsgiref.util import FileWrapper
from xml.dom import minidom, Node
from django.conf import settings
from django.core... | import datetime
import importlib
import json
import logging
import math
import mimetypes
import os
import re
import sys
import uuid
import requests
from urllib.parse import urljoin
from wsgiref.util import FileWrapper
from xml.dom import minidom, Node
from django.conf import settings
from django.core.files.storage ... | en | 0.725346 | Exception class for merged datasets Exception class for inactive forms Go through an XML document returning all the attributes we see. Return a list of XPath, value pairs. :param d: A dictionary :param prefix: A list of prefixes # make a copy # TODO: this only considers the first level of repeats # also check ... | 1.879247 | 2 |
Phase5/testing_query.py | MrKLawrence/Course-Registration-Data-Analytics | 0 | 11275 | import datetime
from pymongo import MongoClient
import pymongo
import pprint
try:
db = MongoClient("mongodb://localhost:27017")["hkust"]
f=0.05
try:
print("Querying Documents...")
listOfCourseWithWaitingListSize = db.course.aggregate([
{ "$unwind": "$sections" },
# { "$project": { "newProduct": {"$multi... | import datetime
from pymongo import MongoClient
import pymongo
import pprint
try:
db = MongoClient("mongodb://localhost:27017")["hkust"]
f=0.05
try:
print("Querying Documents...")
listOfCourseWithWaitingListSize = db.course.aggregate([
{ "$unwind": "$sections" },
# { "$project": { "newProduct": {"$multi... | en | 0.578214 | # { "$project": { "newProduct": {"$multiply": [f, "$sections.enrol"]}, "satisfied": satisfied} }, # { "$project": { "compareResult": {"$gte": ["$sections.wait", "$newProduct"]}, "match_ts" : "$sections.recordTime"} }, #filter timeslot # {"compareResult": "true"}, # {"satisfied" : "Yes"}, #{"sections.sectionId": {"$ne":... | 2.852872 | 3 |
aws_iot/dashboard/migrations/0003_auto_20160427_1641.py | anduslim/aws_iot | 0 | 11276 | <reponame>anduslim/aws_iot
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('dashboard', '0002_gatewaynode_sensorstickerreading'),
]
operations = [
migrations.CreateModel(
... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('dashboard', '0002_gatewaynode_sensorstickerreading'),
]
operations = [
migrations.CreateModel(
name='DerivedInta... | en | 0.769321 | # -*- coding: utf-8 -*- | 1.654931 | 2 |
investing_algorithm_framework/core/models/__init__.py | coding-kitties/investing-algorithm-framework | 9 | 11277 | from flask import Flask
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
def create_all_tables():
db.create_all()
def initialize_db(app: Flask):
db.init_app(app)
db.app = app
from investing_algorithm_framework.core.models.order_status import OrderStatus
from investing_algorithm_framework.core... | from flask import Flask
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
def create_all_tables():
db.create_all()
def initialize_db(app: Flask):
db.init_app(app)
db.app = app
from investing_algorithm_framework.core.models.order_status import OrderStatus
from investing_algorithm_framework.core... | none | 1 | 2.037186 | 2 | |
src/storage-preview/azext_storage_preview/vendored_sdks/azure_storage/v2018_03_28/file/__init__.py | Mannan2812/azure-cli-extensions | 207 | 11278 | <reponame>Mannan2812/azure-cli-extensions
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# -------------------------------------------... | # -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
from .file... | en | 0.468429 | # ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # -------------------------------------------------------------------------- | 1.1736 | 1 |
backend/db/patient.py | wooque/openpacs | 1 | 11279 | <reponame>wooque/openpacs
from db.table import Table
from db.study import Study
from db.series import Series
from pypika.pseudocolumns import PseudoColumn
class Patient(Table):
name = 'patients'
async def sync_db(self):
await self.exec("""
CREATE TABLE IF NOT EXISTS patients (
id ... | from db.table import Table
from db.study import Study
from db.series import Series
from pypika.pseudocolumns import PseudoColumn
class Patient(Table):
name = 'patients'
async def sync_db(self):
await self.exec("""
CREATE TABLE IF NOT EXISTS patients (
id SERIAL PRIMARY KEY,
... | en | 0.315481 | CREATE TABLE IF NOT EXISTS patients ( id SERIAL PRIMARY KEY, patient_id TEXT UNIQUE NOT NULL, name TEXT NOT NULL, birth_date TEXT, sex TEXT, meta JSONB ); CREATE INDEX IF NOT EXISTS patients_patient_id ON patients(patient_id); | 2.898942 | 3 |
egs/cops/s5/local/text2json.py | Shuang777/kaldi-2016 | 0 | 11280 | #!/usr/bin/env python
import sys
import json
def sec2str(seconds):
sec_int = int(round(seconds))
hh = sec_int / 3600
mm = (sec_int - hh * 3600) / 60
ss = sec_int - hh * 3600 - mm * 60
return "%d:%02d:%02d" % (hh, mm, ss)
if len(sys.argv) != 4:
print "Usage:", __file__, "<segment> <text> <json>"
print ... | #!/usr/bin/env python
import sys
import json
def sec2str(seconds):
sec_int = int(round(seconds))
hh = sec_int / 3600
mm = (sec_int - hh * 3600) / 60
ss = sec_int - hh * 3600 - mm * 60
return "%d:%02d:%02d" % (hh, mm, ss)
if len(sys.argv) != 4:
print "Usage:", __file__, "<segment> <text> <json>"
print ... | ru | 0.26433 | #!/usr/bin/env python | 2.718656 | 3 |
codeEval/hard/levenshtein_distance.py | ferhatelmas/algo | 25 | 11281 | <reponame>ferhatelmas/algo<filename>codeEval/hard/levenshtein_distance.py
import sys
from string import ascii_lowercase as alphabet
def generate_neighbours(ws, s):
ls, l = set(), len(s)
for i in xrange(l + 1):
ls.add(s[:i] + s[i + 1 :])
for e in alphabet:
ls.add(s[:i] + e + s[i:])
... | import sys
from string import ascii_lowercase as alphabet
def generate_neighbours(ws, s):
ls, l = set(), len(s)
for i in xrange(l + 1):
ls.add(s[:i] + s[i + 1 :])
for e in alphabet:
ls.add(s[:i] + e + s[i:])
if i < l and e != s[i]:
ls.add(s[:i] + e + s[i... | none | 1 | 3.427693 | 3 | |
models/RelSaleSizeProject.py | the-Minister-0001/cardano-nft-admin | 1 | 11282 | from sqlalchemy import Column, Integer
from sqlalchemy import ForeignKey
from sqlalchemy.orm import declarative_base
from .base import Base
class RelSaleSizeProject(Base):
__tablename__ = 'rel_salesizes_projects'
id = Column(Integer, primary_key=True)
project_id = Column(Integer, ForeignKey('projects.id')... | from sqlalchemy import Column, Integer
from sqlalchemy import ForeignKey
from sqlalchemy.orm import declarative_base
from .base import Base
class RelSaleSizeProject(Base):
__tablename__ = 'rel_salesizes_projects'
id = Column(Integer, primary_key=True)
project_id = Column(Integer, ForeignKey('projects.id')... | none | 1 | 2.482641 | 2 | |
sudoku/recursive_solver.py | mkomaiha/NERS570-Sudoku | 0 | 11283 | from sudoku.constants import SIZE, BOX_SIZE
from sudoku import Sudoku
class RS(Sudoku):
def __init__(self, grade=0, id=None):
super().__init__(grade, id)
def possible(self, r, c, n):
for i in range(0, SIZE):
if self.solved[r, i] == n:
return False
for i in ... | from sudoku.constants import SIZE, BOX_SIZE
from sudoku import Sudoku
class RS(Sudoku):
def __init__(self, grade=0, id=None):
super().__init__(grade, id)
def possible(self, r, c, n):
for i in range(0, SIZE):
if self.solved[r, i] == n:
return False
for i in ... | en | 0.875476 | # Prevent from reseting the board | 3.524792 | 4 |
scraper.py | souravkaranjai/python-webscraper | 0 | 11284 | <filename>scraper.py<gh_stars>0
#!/usr/bin/python3
print('Hello world') | <filename>scraper.py<gh_stars>0
#!/usr/bin/python3
print('Hello world') | fr | 0.386793 | #!/usr/bin/python3 | 1.496996 | 1 |
src/algoritmia/problems/binpacking/firstfitbinpacker.py | DavidLlorens/algoritmia | 6 | 11285 | <filename>src/algoritmia/problems/binpacking/firstfitbinpacker.py<gh_stars>1-10
from algoritmia.problems.binpacking.nextfitbinpacker import NextFitBinPacker
class FirstFitBinPacker(NextFitBinPacker):#[full
def pack(self, w: "IList<Real>", C: "Real") -> "IList<int>":
x = [None] * len(w)
free = ... | <filename>src/algoritmia/problems/binpacking/firstfitbinpacker.py<gh_stars>1-10
from algoritmia.problems.binpacking.nextfitbinpacker import NextFitBinPacker
class FirstFitBinPacker(NextFitBinPacker):#[full
def pack(self, w: "IList<Real>", C: "Real") -> "IList<int>":
x = [None] * len(w)
free = ... | en | 0.303286 | #[full #]full | 2.643198 | 3 |
facebook/matrixWordSearch.py | rando3/leetcode-python | 0 | 11286 | <reponame>rando3/leetcode-python
https://leetcode.com/problems/word-search/description/ | https://leetcode.com/problems/word-search/description/ | none | 1 | 1.367013 | 1 | |
contrib/make_hdf.py | scopatz/PyTables | 9 | 11287 | #!/usr/bin/env python
from __future__ import generators
import tables, cPickle, time
#################################################################################
def is_scalar(item):
try:
iter(item)
#could be a string
try:
item[:0]+'' #check for string
return... | #!/usr/bin/env python
from __future__ import generators
import tables, cPickle, time
#################################################################################
def is_scalar(item):
try:
iter(item)
#could be a string
try:
item[:0]+'' #check for string
return... | en | 0.363191 | #!/usr/bin/env python ################################################################################# #could be a string #check for string for strings it will always make at least 80 char or twice mac char size #Col("Int16", 1) #it is a list-like #get max length #list within the list, make many columns #get max lengt... | 2.634932 | 3 |
jinja2content.py | firemark/new-site | 0 | 11288 | """
jinja2content.py
----------------
DONT EDIT THIS FILE
Pelican plugin that processes Markdown files as jinja templates.
"""
from jinja2 import Environment, FileSystemLoader, ChoiceLoader
import os
from pelican import signals
from pelican.readers import MarkdownReader, HTMLReader, RstReader
from pelican.utils imp... | """
jinja2content.py
----------------
DONT EDIT THIS FILE
Pelican plugin that processes Markdown files as jinja templates.
"""
from jinja2 import Environment, FileSystemLoader, ChoiceLoader
import os
from pelican import signals
from pelican.readers import MarkdownReader, HTMLReader, RstReader
from pelican.utils imp... | en | 0.671307 | jinja2content.py ---------------- DONT EDIT THIS FILE Pelican plugin that processes Markdown files as jinja templates. # will look first in 'JINJA2CONTENT_TEMPLATES', by default the # content root path, then in the theme's templates # pelican 3.7 | 2.51858 | 3 |
task3/code/video_process.py | haohaoqian/STD | 1 | 11289 | <filename>task3/code/video_process.py
import json
from tqdm import tqdm
from utils import *
from alexnet import AlexNet
def classify(net, folder_name, resize=(224, 224)):
transform = []
if resize:
transform.append(torchvision.transforms.Resize(resize))
transform.append(torchvision.transf... | <filename>task3/code/video_process.py
import json
from tqdm import tqdm
from utils import *
from alexnet import AlexNet
def classify(net, folder_name, resize=(224, 224)):
transform = []
if resize:
transform.append(torchvision.transforms.Resize(resize))
transform.append(torchvision.transf... | en | 0.278131 | # 归一化 # root = './dataset/task2/test/' # save_name = './dataset/task2.json' # root = './dataset/train/' # save_name = './dataset/train.json' # 用来标记各视频撞击位置的函数,分类用不到 :param folder_name: 从当前路径访问到‘video_0000’文件夹的路径
:param resize:默认为(224,224)
:return: 14维特征向量,前10维为分类标签
['061_foam_brick', 'green_basketball', ... | 2.307101 | 2 |
Aulas/12aula(antigo)/readint.py | rafaelmcam/RTOs_ChibiOS | 1 | 11290 | <reponame>rafaelmcam/RTOs_ChibiOS
import serial
with serial.Serial("/dev/ttyUSB0", 115200) as ser:
while 1:
for i in range(5):
n = ser.read()[0]
print("{:x}".format(n))
print("--------")
| import serial
with serial.Serial("/dev/ttyUSB0", 115200) as ser:
while 1:
for i in range(5):
n = ser.read()[0]
print("{:x}".format(n))
print("--------") | none | 1 | 2.671093 | 3 | |
packages/pyre/parsing/Parser.py | avalentino/pyre | 25 | 11291 | <gh_stars>10-100
# -*- coding: utf-8 -*-
#
# <NAME>
# orthologue
# (c) 1998-2021 all rights reserved
#
class Parser:
"""
The base class for parsers
"""
# types
from .exceptions import ParsingError, SyntaxError, TokenizationError
# meta methods
def __init__(self, **kwds):
# chai... | # -*- coding: utf-8 -*-
#
# <NAME>
# orthologue
# (c) 1998-2021 all rights reserved
#
class Parser:
"""
The base class for parsers
"""
# types
from .exceptions import ParsingError, SyntaxError, TokenizationError
# meta methods
def __init__(self, **kwds):
# chain up
supe... | en | 0.74025 | # -*- coding: utf-8 -*- # # <NAME> # orthologue # (c) 1998-2021 all rights reserved # The base class for parsers # types # meta methods # chain up # build my scanner # all done # implementation details # my scanner factory # my scanner instance # end of file | 2.341455 | 2 |
shfl/data_distribution/data_distribution_non_iid.py | SSSuperTIan/Sherpa.ai-Federated-Learning-Framework | 1 | 11292 | <filename>shfl/data_distribution/data_distribution_non_iid.py
import numpy as np
import random
import tensorflow as tf
from shfl.data_base.data_base import shuffle_rows
from shfl.data_distribution.data_distribution_sampling import SamplingDataDistribution
class NonIidDataDistribution(SamplingDataDistribution):
"... | <filename>shfl/data_distribution/data_distribution_non_iid.py
import numpy as np
import random
import tensorflow as tf
from shfl.data_base.data_base import shuffle_rows
from shfl.data_distribution.data_distribution_sampling import SamplingDataDistribution
class NonIidDataDistribution(SamplingDataDistribution):
"... | en | 0.765628 | Implementation of a non-independent and identically distributed data distribution using \ [Data Distribution](../data_distribution/#datadistribution-class) In this data distribution we simulate the scenario in which clients have non-identical distribution since they know partially the total classes of ... | 3.051157 | 3 |
example/0_Basic_usage_of_the_library/python_pymongo/2_select.py | AndersonHJB/learning_spider | 2 | 11293 | <reponame>AndersonHJB/learning_spider<gh_stars>1-10
# -*- encoding: utf-8 -*-
'''
@Time : 2021-06-08
@Author : EvilRecluse
@Contact : https://github.com/RecluseXU
@Desc : 增
'''
# here put the import lib
from pymongo import MongoClient
from bson import ObjectId
connection: MongoClient = MongoClient('mo... | # -*- encoding: utf-8 -*-
'''
@Time : 2021-06-08
@Author : EvilRecluse
@Contact : https://github.com/RecluseXU
@Desc : 增
'''
# here put the import lib
from pymongo import MongoClient
from bson import ObjectId
connection: MongoClient = MongoClient('mongodb://localhost:27017')
collection = connection['l... | zh | 0.898081 | # -*- encoding: utf-8 -*- @Time : 2021-06-08 @Author : EvilRecluse @Contact : https://github.com/RecluseXU @Desc : 增 # here put the import lib # 查询方法 # 集合对象查看find开头的方法既是所求,一般使用: find 查询多个结果 与 find_one 查询单个结果 # collection.find # collection.find_one # 实际上,查询所需要的参数都是 mongo查询 本身所定义的,而不是 pymongo所自定义的 # 基本上在 m... | 2.461606 | 2 |
install-b9s.py | ihaveamac/hardmod-b9s-installer | 13 | 11294 | <reponame>ihaveamac/hardmod-b9s-installer
#!/usr/bin/env python3
import hashlib
import os
import shutil
import subprocess
import sys
import time
def doexit(msg, errcode=0):
print(msg)
input('Press Enter to continue...')
sys.exit(errcode)
if not os.path.isfile('NAND.bin'):
doexit('NAND.bin not found... | #!/usr/bin/env python3
import hashlib
import os
import shutil
import subprocess
import sys
import time
def doexit(msg, errcode=0):
print(msg)
input('Press Enter to continue...')
sys.exit(errcode)
if not os.path.isfile('NAND.bin'):
doexit('NAND.bin not found.', errcode=1)
if os.path.isfile('firm0fi... | en | 0.455336 | #!/usr/bin/env python3 # must be divisible by 0x3AF00000 and 0x4D800000 # return(procoutput) | 2.201631 | 2 |
pygazebo/connection.py | robobe/pygazebo | 0 | 11295 | <reponame>robobe/pygazebo
import concurrent
import time
import math
import sys
import asyncio
import logging
from . import msg
from .parse_error import ParseError
from . import DEBUG_LEVEL
logger = logging.getLogger(__name__)
logger.setLevel(DEBUG_LEVEL)
async def _wait_closed(stream):
assert(sys.version_info.ma... | import concurrent
import time
import math
import sys
import asyncio
import logging
from . import msg
from .parse_error import ParseError
from . import DEBUG_LEVEL
logger = logging.getLogger(__name__)
logger.setLevel(DEBUG_LEVEL)
async def _wait_closed(stream):
assert(sys.version_info.major >= 3)
if sys.versi... | en | 0.76355 | :param connection_name: Name of the connection :param server_addr: remote address of the connection (address, port) :type server_addr: tuple[str, int] :param local_addr: local address of the connection (address, port) :type local_addr: tuple[str, int] :param discarded_bytes: numb... | 2.610792 | 3 |
src/visualization/visualize_dataset.py | ivangarrera/MachineLearning | 0 | 11296 | <reponame>ivangarrera/MachineLearning<gh_stars>0
from common_clustering import CommonClustering
#■clustering_features = CommonClustering(r'C:\Users\ivangarrera\Desktop\T2_cleaned.csv')
clustering_features = CommonClustering('D:\Ing. Informatica\Cuarto\Machine Learning\T2_cleaned_gyroscope.csv')
attr = list(clustering... | from common_clustering import CommonClustering
#■clustering_features = CommonClustering(r'C:\Users\ivangarrera\Desktop\T2_cleaned.csv')
clustering_features = CommonClustering('D:\Ing. Informatica\Cuarto\Machine Learning\T2_cleaned_gyroscope.csv')
attr = list(clustering_features.data_set)[0][:list(clustering_features.... | en | 0.769538 | #■clustering_features = CommonClustering(r'C:\Users\ivangarrera\Desktop\T2_cleaned.csv') # Get the number of clusters that provides the best results # Plot silhuettes array # Print k-means with the best number of clusters that have been found # Interprate k-means groups # Plot 3D graph to interpretate k-means groups # ... | 3.126245 | 3 |
app.py | Geo-Gabriel/REST-Api-Hotels | 0 | 11297 | from blacklist import BLACKLIST
from flask import Flask, jsonify
from flask_restful import Api
from resources.hotel import Hoteis, Hotel
from resources.user import User, UserLogin, UserLogout, UserRegister, Users
from resources.site import Site, Sites
from flask_jwt_extended import JWTManager
app = Flask(__name__)
ap... | from blacklist import BLACKLIST
from flask import Flask, jsonify
from flask_restful import Api
from resources.hotel import Hoteis, Hotel
from resources.user import User, UserLogin, UserLogout, UserRegister, Users
from resources.site import Site, Sites
from flask_jwt_extended import JWTManager
app = Flask(__name__)
ap... | en | 0.509197 | # Unautorized # Hotels resource # Users resource # User register resource # Login resource # Logout resource # Sites resource | 2.269616 | 2 |
scdlbot/__init__.py | samillinier/habesha-skin-pack | 0 | 11298 | <filename>scdlbot/__init__.py
# -*- coding: utf-8 -*-
"""Top-level package for Music Downloader Telegram Bot."""
# version as tuple for simple comparisons
VERSION = (0, 9, 16)
__author__ = """<NAME>"""
__email__ = '<EMAIL>'
# string created from tuple to avoid inconsistency
__version__ = ".".join([str(x) for x in VE... | <filename>scdlbot/__init__.py
# -*- coding: utf-8 -*-
"""Top-level package for Music Downloader Telegram Bot."""
# version as tuple for simple comparisons
VERSION = (0, 9, 16)
__author__ = """<NAME>"""
__email__ = '<EMAIL>'
# string created from tuple to avoid inconsistency
__version__ = ".".join([str(x) for x in VE... | en | 0.819886 | # -*- coding: utf-8 -*- Top-level package for Music Downloader Telegram Bot. # version as tuple for simple comparisons <NAME> # string created from tuple to avoid inconsistency | 2.024538 | 2 |
uPython/lopyhelper.py | somervda/ourLora | 0 | 11299 | import struct
import pycom
import time
from network import LoRa
def blink(seconds, rgb):
pycom.rgbled(rgb)
time.sleep(seconds)
pycom.rgbled(0x000000) # off
def setUSFrequencyPlan(lora):
""" Sets the frequency plan that matches the TTN gateway in the USA """
# remove all US915 channels
for c... | import struct
import pycom
import time
from network import LoRa
def blink(seconds, rgb):
pycom.rgbled(rgb)
time.sleep(seconds)
pycom.rgbled(0x000000) # off
def setUSFrequencyPlan(lora):
""" Sets the frequency plan that matches the TTN gateway in the USA """
# remove all US915 channels
for c... | en | 0.822165 | # off Sets the frequency plan that matches the TTN gateway in the USA # remove all US915 channels # set all channels to the same frequency (must be before sending the OTAA join request) # Set up first 8 US915 TTN uplink channels # DR3 = SF8/500kHz # DR0 = SF10/125kHz # DR3 = SF7/125kHz Join the Lorawan network using OT... | 2.690665 | 3 |