index int64 0 1,000k | blob_id stringlengths 40 40 | code stringlengths 7 10.4M |
|---|---|---|
5,100 | 513d7e3c34cc9da030e2e018ad2db6972cf440dc | # Main Parameters
FONTS_PATH = "media/battle_font.ttf"
LEVELS_PATH = "media/levels"
GAME_MUSIC_PATH = "media/sounds/DOOM.ogg"
MENU_MUSIC_PATH = "media/sounds/ANewMorning.ogg"
# GAME Parameters
FONT_SIZE = 30
CELL_WIDTH = 13 * 2
CELL_HEIGHT = 13 * 2
CELL_SIZE = (CELL_WIDTH, CELL_HEIGHT)
FPS = 30
DISPLAY_WIDTH = CELL_WI... |
5,101 | c7f8731fe58a0e0065827b82bb4ad4af670541db | import gitlab
from core import settings
gl = gitlab.Gitlab('https://gitlab.intecracy.com/', private_token='dxQyb5fNbLnBxvvpFjyc')
gl.auth()
project = gl.projects.get(settings.projectID)
print(project)
pipelines = project.pipelines.get(26452)
print pipelines
pipelines_jobs = pipelines.jobs.list()[2]
jobs = project.j... |
5,102 | bc6c3383684cbba775d17f81ead3346fe1a01f90 | import os
import math
import time
from tqdm import tqdm
import torch
from torch import nn
import torch.optim as optim
from torch.nn import functional as F
from torch.nn.utils import clip_grad_norm_
from torch.utils.data import DataLoader
from nag.modules import Transformer, TransformerTorch
from nag.logger... |
5,103 | 07e875a24d0e63ef596db57c4ec402f768225eec | def printBoard(board,pref):
border = "+----+----+----+----+----+----+----+----+"
for row in board:
print(pref,border)
cells ="|"
for cell in row:
if cell == 0:
cell = " "
elif cell in range(1,10):
cell = "0{}".format(cell)
... |
5,104 | fb5508b1b5aa36c4921358d6ca7f96fc7d565241 | # https://www.acmicpc.net/problem/2751
# n 개 수가 주어짐
# 목표 오름차순정렬
# 첫 줄 n개
# 둘째줄부터 n개의 줄에 수가 주어짐 세로로
# 출력 오름차순 정렬한 결과를 한 줄에 하나씩 출력한다?
n=int(input())
n_list=[int(input()) for _ in range(n)]
# print(n_list)
nn_list = []
# 인덱스 2개 관리
mid_idx = len(n_list) //2
left_idx = 0
right_idx = mid_idx +1
while left_idx <= mid... |
5,105 | 4bb006e2e457f5b11157dacb43fe94c8b400f146 | #!/usr/bin/python
import sys
class Generator:
def __init__(self, seed, factor, multiple):
self.value = seed
self.factor = factor
self.multiple = multiple
def iterate(self):
self.value = ( self.value * self.factor ) % 2147483647
# Repeat if this isn't an exact multiple
... |
5,106 | ed246f2887f19ccf922a4d386918f0f0771fb443 | # -*- coding: utf-8 -*-
"""
Created on Sat Jun 23 20:33:08 2018
@author: ashima.garg
"""
import tensorflow as tf
class Layer():
def __init__(self, shape, mean, stddev):
self.weights = tf.Variable(tf.random_normal(shape=shape, mean=mean, stddev=stddev))
self.biases = tf.Variable(tf.zeros(shape=[s... |
5,107 | f57490c8f4a5ba76824c3b41eb18905eb2213c23 | import pandas as pd
import os
"""
This code relies heavily on the form of the data. Namely it will fail if
the authors of the same book are not comma separated. It will also be inaccurate
or even fail if the same author for different books is not spelt in exactly the
same way.
"""
loc = r'C:\Users\james\OneDrive\Do... |
5,108 | 56d90835e64bd80fd9a6bb3a9b414e154d314d4a |
def get_analyse(curse):
'''
要求curse数据中index为时间,columns为策略名称,每一列为该策略净值
'''
qf_drawdown = []
qf_yeild = []
qf_std = []
date = curse.index
y = curse.copy()
for i in curse.columns:
# 计算当前日之前的资金曲线最高点
y["max2here"] = y[i].expanding().max()
# 计算历史最高值到... |
5,109 | b310c35b781e3221e2dacc7717ed77e20001bafa | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon May 6 10:05:25 2019
@author: MCA
"""
import smtplib, ssl
from email import encoders
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
import os,sys
import time
def loadFiles(su... |
5,110 | 00dbcae2d3941c9ef4c8b6753b8f6f7a46417400 | import torch
import torch.nn as nn
import torch.optim as optim
import torchtext
import absl.flags
import absl.app
import pickle
import yaml
import numpy as np
from tqdm import tqdm
from core import model
import core.dnc.explanation
from core import functions
from core.config import ControllerConfig, MemoryConfig, Train... |
5,111 | a4d47b9a28ec66f6a0473498674ebc538d909519 | import tkinter.ttk
import tkinter as tk
def update_info(info_t, data):
# temp = info_t.selection_set("x")
# print(temp)
# info_t.delete(temp)
# temp = info_t.selection_set("y")
# info_t.delete(temp)
pass
def path_to_string(s):
res = ""
for i in range(len(s)-1):
res += str(s[i... |
5,112 | 15539d824490b7ae4724e7c11949aa1db25ecab2 | #!/user/bin/env python
# -*- coding: utf-8 -*-
# @Author : XordenLee
# @Time : 2019/2/1 18:51
import itchat
import requests
import sys
default_api_key = 'bb495c529b0e4efebd5d2632ecac5fb8'
def send(user_id, input_text, api_key=None):
if not api_key:
api_key = default_api_key
msg = {
... |
5,113 | 6c825cb60475a1570e048cab101567bd5847d2c2 | from django.shortcuts import render_to_response, get_object_or_404
from django.http import HttpResponseNotFound
from django.template import RequestContext
from bgame.models import Game, Period, Player, ROLES
from bgame.forms import GameForm
import logging
log = logging.getLogger(__name__)
def index(request):
games... |
5,114 | 789f95095346262a04e7de0f9f9c5df6177e8fbc | # -*- coding: utf-8 -*-
import json
from django.conf import settings
from pdf_generator.utils import build_pdf_stream_from
from django.http import JsonResponse
from helpers.views import ApiView
from pdf_generator.forms import PdfTempStoreForm
from pdf_generator.serializers import PdfTempStoreSerializer
class Report... |
5,115 | f9f66452756cb67689d33aeb2e77535086355a7d | import telebot
import os
from misc.answers import answer_incorrect, answer_correct, answer_start
from helper import get_challenge_text, get_solved_challenge_text, is_correct_answer
bot = telebot.TeleBot(os.environ.get('API_KEY_TELEGRAM'))
default_parse_mode = "Markdown"
@bot.message_handler(commands=['start'])
def w... |
5,116 | e0f25addad8af4541f1404b76d4798d2223d9715 | """
Use the same techniques such as (but not limited to):
1) Sockets
2) File I/O
3) raw_input()
from the OSINT HW to complete this assignment. Good luck!
"""
import socket
import re
import time
host = "cornerstoneairlines.co" # IP address here
port = 45 # Port here
def execute_cmd(cm... |
5,117 | 607f0aac0d6d2c05737f59803befcff37d559398 | #!usr/bin/env python
# -*- coding:utf-8 -*-
"""
@author: Jack
@datetime: 2018/8/31 13:32
@E-mail: zhangxianlei117@gmail.com
"""
def isValid(s):
stack = []
for ss in s:
if ss in '([{':
stack.append(ss)
if ss in ')]}':
if len(stack) <= 0:
return Fal... |
5,118 | ea3217be80b6d1d3a400139bc4a91870cd2f1d87 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Jun 14 20:35:10 2020
@author: Johanna
"""
import numpy as np
###############################################################################
# Complex Visibility Functions
###############################################################################
... |
5,119 | 7f52354487f85a0bf1783c8aa76f228ef17e6d6b | import datetime
import pendulum
import requests
from prefect import task, Flow, Parameter
from prefect.engine.signals import SKIP
from prefect.tasks.notifications.slack_task import SlackTask
from prefect.tasks.secrets import Secret
city = Parameter(name="City", default="San Jose")
api_key = Secret("WEATHER_API_KEY")
... |
5,120 | 15bcfd8859322034ec76a8c861d2151153ab54af | import sys
import urllib
import urlparse
import xbmcgui
import xbmcplugin
import xbmcaddon
import shutil
from shutil import copyfile
base_url = sys.argv[0]
addon_handle = int(sys.argv[1])
args = urlparse.parse_qs(sys.argv[2][1:])
addon = xbmcaddon.Addon()
xbmcplugin.setContent(addon_handle, 'videos')
... |
5,121 | 8cdd7646dbf23259e160186f332b5cb02b67291b | # Generated by Django 2.2.3 on 2019-07-11 22:04
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('app1', '0002_property_details'),
]
operations = [
migrations.AlterField(
model_name='property_details',
name='flat_t... |
5,122 | 5c8de06176d06c5a2cf78ac138a5cb35e168d617 | import os
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.decomposition import TruncatedSVD
from sklearn.metrics.pairwise import cosine_similarity
def get_df_4_model(user_id, n_recommendations = 20000):
'''this func... |
5,123 | 9155b3eed8ac79b94a033801dbf142392b50720b | from bs4 import BeautifulSoup
from cybersource.constants import CHECKOUT_BASKET_ID, CHECKOUT_ORDER_NUM, CHECKOUT_SHIPPING_CODE, CHECKOUT_ORDER_ID
from cybersource.tests import factories as cs_factories
from decimal import Decimal as D
from django.core import mail
from django.core.urlresolvers import reverse
from mock i... |
5,124 | ce28330db66dcdfad63bdac698ce9d285964d288 | import pandas as pd
file = pd.read_csv("KDDTest+.csv")
with open("test_9feats.csv", "w") as f:
df = pd.DataFrame(file,
columns=[
"dst_host_srv_serror_rate", "dst_host_serror_rate",
"serror_rate", "srv_serror_rate", "count", "flag",
... |
5,125 | 55b8590410bfe8f12ce3b52710238a79d27189a7 | import logging
from utils import Utils
from block import Block
from message import Message
from transaction import Transaction
class Response:
def __init__(self, node, data):
self.node = node
self.data = data
self.selector()
def selector(self):
if self.data['flag'] == 1:
... |
5,126 | 700b0b12c75fa502da984319016f6f44bc0d52cc | /home/lidija/anaconda3/lib/python3.6/sre_constants.py |
5,127 | dc5d56d65417dd8061a018a2f07132b03e2d616e | # 15650번 수열 2번째
n, m = list(map(int, input().split()))
arr = [i for i in range(1,n+1)]
check = []
def seq(ctn, array, l):
if sorted(check) in array:
return
# if ctn == m:
# # l+=1
# # print('ctn :',ctn,' check :',sorted(check))
# array.append(sorted(check))
# for k in ... |
5,128 | 8498ba69e4cc5c5f480644ac20d878fb2a632bee | '''
Confeccionar un programa que genere un número aleatorio entre 1 y 100 y no se muestre.
El operador debe tratar de adivinar el número ingresado.
Cada vez que ingrese un número mostrar un mensaje "Gano" si es igual al generado o "El número aleatorio el mayor" o "El número aleatorio es menor".
Mostrar cuando gana el j... |
5,129 | c5d224a3d63d0d67bc7a48fecec156cca41cdcf7 | #!/usr/bin/python
"""
Starter code for exploring the Enron dataset (emails + finances);
loads up the dataset (pickled dict of dicts).
The dataset has the form:
enron_data["LASTNAME FIRSTNAME MIDDLEINITIAL"] = { features_dict }
{features_dict} is a dictionary of features associated with that pers... |
5,130 | ac83d7d39319c08c35302abfb312ebee463b75b2 | import sys
from melody_types import *
import dataclasses
"""
Marks notes for grace notes
"""
# Mark grace notes on the peak note of every segment
def _peaks(song):
for phrase in song.phrases:
for pe in phrase.phrase_elements:
if type(pe) == Segment:
if pe.direction != SegmentDir... |
5,131 | 940c3b4a2b96907644c0f12deddd8aba4086a0f0 | # -*- coding: utf-8 -*-
from tensorflow.python.ops.image_ops_impl import ResizeMethod
import sflow.core as tf
from sflow.core import layer
import numpy as np
# region arg helper
def _kernel_shape(nd, k, indim, outdim):
if isinstance(k, int):
k = [k for _ in range(nd)]
k = list(k)
assert len(k) =... |
5,132 | b5fee01582a28085983c56b9c266ef7fd5c3c927 | #!/usr/bin/env python
import cgitb
import cgi
import pymysql
form = cgi.FieldStorage()
c.execute("SELECT * FROM example")
recs = c.fetchall()
records1 = """
<body>
<table>
<tbody>
<tr>
<th>Full Name</th>
<th>Average Score</th>
</tr>"""
records_dyn = [
f"<tr><td>{name}</td><td>{avg... |
5,133 | 1482c8276f9cfc912293356d04e08307edf6d367 | import tkinter as tk
import cnt_script as sW
import key_script as kW
import text_script as tW
class MainWindow(tk.Tk):
def __init__(self):
super().__init__()
self.title("Main Window")
self.geometry("600x400+30+30")
tk.Button(self, text = "Count Tags", command = self.new_ta... |
5,134 | 0992297ffc19b1bc4dc3d5e8a75307009c837032 | import strawberry as stb
from app.crud import cruduser
from app.db import get_session
@stb.type
class Query:
@stb.field
async def ReadUser(self, info, username: str):
ses = await get_session()
fields = info.field_nodes[0].selection_set.selections[0]
return await cruduser.get_user(ses, ... |
5,135 | 0dea8675d8050a91c284a13bcbce6fd0943b604e | import pandas as pd
import numpy as np
class LabeledArray:
@staticmethod
def get_label_for_indexes_upto(input_data, input_label, input_index):
df_input_data = pd.DataFrame(input_data)
df_labels = pd.DataFrame(input_label)
df_data_labels = pd.concat([df_input_data, df_labels], axis=1)
... |
5,136 | 043ea0efd490522de4f6ee4913c8d66029b34ff5 | # =============================================================================
# Created By : Mohsen Malmir
# Created Date: Fri Nov 09 8:10 PM EST 2018
# Purpose : this file implements the gui handling to interact with emulators
# =============================================================================
from... |
5,137 | 7435aa6cd4eec5582be9f4a1dd75b0dfcadc4409 | from flask_socketio import SocketIO
socket = SocketIO()
@socket.on('test')
def on_test(msg):
print 'got message'
|
5,138 | 47cf3045f2fa0f69759e09b1599e4afe953c06d8 | INITIAL_B = 0.15062677711161448
B_FACTOR = 5.0
INITIAL_GE = 0.22581915788215678
GE_BOUNDS = [1.0 / 10.0, 1.0 / 4.0]
FIXED_P = 0.9401234488501574
INITIAL_GU = 0.2145066414796447
GU_BOUNDS = [1.0 / 15.0, 1.0 / 2.0]
INITIAL_GI = 0.19235137989123863
GI_BOUNDS = [1.0 / 15.0, 1.0 / 5.0]
INITIAL_GH = 0.044937075878220795... |
5,139 | 461b2de86907047df53c3857c6b0397e77de3fcd | import keras
from keras.applications import VGG16
from keras.preprocessing.image import ImageDataGenerator
from keras.models import Model
import matplotlib.pyplot as plt
from keras.callbacks import History
import numpy as np
import os
import cPickle as pickle
import scipy
from scipy import spatial
def getM... |
5,140 | ba1648143d49110a163da02e60fb0fd024a10b79 | from __future__ import print_function # Should comes first than torch
import torch
from torch.autograd import Variable
##
## Autograd.Variable is the central class of the package. It wraps a Tensor, and supports nearly all of operations defined on it. Once you finish your computation you can call .backward() and have ... |
5,141 | 7b527f9ec66ddf35f3395d78c857c021975402c7 | from django.urls import path
from main.views import IndexView, BuiltinsView, CustomView
app_name = 'main'
urlpatterns = [
path('', IndexView.as_view(), name='index'),
path('builtins/', BuiltinsView.as_view(), name='builtins'),
path('custom/', CustomView.as_view(), name='custom')
]
|
5,142 | 67e0536dc9f38ab82fe30e715599fed93c5425a5 | from ...java import opcodes as JavaOpcodes
from .primitives import ICONST_val
##########################################################################
# Common Java operations
##########################################################################
class New:
def __init__(self, classname):
self.clas... |
5,143 | 3f41cb1acbbb1a397ae1288bca1cbcd27c0d3f33 | # -*- coding: utf-8 -*-
import os
import subprocess
import virtualenv
from templateserver import __version__ as version
DEFAULT_TEMPLATE_DIR = 'templates'
DEFAULT_MEDIA_DIR = 'media'
DEFAULT_STATIC_DIR = 'static'
DEFAULT_ENV_DIR = '.env'
DEFAULT_RUNSERVER_PATH = 'runserver.py'
RUNSERVER_TEMPLATE = os.path.abspath(os... |
5,144 | b4e2897e20448d543c93402174db7da4066a8510 | class Solution(object):
def isIsomorphic(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
exist = set()
s_to_t = {}
if len(s) != len(t):
return False
for i, v in enumerate(s):
if v not in s_t... |
5,145 | e6ab18d87ace00436a480f4f01da224eead84fc0 | from PIL import Image, ImageDraw, ImageFont
from PIL.ExifTags import TAGS
from datetime import datetime
#Extracts the timestamp from the filename and inserts it into the image
def insert_timestamp_from_filename_into_image(path_to_image:str,
ignorable_string:str,
output_filename:str = "",
distance_to_border:int = 5, ... |
5,146 | b6d9b6ec10271627b7177acead9a617520dec8f8 | import pygame
from pygame.locals import *
import threading
from load import *
import time
import socket as sck
import sys
port=8767
grid=[[None,None,None],[None,None,None],[None,None,None]]
XO='X'
OX='X'
winner=None
coordinate1=600
coordinate2=20
begin=0
address=('localhost',port)
class TTTError(Exception):
def __i... |
5,147 | ff13ac0ee401471fe5446e8149f019d9da7f3ddf | import pytest
from feast.pyspark.launchers.gcloud import DataprocClusterLauncher
@pytest.fixture
def dataproc_launcher(pytestconfig) -> DataprocClusterLauncher:
cluster_name = pytestconfig.getoption("--dataproc-cluster-name")
region = pytestconfig.getoption("--dataproc-region")
project_id = pytestconfig.... |
5,148 | ef1b759872de6602646ce095823ff37f043ffd9d | class Solution(object):
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
if x < 0: return False
t = []
while x != 0:
t.append(x % 10)
x /= 10
i, j = 0, len(t)-1
while i < j:
if t[i] !... |
5,149 | c3755ff5d4262dbf6eaf3df58a336f5e61531435 |
from itertools import cycle
STEP_VAL = 376
spinlock = []
for count in range(2018):
len(spinlock) % count |
5,150 | 5c1465bc70010ecabc156a04ec9877bbf66a229d | import sys
import time
import numpy
import pb_robot
import pyquaternion
import pybullet as p
from copy import deepcopy
from actions import PlaceAction, make_platform_world
from block_utils import get_adversarial_blocks, rotation_group, ZERO_POS, \
Quaternion, get_rotated_block, Pose, add_noise,... |
5,151 | 41c44b32ce3329cbba5b9b336c4266bb20de31f0 | import shelve
def quantity_posts():
try:
data = shelve.open('data')
except Exception:
print(Exception)
else:
for key, value in sorted(data.items()):
print(key, ': \t', value, '\n')
finally:
data.close()
if __name__ == "__main__":
print('b... |
5,152 | fd391d28d76b0c1b3cf6d0b5134390ab3f1267fb | #!/usr/bin/python
#
# Copyright 2018-2020 Polyaxon, Inc.
#
# 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 ... |
5,153 | f49a133fa94aae791ef0f1eec54cf0629f45a0ed | # -*- coding: UTF-8 -*-
'''
model = DQN,DDQN,PDQN,PDDQN,DQN_PER,DDQN_PER,DQN_InAday,DQN_PER_Ipm...
'''
# -----------ContolGame------------
# CartPole - v1, MountainCar - v0, Acrobot - v1, Pendulum - v0
# from run_ContolGame import run_Game
# run_Game('DQN', 'CartPole-v1', episodes=400) # model,env,episodes
# --------... |
5,154 | f5820824b5b7e473b79b5dfee2f203684c3755be | # -*- coding: utf-8 -*-
import pandas as pd
import matplotlib.pyplot as plt
from tqdm import tqdm
from scipy.io import loadmat
from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt
import numpy as np
import copy
from matplotlib import cm
from matplotlib.animation import FuncAnimation
import scipy.opt... |
5,155 | 156203042ed8a9bde0e9d8587ea3d37de6bcfdf7 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('sub_adjuster', '0002_parameters'),
]
operations = [
migrations.AlterField(
model_name='subtitles',
n... |
5,156 | 527d514cbad0916fecfe0da68de04d3b130d94c7 | import re
from prometheus_client.core import GaugeMetricFamily
class ArrayHardwareMetrics:
def __init__(self, fa):
self.fa = fa
self.chassis_health = None
self.controller_health = None
self.component_health = None
self.temperature = None
self.temperature = None
... |
5,157 | 836e2fd6eca7453ab7a3da2ecb21705552b5f627 | import data
import numpy as np
import matplotlib.pyplot as plt
import xgboost as xgb
import pandas as pd
import csv
from matplotlib2tikz import save as tikz_save
import trial_sets
def print_stats(trial_id, dl):
wrist_device, _, true_device = dl.load_oxygen(trial_id, iid=False)
print("Length of Dataframe: " ... |
5,158 | 95256390e1e7e9227b96dccce33082de9d2cddd3 | import datetime
class Dato:
def __init__(self, id: int, dato: str, tipo: str, fecha: datetime.datetime):
self.__id = id
self.__dato = dato
self.__tipo = tipo
self.__fecha = fecha
def getId(self):
return self.__id
def setId(self, id):
self.__id = id
def... |
5,159 | afccf460bcf04f38b8c66177c86debd39a1b165f | # [백준] https://www.acmicpc.net/problem/11053 가장 긴 증가하는 부분 수열
# 일단 재귀식으로 풀어보기
# 이분탐색 어떻게 할 지 모르겠다
import sys
N = int(sys.stdin.readline().strip())
A = list(map(int, sys.stdin.readline().split()))
def recur():
if A[i] < A[i-1]:
|
5,160 | 66cdeaa106a8f22dbfd64c12c4cb04fdb9f5b453 | #!/usr/bin/env python
import sys
import ROOT
from ROOT import TTree
from ROOT import TChain
import numpy as np
import yaml
import xml.etree.ElementTree as ET
import datetime
#sys.path.append("/disk/gamma/cta/store/takhsm/FermiMVA/AllSky")
#sys.path.append("/home/takhsm/FermiMVA/python")
ROOT.gROOT.SetBatch()
from arra... |
5,161 | d4198c2c3706e03ba1bce3e31c5139f01248a184 | #------------------------------------------------------------------------------
# Copyright (c) 2011, Enthought, Inc.
# All rights reserved.
#------------------------------------------------------------------------------
import wx
from .wx_control import WXControl
from ...components.image_view import AbstractTkImag... |
5,162 | 22d3ff0fca9a5537da37bfbc968d83ec6f919752 | #!/usr/bin/env python2
## -*- coding: utf-8 -*-
import sys
def sx(bits, value):
sign_bit = 1 << (bits - 1)
return (value & (sign_bit - 1)) - (value & sign_bit)
SymVar_0 = int(sys.argv[1])
ref_263 = SymVar_0
ref_278 = ref_263 # MOV operation
ref_5710 = ref_278 # MOV operation
ref_5786 = ref_5710 # MOV operati... |
5,163 | 585c0f89605f1d791b449f42412174f06d0c5db5 | # -*- coding: utf-8 -*-
# !/usr/bin/python
import re
import sys
import xlwt
import os
'''
python logcat_time.py config_file logcat_file
'''
config_file = sys.argv[1]
logcat_file = sys.argv[2]
turns_time = 0
turn_compelete_flag = 0
def get_filePath_fileName_fileExt(filename):
(filepath, tempfilename) = os.path.s... |
5,164 | 4c6b04716f41c3413896f0d59f2cc9b1475d7f64 | from tkinter import*
from tkinter import filedialog
import sqlite3
class Gui:
def __init__(self):
global en3
self.scr = Tk()
self.scr.geometry("2000x3000")
self.scr.title("VIEWING DATABASE")
self.connection = sqlite3.connect("student_details.db")
... |
5,165 | cd9b04a93d85ba0ee2a38b534386f9aec0ef6895 | import httplib
import sys
http_server = "localhost:8000"
connection = httplib.HTTPConnection(http_server)
# Open test input.
test_file_path = "test_input"
test_f = open(test_file_path)
inputs = test_f.readlines()
inputs = [x.strip() for x in inputs]
test_f.close()
# Open expected input.
expected_file_path = "expect... |
5,166 | 5b3a6b44bd9ea80da1983d8254c73bba3e2338e1 | from django.conf.urls import url
from cart import views
urlpatterns=[
url(r'^add/$',views.cart_add,name='add'),#t添加购物车数据
url(r'^count/$',views.cart_count,name='count'),#huo获取购物车商品数量
url(r'^del/$',views.cart_del,name='delete'),#删除购物车商品记录
url(r'update/$',views.cart_update,name='update'),#更新购物车商品数目
u... |
5,167 | 874fa2a6afdd04f3f2232a86f56d220447160ede | # cases where DictAchievement should unlock
# >> CASE
{'name': 'John Doe', 'age': 24}
# >> CASE
{
'name': 'John Doe',
'age': 24
}
# >> CASE
func({'name': 'John Doe', 'age': 24})
|
5,168 | ace7e5676fcb01c3542952eaacdada9963b8467a | import sgc
import multiprocessing as mp
# import json
import argparse
import os
import re
#Process argument passed to the script
parser = argparse.ArgumentParser(description='Execute commands parallel on remote servers')
parser.add_argument('-f', action='store', required=True, dest='file', help='servers list')
group... |
5,169 | 86ec33393bb19ee432c30834ea7983b11f4d1234 | import scraperwiki
import xlrd
xlbin = scraperwiki.scrape("http://www.whatdotheyknow.com/request/82804/response/208592/attach/2/ACCIDENTS%20TRAMS%20Laurderdale.xls")
book = xlrd.open_workbook(file_contents=xlbin)
sheet = book.sheet_by_index(0)
for n, s in enumerate(book.sheets()):
print "Sheet %d is called %s and... |
5,170 | efe2d6f5da36679b77de32d631cca50c2c1dd29e | import numpy as np
from .build_processing_chain import build_processing_chain
from collections import namedtuple
from pprint import pprint
def run_one_dsp(tb_data, dsp_config, db_dict=None, fom_function=None, verbosity=0):
"""
Run one iteration of DSP on tb_data
Optionally returns a value for optimizati... |
5,171 | 89c44d35559504501e4333ea6ff4d3528f1a4c4f | from django.contrib import admin
from .models import Profile
from django.contrib.admin.templatetags.admin_list import admin_actions
admin.site.register(Profile)
# Register your models here.
|
5,172 | 511ea9eb1dc234a488c19f9ee9fbd40f81955d54 | from __future__ import print_function # Python 2/3 compatibility
import boto3
import json
import decimal
AWS_KEY = '****'
AWS_SECRET = '****'
def handler(event, context):
dynamodb = boto3.resource('dynamodb', region_name='us-west-2', aws_access_key_id=AWS_KEY , aws_secret_access_key=AWS_SECRET)
table = dynamo... |
5,173 | ad44e9411ba6a07c54bb55b0d8af9d0c16c6b71b | """
Python wrapper that connects CPython interpreter to the numba dictobject.
"""
from collections import MutableMapping
from numba.types import DictType, TypeRef
from numba import njit, dictobject, types, cgutils
from numba.extending import (
overload_method,
box,
unbox,
NativeValue
)
@njit
def _mak... |
5,174 | 9e2af13a15a98702981e9ee369c3a132f61eac86 | #!python
# -*- coding: utf-8 -*-
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from window.window import *
import sys
app = QtGui.QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_()) |
5,175 | 7484bd9012bc9952b679073ae036de4554d362be | from django import forms
from .models import Recipe, Ingredient, Category, Tag
from blog.widgets import CustomClearableFileInput
class NewCategoriesForm(forms.ModelForm):
friendly_name = forms.CharField(label='... or add your own category',
required=False)
class Meta():
... |
5,176 | 27ec06d084bf819383801be0351c04e7d1fc1752 | #Las listas son similares a las tuplas
# con la diferencia de que permiten modificar los datos una vez creados
miLista = ['cadena', 21, 2.8, 'nuevo dato', 25]
print (miLista)
miLista[2] = 3.8 #el tercer elemento ahora es 3.8
print(miLista)
miLista.append('NuevoDato')
print(miLista)
|
5,177 | b13d4b0ccb693fb97befb4ee47974d8ee076b52b | #!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'Eric Pascual'
from tornado.web import RequestHandler
import os
class UIHandler(RequestHandler):
def get_template_args(self):
return {
'app_title':"Capteurs de lumière et de couleur"
}
def get(self, *args, **kwargs):
... |
5,178 | 8a3694f96203ae8d1e306e1c9a5a47bfe26abeb1 | # -*- coding: utf-8 -*-
from django.shortcuts import render_to_response
from django.views.generic import TemplateView
from django.core.context_processors import csrf
from django.template import RequestContext
from django.views.generic import DetailView, ListView , CreateView , UpdateView , DeleteView , FormView , View
... |
5,179 | f1c6340880b52ba86856913f74c7d589d9b49f49 | #!/usr/bin/env python3
import warnings
import config
import numpy as np
from latplan.model import ActionAE, default_networks
from latplan.util import curry
from latplan.util.tuning import grid_search, nn_task
import keras.backend as K
import tensorflow as tf
float_formatter = lambda x: "%.3f" % x
np.set_printo... |
5,180 | 5a1c4cc572431f89709d20296d43e8d889e8c5b0 | Dict={0:0, 1:1}
def fibo(n):
if n not in Dict:
val=fibo(n-1)+fibo(n-2)
Dict[n]=val
return Dict[n]
n=int(input("Enter the value of n:"))
print("Fibonacci(", n,")= ", fibo(n))
# uncomment to take input from the user
nterms = int(input("How many terms? "))
# check if the number of terms is valid
... |
5,181 | a4dfac7e15064d92c806a4e3f972f06e4dca6b11 | # maze = [0, 3, 0, 1, -3]
with open('./day_5/input.txt') as f:
maze = f.readlines()
f.close
maze = [int(line.strip()) for line in maze]
# I think I will just expand on the original functions
# from now on rather than separating part one from two
def escape_maze(maze):
end = len(maze) - 1
step_counter = 0
... |
5,182 | 5c01b83634b7ae9bc691341d7432a4e59617444c | #!/usr/bin/python
# Classification (U)
"""Program: elasticsearchrepo_create_repo.py
Description: Unit testing of create_repo in
elastic_class.ElasticSearchRepo class.
Usage:
test/unit/elastic_class/elasticsearchrepo_create_repo.py
Arguments:
"""
# Libraries and Global Variables
# St... |
5,183 | ff53a549222b0d5e2fcb518c1e44b656c45ce76e | from rest_framework import status
from rest_framework.response import Response
from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import IsAuthenticated
from playlist.models import Song, AccountSong, Genre, AccountGenre
from account.models import Account
from play... |
5,184 | be279fe44b0d52c9d473e08d8b9c28d5b6386b45 | # -*- coding: utf-8 -*-
from __future__ import print_function
import os
import sys
from dkfileutils.path import Path
def line_endings(fname):
"""Return all line endings in the file.
"""
_endings = {line[-2:] for line in open(fname, 'rb').readlines()}
res = set()
for e in _endings:
if e.en... |
5,185 | d78ac5188cad104ee1b3e214898c41f843b6d8c0 | from sklearn.preprocessing import RobustScaler
from statsmodels.tsa.arima.model import ARIMA
from sklearn.metrics import mean_squared_error, r2_score, mean_absolute_error
from math import sqrt
import tensorflow as tf
import pandas as pd
import numpy as np
import os
import random
# set random seed
random.seed(1)
np.ra... |
5,186 | e5921edef3d3c56a73f2674f483ea4d1f3577629 | """
Copyright (c) 2017 Cyberhaven
Copyright (c) 2017 Dependable Systems Laboratory, EPFL
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 right... |
5,187 | 1152f144e17c11416f9ed56b4408f18615b16dc2 | from eums.test.api.api_test_helpers import create_option
from eums.test.factories.question_factory import MultipleChoiceQuestionFactory
from eums.test.api.authenticated_api_test_case import AuthenticatedAPITestCase
from eums.test.config import BACKEND_URL
from eums.models.question import MultipleChoiceQuestion
ENDPOI... |
5,188 | 0dd5511c0e39f113c46785be78a898e79bc45a21 | import pygame
import os
import random
#Vx = float(input("Input Vx : "))
#Vy = float(input("Input Vy : "))
Vx = 20
Vy = 20
#GEOMETRY
screen_width = 1000
screen_height = 600
FPS = 30
#COLOR
BLUE = (0, 0, 255)
BLACK = (0, 0, 0)
GREEN = (204, 153, 255)
RED = (255, 0, 0)
WHITE = (155, 25, 0)
colorLi... |
5,189 | cca1a491e2a48b4b0c7099a6c54e528158ef30bb | #!/usr/bin/python
import sys, os, glob, numpy
wd = os.path.dirname(os.path.realpath(__file__))
sys.path.append(wd + '/python_speech_features')
from features import mfcc, logfbank
import scipy.io.wavfile as wav
DIR = '/home/quiggles/Desktop/513music/single-genre/classify-me/subset'
OUTDIR = wd + '/songdata/subset'
#... |
5,190 | 3c22fbfd7d83ff3ecacabc3c88af2169fa5906b9 | """ [BBC] Web Scraper """
import os
from .abstract_crawler import AbstractWebCrawler
class BBCCrawler(AbstractWebCrawler):
""" [BBC] Web Scraper """
# Spider Properties
name = "web_bbc"
# Crawler Properties
resource_link = 'http://www.bbc.com/news/topics/cz4pr2gd85qt/cyber-security'
resourc... |
5,191 | 92b22ea23ad0cf4e16c7d19d055b7ec152ca433a | from scheme import *
from tests.util import *
class TestDateTime(FieldTestCase):
def test_instantiation(self):
with self.assertRaises(TypeError):
DateTime(minimum=True)
with self.assertRaises(TypeError):
DateTime(maximum=True)
def test_processing(self):
field =... |
5,192 | cf6dffb28e37003212d3e3402dee58a57a7d9869 | from __future__ import print_function, absolute_import, division
import os
import h5py
import glob
import copy
import numpy as np
from tqdm import tqdm
# from utils.pose import draw_skeleton
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import poseutils.camera_utils as cameras
from pose... |
5,193 | d99278c8f539322fd83ae5459c3121effc044b88 | from trapezoidal import trapezoidal
from midpoint import midpoint
from math import pi, sin
def integrate_sine(f, a, b, n = 2):
I_t = trapezoidal(f, a, b, n)
I_m = midpoint()
return None
a = 0.0; b = pi
f = lambda x: sin(x) |
5,194 | b8e18877af990c533c642d4937354198a4676419 | """autogenerated by genpy from arm_navigation_msgs/GetPlanningSceneRequest.msg. Do not edit."""
import sys
python3 = True if sys.hexversion > 0x03000000 else False
import genpy
import struct
import arm_navigation_msgs.msg
import geometry_msgs.msg
import std_msgs.msg
import genpy
import sensor_msgs.msg
class GetPlanni... |
5,195 | 37feeba8ff682e5998fde4bcba8c37043cb593f2 | # coding=utf-8
from smallinvoice.commons import BaseJsonEncodableObject, BaseService
class Catalog(BaseJsonEncodableObject):
def __init__(self, catalog_type, unit, name, cost_per_unit, vat=0):
self.type = catalog_type
self.unit = unit
self.name = name
self.cost_per_unit = cost_per_... |
5,196 | d65d85b4573728ed32ccf987459d5a228e2a8897 | # Generated by Django 3.1.7 on 2021-04-16 14:03
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='AuditLog',
fields=[
('id', models.AutoField... |
5,197 | 90f5629ac48edfccea57243ffb6188a98123367d | from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
#Print Stop words
stop_words = set(stopwords.words("english"))
print(stop_words)
example_text = "This is general sentence to just clarify if stop words are working or not. I have some awesome projects coming up"
words = word_tokenize(... |
5,198 | 16074fc1824a99b6fd1c4bf113d5b752308e8803 | from sqlalchemy.orm import sessionmaker
from IMDB.spiders.models import IMDB_DATABASE, db_connect, create_table
class ScrapySpiderPipeline(object):
# Bu Fonksiyon Veritabanı bağlantısını ve oturum oluşturucuyu başlatır ve bir İlişkisel Veritabanı tablosu oluşturur.
def __init__(self):
en... |
5,199 | 421b0c1871350ff541b4e56d1e18d77016884552 | # -*- coding: utf-8 -*-
"""Transcoder with TOSHIBA RECAIUS API."""
import threading
import queue
import time
import numpy as np
from logzero import logger
import requests
import model.key
AUTH_URL = 'https://api.recaius.jp/auth/v2/tokens'
VOICE_URL = 'https://api.recaius.jp/asr/v2/voices'
class Transcoder:
"""... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.