repo_name stringlengths 6 97 | path stringlengths 3 341 | text stringlengths 8 1.02M |
|---|---|---|
dsvensson/advent-of-code | 2020/python/day10.py | sample = """
16
10
15
5
1
11
7
19
6
12
4
""".strip()
sample2 = """
28
33
18
42
31
14
46
20
48
47
24
23
49
45
19
38
39
11
1
32
25
35
8
17
7
9
4
2
34
10
3
""".strip()
from collections import deque
data = sample
#data = open("../data/day10.input").read().strip()
plugs = deque(sorted((int(x) for x in data.split("\n... |
dsvensson/advent-of-code | 2019/python/day5.py | s = "1,9,10,3,2,3,11,0,99,30,40,50"
s = open("../data/day5.input").read()
def decode(op):
opmode = op % 100
pmode = op // 100
c = pmode // 100
b = (pmode % 100) // 10
a = pmode % 10
return (opmode, a, b, c)
def read(t, pc):
return t[t[pc]]
def readi(t, pc):
return t[pc]
def write(t,... |
dsvensson/advent-of-code | 2020/python/day9.py | <filename>2020/python/day9.py
from itertools import permutations
sample = """
35
20
15
25
47
40
62
55
65
95
102
117
150
182
127
219
299
277
309
576
""".strip()
data = [int(x) for x in sample.split("\n")]
data = [int(x) for x in open("../data/day9.input")]
preamble=25
for i, e in enumerate(data):
if i < preambl... |
dsvensson/advent-of-code | 2018/python/day10.py | #!/usr/bin/env python3
import numpy as np
import re
# first version actually visual inspection with matplotlib
def solve(input):
data = np.array([(int(x),int(y),int(vx),int(vy))
for (x,y,vx,vy)
in re.findall("[^<]+<([^,]+),([^>]+)>[^<]+<([^,]+),([^>]+)>", input)])
p =... |
dsvensson/advent-of-code | 2018/python/day3.py | <gh_stars>0
#!/usr/bin/env python3
import re
with open("../data/day3.input") as fd:
squares = []
max_x = 0
max_y = 0
for line in fd:
cid, sx, sy, sw, sh = re.findall("#([^ ]+) @ ([^,]+),([^:]+): ([^:]+)x([\d]+)", line)[0]
x, y, w, h = int(sx),int(sy),int(sw),int(sh)
squares.ap... |
dsvensson/advent-of-code | 2020/python/day1.py | <reponame>dsvensson/advent-of-code
from itertools import combinations
from operator import mul, eq
from functools import partial
import time
def compose(*func):
def c(f, g):
return lambda x : f(g(x))
return reduce(c, func, lambda x : x)
def solve(expense, rank):
return map(partial(reduce, mul), fi... |
dsvensson/advent-of-code | 2019/python/day18.py | <gh_stars>0
import networkx
import collections
t = """
#########
#b.A.@.a#
#########
""".strip()
t = t.split("\n")
def find_stuff(chart):
start = None
paths = set([])
keys = {}
doors = {}
for y, row in enumerate(chart):
for x, col in enumerate(row):
if col == "#":
... |
dsvensson/advent-of-code | 2019/python/day22.py | <reponame>dsvensson/advent-of-code<gh_stars>0
import re
def parse_result(v):
return [int(x) for x in v.split(" ")[1:]]
t = """
cut 6
deal with increment 7
deal into new stack
""".strip()
tr = parse_result("Result: 3 0 7 4 1 8 5 2 9 6")
# t = """
# deal with increment 7
# deal with increment 9
# cut -2
# """
# tr... |
dsvensson/advent-of-code | 2020/python/day13.py | from operator import itemgetter
sample = """
939
7,13,x,x,59,x,31,19
""".strip()
data = sample.split("\n")
data = open("../data/day13.input").read().split("\n")
t0 = 0
#t0 = 754018 - 7
#t0 = 100000000000000
#t0 = 100000000000004
arrival = int(data[0].strip())
#data[1] = "67,7,59,61"
#data[1] = "67,x,7,59,61"
#data[... |
dsvensson/advent-of-code | 2018/python/day14.py | <gh_stars>0
#!/usr/bin/env python3
import time
def part_one(value):
elf1 = 0
elf2 = 1
board = [3,7]
count = len(board)
while count < value:
v1 = board[elf1]
v2 = board[elf2]
v = v1 + v2
if v < 10:
board.append(v)
count += 1
else:
... |
dsvensson/advent-of-code | 2019/python/day16.py | <reponame>dsvensson/advent-of-code
from itertools import cycle, islice, chain, product, starmap, repeat
import operator
import math
import time
#next(pattern)
#print(list(zip(t, cycle(pattern))))
#print(sum(starmap(operator.mul, map(lambda p: zip(t, cycle(p)), map(lambda x: chain([0] * x, islice(pattern, 0, len(t... |
NovaJuan/partylist-cli-python | main.py | # Create a party list usign python and commands
# '--add' or '-a' to add a new guest
# '--list' or '-l' to get the list of guests
# '--remove' or '-r' to remove a guest
# '--remove-index' or '-ri' to remove a guest with a specific index
# '--dump' or '-D' to dump the list
import sys
import os
import platform
from meth... |
NovaJuan/partylist-cli-python | methods/list_handlers.py | import sys
from methods.file_handlers import read_list, write_list
def get_list():
print('\nThese are your current guests:\n')
guests = read_list()
if len(guests) == 0:
print('No guests in your list.')
sys.exit()
for i in range(len(guests)):
print(f'{i + 1}. {guests[i]}\n')
d... |
NovaJuan/partylist-cli-python | methods/file_handlers.py | import sys
def read_list():
guests = []
try:
with open('list.txt', 'r+') as file:
for line in file:
if(line.startswith('# ')):
guests.append(line.replace('# ', '').replace('\n', ''))
file.close()
except FileNotFoundError:
pass
... |
tmogstad/copy-and-cleanup | move_and_cleanup.py | #!/usr/bin/env python
#Copyright (c) 2016 Data Equipment AS
#Author: <NAME> <torm _AT_ dataequipment.no>
#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 ... |
MarkChuCarroll/pcomb | python/pcomb/__init__.py | from abc import abstractmethod
class ParserInput(object):
"""Input to a pcomb parser. This is basically just a simple cons-list interface
on top of whatever kind of input - streams, lists, files - you want to
read parser input from. You should not try to instantiate this directly;
instead, pick an implementati... |
MarkChuCarroll/pcomb | python/calc.py | <filename>python/calc.py
# A simple example of using parser combinators to build an arithmetic
# expression parser.
from pcomb import *
## Actions
def digits_to_number(digits, running=0):
"""Convert a list of digits to an integer"""
if len(digits) == 0:
return running
else:
r = (running * 10) + int(dig... |
MarkChuCarroll/pcomb | python/setup.py | from setuptools import setup
setup(name='pcomb',
version='0.1',
description='Very Basic Combinator Parser',
url='https://github.com/MarkChuCarroll/pcomb',
author='<NAME>',
author_email='<EMAIL>',
license='Apache 2.0',
packages=['pcomb'],
zip_safe=False)
|
maxidl/MMD-critic | digits.py | import math
import matplotlib.pyplot as plt
from pathlib import Path
from sklearn.datasets import load_svmlight_file
import torch
from mmd_critic import Dataset, select_prototypes, select_criticisms
cwd = Path('.')
data_dir = cwd / 'data'
output_dir = cwd / 'output'
data_dir.mkdir(exist_ok=True)
output_dir.mkdir(ex... |
maxidl/MMD-critic | imagenet.py | import math
import matplotlib.pyplot as plt
from pathlib import Path
import torch
from torchvision import datasets, transforms, models
from tqdm.auto import tqdm
from mmd_critic import Dataset, select_prototypes, select_criticisms
cwd = Path('.')
output_dir = cwd / 'output'
imagenet_root = Path('~/ILSVRC2012/')
spli... |
yachuan/DCRNN_PyTorch | dcrnn_train_pytorch.py | <filename>dcrnn_train_pytorch.py
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import yaml
from model.pytorch.dcrnn_supervisor import DCRNNSupervisor
from lib.utils import load_graph_data
def main(args):
with open(args.config_filena... |
jinkai-premium/MWS_Cup2019 | setup.py | <reponame>jinkai-premium/MWS_Cup2019
from pathlib import Path
from setuptools import setup, find_packages
setup(
name='mwscup2019_jinkai-premium',
version="1.0.0",
author='s.nakano',
license='MIT',
packages=find_packages(exclude=()),
install_requires=[require for require in Path(Path(__file__).... |
jinkai-premium/MWS_Cup2019 | scripts/indices_evtxfiles.py | <reponame>jinkai-premium/MWS_Cup2019
# coding: utf-8
import sys
from pathlib import Path
from evtxtoelk import EvtxToElk
sys.path.append(str(Path(__file__).parent.parent))
from src.models.Config import Config
def main():
"""
Overview:
bulk_indice evtx to elastic_search
Usage:
```
... |
jinkai-premium/MWS_Cup2019 | src/run.py | # coding: utf-8
from typing import List
from pathlib import Path
from src.models.Config import Config
from src.models.Types import EventLogs
from src.models.PlantUml import PlantUml
from src.models.ElasticSearchController import ElasticSearchController
from src.models.EventLog import EventLog_Logon, EventLog_Logoff, E... |
jinkai-premium/MWS_Cup2019 | src/models/Config.py | # coding: utf-8
from pathlib import Path
from yaml import load, BaseLoader
class Config(object):
def __init__(self):
self.root_directory = Path(__file__).parent.parent.parent
self.config_file = self.root_directory / Path('src/configs/config.yaml')
self.load_settings()
def load_setting... |
jinkai-premium/MWS_Cup2019 | src/models/Types.py | # coding: utf-8
from typing import List, Union
from src.models.EventLog import EventLog, EventLog_Logon, EventLog_Logoff
EventLogs = List[Union[EventLog, EventLog_Logon, EventLog_Logoff]]
|
jinkai-premium/MWS_Cup2019 | src/console_run.py | # coding: utf-8
from typing import List
from pathlib import Path
from subprocess import check_output
import click
from src.models.Config import Config
from src.models.Types import EventLogs
from src.models.PlantUml import PlantUml
from src.models.ElasticSearchController import ElasticSearchController
from src.models.... |
jinkai-premium/MWS_Cup2019 | src/models/ElasticSearchController.py | # coding: utf-8
from typing import List
from elasticsearch import Elasticsearch
from src.models.Config import Config
class ElasticSearchController(object):
def __init__(self, index_name: str) -> None:
c = Config()
self.es = Elasticsearch(f"{c.ELASTICSEARCH_HOST}:{c.ELASTICSEARCH_PORT}")
... |
jinkai-premium/MWS_Cup2019 | scripts/trans_l2tcsv.py | # coding: utf-8
import sys
import subprocess
from pathlib import Path
"""
Overview:
trans evtx -> l2tcsv.
Usage:
```
$ python trans_l2tcsv.py {TARGET_DIRECTORY}
```
"""
basedir = Path(sys.argv[1])
sourcefiles = list(basedir.glob('**/*.evtx'))
for evtx in sourcefiles:
subprocess.run(f"docker run ... |
jinkai-premium/MWS_Cup2019 | src/models/EventLog.py | <gh_stars>0
# coding: utf-8
from typing import List
class EventLog(object):
def __init__(self, raw: dict) -> None:
self.id = get_dict(raw, '_id')
self.index = get_dict(raw, '_index')
self.timestamp = get_dict(raw, '_source.body.@timestamp').replace('T', ' ').split('.')[0]
self.even... |
jinkai-premium/MWS_Cup2019 | src/models/PlantUml.py | # coding: utf-8
from typing import List
from subprocess import check_output
from pathlib import Path, PosixPath
from functools import singledispatch
from src.models.EventLog import EventLog_Logon, EventLog_Logoff, EventLog_DetectMalware
from src.models.Types import EventLogs
class PlantUml(object):
def __init__(... |
jonhilgart22/allennlp | allennlp/common/logging.py | import logging
from logging import Filter
import os
from os import PathLike
from typing import Union
import sys
class AllenNlpLogger(logging.Logger):
"""
A custom subclass of 'logging.Logger' that keeps a set of messages to
implement {debug,info,etc.}_once() methods.
"""
def __init__(self, name)... |
Qkrisi/discordplays-ktane | DiscordPlaysKTaNEBot.py | <gh_stars>1-10
from json import loads
from twitchio.ext import commands
import discord
import asyncio
import re
TwitchContext = None
DiscordChannel = None
intents = discord.Intents.default()
intents.members = True
client = discord.Client(intents=intents)
EmojiOverrides = {}
TwitchOverrides = {}
Chan... |
kv6737/missingValues | setup.py | <filename>setup.py
# -*- coding: utf-8 -*-
"""
Created on Mon Feb 19 16:06:07 2020
@author: <NAME>
"""
import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name="missingValues-kvarshney-101703295",
version="1.0.3",
author="<NAME>",
... |
kv6737/missingValues | missingValues.py | <reponame>kv6737/missingValues<filename>missingValues.py
import numpy as np
import pandas as pd
import sys
from sklearn.impute import SimpleImputer
def missing(dataset):
if dataset.shape[0]==0:
return print("empty dataset")
else:
X=dataset.iloc[:,0:3].values
imputer = Simp... |
simingweng/incubator-heron | heron/instance/src/python/utils/tuple.py | #!/usr/bin/env python
# -*- encoding: utf-8 -*-
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache... |
simingweng/incubator-heron | heron/tools/ui/src/python/handlers/api/topology.py | #!/usr/bin/env python
# -*- encoding: utf-8 -*-
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache... |
simingweng/incubator-heron | heron/tools/cli/src/python/opts.py | #!/usr/bin/env python
# -*- encoding: utf-8 -*-
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache... |
simingweng/incubator-heron | heron/tools/ui/src/python/handlers/ranges.py | #!/usr/bin/env python
# -*- encoding: utf-8 -*-
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache... |
simingweng/incubator-heron | heron/instance/src/python/network/event_looper.py | <gh_stars>0
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you unde... |
simingweng/incubator-heron | heron/tools/cli/src/python/update.py | <reponame>simingweng/incubator-heron<gh_stars>0
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The A... |
simingweng/incubator-heron | heronpy/streamlet/impl/reducebykeyandwindowbolt.py | <reponame>simingweng/incubator-heron<filename>heronpy/streamlet/impl/reducebykeyandwindowbolt.py
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional inf... |
simingweng/incubator-heron | heron/shell/src/python/handlers/killexecutorhandler.py | #!/usr/bin/env python
# -*- encoding: utf-8 -*-
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache... |
simingweng/incubator-heron | heron/instance/src/python/utils/misc/custom_grouping_helper.py | #!/usr/bin/env python
# -*- encoding: utf-8 -*-
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache... |
simingweng/incubator-heron | heron/statemgrs/tests/python/configloader_unittest.py | #!/usr/bin/env python
# -*- encoding: utf-8 -*-
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache... |
simingweng/incubator-heron | heronpy/api/metrics.py | #!/usr/bin/env python
# -*- encoding: utf-8 -*-
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache... |
simingweng/incubator-heron | heron/instance/src/python/network/socket_options.py | <gh_stars>0
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you unde... |
simingweng/incubator-heron | heron/tools/admin/src/python/main.py | <reponame>simingweng/incubator-heron
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Ve... |
simingweng/incubator-heron | heron/instance/src/python/utils/metrics/py_metrics.py | #!/usr/bin/env python
# -*- encoding: utf-8 -*-
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache... |
simingweng/incubator-heron | heron/tools/common/src/python/access/tracker_access.py | #!/usr/bin/env python
# -*- encoding: utf-8 -*-
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache... |
simingweng/incubator-heron | heron/instance/tests/python/utils/mock_generator.py | #!/usr/bin/env python
# -*- encoding: utf-8 -*-
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache... |
simingweng/incubator-heron | heron/instance/src/python/basics/base_instance.py | #!/usr/bin/env python
# -*- encoding: utf-8 -*-
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache... |
irfanchahyadi/Space-Shooter | space shooter.py | <reponame>irfanchahyadi/Space-Shooter
import os
import pygame
import math
import random
#FIX VARIABLE
SIZE = (700, 500)
DIR = os.path.split(os.path.abspath(__file__))[0]
PLAYER_IMAGE = os.path.join(DIR, "assets", "spaceShips_001.png")
BULLET1_IMAGE = os.path.join(DIR, "assets", "spaceMissiles_001.png")
BULLET2_IMAGE =... |
TechnoConserve/utah-restoration-projects | sage_grouse_seeds.py | <reponame>TechnoConserve/utah-restoration-projects<filename>sage_grouse_seeds.py
# Written by @TechnoConserve
import os
import time
import requests
from selenium import webdriver
# Project IDs from Utah's Watershed Restoration Initiative that had greater sage-grouse as a primary beneficiary of the project FY2006-FY2... |
isabella232/nomulus | config/presubmits.py | <filename>config/presubmits.py
# Copyright 2019 The Nomulus Authors. All Rights Reserved.
#
# 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
#
... |
DonQueso89/mongoengine | tests/fields/test_decimal_field.py | <reponame>DonQueso89/mongoengine
# -*- coding: utf-8 -*-
from decimal import Decimal
import pytest
from mongoengine import *
from tests.utils import MongoDBTestCase
class TestDecimalField(MongoDBTestCase):
def test_validation(self):
"""Ensure that invalid values cannot be assigned to decimal fields.
... |
DonQueso89/mongoengine | tests/test_replicaset_connection.py | import unittest
from pymongo import MongoClient, ReadPreference
import mongoengine
from mongoengine.connection import ConnectionFailure
CONN_CLASS = MongoClient
READ_PREF = ReadPreference.SECONDARY
class ConnectionTest(unittest.TestCase):
def setUp(self):
mongoengine.connection._connection_settings = ... |
DonQueso89/mongoengine | tests/test_ci.py | <reponame>DonQueso89/mongoengine<gh_stars>1000+
def test_ci_placeholder():
# This empty test is used within the CI to
# setup the tox venv without running the test suite
# if we simply skip all test with pytest -k=wrong_pattern
# pytest command would return with exit_code=5 (i.e "no tests run")
# ma... |
DonQueso89/mongoengine | tests/fields/test_email_field.py | <reponame>DonQueso89/mongoengine<gh_stars>1-10
# -*- coding: utf-8 -*-
import sys
import pytest
from mongoengine import *
from tests.utils import MongoDBTestCase
class TestEmailField(MongoDBTestCase):
def test_generic_behavior(self):
class User(Document):
email = EmailField()
user =... |
DonQueso89/mongoengine | tests/test_connection.py | import datetime
from bson.tz_util import utc
import pymongo
from pymongo import MongoClient, ReadPreference
from pymongo.errors import InvalidName, OperationFailure
import pytest
try:
import unittest2 as unittest
except ImportError:
import unittest
import mongoengine.connection
from mongoengine import (
... |
DonQueso89/mongoengine | mongoengine/queryset/__init__.py | from mongoengine.errors import *
from mongoengine.queryset.field_list import *
from mongoengine.queryset.manager import *
from mongoengine.queryset.queryset import *
from mongoengine.queryset.transform import *
from mongoengine.queryset.visitor import *
# Expose just the public subset of all imported objects and const... |
DonQueso89/mongoengine | tests/test_common.py | import unittest
import pytest
from mongoengine import Document
from mongoengine.common import _import_class
class TestCommon:
def test__import_class(self):
doc_cls = _import_class("Document")
assert doc_cls is Document
def test__import_class_raise_if_not_known(self):
with pytest.rai... |
DonQueso89/mongoengine | tests/queryset/test_field_list.py | import unittest
import pytest
from mongoengine import *
from mongoengine.queryset import QueryFieldList
class TestQueryFieldList:
def test_empty(self):
q = QueryFieldList()
assert not q
q = QueryFieldList(always_include=["_cls"])
assert not q
def test_include_include(self):... |
BFFoxDen/exchange-api | exchange_api/exchange.py | <gh_stars>0
import json
class Exchange:
def __init__(self, params):
self.params = params
self.__wallets = {}
def proc(self):
raise NotImplementedError("Implementation Required.")
def add_wallet(self, identifier, quantity, cost_basis, currency_name):
self.__w... |
BFFoxDen/exchange-api | exchange_api/__init__.py | <reponame>BFFoxDen/exchange-api
from .exchange import Exchange
|
Crypt0knights/Plagiarism-Detector | sort.py | import json
def main():
f=open('./result.json')
data = json.load(f)
urls={}
final= {}
for i in range(len(data)):
if data[i]['url'] == None:
pass
else:
urls[data[i]['Percents']]=data[i]['url']
sort_percent = sorted(urls, reverse = True)[:5]
print(sort_percent)
for key in sort_percent:
final[key... |
Crypt0knights/Plagiarism-Detector | script/modify_text_file.py | <filename>script/modify_text_file.py
import nltk
import string
from nltk.tokenize import sent_tokenize, word_tokenize
from nltk.corpus import stopwords
clean_source = open("clean_sample.txt", "w")
source_content = open("sample.txt","r").read()
stop_words = list(stopwords.words("english"))
stop_words.append("the")
sto... |
Crypt0knights/Plagiarism-Detector | script.py | import nltk
import string
from nltk.tokenize import sent_tokenize
def main():
clean_source = open("./search.txt", "w")
source_content = open("file.txt","r").read()
for line in sent_tokenize(source_content):
line = line.translate(str.maketrans('', '', string.punctuation))
clean_source.writ... |
Crypt0knights/Plagiarism-Detector | aho.py | <reponame>Crypt0knights/Plagiarism-Detector
class ahoh:
def __init__(self):
self.maxs=5000
self.maxc=27
self.out=[0]*self.maxs
self.f=[-1]*self.maxs
self.g=[]
for i in range(self.maxs):
self.g.append([])
for j in range(self.maxc):
... |
Crypt0knights/Plagiarism-Detector | search.py | <gh_stars>1-10
from bloom_filter import *
from aho import *
from collections import deque
import ahocorasick as ahc
import math
import os
from os import path
global prime_nos,phrases,word_code,input_phrases,input_phrases_idx
prime_nos=(113,117,119,123,129,131,137)
phrases=[]
word_code=[]
input_phrases=[]
input_phrases_... |
Crypt0knights/Plagiarism-Detector | script/working string matching scripts/bloom_filter.py | <reponame>Crypt0knights/Plagiarism-Detector
from bitarray import *
class bloom_filter:
def __init__(self, size):
self.size = size
self.first_filter, self.second_filter = bitarray(size), bitarray(size)
self.first_filter.setall(0)
self.second_filter.setall(0)
def set_bit(self, f... |
Crypt0knights/Plagiarism-Detector | scrape.py | <filename>scrape.py
from requests import get
from requests.exceptions import RequestException
from bs4 import BeautifulSoup
from bs4.element import Comment
import urllib.request
import json
import http.client
import PyPDF2
url_percent=open('./url_percent.json')
data = json.load(url_percent)
def tag_visible(elemen... |
yassinebebba/django-ecommerce | shop/migrations/0002_auto_20200825_0951.py | <reponame>yassinebebba/django-ecommerce<filename>shop/migrations/0002_auto_20200825_0951.py
# Generated by Django 3.0.1 on 2020-08-25 08:51
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('shop', '0001_initial'),
]
... |
yassinebebba/django-ecommerce | shop/admin.py | from django.contrib import admin
from .models import Product, Category, Basket, BasketProduct
admin.site.register(Category)
admin.site.register(Product)
admin.site.register(Basket)
admin.site.register(BasketProduct)
|
yassinebebba/django-ecommerce | shop/models.py | from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save, pre_delete
class Category(models.Model):
class Meta:
verbose_name_plural = 'categories'
name = models.CharField(max_length=100)
def __str__(self):
return self.name
c... |
yassinebebba/django-ecommerce | shop/views.py | from django.http import HttpResponseForbidden, JsonResponse
from django.shortcuts import render, redirect, get_object_or_404
from django.urls import reverse
from django.contrib.messages.views import messages
from django.views import View
from .models import Product
from datetime import datetime
from django.contrib.aut... |
yassinebebba/django-ecommerce | shop/urls.py | <reponame>yassinebebba/django-ecommerce<gh_stars>0
from django.urls import path
from django.conf import settings
from django.conf.urls.static import static
from django.contrib.auth.views import LogoutView
from .views import (
home_view, CustomLoginView, register_view, ProductDetailView, basket_view, CheckoutView
)
... |
khklau/T800 | src/strategy/protoss/voidray_swarm.py | import sc2
from sc2 import run_game, maps, Race, Difficulty
from sc2.player import Bot, Computer
from sc2.constants import NEXUS, PROBE, PYLON, ASSIMILATOR, GATEWAY, CYBERNETICSCORE
from sc2.constants import STALKER, STARGATE, VOIDRAY, OBSERVER, ROBOTICSFACILITY
from sc2.position import Point2
from datetime import dat... |
khklau/T800 | src/exe_bot/baseline.py | <reponame>khklau/T800
import sc2
from sc2 import run_game, maps, Race, Difficulty
from sc2.player import Bot, Computer
from strategy.protoss.cannon_rush import CannonRush
from strategy.protoss.voidray_swarm import VoidRaySwarm
from datetime import datetime
# TODO the strategy selection heuristic should be based on ... |
IAmCorbin/pibooth | pibooth/controls/gpio.py | <gh_stars>0
# -*- coding: utf-8 -*-
"""
Mocks for tests on other HW than Raspberry Pi.
Pin can be triggered using::
$ kill -<GPIO pin number> <pibooth PID>
"""
import os
import time
import signal
from functools import partial
from pibooth.utils import LOGGER
class GpioMock(object):
BOARD = 'board'
IN ... |
IAmCorbin/pibooth | pibooth/language.py | # -*- coding: utf-8 -*-
"""Pibooth language handling.
"""
import io
import os
import os.path as osp
from pibooth.utils import LOGGER, open_text_editor
try:
from configparser import ConfigParser
except ImportError:
# Python 2.x fallback
from ConfigParser import ConfigParser
PARSER = ConfigParser()
CURRE... |
IAmCorbin/pibooth | pibooth/pictures/pool.py | <gh_stars>0
# -*- coding: utf-8 -*-
import multiprocessing
class PicturesMakersPool(object):
def __init__(self):
self._pool = None
self._async_results = []
def add(self, maker):
"""Add a new picture maker and build it asyncronously.
"""
if not self._pool:
... |
IAmCorbin/pibooth | pibooth/controls/camera/__init__.py | # -*- coding: utf-8 -*-
from pibooth.utils import LOGGER, pkill
from pibooth.controls.camera.rpi import RpiCamera, rpi_camera_connected
from pibooth.controls.camera.arducam import ArduCamera, ardu_camera_connected
from pibooth.controls.camera.gphoto import GpCamera, gp_camera_connected
from pibooth.controls.camera.gph... |
IAmCorbin/pibooth | pibooth/controls/__init__.py | # -*- coding: utf-8 -*-
try:
from RPi import GPIO
except ImportError:
# GPIO library only existes on Raspberry Pi
from pibooth.controls.gpio import GpioMock
GPIO = GpioMock()
|
IAmCorbin/pibooth | pibooth/controls/camera/arducam.py | # -*- coding: utf-8 -*-
import time
import subprocess
try:
import pibooth.controls.camera.arducam_mipicamera as arducam
except ImportError:
arducam = None # arducam is optional
import v4l2
from pibooth.utils import LOGGER, memorize
from pibooth.language import get_translated_text
from pibooth.controls.camera.... |
IAmCorbin/pibooth | tests/conftest.py | <reponame>IAmCorbin/pibooth
# -*- coding: utf-8 -*-
import os
import pytest
from PIL import Image
CAPTURES_DIR = os.path.join(os.path.dirname(__file__), 'captures')
@pytest.fixture(scope='session')
def captures_portrait():
return [Image.open(os.path.join(CAPTURES_DIR, 'portrait', img))
for img in o... |
IAmCorbin/pibooth | pibooth/controls/camera/arducam_mipicamera.py | '''
This script is a wrapper for the libarducam_mipicamera.so dynamic library.
To use this script you need to pre-install libarducam_mipicamera.so
https://github.com/ArduCAM/MIPI_Camera/tree/master/RPI
'''
from ctypes import *
import numpy as np
import sys
from pibooth.utils import LOGGER
try:
LOGGER.info("cdll.L... |
IAmCorbin/pibooth | pibooth/controls/printer.py | # -*- coding: utf-8 -*-
try:
import cups
from cups_notify import Subscriber, event
except ImportError:
cups = None # CUPS is optional
import tempfile
import os.path as osp
import pygame
from PIL import Image
from pibooth.utils import LOGGER
from pibooth.pictures import get_picture_maker
PRINTER_TASKS_... |
dberardi2020/MovieSorter | definitions/tasks.py | <reponame>dberardi2020/MovieSorter
import shutil
import subprocess
import sys
import time
from os import path
from InquirerPy import inquirer
from InquirerPy.base import Choice
from Classes import Directories, ANSI, Statistics
from Classes.Logger import Logger
from Classes.Movie import Movie
from definitions import c... |
dberardi2020/MovieSorter | definitions/helpers.py | import re
import time
from Classes import Directories
from Classes import Movie
from definitions import const
def convert_to_gb(size_in_bytes):
return round(size_in_bytes * (10 ** -9))
def format_time(seconds):
return time.strftime("%Hh%Mm%Ss", time.gmtime(seconds))
def run_time(start_time):
return t... |
dberardi2020/MovieSorter | Classes/Movie.py | import shutil
from os import path, remove, rename
from pathlib import Path
from Classes import Directories
from definitions import helpers, const
class Movie:
def __init__(self, movie):
self.name = movie.name
self.path = movie.path
self.dir = Path(self.path).parent
self.size = hel... |
dberardi2020/MovieSorter | definitions/const.py | <reponame>dberardi2020/MovieSorter
import shutil
from os import path
dev = False
upload_limit = 8
external_drive = "E:"
if dev:
base_dir = path.join(external_drive, "Test Movies")
else:
base_dir = path.join(external_drive, "Plex Movies")
data_dir = path.join(base_dir, "data")
log_dir = path.join(data_dir,... |
dberardi2020/MovieSorter | Classes/ANSI.py | <reponame>dberardi2020/MovieSorter
def up_char(n):
return f"\033[{n}A"
def down_char(n):
return f"\033[{n}B"
def clr_char():
return "\x1B[K"
|
dberardi2020/MovieSorter | Classes/Logger.py | from datetime import datetime
from os import path, mkdir
from definitions import const
class Logger:
def __init__(self):
log_folder = path.join(const.log_dir, datetime.now().strftime('%m-%d-%Y @ %Hh%Mm%Ss'))
mkdir(log_folder)
log_file_name = path.join(log_folder, "compression_log.txt")
... |
dberardi2020/MovieSorter | Classes/Statistics.py | <filename>Classes/Statistics.py
from os import path
import pandas as pd
from definitions import const, helpers
class _Statistics:
def __init__(self, name):
self.pickle = path.join(const.data_dir, f"{name}.pkl")
def _create_pickle(self):
pd.DataFrame([]).to_pickle(self.pickle)
def _get_... |
dberardi2020/MovieSorter | Classes/Directories.py | <filename>Classes/Directories.py
from os import path, scandir
from Classes.Movie import Movie
from definitions import const
class _Directory:
def __init__(self, name):
self.name = name
self.path = path.join(const.base_dir, name)
def append(self, file_name):
return path.join(self.path... |
dberardi2020/MovieSorter | main.py | <filename>main.py
#!/usr/bin/env python
import sys
from os import path
import colorama
from definitions import task_selector, const
if __name__ == '__main__':
colorama.init()
print(f"MovieSorter execution started... {const.dev_flag}{const.compression_warning}\n")
if not path.exists(const.external_drive)... |
dberardi2020/MovieSorter | definitions/task_selector.py | import types
from InquirerPy import inquirer
from InquirerPy.base.control import Choice
from definitions import tasks
task_list = types.SimpleNamespace()
task_list.run_dev = "Run Dev Function"
task_list.upload = "Upload to NAS"
task_list.run_compression = "Run Compression"
task_list.compress_upload = "Compress and ... |
ursinus-cs371-s2022/HW2_PlantCellSegmentation | cells.py | <reponame>ursinus-cs371-s2022/HW2_PlantCellSegmentation
import numpy as np
from scipy import ndimage
import matplotlib.pyplot as plt
import skimage.io
from skimage.transform import resize
from skimage.color import rgb2gray
import time
def load_cells_grayscale(filename, n_pixels = 0):
"""
Load in a grayscale im... |
TiltMeSenpai/luna | examples/usb/hid.py | #!/usr/bin/env python3
#
# This file is part of LUNA.
#
# Copyright (c) 2020 <NAME> <<EMAIL>>
# SPDX-License-Identifier: BSD-3-Clause
from nmigen import Elaboratable, Module, Signal
from luna import top_level_cli
from luna.gateware.usb.devices.hid import HIDDevice... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.