index int64 0 1,000k | blob_id stringlengths 40 40 | code stringlengths 7 10.4M |
|---|---|---|
993,300 | 489e23507577d8d270a22634981390e4c82f8f3b | # -*- coding: utf-8 -*-
# @Time : 2021-08-02 17:13
# @Author : zxl
# @FileName: 004_6.py
class Solution:
def findKthNum(self,nums1,nums2,k):
if len(nums1) == 0:
return nums2[k-1]
if len(nums2) == 0:
return nums1[k-1]
i1 = 0
j1 = len(nums1)-1
i... |
993,301 | c55ab49cd5041e8f7e5ecc6055bcdf06396e3b94 | import re
states = "Mississippi Alabama Texas Massachusetts Kansas"
statesArr = states.split()
statesList = list()
for val in statesArr:
if(re.search('xas$',val)):
statesList.append(val)
for val in statesArr:
if(re.search('^K.*s$',val,re.I)):
statesList.append(val)
for val in statesArr:
if(re.... |
993,302 | 7db82b35ce2559f4bf9a461ea58b2d04778ddb38 | # -*- coding: utf-8 -*-
"""
The generator class and related utility functions.
"""
from commando.util import getLoggerWithNullHandler
from fswrap import File, Folder
from hyde.exceptions import HydeException
from hyde.model import Context, Dependents
from hyde.plugin import Plugin
from hyde.template import Template
fr... |
993,303 | 02a308146213a9f6d54c9c917dc1e0e18864198d | from unittest.mock import Mock
import pytest
from hypothesis import strategies
from hypothesis.strategies import text as _text
@pytest.fixture
def mock_consumer(mocker):
from giap.consumer import ConsumerInterface
mock = Mock(spec=ConsumerInterface)
mocker.patch("giap.core.get_consumer", return_value=m... |
993,304 | 7be2e7469d435563c4d948d872e1ad952e4cf0be | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Jan 6 16:53:15 2019
@author: haoqi
RNN model for emotion list to beh score
"""
import torch
import torch.nn as nn
import pdb
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
class Emotion_Seq2Beh_Model(nn.Module):
def __i... |
993,305 | 0bd53bffb57edb3835545e7698c2ee5ec3a50103 | import pandas as pd
import numpy as np
import sys
import matplotlib.pyplot as plt
from matplotlib import ticker
from matplotlib.ticker import AutoMinorLocator
class rvjitter(object):
"""
Predicting RV jitter due to stellar oscillations, in terms of fundamental stellar properties.
Example 1:
... |
993,306 | f93223848962ef9a69e14b228a07d0ace00fd961 | import os
# Package import
import docker
# Local import
import config
docker_client = docker.from_env()
dir_name = os.path.dirname(os.path.abspath(__file__))
def start():
'''Launches the prometheus container'''
if getContainer() is not None:
print('Prometheus container already exists')
retur... |
993,307 | 0736f6c591790bfca982afa78739d6a9c84f74da | __author__ = 'PaleNeutron'
import os
import subprocess
import importlib.util
import sys
# from distutils.sysconfig import get_python_lib
PyQt_path = os.path.dirname(importlib.util.find_spec("PyQt5").origin)
# uic_path = sys.exec_prefix + os.sep + "bin" + os.sep + "pyuic5"
uic_path = PyQt_path + os.sep + "pyuic5... |
993,308 | 05a9a0b83752fd7ef11f36312482023191c417fe | #!/usr/bin/env python
from lofarstation.stationdata import TBBXCData
from datetime import datetime
from casacore.measures import measures
zenith_f24 = measures().direction("J2000", "01h01m51s", "+57d07m52s")
t0_f24 = datetime(2017,2,24, 13,56,35, 135000)
sd = TBBXCData("feb24_0.05s_avg.npy",
station_n... |
993,309 | 51fc3c5ba5a068d313caf551d73d4d78e45ebd6a | print("Teste de python") |
993,310 | c75ed4f568a199762d7944e58e46a22144f5bc34 | from pysnmp.hlapi import *
import socket
import sys
import datetime
from time import sleep
crestron_ip = '192.168.0.5'
crestron_port = 505
# Create a UDP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server_address = (crestron_ip, crestron_port)
while 1:
current_time1 = datetime.datetime.now()
e... |
993,311 | 5a38bc2b1b417d836c3b7896e7db8255c5130166 | import sys
import numpy as np
from numpy.linalg import inv
def GetNextItem(items, used_items, l):
u_i = list(used_items)
if (len(u_i) < 1):
p = np.zeros([1,items.shape[1]])
else:
p = items[u_i]
p = np.vstack([p, np.zeros(p.shape[1])])
ones = np.eye(p.shape[0])
ones *= l
... |
993,312 | 75a8442506d2047e491215edcd74f207cfadc76f | import json
manifest_urls = []
ids = open('vatican-ids.txt', 'r')
list = ids.readlines()
for elem in list:
if list.count(elem) > 1:
print(elem)
# with open('vatican-manifests.txt', 'w') as out:
# json.dump(manifest_urls, out)
|
993,313 | fe91c3456310536029fe89b39ab689dced5806f2 | from monitor import Monitor
from raton import Raton
from teclado import Teclado
class Computadora:
cntComputador = 0
def __init__(self, nombre, monitor, teclado, raton):
Computadora.cntComputador += 1
self._idComputadora = Computadora.cntComputador
self._nombre = nombre
... |
993,314 | 63db5d52e38f6692e0ec679871e82930a455f29a | import can
def send():
bus = can.interface.Bus(bustype='pcan', channel='PCAN_USBBUS1', bitrate=250000)
msg = can.Message(arbitration_id=0xc0ffee,
data=[31, 32, 33, 34])
try:
bus.send(msg)
print("channel: {}, send_msg: {}".format(bus.channel_info, msg))
except can.CanError:
prin... |
993,315 | d3feb319de10259b691619399500f3bb10765976 | #!/usr/bin/env python3
"""
CREATED AT: 2022-10-07
URL: https://leetcode.com/problems/maximum-ascending-subarray-sum/
GITHUB: https://github.com/Jiezhi/myleetcode
FileName: 1800-MaximumAscendingSubarraySum
Difficulty: Easy
Desc:
Tag:
See:
"""
from tool import *
class Solution:
def maxAscendingSum(self, ... |
993,316 | 29db81d78857c11450d35a4e64184474e9f96737 | #!/usr/bin/env python3
# encoding: utf-8
# Copyright 2020 ETRI (Minkyu Lee)
import numpy
from etri_dist.libs import sigproc
from scipy.fftpack import dct
import os.path
def set_cmvn_file(path):
if os.path.exists(path+'/cmvn.ark'):
import kaldiio
import numpy as np
cmvn = kaldiio.load_mat(p... |
993,317 | 07e1f68a864aec4d937573ea3943dddbafcafd85 | from Database_model.app_model import Program, ProgramSchema,db
from flask_restful import Resource
from flask import Flask, request, jsonify
#*********************************************************************************************#
#------------------ ProgramCURD--------------------------------------------------... |
993,318 | cc23cb72292c0ed0f897014c8f7c162aabffffff | class Solution(object):
def findKthLargest(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
ret = self.quick_sort(nums, k, 0, len(nums) - 1)
return ret
def quick_sort(self, nums, k, left, right):
if left < right:
... |
993,319 | df4944169a34caff5f81b1c60d94546411344baf | #!/usr/bin/env python
from __future__ import print_function
from __future__ import unicode_literals
class AccessControlAPI(object):
####
## Access Control API
##
def grant_access_control(self, subject, action, scope, grant_option):
"""
TODO: add docstring
"""
params = {... |
993,320 | 301fa87e8a4eee6d37b1fdd66d2611fb893ffabb | from django.shortcuts import render, redirect
# Create your views here.
def home(request):
return render(request, 'index.html', {'demo_title': 'Wello world', 'name': 'melardev'})
def template_demo(request):
return render(request, 'ui/template_example.html', {'demo_title': 'templates Demo'}) |
993,321 | 78d0669609afb4196c4f56838a59f1d1903858f2 | # Lukas Elsrode - (19/29/2020) - Completed Project for IT department changin
import pandas as pd
from math import ceil
# Init dictionday {fields: count}
d_fields = {'Browser': 'Number of Browser Sessions',
'Exchange ActiveSync': 'Number of Exchange ActiveSync Sessions',
'Exchange Web... |
993,322 | 844c9dbe24834da1ac63955b5e67e98e1d1ed863 | from rest_framework import serializers
from procurements.models import Purchase, Producer, Country, ProductionType, ProductType, OKPD2ProductType, Material, \
Colour, Characteristic, Product, Region, BaseUser, ContactPerson, Customer, Contractor, PurchaseMethod, \
PurchaseType, ProductItem, Law, Offer, Con... |
993,323 | 1847702a7175304cceff4886a47d9584fe690876 | #coding=utf-8
from sklearn.datasets import load_iris # iris数据集
from sklearn.model_selection import train_test_split # 分割数据模块
from sklearn.neighbors import KNeighborsClassifier # K最近邻(kNN,k-NearestNeighbor)分类算法
from sklearn.model_selection import cross_val_score # K折交叉验证模块
import matplotlib.pyplot as plt #可视化模块
#加载iris... |
993,324 | f5c64384b4ba5400ce3de3c2580fc6de5077b6b9 | from Queue import Queue
from Stack import Stack
class Node:
def __init__(self, val, weight = 1, dist = 1):
self.val = val
self.neighbours = []
self.weight = weight
self.dist = dist
class Graph:
def __init__(self, nodes = []):
self.nodes = nodes
def add_node(self, val, weight = 1):
new_node = Node(val... |
993,325 | efad260eaf872b7458a492a49369d84c445b3730 | #!/usr/bin/python
# -*- coding: latin-1 -*-
from parserobjects import *
from lexer_rules import tokens
def p_root(subexpressions):
'h : tempo compasheader constlistinit voicelist'
subexpressions[0] = Root(subexpressions[1], subexpressions[2], subexpressions[3], subexpressions[4])
def p_root_no_const(subexpres... |
993,326 | 9628e37556722e1317a85cfe6824a2bddf781a63 | """alter timestamps
Revision ID: 874ed61bf8d0
Revises: cc757507e996
Create Date: 2018-02-12 02:07:53.798273
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
# revision identifiers, used by Alembic.
revision = '874ed61bf8d0'
down_revision = 'cc757507e996'
branch_labels = N... |
993,327 | f048f431dd8114284a5f5081651420ba0e658ea5 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.17 on 2019-02-25 14:30
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('cate', '0002_auto_20190224_1938'),
]
operations = [
migrations.AlterModelOptions(
... |
993,328 | f1bf3c523356c0dba05c3457e0aadb035477792a | from django import forms
class RegistrationForm(forms.Form):
firstname = forms.CharField(
label = "Enter Your First Name",
widget = forms.TextInput(
attrs = {
'class':'form-control',
'placeholder':'Your First Name'
}
)
)
lastna... |
993,329 | b8dc5facc5253b3b22bfd598990ea0b2ce479412 | from typing import Literal
TextDecorationThickness = Literal[
'auto',
'from-font',
'0',
'1',
'2',
'4',
'8',
]
|
993,330 | 51c26fe0f7f1875ed0843295f955cfc8a920f99d | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import argparse
from logya import __version__
from logya.create import Create
from logya.generate import Generate
from logya.serve import Serve
def create(args):
Create(args.name, site=args.site)
def generate(args):
Generate(verbose=args.verbose, dir_site=args.... |
993,331 | 7d71b9a8acf8bdc58bacf9aece1f5d3e886463a4 | import os,re,pdb
from pprint import pprint
## Get the repos
path='/var/lib/apt/lists/'
files=os.listdir(path)
release_files=[file for file in files if file.endswith('Release')]
origin_pattern=re.compile('Origin: (.*)\n')
suite_pattern=re.compile('Suite: (.*)\n')
regex_url = re.compile(
r'^(?:http|ftp)s?://' # ... |
993,332 | 2eb09cf0efc3961e0b1b7ea6e7818ef72f7f5abe | from ttt_board import Cell_Value, TTT_Board
import numpy as np
class Person:
"""Docstring for Person. """
def __init__(self, player_symbol):
"""TODO: to be defined1. """
self.player_symbol= player_symbol
def play_turn(self, board):
"""TODO: Docstring for play_turn.
:board: TODO
:returns: TODO
"""
... |
993,333 | 602e7d3f1086d131b3b3e03859e5fc4809f6690e | # Copyright CEA/DAM/DIF (2010)
# Contributors:
# Stephane THIELL <stephane.thiell@cea.fr>
# Aurelien DEGREMONT <aurelien.degremont@cea.fr>
#
# This file is part of the ClusterShell library.
#
# This software is governed by the CeCILL-C license under French law and
# abiding by the rules of distribution of free sof... |
993,334 | 740fe308f2c6787ab4301f26c8979c4fa7542ead | def solution(p,v):
F=lambda v,s:F(s,v%s)if s else v
l=len(v)+1
s=[-1]*l
for i in range(l-2):
f=F(v[i],v[i+1])
if f!=v[i]:
s[i+1]=f
for j in range(i+2,l):s[j]=v[j-1]//s[j-1]
for j in range(i,-1,-1):s[j]=v[j]//s[j+1]
return''.join(chr(sorted(set(s)).index(x)+65)for x in s) |
993,335 | 2d1722e76981ec16754ba849ef56590b4323d872 | class Solution:
def uniquePathsWithObstacles(self, obstacleGrid):
if not obstacleGrid:
return 0
m, n = len(obstacleGrid), len(obstacleGrid[0])
dp = [[0 for _ in range(n)]] + obstacleGrid
dp = [[0] + row for row in dp]
dp[0][1] = 1
for i in range(1, m + ... |
993,336 | 1427dd5a6abb01aeb5d3f3ea67be7f08ea66145b | s1=str(input())
s2=str(input())
n=len(s1)
m=len(s2)
a=[0]*n
b=[0]*m
for i in range(0,n-2):
if s1[i]=='1':
a[i]=a[i]+1
a[i+1]+=a[i]
a[i+2]+=a[i];
if(s1[n-2]=='1'):
a[n-2]+=1
if(s1[n-1]=='1'):
a[n-1]+=1
for i in range(0,m-2):
if s2[i]=='1':
++b[i];
b[i+1]+=b[i]
b[i+2]+=b[i]... |
993,337 | 10402fd87159dce0c8e927eb897cbfdcafcd2211 | from django.shortcuts import render
from django.contrib.auth import authenticate, login
from django.http import HttpResponseRedirect
#from django.http import HttpResponse
from .forms import SignInForm
def index(request):
if request.user.is_authenticated:
# if user already authenticated - redirect t... |
993,338 | 77d704a91fc41517f4727181d9db97157477e3b0 | import pytest
from Queue.queue import queue_time
def test_queue_basic():
result = queue_time([10], 4)
assert result == 10
def test_queue_basic2():
result = queue_time([], 4)
assert result == 0
def test_queue1():
result = queue_time([10, 2, 3, 3], 2)
assert result == 10
def test_queue2():... |
993,339 | 3f3d98efaff74303a9970d96ef15a265c383e140 | #!/bin/python3
from flask import Flask,render_template,flash, redirect,url_for,session,logging,request
from flask_sqlalchemy import SQLAlchemy
from flask_mail import Message, Mail
from itsdangerous import URLSafeTimedSerializer, SignatureExpired
import datetime
from validate_email import validate_email
app = Flask(__n... |
993,340 | e4a2ff1da9c79804bd60f0a5489d70459a6c173a | '''
1. Реализовать функцию, принимающую два числа (позиционные аргументы) и
выполняющую их деление. Числа запрашивать у пользователя, предусмотреть
обработку ситуации деления на ноль.
'''
def div(arg, arg2):
if arg2 != 0:
return arg / arg2
else:
print("Неправильное число, деление на ноль")
ar... |
993,341 | 2e662a0739198af528ee8e30ae8789e9fdb097dc | # https://binarysearch.com/problems/Pascal's-Triangle/submissions/4441799
class Solution:
def solve(self, n):
pascal = [[1], [1,1]]
i, temp = 2, []
while i <= n:
pascal.append(self.calc(pascal[i-1]))
i += 1
return pascal[n]
def calc(self, lst):
... |
993,342 | 491540480e8d306dabbe6534b1c1abea0520100d | import numpy as np
from scipy import linalg
import pyHPC
from itertools import izip as zip
def lu(matrix):
"""
Compute LU decompostion of a matrix.
Parameters
----------
a : array, shape (M, M)
Array to decompose
Returns
-------
p : array, shape (M, M)
Permutation matr... |
993,343 | 6fe9192cddc19e1e618c7ad4c50640767425097b | import streamlit as st
import pickle
import nltk
import string
from nltk.stem import SnowballStemmer
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
from sklearn.feature_extraction.text import TfidfVectorizer
def cleanupText(message):
message = message.translate(str.maketrans('','',stri... |
993,344 | 149b2e43fa8817396ff95a41a3751c1f6fba0395 | import json
from django.core import serializers
from .models import *
from datetime import timedelta, date, datetime
def custom_json_converter(o):
if isinstance(o, date):
return o.__str__()
elif isinstance(o, datetime):
return o.__str__()
def get_rank_record(domain_id, user_id, unique=False):... |
993,345 | 2e2923a21ea334e4fc6d877a1a2aa66de5be160c | from json import dumps
from os.path import dirname
pwd = dirname(__file__)
with open(pwd + "/Dockerfile", "r") as f:
dockerfile = ''.join(line for line in f.readlines())
with open(pwd + "/script", "r") as f:
script = ''.join(line for line in f.readlines())
print(dumps(
{
"id": 1,
"testID... |
993,346 | 9e2d988efa25be96b01ae864dfb9699562271abe | # Functions goes here
# string checker function
def string_checker(question, to_check):
valid = False
while not valid:
response = input(question).lower()
for item in to_check:
if response == item:
return response
elif response == item[0]:
... |
993,347 | 686e3971a83637886361a2bdba2dcd4b284744f9 | '''
A mess needs to be reoptimized
Kyle Vonderwerth, Jenny Tang, Stephen Em
INF 141: Search Engine Milestone 1
Python 3.4
'''
from math import log2, log, sqrt
from collections import defaultdict
import json, os
class Indexer(object):
version = '0.1'
def __init__(self,directory):
if os.listdir... |
993,348 | 04ea37908069d6a807b76c3d6d3c7fc0488ffe8a |
import numpy as np
import matplotlib.pyplot as plt
from pandas import read_csv
from scipy.stats import pearsonr
import math,sys,os
import random as rnd
from scipy.misc import derivative
from keras.models import Sequential
from keras.layers import Input
from keras.models import Model
from keras.layers import Dense, reg... |
993,349 | 72029b64016fc8cfc8dd044f4614135c7e514cb0 | import os, io
import argparse
import subprocess
from time import strftime, localtime
import time
import pandas as pd
import numpy as np
import random, pickle
from tqdm import tqdm
import torch
import modeling
import Data
from pyNTCIREVAL import Labeler
from pyNTCIREVAL.metrics import MSnDCG, nERR, nDCG, AP, RR
import c... |
993,350 | 161aabe4aabbc8b47af2f4e15267f589f797553c | #!/usr/bin/env python2
import sys
import binascii
import pyautogui
import serial
import bitarray
key_list = ['a','b','c','d'
'e','f','g','h'
'i','j','k','l'
'm','n','o','p']
def serial_data(baudrate):
ser = serial.Serial()
ser.baudrate = baudrate
try:
ser.port = s... |
993,351 | 4af677e2e21ffbd151bfb2062fbe9d3a22e9cc2c | import base64
hex = "72bca9b68fc16ac7beeb8f849dca1d8a783e8acf9679bf9269f7bf"
bytes_ = bytes.fromhex(hex)
base64_ = base64.b64encode(bytes_);
print(base64_) |
993,352 | aefa4d031c1a554e8f985cb0a79e5b7746f15f87 | from urllib import urlopen as uReq
from bs4 import BeautifulSoup as soup
if __name__ == '__main__':
pages = []
for i in range(1,100):
my_url = 'https://www.monster.se/jobb/sok/Data-IT_4?intcid=swoop_BrowseJobs_Data-IT&page={0}'.format(i)
pages.append(my_url)
for my_url in pages:
try:
uClient ... |
993,353 | f3906c00784ebb729b4f0c3a1efe12e1947f33b7 | from random import sample
# Sorting pair of lists
def lists_sort(list1, list2):
# Result list, combined of inputed pair
new_list = []
# Detect lengths of inputed lists
list1_len = len(list1)
list2_len = len(list2)
# Create iterators for inputed lists
list1_iterator, list2_iterator = 0, 0
... |
993,354 | 976a016a9489f1b001c38f3154f5d17d3515fbd5 | from flask import Blueprint, redirect, url_for, render_template, request, session, flash
from datetime import datetime
import time
from website.current import startRun, getCurrent, getImg
def getSevenDay():
day = ['Mon', 'Tues', 'Wed', 'Thurs', 'Fri', 'Sat', 'Sun']
date = ['2021-06-06', '2021-06-07', '2021-06-... |
993,355 | b0212d1943a7e7b84d02436fa0f314506f2bbb76 | # Link: https://leetcode.com/problems/two-sum/
# Approach: Add all the numbers in the dictionary with corresponding index in the array. Now again start iterating over elements in the array. Perform num = target-array[i].
# If the num is in dictionary then extract its position (let's say j) and return (i, j).
class So... |
993,356 | 78c51721eafe8264b16aaf960629fd4d6c9fb6b5 | # for문
# for 변수 in list/tuple/string:
# code here
# loop
# nums = [10, 20, 30]
# for num in nums:
# print(num)
# values = [100, 200, 300]
# for value in values:
# print(value + 10)
# foods = ["김밥", "라면", "튀김"]
# for food in foods:
# print("오늘의 메뉴: " + food)
# strings = ["SK하이닉스", "삼성전자", "LG전자"]
# fo... |
993,357 | 76017cd0a68fae5a8f6e9f609eb60484069dfcb4 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.6 on 2016-09-13 09:20
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependen... |
993,358 | a10dc83b9a05a0d214b5ab8c029313ae01a86a37 | from keras.layers import Conv2D, Conv2DTranspose, Input, MaxPooling2D, Dropout
from keras.layers import Concatenate, Activation, LeakyReLU
from keras.layers.normalization import BatchNormalization
from keras.layers.merge import concatenate
from keras.models import Model
from keras import backend as K
import tensorflow ... |
993,359 | d675d6bfea034ff7110602e01e5c76825765db35 | import requests
from . import DynamicDnsPlugin
class Rackspace(DynamicDnsPlugin):
def update(self, ip):
fqdn = self.domain.split('.', 1)[1]
# Authenticate to get token and tenent IDs
data = {'auth': {'RAX-KSKEY:apiKeyCredentials': {'username': self.config['username'], 'apiKey': self.conf... |
993,360 | 54e2eea678b07ba86b7ba3077656989142c19fb7 | from .body import MetaTexture |
993,361 | aa443653d78659bbe0ffeda3cf1a125bd1ec01ab | '''
Using 12X3 vectors from forst portion of CNN architecture
gets output 40 class classification
Input: 3 images with same labels (segregated image with 2 digits and 1 alphabet)
Output: 40 class classification problem
'''
from __future__ import print_function
import keras
import numpy as np
import os
f... |
993,362 | 3641303ff15ea4a676b41efe3ccb82ac6c708f8f | -------------------------
lxml |
-------------------------
* 它仅仅只是一个第三方库,算不上框架,提供了强大的xml操作api
* from lxml import etree
-------------------------
lxml-etree 模块 函数 |
-------------------------
HTML(text, parser=None, base_url=None)
* 通过html文本构造一个 Element 对象
XML(text, parser=None, base_url=None)
* 通过xml文本... |
993,363 | e8ad5f1c4d04be9c419b6c794f3bf3d580cf49c1 | from django.contrib import admin
from blog.models import *
from .actions import make_published, make_draft
from accounts.models import UserAccount
User = UserAccount
class ArticleAdmin(admin.ModelAdmin):
list_display = ('title', 'thumbnail_tag','slug', 'author', 'jpublish', 'status') #, 'preview_url'
list_filter ... |
993,364 | 5455de0896dd289bccb42c9bd4a801aa3d1b5f9d | # Copyright 2018 Intel, Inc.
#
# 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 writing,... |
993,365 | 58e0befa5a8f9358b533510c75261a82cf80d2ea | from commun.constants.colors import (
color_blanc,
color_bleu_gris,
color_gris_moyen,
color_gris_fonce,
color_gris_clair,
color_orange,
color_rouge,
color_rouge_clair,
color_vert,
color_vert_fonce,
color_vert_moyen,
color_noir,
color_bleu,
color_bleu_dune,
col... |
993,366 | 7a27c5b3af5c1da8e99ccac6ac340b0536f9273e | from enum import Enum
class SubscriptionStatus(Enum):
Active = 1
Expired = 2
Cancelled = 3
PendingCancellation = 4
PendingActivation = 5
class SubscriptionEventType(Enum):
StatusChange = 1
Renewal = 2
MailingAddressChange = 3
Cancellation = 4
Reactivation = 5
Creation = 6... |
993,367 | 08b1a1acd663d7bbfd437b5a98ac3875ecc5e90a | """
two hard coded parallel lines for......
"""
STATES_LIST = ['Alabama', 'Alaska', 'Arizona', 'Arkansas', 'California', 'Colorado', 'Connecticut', 'Delaware',
'Florida', 'Georgia', 'Hawaii', 'Idaho', 'Illinois', 'Indiana', 'Iowa', 'Kansas', 'Kentucky',
'Louisiana', 'Maine', 'Maryland', ... |
993,368 | a2f53fe2959b7f9aad7d8c19497b7470f3fbf175 | var1 = 'Selamat Belajar!'
var2 = "Bahasa Pemograman Python"
print ("var1[0]: ",var1[0])
print ("var2[3:8]: ", var2[1:8])
|
993,369 | 29056180c8877570cb5e99a641e78ef1daee49e8 | def read_data():
with open ('input.txt') as f:
data = f.readlines()
return [d.strip() for d in data]
def write_data(data):
with open('output.txt','w') as f:
for d in data:
f.write(str(d)+'\n')
###
class Field(object):
"""docstring for Field"""
def __init__(self, name, lower, upper):
self.name = name
... |
993,370 | 94ee2e9d6f661402ea9b2716d4888b26e48a15de | import django_filters
from django.db.models import Q
from .models import *
class GoodsFilter(django_filters.rest_framework.FilterSet):
min_price = django_filters.NumberFilter(field_name="shop_price", lookup_expr='gte')
max_price = django_filters.NumberFilter(field_name="shop_price", lookup_expr='lte')
is_... |
993,371 | 6644390d45f717835b739fd487081b79b8d66b16 | import socket
class C2Manager:
def __init__(self):
self.__C2Sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.__Server = "127.0.0.1"
self.__Port = 4444
def Run(self):
try:
self.__C2Sock.bind((self.__Server, self.__Port)) # throws
except socket... |
993,372 | 7d4993e27c36eba9243be0a67f8bdd89b3f98e74 | import collections.Counter
def countCharacters(words: [str], chars: str) -> int:
sum = 0
template = Counter(chars)
for word in words:
mark = True
hs = Counter(word)
for key in hs:
if key in template:
if hs[key] > template[key]:
mark =... |
993,373 | a41a5c242edd1a75d2ae39aa0d518309bfd7305d | from temp_var import h
print(h)
prim_int = 5
prim_str = "String"
prim_float = 5.5
prim_bool = True
prim_copy = prim_int
prim_int = 6
print(prim_copy)
print(prim_int)
class BananaGabi:
def __init__(self):
pass
b1 = BananaGabi()
b2 = b1
b2.gabrizosa = "cosas"
print("Fin") |
993,374 | 338d41613b242672d7216d4371de423936545ea1 | """cd-dot-cz-price-search
Queries cd.cz for train ticket prices and emails a summary.
AWS Lambda optimized.
Example usage:
$ python lambda_function.py
"""
import argparse
import ast
import csv
import datetime
import io
import json
import pickle
import re
import boto3
import requests
AWS_REGION = None
EMAIL... |
993,375 | fc412fcaeb9642c0a29811663deff032cc0f0e9e | from django.urls import path
from dreamtours_app.views import *#UserList, UserDetail, UserByCity
v = 'v2'
urlpatterns = [
path(v+'/user/', UserList.as_view(), name='User List'),
path(v+'/user/<int:pk>', UserDetail.as_view(), name='User Detail'),
path(v+'/user/<path:name>&<path:passwd>', VerifyUser, name=... |
993,376 | 8e7275970d394eaef7bc962ac3d1f793bc02842c | """
Create a function that determines whether four coordinates properly create a
rectangle. A rectangle has 4 sides and has 90 degrees for each angle.
Coordinates are given as strings containing an x- and a y- coordinate: `"(x,
y)"`.
For this problem, assume none of the rectangles are tilted.
is_rectangle(["(0... |
993,377 | 96b1729477e8a111f4a25845c190b1e19da66d1f | def vol_integrand(z, fsky=0.5, fkp_weighted=False, nbar=1.e-3, P0=5.e3):
## Purely volume integral as a sanity check.
## dV / dz [(h^{-1} Mpc)^3]; Differential comoving volume per red... |
993,378 | 6ee4fe22236fff5ad8d21b1a070f9776f8c210cb | #!/usr/bin/env python
import hello
print hello.getstr('hello world')
|
993,379 | f95f4e1adc1c041e113cba2dc97b3958f466862a | # 练习1: 计算 1~100之间所有数字的总和 5050
sum = 0
for i in range(1, 101):
sum += i
print(sum)
# 练习2: 计算1~100 之间所有 偶数之和
sum = 0
for i in range(1, 101):
if i % 2 == 0:
sum += i
print(sum)
# 练习3: 计算 1~100 之间, 同时被 3 和 2 整除的数字 之和
sum = 0
for i in range(1, 101):
if i % 2 == 0 and i % 3 == 0:
sum += i... |
993,380 | 1f4d48461d6a5b6f4e0bb8a8384d4d1ec33ae0e0 | import aiodns
import asyncio
import ipaddress
from merc import feature
class ResolverFeature(feature.Feature):
NAME = __name__
def __init__(self, app):
self.resolver = aiodns.DNSResolver(loop=app.loop)
install = ResolverFeature.install
@asyncio.coroutine
def resolve_hostname_coro(app, user, timeout):
... |
993,381 | 7c400ed772ed4ab6f1a3416d9c3a7a779ff3d053 | # -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'ResumeWhitoutStaffDailyReportData'
db.create_table(u'dash... |
993,382 | 5368e768b7577130c9082e9344ab9cd22280dc1e | import timeit
import numpy as np
import random as rd
start_time = timeit.default_timer()
# code you want to evaluate
class Sudoku:
def __init__(self):
self.size = 9
self.cell = np.arange(1,self.size+1)
rd.shuffle(self.cell)
self.cells = np.array([self.cell])
for x in range(... |
993,383 | 9808963e34b62d6cca63ca9dcd738aeb7b7f9f80 | #!/usr/bin/env python
#
# Azure Linux extension
#
# Copyright (c) Microsoft Corporation
# All rights reserved.
# MIT License
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
# documentation files (the ""Software""), to deal in the Software without re... |
993,384 | 9b6063216649341dd3ea19d03bd5a394ae54bf47 | """
from typing import List
def greet_all(names: List[str]) -> None:
for name in names:
print(name)
greet_all(["Guilherme", "Giovanna"])
"""
def greet_all(names: list[str]) -> None:
for name in names:
print(name)
greet_all(["Guilherme", "Giovanna"])
|
993,385 | 8347e829969ad60dbcfdb23fbf6d671c8c7f8f66 | zhweekday = ["星期日", "星期一", "星期二",
"星期三", "星期四", "星期五", "星期六"]
from datetime import datetime
from dateutil import relativedelta
import os.path
from pathlib import Path
def from_my_birthday (d):
"""
Calculate time difference between given datetime d and 1986-4-23.
"""
birthday = datetim... |
993,386 | b6a146d8bbeb56b0299b42bfdfb77747a6af8354 | """ User Service Class"""
from organization.model.department import Department as department_model
from organization.model.user import User as user_model
from dding import Dding
class Department(object):
""" User Service Class"""
def __init__(self, mongo):
self.mongo = mongo
self.dding = Dding(... |
993,387 | 02f263b288ce667a6b4c1cff20eb950ab7df56d0 | #Problem 2
text = input()
mid = int((len(text)-1)/2)
print("The old string:" ,text)
print("Middle 3 characters:" ,text[mid-1:mid+2])
print("The new string:" ,text[:mid-1] + text[mid-1:mid+2].upper() + text[mid+2:]) |
993,388 | f9c143360025696c26d837cb566766014c429657 | import os
from tqdm import tqdm # smart progress bar
from PIL import Image
import matplotlib as mpl
import matplotlib.pyplot as plt
from matplotlib import rc_params
import pandas as pd
import numpy as np
from skimage.feature import daisy
from skimage.feature import hog
from skimage.color import rgb2gray
from skimage.ex... |
993,389 | 2999c3beaf89f1167432eb78123dfeb525d0ea5f | from dataclasses import dataclass, field
from typing import Iterable, Optional, Callable
from rlbot.matchcomms.client import MatchcommsClient
from rlbot.matchconfig.match_config import MatchConfig
from rlbot.utils.game_state_util import GameState
from rlbot.utils.rendering.rendering_manager import RenderingManager
fr... |
993,390 | 590d90ce58a8c371cc1840246884dc0ad5ceb94c | from django.conf import settings
from scheduled_job_client.exceptions import InvalidJobConfig
def get_job_config():
try:
return settings.SCHEDULED_JOB_CLIENT
except AttributeError as ex:
raise InvalidJobConfig('Missing Scheduled Job Client Configuration')
|
993,391 | deb7db09650632718e9a3fafc73ca1e970512999 | '''
this program plots frequency of top-10 tags using matplotlib reading from precreated json database named sample.json
'''
import matplotlib.pyplot as plt
import json
f = open('sample.json')
data = json.load(f)
dis = {}
data = sorted(data.items(), key=lambda x:x[1],reverse=True)
for i in range(10):
dis[data[i]... |
993,392 | 6cb519eaf5b5d6073c670a307b08803b0f8a039d | import synapse.lib.stormtypes as s_stormtypes
@s_stormtypes.registry.registerLib
class LibIters(s_stormtypes.Lib):
'''
A Storm library for providing iterator helpers.
'''
_storm_lib_path = ('iters', )
_storm_locals = (
{
'name': 'enum', 'desc': 'Yield (<indx>, <item>) tuples fr... |
993,393 | a23c0c376b5c1b099953c51a8096a62beff06f6e | '''
Выведите таблицу размером n×n, заполненную целыми числами от 1 до n2 по спирали, выходящей из левого верхнего угла
и закрученной по часовой стрелке, как показано в примере.
Формат ввода:
Одна строка, содержащая одно целое число n, n>0.
Формат вывода:
Таблица из n строк, значения в строках разделены пробелом.
Sam... |
993,394 | ab784391291b27de25b57da0ac3f2ba70a5c8eed | # 싱글톤 구현 방법들
class BaseClass:
@classmethod
def gettext(cls):
return "static method string"
def singleton(clazz):
instances = {}
def getinstance(*args, **kargs):
if clazz not in instances:
instances[clazz] = clazz(*args, **kargs)
return instances[clazz]
return getinstance
@singleton
class MainClass(Bas... |
993,395 | 5be603761135358c2e72e77d26e48e2d78040bfb | import scrapy
from scrapy.http import HtmlResponse
from jobparser.items import JobparserItem
class SuperjobruSpider(scrapy.Spider):
name = 'superjobru'
allowed_domains = ['superjob.ru']
start_urls = ['https://www.superjob.ru/vacancy/search/?keywords=python&geo%5Bt%5D%5B0%5D=4']
def parse(self, respons... |
993,396 | f9a94a7af18d18f3c0bc0fb94cd7ce3a4ef8ba04 | def EachWork():
allWork = [
{
'title':"Geographic.",
'date':"2019-01-03",
"content":"chart"
},
{
'title': "Four sided",
'date': "2019-01-01",
"content": "chart"
},
... |
993,397 | d0031cc37bbcd1a14324f38fc9f375b3491ddaff | # -*- coding: utf-8 -*-
# Generated by Django 1.9.4 on 2016-05-23 13:25
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Project... |
993,398 | 262c13ec682dbe0cbd7f1cf491b0eaa9911b2aaa | ITEM: TIMESTEP
1500
ITEM: NUMBER OF ATOMS
2048
ITEM: BOX BOUNDS pp pp pp
-3.2774172604533618e+00 5.0477417260445094e+01
-3.2774172604533618e+00 5.0477417260445094e+01
-3.2774172604533618e+00 5.0477417260445094e+01
ITEM: ATOMS id type xs ys zs
1611 1 0.0650907 0.151107 0.142289
180 1 0.128096 0.0699182 0.0557806
653 1 0... |
993,399 | 4223f26158342f99b412dbe77e3675eeb2a65a05 | clothes = [int(x) for x in input().split()]
rack_capacity = int(input())
racks_count = 1
curr_sum = 0
while clothes:
if curr_sum + clothes[-1] <= rack_capacity:
curr_sum += clothes.pop()
else:
racks_count += 1
curr_sum = 0
print(racks_count)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.