index
int64
0
1,000k
blob_id
stringlengths
40
40
code
stringlengths
7
10.4M
14,100
beb5392d30e4e9516e51d10981ca420936b64ed6
from rest_framework import serializers from . import models class CreateOrderItemSerializer(serializers.ModelSerializer): class Meta: model = models.OrderItem fields = '__all__' class OrderItemSerializer(serializers.ModelSerializer): drink = serializers.StringRelatedField() class Meta:...
14,101
d26c4d3f15ea6b5f38fc4d3e45795b4886ac7d67
''' Authors: Connor Finn, Josh Katz Summer 2020 Description: This script dictates a finate state machine that will be used to control he robot's actions and transitions between different operating modes. Each state exists as a separate file in the states directory. These states each have their own updat...
14,102
e03dbd7507474c80a0bf87b4d90abd0e4f94e968
# Copyright Contributors to the Amundsen project. # SPDX-License-Identifier: Apache-2.0 from abc import abstractmethod from typing import ( Iterator, List, Union, ) from amundsen_common.utils.atlas import AtlasCommonParams, AtlasTableTypes from amundsen_rds.models import RDSModel from amundsen_rds.models.column i...
14,103
0de66eefe392bc00f394fad8ff856a385bd68a65
import argparse from bs4 import BeautifulSoup from bs4.diagnose import diagnose from bs4.element import Tag from io import StringIO import requests import sys from xml.etree import ElementTree EDM_NAMESPACE = "http://docs.oasis-open.org/odata/ns/edm" EDMX_NAMESPACE = "http://docs.oasis-open.org/odata/ns/edmx" EDM_TAG...
14,104
7cd7e35cf5e6ccbe04013365b889afd24d886351
import pandas as pd import math from Record import Record class Iris: def __init__(self): columns = ["SepalLength", "SepalWidth", "PedalLength", "PedalWidth", "Classification"] self._data = pd.read_csv("iris.csv", names=columns) self._records = self.getRecordList() def getRecordList(s...
14,105
f1580afbfb45f8c1ba8c00ddec75b03e007f1a12
import pulsar, re client = pulsar.Client('pulsar://127.0.0.1:6650') consumer = client.subscribe(topic=['persistent://public/default/check-click', 'persistent://public/default/check-impression'], subscription_name='ew') while True: msg = consumer.receive() try: print("Received message '{}' id='{}'".fo...
14,106
0c6568b3f20c73727993ff62de08f0999544843f
# 12.23 # TLE class Solution(object): def openLock(self, deadends, target): """ :type deadends: List[str] :type target: str :rtype: int """ # 记录deadends dead = set() for d in deadends: dead.add(int(d)) # dp = [[[[10000 for c...
14,107
be689e386cc51ba6d94e0e24aa540b506e312373
from collections import Counter import numpy as np import matplotlib.pyplot as plt from core.tweet_reader import TweetReader import statistics import operator reader = TweetReader('data/need/full-day-need/09_02.csv', text_column=1, separator='|', encoding='utf8') # reader.add_file_content_to_corpus('data/need/full-d...
14,108
ac7a0c2aa6d6cf68fbaaf205a3908a28fce7d87c
import random, math def clamp_color(rgb): return map(rgb, clamp_value) def clamp_value(val): if val < 0: return 0 if val > 1.0: return 0.999 return val def clamp_circular(val): return val % 1.0 def sine(x): # compute sine x %= 6.28318531 if x > 3.14159265: x...
14,109
3853c674ce21e697a26a79d7f5837b5c395451f1
import sys freq = {} # frequency of words in text line = input() print(line.split()) for word in line.split(): freq[word] = freq.get(word,0)+1 print(freq[word]) words = freq.keys() print(words) for w in words: print ("%s:%d" % (w,freq[w])) # split is for taking words in place as a single one b...
14,110
84836e365d3e59372a3b85ed8a5e546206d4c9b3
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import smart_selects.db_fields class Migration(migrations.Migration): dependencies = [ ('jobportal', '0003_auto_20160313_0121'), ] operations = [ migrations.AlterField( m...
14,111
015afce36c219ff778bce3af2f866c4b0b39731f
import numpy as np from scipy.integrate import ode from scipy.optimize import curve_fit from lmfit import minimize, Parameters import json from tqdm import tqdm from bfmplot import pl from bfmplot import brewer_qualitative, simple_cycler, markers import bfmplot as bp #brewer_qualitative[6] = brewer_qualitative[1] co...
14,112
33df834116d7671605d001780a1784835a610f46
#immutable data structures, can be unpacked inform = ['Hi', 4, 'yay'] v1, v2, v3 = inform print(v1, v2, v3) one_elem_tuple = (4, ) #you need the comma print(one_elem_tuple)
14,113
6890ea0859c49f215e7d8e2929333a1dbf9b8568
# Importando pacotes # Import import urllib.request # From packages from bs4 import BeautifulSoup as bf4 # Obtenção de dados do ZAP def find_substring(substring, string): indices = [] index = -1 # Begin at -1 so index + 1 is 0 while True: # Find next index of substring, by starting search from i...
14,114
1b07cfd76a583d3605cd448998c678205ad89e91
from ef_common.take_screenshot import take_screenshot from hamcrest import assert_that, equal_to import settings from android.pages.evc.login_page import LoginPage from settings import UAT_Account from teacher_common.teacher_common_web_page import TeacherCommonWebPage from android.tests.abstract_base_android_testcase ...
14,115
39144f720bee1595a756be7b4b6563f797eaef32
import numpy as np #создали матрицу 10 на 10 #x = np.random.randint(100, size=(10,10)) #np.savetxt(delimiter=';',fname='ran.csv',fmt='%1.1i', X=x) y = np.loadtxt(delimiter=';',fname='ran.csv') #поиск минимального и максимального элемента и позиций x_minim = np.min(y) x_maxim = np.max(y) tmp_min = np.where(y ==x_minim...
14,116
a3db0710c7c46c635e99c2afaca1d108a9153cde
from django.contrib.auth import get_user_model from model_mommy import mommy from pos_app.account.models import Doctor from pos_app.category.models import Category, SubCategory from pos_app.factory.models import Factory from pos_app.payment.models import Payment, PaymentProduct from pos_app.product.models import Emba...
14,117
1d13316652cd60a909cb0bf5edc93fc0309f19fe
chichen1 = open('chicken.txt', 'r', encoding='utf-8') for line in chichen1: print(line, end="") chichen1.close() # 메모리에서 제거
14,118
a5c85c08965d7fad4f7d37c2ac95de0287dd901c
#!/usr/bin/python # coding: utf-8 import argparse import sys import Uploader my_parser = argparse.ArgumentParser( description='XSVF file processor.', epilog='Parameters can be in a file, one per line, using @"file name"', fromfile_prefix_chars='@') my_parser.add_argument( '-v', '--version', action...
14,119
44523d19990a173cc236fc5d821f9d59146c7177
class Solution(object): def findRelativeRanks(self, nums): """ :type nums: List[int] :rtype: List[str] """ numsStrs = [] for i in range(len(nums)): numsStrs.append(str(nums[i])+'-'+str(i)) numsStrs = sorted(numsStrs, lambda x,y: cmp(int(x.split("-...
14,120
04069fdae7dfec4ea3198462f7492e36b27b85aa
def halil(start, end): out = list() if start <= 1: start = 2 battal = [True] * (end + 1) for p in range(start, end + 1): if (battal[p]): out.append(p) for i in range(p, end + 1, p): battal[i] = False return out print(halil(1, 100...
14,121
c87ead78bd14ca7ec3d015fdaab4213591348bb9
""" Contains ShoppingList class """ from google.appengine.ext import db from google.appengine.api import memcache from model.listitem import ListItem from model.product import Product import logging import json class ShoppingList(db.Model): """ Model class for ShoppingList """ name = db.StringProperty() ...
14,122
ff99728a2f18831789a492aef5c3a598711874b1
""" Merge files that are devided out by range number into a single file. Author: Hayden Elza Email: hayden.elza@gmail.com Created: 2019-07-26 """ import os # Data Sources wd = os.path.dirname(os.getcwd()) west = os.path.join(wd, 'data/edited/TownshipsWest/') east = os.path.join(wd, 'data/edited/TownshipsEast/') so...
14,123
f090e0e880a100068d46815a45088a66bce1839d
import pygame import os ######################################################################################## pygame.init() #초기화(반드시 필요) #화면 크기 설정 screen_width = 640 #가로 크기 screen_height = 480 #세로 크기 screen = pygame.display.set_mode((screen_width, screen_height)) #화면 타이틀 설정 pygame.display.set_caption("pang pang")...
14,124
e418190dfcf9107c44d15c5aa2e3156e3be24cfe
from ecies.utils import generate_key from ecies import encrypt, decrypt import binascii import coincurve pub = '0227ffac7d33231086df84e12f0856c0e985c18d3daa2c94c7abcbff9a6aa8b258' priv = 'ee113297d1fb3c214722aadf59a3d94dff24264ffc5c34b78c903b36eb1aeca8' def enclave_dec(priv, bytes_data): # pub = '0227ffac7d332310...
14,125
860a86d141976a267867ddfc4195c2ab1f05b770
"""JWT Helper""" import json import time from jose import jwt def create_jwt(config, payload={}): with open(config["AssertionKeyFile"], "r") as f: assertion_key = json.load(f) header = { "alg": "RS256", "typ": "JWT", "kid": assertion_key["kid"], } _payload = { ...
14,126
263ac8e7ede2eba6a293300ee40329b0a9cb161f
import socket from crypto import CryptoBox class Client(CryptoBox): def __init__(self): CryptoBox.__init__(self) self.sock = None def connect(self, host, port, timeout=None): try: socket.setdefaulttimeout(timeout) self.sock = socket.create_connection(...
14,127
6967426cd26d29b34f6cfa0872b2b3c8f52d5659
"""Common test tools.""" import asyncio from unittest.mock import MagicMock, patch from dsmr_parser.clients.protocol import DSMRProtocol from dsmr_parser.clients.rfxtrx_protocol import RFXtrxDSMRProtocol from dsmr_parser.obis_references import ( EQUIPMENT_IDENTIFIER, EQUIPMENT_IDENTIFIER_GAS, LUXEMBOURG_EQ...
14,128
fd839fba65c1f49d57ce7c956cf7c8980fdeb9d2
#!/usr/bin/env python3 # -*- coding: u8 -*- # File : config.py # Author : Hai-Yong Jiang <haiyong.jiang1990@hotmail.com> # Date : 26.01.2020 # Last Modified Date: 20.02.2020 # Last Modified By : Hai-Yong Jiang <haiyong.jiang1990@hotmail.com> import yaml from torch import optim from...
14,129
27665cd1f4986463d2ae3523a6df2f85e1fcf7f1
number = 1 number2 = 1.0 getattr = 'こんにちは' is_ok = True print(number, type(number)) print(number2, type(number2)) print(getattr, type(getattr)) print(is_ok, type(is_ok)) print(2 > 1) print(1 < 1) print(3 > 4) print(5 * 2) print('テスト・テスト')
14,130
9e7eaa110c52651c1bcc572d79e2cdd66002833a
from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from django.utils.translation import ugettext as _ from accounts.models import UserProfile from accounts.widgets import CalendarWidget class NewUserForm(UserCreationForm): email = forms.Email...
14,131
5f5d5c2c3c628ef80f7a37d07b726c2007e96f9d
# Author: Nimesh Ghelani based on code by Mark D. Smucker from collections import defaultdict class Judgement: def __init__(self, query_id: str, doc_id: str, relevance: int): self.query_id = query_id self.doc_id = doc_id self.relevance = relevance def key(self): return self.q...
14,132
b030d535f2d26df09d3dc341292e37efa04ef958
#!/usr/bin/env python3 import sys import time def timer() -> None: try: start_time = time.perf_counter() while True: seconds = int(time.perf_counter() - start_time) clock = f"{int(seconds / 60):0>2}:{int(seconds % 60):0>2}" sys.stdout.write("\r") sy...
14,133
902b758c274fc2c0fa579a3020ba38785023b175
# This file is part of Tryton. The COPYRIGHT file at the top level of # this repository contains the full copyright notices and license terms. from trytond.i18n import gettext from trytond.pool import PoolMeta, Pool from trytond.modules.party.exceptions import EraseError class Replace(metaclass=PoolMeta): __nam...
14,134
9f1320843159024ca4b6c42ea25d24ce973bd6d1
language = ['PYTHON'] languages = ['PYTHON','C','C++','JAVA','PERL'] print(language) print(languages) print(languages[0:3]) print(languages[1:4]) print(languages[2]) languages[2] = 'C#' print(languages[2]) print(languages[-1]) print(languages[-2:-1])
14,135
f61b35dd34444575689b5b53bb5384fa7cfdd027
#!/usr/bin/python import sys ''' **UNDERSTAND THE PROBLEM** Function returns the number of ways (permutations) Cookie Monster can eat n cookies Calculating permutations usually == recursion Recursive base case: When amount of cookies to eat equals 0 Edge case: negative numbers (return 0) For 5 cookies in jar (13 ...
14,136
30348139072d39167b453cc668788875773477c7
import camera from machine import UART import machine led = machine.Pin(4, machine.Pin.OUT) machine.sleep(5000) led.on() uart = UART(1, 9600) # init with given baudrate uart.init(9600, bits=8, parity=None, stop=1) # init with given parameters camera.init() buf = camera.capture() camera.deinit() ...
14,137
389ec221ba8a57dc63e8b0d5b670158100358312
#!/usr/bin/python import RPi.GPIO as GPIO import time # set the GPIO mode GPIO.setmode(GPIO.BCM) # set pin 18 for output GPIO.setup(18, GPIO.OUT) # output to pin 18 GPIO.output(18, True) # sleep for one second time.sleep(1) # turn off output for pin 18 GPIO.output(18, False) # gpio cleanup GPIO.cleanup()
14,138
7e2a2186150daa48076851e486d1a97422d0c7f6
import itertools class Game(): def __init__(self): self.Actions = {} self.numActions = 0 self.Start = None self.Value = None self.Goal = None self.MovesLeft = None self.TotalMoves = None def setup(self): self.Goal = int(input("What is the goal nu...
14,139
21531a4a4b034cbe4df9bb7d362bb6e93768363b
''' Integers in each row are sorted in ascending from left to right. Integers in each column are sorted in ascending from top to bottom. [ [1, 4, 7, 11, 15], [2, 5, 8, 12, 19], [3, 6, 9, 16, 22], [10, 13, 14, 17, 24], [18, 21, 23, 26, 30] ] start from the top right corner, if target is smaller...
14,140
4755c7ce368c36f194361c564fa22a93790c2f57
def solution(cookie): N = len(cookie) best = 0 lsum, rsum = 0, sum(cookie) for m in range(N): lsum += cookie[m] rsum -= cookie[m] a, b = lsum, rsum pa, pb = 0, N-1 while pa <= m and m+1 <= pb: if a == b: best = max(best, a) ...
14,141
cf8f7bf7c31a5c747debf539f154af81477da888
from rest_framework import routers from .views import EnergyTransductorViewSet app_name = "transductors" router = routers.DefaultRouter() router.register(r'energy_transductors', EnergyTransductorViewSet) urlpatterns = []
14,142
13affee18c2d110e8d3878c138350b55ee94b394
# Returns index of x in arr if present, else -1 def binarySearch(arr, l, r, x): # Check base case if r >= l: mid = l + (r - l) / 2 # If element is present at the middle itself if arr[mid] == x: return mid # If element is smaller than mid, then it can only # be...
14,143
254766fa330eebbaf52327c04f345b30352ad880
yd = float(91.44) # 정수가 아닌 실수 자료형 inch = float(2.54) print("2.1yd = ",round(yd*2.1,1), end="cm\n") print("10.5in = ",round(inch*10.5,1), end="cm\n") #소수 자리수 정해주기 round(value,digit) digit만큼 표시
14,144
9bb359ebd2e94484bd756cac995437f68a4118e7
from rolls import Roll from players import Player import random def print_header(): print(f"-------------------------------------------------------") print(f" Welcome to") print(f" Rock, Paper, Scissors") print(f"--------------------------------------------...
14,145
fcac3411475e8a9c5bed870eafaf8e23c79f9445
#!/usr/bin/env python3 __author__ = 'Ron Li' class Sha224: """ A class to calculate SHA224 """ """ Initialize table of round constants: first 32 bits of the fractional parts of the cube roots of the first 64 primes 2..311 """ k = (0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0...
14,146
019fa6a0d5f46f89452fe3c61297e3776f52cf51
import math import sys class Problem(): def __init__(self): self.mu_values = None self.lattice_count_cache = { } self.coprime_count_cache = { 1 : 0 } def solve(self): assert(self.get(10**6) == 159139) for n in [3141592653589793]: print(n, '=>', self.get(n)) ...
14,147
5a86c33cf59b82f0e366e216313239582f746c72
#!/usr/bin/env python # -*- coding: utf-8 -*- import numpy as np ## 我们现有1,2,5,10面值的硬币.当我们有M元时,解出最小数目的硬币组合. coin = [1, 2, 5, 10] def take_coins(m): tc = np.array([0, 0, 0, 0]) tc return tc if __name__ == '__main__': List1 = [1, 2, 3, 4] List2 = [5, 6, 7, 8] ll = [] for i,j in zip(List1,...
14,148
298f64ad7df9488d678a24d5ab1c67dd445a3810
# -*- coding: utf-8 -*- """ Created on Thu Feb 20 12:32:49 2020 @author: combitech """ from sklearn.preprocessing import LabelBinarizer from tensorflow.keras.callbacks import ModelCheckpoint, CSVLogger from tensorflow.keras.layers import Input, Dense, Conv2D, Flatten, Activation from tensorflow.keras.optimizers import...
14,149
4ac942b0285eb4ca615375cc51d9be1adcd8e9b4
from django.shortcuts import render from partidos.models import Partido def ver_partidos(request): partidos = Partido.objects.all().order_by('fecha') return render(request,'partidos/ver_partidos.html',{ 'partidos':partidos })
14,150
a64ad93762ffc97af7c5d620afcc5f7223b1bfee
# Generated by Django 2.2 on 2019-05-02 08:58 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('web', '0056_auto_20190418_1437'), ] operations = [ migrations.AddField( model_name='article', name='storage_temperatur...
14,151
6b3b6bd5ac52bede00bbf02fa672ab8ce019556b
#!/bin/env python ### Submit jobs using NtupleUtils.py, then check jobs' statuses every 30 seconds. ### When jobs are done, automatically proceed to the next step in the sequence ### MC: hadd --> normalize --> hadd-final ### Data: hadd --> skim --> hadd-final --> remove-duplicates import os, sys, subprocess import...
14,152
77b52cb4c9f9cad6559818dc2a5cb866515bbdca
lines_nmbr = int(input()) longest_intersection = set() for el in range(lines_nmbr): first_set, second_set, intersection = set(), set(), set() first_range, second_range = input().split('-') first_start, first_end = first_range.split(',') second_start, second_end = second_range.split(',') first_start...
14,153
f8545dcc435f8f9a921d725b92d4b0bb82694efc
#Program to print product of two numbers is odd or even N1,N2=map(int,input().split()) product=N1*N2 if((product%2)==0): print("even") else: print("odd")
14,154
8cedaf0ff401cbf273e5c54f84201c8b54a599de
import numpy as np from .body import Body from copy import deepcopy from collections import defaultdict from .client import BulletClient class BodyCache: def __init__(self, urdf_ds, client_id): self.urdf_ds = urdf_ds self.client = BulletClient(client_id) self.cache = defaultdict(list) ...
14,155
ea46c812f76b2988b43fcf384aee16babcdce38c
# -*- coding: utf-8 -*- def compress_coordinate(elements: list) -> dict: """Means that reduce the numerical value while maintaining the magnitude relationship. Args: elements: list of integer numbers (greater than -1). Returns: A dictionary's items ((original number, compressed n...
14,156
a78e65ebd58ceb4a5997895830da386cf6f57c7f
import os import json import sys import sqlite3 import requests import netweet.collection.utils as utils # fix class Collector: """Class used to collect tweets using the Twitter API. """ def __init__(self): self.number_apps = None self._keys = None self._secret_keys = None s...
14,157
ccc80c49c27ad3a6b2d9d943cd8688b14d30a18c
# Copyright 2016 Intel Corporation # # 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 to in wri...
14,158
ba99e6e8f9f2fe2b2ae4777e732d9dc96e18973e
import openpyxl import os #To create directory in windows if one doesnt exists #outPath = "C:\\Users\\syede\\Downloads\\SeleniumOutFiles" #if not os.path.isdir(outPath): # os.makedirs(outPath) ''' os.path.dirname(os.path.dirname(__file__))+"\\testCases\\testData\\loginData.xlsx" inFileName = ".\\testData\\loginD...
14,159
fcefb788c2f8da6c3d0a4a677a3d93b8967306e1
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. # # 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 appli...
14,160
59fbdd01e0f7e5c3dd20508b05dfb217a73acb61
import requests class Equity(object): def __init__(self, ticker, api_key=None): self.api_key = api_key or QUANDL_API_KEY self.host = 'https://www.quandl.com/api/v3/datatables/SHARADAR/SF1.json' self.params = {'api_key': self.api_key, 'ticker': ticker, 'dimension': 'MRY', 'qopts.latest': ...
14,161
98b947b7ea5817aa02c52b7a3ae8943a22f4905f
import urllib.request import urllib.parse url = 'https://movie.douban.com/typerank?type_name=%E5%8A%A8%E4%BD%9C&type=5&interval_id=100:90&action=&' headers={ 'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.146 Safari/537.36' } page = int(input('请输入要查看的页码; '))...
14,162
67d323f53d203ec0eff8fc87325c2caa27587c76
# -*- coding: utf-8 -*- from odoo import models, fields, api class WeightType(models.Model): _name = 'weight.type' _inherit = ['mail.thread', 'mail.activity.mixin'] _description = "WeightType" name = fields.Char('Size',required=True) note = fields.Char('Note') active=fields.Boolean(defau...
14,163
b67a80451a68ca4ac17a419124734e86d7f85eb9
from CommonFunctionality import CommonFunctionality from CallRecording import CallRecording class CallRecordingPage(object): """Module for all the Call Recording""" def __init__(self, browser): self.common_func = CommonFunctionality(browser) self.call_recording = CallRecording(browser) ...
14,164
0679cab0e70559e955782a5ae8251c8ab3a4d2cc
import os os.system('cls') print("******** Suma de dos numeros ********") numero1 = float(input("Ingrese el primer numero: ")) numero2 = float(input("Ingrese el segundo numero: ")) resultado = numero1 + numero2 print("El resultado de la suma de los numeros es: ", resultado)
14,165
1bf29301fc32b57c8bbf6fe9a0e4460267498a75
import cv2 from .rules import * from .loader import * from .model_renderer import show, colorize, parse_palette, parse_sinks from .osc import OSCSink, PrintSender from argparse import ArgumentParser parser = ArgumentParser(prog="Wireworld Composer", description=""" Compose sequences using wireworld simulations. Check ...
14,166
44a6fc9c4fc965e61e0b0a5ee63e4f3a004fb8c7
"""Randomly pick customer and print customer info""" # Add code starting here # Hint: remember to import any functions you need from # other files or libraries
14,167
2cfc97f4251d3bc70328edd596d9ff05944beecf
from django.core.urlresolvers import reverse from example.models import Car from example.tests.utils import filter_models, BaseTestCase class AggregatesAPITestCase(BaseTestCase): def setUp(self): super().setUp() self.car_api_url = reverse('car-list') def test_count(self): results = ...
14,168
e6afd09f511f7c9193e9e8fdad7c570fabb5cf44
""" ============================ author:Administrator time:2019/7/24 E-mail:540453724@qq.com ============================ """ user = int(input("请输入数值:")) if user%2 == 0: print(True) else: print(False)
14,169
36de82fdedeeafd3053f3dcde0c13ce273c41951
# coding: utf-8 import zerorpc import logging logging.basicConfig(level=logging.INFO) class CentralRPCClient: """the rpc client to connect server run on central""" def __init__(self, endpoint): self.endpoint = endpoint self.client = None def start(self): logging.info('starting a...
14,170
227904d1e59082d65ba972f04636f576057c2eb2
from demo import CTPN import numpy as np import sys,os import glob import mahotas import shutil import matplotlib.pyplot as plt from PIL import Image import tensorflow as tf import os.path as ops import numpy as np import cv2 import argparse import matplotlib.pyplot as plt try: from cv2 import cv2 except ImportErr...
14,171
cd2cc102abb7a8aa3a5f33967103d8c5e6d7dbac
#!/usr/bin/env python3 """ Tutorial Lesson 4 ================= This is the fourth tutorial arrowhead program. The previous lessons introduced all of the baisc concepts of arrowhead. Now we'll look at how one can work with flow state. As established previously, the first argument of each step function refers to a ste...
14,172
ca7ca4bbe546d5efc33e256eb6bd516a45be0cd9
from sklearn.datasets import load_iris from sklearn.model_selection import cross_val_score from sklearn.neural_network import MLPClassifier if __name__ == "__main__": X, y = load_iris(return_X_y=True) # MLP stands for multi-layer perceptron. clf = MLPClassifier(solver="sgd", random_state=1) print(cro...
14,173
6d5ea44f7e58ef1f7044c8fc2fcc2e11204406fd
print(type(5))
14,174
82575b41353e9d60ff71ed4398c7ecbe69b964f8
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Aug 13 13:56:41 2019 @author: lab """ import os import h5py import numpy as np import torch from pathlib import Path from tools.loggers import call_logger #from tools.loggers import call_logger #logger = utils.get_logger('UNet3DPredictor') import...
14,175
dd9395876a1f3492e411579eb90f09ae5e6d3c77
# resides at $HOME/.ipython/profile_default/ipython_config.py from pathlib import Path import logging _logger = logging.getLogger(Path(__file__).stem) _logger.info('disabling parso logging') logging.getLogger('parso').setLevel(level=logging.WARNING)
14,176
80875f0cf4ea88bc6d3e9a2c9cfbfe4e9b454d0e
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.constant.ParamConstants import * class AlipaySecurityRiskHufuAuthQueryModel(object): def __init__(self): self._code = None self._policy = None self._serial = None @property def code(self): retu...
14,177
d7fafd7c0af34cd9d6c03048774b7b421ece7c5c
#!/usr/bin/env python # coding: utf-8 # In[2]: from keras.models import Sequential from keras.layers import Dense import numpy import pandas as pd # In[5]: import xgboost as xgb from sklearn.metrics import mean_squared_error import pandas as pd import numpy as np # In[3]: train = pd.read_csv("C:/Users/TheUnl...
14,178
b1f4f120fdf58f5f6f84cacec9633ba00fbcfa14
def f1(): print("mod1 f1") def f2(): print("mod1 f2ß")
14,179
a7466e8cb47b35c216abb0edbd8b8566fe6362aa
from django.shortcuts import render from django.http import HttpResponse from django.shortcuts import render from django import template # Create your views here. def home(request): return render(request, 'templates/index.html') def hello(request): return HttpResponse(u'Hellow World! from hello', content_ty...
14,180
53225f429cd26531f22ada0cd1c6890d27b0e534
from django.urls import path from . import views urlpatterns = [ path('', views.dashboard,name='test'), # path('downloadimage/<str:imageid>/$', views.download_image, name='download_image'), path('filter/<int:id>/', views.filter,name='filter'), path('mapview', views.mapView,name='mapview'), path(...
14,181
20668303321637d3328bff1a625f9a906a603285
print "hola mundo" print 5 + 3.45
14,182
8e573eb9d016997bff577101f853deeb0557e3ae
""" Class for the score table: Marker. Attributes: __level: in str we put the name "Level" and then we attribute the value 0 as integer. __alive: in str we put the name "Alive" and then we attribute the value 0 as integer. __saved: in str we put the name "Saved" and then we attribute the value 0 as int...
14,183
86a6769a9470126f0a633b1719b2bc751641941c
DEBUG = True DEVELOPER_KEY = "AI39si5pbWC1StZw1ughtM2KuK4XORJVds7wl_QiYZnW-wsiyLr8oeX3Let3oCvQdHBGf8zee_FUudLzeEvorouufUZbuWhWtg"
14,184
b5a12618cb7da12b43204336cbd0ab900eb82976
from pkg import t_1 t_1.prt('')
14,185
eefe616c1f8169348369d8950d93894cfd1ffb4e
import turtle t = turtle iterations = input("Enter the number of generations: ") # type in the string iterations = int(iterations) startingLen = 500 # length of gen0 line # pick up the pen and move the turtle to the left t.up() t.setpos(-startingLen*1/2, 0) t.speed(0) dragon = 'F' # dragon = 'FRFRF' # dragon sn...
14,186
b8d704d33c8430706319aff1590eb560e48c0eea
#!/usr/bin/env python # coding: utf-8 # In[1]: from sqlalchemy import create_engine import psycopg2 import pandas as pd import datetime #datos hostname = os.getenv("pc_vl_ip") username = os.getenv("pc_vl_username") password = os.getenv("pc_vl_pass") tabla = '"ADJU"' update = "UPDATE public.""{0}"" SET vers = '{1}...
14,187
34d1ebfd2d1dce2db3bae1bcba300fd7c20f2425
from email import encoders from email.mime.base import MIMEBase from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart import smtplib import Config import ExceptionManager import datetime exceptionFileName = "Email.py" class Email: def __init__(self, toaddr): self.fromaddr = C...
14,188
234441a58357716f8660cff04545054fe0d9ff5d
#!/usr/bin/env python # Simple script to create ebs snapshots for volume list and cleanup of snapshots after n of days import boto from boto import ec2 from datetime import datetime from datetime import timedelta now = datetime.now() today = now.date() #Definitions num_of_days_to_keep=13 volume_list = { 'portaldata'...
14,189
eeb5e862d8cf48ef7d0bc265a2d6182f30e7d0b1
from rest_framework import pagination class CustomPaginator(pagination.PageNumberPagination): page_size = 3
14,190
e8e765147fd52782597416f303bfa095a7c080bd
import os from cs50 import SQL from flask import Flask, flash, jsonify, redirect, render_template, request, session from flask_session import Session from tempfile import mkdtemp from werkzeug.exceptions import default_exceptions, HTTPException, InternalServerError from werkzeug.security import check_password_hash, ge...
14,191
62407594e47a41365fcb5add072a0d7bb1c3cf59
class A: name="a" def __init__(self,name=None): self.name=name def Question25(): a=A() a.name="hhh" print(a.name,A.name) b=A("bbb") print(b.name,A.name) Question25()
14,192
f4cb071c64782c8d405747f0e5a6615a4b14c83f
import numpy as np # Parameters trials = 100000 n_bits = 120 n_patterns = [12, 24, 48, 70, 100, 120] zero_diagonal = False def generate_patterns(n_bits, n_pattern): size = (n_bits, n_pattern) p = np.random.randint(2, size=size) p_transform = 2 * p - 1 return p_transform def weight(x, i, j): if ...
14,193
1eef3da125d8564ea13f53a1a8183249280cde61
n,m=map(int,input().split()) a=[list(input()) for _ in range(n)] b=[list(input()) for _ in range(m)] r=n-m+1 print('Yes' if any([all([a[x//r+y//m][x%r+y%m]==b[y//m][y%m] for y in range(m**2)]) for x in range(r**2)]) else 'No')
14,194
53a8d362db3f69122f1d6f2cc654835efa803f46
from api.util.utils import Logger from api import dao, const from api.web import config import numpy as np class KGraphData: def __init__(self, all_rows): self.id_gen = 0 self.all_rows = all_rows self.nodes = [] self.links = [] self.category = {"title": "论文", "author": "作者...
14,195
0003bf8cf2e21f6164c1b7d4270a39830041a744
import maya.cmds as cmds import glTools.utils.stringUtils import glTools.utils.surface def loadPlugin(): """ Load glCurveUtils plugin. """ # Check if plugin is loaded if not cmds.pluginInfo('glCurveUtils', q=True, l=True): # Load Plugin try: cmds.loadPlugin('glCurveUti...
14,196
8e3e772353bc72691c50744cd865617e6d2eaa33
n = int(input()) a = [int(input()) for _ in range(n)] left = [a[0]] right = [a[-1]] for i in range(1, n): left.append(max(left[i-1], a[i])) right.append(max(right[i-1], a[n-i-1])) right = right[::-1] print(right[1]) for i in range(1, n-1): print(max(left[i-1], right[i+1])) print(left[-2])
14,197
c207f1008c18e147f9aa9e9131501fffb540b272
from utils.utils import capital import spacy import pandas as pd class NeExtractor(): def __init__(self): self.ne_type = ['ORG', 'PERSON', 'LOC'] self.sp = spacy.load('en_core_web_sm') pass def extract(self, cluster: pd.DataFrame): rawtext = " ".join(cluster.description) ...
14,198
28d74701a8e292e162dff711f8f705120fe32a26
""" You are at a birthday party and are asked to distribute cake to your guests. Each guess is only satisfied if the size of the piece of cake they’re given, matches their appetite (i.e. is greater than or equal to their appetite). Given two arrays, appetite and cake where the ithelement of appetite represents the ith ...
14,199
5db59231af3b2240f873956fd28aace748b90e5d
import data.data_fetcher import device import time import Queue import threading my_data_list = data.data_fetcher.get_pod_routers([1,2,3,4,5,6,7,8,9],[1,2,3,4]) my_data_list = my_data_list + data.data_fetcher.get_pod_switches([1,2,3,4,5,6,7,8,9],[1]) my_device_list = [] for i in my_data_list: my_device_list.appe...