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 |
|---|---|---|---|---|---|---|---|---|---|---|
toontown/fishing/FishCollection.py | TheFamiliarScoot/open-toontown | 99 | 9200 | from . import FishBase
from . import FishGlobals
class FishCollection:
def __init__(self):
self.fishList = []
def __len__(self):
return len(self.fishList)
def getFish(self):
return self.fishList
def makeFromNetLists(self, genusList, speciesList, weightList):
self.fis... | from . import FishBase
from . import FishGlobals
class FishCollection:
def __init__(self):
self.fishList = []
def __len__(self):
return len(self.fishList)
def getFish(self):
return self.fishList
def makeFromNetLists(self, genusList, speciesList, weightList):
self.fis... | none | 1 | 3.201076 | 3 | |
lead/strategies/strategy_base.py | M4gicT0/Distribute | 0 | 9201 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
#
# Distributed under terms of the MIT license.
"""
Strategy base class
"""
from abc import ABCMeta, abstractmethod
from tinydb import TinyDB, Query
from node import Node
import json
class Strategy(object):
def __init__(self, this_controller, thi... | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
#
# Distributed under terms of the MIT license.
"""
Strategy base class
"""
from abc import ABCMeta, abstractmethod
from tinydb import TinyDB, Query
from node import Node
import json
class Strategy(object):
def __init__(self, this_controller, thi... | en | 0.668957 | #! /usr/bin/env python # -*- coding: utf-8 -*- # vim:fenc=utf-8 # # # Distributed under terms of the MIT license. Strategy base class | 2.685189 | 3 |
project_euler/problem_01/sol6.py | mudit-chopra/Python | 0 | 9202 | <gh_stars>0
'''
Problem Statement:
If we list all the natural numbers below 10 that are multiples of 3 or 5,
we get 3,5,6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below N.
'''
from __future__ import print_function
try:
raw_input # Python 2
except NameError:
r... | '''
Problem Statement:
If we list all the natural numbers below 10 that are multiples of 3 or 5,
we get 3,5,6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below N.
'''
from __future__ import print_function
try:
raw_input # Python 2
except NameError:
raw_input = i... | en | 0.720321 | Problem Statement: If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3,5,6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below N. # Python 2 # Python 3 store multiples of 3 and 5 in a set and then add | 4.352981 | 4 |
jsonfallback/functions.py | laymonage/django-jsonfallback | 0 | 9203 | <reponame>laymonage/django-jsonfallback
import copy
from django.db import NotSupportedError
from django.db.models import Expression
from .fields import mysql_compile_json_path, postgres_compile_json_path, FallbackJSONField
class JSONExtract(Expression):
def __init__(self, expression, *path, output_field=Fallback... | import copy
from django.db import NotSupportedError
from django.db.models import Expression
from .fields import mysql_compile_json_path, postgres_compile_json_path, FallbackJSONField
class JSONExtract(Expression):
def __init__(self, expression, *path, output_field=FallbackJSONField(), **extra):
super()._... | zh | 0.159832 | #> %s'.format(arg_sql) | 2.099116 | 2 |
excelify/tests.py | pmbaumgartner/excelify | 11 | 9204 | <reponame>pmbaumgartner/excelify
import unittest
import tempfile
import pathlib
import datetime
import warnings
from IPython.testing.globalipapp import start_ipython, get_ipython
import pandas.util.testing as tm
from pandas.core.frame import DataFrame
from pandas.core.series import Series
from pandas import read_exce... | import unittest
import tempfile
import pathlib
import datetime
import warnings
from IPython.testing.globalipapp import start_ipython, get_ipython
import pandas.util.testing as tm
from pandas.core.frame import DataFrame
from pandas.core.series import Series
from pandas import read_excel
import pytest
ip = get_ipytho... | en | 0.979553 | # there is probably a better way to test this # this seems like a bad idea... | 2.228477 | 2 |
Easy/233/233.py | lw7360/dailyprogrammer | 0 | 9205 | # https://www.reddit.com/r/dailyprogrammer/comments/3ltee2/20150921_challenge_233_easy_the_house_that_ascii/
import random
import sys
def main():
data = open(sys.argv[1]).read().splitlines()[1::]
door = random.randrange(len(data[-1]))
wideData = []
for row in data:
curStr = ''
for... | # https://www.reddit.com/r/dailyprogrammer/comments/3ltee2/20150921_challenge_233_easy_the_house_that_ascii/
import random
import sys
def main():
data = open(sys.argv[1]).read().splitlines()[1::]
door = random.randrange(len(data[-1]))
wideData = []
for row in data:
curStr = ''
for... | en | 0.620112 | # https://www.reddit.com/r/dailyprogrammer/comments/3ltee2/20150921_challenge_233_easy_the_house_that_ascii/ | 3.38701 | 3 |
usr/callbacks/action/tools.py | uwitec/LEHome | 151 | 9206 | #!/usr/bin/env python
# encoding: utf-8
from __future__ import division
from decimal import Decimal
import subprocess
import threading
import urllib2
import urllib
import httplib
import json
import re
import hashlib
import base64
# import zlib
from lib.command.runtime import UserInput
from lib.helper.CameraHelper ... | #!/usr/bin/env python
# encoding: utf-8
from __future__ import division
from decimal import Decimal
import subprocess
import threading
import urllib2
import urllib
import httplib
import json
import re
import hashlib
import base64
# import zlib
from lib.command.runtime import UserInput
from lib.helper.CameraHelper ... | en | 0.562729 | #!/usr/bin/env python # encoding: utf-8 # import zlib # swift --insecure upload image data/capture/2015_05_23_001856.jpg #block / wait # for test # save_name = "2015_05_02_164052.jpg" | 2.105484 | 2 |
src/fix_code_1.py | Athenian-Computer-Science/numeric-operations-1-practice-template | 0 | 9207 | <gh_stars>0
#############################
# Collaborators: (enter people or resources who/that helped you)
# If none, write none
#
#
#############################
base = input('Enter the base: ")
height =
area = # Calculate the area of the triangle
print("The area of the triangle is (area).") | #############################
# Collaborators: (enter people or resources who/that helped you)
# If none, write none
#
#
#############################
base = input('Enter the base: ")
height =
area = # Calculate the area of the triangle
print("The area of the triangle is (area).") | en | 0.367387 | ############################# # Collaborators: (enter people or resources who/that helped you) # If none, write none # # ############################# # Calculate the area of the triangle | 3.955991 | 4 |
gputools/core/oclmultireduction.py | gmazzamuto/gputools | 89 | 9208 | <reponame>gmazzamuto/gputools
"""
an adaptation of pyopencl's reduction kernel for weighted avarages
like sum(a*b)
<EMAIL>
"""
from __future__ import print_function, unicode_literals, absolute_import, division
from six.moves import zip
import pyopencl as cl
from pyopencl.tools import (
context_dependent_memoize... | """
an adaptation of pyopencl's reduction kernel for weighted avarages
like sum(a*b)
<EMAIL>
"""
from __future__ import print_function, unicode_literals, absolute_import, division
from six.moves import zip
import pyopencl as cl
from pyopencl.tools import (
context_dependent_memoize,
dtype_to_ctype, KernelTe... | en | 0.36346 | an adaptation of pyopencl's reduction kernel for weighted avarages like sum(a*b) <EMAIL> # {{{ kernel source //CL// <% inds = range(len(map_exprs)) %> #define GROUP_SIZE ${group_size} % for i,m in enumerate(map_exprs): #define READ_AND_MAP_${i}(i) (${m}) % endfor #define REDUCE(a, b)... | 2.175873 | 2 |
mineshaft.py | DidymusRex/PiCraft | 0 | 9209 | #! /usr/bin/env python
import mcpi.minecraft as minecraft
import mcpi.block as block
import random
import time
mc = minecraft.Minecraft.create()
# ----------------------------------------------------------------------
# S E T U P
# ----------------------------------------------------------------------
# Where Am ... | #! /usr/bin/env python
import mcpi.minecraft as minecraft
import mcpi.block as block
import random
import time
mc = minecraft.Minecraft.create()
# ----------------------------------------------------------------------
# S E T U P
# ----------------------------------------------------------------------
# Where Am ... | en | 0.162243 | #! /usr/bin/env python # ---------------------------------------------------------------------- # S E T U P # ---------------------------------------------------------------------- # Where Am I? | 2.566413 | 3 |
example/example01.py | ChenglongChen/TextRank4ZH | 2 | 9210 | #-*- encoding:utf-8 -*-
from __future__ import print_function
import sys
try:
reload(sys)
sys.setdefaultencoding('utf-8')
except:
pass
import codecs
from textrank4zh import TextRank4Keyword, TextRank4Sentence
text = codecs.open('../test/doc/01.txt', 'r', 'utf-8').read()
tr4w = TextRank4Keyword()
tr4w.an... | #-*- encoding:utf-8 -*-
from __future__ import print_function
import sys
try:
reload(sys)
sys.setdefaultencoding('utf-8')
except:
pass
import codecs
from textrank4zh import TextRank4Keyword, TextRank4Sentence
text = codecs.open('../test/doc/01.txt', 'r', 'utf-8').read()
tr4w = TextRank4Keyword()
tr4w.an... | zh | 0.312402 | #-*- encoding:utf-8 -*- # py2中text必须是utf8编码的str或者unicode对象,py3中必须是utf8编码的bytes或者str对象 | 3.023639 | 3 |
scripts/anonymize_dumpdata.py | suutari-ai/respa | 1 | 9211 | import random
import uuid
import sys
import json
from faker import Factory
from faker.providers.person.fi_FI import Provider as PersonProvider
fake = Factory.create('fi_FI')
email_by_user = {}
users_by_id = {}
def anonymize_users(users):
usernames = set()
emails = set()
for data in users:
if data... | import random
import uuid
import sys
import json
from faker import Factory
from faker.providers.person.fi_FI import Provider as PersonProvider
fake = Factory.create('fi_FI')
email_by_user = {}
users_by_id = {}
def anonymize_users(users):
usernames = set()
emails = set()
for data in users:
if data... | none | 1 | 2.461199 | 2 | |
torch_geometric/utils/negative_sampling.py | NucciTheBoss/pytorch_geometric | 2,350 | 9212 | import random
from typing import Optional, Tuple, Union
import numpy as np
import torch
from torch import Tensor
from torch_geometric.utils import coalesce, degree, remove_self_loops
from .num_nodes import maybe_num_nodes
def negative_sampling(edge_index: Tensor,
num_nodes: Optional[Union[int... | import random
from typing import Optional, Tuple, Union
import numpy as np
import torch
from torch import Tensor
from torch_geometric.utils import coalesce, degree, remove_self_loops
from .num_nodes import maybe_num_nodes
def negative_sampling(edge_index: Tensor,
num_nodes: Optional[Union[int... | en | 0.682934 | Samples random negative edges of a graph given by :attr:`edge_index`. Args: edge_index (LongTensor): The edge indices. num_nodes (int or Tuple[int, int], optional): The number of nodes, *i.e.* :obj:`max_val + 1` of :attr:`edge_index`. If given as a tuple, then :obj:`edge_ind... | 2.7012 | 3 |
venv/Lib/site-packages/pafy/g.py | DavidJohnKelly/YoutubeDownloader | 2 | 9213 | import sys
if sys.version_info[:2] >= (3, 0):
# pylint: disable=E0611,F0401,I0011
from urllib.request import build_opener
else:
from urllib2 import build_opener
from . import __version__
urls = {
'gdata': "https://www.googleapis.com/youtube/v3/",
'watchv': "http://www.youtube.com/watch?v=%s",
... | import sys
if sys.version_info[:2] >= (3, 0):
# pylint: disable=E0611,F0401,I0011
from urllib.request import build_opener
else:
from urllib2 import build_opener
from . import __version__
urls = {
'gdata': "https://www.googleapis.com/youtube/v3/",
'watchv': "http://www.youtube.com/watch?v=%s",
... | en | 0.747965 | # pylint: disable=E0611,F0401,I0011 # For internal backend # 5 hours # The following are specific to the internal backend | 2.257034 | 2 |
src/cowrie/telnet/userauth.py | uwacyber/cowrie | 2,316 | 9214 | <gh_stars>1000+
# Copyright (C) 2015, 2016 GoSecure Inc.
"""
Telnet Transport and Authentication for the Honeypot
@author: <NAME> <<EMAIL>>
"""
from __future__ import annotations
import struct
from twisted.conch.telnet import (
ECHO,
LINEMODE,
NAWS,
SGA,
AuthenticatingTelnetProtocol,
ITelnet... | # Copyright (C) 2015, 2016 GoSecure Inc.
"""
Telnet Transport and Authentication for the Honeypot
@author: <NAME> <<EMAIL>>
"""
from __future__ import annotations
import struct
from twisted.conch.telnet import (
ECHO,
LINEMODE,
NAWS,
SGA,
AuthenticatingTelnetProtocol,
ITelnetProtocol,
)
from... | en | 0.76378 | # Copyright (C) 2015, 2016 GoSecure Inc. Telnet Transport and Authentication for the Honeypot @author: <NAME> <<EMAIL>> TelnetAuthProtocol that takes care of Authentication. Once authenticated this protocol is replaced with HoneyPotTelnetSession. # self.transport.negotiationMap[NAWS] = self.telnet_NAWS # Initial o... | 1.775027 | 2 |
authcheck/app/model/exception.py | flyr4nk/secscan-authcheck | 572 | 9215 | class WebException(Exception):
pass
class ParserException(Exception):
"""
解析异常
"""
pass
class ApiException(Exception):
"""
api异常
"""
pass
class WsException(Exception):
"""
轮询异常
"""
pass
class SsoException(Exception):
"""
sso异... | class WebException(Exception):
pass
class ParserException(Exception):
"""
解析异常
"""
pass
class ApiException(Exception):
"""
api异常
"""
pass
class WsException(Exception):
"""
轮询异常
"""
pass
class SsoException(Exception):
"""
sso异... | zh | 0.641399 | 解析异常 api异常 轮询异常 sso异常 lib异常 账号异常(账号失效) 认证流量异常 | 1.955626 | 2 |
p_io.py | JeremyBuchanan/psf-photometry-pipeline | 0 | 9216 | <filename>p_io.py<gh_stars>0
import astropy.io.fits as fits
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import obj_data as od
import saphires as saph
from astropy.time import Time
from astropy.visualization import ZScaleInterval, SqrtStretch, ImageNormalize
from matplotlib.backends.backend_pdf ... | <filename>p_io.py<gh_stars>0
import astropy.io.fits as fits
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import obj_data as od
import saphires as saph
from astropy.time import Time
from astropy.visualization import ZScaleInterval, SqrtStretch, ImageNormalize
from matplotlib.backends.backend_pdf ... | en | 0.824411 | Writes a new fits file including the image data and and updated header for the new image Parameters ---------- fn: string The desired file name of the new fits file data: array-like Contains all the image data Returns ------- avg_airm... | 2.455753 | 2 |
sympy/polys/tests/test_monomialtools.py | ichuang/sympy | 1 | 9217 | <gh_stars>1-10
"""Tests for tools and arithmetics for monomials of distributed polynomials. """
from sympy.polys.monomialtools import (
monomials, monomial_count,
monomial_key, lex, grlex, grevlex,
monomial_mul, monomial_div,
monomial_gcd, monomial_lcm,
monomial_max, monomial_min,
monomial_divi... | """Tests for tools and arithmetics for monomials of distributed polynomials. """
from sympy.polys.monomialtools import (
monomials, monomial_count,
monomial_key, lex, grlex, grevlex,
monomial_mul, monomial_div,
monomial_gcd, monomial_lcm,
monomial_max, monomial_min,
monomial_divides,
Monomi... | en | 0.920156 | Tests for tools and arithmetics for monomials of distributed polynomials. | 2.569867 | 3 |
Solutions/TenableIO/Data Connectors/azure_sentinel.py | johnbilliris/Azure-Sentinel | 2,227 | 9218 | <reponame>johnbilliris/Azure-Sentinel
import re
import base64
import hmac
import hashlib
import logging
import requests
from datetime import datetime
class AzureSentinel:
def __init__(self, workspace_id, workspace_key, log_type, log_analytics_url=''):
self._workspace_id = workspace_id
self._works... | import re
import base64
import hmac
import hashlib
import logging
import requests
from datetime import datetime
class AzureSentinel:
def __init__(self, workspace_id, workspace_key, log_type, log_analytics_url=''):
self._workspace_id = workspace_id
self._workspace_key = workspace_key
self.... | none | 1 | 2.413461 | 2 | |
MiniProject.py | siddharths067/CNN-Based-Agent-Modelling-for-Humanlike-Driving-Simulaion | 0 | 9219 | from tkinter import *
from PIL import ImageGrab
import numpy as np
import cv2
import time
import pyautogui as pg
import DirectInputRoutines as DIR
from LogKey import key_check
last_time = time.time()
one_hot = [0, 0, 0, 0, 0, 0]
hash_dict = {'w':0, 's':1, 'a':2, 'd':3, 'c':4, 'v':5}
X = []
y = []
def a... | from tkinter import *
from PIL import ImageGrab
import numpy as np
import cv2
import time
import pyautogui as pg
import DirectInputRoutines as DIR
from LogKey import key_check
last_time = time.time()
one_hot = [0, 0, 0, 0, 0, 0]
hash_dict = {'w':0, 's':1, 'a':2, 'd':3, 'c':4, 'v':5}
X = []
y = []
def a... | en | 0.530488 | # compute the median of the single channel pixel intensities # apply automatic Canny edge detection using the computed median # return the edged image #processed_img = cv2.Canny(processed_img, threshold1=200, threshold2=300) # more info: http://docs.opencv.org/3.0-beta/doc/py_tutorials/py_imgproc/py_houghlines/py_hough... | 2.577406 | 3 |
src/code/djangotest/migrations/0001_initial.py | jielyu/notebook | 2 | 9220 | # Generated by Django 2.2.5 on 2019-10-05 23:22
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Password',
fields=[
('id', models.IntegerFi... | # Generated by Django 2.2.5 on 2019-10-05 23:22
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Password',
fields=[
('id', models.IntegerFi... | en | 0.765609 | # Generated by Django 2.2.5 on 2019-10-05 23:22 | 1.878663 | 2 |
filer/tests/utils/__init__.py | pbs/django-filer | 1 | 9221 | <reponame>pbs/django-filer<filename>filer/tests/utils/__init__.py
from django.template.loaders.base import Loader as BaseLoader
from django.template.base import TemplateDoesNotExist
class Mock():
pass
class MockLoader(BaseLoader):
is_usable = True
def load_template_source(self, template_name, template... | from django.template.loaders.base import Loader as BaseLoader
from django.template.base import TemplateDoesNotExist
class Mock():
pass
class MockLoader(BaseLoader):
is_usable = True
def load_template_source(self, template_name, template_dirs=None):
if template_name == 'cms_mock_template.html':... | none | 1 | 2.205818 | 2 | |
utils/arrival_overlaps.py | davmre/sigvisa | 0 | 9222 | <gh_stars>0
import sigvisa.database.db
from sigvisa.database.dataset import *
import sigvisa.utils.geog
cursor = database.db.connect().cursor()
detections, arid2num = read_detections(cursor, 1237680000, 1237680000 + 168 * 3600, arrival_table="leb_arrival", noarrays=False)
last_det = dict()
overlaps = 0
for det in de... | import sigvisa.database.db
from sigvisa.database.dataset import *
import sigvisa.utils.geog
cursor = database.db.connect().cursor()
detections, arid2num = read_detections(cursor, 1237680000, 1237680000 + 168 * 3600, arrival_table="leb_arrival", noarrays=False)
last_det = dict()
overlaps = 0
for det in detections:
... | none | 1 | 2.524465 | 3 | |
tests/transformation/streamline/test_move_identical_op_past_join_op.py | mmrahorovic/finn | 109 | 9223 | import pytest
from onnx import TensorProto
from onnx import helper as oh
import finn.core.onnx_exec as oxe
from finn.core.modelwrapper import ModelWrapper
from finn.transformation.streamline.reorder import MoveTransposePastJoinAdd
from finn.util.basic import gen_finn_dt_tensor
def create_model(perm):
if perm ==... | import pytest
from onnx import TensorProto
from onnx import helper as oh
import finn.core.onnx_exec as oxe
from finn.core.modelwrapper import ModelWrapper
from finn.transformation.streamline.reorder import MoveTransposePastJoinAdd
from finn.util.basic import gen_finn_dt_tensor
def create_model(perm):
if perm ==... | en | 0.865581 | # Permutation of transpose node # Create input data # Note: it is assumed that both tensors have the same shape and data type # Check if order changed | 2.119054 | 2 |
app/lib/ncr_util.py | jchrisfarris/antiope-scorecards | 1 | 9224 | <filename>app/lib/ncr_util.py<gh_stars>1-10
import json
from lib import authz
from lib.logger import logger
from lib.exclusions import exclusions, state_machine
def get_allowed_actions(user, account_id, requirement, exclusion):
allowed_actions = {
'remediate': False,
'requestExclusion': False,
... | <filename>app/lib/ncr_util.py<gh_stars>1-10
import json
from lib import authz
from lib.logger import logger
from lib.exclusions import exclusions, state_machine
def get_allowed_actions(user, account_id, requirement, exclusion):
allowed_actions = {
'remediate': False,
'requestExclusion': False,
... | en | 0.848518 | # Determine If can remediate Mehtod to validate whether a requirement is capable of being remediated. :param requirement: The dict representing the requirement to check. :returns bool: A boolean representing whether requirement can or cannot be remediated. | 2.263177 | 2 |
ambari-server/src/test/python/stacks/2.6/SPARK2/test_spark_livy2.py | Syndra/Ambari-source | 1 | 9225 | #!/usr/bin/env python
'''
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 (the
"License")... | #!/usr/bin/env python
'''
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 (the
"License")... | en | 0.671418 | #!/usr/bin/env python 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 (the "License"); you... | 1.644628 | 2 |
SentDex/Chapter05.py | harimaruthachalam/SentDexChapters | 0 | 9226 | import quandl
import math
import numpy as np
from sklearn import preprocessing, cross_validation, svm
from sklearn.linear_model import LinearRegression
import pickle
import datetime
from matplotlib import style
import matplotlib.pyplot as plot
# Config
isLoadFromLocal = True
quandl.ApiConfig.api_key = '<KEY>'
style.us... | import quandl
import math
import numpy as np
from sklearn import preprocessing, cross_validation, svm
from sklearn.linear_model import LinearRegression
import pickle
import datetime
from matplotlib import style
import matplotlib.pyplot as plot
# Config
isLoadFromLocal = True
quandl.ApiConfig.api_key = '<KEY>'
style.us... | en | 0.331353 | # Config # Loading data # Data pre-processing # df['label'].plot() # df[forecastCol].plot() # plot.legend(loc = 4) # plot.show() # Regression # classifier = svm.SVR(kernel='linear') # SVM SVR # Linear Regression # seconds in a day | 2.489586 | 2 |
tifinity/actions/icc_parser.py | pmay/tifinity | 1 | 9227 | <reponame>pmay/tifinity
class IccProfile():
"""Parses an ICC Colour Profile.
According to spec: all Profile data shall be encoded as big-endian"""
def __init__(self, bytes):
self.header = {}
self.parse_icc(bytes)
def get_colour_space(self):
"""Returns the data colour space t... | class IccProfile():
"""Parses an ICC Colour Profile.
According to spec: all Profile data shall be encoded as big-endian"""
def __init__(self, bytes):
self.header = {}
self.parse_icc(bytes)
def get_colour_space(self):
"""Returns the data colour space type, or None if not defi... | en | 0.561022 | Parses an ICC Colour Profile. According to spec: all Profile data shall be encoded as big-endian Returns the data colour space type, or None if not defined Parsers the specified bytes representing an ICC Profile # ICC profile consists of: # - 128-byte profile header # - profile tag table: # - profile tagged e... | 2.951652 | 3 |
challenges/binary_search/test_binary_search.py | asakatida/data-structures-and-algorithms.py | 0 | 9228 | from .binary_search import binary_search
def test_binary_search_empty_array():
assert binary_search([], 0) == -1
def test_binary_search_find_single_array():
assert binary_search([3], 3) == 0
def test_binary_search_not_found_single_array():
assert binary_search([1], 0) == -1
def test_binary_search_no... | from .binary_search import binary_search
def test_binary_search_empty_array():
assert binary_search([], 0) == -1
def test_binary_search_find_single_array():
assert binary_search([3], 3) == 0
def test_binary_search_not_found_single_array():
assert binary_search([1], 0) == -1
def test_binary_search_no... | none | 1 | 3.565735 | 4 | |
Module2.py | Cipalex/session3 | 0 | 9229 | def f():
print('f from module 2')
if __name__ == '__main__':
print('Module 2') | def f():
print('f from module 2')
if __name__ == '__main__':
print('Module 2') | none | 1 | 1.750569 | 2 | |
analisis_de_variables.py | scmarquez/Hause-Price-Kaggle-Competition | 0 | 9230 | <filename>analisis_de_variables.py
# -*- coding: utf-8 -*-
"""
Created on Fri Dec 29 16:40:53 2017
@author: Sergio
"""
#Analisis de variables
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn import ensemble, tree, linear_model
from sklearn.model_se... | <filename>analisis_de_variables.py
# -*- coding: utf-8 -*-
"""
Created on Fri Dec 29 16:40:53 2017
@author: Sergio
"""
#Analisis de variables
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn import ensemble, tree, linear_model
from sklearn.model_se... | es | 0.956916 | # -*- coding: utf-8 -*- Created on Fri Dec 29 16:40:53 2017
@author: Sergio #Analisis de variables #Ignorar los warnings #Lectura de los datos #En train se guandan los datos con los que se entrenará al modelo #En test se guarda el conjunto de datos para el test #Primero hay que eliminar las varibles que tengan un nú... | 3.003461 | 3 |
query-gen.py | mdatsev/prostgres | 0 | 9231 | import random
import sys
ntables = 100
ncols = 100
nrows = 10000
def printstderr(s):
sys.stderr.write(s + '\n')
sys.stderr.flush()
def get_value():
return random.randint(-99999999, 99999999)
for t in range(ntables):
printstderr(f'{t}/{ntables}')
print(f"create table x ({','.join(['x int'] * ncols)});")
... | import random
import sys
ntables = 100
ncols = 100
nrows = 10000
def printstderr(s):
sys.stderr.write(s + '\n')
sys.stderr.flush()
def get_value():
return random.randint(-99999999, 99999999)
for t in range(ntables):
printstderr(f'{t}/{ntables}')
print(f"create table x ({','.join(['x int'] * ncols)});")
... | en | 0.709244 | # 10 min to generate # 3 min to process | 2.656802 | 3 |
molecule/default/tests/test_default.py | joshbenner/sensu-ansible-role | 0 | 9232 | import os
import testinfra.utils.ansible_runner
testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(
os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all')
def test_packages(host):
package = host.package('sensu')
assert package.is_installed
assert '1.7.0' in package.version
def test_di... | import os
import testinfra.utils.ansible_runner
testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(
os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all')
def test_packages(host):
package = host.package('sensu')
assert package.is_installed
assert '1.7.0' in package.version
def test_di... | en | 0.825089 | # Tests extension install/enable | 1.981148 | 2 |
wgskex/worker/netlink.py | moepman/wgskex | 2 | 9233 | <filename>wgskex/worker/netlink.py
import hashlib
import logging
import re
from dataclasses import dataclass
from datetime import datetime, timedelta
from textwrap import wrap
from typing import Dict, List
from pyroute2 import IPRoute, NDB, WireGuard
from wgskex.common.utils import mac2eui64
logger = logging.getLogg... | <filename>wgskex/worker/netlink.py
import hashlib
import logging
import re
from dataclasses import dataclass
from datetime import datetime, timedelta
from textwrap import wrap
from typing import Dict, List
from pyroute2 import IPRoute, NDB, WireGuard
from wgskex.common.utils import mac2eui64
logger = logging.getLogg... | en | 0.618362 | # TODO make loglevel configurable WireGuardClient describes complete configuration for a specific WireGuard client Attributes: public_key: WireGuard Public key domain: Domain Name of the WireGuard peer lladdr: IPv6 lladdr of the WireGuard peer wg_interface: Name of the WireGuard int... | 2.233167 | 2 |
api/main.py | Ju99ernaut/super-fastapi | 0 | 9234 | import uvicorn
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from routes import items
import config
from constants import *
config.parse_args()
app = FastAPI(
title="API",
description="API boilerplate",
version="1.0.0",
openapi_tags=API_TAGS_METADATA,
)
app.add_midd... | import uvicorn
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from routes import items
import config
from constants import *
config.parse_args()
app = FastAPI(
title="API",
description="API boilerplate",
version="1.0.0",
openapi_tags=API_TAGS_METADATA,
)
app.add_midd... | none | 1 | 2.355385 | 2 | |
gellifinsta/models.py | vallka/djellifique | 0 | 9235 | from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.utils.html import mark_safe
# Create your models here.
class Gellifinsta(models.Model):
class Meta:
ordering = ['-taken_at_datetime']
shortcode = models.CharField(_("Shortcode"), max_length=20)
taken_... | from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.utils.html import mark_safe
# Create your models here.
class Gellifinsta(models.Model):
class Meta:
ordering = ['-taken_at_datetime']
shortcode = models.CharField(_("Shortcode"), max_length=20)
taken_... | en | 0.963489 | # Create your models here. | 2.129928 | 2 |
scanBase/migrations/0003_ipsection.py | wsqy/sacn_server | 0 | 9236 | # -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2018-01-16 13:35
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('scanBase', '0002_auto_20180116_1321'),
]
operations ... | # -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2018-01-16 13:35
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('scanBase', '0002_auto_20180116_1321'),
]
operations ... | en | 0.749519 | # -*- coding: utf-8 -*- # Generated by Django 1.11 on 2018-01-16 13:35 | 1.635085 | 2 |
sts/train.py | LostCow/KLUE | 18 | 9237 | <filename>sts/train.py
import argparse
import numpy as np
import os
import torch
from transformers import AutoTokenizer, AutoConfig, Trainer, TrainingArguments
from model import RobertaForStsRegression
from dataset import KlueStsWithSentenceMaskDataset
from utils import read_json, seed_everything
from metric import c... | <filename>sts/train.py
import argparse
import numpy as np
import os
import torch
from transformers import AutoTokenizer, AutoConfig, Trainer, TrainingArguments
from model import RobertaForStsRegression
from dataset import KlueStsWithSentenceMaskDataset
from utils import read_json, seed_everything
from metric import c... | en | 0.241452 | # data_arg # train_arg # eval_arg | 2.140695 | 2 |
test/test_base_client.py | walkr/nanoservice | 28 | 9238 | import unittest
from nanoservice import Responder
from nanoservice import Requester
class BaseTestCase(unittest.TestCase):
def setUp(self):
addr = 'inproc://test'
self.client = Requester(addr)
self.service = Responder(addr)
self.service.register('divide', lambda x, y: x / y)
... | import unittest
from nanoservice import Responder
from nanoservice import Requester
class BaseTestCase(unittest.TestCase):
def setUp(self):
addr = 'inproc://test'
self.client = Requester(addr)
self.service = Responder(addr)
self.service.register('divide', lambda x, y: x / y)
... | en | 0.412248 | # Requester side ops # Responder side ops | 2.779106 | 3 |
airtech_api/flight/models.py | chidioguejiofor/airtech-api | 1 | 9239 | <reponame>chidioguejiofor/airtech-api<filename>airtech_api/flight/models.py<gh_stars>1-10
from airtech_api.utils.auditable_model import AuditableBaseModel
from django.db import models
# Create your models here.
class Flight(AuditableBaseModel):
class Meta:
db_table = 'Flight'
capacity = models.Intege... | from airtech_api.utils.auditable_model import AuditableBaseModel
from django.db import models
# Create your models here.
class Flight(AuditableBaseModel):
class Meta:
db_table = 'Flight'
capacity = models.IntegerField(null=False)
location = models.TextField(null=False)
destination = models.Te... | en | 0.963489 | # Create your models here. | 2.464812 | 2 |
Sensor Fusion and Tracking/Kalman Filters/Gaussian/gaussian.py | kaka-lin/autonomous-driving-notes | 0 | 9240 | <reponame>kaka-lin/autonomous-driving-notes
import numpy as np
import matplotlib.pyplot as plt
def gaussian(x, mean, std):
std2 = np.power(std, 2)
return (1 / np.sqrt(2* np.pi * std2)) * np.exp(-.5 * (x - mean)**2 / std2)
if __name__ == "__main__":
gauss_1 = gaussian(10, 8, 2) # 0.12098536225957168
... | import numpy as np
import matplotlib.pyplot as plt
def gaussian(x, mean, std):
std2 = np.power(std, 2)
return (1 / np.sqrt(2* np.pi * std2)) * np.exp(-.5 * (x - mean)**2 / std2)
if __name__ == "__main__":
gauss_1 = gaussian(10, 8, 2) # 0.12098536225957168
gauss_2 = gaussian(10, 10, 2) # 0.1994711402... | en | 0.698393 | # 0.12098536225957168 # 0.19947114020071635 # 標準高斯分佈 # Plot between -10 and 10 with .001 steps. | 3.926603 | 4 |
part19/test_interpreter.py | fazillatheef/lsbasi | 1,682 | 9241 | import unittest
class LexerTestCase(unittest.TestCase):
def makeLexer(self, text):
from spi import Lexer
lexer = Lexer(text)
return lexer
def test_tokens(self):
from spi import TokenType
records = (
('234', TokenType.INTEGER_CONST, 234),
('3.14'... | import unittest
class LexerTestCase(unittest.TestCase):
def makeLexer(self, text):
from spi import Lexer
lexer = Lexer(text)
return lexer
def test_tokens(self):
from spi import TokenType
records = (
('234', TokenType.INTEGER_CONST, 234),
('3.14'... | en | 0.177074 | PROGRAM Test; VAR a : INTEGER; BEGIN a := 10 * ; {Invalid syntax} END. PROGRAM Test; VAR a : INTEGER; BEGIN a := 1 (1 + 2); {Invalid syntax} END. # zero VARs PROGRAM Test; B... | 2.794416 | 3 |
bot_components/configurator.py | Ferlern/Arctic-Tundra | 3 | 9242 | <reponame>Ferlern/Arctic-Tundra
import json
from typing import TypedDict
from .bot_emoji import AdditionalEmoji
class Warn(TypedDict):
text: str
mute_time: int
ban: bool
class PersonalVoice(TypedDict):
categoty: int
price: int
slot_price: int
bitrate_price: int
class System(TypedDict):... | import json
from typing import TypedDict
from .bot_emoji import AdditionalEmoji
class Warn(TypedDict):
text: str
mute_time: int
ban: bool
class PersonalVoice(TypedDict):
categoty: int
price: int
slot_price: int
bitrate_price: int
class System(TypedDict):
token: str
initial_exte... | none | 1 | 2.456306 | 2 | |
recnn/utils/plot.py | ihash5/reinforcement-learning | 1 | 9243 | <filename>recnn/utils/plot.py
from scipy.spatial import distance
from scipy import ndimage
import matplotlib.pyplot as plt
import torch
from scipy import stats
import numpy as np
def pairwise_distances_fig(embs):
embs = embs.detach().cpu().numpy()
similarity_matrix_cos = distance.cdist(embs, embs, 'cosine')
... | <filename>recnn/utils/plot.py
from scipy.spatial import distance
from scipy import ndimage
import matplotlib.pyplot as plt
import torch
from scipy import stats
import numpy as np
def pairwise_distances_fig(embs):
embs = embs.detach().cpu().numpy()
similarity_matrix_cos = distance.cdist(embs, embs, 'cosine')
... | en | 0.815321 | # Weight between 0 and 1 # First value in the plot (first timestep) # Calculate smoothed value # Save it # Anchor the last smoothed value | 2.36012 | 2 |
tests/integration/insights/v1/call/test_metric.py | pazzy-stack/twilio | 0 | 9244 | <gh_stars>0
# coding=utf-8
r"""
This code was generated by
\ / _ _ _| _ _
| (_)\/(_)(_|\/| |(/_ v1.0.0
/ /
"""
from tests import IntegrationTestCase
from tests.holodeck import Request
from twilio.base.exceptions import TwilioException
from twilio.http.response import Response
class MetricTestCas... | # coding=utf-8
r"""
This code was generated by
\ / _ _ _| _ _
| (_)\/(_)(_|\/| |(/_ v1.0.0
/ /
"""
from tests import IntegrationTestCase
from tests.holodeck import Request
from twilio.base.exceptions import TwilioException
from twilio.http.response import Response
class MetricTestCase(Integratio... | en | 0.571334 | # coding=utf-8 This code was generated by \ / _ _ _| _ _ | (_)\/(_)(_|\/| |(/_ v1.0.0 / / { "meta": { "page": 0, "page_size": 50, "first_page_url": "https://insights.twilio.com/v1/Voice/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Me... | 2.276583 | 2 |
2017-2018/lecture-notes/python/02-algorithms_listing_8_contains_word.py | essepuntato/comp-think | 19 | 9245 | def contains_word(first_word, second_word, bibliographic_entry):
contains_first_word = first_word in bibliographic_entry
contains_second_word = second_word in bibliographic_entry
if contains_first_word and contains_second_word:
return 2
elif contains_first_word or contains_second_word:
... | def contains_word(first_word, second_word, bibliographic_entry):
contains_first_word = first_word in bibliographic_entry
contains_second_word = second_word in bibliographic_entry
if contains_first_word and contains_second_word:
return 2
elif contains_first_word or contains_second_word:
... | none | 1 | 4.123122 | 4 | |
backend/user/scripter.py | ivaivalous/ivodb | 0 | 9246 | <filename>backend/user/scripter.py<gh_stars>0
#!/usr/bin/env python
import responses
from selenium import webdriver
# This file contains/references the default JS
# used to provide functions dealing with input/output
SCRIPT_RUNNER = "runner.html"
ENCODING = 'utf-8'
PAGE_LOAD_TIMEOUT = 5
PAGE_LOAD_TIMEOUT_MS = PAGE_L... | <filename>backend/user/scripter.py<gh_stars>0
#!/usr/bin/env python
import responses
from selenium import webdriver
# This file contains/references the default JS
# used to provide functions dealing with input/output
SCRIPT_RUNNER = "runner.html"
ENCODING = 'utf-8'
PAGE_LOAD_TIMEOUT = 5
PAGE_LOAD_TIMEOUT_MS = PAGE_L... | en | 0.437611 | #!/usr/bin/env python # This file contains/references the default JS # used to provide functions dealing with input/output window.requestData = {{method:"{0}", headers:{1}, data:"{2}", params:{3}}}; window.method = requestData.method; window.headers = requestData.headers; window.data = requestData.data; ... | 2.673718 | 3 |
bwtougu/api/names.py | luhouxiang/byrobot | 0 | 9247 | <reponame>luhouxiang/byrobot
#!/usr/bin/env python
# -*- coding: utf-8 -*-
VALID_HISTORY_FIELDS = [
'datetime', 'open', 'close', 'high', 'low', 'total_turnover', 'volume',
'acc_net_value', 'discount_rate', 'unit_net_value',
'limit_up', 'limit_down', 'open_interest', 'basis_spread', 'settlement', 'prev_sett... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
VALID_HISTORY_FIELDS = [
'datetime', 'open', 'close', 'high', 'low', 'total_turnover', 'volume',
'acc_net_value', 'discount_rate', 'unit_net_value',
'limit_up', 'limit_down', 'open_interest', 'basis_spread', 'settlement', 'prev_settlement'
]
VALID_GET_PRICE_FI... | en | 0.352855 | #!/usr/bin/env python # -*- coding: utf-8 -*- | 1.291581 | 1 |
src/PeerRead/data_cleaning/process_PeerRead_abstracts.py | dveni/causal-text-embeddings | 114 | 9248 | <filename>src/PeerRead/data_cleaning/process_PeerRead_abstracts.py
"""
Simple pre-processing for PeerRead papers.
Takes in JSON formatted data from ScienceParse and outputs a tfrecord
Reference example:
https://github.com/tensorlayer/tensorlayer/blob/9528da50dfcaf9f0f81fba9453e488a1e6c8ee8f/examples/data_process/tuto... | <filename>src/PeerRead/data_cleaning/process_PeerRead_abstracts.py
"""
Simple pre-processing for PeerRead papers.
Takes in JSON formatted data from ScienceParse and outputs a tfrecord
Reference example:
https://github.com/tensorlayer/tensorlayer/blob/9528da50dfcaf9f0f81fba9453e488a1e6c8ee8f/examples/data_process/tuto... | en | 0.795163 | Simple pre-processing for PeerRead papers. Takes in JSON formatted data from ScienceParse and outputs a tfrecord Reference example: https://github.com/tensorlayer/tensorlayer/blob/9528da50dfcaf9f0f81fba9453e488a1e6c8ee8f/examples/data_process/tutorial_tfrecord3.py # tokenize PeerRead features # missing titles are qui... | 2.82543 | 3 |
app/packageB/__init__.py | An7ar35/python-app-skeleton-structure | 0 | 9249 | <reponame>An7ar35/python-app-skeleton-structure<gh_stars>0
__all__=['module1'] | __all__=['module1'] | none | 1 | 1.050038 | 1 | |
lib/shop.py | ZakDoesGaming/OregonTrail | 6 | 9250 | from pygame import Surface, font
from copy import copy
from random import randint, choice
import string
from lib.transactionButton import TransactionButton
SHOP_PREFIX = ["archer", "baker", "fisher", "miller", "rancher", "robber"]
SHOP_SUFFIX = ["cave", "creek", "desert", "farm", "field", "forest", "hill", "lake", "m... | from pygame import Surface, font
from copy import copy
from random import randint, choice
import string
from lib.transactionButton import TransactionButton
SHOP_PREFIX = ["archer", "baker", "fisher", "miller", "rancher", "robber"]
SHOP_SUFFIX = ["cave", "creek", "desert", "farm", "field", "forest", "hill", "lake", "m... | none | 1 | 3.112693 | 3 | |
core/dataflow/test/test_runners.py | ajmal017/amp | 0 | 9251 | <gh_stars>0
import logging
import numpy as np
import core.dataflow as dtf
import helpers.unit_test as hut
_LOG = logging.getLogger(__name__)
class TestRollingFitPredictDagRunner(hut.TestCase):
def test1(self) -> None:
"""
Test the DagRunner using `ArmaReturnsBuilder`
"""
dag_bu... | import logging
import numpy as np
import core.dataflow as dtf
import helpers.unit_test as hut
_LOG = logging.getLogger(__name__)
class TestRollingFitPredictDagRunner(hut.TestCase):
def test1(self) -> None:
"""
Test the DagRunner using `ArmaReturnsBuilder`
"""
dag_builder = dtf.... | en | 0.736492 | Test the DagRunner using `ArmaReturnsBuilder` # Test the DagRunner using `ArmaReturnsBuilder` # Create DAG and generate fit state. # # Check that dataframe results of `col` do not retroactively change # over successive prediction steps (which would suggest future # peeking). | 2.193833 | 2 |
Main Project/Main_Program.py | hmnk-1967/OCR-Python-Project-CS-BUIC | 0 | 9252 | import tkinter.messagebox
from tkinter import *
import tkinter as tk
from tkinter import filedialog
import numpy
import pytesseract #Python wrapper for Google-owned OCR engine known by the name of Tesseract.
import cv2
from PIL import Image, ImageTk
import os
root = tk.Tk()
root.title("Object Character Recognizer")
ro... | import tkinter.messagebox
from tkinter import *
import tkinter as tk
from tkinter import filedialog
import numpy
import pytesseract #Python wrapper for Google-owned OCR engine known by the name of Tesseract.
import cv2
from PIL import Image, ImageTk
import os
root = tk.Tk()
root.title("Object Character Recognizer")
ro... | en | 0.865062 | #Python wrapper for Google-owned OCR engine known by the name of Tesseract. #OEM stands for OCR Engine Mode and PSM stands for Page Segmentation Mode. #OEM defines what kind of OCR engine is to be used (this defines the dataset that would be used to cross-match #the available data with the testing data). #PSM defines h... | 3.072035 | 3 |
third_party/nasm/workspace.bzl | wainshine/tensorflow | 54 | 9253 | """loads the nasm library, used by TF."""
load("//third_party:repo.bzl", "tf_http_archive")
def repo():
tf_http_archive(
name = "nasm",
urls = [
"https://storage.googleapis.com/mirror.tensorflow.org/www.nasm.us/pub/nasm/releasebuilds/2.13.03/nasm-2.13.03.tar.bz2",
"http://p... | """loads the nasm library, used by TF."""
load("//third_party:repo.bzl", "tf_http_archive")
def repo():
tf_http_archive(
name = "nasm",
urls = [
"https://storage.googleapis.com/mirror.tensorflow.org/www.nasm.us/pub/nasm/releasebuilds/2.13.03/nasm-2.13.03.tar.bz2",
"http://p... | en | 0.929398 | loads the nasm library, used by TF. | 1.540133 | 2 |
python/tests/test-1-vector.py | wence-/libCEED | 0 | 9254 | # Copyright (c) 2017, Lawrence Livermore National Security, LLC. Produced at
# the Lawrence Livermore National Laboratory. LLNL-CODE-734707. All Rights
# reserved. See files LICENSE and NOTICE for details.
#
# This file is part of CEED, a collection of benchmarks, miniapps, software
# libraries and APIs for efficient h... | # Copyright (c) 2017, Lawrence Livermore National Security, LLC. Produced at
# the Lawrence Livermore National Laboratory. LLNL-CODE-734707. All Rights
# reserved. See files LICENSE and NOTICE for details.
#
# This file is part of CEED, a collection of benchmarks, miniapps, software
# libraries and APIs for efficient h... | en | 0.377439 | # Copyright (c) 2017, Lawrence Livermore National Security, LLC. Produced at # the Lawrence Livermore National Laboratory. LLNL-CODE-734707. All Rights # reserved. See files LICENSE and NOTICE for details. # # This file is part of CEED, a collection of benchmarks, miniapps, software # libraries and APIs for efficient h... | 1.738299 | 2 |
esmvalcore/cmor/_fixes/cmip6/cesm2.py | aperezpredictia/ESMValCore | 1 | 9255 | <gh_stars>1-10
"""Fixes for CESM2 model."""
from ..fix import Fix
from ..shared import (add_scalar_depth_coord, add_scalar_height_coord,
add_scalar_typeland_coord, add_scalar_typesea_coord)
class Fgco2(Fix):
"""Fixes for fgco2."""
def fix_metadata(self, cubes):
"""Add depth (0m) ... | """Fixes for CESM2 model."""
from ..fix import Fix
from ..shared import (add_scalar_depth_coord, add_scalar_height_coord,
add_scalar_typeland_coord, add_scalar_typesea_coord)
class Fgco2(Fix):
"""Fixes for fgco2."""
def fix_metadata(self, cubes):
"""Add depth (0m) coordinate.
... | es | 0.09968 | Fixes for CESM2 model. Fixes for fgco2. Add depth (0m) coordinate. Parameters ---------- cube : iris.cube.CubeList Returns ------- iris.cube.Cube Fixes for tas. Add height (2m) coordinate. Parameters ---------- cube : iris.cube.CubeList ... | 2.292166 | 2 |
examples/GenerateSubset.py | vitay/YouTubeFacesDB | 11 | 9256 | from YouTubeFacesDB import generate_ytf_database
###############################################################################
# Create the dataset
###############################################################################
generate_ytf_database(
directory= '../data',#'/scratch/vitay/Datasets/YouTubeFaces'... | from YouTubeFacesDB import generate_ytf_database
###############################################################################
# Create the dataset
###############################################################################
generate_ytf_database(
directory= '../data',#'/scratch/vitay/Datasets/YouTubeFaces'... | de | 0.311403 | ############################################################################### # Create the dataset ############################################################################### #'/scratch/vitay/Datasets/YouTubeFaces', # Location of the YTF dataset # Name of the HDF5 file to write to # Number of labels to randomly s... | 2.471962 | 2 |
src/waldur_mastermind/billing/tests/test_price_current.py | opennode/nodeconductor-assembly-waldur | 2 | 9257 | from freezegun import freeze_time
from rest_framework import test
from waldur_mastermind.billing.tests.utils import get_financial_report_url
from waldur_mastermind.invoices import models as invoice_models
from waldur_mastermind.invoices.tests import factories as invoice_factories
from waldur_mastermind.invoices.tests ... | from freezegun import freeze_time
from rest_framework import test
from waldur_mastermind.billing.tests.utils import get_financial_report_url
from waldur_mastermind.invoices import models as invoice_models
from waldur_mastermind.invoices.tests import factories as invoice_factories
from waldur_mastermind.invoices.tests ... | none | 1 | 2.136931 | 2 | |
tests/test_cli/test_utils/test_utils.py | ejfitzgerald/agents-aea | 0 | 9258 | # -*- coding: utf-8 -*-
# ------------------------------------------------------------------------------
#
# Copyright 2018-2019 Fetch.AI 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 ... | # -*- coding: utf-8 -*-
# ------------------------------------------------------------------------------
#
# Copyright 2018-2019 Fetch.AI 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 ... | en | 0.599205 | # -*- coding: utf-8 -*- # ------------------------------------------------------------------------------ # # Copyright 2018-2019 Fetch.AI 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 ... | 1.573534 | 2 |
api/flat/urls.py | SanjarbekSaminjonov/musofirlar.backend | 1 | 9259 | from django.urls import path
from . import views
urlpatterns = [
path('', views.FlatListAPIView.as_view()),
path('create/', views.FlatCreateAPIView.as_view()),
path('<int:pk>/', views.FlatDetailAPIView.as_view()),
path('<int:pk>/update/', views.FlatUpdateAPIView.as_view()),
path('<int:pk>/delete/'... | from django.urls import path
from . import views
urlpatterns = [
path('', views.FlatListAPIView.as_view()),
path('create/', views.FlatCreateAPIView.as_view()),
path('<int:pk>/', views.FlatDetailAPIView.as_view()),
path('<int:pk>/update/', views.FlatUpdateAPIView.as_view()),
path('<int:pk>/delete/'... | none | 1 | 1.620273 | 2 | |
hyssop_aiohttp/component/__init__.py | hsky77/hyssop | 0 | 9260 | # Copyright (C) 2020-Present the hyssop authors and contributors.
#
# This module is part of hyssop and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
'''
File created: January 1st 2021
Modified By: hsky77
Last Updated: January 7th 2021 15:30:08 pm
'''
from hyssop.project.com... | # Copyright (C) 2020-Present the hyssop authors and contributors.
#
# This module is part of hyssop and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
'''
File created: January 1st 2021
Modified By: hsky77
Last Updated: January 7th 2021 15:30:08 pm
'''
from hyssop.project.com... | en | 0.913848 | # Copyright (C) 2020-Present the hyssop authors and contributors. # # This module is part of hyssop and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php File created: January 1st 2021 Modified By: hsky77 Last Updated: January 7th 2021 15:30:08 pm | 1.809774 | 2 |
run_clone.py | tGhattas/IMP-seamless-cloning | 0 | 9261 | <reponame>tGhattas/IMP-seamless-cloning
import cv2
import getopt
import sys
from gui import MaskPainter, MaskMover
from clone import seamless_cloning, shepards_seamless_cloning
from utils import read_image, plt
from os import path
def usage():
print(
"Usage: python run_clone.py [options] \n\n\
Opt... | import cv2
import getopt
import sys
from gui import MaskPainter, MaskMover
from clone import seamless_cloning, shepards_seamless_cloning
from utils import read_image, plt
from os import path
def usage():
print(
"Usage: python run_clone.py [options] \n\n\
Options: \n\
\t-h\t Flag to specify... | en | 0.344571 | # parse command line arguments # print help information and exit: # will print something like "option -a not recognized" # # # set default mode to Possion solver # draw the mask # adjust mask position for target image # blend running example: - Possion based solver: python run_clone.py -s external/blend-1.jpg -t exter... | 2.404754 | 2 |
punkweb_boards/rest/serializers.py | Punkweb/punkweb-boards | 20 | 9262 | from rest_framework import serializers
from punkweb_boards.conf.settings import SHOUTBOX_DISABLED_TAGS
from punkweb_boards.models import (
BoardProfile,
Category,
Subcategory,
Thread,
Post,
Conversation,
Message,
Report,
Shout,
)
class BoardProfileSerializer(serializers.ModelSerial... | from rest_framework import serializers
from punkweb_boards.conf.settings import SHOUTBOX_DISABLED_TAGS
from punkweb_boards.models import (
BoardProfile,
Category,
Subcategory,
Thread,
Post,
Conversation,
Message,
Report,
Shout,
)
class BoardProfileSerializer(serializers.ModelSerial... | none | 1 | 1.99812 | 2 | |
runtime/components/Statistic/moving_minimum_time.py | ulise/hetida-designer | 41 | 9263 | <reponame>ulise/hetida-designer<gh_stars>10-100
from hetdesrun.component.registration import register
from hetdesrun.datatypes import DataType
import pandas as pd
import numpy as np
# ***** DO NOT EDIT LINES BELOW *****
# These lines may be overwritten if input/output changes.
@register(
inputs={"data": DataType.... | from hetdesrun.component.registration import register
from hetdesrun.datatypes import DataType
import pandas as pd
import numpy as np
# ***** DO NOT EDIT LINES BELOW *****
# These lines may be overwritten if input/output changes.
@register(
inputs={"data": DataType.Any, "t": DataType.String},
outputs={"movmin... | en | 0.387882 | # ***** DO NOT EDIT LINES BELOW ***** # These lines may be overwritten if input/output changes. entrypoint function for this component Usage example: >>> main( ... data = pd.Series( ... { ... "2019-08-01T15:20:00": 4.0, ... "2019-08-01T15:20:01": 5.0, ... ... | 2.664498 | 3 |
painter.py | MikhailNakhatovich/rooms_painting | 0 | 9264 | import cv2
import ezdxf
import numpy as np
def draw_hatch(img, entity, color, mask):
for poly_path in entity.paths.paths:
# print(poly_path.path_type_flags)
polygon = np.array([vertex[:-1] for vertex in poly_path.vertices]).astype(int)
if poly_path.path_type_flags & 1 == 1:
cv2... | import cv2
import ezdxf
import numpy as np
def draw_hatch(img, entity, color, mask):
for poly_path in entity.paths.paths:
# print(poly_path.path_type_flags)
polygon = np.array([vertex[:-1] for vertex in poly_path.vertices]).astype(int)
if poly_path.path_type_flags & 1 == 1:
cv2... | en | 0.424168 | # print(poly_path.path_type_flags) # print(doc.layers.entries.keys()) | 2.640296 | 3 |
misago/misago/users/serializers/auth.py | vascoalramos/misago-deployment | 2 | 9265 | <reponame>vascoalramos/misago-deployment
from django.contrib.auth import get_user_model
from django.urls import reverse
from rest_framework import serializers
from ...acl.useracl import serialize_user_acl
from .user import UserSerializer
User = get_user_model()
__all__ = ["AuthenticatedUserSerializer", "AnonymousUse... | from django.contrib.auth import get_user_model
from django.urls import reverse
from rest_framework import serializers
from ...acl.useracl import serialize_user_acl
from .user import UserSerializer
User = get_user_model()
__all__ = ["AuthenticatedUserSerializer", "AnonymousUserSerializer"]
class AuthFlags:
def ... | none | 1 | 2.260031 | 2 | |
shop/models.py | mohammadanarul/Ecommerce-Django-YT | 0 | 9266 | <reponame>mohammadanarul/Ecommerce-Django-YT<gh_stars>0
from ctypes.wintypes import CHAR
from distutils.command.upload import upload
from random import choice
from telnetlib import STATUS
from unicodedata import category
from django.db import models
from ckeditor.fields import RichTextField
from taggit.managers import ... | from ctypes.wintypes import CHAR
from distutils.command.upload import upload
from random import choice
from telnetlib import STATUS
from unicodedata import category
from django.db import models
from ckeditor.fields import RichTextField
from taggit.managers import TaggableManager
# Create your models here.
from mptt.mo... | en | 0.963489 | # Create your models here. | 2.100363 | 2 |
supriya/patterns/NoteEvent.py | deeuu/supriya | 0 | 9267 | <gh_stars>0
import uuid
import supriya.commands
import supriya.realtime
from supriya.patterns.Event import Event
class NoteEvent(Event):
### CLASS VARIABLES ###
__slots__ = ()
### INITIALIZER ###
def __init__(
self,
add_action=None,
delta=None,
duration=None,
... | import uuid
import supriya.commands
import supriya.realtime
from supriya.patterns.Event import Event
class NoteEvent(Event):
### CLASS VARIABLES ###
__slots__ = ()
### INITIALIZER ###
def __init__(
self,
add_action=None,
delta=None,
duration=None,
is_stop=T... | en | 0.528668 | ### CLASS VARIABLES ### ### INITIALIZER ### ### PRIVATE METHODS ### # Do not mutate in place. # Begin a Pbind or Pmono synth # Extend and make settings on a Pmono synth | 2.207112 | 2 |
emoji_utils.py | ApacheAA/LastSeen | 0 | 9268 | <filename>emoji_utils.py
# unicode digit emojis
# digits from '0' to '9'
zero_digit_code = zd = 48
# excluded digits
excl_digits = [2, 4, 5, 7]
# unicode digit keycap
udkc = '\U0000fe0f\U000020e3'
hours_0_9 = [chr(i) + udkc for i in range(zd, zd + 10)
if i - zd not in excl_digits]
# number '10' emoji
hours_0_9... | <filename>emoji_utils.py
# unicode digit emojis
# digits from '0' to '9'
zero_digit_code = zd = 48
# excluded digits
excl_digits = [2, 4, 5, 7]
# unicode digit keycap
udkc = '\U0000fe0f\U000020e3'
hours_0_9 = [chr(i) + udkc for i in range(zd, zd + 10)
if i - zd not in excl_digits]
# number '10' emoji
hours_0_9... | en | 0.376239 | # unicode digit emojis # digits from '0' to '9' # excluded digits # unicode digit keycap # number '10' emoji # custom emojis from '11' to '23' | 2.834555 | 3 |
TFBertForMaskedLM/main.py | Sniper970119/ExampleForTransformers | 3 | 9269 | <filename>TFBertForMaskedLM/main.py
# -*- coding:utf-8 -*-
"""
┏┛ ┻━━━━━┛ ┻┓
┃ ┃
┃ ━ ┃
┃ ┳┛ ┗┳ ┃
┃ ┃
┃ ┻ ┃
┃ ┃
┗━┓ ┏━━━┛
┃ ┃ 神兽保佑
┃ ┃ 代码无BUG!
┃ ┗━━━━━━━━━┓
┃CREATE BY SNIPER┣┓
┃ ┏... | <filename>TFBertForMaskedLM/main.py
# -*- coding:utf-8 -*-
"""
┏┛ ┻━━━━━┛ ┻┓
┃ ┃
┃ ━ ┃
┃ ┳┛ ┗┳ ┃
┃ ┃
┃ ┻ ┃
┃ ┃
┗━┓ ┏━━━┛
┃ ┃ 神兽保佑
┃ ┃ 代码无BUG!
┃ ┗━━━━━━━━━┓
┃CREATE BY SNIPER┣┓
┃ ┏... | ja | 0.492424 | # -*- coding:utf-8 -*- ┏┛ ┻━━━━━┛ ┻┓ ┃ ┃ ┃ ━ ┃ ┃ ┳┛ ┗┳ ┃ ┃ ┃ ┃ ┻ ┃ ┃ ┃ ┗━┓ ┏━━━┛ ┃ ┃ 神兽保佑 ┃ ┃ 代码无BUG! ┃ ┗━━━━━━━━━┓ ┃CREATE BY SNIPER┣┓ ┃ ┏┛ ┗━┓ ┓ ┏━━━┳ ┓ ┏━┛ ┃ ┫ ┫ ┃... | 2.655953 | 3 |
mirari/TCS/migrations/0042_auto_20190726_0145.py | gcastellan0s/mirariapp | 0 | 9270 | # Generated by Django 2.0.5 on 2019-07-26 06:45
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('TCS', '0041_auto_20190726_0030'),
]
operations = [
migrations.AlterModelOptions(
name='modelo',
options={'default_permission... | # Generated by Django 2.0.5 on 2019-07-26 06:45
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('TCS', '0041_auto_20190726_0030'),
]
operations = [
migrations.AlterModelOptions(
name='modelo',
options={'default_permission... | en | 0.696614 | # Generated by Django 2.0.5 on 2019-07-26 06:45 | 1.588936 | 2 |
kornia/geometry/calibration/undistort.py | belltailjp/kornia | 1 | 9271 | import torch
from kornia.geometry.linalg import transform_points
from kornia.geometry.transform import remap
from kornia.utils import create_meshgrid
from .distort import distort_points, tilt_projection
# Based on https://github.com/opencv/opencv/blob/master/modules/calib3d/src/undistort.dispatch.cpp#L384
def undis... | import torch
from kornia.geometry.linalg import transform_points
from kornia.geometry.transform import remap
from kornia.utils import create_meshgrid
from .distort import distort_points, tilt_projection
# Based on https://github.com/opencv/opencv/blob/master/modules/calib3d/src/undistort.dispatch.cpp#L384
def undis... | en | 0.686688 | # Based on https://github.com/opencv/opencv/blob/master/modules/calib3d/src/undistort.dispatch.cpp#L384 Compensate for lens distortion a set of 2D image points. Radial :math:`(k_1, k_2, k_3, k_4, k_4, k_6)`, tangential :math:`(p_1, p_2)`, thin prism :math:`(s_1, s_2, s_3, s_4)`, and tilt :math:`(\tau_x, \tau_y... | 2.492273 | 2 |
Tests/Aula_7a.py | o-Ian/Practice-Python | 4 | 9272 | n1 = int(input('Digite um valor: '))
n2 = int(input('Digite outro valor: '))
print('A soma é: {}!' .format(n1+n2))
print('A subtração entre {} e {} é {}!' .format(n1, n2, n1-n2))
print('A multiplicação desses valores é {}!' .format(n1 * n2))
print('A divisão entre {} e {} é {:.3}' .format(n1, n2, n1/n2))
print('A divis... | n1 = int(input('Digite um valor: '))
n2 = int(input('Digite outro valor: '))
print('A soma é: {}!' .format(n1+n2))
print('A subtração entre {} e {} é {}!' .format(n1, n2, n1-n2))
print('A multiplicação desses valores é {}!' .format(n1 * n2))
print('A divisão entre {} e {} é {:.3}' .format(n1, n2, n1/n2))
print('A divis... | none | 1 | 4.077381 | 4 | |
manubot/cite/tests/test_citekey_api.py | shuvro-zz/manubot | 1 | 9273 | <filename>manubot/cite/tests/test_citekey_api.py
"""Tests API-level functions in manubot.cite. Both functions are found in citekey.py"""
import pytest
from manubot.cite import citekey_to_csl_item, standardize_citekey
@pytest.mark.parametrize(
"citekey,expected",
[
("doi:10.5061/DRYAD.q447c/1", "doi:... | <filename>manubot/cite/tests/test_citekey_api.py
"""Tests API-level functions in manubot.cite. Both functions are found in citekey.py"""
import pytest
from manubot.cite import citekey_to_csl_item, standardize_citekey
@pytest.mark.parametrize(
"citekey,expected",
[
("doi:10.5061/DRYAD.q447c/1", "doi:... | en | 0.70936 | Tests API-level functions in manubot.cite. Both functions are found in citekey.py # passthrough non-existent shortDOI Standardize identifiers based on their source https://api.ncbi.nlm.nih.gov/lit/ctxp/v1/pmc/?format=csl&id=3041534 Generated from XML returned by https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.... | 2.249024 | 2 |
vispy/io/datasets.py | hmaarrfk/vispy | 2,617 | 9274 | # -*- coding: utf-8 -*-
# Copyright (c) Vispy Development Team. All Rights Reserved.
# Distributed under the (new) BSD License. See LICENSE.txt for more info.
import numpy as np
from os import path as op
from ..util import load_data_file
# This is the package data dir, not the dir for config, etc.
DATA_DIR = op.join... | # -*- coding: utf-8 -*-
# Copyright (c) Vispy Development Team. All Rights Reserved.
# Distributed under the (new) BSD License. See LICENSE.txt for more info.
import numpy as np
from os import path as op
from ..util import load_data_file
# This is the package data dir, not the dir for config, etc.
DATA_DIR = op.join... | en | 0.643633 | # -*- coding: utf-8 -*- # Copyright (c) Vispy Development Team. All Rights Reserved. # Distributed under the (new) BSD License. See LICENSE.txt for more info. # This is the package data dir, not the dir for config, etc. Load the iris dataset Returns ------- iris : NpzFile data['data'] : a (150, 4) ... | 2.2424 | 2 |
universal_portfolio/knapsack.py | jehung/universal_portfolio | 14 | 9275 | <reponame>jehung/universal_portfolio
# -*- coding: utf-8 -*-
from __future__ import print_function
import numpy as np
np.random.seed(1335) # for reproducibility
np.set_printoptions(precision=5, suppress=True, linewidth=150)
import os
import pandas as pd
import backtest as twp
from matplotlib import pyplot as plt
from... | # -*- coding: utf-8 -*-
from __future__ import print_function
import numpy as np
np.random.seed(1335) # for reproducibility
np.set_printoptions(precision=5, suppress=True, linewidth=150)
import os
import pandas as pd
import backtest as twp
from matplotlib import pyplot as plt
from sklearn import metrics, preprocessin... | en | 0.612079 | # -*- coding: utf-8 -*- # for reproducibility Name: The Self Learning Quant, Example 3 Author: <NAME> Created: 30/03/2016 Copyright: (c) <NAME> 2016 Licence: BSD Requirements: Numpy Pandas MatplotLib scikit-learn TA-Lib, instructions at https://mrjbq7.github.io/ta-lib/install.html Keras, https:... | 2.358647 | 2 |
experiments/experiment_01.py | bask0/q10hybrid | 2 | 9276 | <reponame>bask0/q10hybrid
import pytorch_lightning as pl
import optuna
import xarray as xr
from pytorch_lightning.callbacks.early_stopping import EarlyStopping
from pytorch_lightning.callbacks.model_checkpoint import ModelCheckpoint
import os
import shutil
from argparse import ArgumentParser
from datetime import dat... | import pytorch_lightning as pl
import optuna
import xarray as xr
from pytorch_lightning.callbacks.early_stopping import EarlyStopping
from pytorch_lightning.callbacks.model_checkpoint import ModelCheckpoint
import os
import shutil
from argparse import ArgumentParser
from datetime import datetime
from project.fluxdat... | en | 0.555881 | # Hardcoded `Trainer` args. Note that these cannot be passed via cli. # Further variables used in the hybrid model. # Target (multiple targets not possible currently). # Find variables that are only needed in physical model but not in NN. # ------------ # data # ------------ # Create empty xr.Dataset, will be used by t... | 2.040674 | 2 |
main.py | warifp/InstagramPostAndDelete | 4 | 9277 | #! @@Author : <NAME>
#! @@Create : 18 Januari 2019
#! @@Modify : 19 Januari 2019
#! Gambar dari reddit.
#! Gunakan VPN karena DNS situs reddit sudah di blokir dari negara Indonesia.
import os
import json
import requests
import progressbar
from PIL import Image
from lxml import html
from time import sleep
from ImageDel... | #! @@Author : <NAME>
#! @@Create : 18 Januari 2019
#! @@Modify : 19 Januari 2019
#! Gambar dari reddit.
#! Gunakan VPN karena DNS situs reddit sudah di blokir dari negara Indonesia.
import os
import json
import requests
import progressbar
from PIL import Image
from lxml import html
from time import sleep
from ImageDel... | id | 0.689184 | #! @@Author : <NAME> #! @@Create : 18 Januari 2019 #! @@Modify : 19 Januari 2019 #! Gambar dari reddit. #! Gunakan VPN karena DNS situs reddit sudah di blokir dari negara Indonesia. | 3.10056 | 3 |
pyspectator/collection.py | maximilionus/pyspectator-x | 39 | 9278 | from collections import MutableMapping, Container
from datetime import datetime, timedelta
from pyvalid import accepts
class LimitedTimeTable(MutableMapping, Container):
def __init__(self, time_span):
self.__storage = dict()
self.__time_span = None
self.time_span = time_span
@propert... | from collections import MutableMapping, Container
from datetime import datetime, timedelta
from pyvalid import accepts
class LimitedTimeTable(MutableMapping, Container):
def __init__(self, time_span):
self.__storage = dict()
self.__time_span = None
self.time_span = time_span
@propert... | en | 0.943502 | # Item is too old for current timetable | 2.491096 | 2 |
keyboardrow.py | AndySamoil/Elite_Code | 0 | 9279 | def findWords(self, words: List[str]) -> List[str]:
''' sets and iterate through sets
'''
every = [set("qwertyuiop"), set("asdfghjkl"), set("zxcvbnm")]
ans = []
for word in words:
l = len(word)
for sett in every:
... | def findWords(self, words: List[str]) -> List[str]:
''' sets and iterate through sets
'''
every = [set("qwertyuiop"), set("asdfghjkl"), set("zxcvbnm")]
ans = []
for word in words:
l = len(word)
for sett in every:
... | en | 0.966702 | sets and iterate through sets | 3.723266 | 4 |
DFS_Backtracking/31. Next Permutation.py | xli1110/LC | 2 | 9280 | <gh_stars>1-10
class Solution:
def __init__(self):
self.res = []
self.path = []
def arr_to_num(self, arr):
s = ""
for x in arr:
s += str(x)
return int(s)
def find_position(self, nums):
for i in range(len(self.res)):
if self.res[i] == ... | class Solution:
def __init__(self):
self.res = []
self.path = []
def arr_to_num(self, arr):
s = ""
for x in arr:
s += str(x)
return int(s)
def find_position(self, nums):
for i in range(len(self.res)):
if self.res[i] == nums:
... | en | 0.723942 | # we need the check below for duplicate elements in nums # run nums = [1, 5, 1] and see the case Do not return anything, modify nums in-place instead. # all permutations # note that we need to SORT the array at first # find position # in-place replacement # nums = [2, 1, 3] | 3.848518 | 4 |
plugin/DataExport/extend.py | konradotto/TS | 125 | 9281 | #!/usr/bin/python
# Copyright (C) 2015 Ion Torrent Systems, Inc. All Rights Reserved
import subprocess
import re
pluginName = 'DataExport'
pluginDir = ""
networkFS = ["nfs", "cifs"]
localFS = ["ext4", "ext3", "xfs", "ntfs", "exfat", "vboxsf"]
supportedFS = ",".join(localFS + networkFS)
def test(bucket):
return... | #!/usr/bin/python
# Copyright (C) 2015 Ion Torrent Systems, Inc. All Rights Reserved
import subprocess
import re
pluginName = 'DataExport'
pluginDir = ""
networkFS = ["nfs", "cifs"]
localFS = ["ext4", "ext3", "xfs", "ntfs", "exfat", "vboxsf"]
supportedFS = ",".join(localFS + networkFS)
def test(bucket):
return... | en | 0.523136 | #!/usr/bin/python # Copyright (C) 2015 Ion Torrent Systems, Inc. All Rights Reserved | 2.054894 | 2 |
boids/biods_object.py | PaulAustin/sb7-pgz | 1 | 9282 | # Ported from JavaSript version to Python and Pygame Zero
# Designed to work well with mu-editor environment.
#
# The original Javascript version wasdonw by <NAME>
# at https://github.com/beneater/boids (MIT License)
# No endorsement implied.
#
# Complex numbers are are used as vectors to integrate x and y positions an... | # Ported from JavaSript version to Python and Pygame Zero
# Designed to work well with mu-editor environment.
#
# The original Javascript version wasdonw by <NAME>
# at https://github.com/beneater/boids (MIT License)
# No endorsement implied.
#
# Complex numbers are are used as vectors to integrate x and y positions an... | en | 0.873752 | # Ported from JavaSript version to Python and Pygame Zero # Designed to work well with mu-editor environment. # # The original Javascript version wasdonw by <NAME> # at https://github.com/beneater/boids (MIT License) # No endorsement implied. # # Complex numbers are are used as vectors to integrate x and y positions an... | 2.770236 | 3 |
upoutdf/types/recurring/yearly.py | UpOut/UpOutDF | 0 | 9283 | <filename>upoutdf/types/recurring/yearly.py<gh_stars>0
# coding: utf-8
import pytz
from dateutil.relativedelta import relativedelta
from .base import BaseRecurring
from upoutdf.occurences import OccurenceBlock, OccurenceGroup
from upoutdf.constants import YEARLY_TYPE
class YearlyType(BaseRecurring):
year_day = ... | <filename>upoutdf/types/recurring/yearly.py<gh_stars>0
# coding: utf-8
import pytz
from dateutil.relativedelta import relativedelta
from .base import BaseRecurring
from upoutdf.occurences import OccurenceBlock, OccurenceGroup
from upoutdf.constants import YEARLY_TYPE
class YearlyType(BaseRecurring):
year_day = ... | en | 0.800906 | # coding: utf-8 #(starting <datetimestring>) (ending <datetimestring>) #If we had a problem, try the next year #While we're before the end date (if we have it) #And we're before the max repetetions (if we have it) #We always return a OccurenceGroup, even if just 1 | 2.4085 | 2 |
project/urls.py | dbinetti/captable | 18 | 9284 | <reponame>dbinetti/captable
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.views.generic import TemplateView
urlpatterns = patterns(
'',
url(r'^$', TemplateView.as_view(... | from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.views.generic import TemplateView
urlpatterns = patterns(
'',
url(r'^$', TemplateView.as_view(template_name='home.html'), ... | none | 1 | 2.02493 | 2 | |
common/evaluators/bert_emotion_evaluator.py | marjanhs/procon20 | 5 | 9285 | import warnings
import numpy as np
import torch
import torch.nn.functional as F
from sklearn import metrics
from torch.utils.data import DataLoader, SequentialSampler, TensorDataset
from tqdm import tqdm
from datasets.bert_processors.abstract_processor import convert_examples_to_features_with_emotion, \
... | import warnings
import numpy as np
import torch
import torch.nn.functional as F
from sklearn import metrics
from torch.utils.data import DataLoader, SequentialSampler, TensorDataset
from tqdm import tqdm
from datasets.bert_processors.abstract_processor import convert_examples_to_features_with_emotion, \
... | en | 0.580672 | # Suppress warnings from sklearn.metrics | 2.21914 | 2 |
model/mlp1.py | andrearosasco/DistilledReplay | 7 | 9286 | import torch.nn as nn
import torch.nn.functional as F
class Model(nn.Module):
def __init__(self, config):
super(Model, self).__init__()
self.drop = nn.Dropout(config['dropout'])
self.fc1 = nn.Linear(784, 2000)
self.fc2 = nn.Linear(2000, 2000)
self.fc3 = nn.Linea... | import torch.nn as nn
import torch.nn.functional as F
class Model(nn.Module):
def __init__(self, config):
super(Model, self).__init__()
self.drop = nn.Dropout(config['dropout'])
self.fc1 = nn.Linear(784, 2000)
self.fc2 = nn.Linear(2000, 2000)
self.fc3 = nn.Linea... | en | 0.232787 | # 784 -> 2000 # 2000 -> 2000 # 2000 -> 2000 # 2000 -> 2000 # 2000 -> 100 | 2.857979 | 3 |
netbox/ipam/managers.py | aslafy-z/netbox | 1 | 9287 | <filename>netbox/ipam/managers.py
from django.db import models
from ipam.lookups import Host, Inet
class IPAddressManager(models.Manager):
def get_queryset(self):
"""
By default, PostgreSQL will order INETs with shorter (larger) prefix lengths ahead of those with longer
(smaller) masks. ... | <filename>netbox/ipam/managers.py
from django.db import models
from ipam.lookups import Host, Inet
class IPAddressManager(models.Manager):
def get_queryset(self):
"""
By default, PostgreSQL will order INETs with shorter (larger) prefix lengths ahead of those with longer
(smaller) masks. ... | en | 0.942583 | By default, PostgreSQL will order INETs with shorter (larger) prefix lengths ahead of those with longer (smaller) masks. This makes no sense when ordering IPs, which should be ordered solely by family and host address. We can use HOST() to extract just the host portion of the address (ignoring its mask)... | 2.47511 | 2 |
train.py | VArdulov/learning-kis | 0 | 9288 | #!/usr/bin/env python
# coding: utf-8
""" Learning Koopman Invariant Subspace
(c) <NAME>, 2017.
<EMAIL>
"""
import numpy as np
np.random.seed(1234567890)
from argparse import ArgumentParser
from os import path
import time
from lkis import TimeSeriesBatchMaker, KoopmanInvariantSubspaceLearner
from losses import co... | #!/usr/bin/env python
# coding: utf-8
""" Learning Koopman Invariant Subspace
(c) <NAME>, 2017.
<EMAIL>
"""
import numpy as np
np.random.seed(1234567890)
from argparse import ArgumentParser
from os import path
import time
from lkis import TimeSeriesBatchMaker, KoopmanInvariantSubspaceLearner
from losses import co... | en | 0.745454 | #!/usr/bin/env python # coding: utf-8 Learning Koopman Invariant Subspace (c) <NAME>, 2017. <EMAIL> # -- Parse arguments #ToDo: Implement # grab the command line arguments # find and load the training data # process the delay either set by the user or is set to one 10th of the data # based on the number of batches, d... | 2.494588 | 2 |
Algorithms/Easy/1200. Minimum Absolute Difference/answer.py | KenWoo/Algorithm | 0 | 9289 | <reponame>KenWoo/Algorithm<gh_stars>0
from typing import List
class Solution:
def minimumAbsDifference(self, arr: List[int]) -> List[List[int]]:
arr.sort()
res = []
min_diff = arr[1] - arr[0]
res.append([arr[0], arr[1]])
for i in range(1, len(arr)-1):
diff = arr... | from typing import List
class Solution:
def minimumAbsDifference(self, arr: List[int]) -> List[List[int]]:
arr.sort()
res = []
min_diff = arr[1] - arr[0]
res.append([arr[0], arr[1]])
for i in range(1, len(arr)-1):
diff = arr[i+1]-arr[i]
if diff < min... | none | 1 | 3.609747 | 4 | |
resources/physequations.py | VijayStroup/Physics_Problem_Solver_Basic | 0 | 9290 | <filename>resources/physequations.py
import math
def close(expected, actual, maxerror):
'''checks to see if the actual number is within expected +- maxerror.'''
low = expected - maxerror
high = expected + maxerror
if actual >= low and actual <= high:
return True
else:
return False
def grav_potential_energy(m... | <filename>resources/physequations.py
import math
def close(expected, actual, maxerror):
'''checks to see if the actual number is within expected +- maxerror.'''
low = expected - maxerror
high = expected + maxerror
if actual >= low and actual <= high:
return True
else:
return False
def grav_potential_energy(m... | en | 0.696741 | checks to see if the actual number is within expected +- maxerror. calculate potential energy given mass and height. Mass in kilograms and height in meters. calculate kinetic energy given mass and velocity. Mass in kilograms and velocity in meters per second. calculate work energy given force, displancement, ... | 3.710374 | 4 |
mvpa2/tests/test_erdataset.py | andycon/PyMVPA | 0 | 9291 | <reponame>andycon/PyMVPA
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##
#
# See COPYING file distributed along with the PyMVPA package for the
# copyright and license ter... | # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##
#
# See COPYING file distributed along with the PyMVPA package for the
# copyright and license terms.
#
### ### ### ### ###... | en | 0.785098 | # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ## # # See COPYING file distributed along with the PyMVPA package for the # copyright and license terms. # ### ### ### ### ###... | 1.921974 | 2 |
userbot/plugins/delfp.py | aksr-aashish/FIREXUSERBOT | 0 | 9292 | from telethon.tl.functions.photos import DeletePhotosRequest, GetUserPhotosRequest
from telethon.tl.types import InputPhoto
from userbot.cmdhelp import CmdHelp
from userbot.utils import admin_cmd, edit_or_reply, sudo_cmd
CmdHelp("delfp").add_command("delpfp", None, "delete ur currnt profile picture").add()
@borg.on... | from telethon.tl.functions.photos import DeletePhotosRequest, GetUserPhotosRequest
from telethon.tl.types import InputPhoto
from userbot.cmdhelp import CmdHelp
from userbot.utils import admin_cmd, edit_or_reply, sudo_cmd
CmdHelp("delfp").add_command("delpfp", None, "delete ur currnt profile picture").add()
@borg.on... | en | 0.89697 | For .delpfp command, delete your current profile picture in Telegram. | 2.514316 | 3 |
amlb/benchmarks/file.py | pplonski/automlbenchmark | 282 | 9293 | <filename>amlb/benchmarks/file.py<gh_stars>100-1000
import logging
import os
from typing import List, Tuple, Optional
from amlb.utils import config_load, Namespace
log = logging.getLogger(__name__)
def _find_local_benchmark_definition(name: str, benchmark_definition_dirs: List[str]) -> str:
# 'name' should be e... | <filename>amlb/benchmarks/file.py<gh_stars>100-1000
import logging
import os
from typing import List, Tuple, Optional
from amlb.utils import config_load, Namespace
log = logging.getLogger(__name__)
def _find_local_benchmark_definition(name: str, benchmark_definition_dirs: List[str]) -> str:
# 'name' should be e... | en | 0.847454 | # 'name' should be either a full path to the benchmark, # or a filename (without extension) in the benchmark directory. # We don't account for duplicate definitions (yet). # should we support s3 and check for s3 path before raising error? Loads benchmark from a local file. | 2.392496 | 2 |
pybuspro/devices/control.py | eyesoft/pybuspro | 2 | 9294 | from ..core.telegram import Telegram
from ..helpers.enums import OperateCode
class _Control:
def __init__(self, buspro):
self._buspro = buspro
self.subnet_id = None
self.device_id = None
@staticmethod
def build_telegram_from_control(control):
if control is None:
... | from ..core.telegram import Telegram
from ..helpers.enums import OperateCode
class _Control:
def __init__(self, buspro):
self._buspro = buspro
self.subnet_id = None
self.device_id = None
@staticmethod
def build_telegram_from_control(control):
if control is None:
... | en | 0.285575 | # if telegram.target_address[1] == 100: # print("==== {}".format(str(telegram))) # no more properties # no more properties # no more properties # no more properties | 2.299809 | 2 |
appengine/chrome_infra_console_loadtest/main.py | eunchong/infra | 0 | 9295 | <filename>appengine/chrome_infra_console_loadtest/main.py
# Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import logging
import endpoints
import random
import webapp2
from apiclient import discovery
from ... | <filename>appengine/chrome_infra_console_loadtest/main.py
# Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import logging
import endpoints
import random
import webapp2
from apiclient import discovery
from ... | en | 0.881827 | # Copyright 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. A testing endpoint that receives timeseries data. API for the loadtest configuration UI. | 2.200837 | 2 |
src/mitre/securingai/restapi/task_plugin/controller.py | usnistgov/dioptra | 14 | 9296 | <reponame>usnistgov/dioptra
# This Software (Dioptra) is being made available as a public service by the
# National Institute of Standards and Technology (NIST), an Agency of the United
# States Department of Commerce. This software was developed in part by employees of
# NIST and in part by NIST contractors. Copyright... | # This Software (Dioptra) is being made available as a public service by the
# National Institute of Standards and Technology (NIST), an Agency of the United
# States Department of Commerce. This software was developed in part by employees of
# NIST and in part by NIST contractors. Copyright in portions of this softwar... | en | 0.933608 | # This Software (Dioptra) is being made available as a public service by the # National Institute of Standards and Technology (NIST), an Agency of the United # States Department of Commerce. This software was developed in part by employees of # NIST and in part by NIST contractors. Copyright in portions of this softwar... | 1.398845 | 1 |
dulwich/tests/test_lru_cache.py | mjmaenpaa/dulwich | 0 | 9297 | # Copyright (C) 2006, 2008 Canonical Ltd
#
# Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU
# General Public License as public by the Free Software Foundation; version 2.0
# or (at your option) any later version. You can redistribute it and/or
# modify it under the terms of either of these t... | # Copyright (C) 2006, 2008 Canonical Ltd
#
# Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU
# General Public License as public by the Free Software Foundation; version 2.0
# or (at your option) any later version. You can redistribute it and/or
# modify it under the terms of either of these t... | en | 0.881848 | # Copyright (C) 2006, 2008 Canonical Ltd # # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU # General Public License as public by the Free Software Foundation; version 2.0 # or (at your option) any later version. You can redistribute it and/or # modify it under the terms of either of these t... | 2.131507 | 2 |
py/2016/5B.py | pedrotari7/advent_of_code | 0 | 9298 | import md5
(i,count) = (0,0)
password = ['']*8
while 1:
key = 'reyedfim' + str(i)
md = md5.new(key).hexdigest()
if md[:5] == '00000':
index = int(md[5],16)
if index < len(password) and password[index]=='':
password[index] = md[6]
count += 1
if count ... | import md5
(i,count) = (0,0)
password = ['']*8
while 1:
key = 'reyedfim' + str(i)
md = md5.new(key).hexdigest()
if md[:5] == '00000':
index = int(md[5],16)
if index < len(password) and password[index]=='':
password[index] = md[6]
count += 1
if count ... | none | 1 | 3.050654 | 3 | |
release/scripts/mgear/shifter_epic_components/EPIC_foot_01/__init__.py | lsica-scopely/mgear4 | 0 | 9299 | <filename>release/scripts/mgear/shifter_epic_components/EPIC_foot_01/__init__.py<gh_stars>0
import pymel.core as pm
import ast
from pymel.core import datatypes
from mgear.shifter import component
from mgear.core import node, applyop, vector
from mgear.core import attribute, transform, primitive
class Component(comp... | <filename>release/scripts/mgear/shifter_epic_components/EPIC_foot_01/__init__.py<gh_stars>0
import pymel.core as pm
import ast
from pymel.core import datatypes
from mgear.shifter import component
from mgear.core import node, applyop, vector
from mgear.core import attribute, transform, primitive
class Component(comp... | en | 0.506139 | Shifter component Class # ===================================================== # OBJECTS # ===================================================== Add all the objects needed to create the component. # joint Description Names # Heel --------------------------------------------- # bank pivot # heel # Tip -----------------... | 2.183324 | 2 |