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 |
|---|---|---|---|---|---|---|---|---|---|---|
generator/database.py | Neotrinost/Neotrinost.ir | 4 | 2000 | import sqlite3
class Database:
def get_connection(self):
return sqlite3.connect("./db.sqlite")
def add_card(self, card_title, card_text, card_link_text, card_link_url):
con = self.get_connection()
cur = con.cursor()
create_table_query = "CREATE TABLE IF NOT EXISTS cards('card... | import sqlite3
class Database:
def get_connection(self):
return sqlite3.connect("./db.sqlite")
def add_card(self, card_title, card_text, card_link_text, card_link_url):
con = self.get_connection()
cur = con.cursor()
create_table_query = "CREATE TABLE IF NOT EXISTS cards('card... | none | 1 | 3.818389 | 4 | |
crits/backdoors/forms.py | frbapolkosnik/crits | 22 | 2001 | <gh_stars>10-100
from django import forms
from django.forms.utils import ErrorList
from crits.campaigns.campaign import Campaign
from crits.core.forms import add_bucketlist_to_form, add_ticket_to_form
from crits.core.handlers import get_item_names, get_source_names
from crits.core.user_tools import get_user_organizati... | from django import forms
from django.forms.utils import ErrorList
from crits.campaigns.campaign import Campaign
from crits.core.forms import add_bucketlist_to_form, add_ticket_to_form
from crits.core.handlers import get_item_names, get_source_names
from crits.core.user_tools import get_user_organization
from crits.cor... | en | 0.802777 | Django form for adding a Backdoor to CRITs. | 2.106901 | 2 |
src/aprl/agents/monte_carlo.py | fkamrani/adversarial-policies | 211 | 2002 | <filename>src/aprl/agents/monte_carlo.py
"""Monte Carlo receding horizon control."""
from abc import ABC, abstractmethod
from multiprocessing import Pipe, Process
import gym
from stable_baselines.common.vec_env import CloudpickleWrapper
from aprl.common.mujoco import MujocoState, ResettableEnv
class MujocoResettab... | <filename>src/aprl/agents/monte_carlo.py
"""Monte Carlo receding horizon control."""
from abc import ABC, abstractmethod
from multiprocessing import Pipe, Process
import gym
from stable_baselines.common.vec_env import CloudpickleWrapper
from aprl.common.mujoco import MujocoState, ResettableEnv
class MujocoResettab... | en | 0.762092 | Monte Carlo receding horizon control. Converts a MujocoEnv into a ResettableEnv. Note all MuJoCo environments are resettable. Wraps a MujocoEnv, adding get_state and set_state methods. :param env: a MujocoEnv. NOTE: it must not be wrapped in a TimeLimit. Serializes the qpos and qvel state of the MuJoCo emu... | 2.493043 | 2 |
machineLearnInAction/bayes.py | xuwening/tensorflowDemo | 0 | 2003 | <filename>machineLearnInAction/bayes.py
import numpy as np
def loadDataSet():
postingList = [['my', 'dog', 'has', 'flea', 'problems', 'help', 'please'], #[0,0,1,1,1......]
['maybe', 'not', 'take', 'him', 'to', 'dog', 'park', 'stupid'],
['my', 'dalmation', 'is', 'so', 'cu... | <filename>machineLearnInAction/bayes.py
import numpy as np
def loadDataSet():
postingList = [['my', 'dog', 'has', 'flea', 'problems', 'help', 'please'], #[0,0,1,1,1......]
['maybe', 'not', 'take', 'him', 'to', 'dog', 'park', 'stupid'],
['my', 'dalmation', 'is', 'so', 'cu... | en | 0.571751 | #[0,0,1,1,1......] # 1 is abusive, 0 not # print(setOfWords2Vec(myVocabList, postinList[0])) | 3.139343 | 3 |
py/debug/__init__.py | segrids/arduino_due | 3 | 2004 | <reponame>segrids/arduino_due<filename>py/debug/__init__.py
from .swd import SWD
from .ahb import AHB
from .debugger import Debugger, HaltError, NotHaltedError
try:
from .dwarf import ELFDebugger
except ImportError:
pass
| from .swd import SWD
from .ahb import AHB
from .debugger import Debugger, HaltError, NotHaltedError
try:
from .dwarf import ELFDebugger
except ImportError:
pass | none | 1 | 1.059687 | 1 | |
HAP-NodeJS/Switch3_1.py | cbdunc2/pi-kit | 0 | 2005 | import subprocess
subprocess.Popen(['sh', '../Switches/Switch3_On.sh'])
| import subprocess
subprocess.Popen(['sh', '../Switches/Switch3_On.sh'])
| none | 1 | 1.525751 | 2 | |
src/cicd_sim/artifact/__init__.py | Software-Natives-OSS/cicd_sim | 0 | 2006 | from . artifactory import Artifactory
__all__ = ['Artifactory']
| from . artifactory import Artifactory
__all__ = ['Artifactory']
| none | 1 | 1.067043 | 1 | |
mandoline/line_segment3d.py | Spiritdude/mandoline-py | 5 | 2007 |
class LineSegment3D(object):
"""A class to represent a 3D line segment."""
def __init__(self, p1, p2):
"""Initialize with two endpoints."""
if p1 > p2:
p1, p2 = (p2, p1)
self.p1 = p1
self.p2 = p2
self.count = 1
def __len__(self):
"""Line segment... |
class LineSegment3D(object):
"""A class to represent a 3D line segment."""
def __init__(self, p1, p2):
"""Initialize with two endpoints."""
if p1 > p2:
p1, p2 = (p2, p1)
self.p1 = p1
self.p2 = p2
self.count = 1
def __len__(self):
"""Line segment... | en | 0.729201 | A class to represent a 3D line segment. Initialize with two endpoints. Line segment always has two endpoints. Iterator generator for endpoints. Given a vertex number, returns a vertex coordinate vector. Returns hash value for endpoints Compare points for sort ordering in an arbitrary heirarchy. Provides .format() suppo... | 3.674745 | 4 |
cacheable/adapter/PeeweeAdapter.py | d1hotpep/cacheable | 0 | 2008 | <reponame>d1hotpep/cacheable
import peewee
import playhouse.kv
from time import time
from . import CacheableAdapter
class PeeweeAdapter(CacheableAdapter, peewee.Model):
key = peewee.CharField(max_length=256, unique=True)
value = playhouse.kv.JSONField()
mtime = peewee.IntegerField(default=time)
ttl =... | import peewee
import playhouse.kv
from time import time
from . import CacheableAdapter
class PeeweeAdapter(CacheableAdapter, peewee.Model):
key = peewee.CharField(max_length=256, unique=True)
value = playhouse.kv.JSONField()
mtime = peewee.IntegerField(default=time)
ttl = peewee.IntegerField(default=... | en | 0.884114 | Add the TTL where clause to a query, to filter out stale results | 2.411491 | 2 |
mmgen/models/architectures/arcface/helpers.py | plutoyuxie/mmgeneration | 0 | 2009 | from collections import namedtuple
import torch
from torch.nn import (AdaptiveAvgPool2d, BatchNorm2d, Conv2d, MaxPool2d,
Module, PReLU, ReLU, Sequential, Sigmoid)
# yapf: disable
"""
ArcFace implementation from [TreB1eN](https://github.com/TreB1eN/InsightFace_Pytorch) # isort:skip # noqa
"""
# ... | from collections import namedtuple
import torch
from torch.nn import (AdaptiveAvgPool2d, BatchNorm2d, Conv2d, MaxPool2d,
Module, PReLU, ReLU, Sequential, Sigmoid)
# yapf: disable
"""
ArcFace implementation from [TreB1eN](https://github.com/TreB1eN/InsightFace_Pytorch) # isort:skip # noqa
"""
# ... | en | 0.638713 | # yapf: disable ArcFace implementation from [TreB1eN](https://github.com/TreB1eN/InsightFace_Pytorch) # isort:skip # noqa # yapf: enable Flatten Module. l2 normalization. Args: input (torch.Tensor): The input tensor. axis (int, optional): Specifies which axis of input to calculate the ... | 3.112154 | 3 |
createplaylist.py | mahi0601/SpotifyPlaylist | 47 | 2010 | <reponame>mahi0601/SpotifyPlaylist
import os
from spotifyclient import SpotifyClient
def main():
spotify_client = SpotifyClient(os.getenv("SPOTIFY_AUTHORIZATION_TOKEN"),
os.getenv("SPOTIFY_USER_ID"))
# get last played tracks
num_tracks_to_visualise = int(input("How man... | import os
from spotifyclient import SpotifyClient
def main():
spotify_client = SpotifyClient(os.getenv("SPOTIFY_AUTHORIZATION_TOKEN"),
os.getenv("SPOTIFY_USER_ID"))
# get last played tracks
num_tracks_to_visualise = int(input("How many tracks would you like to visualis... | en | 0.972752 | # get last played tracks # choose which tracks to use as a seed to generate a playlist # get recommended tracks based off seed tracks # get playlist name from user and create playlist # populate playlist with recommended tracks | 3.699341 | 4 |
tests/contrib/flask/test_request.py | thieman/dd-trace-py | 0 | 2011 | # -*- coding: utf-8 -*-
from ddtrace.compat import PY2
from ddtrace.constants import ANALYTICS_SAMPLE_RATE_KEY
from ddtrace.contrib.flask.patch import flask_version
from ddtrace.ext import http
from ddtrace.propagation.http import HTTP_HEADER_TRACE_ID, HTTP_HEADER_PARENT_ID
from flask import abort
from . import BaseFl... | # -*- coding: utf-8 -*-
from ddtrace.compat import PY2
from ddtrace.constants import ANALYTICS_SAMPLE_RATE_KEY
from ddtrace.contrib.flask.patch import flask_version
from ddtrace.ext import http
from ddtrace.propagation.http import HTTP_HEADER_TRACE_ID, HTTP_HEADER_PARENT_ID
from flask import abort
from . import BaseFl... | en | 0.781682 | # -*- coding: utf-8 -*- When making a request We create the expected spans # Assert the order of the spans created # Assert span services # Root request span # Request tags # Handler span Make sure when making a request that we create the expected spans and capture the query string. # Request tags When maki... | 2.43656 | 2 |
ConvDR/data/preprocess_cast19.py | blazejdolicki/CHEDAR | 1 | 2012 | <filename>ConvDR/data/preprocess_cast19.py
import argparse
from trec_car import read_data
from tqdm import tqdm
import pickle
import os
import json
import copy
from utils.util import NUM_FOLD
def parse_sim_file(filename):
"""
Reads the deduplicated documents file and stores the
duplicate passage ids into ... | <filename>ConvDR/data/preprocess_cast19.py
import argparse
from trec_car import read_data
from tqdm import tqdm
import pickle
import os
import json
import copy
from utils.util import NUM_FOLD
def parse_sim_file(filename):
"""
Reads the deduplicated documents file and stores the
duplicate passage ids into ... | en | 0.549013 | Reads the deduplicated documents file and stores the duplicate passage ids into a dictionary # INPUT # OUTPUT # 1. Combine TREC-CAR & MS MARCO, remove duplicate passages, assign new ids #FIX change 'a' to 'w' in normal run # e.g. CAR_76a4a716d4b1b01995c6663ee16e94b4ca35fdd3 -> 10000044 # 2. Process queries # Split ... | 2.577146 | 3 |
coord_convert/geojson_utils.py | brandonxiang/example-pyQGIS | 3 | 2013 | __doc__ = 'github: https://github.com/brandonxiang/geojson-python-utils'
import math
from coordTransform_utils import wgs84togcj02
from coordTransform_utils import gcj02tobd09
def linestrings_intersect(line1, line2):
"""
To valid whether linestrings from geojson are intersected with each other.
reference:... | __doc__ = 'github: https://github.com/brandonxiang/geojson-python-utils'
import math
from coordTransform_utils import wgs84togcj02
from coordTransform_utils import gcj02tobd09
def linestrings_intersect(line1, line2):
"""
To valid whether linestrings from geojson are intersected with each other.
reference:... | en | 0.64048 | To valid whether linestrings from geojson are intersected with each other. reference: http://www.kevlindev.com/gui/math/intersection/Intersection.js Keyword arguments: line1 -- first line geojson object line2 -- second line geojson object if(line1 intersects with other) return intersect point arra... | 3.086154 | 3 |
config.py | Rinku92/Mini_Project3 | 0 | 2014 | import os
'''
user = os.environ['POSTGRES_USER']
password = os.environ['<PASSWORD>']
host = os.environ['POSTGRES_HOST']
database = os.environ['POSTGRES_DB']
port = os.environ['POSTGRES_PORT']
'''
user = 'test'
password = 'password'
host = 'localhost'
database = 'example'
port = '5432'
DATABASE_CONNECTION_URI = f'post... | import os
'''
user = os.environ['POSTGRES_USER']
password = os.environ['<PASSWORD>']
host = os.environ['POSTGRES_HOST']
database = os.environ['POSTGRES_DB']
port = os.environ['POSTGRES_PORT']
'''
user = 'test'
password = 'password'
host = 'localhost'
database = 'example'
port = '5432'
DATABASE_CONNECTION_URI = f'post... | en | 0.498466 | user = os.environ['POSTGRES_USER'] password = os.environ['<PASSWORD>'] host = os.environ['POSTGRES_HOST'] database = os.environ['POSTGRES_DB'] port = os.environ['POSTGRES_PORT'] | 2.239383 | 2 |
10_days_of_statistics_8_1.py | sercangul/HackerRank | 0 | 2015 | <reponame>sercangul/HackerRank
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 3 19:26:47 2019
@author: sercangul
"""
n = 5
xy = [map(int, input().split()) for _ in range(n)]
sx, sy, sx2, sxy = map(sum, zip(*[(x, y, x**2, x * y) for x, y in xy]))
b = (n * sxy - sx * sy) / (n * sx2 - sx**2)
a = ... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 3 19:26:47 2019
@author: sercangul
"""
n = 5
xy = [map(int, input().split()) for _ in range(n)]
sx, sy, sx2, sxy = map(sum, zip(*[(x, y, x**2, x * y) for x, y in xy]))
b = (n * sxy - sx * sy) / (n * sx2 - sx**2)
a = (sy / n) - b * (sx / n)
print('... | en | 0.430557 | #!/usr/bin/env python3 # -*- coding: utf-8 -*- Created on Mon Jun 3 19:26:47 2019 @author: sercangul | 3.443705 | 3 |
rlutils/gym/envs/reset_obs/hopper.py | vermouth1992/rl-util | 0 | 2016 | import gym.envs.mujoco.hopper as hopper
import numpy as np
class HopperEnv(hopper.HopperEnv):
def _get_obs(self):
return np.concatenate([
self.sim.data.qpos.flat[1:],
self.sim.data.qvel.flat,
])
def reset_obs(self, obs):
state = np.insert(obs, 0, 0.)
qp... | import gym.envs.mujoco.hopper as hopper
import numpy as np
class HopperEnv(hopper.HopperEnv):
def _get_obs(self):
return np.concatenate([
self.sim.data.qpos.flat[1:],
self.sim.data.qvel.flat,
])
def reset_obs(self, obs):
state = np.insert(obs, 0, 0.)
qp... | none | 1 | 2.362239 | 2 | |
reco_utils/recommender/deeprec/io/iterator.py | yutian-zhao/recommenders | 0 | 2017 | <reponame>yutian-zhao/recommenders
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import numpy as np
# import tensorflow as tf
import abc
class BaseIterator(object):
@abc.abstractmethod
def parser_one_line(self, line):
pass
@abc.abstractmethod
d... | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import numpy as np
# import tensorflow as tf
import abc
class BaseIterator(object):
@abc.abstractmethod
def parser_one_line(self, line):
pass
@abc.abstractmethod
def load_data_from_file(self, infile... | en | 0.515427 | # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. # import tensorflow as tf # class FFMTextIterator(BaseIterator): # """Data loader for FFM format based models, such as xDeepFM. # Iterator will not load the whole data into memory. Instead, it loads data into memory # ... | 2.569511 | 3 |
HW6/YuliiaKutsyk/3_ unfinished_loop_bug_fixing.py | kolyasalubov/Lv-677.PythonCore | 0 | 2018 | def create_array(n):
res=[]
i=1
while i<=n:
res.append(i)
i += 1
return res
| def create_array(n):
res=[]
i=1
while i<=n:
res.append(i)
i += 1
return res
| none | 1 | 3.219784 | 3 | |
ncm/api.py | SDhuangao/netease-cloud-music-dl | 0 | 2019 | <reponame>SDhuangao/netease-cloud-music-dl
# -*- coding: utf-8 -*-
import requests
from ncm.encrypt import encrypted_request
from ncm.constants import headers
from ncm.constants import song_download_url
from ncm.constants import get_song_url
from ncm.constants import get_album_url
from ncm.constants import get_artist... | # -*- coding: utf-8 -*-
import requests
from ncm.encrypt import encrypted_request
from ncm.constants import headers
from ncm.constants import song_download_url
from ncm.constants import get_song_url
from ncm.constants import get_album_url
from ncm.constants import get_artist_url
from ncm.constants import get_playlist... | en | 0.675216 | # -*- coding: utf-8 -*- Get song info by song id :param song_id: :return: Get all album songs info by album id :param album_id: :return: Get a song's download url. :params song_id: song id<int>. :params bit_rate: {'MD 128k': 128000, 'HD 320k': 320000} :return: Get... | 2.605278 | 3 |
book/trees/binary_search_tree.py | Web-Dev-Collaborative/algos | 153 | 2020 | # -*- coding: utf-8 -*-
"""
The `TreeNode` class provides many helper functions that make the work
done in the `BinarySearchTree` class methods much easier. The
constructor for a `TreeNode`, along with these helper functions, is
shown below. As you can see, many of these helper functions help to
classify a node acco... | # -*- coding: utf-8 -*-
"""
The `TreeNode` class provides many helper functions that make the work
done in the `BinarySearchTree` class methods much easier. The
constructor for a `TreeNode`, along with these helper functions, is
shown below. As you can see, many of these helper functions help to
classify a node acco... | en | 0.91 | # -*- coding: utf-8 -*- The `TreeNode` class provides many helper functions that make the work done in the `BinarySearchTree` class methods much easier. The constructor for a `TreeNode`, along with these helper functions, is shown below. As you can see, many of these helper functions help to classify a node according t... | 4.129365 | 4 |
fire/core.py | adamruth/python-fire | 1 | 2021 | <filename>fire/core.py
# Copyright (C) 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | <filename>fire/core.py
# Copyright (C) 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | en | 0.811297 | # Copyright (C) 2017 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ... | 2.895466 | 3 |
app.py | AmirValeev/auto-ml-classifier | 0 | 2022 | <reponame>AmirValeev/auto-ml-classifier<gh_stars>0
import os, ast
import pandas as pd
from sklearn.svm import SVC
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import OneHotEncoder
from sklearn.compose import make_column_transformer
from sklearn.pipeline import make_pipeline
import pic... | import os, ast
import pandas as pd
from sklearn.svm import SVC
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import OneHotEncoder
from sklearn.compose import make_column_transformer
from sklearn.pipeline import make_pipeline
import pickle
def main():
# Get the dataset from the us... | en | 0.574321 | # Get the dataset from the users GitHub repository # apply encoding on output variable #define a pipeline #training the model # store the artifact in docker container | 2.912923 | 3 |
util/headers.py | giuseppe/quay | 2,027 | 2023 | <gh_stars>1000+
import base64
def parse_basic_auth(header_value):
"""
Attempts to parse the given header value as a Base64-encoded Basic auth header.
"""
if not header_value:
return None
parts = header_value.split(" ")
if len(parts) != 2 or parts[0].lower() != "basic":
return... | import base64
def parse_basic_auth(header_value):
"""
Attempts to parse the given header value as a Base64-encoded Basic auth header.
"""
if not header_value:
return None
parts = header_value.split(" ")
if len(parts) != 2 or parts[0].lower() != "basic":
return None
try:
... | en | 0.737005 | Attempts to parse the given header value as a Base64-encoded Basic auth header. | 3.34628 | 3 |
indico/core/signals/event/core.py | tobiashuste/indico | 0 | 2024 | <gh_stars>0
# This file is part of Indico.
# Copyright (C) 2002 - 2020 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.
from indico.core.signals.event import _signals
sidemenu = _signals.signal('sidemenu', """
Ex... | # This file is part of Indico.
# Copyright (C) 2002 - 2020 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.
from indico.core.signals.event import _signals
sidemenu = _signals.signal('sidemenu', """
Expected to re... | en | 0.881527 | # This file is part of Indico. # Copyright (C) 2002 - 2020 CERN # # Indico is free software; you can redistribute it and/or # modify it under the terms of the MIT License; see the # LICENSE file for more details. Expected to return ``MenuEntryData`` objects to be added to the event side menu. A single entry can be retu... | 2.081519 | 2 |
cinder/tests/unit/volume/drivers/emc/scaleio/test_delete_volume.py | aarunsai81/netapp | 11 | 2025 | # Copyright (c) 2013 - 2015 EMC Corporation.
# 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
#
# Unle... | # Copyright (c) 2013 - 2015 EMC Corporation.
# 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
#
# Unle... | en | 0.827274 | # Copyright (c) 2013 - 2015 EMC Corporation. # 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 # # Unle... | 1.909383 | 2 |
example-package/transportation_tutorials/__init__.py | chrisc20042001/python-for-transportation-modeling | 0 | 2026 | # -*- coding: utf-8 -*-
__version__ = '1.0.2'
import os
import appdirs
import osmnx as ox
import joblib
import requests
from .files import load_vars, save_vars, cached, inflate_tar, download_zipfile
from .data import data, list_data, problematic
from .tools.view_code import show_file
from . import mapping
cache_dir ... | # -*- coding: utf-8 -*-
__version__ = '1.0.2'
import os
import appdirs
import osmnx as ox
import joblib
import requests
from .files import load_vars, save_vars, cached, inflate_tar, download_zipfile
from .data import data, list_data, problematic
from .tools.view_code import show_file
from . import mapping
cache_dir ... | en | 0.60798 | # -*- coding: utf-8 -*- Set up a cache directory for use with the tutorials. Parameter --------- cache_dir : Path-like or False, optional A path for the cache files. Set to False to disable caching. | 2.359453 | 2 |
common/common.py | czajowaty/curry-bot | 3 | 2027 | <reponame>czajowaty/curry-bot<filename>common/common.py
from requests.models import PreparedRequest
def is_valid_url(url):
prepared_request = PreparedRequest()
try:
prepared_request.prepare_url(url, None)
return True
except Exception as e:
return False
class Timestamp: # a speed... | from requests.models import PreparedRequest
def is_valid_url(url):
prepared_request = PreparedRequest()
try:
prepared_request.prepare_url(url, None)
return True
except Exception as e:
return False
class Timestamp: # a speedrun.com style timestamp e.g. "3h 53m 233s 380ms"
def... | en | 0.526177 | # a speedrun.com style timestamp e.g. "3h 53m 233s 380ms" | 3.237384 | 3 |
hendrix/test/test_ux.py | anthonyalmarza/hendrix | 0 | 2028 | import os
import sys
from . import HendrixTestCase, TEST_SETTINGS
from hendrix.contrib import SettingsError
from hendrix.options import options as hx_options
from hendrix import ux
from mock import patch
class TestMain(HendrixTestCase):
def setUp(self):
super(TestMain, self).setUp()
self.DEFAULTS... | import os
import sys
from . import HendrixTestCase, TEST_SETTINGS
from hendrix.contrib import SettingsError
from hendrix.options import options as hx_options
from hendrix import ux
from mock import patch
class TestMain(HendrixTestCase):
def setUp(self):
super(TestMain, self).setUp()
self.DEFAULTS... | en | 0.85805 | A test to ensure that HendrixDeploy.options also has the complete set of options available | 2.243184 | 2 |
discord/types/interactions.py | Voxel-Fox-Ltd/Novus | 61 | 2029 | """
The MIT License (MIT)
Copyright (c) 2015-2021 Rapptz
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, ... | """
The MIT License (MIT)
Copyright (c) 2015-2021 Rapptz
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, ... | en | 0.751534 | The MIT License (MIT) Copyright (c) 2015-2021 Rapptz 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, publ... | 1.490304 | 1 |
local/local_sign.py | EVAyo/chaoxing_auto_sign | 0 | 2030 | # -*- coding: utf8 -*-
import os
import re
import time
import json
import random
import asyncio
from typing import Optional, List, Dict
from aiohttp import ClientSession
from aiohttp.cookiejar import SimpleCookie
from lxml import etree
from bs4 import BeautifulSoup
from config import *
from message import server_chan... | # -*- coding: utf8 -*-
import os
import re
import time
import json
import random
import asyncio
from typing import Optional, List, Dict
from aiohttp import ClientSession
from aiohttp.cookiejar import SimpleCookie
from lxml import etree
from bs4 import BeautifulSoup
from config import *
from message import server_chan... | zh | 0.916999 | # -*- coding: utf8 -*- 初始化就进行登录 # 登录成功 # 登录信息有误 设置cookies # 无效则重新登录,并保存cookies 从响应对象中抽取cookies 保存cookies 检测json文件内是否存有cookies,有则检测,无则登录 # json文件有无账号cookies, 没有,则直接返回假 # 检测cookies是否有效 登录并返回响应 检测activeid是否存在,不存在则添加 # 读取文件 # 如果出错,则表示没有此activeid 保存已成功签到的activeid 获取课程主页中所有课程的classid和courseid 获取签到类型 访问任务面板获取课程的活动id 普通签到 # 网页... | 2.506975 | 3 |
build/scripts-3.6/fit_background_model.py | stahlberggroup/umierrorcorrect | 0 | 2031 | <filename>build/scripts-3.6/fit_background_model.py<gh_stars>0
#!python
import numpy as np
from numpy import inf
from numpy import nan
from scipy.optimize import fmin
from scipy.stats import beta
from scipy.special import beta as B
from scipy.special import comb
import argparse
import sys
def parseArgs():
'''Funct... | <filename>build/scripts-3.6/fit_background_model.py<gh_stars>0
#!python
import numpy as np
from numpy import inf
from numpy import nan
from scipy.optimize import fmin
from scipy.stats import beta
from scipy.special import beta as B
from scipy.special import comb
import argparse
import sys
def parseArgs():
'''Funct... | en | 0.21099 | #!python Function for parsing arguments #print(name) #print(name) #print(famsize) #lg=np.where(lg==-np.inf,0,lg) #a=prob_bb(n1,a1,result[0],result[1]) #a[a==inf]=1e-10 #a[np.isnan(a)]=1e-10 #Q = -10*np.log10(a) #data=np.array(data) #plot_histogram(Q,args.output_path+'/'+args.sample_name+'.histogram.png') #if args.vc_me... | 2.222575 | 2 |
caffe2/python/operator_test/partition_ops_test.py | KevinKecc/caffe2 | 585 | 2032 | # Copyright (c) 2016-present, Facebook, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | # Copyright (c) 2016-present, Facebook, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | en | 0.803623 | # Copyright (c) 2016-present, Facebook, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed... | 1.710422 | 2 |
cisco-ios-xr/ydk/models/cisco_ios_xr/Cisco_IOS_XR_fib_common_cfg.py | Maikor/ydk-py | 0 | 2033 | """ Cisco_IOS_XR_fib_common_cfg
This module contains a collection of YANG definitions
for Cisco IOS\-XR fib\-common package configuration.
This module contains definitions
for the following management objects\:
fib\: CEF configuration
Copyright (c) 2013\-2018 by Cisco Systems, Inc.
All rights reserved.
"""
from ... | """ Cisco_IOS_XR_fib_common_cfg
This module contains a collection of YANG definitions
for Cisco IOS\-XR fib\-common package configuration.
This module contains definitions
for the following management objects\:
fib\: CEF configuration
Copyright (c) 2013\-2018 by Cisco Systems, Inc.
All rights reserved.
"""
from ... | en | 0.353531 | Cisco_IOS_XR_fib_common_cfg This module contains a collection of YANG definitions for Cisco IOS\-XR fib\-common package configuration. This module contains definitions for the following management objects\: fib\: CEF configuration Copyright (c) 2013\-2018 by Cisco Systems, Inc. All rights reserved. FibPbtsFallbac... | 1.78613 | 2 |
action/combo.py | dl-stuff/dl9 | 0 | 2034 | """Series of actions that form a combo chain"""
from __future__ import annotations
from typing import Optional, Sequence, TYPE_CHECKING
from action import Action
from core.utility import Array
from core.constants import PlayerForm, SimActKind, MomentType
from core.database import FromDB
if TYPE_CHECKING:
from ent... | """Series of actions that form a combo chain"""
from __future__ import annotations
from typing import Optional, Sequence, TYPE_CHECKING
from action import Action
from core.utility import Array
from core.constants import PlayerForm, SimActKind, MomentType
from core.database import FromDB
if TYPE_CHECKING:
from ent... | en | 0.946229 | Series of actions that form a combo chain | 2.472745 | 2 |
flask_unchained/bundles/session/config.py | achiang/flask-unchained | 0 | 2035 | <filename>flask_unchained/bundles/session/config.py
import os
from datetime import timedelta
from flask_unchained import BundleConfig
try:
from flask_unchained.bundles.sqlalchemy import db
except ImportError:
db = None
class _DefaultFlaskConfigForSessions(BundleConfig):
SESSION_COOKIE_NAME = 'session'
... | <filename>flask_unchained/bundles/session/config.py
import os
from datetime import timedelta
from flask_unchained import BundleConfig
try:
from flask_unchained.bundles.sqlalchemy import db
except ImportError:
db = None
class _DefaultFlaskConfigForSessions(BundleConfig):
SESSION_COOKIE_NAME = 'session'
... | en | 0.619422 | The name of the session cookie. Defaults to ``'session'``. The domain for the session cookie. If this is not set, the cookie will be valid for all subdomains of ``SERVER_NAME``. Defaults to ``None``. The path for the session cookie. If this is not set the cookie will be valid for all of ``APPLICATION_... | 2.220512 | 2 |
sktime/forecasting/base/adapters/_statsmodels.py | tombh/sktime | 1 | 2036 | #!/usr/bin/env python3 -u
# -*- coding: utf-8 -*-
__author__ = ["<NAME>"]
__all__ = ["_StatsModelsAdapter"]
import numpy as np
import pandas as pd
from sktime.forecasting.base._base import DEFAULT_ALPHA
from sktime.forecasting.base._sktime import _OptionalForecastingHorizonMixin
from sktime.forecasting.base._sktime ... | #!/usr/bin/env python3 -u
# -*- coding: utf-8 -*-
__author__ = ["<NAME>"]
__all__ = ["_StatsModelsAdapter"]
import numpy as np
import pandas as pd
from sktime.forecasting.base._base import DEFAULT_ALPHA
from sktime.forecasting.base._sktime import _OptionalForecastingHorizonMixin
from sktime.forecasting.base._sktime ... | en | 0.578265 | #!/usr/bin/env python3 -u # -*- coding: utf-8 -*- Base class for interfacing statsmodels forecasting algorithms Fit to training data. Parameters ---------- y : pd.Series Target time series to which to fit the forecaster. fh : int, list or np.array, optional (default=None) ... | 2.642127 | 3 |
melodic/lib/python2.7/dist-packages/gazebo_msgs/srv/_GetLinkProperties.py | Dieptranivsr/Ros_Diep | 0 | 2037 | <gh_stars>0
# This Python file uses the following encoding: utf-8
"""autogenerated by genpy from gazebo_msgs/GetLinkPropertiesRequest.msg. Do not edit."""
import codecs
import sys
python3 = True if sys.hexversion > 0x03000000 else False
import genpy
import struct
class GetLinkPropertiesRequest(genpy.Message):
_md5s... | # This Python file uses the following encoding: utf-8
"""autogenerated by genpy from gazebo_msgs/GetLinkPropertiesRequest.msg. Do not edit."""
import codecs
import sys
python3 = True if sys.hexversion > 0x03000000 else False
import genpy
import struct
class GetLinkPropertiesRequest(genpy.Message):
_md5sum = "7d82d6... | en | 0.568797 | # This Python file uses the following encoding: utf-8 autogenerated by genpy from gazebo_msgs/GetLinkPropertiesRequest.msg. Do not edit. # flag to mark the presence of a Header object string link_name # name of link # link names are prefixed by model name, e.g. pr2::base_link Construc... | 2.267118 | 2 |
jupytext/kernels.py | st--/jupytext | 5,378 | 2038 | """Find kernel specifications for a given language"""
import os
import sys
from .languages import same_language
from .reraise import reraise
try:
# I prefer not to take a dependency on jupyter_client
from jupyter_client.kernelspec import find_kernel_specs, get_kernel_spec
except ImportError as err:
find_... | """Find kernel specifications for a given language"""
import os
import sys
from .languages import same_language
from .reraise import reraise
try:
# I prefer not to take a dependency on jupyter_client
from jupyter_client.kernelspec import find_kernel_specs, get_kernel_spec
except ImportError as err:
find_... | en | 0.789812 | Find kernel specifications for a given language # I prefer not to take a dependency on jupyter_client Set the kernel specification based on the 'main_language' metadata Return the python kernel that matches the current env, or the first kernel that matches the given language # Return the kernel that matches the current... | 2.809406 | 3 |
scipy/sparse/_matrix_io.py | dhruv9vats/scipy | 1 | 2039 | import numpy as np
import scipy.sparse
__all__ = ['save_npz', 'load_npz']
# Make loading safe vs. malicious input
PICKLE_KWARGS = dict(allow_pickle=False)
def save_npz(file, matrix, compressed=True):
""" Save a sparse matrix to a file using ``.npz`` format.
Parameters
----------
file : str or file... | import numpy as np
import scipy.sparse
__all__ = ['save_npz', 'load_npz']
# Make loading safe vs. malicious input
PICKLE_KWARGS = dict(allow_pickle=False)
def save_npz(file, matrix, compressed=True):
""" Save a sparse matrix to a file using ``.npz`` format.
Parameters
----------
file : str or file... | en | 0.440113 | # Make loading safe vs. malicious input Save a sparse matrix to a file using ``.npz`` format. Parameters ---------- file : str or file-like object Either the file name (string) or an open file (file-like object) where the data will be saved. If file is a string, the ``.npz`` extensi... | 3.56831 | 4 |
src/simulator/services/resources/atlas.py | ed741/PathBench | 46 | 2040 | from typing import Dict, List
from simulator.services.resources.directory import Directory
from simulator.services.services import Services
class Atlas(Directory):
def __init__(self, services: Services, name: str, parent: str, create: bool = False) -> None:
super().__init__(services, name, parent, create... | from typing import Dict, List
from simulator.services.resources.directory import Directory
from simulator.services.services import Services
class Atlas(Directory):
def __init__(self, services: Services, name: str, parent: str, create: bool = False) -> None:
super().__init__(services, name, parent, create... | none | 1 | 2.665755 | 3 | |
ingestion/src/metadata/great_expectations/builders/table/row_count_to_equal.py | ulixius9/OpenMetadata | 0 | 2041 | # Copyright 2022 Collate
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software... | # Copyright 2022 Collate
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software... | en | 0.840882 | # Copyright 2022 Collate # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software... | 1.924616 | 2 |
tensorflow/bbox/jrieke-tf-parse-v2/jrieke_tf_dataset.py | gustavovaliati/obj-det-experiments | 0 | 2042 | '''
This code is based on https://github.com/jrieke/shape-detection/
'''
import matplotlib.pyplot as plt
import matplotlib
import numpy as np
import tensorflow as tf
import datetime
class JriekeBboxDataset:
def generate(self):
print('Generating...')
self.WIDTH = 8
self.HEIGHT = 8
... | '''
This code is based on https://github.com/jrieke/shape-detection/
'''
import matplotlib.pyplot as plt
import matplotlib
import numpy as np
import tensorflow as tf
import datetime
class JriekeBboxDataset:
def generate(self):
print('Generating...')
self.WIDTH = 8
self.HEIGHT = 8
... | en | 0.739369 | This code is based on https://github.com/jrieke/shape-detection/ # set background to 0 # set rectangle to 1 #why this? # X = (self.imgs.reshape(num_imgs, -1) - np.mean(self.imgs)) / np.std(self.imgs) # Split training and test. #80% for training Calculate overlap between two bounding boxes [x, y, w, h] as the area of in... | 3.058628 | 3 |
src/knownnodes.py | skeevey/PyBitmessage | 1 | 2043 | import pickle
import threading
from bmconfigparser import BMConfigParser
import state
knownNodesLock = threading.Lock()
knownNodes = {}
knownNodesTrimAmount = 2000
def saveKnownNodes(dirName = None):
if dirName is None:
dirName = state.appdata
with knownNodesLock:
with open(dirName + 'knownn... | import pickle
import threading
from bmconfigparser import BMConfigParser
import state
knownNodesLock = threading.Lock()
knownNodes = {}
knownNodesTrimAmount = 2000
def saveKnownNodes(dirName = None):
if dirName is None:
dirName = state.appdata
with knownNodesLock:
with open(dirName + 'knownn... | none | 1 | 2.664371 | 3 | |
chroma_agent/action_plugins/manage_node.py | whamcloud/iml-agent | 1 | 2044 | # Copyright (c) 2018 DDN. All rights reserved.
# Use of this source code is governed by a MIT-style
# license that can be found in the LICENSE file.
import os
from chroma_agent.lib.shell import AgentShell
from chroma_agent.log import console_log
from chroma_agent.device_plugins.action_runner import CallbackAfterResp... | # Copyright (c) 2018 DDN. All rights reserved.
# Use of this source code is governed by a MIT-style
# license that can be found in the LICENSE file.
import os
from chroma_agent.lib.shell import AgentShell
from chroma_agent.log import console_log
from chroma_agent.device_plugins.action_runner import CallbackAfterResp... | en | 0.954614 | # Copyright (c) 2018 DDN. All rights reserved. # Use of this source code is governed by a MIT-style # license that can be found in the LICENSE file. # force a manual failover by failing a node # TODO: signal that manager that a STONITH has been done so that it # doesn't treat it as an AWOL # This will initiate a ... | 2.022025 | 2 |
census_data_downloader/core/tables.py | ian-r-rose/census-data-downloader | 0 | 2045 | #! /usr/bin/env python
# -*- coding: utf-8 -*
"""
A base class that governs how to download and process tables from a Census API table.
"""
import os
import logging
import pathlib
from . import geotypes
from . import decorators
logger = logging.getLogger(__name__)
class BaseTableConfig(object):
"""
Configures... | #! /usr/bin/env python
# -*- coding: utf-8 -*
"""
A base class that governs how to download and process tables from a Census API table.
"""
import os
import logging
import pathlib
from . import geotypes
from . import decorators
logger = logging.getLogger(__name__)
class BaseTableConfig(object):
"""
Configures... | en | 0.813966 | #! /usr/bin/env python # -*- coding: utf-8 -* A base class that governs how to download and process tables from a Census API table. Configures how to download and process tables from the Census API. # All available years # All available geographies Configuration. # Set the inputs # # Allow custom years for data downloa... | 2.857613 | 3 |
sgf2ebook.py | loujine/sgf2ebook | 0 | 2046 | <gh_stars>0
#!/usr/bin/env python3
import argparse
import os
from pathlib import Path
import shutil
import subprocess
import sys
from tempfile import TemporaryDirectory
from uuid import uuid4
from zipfile import ZipFile
import jinja2
import sente # type: ignore
__version__ = (1, 0, 0)
SGF_RENDER_EXECUTABLE = './sgf... | #!/usr/bin/env python3
import argparse
import os
from pathlib import Path
import shutil
import subprocess
import sys
from tempfile import TemporaryDirectory
from uuid import uuid4
from zipfile import ZipFile
import jinja2
import sente # type: ignore
__version__ = (1, 0, 0)
SGF_RENDER_EXECUTABLE = './sgf-render'
TE... | en | 0.649144 | #!/usr/bin/env python3 # type: ignore # read only main sequence, not variations # generate SVG files with sgf-render # replace move number in SVG # not possible directly in sgf-render invocation at the moment # create HTML page with SVG element # Declare all HTML/SVG files in master file # Generate table of contents # ... | 2.350907 | 2 |
vmis_sql_python/evaluation/metrics/popularity.py | bolcom/serenade-experiments-sigmod | 0 | 2047 | class Popularity:
'''
Popularity( length=20 )
Used to iteratively calculate the average overall popularity of an algorithm's recommendations.
Parameters
-----------
length : int
Coverage@length
training_df : dataframe
determines how many distinct item_ids there are in the ... | class Popularity:
'''
Popularity( length=20 )
Used to iteratively calculate the average overall popularity of an algorithm's recommendations.
Parameters
-----------
length : int
Coverage@length
training_df : dataframe
determines how many distinct item_ids there are in the ... | en | 0.767319 | Popularity( length=20 ) Used to iteratively calculate the average overall popularity of an algorithm's recommendations. Parameters ----------- length : int Coverage@length training_df : dataframe determines how many distinct item_ids there are in the training data #group the data ... | 3.945133 | 4 |
dandeliondiary/household/urls.py | amberdiehl/dandeliondiary_project | 0 | 2048 | from django.conf.urls import include, url
from . import views
urlpatterns = [
url(r'^settings$', views.household_dashboard, name='household_dashboard'),
url(r'^myinfo$', views.my_info, name='my_info'),
url(r'^profile$', views.household_profile, name='maintain_household'),
url(r'^members$', views.househ... | from django.conf.urls import include, url
from . import views
urlpatterns = [
url(r'^settings$', views.household_dashboard, name='household_dashboard'),
url(r'^myinfo$', views.my_info, name='my_info'),
url(r'^profile$', views.household_profile, name='maintain_household'),
url(r'^members$', views.househ... | none | 1 | 1.872479 | 2 | |
private/templates/NYC/config.py | devinbalkind/eden | 0 | 2049 | # -*- coding: utf-8 -*-
try:
# Python 2.7
from collections import OrderedDict
except:
# Python 2.6
from gluon.contrib.simplejson.ordered_dict import OrderedDict
from gluon import current
from gluon.html import A, URL
from gluon.storage import Storage
from s3 import s3_fullname
T = current.T
settings... | # -*- coding: utf-8 -*-
try:
# Python 2.7
from collections import OrderedDict
except:
# Python 2.6
from gluon.contrib.simplejson.ordered_dict import OrderedDict
from gluon import current
from gluon.html import A, URL
from gluon.storage import Storage
from s3 import s3_fullname
T = current.T
settings... | en | 0.693979 | # -*- coding: utf-8 -*- # Python 2.7 # Python 2.6 Template settings for NYC Prepared # Pre-Populate # Theme (folder to use for views/layout.html) # Uncomment to Hide the language toolbar # Default timezone for users # Uncomment these to use US-style dates in English # Start week on Sunday # Number formats (defaults to ... | 2.096085 | 2 |
experiments/issue561/v2.py | nitinkaveriappa/downward | 4 | 2050 | <reponame>nitinkaveriappa/downward
#! /usr/bin/env python
# -*- coding: utf-8 -*-
from main import main
main("issue561-v1", "issue561-v2")
| #! /usr/bin/env python
# -*- coding: utf-8 -*-
from main import main
main("issue561-v1", "issue561-v2") | en | 0.347319 | #! /usr/bin/env python # -*- coding: utf-8 -*- | 1.363599 | 1 |
q2_qemistree/tests/test_fingerprint.py | tgroth97/q2-qemistree | 0 | 2051 | # ----------------------------------------------------------------------------
# Copyright (c) 2016-2018, QIIME 2 development team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file LICENSE, distributed with this software.
# ------------------------------------------------... | # ----------------------------------------------------------------------------
# Copyright (c) 2016-2018, QIIME 2 development team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file LICENSE, distributed with this software.
# ------------------------------------------------... | en | 0.646002 | # ---------------------------------------------------------------------------- # Copyright (c) 2016-2018, QIIME 2 development team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file LICENSE, distributed with this software. # ------------------------------------------------... | 1.687357 | 2 |
chroma-manager/tests/utils/__init__.py | GarimaVishvakarma/intel-chroma | 0 | 2052 | import time
import datetime
import contextlib
@contextlib.contextmanager
def patch(obj, **attrs):
"Monkey patch an object's attributes, restoring them after the block."
stored = {}
for name in attrs:
stored[name] = getattr(obj, name)
setattr(obj, name, attrs[name])
try:
yield
... | import time
import datetime
import contextlib
@contextlib.contextmanager
def patch(obj, **attrs):
"Monkey patch an object's attributes, restoring them after the block."
stored = {}
for name in attrs:
stored[name] = getattr(obj, name)
setattr(obj, name, attrs[name])
try:
yield
... | none | 1 | 3.379642 | 3 | |
tempo/worker.py | rackerlabs/Tempo | 4 | 2053 | <gh_stars>1-10
# vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright 2012 Rackspace
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.a... | # vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright 2012 Rackspace
# 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/licen... | en | 0.833411 | # vim: tabstop=4 shiftwidth=4 softtabstop=4 # # Copyright 2012 Rackspace # 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/licen... | 1.719892 | 2 |
bin/basenji_motifs.py | AndyPJiang/basenji | 1 | 2054 | #!/usr/bin/env python
# Copyright 2017 Calico LLC
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# https://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agr... | #!/usr/bin/env python
# Copyright 2017 Calico LLC
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# https://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agr... | de | 0.272133 | #!/usr/bin/env python # Copyright 2017 Calico LLC # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # https://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed... | 1.999326 | 2 |
apps/shop/urls.py | Joetib/jshop | 1 | 2055 | from django.urls import path
from . import views
app_name = "shop"
urlpatterns = [
path('', views.HomePage.as_view(), name="home-page"),
path('shop/', views.ProductListView.as_view(), name="product-list"),
path('shop/<int:category_pk>/', views.ProductListView.as_view(), name="product-list"),
path('sho... | from django.urls import path
from . import views
app_name = "shop"
urlpatterns = [
path('', views.HomePage.as_view(), name="home-page"),
path('shop/', views.ProductListView.as_view(), name="product-list"),
path('shop/<int:category_pk>/', views.ProductListView.as_view(), name="product-list"),
path('sho... | none | 1 | 2.000793 | 2 | |
surpyval/parametric/expo_weibull.py | dfm/SurPyval | 0 | 2056 | <gh_stars>0
import autograd.numpy as np
from scipy.stats import uniform
from autograd import jacobian
from numpy import euler_gamma
from scipy.special import gamma as gamma_func
from scipy.special import ndtri as z
from scipy import integrate
from scipy.optimize import minimize
from surpyval import parametric as para
... | import autograd.numpy as np
from scipy.stats import uniform
from autograd import jacobian
from numpy import euler_gamma
from scipy.special import gamma as gamma_func
from scipy.special import ndtri as z
from scipy import integrate
from scipy.optimize import minimize
from surpyval import parametric as para
from surpyva... | en | 0.34651 | Survival (or reliability) function for the ExpoWeibull Distribution: .. math:: R(x) = 1 - \left [ 1 - e^{-\left ( \frac{x}{\alpha} \right )^\beta} \right ]^{\mu} Parameters ---------- x : numpy array or scalar The values at which the function will be calculated... | 2.055802 | 2 |
tests/test_base_table.py | stjordanis/datar | 110 | 2057 | <filename>tests/test_base_table.py<gh_stars>100-1000
import pytest
from datar import stats
from datar.base import *
from datar import f
from datar.datasets import warpbreaks, state_division, state_region, airquality
from .conftest import assert_iterable_equal
def test_table():
# https://www.rdocumentation.org/pa... | <filename>tests/test_base_table.py<gh_stars>100-1000
import pytest
from datar import stats
from datar.base import *
from datar import f
from datar.datasets import warpbreaks, state_division, state_region, airquality
from .conftest import assert_iterable_equal
def test_table():
# https://www.rdocumentation.org/pa... | pt | 0.148575 | # https://www.rdocumentation.org/packages/base/versions/3.6.2/topics/table #----------------- #----------------- #----------------- #----------------- #----------------- #----------------- # tab = table(a) # assert_iterable_equal(tab.values.flatten(), [10] * 4) #------------------ #------------------- | 2.154427 | 2 |
cqlengine/tests/statements/test_update_statement.py | dokai/cqlengine | 0 | 2058 | <reponame>dokai/cqlengine
from unittest import TestCase
from cqlengine.statements import UpdateStatement, WhereClause, AssignmentClause
from cqlengine.operators import *
class UpdateStatementTests(TestCase):
def test_table_rendering(self):
""" tests that fields are properly added to the select statement ... | from unittest import TestCase
from cqlengine.statements import UpdateStatement, WhereClause, AssignmentClause
from cqlengine.operators import *
class UpdateStatementTests(TestCase):
def test_table_rendering(self):
""" tests that fields are properly added to the select statement """
us = UpdateSta... | en | 0.945285 | tests that fields are properly added to the select statement | 2.885383 | 3 |
packages/facilities/diagnostics/py/custom_checkbox.py | Falcons-Robocup/code | 2 | 2059 | <reponame>Falcons-Robocup/code
# Copyright 2020 <NAME> (Falcons)
# SPDX-License-Identifier: Apache-2.0
#!/usr/bin/python
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle
class Checkbox():
def __init__(self, name, position, default=False, label=None, rsize=0.6, enabled=True):
self... | # Copyright 2020 <NAME> (Falcons)
# SPDX-License-Identifier: Apache-2.0
#!/usr/bin/python
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle
class Checkbox():
def __init__(self, name, position, default=False, label=None, rsize=0.6, enabled=True):
self.name = name # unique ID associ... | en | 0.524752 | # Copyright 2020 <NAME> (Falcons) # SPDX-License-Identifier: Apache-2.0 #!/usr/bin/python # unique ID associated with # label to display next to the checkbox # reuse # position is a tuple (x,y,w,h) # draw text # draw a rectangle, add a bit of spacing # setup event handling # TODO: exclude spacing margin for inaxes calc... | 3.117246 | 3 |
generator.py | Axonny/HexagonalHitori | 0 | 2060 | from hitori_generator import Generator
from argparse import ArgumentParser
def generate(n: int, output_file: str) -> None:
if n < 3 or n > 8:
print("It isn't valid size")
exit(4)
generator = Generator(n)
data = generator.generate()
lines = map(lambda x: ' '.join(map(str, x)), data)
... | from hitori_generator import Generator
from argparse import ArgumentParser
def generate(n: int, output_file: str) -> None:
if n < 3 or n > 8:
print("It isn't valid size")
exit(4)
generator = Generator(n)
data = generator.generate()
lines = map(lambda x: ' '.join(map(str, x)), data)
... | none | 1 | 3.358567 | 3 | |
opaflib/xmlast.py | feliam/opaf | 2 | 2061 | <filename>opaflib/xmlast.py
from lxml import etree
from opaflib.filters import defilterData
#Logging facility
import logging,code
logger = logging.getLogger("OPAFXML")
class PDFXML(etree.ElementBase):
''' Base pdf-xml class. Every pdf token xml representation will
have a span wich indicates where the orig... | <filename>opaflib/xmlast.py
from lxml import etree
from opaflib.filters import defilterData
#Logging facility
import logging,code
logger = logging.getLogger("OPAFXML")
class PDFXML(etree.ElementBase):
''' Base pdf-xml class. Every pdf token xml representation will
have a span wich indicates where the orig... | en | 0.734233 | #Logging facility Base pdf-xml class. Every pdf token xml representation will have a span wich indicates where the original token layed in the file Search the object and generation number of any pdf element #leaf search the referenced indirect object in the containing pdf #tree Check if stream is filtered #del ... | 2.665874 | 3 |
course-code/imooc-tf-mnist-flask/mnist/module.py | le3t/ko-repo | 30 | 2062 | <filename>course-code/imooc-tf-mnist-flask/mnist/module.py
import tensorflow as tf
# y=ax+b linear model
def regression(x):
a = tf.Variable(tf.zeros([784, 10]), name="a")
b = tf.Variable(tf.zeros([10]), name="b")
y = tf.nn.softmax(tf.matmul(x, a) + b)
return y, [a, b]
# 定义卷积模型
def convolutional(x, ... | <filename>course-code/imooc-tf-mnist-flask/mnist/module.py
import tensorflow as tf
# y=ax+b linear model
def regression(x):
a = tf.Variable(tf.zeros([784, 10]), name="a")
b = tf.Variable(tf.zeros([10]), name="b")
y = tf.nn.softmax(tf.matmul(x, a) + b)
return y, [a, b]
# 定义卷积模型
def convolutional(x, ... | zh | 0.547762 | # y=ax+b linear model # 定义卷积模型 # 全连接层 | 3.221382 | 3 |
src/sol/handle_metaplex.py | terra-dashboard/staketaxcsv | 140 | 2063 | from common.make_tx import make_swap_tx
from sol.handle_simple import handle_unknown_detect_transfers
def handle_metaplex(exporter, txinfo):
transfers_in, transfers_out, _ = txinfo.transfers_net
if len(transfers_in) == 1 and len(transfers_out) == 1:
sent_amount, sent_currency, _, _ = transfers_out[0]... | from common.make_tx import make_swap_tx
from sol.handle_simple import handle_unknown_detect_transfers
def handle_metaplex(exporter, txinfo):
transfers_in, transfers_out, _ = txinfo.transfers_net
if len(transfers_in) == 1 and len(transfers_out) == 1:
sent_amount, sent_currency, _, _ = transfers_out[0]... | none | 1 | 2.162751 | 2 | |
dcor/independence.py | lemiceterieux/dcor | 0 | 2064 | """
Functions for testing independence of several distributions.
The functions in this module provide methods for testing if
the samples generated from two random vectors are independent.
"""
import numpy as np
import scipy.stats
from . import _dcor_internals, _hypothesis
from ._dcor import u_distance_correlation_sqr... | """
Functions for testing independence of several distributions.
The functions in this module provide methods for testing if
the samples generated from two random vectors are independent.
"""
import numpy as np
import scipy.stats
from . import _dcor_internals, _hypothesis
from ._dcor import u_distance_correlation_sqr... | en | 0.574207 | Functions for testing independence of several distributions. The functions in this module provide methods for testing if the samples generated from two random vectors are independent. Test of distance covariance independence. Compute the test of independence based on the distance covariance, for two random ve... | 3.591498 | 4 |
cinemasci/cis/__init__.py | cinemascience/cinemasc | 0 | 2065 | <reponame>cinemascience/cinemasc
from . import imageview
from . import cisview
from . import renderer
from . import convert
class cis:
"""Composible Image Set Class
The data structure to hold properties of a Composible Image Set.
"""
def __init__(self, filename):
""" The constructor. """
... | from . import imageview
from . import cisview
from . import renderer
from . import convert
class cis:
"""Composible Image Set Class
The data structure to hold properties of a Composible Image Set.
"""
def __init__(self, filename):
""" The constructor. """
self.fname = filenam... | en | 0.598764 | Composible Image Set Class The data structure to hold properties of a Composible Image Set. The constructor. Debug print statement for CIS properties. Returns an image given its key. Returns all images. Returns list of image names. Set parameter table using a deep copy. Add a parameter to the list of parameters for... | 2.600275 | 3 |
applications/spaghetti.py | fos/fos-legacy | 2 | 2066 | <gh_stars>1-10
import numpy as np
import nibabel as nib
import os.path as op
import pyglet
#pyglet.options['debug_gl'] = True
#pyglet.options['debug_x11'] = True
#pyglet.options['debug_gl_trace'] = True
#pyglet.options['debug_texture'] = True
#fos modules
from fos.actor.axes import Axes
from fos import World, Window,... | import numpy as np
import nibabel as nib
import os.path as op
import pyglet
#pyglet.options['debug_gl'] = True
#pyglet.options['debug_x11'] = True
#pyglet.options['debug_gl_trace'] = True
#pyglet.options['debug_texture'] = True
#fos modules
from fos.actor.axes import Axes
from fos import World, Window, WindowManager
... | en | 0.51047 | #pyglet.options['debug_gl'] = True #pyglet.options['debug_x11'] = True #pyglet.options['debug_gl_trace'] = True #pyglet.options['debug_texture'] = True #fos modules #dipy modules #load T1 volume registered in MNI space #load the tracks registered in MNI space #load initial QuickBundles with threshold 30mm #qb=QuickBund... | 1.730498 | 2 |
faceai/gender.py | dlzdy/faceai | 1 | 2067 | #coding=utf-8
#性别识别
import cv2
from keras.models import load_model
import numpy as np
import chineseText
img = cv2.imread("img/gather.png")
face_classifier = cv2.CascadeClassifier(
"d:\Python36\Lib\site-packages\opencv-master\data\haarcascades\haarcascade_frontalface_default.xml"
)
gray = cv2.cvtColor(img, cv2.CO... | #coding=utf-8
#性别识别
import cv2
from keras.models import load_model
import numpy as np
import chineseText
img = cv2.imread("img/gather.png")
face_classifier = cv2.CascadeClassifier(
"d:\Python36\Lib\site-packages\opencv-master\data\haarcascades\haarcascade_frontalface_default.xml"
)
gray = cv2.cvtColor(img, cv2.CO... | en | 0.284837 | #coding=utf-8 #性别识别 | 3.158103 | 3 |
csm_web/scheduler/tests/utils.py | mudit2103/csm_web | 0 | 2068 | from django.test import TestCase
from os import path
from rest_framework import status
from rest_framework.test import APIClient
import random
from scheduler.models import Profile
from scheduler.factories import (
CourseFactory,
SpacetimeFactory,
UserFactory,
ProfileFactory,
SectionFactory,
Att... | from django.test import TestCase
from os import path
from rest_framework import status
from rest_framework.test import APIClient
import random
from scheduler.models import Profile
from scheduler.factories import (
CourseFactory,
SpacetimeFactory,
UserFactory,
ProfileFactory,
SectionFactory,
Att... | en | 0.825415 | # ----- REQUEST UTILITIES ----- Returns an APIClient object that is logged in as the provided user. Performs a request to the specified endpoint and returns the response object. Also checks if the status code of the response is exp_code, if provided. The method parameter should be a get/post/etc from an... | 2.21058 | 2 |
coldtype/beziers.py | tallpauley/coldtype | 0 | 2069 | import math
from fontTools.pens.recordingPen import RecordingPen, replayRecording
from fontTools.misc.bezierTools import calcCubicArcLength, splitCubicAtT
from coldtype.geometry import Rect, Point
def raise_quadratic(start, a, b):
c0 = start
c1 = (c0[0] + (2/3)*(a[0] - c0[0]), c0[1] + (2/3)*(a[1] - c0[1]))
... | import math
from fontTools.pens.recordingPen import RecordingPen, replayRecording
from fontTools.misc.bezierTools import calcCubicArcLength, splitCubicAtT
from coldtype.geometry import Rect, Point
def raise_quadratic(start, a, b):
c0 = start
c1 = (c0[0] + (2/3)*(a[0] - c0[0]), c0[1] + (2/3)*(a[1] - c0[1]))
... | en | 0.484857 | #return calcCubicArcLength(a, b, c, d) # todo # TODO | 2.52135 | 3 |
p1_navigation/train.py | nick0lay/deep-reinforcement-learning | 0 | 2070 | """
Project for Udacity Danaodgree in Deep Reinforcement Learning
This script train an agent to navigate (and collect bananas!) in a large, square world.
A reward of +1 is provided for collecting a yellow banana, and a reward of -1 is provided for collecting a blue banana. Thus, the goal of your agent is to collect a... | """
Project for Udacity Danaodgree in Deep Reinforcement Learning
This script train an agent to navigate (and collect bananas!) in a large, square world.
A reward of +1 is provided for collecting a yellow banana, and a reward of -1 is provided for collecting a blue banana. Thus, the goal of your agent is to collect a... | en | 0.811448 | Project for Udacity Danaodgree in Deep Reinforcement Learning This script train an agent to navigate (and collect bananas!) in a large, square world. A reward of +1 is provided for collecting a yellow banana, and a reward of -1 is provided for collecting a blue banana. Thus, the goal of your agent is to collect as ma... | 4.075684 | 4 |
models/model_factory.py | jac99/Egonn | 9 | 2071 | # Warsaw University of Technology
from layers.eca_block import ECABasicBlock
from models.minkgl import MinkHead, MinkTrunk, MinkGL
from models.minkloc import MinkLoc
from third_party.minkloc3d.minkloc import MinkLoc3D
from misc.utils import ModelParams
def model_factory(model_params: ModelParams):
in_channels ... | # Warsaw University of Technology
from layers.eca_block import ECABasicBlock
from models.minkgl import MinkHead, MinkTrunk, MinkGL
from models.minkloc import MinkLoc
from third_party.minkloc3d.minkloc import MinkLoc3D
from misc.utils import ModelParams
def model_factory(model_params: ModelParams):
in_channels ... | en | 0.761183 | # Warsaw University of Technology # THIS IS OUR BEST MODEL # Planes list number of channels for level 1 and above | 2.269104 | 2 |
mdns/Phidget22Python/Phidget22/Phidget.py | rabarar/phidget_docker | 0 | 2072 | import sys
import ctypes
from Phidget22.PhidgetSupport import PhidgetSupport
from Phidget22.Async import *
from Phidget22.ChannelClass import ChannelClass
from Phidget22.ChannelSubclass import ChannelSubclass
from Phidget22.DeviceClass import DeviceClass
from Phidget22.DeviceID import DeviceID
from Phidget22.ErrorEvent... | import sys
import ctypes
from Phidget22.PhidgetSupport import PhidgetSupport
from Phidget22.Async import *
from Phidget22.ChannelClass import ChannelClass
from Phidget22.ChannelSubclass import ChannelSubclass
from Phidget22.DeviceClass import DeviceClass
from Phidget22.DeviceID import DeviceID
from Phidget22.ErrorEvent... | none | 1 | 2.019642 | 2 | |
openprocurement/auctions/geb/tests/blanks/create.py | oleksiyVeretiuk/openprocurement.auctions.geb | 0 | 2073 | def create_auction(self):
expected_http_status = '201 Created'
request_data = {"data": self.auction}
entrypoint = '/auctions'
response = self.app.post_json(entrypoint, request_data)
self.assertEqual(response.status, expected_http_status)
def create_auction_check_minNumberOfQualifiedBids(self):
... | def create_auction(self):
expected_http_status = '201 Created'
request_data = {"data": self.auction}
entrypoint = '/auctions'
response = self.app.post_json(entrypoint, request_data)
self.assertEqual(response.status, expected_http_status)
def create_auction_check_minNumberOfQualifiedBids(self):
... | none | 1 | 2.639099 | 3 | |
tests/integration/test_celery.py | crossscreenmedia/scout_apm_python | 0 | 2074 | # coding=utf-8
from __future__ import absolute_import, division, print_function, unicode_literals
from contextlib import contextmanager
import celery
import pytest
from celery.signals import setup_logging
import scout_apm.celery
from scout_apm.api import Config
# http://docs.celeryproject.org/en/latest/userguide/te... | # coding=utf-8
from __future__ import absolute_import, division, print_function, unicode_literals
from contextlib import contextmanager
import celery
import pytest
from celery.signals import setup_logging
import scout_apm.celery
from scout_apm.api import Config
# http://docs.celeryproject.org/en/latest/userguide/te... | en | 0.814039 | # coding=utf-8 # http://docs.celeryproject.org/en/latest/userguide/testing.html#py-test # Just by connecting to this signal, we prevent Celery from setting up # logging - and stop it from interfering with global state # http://docs.celeryproject.org/en/v4.3.0/userguide/signals.html#setup-logging Context manager that co... | 1.804115 | 2 |
molly/apps/places/migrations/0001_initial.py | mollyproject/mollyproject | 7 | 2075 | <gh_stars>1-10
# encoding: utf-8
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'Source'
db.create_table('places_source', (
('id', self.gf('django.db.mo... | # encoding: utf-8
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'Source'
db.create_table('places_source', (
('id', self.gf('django.db.models.fields.Aut... | en | 0.638159 | # encoding: utf-8 # Adding model 'Source' # Adding model 'EntityType' # Adding M2M table for field subtype_of on 'EntityType' # Adding M2M table for field subtype_of_completion on 'EntityType' # Adding model 'Identifier' # Adding model 'Entity' # Adding M2M table for field all_types on 'Entity' # Adding M2M table for f... | 2.04634 | 2 |
sdk/python/pulumi_azure_native/servicebus/v20210601preview/get_subscription.py | polivbr/pulumi-azure-native | 0 | 2076 | # coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from ... import _utilities
fro... | # coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from ... import _utilities
fro... | en | 0.797219 | # coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** Description of subscription resource. Last time there was a receive request to this subscription. ISO 8061 timeSpan idle interval after which the topic ... | 1.588406 | 2 |
py_cfeve/module/CFAF240400E0-030TN-A1.py | crystalfontz/CFA-EVE-Python-Library | 1 | 2077 | <reponame>crystalfontz/CFA-EVE-Python-Library<gh_stars>1-10
#===========================================================================
#
# Crystalfontz Raspberry-Pi Python example library for FTDI / BridgeTek
# EVE graphic accelerators.
#
#-------------------------------------------------------------------------... | #===========================================================================
#
# Crystalfontz Raspberry-Pi Python example library for FTDI / BridgeTek
# EVE graphic accelerators.
#
#---------------------------------------------------------------------------
#
# This file is part of the port/adaptation of existin... | en | 0.721651 | #=========================================================================== # # Crystalfontz Raspberry-Pi Python example library for FTDI / BridgeTek # EVE graphic accelerators. # #--------------------------------------------------------------------------- # # This file is part of the port/adaptation of existing C bas... | 2.042259 | 2 |
quapy/model_selection.py | OneToolsCollection/HLT-ISTI-QuaPy | 0 | 2078 | import itertools
import signal
from copy import deepcopy
from typing import Union, Callable
import numpy as np
import quapy as qp
from quapy.data.base import LabelledCollection
from quapy.evaluation import artificial_prevalence_prediction, natural_prevalence_prediction, gen_prevalence_prediction
from quapy.method.agg... | import itertools
import signal
from copy import deepcopy
from typing import Union, Callable
import numpy as np
import quapy as qp
from quapy.data.base import LabelledCollection
from quapy.evaluation import artificial_prevalence_prediction, natural_prevalence_prediction, gen_prevalence_prediction
from quapy.method.agg... | en | 0.73558 | Grid Search optimization targeting a quantification-oriented metric. Optimizes the hyperparameters of a quantification method, based on an evaluation method and on an evaluation protocol for quantification. :param model: the quantifier to optimize :type model: BaseQuantifier :param param_grid: a d... | 2.198367 | 2 |
flasky.py | ZxShane/slam_hospital | 0 | 2079 | # -*- coding: utf-8 -*-
import os
from flask_migrate import Migrate
from app import create_app, db
from app.models import User, Role, PoseToLocation
app = create_app(os.getenv('FLASK_CONFIG') or 'default')
migrate = Migrate(app, db)
# migrate 的新建 我们需要扫描到这些文件我们才能创建
@app.shell_context_processor
def make_shell_conte... | # -*- coding: utf-8 -*-
import os
from flask_migrate import Migrate
from app import create_app, db
from app.models import User, Role, PoseToLocation
app = create_app(os.getenv('FLASK_CONFIG') or 'default')
migrate = Migrate(app, db)
# migrate 的新建 我们需要扫描到这些文件我们才能创建
@app.shell_context_processor
def make_shell_conte... | zh | 0.907016 | # -*- coding: utf-8 -*- # migrate 的新建 我们需要扫描到这些文件我们才能创建 # 单元测试 run the unit tests | 2.458222 | 2 |
python/day09/smoke_basin.py | aesdeef/advent-of-code-2021 | 2 | 2080 | INPUT_FILE = "../../input/09.txt"
Point = tuple[int, int]
Heightmap = dict[Point, int]
Basin = set[Point]
def parse_input() -> Heightmap:
"""
Parses the input and returns a Heightmap
"""
with open(INPUT_FILE) as f:
heights = [[int(x) for x in line.strip()] for line in f]
heightmap: Heigh... | INPUT_FILE = "../../input/09.txt"
Point = tuple[int, int]
Heightmap = dict[Point, int]
Basin = set[Point]
def parse_input() -> Heightmap:
"""
Parses the input and returns a Heightmap
"""
with open(INPUT_FILE) as f:
heights = [[int(x) for x in line.strip()] for line in f]
heightmap: Heigh... | en | 0.781705 | Parses the input and returns a Heightmap Returns a set of surrounding points within the heightmap Returns the heights of points surrounding the given point Finds the low points on the heightmap Calculates the sum of the risk levels of all low points Finds all basins on the heightmap Calculates the product of the sizes ... | 4.074861 | 4 |
playground.py | NHGmaniac/voctoconfig | 0 | 2081 | <filename>playground.py
#!/usr/bin/env python3
import signal
import logging
import sys
from gi.repository import GObject
GObject.threads_init()
import time
from lib.args import Args
from lib.loghandler import LogHandler
import lib.connection as Connection
def testCallback(args):
log = logging.getLogger("Test... | <filename>playground.py
#!/usr/bin/env python3
import signal
import logging
import sys
from gi.repository import GObject
GObject.threads_init()
import time
from lib.args import Args
from lib.loghandler import LogHandler
import lib.connection as Connection
def testCallback(args):
log = logging.getLogger("Test... | fr | 0.221828 | #!/usr/bin/env python3 | 2.458584 | 2 |
tianshou/utils/logger/tensorboard.py | Aceticia/tianshou | 4,714 | 2082 | <reponame>Aceticia/tianshou<filename>tianshou/utils/logger/tensorboard.py
import warnings
from typing import Any, Callable, Optional, Tuple
from tensorboard.backend.event_processing import event_accumulator
from torch.utils.tensorboard import SummaryWriter
from tianshou.utils.logger.base import LOG_DATA_TYPE, BaseLog... | import warnings
from typing import Any, Callable, Optional, Tuple
from tensorboard.backend.event_processing import event_accumulator
from torch.utils.tensorboard import SummaryWriter
from tianshou.utils.logger.base import LOG_DATA_TYPE, BaseLogger
class TensorboardLogger(BaseLogger):
"""A logger that relies on ... | en | 0.664454 | A logger that relies on tensorboard SummaryWriter by default to visualize \ and log statistics. :param SummaryWriter writer: the writer to log data. :param int train_interval: the log interval in log_train_data(). Default to 1000. :param int test_interval: the log interval in log_test_data(). Default t... | 2.221092 | 2 |
PythonAPI/pythonwrappers/jetfuel/gui/menu.py | InsightGit/JetfuelGameEngine | 4 | 2083 | # Jetfuel Game Engine- A SDL-based 2D game-engine
# Copyright (C) 2018 InfernoStudios
#
# 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... | # Jetfuel Game Engine- A SDL-based 2D game-engine
# Copyright (C) 2018 InfernoStudios
#
# 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... | en | 0.847705 | # Jetfuel Game Engine- A SDL-based 2D game-engine # Copyright (C) 2018 InfernoStudios # # 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.... | 2.67404 | 3 |
latent_programmer/decomposition_transformer_attention/train.py | ParikhKadam/google-research | 2 | 2084 | # coding=utf-8
# Copyright 2021 The Google Research Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicab... | # coding=utf-8
# Copyright 2021 The Google Research Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicab... | en | 0.746666 | # coding=utf-8 # Copyright 2021 The Google Research Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicab... | 1.525153 | 2 |
plot/profile_interpolation/plot_profile.py | ziyixi/SeisScripts | 0 | 2085 | import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import click
import numba
def prepare_data(data_pd, parameter):
lon_set = set(data_pd["lon"])
lat_set = set(data_pd["lat"])
dep_set = set(data_pd["dep"])
lon_list = sorted(lon_set)
lat_list = sorted(lat_set)
dep_list = sor... | import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import click
import numba
def prepare_data(data_pd, parameter):
lon_set = set(data_pd["lon"])
lat_set = set(data_pd["lat"])
dep_set = set(data_pd["dep"])
lon_list = sorted(lon_set)
lat_list = sorted(lat_set)
dep_list = sor... | en | 0.351423 | # def get_value_func(x_mesh, y_mesh, z_mesh, value_mesh): # value_func = RegularGridInterpolator( # (x_mesh, y_mesh, z_mesh), value_mesh, method="nearest") # return value_func # data_pd is too big # print(lats_plot[ih], lons_plot[ih], deps_plot[iv], values[ih, iv]) # plotting part # get vmin and vmax | 2.69747 | 3 |
tests/test_heroku.py | edpaget/flask-appconfig | 61 | 2086 | from flask import Flask
from flask_appconfig import HerokuConfig
def create_sample_app():
app = Flask('testapp')
HerokuConfig(app)
return app
def test_herokupostgres(monkeypatch):
monkeypatch.setenv('HEROKU_POSTGRESQL_ORANGE_URL', 'heroku-db-uri')
app = create_sample_app()
assert app.config... | from flask import Flask
from flask_appconfig import HerokuConfig
def create_sample_app():
app = Flask('testapp')
HerokuConfig(app)
return app
def test_herokupostgres(monkeypatch):
monkeypatch.setenv('HEROKU_POSTGRESQL_ORANGE_URL', 'heroku-db-uri')
app = create_sample_app()
assert app.config... | none | 1 | 2.436383 | 2 | |
flask/util/logger.py | Dev-Jahn/cms | 0 | 2087 | import logging
"""
Formatter
"""
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s', datefmt='%Y-%m-%d:%H:%M:%S')
"""
Set Flask logger
"""
logger = logging.getLogger('FLASK_LOG')
logger.setLevel(logging.DEBUG)
stream_log = logging.StreamHandler()
stream_log.setFormatter(form... | import logging
"""
Formatter
"""
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s', datefmt='%Y-%m-%d:%H:%M:%S')
"""
Set Flask logger
"""
logger = logging.getLogger('FLASK_LOG')
logger.setLevel(logging.DEBUG)
stream_log = logging.StreamHandler()
stream_log.setFormatter(form... | en | 0.416923 | Formatter Set Flask logger # if disabled # logger.disabled = True | 2.649494 | 3 |
utils/backups/backup_psql.py | Krovatkin/NewsBlur | 0 | 2088 | #!/usr/bin/python3
import os
import sys
import socket
CURRENT_DIR = os.path.dirname(__file__)
NEWSBLUR_DIR = ''.join([CURRENT_DIR, '/../../'])
sys.path.insert(0, NEWSBLUR_DIR)
os.environ['DJANGO_SETTINGS_MODULE'] = 'newsblur_web.settings'
import threading
class ProgressPercentage(object):
def __init__(self, fil... | #!/usr/bin/python3
import os
import sys
import socket
CURRENT_DIR = os.path.dirname(__file__)
NEWSBLUR_DIR = ''.join([CURRENT_DIR, '/../../'])
sys.path.insert(0, NEWSBLUR_DIR)
os.environ['DJANGO_SETTINGS_MODULE'] = 'newsblur_web.settings'
import threading
class ProgressPercentage(object):
def __init__(self, fil... | en | 0.819074 | #!/usr/bin/python3 # To simplify, assume this is hooked up to a single filename | 1.866291 | 2 |
onap_tests/scenario/solution.py | Orange-OpenSource/xtesting-onap-tests | 0 | 2089 | <reponame>Orange-OpenSource/xtesting-onap-tests<filename>onap_tests/scenario/solution.py
#!/usr/bin/python
#
# This program and the accompanying materials
# are made available under the terms of the Apache License, Version 2.0
# which accompanies this distribution, and is available at
#
# http://www.apache.org/li... | #!/usr/bin/python
#
# This program and the accompanying materials
# are made available under the terms of the Apache License, Version 2.0
# which accompanies this distribution, and is available at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# pylint: disable=missing-docstring
# pylint: disable=duplicate-c... | en | 0.644268 | #!/usr/bin/python # # This program and the accompanying materials # are made available under the terms of the Apache License, Version 2.0 # which accompanies this distribution, and is available at # # http://www.apache.org/licenses/LICENSE-2.0 # # pylint: disable=missing-docstring # pylint: disable=duplicate-code VNF: ... | 2.02509 | 2 |
tutorials/Controls4Docs/ControlEventsGraph.py | dominic-dev/pyformsd | 0 | 2090 | <gh_stars>0
#!/usr/bin/python
# -*- coding: utf-8 -*-
__author__ = "<NAME>"
__credits__ = ["<NAME>"]
__license__ = "MIT"
__version__ = "0.0"
__maintainer__ = "<NAME>"
__email__ = "<EMAIL>"
__status__ = "Development"
from __init__ import *
import random, time
from PyQt4 import QtCore
cla... | #!/usr/bin/python
# -*- coding: utf-8 -*-
__author__ = "<NAME>"
__credits__ = ["<NAME>"]
__license__ = "MIT"
__version__ = "0.0"
__maintainer__ = "<NAME>"
__email__ = "<EMAIL>"
__status__ = "Development"
from __init__ import *
import random, time
from PyQt4 import QtCore
class SimpleExa... | de | 0.66249 | #!/usr/bin/python # -*- coding: utf-8 -*- #Definition of the forms fields #self._control0.add_event( random.randint(0, 10000), s+o, track=random.randint(0,self.N_TRACKS), color="#00FFDD") ################################################################################################################## #################... | 2.440921 | 2 |
annotation_gui_gcp/orthophoto_view.py | lioncorpo/sfm.lion-judge-corporation | 1 | 2091 | from typing import Tuple
import numpy as np
import rasterio.warp
from opensfm import features
from .orthophoto_manager import OrthoPhotoManager
from .view import View
class OrthoPhotoView(View):
def __init__(
self,
main_ui,
path: str,
init_lat: float,
init_lon: float,
... | from typing import Tuple
import numpy as np
import rasterio.warp
from opensfm import features
from .orthophoto_manager import OrthoPhotoManager
from .view import View
class OrthoPhotoView(View):
def __init__(
self,
main_ui,
path: str,
init_lat: float,
init_lon: float,
... | en | 0.751818 | [summary] Args: main_ui (GUI.Gui) path (str): path containing geotiffs # TODO add widget for zoom level From pixels (in the viewing window) to latlon # Pixel to whatever crs the image is in # pyre-fixme[16]: `OrthoPhotoView` has no attribute `geot`. # And then to WSG84 (lat/lon) Transfo... | 2.399986 | 2 |
tempest/tests/lib/services/compute/test_security_group_default_rules_client.py | mail2nsrajesh/tempest | 254 | 2092 | <reponame>mail2nsrajesh/tempest<filename>tempest/tests/lib/services/compute/test_security_group_default_rules_client.py
# Copyright 2015 NEC Corporation. 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... | # Copyright 2015 NEC Corporation. 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 ... | en | 0.861741 | # Copyright 2015 NEC Corporation. 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 ... | 1.804389 | 2 |
main.py | Light-Lens/PassGen | 3 | 2093 | <filename>main.py
# PassGen
# These imports will be used for this project.
from colorama import Fore, Style
from colorama import init
import datetime
import string
import random
import sys
import os
# Initilaze File organizer.
os.system('title PassGen')
init(autoreset = True)
# Create Log Functions.
cl... | <filename>main.py
# PassGen
# These imports will be used for this project.
from colorama import Fore, Style
from colorama import init
import datetime
import string
import random
import sys
import os
# Initilaze File organizer.
os.system('title PassGen')
init(autoreset = True)
# Create Log Functions.
cl... | en | 0.85227 | # PassGen # These imports will be used for this project. # Initilaze File organizer. # Create Log Functions. # This will Generate a Strong Password for the User! # Create an Empty List. # Split the List of these String Operations, and Join them to JoinChars List. # Shuffle the List. # Get the random passoword. # Code L... | 2.961289 | 3 |
memos/memos/models/Memo.py | iotexpert/docmgr | 0 | 2094 | """
The model file for a Memo
"""
import re
import os
import shutil
import json
from datetime import datetime
from flask import current_app
from memos import db
from memos.models.User import User
from memos.models.MemoState import MemoState
from memos.models.MemoFile import MemoFile
from memos.models.MemoSignature i... | """
The model file for a Memo
"""
import re
import os
import shutil
import json
from datetime import datetime
from flask import current_app
from memos import db
from memos.models.User import User
from memos.models.MemoState import MemoState
from memos.models.MemoFile import MemoFile
from memos.models.MemoSignature i... | en | 0.638867 | The model file for a Memo This class is the single interface to a "memo" and all of the "memos" # Memo Number # A,B,..Z,AA,AB,...AZ,BA # if true only author, signer, distribution can read # user names on the distribution # any keyword # The title of the memo # The number of files attached to the memo # The last time an... | 2.675262 | 3 |
course_catalog/etl/conftest.py | mitodl/open-discussions | 12 | 2095 | <filename>course_catalog/etl/conftest.py
"""Common ETL test fixtures"""
import json
import pytest
@pytest.fixture(autouse=True)
def mitx_settings(settings):
"""Test settings for MITx import"""
settings.EDX_API_CLIENT_ID = "fake-client-id"
settings.EDX_API_CLIENT_SECRET = "fake-client-secret"
settings... | <filename>course_catalog/etl/conftest.py
"""Common ETL test fixtures"""
import json
import pytest
@pytest.fixture(autouse=True)
def mitx_settings(settings):
"""Test settings for MITx import"""
settings.EDX_API_CLIENT_ID = "fake-client-id"
settings.EDX_API_CLIENT_SECRET = "fake-client-secret"
settings... | en | 0.47804 | Common ETL test fixtures Test settings for MITx import Test settings for MITx import Catalog data fixture Catalog data fixture | 2.049935 | 2 |
juliaset/juliaset.py | PageotD/juliaset | 0 | 2096 | import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import random
class JuliaSet:
def __init__(self):
"""
Constructor of the JuliaSet class
:param size: size in pixels (for both width and height)
:param dpi: dots per inch (default 300)
"""
... | import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import random
class JuliaSet:
def __init__(self):
"""
Constructor of the JuliaSet class
:param size: size in pixels (for both width and height)
:param dpi: dots per inch (default 300)
"""
... | en | 0.696267 | Constructor of the JuliaSet class :param size: size in pixels (for both width and height) :param dpi: dots per inch (default 300) # Initialize image related parameters # Initialize process related parameters Get parameters from input dictionary and set attributes. :param kwargs: a dictionary i... | 3.15794 | 3 |
eye_detection.py | ShivanS93/VAtest_withOKN | 0 | 2097 | <reponame>ShivanS93/VAtest_withOKN
#!python3
# eye_detection.py - detect eyes using webcam
# tutorial: https://www.roytuts.com/real-time-eye-detection-in-webcam-using-python-3/
import cv2
import math
import numpy as np
def main():
faceCascade = cv2.CascadeClassifier("haarcascade_frontalface_alt.xml")
eyeCas... | #!python3
# eye_detection.py - detect eyes using webcam
# tutorial: https://www.roytuts.com/real-time-eye-detection-in-webcam-using-python-3/
import cv2
import math
import numpy as np
def main():
faceCascade = cv2.CascadeClassifier("haarcascade_frontalface_alt.xml")
eyeCascade = cv2.CascadeClassifier("haarc... | en | 0.559393 | #!python3 # eye_detection.py - detect eyes using webcam # tutorial: https://www.roytuts.com/real-time-eye-detection-in-webcam-using-python-3/ # grab the reference to the webcam # try: | 3.550297 | 4 |
scripts/make_gene_table.py | lmdu/bioinfo | 0 | 2098 | <gh_stars>0
#!/usr/bin/env python
descripts = {}
with open('macaca_genes.txt') as fh:
fh.readline()
for line in fh:
cols = line.strip('\n').split('\t')
if cols[1]:
descripts[cols[0]] = cols[1].split('[')[0].strip()
else:
descripts[cols[0]] = cols[1]
with open('gene_info.txt') as fh:
for line in fh:
... | #!/usr/bin/env python
descripts = {}
with open('macaca_genes.txt') as fh:
fh.readline()
for line in fh:
cols = line.strip('\n').split('\t')
if cols[1]:
descripts[cols[0]] = cols[1].split('[')[0].strip()
else:
descripts[cols[0]] = cols[1]
with open('gene_info.txt') as fh:
for line in fh:
cols = line.... | ru | 0.26433 | #!/usr/bin/env python | 3.136748 | 3 |
{{cookiecutter.repo_name}}/src/mix_with_scaper.py | nussl/cookiecutter | 0 | 2099 | <filename>{{cookiecutter.repo_name}}/src/mix_with_scaper.py
import gin
from scaper import Scaper, generate_from_jams
import copy
import logging
import p_tqdm
import nussl
import os
import numpy as np
def _reset_event_spec(sc):
sc.reset_fg_event_spec()
sc.reset_bg_event_spec()
def check_mixture(path_to_mix):
... | <filename>{{cookiecutter.repo_name}}/src/mix_with_scaper.py
import gin
from scaper import Scaper, generate_from_jams
import copy
import logging
import p_tqdm
import nussl
import os
import numpy as np
def _reset_event_spec(sc):
sc.reset_fg_event_spec()
sc.reset_bg_event_spec()
def check_mixture(path_to_mix):
... | en | 0.870382 | Creates a single mixture, incoherent. Instantiates according to the event parameters for each source. # do one by itself for testing # now do the rest in parallel | 2.056435 | 2 |