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 |
|---|---|---|---|---|---|---|---|---|---|---|
assignments/07-csv/blastomatic.py | marissalopezpier/biosys-analytics | 0 | 6622051 | #!/usr/bin/env python3
"""
Author : <NAME>
Date : 3 13 2019
Purpose: Python program for blastomics
"""
import os
import sys
import argparse
import csv
#import Bio
#from Bio import SeqIO
from collections import defaultdict
#-------------------------------------
def main():
args = get_args()
hits_header = [... | #!/usr/bin/env python3
"""
Author : <NAME>
Date : 3 13 2019
Purpose: Python program for blastomics
"""
import os
import sys
import argparse
import csv
#import Bio
#from Bio import SeqIO
from collections import defaultdict
#-------------------------------------
def main():
args = get_args()
hits_header = [... | en | 0.309554 | #!/usr/bin/env python3 Author : <NAME> Date : 3 13 2019 Purpose: Python program for blastomics #import Bio #from Bio import SeqIO #------------------------------------- #using first line as hits_header #sseqid = [] #pident = [] #print(row) # -------------------------------------------------- get arguments | 2.679633 | 3 |
5. WEB/CustomTransform/distanceEncoder.py | doyaguillo1997/Data2Gether | 1 | 6622052 | <filename>5. WEB/CustomTransform/distanceEncoder.py
from sklearn.base import BaseEstimator, TransformerMixin
import numpy as np
class DistanceEncoder(BaseEstimator, TransformerMixin):
"""
Clase que devuelve la distancia a un punto específico según latitud/longitud.
MAGNITUDES: Distancias en <km> y ... | <filename>5. WEB/CustomTransform/distanceEncoder.py
from sklearn.base import BaseEstimator, TransformerMixin
import numpy as np
class DistanceEncoder(BaseEstimator, TransformerMixin):
"""
Clase que devuelve la distancia a un punto específico según latitud/longitud.
MAGNITUDES: Distancias en <km> y ... | es | 0.955222 | Clase que devuelve la distancia a un punto específico según latitud/longitud.
MAGNITUDES: Distancias en <km> y latitudes/longitudes en <minutos>.
LÓGICA: Se suma el cuadrado de la diferencias de las latitudes/longitudes y se obtiene la raiz cuadrada.
El resultado se obtiene en <minutos>, por lo q... | 3.026276 | 3 |
BeesEtAl/F3_Fly.py | FJFranklin/BeesEtAl | 1 | 6622053 | import numpy as np
from .Base_Automaton import Base_Automaton
class F3_Fly(object):
def __init__(self, garden, id_no, gender, orientation):
self.G = garden # the F3_Garden object
self.id_no = id_no # a reference number to identify this fly
self.gender ... | import numpy as np
from .Base_Automaton import Base_Automaton
class F3_Fly(object):
def __init__(self, garden, id_no, gender, orientation):
self.G = garden # the F3_Garden object
self.id_no = id_no # a reference number to identify this fly
self.gender ... | en | 0.806999 | # the F3_Garden object # a reference number to identify this fly # 'M', 'N' or 'F' # list of one or more genders # current position # best personal position # associated MESO position #bees={b}, radius={r}'.format(p=self.id_no, g=self.gender, o=self.orientation, b=count, r=self.G.bee_radius)) # this is very noisy # sel... | 3.045636 | 3 |
util/control_flow.py | Elric2718/HierGMM | 0 | 6622054 | # -*- coding: utf-8 -*-
"""
Utilities for control flow
"""
class Register:
"""
Register instances are usually used as decorators, which behaves like "factory pattern".
It helps get rid of the tedious if-else clauses.
"""
def __init__(self):
self._register_map = dict()
def get(self, na... | # -*- coding: utf-8 -*-
"""
Utilities for control flow
"""
class Register:
"""
Register instances are usually used as decorators, which behaves like "factory pattern".
It helps get rid of the tedious if-else clauses.
"""
def __init__(self):
self._register_map = dict()
def get(self, na... | en | 0.892641 | # -*- coding: utf-8 -*- Utilities for control flow Register instances are usually used as decorators, which behaves like "factory pattern". It helps get rid of the tedious if-else clauses. | 3.966385 | 4 |
other_handlers/BaseModelHandler.py | Plawn/petit_ts | 1 | 6622055 | <filename>other_handlers/BaseModelHandler.py
from petit_ts.ts_store import TSTypeStore
from typing import List, Tuple, Optional, Dict, Any, get_type_hints
from petit_type_system import ClassHandler
from petit_ts import TSTypeStore
from pydantic import BaseModel
class BaseModelHandler(ClassHandler):
def is_mapping... | <filename>other_handlers/BaseModelHandler.py
from petit_ts.ts_store import TSTypeStore
from typing import List, Tuple, Optional, Dict, Any, get_type_hints
from petit_type_system import ClassHandler
from petit_ts import TSTypeStore
from pydantic import BaseModel
class BaseModelHandler(ClassHandler):
def is_mapping... | none | 1 | 2.069968 | 2 | |
aws_text_insight/lbd/response.py | MacHu-GWU/aws_text_insight-project | 0 | 6622056 | <filename>aws_text_insight/lbd/response.py
# -*- coding: utf-8 -*-
"""
Response object.
"""
import typing
import attr
from attrs_mate import AttrsClass
@attr.s
class Error(AttrsClass):
traceback: str = attr.ib()
@attr.s
class Response(AttrsClass):
message: str = attr.ib()
data: typing.Union[dict, None... | <filename>aws_text_insight/lbd/response.py
# -*- coding: utf-8 -*-
"""
Response object.
"""
import typing
import attr
from attrs_mate import AttrsClass
@attr.s
class Error(AttrsClass):
traceback: str = attr.ib()
@attr.s
class Response(AttrsClass):
message: str = attr.ib()
data: typing.Union[dict, None... | en | 0.822329 | # -*- coding: utf-8 -*- Response object. | 2.20751 | 2 |
medium_test.py | devsearchcomponent/redux-python | 1 | 6622057 | from typing import *
import asyncio
import pytest
import redux
@pytest.fixture(scope="session", autouse=True)
def setup_environment():
redux.RemoteManager().RECONNECT_TIMEOUT = 0.1
@redux.behavior("sub:local:", redux.SubscribeRecycleOption())
class LocalMediumSubscribeReducer(redux.Reducer):
def __init__(se... | from typing import *
import asyncio
import pytest
import redux
@pytest.fixture(scope="session", autouse=True)
def setup_environment():
redux.RemoteManager().RECONNECT_TIMEOUT = 0.1
@redux.behavior("sub:local:", redux.SubscribeRecycleOption())
class LocalMediumSubscribeReducer(redux.Reducer):
def __init__(se... | none | 1 | 2.102119 | 2 | |
experiments/problems/functions/hyperellipsoid.py | QuintonWeenink/investigating-cpso-for-nn-training | 2 | 6622058 | import numpy as np
from mlpy.numberGenerator.bounds import Bounds
from experiments.problems.functions.structure.function import Function
class Hyperellipsoid(Function):
def function(self, x):
return np.sum(np.arange(1, len(x) + 1) * np.power(x, 2))
def getBounds(self):
return Bounds(-5.12, 5... | import numpy as np
from mlpy.numberGenerator.bounds import Bounds
from experiments.problems.functions.structure.function import Function
class Hyperellipsoid(Function):
def function(self, x):
return np.sum(np.arange(1, len(x) + 1) * np.power(x, 2))
def getBounds(self):
return Bounds(-5.12, 5... | none | 1 | 2.833435 | 3 | |
python version/testing.py | asiddi24/box_model | 0 | 6622059 | <gh_stars>0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jun 6 10:27:14 2019
@author: asiddi24
"""
'''Running the box_model'''
'''Initializing variables'''
from box_model import fourbox
N=4000
Kv=1e-5
AI=1000
Mek=25e6
Aredi=1000
M_s=15e6
D0=500
T0s=2
T0n=4
T0l=17
T0d=3
S0s=34
S0n=35
S0l=36
S0... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jun 6 10:27:14 2019
@author: asiddi24
"""
'''Running the box_model'''
'''Initializing variables'''
from box_model import fourbox
N=4000
Kv=1e-5
AI=1000
Mek=25e6
Aredi=1000
M_s=15e6
D0=500
T0s=2
T0n=4
T0l=17
T0d=3
S0s=34
S0n=35
S0l=36
S0d=34.5
Fws=1... | en | 0.520058 | #!/usr/bin/env python3 # -*- coding: utf-8 -*- Created on Thu Jun 6 10:27:14 2019 @author: asiddi24 Running the box_model Initializing variables | 2.073694 | 2 |
test_pysolar.py | JohnOmernik/solarpi | 1 | 6622060 | #!/usr/bin/python3
from pysolar import solar
import time
import datetime
import pytz
import os.path
MYLAT = 1000.0
MYLNG = 1000.0
STRTZ = ""
ENV_FILE = "env.list"
if not os.path.isfile(ENV_FILE):
print("ENV_FILE at %s not found - exiting")
sys.exit(1)
e = open(ENV_FILE, "r")
lines = e.read()
e.close()
for ... | #!/usr/bin/python3
from pysolar import solar
import time
import datetime
import pytz
import os.path
MYLAT = 1000.0
MYLNG = 1000.0
STRTZ = ""
ENV_FILE = "env.list"
if not os.path.isfile(ENV_FILE):
print("ENV_FILE at %s not found - exiting")
sys.exit(1)
e = open(ENV_FILE, "r")
lines = e.read()
e.close()
for ... | en | 0.44471 | #!/usr/bin/python3 #date = datetime.datetime(2018, 10, 22, 13, 20, 10, 130320) | 2.9041 | 3 |
array/0922_sort_array_by_parity_ii/0922_sort_array_by_parity_ii.py | zdyxry/LeetCode | 6 | 6622061 | <reponame>zdyxry/LeetCode
# -*- coding: utf-8 -*-
class Solution(object):
def sortArrayByParityII(self, A):
"""
:type A: List[int]
:rtype: List[int]
"""
j = 1
for i in xrange(0, len(A), 2):
if A[i] % 2:
while A[j] % 2:
... | # -*- coding: utf-8 -*-
class Solution(object):
def sortArrayByParityII(self, A):
"""
:type A: List[int]
:rtype: List[int]
"""
j = 1
for i in xrange(0, len(A), 2):
if A[i] % 2:
while A[j] % 2:
j += 2
A[i... | en | 0.504075 | # -*- coding: utf-8 -*- :type A: List[int] :rtype: List[int] | 3.455213 | 3 |
etl/scripts.py | GrishenkovP/flask_unit_economy | 1 | 6622062 | # импорт библиотек
from typing import List, Tuple, Dict, Set
import pandas as pd
import sqlite3
import datetime as dt
def func_extract_transform(path: str) -> pd.DataFrame:
"""Предварительная обработка датасета"""
# Считываем датасет
df = pd.read_csv(path, sep=',')
# Приводим названия столб... | # импорт библиотек
from typing import List, Tuple, Dict, Set
import pandas as pd
import sqlite3
import datetime as dt
def func_extract_transform(path: str) -> pd.DataFrame:
"""Предварительная обработка датасета"""
# Считываем датасет
df = pd.read_csv(path, sep=',')
# Приводим названия столб... | ru | 0.980142 | # импорт библиотек Предварительная обработка датасета # Считываем датасет # Приводим названия столбцов датасета к нижнему регистру # Избавляемся от времени и трансформируем строку-дату в правильный формат # Рассчитываем сумму покупки по каждому товару # Удаляем ненужные для дальнейшего анализа столбцы # Заполняем строк... | 3.045467 | 3 |
opportune/tests/test_search.py | Mildly-Sketchy/Mildly-Sketchy | 0 | 6622063 | from pyramid import testing
def test_render_search_view(dummy_request):
"""Test search view"""
from ..views.search import search_view
response = search_view(dummy_request)
assert type(response) == dict
def test_search_view_no_keywords(dummy_request):
"""Test search view response when the user doe... | from pyramid import testing
def test_render_search_view(dummy_request):
"""Test search view"""
from ..views.search import search_view
response = search_view(dummy_request)
assert type(response) == dict
def test_search_view_no_keywords(dummy_request):
"""Test search view response when the user doe... | en | 0.794286 | Test search view Test search view response when the user does not give any keywords Test search view with no keywords Test search view returns keywords with fake authenticated user test handle keywords bad request test that it gets the key word test that a number throws the correct error test delete keywords bad reques... | 2.51929 | 3 |
storymaker/english.py | bitcraft/storymaker | 6 | 6622064 | from pygoap.precepts import *
def name(p):
try:
return p.name
except AttributeError:
return p
def make_english(caller, p):
"""
create an english phrase from a precept
very simple!!
:rtype : str
"""
if isinstance(p, DatumPrecept):
if p.entity is caller:
... | from pygoap.precepts import *
def name(p):
try:
return p.name
except AttributeError:
return p
def make_english(caller, p):
"""
create an english phrase from a precept
very simple!!
:rtype : str
"""
if isinstance(p, DatumPrecept):
if p.entity is caller:
... | en | 0.724139 | create an english phrase from a precept very simple!! :rtype : str | 3.083351 | 3 |
dashboard/layout/navbar.py | PPBP-2021/photogrammetry | 0 | 6622065 | import dash
import dash_bootstrap_components as dbc
from dash import dcc
from dash import html
layout = dbc.NavbarSimple(
children=[
dbc.DropdownMenu(
children=[
dbc.DropdownMenuItem("Image Segmentation", href="segmentation"),
dbc.DropdownMenuItem("Litophane", h... | import dash
import dash_bootstrap_components as dbc
from dash import dcc
from dash import html
layout = dbc.NavbarSimple(
children=[
dbc.DropdownMenu(
children=[
dbc.DropdownMenuItem("Image Segmentation", href="segmentation"),
dbc.DropdownMenuItem("Litophane", h... | none | 1 | 2.174537 | 2 | |
tests/Transform/test_Transform.py | kamilazdybal/multipy | 0 | 6622066 | import unittest
import numpy as np
import multipy
################################################################################
################################################################################
####
#### Class: Transform
####
########################################################################... | import unittest
import numpy as np
import multipy
################################################################################
################################################################################
####
#### Class: Transform
####
########################################################################... | de | 0.8686 | ################################################################################ ################################################################################ #### #### Class: Transform #### ################################################################################ ##########################################... | 2.684736 | 3 |
taxi_domain/methods/train_autoencoder_for_kmeans.py | CORE-Robotics-Lab/Personalized_Neural_Trees | 3 | 6622067 | """
trains autoencoder
"""
import torch
import sys
import torch.nn as nn
import pickle
import os
# sys.path.insert(0, '/home/Anonymous/PycharmProjects/bayesian_prolo')
import numpy as np
from torch.autograd import Variable
from utils.global_utils import save_pickle
import itertools
sys.path.insert(0, '../')
torch.b... | """
trains autoencoder
"""
import torch
import sys
import torch.nn as nn
import pickle
import os
# sys.path.insert(0, '/home/Anonymous/PycharmProjects/bayesian_prolo')
import numpy as np
from torch.autograd import Variable
from utils.global_utils import save_pickle
import itertools
sys.path.insert(0, '../')
torch.b... | en | 0.604618 | trains autoencoder # sys.path.insert(0, '/home/Anonymous/PycharmProjects/bayesian_prolo') autoencoder torch model forward pass :param x: :return: produce encoding :param x: :return: create and train the autoencoder # self.states = None loads in train data :return: # noinspection ... | 2.641095 | 3 |
json_to_relation/test/test_mongodb.py | paepcke/json_to_relation | 4 | 6622068 | <filename>json_to_relation/test/test_mongodb.py
# Copyright (c) 2014, Stanford University
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
# 1. Redistributions of source code must retain the above co... | <filename>json_to_relation/test/test_mongodb.py
# Copyright (c) 2014, Stanford University
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
# 1. Redistributions of source code must retain the above co... | en | 0.724218 | # Copyright (c) 2014, Stanford University # All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: # 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the ... | 1.525905 | 2 |
reddit2telegram/channels/smilethoughts/app.py | mainyordle/reddit2telegram | 187 | 6622069 | <filename>reddit2telegram/channels/smilethoughts/app.py<gh_stars>100-1000
#encoding:utf-8
subreddit = 'MadeMeSmile'
t_channel = '@SmileThoughts'
def send_post(submission, r2t):
return r2t.send_simple(submission)
| <filename>reddit2telegram/channels/smilethoughts/app.py<gh_stars>100-1000
#encoding:utf-8
subreddit = 'MadeMeSmile'
t_channel = '@SmileThoughts'
def send_post(submission, r2t):
return r2t.send_simple(submission)
| en | 0.735217 | #encoding:utf-8 | 1.379314 | 1 |
scrape_korea.py | LiveCoronaDetector/Crawler | 8 | 6622070 | # -*- coding:utf-8 -*-
"""대한민국 (+ 세계) 환자수 수집"""
import re
import time
import requests
from bs4 import BeautifulSoup
from utils import postprocess, load_json
from slack_handler import SlackHandler
patients = load_json("./_data.json")
# def scrape_namuWiki():
# """나무위키에서 대한민국 확진환자수, 격리해제수, 사망자수 수집
#
# Return... | # -*- coding:utf-8 -*-
"""대한민국 (+ 세계) 환자수 수집"""
import re
import time
import requests
from bs4 import BeautifulSoup
from utils import postprocess, load_json
from slack_handler import SlackHandler
patients = load_json("./_data.json")
# def scrape_namuWiki():
# """나무위키에서 대한민국 확진환자수, 격리해제수, 사망자수 수집
#
# Return... | ko | 0.790841 | # -*- coding:utf-8 -*- 대한민국 (+ 세계) 환자수 수집 # def scrape_namuWiki(): # """나무위키에서 대한민국 확진환자수, 격리해제수, 사망자수 수집 # # Returns: # (dict) 한국의 세계 확진환자수(cc), 격리해제수(recovered), 사망자수(dead) # """ # html = requests.get("https://namu.wiki/w/%EC%8B%A0%EC%A2%85%20%EC%BD%94%EB%A1%9C%EB%82%98%EB%B0%94%EC%9D%B4%EB%9F... | 2.807457 | 3 |
src/data/wave_cir.py | poly-ai/fluid-surface-estimation | 2 | 6622071 | import numpy as np
import math
from matplotlib.image import AxesImage
import matplotlib.pyplot as plt
import matplotlib.animation as animation
# Fixed for the time being...
WAVE_FREQ = 10 # This scalar defines the speed of the wave
WAVE_NUMBER = 1 # This scalar defines the speed of the wave
X_CENTER = np.pi
... | import numpy as np
import math
from matplotlib.image import AxesImage
import matplotlib.pyplot as plt
import matplotlib.animation as animation
# Fixed for the time being...
WAVE_FREQ = 10 # This scalar defines the speed of the wave
WAVE_NUMBER = 1 # This scalar defines the speed of the wave
X_CENTER = np.pi
... | en | 0.54219 | # Fixed for the time being... # This scalar defines the speed of the wave # This scalar defines the speed of the wave # Constant now (Don't change this) # This vector defines the direction of the travelling wave. # The magnitude of this vector defines the "length" of the wave # Data to generate # Deltas, num ticks in e... | 3.374965 | 3 |
flowerpath.py | laurentgrangeau/minecraft-pi | 1 | 6622072 | <filename>flowerpath.py
import mcpi.minecraft as minecraft
import time
mc = minecraft.Minecraft.create()
while True:
pos = mc.player.getPos()
x = pos.x
y = pos.y
z = pos.z
block = 38
mc.setBlock(x, y, z, block)
time.sleep(0.2)
| <filename>flowerpath.py
import mcpi.minecraft as minecraft
import time
mc = minecraft.Minecraft.create()
while True:
pos = mc.player.getPos()
x = pos.x
y = pos.y
z = pos.z
block = 38
mc.setBlock(x, y, z, block)
time.sleep(0.2)
| none | 1 | 2.114092 | 2 | |
src/luq.py | zfergus2/APLMOO | 1 | 6622073 | <reponame>zfergus2/APLMOO
"""
Compute the LUQ decomposition of a sparse square matrix.
Based on Pawel Kowal's MatLab code.
Written by: <NAME>
"""
import numpy
import scipy.sparse
import scipy.sparse.linalg
def luq(A, do_pivot, tol = 1e-8):
"""
PURPOSE: calculates the following decomposition
A = L |... | """
Compute the LUQ decomposition of a sparse square matrix.
Based on Pawel Kowal's MatLab code.
Written by: <NAME>
"""
import numpy
import scipy.sparse
import scipy.sparse.linalg
def luq(A, do_pivot, tol = 1e-8):
"""
PURPOSE: calculates the following decomposition
A = L |Ubar 0 | Q
... | de | 0.392463 | Compute the LUQ decomposition of a sparse square matrix. Based on Pawel Kowal's MatLab code. Written by: <NAME> PURPOSE: calculates the following decomposition A = L |Ubar 0 | Q |0 0 | where Ubar is a square invertible matrix and matrices L, Q are invertible. USAGE: [L... | 3.567048 | 4 |
aperte/base/views.py | smevirtual/aperte | 0 | 6622074 | <reponame>smevirtual/aperte
# Copyright 2018 SME Virtual Network Contributors. 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/LICE... | # Copyright 2018 SME Virtual Network Contributors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required ... | en | 0.686578 | # Copyright 2018 SME Virtual Network Contributors. 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 ... | 2.095135 | 2 |
py2pxd_/pxclass.py | secretyv/py2pxd | 0 | 6622075 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import ast
import logging
from .pxreader import PXReader
from .pxvariable import PXVariable
from .pxfunction import PXFunction
LOGGER = logging.getLogger("INRS.IEHSS.Python.cython.class")
class PXClass(ast.NodeVisitor, PXReader):
def __init__(self):
super(... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import ast
import logging
from .pxreader import PXReader
from .pxvariable import PXVariable
from .pxfunction import PXFunction
LOGGER = logging.getLogger("INRS.IEHSS.Python.cython.class")
class PXClass(ast.NodeVisitor, PXReader):
def __init__(self):
super(... | en | 0.339342 | #!/usr/bin/env python # -*- coding: utf-8 -*- #-------------------- # Python source code parser (ast visitors) #-------------------- Class attributes # --- Look for childrens # --- Resolve first childrens # --- Remove attributes allready defined in parent #-------------------- # Reader for pxd files #-----------... | 2.566183 | 3 |
translation/filters.py | paxenarius/ajiragis-api | 0 | 6622076 | import django_filters
from .models import Word
class WordFilter(django_filters.FilterSet):
iso_639_2_code = django_filters.CharFilter(method='word_iso_code_fiiler')
class Meta:
model = Word
fields = ['word', 'language', 'iso_639_2_code', 'part_of_speech']
def word_iso_code_fiiler(self,... | import django_filters
from .models import Word
class WordFilter(django_filters.FilterSet):
iso_639_2_code = django_filters.CharFilter(method='word_iso_code_fiiler')
class Meta:
model = Word
fields = ['word', 'language', 'iso_639_2_code', 'part_of_speech']
def word_iso_code_fiiler(self,... | none | 1 | 2.332231 | 2 | |
src/evaluation/evaluator_loe.py | tiefenauer/ip7-python | 0 | 6622077 | from src.database.classification_results import LoeClassificationResults
from src.evaluation.evaluator import Evaluator
from src.scoring.loe_scorer_linear import LinearLoeScorer
from src.scoring.loe_scorer_strict import StrictLoeScorer
from src.scoring.loe_scorer_tolerant import TolerantLoeScorer
class LoeEvaluator(E... | from src.database.classification_results import LoeClassificationResults
from src.evaluation.evaluator import Evaluator
from src.scoring.loe_scorer_linear import LinearLoeScorer
from src.scoring.loe_scorer_strict import StrictLoeScorer
from src.scoring.loe_scorer_tolerant import TolerantLoeScorer
class LoeEvaluator(E... | none | 1 | 2.429915 | 2 | |
newsletter/models.py | elyak123/imagewrite | 0 | 6622078 | <reponame>elyak123/imagewrite
from django.db import models
from .storages import upload_to_image_1, OverwriteStorage, Image1Storage
class Newsletter(models.Model):
def upload_to_image_2(self, filename):
if self.pk:
pk = self.pk
else:
instance = Newsletter.objects.all().orde... | from django.db import models
from .storages import upload_to_image_1, OverwriteStorage, Image1Storage
class Newsletter(models.Model):
def upload_to_image_2(self, filename):
if self.pk:
pk = self.pk
else:
instance = Newsletter.objects.all().order_by("-pk").first()
... | none | 1 | 2.259729 | 2 | |
server/framework/lib/classes/__init__.py | tetelevm/OrdeRPG | 0 | 6622079 | """
A submodule with individual classes.
"""
from .env_parser import __all_for_module__ as __env_parser_all__
from .hasher import __all_for_module__ as __hasher_all__
from .singleton import __all_for_module__ as __singleton_all__
from .env_parser import *
from .hasher import *
from .singleton import *
__all_for_mod... | """
A submodule with individual classes.
"""
from .env_parser import __all_for_module__ as __env_parser_all__
from .hasher import __all_for_module__ as __hasher_all__
from .singleton import __all_for_module__ as __singleton_all__
from .env_parser import *
from .hasher import *
from .singleton import *
__all_for_mod... | en | 0.637494 | A submodule with individual classes. | 1.389239 | 1 |
simulator/customer.py | animilimina/customer_activity_simulator | 1 | 6622080 | <reponame>animilimina/customer_activity_simulator
import settings
from random import random
from numpy.random import normal
class Customer:
def __init__(self, first_period: int, last_period: int, average_returning_rate: float, average_reactivation_rate:float, average_survival_rate: float):
self.__first_pe... | import settings
from random import random
from numpy.random import normal
class Customer:
def __init__(self, first_period: int, last_period: int, average_returning_rate: float, average_reactivation_rate:float, average_survival_rate: float):
self.__first_period = first_period
self.__last_period = l... | none | 1 | 2.980429 | 3 | |
experiments/ZxH.py | Vrekrer/magdynlab | 6 | 6622081 | # -*- coding: utf-8 -*-
import numpy
import time
import os
import magdynlab.instruments
import magdynlab.controllers
import magdynlab.data_types
import threading_decorators as ThD
import matplotlib.pyplot as plt
@ThD.gui_safe
def Plot_ColorMap(Data):
f = plt.figure('ZxH', (5, 4))
extent = numpy.array([Data['... | # -*- coding: utf-8 -*-
import numpy
import time
import os
import magdynlab.instruments
import magdynlab.controllers
import magdynlab.data_types
import threading_decorators as ThD
import matplotlib.pyplot as plt
@ThD.gui_safe
def Plot_ColorMap(Data):
f = plt.figure('ZxH', (5, 4))
extent = numpy.array([Data['... | en | 0.741633 | # -*- coding: utf-8 -*- #check Y scale #Experimental/plot data #Z vs hs vs fs #Z vs ts vs fs #|Z| vs hs vs fs # Update up to i column # Update up to i column # Update up to i column # Loop for each field # Loop for each field | 2.125227 | 2 |
test_grader_lib/testPolarTransform.py | rmok57/sketchresponse | 11 | 6622082 | <filename>test_grader_lib/testPolarTransform.py
from __future__ import absolute_import
from __future__ import division
import unittest
from . import TestDataPolar
from grader_lib import GradeableFunction
from grader_lib import Point
from math import pi, sqrt
class TestPolarTransform(TestDataPolar.TestDataPolar):
... | <filename>test_grader_lib/testPolarTransform.py
from __future__ import absolute_import
from __future__ import division
import unittest
from . import TestDataPolar
from grader_lib import GradeableFunction
from grader_lib import Point
from math import pi, sqrt
class TestPolarTransform(TestDataPolar.TestDataPolar):
... | none | 1 | 3.001001 | 3 | |
run.py | slackr31337/home-agent | 1 | 6622083 | <filename>run.py
#!/usr/bin/env python3
"""Run the HomeAgent as a service"""
import sys
import threading
import traceback
import logging
from utilities.log import LOGGER
from utilities.states import ThreadSafeDict
from scheduler import Scheduler
from agent_args import parse_args
from agent import LOG_PREFIX, HomeAge... | <filename>run.py
#!/usr/bin/env python3
"""Run the HomeAgent as a service"""
import sys
import threading
import traceback
import logging
from utilities.log import LOGGER
from utilities.states import ThreadSafeDict
from scheduler import Scheduler
from agent_args import parse_args
from agent import LOG_PREFIX, HomeAge... | de | 0.630523 | #!/usr/bin/env python3 Run the HomeAgent as a service ######################################### Run Home Agent Service ######################################### Main run function # pylint: disable=broad-except ######################################### | 2.494845 | 2 |
app.py | andreasca/covid-dashboard | 0 | 6622084 | import dash
import dash_core_components as dcc
import dash_flexbox_grid as dfx
import dash_html_components as html
from dash.dependencies import Input, Output
import dash_table
import flask
import glob
import os
import pathlib
import numpy as np
import pandas as pd
import re
scriptdir = pathlib.Path(os.getcwd()) # ... | import dash
import dash_core_components as dcc
import dash_flexbox_grid as dfx
import dash_html_components as html
from dash.dependencies import Input, Output
import dash_table
import flask
import glob
import os
import pathlib
import numpy as np
import pandas as pd
import re
scriptdir = pathlib.Path(os.getcwd()) # ... | en | 0.263304 | # this notebook # directory where the csv files are # # world # csv_path = outputdir / 'Staight_Line_COVID_Prediction_Table_world.csv' # print(csv_path) # df = pd.read_csv(csv_path) # # US # csv_path = outputdir / 'Staight_Line_COVID_Prediction_Table_us.csv' # print(csv_path) # df_us = pd.read_csv(csv_path) # # # CA # ... | 2.287803 | 2 |
tests/collections/asr/test_asr_datasets.py | vadam5/NeMo | 10 | 6622085 | # Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | # Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | en | 0.824047 | # Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appli... | 1.834524 | 2 |
demo/PYTHON3/zouwu.py | Yunlei-AI/ZouWu | 8 | 6622086 | <reponame>Yunlei-AI/ZouWu
import os
import ctypes
from ctypes import CDLL
class ZouWu(object):
def __init__(
self,
library_path):
if not os.path.exists(library_path):
raise IOError("Zouwu library path erro at '%s'" % library_path)
#
... | import os
import ctypes
from ctypes import CDLL
class ZouWu(object):
def __init__(
self,
library_path):
if not os.path.exists(library_path):
raise IOError("Zouwu library path erro at '%s'" % library_path)
#
#self.zouwulib = CDLL(libr... | en | 0.276556 | # #self.zouwulib = CDLL(library_path) # init # load model #self.zouwulib.ZouwuLoadModel(self.zouwu_pInst, model_path.encode()) #set Param #c_sensitivity = ctypes.c_float(sensitivity) #pcmd=ctypes.c_char_p(b'sensitivity') #mdlid=ctypes.c_int(1) #self.zouwulib.ZouwuSetParam(self.zouwu_pInst,pcmd,ctypes.byref(c_sensitivit... | 2.322797 | 2 |
playground/server test.py | antonloof/lnpsController | 0 | 6622087 | import socket, json, serial, time
## ps communication constants
MSG_TYPE_SEND = 0xC0
MSG_TYPE_QUERY = 0x40
MSG_TYPE_ANSWER = 0x80
CAST_TYPE_ANSWER_FROM_DEV = 0x00
CAST_TYPE_BROADCAST = 0x20
DIRECTION_FROM_PC = 0x10
DIRECTION_FROM_DEV = 0x00
TRANSMISSION_LATENCY = 0.050 #50 ms
class ComObject:
DEV_TYPE ... | import socket, json, serial, time
## ps communication constants
MSG_TYPE_SEND = 0xC0
MSG_TYPE_QUERY = 0x40
MSG_TYPE_ANSWER = 0x80
CAST_TYPE_ANSWER_FROM_DEV = 0x00
CAST_TYPE_BROADCAST = 0x20
DIRECTION_FROM_PC = 0x10
DIRECTION_FROM_DEV = 0x00
TRANSMISSION_LATENCY = 0.050 #50 ms
class ComObject:
DEV_TYPE ... | en | 0.491018 | ## ps communication constants #50 ms ## ps communication helpers # wait for some time to pass in order not to bombard the ps with requests ## load json ## establish which port talks to which ps ## start threads for com ports ## start web server ## delegate serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM... | 2.253575 | 2 |
ana/OpticksIdentity.py | hanswenzel/opticks | 11 | 6622088 | <gh_stars>10-100
#!/usr/bin/env python
"""
In [80]: trpo[trpo[:,1] == 5]
Out[80]:
array([[83886080, 5, 0, 0],
[83886081, ... | #!/usr/bin/env python
"""
In [80]: trpo[trpo[:,1] == 5]
Out[80]:
array([[83886080, 5, 0, 0],
[83886081, 5, 0, ... | en | 0.318317 | #!/usr/bin/env python In [80]: trpo[trpo[:,1] == 5] Out[80]: array([[83886080, 5, 0, 0], [83886081, 5, 0, 1]... | 2.316205 | 2 |
displayio/_bitmap.py | adafruit/Adafruit_Blinka_displayio | 0 | 6622089 | <gh_stars>0
# SPDX-FileCopyrightText: 2020 <NAME> for Adafruit Industries
#
# SPDX-License-Identifier: MIT
"""
`displayio.bitmap`
================================================================================
displayio for Blinka
**Software and Dependencies:**
* Adafruit Blinka:
https://github.com/adafruit/Adaf... | # SPDX-FileCopyrightText: 2020 <NAME> for Adafruit Industries
#
# SPDX-License-Identifier: MIT
"""
`displayio.bitmap`
================================================================================
displayio for Blinka
**Software and Dependencies:**
* Adafruit Blinka:
https://github.com/adafruit/Adafruit_Blinka/... | en | 0.565492 | # SPDX-FileCopyrightText: 2020 <NAME> for Adafruit Industries # # SPDX-License-Identifier: MIT `displayio.bitmap` ================================================================================ displayio for Blinka **Software and Dependencies:** * Adafruit Blinka: https://github.com/adafruit/Adafruit_Blinka/relea... | 2.675762 | 3 |
plastering/inferencers/algorithm/GeneticAlgorithm/colocation/utils/paths.py | MingzheWu418/plastering | 0 | 6622090 | <reponame>MingzheWu418/plastering<gh_stars>0
"""Helper function that deal with paths
"""
import pathlib
def create_dir(dir_name):
"""Create a dir if it does not already exist
Args:
dir_name (str): the directory name
Raises:
FileExistsError: If the path specified already exists and is a ... | """Helper function that deal with paths
"""
import pathlib
def create_dir(dir_name):
"""Create a dir if it does not already exist
Args:
dir_name (str): the directory name
Raises:
FileExistsError: If the path specified already exists and is a file
"""
path = pathlib.Path(dir_nam... | en | 0.712992 | Helper function that deal with paths Create a dir if it does not already exist Args: dir_name (str): the directory name Raises: FileExistsError: If the path specified already exists and is a file | 4.096374 | 4 |
algorithms/graphs/dijkstra.py | mchao409/python-algorithms | 3 | 6622091 | <filename>algorithms/graphs/dijkstra.py
"""
Dijkstra's algorithm is an algorithm for finding the shortest paths between nodes in a graph,
which may represent, for example, road networks.
It was conceived by computer scientist <NAME> in 1956 and published three years later [Wikipedia]
Worst-case Performance: O(|E|+|V| ... | <filename>algorithms/graphs/dijkstra.py
"""
Dijkstra's algorithm is an algorithm for finding the shortest paths between nodes in a graph,
which may represent, for example, road networks.
It was conceived by computer scientist <NAME> in 1956 and published three years later [Wikipedia]
Worst-case Performance: O(|E|+|V| ... | en | 0.87643 | Dijkstra's algorithm is an algorithm for finding the shortest paths between nodes in a graph, which may represent, for example, road networks. It was conceived by computer scientist <NAME> in 1956 and published three years later [Wikipedia] Worst-case Performance: O(|E|+|V| log |V|) Solves shortest path problem using ... | 3.904464 | 4 |
scripts/make_simulations.py | Karthikprabhu22/lynx | 0 | 6622092 | <filename>scripts/make_simulations.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#######################################################################
#
# This script is used to generate simulations for B-mode forecasting.
#
#
#
#
#
#
#
#######################################################################
im... | <filename>scripts/make_simulations.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#######################################################################
#
# This script is used to generate simulations for B-mode forecasting.
#
#
#
#
#
#
#
#######################################################################
im... | en | 0.250339 | #!/usr/bin/env python # -*- coding: utf-8 -*- ####################################################################### # # This script is used to generate simulations for B-mode forecasting. # # # # # # # ####################################################################### Frequencies: {freqs!s} Nside: {nside:04d... | 2.09422 | 2 |
tests/unit_tests.py | peterjiz/pytorch-colors | 187 | 6622093 | import torch
import torch.cuda
from torch.autograd import Variable
import unittest
import sys
import pytorch_colors as colors
class TestColorConversion(unittest.TestCase):
def test_yuv(self):
a = torch.randn(1, 3, 512, 512).clamp(0, 1)
a_yuv = colors.rgb_to_yuv(a)
a_ = colors.yuv_to_rgb(a_y... | import torch
import torch.cuda
from torch.autograd import Variable
import unittest
import sys
import pytorch_colors as colors
class TestColorConversion(unittest.TestCase):
def test_yuv(self):
a = torch.randn(1, 3, 512, 512).clamp(0, 1)
a_yuv = colors.rgb_to_yuv(a)
a_ = colors.yuv_to_rgb(a_y... | none | 1 | 2.663749 | 3 | |
googledevices/utils/__init__.py | vlebourl/googledevices | 19 | 6622094 | <reponame>vlebourl/googledevices<filename>googledevices/utils/__init__.py
"""Initialize the utils."""
| """Initialize the utils.""" | en | 0.603895 | Initialize the utils. | 1.215801 | 1 |
LeReS/Train/tools/parse_arg_base.py | chensjtu/AdelaiDepth | 0 | 6622095 | import argparse
class BaseOptions():
def __init__(self):
self.initialized = False
def initialize(self, parser):
parser.add_argument('--backbone', type=str, default='resnet50', help='Select backbone type, resnet50 or resnext101')
parser.add_argument('--batchsize', type=int, default=2, h... | import argparse
class BaseOptions():
def __init__(self):
self.initialized = False
def initialize(self, parser):
parser.add_argument('--backbone', type=str, default='resnet50', help='Select backbone type, resnet50 or resnext101')
parser.add_argument('--batchsize', type=int, default=2, h... | en | 0.048483 | # parser.add_argument('--optim', default='SGD', help='Select optimizer, SGD or Adam') # parser.add_argument('--start_epoch', default=0, type=int, help='Set training epochs') # parser.add_argument('--results_dir', type=str, default='./evaluation', help='Output dir') # parser.add_argument('--diff_loss_weight', default=1,... | 2.273029 | 2 |
catalog/bindings/csw/polygon.py | NIVANorge/s-enda-playground | 0 | 6622096 | <gh_stars>0
from dataclasses import dataclass
from bindings.csw.polygon_type import PolygonType
__NAMESPACE__ = "http://www.opengis.net/gml"
@dataclass
class Polygon(PolygonType):
class Meta:
namespace = "http://www.opengis.net/gml"
| from dataclasses import dataclass
from bindings.csw.polygon_type import PolygonType
__NAMESPACE__ = "http://www.opengis.net/gml"
@dataclass
class Polygon(PolygonType):
class Meta:
namespace = "http://www.opengis.net/gml" | none | 1 | 2.231394 | 2 | |
example/gen_chinese_data.py | johnson7788/OpenNRE | 5 | 6622097 | <reponame>johnson7788/OpenNRE<filename>example/gen_chinese_data.py<gh_stars>1-10
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2021/3/19 10:58 上午
# @File : gen_chinese_data.py
# @Author: johnson
# @Contact : github: johnson7788
# @Desc : 根据Chinese-Literature-NER-RE-Dataset提供的数据格式,生成我们需要的训练数据格式
# 由于Chinese-... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2021/3/19 10:58 上午
# @File : gen_chinese_data.py
# @Author: johnson
# @Contact : github: johnson7788
# @Desc : 根据Chinese-Literature-NER-RE-Dataset提供的数据格式,生成我们需要的训练数据格式
# 由于Chinese-Literature-NER-RE-Dataset是文档级的数据,所以其实需要更高效的训练和预测方法
import os
import json
import r... | zh | 0.785852 | #!/usr/bin/env python # -*- coding: utf-8 -*- # @Date : 2021/3/19 10:58 上午 # @File : gen_chinese_data.py # @Author: johnson # @Contact : github: johnson7788 # @Desc : 根据Chinese-Literature-NER-RE-Dataset提供的数据格式,生成我们需要的训练数据格式 # 由于Chinese-Literature-NER-RE-Dataset是文档级的数据,所以其实需要更高效的训练和预测方法 根据Chinese-Literature-NER-RE-Da... | 2.56416 | 3 |
bias_detector/fuzzy_names_from_emails/FullName.py | yairhoresh/bias-detector | 50 | 6622098 | <reponame>yairhoresh/bias-detector<gh_stars>10-100
import pandas as pd
class FullName:
def __init__(self, first_name: str, last_name: str) -> None:
self.first_name = first_name
self.last_name = last_name
def is_empty(self) -> bool:
return (self.first_name is None or self.first_name ... | import pandas as pd
class FullName:
def __init__(self, first_name: str, last_name: str) -> None:
self.first_name = first_name
self.last_name = last_name
def is_empty(self) -> bool:
return (self.first_name is None or self.first_name == '') \
and (self.last_name is None ... | none | 1 | 3.276055 | 3 | |
datasets/general_dataset.py | huhongjun/3d-semantic-segmentation | 98 | 6622099 | import os
import numpy as np
import datasets.color_constants as cc
from tools.lazy_decorator import *
from typing import Tuple, List, Dict
import logging
class GeneralDataset:
"""
Class used for reading in datasets for training/testing.
Parameterized in order to handle different kinds of datasets (e.g. k-... | import os
import numpy as np
import datasets.color_constants as cc
from tools.lazy_decorator import *
from typing import Tuple, List, Dict
import logging
class GeneralDataset:
"""
Class used for reading in datasets for training/testing.
Parameterized in order to handle different kinds of datasets (e.g. k-... | en | 0.842776 | Class used for reading in datasets for training/testing. Parameterized in order to handle different kinds of datasets (e.g. k-fold datasets) # it is possible that there is no class information given for test sets # log some dataset properties calculate the number of unique class labels if class information is given... | 2.595157 | 3 |
musicstore/musicapp/views.py | hannahclee/recordreview | 0 | 6622100 | <filename>musicstore/musicapp/views.py
from django.shortcuts import render
from .models import Artist
from .models import Record
from .models import Review
from django.shortcuts import render, get_object_or_404
from .forms import RecordForm, ReviewForm
from django.contrib.auth.decorators import login_required
# Create... | <filename>musicstore/musicapp/views.py
from django.shortcuts import render
from .models import Artist
from .models import Record
from .models import Review
from django.shortcuts import render, get_object_or_404
from .forms import RecordForm, ReviewForm
from django.contrib.auth.decorators import login_required
# Create... | en | 0.968116 | # Create your views here. | 2.140226 | 2 |
LBP_SVM/classifier.py | VieVie31/kaggle_invasive_species | 1 | 6622101 | import random
import numpy as np
import pandas as pd
from sklearn.svm import SVC
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.externals import joblib
import warnings
warnings.filterwarnings('ignore')
#reproductibility
random.seed(1996)
np.rand... | import random
import numpy as np
import pandas as pd
from sklearn.svm import SVC
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.externals import joblib
import warnings
warnings.filterwarnings('ignore')
#reproductibility
random.seed(1996)
np.rand... | en | 0.694168 | #reproductibility #load training labels #load training data (allready normalized) #shuffling data #split training set #train a SVC classifier #train a RandomForestClassifier classifier #load testing data (allready normalized) #save the ouput for kaggle in csv | 2.801479 | 3 |
src/selfcoin/common/globall.py | wangyubin112/selfcoin | 0 | 6622102 | <reponame>wangyubin112/selfcoin<gh_stars>0
'''
c : card
ch : chain
s : socket
f : file
fo : folder
l : line
m : mutual
i : index
p : position/pointer
G : globall
T : tune
'''
'''
TRADE protocol:
deferred trade (need server to involve):
(pay) demand newest mutual card --> server... | '''
c : card
ch : chain
s : socket
f : file
fo : folder
l : line
m : mutual
i : index
p : position/pointer
G : globall
T : tune
'''
'''
TRADE protocol:
deferred trade (need server to involve):
(pay) demand newest mutual card --> server
(server) demand ack ... | en | 0.671314 | c : card
ch : chain
s : socket
f : file
fo : folder
l : line
m : mutual
i : index
p : position/pointer
G : globall
T : tune TRADE protocol:
deferred trade (need server to involve):
(pay) demand newest mutual card --> server
(server) demand ack --> pay
(p... | 2.150824 | 2 |
reviews/management/commands/create_reviews.py | Flict-dev/Boxes-api | 1 | 6622103 | from django.core.exceptions import ValidationError
from django.core.management import BaseCommand
from items.models import Item
from reviews.models import Reviews
from users.models import User
import requests
class Command(BaseCommand):
def handle(self, *args, **options):
response_review = requests.get(
... | from django.core.exceptions import ValidationError
from django.core.management import BaseCommand
from items.models import Item
from reviews.models import Reviews
from users.models import User
import requests
class Command(BaseCommand):
def handle(self, *args, **options):
response_review = requests.get(
... | none | 1 | 2.249508 | 2 | |
relaax/common/algorithms/subgraph.py | deeplearninc/relaax | 71 | 6622104 | from builtins import object
import tensorflow as tf
import re
class Subgraph(object):
def __init__(self, *args, **kwargs):
with tf.variable_scope(None, default_name=type(self).__name__):
self.__node = self.build_graph(*args, **kwargs)
@property
def node(self):
return self.__n... | from builtins import object
import tensorflow as tf
import re
class Subgraph(object):
def __init__(self, *args, **kwargs):
with tf.variable_scope(None, default_name=type(self).__name__):
self.__node = self.build_graph(*args, **kwargs)
@property
def node(self):
return self.__n... | en | 0.298673 | # print('feed_dict') # for k, v in self.flatten_feed_dict(feed_dict).items(): # import numpy as np # print(repr(k), repr(np.asarray(v).shape)) | 2.598403 | 3 |
src/player.py | Jakub21/Disk-Game | 0 | 6622105 | class Player:
def __init__(self, name, pwd):
self.username = name
self.clr_choice = 'green'
def add_to_session(self, session):
self.session = session
self.color = session.get_color(self)
self.blnd_count = 0
self.unit_count = 0
self.r_wood = session.app.GA... | class Player:
def __init__(self, name, pwd):
self.username = name
self.clr_choice = 'green'
def add_to_session(self, session):
self.session = session
self.color = session.get_color(self)
self.blnd_count = 0
self.unit_count = 0
self.r_wood = session.app.GA... | none | 1 | 2.784716 | 3 | |
ReportarHardware.py | wisrovi/NurcallApp | 0 | 6622106 | <gh_stars>0
umbralTempCPU = 80
umbralTempGPU = 70
umbralRamUsada = 75
segundos = 600
import requests
import json
import platform
import subprocess as commands
import sched, time
class ObtenerIP:
def __init__(self):
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
... | umbralTempCPU = 80
umbralTempGPU = 70
umbralRamUsada = 75
segundos = 600
import requests
import json
import platform
import subprocess as commands
import sched, time
class ObtenerIP:
def __init__(self):
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect((... | es | 0.139489 | AUTHOR: WISROVI # Mostrar temperatura en grados Fahrenheit # return float(1.8*cpu_temp)+32 # Mostrar temperatura en grados Fahrenheit # return float(1.8* gpu_temp)+32 # Return RAM information (unit=kb) in a list # Index 0: total RAM # Index 1: used RAM # Index 2: free RAM #infoEnviar += "Soy la raspberry con IP: " + my... | 2.413883 | 2 |
Evaluation/packet_in_idle_new/merger.py | ManuelMeinen/DC-MONDRIAN | 0 | 6622107 | import pandas as pd
def merge(df1, df2):
total = df1['No_of_Packets']+df2['No_of_Packets']
result = {
'second': range(601),
'No_of_Packets': total[0:601]
}
res = pd.DataFrame(result,columns=['second','No_of_Packets'])
res['No_of_Packets'] = res['No_of_Packets'].astype(i... | import pandas as pd
def merge(df1, df2):
total = df1['No_of_Packets']+df2['No_of_Packets']
result = {
'second': range(601),
'No_of_Packets': total[0:601]
}
res = pd.DataFrame(result,columns=['second','No_of_Packets'])
res['No_of_Packets'] = res['No_of_Packets'].astype(i... | none | 1 | 2.912253 | 3 | |
bomeba0/external/__init__.py | aloctavodia/bomeba0 | 0 | 6622108 | <filename>bomeba0/external/__init__.py
from .gaussian import gen_tripeptides | <filename>bomeba0/external/__init__.py
from .gaussian import gen_tripeptides | none | 1 | 1.102084 | 1 | |
usercustomize.py | aroberge/ideas | 36 | 6622109 | <gh_stars>10-100
from ideas import experimental_syntax_encoding
print(f" --> {__file__} was executed")
| from ideas import experimental_syntax_encoding
print(f" --> {__file__} was executed") | none | 1 | 1.27316 | 1 | |
python/get_twitter_followers_id.py | zixels/booklio | 0 | 6622110 | # gets user ids of twitter followers of a specific account (user_screen_name) and
# saves them in a csv file named user_screen_name+'_followers_twitter_ids.csv'
# Imports
import os
import codecs
import time
import tweepy
# Inputs
user_screen_name = "AminSarafraz"
consumer_key = os.getenv("TWITTER_CONSUMER_KEY")
consu... | # gets user ids of twitter followers of a specific account (user_screen_name) and
# saves them in a csv file named user_screen_name+'_followers_twitter_ids.csv'
# Imports
import os
import codecs
import time
import tweepy
# Inputs
user_screen_name = "AminSarafraz"
consumer_key = os.getenv("TWITTER_CONSUMER_KEY")
consu... | en | 0.765515 | # gets user ids of twitter followers of a specific account (user_screen_name) and # saves them in a csv file named user_screen_name+'_followers_twitter_ids.csv' # Imports # Inputs # oAuth for twitter API # Get user ids for the followers of a user # To avoid exceeding Twitter API rate limit (15 GETS every 15 minutes) | 3.098141 | 3 |
tests/mock/i2c_checks_addr.py | jontrulson/mraa | 1,167 | 6622111 | #!/usr/bin/env python
# Author: <NAME> <<EMAIL>>
# Copyright (c) 2016 <NAME>.
#
# SPDX-License-Identifier: MIT
import mraa as m
import unittest as u
from i2c_checks_shared import *
class I2cChecksAddr(u.TestCase):
def setUp(self):
self.i2c = m.I2c(MRAA_I2C_BUS_NUM)
def tearDown(self):
del self.i2c
d... | #!/usr/bin/env python
# Author: <NAME> <<EMAIL>>
# Copyright (c) 2016 <NAME>.
#
# SPDX-License-Identifier: MIT
import mraa as m
import unittest as u
from i2c_checks_shared import *
class I2cChecksAddr(u.TestCase):
def setUp(self):
self.i2c = m.I2c(MRAA_I2C_BUS_NUM)
def tearDown(self):
del self.i2c
d... | en | 0.492743 | #!/usr/bin/env python # Author: <NAME> <<EMAIL>> # Copyright (c) 2016 <NAME>. # # SPDX-License-Identifier: MIT # For standard 7-bit addressing 0x7F is max address | 2.669222 | 3 |
formsnext/formsnext/report/survey_all_results/survey_all_results.py | ElasticRun/FormsNext | 3 | 6622112 | <reponame>ElasticRun/FormsNext
# Copyright (c) 2013, ElasticRun and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
import pandas as pd
def execute(filters=None):
survey = filters.get("survey")
query = """
SELECT
tuf.user,
tq.question_string ... | # Copyright (c) 2013, ElasticRun and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
import pandas as pd
def execute(filters=None):
survey = filters.get("survey")
query = """
SELECT
tuf.user,
tq.question_string AS Question,
tq.evaluate AS ... | en | 0.429014 | # Copyright (c) 2013, ElasticRun and contributors # For license information, please see license.txt SELECT tuf.user, tq.question_string AS Question, tq.evaluate AS Evaluate, (CASE WHEN tq.evaluate THEN trl.score ELSE NULL END) AS Score, GROUP_CONCAT(trv.value) AS Responses FROM `tabUser Feedback` tuf INN... | 2.429164 | 2 |
forecast/endpoints.py | brennv/surf-api | 2 | 6622113 | <reponame>brennv/surf-api
from .data import (get_response, parse_data, get_forecast, get_swell, get_wave,
get_wind_direction, get_wind_speed)
from flask_restful import Resource
class Health(Resource):
def get(self):
"""
API health check
---
tags:
- stat... | from .data import (get_response, parse_data, get_forecast, get_swell, get_wave,
get_wind_direction, get_wind_speed)
from flask_restful import Resource
class Health(Resource):
def get(self):
"""
API health check
---
tags:
- status
responses:
... | en | 0.495067 | API health check --- tags: - status responses: 200: description: Status check Point forecast --- tags: - point parameters: - name: lat in: path type: string required: true de... | 2.789472 | 3 |
crawlino/models/__init__.py | BBVA/crawlino | 1 | 6622114 | <gh_stars>1-10
from .bases import *
from .crawlino_model import *
from .plugins_models import *
from .input_model import *
| from .bases import *
from .crawlino_model import *
from .plugins_models import *
from .input_model import * | none | 1 | 1.127569 | 1 | |
circuitPython/examples/audio-playback/code.py | BRTSG-FOSS/pico-bteve | 1 | 6622115 | from brteve.brt_eve_bt817_8 import BrtEve
from brteve.brt_eve_rp2040 import BrtEveRP2040
from audio_playback.audio_playback import audio_playback
from audio_playback.widgets import widgets_dialog_yes_no
host = BrtEveRP2040()
eve = BrtEve(host)
eve.init(resolution="1280x800", touch="goodix")
# Store calibration setti... | from brteve.brt_eve_bt817_8 import BrtEve
from brteve.brt_eve_rp2040 import BrtEveRP2040
from audio_playback.audio_playback import audio_playback
from audio_playback.widgets import widgets_dialog_yes_no
host = BrtEveRP2040()
eve = BrtEve(host)
eve.init(resolution="1280x800", touch="goodix")
# Store calibration setti... | en | 0.214702 | # Store calibration setting #eve.wr32(eve.REG_TOUCH_TRANSFORM_A, 0xfffefefc); #eve.wr32(eve.REG_TOUCH_TRANSFORM_B, 0xfffffcbf); #eve.wr32(eve.REG_TOUCH_TRANSFORM_C, 0x506adb4); #eve.wr32(eve.REG_TOUCH_TRANSFORM_D, 0xfffffed1); #eve.wr32(eve.REG_TOUCH_TRANSFORM_E, 0xfffefc79); #eve.wr32(eve.REG_TOUCH_TRANSFORM_F, 0x32c3... | 1.908637 | 2 |
euporie/text.py | joouha/euporie | 505 | 6622116 | <reponame>joouha/euporie
# -*- coding: utf-8 -*-
"""Contains dpdated ANSI parsing and Formatted Text processing."""
from __future__ import annotations
import re
from typing import TYPE_CHECKING
from prompt_toolkit.formatted_text import ANSI as PTANSI
from prompt_toolkit.formatted_text import (
fragment_list_to_te... | # -*- coding: utf-8 -*-
"""Contains dpdated ANSI parsing and Formatted Text processing."""
from __future__ import annotations
import re
from typing import TYPE_CHECKING
from prompt_toolkit.formatted_text import ANSI as PTANSI
from prompt_toolkit.formatted_text import (
fragment_list_to_text,
split_lines,
... | en | 0.692737 | # -*- coding: utf-8 -*- Contains dpdated ANSI parsing and Formatted Text processing. Applies formatted text to a TextArea. Initiate the processor. Args: formatted_text: The text in a buffer but with formatting applied. Apply text formatting to a line in a buffer. Applies formatted text to a TextAre... | 2.547259 | 3 |
backtest.py | Yanjing-PENG/index_prediction | 0 | 6622117 | <reponame>Yanjing-PENG/index_prediction
# -*- encoding:utf-8 -*-
from getdata import getData
from signaltrade import signaltrade
from tradestats import tradestats
from plot import plot_net_value
from configue import M, T
import pandas as pd
# set the display parameters for pandas DataFrame
pd.set_option('di... | # -*- encoding:utf-8 -*-
from getdata import getData
from signaltrade import signaltrade
from tradestats import tradestats
from plot import plot_net_value
from configue import M, T
import pandas as pd
# set the display parameters for pandas DataFrame
pd.set_option('display.max_columns', None)
pd.set_option... | en | 0.532896 | # -*- encoding:utf-8 -*- # set the display parameters for pandas DataFrame # set some basic parameters # do the backtest # get detailed backtest performance # save backtest performance into excel file # plot the net value figure # print out the backtest performance | 2.747642 | 3 |
honeycomb/utils/config_utils.py | omercnet/honeycomb | 81 | 6622118 | <reponame>omercnet/honeycomb
# -*- coding: utf-8 -*-
"""Honeycomb Config Utilities."""
from __future__ import unicode_literals, absolute_import
import os
import re
import json
import logging
import six
import yaml
from honeycomb import defs, exceptions
from honeycomb.error_messages import CONFIG_FIELD_TYPE_ERROR
... | # -*- coding: utf-8 -*-
"""Honeycomb Config Utilities."""
from __future__ import unicode_literals, absolute_import
import os
import re
import json
import logging
import six
import yaml
from honeycomb import defs, exceptions
from honeycomb.error_messages import CONFIG_FIELD_TYPE_ERROR
logger = logging.getLogger(__... | en | 0.844932 | # -*- coding: utf-8 -*- Honeycomb Config Utilities. Validate a config field against a type. Similar functionality to :func:`validate_field_matches_type` but returns :obj:`honeycomb.defs.ConfigField` Validate a JSON file configuration against list of :obj:`honeycomb.defs.ConfigField`. Return the parameters section ... | 2.443598 | 2 |
amocrm_api_client/make_json_request/core/MakeJsonRequestException.py | iqtek/amocrm_api_client | 0 | 6622119 | from typing import Mapping
from typing import Optional
from amocrm_api_client.exceptions import AmocrmClientException
__all__ = [
"MakeJsonRequestException",
]
class MakeJsonRequestException(AmocrmClientException):
__slots__ = (
"status_code",
"headers",
"content",
)
def _... | from typing import Mapping
from typing import Optional
from amocrm_api_client.exceptions import AmocrmClientException
__all__ = [
"MakeJsonRequestException",
]
class MakeJsonRequestException(AmocrmClientException):
__slots__ = (
"status_code",
"headers",
"content",
)
def _... | none | 1 | 2.513432 | 3 | |
python3/koans/a_package_folder/__init__.py | digiaonline/python_koans | 1 | 6622120 | <filename>python3/koans/a_package_folder/__init__.py
#!/usr/bin/env python
an_attribute = 1984 | <filename>python3/koans/a_package_folder/__init__.py
#!/usr/bin/env python
an_attribute = 1984 | ru | 0.26433 | #!/usr/bin/env python | 1.143534 | 1 |
multitest_transport/cli/cluster.py | maksonlee/multitest_transport | 0 | 6622121 | <reponame>maksonlee/multitest_transport
# Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by ... | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | en | 0.732138 | # Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ... | 2.188802 | 2 |
test/unittests/test.py | dutille/doconce | 305 | 6622122 | import itertools
from invoke import format_html
import os
def read_options(subdir):
default = ()
infile = os.path.join(subdir, 'OPTIONS')
if not os.path.isfile(infile):
return default
with open(infile, 'r') as f:
OPTIONS = tuple(l.strip() for l in f.readlines())
return OPTIONS
... | import itertools
from invoke import format_html
import os
def read_options(subdir):
default = ()
infile = os.path.join(subdir, 'OPTIONS')
if not os.path.isfile(infile):
return default
with open(infile, 'r') as f:
OPTIONS = tuple(l.strip() for l in f.readlines())
return OPTIONS
... | none | 1 | 2.290767 | 2 | |
week 1/2/2c.py | Monxun/SmoothStack | 0 | 6622123 | <gh_stars>0
#############################
# Three's a crowd: pt. 1 / pt. 2
people = ['Matt', 'Mark', 'Luke', 'Ringo']
def test_crowd(people):
if len(people) > 3:
print("This room's crowded!")
else:
print("Room's all good.")
test_crowd(people)
people.pop()
test_crowd(people)
##############... | #############################
# Three's a crowd: pt. 1 / pt. 2
people = ['Matt', 'Mark', 'Luke', 'Ringo']
def test_crowd(people):
if len(people) > 3:
print("This room's crowded!")
else:
print("Room's all good.")
test_crowd(people)
people.pop()
test_crowd(people)
##########################... | de | 0.531589 | ############################# # Three's a crowd: pt. 1 / pt. 2 ############################# # Six is a Mob | 3.969133 | 4 |
tests/unit/test_unicode.py | simon-engledew/sshim | 16 | 6622124 | # -*- coding: utf8 -*-
import unittest
import sshim
import re
import codecs
import six
from . import connect
class TestUnicode(unittest.TestCase):
def test_unicode_echo(self):
def decode(value):
if isinstance(value, six.text_type):
return value
return codecs.decode(value, ... | # -*- coding: utf8 -*-
import unittest
import sshim
import re
import codecs
import six
from . import connect
class TestUnicode(unittest.TestCase):
def test_unicode_echo(self):
def decode(value):
if isinstance(value, six.text_type):
return value
return codecs.decode(value, ... | en | 0.406466 | # -*- coding: utf8 -*- | 3.019623 | 3 |
utils/sort.py | mymsimple/plate_generator | 10 | 6622125 | # encoding='utf-8'
import os
'''
按字符数量做排序,如下:
['京 7577'] 冀 20417
['津 3843'] =====> 京 7577
['冀 20417'] 津 3843
'''
def char_sort(old_txt):
with open(old_txt, "r", encoding="utf-8") as f:
char_list = []
c_list = []
for line in f.readlines():
... | # encoding='utf-8'
import os
'''
按字符数量做排序,如下:
['京 7577'] 冀 20417
['津 3843'] =====> 京 7577
['冀 20417'] 津 3843
'''
def char_sort(old_txt):
with open(old_txt, "r", encoding="utf-8") as f:
char_list = []
c_list = []
for line in f.readlines():
... | zh | 0.337309 | # encoding='utf-8' 按字符数量做排序,如下: ['京 7577'] 冀 20417 ['津 3843'] =====> 京 7577 ['冀 20417'] 津 3843 | 3.344179 | 3 |
plata_charts/apps.py | eonpatapon/plata-charts | 0 | 6622126 | <gh_stars>0
from django.apps import AppConfig
class Config(AppConfig):
name = 'plata_charts'
verbose_name = 'Charts'
| from django.apps import AppConfig
class Config(AppConfig):
name = 'plata_charts'
verbose_name = 'Charts' | none | 1 | 1.101264 | 1 | |
kirberichuk/urls.py | kirberich/kirberich.uk | 0 | 6622127 | from django.conf.urls import patterns, include, url
import session_csrf
session_csrf.monkeypatch()
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^_ah/', include('djangae.urls')),
url(r'^admin/?', include(admin.site.urls)),
url(r'^summernote/', include('django_summ... | from django.conf.urls import patterns, include, url
import session_csrf
session_csrf.monkeypatch()
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^_ah/', include('djangae.urls')),
url(r'^admin/?', include(admin.site.urls)),
url(r'^summernote/', include('django_summ... | none | 1 | 1.827613 | 2 | |
src/configs/config.py | Callet91/sw | 0 | 6622128 | <reponame>Callet91/sw
'''Config file for example model'''
example_config = {
'activation': 'relu',
'batch': 32,
'epochs': 5,
'loss': 'sparse_categorical_crossentropy',
'metrics': 'accuracy',
'optimizer': 'adam'
} | '''Config file for example model'''
example_config = {
'activation': 'relu',
'batch': 32,
'epochs': 5,
'loss': 'sparse_categorical_crossentropy',
'metrics': 'accuracy',
'optimizer': 'adam'
} | en | 0.69694 | Config file for example model | 1.612994 | 2 |
board.py | naderabdalghani/othello | 0 | 6622129 | <reponame>naderabdalghani/othello
from tkinter import *
import numpy as np
import PIL.Image
import PIL.ImageTk
import math
from othello import Othello
from agent import Agent
from constants import WHITE, BLACK, VALID_MOVE, WHITE_IMG, BLACK_IMG, NEXT_MOVE_IMG, BLACK_TURN_TEXT, WHITE_TURN_TEXT, \
BLACK_WON_TEXT, WHIT... | from tkinter import *
import numpy as np
import PIL.Image
import PIL.ImageTk
import math
from othello import Othello
from agent import Agent
from constants import WHITE, BLACK, VALID_MOVE, WHITE_IMG, BLACK_IMG, NEXT_MOVE_IMG, BLACK_TURN_TEXT, WHITE_TURN_TEXT, \
BLACK_WON_TEXT, WHITE_WON_TEXT, DRAW_TEXT, BLACK_LOADI... | en | 0.936307 | # Initialize agents # Initialize game object # Pass turn to black as black always starts first # Initialize board parameters # Initialize images # Initialize widgets (board, scoreboard) # Render widgets # If a player doesn't have a move, pass the play to the other player # If a player doesn't have a move, pass the play... | 2.932645 | 3 |
plainenglish.py | anthonycurtisadler/ARCADES | 7 | 6622130 | ### contains queries, labels, alerts for plain English language, as well as the commands.
### and various input terms.
### NOTE that the names of the commands cannot be changed since
from globalconstants import DASH, PLUS, CARET,\
VERTLINE, EOL, DOLLAR, POUND, SEMICOLON, QUESTIONMARK
import commandscript
... | ### contains queries, labels, alerts for plain English language, as well as the commands.
### and various input terms.
### NOTE that the names of the commands cannot be changed since
from globalconstants import DASH, PLUS, CARET,\
VERTLINE, EOL, DOLLAR, POUND, SEMICOLON, QUESTIONMARK
import commandscript
... | en | 0.887995 | ### contains queries, labels, alerts for plain English language, as well as the commands. ### and various input terms. ### NOTE that the names of the commands cannot be changed since Name or index of notebook,
(N)ew to open a new notebook,
or quit(... | 2.737755 | 3 |
py_midiplus_fit/Fader.py | soccermitchy/py_midiplus_waves | 0 | 6622131 |
class Fader:
controller = None
channel: int = None
select_btn_id: int = None
solo_btn_id: int = None
mute_btn_id: int = None
fader_touch_id: int = None
fader_id: int = None
def __init__(self, controller, channel: int):
self.controller = controller
self.channel = channel... |
class Fader:
controller = None
channel: int = None
select_btn_id: int = None
solo_btn_id: int = None
mute_btn_id: int = None
fader_touch_id: int = None
fader_id: int = None
def __init__(self, controller, channel: int):
self.controller = controller
self.channel = channel... | en | 0.738553 | # Init IDs for everything # Whee, special cases! | 2.350243 | 2 |
retrieve_any_layer.py | tyler-hayes/Deep_SLDA | 32 | 6622132 | import torch.nn as nn
def get_name_to_module(model):
name_to_module = {}
for m in model.named_modules():
name_to_module[m[0]] = m[1]
return name_to_module
def get_activation(all_outputs, name):
def hook(model, input, output):
all_outputs[name] = output.detach()
return hook
def... | import torch.nn as nn
def get_name_to_module(model):
name_to_module = {}
for m in model.named_modules():
name_to_module[m[0]] = m[1]
return name_to_module
def get_activation(all_outputs, name):
def hook(model, input, output):
all_outputs[name] = output.detach()
return hook
def... | en | 0.547805 | :param model: :param outputs: Outputs from layers specified in `output_layer_names` will be stored in `output` variable :param output_layer_names: :return: | 2.754383 | 3 |
code/ch_09_tuples/_01_unpack_and_move_in.py | NogNoa/write-pythonic-code-demos | 679 | 6622133 | <reponame>NogNoa/write-pythonic-code-demos
# tuples are defined as:
t = (7, 11, "cat", [1, 1, 3, 5, 8])
print(t)
t = 7, 11, "cat", [1, 1, 3, 5, 8]
# print(t)
# t = 7,
# print(t, len(t))
# create a tuple, grab a value.
print(t[2])
# we can assign individual variables:
t = 7, "cat", 11
# n = [0]
# a = [1]
# show them
... | # tuples are defined as:
t = (7, 11, "cat", [1, 1, 3, 5, 8])
print(t)
t = 7, 11, "cat", [1, 1, 3, 5, 8]
# print(t)
# t = 7,
# print(t, len(t))
# create a tuple, grab a value.
print(t[2])
# we can assign individual variables:
t = 7, "cat", 11
# n = [0]
# a = [1]
# show them
n, a, _ = t
print("n={}, a={}".format(n, a)... | en | 0.876494 | # tuples are defined as: # print(t) # t = 7, # print(t, len(t)) # create a tuple, grab a value. # we can assign individual variables: # n = [0] # a = [1] # show them # can also assign on a single line: # You'll find this often in loops (remember numerical for-in loops): | 4.4553 | 4 |
medium/problem738/Solution.py | cutoutsy/leetcode | 1 | 6622134 | <gh_stars>1-10
class Solution:
def monotoneIncreasingDigits(self, N):
"""
:type N: int
:rtype: int
"""
if N < 10: return N
n, inv_index = N, -1
num = [int(d) for d in str(n)[::-1]]
for i in range(1, len(num)):
if num[i] > num[i - 1... | class Solution:
def monotoneIncreasingDigits(self, N):
"""
:type N: int
:rtype: int
"""
if N < 10: return N
n, inv_index = N, -1
num = [int(d) for d in str(n)[::-1]]
for i in range(1, len(num)):
if num[i] > num[i - 1] or (inv_index... | en | 0.43098 | :type N: int :rtype: int | 2.967426 | 3 |
edabit/hard/recursive_length_of_string/recursive_length_of_string.py | ticotheps/practice_problems | 0 | 6622135 | <gh_stars>0
"""
RECURSION: LENGTH OF A STRING
Instructions:
- Write a function that returns the length of a string. Make your function
recursive.
Examples:
- length('apple') -> 5
- length('make') -> 4
- length('a') -> 1
- length('') -> 0
"""
"""
----- 4 Phases of The U.P.E.R. Problem-Solving Fram... | """
RECURSION: LENGTH OF A STRING
Instructions:
- Write a function that returns the length of a string. Make your function
recursive.
Examples:
- length('apple') -> 5
- length('make') -> 4
- length('a') -> 1
- length('') -> 0
"""
"""
----- 4 Phases of The U.P.E.R. Problem-Solving Framework -----
... | en | 0.659925 | RECURSION: LENGTH OF A STRING Instructions: - Write a function that returns the length of a string. Make your function recursive. Examples: - length('apple') -> 5 - length('make') -> 4 - length('a') -> 1 - length('') -> 0 ----- 4 Phases of The U.P.E.R. Problem-Solving Framework ----- PHASE I: UND... | 4.133552 | 4 |
programs/programs8112021/menudrivenprog.py | VishalAgr11/CSE-programs | 1 | 6622136 | '''
WAP to menu driven program to find the add, sub,mul,div with 2 inputs
'''
choice=0
while choice!=5:
choice=int(input("\n\n1. for add \n2. for sub\n3. for mul\n4. for div\n5. to exit\n"))
l=input("Enter 2 numbers: ").split()
if choice==5:
break
a,b=l
if choice==1:
print("Addition:... | '''
WAP to menu driven program to find the add, sub,mul,div with 2 inputs
'''
choice=0
while choice!=5:
choice=int(input("\n\n1. for add \n2. for sub\n3. for mul\n4. for div\n5. to exit\n"))
l=input("Enter 2 numbers: ").split()
if choice==5:
break
a,b=l
if choice==1:
print("Addition:... | en | 0.731572 | WAP to menu driven program to find the add, sub,mul,div with 2 inputs | 3.700828 | 4 |
tests/test_mca.py | kormilitzin/Prince | 10 | 6622137 | <gh_stars>1-10
import numpy as np
import pandas as pd
import pytest
from prince import MCA
from tests import util as test_util
@pytest.fixture
def df():
"""The original dataframe."""
return pd.read_csv('tests/data/ogm.csv', index_col=0)
@pytest.fixture
def indicator_matrix(df):
"""The indicator matrix ... | import numpy as np
import pandas as pd
import pytest
from prince import MCA
from tests import util as test_util
@pytest.fixture
def df():
"""The original dataframe."""
return pd.read_csv('tests/data/ogm.csv', index_col=0)
@pytest.fixture
def indicator_matrix(df):
"""The indicator matrix of the original... | en | 0.830109 | The original dataframe. The indicator matrix of the original dataframe. The number of rows. The number of columns in the indicator matrix. The number of columns in the initial dataframe. The number of principal components to compute. The total number of observed value. The executed CA. Check the dimensions are correct.... | 2.755355 | 3 |
array/maxProfit2.py | saai/LeetcodePythonSolutions | 0 | 6622138 | <filename>array/maxProfit2.py<gh_stars>0
class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
profits = 0
min_v = -1
max_v = -1
n = len(prices)
for i in range(n):
p = prices[i]
... | <filename>array/maxProfit2.py<gh_stars>0
class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
profits = 0
min_v = -1
max_v = -1
n = len(prices)
for i in range(n):
p = prices[i]
... | en | 0.606497 | :type prices: List[int] :rtype: int # get every profits you can get. :type prices: List[int] :rtype: int | 3.29592 | 3 |
src/setup.py | Aniana0/dvcfg_pytools | 0 | 6622139 | <reponame>Aniana0/dvcfg_pytools
from setuptools import setup
setup(
name='dvcfg_pytools',
version='1.1.0',
description='Python module for editing .dvcfg in Python.',
author='Aniana0',
author_email='<EMAIL>',
url='https://github.com/Aniana0/dvcfg_pytools',
py_modules=['dvcfg_pytools'])
| from setuptools import setup
setup(
name='dvcfg_pytools',
version='1.1.0',
description='Python module for editing .dvcfg in Python.',
author='Aniana0',
author_email='<EMAIL>',
url='https://github.com/Aniana0/dvcfg_pytools',
py_modules=['dvcfg_pytools']) | none | 1 | 1.071367 | 1 | |
main.py | psiang/OSMcrop | 0 | 6622140 | import capture
import getmap
import cutmap
if __name__ == '__main__':
# 59.9055,24.7385,60.3133,25.2727 赫尔基辛
# 60.1607,24.9191,60.1739,24.9700
# 60.16446,24.93824,60.16776,24.95096
# 60.1162,24.7522,60.3041,25.2466
name = "Helsinki"
tif_file = "google_17m.tif"
tfw_file = "google_17m.tfw"
... | import capture
import getmap
import cutmap
if __name__ == '__main__':
# 59.9055,24.7385,60.3133,25.2727 赫尔基辛
# 60.1607,24.9191,60.1739,24.9700
# 60.16446,24.93824,60.16776,24.95096
# 60.1162,24.7522,60.3041,25.2466
name = "Helsinki"
tif_file = "google_17m.tif"
tfw_file = "google_17m.tfw"
... | en | 0.605635 | # 59.9055,24.7385,60.3133,25.2727 赫尔基辛 # 60.1607,24.9191,60.1739,24.9700 # 60.16446,24.93824,60.16776,24.95096 # 60.1162,24.7522,60.3041,25.2466 # lat1, lon1, lat2, lon2 = 60.1162,24.7522,60.3041,25.2466 # # get tif # x = getmap.getpic(lat1, lon1, lat2, lon2, # 17, source='google', style='s', outfile=tif_fil... | 2.509427 | 3 |
Week3_code-drills/week-03/day-01/06/challenge-prompt.py | ruturajshete1008/code-drills | 1 | 6622141 | <reponame>ruturajshete1008/code-drills<filename>Week3_code-drills/week-03/day-01/06/challenge-prompt.py
# create a list, list_1, with 0, 1 ,2 ,3 as values
# create list, list_2 with 4,5,6,7 as values
# create list, list_3 with 8,9,10,11 as values
# create list, list_4 with 12,13,14,15 as values
# pri... | # create a list, list_1, with 0, 1 ,2 ,3 as values
# create list, list_2 with 4,5,6,7 as values
# create list, list_3 with 8,9,10,11 as values
# create list, list_4 with 12,13,14,15 as values
# print the first list_1
# print each index of the list_1
# print the second list_2
# prin... | en | 0.651502 | # create a list, list_1, with 0, 1 ,2 ,3 as values # create list, list_2 with 4,5,6,7 as values # create list, list_3 with 8,9,10,11 as values # create list, list_4 with 12,13,14,15 as values # print the first list_1 # print each index of the list_1 # print the second list_2 # print each index of the second list_2 # p... | 3.770475 | 4 |
techreviewproj/techreviewapp/apps.py | yonny23/techreviewproject | 0 | 6622142 | from django.apps import AppConfig
class TechreviewappConfig(AppConfig):
name = 'techreviewapp'
| from django.apps import AppConfig
class TechreviewappConfig(AppConfig):
name = 'techreviewapp'
| none | 1 | 1.040944 | 1 | |
facebook_login.py | grassym/p366 | 0 | 6622143 | <reponame>grassym/p366
#!/usr/bin/python
# -*- coding: utf-8 -*-
import facebook
import requests
file = open("/home/olia/Documents/fuck_the_code/facebook_credentials.txt")
app_id = file.readline()
app_secret = file.readline()
graph_api_token = file.readline()
# print ("app_id = " + str(app_id))
# print ("app_secre... | #!/usr/bin/python
# -*- coding: utf-8 -*-
import facebook
import requests
file = open("/home/olia/Documents/fuck_the_code/facebook_credentials.txt")
app_id = file.readline()
app_secret = file.readline()
graph_api_token = file.readline()
# print ("app_id = " + str(app_id))
# print ("app_secret = " + str(app_secret)... | en | 0.400096 | #!/usr/bin/python # -*- coding: utf-8 -*- # print ("app_id = " + str(app_id)) # print ("app_secret = " + str(app_secret)) # def get_fb_token(app_id, app_secret): # payload = {'grant_type': 'client_credentials', 'client_id': app_id, 'client_secret': app_secret} # file = requests.post('https://graph.facebook.com/... | 3.21508 | 3 |
tests/window_flags.py | stonewell/eim | 0 | 6622144 | from PySide6.QtCore import Slot, Qt, QRect, QSize
from PySide6.QtGui import QColor, QPainter, QTextFormat
from PySide6.QtWidgets import QPlainTextEdit, QWidget, QTextEdit, QPushButton, QVBoxLayout, QHBoxLayout, QGroupBox, QGridLayout, QCheckBox, QRadioButton, QApplication
class PreviewWindow(QWidget):
def __init_... | from PySide6.QtCore import Slot, Qt, QRect, QSize
from PySide6.QtGui import QColor, QPainter, QTextFormat
from PySide6.QtWidgets import QPlainTextEdit, QWidget, QTextEdit, QPushButton, QVBoxLayout, QHBoxLayout, QGroupBox, QGridLayout, QCheckBox, QRadioButton, QApplication
class PreviewWindow(QWidget):
def __init_... | none | 1 | 2.124129 | 2 | |
upvote/gae/datastore/models/exemption_test.py | iwikmai/upvote | 453 | 6622145 | <gh_stars>100-1000
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by ... | # Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | en | 0.849424 | # Copyright 2017 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a... | 1.9862 | 2 |
mpisppy/extensions/avgminmaxer.py | Matthew-Signorotti/mpi-sppy | 2 | 6622146 | <reponame>Matthew-Signorotti/mpi-sppy
# Copyright 2020 by <NAME>, <NAME>, <NAME>, <NAME>, and <NAME>
# This software is distributed under the 3-clause BSD License.
# An extension to compute and output avg, min, max for
# a component (e.g., first stage cost).
# DLW, Feb 2019
# This extension uses options["avgminmax_name... | # Copyright 2020 by <NAME>, <NAME>, <NAME>, <NAME>, and <NAME>
# This software is distributed under the 3-clause BSD License.
# An extension to compute and output avg, min, max for
# a component (e.g., first stage cost).
# DLW, Feb 2019
# This extension uses options["avgminmax_name"]
import mpisppy.extensions.xhatbase... | en | 0.687813 | # Copyright 2020 by <NAME>, <NAME>, <NAME>, <NAME>, and <NAME> # This software is distributed under the 3-clause BSD License. # An extension to compute and output avg, min, max for # a component (e.g., first stage cost). # DLW, Feb 2019 # This extension uses options["avgminmax_name"] Args: ph (PH object): the c... | 2.101052 | 2 |
src/commands/start.py | rsoorajs/TorrentSeedr | 0 | 6622147 | import json
import asyncio
import requests, json
from src.objs import *
from src.commands.addTorrent import addTorrent
from src.functions.keyboard import mainReplyKeyboard, githubAuthKeyboard
# Start handler
@bot.message_handler(commands=['start'])
def start(message):
userId = message.from_user.id
params = me... | import json
import asyncio
import requests, json
from src.objs import *
from src.commands.addTorrent import addTorrent
from src.functions.keyboard import mainReplyKeyboard, githubAuthKeyboard
# Start handler
@bot.message_handler(commands=['start'])
def start(message):
userId = message.from_user.id
params = me... | en | 0.473293 | # Start handler #! If start paramater is passed #! If add torrent paramater is passed via database key #! If add torrent paramater is passed via URL #! Github oauth #! Successfully authenticated #! User is following #! User is not following #! Error #: Account login #! If account logged in successfully #! Captcha faile... | 2.532515 | 3 |
src/route_viewer/show_args.py | masaharu-kato-lab/firefly_algorithm | 2 | 6622148 | #!env/bin/python
import pickle
import argparse
import json
import sys
import os
sys.path.append(os.path.dirname(__file__) + '/../route_planner')
def main():
argp = argparse.ArgumentParser(description='Route binary arguments checker')
argp.add_argument('input', type=str, help='Input binary pickle file path')
... | #!env/bin/python
import pickle
import argparse
import json
import sys
import os
sys.path.append(os.path.dirname(__file__) + '/../route_planner')
def main():
argp = argparse.ArgumentParser(description='Route binary arguments checker')
argp.add_argument('input', type=str, help='Input binary pickle file path')
... | ru | 0.18615 | #!env/bin/python | 2.904024 | 3 |
visionRecog.py | kureuetan/img_recog_for_non_eng_speakers | 0 | 6622149 | <reponame>kureuetan/img_recog_for_non_eng_speakers
#!/usr/bin/env python3
# Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/L... | #!/usr/bin/env python3
# Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | en | 0.864442 | #!/usr/bin/env python3 # Copyright 2017 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or... | 2.247475 | 2 |
mushroom_rl/utils/callbacks/callback.py | PuzeLiu/mushroom-rl | 344 | 6622150 | <reponame>PuzeLiu/mushroom-rl
class Callback(object):
"""
Interface for all basic callbacks. Implements a list in which it is possible
to store data and methods to query and clean the content stored by the
callback.
"""
def __init__(self):
"""
Constructor.
"""
s... | class Callback(object):
"""
Interface for all basic callbacks. Implements a list in which it is possible
to store data and methods to query and clean the content stored by the
callback.
"""
def __init__(self):
"""
Constructor.
"""
self._data_list = list()
d... | en | 0.884976 | Interface for all basic callbacks. Implements a list in which it is possible to store data and methods to query and clean the content stored by the callback. Constructor. Add samples to the samples list. Args: dataset (list): the samples to collect. Returns: The current collect... | 3.802602 | 4 |