text stringlengths 8 6.05M |
|---|
def view_code(filename):
try:
if input('показать исходный код задачи? [y/n]') == 'y':
with open(filename, 'r', encoding='utf-8') as file:
for line in file:
print(line.rstrip())
except:
print(f'файл {filename} не существует или что-то сломалось')
|
import ppn
import utils
from matplotlib.pylab import *
symbs=utils.symbol_list('lines2')
x=ppn.xtime('.')
specs=['PROT','HE 4','C 12','N 14','O 16']
i=0
for spec in specs:
x.plot('time',spec,logy=True,logx=True,shape=utils.linestyle(i)[0],show=False,title='')
i += 1
ylim(-5,0.2)
legend(loc=0)
xlabel('$\log ... |
from django.contrib.auth.models import Group
from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import auth
from .models import Cars, Bikes, Order
from .forms import RegisterForm, CustomerProfileForm, CarUploadForm, OrderForm, BikeUplo... |
class Bai_6():
String1 = ''
String2 = ''
Numberx=0
def __init__(self,string1='',string2='',numberx=''):
self.Numberx=numberx
self.String1=string1
self.String2=string2
def getString(self):
x=input();
self.String2=x
def printString(self):
print(self.... |
import cv2
import threading
from PyQt5.QtCore import pyqtSlot, pyqtSignal,QTimer, QDateTime,Qt, QObject
from PyQt5.QtGui import QPixmap,QColor
from PyQt5 import QtCore, QtGui
import time
Camera_Number = 0
Camera_Object = cv2.VideoCapture(Camera_Number)
class GetImageFromCamera(QObject):
... |
import demoji
import regex as re
# demoji.download_codes()
text = u'منو فالو نمیکنید☹️☹️ یعنی یه دوووونه کامنت وجودره 🤦♀️ همه دنبال یه چیزی میگردن ،خاک برسرتون ،واقعا حت ریده به ت تصویری با ۸۵واقعی❤️'
new = demoji.replace(text, "")
print(new) |
from django.db import models
from django.contrib.auth.models import AbstractUser
# Create your models here.
class CustomUser(AbstractUser):
"""Model definition for CustomUser."""
class Meta:
verbose_name_plural = 'CustomUsers'
def __str__(self):
return self.username |
class DNAAttributeConstruction:
'''parent class for dna translation and feature initialization'''
def __init__(self, sequence_data, labels=None, list_indices=None, chunk=True):
'''Takes whole string{-id, -lab} or list(strings){+/- id, +lab}. generates frags, frag_id, labels'''
self.peptides =... |
import datetime
import simplejson
class BaseConverter(object):
html_codes = (
('&', '&'),
('<', '<'),
('>', '>'),
('"', '"'),
("'", '''),
)
def __init__(self, graph):
self.graph = graph
def encode_html(self, value):
if ... |
from random import randint
print("This is an interactive guessing game!")
print("You have to enter a number between 1 and 99 to find out the secret number.")
print("Type 'exit' to end the game.")
print("Good luck!\n")
number = randint(1, 99)
answer = 0
attempt = 0
while (answer != number):
try:
print("What's your ... |
import os
from pydub import AudioSegment
from subprocess import call
import youtubetomp3.core.utils as Utils
class Converter(object):
"""Converter from video to needed extension"""
def __init__(self, user):
super(Converter, self).__init__()
self.user = user
def convert(sel... |
# Guided Exploration No. 3
# Ryan C. Rose
# Import the "random" library for use in the program.
import random
# Initialize the "possible_names" list for future use.
possible_names = []
# Open/Create a text file titled "rape-names-output.txt" and assign writing access to it to the outputFile variable
outputFile = ope... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# coding=utf-8
list1 = ["这", "是", "一个", "测试"]
for index, item in enumerate(list1):
print(index, item)
for index, item in enumerate(list1, 1):
print(index, item) |
from django.contrib import admin
from .models import HeadTeacher
# Register your models here.
@admin.register(HeadTeacher)
class HeadTeacherAdmin(admin.ModelAdmin):
list_display = ['classes','semester','teacher'] |
class Node(object):
"""docstring for Node"""
def __init__(self, index):
self.index = index
self.left_child = None
self.right_child = None
class BinaryTree(object):
"""docstring for BinaryTree"""
def __init__(self, root):
self.root = root
def pre_travel(self,node):
if not node:
return
print(node.in... |
# Stacement
print("Hello world")
# Expression
x = 10
y = x + 2
print(x,y)
# String
title = "Pyhon Course"
print(title[0], title[1], title[2], title[-1], title[-2])
# String Operation
name = 'Mehedi Amin'
print(name.title())
print(name.upper())
print(name.lower())
print(name.upper().lower().title())
#String Concatena... |
__author__ = 'Skyeyes'
import pygame, sys, random
from pygame.locals import *
pygame.init()
pygame.display.set_caption("drawboard")
font1 = pygame.font.Font(None, 20)
font2 = pygame.font.Font(None, 40)
font3 = pygame.font.Font(None, 80)
font4 = pygame.font.Font(None, 100)
white = 255, 255, 255
red = 220, 50, 50
yel... |
"""
A set of classes for logging in multiprocessing environments. The logging system in this case includes two entities:
server and queued logger, which are connected with a multiprocessing queue. Server is represented by LoggingServer
class and a queued logger is represented by QueuedLogger class. In this model, a ... |
import math
def polygon_area(ns, ls):
length = ls ** 2
t = math.pi/ns
tr = math.tan(t)
return ns * length / tr / 4
print polygon_area(7, 3) |
import random
import numpy as np
from numpy import pi, exp, cos
import os
import time as time
import sys
from datetime import datetime
from bqpe import *
M_range = np.linspace(1, 100, 100, dtype = int)
Attempts = 100
pres = 5*10**-3
MaxR = 1/pres**2
from progress.bar import ShadyBar
bar = ShadyBar('Generating:', ma... |
from django.urls import path
from . import views
urlpatterns = [
path('campus/', views.campus_page, name='campus_page'),
]
|
#Ryan Ulsberger
#October 24, 2014
#Challenge Exercise 4 Chapter 5
import arcpy
from arcpy import env
env.workspace = "C:/MS_GST/TGIS_501/lab4/Exercise05"
extension_spatial = arcpy.CheckExtension("Spatial")
extension_net = arcpy.CheckExtension("Network")
extension_3d = arcpy.CheckExtension("3D")
my_extensions = [exte... |
# use gensim to summarize then use scispacy to find words then build hypernymy / synonymy substition with cuDF hypernymy tree
import gensim
import spacy
spacy.prefer_gpu()
nlp = spacy.load("en_core_sci_sm")
text = """
Myeloid derived suppressor cells (MDSC) are immature
myeloid cells with immunosuppressive activity... |
from flask import Flask, jsonify, request, render_template
import requests
import csv
import io
app = Flask("story_points_predictor", template_folder='templates')
json = ""
@app.route('/', methods=['GET'])
def get():
return render_template('index.html') |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.8 on 2016-08-23 19:12
from __future__ import unicode_literals
import django.contrib.postgres.fields.jsonb
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('core', '0007_aut... |
import requests # pip install requests
from bs4 import BeautifulSoup # pip install beautifulsoup4
import urllib.request
from urllib.error import HTTPError
from urllib.error import URLError
from datetime import datetime
from socket import timeout
from requests.exceptions import ConnectionError
from selenium imp... |
from flask import Flask, request, send_file
from qrbill.bill import QRBill
from io import BytesIO, StringIO
app = Flask(__name__)
@app.route('/')
def main():
try:
payment_parts = QRBill(
account=request.args.get('account'),
amount=request.args.get('amount'),
currency=re... |
# coding:utf-8
import xadmin
from .models import Experiment
class ExperimentAdmin(object):
list_display = ['name', 'degree','images','port','category', 'students',]
search_fields = ['name', 'degree', 'category']
list_filter = ['degree', 'category','click_nums', 'fav_nums', 'students','add_tim... |
#!/usr/bin/env python
"""
File: ops
Date: 11/21/18
Author: Jon Deaton (jdeaton@stanford.edu)
"""
import tensorflow as tf
def f1(y_true, y_pred):
with tf.variable_scope("macro-f1-score"):
y_pred = tf.cast(y_pred, tf.float32)
tp = tf.reduce_sum(y_true * y_pred, axis=0)
tn = tf.reduce_sum(... |
#!/usr/bin/python
#\file send_fake_io1.py
#\brief Sending a fake IO states (digital in).
#\author Akihiko Yamaguchi, info@akihikoy.net
#\version 0.1
#\date Apr.20, 2021
import roslib
import rospy
import std_msgs.msg
import std_srvs.srv
#roslib.load_manifest('ur_dashboard_msgs')
#import ur_dashboard_msgs.msg
ro... |
from constants import *
import numpy as np
from sympy.solvers import solve
from sympy import Symbol
from scipy.signal import correlate
# takes multiple audio feeds (for the same sound) of the form
# (position, numpyarray)
# and calculates the approximate position of the sound
def localize(mics):
for index1, mic1 i... |
#!/usr/bin/env python
def story(**kwds):
return 'Once upon a time, there was a' \
'%(job)s called %(name)s.' % kwds
story(job='king',name='Gummy')
params={'job':'language','name':'Python'}
story(**params)
del params['job']
story(job='stroke of genius',**params)
##############################################
def power(... |
import re
import json
class GenericFormatter(object):
NAME = "Generic"
@staticmethod
def decode(raw):
pattern = re.compile(r"\d+")
result = map(int, re.findall(pattern, raw))
return json.dumps(result)
@staticmethod
def representation(encoded):
... |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import sys,math,os,random
__all__ = []
__all__.append("parse_and_apply")
def parse_and_apply(arguments):
directori,filename,y_min,bootstrap = arguments.split()
filename = os.path.join(directori, filename)
print >> sys.stderr, "calling main for", filename
y_min... |
from flask import Flask, render_template, url_for, redirect
from reporter_app.electricity_use import bp
from reporter_app import db
from reporter_app.models import User, ElecUse
import pandas as pd
from reporter_app.electricity_use.utils import call_leccyfunc, get_real_power_usage_for_times
from flask_security import a... |
# -*- coding: utf-8 -*-
# Depends: smartctl
from __future__ import print_function
try:
from . import Helper
except:
import Helper
import os
import stat
import re
import sys
class SmartInfo(object):
def __init__(self, device):
self.device = None
self.information = []
self.attribu... |
from openVulnQuery import query_client
import csv
import sys,os
import datetime
import json
from webexteamssdk import WebexTeamsAPI
import schedule
import time
api_id = None
api_secret = None
webex_token = None
webex_room_id = None
webex_api = None
class Advisory():
def __init__(self,advisory):
se... |
from framework.data.constants import BASE_URL, HEADERS, REDIRECT, STATUS
from framework.utils.service_utils import send_request
def request_headers(headers=None):
url = '{}{}'.format(BASE_URL, HEADERS)
return send_request(url, headers=headers)
def request_redirect(count):
url = '{}{}{}'.format(BASE_URL,... |
# This Python 3 environment comes with many helpful analytics libraries installed
# It is defined by the kaggle/python docker image: https://github.com/kaggle/docker-python
# For example, here's several helpful packages to load in
import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O... |
from InstIO import *
from DeviceManager import *
class CPU:
def __init__(self,deviceManager,queueReady,resultQueue,waitingProcess):
self.deviceManager = deviceManager
self.queueReady = queueReady
self.resultQueue = resultQueue
self.waitingProcess = waitingProcess
se... |
from .ask_auth_correctness import StateAskAuthCorrectness
from .ask_scores import StateAskScores
from .auth import StateAuth
from .calc import StateCalc
from .greeting import StateGreeting
from .menu import StateMenu
from .ratings import StateRatings
from .settings import StateSettings
from .start import StateStart
fro... |
from django.db import models
class Rabbit(models.Model):
name = models.CharField(max_length=30, null=False, blank=False, unique=True)
carrots = models.PositiveIntegerField(null=False)
def __str__(self):
return self.name
|
from typing import Union
# System level concepts
# ---------------------
# An absolute path to a file on the local filesystem
FilePath = str
# An absolute path to an executable file on the local filesystem
ExecutablePath = str
# An absolute path to a directory on the local filesystem (with no trailing slash)
Direct... |
import os
import tarfile
from six.moves import urllib
import pandas as pd
import pprint
import matplotlib.pyplot as plt
import subprocess
import numpy as np
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
DOWNLOAD_ROOT = 'https://raw.githubusercontent.com/ageron/handson-ml/master/'
HOUSING_PATH = "datasets/housi... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2009-2010 W-Mark Kubacki; wmark@hurrikane.de
#
__all__ = []
|
#!/usr/bin/env python
import http.server
import socketserver
import threading
import rospy
import robot_resource.robot_resource as rs
from sensor_msgs.msg import Image
from sensor_msgs.msg import NavSatFix
class RequestHandler(http.server.SimpleHTTPRequestHandler):
def do_GET(self):
if self.path == "/robot... |
import itertools as itr
import causaldag as cd
from collections import defaultdict
from copy import deepcopy
class IntransitiveParentError(Exception):
def __init__(self, i, j):
message = f"The relation {i}<{j} cannot be added since there is a k s.t. k<{i} but k is not <{j}"
super().__init__(messag... |
import os
import shutil
import glob
UUID = os.getenv('UUID')
TYPE = os.getenv('TYPE')
path= TYPE+'/'+UUID+'/raw/*'
files = glob.glob(path)
os.mkdir(TYPE+'/'+UUID+"/processed/")
for file in files:
#file_path= "type-1-imaging/2020-07-28-rezaee/processed/"+ file.rsplit('/', 1)[-1]
processed_f... |
#!/usr/bin/env python
# -----------------------------------------------------------------------------
# Copyright (c) 2014--, The Qiita Development Team.
#
# Distributed under the terms of the BSD 3-clause License.
#
# The full license is in the file LICENSE, distributed with this software.
# -------------------------... |
#!/usr/bin/env/ python
import requests
import match_history
import sys
import csv
"""
Gets the summoner match history of a particular summoner in the
na region. If summoners outside of NA are desired, edit the
match_history and summoner_name py scripts that get called
in tandem. Basically, don't do that.
Returns... |
import logging
from mongoengine import *
from spaceone.core.locator import Locator
from spaceone.core.model.mongo_model import MongoModel
_LOGGER = logging.getLogger(__name__)
class SecretTag(EmbeddedDocument):
key = StringField(max_length=255)
value = StringField(max_length=255)
class Secret(MongoModel):... |
from challenges.array_binary_search import __version__
from challenges.array_binary_search.array_binary_search import binary_search
def test_version():
assert __version__ == '0.1.0'
def test_number_contained_inside_list():
actual = binary_search([4,8,15,16,23,42], 15)
expected = 2
assert actual == ex... |
from blog.models import Post
from django.shortcuts import get_object_or_404, render
from .models import Work
# Create your views here.
def single(request, slug):
w = get_object_or_404(Work, slug=slug)
context = {
'w': w.to_dict(),
'news': Post.objects.order_by('-date_created').all(),
# ... |
#!/usr/bin/env python
# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Generates build.ninja that will build GN."""
import contextlib
import errno
import optparse
import os
import platform
import re
imp... |
from django import forms
from django.http import JsonResponse, HttpResponseRedirect
from django.shortcuts import render
from swahiliapiapp.models import English, Swahili
class SearchForm(forms.Form):
searchterm = forms.CharField(label="", widget=forms.TextInput(attrs={'placeholder': 'Enter search term here'}))
... |
from keras.models import Sequential, load_model
from keras.layers import Conv2D, Dropout, BatchNormalization, MaxPooling2D,Dense, Activation, Flatten
from keras.optimizers import Adam
from keras.utils import to_categorical
from keras.callbacks import TensorBoard, ModelCheckpoint, EarlyStopping
import os
import glob
im... |
#!/usr/bin/env python2
import socket
import sys
def isproxyalive(proxy):
host_port = proxy.split(":")
if len(host_port) != 2:
#sys.stderr.write('proxy host is not defined as host:port\n')
return False
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(10)
try:
s.connect((host_port[0], int(h... |
import time
import pickle
import graphene
from graphene import resolve_only_args
from graphene_django import DjangoObjectType, DjangoConnectionField
from graphql_jwt.decorators import login_required
from django_redis import get_redis_connection
from django.db import IntegrityError, transaction
from .models ... |
# -*- coding: future_fstrings -*-
# Copyright 2018 Brandon Shelley. 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
#
#... |
import datetime
from app.main import db
from app.main.model.lead import Lead
from app.main.model.status import Status
from app.main.service.business_rules import is_valid_status_change, need_new_customer, need_to_book_meeting
from app.main.service.customer_service import save_new_customer
from app.main.service.oppor... |
from utils.data import read_inventory_optimization_data
class Chain(list):
def __init__(self) -> None:
super().__init__()
def process_single_qubo(self, index, sampler, **kwargs):
qubo = self[index]
qubo.solve(sampler, **kwargs)
def process_best(self, samplers: list, sample... |
'''
define the rpc processing logic
'''
import pickle
from .exception import FunctionNotExistError
class Service:
'''
parsing the client data and call the functions
'''
def __init__(self):
self._function_dict = {}
def register(self, function_name, function):
'''
... |
#encoding:utf8
import urllib2
import urllib
import re
import sys
import os
import time
def Schedule(a,b,c):
per = 100.0 * a * b / c
if per > 100 : per = 100
sys.stdout.write(u"------进度:%.1f%%\r" % per)
sys.stdout.flush()
def createDir():
path = sys.path[0]
new_path = os.path.join(path,'f... |
from functools import cached_property
from onegov.core.elements import Confirm
from onegov.core.elements import Intercooler
from onegov.core.elements import Link
from onegov.wtfs import _
from onegov.wtfs.layouts.default import DefaultLayout
from onegov.wtfs.security import AddModel
from onegov.wtfs.security import Del... |
import boto3
import semver
from aws_conduit import conduit_factory as factory
from aws_conduit.conduit_portfolio import ConduitPortfolio
SESSION = boto3.session.Session()
IAM = boto3.client('iam')
STS = boto3.client('sts')
CONFIG_PREFIX = 'conduit.yaml'
RESOURCES_KEY = "__resources__"
BUCKET_KEY = "__bucket__"
PREF... |
import pandas as pd
import json
import sys
from casos import casos_positivos, casos_fallecidos
poblacion_cusco = 1360013
positivos_cusco = list(casos_positivos[casos_positivos['DEPARTAMENTO'] == "CUSCO"].shape)[0]
positivos_hombres_cusco = list(casos_positivos[(casos_positivos['DEPARTAMENTO'] == "CUSCO") &(casos_posit... |
"""
数轴上放置了一些筹码,每个筹码的位置存在数组 chips 当中。
你可以对 任何筹码 执行下面两种操作之一(不限操作次数,0 次也可以):
将第 i 个筹码向左或者右移动 2 个单位,代价为 0。
将第 i 个筹码向左或者右移动 1 个单位,代价为 1。
最开始的时候,同一位置上也可能放着两个或者更多的筹码。
返回将所有筹码移动到同一位置(任意位置)上所需要的最小代价。
示例 1:
输入:chips = [1,2,3]
输出:1
解释:第二个筹码移动到位置三的代价是 1,第一个筹码移动到位置三的代价是 0,总代价为 1。
示例 2:
输入:chips = [2,2,2,3,3]
输出:2
解释:第四和第五个筹码移... |
# -*- coding: utf-8 -*-
import pandas as pd
from sklearn import tree
import matplotlib.pyplot as plt
import re
col_names = [] #contiene i nomi delle colonne
#leggo i nomi delle colonne dal file adult.names
with open("adult.names",'r') as f:
for line in f:
line = line.strip()
if len(line) == 0 or line[0] == '|':
... |
#!/scratch_net/neo/aabhinav/anaconda3/bin/python -u
import os
import shutil
import sys
import torch
from pytorch_lightning import Trainer
from pytorch_lightning.callbacks import ModelCheckpoint
from pytorch_lightning.logging import TestTubeLogger
sys.path.append('/scratch_net/neo_second/aabhinav/dlad_project/project_... |
#-*-coding: utf-8 -*-#
class Service:
secret="영구는 배꼽이 두 개다." #클래스가 가지는 고유의 공통속성
name=""
def __init__(self, name): #언더스코어 두개의 의미는 이 함수가 원래 파이썬에 있는 함수란 것을 의미한다
self.name= name
def sum(self, a, b):
result = a+b
print("%s님 %s+%s=%s입니다." % (self.name, a,b,result))
def get_secret(s... |
"""
A module that trains readmissions xgboost models.
"""
import json
import os
import sys
import time
import numpy as np
import pandas as pd
import shutil
from time import gmtime, strftime
import sagemaker
import boto3
from sagemaker.tuner import (
IntegerParameter,
CategoricalParameter,
ContinuousParam... |
"""
Views for Tutorial Page application.
"""
#from django.test import TestCase
# Create your tests here.
|
#!/usr/bin/python
from os.path import splitext, split
from pycparser import c_generator, c_ast, parse_file
from textwrap import dedent
from sys import argv, exit
class InvalidTemplateException(Exception):
""" A template file has been determined to be invalid during parsing. """
def __init__(self, msg):
... |
"""Main.py."""
# import os
# import tarfile
# import subprocess
import pprint
# import pandas as pd
# import matplotlib.pyplot as plt
import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import cross_val_score
from sklearn.tree import DecisionTreeRegressor
from sklearn.ens... |
file = open("example.txt",'a')
file.write("Line 4\n")
file.close()
# write has r,w,a and r+,w+,a+ modes; available in dox
|
from .piece import Piece
from game_rules import can_move
from game_state import GameState
import os
class Pawn(Piece):
# add boundary checking functions
def __init__(self, color, name):
self.sprite_dir = color + "Pawn.png"
self.name = name
self.color=color
super(Pawn,self)... |
# Author : Xiang Xu
# -*- coding: utf-8 -*-
def getCheckinTimes(infile, outfile):
inf = open(infile, 'r')
outf = open(outfile, 'w')
uid = ''
count = 0
outline = ''
for line in inf:
line = line.strip()
token = line.split('\t')
if token[0] != uid:
if outline... |
# Print all the words that appear in the text, one for each
# line. Words should be sorted in descending order of the
# number of occurrences in the text.
with open('input.txt') as inFile:
myFile = inFile.readlines()
myDict = {}
ans = {}
ans1 = []
for line in myFile:
myLine = line.split()
... |
import os
import os.path as op
import sys
import json
appengine_path = op.expanduser('~/dev/google_appengine')
sys.path.append(appengine_path)
import dev_appserver
dev_appserver.fix_sys_path() # otherwise fancy_urllib will not be found
service_account_key_path = op.join(op.abspath('.'), 'service_account_key.json')... |
from ED6ScenarioHelper import *
def main():
# 玛鲁加山道
CreateScenaFile(
FileName = 'R0300 ._SN',
MapName = 'Rolent',
Location = 'R0300.x',
MapIndex = 21,
MapDefaultBGM = "ed60022",
Flags = 0,
... |
import tkinter as tk
def textUpdate():
label.configure(text=entry.get())
def scaleUpdate(e):
label.configure(font=("", e))
root = tk.Tk()
label = tk.Label(root)
label.pack()
entry = tk.Entry(root)
entry.pack()
tk.Button(root, text="Update", command=textUpdate).pack()
tk.Scale(root, orient = 'h', from_ = 10,... |
# AdventOfCode 2019 day 2 pt 1
# https://adventofcode.com/2019/day/2
# start 7:19am
# started over at 7:37am confused af
# solved pt 1 8:19am
#
# AdventOfCode 2019 day 2 pt 2
# start pt2 8:55 - paused 9:30
# unpaused 13:30
# solved pt2 13:50
def calcPt1(intcode):
i = 0
while i < len(intcode):
opcode =... |
#!/usr/bin/python3
"""main.py: Holds the boilerplate code to show that this code solves
the 8 queens problem
"""
from queen import Queen
def main():
"""main: Code to show the 8 queens problem being solved
"""
for i in range(8):
solver = Queen(8)
print("Solution {0} - {1}".format(i + 1, so... |
INTRODUCTION = """# Coding Problems
This repository contains my solutions for various competitive programming problems.
Note: Not all source code offers a valid solution (yet). Most code does.
"""
from pathlib import Path
import re
ROOTS = {
"advent-of-code": Path("./problems/advent-of-code"),
"codechef": Pa... |
# Generated by Django 3.2.5 on 2021-07-12 22:28
from django.db import migrations
from django.conf import settings
def ensure_share_system_user(apps, schema_editor):
ShareUser = apps.get_model('share', 'ShareUser')
Source = apps.get_model('share', 'Source')
system_user = ShareUser.objects.filter(username... |
from django.db import models
class Sensor(models.Model):
name = models.CharField(max_length=50)
abbreviation = models.CharField(max_length=30)
description = models.TextField()
unit_of_measure = models.CharField(max_length=20)
picture = models.ImageField(upload_to="media/", null=True)
type = mo... |
from pwn import *
import sys
#config
context(os='linux', arch='i386')
context.log_level = 'debug'
FILE_NAME = "../bin/skywriting"
HOST = "2020.redpwnc.tf"
PORT = 31034
if len(sys.argv) > 1 and sys.argv[1] == 'r':
conn = remote(HOST, PORT)
else:
conn = process(FILE_NAME)
elf = ELF(FILE_NAME)
libc = ELF('../libc.s... |
import configparser
config = configparser.ConfigParser()
def read_property_file(section,key):
config.read('C:/Users/richa.anand/PycharmProjects/POM_Using_Pytest/Pom_Project/Config/config.properties')
sec = dict(config.items(section))
print(sec[key])
return sec[key]
|
# -*- coding: UTF-8 -*-
import kuva
from kuva import *
import kuvaaja
def piste(x, y, nimi = "", suunta = 0, piirra = True):
"""Piirtää pisteen (x, y). Nimi kirjoitetaan suuntaan 'suunta' (asteina).
Palauttaa pisteen (x, y)."""
P = (x, y)
if piirra: kuva.piste((x, y), nimi, suunta)
return P
def leikkauspis... |
#Programa: tiempo.py
#Propósito: Realiza un programa que reciba una cantidad de minutos y muestre por pantalla a cuantas horas y minutos corresponde.
#Autor: Jose Manuel Serrano Palomo.
#Fecha: 13/10/2019
#
#Variables a usar:
# mins serán los minutos que vamos a convertir en tiempo.
# horas,minutos son los resultados q... |
#!/usr/bin/env python3
# File Name: Report.py
# Created by: Vadim Lakhterman
# Date: 24.5.20
# Last Update: 25.5.20
import time
import os
import os.path
import Pattern
from Pattern import *
RESULTS_FOLDER = 'Results'
RESULTS_FILENAME = RESULTS_FOLDER + '/' + 'results'
TIME = time.strftim... |
#!/usr/bin/env python3
import os,sys,getopt,tarfile
import getpass
from distutils.spawn import find_executable
import time
import socket
import optparse
import subprocess
import multiprocessing
from swiftclient import Connection
from swiftclient import shell
from swiftclient import RequestException
from swiftclien... |
import os
from twilio.rest import Client
account_sid = os.environ["TWILIO_ACCOUNT_SID"]
auth_token = os.environ["TWILIO_AUTH_TOKEN"]
client = Client(account_sid, auth_token)
call=client.calls.create(
to="+19254781531",
from_=os.environ["TWILIO_SMS_FROM"],
twiml='<Response><Say>Howdy, Anne!"</Say></Response>',
url="h... |
import urllib.request
class Scraper(object):
def __init__(self, url):
self.url = url
def grab_contents(self):
self.bytes = urllib.request.urlopen(self.url)
self.data = self.bytes.read().decode('UTF-8')
self.
|
def cmpare(num2,prev):
county = 0
for i in range(len(prev)):
if num2[i]==prev[i]:
county+=1
if county == len(num2):
return True
else:
return False
#Fe
with open("spindownFe.txt","r") as f1, open("spinupdown_parsed.txt","w") as f2:
for line in f1:
numbers ... |
import os
from trie import Trie, _iter_nonempty
from string import Template, ascii_lowercase
from itertools import zip_longest
def escape(word):
word = word.lower()
encoded = ''
for char in word:
if char.isalnum():
encoded += char
else:
encoded += '-' + str(ord(char)) + '-'
return encoded
def un... |
import os
import shutil
def create():
path = raw_input("enter the path where u want to create a file: ") # location of file
try:
os.chdir(path) # changing directory
except OSError: ## error handling in case of that directory does nit exist
print "No such directory"
else:
name ... |
def get_platos_y_dinero():
"""Funcion que obtiene el numero de platos y el dienro a gastar"""
platos = input("Cuantos platos se sirven hoy? ")
dinero_disponible = input("Cuanto dinero va a gastar?: ")
return platos, dinero_disponible
prices = [1, 2, 4, 8, 16, 32, 64, 128, 256, 512] # creo una lis... |
#####################################################
## samples.tsv
# sample assembly descriptive_name cell
# CMC_ATAC hg38 CMC_ATAC CMC
# CMC_H3K27ac hg38 CMC_H3K27ac CMC
# KRT_p300 hg38 KRT_p300 KRT
#####################################################
## Snakefile
import os
import pandas as pd
configfile: "confi... |
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 11 14:41:16 2018
@author: JHodges
"""
import geopandas as gpd
import matplotlib.pyplot as plt
import gdal
import skimage.transform as skt
import numpy as np
from generate_dataset import GriddedMeasurement
import scipy.interpolate as scpi
import behavePlus as bp
import os... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.