class NewSession:
    """Create a session for connecting to repl.it. The session is good because
    then one connection to repl.it is needed for all scrapes and not a new
    connection per scrape."""

    def __init__(self, proxies={}):
        # Create new session
        self.request_session = requests.Session()
        self.proxies = proxies
        # Use header that makes it seem less like a bot
        self.headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36",
                        "Accept-Language": "en-US,en;q=0.8",
                        "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8"}
        # repl base is A-Z0-9a-z
        repl_it_string = string.ascii_uppercase + string.digits + string.ascii_lowercase
        self.repl_it_base = BaseConverter(repl_it_string)

    def decode(self, number):
        "Decode repl.it code id to a base 10 number"
        return int(self.repl_it_base.decode(number))

    def encode(self, number):
        "Encode base 10 number to repl.it code id"
        return self.repl_it_base.encode(number)

    def get_repl_save(self, code_id):
        "Save repl.it by code id"
        repl_html = self.get_repl_it_html(code_id)
        return self.get_data_from_html(repl_html, code_id)

    def get_repl_it_html(self, code_id):
        "Get html for code id"
        url = 'https://repl.it/{}'.format(code_id)
        return self.request_session.get(url, proxies=self.proxies, headers=self.headers).text

    def get_data_from_html(self, repl_html, code_id):
        "Get all data from the html"
        # All the data we need is in the HTML
        soup = BeautifulSoup(repl_html, 'html.parser')
        try:
            editor_data = [x.text for x in soup.findAll('script') if 'REPLIT_DATA' in x.text][0]
        except IndexError:
            data = {}
            data['session_id'] = code_id
            for x in ['language', 'time_created',
                      'time_updated', 'owner', 'title', 'editor_text']:
                data[x] = '404'
            return data
        editor_data_json = re.findall('{.*}', editor_data)[0]
        data = json.loads(editor_data_json)
        del data['console_dump']  # Not needed
        # String is HTML escaped so we need to unescape it
        data['editor_text'] = html.unescape(data['editor_text'])

        return data
예제 #2
0
def main():
    for t in range(int(input())):

        print('Case #%d:' % (t + 1))
        n, j = map(int, input().split(' '))
        #print(('').join(map(str, [ tmp for tmp in range(0, x) ])))
        #conv = BaseConverter(('').join(map(str, [ tmp for tmp in range(0, x) ])))
        #s = ('%s1' % (('').join(map(str, [0 for tmp in range(0, n-2)]))))
        b2 = BaseConverter('01')
        f = b2.encode(pow(2, n-1) + 1)
        f = pow(2, n-1) + 1
        
        found = 0
        primes = prime_list(1000)
        
        while found < j:
            res = []
            if is_jam_coin(b2.encode(f), 2, primes, res):
                print('%s %d %d %d %d %d %d %d %d %d' % (b2.encode(f), res[0], res[1], res[2], res[3], res[4], res[5], res[6], res[7], res[8]))
                found += 1
            f += 2
예제 #3
0
def main():
    for t in range(int(input())):

        print('Case #%d:' % (t + 1))
        n, j = map(int, input().split(' '))
        #print(('').join(map(str, [ tmp for tmp in range(0, x) ])))
        #conv = BaseConverter(('').join(map(str, [ tmp for tmp in range(0, x) ])))
        #s = ('%s1' % (('').join(map(str, [0 for tmp in range(0, n-2)]))))
        b2 = BaseConverter('01')
        f = b2.encode(pow(2, n - 1) + 1)
        f = pow(2, n - 1) + 1

        found = 0
        while found < j:
            res = []
            if find_prime(b2.encode(f), 2, res):
                print('%s %d %d %d %d %d %d %d %d %d' %
                      (b2.encode(f), res[0], res[1], res[2], res[3], res[4],
                       res[5], res[6], res[7], res[8]))
                found += 1
            f += 2
예제 #4
0
def get_uid():
    interfaces = netifaces.interfaces()
    interfaces.sort()
    i = interfaces[0]
    s = "abcdefghijklmnopqrstuvwxyz"
    u = "ABCDEFGHJKLMNPQRSTUVWXYZ"
    d = "0123456789"
    bc = BaseConverter(d+s+u)
    hashid = hashlib.sha1(i.encode("utf-8")).hexdigest()
    hashid = hashid.upper()
    raw = base16.decode(hashid)
    uid = bc.encode(raw)
    return uid
예제 #5
0
class BoopyBoop():
	def __init__(self, words=None, settings=None):
		if words == None:
			#criteria:
			#not abstract, but concrete. must be able to sense it directly
			#not about people, but about things that are not people
			#about 100 of them: currently 35
			self.words = ["pen","pencil","water","air","steam","wind","land","rock","steel","house","cat","school","plant","sun","star","tree","farm","sea","paper","chair","music","river","car","book","room","fish","mountain","horse","wood","bird","dog","song","door","ship","fire","bow","spoon","fork","roof","apple","cloth","wheat","boat","gold","drum","flute","ball","cube","triangle","square","hill","orange","grape","iron","brush","azure","periwinkle","burnet","diamond","goldenrod","maroon","ochre","saffron","pepper","croissant","bearclaw","pie","cake","bag","cookie","donut","quiche","custard","salt","carrot","spinach","broccoli","asparagus","wool","egg","butter","rice","dark","light","hut","shack","castle","pyramid","igloo","salon","ranch","pagoda","abbey","tavern","stadium","factory","bank","manor","stables","vineyard","porch","well","closet","corridor","fireplace","tie","belt","gloves","tea","coffee","soda","macaroni","gyro","almonds","waffles","hamburger","bookcase","mattress","tuba","saxophone","accordion","metronome","banjo","kazoo","dulcimer","viola","harp","oboe","cave","duck","tomato","bananas","lettuce","cabbage","onions","elm","palm","maple","arrow","pickax","doll","balloon","vase","typewriter","desk","chalk","galleon","frigate","gondola","dinghy","canoe","train","buggy","firetruck","harbor","pond","brook","waterfall","sleet","snow","fog"]
			print [x for x, y in collections.Counter(self.words).items() if y > 1]
			assert len(list(set(self.words))) == len(self.words)
		else:
			self.words = words
		if settings == None:
			self.settings = MONGO_OBJ_ID_SETTINGS
		else:
			self.settings = settings
		self.len_words = len(self.words)
		self.base_conv = BaseConverter(self.settings["alphabet"])

	def id_to_string(self, id_string):
		id_num = int(id_string, base=len(self.settings["alphabet"]))
		words = []
		print "id_to_string id_num: ", id_num
		while id_num > 0:
			word_idx = id_num % self.len_words
			id_num = id_num // self.len_words
			print "curr id_num: ", id_num
			words.append(self.words[word_idx])
		return words

	def string_to_id(self, word_arr):
		id_num = 0
		word_arr.reverse()
		for idx, word in enumerate(word_arr):
			id_num += self.words.index(word)
			print "curr_id_num: ", id_num
			if idx < (len(word_arr) - 1):
				id_num *= self.len_words
		print "string_to_id id_num: ", id_num
		return self.base_conv.encode(id_num)

if __name__ == "__main__":
	"""
	This is a test: use it as an example of usage
	"""
	boop = BoopyBoop()
	boop_res = boop.id_to_string("507f1f77bcf86cd799439011")
	print boop_res
	print len(boop_res)
	print boop.len_words
	print boop.string_to_id(boop_res)
예제 #6
0
class IdConverter(object):

    """
    Generates an id based on an integer.
    Essentially it's a small hashing algorithm that allows us to
    give unique ids that aren't too long.
    """

    def __init__(
            self,
            state: int = 0,
            prefix: str = "",
            length: int = 4,
            alphabet: str = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ',
            ) -> None:
        """
        """

        self.state = state
        self.prefix = prefix
        self.length = length
        self.alphabet = alphabet

        from baseconv import BaseConverter
        self.converter = BaseConverter(alphabet)
        return

    def encode(self, number: int) -> str:
        """
        """
        template = "{pre}{{p:{first}>{length}}}".format(
            pre=self.prefix,
            first=self.converter.digits[0],
            length=self.length,
            )
        return template.format(p=self.converter.encode(number))

    def decode(self, pattern: str) -> int:
        """
        """
        pattern = pattern[len(self.prefix):]
        return int(self.converter.decode(pattern))

    def __next__(self):
        string = self.encode(self.state)
        self.state += 1
        return string

    def __iter__(self):
        return self
예제 #7
0
def is_jam_coin(f, base, primes, res):
    conv = BaseConverter(('').join(map(str, [ tmp for tmp in range(0, base) ])))
    f = int(conv.decode(f))
    if base == 10:
        factor = find_prime_fact(f, primes)
        if factor:
            res.append(factor)
            return True
        else:
            return False

    factor = find_prime_fact(f, primes)
    if factor:
        res.append(factor)
        return is_jam_coin(conv.encode(f), base+1, primes, res)
    else:
        return False
예제 #8
0
def find_prime(f, base, res):
    conv = BaseConverter(('').join(map(str, [tmp for tmp in range(0, base)])))
    f = int(conv.decode(f))
    if base == 10:
        factor = get_prime_factor(f)
        if factor:
            res.append(factor)
            return True
        else:
            return False

    factor = get_prime_factor(f)
    if factor:
        res.append(factor)
        return find_prime(conv.encode(f), base + 1, res)
    else:
        return False
예제 #9
0
def is_jam_coin(f, base, primes, res):
    conv = BaseConverter(('').join(map(str, [tmp for tmp in range(0, base)])))
    f = int(conv.decode(f))
    if base == 10:
        factor = find_prime_fact(f, primes)
        if factor:
            res.append(factor)
            return True
        else:
            return False

    factor = find_prime_fact(f, primes)
    if factor:
        res.append(factor)
        return is_jam_coin(conv.encode(f), base + 1, primes, res)
    else:
        return False
예제 #10
0
from baseconv import BaseConverter
import random

primary_numbers = []
secondary_numbers = []
outputs = []

for i in xrange(25):
	ternary_string1 = ""
	for j in xrange(random.randint(50, 100)):
		ternary_string1 += str(random.randint(0,2))

	ternary_string2 = ""
	for j in xrange(random.randint(50, 100)):
		ternary_string2 += str(random.randint(0,2))

	base3 = BaseConverter("012")
	decimal_string1 = base3.decode(ternary_string1)
	decimal_string2 = base3.decode(ternary_string2)
	decimal_output = int(decimal_string1) - int(decimal_string2)
	ternary_output = base3.encode(str(decimal_output))

	input = ternary_string1 + "#" + ternary_string2
	expected_output = ternary_output

	print "Input:"
	print input
	print "Expected Output:"
	print expected_output
	print
예제 #11
0
from baseconv import BaseConverter
import random

primary_numbers = []
secondary_numbers = []
outputs = []

for i in xrange(25):
    ternary_string1 = ""
    for j in xrange(random.randint(50, 100)):
        ternary_string1 += str(random.randint(0, 2))

    ternary_string2 = ""
    for j in xrange(random.randint(50, 100)):
        ternary_string2 += str(random.randint(0, 2))

    base3 = BaseConverter("012")
    decimal_string1 = base3.decode(ternary_string1)
    decimal_string2 = base3.decode(ternary_string2)
    decimal_output = int(decimal_string1) - int(decimal_string2)
    ternary_output = base3.encode(str(decimal_output))

    input = ternary_string1 + "#" + ternary_string2
    expected_output = ternary_output

    print "Input:"
    print input
    print "Expected Output:"
    print expected_output
    print
예제 #12
0
 def base6(self, num):
     """Retorna uma representação em base 6 do número em um array"""
     n = int(num)
     base6 = BaseConverter('012345')
     return base6.encode(n)