index int64 0 1,000k | blob_id stringlengths 40 40 | code stringlengths 7 10.4M |
|---|---|---|
989,600 | 739063a13cfe1e8c6577e31f5a09735a1a064224 | # Program will draw a shape using nested loops
# 10/28/2018
# P4LAB - Nested Loops
# Jacob White
#
# Import Turtle
def main():
import turtle
# Assign varibale t to turtle
t = turtle.Turtle()
# Make turtle program background black
turtle.Screen().bgcolor('black')
# Pen color cyan
t.color('cy... |
989,601 | 2ba209ef9f74c88e2ebd7fad205cd1b2eb66fe77 | from sqlalchemy import Column, Date, Float, ForeignKey, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship, sessionmaker
from sqlalchemy import create_engine
Base = declarative_base()
#TABLE INFORMATION ARE PLACED HERE.
class THE_TABLE_NAME(Base):
__tablen... |
989,602 | 3e9ed357a8407641fed08a14b84fc9ec97297dab | # --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... |
989,603 | 441f4e0122fbb4210574f5185204bb67b1c99e40 | from .general import _pkg_root
from .dress import dress
from .dress_element import dress_element, BeamElement
from .beam_elements import *
from .line import Line
from .particles import Particles
from .particles import pyparticles_to_xtrack_dict
from .tracker import Tracker
from .monitors import generate_monitor_clas... |
989,604 | f17cd01350ea28981ac9edac87139fdaf14129c6 | # 11_07 Sending a Letter
lloyd = {
"name": "Lloyd",
"homework": [90.0, 97.0, 75.0, 92.0],
"quizzes": [88.0, 40.0, 94.0],
"tests": [75.0, 90.0]
}
alice = {
"name": "Alice",
"homework": [100.0, 92.0, 98.0, 100.0],
"quizzes": [82.0, 83.0, 91.0],
"tests": [89.0, 97.0]
}
tyler = {
"name... |
989,605 | 6ff971985c4b55d883efe603ac190f6d697d8e20 | #import pandas as pd
#import scipy.io
#from pandas import Series,DataFrame
#from PIL import Image
#from os import listdir
#from os.path import isfile, join
import numpy as np
import cv2
import os
#from tempfile import TemporaryFile
#image_names = []
path = "./small_1"
valid_images = [".jpg",".jpeg",".png",".tga",".bmp... |
989,606 | bee756799705f31aa80bded1dba1063c41829233 |
# coding: utf-8
# In[ ]:
s, m = 0,1
num = []
with open("input.txt",'r') as file_in:
for line in file_in:
a = line.split(' ')
for i in range(len(a)):
num.append(int(a[i]))
if (((int(a[i])) > 0)):
s = s + int(a[i])
mn = min(num)
mx = max(num)
for i in range(len(... |
989,607 | 422179fde6e44668b2499cb9ba4f1857adc938a6 | import os
class CollectFood:
def __init__(self, input_file, output_file):
self.input_file = input_file
self.output_file = output_file
self.food_set = set()
def __loadData(self, input_file, food_set):
with open(input_file, "r") as file_in:
os.linesep='\r'
... |
989,608 | 0200c18c1783f8dfba343c8de24640e367929772 | from Shared.API.infrastructure import ResourceManager
from Utils.guid import guid
import logging
import pytest
logger = logging.getLogger("test")
@pytest.mark.pasapi
@pytest.mark.bhavna
@pytest.mark.pas
def test_delete_password_profile(core_session):
"""
TC: C281495 - Delete Password Complex Profile
:par... |
989,609 | ca76eb6a30404078579c1300349af8cc840a397c | from functools import wraps
from flask import (
Blueprint,
flash,
g,
redirect,
render_template,
request,
session,
url_for
)
from werkzeug.security import (
check_password_hash,
generate_password_hash
)
from serafim.model import db_session_required
from serafim.model import User
... |
989,610 | 621d7b9e4db536c52cf46fac5df23501bb7b8acb | #
# This SCons Tool is executed after transpSConsSetup and is meant to modify
# the final environment variables used in the builders. This is probably
# only useful for debugging.
#
# The environment variable TRANSP_SCONS_DIR can be used to add one or
# more directories to the tool path which is used to find all of th... |
989,611 | 2e37205a6c6fe44c0633f79fdee13b50ddfc0304 | count = 0
num_lines = 0
#with codecs.open('alice.txt','r',encoding='utf-8') as f:
myfile = open('alice.txt', 'r')
for line in myfile:
tmplist=line.split()
num_lines += 1
print tmplist
#print num_lines
print tmplist
# count = count + len(tmplist)
#print count
#for line in f.readlines():
# lines = ... |
989,612 | d776a4fc56c7cf502597ac031db2ea245b7ee62d | # Copyright 2018 Canonical Ltd.
#
# 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 writin... |
989,613 | 66341a1f5d376ccfdb52fd33f5fb76d673788ee0 | ##THIS CLASS HANDLES THE CALL TO SIZE THE WINDOW##
##It returns a rectangle an points that describe the window##
from ctypes import *
from ctypes.wintypes import *
def WM_SIZE(cs,hwnd):
##Get Rectangle of selected screen
windll.user32.GetClientRect(hwnd,pointer(cs.variables.Client_window.rcClient))
##Tran... |
989,614 | ac846c76b06d9e1faab962ff8c81930aea08d2c1 | # Generated by Django 3.0.5 on 2020-07-05 02:28
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('users', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='profile',
name='instr_transpose_shift',
... |
989,615 | 991e2c3449e7052e577f4efd3aa444c32b202836 | # coding:utf-8
'''
plsi_helper.py
'''
import os, sys
def main(argv):
pass
def combine_corpora(folder):
for file in os.listdir(folder):
if file[0]!='.':
lines = [line.strip() for line in open(folder+file)]
chunk = ' '.join(lines)
print(chunk)
if __name__ == '__main__':
# main(sys.a... |
989,616 | 1dcf75ab84a04d085cf0893b2e8db90b33a6044e | from travels.views import Views
r = Views()
urls = [
('routes', r.routes),
('new_route', r.new_route),
('get_route', r.get_route)
]
|
989,617 | 1d7ed44abc855de118920955a0da5b07147340f5 | ## ScrollingMemory class
##
## Attributes are:
## 1. an internal list holding the cinematic data:
## self.memory_list
## 2. the maximum size of that list:
## self.max_size
##
## Only the method
## continuation(self, pattern_list, horizon)
## produces an output, i.e. the continuation of a matc... |
989,618 | cdb32d797d5bebdfcef21a9e7b188b9e62d26dd8 | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import rcParams
from sklearn import neighbors
from pandas import DataFrame
df_train =pd.read_csv("/Users/gaojie/Kaggle/data/digit-recognizer/train.csv")
df_test =pd.read_csv("/Users/gaojie/Kaggle/data/digit-recognizer/test.csv")
tra... |
989,619 | 1d3ba074276e1ab82653a45d995da208f7eec8a3 | # Sophie Johnson
# 11/24/18
import cherrypy
import json
from _song_database import _song_database
# Recommendations class
class RecommendationController(object):
# Constructor
def __init__(self, sdb=None):
# Initialize database
if sdb is None:
self.sdb = _movie_database()
... |
989,620 | f9bdef88a9ce3452aef54bba5082e0f506898e8e | # MDP from the example by Sebastian Thrun in: https://www.youtube.com/watch?v=glHKJ359Cnc&t=44s
mdp = [[-3, -3, -3, 100], [-3, None, -3, -100], [-3, -3, -3, -3]]
# Initial utilities
utilities = [[0, 0, 0, 100], [0, None, 0, -100], [0, 0, 0, 0]]
# Actions
# These are the actions the agent can perform,
# they are defin... |
989,621 | 23348513c90e193e570d79951a63d6f2939c9059 | croatia = ['c=', 'c-', 'dz=', 'd-', 'lj', 'nj', 's=', 'z=']
string = input()
for i in croatia:
string = string.replace(i, '#')
print(len(string))
|
989,622 | 16e5e0de74d8bc42b45d4610cf1de8510d164996 | # Copyright 2015 The Cobalt Authors. 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 applicable ... |
989,623 | 923e9ee75a9c105b82616c201ece4ff5b9502d87 | #!/usr/bin/python
#If p is the perimeter of a right angle triangle with integral length sides, {a,b,c}, there are exactly three solutions for p = 120.
#
#{20,48,52}, {24,45,51}, {30,40,50}
#
#For which value of p 1000, is the number of solutions maximised?
numSolutions = [0] * 1001
for n in range(1,500):
m = n+1... |
989,624 | cb31513711315bf10ff915735a8d670babaa70cc | import os
import csv
votes = 0
election_data = os.path.join(r"C:\Users\khanh\Desktop\UCIRV201810DATA4\Homeworks\HW03-Python\PyPoll\Resources\election_data.csv")
Khan = Correy = Li = Tooley = 0
percentage_Khan = percentage_Correy = percentage_Li = percentage_Tooley = 0
with open(election_data, "r") as csvfile:... |
989,625 | 3950e06d4c18dd42a11833df894ab24807936955 | import tkinter as tk
import PIL
from PIL import Image, ImageTk
import cv2
import numpy as np
import google_cloud_storage
from database import BookingDatabase, LoginDatabase, UserDatabase, EmployeesDatabase, IssuesDatabase
import socket_communication
import json
import datetime
import camera
import os
gcs = google_clou... |
989,626 | d5da7a7a50c177ee6162dbbbe48887e57f2008df | """ Interacts with a Docker Daemon on a remote instance"""
import random
from typing import (
Any,
Dict,
List,
Optional
)
import docker
from requests.exceptions import ConnectionError, Timeout
from loadsbroker import logger
from loadsbroker.util import retry
StrDict = Dict[str, str]
DOCKER_RETRY_EXC... |
989,627 | 9866b1219097fba522ef0fe4c53f9e8194911f48 | import json
import web3
from web3 import Web3
from web3.contract import ConciseContract
import _thread
import logging
import numpy as np
def new(user):
email = user.get('email')
address = user.get('address')
import settings
mydb = settings.mydb
w3 = Web3(Web3.HTTPProvider("https://ropsten.infura.io/KZSQap... |
989,628 | 6e49ab386114a224be2f571a62002cfd3a0a4037 | def affiche_produit(nb1, nb2):
produit = nb1 * nb2
print(produit)
affiche_produit(14, 2)
|
989,629 | 86dc557363bf40b164c8aa5c9e6b8413b619cf7a | from django import forms
from .models import *
class question_form(forms.ModelForm):
class Meta:
model=questions_model
fields=['author','question']
class answer_form(forms.ModelForm):
class Meta:
model=answers_model
fields=['question','answer']
|
989,630 | e450e8d9ff79cd68a693b101fba6c9078918e7e8 | #MODULKE FOR CONTROL MOTOR 4WD - 2WD
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setup(23, GPIO.OUT)
GPIO.setup(24, GPIO.OUT)
GPIO.setup(12, GPIO.OUT)
GPIO.setup(14, GPIO.OUT)
GPIO.setup(15, GPIO.OUT)
GPIO.setup(18, GPIO.OUT)
pdr = GPIO.PWM(12, 1500) # channel=12 frequency=1500Hz
piz = GPIO.PWM(18, 1500) ... |
989,631 | 856a7d58ce296e8702b0f348d2a9b401dfd1a830 | def ticker():
infile = open('ticker.txt', 'r')
regels = infile.readlines()
infile.close()
tickerdict = {}
for regel in regels:
ticker_regel = regel.split(':')
sleutel = ticker_regel[0]
waarde = ticker_regel[1].strip()
tickerdict[sleutel] = waarde
return tickerdict
tickerbestand = ticker()
bedrijfnaam =... |
989,632 | fd4e38c7c4bbac0d4c29ed90d8383e815289a498 | s2resolution = {
"Traffic" :[2560,1600],
"PeopleOnStreet" :[2560,1600],
"Nebuta" :[2560,1600],
"SteamLocomotive" :[2560,1600],
"Kimono1" :[1920,1080],
"ParkScene" :[1920,1080],
"Cactus" :[1920,1080],
"BQTerrace" :[192... |
989,633 | 6510e1076ffa8b238ec7de539a0d01b0a6ae70ff | import os
from page import Page
from random import choice
from file_handler import f_read_json
import config
def award_show(self,award, data, icon):
self.add_text(award,fg="GREEN")
self.add_newline()
try:
winners = data[award]
except KeyError:
self.add_text("No-one has won this award ye... |
989,634 | 4317e617be9386217d16d5d7489356c57e888643 | #!/usr/bin/env python
# encoding: utf-8
name = ""
shortDesc = ""
longDesc = """
"""
entry(
index = 0,
label = "C2H2O + C2H2O-2 <=> C4H4O2",
degeneracy = 1.0,
kinetics = Arrhenius(A=(178,'m^3/(mol*s)'), n=0, Ea=(73.999,'kJ/mol','+|-',0.74), T0=(1,'K'), Tmin=(498,'K'), Tmax=(596,'K'), Pmin=(800,'Pa'), P... |
989,635 | a06c22e6748b828bfd90c2018e5c1aabde0d0317 | #!/usr/bin/env python3.7
# -*- coding: utf-8 -*-
# @project: algorithm-python
# @Time : 2019/4/17 11:34
# @Author : Lemon
# @File : ArrayFindNumsAppearOnce40.py
"""
* 题目描述
* 一个整型数组里除了两个数字之外,其他的数字都出现了偶数次。请写程序找出这两个只出现一次的数字。
*
* 解题思路;
* 首先我们考虑这个问题的一个简单版本:一个数组里除了一个数字之外,其他的数字都出现了两次。请写程序找
* 出这个只出现一次的数字。
* 这个... |
989,636 | 3972dcbd93b9e996d5980e9e42ab3e77df3f6573 | from linked_list import LinkedList
# Complete this function:
def nth_last_node(linked_list, n):
current = None
tail_seeker = linked_list.head_node
count = 1
while tail_seeker.get_value() is not None:
tail_seeker = tail_seeker.get_next_node()
count += 1
if count >= n + 1:
if current... |
989,637 | be4d5c0ac66195ac286d616690d829bb26b4c835 | import os
import functools
import requests
from pathlib import Path
import flask
from flask import (
Flask,
abort,
make_response,
jsonify,
redirect,
render_template,
url_for,
)
from astroapiserver import ENV, API
PROJECT_PATH = Path(__file__).parents[1].resolve()
API_URL = "http://127.0.0.1... |
989,638 | c898d70cb349404e272208517867199fa65990e5 | #-------------------------------------------------------------------------------
# Name: module1
# Purpose:
#
# Author: Katherine
#
# Created: 01/04/2015
# Copyright: (c) Katherine 2015
# Licence: <your licence>
#-------------------------------------------------------------------------------
from ... |
989,639 | 012ac41500fe052568a4fc1eeb349c88cf12b13f | import param
import numpy as np
from bokeh.models import Patches
from ...core.data import Dataset
from ...core.util import basestring, max_range, dimension_sanitizer
from .graphs import GraphPlot
class SankeyPlot(GraphPlot):
color_index = param.ClassSelector(default=2, class_=(basestring, int),
... |
989,640 | 8ae8bcecfd9f0ee703431e9e237f3198175f9398 | # --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incor... |
989,641 | c489663b1675bfc333455e132743fe45948e9de9 | import numpy
from srxraylib.plot.gol import plot, plot_image
from srxraylib.metrology.dabam import write_shadowSurface
filein = "/users/srio/Oasys/diaboloid_correction.txt"
sagittal = numpy.loadtxt(filein)
sagittal_x = sagittal[:,0].copy()
sagittal_y = sagittal[:,1].copy() * 1
# print(sagittal_x.shape)
plot(sagitta... |
989,642 | b39abf19244f5a7f7caec4005a63834f8b74d9e6 | #!/usr/bin/env python
import sys
import os
from time import sleep
key = ""
if len(sys.argv) <= 2:
print("Usage: ")
print("python rsadecrypt.py <numeric file> <modulus> <d>")
else:
file = sys.argv[1]
modulus = sys.argv[2]
d = sys.argv[3]
f = open(file).read().split(" ")
output = open("decrypted.rsa", "w")
for... |
989,643 | 50e0cb42d4b8f97eacabb64b47bef01cdaac0448 | import os
import matplotlib.pyplot as plt
import h5py
def display_dataset(path, save, dset='sum'):
"""Displays a dataset, where VOIs are saved in individual locations."""
# List datasets
files_surf = os.listdir(path[0])
files_surf.sort()
files_deep = os.listdir(path[1])
files_deep.sort()
f... |
989,644 | 3c6bd80fb5e24bcfaa39ac3b61a1a3f82ba1435c | from __future__ import annotations
from itertools import chain
from random import random, choice, sample
from typing import Optional, List
from lcs import Perception, TypedList
from lcs.agents.acs2.components.alp import expected_case, unexpected_case, \
cover
from lcs.agents.acs2.components.genetic_algorithm \
... |
989,645 | a66f7deaa574e51b941f2105138bc786c06647e8 | # -*- coding: utf-8 -*-
"""
Created on Tue Jul 9 18:29:53 2019
@author: user
"""
#66. Plus One
class Solution(object):
def plusOne(self, digits):
"""
:type digits: List[int]
:rtype: List[int]
"""
for i in reversed(range(len(digits))): #數列倒序
if d... |
989,646 | 0473ef52de3251d74c5f94cb498a031cd5e04a5a | # coding: utf-8
from django.core.paginator import Paginator, InvalidPage, EmptyPage
from django.core.urlresolvers import reverse
from django.http import Http404, HttpResponse, HttpResponseForbidden, HttpResponseServerError, HttpResponseRedirect
from django.shortcuts import render_to_response, get_object_or_404, render... |
989,647 | 7ffc6671635a9c6dbb70efaf83baf7caee9bff95 | import datetime
now = datetime.datetime.now()
print("current date and time is :",now)
print("in y:m:d h:m:s format : " )
print(now.strftime("%Y-%m-%d %H:%M:%S ")) |
989,648 | f5068cb674c62aedd39e412ccfb09d3f9d426ffd | # https://www.reddit.com/r/dailyprogrammer/comments/5llkbj/2017012_challenge_298_easy_too_many_parentheses/
# [298] [Easy] [Too many parenthesis]
# ((a((bc)(de)))f)
# (((zbcd)(((e)fg))))
# ab((c))
# ((a((bc)(de)))f)
# ((zbcd)((e)fg))
# ab(c)
def sol(exp):
if (exp == "()"): return ""
for i in range(0,len(ex... |
989,649 | 2248348304ee631407e525abaa1660fbdca61048 | """
Core routines for controlling the display board with a controller.
"""
|
989,650 | 3045c05da7797579443249f639b843387598ed19 | #!/usr/bin/env python3
import os
import atexit
import logging
def exitLogCleanup(*args):
"""Cleanup the logging file(s) prior to exiting"""
for logFile in args:
os.unlink(logFile)
return None
atexit.register(exitLogCleanup, snakemake.log[0])
logging.basicConfig(filename=snakemake.log[0], filemo... |
989,651 | 8175bf2f6d68e427f70bb8bedebae59bdaca4408 | # Kmp failure function
a = raw_input()
b = raw_input()
pattern = a + b
matched, n = 0, len(pattern)
pi = [0]*n
for i in range(1, n):
while matched > 0 and pattern[i] != pattern[matched]:
matched = pi[matched-1]
if pattern[i] == pattern[matched]:
matched += 1
pi[i] = matched
l = []
while n ... |
989,652 | 8a212c64dfea9859cd41cea1386e1802076720e3 | from math import *
def fk(x, h, n, p):
# I'm recursive :)
if n == 1:
return df(x, h)
n -= 1
return (2 ** (n * p) * fk(x, h/2, n, p) - fk(x, h, n, p)) / (2 ** (n * p) - 1)
fs = ["cos(x**x)",
"sin(x)",
"x**(cos(x))",
"e**(-x**2)"]
dfs = ["(f(p)-f(p-h))/h",
"(f(p+h)-f(p-h))/(2*h)... |
989,653 | 6cd39e9aaf4d3ae3a298c9205c800cc5abd57f83 | '''
Given a non-empty list of words, return the k most frequent elements.
Your answer should be sorted by frequency from highest to lowest. If two words have the same frequency, then the word with the lower alphabetical order comes first.
Example 1:
Input: ["i", "love", "leetcode", "i", "love", "coding"], k = 2
... |
989,654 | 8ca9e5b1f74e7c5ad93c305ef679841a0b9375d3 | from django import forms
from .models import chef
class chef_form(forms.Form):
chef_code = forms.IntegerField()
chef_name = forms.CharField()
chef_age = forms.IntegerField()
chef_area = forms.CharField()
class chefFormSet(forms.ModelForm):
class Meta:
model = chef
fields = '__all__' |
989,655 | c4b899a045f6833bca62ac04de4308875202228e | import mysql.connector
mysqlConnector = mysql.connector.connect(
host="13.209.50.185",
user="root",
passwd="cww1003",
database="choi"
)
mycursor = mysqlConnector.cursor()
latest_product_name = "test11"
before_latestProd_name = "b-test11"
sql = "INSERT INTO yj_mall_update_record (mall_n... |
989,656 | 4c4cd9316a1b7757427c17e246ed324c1a2bf8e0 | import torch.nn as nn
class SimpleDNN(nn.Module):
def __init__(self, in_dim, hidden_dim, out_dim, depth, act_fn):
super(SimpleDNN, self).__init__()
assert depth > 0
self.act_fn = act_fn
self.linears = nn.ModuleList()
if depth == 1:
self.linears.append(nn.Linear(... |
989,657 | e5fde9354494255bdbd7a87694071ae6bdf2c7e5 | import os
# Reports false error on Linux as LnkParse3 is Windows-only dependency
import LnkParse3 # type: ignore
from typing import List
from pcbdraw.convert_common import chooseInkscapeCandidate
def detectInkscape() -> str:
"""
Return path to working Inkscape >v1.0 executable
"""
candidates = []
i... |
989,658 | 8eb8908eb1381b5ca68bf3adce2075a055db7acf | import sys
from PyQt5.QtWidgets import QApplication,QWidget,QToolTip,QPushButton
from PyQt5.QtGui import QFont,QIcon
class Example(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
QToolTip.setFont(QFont('SansSerif',10))#使用了10px的SansSerif字体
#调用s... |
989,659 | 042af55c26d350b03084a4aa9be3b1b08caf7523 | import unittest
import os
import boto3
import responses
import json
import urllib.parse as urlparse
import decimal
from moto import mock_dynamodb2
from lambdas.aqi_GET import lambda_function as aqi_route
def decimal_default(obj):
if isinstance(obj, decimal.Decimal):
return float(obj)
raise TypeError
... |
989,660 | d72b3614115433e2c7c7ebe07b7d4886a3faa46f | #!/usr/bin/env python3
import sys
try:
from OSC import OSCServer
except ImportError:
sys.path.append("/home/ubiuser/deploy/pyosc/")
from OSC import OSCServer
from time import sleep
server = OSCServer( ("0.0.0.0", 3333) )
server.timeout = 0
run = True
# this method of reporting timeouts only works by conv... |
989,661 | dd4a0453f7ee96b8cf5a1a0bf78de65d50629707 | """Base class for Tasks."""
from oslo_log import log as logging
from asciipic.tasks import base
from asciipic.common import exception
LOG = logging.getLogger(__name__)
class ExampleTask(base.BaseTask):
"""Base class for Tasks."""
def _on_task_done(self, result):
"""What to execute after successful... |
989,662 | 8e51bfed97b7040e00ca4cad11512d55237ece7c | """
Definition of ListNode
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
"""
class Solution:
"""
@param: head: ListNode head is the head of the linked list
@param: m: An integer
@param: n: An integer
@return: The head of the revers... |
989,663 | 267d9bedd292039dea2fb0b1c5f08c4fa1a2f292 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys, os
# DATA packaged
import numpy as np
import pandas as pd
from pandas import Series, DataFrame
# ML packages
import tensorflow as tf
from keras import backend as K
K.clear_session
# Word embedding
import gensim
#from gensim.models import Word2Vec
from gens... |
989,664 | 8833564fd07a266800c0a92875b0474c6e90d3d1 | # draw a triangle
import turtle
t = turtle.Turtle()
t.forward(100)
t.left(120)
t.forward(100)
t.left(120)
t.forward(100)
t.left(120) |
989,665 | 63ad82c283fa7a98ffdc917a60bdae13f7025207 | import os
from datetime import datetime, timedelta
from django.test import TestCase
from mock import patch, call
from oauthlib.oauth2 import TokenExpiredError, InvalidClientError
from hgw_common.utils.mocks import MockOAuth2Session
os.environ['DJANGO_SETTINGS_MODULE'] = 'hgw_common.test.settings'
from hgw_common.mod... |
989,666 | 5c2fce7452b63c8ea76f0179906610ce8d55730f | """This tests passing local_ns and global_ns (for backwards compatibility only)
at activation of an embedded shell."""
from IPython.terminal.embed import InteractiveShellEmbed
user_ns = dict(cookie='monster')
ISE = InteractiveShellEmbed(
banner1='check cookie in locals, and globals empty')
ISE(local_ns=user_ns, gl... |
989,667 | ea49a1099fd97a88aab8931911064af206c352bd | from distutils.core import setup
import os
PKG_VERSION = os.environ.get('PACKAGE_VERSION') or '1.9.0'
setup(
name='python3-indy',
version=PKG_VERSION,
packages=['indy'],
url='https://github.com/hyperledger/indy-sdk',
license='MIT/Apache-2.0',
author='Vyacheslav Gudkov',
author_email='vyach... |
989,668 | 3bf3deb17c2da6a5f496ced029636ed2857bf555 | # main model
import pickle
import numpy as np
from numpy.random import random
import math
import spams
from spams import spams.omp
from keras.models import Sequential
from keras.layers import LSTM
from sklearn.decomposition import SparseCoder
print 'Starting up...'
# load preprocessed data
U = pickle.load(open('... |
989,669 | 7e9117726dc946e693e96663129b56e4edcd0a1c | import pandas as pd
df = pd.read_csv('data/enrollment.csv')
df["status"] = "allowed"
info = df["course name"] == "information technology"
freshmen = df["year"] == 1
df.loc[info & freshmen, "status"] = "not allowed"
commerce = df["course name"] == "commerce"
senior = df["year"] == 4
df.loc[commerce & senior, "status... |
989,670 | 63fffa3ef0136d5d160d39032eba9ac181e71378 | import tensorflow as tf
import os
def brain_dataset(path, image_size=None, augment_function=None, num_parallel_calls=tf.data.experimental.AUTOTUNE):
def get_subdirectory_files(subdir):
sub_path = os.path.join(path, subdir)
return sorted([os.path.join(dp, f) for dp, dn, fn in
... |
989,671 | d7d8d600a2a6df3c81c27b6c97ad81882fda6d55 | #!/usr/bin/python
import os
import re
import nltk
import sys
import getopt
import codecs
import struct
import math
import io
import collections
import timeit
RECORD_TIME = False # toggling for recording the time taken for indexer
BYTE_SIZE = 4 # docID is in int
"""
conducts boolean queries from queries_file and... |
989,672 | 8deab702e2ddcdba89da00388e181cd61a88e7fd | # _*_coding:utf-8_*_
# 创建用户 :chenzhengwei
# 创建日期 :2019/7/15 下午3:59
"""
"""
Student = type('Student', (object,), {'name': "chenzecc"})
stu1 = Student()
print(getattr(stu1, 'name', None))
def __init__(self, name):
self.name = name
def test(self):
print('0000')
People = type('People', (object,), {"__in... |
989,673 | d2ff70cdacd1ad5ec4482484b609e60c4b0b1cfa | #!/usr/bin/env python3
# -*- coding: latin-1 -*-
from flask import jsonify
def url_parser(url):
split_index = url.find('?') # returns first index of '?', in case there are ? in the body
url = url[split_index + 1:]
if url :
dict_response = {}
for chunk in url.split('&'):
... |
989,674 | 5fa51448fd07c1c955b7033a0ca00de013f8b917 | # create a new empty set
s = set()
# adding to set (value)
s.add(1)
s.add(3)
s.add(0)
s.add(42)
s.add(12)
# no element appears twice
s.add(3)
#remove elements (value)
s.remove(12)
print(s)
# len()
print(f"length of s: {len(s)}") |
989,675 | fb2e4271df60fd9c868c36e3caa9266a8a9498b1 | x,y = input().split()
numHayBales = int(x)
farmersPurchasing = int(y)
prices = []
for i in range (farmersPurchasing):
prices.append(int(input()))
prices.sort()
totals = []
for i in range (len(prices)):
if farmersPurchasing-i > numHayBales:
totals.append([(prices[i]*(numHayBales)),prices[i]])
else:
... |
989,676 | 5a750c71a7ae32f4aed4dd0878861582f0289f5c | from test_plus import TestCase
from ..factories import BlogCommentFactory
class BlogCommentTestCase(TestCase):
def test_get_descendants_reversely(self):
parent = BlogCommentFactory()
descendants = BlogCommentFactory.create_batch(10, parent=parent)
self.assertEqual(parent.get_descendants_r... |
989,677 | 49e7c40869ee10a8dcbbe866fedf9458dd7b0b04 | import os
from Bio import SeqIO
from snapgene_reader import snapgene_file_to_seqrecord
def load_records(path):
if isinstance(path, (list, tuple)):
return [record for p in path for record in load_records(p)]
no_extension, extension = os.path.splitext(path)
fmt = {".fa": "fasta", ".gb": "genbank",... |
989,678 | b6050a0a2455b8c2cc99e4ac175f927d6af64be5 | #!/usr/bin/python3
"""
Pascal Triangle
"""
def pascal_triangle(n):
"""
Function that returns a list of lists of integers
representing the Pascal’s triangle of n
Arguments:
- n will be always an integer
Returns:
An empty list if n <= 0
"""
pascal = []
for i in range(1, n + ... |
989,679 | 87b8189a0d4a78553e3467bc6437c4cd8fe3721c | a = float(input(" Digite um numero: "))
b = float(input(" Digite um numero: "))
c = float(input(" Digite um numero: "))
x = (a ** 2 + b ** 2 + c ** 2) / (a + b + c)
print (round(x , 7)) |
989,680 | 1b3d6bd994058bb280bf5c64953d715cf45774a0 | # F strings
import math
me = "JITU"
a1 = 3
a12 = "this is %s %s"%(me, a1)
a = "This is {1} {0}"
b = a.format(me, a1)
print(b)
print(a1)
a = f"this is {me} {a1} {math.cos(65)}"
# time
print(a)
|
989,681 | 650528d43328c1beac7b98961885734564296653 | #Faça um Programa que receba
# uma quantidade pré determinada de notas e mostre as notas e a média na tela
# a = False
# while a == False:
# qtd = input('Informe quantas notas você gostaria de analisar: ')
# try:
# qtd = int(qtd)
# if qtd > 0:
# a == True
# break
# ... |
989,682 | 86a30d544a908e7a0a7565e8417d970962f06335 |
from bs4 import BeautifulSoup
from catalog.models import Product
import requests
from decimal import Decimal
from abc import ABC, abstractmethod
class AbstractParser(ABC):
@abstractmethod
def parse(self):
pass
@abstractmethod
def get_soup(self):
pass
@abstractmethod
... |
989,683 | 9f8a50a8785f39b87c56107127b8fb7e789bb2bb | #!/usr/bin/env python3
import subprocess, re, sys, glob
from collections import defaultdict
path = 'hfo2/**/*.rs'
if len(sys.argv) > 1:
path = sys.argv[1]
if subprocess.call('which count-unsafe > /dev/null 2>&1', shell=True) != 0:
print('''Please install count-unsafe by\n
`rustup update nightly && cargo +ni... |
989,684 | 63ec33b83c89f75b121372a7b4390db14e3fb8a3 | import pypboy
import pygame
import game
import config
class Module(pypboy.SubModule):
label = " Weapons "
def __init__(self, *args, **kwargs):
super(Module, self).__init__((config.WIDTH, config.HEIGHT), *args, **kwargs)
handlers = []
item_names = []
INVENTORY = [
Weapon('Ranger Sequoia','images/inventor... |
989,685 | e21f2181ee3f9c71277cd65fc5b6ac7c5d5e44cd | # coding=utf-8
# -*- conding=utf-8 -*-
# encoding: utf-8
# --==================================================================
# By 函数的属性:
# ID = "id"
# XPATH = "xpath"
# LINK_TEXT = "link text"
# PARTIAL_LINK_TEXT = "partial link text"
# NAME = "name"
# TAG_NAME = "tag name"
# CLASS_NAME ... |
989,686 | 1ca080df75a07e3dc7b6d4219ac0d3de037e2c4c | import boto3
import logging
import os
import json
dynamodb_client = boto3.client('dynamodb', region_name="us-east-1")
sns_client = boto3.client('sns', region_name="us-east-1")
CUSTOMERS_TABLE_NAME = os.getenv('CUSTOMERS_TABLE', "functions_table")
SNS_TOPIC_ARN_FUNCTION_MODIFIED = "function_modified"
with_sns_msg = T... |
989,687 | dc2b4a1b1f7f5f3982b1130a4961fa5a05aba48a | def bubble(a):
l=len(a)
for i in range(l):
for j in range(l-i-1):
if a[j]>a[j+1]:
a[j+1],a[j]=a[j],a[j+1]
return a
print ("Enter array elements")
a=input().split()
a=[int(x) for x in a]
print("Sorted array")
a=bubble(a)
for i in a:
print(i)
|
989,688 | b1b630b0a409a6ad11280e8c4c45d0fc05920f32 | # --------------
#Importing header files
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
#Path of the file is stored in the variable path
#Code starts here
# Data Loading
data = pd.read_csv(path)
data.rename(columns={'Total': 'Total_Medals'}, inplace=True)
data.head(10)
# Summer or Winter
... |
989,689 | 49567b26eabfe372ab6b8a06b14270e427b413e8 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time : 5/21/2018 11:05 AM
# @Author : Siqi
#! /usr/bin/env python
import tensorflow as tf
import numpy as np
import os
import time
import datetime
import data_helpers
from sklearn.metrics import precision_score, recall_score, f1_score
from Bi_LSTM_Model im... |
989,690 | 44410626c2341a860376b6a42d6d1d6ed7e56722 | #@String directory
from ij import IJ, WindowManager
from ij.plugin import Duplicator, Thresholder
from loci.plugins import BF
import os
def get_image_paths():
files = os.listdir(directory)
files = [f.strip() for f in files]
files = [f for f in files if f[-4:]=='.oib']
return files
def run_analysis(img... |
989,691 | 5fb82dfd918cdac7a4dfba3619c5c21250f36ec3 | import datetime
class Post:
def __init__(self, content, author_id):
self.content = content
self.author_id = author_id
self.timestamp = datetime.datetime.now().timestamp()
def insert(self, cursor):
cursor.execute('''
INSERT INTO posts
( content
, a... |
989,692 | 88ed964382c720f23f10895566a4506978928dbf | #####################################################################
# #
# This program will automatically run 'run' and check #
# if any undocumented computers are online #
# ... |
989,693 | b34ff0a6d766334bcab43194f107b67c624509f1 | import base64
import hashlib
import hmac
import json
from datetime import datetime, timedelta
from time import time
import requests
from utils.configuration import agni_configuration
from utils.logger import getAgniLogger
_logger = getAgniLogger(__name__)
PARAM_ACCESS_TOKEN = 'access_token'
PARAM_STATUS = 'status... |
989,694 | 03ff1ec7b54cbe04266236a63f3730629c6b7d83 |
# ex.1
print("I'd much rather you 'not'.")
print('I "said" do not.')
# ex.3
print("hens", 25 + 30 / 6)
print("roosters", 100 - 25 * 3 % 4)
# < has lower precedence than +/-. + first, - second, then comparison
# PEMDAS PE(M&D)(A&S)
print(3.2 + 2.5 < 5 - 7)
print(5 >= -2.45)
# ex.4
cars_driven = 100
space_in_a_car = ... |
989,695 | 8981a898331836099717aca640b8fcfbb518ad8d | from country_class import country
from player_class import player
from generate_countries import generateCountries
from random import shuffle
from drawer import drawMap
from setup import init_players,split_territories
from helper_functions import attackTerritory,fortify
countries=generateCountries()
id_... |
989,696 | 57b24de6bf23b0079cc998a03670b5f8795084b6 |
"""
This is from an internal project tracking application; it extends two
generic views as well as defining logic for various sorting operations.
"""
from django.http import HttpResponse, HttpResponseRedirect
from django.template import RequestContext, loader
from models import Project, Ticket, STATUS_CODES, PRIORIT... |
989,697 | e6dd515872a7e49df7194d230e868ea1a418eda3 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Aug 14 14:57:07 2019
@author: xam
"""
from PIL import Image
import numpy as np
import statistics
import getBlobLoc
import itertools
import math
import Kclus
import Squarepos
b1 = getBlobLoc.getOrdBlob('1.png')
b2 = getBlobLoc.getOrdBlob('2.png')
b3 = ge... |
989,698 | 002dddd665795003017bb9e91bb45c1b6253fa9c | import torch
import torch.nn as nn
import torch.nn.functional as F
class PANNsLoss(nn.Module):
def __init__(self):
super().__init__()
self.bce = nn.BCEWithLogitsLoss()
self.cel = nn.CrossEntropyLoss()
def forward(self, input, target):
"""
input_ = input
input_ ... |
989,699 | bb547879b6b4f0a566266086ac6815fa743eebdb | # Generated by Django 3.1.1 on 2020-09-11 00:38
import django.contrib.postgres.fields
import django.db.models.deletion
import django_enumfield.db.fields
from django.db import migrations, models
import cards.models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.