text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Fix hiding sign-up form on success.
Teikei.module('User', function(User, App, Backbone, Marionette, $, _) { User.Model = Backbone.Model.extend({ urlRoot: "/api/v1/sessions/", initialize: function() { if ($.cookie('auth_token')) { this.setAuthToken($.cookie('auth_token')); this.setUserName($.cookie('username')); } }, parse: function(user) { $.cookie('username', user.name); $.cookie('auth_token', user.auth_token); this.setAuthToken(user.auth_token); this.setUserName(user.name); return user; }, setUserName: function(userName) { this.set("userName", userName); }, setAuthToken:function(authToken) { this.set("loggedIn", true); var headerData = { auth_token: authToken }; $.ajaxSetup({ headers: headerData }); }, signUp: function(signUpData, callback) { this.save(signUpData, { url: "/api/v1/users", success: callback.success, error: callback.error }); }, destroy: function() { $.removeCookie('username'); $.removeCookie('auth_token'); return Backbone.Model.prototype.destroy.apply(this, arguments); } }); });
Teikei.module('User', function(User, App, Backbone, Marionette, $, _) { User.Model = Backbone.Model.extend({ urlRoot: "/api/v1/sessions/", initialize: function() { if ($.cookie('auth_token')) { this.setAuthToken($.cookie('auth_token')); this.setUserName($.cookie('username')); } }, parse: function(data) { $.cookie('username', data.user.name); $.cookie('auth_token', data.auth_token); this.setAuthToken(data.auth_token); this.setUserName(data.user.name); return data.user; }, setUserName: function(userName) { this.set("userName", userName); }, setAuthToken:function(authToken) { this.set("loggedIn", true); var headerData = { auth_token: authToken }; $.ajaxSetup({ headers: headerData }); }, signUp: function(signUpData, callback) { this.save(signUpData, { url: "/api/v1/users", success: callback.success, error: callback.error }); }, destroy: function() { $.removeCookie('username'); $.removeCookie('auth_token'); return Backbone.Model.prototype.destroy.apply(this, arguments); } }); });
ikiwiki: Allow only alphanumerics in wiki/blog name
# # This file is part of Plinth. # # 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/>. # """ Forms for configuring ikiwiki """ from django import forms from django.utils.translation import ugettext_lazy as _ from django.core.validators import RegexValidator class IkiwikiCreateForm(forms.Form): """Form to create a wiki or blog.""" site_type = forms.ChoiceField( label=_('Type'), choices=[('wiki', 'Wiki'), ('blog', 'Blog')]) name = forms.CharField(label=_('Name'), validators=[RegexValidator(regex='^[a-zA-Z0-9]+$')]) admin_name = forms.CharField(label=_('Admin Account Name')) admin_password = forms.CharField( label=_('Admin Account Password'), widget=forms.PasswordInput())
# # This file is part of Plinth. # # 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/>. # """ Forms for configuring ikiwiki """ from django import forms from django.utils.translation import ugettext_lazy as _ class IkiwikiCreateForm(forms.Form): """Form to create a wiki or blog.""" site_type = forms.ChoiceField( label=_('Type'), choices=[('wiki', 'Wiki'), ('blog', 'Blog')]) name = forms.CharField(label=_('Name')) admin_name = forms.CharField(label=_('Admin Account Name')) admin_password = forms.CharField( label=_('Admin Account Password'), widget=forms.PasswordInput())
KULRICE-9047: Disable term lookup smoke test to avoid any server impact till fixed. git-svn-id: 2a5d2b5a02908a0c4ba7967b726d8c4198d1b9ed@37464 7a7aa7f6-c479-11dc-97e2-85a2497f191d
/** * Copyright 2005-2011 The Kuali Foundation * * Licensed under the Educational Community 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.opensource.org/licenses/ecl2.php * * 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 edu.samplu.mainmenu.test; import org.junit.Test; import edu.samplu.common.MainMenuLookupLegacyITBase; /** * tests that user 'admin' can display the Term lookup screen, search, * initiate an Term maintenance document via an edit action on the search results and * finally cancel the maintenance document * * @author Kuali Rice Team (rice.collab@kuali.org) */ public class TermLookUpLegacyIT extends MainMenuLookupLegacyITBase { @Override public void testLookUp() {} // no-op to avoid https://jira.kuali.org/browse/KULRICE-9047 messing up the server state @Override public String getLinkLocator() { return "Term Lookup"; } @Test public void lookupAssertions() throws Exception{ gotoMenuLinkLocator(); super.testTermLookUp(); } }
/** * Copyright 2005-2011 The Kuali Foundation * * Licensed under the Educational Community 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.opensource.org/licenses/ecl2.php * * 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 edu.samplu.mainmenu.test; import org.junit.Test; import edu.samplu.common.MainMenuLookupLegacyITBase; /** * tests that user 'admin' can display the Term lookup screen, search, * initiate an Term maintenance document via an edit action on the search results and * finally cancel the maintenance document * * @author Kuali Rice Team (rice.collab@kuali.org) */ public class TermLookUpLegacyIT extends MainMenuLookupLegacyITBase { @Override public String getLinkLocator() { return "Term Lookup"; } @Test public void lookupAssertions() throws Exception{ gotoMenuLinkLocator(); super.testTermLookUp(); } }
Send command in the child process
#!/usr/bin/env python # Auto-launching using this: export PROMPT_COMMAND='/Users/putilin/client.py "`fc -nl -1`"' import os import sys shell_pid = os.getppid() if os.fork() != 0: sys.exit() import requests import re assert len(sys.argv) == 2 history_output = sys.argv[1] m = re.match(r"[ ]*(\d+)[ ][ ](.*)", history_output) command_id = m.group(1) command_text = m.group(2) USERNAME = "eleweek" HOST = "histsync.herokuapp.com" API_KEY = "9b946c76-1688-4d3d-9b13-c4d25ef878ef" payload = {'api_key': API_KEY, 'command_text': command_text, "id": '{}${}'.format(shell_pid, command_id)} r = requests.post("http://{}/api/v0/user/{}/add_command".format(HOST, USERNAME), data=payload) r.raise_for_status()
#!/usr/bin/env python # Auto-launching using this: export PROMPT_COMMAND='/Users/putilin/client.py "`fc -nl -1`"' import requests import sys import os import re assert len(sys.argv) == 2 history_output = sys.argv[1] m = re.match(r"[ ]*(\d+)[ ][ ](.*)", history_output) command_id = m.group(1) command_text = m.group(2) USERNAME = "eleweek" HOST = "histsync.herokuapp.com" API_KEY = "61f33ca6-50d3-4eea-a924-e9b7b6f86ed4" payload = {'api_key': API_KEY, 'command_text': command_text, "id": '{}${}'.format(os.getppid(), command_id)} print payload r = requests.post("http://{}/api/v0/user/{}/add_command".format(HOST, USERNAME), data=payload) r.raise_for_status()
Change default utc_offset to account for DST
utils = { startsAtMomentWithOffset: function (game) { var offset = game.location.utc_offset; if (! Match.test(offset, UTCOffset)) { // XXX should account for DST here offset = -7; // Default to California } // UTC offsets returned by Google Places API, // which is the source of game.location.utc_offset, // differ in sign from what is expected by moment.js return moment(game.startsAt).zone(-offset); }, displayTime: function (game) { return utils.startsAtMomentWithOffset(game).format('ddd h:mma'); }, // Same-day-ness depends on the known timezone of the game, // not the timezone of the system executing this function. isToday: function (game) { var gameWhen = utils.startsAtMomentWithOffset(game); var now = utils.startsAtMomentWithOffset( // clone of game that starts now _.extend({startsAt: new Date()}, _.omit(game, 'startsAt')) ); return gameWhen.isSame(now, 'day'); }, // Markdown->HTML converter: new Showdown.converter() };
utils = { startsAtMomentWithOffset: function (game) { var offset = game.location.utc_offset; if (! Match.test(offset, UTCOffset)) { offset = -8; // Default to California } // UTC offsets returned by Google Places API, // which is the source of game.location.utc_offset, // differ in sign from what is expected by moment.js return moment(game.startsAt).zone(-offset); }, displayTime: function (game) { return utils.startsAtMomentWithOffset(game).format('ddd h:mma'); }, // Same-day-ness depends on the known timezone of the game, // not the timezone of the system executing this function. isToday: function (game) { var gameWhen = utils.startsAtMomentWithOffset(game); var now = utils.startsAtMomentWithOffset( // clone of game that starts now _.extend({startsAt: new Date()}, _.omit(game, 'startsAt')) ); return gameWhen.isSame(now, 'day'); }, // Markdown->HTML converter: new Showdown.converter() };
Read file as text not binary Reads the working PHIL file, but reading this as binary breaks the phil parsing as the data are a byte array on Python 3 - open as text seems to fix this - fixes #483
import os import sys import iotbx.phil import xia2.Handlers.Streams from xia2.Interfaces.ISPyB.ISPyBXmlHandler import ISPyBXmlHandler from xia2.Schema.XProject import XProject def ispyb_xml(xml_out): assert os.path.exists("xia2.json") assert os.path.exists("xia2.txt") assert os.path.exists("xia2-working.phil") command_line = "" for record in open("xia2.txt"): if record.startswith("Command line:"): command_line = record.replace("Command line:", "").strip() with open("xia2-working.phil", "r") as f: working_phil = iotbx.phil.parse(f.read()) xinfo = XProject.from_json(filename="xia2.json") crystals = xinfo.get_crystals() assert len(crystals) == 1 crystal = next(iter(crystals.values())) ispyb_hdl = ISPyBXmlHandler(xinfo) ispyb_hdl.add_xcrystal(crystal) ispyb_hdl.write_xml(xml_out, command_line, working_phil=working_phil) if __name__ == "__main__": xia2.Handlers.Streams.setup_logging() if len(sys.argv) >= 2: ispyb_xml(sys.argv[1]) else: ispyb_xml("ispyb.xml")
import os import sys import iotbx.phil import xia2.Handlers.Streams from xia2.Interfaces.ISPyB.ISPyBXmlHandler import ISPyBXmlHandler from xia2.Schema.XProject import XProject def ispyb_xml(xml_out): assert os.path.exists("xia2.json") assert os.path.exists("xia2.txt") assert os.path.exists("xia2-working.phil") command_line = "" for record in open("xia2.txt"): if record.startswith("Command line:"): command_line = record.replace("Command line:", "").strip() with open("xia2-working.phil", "rb") as f: working_phil = iotbx.phil.parse(f.read()) xinfo = XProject.from_json(filename="xia2.json") crystals = xinfo.get_crystals() assert len(crystals) == 1 crystal = next(iter(crystals.values())) ispyb_hdl = ISPyBXmlHandler(xinfo) ispyb_hdl.add_xcrystal(crystal) ispyb_hdl.write_xml(xml_out, command_line, working_phil=working_phil) if __name__ == "__main__": xia2.Handlers.Streams.setup_logging() if len(sys.argv) >= 2: ispyb_xml(sys.argv[1]) else: ispyb_xml("ispyb.xml")
Change capitalization to match the filesystem exactly.
import './utils/polyfills'; // Import polyfills for IE11 export App from './app'; export AppBar from './app_bar'; export Autocomplete from './autocomplete'; export Avatar from './avatar'; export Button from './button/Button'; export IconButton from './button/IconButton'; export * from './card'; export Checkbox from './checkbox'; export DatePicker from './date_picker'; export Dialog from './dialog'; export Drawer from './drawer'; export Dropdown from './dropdown'; export FontIcon from './font_icon'; export Form from './form'; export Input from './input'; export Link from './link'; export List from './list/List'; export ListItem from './list/ListItem'; export ListDivider from './list/ListDivider'; export ListCheckbox from './list/ListCheckbox'; export ListSubHeader from './list/ListSubheader'; export Menu from './menu/Menu'; export MenuItem from './menu/MenuItem'; export MenuDivider from './menu/MenuDivider'; export IconMenu from './menu/IconMenu'; export Navigation from './navigation'; export ProgressBar from './progress_bar'; export RadioGroup from './radio/RadioGroup'; export RadioButton from './radio/RadioButton'; export Ripple from './ripple'; export Slider from './slider'; export Snackbar from './snackbar'; export Switch from './switch'; export Table from './table'; export Tabs from './tabs/Tabs'; export Tab from './tabs/Tab'; export Tooltip from './tooltip'; export TimePicker from './time_picker';
import './utils/polyfills'; // Import polyfills for IE11 export App from './app'; export AppBar from './app_bar'; export Autocomplete from './autocomplete'; export Avatar from './avatar'; export Button from './button/Button'; export IconButton from './button/IconButton'; export * from './card'; export Checkbox from './checkbox'; export DatePicker from './date_picker'; export Dialog from './dialog'; export Drawer from './drawer'; export Dropdown from './dropdown'; export FontIcon from './font_icon'; export Form from './form'; export Input from './input'; export Link from './link'; export List from './list/List'; export ListItem from './list/ListItem'; export ListDivider from './list/ListDivider'; export ListCheckbox from './list/ListCheckbox'; export ListSubHeader from './list/ListSubHeader'; export Menu from './menu/Menu'; export MenuItem from './menu/MenuItem'; export MenuDivider from './menu/MenuDivider'; export IconMenu from './menu/IconMenu'; export Navigation from './navigation'; export ProgressBar from './progress_bar'; export RadioGroup from './radio/RadioGroup'; export RadioButton from './radio/RadioButton'; export Ripple from './ripple'; export Slider from './slider'; export Snackbar from './snackbar'; export Switch from './switch'; export Table from './table'; export Tabs from './tabs/Tabs'; export Tab from './tabs/Tab'; export Tooltip from './tooltip'; export TimePicker from './time_picker';
Implement equals, hashcode and row field
package javafx.scene.chart; /** * @author Adrian Healey <adrian.j.healey@gmail.com> */ public class SankeyNode { private String name; private double value = 0.0; private int column = 0; private int row = 0; public SankeyNode(String name) { this.name = name; } public String getName() { return name; } double getValue() { return value; } void setValue(double value) { this.value = value; } int getColumn() { return column; } void setColumn(int column) { this.column = column; } void moveRight() { this.column++; } int getRow() { return row; } void setRow(int row) { this.row = row; } void movDown() { this.row++; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; SankeyNode that = (SankeyNode) o; return name.equals(that.name); } @Override public int hashCode() { return name.hashCode(); } }
package javafx.scene.chart; /** * @author Adrian Healey <adrian.j.healey@gmail.com> */ public class SankeyNode { private String name; private double value = 0.0; private int column = 0; public SankeyNode(String name) { this.name = name; } public String getName() { return name; } double getValue() { return value; } void setValue(double value) { this.value = value; } int getColumn() { return column; } void setColumn(int column) { this.column = column; } void moveRight() { this.column++; } }
Terminate worker before every task start
import store from 'store'; import uuid from 'node-uuid'; import later from 'later'; let worker; function initDeviceID() { let deviceID = store.get('device_id'); if (!deviceID) { store.set('device_id', uuid.v4()); } } function setupWorker() { // var sched = later.parse.cron('1/1 * * * *'); var sched = later.parse.cron('0,30 * * * *'); later.setInterval(runWorker, sched); } function runWorker() { var deviceID = store.get('device_id'); if (typeof worker !== 'undefined') { worker.terminate(); } worker = new Worker('./js/worker.js'); worker.onmessage = (e) => { // TODO: update update records const { unreadChapters, comicID } = e.data; // console.log(unreadChapters.length); switch(window.PLATFORM) { case 'electron': // TODO: create native notification // var { ipcRenderer } = require('electron'); break; case 'chrome_extension': // TODO create chrome notification break; default: throw 'Unsupported Platform'; } }; // start worker worker.postMessage({deviceID}); } export function initializeApp({callback}) { initDeviceID(); setupWorker(); callback(); }
import store from 'store'; import uuid from 'node-uuid'; import later from 'later'; function initDeviceID() { let deviceID = store.get('device_id'); if (!deviceID) { store.set('device_id', uuid.v4()); } } function setupWorker() { // var sched = later.parse.cron('1/1 * * * *'); var sched = later.parse.cron('0,30 * * * *'); later.setInterval(runWorker, sched); } function runWorker() { var deviceID = store.get('device_id'); let worker = new Worker('./js/worker.js'); worker.onmessage = (e) => { // TODO: update update records const { unreadChapters, comicID } = e.data; // console.log(unreadChapters.length); switch(window.PLATFORM) { case 'electron': // TODO: create native notification // var { ipcRenderer } = require('electron'); break; case 'chrome_extension': // TODO create chrome notification break; default: throw 'Unsupported Platform'; } }; // start worker worker.postMessage({deviceID}); } export function initializeApp({callback}) { initDeviceID(); setupWorker(); callback(); }
MAke match checking function final
<?php namespace App\Chatbot\Commands; use Casperlaitw\LaravelFbMessenger\Contracts\BaseHandler; use Casperlaitw\LaravelFbMessenger\Messages\ReceiveMessage; abstract class Command { /* @var array 對應指令清單 */ public $commands = ['']; /* @var string 指令描述 */ public $description = ''; /** * 執行指令 * * @param BaseHandler $handler * @param ReceiveMessage $receiveMessage * @return mixed */ abstract public function run(BaseHandler $handler, ReceiveMessage $receiveMessage); /** * 檢查是否匹配指令 * * @param ReceiveMessage $receiveMessage * @return bool */ final public function match(ReceiveMessage $receiveMessage) { foreach ($this->commands as $command) { if (strcasecmp($receiveMessage->getMessage(), $command) == 0) { return true; } } return false; } }
<?php namespace App\Chatbot\Commands; use Casperlaitw\LaravelFbMessenger\Contracts\BaseHandler; use Casperlaitw\LaravelFbMessenger\Messages\ReceiveMessage; abstract class Command { /* @var array 對應指令清單 */ public $commands = ['']; /* @var string 指令描述 */ public $description = ''; /** * 執行指令 * * @param BaseHandler $handler * @param ReceiveMessage $receiveMessage * @return mixed */ abstract public function run(BaseHandler $handler, ReceiveMessage $receiveMessage); /** * 檢查是否匹配指令 * * @param ReceiveMessage $receiveMessage * @return bool */ public function match(ReceiveMessage $receiveMessage) { foreach ($this->commands as $command) { if (strcasecmp($receiveMessage->getMessage(), $command) == 0) { return true; } } return false; } }
Fix observation of reduced events
// Returns fragment of specified records 'use strict'; var aFrom = require('es5-ext/array/from') , uniq = require('es5-ext/array/#/uniq') , ensureString = require('es5-ext/object/validate-stringifiable-value') , ensureIterable = require('es5-ext/iterable/validate-object') , Set = require('es6-set') , deferred = require('deferred') , memoize = require('memoizee') , Fragment = require('data-fragment') , ensureStorage = require('dbjs-persistence/ensure-storage') , assimilateEvent = require('./lib/assimilate-driver-event'); module.exports = memoize(function (storage, ids) { var idsSet = new Set(ids) , fragment = new Fragment(); fragment.promise = deferred.map(ids, function (id) { return storage.getReduced(id)(function (data) { if (data) assimilateEvent(fragment, id, data); }); }); storage.on('update:reduced', function (event) { if (idsSet.has(event.id)) assimilateEvent(fragment, event.id, event.data); }); return fragment; }, { primitive: true, resolvers: [ensureStorage, function (ids) { return uniq.call(aFrom(ensureIterable(ids)).map(ensureString)).sort(); }] });
// Returns fragment of specified records 'use strict'; var aFrom = require('es5-ext/array/from') , uniq = require('es5-ext/array/#/uniq') , ensureString = require('es5-ext/object/validate-stringifiable-value') , ensureIterable = require('es5-ext/iterable/validate-object') , Set = require('es6-set') , deferred = require('deferred') , memoize = require('memoizee') , Fragment = require('data-fragment') , ensureStorage = require('dbjs-persistence/ensure-storage') , assimilateEvent = require('./lib/assimilate-driver-event'); module.exports = memoize(function (storage, ids) { var idsSet = new Set(ids) , fragment = new Fragment(); fragment.promise = deferred.map(ids, function (id) { return storage.getReduced(id)(function (data) { if (data) assimilateEvent(fragment, id, data); }); }); storage.on('update', function (event) { if (idsSet.has(event.id)) assimilateEvent(fragment, event.id, event.data); }); return fragment; }, { primitive: true, resolvers: [ensureStorage, function (ids) { return uniq.call(aFrom(ensureIterable(ids)).map(ensureString)).sort(); }] });
Replace npms with <: $lia_name :>
(function (env) { "use strict"; env.ddg_spice_<: $lia_name :> = function(api_result){ // Validate the response if (api_result.error) { return Spice.failed('<: $lia_name :>'); } // Render the response Spice.add({ id: "<: $lia_name :>", // Customize these properties name: "AnswerBar title", data: api_result, meta: { sourceName: "Example.com", sourceUrl: 'http://example.com/url/to/details/' + api_result.name }, templates: { group: 'your-template-groups', options: { content: Spice.<: $lia_name :>.content, moreAt: true } } }); }; }(this));
(function (env) { "use strict"; env.ddg_spice_npm = function(api_result){ // Validate the response if (api_result.error) { return Spice.failed('<: $lia_name :>'); } // Render the response Spice.add({ id: "<: $lia_name :>", // Customize these properties name: "AnswerBar title", data: api_result, meta: { sourceName: "Example.com", sourceUrl: 'http://example.com/url/to/details/' + api_result.name }, templates: { group: 'your-template-groups', options: { content: Spice.npm.content, moreAt: true } } }); }; }(this));
Load SVM pickle and print metrics
#!/usr/bin/env python """ Load a neural network model from a data frame """ import pickle import numpy as np import pandas as pd from lasagne import nonlinearities from lasagne.layers import DenseLayer from lasagne.layers import InputLayer from nolearn.lasagne import NeuralNet from sklearn.cross_validation import train_test_split from sklearn.grid_search import GridSearchCV NN_PICKLE = 'nn_data.pkl' SVM_PICKLE = 'svm_data.pkl' def results(): with open(NN_PICKLE, 'rb') as file: grid_search = pickle.load(file) net = pickle.load(file) print(grid_search.grid_scores_) print(grid_search.best_estimator_) print(grid_search.best_score_) print(grid_search.best_params_) grid_search.save_params_to('/tmp/grid_search.params') net.save_params_to('/tmp/net.params') with open(SVM_PICKLE, 'rb') as file: mean_abs = pickle.load(file) mean_sq = pickle.load(file) median_abs = pickle.load(file) r2 = pickle.load(file) print mean_abs, mean_sq, median_abs, r2
#!/usr/bin/env python """ Load a neural network model from a data frame """ import pickle import numpy as np import pandas as pd from lasagne import nonlinearities from lasagne.layers import DenseLayer from lasagne.layers import InputLayer from nolearn.lasagne import NeuralNet from sklearn.cross_validation import train_test_split from sklearn.grid_search import GridSearchCV PICKLE = 'data.pkl' def results(): with open(PICKLE, 'rb') as file: grid_search = pickle.load(file) net = pickle.load(file) print(grid_search.grid_scores_) print(grid_search.best_estimator_) print(grid_search.best_score_) print(grid_search.best_params_) net.save_params_to('/tmp/net.params')
Remove description for pingPong, leave tests for pingPongType and isPingPong
describe('pingPongType', function() { it("returns ping for a number that is divisible by 3", function() { expect(pingPongType(6)).to.equal("ping"); }); it("returns pong for a number that is divisible by 5", function() { expect(pingPongType(10)).to.equal("pong"); }); it("returns pingpong for a number that is divisible by 3 and 5", function() { expect(pingPongType(30)).to.equal("pingpong") }); }); describe('isPingPong', function() { it("returns pingPongType for a number divisible by 3, 5, or 15", function() { expect(isPingPong(6)).to.equal("ping"); }); it("returns false for a number not divisible by 3, 5, or 15", function() { expect(isPingPong(7)).to.equal(false); }); });
describe('pingPong', function() { it("is false for a number that is not divisible by 3 or 5", function() { expect(pingPong(7)).to.equal(false); }); it("will run pingPongType if isPingPong is true", function() { expect(pingPong(6)).to.equal("ping"); }); }); describe('pingPongType', function() { it("returns ping for a number that is divisible by 3", function() { expect(pingPongType(6)).to.equal("ping"); }); it("returns pong for a number that is divisible by 5", function() { expect(pingPongType(10)).to.equal("pong"); }); it("returns pingpong for a number that is divisible by 3 and 5", function() { expect(pingPongType(30)).to.equal("pingpong") }); }); describe('isPingPong', function() { it("returns true for a number divisible by 3, 5, or 15", function() { expect(isPingPong(6)).to.equal(true); }); it("returns false for a number not divisible by 3, 5, or 15", function() { expect(isPingPong(7)).to.equal(false); }); });
Mark crate as a namepsace package in the metadata
#!/usr/bin/env python from setuptools import setup, find_packages install_requires = [ "bleach", "jinja2", "celery-haystack", "Django>=1.4", "django-celery", "django-haystack", "django-jsonfield", "django-model-utils", "django-tastypie", "docutils", "isoweek", "lxml", "saved_searches", ] setup( name="crate.web", version="0.1", author="Donald Stufft", author_email="donald@crate.io", url="https://github.com/crateio/crate.web", description="crate.web is a Django app that provides the building blocks to build a Package Index Server.", license=open("LICENSE").read(), namespace_packages=["crate"], packages=find_packages(exclude=("tests",)), package_data={'': ['LICENSE', 'NOTICE']}, include_package_data=True, install_requires=install_requires, zip_safe=False, classifiers=[ "Development Status :: 4 - Beta", "Environment :: Web Environment", "Framework :: Django", "Intended Audience :: Developers", "License :: OSI Approved :: BSD License", "Programming Language :: Python :: 2.7", "Operating System :: OS Independent", ], )
#!/usr/bin/env python from setuptools import setup, find_packages install_requires = [ "bleach", "jinja2", "celery-haystack", "Django>=1.4", "django-celery", "django-haystack", "django-jsonfield", "django-model-utils", "django-tastypie", "docutils", "isoweek", "lxml", "saved_searches", ] setup( name="crate.web", version="0.1", author="Donald Stufft", author_email="donald@crate.io", url="https://github.com/crateio/crate.web", description="crate.web is a Django app that provides the building blocks to build a Package Index Server.", license=open("LICENSE").read(), packages=find_packages(exclude=("tests",)), package_data={'': ['LICENSE', 'NOTICE']}, include_package_data=True, install_requires=install_requires, zip_safe=False, classifiers=[ "Development Status :: 4 - Beta", "Environment :: Web Environment", "Framework :: Django", "Intended Audience :: Developers", "License :: OSI Approved :: BSD License", "Programming Language :: Python :: 2.7", "Operating System :: OS Independent", ], )
Make class test-class name more specific ... to make room for more client tests.
import unittest from IPython.parallel import Client from distarray.client import DistArrayContext class TestDistArrayContext(unittest.TestCase): def setUp(self): self.client = Client() self.dv = self.client[:] def test_create_DAC(self): '''Can we create a plain vanilla context?''' dac = DistArrayContext(self.dv) self.assertIs(dac.view, self.dv) def test_create_DAC_with_targets(self): '''Can we create a context with a subset of engines?''' dac = DistArrayContext(self.dv, targets=[0, 1]) self.assertIs(dac.view, self.dv) if __name__ == '__main__': unittest.main(verbosity=2)
import unittest from IPython.parallel import Client from distarray.client import DistArrayContext class TestClient(unittest.TestCase): def setUp(self): self.client = Client() self.dv = self.client[:] def testCreateDAC(self): '''Can we create a plain vanilla context?''' dac = DistArrayContext(self.dv) self.assertIs(dac.view, self.dv) def testCreateDACwithTargets(self): '''Can we create a context with a subset of engines?''' dac = DistArrayContext(self.dv, targets=[0, 1]) self.assertIs(dac.view, self.dv) if __name__ == '__main__': unittest.main(verbosity=2)
Remove environment variables having too general names
package shell import ( "github.com/codegangsta/cli" "strings" ) func SetUp() cli.Command { cmd := cli.Command{ Name: "shell", Usage: "BQL shell", Description: "shell command launches an interactive shell for BQL", Action: Launch, } cmd.Flags = []cli.Flag{ cli.StringFlag{ Name: "uri", Value: "http://localhost:8090/", Usage: "target URI to launch", }, cli.StringFlag{ Name: "version,v", Value: "v1", Usage: "SenserBee API version", }, } return cmd } // Launch SensorBee's command line client tool. func Launch(c *cli.Context) { host := c.String("uri") // TODO: validate URI if !strings.HasSuffix(host, "/") { host += "/" } uri := host + "api/" + c.String("version") cmds := []Command{} for _, c := range NewTopologiesCommands() { cmds = append(cmds, c) } for _, c := range NewFileLoadCommands() { cmds = append(cmds, c) } app := SetUpCommands(cmds) app.Run(uri) }
package shell import ( "github.com/codegangsta/cli" "strings" ) func SetUp() cli.Command { cmd := cli.Command{ Name: "shell", Usage: "BQL shell", Action: Launch, } cmd.Flags = []cli.Flag{ cli.StringFlag{ Name: "uri", Value: "http://localhost:8090/api", Usage: "target URI to launch", EnvVar: "URI", }, cli.StringFlag{ Name: "version,v", Value: "v1", Usage: "SenserBee API version", EnvVar: "VERSION", }, } return cmd } // Launch SensorBee's command line client tool. func Launch(c *cli.Context) { host := c.String("uri") if !strings.HasSuffix(host, "/") { host += "/" } uri := host + c.String("version") cmds := []Command{} for _, c := range NewTopologiesCommands() { cmds = append(cmds, c) } for _, c := range NewFileLoadCommands() { cmds = append(cmds, c) } app := SetUpCommands(cmds) app.Run(uri) }
Rename user_id to id parameter
'use strict'; /** * Module dependencies */ import * as mongo from 'mongodb'; import User from '../../models/user'; import serialize from '../../serializers/user'; /** * Show a user * * @param {Object} params * @param {Object} reply * @param {Object} me * @return {void} */ module.exports = async (params, reply, me) => { // Init 'id' parameter let userId = params.id; if (userId === undefined || userId === null || userId === '') { userId = null; } // Init 'username' parameter let username = params.username; if (username === undefined || username === null || username === '') { username = null; } if (userId === null && username === null) { return reply(400, 'id or username is required', 'EMPTY_QUERY'); } // Lookup user const user = userId !== null ? await User.findOne({ _id: new mongo.ObjectID(userId) }) : await User.findOne({ username }); if (user === null) { return reply(404, 'user not found'); } // Send response reply(await serialize(user, me)); };
'use strict'; /** * Module dependencies */ import * as mongo from 'mongodb'; import User from '../../models/user'; import serialize from '../../serializers/user'; /** * Show a user * * @param {Object} params * @param {Object} reply * @param {Object} me * @return {void} */ module.exports = async (params, reply, me) => { // Init 'user_id' parameter let userId = params.user_id; if (userId === undefined || userId === null || userId === '') { userId = null; } // Init 'username' parameter let username = params.username; if (username === undefined || username === null || username === '') { username = null; } if (userId === null && username === null) { return reply(400, 'user_id or username is required', 'EMPTY_QUERY'); } // Lookup user const user = userId !== null ? await User.findOne({ _id: new mongo.ObjectID(userId) }) : await User.findOne({ username }); if (user === null) { return reply(404, 'user not found'); } // Send response reply(await serialize(user, me)); };
Replace use of Spring's ClassUtils
/* * This file is part of Bisq. * * Bisq 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. * * Bisq 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 Bisq. If not, see <http://www.gnu.org/licenses/>. */ package bisq.desktop.common.view; public class DefaultPathConvention implements FxmlView.PathConvention { /** * Convert a '.'-based fully-qualified name of {@code viewClass} to a '/'-based * resource path suffixed with ".fxml". */ @Override public String apply(Class<? extends View> viewClass) { return viewClass.getName().replace('.', '/').concat(".fxml"); } }
/* * This file is part of Bisq. * * Bisq 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. * * Bisq 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 Bisq. If not, see <http://www.gnu.org/licenses/>. */ package bisq.desktop.common.view; import org.springframework.util.ClassUtils; public class DefaultPathConvention implements FxmlView.PathConvention { @Override public String apply(Class<? extends View> viewClass) { return ClassUtils.convertClassNameToResourcePath(viewClass.getName()).concat(".fxml"); } }
Remove stacktrace when adding unknown commands args
package com.tmitim.twittercli; import com.github.rvesse.airline.annotations.Cli; import com.github.rvesse.airline.help.Help; import com.github.rvesse.airline.parser.errors.ParseArgumentsUnexpectedException; import com.tmitim.twittercli.commands.DirectMessage; import com.tmitim.twittercli.commands.Location; import com.tmitim.twittercli.commands.TimeLine; import com.tmitim.twittercli.commands.Trend; import com.tmitim.twittercli.commands.Tweet; import com.tmitim.twittercli.commands.Search; @Cli( name = "twitter", description = "Provides a basic example CLI", defaultCommand = Help.class, commands = { Tweet.class, TimeLine.class, Location.class, Trend.class, Search.class, DirectMessage.class, Help.class } ) public class TwitterCli { public static void main(String[] args) { com.github.rvesse.airline.Cli<Runnable> cli = new com.github.rvesse.airline.Cli<>(TwitterCli.class); try { Runnable cmd = cli.parse(args); cmd.run(); } catch (ParseArgumentsUnexpectedException e) { System.out.println(e.getMessage()); } } }
package com.tmitim.twittercli; import com.github.rvesse.airline.annotations.Cli; import com.github.rvesse.airline.help.Help; import com.tmitim.twittercli.commands.DirectMessage; import com.tmitim.twittercli.commands.Location; import com.tmitim.twittercli.commands.TimeLine; import com.tmitim.twittercli.commands.Trend; import com.tmitim.twittercli.commands.Tweet; import com.tmitim.twittercli.commands.Search; @Cli( name = "twitter", description = "Provides a basic example CLI", defaultCommand = Help.class, commands = { Tweet.class, TimeLine.class, Location.class, Trend.class, Search.class, DirectMessage.class, Help.class } ) public class TwitterCli { public static void main(String[] args) { com.github.rvesse.airline.Cli<Runnable> cli = new com.github.rvesse.airline.Cli<>(TwitterCli.class); Runnable cmd = cli.parse(args); cmd.run(); } }
Remove enum and add absl-py. PiperOrigin-RevId: 256969582
# Copyright 2019 The Empirical Calibration Authors. # # 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 # # https://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. # ============================================================================ """Setup for empirical calibration package.""" from setuptools import find_packages from setuptools import setup setup( name='empirical_calibration', version='0.1', description='Package for empirical calibration', author='Google LLC', author_email='no-reply@google.com', url='https://github.com/google/empirical_calibration', license='Apache 2.0', packages=find_packages(), install_requires=[ 'absl-py', 'numpy >= 1.11.1', 'pandas', 'patsy', 'scipy', 'six', 'sklearn', ], )
# Copyright 2019 The Empirical Calibration Authors. # # 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 # # https://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. # ============================================================================ """Setup for empirical calibration package.""" from setuptools import find_packages from setuptools import setup setup( name='empirical_calibration', version='0.1', description='Package for empirical calibration', author='Google LLC', author_email='no-reply@google.com', url='https://github.com/google/empirical_calibration', license='Apache 2.0', packages=find_packages(), install_requires=[ 'enum', 'numpy >= 1.11.1', 'pandas', 'patsy', 'scipy', 'six', 'sklearn', 'typing', ], )
Edit user initial commit for userService
angular.module('services') .service('userService',['$q','config','storageService','$http',userService]); function userService($q,config,storageService,$http) { var service = {}; service.get = get; service.one = one; service.update = update; return service; function one(userId) { var deferred = $q.defer(); $http.get(config.apiEndPoint + '/users/' + userId).then(function(response) { deferred.resolve(response.data); },function(){ deferred.resolve({}); }); return deferred.promise; } function get(userId) { var deferred = $q.defer(), query = config.apiEndPoint + '/users'; if(userId) { query += '?filter=' + userId; } $http.get(query).then(function(response) { deferred.resolve(response.data); },function(){ deferred.resolve({}); }); return deferred.promise; } function update(user) { var deferred = $q.defer(), query = config.apiEndPoint + '/users/' + user._id; $http.put(query,user).then(function(data){ deferred.resolve(data); },function(err){ deferred.reject(err) }); return deferred.promise; } };
angular.module('services') .service('userService',['$q','config','storageService','$http',userService]); function userService($q,config,storageService,$http) { var service = {}; service.get = get; service.one = one; return service; function one(userId) { var deferred = $q.defer(); $http.get(config.apiEndPoint + '/users/' + userId).then(function(response) { deferred.resolve(response.data); },function(){ deferred.resolve({}); }); return deferred.promise; } function get(userId) { var deferred = $q.defer(), query = config.apiEndPoint + '/users'; if(userId) { query += '?filter=' + userId; } $http.get(query).then(function(response) { deferred.resolve(response.data); },function(){ deferred.resolve({}); }); return deferred.promise; } };
Fix ESLint error thrown due to infinite scrolling tweaks
var approachingBottomOfPage, loadNextPageAt, nextPage, nextPageFnRunning, viewMore, ready, checkAndLoad; nextPageFnRunning = false; loadNextPageAt = 3000; approachingBottomOfPage = function() { return $(window).scrollTop() > $(document).height() - $(window).height() - loadNextPageAt; }; nextPage = function() { var loadingMore, url; viewMore = $('#view-more'); loadingMore = $('#loading-more'); url = viewMore.find('a').attr('href'); if (nextPageFnRunning || !url) { return; } viewMore.hide(); loadingMore.show(); nextPageFnRunning = true; return $.ajax({ url: url, method: 'GET', dataType: 'script' }).always(function() { nextPageFnRunning = false; viewMore.show(); return loadingMore.hide(); }); }; // Checks to see if we are close to the bottom of the page and if we are load more measures checkAndLoad = function() { if (approachingBottomOfPage()) { return nextPage(); } }; ready = function() { viewMore = $('#view-more'); // Call checkAndLoad now and when the page scrolls checkAndLoad(); $(window).on('scroll', checkAndLoad); viewMore.find('a').unbind('click').click(function(e) { nextPage(); return e.preventDefault(); }); } $(document).ready(ready); $(document).on('page:load', ready);
var approachingBottomOfPage, loadNextPageAt, nextPage, nextPageFnRunning, viewMore, ready; nextPageFnRunning = false; loadNextPageAt = 3000; approachingBottomOfPage = function() { return $(window).scrollTop() > $(document).height() - $(window).height() - loadNextPageAt; }; nextPage = function() { var loadingMore, url; viewMore = $('#view-more'); loadingMore = $('#loading-more'); url = viewMore.find('a').attr('href'); if (nextPageFnRunning || !url) { return; } viewMore.hide(); loadingMore.show(); nextPageFnRunning = true; return $.ajax({ url: url, method: 'GET', dataType: 'script' }).always(function() { nextPageFnRunning = false; viewMore.show(); return loadingMore.hide(); }); }; // Checks to see if we are close to the bottom of the page and if we are load more measures checkAndLoad = function() { if (approachingBottomOfPage()) { return nextPage(); } }; ready = function() { viewMore = $('#view-more'); // Call checkAndLoad now and when the page scrolls checkAndLoad(); $(window).on('scroll', checkAndLoad); viewMore.find('a').unbind('click').click(function(e) { nextPage(); return e.preventDefault(); }); } $(document).ready(ready); $(document).on('page:load', ready);
Update password state after clear the mod
function solvePasswords() { $(".js-mod-passwords .js-mod-passwords-word").each(function() { wordOfInput = $(this).attr('js-data-word'); arrayOfWordInput = wordOfInput.split(''); compareArray = []; for (var i = 0; i < arrayOfWordInput.length; i++) { compareArray.push(compareWithInput(arrayOfWordInput[i], i)); }; if (compareArray.indexOf('found') > -1 && compareArray.indexOf('not-found') == -1) { $(this).removeClass('js-word-inactive'); $(this).addClass('js-word-active'); } else { $(this).removeClass('js-word-active'); $(this).addClass('js-word-inactive'); } }); } function compareWithInput(char, inputIndex) { var currentInputValArray = $('.js-mod-passwords .js-mod-passwords-input:eq('+inputIndex+')').val().split(''); if (currentInputValArray.length == 0) { var result = 'empty' } else if (currentInputValArray.indexOf(char) > -1) { var result = 'found' } else { var result = 'not-found' } return result; } function clearPasswords() { $('.js-mod-passwords .js-mod-passwords-input').val(''); solvePasswords(); } $('.js-mod-passwords .js-mod-passwords-input').keyup(function(){ solvePasswords(); });
function solvePasswords() { $(".js-mod-passwords .js-mod-passwords-word").each(function() { wordOfInput = $(this).attr('js-data-word'); arrayOfWordInput = wordOfInput.split(''); compareArray = []; for (var i = 0; i < arrayOfWordInput.length; i++) { compareArray.push(compareWithInput(arrayOfWordInput[i], i)); }; if (compareArray.indexOf('found') > -1 && compareArray.indexOf('not-found') == -1) { $(this).removeClass('js-word-inactive'); $(this).addClass('js-word-active'); } else { $(this).removeClass('js-word-active'); $(this).addClass('js-word-inactive'); } }); } function compareWithInput(char, inputIndex) { var currentInputValArray = $('.js-mod-passwords .js-mod-passwords-input:eq('+inputIndex+')').val().split(''); if (currentInputValArray.length == 0) { var result = 'empty' } else if (currentInputValArray.indexOf(char) > -1) { var result = 'found' } else { var result = 'not-found' } return result; } function clearPasswords() { $('.js-mod-passwords .js-mod-passwords-input').val(''); } $('.js-mod-passwords .js-mod-passwords-input').keyup(function(){ solvePasswords(); });
Fix bug with currency symbol
<?php namespace Pixiu\Commerce\Classes; use Pixiu\Commerce\Models\CommerceSettings; class CurrencyHandler { public $currencySymbol; public $decimalSymbol; public $format; /** * CurrencyHandler constructor. * @param $currencySymbol * @param $decimalSymbol * @param $format */ public function __construct() { $this->currencySymbol = CommerceSettings::get('currency'); $this->decimalSymbol = CommerceSettings::get('decimalSymbol'); $this->format = "%n %s"; } public function getValueFromInput($input) : int { return (int) str_replace(' ', '', str_replace($this->decimalSymbol, '', substr($input, 0, -(strlen($this->currencySymbol)+1)))); } public function getValueForInput($value) : float { return ($value / 100); } }
<?php namespace Pixiu\Commerce\Classes; use Pixiu\Commerce\Models\CommerceSettings; class CurrencyHandler { public $currencySymbol; public $decimalSymbol; public $format; /** * CurrencyHandler constructor. * @param $currencySymbol * @param $decimalSymbol * @param $format */ public function __construct() { $this->currencySymbol = CommerceSettings::get('currency'); $this->decimalSymbol = CommerceSettings::get('decimalSymbol'); $this->format = "%n %s"; } public function getValueFromInput($input) : int { return (int) str_replace(' ', '', str_replace($this->decimalSymbol, '', substr($input, 0, -3))); } public function getValueForInput($value) : float { return ($value / 100); } }
Revert "Add ZoneName to FixtureVM" This reverts commit 90860c6650ef70608e6a83ffd9e09e94cfe7d5c0.
package main import ( "github.com/BytemarkHosting/bytemark-client/lib" "github.com/BytemarkHosting/bytemark-client/mocks" "github.com/urfave/cli" ) var defVM lib.VirtualMachineName var defGroup lib.GroupName func baseTestSetup() (config *mocks.Config, client *mocks.Client) { config = new(mocks.Config) client = new(mocks.Client) global.Client = client global.Config = config baseAppSetup() return } func traverseAllCommands(cmds []cli.Command, fn func(cli.Command)) { if cmds == nil { return } for _, c := range cmds { fn(c) traverseAllCommands(c.Subcommands, fn) } } func getFixtureVM() lib.VirtualMachine { return lib.VirtualMachine{ Name: "test-server", Hostname: "test-server.test-group", GroupID: 1, } } func getFixtureGroup() lib.Group { vms := make([]*lib.VirtualMachine, 1, 1) vm := getFixtureVM() vms[0] = &vm return lib.Group{ Name: "test-group", VirtualMachines: vms, } }
package main import ( "github.com/BytemarkHosting/bytemark-client/lib" "github.com/BytemarkHosting/bytemark-client/mocks" "github.com/urfave/cli" ) var defVM lib.VirtualMachineName var defGroup lib.GroupName func baseTestSetup() (config *mocks.Config, client *mocks.Client) { config = new(mocks.Config) client = new(mocks.Client) global.Client = client global.Config = config baseAppSetup() return } func traverseAllCommands(cmds []cli.Command, fn func(cli.Command)) { if cmds == nil { return } for _, c := range cmds { fn(c) traverseAllCommands(c.Subcommands, fn) } } func getFixtureVM() lib.VirtualMachine { return lib.VirtualMachine{ Name: "test-server", Hostname: "test-server.test-group", GroupID: 1, ZoneName: "test-zone", } } func getFixtureGroup() lib.Group { vms := make([]*lib.VirtualMachine, 1, 1) vm := getFixtureVM() vms[0] = &vm return lib.Group{ Name: "test-group", VirtualMachines: vms, } }
Check if a cube exists on disk.
import os import json from regenesis.core import app def cube_path(cube_name, ext): return os.path.join( app.config.get('DATA_DIRECTORY'), cube_name + '.' + ext ) def exists_raw(cube_name): return os.path.isfile(cube_path(cube_name, 'raw')) def store_cube_raw(cube_name, cube_data): fh = open(cube_path(cube_name, 'raw'), 'wb') fh.write(cube_data.encode('utf-8')) fh.close() def load_cube_raw(cube_name): fh = open(cube_path(cube_name, 'raw'), 'rb') data = fh.read().decode('utf-8') fh.close() return data def dump_cube_json(cube): fh = open(cube_path(cube.name, 'json'), 'wb') json.dump(cube, fh, cls=JSONEncoder, indent=2) fh.close()
import os import json from regenesis.core import app def cube_path(cube_name, ext): return os.path.join( app.config.get('DATA_DIRECTORY'), cube_name + '.' + ext ) def store_cube_raw(cube_name, cube_data): fh = open(cube_path(cube_name, 'raw'), 'wb') fh.write(cube_data.encode('utf-8')) fh.close() def load_cube_raw(cube_name): fh = open(cube_path(cube_name, 'raw'), 'rb') data = fh.read().decode('utf-8') fh.close() return data def dump_cube_json(cube): fh = open(cube_path(cube.name, 'json'), 'wb') json.dump(cube, fh, cls=JSONEncoder, indent=2) fh.close()
Remove unused imports in interpeter.
# -*- coding: utf-8 -*- from .evaluator import evaluate from .parser import parse, unparse, parse_multiple from .types import Environment def interpret(source, env=None): """ Interpret a DIY Lang program statement Accepts a program statement as a string, interprets it, and then returns the resulting DIY Lang expression as string. """ if env is None: env = Environment() return unparse(evaluate(parse(source), env)) def interpret_file(filename, env=None): """ Interpret a DIY Lang file Accepts the name of a DIY Lang file containing a series of statements. Returns the value of the last expression of the file. """ if env is None: env = Environment() with open(filename, 'r') as sourcefile: source = "".join(sourcefile.readlines()) asts = parse_multiple(source) results = [evaluate(ast, env) for ast in asts] return unparse(results[-1])
# -*- coding: utf-8 -*- from os.path import dirname, join from .evaluator import evaluate from .parser import parse, unparse, parse_multiple from .types import Environment def interpret(source, env=None): """ Interpret a DIY Lang program statement Accepts a program statement as a string, interprets it, and then returns the resulting DIY Lang expression as string. """ if env is None: env = Environment() return unparse(evaluate(parse(source), env)) def interpret_file(filename, env=None): """ Interpret a DIY Lang file Accepts the name of a DIY Lang file containing a series of statements. Returns the value of the last expression of the file. """ if env is None: env = Environment() with open(filename, 'r') as sourcefile: source = "".join(sourcefile.readlines()) asts = parse_multiple(source) results = [evaluate(ast, env) for ast in asts] return unparse(results[-1])
Throw IllegalStateException if the Metric service is not available
/* * Copyright 2014 WSO2 Inc. (http://wso2.org) * * 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 org.wso2.carbon.metrics.manager.internal; import org.wso2.carbon.metrics.manager.MetricService; /** * Holding references to the OSGi services */ public class ServiceReferenceHolder { private static final ServiceReferenceHolder INSTANCE = new ServiceReferenceHolder(); private MetricService metricService; public static ServiceReferenceHolder getInstance() { return INSTANCE; } private ServiceReferenceHolder() { } public void setMetricService(MetricService metricService) { this.metricService = metricService; } public MetricService getMetricService() { if (metricService == null) { throw new IllegalStateException("Metric Service is not available!"); } return metricService; } }
/* * Copyright 2014 WSO2 Inc. (http://wso2.org) * * 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 org.wso2.carbon.metrics.manager.internal; import org.wso2.carbon.metrics.manager.MetricService; /** * Holding references to the OSGi services */ public class ServiceReferenceHolder { private static final ServiceReferenceHolder INSTANCE = new ServiceReferenceHolder(); private MetricService metricService; public static ServiceReferenceHolder getInstance() { return INSTANCE; } private ServiceReferenceHolder() { } public void setMetricService(MetricService metricService) { this.metricService = metricService; } public MetricService getMetricService() { return metricService; } }
Update fastapp version to 0.7.8
__version__ = "0.7.8" import os from django.core.exceptions import ImproperlyConfigured # load plugins from django.conf import settings try: plugins_config = getattr(settings, "FASTAPP_PLUGINS_CONFIG", {}) plugins = plugins_config.keys() plugins = plugins + getattr(settings, "FASTAPP_PLUGINS", []) for plugin in list(set(plugins)): def my_import(name): # from http://effbot.org/zone/import-string.htm m = __import__(name) for n in name.split(".")[1:]: m = getattr(m, n) return m amod = my_import(plugin) except ImproperlyConfigured, e: print e
__version__ = "0.7.7" import os from django.core.exceptions import ImproperlyConfigured # load plugins from django.conf import settings try: plugins_config = getattr(settings, "FASTAPP_PLUGINS_CONFIG", {}) plugins = plugins_config.keys() plugins = plugins + getattr(settings, "FASTAPP_PLUGINS", []) for plugin in list(set(plugins)): def my_import(name): # from http://effbot.org/zone/import-string.htm m = __import__(name) for n in name.split(".")[1:]: m = getattr(m, n) return m amod = my_import(plugin) except ImproperlyConfigured, e: print e
Update "The Order of the Stick" after site change
from comics.aggregator.crawler import CrawlerBase, CrawlerImage from comics.core.comic_data import ComicDataBase class ComicData(ComicDataBase): name = "The Order of the Stick" language = "en" url = "http://www.giantitp.com/" start_date = "2003-09-30" rights = "Rich Burlew" class Crawler(CrawlerBase): history_capable_days = 10 time_zone = "US/Eastern" headers = {"User-Agent": "Mozilla/5.0"} def crawl(self, pub_date): feed = self.parse_feed("http://www.giantitp.com/comics/oots.rss") if len(feed.all()): entry = feed.all()[0] page = self.parse_page(entry.link) url = page.src('img[src*="/comics/oots/"]') title = entry.title return CrawlerImage(url, title)
from comics.aggregator.crawler import CrawlerBase, CrawlerImage from comics.core.comic_data import ComicDataBase class ComicData(ComicDataBase): name = "The Order of the Stick" language = "en" url = "http://www.giantitp.com/" start_date = "2003-09-30" rights = "Rich Burlew" class Crawler(CrawlerBase): history_capable_days = 1 time_zone = "US/Eastern" def crawl(self, pub_date): feed = self.parse_feed("http://www.giantitp.com/comics/oots.rss") if len(feed.all()): entry = feed.all()[0] page = self.parse_page(entry.link) url = page.src('img[src*="/comics/images/"]') title = entry.title return CrawlerImage(url, title)
Read binding interface and MD file via flags.
package main import ( "flag" "fmt" "io/ioutil" "log" "net/http" utils "github.com/shurcooL/github_flavored_markdown" ) var ( file string bind string ) func init() { flag.StringVar(&bind, "bind", ":8080", "interface to bind to, eg. 0.0.0.0:8080") flag.StringVar(&file, "file", "README.md", "file to render on web interface") } func main() { flag.Parse() http.HandleFunc("/", Handler) log.Printf("Listening on port %s\n", bind) log.Fatal(http.ListenAndServe(bind, nil)) } func Handler(res http.ResponseWriter, req *http.Request) { readme, err := GetReadme() if err != nil { fmt.Fprintf(res, "Something went wrong:\n%s", err) return } fmt.Fprintf(res, string(readme)) } func GetReadme() ([]byte, error) { b, err := ioutil.ReadFile(file) if err != nil { return nil, err } return utils.Markdown(b), nil }
package main import ( "fmt" "io/ioutil" "log" "net/http" utils "github.com/shurcooL/github_flavored_markdown" ) func main() { http.HandleFunc("/", Handler) log.Printf("Listening on port %d\n", 8080) log.Fatal(http.ListenAndServe(":8080", nil)) } func Handler(res http.ResponseWriter, req *http.Request) { readme, err := GetReadme() if err != nil { fmt.Fprintf(res, "Something went wrong:\n%s", err) return } fmt.Fprintf(res, string(readme)) } func GetReadme() ([]byte, error) { b, err := ioutil.ReadFile("./README.md") if err != nil { return nil, err } return utils.Markdown(b), nil }
Add excluded artist ids to suggested artist arguments
import { GraphQLBoolean, GraphQLString, GraphQLInt, GraphQLList } from "graphql" export const SuggestedArtistsArgs = { artist_id: { type: GraphQLString, description: "The slug or ID of an artist", }, exclude_artists_without_forsale_artworks: { type: GraphQLBoolean, description: "Exclude artists without for sale works", }, exclude_artists_without_artworks: { type: GraphQLBoolean, description: "Exclude artists without any artworks", }, exclude_followed_artists: { type: GraphQLBoolean, description: "Exclude artists the user already follows", }, exclude_artist_ids: { type: new GraphQLList(GraphQLString), description: "Exclude these ids from results, may result in all artists being excluded.", }, page: { type: GraphQLInt, description: "Pagination, need I say more?", }, size: { type: GraphQLInt, description: "Amount of artists to return", }, }
import { GraphQLBoolean, GraphQLString, GraphQLInt } from "graphql" export const SuggestedArtistsArgs = { artist_id: { type: GraphQLString, description: "The slug or ID of an artist", }, exclude_artists_without_forsale_artworks: { type: GraphQLBoolean, description: "Exclude artists without for sale works", }, exclude_artists_without_artworks: { type: GraphQLBoolean, description: "Exclude artists without any artworks", }, exclude_followed_artists: { type: GraphQLBoolean, description: "Exclude artists the user already follows", }, page: { type: GraphQLInt, description: "Pagination, need I say more?", }, size: { type: GraphQLInt, description: "Amount of artists to return", }, }
Add slash to service detail route
import Router from 'react-router'; let Route = Router.Route; import ServiceOverlay from '../components/ServiceOverlay'; import ServicesPage from '../pages/ServicesPage'; let servicesRoutes = { type: Route, name: 'services', path: 'services/?', handler: ServicesPage, children: [ { type: Route, name: 'services-detail', path: ':id/?' }, { type: Route, name: 'service-ui', path: 'ui/:serviceName/?', handler: ServiceOverlay }, { type: Route, name: 'services-panel', path: 'service-detail/:serviceName/?' }, { type: Route, name: 'services-task-panel', path: 'task-detail/:taskID/?' } ] }; module.exports = servicesRoutes;
import Router from 'react-router'; let Route = Router.Route; import ServiceOverlay from '../components/ServiceOverlay'; import ServicesPage from '../pages/ServicesPage'; let servicesRoutes = { type: Route, name: 'services', path: 'services/?', handler: ServicesPage, children: [ { type: Route, name: 'services-detail', path: ':id' }, { type: Route, name: 'service-ui', path: 'ui/:serviceName/?', handler: ServiceOverlay }, { type: Route, name: 'services-panel', path: 'service-detail/:serviceName/?' }, { type: Route, name: 'services-task-panel', path: 'task-detail/:taskID/?' } ] }; module.exports = servicesRoutes;
Add the GAE application version to the tags
package net.kencochrane.raven.appengine.event.helper; import com.google.appengine.api.utils.SystemProperty; import com.google.apphosting.api.ApiProxy; import net.kencochrane.raven.event.EventBuilder; import net.kencochrane.raven.event.helper.EventBuilderHelper; /** * EventBuildHelper defining Google App Engine specific properties (hostname). */ public class AppEngineEventBuilderHelper implements EventBuilderHelper { /** * Property used internally by GAE to define the hostname. * * @see <a href="https://developers.google.com/appengine/docs/java/appidentity/">GAE: App Identity Java API</a> */ private static final String CURRENT_VERSION_HOSTNAME_PROPERTY = "com.google.appengine.runtime.default_version_hostname"; @Override public void helpBuildingEvent(EventBuilder eventBuilder) { ApiProxy.Environment env = ApiProxy.getCurrentEnvironment(); // Set the hostname to the actual application hostname eventBuilder.setServerName((String) env.getAttributes().get(CURRENT_VERSION_HOSTNAME_PROPERTY)); eventBuilder.addTag("GAE Application Version", SystemProperty.applicationVersion.get()); } }
package net.kencochrane.raven.appengine.event.helper; import com.google.apphosting.api.ApiProxy; import net.kencochrane.raven.event.EventBuilder; import net.kencochrane.raven.event.helper.EventBuilderHelper; /** * EventBuildHelper defining Google App Engine specific properties (hostname). */ public class AppEngineEventBuilderHelper implements EventBuilderHelper { /** * Property used internally by GAE to define the hostname. * * @see <a href="https://developers.google.com/appengine/docs/java/appidentity/">GAE: App Identity Java API</a> */ private static final String CURRENT_VERSION_HOSTNAME_PROPERTY = "com.google.appengine.runtime.default_version_hostname"; @Override public void helpBuildingEvent(EventBuilder eventBuilder) { ApiProxy.Environment env = ApiProxy.getCurrentEnvironment(); // Set the hostname to the actual application hostname eventBuilder.setServerName((String) env.getAttributes().get(CURRENT_VERSION_HOSTNAME_PROPERTY)); } }
Update test to check for new adsense markup.
/** * WordPress dependencies */ import { createURL } from '@wordpress/e2e-test-utils'; /** * Asserts the URL at the given path contains an AdSense tag. * * @since 1.10.0 * * @param {string} path The URL path of the current site to check. * @return {Object} Matcher result. */ export async function toHaveAdSenseTag( path ) { const result = {}; const page = await browser.newPage(); await page.goto( createURL( path ) ); try { await expect( page ).toMatchElement( 'script[src*="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client="]' ); result.pass = true; result.message = () => `Expected ${ path } not to contain an Adsense tag.`; } catch { result.pass = false; result.message = () => `Expected ${ path } to contain an Adsense tag.`; } await page.close(); return result; }
/** * WordPress dependencies */ import { createURL } from '@wordpress/e2e-test-utils'; /** * Asserts the URL at the given path contains an AdSense tag. * * @since 1.10.0 * * @param {string} path The URL path of the current site to check. * @return {Object} Matcher result. */ export async function toHaveAdSenseTag( path ) { const result = {}; const page = await browser.newPage(); await page.goto( createURL( path ) ); try { await expect( page ).toMatchElement( 'script[src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"]' ); result.pass = true; result.message = () => `Expected ${ path } not to contain an Adsense tag.`; } catch { result.pass = false; result.message = () => `Expected ${ path } to contain an Adsense tag.`; } await page.close(); return result; }
:bug: Fix error on iOS when script loaded in head
import iOS from './iOS'; import dummy from './dummy'; export default function touchLock(context, callback) { const locked = iOS; function unlock() { if (context && context.state === 'suspended') { context.resume() .then(() => { dummy(context); unlocked(); }); } else { unlocked(); } } function unlocked() { document.body.removeEventListener('touchstart', unlock); document.body.removeEventListener('touchend', unlock); callback(); } if (locked) { document.addEventListener('DOMContentLoaded', () => { document.body.addEventListener('touchstart', unlock, false); document.body.addEventListener('touchend', unlock, false); }); } return locked; }
import iOS from './iOS'; import dummy from './dummy'; export default function touchLock(context, callback) { const locked = iOS; function unlock() { if (context && context.state === 'suspended') { context.resume() .then(() => { dummy(context); unlocked(); }); } else { unlocked(); } } function unlocked() { document.body.removeEventListener('touchstart', unlock); document.body.removeEventListener('touchend', unlock); callback(); } if (locked) { document.body.addEventListener('touchstart', unlock, false); document.body.addEventListener('touchend', unlock, false); } return locked; }
Add KarmTestError we can distinguish and print full tracebacks for unexpected errors. Delete exception trapping--let the test scripts do that. svn path=/trunk/kdepim/; revision=367066
import sys import os class KarmTestError( Exception ): pass def dcopid(): '''Get dcop id of karm. Fail if more than one instance running.''' id = stdin = stdout = None ( stdin, stdout ) = os.popen2( "dcop" ) l = stdout.readline() while l: if l.startswith( "karm" ): if not id: id = l else: raise KarmTestError( "Only one instance of karm may be running." ) l = stdout.readline() if not id: raise KarmTestError( "No karm instance found. Try running dcop at command-line to verify it works." ) stdin.close() stdout.close() # strip trailing newline return id.strip() def test( goal, actual ): '''Raise exception if goal != actual.''' if goal != actual: path, scriptname = os.path.split( sys.argv[0] ) raise KarmTestError( "%s: expected '%s', got '%s'" % ( scriptname, goal, actual ) )
import sys import os def dcopid(): '''Get dcop id of karm. Fail if more than one instance running.''' id = stdin = stdout = None try: ( stdin, stdout ) = os.popen2( "dcop" ) l = stdout.readline() while l: if l.startswith( "karm" ): if not id: id = l else: raise "Only one instance of karm may be running." l = stdout.readline() if not id: raise "No karm instance found. Try running dcop at command-line to verify it works." except: if stdin: stdin.close() if stdout: stdout.close() print sys.exc_info()[0] sys.exit(1) stdin.close() stdout.close() # strip trailing newline return id.strip() def test( goal, actual ): '''Raise exception if goal != actual.''' if goal != actual: path, scriptname = os.path.split( sys.argv[0] ) raise "%s: expected '%s', got '%s'" % ( scriptname, goal, actual )
Make mod name tooltip italic
package mezz.jei; import javax.annotation.Nonnull; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.EnumChatFormatting; import net.minecraftforge.event.entity.player.ItemTooltipEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import mezz.jei.api.JEIManager; import mezz.jei.config.Config; public class TooltipEventHandler { private static final String chatFormatting = EnumChatFormatting.BLUE.toString() + EnumChatFormatting.ITALIC.toString(); @SubscribeEvent public void onToolTip(@Nonnull ItemTooltipEvent event) { if (!Config.tooltipModNameEnabled) { return; } ItemStack itemStack = event.itemStack; if (itemStack == null) { return; } Item item = itemStack.getItem(); if (item == null) { return; } String modName = JEIManager.itemRegistry.getModNameForItem(item); event.toolTip.add(chatFormatting + modName); } }
package mezz.jei; import javax.annotation.Nonnull; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.EnumChatFormatting; import net.minecraftforge.event.entity.player.ItemTooltipEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import mezz.jei.api.JEIManager; import mezz.jei.config.Config; public class TooltipEventHandler { @SubscribeEvent public void onToolTip(@Nonnull ItemTooltipEvent event) { if (!Config.tooltipModNameEnabled) { return; } ItemStack itemStack = event.itemStack; if (itemStack == null) { return; } Item item = itemStack.getItem(); if (item == null) { return; } String modName = JEIManager.itemRegistry.getModNameForItem(item); event.toolTip.add(EnumChatFormatting.BLUE + modName); } }
Use compatible min Firefox version
const path = require('path'); const fs = require('fs'); // eslint-disable-next-line const manifest = require('../dist/chrome/manifest.json'); fs.writeFileSync( path.join(__dirname, '../dist/firefox/manifest.json'), JSON.stringify( Object.assign({}, manifest, { applications: { gecko: { id: 'extension@hyper-gwent.com', strict_min_version: '57.0' } } }), null, 2 ) );
const path = require('path'); const fs = require('fs'); // eslint-disable-next-line const manifest = require('../dist/chrome/manifest.json'); fs.writeFileSync( path.join(__dirname, '../dist/firefox/manifest.json'), JSON.stringify( Object.assign({}, manifest, { applications: { gecko: { id: 'extension@hyper-gwent.com', strict_min_version: '53.0' } } }), null, 2 ) );
Add multi-botlist integration (+ novo and mayo)
const snekfetch = require('snekfetch'); exports.create = (Bot, guild) => { guild.owner.send(`Thanks for adding me to your server! To see a list of my commands, send \`${Bot.config.defaultPrefix}help\`.\nFeel free to DM Aetheryx#2222 for any questions or concerns!`); postStats(Bot); }; exports.delete = async (Bot, guild) => { await Bot.db.run('DELETE FROM prefixes WHERE guildID = ?;', guild.id); Bot.prefixes.delete(guild.id); postStats(Bot); }; function postStats (Bot) { Bot.botlists.forEach((token, url) => { if (url) { console.log(url, token); snekfetch .post(url) .set('Authorization', token) .send({ server_count: Bot.client.guilds.size }) .end(); } }); }
const snekfetch = require('snekfetch'); exports.create = (Bot, guild) => { guild.owner.send(`Thanks for adding me to your server! To see a list of my commands, send \`${Bot.config.defaultPrefix}help\`.\nFeel free to DM Aetheryx#2222 for any questions or concerns!`); postStats(Bot); }; exports.delete = async (Bot, guild) => { await Bot.db.run('DELETE FROM prefixes WHERE guildID = ?;', guild.id); Bot.prefixes.delete(guild.id); postStats(Bot); }; function postStats (Bot) { if (Bot.config.keys.botspw) { snekfetch .post(`https://bots.discord.pw/api/bots/${Bot.client.user.id}/stats`) .set('Authorization', Bot.config.keys.botspw) .send({ server_count: Bot.client.guilds.size }) .end(); } if (Bot.config.keys.dbots) { snekfetch .post(`https://discordbots.org/api/bots/${Bot.client.user.id}/stats`) .set('Authorization', Bot.config.keys.dbots) .send({ server_count: Bot.client.guilds.size }) .end(); } }
Test files shouldn't import 'fastavro.compat'. Just import BytesIO manually.
# -*- coding: utf-8 -*- """Python3 string tests for fastavro""" from __future__ import absolute_import from os import SEEK_SET from random import choice, seed from string import ascii_uppercase, digits try: from cStringIO import StringIO as BytesIO except ImportError: from io import BytesIO import fastavro letters = ascii_uppercase + digits id_size = 100 seed('str_py3') # Repeatable results def gen_id(): return ''.join(choice(letters) for _ in range(id_size)) keys = ['first', 'second', 'third', 'fourth'] testdata = [dict((key, gen_id()) for key in keys) for _ in range(50)] schema = { "fields": [{'name': key, 'type': 'string'} for key in keys], "namespace": "namespace", "name": "zerobyte", "type": "record" } def test_str_py3(): buf = BytesIO() fastavro.writer(buf, schema, testdata) buf.seek(0, SEEK_SET) for i, rec in enumerate(fastavro.iter_avro(buf), 1): pass size = len(testdata) assert i == size, 'bad number of records' assert rec == testdata[-1], 'bad last record' if __name__ == '__main__': test_str_py3()
from os import SEEK_SET from random import choice, seed from string import ascii_uppercase, digits import fastavro from fastavro.compat import BytesIO letters = ascii_uppercase + digits id_size = 100 seed('str_py3') # Repeatable results def gen_id(): return ''.join(choice(letters) for _ in range(id_size)) keys = ['first', 'second', 'third', 'fourth'] testdata = [dict((key, gen_id()) for key in keys) for _ in range(50)] schema = { "fields": [{'name': key, 'type': 'string'} for key in keys], "namespace": "namespace", "name": "zerobyte", "type": "record" } def test_str_py3(): buf = BytesIO() fastavro.writer(buf, schema, testdata) buf.seek(0, SEEK_SET) for i, rec in enumerate(fastavro.iter_avro(buf), 1): pass size = len(testdata) assert i == size, 'bad number of records' assert rec == testdata[-1], 'bad last record' if __name__ == '__main__': test_str_py3()
Migrate to @angular:2.0.0-rc.1. - partial test support
'use strict'; Error.stackTraceLimit = Infinity; require('es6-shim'); require('reflect-metadata'); require('zone.js/dist/zone'); require('@angular/core/testing'); /* Ok, this is kinda crazy. We can use the the context method on require that webpack created in order to tell webpack what files we actually want to require or import. Below, context will be an function/object with file names as keys. using that regex we are saying look in client/app and find any file that ends with spec.js and get its path. By passing in true we say do this recursively */ var appContext = require.context('./src', true, /root\.spec\.ts/); // get all the files, for each file, call the context function // that will require the file and load it up here. Context will // loop and require those spec files here appContext.keys().forEach(appContext); // Select BrowserDomAdapter. // see https://github.com/AngularClass/angular2-webpack-starter/issues/124 // Somewhere in the test setup var testing = require('@angular/core/testing'); var browser = require('@angular/platform-browser-dynamic/testing'); testing.setBaseTestProviders(browser.TEST_BROWSER_PLATFORM_PROVIDERS, browser.TEST_BROWSER_APPLICATION_PROVIDERS);
'use strict'; Error.stackTraceLimit = Infinity; require('es6-shim'); require('angular2/bundles/angular2-polyfills.js'); require('angular2/testing'); /* Ok, this is kinda crazy. We can use the the context method on require that webpack created in order to tell webpack what files we actually want to require or import. Below, context will be an function/object with file names as keys. using that regex we are saying look in client/app and find any file that ends with spec.js and get its path. By passing in true we say do this recursively */ var appContext = require.context('./src', true, /root\.spec\.ts/); // get all the files, for each file, call the context function // that will require the file and load it up here. Context will // loop and require those spec files here appContext.keys().forEach(appContext); // Select BrowserDomAdapter. // see https://github.com/AngularClass/angular2-webpack-starter/issues/124 // Somewhere in the test setup var testing = require('angular2/testing'); var browser = require('angular2/platform/testing/browser'); testing.setBaseTestProviders(browser.TEST_BROWSER_PLATFORM_PROVIDERS, browser.TEST_BROWSER_APPLICATION_PROVIDERS);
Convert Syslog to ES6 class. Closes #993.
const coalesce = require('extant') const FACILITY = require('prolific.facility') const LEVEL = require('prolific.level') class Processor { constructor (configuration) { this._application = coalesce(configuration.application, process.title) this._hostname = coalesce(configuration.hostname, 'localhost') this._facility = FACILITY[coalesce(configuration.facility, 'local0')] this._serializer = coalesce(configuration.serializer, JSON) } format (entry) { const pid = entry.pid, when = entry.when // TODO Probably faster if I set `undefined`. delete entry.when delete entry.pid const line = [ '<' + (this._facility * 8 + LEVEL[entry.level]) + '>1', new Date(when).toISOString(), this._hostname, this._application, coalesce(pid, '-'), '-', '-', this._serializer.stringify(entry) ] entry.when = when entry.pid = pid return line.join(' ') + '\n' } } module.exports = Processor
var coalesce = require('extant') var FACILITY = require('prolific.facility') var LEVEL = require('prolific.level') function Processor (configuration) { this._application = coalesce(configuration.application, process.title) this._hostname = coalesce(configuration.hostname, 'localhost') this._facility = FACILITY[coalesce(configuration.facility, 'local0')] this._serializer = coalesce(configuration.serializer, JSON) } Processor.prototype.format = function (entry) { var pid = entry.pid, when = entry.when // TODO Probably faster if I set `undefined`. delete entry.when delete entry.pid var line = [ '<' + (this._facility * 8 + LEVEL[entry.level]) + '>1', new Date(when).toISOString(), this._hostname, this._application, coalesce(pid, '-'), '-', '-', this._serializer.stringify(entry) ] entry.when = when entry.pid = pid return line.join(' ') + '\n' } module.exports = Processor
Add current date to polling log messages.
var TaskScheduler = require("./task").TaskScheduler; var colors = require("colors"); exports.execute = function(initialStep, context, cb) { var completedSteps = 0; var estimatedSteps = initialStep.remaining; var scheduler = new TaskScheduler({ maxConcurrency: 5, mode: "lifo" }, cb); scheduler.schedule(execute_step, initialStep.weight, initialStep.name, [initialStep, null]); function execute_step(step, item, cb) { step.handler(item, step.args, context, step_complete); function step_complete(err, items) { ++completedSteps; if(step.next) { if(err == null) { if(items == null) { items = []; } else if(items.length == undefined) { items = [items]; } estimatedSteps += (items.length - 1) * step.next.remaining; } else { estimatedSteps -= step.next.remaining; } } console.log("%s Completed %d steps of %d".green, new Date(), completedSteps, estimatedSteps); if(step.next && err == null) { items.forEach(function(i) { scheduler.schedule(execute_step, step.next.weight, step.next.name, [step.next, i]); }); } cb(err); } } }
var TaskScheduler = require("./task").TaskScheduler; var colors = require("colors"); exports.execute = function(initialStep, context, cb) { var completedSteps = 0; var estimatedSteps = initialStep.remaining; var scheduler = new TaskScheduler({ maxConcurrency: 5, mode: "lifo" }, cb); scheduler.schedule(execute_step, initialStep.weight, initialStep.name, [initialStep, null]); function execute_step(step, item, cb) { step.handler(item, step.args, context, step_complete); function step_complete(err, items) { ++completedSteps; if(step.next) { if(err == null) { if(items == null) { items = []; } else if(items.length == undefined) { items = [items]; } estimatedSteps += (items.length - 1) * step.next.remaining; } else { estimatedSteps -= step.next.remaining; } } console.log("Completed %d steps of %d".green, completedSteps, estimatedSteps); if(step.next && err == null) { items.forEach(function(i) { scheduler.schedule(execute_step, step.next.weight, step.next.name, [step.next, i]); }); } cb(err); } } }
Add coordinateFormat function to controlOptions if present
angular.module('anol.mouseposition', []) .directive('anolMousePosition', ['MapService', function(MapService) { return { restrict: 'A', require: '?^anolMap', scope: {}, link: { pre: function(scope, element, attrs) { scope.map = MapService.getMap(); }, post: function(scope, element, attrs, AnolMapController) { var controlOptions = {}; if(angular.isFunction(scope.coordinateFormat)) { controlOptions.coordinateFormat = scope.coordinateFormat; } if(angular.isUndefined(AnolMapController)) { controlOptions = { target: element[0] }; } scope.map.addControl( new ol.control.MousePosition(controlOptions) ); } } }; }]);
angular.module('anol.mouseposition', []) .directive('anolMousePosition', ['MapService', function(MapService) { return { restrict: 'A', require: '?^anolMap', scope: {}, link: { pre: function(scope, element, attrs, AnolMapController) { scope.map = MapService.getMap(); var controlOptions = {}; if(angular.isUndefined(AnolMapController)) { controlOptions = { target: element[0] }; } scope.map.addControl( new ol.control.MousePosition(controlOptions) ); } } }; }]);
Create commandline options for the clampval
import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D import sys def loadCudaStream(name): """ reads the file specified by name into a numpy array (and removes the superfluous fourth bit from cuda's float4) np.shape(data)=(N,3) where N is the length of a streamline """ data=np.fromfile(name, dtype="float32") data=data.reshape(int(len(data)/4), 4) data=np.delete(data,3,1) return data clampVal = 1; if (len(sys.argv) < 2) : print("Usage: \n dataplot.py path_to_binfile [clamp value]") sys.exit() elif (len(sys.argv) > 2) : clampVal = int(sys.argv[2]) binfile = sys.argv[1] data=np.fromfile(binfile, dtype="float32") datasize = np.sqrt(data.shape[0]) data=data.reshape(datasize, datasize) data = np.minimum(data,clampVal*np.ones(data.shape)) data = np.maximum(data,-1*clampVal*np.ones(data.shape)) img = plt.imshow(data) #img.set_cmap('hot') plt.colorbar() plt.show()
import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D import sys def loadCudaStream(name): """ reads the file specified by name into a numpy array (and removes the superfluous fourth bit from cuda's float4) np.shape(data)=(N,3) where N is the length of a streamline """ data=np.fromfile(name, dtype="float32") data=data.reshape(int(len(data)/4), 4) data=np.delete(data,3,1) return data # binfile = sys.argv[1] data=np.fromfile(binfile, dtype="float32") datasize = np.sqrt(data.shape[0]) data=data.reshape(datasize, datasize) data = np.minimum(data,1*np.ones(data.shape)) data = np.maximum(data,-1*np.ones(data.shape)) img = plt.imshow(data) #img.set_cmap('hot') plt.colorbar() plt.show()
Fix invalid registerEvent and triggerEvent anon MR
<?php /** * Mongo Record, anonymous Mongo Record when an entire class isn't needed * * Used when only an anonymous Mongo Record is needed * * @author Lu Wang <https://github.com/lunaru/> * @version 1.0.1 * @package MongoRecord */ final class MongoRecord extends BaseMongoRecord { protected $__meta; public static function find($collection, $query = array(), $options = array()) { return parent::find($query, $options, $collection); } public static function findOne($collection, $query = array(), $options = array()) { return parent::findOne($query, $options, $collection); } public static function count($collection, $query = array()) { return parent::count($query, $collection); } protected static function instantiate($collection, $document) { return parent::instantiate($document, $collection); } protected static function registerEvent($collection, $event, $callback) { return parent::registerEvent($event, $callback, $collection); } protected static function triggerEvent($collection, &$scope, $event) { return parent::registerEvent($scope, $event, $collection); } }
<?php /** * Mongo Record, anonymous Mongo Record when an entire class isn't needed * * Used when only an anonymous Mongo Record is needed * * @author Lu Wang <https://github.com/lunaru/> * @version 1.0.1 * @package MongoRecord */ final class MongoRecord extends BaseMongoRecord { protected $__meta; public static function find($collection, $query = array(), $options = array()) { return parent::find($query, $options, $collection); } public static function findOne($collection, $query = array(), $options = array()) { return parent::findOne($query, $options, $collection); } public static function count($collection, $query = array()) { return parent::count($query, $collection); } protected static function instantiate($collection, $document) { return parent::instantiate($document, $collection); } }
Prepare for next dev cycle
#!/usr/bin/env python # coding: utf-8 from setuptools import setup, find_packages setup( name="bentoo", description="Benchmarking tools", version="0.15.dev", packages=find_packages(), scripts=["scripts/bentoo-generator.py", "scripts/bentoo-runner.py", "scripts/bentoo-collector.py", "scripts/bentoo-analyser.py", "scripts/bentoo-likwid-metric.py", "scripts/bentoo-quickstart.py", "scripts/bentoo-calltree.py", "scripts/bentoo-merge.py", "scripts/bentoo-calltree-analyser.py", "scripts/bentoo-viewer.py", "scripts/bentoo-svgconvert.py", "scripts/bentoo-confreader.py"], package_data={ '': ['*.adoc', '*.rst', '*.md'] }, author="Zhang YANG", author_email="zyangmath@gmail.com", license="PSF", keywords="Benchmark;Performance Analysis", url="http://github.com/ProgramFan/bentoo" )
#!/usr/bin/env python # coding: utf-8 from setuptools import setup, find_packages setup( name="bentoo", description="Benchmarking tools", version="0.14", packages=find_packages(), scripts=["scripts/bentoo-generator.py", "scripts/bentoo-runner.py", "scripts/bentoo-collector.py", "scripts/bentoo-analyser.py", "scripts/bentoo-likwid-metric.py", "scripts/bentoo-quickstart.py", "scripts/bentoo-calltree.py", "scripts/bentoo-merge.py", "scripts/bentoo-calltree-analyser.py", "scripts/bentoo-viewer.py", "scripts/bentoo-svgconvert.py", "scripts/bentoo-confreader.py"], package_data={ '': ['*.adoc', '*.rst', '*.md'] }, author="Zhang YANG", author_email="zyangmath@gmail.com", license="PSF", keywords="Benchmark;Performance Analysis", url="http://github.com/ProgramFan/bentoo" )
Comment out numpy, scipy which cause problems in buildout
from setuptools import setup, find_packages import os version = '0.1' long_description = ( open('README.txt').read() + '\n' + 'Contributors\n' '============\n' + '\n' + open('CONTRIBUTORS.txt').read() + '\n' + open('CHANGES.txt').read() + '\n') requires = ['pyramid', 'PasteScript', 'requests', 'pymongo',]# 'numpy', 'scipy==0.10.0'] setup(name='mist.monitor', version=version, description="Monitoring node for the https://mist.io service", long_description=long_description, # Get more strings from # http://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=[ "Programming Language :: Python", ], keywords='', author='', author_email='', url='https://mist.io/', license='copyright', packages=find_packages('src'), package_dir = {'': 'src'}, namespace_packages=['mist'], include_package_data=True, zip_safe=False, install_requires= requires, entry_points=""" # -*- Entry points: -*- [paste.app_factory] main = mist.monitor:main """, )
from setuptools import setup, find_packages import os version = '0.1' long_description = ( open('README.txt').read() + '\n' + 'Contributors\n' '============\n' + '\n' + open('CONTRIBUTORS.txt').read() + '\n' + open('CHANGES.txt').read() + '\n') requires = ['pyramid', 'PasteScript', 'requests', 'pymongo', 'numpy', 'scipy==0.10.0'] setup(name='mist.monitor', version=version, description="Monitoring node for the https://mist.io service", long_description=long_description, # Get more strings from # http://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=[ "Programming Language :: Python", ], keywords='', author='', author_email='', url='https://mist.io/', license='copyright', packages=find_packages('src'), package_dir = {'': 'src'}, namespace_packages=['mist'], include_package_data=True, zip_safe=False, install_requires= requires, entry_points=""" # -*- Entry points: -*- [paste.app_factory] main = mist.monitor:main """, )
Add example of extending Gerrit's top menu item Add a "Browse Repositories" item in the "Projects" menu. Change-Id: I67af5bca1a14288147b1bc43fb089ba0abe0d6b2
// Copyright (C) 2013 The Android Open Source Project // // 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.googlesource.gerrit.plugins.cookbook; import java.util.List; import com.google.common.collect.Lists; import com.google.gerrit.extensions.annotations.PluginName; import com.google.gerrit.extensions.webui.TopMenu; import com.google.inject.Inject; public class HelloTopMenu implements TopMenu { private final List<MenuEntry> menuEntries; @Inject public HelloTopMenu(@PluginName String pluginName) { String baseUrl = "/plugins/" + pluginName + "/"; List<MenuItem> menuItems = Lists.newArrayListWithCapacity(1); menuItems.add(new MenuItem("Documentation", baseUrl)); menuEntries = Lists.newArrayListWithCapacity(1); menuEntries.add(new MenuEntry("Cookbook", menuItems)); menuEntries.add(new MenuEntry("Projects", Lists.newArrayList( new MenuItem("Browse Repositories", "https://gerrit.googlesource.com/")))); } @Override public List<MenuEntry> getEntries() { return menuEntries; } }
// Copyright (C) 2013 The Android Open Source Project // // 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.googlesource.gerrit.plugins.cookbook; import java.util.List; import com.google.common.collect.Lists; import com.google.gerrit.extensions.annotations.PluginName; import com.google.gerrit.extensions.webui.TopMenu; import com.google.inject.Inject; public class HelloTopMenu implements TopMenu { private final List<MenuEntry> menuEntries; @Inject public HelloTopMenu(@PluginName String pluginName) { String baseUrl = "/plugins/" + pluginName + "/"; List<MenuItem> menuItems = Lists.newArrayListWithCapacity(1); menuItems.add(new MenuItem("Documentation", baseUrl)); menuEntries = Lists.newArrayListWithCapacity(1); menuEntries.add(new MenuEntry("Cookbook", menuItems)); } @Override public List<MenuEntry> getEntries() { return menuEntries; } }
Fix to use get_serializer_class method instead of serializer_class
class NestedViewSetMixin(object): def get_queryset(self): """ Filter the `QuerySet` based on its parents as defined in the `serializer_class.parent_lookup_kwargs`. """ queryset = super(NestedViewSetMixin, self).get_queryset() serializer_class = self.get_serializer_class() if hasattr(serializer_class, 'parent_lookup_kwargs'): orm_filters = {} for query_param, field_name in serializer_class.parent_lookup_kwargs.items(): orm_filters[field_name] = self.kwargs[query_param] return queryset.filter(**orm_filters) return queryset
class NestedViewSetMixin(object): def get_queryset(self): """ Filter the `QuerySet` based on its parents as defined in the `serializer_class.parent_lookup_kwargs`. """ queryset = super(NestedViewSetMixin, self).get_queryset() if hasattr(self.serializer_class, 'parent_lookup_kwargs'): orm_filters = {} for query_param, field_name in self.serializer_class.parent_lookup_kwargs.items(): orm_filters[field_name] = self.kwargs[query_param] return queryset.filter(**orm_filters) return queryset
Use fat arrow function for more concise code
'use strict' const promisify = require('promisify-node') const ghissues = promisify('ghissues') const semverRegex = require('semver-regex') const logger = require('../logging').logger function writeComment (authData, user, project, pr, comment) { return ghissues.createComment(authData, user, project, pr, comment).then( function (comment) { logger.debug('Comment added to PR#%d: %s', pr, JSON.stringify(comment)) }, function (error) { logger.error('Error adding comment to PR#%d: %s', pr, error) }) } function getSemverComments (commentList) { const commentBodies = commentList.map(comment => comment.body) const semverComments = commentBodies.filter(body => semverRegex().test(body)) return semverComments } module.exports = { getSemverComments, writeComment }
'use strict' const promisify = require('promisify-node') const ghissues = promisify('ghissues') const semverRegex = require('semver-regex') const logger = require('../logging').logger function writeComment (authData, user, project, pr, comment) { return ghissues.createComment(authData, user, project, pr, comment).then( function (comment) { logger.debug('Comment added to PR#%d: %s', pr, JSON.stringify(comment)) }, function (error) { logger.error('Error adding comment to PR#%d: %s', pr, error) }) } function getSemverComments (commentList) { const commentBodies = commentList.map(comment => comment.body) const semverComments = commentBodies.filter(function (body) { return semverRegex().test(body) }) return semverComments } module.exports = { getSemverComments, writeComment }
Fix copy-pasta error on Toolkit constants
<?php /** * This file contains class name definitions for bricks in the GenesisThemeToolkit * * @package Gamajo\GenesisThemeTookit * @author Gary Jones * @copyright Gamajo * @license MIT */ declare(strict_types=1); namespace Gamajo\GenesisThemeToolkit; /** * Define the brick class names for GenesisThemeToolkit * * These are used at the end of the config file e.g.: * * ``` * return [ * 'Gamajo' => [ * 'Theme' => [ * ThemeToolkit::GOOGLEFONTS => $gamajo_google_fonts, * ThemeToolkit::IMAGESIZES => $gamajo_image_sizes, * GenesisThemeToolkit::LAYOUTS => $gamajo_genesis_layouts, * GenesisThemeToolkit::WIDGETAREAS => $gamajo_genesis_widget_areas, * ], * ], * ]; * ``` * * @package Gamajo\GenesisThemeTookit */ class GenesisThemeToolkit { const BREADCRUMBARGS = 'BreadcrumbArgs'; const LAYOUTS = 'Layouts'; const TEMPLATES = 'Templates'; const THEMESETTINGS = 'ThemeSettings'; const WIDGETAREAS = 'WidgetAreas'; }
<?php /** * This file contains class name definitions for bricks in the GenesisThemeToolkit * * @package Gamajo\GenesisThemeTookit * @author Gary Jones * @copyright Gamajo * @license MIT */ declare(strict_types=1); namespace Gamajo\GenesisThemeToolkit; /** * Define the brick class names for GenesisThemeToolkit * * These are used at the end of the config file e.g.: * * ``` * return [ * 'Gamajo' => [ * 'Theme' => [ * ThemeToolkit::GOOGLEFONTS => $gamajo_google_fonts, * ThemeToolkit::IMAGESIZES => $gamajo_image_sizes, * GenesisThemeToolkit::LAYOUTS => $gamajo_genesis_layouts, * GenesisThemeToolkit::WIDGETAREAS => $gamajo_genesis_widget_areas, * ], * ], * ]; * ``` * * @package Gamajo\GenesisThemeTookit */ class GenesisThemeToolkit { const BREADCRUMBARGS = 'GoogleFonts'; const LAYOUTS = 'Layouts'; const TEMPLATES = 'Templates'; const THEMESETTINGS = 'ThemeSettings'; const WIDGETAREAS = 'WidgetAreas'; }
Add paramiko req >= 2.3.1
from setuptools import setup, find_packages import platform with open('README.rst') as f: readme = f.read() execfile('substance/_version.py') install_requires = ['setuptools>=1.1.3', 'PyYAML', 'tabulate', 'paramiko>=2.3.1', 'netaddr', 'requests', 'tinydb', 'python_hosts==0.3.3', 'jinja2'] if 'Darwin' in platform.system(): install_requires.append('macfsevents') setup(name='substance', version=__version__, author='Turbulent', author_email='oss@turbulent.ca', url='https://substance.readthedocs.io/', license='Apache License 2.0', long_description=readme, description='Substance - Local dockerized development environment', install_requires=install_requires, packages=find_packages(), package_data={'substance': ['support/*']}, test_suite='tests', zip_safe=False, include_package_data=True, entry_points={ 'console_scripts': [ 'substance = substance.cli:cli', 'subenv = substance.subenv.cli:cli' ], })
from setuptools import setup, find_packages import platform with open('README.rst') as f: readme = f.read() execfile('substance/_version.py') install_requires = ['setuptools>=1.1.3', 'PyYAML', 'tabulate', 'paramiko>=2.3', 'netaddr', 'requests', 'tinydb', 'python_hosts==0.3.3', 'jinja2'] if 'Darwin' in platform.system(): install_requires.append('macfsevents') setup(name='substance', version=__version__, author='Turbulent', author_email='oss@turbulent.ca', url='https://substance.readthedocs.io/', license='Apache License 2.0', long_description=readme, description='Substance - Local dockerized development environment', install_requires=install_requires, packages=find_packages(), package_data={'substance': ['support/*']}, test_suite='tests', zip_safe=False, include_package_data=True, entry_points={ 'console_scripts': [ 'substance = substance.cli:cli', 'subenv = substance.subenv.cli:cli' ], })
Allow 'staging' as an env name for non-clustered run
#!/usr/bin/env node /* * SQL API loader * =============== * * node app [environment] * * environments: [development, test, production] * */ var _ = require('underscore'); // sanity check arguments var ENV = process.argv[2]; if (ENV != 'development' && ENV != 'production' && ENV != 'test' && ENV != 'staging' ) { console.error("\n./app [environment]"); console.error("environments: [development, staging, production, test]"); process.exit(1); } // set Node.js app settings and boot global.settings = require(__dirname + '/config/settings'); var env = require(__dirname + '/config/environments/' + ENV); _.extend(global.settings, env); // kick off controller if ( ! global.settings.base_url ) global.settings.base_url = '/api/*'; var app = require(global.settings.app_root + '/app/controllers/app'); app.listen(global.settings.node_port, global.settings.node_host, function() { console.log("CartoDB SQL API listening on " + global.settings.node_host + ":" + global.settings.node_port + " with base_url " + global.settings.base_url); });
#!/usr/bin/env node /* * SQL API loader * =============== * * node app [environment] * * environments: [development, test, production] * */ var _ = require('underscore'); // sanity check arguments var ENV = process.argv[2]; if (ENV != 'development' && ENV != 'production' && ENV != 'test') { console.error("\n./app [environment]"); console.error("environments: [development, test, production]"); process.exit(1); } // set Node.js app settings and boot global.settings = require(__dirname + '/config/settings'); var env = require(__dirname + '/config/environments/' + ENV); _.extend(global.settings, env); // kick off controller if ( ! global.settings.base_url ) global.settings.base_url = '/api/*'; var app = require(global.settings.app_root + '/app/controllers/app'); app.listen(global.settings.node_port, global.settings.node_host, function() { console.log("CartoDB SQL API listening on " + global.settings.node_host + ":" + global.settings.node_port + " with base_url " + global.settings.base_url); });
Allow math symbols to be input via character entities Entity decoding occurs when an input field loses focus. Note that this is a hack and potentially a security risk. Also, it can't handle custom mnemonics for math symbols.
// TODO Don't use a global var proofRows = []; // TODO Don't use a global var proofTable = document.getElementById("theTable"); var escapingDiv = document.createElement("div"); proofTable.addEventListener("change", function (changeEvent) { // TODO May be a security risk -- also annoying to type HTML entities escapingDiv.innerHTML = changeEvent.target.value; changeEvent.target.value = escapingDiv.innerHTML; }); // TODO Don't use a global var proofTBody = proofTable.createTBody(); function makeProofLine(formulaText, reasonText) { formulaText = formulaText || ""; reasonText = reasonText || ""; var newId = proofRows.length; var row = document.createElement("tr"); proofRows[newId] = row; var idCell = row.insertCell(); idCell.innerText = newId; var formulaInput = document.createElement("input"); formulaInput.className = "formula"; formulaInput.value = formulaText; row.insertCell().appendChild(formulaInput); var reasonInput = document.createElement("input"); reasonInput.value = reasonText; row.insertCell().appendChild(reasonInput); return newId; } function moveAbove(topRow, botRow) { proofTBody.insertBefore(proofRows[topRow], proofRows[botRow]); } function setFormula(row, formulaHtml) { proofRows[row].children[1].innerHTML = formulaHtml; } function setReason(row, reasonHtml) { proofRows[row].children[2].innerHTML = reasonHtml; }
// TODO Don't use a global var proofRows = []; // TODO Don't use a global var proofTBody = document.getElementById("theTable").createTBody(); function makeProofLine(formulaText, reasonText) { formulaText = formulaText || ""; reasonText = reasonText || ""; var newId = proofRows.length; var row = document.createElement("tr"); proofRows[newId] = row; var idCell = row.insertCell(); idCell.innerText = newId; var formulaInput = document.createElement("input"); formulaInput.className = "formula"; formulaInput.value = formulaText; row.insertCell().appendChild(formulaInput); var reasonInput = document.createElement("input"); reasonInput.value = reasonText; row.insertCell().appendChild(reasonInput); return newId; } function moveAbove(topRow, botRow) { proofTBody.insertBefore(proofRows[topRow], proofRows[botRow]); } function setFormula(row, formulaHtml) { proofRows[row].children[1].innerHTML = formulaHtml; } function setReason(row, reasonHtml) { proofRows[row].children[2].innerHTML = reasonHtml; }
Rename ambiguous variable name "word" to "letters" The variable is renamed because it is better to call an ArrayList of Letter "letters" rather than "word".
package com.nigorojr.typebest; import java.util.ArrayList; import javax.swing.JPanel; public class Word extends JPanel { private ArrayList<Letter> letters = new ArrayList<Letter>(); private String rawWord; /** * Accepts a String which is what will be shown in this JPanel. * The constructor will then split the word into letters and create a Letter * object for each letter. After that, Letter objects are added to the * this JPanel. * * @param word * The word that will be shown as a collection of "Letter" class. */ public Word(String word) { rawWord = word; letterCount = 0; split(); for (int i = 0; i < letters.size(); i++) this.add(letters.get(i)); } /** * Splits up the word into letters and add them to an ArrayList. */ private void split() { for (int i = 0; i < rawWord.length(); i++) { Letter letter = new Letter(rawWord.charAt(i)); letters.add(letter); } } }
package com.nigorojr.typebest; import java.util.ArrayList; import javax.swing.JPanel; public class Word extends JPanel { private ArrayList<Letter> word = new ArrayList<Letter>(); private String rawWord; /** * Accepts a String which is what will be shown in this JPanel. * The constructor will then split the word into letters and create a Letter * object for each letter. After that, Letter objects are added to the * this JPanel. * * @param word * The word that will be shown as a collection of "Letter" class. */ public Word(String word) { rawWord = word; split(); for (int i = 0; i < this.word.size(); i++) this.add(this.word.get(i)); } /** * Splits up the word into letters and add them to an ArrayList. */ private void split() { for (int i = 0; i < rawWord.length(); i++) { Letter letter = new Letter(rawWord.charAt(i)); word.add(letter); } } }
Fix for default_affiliation valid values
package org.buddycloud.channelserver.channel.node.configuration.field; public class Affiliation extends Field { public static final String FIELD_NAME = "pubsub#default_affiliation"; public static final String DEFAULT_VALUE = Affiliation.models.MEMBER .toString(); public enum models { FOLLOWER_AND_POST("publisher"), MEMBER("follower"), OWNER("owner"), MODERATOR( "moderator"); String model = null; private models(String model) { this.model = model; } public String toString() { return model; } } public Affiliation() { name = FIELD_NAME; } public boolean isValid() { return (getValue().equals( Affiliation.models.FOLLOWER_AND_POST.toString()) || getValue().equals(Affiliation.models.MEMBER.toString()) || getValue().equals(Affiliation.models.OWNER.toString()) || getValue().equals(Affiliation.models.MODERATOR.toString()) ); } }
package org.buddycloud.channelserver.channel.node.configuration.field; public class Affiliation extends Field { public static final String FIELD_NAME = "pubsub#default_affiliation"; public static final String DEFAULT_VALUE = Affiliation.models.MEMBER.toString(); public enum models { FOLLOWER_AND_POST("publisher"), MEMBER("follower"); String model = null; private models(String model) { this.model = model; } public String toString() { return model; } } public Affiliation() { name = FIELD_NAME; } public boolean isValid() { return (getValue().equals(Affiliation.models.FOLLOWER_AND_POST.toString()) || getValue().equals(Affiliation.models.MEMBER.toString()) ); } }
Add time stamp to tweet Добавляется в начало твита время для обхода защиты от повторяющихся постов.
<?php /* * @version 0.1 (auto-set) */ /** * Title * * Description * * @access public */ function postToTwitter($message) { if (!defined('SETTINGS_TWITTER_CKEY')) { return 0; } $consumerKey = SETTINGS_TWITTER_CKEY; $consumerSecret = SETTINGS_TWITTER_CSECRET; $oAuthToken = SETTINGS_TWITTER_ATOKEN; $oAuthSecret = SETTINGS_TWITTER_ASECRET; if ($consumerKey=='' || $consumerSecret=='' || $oAuthSecret=='' || $oAuthToken=='') { return 0; } require_once(ROOT.'lib/twitter/twitteroauth.php'); // create a new instance $tweet = new TwitterOAuth($consumerKey, $consumerSecret, $oAuthToken, $oAuthSecret); // add time to message $message = date('H:i:s').' '.$message; //send a tweet $tweet->post('statuses/update', array('status' => $message)); } ?>
<?php /* * @version 0.1 (auto-set) */ /** * Title * * Description * * @access public */ function postToTwitter($message) { if (!defined('SETTINGS_TWITTER_CKEY')) { return 0; } $consumerKey = SETTINGS_TWITTER_CKEY; $consumerSecret = SETTINGS_TWITTER_CSECRET; $oAuthToken = SETTINGS_TWITTER_ATOKEN; $oAuthSecret = SETTINGS_TWITTER_ASECRET; if ($consumerKey=='' || $consumerSecret=='' || $oAuthSecret=='' || $oAuthToken=='') { return 0; } require_once(ROOT.'lib/twitter/twitteroauth.php'); // create a new instance $tweet = new TwitterOAuth($consumerKey, $consumerSecret, $oAuthToken, $oAuthSecret); //send a tweet $tweet->post('statuses/update', array('status' => $message)); } ?>
Include subfolders of `demo` and `test` folders for linting
'use strict'; var gulp = require('gulp'); var eslint = require('gulp-eslint'); var htmlExtract = require('gulp-html-extract'); var stylelint = require('gulp-stylelint'); gulp.task('lint', ['lint:js', 'lint:html', 'lint:css']); gulp.task('lint:js', function() { return gulp.src([ '*.js', 'test/**/*.js' ]) .pipe(eslint()) .pipe(eslint.format()) .pipe(eslint.failAfterError()); }); gulp.task('lint:html', function() { return gulp.src([ '*.html', 'demo/**/*.html', 'test/**/*.html' ]) .pipe(htmlExtract({ sel: 'script, code-example code' })) .pipe(eslint()) .pipe(eslint.format()) .pipe(eslint.failAfterError()); }); gulp.task('lint:css', function() { return gulp.src([ '*.html', 'demo/**/*.html', 'test/**/*.html' ]) .pipe(htmlExtract({ sel: 'style' })) .pipe(stylelint({ reporters: [ {formatter: 'string', console: true} ] })); });
'use strict'; var gulp = require('gulp'); var eslint = require('gulp-eslint'); var htmlExtract = require('gulp-html-extract'); var stylelint = require('gulp-stylelint'); gulp.task('lint', ['lint:js', 'lint:html', 'lint:css']); gulp.task('lint:js', function() { return gulp.src([ '*.js', 'test/*.js' ]) .pipe(eslint()) .pipe(eslint.format()) .pipe(eslint.failAfterError()); }); gulp.task('lint:html', function() { return gulp.src([ '*.html', 'demo/*.html', 'test/*.html' ]) .pipe(htmlExtract({ sel: 'script, code-example code' })) .pipe(eslint()) .pipe(eslint.format()) .pipe(eslint.failAfterError()); }); gulp.task('lint:css', function() { return gulp.src([ '*.html', 'demo/*.html', 'test/*.html' ]) .pipe(htmlExtract({ sel: 'style' })) .pipe(stylelint({ reporters: [ {formatter: 'string', console: true} ] })); });
Use Accept header instead of funky .json suffix.
askaway.controller('QuestionsCtrl', ['$scope', '$http', function( $scope, $http ) { $http.get('/trending.json').success(function(data) { $scope.questionList = data; }); $scope.toggleVote = function() { var question = this.question; if (question.vote_id) { $http.delete('/votes/' + question.vote_id).success(function(vote) { question.votes_count--; question.vote_id = undefined; }); } else { $http.post('/questions/' + question.id + '/votes', null, { headers: { Accept: 'application/json' } }) .success(function(vote) { question.votes_count++; question.vote_id = vote.id; }) .error(function(data, status) { if (status === 401) { $('#login-modal').modal('show'); } // FIXME handle other error statuses ... message box? }); } }; }]); askaway.controller( 'QuestionFormCtrl', ['$scope', function( $scope ) { }]);
askaway.controller('QuestionsCtrl', ['$scope', '$http', function( $scope, $http ) { $http.get('/trending.json').success(function(data) { $scope.questionList = data; }); $scope.toggleVote = function() { var question = this.question; if (question.vote_id) { $http.delete('/votes/' + question.vote_id).success(function(vote) { question.votes_count--; question.vote_id = undefined; }); } else { $http.post('/questions/' + question.id + '/votes.json') .success(function(vote) { question.votes_count++; question.vote_id = vote.id; }) .error(function(data, status) { if (status === 401) { $('#login-modal').modal('show'); } // FIXME handle other error statuses ... message box? }); } }; }]); askaway.controller( 'QuestionFormCtrl', ['$scope', function( $scope ) { }]);
Update communication configuration class to allow the base url to be set for the purpose of testing
<?php namespace Zara4\API\Communication; class Config { const VERSION = '1.2.3'; const USER_AGENT = 'Zara 4 PHP-SDK, Version-1.2.3'; const PRODUCTION_API_ENDPOINT = "https://api.zara4.com"; const DEVELOPMENT_API_ENDPOINT = "http://api.zara4.dev"; public static $BASE_URL = self::PRODUCTION_API_ENDPOINT; // --- --- --- --- --- /** * Get the base url. * * @return string */ public static function BASE_URL() { return self::$BASE_URL; } /** * Set the base url * * @param $baseUrl */ public static function setBaseUrl($baseUrl) { self::$BASE_URL = $baseUrl; } /** * Configure production mode. */ public static function enterProductionMode() { self::setBaseUrl(self::PRODUCTION_API_ENDPOINT); } /** * Configure development mode. */ public static function enterDevelopmentMode() { self::setBaseUrl(self::DEVELOPMENT_API_ENDPOINT); } }
<?php namespace Zara4\API\Communication; class Config { const VERSION = '1.1.0'; const USER_AGENT = 'Zara 4 PHP-SDK, Version-1.1.0'; const PRODUCTION_API_ENDPOINT = "https://api.zara4.com"; const DEVELOPMENT_API_ENDPOINT = "http://api.zara4.dev"; private static $BASE_URL = self::PRODUCTION_API_ENDPOINT; // --- --- --- --- --- /** * Get the base url. * * @return string */ public static function BASE_URL() { return self::$BASE_URL; } /** * Configure production mode. */ public static function enterProductionMode() { self::$BASE_URL = self::PRODUCTION_API_ENDPOINT; } /** * Configure development mode. */ public static function enterDevelopmentMode() { self::$BASE_URL = self::DEVELOPMENT_API_ENDPOINT; } }
Transform data to the target format
import os.path import sys import pandas as pd import logging INPUT_DIRECTORY = '../../../data/raw/disease_SG' INPUT_FILE = "weekly-dengue-malaria.csv" OUTPUT_DIRECTORY = '../../../data/interim/disease_SG' OUTPUT_FILE = "weekly-dengue-malaria-cleaned.csv" logger = logging.getLogger(__name__) def clean(): input_path = os.path.join(INPUT_DIRECTORY, INPUT_FILE) if not os.path.isfile(input_path): logger.error("Input file is not found %s", os.path.abspath(input_path)) data_frame = pd.read_csv(input_path, names=['year_week', 'disease', 'number_of_cases']) data_frame['country'] = 'Singapore' year_week = pd.DataFrame(data_frame.year_week.str.split('-').tolist(), columns=['year','week']) data_frame['year'] = year_week['year'] data_frame['week'] = year_week['week'] data_frame.drop('year_week', 1, inplace=True) os.makedirs(OUTPUT_DIRECTORY, exist_ok=True) output_path = os.path.join(OUTPUT_DIRECTORY, OUTPUT_FILE) data_frame.to_csv(output_path, index=False) logger.info('Data clean successfully') if __name__ == "__main__": logging.basicConfig(stream=sys.stdout, level=logging.DEBUG) clean()
import os.path import sys import pandas as pd import logging INPUT_DIRECTORY = '../../../data/raw/disease_SG' INPUT_FILE = "weekly-dengue-malaria.csv" OUTPUT_DIRECTORY = '../../Data/interim/disease_SG' OUTPUT_FILE = "weekly-dengue-malaria.csv" logger = logging.getLogger(__name__) def clean(): input_path = os.path.join(INPUT_DIRECTORY, INPUT_FILE) if not os.path.isfile(input_path): logger.error("Input file is not found %s", os.path.abspath(input_path)) data_frame = pd.read_csv(input_path, names=['week', 'disease', 'number of cases']) print (data_frame) print("end") if __name__ == "__main__": logging.basicConfig(stream=sys.stdout, level=logging.DEBUG) clean()
Add error message to BadRequest signup response for invalid method
from django.http import JsonResponse, HttpResponse, HttpResponseBadRequest from django.views.decorators.csrf import csrf_exempt import json from helpers import get_school_list, check_signup_email def get_schools(request): resp = JsonResponse({'schools': get_school_list()}) resp['Access-Control-Allow-Origin'] = 'http://localhost:3000' return resp @csrf_exempt def signup(request): if request.method == "POST": signup_parameters = json.loads(request.body.decode('utf-8')) if check_signup_email(signup_parameters['email']): resp = HttpResponse('Signup OK') else: resp = HttpResponseBadRequest('Invalid univesity email') elif request.method == "OPTIONS": resp = HttpResponse('') resp['Access-Control-Allow-Headers'] = 'Content-Type' else: resp = HttpResponseBadRequest('Invalid request method') resp['Access-Control-Allow-Origin'] = 'http://localhost:3000' return resp
from django.http import JsonResponse, HttpResponse, HttpResponseBadRequest from django.views.decorators.csrf import csrf_exempt import json from helpers import get_school_list, check_signup_email def get_schools(request): resp = JsonResponse({'schools': get_school_list()}) resp['Access-Control-Allow-Origin'] = 'http://localhost:3000' return resp @csrf_exempt def signup(request): if request.method == "POST": signup_parameters = json.loads(request.body.decode('utf-8')) if check_signup_email(signup_parameters['email']): resp = HttpResponse('Signup OK') else: resp = HttpResponseBadRequest('Invalid univesity email') elif request.method == "OPTIONS": resp = HttpResponse('') resp['Access-Control-Allow-Headers'] = 'Content-Type' else: resp = HttpResponseBadRequest('') resp['Access-Control-Allow-Origin'] = 'http://localhost:3000' return resp
Refactor to_dict method on the Message model
from django.db import models class Channel(models.Model): def __str__(self): return self.name name = models.CharField(max_length=20, unique=True) class Message(models.Model): def __str__(self): return self.text def to_dict(self): serializable_fields = ('text', 'datetime_start', 'datetime_sent', 'username') return {key: getattr(self, key) for key in serializable_fields} text = models.TextField(max_length=2000) datetime_start = models.DateTimeField(default=None) datetime_sent = models.DateTimeField(default=None, null=True) typing = models.BooleanField(default=False) username = models.CharField(max_length=20) channel = models.ForeignKey(Channel)
from django.db import models class Channel(models.Model): def __str__(self): return self.name name = models.CharField(max_length=20, unique=True) class Message(models.Model): def __str__(self): return self.text def to_dict(self): return { 'text': self.text, 'datetime_start': self.datetime_start, 'datetime_sent': getattr(self, 'datetime_sent', False), 'username': self.username } text = models.TextField(max_length=2000) datetime_start = models.DateTimeField(default=None) datetime_sent = models.DateTimeField(default=None, null=True) typing = models.BooleanField(default=False) username = models.CharField(max_length=20) channel = models.ForeignKey(Channel)
Change API keys to uppercase
var Twit = require('twit'); var twitInfo = [CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET]; //use when testing locally // var twitInfo = require('./config.js') var twitter = new Twit(twitInfo); var useUpperCase = function(wordList) { var tempList = Object.keys(wordList).filter(function(word) { return word[0] >= "A" && word[0] <= "Z"; }); return tempList[~~(Math.random()*tempList.length)]; }; var MarkovChain = require('markovchain') , fs = require('fs') , quotes = new MarkovChain(fs.readFileSync('./rabelais.txt', 'utf8')); function generateSentence() { return quotes.start(useUpperCase).end(Math.floor((Math.random() * 3) + 6)).process() + "."; } function postTweet(sentence) { var tweet = { status: sentence }; twitter.post('statuses/update', tweet , function(err, data, response) { if (err) { // console.log("5OMeTh1nG weNt wR0ng"); } else { // console.log("Tweet sucessful"); } }); } postTweet(generateSentence); // second parameter is in miliseconds MNMNsetInterval(postTweet(generateSentence), 1000*60*60*11);
var Twit = require('twit'); var twitInfo = [consumer_key, consumer_secret, access_token, access_token_secret]; //use when testing locally // var twitInfo = require('./config.js') var twitter = new Twit(twitInfo); var useUpperCase = function(wordList) { var tempList = Object.keys(wordList).filter(function(word) { return word[0] >= "A" && word[0] <= "Z"; }); return tempList[~~(Math.random()*tempList.length)]; }; var MarkovChain = require('markovchain') , fs = require('fs') , quotes = new MarkovChain(fs.readFileSync('./rabelais.txt', 'utf8')); function generateSentence() { return quotes.start(useUpperCase).end(Math.floor((Math.random() * 3) + 6)).process() + "."; } function postTweet(sentence) { var tweet = { status: sentence }; twitter.post('statuses/update', tweet , function(err, data, response) { if (err) { // console.log("5OMeTh1nG weNt wR0ng"); } else { // console.log("Tweet sucessful"); } }); } postTweet(generateSentence); // second parameter is in miliseconds setInterval(postTweet(generateSentence), 1000*60*60*11);
Switch back to emscripten incoming Fixes #23
const fs = require("fs"); const path = require("path"); const dependencyUtils = require("../../compiler/scripts/dependency-utils"); const EMSCRIPTEN_GIT_URL = "https://github.com/kripken/emscripten.git"; // TODO Switch to emsdk if web assembly backend is included function buildEmscripten(directory) { console.log("Build Emscripten"); const emscriptenDirectory = path.join(directory, "emscripten"); dependencyUtils.gitCloneOrPull(EMSCRIPTEN_GIT_URL, emscriptenDirectory); dependencyUtils.exec("git -C %s checkout incoming", emscriptenDirectory); return emscriptenDirectory; } function install(directory) { if (process.env.EMSCRIPTEN) { fs.symlinkSync(process.env.EMSCRIPTEN, path.join(directory, "emscripten"), "directory"); return process.env.EMSCRIPTEN; } return buildEmscripten(directory); } module.exports = { install: install };
const fs = require("fs"); const path = require("path"); const dependencyUtils = require("../../compiler/scripts/dependency-utils"); const EMSCRIPTEN_GIT_URL = "https://github.com/kripken/emscripten.git"; // TODO Switch to emsdk if web assembly backend is included function buildEmscripten(directory) { console.log("Build Emscripten"); const emscriptenDirectory = path.join(directory, "emscripten"); dependencyUtils.gitCloneOrPull(EMSCRIPTEN_GIT_URL, emscriptenDirectory); // dependencyUtils.exec("git -C %s checkout incoming", emscriptenDirectory); dependencyUtils.exec("git -C %s checkout d1a1fc121b7d6aab9adcb0c418453d48be318754", emscriptenDirectory); // use last working until #23 is fixed return emscriptenDirectory; } function install(directory) { if (process.env.EMSCRIPTEN) { fs.symlinkSync(process.env.EMSCRIPTEN, path.join(directory, "emscripten"), "directory"); return process.env.EMSCRIPTEN; } return buildEmscripten(directory); } module.exports = { install: install };
Fix failing python style test
#!/usr/bin/env python # -*- coding: utf-8 -*- ############################################################################### # Copyright Kitware 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. ############################################################################### from girder.api import access from girder.api.describe import Description from girder.api.rest import Resource class CustomAppRoot(object): """ The webroot endpoint simply serves the main index HTML file. """ exposed = True def GET(self): return "hello world" class Other(Resource): def __init__(self): self.resourceName = 'other' self.route('GET', (), self.getResource) @access.public def getResource(self, params): return ['custom REST route'] getResource.description = Description('Get something.') def load(info): info['serverRoot'], info['serverRoot'].girder = ( CustomAppRoot(), info['serverRoot']) info['serverRoot'].api = info['serverRoot'].girder.api del info['serverRoot'].girder.api info['apiRoot'].other = Other()
#!/usr/bin/env python # -*- coding: utf-8 -*- ############################################################################### # Copyright Kitware 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. ############################################################################### from girder.api import access from girder.api.describe import Description from girder.api.rest import Resource class CustomAppRoot(object): """ The webroot endpoint simply serves the main index HTML file. """ exposed = True def GET(self): return "hello world" class Other(Resource): def __init__(self): self.resourceName = 'other' self.route('GET', (), self.getResource) @access.public def getResource(self, params): return ['custom REST route'] getResource.description = Description('Get something.') def load(info): info['serverRoot'], info['serverRoot'].girder = CustomAppRoot(), info['serverRoot'] info['serverRoot'].api = info['serverRoot'].girder.api del info['serverRoot'].girder.api info['apiRoot'].other = Other()
Use fake email for test.
<?php use Illuminate\Database\Seeder; class UserTableSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { DB::table('user')->insert([ 'name' => 'Guo Yunhe', 'email' => 'yunhe.guo@example.com', 'password' => bcrypt('abcd123456'), ]); DB::table('user')->insert([ 'name' => 'Du Yuexin', 'email' => 'yuexin.du@example.com', 'password' => bcrypt('abcd123456'), ]); DB::table('user')->insert([ 'name' => 'Yun Xiaotong', 'email' => 'xiaotong.yun@example.com', 'password' => bcrypt('abcd123456'), ]); } }
<?php use Illuminate\Database\Seeder; class UserTableSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { DB::table('user')->insert([ 'name' => 'Guo Yunhe', 'email' => 'yunhe.guo@santakani.com', 'password' => bcrypt('abcd123456'), ]); DB::table('user')->insert([ 'name' => 'Du Yuexin', 'email' => 'yuexin.du@santakani.com', 'password' => bcrypt('abcd123456'), ]); DB::table('user')->insert([ 'name' => 'Yun Xiaotong', 'email' => 'xiaotong.yun@santakani.com', 'password' => bcrypt('abcd123456'), ]); } }
Test delete does in fact delete requested row closes #13
<?php /** * Tests deleting existing rows from a CSV file. * * http://github.com/g105b/phpcsv * @copyright Copyright Ⓒ 2015 Bright Flair Ltd. (http://brightflair.com) * @license http://www.opensource.org/licenses/mit-license.php MIT */ namespace g105b\phpcsv; class DeleteRecord_Test extends \PHPUnit_Framework_TestCase { public function tearDown() { TestHelper::removeDir(TestHelper::getTempPath()); } /** * @dataProvider \g105b\phpcsv\TestHelper::data_randomFilePath */ public function testDeleteSingleRow($filePath) { TestHelper::createCsv($filePath, 10); $csv = new Csv($filePath); $allRows = $csv->getAll(); $csv->deleteRow(2); $allRowsAfterDelete = $csv->getAll(); $this->assertNotSameSize($allRowsAfterDelete, $allRows, "Rows should not be same size after delete"); $this->assertCount(count($allRows) - 1, $allRowsAfterDelete, "Should be -1 row after delete"); } /** * @dataProvider \g105b\phpcsv\TestHelper::data_randomFilePath */ public function testDeleteRemovesExpectedRow($filePath) { TestHelper::createCsv($filePath); $csv = new Csv($filePath); $rowThree = $csv->get(3); $allRows = $csv->getAll(); $this->assertContains($rowThree, $allRows); $csv->deleteRow(3); $allRowsAfterDelete = $csv->getAll(); $this->assertNotContains($rowThree, $allRowsAfterDelete); } }#
<?php /** * Tests deleting existing rows from a CSV file. * * http://github.com/g105b/phpcsv * @copyright Copyright Ⓒ 2015 Bright Flair Ltd. (http://brightflair.com) * @license http://www.opensource.org/licenses/mit-license.php MIT */ namespace g105b\phpcsv; class DeleteRecord_Test extends \PHPUnit_Framework_TestCase { public function tearDown() { TestHelper::removeDir(TestHelper::getTempPath()); } /** * @dataProvider \g105b\phpcsv\TestHelper::data_randomFilePath */ public function testDeleteSingleRow($filePath) { TestHelper::createCsv($filePath, 10); $csv = new Csv($filePath); $allRows = $csv->getAll(); $csv->deleteRow(2); $allRowsAfterDelete = $csv->getAll(); $this->assertNotSameSize($allRowsAfterDelete, $allRows, "Rows should not be same size after delete"); $this->assertCount(count($allRows) - 1, $allRowsAfterDelete, "Should be -1 row after delete"); } }#
Replace trailing whitespaces for example code.
"use strict"; function simplePassing() { describe('test embedded mocha', function() { it('should run jasmine-style tests', function() { expect(1) .toBe(1); }); it('should run should-style tests', function() { should(1).ok; }); }); } function simpleFailing() { describe('test embedded mocha', function() { it('should fail', function() { expect(1) .toBe(2); }); }); } // Make sure the code block starts with no indentation. function _replaceTrailingWhitespaces(lines) { var firstLineTrailingSpaces = lines[1].match(/^[\s\t]+/); if (firstLineTrailingSpaces) { lines = lines.map(function(line) { return line.replace(firstLineTrailingSpaces, ''); }); } return lines; } function getSourceFrom(func) { var lines = func.toString().split('\n'); lines = _replaceTrailingWhitespaces(lines); return lines.slice(1, -1).join('\n'); } module.exports = { simplePassingTestCode: getSourceFrom(simplePassing), simpleFailingTestCode: getSourceFrom(simpleFailing) };
"use strict"; function simplePassing() { describe('test embedded mocha', function() { it('should run jasmine-style tests', function() { expect(1) .toBe(1); }); it('should run should-style tests', function() { should(1).ok; }); }); } function simpleFailing() { describe('test embedded mocha', function() { it('should fail', function() { expect(1) .toBe(2); }); }); } function getSourceFrom(func) { var lines = func.toString().split('\n'); return lines.slice(1, -1).join('\n'); } module.exports = { simplePassingTestCode: getSourceFrom(simplePassing), simpleFailingTestCode: getSourceFrom(simpleFailing) };
Use any version of rotonde-core
import fs from 'fs-extra'; import path from 'path'; import { spawn } from 'child_process'; const directory = path.join(__dirname, '../dist'); fs.mkdirs(directory, err => { if (err) { throw err; } const packageJsonPath = path.join(directory, 'package.json'); const packageJson = { name: 'rotonde', scripts: { start: 'node index.js' }, dependencies: { 'rotonde-core': '*' } }; fs.writeFile(path.join(directory, 'index.js'), `require('rotonde-core/lib/index');`, err => { fs.writeJson(packageJsonPath, packageJson, err => { if (err) { throw err; } const now = spawn('now', [ directory ], { stdio: 'inherit' }); now.on('close', code => { console.log('done'); }); }); }); });
import fs from 'fs-extra'; import path from 'path'; import { spawn } from 'child_process'; const directory = path.join(__dirname, '../dist'); fs.mkdirs(directory, err => { if (err) { throw err; } const packageJsonPath = path.join(directory, 'package.json'); const packageJson = { name: 'rotonde', scripts: { start: 'node index.js' }, dependencies: { 'rotonde-core': '^1.0.0' } }; fs.writeFile(path.join(directory, 'index.js'), `require('rotonde-core/lib/index');`, err => { fs.writeJson(packageJsonPath, packageJson, err => { if (err) { throw err; } const now = spawn('now', [ directory ], { stdio: 'inherit' }); now.on('close', code => { console.log('done'); }); }); }); });
Fix potential NPE in grenade spell.
package com.elmakers.mine.bukkit.plugins.magic.spells; import org.bukkit.Location; import org.bukkit.block.Block; import org.bukkit.entity.EntityType; import org.bukkit.entity.TNTPrimed; import org.bukkit.util.Vector; import com.elmakers.mine.bukkit.plugins.magic.Spell; import com.elmakers.mine.bukkit.plugins.magic.SpellResult; import com.elmakers.mine.bukkit.utilities.borrowed.ConfigurationNode; public class GrenadeSpell extends Spell { int defaultSize = 6; @Override public SpellResult onCast(ConfigurationNode parameters) { int size = parameters.getInt("size", defaultSize); size = (int)(playerSpells.getPowerMultiplier() * size); int fuse = parameters.getInt("fuse", 80); boolean useFire = parameters.getBoolean("fire", false); Block target = getNextBlock(); if (target == null) { return SpellResult.NO_TARGET; } Location loc = target.getLocation(); TNTPrimed grenade = (TNTPrimed)player.getWorld().spawnEntity(loc, EntityType.PRIMED_TNT); if (grenade == null) { return SpellResult.FAILURE; } Vector aim = getAimVector(); grenade.setVelocity(aim); grenade.setYield(size); grenade.setFuseTicks(fuse); grenade.setIsIncendiary(useFire); return SpellResult.SUCCESS; } }
package com.elmakers.mine.bukkit.plugins.magic.spells; import org.bukkit.Location; import org.bukkit.block.Block; import org.bukkit.entity.EntityType; import org.bukkit.entity.TNTPrimed; import org.bukkit.util.Vector; import com.elmakers.mine.bukkit.plugins.magic.Spell; import com.elmakers.mine.bukkit.plugins.magic.SpellResult; import com.elmakers.mine.bukkit.utilities.borrowed.ConfigurationNode; public class GrenadeSpell extends Spell { int defaultSize = 6; @Override public SpellResult onCast(ConfigurationNode parameters) { int size = parameters.getInt("size", defaultSize); size = (int)(playerSpells.getPowerMultiplier() * size); int fuse = parameters.getInt("fuse", 80); boolean useFire = parameters.getBoolean("fire", false); Block target = getNextBlock(); Location loc = target.getLocation(); TNTPrimed grenade = (TNTPrimed)player.getWorld().spawnEntity(loc, EntityType.PRIMED_TNT); Vector aim = getAimVector(); grenade.setVelocity(aim); grenade.setYield(size); grenade.setFuseTicks(fuse); grenade.setIsIncendiary(useFire); return SpellResult.SUCCESS; } }
Update Dotenv config to the new version
<?php declare(strict_types=1); /* * This file is part of gpupo/common * Created by Gilmar Pupo <contact@gpupo.com> * For the information of copyright and license you should read the file * LICENSE which is distributed with this source code. * Para a informação dos direitos autorais e de licença você deve ler o arquivo * LICENSE que é distribuído com este código-fonte. * Para obtener la información de los derechos de autor y la licencia debe leer * el archivo LICENSE que se distribuye con el código fuente. * For more information, see <https://opensource.gpupo.com/>. * */ use Symfony\Component\Dotenv\Dotenv; if (!class_exists('\Gpupo\Common\Console\Application')) { require __DIR__.'/../vendor/autoload.php'; } if (!class_exists(Dotenv::class)) { throw new RuntimeException('Please run "composer require symfony/dotenv" to load the ".env" files configuring the application.'); } // load all the .env files (new Dotenv(true))->loadEnv(dirname(__DIR__).'/.env');
<?php declare(strict_types=1); /* * This file is part of gpupo/common * Created by Gilmar Pupo <contact@gpupo.com> * For the information of copyright and license you should read the file * LICENSE which is distributed with this source code. * Para a informação dos direitos autorais e de licença você deve ler o arquivo * LICENSE que é distribuído com este código-fonte. * Para obtener la información de los derechos de autor y la licencia debe leer * el archivo LICENSE que se distribuye con el código fuente. * For more information, see <https://opensource.gpupo.com/>. * */ use Symfony\Component\Dotenv\Dotenv; if (!class_exists('\Gpupo\Common\Console\Application')) { require __DIR__.'/../vendor/autoload.php'; } if (!class_exists(Dotenv::class)) { throw new RuntimeException('Please run "composer require symfony/dotenv" to load the ".env" files configuring the application.'); } // load all the .env files (new Dotenv())->loadEnv(dirname(__DIR__).'/.env');
Add CHANGELOG.MD to copy-misc-files task
const inlineNg2Template = require('gulp-inline-ng2-template'); const gulp = require('gulp'); const clean = require('gulp-clean'); const tmpDir = './tmp'; const distDir = './dist'; gulp.task('inline-templates', ['clean-tmp'], function () { return gulp.src('./src/**/*.ts') .pipe(inlineNg2Template({ base: '/src', target: 'es6', useRelativePaths: true })) .pipe(gulp.dest(tmpDir)); }); gulp.task('clean-tmp', function () { return gulp.src(tmpDir, { read: false }) .pipe(clean()); }); gulp.task('clean-dist', function () { return gulp.src(distDir, { read: false }) .pipe(clean()); }); gulp.task('copy-package-json', function () { return gulp.src('package.json') .pipe(gulp.dest(distDir)); }); gulp.task('copy-misc-files', function () { return gulp.src(['README.MD', 'LICENSE', 'CHANGELOG.MD']) .pipe(gulp.dest(distDir)); }); gulp.task('copy-all', ['copy-package-json', 'copy-misc-files']);
const inlineNg2Template = require('gulp-inline-ng2-template'); const gulp = require('gulp'); const clean = require('gulp-clean'); const tmpDir = './tmp'; const distDir = './dist'; gulp.task('inline-templates', ['clean-tmp'], function () { return gulp.src('./src/**/*.ts') .pipe(inlineNg2Template({ base: '/src', target: 'es6', useRelativePaths: true })) .pipe(gulp.dest(tmpDir)); }); gulp.task('clean-tmp', function () { return gulp.src(tmpDir, { read: false }) .pipe(clean()); }); gulp.task('clean-dist', function () { return gulp.src(distDir, { read: false }) .pipe(clean()); }); gulp.task('copy-package-json', function () { return gulp.src('package.json') .pipe(gulp.dest(distDir)); }); gulp.task('copy-misc-files', function () { return gulp.src(['README.MD', 'LICENSE']) .pipe(gulp.dest(distDir)); }); gulp.task('copy-all', ['copy-package-json', 'copy-misc-files']);
Update lline 15 and 21 It's about the dummy string replacement.
function r_d(a) { "use strict"; var b = a.slice(), //copy array i = 0, k = 0, length = b.length, j, buffer = []; //splicing same elements for (i; i < length; i++) { j = 0; for (j; j < length; j++) { if (i < j && b[j] === b[i]) { b.splice(j, 1, j + " (deleted)"); //added token the "original element + (deleted)" string } } } //removing "deleted" elements for (k; k < length; k++) { if (!b[k].toString().match("(deleted)")) { //if it matches the string "(deleted)" buffer.push(b[k]); } } //return reconstructed array return buffer; }
function r_d(a) { "use strict"; var b = a.slice(), //copy array i = 0, k = 0, length = b.length, j, buffer = []; //splicing same elements for (i; i < length; i++) { j = 0; for (j; j < length; j++) { if (i < j && b[j] === b[i]) { b.splice(j, 1, "deleted"); } } } //removing "deleted" elements for (k; k < length; k++) { if (b[k] !== "deleted") { buffer.push(b[k]); } } //return reconstructed array return buffer; }
Change of second error message
"use strict"; var utils = require("../utils"); var log = require("npmlog"); module.exports = function(defaultFuncs, api, ctx) { return function changeNickname(nickname, threadID, participantID, callback) { var form = { 'nickname': nickname, 'participant_id': participantID, 'thread_or_other_fbid': threadID }; defaultFuncs .post("https://www.messenger.com/messaging/save_thread_nickname/?source=thread_settings&dpr=1", ctx.jar, form) .then(utils.parseAndCheckLogin(ctx.jar, defaultFuncs)) .then(function(resData) { if (resData.error === 1545014) { throw {error: "Trying to change nickname of user isn't in thread"}; } if (resData.error === 1357031) { throw {error: "Trying to change user nickname of a thread that doesn't exist. Have at least one message in the thread before trying to change the user nickname."}; } if (resData.error) { throw resData; } return callback(); }) .catch(function(err) { log.error("Error in changeNickname", err); return callback(err); }); }; };
"use strict"; var utils = require("../utils"); var log = require("npmlog"); module.exports = function(defaultFuncs, api, ctx) { return function changeNickname(nickname, threadID, participantID, callback) { var form = { 'nickname': nickname, 'participant_id': participantID, 'thread_or_other_fbid': threadID }; defaultFuncs .post("https://www.messenger.com/messaging/save_thread_nickname/?source=thread_settings&dpr=1", ctx.jar, form) .then(utils.parseAndCheckLogin(ctx.jar, defaultFuncs)) .then(function(resData) { if (resData.error === 1545014) { throw {error: "Trying to change nickname of user isn't in thread"}; } if (resData.error === 1357031) { throw {error: "Trying to change user nickname of a chat that doesn't exist. Have at least one message in the thread before trying to change the user nickname."}; } if (resData.error) { throw resData; } return callback(); }) .catch(function(err) { log.error("Error in changeNickname", err); return callback(err); }); }; };
Add checkTypeAs() to simplify the code/tests.
package atlas import ( "errors" ) var ( allTypes = []string{ "dns", "ntp", "ping", "sslcert", "traceroute", "wifi", } ) var ErrInvalidMeasurementType = errors.New("invalid measurement type") // checkType verify that the type is valid func checkType(d Definition) (valid bool) { valid = false for _, t := range allTypes { if d.Type == t { valid = true break } } return } // checkTypeAs is a shortcut func checkTypeAs(d Definition, t string) (valid bool) { valid = true if checkType(d) && d.Type != t { valid = false } return } // DNS creates a measurement func DNS(d Definition) (m *Measurement, err error) { if checkType(d) || d.Type != "dns" { err = ErrInvalidMeasurementType return } return } // NTP creates a measurement func NTP(d Definition) (m *Measurement, err error) { return } // Ping creates a measurement func Ping(d Definition) (m *Measurement, err error) { return } // SSLCert creates a measurement func SSLCert(d Definition) (m *Measurement, err error) { return } // Traceroute creates a measurement func Traceroute(d Definition) (m *Measurement, err error) { return }
package atlas import ( "errors" ) var ( allTypes = []string{ "dns", "ntp", "ping", "sslcert", "traceroute", "wifi", } ) var ErrInvalidMeasurementType = errors.New("invalid measurement type") // checkType verify that the type is valid func checkType(d Definition) (valid bool) { valid = false for _, t := range allTypes { if d.Type == t { valid = true break } } return } // DNS creates a measurement func DNS(d Definition) (m *Measurement, err error) { if checkType(d) || d.Type != "dns" { err = ErrInvalidMeasurementType return } return } // NTP creates a measurement func NTP(d Definition) (m *Measurement, err error) { return } // Ping creates a measurement func Ping(d Definition) (m *Measurement, err error) { return } // SSLCert creates a measurement func SSLCert(d Definition) (m *Measurement, err error) { return } // Traceroute creates a measurement func Traceroute(d Definition) (m *Measurement, err error) { return }
Add site footer to each documentation generator
var _ = require('lodash') var fs = require('fs') var gzip = require('gzip-size') var filesize = require('filesize') var cssstats = require('cssstats') var module = require('tachyons-borders/package.json') var moduleCss = fs.readFileSync('node_modules/tachyons-borders/tachyons-borders.min.css', 'utf8') var moduleObj = cssstats(moduleCss) var moduleSize = filesize(moduleObj.gzipSize) var srcCSS = fs.readFileSync('./src/_borders.css', 'utf8') var navDocs = fs.readFileSync('./templates/nav_docs.html', 'utf8') var siteFooter = fs.readFileSync('./templates/footer.html', 'utf8') var template = fs.readFileSync('./templates/docs/borders/index.html', 'utf8') var tpl = _.template(template) var html = tpl({ moduleVersion: module.version, moduleSize: moduleSize, moduleObj: moduleObj, srcCSS: srcCSS, navDocs: navDocs, siteFooter: siteFooter }) fs.writeFileSync('./docs/themes/borders/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-borders/package.json') var moduleCss = fs.readFileSync('node_modules/tachyons-borders/tachyons-borders.min.css', 'utf8') var moduleObj = cssstats(moduleCss) var moduleSize = filesize(moduleObj.gzipSize) var srcCSS = fs.readFileSync('./src/_borders.css', 'utf8') var navDocs = fs.readFileSync('./templates/nav_docs.html', 'utf8') var template = fs.readFileSync('./templates/docs/borders/index.html', 'utf8') var tpl = _.template(template) var html = tpl({ moduleVersion: module.version, moduleSize: moduleSize, moduleObj: moduleObj, srcCSS: srcCSS, navDocs: navDocs }) fs.writeFileSync('./docs/themes/borders/index.html', html)
Add arg --https even for non-443.
import gevent.monkey gevent.monkey.patch_all() import logging handler = logging.StreamHandler() log_format = '{levelname}:etiquette.{module}.{funcName}: {message}' handler.setFormatter(logging.Formatter(log_format, style='{')) logging.getLogger().addHandler(handler) import etiquette_flask import gevent.pywsgi import gevent.wsgi import sys import werkzeug.contrib.fixers etiquette_flask.site.wsgi_app = werkzeug.contrib.fixers.ProxyFix(etiquette_flask.site.wsgi_app) if len(sys.argv) >= 2: port = int(sys.argv[1]) else: port = 5000 use_https = (port == 443) or ('--https' in sys.argv) if use_https: http = gevent.pywsgi.WSGIServer( listener=('0.0.0.0', port), application=etiquette_flask.site, keyfile='D:\\git\\etiquette\\frontends\\etiquette_flask\\https\\etiquette.key', certfile='D:\\git\\etiquette\\frontends\\etiquette_flask\\https\\etiquette.crt', ) else: http = gevent.pywsgi.WSGIServer( listener=('0.0.0.0', port), application=etiquette_flask.site, ) message = 'Starting server on port %d' % port if use_https: message += ' (https)' print(message) http.serve_forever()
import gevent.monkey gevent.monkey.patch_all() import logging handler = logging.StreamHandler() log_format = '{levelname}:etiquette.{module}.{funcName}: {message}' handler.setFormatter(logging.Formatter(log_format, style='{')) logging.getLogger().addHandler(handler) import etiquette_flask import gevent.pywsgi import gevent.wsgi import sys import werkzeug.contrib.fixers etiquette_flask.site.wsgi_app = werkzeug.contrib.fixers.ProxyFix(etiquette_flask.site.wsgi_app) if len(sys.argv) == 2: port = int(sys.argv[1]) else: port = 5000 if port == 443: http = gevent.pywsgi.WSGIServer( listener=('0.0.0.0', port), application=etiquette_flask.site, keyfile='D:\\git\\etiquette\\frontends\\etiquette_flask\\https\\etiquette.key', certfile='D:\\git\\etiquette\\frontends\\etiquette_flask\\https\\etiquette.crt', ) else: http = gevent.pywsgi.WSGIServer( listener=('0.0.0.0', port), application=etiquette_flask.site, ) print('Starting server on port %d' % port) http.serve_forever()
Change the new line in file to match results from Avetmiss
<?php namespace Avetmiss; use Avetmiss\Row; class File { protected $rows = array(); protected $time; public function __construct() { $this->time = time(); } /** * Add a row to the file */ public function addRow(Row $row) { if(!$row->isValid()) { throw new \Exception('Cant add invalid row'); } $this->rows[] = $row; } /** * Exports the rows to a file */ public function export($name) { $file = fopen($name, 'w'); foreach($this->rows as $row) { fwrite($file, $row ."\r\n"); } fclose($file); } public function getTime() { return time() - $this->time; } }
<?php namespace Avetmiss; use Avetmiss\Row; class File { protected $rows = array(); protected $time; public function __construct() { $this->time = time(); } /** * Add a row to the file */ public function addRow(Row $row) { if(!$row->isValid()) { throw new \Exception('Cant add invalid row'); } $this->rows[] = $row; } /** * Exports the rows to a file */ public function export($name) { $file = fopen($name, 'w'); foreach($this->rows as $row) { fwrite($file, $row ."\n"); } fclose($file); } public function getTime() { return time() - $this->time; } }
Fix extra line in package class
package com.gitrekt.resort.model.entities; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name = "resort.packages") public class Package { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(name = "name") private String name; @Column(name = "price_per_person") private double pricePerPerson; public Package(String name, double pricePerPerson){ this.name = name; this.pricePerPerson = pricePerPerson; } public String getName(){ return name; } public double getPricePerPerson(){ return pricePerPerson; } }
package com.gitrekt.resort.model.entities; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name = "resort.packages") public class Package { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(name = "name") private String name; @Column(name = "price_per_person") private double pricePerPerson; public Package(String name, double pricePerPerson){ this.name = name; this.pricePerPerson = pricePerPerson; } public String getName(){ return name; } //Returns the price rate per person for the package public double getPricePerPerson(){ return pricePerPerson; } }
Rename reset_url to revoke url
(function (window) { "use strict"; var setts = { "SERVER_URL": "http://localhost:8061/", "CREDZ": { "client_id": "5O1KlpwBb96ANWe27ZQOpbWSF4DZDm4sOytwdzGv", "client_secret": "PqV0dHbkjXAtJYhY9UOCgRVi5BzLhiDxGU91" + "kbt5EoayQ5SYOoJBYRYAYlJl2RetUeDMpSvh" + "e9DaQr0HKHan0B9ptVyoLvOqpekiOmEqUJ6H" + "ZKuIoma0pvqkkKDU9GPv", "token_url": "o/token/", "revoke_url": "o/revoke_token" } }; setts.CREDZ.token_url = setts.SERVER_URL + setts.CREDZ.token_url; setts.CREDZ.revoke_url = setts.SERVER_URL + setts.CREDZ.revoke_url; window.MFL_SETTINGS = setts; })(window);
(function (window) { "use strict"; var setts = { "SERVER_URL": "http://localhost:8061/", "CREDZ": { "client_id": "5O1KlpwBb96ANWe27ZQOpbWSF4DZDm4sOytwdzGv", "client_secret": "PqV0dHbkjXAtJYhY9UOCgRVi5BzLhiDxGU91" + "kbt5EoayQ5SYOoJBYRYAYlJl2RetUeDMpSvh" + "e9DaQr0HKHan0B9ptVyoLvOqpekiOmEqUJ6H" + "ZKuIoma0pvqkkKDU9GPv", "token_url": "o/token/", "reset_url": "o/reset_token" } }; setts.CREDZ.token_url = setts.SERVER_URL + setts.CREDZ.token_url; setts.CREDZ.reset_url = setts.SERVER_URL + setts.CREDZ.reset_url; window.MFL_SETTINGS = setts; })(window);
Use / as a separator for urls
var async = require("async"); var path = require("path"); var url = require("url"); var utils = require("./lib/utils"); module.exports = function(options, callback) { utils.list_files(options, function(err, objects) { if (err) { callback(err); return; } var q = async.queue(function(translation, callback) { var local_path_split = url.parse(translation).pathname.split("/"); var local_path = path.join(options.dir, local_path_split[2], local_path_split[3]); utils.stream_url_to_file(translation, local_path, callback); }, 16); q.push(objects, function(err) { if (err) { q.tasks.length = 0; callback(err); } }); q.drain = callback; }); };
var async = require("async"); var path = require("path"); var url = require("url"); var utils = require("./lib/utils"); module.exports = function(options, callback) { utils.list_files(options, function(err, objects) { if (err) { callback(err); return; } var q = async.queue(function(translation, callback) { var local_path_split = url.parse(translation).pathname.split(path.sep); var local_path = path.join(options.dir, local_path_split[2], local_path_split[3]); utils.stream_url_to_file(translation, local_path, callback); }, 16); q.push(objects, function(err) { if (err) { q.tasks.length = 0; callback(err); } }); q.drain = callback; }); };
Fix lirear regression model loss calculation
import random from keras.models import Sequential from keras.layers import Dense, Activation import numpy as np def generate_data(size): """" x_train = [] y_train = [] for i in range(size): x = random.randint(0, 100) y = 2*x x_train.append(x) y_train.append(y) return np.array(x_train), np.array(y_train) """ import numpy as np #data = np.random.random((10000, 100)) #labels = np.random.randint(2, size=(10000, 1)) #data = np.random.random((10000, 2)) #labels = np.sum(data, (1,)) data = np.random.random((10000, 1)) labels = data*2 return data, labels model = Sequential() model.add(Dense(1, input_dim=1)) model.compile(optimizer='rmsprop', loss='mse', metrics=['accuracy']) x_train, y_train = generate_data(10000) x_test, y_test = generate_data(100) model.fit(x_train, y_train, epochs=30, batch_size=32) loss_and_metrics = model.evaluate(x_test, y_test, batch_size=16) #print(loss_and_metrics) pred = model.predict(x_test, batch_size=32, verbose=0) print("expected:") print(y_test) print("actual:") print(pred)
import random from keras.models import Sequential from keras.layers import Dense, Activation import numpy as np def generate_data(size): """" x_train = [] y_train = [] for i in range(size): x = random.randint(0, 100) y = 2*x x_train.append(x) y_train.append(y) return np.array(x_train), np.array(y_train) """ import numpy as np #data = np.random.random((10000, 100)) #labels = np.random.randint(2, size=(10000, 1)) data = np.random.random((10000, 1)) labels = data*2 return data, labels model = Sequential() model.add(Dense(1, input_dim=1)) model.compile(optimizer='rmsprop', loss='binary_crossentropy', metrics=['accuracy']) x_train, y_train = generate_data(1000) x_test, y_test = generate_data(10) model.fit(x_train, y_train, epochs=1000, batch_size=32) loss_and_metrics = model.evaluate(x_test, y_test, batch_size=128) print(loss_and_metrics)
Add a missing semi colon and make one line < 80 chars
describe("Map", function () { describe("#whenReady", function () { describe("when the map has not yet been loaded", function () { it("calls the callback when the map is loaded", function () { var map = L.map(document.createElement('div')), spy = jasmine.createSpy(); map.whenReady(spy); expect(spy).not.toHaveBeenCalled(); map.setView([0, 0], 1); expect(spy).toHaveBeenCalled(); }); }); describe("when the map has already been loaded", function () { it("calls the callback immediately", function () { var map = L.map(document.createElement('div')), spy = jasmine.createSpy(); map.setView([0, 0], 1); map.whenReady(spy); expect(spy).toHaveBeenCalled(); }); }); }); describe("#getBounds", function () { it("is safe to call from within a moveend callback during initial " + "load (#1027)", function () { var c = document.createElement('div'), map = L.map(c); map.on("moveend", function () { map.getBounds(); }); map.setView([51.505, -0.09], 13); }); }); });
describe("Map", function () { describe("#whenReady", function () { describe("when the map has not yet been loaded", function () { it("calls the callback when the map is loaded", function () { var map = L.map(document.createElement('div')), spy = jasmine.createSpy(); map.whenReady(spy); expect(spy).not.toHaveBeenCalled(); map.setView([0, 0], 1); expect(spy).toHaveBeenCalled(); }) }); describe("when the map has already been loaded", function () { it("calls the callback immediately", function () { var map = L.map(document.createElement('div')), spy = jasmine.createSpy(); map.setView([0, 0], 1); map.whenReady(spy); expect(spy).toHaveBeenCalled(); }); }); }); describe("#getBounds", function () { it("is safe to call from within a moveend callback during initial load (#1027)", function () { var c = document.createElement('div'), map = L.map(c); map.on("moveend", function () { map.getBounds(); }); map.setView([51.505, -0.09], 13); }); }); });
Remove unused set*(Collection) methods on models
<?php /* * This file is part of the Sylius package. * * (c) Paweł Jędrzejewski * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Sylius\Component\Locale\Model; use Doctrine\Common\Collections\Collection; /** * Interface implemented by objects related to multiple locales * * @author Paweł Jędrzejewski <pawel@sylius.org> */ interface LocalesAwareInterface { /** * @return Collection|LocaleInterface[] */ public function getLocales(); /** * @param LocaleInterface $locale * * @return bool */ public function hasLocale(LocaleInterface $locale); /** * @param LocaleInterface $locale */ public function addLocale(LocaleInterface $locale); /** * @param LocaleInterface $locale */ public function removeLocale(LocaleInterface $locale); }
<?php /* * This file is part of the Sylius package. * * (c) Paweł Jędrzejewski * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Sylius\Component\Locale\Model; use Doctrine\Common\Collections\Collection; /** * Interface implemented by objects related to multiple locales * * @author Paweł Jędrzejewski <pawel@sylius.org> */ interface LocalesAwareInterface { /** * @return Collection|LocaleInterface[] */ public function getLocales(); /** * @param Collection $collection */ public function setLocales(Collection $collection); /** * @param LocaleInterface $locale * * @return bool */ public function hasLocale(LocaleInterface $locale); /** * @param LocaleInterface $locale */ public function addLocale(LocaleInterface $locale); /** * @param LocaleInterface $locale */ public function removeLocale(LocaleInterface $locale); }
Change step example to plot US postage rates
""" This example uses the U.S. postage rate per ounce for stamps and postcards. Source: https://en.wikipedia.org/wiki/History_of_United_States_postage_rates """ from bokeh.charts import Step, show, output_file # build a dataset where multiple columns measure the same thing data = dict(stamp=[ .33, .33, .34, .37, .37, .37, .37, .39, .41, .42, .44, .44, .44, .45, .46, .49, .49], postcard=[ .20, .20, .21, .23, .23, .23, .23, .24, .26, .27, .28, .28, .29, .32, .33, .34, .35], ) # create a line chart where each column of measures receives a unique color and dash style line = Step(data, y=['stamp', 'postcard'], dash=['stamp', 'postcard'], color=['stamp', 'postcard'], title="U.S. Postage Rates (1999-2015)", ylabel='Rate per ounce', legend=True) output_file("steps.html") show(line)
from bokeh.charts import Step, show, output_file # build a dataset where multiple columns measure the same thing data = dict(python=[2, 3, 7, 5, 26, 221, 44, 233, 254, 265, 266, 267, 120, 111], pypy=[12, 33, 47, 15, 126, 121, 144, 233, 254, 225, 226, 267, 110, 130], jython=[22, 43, 10, 25, 26, 101, 114, 203, 194, 215, 201, 227, 139, 160], test=['foo', 'bar', 'foo', 'bar', 'foo', 'bar', 'foo', 'bar', 'foo', 'bar', 'foo', 'bar', 'foo', 'bar'] ) # create a line chart where each column of measures receives a unique color and dash style line = Step(data, y=['python', 'pypy', 'jython'], dash=['python', 'pypy', 'jython'], color=['python', 'pypy', 'jython'], title="Interpreter Sample Data", ylabel='Duration', legend=True) output_file("steps.html") show(line)
Use "NO_PROXY" for urls that are not proxied.
package com.pr0gramm.app; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.net.InetSocketAddress; import java.net.Proxy; import java.net.ProxySelector; import java.net.SocketAddress; import java.net.URI; import java.util.Collections; import java.util.List; /** */ public class CustomProxySelector extends ProxySelector { private static final Logger logger = LoggerFactory.getLogger("CustomProxySelector"); @Override public List<Proxy> select(URI uri) { if ("pr0gramm.com".equals(uri.getHost())) { if (uri.getPath().startsWith("/api/") && !"/api/user/login".equals(uri.getPath())) { logger.info("Using proxy for {}", uri); InetSocketAddress address = new InetSocketAddress("pr0.wibbly-wobbly.de", 80); Proxy proxy = new Proxy(Proxy.Type.HTTP, address); return Collections.singletonList(proxy); } } return Collections.singletonList(Proxy.NO_PROXY); } @Override public void connectFailed(URI uri, SocketAddress address, IOException failure) { } }
package com.pr0gramm.app; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.net.InetSocketAddress; import java.net.Proxy; import java.net.ProxySelector; import java.net.SocketAddress; import java.net.URI; import java.util.Collections; import java.util.List; /** */ public class CustomProxySelector extends ProxySelector { private static final Logger logger = LoggerFactory.getLogger("CustomProxySelector"); @Override public List<Proxy> select(URI uri) { if ("pr0gramm.com".equals(uri.getHost())) { if (uri.getPath().startsWith("/api/") && !"/api/user/login".equals(uri.getPath())) { logger.info("Using proxy for {}", uri); InetSocketAddress address = new InetSocketAddress("pr0.wibbly-wobbly.de", 80); Proxy proxy = new Proxy(Proxy.Type.HTTP, address); return Collections.singletonList(proxy); } } return Collections.emptyList(); } @Override public void connectFailed(URI uri, SocketAddress address, IOException failure) { } }
Fix test spec for old browsers
define(function(require) { var test = require('../../../test') var n = 0 // 404 var a = require('./a') test.assert(a === null, '404 a') // exec error setTimeout(function() { var b = require('./b') }, 0) require.async('./c', function(c) { test.assert(c === null, '404 c') done() }) require.async('./e', function(e) { test.assert(e === null, 'exec error e') done() }) seajs.use('./d', function(d) { test.assert(d === null, '404 d') done() }) // 404 css //require('./f.css') function done() { if (++n === 3) { test.assert(w_errors.length > 0, w_errors.length) // 0 for IE6-8 test.assert(s_errors.length === 0 || s_errors.length === 3, s_errors.length) test.next() } } })
define(function(require) { var test = require('../../../test') var n = 0 // 404 var a = require('./a') test.assert(a === null, '404 a') // exec error setTimeout(function() { var b = require('./b') }, 0) require.async('./c', function(c) { test.assert(c === null, '404 c') done() }) require.async('./e', function(e) { test.assert(e === null, 'exec error e') done() }) seajs.use('./d', function(d) { test.assert(d === null, '404 d') done() }) // 404 css //require('./f.css') function done() { if (++n === 3) { test.assert(w_errors.length > 0, w_errors.length) test.assert(s_errors.length === 3, s_errors.length) test.next() } } })
Remove user slice since since not used
import React from "react"; import { render } from "react-dom"; import ProjectSamples from "./components/ProjectSamples"; import { configureStore } from "@reduxjs/toolkit"; import { setupListeners } from "@reduxjs/toolkit/query"; import { Provider } from "react-redux"; import { samplesApi } from "../../../apis/projects/samples"; import { associatedProjectsApi } from "../../../apis/projects/associated-projects"; import samplesReducer from "../redux/samplesSlice"; import { projectApi } from "../../../apis/projects/project"; export const store = configureStore({ reducer: { samples: samplesReducer, [projectApi.reducerPath]: projectApi.reducer, [samplesApi.reducerPath]: samplesApi.reducer, [associatedProjectsApi.reducerPath]: associatedProjectsApi.reducer, }, middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat( samplesApi.middleware, associatedProjectsApi.middleware ), devTools: process.env.NODE_ENV !== "production", }); setupListeners(store.dispatch); render( <Provider store={store}> <ProjectSamples /> </Provider>, document.getElementById("root") );
import React from "react"; import { render } from "react-dom"; import ProjectSamples from "./components/ProjectSamples"; import { configureStore } from "@reduxjs/toolkit"; import { setupListeners } from "@reduxjs/toolkit/query"; import { Provider } from "react-redux"; import { samplesApi } from "../../../apis/projects/samples"; import { associatedProjectsApi } from "../../../apis/projects/associated-projects"; import samplesReducer from "../redux/samplesSlice"; import userReducer from "../redux/userSlice"; import { projectApi } from "../../../apis/projects/project"; export const store = configureStore({ reducer: { user: userReducer, samples: samplesReducer, [projectApi.reducerPath]: projectApi.reducer, [samplesApi.reducerPath]: samplesApi.reducer, [associatedProjectsApi.reducerPath]: associatedProjectsApi.reducer, }, middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat( samplesApi.middleware, associatedProjectsApi.middleware ), devTools: process.env.NODE_ENV !== "production", }); setupListeners(store.dispatch); render( <Provider store={store}> <ProjectSamples /> </Provider>, document.getElementById("root") );
Update checkout zone script to unlock entities if they are locked before leaving
// // shopZone.js // // Created by Thijs Wenker on 10/20/17. // Copyright 2017 High Fidelity, Inc. // // Distributed under the Apache License, Version 2.0. // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // (function () { var shared = Script.require('../attachmentZoneShared.js'); this.leaveEntity = function (entityID) { shared.getAvatarChildEntities(MyAvatar).forEach(function (entityID) { var properties = Entities.getEntityProperties(entityID, ['clientOnly', 'userData', 'locked']); try { var isAttachment = JSON.parse(properties.userData).Attachment !== undefined; if (properties.locked) { print("Entity locked"); Entities.editEntity(entityID, {"locked" : false}); } if (isAttachment && !properties.clientOnly) { Entities.deleteEntity(entityID); } } catch (e) { // e } }); }; });
// // shopZone.js // // Created by Thijs Wenker on 10/20/17. // Copyright 2017 High Fidelity, Inc. // // Distributed under the Apache License, Version 2.0. // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // (function () { var shared = Script.require('../attachmentZoneShared.js'); this.leaveEntity = function (entityID) { shared.getAvatarChildEntities(MyAvatar).forEach(function (entityID) { var properties = Entities.getEntityProperties(entityID, ['clientOnly', 'userData']); try { var isAttachment = JSON.parse(properties.userData).Attachment !== undefined; if (isAttachment && !properties.clientOnly) { Entities.deleteEntity(entityID); } } catch (e) { // e } }); }; });
Change name of spot() to spot2()
<?php namespace Ronanchilvers\Silex\Application; /** * Simple utility trait for the Silex\Application object. * * This trait provides some useful shortcut methods for getting the spot locator * and accessing data mappers. * * @author Ronan Chilvers <ronan@d3r.com> */ trait Spot2Trait { /** * Get the spot2 locator. * * @return Spot\Locator * * @author Ronan Chilvers <ronan@d3r.com> */ public function spot2() { return $this['spot2.locator']; } /** * Get a mapper for a given entity. * * @param string $entityName * * @return Spot\Mapper * * @author Ronan Chilvers <ronan@d3r.com> */ public function mapper($entityName) { if (!class_exists($entityName)) { throw new \Exception('Unable to get mapper for unknown entity class '.$entityName); } $locator = $this['spot2.locator']; return $locator->mapper($entityName); } }
<?php namespace Ronanchilvers\Silex\Application; /** * Simple utility trait for the Silex\Application object. * * This trait provides some useful shortcut methods for getting the spot locator * and accessing data mappers. * * @author Ronan Chilvers <ronan@d3r.com> */ trait Spot2Trait { /** * Get the spot2 locator. * * @return Spot\Locator * * @author Ronan Chilvers <ronan@d3r.com> */ public function spot() { return $this['spot2.locator']; } /** * Get a mapper for a given entity. * * @param string $entityName * * @return Spot\Mapper * * @author Ronan Chilvers <ronan@d3r.com> */ public function mapper($entityName) { if (!class_exists($entityName)) { throw new \Exception('Unable to get mapper for unknown entity class '.$entityName); } $locator = $this['spot2.locator']; return $locator->mapper($entityName); } }
Expand home shorthand in CLI help around `THELOUNGE_HOME` environment variable
"use strict"; const colors = require("colors/safe"); const fs = require("fs"); const Helper = require("../helper"); const path = require("path"); let home; class Utils { static extraHelp() { [ "", "", " Environment variable:", "", ` THELOUNGE_HOME Path for all configuration files and folders. Defaults to ${colors.green(Helper.expandHome(Utils.defaultHome()))}.`, "", ].forEach((e) => console.log(e)); // eslint-disable-line no-console } static defaultHome() { if (home) { return home; } let distConfig; // TODO: Remove this section when releasing The Lounge v3 const deprecatedDistConfig = path.resolve(path.join( __dirname, "..", "..", ".lounge_home" )); if (fs.existsSync(deprecatedDistConfig)) { log.warn(`${colors.green(".lounge_home")} is ${colors.bold("deprecated")} and will be ignored as of The Lounge v3.`); log.warn(`Use ${colors.green(".thelounge_home")} instead.`); distConfig = deprecatedDistConfig; } else { distConfig = path.resolve(path.join( __dirname, "..", "..", ".thelounge_home" )); } home = fs.readFileSync(distConfig, "utf-8").trim(); return home; } } module.exports = Utils;
"use strict"; const colors = require("colors/safe"); const fs = require("fs"); const path = require("path"); let home; class Utils { static extraHelp() { [ "", "", " Environment variable:", "", ` THELOUNGE_HOME Path for all configuration files and folders. Defaults to ${colors.green(Utils.defaultHome())}.`, "", ].forEach((e) => console.log(e)); // eslint-disable-line no-console } static defaultHome() { if (home) { return home; } let distConfig; // TODO: Remove this section when releasing The Lounge v3 const deprecatedDistConfig = path.resolve(path.join( __dirname, "..", "..", ".lounge_home" )); if (fs.existsSync(deprecatedDistConfig)) { log.warn(`${colors.green(".lounge_home")} is ${colors.bold("deprecated")} and will be ignored as of The Lounge v3.`); log.warn(`Use ${colors.green(".thelounge_home")} instead.`); distConfig = deprecatedDistConfig; } else { distConfig = path.resolve(path.join( __dirname, "..", "..", ".thelounge_home" )); } home = fs.readFileSync(distConfig, "utf-8").trim(); return home; } } module.exports = Utils;
Apply `repr()` to values passed to `ReprBuilder.add`, too
# -*- coding: utf-8 -*- """ byceps.util.instances ~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2016 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ class ReprBuilder(object): """An instance representation builder.""" def __init__(self, instance): self.instance = instance self.attributes = [] def add_with_lookup(self, name): """Add the attribute with its value looked up on the instance.""" value = getattr(self.instance, name) return self.add(name, value) def add(self, name, value): """Add the attribute with the given value.""" return self.add_custom('{}={!r}'.format(name, value)) def add_custom(self, value): """Add a custom value.""" self.attributes.append(value) return self def build(self): """Assemble the full textual representation.""" class_name = type(self.instance).__name__ attributes = ', '.join(self.attributes) return '<{}({})>'.format(class_name, attributes)
# -*- coding: utf-8 -*- """ byceps.util.instances ~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2016 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ class ReprBuilder(object): """An instance representation builder.""" def __init__(self, instance): self.instance = instance self.attributes = [] def add_with_lookup(self, name): """Add the attribute with its value looked up on the instance.""" value = getattr(self.instance, name) return self.add(name, repr(value)) def add(self, name, value): """Add the attribute with the given value.""" return self.add_custom('{}={}'.format(name, value)) def add_custom(self, value): """Add a custom value.""" self.attributes.append(value) return self def build(self): """Assemble the full textual representation.""" class_name = type(self.instance).__name__ attributes = ', '.join(self.attributes) return '<{}({})>'.format(class_name, attributes)
PendingOwnerInviteRow: Convert `isAccepted/Declined` to tracked properties
import Component from '@ember/component'; import { inject as service } from '@ember/service'; import { tracked } from '@glimmer/tracking'; import { task } from 'ember-concurrency'; export default class PendingOwnerInviteRow extends Component { @service notifications; tagName = ''; @tracked isAccepted = false; @tracked isDeclined = false; @task(function* () { this.invite.set('accepted', true); try { yield this.invite.save(); this.isAccepted = true; } catch (error) { if (error.errors) { this.notifications.error(`Error in accepting invite: ${error.errors[0].detail}`); } else { this.notifications.error('Error in accepting invite'); } } }) acceptInvitationTask; @task(function* () { this.invite.set('accepted', false); try { yield this.invite.save(); this.isDeclined = true; } catch (error) { if (error.errors) { this.notifications.error(`Error in declining invite: ${error.errors[0].detail}`); } else { this.notifications.error('Error in declining invite'); } } }) declineInvitationTask; }
import Component from '@ember/component'; import { inject as service } from '@ember/service'; import { task } from 'ember-concurrency'; export default class PendingOwnerInviteRow extends Component { @service notifications; tagName = ''; isAccepted = false; isDeclined = false; @task(function* () { this.invite.set('accepted', true); try { yield this.invite.save(); this.set('isAccepted', true); } catch (error) { if (error.errors) { this.notifications.error(`Error in accepting invite: ${error.errors[0].detail}`); } else { this.notifications.error('Error in accepting invite'); } } }) acceptInvitationTask; @task(function* () { this.invite.set('accepted', false); try { yield this.invite.save(); this.set('isDeclined', true); } catch (error) { if (error.errors) { this.notifications.error(`Error in declining invite: ${error.errors[0].detail}`); } else { this.notifications.error('Error in declining invite'); } } }) declineInvitationTask; }
Fix sorting of experimental browser in the comparison browser picker
<?php class Browsers { static function getAll($release) { $results = array(); $types = array('desktop', 'tablet', 'mobile', 'television', 'gaming'); $db = Factory::Database(); foreach($types AS $type) { $result = $db->query(" SELECT v.platform, IFNULL(v.version,'') AS version, v.nickname, v.details, v.visible, IFNULL(p.related,p.platform) AS id, f.score FROM data_platforms AS p LEFT JOIN data_versions AS v ON (p.platform = v.platform) LEFT JOIN scores AS s ON (v.platform = s.platform AND (v.version = s.version OR (v.version IS NULL AND s.version IS NULL))) LEFT JOIN fingerprints AS f ON (f.fingerprint = s.fingerprint) WHERE FIND_IN_SET('" . $type . "',v.type) AND s.release = '" . $release . "' AND f.points != '' ORDER BY v.platform, v.status='experimental', v.status='upcoming', ISNULL(v.releasedate), v.releasedate, v.version "); while ($row = $result->fetch_object()) { $row->uid = $type . '-' . $row->platform . '-' . $row->version; $row->type = $type; $row->visible = $row->visible == '1'; $results[] = $row; } } return $results; } }
<?php class Browsers { static function getAll($release) { $results = array(); $types = array('desktop', 'tablet', 'mobile', 'television', 'gaming'); $db = Factory::Database(); foreach($types AS $type) { $result = $db->query(" SELECT v.platform, IFNULL(v.version,'') AS version, v.nickname, v.details, v.visible, IFNULL(p.related,p.platform) AS id, f.score FROM data_platforms AS p LEFT JOIN data_versions AS v ON (p.platform = v.platform) LEFT JOIN scores AS s ON (v.platform = s.platform AND (v.version = s.version OR (v.version IS NULL AND s.version IS NULL))) LEFT JOIN fingerprints AS f ON (f.fingerprint = s.fingerprint) WHERE FIND_IN_SET('" . $type . "',v.type) AND s.release = '" . $release . "' AND f.points != '' ORDER BY v.platform, ISNULL(v.releasedate), v.releasedate, v.version "); while ($row = $result->fetch_object()) { $row->uid = $type . '-' . $row->platform . '-' . $row->version; $row->type = $type; $row->visible = $row->visible == '1'; $results[] = $row; } } return $results; } }
Fix repo update when null is returned (eg, no plugin has modified the repo).
<?php # Copyright (C) 2008 John Reese # # 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. access_ensure_global_level( plugin_config_get( 'manage_threshold' ) ); $f_repo_id = gpc_get_int( 'repo_id' ); $f_repo_name = gpc_get_string( 'repo_name' ); $f_repo_url = gpc_get_string( 'repo_url' ); $t_repo = SourceRepo::load( $f_repo_id ); $t_type = SourceType($t_repo->type); $t_repo->name = $f_repo_name; $t_repo->url = $f_repo_url; $t_updated_repo = event_signal( 'EVENT_SOURCE_UPDATE_REPO', array( $t_repo ) ); if ( !is_null( $t_updated_repo ) ) { $t_updated_repo->save(); } else { $t_repo->save(); } print_successful_redirect( plugin_page( 'repo_manage_page', true ) . '&id=' . $t_repo->id );
<?php # Copyright (C) 2008 John Reese # # 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. access_ensure_global_level( plugin_config_get( 'manage_threshold' ) ); $f_repo_id = gpc_get_int( 'repo_id' ); $f_repo_name = gpc_get_string( 'repo_name' ); $f_repo_url = gpc_get_string( 'repo_url' ); $t_repo = SourceRepo::load( $f_repo_id ); $t_type = SourceType($t_repo->type); $t_repo->name = $f_repo_name; $t_repo->url = $f_repo_url; $t_repo = event_signal( 'EVENT_SOURCE_UPDATE_REPO', array( $t_repo ) ); $t_repo->save(); print_successful_redirect( plugin_page( 'repo_manage_page', true ) . '&id=' . $t_repo->id );
Fix edge case when you just loaded the binary and didn't have a command or a flag.
// +build linux darwin freebsd package cmd import ( "fmt" "log" "os" "strings" "time" ) // ReturnCurrentUTC returns the current UTC time in RFC3339 format. func ReturnCurrentUTC() string { t := time.Now().UTC() dateUpdated := (t.Format(time.RFC3339)) return dateUpdated } // SetDirection returns the direction. func SetDirection() string { args := fmt.Sprintf("%x", os.Args) direction := "main" if strings.ContainsAny(args, " ") { if strings.HasPrefix(os.Args[1], "-") { direction = "main" } else { direction = os.Args[1] } } return direction } // Log adds the global Direction to a message and sends to syslog. // Syslog is setup in main.go func Log(message, priority string) { message = fmt.Sprintf("%s: %s", Direction, message) if Verbose { time := ReturnCurrentUTC() fmt.Printf("%s: %s\n", time, message) } switch { case priority == "debug": if os.Getenv("OCTO_DEBUG") != "" { log.Print(message) } default: log.Print(message) } } // GetHostname returns the hostname. func GetHostname() string { hostname, _ := os.Hostname() return hostname }
// +build linux darwin freebsd package cmd import ( "fmt" "log" "os" "strings" "time" ) // ReturnCurrentUTC returns the current UTC time in RFC3339 format. func ReturnCurrentUTC() string { t := time.Now().UTC() dateUpdated := (t.Format(time.RFC3339)) return dateUpdated } // SetDirection returns the direction. func SetDirection() string { direction := "" if strings.HasPrefix(os.Args[1], "-") { direction = "main" } else { direction = os.Args[1] } return direction } // Log adds the global Direction to a message and sends to syslog. // Syslog is setup in main.go func Log(message, priority string) { message = fmt.Sprintf("%s: %s", Direction, message) if Verbose { time := ReturnCurrentUTC() fmt.Printf("%s: %s\n", time, message) } switch { case priority == "debug": if os.Getenv("OCTO_DEBUG") != "" { log.Print(message) } default: log.Print(message) } } // GetHostname returns the hostname. func GetHostname() string { hostname, _ := os.Hostname() return hostname }