index
int64
0
1,000k
blob_id
stringlengths
40
40
code
stringlengths
7
10.4M
11,100
0ddda57b4b7aabc14e4d1ded70a121f34aaf8857
#!/usr/bin/env/ python3 proto = ["ssh", "http", "https"] protoa = ["ssh", "http", "https"] print(proto) proto.append("dns") #this line will add "dns" to the end of the list protoa.append("dns") #this line will add print(proto) proto2 = [22, 80, 443, 53] # a list of common ports proto.extend(proto2) # pass proto2 as an...
11,101
2b4d24d4b105f6f11d10138436ab74c35f668084
lis=[4,5,3,5,7,2,3,4,6,1,2] for i in range(0,len(lis)+1):
11,102
fb4778c36617067b6fc4367500969c0598c03992
# 2 + 3 # দুই এর সাথে তিন যোগ # 5 # 7-4 # সাথ থেকে চার বিয়োগ # 3 # 6*4 # ছয় আর চার গুন! # 24 # 8/2 # আটকে দুই দিয়ে ভাগ # 4.0 # 8//2 # ফ্লোর ডিভিশন অপারেটর, দশমিকের পরের সংখ্যা বাদ দিয়ে দেয় # 4 # 10%3 # মডুলাস অপারেটর, দশ কে তিন দিয়ে ভাগ করলে যে ভাগশেষ পাওয়া যায়! # 1 # 3**2 # এক্সপোনেন্ট অপারেটর, পাওয়ার বের করতে # 9 # 3...
11,103
d7e9603113c0fc8698e417cbc1f9b8e1f38cde0e
from rest_framework import serializers from rest_framework.response import Response from .models import WomenCycle, GeneratedCycle class WomenCycleSerializers(serializers.ModelSerializer): last_period_date = serializers.DateField() cycle_average = serializers.IntegerField() Period_average = serializers.Int...
11,104
f08d65aa7fb5e61c06fd524717aec64678f1ed51
import unittest class Stack: def __init__(self, size=10): self.items = size * [None] # utworzenie tablicy self.n = 0 # liczba elementow na stosie self.size = size def is_empty(self): return self.n == 0 def is_full(self): return self.size ...
11,105
81b2495bb6083ecd218d14f45a41e72f6881a1e5
# -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import division from __future__ import print_function import csv import numpy as np import os import sys from observations.util import maybe_download_and_extract def ohio(path): """Ohio Children Wheeze Status The `ohio` data frame h...
11,106
c2c41e6dd396cc9826e9097beec28fc34ae9e6cc
import firebase_admin from firebase_admin import credentials from firebase_admin import firestore cred = credentials.Certificate("venv/serviceAccountKey.json") firebase_admin.initialize_app(cred) db = firestore.client() '''student_data = {} for x in range(10): name = input('Enter name: ') age = input('Enter...
11,107
df9d42303168d52c6487b1fd237586d6ae06b948
''' 388. Longest Absolute File Path (Medium) Suppose we abstract our file system by a string in the following manner: The string "dir\n\tsubdir1\n\tsubdir2\n\t\tfile.ext" represents: dir subdir1 subdir2 file.ext The directory dir contains an empty sub-directory subdir1 and a sub-directory subdir2 con...
11,108
1d6665003789e5429a0b472221c35f6f98a49044
import os import sys import numpy as np import logging as log from openvino.inference_engine import IECore import tensorflow as tf from datetime import datetime import cv2 def infer(): start=datetime.now() log.basicConfig(format="[ %(levelname)s ] %(message)s", level=log.INFO, stream=sys.stdout) cpu_exte...
11,109
18bed57c84115db9064237f695583f0f5dafc711
#clasesPython.py class Miclase(object): def __init__(self, name): self.name = name def get_name(self): return self.name def set_name(self, name): self.name = name return self.name #Miclase objeto = new Miclase("John wick"); objeto = Miclase("John Wick") print(objeto.get_name()) print(objeto.set_name...
11,110
b02cdceece98c4feb73ffde8f7de57b8ccbf1cca
class Solution(object): def isLongPressedName(self, name, typed): """ :type name: str :type typed: str :rtype: bool """ if not name and not typed: return True if not name or not typed: return False # f[i][j] = typed[:j] can mat...
11,111
71d2dc171d83670d99a22a8834aa4df1205e1961
""" Scientific numbers are arbitrary precision. They are represented using scientific notation. The implementation uses an integer coefficient and a base-10 exponent. """ __all__ = \ [ 'Scientific' # Construction , 'scientific' # Projections , 'coefficient' , 'base10Exponent' # Predicate...
11,112
4106a2f5596fdc8c4387ebeb72f19c96a3198eba
#!/usr/bin/env python # -*- coding: UTF-8 -*- from django.conf import settings from django.conf.urls.defaults import * from django.views.generic.simple import direct_to_template # Uncomment the next two lines to enable the admin: from django.contrib import admin from motor.models import Hotel admin.autodiscover() urlp...
11,113
e442e78d275b81f7713ac2b73dc91a66ed32c5fe
#!/usr/bin/python # Nombre de Fichero : readBin.py import struct f = file('prueba.bin','r') i=1 f.seek(0,2) #vamos al final del archivo fin = f.tell() f.seek(0,0) #vamos al principio del archivo while (f.tell() < fin): s = f.read(12) dato = str(struct.unpack("i b i", s)) # desempaquetamos print i ," ->",d...
11,114
d0ea7c85d56173abfe25539bf9adf79358028d42
from __future__ import unicode_literals from django.db import models # Create your models here. class Project(models.Model): name = models.CharField(max_length=30, unique=True, blank=False) description = models.CharField(max_length=100, blank=False)
11,115
9a03042bcd3166d6e1477a325818e734c2ede600
import cv2 import numpy as np def otsu_mask(image_input): ''' Using OTSU method to segment the input image :param image_input: original image :return:OTSU mask ''' kernel1 = np.ones((5, 5), dtype=np.uint8) kernel2 = np.ones((5, 5), dtype=np.uint8) kernel3 = np.ones((20, 20), dtype=np.ui...
11,116
29e5dec800834d0d105fb750e2f29b4e6b8f4e44
# tuple of strings my_data = ("hi", "hello", "bye") print(my_data) # tuple of int, float, string my_data2 = (1, 2.8, "Hello World") print(my_data2) # tuple of string and list my_data3 = ("Book", [1, 2, 3]) print(my_data3) # tuples inside another tuple # nested tuple my_data4 = ((2, 3, 4), (1, 2, "hi")) print(my_data...
11,117
72358d8e95dde84ae7043fa9465d4b7e3d2c3355
import threading import pytemperature import usb.core import usb.util from numpy import interp from devices import Formula from devices.s300 import constants class S300: def __init__(self): self.data0 = [] self.data1 = [] self.data2 = [] self.data3 = [] self.data4 = [] ...
11,118
96874e7f5b8aab520e4df7c77938d2bea6e978b4
from LinkedInOauth import * from LinkedInParser import * from Parser import * from Lib import *
11,119
dd623be5195a762ea22726db652cc178c84a3501
import base def map(state): state.MakeEntity(-1, -1, 'data/man.png') state.MakeEntity(1, 1, 'data/man.png') state.MakeEntity(1, -1, 'data/man.png')
11,120
0e95cc275442522bea36635d00a182f472e80bdb
import setuptools import subprocess import os with open("README.md", "r", encoding="utf-8") as fh: long_description = fh.read() def main(): import onaws setuptools.setup( name="onaws", version=onaws.__version__, author="Amal Murali", author_email="amalmurali47@gmail.c...
11,121
ef0cd2844157306f25af4edfcb2c7785b9845e59
from __future__ import division import scipy.io #Used to load the OCTAVE *.mat files from scipy import linalg, sparse #for linalg import matplotlib.pyplot as plt #for the graph import numpy as np #for lin alg operations from scipy.special import expit #vectorized sigmoid function import itertools data_file = 'ex5data...
11,122
855fb93f073ac783e5bc0060dab9485776394d61
import zlib from .oct_key import OctKey from ._cryptography_backends import JWE_ALG_ALGORITHMS, JWE_ENC_ALGORITHMS from ..rfc7516 import JWEAlgorithm, JWEZipAlgorithm, JsonWebEncryption class DirectAlgorithm(JWEAlgorithm): name = 'dir' description = 'Direct use of a shared symmetric key' def prepare_key(...
11,123
77e86432e74873fdcbbf3af69fe73cbdc0f0d850
from django.contrib import admin from django.forms import ModelForm, SplitDateTimeField from django.utils.translation import ugettext_lazy as _ from danceschool.core.admin import EventChildAdmin from danceschool.core.models import EventOccurrence, Event from .models import PrivateEvent, PrivateEventCategory, EventRem...
11,124
e9bcc86bac349494c0c0543a2dd363299f61998f
from xai.brain.wordbase.verbs._transcend import _TRANSCEND #calss header class _TRANSCENDS(_TRANSCEND, ): def __init__(self,): _TRANSCEND.__init__(self) self.name = "TRANSCENDS" self.specie = 'verbs' self.basic = "transcend" self.jsondata = {}
11,125
e25a18941f19bccb64f482ea14080b03563b733e
import csv from datetime import datetime as dt from datetime import timedelta as td from flask import Flask, jsonify import requests class MetadataHelper: def __init__(self): self.licenses = self.populate_licenses() self.vulnerabilities = self.populate_vulnerabilities() def populate_licenses(self): licenses ...
11,126
a3260136e5a7e1b84810e48a32392fbc314785ff
import argparse import asyncio import json import logging from logging.handlers import QueueHandler, SocketHandler from multiprocessing import Process, Queue import os import platform from queue import Empty import signal import socket from subprocess import PIPE, Popen from threading import Thread from time import sle...
11,127
99d1696bd819ecb321b4958842ee8a62aade0e14
class DataTracker: def __init__( self ): self.data_points = [] self.mode = None def add_point( self, point: int ): self.data_points.append( point ) def clear_data( self ): self.__init__() def get_mode( self ) -> int: self._update_mode() return self.mo...
11,128
96db95e122dc43666fc4b21a7225f96fd26a9062
#! # -*- coding: utf-8 -*- from picamera.array import PiRGBArray from picamera import PiCamera from functools import partial from Search import search import argparse import warnings import datetime import cv2 import multiprocessing as mp import urllib2 import urllib import re import paho.mqtt.client as mqtt impor...
11,129
547e5dc494285ef3e59afc94324ebef370a8c4c1
sys imports x = "Podaj dwie liczby do mnozenia: a = sys.stdin.readline() a = int(a) b = sys.stdin.readline() b = int(b) c = a*b c = str(c) sys.stdout.write(c)
11,130
ff84765471f9fc657662bec9150f166a0afd1663
#!/usr/bin/python from time import sleep # https://projecteuler.net/problem=38 # Chose 9876 as a limit. # There might be a better one but it is still fast enough. # The rest is brute force. limit = 9876 print "Limit is", limit digits = [] for i in range(1, 10): digits.append(str(i)) print "Setup digits", digits...
11,131
8c69ded7e2d6b8ea99ab49b606244284ffcfec98
# Arrays: move zeros to the left def move_zeros(Value): #Function to move if len(Value) < 1: return lengthA = len(Value) write_index = lengthA - 1 read_index = lengthA - 1 while(read_index >= 0): if Value[read_index] != 0: Value[write_index] = Value[read_in...
11,132
da15011abd55ddfceaee2c4b6a1f14e594d372c1
# 1- Break Time, webbrowser, time import webbrowser import time listOfYouTubeURL = ["G:\\new ibb\\music\\1.mp4","G:\\new ibb\\music\\2.mp4","G:\\new ibb\\music\\3.mp4"] print "this code start at " , time.ctime() for url in listOfYouTubeURL : time.sleep(2*5) webbrowser.open(url,new=1) # class class Parent(): d...
11,133
9a2f5117c2463946d00b4d43c62f26a0d7c8fb73
from django.shortcuts import render from django.db import connections from django.shortcuts import redirect from django.http import Http404 from django.db.utils import IntegrityError with connections['default'].cursor() as cursor: cursor.execute(f''' SELECT ship_type, CAST(AVG(technical_efficienc...
11,134
499aac609535db528a0e6153fd2a2a5d6d147769
# here we will define our oepn/close functions def open_read_file(file): try: openedfile = open(file, 'r') file_lines_list = openedfile.readlines() # print(file_lines_list) for line in file_lines_list: print(line.rstrip('\n')) openedfile.close() # this closes ...
11,135
72994c7a9d0dda7a4744e1564af6c88d0be118a1
# -*- coding: utf-8 -*- """ """ from __future__ import unicode_literals from __future__ import print_function import logging from time import time from umsgpack import packb, unpackb from p2p0mq.constants import MESSAGE_TYPE_REPLY, MESSAGE_TYPE_REQUEST, DEFAULT_TIME_TO_LIVE from p2p0mq.errors import MessageValidatio...
11,136
4d8b3a7e77b64ddeaaf65d97ce47896ade75b167
import math import pytest from src.suggestions.scoring import metrics from tests.suggestions.scoring.metrics.metrics_test_helpers import get_score_from_population_metric WORLD_POPULATION = 8000000000 A_HIGHLY_POPULATED_CITY = 100000 A_MILDLY_POPULATED_CITY = 1000 A_LOWLY_POPULATED_CITY = 10 @pytest.fixture def lo...
11,137
4b4c1d2e76c8c204fbb02ffd6d0651862c1e785a
#!/usr/bin/env python # -*- coding: utf-8 -*- __import__("sys").path.append('../') from Kernel import Utils from Kernel import ExtractKeywords as ex from GenerateCode import Grammar as g from random import uniform def hide_definitions_with_assign(obj): for i in xrange(len(obj)): obj[i] = obj[i].strip() aux ...
11,138
70eef550c8eb73cf346ea7fd5c157e9bf22f324b
import unittest from typing import List def find_pivot(arr, start, end): if end < start: return -1 if end == start: return start mid = (start + end) // 2 if mid < end and arr[mid] > arr[mid + 1]: return mid if mid > start and arr[mid] < arr[mid - 1]: return mid - ...
11,139
aab673f1c63a56ce5eaf59a71e0ec884d868c59c
bind = "0.0.0.0:8080" def app (environ, start_response): status = '200 OK' response_headers = [('Content-type' , 'text/plain')] start_response (status, response_headers) resp = '\r\n'.join(environ['QUERY_STRING'].split("&")) return [resp]
11,140
5ae0a2de8aa0cdbbe4df2e255571bc717e077d6b
from pymongo import MongoClient import random import string import bcrypt from datetime import datetime, timedelta, date # Step 1: Connect the mongodb server. Please change the connection string to yours while testing client = MongoClient("mongodb://localhost:27017/") #Step 2: Create a new database called emlab db = ...
11,141
aecff5eb13f900dd7e2b23bd5cdada98299906fc
import math as math # Function definitions def trapezium_rule(f, m, x, a, b, n): """Implements the trapezium rule""" h = (b-a)/float(n) s = 0.5*(f(m, x, a) + f(m, x, b)) for i in range(n): s = s + f(m, x, a + i*h) return h*s def bessel(m, x, theta): """Holds the formula for the integra...
11,142
afc0ca4df1e811cd29b278affa8295eba5f752aa
# ---------------------------------------------------------------- # Copyright 2016 Cisco Systems # # 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/LICENS...
11,143
633b9dff0a8a1e0738b302383b8952033a3f2c72
import sys from No_1 import* from PyQt5.QtCore import* from PyQt5.QtWidgets import* class DemoNo1(QDialog): def __init__(self,parent = None): QDialog. __init__(self, parent) self.ui = Ui_Form() self.ui.setupUi(self) self.ui.editBttn.clicked.connect(self.editClicked) ...
11,144
1de8e0e76566849c0f8be2801977b656a5a737c1
''' 给定一个链表,判断链表中是否有环。 为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。 示例 1: 输入:head = [3,2,0,-4], pos = 1 输出:true 解释:链表中有一个环,其尾部连接到第二个节点。 3--->2--->0--->4 |---------| 示例 2: 输入:head = [1,2], pos = 0 输出:true 解释:链表中有一个环,其尾部连接到第一个节点。 1--->2 |----| 示例 3: 输入:head = [1], pos = -1 输出:false 解...
11,145
c636b4906a7947ed27b74f1160e66a97a6036798
import hashlib import os import stat from datetime import datetime, timedelta import bleach from PIL import Image from flask import current_app, request from flask_login import UserMixin, AnonymousUserMixin from itsdangerous import TimedJSONWebSignatureSerializer as Serializer from markdown import markdown from sqlalc...
11,146
6a64f2ff5765650ea109c8a7792834db28fd139d
########################################################################### # # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/l...
11,147
a795dab2de2660c1b6c3dbe8392734fe1824db58
#!/opt/bin/python2.7 ''' ''' import re import time import sys import os import tree import shutil import getpass import pickle from progressbar import ProgressBar,Percentage,Bar import glob import argparse backupList=[] #Append list to execute backup copiedAtThisRound=[] #Pickle dump list for the round of back up ini...
11,148
f6c6b865ba0e3d4c3f983b5eb1912b4d0f967cf2
import urllib.request from selenium import webdriver def cbk(a,b,c): per = 100.0*a*b/c if per>100: per=100 print('%.2f%%'% per) drive = webdriver.Firefox() drive.get("https://www.quanjing.com/creative/topic/9") pas = drive.find_element_by_xpath('/html/body/section/div[2]/section/div/a[1]/img') url...
11,149
a0df45f9034903a3c0d41fe816353a6f5de4bee3
def chromosome_to_cycle(chromosome): """ convert genome to graph, where node1 = chrom1_head, node2 = chrom1_tail node3 = chrom2_head, node4 = chrom2_tail """ nodes = [0] * (len(chromosome) * 2 + 1) chromo = [0] + chromosome.copy() for j in range(1, len(chromo)): i = chromo[j] ...
11,150
567899814885a3be479a0d7636bee52bcae3a70b
from keras.models import Sequential from keras.layers import Conv2D from keras.layers import MaxPooling2D from keras.layers import Flatten from keras.layers import Dense from keras.preprocessing.image import ImageDataGenerator import keras classifier = Sequential() classifier.add(Conv2D(32, (3, 3), input_sh...
11,151
194cfa0c038dfb253ba520200e42225c0fd4912e
from kivy.app import App from kivy.uix.label import Label from kivy.uix.image import Image class MainApp(App): def build(self): #label = Label(text = 'Hello from Kivy', image = Image(source='index.jpeg', size_hint = (.5,.5), pos_hint = {'center_x':.5, 'center_y':.5}) #return label return image ...
11,152
5fe2ff779fcaefbf8cddd0e0233d8f133f536810
from Lang.Struct import OrderedSet import sys class EventReceiver(object): """ Feel free to use this class as a mixin for receiving specific events. However, strict use of this class is not necessary. If your class is subscribed to an EventProxy and is not a subclass of EventReceiver, your class will still recei...
11,153
60b511cd5dbc8f2f0d3b50a6024855a6d74f71be
from django.db import models from django.conf import settings class Subject(models.Model): title = models.CharField(max_length=20) def __str__(self): return self.title class Chapter(models.Model): subject = models.ForeignKey(Subject, on_delete=models.CASCADE) title = models.CharField(max_l...
11,154
6f83282e381c41290e82673896921d3a7dd7ebc7
import unittest from scrapyz.util import JsonSelector from util import fake_response from spiders import * class TestGenericSpiders(unittest.TestCase): """ Tests the basic functionality of GenericSpider. """ expected_items = [ { 'disclaimer': u'Disclaimer One', 'd...
11,155
da3f8c00ed6017b7645904983deb12715639c77e
# Four collection types in Python # 1) List # 2) Tuple # 3) Set # 4) Dictionary list = ["James", "Harry", "Albus"] print("List:", list) print("List item at 2:", list[2]) list[0] = "Percevel" print("List:", list) print("Iteration:") for x in list: print("\t", x) print("List length:", len(list)) list.append("Gi...
11,156
737f24838054cf9717214154a22a7c29581a732a
# -*- coding: utf-8 -*- from Acquisition import aq_inner from Products.CMFPlone.PloneBatch import Batch from zope.component import getMultiAdapter from archetypes.referencebrowserwidget.interfaces import IReferenceBrowserHelperView from archetypes.referencebrowserwidget import utils from Products.Five.browser.pagetempl...
11,157
0969a7e0bb299c08cd5f368a2ff5c7e815e7b2ad
# 設置密鑰 SECRET_KEY = 'many random bytes' # 設置資料庫地址以及相關配置 MYSQL_HOST = '192.168.112.134' MYSQL_USER = 'root' MYSQL_PASSWORD = 'redd00r' MYSQL_DB = 'crud'
11,158
e0714caacebd57cc92ab00d53210596d1fc7b259
# Generated by Django 2.1 on 2018-11-23 19:22 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('attendance', '0003_attendance'), ] operations = [ migrations.RenameField( model_name='students', old_name='unit_name', ...
11,159
cfbc46524acd375ecdce9f0d2768ec82b2e7d859
import turtle # Example 3 t = turtle.Turtle() t.width(5) for n in range(12): t.color("gray") # Add some if statements (with modulo) here! if n % 3 == 0: t.color("red") elif n % 3 == 1: t.color("orange") else: t.color("yellow") t.forward(50) t.right(360/12)
11,160
b88eb5e95996eccafb23fa243b8f1d87ba1db90f
# Logistic Regression # по факту, алгоритм просто рисует линейную регрессию для 0, 1 элементов # все что выходит за границы между 0 и 1 будет равно 0 или 1 соответсвенно # и потом по этой ломанной прямой вписывают atan(опционально, тут нет этого) # и по этой кривой можно определить вероятность того, что человек с таким...
11,161
0a448d782e57bee8fe2f7024790966e6ba760c3d
def dimensions(gltf, index, parentMatrix=transformations.scale_matrix(1), myMin=[10000000, 10000000, 10000000], myMax=[-10000000, -10000000, -10000000]): node = gltf.nodes[index] print("\n\n---------------------------Node_---------------------------------") T = node.translation if len(node.translation) != ...
11,162
ac9ea3d6e30a61bb343b311701a85effe51d7181
# coding: cp949 from pico2d import * import time import Scene_NormalStage import Scene_BossStage import Manager_Collision import Manager_Sound import Object import Object_Bubble import Object_Item class Player(Object.GameObject): def __init__(self, _x, _y, _type, _ambul = 0, _dart = 0, _pin = 0, _banana = 0): ...
11,163
50ed2e0e01e78c791186cb696a1983ad9c31844b
default_app_config = 'tools_manager.apps.ToolsManagerConfig'
11,164
dcedc7607d8eeda31a23af08eead477769869592
# Generated by Django 2.2.3 on 2019-07-09 09:14 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('polls', '0001_initial'), ] operations = [ migrations.AlterField( model_name='choice', ...
11,165
900e967ce4e0f932befb910b9c22c633f7180649
# FIRST CREATE YOUR OWN MODULE --> e.g; calculator.py # FIRST WAY OF IMPORTING OUR OWN MODULE import calculator print(calculator.add(2, 2)) print(calculator.sub(2, 2)) print(calculator.divide(2, 2)) print(calculator.multiply(2, 2)) # SECOND WAY OF IMPORTING WITH JUST BRINGING SPECIFIC METHODS from calculator import a...
11,166
b0842cfd7158bd21be956b016620890d23ac9884
from sys import argv script, filename = argv txt = open (filename) print "Here's your file %r:" % filename print txt.read() txt.close() print "Closed or not : ", txt.closed print "Type the filename again:" file_again = raw_input ("> ") txt_again = open(file_again) print txt_again.read() txt_again.close() print "Na...
11,167
96a5c0545a18966464bcfebdedd1929f3a781b6d
#FIND SECOND LARGEST NUMBER num1=int(input("enter first number:")) num2=int(input("enter 2nd number:")) num3=int(input("enter 3rd number:")) if(num1>num2)&(num1<num3): print("second largest number is",num1) elif(num1>num3)&(num1<num2): print("second largest number is",num1) elif(num2>num1)&(num2<num3): prin...
11,168
4aeafc82d3e0abd9c652054561e262e7ef6b9cfd
#!/usr/bin/python from bisect import * from copy import * import sys import json import numpy from pylab import * key_time = 'timestamp' key_value = 'value' key_counts = 'counts' key_energies = 'energies' key_lightvar = 'lightvariance' key_id = 'id' key_survey = 'survey' key_interval = 'interval' key_label = 'label...
11,169
74820982a493f3a01925d0f30d3486c692e64a8c
""" scaffoldgraph tests.utils """ from .. import mock_sdf, mock_sdf_2
11,170
ba117f0870333adfc5b3a79b4154b814c7c578c1
# ベストセラー2 # 编程挑战说明: # 一週間にN個の購買履歴データがあります。 # それぞれの購買履歴データは購入日、商品名、単価、個数からなり、購入日が古いものから順番に並んでいます。 # 1日ごとに合計の購入個数が一番おおい商品を、日付と個数とともに表示してください。 # 結果は日付の昇順で表示してください。 # ただし1日の購入個数が等しい商品が複数ある場合は、そのすべての商品を商品名の昇順で表示してください。 # ある1日に1個も商品が売れなかった場合は、その日の結果を表示する必要はありません。 # # 输入: # 標準入力の一行目に購買履歴の個数Nが与えられます。 # 続くN行は販売履歴データです。 # 入力データの...
11,171
b10c7980e39198f369eb46c8a851dcf2d127b0a9
# Given a 2D board and a word, find if the word exists in the grid. # # The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once. # # Example: # # board = # [ # ['A','B','C','E']...
11,172
2c3d021b41d81217196574be37ee83cef731aef7
import math from docx import Document from docx.shared import Inches from docx.shared import Pt from docx.oxml.shared import OxmlElement from docx.oxml.ns import qn from docx.enum.table import WD_TABLE_ALIGNMENT from docx.shared import RGBColor document = Document() #the following variable is to know i...
11,173
d1aba367f453f23741629c8cacddb0a803e6826b
list = [1, 2, 3, 4, 5, 6, 7] index=0 new=[] while index<len(list): var=list[index]*list[index] new.append(var) index=index+1 print(new)
11,174
4427f5e141af758cbe904f5b3cb4e4e3b22d846a
from django.contrib import admin from adminapp.models import Book,BookCategory admin.site.register(Book) admin.site.register(BookCategory)
11,175
b52406557dd60021311df862138344eef46e3c51
from tensorflow.keras.datasets import cifar100 from tensorflow.keras.utils import to_categorical from tensorflow.keras.models import Sequential, Model from tensorflow.keras.layers import Dense, Conv2D, LSTM from tensorflow.keras.layers import MaxPooling2D, Flatten import matplotlib.pyplot as plt import numpy as np (x_...
11,176
8e3afe6bd0774b1cd1a9878b4597cec97628fe99
def reverse_name(str): """ Return a string that does not have a comma in between names and in order: First_name Last_name :param str: a random string :return: a new formatted string without comma and in revers order """ if ',' not in str: return(str) else: str=s...
11,177
e0104fc376e0235b53669aa83a46c27f460d514e
# # Elizabeth Wanic # Programming Assignment # Step 2 # CS3502 # 21 February 2017 # '''In order to run this program, Client_Final.py must also be running on a separate terminal. The program can be run via the command line with the following syntax: python3 Server_Final.py localhost It was created in and meant to be r...
11,178
aea4b22fd106f5ffedb4b210efbcb86cde341d71
x = 2.0 * xwidth * sample.px - xwidth y = 2.0 * ywidth * sample.py - ywidth if x < 0.0: x = x * -1.0 if y < 0.0: y = y * -1.0 tx = xwidth - x ty = xwidth - y weight = max(0.0, tx) * max(0.0, ty) sample.weight = weight
11,179
74c01f298158552df68e6601db727a0017851ffa
from sequential import * from settings import Config import models import utils class UserModeling(Seq2Vec): def _build_model(self): self.doc_encoder = doc_encoder = self.get_doc_encoder() user_encoder = keras.layers.TimeDistributed(doc_encoder) clicked = keras.Input((self.config.window_...
11,180
57805c4ffaecb324c342ad3c2997a7bd7d43f70b
# author: smilu97 # description: serialize states in core import numpy as np state_code = ['blank', 'tails', 'head', 'food'] def serialize(core): w = core.max_x + 1 h = core.max_y + 1 state = np.zeros((w, h), np.int32) def getidx(x, y): return x + y * w for pos in core.trails: s...
11,181
f931e2d03abe214275f64cfd53d949f56b02de3f
""" @author Anirudh Sharma A and B are playing a game. At the beginning there are n coins. Given two more numbers x and y. In each move a player can pick x or y or 1 coins. A always starts the game. The player who picks the last coin wins the game or the person who is not able to pick any coin loses the game. For a giv...
11,182
ebdcbaa71c565b7e14f93984c55be5bd35c5f7ca
from graphserver.ext.osm.osmdb import OSMDB class OSMReverseGeocoder: def __init__(self, osmdb_filename): self.osmdb = OSMDB( osmdb_filename ) def __call__(self, lat, lon): nearby_vertex = list(self.osmdb.nearest_node(lat, lon)) return "osm-%s"%(nearby_vertex[0]) d...
11,183
c05409c5abdc8d7e089480d6ec6698853ceca97f
from app.worker_pool.wo_selenium import SeleniumTaskHandler, SeleniumWorkerSession from app.core.core_orchestrator import RequestWorkers, WorkerAvailability from flask import Flask, jsonify, abort, request, make_response, url_for from app.config import config from app import network_health import requests as r import ...
11,184
7c737f54bb2f8d0e367a7f29e632769f9964112d
# coding:utf-8 # 此文件是流程的相关的常量定义处 TOTAL_SEAT = 4 # 一个桌子的坐位数 # 桌子的状态 # 注意顺序不可修改,否则影响游戏进程 T_IDLE = 0 # 空闲中 T_READY = 1 # 准备中 T_PLAYING = 2 # 游戏中 T_CHECK_OUT = 3 # 结算中 T_IN_IDLE = 0 # 无状态 T_IN_CHU_PAI = 1 # 在出牌中 T_IN_PUBLIC_OPRATE = 2 # 公共操作过程中 T_IN_MO_PAI = 3 # 在摸牌中暗(未公示) T_IN_MO_PAI_CALL = 4 # 在摸牌后的呼叫中 T_I...
11,185
bfb57b3b1f4891f92683589ce478e45ebc79903a
#!/usr/bin/env python import scipy.io as scio import os import rospy import tf """this piece of code publishes object mesh to rviz, translated by eval prediction result.""" id2name = {1: '002_master_chef_can', 2: '003_cracker_box', 3: '004_sugar_box', 4: '005_tomato_soup_can', ...
11,186
f1927786b8ae5bddd07037eeee25d4d44c5eb204
# Copyright 2016 Huawei, Inc. 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...
11,187
911541280e4c1fc43fe278adcf1bf4b322750f66
__FILENAME__ = osm-slurp from sys import stdin from math import hypot, ceil from shapely.geometry import Polygon from Skeletron import network_multiline, multiline_centerline, multiline_polygon from Skeletron.util import simplify_line, polygon_rings from Skeletron.input import ParserOSM from Skeletron.draw i...
11,188
9061f38b16bee1f2ba4657a598b5e491482a08d8
""" Title: Rock Paper Scisors Program Author: Kelton Adey """ import random continuePlay = True aiChoices = ['Rock', 'Paper', 'Scisors'] while continuePlay: inputCheck = False while not(inputCheck): choice = input('Rock, Paper, or Scisors? ') if choice.lower() in ['rock', 'paper', 's...
11,189
acfe6b784f7c53c1b38160b52984893373610127
############################################################################### # Copyright (C) [2020] by Cambricon, Inc. 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 a...
11,190
4c1007065a5f715f296583595d84d7197f2b161b
from torch.utils.data import Dataset from DukeNet.Utils import * from torch.nn.utils.rnn import pad_sequence import numpy as np class Dataset(Dataset): def __init__(self, mode, samples, query, passage, vocab2id, max_knowledge_pool_when_train=None, max_knowledge_pool_when_inference=None, context_len=None, knowled...
11,191
c6e43e5bc18fbe89804999df44f05962880194a0
import numpy import time class BasicEffects: def __init__(self, cube, effect_name): self.cube = cube self.effect_name = effect_name def run(self): self.cube.clear() self.cube.flush() if self.effect_name == "rain": self.sendvoxels_rand_y(150, 0.015, 0.09) elif self.effect_name == "ra...
11,192
bfb94df08cdb4d54a275440dc265cd3a39155da1
# -*- coding: utf-8 -*- """ Created on Wed May 07 14:21:37 2014 @author: Misha """ fig = plt.figure(1, figsize=(8,16)) results={} for i, outcome in enumerate(outcomes): years = range(1,43) yearlyDiffs = [np.array(output[year][group2][outcome]) - np.array(output[year][group1][outcome]) for year in y...
11,193
0a2a90c950f087e1a84f66224a33aa0558b54901
# Problems setting up Python development server at http://127.0.0.1:8000/ python manage.py runserver 127.0.0.1:8001 # it normally runs at :8000
11,194
7f2425fadf0fd883c65af9aeca3392974d62c802
# -*- coding: utf-8 -*- from openerp import models, api, fields, _ class Inventory(models.Model): _inherit = 'stock.inventory' stock_move_related_count = fields.Integer( string='# of Invoices', compute='_compute_stock_move_related_count', help='Count invoice in billing', ) @a...
11,195
87953321b9d3809f5a959103e8456383dbc6d247
#!/usr/bin/python # -*- coding: utf-8 -*- from app_config import app from flask_sqlalchemy import SQLAlchemy db = SQLAlchemy(app) # 创建数据库模型 class Info(db.Model): __tablename__ = 'house_info' h_no = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(2000), nullable=True) type...
11,196
934197c6a7845ed5c7bb409d157a707036f9e038
#calss header class _X(): def __init__(self,): self.name = "X" self.definitions = [u'used to represent a number, or the name of person or thing that is not known or stated: ', u'used at the end of an informal piece of writing to represent a kiss: ', u'written on an answer to a question to show that the answer i...
11,197
f20414f3ff53fbdbb42900840907dc737f575fec
import flask from flask.ext.admin.contrib import sqla import models # Global admin object from refstack.extensions import admin from refstack.extensions import db class SecureView(sqla.ModelView): def is_accessible(self): # let us look at the admin if we're in debug mode if flask.current_app.de...
11,198
f80e2c65fb245354028ac4a0b6dd0aa199651785
# import datetime file from datetime module to use date and time functions from datetime import datetime # class created named as spy class Spy: # constructor of Spy class.It is called automatically whenever the object of Spy class is created. def __init__(self,name,salutation,age,rating): self.name =...
11,199
99e398e788b29d14cb32f45a3c5e8cc8857789a9
from .read import read from .write import write def read_glue( query, database, s3_output, region=None, key=None, secret=None, profile_name=None ): return read( query=query, database=database, s3_output=s3_output, region=region, key=key, secret=secret, p...