blob_id stringlengths 40 40 | language stringclasses 1
value | repo_name stringlengths 5 133 | path stringlengths 2 333 | src_encoding stringclasses 30
values | length_bytes int64 18 5.47M | score float64 2.52 5.81 | int_score int64 3 5 | detected_licenses listlengths 0 67 | license_type stringclasses 2
values | text stringlengths 12 5.47M | download_success bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|
afc8470c3b1ae6199f7b2328ed048d5006e3ca45 | Python | Rmartin20/Regim-project | /RegimUI/Regim/DVisual.py | UTF-8 | 9,661 | 2.515625 | 3 | [] | no_license | # -*- coding: utf-8 -*-
from Regim import ZoomAdvanced
try:
from Tkinter import *
except ImportError:
from tkinter import *
class DVisual:
def __init__(self, top=None, fixed_img=None, mov_img=None, reg_img=None, bw_img=None):
"""Visualization GUI"""
from PIL import Image, ImageTk
... | true |
8b4f34593489281cdcf22ec7fa6f9839fd3e80ac | Python | AI-DI/Brancher | /development_playgrounds/GP_playground.py | UTF-8 | 1,629 | 2.75 | 3 | [
"MIT"
] | permissive | import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from brancher.variables import ProbabilisticModel
from brancher.stochastic_processes import GaussianProcess as GP
from brancher.stochastic_processes import SquaredExponentialCovariance as SquaredExponential
from brancher.stochastic_processes impor... | true |
c2b2a433d39e9dadf25e78e8f54dfc586563535d | Python | Ankur3107/scalingQA | /scalingqa/extractivereader/training/scheduler_factory.py | UTF-8 | 2,008 | 3.15625 | 3 | [
"MIT"
] | permissive | # -*- coding: UTF-8 -*-
""""
Created on 16.07.20
This module contains factory for creating schedulers.
:author: Martin Dočekal
"""
from abc import ABC, abstractmethod
from typing import Callable, Dict
import torch
from torch.optim.lr_scheduler import _LRScheduler # TODO: protected member access, seems dirty :(... | true |
c2d7cfe4d854cc6fa98de62ea2891488fba90853 | Python | 12rambau/sepal_ui | /sepal_ui/mapping/marker_cluster.py | UTF-8 | 622 | 2.59375 | 3 | [
"MIT"
] | permissive | """Custom implementation of the marker cluster to hide it at once."""
from ipyleaflet import MarkerCluster
from traitlets import Bool, observe
class MarkerCluster(MarkerCluster):
"""Overwrite the MarkerCluster to hide all the underlying cluster at once.
.. todo::
remove when https://github.com/jupyt... | true |
3b91b591c4b2f7faad0f8201f50060608866c373 | Python | nOctaveLay/TM_information | /python-docs.py | UTF-8 | 542 | 2.65625 | 3 | [] | no_license | # 반드시 python-docs를 설치할것.
from docx import Document
from docx.shared import Inches
document = Document()
with open('law.txt','r',encoding='utf-8') as f:
file_list = list()
for line in f:
if line != '\n':
file_list.append(line[:-1])
table = document.add_table(rows = len(file_list), cols ... | true |
99ced1b3a9b9c7a493dd331be0bb7e2627c4ce4e | Python | courageousillumination/django-flags | /flags/flag_overrider.py | UTF-8 | 699 | 2.921875 | 3 | [] | no_license | """The base FlagOverrider class."""
from typing import Any
from flags.flag import Flag
class FlagOverrider(object): # pragma: no cover
"""
A flag overrider is an object that can overide flag values.
These get various bits of context (request, user, etc.) and use these to determine
if the flag value... | true |
72c36d98ce3eff4a83c1885dbceb599c7e0ce92c | Python | mrliuzhao/OpenCVNotebook-Python | /CarDetection/detector.py | UTF-8 | 5,876 | 2.671875 | 3 | [] | no_license | import cv2
import numpy as np
import time
'''
该文件用于使用UIUC数据集训练出识别汽车的BOW+SVM模型
'''
datapath = r".\resources\CarData\TrainImages"
SAMPLES = 400
def path(cls, i):
return "%s/%s%d.pgm" % (datapath, cls, i)
def get_flann_matcher():
flann_params = dict(algorithm=1, trees=5)
return cv2.FlannBasedMatcher(flan... | true |
6c36e52d7f9d1781e7f2fabfff3efd4fe9c2a8fb | Python | David-Carrasco-Vidaurre/trabajo05.Carrasco.Castillo | /verificador03.py | UTF-8 | 409 | 3.515625 | 4 | [] | no_license | # calculadora nro3
# esta calculadora realiza el cálculo de la potencia
# declaración de variables
trabajo, tiempo, potencia = 0.0 , 0.0 , 0.0
# calculadora
trabajo = 18
tiempo = 9
potencia = (trabajo // tiempo)
verificador=(potencia>=2)
# motrar datos
print ( " trabajo = " , trabajo)
print ( " tiempo = ... | true |
a0d4463dc28ad6338f59282d3b7c7c47a37e34f4 | Python | cuttlefish/stactools | /src/stactools/core/io/__init__.py | UTF-8 | 1,300 | 2.828125 | 3 | [
"Apache-2.0"
] | permissive | from typing import Callable, Optional, Any
from pystac.stac_io import DefaultStacIO, StacIO
import fsspec
ReadHrefModifier = Callable[[str], str]
"""Type alias for a function parameter
that allows users to manipulate HREFs for reading,
e.g. appending an Azure SAS Token or translating
to a signed URL
"""
def read_te... | true |
b93f34daabfbf383deda18682dfa807ffb074a6c | Python | raster-foundry/raster-foundry-python-client | /tests/test_notebook_check.py | UTF-8 | 845 | 2.5625 | 3 | [
"Apache-2.0"
] | permissive | def test_warn_without_notebook_support():
import rasterfoundry.decorators
rasterfoundry.decorators.NOTEBOOK_SUPPORT = False
from rasterfoundry.decorators import check_notebook
@check_notebook
def f():
return 'foo'
assert f() is None
def test_warn_without_notebook_support_with_args():
... | true |
ca3a2460a7f07b378c3a2fe25d2ecd6b1d3428ad | Python | Aasthaengg/IBMdataset | /Python_codes/p03078/s543307944.py | UTF-8 | 1,148 | 3.046875 | 3 | [] | no_license | import heapq
x, y, z, k = map(int, input().split())
a = sorted(map(int, input().split()))[::-1]
b = sorted(map(int, input().split()))[::-1]
c = sorted(map(int, input().split()))[::-1]
print(a[0] + b[0] + c[0])
candidates = []
if x > 1: candidates.append((-(a[1] + b[0] + c[0]), 1, 0, 0))
if y > 1: candidates.append((-(... | true |
eca7d8f259370d8c4c4dbe4857b31d085519a85e | Python | duleignjatovic995/OpenParliamentAnalysis | /preprocess/preprocess_data.py | UTF-8 | 4,307 | 3.546875 | 4 | [] | no_license | """
This file contains methods for preprocessing text.
The intendet pipeline would be:
1. s = get_stemmed_list_of_documents(list_of_documents) # parsing one document at a time
2. d = create_dictionary(s)
3. m = create_document_term_matrix(d, s) # bag of words
"""
from preprocess.stemmers.Croatian_stemmer... | true |
93f8c828a683ab2d539cc0b77150d822f0421659 | Python | Aasthaengg/IBMdataset | /Python_codes/p02397/s336800437.py | UTF-8 | 173 | 3.21875 | 3 | [] | no_license | while True :
a = raw_input().split()
x = int(a[0])
y = int(a[1])
if x == 0 and y == 0 :
break
elif x < y :
print u"%d %d" % (x, y)
else :
print u"%d %d" % (y, x) | true |
fdb76e2af2bacafcc6185d3bd1b72c8b08d8b490 | Python | MichiganCOG/video-frame-inpainting | /videolist/master_to_contiguous.py | UTF-8 | 1,759 | 2.9375 | 3 | [] | no_license | import argparse
def range_to_str(a, b):
return '%d-%d' % (a, b)
def str_to_range(str):
return tuple(int(d) for d in str.split('-'))
def main(input_path, output_path, clip_length, default_stride, first_only):
input_reader = open(input_path, 'r')
output_writer = open(output_path, 'w')
for line i... | true |
1a1204e4face38bd241e7aa4fc45b2f43373d86a | Python | kaer-hero/python-learning | /001.py | UTF-8 | 1,002 | 3.953125 | 4 | [] | no_license | print('i love %s')
print('i love %s'%"lixiao")
print('i am %d years old'%18)
print('i am %d years old, i am %s'%(18,'minlei'))
s = 'i love {}'.format('lixiao')
print(s)
s = 'i am {1}, i love {0}, {1} hate the dog'.format('lixiao','wangjun')
print(s)
# format 格式限定符 有着丰富的格式限定符,语法是{}中带:号
# 填充与对齐 填充经常跟对齐一起使用 ^ < > 分别是居中、左对... | true |
db0a6635bfe78c2dd716577409eade599458dad5 | Python | zuxinlin/leetcode | /leetcode/709.ToLowerCase.py | UTF-8 | 692 | 3.890625 | 4 | [] | no_license | #! /usr/bin/env python
# coding: utf-8
'''
题目: 转换成小写字母 https://leetcode-cn.com/problems/to-lower-case/
主题: string
解题思路:
1. 调用字符串库函数lower
'''
class Solution(object):
'''
'''
def toLowerCase(self, str):
"""
:type str: str
:rtype: str
"""
# return str.lower()
... | true |
f87dc1d166b750049e50a27de9a24a285628522f | Python | chuckbenger/Asteroids-Multiplayer-Backend | /services/common/adapters/sqs_game_queue.py | UTF-8 | 1,991 | 2.875 | 3 | [
"Apache-2.0"
] | permissive | import boto3
from typing import List
from common.domain.player import Player
from common.domain.game_queue_interface import GameQueueInterface
class SQSGameQueueAdapter(GameQueueInterface):
def __init__(self, queue_name: str):
self.queue_name = queue_name
self.sqs = boto3.resource('sqs')
s... | true |
0553f121a3d7a1ec316d447765cfc947c935e1df | Python | javokhirbek1999/CodeSignal | /Arcade/Intro/Island-Of-Knowledge/avoidObstacles.py | UTF-8 | 311 | 2.828125 | 3 | [] | no_license | def avoidObstacles(inputArray):
i = 1
while True:
j = i
while True:
if j in inputArray:
break
elif j>max(inputArray):
return i
else:
j+=i
i+=1
if max(inputArray)<i:
return i
| true |
c79805236b267261e887e514b86020c7363332bc | Python | cbg-ethz/openproblems2021 | /task01_predictmodality/method/scmm/vaes/vis.py | UTF-8 | 3,251 | 2.65625 | 3 | [
"MIT"
] | permissive | # visualisation related functions
import matplotlib.colors as colors
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
import torch
from matplotlib.lines import Line2D
from umap import UMAP
def custom_cmap(n):
"""Create customised colormap for scattered latent plot of n... | true |
e81f13575137b694c8fa91af5fb1b5be46cb02fd | Python | fujikosu/Keras-BatchAI | /keras.py | UTF-8 | 2,010 | 2.703125 | 3 | [] | no_license | from keras.applications.inception_v3 import InceptionV3
from keras.preprocessing import image
from keras.models import Model
from keras.layers import Dense, GlobalAveragePooling2D
from keras import backend as K
# create the base pre-trained model
base_model = InceptionV3(weights='imagenet', include_top=False)
# add a... | true |
848ad20e958c658d325337ad3a248caa491eda00 | Python | imwujue/python-practice-wujue | /Q76.py | UTF-8 | 248 | 3.375 | 3 | [] | no_license | def solve(n):
sum = 0.0
while True:
sum += 1/n
# print(1/n)
# print(sum)
if n == 1 or n == 2:
break
else:
n -= 2
return sum
n = int(input("n:"))
print('sum:%lf' %solve(n)) | true |
d75a3b09b0937ebc6c6d0fd1fd0062cd191b32a2 | Python | taka1156/AtCoder | /ABC/ABC_B_Product_Max.py | UTF-8 | 367 | 3.03125 | 3 | [] | no_license | import test_case
_CASE = """\
-1000000000 0 -1000000000 0
"""
test_case.test_input(_CASE)
###########
# code
##########
a, b, c, d = map(int, input().split())
print(max(max(a * c, a * d), max(b * c, b * d)))
# 最大になるパターンは
# 範囲がプラス側のみの場合、`-x * -y, x * y`
# 範囲がマイナス側のみの場合は` -x * x, x * -y`
| true |
7e1fe19f693b96284196cf99ee2dcfc5f267704c | Python | Alex10ua/Detected | /venv/imagedetect.py | UTF-8 | 1,289 | 2.609375 | 3 | [] | no_license | from imageai.Detection import ObjectDetection
import os
exac_path=os.getcwd()#вказує шлях до цього проекту щоб програма знаходила додаткові файли
detector=ObjectDetection()
detector.setModelTypeAsRetinaNet()# встановлюємо те що використовуємо рітіна модель для визначення об єктів
detector.setModelPath(os.path.join(... | true |
79dd3317aee307acf7f91d1668f78a63a7e357b6 | Python | harkevich/testgithub | /Lesson/Lesson30 Модули в Python.py | UTF-8 | 537 | 2.828125 | 3 | [] | no_license | # import os
# # import random as r
# # import random
# from random import randint, shuffle # доступны только два метода randint и shuffle
# from random import * # доступ все модули из random
#
#
# print(os.getcwd())
# # print(random.randint(1 , 100))
# print(randint(1, 100))
# l = [1, 2, 3, 4, 5]
# shuffle(l)
# ... | true |
22744458c6086948040d719df8f4930f0120a06f | Python | DataDeveloper7865/my-flask-app | /app.py | UTF-8 | 633 | 3.078125 | 3 | [] | no_license | from flask import Flask
app = Flask(__name__)
@app.route('/')
def index():
""" Show homepage"""
return """
<html>
<body>
<h1> I am the landing page </h1>
</body>
</html>
"""
@app.route('/hello')
def say_hello():
"""Return simple "Hello" Gre... | true |
0d5704bdd1fd815a263d74f8e526fcc755c5a7cc | Python | rjm49/mltm | /static/classes.py | UTF-8 | 3,383 | 2.625 | 3 | [] | no_license | import numpy
from utils import generate_student_name
from keras import backend as K
from keras.constraints import Constraint
from keras.engine.topology import Layer
from keras import initializers, constraints
class WeightClip(Constraint):
'''Clips the weights incident to each hidden unit to be inside a range
... | true |
4a3e5628f565ff236a04997a7e1763987857bff7 | Python | escape2020/school2022 | /extra/participants.py | UTF-8 | 1,580 | 2.75 | 3 | [
"MIT"
] | permissive | import pandas as pd
from pandas.io.excel._xlrd import XlrdReader
from pandas.io.excel import ExcelFile
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('filename')
args = parser.parse_args()
filename = args.filename
class CustomXlrdReader(XlrdReader):
def load_workbook(self, filepath_or_bu... | true |
99e3ae633abf8ecddd9f8bf6606d503f323bc24c | Python | bgmacris/100daysOfCode | /Day76/game.py | UTF-8 | 2,911 | 2.921875 | 3 | [] | no_license | import random
import pygame
import os
import time
NEGRO = (0, 0, 0)
BLANCO = (255, 255, 255)
VERDE = (0, 255, 0)
AZUL = (0, 0, 255)
VIOLETA = (98, 0, 255)
pygame.init()
dimensiones = [300, 300]
root = pygame.display.set_mode(dimensiones)
pygame.display.set_caption('Piedra, Papel, Tijeras')
quit = False
clock = pyg... | true |
e6e18a73f6355f186bd7be3ac53d0376cf950f4f | Python | mrparkonline/python3-euler | /q12.py | UTF-8 | 1,647 | 4.5 | 4 | [
"MIT"
] | permissive | # The sequence of triangle numbers is generated by adding the natural numbers.
# So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28.
# The first ten terms would be:
# 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...
# Let us list the factors of the first seven triangle numbers:
"""
1: 1
3: 1,3
6: 1,2,3,6
10... | true |
81eab7d38b540a8fdf14870451c1a80571372a2c | Python | zhanglong362/zane | /weektest/test2/ATM_chengjunhua/core/src.py | UTF-8 | 5,946 | 2.71875 | 3 | [] | no_license | from interface import user
from lib import common
from interface import bank
import time
logger1=common.get_logger('ATM')
users={'name':None,
'status':False}
# print('注册')
def register():
if users['status']:
print('您已登陆!')
return
while True:
name=input(... | true |
4ad3fbe3437bd9afc74064097e3eb7a2eb792a0c | Python | YorkShen/LeetCode | /python/week2/241.py | UTF-8 | 1,385 | 3.34375 | 3 | [] | no_license | import operator
class Solution(object):
func_map = {
'+': operator.add,
'-': operator.sub,
'*': operator.mul,
}
def __init__(self):
self.cache = {}
def diffWaysToCompute(self, input):
"""
:type input: str
:rtype: List[int]
"""
r... | true |
dafb8260258ef4561ef2918d29dbdd2780efcca1 | Python | hardr0m/geek-python | /geek-python/Khrapov_Roman_lesson4/task6.py | UTF-8 | 2,135 | 4.25 | 4 | [] | no_license | # Реализовать два небольших скрипта:
# а) итератор, генерирующий целые числа, начиная с указанного,
# б) итератор, повторяющий элементы некоторого списка, определенного заранее.
#
# Подсказка: использовать функцию count() и cycle() модуля itertools.
# Обратите внимание, что создаваемый цикл не должен быть бесконечн... | true |
a1d060901a7729b87e6c3747e41f9a5defa0b66a | Python | freddyfok/cs_with_python | /problems/leetcode/101_symmetric_tree.py | UTF-8 | 698 | 3.5625 | 4 | [] | no_license | """
Return true if left of the center is
"""
from queue import Queue
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def is_symmetric(root: TreeNode) -> bool:
q = Queue()
q.put(root)
q.put(root)
while... | true |
d56dd944fdab677bbaff522ab477ce65a0272d96 | Python | chenjiayu1502/NER | /model_on_crf.py | UTF-8 | 15,361 | 2.578125 | 3 | [] | no_license | import torch
import torch.nn as nn
import torch.nn.init as I
import torch.nn.utils.rnn as R
from torch.autograd import Variable
import numpy as np
def log_sum_exp(vec, dim=0):
max, idx = torch.max(vec, dim)
max_exp = max.unsqueeze(-1).expand_as(vec)
return max + torch.log(torch.sum(torch.exp(vec - max_exp... | true |
078c73cade0e49fdb523587d911e7b6ca12283c5 | Python | ugly113/RPS | /main.py | UTF-8 | 1,387 | 4.03125 | 4 | [] | no_license | import random
# List for computer to choose from
rps = ['rock', 'paper', 'scissors']
# Displaying the results
def lose(computer):
print(f'\nI picked {computer}, you lose!')
def win(computer):
print(f'\nI picked {computer}, you win!')
def tie(computer):
print(f'\nI pick {computer} as well, it\'s a tie!'... | true |
b4b38871ea21c7ec93c9b0beb36fcbbcb0f3cb69 | Python | sinandylmz/Alistirma_1 | /1_8.py | UTF-8 | 213 | 2.625 | 3 | [] | no_license | def aynirakam():
sayac=0
for i in range(100,1000):
a=str(i)
if i%2==0 and (a[0]==a[1] or a[0]==a[2] or a[1]==a[2] or a[0]==a[1]==a[2]):
sayac+=1
return sayac
| true |
8a60f772a6aae5d6a5016c6369df572a4ffdab19 | Python | michalisvaz/Ham-or-Spam-classifier | /ig_calculation.py | UTF-8 | 2,180 | 3.046875 | 3 | [] | no_license | from math import log2
# return (ig, p_x1_ham, p_x0_ham)
def calculate_ig(x1, x1_ham, x1_spam, total_ham, total_spam):
total_mails = total_ham + total_spam
if x1 == 0 or x1 == total_mails:
return (0, total_ham/total_mails, total_ham/total_mails)
x0 = total_mails - x1
x0_spam = total_spam... | true |
078226e4e9533fec6ba6915c0dde7ccf50a8192f | Python | RamonBecker/S.O.L.I.D-Python | /Dependency Inversion Principle/BAD/repo/reports/file_write.py | UTF-8 | 159 | 2.59375 | 3 | [] | no_license |
class ReportFileWriter():
@staticmethod
def write_file(report):
file = open('report.txt', 'w')
file.write(report)
file.close() | true |
930e951968c6f5fcd44972f558762ed464de1147 | Python | cwz920716/GroDrawer | /groDrawer.py | UTF-8 | 14,052 | 3.609375 | 4 | [] | no_license | import sys
import math
import random
import numpy as np
def round3(x):
return float("{0:.3f}".format(x))
class Vec2(object):
def __init__(self, x, y):
self._x = float(x)
self._y = float(y)
@property
def x(self):
return self._x
@x.setter
def x(self, new_x):
sel... | true |
cd6099d6870ffddf5841ad7ae67480e6e5693c13 | Python | gavinrozzi/aleph | /services/extract-entities/entityextractor/aggregate.py | UTF-8 | 2,396 | 2.890625 | 3 | [
"MIT"
] | permissive | from entityextractor.extract import extract_polyglot, extract_spacy
from entityextractor.normalize import clean_label, label_key
from entityextractor.normalize import select_label
from entityextractor.util import overlaps
class EntityGroup(object):
def __init__(self, label, key, category, span):
self.lab... | true |
ec467636bb6136b33a7ec3704046a6fcdd53ef28 | Python | jestrella52/indybot | /rrScripts/rrBirthdays.py | UTF-8 | 2,577 | 2.671875 | 3 | [] | no_license | #!/usr/bin/env python
#
# Adds driver birth dates to database.
#
import MySQLdb
import MySQLdb.cursors
import datetime
import requests
import string
import time
import sys
import re
def findDriverID(driverList, last, first):
for driver in driverList:
if driver['last'] == last and driver['first'] == fir... | true |
5fd9353aa69cf0da94e67f18cc8ab979041e7d9f | Python | chess-equality/Arthur | /src/test/resources/same/operators/Operators.py | UTF-8 | 314 | 3 | 3 | [
"Apache-2.0"
] | permissive | def andOperator():
if True and True:
print ""
def orOperator():
if True or True:
print ""
def equalOperator():
if True == True:
print ""
def notEqualOperator():
if True != True:
print ""
def alternateNotEqualOperator():
if True <> True:
print ""
| true |
f2551a2cb174b8704ee3e9afa78ad6fdb55036b7 | Python | san33eryang/learnpy | /decorator.py | UTF-8 | 2,543 | 3.4375 | 3 | [] | no_license | # -*- coding: utf-8 -*
# 增加日志功能,并返回函数
def log(func):
def wrapper(*args,**kwargs):
print('call %s():'% func.__name__)
return func(*args,**kwargs)
return wrapper
@log
def nows():
print('2019-3-24 12:00')
# 增加日志功能,并返回函数,并解决了 nows的名字改变的情况
import functools
def log1(func):
@ functools.wr... | true |
b67b7316ee04f52d5585a42ecb3448b91843f863 | Python | vatula/capi | /capi/src/interfaces/datastructures/polygon.py | UTF-8 | 374 | 2.6875 | 3 | [
"MIT"
] | permissive | import abc
import typing
from capi.src.implementation.dtos.coordinate import Coordinate
class IPolygon(abc.ABC):
@property
@abc.abstractmethod
def vertices(self) -> typing.Sequence[Coordinate]:
pass
@abc.abstractmethod
def __eq__(self, other: object) -> bool:
pass
@abc.abstr... | true |
2a044f432e9d0539873edb17ea6ed946a0b09374 | Python | srp2210/PythonBasic | /pp_w3resource_solutions/basic_part_1/pp_w3_9.py | UTF-8 | 81 | 2.5625 | 3 | [] | no_license | exam_date = (11, 12, 2014)
print(exam_date[0], "/",exam_date[1],"/",exam_date[2]) | true |
53addf3e83f31fc1a265878056563dc299cefcf3 | Python | Y-Joo/Baekjoon-Algorithm | /pythonProject/Graph/Alphabet.py | UTF-8 | 581 | 2.671875 | 3 | [] | no_license | def bfs(start):
pas = set()
pas.add(board[0][0])
queue = set([start])
m = 1
while queue:
x, y, cnt, passed = queue.pop()
m = max(m, cnt)
for i in range(4):
lx, ly = x + dx[i], y + dy[i]
if 0 <= lx < r and 0 <= ly < c:
if board[lx][ly] n... | true |
a62f7ce02799b28d37604bceea04a2eb95589ea2 | Python | MakarVS/GeekBrains_Algorithms_Python | /Lesson_8/les_8_task_2.py | UTF-8 | 2,260 | 3.765625 | 4 | [] | no_license | """
Задача № 2.
Доработать алгоритм Дейкстры (рассматривался на уроке), чтобы он дополнительно возвращал список вершин,
которые необходимо обойти.
"""
from collections import deque
g = [
[0, 0, 1, 1, 9, 0, 0, 0],
[0, 0, 9, 4, 0, 0, 5, 0],
[0, 9, 0, 0, 3, 0, 6, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0... | true |
f333d77abf45c939a3a1b06212e1e5448b6b6809 | Python | fosc/tick-tack-toe | /opponents.py | UTF-8 | 3,971 | 4.125 | 4 | [] | no_license | """
This module contains implementations of the Player interface. A Player provides the play method:
1. play(Game State) --> tuple
The Game State interface provides the following methods:
1. is_game_over() --> Boolean
2. get_moves() --> list of tuples
3. is_winnable() --> Boolean
4. + tuple --> new Game State
"""
c... | true |
51732a90a88ebcc4ecc710f86b6cc3d3eb6e78af | Python | bot-kevin/python | /juegos/milove.py | UTF-8 | 570 | 3.265625 | 3 | [] | no_license | import turtle
azadine = turtle.Turtle()
badis = turtle.Screen()
badis.bgcolor("black")
badis.title("I love you")
azadine.speed(1)
azadine.goto(0,-100)
azadine.pensize(9)
azadine.color("red")
azadine.begin_fill()
azadine.fillcolor("red")
azadine.left(140)
azadine.forward(180)
azadine.circle(-90,200)
azadine.sethead... | true |
deefbff9896ca13b1a15e5d32e312c734c4057d2 | Python | boboalex/LeetcodeExercise | /leetcode_98.py | UTF-8 | 717 | 3.4375 | 3 | [] | no_license | import math
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def __init__(self):
self.pre = -2 ** 31
def isValidBST(self, root: TreeNode) -> bool:
def validation(node):
... | true |
45d6f234c686cdcec9b6aa66854b542c14c6dc55 | Python | UWPCE-PythonCert-ClassRepos/SP_Online_PY210 | /students/Z_shen/lesson09/test_mailroom_oo.py | UTF-8 | 2,013 | 3 | 3 | [] | no_license | from donor_models import *
import os.path
import pathlib
import pytest
donor_list = {'William Gates': [1500.99, 3500, 800.25],
'Jeff Bezos': [145.72, 1350.25],
'Paul Allen': [250.00, 57.00],
'Mark Zuckerberg': [600.00]}
def test_donor():
a = Donor('William Gates', 123)
... | true |
a35a1a87eb797744cdd7f9029e00a810e7c860aa | Python | koki0702/chainer0 | /chainer0/functions/basic_math.py | UTF-8 | 4,494 | 2.578125 | 3 | [
"MIT"
] | permissive | import numpy as np
import chainer0
from chainer0.function import Function
from chainer0 import variable
from chainer0 import functions
class Add(Function):
def forward(self, a, b):
self.is_broadcast = a.shape != b.shape
y = a + b
return y
def backward(self, gy):
ga, gb = gy, g... | true |
69e91a4e520be5c6e12721d0a874116ef26cd7e7 | Python | elderfd/numpyson | /numpyson.py | UTF-8 | 6,469 | 2.8125 | 3 | [
"MIT"
] | permissive | """
transparent serialization of numpy/pandas data via jsonpickle.
compatible to python2.7 and python3.3 and allows to serialize
between the two interpreters.
majorly based on code and ideas of David Moss in his MIT licensed pdutils
repository: https://github.com/drkjam/pdutils
Note that the serialization/deserializa... | true |
213bbe7ce2832ef07c329e587287441c6cd27e58 | Python | noxtoby/dem | /python/dem_utilities.py | UTF-8 | 16,890 | 2.546875 | 3 | [
"MIT"
] | permissive | import numpy as np
import pandas as pd
import os
import pystan
from sklearn.model_selection import StratifiedKFold
from matplotlib import pyplot as plt
import seaborn as sn
import statsmodels.formula.api as smf
import statsmodels.api as sm
import itertools
from datetime import datetime
def preliminaries(fname_sav... | true |
7557656e38c08e2295c753923085f1d14de47ab3 | Python | mayankmahavar111/Text-Classification | /stem.py | UTF-8 | 1,529 | 2.5625 | 3 | [] | no_license | import os
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
from nltk.stem import PorterStemmer ,WordNetLemmatizer
output =[]
stop=set(stopwords.words('english'))
stemmer = PorterStemmer()
lemma =WordNetLemmatizer()
for j in range(22):
if j >9 :
with open('reut2-0'+str(j)+'.sgm','r'... | true |
ee9f27a57bce0ee2310cb7215773ea89b6ed1736 | Python | harimurugesan/Python-Workouts | /hacker rank & hacker earth codes/discount dbs problem.py | UTF-8 | 498 | 3.171875 | 3 | [] | no_license | def disc(prices):
newprice = []
discountprice = []
list1 = []
lenp = len(prices)
for i in range(lenp):
discountprice.append(int(input()))
print(discountprice)
for num1, num2 in enumerate(prices):
newprice.append(num2 - discountprice[num1])
print(newprice)
for p1,p2 in... | true |
e8b561871ca494b174032768da3342f78457f82c | Python | Nishi0607/DSAlgoPython | /Queue-Python.py | UTF-8 | 949 | 3.859375 | 4 | [] | no_license | # -*- coding: utf-8 -*-
"""
Created on Thu Apr 16 22:14:43 2020
@author: NK
"""
#Queue implementation in Python
class Queue:
def __init__(self):
self.queue = []
def isEmpty(self):
self.queue == []
def enqueue(self, data):
self.queue.append(data)
... | true |
9ba6e92981a1d9d17602c2573a2d5b5b652d2023 | Python | ngroebner/Autoencoders | /Autoencoders/decoders.py | UTF-8 | 2,303 | 2.75 | 3 | [
"MIT"
] | permissive | import numpy as np
import torch
from torch import nn, optim
from torch.nn import functional as F
from Autoencoders.layers import Flatten, UnFlatten
class Decoder2DConv(nn.Module):
"""Constructs an decoder for use in various autoencoder models.
This is antisymmetric to the Encoder2DConv class. I.e., it
t... | true |
48f2953838a928d8258404aa498c43bde2ca9439 | Python | hxdaze/TCP-IP-Controlled-Robot | /server socket/robot-socket-gui.py | UTF-8 | 2,399 | 2.859375 | 3 | [] | no_license | # Robot Controller Client with socket-connection - made in May 2021 for TI502
# Matheus Seiji Luna Noda - 19190
# All imports
from PySimpleGUI import PySimpleGUI as gui
import struct, socket, sys, _thread
# Function that returns the port used for the socket
def get_port():
return 9001
# Function that return... | true |
80288ac7239c2e17a3fd081251ecc33eb92049d9 | Python | CCM-Balderas-Pensamiento-Comp/decisiones | /assignments/15ParkingFare/src/exercise.py | UTF-8 | 259 | 3.46875 | 3 | [] | no_license | def parking_cost(hours, minutes):
# Write your code here
def main():
hours = int(input("Enter number of hours: "))
minutes = int(input("Enter number of minutes: "))
print(parking_cost(hours, minutes))
if __name__ == '__main__':
main()
| true |
8b4d919bf394018e3f3c27f7acb5fd50aaf0aaf7 | Python | martincastro1575/python | /courseraPython/begin/SumarDosDados.py | UTF-8 | 1,144 | 4.125 | 4 | [] | no_license | """Este programa tirara dos dados y sumara el resultado"""
import random
# esta funcion elige elige un numero entre 1 y 6
def TirarDado():
Dado= int((random.random()*10%6)+1)
return Dado
# esta funcion suma los dos dados
def SumarDosDados(d1,d2):
resultado = d1+d2
return resultado
# esta fun... | true |
9b5f39e29d6532da01400e4cf4b3745b026e64f0 | Python | Jonathan-aguilar/DAS_Sistemas | /Ago-Dic-2018/Daniel Enriquez/ExamenExtraordinario/BaseExtra.py | UTF-8 | 1,535 | 2.796875 | 3 | [
"MIT"
] | permissive | import time, re, requests, os, errno, json, sqlite3
i=0
#conexion con la base
db = sqlite3.connect('Cervecitas.db')
cursor = db.cursor()
#Mediante este ciclo se trae una cerveza a la vez de la API desde la posicion 0 a la 50
for i in range(0,50):
i+=1
url = 'https://api.punkapi.com/v2/beers/'+ str(i)
req... | true |
948e6c589788028d915fc802b9e265bc49380c21 | Python | prachi411/Data_Structures_and_Algorithms.github.io | /Python/graph traversal.py | UTF-8 | 613 | 3.125 | 3 | [
"Unlicense"
] | permissive | class graph:
def __init__(self,edges):
self.edges=edges
self.graph_dic={}
for start,end in edges:
if start in self.graph_dic:
self.graph_dic[start].append(end)
else:
self.graph_dic[start]=[end]
print("graph_dic",self.gr... | true |
bb5f849ab83576b7c11e473109bf7fe20d54565d | Python | gitandlucsil/python_classes | /complet_curs/oriented_objects/cont_bank.py | UTF-8 | 675 | 3.609375 | 4 | [] | no_license | class Cont:
def __init__(self, client, number):
self.client = client
self.number = number
self.money = 0
def pull_money(self, value):
self.money += value
def push_money(self, value):
self.money -= value
def report(self):
print("Cont number "+self.n... | true |
ba1898f4b58303ecab1f93c1226894c02f0f5991 | Python | malithj/blog-examples | /mtpltlib-custom-hatch/main.py | UTF-8 | 1,863 | 3.296875 | 3 | [] | no_license | import matplotlib.pyplot as plt
import numpy as np
from matplotlib.hatch import Shapes, _hatch_types
from matplotlib.patches import Rectangle
class SquareHatch(Shapes):
"""
Square hatch defined by a path drawn inside [-0.5, 0.5] square.
Identifier 's'.
"""
def __init__(self, hatch, density):
... | true |
0981a3679c46bac83952cca95e6165c6bd9eb915 | Python | mushahiroyuki/beginning-python | /Chapter06/0611print-params2.py | UTF-8 | 432 | 3.421875 | 3 | [] | no_license | #@@range_begin(list1) # ←この行は無視してください。本文に引用するためのものです。
#ファイル名 Chapter06/0611print-params2.py
def print_params_2(title, *params):
print(title)
print(params)
#実行
print_params_2('引数:', 1, 2, 3)
print_params_2('引数はこれだけ:')
#@@range_end(list1) # ←この行は無視してください。本文に引用するためのものです。
| true |
a80e310d0af3d816d175ab5d110692da06c66ae5 | Python | cpe342/PythonCourse | /Lists/list_comp_inter.py | UTF-8 | 191 | 3.421875 | 3 | [] | no_license | num1=[1,2,3,4]
num2=[3,4,5,6]
answer=[]
answer=[n for n in num1 if n in num2]
print(list(answer))
names=["Ellie","Tim","Matt"]
answer2=[n[::-1].lower() for n in names]
print(list(answer2)) | true |
15434546a032255ee7cfb29f30a6501d60d81d41 | Python | kdaivam/PythonPrep | /Leetcode/remove_duplicates_in_list.py | UTF-8 | 637 | 3.484375 | 3 | [] | no_license | # -*- coding: utf-8 -*-
"""
Created on Sun Jun 9 21:36:00 2019
@author: kanyad
"""
def removeDuplicates_count_by_2( nums) :
i = 1
cnt = 1
while i < len(nums):
print(nums)
if nums[i] == nums[i-1]:
cnt += 1
else:
cnt = 1
... | true |
bf843bf241e023487d426b574f80a7db65cdf3ef | Python | molchiro/AtCoder | /old/ABC144/D.py | UTF-8 | 253 | 3.46875 | 3 | [] | no_license | import math
a, b, x = list(map(int, input().split()))
if a**2*b == x:
theta = 90
elif a**2*b/2 > x:
h = 2*x/a/b
theta = math.degrees(math.atan(h/b))
else:
h = 2*x/(a**2)-b
theta = math.degrees(math.atan(a/(b-h)))
print(90 - theta)
| true |
cf4323ca5710c59edb3e6e736b832dd19d8b1100 | Python | traffaillac/traf-kattis | /roundedbuttons.py | UTF-8 | 457 | 3.34375 | 3 | [] | no_license | from math import hypot
for _ in range(int(input())):
x, y, w, h, r, m, *clicks = map(float, input().split())
for i in range(int(m)):
X, Y = clicks[i * 2], clicks[i * 2 + 1]
inside = (
x <= X <= x+w and y+r <= Y <= y+h-r or
x+r <= X <= x+w-r and y <= Y <= y+h or
hypot(x+r-X, y+r-Y) <= r or
hypot(x+w-r... | true |
4e70e672a1965c8990383ccf0803b456a49a18cc | Python | ender8848/the_fluent_python | /chapter_18/multi_coroutine_spider.py | UTF-8 | 799 | 2.75 | 3 | [] | no_license | import time
import requests
from multiprocessing.dummy import Pool as ThreadPool
total = 100
thread = 4
async def request(loop):
url = 'http://127.0.0.1:5000'
future = loop.run_in_executor(None, requests.get, url)
response = await future
def divide(i):
import asyncio
loop = asyncio.new_event_loop()
asyncio... | true |
a8130a7aaf3eb5028db76900692cf2c3dc8561a5 | Python | Mbabysbreath/Python_Test | /src01/hello.py | UTF-8 | 1,341 | 3 | 3 | [] | no_license | from selenium import webdriver
import time
driver = webdriver.Chrome()
# 打开驱动指向的浏览器
driver.get("https://www.baidu.com/")
# 用id查询
# driver.find_element_by_id("kw").send_keys("大虞海棠")
# # time.sleep(6)
# driver.find_element_by_id("su").click()
# 用name查询
# driver.find_element_by_name("wd").send_keys("王一博")
# time.sleep(3... | true |
57802cd00a33596ee0ee680deb3cd4255325e40a | Python | nonnikb/verkefni | /Lokapróf/1 Basics/Time calculation.py | UTF-8 | 572 | 4.0625 | 4 | [] | no_license | """Given seconds (int) calculate hours, minutes and seconds.
For example, given 80000 seconds that is 22 hours, 13 minutes and 20 seconds.
Hint 1: use integer division // and remainder %
Hint 2: we require that you create and output variables hours, minutes
and seconds but you will likely find an additional variable us... | true |
b9b181065f40d5e9f6044622625c70ce4303be1e | Python | BarrettJB/CS104 | /lab1/lab1.py | UTF-8 | 505 | 3 | 3 | [] | no_license | #
# Lab 1, CS104
# Barrett Bryson 1252391
# Caleb Bieske 2219011
# 9-4-2014
#
from __future__ import division, print_function
input = raw_input
from myro import *
init("COM40")
print("Done connecting")
# Make the robot draw a circle by making the left wheel
# go forward at speed 0.4, and the right wheel go forward
# ... | true |
9196fafcdeb26e9802cb89d820002678d77e3e8d | Python | Gageowe/texquest | /screens.py | UTF-8 | 2,634 | 2.90625 | 3 | [] | no_license | class Screen:
def __init__(self, content = None, icon = "*",width = 40, height = 10, top = 1, bottom = 1, left = 1, right = 1):
self.content = content
self.width = width
self.height = height
self.top = top
self.bottom = bottom
self.left = left
self.right = rig... | true |
e5b2fce8fb9382bb0f7f01336f05861d1088a7a9 | Python | bkandel/BiteBar | /ConvertToTxt.py | UTF-8 | 534 | 2.75 | 3 | [] | no_license | #!/usr/bin/python
import glob
import os
import struct
FilesToConvert = glob.glob('*.dat')
for File in FilesToConvert:
FileComponents = os.path.splitext(File)
BaseFileName = FileComponents[0]
fid = open(File, 'rb')
BinaryString = fid.read()
AsciiData = []
i = 115
while (i + 28) < len(BinaryString):
... | true |
03093a3318187bbbbb8ce295821f782664412d20 | Python | ringhilterra/DSE201-Data-Management-Systems | /final/testing_data/soccer_data_generator.py | UTF-8 | 2,078 | 2.96875 | 3 | [] | no_license | import random
import pandas as pd
filename = "soccer_test_data_big.sql"
numTeams = 1000
numMatches = 100000
hlist = [] #hteam
vlist = [] #vteam
s1_list = [] #home score
s2_list = [] #visit team score
for i in range(1,numMatches):
h = random.randrange(1,numTeams+1)
v = random.randrange(1,numTeams+1)
# a te... | true |
532612005343510281d53bae828726c877906f05 | Python | mramire8/structured | /utilities/amt_tokenizer.py | UTF-8 | 386 | 2.703125 | 3 | [
"Apache-2.0"
] | permissive | __author__ = 'maru'
class AMTSentenceTokenizer(object):
def __init__(self):
pass
def tokenize_sents(self, doc):
return [sent.split("THIS_IS_A_SEPARATOR") for sent in doc]
def tokenize(self, doc):
return doc.split("THIS_IS_A_SEPARATOR")
def __call__(self, doc):
return ... | true |
434765246c329015c46316ccb907b6ba13ecb691 | Python | samuelyeewl/specmatch-emp | /specmatchemp/plots.py | UTF-8 | 5,999 | 3.1875 | 3 | [] | no_license | """
@filename plots.py
Helper functions to plot various data from SpecMatch-Emp
"""
import matplotlib.pyplot as plt
import matplotlib.transforms as transforms
def reverse_x():
"""Reverses the x-axis of the current figure"""
plt.xlim(plt.xlim()[::-1])
def reverse_y():
"""Reverses the y-axis of the curr... | true |
0341c61c76c02fe64b43c73874bb62a6e13f7ee3 | Python | GNeki4/urfuwmbot | /sheet_addition.py | UTF-8 | 2,273 | 3.25 | 3 | [] | no_license | from datetime import datetime, timedelta
import time
def get_dates_from_now(n):
list_of_dates = []
for single_date in (datetime.today() + timedelta(n) for n in range(n)):
list_of_dates.append(single_date.strftime("%d.%m"))
return list_of_dates
def merge_cells(sheetId, ss, top, bottom, left, ri... | true |
094f9fd68e9c2acf3a89a113bf5a7735768e424d | Python | zhaojunqin93/Reinforement_Learning | /RL/Policy Gradient/Policy_Gradient.py | UTF-8 | 2,983 | 2.921875 | 3 | [] | no_license | import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
class PolicyGradient:
def __init__(self, n_features, n_actions, learning_rate = 0.01, reward_decay = 0.95):
self.n_actions = n_actions
self.n_features = n_features
self.lr = learning_rate
self.gamma = reward_decay
self.ep_obs, self.... | true |
b444104cdb08e4aa3b75295bc041858ba9de96e0 | Python | SINHOLEE/Algorithm | /python/SSAFY_정규수업/9월/서울2반9월16일/순열.py | UTF-8 | 716 | 2.90625 | 3 | [] | no_license | # arr = [3, 1, 6, 4]
#
# def perm(r):
# global count
# count+= 1
# if len(arr) == r:
# print(temp, 'count = ',count)
# return
# for j in range(len(arr)):
# if visited[j] == False:
# visited[j] = True
# temp[r] = arr[j]
# perm(r + 1)
# ... | true |
86960b1b5c6f444c6f09ef2def68d11362a0c84f | Python | pabluc/test-gh-raspberry | /led.py | UTF-8 | 319 | 2.96875 | 3 | [] | no_license | import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
pinout = 18
color = "Green"
GPIO.setup(pinout,GPIO.OUT)
print "LED on N" + str(pinout) + " " + color
GPIO.output(pinout,GPIO.HIGH)
time.sleep(1)
print "LED off N" + str(pinout) + " " + color
GPIO.output(pinout,GPIO.LOW)
time.sleep(1)
| true |
291f279a6ceb9939cefa4227e2be48ac44df6b9b | Python | gauravsinha12/Screen-Recorder-In-Python | /samaye.py | UTF-8 | 376 | 3.25 | 3 | [] | no_license | from datetime import datetime
tdelta=""
try:
s1 = input("enter the time to start meeting ")
s2 = f"{datetime.now().time().hour}:{datetime.now().time().minute}:{datetime.now().time().second}"
FMT = '%H:%M:%S'
tsub = datetime.strptime(s1, FMT) - datetime.strptime(s2, FMT)
except:
print("Enter in this ... | true |
97f35448773dd049515d14bb54e990ec1d609112 | Python | brovador/advent-of-code-python-2017 | /day24/main2.py | UTF-8 | 1,314 | 2.84375 | 3 | [] | no_license | #encoding: utf-8
import os
import re
import string
import sys
max_strength = 0
max_length = 0
def main():
input_file = './input.txt'
with open(input_file, 'r') as f:
lines = [map(int, l.strip().split('/')) for l in f]
ports = sorted([line + [sum(line)] for line in lines], lambda x, y: x[2] > y[2])
starting_p... | true |
1d2c9a4252d76c9f7f4b49a650e666c00f3ce63a | Python | ARJOM/testes-sistema | /tribos/backend/app/utils/getAge.py | UTF-8 | 228 | 3.046875 | 3 | [] | no_license | from datetime import datetime
def get_age(date):
now = datetime.now()
birthday = datetime.strptime(date, "%Y-%m-%d")
return abs((now.year - birthday.year) - ((now.month, now.day) < (birthday.month, birthday.day)))
| true |
142ab16a96affd6ce2f29b49bea45cd8206d1c53 | Python | sublee/josa | /josa.py | UTF-8 | 984 | 2.640625 | 3 | [] | no_license | # -*- coding: utf-8 -*-
import warnings
from korean import Loanword, Noun, Particle, hangul, morphology
warnings.warn('This library has been deprecated. Use "korean" instead.',
DeprecationWarning)
def has_jongseong(word, lang='eng'):
if lang == 'kor':
word = Noun(word)
else:
i... | true |
3cc50a9911a77726966cd90bf0709293b458b593 | Python | adityanshastry/Car-alarm-trust | /common/Utils.py | UTF-8 | 3,943 | 2.640625 | 3 | [] | no_license | from __future__ import division
import numpy as np
from sklearn.utils.extmath import cartesian
import Constants
def scale_to_fourier_basis(value, bounds):
return (value - bounds[0]) / (bounds[1] - bounds[0])
def update_states_to_bounds(state):
state[0] = max(state[0], Constants.states[0][0])
state[0] =... | true |
1bc4af1bb0daef25fcf4fb0db67eb22c9b5592d5 | Python | ShirleyMwombe/Python-Training | /Stringmethods.py | UTF-8 | 271 | 3.46875 | 3 | [] | no_license | name = "SHirley"
#print(name.find("r"))
#print(len(name))
#print(type(name))
#print(name.capitalize())
#print(name.count("l"))
#print(name.upper())
#print(name.lower())
#print(name.isdigit())
#print(name.isalpha())
#print(name.replace("H","k"))
print(name*3) | true |
72a4508b128d0b0c80230468d3aa5a5abda35e9a | Python | zhouyuels/webTest | /WebTEST/main/commom/init/Browser.py | UTF-8 | 2,121 | 2.609375 | 3 | [] | no_license | #!/usr/bin/env python3
# -*- coding:utf-8 -*-
# @FileName :Browser.py
# @Time :2019/12/3 17:26
# @Author :ZhouYue
# @Description :浏览器驱动设置,取的driver
import os
from selenium import webdriver
from main.config.readconfig import Readconfig
from main.commom.init.globalvar import globalvar
from main.commom.tools.l... | true |
09255b8eb0862e85833b5e28ea3bfc7a2fceffbc | Python | igizm0/SimplePyScripts | /rumble (vibration) a xbox 360 controller/web/rumble.py | UTF-8 | 1,048 | 2.5625 | 3 | [] | no_license | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = 'ipetrash'
# SOURCE: http://stackoverflow.com/questions/19749404/
import ctypes
# Define necessary structures
class XINPUT_VIBRATION(ctypes.Structure):
_fields_ = [
("wLeftMotorSpeed", ctypes.c_ushort),
("wRightMotorSpeed", ctypes.c_u... | true |
54a8f9e3cba8472adaec23f0f44e99694913a4ee | Python | arkocal/tetai | /torch_learn_by_trial.py | UTF-8 | 3,471 | 2.671875 | 3 | [] | no_license | #
# Step 1. pick a field
# Step 2. pick 2 random moves
# Step 3. rate moves
# Step 4. play for NR_MOVES, re-evaluate
# Step 5. train by swapping ORIGINAL EVALUATIONS if worse > better
import random
import time
from ai_players import TorchAIPlayer
import utils
from mechanics import Mechanics
nes_tetris = Mechanics()
... | true |
7e7a40af9dd3370c78fe8744e5b2d38476cb8398 | Python | vinayaklal98/ITDBot | /app/gsearch.py | UTF-8 | 277 | 2.84375 | 3 | [] | no_license | from googlesearch import search
def searching(query):
results = {}
key = 1
for i in search(query, tld="co.in", num=10, stop=10, pause=2):
results[key] = i
key += 1
else:
return results
#query = input("Enter Search: ")
#searching(query) | true |
396d4adb7f3c7aca4d9103f9c68bf8c63c136567 | Python | phicau/olaFlow | /tutorials/wavemakerFlume/constant/pistonWaveGen.py | UTF-8 | 1,706 | 2.5625 | 3 | [] | no_license | #!/usr/bin/python
import numpy as np
def dispersion(T, h):
L0 = 9.81*T**2/(2.*np.pi)
L = L0
for i in range(0,100):
Lnew = L0 * np.tanh(2.*np.pi/L*h)
if(abs(Lnew-L)<0.001):
L = Lnew
break
L = Lnew
return L
## Piston wavemaker data ##
H = 0.1
T = 3.0
... | true |
76ef9f48be5b09e2a1c2253e4e74279cbbc46b1e | Python | elanstop/protein-classification-and-generation | /make_data.py | UTF-8 | 3,882 | 3.21875 | 3 | [] | no_license | from Bio import SeqIO
import numpy as np
import pickle
from random import shuffle, seed
# data downloaded in .fasta file format from UniProt
# funky amino letters are X,U,Z,B. We exclude sequences containing these letters.
# 100_to_200.fasta was created with the following search terms: length 100 to 200, complete s... | true |
24695cb13b7e5bd0a6679fc88d767a6afc6c44ec | Python | max-kalganov/NN_subject | /Lab_3/classifier.py | UTF-8 | 2,534 | 2.8125 | 3 | [] | no_license | from os.path import join
import pandas as pd
from tensorflow.keras import Sequential
from tensorflow.keras.models import load_model
from tensorflow.keras.layers import Dense
from sklearn.metrics import confusion_matrix
from matplotlib import pyplot as plt
import numpy as np
from utils import get_dataset
# import Tenso... | true |
3f38420c535f31f133aadb1f09adc1ef3ba8ce37 | Python | ibssasimon/CSC365G22Lab1-2 | /ericFuncs.py | UTF-8 | 2,463 | 3.703125 | 4 | [] | no_license | def searchStudent(students, teachers, lastName):
for student in students:
if lastName == student.lastName:
for teacher in teachers:
if teacher.classroom == student.classroom:
print("\nStudent: " + student.lastName + ", " + student.firstName +
... | true |
10faa955ed7cedf291fa0562eb0485f98bcaa73f | Python | cinhori/LeetCode | /python_src/valid_parentheses.py | UTF-8 | 1,350 | 4 | 4 | [] | no_license | # 给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。
# 有效字符串需满足:
# 左括号必须用相同类型的右括号闭合。
# 左括号必须以正确的顺序闭合。
# 注意空字符串可被认为是有效字符串。
#
# 示例 1:
# 输入: "()"
# 输出: true
# 示例 2:
# 输入: "()[]{}"
# 输出: true
# 示例 3:
# 输入: "(]"
# 输出: false
# 示例 4:
# 输入: "([)]"
# 输出: false
# 示例 5:
# 输入: "{[]}"
# 输出: true
class Solution:
# 36ms, 84.19%; ... | true |
4ac8872b63eda9c684840d3611a7b8e69d8fad67 | Python | HawpT/BrainFloss | /playgame/models.py | UTF-8 | 3,146 | 2.640625 | 3 | [] | no_license | # from __future__ import unicode_literals
from django.db import models
from django.conf import settings
# Create your models here. models are tables
class Level_One(models.Model):
op1 = models.IntegerField(blank=False, null=False, default=0)
op2 = models.IntegerField(blank=True, null=True, default=0)
st... | true |
d0bbf56f725df4594d04ceea6a4f4ff373480305 | Python | santhosh-kumar/DataScienceToolbox | /tests/unit/common/utils/test_string_utils.py | UTF-8 | 1,849 | 3.125 | 3 | [] | no_license | """
Unit Test for string_utils
"""
from unittest import TestCase
from utils.string_utils import StringUtils
from exceptions.exceptions import AssertionException
class TestStringUtils(TestCase):
"""
Unit test for string utils
"""
def test_str_to_boolean(self):
"""Test str_to_boolean
... | true |