index int64 0 1,000k | blob_id stringlengths 40 40 | code stringlengths 7 10.4M |
|---|---|---|
4,400 | b227f222569761493f50f9dfee32f21e0e0a5cd6 | #Copyright 2008, Meka Robotics
#All rights reserved.
#http://mekabot.com
#Redistribution and use in source and binary forms, with or without
#modification, are permitted.
#THIS SOFTWARE IS PROVIDED BY THE Copyright HOLDERS AND CONTRIBUTORS
#"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
#LIMITED... |
4,401 | d0e957abfe5646fb84aed69902f2382d554dc825 |
from calc1 import LispTranslator, RPNTranslator, Parser, Lexer
import unittest
class TestTranslators(unittest.TestCase):
def init_rpn(self, program):
return RPNTranslator(Parser(Lexer(program)))
def init_lisp(self, program):
return LispTranslator(Parser(Lexer(program)))
def test_simple... |
4,402 | 8c2920db7fc49d56aa8da6289cd22272ed3e3283 | from django.apps import AppConfig
class ShortenConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'shorten'
|
4,403 | 29ec576d1fe04108eeb03a5d1b167671d3004570 | # Copyright 2017-2018 Ivan Yelizariev <https://it-projects.info/team/yelizariev>
# License MIT (https://opensource.org/licenses/MIT).
from datetime import datetime, timedelta
from odoo import fields
from odoo.tests.common import TransactionCase
class TestCase(TransactionCase):
def setUp(self):
super(Test... |
4,404 | f50c9aec85418553f4724146045ab7c3c60cbb80 | import numpy as np
from sklearn.preprocessing import OneHotEncoder
def formator(value):
return "%.2f" % value
def features_preprocessor(datasetLocation):
data = np.genfromtxt(datasetLocation,delimiter=",",usecols=range(41)) ##!!! usecols = range(41)
encoder = OneHotEncoder(categorical_features=[1,2,3])
encoder.fi... |
4,405 | 459bd36037158c9a6a38da6eadf45a3dc6f19e04 | import os
import sys
import requests
import urllib.parse
import urllib.request
import json
from shutil import copyfile
def sdssDownload(band, location, size, path):
"""
.
sdssArchie populates a directory with links to raw images
from the SDSS mission. These images are all in FITS format
and su... |
4,406 | 468c070aebff3124927c5595d68bb94321dd75e5 | import datetime
if __name__ == "__main__" :
keys = {'a','e','i', 'o', 'u', 'y'}
values = [1]
dictionnaire = {cle : list(values) for cle in keys}
print("dictionnaire : ", dictionnaire)
values.append(2)
#for cle in keys : dictionnaire.update({cle:values})
#dictionnaire.update({cle2 ... |
4,407 | cc87682d4ebb283e2d0ef7c09ad28ba708c904bd | # stopwatch.py - A simple stopwatch program.
import time
# Display the porgram's instructions
print(
""" \n\nInstructions\n
press Enter to begin.\n
Afterwards press Enter to "click" the stopwatch.\n
Press Ctrl-C to quit"""
)
input() # press Enter to begin
print("Started")
startTime = time.time()
lastTime = star... |
4,408 | d436362468b847e427bc14ca221cf0fe4b2623e3 | from flask_restful import Resource, reqparse
from db import query
import pymysql
from flask_jwt_extended import jwt_required
"""
This module is used to retrieve the data
for all the request_no's which have a false or a 0 select_status.
This is done by selecting distinct request_no's from requests table
for ... |
4,409 | 9004314951f77b14bab1aba9ae93eb49c8197a8d | # B. A New Technique
# TLE (Time limit exceeded)
from sys import stdin, stdout
t = int(input())
for _ in range(t):
n, m = map(int, input().split())
rows = [0] * n
a_column = list()
for r in range(n):
tmp = list(input().split())
rows[r] = tmp
a_column.append(tmp[0])
sorte... |
4,410 | b976dab3c621bb929eb488fa7f4394666efec2ed | import os
import json
from threading import Thread
import time
from time import sleep
from flask import Flask, json, render_template, request
import redis
from collections import OrderedDict
import requests
from Queue import Queue
REGISTRAR_URL = 'http://cuteparty-registrar1.cfapps.io/update'
app = Flask(__name__)
p... |
4,411 | ff09993a4f8fed65fa00c065eb5cfa41e7f9dcc1 | from django.contrib.auth.models import User
from django.db import models
class QueuedSpace(models.Model):
""" Stores space json for possible further editing before being sent to the server.
q_etag should update on every save so conflicts can be checked for in queued items.
"""
space_id = models.In... |
4,412 | d0f9dd0a06023dd844b0bf70dff360f6bb46c152 | #-*- coding: utf-8 -*-
#############################################################################
# #
# Copyright (c) 2008 Rok Garbas <rok@garbas.si> #
# ... |
4,413 | 6e739c30b3e7c15bd90b74cfd5a1d6827e863a44 | '''
Created on 4 Oct 2016
@author: MetalInvest
'''
def isHammerHangman(high, low, open, close):
body = abs(open - close)
leg = min(open, close) - low
return leg / body >= 2.0 and high/max(open, close) <= 1.08
def isEngulfing(df, bottom = True):
open_0 = df['open'][-1]
close_0 = d... |
4,414 | 7dff15a16ecc3ce3952f4b47290393ea3183807f | x=input("Do you really want to run this program? (y/n) : ")
x=x.upper()
if x=="Y" or x=="N" or x=="Q":
while x=="Y" or x=="N" or x=="Q":
if x=="Q":
print("Exiting the Program")
import sys
sys.exit()
elif x=="N":
print("You decided to leave. See you ag... |
4,415 | 44649e44da4eb80e7f869ff906798d5db493b913 | # -*- coding: utf-8; -*-
import gherkin
from gherkin import Lexer, Parser, Ast
def test_lex_test_eof():
"lex_text() Should be able to find EOF"
# Given a lexer that takes '' as the input string
lexer = gherkin.Lexer('')
# When we try to lex any text from ''
new_state = lexer.lex_text()
# T... |
4,416 | 391ecb2f23cc0ce59bd9fac6f97bd4c1788444b9 | n = eval(input("Entrez valeur: "))
res = 0
while n > 0:
res += n%10
n //= 10
print(res, n)
print(res)
|
4,417 | 5626e5a4a448630fbbbc92a67ae08f3ed24e1b9e | #Main program:
#reads IMU data from arduino uart
#receives PS3 Controller input
#Mantains Controller input frequency with CST
#!/usr/bin/env python
from map import mapControllerToDeg
from map import constrain
from map import wrap_180
from map import motorOutputLimitHandler
from uart1 import IMUDevice
import socket
fro... |
4,418 | c036621c5f03d94987b4da004d063d11a7cc8424 | # -*- coding:utf-8 -*-
'''
Created on 2013. 4. 30.
@author: Hwang-JinHwan
parsing the txt file which are generated by coping the pdf nova praxis rpg rule book
to create bootstrap document
'''
import re
import codecs
template = """
<head>
<style type="text/css">
body {{
padding-... |
4,419 | 80891a4c9703f91509d2c1b22304f33426dfb962 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file '/home/cypher/.eric6/eric6plugins/vcsGit/ConfigurationPage/GitPage.ui'
#
# Created by: PyQt5 UI code generator 5.8
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_GitPage(object):... |
4,420 | 4bc61ae2fe6453819a5bbf9cf05976f7800fa7c1 | import cv2
import numpy as np
from matplotlib import pyplot as plt
import glob
def des_match(des_l,des_q):
bf=cv2.BFMatcher(cv2.NORM_L2,crossCheck=True)
matches=bf.match(des_l,des_q)
matches = sorted(matches,key=lambda x:x.distance)
return matches
def check_match(matches,threshold,txt):
count=0
if (matches... |
4,421 | d6574cacea693517f3eaa92b4b929c2ee73da2e4 | from .tc_gcc import *
class AndroidGccToolChain(GccToolChain):
def __init__(self, name, ndkDir, gccVersionStr, platformVer, archStr, prefix = "", suffix = ""):
# TODO: non-windows host platform
hostPlatform = 'windows'
installDir = os.path.join(ndkDir, 'toolchains', prefix + gccVersionStr,... |
4,422 | 064f535b7ea0f1e4a09bdf830021f17d175beda7 | #coding=utf-8
from __future__ import division
import os
def judgeReported(evi, content):
for item in evi['reported']:
flag = content.find(item)
if flag > 0:
return 'Y'
for item in evi['properly']['neg']:
flag = content.find(item)
if flag > 0:
return... |
4,423 | 53c5f298dbfb21d7688fef8f0312858e2fd73d79 | # Python 3 program - Currency Sum Validator
# def bill_count
def bill_count(amount_user, list_of_money_bills):
n = len(list_of_money_bills)
# Initialize Result
ans = []
# Traverse through all the list
i = n - 1
while (i >= 0):
# Find list
while (amount_user >= list_of_mo... |
4,424 | 02bec34b138d53235dc944adeae8ccb8d6b3d340 | from django.shortcuts import render, HttpResponse, redirect
from .models import Book, Author # This is the models.py Database
# Create your views here.
def main(request):
context = {
"the_books" : Book.objects.all(), #Book Class model.py
}
return render(request, "index.html", context)
def book(re... |
4,425 | 01849a6bf5ce5eb75c549af28312f61711ad2494 | import smtplib
import subprocess
import time
class NotifyError(Exception):
def __init__(self, message):
self.message = message
class Notification(object):
def __init__(self, config, dry_run):
self.dry_run = dry_run
self.notifications = {}
def submit(self, recipient, message):
... |
4,426 | 72f3ae476581ff5acd6c7101764f4764285a47bd | input_object = open("input.txt", "r")
input_data = input_object.readlines()
input_object.close()
cleaned_data = []
for line in input_data:
cleaned_data.append(int(line.strip()))
input_size = len(cleaned_data)
for i in range(0, input_size):
for j in range(i, input_size):
for k in range(j, input_size):... |
4,427 | 571636be9d213d19bddfd1d04688bc0955c9eae5 | print('SYL_2整型数组_12 合并排序数组') |
4,428 | 7d6e8e6142184a1540daa29dac802fe75bd93d8e |
#Copyright ReportLab Europe Ltd. 2000-2017
#see license.txt for license details
__version__='3.3.0'
__doc__="""
The Canvas object is the primary interface for creating PDF files. See
doc/reportlab-userguide.pdf for copious examples.
"""
__all__ = ['Canvas']
ENABLE_TRACKING = 1 # turn this off to do profile testing w/... |
4,429 | 1522ebb52504f7f27a526b597fe1e262bbcbfbb0 | #!/usr/bin/python3
def add_tuple(tuple_a=(), tuple_b=()):
if len(tuple_a) < 1:
a_x = 0
else:
a_x = tuple_a[0]
if len(tuple_a) < 2:
a_y = 0
else:
a_y = tuple_a[1]
if len(tuple_b) < 1:
b_x = 0
else:
b_x = tuple_b[0]
if len(tuple_b) < 2:
b... |
4,430 | 9f02313b6f91f83e3a8b4af8d9447b1d8f3558f6 | import socket
from threading import Thread
from ast import literal_eval
clients = {}
addresses = {}
host = '127.0.0.1'
port = 5678
active = []
addr = (host, port)
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(addr)
groups = []
def broadcast(msg, prefix=""): # prefix is for name identificatio... |
4,431 | 341fb4442ba1d1bb13dbbe123e1051e1ceeb91e7 | import pymongo
import pandas as pd
import re
from pymongo import MongoClient
from nltk.corpus import stopwords
from nltk import word_tokenize
from gensim import corpora
import pickle
client = MongoClient()
db = client.redditCrawler
collection = db.data_test1
def remove_posts(data, index_list):
data = data.drop(i... |
4,432 | 5287bd1847848aa527df8ce57e896bc30c70b43c | from django.test import TestCase
from stack_it.models import Image
class TextPageContentModelTest(TestCase):
def test_instance(self):
file = Image.create_empty_image_file(name='hello.jpg')
image = Image.objects.create(image=file, alt="World")
self.assertEqual(Image.objects.count(), 1)
... |
4,433 | ef5d235f09eea827b240290218c397f880f1046d | import re
text = 'Macademia nuts, Honey tuile, Cocoa powder, Pistachio nuts'
search_pattern = re.compile('nuts')
search_match_object = search_pattern.search(text)
if search_match_object:
print(search_match_object.span())
print(search_match_object.start())
print(search_match_object.end())
print(search_... |
4,434 | 6cc23e370d1ec1e3e043c3fa6819f9166b6e3b40 | #!/usr/bin/python
class Symbol(object):
pass
class Fundef(Symbol):
def __init__(self, name, type, args):
self.name = name
self.type = type
self.args = args
class VariableSymbol(Symbol):
def __init__(self, name, type):
self.name = name
self.type = type
class ... |
4,435 | 2168d10a1b4796576cc7ebb6893e0dc8b58085ca |
""" view.py: Contains the View class. """
import random
import config
from graphics import *
class View:
""" The view class which handles the visual component of the application.
"""
def __init__(self, pygame, master):
""" Set up and initialise the view. Does not start the display. "... |
4,436 | d75187ed435c3d3aeeb31be4a0a4ed1754f8d160 | from temp_conversion_script import convert_c_to_f
from temp_conversion_script import fever_detection
def test_convert_c_to_f():
answer = convert_c_to_f(20.0)
expected = 68.0
assert answer == expected
def test2():
answer = convert_c_to_f(-40.0)
expected = -40.0
assert answer == expected
def test_fever_detection... |
4,437 | dd902f99ee8dc23f56641b8e75544a2d4576c19a | """
Given two strings A and B of lowercase letters, return true
if and only if we can swap two letters in A so that the result
equals B.
Example 1:
Input: A = "ab", B = "ba"
Output: true
"""
class Solution:
def buddyStrings(self, A: str, B: str) -> bool:
if len(A) != len(B):
return False... |
4,438 | 5c61ec549a3e78da4ea8a18bb4f8382f2b5c2cfa | #!/usr/bin/env python
# encoding: utf-8
# -*- coding: utf-8 -*-
# @contact: ybsdeyx@foxmail.com
# @software: PyCharm
# @time: 2019/3/6 9:59
# @author: Paulson●Wier
# @file: 5_词向量.py
# @desc:
# (1)Word2Vec
from gensim.models import Word2Vec
import jieba
# 定义停用词、标点符号
punctuation = ['、',')','(',',',",", "。", ":", ";",... |
4,439 | c0adc0032a2647a19d3540c057fa9762906e5f62 | from __future__ import division
import random as rnd
import math
from collections import Counter
from matplotlib import pyplot as plt
import ds_library
import ds_algebra
import ds_probability
import ds_gradient_descent
def normal_pdfs_visualization():
xs = [x/10.0 for x in range(-50, 50)]
plt.plot(xs... |
4,440 | db1b6c545555116a334061440614e83e62994838 | from flask import Flask, render_template
serious12 = Flask(__name__)
@serious12.route("/")
def home():
return "HOME"
@serious12.route("/user/<username>")
def user(username):
user = {
"trung": {
"name": "Trung",
"age": 19,
"birthplace": "Hanoi"
},
"n... |
4,441 | 7378f76b4c1f67d8a549aa2a88db8caa9b05338e | # -*- coding:utf-8 -*-
import time
import random
import numpy as np
from collections import defaultdict
class Simulator(object):
ALLOCATION_INTERVAL_MEAN = 150
ALLOCATION_INTERVAL_STDEV = 30
AFTER_ALLOCATION_INTERVAL_MEAN = 150
AFTER_ALLOCATION_INTERVAL_STDEV = 30
CLICK_INTERVAL_MEAN = 30
CLICK_INTERVAL_STDEV = ... |
4,442 | dfae1007adc557a15d03b78f2bf790fb5b06141a | from distributions.zero_inflated_poisson import ZeroInflatedPoisson
from distributions.negative_binomial import NegativeBinomial
from distributions.zero_inflated_negative_binomial import ZeroInflatedNegativeBinomial
from distributions.zero_inflated import ZeroInflated
from distributions.categorized import Categorized
f... |
4,443 | 6a3fd3323ed8792853afdf5af76161f3e20d4896 | '''
The while statement allows you to repeatedly execute a block of statements as long as a condition is true.
A while statement is an example of what is called a looping statement. A while statement can have an optional else clause.
'''
#Modifying the values using while loop in a list
l1: list = [1,2,3,4,5,6,7,8,9,10... |
4,444 | d2fce15636e43ca618c39c5c963bbf0c3a6a3886 | # this is just to test with ilp_polytope
import polytope
polytope.ilp_polytope.test2()
|
4,445 | 533154fe58511ac9c9c693bf07f076146b0c6136 | import os
from PIL import Image
import urllib
import json
import math
def download_images(a,b):
image_count = 0
k = a
no_of_images = b
baseURL='https://graph.facebook.com/v2.2/'
imgURL='/picture?type=large'
sil_check='/picture?redirect=false'
while image_count<no_of_images:
obj=urllib.urlopen(baseURL+str(k)+s... |
4,446 | 166a8cd0e09fbec739f43019659eeaf98b1d4fa4 | import argparse
def wrong_subtraction(n, k):
output = n
for i in range(k):
string_n = str(output)
if string_n[len(string_n) - 1] == '0':
output = int(string_n[:-1])
else:
output -= 1
return output
# d = "Do the wrong subtraction as per https://codeforces.com... |
4,447 | 7a6d5309580b673413f57047e631a08e61e837cf | from django.core.exceptions import ValidationError
from django.utils import timezone
def year_validator(value):
if value < 1 or value > timezone.now().year:
raise ValidationError(
('%s is not a correct year!' % value)
)
def raiting_validator(value):
if value < 1 or value > 10:
... |
4,448 | 43a23958b8c8779e3292f0f523a37b6d712fdbac | import time
class Block:
def __init__(self, index, transactions, previous_hash, nonce=0):
self.index = index
self.transaction = transactions
self.timestamp = time.time()
self.previous_hash = previous_hash
self.nonce = nonce
self.hash = None
|
4,449 | 913ff9b811d3abbe43bda0554e40a6a2c87053be | from abc import ABC, abstractmethod
from raspberry_home.view.geometry import *
from raspberry_home.view.renderable import Renderable
class View(Renderable, ABC):
@abstractmethod
def content_size(self, container_size: Size) -> Size:
pass
|
4,450 | 3179c13968f7bcdccbd00ea35b9f098dc49b42d8 | from functools import reduce
with open("input.txt") as f:
numbers = f.read().split("\n")
n = sorted(list(map(lambda x: int(x), numbers)))
n.insert(0, 0)
n.append(n[-1] + 3)
target = n[-1]
memoize = {}
def part2(number):
if number == target:
return 1
if number in memoize.keys():
return ... |
4,451 | d2c9ee64472c74767812d842d2c49eec962e28c6 | from utils import *
from wordEmbedding import *
print("bat dau")
def predict(text, phobert, tokenizer):
model = load_model('model.h5')
X_test = word2vec(text, phobert, tokenizer)
x_test_tensor = tf.convert_to_tensor(X_test)
X_tests = []
X_tests.append(x_test_tensor)
X_tests = tf.convert_to_t... |
4,452 | 1dcea61908753777604d99235407981e89c3b9d4 | import sys
sys.path.append('/usr/local/anaconda3/lib/python3.6/site-packages')
from numpy import sin, linspace
x = linspace(0, 4, 101)
y = sin(x)
from numpy import sin, linspace
plt.grid()
plt.xlabel('x')
plt.ylabel('f(x)')
plt.title('Funkcija $sin(x)$ un tās izvitzījums rindā')
plt.plot(x, y2)
plt.plot(x, y2, color ... |
4,453 | 6b647dc2775f54706a6c18ee91145ba60d70be21 | import konlpy
import nltk
# POS tag a sentence
sentence = u'만 6세 이하의 초등학교 취학 전 자녀를 양육하기 위해서는'
words = konlpy.tag.Twitter().pos(sentence)
# Define a chunk grammar, or chunking rules, then chunk
grammar = """
NP: {<N.*>*<Suffix>?} # Noun phrase
VP: {<V.*>*} # Verb phrase
AP: {<A.*>*} # Adjective... |
4,454 | ff8ffeb418bf4f9bc7d5dadd126ebc7c34c5c2cd | speed, lic_plate = input().split()
salary = int(0)
while lic_plate != "A999AA":
if int(speed) > 60:
if lic_plate[1] == lic_plate[2] and lic_plate [2] == lic_plate[3]:
salary += 1000
elif lic_plate[1] == lic_plate[2] or lic_plate [1] == lic_plate[3]:
salary += 500
elif... |
4,455 | 382cb55a6b849f0240276d8f45746e995b16d714 | import pandas as pd
import folium
ctx = '../data/'
json = ctx + 'us-states.json'
csv = ctx + 'US_Unemployment_Oct2012.csv'
data = pd.read_csv(csv)
m = folium.Map(location=[37, -102], zoom_start=5)
m.choropleth(
geo_data=json,
name='choropleth',
data=data,
columns=['State', 'Unemployment'],
Key_on=... |
4,456 | 5eab41a2ef536365bab6f6b5ad97efb8d26d7687 | import numpy as np
import initialization as init
import evaluation as eval
import selection as sel
import recombination as rec
import mutation as mut
initialize = init.permutation
evaluate = eval.custom
select = sel.rank_based
mutate = mut.swap
reproduce = rec.pairwise
crossover = rec.order
replace = sel.rank_based
... |
4,457 | d178818faf5fb18f5da48c1e2cf7991600731d06 | # -*- coding: utf-8 -*-
class Bot(dict):
def __init__(self):
self["getRayon"] = 0
self["getPosition"] = (-1000, -1000)
self.traj = []
def getTrajectoires(self):
return self.traj
def getRayon(self):
return self["getRayon"]
def getPosition(self):
return self["getPosition"]
if __name__ == "__main__":
i... |
4,458 | 963499e071873083dc942486b9a5b094393cd99e | from db_upgrader.Repositories.store import Store, StoreException
from db_upgrader.Models.product import *
class ProductStore(Store):
table = 'product'
def add_product(self, product):
try:
c = self.conn.cursor()
c.execute(
'INSERT INTO product (`name`,customerId,i... |
4,459 | efe5df4005dbdb04cf4e7da1f350dab483c94c92 | from django.db import models
# Create your models here.
class person(models.Model):
name=models.CharField(max_length=20,unique=True)
age=models.IntegerField()
email=models.CharField(max_length=20,unique=True)
phone=models.CharField(max_length=10, unique=True)
gender=models.CharField(max_length=10)
... |
4,460 | 85d1069d85e285bc5c36811f569dabd793b5064b | config = {'numIndividuals': 50, 'maxNumGen':20, 'eliteProp':0.1, 'mutantProp':0.2, 'inheritanceProb':0.7}
|
4,461 | 229d7378695f7e00176eb7c3962519af3db1b7e1 | # encoding: utf-8
from GlyphsApp.plugins import *
from outlineTestPenGlyphs import OutlineTestPenGlyphs
from string import strip
plugin_id = "de.kutilek.RedArrow"
class RedArrow(ReporterPlugin):
def settings(self):
self.menuName = "Red Arrows"
self.keyboardShortcut = 'a'
self.keyboardShortcutModifier = N... |
4,462 | 6d4950ca61cd1e2ee7ef8b409577e9df2d65addd | from disaggregation import DisaggregationManager
import numpy as np
from more_itertools import windowed
x = np.random.random_sample(10 * 32 * 1024)
w = windowed(x, n=1024, step=128)
z = DisaggregationManager._overlap_average(np.array(list(w)), stride=128)
print(z.shape)
print(x.shape)
assert z.shape == x.shape |
4,463 | a5ef2adbf85b5ab80c59697340f94bc57d60952e | """
Code for Alexa skill to check PB tracking
"""
from __future__ import print_function
import traceback
import requests
import os
import json
# --------------- Helpers that build all of the responses ----------------------
def build_speechlet_response(title, output, reprompt_text, should_end_session):
return {... |
4,464 | 48cef0377087d9245aad1fb759adf8ff07d2b66f | # Copyright 2021 Huawei Technologies Co., Ltd
#
# 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 law or agree... |
4,465 | da41f26489c477e0df9735606457bd4ee4e5a396 | import kubernetes.client
from kubernetes.client.rest import ApiException
from pprint import pprint
from kubeops_api.models.cluster import Cluster
class ClusterMonitor():
def __init__(self,cluster):
self.cluster = cluster
self.token = self.cluster.get_cluster_token()
self.cluster.change_to(... |
4,466 | 6abfd6c0a644356ae0bc75d62472b5c495118a8e | import time
from bitfinex_trade_client import BitfinexClient,BitfinexTradeClient
KEY = "nBi8YyJZZ9ZhSOf2jEpMAoBpzKt2Shh6IoLdTjFRYvb"
SECRET = "XO6FUYbhFYqBflXYSaKMiu1hGHLhGf63xsOK0Pf7osA"
class EMA:
def __init__(self, duration):
self.value = 0
self.duration = duration
self.count = 0
... |
4,467 | d122267e1da2d9cf68d245148bb496dfba3e7d19 | #!/usr/bin/env python
"""
Load API client for a Tool Registry Service (TRS) endpoint based
either on the GA4GH specification or an existing client library.
"""
import logging
from bravado.requests_client import RequestsClient
from ga4ghtest.core.config import trs_config
from .client import TRSClient
logger = logging... |
4,468 | 45750152313fd3670867c61d0173e4cb11a806ba | T = int(input())
for cnt in range(1, T + 1):
S = input()
S_list = []
card = {'S': 13, 'D': 13, 'H': 13, 'C': 13}
print('#' + str(cnt), end=' ')
for i in range(0, len(S), 3):
S_list.append(S[i:i + 3])
if len(set(S_list)) != len(S_list):
print('ERROR')
else:
for i in S_... |
4,469 | e2e5ca388d67f2a13eaef6067fc19e2dfe284a55 | import json
import sys
import os
# Change to Singularity working directory.
os.chdir('/mnt/cwd')
# Take subset index as argument
subset_index = sys.argv[1]
# Open up subset matching this.
with open('/mnt/scripts/outputs/instcat_list_subset'+str(subset_index)+'.json', 'r') as f:
instcat_list_subset = json.load(f)... |
4,470 | 6c27f70e820202f6cc4348de3c9198e7b20ec7d9 | from zExceptions import Unauthorized
if REQUEST is not None:
raise Unauthorized
portal = context.getPortalObject()
compute_node = context
reference = "TIOCONS-%s-%s" % (compute_node.getReference(), source_reference)
version = "%s" % context.getPortalObject().portal_ids.generateNewId(
id_group=('slap_tioxml_consum... |
4,471 | 00c6899b9d49cbbd0f1980eada77ad91562211a0 | import requests
import json
class Parser:
init_url = r'https://www.joom.com/tokens/init'
products_url = r'https://api.joom.com/1.1/search/products?language=ru-RU¤cy=RUB'
def __init__(self, links_list):
self.links = links_list
self.product_info_dict = {}
access_token = json.l... |
4,472 | 7dce240a891e807b1f5251a09a69368f4e513973 | # Advent of Code: Day 4
"""A new system policy has been put in place that requires all accounts to
use a passphrase instead of simply a password. A passphrase consists of a
series of words (lowercase letters) separated by spaces.
To ensure security, a valid passphrase must contain no duplicate words.
"""
def valid... |
4,473 | a52e0dde47d7df1b7b30887a690b201733ac7592 | from trytond.pool import Pool
from .reporte import MyInvoiceReport
def register():
Pool.register(
MyInvoiceReport,
module='cooperar-reporte-factura', type_='report')
|
4,474 | 0d28ab54f08301d9788ca9a5e46d522e043e9507 | from django.test import TestCase, Client
from pdf_crawler.models import Document
from rest_framework.reverse import reverse
class TestCase(TestCase):
client = Client()
def setUp(self):
Document.objects.create(name='First').save()
def test_endpoints(self):
"""
test for endpoints
... |
4,475 | 5456fb2938ae4d0f69414c153390f86437088114 | # Copyright 2017 Battelle Energy Alliance, LLC
#
# 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 law or agreed t... |
4,476 | b7d3af29e024b0b2cf5d2c054290f799eae7fed1 | import pymysql
pymysql.install_as_MySQLdb()
# from keras.models import load_model
# from keras.models import Model
# from ai import settings
#
# print('load model ...')
# model = load_model(settings.MODEL_PATH)
# model = Model(inputs=model.input, outputs=model.get_layer('dnsthree').output)
# print('load done.')
|
4,477 | 08f0b261b5a9b0f5133c468b3f92dc00285eda6a | import numpy as np
from sklearn.ensemble import RandomForestClassifier
from sklearn.grid_search import GridSearchCV
import matplotlib.pyplot as plt
def loadTrainSet(filepath):
raw = np.loadtxt(filepath, delimiter=',', dtype=np.str, skiprows=1)
X, y = raw[:,1:], raw[:,0]
trainSet = np.hstack((X, y.reshape(-... |
4,478 | 8ae6630ccd2f2b5a10401cadb4574772f6ecbc4a | import numpy as np
from math import inf
"""
Strategy made by duckboycool for carykh's Prisoner's Dilemma Tournament. (https://youtu.be/r2Fw_rms-mA)
It is a nice Tit for Tat based strategy that attempts to detect when the opponent is not changing their actions based
off of ours so we can maximize with defects, and att... |
4,479 | 149ac778a552fac4499d7146db8600c91c68c60e | from time import sleep
import RPi.GPIO as gpio
buzzer_pin = 18
gpio.setmode(gpio.BCM)
gpio.setup(buzzer_pin, gpio.OUT)
def buzz(pitch, duration):
peroid = 1.0/pitch
delay = peroid / 2.0
cycles = int(duration*pitch)
for i in range(cycles):
gpio.output(buzzer_pin, True)
sleep(delay)
... |
4,480 | 5ed34ada35dfb2f783af4485bf9d31aa42712b9a | """
Django settings for hauki project.
"""
import logging
import os
import subprocess
import environ
import sentry_sdk
from django.conf.global_settings import LANGUAGES as GLOBAL_LANGUAGES
from django.core.exceptions import ImproperlyConfigured
from sentry_sdk.integrations.django import DjangoIntegration
CONFIG_FILE... |
4,481 | 04938e14f22c44437188469b53dfb05d2ecd4a5c | '''
tag名だけで変えてもいいよね??
ただし,置換するときは,「代表参照表現(参照表現)」のように,元の参照表現が分かるように配慮せよ.→何を言いたい!?
もしかして:
<mention> -> <mention representative="false"> 欲しい??「元の参照表現が分かる」とは <mention representative="true"> と区割りできればいいよね?
'''
from bs4 import BeautifulSoup, element
soup = BeautifulSoup(open("nlp.txt.xml"),"lxml")
mentions = soup.find_all('me... |
4,482 | c173c4673fd716a8b88faf751639d52e9ea4ffab | '''
Copyright 2014-2015 Reubenur Rahman
All Rights Reserved
@author: reuben.13@gmail.com
'''
import XenAPI
inputs = {'xenserver_master_ip': '15.22.18.17',
'xenserver_password': 'reuben',
'xenserver_user': 'root',
'vm_name': 'SLES11SP2x64',
'target_host': 'xenserver-2'
... |
4,483 | 1ac3630e6433a2d11c716b558640cab7c559f6ba | # coding: utf8
from __future__ import unicode_literals
from nltk.tag import stanford
from .SequenceTagger import SequenceTagger
class POSTagger(SequenceTagger):
"""
>>> tagger = POSTagger(model='resources/postagger.model')
>>> tagger.tag(['من', 'به', 'مدرسه', 'رفته_بودم', '.'])
[('من', 'PRO'), ('به', 'P'), ('مدر... |
4,484 | 3da82bcff0a4f91c1245892bc01e9f743ea354a8 | import sys
n=int(input().strip())
a=list(input().strip().split(' '))
H=list(input().strip().split(' '))
a = [int(i) for i in a]
m=int(H[0])
hmin=int(H[1])
hmax=int(H[2])
pos=0
found = 0
d=a[-1]-a[0]
if(d==m):
print(a[0])
elif(0<d<m):
for i in range(hmin, hmax+1):
fin1 = a[0]-i+m
if(hmin<=fin1-... |
4,485 | 3956d4cdb0a8654b6f107975ac003ce59ddd3de1 | import random
def generatePassword ():
numLowerCase = numUpperCase = numSpecialCase = numNumber = 0
password = ""
randomChars = "-|@.,?/!~#%^&*(){}[]\=*"
length = random.randint(10, 25)
while(numSpecialCase < 1 or numNumber < 1 or numLowerCase < 1 or numUpperCase < 1):
password = ""
... |
4,486 | fe3584dd858c06d66215b4a182adf87d35324975 | from pyecharts import options as opts
from pyecharts.charts import *
import pandas as pd
import namemap
from pyecharts.globals import ThemeType
#
import time
import json
import requests
from datetime import datetime
import pandas as pd
import numpy as np
def read_country_code():
"""
获取... |
4,487 | 90a220775efcc8ff9e83f1a1f011f424ddc3476d | import tensorflow as tf
from model import CabbageModel
import numpy as np
from krx import KrxCrawler
from naver_stock import StockModel as sm
from scattertest import scattertest as st
class CabbageController:
def __init__(self):
#def __init__(self, avg_temp, min_temp, max_temp, rain_fall):
#self._a... |
4,488 | 5e6bbb10ec82e566c749dd4d794eabd2e8f7a648 | #!/usr/bin/env python3
import numpy as np
from DMP.PIDMP import RLDMPs
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
np.random.seed(50)
dmp_y0 = np.array([-1.52017496, 0.04908739, 1.41433029])
dmp_goal = np.array([-1.50848603, 0.0591503 , 1.44347592])
load_file_name = "w_0_2_right_3... |
4,489 | af80cb4d4ce5c071efc39e85f89bb412cff6bf6e | IMAGE_SIZE=(640, 480)
|
4,490 | eee60a6f46549ededfbc7b0b294ab723e2e73f7e | from .base import *
RAVEN_CONFIG = {}
ALLOWED_HOSTS = ['*']
|
4,491 | f996dffcb9650663278ec1e31d9f88d50142f4ea | class TrieNode:
def __init__(self):
self.children: Dict[str, TrieNode] = collections.defaultdict(TrieNode)
self.word: Optional[str] = None
class Solution:
def findWords(self, board: List[List[str]], words: List[str]) -> List[str]:
m = len(board)
n = len(board[0])
ans = []
root = TrieNode()... |
4,492 | 8fedaeb13fde117cf6b7ace23b59c26e4aab2bc2 | a = input()
b = []
ind = []
for i in a:
if i.isalpha():
b.append(i)
else:
ind.append(a.index(i))
c = list(reversed(b))
for i in ind:
c.insert(i,a[i])
print(''.join(c))
|
4,493 | b216c0f92bcf91fd538eabf0239cf149342ef2eb | from django.shortcuts import render
from django.views.generic import ListView
from auth_person.models import Post_news, User
# Create your views here.
def blog(request, foo):
inf = {'login': foo}
return render(request, 'blog/blog.html', context=inf)
class feed(ListView):
template_name = 'blog/feed.html'... |
4,494 | 9b715fb95e89804a57ea77a98face673b57220c6 | import socket
import struct
def parsing_ethernet_header(data):
ethernet_header=struct.unpack("!6c6c2s",data)
ether_dest = convert_ethernet_address(ethernet_header[0:6])
ether_src = convert_ethernet_address(ethernet_header[6:12])
ip_header="0x"+ethernet_header[12].hex()
print("=========ethernet hea... |
4,495 | 7a243f5e24d81d3395cc790dface5e795b9c04e6 | """Distribution script for unitreport."""
import setuptools
with open("README.md", "r") as f:
long_description = f.read()
setuptools.setup(
name="unitreport",
version="0.1.1",
author="annahadji",
author_email="annahadji@users.noreply.github.com",
description="A small unittest-based tool for ge... |
4,496 | b63ed9e09b9e8c539aff765d719f3610283663fe | # -*- coding: utf-8 -*-
from __future__ import unicode_literals, print_function
from abc import ABCMeta, abstractmethod
from six import with_metaclass
from .utils import parse_query_parameters
class CollectionMixin(with_metaclass(ABCMeta, object)):
@abstractmethod
def list(self, size=100, offset=None, **fil... |
4,497 | ba13bcf9e89ae96e9a66a42fc4e6ae4ad33c84b4 | import mclient
from mclient import instruments
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
#from pulseseq import sequencer, pulselib
mpl.rcParams['figure.figsize']=[6,4]
qubit_info = mclient.get_qubit_info('qubit_info')
qubit_ef_info = mclient.get_qubit_info('qubit_ef_info')
... |
4,498 | 2bc20f3410d068e0592c8a45e3c13c0559059f24 | #Use bisection search to determine square root
def square_calculator(user_input):
"""
accepts input from a user to determine the square root
returns the square root of the user input
"""
precision = .000000000001
counter = 0
low = 0
high = user_input
guess = (low + high) / 2.0
w... |
4,499 | 4f0a0089ad128edca3052da58a4c71f935592e25 | import sys
from arguments_parser import parse_args
from open_ldap import OpenLdap
from csv_parser import parse_csv, random_password
from smtp_mail import SmtpServer
def create_user(open_ldap, smtp, entries):
"""
If the 'ldap_insert' returns True, then
the email will be send with the account info.
"""
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.