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 |
|---|---|---|---|---|---|---|---|---|---|---|
etools/apps/pcs/tests.py | Igelinmist/etools | 0 | 6632651 | from datetime import date, datetime, timedelta, time
from django.test import TestCase
from pcs.models.extern_data_models import Param, load_params
from pcs.utils import AddrCoder
class ParamTestCase(TestCase):
def setUp(self):
load_params()
def test_getting_params(self):
""" test params loa... | from datetime import date, datetime, timedelta, time
from django.test import TestCase
from pcs.models.extern_data_models import Param, load_params
from pcs.utils import AddrCoder
class ParamTestCase(TestCase):
def setUp(self):
load_params()
def test_getting_params(self):
""" test params loa... | en | 0.683639 | test params load from external db test getting historical data test getting hours slices | 2.441584 | 2 |
Code/DataManager.py | chaturanand/Voice-based-gender-recognition | 0 | 6632652 | <filename>Code/DataManager.py<gh_stars>0
import os
import sys
import math
import tarfile
class DataManager:
def __init__(self, dataset_path):
self.dataset_path = dataset_path
def extract_dataset(self, compressed_dataset_file_name, dataset_directory):
try:
# extract fil... | <filename>Code/DataManager.py<gh_stars>0
import os
import sys
import math
import tarfile
class DataManager:
def __init__(self, dataset_path):
self.dataset_path = dataset_path
def extract_dataset(self, compressed_dataset_file_name, dataset_directory):
try:
# extract fil... | en | 0.789829 | # extract files to dataset folder # read config file and get path to compressed dataset # create a folder for the data # extract dataset # select females files and males files # fill in dictionary # divide and group file names # make training and testing folders # move files | 2.721071 | 3 |
mongomantic/__init__.py | techie-gg/Mongomantic | 18 | 6632653 | <filename>mongomantic/__init__.py
# type: ignore[attr-defined]
"""A MongoDB Python ORM, built on Pydantic and PyMongo."""
try:
from importlib.metadata import PackageNotFoundError, version
except ImportError: # pragma: no cover
from importlib_metadata import PackageNotFoundError, version
try:
__version__... | <filename>mongomantic/__init__.py
# type: ignore[attr-defined]
"""A MongoDB Python ORM, built on Pydantic and PyMongo."""
try:
from importlib.metadata import PackageNotFoundError, version
except ImportError: # pragma: no cover
from importlib_metadata import PackageNotFoundError, version
try:
__version__... | en | 0.59342 | # type: ignore[attr-defined] A MongoDB Python ORM, built on Pydantic and PyMongo. # pragma: no cover # pragma: no cover | 1.977393 | 2 |
src/models/model.py | rudyn2/tsad_v2 | 0 | 6632654 | import torch
import torch.nn as nn
from torch.distributions import Normal
from torch.distributions.transformed_distribution import TransformedDistribution
# from torch.distributions.transforms import TanhTransform
from src.utils.eps_scheduler import Epsilon
from src.utils.transforms import TanhTransform
class FullyCon... | import torch
import torch.nn as nn
from torch.distributions import Normal
from torch.distributions.transformed_distribution import TransformedDistribution
# from torch.distributions.transforms import TanhTransform
from src.utils.eps_scheduler import Epsilon
from src.utils.transforms import TanhTransform
class FullyCon... | en | 0.444185 | # from torch.distributions.transforms import TanhTransform # inverse indices array # reorder output as input # deterministic parameter just for compatibility # deterministic parameter just for compatibility # inverse indices array # reorder output as input | 2.179119 | 2 |
pyalgorithm/search/linear_search.py | AjithPanneerselvam/algo | 2 | 6632655 | <reponame>AjithPanneerselvam/algo
""" Linear search
Time complexity - O(n)
"""
def linear_search(ls, val):
for i in range(len(ls)):
if ls[i] == val:
# Found! Returns the index
return i + 1
# Not found
return None
| """ Linear search
Time complexity - O(n)
"""
def linear_search(ls, val):
for i in range(len(ls)):
if ls[i] == val:
# Found! Returns the index
return i + 1
# Not found
return None | en | 0.641422 | Linear search
Time complexity - O(n) # Found! Returns the index # Not found | 3.743306 | 4 |
src/careers.py | nilund93/whfrp_generator | 0 | 6632656 | # careers
human_careers={
1:"apothecary",
2:"engineer",
3:"lawyer",
4:"nun",
5:"nun",
6:"physician",
7:"priest",
8:"priest",
9:"priest",
10:"priest",
... | # careers
human_careers={
1:"apothecary",
2:"engineer",
3:"lawyer",
4:"nun",
5:"nun",
6:"physician",
7:"priest",
8:"priest",
9:"priest",
10:"priest",
... | en | 0.745232 | # careers # class # names | 1.709999 | 2 |
src/main/python/apache/thermos/observer/http/static_assets.py | wickman/incubator-aurora | 1 | 6632657 | #
# Copyright 2013 Apache Software Foundation
#
# 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 agree... | #
# Copyright 2013 Apache Software Foundation
#
# 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 agree... | en | 0.83126 | # # Copyright 2013 Apache Software Foundation # # 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 agree... | 2.009618 | 2 |
Course02/Week3/12.5. Returning a value from a function.py | skunkworksdev/Python_Programming_Michigan | 0 | 6632658 | """
12.5. Returning a value from a function
"""
# Not only can you pass a parameter value into a function, a function can also
# produce a value. You have already seen this in some previous functions that
# you have used. For example, len takes a list or string as a parameter value
# and returns a number, the length o... | """
12.5. Returning a value from a function
"""
# Not only can you pass a parameter value into a function, a function can also
# produce a value. You have already seen this in some previous functions that
# you have used. For example, len takes a list or string as a parameter value
# and returns a number, the length o... | en | 0.89795 | 12.5. Returning a value from a function # Not only can you pass a parameter value into a function, a function can also # produce a value. You have already seen this in some previous functions that # you have used. For example, len takes a list or string as a parameter value # and returns a number, the length of that li... | 4.750952 | 5 |
metarunlog/util.py | tomsercu/metarunlog | 2 | 6632659 | <gh_stars>1-10
# Metarunlog, experiment management tool.
# Author: <NAME>
# Date: 2015-01-23
import datetime
import subprocess
def nowstring(sec=True, ms= False):
tstr = datetime.datetime.now().isoformat()
if not ms:
tstr = tstr.split('.')[0]
if not sec:
tstr = tstr.rsplit(':',1)[0]
re... | # Metarunlog, experiment management tool.
# Author: <NAME>
# Date: 2015-01-23
import datetime
import subprocess
def nowstring(sec=True, ms= False):
tstr = datetime.datetime.now().isoformat()
if not ms:
tstr = tstr.split('.')[0]
if not sec:
tstr = tstr.rsplit(':',1)[0]
return tstr
def ... | en | 0.561969 | # Metarunlog, experiment management tool. # Author: <NAME> # Date: 2015-01-23 #cmd = 'ssh -t {} "{}"'.format(sshHost, cmd) #works but messes up terminal #cmd = 'ssh {} "shopt -s huponexit; {}"'.format(sshHost, cmd) # doesnt work to kill job on exit #TODO use paramiko or pexpect see http://stackoverflow.com/questions/46... | 2.256916 | 2 |
ex03 - key phrase problem.py | neong83/algorithm_practices | 0 | 6632660 | <reponame>neong83/algorithm_practices
from typing import Dict
text = (
"Suppose we have a set of English text documents "
"and wish to rank which document is most relevant to the query, "
"the brown cow . A simple way to start out is by eliminating "
"documents that do not contain all three words the ... | from typing import Dict
text = (
"Suppose we have a set of English text documents "
"and wish to rank which document is most relevant to the query, "
"the brown cow . A simple way to start out is by eliminating "
"documents that do not contain all three words the brown, and cow, "
"but this still ... | en | 0.969815 | # first attempt # key in dict is O(1) # second attempts # this is O(n) | 4.124248 | 4 |
torch/optimization/combine_optimization.py | jihuacao/Putil | 1 | 6632661 | <filename>torch/optimization/combine_optimization.py<gh_stars>1-10
# coding=utf-8
#from torch.optim import Optimizer
import torch
class CombineOptimization:
def __init__(self, **optimizations):
self._optimizations = optimizations
pass
def step(self, closure=None):
for index, (k, v) in... | <filename>torch/optimization/combine_optimization.py<gh_stars>1-10
# coding=utf-8
#from torch.optim import Optimizer
import torch
class CombineOptimization:
def __init__(self, **optimizations):
self._optimizations = optimizations
pass
def step(self, closure=None):
for index, (k, v) in... | en | 0.377287 | # coding=utf-8 #from torch.optim import Optimizer | 2.375397 | 2 |
scripts/teamforge-import.py | rohankumardubey/allura | 113 | 6632662 | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (t... | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (t... | en | 0.737778 | # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (t... | 1.52271 | 2 |
judger.py | SkyErnest/legal_basis | 0 | 6632663 | <reponame>SkyErnest/legal_basis<filename>judger.py<gh_stars>0
from math import log
import os
import json
import numpy as np
class Judger:
# Initialize Judger, with the path of accusation list and law articles list
def __init__(self, accusation_path, law_path):
self.accu_dic = {}
f = open(accus... | from math import log
import os
import json
import numpy as np
class Judger:
# Initialize Judger, with the path of accusation list and law articles list
def __init__(self, accusation_path, law_path):
self.accu_dic = {}
f = open(accusation_path, "r",encoding='utf-8')
self.task1_cnt = 0
... | en | 0.804314 | # Initialize Judger, with the path of accusation list and law articles list # Format the result generated by the Predictor class # Gen new results according to the truth and users output # Calculate precision, recall and f1 value # According to https://github.com/dice-group/gerbil/wiki/Precision,-Recall-and-F1-measure ... | 3.010003 | 3 |
check_data_quality/cc/removern.py | genejiang2012/ETL_tools | 0 | 6632664 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
import sys
import os
import codecs
def remove_wrapping_lines(filePath, fromCode='utf_8_sig', toCode='utf-8'):
"""
将csv文件中的内容中换行符转为\n,并转换编码保存
常用编码类型:
gb18030: 中文编码
utf_8: 常用的utf8编码
utf_8_sig: utf8 with bom
"""
fr = codecs.open(filePath, 'r... | #!/usr/bin/env python
# -*- coding:utf-8 -*-
import sys
import os
import codecs
def remove_wrapping_lines(filePath, fromCode='utf_8_sig', toCode='utf-8'):
"""
将csv文件中的内容中换行符转为\n,并转换编码保存
常用编码类型:
gb18030: 中文编码
utf_8: 常用的utf8编码
utf_8_sig: utf8 with bom
"""
fr = codecs.open(filePath, 'r... | zh | 0.942556 | #!/usr/bin/env python # -*- coding:utf-8 -*- 将csv文件中的内容中换行符转为\n,并转换编码保存 常用编码类型: gb18030: 中文编码 utf_8: 常用的utf8编码 utf_8_sig: utf8 with bom # 当前行是否未结束的标记,默认False代表正常结束 # 完整行内容变量 # 读取一行 # 如果文件内容结束 # 去除前后空格和行尾换行符 # 如果上一次循环标记行未结束,则把本次循环读取行内容附加到上一行后面 # 否则正常读取本行内容 # 如果当前行尾最后一个字符是双引号,认为是正常结束,标记符设置为False,并写入文件 # 否... | 3.031715 | 3 |
fastml_engine/exception/infer_exception.py | fast-mlops/fastml-engine | 1 | 6632665 | <reponame>fast-mlops/fastml-engine
class InferException(Exception):
def __init__(self, code=500, message="", *arg):
self.args = arg
self.message = message
self.code = code
if arg:
Exception.__init__(self, code, message, arg)
else:
Exception.__init__(se... | class InferException(Exception):
def __init__(self, code=500, message="", *arg):
self.args = arg
self.message = message
self.code = code
if arg:
Exception.__init__(self, code, message, arg)
else:
Exception.__init__(self, code, message) | none | 1 | 3.066533 | 3 | |
spotify_playlist_additions/playlists/abstract.py | CoolDudde4150/Spotify-Playlist-Additions | 0 | 6632666 | """Contains the abstract interface for a playlist addon"""
from abc import ABC, abstractmethod
from typing import Any
from spotipy import Spotify
class AbstractPlaylist(ABC):
"""An abstract class that a new playlist can inherit callback functions
from. Each frame, any of these may be invoked if the required ... | """Contains the abstract interface for a playlist addon"""
from abc import ABC, abstractmethod
from typing import Any
from spotipy import Spotify
class AbstractPlaylist(ABC):
"""An abstract class that a new playlist can inherit callback functions
from. Each frame, any of these may be invoked if the required ... | en | 0.910665 | Contains the abstract interface for a playlist addon An abstract class that a new playlist can inherit callback functions from. Each frame, any of these may be invoked if the required state is found. The most basic initializer that can be implemented. Any playlist implementation needs take in a Spotify ... | 3.210902 | 3 |
setup.py | CaliDog/tachikoma | 21 | 6632667 | <filename>setup.py
from setuptools import setup, find_packages
import os
here = os.path.abspath(os.path.dirname(__file__))
with open('requirements.txt') as f:
dependencies = f.read().splitlines()
long_description = """
Tachikoma is a jobs pipeline for connecting to services, processing results, and sending notif... | <filename>setup.py
from setuptools import setup, find_packages
import os
here = os.path.abspath(os.path.dirname(__file__))
with open('requirements.txt') as f:
dependencies = f.read().splitlines()
long_description = """
Tachikoma is a jobs pipeline for connecting to services, processing results, and sending notif... | en | 0.961181 | Tachikoma is a jobs pipeline for connecting to services, processing results, and sending notifications. It handles all the magic bits like storage and diffing for you, and all you have to do is focus on the meat and potatos of what you want to do! | 1.620932 | 2 |
setup.py | rjgpinel/rlbc | 43 | 6632668 | <filename>setup.py<gh_stars>10-100
import shutil
from setuptools import setup, find_packages
from codecs import open
from os import path
here = path.abspath(path.dirname(__file__))
def read_requirements_file(filename):
req_file_path = path.join(path.dirname(path.realpath(__file__)), filename)
with open(req_... | <filename>setup.py<gh_stars>10-100
import shutil
from setuptools import setup, find_packages
from codecs import open
from os import path
here = path.abspath(path.dirname(__file__))
def read_requirements_file(filename):
req_file_path = path.join(path.dirname(path.realpath(__file__)), filename)
with open(req_... | none | 1 | 1.874821 | 2 | |
pype/plugins/maya/publish/validate_ass_relative_paths.py | kalisp/pype | 0 | 6632669 | <gh_stars>0
import os
import types
import maya.cmds as cmds
import pyblish.api
import pype.api
import pype.hosts.maya.action
class ValidateAssRelativePaths(pyblish.api.InstancePlugin):
"""Ensure exporting ass file has set relative texture paths"""
order = pype.api.ValidateContentsOrder
hosts = ['maya']... | import os
import types
import maya.cmds as cmds
import pyblish.api
import pype.api
import pype.hosts.maya.action
class ValidateAssRelativePaths(pyblish.api.InstancePlugin):
"""Ensure exporting ass file has set relative texture paths"""
order = pype.api.ValidateContentsOrder
hosts = ['maya']
familie... | en | 0.827586 | Ensure exporting ass file has set relative texture paths # we cannot ask this until user open render settings as # `defaultArnoldRenderOptions` doesn't exists # Use project root variables for multiplatform support, see: # https://docs.arnoldrenderer.com/display/A5AFMUG/Search+Path # ':' as path separator is supported b... | 2.155078 | 2 |
test/test_pypigeonhole_build/test_app_version_control.py | psilons/pypigeonhole-build | 0 | 6632670 | import unittest
import os
import shutil
import pypigeonhole_build.app_version_control as app_version_control
class FileEditorUtilsTest(unittest.TestCase):
def test_replace_line(self):
curr_path = os.path.dirname(os.path.abspath(__file__))
src_file = os.path.join(curr_path, 'sample_file_edit.txt')... | import unittest
import os
import shutil
import pypigeonhole_build.app_version_control as app_version_control
class FileEditorUtilsTest(unittest.TestCase):
def test_replace_line(self):
curr_path = os.path.dirname(os.path.abspath(__file__))
src_file = os.path.join(curr_path, 'sample_file_edit.txt')... | en | 0.687206 | # open a tmp file, save 1.2.3 in it. # bump 1.2.3 to 1.2.4 # bump 1.2.4 to 1.2.5 # bump 1.2.5 to 1.2.6 # os.remove(tmp_file) | 2.734776 | 3 |
SpaceInvaders/SpaceInvaders.py | dimikave/Space-Invaders-Game-Pygame | 0 | 6632671 | <filename>SpaceInvaders/SpaceInvaders.py
import pygame
import os
from pygame.locals import *
from random import randint
from sys import exit
def CenterMessage(screen,surface):
return (screen.get_width() - surface.get_width())/2
def PrepareSound(filename):
sound = pygame.mixer.Sound(filename)
... | <filename>SpaceInvaders/SpaceInvaders.py
import pygame
import os
from pygame.locals import *
from random import randint
from sys import exit
def CenterMessage(screen,surface):
return (screen.get_width() - surface.get_width())/2
def PrepareSound(filename):
sound = pygame.mixer.Sound(filename)
... | none | 1 | 2.743208 | 3 | |
examples/03-sign-key/sign-key.py | winterwolf32/JWT- | 0 | 6632672 | from myjwt.modify_jwt import change_payload
from myjwt.modify_jwt import signature
from myjwt.utils import jwt_to_json
from myjwt.variables import INVALID_SIGNATURE
from myjwt.variables import VALID_SIGNATURE
jwt = "<KEY>"
key = "pentesterlab"
# "header" = {"typ": "JWT", "alg": "HS256"}
# "payload" = {"userna... | from myjwt.modify_jwt import change_payload
from myjwt.modify_jwt import signature
from myjwt.utils import jwt_to_json
from myjwt.variables import INVALID_SIGNATURE
from myjwt.variables import VALID_SIGNATURE
jwt = "<KEY>"
key = "pentesterlab"
# "header" = {"typ": "JWT", "alg": "HS256"}
# "payload" = {"userna... | en | 0.509381 | # "header" = {"typ": "JWT", "alg": "HS256"} # "payload" = {"username": null} # "signature" = "Tr0VvdP6rVBGBGuI_luxGCOaz6BbhC6IxRTlKOW8UjM" # "header" = {"typ": "JWT", "alg": "HS256"} # "payload" = {"username": "admin"} # "signature" = "Tr0VvdP6rVBGBGuI_luxGCOaz6BbhC6IxRTlKOW8UjM" # verify your jwt | 2.966941 | 3 |
django_functest/tests/views.py | django-functest/django-functest | 71 | 6632673 | from __future__ import absolute_import, print_function, unicode_literals
import uuid
from django import forms
from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.utils.html import mark_safe
from .models import Thing
try:
from django.urls import reverse
except ImportError... | from __future__ import absolute_import, print_function, unicode_literals
import uuid
from django import forms
from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.utils.html import mark_safe
from .models import Thing
try:
from django.urls import reverse
except ImportError... | en | 0.920762 | # Hack to help test interacting with elements # that aren't in view. # Have separate forms so that we test different form enctype | 2.173245 | 2 |
Semester 6/DWM/page_rank.py | atharva8300/Engineering-Practical-Experiments | 7 | 6632674 | <filename>Semester 6/DWM/page_rank.py
import string
LETTERS = string.ascii_uppercase
graph = [
[0, 0, 1, 1, 1, 0, 0],
[0, 1, 0, 1, 1, 0, 1],
[0, 1, 1, 0, 0, 1, 0],
[1, 0, 0, 1, 1, 1, 0],
[1, 0, 1, 0, 0, 1, 0],
[1, 1, 0, 0, 1, 0, 1],
[1, 1, 1, 0, 1, 0, 0],
]
cl... | <filename>Semester 6/DWM/page_rank.py
import string
LETTERS = string.ascii_uppercase
graph = [
[0, 0, 1, 1, 1, 0, 0],
[0, 1, 0, 1, 1, 0, 1],
[0, 1, 1, 0, 0, 1, 0],
[1, 0, 0, 1, 1, 1, 0],
[1, 0, 1, 0, 0, 1, 0],
[1, 1, 0, 0, 1, 0, 1],
[1, 1, 1, 0, 1, 0, 0],
]
cl... | none | 1 | 3.157407 | 3 | |
rofl/config/__init__.py | Bobobert/RoLas | 2 | 6632675 | from .config import createConfig, createAgent, createPolicy, getTrainFun, getEnvMaker, createNetwork
from .experimentScrips import setUpExperiment, loadExperiment
| from .config import createConfig, createAgent, createPolicy, getTrainFun, getEnvMaker, createNetwork
from .experimentScrips import setUpExperiment, loadExperiment
| none | 1 | 1.011598 | 1 | |
fuelrat_hexchat.py | Guntereno/FuelRatHelper | 0 | 6632676 | import datetime
import hexchat
import json
import os
import sys
from tkinter import Tk
__module_name__ = "fuelrat_helper_hexchat"
__module_version__ = "1.0"
__module_description__ = "Fuel Rat Helper"
# The script folder isn't necessarily in the search path when running through HexChat
path = os.path.join(hexchat.get_... | import datetime
import hexchat
import json
import os
import sys
from tkinter import Tk
__module_name__ = "fuelrat_helper_hexchat"
__module_version__ = "1.0"
__module_description__ = "Fuel Rat Helper"
# The script folder isn't necessarily in the search path when running through HexChat
path = os.path.join(hexchat.get_... | en | 0.741862 | # The script folder isn't necessarily in the search path when running through HexChat # Dump json to the logs # Parse a case data from the message # If found, dump the data and copy system to clipboard #set_logging_enabled(True) | 2.172642 | 2 |
pandas_redshift/core.py | thcborges/pandas_redshift | 0 | 6632677 | #!/usr/bin/env python3
from io import StringIO
import pandas as pd
import traceback
import psycopg2
import boto3
import sys
import os
import re
S3_ACCEPTED_KWARGS = [
'ACL', 'Body', 'CacheControl ', 'ContentDisposition', 'ContentEncoding', 'ContentLanguage',
'ContentLength', 'ContentMD5', 'ContentType', 'Expi... | #!/usr/bin/env python3
from io import StringIO
import pandas as pd
import traceback
import psycopg2
import boto3
import sys
import os
import re
S3_ACCEPTED_KWARGS = [
'ACL', 'Body', 'CacheControl ', 'ContentDisposition', 'ContentEncoding', 'ContentLanguage',
'ContentLength', 'ContentMD5', 'ContentType', 'Expi... | en | 0.425581 | #!/usr/bin/env python3 # Available parameters for service: https://boto3.readthedocs.io/en/latest/reference/services/s3.html#S3.Client.put_object # pass a sql query and return a pandas dataframe Validate the column names to ensure no reserved words are used. Arguments: dataframe pd.data_frame -- data to va... | 2.146632 | 2 |
src/gmmtest.py | ClementLancien/machineLearning | 0 | 6632678 | <gh_stars>0
import matplotlib.pyplot as plt
import numpy as np
from matplotlib import animation
from JSAnimation import IPython_display
np.random.seed(13)
data = np.random.random(100)
plt.hist(data, bins=15, normed=True, color='black', alpha=0.5)
plt.title('Histogram of $U(0,1)$ samples')
plt.show()
def normal(x, ... | import matplotlib.pyplot as plt
import numpy as np
from matplotlib import animation
from JSAnimation import IPython_display
np.random.seed(13)
data = np.random.random(100)
plt.hist(data, bins=15, normed=True, color='black', alpha=0.5)
plt.title('Histogram of $U(0,1)$ samples')
plt.show()
def normal(x, mu, sigma):
... | en | 0.889965 | Normal distribution PDF. Fit a single GMM with EM with one random initialization. # Random initialization. # Keep track of results after each iteration. # E-step. # M-step. # Bookkeeping. Find the maximum likelihood GMM over several random initializations. # Try several random initializations and keep the best. # Remov... | 3.133467 | 3 |
speedtest-charts.py | frdmn/google-speedtest-chart | 53 | 6632679 | <reponame>frdmn/google-speedtest-chart
#!/usr/bin/env python3
import datetime
import pygsheets
import speedtest
import argparse
# Set options
parser = argparse.ArgumentParser(
description='Simple Python script to push speedtest results \
(using speedtest-cli) to a Google Docs spreadsheet'
)
parser... | #!/usr/bin/env python3
import datetime
import pygsheets
import speedtest
import argparse
# Set options
parser = argparse.ArgumentParser(
description='Simple Python script to push speedtest results \
(using speedtest-cli) to a Google Docs spreadsheet'
)
parser.add_argument(
"-w, --workbookname"... | en | 0.512417 | #!/usr/bin/env python3 # Set options # Set constants # set variable scope Function to check for valid OAuth access tokens. Function to submit speedtest result. # create header row Function to generate speedtest result. # Check for proper credentials # Run speedtest and store output # Write to spreadsheet | 2.932428 | 3 |
tools/mo/openvino/tools/mo/front/kaldi/extractors/backproptruncation_ext.py | pazamelin/openvino | 1 | 6632680 | <gh_stars>1-10
# Copyright (C) 2018-2021 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import numpy as np
from openvino.tools.mo.front.caffe.extractors.utils import embed_input
from openvino.tools.mo.front.extractor import FrontExtractorOp
from openvino.tools.mo.front.kaldi.loader.utils import read_binary_f... | # Copyright (C) 2018-2021 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import numpy as np
from openvino.tools.mo.front.caffe.extractors.utils import embed_input
from openvino.tools.mo.front.extractor import FrontExtractorOp
from openvino.tools.mo.front.kaldi.loader.utils import read_binary_float_token, rea... | en | 0.257653 | # Copyright (C) 2018-2021 Intel Corporation # SPDX-License-Identifier: Apache-2.0 # TODO add real batch here | 1.964389 | 2 |
Solutions/problem20.py | WalrusCow/euler | 0 | 6632681 | <reponame>WalrusCow/euler<filename>Solutions/problem20.py<gh_stars>0
# Project Euler Problem 20
# Created on: 2012-06-18
# Created by: <NAME>
from math import factorial
print(sum(map(int, str(factorial(100)))))
| # Project Euler Problem 20
# Created on: 2012-06-18
# Created by: <NAME>
from math import factorial
print(sum(map(int, str(factorial(100))))) | en | 0.659634 | # Project Euler Problem 20 # Created on: 2012-06-18 # Created by: <NAME> | 3.152137 | 3 |
icinga2api_py/api.py | TimL20/icinga2api_py | 0 | 6632682 | <filename>icinga2api_py/api.py
# -*- coding: utf-8 -*-
"""
Small client for easy access to the Icinga2 API using the requests library
(https://github.com/psf/requests).
This client is really dump and has not much ideas about how the Icinga2 API works.
What it does is to set up a requests.Session (which it extends), bu... | <filename>icinga2api_py/api.py
# -*- coding: utf-8 -*-
"""
Small client for easy access to the Icinga2 API using the requests library
(https://github.com/psf/requests).
This client is really dump and has not much ideas about how the Icinga2 API works.
What it does is to set up a requests.Session (which it extends), bu... | en | 0.821379 | # -*- coding: utf-8 -*- Small client for easy access to the Icinga2 API using the requests library (https://github.com/psf/requests). This client is really dump and has not much ideas about how the Icinga2 API works. What it does is to set up a requests.Session (which it extends), build URL and body, construct request... | 3.266523 | 3 |
simplemooc/courses/views.py | KelsonMaciel/simplemooc- | 0 | 6632683 | from django.shortcuts import render, get_object_or_404, redirect
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from .models import Course, Enrollment, Announcement, Lesson, Material
from .forms import ContactCourse, CommentForm
from .decorators import enrollment_required... | from django.shortcuts import render, get_object_or_404, redirect
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from .models import Course, Enrollment, Announcement, Lesson, Material
from .forms import ContactCourse, CommentForm
from .decorators import enrollment_required... | en | 0.465006 | # def details(request, pk): # course = get_object_or_404(Course, pk=pk) # context = { # 'course': course # } # template_name = 'courses/details.html' # return render(request, template_name, context) # enrollment.active() | 1.967266 | 2 |
libtrellis/3rdparty/pybind11/pybind11/__main__.py | antmicro/prjtrellis | 2 | 6632684 | # pylint: disable=missing-function-docstring
import argparse
import sys
import sysconfig
from .commands import get_cmake_dir, get_include
def print_includes() -> None:
dirs = [
sysconfig.get_path("include"),
sysconfig.get_path("platinclude"),
get_include(),
]
# Make unique but p... | # pylint: disable=missing-function-docstring
import argparse
import sys
import sysconfig
from .commands import get_cmake_dir, get_include
def print_includes() -> None:
dirs = [
sysconfig.get_path("include"),
sysconfig.get_path("platinclude"),
get_include(),
]
# Make unique but p... | en | 0.689051 | # pylint: disable=missing-function-docstring # Make unique but preserve order | 2.341991 | 2 |
previous_work/interface_functions.py | orangewaxcap/cellcounter | 0 | 6632685 | """
This file contains various functions used in the main
counting notebook.
"""
import matplotlib.pyplot as plt
import numpy as np
from skimage import exposure, feature, filters, io, morphology
from ipywidgets import widgets, interactive, fixed, interact_manual
from math import sqrt
from collections import Counter
im... | """
This file contains various functions used in the main
counting notebook.
"""
import matplotlib.pyplot as plt
import numpy as np
from skimage import exposure, feature, filters, io, morphology
from ipywidgets import widgets, interactive, fixed, interact_manual
from math import sqrt
from collections import Counter
im... | en | 0.846635 | This file contains various functions used in the main counting notebook. OLD FUNCTIONS BELOW Loads an image, strips out the desired channel, and optionally displays the image. Returns image and its filename for later use. Applies contrast stretching to an image, then uses a white top-hat filter to ... | 2.654614 | 3 |
scripts/data_processing/bckgrd_subtraction/bckgrd_subtract_batch_spline.py | fang-ren/segmentation_CoFeZr | 0 | 6632686 | # -*- coding: utf-8 -*-
"""
Created on Wed Aug 03 16:22:25 2016
@author: fangren
"""
import numpy as np
import matplotlib.pyplot as plt
from scipy.interpolate import splev, splrep
import os
import csv
def file_index(index):
if len(str(index)) == 1:
return '000' + str(index)
elif len(str(index)) == ... | # -*- coding: utf-8 -*-
"""
Created on Wed Aug 03 16:22:25 2016
@author: fangren
"""
import numpy as np
import matplotlib.pyplot as plt
from scipy.interpolate import splev, splrep
import os
import csv
def file_index(index):
if len(str(index)) == 1:
return '000' + str(index)
elif len(str(index)) == ... | en | 0.733766 | # -*- coding: utf-8 -*- Created on Wed Aug 03 16:22:25 2016 @author: fangren | 2.630889 | 3 |
pysmt/plugins.py | div72/py2many | 345 | 6632687 | <gh_stars>100-1000
import io
import os
import random
import sys
import time
from tempfile import NamedTemporaryFile
from typing import Callable, Dict, List, Tuple, Union
try:
from argparse_dataclass import dataclass as ap_dataclass
from argparse_dataclass import ArgumentParser
except:
ArgumentParser = "Ar... | import io
import os
import random
import sys
import time
from tempfile import NamedTemporaryFile
from typing import Callable, Dict, List, Tuple, Union
try:
from argparse_dataclass import dataclass as ap_dataclass
from argparse_dataclass import ArgumentParser
except:
ArgumentParser = "ArgumentParser"
a... | en | 0.872029 | # TODO # TODO # TODO # TODO # Do whatever transformation the decorator does to cls here # small one liners are inlined here as lambdas | 2.694723 | 3 |
api_study/apps/trade/models.py | shidashui/django_restful_api_study | 2 | 6632688 | import datetime
from django.contrib.auth import get_user_model
from django.db import models
# Create your models here.
from goods.models import Goods
User = get_user_model()
class ShoppingCart(models.Model):
"""
购物车
"""
user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name="用户")
... | import datetime
from django.contrib.auth import get_user_model
from django.db import models
# Create your models here.
from goods.models import Goods
User = get_user_model()
class ShoppingCart(models.Model):
"""
购物车
"""
user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name="用户")
... | zh | 0.96184 | # Create your models here. 购物车 订单信息 #订单号唯一 #微信支付会用到 #支付宝交易号 #支付状态 #订单支付类型 #用户信息 订单内的商品详情 #一个订单对应多个商品 #两个外键形成一张关联表 | 2.399927 | 2 |
tests/test_data/test_datasets/test_trackingnet_dataset.py | benxiao/mmtracking | 1 | 6632689 | # Copyright (c) OpenMMLab. All rights reserved.
import os.path as osp
import tempfile
import mmcv
import numpy as np
from mmtrack.datasets import DATASETS as DATASETS
PREFIX = osp.join(osp.dirname(__file__), '../../data')
LASOT_ANN_PATH = f'{PREFIX}/demo_sot_data/lasot'
def test_format_results():
dataset_class... | # Copyright (c) OpenMMLab. All rights reserved.
import os.path as osp
import tempfile
import mmcv
import numpy as np
from mmtrack.datasets import DATASETS as DATASETS
PREFIX = osp.join(osp.dirname(__file__), '../../data')
LASOT_ANN_PATH = f'{PREFIX}/demo_sot_data/lasot'
def test_format_results():
dataset_class... | en | 0.828799 | # Copyright (c) OpenMMLab. All rights reserved. | 2.362843 | 2 |
thrift/lib/py/util/trollius.py | fakeNetflix/facebook-repo-fbthrift | 15 | 6632690 | <gh_stars>10-100
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import trollius as asyncio
from trollius import (From, Return, )
from thrift.server.TTrolliusServer import ThriftClientProtocolFactory
from thrift.util.... | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import trollius as asyncio
from trollius import (From, Return, )
from thrift.server.TTrolliusServer import ThriftClientProtocolFactory
from thrift.util.Decorators import... | en | 0.75274 | create a Trollius thrift client and return a context manager for it This is a coroutine :param client_klass: thrift Client class :param host: hostname/ip, None = loopback :param port: port number :param loop: Trollius event loop :returns: a Context manager which provides the thrift client This i... | 2.51644 | 3 |
src/pyrad_proc/pyrad/EGG-INFO/scripts/main_process_data_birds.py | jfigui/pyrad | 41 | 6632691 | #!/home/daniel/anaconda3/bin/python
# -*- coding: utf-8 -*-
"""
================================================
Pyrad: The MeteoSwiss Radar Processing framework
================================================
Welcome to Pyrad!
This program processes bird data
"""
# Author: fvj
# License: BSD 3 clause
import dat... | #!/home/daniel/anaconda3/bin/python
# -*- coding: utf-8 -*-
"""
================================================
Pyrad: The MeteoSwiss Radar Processing framework
================================================
Welcome to Pyrad!
This program processes bird data
"""
# Author: fvj
# License: BSD 3 clause
import dat... | en | 0.300276 | #!/home/daniel/anaconda3/bin/python # -*- coding: utf-8 -*- ================================================ Pyrad: The MeteoSwiss Radar Processing framework ================================================ Welcome to Pyrad! This program processes bird data # Author: fvj # License: BSD 3 clause # parse the arguments ... | 2.43814 | 2 |
aiosnow/models/_schema/schema.py | michaeldcanady/aiosnow | 38 | 6632692 | <reponame>michaeldcanady/aiosnow<gh_stars>10-100
from typing import Any, Dict, Iterable, Tuple, Union
import marshmallow
from aiosnow.exceptions import (
DeserializationError,
IncompatiblePayloadField,
SchemaError,
SerializationError,
UnexpectedPayloadType,
UnknownPayloadField,
)
from .fields... | from typing import Any, Dict, Iterable, Tuple, Union
import marshmallow
from aiosnow.exceptions import (
DeserializationError,
IncompatiblePayloadField,
SchemaError,
SerializationError,
UnexpectedPayloadType,
UnknownPayloadField,
)
from .fields.base import BaseField
from .fields.mapped import... | en | 0.547511 | Load response content @TODO - move into load() Args: data: Dictionary of fields to deserialize Returns: dict(field_name=field_value, ...) Yields deserialized response content items Args: content: Response content to deserialize Yields: <nam... | 2.143478 | 2 |
ravenclaw/wrangling/fill_with_regression.py | idin/ravenclaw | 1 | 6632693 | <gh_stars>1-10
from copy import deepcopy
from numpy import where, minimum, maximum
def fill_with_regression(
data, regressor, based_on_col, group_by = None,
cols=None, except_cols=[], inplace=False,
limit_min = False,
limit_max = False,
global_min = None,
global_max = None
):
if inplace:
new_data = da... | from copy import deepcopy
from numpy import where, minimum, maximum
def fill_with_regression(
data, regressor, based_on_col, group_by = None,
cols=None, except_cols=[], inplace=False,
limit_min = False,
limit_max = False,
global_min = None,
global_max = None
):
if inplace:
new_data = data
else:
new_... | none | 1 | 2.85342 | 3 | |
res/TensorFlowPythonModels/examples/minimum-maximum/__init__.py | juitem/ONE | 255 | 6632694 | <reponame>juitem/ONE
import tensorflow as tf
in_ = tf.compat.v1.placeholder(dtype=tf.float32, shape=(1, 16, 160, 160), name="Hole")
upper_ = tf.compat.v1.constant(6.)
lower_ = tf.compat.v1.constant(0.)
min_ = tf.compat.v1.minimum(in_, upper_)
max_ = tf.compat.v1.maximum(min_, lower_)
'''
python ../../compiler/tf2tfl... | import tensorflow as tf
in_ = tf.compat.v1.placeholder(dtype=tf.float32, shape=(1, 16, 160, 160), name="Hole")
upper_ = tf.compat.v1.constant(6.)
lower_ = tf.compat.v1.constant(0.)
min_ = tf.compat.v1.minimum(in_, upper_)
max_ = tf.compat.v1.maximum(min_, lower_)
'''
python ../../compiler/tf2tfliteV2/tf2tfliteV2.py ... | en | 0.215826 | python ../../compiler/tf2tfliteV2/tf2tfliteV2.py --v1 \ -i minimum-maximum.pbtxt \ -o minimum-maximum.tflite \ -I Hole -O Maximum | 2.571375 | 3 |
octicons16px/skip.py | andrewp-as-is/octicons16px.py | 1 | 6632695 |
OCTICON_SKIP = """
<svg class="octicon octicon-skip" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16"><path fill-rule="evenodd" d="M1.5 8a6.5 6.5 0 1113 0 6.5 6.5 0 01-13 0zM8 0a8 8 0 100 16A8 8 0 008 0zm3.28 5.78a.75.75 0 00-1.06-1.06l-5.5 5.5a.75.75 0 101.06 1.06l5.5-5.5z"></path></svg>
... |
OCTICON_SKIP = """
<svg class="octicon octicon-skip" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16"><path fill-rule="evenodd" d="M1.5 8a6.5 6.5 0 1113 0 6.5 6.5 0 01-13 0zM8 0a8 8 0 100 16A8 8 0 008 0zm3.28 5.78a.75.75 0 00-1.06-1.06l-5.5 5.5a.75.75 0 101.06 1.06l5.5-5.5z"></path></svg>
... | en | 0.174351 | <svg class="octicon octicon-skip" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16"><path fill-rule="evenodd" d="M1.5 8a6.5 6.5 0 1113 0 6.5 6.5 0 01-13 0zM8 0a8 8 0 100 16A8 8 0 008 0zm3.28 5.78a.75.75 0 00-1.06-1.06l-5.5 5.5a.75.75 0 101.06 1.06l5.5-5.5z"></path></svg> | 1.219285 | 1 |
else/else14.py | mifomen/python | 0 | 6632696 | <filename>else/else14.py
a=int(input())
b=int(input())
c=int(input())
if a<=b<=c:
print(a,c)
elif a<=c<=b:
print(a,b)
elif a<=c<=b: #2,3,1
print(a,b)
elif a<=c<=b:
print(a,b)
#rpoblem
| <filename>else/else14.py
a=int(input())
b=int(input())
c=int(input())
if a<=b<=c:
print(a,c)
elif a<=c<=b:
print(a,b)
elif a<=c<=b: #2,3,1
print(a,b)
elif a<=c<=b:
print(a,b)
#rpoblem
| ca | 0.346387 | #2,3,1 #rpoblem | 3.884371 | 4 |
Anaconda-files/Program_19c.py | DrStephenLynch/dynamical-systems-with-applications-using-python | 1 | 6632697 | <reponame>DrStephenLynch/dynamical-systems-with-applications-using-python<filename>Anaconda-files/Program_19c.py<gh_stars>1-10
# Program 19c: Synchronization between two Lorenz systems.
# See Figure 19.7(b).
import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import odeint
# Constants
sigma = 16
b... | # Program 19c: Synchronization between two Lorenz systems.
# See Figure 19.7(b).
import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import odeint
# Constants
sigma = 16
b = 4
r = 45.92
tmax = 100
t = np.arange(0.0, tmax, 0.1)
def two_lorenz_odes(X, t):
x1, x2, x3, y2, y3 = X
dx1 = sigma... | en | 0.697408 | # Program 19c: Synchronization between two Lorenz systems. # See Figure 19.7(b). # Constants # unpack columns | 3.561941 | 4 |
search/search/request_handler.py | ATintern/microservices | 1 | 6632698 | # Python
import asyncio
# module
from search.grpc_client import gene_search, chromosome_search, chromosome_region
from search.query_parser import makeQueryParser
class RequestHandler:
def __init__(self, parser, gene_address, chromosome_address, region_address):
self.parser = parser
self.gene_address = gene... | # Python
import asyncio
# module
from search.grpc_client import gene_search, chromosome_search, chromosome_region
from search.query_parser import makeQueryParser
class RequestHandler:
def __init__(self, parser, gene_address, chromosome_address, region_address):
self.parser = parser
self.gene_address = gene... | en | 0.244327 | # Python # module # parser the query and search the indexes | 2.719724 | 3 |
packages/core/minos-microservice-aggregate/minos/aggregate/snapshots/repositories/database/factories.py | minos-framework/minos-python | 247 | 6632699 | from abc import (
ABC,
abstractmethod,
)
from collections.abc import (
Iterable,
)
from datetime import (
datetime,
)
from typing import (
Any,
Optional,
)
from uuid import (
UUID,
)
from minos.common import (
DatabaseOperation,
DatabaseOperationFactory,
)
from ....queries import (... | from abc import (
ABC,
abstractmethod,
)
from collections.abc import (
Iterable,
)
from datetime import (
datetime,
)
from typing import (
Any,
Optional,
)
from uuid import (
UUID,
)
from minos.common import (
DatabaseOperation,
DatabaseOperationFactory,
)
from ....queries import (... | en | 0.772485 | Snapshot Database Operation Factory class. Build the database operation to create the snapshot table. :return: A ``DatabaseOperation`` instance. Build the database operation to delete rows by transaction identifiers. :param transaction_uuids: The transaction identifiers. :return: A ``DatabaseO... | 2.552762 | 3 |
udify/modules/xlmr_pretrained.py | TeMU-BSC/udify-transformers | 1 | 6632700 | """
An extension of AllenNLP's BERT pretrained helper classes. Supports modification to BERT dropout, and applies
a sliding window approach for long sentences.
"""
from typing import Dict, List, Callable, Tuple, Any
import logging
import collections
from overrides import overrides
import torch
import torch.nn.functi... | """
An extension of AllenNLP's BERT pretrained helper classes. Supports modification to BERT dropout, and applies
a sliding window approach for long sentences.
"""
from typing import Dict, List, Callable, Tuple, Any
import logging
import collections
from overrides import overrides
import torch
import torch.nn.functi... | en | 0.806316 | An extension of AllenNLP's BERT pretrained helper classes. Supports modification to BERT dropout, and applies a sliding window approach for long sentences. # TODO(joelgrus): Figure out how to generate token_type_ids out of this token indexer. # This is the default list of tokens that should not be lowercased. A token i... | 2.448824 | 2 |
LinearRegression/ScriptEval_linearRegression.py | ChristofSchwarz/qs-python-samples | 7 | 6632701 | import logging
import logging.config
import grpc
from SSEData_linearRegression import ArgType, \
evaluate, \
get_arg_types, \
get_return_type, \
FunctionType, \
ge... | import logging
import logging.config
import grpc
from SSEData_linearRegression import ArgType, \
evaluate, \
get_arg_types, \
get_return_type, \
FunctionType, \
ge... | en | 0.628568 | Class for SSE plugin ScriptEval functionality. Evaluates script provided in the header, given the arguments provided in the sequence of RowData objects, the request. :param header: :param request: an iterable sequence of RowData. :param func_type: function type. :return: an iter... | 2.290521 | 2 |
src/main.py | Others/cos_memspec | 1 | 6632702 | #!/usr/local/bin/python3
from z3 import set_option
from shrinker import check_fragmentation
from vms import \
configure_setup_with_io_manager, \
configure_setup_with_io_and_chaining, \
configure_setup_with_io_and_sharing, \
setup_config_1, setup_config_2, setup_config_3, setup_config_4, setup_config_5
... | #!/usr/local/bin/python3
from z3 import set_option
from shrinker import check_fragmentation
from vms import \
configure_setup_with_io_manager, \
configure_setup_with_io_and_chaining, \
configure_setup_with_io_and_sharing, \
setup_config_1, setup_config_2, setup_config_3, setup_config_4, setup_config_5
... | en | 0.529271 | #!/usr/local/bin/python3 # def gen_config(size, complex_overlap_constraint): # hw_config = HardwareConfig(region_count=3, # subregion_count=8, # complex_overlap_constraint=complex_overlap_constraint) # # server = Component("server", hw_config) # ... | 2.026543 | 2 |
profiles_api/tests.py | Algernonagon/rest-api | 0 | 6632703 | from django.test import TestCase
from django.contrib import auth
from django.contrib.auth import get_user_model
User = get_user_model()
class AuthTestCase(TestCase):
def setUp(self):
self.u = User.objects.create_user('<EMAIL>', '<EMAIL>', '<PASSWORD>')
self.u.is_staff = True
self.u.is_supe... | from django.test import TestCase
from django.contrib import auth
from django.contrib.auth import get_user_model
User = get_user_model()
class AuthTestCase(TestCase):
def setUp(self):
self.u = User.objects.create_user('<EMAIL>', '<EMAIL>', '<PASSWORD>')
self.u.is_staff = True
self.u.is_supe... | none | 1 | 2.409289 | 2 | |
lib/view.py | goznalo-git/rate.sx | 903 | 6632704 | from mng import MongoReader
from view_ansi import print_table
import sys
try:
reload(sys)
sys.setdefaultencoding("utf-8")
except NameError:
pass # Python 3 already defaults to utf-8
def show(config):
"main function"
default_config = {
'number_of_ticks': 12,
'number_of_coins': 10,... | from mng import MongoReader
from view_ansi import print_table
import sys
try:
reload(sys)
sys.setdefaultencoding("utf-8")
except NameError:
pass # Python 3 already defaults to utf-8
def show(config):
"main function"
default_config = {
'number_of_ticks': 12,
'number_of_coins': 10,... | en | 0.111993 | # Python 3 already defaults to utf-8 #default_config.update(config) | 2.587838 | 3 |
server/problems.py | ChuckMN/Apple-iOS-MDM-Server | 549 | 6632705 | <reponame>ChuckMN/Apple-iOS-MDM-Server<filename>server/problems.py
problems = []
| problems = [] | none | 1 | 1.052036 | 1 | |
pydantic/color.py | FuegoFro/pydantic | 10 | 6632706 | """
Color definitions are used as per CSS3 specification:
http://www.w3.org/TR/css3-color/#svg-color
A few colors have multiple names referring to the sames colors, eg. `grey` and `gray` or `aqua` and `cyan`.
In these cases the LAST color when sorted alphabetically takes preferences,
eg. Color((0, 255, 255)).as_name... | """
Color definitions are used as per CSS3 specification:
http://www.w3.org/TR/css3-color/#svg-color
A few colors have multiple names referring to the sames colors, eg. `grey` and `gray` or `aqua` and `cyan`.
In these cases the LAST color when sorted alphabetically takes preferences,
eg. Color((0, 255, 255)).as_name... | en | 0.762648 | Color definitions are used as per CSS3 specification: http://www.w3.org/TR/css3-color/#svg-color A few colors have multiple names referring to the sames colors, eg. `grey` and `gray` or `aqua` and `cyan`. In these cases the LAST color when sorted alphabetically takes preferences, eg. Color((0, 255, 255)).as_named() ... | 3.547344 | 4 |
angr-management/angrmanagement/logic/threads.py | Ruide/angr-dev | 0 | 6632707 | <filename>angr-management/angrmanagement/logic/threads.py
import thread
import threading
from PySide.QtCore import QEvent, QCoreApplication
from . import GlobalInfo
class ExecuteCodeEvent(QEvent):
def __init__(self, callable, args=None):
super(ExecuteCodeEvent, self).__init__(QEvent.User)
self.... | <filename>angr-management/angrmanagement/logic/threads.py
import thread
import threading
from PySide.QtCore import QEvent, QCoreApplication
from . import GlobalInfo
class ExecuteCodeEvent(QEvent):
def __init__(self, callable, args=None):
super(ExecuteCodeEvent, self).__init__(QEvent.User)
self.... | en | 0.770337 | Derived from http://code.activestate.com/recipes/496741-object-proxying/ # # proxying (special cases) # # # factories # Creates a proxy for the given class. creates an proxy instance referencing `obj`. (obj, *args, **kwargs) are passed to this class' __init__, so deriving classes can define an __init__ ... | 2.263583 | 2 |
faculty/clients/user.py | jkeelan/faculty | 0 | 6632708 | <filename>faculty/clients/user.py
# Copyright 2018-2019 Faculty Science Limited
#
# 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 re... | <filename>faculty/clients/user.py
# Copyright 2018-2019 Faculty Science Limited
#
# 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 re... | en | 0.847013 | # Copyright 2018-2019 Faculty Science Limited # # 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... | 2.226831 | 2 |
backend/backend/urls.py | indian-innovation-company/copr8 | 0 | 6632709 | <filename>backend/backend/urls.py<gh_stars>0
from contrib.views import char_count
from django.contrib import admin
from django.urls import include, path, re_path
from django.views.generic import TemplateView
from rest_framework import routers
from contrib.views import ResourcesViewSet
router = routers.DefaultRouter()... | <filename>backend/backend/urls.py<gh_stars>0
from contrib.views import char_count
from django.contrib import admin
from django.urls import include, path, re_path
from django.views.generic import TemplateView
from rest_framework import routers
from contrib.views import ResourcesViewSet
router = routers.DefaultRouter()... | none | 1 | 1.790193 | 2 | |
src/rush/limiters/base.py | algobot76/rush | 41 | 6632710 | """Interface definition for limiters."""
import attr
from .. import quota
from .. import result
from .. import stores
@attr.s
class BaseLimiter:
"""Base object defining the interface for limiters."""
store: stores.BaseStore = attr.ib(
validator=attr.validators.instance_of(stores.BaseStore)
)
... | """Interface definition for limiters."""
import attr
from .. import quota
from .. import result
from .. import stores
@attr.s
class BaseLimiter:
"""Base object defining the interface for limiters."""
store: stores.BaseStore = attr.ib(
validator=attr.validators.instance_of(stores.BaseStore)
)
... | en | 0.770071 | Interface definition for limiters. Base object defining the interface for limiters. Apply the rate-limit to a quantity of requests. Reset the rate-limit for a given key. | 2.542717 | 3 |
learn/05learn-n19.py | keydepth/facedetect | 0 | 6632711 | <filename>learn/05learn-n19.py
from keras.layers import Activation, Conv2D, Dense, Flatten, MaxPooling2D
from keras.models import Sequential, load_model
from keras.utils.np_utils import to_categorical
# 画像と正解ラベルをリストにする
import random
from keras.utils.np_utils import to_categorical
import os
import cv2
import numpy as n... | <filename>learn/05learn-n19.py
from keras.layers import Activation, Conv2D, Dense, Flatten, MaxPooling2D
from keras.models import Sequential, load_model
from keras.utils.np_utils import to_categorical
# 画像と正解ラベルをリストにする
import random
from keras.utils.np_utils import to_categorical
import os
import cv2
import numpy as n... | ja | 0.970171 | # 画像と正解ラベルをリストにする #print(X_test[0]) #print(y_test[0]) #plt.imshow(X_train[0]) #plt.show() #print(y_train[0]) # モデルの定義 # コンパイル # 学習 # model.fit(X_train, y_train, batch_size=32, epochs=100) #グラフ用 # 汎化制度の評価・表示 #acc, val_accのプロット #モデルを保存 | 3.005438 | 3 |
scripts/modules/conditions.py | vkostyanetsky/Organizer | 0 | 6632712 | <filename>scripts/modules/conditions.py
import re
import datetime
def is_task_started(task, date):
result = True
regexp = '.*(, начиная с| с) ([0-9]{1,2}.[0-9]{1,2}.[0-9]{4})$'
groups = re.match(regexp, task['condition'])
if groups != None:
start_date = datetime.datetime.strptime(groups[2]... | <filename>scripts/modules/conditions.py
import re
import datetime
def is_task_started(task, date):
result = True
regexp = '.*(, начиная с| с) ([0-9]{1,2}.[0-9]{1,2}.[0-9]{4})$'
groups = re.match(regexp, task['condition'])
if groups != None:
start_date = datetime.datetime.strptime(groups[2]... | none | 1 | 2.832792 | 3 | |
plugins/panorama/panorama/chart_factory.py | mohnjahoney/website_source | 13 | 6632713 | <reponame>mohnjahoney/website_source
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from functools import partial
from pandas import Series, DataFrame
# !! Import required to instantiate charts, do not remove
from nvd3 import *
import numpy
# A dict used for chart configuration.
# DEFAULT settings ... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from functools import partial
from pandas import Series, DataFrame
# !! Import required to instantiate charts, do not remove
from nvd3 import *
import numpy
# A dict used for chart configuration.
# DEFAULT settings can be overwritten and/or completed b... | en | 0.774642 | # -*- coding: utf-8 -*- # !! Import required to instantiate charts, do not remove # A dict used for chart configuration. # DEFAULT settings can be overwritten and/or completed by chart specific settings. # In this case, the chart class is used as key. # TODO extra series conf ? Create a chart by using the renderer, add... | 3.014992 | 3 |
utils/unpacker.py | woshimaliang/xcbuildkit | 165 | 6632714 | #!/usr/local/bin/python3
import msgpack
import service
import sys
import fcntl
import os
import time
import datetime
global log_file
global log_path
if len(sys.argv) > 1:
log_path = sys.argv[1]
else:
log_path = "/tmp/xcbuild.diags"
log_file = None
def unpack(unpacker, data=[]):
state = unpacker.tell... | #!/usr/local/bin/python3
import msgpack
import service
import sys
import fcntl
import os
import time
import datetime
global log_file
global log_path
if len(sys.argv) > 1:
log_path = sys.argv[1]
else:
log_path = "/tmp/xcbuild.diags"
log_file = None
def unpack(unpacker, data=[]):
state = unpacker.tell... | en | 0.771662 | #!/usr/local/bin/python3 # Handle when the file is done | 2.225312 | 2 |
eventmapper/__init__.py | Moguri/panda3d-eventmapper | 0 | 6632715 | <reponame>Moguri/panda3d-eventmapper
import pprint
from direct.showbase.DirectObject import DirectObject
from direct.directnotify.DirectNotifyGlobal import directNotify
from direct.showbase.MessengerGlobal import messenger
import panda3d.core as p3d
class EventMapper(DirectObject):
notify = directNotify.newCateg... | import pprint
from direct.showbase.DirectObject import DirectObject
from direct.directnotify.DirectNotifyGlobal import directNotify
from direct.showbase.MessengerGlobal import messenger
import panda3d.core as p3d
class EventMapper(DirectObject):
notify = directNotify.newCategory("EventMapper")
event_map_item... | en | 0.415349 | # Setup gamepadds # Setup input map # Remove previous mappings # Build mappings from ConfigVariables # Prevent circular reference # Listen for events # remove gamepadN prefix | 2.034299 | 2 |
game_data.py | jamestk97/BongBongAI | 0 | 6632716 | # The sprite data and level design were adopted from <Bong Bong> (1989) written by
# <NAME> (co-founder of Daum Corporation: https://en.wikipedia.org/wiki/Daum_(web_portal))
# while in Computer Science Department at Yonsei University, Korea.
# The program and the data had been open-sourced in a Korean online game commu... | # The sprite data and level design were adopted from <Bong Bong> (1989) written by
# <NAME> (co-founder of Daum Corporation: https://en.wikipedia.org/wiki/Daum_(web_portal))
# while in Computer Science Department at Yonsei University, Korea.
# The program and the data had been open-sourced in a Korean online game commu... | en | 0.705758 | # The sprite data and level design were adopted from <Bong Bong> (1989) written by # <NAME> (co-founder of Daum Corporation: https://en.wikipedia.org/wiki/Daum_(web_portal)) # while in Computer Science Department at Yonsei University, Korea. # The program and the data had been open-sourced in a Korean online game commu... | 2.003449 | 2 |
main.py | Mort1J1/Python-spill | 0 | 6632717 | from cmath import pi
from math import sqrt
from turtle import Screen
import pygame
import sys
import random
from pyparsing import Or
from scipy import rand
from soupsieve import match
from sqlalchemy import case, false
pygame.init()
SCREEN_WIDTH = 1400
SCREEN_HEIGHT = 800
COLOR_BLACK = (0, 0, 0)
COLOR_WHITE = (25... | from cmath import pi
from math import sqrt
from turtle import Screen
import pygame
import sys
import random
from pyparsing import Or
from scipy import rand
from soupsieve import match
from sqlalchemy import case, false
pygame.init()
SCREEN_WIDTH = 1400
SCREEN_HEIGHT = 800
COLOR_BLACK = (0, 0, 0)
COLOR_WHITE = (25... | en | 0.242122 | #Create surface #Create title #sounds #antall virus og murlocs for "score" # pygame.draw.circle(surface, m.color, (m.x, m.y), m.size) # if m.x + m.size >= SCREEN_WIDTH: # Alive = False # elif m.x - m.size <= SCREEN_WIDTH: # Alive = False # elif m.y + m.size >= SCREEN_HEIGHT: # Alive = False # elif m.y - m.... | 2.783146 | 3 |
scripts/bump-config.py | Thaodan/sailfishos-sony-tama-main | 0 | 6632718 | #!/usr/bin/env python3
import sys, glob
import lxml.etree as ET
from datetime import datetime
base = sys.argv[1]
for T in ['config', 'hal-version']:
for f in glob.glob(base + ('/*%s*/_service' % T)):
tree = ET.parse(f)
root = tree.getroot()
for c in root:
if c.tag is ET.Comment ... | #!/usr/bin/env python3
import sys, glob
import lxml.etree as ET
from datetime import datetime
base = sys.argv[1]
for T in ['config', 'hal-version']:
for f in glob.glob(base + ('/*%s*/_service' % T)):
tree = ET.parse(f)
root = tree.getroot()
for c in root:
if c.tag is ET.Comment ... | fr | 0.221828 | #!/usr/bin/env python3 | 2.297341 | 2 |
script/ssdnet/mycaffe.py | Hiroki-kt/image-recognition-train | 0 | 6632719 | <filename>script/ssdnet/mycaffe.py
import numpy as np
import re
import sys
import chainer.links.caffe.caffe_function as cf
from ssdnet.ssd import _Normalize
def _rename(name):
m = re.match(r'^conv(\d+)_([123])$', name)
if m:
i, j = list(map(int, m.groups()))
if i >= 6:
i += 2
... | <filename>script/ssdnet/mycaffe.py
import numpy as np
import re
import sys
import chainer.links.caffe.caffe_function as cf
from ssdnet.ssd import _Normalize
def _rename(name):
m = re.match(r'^conv(\d+)_([123])$', name)
if m:
i, j = list(map(int, m.groups()))
if i >= 6:
i += 2
... | none | 1 | 2.407453 | 2 | |
bamboo_api/__init__.py | sdlm/dev_idwell_bot | 2 | 6632720 | <reponame>sdlm/dev_idwell_bot
__author__ = 'lionel.cuevas'
from .api import BambooAPIClient
| __author__ = 'lionel.cuevas'
from .api import BambooAPIClient | none | 1 | 1.112552 | 1 | |
src/pytorch.py | ManiacMaxo/Thesis | 0 | 6632721 | import torch.nn as nn
import torch.nn.functional as F
class DanQ(nn.Sequential):
def __init__(self, outputs: int = 1):
super(DanQ, self).__init__()
self.conv = nn.Conv1d(in_channels=4, out_channels=320, kernel_size=26)
self.pooling = nn.MaxPool1d(kernel_size=13)
self.dropout1 = nn... | import torch.nn as nn
import torch.nn.functional as F
class DanQ(nn.Sequential):
def __init__(self, outputs: int = 1):
super(DanQ, self).__init__()
self.conv = nn.Conv1d(in_channels=4, out_channels=320, kernel_size=26)
self.pooling = nn.MaxPool1d(kernel_size=13)
self.dropout1 = nn... | none | 1 | 2.910286 | 3 | |
bundle/kinesis_webrtc_manager/share/kinesis_webrtc_manager/package.py | gitobic/deepracer-simapp | 1 | 6632722 | # template generated by /usr/local/lib/python3.6/dist-packages/colcon_python_shell/shell/python_shell.py
# This script extends the environment for this package.
import pathlib
# assumes colcon_current_prefix has been injected into globals by caller
assert colcon_current_prefix
def prepend_unique_path(envvar, subdire... | # template generated by /usr/local/lib/python3.6/dist-packages/colcon_python_shell/shell/python_shell.py
# This script extends the environment for this package.
import pathlib
# assumes colcon_current_prefix has been injected into globals by caller
assert colcon_current_prefix
def prepend_unique_path(envvar, subdire... | en | 0.806064 | # template generated by /usr/local/lib/python3.6/dist-packages/colcon_python_shell/shell/python_shell.py # This script extends the environment for this package. # assumes colcon_current_prefix has been injected into globals by caller # If subdirectory is relative, it is relative to prefix # source python hooks | 1.977099 | 2 |
dl4nlp_pos_tagging/models/modules/token_embedders/embedding_sum.py | michaeljneely/model-uncertainty-pos-tagging | 1 | 6632723 | <reponame>michaeljneely/model-uncertainty-pos-tagging<gh_stars>1-10
import torch
from overrides import overrides
from typing import List
from allennlp.modules.token_embedders.token_embedder import TokenEmbedder
@TokenEmbedder.register("summed-embedding")
class SummedEmbedding(TokenEmbedder):
"""
This class is... | import torch
from overrides import overrides
from typing import List
from allennlp.modules.token_embedders.token_embedder import TokenEmbedder
@TokenEmbedder.register("summed-embedding")
class SummedEmbedding(TokenEmbedder):
"""
This class is meant for summing multiple embeddings together.
Registered as ... | en | 0.884312 | This class is meant for summing multiple embeddings together. Registered as a `TokenEmbedder` with name "summed-embedding". | 2.635972 | 3 |
deeptools/_version.py | samhuairen/deepTools | 0 | 6632724 |
# This file is originally generated from Git information by running 'setup.py
# version'. Distribution tarballs contain a pre-generated copy of this file.
__version__ = '3.3.2'
|
# This file is originally generated from Git information by running 'setup.py
# version'. Distribution tarballs contain a pre-generated copy of this file.
__version__ = '3.3.2'
| en | 0.868437 | # This file is originally generated from Git information by running 'setup.py # version'. Distribution tarballs contain a pre-generated copy of this file. | 0.849952 | 1 |
optimizers/BAT.py | VicZH/Evolutionary-Algorithm-Racing | 0 | 6632725 | import numpy
import random
from solution import solution
class BAT(solution):
def __init__(self, objf, sol_shift, lb, ub, dim, PopSize, EvlNum):
# Loudness (constant or decreasing)
self.A = 0.5
# Pulse rate (constant or decreasing)
self.r = 0.5
self.dim = dim
... | import numpy
import random
from solution import solution
class BAT(solution):
def __init__(self, objf, sol_shift, lb, ub, dim, PopSize, EvlNum):
# Loudness (constant or decreasing)
self.A = 0.5
# Pulse rate (constant or decreasing)
self.r = 0.5
self.dim = dim
... | en | 0.650629 | # Loudness (constant or decreasing) # Pulse rate (constant or decreasing) # convert lb, ub to array # Frequency minimum # Frequency maximum # Initializing arrays # Frequency # Velocities # new solutions # initialize population # calculate fitness for all the population # Loop over all bats(solutions) # Check boundarie... | 2.663596 | 3 |
ipyprogressbar/ipyprogressbar.py | WillahScott/ipyprogressbar | 3 | 6632726 | <reponame>WillahScott/ipyprogressbar
# -*- coding: utf-8 -*-
"""Python-asynchronous progressbar widgets for use in Jupyter/IPython in conjunction with `ipywidgets<https://ipywidgets.readthedocs.io>`_
.. module:: ipyprogressbar.asyncprogressbar
:platform: Unix, Windows
:synopsis: Progressbar that executes asynch... | # -*- coding: utf-8 -*-
"""Python-asynchronous progressbar widgets for use in Jupyter/IPython in conjunction with `ipywidgets<https://ipywidgets.readthedocs.io>`_
.. module:: ipyprogressbar.asyncprogressbar
:platform: Unix, Windows
:synopsis: Progressbar that executes asynchronous of python
.. |widget| replace... | en | 0.546435 | # -*- coding: utf-8 -*- Python-asynchronous progressbar widgets for use in Jupyter/IPython in conjunction with `ipywidgets<https://ipywidgets.readthedocs.io>`_ .. module:: ipyprogressbar.asyncprogressbar :platform: Unix, Windows :synopsis: Progressbar that executes asynchronous of python .. |widget| replace:: `... | 3.439018 | 3 |
flask_s3_viewer/routers.py | blairdrummond/flask-s3-viewer | 7 | 6632727 | <reponame>blairdrummond/flask-s3-viewer<gh_stars>1-10
from .blueprints.view import blueprint as FlaskS3ViewerViewRouter
| from .blueprints.view import blueprint as FlaskS3ViewerViewRouter | none | 1 | 1.188688 | 1 | |
test/implicit-cache/basic.py | moroten/scons | 1 | 6632728 | <gh_stars>1-10
#!/usr/bin/env python
#
# __COPYRIGHT__
#
# 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, m... | #!/usr/bin/env python
#
# __COPYRIGHT__
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
... | en | 0.659193 | #!/usr/bin/env python # # __COPYRIGHT__ # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, ... | 1.657625 | 2 |
tests/test_config.py | eirki/kamera | 0 | 6632729 | #! /usr/bin/env python3
# coding: utf-8
import numpy as np
import pytest
from kamera import config
from tests.mock_dropbox import MockDropbox
def test_settings_default_tz(settings):
assert settings.default_tz == "US/Eastern"
def test_settings_recognition_tolerance(settings):
assert settings.recognition_tol... | #! /usr/bin/env python3
# coding: utf-8
import numpy as np
import pytest
from kamera import config
from tests.mock_dropbox import MockDropbox
def test_settings_default_tz(settings):
assert settings.default_tz == "US/Eastern"
def test_settings_recognition_tolerance(settings):
assert settings.recognition_tol... | en | 0.272496 | #! /usr/bin/env python3 # coding: utf-8 | 2.247773 | 2 |
pysecs/secs.py | greglucas/pysecs | 2 | 6632730 | import numpy as np
class SECS:
"""Spherical Elementary Current System (SECS).
The algorithm is implemented directly in spherical coordinates
from the equations of the 1999 Amm & Viljanen paper [1]_.
Parameters
----------
sec_df_loc : ndarray (nsec x 3 [lat, lon, r])
The latitude, lo... | import numpy as np
class SECS:
"""Spherical Elementary Current System (SECS).
The algorithm is implemented directly in spherical coordinates
from the equations of the 1999 Amm & Viljanen paper [1]_.
Parameters
----------
sec_df_loc : ndarray (nsec x 3 [lat, lon, r])
The latitude, lo... | en | 0.797658 | Spherical Elementary Current System (SECS). The algorithm is implemented directly in spherical coordinates from the equations of the 1999 Amm & Viljanen paper [1]_. Parameters ---------- sec_df_loc : ndarray (nsec x 3 [lat, lon, r]) The latitude, longiutde, and radius of the divergence fr... | 3.132842 | 3 |
scripts/pysurfer_plot_500parcellation_surface_values.py | SarahMorgan/BrainsForPublication | 0 | 6632731 | #!/usr/bin/env python
#=============================================================================
# Created by <NAME>
# September 2014
# Contact: <EMAIL>
#=============================================================================
#=============================================================================
# I... | #!/usr/bin/env python
#=============================================================================
# Created by <NAME>
# September 2014
# Contact: <EMAIL>
#=============================================================================
#=============================================================================
# I... | en | 0.675663 | #!/usr/bin/env python #============================================================================= # Created by <NAME> # September 2014 # Contact: <EMAIL> #============================================================================= #============================================================================= # IMP... | 1.785265 | 2 |
brainsprite/__init__.py | kchapelier/brainsprite | 13 | 6632732 | """Brainsprite python API."""
from .brainsprite import viewer_substitute
__all__ = ['viewer_substitute']
| """Brainsprite python API."""
from .brainsprite import viewer_substitute
__all__ = ['viewer_substitute']
| en | 0.250533 | Brainsprite python API. | 1.207383 | 1 |
corehq/apps/hqwebapp/tests/test_csrf_middleware.py | kkrampa/commcare-hq | 1 | 6632733 | from __future__ import absolute_import
from __future__ import unicode_literals
from bs4 import BeautifulSoup
from django.urls import reverse
from django.test import TestCase, Client
from corehq.apps.domain.models import Domain
from corehq.apps.users.models import WebUser
class TestCSRF(TestCase):
@classmethod
... | from __future__ import absolute_import
from __future__ import unicode_literals
from bs4 import BeautifulSoup
from django.urls import reverse
from django.test import TestCase, Client
from corehq.apps.domain.models import Domain
from corehq.apps.users.models import WebUser
class TestCSRF(TestCase):
@classmethod
... | en | 0.895531 | # There is no particular reason in using 'send_to_recipients' as the CSRF test view, # all views unless decorated with csrf_exempt should be CSRF protected by default via Django's middleware | 2.225385 | 2 |
setup.py | ProfBIT-develop/django-modeltranslation | 1 | 6632734 | #!/usr/bin/env python
from distutils.core import setup
# Dynamically calculate the version based on modeltranslation.VERSION.
version = __import__('modeltranslation').get_version()
setup(
name='django-modeltranslation',
version=version,
description='Translates Django models using a registration approach.... | #!/usr/bin/env python
from distutils.core import setup
# Dynamically calculate the version based on modeltranslation.VERSION.
version = __import__('modeltranslation').get_version()
setup(
name='django-modeltranslation',
version=version,
description='Translates Django models using a registration approach.... | en | 0.63457 | #!/usr/bin/env python # Dynamically calculate the version based on modeltranslation.VERSION. | 1.996652 | 2 |
mqtt_gate/main.py | icservis/majordomo | 0 | 6632735 | <gh_stars>0
import os
import binascii
import yaml
import paho.mqtt.client as mqtt
import re
from lib.garage import GarageDoor
print ("Welcome to GarageBerryPi!")
# Update the mqtt state topic
def update_state(value, topic):
print ("State change triggered: %s -> %s" % (topic, value))
client.publish(topic, val... | import os
import binascii
import yaml
import paho.mqtt.client as mqtt
import re
from lib.garage import GarageDoor
print ("Welcome to GarageBerryPi!")
# Update the mqtt state topic
def update_state(value, topic):
print ("State change triggered: %s -> %s" % (topic, value))
client.publish(topic, value, retain=T... | en | 0.701123 | # Update the mqtt state topic # The callback for when the client receives a CONNACK response from the server. # Execute the specified command for a door ### SETUP MQTT ### ### SETUP END ### ### MAIN LOOP ### # Create door objects and create callback functions # If no name it set, then set to id # Sanitize id value for ... | 2.616758 | 3 |
apps/test.py | xroynard/ms_deepvoxscene | 13 | 6632736 | <filename>apps/test.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: <NAME>
"""
from __future__ import print_function, division
import os
import sys
import glob
import argparse
import numpy as np
# Pytorch
import torch
from torch.utils.data import DataLoader
# cudnn optim
import torch.backends.cudnn as... | <filename>apps/test.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: <NAME>
"""
from __future__ import print_function, division
import os
import sys
import glob
import argparse
import numpy as np
# Pytorch
import torch
from torch.utils.data import DataLoader
# cudnn optim
import torch.backends.cudnn as... | de | 0.734961 | #!/usr/bin/env python3 # -*- coding: utf-8 -*- @author: <NAME> # Pytorch # cudnn optim # to import modules #import models ############################################################################### #%% Parses Command Line Arguments ############################################################################## #%% R... | 2.018967 | 2 |
Python/minesweeper.py | ruikunl/LeetCode | 5 | 6632737 | <gh_stars>1-10
# Time: O(m * n)
# Space: O(m + n)
# Let's play the minesweeper game (Wikipedia, online game)!
#
# You are given a 2D char matrix representing the game board. 'M' represents an unrevealed mine,
# 'E' represents an unrevealed empty square, 'B' represents a revealed blank square that has no adjacent
# (a... | # Time: O(m * n)
# Space: O(m + n)
# Let's play the minesweeper game (Wikipedia, online game)!
#
# You are given a 2D char matrix representing the game board. 'M' represents an unrevealed mine,
# 'E' represents an unrevealed empty square, 'B' represents a revealed blank square that has no adjacent
# (above, below, le... | en | 0.80327 | # Time: O(m * n) # Space: O(m + n) # Let's play the minesweeper game (Wikipedia, online game)! # # You are given a 2D char matrix representing the game board. 'M' represents an unrevealed mine, # 'E' represents an unrevealed empty square, 'B' represents a revealed blank square that has no adjacent # (above, below, lef... | 3.769517 | 4 |
djackal/erra.py | jrog612/djackal | 0 | 6632738 | from enum import Enum
class Erra(Enum):
def __str__(self):
return self.name
@property
def message(self):
return self.value
@property
def code(self):
return self.name
def get_message(self, context=None):
message = self.message
if context and message:
... | from enum import Enum
class Erra(Enum):
def __str__(self):
return self.name
@property
def message(self):
return self.value
@property
def code(self):
return self.name
def get_message(self, context=None):
message = self.message
if context and message:
... | none | 1 | 2.845569 | 3 | |
tests/test_coverage_sorteddict.py | monkeywithacupcake/python-sortedcontainers | 1 | 6632739 | <reponame>monkeywithacupcake/python-sortedcontainers
# -*- coding: utf-8 -*-
import random, string
from .context import sortedcontainers
from sortedcontainers import SortedDict
import pytest
from sys import hexversion
if hexversion < 0x03000000:
range = xrange
def negate(value):
return -value
def modulo(val... | # -*- coding: utf-8 -*-
import random, string
from .context import sortedcontainers
from sortedcontainers import SortedDict
import pytest
from sys import hexversion
if hexversion < 0x03000000:
range = xrange
def negate(value):
return -value
def modulo(value):
return value % 10
def get_keysview(dic):
... | en | 0.769321 | # -*- coding: utf-8 -*- | 2.423865 | 2 |
move.py | martinogden/chessval | 0 | 6632740 | <reponame>martinogden/chessval<filename>move.py
class flags(object):
DPUSH = 0x01
KCASTLE = 0x02
QCASTLE = 0x04
CAPTURE = 0x08
EP = 0x10
def new(frm, to, cpiece=-1, flags=0x00, cr=0X0F, promotion=None):
return (frm, to, cpiece, flags, cr, promotion)
| class flags(object):
DPUSH = 0x01
KCASTLE = 0x02
QCASTLE = 0x04
CAPTURE = 0x08
EP = 0x10
def new(frm, to, cpiece=-1, flags=0x00, cr=0X0F, promotion=None):
return (frm, to, cpiece, flags, cr, promotion) | none | 1 | 2.300516 | 2 | |
modeling/model_utils/unet_parts.py | UESTC-Liuxin/SkmtSeg | 2 | 6632741 | """ Parts of the U-Net model """
import torch
import torch.nn as nn
import torch.nn.functional as F
from utils.utils import init_weights
class DoubleConv(nn.Module):
"""(convolution => [BN] => ReLU) * 2"""
def __init__(self, in_channels, out_channels, BatchNorm,mid_channels=None):
super().__init__()
... | """ Parts of the U-Net model """
import torch
import torch.nn as nn
import torch.nn.functional as F
from utils.utils import init_weights
class DoubleConv(nn.Module):
"""(convolution => [BN] => ReLU) * 2"""
def __init__(self, in_channels, out_channels, BatchNorm,mid_channels=None):
super().__init__()
... | en | 0.584623 | Parts of the U-Net model (convolution => [BN] => ReLU) * 2 Upscaling then double conv # input is CHW # initialise the blocks # initialise the blocks | 2.786952 | 3 |
scripts/previousScripts-2015-12-25/approxMC_boolector_bvurem.py | mistryrakesh/SMTApproxMC | 0 | 6632742 | #!/home/rakeshmistry/bin/Python-3.4.3/bin/python3
# @author: <NAME> - 'inspire'
# @date: 2015-06-14
import sys
import re
import os
import math
import random
import functools
import collections
import numpy
################################################################################
# Functions to generate SMT2 e... | #!/home/rakeshmistry/bin/Python-3.4.3/bin/python3
# @author: <NAME> - 'inspire'
# @date: 2015-06-14
import sys
import re
import os
import math
import random
import functools
import collections
import numpy
################################################################################
# Functions to generate SMT2 e... | en | 0.560302 | #!/home/rakeshmistry/bin/Python-3.4.3/bin/python3 # @author: <NAME> - 'inspire' # @date: 2015-06-14 ################################################################################ # Functions to generate SMT2 expressions ################################################################################ # Function: popul... | 2.175645 | 2 |
message_creator/multi_list_pb2.py | jameshp/deviceadminserver | 0 | 6632743 | # Generated by the protocol buffer compiler. DO NOT EDIT!
# source: multi_list.proto
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
from google.p... | # Generated by the protocol buffer compiler. DO NOT EDIT!
# source: multi_list.proto
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
from google.p... | en | 0.348111 | # Generated by the protocol buffer compiler. DO NOT EDIT! # source: multi_list.proto # @@protoc_insertion_point(imports) # @@protoc_insertion_point(class_scope:Proto.Config.multilist_entry_object.DataEntry) # @@protoc_insertion_point(class_scope:Proto.Config.multilist_entry_object) # @@protoc_insertion_point(class_sco... | 1.220371 | 1 |
tests/test_notebooks.py | francescodonato/GPflux | 100 | 6632744 | #
# Copyright (c) 2021 The GPflux Contributors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | #
# Copyright (c) 2021 The GPflux Contributors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | en | 0.860274 | # # Copyright (c) 2021 The GPflux Contributors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agr... | 1.996073 | 2 |
supabase_py/lib/supabase_storage_client.py | olirice/supabase-py | 0 | 6632745 | <filename>supabase_py/lib/supabase_storage_client.py
from supabase_py.lib.storage.storage_bucket_api import StorageBucketAPI
class SupabaseStorageClient(StorageBucketAPI):
"""
Manage the storage bucket and files
Examples
--------
>>> url = storage_file.create_signed_url("poll3o/test2.txt", 80) #... | <filename>supabase_py/lib/supabase_storage_client.py
from supabase_py.lib.storage.storage_bucket_api import StorageBucketAPI
class SupabaseStorageClient(StorageBucketAPI):
"""
Manage the storage bucket and files
Examples
--------
>>> url = storage_file.create_signed_url("poll3o/test2.txt", 80) #... | en | 0.583502 | Manage the storage bucket and files Examples -------- >>> url = storage_file.create_signed_url("poll3o/test2.txt", 80) # signed url >>> loop.run_until_complete(storage_file.download("poll3o/test2.txt")) #upload or download >>> loop.run_until_complete(storage_file.upload("poll3o/test2.txt","path_fi... | 2.731857 | 3 |
node_modules/nuclide/pkg/nuclide-debugger-native-rpc/scripts/thread_manager.py | kevingatera/kgatewebapp | 1 | 6632746 | <reponame>kevingatera/kgatewebapp
# Copyright (c) 2015-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the license found in the LICENSE file in
# the root directory of this source tree.
from find_lldb import get_lldb
from remote_objects import ValueListRemoteObject
CALL_STACK_OB... | # Copyright (c) 2015-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the license found in the LICENSE file in
# the root directory of this source tree.
from find_lldb import get_lldb
from remote_objects import ValueListRemoteObject
CALL_STACK_OBJECT_GROUP = 'thread_stack'
MAX_ST... | en | 0.841837 | # Copyright (c) 2015-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. Manages all the threads in target process. The client expects one `Debugger.threadCreated` message for each thread. Initializ... | 2.23464 | 2 |
examples/swarmalator/plot_swarmalator.py | wordsworthgroup/libode | 11 | 6632747 | from os import listdir
from os.path import join
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
plt.style.use('dark_background')
#plt.rc('font', family='monospace')
frgb = lambda theta: 0.45*(1 + np.cos(theta))
def rgb(theta):
r = frgb(theta)
g = frgb(theta - 2*np.... | from os import listdir
from os.path import join
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
plt.style.use('dark_background')
#plt.rc('font', family='monospace')
frgb = lambda theta: 0.45*(1 + np.cos(theta))
def rgb(theta):
r = frgb(theta)
g = frgb(theta - 2*np.... | en | 0.178467 | #plt.rc('font', family='monospace') #load results #x, y, theta = x, y, theta | 2.396326 | 2 |
lectures/l08-inclass.py | davidd-55/cs152fa21 | 1 | 6632748 | # ---
# jupyter:
# jupytext:
# formats: ipynb,py:percent
# text_representation:
# extension: .py
# format_name: percent
# format_version: '1.3'
# jupytext_version: 1.11.4
# kernelspec:
# display_name: Python 3 (ipykernel)
# language: python
# name: python3
# ---
# %%
imp... | # ---
# jupyter:
# jupytext:
# formats: ipynb,py:percent
# text_representation:
# extension: .py
# format_name: percent
# format_version: '1.3'
# jupytext_version: 1.11.4
# kernelspec:
# display_name: Python 3 (ipykernel)
# language: python
# name: python3
# ---
# %%
imp... | en | 0.256277 | # --- # jupyter: # jupytext: # formats: ipynb,py:percent # text_representation: # extension: .py # format_name: percent # format_version: '1.3' # jupytext_version: 1.11.4 # kernelspec: # display_name: Python 3 (ipykernel) # language: python # name: python3 # --- # %% # %%... | 2.56517 | 3 |
tensorflow/contrib/distributions/python/ops/mvn.py | returncode13/tensorflow | 1 | 6632749 | # Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | # Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | en | 0.778227 | # Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica... | 1.74776 | 2 |
write_to_file.py | arpanrec/bitwarden-export-migrate | 0 | 6632750 | <filename>write_to_file.py
import gnupg
import os
import tempfile
class EncryptAndWriteToFile:
def __init__(self, keyid) -> None:
self.keyid = keyid
dirpath = tempfile.mkdtemp()
self.gpg = gnupg.GPG(gnupghome=os.path.abspath(dirpath))
self.gpg.encoding = 'utf-8'
self.gpg.r... | <filename>write_to_file.py
import gnupg
import os
import tempfile
class EncryptAndWriteToFile:
def __init__(self, keyid) -> None:
self.keyid = keyid
dirpath = tempfile.mkdtemp()
self.gpg = gnupg.GPG(gnupghome=os.path.abspath(dirpath))
self.gpg.encoding = 'utf-8'
self.gpg.r... | none | 1 | 3.27645 | 3 |