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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
456276225091fc89504b3d4a4d93c9893bdf2110 | Python | Zuzukin-dp/introPython_BAV | /HomeWorks/BAV_HW_14.py | UTF-8 | 5,552 | 3.96875 | 4 | [] | no_license | # В компьютерной игре есть юниты (персонажи).
# Каждый юнит имеет такие характеристики:
# имя
# клан
# здоровье (int от 1 до 100. Начальное значение 100)
# сила (int от 1 до 10. Начальное значение 1)
# ловкость (int от 1 до 10. Начальное значение 1)
# интелект (int от 1 до 10. Начальное значение 1)
#
# ... | true |
40d715b25a448cc7e3c8ee7508b0f9c06aa9ec3e | Python | rafinhadufluxo/Under-Control | /main.py | UTF-8 | 694 | 3.296875 | 3 | [
"MIT"
] | permissive | from calculator_factories import make_root, make_display, make_label, make_buttons
from calculator_function import CalculatorFunction
from calculator_actions import calculate
# Derivar f(x) = (x**3 - 3*x + 2)*exp(-x/4) - 1.
def main():
root = make_root() # Cria a tela da calculadora
display = make_display(root... | true |
1aee320f0415d1770bf23f1fed1a146395987e5c | Python | rongunit/ASC_HW3 | /main.py | UTF-8 | 5,065 | 3.34375 | 3 | [] | no_license | # ----------------------------- main.py ------------------------------
# Исполняемый файл программы.
# -----------------------------------------------------------------------
import sys
from random import randint
import time
from parallelepiped import Parallelepiped
from shape import Shape
from sphere import Sphere
f... | true |
e89a22ef4f9dca30e3679af9997ed0cd11017b90 | Python | emilylinh/school | /CS 8/Projects/spycraft.py | UTF-8 | 2,204 | 3.34375 | 3 | [] | no_license | #Emily Lu, Simon Freund
def buildKey(rawKey):
key = ''
x = {}
rawKey_sorted = sorted(rawKey)
acc = 1
for ch in rawKey_sorted:
number = ord(ch)
for number in rawKey_sorted:
if number not in x:
x[number] = acc
acc = acc + 1
for i in rawK... | true |
2b3343a26e1e92f1bccd33dca6143014527d3f61 | Python | balabit-deps/balabit-os-6-heartbeat | /heartbeat/hb_api.py | UTF-8 | 28,569 | 2.75 | 3 | [] | no_license | #!/usr/bin/python
'''Heartbeat related classes.
What we have here is a handful of classes related to the
heartbeat cluster membership services.
These classes are:
ha_msg: The heartbeat messaging class
hb_api: The heartbeat API class
'''
__copyright__='''
Copyright (C) 2000 Alan Robertson <alanr@unix.sh>
... | true |
e54d402338044449bf06ef766f46cac26ad0f60d | Python | ShiFengZeng/ZeroJudge_py | /b051.py | UTF-8 | 326 | 3.328125 | 3 | [] | no_license | from functools import cmp_to_key
def cmp(a, b):
if a + b < b + a:
return 1
elif a + b > b + a:
return -1
else:
return 0
while True:
try:
A = []
A = input().split()[1:]
A.sort(key=cmp_to_key(cmp))
print(*A, sep='')
except EOFError:
... | true |
96c3662e41dab603543d8ed224e414353efd6544 | Python | bifferos/bb | /qemu/scripts/qapi.py | UTF-8 | 4,917 | 2.53125 | 3 | [] | no_license | #
# QAPI helper library
#
# Copyright IBM, Corp. 2011
#
# Authors:
# Anthony Liguori <aliguori@us.ibm.com>
#
# This work is licensed under the terms of the GNU GPLv2.
# See the COPYING.LIB file in the top-level directory.
from ordereddict import OrderedDict
def tokenize(data):
while len(data):
if data[0]... | true |
1c288074520a8588dec44e7235a1eec108ec5aa5 | Python | mattcodesz/FirstProject | /main.py | UTF-8 | 4,058 | 4.03125 | 4 | [] | no_license | # main file to hold all the code relevant to making an employee
# This is the superclass Person; it is used to make the base of everything.
# This program can become more than just employee; can be anything related to person
class Person():
# sets up values of object
def __init__(self, firstName, lastNam... | true |
13726976d63e6da49d152b586bea70bb5acd16ca | Python | jsndc99/dbce | /chat/client.py | UTF-8 | 477 | 3.203125 | 3 | [] | no_license | # client.py
import socket
soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
soc.connect(("127.0.0.1", 12345))
clients_input = input("Wanna type something?\n")
soc.send(clients_input.encode("utf8")) # we must encode the string to bytes
result_bytes = soc.recv(4096) # the number means how the response can ... | true |
86d8132ff918414258b04ac8ea6fff1a0380959e | Python | davidozhang/easy-test | /monitor.py | UTF-8 | 920 | 2.640625 | 3 | [] | no_license | # -*- coding: utf-8 -*-
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
class FileModifiedHandler(FileSystemEventHandler):
def on_modified(self, event):
if event.src_path == self.path:
self.easy_test._test()
def set_path(self, path):
self... | true |
7e32aac73b2fff94e3cb0377b9aebb4bb6111b45 | Python | PotapovaSofia/NextBestViewRL | /compute_metrics.py | UTF-8 | 2,036 | 2.546875 | 3 | [] | no_license | import numpy as np
import itertools
import trimesh
import math
import k3d
from time import sleep
from tqdm import tqdm
import torch
from rl.dqn import *
USE_CUDA = torch.cuda.is_available()
def compute_metrics(env, agent_func, iter_cnt=10, max_iter=30):
rewards, final_rewards, novp = [], [], []
for _ in rang... | true |
aba7fcf75339a54419ac0dd5f089e4c6aad897d5 | Python | santibaamonde/prueba | /ejercicio3_clase9_parte2.py | UTF-8 | 469 | 4.375 | 4 | [] | no_license |
# Crea un programa que muestre por pantalla la tabla de multiplicar de un número introducido por el usuario, pero invertida, comenzando desde el 10.
numero_tabla = int(input("De que número quieres la tabla de multiplicar invertida?: "))
indice = 9
lista_multiplos = range(1,11)
while indice == int(lista_multiplos[i... | true |
9f158b70c03167d28f7b7df5281c44b6054d6658 | Python | nickmvincent/where_that_from | /unused/parse_xml.py | UTF-8 | 465 | 2.921875 | 3 | [
"MIT"
] | permissive | """
Not currently used
"""
import xml.etree.ElementTree
def parse_xml():
filename = 'sample_paper.xml'
e = xml.etree.ElementTree.parse(filename).getroot()
print(e)
out = ""
for page in e.findall('page'):
for region in page.findall('region'):
out += region.text + ' '
... | true |
0ba5f07bd03d28265005698c6a2f8f81c2cbdd6c | Python | softwarefaith/PythonFullStack | /PythonFullStack/000Basic/Day01-基础/day01/06-输入和输出.py | UTF-8 | 460 | 4.1875 | 4 | [] | no_license | #输出
print("helloworld")
mystr1 = "hello"
mystr2 = "world"
#输出多个变量的时候,中间会有分隔符(默认的分隔符是空格)
print(mystr1,mystr2)
#修改输出的分隔符
print(mystr1,mystr2,sep="&")
#print函数默认输出之后会换行
print("1",end="zhangsan")
print("2",end="\n\n")
print("3")
#输入:获取用户键盘输入的文字(python2 raw_input)
result = input()
print("打印输入的数字",result) | true |
53c6536e940df2eca2a2074915fe9cb87393a70e | Python | jnguyen0597/EARTH119 | /Earth119/Week 8/ODE4_oscillator_RK.py | UTF-8 | 4,644 | 3.203125 | 3 | [] | no_license | #!/bin/python2.7
"""
solve second order, homogeneous ODE: damped, harmonic oscillator
- compare analytical and numerical (both Euler and Range Kutta)
ODE: my''(t) + ky(t) = 0
f(t) = F*cos(wt)
w0**2 = k/m
"""
from __future__ import division
import os
import matplotlib as mpl
import matplotlib.pyplo... | true |
9d4b7f09a9c4ff1dd23429dd08d1fa1cdf9960ca | Python | RaspiKidd/PythonByExample | /Challenge24.py | UTF-8 | 159 | 4.03125 | 4 | [] | no_license | # Python By Example Book
# Challenge 024 - Ask the user to type in any word and display it in upper case
word = input("enter any word: ")
print(word.upper()) | true |
efbfe109dab169718200171a709e368cb76d62ef | Python | Ayesha116/piaic.assignment | /q36.py | UTF-8 | 236 | 4.34375 | 4 | [] | no_license | #Write a program to check whether given input is palindrome or not
a = input("enter text: ").lower()
reverse = a[::-1]
if a == reverse:
print("enterd text",a," is palindrome")
else:
print("enterd text",a," is not a palindrome")
| true |
d6245c088744dccd965dbc4a8f10679089009b77 | Python | XingshengLiu/PythonTools | /datamidplatform/covercalcu.py | UTF-8 | 1,195 | 2.59375 | 3 | [] | no_license | # @File : covercalcu.py
# @Author: LiuXingsheng
# @Date : 2021/1/20
# @Desc : 学习进度覆盖率计算脚本
from collections import defaultdict
import csv
import os
DirPath = r'F:\EnterpriseMM Cache\WXWork Files\File\2021-01\NeuralCD_predict_Version02_test\NeuralCD_predict_Version02\bubugao_data\original_data'
def getAllData():
c... | true |
5552ed7a20013c88e68808d552bc299ed349c245 | Python | yukioichida/self-attention-encoder | /test.py | UTF-8 | 918 | 3.109375 | 3 | [
"MIT"
] | permissive | import torch.nn.functional as F
import torch
fn = F.cross_entropy
label = torch.tensor([2])
predicted = torch.tensor([[0.0, 0.0, 5.]])
print("Loss = {:.4f}".format(fn(predicted, label)))
print("torch.max {}".format(torch.max(predicted, 1)))
# POSITIONAL EMBEDDING JUST LIKE OPEN AI FINE TUNED TRANSFORMER
import n... | true |
61b7a0290cded7aed88687a7f79ae157b611cf34 | Python | Fhernd/Python-CursoV2 | /parte12/demo_122_programa_python_punto_entrada.py | UTF-8 | 373 | 4.3125 | 4 | [] | no_license | # Programa Python con punto de entrada:
def saludar(mensaje):
print(mensaje)
class Persona:
def __init__(self, documento, nombre):
self.documento = documento
self.nombre = nombre
def main():
edward = Persona(123456789, 'Edward Ortiz')
saludo = f'Hola, mi nombre es {edward.nombre}.'
... | true |
dca434f566a4f9c4715ccd7b65173f1d71777027 | Python | gracehaza/DevTools-Utilities | /scripts/merge.py | UTF-8 | 1,131 | 3.015625 | 3 | [] | no_license | #!/usr/bin/env python
'''
Script to merge files.
'''
import argparse
import glob
import os
import sys
def parse_command_line(argv):
parser = argparse.ArgumentParser(description='Merge files from directory')
parser.add_argument('directory',type=str,help='Input top-level directory to merge, merges each subdirec... | true |
d8b715c0070c26949a7c50fd009e8a26e272d6ec | Python | filljonas/bone-cement-injection-planning | /nets/segmentation_network.py | UTF-8 | 6,810 | 2.75 | 3 | [] | no_license | import torch
import torch.nn as nn
from . import custom_layers as layers
class ConvBlock(nn.Module):
"""2 x 3D convolution with following parameters
kernel=3, stride=1, padding=1, Xavier's init
followed by Leaky ReLU Activation and Batch Normalization
"""
def __init__(self, in_chs, chs_1, chs_2):... | true |
9e6b1f695b0f26f5907a6a25fe8e7dac8fb33590 | Python | ddfelts/RestDefaults | /lib/utils/timelib.py | UTF-8 | 287 | 2.734375 | 3 | [] | no_license | import os
import time
def current_epoch():
return int(time.time())
def date_to_epoch(dateString, strFormat="%Y-%m-%d"):
return time.mktime(time.strptime(dateString, strFormat))
def epoch_to_date(t, strFormat="%Y-%m-%d"):
return time.strftime(strFormat, time.localtime(t))
| true |
560361c174c186a0a9e928c69d40f47ab9520e6b | Python | agateau/nanoci | /tests/test_config.py | UTF-8 | 853 | 2.515625 | 3 | [
"BSD-3-Clause"
] | permissive | import os
import yaml
from nanoci.config import Config
from nanoci.fileutils import mkdir_p
def create_project(tmpdir, name, build=None, notify=None):
project_path = os.path.join(tmpdir, 'projects', name + '.yaml')
mkdir_p(os.path.dirname(project_path))
dct = {}
if build is not None:
dct['b... | true |
ab95827165a4354d2e43e2a84e3f2fecf3f88204 | Python | tczhaodachuan/LeetCode | /src/main/facebook/Matrix.py | UTF-8 | 1,484 | 3.8125 | 4 | [] | no_license | # a matrix, for one row, from left to right if one column is 1, all of the remaining columns are 1.
# find the first column which contains the 1
def findColumn(matrix):
m = len(matrix)
n = len(matrix[0])
i = 0
j = n - 1
result = -1
while i < m and j >= 0:
if matrix[i][j] == 1:
... | true |
139b55b905b319b8f2ad8a20a65684a6f07cad37 | Python | MrFlygerian/Tweet-classification | /utils/TweetClassifierBuilder.py | UTF-8 | 7,185 | 2.703125 | 3 | [] | no_license | # Data Manipulation
import pandas as pd
pd.set_option('use_inf_as_na', True)
import numpy as np
from sklearn.model_selection import train_test_split
# tweets processing
import nltk
nltk.download('stopwords')
nltk.download('punkt')
import re
from nltk.tokenize import word_tokenize
from string import punctuation
from nl... | true |
1df465c93ea8529f3674ddd5314dc31ce84a520f | Python | samkaufman01/pyLCI | /utils/rpc_api.py | UTF-8 | 1,532 | 2.609375 | 3 | [
"Apache-2.0"
] | permissive | from jsonrpclib.SimpleJSONRPCServer import SimpleJSONRPCServer
import threading
class RPCApi():
functions = []
def __init__(self, config):
self.config = config
self.server = SimpleJSONRPCServer((self.config['rpc_host'], self.config['rpc_port']))
self.server.timeout = self.config['rpc_... | true |
a621315aa926ca7a5d5a8670acc6349219a4dfbc | Python | JIceberg/Chess | /src/parse_input.py | UTF-8 | 836 | 3.421875 | 3 | [
"MIT"
] | permissive | import chess
import re
def __parse(s: str) -> chess.Move:
# return arbitrary invalid move
if not re.match('^[A-Za-z]\d, [A-Za-z]\d', s): return chess.Move.null()
tmp = s.split(', ')
return chess.Move.from_uci(tmp[0].lower()+tmp[1].lower()+tmp[2]) if len(tmp) > 2 else chess.Move.from_uci(tmp[0].lower()... | true |
2890f74e0d9fe87b516b7023fd33d2410e0f03ae | Python | ranjithkumar121/Python | /ProductSmallestPair.py | UTF-8 | 639 | 3.8125 | 4 | [] | no_license | '''Implement the following Function
def ProductSmallestPair(sum, arr)
The function accepts an integers sum and an integer array arr of size n.
Implement the function to find the pair, (arr[j], arr[k]) where j!=k, Such that arr[j] and arr[k] are
the least two elements of array (arr[j] + arr[k] <= sum) and return the... | true |
79bd036618c4326d305acaa84634a2d0e8282ec6 | Python | signeus/API-Web | /modules/route_builder/url_builder.py | UTF-8 | 1,254 | 2.890625 | 3 | [
"LicenseRef-scancode-public-domain"
] | permissive | import urllib
class URLBuilder:
def urlBuild(self, parametersApp):
#protocol, ip, port, application, controller, {atribs}
protocol = parametersApp.get('protocol', "http")
ip = parametersApp.get('ip', "localhost")
port = parametersApp.get('port', "80")
application = parameter... | true |
0c14009118cfedeeb9c1206c941f3dc3131ff112 | Python | AnelaK/PrimePartitions | /PrimePartitions.py | UTF-8 | 1,409 | 4.125 | 4 | [] | no_license | import sys, math
def sieveOfEratosthenes(a, b):
#returns list of all primes between a and b inclusive using the method Sieve of Eratosthenes
primes =[True for i in range(b+1)]
primes[0] = False
primes[1] = False
length = int(math.sqrt(b))
for i in range(length + 1):
if (... | true |
530802add454c8af4dec032c826a32f4b2d7bd41 | Python | ankitakash2007/vaani-survey | /chatbotserver/chatbotserver/polyglot.py | UTF-8 | 168 | 2.5625 | 3 | [] | no_license | import polyglot
from polyglot.text import Text, Word
text = Text(u"In Großbritannien war Gandhi mit dem westlichen Lebensstil vertraut geworden")
print(text.entities)
| true |
f030549c888eb9b3ff4ebf1b92f59851d6531460 | Python | Choco31415/groupMeApiWebhooks | /fancySheep/logger.py | UTF-8 | 624 | 2.8125 | 3 | [] | no_license | """
This class holds the logger.
"""
# Handle imports
import logging
import logging.handlers
# Config logger
def setup_logger(path):
global logger, absolute_path
# Formatting
logger = logging.getLogger(__name__)
format = "[%(asctime)s] %(message)s"
formatter = logging.Formatter(format, datefmt='%... | true |
b36a9911c910d2afda443a1fc0c2cf4c703c8c36 | Python | riatalwar/Honors-Geometry | /Unit-2/TriangleSideLengthsFunctions.py | UTF-8 | 2,159 | 4.84375 | 5 | [] | no_license | """
STUDENT NAME, Honors Geometry, 3-8-2021
Program: Triangle Side Lengths
This program will prompt the user to enter the coordinates of the vertices of a triangle. It will then calculate and display the lengths of the sides of the triangle
"""
## FUNCTIONS ##
def WelcomeMessage ():
"""
Print a welcome messag... | true |
f72d09c1b2ad249fe1ad8ed615b074acfa9de969 | Python | pp-mo/bbc | /lib/sim/device/pseudo_devices.py | UTF-8 | 4,955 | 2.625 | 3 | [
"BSD-3-Clause"
] | permissive | import sys
sys.path.append(
'/storage/emulated/0/qpython/')
from types import MethodType
from sim.signal import SIG_UNDEF
from sim.device import okeq, okin
from sim.device import Device, Action
class SigBitslice(Device):
"""
A pseudo device that outputs
a bit slice of an input signal.
"""
... | true |
7c831b33d8049f08f88cc286a90d94af7bb236a5 | Python | fengzhi19940518/NaiveBayesDemo | /bayes.py | UTF-8 | 8,635 | 2.65625 | 3 | [] | no_license | from numpy import *
import re
import feedparser
def loadDataSet():
postingList = [['my', 'dog', 'has', 'flea', 'problem', 'help', 'please'],
['maybe', 'not', 'take', 'him', 'to', 'dog', 'park', 'stupid'],
['my', 'dalmation', 'is', 'so', 'cute', 'I', 'love', 'him'],
... | true |
32ead5127b35d4ec471349ba445d1279753d244c | Python | flogothetis/Technical-Coding-Interviews-Algorithms-LeetCode | /Grokking-Coding-Interview-Patterns/1. Sliding Window/No-repeat Substring.py | UTF-8 | 887 | 3.953125 | 4 | [] | no_license | '''
Problem Statement #
Given a string, find the length of the longest substring which has no repeating characters.
'''
# Time Complexity : O(N)
# Space O(1) constant number of characters
def longestSubArrayKDistinct (array):
startWindowPointer = 0
dict_arr = {}
longestSubArray = 0
for endWindowPointer in range... | true |
325ce01f2b6117c684dbbc2cd77e487377fb9e64 | Python | KristerSJakobsson/japanese-data-extractor | /src/extractor/models/DateValue.py | UTF-8 | 1,084 | 3.390625 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"BSL-1.0"
] | permissive | from abc import ABC
from enum import Enum
from typing import Optional
class DateValueType(Enum):
RELATIVE = 1
ABSOLUTE = 2
class DateValue(ABC):
"""
This model represents a date value, either relative or absolute.
"""
def __init__(self, value: int, type: DateValueType):
self.value =... | true |
e05df6b39dec8a351b9e65d374b8d5898966fb96 | Python | jishnu7/UniCal-Notifier | /twitterbot/__init__.py | UTF-8 | 568 | 2.75 | 3 | [] | no_license | #!/usr/bin/env python
import tweepy
from keys import *
class Twitter():
""" to manage twitter related activities """
def __init__(self):
# OAuth authentication
auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_KEY, ACCESS_SECRET)
self.api =... | true |
6726ec2dc3815476af729792bff6f7a315e8f891 | Python | rec/randpass | /old/simple_key.py | UTF-8 | 1,224 | 3.078125 | 3 | [] | no_license | #!/usr/bin/python
import random
import sys
import badwords
VOWELS = 'aeiou'
CONSONANTS = 'bdfgklmnprstvz'
LETTERS = VOWELS, CONSONANTS
CAPITALIZE = True
BAD_INITIALS = ['l', 'i']
TERMINAL_PUNCTUATION = ['.', '...', '!', '?', '!!', '!?', '?!', '??']
def is_bad(key):
return badwords.is_bad(key) or (key[0] == BAD_IN... | true |
1724e0042916a5e24267671057fba45e792b49d3 | Python | Mullans/evolutionary-deep-learning | /data_manager.py | UTF-8 | 967 | 2.859375 | 3 | [
"MIT"
] | permissive | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
def plot_accuracy_over_gen(filenames, labels=[], colors=[], lower_cutoff=0.5):
for i in range(len(filenames)):
data = pd.read_csv(filenames[i], sep=',').values.astype(np.float32)
generations = data[:, 0]
fitness = data[... | true |
f458699b51055c5201346b3ad1e29997cf119acf | Python | RahulKrg14/ML_Plagiarism_Detection | /plagiarism/plagiarism/build/lib/plagiarism/tests/test_ngrams.py | UTF-8 | 1,383 | 2.953125 | 3 | [] | no_license | from plagiarism.bag_of_words import count_all
from plagiarism.ngrams import optimal_bigrams, ngrams, remove_ngram
def test_ngram_simple():
assert ngrams(['foo', 'bar', 'baz'], 2, sep=' ') == \
['foo bar', 'bar baz']
assert ngrams(['foo', 'bar', 'baz'], 2, join=tuple) == \
[('foo', 'bar')... | true |
25a74302dabdac3ca1e661fca58faf33ac36c29a | Python | hakaorson/CodePractise | /Write_test/hongshu/1.py | UTF-8 | 419 | 3.046875 | 3 | [] | no_license | '''
2
3
3 1 4
5 8 10
'''
n = int(input())
m = int(input())
maxnum = 0
nums = []
for i in range(n):
temp = list(map(int, input().split()))
nums.append(temp)
maxnum = max(maxnum, max(temp))
result = [False for i in range(maxnum+2)]
for i in range(n):
for j in range(m):
result[nums[i][j]] = True
f... | true |
b39cb0b213a8a97d7d3f22b8b0d4380d27fba6f2 | Python | gbowerman/wordtools | /containers/containers/api_layer/api_layer.py | UTF-8 | 5,127 | 2.703125 | 3 | [
"CC0-1.0"
] | permissive | from bottle import error, get, response, route, run
import json
import os
import pymysql
from random import randint
import socket
import sys
#hostname = socket.gethostname()
hostname = '0.0.0.0'
dbhost = 'wordtools-data' # name of the database server container, linked by compose file
hostport = 8081
max_words = 200
#... | true |
8a7c2c0cedd2a2848b685ec5ea0a5578ff9c46b9 | Python | kiselyovanat/diploma | /clear.py | UTF-8 | 2,610 | 2.640625 | 3 | [] | no_license | import random
import sage.all
from sage.matrix.constructor import Matrix
from sage.rings.integer_ring import ZZ
from sage.crypto.sbox import SBox
from sage.modules.free_module_element import vector
def difference_distribution_table(g):
m = g.input_size()
n = g.output_size()
nrows = 1<<m
ncols = 1<<n
... | true |
3a9f28a34dfa7936e11c7936a286e301a7b3f3c8 | Python | Mubeen31/Covid-19-data-in-plotly-dash | /index.py | UTF-8 | 6,454 | 2.578125 | 3 | [] | no_license | import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
import plotly.graph_objs as go
import pandas as pd
from datetime import date
covid = pd.read_csv('covid_19_clean_complete.csv')
covid['Date'] = pd.to_datetime(covid['Date'])
app = dash.D... | true |
37bda2b9d4dc4b7b3884c80a7d64c51fb5972f41 | Python | anandnitt/Robotix-arm-using-IK | /mech3mod.py | UTF-8 | 2,191 | 3.109375 | 3 | [] | no_license | import numpy as np
import matplotlib.pyplot as plt
from collections import deque
from math import acos,sin,radians,degrees,cos
import serial
import time
from scipy.optimize import fsolve
from scipy.interpolate import spline
import math
from math import cos,sin
import numpy as np
from matplotlib import pyplot... | true |
448ddccc951e9755f2091b2d1a6d319d38aedcd9 | Python | eduard-kazakov/OceanDataProcessor | /ODPTools.py | UTF-8 | 612 | 2.796875 | 3 | [] | no_license | from pyproj import Proj, transform
def lon_lat_to_x_y (lon, lat, proj_desc):
p1 = Proj(init='epsg:4326')
p2 = Proj(proj_desc)
x,y = transform(p1,p2,lon,lat)
return x, y
def lon_lat_to_grid_cell (lon,lat,xmin,xmax,ymin,ymax,xstep,ystep,proj_desc):
size_x = (xmax-xmin)/xstep
size_y = (ymax-... | true |
2a79735a8507f14407d291f2481b03a6f3fa250f | Python | Sholde/EasyBot | /bot.py | UTF-8 | 4,037 | 3.078125 | 3 | [] | no_license | import os
import discord
from dotenv import load_dotenv
from discord.ext import commands
import random
load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
bot = commands.Bot(command_prefix = '!')
# Print in terminal when the bot is ready
@bot.event
async def on_ready():
print(f'{bot.user.name} has connected to Di... | true |
3bf9400caf779811287888ef628213729549bf4a | Python | K-subin/HangmanGame | /testGuess.py | UTF-8 | 3,216 | 2.578125 | 3 | [] | no_license | import unittest
from guess import Guess
class TestGuess(unittest.TestCase):
def setUp(self):
self.g1 = Guess('default')
def tearDown(self):
pass
def testDisplayCurrent(self):
self.g1.guess('e')
self.assertEqual(self.g1.displayCurrent(), '_ e _ _ _ _ _')
... | true |
a269d459d79c3a96d2a635e25ee38d2a4298d586 | Python | grogsy/roguelike | /entities/inanimate.py | UTF-8 | 1,045 | 3.109375 | 3 | [] | no_license | import tcod
from .entity import Entity
from components.inventory import Inventory
from items.util import generate_random_item
from game_state import RenderOrder
class Inanimate(Entity):
def __init__(self, *args, **kwargs):
super().__init__(*args, render_order=RenderOrder.ITEM, blocks=False)
class Containe... | true |
cd2dd51bc36e5abdfa218b34ce6afb6504f76f00 | Python | baxtercl/python-examples | /problema_atletas.py | UTF-8 | 3,189 | 3.78125 | 4 | [
"MIT"
] | permissive | import pandas as pd
from math import *
from numpy import *
print("Determinar si la diferencia de altura de las personas de dos deportes es significativamente distinta. A continuación, se debe ingresar dos nombres de deportes.")
#Entradas
deporte1 = input("Ingresa primer deporte: ").lower()
deporte2 = input("Ingresa s... | true |
732818ff2db27adee34527082fcc209b24e5638e | Python | billallen256/minnow | /examples/make_ingest_data.py | UTF-8 | 607 | 2.71875 | 3 | [
"MIT"
] | permissive | # vim: expandtab tabstop=4 shiftwidth=4
from datetime import datetime
from pathlib import Path
from random import randint
from uuid import uuid4
import sys
def main():
output_path = Path(sys.argv[1])
for i in range(10):
dt = datetime.fromtimestamp(randint(0, 2**32))
name = str(uuid4())
... | true |
a1fa10a41833e57617aa4033c9b5ddf2e578f332 | Python | shradhit/Anecdote_Detector | /Source_Code/Statistical_Analysis/Other/add_spaces_around_story_tags.py | UTF-8 | 289 | 3.21875 | 3 | [] | no_license | # This script will add spaces around the story tags (ie <story> and </story>)
import re
fname = "a1"
f = open(fname, "r")
s = f.read()
p = re.compile("<story>")
q = re.compile("</story>")
s = p.sub(" <story> ", s)
s = q.sub(" </story> ", s)
fname2 = "a2"
f = open(fname2, "w")
f.write(s)
| true |
72556896e3c447c06d72a69fc4b1350eb46d691a | Python | navuhod/pyneng | /04_/sample_number.py | UTF-8 | 962 | 4.0625 | 4 | [] | no_license | # деление int и float
print('деление int - 10 на 3 ', 10/3)
print('деление float - 10 на 3.0 ', 10/3.0)
# функция round позволяет округлять до нужного числа знаков
print('округление до 2 и 4 знаков', round(10/3.0, 2), round(10/3.0, 4))
# целая часть и остаток от деления
print (10 // 3, 'целая часть от деления 10 на 3')... | true |
e86b56b76a85136faf9d6c0c310a90beb21af9a6 | Python | SFM61319/OhMyMath | /OhMyMath!/OhMyMath!.py | UTF-8 | 71,822 | 3.15625 | 3 | [] | no_license | """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" ##############################################################################################################################################################################################################################################################... | true |
d8586dd56e8a09e82a8a620efe1fbf118c4dbbd7 | Python | TongjiMechineLearning/siameseNet | /inference.py | UTF-8 | 2,166 | 2.609375 | 3 | [] | no_license | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 18-9-19 下午12:46
# @File : demo.py
# @Software: PyCharm
# @Author : wxw
# @Contact : xwwei@lighten.ai
# @Desc :
import tensorflow as tf
import cv2
import numpy as np
from scipy.spatial.distance import pdist
class SiameseNet(object):
##默认输入4*4
de... | true |
817baff2881cf74f1eb4a45d9454ea514da91eba | Python | ripvanchuckle/python | /URL.py | UTF-8 | 1,781 | 3.640625 | 4 | [] | no_license | #Begining info for this script can be found at the following URL
#https://www.geeksforgeeks.org/python-find-current-weather-of-any-city-using-openweathermap-api/
#I used the foundaton of the original script, and built off that in an attempt to meet
#the criteria for the homework assignment. The weather options I use... | true |
6db78c0549a126e93dab994a8c0842c754133345 | Python | slemonide/arcane_text | /encrypt.py | UTF-8 | 452 | 3.34375 | 3 | [] | no_license | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import random
while True:
user_input = input("> ")
encrypted_string = ""
for c in user_input:
offset = random.randint(0, 90)
encrypted_string = encrypted_string + chr((ord(c) - 32 + offset) % 90 + 32) + chr(offset + 32)
... | true |
704b87fc09611cf83db5bf72ae7c7013c7d37a02 | Python | etmo6394/cs2270_ethan | /homeworks/hw-6-pq/py/pq.py | UTF-8 | 849 | 3.78125 | 4 | [] | no_license | class PriorityQueue:
def __init__(self):
'''
Do whatever initialization you need here.
'''
pass
def insert(self, text, priority):
'''
Insert the given text information into the queue with the
specified priority.
Larger priority values h... | true |
4e790302eeb10be0dd8b9a5cf3ea0a7fa8d05594 | Python | tiyberius/project-euler | /xor_decryption/xor_decryption.py | UTF-8 | 2,122 | 3.71875 | 4 | [] | no_license | import csv
import os
import itertools
def solve_problem():
script_directory = os.path.dirname(os.path.realpath(__file__))
ciphertext_file_path = os.path.join(script_directory, 'p059_cipher.txt')
with open(ciphertext_file_path) as names_file:
dirty_cipher_text = list(csv.reader(names_file))[0]
... | true |
64ddededbb1d679a4c3b4be4601374438a8b01d3 | Python | AkulK1/TextReadability | /model_explore.py | UTF-8 | 3,282 | 2.859375 | 3 | [] | no_license | # -*- coding: utf-8 -*-
"""
Created on Fri Aug 14 22:40:19 2020
@author: BX
"""
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression, Lasso
from sklearn.model_selection import cross_val_score
from sklearn.ensemble import RandomForestRegres... | true |
3182d53c28e94f2df13058b0cd713880338db617 | Python | Thomas-Wallis/2018-practicals | /prac_04/quick_picks.py | UTF-8 | 630 | 3.8125 | 4 | [] | no_license | def main():
import random
min_picks = 1
max_picks = 45
numbers_per_line = 6
number_of_quick_picks = int(input("How many quick picks? "))
while number_of_quick_picks < 1:
print("Please select a number greater than 1")
number_of_quick_picks = int(input("How many quick picks? "))
... | true |
0337c62fec3b3223e9a6786b21ae144a4abc2056 | Python | YiSoJeong/Algorithm_Python | /SW/Basic/6257_셋, 딕셔너리5.py | UTF-8 | 123 | 3.25 | 3 | [] | no_license | fruit = [' apple ', 'banana', ' melon']
fruit = [x.strip() for x in fruit]
d = {x: len(x) for x in fruit}
print(d)
| true |
740515b69a5edf79c3fe51cdd012bf650b8ebde2 | Python | joshcabral/FlexTracker | /scraping/emailloginscraper.py | UTF-8 | 1,461 | 3.234375 | 3 | [] | no_license | import easyimap
import emaillogin as el
def check_email_for_new_logins():
"""
Checks the email and scrapes for logins and passwords from the claremont
Card Office.
Returns: a list tuple pairs in the format: (login, password).
"""
logins = []
# Loop through unread emails
imapper = easy... | true |
e07578c43764d5798086282f66977a6649069a6f | Python | nicweisberg/AStar | /basicSearch.py | UTF-8 | 7,542 | 3.328125 | 3 | [] | no_license | # Nick Weisberg
import UninformedSearch as BlindSearch
import InformedSearch as Search
import Problem as P
print()
print()
print()
print("///////////// Comparing Search Algorithms ////////////")
print("//////////// Shows time, nodes & space ////////////")
print("/////////// Nick Weisberg /////... | true |
396983d799dae77c90cb863d191d9cb9c7396a31 | Python | duraes-antonio/ResolveAE | /Persistencia/Scripts/micro_dao/estado.py | UTF-8 | 691 | 2.703125 | 3 | [] | no_license | from micro_dao.objeto_modelo import ObjetoModelo
class Estado(ObjetoModelo):
_id: int
_nome: str
_sigla: str
def __init__(self, nome_estado: str, sigla: str):
self._id = 1
self.set_nome(nome_estado)
self.set_sigla(sigla)
def get_id(self) -> int:
return self._id
... | true |
ce2e23cc12d78020ffc38b54a9f7510be1933776 | Python | remixknighx/quantitative | /exercise/leetcode/can_place_flowers.py | UTF-8 | 638 | 3.5 | 4 | [] | no_license | # -*- coding: utf-8 -*-
"""
605. Can Place Flowers
@link https://leetcode.com/problems/can-place-flowers/
"""
from typing import List
class Solution:
def canPlaceFlowers(self, flowerbed: List[int], n: int) -> bool:
ans = 0
num = 1
for x in flowerbed:
if x == 0:
... | true |
420ce2ed5de501660ef3b80c1bb50d33fff90ca4 | Python | BossCai-790923/Hello-world | /0006_sorted_solution_2.py | UTF-8 | 962 | 2.890625 | 3 | [] | no_license |
# merge
list_a = [1,5,7,9,13,15,24,27,78,110,167]
list_b = [2,2,6,8,16,17,18,19,99]
# to list_ab
# merge
list_c = [1,5,7]
list_d = [2,2,6,8,16,17,18,19,99]
# to list_cd
# merge
list_e = []
list_f = [2,2,6,8,16,17,18,19,99]
# to list_ef
x=[]
list_ab=[]
list_cd=[]
list_ef=[]
x+=list_a
x+=list_b
... | true |
98e580bc5993569fa9ced968c5d3eb5b22a5e064 | Python | ronak148/fizzbuzz | /fizzbuzz.py | UTF-8 | 239 | 3.65625 | 4 | [] | no_license | print("Fizzbuzz puzzle")
a=int(raw_input("Write any Number:"))
if a % 3 == 0 and a % 5 == 0:
print("Fizzbuzz")
elif a % 3== 0:
print ("Fizz")
elif a % 5==0:
print("buzz")
else:
print("Try Again") | true |
1f4d1968374444b2a559f2cf00ede7c9c948bc5d | Python | icapistrano/cards_recognition | /process scripts/trainRanks/machineLearning2.py | UTF-8 | 919 | 3.0625 | 3 | [] | no_license | import matplotlib.pyplot as plt
import cv2
import numpy as np
from sklearn import datasets
from sklearn.neural_network import MLPClassifier
from scipy import misc
digits = datasets.load_digits()
features = digits.data
labels = digits.target
clf = MLPClassifier() #2, 4, 7,
clf.fit(features, labels)
i... | true |
001d1bc6d2a9e55ffc0b5b93e56f58439b9d2577 | Python | kate-ka/problem-solving | /multiprocessing.py | UTF-8 | 2,290 | 3.296875 | 3 | [] | no_license | import multiprocessing as mp
import os
from os import path
import time
import datetime
# non persistant task list
running = {}
executed = {}
errors = {}
class Task(object):
"""
read a task file with the following content: Hello Parallel Tasks;5
"""
def __init__(self, taskfile):
self.name = t... | true |
f0982a0f486dd1378ac0eb07e906c560685556ae | Python | Vision314/CompSciClub | /cogs/tictactoe.py | UTF-8 | 7,856 | 3.203125 | 3 | [] | no_license | # Tic-Tac-Toe by Frankie
# 1/16/21
import discord
from discord.ext import commands
class TicTacToe(commands.Cog):
def __init__(self, client):
self.client = client
self.gameOn = False
@commands.Cog.listener()
async def on_command_error(self, ctx, error):
if i... | true |
5d60b7771aded715df20729cadb1aff49a45a54c | Python | bryan-l-serrano/orps | /updateFunctions.py | UTF-8 | 2,789 | 2.78125 | 3 | [] | no_license | #!/usr/bin/python
import sqlite3
import string
import os
import readFunctions
k = 32
def updatePlayerPassword(playerId, newPassword):
conn = sqlite3.connect('/orps/orps.db')
conn.row_factory = sqlite3.Row
cursor = conn.cursor()
cursor.execute("UPDATE PLAYER SET password = ? WHERE PlayerID = ?", (newPa... | true |
d6e5a2577238431c551541b50b70c27b4cbffc96 | Python | Gregory-Ryan/Friends_list | /friend list.py | UTF-8 | 6,829 | 3.671875 | 4 | [] | no_license | def first_name(first_name_last_name):
for place_in_name in range(1, len(first_name_last_name)):
if first_name_last_name[place_in_name] == " ":
return first_name_last_name[0:place_in_name]
def last_name(first_name_last_name):
fin = 0
found = 0
first_space = 0
second_space = 0
... | true |
0176aedce21edbdebc97b5d20df39f17c4505235 | Python | J-GG/Pymon | /src/views/common/text.py | UTF-8 | 2,110 | 3.34375 | 3 | [] | no_license | import cocos
import pyglet
from toolbox.init import PATH
class Text(cocos.cocosnode.CocosNode):
"""Enables to write text with the Pokemon font.
Attributes:
- characters: List of characters for which a special process is
necessary.
"""
characters = dict()
characters["/"] = (... | true |
c560a4904c8dd745d7a711428e297f8be5262f95 | Python | martin-sun/Teach_Kids_To_Code | /lesson_2/clock.py | UTF-8 | 389 | 3.453125 | 3 | [] | no_license | import turtle
window = turtle.Screen()
window.bgcolor("green")
pen = turtle.Pen()
pen.pencolor("blue")
pen.pensize(5)
pen.shape("turtle")
def draw_clock():
pen.penup()
pen.forward(150)
pen.pendown()
pen.forward(30)
pen.penup()
pen.forward(30)
pen.stamp()
pen.backward(210)
for i in ra... | true |
52ef0e7435ecb2a2d9c34c6afd75f4ad2cdadb1e | Python | rkd1003/python202003 | /sqlitetest/sqlitetest5.py | UTF-8 | 630 | 2.9375 | 3 | [] | no_license | #csv->db
import sqlite3,csv
conn=sqlite3.connect('sqlitetest/sup.db')
cur=conn.cursor()
sql='''
create table if not exists sup
(
sup_name varchar(20),
invoice_number varchar(20),
part_number varchar(20),
cost float,
date date
)'''
cur.execute(sql)
sql='delete fr... | true |
5b5ec879bb6eac27c55ae829295e43bb8bb630b3 | Python | timed1975/testrepos | /loan/LoanModule.py | UTF-8 | 12,295 | 2.71875 | 3 | [] | no_license | from collections import namedtuple
import os
import urllib.parse as URL
import xml.etree.ElementTree as TREE
def calc_monthly_payment(amt, rate, pymnts):
mthly_rate = float(rate) / (12 * 100)
period_calc = 1 - pow(1 + mthly_rate, -int(pymnts))
return round(float(amt) * (mthly_rate / period_calc), 2... | true |
160b043f1ee9972f8ef799ba685131b80b803a7a | Python | ewanlee/stanford-tensorflow-tutorials | /2017/assignments/exercises/e03_heart.py | UTF-8 | 4,099 | 2.65625 | 3 | [] | no_license | import os
os.environ['TF_CPP_MIN_LOG_LEVEL']='2'
os.environ['CUDA_VISIBLE_DEVICES'] = '1'
import numpy as np
import tensorflow as tf
import time
import pandas as pd
from sklearn import preprocessing
from sklearn.model_selection import train_test_split
import shutil
tf.set_random_seed(42)
np.random.seed(42)
# Define ... | true |
5c6f79bb477f88d332a9718ba90c42af854848f5 | Python | jeremyosborne/python | /ml/data_frames.py | UTF-8 | 3,112 | 3.765625 | 4 | [
"MIT"
] | permissive | import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
print("Messing with pandas data frams.")
dates = pd.date_range('20130101', periods=6)
print("""
# (Interpretation of docs):
# * Two dimensional data array.
# * index = row labels
# * columns = column labels
# * data = contents of the 2d array, can... | true |
d2ca26d0e6f3adaf12a4a4d0116808b2860081cf | Python | Aden-Q/LeetCode | /code/647.Palindromic-Substrings.py | UTF-8 | 656 | 2.890625 | 3 | [
"MIT"
] | permissive | class Solution:
def countSubstrings(self, s: str) -> int:
dp = [[False] * len(s) for _ in range(len(s))]
res = 0
for i in range(len(s)-1, -1, -1):
for j in range(i, len(s)):
if j == i:
dp[i][j] = True
res += 1
... | true |
bd42f8e3deaa4ad29f8309946117d5e27ed75c16 | Python | rozierguillaume/formation_indus_ds_cicd | /src/feature_engineering.py | UTF-8 | 6,325 | 3.359375 | 3 | [] | no_license | import numpy as np
import pandas as pd
from typing import Tuple
def names(train: pd.DataFrame, test: pd.DataFrame) -> Tuple[pd.DataFrame, pd.DataFrame]:
"""
Creates two separate columns: a numeric column indicating the length of a
passenger's Name field, and a categorical column that extracts the
pass... | true |
71eb916ce69edae9476f63e7c10cbf8c4fb9d4eb | Python | MashaPo/class_works | /training/16.10.10_orph.py | UTF-8 | 280 | 3.65625 | 4 | [] | no_license | #заменяем все четные на Б. абракадабра -> БбБаБаБаБрБ
inpt = input('введите слово\n')
word = ''
for number,letter in enumerate(inpt):
if number%2 == 0:
word += 'Б'
else:
word += letter
print(word)
| true |
b1b4f1445b20c072578664c7aa940b7b6f76c163 | Python | gitaprisilfia/tugas2 | /R-2.1.py | UTF-8 | 452 | 2.84375 | 3 | [] | no_license | # R-2.1
"""
Give three examples of life-critical software applications.
1) Self-driving cars -- if there is a software failure, it can lead to fatal accidents.
2) insulin checker -- a person who has diabetes must always track his/her insulin intake, and they rely on
machines that can check their blood
3) Air tr... | true |
c151e5cfa8821f249237e72a818c5d81374e6a62 | Python | sctweedie/csvdiff3 | /csvdiff3/tools/tools.py | UTF-8 | 1,401 | 2.78125 | 3 | [
"MIT"
] | permissive | #!/usr/bin/python3
#
# csvdiff3/tools/hooks
#
# Simple utility functions useful for general manipulation/validation
# of CSV files
import csv
import sys
from .options import *
def eprint(*args, **kwargs):
print(*args, file=sys.stderr, **kwargs)
def __check_key(reader, filename, key):
if not key:
ret... | true |
2e3ddd64f1d4a243f1c392c2fce6b24953044b3a | Python | kumarsaurav20/pythonchapters | /01_conditions.py | UTF-8 | 557 | 4.84375 | 5 | [] | no_license | # How to use if else ,elif
# If-elif ladder
a = 30
# if(a>3):
# print("The value of a is greater than 3")
# elif(a>7):
# print("The value of a is greater than 7")
# elif(a>17):
# print("The value of a is greater than 17")
# else:
# print("The value is not greater that 3 and 7")
# print(" ... | true |
6d3472e33a1f34eac626855ef67df53d623954d2 | Python | PratikKelkar/research-ML | /mn.py | UTF-8 | 1,255 | 2.640625 | 3 | [] | no_license | import numpy as np
np.random.seed(123)
from keras.models import Sequential
from keras.datasets import mnist
from keras.layers import Dense,Dropout,Activation,Flatten
from keras.layers import Convolution2D, MaxPooling2D
from keras.utils import np_utils
from matplotlib import pyplot as plt
(xtrain, ytrain), (xt... | true |
e0ccab7bd43b0e763dd683d6317dc8bf46319ba1 | Python | ynahum/rl_hw | /wet3/q_learn_mountain_car.py | UTF-8 | 6,590 | 2.734375 | 3 | [] | no_license | import numpy as np
import time
from data_transformer import DataTransformer
from mountain_car_with_data_collection import MountainCarWithResetEnv
from radial_basis_function_extractor import RadialBasisFunctionExtractor
class Solver:
def __init__(self, number_of_kernels_per_dim, number_of_actions, gamma,... | true |
5e1d535a9ac72f040d251cbda98ad0a369b70bbb | Python | geninhocell/data_science | /algebra/vector_operation.py | UTF-8 | 5,371 | 4.1875 | 4 | [] | no_license | """
# soma
[1, 2] + [ 2, 1] => [1+2, 2+1] = [3, 3]
# subtração
[1, 2] - [ 2, 1] => [1-2, 2-1] = [-1, 1]
# distance
sqrt((v_1 - w_1)** + ... + (v_n - w_n)**)
"""
from functools import reduce, partial
from math import sqrt
from typing import List
Vector = List[float]
##################################################... | true |
4a252581e44764bd10cb7493a92b36fbfb8128e1 | Python | lazodelsol/DQ-Projects | /CIA World Factbook (SQL Practice)/query.py | UTF-8 | 193 | 2.9375 | 3 | [] | no_license | import sqlite3
conn = sqlite3.connect("factbook.db")
cursor = conn.cursor()
query = "select name from facts order by population asc;"
results = cursor.execute(query).fetchmany(5)
print(results) | true |
53754440f413787b36f4481fc257d904f88f7420 | Python | VittorioParagallo/tln-1920 | /part3/exercise5/model.py | UTF-8 | 3,391 | 3.03125 | 3 | [] | no_license | from collections import namedtuple
from data import Vocabulary
from batcher import Batcher
from keras.models import Sequential
from keras.layers import GRU, Dense, Embedding, Dropout
from beam_search import beam_search
import numpy as np
vocab = Vocabulary("./vocabulary.txt")
params = {
'hid_dim': 128,
'emb_... | true |
ace1615fbb891d3bd7018d28f74908d8548c448d | Python | LozenPoi/UrbanSeg | /Code/train.py | UTF-8 | 3,055 | 2.65625 | 3 | [] | no_license | import gc
import torch
import visdom
import torch.optim as optim
import torchvision.transforms as transforms
from PIL import Image
from torch.autograd import Variable
from tqdm import tqdm as tqdm
import cityscapes_loader
import loss
import segnet
# Setup visdom for visualization.
vis = visdom.Visdom()
loss_window = ... | true |
4a757f91d94420eee63844512a3402a4b8ba1910 | Python | mdghayman/sister_moon | /01_graphics.py | UTF-8 | 1,131 | 2.921875 | 3 | [] | no_license | import tdl
SCREEN_WIDTH = 80
SCREEN_HEIGHT = 50
def handle_keys():
global player_x, player_y
user_input = tdl.event.key_wait()
#movement keys
if user_input.key == 'UP':
player_y -= 1
elif user_input.key == 'DOWN':
player_y += 1
elif user_input.key == 'LEFT':
player_x -=... | true |
8e68ff48ac963ffcf6bfc0b6b210e05b54429367 | Python | wangbin2360/HMDB51_CNN | /train_test.py | UTF-8 | 2,123 | 2.578125 | 3 | [] | no_license | # -*- coding: utf-8 -*-
"""
Created on Thu May 3 14:26:50 2018
@author: ghm13
"""
import os
import numpy as np
import random
from sklearn.preprocessing import OneHotEncoder
path_save = 'C:/Users/ghm13/Desktop/inputdata'
dirs = os.listdir(path_save)
numbers = np.arange(0,51)
dictionary = {}
for i in range(len(di... | true |
33620e488ab7a707f9c0606c1467e4d1dabc9bee | Python | sbasu-datalicious/APITesting | /TestCases/test_Customers_Positive.py | UTF-8 | 5,125 | 2.890625 | 3 | [] | no_license | from Tools import Request
from Tools import DBConnect
from Tools import Helpers
from datetime import datetime
import string
import random
rq = Request.Request()
qry = DBConnect.DBConnect()
helper = Helpers.Helper()
def generate_random_info():
"""
This generates random strings. The strings generated are for em... | true |
73a9544105ca7eae0d7997aa2e0a4b74bf8723b7 | Python | SanamKhatri/school | /teacher_delete.py | UTF-8 | 1,234 | 3.734375 | 4 | [] | no_license | import teacher_database
from Teacher import Teacher
def delete_teacher():
delete_menu="""
1.By Name
2.By Addeess
3.By Subject
"""
print(delete_menu)
delete_choice=int(input("Enter the delete choice"))
if delete_choice==1:
delete_name=input("Enter the name of the... | true |
5acced597b8312da2214d10e56ab8296a37129ad | Python | kimukook/variable_length_oscillating_pendulum | /LF/NNLF/Functions.py | UTF-8 | 3,448 | 2.90625 | 3 | [
"MIT"
] | permissive | # # -*- coding: utf-8 -*-
# import dreal
# import torch
# import numpy as np
# import random
#
#
# def CheckLyapunov(x, f, V, ball_lb, ball_ub, config, epsilon):
# # Given a dynamical system dx/dt = f(x,u) and candidate Lyapunov function V
# # Check the Lyapunov conditions within a domain around the origin (bal... | true |
2a3a8536d699130087b42595a87f072b4522e334 | Python | awilsoncs/worldgen | /worldgen/saving.py | UTF-8 | 2,368 | 2.875 | 3 | [] | no_license | from __future__ import print_function
import errno
import os
import numpy
import png
class SaveHandler:
"""Handles all saving functionality."""
def __init__(self, world_map, path):
self.world_map = world_map
self.path = path
set_up_dir('worlds')
set_up_dir('worlds/' + path)
... | true |
cbf93c247d135efdd036a249aad0b46276975802 | Python | rgkaufmann/CCodes | /PHYS 319/Python Integration/Ultrasonic/Serial Plotting.py | UTF-8 | 1,584 | 2.875 | 3 | [] | no_license | import serial
import numpy as np
from time import sleep, time
import pygtk as gtk
from matplotlib.figure import Figure
from matplotlib.backends.backend_gtk3agg import FigureCanvasGTK3Agg as FigureCanvas
def press(event):
print('press', event.key)
if event.key == 'q':
print ('got q!')
quit_app()... | true |