blob_id large_string | repo_name large_string | path large_string | src_encoding large_string | length_bytes int64 | score float64 | int_score int64 | detected_licenses large list | license_type large_string | text string | download_success bool |
|---|---|---|---|---|---|---|---|---|---|---|
ab9e77965c2e9a3ea62ff45834952c695f3e3e13 | thales-mro/python-basic | /numpy/resize-reshape-ravel_examples.py | UTF-8 | 410 | 3.796875 | 4 | [] | no_license | import numpy as np
a = np.array([[0, 1], [2, 3]])
print("Original Array:")
print(a)
print("Resize example:")
print(np.resize(a, (2, 3)))
print("Reshape example: (size of array should be unchanged)")
print("Original:")
x = np.ones((3, 4))
print(x)
print("Size:", x.size)
y = x.reshape((2, 6))
print("After reshape:")
pr... | true |
cd631c9efeae502e3facf87f1ae88ad8754fbfee | alok123t/HyINDEL | /scripts/helperSimulations.py | UTF-8 | 2,907 | 3 | 3 | [
"MIT"
] | permissive | import random
import sys
# Small, large size ranges
DISTR = [[50, 500], [500, 10000]]
# Number of variants for each size range
N_DISTR = 375
def getRandomString(l):
return ''.join(random.choice('ATGC') for _ in range(l))
def genPositions():
# For each size range
for d in DISTR:
# Insertions
... | true |
a5a080b0fd38a6ba4a92a4aabca157426497e9ef | CS22-team-13/cs-build-week-2 | /miner.py | UTF-8 | 3,032 | 3.109375 | 3 | [
"MIT"
] | permissive | import hashlib
import requests
import json
import sys
from keys import api_key
from uuid import uuid4
from time import sleep
from timeit import default_timer as timer
from json import loads, dumps
import random
def proof_of_work(last_proof, difficulty):
"""
Multi-Ouroboros of Work Algorithm
- Find a numbe... | true |
74df0df7cc606b3681810f05f142930c934c45de | maomao905/algo | /single-number-3.py | UTF-8 | 1,164 | 3.734375 | 4 | [] | no_license | """
first-pass
xor -> find number which appear odd times
but we get two numbers which appear once
get the right-most 1 bit from xor result
if the answer is a and b, a or b has the right-most 1bit
let's take the second pass to know which a or b has the right-most 1bit
time: O(N) space: O(1)
"""
from typing import List... | true |
b53bbebdf8b331fbad40be54fcf187dce6e82580 | li594/li594 | /多彩螺旋线.py | UTF-8 | 472 | 3.171875 | 3 | [] | no_license | Python 3.8.5 (tags/v3.8.5:580fbb0, Jul 20 2020, 15:57:54) [MSC v.1924 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> import turtle
>>> t = turtle.Pen()
>>> def draw_spin():
colores = ['orange','blue','yellow','red','purple','green']
turtle.bgcolor('black')
... | true |
d438d3feca0f8f6267367d7fec3aeb8634dbdef1 | MI-911/cold-start-framework | /models/fmf/fmf_interviewer.py | UTF-8 | 5,012 | 2.640625 | 3 | [] | no_license | import pickle
from typing import Dict, List, Union
from tqdm import tqdm
from models.base_interviewer import InterviewerBase
from models.fmf.fmf import LIKE, DISLIKE, UNKNOWN, FMF, Tree
import numpy as np
from loguru import logger
from shared.meta import Meta
from shared.user import WarmStartUser
from shared.utility... | true |
8efa910ea513c59171bd14f25b041bf59c044661 | andreishumeiko/shumeiko_project | /dz2_1.py | UTF-8 | 293 | 2.71875 | 3 | [] | no_license | s_list = [1, 2.1, (-1 + 2j), True, 'Airplane', [5, 8], (5, 6.5), range(12), {1: 'fname', 2: 'lname'},
(b'literal'), bytearray(b'twelve'), {8, 9}, frozenset(), zip(*[(5, 6), (18, 19), ('a', 'b')]), ValueError]
for i, item in enumerate(s_list):
print(f"{i}. {item} - {type(item)}") | true |
44d7a3974090ce3277b2ecaf84a997cc3f611755 | DanaPiff/RIP | /Circle.py | UTF-8 | 489 | 3.1875 | 3 | [] | no_license | #! /usr/bin/env python
# -*- coding:utf-8 -*-
from lab_python_oop.Geom_figures import GeometricFigures
from math import pi
class Circles(GeometricFigures):
def __init__(self, radius, color, name="Circle"):
self.color = color
self.radius = radius
self.name = name
def area(self):
... | true |
d3b493be1b39b21439c671753ec38ef9043f688f | djreiss/AnalyzeSN | /analyzeSN/lightcurve.py | UTF-8 | 6,747 | 2.953125 | 3 | [
"MIT"
] | permissive | """
Class for holding Light Curve Data
"""
from __future__ import absolute_import, print_function, division
from future.utils import with_metaclass
import abc
import numpy as np
import pandas as pd
from astropy.table import Table
from .aliases import aliasDictionary
__all__ = ['BaseLightCurve', 'LightCurve']
class ... | true |
f2ab2e3d52641dc752d23fc025ddfed811003e23 | lguangyu/BioinformaticsUtilities | /silva_taxonomy_db.py | UTF-8 | 8,099 | 2.609375 | 3 | [
"MIT"
] | permissive | #!/usr/bin/env python3
################################################################################
# silva_taxonomy_export_reloader.py
################################################################################
# SYNOPSIS
# load SILVA exported taxonomy database to a searchable form
###########################... | true |
104b73a62e120cbee2d44bd9f3224ccc5aaddf73 | james-xi/gui-python-tkinter | /src/examples/crud_sqlachemy_with_frames/MainWindowFrame.py | UTF-8 | 892 | 3.0625 | 3 | [
"MIT"
] | permissive | # -*- coding: utf-8 -*-
"""."""
import tkinter as tk
class MainWindowFrame(tk.Frame):
def __init__(self, master=None):
super().__init__(master)
self.master = master
self.pack(expand=True, fill=tk.BOTH, padx=10, pady=10)
self.create_widgets()
def create_widgets(self):
... | true |
b3dd428fffe7a7ccad2fa3b1adcc2b9d237d8729 | IntroProgramacion-P-Oct20-Feb21/trabajofinal-1bim-KrissBustamante | /Taller6/taller6/taller6/problema2.py | UTF-8 | 315 | 3.3125 | 3 | [] | no_license | ##Se realiza una repeticion pra presentar en fraccion
contador1 = 1
contador2 = 10
contador3 = 20
while (contador1 <= 6):
if ((contador1 % 2) == 0):
print(contador1,"/", contador3)
contador3 = contador3 + 1
else:
print(contador1,"/", contador2)
contador2 = contador2 + 1
contador1 = contador1 + 1
| true |
9db369904b36c737cb1c5a8df67221b00c6253a9 | bbw7561135/fhee | /v01/analyse_data.py | UTF-8 | 1,250 | 3.078125 | 3 | [
"MIT",
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | # this analysis script finds the photons with the highest energy for the crab nebula from the 2FHL event list
from numpy import *
from astropy.io import fits
hdulist=fits.open('gll_psch_v08.fit.gz')
print hdulist.info()
datalist=hdulist[1] #hdu=1 is the source catalog, found using "ftlist" or "hdulist.info()"
... | true |
ae1b8f0d64c23c1606966429dbbc2c592c5c17ac | CinatitBR/exercicios-phyton | /exercicios/ex065.py | UTF-8 | 675 | 4.3125 | 4 | [
"MIT"
] | permissive | soma = 0 # Irá somar valores digitados
cont = 0 # Contará quantas vezes o laço rodou
maior = 0 # Armazena maior valor
menor = 0 # Armazena menor valor
op = '' # Onde o Usuário insere números e faz decisões
while 'N' not in op:
op = int(input('Digite um número: '))
soma += op
cont += 1
if cont == 1... | true |
00765f3484ae905963b15407d7746df5dad69aa7 | baileyp/advent-of-code-2020 | /tests/integration/day10_test.py | UTF-8 | 664 | 2.703125 | 3 | [] | no_license | import pytest
from io import StringIO
from aoc.solution import day10
from aoc.util import FileReader
INPUT1 = """16
10
15
5
1
11
7
19
6
12
4"""
INPUT2 = """28
33
18
42
31
14
46
20
48
47
24
23
49
45
19
38
39
11
1
32
25
35
8
17
7
9
4
2
34
10
3"""
@pytest.mark.parametrize('test_case, result', [
(INPUT1, 35),
... | true |
bec87d826e457f6400128d50300d7a9f275ac98f | FaithKoech/Python-Iterations | /IterationsAssigment.py | UTF-8 | 661 | 4.5625 | 5 | [] | no_license | # a.Write a program that prints your name 100 times.
i=0
while i<=100:
i = i + 1
print("Faith")
# b.Write a program that outputs 100 lines, numbered 1 to 100, each with your name on it. The output should look like the output below.
#
# 1 Your name
#
# 2 Your name
#
# 3 Your name
#
# 4 Your name
i =0
for i in... | true |
0289dea6706d56b8e4311584a33b578e10a23da5 | binna/study | /PythonWorkspace/basic/01_print.py | UTF-8 | 7,008 | 3.890625 | 4 | [] | no_license | # '#'으로 시작하면 한 줄 주석 => 컴파일러나 인터프리터가 번역하지 않는다.
# ''' 부터 ''' 사이에 코딩하면 범위 주석으로 지정할 수 있다.
# print() 함수는 ()안의 내용을 출력하고 줄을 바꾼다.
print("Hello Python")
print('안녕 파이썬')
print("제2외국어를 배운 호랑이가 '야옹' 했습니다.")
print('제2외국어를 배운 고양이가 "어흥" 했습니다.')
print("제2외국어를 배운 호랑이가 \"야옹\" 했습니다.")
print('제2외국어를 배운 고양이가 \'어흥\' 했습니다.')
# print() 함수로 ... | true |
e6a6ccbd458527a9cff1e7fe81090a187b40275a | lucy9215/leetcode-python | /434_numberOfSegmentsInAString.py | UTF-8 | 535 | 3.640625 | 4 | [] | no_license | class Solution(object):
def countSegments(self, s):
"""
:type s: str
:rtype: int
"""
# count = 0
# for i,v in enumerate(s):
# if v!=' ' and (i==0 or s[i-1]==' '):
# count+=1
count = len([i for i in s.split(' ') if i!=''])... | true |
901559f5901c73b9317cd0c5999b0ac2584b59fb | quochoantp/Project2 | /PythonBTCoBan/2.6.py | UTF-8 | 211 | 3.328125 | 3 | [] | no_license | list = []
print("Nhap n:")
n = int(input())
for i in range(n):
list.append(int(input()))
print("Nhap k:")
k = int(input())
if k >= n:
print("k khong hop le")
else:
list.remove(list[k-1])
print(list)
| true |
b1f25d8777185dbf9f344c88593b517e0e62a57f | sugarfrosted/register-machine | /programs.py | UTF-8 | 1,649 | 2.78125 | 3 | [] | no_license | # -*- coding: utf-8 -*-
from collections import defaultdict
def subtractor(R_0=0, R_1=1, R_2=2, shift=0, output = True):
program = [["jump" , R_1, {"□": 4, "a": 1}],
["append", R_0, "a"],
["remove", R_1, "a"],
["jump" , R_0, {"□": 0, "a": 0,}],
["remove", R_2, "a"],
["jump"... | true |
6ba8758f854313ea81a39e23ffe33deafb540a14 | marcellass/Exercicios-de-Python-Curso-em-Video-Mundo1 | /exercicios/ex031.py | UTF-8 | 187 | 3.546875 | 4 | [
"MIT"
] | permissive | distancia = int(input('Digite a distância: '))
if distancia <= 200:
preco = 0.50 * distancia
else:
preco = 0.45 * distancia
print(f'Sua passagem deu um total de R${preco:.2f}') | true |
4474b163c4130e7d5b91a418fc802e85707196c1 | alpha-kwhn/Baekjun | /GONASOO/11651.py | UTF-8 | 141 | 3.125 | 3 | [] | no_license | yx = []
for _ in range(int(input())):
yx.append(list(reversed(list(map(int,input().split())))))
for i in sorted(yx): print(i[1], i[0]) | true |
7d0f52514987c2b4295aaeb5f3edfbc176032e2a | connie-liou/powersimstore | /Graphing.py | UTF-8 | 14,324 | 2.65625 | 3 | [] | no_license | import sys
sys.path.append("/classes/")
from classes.Battery import *
from classes.Solar import *
import time
import plotly.graph_objs as go
'''
Returns blank graphs for when the program initially starts
'''
'''
These functions extract data from battery and solar array to generate the graph data and layou... | true |
a26b12150407753f6e49c890b304d3b98223747f | AnKra/deep-reinforcement-learning | /p1_navigation/cnn_model.py | UTF-8 | 2,718 | 3 | 3 | [
"MIT"
] | permissive | import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
def hidden_init(layer):
fan_in = layer.weight.data.size()[0]
lim = 1. / np.sqrt(fan_in)
return (-lim, lim)
class CNNNetwork(nn.Module):
"""Actor (Policy) Model."""
last_conv_layer_size = 16
conv_output_size ... | true |
330c4b2932ebec42f39255d96751ebf833566d64 | ub-wroteIt/greyatom-python-for-data-science | /numpy-101/code.py | UTF-8 | 1,607 | 3.234375 | 3 | [
"MIT"
] | permissive | # --------------
# Importing header files
import numpy as np
# Path of the file has been stored in variable called 'path'
data = np.genfromtxt(path,delimiter=",",skip_header=1)
print(data)
#New record
new_record=[[50, 9, 4, 1, 0, 0, 40, 0]]
census = np.concatenate((data,new_record))
print(census)
#Code... | true |
2b62f3ff4a255562c00e52c2b07c6dce76addd66 | Ranjana151/Machine_learning | /malaria_predication.py | UTF-8 | 620 | 2.71875 | 3 | [] | no_license | import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier,AdaBoostClassifier
from sklearn import metrics
import joblib
df=pd.read_csv("dataset.csv")
print(df.head())
x=df.drop(['Label'],axis=1)
y=df["Label"]
x_train,x_test,y_train,y_test=... | true |
1bc0269aeafd5c8cfbcacafda2ae4aa03f60c993 | davidfbpereira/pws_repo | /querying/scripts/querier.py | UTF-8 | 1,066 | 2.828125 | 3 | [] | no_license |
# Input: 1) it requires the presence of the sampled .txt files in the following directory: ../../sampling/samples/
# and 2) requires the existence of the following directory: ../results/
# Main function: to query all samples into a new .txt file with a predefined format
# Output: .txt file with the following format:... | true |
799befad5be43cb0970ffd3ca6e483a50a53e9b3 | opendatadurban/citizen_sensors | /Weather_Station/gas_test.py | UTF-8 | 551 | 2.6875 | 3 | [
"Apache-2.0"
] | permissive | import spidev
import RPi.GPIO as GPIO
def readadc(pin):
if ((pin > 7) or (pin < 0)):
return -1
r = spi.xfer2([1,(8+pin)<<4,0])
adcout = ((r[1]&3) << 8) + r[2]
return adcout
def readMQ135(mq135Pin):
gas_array = []
for i in range(10):
mq135_reading = readadc(mq135Pin)
gas_... | true |
1fbdbf0620311bd8957c8d8b2918a4cd67310fdf | maciejszulia/python-uwm | /praca-domowa-1-wstęp/zad_lab_9.py | UTF-8 | 282 | 3.578125 | 4 | [] | no_license | #Zad.9 Napisz skrypt, w którym zadeklarujesz zmienne typu:
# string, float i szestnastkowe.
# Następnie wyświetl je wykorzystując odpowiednie formatowanie.
#MACIEJ SZULIA 154733
my_string = 'string'
my_float = 3.333
my_hex = hex(99999)
print(my_string)
print(my_float)
print(my_hex) | true |
d968d712bc95746bc57c37530ea65fb36b40dcfa | SakinaGadri/Python | /Basic Python - Classes/ex8/ex8.py | UTF-8 | 4,633 | 4.28125 | 4 | [] | no_license | class LightSwitch:
'''This is a class for a light switch'''
def __init__(self, switch_state):
''' (LightSwitch, str) -> NoneType
Returns None and assigns the input parameters to class variables
REQ: switch_state can only be 'on' and 'off'
'''
# assign the input parameters... | true |
d162a892aae638ab83d47d3a776099f97dd22e35 | nayulbak1/TIL | /07_swea/1936.py | UTF-8 | 399 | 3.015625 | 3 | [] | no_license | import sys; sys.stdin=open("1936.txt","r")
def winner(A, B):
if A == 1 and B == 2 :
print('B')
if A == 2 and B == 3 :
print('B')
if A == 3 and B == 1 :
print('B')
if A == 2 and B == 1 :
print('A')
if A == 3 and B == 2 :
print('A')
if A == 1 and B ==... | true |
8ea961cea455d97c9798454f9b57fdeeb5096e11 | lefttree/deep_learning_foundation | /multilayer-perceptron/multi_tensorflow.py | UTF-8 | 1,806 | 2.765625 | 3 | [
"MIT"
] | permissive | from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets(".", one_hot=True, reshape=False)
import tensorflow as tf
#parameters
learning_rate = 0.001
training_epochs = 20
batch_size = 128
display_step = 1
n_input = 784
n_classes = 10
n_hidden_layer = 256 # layer number of features... | true |
bb8b705970bf29e1614bf7e3f74349022ed5a51a | chelseajohn/PhysicsProjects | /mechanics/mercury_b.py | UTF-8 | 2,069 | 3.015625 | 3 | [] | no_license |
from pylab import*
import math
e = 0.2056
thet = 58.98/300000.0
theta = math.pow(thet,2)
time = 0.0
end_time = 100000.0
delta_t = 0.01
N = int(end_time/delta_t)
x = 1.0
y = 0.0
initial_v_x = 0.0
initial_v_y = 1.0
a_x = -x/(math.pow(x*x + y*y,1.5)*(1+e)) - (3*x*theta)/(math.pow(x*x + y*y,2.5)*(1+e... | true |
983ebf8d4eb83d1ecea3e7774aad10f20d5f4967 | MrHamdulay/csc3-capstone | /examples/data/Assignment_5/mrcaye002/question2.py | UTF-8 | 1,250 | 4.03125 | 4 | [] | no_license | """Program to simulate a vending machine and calculate change
Ayesha Marcus
15/04/2014"""
import math
def getChange( change, denomination, denominationLabel ):
#deduct denomination from change 250 in
val=math.floor(change/denomination) # = 200
# if cash deducted display it
if val > 0:
print (val... | true |
9cfa4524583a48577c42d57bc32c4f8772209e89 | chandramgc/fastapi-snippet | /src/core/logger.py | UTF-8 | 585 | 2.703125 | 3 | [] | no_license | import logging
def setLogger(logName,logLevel):
# create console handler and set level to debug
handler = logging.StreamHandler()
# create formatter
#formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
formatter = logging.Formatter('%(asctime)s - %(levelname)s - ... | true |
afdb7993ac26246087b3f79831e3d8ab0f42f12a | philwilliammee/ax12a_test_acceleration | /Ports.py | UTF-8 | 1,900 | 2.921875 | 3 | [
"LicenseRef-scancode-warranty-disclaimer"
] | no_license | '''
Created on Nov 18, 2013
@author: philwilliammee
make sure user is a member of dialout
sudo usermod -a -G tty yourUserName
sudo usermod -a -G dialout username
Log off and log on again for the changes to take effect!
'''
import serial
import os
import stat
import getpass
s = serial.Serial() # create ... | true |
fca40dfede17b273d217617815fbd3714acba71a | wcrwcr/py_sh_tray | /lib/sys_low_level/lol_client_api.py | UTF-8 | 1,477 | 2.640625 | 3 | [] | no_license | import requests as http
from requests.auth import HTTPBasicAuth
from lib import client_checker
from requests.packages.urllib3.exceptions import InsecureRequestWarning
http.packages.urllib3.disable_warnings(InsecureRequestWarning)
class Error(Exception):
pass
class ApiNotReady(Error):
pass
#def __init__... | true |
bcf39182ded670c02b8a1ebb40b3817e754a5a41 | Aasthaengg/IBMdataset | /Python_codes/p03435/s836314704.py | UTF-8 | 493 | 2.96875 | 3 | [] | no_license |
def main():
c11, c12, c13 = map(int, input().split())
c21, c22, c23 = map(int, input().split())
c31, c32, c33 = map(int, input().split())
for a1 in range(-200, 200):
b1 = c11 - a1
b2 = c12 - a1
b3 = c13 - a1
a2 = c21 - b1
a3 = c31 - b1
if c22 == a2 +... | true |
c48c4c980e0f1250d890c74ba997873cd259c976 | MaheshValiveti/Code-Challenges | /Exercise.py | UTF-8 | 2,129 | 2.734375 | 3 | [] | no_license | # -*- coding: utf-8 -*-
"""
Created on Wed Mar 6 21:44:45 2019
@author: Mahesh
"""
#%%
import csv
import phonenumbers
import pandas as pd
import tldextract
import psycopg2
#create Contacts data frame
File = "company_contacts.csv"
try:
with open (File,'r') as f:
reader = csv.reader(f)
... | true |
3f33cccb89e97dbc04c5584f20d87c9ba1c44fb2 | shoppimon/figcan | /tests/test_mapping_iface.py | UTF-8 | 2,003 | 2.75 | 3 | [
"Apache-2.0"
] | permissive | """Figcan tests - test mapping interface access
"""
# Copyright (c) 2018 Shoppimon LTD
#
# 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
#
# Un... | true |
e6158e72ed862faf3159de1fed2a5b2e757e4f97 | theamazingmrb/brew-good-backend | /resources/users.py | UTF-8 | 2,481 | 2.78125 | 3 | [] | no_license | import models
from flask import Blueprint, jsonify, request
from playhouse.shortcuts import model_to_dict
from flask_bcrypt import generate_password_hash, check_password_hash
from flask_login import login_user, logout_user, current_user
users = Blueprint("users", "users")
# register route
@users.route('/register', m... | true |
58260a940df9ec730effdd4dd08d777e41f7d480 | Nikkuniku/AtcoderProgramming | /AGC/AGC043/a.py | UTF-8 | 908 | 2.78125 | 3 | [] | no_license | from collections import deque
h, w = map(int, input().split())
grid = []
for _ in range(h):
grid.append(input())
q = deque()
INF = 1000
ans = [[INF]*w for _ in range(h)]
dx = [0, 1]
dy = [1, 0]
isBlack = False
if grid[0][0] == '.':
ans[0][0] = 0
else:
ans[0][0] = 1
isBrack = True
q.append((0, 0))
while... | true |
b16e034d2c62e6678f3c1eed6bc608e4dd2ad228 | lei-wang-/MyResearch | /overlap_mat.py | UTF-8 | 1,192 | 2.65625 | 3 | [] | no_license | from numpy import *
import re
set_printoptions(threshold=nan)
class overlap_mat(object):
"""a class to extract the overlap matrix S"""
def __init__(self, string, nbf):
self.regEX = "1eov\s+(\d+)\s+\w+\s+\w+\s+(\d+)\s+\w+\s+\w+\s+(-?\d+\.\d+)(\s+)?"
self.overlap = zeros([nbf,nbf],float64)
... | true |
683f2b0d6787fecf03a688cb19fb2b6ba8e750f2 | ralienpp/advice-fortune | /advice/spiders/advice_spider.py | UTF-8 | 1,549 | 2.734375 | 3 | [] | no_license | import scrapy
from scrapy.spiders import CrawlSpider, Rule
from scrapy.linkextractors import LinkExtractor
from advice.items import AdviceItem
class AdviceSpider(CrawlSpider):
name = 'advice'
allowed_domains = ['fucking-great-advice.ru']
start_urls = ['http://fucking-great-advice.ru/advice/1/']
url_... | true |
c4d070d30d24b5a4810b47a01dc3f3ad18de75f7 | vikassable/Frequent-Itemset-Mining-using-Hadoop-MapReduce-framework | /3itemsets_step3_reducer.py | UTF-8 | 1,301 | 3.171875 | 3 | [] | no_license | #!/usr/bin/env python
import sys
current_item_1 = None
current_item_2 = None
current_item_3 = None
current_count = 0
item_1 = None
item_2 = None
item_3 = None
# input comes from STDIN
for line in sys.stdin:
# remove leading and trailing whitespace
line = line.strip()
# parse the input we got from mapper.py
item... | true |
0ac92080001197e6221773db91b3ba127703a795 | sagarbhalke888/gluon-cv | /docs/tutorials/action_recognition/demo_ucf101.py | UTF-8 | 3,380 | 3.28125 | 3 | [
"Apache-2.0"
] | permissive | """1. Getting Started with Pre-trained TSN Model on UCF101
======================================================
`UCF101 <https://www.crcv.ucf.edu/data/UCF101.php>`_ is an action recognition dataset
of realistic action videos, collected from YouTube. With 13,320 short trimmed videos
from 101 action categories, it is... | true |
ae0934dded0807267d4265f23c7e8c2a600fc064 | fanren5599/LeNet | /test.py | UTF-8 | 828 | 2.578125 | 3 | [] | no_license | import torch
import torch.nn as nn
from model import LeNet
from data import data_train_loader,data_test_loader
model_path="./model_save/model.pth"
save_info=torch.load(model_path)
model=LeNet()
criterion=nn.CrossEntropyLoss()
model.load_state_dict(save_info["model"]) #载入模型参数
model.eval() #切换模型到测试状态
test_loss=0
corre... | true |
504fe030cd2f864a1b2065eae89aaf26790618c7 | wangerde/codewars | /tests/python2/kyu_6/test_square_divisors.py | UTF-8 | 482 | 3.25 | 3 | [] | no_license | # pylint: disable=missing-docstring
"""Integers: Recreation One"""
import pytest
from python2.kyu_6.square_divisors import list_squared
EXAMPLES = (
('start', 'stop', 'expected'),
[
(1, 250, [[1, 1], [42, 2500], [246, 84100]]),
(42, 250, [[42, 2500], [246, 84100]]),
(250, 500, [[287,... | true |
7c74f6bf5e0bfc7f922992e4bf6a6a3b5fe5fe32 | manhdan226/multiprocess_with_pulsar | /book.py | UTF-8 | 1,989 | 2.765625 | 3 | [] | no_license | import boto3
import pulsar
import json
dynamodb = boto3.resource('dynamodb', endpoint_url = "http://localhost:4566")
table = dynamodb.Table('Popo.books')
client = pulsar.Client('pulsar://localhost:6650')
consumer = client.subscribe('Popo.category_book', 'my-subscription')
def list_of_books(category):
#print("---... | true |
adbdc4ea288b8aadf220661d5e7d32f5547c9eed | paulpmi/Inference-Tree-Finding-The-Most-Costly-Path | /12AI-Lab2.py | UTF-8 | 9,265 | 3.078125 | 3 | [] | no_license | import random
from copy import deepcopy
class Controller:
def __init__(self, n):
self.n = n
self.size = n*(n+1)/2
self.instance = Problem(n)
#self.currentState = self.createM()
def getMatrix(self):
return self.instance.getMatrix()
def printMatrix(self):
for... | true |
5019337ae9f7aa4094c04a60d4b245643b00ec78 | Littlesnowman88/TowerDefenseGame | /InvaderClasses.py | UTF-8 | 20,467 | 2.53125 | 3 | [] | no_license | from tkinter import PhotoImage
from ShapeRendering import *
from MoveBehavior import *
from WaveManager import *
from HomeBase import *
from TargetMediator import *
from ProjectileClasses import *
from Subject_Observer import Subject, Observer
import types, random
from TowerClasses import AbstractTower
###############... | true |
ce118693d3be5accf3ebf427b2b1cdad88b5c5d1 | edstott/cat | /src/servotest.py | UTF-8 | 524 | 2.859375 | 3 | [] | no_license | import RPi.GPIO as GPIO
import time
PERIOD = 0.02
SLEEP = 0.1
MIN_PRD = 0.0007
MAX_PRD = 0.0024
try:
GPIO.setmode(GPIO.BCM)
GPIO.setup(18,GPIO.OUT)
pwm = GPIO.PWM(18,1/PERIOD)
Dir = 1
Angle = 0
DC = (MIN_PRD+(MAX_PRD-MIN_PRD)*Angle)/PERIOD
pwm.start(DC)
while True:
if Dir:
Angle += 0.01
if Angle >= ... | true |
899701d79c4d1d6794d979afea7220696c6621b2 | ScottMWong/UoM-COMP30024-Project | /Tronity.py | UTF-8 | 54,456 | 2.6875 | 3 | [] | no_license | from collections import defaultdict as dd
import numpy as np
import random
import math
class Player:
def __init__(self, player):
self.team = player
self.coord_dict, self.piece_dict = getEmptyBoardConfigs()
self.upper_thrown_num = 0
self.lower_thrown_num = 0
sel... | true |
c946512494510a343a6911bffd95d174575e49ab | huggingface/simulate | /src/simulate/assets/procgen/wfc/build_map.py | UTF-8 | 5,241 | 2.8125 | 3 | [
"Apache-2.0"
] | permissive | """
Builds map using Wave Function Collapse.
"""
from typing import List, Optional, Tuple
import numpy as np
from ..constants import TILE_SIZE
from .wfc_utils import generate_seed
from .wfc_wrapping import apply_wfc
def generate_2d_map(
width: int,
height: int,
periodic_output: bool = True,
N: int ... | true |
8a2274aa4ede0e19ed269a08e85fbab227cf7998 | Timjaris/A-Bunch-of-Miscellaneous-Programs | /Chad....py | UTF-8 | 49 | 3.0625 | 3 | [] | no_license | for i in range(30, 50):
print "Chad" + "."*i
| true |
4d4c727d8c6d9c96860ef785d4286eb2d1d89d7c | Stanford-BIS/pystorm | /pystorm/test/test_hal_io.py | UTF-8 | 2,328 | 2.78125 | 3 | [
"MIT"
] | permissive | """Test whether we can inject and tags and loop them back"""
import time
import numpy as np
from pystorm.hal import HAL
from pystorm.hal.neuromorph import graph # to describe HAL/neuromorph network
DIM = 1 # 1 dimensional
RATE = 10000 # rate of input spikes
WEIGHT = 1 # weight of connection from input to output
REL_E... | true |
ae72ffee6f855a4002012294db08cd373586d139 | zhang4ever/target_offer | /ConstructBinaryTree.py | UTF-8 | 3,546 | 4 | 4 | [] | no_license | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
# @File : ContructBinaryTree.py
# @Time : 2018-03-24 21:52
# @Author : zhang bo
# @Note :
"""
'''
描述:输入某二叉树的前序遍历要和中序遍历,。请重构出该二叉树。假设输入的前序和中序的结果都不含重复的数字。
思路:先根据前序的第一个数字确定头结点,然后根据中序遍历确定头结点的位置,从而确定左右子树的数量,然后使用递归的思想。
'''
class TreeNode:
def __init__(self, x):... | true |
01056aa4a2c896c927e3f18f4628177be3f819e2 | GANESH0080/Python-Scripts | /DoWhileOne.py | UTF-8 | 99 | 3.75 | 4 | [] | no_license | num = 1
while True:
print("Numbers are : " ,num)
num =num+1
if(num > 5):
break
| true |
0f025226ae31f65afdce71f564fa553a1fbfacf5 | arieldelga/learning-python | /prueba_exept2.py | UTF-8 | 356 | 3.953125 | 4 | [] | no_license | def dividir():
try:
num1 = float(input("Introduzca el primer número: "))
num2 = float(input("Introduzca el segundo número: "))
print("El resultado es" + str(num1/num2) + ".")
except ValueError:
print("Valor incorrecto.")
except ZeroDivisionError:
print("No se puede dividir entre cero.")
finally:
print("... | true |
caf559cf84f051996658ee9ef45adbb88b283b01 | WeAreHus/StudyRecord | /day-2018-10-21/xjh_xianxinghuigui/trainingxian.py | UTF-8 | 1,987 | 3.1875 | 3 | [] | no_license | # -*- coding: utf-8 -*-
# 预测LebronJames近三个赛季出手次数和得分之间的关系
import tensorflow as tf
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# 读取数据
train = pd.read_csv("/home/xiang/mygit/学习记录和随笔/AI/james.csv")
# 定义参数
train = train[train['shoot'] < 12000]
train_X = train['shoot'].values.reshape(-1,1)
train_Y... | true |
a252ab2da729c731c0831dd397cdb69a191eec1d | yuly3/atcoder | /ABC/ABC174/B.py | UTF-8 | 330 | 2.875 | 3 | [] | no_license | import sys
sys.setrecursionlimit(10 ** 7)
rl = sys.stdin.readline
def solve():
N, D = map(int, rl().split())
XY = [list(map(int, rl().split())) for _ in range(N)]
ans = 0
for x, y in XY:
if (x ** 2 + y ** 2) ** 0.5 <= D:
ans += 1
print(ans)
if __name__ == '__main__':
... | true |
cf810c4d06f778baadcdc6c282adf8ce42cd4c22 | mshekhar/random-algs | /epi_solutions/dynamic_prog/unique-substrings-in-wraparound-string.py | UTF-8 | 1,561 | 3.140625 | 3 | [] | no_license | class Solution(object):
def is_cts_char(self, x1, x2):
# print 'is_cts_char', x1, x2
if ord(x2) - ord(x1) == 1:
return True
elif ord(x1) - ord(x2) == 25:
return True
return False
def findSubstringInWraproundString(self, p):
"""
:type p: st... | true |
234423c08a0eaeb37e29e7846466500c277bd79a | EricSchles/anti-trafficking-tools | /modeling_code/features.py | UTF-8 | 8,625 | 2.921875 | 3 | [] | no_license | # -*- coding: utf-8 -*-
from nltk.tag.stanford import StanfordPOSTagger
from nltk.tokenize.stanford import StanfordTokenizer
import re
import pandas
import numpy
import itertools
from values import Values
import math
from sklearn import linear_model
import os
#initializes with two value vectors (one from each ad). cal... | true |
08e34140e2058f6849abe6c9e46b9d8ccbec8eec | vaad2/hands_tests | /task2.py | UTF-8 | 781 | 3.09375 | 3 | [] | no_license | import ujson
# case 1 simple values
arr = ['hello', 2, 3.21, 2, 'hello', 'Hello']
print(arr := list(set(arr)))
# case 2 dicts and None
arr = [
None,
'hello',
2, 3.20, 3.2, 3.2099999999999, 2, 'hello',
{'a': {'v': 2, 'a': 3}},
{'m': {'kk': 2}, 'z': [1, 3, 'aaa']},
{'a': {'v': 2, 'a': 3}},
{... | true |
7e2e17da88a910fe5380a3b59f8ec10e29156e87 | FabioCostaR/aprendendoPYTHON | /Desafio101.py | UTF-8 | 1,000 | 4.40625 | 4 | [] | no_license | # Crie um programa que tenha uma função chamada voto() que vai receber como parametro
# o ano de nascimento de uma pessoa, retornado um valor literal indicando se uma pessoa
# tem voto NEGADO, OPCIONAL ou OBRIGATÓRIO nas eleições.
def voto(ano):
"""
-> Faz o calculo da situação de voto
:param ano: ent... | true |
3a73396c9e06bea1d23de846354893b967c9ccac | VZRXS/LeetCode-noob-solutions | /Easy/160_Intersection_of_Two_Linked_Lists.py | UTF-8 | 2,540 | 3.671875 | 4 | [] | no_license | #!/usr/bin/env python3
from sys import path
path.append('.')
from utils.linked_list_utils import LinkedList, ListNode
class Solution(object):
# 160. Intersection of Two Linked Lists
def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
# OVERTIME
curA = headA
cu... | true |
bf19a90fd27b00c727c17f49cb36f5ea40096728 | UA-SOlsen/pentesting-tools | /discover_hosts.py | UTF-8 | 1,716 | 3.015625 | 3 | [] | no_license | import requests
import time
import re
url = ''
def get_content_length():
resp = requests.get(url)
if resp.status_code == 200:
return resp.headers['content-length']
return -1
def bf_hosts(path):
host_file = open(path, 'r')
main_length = get_content_length()
skip = 'N'
old_host = ''... | true |
3f9308ccec06fb981f2370e6d4b7311c691ba023 | weimingtom/kws_game | /game/input_handler.py | UTF-8 | 2,149 | 3.234375 | 3 | [] | no_license | """
input handler class
"""
import pygame
class InputHandler():
"""
Input Handler class
"""
def __init__(self, obj, grid_move=False):
# object to be handled
self.obj = obj
# grid handling
self.grid_move = grid_move
def handle(self, event):
"""
handle object
"""
pass
class InputKeyHandler... | true |
d6f83cc5079a670ed65d1510dd6e4439d9710804 | gaelwjl/Leetcode-Solution | /solutions/1732-minimum-one-bit-operations-to-make-integers-zero/minimum-one-bit-operations-to-make-integers-zero.py | UTF-8 | 1,634 | 3.703125 | 4 | [] | no_license | # Given an integer n, you must transform it into 0 using the following operations any number of times:
#
#
# Change the rightmost (0th) bit in the binary representation of n.
# Change the ith bit in the binary representation of n if the (i-1)th bit is set to 1 and the (i-2)th through 0th bits are set to 0.
#
#
# Retu... | true |
6e805928306adcb886794ace4b9a1aa573a28c63 | Cavtheman/skolearbejde | /numintro/week4/Q0020.py | UTF-8 | 3,162 | 3.8125 | 4 | [] | no_license | import numpy as np
import auto_test_tools as att
from math import exp, sin
import math
import matplotlib.pyplot as plt
'''
First implement the f-function defined by
f(x)= exp(x)-sin(x) closest to zero.
Second implement the Secant method on page 95 and use it
to find the root of the f-function given x0 = -... | true |
1ba2a3d5fdc1776840095fec571086f17c1a5bac | filippoboiani/machine-learning | /dectrees/python/inform_gain.py | UTF-8 | 565 | 2.765625 | 3 | [] | no_license | import monkdata as m
import dtree as dtree
datasets = [{
'name': 'monk1',
'ref' : m.monk1
},
{
'name': 'monk2',
'ref' : m.monk2
},
{
'name': 'monk3',
'ref' : m.monk3
}]
print "Sample class: " + m.Sample.__doc__
# TODO:
# print dtree.averageGain... | true |
6fd74eb006e56ae4d964591ee1bd7a6a489d0f75 | SergioCancinos/Proyecto-IoT | /src/iot/finalv3.py | ISO-8859-1 | 2,501 | 3.09375 | 3 | [] | no_license | #!/usr/bin/python
# Universidad del Valle de Guatemala
# Angel Basegoda 13256
# Erick Hernndez Woc 13197
# Johnny del Cid 13032
# Sergio Cancinos 13062
# final.py
# El programa utiliza el sensor PIR para mandar mensajes a twitter cada vez que el sensor indique que hubo movimiento.
# Permite que solamente se manden ... | true |
4360d73f64f33922a5d3b0a2c36fea8759f393b5 | Rajiramu97/Detecting-phishing-websites | /index.py | UTF-8 | 494 | 2.6875 | 3 | [] | no_license | # -*- coding: utf-8 -*-
#importing libraries
from sklearn.externals import joblib
import warnings
import inputScript
warnings.filterwarnings('ignore')
#load the pickle file
classifier = joblib.load('final_models/svm_final.pkl')
#input url
print("enter url")
url = input()
#checking and predicting
checkprediction = i... | true |
f8f518d10103b7b26bdd654243ccf2815e6b7bc7 | Natim/Thumbnailer | /src/thumbnailer.core/thumbnailer/cache/__init__.py | UTF-8 | 759 | 2.6875 | 3 | [] | no_license | # -*- coding: utf-8 -*-
"""Read and URL and get the file from cache if possible or update the file."""
import hashlib
import settings
import os
import pickle
THUMB_CACHE_DIR = getattr(settings, 'THUMB_CACHE_DIR', '/tmp')
def get_thumb_path_for_kwargs(**kwargs):
"""Return the cache file path for url"""
dumps =... | true |
c7af9a8d360e1733e7418a8624cdcb3bb0ce8fbb | Shuyangzero/LearnedIndexesBloomFilter | /Run.py | UTF-8 | 2,256 | 2.796875 | 3 | [] | no_license | from Utils import *
from DataLoader import CharDataset
from torch.utils.data import DataLoader
import json
from GRUModel import GRUModel
from tqdm import tqdm
from tqdm import trange
import torch
from torch import nn
def train(model, train_dataloader, lr=0.001):
optimizer = torch.optim.Adam(
filter(lambda... | true |
b2ce49661d498e4713aec5a225d251821d764454 | hopeqpy/Python000-class01 | /Week_04/G20200389010058/work04.py | UTF-8 | 1,133 | 3.265625 | 3 | [] | no_license | import pandas as pd
data = [
# id name age
[1, 'ABC', 12],
[2, 'ABC', 23],
[3, 'ABC', 14],
[4, 'ABC', 43],
[5, 'ABC', 17],
[6, 'ABC', 31],
[7, 'ABC', 56],
[8, 'ABC', 12],
[9, 'ABC', 45],
[10, 'ABC', 9],
[11, 'ABC', 75],
]
# select * from data
df = pd.DataFrame(data)
df.c... | true |
18436da7b3dc361ed43ae8f75ed2cd372908888a | linfeng521/arm_4dof | /algorithm/3dof_v2/main.py | UTF-8 | 2,009 | 3 | 3 | [] | no_license | import numpy as np
from numpy import pi
class Arm(object):
def __init__(self,q = None,q0=None, L=None):
# initial joint angles
self.q = [.3, .3, 0] if q is None else q
# some default arm positions
self.q0 = np.array([np.pi / 4, np.pi / 4, np.pi / 4]) if q0 is None else q0
... | true |
98a88ce86494d313a4e4bc5190c3a676048347f5 | marsming/python_basic | /study/fileOperations/com/ctyun/shutl/修改文件名日期.py | UTF-8 | 1,261 | 2.859375 | 3 | [] | no_license | import os,shutil,re
import logging
logging.basicConfig(level=logging.DEBUG, format=' %(asctime)s - %(levelname)s - %(message)s')
logging.debug('Start of program')
'''
为美国风格的日期创建一个正则表达式
MM-DD-YYYY
'''
if __name__ == '__main__':
datePattern = re.compile(r'''
^(.*?) #任意字符串开头
((0|1)?\d)- #一个或两个数... | true |
4aba05c5888492827248d43f5eed98ff92895de3 | zhanglulu15/python-machine-study | /RELU.py | UTF-8 | 275 | 2.96875 | 3 | [] | no_license | import math
import matplotlib as plt
def sigmoid(x, derivate=False):
if derivate:
return sigmoid(x) * (1 - sigmoid(x))
return 1.0 / (1 + math.exp(-x))
print(sigmoid(8))
def relu(x):
if x > 0:
return x
else:
return 0
print(relu(8))
| true |
fd0081d2ea5c2138a88f6c970bd03978d6f42f89 | lionicsheriff/literate-dotfiles | /publishDotfile.py | UTF-8 | 4,218 | 2.796875 | 3 | [] | no_license | import os
import platform
## Set up menu item
WIKIDPAD_PLUGIN = (("MenuModifier", 1), ("MenuItemProvider", 1))
ID_CMD_PUBLISHCONFIG = "menuItem/editor/textArea/plugin/publishConfigContext/publishCurrent"
def modifyMenuV01(contextName, contextDict, menu):
if contextName == "contextMenu/editor/textArea":
... | true |
624b6eedee9e9ec33200c485f877fec5802ed80b | samidhaliwal/darkcurrent | /Parse/MakeDC_acq/MakeDCimageFromOrigACQ.py | UTF-8 | 7,589 | 2.84375 | 3 | [] | no_license | #!/usr/local/bin/python
import math
from itertools import islice
from collections import Counter
class AnalyzeFile():
def __init__(self, filename):
self.filename = filename
self.fi_name = '/Users/dhaliwal/Work/Alignment/DarkCurrent/acqidfiles_DC/'+filename+'.acq'
self.fo_name = '/Users/dhal... | true |
4eb2cc88364ae999de5af8de79792b995d1147b4 | fawadkhanf3/DDW-MaxRS | /exact/hline.py | UTF-8 | 299 | 2.8125 | 3 | [] | no_license | class HLine:
def __init__(self, y, inv):
self.y = y
self.maxInv = inv
def getY(self):
return self.y
def getMaxInv(self):
return self.maxInv
def size(self):
return HLine.size
def __str__(self):
return f'{self.y} {self.maxInv}'
| true |
af24a456a13383e303454dfae925c00a44023df7 | bsipin20/pragmatic | /yaml_to_json.py | UTF-8 | 370 | 2.953125 | 3 | [] | no_license | import yaml
import os
# Set the directory you want to start from
rootDir = 'yaml_files'
for dirName, subdirList, fileList in os.walk(rootDir):
print('Found directory: %s' % dirName)
for fname in fileList:
file_ = rootDir + "/" + fname
with open(file_,"r") as fh:
data = yaml.load(fh,... | true |
be17747c568927adfce6c86e7b6feabcf931396c | viki760/An-Information-theoretic-Metric-of-Transferability | /validate_transferability/H-score_target_task_selection.py | UTF-8 | 2,313 | 2.609375 | 3 | [
"MIT"
] | permissive | """
This file is for showing the relationship between transferability and transfer performance under the scenario of target task selection.
"""
import numpy as np
import matplotlib.pyplot as plt
score_p = np.load('../outputs/score_p.npy')
trn_loss_p = np.load('../outputs/trn_loss_p.npy')
trn_accs_p = np.load('../outpu... | true |
06d1049ac9cc8b2c6d60cd44d3e015ad2964ec95 | zzz686970/leetcode-2018 | /57_insert.py | UTF-8 | 585 | 3.4375 | 3 | [] | no_license | from typing import List
import bisect
def insert(intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]:
bisect.insort(intervals, newInterval)
res = [intervals[0]]
for el in intervals:
if el[0] > res[-1][1]:
res.append(el)
else:
# res[-1][0] = min(el... | true |
9fab4bce3af4732f777b7f722471abcf4ab59c31 | NastyaSavina/IBA_courses | /HW_4/4_3hw.py | UTF-8 | 231 | 2.6875 | 3 | [] | no_license | import unittest
import conc
class MyTestCase(unittest.TestCase):
def test_concatenation(self):
self.assertEqual(conc.concatenation(35, 21), 3521) # add assertion here
if __name__ == '__main__':
unittest.main()
| true |
6089864f2c93e0ae5e9b8e3e78a5480088e16463 | carrieb/scratch | /crawler/ffprocessor.py | UTF-8 | 1,025 | 2.703125 | 3 | [] | no_license | import json
import sys
def compile():
queue = []
counter = 0
LIMIT = 10000
compiled_file = open('compiled_fanfic.json', 'w+')
compiled_file.write('[')
total_len = 0
while (counter < LIMIT):
print "File #" + str(counter)
json_data = open('data/fanfic_data_'+str(counter)+'.json')
data = json_data.read()
i... | true |
04b9b41464212fc78fa89852bcfc314adeb6fca4 | flenters/python | /remove_empty_lines.py | UTF-8 | 201 | 2.890625 | 3 | [] | no_license | def removeEmptyLines():
with open("file1.txt", 'r') as inp, open('file2.txt', 'w') as out:
for line in inp:
if line.strip():
out.write(line)
removeEmptyLines()
| true |
cf4b71ee08421ed6877d32ca213f5d412f8717f7 | BillZong/CorePythonProgrammingDemos | /5/demo5.1.py | UTF-8 | 388 | 3.40625 | 3 | [
"MIT"
] | permissive | #!/usr/bin/env python
"""Number tests."""
a = 0
print id(a)
del a
print repr(123432342342343234234)
print str(123432342342343234234)
print repr(2 << 32)
print repr(2 << 64)
print repr(2 << 128)
aComplex = -38.2 - 1.234j
print aComplex
print aComplex.conjugate()
print aComplex.real
print aComplex.imag
print 5.52 ... | true |
0f3f0fefc1ce9898c1a721ff81284e07dd83071e | Ay00la/Data-Modeling-with-Apache-Cassandra | /script.py | UTF-8 | 4,907 | 2.640625 | 3 | [] | no_license | import pandas as pd
import os
import glob
import csv
from helpers import create_row_list, write_output_csv
from db.cdb import local_cassandra, execute_query, set_ks
# checking current working directory
print(os.getcwd())
# Get your current folder and subfolder event data
filepath = os.getcwd() + '/event_data'
# Crea... | true |
d1bbefede1c4c9b8d1ed28fcd9d630c954404842 | mfraza786/index | /set.py | UTF-8 | 332 | 4.25 | 4 | [] | no_license | #create an Empty Set
s=set()
#Add Element to Set.
s.add(1)
s.add(3)
s.add(5)
s.add(2)
s.add(1)
s.add(7)
s.add(4)
print(s)
s.remove(4)
print(" Set ofter Remove Function : ", s)
new = int (input("Enter New number: "))
s.add(new)
print(" Set after add new number",s)
print()
print(f"The set has {len(s)} ... | true |
0e56ba13f1cd1dee7f2f9ecb3db5da961c4e6a1a | michelprojets/Ensimag1 | /BPI/TP1/point.py | UTF-8 | 464 | 3.859375 | 4 | [] | no_license | #! /usr/bin/env python3
"""
module comportant la classe Point
"""
class Point:
"""
classe Point de deux coordonnées
"""
def __init__(self, coord_x=0, coord_y=0):
""" constructeur """
# abscisse
self.coord_x = coord_x
# ordonnée
self.coord_y = coord_y
def __s... | true |
ee70df185dd918a17486f200e76d5e497399660e | dr-dos-ok/Code_Jam_Webscraper | /solutions_python/Problem_200/51.py | UTF-8 | 326 | 3.09375 | 3 | [] | no_license | t = int(raw_input())
for i in xrange(1, t + 1):
a = [int(c) for c in raw_input()]
for j in xrange(len(a)-1, 0, -1):
if (a[j] < a[j-1]):
a[j-1]-=1
for k in xrange(j, len(a)):
a[k]=9
result = long(''.join(map(str,a)))
print "Case #{}: {}".format(i, re... | true |
0892adc43f6151cb59d942d48af1a7dc4ff2357d | DongHyunByun/algorithm_practice | /past_archive/swexpert/1258(7일차 - 행렬찾기).py | UTF-8 | 748 | 3.078125 | 3 | [
"MIT"
] | permissive | def returnRC(L,N,i,j):
row=1
col=1
L[i][j]=0
try:
while(L[i+row][j]!=0):
row+=1
except:
pass
try:
while(L[i][j+col]!=0):
col+=1
except:
pass
for a in range(row):
for b in range(col):
L[i+a][j+b]=0
return [r... | true |
bdfb27f4f310130379db7fa3a61521f2d2903978 | shirguin/python | /task_02.py | UTF-8 | 578 | 3.96875 | 4 | [] | no_license | # задание №2
# Пользователь вводит время в секундах. Переведите время в часы,
# минуты, секунды и выведите в формате чч:мм:сс. Используйте
# форматирование строк.
seconds = int(input('Введите количество необходимых секунд: '))
hour = seconds // 3600
minutes = (seconds - hour*3600) // 60
remains_seconds = seconds - hou... | true |
7879ebef979b591b2b31650e4ed7a77e63247eb8 | Xinxin-Wang-0128/ehdn-paper-analysis | /CompareSTRDatabases/SCRIPTS/FilterBedForSize.py | UTF-8 | 1,119 | 2.90625 | 3 | [
"Apache-2.0"
] | permissive | import sys,os,argparse
def GetArgs():
# Redone with Argparse
parser = argparse.ArgumentParser()
parser.add_argument("-T","--Type",help="GangSTR || STRetch", required=True)
parser.add_argument("-I","--Infile",help="Input File",required=True)
parser.add_argument("-O","--Outfile",help="Output File",required=True)
... | true |
05a183dde136cbade4a8d0049dc21474a2ef9d9d | wagnersistemalima/Mundo-2-Python-Curso-em-Video | /pacote dawload/projetos progama em Python/desafio051 Progressão Aritimética For.py | UTF-8 | 431 | 4.375 | 4 | [
"MIT"
] | permissive | #Desafio051 Progressão Aritimetica.
#Desenvolva um programa que leia o primeiro termo e a razão de uma PA. No final, mostre os 10 primeiros
# termos dessa progressão.
print('-=-'*10)
print('10 Termos de uma PA')
print('-=-'*10)
termo = int(input('Digite o primeiro termo:'))
razao = int(input('Digite a razão:'))
decimo... | true |
7e19820a774520c2722da9da94b3ee9ba0679405 | kyliewing/LeetCode | /167_TwoSumII_Sorted.py | UTF-8 | 340 | 2.921875 | 3 | [] | no_license | #My dictionary hash table version, One Time AC
class Solution(object):
def twoSum(self, numbers, target):
my_dict={}
for i in range(len(numbers)):
if numbers[i] in my_dict:
return [my_dict[numbers[i]],i+1]
else:
my_dict[target-numbers[i]]=i+1
... | true |
55ba3a7d47e7119c49e63dac0638022a705fdb32 | JaroslavHron/projection | /time_control.py | UTF-8 | 3,973 | 2.546875 | 3 | [] | no_license | import csv
from dolfin.cpp.common import toc, tic, info
class TimeControl:
def __init__(self):
info('Initializing Time control')
# watch is list [total_time, last_start, message_when_measured, count into total time]
self.watches = {}
self.last_measurement = 0
self.measuring... | true |
c9b1c37de24031b84cc78c456674a74da516d595 | zu20670/UOBzu20670_EMATM0048 | /SDPA_Part1/carRental_test.py | UTF-8 | 1,676 | 2.890625 | 3 | [] | no_license | import unittest
import car_rental
class MyTestCase(unittest.TestCase):
def test_fee(self):
""" The cost of testing ordinary users """
self.assertEqual(car_rental.Customer.fee('', 1, 5), 150)
self.assertEqual(car_rental.Customer.fee('', 2, 5), 250)
self.assertEqual(car_rental.Custo... | true |