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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
d240a20e48f68351ae620b3ee2d82468edfbd450 | Python | erickmiller/AutomatousSourceCode | /AutonomousSourceCode/data/raw/sort/5824a259-97ee-4c08-bf18-8f715a0bfd52__alternateSort.py | UTF-8 | 647 | 3.25 | 3 | [] | no_license | '''
Created on Oct 15, 2014
@author: Ben Athiwaratkun (pa338)
'''
#from __future__ import division
#import numpy as np
def sortedToAlternateSort(A):
n = len(A)
B = [None]*n
# assume that A is sorted
half = len(A)/2
for i in range(half):
B[2*i] = A[i]
B[2*i+1] = A[n-1-i]
... | true |
8861ad18e8fd95b706abcd6155889d7a6f834494 | Python | zhlstone/AIR | /interaction_prediction/loss.py | UTF-8 | 6,180 | 2.671875 | 3 | [
"Apache-2.0"
] | permissive | # This is the loss for interaction prediction
import tensorflow as tf
import numpy as np
class JointPredMultiModalLoss(tf.keras.losses.Loss):
def __init__(self, name = 'jpmm_loss'):
super().__init__(name = name)
def call(self, gt, avails, pred, confidences, reduce_mean=True):
"""
Call Arguments:
... | true |
2a20adf71a1212466bbb9c7f6ad0153acf5475d2 | Python | srazihaider/PythonExcercises | /Excercise7.py | UTF-8 | 107 | 3.265625 | 3 | [] | no_license | myfilename = input("Enter a file name with its extension")
mylist = myfilename.split(".")
print(mylist[1]) | true |
0794d75bab74119b479a7c05d760c869f0d9118e | Python | dozhdikov99/SnakeGame | /SnakeGame.py | UTF-8 | 4,344 | 2.703125 | 3 | [] | no_license | #!/usr/bin/env python3.4
# By Igoru99 (C) 2016 year
import time
import win32api
import pythoncom
import pyHook
import threading
import os
import random
from colorama import Fore, Back, Style, init
data = ['0' for i in range(200)] # Game box 10*20
scores = 0 # Scores
python = [110,130,150] # List of coordinats the ... | true |
831d9f25dbfb77a08b1bc62df528191b19474942 | Python | ffigura/Euler-deconvolution-plateau | /code/synthetic_test/estimates_statistics.py | UTF-8 | 2,093 | 2.875 | 3 | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | """
Estimates statistics
A Python program to compute the standard deviation of depth and base-level
estimates and the mean of the northing, easting and depth estimates
on plateau plots.
The outputs are placed at the folder 'results'.
The nomenclature is 'plateau_pltX.txt', where
X stands for the area corre... | true |
cd10cd1cafc934b6c2a7535a158acebaa84c1d12 | Python | GhadeerElmkaiel/Simple-Evolution-Simulation | /Run_Simulation.py | UTF-8 | 18,342 | 2.65625 | 3 | [] | no_license | import pygame
import random
import math
# -----------------------------------------------------------------
pygame.init()
winWidth = 1100
winHeight = 800
playWinWidth = 800
playWinHeight = 800
FPS = 100
mutationRate = 0.01
hugeMutationRate = 0.05
gen = 1
maxFitness = 0
minAnglesChange = 10**7
minSteps = 1000
minSte... | true |
369b64e1d9558b595120012dbe625bf61b2b687b | Python | MatrixWeber/python_cleanup_directory | /ask_question_to_delete.py | UTF-8 | 1,905 | 2.78125 | 3 | [] | no_license | import subprocess, os, platform
from write_msg_to_desktop import notify
from verbose import checkIfVerbose
import shutil
def askQuestionAndPerform(destDirection, fileName, sayYesToString = '/][??05436'):
destFile = destDirection + fileName
if sayYesToString in fileName:
deleteOptions = 'y'
else:
... | true |
37b4b4d0f6e66e4c8123f2f12b881e3d7813c4e6 | Python | jochembruins/DataProcessing | /Homework/scraper/tvscraper.py | UTF-8 | 4,250 | 3.359375 | 3 | [] | no_license | #!/usr/bin/env python
# Name: Jochem Bruins
# Student number: 10578811
"""
This script scrapes IMDB and outputs a CSV file with highest rated tv series.
"""
import re
import csv
from requests import get
from requests.exceptions import RequestException
from contextlib import closing
from bs4 import BeautifulSoup
TARGE... | true |
eebb7f782ba360f65d065eef86db2450f71874da | Python | thomaszhouan/CodeIT2018 | /codeitsuisse/routes/twodinosaurs.py | UTF-8 | 2,717 | 2.671875 | 3 | [] | no_license | import logging
import numpy as np
from flask import request, jsonify
from codeitsuisse import app
logger = logging.getLogger(__name__)
def solve_dp(A):
mod = 100000123
maxn = 400010
dp = np.zeros(maxn, dtype=np.int32)
dp[0] = 1
cur = 0
for a in A:
cur += a
dp_new = np.copy(dp... | true |
52668a2fdbf22a75b0b005b9ee7c6f81ad0b659b | Python | bonangrs/Bonang-Respati-S_I0320018_Wildan_Tugas4 | /I0320018_soal2_tugas4.py | UTF-8 | 227 | 3.765625 | 4 | [] | no_license | import math
bil1 = int(input("Masukkan bilangan pertama: "))
bil2 = int(input("Masukkan bilangan kedua: "))
hasil = math.floor(bil2 / bil1)
print("Angka", bil2, "dapat dibagi menjadi angka", bil1, "sebanyak", hasil, "kali.")
| true |
273a23793f38173a41b155b9ceef808d686dbaae | Python | tillahoffmann/nonpoisson-dynamics | /distributions.py | UTF-8 | 4,712 | 3.6875 | 4 | [
"MIT"
] | permissive | """
This file builds on the C extension _distributions.c and contains python classes
that are used to evaluate PDFs and CDFs of distributions and draw samples from
a range of distributions.
The following distributions are currently implemented
- Exponential (http://en.wikipedia.org/wiki/Exponential_distribution)
- Log... | true |
71cad161a07621815bccc275f0c109407da176f7 | Python | bluekitchen/btstack-packet-log | /btstack-packet-log.py | UTF-8 | 3,554 | 2.578125 | 3 | [
"BSD-2-Clause"
] | permissive | #
# convert log output to PacketLogger format and open in PacketLogger(mac) or Wireshark
#
import sublime
import sublime_plugin
import re
import sys
import time
import os
import tempfile
import subprocess
default_date="2001-01-01"
default_hours = 12
packet_counter = 0
last_time = default_date + " " + str(default_h... | true |
83caff062fb1fea24bb4f821ac398c3b9fe107d9 | Python | HydraPhantasm/JokerBot | /cogs/caption.py | UTF-8 | 1,511 | 2.71875 | 3 | [
"MIT"
] | permissive | from discord.ext import commands
import discord
from captionbot import CaptionBot
import functools
class Caption(commands.Cog):
def __init__(self, client):
self.client = client
@commands.cooldown(1, 2, commands.BucketType.user)
@commands.command(pass_context=True)
async def captio... | true |
65dbdae557497a53663d4b0ec50dfb2740157e86 | Python | sitting-cat/intelligentSystemTraining | /logisticRegression_template.py | UTF-8 | 4,475 | 3.0625 | 3 | [] | no_license | # -*- coding: utf-8 -*-
import numpy as np
import data
import matplotlib.pylab as plt
import classifier_template as classifier
import pdb
#-------------------
# クラスの定義始まり
class logisticRegression(classifier.basic):
#------------------------------------
# 1) 学習データおよびモデルパラメータの初期化
# x: 学習入力データ(入力ベクトルの次元数×デ... | true |
2cb059ec453fbbff892b6066d43933cd5efa30e9 | Python | sankalpreddy1998/Classical-Algorithms | /segment tree/max-range.py | UTF-8 | 1,169 | 3.25 | 3 | [] | no_license | # def construct(st,arr,l):
# for i in range(l):
# st[l+i] = arr[i]
# for i in range(l-1,0,-1):
# st[i] = max(st[2*i],st[2*i+1])
# def max_query(st,i,j,l):
# i += l
# j += l
# m = -999999
# while i<j:
# if i%2!=0:
# m = max(m,st[i])
# ... | true |
41a3d82c99a34b5183fdf943305bc70a7a229b83 | Python | zion-ai/PythonLearn | /with mosh everybody python/nestedLoops.py | UTF-8 | 830 | 4.03125 | 4 | [
"Apache-2.0"
] | permissive | for x in range(4):
for y in range(3):
print(f'({x,y})')
# bu şekilde iç içe geçmiş döngüler oluşturduk
print('---------------------------------')
"""
CHALLENGE
"""
"""
numbers = [5,2,5,2,2]
çıktı:
xxxxx
xx
xxxxx
xx
xx
"""
# bizden kolayca x le çarpılmasını istenmiyor yoksa bu çıktıya bu yöntemle de ula... | true |
ed4c2f7350a30736e021ddf54d608cf04d43abbb | Python | redyelruc/BoringStuff | /StringStripper.py | UTF-8 | 514 | 3.515625 | 4 | [] | no_license | def mysplit(strng):
strng = strng.lstrip()
mylist = []
word = ''
for character in range(len(strng)):
if strng[character].isalpha():
word = word + strng[character]
else:
mylist.append(word)
word = ''
mylist.append(word)
return mylist
# put your ... | true |
f6b72bee5b698a6b008e1849b0e57ec64b17ba99 | Python | the-inevitable/programming-python-book | /gui/tk-tour/config_label.py | UTF-8 | 274 | 2.703125 | 3 | [] | no_license | from tkinter import *
root = Tk()
label_font = ('times', 20, 'bold')
widget = Label(root, text='Trying out config')
widget.config(bg='black', fg='yellow')
widget.config(font=label_font)
widget.config(height=3, width=20)
widget.pack(expand=YES, fill=BOTH)
root.mainloop()
| true |
f0671b4d9919eed67c2c5194d98114bb0afa312e | Python | 42lan/bootcamp_python | /day00/ex01/exec.py | UTF-8 | 356 | 3.34375 | 3 | [] | no_license | import sys
def string_from_args():
x = 1
string = ''
while x < len(sys.argv):
string += sys.argv[x]
x += 1
if x < len(sys.argv):
string += ' '
return string
def rev_alpha():
return (string_from_args().swapcase())[::-1]
def main():
print(rev_alpha())
if... | true |
1b141b735c7b8071eaefc2c5e875fb19b5e80993 | Python | BenettTregenna/COMP3000Proj-SNET | /pythonInterface.py | UTF-8 | 1,003 | 2.625 | 3 | [] | no_license | import sys
# creation of network config python script
confFile = open("networkConf.py", "w")
#header
confFile.write("from mininet.topo import Topo\n")
confFile.write("class MyTopo( Topo ):\n")
confFile.write(" def __init__( self ):\n") #custom topology creation
confFile.write(" Topo.__init__( self )\n")# i... | true |
f04c50e4a89d0f19031f9035b6cf09292c7605cd | Python | Louvani/holberton-system_engineering-devops | /0x15-api/0-gather_data_from_an_API.py | UTF-8 | 742 | 3.421875 | 3 | [] | no_license | #!/usr/bin/python3
""" 0. Gather data from an API """
import requests
from sys import argv
if __name__ == '__main__':
employee_ID = argv[1]
url = 'https://jsonplaceholder.typicode.com/todos'
values = {'userId': employee_ID}
tasks = requests.get(url, params=values).json()
url2 = 'https://jsonpla... | true |
d3835111ab0c852c6a0cc90bf43d4cbadf681086 | Python | http-www-testyantra-com/Afifa_Sony | /oops_concepts/vehicle.py | UTF-8 | 1,626 | 2.796875 | 3 | [] | no_license | class Vehicles():
vehicle_brand="suzuki"
INIT=20
def __init__(self,color,chno,price,vhno,mileage):
self.color=color
self.chno=chno
self.price=price
self.vhno=vhno
self.mileage=mileage
def display(self):
print(self.color,self.chno,self.price,self.vhno,self.... | true |
8133754a82f25118f0dcb17c568fdfd76b25bef8 | Python | herzenuni/sem3-assignment1-281117-vonkuptschino | /sumsq/powsum.py | UTF-8 | 388 | 3.8125 | 4 | [] | no_license |
def digitsSum(num):
num = str(num)
sum = 0
for i in num:
sum += int(i) ** 2
return sum
def usinp():
n = int(input("input the number of digits: "))
res = []
for i in range((10 ** (n - 1)), (10 ** n)):
if digitsSum(i) % 17 == 0:
res.append(i)
print("{}-digit nums which sum of powered digits is devisible ... | true |
0262901427143b582a3c4d71de5ba64a17673230 | Python | GerardoTravesedo/fast-rcnn-object-detection | /object_detection/dataset/roi_tools.py | UTF-8 | 15,100 | 3.09375 | 3 | [] | no_license | import itertools
import math
import random
import numpy as np
import selectivesearch
NUMBER_CLASSES = 21
def find_rois_complete(image_pixels, gt_boxes, min_rois_foreground, max_rois_background):
"""
Generates a minimum number of foreground rois and a maximum number of background ones
1) First it genera... | true |
b3568937641bf82393068a923557ec3eb10d201c | Python | openforcefield/openff-bespokefit | /openff/bespokefit/fragmentation/base.py | UTF-8 | 3,007 | 3.0625 | 3 | [
"MIT"
] | permissive | """
Register new fragmentation methods with bespokefit
"""
from typing import Dict, List, Type, Union
from openff.fragmenter.fragment import Fragmenter, PfizerFragmenter, WBOFragmenter
from openff.bespokefit.exceptions import FragmenterError
_fragmentation_engines: Dict[str, Type[Fragmenter]] = {}
def register_fra... | true |
8bb377b5eeaa2c8b845e25e1d9ba3f7761bb6823 | Python | AdamZhouSE/pythonHomework | /Code/CodeRecords/2332/60712/305530.py | UTF-8 | 65 | 3.046875 | 3 | [] | no_license | x = int(input())
if x==5:
print(8)
else:
print(x) | true |
be9c4968a582a96742642990a09be3a229213927 | Python | Ben4issi/7150626-Apprenez-la-programmation-orientee-objet-avec-Python | /exercices/p3c1_solution/contact/owlcontact.py | UTF-8 | 662 | 3.375 | 3 | [] | no_license | """Définit le contact par chouette."""
from contact.abstract import ContactSystem
from contact.helpers import verify_adress
class OwlContactSystem(ContactSystem):
"""Envoi un message en utilisant une chouette ! 🧙♂️"""
def __init__(self, address):
"""Initialise l'adresse."""
verify_adress(a... | true |
e9fc2e579251b65dce97135558add968314af128 | Python | chtenb/fate | /fate/commandtools.py | UTF-8 | 3,969 | 3.515625 | 4 | [
"MIT"
] | permissive | """
This module contains several base classes and decorators for creating commands.
"""
from logging import debug
from collections import deque
from inspect import isclass
from .mode import Mode
class Undoable:
"""
For some commands, we want to be able to undo them.
Let us define the class Undoable for th... | true |
0184bca86826ade957b46d31e2622bd4bec42fd5 | Python | jnjnslab/firebase-sample | /python/add_example_data.py | UTF-8 | 2,688 | 2.96875 | 3 | [] | no_license | import firebase_admin
from firebase_admin import credentials
from firebase_admin import firestore
# Use a service account
cred = credentials.Certificate('firebase.json')
firebase_admin.initialize_app(cred)
db = firestore.client()
# [START custom_class_def]
# [START firestore_data_custom_type_definition]
class City(o... | true |
bd68d31462866fbeee6f9fb8341dfff8708e10ef | Python | RoryGlenn/CSE_20 | /pa3/cipher.py | UTF-8 | 5,351 | 4.0625 | 4 | [] | no_license | # assignment: programming assignment 3
# author: Rory Glenn
# date: 7/17/20
# file: cipher.py is a program that encrypts letters by using shifting the entire alphabet to the right by 3 digits
# input: give the program an input file to read such as input_file.txt
# output: writes to a new file the encrypted text and pri... | true |
66d770f667ed8a44128d8577090390d9edd7c5ab | Python | DanielLongo/eegML | /discriminators/convD_eeg.py | UTF-8 | 1,960 | 2.609375 | 3 | [] | no_license | import torch.nn as nn
import torch.nn.functional as F
import torch
import numpy as np
class ConvDiscriminator(nn.Module):
def __init__(self, img_shape):
self.img_size = img_shape[1]
self.channels = img_shape[0]
super(ConvDiscriminator, self).__init__()
def discriminator_block(in_filters, out_filters, bn=True... | true |
23eaea447b58c4482e5c776c2cdf71a87b6e0595 | Python | karanj1994/personal-training | /python_tips.py | UTF-8 | 1,530 | 2.671875 | 3 | [] | no_license | import os
import json
import argparse
my_file = os.popen("maprcli table region list -path /datalake/other/polarisprovider/polarisdatamovement/blue/perf/data/hcp_region -json")
with my_file as json_data:
d = json.load(my_file)
# test = []
# for i in d["data"]:
# test.append(i["logicalsize"])
# list comprehensi... | true |
3f28b4f33a45e5a47a19a84f3012bd69f5ffa8a6 | Python | lhy0807/A2CS | /Ch23/binary_tree.py | UTF-8 | 1,609 | 3.640625 | 4 | [] | no_license | nullPtr = -1
class Node(object):
def __init__(self):
self.data = None
self.leftPtr = nullPtr
self.rightPtr = nullPtr
class BinaryTree(object):
def __init__(self, space):
self.space = space
self.freePtr = 0
self.rootPtr = nullPtr
self.record = []
for i in range(self.space): # initialize the tree
... | true |
41e1dcea661ca16589c347ae01446de67ca16084 | Python | nikicat/yasd | /yasd/recvmmsg.py | UTF-8 | 2,057 | 2.71875 | 3 | [] | no_license | import cffi
def recv_mmsg(stream, sock, vlen=1000, bufsize=9000):
ffi = cffi.FFI()
ffi.cdef('''
typedef unsigned int socklen_t;
struct msghdr {
void *msg_name;/* Address to send to/receive from. */
socklen_t msg_namelen;/* Length of address data. */
struct... | true |
580ca5f6c97d4d207cda76bd1a60565f16a4fcbb | Python | wxWidgets/Phoenix | /unittests/test_lib_agw_flatmenu.py | UTF-8 | 3,510 | 2.546875 | 3 | [] | no_license | import unittest
from unittests import wtc
import wx
import wx.lib.agw.flatmenu as FM
#---------------------------------------------------------------------------
class lib_agw_flatmenu_Tests(wtc.WidgetTestCase):
def setUp(self):
'''
Monkey patch some methods which don't behave well without
... | true |
a60ccef01881134369b60a3f176b7377f7f72d4e | Python | FitzWang/Marvel | /agg_pairwise.py | UTF-8 | 13,801 | 2.546875 | 3 | [] | no_license | # -*- coding: utf-8 -*-
"""
Created on Sun Mar 21 16:52:32 2021
@author: guang
"""
import pandas as pd
import os
import matplotlib
# matplotlib.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
from pathlib import Path
import time
import copy
def ExtendOutput(pathbase,csvList):
for outFile in csvList... | true |
2a408d2a9a172a8e1657f227b0a6cf1e9983ac6e | Python | cephcyn/MessengerGrapher | /parser.py | UTF-8 | 2,440 | 2.59375 | 3 | [] | no_license | import pickle as pkl
from collections import namedtuple
from datetime import datetime, timedelta
import json
from urllib.request import urlopen
import os.path
from bs4 import BeautifulSoup
from userinfo import ME, API_KEY
soup = BeautifulSoup(open("messages.htm", encoding='utf8').read(), 'html.parser')
Message = named... | true |
ed23a63ebfd7784306f90a73b4e4053572d185f6 | Python | LVO3/python-2021 | /fmake.py | UTF-8 | 119 | 3.203125 | 3 | [] | no_license | #write
f = open("새파일.txt", 'w')
for i in range(1, 11):
data = '%dth line\n' %i
f.write(data)
f.close() | true |
61338e611c822320a747c7d26fbfa77a385a7b79 | Python | jdwdm3/CodingChallenge | /Exercise3/Algorithm.py | UTF-8 | 3,423 | 4.3125 | 4 | [] | no_license | ################################################################inp##########
## ##
## Jeremy Warden -- Gateway Blend Coding Challenge ##
## ##
#############... | true |
dbe873de758254a420338b2563e8d5fbddc87266 | Python | parksjsj9368/TIL | /ALGORITHM/PROGRAMMERS/ALGORITHM_TEST/22. 압축.py | UTF-8 | 664 | 3.328125 | 3 | [] | no_license | # 아이디어 구상
# 앞에가 있고, 뒤에가 없어
# => 앞+뒤 append
# => 앞 값 출력
#
# 앞에가 있고, 뒤에도 있어
# => 뒤 값을 +1
# 결국엔, 뒤에가 없을 때까지
# => 앞+뒤 append
# => 앞 값 출력
def solution(msg):
dict = {} # 기본 A~Z 리스트
for i in range(65, 91):
dict[chr(i)] = i - 64
answer = []
i = 0
while (i < len(msg)):
... | true |
73a392b60ca9d20f6adf8df651dc5c9121a13ea6 | Python | Caceros/Load-Forecast-using-SVR | /my_functions/scrape_weather_data.py | UTF-8 | 4,830 | 3.140625 | 3 | [] | no_license | """
Download historical weather data using wunderground API. https://www.wunderground.com/weather/api/d/docs
This script is based on @jtelszasz work. https://github.com/jtelszasz/my_energy_data_viz
Basic Usage:
python scrape_weather_data.py startMonth startDay startYear endMonth endDay endYear
python scrape_we... | true |
02ed06d8c1e05c241d2b2978bc4642aad49c1236 | Python | yuju30/NTUML18 | /hw2/HW2_logistic.py | UTF-8 | 2,955 | 2.734375 | 3 | [] | no_license | import sys
import numpy as np
import pandas as pd
def read_data(trainX_name,trainY_name,testX_name):
trainX = pd.read_csv(trainX_name,header=0).as_matrix()
#print(trainX.shape)
trainX = trainX.astype(float)
trainY = pd.read_csv(trainY_name,header=0).as_matrix()
#print(trainY.shape)
trainY = trainY.astype(int)
t... | true |
8f71ac65f01197ca0e08c3df87b0174abe4ebf62 | Python | SAV2018/Python-BaseLevel | /BL-L4/task-4-6.py | UTF-8 | 1,343 | 4.15625 | 4 | [] | no_license | '''
Реализовать два небольших скрипта:
а) бесконечный итератор, генерирующий целые числа, начиная с указанного,
б) бесконечный итератор, повторяющий элементы некоторого списка, определенного заранее.
Подсказка: использовать функцию count() и cycle() модуля itertools.
'''
from itertools import count, cycle
# а)
ilist =... | true |
8fabd84bc2d756b00e6288c74cafb6ec841caac2 | Python | webclinic017/loris-server-tmp | /ebest/minute.py | UTF-8 | 657 | 2.921875 | 3 | [] | no_license | import os
import pickle
import pandas as pd
"""
ebest로 받은 데이터를 종목별로 구분하여 저장하는 역할
"""
files = os.listdir('./data')
codes = list(set([f.split('_')[0] for f in files]))
cnt = 0
for code in codes:
f = [f for f in files if code == f.split('_')[0]]
full_df = pd.DataFrame()
for pkl in f:
pkl_f = open(f'... | true |
ea8a2a573b56ba3fe18fbc81e3db50f4b651619d | Python | Xinxinatg/chess | /encoder.py | UTF-8 | 5,003 | 3.046875 | 3 | [
"MIT"
] | permissive | from chess_types import *
import copy
import collections
import numpy as np
BOARD = ['帅', '将', '士', '仕', '相', '象', '马', '馬', '车', '車', '兵', '卒', '炮', '包']
DEFAULT = {
'帅': [-1],
'将': [-1],
'士': [-1, -1],
'仕': [-1, -1],
'相': [-1, -1],
'象': [-1, -1],
'马': [-1, -1],
'馬': [-1, -1],
'车... | true |
9b1b24787943cf9bd1c4934094097d0e60e616b9 | Python | felipefiali/studying-in-python | /algorithms/find_numbers_that_sum.py | UTF-8 | 1,938 | 4.25 | 4 | [] | no_license | def check_for_sum_in_two_unique_numbers(array, target):
"""
Given an array of unique integers, and a target T, check if it is possible to reach that value
with two unique numbers in the array.
"""
hash_table = {}
for index, number in enumerate(array):
hash_table[number] = True
for... | true |
09e1b9f20caaab175e3411e44047609badccd66d | Python | LalithK90/LearningPython | /privious_learning_code/OS_Handling/os.read() Method.py | UTF-8 | 681 | 4.375 | 4 | [] | no_license |
# Description
#
# The method read() reads at most n bytes from file desciptor fd, return a string containing the bytes read. If the end of file referred to by fd has been reached, an empty string is returned.
# Syntax
#
# Following is the syntax for read() method −
#
# os.read(fd,n)
#
# Parameters
#
# fd − This is the... | true |
217e6a825add1f4baf5d12c95a37150dfa8d631a | Python | david888844/C-digos-Programaci-n | /4.Calcular la velocidad.py | UTF-8 | 319 | 3.46875 | 3 | [] | no_license | # -*- coding: utf-8 -*-
"""
Created on Thu Feb 18 09:37:00 2021
@author: David Alzate
"""
# Calcular la velocidad
# Valores a determinar d y t
tf=int(input('¿cuanto tiempo?: '))
d=float(input('¿distancia recorrida?: '))
v=d/tf
vkmh=(v/1000)*60*60
print('Velocidad del vehiculo(Km/h)')
print(vkmh... | true |
b3252eb52bad2d873346f1764e5bdad8c0b51df1 | Python | hibiup/HelloSciKitLearn | /tests/test_normalization.py | UTF-8 | 2,995 | 3.21875 | 3 | [] | no_license | from unittest import TestCase
class NormalizationTest(TestCase):
def test_normalization(self):
'''
Normalization 又称为 scale,它的作用是让数据更集中在设定的范围内。在 ML 中数据的取值区域如果太宽会导致内涵太丰富以至于无法解释
因此需要将其转化为无量纲的纯数值以便于比较。其中最典型的是归一化处理,即将数据映射到[0,1]区间。
原理解释:
https://zhuanlan.zhihu.com/p/331... | true |
e65e8ed2cd3852e43102190bf40fe3d405406cad | Python | genkinaoko/Mac | /w.py | UTF-8 | 356 | 3.453125 | 3 | [] | no_license | import re
text = "私の名前は__名前__です。"
def mad(mls):
hint = re.findall("__.*?__",mls)
if hint is not None:
for word in hint:
q = "{}を入力".format(word)
new = input(q)
mls = mls.replace(word, new, 1)
#print("\n")
#mls = mls.replace("\n","")
print(mls)... | true |
81f00d1b3d32995c9d6882ea160914b2e40eebc5 | Python | gentle-yu/PythonProject | /Script/configuration/case_readyaml.py | UTF-8 | 492 | 2.515625 | 3 | [] | no_license | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@File : case_readyaml.py
@Author: gentle.yu
@Date : 2020/8/16 16:00
"""
import yaml
import os
# 获取当前脚本所在文件夹路径
curpath = os.path.dirname(os.path.realpath(__file__))
# 获取yaml文件路径
#yamlpath = os.path.join(curpath, "case_readyaml.yaml")
# 用open方法打开直接读出来
f = open(yamlp... | true |
b74e1ba6d47d2a6590949add68df6bbe785a0c72 | Python | melnaquib/CarND-Traffic-Sign-Classifier-Project | /scratch.py | UTF-8 | 826 | 2.75 | 3 | [] | no_license | ### Load the images and plot them here.
### Feel free to use as many code cells as needed.
import os
import numpy as np
import cv2
examples_dir = 'examples'
example_files = [os.path.join(examples_dir, filename) for filename in list(os.walk(examples_dir))[0][2]]
n_imgs = len(example_files)
example_images = np.zeros((n... | true |
8022bd48eb7830df868c09162f1f7959605a4d75 | Python | FredericoIsaac/mail_project | /word_machine.py | UTF-8 | 3,117 | 2.890625 | 3 | [] | no_license | import corresponding_date
from mailmerge import MailMerge
import mammoth
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
import docx2txt
MONTH_DICT = {
1: 'Janeiro',
2: 'Fevereiro',
3: 'Março',
4: 'Abril',
5: 'Maio',
6:... | true |
8c9d94285a90d1bf672f415898ac2d38d6421ea5 | Python | ssulav/interview-questions | /leetcode/3_longest-substring-without-repeating-characters.py | UTF-8 | 1,952 | 3.640625 | 4 | [] | no_license | """
https://leetcode.com/problems/longest-substring-without-repeating-characters
Given a string s, find the length of the longest substring without repeating characters.
Example 1:
Input: s = "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.
"""
import time
class Solution:
def lengthO... | true |
b159fe6e628f6a0d7f65911490dcdf6a4b455a3b | Python | tsxtypr/demo | /demo/views.py | UTF-8 | 2,875 | 2.765625 | 3 | [] | no_license | from django.http import HttpResponse
def index(request):
return HttpResponse("Hello world")
def about(request):
return HttpResponse("这是一个about页面")
def demo(request,year,mon,day):
ls = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30]
res = 0
if int(year) % 4 == 0 and int(year) % 100 != 0:
for ... | true |
7ac045a96cdab44c63072b02562b33e90377381f | Python | dkatz23238/LegalDataScience1 | /learning.py | UTF-8 | 462 | 2.65625 | 3 | [] | no_license | from sklearn.model_selection import train_test_split
from sklearn.preprocessing import OneHotEncoder
from sklearn.linear_model import LogisticRegression
import pandas as pd
df = pd.read_csv("dataset.csv").set_index("index")
train_ = df[[i for i in df.columns if i != "label"]]
labels_ = df["label"]
train_X, test_X, tr... | true |
4d1f332ca051d76c1680ff245a279167a752c2a4 | Python | sss6391/iot_python2019 | /03_Bigdata/02_Standardization_Analysis/3. DB/2db_insert_rows.py | UTF-8 | 1,128 | 2.984375 | 3 | [] | no_license | # 비휘발성 데이터 베이스 생성
# 외부 데이터로부터 초기 DB table 값 생성
import csv
import sys
import sqlite3
input_file = sys.argv[1] # supplier_data.csv
# SQLite의 경우 DB명이 파일로 1:1 매칭이 된다.
con = sqlite3.connect('Suppliers.db')
c = con.cursor()
create_table = '''CREATE TABLE IF NOT EXISTS Suppliers
(Supplier_Name VARCHAR(20),
InVoice_Nu... | true |
e39448469a1a9729897b849b7352090768777aa3 | Python | rmurali200/Assorted | /Sorting/MergeSort/SelectionSort.py | UTF-8 | 353 | 3.03125 | 3 | [] | no_license | def selectionsort(A):
for i in range(len(A)):
minIdx = i
for j in range(i+1,len(A)):
if A[j] < A[minIdx]:
minIdx = j
A[i],A[minIdx] = A[minIdx],A[i]
return A
x = [4,5,2,10,1.2,1.3,1.8,2.1,2.4,2.7,65,3.5,3.9,4.1,4.2,4.3,4.6,4.9,5.3,5.7,6.5,7.2,2.2,1.8]
xSorted... | true |
7c3b3e7785b7b732008416c379697d54a2f45115 | Python | ahmetmenguc/Zoom_Poll_Analyzer | /Zoom-Poll-Analyzer-main/python_iteration1/Question.py | UTF-8 | 232 | 3.203125 | 3 | [] | no_license | class Question:
def __init__(self, question, answer):
self.question = question
self.answer = answer
def get_question(self):
return self.question
def get_answer(self):
return self.answer
| true |
50928700a932a183388aed48dc149f9811fd5843 | Python | muenchner/event-impact | /STEP_1_update_vstar_medians3.py | UTF-8 | 16,755 | 2.984375 | 3 | [] | no_license | #!/usr/bin/python2.7
"""Author: Mahalia Miller
Date: August 10, 2011
Builds graph of D7 sensors
"""
import sqlite3
import string
from math import cos, sin, radians, acos, pi
import numpy as np
def run_on_file(filename):
"""opens and reads file"""
try:
f = open(filename, "r")
rows ... | true |
3b35fbc2906eab9ef7c8a048051a06cc39438f83 | Python | coldblade2000/MathIAData | /getAccelDiff.py | UTF-8 | 2,066 | 3.109375 | 3 | [
"BSD-3-Clause"
] | permissive | import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
def getFirstgoodrow(tb, height, groundheight):
for index, row in df.iterrows():
if row["ASL"] < height + groundheight + 500 and row["ASL"] > height + groundheight - 500:
return index
return tb.head(1).index[0]
def get... | true |
aa791af8fc0fe359ea3937657ef2494425c42b10 | Python | jdanray/leetcode | /ThroneInheritance.py | UTF-8 | 554 | 3.84375 | 4 | [] | no_license | # https://leetcode.com/problems/throne-inheritance/
class ThroneInheritance(object):
def __init__(self, kingName):
self.dead = set()
self.tree = {kingName: []}
self.root = kingName
def birth(self, parentName, childName):
self.tree[parentName].append(childName)
self.tree[childName] = []
def death(self, ... | true |
8313d5d7712291ccb5018a9b47af8b0b47cd8b4c | Python | aKeller25/Coursework | /GEOG476/Lab01.py | UTF-8 | 7,616 | 3.859375 | 4 | [] | no_license | #!/usr/bin/env python
# coding: utf-8
# Class: GEOG476
# Semester: FALL2018
# Assignment: Lab01
# Author: Alex Keller
# Written: 10:17 AM 9/5/2018
# Last edited: 10:16 AM 9/10/2018
#
# Notes: http://pythontutor.com & http://www.asciitable.com/ are a good resources
# Deliminate the sec 4 strings by using '/'
#
# Sepa... | true |
50b4a00bda531edb2944a89ee8fcc5beca0ffc7a | Python | Ben-Hardy/leetcode_solutions | /171_title_to_number.py | UTF-8 | 200 | 3.875 | 4 | [
"MIT"
] | permissive | def title_to_number(title: str) -> int:
total = 0
idx = 0
for i in title[::-1]:
total += (ord(i) - 64) * 26 ** idx
idx += 1
return total
print(title_to_number("AB"))
| true |
33aa739b945a5e0ad47d601a5223d145403fc441 | Python | davidthaler/FluentPython | /ch17_futures/futures.py | UTF-8 | 532 | 2.59375 | 3 | [] | no_license | # Example 17-3 from Fluent Python
from concurrent import futures
from seqential import save_flag, get_flag, show, main
MAX_WORKERS = 5
def download_one(cc):
img = get_flag(cc)
show(cc)
save_flag(img, cc.lower() + '.gif')
return cc
def download_many(cc_list):
num_workers = min(MAX_WORKERS, len(c... | true |
02120845cd6f46e8bc8dacfad56eac0e871c8d6c | Python | zopepy/leetcode | /mergeklist.py | UTF-8 | 1,184 | 3.40625 | 3 | [] | no_license | # Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def __str__(self):
return str(self.val)
def __repr__(self):
return str(self)
from heapq import heappush, heappop
class Solution:
def mergeKLists(self, lists):
""... | true |
ca883e2ba92cfbe18e27c4bba2386dfcd1c18e9f | Python | Vishesh-Sharma221/School-Projects | /read_uplow.py | UTF-8 | 544 | 4.4375 | 4 | [] | no_license | # Input File Name
print("\n\nEnter the name of the file : ")
file_name=str(input())
with open(file_name,"r") as file:
file.seek(0)
lines=file.read()
count_upper=0
count_lower=0
# Checking For Uppercase and Lowercase Letters
for items in lines:
if items.isupper():
count_upper+=1
elif items.... | true |
6bd38b4a5e7eeffa34e935f52303e5ef0a853f7b | Python | luizgustavodarossi/Pyhton | /ex034.py | UTF-8 | 244 | 3.859375 | 4 | [] | no_license | salario = float(input('Qual é o salário do funcionário? '))
if salario > 1250:
aumento = salario * 0.1
else:
aumento = salario * 0.15
print('Quem ganhava R${:.2f} passa a ganhar R${:.2f} agora'.format(salario,salario + aumento)) | true |
c17145f202edcad5698fceaede0a35c82abedfe8 | Python | Hermoine-Granger/Rectangle-Rise-and-Drop | /Rectangles.py | UTF-8 | 696 | 2.875 | 3 | [] | no_license | n=int(input())
recs=[]
mx_range=0
min_range=99999999999
for i in range(n):
x=tuple(map(int,input().split()))
recs.append(x)
mx_range=max(mx_range,x[1])
min_range=min(min_range,x[0])
height=[0 for i in range(0,mx_range+1)]
print(len(height))
for each in recs:
#print (each[0]," ",each[1])
x1... | true |
bc53e611d48be45bb82dc18afae921dc5ebc3ff1 | Python | dskut/euler | /25-fib.py | UTF-8 | 157 | 2.828125 | 3 | [] | no_license | #! /usr/bin/env python
fib = []
prev = 1
fib = 1
count = 2
while fib < 10**999:
tmp = fib + prev
prev = fib
fib = tmp
count += 1
print count
| true |
21b25ec87ec1cc611692f0cca9c90836eaa57b19 | Python | NielshuldC/Simulation-AOCS-APEX-CubeSat | /CAN_bus/sender.py | UTF-8 | 506 | 2.859375 | 3 | [] | no_license | #main.py -- put your code here!
# Sending message board
import pyb
from pyb import CAN
led = pyb.LED(3)# Using red LED from board to check if messages are sent
while True:
led.toggle()
pyb.delay(500)
can = CAN(1, CAN.NORMAL, extframe=True, prescaler=16, sjw=4, bs1=25, bs2=1)
# Receiver and sender shoul... | true |
104c9d5847e05aacff74171e338c4e4510432d95 | Python | TaraBlackburn/crowd-sound-affect | /src/rps_app.py | UTF-8 | 1,617 | 2.71875 | 3 | [] | no_license | import streamlit as st
import tensorflow as tf
from PIL import Image, ImageOps
from tensorflow.keras import models
import numpy as np
import os
import cv2
from tensorflow.keras.preprocessing import image
from tensorflow import keras
import sklearn
# loaded_model = models.load_model('/home/pteradox/Galvanize/capstones... | true |
b1e239b37b120ead40ed5b8d2bd3214bced67737 | Python | MijaToka/Random3_1415 | /Codficadores/rot13.py | UTF-8 | 461 | 3.53125 | 4 | [] | no_license | def rot13(char):
if ord(char)>=ord('A') and ord(char)<=ord('Z'):
rank = ord(char) - ord('A')
shiftedRank = (rank + 13) % 26
newOrd = shiftedRank + ord('A')
return chr(newOrd)
elif ord(char)>=ord('a') and ord(char)<=ord('z'):
rank = ord(char) - ord('a')
... | true |
269d42d6824ec940c9a7dcf9b9558684e46b3368 | Python | KupermanAlex/Zen_of_Python | /CardGame.py | UTF-8 | 1,399 | 3.296875 | 3 | [] | no_license | # import pygame
# import random
# from random import shuffle
# SUITS = ['heart','diamonds','spades','clubs']
# class Card :
# def __init__(self, rank,suit):
# self.rank = rank
# self.suit = suit
# def __repr__(self):
# return (f'{self.__class__.__name__}'f'(rank={self.rank!r}, suit={... | true |
7d854f18c4f5933cf1a3ff5503a4e03b6d380b1b | Python | Tirklee/python3-demo | /T2_47 Python 数组翻转指定个数的元素.py | UTF-8 | 1,440 | 4 | 4 | [] | no_license | # 实例 1
def leftRotate(arr, d, n):
for i in range(d):
leftRotatebyOne(arr, n)
def leftRotatebyOne(arr, n):
temp = arr[0]
for i in range(n - 1):
arr[i] = arr[i + 1]
arr[n - 1] = temp
def printArray(arr, size):
for i in range(size):
print("%d" % arr[i], end=" ")
arr = [1, ... | true |
4b3e87f2a8575894d6ab7f56691aecbdc2f39dbe | Python | google/agi | /vulkan_generator/vulkan_parser/internal/funcptr_parser.py | UTF-8 | 4,453 | 2.640625 | 3 | [
"Apache-2.0"
] | permissive | # Copyright (C) 2022 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writ... | true |
3fc0e315d8f9d2bb7f73413d2e0746e5726dc0c7 | Python | warun27/Association-Rules | /movies.py | UTF-8 | 2,255 | 3.15625 | 3 | [] | no_license | # -*- coding: utf-8 -*-
"""
Created on Fri Nov 13 04:41:54 2020
@author: shara
"""
import pandas as pd
import numpy as np
from mlxtend.frequent_patterns import apriori, association_rules
movies = pd.read_csv("F:\Warun\\DS Assignments\\DS Assignments\\Association Rules\\my_movies.csv")
movies.head()
movies.v... | true |
9d1e3438c03d52c9d729f9e188e19a4da8dab37d | Python | hidepin/dbviewer | /dbviewer.py | UTF-8 | 2,896 | 2.71875 | 3 | [] | no_license | #!/usr/bin/env python
import argparse
import sys
import os
import dropbox
# OAuth2 access token. TODO: login etc.
TOKEN = ''
parser = argparse.ArgumentParser(description='View Dropbox')
parser.add_argument('folder', type=str, nargs='?', default='download',
help='Folder name in your Dropbox')
par... | true |
d94e371733660bab8e31872b6d180a337e71b6db | Python | CMakerA/WiSync | /build/lib/WiSync/Ider.py | UTF-8 | 632 | 3.140625 | 3 | [
"MIT"
] | permissive | class Ider:
def __init__(self, prefix: str):
self.prefix = prefix
self.elements = list()
def __len__(self) -> int:
return len(self.elements)
def add(self, element) -> str:
self.elements.append(element)
return self.prefix + str(len(self))
class Iders:
btnIder =... | true |
7b8c13c54feb9784f43a8560c1ce93a0df8c4f28 | Python | guicavicci1997/ilana | /aula-23-08/histograma.py | UTF-8 | 714 | 3.1875 | 3 | [] | no_license | import cv2
# Biblioteca para plotar imagem com os eixos
from matplotlib import pyplot as plt
#Biblioteca para trabalhar com numeros
import numpy as np
imagem = cv2.imread("layne-staley2.jpg")
#cv2.imshow("Original", imagem)
#Determinando os metodos de cores que será convertido
#No caso, em tons de cinza
cinza = cv2.... | true |
b67c7ecdec520d6041f113ab8d3d8771a1b2e413 | Python | marqeta/marqeta-python | /tests/cards_merchant/test_cards_merchant_create.py | UTF-8 | 3,310 | 2.546875 | 3 | [
"MIT"
] | permissive | import unittest
import time
from tests.lib.client import get_client
from marqeta.errors import MarqetaError
class TestCardsMerchantCreate(unittest.TestCase):
"""Tests creating merchant cards"""
def setUp(self):
"""Setup each test."""
self.client = get_client()
def get_merchant(self):
... | true |
bdb0b82630fde9b06f56cd1aa886987747fecc2d | Python | dr-dos-ok/Code_Jam_Webscraper | /solutions_python/Problem_96/1844.py | UTF-8 | 696 | 3.21875 | 3 | [] | no_license | #!/usr/bin/env python
T = int(raw_input())
for i in xrange(T):
sum = 0
G = raw_input().split()
N = int(G[0])
S = int(G[1])
p = int(G[2])
# print N, S, p
for j in xrange(N):
n = int(G[j+3])
x = n/3
y = n%3
# print "--",n, x, y
if n == 0:
if p ... | true |
27008cb3dff020593b05ea2d32a4ef7bb46f1197 | Python | alpha-kwhn/Baekjun | /powerful104/6603.py | UTF-8 | 244 | 2.890625 | 3 | [] | no_license | import itertools as ite
while True:
li = list(map(int, input().split()))
if li[0]==0:
break
num=li[0]
del li[0]
lit = ite.combinations(li,6)
for i in lit:
print(" ".join(map(str,i)))
print() | true |
9b4e0268290528d3eea5a1d8bd3f41ab42d2c403 | Python | pedireddy/guvi1 | /poornabeg48.py | UTF-8 | 114 | 3.03125 | 3 | [] | no_license | num=int(input())
l=[int(x) for x in input().split()]
sum=0
for i in range(1,num+1):
sum=sum+i
print(sum//num)
| true |
58475ceb9eb99e26c7cfc4507d12b735a5e0206b | Python | tungminhphan/reactive_contracts | /components/robots.py | UTF-8 | 5,260 | 2.984375 | 3 | [
"LicenseRef-scancode-warranty-disclaimer",
"BSD-3-Clause"
] | permissive | #!/usr/local/bin/python
# Robot Class
# Tung M. Phan
# California Institute of Technology
# April 14, 2019
import imageio
import os
import numpy as np
from PIL import Image
import scipy.integrate as integrate
dir_path = os.path.dirname(os.path.realpath(__file__))
all_robot_types = {'1','2','3'}
class Robot:
def ... | true |
46ecd6085515330043d2d5a39b0e044ea9203b3f | Python | 2mohammad/lucky_number | /app.py | UTF-8 | 1,253 | 2.859375 | 3 | [] | no_license | from flask import Flask, render_template, jsonify, request
import requests
import random
from werkzeug.utils import redirect
app = Flask(__name__)
@app.route("/")
def homepage():
"""Show homepage."""
return render_template("index.html")
@app.route('/api/get-lucky-num', methods=["POST", "GET"])
def respons... | true |
0539ca564f8bc2c03f3f60faabbcf035673c9a9b | Python | JeroenDM/benchmark_runner | /benchmark_runner/scripts/run.py | UTF-8 | 2,835 | 2.546875 | 3 | [] | no_license | #!/usr/bin/env python
"""
This script runs a task.
It takes as a command line argument the planner group it has to use.
The task is read from the parameter server for now
(parameter: '/planning_task_path').
"""
import sys
import json
import datetime
import rospy
import rospkg
import rosparam
from nexon.robot import R... | true |
c3c550cf5e7e0cef99a8af92ab2656ee5090d0bf | Python | veezard/vid_scraper | /scrapers/simons.py | UTF-8 | 4,202 | 2.75 | 3 | [
"MIT"
] | permissive | import requests
import re
from bs4 import BeautifulSoup
from scrapers import Talk
from datetime import date
from dateutil.parser import parse as dateParser_
from scrapers import dateParse
from scrapers import removeParentheses
from scrapers import cleanSpeaker
import pickle
def scrape(start_date=date(1980, 1, 1), pro... | true |
7a449f989d5b3b4c48f9d58f0158b34fc00df9ea | Python | chalei/espectro32-micropython | /dht22.py | UTF-8 | 266 | 2.734375 | 3 | [] | no_license | from machine import Pin
import time
import dht
sensor = dht.DHT22Pin(26))
delay = 2
while True:
try:
sensor.measure()
print(sensor.temperature(), "C")
print(sensor.humidity(), "persen")
time.sleep(delay)
except OSError:
pass
| true |
feef2ff9f26bdbf42279fdef1ca8e06b7577f3bf | Python | FabrizioParker/Piggy | /student.py | UTF-8 | 10,270 | 3.21875 | 3 | [
"MIT"
] | permissive | from teacher import PiggyParent
import sys
import time
class Piggy(PiggyParent):
'''
*************
SYSTEM SETUP
*************
'''
def __init__(self, addr=8, detect=True):
PiggyParent.__init__(self) # run the parent constructor
'''
MAGIC NUMBERS <-- where we hard-code ... | true |
6802d69408cceaaabc72e7b2db1170b53912e5c1 | Python | ephracis/hermes | /utilities/strings.py | UTF-8 | 983 | 3.453125 | 3 | [
"MIT"
] | permissive | """ This file contains code for working with strings. """
import re
def fixName(category):
""" Turn the category name into human readable form. """
exceptions = ['a', 'an', 'of', 'the', 'is', 'and', 'with', 'by']
fixed = title_except(re.sub('_',' ',category), exceptions)
if fixed == "App Wallpaper":
fixed = "Li... | true |
a5f683df759304a3406cb32a6c7a4d16e9865230 | Python | 57066698/simpleRotate | /rotateExample/ex0.1-Calculate-RM-by-3P.py | UTF-8 | 568 | 2.671875 | 3 | [] | no_license | # successed
import numpy as np
from rotateExample.scenes.rotateScene import RotateScene
rotateScene = RotateScene()
def cal():
rotation = rotateScene.axis1.transform.rotation
p1 = [1, 0, 0]
p2 = [0, 1, 0]
p3 = [0, 0, 1]
P = np.stack([p1, p2, p3], axis=1)
p1_ = np.dot(rotation, [1, 0, 0])
... | true |
7087570f625e02b4e8ee59177ee2e42dce2fb941 | Python | dundunmao/lint_leet | /mycode/lintcode/Binary Tree & Divide Conquer/95 Validate Binary Search Tree.py | UTF-8 | 3,171 | 3.890625 | 4 | [] | no_license | # -*- encoding: utf-8 -*-
# 给定一个二叉树,判断它是否是合法的二叉查找树(BST)
#
# 一棵BST定义为:
#
# 节点的左子树中的值要严格小于该节点的值。
# 节点的右子树中的值要严格大于该节点的值。
# 左右子树也必须是二叉查找树。
# 一个节点的树也是二叉查找树。
# 您在真实的面试中是否遇到过这个题? Yes
# 样例
# 一个例子:
#
# 2
# / \
# 1 4
# / \
# 3 5
# 上述这棵二叉树序列化为 {2,1,4,#,#,3,5}.
class TreeNode:
def __init__(self, val):
self.... | true |
2eab3b12267e49248803b14b55c9eecbe8418f26 | Python | UmbertoFasci/sdm-python | /project/b_data_processing/scripts/prepare_files.py | UTF-8 | 2,865 | 2.796875 | 3 | [
"MIT"
] | permissive | import os
import datetime
import pandas as pd
def _only_chosen(bag_of_files, infile, file_end):
f_list = []
for f in bag_of_files:
if f.endswith(file_end):
for rec in infile:
if rec in f:
f_list.append(f)
return f_list
def get_filelist(folder, infi... | true |
aad7ef7b5caa7c8c105228666f794a1fccdb45d4 | Python | kidusasfaw/addiscoder_2016 | /labs/server_files/lab7/fromListToMatrix/fromListToMatrix.py | UTF-8 | 725 | 3.234375 | 3 | [] | no_license |
def fromListToMatrix():
num_nodes = int(raw_input())
list_graph = []
for i in range(num_nodes):
nodes = raw_input()
int_nodes = [int(elem) for elem in nodes.split()]
list_graph.append(int_nodes)
print list_graph
ans = []
for i in xrange(len(list_graph)):
ans ... | true |
61aa51604f9db9e6c0e3381a61b2f50b69b8ece5 | Python | kervynj/Trending-Value-Python-web-data-via-CGI | /data_search.py | UTF-8 | 1,299 | 2.65625 | 3 | [] | no_license | #!/usr/bin/python
import cgi
import csv
import cgitb; cgitb.enable()
print "Content-Type: text/html\n"
#Get requested company from user form input
form = cgi.FieldStorage()
ticker = form.getvalue('ticker')
if ".to" in ticker:
#Open TSX daily data
TSX_object = open('TSX_master.csv','rU')
TSX_data = csv.reader(TSX_... | true |
cd7bc9b61c7deb6ccfe5935067af49034be8b2d0 | Python | bopopescu/pythonFist | /src/ziptest/readercsv.py | UTF-8 | 140 | 2.703125 | 3 | [] | no_license |
import csv
with open('names.csv', newline='') as f:
reader = csv.reader(f)
for row in reader:
print(row)
| true |
20c994ed0208d461a43e71af763b9eba009a08a9 | Python | ZhangYet/vanguard | /myrtle/befor0225/remove_invalid_parentheses.py | UTF-8 | 867 | 3.484375 | 3 | [] | no_license | # https://leetcode.com/problems/remove-invalid-parentheses/
from typing import List
class Solution:
def removeInvalidParentheses(self, s: str) -> List[str]:
def _is_valid(s: str):
stack = []
for c in s:
if c == '(':
stack.append(c)
... | true |
4c502c21252d98482a5e2a6de164552497851ffa | Python | malhotra1432/rasa-1 | /rasa/shared/utils/common.py | UTF-8 | 3,897 | 3.15625 | 3 | [
"Apache-2.0",
"MIT",
"LicenseRef-scancode-generic-cla"
] | permissive | import importlib
import logging
from typing import Text, Dict, Optional, Any, List, Callable, Collection
logger = logging.getLogger(__name__)
def class_from_module_path(
module_path: Text, lookup_path: Optional[Text] = None
) -> Any:
"""Given the module name and path of a class, tries to retrieve the class.
... | true |
760b44eab9274bd3bce1d3d57c1780f45b3d5236 | Python | Jokezor/Instagram | /insta_main.py | UTF-8 | 882 | 2.59375 | 3 | [] | no_license | '''
This is the main script which will handle all of the functions of the isntagram
scraper, bot and statistics etc.
'''
# Own code
import init
import Database_talk
# Creates all databases/tables needed for accounts.
def setup(path_db, path_acc):
# Creates the database
init.setup_database(path_db, path_acc)
#... | true |