index
int64
0
1,000k
blob_id
stringlengths
40
40
code
stringlengths
7
10.4M
995,600
5d8a43f74f469b3960819c91e4706406b7dfc94d
from google.auth import credentials from google.auth import environment_vars from google.cloud import storage import logging import os import yum import yum.config import yum.Errors import yum.plugins from yum.yumRepo import YumRepository URL_SCHEME = 'gs://' __all__ = ['requires_api_version', 'plugin_type', 'COND...
995,601
2a2a958a917453f5f6827febeebf6106303a8577
#!/usr/bin/python import json from subprocess import call dirs = json.loads('<%= node["mirror"]["directories"].to_json %>') for _from in dirs.keys(): full_from = "<%= node['mirror']['from'] %>/" + _from call(["rsync", "-avz", "--delete", full_from, "<%= node['mirror']['to'] %>"])
995,602
7a48b1427da5469940ee7ad8148d984c13edf690
# -*- coding: utf-8 -*- a = float(input()) b = float(input()) print("MEDIA = %.5f" % float(((a*3.5)+(b*7.5))/11))
995,603
30edc9fa27f58f7962d3c35726ae80d2e5af0343
#!/usr/bin/env python # 5000 IRC Bot - Developed by acidvegas in Python (https://acid.vegas/trollbots) ''' Requirements * Python (https://www.python.org/downloads/) Note: This script was developed to be used with the latest version of Python. Information: This bot requires network operator privledges in order to u...
995,604
c0db339bd7bfa1b873c603d9f6d9395e88be645a
def vect_gender(data:str): col_options = {"Male": 0, "Female": 1, "Other": 2} if(data in col_options.keys()): return col_options[data] # else: # return 3 def vect_relevent_experience(data:str): col_options = {"No relevent experience": 0, "Has relevent experience": 1} return co...
995,605
c2627a1e9960b4ad3e4928406614c6c74ae6a150
from bpy.types import Panel from . import props class MeshConstraintsPanelBase(Panel): bl_space_type = "VIEW_3D" bl_region_type = "UI" bl_category = "Constraints" class MeshConstraintsPanelMain(MeshConstraintsPanelBase): bl_label = "Mesh Constraints" bl_idname = "MESH_CONSTRAINTS_PT_MAIN" ...
995,606
cb8631eeb1728b90ccb406700f344800a433ed4d
# Generated by Django 3.1.4 on 2021-01-23 18:35 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('web', '0002_auto_20201230_2138'), ] operations = [ migrations.RenameField( model_name='contact', old_name='firstname...
995,607
9fc65052e5506be5a6da8dcb26f10a20ed46c07c
import copy import json import os import time import urllib.request from typing import Any, Dict, List, Tuple, Union import numpy as np from scipy.optimize import linprog global penguin_url, headers penguin_url = "https://penguin-stats.io/PenguinStats/api/" headers = {"User-Agent": "ArkPlanner"} gamedata_langs = ["e...
995,608
6cacec9e724cbaebe90e8664ea36c16d595b20f0
#second python print("this is my second python")
995,609
769910e9b4f83fcd096faecd6c534b324907bcbd
# Given a string, your task is to count how many palindromic substrings in this # string. # # The substrings with different start indexes or end indexes are counted as # different substrings even they consist of same characters. # # Example 1: # # Input: "abc" # Output: 3 # Explanation: Three palindromic strings: "a"...
995,610
556899cd3e358f6d93caed2b02fb7fc57be521f8
from pyston.utils import LOOKUP_SEP from pyston.filters.filters import Filter from pyston.filters.utils import OperatorSlug from pyston.filters.exceptions import OperatorFilterError from pyston.filters.managers import BaseParserModelFilterManager class BaseDynamoFilter(Filter): allowed_operators = None def ...
995,611
75373f24ca4bc660608670622408f97d1c5a8d7c
num = int(input('enter num: ')) if num < 10 and num >=0: print ('mardod') elif num >=10 and num <=20: print ('gabol') elif num >20: print ('mare than 20!') else: print ('error!')
995,612
38218037ffa1d68a9b7cd97a697cd1193ff466d5
import sys from queue import PriorityQueue from peers import PeersHandler from torrent_client import TorrentClient def download_torrent(torrent_file_path): s_memory = PriorityQueue() peer_handler = PeersHandler(torrent_file_path) torrent_client = TorrentClient(1, "Main_Torrent_Process", peer_handler, s_m...
995,613
5c318d679bac6044a80c9ad7766b35354080299a
# -*- coding: utf-8 -*- from django.conf import settings from djmail import template_mail import premailer import logging # Hide CSS warnings messages if debug mode is disable if not getattr(settings, "DEBUG", False): premailer.premailer.cssutils.log.setLevel(logging.CRITICAL) class InlineCSSTemplateMail(tem...
995,614
cb1900d0a0fce23dce50e47ee92e449f9b51a115
def is_leap_year(inYear): ''' Takes any year and reports if given year is a leap year. Leap years are on every year that is evenly divisible by 4 except every year that is evenly divisible by 100 unless the year is also evenly divisible by 400 ''' if not inYear % 400: return True elif not inYear %...
995,615
1a29a9ce42eade39909ba0611eb5dac2d49d2ae7
#!/usr/bin/python ''' Priority queue with random access updates ----------------------------------------- .. autoclass:: PrioQueue :members: :special-members: ''' #----------------------------------------------------------------------------- class PrioQueue: ''' Priority queue that supports updating pr...
995,616
3821a62403b56de5abac6e3dcf94a35de8d78672
"""Unit tests for database.py.""" # standard library from pathlib import Path import unittest from unittest.mock import MagicMock from unittest.mock import sentinel # first party from delphi.epidata.acquisition.covid_hosp.test_utils import TestUtils # py3tester coverage target __test_target__ = 'delphi.epidata.acqui...
995,617
acb042bfe9a1bc9617611b32794c00c71efafeff
import datetime import logging from calendar import timegm from importlib import import_module from django.conf import settings from django.contrib.auth import SESSION_KEY, get_user_model from django.utils import timezone from jose import jwk, jwt from jose.jwt import JWTClaimsError, JWTError from social_core.exceptio...
995,618
31ecee0ce439fa7e49910c48a47227b9939be79d
import unittest import os, signal, subprocess from detection_engine_modules.Sniffer import Sniffer # # Sniffer module testing file. # # Black box testing class bb_SnifferTest(unittest.TestCase): def test_init__no_arg(self): ''' Testing the module's constructor. Input - no argument. ...
995,619
4e9773e133a58362a941b90222b74c3961157d28
from django.urls import path from rest_framework.urlpatterns import format_suffix_patterns from fxaccount import views urlpatterns = [ path('<int:user>', views.FxAccountView), path('<int:user>/<int:pk>', views.AlterFxAccount), path('transfer', views.FxAccountTransferViews.as_view()), path('deposit/<i...
995,620
3dc98b0fc0f0cc9d410630439ccb4976ea7e4b86
"""JSON implementations of logging records.""" # pylint: disable=no-init # Numerous classes don't require __init__. # pylint: disable=too-many-public-methods,too-few-public-methods # Number of methods are defined in specification # pylint: disable=protected-access # Access to protected methods allowed in p...
995,621
7aff203e7c847072bba376fc5271dc9e88d3b253
# -*- coding: utf-8 -*- S1 = 72 S2 = 85 r = 100*(S2-S1)/S1 #print('小明的成绩提高了r%') print('xiao ming score increased by %0.2f %%' % r) # %0.2f相当于保留小树点后面两位。为什么要两个%,%%相当于转义 等同于1个% #%%相当于转义 相当以一个%
995,622
bffb5b2ec43fe0dda7a7121250061023acb31905
#!/usr/bin/python # -*- encoding: utf-8 -*- import torch import torch.nn as nn import torch.nn.functional as F import torch.cuda.amp as amp import soft_dice_cpp # should import torch before import this ## Soft Dice Loss for binary segmentation ## # v1: pytorch autograd class SoftDiceLossV1(nn.Module): ''' s...
995,623
775eae291094d30ecba65c31633c957a700dab01
#!/usr/bin/python import boto3 import time client = boto3.client('cloudformation', region_name='us-east-1') #functions def status(stack): while True: stackStatus = client.describe_stacks(StackName=stack) status=(stackStatus['Stacks'][0]['StackStatus']) print "{}'s current status is {}.".fo...
995,624
11c9596845cdb43fca7d9d0cc874521a2d7e3c89
import pandas as pd import matplotlib.pyplot as plt # # TODO: Load up the Seeds Dataset into a Dataframe # It's located at 'Datasets/wheat.data' # # .. your code here .. data = pd.read_csv('Datasets/wheat.data') # # TODO: Drop the 'id' feature # # .. your code here .. data.drop('id',1,inplace=True) # # TODO: Co...
995,625
48699e3ded5ce9474b9f3b3a1c8b723065ab3390
#!/usr/bin/env python # -*- encoding: utf-8 -*- from BeautifulSoup import BeautifulSoup, NavigableString, Tag from urllib2 import urlopen from datetime import date import re URL = "http://laco.se/lunch/" def get_daily_specials(day=None): page = urlopen(URL) soup = BeautifulSoup(page) page.close() daily_specials...
995,626
70b9109ef259d0df97598c1be75eb5285d0a0c33
import markovify from flask import Flask, render_template, request, redirect from flask import jsonify, abort from flask_sqlalchemy import SQLAlchemy from flask_wtf import FlaskForm, CSRFProtect from wtforms import TextAreaField, validators PATH_TO_DB = "./sqlite.db" app = Flask(__name__) app.secret_key = 'qwerty' ...
995,627
96aee793701aee8f224905db86f2f977ad1af5c0
import cv2 import numpy as np import json red_img1 = [] blue_img1 = [] white_img1 = [] gray_img1 = [] yellow_img1 = [] red_fig1 = [] blue_fig1 = [] white_fig1 = [] gray_fig1 = [] yellow_fig1 = [] red_waga = [] blue_waga = [] white_waga = [] gray_waga = [] yellow_waga = [] roi = [] path_js...
995,628
6ed8e9edff29cb2177d7721361ee6ea92c630c40
from datetime import datetime, timedelta from flask import Flask, request, redirect from flask.helpers import make_response, url_for from flask_sqlalchemy import SQLAlchemy import jwt app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = '' app.config['SECRET_KEY'] = 'flasksecretkey' db = SQLAlchemy(a...
995,629
af9e4838d4b29a4f30de6630262e15304f014c0c
#!/usr/bin/env python import os import subprocess import sys import optparse import gzip import shutil try: import hashlib # New for python 2.5 sha = hashlib.sha1 except: import sha sha = sha.sha CMDS = ['cat','q','partition','import','print'] TYPES = ['s3','fb','tsv.gz', 'cz'] delim = "\t" def s3conne...
995,630
bdf7a6aca1a12d98f8050f477e3a3565fafa1831
def foo2(): x=100 print "Local:" ,locals() print x if __name__ == '__main__': print "this is the main program" foo2() #to import a function you must call the file from the correct directory then call the specific function
995,631
e7e23f45eb6d53050273d4c0f66c5f3820b2745a
import pytest from flask import url_for from app import create_app, mail from app.models import db, User, Store, Product @pytest.fixture def app(): return create_app('test') @pytest.fixture def init_database(): db.create_all() yield db.drop_all() @pytest.fixture def authenticated_request(client):...
995,632
ca50b26b3fd05b82f8ac27876129bf846784a0d0
# -*- coding: utf-8 -*- # Author: WangZi # Mail: wangzitju@163.com # Created Time: ########################### # template method # processing framework is defined in father class # while concrete prcessing method is implemented in child class from abc import ABCMeta, abstractmethod class AbstractDisplay(metaclass=ABC...
995,633
00f2df37799d68cddc29ec7f086f2bf13c71bc05
from collections import defaultdict dwarfs = {} dwarf_name_hat_color_count = defaultdict(int) while True: tokens = input() if tokens == "Once upon a time": break tokens = tokens.split(" <:> ") dwarf_name, dwarf_hat_color, dwarf_physics = tokens[0], tokens[1], int(tokens[2]) key = dwarf_nam...
995,634
f9988acc80e8c3f89b44e88509f20f97b807e0f6
import math import euler from sets import Set squares = {} matches = {} for i in range(1000): squares[i*i] = i for p in range(3, 1001): print p matchCount = [] for a in range(1, 998): if a >= p-2: break for b in range(1, 998): if a+b >= p-1: break c = a*a + b*b if c not in squares: ...
995,635
b66ff58928d75dbe792dcdf08223c57ca8d96931
import dash import dash_core_components as dcc import dash_html_components as html from dash.dependencies import Output, Event from textblob import TextBlob from collections import deque import plotly.graph_objs as go neg_polarity = [] neg_subjectivity = [] with open('negative.txt','r') as n: negative_file = n.read(...
995,636
8961d02da6d859b4b421fa698370f5b63162734f
# Generated by Django 2.0.6 on 2018-12-02 19:33 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('User', '0001_initial'), ] operations = [ migrations.AddField( model_name='supplier', name='phone', field...
995,637
1ad625ba98fb789ba96022d85d8691491a9d69a2
#!/bin/python3 import sys import itertools n = int(input().strip()) a = [int(a_temp) for a_temp in input().strip().split(' ')] count = 0 pairs = list(itertools.product(a, a)) for pair in pairs: if abs(pair[0] - pair[1]) > 1: pairs.remove(pair) print(pairs)
995,638
403e038af3e898a8342303e75c6af9d53a13be24
class BinaryTree(object): def __init__(self, value): self.value = value self.leftChild = None self.rightChild = None def insertLeft(self, newData): if self.leftChild is None: self.leftChild = BinaryTree(newData) else: t = BinaryTree(newData) ...
995,639
ca2c0c9b90c828540dfcf9c04dcc5eeaed506a72
s=input() k=int(input()) n=len(s) num=[0]*n for i in range(n): if s[i]!="a": num[i]=123-ord(s[i]) if sum(num)>=k: ans="" for i in range(n-1): if k>=num[i]: k-=num[i] ans+="a" else: ans+=s[i] if k>=num[-1]: ans+="a" else: ans...
995,640
db5698eb1adacbf0e5b9fae34f1e52b443fc32a9
#!/usr/bin/env python import roslib roslib.load_manifest('cram_ptu') import rospy import actionlib import tf import cogman_msgs.msg class TFRelayAction(object): # create messages that are used to publish result _result = cogman_msgs.msg.TFRelayResult() def __init__(self, name): self._action_name = name ...
995,641
728772e9bdf0c5d16c402a8810f61b0bcd8dbefe
#!/bin/python3 import sys #system functions and parameters from datetime import datetime as dt #import with alias print(dt.now()) my_name = "Arjun" print(my_name[0]) print(my_name[-1]) sentence = "This is a sentence." print(sentence[:4]) print(sentence.split()) sentence_split = sentence.split() sentence_join = '...
995,642
139d00ea298d8a1ae0aa000399d0b43724df6a08
import abc import typing import torch import brats.functional as F ONE_CLASS = 1 CLASS_DIM = 1 class Loss(abc.ABC): """ Interface for loss """ @abc.abstractmethod def __call__(self, prediction: torch.Tensor, target: torch.Tensor) -> torch.Tensor: raise NotImplementedEr...
995,643
c362caacf0df78ad95783f500f6a85bbc4640bb4
# Copyright 2021 Curtin University # # 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 writi...
995,644
5d90ee051de923ad1e68e189ac7be34069371cae
########################################### # Project: CMSIS DSP Library # Title: FileSource.py # Description: Node for creating file source # # $Date: 30 July 2021 # $Revision: V1.10.0 # # Target Processor: Cortex-M and Cortex-A cores # ---------------------------------------------------------...
995,645
473c1869e981500c2ddba49732ffbb825153bba8
# Generated by Django 2.0.5 on 2018-06-25 02:05 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('Paciente', '0002_paciente_user'), ('Laboratorio', '0004_auto_20180624_1449'), ] operations = [ migr...
995,646
1e9de2936ccf0b88753e155361f0886e7ad65176
import pytest @pytest.yield_fixture() def setup(): print("this url is opened") yield print("Browser is closed") def test_Signupbyemail(setup): print("This is simple Sign Up email function to test") def test_signupbyfacebook(setup): print("This is simple Sign Up facebook function to test")
995,647
5d8c6856f061f8469941615ad748801277a36a97
#!/usr/bin/env python from analyze_logs import LogAnalyzer analyzer = LogAnalyzer() # 1. What are the most popular three articles of all time? r = analyzer.most_popular_articles() assert(r[0][1] == 338647) # 2. Who are the most popular article authors of all time? r = analyzer.most_popular_authors() assert(r[0][1] ...
995,648
9a41d71bf77b249077829fa9d2d8f64ba6a062fa
from django.contrib import admin from .models import GalleryModel admin.site.register(GalleryModel)
995,649
6e463cf73c3d8a4b7ff54b2ed71326267c5377b7
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Jul 25 14:52:15 2020 @author: cxue2 """ from datetime import datetime import numpy as np from sklearn.metrics import confusion_matrix from sklearn.metrics import roc_auc_score, roc_curve, auc from sklearn.metrics import precision_recall_curve, average_p...
995,650
40f728d674d83e396b25cc06c08f6f8a5f6e0892
# PYTHON2 file to be run on the Pi Zero import RPi.GPIO as r from time import sleep from math import cos, radians r.setmode(r.BOARD) pins = [11, 12, 13, 15, 16, 18, 22, 7, 3, 5, 24, 26, 19, 21, 23, 8, 10] r.setup(pins[0], r.OUT) pwm = r.PWM(pins[0], 50) i = 0 while True: pwm.start(50 * (1 -...
995,651
d9d0c1a7ce6e26342a9e7becc7c75792fbe16940
__source__ = 'https://leetcode.com/problems/unique-email-addresses/' # Time: O() # Space: O() # # Description: Leetcode # 929. Unique Email Addresses # # Every email consists of a local name and a domain name, separated by the @ sign. # # For example, in alice@leetcode.com, alice is the local name, and leetcode.com is...
995,652
0ff4bbb05fa13b9e8f7911f4ae71e4d1af7e22a6
# Create by CodeMeow # -*- coding:utf-8 -*- import urllib2 import logging import logging.handlers import sys, os, re reload(sys) sys.setdefaultencoding('utf8') WEATHER_URI = 'http://vehiclenet-python-0-codemeow.myalauda.cn/carlink/weather/findWeather.htm?city=%s' def fetch_weather(city_name): logger = logg...
995,653
63aecb1297120a78f0b5ebde5642f4e74ffa055a
import os import sys sys.path.append(os.path.abspath(os.path.dirname(__file__) + '/../..')) import unittest from tests.cases.google_test_case import GoogleTestCaseSimple class TestSuite1(unittest.TestCase): def test_main(self): # suite of TestCases self.suite = unittest.TestSuite() self....
995,654
7a92a6b22c31be1a14f6f2da5143e757fb0c8ebe
from mock_api.response_rules import response_rules_provider class ResponseResolver(object): rules_provider = response_rules_provider def __init__(self, api_endpoint, response_rule_provider=None): self.api_endpoint = api_endpoint if response_rule_provider: self.rules_provider = res...
995,655
bde478969734138ba60464de702a1538cba2c946
# class Test: # def __init__(self): # print("This is in __init__") # pass # def __call__(self, func): # print("This is in __call__") # def inter(a, b): # print("This is in inter") # ret = func(a, b) # return a + b - ret # ...
995,656
fbafc641bf18a43595f7177625059eb317272506
import math x, y, n_devices = map(int, input().split()) devices = [] for _ in range(n_devices): devices.append(tuple(map(int, input().split()))) close_devices = sorted(devices, key=lambda dev:math.sqrt((x-dev[0])**2 + (y-dev[1])**2)-dev[2]) dev = close_devices[2] dist = math.sqrt((x - dev[0]) ** 2 + (y - dev[1]) *...
995,657
c590b59aa142fa4e412c08cb6b25b0a7d94f9b35
from Queue import Queue class IterableQueue(Queue): _sentinel = object() def __iter__(self): return self def close(self): self.put(self._sentinel) def next(self): item = self.get() if item is self._sentinel: raise StopIteration else: ...
995,658
118055756466c23917ade71f27e35933122d827b
import math import random LEVELS = ['user', 'easy', 'medium', 'hard'] class TicTacToe: def __init__(self): self.board = self.make_board() self.current_winner = None @staticmethod def make_board(): return ['_'] * 9 def print_board(self): print('---------') for...
995,659
0a4e959da401c83fd86ca2302732de272218be69
a, b = list(map(int, input().split())) seki = a*b seki = seki % 2 if seki == 0: print("Even") else: print("Odd")
995,660
f18e3baf5757219110b9e64e4bd180921782a7a7
import numpy as np import tensorflow as tf from config import PREDICT_THRESHOLD IOU_METRIC_THRESHOLDS = list(np.arange(0.5, 1, 0.05)) def _seg_iou(seg1, seg2): batch_size = seg1.shape[0] metrics = [] for idx in range(batch_size): ans1 = seg1[idx] > 0 ans2 = seg2[idx] > 0 inters...
995,661
2f97593d020e0e931c4072607fac5a384e24c982
from geopy.geocoders import Nominatim #Used for grabbing geocode info from open street maps from geopy.exc import GeocoderTimedOut import time import datetime def do_geocode(street, city, state, unit_number=''): street = street.title().strip() city = city.title().strip() state = state.upper().strip() address = '"...
995,662
d42ae44baf1a3415d04522ba209c27dd54944407
from django.shortcuts import render, redirect from student.models import StudentCourses, Student from course.models import Catalog, Prerequisites from authentication.models import UserType from registrar.models import Constraints from django.contrib import messages from history.models import StudentCourseHistory impor...
995,663
323f7018608aa58238bab93ea33bbdada7728159
class SwordMeta(type): """docstring for ClassName""" def __instancecheck__(cls, instance): return cls.__subclasscheck__(type(instance)) def __subclasscheck__(cls, sub): return (hasattr(sub, 'swipe') and callable(sub.swipe) and hasattr(sub, 'sharpen') and callable(sub.sharpen)) class Sword(metaclass = SwordM...
995,664
e86a0c1b25a706ec04447bf940f69533144d5072
# -*- coding: utf-8 -*- import os import urllib2 import unittest import simplejson as json import polls from codecs import open TEST_WIKIPEDIA_PAGE = 'tests/resources/full.html' LATEST_TEMP_FILE = "tests/latest_temp.json" __author__ = 'Simao Mata' class TestPolls(unittest.TestCase): def setUp(self): sel...
995,665
a19c87c68344794f7434119fd1372e22034a5d6c
from bs4 import BeautifulSoup import requests import re import random base_url = 'https://baike.baidu.com' his=['/item/%E7%BD%91%E7%BB%9C%E7%88%AC%E8%99%AB'] url = base_url + his[-1] html = requests.get(url).text soup=BeautifulSoup(html,'lxml') # print(soup.find('h1').get_text(),' url:',his[-1]) print(html)
995,666
ef6340aad9699af5fea2451df95bfbf78c9adfef
# -*- coding: utf-8 -*- import re import unittest from aliyunsdkrds.request.v20140815.DescribeSlowLogRecordsRequest import DescribeSlowLogRecordsRequest from ali_rds import AliRds class AliRdsTestCase(unittest.TestCase): def setUp(self): #print("init") pass def tearDown(self): #print("...
995,667
020116b00caa294c52f0ae0931c46f384daf9d05
#detecting hands with mediapipe #using google's pre-made ML algos in mediapipe import cv2 import mediapipe as mp img = cv2.imread("hands.jfif",-1) mpHands = mp.solutions.hands hands = mpHands.Hands() drawTools = mp.solutions.drawing_utils imgRGB = cv2.cvtColor(img,cv2.COLOR_BGR2RGB) results = hands.process(imgRGB) f...
995,668
7653ac525960586985fc2345d8e966c83c722547
from pynta.apps import PyntaApp from pynta.apps.decorators import require_method from pynta.core.paginator import Paginator from pynta.storage.base import Anydbm class CRUDApp(PyntaApp): """ Provide full CRUD (Create, Read, Update, Delete) interface for any data set via five actions: `_create`, `_list`, `...
995,669
7258e1fc714b6d1fccbaf2ef91bf08b96dd32cc1
import socket def client(): s = socket.socket() HOST="127.0.0.1" PORT=6666 s.connect((HOST,PORT)) s.send(b'hello word') msg = s.recv(1024) print("form server %s " % msg) if __name__=='__main__': client()
995,670
12af87a2756d8f86cb688eaa0617114e3b7b5b92
from flask import abort from flask import Blueprint from flask import flash from flask import redirect from flask import render_template from flask import request from flask import Response from flask import session from flask import url_for from flask_login import current_user from pingpong.decorators.LoginRequired im...
995,671
3243d512dfd11d5667a64ab1473c1dc4d476548f
/usr/share/pyshared/openerp/addons/document/document.py
995,672
ed614ecdd646f3b58916ba648c93d27d7f2f3e05
# Generated by Django 3.1.4 on 2020-12-28 05:04 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='objetivos', fields=[ ...
995,673
8e3a3245eb53935b2ac1edf402a6fd0c933c6cf8
import numpy as np from tabulate import tabulate def iteration(alpha, beta, x, eps): k=1 err = eps + 1 while err > eps and k < 500: err = np.linalg.norm(np.dot(alpha, x) + beta - x) x = np.dot(alpha, x) + beta k += 1 x = np.dot(alpha, x) + beta return x, k def zeidel(A,...
995,674
bb874ec373c77789bbda7c76ed5c9f237084d0a7
class Protocol: def __init__(self): pass def decodeMessage(self,*args,**kwargs): pass def encodeMessage(self,*args,**kwargs): pass
995,675
7e09be1aa3185300cdcace9302d1910b17e370d4
print “https://dataplatform.cloud.ibm.com/analytics/notebooks/v2/b98b218f-4492-4a29-842a-6eddc479001b/view?access_token=a68970d0e2205f734085612c6998864010927d9f79f6a8867b8d6aad5a266b10"
995,676
fbeb50f795133a4fcc20f51215a3614a79ef1736
# -*- coding: utf-8 -*- from django.core.serializers import serialize from django.db import models from django.conf import settings import json from django.core.serializers.json import DjangoJSONEncoder # Create your models here. def upload_file(instance,filename): return "persons/{user}/{filename}".format(user=in...
995,677
03d876ed6018f9b83e2fd065ed871c804dbf65ff
import torch.nn as nn import torch.nn.functional as F from layers import GraphConvolution, InnerProductDecoder import torch class CONN(nn.Module): def __init__(self, nfeat, nnode, nattri, nlayer, dropout, drop, hid1=512, hid2=128, act='relu'): super(CONN, self).__init__() self.latent_dim = nfeat ...
995,678
79351e1edf1c5cbff2addef6a7e1cf0a187ce63e
# %% import math def calcular(t): exponente = math.exp(-t) seno = math.sin(math.pi*t) total = exponente*seno print("EXPONENTE: ",exponente) print("g(t): ", total) return calcular(0) calcular(1) '''EXPONENTE: 1.0 g(t): 0.0 EXPONENTE: 0.36787944117144233 g(t): 4.505223801027239e-17''' #%%...
995,679
3a1439ed4d74d6a5ed1b7f84ce99cc8dd0249444
""" This file builds the figures which demonstrate the training of a Gaussian process. """ figwidth = 6 # 2.5 figheight = 6/1.616 import matplotlib.pyplot as plt import matplotlib.cm as cmap cm = cmap.inferno plt.style.use("../thesis-style.mpl") import numpy as np import scipy as sp import theano import theano.tens...
995,680
468761c107bcb50f86fbb1b64c8296be8793d72c
from pylab import plot, show, bar y = [1,3,6,9,11,21,5,8,3] plot(y) show()
995,681
2145e06dae22b911877e394cf3f8193c042862a1
""" 假设 我需要一个函数,接收2个参数,分别为方向(direc棋盘大小为50*50,左上角为坐标系原点(0,0),我需要一个函数,接收2个参数,分别为方向(direction),步长(step), 该函数控制棋子的运动。棋子运动的新的坐标除了依赖于方向和步长以外, 当然还要根据原来所处的坐标点, 用闭包就可以保持住这个棋子原来所处的坐标。 """ # # 系统已经没有内存可以给你使用了 内存泄露 # 系统只分配给你100m内存,101M 内存溢出 def start_game(direction, step): # 原点坐标 origin_position = [0, 0] # ...
995,682
4fba6d82c6478bf4770cfff4b346032fce183b49
def logger(func): def wrapper(*args, **kwargs): print('args: ', args, 'kwargs: ', kwargs) # try: result = func(*args, **kwargs) # except Exception as e: # print(e) # result = e with open('text.txt', 'a') as file: file.write(f'{args} \n') ...
995,683
38b43a2fcdb74621a72f408c00a3ad5e131e99ae
'''Write a python program to find if a given year is a leap year or not''' def leapYear(y): if y % 4 == 0: if y % 100 == 0 and y % 400 != 0: print("{} is not a leap year".format(y)) else: print("{} is a leap year".format(y)) else: print("{} is not a leap year".format(y)) ye...
995,684
3b9b3dfbd2af2b0333840d2c14e4c9c29e9d6895
import sys from collections import namedtuple Point = namedtuple("Point", "x y") Rectangle = namedtuple("Rectangle", "left top right bottom") def outSideCheck(a, b): return b.right < a.left or a.right < b.left def outBottomUpCheck(a, b): return a.top < b.bottom or a.bottom > b.top def overlapRect(a, b): ...
995,685
a26aa54ae77622cf3897cb358f6c3cab30f8f59f
import os from datetime import datetime import numpy as np from msl.io import JSONWriter, read from .. import __version__ from ..log import log from ..constants import REL_UNC, DELTA_STR, SUFFIX, MU_STR def num_to_eng_format(num): for key, val in SUFFIX.items(): renum = num/val if abs(renum) < 1...
995,686
5eccae6e643f27e3e5224e8004205c0b1fc63c52
from fastapi import FastAPI, Form from fastapi.testclient import TestClient app = FastAPI() @app.post("/form/python-list") def post_form_param_list(items: list = Form()): return items @app.post("/form/python-set") def post_form_param_set(items: set = Form()): return items @app.post("/form/python-tuple") ...
995,687
4e0e4e1b2b711581ba826c730a7299a637726383
class update: startOver = False fctDataPath = None useCache = False
995,688
86f11623b798c7d0f907610ac9728210e63f422e
#!/usr/bin/python # -*- coding:utf-8 -*- #功能:把用户输入的不规范的英文名字,变为首字母大写,其他小写的规范名字 def normalize(name): return name.capitalize() L1 = ['adam', 'LISA', 'barT'] L2 = list(map(normalize, L1)) print(L2)
995,689
fde31ae3a78158facefe00e237326ffe3cee6bff
# list My_list = [1,2,3,4,56,67] my_list2 = list(range(1,7)) print(My_list) print(my_list2) my_list3 = list(range(1, 50, 10)) # it will increment each time with diff of 10 print(my_list3) # operations on list : # this will return the fifth element print(my_list2[4]) print(my_list2[-2]) # lets create...
995,690
90d53d2c2cd074080287f7449c8b3e91143fbc5d
__copyright__ = "Copyright (c) 2020 Jina AI Limited. All rights reserved." __license__ = "Apache-2.0" from typing import Tuple from ...types.querylang.queryset.dunderkey import dunder_get from .. import QuerySetReader, BaseRecursiveDriver if False: from ...types.sets import DocumentSet class SortQL(QuerySetRea...
995,691
cdb05864bebbe10ffa563542dd51d889af85b4c1
# !/usr/bin/env python """ CLPSO.py Description: the implemention of CLPSO Refrence paper: Liang, Jing J., et al. "Comprehensive learning particle swarm optimizer for global optimization of multimodal functions." IEEE transactions on evolutionary computation 10.3 (2006): 281-295. Member variables: Name: ...
995,692
91a30f195f7f1f9d88f447b050188196f5b507d6
#! /usr/bin/python # Filename: Str_cont.py # # Story from paultyma.blogspot.jp/2010/11/google-interviewing-story.html # # Example: String1: ABCDEFGHLMNOPQRS String1: ABCDEFGHLMNOPQRS # String2: DCGSRQPOM String2: DCGSRQPOZ # Output: true Output: false # # # Best complexity: o(m+n) m:len(String1) & n:len(String...
995,693
522153553cb78501acc788a70c839d9abd8987e3
import pymysql #mysql connection conn = pymysql.connect(host='localhost', user='python', password='qwer1234', db='python_app1',charset='utf8') try: with conn.cursor() as c: #conn.cursor(pymysql.cursors.dictcursor) : 디셔너리 형태로 리턴 # c.execute("select * from users") #1개 로우 ...
995,694
3ec6370865d157326eb2459c286496cc28244e0b
import subprocess import os import re import argparse parser = argparse.ArgumentParser() parser.add_argument('--files', type=str, help='Comma separated test filenames') args = parser.parse_args() test_files = {x for x in os.listdir() if re.search(r'.*_test.py', x)} if args.files: arg_files = set(args.files.split(',...
995,695
959bcff418c448d478f9b1f22a75ab6e25fde2d5
import time import torch import numpy as np import pandas as pd from torch.optim import Adam from options import * from Encoder import * from Decoder import * from util import * def inference(opt, encoder, decoder, test_loader): encoder.eval() decoder.eval() result = [] for batch_idx, (utterances, u_...
995,696
60579df55b7342f11938e9150d04a57ee8c6474c
from sklearn.neural_network import MLPRegressor from sklearn.model_selection import train_test_split from sklearn.metrics import r2_score import sys import pickle # split a string into tokens based on a given character def parse (str1, char) : l = str1.split(char) return l # building inputs x and y # Reading ...
995,697
b4a93369065aab23a7134539b9b56b6301558ed0
from hmmlearn.hmm import GaussianHMM import matplotlib.pyplot as plt import numpy as np # Here n_components correspond to number of states in the hidden # variables. model_gaussian = GaussianHMM(n_components=3, covariance_type='full') # Transition probability as specified above transition_matrix = np.array([[0.2, 0.6...
995,698
aa4f681c011f798ef93bf77b8db4e5a46758297d
# -*- coding: utf-8 -*- """XDCGAN-MINST-RVL-FVL.ipynb Automatically generated by Colaboratory. Original file is located at https://colab.research.google.com/drive/1UBOzY5n5KsevH-j3znDhaFUcSDXg66Bp """ from keras.datasets import mnist from keras.utils import np_utils from keras.models import Sequential, Model fro...
995,699
69b5916108712cd0e56e09501991abbd4792b53b
from typing import Tuple import os from PIL import Image import imagehash import math import random INPUT_DATA_DIR = "d:\\ml\\goat-data\\goat-train-compressed" OUTPUT_DATA_DIR = "d:\\ml\\goat-data\\goat-train-input" def to_ratio(image: Image, ratio: Tuple[int, int] = (4, 3)) -> Image: width = image.size[0] ...