index int64 0 1,000k | blob_id stringlengths 40 40 | code stringlengths 7 10.4M |
|---|---|---|
10,000 | 7a52f31939ad767d003f3364dd387f3ff1422c8a |
class StringUtil:
@staticmethod
def get_words(sentence=None, delimiter=" "):
words = None
if sentence is None:
raise Exception("No input to the function")
else:
if delimiter in sentence:
words = sentence.split(" ")
else:
... |
10,001 | 7c2d4c61b4422adb7fe94e0932c18085351a39eb | __version__ = '0.9.8-dev'
# from HTMLr.core import HTMLObject
# from HTMLr.templates import Card, Combos, Table
|
10,002 | 109a83de24b4c4526b0bb94941441d7ccbd2824e | import fun
### białe
## pionki [x,y]
b_p_1 = [1, 2, 1, 'p']
b_p_2 = [2, 2, 1, 'p']
b_p_3 = [3, 2, 1, 'p']
b_p_4 = [4, 2, 1, 'p']
b_p_5 = [5, 2, 1, 'p']
b_p_6 = [6, 2, 1, 'p']
b_p_7 = [7, 2, 1, 'p']
b_p_8 = [8, 2, 1, 'p']
## figury [x,y]
# wieża
b_wie_l = [1, 1, 1, 'w']
b_wie_p = [8, 1, 1, 'w']
# Skoczek
b_skocz_l ... |
10,003 | d5f5a5f1a9a040f5fffa1421f8ee09e251050e4b | from rest_framework import serializers
from main.models import Category, Product, Wear, Food, Order, Cart
from auth_.serializers import ClientSerializer, CourierSerializer, StaffSerializer
class CategorySerializer(serializers.Serializer):
id = serializers.IntegerField()
name = serializers.CharField(max_length... |
10,004 | 2dafcd5b1fa38f6d668b709b51501517efea191b | ##Authors: Whitney Huang, Mario Liu, Joe Zhang
##Lab 3
from pithy import *
import libMotorPhoton as lmp #motor photon interface
import libmae221
import numpy as np
from datetime import datetime as dt
import time
##############################################################
#THIS IS DAN'S DA... |
10,005 | 5a7a3a6d75346509b4a4a07b4d1535b0a6ed089e | # Generated by Django 2.2.12 on 2020-07-08 19:29
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('products', '0017_auto_20200709_0008'),
]
operations = [
migrations.RemoveField(
model_name='item',
name='size',
),
... |
10,006 | ce2d69dd5e25088e2cd7828b872b20119b4c8c3f | from __future__ import absolute_import
import re
import json
import requests
from apis.base import BaseAPI, APIException
# Flickr API: https://www.flickr.com/services/api/
class FlickrPhotoAPI(BaseAPI):
url_format = "https://farm{farm}.staticflickr.com/{server}/{id}_{secret}_m.jpg"
per_page = 10
def __in... |
10,007 | 68949e4cb12e2432036501162040e83bd7070d7e | from typing import Dict, Sequence
import numpy as np
from pycocotools import mask as maskUtils
class MetricsInstanceSegmentaion:
@staticmethod
def convert_uncompressed_RLE_COCO_type(
element: Dict, height: int, width: int
) -> Dict:
"""
converts uncompressed RLE to COCO default t... |
10,008 | 9859ea10d26a961d5af34c6fd64ccbef7b4eeb79 | from subprocess import Popen, PIPE
from collections import defaultdict
import time
import sys
import os
import re
fname = 'hehe' if len(sys.argv) == 1 else sys.argv[1]
fsize = os.path.getsize(fname)
repetitions = 11
cmds = [
['rampin', '-0q'],
['openssl', 'sha1'],
['C:/Program Files/Git/usr/bin/sha1sum.... |
10,009 | 032dfe078bb3f203105df802516b4e66ec80d4d9 | n=int(input())
num=list(map(int,input().split()))
count=0
for i in range(0,n):
minj=i
a=0
for j in range(i+1,n):
if num[minj]>num[j]:
minj=j
if minj!=i:
count+=1
a=num[minj]
num[minj]=num[i]
num[i]=a
print(' '.join(list(map(str,num))))
print(count)
|
10,010 | 4bba1ae59920b8f16b83167fbeedd40a6e172fbf | '''
本题要求先序遍历树的元素并保存入一个数组,尽量采用迭代的方法解决。
因此可以维护一个treeStack列表用于当做节点栈。先将根节点放入栈中。
在循环中,先将栈顶元素弹出并放入result数组中,然后依次压入右孩子、左孩子。
本题时间复杂度为O(n),运行时间36ms,击败98.84%用户。
'''
class Solution:
def preorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
treeStack ,... |
10,011 | 283fc3c26a0d800dd02a978ac01e1f4b2caa01c6 | #http://www.binarytides.com/raw-socket-programming-in-python-linux/
import socket, sys
from struct import *
qos_list = []
with open("f.txt", "rb") as f:
byte = f.read(1)
while byte:
qos_list.append((ord(byte) & 192)>>6)
qos_list.append((ord(byte) & 48)>>4)
qos_list.append((ord(byte) & 12... |
10,012 | b6df800f1cf5d3ce15387472cf3a5c94ca55cd80 | #! /usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright 2017 Romain Boman
#
# 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
#
... |
10,013 | 01a37eff8692b173b56cc21186ab30cf850a5833 | import dataprocessing
import numpy as np
if __name__=='__main__':
dp = dataprocessing.DataPlotter()
# losses = []
# val_accuracies = []
# train_losses=[]
# for num_samples in [200,100,50]:
# losses.append(np.load("/home/jasper/oneshot-gestures/output/data-17-retrain-1-samples-{}/train_loss.... |
10,014 | 8dd0fe5f90f30babbd17201a432573deaf075ee5 |
# a = input()
# a = ['ab','ca','bc','ab','ca','bc','de','de','de','de','de','de']
# check values front to next, if cond == True, change num['word'] from i to i+1
# check all len(comp)
# print(minimum)
length = 2
s = 'abcabcabcabcdededededede'
s_split = [words for words in s]
print(s_split)
cnt = []
for j in range... |
10,015 | 06dc7790c9206822c66d72f4185f16c0127e377d | # Задача-1:
# Дан список фруктов.
# Напишите программу, выводящую фрукты в виде нумерованного списка,
# выровненного по правой стороне.
# Пример:
# Дано: ["яблоко", "банан", "киви", "арбуз"]
# Вывод:
# 1. яблоко
# 2. банан
# 3. киви
# 4. арбуз
# Подсказка: воспользоваться методом .format()
fruits_list = ['Абрико... |
10,016 | 6872594152bae4130326f68e417411ba0d9109c0 | #!/usr/bin/python
import base64
from Crypto.Cipher import AES
import Crypto.Util.Counter
def aes_ecb_encrypt(byte_array):
aes = AES.new(key, AES.MODE_ECB)
return aes.encrypt(byte_array)
####################################
def xor_bytes(byte_arr1, byte_arr2):
xored_arr = ''
for b in r... |
10,017 | f6f664c79b1bc762aeb26c8a6e324423a90e5e8d | #Ejercicio 7
#Escribí un porgrama que lea un archivo e identifique la palabra más larga, la cual debe imprimir y decir cuantos caracteres tiene. |
10,018 | b9d85735ed86e8585967293dd9735ab69cc23576 | # from bw_processing.loading import load_bytes
# from bw_processing import create_package
# from io import BytesIO
# from pathlib import Path
# import json
# import numpy as np
# import tempfile
# def test_load_package_in_directory():
# with tempfile.TemporaryDirectory() as td:
# td = Path(td)
# ... |
10,019 | f680fdf09a86f094018832699d7cf2a654d1d47d | from django.urls import path
from . import views
urlpatterns = [
path('user_list', views.user_list, name = 'user_list'),
path('log_in', views.log_in, name = 'log_in'),
path('log_out', views.log_out, name = 'log_out'),
path('sign_up', views.sign_up, name = 'sign_up'),
path('WebWorker', views.WebWork... |
10,020 | aa233a0442cc287c402e05c6b3522656ecd729a7 | #!/usr/local/bin/python
# -*- coding: utf-8 -*-
'''pyDx9adl
'''
import ctypes
from ctypes import cast, POINTER, c_void_p, byref, pointer, CFUNCTYPE
from ctypes import c_double, c_float, c_long, c_int, c_char_p, c_wchar_p
dllnames = ['d3d9', 'd3dx9', 'D3DxConsole', 'D3DxFreeType2',
'D3DxTextureBmp', 'dx9adl', 'D3DxG... |
10,021 | 6930f4e461a26e544ab4477752d679ce9832560a | from __future__ import print_function
import bisect
import boto3
import json
import logging
import math
import os
import time
import gym
import numpy as np
from gym import spaces
from PIL import Image
logger = logging.getLogger(__name__)
# Type of worker
SIMULATION_WORKER = "SIMULATION_WORKER"
SAGEMAKER_TRAINING_WO... |
10,022 | 7acb3965422ad97da644c7daa9b791f025aa5062 | #-*- coding: utf-8 -*-
from pyramid import testing
class MockSession(object):
def merge(self, record):
pass
def flush(self):
pass
def add(self, record):
pass
class MockMixin(object):
def to_appstruct(self):
return dict([('a','a'),('b','b')])
def log(self):
... |
10,023 | b29b4f5c6f8af18dc2dad3bdea6e1e8b2ab109f8 | #!/usr/bin/env python
"""Drukkers2RDF.py: An RDF converter for the NL printers file."""
from rdflib import ConjunctiveGraph, Namespace, Literal, RDF, RDFS, BNode, URIRef
class Drukkers2RDF:
"""An RDF converter for the NL printers file."""
namespaces = {
'dcterms':Namespace('http://purl.org/dc/term... |
10,024 | bb2607602c218157bcda4694975bbeef4fe48c64 | # -*- coding: utf-8 -*-
import logging
import subprocess
import socket
import os.path
class SendmailHandler(logging.Handler):
sendmail = ['/usr/sbin/sendmail', '-i', '-t' ]
def __init__(self, recipient, name='nobody', level=logging.NOTSET):
logging.Handler.__init__(self, level=level)
self.hostname ... |
10,025 | f9d0b6911e49d0974cb06f5f307d51d522850849 | from gym_foo.model.action.action import Action
class SpeedUp(Action):
def __init__(self, hive_id, march_id):
super().__init__(hive_id)
self._march_id = march_id
def get_march_id(self):
return self._march_id
def do(self, march):
march.speedup()
def __repr__(self):
... |
10,026 | 511087c11652ddcaffbdc18f5c4cdd806a0a7533 | import re
class Algorithms():
def UnNTerminals(self, inputData):
print "Unproductive not terminals"
t_out = []
t_in = []
unproductive = []
productive = []
'''split by rows'''
inputData = inputData.split("\n")
t_out = self._SearchAfter(inputData)
... |
10,027 | fa8ff35c51be178e7b660a1a50a3f018c0402d88 | # import requests
# url = 'https://www.w3schools.com/python/demopage.php'
# myobj = {'somekey': 'somevalue'}
# x = requests.post(url, data = myobj)
# print(x)
# print("asd")
# Python 3 server example
import json
import os
from http.server import BaseHTTPRequestHandler, HTTPServer
from expertai.nlapi.cloud.client im... |
10,028 | b729950e1b1766d479e5f2e077b8dc01b4180ec8 | from rest_framework import viewsets, mixins
from rest_framework.response import Response
from api.serializers import ProductSerializer, EventSerializer
from api.models import Products, Editions, Publishers, Events
class ProductViewSet(mixins.RetrieveModelMixin,
mixins.ListModelMixin,
... |
10,029 | f279eeadbc2559e6bb671bc38ff74e932e60b2dc | import matplotlib as mpl
mpl.use('Agg')
from sandbox.rocky.tf.algos.trpo import TRPO
from rllab.baselines.linear_feature_baseline import LinearFeatureBaseline
from rllab.envs.normalized_env import normalize
from sandbox.rocky.tf.optimizers.conjugate_gradient_optimizer import ConjugateGradientOptimizer
from sandbox.roc... |
10,030 | 5124c70d27bbf70384ffcf1471c7b984a5afe0eb | #
# @lc app=leetcode id=24 lang=python
#
# [24] Swap Nodes in Pairs
#
# @lc code=start
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def swapPairs(self, head):
"""
:type head: Li... |
10,031 | 550a73cc1f9d8d83bed15903792786a3d6dc9162 | # This file is part of the NESi software.
#
# Copyright (c) 2020
# Original Software Design by Ilya Etingof <https://github.com/etingof>.
#
# Software adapted by inexio <https://github.com/inexio>.
# - Janis Groß <https://github.com/unkn0wn-user>
# - Philip Konrath <https://github.com/Connyko65>
# - Alexander Dincher <... |
10,032 | a1c9ccbd6aa7646f3c5f2efac0beaae8ca9532f0 | # Generated by Django 2.2.13 on 2020-12-04 09:34
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('researcher_UI', '0057_auto_20201204_0933'),
]
operations = [
migrations.AddField(
model_name='study',
name='demogra... |
10,033 | ec64a9e234c06fed2d4d930ab1f7874828d2f3bd | # -*- coding: utf-8 -*-
"""
Created on Thu Aug 15 12:17:23 2019
@author: Umberto Gostoli
"""
from collections import OrderedDict
from person import Person
from person import Population
from house import House
from house import Town
from house import Map
import Tkinter
import tkFont as tkfont
import pylab... |
10,034 | cf89ead2e9feade098ce2b8c99d64d4fe9edb5c1 | # -*- coding: utf-8 -*-
"""
Created on Sat Oct 03 11:22:34 2015
@author: Binoy
"""
import rhinoscriptsyntax as rs
def readOffset(filename= None):
fname = rs.OpenFileName("offset")
#fname = r""
_file = open(fname, 'r')
hdr = _file.next()
ncurves = int(_file.next())
_curves = []
... |
10,035 | 7db70dca8c268fed257c7535bf4e93dd2ad8ecdf | from flask.ext.wtf import Form
from wtforms import TextField, SelectMultipleField, widgets
from wtforms.validators import Required
from app.models.author import Author
class BookForm(Form):
name = TextField('name', validators = [Required()])
authors = SelectMultipleField('Authors',
choices=[(author.i... |
10,036 | ea06783f24feb22e5bd9b1ca617a2e3cdd7be678 | a,b,c,d = [int(e) for e in input().split()]
if a>b:
t = a
a = b
b = t
if d>=a:
if c>d:
c -= a
else:
c += a
b = a+c+d
else:
if c>a and a>=b:
d += a
if d>c:
b += 2
else:
b *= 2
print(a,b,c,d) |
10,037 | d046bf1e194f84c99aa915026dbcc76cadeda65b | from django.urls import path
from django.conf.urls import url, include
from . import views
urlpatterns = [
url('^$', views.index),
url(r'^usuarios/', views.UsuarioList),
url(r'^capacidades/', views.CapacidadList, name='capacidadList'),
url(r'^capacidad/(?P<id_capacidad>\d+)/$', views.Capacida... |
10,038 | 5fe529acbf6c385da7f799b932609dabd43eddd2 | import smtplib
import getpass
# creates SMTP session
s = smtplib.SMTP('smtp.gmail.com', 587)
# start TLS for security
s.starttls()
sender_email = input("Enter sender's address:")
#Use app specific password if two factor authentication is enabled
pswd = getpass.getpass('Password:')
s.login(sender_email, pswd) ... |
10,039 | 2159846a044e5b10b95ddf1a4cf39e25757dbf58 | # This code is part of Qiskit.
#
# (C) Copyright IBM 2018, 2019, 2020, 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modification... |
10,040 | f37cb12cbe8d4929cb7cfc7788c79cf9a1db7fab | def coins_chain_recursive(n):
coins = [25,10,5,1]
def make_chang(amount, index):
if index >= len(coins) - 1:
return 1
denom_amount = coins[index]
ways = 0
i = 0
while denom_amount * i <= amount:
used = amount - denom_amount * i
ways += ... |
10,041 | e554c829612aa906d62c64c27fd40ed1f25b8aae | # 2750 - saida 4
print('-'*39)
print('| decimal | octal | Hexadecimal |')
print('-'*39)
for i in range(16):
print('| {:2d} | {:2o} | {:X} |'.format(i, i, i))
print('-'*39)
|
10,042 | 89628940a15eb55cd56e6cad3046bec967b00ba3 | import numpy as np
class ExtractedFeature:
def __init__(self, raw_data, raw_feature_data, persistence_diagram_1d, binned_diagram_1d):
self.features = {}
self.features['raw_data'] = raw_data
self.features['raw_feature_data'] = raw_feature_data
self.features['pd_1d'] = persis... |
10,043 | 0bf2068c7ad7e0c240f95e0fcc5a0322a32805e6 | from wexapi.models.pair_info import PairInfo
from wexapi.models.ticker import Ticker
from wexapi.models.trade import Trade
from wexapi.models.account_info import AccountInfo
from wexapi.models.trans_history import TransHistory
from wexapi.models.trade_history import TradeHistory
from wexapi.models.order import Order
fr... |
10,044 | 853ecb85696b580d415c673c4ef5485128f5ae8d | SLAVES = {
'fedora': dict([("talos-r3-fed-%03i" % x, {}) for x in range(3,10) + range(11,18) + range(19,77)]),
'fedora64' : dict([("talos-r3-fed64-%03i" % x, {}) for x in range (3,10) + range(11,35) + range(36,72)]),
'xp': dict([("talos-r3-xp-%03i" % x, {}) for x in range(4,10) + range(11,76) \
if... |
10,045 | 07ebcaac38c35c583b53554fe4b300b62224e13b | # -*- coding:utf-8 -*-
# project: PrimeCostOrderManagement
# @File : DataMaintenance.py
# @Time : 2021-07-06 08:58
# @Author: LongYuan
# @FUNC : 基础数据维护界面
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QIntValidator
from PyQt5.QtSql import QSqlDatabase, QSqlTableModel
from PyQt5.QtWidgets import QWidget, QHeade... |
10,046 | 524f40afd76429837b97c35a25014acaa13ad031 | #!/usr/bin/python
# -*- coding: utf-8 -*-
import json
from common.util.logger import log
class Assertion():
"""
判断是否为None
"""
@classmethod
def is_not_none(cls, rsp):
assert rsp, "数据为None"
@classmethod
def is_ok(cls, rsp):
cls.is_not_none(rsp)
data = json.loads(rsp)
assert data["code"] == 200
"""... |
10,047 | 78623057cfd1e6b9e2eedca6af8919f24363456f | # https://programmers.co.kr/learn/courses/30/lessons/43105
def solution(triangle):
answer = 0
t = calc_sum_triangle(triangle)
answer = max(t[-1])
return answer
def calc_sum_triangle(triangle):
for level in range(1, len(triangle)):
for idx in range(len(triangle[level])):
up_left ... |
10,048 | 0459231d69836946b01928f84ebd1505211388f9 | import os
import json
import re
from flask import Flask, request, jsonify, make_response
from google.cloud import datastore
try:
os.chdir(os.path.join(os.getcwd(), 'scripts'))
print(os.getcwd())
except:
pass
# get_ipython().system('pip install flask')
app = Flask(__name__)
@app.route('/webhook/', methods=['POST'... |
10,049 | c40f5085d732e88cf8e19ef65f694962819e9dcb | # Source: https:// www.guru99.com/reading-and-writing-files-in-python.html'
# Data to be outputted
data = ['first','second','third','fourth','fifth','sixth','seventh']
# Get filename, can't be blank / invalid
# assume vaild data for now.
filename = input("Enter a Filename (leave off the extension): ")
# add .txt suf... |
10,050 | a3944df20717cd00575cba77206d4bcc79619f3c | import abc
import asyncio
import random
from cards import ActionCard
from constants import URBANIZE, BUILD_UP, PLAN, RESOURCE, TILE, LEFT, DOWN, RIGHT, UP, VICTORY_POINT, COLORS, RESET
from pieces import Space, Marker, Tile
class Player(abc.ABC):
def __init__(self, name, color):
self.name = name
... |
10,051 | 0800efa769fe02f81a763a9bf67ec0286fb76653 | # sss.py
# Commonly used routines to analyse small patterns in isotropic 2-state rules
# Includes giveRLE.py, originally by Nathaniel Johnston
# Includes code from get_all_iso_rules.py, originally by Nathaniel Johnston and Peter Naszvadi
# by Arie Paap, Oct 2017
import itertools
import math
import golly as g
... |
10,052 | 5c57f46700b0113b534f2f10b14b9869f69bd6db | #!/usr/bin/python2.5
#
# Copyright 2009 the Melange authors.
#
# 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
#
# Unless required by applicable... |
10,053 | bbe82eecff9faa9fb5c9803592b7622c74e56715 | # ---------------------------------------------------------------------------
# SBDD_FRQ_uniques.py
# Created on: May 16, 2011
# Created by: Michael Byrne
# Federal Communications Commission
# creates the individual layers necessary for the
# National Broadband Map from the source file geodatabases
# requires o... |
10,054 | bcc6664d3c1d4703e377a0854dbd088bb2ba929d | import numpy as np
import tensorflow as tf
from utils.bbox import bbox_giou, bbox_iou
from common.constants import YOLO_STRIDES, YOLO_IOU_LOSS_THRESHOLD
def compute_loss(pred, conv, label, bboxes, i=0, num_classes=80):
conv_shape = tf.shape(conv)
batch_size = conv_shape[0]
output_size = conv_shape[1]
... |
10,055 | 77b2799a84da7e2f230bd62b0e5f911289d840b7 | import requests as r
from datetime import datetime
def add_to_list(res_list, age):
found = False
for cort in res_list:
if cort[0] == age:
cort[1] += 1
found = True
break
if not found:
res_list.append([age, 1])
def parce_friends(res_json):
res_lis... |
10,056 | 8b47a5fbf4e5d06b22efccf1aad465d7c2a3228a | import sys
import os
import pandas as pd
import numpy as np
import pickle
from sqlalchemy import create_engine
from nltk.tokenize import word_tokenize
from nltk.stem import WordNetLemmatizer
from sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer
from sklearn.metrics import confusion_matrix
from s... |
10,057 | 5c762d880b987708d2b4219812b363d11f7e2069 | import authenticate
import sys
error_ids = []
testing = True
# process cmd-line args
def process_cmd_args():
if len(sys.argv) == 1:
print("No AMI's specified. Exiting...")
exit(1)
amis = []
for i in range(1, len(sys.argv)):
amis.append(sys.argv[i])
return amis
# get_snapshot_for_amis
def get_snapshots_... |
10,058 | 16aaf78ebb99b9ff17f46f8ab2e7f9176df59cf4 | from django.db import models
from datetime import *
from django.urls import reverse
from django.utils import timezone
from django.core.validators import RegexValidator
#Choices
DAYS_OF_WEEK = (
('Monday', 'Monday'),
('Tuesday', 'Tuesday'),
('Wednesday', 'Wednesday'),
('Thursday', 'Thurs... |
10,059 | 238ffcd3aae0337fcf1730a27025db9d7a0100ce | from django import forms
from .models import Cupon
from userprofiles.models import Afiliado
from django.contrib.auth.models import User
class CuponForm(forms.ModelForm):
titulo = forms.CharField(widget=forms.TextInput(attrs={ 'class': 'form-control'}))
fecha_inicio = forms.DateField(widget=forms.TextInput(attrs={ 'c... |
10,060 | 01e48c754f411f8bd0148ea3636f85f004c86a0a | import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
from torch.autograd import Variable
import numpy as np
from torch.utils.data import DataLoader, TensorDataset
import matplotlib.pyplot as plt
from math import *
from mpl_toolkits.mplot3d import Axes3D
class Net(nn.Module):
... |
10,061 | aff778dea68c976494ee5b29ddd0838abcf75e05 | import PhysicsMixin
import ID
import Enemy
import Friend
import Beam
import Joints
import Contacts
class PumpkinBomberSprite(PhysicsMixin.PhysicsMixin):
def __init__(self,**kwargs):
self.params = kwargs
self.params['name'] = "PumpkinBomber"
self.params['__objID__'] = ID.next()
self... |
10,062 | 4adf9f1c608acd85ab15b1164a5a91364e706261 | import jinja2
import json
import os
import webapp2
from apiclient.discovery import build
JINJA_ENVIRONMENT = jinja2.Environment(
loader=jinja2.FileSystemLoader(os.path.dirname(__file__)),
extensions=['jinja2.ext.autoescape'])
REGISTRATION_INSTRUCTIONS = """
You must set up a project and get an API key to... |
10,063 | f53caa4ca221906f9936d1ff81de80425a5c731c |
def readcsv():
result=[]
resultDict={}
import csv
#csvFile = "C:\\00-Erics\\01-Current\\YuShi\\ML-KWS-for-MCU\\DataSet\\ASR\\36-0922-sj\\mapping.csv"
csvFile = "./conf/mapping.csv"
with open(csvFile, newline='') as csvfile:
spamreader = csv.reader(csvfile, delimiter=',', quotechar='|')
... |
10,064 | e4eecd18ab049f1a9b5e26d6757ce1606df410fa | import json
import zmq
from random import randint
import logging
from classes.utils import *
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__) #Q will this make it shared between all objects?
hdlr = logging.FileHandler('subscriber.log',mode='w')
logger.addHandler(hdlr)
class Subscriber:
#... |
10,065 | 51e4a460b06fdc717cb5aba2e0e8d078e6bf9605 | import pandas as pd
from sklearn.model_selection import train_test_split
def get_data():
'''
Simple function, that ready in the data, cleans it
and returns it already split and train and test
'''
complete_data = pd.read_csv('../datasets/complete-set.csv')
complete_data.dropna()
texts = complete_data['content'].... |
10,066 | c972d31b3a4f93066278beb4a2f3b9efea5c28de | N = int(input())
def f(limit):
i = 1
j = 2
while True:
if i > limit:
break
yield i
i += j
j += 1
def h1(l, n):
s = 0
for i in range(n):
yield l[s:s+i+1]
s += i+1
def h2(p, l):
if not l:
return
for pp, ll in zip(p, l):
... |
10,067 | 7aa7f6886bd360a989f346e337e9414f0dc0b630 | import argparse
import tensorflow as tf
import pickle
import math
import numpy as np
from getData import getData
def getBatch(FLAGS):
train_x, train_y, dev_x, dev_y, test_x, test_y, word2id, id2word, tag2id, id2tag = getData(FLAGS)
train_steps = math.ceil(train_x.shape[0] / FLAGS.train_batch_size)
d... |
10,068 | e47892c01f4e805f6ce8ebdfab04661d55adc440 | from __future__ import absolute_import
import json
import os
import subprocess
class MetaparticleRunner:
def cancel(self, name):
subprocess.check_call(['mp-compiler', '-f', '.metaparticle/spec.json', '--delete'])
def logs(self, name):
subprocess.check_call(['mp-compiler', '-f', '.metaparticle... |
10,069 | 2f0dd2de0a0638498587c391d4bca4e66cf776f6 | from django.urls import include, path
from rest_framework.routers import DefaultRouter
from .views import (CategoryViewSet, CommentViewSet, GenreViewSet,
ReviewViewSet, TitleViewSet, UserViewSet,
get_confirmation_code, get_token)
v1_router = DefaultRouter()
v1_router.register('... |
10,070 | f5c02d936aed23b62a856bae9c9f5b0beadc963f | import re
f = open('http_access_log', 'r')
lineList = []
statusList = []
count = 0
for line in f:
count += 1
lineList.append(line)
for i in range(len(lineList)):
splitLine = lineList[int(i)].split()
try: status = splitLine[8]
except: pass
try: statusInt = int(status)
except: pass
statusList.append(status... |
10,071 | b1135b47be4940d8fb894e712c2d3f070ad4f777 | import requests
from bs4 import BeautifulSoup
import datetime
#-------------- --------------------------------------------------------------------------------------------------------------------
#calcule et convertion de la date du jour precedant
date1 = datetime.date.today() - datetime.timedelta(days=1)
new_date = dat... |
10,072 | 9ccceba6933c56fe585b8ff3afa5339279225531 | import numpy as np
import cv2
img = cv2.imread('pattern.png')
img2 = img.copy()
imgray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
imgray = np.float32(imgray)
dst = cv2.cornerHarris(imgray,2,3,0.04) # opencv 0.04랑 순길이소스 0.01이랑 같음
dst = cv2.dilate(dst,None)
img2[dst > 0.01 * dst.max()] = [0,0,255]
cv2.imshow('Harris',im... |
10,073 | f2e6961028c85703467a9221a49182bf7cd56107 | from chips import Chips
from player import Player
from hand import Hand
from deck import Deck
import sys
def promt_player_dealer():
while True:
print('Do you want to be the player or the dealer? \n -let me be the dealer, love to take all your money ;)\n -then I would buy some new proccessors.. \n1: pla... |
10,074 | 28b92e7988d8fbd11f16e1d8f5acb5398e303953 | '''user_range = input('Please write numbers')
user_range2 = input('please write number')
x = int(user_range)
y = int(user_range2)'''
def fizzbuzzz(star_num, stop_num):
#if x >= y:
# print('1st number must be lower than second')
for num in range(x, y):
if num % 3 == 0 and num % 5 == 0:
print(n... |
10,075 | ba0c477a37feb1dd19a7ecaa58948c1bcdae44a5 | print('hello test git routage') |
10,076 | db292faecd0f3b314ffc84d5f26c2a150d379f9a | count = 0
names = ["Adam","Alex","Mariah","Martine","Columbus"]
for name in names:
if name == "Adam":
count == count + 1
print
|
10,077 | b1bef3c4419e96592dc0df8623f88f7bbd9d6a8f | import os #importing os library so as to communicate with the system
import time #importing time library to make Rpi wait because its too impatient
os.system ("sudo pigpiod") #Launching GPIO library
import pigpio #importing GPIO library
ESC=4 #Connect the ESC in this GPIO pin
pi = pigpio.pi();
pi.set... |
10,078 | cea2ce65944927c54002666d77297d5aa55c22cb | #!/usr/bin/env python
import os
import time
import rospy
import math
import numpy as np
from std_msgs.msg import Float64
from geometry_msgs.msg import Pose2D
from geometry_msgs.msg import Vector3
from std_msgs.msg import Float32MultiArray
class Test:
def __init__(self):
self.testing = True
self.d... |
10,079 | a333b5d599462e6c102359924816c4384193675c | from math import radians, sin, cos, asin
from haversine import haversine, Unit
import numpy as np
from geopy import distance as vin
#RADIUS = 6372.8 # km
RADIUS = 6.371e6 # meters
#RADIUS = 6372.8e3 # wtf
#RADIUS = 3963 # miles
my_lat = 39.1114
my_lon = -84.4712
re_lat = 39.08961
re_lon = -84.4922799
vectors = [my... |
10,080 | cd09b63880a35a624a6458c96bcb7a5d155b4210 | import sys
"""
输入:
3 1
-1 1 3
1 1 3
输出:
3
https://blog.csdn.net/qq_18055167/article/details/108660179
"""
def myfun(n,xset,sset):
if n==0:
return sset[n]
res=[]
for i in range(n):
if (n-i)*d>=abs(xset[n]-xset[i]):
res.append(myfun(i,xset,sset)+sset[n])
return max(res)
n,d = ... |
10,081 | 23b3650a875147e9dc08d6846490ab0d4c960ebd | #!/usr/bin/env python
"""Unit tests for the NameGenerator class"""
from unittest import TestCase
from mock import Mock
from puckman.name_generator import NameGenerator
class TestNameGenerator(TestCase):
def test_creation(self):
generator = NameGenerator()
self.assertIsNotNone(generator)
se... |
10,082 | a5b00cb71666b0a41ddb717f9559b68efe412b0a | """
Created on Thu Nov 14 18:48:46 2019
@author: waqas
"""
import random
import numpy as np
from math import ceil, exp
from copy import deepcopy
from sklearn.metrics import mean_squared_error
class cgpann(object):
"""
Cartesian Genetic Programming of Artificial Neural Networks
is a Ne... |
10,083 | 6c5d11067f3c4b3c0722e7da38b3d1530e54898b | from django import forms
from .models import Zadanie
class ZadanieForm(forms.ModelForm):
temat = forms.CharField(widget=forms.TextInput(attrs={"placeholder": "Wpisz temat"}))
opis = forms.CharField(widget=forms.Textarea(attrs={"placeholder": "Dodaj opis", "rows": 20, "cols": 60}))
uwagi = forms.CharField(required=... |
10,084 | f758fd44538137dee0cb4811a27d0642362edb28 |
from app import models, db
from random import randint
user = models.User(user_name='123456789')
db.session.add(user)
db.session.commit()
while 1:
answer = raw_input("Create request?\n> ")
if answer == "n":
break
else:
r = models.Request(body="Sample text, lorem impsum, all that jazz.", parishioner=user)
db.... |
10,085 | 30ab6ece996efa052ca3ab6441537be1ced4f9cf | # Generated by Django 3.2 on 2021-04-19 01:36
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('Communication', '0006_auto_20210415_2126'),
]
operations = [
migrations.AlterField(
model_name='contacts',
name='Whos_... |
10,086 | b35478122ec803a6469afe1261c34df58c5e3a4a | from django.contrib.auth.models import AbstractUser
from django.db import models
from datetime import datetime
class User(AbstractUser):
company_name = models.CharField(max_length=64, blank=True)
first_name = models.CharField(max_length=64)
last_name = models.CharField(max_length=64)
phone = models.Ch... |
10,087 | 3c5458f803f84c25eb4aab4d35cb6042f7752020 |
import sqlite3
class User():
def __init__(self):
self.name = ''
self.password = ''
def Register(self):
konn = sqlite3.connect('User.db')
a = konn.cursor()
alllines = a.execute("select * from UserList")
user_list = []
... |
10,088 | 649861442a8182c20e68619b1fffe6aa0cd94d6e | #!/usr/bin/python
# Project: Soar <http://soar.googlecode.com>
# Author: Jonathan Voigt <voigtjr@gmail.com>
#
import distutils.sysconfig as sysconfig
import os, os.path, sys
import SCons.Script
from ast import literal_eval
from subprocess import check_output
Import('env')
clone = env.Clone()
clone['SWIGPATH'] = clone[... |
10,089 | 6b49be3df50bee2f1d2960ec46f56367c7dee3e1 | n = int(input("Enter a number: "))
while n < 0:
print("Please enter a positive number starting from 0")
n = int(input("Enter a number: "))
else:
f = 1
for i in range (1, n+1):
f = f * i
print("The total factorial of", n, "is", f)
|
10,090 | caebde443e15aeede8f019be4009fc6ac86e360b | import json
import os
import numpy as np
import pandas as pd
import requests
# Get the predict result of Azure model
def predict(data_csv, scoring_uri, key):
data_list = data_csv.values.tolist()
data = {'data': data_list}
# Convert to JSON string
input_data = json.dumps(data)
# Set the content... |
10,091 | 87db268a672ff4a9d6f969ded11b88e2646e0d15 | def scramble(s1, s2):
for i in range(100):
try:
if s2.count(s2[i]) > s1.count(s2[i]):
return False
except:
pass
return len(set(s2) - (set(s1) & set(s2))) == 0
#or from collections import Counter
|
10,092 | 17d1ff4c816a7de15be79b350b7372ce2f1e3541 | #!/usr/bin/python
"""
Gather several descriptive systems about a CCGbank instance:
- Number of categories vs n, where n is a frequency threshold
- Avg. category ambiguiy vs n
- Expected category entropy
"""
from os.path import join as pjoin
import CCG, pickles
import Gnuplot, Gnuplot.funcutils
import math, re, sys
fro... |
10,093 | cbfc5eb84726f99a8fad9a260020f0af022b81a5 | import unittest
def solution(S):
# ********** Attempt 2 - 2019/09/20 **********
count = 0
result = ''
current = 0
for i in range(len(S)):
if S[i] == '(':
count += 1
else:
count -= 1
if count == 0:
result += S[current + 1: i]
... |
10,094 | 9c9b302e18b5a29b58a7779c654cd57e21a9cdd8 | #
# CAESAR CIPHER - PART 6
# Add a GUI
# - by JeffGames
#
#
#
# ToDo:
# 1. Add JeffGames icon
# 2. Handle spaces in the string
# Import tkinter, our GUI framework
from tkinter import * # Import tkinter, our GUI framework
root = Tk()
# Variables used by the main program.
alphabet01 = 'GjlZCMaQKU"/-Xf$£\\m... |
10,095 | f6e392a9fee110a8a34f6456288654790c262533 | # https://atcoder.jp/contests/abc203/tasks/abc203_b
def sol1(N,K):
t = 0
for n in range(1, N+1):
for k in range(1, K+1):
t += n*100 + k
return t
def sol(N,K):
return sol1(N,K)
def test_1():
assert sol(1, 2) == 203
def test_2():
assert sol(3, 3) == 1818
# sol1(AC,8min)
#... |
10,096 | 7761a90f9180df39fd134abce9949ed766cc6ecb | import sys
import pdb
import numpy as np
import pandas as pd
import seaborn as sns
import pickle
from sqlalchemy import create_engine
from nltk.tokenize import word_tokenize
from nltk.stem import WordNetLemmatizer
from sklearn.pipeline import Pipeline
from sklearn.metrics import confusion_matrix
from sklearn.model_sele... |
10,097 | e240be130d20225aa423c8f71ae8a48294a18ff7 | WIDTH = 'width'
HEIGHT = 'height'
def get_bbox(pts):
bbox = {'x': int(pts[:, 0].min()), 'y': int(pts[:, 1].min())}
bbox['width'] = int(pts[:, 0].max() - bbox['x'])
bbox['height'] = int(pts[:, 1].max() - bbox['y'])
return bbox
def in_bbox(bbox, x, y):
return x >= bbox['x'] and x <= bbox['x'] + bbox[WIDT... |
10,098 | 473c4781ecc571c28b8a17abdc7b1b754e3ef34f | import re
import sys
import os
def parseTH3Log( logFileName ):
resultsDict = dict()
with open(logFileName) as f:
taskName = ""
taskResult=""
for line in f:
if line.rstrip() == "Begin MISUSE testing." or line.rstrip() == "End MISUSE testing." :
continue
... |
10,099 | fbc85d162745f5a57561728ce8ea0cc7075da491 | from django.urls import path
from .import views
urlpatterns = [
path('', views.rent, name='rent'),
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.