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 |
|---|---|---|---|---|---|---|---|---|---|---|
73f859bcff52ac610e0f2647976a64924a125e6c | adamhammes/advent-of-code | /aoc_2019/tests/test_day10.py | UTF-8 | 2,596 | 3.015625 | 3 | [] | no_license | import unittest
from day10 import *
MY_EXAMPLE = """
..#..
..#..
#####
..#..
..#..
"""
MY_EXAMPLE_2 = """
######
"""
EXAMPLE_1 = """
.#..#
.....
#####
....#
...##
""".strip()
EXAMPLE_2 = """
......#.#.
#..#.#....
..#######.
.#.#.###..
.#..#.....
..#....#.#
#..#....#.
.##.#..###
##...#..#.
.#....####
""".strip()
... | true |
e4d6dc2e739e78d881db445e40b422a7ca5afb49 | JakeRoggenbuck/dot_dropper | /main.py | UTF-8 | 1,115 | 2.609375 | 3 | [
"MIT"
] | permissive | from jakesutils.config import Config
import subprocess
import yaml
class CopyDot:
def __init__(self, in_use: str, in_git: str):
self.in_use = in_use
self.in_git = in_git
def get_diff(self):
check_nums = []
for check in ["^<", "^>"]:
check_num = subprocess.check_out... | true |
e6815ed5057cd212cb0383d1994dcacfc2995f7e | martinapinky/Generate-prime-numbers | /test_generateprimenumbers.py | UTF-8 | 724 | 3.515625 | 4 | [] | no_license | from unittest import TestCase
from generate_prime_numbers import generateprimenumbers
class TestPrimeGenerator(TestCase):
def test_correct_output(self):
self.assertListEqual([2, 3, 5, 7], generateprimenumbers(10))
def test_one_in_result(self):
self.assertFalse(1 in generateprimenumbers(10), ms... | true |
9816e2ff197247a435dc316c8394b6f277f2ae77 | pixelogik/NearPy | /nearpy/storage/storage_redis.py | UTF-8 | 7,994 | 2.515625 | 3 | [
"MIT"
] | permissive | # -*- coding: utf-8 -*-
# Copyright (c) 2013 Ole Krause-Sparmann
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# -*- coding: u... | true |
6b85568fe65fb035dd812b00056cfd58bd89f30d | dinhtrungvn92/voip-bot | /src/bothelper.py | UTF-8 | 1,620 | 2.53125 | 3 | [] | no_license | import soundfile as sf
import clipaudiomodule as ca
import bingspeechmodule as bs
import bingttsmodule as bt
import luismodule as luis
import requests
class BotHelper():
def convert_audio(self):
myfile = sf.SoundFile('/home/trungbd1/input.wav', mode='r', format='RAW',
sample... | true |
b85e5a352390efc64761b2290d8dbf2b8df18015 | SmallJimbo/Textgame | /introtest.py | UTF-8 | 413 | 2.671875 | 3 | [] | no_license | import game.Game
def start():
print("It's 2am")
print("*********************************************************")
print("**** DND *********** Text Based game *********** DND ****")
print("**** made by Dana & Axel ****")
print("**** ****... | true |
5d1b97d4c97c827e965eff3351636de5d04591cb | yumengch/InferDynPaper | /plotting/analysis_CLVs.py | UTF-8 | 5,350 | 2.59375 | 3 | [
"MIT"
] | permissive | """amplitude of CLVs for line plot."""
import numpy as np
import matplotlib.pyplot as plt
import subprocess
import os
import matplotlib.cm as cm
from matplotlib import colors
import matplotlib.markers as mrks
def plot(field, F, G, alpha, gamma, is_alpha):
# cmap2 = cm.get_cmap(,lut=15)
# cmap2.set_u... | true |
1a942e19f975603ea296e2600f52763a44962eeb | marie-elia/Python-Course | /assignment1/1-c.py | UTF-8 | 1,214 | 3.84375 | 4 | [] | no_license | # -*- coding: utf-8 -*-
"""
Created on Tue Jun 11 23:25:53 2019
@author: marie
"""
POST=input("enter postal code in this form LDL DLD where L is a letter in [A-Z] and D is a digit in [0-9]")
#first of all check that there is a space in between the first and second 3 chracters
if (POST[3] !=" "): ... | true |
6b528e16ca3aa2f6860a0a6e197eb2749b8ddb2d | naziknovak/Hillel | /hw6.py | UTF-8 | 3,843 | 3.96875 | 4 | [
"MIT"
] | permissive | txt = "the first letter is capital"
x = txt.capitalize()
print(x)
txt = "The first letter in lower case"
x = txt.casefold()
print(x)
txt = "The text is displayed in the center"
x = txt.center(50)
print(x)
txt = "There are _ letters 't' in this string"
x = txt.count("t")
print(f"There are {x} letters 't' in this stri... | true |
551513e76d5a6b9db73305719ef01c84b96e8f37 | dilipRathoreRepo/data_structures | /stacks_queues_deques/deque.py | UTF-8 | 1,205 | 4.5 | 4 | [] | no_license | """
It is also known as double ended queue. It is ordered collection. It has two ends, front and rear.
New items can be added either at front or rear.
"""
class Deque(object):
def __init__(self):
self.deque = []
def addFront(self, item):
self.deque.append(item)
def removeFront(self):
... | true |
954acfe15291ee264a1c645ed3f1cf0abd0f6bcc | linshaoxin-maker/taas | /models/NTM.py | UTF-8 | 1,822 | 2.5625 | 3 | [
"MIT"
] | permissive | import torch
from torch import nn
from models.utils import kld_normal, topic_covariance_penalty
class NTM(nn.Module):
def __init__(self, hidden, normal, h_to_z, topics):
super(NTM, self).__init__()
self.hidden = hidden
self.normal = normal
self.h_to_z = h_to_z
self.topics ... | true |
39877a3a62d13facf5d1a8f094606824360f1658 | taogangshow/python_Code | /第1章 python基础/Python基础05/1-匿名函数.py | UTF-8 | 326 | 3.359375 | 3 | [] | no_license | def test1(a, b):
return a+b
result1 = test1(11,22)
test2 = lambda a,b:a+b
result2 = test2(11,22)#调用匿名函数
print("result1=%d,result2=%d"%(result1, result2))
def test3(c,d):
return c+d
result3 = test3(33,44)
test4 = lambda c,d:d-c
result4 = test4(33,44)
print("result3=%d,result4=%d"%(result3,result4))
| true |
b1080afbe8e877777c3d5602b22f6bb01a10a7b2 | Aasthaengg/IBMdataset | /Python_codes/p02796/s784010171.py | UTF-8 | 344 | 2.75 | 3 | [] | no_license | import copy
import numpy as np
n=int(input())
xl=[]
for i in range(n):
x,l = map(int,input().split())
xl.append([x-l,l+x])
#print(xl)
xl = sorted(xl, key=lambda x: x[0],reverse=True)
#print(xl)
ans=0
r=2*(10**9+1)
for i in range(n):
if xl[i][1]>r:
continue
if xl[i][0]<=r:
r=xl[i][0]
#print("r",... | true |
f82bef2497a4668dd7906ffd9e0fc65ad0190970 | namhyun-gu/algorithm | /baekjoon/union_find/1976.py | UTF-8 | 1,069 | 2.9375 | 3 | [] | no_license | # region Input redirection
import io
import sys
example = """
3
3
0 1 0
1 0 1
0 1 0
1 2 3
"""
sys.stdin = io.StringIO(example.strip())
# endregion
#
# ⛔ DO NOT COPY ABOVE CONTENTS
#
import sys
def find(group, x):
if group[x] == x:
return x
group[x] = find(group, group[x])
return group[x]
def un... | true |
26a0ce46cb7e1ece094e83477833cf1fe09d9379 | ZerxXxes/ipv6board | /ipv6-board.py | UTF-8 | 2,341 | 2.84375 | 3 | [] | no_license | #!/usr/bin/env python3
from scapy.all import *
from queue import Queue
from threading import Thread
import dothat.backlight as backlight
import dothat.lcd as lcd
import time
import sys
# The /64 IPv6 prefix
prefix = "2001:6b0:1001:105"
# Read from the queue
def reader_proc(queue):
# Create rows
rows = [" ","... | true |
98ba626db10a49de45d4408f7fc7e0acd7ae3460 | mystery2828/pythonfiles | /queueusing1stack.py | UTF-8 | 389 | 3.609375 | 4 | [] | no_license | import time
start = time.time()
class Queue1Stack(object):
def __init__(self):
self.stack = []
def enqueue(self,item):
self.stack.append(item)
def dequeue(self):
return self.stack.pop(0)
q = Queue1Stack()
for i in range(5000):
q.enqueue(i)
for ... | true |
78c8eb145ac7b2867a47fa68b9d456bf336dc12f | matteogabburo/DM_BD_Project2016 | /libraries/tests/words_distribuition.py | UTF-8 | 1,975 | 2.703125 | 3 | [] | no_license | #!/usr/bin/env python3.5
import sys
from operator import itemgetter
sys.path.append('..')
import utils.http_requests as http
sys.path.remove('..')
def avg_list(numbers):
res = 0.0
numbers = [n for n in numbers if n > -100]
if len(numbers) > 0:
for number in numbers:
res += number
return res / len(numbers... | true |
960ed2c19e9d598634d7aef513fe39c5441b8bec | PetrPrazak/AdventOfCode | /2016/12/aoc2016_12.py | UTF-8 | 1,376 | 3 | 3 | [] | no_license | # http://adventofcode.com/2016/day/12
from __future__ import print_function
from collections import defaultdict, Counter
def emulate(prog, registers):
ip = 0
while ip < len(prog):
op, *args = prog[ip]
if op == "cpy":
src, dest = args
registers[dest] = int(src) if src.is... | true |
3653e9a29fe809b9456c22cb63ed84d0343bf706 | lohith261201/UE19CS305-MI-LAB | /PES2UG19CS203 (5).py | UTF-8 | 7,792 | 3.75 | 4 | [] | no_license | import numpy as np
class Tensor:
"""
Tensor Wrapper for Numpy arrays.
Implements some binary operators.
Array Broadcasting is disabled
Args:
arr: Numpy array (numerical (int, float))
requires_grad: If the tensor requires_grad (bool)(otherwise gradient dont apply to the ... | true |
05dae957969b19d117400625fc2b9dfadf931a71 | chenhh/Uva | /uva_10336_graph.py | UTF-8 | 1,935 | 3.171875 | 3 | [] | no_license | # -*- coding: utf-8 -*-
"""
Authors: Hung-Hsin Chen <chenhh@par.cse.nsysu.edu.tw>
License: GPL v2
status: AC
difficulty: 2
https://uva.onlinejudge.org/external/103/10336.pdf
http://luckycat.kshs.kh.edu.tw/homework/q10336.htm
"""
import sys
# N, E, S, W
directions = ((-1, 0), (0, 1), (1, 0), (0, -1))
def connected... | true |
501c276db5668b278b3a88c1bd010570f4c85845 | zhangyafeii/Flask | /CodeStatistics/files/7b04e56a-40bb-4ea1-bd3e-58e10ae40e39/django_page/app02/views.py | UTF-8 | 1,716 | 2.5625 | 3 | [
"MIT"
] | permissive | from django.shortcuts import render,HttpResponse,redirect
from django import forms
from django.forms import fields
class F1Form(forms.Form):
username = fields.CharField(max_length=18,min_length=6,required=True,
error_messages={'required':'用户名不能为空','max_length':'太长了','min_length':'... | true |
a123384f0a2602df5f7ed6ae39628e8df2bd602c | Jahnavi-Jonnalagadda/100DaysOfCode | /LeetCode/Easy/Plus_One.py | UTF-8 | 974 | 3.453125 | 3 | [] | no_license | # Approach-1
def plus_one(arr):
n = len(arr)
arr[n-1] += 1
carry = arr[n-1]//10
arr[n-1] = arr[n-1]%10
for i in range(n-2, -1, -1):
if(carry == 1):
arr[i] += 1
carry = arr[i]//10
arr[i] = arr[i]%10
if(carry == 1):
arr.insert(0, 1)
return ... | true |
af7a37e1b9ff1b6c00617a692f5619d3d530c659 | elisamussumeci/dijkstra-usa-roads | /rodovias.py | UTF-8 | 5,055 | 3.265625 | 3 | [] | no_license | import heapq
from csv import *
estradas = {1:{'status':None,'neighbor':{2:3,5:2 },'cost':10000,'from':None,'latitude':1, 'longitude':2},
2:{'status':None,'neighbor':{1:3,3:2,5:0},'cost':10000,'from':None, 'latitude':4, 'longitude':5},
3:{'status':None,'ne ighbor':{2:2,4:4,5:6},'cost':10000,'fro... | true |
4f0b1a685bf8f0a42f3b0b3afef4529fab889d1e | jordandjp/Degrees | /util.py | UTF-8 | 1,361 | 3.5625 | 4 | [] | no_license | class Node():
def __init__(self, state, parent, action):
self.state = state
self.parent = parent
self.action = action
class StackFrontier():
def __init__(self):
self.frontier = []
# Create set to improve searching of node explored
self.node_state = set... | true |
495b1c7af3a2d056758ab0b69d3a4ca79526ffc9 | joacorapela/figsResultsAndErrorsFromIzhikevich2007 | /scripts/problems/ch4/p11/doIntegrateStableFocus.py | UTF-8 | 1,569 | 2.625 | 3 | [] | no_license |
import sys
import numpy as np
import pdb
import matplotlib.pyplot as plt
from scipy.integrate import ode
from utils import buildMatrixFromArraysList
def main(argv):
a = -1.0
b = 1.0
c = 2.0
x0 = -0.7
y0 = 1.0
t0 = 0.0
tf = 15.0
dt = 1e-5
xBounds = [-10, 10]
yBounds = [-10, 10]
... | true |
f5217e0065f1f5c2d7bdd779a3414e52c15161d1 | philipkarim/CNN-and-logisitc-regression--FysStk4155 | /src/logreg_real_pics_predict.py | UTF-8 | 3,238 | 2.671875 | 3 | [] | no_license | #Import modules
from skimage.transform import resize
from skimage.color import rgb2gray
import glob
import numpy as np
import matplotlib.pyplot as plt
import sklearn.linear_model as lm
from sklearn.utils import shuffle
import skimage.io
from utils import heatmap, accuracy
size=224
#Defining lists
real_pic_mask_list ... | true |
abe0dfcfda65bcc59bffb7bf0089e7c8a6c3c06b | ericg108/scikit-learn-try | /test/utils/one_hot_encoding_all.py | UTF-8 | 3,762 | 2.6875 | 3 | [] | no_license | __author__ = 'nenggong'
import numpy as np
import pandas as pd
from sklearn import preprocessing
from sklearn.preprocessing import Imputer
from sklearn.feature_extraction import DictVectorizer as dv
from sklearn.linear_model import SGDRegressor
from sklearn.linear_model import SGDClassifier
from sklearn.linear_model i... | true |
63f5ba0250d6a952943313794e5d07be1a5f66ee | vertexproject/synapse | /synapse/lib/crypto/tinfoil.py | UTF-8 | 3,875 | 2.984375 | 3 | [
"Apache-2.0"
] | permissive | import os
import logging
import itertools
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
import synapse.exc as s_exc
import synapse.lib.msgpack as s_msgpack
logger = logging.getLogger(__name__)
def newkey():
'''
Generate a new, random... | true |
9f4afe9afe2f878433d7d54f93343db7abcbe457 | vietanhtran2710/projectEuler | /triangularPentagonalAndHexagonal.py | UTF-8 | 441 | 3.078125 | 3 | [] | no_license | def solve(a, b, c):
from math import sqrt
delta = (b ** 2) - (4 * a * c)
if delta < 0:
return 1.5
else:
return (-b + sqrt(delta)) / (2 * a)
t = 2
while True:
# print(t)
triangle = t ** 2 + t
p = solve(3, -1, -triangle)
if p != int(p):
if t == 285:
break
t += 1
continue
h = solve(4, -2, -triangle... | true |
994d1d3822cd06e93d8ea8f29f08d6130fcf20fe | litvinovserge/WebAcademy | /HomeWork_01/Task_5.py | UTF-8 | 714 | 4.03125 | 4 | [] | no_license | '''
Задача №5
Дано число n. С начала суток прошло n минут.
Определите, сколько часов и минут будут показывать электронные часы в этот момент.
Программа должна вывести два числа: количество часов (от 0 до 23) и количество минут (от 0 до 59).
Учтите, что число n может быть больше, чем количество минут в сутках.
'''
n = ... | true |
e8d68c9fd288e9a45ef7ee94bd58959cfd276af8 | vargheseashik/python | /imports_module/number_sqr_limit.py | UTF-8 | 231 | 3.578125 | 4 | [] | no_license | import math
inc=int(input("enter the number"))
ll=int(input("enter the upper limit"))
ul=int(input("enter the lower limit"))
for i in range(1,ul+1):
num=math.pow(i,inc)
if(num>ll)and(num<ul):
print(num,"is",i,inc) | true |
80bf3a8e7f5b3c5e910518fb6d01b800fcc2d631 | javierivanov/MLP-models-for-regression | /capstone_project/zillow_project/utils.py | UTF-8 | 1,236 | 3.453125 | 3 | [] | no_license | import tensorflow as tf
import math
def xavier_init(n_inputs, n_outputs, uniform=True):
"""Set the parameter initialization using the method described.
This method is designed to keep the scale of the gradients roughly the same
in all layers.
Xavier Glorot and Yoshua Bengio (2010):
Understandi... | true |
495add90fd35b7cc63a1c5cfb830809c4721f943 | menwhitehead/NPANN | /npann/Optimizers/RMSProp.py | UTF-8 | 822 | 2.78125 | 3 | [] | no_license | from npann.Utilities.misc_functions import *
from Optimizer import Optimizer
class RMSProp(Optimizer):
def __init__(self, learning_rate=0.01, gamma=0.9):
self.learning_rate = learning_rate
self.gamma = gamma
self.prev_updates = {}
self.little = 1E-7 # Don't divide by zero!
d... | true |
21faf843afdeb781c1c19656871aefb721200f04 | nholaday/tabletennis | /tabletennis_rand.py | UTF-8 | 706 | 3.265625 | 3 | [] | no_license | #!/usr/bin/env python
#Created by Nic Holaday 2018
#nholaday@gmail.com
"""
Takes in a csv with a column of advanced players and beginner players.
Assigns each advanced player with a random beginner player for random
but even teams.
"""
import csv
import random
cola, colb = [], []
with open('Table_Tennis_Teams.csv') a... | true |
f4e1e2c1e436b1d3aaf5ec5367a90775ec5960ed | qianyu-berkeley/data_engineering | /shared/utils.py | UTF-8 | 2,592 | 2.78125 | 3 | [
"MIT"
] | permissive | import os
from datetime import datetime, timedelta
from itertools import islice
import pytz
from etlexceptions import ETLException
from pytz import timezone
def oscmd_rmfile(filename):
"""
Removes the file by full path
"""
os.remove(filename)
return
def gp_validate_date(date_str):
try:
... | true |
49c542b82782500c19cad36f10b37d156a63bf9e | freakimkaefig/itt_lamm_lechler | /Kopie von classify.py | UTF-8 | 17,275 | 2.546875 | 3 | [] | no_license | #!/usr/bin/env python
# coding: utf-8
# -*- coding: utf-8 -*-
from pyqtgraph.flowchart import Flowchart, Node
from pyqtgraph.flowchart.library.common import CtrlNode
import pyqtgraph.flowchart.library as fclib
from pyqtgraph.Qt import QtGui, QtCore
import pyqtgraph as pg
from scipy import fft
import numpy as np
impor... | true |
98c368df0bddfa5948d4756703844d93480941dd | rghiglia/ML_ND_Projects | /smartcab/Version1/smartcab/agent_20160606_bkp.py | UTF-8 | 12,179 | 2.96875 | 3 | [] | no_license | import sys
sys.path.append(r'C:\Users\rghiglia\Documents\ML_ND\smartcab\smartcab')
sys.path.append(r'C:\Users\rghiglia\Documents\ML_ND\smartcab\images')
import random
from environment import Agent, Environment
from planner import RoutePlanner
from simulator import Simulator
import numpy as np
import pandas as pd
impor... | true |
aae51fe6877b145cb10622dcb47f9d41ec3d9059 | SkyLoveAngle/Python | /mypy-04.py | UTF-8 | 327 | 4.21875 | 4 | [] | no_license | import turtle
import math
#定义多个点
x1,y1=100,100
x2,y2=100,-100
x3,y3=-100,-100
x4,y4=-100,100
#绘制折线
turtle.penup()
turtle.goto(x1,y1)
turtle.pendown()
turtle.goto(x2,y2)
turtle.goto(x3,y3)
turtle.goto(x4,y4)
#计算起始点和终点的距离
distance=math.sqrt((x1-x4)**2+(y1-y4)**2)
turtle.write(distance)
| true |
ca4fdd0ddd11e178634243614dc34430f7308c43 | Drom0s137/Python-Zombie-Survival-Game | /Summative V3.py | UTF-8 | 18,764 | 2.703125 | 3 | [] | no_license | from pygame import *
import random
init()
#screen and variables initialization setup**************************************
size = width, height = 1000, 700
screen = display.set_mode(size)
button = 0
pos = 0
page = 0
charx = 500
chary= 350
gameTimer = 0
vitality = 100
#booleans setup***********************... | true |
fdd9479b64f6805e4d9dc6618221e8e2b2ae79f6 | gasser277/Data-Structures-and-Algorithms | /Basic Algorithms/Dutch_National_Flag_Problem_Sorting_Algorithm_Efficient.py | UTF-8 | 958 | 3.71875 | 4 | [] | no_license | def sort_012(arr):
i_current= 0
i_0= 0
i_2 = len(arr) - 1
while(i_current) < i_2 + 1:
current_val = arr[i_current]
if current_val == 0:
arr[i_current] = arr[i_0]
arr[i_0] = current_val
i_0+= 1
i_current+= 1
elif current_v... | true |
6370c6dde950d2ff79d57f03dc6041d45a464392 | sidv/Assignments | /Govind_Gopal/one_emp.py | UTF-8 | 384 | 3.734375 | 4 | [] | no_license | emp = {}
print ("Enter the employee details")
name = input("Enter the name")
age = input("Enter the age")
place = input("Enter his place of origin")
salary = input("Enter the salary")
prev_emp = input("Enter their previous employeer")
emp["Name"] = name
emp["Age"] = age
emp["Place of origin"] = place
emp["Current sala... | true |
f5f436d34a9c15f3a8e0b035f80a21e8c56db50f | novayo/LeetCode | /Tutorials/example_lc473_version_1.py | UTF-8 | 851 | 3 | 3 | [] | no_license | class Solution:
def makesquare(self, matchsticks: List[int]) -> bool:
'''
分成四等分,每一份一樣長
'''
_sum = sum(matchsticks)
if _sum % 4 != 0:
return False
equal = _sum // 4
def recr(idx, s1, s2, s3, s4):
if idx >= len(matchsticks):
... | true |
6d7d7005d054a0d53c480ed6e2552fee7c09fff0 | VincentVanBork/SE_DS_AI | /Graphs/BFS.py | UTF-8 | 1,092 | 3.171875 | 3 | [] | no_license | from graphs import graph, graph_path
from queue import Queue
routes = []
routes_weights = []
def BFS(g, current_node):
print(g)
layer = g.all[current_node]
checking_now = Queue()
for node in g.current[current_node]:
checking_now.put(node)
g.reset_graph()
while not checking_now.empty(... | true |
30198e0c771f83b9cf295eac76af83b122e69332 | hitochan777/kata | /atcoder/agc038/A.py | UTF-8 | 228 | 3.5625 | 4 | [] | no_license | H, W, A, B = (int(x) for x in input().split())
for i in range(H):
for j in range(W):
if i < B and j < A:
print(0, end="")
elif i < B or j < A:
print(1, end="")
else:
print("0", end="")
print() | true |
7b73cac38a1d89fe624b84bb75d7dda014fcb8b3 | lovemineyue/mytest | /old_practice/11GPU.py | UTF-8 | 1,904 | 3.34375 | 3 | [] | no_license | import mxnet as mx
from mxnet import nd
from mxnet.gluon import nn
print(mx.cpu(), mx.gpu())
x = nd.array([1, 2, 3])
# print(x.context)
# a = nd.array([1, 2, 3], ctx=mx.gpu())
# print(a)
# B = nd.random.uniform(shape=(2, 3), ctx=mx.gpu(1))
# 除了在创建时指定,我们也可以通过copyto函数和as_in_context函数在设备之间传输数据。下面我们将内存上的NDArray变量x复... | true |
78a4773d69504fc8059da69a5d7078a5030569cf | mgmk2/atcoder-python | /ABC/197/d.py | UTF-8 | 421 | 3.046875 | 3 | [] | no_license | import numpy as np
n = int(input())
x0, y0 = map(int, input().split())
xn_2, yn_2 = map(int, input().split())
p0 = np.array([x0, y0], dtype=float)
pn_2 = np.array([xn_2, yn_2], dtype=float)
c = (p0 + pn_2) / 2
z0 = p0 - c
theta = 2 * np.pi / n
A = np.array([[np.cos(theta), -np.sin(theta)],
... | true |
372b07f7e5bcece18783cb27961cc9b1bf0a2d5c | Cute-Monster/RasPi_DND_Server | /src/Models/Entity.py | UTF-8 | 791 | 2.5625 | 3 | [] | no_license | """
Entity.py: Module for representing base Entity class
"""
__author__ = "Runtov Constantin, Mandrila Daniel"
__copyright__ = "Copyright 2020, The Earth"
__credits__ = ["Runtov Constantin", "Mandrila Daniel"]
__license__ = "USM"
__version__ = "0.1.5"
__maintainer__ = "Gheorghe Latul"
__email__ = "ghostshow@yandex.ru "... | true |
31e3d5d3621bd0581fbbbf87966e73a1863eaea6 | niavivek/Python_programs | /all_files/hw10/user_similarity_template.py | UTF-8 | 2,189 | 2.671875 | 3 | [] | no_license | ###
###
# Author Info:
# This code is modified from code originally written by Jim Blomo and Derek Kuo
##/
from mrjob.job import MRJob
from mrjob.protocol import JSONValueProtocol
from mrjob.step import MRStep
class UserSimilarity(MRJob):
INPUT_PROTOCOL = JSONValueProtocol
def mapper1_extract_user_business(s... | true |
0d49a43db66b8499924227510216bc0eb0ad9255 | MelicHamtes/EMA | /SEM_USO/db_experimento.py | UTF-8 | 2,242 | 3.09375 | 3 | [] | no_license | import sqlite3
import os
import platform
class Teste:
def __init__(self):
if platform.system() == 'Linux':
dir_path = '/home/melic/PROJETOS/LP/EMA/Banco_armazenamento/db/'
elif platform.system() == 'Windows':
dir_path = os.path.dirname(os.path.realpath(__file__)) + '\\db\\Ema.db'
conexao = sqlite3.conn... | true |
7c687f191a3c00df68ffe5b797954c55b523484a | borisboychev/SoftUni | /Python_Advanced_Softuni/Comprehensions_Lab/venv/flattering_matrix.py | UTF-8 | 201 | 3.03125 | 3 | [
"MIT"
] | permissive | def read_matrix(n):
return [map(int , input().split(', ')) for _ in range(n)]
n = int(input())
matrix = read_matrix(n)
flattened = [num for sublist in matrix for num in sublist]
print(flattened) | true |
4aef58f8266fbd7c8a115d9f0943e11416da6fc3 | biancapolk/Shipwell_Training | /generators_tutorial/generators.py | UTF-8 | 208 | 2.984375 | 3 | [] | no_license | def genfibon(n):
"""
This program generates a fibonnaci sequence
"""
a = 1
b = 1
for i in range(n):
yield a
a,b = b,a+b
for num in genfibon(10):
print(num) | true |
e8c260474d2fbfc37b418ba05a7327ff2642d8dd | wyaadarsh/LeetCode-Solutions | /Python3/0760-Find-Anagram-Mappings/soln.py | UTF-8 | 378 | 2.796875 | 3 | [
"MIT"
] | permissive | class Solution:
def anagramMappings(self, A, B):
"""
:type A: List[int]
:type B: List[int]
:rtype: List[int]
"""
m = collections.defaultdict(list)
for idx, val in enumerate(B):
m[val].append(idx)
res = []
for idx, val in enumerate(A... | true |
36af85746aa11c2ef1924c85264834f937e7fa5c | HForrest/DropboxBulkModify | /DropboxBulkModifyCL.py | UTF-8 | 2,117 | 2.71875 | 3 | [
"Unlicense"
] | permissive | import pandas as pd
import dropbox
from tqdm import tqdm
from dropbox import DropboxOAuth2FlowNoRedirect
'''
This sets up a dropbox OAuthed client
'''
APP_KEY = 'xxx'
APP_SECRET = 'xxx'
auth_flow = DropboxOAuth2FlowNoRedirect(APP_KEY, APP_SECRET)
authorize_url = auth_flow.start()
print("1. Go to: " +... | true |
f21d90d145f25a99c7efb6911e571df4313bb588 | wgq1134711420/shiye_kf3 | /kafka_stream/dwd_news_yq/config/__init__.py | UTF-8 | 354 | 2.796875 | 3 | [] | no_license |
import configparser
import os
# 实例化configparser
conf = configparser.ConfigParser()
# 获取当前的绝对路径
current_path = os.path.abspath(__file__)
# 获取配置文件夹
current_dir = os.path.dirname(current_path)
# 拼接配置文件路径
config_path = os.path.join(current_dir, 'config.ini')
# 读取config.ini
conf.read(config_path)
| true |
d6259cc95f11637bf002cf37278b027a3747ed1b | gsx0/Feature-Generating-Networks | /trainer.py | UTF-8 | 9,581 | 2.5625 | 3 | [] | no_license | import torch
import torch.autograd as autograd
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.distributions import uniform, normal
import os
import numpy as np
from sklearn.metrics import accuracy_score
from models import Generator, Discriminator, MLPClassifier, Resnet101... | true |
d845ccdbf83f03a35133972a544b5b5f64d9623a | nik-052/Mail-generator | /Email.py | UTF-8 | 519 | 2.671875 | 3 | [] | no_license | # Import smtplib for the actual sending function
import smtplib
from email.mime.multipart import MIMEMultipart
msg = MIMEMultipart()
COMMASPACE = ', '
# Create the container (outer) email message.
msg['Subject'] = 'Our family reunion'
me ='me@gmail.com'
family = 'you@gmail.com, uncle@gmail.com'
msg['From'] =... | true |
b565d6bc7e2bb9ea3986db691d1c310bdcb8c18b | Rex--/pythang | /hangman.py | UTF-8 | 6,017 | 2.984375 | 3 | [] | no_license | import random
import linecache
from Tkinter import *
from functools import partial
word = ''
guessed_word = ''
guessed_letters = ''
total_letters = 0
num_guessed_letters = 0
lives = 0
wins = 0
loses = 0
batman = False
class GUI():
def __init__(self, master):
grid = Grid()
self._master = master
... | true |
53046d7c8472943b54402daddf715264f21c6581 | semion-spivak/advent_2018 | /15.py | UTF-8 | 1,683 | 3.1875 | 3 | [] | no_license | from collections import OrderedDict
import networkx as nx
cave = OrderedDict()
graph = nx.OrderedGraph()
class Unit:
enemy_class = None
range_search = ((1, 0), (0, 1), (-1, 0), (0, -1))
def __init__(self, x, y):
self.x = x
self.y = y
self.attack_power = 3
self.hit_points ... | true |
afe1554eca59c8e312b3e5b9c86050108daa7a36 | Heismart/SentencePairMatch_doc2vec-word2vec | /ParaPhrase_doc2vec.py | UTF-8 | 3,671 | 2.546875 | 3 | [] | no_license |
import numpy as np
import pandas as pd
# import sys
# reload(sys)
# sys.setdefaultencoding('utf-8')
class ParaPhrase_word2vec:
def load_doc2vec(self, word2vecpath):
f = open(word2vecpath)
embeddings_index = {}
count = 0
for line in f:
# count += 1
# if coun... | true |
00ecd423510be6b7afc817a0dbb95db5929d736a | coderswapnil/PythonLearnings | /emailSlicer.py | UTF-8 | 370 | 3.375 | 3 | [] | no_license | ##take user email addres via UI
userEmail=input('Give User email address : ')
##separate username
userName=userEmail[0:userEmail.index("@")]
#separate domain name
domainName=userEmail[(userEmail.index("@"))+1:]
#output message
output='username is {} and email created by {}'
output=output.format(userNa... | true |
6f50cffc08c4105261b7d1ba81343aeaa4ab21d7 | bngetich/crypto | /vigenere.py | UTF-8 | 983 | 3.765625 | 4 | [] | no_license | from helpers import alphabet_position, rotate_character
from sys import argv, exit
def encrypt(text, key):
startingIndex = 0
encrypted = []
for letter in text:
if letter.isalpha() == True:
rotation = alphabet_position(key[startingIndex % len(key)])
encrypted.append(rotate_... | true |
d0d91b8a1dc9c3f2d70550502135e892c4ff7d78 | isthegoal/Predicting_Air_Quality | /process/trans_weather_to_num.py | UTF-8 | 2,115 | 2.890625 | 3 | [] | no_license | import pandas as pd
def trans_weather_to_num():
data = pd.read_csv('./data/process_data/final_merge_aq_grid_meo_deal_new.csv')
print(data.info())
#去除所有weather为空的数据,~表示去除的一种方法,因为连续20天没有数据
#data = data[~data['weather'].isnull()]
data.loc[data["weather"] == "Sunny/clear", "weather"] = 1
data.loc[d... | true |
050d90f43794f41e4f310d72968ac58e9bcd109a | yument7/PyLearn | /PyaBaseGrammer/TupleTest.py | UTF-8 | 572 | 3.515625 | 4 | [] | no_license | #!/usr/bin/python3
# --coding=UTF-8--
def tupleTest():
tp1 = (1,2,3,4,5)
# tp1[2] = 9 错误的,不允许通过索引修改元组的值
tp2 = tuple(['apple','oragne','banner','pear','peach','grape'])
print("tp1=%s,tp1[2]=%s"%(tp1,tp1[2]))
# print("tp2[1:5]=%s"%(tp2[1:5])) 错误的, 元组没有切片功能
list1 = list(tp2)
print(list1)
... | true |
ad3085bf8ca74bed14a5e984e9f4381b3d32d5fb | skrstv123/CP-ALGO | /dsa/cfcomps/A. Space Navigation .py | UTF-8 | 672 | 3.265625 | 3 | [] | no_license | from collections import Counter as co
for _ in range(int(input())):
x,y = map(int, input().split())
c = list(input())
count_of_commands = co(c)
cx=cy=0
for i in c:
if i=='R': cx+=1
if i=='L': cx-=1
if i=='U': cy+=1
if i=='D': cy-=1
ans = "NO"
if cx<x:
... | true |
c8d3e6a128c1b962ebef266be55dc5bf581f7d7a | sudhir-j-sapkal/python-basic-examples | /00Variable_OutputFunction/basic_variable.py | UTF-8 | 70 | 3.1875 | 3 | [] | no_license |
my_first_variable="Yeah, It's a variable";
print(my_first_variable);
| true |
d15d4356e30c803be4aa5926cd6504642f9de6ad | joseph-mutu/Codes-of-Algorithms-and-Data-Structure | /Leetcode/[10]正则表达式匹配 -- 备忘录递归.py | UTF-8 | 1,278 | 2.9375 | 3 | [] | no_license | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2020-04-06 07:44:53
# @Author : mutudeh (josephmathone@gmail.com)
# @Link : ${link}
# @Version : $Id$
import os
class Solution(object):
def isMatch(self, s, p):
memo = {}
def dp(i,j):
if (i,j) in memo:
retur... | true |
6dcdee7233df5890bfda2a7a208132886c7169b5 | Daniel-Wuthnow/python_nov_2017 | /Daniel_Wuthnow/making_dictionaries.py | UTF-8 | 679 | 3.40625 | 3 | [] | no_license | name = ["Anna", "Eli", "Pariece", "Brendan", "Amy", "Shane", "Oscar"]
favorite_animal = ["horse", "cat", "spider", "giraffe", "ticks", "dolphins", "llamas"]
# print name_animal
# print name_animal_dict
# def make_dict(arr1, arr2):
# new_dict = {}
# name_animal = zip(name, favorite_animal)
# name_animal_dict = dict(na... | true |
6e7d8c22414bc0150c6d12aee9199b98a3b886eb | LucasMonteiroi/python-course | /exercises/strings.py | UTF-8 | 1,126 | 4.21875 | 4 | [] | no_license | print('Hello there\nHow are you?')
print("This is Lucas's dog")
print('This is Lucas\'s cat')
print(r'This is Lucas\'s fish') # raw string
print("""Lucas work with development
since 2014, beginning with C#""")
spam = 'Hello'
print(spam)
print(spam[0])
print(spam[1:5]) # substring
print(str('Hello' in spam))
print(str(... | true |
393c4b3668c4770d7a89a6b62d59ce563f90c404 | sftwre/Logistic_Regression | /StochasticGradientDescent.py | UTF-8 | 1,333 | 2.78125 | 3 | [] | no_license | import numpy as np
from logits import linearPredict, softmax, cross_entropy
def sgd(X: np.ndarray, y: np.ndarray, W: np.ndarray,
biases: np.ndarray, lr: float, n_cls: int,
iterations: int) -> (np.ndarray, np.ndarray):
"""
Stochastic gradient descent
"""
n = len(y)
L2grad = 2 * W / ... | true |
c1e99bbc0c9c29328b76b82b43edcd6d27216bf2 | LeiShi/Synthetic-Diagnostics-Platform | /src/python3/sdp/model/lightbeam.py | UTF-8 | 13,890 | 3.234375 | 3 | [
"Apache-2.0",
"BSD-3-Clause"
] | permissive | # -*- coding: utf-8 -*-
"""
Created on Thu Jan 28 10:54:24 2016
@author: lei
This module contains mathmatical formula to evaluate Gaussian light beam
propating in vacuum at certain angle
"""
from abc import ABCMeta, abstractmethod
import numpy as np
from numpy.lib.scimath import sqrt
from ..math.coordtransform im... | true |
e09c4feda06efff89905981b0d76405ffc7d6beb | mengnan1994/Surrender-to-Reality | /py/0130_surrounded_regions.py | UTF-8 | 4,016 | 4.125 | 4 | [] | no_license | """
Given a 2D board containing 'X' and 'O' (the letter O), capture all regions surrounded by 'X'.
A region is captured by flipping all 'O's into 'X's in that surrounded region.
Example:
X X X X
X O O X
X X O X
X O X X
After running your function, the board should be:
X X X X
X X X X
X X X X
X O X X
Explanation:
... | true |
68c92045f6cf01b2154b51c4ca245d0507602412 | gplatono/tf_projects | /qc_template.py | UTF-8 | 2,141 | 3.140625 | 3 | [] | no_license | import tensorflow.compat.v1 as tf
#from sklearn import datasets as skds
from sklearn import model_selection
import random
import numpy as np
#import matplotlib.pyplot as plt
#Generate random data
#I generate as lists and then cast into np array, but you can modify to generate random
#np arrays directly. Something lik... | true |
45f4bde194948ca1fd02212da4b4f39d13b0286f | CorbanSwain/Python-Utils | /xml.py | UTF-8 | 2,491 | 2.921875 | 3 | [] | no_license | #!python3
# xml.py
# Project: c_swain_python_utils
# by Corban Swain 2021
import xml.etree.ElementTree as ElementTree
from xml.etree.ElementTree import Element
import copy
__all__ = ['XML', 'load_xml', 'print_xml']
def load_xml(xml_path):
tree = ElementTree.parse(xml_path)
return tree.getroot()
def print... | true |
428d77267225d5ed9b5047412f8d565f987079ec | EladioDeveloper/ArtificialIntelligence | /Practica 1/Ejercicio 11.py | UTF-8 | 220 | 3.71875 | 4 | [] | no_license | def showNumbers (limit):
for i in range(0,limit+1):
if(i%2==0):
print(i,' EVEN')
else:
print(i,' ODD')
limit = int(input("Enter limit: "))
showNumbers(limit)
| true |
05f1e2074722ba38bd0f45a6648d8101d23e281c | ramyashah27/chapter-2-and-3-strings-and-variables | /chapter 3 strings/07findspacepr.py | UTF-8 | 106 | 2.96875 | 3 | [] | no_license | paragraph=("my name is raya shah i am chess player")
doublespace=paragraph.find( ' ' )
print(doublespace) | true |
c3f1b470a04069b2ea9f7745c16f6244b24922cf | geekyrocketguy/laptop | /detectors/gain_temp_saphira.py | UTF-8 | 4,169 | 2.671875 | 3 | [] | no_license | #/usr/bin/env python
#updated 2/18/15
#Calculates gain using temporal method (instead of spatial method)
import pyfits
import matplotlib.pyplot as plt
import numpy as np
import pdb
dir = 'saphira/'
filename = '150324_163748.fits'
img = pyfits.getdata(dir+filename)
for i in np.arange(10, 80, 2):
im0 = img[i, : ... | true |
92ce264faa5a617c14d54c3f071097f7e986598c | C-Kenny/COSC364-RIP | /rip/bellman_ford.py | UTF-8 | 1,486 | 3.421875 | 3 | [] | no_license | import sys
"""
Author: Carl Kenny
Date: 19/04/2015
Prog: Modified Bellman-Ford helper for RIP. Each router or host is assumed to
keep all information about all of the destinations within the system.
The algorithm bases itself on the table in each router listing, via the
metric heuristic. Th... | true |
fd2a8c20a17e1abf687d0b231e422de8dc1fcc34 | giridhersadineni/pythonsrec | /03.Loops/continue_demo2.py | UTF-8 | 126 | 2.796875 | 3 | [] | no_license | numbers=[1,2,3,4,6,4,3,5,0,7,8,923,3,0,67,0,7]
for number in numbers:
if number==0:
continue
print(number) | true |
923d0ba6a5ee5af20e5ba85d30524ca18f87fab3 | jasper2326/HackerRank | /PMLC/Ch04/customer_segmentation.py | UTF-8 | 1,596 | 2.75 | 3 | [] | no_license | import csv
import numpy as np
from sklearn import cluster, covariance, manifold
from sklearn.cluster import MeanShift, estimate_bandwidth
import matplotlib.pyplot as plt
input_file = '/Users/jasper/Desktop/HackerRank/PMLC/Ch04/wholesale.csv'
file_reader = csv.reader(open(input_file, 'r'), delimiter=',')
X = []
for c... | true |
0f73e0d02381077db2bd47f42fb45346eafe5e75 | Tank1991/datongtest | /jiekou-test-0827/test01/test-02-post.py | UTF-8 | 1,211 | 2.828125 | 3 | [] | no_license | # coding:utf-8
import requests
# 忽略警告
import urllib3
urllib3.disable_warnings()
# 第一种 json
url = ""
par = {
#传的是url 后面问号传值的数据
}
h = {
#这是请求的头信息
}
body = {
"key1" : "value1"
}
r = requests.get(url,json= body,headers = h, params= par, verify= False) # json= body,headers = h, # verify= False 忽略警告
# 第二... | true |
909f6180acc6737c00583ef73f602608ab49491b | ryanwes/TicTacToe | /tttgame.py | UTF-8 | 5,422 | 4.0625 | 4 | [] | no_license | # Format of board and Function to print Tic Tac Toe
def print_tic_tac_toe(values):
print("\n")
print("\t | |")
print("\t {} | {} | {}".format(values[0], values[1], values[2]))
print('\t_____|_____|_____')
print("\t | |")
print("\t {} | {} | {}".format(values[3], value... | true |
5e9437f9868e4cb6ccfde0ffd9e2ee555b8b18c9 | cff874460349/tct | /archived/data_preparation/select_separate.py | UTF-8 | 2,080 | 2.828125 | 3 | [] | no_license | import os
from random import shuffle
from shutil import move
def scan_files(directory, prefix=None, postfix=None):
files_list = []
for root, sub_dirs, files in os.walk(directory):
for special_file in files:
if postfix:
if special_file.endswith(postfix):
... | true |
3fdc08920a3aa4d95273aa7913c31af58e0a3663 | Sun-Ke/manim-projects | /Heap/layered.py | UTF-8 | 5,875 | 2.75 | 3 | [] | no_license | import numpy as np
level_separation = 1.5
sibling_separation = 0.8
subtree_separation = 0.8
node_size = 0.6
class Gen:
def __init__(self, edges, **kwargs):
global level_separation,sibling_separation,subtree_separation,node_size
if "level_separation" in kwargs:
level_separation=kwargs["l... | true |
0300927ede82d4af60a4208938c3e1f49ad0be4a | PythonOpen/PyhonProjects | /scrapy/scrapy05.py | UTF-8 | 1,195 | 3.296875 | 3 | [] | no_license | from urllib import request, parse
# 负责处理json格式
import json
'''
大致流程是:
1.利用data构造内容,然后urlopen打开
2.返回一个json格式的结果
3.结果就应该是girl的释义
1.打开F12
2.尝试输入单词girl,发现每敲一个字母后都有请求
3.请求地址是http://fanyi.baidu,com/sug
4.利用NetWork-All-Headers查看,发现FromData的值是kw:girl
5.检查返回内容格式,发现返回的是json格式内容==>需要利用json包
'''
if __name__ == '__main__':
bas... | true |
1b6770f2be68fce2fa88ba5bf99fe88d035c65d1 | segundoayllon/Actividad-Python-Plus | /goodreads_pack/goodreads_window.py | UTF-8 | 897 | 2.875 | 3 | [] | no_license | import PySimpleGUI as sg
from goodreads_pack import mejor_puntuados
from goodreads_pack import autores_publicados
def layout():
layout=[[sg.Button('Libros en español mejor puntuados')],
[sg.Button('Autores con mas libros publicados')],
[sg.Button('VOLVER')]]
ventana = sg.Window('GoodR... | true |
bb06285a17209a5b7293b569dc1b006889af8ed1 | TheMostOriginalUserName/Stanford-CS224n-2016-2017-winter | /assignment2/q2_parser_transitions.py | UTF-8 | 9,839 | 3.546875 | 4 | [] | no_license | class PartialParse(object):
def __init__(self, sentence):
"""Initializes this partial parse.
Your code should initialize the following fields:
self.stack: The current stack represented as a list with the top of the stack as the
last element of the list.
... | true |
7c9265fa83bea2cbe70aa9f7287112b79bb3c723 | lesion/strumenti | /strumenti/libs/db.py | UTF-8 | 3,868 | 2.546875 | 3 | [] | no_license |
class MySQL( ):
""" Use this class to connect to MySQL database:
MySQL( host, user, password ) """
def __init__( self, host='localhost', user='root', password='' ):
import MySQLdb
self.connection = MySQLdb.connect( host, user, password, use_unicode=True, charset='utf8' )
self.connection.autocommit... | true |
d96e9d7508a1503922096f343cc7bf5e3df7eb96 | Ritvik19/CodeBook | /data/CodeChef/REMISS.py | UTF-8 | 138 | 3.3125 | 3 | [] | no_license | for i in range(int(input())):
inp = input().split(" ")
a = int(inp[0])
b = int(inp[1])
print(str(max(a, b))+" "+str(a+b))
| true |
cb9cc1e39c840ffad348a24e62dbb7fafd817ece | nikhgarg/CircuitSnap | /CircuitSolver.py | UTF-8 | 2,811 | 2.609375 | 3 | [] | no_license | from kvlLoop import kvlLoop
from copy import deepcopy
import numpy
def solveCircuit(elements):
nonmesh = []
meshs = []
kvlLoops = []
elementLocationMap = {"":0}
elementLoopMap = {"":[]}
stringifyLoop = {"":[]}
print "these are the meshes"
for element in elements:
if element[4] == 'm':
print element
mesh... | true |
d1e7019a0fb0f8a14ee4fc9e8e37d30cd08a7c2d | llalexandru00/Neural-Networks | /digit.py | UTF-8 | 2,754 | 2.828125 | 3 | [] | no_license | import pickle
import gzip
import numpy as np
def activate(vec):
best_score = vec[0]
idx = 0
for i in range(1, len(vec)):
if vec[i] > best_score:
best_score = vec[i]
idx = i
ar = np.zeros((10, 1))
ar[idx] = 1
return ar
def reshaped_result(result):
ar = np.z... | true |
baf749ca12528141fc515efbfb55f0727b15f05d | priyanka1113/assignment1 | /DisplayMenuItems.py | UTF-8 | 298 | 3.296875 | 3 | [] | no_license | import numpy as np
from inputNum import inputNum
def DisplayMenuItems(options):
for i in range(len(options)):
print("{:d}.{:s}".format(i+1,options[i]))
choice = 0
while not(np.any(choice == np.arange(len(options))+1)):
choice = inputNum("please choose a menu item:")
return choice
| true |
c35c3acfecd8d75eda1c0ab56baa5cc4686186ca | 5words/prj | /py/函数式编程/lamdaTraining.py | UTF-8 | 145 | 3.34375 | 3 | [] | no_license | """
def is_odd(n):
return n % 2 == 1
L = list(filter(is_odd, range(1, 20)))
"""
L = list(filter(lambda x:x % 2==1, range(1, 20)))
print(L) | true |
3f49686b13bb58aa4ac5b7d86cb418f11b7fde8d | PeterZs/Network-Distributed-Algorithm | /problems/problem.py | UTF-8 | 6,074 | 3.109375 | 3 | [] | no_license | #!/usr/bin/env python
# coding=utf-8
import numpy as np
import networkx as nx
import matplotlib.pyplot as plt
from scipy import optimize as opt
class Problem(object):
'''The base problem class, which generates the random problem and supports function value and gradient evaluation'''
def __init__(self, n_agent... | true |
e2f6d81e64192b1ae5b1c7a2f3c6c276e39e1578 | jen-dooley/ai3202 | /Assignment3/Dooley_Assignment3.py | UTF-8 | 4,385 | 3.375 | 3 | [] | no_license | #Jennifer Dooley
#830371622
#Assignment 3 CSCI3202
from sys import argv
import math
WIDTH = 10
HEIGHT = 8
class Node:
def __init__(self, val):
#map value
self.val = int(val)
#location values
self.x = 0
self.y = 0
self.parent = None
#A* search cost values
self.h = 0
self.g = 0
self.f = 0
def se... | true |
68d07e6db1cf35ef48b78534fb7be274d7feaef0 | eoriont/machine-learning | /kaggle/titanic/exploration2.py | UTF-8 | 1,004 | 2.5625 | 3 | [] | no_license | import sys, os, math
sys.path.append("analysis/kaggle/titanic")
sys.path.append("src/models")
from parse_line import parse_line
from data_loading import data_types
from dataframe import DataFrame
if __name__ == "__main__":
path0 = os.path.join(os.getcwd(), 'datasets', 'titanic', "dataset_of_knowns.csv")
df = ... | true |
c30d2e3d2064ae9fcee6d63a2a7c3702eae95207 | caiqinxiong/python | /day04/json序列化.py | UTF-8 | 1,118 | 3.546875 | 4 | [] | no_license | # -*- coding:utf-8 -*-
# Author:caiqinxiong
import json #主要用于不同语言之间的转换,list,dict,str等,函数不行。
import pickle #用法和json一样,支持所以类型转换,二进制形式,只能在python里用
def sayHi(name):
print('Hi',name)
info = {
'name':'lixiaoxin',
'age':30,
'func':sayHi
}
#f = open('info.txt','w')
f = open('info.txt','wb')
#f.write(str(info))... | true |
e8996de11291673149482a2c63dabbf858354723 | DoubleBridges/Graphs | /projects/ancestor/ancestor.py | UTF-8 | 836 | 3.609375 | 4 | [] | no_license | from graph import Graph
def earliest_ancestor(ancestors, starting_node):
graph = Graph()
for (parent, child) in ancestors:
graph.add_vertex(child)
graph.add_edge(child, parent)
paths = graph.dft_recursive(starting_node)
longest = len(sorted(paths, key=len)[-1])
longest_paths = li... | true |
8736c02c44277d7e0bf63353b7c5e1a816b7407b | simon-ritchie/python-novice-book | /src/answer_str_repetition.py | UTF-8 | 36 | 3.53125 | 4 | [] | no_license | cat_str = '猫' * 10
print(cat_str) | true |
add218f90d563b7983bb07eaef5e169125bd8c97 | steven0129/nlp | /ltp/ltp-parser.py | UTF-8 | 1,030 | 2.90625 | 3 | [] | no_license | # -*- coding: utf-8 -*-
import nltk
from nltk.tree import Tree
from nltk.grammar import DependencyGrammar
from nltk.parse import *
from pyltp import *
import re
sent = '在 包含 問題 的 所有 解 的 解空間樹 中 , 按照 深度優先 搜尋 的 策略 , 從 根節點 出發 深度優先 搜尋 解空間樹'
words = sent.split(' ')
postagger = Postagger()
postagger.load('./data/l... | true |
060f62ebef3a3aac0ceef6442cf82f78a0a042c8 | RenatoCotrim/An-Introduction-to-Interactive-Programming-in-Python-Part-1- | /Is_Lunchtime.py | UTF-8 | 1,227 | 3.625 | 4 | [] | no_license | # URL = http://www.codeskulptor.org/#user45_y9PE0ldR04_0.py
# Compute whether the given time is lunchtime.
###################################################
# Is lunchtime formula
# Student should enter function on the next lines.
"""
Returns wether the given time, as represented by the hour
and ... | true |