コード例 #1
0
ファイル: monitor.py プロジェクト: briantanner/Grepobot.py
	def update(self, server, monitor, data):
		# clone monitor so we don't overwrite settings
		_monitor = dict(monitor)

		# TODO: delete monitor
		# skip empty monitor
		if not _monitor['alliances']: return

		logging.info("Sending Updates to chat %s", monitor['chatname'])

		# filter updates, conquers, and changes per this monitor
		_monitor['updates'] = {k: data['updates'][str(k)] for k in _monitor['alliances'] if data['updates'][str(k)] != None}
		_monitor['conquers'] = {k: data['conquers'][str(k)] for k in _monitor['alliances'] if data['conquers'][str(k)] != None}
		_monitor['changes'] = {k: data['changes'][str(k)] for k in _monitor['alliances'] if data['changes'][str(k)] != None}

		# get chat for monitor
		chat = self._skype.Chat(monitor['chatname'])
		
		# send updates to chat
		if (_monitor['updates']):
			chat.SendMessage(Formatter.format_updates(server, _monitor['updates']))
		if (_monitor['conquers']):
			chat.SendMessage(Formatter.format_conquers(server, _monitor['conquers']))
		if (_monitor['changes']):
			chat.SendMessage(Formatter.format_changes(server, _monitor['changes']))
コード例 #2
0
 def print_progress(self):
     print("Average tfidf: " + str(1 - self.sum_tfidf / self.queries_asked))
     print("Average ngram-perplexity: " + str(self.sum_ngp / self.sentences_asked))
     print("Average edit-distance: " + str(self.sum_edit / self.queries_asked))
     print("Accept percent by tfidf extractor: " + Formatter.percent(self.accepted_by_tfidf / self.sentences_asked))
     print("Accept percent by ngram-perplexity extractor: " + Formatter.percent(self.accepted_by_ngp / self.sentences_asked))
     print("Accept percent by edit-distance extractor: " + Formatter.percent(self.accepted_by_edit_distance / self.sentences_asked))
コード例 #3
0
ファイル: plugin.py プロジェクト: jonspeicher/snore
class SnorePlugin(nose.plugins.Plugin):    
    """Enable Snarl notifications"""
    
    enabled = False
    name = "snore"
    score = 1
    
    def __init__(self, snarler, clock):
        super(SnorePlugin, self).__init__()
        self._formatter = Formatter(self._get_path('icons/'))
        self._snarler = snarler
        self._clock = clock
        
    def begin(self):
        self._start_time = self._clock.now()
        
    def finalize(self, result):
        counts = self._get_counts(result)
        title, icon = self._formatter.format_result(*counts)
        body = self._formatter.format_time(self._clock.now() - self._start_time)
        self._snarler.snarl(title, body, icon)
    
    def _get_counts(self, result):
        return (result.testsRun, len(result.failures), len(result.errors))
        
    def _get_path(self, filename):
        return pkg_resources.resource_filename('snore', filename)
コード例 #4
0
ファイル: models.py プロジェクト: chewable/ella
    def generate(self, save=True):
        "Generates photo file in current format"
        crop_box = None
        if self.crop_left:
            crop_box = (self.crop_left, self.crop_top, \
                    self.crop_left + self.crop_width, self.crop_top + self.crop_height)

        important_box = None
        if self.photo.important_top is not None:
            p = self.photo
            important_box = (p.important_left, p.important_top, p.important_right, p.important_bottom)

        formatter = Formatter(Image.open(self.photo.image.path), self.format, crop_box=crop_box, important_box=important_box)

        stretched_photo, crop_box = formatter.format()

        self.crop_left, self.crop_top, right, bottom = crop_box
        self.crop_width = right - self.crop_left
        self.crop_height = bottom - self.crop_top

        self.width, self.height = stretched_photo.size
        stretched_photo.save(self.file(), quality=self.format.resample_quality)

        f = open(self.file())
        file = ContentFile(f.read())
        f.close()

        self.image.save(self.file(relative=True), file, save)
コード例 #5
0
def main():
    """
    Get all questions, for each question get all the answers.
    :return:
    """

    print '|Getting questions from Stackoverflow. Please wait...|'
    items = list()
    questions = get_questions()
    print '|Total questions: {} |'.format(len(questions))
    if questions:
        for question in questions:
            formatter = Formatter()
            question.body = get_question_body(question.id)
            question.body_clean = formatter.beautify(question.body)
            question.answers = get_answers(question.id)             # Iterate over each question and get all answers

    print '|Display information'
    for question in questions:
        item = Item()
        if question.title and question.body_clean:
            item.text = question.title + ' ' + question.body_clean

        if question.answers:
            for answer in question.answers:
                item.text += ' ' + answer.body_clean
                item.text.rstrip('\r\n')
        items.append(item)
        print '<<'
        print item.text
コード例 #6
0
ファイル: worker.py プロジェクト: gauravmanchanda/Git-Janitor
 def delete_branches(self, remote=False):
     """Delete the branches."""
     """If Remote=True, deletes remote branches as well."""
     if len(self.branches_to_be_deleted()) > 0:
         self.delete_local_branches()
         if remote:
             self.delete_remote_branches()
         Formatter.print_pretty_ok_message("Cleaned Successfully!!")
コード例 #7
0
ファイル: jsca2js.py プロジェクト: pchlupacek/jsca2js
def formatMethods(namespace):
    formatter = Formatter(METHOD_INDENTATION)
    for method in namespace['methods']:
        formatter.add(generateMethodJSDoc(method))
        formatter.addLine('this.', convertIds(method['name']), ' = function(', formatParams(method['parameters']), ") {")
        formatter.addLine('};')
        formatter.newLine()
    return formatter.getResult()
コード例 #8
0
ファイル: jsca2js.py プロジェクト: Tsuguya/jsca2js
def formatGlobal(namespace):
    formatter = Formatter(METHOD_INDENTATION)

    for method in namespace['methods']:
        formatter.add(generateMethodJSDoc(method))
        formatter.addLine('function ', convertKey(method['name']), '(', formatParams(method['parameters']), ") {")
        formatter.addLine('}')
        formatter.newLine()
    return formatter.getResult()
コード例 #9
0
ファイル: jsca2js.py プロジェクト: Tsuguya/jsca2js
def extendGlobal(name, namespace):
    formatter = Formatter(METHOD_INDENTATION)

    for method in namespace['methods']:
        formatter.add(generateMethodJSDoc(method))
        formatter.addLine(name, '.prototype.', convertKey(method['name']), ' = function(', formatParams(method['parameters']), ") {")
        formatter.addLine('};')
        formatter.newLine()
    return formatter.getResult()
コード例 #10
0
ファイル: sengfmt2.py プロジェクト: cwins0r/sample-code
def main():
	lines = []
	for line in fileinput.input():
		lines.append(line)
	f = Formatter(lines)
	lines = f.get_lines()

	for l in lines:
		print (l)
コード例 #11
0
ファイル: jsca2js.py プロジェクト: Tsuguya/jsca2js
def formatMethods(namespace):
    formatter = Formatter(METHOD_INDENTATION)
    key = 'methods' if 'methods' in namespace else 'method'
    for method in namespace[key]:
        formatter.add(generateMethodJSDoc(method))
        formatter.addLine(convertKey(method['name']), ':function(', formatParams(method['parameters']), ") {")
        formatter.addLine('},')
        formatter.newLine()
    return formatter.getResult()
コード例 #12
0
ファイル: worker.py プロジェクト: gauravmanchanda/Git-Janitor
 def branches_to_be_deleted(self):
     """Return branches to be deleted."""
     branches = self.branches_to_be_deleted_excluding_skipped()
     if len(branches) > 0:
         Formatter.print_pretty_warn_message("Following local branches would \
             be deleted:")
         return branches
     else:
         Formatter.print_pretty_fail_message("No branches to be deleted")
         return []
コード例 #13
0
 def test_format_all(self):
   text = '''
   I HATE JUSTIN BIEBER comedy 
   I LOVE JUSTIN BIEBER comedy 
   JUSTIN BIEBER WEDDING comedy 
   JUSTIN BIEBER HAIR SOS 83 actress albino squirrel bored brittani taylor comedy entertainment fun funky funny happy hollywood hot justin bieber love missal random series sexy shout out sunday show silly sketch vampire vampires weekly 
   IS JUSTIN BIEBER CREEPY OR ADORABLE What Really Happened To Tiger Woods Criminal Names comedy newsinformation 
   Lady Gaga Alejandro Video Eats Rosary Miley Cyrus NO H**O Spellbound Wins BGT comedy newsinformation 
   Black Eyed Peas on winning their 2nd consecutive AMA 2010 abc aguilera american awards bieber black bon christina clark dick diddy diddydirty dirty divorce dream enrique eyed iglesias jovi justin katy milian money music peas perry pink productions rihanna talkinterview tay the usher 
   '''
   formatter = Formatter(text, "\n")
   words = formatter.run_all()
   expect(words).to.equal(set(['hate justin bieber comedy', 'black eyed peas winning their consecutive aguilera american awards bieber black christina clark dick diddy diddydirty dirty divorce dream enrique eyed iglesias jovi justin katy milian money music peas perry pink productions rihanna talkinterview usher', 'justin bieber creepy adorable what really happened tiger woods criminal names comedy newsinformation', 'lady gaga alejandro video eats rosary miley cyrus h**o spellbound wins comedy newsinformation', 'justin bieber hair actress albino squirrel bored brittani taylor comedy entertainment funky funny happy hollywood justin bieber love missal random series sexy shout sunday show silly sketch vampire vampires weekly', 'love justin bieber comedy', 'justin bieber wedding comedy']))
コード例 #14
0
ファイル: jsca2js.py プロジェクト: Tsuguya/jsca2js
def formatProperties(namespace):
    formatter = Formatter(METHOD_INDENTATION)
    for property in namespace['properties']:
        formatter.add(generatePropertyJSDoc(property))
        formatter.addLine(convertKey(property['name']), ':null,')
        formatter.newLine()
    return formatter.getResult()
コード例 #15
0
ファイル: models.py プロジェクト: andymccurdy/ella
    def _generate_img(self):
        crop_box = None
        if self.crop_left:
            crop_box = (self.crop_left, self.crop_top, \
                    self.crop_left + self.crop_width, self.crop_top + self.crop_height)

        important_box = None
        if self.photo.important_top is not None:
            p = self.photo
            important_box = (p.important_left, p.important_top, p.important_right, p.important_bottom)

        formatter = Formatter(self.photo._get_image(), self.format, crop_box=crop_box, important_box=important_box)

        return formatter.format()
コード例 #16
0
 def print_progress_summary(self):
     useful_lines = self.assigned_lines - self.unusable_lines
     print("(General corpora): Total lines scanned : " + str(self.scanned_lines))
     print("(General corpora): Lines assigned to worker: " + str(self.assigned_lines))
     print("(General corpora): Lines containing words: " + str(useful_lines))
     print("(General corpora): Extracted lines: " + str(self.extracted_lines))
     print("(General corpora): Sentence accept rate: " + Formatter.percent(self.extracted_lines / useful_lines))
コード例 #17
0
ファイル: player.py プロジェクト: briantanner/Grepobot.py
	def execute(self, msg, settings, args):
		m = msg.Chat.SendMessage('Fetching player stats...')
		
		# make api request
		url = '/{server}/player/{player}'.format(server=args[0], player=quote(' '.join(args[1:]).replace(" ", "+")))
		player = api.request(url)
		
		# update message with player stats
		m.Body = "{code}" + Formatter.format_player(player) + "{code}"
コード例 #18
0
ファイル: models.py プロジェクト: dedaluz/ella
    def generate(self):
        "Generates photo file in current format"
        crop_box = None
        if self.crop_left:
            crop_box = (self.crop_left, self.crop_top, \
                    self.crop_left + self.crop_width, self.crop_top + self.crop_height)

        important_box = None
        if self.photo.important_top:
            p = self.photo
            important_box = (p.important_left, p.important_top, p.important_right, p.important_bottom)

        formatter = Formatter(Image.open(self.filename), self.format, crop_box=crop_box, important_box=important_box)

        stretched_photo, crop_box = formatter.format()
        self.width, self.height = stretched_photo.size
        self.filename = self.file(relative=True)
        stretched_photo.save(self.file(), quality=self.format.resample_quality)
コード例 #19
0
def process_answer_items(content, beautify=True):
    """
    Process response and generate dictionary with questions and URL
    :param content:
    :param beautify:
    :return:
    """
    answers = list()
    if "items" in content:
        items = content["items"]
        for item in items:
            answer = Answer()
            answer.id = item['answer_id']
            answer.body = item['body']
            answer.is_accepted = item['is_accepted']
            if beautify:
                formatter = Formatter()
                answer.body_clean = formatter.beautify(answer.body)
            answers.append(answer)
    return answers
コード例 #20
0
 def __init__(self, width, height):
     self.width = 480
     self.height = 360
     self.cx = self.width / 2
     self.cy = self.height / 2
     self.buttons = {}
     self.textBoxes = {}
     self.checkBoxes = {}
     self.path = ""
     self.formatter = Formatter()
     self.running = False
コード例 #21
0
def format_file(input_file, output_file, param_file, error_file):

    f = Formatter(param_file)
    tags, errors = analyze_code(input_file)
    result = f.format(tags)

    directory = os.path.dirname(output_file)
    if directory != '' and not os.path.exists(directory):
        os.makedirs(directory)
    file = open(output_file, mode='w')
    file.write(result)
    file.close()

    directory = os.path.dirname(error_file)
    if directory != '' and not os.path.exists(directory):
        os.makedirs(directory)
    file = open(error_file, mode='w')
    for e in errors:
        file.write(str(e) + "\n")
    file.close()

    print('HTML file succesfuly formatted and written to', output_file,
          '\nErrors in:', error_file)
コード例 #22
0
def main():
	if len(sys.argv) == 1:
		raise Exception("Come one, at least one country, bro")

	if len(sys.argv) > 2:
		raise Exception("Just one argument please, bro")

	country = sys.argv[1]
	try:
		stats = api.fetchStats(country)
		formatted_text = Formatter.stringFrom(country, stats)
		print(formatted_text)
		
	except Exception as e:
		print('It\'s not a country, bro' + str(e))
コード例 #23
0
    def print_report(self):
        print "%s (Count = %s) " % (self.header, len(self.pull_requests))

        fields_tuple = self._build_tuple(
            ('URL', 'Title', 'Created', 'Last Updated (Days)', 'User'), '')
        if len(self.pull_requests) > 0:
            row_tuple = self._row_tuple(self.pull_requests[0])

            formatter = Formatter(fields_tuple, row_tuple,
                                  self._min_width_tuple())

            self.print_(formatter, fields_tuple)
            for pull in self.pull_requests:
                row_tuple = self._row_tuple(pull)
                self.print_(formatter, row_tuple)
コード例 #24
0
ファイル: report.py プロジェクト: Whale2021/Whale
    def print_report(self, print_comments=False):
        print "%s (Count = %s) " % (self.header, len(self.github_report.pull_requests))

        fields_tuple = ('JIRA ID', 'Pull Request', 'Jira Summary', 'JIRA Age',
                        'Pull Age', 'JIRA Update Age', 'Pull Update Age (Days)',
                        'JIRA Status', 'GitHub user')
        row_tuple = self._row_tuple(0)
        formatter = Formatter(fields_tuple, row_tuple)
        self.print_(formatter, fields_tuple)

        row_tuple_1 = ()
        formatter_1 = Formatter()

        if print_comments or self.print_comments:
            fields_tuple_1 = self._build_tuple(('Comment Vote', 'Comment Author', 'Pull URL', 'Comment Age'), '-\t\t')
            row_tuple_1 = self._build_tuple(self._row_tuple_1(*self._idx_1st_comment_with_vote()), '-\t\t')
            formatter_1 = Formatter(fields_tuple_1, row_tuple_1)
            self.print_(formatter_1, fields_tuple_1)
            print ''

        for p in range(0, len(self.github_report.pull_requests)):
            row_tuple = self._row_tuple(p)
            self.print_(formatter, row_tuple)

            if print_comments or self.print_comments:
                has_vote = False
                comments = self._jira_comments(self._jira_id(p))
                for c in range(len(comments)):     # Check cleaner way
                    comment = comments[c]
                    if comment.has_vote():
                        row_tuple_1 = self._build_tuple(self._row_tuple_1(p, c), '-\t\t')
                        if row_tuple_1 is not None:
                            self.print_(formatter_1, row_tuple_1)
                            has_vote = True
                if has_vote:
                    print ''
コード例 #25
0
    def _generate_img(self):
        crop_box = None
        if self.crop_left:
            crop_box = (self.crop_left, self.crop_top, \
                    self.crop_left + self.crop_width, self.crop_top + self.crop_height)

        important_box = None
        if self.photo.important_top is not None:
            p = self.photo
            important_box = (p.important_left, p.important_top, p.important_right, p.important_bottom)

        image = None
        if crop_box is None and self.format.master_id:
            try:
                fp = FormatedPhoto.objects.get(format=self.format.master_id, photo=self.photo)
                image = Image.open(fp.image)
            except FormatedPhoto.DoesNotExist:
                pass

        if image is None:
            image = self.photo._get_image()
        formatter = Formatter(image, self.format, crop_box=crop_box, important_box=important_box)

        return formatter.format()
コード例 #26
0
ファイル: models.py プロジェクト: whit/ella
    def generate(self, save=True):
        "Generates photo file in current format"
        crop_box = None
        if self.crop_left:
            crop_box = (self.crop_left, self.crop_top, \
                    self.crop_left + self.crop_width, self.crop_top + self.crop_height)

        important_box = None
        if self.photo.important_top is not None:
            p = self.photo
            important_box = (p.important_left, p.important_top,
                             p.important_right, p.important_bottom)

        formatter = Formatter(Image.open(self.photo.image.path),
                              self.format,
                              crop_box=crop_box,
                              important_box=important_box)

        stretched_photo, crop_box = formatter.format()

        # set crop_box to (0,0,0,0) if photo not cropped
        if not crop_box:
            crop_box = 0, 0, 0, 0

        self.crop_left, self.crop_top, right, bottom = crop_box
        self.crop_width = right - self.crop_left
        self.crop_height = bottom - self.crop_top

        self.width, self.height = stretched_photo.size
        stretched_photo.save(self.file(), quality=self.format.resample_quality)

        f = open(self.file(), 'rb')
        file = ContentFile(f.read())
        f.close()

        self.image.save(self.file(relative=True), file, save)
コード例 #27
0
ファイル: models.py プロジェクト: fragaria/ella
    def _generate_img(self):
        crop_box = None
        if self.crop_left:
            crop_box = (self.crop_left, self.crop_top, \
                    self.crop_left + self.crop_width, self.crop_top + self.crop_height)

        important_box = None
        if self.photo.important_top is not None:
            p = self.photo
            important_box = (p.important_left, p.important_top, p.important_right, p.important_bottom)

        image = None
        if crop_box is None and self.format.master_id:
            try:
                fp = FormatedPhoto.objects.get(format=self.format.master_id, photo=self.photo)
                image = Image.open(fp.image)
            except FormatedPhoto.DoesNotExist:
                pass

        if image is None:
            image = self.photo._get_image()
        formatter = Formatter(image, self.format, crop_box=crop_box, important_box=important_box)

        return formatter.format()
コード例 #28
0
ファイル: felow.py プロジェクト: lux-sol/felow
    def generate_text(self, weights, vocab, config, num, lines, temp,
                      document):
        applicator = Applicator()
        formatter = Formatter()
        generator = Generator()

        generator.set_weights(weights, vocab, config)
        generator.gen_text(num, lines, temp)
        gen_list = generator.get_text_list()

        formatter.set_sentlist(gen_list)
        formatter.frmt_textlist()
        format_text = formatter.get_text()
        applicator.apply_text(format_text, document)
コード例 #29
0
ファイル: main.py プロジェクト: Shevvv/NMR_reporter_-En-
def read_format_style(paragraphs, anchor):
    """
    Read the format style template for the spectra to be read/written.

    :param paragraphs: the spectra .docx document parsed into separate
    paragraphs.
    :param anchor: the keyword found at the beginning of a paragraph
    containing the necessary format template.

    :return: a `Formatter` object describing the format style for a spectrum.
    """

    for paragraph in paragraphs:
        if anchor in paragraph.text:
            raw_format = Block(paragraph, runs=True)[len(anchor):]
            # Clip the keyword and the space after it to be processed into a
            # `Formatter` object.
            return Formatter(raw_format)
    raise InputError('format template not located within the file')
コード例 #30
0
ファイル: logger.py プロジェクト: bogdan-cornianu/plp
 def __init__(self, config_file):
     if path.exists(config_file) and path.isfile(config_file):
         conf = ConfigReader(config_file)
         self.output = conf.get("output")
         self.output_file = conf.get("output_file")
         self.level = conf.get("level")
         self.__log_levels = {
             "debug": 10,
             "info": 20,
             "warning": 30,
             "error": 40,
             "critical": 50,
             }
         self.message_format = conf.get("message_format")
         self.date_format = conf.get("date_format")
         self.formatter = Formatter(
             self.level, self.message_format, self.date_format)
     else:
         raise IOError("Can't find configuration file.")
コード例 #31
0
    def process_request(self, update):
        action = update.get('action')
        issue = update['issue']
        if action == 'opened':
            author = issue['user']['login']
            number = issue['number']
            title = issue['title']
            text = issue['body']
            url = issue['html_url']
            message_text = 'Se ha creado una issue!\n'
            message_text += Formatter.format_issue(author, number, title, text,
                                                   url)
            for chat_id in self.chat:
                self.telegram.send_message(chat_id, message_text)

            error_text = self.seek_exception(text)
            if error_text:
                self.post_helpful_link(error_text, number)
        elif action == 'closed':
            self.check_googleable(issue)
コード例 #32
0
ファイル: cli.py プロジェクト: chris-lock/msvg
class Cli:
    def __init__(self, module_name, config, parser):
        self.__parser = parser
        self.formatter = Formatter(module_name)
        self.__option_parser = self.__get_option_parser(config, parser)

        self.formatter.option_parser = self.__option_parser

    def parse_args(self):
        return self.__option_parser.parse_args()

    def __get_option_parser(self, config, parser):
        option_parser = OptionParser(self.formatter.format(config.usage))

        self.__add_options(config, parser, option_parser)
        self.__add_option_groups(config, option_parser, parser)

        return option_parser

    def __add_options(self, group, parser, option_parser):
        for option in group.options:
            self.__add_option(parser, option, option_parser)

    def __add_option(self, parser, option, option_parser):
        kwargs = self.__get_option_kwargs(parser, option.kwargs)
        option_parser.add_option(*option.argv, **kwargs)

    def __get_option_kwargs(self, parser, kwargs):
        if "callback" in kwargs:
            kwargs["callback"] = getattr(parser, kwargs["callback"])

        return kwargs

    def __add_option_groups(self, config, option_parser, parser):
        for group in config.groups:
            self.__add_option_group(option_parser, group, parser)

    def __add_option_group(self, option_parser, group, parser):
        option_parser_group = OptionGroup(option_parser, group.title, group.description)
        self.__add_options(group, parser, option_parser_group)
        option_parser.add_option_group(option_parser_group)
コード例 #33
0
    def build_dashboard(self,
                        input_data={},
                        aligment={},
                        params={},
                        title="Stock Closing Prices",
                        ylabel='Price',
                        ylabel_right={},
                        show=True,
                        column='adj_close',
                        height=[],
                        **kwargs_to_bokeh):
        plots = []
        _data, x_range, _names = Formatter().format_input_data(
            input_data, column)
        _params = Formatter().format_params(_data, params, _names)
        _aligment = Formatter().format_aligment(aligment, _names)
        _y_label_right = Formatter().format_y_label_right(
            ylabel_right, ylabel, _names)
        kwargs_to_bokeh['y_axis_label'] = ylabel
        if 'x_range' not in kwargs_to_bokeh:
            kwargs_to_bokeh['x_range'] = Range1d(x_range[0], x_range[-1])
        if not height:
            height = [(1. / len(_data))] * len(_data)
        else:
            assert len(height) == len(_data), (
                "Number of heights should be equal to the number of plots. " +
                "expected: %s, " % len(_data) +
                "found: %s, len(height)= %s. " % (height, len(height)))
            assert sum(height) == 1, ("All heights should sum up to 1, " +
                                      "found: %s, sum(height)=%s" %
                                      (height, sum(height)))
        for i, (plot_title, data) in enumerate(_data.items()):
            plots.append(
                self._plot_stock(data=data,
                                 names=_names[plot_title],
                                 title=plot_title,
                                 params=_params[plot_title],
                                 aligment=_aligment[plot_title],
                                 ylabel_right=_y_label_right[plot_title],
                                 height=height[i],
                                 **kwargs_to_bokeh))

        layout = gridplot(plots, plot_width=self.width, ncols=self.ncols)
        self.layout = layout
        if show:
            curdoc().add_root(layout)
            curdoc().title = title
        return curdoc
コード例 #34
0
    def update_data(self, attrname, old, new):
        sliders_values = {}
        data_temp = {}
        result = {}
        for k, v in list(self.sliders.items()):
            sliders_values[k] = v.value
        for i, __data_source in enumerate(self.sdb.datasources):
            for name in list(__data_source.data.keys()):
                if re.findall("\(\w+\)", name):
                    raise (ValueError("Variable should not contain " +
                                      "plain parentheses. "
                                      "If included use '\(' and '\)'." +
                                      "Found: %s" % name))
                if len(__data_source.data[name]) > 1:
                    data_temp[name] = pd.Series(
                        copy.deepcopy(__data_source.data[name]),
                        index=copy.deepcopy(__data_source.data['x']))
                else:
                    data_temp[name] = copy.deepcopy(__data_source.data[name])

        if not hasattr(self, 'signal_expressions_formatted'):
            self._format_signal_expressions(data_temp)
        # Run twice since some singals depends on others
        for i in range(2):
            for signal_name, expr in list(self.signals_expressions.items()):
                result[signal_name] = eval(
                    self.signals_expressions_formatted[signal_name])
                # Update result in data_temp. If it is not dependent
                # of other variable signal, this result won't change.
                data_temp[signal_name] = result[signal_name]

        for i, __data_source in enumerate(self.sdb.datasources):
            for name in result:
                if name in __data_source.data:
                    (__data_source.data['x'],
                     __data_source.data[name]) = copy.deepcopy(
                         Formatter._get_x_y(result[name]))
コード例 #35
0
    def __init__(self,inputFile):
        self.file = inputFile
        with open(self.file) as f:
            lines = f.read().splitlines() #splitlines() gets rid of \n
        f.close()
        self.content = lines
        
        self.originalLength = len(self.content)

        self.testContent = []
        testSize = int(.15 * self.originalLength)
        for i in range(0,testSize):
            self.testContent.append(self.content.pop())
            
        labelList = []
        self.attributeList = []
        if self.file == "mushroom.data":
            self.attributeList, labelList = Formatter.separate_mushroom(self.content)
        else:
            for line in self.content:
                attributes = line.split(",")
                attributes = attributes[:-1]
                self.attributeList.append(attributes)
            self.attributeList = np.array(self.attributeList, dtype=float)
コード例 #36
0
def getInput():
    text = []
    filename = None
    with fileinput.input() as f:
        for line in f:
            if (f.filename() != None):
                filename = f.filename()
                break
            else:
                text.append(line)
    if (filename != None):
        f = Formatter(filename=filename)
        t = f.get_lines()
        print_out(t)
    else:
        f = Formatter(inputlines=text)
        t = f.get_lines()
        print_out(t)

    fileinput.close()
コード例 #37
0
        elif format == 'web':
            outname = m.htmlname

        if verb:
            print "mdoc: generating %s from %s" % (outname, m.path)

        # extract comment block from file
        (lines, func, brief) = extract(m.path)

        m.brief = brief

        # Run formatter
        content = ""
        if len(lines) > 0:
            if format == 'wiki':
                formatter = Formatter(lines, linkdict, 'wiki')
            else:
                formatter = Formatter(lines, linkdict, 'a')

            content = formatter.toDOM().toxml("UTF-8")
            content = content[content.find('?>') + 2:]

        # add decorations
        if not format == 'wiki':
            content = breadCrumb(m) + content

        if format == 'web':
            content = "<group>\n" + content + "</group>\n"

        # save the result to an html file
        if format == 'wiki':
コード例 #38
0
ファイル: felow.py プロジェクト: lux-sol/felow
    def format_text(self, text, document, formatting):
        par_len = 150

        applicator = Applicator()
        cleaner = Cleaner()
        formatter = Formatter()
        new_text = self.get_string(text)

        cleaner.create_sentc_list(new_text)
        sentc_list = cleaner.get_sentc_list()
        formatter.set_sentlist(sentc_list)

        if formatting == "list":
            formatter.frmt_textlist()

        elif formatting == "block":
            formatter.frmt_textblock(par_len=par_len)

        elif formatting == "string":
            formatter.frmt_textstring()

        else:
            print("format not supported")
            raise SystemExit

        format_text = formatter.get_text()
        applicator.apply_text(format_text, document=document)
コード例 #39
0
ファイル: jsca2js.py プロジェクト: Tsuguya/jsca2js
def generateMethodJSDoc(method):
    formatter = Formatter(METHOD_INDENTATION)
    formatter.addLine('/**')

    prefix = ' * '

    if KEYS['value'] in method:
        formatter.addLine(prefix, method[KEYS['value']])

    if 'platforms' in method and 'since' in method:
        formatter.addLine(prefix, 'platforms: ', ', '.join(getPlatforms(method['platforms'])))

    for param in method['parameters']:
        formatter.addLine(prefix, '@param {', formatType(param['type']), '} ',
            convertIds(param['name']), ' ', (param[KEYS['description']] if KEYS['description'] in param else param['description'] ) or '')

    if 'returntype' in method and method['returntype'] == 'void':
        formatter.addLine(prefix, '@returns ', method['returntype'])
    elif 'returns' in method:
        returns = method['returns']
        if type(returns) is list:
            for ret in returns:
                if ret['type'] != 'void':
                    formatter.addLine(prefix, '@returns ', formatReturn(ret))
        elif returns['type'] != 'void':
            formatter.addLine(prefix, '@returns ', formatReturn(returns))

    sinceVer = formatSince(method)
    if sinceVer:
        formatter.addLine(prefix, '@since ', sinceVer)

    formatter.addLine(' */')

    return convertLinks(formatter.getResult())
コード例 #40
0
ファイル: trainer.py プロジェクト: wkddnjset/KBOPrediction
if __name__ == '__main__':
    args = parser.parse_args()

    # ====== Open data file ======
    file_name = ''
    if args.year == 2017:
        file_name = DATA_17
    elif args.year == 2016:
        file_name = DATA_16
    f = open(DIRNAME + "/" + file_name, 'r')
    print("Loading JSON data")
    data = json.load(f)

    print("Preprocessing the data")
    # formatter class that contains trainX, trainY, testX, testY for individual teams
    formatter = Formatter(data, args.train_size, args.sequence_length)
    trainX_home, trainX_away, trainY, testX_home, testX_away, testY = formatter.get_data(
    )

    ## ======== Build model ======
    with tf.Session() as sess:
        kbo_pred_model = SeLuModel(sess,
                                   args.model_name,
                                   learn_rate=args.learn_rate,
                                   sequence_length=args.sequence_length)

        ## ======== Train model ======
        print("Started the training...")
        kbo_runner = Runner()
        kbo_runner.train_run(kbo_pred_model,
                             trainX_home,
コード例 #41
0
ファイル: course.py プロジェクト: donny-chan/gpa-calculator
 def formatted_str(self):
     return Formatter.course_row(self._id, self.name, self.credit,
                                 self.grade, self._type, self.sem)
コード例 #42
0
ファイル: jsca2js.py プロジェクト: jvandijk/jsca2js
def formatMethods(namespace):
    formatter = Formatter(METHOD_INDENTATION)
    key = 'methods' if 'methods' in namespace else 'method'
    for method in namespace[key]:
        formatter.add(generateMethodJSDoc(method))
        formatter.addLine(convertKey(method['name']), ':function(',
                          formatParams(method['parameters']), ") {")
        formatter.addLine('},')
        formatter.newLine()
    return formatter.getResult()
コード例 #43
0
ファイル: jsca2js.py プロジェクト: jvandijk/jsca2js
def generateNamespaceJSDoc(namespace):
    formatter = Formatter()
    formatter.addLine('/**')

    prefix = ' * '
    if 'notes' in namespace and namespace['notes']:
        formatter.addLine(prefix, 'Notes: ', namespace['notes'])

    if 'platforms' in namespace:
        formatter.addLine(prefix, 'platforms: ',
                          ', '.join(getPlatforms(namespace['platforms'])))
    if namespace['description']:
        formatter.addLine(prefix, '@namespace ', namespace['description'])
    if 'since' in namespace:
        formatter.addLine(prefix, '@since ', namespace['since'])

    if 'examples' in namespace:
        for example in namespace['examples']:
            formatter.addLine(prefix)
            formatter.addLine(prefix, '@example ', example['description'])
            formatter.addLine(prefix, example['code'])

    formatter.addLine(' */')
    return convertLinks(formatter.getResult())
コード例 #44
0
ファイル: jsca2js.py プロジェクト: jvandijk/jsca2js
def generateMethodJSDoc(method):
    formatter = Formatter(METHOD_INDENTATION)
    formatter.addLine('/**')

    prefix = ' * '

    if KEYS['value'] in method:
        formatter.addLine(prefix, method[KEYS['value']])

    if 'platforms' in method and 'since' in method:
        formatter.addLine(prefix, 'platforms: ',
                          ', '.join(getPlatforms(method['platforms'])))

    for param in method['parameters']:
        formatter.addLine(prefix, '@param {', formatType(param['type']), '} ',
                          convertIds(param['name']), ' ',
                          (param[KEYS['description']] if KEYS['description']
                           in param else param['description']) or '')

    if 'returntype' in method and method['returntype'] == 'void':
        formatter.addLine(prefix, '@returns ', method['returntype'])
    elif 'returns' in method:
        returns = method['returns']
        if type(returns) is list:
            for ret in returns:
                if ret['type'] != 'void':
                    formatter.addLine(prefix, '@returns ', formatReturn(ret))
        elif returns['type'] != 'void':
            formatter.addLine(prefix, '@returns ', formatReturn(returns))

    sinceVer = formatSince(method)
    if sinceVer:
        formatter.addLine(prefix, '@since ', sinceVer)

    formatter.addLine(' */')

    return convertLinks(formatter.getResult())
コード例 #45
0
# file settings
parser.add_argument('--raw-data-dir',
                    default='./raw_data',
                    help='directory containing raw data')
parser.add_argument('--data-dir',
                    default='./data',
                    help='directory to write formatted data to')
parser.add_argument('--threshold',
                    default='20',
                    help='threshold for relevant counties')

args = parser.parse_args()

# run
formatter = Formatter(args)

## First, we load the data and identify some counties we're interested in
## Let's go with King County, WA (where the first US case was identified), and WESTCHESTER
infections = pd.read_csv(
    join(formatter.raw_data_dir,
         'national/USAfacts_infections/covid_confirmed_usafacts_aligned.csv'))
deaths = pd.read_csv(
    join(formatter.raw_data_dir,
         'national/USAfacts_infections/covid_deaths_usafacts_aligned.csv'))
fips = [53033, 36119]

## Extract the features from those counties
national_data = formatter.parse_national_data()
king_data = national_data[str(fips[0])]
westchester_data = national_data[str(fips[1])]
コード例 #46
0
class MP3k(Widget):
    playlist_width = NumericProperty()

    def __init__(self, **kwargs):
        Globals.CONFIG = App.get_running_app().config
        Globals.TESTING = Globals.CONFIG.get('Development', 'test_mode')

        self.playlist_width = int(
            Globals.CONFIG.get('Playlist', 'playlist_width'))

        Globals.API = GoogleMusicApi()
        self.login_failed_popup = None
        self.google_music_api_login()

        self.formatter = Formatter()

        self.player = Player()
        self.player.set_streaming_quality(
            Globals.CONFIG.get('Google Play Music', 'quality').split(':')[0])

        self.playlist = Playlist()

        self.librarymanager = LibraryManager()
        # self.librarymanager.load_library()

        self.history = History()
        self.playlist.queue = self.history.playlist_history

        self.updating_progress = False
        self.playlist_hidden = False

        super().__init__(**kwargs)
        self.player.bind(playing=self.update_play_button_state)
        self.player.bind(progress_percent=self.update_progress_slider)

        # Add search result views
        # Songs
        self.songlist = SongViewer()

        # Stations
        # self.stationlist = StationViewer()
        self.stationscroll = ScrollView(size_hint=(1, 1))
        self.stationscroll.do_scroll_x = False
        self.stationlist = StackLayout(size_hint_y=None, spacing=10)
        self.stationlist.bind(minimum_height=self.stationlist.setter('height'))
        self.stationscroll.add_widget(self.stationlist)

        # Albums
        self.albumlist = AlbumViewer()
        # Create and init screen manager
        self.sm = ScreenManager()
        self.init_screens()

        # Listen for Keyboard events
        self._keyboard = Window.request_keyboard(None, self, 'text')
        self._keyboard.bind(on_key_down=self._pressed_key)
        self.searchbar.focus = True

    def google_music_api_login(self):
        if Globals.API.login(
                Globals.CONFIG.get('Google Play Music', 'login'),
                Globals.CONFIG.get('Google Play Music', 'password'),
                Globals.CONFIG.get('Google Play Music', 'device_id')):
            Logger.debug('Google Music: Login successful')
            if self.login_failed_popup:
                self.login_failed_popup.dismiss()
                self.login_failed_popup = None
        else:
            Logger.warning("Google Music: Login Failed")
            if not self.login_failed_popup:
                popup = Popup(title='Google Play Music™ login',
                              content=LoginCredentials(),
                              auto_dismiss=False,
                              size_hint=(1, 1))
                self.login_failed_popup = popup

            if Globals.STARTED:  # login failed after configuration change
                self.login_failed_popup.open(
                )  # open popup because MP3k is completely rendered
                App.get_running_app().close_settings()

            else:  # login failed on start
                pass  # wait with popup until MP3k is completely rendered (MP3kApp opens the popup in on_start())

    def try_login_step_1(self, instance, google_login, google_password):
        # Credentials login without device ID
        if Globals.API.login(google_login, google_password, ''):
            # login successful
            Globals.CONFIG.set('Google Play Music', 'login', google_login)
            Globals.CONFIG.set('Google Play Music', 'password',
                               google_password)
            Globals.CONFIG.write()

            self.show_device_login()

        else:
            instance.login_failed_label.color = (1, 0, 0, 1)

    def try_login_step_2(self, button_container):
        # look for selected device
        for button in button_container.children:
            if button.state == 'down':  # got it
                Globals.CONFIG.set('Google Play Music', 'device_id',
                                   button.device_id)
                Globals.CONFIG.write()  # set device id in config

                if Globals.API.relogin(
                        Globals.CONFIG.get(
                            'Google Play Music',
                            'login'),  # re-login with valid device_id
                        Globals.CONFIG.get('Google Play Music', 'password'),
                        Globals.CONFIG.get('Google Play Music', 'device_id')):
                    self.login_failed_popup.dismiss()
                    break
        else:
            Logger.error('LOGIN: You have to select a device!')

    def show_device_login(self):
        self.login_failed_popup.dismiss()
        self.login_failed_popup = Popup(title='Google Play Music™ login',
                                        content=self.build_devices_login(),
                                        auto_dismiss=False,
                                        size_hint=(1, 1))
        self.login_failed_popup.open()

    @staticmethod
    def build_devices_login():
        devices = Globals.API.get_registered_mobile_devices(
        )  # get registered mobile devices
        login_devices = LoginDevices()

        # add buttons for devices
        for device in devices:
            btn = DeviceButton(text='{} (ID: {})'.format(
                device['name'], device['id']),
                               device_id=device['id'],
                               size_hint_y=None,
                               height=30,
                               group='devices')
            login_devices.device_button_container.add_widget(btn)

        return login_devices

    def init_screens(self):

        # Create screens
        screen_songs = Screen(name='Songs', size_hint=(1, 1))
        screen_stations = Screen(name='Stations', size_hint=(1, 1))
        screen_albums = Screen(name='Albums', size_hint=(1, 1))

        # Add content to screens
        screen_songs.add_widget(self.songlist)
        # screen_stations.add_widget(self.stationlist)
        screen_stations.add_widget(self.stationscroll)
        screen_albums.add_widget(self.albumlist)

        # Add screens
        self.sm.add_widget(screen_songs)
        self.sm.add_widget(screen_stations)
        self.sm.add_widget(screen_albums)

        # Add screen manager and playlist
        self.screenmanagercontainer.add_widget(self.sm)

    def _pressed_key(self, keyboard, keycode, text, modifiers):
        if not self.searchbar.focus:
            if keycode[1] == 'spacebar' or keycode[0] == 1073742085:
                Logger.debug('Keyboard: Pressed spacebar/play-pause-media-key')
                self.playbutton_callback()
            elif keycode[0] == 1073742083:  # 'previous track' media key
                Logger.debug("Keyboard: Pressed 'previous track' media key")
                self.previousbutton_callback()
            elif keycode[0] == 1073742082:  # 'next track' media key
                Logger.debug("Keyboard: Pressed 'next track' media key")
                self.nextbutton_callback()
            #else:
            #    print(keycode)

    def update_play_button_state(self, instance, value):
        if value:
            self.playbutton.icon = '../res/icons/glyphicons-175-pause_white.png'
        else:
            self.playbutton.icon = '../res/icons/glyphicons-174-play_white.png'

    def update_progress_slider(self, instance, value):
        self.progress_slider.value = value

    def update_playlist_position(self, window, width, height):
        self.playlist_view.pos_hint = {'x': .3, 'y': 90.0 / height}

    def update_playlist_view(self, instance, value):
        print('Updating playlist..')
        print('data_queue before: ' + str(len(self.playlist_view.data_queue)))
        # self.playlist_view.data_queue = self.playlist.queue  # ListView should be updated if we do it like this..
        self.playlist_view.children[0].adapter.data.clear(
        )  # ..but it isn't, so we do this
        self.playlist_view.children[0].adapter.data.extend(
            self.playlist.queue)  # and then this
        # self.playlist_view.content.listview.adapter.data = self.playlist.queue  # never do this, it replaces the
        # ObservableList and breaks kivy functionality
        print('data_queue after: ' + str(len(self.playlist_view.data_queue)))

    def _update_progress_interval(self, delta_time):
        if not self.updating_progress:
            self.updating_progress = True

            if self.player.current_track and self.player.playback_started and self.player.playing:
                # time_played_ms = pygame.mixer.music.get_pos()
                # duration_ms = int(self.musicmanager.current_track['duration_ms'])
                # progress = time_played_ms / (duration_ms / 100)

                progress_percent = self.player.send_cmd_to_mplayer(
                    'get_percent_pos', 'ANS_PERCENT_POSITION')
                if progress_percent is not False and progress_percent is not None:
                    old_progress_percent = self.player.progress_percent
                    self.player.progress_percent = interpolate(
                        old_progress_percent, int(progress_percent))
                    Logger.trace('Progress: ' +
                                 str(self.player.progress_percent))
                elif progress_percent is False:
                    Logger.debug('_update_progress_interval: Received ' +
                                 str(progress_percent) + ' as progress')
                    self.player.playback_finished()
                    self.play_next_track()
                else:
                    Logger.debug('_update_progress_interval: Received ' +
                                 str(progress_percent) + ' as progress')

            # remove schedule if no track selected
            elif not self.player.playback_started and not self.player.playing:
                Logger.debug(
                    'No song playing, removing slider update interval..')
                self.updating_progress = False
                return False

            self.updating_progress = False

    def on_config_changed(self, section, key, value):
        Logger.debug('Config: Config changed')

        if key == 'playlist_width':
            self.playlist_width = int(value)

        elif section == 'Google Play Music':
            Globals.API.logout()
            self.google_music_api_login()

        elif section == 'Development':
            if key == 'test_mode':
                Globals.TESTING = True if value == '1' else False

    def fix_scrolling_workaround(self):
        self.playlist_view.listview._reset_spopulate()

    def playbutton_state(self):
        Logger.debug('Playbuttonstate: ' + self.playbutton.state)
        return 'down' if self.player.playing else 'normal'

    def mark_playing_track(self):
        # track_item = self.playlist_view.get_track(0)
        # track_item.update_image('../res/icons/equalizer.gif')
        playing_text = '{} - {}'.format(self.player.current_track['title'],
                                        self.player.current_track['artist'])

        self.playinglabel.text = playing_text
        App.get_running_app().title = playing_text

    def restart_track(self):
        Logger.info('Restarting track..')
        self.play_track(self.player.current_track)

    def play_previous_track(self):
        Logger.info('Playing previous track')
        track = self.playlist.get_previous_track()
        if track:
            self.play_track(track)

    def play_next_track(self):
        Logger.info('Playing next track')
        track = self.playlist.get_next_track()
        if track:
            self.play_track(track)
        else:
            App.get_running_app(
            ).title = 'MusicPlayer 3000 for Google Play Music™'

    def switch_screen_callback(self, screen_title):
        self.sm.current = screen_title

    def play_callback(self, track, index):
        Logger.debug('Playing from songlist (left): Index ' + str(index))
        self.playlist.add_track_and_set_current(track)
        self.fix_scrolling_workaround()
        self.play_track(track)

    def play_album_callback(self, album_id):
        index = len(self.playlist.queue)
        self.add_album_to_playlist_callback(album_id)
        idx, track = self.playlist.set_current_track(index)
        self.play_track(track)

    def play_from_playlist_callback(self, track, index):
        Logger.debug('Playing from playlist (right): Index ' + str(index))
        self.playlist.set_current_track(index)
        self.play_track(track)

    def play_track(self, track):
        Logger.info('Playing track: ' + track['title'])
        self.player.play_track_from_id(track)
        self.mark_playing_track()
        # self.set_playing_icon()
        # unschedule possible previous intervals
        Clock.unschedule(self._update_progress_interval)
        # start interval for updating the progress slider
        Clock.schedule_interval(self._update_progress_interval, .1)

    def set_playing_icon(self):
        index, current_track = self.playlist.get_current_track()
        # self.playlist_view.children[0].adapter.data[index]

    def playbutton_callback(self):
        if self.player.current_track:  # we have a track selected
            if self.player.playback_started and self.player.playing:  # pause track
                self.player.pause_current_track()
            elif self.player.playback_started and not self.player.playing:  # resume track
                self.player.resume_current_track()
            else:  # playback has finished, restart track
                self.restart_track()
        else:  # No track selected but maybe we have elements in the playlist
            Logger.debug('No current track set!')
            track = self.playlist.get_start()
            if track:
                self.play_track(track)
            else:  # do nothing if no track selected
                #self.librarymanager.synchronize_library()
                pass

    def nextbutton_callback(self):
        if self.player.current_track:  # we have a track selected
            self.play_next_track()
        else:  # No track selected but maybe we have some in the playlist
            Logger.debug('No current track set!')
            track = self.playlist.get_start()
            if track:
                self.play_track(track)
            else:  # do nothing if no track selected
                pass

    def previousbutton_callback(self):
        if self.player.current_track:  # we have a track selected
            self.play_previous_track()
        else:  # No track selected but maybe we have some in the playlist
            Logger.debug('No current track set!')
            track = self.playlist.get_start()
            if track:
                self.play_track(track)
            else:  # do nothing if no track selected
                pass

    def shufflebutton_callback(self):
        if self.playlist.shuffle:
            Logger.info("I won't shuffle anymore..")
            self.playlist.shuffle = False
            self.shufflebutton.source = self.shufflebutton.source_img_alt
        else:
            Logger.info("Everyday I'm shuffling..")
            self.playlist.shuffle = True
            self.shufflebutton.source = self.shufflebutton.source_img

    def skip_callback(self, touch_pos):
        width = self.progress_slider.width
        touch_pos_x = touch_pos[0]
        position = touch_pos_x / (width / 100)
        if self.player.current_track:  # we need a track to skip into
            if not self.player.playback_started:  # song is not playing, restart song
                self.restart_track()
            self.player.skip_track_to(position)  # skip to position
        else:
            # self.progress_slider.value = 0  # keep slider position at 0
            # TODO: Look into slider implementation to keep slider at 0
            pass

    def add_to_playlist_callback(self, track):
        self.playlist.add_track(QueryDict(track))
        self.fix_scrolling_workaround()

    def remove_from_playlist_callback(self, index):
        self.playlist.remove_track(index)

    def add_album_to_playlist_callback(self, album_id):
        album = Globals.API.get_album_info(album_id)
        album_tracks = album['tracks']
        if album_tracks:
            album_tracks = self.formatter.format_tracks_list(album_tracks)
            for track in album_tracks:
                self.playlist.add_track(QueryDict(track))
            self.fix_scrolling_workaround()

    def play_station_callback(self, title, seed):
        tracks = Globals.API.get_station_tracks(title, seed)
        if tracks:
            tracks = self.formatter.format_tracks_list(tracks)
            self.playlist.clear()
            for track in tracks:
                self.playlist.add_track(track)
            self.fix_scrolling_workaround()
            # self.playlist.set_current_track(0)
            #self.playbutton_callback()
            track = self.playlist.get_start()
            if track:
                self.play_track(track)
            else:  # do nothing if no track selected
                pass

    def playlist_button_callback(self):
        if self.playlist_hidden:
            self.playlist_container.width = self.playlist_width
            self.playlist_hidden = False
        else:
            self.playlist_container.width = 0
            self.playlist_hidden = True

    def clear_playlist_callback(self):
        Logger.info('Clearing playlist')
        self.playlist.clear()
        # self.playlist.set_current_track(0)

    def search(self, text):
        if len(text) >= 3:
            try:
                search_results = Globals.API.search(text)
                # with open('search_test.json', 'w') as outfile:
                #    json.dump(search_results, outfile)

                self.display_search_results(search_results)
            except CallFailure:
                Logger.warning("Search: No All Access for this account!")
                # TODO: Show login popup
                # TODO: Remove try..except block when gmusicapi 9.0.1 is stable
        else:
            with open('search_test.json') as outfile:
                search_results = json.load(outfile)
                self.display_search_results(search_results)

    def display_search_results(self, search_results):
        Logger.info("Displaying results..")

        Logger.debug("Displaying song results")
        tracks = []
        for entry in search_results['song_hits']:
            tracks.append(entry['track'])
        # songs_sorted = sorted(songs, key=self.get_song_key)
        tracks_formatted = self.formatter.format_tracks_list(tracks)
        # self.ids['list_songs'].data_songs = tracks_formatted
        self.songlist.data_songs = tracks_formatted

        Logger.debug("Displaying station results")
        stations = []
        for entry in search_results['station_hits']:
            stations.append(entry['station'])
        stations_formatted = self.formatter.format_stations_list(stations)

        # add station list items
        # self.stationlist.data_stations = stations_formatted

        # add station panels
        self.stationlist.clear_widgets()
        for station in stations_formatted:
            self.stationlist.add_widget(StationPanelItem(station))

        Logger.debug("Displaying album results")
        albums = []
        for entry in search_results['album_hits']:
            albums.append(entry['album'])
        albums_formatted = self.formatter.format_albums_list(albums)
        self.albumlist.data_albums = albums_formatted
コード例 #47
0
ファイル: bruteForceDrawTool.py プロジェクト: Sina1/4E1S
def main():
    #define busses, . means black, + means green, - means red
    #busList = [
    #            {'name': 'bus1','description': '6kV','status': '.'},
    #            {'name': 'bus2','description': '12kV','status': '.'},
    #            {'name': 'bus3','description': '18kV','status': '.'},
    #            {'name': 'bus4','description': '22kV','status': '.'},
    #            {'name': 'bus5','description': '54kV','status': '.'},
    #        ]
    ## define the connections. '.' means black, + means green, - means read
    #connectionList = [
    #                {1 : 'bus1', 2 : 'bus2', 'status': '.'},
    #                {1 : 'bus2', 2 : 'bus3', 'status': '.'},
    #                {1 : 'bus1', 2 : 'bus3', 'status': '+'},
    #                {1 : 'bus4', 2 : 'bus1', 'status': '+'},
    #                {1 : 'bus5', 2 : 'bus1', 'status': '+'},
    #                ]
    # mkae graphviz string

    #get json data and deserialize it

    fp = open('jsonFile.txt')
    for line in fp:
        print (line)

    fp.close()
    fp = open('jsonFile.txt')
    dataDict = json.loads(fp.read())
    fp.close()
    
    # load data
    nodeList = dataDict['busList']
    connectionList = dataDict['connectionList']
    config['destPath'] = dataDict['filepath']

    # add transformer name to node list
    for node in nodeList:
        if node['type'] == 'transformer':
            #node['name'] = node['busFrom'] + '' + node['id'] + '' + node['busTo']
            node['name'] = str(int(node['busFrom']) + int(node['busTo']))
    # add transformer connections
    for node in nodeList:
        if node['type'] == 'transformer':
            makeTransformerConnection(node, connectionList)
    
    gString = make_graphviz_string(nodeList, connectionList)

    # make node info list
    nodeTypeDict = {}
    for item in nodeList:
        nodeTypeDict[item['name']] = item['type']

    
    # write gString to file for later use
    text_file = open("temp.dot", "w")
    text_file.write(gString)
    text_file.close()

    # write gString to file for later use
    text_file = open(config['pollDir'] + "out.txt", "w")
    text_file.write(gString)
    text_file.close()

    # write dest to file for later use
    text_file = open(config['pollDir'] + "dest.txt", "w")
    text_file.write(config['destPath'])
    text_file.close()

    # write node information
    text_file = open(config['pollDir'] + "nodeInfo.txt", "w")
    json.dump(nodeTypeDict,text_file)
    text_file.close()
    
    # write node list
    text_file = open(config['pollDir'] + "nodeList.txt", "w")
    json.dump(nodeList,text_file)
    text_file.close()
    
    command = '"' + config['graphvizPath'] + '" ' + config['dotCommand'] \
              + "temp.dot > " + config['formatlessVisioFilename']
              #+ "temp.dot > " + config['destPath'] + ".png" 
    print (gString)
    print (command)
    returnCode = os.system(command)
    os.remove("temp.dot")
    print (returnCode)
    
    # start formatter
    formatter = Formatter(config['formatlessVisioFilename'])
    #input(config['destPath'] + config['outputExtension'])
    formatter.start(config['destPath'] + config['outputExtension'])
    time.sleep(1)
コード例 #48
0
ファイル: jsca2js.py プロジェクト: jvandijk/jsca2js
def formatGlobal(namespace):
    formatter = Formatter(METHOD_INDENTATION)

    for method in namespace['methods']:
        formatter.add(generateMethodJSDoc(method))
        formatter.addLine('function ', convertKey(method['name']), '(',
                          formatParams(method['parameters']), ") {")
        formatter.addLine('}')
        formatter.newLine()
    return formatter.getResult()
コード例 #49
0
ファイル: plugin.py プロジェクト: jonspeicher/snore
 def __init__(self, snarler, clock):
     super(SnorePlugin, self).__init__()
     self._formatter = Formatter(self._get_path('icons/'))
     self._snarler = snarler
     self._clock = clock
コード例 #50
0
ファイル: jsca2js.py プロジェクト: jvandijk/jsca2js
def extendGlobal(name, namespace):
    formatter = Formatter(METHOD_INDENTATION)

    for method in namespace['methods']:
        formatter.add(generateMethodJSDoc(method))
        formatter.addLine(name, '.prototype.',
                          convertKey(method['name']), ' = function(',
                          formatParams(method['parameters']), ") {")
        formatter.addLine('};')
        formatter.newLine()
    return formatter.getResult()
コード例 #51
0
ファイル: parser.py プロジェクト: syntacticNaCl/lintthesql
    def format(self):
        file_contents = self.get_file_contents()
        formatter = Formatter()
        file_contents = formatter.format(file_contents, **self.get_rule_list())

        Reporter.add_message(file_contents)
コード例 #52
0
ファイル: jsca2js.py プロジェクト: jvandijk/jsca2js
def formatNamespace(namespace):
    namespaceName = convertIds(namespace[0])
    namespaceContent = namespace[1]

    formatter = Formatter()
    formatter.add(generateNamespaceJSDoc(namespaceContent))

    if namespaceName.find('.') < 0:
        if namespaceName == 'Global':  # ie. Global.alert -> alert()
            formatter.add(formatGlobal(namespaceContent))
            return formatter.getResult()

        formatter.add('var ')
        if namespaceName == 'Titanium':
            namespaceName = 'Ti'

    elif namespaceName.startswith(
            'Global.'):  # ie. Global.String prototype extension
        formatter.add(extendGlobal(namespaceName[7:], namespaceContent))
        return formatter.getResult()

    if 'subtype' in namespaceContent and namespaceContent['subtype'] == 'proxy':
        formatter.addLine(namespaceName, ' = function() {').addLine('};')
        formatter.addLine(namespaceName, '.prototype = {').newLine()
    else:
        formatter.addLine(namespaceName, ' = {').newLine()
    formatter.addLine(formatProperties(namespaceContent))
    formatter.addLine(formatMethods(namespaceContent))
    formatter.addLine('};').newLine()

    return formatter.getResult()
コード例 #53
0
ファイル: jsca2js.py プロジェクト: Tsuguya/jsca2js
def generateNamespaceJSDoc(namespace):
    formatter = Formatter()
    formatter.addLine('/**')

    prefix = ' * '
    if 'notes' in namespace and namespace['notes']:
        formatter.addLine(prefix, 'Notes: ', namespace['notes'])

    if 'platforms' in namespace:
        formatter.addLine(prefix, 'platforms: ', ', '.join(getPlatforms(namespace['platforms'])))
    if namespace['description']:
        formatter.addLine(prefix, '@namespace ', namespace['description'])
    if 'since' in namespace:
        formatter.addLine(prefix, '@since ', namespace['since'])

    if 'examples' in namespace:
        for example in namespace['examples']:
            formatter.addLine(prefix)
            formatter.addLine(prefix, '@example ', example['description'])
            formatter.addLine(prefix, example['code'])

    formatter.addLine(' */')
    return convertLinks(formatter.getResult())
コード例 #54
0
ファイル: jsca2js.py プロジェクト: jvandijk/jsca2js
def generatePropertyJSDoc(property):
    formatter = Formatter(METHOD_INDENTATION)
    formatter.addLine('/**')

    prefix = ' * '

    if KEYS['value'] in property:
        formatter.addLine(prefix, property[KEYS['value']])
    if 'since' in property:
        formatter.addLine(prefix, 'platforms: ',
                          ', '.join(getPlatforms(property['platforms'])))
    formatter.addLine(prefix, '@type ', formatType(property['type']))

    sinceVer = formatSince(property)
    if sinceVer:
        formatter.addLine(prefix, '@since ', sinceVer)

    formatter.addLine(' */')

    return convertLinks(formatter.getResult())
コード例 #55
0
                "Recover table activity?\nEnter yes or no y/n: ").lower()
            if confirmation == "n":
                print("")
            elif confirmation == "y":
                recovery_list = activity_log.recovery(self.date)
                self.repopulate_data(recovery_list)
                self.show_tables()
            else:
                print("")
                print("*** You did not enter a valid response.  Try again champ. ***")

################ running of the app below ############


# creating instances of  classes to run app
formatter = Formatter()
manager = TableManager(day)
activity_log = ActivityLog(manager.date)

# creating list and filling  it with table objects
tables = []
for i in range(1, 13):
    table = Table(i)
    tables.append(table)
# for table in tables:
    # print(f"Table - {table.name}- {table.occupied}")
    # print(manager.day)

# while loop that keeps app in a running state until user quits with 'q'
user_input = ""
while user_input != "q":
コード例 #56
0
def main():
    config = configparser.ConfigParser()
    config.read('config.ini')
    local_config = configparser.ConfigParser()
    local_config.read('config.local.ini')
    parser = argparse.ArgumentParser()
    parser.add_argument('--bot_key',
                        action='store',
                        dest='bot_key',
                        help='Telegram Bot Key')
    parser.add_argument('--target',
                        action='store',
                        dest='target',
                        help='Who will receive the messages')
    args = parser.parse_args()
    pretty = Formatter()
    overrided_config = check_config(config, local_config, args)
    LOGGER.debug("""
-------------------------------------
DUMP CONFIG
-------------------------------------
%s""" % pretty(overrided_config.__dict__))
    bot = telepot.Bot(overrided_config["telegram"]["bot_key"])
    (dict_subs, _, dict_subs) = scan_dirs(dir_subs)
    (dict_files, del_list, dict_subs) = scan_dirs(dir_files, dict_subs)
    to_move = set(dict_files.keys()).intersection(set(dict_subs.keys()))
    out_file = open(output_file, 'a')
    LOGGER.debug("""
-------------------------------------
DUMP VARIABLES
-------------------------------------
to_move:
%s
list subs:
%s
list files:
%s
del list:
%s
""" % (pretty(to_move), pretty(dict_subs), pretty(dict_files),
       pretty(del_list)))
    for episode in to_move:
        videofile = dict_files[episode]
        if dict_subs[episode].split('.')[-1] == 'zip':
            sub = zipfile.ZipFile(dict_subs[episode])
            sub_extracted = sub.extract(sub.namelist()[0], '/tmp')
        else:
            sub_extracted = dict_subs[episode]
        destination = dir_dest + '/' + regexp.match(
            dict_files[episode].split('/')[-1]).group(1).replace(
                '.', ' ') + '/Season ' + episode.split('.')[-2]
        mkdir_p(destination)
        shutil.move(
            sub_extracted, destination + '/' +
            '.'.join(videofile.split('/')[-1].split('.')[:-1]) + '.' +
            sub_extracted.split('.')[-1])
        LOGGER.debug("shutil.move(%s, %s/%s)\n" %
                     (videofile, destination, videofile.split('/')[-1]))
        shutil.move(videofile, destination + '/' + videofile.split('/')[-1])
        try:
            os.chmod(destination + '/' + videofile.split('/')[-1], 660)
            os.chmod(destination, 2770)
        except OSError:
            print("Can't change permissions, different owner")
        output_string = "PUNTATA COPIATA: %s\n" % videofile
        out_file.write(output_string)
        LOGGER.info(output_string)
        try:
            bot.sendMessage(overrided_config["telegram"]["target"],
                            "PUNTATA COPIATA: %s\n" % videofile)
        except Exception:
            pass
        if os.path.dirname(videofile) in del_list:
            LOGGER.debug("shutil.rmtree(%s)\n" % os.path.dirname(videofile))
            shutil.rmtree(os.path.dirname(videofile))
    out_file.close()
コード例 #57
0
ファイル: felow.py プロジェクト: lux-sol/felow
    def clean_text(self, text, document, sentmin, sentmax, dictionary, cycle):
        print("applicator selected")
        applicator = Applicator()
        cleaner = Cleaner()
        formatter = Formatter()
        new_text = self.get_string(text)

        cycle_list = [
            "noalpha", "nodeclare", "excaps", "exletters", "firstperson",
            "secondperson", "dupwords", "duplicates", "trimsentlist",
            "checkspelling", "help (or h)"
        ]

        def return_cycles():
            s = ", "
            s = s.join(cycle_list)
            return s

        cleaner.create_sentc_list(new_text)
        if cycle == "full":
            cleaner.remv_noalpha()
            cleaner.remv_nodeclare()
            cleaner.remv_excaps()
            cleaner.remv_exletters()
            cleaner.remv_firstperson()
            cleaner.remv_secondperson()
            cleaner.remv_dupwords()
            cleaner.remv_duplicates()
            cleaner.trim_sentlist(sentmin, sentmax)
            cleaner.check_misspelled(dictionary)

        elif cycle == "noalpha":
            cleaner.remv_noalpha()

        elif cycle == "nodeclare":
            cleaner.remv_nodeclare()

        elif cycle == "excaps":
            cleaner.remv_excaps()

        elif cycle == "exletters":
            cleaner.remv_exletters()

        elif cycle == "firstperson":
            cleaner.remv_firstperson()

        elif cycle == "secondperson":
            cleaner.remv_secondperson()

        elif cycle == "dupwords":
            cleaner.remv_dupwords()

        elif cycle == "duplicates":
            cleaner.remv_duplicates()

        elif cycle == "trimsentlist":
            cleaner.trim_sentlist(sentmin, sentmax)

        elif cycle == "checkspelling":
            cleaner.check_misspelled(dictionary)

        else:
            print("cycle not found")
            print("available cycles:")
            print(return_cycles())
            raise SystemExit

        sentc_list = cleaner.get_sentc_list()
        formatter.set_sentlist(sentc_list)
        formatter.frmt_textlist()
        clean_text = formatter.get_text()
        applicator.apply_text(text=clean_text, document=document)
コード例 #58
0
ファイル: jsca2js.py プロジェクト: Tsuguya/jsca2js
def formatNamespace(namespace):
    namespaceName = convertIds(namespace[0])
    namespaceContent = namespace[1]

    formatter = Formatter()
    formatter.add(generateNamespaceJSDoc(namespaceContent))

    if namespaceName.find('.') < 0:
        if namespaceName == 'Global': # ie. Global.alert -> alert()
            formatter.add(formatGlobal(namespaceContent))
            return formatter.getResult();
            
        formatter.add('var ')
        if namespaceName == 'Titanium':
            namespaceName = 'Ti'

    elif namespaceName.startswith('Global.'): # ie. Global.String prototype extension
        formatter.add(extendGlobal(namespaceName[7:], namespaceContent))
        return formatter.getResult();

    if 'subtype' in namespaceContent and namespaceContent['subtype'] == 'proxy':
        formatter.addLine(namespaceName, ' = function() {').addLine('};')
        formatter.addLine(namespaceName, '.prototype = {').newLine()
    else:
        formatter.addLine(namespaceName, ' = {').newLine()
    formatter.addLine(formatProperties(namespaceContent))
    formatter.addLine(formatMethods(namespaceContent))
    formatter.addLine('};').newLine()

    return formatter.getResult()
コード例 #59
0
ファイル: jsca2js.py プロジェクト: Tsuguya/jsca2js
def generatePropertyJSDoc(property):
    formatter = Formatter(METHOD_INDENTATION)
    formatter.addLine('/**')

    prefix = ' * '

    if KEYS['value'] in property:
        formatter.addLine(prefix, property[KEYS['value']])
    if 'since' in property:
        formatter.addLine(prefix, 'platforms: ', ', '.join(getPlatforms(property['platforms'])))
    formatter.addLine(prefix, '@type ', formatType(property['type']))

    sinceVer = formatSince(property)
    if sinceVer:
        formatter.addLine(prefix, '@since ', sinceVer)

    formatter.addLine(' */')

    return convertLinks(formatter.getResult())
コード例 #60
0
parser_config = "parsers.config.json"


def load_parser_config(path):
    ps = []
    with open(path) as f:
        config = json.load(f)
        npm_config = config.get("npm")
        if npm_config:
            import parsers.npm
            ps.append(parsers.npm.get(**npm_config))

        pip_config = config.get("pip")
        if pip_config:
            import parsers.pip
            ps.append(parsers.pip.get(**pip_config))

    return ps


if __name__ == '__main__':
    formatter = Formatter(formatter_path)
    bill = BillOfMaterials(bill_of_materials_path, formatter)
    retrievers = load_parser_config(parser_config)

    for f in retrievers:
        for material in f():
            bill.add(material)

    bill.save()