text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Add state to NewOptionForm; add Col util function
import m from 'mithril'; export const Col = (el) => m('div.col', [el]) export class NewOptionForm { oninit(vnode) { vnode.state.newOption = { name: '', pattern: '', selector: '', enabled: true }; } view(vnode) { const { name, pattern, selector, enabled } = vnode.state.newOption; return m('form', [ m('div.row.p-3', [ Col(m('input.form-control', { type: 'text', placeholder: 'Name', value: name})), Col(m('input.form-control', { type: 'text', placeholder: 'Pattern', value: pattern })), Col(m('input.form-control', { type: 'text', placeholder: 'Selector (Optional)', value: selector })), Col(m('div.form-check.form-check-inline', [ m('label.form-check-label', [ m('input.form-check-input', { type: 'checkbox', checked: enabled }), 'Enabled', ]), ])), Col(m('button.btn.btn-primary', { type: 'button' }, '+')), ]), ]); } }
import m from 'mithril'; export class NewOptionForm { view() { return m('form', [ m('div.row.p-3', [ m('div.col', [ m('input.form-control', { type: 'text', placeholder: 'Name' }), ]), m('div.col', [ m('input.form-control', { type: 'text', placeholder: 'Pattern' }), ]), m('div.col', [ m('div.form-check.form-check-inline', [ m('label.form-check-label', [ m('input.form-check-input', { type: 'checkbox' }), 'Enabled', ]), ]), ]), m('div.col', [ m('input.form-control', { type: 'text', placeholder: 'Selector (Optional)' }), ]), ]), ]); } }
Update copyright notice with MIT license
/*++ NASM Assembly Language Plugin Copyright (c) 2017-2018 Aidan Khoury 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, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. --*/ package com.nasmlanguage; import com.intellij.openapi.fileTypes.FileTypeConsumer; import com.intellij.openapi.fileTypes.FileTypeFactory; import org.jetbrains.annotations.NotNull; public class NASMFileTypeFactory extends FileTypeFactory { @Override public void createFileTypes(@NotNull FileTypeConsumer fileTypeConsumer) { fileTypeConsumer.consume(NASMFileType.INSTANCE, NASMFileType.FILE_EXTENSION); } }
/*++ NASM Assembly Language Plugin Copyright (c) 2017-2018 Aidan Khoury. All rights reserved. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. --*/ package com.nasmlanguage; import com.intellij.openapi.fileTypes.FileTypeConsumer; import com.intellij.openapi.fileTypes.FileTypeFactory; import org.jetbrains.annotations.NotNull; public class NASMFileTypeFactory extends FileTypeFactory { @Override public void createFileTypes(@NotNull FileTypeConsumer fileTypeConsumer) { fileTypeConsumer.consume(NASMFileType.INSTANCE, NASMFileType.FILE_EXTENSION); } }
Resolve error when settings does not have globals/locals objects Closes #49
const fs = require('fs-extra'), Path = require('path'); var _settings = { // Private storage of settings global: {}, local: {} }, _currPath; // Path to the settings.json file var Settings = { GetGlobal: (name) => { if(!_settings.global) _settings.global = {}; return _settings.global[name] || null; }, GetLocal: (name) => { if(!_settings.local) _settings.local = {}; return _settings.local[name] || null; }, SetGlobal: (name, data) => { _settings.global[name] = data; }, SetLocal: (name, data) => { _settings.local[name] = data; }, Save: function() { fs.ensureFileSync(_currPath); fs.writeJsonSync(_currPath, _settings); }, Load: function(dir) { // Load the settings into memory _currPath = Path.resolve(dir, 'settings.json'); if(!fs.existsSync(_currPath)) { // Ensure the settings.json file exists with // at least empty `global` and `local` objects fs.writeFileSync(_currPath, '{"global": {}, "local": {}}'); } _settings = fs.readJsonSync(_currPath); } } module.exports = Settings;
const fs = require('fs-extra'), Path = require('path'); var _settings = { // Private storage of settings global: {}, local: {} }, _currPath; // Path to the settings.json file var Settings = { GetGlobal: (name) => { return _settings.global[name] || null; //return _settings.global[name]; }, GetLocal: (name) => { return _settings.local[name] || null; //return _settings.local[name]; }, SetGlobal: (name, data) => { _settings.global[name] = data; }, SetLocal: (name, data) => { _settings.local[name] = data; }, Save: function() { fs.ensureFileSync(_currPath); fs.writeJsonSync(_currPath, _settings); }, Load: function(dir) { // Load the settings into memory _currPath = Path.resolve(dir, 'settings.json'); if(!fs.existsSync(_currPath)) { // Ensure the settings.json file exists with // at least empty `global` and `local` objects fs.writeFileSync(_currPath, '{"global": {}, "local": {}}'); } _settings = fs.readJsonSync(_currPath); } } module.exports = Settings;
Add link to Privacy page
<br> <div class="main-container shadow"> <p> Associazione Portico delle Parole <br> Via del Pratello 9, 40122 Bologna, Italia <br> Tel: +39 327 6617027 <br> <a href="mailto:info@porticodelleparole.it">info@porticodelleparole.it</a>&nbsp;&nbsp;&nbsp; <a href="https://www.porticodelleparole.it">www.porticodelleparole.it</a> </p> <p> C.F.: 91361610370 </p> <hr> <p> <a href="/cookie/">Informativa sui Cookie</a> &nbsp;|&nbsp; <a href="/privacy/">Privacy Policy</a> </p> </div>
<br> <div class="main-container shadow"> <p> Associazione Portico delle Parole <br> Via del Pratello 9, 40122 Bologna, Italia <br> Tel: +39 327 6617027 <br> <a href="mailto:info@porticodelleparole.it">info@porticodelleparole.it</a>&nbsp;&nbsp;&nbsp; <a href="https://www.porticodelleparole.it">www.porticodelleparole.it</a> </p> <p> C.F.: 91361610370 </p> <hr> <p> <a href="/cookie/">Informativa sui Cookie</a> </p> </div>
Add Event ordering by datetime
from django.db import models class Artist(models.Model): name = models.CharField(max_length=100) image_url = models.URLField(blank=True) thumb_url = models.URLField(blank=True) events = models.ManyToManyField( 'event.Event', related_name='artists', blank=True, ) class Meta: ordering = ['name'] def __str__(self): return self.name class Event(models.Model): title = models.CharField(max_length=200) datetime = models.DateTimeField() venue = models.ForeignKey( 'event.Venue', related_name='events', on_delete=models.CASCADE, ) class Meta: ordering = ['datetime'] def __str__(self): return self.title class Venue(models.Model): name = models.CharField(max_length=100) city = models.CharField(max_length=100) country = models.CharField(max_length=100) def __str__(self): return self.name
from django.db import models class Artist(models.Model): name = models.CharField(max_length=100) image_url = models.URLField(blank=True) thumb_url = models.URLField(blank=True) events = models.ManyToManyField( 'event.Event', related_name='artists', blank=True, ) class Meta: ordering = ['name'] def __str__(self): return self.name class Event(models.Model): title = models.CharField(max_length=200) datetime = models.DateTimeField() venue = models.ForeignKey( 'event.Venue', related_name='events', on_delete=models.CASCADE, ) def __str__(self): return self.title class Venue(models.Model): name = models.CharField(max_length=100) city = models.CharField(max_length=100) country = models.CharField(max_length=100) def __str__(self): return self.name
Add fab command for fetching episodes
from fabric.api import run, env from fabric.context_managers import cd import os env.hosts = ['root@0.0.0.0:1337'] def update_podcasts(): with cd('"{}"'.format(os.path.dirname(__file__))): run('python3 manage.py updatepodcasts') def fetch_episodes(): with cd('"{}"'.format(os.path.dirname(__file__))): run('python3 manage.py fetchepisodes') def setup_dev(): with cd('"{}"'.format(os.path.dirname(__file__))): run('python3 manage.py syncdb') run('python3 manage.py loaddata sample_podcasts') run('python3 manage.py updatepodcasts') run('python3 manage.py fetchepisodes') run('python3 manage.py update_index') def rebuild_index(): with cd('"{}"'.format(os.path.dirname(__file__))): # Add --noinput flag because of this issue: # https://github.com/toastdriven/django-haystack/issues/902 run('python3 manage.py rebuild_index --noinput')
from fabric.api import run, env from fabric.context_managers import cd import os env.hosts = ['root@0.0.0.0:1337'] def update_podcasts(): with cd('"{}"'.format(os.path.dirname(__file__))): run('python3 manage.py updatepodcasts') def setup_dev(): with cd('"{}"'.format(os.path.dirname(__file__))): run('python3 manage.py syncdb') run('python3 manage.py loaddata sample_podcasts') run('python3 manage.py updatepodcasts') run('python3 manage.py fetchepisodes') run('python3 manage.py update_index') def rebuild_index(): with cd('"{}"'.format(os.path.dirname(__file__))): # Add --noinput flag because of this issue: # https://github.com/toastdriven/django-haystack/issues/902 run('python3 manage.py rebuild_index --noinput')
Correct typo in test method name
package main import ( "encoding/xml" "fmt" "net/http" "net/http/httptest" "strings" "testing" ) func TestStraingToVoiceMailResponse(t *testing.T) { recorder := httptest.NewRecorder() StraightToVoiceMail(recorder, nil) if status := recorder.Code; status != http.StatusOK { t.Errorf("returned wrong status code: got %v expected %v", status, http.StatusOK) } if err := checkWellFormedXML(recorder.Body.String()); err != nil { t.Errorf("body need to be valid XML: %v", err) } } func checkWellFormedXML(s string) error { d := xml.NewDecoder(strings.NewReader(s)) t, err := d.Token() if err != nil { return err } v, ok := t.(xml.ProcInst) if !ok || v.Target != "xml" || !strings.Contains(string(v.Inst), "version=\"1.0\"") { return fmt.Errorf("No XML header detected with version 1.0 at the start") } return nil }
package main import ( "encoding/xml" "fmt" "net/http" "net/http/httptest" "strings" "testing" ) func TestStraingToVoiceMailResponse(t *testing.T) { recorder := httptest.NewRecorder() StraightToVoiceMail(recorder, nil) if status := recorder.Code; status != http.StatusOK { t.Errorf("returned wrong status code: got %v expected %v", status, http.StatusOK) } if err := checkWellFormetXML(recorder.Body.String()); err != nil { t.Errorf("body need to be valid XML: %v", err) } } func checkWellFormetXML(s string) error { d := xml.NewDecoder(strings.NewReader(s)) t, err := d.Token() if err != nil { return err } v, ok := t.(xml.ProcInst) if !ok || v.Target != "xml" || !strings.Contains(string(v.Inst), "version=\"1.0\"") { return fmt.Errorf("No XML header detected with version 1.0 at the start") } return nil }
Change reference on the twitter's singleton
/* * The MIT License (MIT) * * Copyright (c) 2015 Ivan Maslov * * 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, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package info.maslowis.twitterripper.command; import twitter4j.Twitter; import twitter4j.TwitterFactory; /** * The superclass for any twitter command * * @author Ivan Maslov */ public abstract class TwitterCommand extends Command { protected Twitter twitter; protected TwitterCommand() { super(); this.twitter = TwitterFactory.getSingleton(); } }
/* * The MIT License (MIT) * * Copyright (c) 2015 Ivan Maslov * * 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, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package info.maslowis.twitterripper.command; import twitter4j.Twitter; /** * The superclass for any twitter command * * @author Ivan Maslov */ public abstract class TwitterCommand extends Command { protected Twitter twitter; protected TwitterCommand(Twitter twitter) { super(); this.twitter = twitter; } }
Fix wrong permissions. Admins couldnt have access to AdminController
<?php /** * @author Pierre-Henry Soria <hello@ph7cms.com> * @copyright (c) 2019, Pierre-Henry Soria. All Rights Reserved. * @license GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory. * @package PH7 / App / System / Module / SMS Verification / Config */ namespace PH7; use PH7\Framework\Layout\Html\Design; use PH7\Framework\Mvc\Router\Uri; use PH7\Framework\Url\Header; defined('PH7') or exit('Restricted access'); class Permission extends PermissionCore { public function __construct() { parent::__construct(); if ($this->registry->controller === 'MainController' && !$this->session->exists(SmsVerificationCore::PROFILE_ID_SESS_NAME)) { $this->signUpRedirect(); } if ($this->registry->controller === 'AdminController' && !AdminCore::auth()) { // For security reasons, don't redirect user to admin panel URL Header::redirect( Uri::get('user', 'main', 'login'), $this->adminSignInMsg(), Design::ERROR_TYPE ); } } }
<?php /** * @author Pierre-Henry Soria <hello@ph7cms.com> * @copyright (c) 2019, Pierre-Henry Soria. All Rights Reserved. * @license GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory. * @package PH7 / App / System / Module / SMS Verification / Config */ namespace PH7; use PH7\Framework\Layout\Html\Design; use PH7\Framework\Mvc\Router\Uri; use PH7\Framework\Url\Header; defined('PH7') or exit('Restricted access'); class Permission extends PermissionCore { public function __construct() { parent::__construct(); if (!$this->session->exists(SmsVerificationCore::PROFILE_ID_SESS_NAME)) { $this->signUpRedirect(); } if (!AdminCore::auth() && $this->registry->controller === 'AdminController') { // For security reasons, don't redirect user to admin panel URL Header::redirect( Uri::get('user', 'main', 'login'), $this->adminSignInMsg(), Design::ERROR_TYPE ); } } }
Make use of chained comparisons
# Copyright (c) 2016-2021 Renata Hodovan, Akos Kiss. # # Licensed under the BSD 3-Clause License # <LICENSE.rst or https://opensource.org/licenses/BSD-3-Clause>. # This file may not be copied, modified, or distributed except # according to those terms. import pytest import fuzzinator @pytest.mark.parametrize('fuzzer_kwargs, exp_min_len, exp_max_len', [ ({}, 1, 1), ({'max_length': '100'}, 1, 100), ({'min_length': '10', 'max_length': '100'}, 10, 100), ]) def test_random_content(fuzzer_kwargs, exp_min_len, exp_max_len): for index in range(100): out = fuzzinator.fuzzer.RandomContent(index=index, **fuzzer_kwargs) out_len = len(out) assert exp_min_len <= out_len <= exp_max_len
# Copyright (c) 2016 Renata Hodovan, Akos Kiss. # # Licensed under the BSD 3-Clause License # <LICENSE.rst or https://opensource.org/licenses/BSD-3-Clause>. # This file may not be copied, modified, or distributed except # according to those terms. import pytest import fuzzinator @pytest.mark.parametrize('fuzzer_kwargs, exp_min_len, exp_max_len', [ ({}, 1, 1), ({'max_length': '100'}, 1, 100), ({'min_length': '10', 'max_length': '100'}, 10, 100), ]) def test_random_content(fuzzer_kwargs, exp_min_len, exp_max_len): for index in range(100): out = fuzzinator.fuzzer.RandomContent(index=index, **fuzzer_kwargs) out_len = len(out) assert out_len >= exp_min_len and out_len <= exp_max_len
Fix deadlock in subprocess pipes
import asyncio import sys import pytest pytestmark = pytest.mark.asyncio() async def test_command_line_send(smtpd_server, hostname, port): proc = await asyncio.create_subprocess_exec( sys.executable, b"-m", b"aiosmtplib", stdin=asyncio.subprocess.PIPE, stdout=asyncio.subprocess.PIPE, ) inputs = ( bytes(hostname, "ascii"), bytes(str(port), "ascii"), b"sender@example.com", b"recipient@example.com", b"Subject: Hello World\n\nHi there.", ) messages = ( b"SMTP server hostname [localhost]:", b"SMTP server port [25]:", b"From:", b"To:", b"Enter message, end with ^D:", ) output, errors = await proc.communicate(input=b"\n".join(inputs)) assert errors is None for message in messages: assert message in output assert proc.returncode == 0
import asyncio import sys import pytest pytestmark = pytest.mark.asyncio() async def test_command_line_send(smtpd_server, hostname, port): proc = await asyncio.create_subprocess_exec( sys.executable, b"-m", b"aiosmtplib", stdin=asyncio.subprocess.PIPE, stdout=asyncio.subprocess.PIPE, ) expected = ( (b"hostname", bytes(hostname, "ascii")), (b"port", bytes(str(port), "ascii")), (b"From", b"sender@example.com"), (b"To", b"recipient@example.com"), (b"message", b"Subject: Hello World\n\nHi there."), ) for expected_output, write_bytes in expected: output = await proc.stdout.readuntil(separator=b":") assert expected_output in output proc.stdin.write(write_bytes + b"\n") await proc.stdin.drain() proc.stdin.write_eof() await proc.stdin.drain() return_code = await proc.wait() assert return_code == 0
Use ensureDir instead of mkdir
const path = require('path'); const fs = require('fs-extra'); const log = require('./log'); // ----------------------------------------------------------------------------- // main build // ----------------------------------------------------------------------------- function makeOutputFilePath(filePath, cb) { const dir = path.dirname(filePath); fs.ensureDir(dir, (err) => { log.error(err); cb(filePath); }); return filePath; } // ----------------------------------------------------------------------------- // write file // ----------------------------------------------------------------------------- function write(outFilePath, content) { return makeOutputFilePath(outFilePath, () => { fs.writeFile(outFilePath, content, (err) => { if (err) { log.error(err); } }); }); } // ----------------------------------------------------------------------------- // copy file // ----------------------------------------------------------------------------- function copy(src, dest) { return makeOutputFilePath(dest, () => { fs.copy(src, dest, (err) => { if (err) { log.error(err); } }); }); } module.exports = { write, copy };
const path = require('path'); const fs = require('fs-extra'); const log = require('./log'); // ----------------------------------------------------------------------------- // main build // ----------------------------------------------------------------------------- function makeOutputFilePath(filePath, cb) { const dir = path.dirname(filePath); fs.mkdirs(dir, {}, () => { cb(filePath); }); return filePath; } // ----------------------------------------------------------------------------- // write file // ----------------------------------------------------------------------------- function write(outFilePath, content) { return makeOutputFilePath(outFilePath, () => { fs.writeFile(outFilePath, content, (err) => { if (err) { log.error(err); } }); }); } // ----------------------------------------------------------------------------- // copy file // ----------------------------------------------------------------------------- function copy(src, dest) { return makeOutputFilePath(dest, () => { fs.copy(src, dest, (err) => { if (err) { log.error(err); } }); }); } module.exports = { write, copy };
Remove the requirement no longer being used
/* global atom:true */ const clipboard = atom.clipboard; module.exports = class KillRing { constructor(limit=16) { this.buffer = []; this.sealed = true; this.limit = limit; } put(texts, forward=true) { if(this.sealed) this.push(texts); else this.update(texts, forward); } seal() { this.sealed = true; } push(texts) { this.buffer.push(texts); clipboard.write(texts.join('\n')); if(this.buffer.length > this.limit) this.buffer.shift(); this.sealed = false; } update(texts, forward) { const lasts = this.buffer.pop(); const newTexts = texts.map((t,i) => forward ? lasts[i]+(t?t:'') : (t?t:'')+lasts[i]); this.push(newTexts); } top() { this.updateBuffer(); return this.buffer.slice(-1)[0]; } updateBuffer() { const lasts = this.buffer.slice(-1)[0]; if(clipboard.md5(lasts?lasts.join('\n'):'') != clipboard.signatureForMetadata) this.push(clipboard.read()); } };
/* global atom:true */ const _ = require('underscore-plus'); const clipboard = atom.clipboard; module.exports = class KillRing { constructor(limit=16) { this.buffer = []; this.sealed = true; this.limit = limit; } put(texts, forward=true) { if(this.sealed) this.push(texts); else this.update(texts, forward); } seal() { this.sealed = true; } push(texts) { this.buffer.push(texts); clipboard.write(texts.join('\n')); if(this.buffer.length > this.limit) this.buffer.shift(); this.sealed = false; } update(texts, forward) { const lasts = this.buffer.pop(); const newTexts = texts.map((t,i) => forward ? lasts[i]+(t?t:'') : (t?t:'')+lasts[i]); this.push(newTexts); } top() { this.updateBuffer(); return this.buffer.slice(-1)[0]; } updateBuffer() { const lasts = this.buffer.slice(-1)[0]; if(clipboard.md5(lasts?lasts.join('\n'):'') != clipboard.signatureForMetadata) this.push(clipboard.read()); } };
Modify match rules for activating extension or not
chrome.runtime.onInstalled.addListener(function() { chrome.declarativeContent.onPageChanged.removeRules(undefined, function() { chrome.declarativeContent.onPageChanged.addRules([ { conditions: [ new chrome.declarativeContent.PageStateMatcher({ pageUrl: { hostEquals: 'github.com', schemes: ['https'], urlMatches: '/(.+)/(.+)/issues|pull/(\\d+)' }, css: ['.gh-header-title'] }) ], actions: [ new chrome.declarativeContent.ShowPageAction() ] } ]); }); });
chrome.runtime.onInstalled.addListener(function() { chrome.declarativeContent.onPageChanged.removeRules(undefined, function() { chrome.declarativeContent.onPageChanged.addRules([ { conditions: [ new chrome.declarativeContent.PageStateMatcher({ pageUrl: { hostEquals: 'github.com', schemes: ['https'], urlMatches: '/(.+)/(.+)/issues|pull/(\\d+)' }, css: ['span.js-issue-title', 'span.gh-header-number'] }) ], actions: [ new chrome.declarativeContent.ShowPageAction() ] } ]); }); });
Add bidi (right-to-left layout) attr to locale resource
# Copyright (C) 2015 Andrey Antukh <niwi@niwi.be> # Copyright (C) 2015 Jesús Espino <jespinog@gmail.com> # Copyright (C) 2015 David Barragán <bameda@dbarragan.com> # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from django.conf import settings from taiga.base import response from taiga.base.api.viewsets import ReadOnlyListViewSet from . import permissions class LocalesViewSet(ReadOnlyListViewSet): permission_classes = (permissions.LocalesPermission,) def list(self, request, *args, **kwargs): locales = [{"code": c, "name": n, "bidi": c in settings.LANGUAGES_BIDI} for c, n in settings.LANGUAGES] return response.Ok(locales)
# Copyright (C) 2015 Andrey Antukh <niwi@niwi.be> # Copyright (C) 2015 Jesús Espino <jespinog@gmail.com> # Copyright (C) 2015 David Barragán <bameda@dbarragan.com> # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from django.conf import settings from taiga.base import response from taiga.base.api.viewsets import ReadOnlyListViewSet from . import permissions class LocalesViewSet(ReadOnlyListViewSet): permission_classes = (permissions.LocalesPermission,) def list(self, request, *args, **kwargs): locales = [{"code": c, "name": n} for c, n in settings.LANGUAGES] return response.Ok(locales)
Remove sun setup for now
from teeminus10_helpers import * import unittest class TestInTimeOfDay(unittest.TestCase): def setUp(self): self.location = ephem.city('London') self.location.date = datetime(2013, 03, 14, 9, 0, 0) self.pass_day_time = datetime(2013, 03, 14, 12, 0, 0) self.pass_night_time = datetime(2013, 03, 14, 0, 0, 0) def test_pass_in_whatever_time(self): self.assertTrue(in_time_of_day(self.location, self.pass_day_time, "whatever")) self.assertTrue(in_time_of_day(self.location, self.pass_night_time, "whatever")) def test_pass_in_day_time(self): self.assertTrue(in_time_of_day(self.location, self.pass_day_time, "day")) self.assertFalse(in_time_of_day(self.location, self.pass_night_time, "day")) def test_pass_in_night_time(self): self.assertFalse(in_time_of_day(self.location, self.pass_day_time, "night")) self.assertTrue(in_time_of_day(self.location, self.pass_night_time, "night"))
from teeminus10_helpers import * import unittest class TestInTimeOfDay(unittest.TestCase): def setUp(self): self.location = ephem.city('London') self.location.date = datetime(2013, 03, 14, 9, 0, 0) self.pass_day_time = datetime(2013, 03, 14, 12, 0, 0) self.pass_night_time = datetime(2013, 03, 14, 0, 0, 0) self.sun = ephem.Sun("2013/03/14") def test_pass_in_whatever_time(self): self.assertTrue(in_time_of_day(self.location, self.pass_day_time, "whatever")) self.assertTrue(in_time_of_day(self.location, self.pass_night_time, "whatever")) def test_pass_in_day_time(self): self.assertTrue(in_time_of_day(self.location, self.pass_day_time, "day")) self.assertFalse(in_time_of_day(self.location, self.pass_night_time, "day")) def test_pass_in_night_time(self): self.assertFalse(in_time_of_day(self.location, self.pass_day_time, "night")) self.assertTrue(in_time_of_day(self.location, self.pass_night_time, "night"))
Fix trailing whitespace for checkstyle
package seedu.task.storage; import javax.xml.bind.annotation.XmlValue; import seedu.task.commons.exceptions.IllegalValueException; import seedu.task.model.tag.Tag; /** * JAXB-friendly adapted version of the Tag. */ public class XmlAdaptedTag { @XmlValue public String tagName; /** * Constructs an XmlAdaptedTag. * This is the no-arg constructor that is required by JAXB. */ public XmlAdaptedTag() {} /** * Converts a given Tag into this class for JAXB use. * * @param source future changes to this will not affect the created */ public XmlAdaptedTag(Tag source) { tagName = source.tagName; } /** * Converts this jaxb-friendly adapted tag object into the model's Tag object. * * @throws IllegalValueException if there were any data constraints violated in the adapted task */ public Tag toModelType() throws IllegalValueException { return new Tag(tagName); } }
package seedu.task.storage; import javax.xml.bind.annotation.XmlValue; import seedu.task.commons.exceptions.IllegalValueException; import seedu.task.model.tag.Tag; /** * JAXB-friendly adapted version of the Tag. */ public class XmlAdaptedTag { @XmlValue public String tagName; /** * Constructs an XmlAdaptedTag. * This is the no-arg constructor that is required by JAXB. */ public XmlAdaptedTag() {} /** * Converts a given Tag into this class for JAXB use. * * @param source future changes to this will not affect the created */ public XmlAdaptedTag(Tag source) { tagName = source.tagName; } /** * Converts this jaxb-friendly adapted tag object into the model's Tag object. * * @throws IllegalValueException if there were any data constraints violated in the adapted task */ public Tag toModelType() throws IllegalValueException { return new Tag(tagName); } }
Make cargs and gargs truly optional
import os import subprocess def load_variables_from_env(prefix="XII_INTEGRATION_"): length = len(prefix) vars = {} for var in filter(lambda x: x.startswith(prefix), os.environ): vars[var[length:]] = os.environ[var] return vars def run_xii(deffile, cmd, variables={}, gargs=None, cargs=None): xii_env = os.environ.copy() for key, value in variables.items(): print("=> XII_" + key + " defined") xii_env["XII_" + key] = value call = ["xii", "--no-parallel", "--deffile", deffile, gargs, cmd, cargs] print("calling `{}`".format(" ".join(call))) process = subprocess.Popen(call, stdout=subprocess.PIPE, env=xii_env) for line in process.stdout: print("> " + line.rstrip(os.linesep)) if process.returncode != 0: raise RuntimeError("running xii failed")
import os import subprocess def load_variables_from_env(prefix="XII_INTEGRATION_"): length = len(prefix) vars = {} for var in filter(lambda x: x.startswith(prefix), os.environ): vars[var[length:]] = os.environ[var] return vars def run_xii(deffile, cmd, variables={}, gargs="", cargs=""): xii_env = os.environ.copy() for key, value in variables.items(): print("=> XII_" + key + " defined") xii_env["XII_" + key] = value call = ["xii", "--no-parallel", "--deffile", deffile, gargs, cmd, cargs] print("calling `{}`".format(" ".join(call))) process = subprocess.Popen(call, stdout=subprocess.PIPE, env=xii_env) for line in process.stdout: print("> " + line.rstrip(os.linesep)) if process.returncode != 0: raise RuntimeError("running xii failed")
Remove unneeded css parser options
"use strict"; var CssSelectorParser = require('css-selector-parser').CssSelectorParser var cssSelector = new CssSelectorParser() cssSelector.registerNestingOperators('>', '+', '~'); cssSelector.registerAttrEqualityMods('^', '$', '*', '~'); module.exports = replaceClasses function replaceClasses(selector, map) { var ast = cssSelector.parse(selector) visitRules(ast, function(node) { if (node.classNames) { node.classNames = node.classNames.map(function(cls) { if (map.hasOwnProperty(cls)) { return map[cls] } else { return cls } }) } }) return cssSelector.render(ast) } function visitRules(node, fn) { if (node.rule) { visitRules(node.rule, fn) } if (node.selectors) { node.selectors.forEach(function(node) { visitRules(node, fn) }) } if (node.pseudos) { node.pseudos.forEach(function(pseudo) { if (pseudo.valueType === 'selector') { visitRules(pseudo.value, fn) } }) } if (node.type === 'rule') { fn(node) } }
"use strict"; var CssSelectorParser = require('css-selector-parser').CssSelectorParser var cssSelector = new CssSelectorParser() cssSelector.registerSelectorPseudos('has'); cssSelector.registerNestingOperators('>', '+', '~'); cssSelector.registerAttrEqualityMods('^', '$', '*', '~'); cssSelector.enableSubstitutes(); module.exports = replaceClasses function replaceClasses(selector, map) { var ast = cssSelector.parse(selector) visitRules(ast, function(node) { if (node.classNames) { node.classNames = node.classNames.map(function(cls) { if (map.hasOwnProperty(cls)) { return map[cls] } else { return cls } }) } }) return cssSelector.render(ast) } function visitRules(node, fn) { if (node.rule) { visitRules(node.rule, fn) } if (node.selectors) { node.selectors.forEach(function(node) { visitRules(node, fn) }) } if (node.pseudos) { node.pseudos.forEach(function(pseudo) { if (pseudo.valueType === 'selector') { visitRules(pseudo.value, fn) } }) } if (node.type === 'rule') { fn(node) } }
Update the PyPI version to 0.2.13
# -*- coding: utf-8 -*- import os from setuptools import setup def read(fname): try: return open(os.path.join(os.path.dirname(__file__), fname)).read() except: return '' setup( name='todoist-python', version='0.2.13', packages=['todoist', 'todoist.managers'], author='Doist Team', author_email='info@todoist.com', license='BSD', description='todoist-python - The official Todoist Python API library', long_description = read('README.md'), install_requires=[ 'requests', ], # see here for complete list of classifiers # http://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=( 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Programming Language :: Python', ), )
# -*- coding: utf-8 -*- import os from setuptools import setup def read(fname): try: return open(os.path.join(os.path.dirname(__file__), fname)).read() except: return '' setup( name='todoist-python', version='0.2.12', packages=['todoist', 'todoist.managers'], author='Doist Team', author_email='info@todoist.com', license='BSD', description='todoist-python - The official Todoist Python API library', long_description = read('README.md'), install_requires=[ 'requests', ], # see here for complete list of classifiers # http://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=( 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Programming Language :: Python', ), )
Add support for new jOOQ 3.15 distributions I've just published jOOQ 3.15, see: https://blog.jooq.org/2021/07/06/3-15-0-release-with-support-for-r2dbc-nested-row-array-and-multiset-types-5-new-sql-dialects-create-procedure-function-and-trigger-support-and-much-more/ jOOQ 3.15 includes the following changes that are relevant for your plugin: - The commercial editions now have a new Java 11 distribution. The default distribution is a Java 17 distribution (currently supporting Java 16) - Support for the Java 6 distribution has been dropped in jOOQ 3.15, though I guess you should keep that enum value for now, in case someone uses jOOQ 3.14 or less - The open source edition requires Java 11 starting from jOOQ 3.15 Let me know if you need any additional info and I'll be very happy to help.
/* Copyright 2014 Etienne Studer Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package nu.studer.gradle.jooq; /** * jOOQ comes in different editions, which are published * under different group ids. The artifact names and versions * are the same for all editions. */ public enum JooqEdition { OSS("org.jooq"), PRO("org.jooq.pro"), PRO_JAVA_11("org.jooq.pro-java-11"), PRO_JAVA_8("org.jooq.pro-java-8"), PRO_JAVA_6("org.jooq.pro-java-6"), TRIAL("org.jooq.trial"), TRIAL_JAVA_11("org.jooq.trial-java-11"), TRIAL_JAVA_8("org.jooq.trial-java-8"), TRIAL_JAVA_6("org.jooq.trial-java-6"); private final String groupId; JooqEdition(String groupId) { this.groupId = groupId; } public String getGroupId() { return groupId; } }
/* Copyright 2014 Etienne Studer Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package nu.studer.gradle.jooq; /** * jOOQ comes in different editions, which are published * under different group ids. The artifact names and versions * are the same for all editions. */ public enum JooqEdition { OSS("org.jooq"), PRO("org.jooq.pro"), PRO_JAVA_8("org.jooq.pro-java-8"), PRO_JAVA_6("org.jooq.pro-java-6"), TRIAL("org.jooq.trial"), TRIAL_JAVA_8("org.jooq.trial-java-8"), TRIAL_JAVA_6("org.jooq.trial-java-6"); private final String groupId; JooqEdition(String groupId) { this.groupId = groupId; } public String getGroupId() { return groupId; } }
Remove leftover imports from testing
import os from cs251tk.student import remove from cs251tk.student import clone_student from cs251tk.student import stash from cs251tk.student import pull from cs251tk.student import checkout_date from cs251tk.student import record from cs251tk.student import reset from cs251tk.student import analyze def process_student( student, *, assignments, basedir, clean, date, debug, interact, no_check, no_update, specs, stogit_url ): if clean: remove(student) clone_student(student, baseurl=stogit_url) try: stash(student, no_update=no_update) pull(student, no_update=no_update) checkout_date(student, date=date) recordings = record(student, specs=specs, to_record=assignments, basedir=basedir, debug=debug, interact=interact) analysis = analyze(student, specs, check_for_branches=not no_check) if date: reset(student) return analysis, recordings except Exception as err: if debug: raise err return {'username': student, 'error': err}, []
import os from cs251tk.student import remove from cs251tk.student import clone_student from cs251tk.student import stash from cs251tk.student import pull from cs251tk.student import checkout_date from cs251tk.student import record from cs251tk.student import reset from cs251tk.student import analyze from cs251tk.common import run from ..common import chdir def process_student( student, *, assignments, basedir, clean, date, debug, interact, no_check, no_update, specs, stogit_url ): if clean: remove(student) clone_student(student, baseurl=stogit_url) try: stash(student, no_update=no_update) pull(student, no_update=no_update) checkout_date(student, date=date) recordings = record(student, specs=specs, to_record=assignments, basedir=basedir, debug=debug, interact=interact) analysis = analyze(student, specs, check_for_branches=not no_check) if date: reset(student) return analysis, recordings except Exception as err: if debug: raise err return {'username': student, 'error': err}, []
Update Blog model and content item matching
""" Definition of the plugin. """ from django.apps import apps from django.conf import settings from django.utils.translation import ugettext_lazy as _ from fluent_contents.extensions import ContentPlugin, plugin_pool default_blog_model = 'blog_tools.BlogPost' icekit_blog_model = getattr(settings, 'ICEKIT_BLOG_MODEL', default_blog_model) BLOG_MODEL = apps.get_model(*icekit_blog_model.rsplit('.', 1)) if icekit_blog_model != default_blog_model: @plugin_pool.register class BlogPostPlugin(ContentPlugin): model = apps.get_model(getattr(settings, 'ICEKIT_BLOG_CONTENT_ITEM', 'blog_post.BlogPostItem')) category = _('Blog') render_template = 'icekit/plugins/post/default.html' raw_id_fields = ['post', ]
""" Definition of the plugin. """ from django.apps import apps from django.conf import settings from django.db.models.loading import get_model from django.utils.translation import ugettext_lazy as _ from fluent_contents.extensions import ContentPlugin, plugin_pool default_blog_model = 'blog_tools.BlogPost' icekit_blog_model = getattr(settings, 'ICEKIT_BLOG_MODEL', default_blog_model) BLOG_MODEL = apps.get_model(*icekit_blog_model.rsplit('.', 1)) if icekit_blog_model != default_blog_model: @plugin_pool.register class BlogPostPlugin(ContentPlugin): model = get_model(getattr(settings, 'ICEKIT_BLOG_CONTENT_ITEM', 'blog_post.PostItem')) category = _('Blog') render_template = 'icekit/plugins/post/default.html' raw_id_fields = ['post', ]
Make pages' links in the header active when we visit them
<div class="navbar navbar-default"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="/">Husky Helpers</a> </div> <div class="navbar-collapse collapse"> <ul class="nav navbar-nav"> <li <? if($_SERVER['PHP_SELF'] == "/index.php") { ?>class="active"<? } ?>><a href="/">Home</a></li> <li <? if($_SERVER['PHP_SELF'] == "/eventlist.php") { ?>class="active"<? } ?>><a href="/eventlist.php">Event List</a></li> <li <? if($_SERVER['PHP_SELF'] == "/evententry.php") { ?>class="active"<? } ?>><a href="/evententry.php">Event Entry</a></li> </ul> </div><!--/.nav-collapse --> </div>
<div class="navbar navbar-default"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="/">Husky Helpers</a> </div> <div class="navbar-collapse collapse"> <ul class="nav navbar-nav"> <li class="active"><a href="/">Home</a></li> <li><a href="/eventlist.php">Event List</a></li> <li><a href="/evententry.php">Event Entry</a></li> </ul> </div><!--/.nav-collapse --> </div>
Add Spanish to list of available languages
import Settings from 'utils/Settings'; import cs from './lang/cs'; import en from './lang/en'; import es from './lang/es'; import nl from './lang/nl'; import sk from './lang/sk'; const ALL = [ cs, en, es, nl, sk ]; function getAvailable() { return ALL.slice(); } function getSelected() { return Settings.get().then(({ language }) => language); } function find(languageCode) { const majorLanguageCode = languageCode.split(/-_/).shift().toLowerCase(); return ALL.find(({ code }) => code === majorLanguageCode); } function detect(document) { const siteLanguageCode = document.documentElement.getAttribute('lang'); const navigatorLanguageCode = navigator.language; const detectedlanguage = find(siteLanguageCode) || find(navigatorLanguageCode); return detectedlanguage || null; } export default { detect, find, getAvailable, getSelected };
import Settings from 'utils/Settings'; import cs from './lang/cs'; import en from './lang/en'; import nl from './lang/nl'; import sk from './lang/sk'; const ALL = [ cs, en, nl, sk ]; function getAvailable() { return ALL.slice(); } function getSelected() { return Settings.get().then(({ language }) => language); } function find(languageCode) { const majorLanguageCode = languageCode.split(/-_/).shift().toLowerCase(); return ALL.find(({ code }) => code === majorLanguageCode); } function detect(document) { const siteLanguageCode = document.documentElement.getAttribute('lang'); const navigatorLanguageCode = navigator.language; const detectedlanguage = find(siteLanguageCode) || find(navigatorLanguageCode); return detectedlanguage || null; } export default { detect, find, getAvailable, getSelected };
fix(build): Fix the typo when copying fonts. fixes #907
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ module.exports = function (grunt) { 'use strict'; grunt.config('rev', { dist: { files: { src: [ '<%= yeoman.dist %>/bower_components/{,*/}*.js', '<%= yeoman.dist %>/bower_components/**/*.{woff,eot,ttf,svg,ofl}', '<%= yeoman.dist %>/scripts/{,*/}*.js', '<%= yeoman.dist %>/styles/{,*/}*.css', '<%= yeoman.dist %>/images/{,*/}*.{png,jpg,jpeg,gif,webp}' ] } } }); };
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ module.exports = function (grunt) { 'use strict'; grunt.config('rev', { dist: { files: { src: [ '<%= yeoman.dist %>/bower_components/{,*/}*.js', '<%= yeoman.dist %>/bower_components/**/*.{woff,eot,ttf,svg.ofl}', '<%= yeoman.dist %>/scripts/{,*/}*.js', '<%= yeoman.dist %>/styles/{,*/}*.css', '<%= yeoman.dist %>/images/{,*/}*.{png,jpg,jpeg,gif,webp}' ] } } }); };
Use TachyFontData to get the base data. Get the fontname from the request. Add copyright.
/* * Copyright 2015 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.github.googlei18n.tachyfont; import java.io.IOException; import java.io.OutputStream; import javax.servlet.http.*; @SuppressWarnings("serial") public class GetBase extends HttpServlet { @Override public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { // Get the TachyFont base. String pathInfo = req.getPathInfo(); String[] pathParts = pathInfo.split("/"); if (!("".equals(pathParts[0])) || !("base".equals(pathParts[2]))) { throw new IOException(); } byte[] buffer = TachyFontData.getBase(pathParts[1]); // TODO(bstell): Check that the transfer is compressed. //resp.setContentType("application/x-font-otf"); resp.setContentType("application/binary"); OutputStream outputStream = resp.getOutputStream(); outputStream.write(buffer); } }
package com.github.googlei18n.tachyfont; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.jar.JarEntry; import java.util.jar.JarFile; import java.util.zip.GZIPOutputStream; import javax.servlet.http.*; @SuppressWarnings("serial") public class GetBase extends HttpServlet { @Override public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { // Get the TachyFont base. System.out.println("need to get the font parameter"); String jarFilename = "fonts/noto/sans/NotoSansJP-Thin.TachyFont.jar"; JarFile jarFile = new JarFile("WEB-INF/" + jarFilename); JarEntry base = jarFile.getJarEntry("base"); InputStream baseStream = jarFile.getInputStream(base); // Send the data. byte[] buffer = new byte[4096]; int bytesRead = 0; resp.setContentType("application/x-font-otf"); OutputStream outputStream = resp.getOutputStream(); // GZIPOutputStream gzipOutputStream = new GZIPOutputStream(outputStream); // resp.setHeader("Content-Encoding", "gzip"); while ((bytesRead = baseStream.read(buffer)) != -1) { outputStream.write(buffer, 0, bytesRead); } // gzipOutputStream.close(); jarFile.close(); } }
Fix Two Bugs for MidRand
from random import shuffle def midrand(sentence): words = sentence.split() newwords = [randomized(word) for word in words] newsentence = ' '.join(newwords) if sentence == newsentence: return "They can't be different" else: return newsentence def randomized(word): if len(set(word[1:-1])) < 2: return word mid = range(1, len(word) - 1) while True: pre = mid[:] shuffle(mid) isdiff = False for j in range(len(mid)): if word[pre[j]] != word[mid[j]]: isdiff = True break if isdiff: break newword = word[0] for i in mid: newword += word[i] newword += word[-1] return newword def main(): tests = [] tests.append("A") tests.append("I eat apple") tests.append("A fox runs so fast that it suddenly die") for test in tests: print test print midrand(test) print if __name__ == "__main__": main()
from random import shuffle def midrand(sentence): words = sentence.split() newwords = [randomized(word) for word in words] newsentence = ' '.join(newwords) if sentence == newsentence: return "They can't be different" else: return newsentence def randomized(word): if len(set(word[1:-1])) < 2: return word mid = range(1, len(word) - 1) pre = mid[:] while pre == mid: pre = mid[:] shuffle(mid) newword = word[0] for i in mid: newword += word[i] newword += word[-1] return newword tests = [] tests.append("I love you so much") tests.append("A fox runs so fast so it has to die in a extremely way") tests.append("A") for test in tests: print midrand(test)
Add print statements for logging lambda func
var https = require('https'); exports.handler = function(event, context, callback) { // This token should live as an environmental variable set in the // build config for Netlify. var bearerToken = process.env.TWITTER_BEARER_TOKEN; if (bearerToken == null) { callback('Could not find required TWITTER_BEARER_TOKEN environmental variable.'); } var authToken = 'Bearer ' + bearerToken; var queryString = '?q=chano4mayor%20OR%20chance4mayor%20OR%20chanoformayor%20OR%20chanceformayor'; var options = { hostname: 'api.twitter.com', path: '/1.1/search/tweets.json' + queryString, headers: { 'Authorization': authToken } }; console.log('Initializing https request...'); https.get(options, function(res) { console.log('https request sent! Waiting for response...'); res.on('data', function(data) { console.log('Data received'); callback(null, { statusCode: 200, body: data }) }); }).on('error', function(err) { console.log('Error in the https request'); callback(err); }); }
var https = require('https'); exports.handler = function(event, context, callback) { // This token should live as an environmental variable set in the // build config for Netlify. var bearerToken = process.env.TWITTER_BEARER_TOKEN; if (bearerToken == null) { callback('Could not find required TWITTER_BEARER_TOKEN environmental variable.'); } var authToken = 'Bearer ' + bearerToken; var queryString = '?q=chano4mayor%20OR%20chance4mayor%20OR%20chanoformayor%20OR%20chanceformayor'; var options = { hostname: 'api.twitter.com', path: '/1.1/search/tweets.json' + queryString, headers: { 'Authorization': authToken } }; https.get(options, function(res) { res.on('data', function(data) { callback(null, { statusCode: 200, body: data }) }); }).on('error', function(err) { callback(err); }); }
Fix undeclared variable in node runtime
$JSRTS.os = require('os'); $JSRTS.fs = require('fs'); $JSRTS.prim_systemInfo = function (index) { switch (index) { case 0: return "node"; case 1: return $JSRTS.os.platform(); } return ""; }; $JSRTS.prim_writeStr = function (x) { return process.stdout.write(x) } $JSRTS.prim_readStr = function () { var ret = ''; var b = new Buffer(1024); var i = 0; while (true) { $JSRTS.fs.readSync(0, b, i, 1) if (b[i] == 10) { ret = b.toString('utf8', 0, i); break; } i++; if (i == b.length) { var nb = new Buffer(b.length * 2); b.copy(nb) b = nb; } } return ret; };
$JSRTS.os = require('os'); $JSRTS.fs = require('fs'); $JSRTS.prim_systemInfo = function (index) { switch (index) { case 0: return "node"; case 1: return $JSRTS.os.platform(); } return ""; }; $JSRTS.prim_writeStr = function (x) { return process.stdout.write(x) } $JSRTS.prim_readStr = function () { var ret = ''; var b = new Buffer(1024); var i = 0; while (true) { $JSRTS.fs.readSync(0, b, i, 1) if (b[i] == 10) { ret = b.toString('utf8', 0, i); break; } i++; if (i == b.length) { nb = new Buffer(b.length * 2); b.copy(nb) b = nb; } } return ret; };
Throw when no user agent supplied during server-side rendering
/** * Based on https://github.com/jsstyles/css-vendor, but without having to * convert between different cases all the time. * * @flow */ import InlineStylePrefixer from 'inline-style-prefixer'; function transformValues(style) { return Object.keys(style).reduce((newStyle, key) => { let value = style[key]; if (Array.isArray(value)) { value = value.join(';' + key + ':'); } newStyle[key] = value; return newStyle; }, {}); } let lastUserAgent; let prefixer; // Returns a new style object with vendor prefixes added to property names // and values. export function getPrefixedStyle( style: Object, componentName: ?string, userAgent?: ?string, ): Object { const actualUserAgent = userAgent || (global && global.navigator && global.navigator.userAgent); if (!actualUserAgent) { throw new Error( 'Radium: userAgent must be supplied for server-side rendering. See ' + 'https://github.com/FormidableLabs/radium/tree/master/docs/api#radium ' + 'for more information.' ); } if (!prefixer || actualUserAgent !== lastUserAgent) { prefixer = new InlineStylePrefixer(actualUserAgent); lastUserAgent = actualUserAgent; } const prefixedStyle = prefixer.prefix(style); const prefixedStyleWithFallbacks = transformValues(prefixedStyle); return prefixedStyleWithFallbacks; }
/** * Based on https://github.com/jsstyles/css-vendor, but without having to * convert between different cases all the time. * * @flow */ import InlineStylePrefixer from 'inline-style-prefixer'; function transformValues(style) { return Object.keys(style).reduce((newStyle, key) => { let value = style[key]; if (Array.isArray(value)) { value = value.join(';' + key + ':'); } newStyle[key] = value; return newStyle; }, {}); } // Returns a new style object with vendor prefixes added to property names // and values. export function getPrefixedStyle( style: Object, componentName: ?string, userAgent?: ?string, ): Object { const prefixer = new InlineStylePrefixer(userAgent); const prefixedStyle = prefixer.prefix(style); const prefixedStyleWithFallbacks = transformValues(prefixedStyle); return prefixedStyleWithFallbacks; }
lastfm: Add default config and config schema
from __future__ import unicode_literals import mopidy from mopidy import exceptions, ext from mopidy.utils import config, formatting default_config = """ [ext.lastfm] # If the Last.fm extension should be enabled or not enabled = true # Your Last.fm username username = # Your Last.fm password password = """ __doc__ = """ Frontend which scrobbles the music you play to your `Last.fm <http://www.last.fm>`_ profile. .. note:: This frontend requires a free user account at Last.fm. **Dependencies:** .. literalinclude:: ../../../requirements/lastfm.txt **Default config:** .. code-block:: ini %(config)s **Usage:** The frontend is enabled by default if all dependencies are available. """ % {'config': formatting.indent(default_config)} class Extension(ext.Extension): name = 'Mopidy-Lastfm' version = mopidy.__version__ def get_default_config(self): return default_config def get_config_schema(self): schema = config.ExtensionConfigSchema() schema['username'] = config.String() schema['password'] = config.String(secret=True) return schema def validate_environment(self): try: import pylast # noqa except ImportError as e: raise exceptions.ExtensionError('pylast library not found', e) def get_frontend_classes(self): from .actor import LastfmFrontend return [LastfmFrontend]
from __future__ import unicode_literals import mopidy from mopidy import ext from mopidy.exceptions import ExtensionError __doc__ = """ Frontend which scrobbles the music you play to your `Last.fm <http://www.last.fm>`_ profile. .. note:: This frontend requires a free user account at Last.fm. **Dependencies:** .. literalinclude:: ../../../requirements/lastfm.txt **Settings:** - :attr:`mopidy.settings.LASTFM_USERNAME` - :attr:`mopidy.settings.LASTFM_PASSWORD` **Usage:** The frontend is enabled by default if all dependencies are available. """ class Extension(ext.Extension): name = 'Mopidy-Lastfm' version = mopidy.__version__ def get_default_config(self): return '[ext.lastfm]' def validate_config(self, config): pass def validate_environment(self): try: import pylast # noqa except ImportError as e: raise ExtensionError('pylast library not found', e) def get_frontend_classes(self): from .actor import LastfmFrontend return [LastfmFrontend]
Add config reloading to the reload command.
package com.campmongoose.serversaturday.spigot.command.sscommand; import com.campmongoose.serversaturday.common.Reference.Commands; import com.campmongoose.serversaturday.common.Reference.Messages; import com.campmongoose.serversaturday.common.Reference.Permissions; import com.campmongoose.serversaturday.spigot.command.AbstractSpigotCommand; import com.campmongoose.serversaturday.spigot.command.SpigotCommandArgument; import com.campmongoose.serversaturday.spigot.command.SpigotCommandPermissions; import com.campmongoose.serversaturday.spigot.command.SpigotCommandUsage; import java.util.Arrays; import org.bukkit.ChatColor; public class SSReload extends AbstractSpigotCommand { public SSReload() { super(Commands.RELOAD_NAME, Commands.RELOAD_DESC); } @Override protected void build() { usage = new SpigotCommandUsage(Arrays.asList(new SpigotCommandArgument(Commands.SS_CMD), new SpigotCommandArgument(Commands.RELOAD_NAME))); permissions = new SpigotCommandPermissions(Permissions.RELOAD, false); executor = (sender, args) -> { getSubmissions().save(); getSubmissions().load(); getPluginInstance().getPluginConfig().reload(); sender.sendMessage(ChatColor.GOLD + Messages.PLUGIN_RELOADED); return true; }; } }
package com.campmongoose.serversaturday.spigot.command.sscommand; import com.campmongoose.serversaturday.common.Reference.Commands; import com.campmongoose.serversaturday.common.Reference.Messages; import com.campmongoose.serversaturday.common.Reference.Permissions; import com.campmongoose.serversaturday.spigot.command.AbstractSpigotCommand; import com.campmongoose.serversaturday.spigot.command.SpigotCommandArgument; import com.campmongoose.serversaturday.spigot.command.SpigotCommandPermissions; import com.campmongoose.serversaturday.spigot.command.SpigotCommandUsage; import java.util.Arrays; import org.bukkit.ChatColor; public class SSReload extends AbstractSpigotCommand { public SSReload() { super(Commands.RELOAD_NAME, Commands.RELOAD_DESC); } @Override protected void build() { usage = new SpigotCommandUsage(Arrays.asList(new SpigotCommandArgument(Commands.SS_CMD), new SpigotCommandArgument(Commands.RELOAD_NAME))); permissions = new SpigotCommandPermissions(Permissions.RELOAD, false); executor = (sender, args) -> { getSubmissions().save(); getSubmissions().load(); sender.sendMessage(ChatColor.GOLD + Messages.PLUGIN_RELOADED); return true; }; } }
Remove browserSync.stream() so that it's only executed in inject task to avoid conflicts
const gulp = require('gulp'); const browserSync = require('browser-sync'); <% if (js === 'babel' || framework === 'react' && js === 'js') { -%> const babel = require('gulp-babel'); <% } -%> <% if (js === 'typescript') { -%> const typescript = require('gulp-typescript'); const tsConf = require('../conf/ts.conf.json').compilerOptions; <% } -%> const conf = require('../conf/gulp.conf'); gulp.task('scripts', scripts); function scripts() { return gulp.src(conf.path.src('**/*.js')) <% if (js === 'babel' || framework === 'react' && js === 'js') { -%> .pipe(babel()) <% } -%> <% if (js === 'typescript') { -%> .pipe(typescript(tsConf)) <% } -%> .pipe(gulp.dest(conf.path.tmp())); }
const gulp = require('gulp'); const browserSync = require('browser-sync'); <% if (js === 'babel' || framework === 'react' && js === 'js') { -%> const babel = require('gulp-babel'); <% } -%> <% if (js === 'typescript') { -%> const typescript = require('gulp-typescript'); const tsConf = require('../conf/ts.conf.json').compilerOptions; <% } -%> const conf = require('../conf/gulp.conf'); gulp.task('scripts', scripts); function scripts() { return gulp.src(conf.path.src('**/*.js')) <% if (js === 'babel' || framework === 'react' && js === 'js') { -%> .pipe(babel()) <% } -%> <% if (js === 'typescript') { -%> .pipe(typescript(tsConf)) <% } -%> .pipe(gulp.dest(conf.path.tmp())) .pipe(browserSync.stream()); }
Remove unnecessary argument in test
from __future__ import unicode_literals import pytest from ...symbols import POS, VERB, VerbForm_inf from ...tokens import Doc from ...vocab import Vocab from ...lemmatizer import Lemmatizer @pytest.fixture def index(): return {'verb': {}} @pytest.fixture def exceptions(): return {'verb': {}} @pytest.fixture def rules(): return {"verb": [["ed", "e"]]} @pytest.fixture def lemmatizer(index, exceptions, rules): return Lemmatizer(index, exceptions, rules) @pytest.fixture def tag_map(): return {'VB': {POS: VERB, 'morph': VerbForm_inf}} @pytest.fixture def vocab(lemmatizer, tag_map): return Vocab(lemmatizer=lemmatizer, tag_map=tag_map) def test_not_lemmatize_base_forms(vocab): doc = Doc(vocab, words=["Do", "n't", "feed", "the", "dog"]) feed = doc[2] feed.tag_ = u'VB' assert feed.text == u'feed' assert feed.lemma_ == u'feed'
from __future__ import unicode_literals import pytest from ...symbols import POS, VERB, VerbForm_inf from ...tokens import Doc from ...vocab import Vocab from ...lemmatizer import Lemmatizer @pytest.fixture def index(): return {'verb': {}} @pytest.fixture def exceptions(): return {'verb': {}} @pytest.fixture def rules(): return {"verb": [["ed", "e"]]} @pytest.fixture def lemmatizer(index, exceptions, rules): return Lemmatizer(index, exceptions, rules) @pytest.fixture def tag_map(): return {'VB': {POS: VERB, 'morph': VerbForm_inf}} @pytest.fixture def vocab(lemmatizer, tag_map): return Vocab(lemmatizer=lemmatizer, tag_map=tag_map) def test_not_lemmatize_base_forms(vocab, lemmatizer): doc = Doc(vocab, words=["Do", "n't", "feed", "the", "dog"]) feed = doc[2] feed.tag_ = u'VB' assert feed.text == u'feed' assert feed.lemma_ == u'feed'
[Python] Add strikes support when rolling
class Game(): def __init__(self): self._rolls = [0] * 21 self._current_roll = 0 def roll(self, pins): self._rolls[self._current_roll] += pins self._current_roll += 1 if pins < 10 else 2 def score(self): score = 0 for frame in range(0, 20, 2): if self._is_strike(frame): score += 10 + self._rolls[frame + 2] + self._rolls[frame + 3] elif self._is_spare(frame): score += 10 + self._rolls[frame + 2] else: score += self._frame_score(frame) return score def _is_spare(self, frame): return self._rolls[frame] + self._rolls[frame + 1] == 10 def _is_strike(self, frame): print(frame) return self._rolls[frame] == 10 def _frame_score(self, frame): return self._rolls[frame] + self._rolls[frame + 1]
class Game(): def __init__(self): self._rolls = [0] * 21 self._current_roll = 0 def roll(self, pins): self._rolls[self._current_roll] += pins self._current_roll += 1 def score(self): score = 0 for frame in range(0, 20, 2): if self._is_spare(frame): score += 10 + self._rolls[frame + 2] else: score += self._frame_score(frame) return score def _is_spare(self, frame): return self._rolls[frame] + self._rolls[frame + 1] == 10 def _frame_score(self, frame): return self._rolls[frame] + self._rolls[frame + 1]
Use appspotmail.com instead of appspot.com for email sender
# Copy this file to config.py and change the settings. Don't forget to specify your own SECRET_KEY. # The app name will be used in several places. APP_NAME = 'Yelp Love' APP_BASE_URL = 'https://PROJECT_ID.appspot.com/' LOVE_SENDER_EMAIL = 'Yelp Love <love@PROJECT_ID.appspotmail.com>' # Flask's secret key, used to encrypt the session cookie. # Set this to any random string and make sure not to share this! SECRET_KEY = 'YOUR_SECRET_HERE' # Use default theme THEME = 'default' # Every employee needs a reference to a Google Account. This reference is based on the users # Google Account email address and created when employee data is imported: we take the *username* # and this DOMAIN DOMAIN = 'example.com' # Name of the S3 bucket used to import employee data from a file named employees.json # Check out /import/employees.json.example to see how this file should look like. S3_BUCKET = 'employees'
# Copy this file to config.py and change the settings. Don't forget to specify your own SECRET_KEY. # The app name will be used in several places. APP_NAME = 'Yelp Love' APP_BASE_URL = 'https://PROJECT_ID.appspot.com/' LOVE_SENDER_EMAIL = 'Yelp Love <love@PROJECT_ID.appspot.com>' # Flask's secret key, used to encrypt the session cookie. # Set this to any random string and make sure not to share this! SECRET_KEY = 'YOUR_SECRET_HERE' # Use default theme THEME = 'default' # Every employee needs a reference to a Google Account. This reference is based on the users # Google Account email address and created when employee data is imported: we take the *username* # and this DOMAIN DOMAIN = 'example.com' # Name of the S3 bucket used to import employee data from a file named employees.json # Check out /import/employees.json.example to see how this file should look like. S3_BUCKET = 'employees'
Include API url in JS call
<?php include('lib/panda.php'); include('lib/config.inc.php'); include('lib/head.inc.html'); ?> <p>This is an example <strong>Panda</strong> client application, written in <strong>PHP</strong>.</p> <form action="/player.php" method="get" id="upload-form"> <label>Upload a video<br/></label> <span id="upload_button"></span> <input type="text" id="upload_filename" disabled="true" class="panda_upload_filename" /> <div id="upload_progress" class="panda_upload_progress"></div> <input type="hidden" id="returned_video_id" name="panda_video_id" /> <script type="text/javascript"> $('#returned_video_id').pandaUploader(<?php echo json_encode(@$panda->signed_params("POST", "/videos.json", array())); ?>, { upload_button_id: 'upload_button', upload_filename_id: 'upload_filename', upload_progress_id: 'upload_progress', api_url: '<?php echo $panda->api_url() ?>' }); </script> <p><input type="submit" value="Save" /></p> </form> <?php include('lib/foot.inc.html'); ?>
<?php include('lib/panda.php'); include('lib/config.inc.php'); include('lib/head.inc.html'); ?> <p>This is an example <strong>Panda</strong> client application, written in <strong>PHP</strong>.</p> <form action="/player.php" method="get" id="upload-form"> <label>Upload a video<br/></label> <span id="upload_button"></span> <input type="text" id="upload_filename" disabled="true" class="panda_upload_filename" /> <div id="upload_progress" class="panda_upload_progress"></div> <input type="hidden" id="returned_video_id" name="panda_video_id" /> <script type="text/javascript"> $('#returned_video_id').pandaUploader(<?php echo json_encode(@$panda->signed_params("POST", "/videos.json", array())); ?>, { upload_button_id: 'upload_button', upload_filename_id: 'upload_filename', upload_progress_id: 'upload_progress' }); </script> <p><input type="submit" value="Save" /></p> </form> <?php include('lib/foot.inc.html'); ?>
Fix id tags and svn:keywords for optimization package. git-svn-id: 80d496c472b8b763a5e941dba212da9bf48aeceb@1364392 13f79535-47bb-0310-9956-ffa450edef68
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.math3.optimization; import java.io.Serializable; /** * Goal type for an optimization problem. * * @version $Id$ * @since 2.0 */ public enum GoalType implements Serializable { /** Maximization goal. */ MAXIMIZE, /** Minimization goal. */ MINIMIZE }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.math3.optimization; import java.io.Serializable; /** * Goal type for an optimization problem. * @version $Id$ * @since 2.0 */ public enum GoalType implements Serializable { /** Maximization goal. */ MAXIMIZE, /** Minimization goal. */ MINIMIZE }
Fix line lengths to keep Travis happy
define(function () { // French return { errorLoading: function () { return 'Les résultats ne peuvent pas être chargés.'; }, inputTooLong: function (args) { var overChars = args.input.length - args.maximum; return 'Supprimez ' + overChars + ' caractère' + (overChars > 1) ? 's' : ''; }, inputTooShort: function (args) { var remainingChars = args.minimum - args.input.length; return 'Saisissez au moins ' + remainingChars + ' caractère' + (remainingChars > 1) ? 's' : ''; }, loadingMore: function () { return 'Chargement de résultats supplémentaires…'; }, maximumSelected: function (args) { return 'Vous pouvez seulement sélectionner ' + args.maximum + ' élément' + (args.maximum > 1) ? 's' : ''; }, noResults: function () { return 'Aucun résultat trouvé'; }, searching: function () { return 'Recherche en cours…'; } }; });
define(function () { // French return { errorLoading: function () { return 'Les résultats ne peuvent pas être chargés.'; }, inputTooLong: function (args) { var overChars = args.input.length - args.maximum; return 'Supprimez ' + overChars + ' caractère' + (overChars > 1) ? 's' : ''; }, inputTooShort: function (args) { var remainingChars = args.minimum - args.input.length; return 'Saisissez au moins ' + remainingChars + ' caractère' + (remainingChars > 1) ? 's' : ''; }, loadingMore: function () { return 'Chargement de résultats supplémentaires…'; }, maximumSelected: function (args) { return 'Vous pouvez seulement sélectionner ' + args.maximum + ' élément' + (args.maximum > 1) ? 's' : ''; }, noResults: function () { return 'Aucun résultat trouvé'; }, searching: function () { return 'Recherche en cours…'; } }; });
Add a list filter to make looking a specific users easier.
from django.contrib import admin from twitter.models import User, Tweet, Analytics, AnalyticsReport class UserAdmin(admin.ModelAdmin): list_display = ('screen_name', 'current_followers') class AnalyticsAdmin(admin.ModelAdmin): list_display = ( 'date', 'user', 'followers', 'following', 'listed', 'tweet_count', 'retweet_count', 'reply_count', 'user_mention_count', 'link_count', 'hashtag_count', ) list_filter = ('user',) class AnalyticsReportAdmin(admin.ModelAdmin): list_display = ( 'date', 'user', 'tweets_reweeted_count', 'tweets_favorited_count', ) admin.site.register(User, UserAdmin) admin.site.register(Tweet) admin.site.register(Analytics, AnalyticsAdmin) admin.site.register(AnalyticsReport, AnalyticsReportAdmin)
from django.contrib import admin from twitter.models import User, Tweet, Analytics, AnalyticsReport class UserAdmin(admin.ModelAdmin): list_display = ('screen_name', 'current_followers') class AnalyticsAdmin(admin.ModelAdmin): list_display = ( 'date', 'user', 'followers', 'following', 'listed', 'tweet_count', 'retweet_count', 'reply_count', 'user_mention_count', 'link_count', 'hashtag_count', ) class AnalyticsReportAdmin(admin.ModelAdmin): list_display = ( 'date', 'user', 'tweets_reweeted_count', 'tweets_favorited_count', ) admin.site.register(User, UserAdmin) admin.site.register(Tweet) admin.site.register(Analytics, AnalyticsAdmin) admin.site.register(AnalyticsReport, AnalyticsReportAdmin)
Fix jvm.info metric naming to match micrometer convention This patch brings the jvm.info metric in line with other jvm metric names and in line with general micrometer naming conventions which define "." as the separator. This will later automatically convert to "_" through a prometheus naming convention if prometheus export is used. Even in a pure prometheus use-case the difference is relevantas metric mappers and filters see the original name.
package io.quarkus.micrometer.runtime.binder; import io.micrometer.core.instrument.Counter; import io.micrometer.core.instrument.MeterRegistry; import io.micrometer.core.instrument.binder.MeterBinder; public class JVMInfoBinder implements MeterBinder { @Override public void bindTo(MeterRegistry registry) { Counter.builder("jvm.info") .description("JVM version info") .tags("version", System.getProperty("java.runtime.version", "unknown"), "vendor", System.getProperty("java.vm.vendor", "unknown"), "runtime", System.getProperty("java.runtime.name", "unknown")) .register(registry) .increment(); } }
package io.quarkus.micrometer.runtime.binder; import io.micrometer.core.instrument.Counter; import io.micrometer.core.instrument.MeterRegistry; import io.micrometer.core.instrument.binder.MeterBinder; public class JVMInfoBinder implements MeterBinder { @Override public void bindTo(MeterRegistry registry) { Counter.builder("jvm_info") .description("JVM version info") .tags("version", System.getProperty("java.runtime.version", "unknown"), "vendor", System.getProperty("java.vm.vendor", "unknown"), "runtime", System.getProperty("java.runtime.name", "unknown")) .register(registry) .increment(); } }
Disable bts plugin for general usage
# -*- coding: utf-8 -*- from functools import wraps from pollirio import commands def old_expose(cmd): def inner(fn): def wrapped(*args, **kwargs): commands[cmd] = fn fn(*args) return wraps(fn)(wrapped) return inner def expose(cmd, args=None): def decorator(fn): commands[cmd] = {"func":fn, "args":args} return fn return decorator def plugin_run(name, *args): if name in commands: return commands.get(name)["func"](*args) def check_args(name, bot, ievent): if name in commands: if commands.get(name)["args"]: # TODO: check if we have all the arguments print len(ievent.args), commands.get(name)["args"] if len(ievent.args) < commands.get(name)["args"]: bot.msg(ievent.channel, "%s: %s" % (ievent.nick, commands.get(name)["func"].__doc__)) return False else: return True else: return True return False from lart import * from polygen import * #from bts import * from misc import *
# -*- coding: utf-8 -*- from functools import wraps from pollirio import commands def old_expose(cmd): def inner(fn): def wrapped(*args, **kwargs): commands[cmd] = fn fn(*args) return wraps(fn)(wrapped) return inner def expose(cmd, args=None): def decorator(fn): commands[cmd] = {"func":fn, "args":args} return fn return decorator def plugin_run(name, *args): if name in commands: return commands.get(name)["func"](*args) def check_args(name, bot, ievent): if name in commands: if commands.get(name)["args"]: # TODO: check if we have all the arguments print len(ievent.args), commands.get(name)["args"] if len(ievent.args) < commands.get(name)["args"]: bot.msg(ievent.channel, "%s: %s" % (ievent.nick, commands.get(name)["func"].__doc__)) return False else: return True else: return True return False from lart import * from polygen import * from bts import * from misc import *
Fix how Request methods are called (pass them a 'this' arg) Needed so `this` is set to the right context when running
var debug = require( 'debug' )( 'wpcom-vip' ); var Request = require( './lib/util/request' ); // Modules function WPCOM_VIP( token ) { this.req = new Request( this ); this.auth = {}; } WPCOM_VIP.prototype.API_VERSION = '1'; WPCOM_VIP.prototype.API_TIMEOUT = 10000; WPCOM_VIP.prototype.get = function() { return this.req.get.apply( this.req, arguments ); }; WPCOM_VIP.prototype.post = function() { return this.req.post.apply( this.req, arguments ); }; WPCOM_VIP.prototype.put = function() { return this.req.get.apply( this.req, arguments ); }; WPCOM_VIP.prototype.delete = function() { return this.req.delete.apply( this.req, arguments ); }; module.exports = WPCOM_VIP;
var debug = require( 'debug' )( 'wpcom-vip' ); var Request = require( './lib/util/request' ); // Modules function WPCOM_VIP( token ) { this.req = new Request( this ); this.auth = {}; } WPCOM_VIP.prototype.API_VERSION = '1'; WPCOM_VIP.prototype.API_TIMEOUT = 10000; WPCOM_VIP.prototype.get = function() { return this.req.get.apply( arguments ); }; WPCOM_VIP.prototype.post = function() { return this.req.post.apply( arguments ); }; WPCOM_VIP.prototype.put = function() { return this.req.get.apply( arguments ); }; WPCOM_VIP.prototype.delete = function() { return this.req.delete.apply( arguments ); }; module.exports = WPCOM_VIP;
Add fixed vision tracking point constants to the fixed point command. These constants make it possible to centralize the coordinates used for fixed point vision tracking.
package com.edinarobotics.zed.commands; public class FixedPointVisionTrackingCommand extends VisionTrackingCommand { private double fixedXSetpoint; private double fixedYSetpoint; public static final double PYRAMID_BACK_MIDDLE_X = 0.0273556; public static final double PYRAMID_BACK_MIDDLE_Y = -0.29411; public static final double PYRAMID_BACK_RIGHT_X = -0.063829; public static final double PYRAMID_BACK_RIGHT_Y = -0.226891; public FixedPointVisionTrackingCommand(double xSetpoint, double ySetpoint) { super(); this.fixedXSetpoint = xSetpoint; this.fixedYSetpoint = ySetpoint; } public FixedPointVisionTrackingCommand(double xSetpoint, double ySetpoint, byte goalType) { super(goalType); this.fixedXSetpoint = xSetpoint; this.fixedYSetpoint = ySetpoint; } protected double getXSetpoint(double distance) { return fixedXSetpoint; } protected double getYSetpoint(double distance) { return fixedYSetpoint; } }
package com.edinarobotics.zed.commands; public class FixedPointVisionTrackingCommand extends VisionTrackingCommand { private double fixedXSetpoint; private double fixedYSetpoint; public FixedPointVisionTrackingCommand(double xSetpoint, double ySetpoint) { super(); this.fixedXSetpoint = xSetpoint; this.fixedYSetpoint = ySetpoint; } public FixedPointVisionTrackingCommand(double xSetpoint, double ySetpoint, byte goalType) { super(goalType); this.fixedXSetpoint = xSetpoint; this.fixedYSetpoint = ySetpoint; } protected double getXSetpoint(double distance) { return fixedXSetpoint; } protected double getYSetpoint(double distance) { return fixedYSetpoint; } }
Set editor holder to stacked
<?php class SirTrevorEditor extends TextareaField { private static function path($to = '') { return 'sirtrevor/' . $to; } /** * Includes the JavaScript neccesary for this field to work using the {@link Requirements} system. */ public static function requirements() { Requirements::css(self::path('thirdparty/sir-trevor-js/sir-trevor-icons.css')); Requirements::css(self::path('thirdparty/sir-trevor-js/sir-trevor.css')); Requirements::javascript(THIRDPARTY_DIR . '/jquery/jquery.js'); Requirements::javascript(THIRDPARTY_DIR. '/jquery-entwine/dist/jquery.entwine-dist.js'); Requirements::javascript(self::path('thirdparty/underscore/underscore-min.js')); Requirements::javascript(self::path('thirdparty/Eventable/eventable.js')); Requirements::javascript(self::path('thirdparty/sir-trevor-js/sir-trevor.js')); Requirements::javascript(self::path('javascript/sirtrevor.js')); } public function __construct($name, $title = null, $value = '') { parent::__construct($name, $title, $value); self::requirements(); } public function FieldHolder($properties = array()) { $this->addExtraClass('stacked'); return parent::FieldHolder($properties); } }
<?php class SirTrevorEditor extends TextareaField { private static function path($to = '') { return 'sirtrevor/' . $to; } /** * Includes the JavaScript neccesary for this field to work using the {@link Requirements} system. */ public static function requirements() { Requirements::css(self::path('thirdparty/sir-trevor-js/sir-trevor-icons.css')); Requirements::css(self::path('thirdparty/sir-trevor-js/sir-trevor.css')); Requirements::javascript(THIRDPARTY_DIR . '/jquery/jquery.js'); Requirements::javascript(THIRDPARTY_DIR. '/jquery-entwine/dist/jquery.entwine-dist.js'); Requirements::javascript(self::path('thirdparty/underscore/underscore-min.js')); Requirements::javascript(self::path('thirdparty/Eventable/eventable.js')); Requirements::javascript(self::path('thirdparty/sir-trevor-js/sir-trevor.js')); Requirements::javascript(self::path('javascript/sirtrevor.js')); } public function __construct($name, $title = null, $value = '') { parent::__construct($name, $title, $value); self::requirements(); } }
Update with reference to global nav partial
var _ = require('lodash') var fs = require('fs') var gzip = require('gzip-size') var filesize = require('filesize') var cssstats = require('cssstats') var module = require('tachyons-white-space/package.json') var moduleCss = fs.readFileSync('node_modules/tachyons-white-space/tachyons-white-space.min.css', 'utf8') var moduleObj = cssstats(moduleCss) var moduleSize = filesize(moduleObj.gzipSize) var srcCSS = fs.readFileSync('./src/_white-space.css', 'utf8') var navDocs = fs.readFileSync('./templates/nav_docs.html', 'utf8') var template = fs.readFileSync('./templates/docs/white-space/index.html', 'utf8') var tpl = _.template(template) var html = tpl({ moduleVersion: module.version, moduleSize: moduleSize, moduleObj: moduleObj, srcCSS: srcCSS, navDocs: navDocs }) fs.writeFileSync('./docs/typography/white-space/index.html', html)
var _ = require('lodash') var fs = require('fs') var gzip = require('gzip-size') var filesize = require('filesize') var cssstats = require('cssstats') var module = require('tachyons-white-space/package.json') var moduleCss = fs.readFileSync('node_modules/tachyons-white-space/tachyons-white-space.min.css', 'utf8') var moduleObj = cssstats(moduleCss) var moduleSize = filesize(moduleObj.gzipSize) var srcCSS = fs.readFileSync('./src/_white-space.css', 'utf8') var template = fs.readFileSync('./templates/docs/white-space/index.html', 'utf8') var tpl = _.template(template) var html = tpl({ moduleVersion: module.version, moduleSize: moduleSize, moduleObj: moduleObj, srcCSS: srcCSS }) fs.writeFileSync('./docs/typography/white-space/index.html', html)
Fix fake game one script
import random from django.core.management.base import BaseCommand from django.contrib.auth.models import User from mla_game.apps.accounts.models import Profile from ...models import ( Transcript, TranscriptPhraseDownvote ) class Command(BaseCommand): help = 'Creates random votes for all phrases in a random transcript' def handle(self, *args, **options): users = User.objects.all() transcript = Transcript.objects.random_transcript() for phrase in transcript.phrases.all(): for user in users: profile = Profile.objects.get(user=user) profile.considered_phrases.add(phrase) if random.choice([True, False]): TranscriptPhraseDownvote.objects.create( transcript_phrase=phrase, user=user )
import random from django.core.management.base import BaseCommand from django.contrib.auth.models import User from mla_game.apps.accounts.models import Profile from ...models import ( Transcript, TranscriptPhraseDownvote ) class Command(BaseCommand): help = 'Creates random votes for all phrases in a random transcript' def handle(self, *args, **options): users = User.objects.all() transcript = Transcript.objects.random() for phrase in transcript.phrases.all(): for user in users: profile = Profile.objects.get(user=user) profile.considered_phrases.add(phrase) if random.choice([True, False]): TranscriptPhraseDownvote.objects.create( transcript_phrase=phrase, user=user )
Use process.nextTick instead of setTimeout if available
// Wraps any value with promise. Not very useful on its own, used internally // by deferred.js 'use strict'; var curry = require('es5-ext/lib/Function/curry').call , isFunction = require('es5-ext/lib/Function/is-function') , noop = require('es5-ext/lib/Function/noop') , sequence = require('es5-ext/lib/Function/sequence').call , nextTick = require('clock/lib/next-tick') , isPromise = require('./is-promise') , deferred, then, throwError, end; then = function (value, ignore, callback) { var d = deferred(); nextTick(callback ? sequence(curry(callback, value), d.resolve) : d.resolve.bind(d, value)); return d.promise; }; throwError = function () { throw this; }; end = function (handler) { nextTick( isFunction(handler) ? curry(handler, this) : throwError.bind(this)); }; module.exports = function (value) { var r; if (isPromise(value)) { return value; } else if (value instanceof Error) { r = curry(then, value); r.end = end.bind(value); } else { r = curry(then, value, null); r.end = noop; } return r.then = r; }; deferred = require('./deferred');
// Wraps any value with promise. Not very useful on its own, used internally // by deferred.js 'use strict'; var curry = require('es5-ext/lib/Function/curry').call , isFunction = require('es5-ext/lib/Function/is-function') , noop = require('es5-ext/lib/Function/noop') , sequence = require('es5-ext/lib/Function/sequence').call , isPromise = require('./is-promise') , deferred, then, throwError, end; then = function (value, ignore, callback) { var d = deferred(); setTimeout(callback ? sequence(curry(callback, value), d.resolve) : d.resolve.bind(d, value), 0); return d.promise; }; throwError = function () { throw this; }; end = function (handler) { setTimeout( isFunction(handler) ? curry(handler, this) : throwError.bind(this), 0); }; module.exports = function (value) { var r; if (isPromise(value)) { return value; } else if (value instanceof Error) { r = curry(then, value); r.end = end.bind(value); } else { r = curry(then, value, null); r.end = noop; } return r.then = r; }; deferred = require('./deferred');
Change argument name to configurationName
package com.github.blindpirate.gogradle.core.dependency.produce.strategy; import com.github.blindpirate.gogradle.core.dependency.GolangDependencySet; import com.github.blindpirate.gogradle.core.dependency.ResolvedDependency; import com.github.blindpirate.gogradle.core.dependency.produce.DependencyVisitor; import java.io.File; /** * Direct how to generate dependencies of an existing golang package module. */ // Default: if external exist, use it; else if vendor exist, use it; else scan source public interface DependencyProduceStrategy { DependencyProduceStrategy DEFAULT_STRATEGY = new DefaultDependencyProduceStrategy(); GolangDependencySet produce(ResolvedDependency dependency, File rootDir, DependencyVisitor visitor, String configurationName); }
package com.github.blindpirate.gogradle.core.dependency.produce.strategy; import com.github.blindpirate.gogradle.core.dependency.GolangDependencySet; import com.github.blindpirate.gogradle.core.dependency.ResolvedDependency; import com.github.blindpirate.gogradle.core.dependency.produce.DependencyVisitor; import java.io.File; /** * Direct how to generate dependencies of an existing golang package module. */ // Default: if external exist, use it; else if vendor exist, use it; else scan source public interface DependencyProduceStrategy { DependencyProduceStrategy DEFAULT_STRATEGY = new DefaultDependencyProduceStrategy(); GolangDependencySet produce(ResolvedDependency dependency, File rootDir, DependencyVisitor visitor, String configuration); }
Enable appstats by default in dev too.
# -*- coding: utf-8 -*- """WSGI app setup.""" import os import sys if 'lib' not in sys.path: # Add lib as primary libraries directory, with fallback to lib/dist # and optionally to lib/dist.zip, loaded using zipimport. sys.path[0:0] = ['lib', 'lib/dist', 'lib/dist.zip'] from tipfy import Tipfy from config import config from urls import rules def enable_appstats(app): """Enables appstats middleware.""" from google.appengine.ext.appstats.recording import \ appstats_wsgi_middleware app.wsgi_app = appstats_wsgi_middleware(app.wsgi_app) def enable_jinja2_debugging(): """Enables blacklisted modules that help Jinja2 debugging.""" if not debug: return # This enables better debugging info for errors in Jinja2 templates. from google.appengine.tools.dev_appserver import HardenedModulesHook HardenedModulesHook._WHITE_LIST_C_MODULES += ['_ctypes', 'gestalt'] # Is this the development server? debug = os.environ.get('SERVER_SOFTWARE', '').startswith('Dev') # Instantiate the application. app = Tipfy(rules=rules, config=config, debug=debug) enable_appstats(app) enable_jinja2_debugging() def main(): # Run the app. app.run() if __name__ == '__main__': main()
# -*- coding: utf-8 -*- """WSGI app setup.""" import os import sys if 'lib' not in sys.path: # Add lib as primary libraries directory, with fallback to lib/dist # and optionally to lib/dist.zip, loaded using zipimport. sys.path[0:0] = ['lib', 'lib/dist', 'lib/dist.zip'] from tipfy import Tipfy from config import config from urls import rules def enable_appstats(app): """Enables appstats middleware.""" if debug: return from google.appengine.ext.appstats.recording import appstats_wsgi_middleware app.wsgi_app = appstats_wsgi_middleware(app.wsgi_app) def enable_jinja2_debugging(): """Enables blacklisted modules that help Jinja2 debugging.""" if not debug: return # This enables better debugging info for errors in Jinja2 templates. from google.appengine.tools.dev_appserver import HardenedModulesHook HardenedModulesHook._WHITE_LIST_C_MODULES += ['_ctypes', 'gestalt'] # Is this the development server? debug = os.environ.get('SERVER_SOFTWARE', '').startswith('Dev') # Instantiate the application. app = Tipfy(rules=rules, config=config, debug=debug) enable_appstats(app) enable_jinja2_debugging() def main(): # Run the app. app.run() if __name__ == '__main__': main()
Add styles to watched directories for watch:build/watch
/* * Copyright 2014 Workiva, LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ module.exports = function(gulp, options, subtasks) { var taskname = 'watch:build'; gulp.desc(taskname, 'Watch source files for changes and rebuild'); var fn = function(done) { gulp.watch([ options.path.src + options.glob.all, options.path.styles + options.glob.all ], ['build']); }; gulp.task(taskname, ['build'], fn); };
/* * Copyright 2014 Workiva, LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ module.exports = function(gulp, options, subtasks) { var taskname = 'watch:build'; gulp.desc(taskname, 'Watch source files for changes and rebuild'); var fn = function(done) { gulp.watch(options.glob.all, { cwd: options.path.src }, ['build']); }; gulp.task(taskname, ['build'], fn); };
Remove unnecessary uglify `passes` property
import commonjs from 'rollup-plugin-commonjs'; import babel from 'rollup-plugin-babel'; import uglify from 'rollup-plugin-uglify'; import replace from 'rollup-plugin-replace'; import resolve from 'rollup-plugin-node-resolve'; const env = process.env.NODE_ENV; const config = { output: { name: 'react-uncontrolled-form', format: 'umd', globals: {react: 'React'} }, external: ['react'], plugins: [ resolve({jsnext: true}), commonjs({include: 'node_modules/**'}), babel({exclude: 'node_modules/**'}), replace({'process.env.NODE_ENV': JSON.stringify(env)}) ] }; if (env === 'production') { config.plugins.push( uglify({ compress: { pure_getters: true, unsafe: true, unsafe_proto: true } }) ); } export default config;
import commonjs from 'rollup-plugin-commonjs'; import babel from 'rollup-plugin-babel'; import uglify from 'rollup-plugin-uglify'; import replace from 'rollup-plugin-replace'; import resolve from 'rollup-plugin-node-resolve'; const env = process.env.NODE_ENV; const config = { output: { name: 'react-uncontrolled-form', format: 'umd', globals: {react: 'React'} }, external: ['react'], plugins: [ resolve({jsnext: true}), commonjs({include: 'node_modules/**'}), babel({exclude: 'node_modules/**'}), replace({'process.env.NODE_ENV': JSON.stringify(env)}) ] }; if (env === 'production') { config.plugins.push( uglify({ compress: { pure_getters: true, unsafe: true, unsafe_proto: true, passes: 2, } }) ); } export default config;
Add unknown POST /fp-setup route
'use strict'; var debug = require('debug')('airserver'); var router = require('router')(); var photo = require('./photo'); var serverInfo = require('./server-info'); module.exports = function (server) { server.on('airplay', router); // generic airplay routes router.post('/reverse', notImplemented); // photo router.put('/photo', photo(server)); // slideshow router.get('/slideshow-features', notImplemented); router.put('/slideshows/{id}', notImplemented); // video router.get('/server-info', serverInfo(server)); // isn't this also used for photos? router.post('/play', notImplemented); router.post('/scrub', notImplemented); router.post('/rate', notImplemented); router.post('/stop', notImplemented); router.get('/scrub', notImplemented); router.get('/playback-info', notImplemented); router.put('/setProperty', notImplemented); router.post('/getProperty', notImplemented); // screen mirroring router.get('/stream.xml', notImplemented); router.post('/stream', notImplemented); // unknown router.post('/fp-setup', notImplemented); }; var notImplemented = function (req, res) { debug('%s %s is not supported!', req.method, req.url); res.end(); };
'use strict'; var debug = require('debug')('airserver'); var router = require('router')(); var photo = require('./photo'); var serverInfo = require('./server-info'); module.exports = function (server) { server.on('airplay', router); // generic airplay routes router.post('/reverse', notImplemented); // photo router.put('/photo', photo(server)); // slideshow router.get('/slideshow-features', notImplemented); router.put('/slideshows/{id}', notImplemented); // video router.get('/server-info', serverInfo(server)); // isn't this also used for photos? router.post('/play', notImplemented); router.post('/scrub', notImplemented); router.post('/rate', notImplemented); router.post('/stop', notImplemented); router.get('/scrub', notImplemented); router.get('/playback-info', notImplemented); router.put('/setProperty', notImplemented); router.post('/getProperty', notImplemented); // screen mirroring router.get('/stream.xml', notImplemented); router.post('/stream', notImplemented); }; var notImplemented = function (req, res) { debug('%s %s is not supported!', req.method, req.url); res.end(); };
Fix ID generation for js package documentation
# # Jasy - Web Tooling Framework # Copyright 2010-2012 Zynga Inc. # Copyright 2013-2014 Sebastian Werner # import os import jasy.js.api.Data as Data import jasy.core.Text as Text import jasy.item.Abstract as Abstract from jasy import UserError class DocItem(Abstract.AbstractItem): kind = "doc" def generateId(self, relpath, package): if package: fileId = "%s/" % package else: fileId = "" return (fileId + os.path.dirname(relpath)).replace("/", ".") def getApi(self): field = "api[%s]" % self.id apidata = self.project.getCache().read(field, self.getModificationTime()) if not Text.supportsMarkdown: raise UserError("Missing Markdown feature to convert package docs into HTML.") if apidata is None: apidata = Data.ApiData(self.id) apidata.main["type"] = "Package" apidata.main["doc"] = Text.highlightCodeBlocks(Text.markdownToHtml(self.getText())) self.project.getCache().store(field, apidata, self.getModificationTime()) return apidata
# # Jasy - Web Tooling Framework # Copyright 2010-2012 Zynga Inc. # Copyright 2013-2014 Sebastian Werner # import os import jasy.js.api.Data as Data import jasy.core.Text as Text import jasy.item.Abstract as Abstract from jasy import UserError class DocItem(Abstract.AbstractItem): kind = "doc" def generateId(self, relpath, package): if package: fileId = "%s/" % package else: fileId = "" return (fileId + os.path.splitext(relPath)[0]).replace("/", ".") def getApi(self): field = "api[%s]" % self.id apidata = self.project.getCache().read(field, self.getModificationTime()) if not Text.supportsMarkdown: raise UserError("Missing Markdown feature to convert package docs into HTML.") if apidata is None: apidata = Data.ApiData(self.id) apidata.main["type"] = "Package" apidata.main["doc"] = Text.highlightCodeBlocks(Text.markdownToHtml(self.getText())) self.project.getCache().store(field, apidata, self.getModificationTime()) return apidata
Fix StutterShot not being generated.
package edu.stuy.starlorn.upgrades; public class StutterShotUpgrade extends GunUpgrade { protected boolean _fast_shot; public StutterShotUpgrade() { super(); _name = "Stutter Shot"; _description = "P-Pew P-Pew P-Pew!"; _fast_shot = false; } @Override public double getShotSpeed(double shotspeed) { return shotspeed; } @Override public double getCooldown(double cooldown) { _fast_shot = !_fast_shot; if (_fast_shot) { return cooldown * 3 / 2; } else { return cooldown / 2; } } @Override public String getSpriteName() { return "upgrade/stuttershot"; } @Override public Upgrade clone() { return new StutterShotUpgrade(); } }
package edu.stuy.starlorn.upgrades; public class StutterShotUpgrade extends GunUpgrade { protected boolean _fast_shot; public StutterShotUpgrade() { super(); _name = "Stutter Shot"; _description = "P-Pew P-Pew P-Pew!"; _fast_shot = false; } @Override public double getShotSpeed(double shotspeed) { return shotspeed; } @Override public double getCooldown(double cooldown) { _fast_shot = !_fast_shot; if (_fast_shot) { return cooldown * 3 / 2; } else { return cooldown / 2; } } @Override public String getSpriteName() { return "upgrade/stuttershot"; } @Override public Upgrade clone() { return new SpeedShotUpgrade(); } }
Fix missing exports for SpecError This needs to be followed-up with test coverage.
// Copyright (c) 2015 Uber Technologies, Inc. // // 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, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. 'use strict'; module.exports = SpecError; function SpecError(message) { var error = new Error(message); error.context = []; error.annotate = annotate; return error; } function annotate(context) { this.context.push(context); }
// Copyright (c) 2015 Uber Technologies, Inc. // // 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, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. 'use strict'; function SpecError(message) { var error = new Error(message); error.context = []; error.annotate = annotate; return error; } function annotate(context) { this.context.push(context); }
Add license, update minor version
#!/usr/bin/env python from setuptools import setup, find_packages try: with open("requirements.txt", "r") as f: install_requires = [x.strip() for x in f.readlines()] except IOError: install_requires = [] setup(name='bcbio_monitor', # For versioning: http://semver.org/ version='1.0.5', description="bcbio-monitor is an extension of bcbio-nextgen to visualize its progress", author='Guillermo Carrasco', author_email='guille.ch.88@gmail.com', url='https://github.com/guillermo-carrasco/bcbio-nextgen-monitor', packages=find_packages(), include_package_data=True, keywords=['bcbio', 'bcbio-nextgen', 'bioinformatics', 'genomics'], zip_safe=True, license='MIT', entry_points={ 'console_scripts': [ 'bcbio_monitor = bcbio_monitor.cli:cli', ], }, install_requires=install_requires )
#!/usr/bin/env python from setuptools import setup, find_packages try: with open("requirements.txt", "r") as f: install_requires = [x.strip() for x in f.readlines()] except IOError: install_requires = [] setup(name='bcbio_monitor', # For versioning: http://semver.org/ version='1.0.4', description="bcbio-monitor is an extension of bcbio-nextgen to visualize its progress", author='Guillermo Carrasco', author_email='guille.ch.88@gmail.com', url='https://github.com/guillermo-carrasco/bcbio-nextgen-monitor', packages=find_packages(), include_package_data=True, keywords=['bcbio', 'bcbio-nextgen', 'bioinformatics', 'genomics'], zip_safe=True, entry_points={ 'console_scripts': [ 'bcbio_monitor = bcbio_monitor.cli:cli', ], }, install_requires=install_requires )
Enable pointer events and gestures for native ShadowDOM
(function(scope) { scope.WebkitShadowDOM = { ShadowRoot: function(inElement) { var root = inElement.webkitCreateShadowRoot(); // TODO(sjmiles): .shadow, .host, .olderSubtree are supposed to be native, // at least for public ShadowDOMs root.olderSubtree = inElement.shadow; inElement.shadow = root; root.host = inElement; // Set up gesture events on shadow if (window.PointerGestures) { PointerGestures.register(root); // Set up pointerevents on shadow if (window.PointerEventsPolyfill) { PointerEventsPolyfill.setTouchAction(root, inElement.getAttribute('touch-action')); } } // TODO(sjmiles): enabled by default so that @host polyfills will // work under composition. Can remove when @host is implemented // natively. root.applyAuthorStyles = true; return root; }, distribute: function() {}, localQuery: function(inElement, inSlctr) { return inElement.querySelector(inSlctr); }, localQueryAll: function(inElement, inSlctr) { return inElement.querySelectorAll(inSlctr); }, deref: function(inNode) { return inNode; }, localNodes: function(inNode) { return inNode.childNodes; }, localParent: function(inNode) { return inNode.parentNode; }, forEach: Array.prototype.forEach.call.bind(Array.prototype.forEach) }; })(window.__exported_components_polyfill_scope__);
(function(scope) { scope.WebkitShadowDOM = { ShadowRoot: function(inElement) { var root = inElement.webkitCreateShadowRoot(); // TODO(sjmiles): .shadow, .host, .olderSubtree are supposed to be native, // at least for public ShadowDOMs root.olderSubtree = inElement.shadow; inElement.shadow = root; root.host = inElement; // TODO(sjmiles): enabled by default so that @host polyfills will // work under composition. Can remove when @host is implemented // natively. root.applyAuthorStyles = true; return root; }, distribute: function() {}, localQuery: function(inElement, inSlctr) { return inElement.querySelector(inSlctr); }, localQueryAll: function(inElement, inSlctr) { return inElement.querySelectorAll(inSlctr); }, deref: function(inNode) { return inNode; }, localNodes: function(inNode) { return inNode.childNodes; }, localParent: function(inNode) { return inNode.parentNode; }, forEach: Array.prototype.forEach.call.bind(Array.prototype.forEach) }; })(window.__exported_components_polyfill_scope__);
Fix return statement for `invite`
import json from slackipycore import invite, get_team_info from slackipycore import (AlreadyInTeam, InvalidInviteeEmail, InvalidAuthToken, AlreadyInvited, APIRequestError) from flask import current_app def invite_user(email): api_token = current_app.config['SLACK_API_TOKEN'] team_id = current_app.config['SLACK_TEAM_ID'] try: if invite(team_id=team_id, api_token=api_token, invitee_email=email): return {'status': 'success'} except (AlreadyInTeam, InvalidInviteeEmail, InvalidAuthToken, AlreadyInvited, APIRequestError) as e: return _response_message(message=str(e)) def get_team_name(): api_token = current_app.config['SLACK_API_TOKEN'] team_id = current_app.config['SLACK_TEAM_ID'] team_info = get_team_info(team_id=team_id, api_token=api_token) return team_info['name'] def _response_message(message): return {'status': 'fail', 'error': message}
import json from slackipycore import invite, get_team_info from slackipycore import (AlreadyInTeam, InvalidInviteeEmail, InvalidAuthToken, AlreadyInvited, APIRequestError) from flask import current_app def invite_user(email): api_token = current_app.config['SLACK_API_TOKEN'] team_id = current_app.config['SLACK_TEAM_ID'] try: if invite(team_id=team_id, api_token=api_token, invitee_email=email): return json.dumps({'status': 'success'}) except (AlreadyInTeam, InvalidInviteeEmail, InvalidAuthToken, AlreadyInvited, APIRequestError) as e: return _response_message(message=str(e)) def get_team_name(): api_token = current_app.config['SLACK_API_TOKEN'] team_id = current_app.config['SLACK_TEAM_ID'] team_info = get_team_info(team_id=team_id, api_token=api_token) return team_info['name'] def _response_message(message): return {'status': 'fail', 'error': message}
Tweak debugging messages, add comments
import logging logger = logging.getLogger('tohu') class CustomGeneratorMetaV2(type): def __new__(metacls, cg_name, bases, clsdict): logger.debug('[DDD]') logger.debug('CustomGeneratorMetaV2.__new__') logger.debug(f' - metacls={metacls}') logger.debug(f' - cg_name={cg_name}') logger.debug(f' - bases={bases}') logger.debug(f' - clsdict={clsdict}') # # Create new custom generator object # new_obj = super(CustomGeneratorMetaV2, metacls).__new__(metacls, cg_name, bases, clsdict) logger.debug(f' - new_obj={new_obj}') # # Create and assign automatically generated reset() method # def reset(self, seed=None): logger.debug(f'[EEE] Inside automatically generated reset() method for {self} (seed={seed})') logger.debug(f' TODO: reset internal seed generator and call reset() on each child generator') new_obj.reset = reset return new_obj
import logging logger = logging.getLogger('tohu') class CustomGeneratorMetaV2(type): def __new__(metacls, cg_name, bases, clsdict): logger.debug('[DDD] CustomGeneratorMetaV2.__new__') logger.debug(f' - metacls={metacls}') logger.debug(f' - cg_name={cg_name}') logger.debug(f' - bases={bases}') logger.debug(f' - clsdict={clsdict}') new_obj = super(CustomGeneratorMetaV2, metacls).__new__(metacls, cg_name, bases, clsdict) logger.debug(f' -- new_obj={new_obj}') def reset(self, seed=None): logger.debug(f'[EEE] Inside automatically generated reset() method for {self} (seed={seed})') logger.debug(f' TODO: reset internal seed generator and call reset() on each child generator') new_obj.reset = reset return new_obj
Remove blank line at end of file.
class Formatter(object): name = None description = None def __init__(self, stream, config): self.stream = stream self.config = config def uri(self, uri): pass def feature(self, feature): pass def background(self, background): pass def scenario(self, scenario): pass def scenario_outline(self, outline): pass def examples(self, examples): pass def step(self, step): pass def match(self, match): pass def result(self, result): pass def eof(self): pass def close(self): pass
class Formatter(object): name = None description = None def __init__(self, stream, config): self.stream = stream self.config = config def uri(self, uri): pass def feature(self, feature): pass def background(self, background): pass def scenario(self, scenario): pass def scenario_outline(self, outline): pass def examples(self, examples): pass def step(self, step): pass def match(self, match): pass def result(self, result): pass def eof(self): pass def close(self): pass
fix: Test fix. rebase_addr to mapped_base
import angr import os import nose test_location = str(os.path.join(os.path.dirname(os.path.realpath(__file__)), '../../binaries/tests')) binpath = os.path.join(test_location, "x86_64/test_gdb_plugin") def check_addrs(p): libc = p.loader.shared_objects['libc.so.6'] ld = p.loader.shared_objects['ld-linux-x86-64.so.2'] nose.tools.assert_equal(libc.mapped_base, 0x7ffff7a17000) nose.tools.assert_equal(ld.mapped_base, 0x7ffff7ddc000) def test_cle_gdb(): """ Test for `info proc mappings` """ mappath = os.path.join(test_location, "../test_data/test_gdb_plugin/procmap") p = angr.Project(binpath, load_options={"gdb_map":mappath}) check_addrs(p) def test_sharedlibs(): """ Test for info sharedlibrary """ mappath = os.path.join(test_location, "../test_data/test_gdb_plugin/info_sharedlibs") p = angr.Project(binpath, load_options={"gdb_map":mappath, "gdb_fix":True}) check_addrs(p) if __name__ == "__main__": test_cle_gdb() test_sharedlibs()
import angr import os import nose test_location = str(os.path.join(os.path.dirname(os.path.realpath(__file__)), '../../binaries/tests')) binpath = os.path.join(test_location, "x86_64/test_gdb_plugin") def check_addrs(p): libc = p.loader.shared_objects['libc.so.6'] ld = p.loader.shared_objects['ld-linux-x86-64.so.2'] nose.tools.assert_equal(libc.rebase_addr, 0x7ffff7a17000) nose.tools.assert_equal(ld.rebase_addr, 0x7ffff7ddc000) def test_cle_gdb(): """ Test for `info proc mappings` """ mappath = os.path.join(test_location, "../test_data/test_gdb_plugin/procmap") p = angr.Project(binpath, load_options={"gdb_map":mappath}) check_addrs(p) def test_sharedlibs(): """ Test for info sharedlibrary """ mappath = os.path.join(test_location, "../test_data/test_gdb_plugin/info_sharedlibs") p = angr.Project(binpath, load_options={"gdb_map":mappath, "gdb_fix":True}) check_addrs(p) if __name__ == "__main__": test_cle_gdb() test_sharedlibs()
Load a copy of a note into the form, rather than the actual object from the array.
angular.module('notely') .service('NotesService', NotesService); // NotesService // Handle CRUD operations against the server. NotesService.$inject = ['$http']; function NotesService($http) { var self = this; self.notes = []; // Get all notes from server self.fetch = function() { return $http.get('http://localhost:3000/notes') .then( // Success callback function(response) { self.notes = response.data; }, // Failure callback function(response) { // TODO: Handle failure } ); }; self.get = function() { return self.notes; }; self.findById = function(noteId) { // Look through `self.notes` for a note with a matching _id. for (var i = 0; i < self.notes.length; i++) { if (self.notes[i]._id === noteId) { return angular.copy(self.notes[i]); } } return {}; }; self.save = function(note) { $http.post('http://localhost:3000/notes', { note: note }).then(function(response) { self.notes.unshift(response.data.note); }); } } //
angular.module('notely') .service('NotesService', NotesService); // NotesService // Handle CRUD operations against the server. NotesService.$inject = ['$http']; function NotesService($http) { var self = this; self.notes = []; // Get all notes from server self.fetch = function() { return $http.get('http://localhost:3000/notes') .then( // Success callback function(response) { self.notes = response.data; }, // Failure callback function(response) { // TODO: Handle failure } ); }; self.get = function() { return self.notes; }; self.findById = function(noteId) { // Look through `self.notes` for a note with a matching _id. for (var i = 0; i < self.notes.length; i++) { if (self.notes[i]._id === noteId) { return self.notes[i]; } } return {}; }; self.save = function(note) { $http.post('http://localhost:3000/notes', { note: note }).then(function(response) { self.notes.unshift(response.data.note); }); } } //
Set "Accept: 'application/json'" header on Slack API calls
var _ = require('underscore'); module.exports = function(robot){ robot.slack = { baseApiUrl: 'https://slack.com/api/', createApiUrl: function (suffix, queryString){ if (!!queryString){ if (_.isObject(queryString)) queryString = robot.util.toQueryString(queryString); return robot.slack.baseApiUrl + suffix + queryString; } return robot.slack.baseApiUrl + suffix; } }; robot.respond(/channel list/i, function(res){ if (robot.auth.isAdmin(res.message.user)){ var data = { token: process.env.HUBOT_SLACK_TOKEN, exclude_archived: 1 }; robot.http(robot.slack.createApiUrl('channels.list', data)) .header('Accept', 'application/json') .get()(function(err, response, body){ if (!!err){ res.reply('ERROR: ' + err); robot.errors.log(err); return; } var bodyJson = JSON.parse(body); res.send(robot.util.prettifyJson(bodyJson)); }); } }); }
var _ = require('underscore'); module.exports = function(robot){ robot.slack = { baseApiUrl: 'https://slack.com/api/', createApiUrl: function (suffix, queryString){ if (!!queryString){ if (_.isObject(queryString)) queryString = robot.util.toQueryString(queryString); return robot.slack.baseApiUrl + suffix + queryString; } return robot.slack.baseApiUrl + suffix; } }; robot.respond(/channel list/i, function(res){ if (robot.auth.isAdmin(res.message.user)){ var data = { token: process.env.HUBOT_SLACK_TOKEN, exclude_archived: 1 }; robot.http(robot.slack.createApiUrl('channels.list', data)) .get()(function(err, response, body){ if (!!err){ res.reply('ERROR: ' + err); robot.errors.log(err); return; } var bodyJson = JSON.parse(body); res.send(robot.util.prettifyJson(bodyJson)); }); } }); }
Fix emoji byte length issue
// These should be easily identifiable and both visually and conceptually unique // Don't include symbols that could be misconstrued to have some actual meaning // (like a warning sign) const emojis = [ '🦊', '🐸', '🦉', '🦄', '🐙', '🐳', '🌵', '🍀', '🍁', '🍄', '🌍', '⭐️', '🔥', '🌈', '🍎', '🥯', '🌽', '🥞', '🥨', '🍕', '🌮', '🍦', '🎂', '🍿', '🏈', '🛼', '🏆', '🎧', '🎺', '🎲', '🚚', '✈️', '🚀', '⛵️', '⛺️', '📻', '💰', '💎', '🧲', '🔭', '🪣', '🧸', ]; module.exports = { emoji(executionId) { // Create a simple hash of the execution ID const hash = [...executionId].reduce( (prev, curr) => prev + curr.charCodeAt(0), 0, ); // Return an emoji based on the hash. This is hopefully significantly // random that deploys near to each other in time don't get the same // symbol return emojis[hash % emojis.length]; }, };
// These should be easily identifiable and both visually and conceptually unique // Don't include symbols that could be misconstrued to have some actual meaning // (like a warning sign) const emojis = '🦊🐸🦉🦄🐙🐳🌵🍀🍁🍄🌍⭐️🔥🌈🍎🥯🌽🥞🥨🍕🌮🍦🎂🍿🏈🛼🏆🎧🎺🎲🚚✈️🚀⛵️⛺️📻💰💎🧲🔭🪣🧸'; module.exports = { emoji(executionId) { // Create a simple hash of the execution ID const hash = [...executionId].reduce( (prev, curr) => prev + curr.charCodeAt(0), 0, ); // Return an emoji based on the hash. This is hopefully significantly // random that deploys near to each other in time don't get the same // symbol return [...emojis][hash % [...emojis].length]; }, };
Set up server/client once for the netcode test
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Run from Cryptchat # python3 -m unittest discover import unittest from ..network.networkhandler import NetworkHandler from ..crypto.aes import AESCipher from ..crypto.diffiehellman import DiffieHellman class testNetworkHandler(unittest.TestCase): @classmethod def setUpClass(self): alice = DiffieHellman() bob = DiffieHellman() a = alice.gensessionkey(bob.publickey) b = bob.gensessionkey(alice.publickey) aes1 = AESCipher(a) aes2 = AESCipher(b) self.server = NetworkHandler("localhost", 8090, True, alice, aes1) self.client = NetworkHandler("localhost", 8090, False, bob, aes2) def test_sendmessage(self): self.server.start() self.client.start() m = "This is secret please do not read. And some chars to get unicode-testing out of the way åäö" self.client.send(m) m2 = self.server.getinmessage() self.assertEqual(m, m2) def main(): unittest.main() if __name__ == '__main__': main()
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Run from Cryptchat # python3 -m unittest discover import unittest from ..network.networkhandler import NetworkHandler from ..crypto.aes import AESCipher from ..crypto.diffiehellman import DiffieHellman class testNetworkHandler(unittest.TestCase): def setUp(self): alice = DiffieHellman() bob = DiffieHellman() a = alice.gensessionkey(bob.publickey) b = bob.gensessionkey(alice.publickey) aes1 = AESCipher(a) aes2 = AESCipher(b) self.server = NetworkHandler("localhost", 8090, True, alice, aes1) self.client = NetworkHandler("localhost", 8090, False, bob, aes2) def test_sendmessage(self): self.server.start() self.client.start() m = "This is secret please do not read. And some chars to get unicode-testing out of the way åäö" self.client.send(m) m2 = self.server.getinmessage() self.assertEqual(m, m2) def tearDown(self): self.server.stop() self.client.stop() def main(): unittest.main() if __name__ == '__main__': main()
Change project migration table name
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateIndividualProjectTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('individual_project', function (Blueprint $table) { $table->engine = 'InnoDB'; $table->increments('id'); $table->integer('project_id'); $table->string('reminders'); $table->softDeletes(); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('individual_project'); } }
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateProjectIndividualTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('project_individual', function (Blueprint $table) { $table->engine = 'InnoDB'; $table->increments('id'); $table->integer('project_id'); $table->string('reminders'); $table->softDeletes(); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('project_individual'); } }
Remove import from testing packages
''' Created on Sep 24, 2016 @author: rtorres ''' from flaskiwsapp.database import SurrogatePK, Model, db, reference_col, relationship, Column from sqlalchemy.dialects.postgresql.base import ENUM AREAS = ('Policies', 'Billing', 'Claims', 'Reports') class Target(SurrogatePK, Model): """A user of the app.""" __tablename__ = 'targets' title = Column(db.String(80), nullable=False) description = Column(db.Text(), nullable=False) client_id = reference_col('clients', nullable=False) client = relationship('Client', backref='targets') client_priority = Column(db.SmallInteger(), nullable=False) product_area = Column(ENUM(*AREAS, name='areas', create_type=False), nullable=False) target_date = Column(db.DateTime(), nullable=False) ticket_url = Column(db.String(256), nullable=False) def __init__(self, title="", password=None, **kwargs): """Create instance.""" db.Model.__init__(self, title=title.strip(), **kwargs) def __str__(self): """String representation of the user. Shows the target title.""" return self.title def get_id(self): return self.id
''' Created on Sep 24, 2016 @author: rtorres ''' from flaskiwsapp.database import SurrogatePK, Model, db, reference_col, relationship, Column from sqlalchemy.dialects.postgresql.base import ENUM from sqlalchemy_utils.types.url import URLType from flask_validator.constraints.internet import ValidateURL AREAS = ('Policies', 'Billing', 'Claims', 'Reports') class Target(SurrogatePK, Model): """A user of the app.""" __tablename__ = 'targets' title = Column(db.String(80), nullable=False) description = Column(db.Text(), nullable=False) client_id = reference_col('clients', nullable=False) client = relationship('Client', backref='targets') client_priority = Column(db.SmallInteger(), nullable=False) product_area = Column(ENUM(*AREAS, name='areas', create_type=False), nullable=False) target_date = Column(db.DateTime(), nullable=False) ticket_url = Column(db.String(256), nullable=False) def __init__(self, title="", password=None, **kwargs): """Create instance.""" db.Model.__init__(self, title=title.strip(), **kwargs) def __str__(self): """String representation of the user. Shows the target title.""" return self.title def get_id(self): return self.id
Add getTemporaryFile method to base test class
<?php declare(strict_types=1); namespace PhpSchool\PhpWorkshopTest; use PhpSchool\PhpWorkshop\Utils\Path; use PHPUnit\Framework\TestCase; use Symfony\Component\Filesystem\Filesystem; abstract class BaseTest extends TestCase { private $tempDirectory; public function getTemporaryDirectory(): string { if (!$this->tempDirectory) { $tempDirectory = sprintf('%s/%s', realpath(sys_get_temp_dir()), $this->getName()); mkdir($tempDirectory, 0777, true); $this->tempDirectory = realpath($tempDirectory); } return $this->tempDirectory; } public function getTemporaryFile(string $filename): string { $file = Path::join($this->getTemporaryDirectory(), $filename); if (file_exists($file)) { return $file; } @mkdir(dirname($file), 0777, true); touch($file); return $file; } public function tearDown(): void { if ($this->tempDirectory) { (new Filesystem())->remove($this->tempDirectory); } } }
<?php declare(strict_types=1); namespace PhpSchool\PhpWorkshopTest; use PHPUnit\Framework\TestCase; use Symfony\Component\Filesystem\Filesystem; abstract class BaseTest extends TestCase { private $tempDirectory; public function getTemporaryDirectory(): string { if (!$this->tempDirectory) { $tempDirectory = sprintf('%s/%s', realpath(sys_get_temp_dir()), $this->getName()); mkdir($tempDirectory, 0777, true); $this->tempDirectory = realpath($tempDirectory); } return $this->tempDirectory; } public function tearDown(): void { if ($this->tempDirectory) { (new Filesystem())->remove($this->tempDirectory); } } }
Fix to allow for null buffers to be passed in.
(function () { "use strict"; function concat(bufs) { if (!Array.isArray(bufs)) { bufs = Array.prototype.slice.call(arguments); } var bufsToConcat = [], length = 0; bufsToConcat.forEach(function (buf) { if (buf) { if (!Buffer.isBuffer(buf)) { buf = new Buffer(buf); } length += buf.length; bufsToConcat.push(buf); } } var concatBuf = new Buffer(length), index = 0; bufsToConcat.forEach(function (buf) { buf.copy(concatBuf, index, 0, buf.length); index += buf.length; }); return concatBuf; } Buffer.concat = concat; }());
(function () { "use strict"; function concat(bufs) { var buffer, length = 0, index = 0; if (!Array.isArray(bufs)) { bufs = Array.prototype.slice.call(arguments); } for (var i=0, l=bufs.length; i<l; i++) { buffer = bufs[i]; if (!Buffer.isBuffer(buffer)) { buffer = bufs[i] = new Buffer(buffer); } length += buffer.length; } buffer = new Buffer(length); bufs.forEach(function (buf, i) { buf = bufs[i]; buf.copy(buffer, index, 0, buf.length); index += buf.length; delete bufs[i]; }); return buffer; } Buffer.concat = concat; }());
ENYO-1648: Increase moveTolerance value from 16 to 1500 on configureHoldPulse Issue: - The onHoldPulse event is canceled too early when user move mouse abound. Fix: - We need higher moveTolerance value to make it stay pulse more on TV. - Increase moveTolerance value from 16 to 1500 on configureHoldPulse by testing. DCO-1.1-Signed-Off-By: Kunmyon Choi kunmyon.choi@lge.com
'use strict'; var platform = require('enyo/platform'), dispatcher = require('enyo/dispatcher'), gesture = require('enyo/gesture'); exports = module.exports = require('./lib/options'); exports.version = '2.6.0-pre'; // Override the default holdpulse config to account for greater delays between keydown and keyup // events in Moonstone with certain input devices. gesture.drag.configureHoldPulse({ frequency: 200, events: [{name: 'hold', time: 400}], resume: false, moveTolerance: 1500, endHold: 'onMove' }); /** * Registers key mappings for webOS-specific device keys related to media control. * * @private */ if (platform.webos >= 4) { // Table of default keyCode mappings for webOS device dispatcher.registerKeyMap({ 415 : 'play', 413 : 'stop', 19 : 'pause', 412 : 'rewind', 417 : 'fastforward', 461 : 'back' }); } // ensure that these are registered require('./lib/resolution'); require('./lib/fonts');
'use strict'; var platform = require('enyo/platform'), dispatcher = require('enyo/dispatcher'), gesture = require('enyo/gesture'); exports = module.exports = require('./lib/options'); exports.version = '2.6.0-pre'; // Override the default holdpulse config to account for greater delays between keydown and keyup // events in Moonstone with certain input devices. gesture.drag.configureHoldPulse({ frequency: 200, events: [{name: 'hold', time: 400}], resume: false, moveTolerance: 16, endHold: 'onMove' }); /** * Registers key mappings for webOS-specific device keys related to media control. * * @private */ if (platform.webos >= 4) { // Table of default keyCode mappings for webOS device dispatcher.registerKeyMap({ 415 : 'play', 413 : 'stop', 19 : 'pause', 412 : 'rewind', 417 : 'fastforward', 461 : 'back' }); } // ensure that these are registered require('./lib/resolution'); require('./lib/fonts');
Handle null overrides and same module overrides
const loaderUtils = require('loader-utils'); const path = require('path'); const deepMerge = require('./lib/deep-merge'); function _removeModuleSyntax (moduleSource) { return moduleSource .replace(/^ ?module.exports ?= ?/i, '') .replace(/\;$/g, ''); }; module.exports = function(source) { const callback = this.async(); const options = loaderUtils.getOptions(this); this.cacheable && this.cacheable(); if (!!options.override && options.override !== this.resourcePath) { this.loadModule(path.resolve(this.context, options.override), function(err, overrideSource, sourceMap, module) { if (err) { return callback(err); } const baseObj = JSON.parse(_removeModuleSyntax(source)); const overrideObj = JSON.parse(_removeModuleSyntax(overrideSource)); let mergedModule; if (!!options.baseNamespace && !!options.overrideNamespace) { mergedModule = { [options.baseNamespace]: deepMerge(baseObj[options.baseNamespace], overrideObj[options.overrideNamespace]) }; } else { mergedModule = deepMerge(baseObj, overrideObj); } callback(null, JSON.stringify(mergedModule)); }); } else { callback(null, JSON.stringify(source)); } };
const loaderUtils = require('loader-utils'); const path = require('path'); const deepMerge = require('./lib/deep-merge'); function _removeModuleSyntax (moduleSource) { return moduleSource .replace(/^ ?module.exports ?= ?/i, '') .replace(/\;$/g, ''); }; module.exports = function(source) { const callback = this.async(); const options = loaderUtils.getOptions(this); const overridePath = path.resolve(this.context, options.override); this.cacheable && this.cacheable(); this.loadModule(overridePath, function(err, overrideSource, sourceMap, module) { if (err) { return callback(err); } const baseObj = JSON.parse(_removeModuleSyntax(source)); const overrideObj = JSON.parse(_removeModuleSyntax(overrideSource)); let mergedModule; if (!!options.baseNamespace && !!options.overrideNamespace) { mergedModule = { [options.baseNamespace]: deepMerge(baseObj[options.baseNamespace], overrideObj[options.overrideNamespace]) }; } else { mergedModule = deepMerge(baseObj, overrideObj); } callback(null, JSON.stringify(mergedModule)); }); };
Put the setName method back again
/* * (C) Copyright IBM Corporation 2016 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ibm.ws.microprofile.sample.conference.vote.model; public class Attendee { private String id; private final String revision; private String name; public Attendee(String name) { this(null, null, name); } public Attendee(String id, String name) { this(id, null, name); } public Attendee(String id, String revision, String name) { this.id = id; this.revision = revision; this.name = name; } public String getId() { return id; } public void setID(String id) { this.id = id; } public String getRevision() { return revision; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
/* * (C) Copyright IBM Corporation 2016 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ibm.ws.microprofile.sample.conference.vote.model; public class Attendee { private String id; private final String revision; private final String name; public Attendee(String name) { this(null, null, name); } public Attendee(String id, String name) { this(id, null, name); } public Attendee(String id, String revision, String name) { this.id = id; this.revision = revision; this.name = name; } public String getId() { return id; } public void setID(String id) { this.id = id; } public String getRevision() { return revision; } public String getName() { return name; } }
Update width of search box Minor fixes to classes, add new rounding classes for search box and button to achieve a neat join effect.
import PropTypes from 'prop-types'; import React, { Fragment } from 'react'; import AUtextInput from '@gov.au/text-inputs'; /** * The Search Results component * * @disable-docs */ const SearchResults = ( page ) => { return ( <div className="container-fluid au-body"> <div className="row"> <div className="col-xs-12 searchresults__list"> <h2 className="au-display-xxl">{ page.heading }</h2> <p><span id="searchresults__count" /> results for [query]</p> <div className="row"> <div className="col-xs-12 col-sm-6 col-md-5"> <form className="search__searchbox" role="search" autoComplete="off" action="/search" method="get"> <input type="search" className="au-text-input round--left" name="q" id="search-input" placeholder="Digital Guides"/> <button type="submit" className="au-btn icon icon--search--dark round--right" id="search-btn">Search</button> </form> </div> </div> <ul className="searchresults__ul" id="searchresults__resultslist"></ul> </div> </div> </div> ); } SearchResults.propTypes = { /** * _body: (partials)(4) */ _body: PropTypes.node.isRequired, }; SearchResults.defaultProps = {}; export default SearchResults;
import PropTypes from 'prop-types'; import React, { Fragment } from 'react'; import AUtextInput from '@gov.au/text-inputs'; /** * The Search Results component * * @disable-docs */ const SearchResults = ( page ) => { return ( <div className="container-fluid au-body"> <div className="row"> <div className="col-xs-12 searchresults__list"> <h2 className="au-display-xxl">{ page.heading }</h2> <p><span id="searchresults__count" /> results for [query]</p> <form className="search__searchbox" role="search" autoComplete="off" action="/search" method="get"> <input type="search" className="au-text-input" name="q" id="text-input" placeholder="Digital Guides"/> <button type="submit" className="au-btn au-btn--light icon icon--search--dark search__button">Search</button> </form> <ul className="searchresults__ul" id="searchresults__resultslist"></ul> </div> </div> </div> ); } SearchResults.propTypes = { /** * _body: (partials)(4) */ _body: PropTypes.node.isRequired, }; SearchResults.defaultProps = {}; export default SearchResults;
Fix get transaction by id
<?php namespace Nocks\SDK\Api; /** * Class Transaction * @package Nocks\SDK\Api */ class Transaction extends Api { /** * @param $transaction * @return \Nocks\SDK\Connection\Response */ public function create($transaction) { $transaction = $this->client->post('transaction', null, $transaction); return json_decode($transaction->body(), true); } /** * @param $transactionId * @return \Nocks\SDK\Connection\Response */ public function get($transactionId) { $transaction = $this->client->get('transaction/'.$transactionId); return json_decode($transaction->body(), true); } }
<?php namespace Nocks\SDK\Api; /** * Class Transaction * @package Nocks\SDK\Api */ class Transaction extends Api { /** * @param $transaction * @return \Nocks\SDK\Connection\Response */ public function create($transaction) { $transaction = $this->client->post('transaction', null, $transaction); return json_decode($transaction->body(), true); } /** * @param $transactionId * @return \Nocks\SDK\Connection\Response */ public function get($transactionId) { $transaction = $this->client->get('transaction', null, $transactionId); return json_decode($transaction->body(), true); } }
Add comment on ACM affil structure
import requests from lxml import html, etree def scrape_acm(page): tree = html.fromstring(page.content) author_affiliations = [] # The ACM author affiliations are stored in a kind of nasty table layout, # best to view source or inspect element on their page for an explanation of this. authors = tree.xpath('//td/a[@title="Author Profile Page"]') for a in authors: affiliation = a.getparent().getnext().find("a/small") # If we don't find it under a URL it's likely just a <small> if affiliation == None: affiliation = a.getparent().getnext().find("small") if affiliation: affiliation = affiliation.text else: affiliation = "None" author_affiliations.append(affiliation) return author_affiliations # Returns an array of the author affilations, ordered by the author appearance list on the paper # e.g. first author, second author, etc. This is done because we can't assume the names in the DBLP # database exactly match the names shown on the webpage. def scrape_affiliation(doi): # The doi urls are typically just http://dx.doi.org/... and we get the actual publication host # by following the redirect, so we must hit the page before we know if we can handle the URL # or not. page = requests.get(doi) if page.url.startswith("http://dl.acm.org/"): return scrape_acm(page) print("Warning! Unhandled Journal Site {}".format(page.url)) return None
import requests from lxml import html, etree def scrape_acm(page): tree = html.fromstring(page.content) author_affiliations = [] authors = tree.xpath('//td/a[@title="Author Profile Page"]') for a in authors: affiliation = a.getparent().getnext().find("a/small") # If we don't find it under a URL it's likely just a <small> if affiliation == None: affiliation = a.getparent().getnext().find("small") if affiliation: affiliation = affiliation.text else: affiliation = "None" author_affiliations.append(affiliation) return author_affiliations # Returns an array of the author affilations, ordered by the author appearance list on the paper # e.g. first author, second author, etc. This is done because we can't assume the names in the DBLP # database exactly match the names shown on the webpage. def scrape_affiliation(doi): # The doi urls are typically just http://dx.doi.org/... and we get the actual publication host # by following the redirect, so we must hit the page before we know if we can handle the URL # or not. page = requests.get(doi) if page.url.startswith("http://dl.acm.org/"): return scrape_acm(page) print("Error! Unhandled Journal Site {}".format(page.url)) return None
Add jshint options and comments.
/*jshint bitwise: true, curly: true, eqeqeq: true, forin: true, immed: true, indent: 4, latedef: true, newcap: true, noarg: true, noempty: true, nonew: true, quotmark: double, undef: true, unused: vars, strict: true, trailing: true, maxdepth: 3, devel: true, asi: true */ /*global HTMLElement: true */ // // ELEMENT // // Closest // Usage: element.closest(selector) this.Element && function (ElementPrototype) { ElementPrototype.closest = function (selector) { var node = this; while (node) { if (node == document) return undefined; if (node.matches(selector)) return node; node = node.parentNode; } } } (Element.prototype); // Matches // Usage: element.matches(selector) this.Element && function (ElementPrototype) { ElementPrototype.matches = ElementPrototype.matches || ElementPrototype.matchesSelector || ElementPrototype.mozMatchesSelector || ElementPrototype.msMatchesSelector || ElementPrototype.webkitMatchesSelector || function (selector) { var node = this, nodes = (node.parentNode || node.document).querySelectorAll(selector), i = -1; while (nodes[++i] && nodes[i] != node); return !!nodes[i]; } } (Element.prototype);
this.Element && function (ElementPrototype) { ElementPrototype.matches = ElementPrototype.matches || ElementPrototype.matchesSelector || ElementPrototype.mozMatchesSelector || ElementPrototype.msMatchesSelector || ElementPrototype.webkitMatchesSelector || function (selector) { var node = this, nodes = (node.parentNode || node.document).querySelectorAll(selector), i = -1; while (nodes[++i] && nodes[i] != node); return !!nodes[i]; } } (Element.prototype); this.Element && function (ElementPrototype) { ElementPrototype.closest = function (selector) { var node = this; while (node) { if (node == document) return undefined; if (node.matches(selector)) return node; node = node.parentNode; } } } (Element.prototype);
:bug: Fix test case in react 15
import React from 'react'; let Trigger; // eslint-disable-line if (process.env.REACT === '15') { const ActualTrigger = require.requireActual('rc-trigger'); // cannot use object destruction, cause react 15 test cases fail const render = ActualTrigger.prototype.render; // eslint-disable-line ActualTrigger.prototype.render = function () { const { popupVisible } = this.state; // eslint-disable-line let component; if (popupVisible || this._component) { // eslint-disable-line component = this.getComponent(); // eslint-disable-line } return ( <div id="TriggerContainer"> {render.call(this)} {component} </div> ); }; Trigger = ActualTrigger; } else { const TriggerMock = require('rc-trigger/lib/mock'); // eslint-disable-line Trigger = TriggerMock; } export default Trigger;
import React from 'react'; let Trigger; // eslint-disable-line if (process.env.REACT === '15') { const ActualTrigger = require.requireActual('rc-trigger'); // cannot use object destruction, cause react 15 test cases fail const render = ActualTrigger.prototype.render; // eslint-disable-line ActualTrigger.prototype.render = () => { const { popupVisible } = this.state; // eslint-disable-line let component; if (popupVisible || this._component) { // eslint-disable-line component = this.getComponent(); // eslint-disable-line } return ( <div id="TriggerContainer"> {render.call(this)} {component} </div> ); }; Trigger = ActualTrigger; } else { const TriggerMock = require('rc-trigger/lib/mock'); // eslint-disable-line Trigger = TriggerMock; } export default Trigger;
Update LS Schleswig feed URL
/* * substitution-schedule-parser - Java library for parsing schools' substitution schedules * Copyright (c) 2017 Johan v. Forstner * * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. * If a copy of the MPL was not distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/. */ package me.vertretungsplan.additionalinfo.lsschleswig; import me.vertretungsplan.additionalinfo.BaseRSSFeedParser; public class LsSchleswigRSSParser extends BaseRSSFeedParser { @Override protected String getRSSUrl() { return "http://hp.lornsenschule.de/index" + ".php/12-aktuelle-beitraege?option=com_content&format=feed&type=rss&filter_order=a" + ".publish_up&filter_order_Dir=desc"; } }
/* * substitution-schedule-parser - Java library for parsing schools' substitution schedules * Copyright (c) 2017 Johan v. Forstner * * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. * If a copy of the MPL was not distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/. */ package me.vertretungsplan.additionalinfo.lsschleswig; import me.vertretungsplan.additionalinfo.BaseRSSFeedParser; public class LsSchleswigRSSParser extends BaseRSSFeedParser { @Override protected String getRSSUrl() { return "http://hp.lornsenschule.de/index" + ".php/schule/artikelarchiv?option=com_content&format=feed&type=rss&filter_order=a" + ".publish_up&filter_order_Dir=desc"; } }
Refactor the one file converter.
import fs from 'fs'; import path from 'path'; import promisify from 'es6-promisify'; import { InvalidFile, InvalidJsonString } from './errors'; export function convertOneFile(fileName, destFileName) { const fileReadPromise = promisify(fs.readFile); const fileWritePromise = promisify(fs.writeFile); const readFile = fileReadPromise(fileName) .catch(reason => {throw new InvalidFile(reason.path)}); const minify = fileContent => minifyJson(fileContent) .catch(() => {throw new InvalidJsonString()}); const writeFile = minifiedJson => fileWritePromise(destFileName, minifiedJson) .catch(reason => {throw new InvalidFile(reason.path)}); return readFile .then(minify) .then(writeFile); } const minifyJson = content => new Promise((resolve, reject) => { try { resolve(JSON.stringify(JSON.parse(content))); } catch (e) { reject(e); } });
import fs from 'fs'; import path from 'path'; import promisify from 'es6-promisify'; import { InvalidFile, InvalidJsonString } from './errors'; export function convertOneFile(fileName, destFileName) { const fileReadPromise = promisify(fs.readFile); const fileWritePromise = promisify(fs.writeFile); return fileReadPromise(fileName) .then(fileContent => fileWritePromise(destFileName, minifyJson(fileContent)) ) .catch(reason => { if (reason instanceof InvalidJsonString) throw reason; throw new InvalidFile(reason.path); } ); } function minifyJson(content) { try { return JSON.stringify(JSON.parse(content)); } catch (e) { throw new InvalidJsonString(); } }
Allow adding translations for console commands This is the state when there is no request available
<?php namespace ForkCMS\Core\Domain\Application; use ForkCMS\Modules\Internationalisation\Domain\Translation\TranslationKey; use Symfony\Contracts\Translation\TranslatableInterface; use Symfony\Contracts\Translation\TranslatorInterface; enum Application: string implements TranslatableInterface { case BACKEND = 'backend'; case FRONTEND = 'frontend'; case CONSOLE = 'console'; case API = 'api'; public function trans(TranslatorInterface $translator, string $locale = null): string { return $translator->trans('lbl.Application' . ucfirst($this->value), locale: $locale); } public function canHaveTranslations(): bool { return match ($this) { self::BACKEND, self::FRONTEND, self::CONSOLE => true, default => false, }; } }
<?php namespace ForkCMS\Core\Domain\Application; use ForkCMS\Modules\Internationalisation\Domain\Translation\TranslationKey; use Symfony\Contracts\Translation\TranslatableInterface; use Symfony\Contracts\Translation\TranslatorInterface; enum Application: string implements TranslatableInterface { case BACKEND = 'backend'; case FRONTEND = 'frontend'; case CONSOLE = 'console'; case API = 'api'; public function trans(TranslatorInterface $translator, string $locale = null): string { return $translator->trans('lbl.Application' . ucfirst($this->value), locale: $locale); } public function canHaveTranslations(): bool { return match ($this) { self::BACKEND, self::FRONTEND => true, default => false, }; } }
feat: Format pie-date to proper format each time model change
import Ember from 'ember'; import $ from 'jquery'; export default Ember.Controller.extend({ spendingsMeter: 0.00, sumByCategory: null, watchAddSpending: function () { this.updateSpendingsMeter(); }.observes('model.@each'), updateSpendingsMeter () { let sumCounted = 0; let sumByCategory = []; this.get('model').forEach(item => { let sum = item.get('sum'); let category = item.get('category'); if (sumByCategory.findBy('category', category)) { sumByCategory.findBy('category', category).sum += parseFloat(sum); } else { sumByCategory.pushObject({ category, sum: parseFloat(sum) }); } sumCounted += parseFloat(sum); }); this.set('spendingsMeter', sumCounted); this.set('sumByCategory', sumByCategory); return; }, formatedChartData: function () { const data = [ ['Category', 'Spendings'] ]; this.get('sumByCategory').forEach(category => { data.push( [category.category, category.sum] ); }); return data; }.property('sumByCategory'), saveRecord (record) { let newExpense = this.store.createRecord('expense', record); newExpense.save(); } } });
import Ember from 'ember'; import $ from 'jquery'; export default Ember.Controller.extend({ spendingsMeter: 0.00, sumByCategory: null, watchAddSpending: function () { this.updateSpendingsMeter(); }.observes('model.@each'), updateSpendingsMeter () { let sumCounted = 0; let sumByCategory = []; this.get('model').forEach(item => { let sum = item.get('sum'); let category = item.get('category'); if (sumByCategory.findBy('category', category)) { sumByCategory.findBy('category', category).sum += parseFloat(sum); } else { sumByCategory.pushObject({ category, sum: parseFloat(sum) }); } sumCounted += parseFloat(sum); }); this.set('spendingsMeter', sumCounted); this.set('sumByCategory', sumByCategory); return; }, saveRecord (record) { let newExpense = this.store.createRecord('expense', record); newExpense.save(); } } });
Update expression/aggregate.js - change the constructor signature
import Expression from './base' /** * @class ColumnExpression */ export default class Column extends Expression { /** * * @param {String} name * @constructor */ constructor(value) { super() var as = '' var table = '' if ( !as && value.toLowerCase().indexOf(' as ') > 0 ) [value, as] = value.split(' as ').map(str => str.trim()) if ( !table && value.indexOf('.') > 0 ) [table, value] = value.split('.').map(str => str.trim()) this.table = table this.name = value this.alias = as } /** * * @param {Compiler} compiler * @return string */ compile(compiler) { var table = this.table var column = compiler.escapeIdentifier(this.name) if ( table ) table = compiler.escapeIdentifier(this.table) + '.' return compiler.alias(table + column, this.alias) } /** * * @param {Any} expr * @return boolean */ isEqual(expr) { return super.isEqual() || ( expr instanceof Column && expr.name === this.name && expr.table === this.table && expr.alias === this.alias ) } }
import Expression from './base' /** * @class ColumnExpression */ export default class Column extends Expression { /** * * @param {String} name * @param {String} table * @param {String} as * @constructor */ constructor(name, table = '', as = '') { super() if ( !as && name.toLowerCase().indexOf(' as ') > 0 ) [name, as] = name.split(' as ').map(str => str.trim()) if ( !table && name.indexOf('.') > 0 ) [table, name] = name.split('.').map(str => str.trim()) this.table = table this.name = name this.alias = as } /** * * @param {Compiler} compiler * @return string */ compile(compiler) { var table = this.table var column = compiler.escapeIdentifier(this.name) if ( table ) table = compiler.escapeIdentifier(this.table) + '.' return compiler.alias(table + column, this.alias) } /** * * @param {Any} expr * @return boolean */ isEqual(expr) { return super.isEqual() || ( expr instanceof Column && expr.name === this.name && expr.table === this.table && expr.alias === this.alias ) } }
Use explicit read buffer size in curio/streams bench
from curio import Kernel, new_task, run_server from socket import * async def echo_handler(client, addr): print('Connection from', addr) try: client.setsockopt(IPPROTO_TCP, TCP_NODELAY, 1) except (OSError, NameError): pass reader, writer = client.make_streams() async with reader, writer: while True: data = await reader.read(102400) if not data: break await writer.write(data) await client.close() print('Connection closed') if __name__ == '__main__': kernel = Kernel() kernel.run(run_server('', 25000, echo_handler))
from curio import Kernel, new_task, run_server from socket import * async def echo_handler(client, addr): print('Connection from', addr) try: client.setsockopt(IPPROTO_TCP, TCP_NODELAY, 1) except (OSError, NameError): pass reader, writer = client.make_streams() async with reader, writer: while True: data = await reader.read() if not data: break await writer.write(data) await client.close() print('Connection closed') if __name__ == '__main__': kernel = Kernel() kernel.run(run_server('', 25000, echo_handler))
Remove failing expectations for the pixel tests. The expectations were only in temporarily to allow a rebaseline. BUG=416450 Review URL: https://codereview.chromium.org/591213002 Cr-Commit-Position: 972c6d2dc6dd5efdad1377c0d224e03eb8f276f7@{#296061}
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from telemetry.page import test_expectations # Valid expectation conditions are: # # Operating systems: # win, xp, vista, win7, mac, leopard, snowleopard, lion, mountainlion, # linux, chromeos, android # # GPU vendors: # amd, arm, broadcom, hisilicon, intel, imagination, nvidia, qualcomm, # vivante # # Specific GPUs can be listed as a tuple with vendor name and device ID. # Examples: ('nvidia', 0x1234), ('arm', 'Mali-T604') # Device IDs must be paired with a GPU vendor. class PixelExpectations(test_expectations.TestExpectations): def SetExpectations(self): # Sample Usage: # self.Fail('Pixel.Canvas2DRedBox', # ['mac', 'amd', ('nvidia', 0x1234)], bug=123) pass
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from telemetry.page import test_expectations # Valid expectation conditions are: # # Operating systems: # win, xp, vista, win7, mac, leopard, snowleopard, lion, mountainlion, # linux, chromeos, android # # GPU vendors: # amd, arm, broadcom, hisilicon, intel, imagination, nvidia, qualcomm, # vivante # # Specific GPUs can be listed as a tuple with vendor name and device ID. # Examples: ('nvidia', 0x1234), ('arm', 'Mali-T604') # Device IDs must be paired with a GPU vendor. class PixelExpectations(test_expectations.TestExpectations): def SetExpectations(self): # Sample Usage: # self.Fail('Pixel.Canvas2DRedBox', # ['mac', 'amd', ('nvidia', 0x1234)], bug=123) self.Fail('Pixel.CSS3DBlueBox', bug=416450) pass
Make Biblioteca methods non static
package com.twu.biblioteca; import com.twu.biblioteca.menu.MainMenu; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class BibliotecaApp { private MainMenu menu = MainMenu.instance; public static boolean testing = false; //Used to prevent infinite loop during unit tests public static void main(String[] args) { BibliotecaApp app = new BibliotecaApp(); app.run(); } private void run() { displayWelcomeMessage(); menu.loop(); } public static String readLine() throws IOException { return new BufferedReader(new InputStreamReader(System.in)).readLine(); } private void displayWelcomeMessage() { print("Welcome to Biblioteca.\n"); } public static void print(String str) { System.out.print(str); } public static void setTesting(boolean testing) { BibliotecaApp.testing = testing; } }
package com.twu.biblioteca; import com.twu.biblioteca.menu.MainMenu; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class BibliotecaApp { private static MainMenu menu = MainMenu.instance; public static boolean testing = false; //Used to prevent infinite loop during unit tests public static void main(String[] args) { displayWelcomeMessage(); menu.loop(); } public static String readLine() throws IOException { return new BufferedReader(new InputStreamReader(System.in)).readLine(); } private static void displayWelcomeMessage() { print("Welcome to Biblioteca.\n"); } public static void print(String str) { System.out.print(str); } public static void setTesting(boolean testing) { BibliotecaApp.testing = testing; } }
Clarify logic around codesGenerated boolean
var utils = require("./utils"); function CodeManager() { this.codes = []; this.currentSession = -1; this.codesGenerated = false; } CodeManager.prototype.nextSession = function() { if (!this.codesGenerated) { throw "No codes generated"; } if (this.codes[this.currentSession + 1]) { this.currentSession++; } else { this.currentSession = -1; throw "Out of generated codes"; } }; CodeManager.prototype.generateCodes = function(nbrOfUsers, nbrOfCodesPerUser, lengthOfCodes) { this.codesGenerated = true; return this.codes = utils.generateCodes(nbrOfUsers, nbrOfCodesPerUser, lengthOfCodes); }; CodeManager.prototype.currentSessionCodes = function() { return this.codes[this.currentSession]; }; CodeManager.prototype.isValidCode = function(code) { return this.currentSessionCodes().indexOf(code) !== -1; }; CodeManager.prototype.invalidateCode = function(code) { var previousLength = this.currentSessionCodes().length; this.codes[this.currentSession] = this.currentSessionCodes().filter(function(sessionCode) { return sessionCode !== code; }); return previousLength - 1 === this.currentSessionCodes().length; }; module.exports = CodeManager;
var utils = require("./utils"); function CodeManager() { this.codes = []; this.currentSession = -1; this.codesGenerated = false; } CodeManager.prototype.nextSession = function() { if (this.codes[this.currentSession + 1]) { this.currentSession++; } else if (this.currentSession === -1) { throw "No codes generated"; } else { this.currentSession = -1; throw "Out of generated codes"; } }; CodeManager.prototype.generateCodes = function(nbrOfUsers, nbrOfCodesPerUser, lengthOfCodes) { this.codesGenerated = true; return this.codes = utils.generateCodes(nbrOfUsers, nbrOfCodesPerUser, lengthOfCodes); }; CodeManager.prototype.currentSessionCodes = function() { return this.codes[this.currentSession]; }; CodeManager.prototype.isValidCode = function(code) { return this.currentSessionCodes().indexOf(code) !== -1; }; CodeManager.prototype.invalidateCode = function(code) { var previousLength = this.currentSessionCodes().length; this.codes[this.currentSession] = this.currentSessionCodes().filter(function(sessionCode) { return sessionCode !== code; }); return previousLength - 1 === this.currentSessionCodes().length; }; module.exports = CodeManager;
Make default grunt task build entire app Change-Id: I0f3ccabd86f69c6f402b69c34addceb653398038
module.exports = function(grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), cedict: { 'cedict.js': 'cedict_ts.u8' }, compass: { dist: { options: { require: ['animation'], sassDir: 'assets/sass', cssDir: 'assets/css' } } }, watch: { styles: { files: ['assets/sass/*.sass'], tasks: ['compass'] } } }); grunt.loadTasks('./tasks'); grunt.loadNpmTasks('grunt-contrib-compass'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.registerTask('default', ['cedict', 'compass']); };
module.exports = function(grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), cedict: { 'cedict.js': 'cedict_ts.u8' }, compass: { dist: { options: { require: ['animation'], sassDir: 'assets/sass', cssDir: 'assets/css' } } }, watch: { styles: { files: ['assets/sass/*.sass'], tasks: ['compass'] } } }); grunt.loadTasks('./tasks'); grunt.loadNpmTasks('grunt-contrib-compass'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.registerTask('default', ['compass']); };
Detach both level select transition input methods from tutorial
function TutorialState(game) { this.game = game; this.playingState = new PlayingState(game); var renderRegion = new RenderRegion(null, game.canvas.height * .005, null, game.canvas.height * .10); var tutorial = new TutorialRenderer(game.brush, renderRegion, game.config.textColor, game.config.textBackground); this.tutorial = tutorial; var afterInput = this.playingState.levelKeyboardInputMethod.afterInput; var tutorialAfterInput = function() { afterInput(); tutorial.draw(); }; this.playingState.levelKeyboardInputMethod.afterInput = tutorialAfterInput; this.playingState.levelTouchInputMethod.afterInput = tutorialAfterInput; } TutorialState.prototype.onEnter = function(context) { if(!context) { context = {}; } context.level = this.tutorial.level = this.game.levels.get(1); this.playingState.onEnter(context); this.playingState.selectTransitionKeyboardInputMethod.detach(); this.playingState.selectTransitionTouchInputMethod.detach(); this.tutorial.renderRegion.x = this.playingState.statusBar.renderRegion.x; this.tutorial.renderRegion.width = this.playingState.statusBar.renderRegion.width; this.tutorial.draw(); this.tutorial.initial = false; }; TutorialState.prototype.onLeave = function() { return this.playingState.onLeave(); };
function TutorialState(game) { this.game = game; this.playingState = new PlayingState(game); var renderRegion = new RenderRegion(null, game.canvas.height * .005, null, game.canvas.height * .10); var tutorial = new TutorialRenderer(game.brush, renderRegion, game.config.textColor, game.config.textBackground); this.tutorial = tutorial; var afterInput = this.playingState.levelKeyboardInputMethod.afterInput; var tutorialAfterInput = function() { afterInput(); tutorial.draw(); }; this.playingState.levelKeyboardInputMethod.afterInput = tutorialAfterInput; this.playingState.levelTouchInputMethod.afterInput = tutorialAfterInput; } TutorialState.prototype.onEnter = function(context) { if(!context) { context = {}; } context.level = this.tutorial.level = this.game.levels.get(1); this.playingState.onEnter(context); this.playingState.selectTransitionInputMethod.detach(); this.tutorial.renderRegion.x = this.playingState.statusBar.renderRegion.x; this.tutorial.renderRegion.width = this.playingState.statusBar.renderRegion.width; this.tutorial.draw(); this.tutorial.initial = false; }; TutorialState.prototype.onLeave = function() { return this.playingState.onLeave(); };
Update header comment with correct date creation, dependencies, and modules needed
/* NewsSelector.js * Use reselect.js library for our seearch functionlity which has two types of selectors: input and memoized * Dependencies: reselect * Modules: reshapeNewsData * Author: Tiffany Tse * Created: August 12, 2017 */ //import dependencies import {createSelector } from 'reselect'; //import modules import { reshapeNewsData } from '../util/DataTransformations.js'; //pass state to newsSelector where wstate.news is passed to reshapeNewsData as input const newsSelector = state => state.news; /*Return the news portion of our Redux state tree. From there, we create two memoized selectors–reshapeNewsSelector and allNewsSelector. Memoized selectors take two arguments. The first is an array of inputs or memoized selectors.*/ const reshapeNewsSelector = createSelector( [newsSelector], reshapeNewsData ); //allNewsSelector simply returns the entire transformed list without modification (newsItems => newsItems). export const allNewsSelector = createSelector( [reshapeNewsSelector], newsItems => newsItems );
/* NewsSelector.js * Use reselect.js library for our seearch functionlity which has two types of selectors: input and memoized * Dependencies: ActionTypes * Modules: NewsActions, and NewsFeed * Author: Tiffany Tse * Created: July 29, 2017 */ //import dependencies import {createSelector } from 'reselect'; //import modules import { reshapeNewsData } from '../util/DataTransformations.js'; //pass state to newsSelector where wstate.news is passed to reshapeNewsData as input const newsSelector = state => state.news; /*Return the news portion of our Redux state tree. From there, we create two memoized selectors–reshapeNewsSelector and allNewsSelector. Memoized selectors take two arguments. The first is an array of inputs or memoized selectors.*/ const reshapeNewsSelector = createSelector( [newsSelector], reshapeNewsData ); //allNewsSelector simply returns the entire transformed list without modification (newsItems => newsItems). export const allNewsSelector = createSelector( [reshapeNewsSelector], newsItems => newsItems );
Set verbose name of NewResource.
from django.db import models from bulletin.models import Post class Event(Post): start_date = models.DateTimeField() end_date = models.DateTimeField(null=True, blank=True) time = models.CharField(max_length=255, null=True, blank=True) organization = models.CharField(max_length=255, null=True, blank=True) location = models.CharField(max_length=255) class Job(Post): organization = models.CharField(max_length=255) class NewResource(Post): blurb = models.TextField() verbose_name = 'newresource' class Opportunity(Post): blurb = models.TextField() class Meta: verbose_name_plural = 'opportunities' class Story(Post): blurb = models.TextField() date = models.DateTimeField() class Meta: verbose_name_plural = 'stories'
from django.db import models from bulletin.models import Post class Event(Post): start_date = models.DateTimeField() end_date = models.DateTimeField(null=True, blank=True) time = models.CharField(max_length=255, null=True, blank=True) organization = models.CharField(max_length=255, null=True, blank=True) location = models.CharField(max_length=255) class Job(Post): organization = models.CharField(max_length=255) class NewResource(Post): blurb = models.TextField() class Opportunity(Post): blurb = models.TextField() class Meta: verbose_name_plural = 'opportunities' class Story(Post): blurb = models.TextField() date = models.DateTimeField() class Meta: verbose_name_plural = 'stories'
Delete old teams before seeding
<?php use Illuminate\Database\Seeder; use Illuminate\Support\Facades\File; use Illuminate\Support\Facades\DB; class TeamTableSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { DB::table('teams')->delete(); $teamsAsString = File::get(storage_path('data/teams')); foreach(explode("\n", $teamsAsString) as $team) { if (strlen($team) > 0) { DB::table('teams')->insert([ 'name' => $team ]); } } } }
<?php use Illuminate\Database\Seeder; use Illuminate\Support\Facades\File; use Illuminate\Support\Facades\DB; class TeamTableSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { $teamsAsString = File::get(storage_path('data/teams')); foreach(explode("\n", $teamsAsString) as $team) { if (strlen($team) > 0) { DB::table('teams')->insert([ 'name' => $team ]); } } } }
Fix start new project from type - count was missing
import Ember from 'ember'; import AuthenticatedRouteMixin from 'simple-auth/mixins/authenticated-route-mixin'; // global $ export default Ember.Route.extend(AuthenticatedRouteMixin, { actions: { createType: function () { this.transitionTo('types.new'); }, deleteType: function (type) { type.destroyRecord(); }, startProject: function (type, name) { var project = this.store.createRecord('item', { serial: name, type: type, count: 1 }); var self = this; project.save().then(function (p) { self.transitionTo('items.show', p); }).catch(function () { project.rollback(); }); } }, activate: function() { $(document).attr('title', 'shelves - Part types'); }, model: function () { return this.store.peekAll('type'); } });
import Ember from 'ember'; import AuthenticatedRouteMixin from 'simple-auth/mixins/authenticated-route-mixin'; // global $ export default Ember.Route.extend(AuthenticatedRouteMixin, { actions: { createType: function () { this.transitionTo('types.new'); }, deleteType: function (type) { type.destroyRecord(); }, startProject: function (type, name) { var project = this.store.createRecord('item', { serial: name, type: type }); var self = this; project.save().then(function (p) { self.transitionTo('items.show', p); }).catch(function () { project.rollback(); }); } }, activate: function() { $(document).attr('title', 'shelves - Part types'); }, model: function () { return this.store.peekAll('type'); } });
Change the virtualenv test to an integration test So that we're not downloading them constantly
import os from ..virtualenv import ext_virtualenv def integration(tmpdir): tmpdir = str(tmpdir) abs_source = os.path.join(tmpdir, 'requirements.txt') with open(abs_source, 'w') as vfile: vfile.write('bottle\n') vfile.write('pytest\n') dest = os.path.join(tmpdir, 'env~virtualenv') finalfile = ext_virtualenv(abs_source, dest) assert os.path.exists(finalfile) assert os.path.exists(os.path.join(finalfile, 'bin', 'activate')) assert os.path.exists(os.path.join(finalfile, 'bin', 'activate')) lib_dir = os.path.join(finalfile, 'lib', 'python2.7', 'site-packages') assert os.path.exists(os.path.join(lib_dir, 'bottle.py')) assert os.path.exists(os.path.join(lib_dir, 'pytest.py'))
import os from ..virtualenv import ext_virtualenv def test_basic(tmpdir): tmpdir = str(tmpdir) abs_source = os.path.join(tmpdir, 'requirements.txt') with open(abs_source, 'w') as vfile: vfile.write('bottle\n') vfile.write('pytest\n') dest = os.path.join(tmpdir, 'env~virtualenv') finalfile = ext_virtualenv(abs_source, dest) assert os.path.exists(finalfile) assert os.path.exists(os.path.join(finalfile, 'bin', 'activate')) assert os.path.exists(os.path.join(finalfile, 'bin', 'activate')) lib_dir = os.path.join(finalfile, 'lib', 'python2.7', 'site-packages') assert os.path.exists(os.path.join(lib_dir, 'bottle.py')) assert os.path.exists(os.path.join(lib_dir, 'pytest.py'))
Fix error mssage of ParagraphNumber
/** * redpen: a text inspection tool * Copyright (c) 2014-2015 Recruit Technologies Co., Ltd. and contributors * (see CONTRIBUTORS.md) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package cc.redpen.validator.section; import cc.redpen.model.Section; import cc.redpen.validator.Validator; /** * Validate paragraph number. If a section has paragraphs more than specified, * This validator reports it. */ final public class ParagraphNumberValidator extends Validator { public ParagraphNumberValidator() { super("max_num", 5); // Default maximum number of paragraphs in a section. } @Override public void validate(Section section) { int paragraphNumber = section.getNumberOfParagraphs(); if (getInt("max_num") < paragraphNumber) { addLocalizedError(section.getJoinedHeaderContents(), getInt("max_num")); } } }
/** * redpen: a text inspection tool * Copyright (c) 2014-2015 Recruit Technologies Co., Ltd. and contributors * (see CONTRIBUTORS.md) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package cc.redpen.validator.section; import cc.redpen.model.Section; import cc.redpen.validator.Validator; /** * Validate paragraph number. If a section has paragraphs more than specified, * This validator reports it. */ final public class ParagraphNumberValidator extends Validator { public ParagraphNumberValidator() { super("max_num", 5); // Default maximum number of paragraphs in a section. } @Override public void validate(Section section) { int paragraphNumber = section.getNumberOfParagraphs(); if (getInt("max_num") < paragraphNumber) { addLocalizedError(section.getJoinedHeaderContents(), paragraphNumber); } } }
Make tabs closable in DynamicTabPanel
{ netzkeTabComponentDelivered: function(c, config) { var tab, i, activeTab = this.getActiveTab(), cmp = Ext.ComponentManager.create(Ext.apply(c, {closable: true})); if (config.newTab || activeTab == null) { tab = this.add(cmp); } else { tab = this.getActiveTab(); i = this.items.indexOf(tab); this.remove(tab); tab = this.insert(i, cmp); } this.setActiveTab(tab); }, netzkeLoadComponentByClass: function(klass, options) { this.netzkeLoadComponent('child', Ext.apply(options, { configOnly: true, clone: true, clientConfig: Ext.apply(options.clientConfig || {}, {klass: klass}), callback: this.netzkeTabComponentDelivered, scope: this, })); } }
{ netzkeTabComponentDelivered: function(c, config) { var tab, i, activeTab = this.getActiveTab(), cmp = Ext.ComponentManager.create(c); if (config.newTab || activeTab == null) { tab = this.add(cmp); } else { tab = this.getActiveTab(); i = this.items.indexOf(tab); this.remove(tab); tab = this.insert(i, cmp); } this.setActiveTab(tab); }, netzkeLoadComponentByClass: function(klass, options) { this.netzkeLoadComponent('child', Ext.apply(options, { configOnly: true, clone: true, clientConfig: Ext.apply(options.clientConfig || {}, {klass: klass}), callback: this.netzkeTabComponentDelivered, scope: this, })); } }
Fix XML Checking on HHVM
<?php function isXml($filename) { $xml = XMLReader; $xml->open($filename); // The validate parser option must be enabled for // this method to work properly $xml->setParserProperty(XMLReader::VALIDATE, true); return $xml->isValid(); } require_once __DIR__.'/../_functions/glob_recursive.php'; $xml_files = glob_recursive(__DIR__.'/../*.xml'); $result['invalid_files'] = array(); $result['valid_files'] = array(); foreach ( $xml_files as $filename ) { // Validate if ( isXml($filename) ) { $result['valid_files'][] = $filename; } else { $result['invalid_files'][] = $filename; } } var_dump($result); if ( !empty($result['invalid_files']) ) { // That's an error exit(1); }
<?php function isXml($filename) { $xml = XMLReader::open($filename); // The validate parser option must be enabled for // this method to work properly $xml->setParserProperty(XMLReader::VALIDATE, true); return $xml->isValid(); } require_once __DIR__.'/../_functions/glob_recursive.php'; $xml_files = glob_recursive(__DIR__.'/../*.xml'); $result['invalid_files'] = array(); $result['valid_files'] = array(); foreach ( $xml_files as $filename ) { // Validate if ( isXml($filename) ) { $result['valid_files'][] = $filename; } else { $result['invalid_files'][] = $filename; } } var_dump($result); if ( !empty($result['invalid_files']) ) { // That's an error exit(1); }
Update the style of the dialog with open source licenses
package com.khmelenko.lab.travisclient.fragment; import android.app.Dialog; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v4.app.DialogFragment; import android.support.v7.app.AlertDialog; import android.view.LayoutInflater; import android.webkit.WebView; import com.khmelenko.lab.travisclient.R; /** * Dialog with licenses * * @author Dmytro Khmelenko (d.khmelenko@gmail.com) */ public class LicensesDialogFragment extends DialogFragment { public static LicensesDialogFragment newInstance() { return new LicensesDialogFragment(); } @NonNull @Override public Dialog onCreateDialog(Bundle savedInstanceState) { WebView view = (WebView) LayoutInflater.from(getActivity()).inflate(R.layout.dialog_licenses, null); view.loadUrl("file:///android_asset/opensource_licenses.html"); return new AlertDialog.Builder(getActivity()) .setTitle(getString(R.string.dialog_licenses_title)) .setView(view, 0, 25, 0, 0) .create(); } }
package com.khmelenko.lab.travisclient.fragment; import android.app.Dialog; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v4.app.DialogFragment; import android.support.v7.app.AlertDialog; import android.view.LayoutInflater; import android.webkit.WebView; import com.khmelenko.lab.travisclient.R; /** * Dialog with licenses * * @author Dmytro Khmelenko (d.khmelenko@gmail.com) */ public class LicensesDialogFragment extends DialogFragment { public static LicensesDialogFragment newInstance() { return new LicensesDialogFragment(); } @NonNull @Override public Dialog onCreateDialog(Bundle savedInstanceState) { WebView view = (WebView) LayoutInflater.from(getActivity()).inflate(R.layout.dialog_licenses, null); view.loadUrl("file:///android_asset/opensource_licenses.html"); return new AlertDialog.Builder(getActivity(), R.style.Theme_AppCompat_Light_Dialog_Alert) .setTitle(getString(R.string.dialog_licenses_title)) .setView(view) .setPositiveButton(android.R.string.ok, null) .create(); } }
Remove console.log from server start
/* Kent Hack Enough Let's try to organize organizing. @author Paul Dilyard To get the app instance, just call getAppInstance() from anywhere To get a db connection, require('mongoose') */ var express = require('express'); var mongoose = require('mongoose'); var bodyParser = require('body-parser'); var multer = require('multer'); var error = require('./app/error'); // Start up server var app = express(); app.use(bodyParser.urlencoded({ extended: false })); app.use(bodyParser.json()); app.use(multer({dest: './uploads/'})); app.use(error); var port = process.env.PORT || 3000; var server = app.listen(port); // Connect to database var mongo = process.env.MONGO_URI || 'mongodb://localhost:27017/khe'; mongoose.connect(mongo); module.exports.app = app; module.exports.mongoose = mongoose; GLOBAL.getAppInstance = function () { return app; }; // Include modules [ 'users', 'applications' ].forEach(function (module) { require('./app/' + module + '/controller'); });
/* Kent Hack Enough Let's try to organize organizing. @author Paul Dilyard To get the app instance, just call getAppInstance() from anywhere To get a db connection, require('mongoose') */ var express = require('express'); var mongoose = require('mongoose'); var bodyParser = require('body-parser'); var multer = require('multer'); var error = require('./app/error'); // Start up server var app = express(); app.use(bodyParser.urlencoded({ extended: false })); app.use(bodyParser.json()); app.use(multer({dest: './uploads/'})); app.use(error); var port = process.env.PORT || 3000; var server = app.listen(port, function () { var host = server.address().address; var port = server.address().port; console.log('\n 🎉 Kent Hack Enough listening at %s%s\n', host, port); }); // Connect to database var mongo = process.env.MONGO_URI || 'mongodb://localhost:27017/khe'; mongoose.connect(mongo); module.exports.app = app; module.exports.mongoose = mongoose; GLOBAL.getAppInstance = function () { return app; }; // Include modules [ 'users', 'applications' ].forEach(function (module) { require('./app/' + module + '/controller'); });