repo_name
stringlengths
6
97
path
stringlengths
3
341
text
stringlengths
8
1.02M
gauchm/mlstream
mlstream/scaling.py
from pathlib import Path from typing import List import pandas as pd import numpy as np from .datautils import (load_forcings_lumped, load_discharge, load_static_attributes) class Scaler: def __init__(self): self.scalers = {} def normalize(self, feat...
larryyin/rectangular
rectangular.py
<filename>rectangular.py #!/usr/bin/env python from flask import Flask, jsonify, render_template, request app = Flask(__name__) from osgeo import ogr from osgeo import osr from osgeo import gdal from osgeo.gdalnumeric import * from osgeo.gdalconst import * import json import numpy as np import pandas as pd from scipy...
Harkor421/mono-rnn
scraper/dasmalwerk.py
import os from io import BytesIO from zipfile import ZipFile import requests from bs4 import BeautifulSoup def get_hrefs(): html = requests.get("https://das-malwerk.herokuapp.com").text soup = BeautifulSoup(html, "html.parser") rows = soup.find_all("tr")[1:] malware2href = {} for row in rows: ...
Harkor421/mono-rnn
dataset.py
<filename>dataset.py import os import pickle import torch from sklearn.model_selection import train_test_split from torch.utils.data import DataLoader, Dataset, Subset class MalwareDataset(Dataset): def __init__(self, benign_dir="data/benign", malware_dir="data/malware"): self.benign_dir = benign_dir ...
Harkor421/mono-rnn
train.py
import argparse import torch import models from utils import plot_confusion_matrix, train def main(args): device = torch.device("cuda" if torch.cuda.is_available() else "cpu") model = MalConvPlus(8, 4096, 128, 32).to(device) train(model, train_loader, val_loader, device, "malconv_plus") plot_confusi...
Harkor421/mono-rnn
scraper/eda.py
<gh_stars>10-100 import json import os from collections import Counter import matplotlib.pyplot as plt import pefile def walk(): len_count = [] for directory in ("benign", "malware"): data_dir = os.path.join("raw", directory) for file_name in os.listdir(data_dir): try: ...
Harkor421/mono-rnn
scraper/make_data.py
import json import os import pickle import time import pefile def main(): failed_files = [] for directory in ("benign", "malware"): data_dir = os.path.join("raw", directory) for file_name in os.listdir(data_dir): output_dir = os.path.join(directory, file_name) try: ...
Harkor421/mono-rnn
utils.py
<gh_stars>10-100 import os import random import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns import torch from sklearn.metrics import auc, confusion_matrix, roc_curve from torch import optim from torch.nn.functional import sigmoid from tqdm.auto import tqdm def set_seed(seed)...
Harkor421/mono-rnn
scraper/make_label.py
<filename>scraper/make_label.py<gh_stars>10-100 import csv import os def main(): dir = "raw" with open(os.path.join(dir, "labels.csv"), mode="w") as f: writer = csv.writer(f, delimiter=",") for file_name in os.listdir(dir): is_malware = len(file_name) > 31 writer.writer...
Harkor421/mono-rnn
models.py
import torch from torch import nn from torch.nn import functional as F class MalConvBase(nn.Module): def __init__(self, embed_dim, max_len, out_channels, window_size, dropout=0.5): super(MalConvBase, self).__init__() self.embed = nn.Embedding(257, embed_dim) self.dropout = nn.Dropout(dropo...
Harkor421/mono-rnn
scraper/malshare.py
import argparse import os import random import zipfile import requests from bs4 import BeautifulSoup def construct_href(link): root, rest = link.split("sample") action, hash_ = rest.split("detail") return f"{root}sampleshare{action}getfile{hash_}" def download(session, href, save_dir): source = ses...
violetguos/intro_machine_learning
a1/q1.py
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Tue Sep 26 13:16:31 2017 @author: vikuo """ from sklearn import datasets import matplotlib.pyplot as plt import numpy as np import random def load_data(): boston = datasets.load_boston() X = boston.data #506 row, 13 columns #print X.shape...
violetguos/intro_machine_learning
a2/code/q2_0.py
''' Question 2.0 Skeleton Code Here you should load the data and plot the means for each of the digit classes. ''' import data import numpy as np import matplotlib.pyplot as plt #import matplotlib.pyplot.imshow def mean_i_digit(i_digits): '''returns the mean for one digit, avg across ...
violetguos/intro_machine_learning
a2/code/q2_2.py
''' Question 2.2 Skeleton Code Here you should implement and evaluate the Conditional Gaussian classifier. ''' import data import numpy as np # Import pyplot - plt.imshow is useful! import matplotlib.pyplot as plt import json def mean_i_digit(i_digits): '''returns the mean for one digit, ...
violetguos/intro_machine_learning
a2/code/q2_1.py
<gh_stars>0 ''' Question 2.1 Skeleton Code Here you should implement and evaluate the k-NN classifier. ''' import data import numpy as np # Import pyplot - plt.imshow is useful! import matplotlib.pyplot as plt from sklearn.model_selection import KFold class KNearestNeighbor(object): ''' K Neare...
violetguos/intro_machine_learning
a1/q3.py
import numpy as np from sklearn.datasets import load_boston import matplotlib.pyplot as plt BATCHES = 50 ##################### #This is a program that # # class BatchSampler(object): ''' A (very) simple wrapper to randomly sample batches without replacement. You shouldn't need to touch this. '''...
violetguos/intro_machine_learning
a3/q2.py
import numpy as np from sklearn.datasets import fetch_mldata import matplotlib.pyplot as plt import math np.random.seed(1847) class BatchSampler(object): ''' A (very) simple wrapper to randomly sample batches without replacement. You shouldn't need to touch this. ''' def __init__(self, data...
violetguos/intro_machine_learning
a2/code/q2_3.py
<reponame>violetguos/intro_machine_learning ''' Question 2.3 Skeleton Code Here you should implement and evaluate the Naive Bayes classifier. ''' import data import numpy as np # Import pyplot - plt.imshow is useful! import matplotlib.pyplot as plt def binarize_data(pixel_values): ''' Binarize t...
violetguos/intro_machine_learning
a3/q1.py
<gh_stars>0 ''' Question 1 Skeleton Code ''' import sklearn import numpy as np from sklearn.model_selection import KFold from sklearn.datasets import fetch_20newsgroups from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer from sklearn.naive_bayes import BernoulliNB import sklearn.neighbors f...
violetguos/intro_machine_learning
a1/q2.py
<reponame>violetguos/intro_machine_learning<filename>a1/q2.py # -*- coding: utf-8 -*- """ Created on Tue Sep 12 20:39:09 2017 """ from __future__ import print_function import matplotlib.pyplot as plt import numpy as np from sklearn.datasets import load_boston np.random.seed(0) from scipy.misc import logsumexp ######...
catusf/tudienanhviet
bin/tab2opf.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # Script for conversion of Stardict tabfile (<header>\t<definition> # per line) into the OPF file for MobiPocket Dictionary # # For usage of dictionary convert it by: # (wine) mobigen.exe DICTIONARY.opf # or now... # kindlegen DICTIONARY.opf # # MobiPocket Reader at: www...
catusf/tudienanhviet
bin/create_english_inflections.py
<gh_stars>10-100 # from nltk.corpus import words from pattern.en import lexeme #conjugate, lemma, from pattern.en import pluralize # List of common English words wordlist = set(open("../misc/354984si.ngl").read().split()) keys = set(open("english_keys.txt", encoding='utf-8').read().split()) def getInflections(key):...
Candygoblen123/roboco
ytthings.py
import googleapiclient.discovery import googleapiclient.errors from pathlib import Path class apiAsker: def __init__(self): self.youtube = googleapiclient.discovery.build("youtube", "v3", developerKey=Path('youtubeapikey.txt').read_text()) def listId(self, id: str): return self.youtube.channels...
Candygoblen123/roboco
roboco.py
<reponame>Candygoblen123/roboco import asyncio from asyncio.tasks import sleep import json import re from typing import Dict, Set, Union, List import discord import discord_slash from util import * client = discord.Client(intents=discord.Intents.all(), activity=discord.Game(name='Send all complaints to yoyoyonono#55...
Unprocessable/pandas
pandas/tests/series/test_diff.py
<reponame>Unprocessable/pandas from pandas import ( Series ) from numpy import nan def test_diff(): data = Series([0,-1,-2,-3,-4,-3,-2,-1,0,-1,-1,0,-1,-2,-3,-2,0]) filtered = data.between(-2,0, inclusive = True) diff_boolean = filtered.diff() expected_boolean = Series([nan, False, False, True, Fa...
SunDoge/L-GCN
utils/__init__.py
import pandas as pd from .dictionary import Dictionary, CharDictionary import pickle from typing import Dict, List import torch import os import numpy as np # from torchpie.config import config MULTIPLE_CHOICE_TASKS = ['action', 'transition'] def load_csv_from_dataset(task: str, split: str) -> pd.DataFrame: retu...
SunDoge/L-GCN
scripts/build_tgif_cache.py
<gh_stars>10-100 import argparse import os import pickle from typing import Dict, Optional import pandas as pd import torch from torchtext import vocab from tqdm import tqdm from utils import load_csv_from_dataset from utils.dictionary import Dictionary, CharDictionary from utils.const import IGNORE_INDEX from typing...
SunDoge/L-GCN
utils/logging.py
import sys import logging from typing import Optional import os def set_default_logger(experiment_path: Optional[str], debug=False): log_format = '%(asctime)s|%(levelname)-8s| %(message)s' formatter = logging.Formatter(log_format) handlers = [] console_handler = logging.StreamHandler(sys.stdout) ...
SunDoge/L-GCN
scripts/split_n_parts.py
<reponame>SunDoge/L-GCN<filename>scripts/split_n_parts.py import os import numpy as np from typing import List from utils.io import dump_pickle import argparse from pathlib import Path # FRAME_PATH = '/mnt/dataset/tgif-qa/frames/' parser = argparse.ArgumentParser() parser.add_argument( '-f', '--frame-path', defa...
SunDoge/L-GCN
utils/config.py
from pyhocon import ConfigFactory from arguments import args config = ConfigFactory.parse_file(args.config)
SunDoge/L-GCN
utils/data.py
<filename>utils/data.py import os import pickle from glob import glob from PIL import Image from torch.utils.data import Dataset from torchvision import transforms as T from pprint import pprint from tqdm import tqdm class VideoDataset(Dataset): def __init__(self, root: str, extension='*.jpg'): self.roo...
SunDoge/L-GCN
utils/io.py
import json import pickle from PIL import Image, features # from torchpie.logging import logger import logging logger = logging.getLogger(__name__) logger.info(f'pillow version: {Image.PILLOW_VERSION}') logger.info( 'Using jpeg-turbo: {}'.format(features.check_feature('libjpeg_turbo'))) def load_json(filename: ...
SunDoge/L-GCN
scripts/merge_bboxes.py
import torch # from typed_args import TypedArgs import argparse import os from typing import Dict, List, NewType, Tuple from tqdm import tqdm from numpy.lib.format import open_memmap import numpy as np from utils.npy_file import NpyFile from utils.io import dump_pickle # class Args(TypedArgs): # def __init__(sel...
SunDoge/L-GCN
model/rnn.py
<gh_stars>10-100 import torch import torch.nn.functional as F from torch import nn from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence class RNNEncoder(nn.Module): def __init__( self, input_size: int, hidden_size: int, num_layers: int = 1, bidirectiona...
SunDoge/L-GCN
train.py
import logging import math import os import pickle import random from pprint import pprint from typing import Dict import numpy as np import pandas as pd # import ipdb import torch import torch.nn.functional as F from pyhocon import ConfigFactory from termcolor import colored from torch import nn, optim from torch.uti...
SunDoge/L-GCN
utils/npy_file.py
import math import os import pickle from functools import lru_cache import numpy as np from numpy.lib.format import open_memmap from typing import Tuple, List, Dict class NpyFile: def __init__(self, name: str, mode='r'): self.name = name self.index_path = os.path.join(name, 'indices.pkl') ...
SunDoge/L-GCN
scripts/extract_resnet152_features_with_bboxes.py
<gh_stars>10-100 import argparse import os import pickle from glob import glob from pprint import pprint import numpy as np import torch import torchvision.transforms as T from numpy.lib.format import open_memmap from PIL import Image from torch.utils.data import DataLoader, Dataset from torchvision.datasets import Im...
SunDoge/L-GCN
scripts/extract_resnet152_features.py
<gh_stars>10-100 import argparse import os import pickle from glob import glob from pprint import pprint import numpy as np import torch import torchvision.transforms as T from numpy.lib.format import open_memmap from PIL import Image from torch.utils.data import DataLoader, Dataset from torchvision.datasets import Im...
SunDoge/L-GCN
dataset/qa_pair.py
from typing import List class QAPair: def __init__(self, task: str): self.task = task def from_row(self, row): self.gif_name: str = row.gif_name self.question: str = row.question.lower() if self.task in ['action', 'trans']: self.answers: List[str] = [ ...
SunDoge/L-GCN
utils/checkpoint.py
import os import torch import shutil def save_checkpoint(state: dict, is_best=False, folder='', filename='checkpoint.pth.tar'): filename = os.path.join(folder, filename) torch.save(state, filename) if is_best: shutil.copyfile(filename, os.path.join(folder, 'model_best.pth.tar'))
SunDoge/L-GCN
arguments.py
<reponame>SunDoge/L-GCN import argparse import sys import time __ALL__ = ['args'] # class Args(TypedArgs): # def __init__(self): # parser = argparse.ArgumentParser() # self.experiment_path: Optional[str] = parser.add_argument( # '-e', # '--experiment-path', # t...
SunDoge/L-GCN
dataset/tgifqa_dataset.py
<reponame>SunDoge/L-GCN import os import pickle import random from logging import Logger import ipdb import numpy as np import torch from pyhocon import ConfigTree from torch.nn.utils.rnn import pad_sequence from torch.utils.data import DataLoader, Dataset, get_worker_info from typing import List from utils.npy_file ...
SunDoge/L-GCN
utils/const.py
<reponame>SunDoge/L-GCN MSVD_QTYPES = [ 'what', 'who', 'how', 'when', 'where' ] MSVD_QTYPE_DICT = {k: v for v, k in enumerate(MSVD_QTYPES)} # ingore index for crossentropy IGNORE_INDEX = -100
SunDoge/L-GCN
dataset/__init__.py
from logging import Logger from pyhocon import ConfigTree from torch.utils.data import DataLoader # from torchpie.environment import args from arguments import args from .tgifqa_dataset import collate_fn def get_dataloader(opt: ConfigTree, logger: Logger) -> (DataLoader, DataLoader): if opt.get_string('task') i...
SunDoge/L-GCN
scripts/merge_box_scores_and_labels.py
import torch from typed_args import TypedArgs, add_argument import argparse import os from typing import Dict, List, NewType, Optional from tqdm import tqdm from numpy.lib.format import open_memmap import numpy as np from utils.io import dump_pickle from dataclasses import dataclass SplitData = NewType('SplitData', D...
SunDoge/L-GCN
model/embedding.py
<gh_stars>10-100 import torch import torch.nn.functional as F from torch import nn # https://github.com/BangLiu/QANet-PyTorch/blob/master/model/QANet.py class Highway(nn.Module): def __init__(self, layer_num, size): super().__init__() self.n = layer_num self.linear = nn.ModuleList( ...
SunDoge/L-GCN
model/__init__.py
from torch import nn from pyhocon import ConfigTree from .lgcn import LGCN # from torchpie.config import config # from torchpie.logging import logger from utils.config import config import logging logger = logging.getLogger(__name__) def get_model( vocab_size: int, char_vocab_size: int, num_c...
SunDoge/L-GCN
model/lgcn.py
<reponame>SunDoge/L-GCN import torch import torch.nn.functional as F from pyhocon import ConfigTree from torch import nn # from torchpie.config import config # from torchpie.logging import logger from utils.config import config import logging logger = logging.getLogger(__name__) from .attention import BidafAttn from ...
SunDoge/L-GCN
utils/dictionary.py
import re import pickle from typing import Dict, List import spacy import numpy as np import torch class Dictionary: def __init__(self, word2idx=None, idx2word=None): if word2idx is None: word2idx = {'<pad>': 0, '<unk>': 1, '<eos>': 2} if idx2word is None: idx2word = list(w...
SunDoge/L-GCN
scripts/extract_bboxes_with_maskrcnn.py
import argparse import os from collections import defaultdict from typing import Dict, List import ipdb import torch import torchvision.transforms as T import torchvision.transforms.functional as F from torch import nn from torch.utils.data import DataLoader, Dataset from tqdm import tqdm from yacs.config import CfgN...
flatsurf/ipyvue-async
setup.py
<reponame>flatsurf/ipyvue-async # ****************************************************************************** # Copyright (c) 2021-2022 <NAME> <<EMAIL>> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # i...
flatsurf/ipyvue-async
ipyvue_async/__init__.py
<reponame>flatsurf/ipyvue-async #******************************************************************************* # Copyright (c) 2021 <NAME> <<EMAIL>> # # 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...
flatsurf/ipyvue-async
ipyvue_async/force_load.py
#******************************************************************************* # Copyright (c) 2021 <NAME> <<EMAIL>> # # 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 restriction, i...
flatsurf/ipyvue-async
ipyvue_async/comm_widget.py
#******************************************************************************* # Copyright (c) 2021 <NAME> <<EMAIL>> # # 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 restriction, i...
flatsurf/ipyvue-async
ipyvue_async/channel.py
<reponame>flatsurf/ipyvue-async<filename>ipyvue_async/channel.py #******************************************************************************* # Copyright (c) 2021 <NAME> <<EMAIL>> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (...
summerysaturn/archive
Midi-to-VirtualPiano/Midi to VirtualPiano.py
import sys keys = ["1", "!", "2", "\"", "3", "4", "$", "5", "%", "6", "^", "7", "8", "*", "9", "(", "0", "q", "Q", "w", "W", "e", "E", "r", "t", "T", "y", "Y", "u", "i", "I", "o", "O", "p", "P", "a", "s", "S", "d", "D", "f", "g", "G", "h", "H", "j", "J", "k", "l", "L", "z", "Z", "x", "c", "C", "v", "V", "b", "B", "n",...
summerysaturn/archive
BMP-Corruptor/image-corrupt.py
<gh_stars>0 #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ File Handling ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ import math, random def GoTo(linenum): global line line = linenum def convert_size(size_bytes): if size_bytes == 0: return "0B" size_name = ("B", "KB", "MB", "GB", "TB", "PB...
Jibanprakash/tensorflow
tensorflow/contrib/data/python/kernel_tests/reader_dataset_ops_test.py
<reponame>Jibanprakash/tensorflow # Copyright 2017 The TensorFlow 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-...
Jibanprakash/tensorflow
tensorflow/contrib/mixed_precision/python/loss_scale_optimizer.py
# Copyright 2018 The TensorFlow 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 applica...
Jibanprakash/tensorflow
tensorflow/python/keras/losses.py
<reponame>Jibanprakash/tensorflow # Copyright 2015 The TensorFlow 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-...
Jibanprakash/tensorflow
tensorflow/contrib/lite/python/lite_test.py
# Copyright 2018 The TensorFlow 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 applica...
Jibanprakash/tensorflow
tensorflow/contrib/distribute/python/combinations.py
<filename>tensorflow/contrib/distribute/python/combinations.py # Copyright 2018 The TensorFlow 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...
Jibanprakash/tensorflow
tensorflow/contrib/lite/python/convert_saved_model.py
<gh_stars>1-10 # Copyright 2018 The TensorFlow 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 requ...
Jibanprakash/tensorflow
tensorflow/contrib/eager/python/examples/l2hmc/l2hmc_test.py
# Copyright 2018 The TensorFlow 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 applica...
Jibanprakash/tensorflow
tensorflow/python/training/device_util_test.py
<reponame>Jibanprakash/tensorflow # Copyright 2015 The TensorFlow 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-...
Jibanprakash/tensorflow
tensorflow/contrib/distribute/python/cross_tower_utils.py
<gh_stars>10-100 # Copyright 2018 The TensorFlow 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 re...
artudi54/programs-integrator
programs_integrator/desktoputils/__init__.py
<reponame>artudi54/programs-integrator from programs_integrator.desktoputils.StructureMaker import *
artudi54/programs-integrator
programs_integrator/config/__init__.py
from programs_integrator.config.Config import * from programs_integrator.config.ApplicationDir import *
artudi54/programs-integrator
programs_integrator/ProgramsIntegrator.py
import sys import signal import pathlib import pkg_resources import dbus import dbus.bus import dbus.service import dbus.mainloop.glib from PySide2 import QtWidgets from PySide2 import QtCore from PySide2 import QtGui from programs_integrator.desktoputils import StructureMaker from programs_integrator.config import Con...
artudi54/programs-integrator
programs_integrator/config/UserApplicationDir.py
<reponame>artudi54/programs-integrator<gh_stars>1-10 from programs_integrator.config.ApplicationDir import ApplicationDir import pathlib class UserApplicationDir(ApplicationDir): def __init__(self, home_path: pathlib.Path): super().__init__() self.name = "UserApplications" self.path = home...
artudi54/programs-integrator
setup.py
#!/usr/bin/env python3 from setuptools import setup, find_packages setup( name="programs-integrator", version="0.2", author="<NAME>", author_email="<EMAIL>", description="Daemon program for dynamically generating 'Programs' directory", long_description=open("README.md").read(), long_descrip...
artudi54/programs-integrator
programs_integrator/user/__init__.py
<filename>programs_integrator/user/__init__.py from programs_integrator.user.ConfigDialog import ConfigDialog
artudi54/programs-integrator
programs_integrator/desktoputils/DesktopEntry.py
<filename>programs_integrator/desktoputils/DesktopEntry.py import pathlib import configparser class DesktopEntry: def __init__(self, path, ): self.path = path self.filename = self.path.name self.name = DesktopEntry._read_name(self.path) def is_valid(self): return self.name is ...
artudi54/programs-integrator
programs_integrator/__init__.py
from programs_integrator.ProgramsIntegrator import run, notify
artudi54/programs-integrator
programs_integrator/user/ConfigDialog.py
import pkg_resources import sortedcontainers import numpy from PySide2 import QtWidgets from PySide2 import QtCore from programs_integrator.user.SelfUiLoader import SelfUiLoader class ConfigDialog(QtWidgets.QDialog): config_changed = QtCore.Signal() update_requested = QtCore.Signal() def __init__(self, c...
artudi54/programs-integrator
programs_integrator/config/Config.py
import os import sys import contextlib import pathlib import configparser import distutils.util import numpy import sortedcontainers from programs_integrator.config.ApplicationDir import ApplicationDir from programs_integrator.config.UserApplicationDir import UserApplicationDir class Config: _SECTION_CONFIG = "Co...
artudi54/programs-integrator
programs_integrator/user/SelfUiLoader.py
from PySide2 import QtUiTools class SelfUiLoader(QtUiTools.QUiLoader): def __init__(self, widget): QtUiTools.QUiLoader.__init__(self, widget) self.widget = widget def createWidget(self, class_name, parent=None, name=''): if parent is None and self.widget: return self.widge...
artudi54/programs-integrator
programs_integrator/desktoputils/StructureMaker.py
import os import sys from programs_integrator.desktoputils.DesktopEntry import DesktopEntry class StructureMaker: class Programs: def __init__(self, configuration): self.path = configuration.user.home_path / "Programs" self.autostart_path = self.path / "Autostart" self....
artudi54/programs-integrator
programs_integrator/config/ApplicationDir.py
<filename>programs_integrator/config/ApplicationDir.py import pathlib class ApplicationDir: _MAPPING = { "/usr/share": "SystemApplications", "/usr/local/share": "LocalSystemApplications", "/var/lib/snapd/desktop": "SnapApplications" } def __init__(self, path: pathlib.Path = None):...
jbauermanncode/Curso_Em_Video_Python
Python_Exercicios/Mundo2/Repetições em Python (while)/python_056.py
''' Crie um programa que leia números inteiros pelo teclado. O programa só vai parar quando o usuário digitar o valor 999, que é a condição de parada. No final, mostre quantos números foram digitados e qual foi a soma entre elas (desconsiderando o flag). ''' # Iniciar as variaveis n = s = 0 contador = 0 # Laço whi...
jbauermanncode/Curso_Em_Video_Python
Python_Test/aula20a.py
def soma(a, b): print(f'A = {a} e B = {b}.') s = a + b print(f'A soma de A + B = {s}.') # Programa Principal soma(a=4, b=5) soma(b=8, a=9) soma(2, 1) # Empacotamento def contador(* num): for valor in num: print(f'{valor} ', end=' ') print('FIM!') tam = len(num) print(f'O total d...
jbauermanncode/Curso_Em_Video_Python
Python_Exercicios/Mundo2/Repetições em Python (for)/python_044.py
<reponame>jbauermanncode/Curso_Em_Video_Python<gh_stars>0 ''' Faça um programa que calcule a soma entre todos os números que são múltiplos de três e que se encontram no intervalo de 1 até 500. ''' # Acumulador para fazer a soma total s = 0 # Contador para ver quantos números foram somados c = 0 # Laço for para sa...
jbauermanncode/Curso_Em_Video_Python
Python_Exercicios/Mundo1/Utilizando Módulos/python_018.py
<reponame>jbauermanncode/Curso_Em_Video_Python ''' Faça um programa que leia um ângulo qualquer e mostre na tela o valor do seno, cosseno e tangente desse ângulo. ''' # Importar math library from math import radians, sin, cos, tan # Leia o ângulo angulo = float(input('Digite o valor de um ângulo: ')) # Calcular o...
jbauermanncode/Curso_Em_Video_Python
Python_Test/aula10b.py
<gh_stars>0 # Ler duas notas n1 = float(input('Digite a primeira nota: ')) n2 = float(input('Digite a segunda nota: ')) # Calcular a média das notas m = (n1 + n2) / 2 # Imprimir a média print('A sua média foi {:.1f}.'.format(m)) # Analisar a condição da média if m >= 6.0: print('Sua média foi boa! PARABÉNS') els...
jbauermanncode/Curso_Em_Video_Python
Python_Exercicios/Mundo1/Utilizando Módulos/python_017.py
<reponame>jbauermanncode/Curso_Em_Video_Python ''' Faça um programa que leia o comprimento do cateto oposto e do cateto adjacente de um triângulo retângulo, calcule e mostre o comprimento da hipotenusa. ''' # Importar math from math import hypot # Leia os catetos co= float(input('Valor do cateto oposto: ')) ca= fl...
jbauermanncode/Curso_Em_Video_Python
Python_Exercicios/Mundo3/Funções em Python/python_084.py
''' Faça um programa que tenha uma função notas() que pode receber várias notas de alunos e vai retornar um dicionário com as seguintes informações: – Quantidade de notas – A maior nota – A menor nota – A média da turma – A situação (opcional) '...
jbauermanncode/Curso_Em_Video_Python
Python_Exercicios/Mundo3/Tuplas em Python/python_060.py
''' Desenvolva um programa que leia quatro valores pelo teclado e guarde-os em uma tupla. No final, mostre: A) Quantas vezes apareceu o valor 9. B) Em que posição foi digitado o primeiro valor 3. C) Quais foram os números pares. ''' # Fazer uma Tupla ler 4 números n = (int(input('Digite um número: ')), int(...
jbauermanncode/Curso_Em_Video_Python
Python_Exercicios/Mundo1/Condições em Python (if..else)/python_028.py
<reponame>jbauermanncode/Curso_Em_Video_Python ''' Escreva um programa que faça o computador "pensar" em um número inteiro entre 0 e 5 e peça para o usuário tentar descobrir qual foi o número escolhido pelo computador. O programa deverá escrever na tela se o usuário venceu ou perdeu. ''' # Importar função randint d...
jbauermanncode/Curso_Em_Video_Python
Python_Exercicios/Mundo2/Condições em Python (if..elif)/python_038.py
<reponame>jbauermanncode/Curso_Em_Video_Python ''' Escreva um programa que leia dois números inteiros e compare- os, mostrando na tela uma mensagem: - O primeiro valor é maior - O segundo valor é maior - não existe valor maior, os dois são iguais ''' # Ler dois números inteiros n1 = int(input('In...
jbauermanncode/Curso_Em_Video_Python
Python_Test/aula14a.py
<reponame>jbauermanncode/Curso_Em_Video_Python<gh_stars>0 for c in range(1, 10): print(c) print('FIM') w = 1 while w < 10: print(w) w = w +1 print('FIM') for i in range(1, 5): n = int(input('Digite um número: ')) print('FIM') num = 1 while num != 0: num = int(input('Digite um número: ')) print('F...
jbauermanncode/Curso_Em_Video_Python
Python_Test/aula13.a.py
# Estrutura de Repetição for # Dando oi 6 vezes for c in range(0, 6): print('OI!!!') print('FIM!!!') print() # Contar de 1 a 6 for c in range(1, 7): print(c) print('FIM') print() # Contagem regressiva a partir de 6 for c in range(6, -1, -1): print(c) print('FIM') # Contar de 2 em 2 for c in range(0, 7, 2)...
jbauermanncode/Curso_Em_Video_Python
Python_Exercicios/Mundo1/Tipos Primitivos e Saída de Dados/python_007.py
<reponame>jbauermanncode/Curso_Em_Video_Python ''' Desenvolva um programa que leia as duas notas de um aluno, calcule e mostre a sua média. ''' # Ler notas n1 = float(input('Digite uma nota: ')) n2 = float(input('Digite outra nota: ')) # Calcular média m = float((n1 + n2)/2) # Imprimir média print('Nota da Prova: ...
jbauermanncode/Curso_Em_Video_Python
Python_Exercicios/Mundo2/Condições em Python (if..elif)/python_039.py
''' Faça um programa que leia o ano de nascimento de um jovem e informe, de acordo com a sua idade, se ele ainda vai se alistar ao serviço militar, se é a hora exata de se alistar ou se já passou do tempo do alistamento. Seu programa também deverá mostrar o tempo que falta ou que passou do prazo. ''' # Importar dat...
jbauermanncode/Curso_Em_Video_Python
Python_Exercicios/Mundo2/Repetições em Python (for)/python_043.py
''' Crie um programa que mostre na tela todos os números pares que estão no intervalo entre 1 e 50. ''' # Laço for para descobrir os numeros pares for i in range(1 + 1, 51, 2):# 1 + 1 para a contagem começar a partir de 2 print(i) print('Esses são os números pares de 1 a 50.') print() print('**'*40) print() # ...
jbauermanncode/Curso_Em_Video_Python
Python_Test/aula17.py
<filename>Python_Test/aula17.py print('Lista 1') num = [2, 5, 9, 1] print(num) print('*'*40) print('Lista 2') num[2] = 3 num.append(7) print(num) num.sort() print(num) print('*'*40) print('Lista 3') num.sort(reverse=True) print(num) num.insert(2, 0) print(num) print(f'Essa lista tem {len(num)} elementos.') print('*'*...
jbauermanncode/Curso_Em_Video_Python
Python_Exercicios/Mundo1/Tipos Primitivos e Saída de Dados/python_014.py
''' Escreva um programa que converta uma temperatura digitada em Celsius para Farenheit. ''' # Ler Temperatura c = float(input('Informe a temperatura em °C: ')) # Converter para °F f = ((9 * c) / 5) + 32 # Imprimir na tela print('A temperatura de {}°C corresponde a {}°F!'.format(c, f))
jbauermanncode/Curso_Em_Video_Python
Python_Exercicios/Mundo1/Utilizando Módulos/python_020.py
<reponame>jbauermanncode/Curso_Em_Video_Python<filename>Python_Exercicios/Mundo1/Utilizando Módulos/python_020.py ''' Sortear a ordem de apresentação de trabalhos dos alunos. Faça um programa que leia o nome dos quatro alunos e mostre a ordem sorteada. ''' # Importar Biblioteca Random from random import shuffle # ...
jbauermanncode/Curso_Em_Video_Python
Python_Exercicios/Mundo1/Tipos Primitivos e Saída de Dados/python_006.py
<reponame>jbauermanncode/Curso_Em_Video_Python<filename>Python_Exercicios/Mundo1/Tipos Primitivos e Saída de Dados/python_006.py ''' Crie um algoritmo que leia um número e mostre o seu dobro, triplo e raiz quadrada. ''' # Leia um número inteiro n = int(input('Digite um valor: ')) # Mostrar o dobro d = n * 2 # Mostra...
jbauermanncode/Curso_Em_Video_Python
Python_Test/aula12a.py
<filename>Python_Test/aula12a.py nome = str(input('Qual o seu nome: ')) if nome == 'Josué': print('Que nome bonito!') elif nome == 'Rosicléia' or nome=='Astolfo': print('Que nome feio!') elif nome == 'Maria' or nome == 'João' or nome == 'Pedro' or nome == 'Ana': print('Seu nome é bem popular!') elif nom...
jbauermanncode/Curso_Em_Video_Python
Python_Exercicios/Mundo3/Listas em Python/python_069.py
''' Faça um programa que leia nome e peso de várias pessoas, guardando tudo em uma lista. No final, mostre: A) Quantaspessoasforamcadastradas. ...