repo_name stringlengths 6 97 | path stringlengths 3 341 | text stringlengths 8 1.02M |
|---|---|---|
thinkmoore/blight | src/blight/actions/__init__.py | <gh_stars>0
"""
Actions supported by blight.
"""
from .benchmark import Benchmark # noqa: F401
from .find_outputs import FindOutputs # noqa: F401
from .inject_flags import InjectFlags # noqa: F401
from .record import Record # noqa: F401
|
thinkmoore/blight | src/blight/cli.py | import logging
import os
import shlex
import shutil
import stat
import sys
import tempfile
from pathlib import Path
import click
import blight.tool
from blight.exceptions import BlightError
from blight.util import die
logging.basicConfig(level=os.environ.get("BLIGHT_LOGLEVEL", "INFO").upper())
def _export(variable... |
Yamakaky/nxbt | nxbt/tui.py | import os
import time
import psutil
from collections import deque
import multiprocessing
from blessed import Terminal
from .nxbt import Nxbt, PRO_CONTROLLER
class LoadingSpinner():
SPINNER_CHARS = ['■ □ □ □', '□ ■ □ □', '□ □ ■ □', '□ □ □ ■', '□ □ □ ■', '□ □ ■ □', '□ ■ □ □', '■ □ □ □'] # noqa
def __init__... |
Yamakaky/nxbt | scripts/switch_emu.py | """
Quick script to emulate a Switch connecting to a Joy-Con/Pro Controller.
Note: If you get an Invalid Exchange error when running this script, this means
that the Switch has paired to the controller, invalidating the original pairing
key we created. You'll need to re-pair the controller to this device.
"""
import ... |
Yamakaky/nxbt | nxbt/controller/server.py | import socket
import fcntl
import os
import time
import queue
import logging
import traceback
from .controller import Controller, ControllerTypes
from ..bluez import BlueZ
from .protocol import ControllerProtocol
from .input import InputParser
from .utils import format_msg_controller, format_msg_switch
class Control... |
Yamakaky/nxbt | scripts/reconnect_proxy.py | <reponame>Yamakaky/nxbt
"""
This is a quick and dirty script for recording input from a controller
and dumping it into a "messages.txt" file. You'll need to input the
device's Bluetooth MAC address manually and specify the type of
controller before this script works.
Note: If you get an Invalid Exchange error when run... |
Yamakaky/nxbt | nxbt/bluez.py | <gh_stars>0
import subprocess
import re
import os
import time
import logging
import dbus
SERVICE_NAME = "org.bluez"
BLUEZ_OBJECT_PATH = "/org/bluez"
ADAPTER_INTERFACE = SERVICE_NAME + ".Adapter1"
PROFILEMANAGER_INTERFACE = SERVICE_NAME + ".ProfileManager1"
DEVICE_INTERFACE = SERVICE_NAME + ".Device1"
def find_obje... |
Yamakaky/nxbt | scripts/crash_switch.py | """
---------------------------------------------------
--> THIS SCRIPT WILL CRASH YOUR NINTENDO SWITCH <--
---------------------------------------------------
Any save data or active game state will be lost
since this forces a restart. I take no
responsibility whatsoever for any lost data or
harm caused by this scrip... |
dfb/uepy | Content/Scripts/uepy/netrep.py | '''
Python side of network replication (aka NetRep or NR) code. Misc info/notes:
- Any object (not just actors) can declare itself as replicated and send/receive network messages; each object that does so needs to
have a unique network name/ID known as the netID.
- Replicated objects declare an optional 'repProps' ... |
dfb/uepy | Content/Scripts/uepy/deps.py | <gh_stars>1-10
'''Manages installable dependencies - used both to package them and at runtime to make them available'''
import os, shutil, zipapp, glob, sys
def Package():
'''Called if you run deps.py from the command line, which you should do anytime you modify requirements.txt'''
outName = 'deps.pyz'
if ... |
dfb/uepy | Content/Scripts/sourcewatcher.py | '''
Provides a development tool that monitors the source files used, reloading stuff when
something changes. The developer provides a "dev module" that is used to set up the
work area. Any module can opt-in to be informed about reloads by implementing any of:
- OnModuleBeforeReload(watcher) - called right before the m... |
dfb/uepy | Content/Scripts/uepy/__init__.py | from _uepy import *
from importlib import reload
import sys, shlex, json, time, weakref, inspect
from . import enums
# Capture sys.stdout/stderr
class OutRedir:
def write(self, buf):
log(buf)
def flush(self):
pass
def isatty(self):
return False
sys.stdout = OutRedir()
sys.stderr =... |
dfb/uepy | Content/Scripts/uepy/enums.py | <reponame>dfb/uepy<filename>Content/Scripts/uepy/enums.py<gh_stars>1-10
'''
Engine enumerations exposed to Python, along with a base enum class that adds a reverse mapping (value-to-name) API.
'''
class EnumMeta(type):
'''Used by Enum class'''
def __new__(metaclass, name, bases, dct):
# Create an inver... |
dfb/uepy | Content/Scripts/uepy/rrepl.py | '''
Embeddable read-eval-print loop for Python applications.
Example usage:
# during application startup
repl = RemoteREPL() # optionally pass in listen host and/or port
# call this often during app lifetime
repl.Process()
To connect use telnet or:
python -m telnetlib 127.0.0.1 9999 # or other ho... |
dfb/uepy | Content/Scripts/uepy/editor_spawner.py | # Creates a tab/window in the editor for spawning Python-based actors
import uepy, time
from uepy import umg, editor
from uepy import log, logTB
class SpawnerTab(uepy.UUserWidget_PGLUE):
def __init__(self):
self.num = int(time.time())
def Construct(self, vboxRoot):
log('editor_spawner.SpawnerT... |
dfb/uepy | Content/Scripts/uepy/umg.py | <reponame>dfb/uepy
from _uepy import *
from _uepy._umg import *
|
dfb/uepy | Content/Scripts/uepy/editor.py | from _uepy import *
from _uepy._editor import *
|
cgnik/euler | src/py/util/nth.py | def nth(test, items):
if test > 0:
test -= 1
else:
test = 0
for i, v in enumerate(items):
if i == test: return v
|
cgnik/euler | src/py/problem26.py | # A unit fraction contains 1 in the numerator. The decimal representation of the unit fractions with denominators 2 to 10 are given:
#
# 1/2 = 0.5
# 1/3 = 0.(3)
# 1/4 = 0.25
# 1/5 = 0.2
# 1/6 = 0.1(6)
# 1/7 = 0.(142857)
# 1/8 = 0.125
# 1/9 = 0.(1)
# 1/10 = 0.1
# Where 0.1(6) means 0.166666..., and has a 1-digi... |
cgnik/euler | src/py/util/permutation.py | <filename>src/py/util/permutation.py
def permutations(items):
# c is an encoding of the stack state. c[k] encodes the for-loop counter for when generate(k+1, A) is called
c = [0 for c in range(0, len(items))]
yield items
# i acts similarly to the stack pointer
i = 0
while i < len(items):
... |
cgnik/euler | src/py/problem22.py | # https://projecteuler.net/problem=22
# Using names.txt (right click and 'Save Link/Target As...'), a 46K text file containing over five-thousand first names, begin by sorting it into alphabetical order. Then working out the alphabetical value for each name, multiply this value by its alphabetical position in the list ... |
cgnik/euler | src/py/problem17.py | from num2words import num2words
def problem17():
print(f"Problem 17: {sum([len(num2words(a).replace(' ', '').replace('-', '')) for a in range(1,1001)])}")
problem17()
|
cgnik/euler | src/py/util/factoring.py | <gh_stars>0
from math import sqrt
from util.divisible import divisible_by
def factors(num):
n = num
yield 1
for x in [2, 3, 5, 7]:
while n % x == 0:
n = int(n / x)
yield x
f = 11
while f <= int(sqrt(n)):
if n % f == 0:
yield f
while ... |
cgnik/euler | src/py/problem11.py | import numpy as np
from matrix import flipdiag, groups
# grid is 20x20 to begin
matrix = np.array([8, 2, 22, 97, 38, 15, 0, 40, 0, 75, 4, 5, 7, 78, 52, 12, 50, 77, 91, 8,
49, 49, 99, 40, 17, 81, 18, 57, 60, 87, 17, 40, 98, 43, 69, 48, 4, 56, 62, 0,
81, 49, 31, 73, 55, 79, 14, 29, ... |
cgnik/euler | src/py/util/test_collatz.py | <gh_stars>0
from unittest import TestCase
from util.collatz import collatz, collatz_series
class Test_collatz(TestCase):
def test_collatz(self):
self.assertEqual(collatz(13), 40)
self.assertEqual(collatz(40), 20)
def test_collatz_series(self):
self.assertListEqual(list(collatz_series... |
cgnik/euler | src/py/util/test_factors.py | from unittest import TestCase
import numpy as np
from util.factoring import factors
from util.cartesian import all_factors
class Test_factors(TestCase):
def test_factors(self):
self.assertListEqual(listify(factors(1)), [1])
self.assertListEqual(listify(factors(12)), [1, 2, 3, 12])
self.as... |
cgnik/euler | src/py/util/test_fibonacci.py | from unittest import TestCase
from util.fibonacci import fibonacci
class Test_fibonacci(TestCase):
def test_fibonacci(self):
def nth_fibonacci(n):
count = 0
for f in fibonacci():
count += 1
if count >= n:
break;
retur... |
cgnik/euler | src/py/problem33.py | <reponame>cgnik/euler
# https://projecteuler.net/problem=33
#
# The fraction 49/98 is a curious fraction, as an inexperienced mathematician in attempting to simplify it may incorrectly believe that 49/98 = 4/8, which is correct, is obtained by cancelling the 9s.
#
# We shall consider fractions like, 30/50 = 3/5, to be ... |
cgnik/euler | src/py/util/test_abundant.py | from unittest import TestCase
from util.abundant import abundant_numbers, contains_sum_for
class Test_abundants(TestCase):
test_data1 = []
test_data2 = [[1, 2], [3, 4]]
test_data3 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
# def test_abundants_wierdos(self):
# # [1, 2, 4, 11, 22, 44, 121, 242, 253,... |
cgnik/euler | src/py/util/spiral.py | import numpy as np
def spiral_diagonals(length):
return list(diagonal_values(2 * length - 1))
def diagonal_values(cycles):
offset = 2
cycle = 0
previous = 1
yield previous
while cycle + 1 < cycles:
cycle += 1
previous += offset
if cycle % 4 == 0:
offset +=... |
cgnik/euler | src/py/util/grids.py | import numpy as np
def get_sticks(grid):
if len(grid.shape) != 2:
return []
rows, columns = grid.shape
sticks = []
for x in range(0, columns):
for y in range(0, rows):
if x < columns - 1:
sticks.append((grid[y][x], grid[y][x + 1]))
if y < rows - ... |
cgnik/euler | src/py/util/test_permutations.py | <gh_stars>0
from unittest import TestCase
from util.permutation import permutations, permute_all, permute, combinations, permute_all_combinations
def stringify(arr):
response = [''.join([str(a) for a in b]) for b in arr]
response.sort()
return response
class Test_Permutations(TestCase):
def test_pe... |
cgnik/euler | src/py/util/threadsafe_generator.py | <reponame>cgnik/euler<filename>src/py/util/threadsafe_generator.py
import threading
class ThreadsafeIterator:
def __init__(self, it):
self.it = it
self.lock = threading.Lock()
def __iter__(self):
return self
def __next__(self):
with self.lock:
return self.it._... |
cgnik/euler | src/py/problem10.py | <gh_stars>0
from primerator import Primerator
import numpy
limit = 2000000
p = Primerator(limit).primes()
with open('primes.txt', 'w') as f:
f.write('\n'.join(map(lambda x: str(x), p)))
print(f"\nSum of primes < {limit}: {numpy.sum(p)}")
|
cgnik/euler | src/py/problem32.py | <reponame>cgnik/euler
# https://projecteuler.net/problem=32
# We shall say that an n-digit number is pandigital if it makes use of all the digits 1 to n exactly once; for example, the 5-digit number, 15234, is 1 through 5 pandigital.
#
# The product 7254 is unusual, as the identity, 39 × 186 = 7254, containing multipli... |
cgnik/euler | src/py/util/test_distinct_powers.py | from unittest import TestCase
from util.distinct_powers import distinct_powers, simplify_exponent
class Test_distinct_powers(TestCase):
def test_distinct_powers(self):
# self.assertSetEqual(distinct_powers(2, 5), {4, 8, 9, 16, 25, 27, 32, 64, 81, 125, 243, 256, 625, 1024, 3125})
self.assertEqual(... |
cgnik/euler | src/py/util/test_digit_exponents.py | <reponame>cgnik/euler
from unittest import TestCase
from util.digit_exponents import is_power_sum, power_sums
class TestDigitExponents(TestCase):
def test_is_power_sum(self):
self.assertTrue(is_power_sum(1634, 4))
self.assertTrue(is_power_sum(8208, 4))
self.assertTrue(is_power_sum(9474, 4... |
cgnik/euler | src/py/util/divisible.py | def is_divisible(a, b):
return a % b == 0
def any_divisors(a, bs):
if not bs: return False
for b in iter(bs):
yield is_divisible(a, b)
return False
def divisible_by(a, bs):
return any(any_divisors(a, bs)) |
cgnik/euler | src/py/problem27.py | <reponame>cgnik/euler<gh_stars>0
# Euler discovered the remarkable quadratic formula:
#
# n2+n+41
# It turns out that the formula will produce 40 primes for the consecutive integer values 0≤n≤39. However, when n=40,402+40+41=40(40+1)+41 is divisible by 41, and certainly when n=41,412+41+41 is clearly divisible by 41.
#... |
cgnik/euler | src/py/problem24.py | <reponame>cgnik/euler
# Lexicographic permutations
#
# Problem 24
#
# A permutation is an ordered arrangement of objects. For example, 3124 is one possible permutation of the digits 1, 2, 3 and 4. If all of the permutations are listed numerically or alphabetically, we call it lexicographic order. The lexicographic perm... |
cgnik/euler | src/py/util/quadratic_primes.py | from util.factoring import is_prime_quick
import numpy as np
def expr(n, ab):
return n ** 2 + (ab[0] * n) + ab[1]
def consecutive_primes(ab):
n = 0
while True:
n += 1
if not is_prime_quick(expr(n, ab)):
return n
return 0
signs = np.array([(-1, 1), (1, -1), (-1, -1), (1,... |
cgnik/euler | src/py/problem35.py | <reponame>cgnik/euler
# The number, 197, is called a circular prime because all rotations of the digits: 197, 971, and 719, are themselves prime.
#
# There are thirteen such primes below 100: 2, 3, 5, 7, 11, 13, 17, 31, 37, 71, 73, 79, and 97.
#
# How many circular primes are there below one million?
# https://projecte... |
cgnik/euler | src/py/problem19.py | month_days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
month_days_leap = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
days = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat']
months = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec']
def problem19():
matches = []
... |
cgnik/euler | src/py/util/test_cartesian.py | <filename>src/py/util/test_cartesian.py
from unittest import TestCase
import numpy as np
from util.cartesian import cartesian
class Test_cartesian(TestCase):
def test_cartesian(self):
def lte(limit):
def test(x):
return x <= limit
return test
self.assertL... |
cgnik/euler | src/py/util/test_nth.py | <gh_stars>0
from unittest import TestCase
from util.nth import nth
class Test_nth(TestCase):
def test_nth(self):
self.assertEqual(1, nth(3, [0, 2, 1]))
self.assertEqual(0, nth(-33, [0, 2, 1]))
def test_gen(max):
for i in range(0, max):
yield i
self.as... |
cgnik/euler | src/py/problem29.py | <gh_stars>0
# Consider all integer combinations of ab for 2 ≤ a ≤ 5 and 2 ≤ b ≤ 5:
#
# 22=4, 23=8, 24=16, 25=32
# 32=9, 33=27, 34=81, 35=243
# 42=16, 43=64, 44=256, 45=1024
# 52=25, 53=125, 54=625, 55=3125
# If they are then placed in numerical order, with any repeats removed, we get the following sequence of 15 distin... |
cgnik/euler | src/py/util/test_spiral.py | from unittest import TestCase
from util.spiral import spiral_diagonals
class Test_spiral(TestCase):
def test_spiral_diagonals(self):
self.assertListEqual(spiral_diagonals(3), [1, 3, 5, 7, 9])
self.assertListEqual(spiral_diagonals(5), [1, 3, 5, 7, 9, 13, 17, 21, 25])
self.assertListEqual(s... |
cgnik/euler | src/py/problem20.py | <filename>src/py/problem20.py
from functools import reduce
def problem20():
fac = reduce(lambda x, accum: x * accum, range(1, 101))
print(f"fac: {sum(map(int, list(str(fac))))}")
problem20()
|
cgnik/euler | src/py/util/test_quadratic_primes.py | from unittest import TestCase
from util.quadratic_primes import consecutive_primes, expr, sign_combos
class Test_quadratic_primes(TestCase):
def test_consecurive_primes(self):
self.assertEqual(40, consecutive_primes((1, 41)))
self.assertEqual(80, consecutive_primes((-79, 1601)))
def test_exp... |
cgnik/euler | src/py/problem28.py | <reponame>cgnik/euler
# Starting with the number 1 and moving to the right in a clockwise direction a 5 by 5 spiral is formed as follows:
#
# 21 22 23 24 25
# 20 7 8 9 10
# 19 6 1 2 11
# 18 5 4 3 12
# 17 16 15 14 13
#
# It can be verified that the sum of the numbers on the diagonals is 101.
#
# What is the sum... |
cgnik/euler | src/py/problem3.py | from util.factoring import factors
if __name__ == '__main__':
num = 600851475143
fs = [f for f in factors(num)]
fs.append([x for f in x for x in factors(f)])
print(f"{fs}")
|
cgnik/euler | src/py/util/digit_exponents.py | def is_power_sum(n, exponent):
return sum(map(lambda x: int(x) ** exponent, str(n))) == n
def power_sums(exponent, limit=10000):
n = 1
one_percent = int(limit / 100)
percent_complete = 0
while n <= limit:
if int((n / limit) * 100) > percent_complete:
percent_complete = int((n /... |
cgnik/euler | src/py/problem25.py | # The Fibonacci sequence is defined by the recurrence relation:
#
# Fn = Fn−1 + Fn−2, where F1 = 1 and F2 = 1.
# Hence the first 12 terms will be:
#
# F1 = 1
# F2 = 1
# F3 = 2
# F4 = 3
# F5 = 5
# F6 = 8
# F7 = 13
# F8 = 21
# F9 = 34
# F10 = 55
# F11 = 89
# F12 = 144
# The 12th term, F12, is the first term to contain th... |
cgnik/euler | src/py/util/matrix.py | import numpy as np
def flipdiag(x, dim):
a = np.zeros((dim, dim))
for i in range(-1 * dim, dim):
hd = x.diagonal(offset=i)
a[i][0:len(hd)] = hd
return a
def groups(x, size, start=0):
return np.vstack([x[:, n:n + size] for n in range(start, x.shape[0] - size + 1) if len(x[n]) >= size]... |
cgnik/euler | src/py/problem16.py | from functools import reduce
def problem16():
print(f"Problem 16 {reduce(lambda x,y: x+y, [int(a) for a in str(2**1000)])}")
problem16()
|
cgnik/euler | src/py/util/test_any_divisors.py | from unittest import TestCase
from util.divisible import divisible_by
class Test_divisible_by(TestCase):
def test_any_divisors(self):
self.assertFalse(divisible_by(12, None))
self.assertFalse(divisible_by(12, []))
self.assertTrue(divisible_by(12, [5, 6, 2]))
self.assertTrue(divisi... |
cgnik/euler | src/py/problem21.py | from util.factoring import all_factors
# https://projecteuler.net/problem=21
# Let d(n) be defined as the sum of proper divisors of n (numbers less than n which divide evenly into n).
# If d(a) = b and d(b) = a, where a ≠ b, then a and b are an amicable pair and each of a and b are called amicable numbers.
#
# For ex... |
cgnik/euler | src/py/util/palindrome.py | def is_palindrome(x):
s = str(x)
end = len(s) - 1
for i in range(0, len(s)):
if s[i] != s[end - i]:
return False
return True
def find_palindromes():
all = []
for i in range(100, 999):
for j in range(100, 999):
if is_palindrome(i * j):
all... |
cgnik/euler | src/py/problem14.py | from util.collatz import collatz_series
def longest_collatz_between(start, end):
answer = (0, [], 0)
for i in range(start, end):
if i % 1000 == 0: print('.', end='', flush=True)
x = list(collatz_series(i))
if len(x) > answer[2]:
answer = (i, x, len(x))
return answer
d... |
cgnik/euler | src/py/util/fibonacci.py | def fibonacci():
nums = [1, 1, 2]
yield from nums
i = 3
while True:
index = i % 3
nums[index] = nums[index - 2] + nums[index - 1]
yield nums[index]
i += 1
|
cgnik/euler | src/py/util/test_grids.py | from unittest import TestCase
import numpy as np
from util.grids import gen_paths, get_sticks
class Test_grids(TestCase):
test_data1 = []
test_data2 = [[1, 2], [3, 4]]
test_data3 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
def test_get_sticks(self):
self.assertCountEqual(get_sticks(np.array(self.te... |
cgnik/euler | src/py/util/cartesian.py | import itertools as it
from operator import mul
import numpy as np
from functools import reduce
from util.factoring import factors
def cartesian(boundary, x, *args, reducer=mul):
products = x
last_products = []
def gen():
yield x
if args and len(args):
for z in args:
... |
cgnik/euler | src/py/util/distinct_powers.py | <gh_stars>0
import itertools as it
import numpy as np
# NEED TO DEDUPE/SIMPLIFY_POWERS ON THE POWS LIST BEFORE USING IT. CHICKENEGG.
pows = {a ** b: (a, b) for b in range(2, 10) for a in range(2, 11) if a ** b <= 100}
def distinct_powers(l, h):
values = np.arange(l, h + 1)
terms = {simplify_exponent(*p) for... |
cgnik/euler | src/py/problem34.py | # 145 is a curious number, as 1! + 4! + 5! = 1 + 24 + 120 = 145.
#
# Find the sum of all numbers which are equal to the sum of the factorial of their digits.
#
# Note: As 1! = 1 and 2! = 2 are not sums they are not included.
# https://projecteuler.net/problem=34
from math import factorial
from time import process_time... |
cgnik/euler | src/py/problem30.py | # Surprisingly there are only three numbers that can be written as the sum of fourth powers of their digits:
#
# 1634 = 14 + 64 + 34 + 44
# 8208 = 84 + 24 + 04 + 84
# 9474 = 94 + 44 + 74 + 44
# As 1 = 14 is not a sum it is not included.
#
# The sum of these numbers is 1634 + 8208 + 9474 = 19316.
#
# Find the sum of all... |
cgnik/euler | src/py/problem4.py | <reponame>cgnik/euler
from palindrome import find_palindromes
def first(x): return x[0]
def problem4():
palindromes = find_palindromes()
palindromes.sort(key=first, reverse=True)
print(f"best: {palindromes[0]}")
problem4()
|
cgnik/euler | src/py/problem18.py | <filename>src/py/problem18.py<gh_stars>0
from statistics import mean
def weight_down(d, row, column):
w = [d for i in range(0, len(d) - row) for d in d[i][column:column + i]]
if len(w) == 0:
return d[row][column]
return int(mean([d[row][column], mean(w)]))
def weight_data_down(d):
weights = ... |
cgnik/euler | src/py/util/collatz.py | <filename>src/py/util/collatz.py
def collatz(n):
if n % 2 == 0:
return int(n / 2)
return (n * 3) + 1
def collatz_series(n):
a = n
while a != 1:
a = collatz(a)
yield a
return 1 |
cgnik/euler | src/py/util/abundant.py | <reponame>cgnik/euler
from util.cartesian import all_factors
def abundant_numbers(up_to):
abundants = []
for n in range(12, up_to + 1):
if n % 100 == 0: print(f"\rcalculating abundants: {int(n * 100 / up_to)}%", end='', flush=True)
if sum(all_factors(n)) > n:
abundants.append(n)
... |
cgnik/euler | src/py/problem31.py | <gh_stars>0
# In England the currency is made up of pound, £, and pence, p, and there are eight coins in general circulation:
#
# 1p, 2p, 5p, 10p, 20p, 50p, £1 (100p) and £2 (200p).
# It is possible to make £2 in the following way:
#
# 1×£1 + 1×50p + 2×20p + 1×5p + 1×2p + 3×1p
# How many different ways can £2 be made u... |
cgnik/euler | src/py/util/primerator.py | from multiprocessing import Pool
from util.factoring import is_prime_quick
class Primerator:
def __init__(self, limit):
self.limit = limit
def _candidate_generator_(self):
for x in range(3, self.limit, 2):
yield x
def _one_thread_(self, candidate):
if candidate % 10... |
cgnik/euler | src/py/util/repeats.py | <reponame>cgnik/euler<gh_stars>0
import re, decimal
max_precision = 4096
def unit_fraction_cycle(n):
decimal.setcontext(decimal.Context(prec=max_precision, rounding=decimal.ROUND_HALF_DOWN))
val = str(decimal.Decimal(1) / decimal.Decimal(n))
if val and '.' in val:
s = val.split('.')[1][:-1]
... |
cgnik/euler | src/py/util/test_repeats.py | <filename>src/py/util/test_repeats.py<gh_stars>0
from unittest import TestCase
from util.repeats import unit_fraction_cycle, repeats, tip_to_tail
class Test_repeats(TestCase):
def test_repeats(self):
self.assertEqual('', repeats('f'))
self.assertEqual('f', repeats('ff'))
self.assertEqual... |
cgnik/euler | src/py/problem12.py | from util.numeric import triangles
from util.cartesian import cartesian_factors
from util.factoring import factors
def triangulate(start=2 ** 30, limit=100):
count = 0
for x in triangles():
count += 1
if x >= start:
facs = list(factors(x, log=False))
facs.remove(x)
... |
cgnik/euler | src/py/util/numeric.py | <reponame>cgnik/euler
def ticklog(count, increment):
if count % increment == 0:
print(".", end='', flush=True)
def naturals(seed=1):
num = seed
while True:
yield num
num += 1
def triangles():
last = 0
for n in naturals():
last = n + last
yield last
|
cgnik/euler | src/py/problem15.py | <filename>src/py/problem15.py
from scipy.linalg import pascal
def problem15():
print(f"binom: {pascal(21)[-1][-1]}")
problem15()
|
sTeeLM/tc | tc.py | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
import torrent_parser as tp
import sys
import md5
import re
def md5_string(val):
m = md5.new()
matchObj = re.match(r'^(.*)\.(.*?)$', val)
if matchObj:
val = matchObj.group(1)
m.update(val)
return m.hexdigest() + '.' + matchObj.group(2)
else:
m.update(val)
... |
zingp/nlpclub | data/utils.py | import time
import json
import datetime
import xlrd
import xlsxwriter
"""
本模块定义通用数据处理相关的功能函数
"""
def read_text(file_path):
""" 读文本文件返回内容列表,列表元素是原文的一行
Args:
file_path (str) 原文本文件
Returns:
data (list) 列表元素是文本行
"""
with open(file_path, "r") as f:
data = f.read().splitlines()
... |
zingp/nlpclub | data/eda.py | <reponame>zingp/nlpclub
import jieba
import synonyms
import random
from random import shuffle
from pprint import pprint
"""
EDA数据增强
现在存在问题:随机交换可能出现标点符号相互交换
"""
random.seed(42)
# 同义词替换
def synonym_replacement(words, n, stopwords):
"""替换一个语句中的n个单词为其同义词"""
new_words = words.copy()
random_word_list = list(set(... |
zingp/nlpclub | data/main.py |
from utils import read_excel, write_text
from utils import obj_to_json
# 保存原文
# 保存文本违规json
# 音频违规json
# 数据加载
def build_audio_dic(text_list):
if len(text_list) != 5:
return {}
dic = {
"idx": text_list[0],
"date": text_list[1],
"cate1": text_list[2],
"cate2": text_list[... |
zingp/nlpclub | data/about_excel.py |
from utils import *
if __name__ == '__main__':
txt = "/Users/liuyouyuan/Desktop/unsafe_text_main.txt"
data = read_text(txt)
new_data = [line.split("\t") for line in data]
col = ["Live id", "Text", "违规类型"]
write_excel(new_data, "/Users/liuyouyuan/Desktop/直播30s不安全标注20210419.xlsx", col)
|
zingp/nlpclub | emoji_data/proprecessing_emoji.py | <filename>emoji_data/proprecessing_emoji.py
import os
import re
import emoji
import numpy as np
def clean_text_zh(text):
"""中文数据清洗"""
# 去除空格
text = re.sub(' ', '', text)
# 去掉全角空白符,\u3000 是全角的空白符
text = re.sub('\u3000', '', text)
# 去掉 \xa0 是不间断空白符
text = re.sub('\xa0', '', text)
... |
ShuteLee/submit_to_site | main.py | # encoding=utf8
from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
import time
import os
'''
Update your chrome
Download the latest chromedriver
Put all the papers in one directory and update to "paper_dir"
If your chrome says "THE ... |
B-Rad80/code-components | hubQuery/FileDumpParser.py | #FileDumpParser
import csv
import os, zipfile, sys
import codecs
og = os.getcwd()
def unzip(file):
cwd = os.path.join(og, "ZipFIles")
print(cwd)
os.chdir(cwd) # change directory from working dir to dir with files
if(zipfile.is_zipfile(file)):
with zipfile.ZipFile(file,"r") as zip_ref:
zip_ref.extractall(cwd... |
B-Rad80/code-components | getInHub.py | import requests
import simplejson as json
import designation
key = "<KEY>"
def getCoord(addr): #takes plaintext address and returns coordinates
payload = {'address':addr, 'key':key} #puts paramaters for url in dictionary, to be passed in next line
mapsResponse = requests.get('https://maps.googleapis.com/maps... |
B-Rad80/code-components | FileDumpParser.py | # FileDumpParser
import csv
import os
import zipfile
import sys
import io
import glob
import pyap
import docx
import codecs
class FileDumpParser:
def __init__(self):
self.og = os.getcwd()
self.debug = False
def __init__(self, d):
self.og = os.getcwd()
self.debug = d
def u... |
B-Rad80/code-components | mysite/accounts/views.py | from django.shortcuts import render
# Create your views here.
def signup(request):
return render(request, 'app/signup.html')
def signin(request):
return render(request, 'app/signup.html') |
B-Rad80/code-components | designation.py | <reponame>B-Rad80/code-components<gh_stars>0
import psycopg2
import os
def getDesignation(countyCode,tractCode):
#if type(countyCode) != str or type(tractCode): #if addr is not a string, throws error
# raise ValueError('countyCode and tractCode must be type str')
# DATABASE_URL = os.environ['DATABASE_UR... |
B-Rad80/code-components | hubQuery/views.py | <filename>hubQuery/views.py
from django.shortcuts import render
from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect
from .forms import queryForm, massForm, FileForm
from django.conf import settings
from django.core.files.storage import FileSystemStorage
import getInHub
import Fi... |
B-Rad80/code-components | hubQuery/apps.py | from django.apps import AppConfig
class hubQueryConfig(AppConfig):
name = 'hubQuery'
|
B-Rad80/code-components | hubQuery/forms.py | <filename>hubQuery/forms.py
from django import forms
class queryForm(forms.Form):
addr_in = forms.CharField(label='addr in', max_length=100)
class massForm(forms.Form):
addr_in = forms.CharField(label='addr in', max_length=100)
addr_in2 = forms.CharField(label='addr in', max_length=100)
name_in = form... |
B-Rad80/code-components | polls/urls.py | <reponame>B-Rad80/code-components<filename>polls/urls.py
"""urls.py
"""
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
] |
B-Rad80/code-components | mysite/urls.py | <gh_stars>0
"""mysite URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
... |
B-Rad80/code-components | boards/views.py | from django.shortcuts import render
# Create your views here.
from django.shortcuts import render_to_response
def home(request):
return render_to_response('app/menu.html')
def aboutUs(request):
return render_to_response('app/about.html') |
B-Rad80/code-components | getInHub_test.py | <reponame>B-Rad80/code-components
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
getInHub.py testing file
"""
import unittest
import getInHub
import requests
import simplejson as json
import designation
class TextprocTestCase(unittest.TestCase):
@classmethod
def setUpClass(cls):
pass
@classmethod
def tea... |
GH0STsama/GhostNoobBot | noob.py | <reponame>GH0STsama/GhostNoobBot
from telethon import TelegramClient, Button
from telethon.events import NewMessage
from telethon.tl.custom import Message
from pyshorteners import Shortener
from os import getenv, path, makedirs
from qrcode import make
from yarl import URL
try:
from secure import *
AP... |
milos85vasic/Apache-Factory-Toolkit | main_proxy.py | import json
import getpass
import sys
from commands import *
from configuration import *
from system_configuration import *
account = getpass.getuser()
if sys.argv.__len__() >= 2:
account = sys.argv[1]
print("Account passed as parameter: " + account)
system_configuration = get_system_configuration()
schedu... |
milos85vasic/Apache-Factory-Toolkit | websetup_run.py | <reponame>milos85vasic/Apache-Factory-Toolkit
import sys
from commands import *
from configuration import *
branch = "master"
if __name__ == '__main__':
what = sys.argv[1]
if len(sys.argv) >= 3:
branch = sys.argv[2]
if what == apache_factory:
print("Apache server factory application reco... |
milos85vasic/Apache-Factory-Toolkit | wipe.py | import os
import sys
source_file = ""
destination_file = ""
replacements = []
for arg in sys.argv:
index = sys.argv.index(arg)
if index == 1:
source_file = arg
if index == 2:
destination_file = arg
if index >= 3:
replacements.append(arg)
if os.path.isfile(source_file):
pri... |
milos85vasic/Apache-Factory-Toolkit | mysql_common.py | import sys
from .commands import *
from .mysql_common_5560 import *
mysql_init_tmp = "init.tmp"
def get_account_from_sys_argv():
return sys.argv[1]
def user_home():
return get_home_directory_path(get_account_from_sys_argv())
def get_mysql_bin_directory():
# MySQL 8.0:
# return user_home() + "/" +... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.