index int64 0 1,000k | blob_id stringlengths 40 40 | code stringlengths 7 10.4M |
|---|---|---|
6,500 | fea0619263b081f60ed0a4e178ef777a8d5dc988 | from django.contrib import admin
from .models import TutorialsReview,TutorialsReviewComment
admin.site.register(TutorialsReview)
admin.site.register(TutorialsReviewComment) |
6,501 | 0779e516e35c41acf0529961e11541dfd1320749 | # funkcja usuwająca zera z listy
def remove_zeros(given_list):
list_without_zero = []
for element in given_list:
if element != 0:
list_without_zero.append(element)
return list_without_zero
# funkcja sortująca listę
def sort_desc(given_list):
# sorted_list = []
# for ... |
6,502 | 1f0349edd9220b663f7469b287f796e4a54df88d | '''Finding Perfect Numbers
3/2/17
@author: Annalane Miller (asm9) and Ivanna Rodriguez (imr6)'''
num_perfect = 0
for value in range(2, 10000):
#set initial values
high= value
low = 1
divisors = []
#finding divisors
while low < high:
if value % low ==0:
high = value// low
... |
6,503 | b80deec4d3d3ab4568f37cc59e098f1d4af5504c | # Square-Root of Trinomials
import math
print("Έχουμε ένα τριώνυμο ax²+bx+c. Δώστε μία θετική ή αρνητική τιμή σε κάθε σταθερά!")
a=int(input("a:"))
b=int(input("b:"))
c=int(input("c:"))
D= b**2-4*a*c
print("Η Διακρίνουσα ειναι: " + str(D))
if D>0:
x1=(-b+math.sqrt(D))/(2*a)
print("Η πρώτη ρίζα ειναι: " + s... |
6,504 | 7775d260f0db06fad374d9f900b03d8dbcc00762 | # -*- coding: utf-8 -*-
# @time : 2021/1/10 10:25
# @Author : Owen
# @File : mainpage.py
from selenium.webdriver.common.by import By
from homework.weixin.core.base import Base
from homework.weixin.core.contact import Contact
'''
企业微信首页
'''
class MainPage(Base):
#跳转到联系人页面
def goto_contact(self):
... |
6,505 | 071e3cf6b4337e0079bbb2c7694fff2468142070 | import pygame
class BackGround:
def __init__(self, x, y):
self.y = y
self.x = x
def set_image(self, src):
self.image = pygame.image.load(src)
self.rect = self.image.get_rect()
self.rect.y = self.y
self.rect.x = self.x
def draw(self, screen):
screen... |
6,506 | 784b51c05dc7b5e70016634e2664c9ec25b8a65a | import numpy as np
from sklearn.decomposition import PCA
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
from preprocessing import *
from utils import *
def find_optimal_param(lda, x_train, y_train):
probs_train = lda.predict_proba(x_train)[:, 1]
y_train = [x for _,x in sorted(zip(prob... |
6,507 | b0468e58c4d0387a92ba96e8fb8a876ece256c78 | import mmap;
import random;
def shuffle():
l_digits = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
random.shuffle(l_digits);
return "".join(l_digits);
with open("hello.txt", "r+") as f:
map = mmap.mmap(f.fileno(), 1000);
l_i = 0;
for l_digit in shuffle():
map[l_i] = l_digit;
... |
6,508 | 9cca73ebdf2b05fe29c14dc63ec1b1a7c917b085 | # Cutting a Rod | DP-13
# Difficulty Level : Medium
# Last Updated : 13 Nov, 2020
# Given a rod of length n inches and an array of prices that contains prices of all pieces of size smaller than n. Determine the maximum value obtainable by cutting up the rod and selling the pieces. For example, if length of the rod is... |
6,509 | 9061db3bb3aa3178262af58e56126302b9effdff | import pymel.all as pm
from collections import Counter
# example
# v.Create( sel[0], pm.datatypes.Color.red, sel[1], 'leftEye', 0.2 )
# select mesh 1st then the control
def Create( obj, targetColor, control, attr, offset ) :
shape = obj.getShape()
name = obj.name()
if( type(shape) == pm.Mesh ) :
outVerts = []
... |
6,510 | 89dfd9a32b008307eb4c456f2324804c29f3b68f | import numpy as np
class SampleMemory(object):
def __init__(self, item_shape, max_size):
self.memory = np.zeros((max_size,) + item_shape)
self.item_shape = item_shape
self.num_stored = 0
self.max_size = max_size
self.tail_index = 0
def sample(self, num_sampl... |
6,511 | 30e4c4c5ef944b0cd2d36b2fe5f7eee39dff1d16 | alien_color = 'green'
if alien_color == 'green':
print('you earned 5 points')
alien_color2 = 'yellow'
if alien_color2 == 'green':
print ('your earned 5 points')
if alien_color2 == 'yellow':
print('Right answer')
# 5.4
alien_color = 'green'
if alien_color == 'green':
print('you earned 5 po... |
6,512 | 3970c7768e892ad217c193b1d967c1203b7e9a25 | import math
def is_prime(n):
# Based on the Sieve of Eratosthenes
if n == 1:
return False
if n < 4:
# 2 and 3 are prime
return True
if n % 2 == 0:
return False
if n < 9:
# 5 and 7 are prime (we have already excluded 4, 6 and 8)
return True
if n %... |
6,513 | 76526bdff7418997ac90f761936abccbb3468499 | """
Array.diff
Our goal in this kata is to implement a difference function,
which subtracts one list from another and returns the result.
It should remove all values from list a, which are present in list b keeping their order.
"""
from unittest import TestCase
def list_diff(a, b):
return [x for x in a if x n... |
6,514 | 9fd985e9675514f6c8f3ac5b91962eb744e0e82c | import numpy
import matplotlib.pyplot as plt
numpy.random.seed(2)
# create datasets
x = numpy.random.normal(3, 1, 100)
y = numpy.random.normal(150, 40, 100) / x
# displaying original dataset
plt.scatter(x, y)
plt.title("Original dataset")
plt.xlabel("Minutes")
plt.ylabel("Spent money")
plt.show()
# train dataset wi... |
6,515 | 607700faebc2018327d66939419cc24a563c3900 | # Return min number of hacks (swap of adjacent instructions)
# in p so that total damage <= d.
# If impossible, return -1
def min_hacks(d, p):
# list containing number of shoot commands per
# damage level. Each element is represents a
# damage level; 1, 2, 4, 8, ... and so on.
shots = [0]
damage = 0
for c ... |
6,516 | 1634ae0e329b4f277fa96a870fbd19626c0ece81 | from sympy import *
import sys
x = Symbol("x")
# EOF
try:
in_str = input()
except Exception as e:
print("WRONG FORMAT!") # Wrong Format!
sys.exit(0)
in_str = in_str.replace("^", "**") #change '^'into'**' for recognition
# wrong expression
try:
in_exp = eval(in_str) # turn s... |
6,517 | 052824082854c5f7721efb7faaf5a794e9be2789 | L5 = [0]*10
print(L5)
L5[2] = 20
print(L5)
print(L5[1:4])
L5.append(30)
print(L5)
L5.remove(30) #Elimina la primera ocurrencia del objeto
print(L5)
L6 = [1,2,3,4,5,6]
print(L6[1::2])
print(L6[::2]) |
6,518 | e99d3ae82d8eea38d29d6c4f09fdb3858e36ca50 | import requests as r
from .security import Security, Securities
from .data import Data
url_base = 'https://www.alphavantage.co/query'
def _build_url(**kargs):
query = {
'function': 'TIME_SERIES_DAILY',
'symbol': 'SPY',
'outputsize': 'full',
'datatype': 'json',
'apikey': 'JPIO2GNGBMFRLGMN'
}
query.update(kar... |
6,519 | 4b14dee3625d5d0c703176ed2f0a28b2583fd84d | """
Creating flask server that response with a json
"""
from flask import Flask
from flask import jsonify
micro_service = Flask(__name__)
@micro_service.route('/') # http://mysite.com/
def home():
return jsonify({'message': 'Hello, world!'})
if __name__ == '__main__':
micro_service.run()
|
6,520 | 430e971d2ae41bfd60e7416ecb2c26bb08e4df45 | import os
import os.path
import numpy as np
import pickle
import codecs
from konlpy.tag import Okt
from hyperparams import params
from gensim.models import FastText
#tokenizer
tokenizer = Okt()
def make_word_dictionary(word_dict_pkl_path=params['default_word_dict_pkl_path'], training_data_path = params['d... |
6,521 | 275f8b6ac31792a9e4bb823b61366f868e45ef4e | import datetime
from app.api.v2.models.db import Database
now = datetime.datetime.now()
db = Database()
cur = db.cur
class Meetup():
#meetup constructor
def __init__(self, topic, location, tags, happening_on):
self.topic = topic
self.location = location
self.tags = tags
self.h... |
6,522 | 8804bfc5bed8b93e50279f0cbab561fe09d92a64 | from random import randint
import matplotlib.pyplot as plt
def generate_list(length: int) -> list:
"""Generate a list with given length with random integer values in the interval [0, length]
Args:
length (int): List length
Returns:
list: List generated with random values
"""
retu... |
6,523 | cb2dd08a09d2e39bd83f82940c3d9a79a5a27918 | import logging
import subprocess
from pathlib import Path
from typing import Union
from git import Repo
def init_repo(metadata: str, path: str, deep_clone: bool) -> Repo:
clone_path = Path(path)
if not clone_path.exists():
logging.info('Cloning %s', metadata)
repo = (Repo.clone_from(metadata, ... |
6,524 | 7df55853d0f4f1bf56512c4427d7f91e9c1f2279 | """Initial migration
Revision ID: 1f2296edbc75
Revises: 7417382a3f1
Create Date: 2014-01-19 23:04:58.877817
"""
# revision identifiers, used by Alembic.
revision = '1f2296edbc75'
down_revision = '7417382a3f1'
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
from sqlalchemy i... |
6,525 | 7eb4efb64a5a5b2e8c2dfa965411ff4c7aad6e35 | from soln import Solution
import pytest
@pytest.mark.parametrize(
["inp1", "inp2", "res"],
[
("112", 1, "11"),
("11000002000304", 4, "4"),
("9119801020", 6, "20"),
("111111", 3, "111"),
("1432219", 3, "1219"),
("10200", 1, "200"),
("10", 2, "0"),
... |
6,526 | 21c12aabfb21e84f3ea546842fb55c41d2129ff9 | import re
list = ["Protein XVZ [Human]","Protein ABC [Mouse]","go UDP[3] glucosamine N-acyltransferase [virus1]","Protein CDY [Chicken [type1]]","Protein BBC [type 2] [Bacteria] [cat] [mat]","gi p19-gag protein [2] [Human T-lymphotropic virus 2]"]
pattern = re.compile("\[(.*?)\]$")
for string in list:
match = re.se... |
6,527 | 9609f23463aa4c7859a8db741c7f3badd78b8553 | #!/usr/bin/python
'''Defines classes for representing metadata found in Biographies'''
class Date:
'''Object to represent dates. Dates can consist of regular day-month-year, but also descriptions (before, after, ca.). Object has attributes for regular parts and one for description, default is empty string.'''
... |
6,528 | f14b9373e9bf1ad7fe2216dfefc1571f5380fb27 | #!/usr/bin/python3
"""minimum time time to write operations of copy and paste"""
def minOperations(n):
"""
a method that calculates the fewest number of operations needed
to result in exactly n H characters in the file
"""
if n <= 1:
return 0
"""loop for n number of times"""
for i... |
6,529 | 9c14f024b25c5014567405535dbe5a6c787cfe28 | from abc import ABC
from rest_framework import serializers
from shopping_cars.models import Order, ShoppingCart
class OrderSerializer(serializers.ModelSerializer):
class Meta:
model = Order
fields = '__all__'
class OrderProductSerializer(serializers.ModelSerializer):
class Meta:
mode... |
6,530 | 02d4e1ddb0b4cf75c9902e13263c5a80417de01b | from tkinter import *
from tkinter import messagebox as mb
from tkinter.scrolledtext import ScrolledText
from tkinter import filedialog as fd
from child_window import ChildWindow
# from PIL import Image as PilImage
# from PIL import ImageTk, ImageOps
class Window:
def __init__(self, width, height, title="MyWindow... |
6,531 | 76fbe055b53af9321cc0d57a210cfffe9188f800 | #
# PySNMP MIB module CISCO-LWAPP-CLIENT-ROAMING-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-LWAPP-CLIENT-ROAMING-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:04:56 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python ... |
6,532 | 2c6dc4d55f64d7c3c01b3f504a72904451cb4610 | """
2. Schreiben Sie die Anzahl von symmetrischen Paaren (xy) und (yx).
"""
def symetrisch(x, y):
"""
bestimmt weder zwei zweistellige Zahlen x und y symetrisch sind
:param x: ein Element der Liste
:param y: ein Element der Liste
:return: True- wenn x und y symetrisch
False - sonst
... |
6,533 | 6afcb8f17f7436f0ae9fa3a8c2a195245a9801f1 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import numpy as np
class ZoomPanHandler:
"""
Matplotlib callback class to handle pan and zoom events.
"""
def __init__(self, axes, scale_factor=2, mouse_button=2):
"""
Default constructor for the ZoomPanHandler class.
Parameters... |
6,534 | 3852ff2f3f4ac889256bd5f4e36a86d483857cef | from pyspark.sql import SparkSession, Row, functions, Column
from pyspark.sql.types import *
from pyspark.ml import Pipeline, Estimator
from pyspark.ml.feature import SQLTransformer, VectorAssembler
from pyspark.ml.evaluation import RegressionEvaluator
from pyspark.ml.tuning import TrainValidationSplit, ParamGridBuild... |
6,535 | d292de887c427e3a1b95d13cef17de1804f8f9ee | import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
#led = 21
pins = [21, 25, 18]
# 0 1 2 3 4
names = ["First", "Second", "Third"]
for x in range(len(pins)):
GPIO.setup(pins[x], GPIO.IN, pull_up_down=GPIO.PUD_UP)
#GPIO.setup(led, GPIO.OUT)
while True:
input_state = 0
for i in ran... |
6,536 | 21ef8103a5880a07d8c681b2367c2beef727260f | import random
def take_second(element):
return element[1]
import string
def get_random_name():
name = ""
for i in range(random.randint(5, 15)):
name += random.choice(string.ascii_letters)
return name
imenik = [(777, "zejneba"), (324, "fahro"), (23, "fatih"), (2334, "muamer"), (435, "keri... |
6,537 | 93909ab98f1141940e64e079e09834ae5ad3995f | import requests
import time
import csv
import os
import pandas as pd
col_list1 = ["cardtype","username_opensea", "address", "username_game"]
df1 = pd.read_csv("profiles.csv", usecols=col_list1)
#
for j in range(0,len(df1) ): #usernames in opensea
print(j)
user=[]
proto=[]
purity=[]
... |
6,538 | ee57e6a1ccbec93f3def8966f5621ea459f3d228 | from distutils.core import setup
setup(
name='json_config',
version='0.0.01',
packages=['', 'test'],
url='',
license='',
author='craig.ferguson',
author_email='',
description='Simple Functional Config For Changing Environments'
)
|
6,539 | f60d02fb14364fb631d87fcf535b2cb5782e728f | from typing import Any, Dict
from django.http import HttpRequest, HttpResponse
from zerver.decorator import REQ, has_request_variables, webhook_view
from zerver.lib.response import json_success
from zerver.lib.webhooks.common import check_send_webhook_message, get_setup_webhook_message
from zerver.models import UserP... |
6,540 | 40d08bfa3286aa30b612ed83b5e9c7a29e9de809 | # -*- coding: utf-8 -*-
from euler.baseeuler import BaseEuler
from os import path, getcwd
def get_name_score(l, name):
idx = l.index(name) + 1
val = sum([(ord(c) - 64) for c in name])
return idx * val
class Euler(BaseEuler):
def solve(self):
fp = path.join(getcwd(), 'euler/resources/names.t... |
6,541 | 0069a61127c5968d7014bdf7f8c4441f02e67df0 | # Copyright 2021 QuantumBlack Visual Analytics Limited
#
# 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
#
# THE SOFTWARE IS PROVIDED "AS IS",... |
6,542 | 4f81eb7218fa1341bd7f025a34ec0677d46151b0 | from setuptools import find_packages, setup
NAME = 'compoelem'
VERSION = "0.1.1"
setup(
name=NAME,
packages=['compoelem', 'compoelem.generate', 'compoelem.compare', 'compoelem.visualize', 'compoelem.detect', 'compoelem.detect.openpose', 'compoelem.detect.openpose.lib'],
include_package_data=True,
versio... |
6,543 | b090e92fe62d9261c116529ea7f480daf8b3e84e | #!/usr/bin/python3
def square_matrix_simple(matrix=[]):
'''This function will compute the square root of all integers in
a matrix. '''
new_matrix = []
for index in matrix:
jndex = 0
new_row = []
while jndex < len(index):
... |
6,544 | 207bb7c79de069ad5d980d18cdfc5c4ab86c5197 | def slices(series, length):
if length <= 0:
raise ValueError("Length has to be at least 1")
elif length > len(series) or len(series) == 0:
raise ValueError("Length has to be larger than len of series")
elif length == len(series):
return [series]
else:
result = []
... |
6,545 | b3f72bc12f85724ddcdaf1c151fd2a68b29432e8 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
MQTT handler for Event subscriptions.
"""
import json
import time
import tornado.gen
import tornado.ioloop
from hbmqtt.mqtt.constants import QOS_0
from tornado.queues import QueueFull
from wotpy.protocols.mqtt.handlers.base import BaseMQTTHandler
from wotpy.protocol... |
6,546 | 829e23ce2388260467ed159aa7e1480d1a3d6045 | """I referred below sample.
https://ja.wikipedia.org/wiki/Adapter_%E3%83%91%E3%82%BF%E3%83%BC%E3%83%B3#:~:text=Adapter%20%E3%83%91%E3%82%BF%E3%83%BC%E3%83%B3%EF%BC%88%E3%82%A2%E3%83%80%E3%83%97%E3%82%BF%E3%83%BC%E3%83%BB%E3%83%91%E3%82%BF%E3%83%BC%E3%83%B3%EF%BC%89,%E5%A4%89%E6%9B%B4%E3%81%99%E3%82%8B%E3%81%93%E3%81%A... |
6,547 | 6ee71cf61ae6a79ec0cd06f1ddc7dc614a76c7b9 | import os
_basedir = os.path.abspath(os.path.dirname(__file__))
DEBUG = True
SECRET_KEY = '06A52C5B30EC2960310B45E4E0FF21C5D6C86C47D91FE19FA5934EFF445276A0'
SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(_basedir, 'app.db')
SQLALCHEMY_ECHO = True
DATABASE_CONNECT_OPTIONS = {}
THREADS_PER_PAGE = 8
CSRF_ENABL... |
6,548 | 253804644e366382a730775402768bc307944a19 | import unittest
'''
시험 문제 2) 장식자 구현하기
- 다수의 인자를 받아, 2개의 인자로 변환하여 함수를 호출토록 구현
- 첫번째 인자 : 홀수의 합
- 두번째 인자 : 짝수의 합
모든 테스트가 통과하면, 다음과 같이 출력됩니다.
쉘> python final_2.py
...
----------------------------------------------------------------------
Ran 3 tests in 0.000s
OK
'''
def divider(fn):
def wrap(*args):
o... |
6,549 | 0d37b6f0ea8854f9d4d4cd2ff235fa39bab7cc12 | import sys
def digit_sum(x):
sum = 0
while x != 0:
sum = sum + x % 10
x = x // 10
return sum
for i in sys.stdin:
test_num = int( i )
if test_num == 0:
break
count = 11
while digit_sum(test_num) != digit_sum(count * test_num):
count = count + 1
print('{... |
6,550 | bcc76e4dbcc191e7912085cbb92c5b0ebd2b047b | from datetime import datetime
from pymongo import MongoClient
from bson import ObjectId
from config import config
class Database(object):
def __init__(self):
self.client = MongoClient(config['db']['url']) # configure db url
self.db = self.client[config['db']['name']] # configure db name
de... |
6,551 | 326f1b5bee8f488382a76fcc5559f4ea13734f21 | from scrapy import cmdline
cmdline.execute("scrapy crawl rapo.com".split())
|
6,552 | e364ba45513167966fe50e31a01f552ccedec452 | from ethereum.common import mk_transaction_sha, mk_receipt_sha
from ethereum.exceptions import InsufficientBalance, BlockGasLimitReached, \
InsufficientStartGas, InvalidNonce, UnsignedTransaction
from ethereum.messages import apply_transaction
from ethereum.slogging import get_logger
from ethereum.utils import enco... |
6,553 | deaaf7620b9eba32149f733cd543399bdc2813a1 |
import os
import requests
import json
from web import *
from libs_support import *
from rss_parser import *
from database import *
class Solr_helper:
""" Ho tro He thong tu dong cap nhat du lieu - su dung post.jar de tu dong cap nhat du lieu moi vao he thong theo
tung khoang thoi gian nhat dinh """
de... |
6,554 | 268c36f6fb99383ea02b7ee406189ffb467d246c | import re
import requests
def download_image(url: str) -> bool:
img_tag_regex = r"""<img.*?src="(.*?)"[^\>]+>"""
response = requests.get(url)
if response.status_code != 200:
return False
text = response.text
image_links = re.findall(img_tag_regex, text)
for link in image_links:
... |
6,555 | d35d26cc50da9a3267edd2da706a4b6e653d22ac | import subprocess
class Audio:
def __init__(self):
self.sox_process = None
def kill_sox(self, timeout=1):
if self.sox_process is not None:
self.sox_process.terminate()
try:
self.sox_process.wait(timeout=timeout)
except subprocess.TimeoutExpir... |
6,556 | afe63f94c7107cf79e57f695df8543e0786a155f | def getGC(st):
n = 0
for char in st:
if char == 'C' or char == 'G':
n += 1
return n
while True:
try:
DNA = input()
ln = int(input())
maxLen = 0
subDNA = ''
for i in range(len(DNA) - ln + 1):
sub = DNA[i : i + ln]
if getG... |
6,557 | a8c59f97501b3f9db30c98e334dbfcffffe7accd | import simple_map
import pickle
import os
import argparse
import cv2
argparser = argparse.ArgumentParser()
argparser.add_argument("--src", type=str, required=True,
help="source directory")
argparser.add_argument("--dst", type=str, required=True,
help="destination directory")
ar... |
6,558 | 94560d8f6528a222e771ca6aa60349d9682e8f4b | from pig_util import outputSchema
@outputSchema('word:chararray')
def reverse(word):
"""
Return the reverse text of the provided word
"""
return word[::-1]
@outputSchema('length:int')
def num_chars(word):
"""
Return the length of the provided word
"""
return len(word) |
6,559 | e6bd9391a5364e798dfb6d2e9b7b2b98c7b701ac | # coding:utf-8
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from multiprocessing import Pool
"""
用户id,时间戳,浏览行为数据,浏览子行为编号
"""
names = ['userid','time','browser_behavior','browser_behavior_number']
browse_history_train = pd.read_csv("../../pcredit/train/browse_history_train.txt",header=None)
... |
6,560 | 146cae8f60b908f04bc09b10c4e30693daec89b4 | import imgui
print("begin")
imgui.create_context()
imgui.get_io().display_size = 100, 100
imgui.get_io().fonts.get_tex_data_as_rgba32()
imgui.new_frame()
imgui.begin("Window", True)
imgui.text("HelloWorld")
imgui.end()
imgui.render()
imgui.end_frame()
print("end")
|
6,561 | 31a5bf0b275238e651dcb93ce80446a49a4edcf4 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 11 13:25:03 2020
@author: Dr. Michael Sigmond, Canadian Centre for Climate Modelling and Analysis
"""
import matplotlib.colors as col
import matplotlib.cm as cm
import numpy as np
def register_cccmacms(cmap='all'):
"""create my ... |
6,562 | b9b113bdc5d06b8a7235333d3b3315b98a450e51 | import random
s = {1: 1, 2: 2, 3: 3, 4: 4, 5: 5}
t = True
while t:
a = random.randint(1, 10)
if a not in s:
t = False
s[a] = a
print(s)
|
6,563 | 10a7c1827abb8a87f5965453aa2d8f5e8b4914e5 | import matplotlib.pyplot as plt
def xyplot(xdata,ydata,title):
fname = "/Users/nalmog/Desktop/swa_equipped_cumulative_"+title+".png"
#plt.figure(figsize=(500,500))
plt.plot(xdata, ydata)
plt.ylabel('some numbers')
# plt.savefig("/Users/nalmog/Desktop/swa_equipped_cumulative_"+title+".png", format... |
6,564 | 1190e802fde6c2c6f48bd2720688bd9231b622e0 | """
PROYECTO : Portal EDCA-HN
NOMBRE : ZipTools
Descripcion : Clase utilitaria para descomprimir archivos ZIP.
MM/DD/YYYY Colaboradores Descripcion
05/07/2019 Alla Duenas Creacion.
"""
import zipfile
from edca_mensajes import EdcaErrores as err, EdcaMensajes as msg
from edca_logs.EdcaLogger... |
6,565 | 71503282e58f60e0936a5236edc094f1da937422 | from django.utils.text import slugify
from pyexpat import model
from django.db import models
# Create your models here.
from rest_framework_simplejwt.state import User
FREQUENCY = (
('daily', 'Diario'),
('weekly', 'Semanal'),
('monthly', 'Mensual')
)
class Tags(models.Model):
name = models.CharField(m... |
6,566 | b7038ad73bf0e284474f0d89d6c34967d39541c0 | from .auth import Auth
from .banDetection import BanDetectionThread
from .botLogging import BotLoggingThread
from .clientLauncher import ClientLauncher
from .log import LogThread, Log
from .mainThread import MainThread
from .nexonServer import NexonServer
from .tmLogging import TMLoggingThread
from .worldCheckboxStatus... |
6,567 | 6928ff58ddb97883a43dfd867ff9a89db72ae348 | from flask_sqlalchemy import SQLAlchemy
from flask_cors import CORS
import urllib
from flask import Flask
########################################################################################DataBase@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@2
#connection string
params = urllib.parse.quote_plus('Driv... |
6,568 | dc5b9600828857cc5ea434a7b010cd8aa2589d22 | from math import log2
from egosplit.benchmarks.data_structures.cover_benchmark import *
from egosplit.benchmarks.evaluation.utility import create_line
from networkit.stopwatch import clockit
# Analyse the result cover of a benchmark run
@clockit
def analyze_cover(benchmarks, result_dir, calc_f1, append):
if not app... |
6,569 | 94a84c7143763c6b7ccea1049cdec8b7011798cd | #!/usr/bin/python
#_*_ coding: utf-8 _*_
import MySQLdb as mdb
import sys
con = mdb.connect("localhost","testuser","testdB","testdb")
with con:
cur = con.cursor()
cur.execute("UPDATE Writers SET Name = %s WHERE Id = %s ",
("Guy de manupassant", "4"))
print "Number of rows updated: %d "% cur.... |
6,570 | b2c0ef4a0af12b267a54a7ae3fed9edeab2fb879 | import torch
import torch.nn as nn
from model.common import UpsampleBlock, conv_, SELayer
def wrapper(args):
act = None
if args.act == 'relu':
act = nn.ReLU(True)
elif args.act == 'leak_relu':
act = nn.LeakyReLU(0.2, True)
elif args.act is None:
act = None
else:
rais... |
6,571 | b984dc052201748a88fa51d25c3bd3c22404fa96 |
# import draw as p
# ако няма __init__.py
# from draw.point import Point
from draw import Rectangle
from draw import Point
from draw import ShapeUtils
if __name__ == '__main__':
pn1 = Point(9,8)
pn2 = Point(6,4)
print(f'dist: {pn1} and {pn1} = {ShapeUtils.distance(pn1,pn2)}')
rc1 = Rectangle(4... |
6,572 | 6c9f9363a95ea7dc97ccb45d0922f0531c5cfec9 | import re
_camel_words = re.compile(r"([A-Z][a-z0-9_]+)")
def _camel_to_snake(s):
""" Convert CamelCase to snake_case.
"""
return "_".join(
[
i.lower() for i in _camel_words.split(s)[1::2]
]
)
|
6,573 | fd41e6d8530d24a8a564572af46078be77e8177f | SQL_INSERCION_COCHE = "INSERT INTO tabla_coches(marca, modelo, color, motor, precio) VALUES (%s,%s,%s,%s,%s);"
SQL_LISTADO_COCHES = "SELECT * FROM tabla_coches;"
|
6,574 | 2ee4b31f880441e87c437d7cc4601f260f34ae24 | from sys import getsizeof
# using parenthesis indicates that we are creating a generator
a = (b for b in range(10))
print(getsizeof(a))
c = [b for b in range(10)]
# c uses more memory than a
print(getsizeof(c))
for b in a:
print(b)
print(sum(a)) # the sequence has disappeared
|
6,575 | 9376d697158faf91f066a88e87d317e79a4d9240 | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
This is a collection of monkey patches and workarounds for bugs in
earlier versions of Numpy.
"""
from ...utils import minversion
__all__ = ['NUMPY_LT_1_10_4', 'NUMPY_LT_1_11',
'NUMPY_LT_1_12', 'NUMPY_LT_1_13', 'NUMPY_LT_1_14',
... |
6,576 | 539523f177e2c3c0e1fb0226d1fcd65463b68a0e | # -*- coding: utf-8 -*-
from __future__ import print_function
"""phy main CLI tool.
Usage:
phy --help
"""
#------------------------------------------------------------------------------
# Imports
#------------------------------------------------------------------------------
import sys
import os.path as op
im... |
6,577 | 31b109d992a1b64816f483e870b00c703643f514 | def resolve_data(raw_data, derivatives_prefix):
derivatives = {}
if isinstance(raw_data, dict):
for k, v in raw_data.items():
if isinstance(v, dict):
derivatives.update(resolve_data(v, derivatives_prefix + k + '_'))
elif isinstance(v, list):
deriva... |
6,578 | 09850f0d3d295170545a6342337e97a0f190989a | import plotly.express as px
import pandas as pd
def fiig(plan):
df = pd.DataFrame(plan)
fig = px.timeline(df, x_start="Начало", x_end="Завершение", y="РЦ", color='РЦ', facet_row_spacing=0.6,
facet_col_spacing=0.6, opacity=0.9, hover_data=['Проект', 'МК', 'Наменование', 'Номер', 'Минут'],... |
6,579 | d261efa72e1ab77507a1fd84aa2e462c6969af56 | from django.shortcuts import render, Http404, HttpResponse, redirect
from django.contrib.auth import authenticate, login
from website.form import UserForm
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
from website.models import UserProfile
from website.form import UserForm
import pandas as ... |
6,580 | f8e6f6e1be6c4ea306b7770c918b97808a0765b2 | import random
import time
import unittest
from old import dict_groupby
class TestDictGroupBy(unittest.TestCase):
def setUp(self):
random.seed(0)
self.sut = dict_groupby
def generate_transaction(self):
return {
'transaction_type': random.choice(['a', 'b', 'c']),
... |
6,581 | 0229783467b8bcd0361baf6be07e3261f34220c7 |
from numpy.testing import assert_almost_equal
from fastats.maths.norm_cdf import norm_cdf
def test_norm_cdf_basic_sanity():
assert_almost_equal(0.5, norm_cdf(0.0, 0, 1))
def test_norm_cdf_dartmouth():
"""
Examples taken from:
https://math.dartmouth.edu/archive/m20f12/public_html/matlabnormal
s... |
6,582 | f14a8d0d51f0baefe20b2699ffa82112dad9c38f | no_list = {"tor:", "getblocktemplate", " ping ", " pong "}
for i in range(1, 5):
with open("Desktop/"+str(i)+".log", "r") as r:
with open("Desktop/"+str(i)+"-clean.log", "a+") as w:
for line in r:
if not any(s in line for s in no_list):
w.write(line)
|
6,583 | aa6464c53176be9d89c6c06997001da2b3ee1e5c | from django import forms
from .models import Diagnosis, TODOItem
class DiagnosisForm(forms.ModelForm):
class Meta:
model = Diagnosis
fields = ['name', 'Rostered_physician', 'condition', 'details', 'date_of_diagnosis', 'content']
class TODOItemForm(forms.ModelForm):
class Meta:... |
6,584 | 2fdbf418b5cec50ee6568897e0e749681efeef6b | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'find_result_window.ui'
#
# Created by: PyQt5 UI code generator 5.12.2
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_FindResultWindow(object):
def setupUi(self, FindResultW... |
6,585 | eb891341488e125ae8c043788d7264fff4018614 | #!/usr/bin/env python
from http.client import HTTPConnection
import pytest
from circuits.web import Controller
from circuits.web.client import Client, request
from .helpers import urlopen
class Root(Controller):
def index(self):
return "Hello World!"
def request_body(self):
return self.r... |
6,586 | c5b40b373953a2375eeca453a65c49bdbb8715f1 | '''import math
x = 5
print("sqrt of 5 is", math.sqrt(64))
str1 = "bollywood"
str2 = 'ody'
if str2 in str1:
print("String found")
else:
print("String not found")
print(10+20)'''
#try:
#block of code
#except Exception l:
#block of code
#else:
#this code executes if except block is executed
try... |
6,587 | bd0530b6f3f7b1a5d72a5b11803d5bb82f85105d | import numpy as np
import math
a = [
[0.54, -0.04, 0.10],
[-0.04, 0.50, 0.12],
[0.10, 0.12, 0.71]
]
b = [0.33, -0.05, 0.28]
# Метод Гаусса
def gauss(left, right, prec=3):
# Создаем расширенную матрицу
arr = np.concatenate((np.array(left), np.array([right]).T), axis=1)
print('\nИсходная матриц... |
6,588 | 68f8b301d86659f9d76de443b0afe93fd7f7e8c2 | # getting a sample of data to parse for the keys of the players
import requests
import xml.etree.ElementTree as ET
currentPlayerInfoUrl="http://stats.nba.com/stats/commonallplayers?IsOnlyCurrentSeason=1&LeagueID=00&Season=2015-16"
r=requests.get(currentPlayerInfoUrl)
if r.status_code == requests.codes.ok:
with open(... |
6,589 | 38f6700b283bdc68a0271cb3ec397ce72aa2de3c | # uncompyle6 version 3.2.4
# Python bytecode 2.7 (62211)
# Decompiled from: Python 2.7.15 (v2.7.15:ca079a3ea3, Apr 30 2018, 16:30:26) [MSC v.1500 64 bit (AMD64)]
# Embedded file name: filecmp
import os, stat
from itertools import ifilter, ifilterfalse, imap, izip
__all__ = [
'cmp', 'dircmp', 'cmpfiles']
_cache = {}
BU... |
6,590 | ac19ae96d8262cadd43314c29198fccbc008c1b5 | #!/usr/bin/env python
from __future__ import print_function, division, unicode_literals
import os
import sys
import json
import logging
import tempfile
import itertools
import traceback
import subprocess as sp
from os.path import basename
from datetime import datetime
from argparse import ArgumentParser, FileType
PRE... |
6,591 | 501b8a9307a1fd65a5f36029f4df59bbe11d881a | from LAMARCK_ML.data_util import ProtoSerializable
class NEADone(Exception):
pass
class NoSelectionMethod(Exception):
pass
class NoMetric(Exception):
pass
class NoReproductionMethod(Exception):
pass
class NoReplaceMethod(Exception):
pass
class ModelInterface(ProtoSerializable):
def reset(self):
... |
6,592 | 37804c92b69d366cc1774335b6a2295dfd5b98f3 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import json
import codecs
import Levenshtein
import logging
import random
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import cross_val_score
import time
from sklearn.model_selection import KFold
import numpy as np
import s... |
6,593 | cd0b55e163851344273ad020d434cc8662083d19 | import math
class Rank:
class Stats(object):
'''Holds info used to calculate amount of xp a player gets'''
post_likes = 0
post_dislikes = 0
comment_likes = 0
comment_dislikes = 0
usage = 0
class Interval(object):
'''A class representing an interval. It ... |
6,594 | fc5d0dd16b87ab073bf4b054bd2641bdec88e019 | def descending_order(num):
return int(''.join(sorted(str(num), reverse=True)))
import unittest
class TestIsBalanced(unittest.TestCase):
def test_is_balanced(self):
self.assertEquals(descending_order(0), 0)
self.assertEquals(descending_order(15), 51)
self.assertEquals(descending_order(1... |
6,595 | 1f3e20e7fe597a88cddacf6813250f1ede6c6ee0 | #!/usr/bin/python3
"""Prints the first State object from the database specified
"""
from sys import argv
import sqlalchemy
from sqlalchemy import create_engine, orm
from model_state import Base, State
if __name__ == "__main__":
engine = create_engine('mysql+mysqldb://{}:{}@localhost/{}'
... |
6,596 | d13f06afeac938fc2cf4d3506b3f68c6de9de210 | import cv2
img = cv2.imread('imgs/1.png')
pixel = img[100, 100]
img[100, 100] = [57, 63, 99] # 设置像素值
b = img[100, 100, 0] # 57, 获取(100, 100)处, blue通道像素值
g = img[100, 100, 1] # 63
r = img[100, 100, 2] # 68
r = img[100, 100, 2] = 99 # 设置red通道
# 获取和设置
piexl = img.item(100, 100, 2)
img.itemset((100, 100, 2), 99)
|
6,597 | 79f4ede16628c6fbf37dfb4fe5afb8489c120f5a | class Solution(object):
def lexicalOrder(self, n):
"""
:type n: int
:rtype: List[int]
"""
acc = []
self.backtrack(acc, 1, n)
return acc
def backtrack(self, acc, counter, n):
if counter > n:
return
elif len(acc) == n:
... |
6,598 | 37969899aa646f4cdd7a5513f17d26b334870f1b | import pymongo
import redis
import json
from time import time
user_timeline_mongodb = "mongodb://user-timeline-mongodb.sdc-socialnetwork-db.svc.cluster.local:27017/"
user_timeline_redis = "user-timeline-redis.sdc-socialnetwork-db.svc.cluster.local"
def handle(req):
"""handle a request to the function
Args:
... |
6,599 | 2c43ede960febfb273f1c70c75816848768db4e5 | a,b,c,y=4.4,0.0,4.2,3.0
print(c+a*y*y/b) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.