repo_name
stringlengths
6
97
path
stringlengths
3
341
text
stringlengths
8
1.02M
markhuyong/galaxy
rest/decorators.py
# -*- coding: utf-8 -*- from functools import wraps import warnings from .exceptions import GalaxyDeprecationWarning def deprecated(use_instead=None): """This is a decorator which can be used to mark functions as deprecated. It will result in a warning being emitted when the function is used. Taken ...
markhuyong/galaxy
crawler/misc/mobile_agents.py
<gh_stars>0 # -*- coding: utf-8 -*- AGENTS = [ "Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_2_1 like Mac OS X; da-dk) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8C148 Safari/6533.18.5", "Mozilla/5.0 (iPhone; U; CPU like Mac OS X; en) AppleWebKit/420 (KHTML, like Gecko) Version/3.0 Mobile/1A543a...
markhuyong/galaxy
crawler/qq/qq/middleware.py
# -*- coding: utf-8 -*- import sys import random import redis import json import logging from cookies import initCookie, updateCookie, removeCookie from scrapy.exceptions import IgnoreRequest from scrapy.utils.response import response_status_message from scrapy.downloadermiddlewares.retry import RetryMiddleware from ...
markhuyong/galaxy
crawler/misc/log.py
import logging # from logging.config import fileConfig # fileConfig('logging_config.ini') logger = logging.getLogger(__name__) # handler = logging.StreamHandler() handler = logging.FileHandler('hello.log') formatter = logging.Formatter( '%(asctime)s %(name)-12s %(levelname)-8s %(message)s') handler.setFormatte...
markhuyong/galaxy
crawler/jianshu/jianshu/settings.py
# -*- coding: utf-8 -*- BOT_NAME = 'jianshu' SPIDER_MODULES = ['jianshu.spiders'] NEWSPIDER_MODULE = 'jianshu.spiders' DOWNLOADER_MIDDLEWARES = { # Engine side # 'crawler.misc.middleware.agent.CustomUserAgentMiddleware': 401, #'scrapy_splash.SplashCookiesMiddleware': 723, #'scrapy_splash.SplashMiddle...
markhuyong/galaxy
tests/shell/qq/launch.py
from scrapy import cmdline cmdline.execute("scrapy crawl qq".split())
markhuyong/galaxy
tests/test_crawler.py
# -*- coding: utf-8 -*- from scrapy.utils.engine import get_engine_status from twisted.internet import defer from twisted.trial import unittest from rest.core import GalaxyCrawler from .servers import MockServer from .spiders import SingleRequestSpider from .utils import get_settings class TestCrawler(unittest.Test...
markhuyong/galaxy
rest/cmdline.py
# -*- coding: utf-8 -*- from ConfigParser import SafeConfigParser, NoOptionError, NoSectionError import argparse import os import sys from scrapy.utils.conf import closest_scrapy_cfg from scrapy.utils.misc import load_object from twisted.application import app from twisted.application.internet import TCPServer from tw...
markhuyong/galaxy
crawler/misc/xicidaili.py
<gh_stars>0 #!/usr/bin/env python # -*- coding: UTF-8 -*- #------------------------------------------------------------------------- # 程序:xicidaili.py # 版本:0.1 # 作者:ly # 日期:编写日期201l/11/16 # 语言:Python 2.7 # 操作:python referer_forge.py # 功能:从www.xicidaili.com网站采集代理信息并存入数据库 #----------------------------------...
markhuyong/galaxy
crawler/misc/middleware/proxy.py
<gh_stars>0 # -*- coding: utf-8 -*- from ..proxy import PROXIES, FREE_PROXIES import requests import redis import random class CustomHttpProxyFromRedisMiddleware(object): def __init__(self, settings, crawler): self.rconn = settings.get("RCONN", redis.Redis( crawler.settings.get('REDIS_HOST', ...
markhuyong/galaxy
tests/utils.py
# -*- coding: utf-8 -*- import os import socket from scrapy.settings import Settings from . import TESTS_PATH LOCALHOST = 'localhost' def get_testenv(): env = os.environ.copy() env['PYTHONPATH'] = os.path.realpath(os.path.join(TESTS_PATH, '..')) return env def get_settings(): """Settings with all...
markhuyong/galaxy
tests/qq/test_photo_status.py
''' Offline tests ''' import json from builtins import range from unittest import TestCase from mock import MagicMock from crawler.qq.qq.spiders.photo import QqPhotoSpider from scrapy.http import TextResponse from scrapy.http import Request from crawler.qq.qq.items import QqStatusItem, QqPhotoItem class TestQqPhoto...
markhuyong/galaxy
tests/__init__.py
# -*- coding: utf-8 -*- import os TESTS_PATH = os.path.realpath(os.path.dirname(__file__)) PROJECT_PATH = os.path.realpath(os.path.join(TESTS_PATH, '..'))
markhuyong/galaxy
crawler/qq/qq/items.py
<gh_stars>0 # -*- coding: utf-8 -*- # Define here the models for your scraped items from scrapy import Item, Field class QqStatusItem(Item): text = Field() publishTime = Field() pictures = Field() class QqPhotoItem(Item): publishTime = Field() images = Field() class PictureItem(Item): ur...
markhuyong/galaxy
tests/test_crawl_manager.py
# -*- coding: utf-8 -*- import os from time import sleep import datetime import pytest from mock import patch, MagicMock from scrapy import Item from scrapy.exceptions import DontCloseSpider from scrapy.http import Response from scrapy.settings import Settings from scrapy.utils.test import get_crawler from twisted.int...
markhuyong/galaxy
tests/test_settings/__init__.py
<gh_stars>0 # -*- coding: utf-8 -*- from mock import patch from twisted.trial import unittest from rest.conf import Settings from . import default_settings class TestSettings(unittest.TestCase): @patch('rest.conf.default_settings', default_settings) def setUp(self): self.settings = Settings() ...
markhuyong/galaxy
tests/test_resource_crawl.py
# -*- coding: utf-8 -*- import pytest from twisted.trial import unittest from twisted.web.error import Error import requests from rest.resources import CrawlResource from .servers import galaxyTestServer, MockServer @pytest.fixture() def server(request): target_site = MockServer() target_site.start() se...
markhuyong/galaxy
crawler/jianshu/jianshu/spiders/lectures.py
# -*- coding: utf-8 -*- import json import logging from scrapy import Selector from scrapy.http.cookies import CookieJar from scrapy.http.request import Request from ..items import LecturesItem from ..utils import CommonSpider from ..utils import BaseHelper logger = logging.getLogger(__name__) class LectureSpide...
markhuyong/galaxy
rest/protocols.py
<filename>rest/protocols.py # -*- coding: utf-8 -*- from twisted.internet.protocol import Protocol class HTTPReturner(Protocol): def __init__(self, finished): self._data = "" self.deferred = finished def dataReceived(self, data): self._data += data def connectionLost(self, reason...
markhuyong/galaxy
crawler/weibo/weibo/cookies.py
<filename>crawler/weibo/weibo/cookies.py<gh_stars>0 # -*- coding: utf-8 -*- import base64 import binascii import json import logging import random import time import requests import rsa from selenium import webdriver from selenium.webdriver.common.desired_capabilities import DesiredCapabilities from yumdama import i...
markhuyong/galaxy
crawler/qq/qq/utils.py
# -*- coding: utf-8 -*- import random import urllib from scrapy.http.headers import Headers from crawler.misc.spider import CommonSpider from crawler.misc import agents class BaseHelper(object): PROFILE_URL = "https://mobile.qzone.qq.com/profile?hostuin=USER_QQ_NUMBER" SHUOSHU_URL = "https://mobile.qzone.q...
JLivingston01/JasonvsData
data_to_string.py
<reponame>JLivingston01/JasonvsData # -*- coding: utf-8 -*- """ Created on Thu May 11 10:07:20 2017 @author: <NAME> """ ##Transform pandas DFs for other uses ##DF to query string creates string of form 'date=2017-01-01&a=8&b=5&c=6\ndate=2017-01-02&a=3&b=3&c=0' from DF ##df_to_html writes html table from conten...
JLivingston01/JasonvsData
correlation functions.py
<reponame>JLivingston01/JasonvsData<gh_stars>0 # -*- coding: utf-8 -*- """ Created on Thu Jul 27 15:39:50 2017 @author: <NAME> """ ##R-Squared of two arrays/lists/pandas DF columns def rsquaredfn(X,Y): import pandas as pd import numpy as np R = pd.DataFrame() R['X'] = X R['Y'] = Y ...
JLivingston01/JasonvsData
perceptronNN.py
# -*- coding: utf-8 -*- """ Created on Fri Jul 21 10:25:21 2017 @author: <NAME> """ import pandas as pd import numpy as np #Credit to <NAME> for inspiring descent method def perceptron_fit(W0,lrate,iteration,data, sig_weight): w = W0 lrate = lrate n = len(data) k = len(list(data.co...
JLivingston01/JasonvsData
Linear Regression by OLGD and Closed Form.py
<gh_stars>0 # -*- coding: utf-8 -*- """ Created on Mon Jul 24 10:52:46 2017 @author: <NAME> """ import pandas as pd import numpy as np from sklearn import linear_model ##CLOSED FORM LINEAR REGRESSION X = pd.DataFrame() X['int'] = [1,1,1,1,1] X['A'] = [1,2,3,4,5] X['B'] = [3,4,4,6,7] X = X.values ...
JLivingston01/JasonvsData
data manipulation.py
# -*- coding: utf-8 -*- """ Created on Wed May 10 12:58:35 2017 @author: <NAME> """ import pandas as pd import numpy as np check = pd.DataFrame() check['date'] = ['2017-01-01','2017-01-02','2017-01-03','2017-01-04','2017-01-05','2017-01-06','2017-01-07','2017-01-08','2017-01-09','2017-01-10'] check['a'] ...
JLivingston01/JasonvsData
Model Samples.py
<gh_stars>0 # -*- coding: utf-8 -*- """ Created on Thu Mar 30 10:07:21 2017 @author: <NAME> """ ##Several SKlearn example fits with functions to quickly return fit, useful for determining the method which best describes the data (AR2) import pandas as pd import numpy as np from treeinterpreter import treeinte...
minchen57/TextClassifyKeras
temp.py
<gh_stars>0 import os import pandas as pd from sklearn.model_selection import train_test_split CUSTOM_SEED = 43 TEST_SPLIT = 0.2 VALIDATION_SPLIT = 0.25 relativePath = os.getcwd() sentencePath = relativePath + "/data/sample5_sentences_08132018.csv" sentences = pd.read_csv(sentencePath, index_col="Sentence#") sentences...
minchen57/TextClassifyKeras
review_classification_test_dependent.py
<reponame>minchen57/TextClassifyKeras<filename>review_classification_test_dependent.py #!/usr/bin/env python import nltk import pandas as pd import numpy as np import os from gensim.models import Word2Vec from keras.utils import plot_model import matplotlib.pyplot as plt from keras.preprocessing.sequence import pad_se...
minchen57/TextClassifyKeras
review_classification.py
#!/usr/bin/env python import nltk import pandas as pd import numpy as np import os from gensim.models import Word2Vec from keras.utils import plot_model import matplotlib.pyplot as plt from keras.preprocessing.sequence import pad_sequences from keras.layers import Embedding from keras.layers import Dense from keras.la...
minchen57/TextClassifyKeras
process_results.py
import pandas as pd import numpy as np import os relativePath = os.getcwd() path = relativePath + "/Results/08082018-1/" df = pd.read_csv(path+"predicted_result.csv", index_col="Sentence#") jump = int((len(df.columns)+1)/2) print(jump) print(df.columns[jump-1]) #print(df.columns[5], " ", df.columns[5+jump]) values...
evature/botkit-integrations
main.py
<gh_stars>1-10 ''' Created on May 18, 2016 @author: marina ''' from enums import MessagingProviders from amadeus import flights_low_fare_search, amadeus_results_to_facebook from expedia import get_ean_tags_from_webhook_input, expedia_search_request_to_facebook def get_structured_message(messaging_provider, text=None,...
bee-hive/scGeneFit-python
setup.py
<filename>setup.py<gh_stars>10-100 import setuptools with open("README.md", "r") as fh: long_description = fh.read() setuptools.setup( name='scGeneFit', version='1.0.0', author="<NAME>", author_email="<EMAIL>", description="Genetic marker selection with linear programming", long_de...
bee-hive/scGeneFit-python
scGeneFit/functions.py
<filename>scGeneFit/functions.py import numpy as np import matplotlib.pyplot as plt import scipy import time import sklearn import sklearn.manifold import scipy.io from . import data_files def get_markers(data, labels, num_markers, method='centers', epsilon=1, sampling_rate=1, n_neighbors=3, max_constraints=1000, r...
bee-hive/scGeneFit-python
scGeneFit/data_files/__init__.py
try: import importlib.resources as importlib_resources except ImportError: # In PY<3.7 fall-back to backported `importlib_resources`. import importlib_resources def get_data(filename): with importlib_resources.path(__name__, filename) as foo: return str(foo)
YTCdev/yangubot
src/misc.py
<reponame>YTCdev/yangubot import discord from config import Config class Misc: @staticmethod def is_staff(ctx): roles = [role.id for role in ctx.author.roles] return any(id in roles for id in Config.STAFF_IDS) @staticmethod def is_owner(ctx): return ctx.author.id in Config.OWN...
YTCdev/yangubot
src/ccm.py
<filename>src/ccm.py<gh_stars>0 from dataclasses import dataclass from discord.ext import commands from discord import Embed, Message import jsonpickle from config import Config from misc import Misc class CustomCommandsManager(commands.Cog): def __init__(self, bot, prefix=''): self.bot = bot self...
YTCdev/yangubot
src/config_ex.py
from discord import Colour class Config: # WooCommerce API settings # # Get an API key by going to WooCommerce > Settings > Advanced > REST API on # your WordPress installation. WCM_URL = '' WCM_KEY = '' WCM_SECRET = '' # Discord API settings # # Get your bot token at https://...
YTCdev/yangubot
src/bot.py
from time import monotonic from sys import exit import discord from discord.ext import commands from config import Config from ccm import CustomCommandsManager from store import Store from order import Order from misc import Misc ytc = Store(Config.WCM_URL, Config.WCM_KEY, Config.WCM_SECRET) bot = commands.Bot(command...
YTCdev/yangubot
src/order.py
import dateutil.parser from pandas.tseries.offsets import BDay from discord import Embed from config import Config class Order: def __init__(self, json, notes): self.json = json self.notes = notes self.id = json['id'] self.status = json['status'] self.product = json['line_i...
YTCdev/yangubot
src/store.py
<filename>src/store.py from woocommerce import API class Store: def __init__(self, url, key, secret): self.wcapi = API( url=url, consumer_key=key, consumer_secret=secret, wp_api=True, version="wc/v3" ) def get_order(self, order_id): ...
BeanyZoldyck/MTAG
haganai.py
<filename>haganai.py import time import random import math from functools import reduce playerEgo = 50 playerBag = ['stick']#random even is you find money or gifts playerBread = 35 possibleInterests = ["Lexi", "Ali", "Chuck", "Socrates"] relations = {"Lexi": 7, "Ali": 12, "Chuck": -4, ...
BeanyZoldyck/MTAG
quests.py
<reponame>BeanyZoldyck/MTAG import time try: import gift_shop#this file except ModuleNotFoundError: print("(Btw this code will be used where it can access my modular gift shop code)") playerEgo = 100 playerBag = ['stick'] playerBread = 50 possibleInterests = ["Lexi", "Ali", "Chuka", "Socrates"] relations = {"L...
BeanyZoldyck/MTAG
markov_wordgram.py
<gh_stars>0 import random #the main algorithm that will run the game def Markov(sample, length): for i in enumerate(sample): try: ngrams[i[1]].append(sample[i[0]+1]) except KeyError: ngrams[i[1]] = [] try: ngrams[i[1]].append(sample[i[0]+1]) ...
BeanyZoldyck/MTAG
instagramScraped/instagram_scraper.py
<filename>instagramScraped/instagram_scraper.py from time import sleep as s import keyboard import clipboard from guide import file import pyautogui as pag peachsocne = file('lex') textPath = 'lex.txt' def area(t1, t2): return (t1[0],t1[1],t2[0]-t1[0],t2[1]-t1[1]) def capture(): click=True post = pag.screen...
BeanyZoldyck/MTAG
gift_shop.py
#This is a freestlye by <NAME> def displayItems(offSet): print('\n') for i in enumerate(items[offSet:]): print(i[0]+offSet+1,i[1]) def displaySingle(): userItem=int(input("Enter a number to select an item: "))-1 print(f'{descriptions[userItem]}\n{items[userItem]} costs ${prices[userItem]}.') ...
BeanyZoldyck/MTAG
discordScraped/discord_scraper.py
<filename>discordScraped/discord_scraper.py import mouse as m from time import sleep as s import keyboard import clipboard textPath = 'data.txt' beanPath = 'BeanZ.txt' def capture(): """ scrape BeanZ's messages then go next """ topPageLeftCorner = (882,179)#(1329,266) dragAt = (1150, 719) n...
yeladlouni/AnswerSelection
tests/experiment/qa/model/test_pooling_helper.py
import unittest import numpy as np import numpy.testing as npt import tensorflow as tf from experiment.qa.model.helper.pooling_helper import non_zero_tokens, attention_softmax, soft_alignment, \ attentive_pooling_weights, weighted_pooling class TestPoolingHelper(unittest.TestCase): def setUp(self): ...
yeladlouni/AnswerSelection
experiment/qa/model/helper/lw.py
<reponame>yeladlouni/AnswerSelection import tensorflow as tf from tensorflow.python.ops import rnn_cell from experiment import ComponentBase from experiment.qa.model import weight_variable from experiment.qa.model.helper.pooling_helper import non_zero_tokens, attention_softmax class LW(ComponentBase): def __init...
yeladlouni/AnswerSelection
experiment/qa/model/cnn_lstm.py
import tensorflow as tf from experiment.qa.model.cnn import CNNModel from experiment.qa.model.helper.pooling_helper import maxpool from experiment.qa.model.lstm import BiLSTMModel class LSTMCNNModel(CNNModel, BiLSTMModel): def __init__(self, config, config_global, logger): super(LSTMCNNModel, self).__ini...
yeladlouni/AnswerSelection
experiment/qa/evaluation/evaluation.py
<reponame>yeladlouni/AnswerSelection<gh_stars>1-10 from __future__ import division import math import numpy as np import experiment class QAEvaluation(experiment.Evaluation): def __init__(self, config, config_global, logger): super(QAEvaluation, self).__init__(config, config_global, logger) sel...
yeladlouni/AnswerSelection
experiment/qa/model/lw_cnn.py
from experiment.qa.model.cnn import CNNModel from experiment.qa.model.helper.lw import LW from experiment.qa.model.helper.pooling_helper import weighted_pooling class LWCNNModel(CNNModel, LW): def __init__(self, config, config_global, logger): super(LWCNNModel, self).__init__(config, config_global, logger...
yeladlouni/AnswerSelection
experiment/qa/data/semeval/semeval.py
import os from collections import OrderedDict import xml.etree.ElementTree as ET from experiment.qa.data import QAData from experiment.qa.data.reader import ArchiveReader from experiment.qa.data.models import Token, Sentence, TextItem, QAPool, Data, Archive def _get_text_item(text, id): question_tokens = [Toke...
yeladlouni/AnswerSelection
experiment/qa/model/ap_lstm.py
from experiment.qa.model import weight_variable from experiment.qa.model.helper.pooling_helper import attentive_pooling_weights, weighted_pooling from experiment.qa.model.lstm import BiLSTMModel class AttentivePoolingLSTMModel(BiLSTMModel): def build(self, data, sess): self.build_input(data, sess) ...
yeladlouni/AnswerSelection
experiment/qa/model/lstm_lstm.py
<filename>experiment/qa/model/lstm_lstm.py<gh_stars>1-10 from experiment.qa.model.helper.pooling_helper import maxpool from experiment.qa.model.lstm import BiLSTMModel class LSTMLSTMModel(BiLSTMModel): def __init__(self, config, config_global, logger): super(LSTMLSTMModel, self).__init__(config, config_g...
yeladlouni/AnswerSelection
experiment/qa/data/wikiqa/wikiqa.py
import os from collections import OrderedDict from experiment.qa.data import QAData from experiment.qa.data.reader import TSVArchiveReader from experiment.qa.data.models import Token, Sentence, TextItem, QAPool, Data, Archive def _get_text_item(text, id): question_tokens = [Token(t) for t in text.split()] q...
yeladlouni/AnswerSelection
experiment/qa/train/training.py
<filename>experiment/qa/train/training.py import math import numpy as np from experiment.qa.train import QABatchedTraining class InsuranceQATrainingSimple(QABatchedTraining): """This is a simple training method that runs over the training data in a linear fashion, just like in keras.""" def __init__(self, ...
yeladlouni/AnswerSelection
scripts/run_hyperparameter_optimization.py
import importlib import itertools import json import logging import sys import click import numpy as np import tensorflow as tf from experiment.util import replace_dict_values from experiment.config import load_config # Allows the gpu to be used in parallel sess_config = tf.ConfigProto() sess_config.gpu_options.allo...
yeladlouni/AnswerSelection
experiment/qa/model/cnn.py
<filename>experiment/qa/model/cnn.py<gh_stars>1-10 import tensorflow as tf from experiment.qa.model import QAModel, bias_variable, weight_variable from experiment.qa.model.helper.pooling_helper import maxpool_tanh class CNNModel(QAModel): def __init__(self, config, config_global, logger): super(CNNModel,...
yeladlouni/AnswerSelection
experiment/qa/train/training_dynamic.py
<filename>experiment/qa/train/training_dynamic.py # coding=utf-8 import math import numpy as np from experiment.qa.train import QABatchedTraining class InsuranceQATrainingDynamic(QABatchedTraining): """This is a training method that tries to replicate training method used in recent work on QA (esp. insuranceqa...
yeladlouni/AnswerSelection
experiment/qa/model/lw_lstm.py
<filename>experiment/qa/model/lw_lstm.py from experiment.qa.model.helper.lw import LW from experiment.qa.model.helper.pooling_helper import weighted_pooling from experiment.qa.model.lstm import BiLSTMModel class LWLSTMModel(BiLSTMModel, LW): def __init__(self, config, config_global, logger): super(LWLSTM...
ambeimers/cs257
webapp/convert.py
<gh_stars>1-10 ''' <NAME> and <NAME> Converts the dataset from Kaggle into a smaller one to be converted into a postgresql DB ''' import csv import sys csv_folder = 'archive/' def main(): try: artists_file = open(csv_folder + "data_by_artist.csv", newline='') songs_file = o...
ambeimers/cs257
database/olympics.py
''' Author: <NAME>, 28 Jan, 2021 This program does one of five things based on command-line input: Prints a version statement Prints a usage statement for "python3 olympics.py -h" (or --help). You may use argparse or not for command-line parsing and usage statement printing. Lists the names of all the athlete...
ambeimers/cs257
books/books.py
"""<NAME> and <NAME>, CS 257 : books.py January 22, 2021 This program sorts a file by parameters from the command-line.""" import argparse import csv def get_parsed_arguments(): """Analyzes command-line arguments to provide search parameters, and returns a namespace object.""" parser = argparse.ArgumentParser(desc...
ambeimers/cs257
database/config.py
# config.py user = 'beimersa' password = ' ' database = 'olympics'
ambeimers/cs257
webapp/api.py
''' <NAME> and <NAME> ''' import sys import flask import json import config import psycopg2 #sensitive infromation about the database to access from config import password from config import database from config import user api = flask.Blueprint('api', __name__) @api.route('/year/<year>') def ge...
ambeimers/cs257
database/archive/convert.py
''' Authors: <NAME> and <NAME> Date: January 26th, 2021 This program converts 2 .csv files into 3 smaller .csv files. ''' import csv def remove_commas(input_string): for i in range(len(input_string)): if i > len(input_string)-1: break if input_string[i] == ',': input_string = input_string[0:i]...
199-cmd/Jump-Space-Game-In-Tkinter
setting.py
<reponame>199-cmd/Jump-Space-Game-In-Tkinter<gh_stars>0 width = 800 height = 700 fps = 60 font_n = 'arial' sheetload = "spritesheet_jumper.png" mob_fq = 5000 player_acc = 0.5 player_friction = -0.12 player_gra = 0.8 player_jump = 21 platform_list = [(0,height-50),(width/2-50,height*3/4), (2...
199-cmd/Jump-Space-Game-In-Tkinter
new1.py
import pygame as pg import random from os import path from setting import * from sprites import * class Game: def __init__(self): self.running = True pg.init() pg.mixer.init() self.screen = pg.display.set_mode((width,height)) pg.display.set_caption("Nitya") ...
199-cmd/Jump-Space-Game-In-Tkinter
sprites.py
from setting import * import pygame as pg from random import * vec = pg.math.Vector2 class Spritesheet: def __init__(self, filename): self.spsheet = pg.image.load(filename).convert() def get_img(self,x,y,width,height): image = pg.Surface((width,height)) image.blit(self.spsheet...
brianhowes/pynet_test
file_ex1.py
<reponame>brianhowes/pynet_test #!/usr/bin/env python f = open("new_file.txt","w") f.write('I love to ride!!!') f.close() with open("new_file.txt","a") as f: f.write("Always!!!/n")
zeineb/testzz
bittensor/utils/__init__.py
import binascii import struct import hashlib import math import bittensor import rich import time def hex_bytes_to_u8_list( hex_bytes: bytes ): hex_chunks = [int(hex_bytes[i:i+2], 16) for i in range(0, len(hex_bytes), 2)] return hex_chunks def u8_list_to_hex( values: list ): total = 0 for val in rever...
zeineb/testzz
tests/unit_tests/bittensor_tests/test_metagraph.py
<reponame>zeineb/testzz import bittensor import torch import unittest class TestMetagraph(unittest.TestCase): def setUp (self): self.metagraph = bittensor.metagraph(network = 'akatsuki') assert True def test_print_empty(self): print (self.metagraph) def test_forward(self): ...
zeineb/testzz
tests/unit_tests/bittensor_tests/test_wallet.py
<filename>tests/unit_tests/bittensor_tests/test_wallet.py import bittensor from unittest.mock import MagicMock import os import shutil from pytest import fixture import subprocess from loguru import logger import time import sys from sys import platform from bittensor.utils.balance import Balance subtensor = bitt...
zeineb/testzz
bittensor/_receptor/receptor_impl.py
<reponame>zeineb/testzz """ Encapsulates a grpc connection to an axon endpoint as a standard auto-grad torch.nn.Module. """ # The MIT License (MIT) # Copyright © 2021 <NAME> # Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated # documentation files (the “Softw...
zeineb/testzz
bittensor/_neuron/text/template_validator/nucleus_impl.py
<reponame>zeineb/testzz<filename>bittensor/_neuron/text/template_validator/nucleus_impl.py import bittensor import torch from torch.nn import TransformerEncoder, TransformerEncoderLayer import torch.nn.functional as F class Validator( torch.nn.Module ): def __init__(self, config, metagraph, dendrite, device):...
zeineb/testzz
bittensor/_config/config_impl.py
<gh_stars>0 """ Implementation of the config class, which manages the config of different bittensor modules. """ # The MIT License (MIT) # Copyright © 2021 <NAME> # Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated # documentation files (the “Software”), to d...
zeineb/testzz
tests/unit_tests/bittensor_tests/test_dendrite.py
from bittensor._endpoint import endpoint import torch import pytest import time import bittensor wallet = bittensor.wallet( path = '/tmp/pytest', name = 'pytest', hotkey = 'pytest', ) wallet.create_new_coldkey(use_password=False, overwrite = True) wallet.create_new_hotkey(use_password=False, overwrite ...
zeineb/testzz
bittensor/_dataset/dataset_impl.py
""" Implementation for the dataset and GenesisTextDataset class, which handles dataloading from ipfs """ # The MIT License (MIT) # Copyright © 2021 <NAME> # 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 th...
erosson/PyPoE
PyPoE/index_dat.py
# Generate a list of all .dat file names, based on PyPoE specifications. # Run me from the PyPoE package directory! `scripts/dist` copies me there. from poe.file.specification.data.stable import specification import json print(json.dumps(list(specification.keys()), indent=4))
erosson/PyPoE
PyPoE/poe/file/specification/generation/virtual_fields.py
<gh_stars>1-10 from PyPoE.poe.file.specification.fields import VirtualField virtual_fields = { 'BaseItemTypes.dat': [ VirtualField( name='NormalPurchase', fields=('NormalPurchase_BaseItemTypesKeys', 'NormalPurchase_Costs'), zip=True, ), VirtualField( ...
erosson/PyPoE
PyPoE/poe/file/specification/generation/custom_attributes.py
class CustomizedField: def __init__(self, enum: str = None): self.enum = enum custom_attributes = { 'BaseItemTypes.dat': { 'ModDomainsKey': CustomizedField( enum='MOD_DOMAIN', ), }, 'BestiaryRecipeComponent.dat': { 'RarityKey': CustomizedFi...
erosson/PyPoE
PyPoE/poe/file/specification/generation/template.py
<filename>PyPoE/poe/file/specification/generation/template.py # template for data/stable.py """ Description =============================================================================== Contains the specification for the stable version of the game. This file is generated automatically based on https://github.com/poe...
erosson/PyPoE
PyPoE/poe/file/dat.py
""" Overview =============================================================================== +----------+------------------------------------------------------------------+ | Path | PyPoE/poe/file/dat.py | +----------+------------------------------------------------------...
sanorris/homebridge-Irrigation
python-scripts/stationOn.py
from gpiozero import LED from time import sleep led1 = LED(14) led1.on() sleep(2)
ocean2333/crawer
spider-3.py
# coding=utf-8 # work with vpn !!! import requests from bs4 import BeautifulSoup import os import time import zipfile # http请求头 Hostreferer = { 'User-Agent': 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)', 'Referer': 'https://www.wnacg.com/albums' } same_url = 'https://www.wnacg.com/albums' main_url = 'https:/...
ocean2333/crawer
spider-2.py
<filename>spider-2.py #coding=utf-8 import requests from bs4 import BeautifulSoup import os import random import time import multiprocessing as mp import sys #http请求头 Hostreferer = { 'User-Agent':'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)', 'Referer':'https://www.wnacg.com/albums' } sam...
ocean2333/crawer
spider_bzhan.py
# coding=utf-8 import os import random import sys import time from multiprocessing import Pool import requests from bs4 import BeautifulSoup # 1.输入cv号 # 1.5.获得该合集标题并创建文件夹 # 2.得到该网址下所有<figure class="img-box"中的图片地址 # 3.截去.jpg之后的部分 # 4.下载并储存 # v2.0:加入批量下载功能 # head = 'https:' http_head = 'https://www.bilibili.com' http...
Niirok/Pyckstarter
src/pkgexemple2/anotherex.py
def format_exception_numpy(etype, value, tb, limit=None): """ Format the exception with a traceback. Parameters ---------- etype : str exception type value : int exception value tb : traceback traceback object limit : int or None maximum number of stack f...
Niirok/Pyckstarter
src/pkgexemple/welcome.py
<filename>src/pkgexemple/welcome.py def int_randomizer(): """ This function will always return 42 (int), test: /test/test_welcome.py Extended description of function should be placed here, yet there is not much to say about this one... Returns ------- int will always be 42 """ ...
Niirok/Pyckstarter
test/test_welcome.py
import pytest from src.pkgexemple.welcome import * def test_int_randomizer_return42(): assert int_randomizer() == 42 def test_say_something_string(): toTest = say_something("Test string") assert toTest =="Hello World, I must tell you something: Test string."
pietow/demo_project
clean_data.py
# To add a new cell, type '# %%' # To add a new markdown cell, type '# %% [markdown]' # %% import pandas as pd import re data = pd.read_csv("bmw.csv") df_dealer = data.Dlodealer df_dealer def get_index_street(list_, str_, i): #str_ = 'Straße' if str_ in new: index = list_.index(str_) #print(i,...
pietow/demo_project
webscraper.py
import requests from bs4 import BeautifulSoup URL = 'https://www.bmw.de/de/fastlane/bmw-partner.html#/dlo/DE/de/BMW_BMWM?type=location&term=Nordrhein-Westfalen,%20Deutschland' page = requests.get(URL) soup = BeautifulSoup(page.content, 'html.parser') results = soup.body cookies = dict(cc_digital_sessionCookie='4610991...
ying-yee/qunarHotelSpider
config.py
#!/usr/bin/env python # -*- coding: utf-8 -*- MONGO_URL = 'localhost' MONGO_DB = 'hotel' inter_city_list = [ 'bangkok', 'seoul', 'singapore_city', 'tokyo', 'pattaya', 'chiang_mai', 'koh_phuket_tha', 'kuala_lumpur', 'surat_thani_th', 'jeju', 'osaka', 'sabah', 'maldi...
ying-yee/qunarHotelSpider
main.py
<reponame>ying-yee/qunarHotelSpider<filename>main.py<gh_stars>1-10 #!/usr/bin/env python # -*- coding: utf-8 -* import codecs import json import pprint import re import collections from operator import itemgetter import argparse from bs4 import BeautifulSoup import requests import pandas from selenium import webdriv...
neeyongliang/gists
tool-code-counter.py
<gh_stars>0 #! /usr/bin/python3 # -*- coding: utf-8 -*- import os import subprocess # 存放修改后的源码目录,可修改 SOURCE_CODE_DIR = '/home/someone/SourceCode' # 存放上游源码的目录,可修改 UPSTREAM_CODE_DIR = '/home/someone/Downloads/open-source' class CodeCount: """代码统计脚本 说明: DebianCodeCount 是专门为源码统计而编写的脚本, 使用本脚本之前,要在系统中安装 ...
hurutoriya/model-analysis
examples/chicago_taxi/process_tfma.py
<gh_stars>1-10 # Copyright 2018 Google LLC # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed ...
hurutoriya/model-analysis
tensorflow_model_analysis/extractors/predict_extractor.py
# Copyright 2018 Google LLC # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
lbartnik/rl
4.9/main.py
<gh_stars>0 #!/usr/bin/python3 import pickle import seaborn class ValueIteration: def __init__(self, ph = .4, win_state = 100): # state is the amount of money held by the player self.win_state = win_state # value of each state is the probability of winning with that much money sel...
pwinslow/change-org-app
runner.py
<reponame>pwinslow/change-org-app """ This file sets up multiple jobs to run on a PBS cluster. Each job collects data on a list of petitions. """ # Miscellaneous imports from sys import exit from csv import reader from os import getcwd, listdir, remove, system from os.path import join, isfile, isdir class Runner(obj...