text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Use staging for confirmation while testing
var CONTEXT_URI = process.env.CONTEXT_URI; var _ = require('underscore'); var IntentManager = function () { }; IntentManager.prototype.process = function (intent, req, res) { var redirect = function (url) { console.log("And CONTEXT URI IS ->", CONTEXT_URI); res.redirect(CONTEXT_URI + url + "?username=" + req.session.oneselfUsername); }; if (_.isEmpty(intent)) { res.redirect("/dashboard"); } else { var intentName = intent.name; var intentData = intent.data; console.log("intentName -#-#->", intentName); if (intentName === "website_signup") { res.redirect("http://www-staging.1self.co/confirmation.html"); } else if (intentName === "chart.comment") { res.redirect(intentData.url); } else { redirect("/dashboard"); } } }; module.exports = new IntentManager();
var CONTEXT_URI = process.env.CONTEXT_URI; var _ = require('underscore'); var IntentManager = function () { }; IntentManager.prototype.process = function (intent, req, res) { var redirect = function (url) { console.log("And CONTEXT URI IS ->", CONTEXT_URI); res.redirect(CONTEXT_URI + url + "?username=" + req.session.oneselfUsername); }; if (_.isEmpty(intent)) { res.redirect("/dashboard"); } else { var intentName = intent.name; var intentData = intent.data; console.log("intentName -#-#->", intentName); if (intentName === "website_signup") { res.redirect("http://1self.co/confirmation.html"); } else if (intentName === "chart.comment") { res.redirect(intentData.url); } else { redirect("/dashboard"); } } }; module.exports = new IntentManager();
Remove reset, we don't need that. Add link to forgotten password git-svn-id: 3b6cb4556d214d66df54bca2662d7ef408f367bf@4327 46e82423-29d8-e211-989e-002590a4cdd4
<?php # # $Id: login.php,v 1.3 2010-09-17 14:44:38 dan Exp $ # # Copyright (c) 1998-2003 DVL Software Limited # if (IsSet($_GET['origin'])) $origin = $_GET["origin"]; ?> <form action="<?php echo $_SERVER["PHP_SELF"] . "?origin=$origin" ?>" method="POST" name="l"> <input type="hidden" name="custom_settings" value="1"><input type="hidden" name="LOGIN" value="1"> <p>User ID:<br> <input SIZE="15" NAME="UserID" value="<?php if (IsSet($UserID)) echo htmlentities($UserID) ?>"></p> <p>Password:<br> <input TYPE="PASSWORD" NAME="Password" VALUE = "<?php if (IsSet($Password)) echo htmlentities($Password) ?>" size="20"></p> <p><input TYPE="submit" VALUE="Login" name=submit> <br> <br> <a href="forgotten-password.php">Forgotten your password?</a> <br><br> </form>
<?php # # $Id: login.php,v 1.2 2006-12-17 11:55:53 dan Exp $ # # Copyright (c) 1998-2003 DVL Software Limited # if (IsSet($_GET['origin'])) $origin = $_GET["origin"]; ?> <form action="<?php echo $_SERVER["PHP_SELF"] . "?origin=$origin" ?>" method="POST" name="l"> <input type="hidden" name="custom_settings" value="1"><input type="hidden" name="LOGIN" value="1"> <p>User ID:<br> <input SIZE="15" NAME="UserID" value="<?php if (IsSet($UserID)) echo htmlentities($UserID) ?>"></p> <p>Password:<br> <input TYPE="PASSWORD" NAME="Password" VALUE = "<?php if (IsSet($Password)) echo htmlentities($Password) ?>" size="20"></p> <p><input TYPE="submit" VALUE="Login" name=submit> &nbsp;&nbsp;&nbsp;&nbsp; <input TYPE="reset" VALUE="reset form"> </form>
Correct spacing and language in comments
describe("About Expects", function() { // We shall contemplate truth by testing reality, via spec expectations. it("should expect true", function() { expect(false).toBeTruthy(); // This should be true }); // To understand reality, we must compare our expectations against reality. it("should expect equality", function () { var expectedValue = FILL_ME_IN; var actualValue = 1 + 1; expect(actualValue === expectedValue).toBeTruthy(); }); // Some ways of asserting equality are better than others. it("should assert equality a better way", function () { var expectedValue = FILL_ME_IN; var actualValue = 1 + 1; // toEqual() compares using common sense equality. expect(actualValue).toEqual(expectedValue); }); // Sometimes you need to be precise about what you "type". it("should assert equality with ===", function () { var expectedValue = FILL_ME_IN; var actualValue = (1 + 1).toString(); // toBe() will always use === to compare. expect(actualValue).toBe(expectedValue); }); // Sometimes we will ask you to fill in the values. it("should have filled in values", function () { expect(1 + 1).toEqual(FILL_ME_IN); }); });
describe("About Expects", function() { //We shall contemplate truth by testing reality, via spec expectations. it("should expect true", function() { expect(false).toBeTruthy(); //This should be true }); //To understand reality, we must compare our expectations against reality. it("should expect equality", function () { var expectedValue = FILL_ME_IN; var actualValue = 1 + 1; expect(actualValue === expectedValue).toBeTruthy(); }); //Some ways of asserting equality are better than others. it("should assert equality a better way", function () { var expectedValue = FILL_ME_IN; var actualValue = 1 + 1; // toEqual() compares using common sense equality. expect(actualValue).toEqual(expectedValue); }); //Sometimes you need to be really exact about what you "type". it("should assert equality with ===", function () { var expectedValue = FILL_ME_IN; var actualValue = (1 + 1).toString(); // toBe() will always use === to compare. expect(actualValue).toBe(expectedValue); }); //Sometimes we will ask you to fill in the values. it("should have filled in values", function () { expect(1 + 1).toEqual(FILL_ME_IN); }); });
Check whether file does exist
package main import ( "net/http" "io/ioutil" "os" "log" ) func saveHandler(w http.ResponseWriter, r *http.Request) { folder := "/PRODUCTION/EXPERIMENT/web/savedfiles/" filename := generateRandomURL() path := folder + filename if _, err := os.Stat(path); err != nil { if !(os.IsNotExist(err)) { log.Fatal("ListenAndServe: ", err) http.Error(w, err.Error(), http.StatusInternalServerError) return } log.Fatal("ListenAndServe: ", err) } r.ParseForm() text := r.Form.Get("text") ioutil.WriteFile(path, []byte(text), 0400) os.Chown(path, 995, 994) http.Redirect(w, r, "http://experiment.safkanyazilim.com/"+filename, http.StatusTemporaryRedirect) } func generateRandomURL() string { return "1234556" } func main() { http.HandleFunc("/save", saveHandler) //http.ListenAndServe(":8080", nil) err := http.ListenAndServe(":8080", nil) if err != nil { log.Fatal("Main: ", err) } }
package main import ( "net/http" "io/ioutil" "os" "log" ) func saveHandler(w http.ResponseWriter, r *http.Request) { folder := "/PRODUCTION/EXPERIMENT/web/savedfiles/" filename := generateRandomURL() path := folder + filename if _, err := os.Stat(path); err != nil { if os.IsNotExist(err) { log.Fatal("ListenAndServe: ", err) http.Error(w, err.Error(), http.StatusInternalServerError) return } log.Fatal("ListenAndServe: ", err) } r.ParseForm() text := r.Form.Get("text") ioutil.WriteFile(path, []byte(text), 0400) os.Chown(path, 995, 994) http.Redirect(w, r, "http://experiment.safkanyazilim.com/"+filename, http.StatusTemporaryRedirect) } func generateRandomURL() string { return "1234556" } func main() { http.HandleFunc("/save", saveHandler) //http.ListenAndServe(":8080", nil) err := http.ListenAndServe(":8080", nil) if err != nil { log.Fatal("ListenAndServe: ", err) } }
Fix bash output displaying <br> instead of returning.
import React from 'react'; var AU = require('ansi_up'); var ansi_up = new AU.default(); class BashOutput extends React.Component { updateHTML(text) { return { __html: ansi_up.ansi_to_html(text.replace(/<br>/g, '\n')) }; } render() { if (this.props.text) { return ( <pre> <div className="bash-output" dangerouslySetInnerHTML={this.updateHTML(this.props.text)} /> </pre> ); } else { return (<div/>); } } } export default BashOutput;
import React from 'react'; var AU = require('ansi_up'); var ansi_up = new AU.default(); class BashOutput extends React.Component { updateHTML(text) { return { __html: ansi_up.ansi_to_html(text) }; } render() { if (this.props.text) { return ( <pre> <div className="bash-output" dangerouslySetInnerHTML={this.updateHTML(this.props.text)} /> </pre> ); } else { return (<div/>); } } } export default BashOutput;
Use 'diff_base' for pycodestyle check, if set. Speeds it up, plus reduces spew when testing locally.
# Copyright 2016 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Custom script to run pycodestyle on google-cloud codebase. This runs pycodestyle as a script via subprocess but only runs it on the .py files that are checked in to the repository. """ import os import subprocess import sys from run_pylint import get_files_for_linting def main(): """Run pycodestyle on all Python files in the repository.""" git_root = subprocess.check_output( ['git', 'rev-parse', '--show-toplevel']).strip() os.chdir(git_root) candidates, _ = get_files_for_linting() python_files = [ candidate for candidate in candidates if candidate.endswith('.py')] pycodestyle_command = ['pycodestyle'] + python_files status_code = subprocess.call(pycodestyle_command) sys.exit(status_code) if __name__ == '__main__': main()
# Copyright 2016 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Custom script to run pycodestyle on google-cloud codebase. This runs pycodestyle as a script via subprocess but only runs it on the .py files that are checked in to the repository. """ import os import subprocess import sys def main(): """Run pycodestyle on all Python files in the repository.""" git_root = subprocess.check_output( ['git', 'rev-parse', '--show-toplevel']).strip() os.chdir(git_root) python_files = subprocess.check_output(['git', 'ls-files', '*py']) python_files = python_files.strip().split() pycodestyle_command = ['pycodestyle'] + python_files status_code = subprocess.call(pycodestyle_command) sys.exit(status_code) if __name__ == '__main__': main()
Exit -1 on ERROR in non-global logger Fixes #3239
// Copyright 2015 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by 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 main import ( "runtime" "os" "github.com/spf13/hugo/commands" jww "github.com/spf13/jwalterweatherman" ) func main() { runtime.GOMAXPROCS(runtime.NumCPU()) commands.Execute() if jww.LogCountForLevelsGreaterThanorEqualTo(jww.LevelError) > 0 { os.Exit(-1) } if commands.Hugo != nil { if commands.Hugo.Log.LogCountForLevelsGreaterThanorEqualTo(jww.LevelError) > 0 { os.Exit(-1) } } }
// Copyright 2015 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by 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 main import ( "runtime" "github.com/spf13/hugo/commands" jww "github.com/spf13/jwalterweatherman" "os" ) func main() { runtime.GOMAXPROCS(runtime.NumCPU()) commands.Execute() if jww.LogCountForLevelsGreaterThanorEqualTo(jww.LevelError) > 0 { os.Exit(-1) } }
[FIX] membership: Remove unpaid inovice import from init file bzr revid: mra@mra-laptop-20101006072219-twq77xlem3d69rg7
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # 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/>. # ############################################################################## import membership_invoice # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # 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/>. # ############################################################################## import membership_invoice import membership_unpaid_invoice # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
Set up probe to investigate possible crash(es) with null PageTitle. Change-Id: I96f01582b239d84182cb7926371bdb6e7ca54cd3
package org.wikipedia.page; import androidx.annotation.NonNull; import org.wikipedia.history.HistoryEntry; import org.wikipedia.model.BaseModel; public class PageBackStackItem extends BaseModel { @NonNull private PageTitle title; @NonNull private HistoryEntry historyEntry; private int scrollY; public PageBackStackItem(@NonNull PageTitle title, @NonNull HistoryEntry historyEntry) { // TODO: remove this crash probe upon fixing if (title == null || historyEntry == null) { throw new IllegalArgumentException("Nonnull parameter is in fact null."); } this.title = title; this.historyEntry = historyEntry; } @NonNull public PageTitle getTitle() { return title; } public void setTitle(@NonNull PageTitle title) { this.title = title; } @NonNull public HistoryEntry getHistoryEntry() { return historyEntry; } public int getScrollY() { return scrollY; } public void setScrollY(int scrollY) { this.scrollY = scrollY; } }
package org.wikipedia.page; import androidx.annotation.NonNull; import org.wikipedia.history.HistoryEntry; import org.wikipedia.model.BaseModel; public class PageBackStackItem extends BaseModel { @NonNull private PageTitle title; @NonNull private HistoryEntry historyEntry; private int scrollY; public PageBackStackItem(@NonNull PageTitle title, @NonNull HistoryEntry historyEntry) { this.title = title; this.historyEntry = historyEntry; } @NonNull public PageTitle getTitle() { return title; } public void setTitle(@NonNull PageTitle title) { this.title = title; } @NonNull public HistoryEntry getHistoryEntry() { return historyEntry; } public int getScrollY() { return scrollY; } public void setScrollY(int scrollY) { this.scrollY = scrollY; } }
Add a new value set
package rlpark.plugin.rltoys.experiments.parametersweep.parameters; public class ParameterValues { public static final String StepSize = "StepSize"; public static final String MetaStepSize = "MetaStepSize"; static public double[] getStepSizeValues(boolean withZero) { double[] values = new double[] { .0001, .0005, .001, .005, .01, .05, .1, .5, 1. }; if (withZero) values = ParameterValues.addZero(values); return values; } static public double[] getWideStepSizeValues(boolean withZero) { double[] values = new double[] { 1e-8, 1e-7, 1e-6, 1e-5, 1e-4, 1e-3, 1e-2, 1e-1, 1e0 }; if (withZero) values = ParameterValues.addZero(values); return values; } private static double[] addZero(double[] withoutZero) { double[] result = new double[withoutZero.length + 1]; System.arraycopy(withoutZero, 0, result, 1, withoutZero.length); result[0] = 0.0; return result; } public static double[] getFewStepSizeValues(boolean withZero) { double[] values = new double[] { 1e-8, 1e-4, 1 }; if (withZero) values = ParameterValues.addZero(values); return values; } }
package rlpark.plugin.rltoys.experiments.parametersweep.parameters; public class ParameterValues { public static final String StepSize = "StepSize"; public static final String MetaStepSize = "MetaStepSize"; static public double[] getStepSizeValues(boolean withZero) { double[] values = new double[] { .0001, .0005, .001, .005, .01, .05, .1, .5, 1. }; if (withZero) values = ParameterValues.addZero(values); return values; } static public double[] getWideStepSizeValues(boolean withZero) { double[] values = new double[] { 1e-8, 1e-7, 1e-6, 1e-5, 1e-4, 1e-3, 1e-2, 1e-1, 1e0 }; if (withZero) values = ParameterValues.addZero(values); return values; } private static double[] addZero(double[] withoutZero) { double[] result = new double[withoutZero.length + 1]; System.arraycopy(withoutZero, 0, result, 1, withoutZero.length); result[0] = 0.0; return result; } public static double[] getFewStepSizeValues(boolean withZero) { double[] values = new double[] { 1e-8, 1e-4, 1e0 }; if (withZero) values = ParameterValues.addZero(values); return values; } }
Change transition route to exact order
import Ember from 'ember'; export default Ember.Controller.extend({ session: Ember.inject.service(), notifications: Ember.inject.service(), actions: { addToOrder(order, account, attrs) { const isManager = (this.get('session.account.id') === order.get('manager.id')); const portion = this.store.createRecord('portion', attrs); portion.set('order', order); portion.set('owner', account); if (isManager) { portion.set('paid', true); } portion.save().then(() => { order.addPortion(portion); if (isManager) { portion.updateOrderMoney(); } order.save(); }); this.get('notifications').subscribeOrderNotification(order.id); this.transitionToRoute('order', order.id); } } });
import Ember from 'ember'; export default Ember.Controller.extend({ session: Ember.inject.service(), notifications: Ember.inject.service(), actions: { addToOrder(order, account, attrs) { const isManager = (this.get('session.account.id') === order.get('manager.id')); const portion = this.store.createRecord('portion', attrs); portion.set('order', order); portion.set('owner', account); if (isManager) { portion.set('paid', true); } portion.save().then(() => { order.addPortion(portion); if (isManager) { portion.updateOrderMoney(); } order.save(); }); this.get('notifications').subscribeOrderNotification(order.id); this.transitionToRoute('orders'); } } });
Fix the header title for AddIncomeContainer
import React, { PropTypes } from 'react'; import { connect } from 'react-redux'; import { NavigationExperimental } from 'react-native'; const { Header: NavigationHeader, } = NavigationExperimental; const TitleHeaderComponent = ({ scene, }) => { const { route } = scene; let title = ''; if (route.key !== 'login') { switch (route.key) { case 'home': title = 'Home'; break; case 'add_item': title = 'Add item'; break; case 'add_category': title = 'Add category'; break; case 'edit_salary': title = 'Monthly salary'; break; case 'add_income': title = 'Add income'; break; default: title = 'Not found'; } } return ( <NavigationHeader.Title textStyle={{ color: '#FFFFFF' }}> {title} </NavigationHeader.Title> ); }; TitleHeaderComponent.propTypes = { scene: PropTypes.object, }; export default connect( null )(TitleHeaderComponent);
import React, { PropTypes } from 'react'; import { connect } from 'react-redux'; import { NavigationExperimental } from 'react-native'; const { Header: NavigationHeader, } = NavigationExperimental; const TitleHeaderComponent = ({ scene, }) => { const { route } = scene; let title = ''; if (route.key !== 'login') { switch (route.key) { case 'home': title = 'Home'; break; case 'add_item': title = 'Add item'; break; case 'add_category': title = 'Add category'; break; case 'edit_salary': title = 'Monthly salary'; break; default: title = 'Not found'; } } return ( <NavigationHeader.Title textStyle={{ color: '#FFFFFF' }}> {title} </NavigationHeader.Title> ); }; TitleHeaderComponent.propTypes = { scene: PropTypes.object, }; export default connect( null )(TitleHeaderComponent);
Fix wrong function name in server_chain
// Update user's last activity time in redis. Field `User.last_active_ts` will be updated via cron. // 'use strict'; module.exports = function (N) { // Update last activity time. Fired before each server handler. // N.wire.before('server_chain:*', { priority: -55 }, function last_active_update(env, callback) { // Not logged in - skip time update. if (env.user_info.is_guest) { callback(); return; } N.redis.time(function (err, time) { if (err) { callback(err); return; } N.redis.zadd('users:last_active', Math.floor(time[0] * 1000 + time[1] / 1000), env.user_info.user_id, callback); }); }); };
// Update user's last activity time in redis. Field `User.last_active_ts` will be updated via cron. // 'use strict'; module.exports = function (N) { // Update last activity time. Fired before each server handler. // N.wire.before('server_chain:*', { priority: -55 }, function current_user_load(env, callback) { // Not logged in - skip time update. if (env.user_info.is_guest) { callback(); return; } N.redis.time(function (err, time) { if (err) { callback(err); return; } N.redis.zadd('users:last_active', Math.floor(time[0] * 1000 + time[1] / 1000), env.user_info.user_id, callback); }); }); };
Refactor previous migration, better code but shouldn't affect existing production db
<?php namespace Application\Migrations; use SimplyTestable\BaseMigrationsBundle\Migration\BaseMigration, Doctrine\DBAL\Schema\Schema; /** * Auto-generated Migration: Please modify to your need! */ class Version20120925115659 extends BaseMigration { public function up(Schema $schema) { $this->addCommonStatement('ALTER TABLE TaskOutput ADD errorCount INT NOT NULL'); parent::up($schema); } public function down(Schema $schema) { $this->statements['mysql'] = array( "ALTER TABLE TaskOutput DROP errorCount" ); $this->statements['sqlite'] = array( "SELECT 1 + 1" ); parent::down($schema); } }
<?php namespace Application\Migrations; use Doctrine\DBAL\Migrations\AbstractMigration, Doctrine\DBAL\Schema\Schema; /** * Auto-generated Migration: Please modify to your need! */ class Version20120925115659 extends AbstractMigration { public function up(Schema $schema) { // this up() migration is autogenerated, please modify it to your needs $this->abortIf($this->connection->getDatabasePlatform()->getName() != "mysql"); $this->addSql("ALTER TABLE TaskOutput ADD errorCount INT NOT NULL"); } public function down(Schema $schema) { // this down() migration is autogenerated, please modify it to your needs $this->abortIf($this->connection->getDatabasePlatform()->getName() != "mysql"); $this->addSql("ALTER TABLE TaskOutput DROP errorCount"); } }
Disable redirect that prevented access to the admin panel.
from django.conf import settings from django.conf.urls import patterns, include, url from django.core.urlresolvers import reverse from django.views.generic import TemplateView from django.views.generic import RedirectView from django.contrib import admin import os import logging logger = logging.getLogger("kpcc_backroom_handshakes") admin.autodiscover() urlpatterns = [ url(r"^admin/doc/", include("django.contrib.admindocs.urls")), url(r"^admin/", include(admin.site.urls)), url(r"^admin/", include("massadmin.urls")), url(r"^elections/", include("newscast.urls", namespace="newscast")), url(r"^elections/", include("ballot_box.urls", namespace="ballot-box")), url(r"^elections/", include("measure_finance.urls", namespace="campaign-finance")), url(r"^elections/", include("election_registrar.urls", namespace="elections")), # url(r"^", RedirectView.as_view(url="elections/", permanent=False)), ]
from django.conf import settings from django.conf.urls import patterns, include, url from django.core.urlresolvers import reverse from django.views.generic import TemplateView from django.views.generic import RedirectView from django.contrib import admin import os import logging logger = logging.getLogger("kpcc_backroom_handshakes") admin.autodiscover() urlpatterns = [ url(r"^admin/doc/", include("django.contrib.admindocs.urls")), url(r"^admin/", include(admin.site.urls)), url(r"^admin/", include("massadmin.urls")), url(r"^elections/", include("newscast.urls", namespace="newscast")), url(r"^elections/", include("ballot_box.urls", namespace="ballot-box")), url(r"^elections/", include("measure_finance.urls", namespace="campaign-finance")), url(r"^elections/", include("election_registrar.urls", namespace="elections")), url(r"^", RedirectView.as_view(url="elections/", permanent=False)), ]
Index size check, for Elastic 8 upgrade (I10).
package roart.common.util; import java.io.InputStream; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import roart.common.constants.Constants; public class IOUtil { private static Logger log = LoggerFactory.getLogger(IOUtil.class); public static byte[] toByteArrayMax(InputStream is) { try { return is.readNBytes(Integer.MAX_VALUE - 8); } catch (Exception e) { log.error(Constants.EXCEPTION, e); return new byte[0]; } } public static byte[] toByteArray1G(InputStream is) { try { return is.readNBytes(1024 * 1024 * 1024); } catch (Exception e) { log.error(Constants.EXCEPTION, e); return new byte[0]; } } public static byte[] toByteArray(InputStream is, int bytes) { try { return is.readNBytes(bytes); } catch (Exception e) { log.error(Constants.EXCEPTION, e); return new byte[0]; } } }
package roart.common.util; import java.io.InputStream; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import roart.common.constants.Constants; public class IOUtil { private static Logger log = LoggerFactory.getLogger(IOUtil.class); public static byte[] toByteArrayMax(InputStream is) { try { return is.readNBytes(Integer.MAX_VALUE - 8); } catch (Exception e) { log.error(Constants.EXCEPTION, e); return new byte[0]; } } public static byte[] toByteArray1G(InputStream is) { try { return is.readNBytes(1024 * 1024 * 1024); } catch (Exception e) { log.error(Constants.EXCEPTION, e); return new byte[0]; } } }
[BG-7750] Remove TBTG fee info test Summary: TBTG doesn't exist, but there's a test to get fee info from the platform, which is breaking all SDK builds Reviewers: kevin, tyler, leo, bigly, zacleids Reviewed By: zacleids Subscribers: tyler, mark Differential Revision: https://phabricator.bitgo.com/D9844
// // Tests for basecoin // const Promise = require('bluebird'); const co = Promise.coroutine; const _ = require('lodash'); require('should'); const TestV2BitGo = require('../../lib/test_bitgo'); const bitgo = new TestV2BitGo({ env: 'test' }); bitgo.initializeTestVars(); describe('V2 Base Coin:', function() { describe('fee estimate call', function() { before(() => require('nock').restore()); _.forEach(['tbtc', 'trmg', 'tltc', 'tbch'], function(coin) { const basecoin = bitgo.coin(coin); it('should fetch fee info for utxo coins', co(function *() { const feeInfo = yield basecoin.feeEstimate(); feeInfo.should.have.property('feePerKb'); feeInfo.should.have.property('numBlocks'); })); }); _.forEach(['teth', 'txrp'], function(coin) { const basecoin = bitgo.coin(coin); it('should fail to to fetch fee info for account coin', co(function *() { try { yield basecoin.feeEstimate(); throw new Error(); } catch (err) { err.message.should.equal('cannot get fee estimate data for ' + coin); } })); }); }); });
// // Tests for basecoin // const Promise = require('bluebird'); const co = Promise.coroutine; const _ = require('lodash'); require('should'); const TestV2BitGo = require('../../lib/test_bitgo'); const bitgo = new TestV2BitGo({ env: 'test' }); bitgo.initializeTestVars(); describe('V2 Base Coin:', function() { describe('fee estimate call', function() { before(() => require('nock').restore()); _.forEach(['tbtc', 'trmg', 'tltc', 'tbch', 'tbtg'], function(coin) { const basecoin = bitgo.coin(coin); it('should fetch fee info for utxo coins', co(function *() { const feeInfo = yield basecoin.feeEstimate(); feeInfo.should.have.property('feePerKb'); feeInfo.should.have.property('numBlocks'); })); }); _.forEach(['teth', 'txrp'], function(coin) { const basecoin = bitgo.coin(coin); it('should fail to to fetch fee info for account coin', co(function *() { try { yield basecoin.feeEstimate(); throw new Error(); } catch (err) { err.message.should.equal('cannot get fee estimate data for ' + coin); } })); }); }); });
Replace coverage API calls by subprocess calls.
#!/usr/bin/env python """Script to collect coverage information on ofStateManager""" import os import sys import inspect import coverage import subprocess def main(): """Main function""" arguments = '' if len(sys.argv) > 1: arguments = ' '.join(sys.argv[1:]) testdir = os.path.abspath(os.path.dirname( inspect.getfile(inspect.currentframe()))) script_path = os.path.join(testdir, '..', 'ofStateManager.py') os.environ['COVERAGE_PROCESS_START'] = os.path.join(testdir, '.coveragerc') os.environ['COVERAGE_FILE'] = os.path.join(testdir, '.coverage') subprocess.call('coverage erase', shell=True, cwd=testdir) subprocess.call('coverage run -m py.test ' + arguments, shell=True, cwd=testdir) subprocess.call('coverage combine', shell=True, cwd=testdir) subprocess.call('coverage html -d ' + os.path.join(testdir, 'htmlcov') + ' --include=' + script_path, shell=True, cwd=testdir) subprocess.call('coverage report --include=' + script_path, shell=True, cwd=testdir) if __name__ == '__main__': main()
#!/usr/bin/env python """Script to collect coverage information on ofStateManager""" import os import sys import inspect import coverage import subprocess def main(): """Main function""" arguments = '' if len(sys.argv) > 1: arguments = ' '.join(sys.argv[1:]) testdir = os.path.abspath(os.path.dirname( inspect.getfile(inspect.currentframe()))) os.environ['COVERAGE_PROCESS_START'] = os.path.join(testdir, '.coveragerc') os.environ['COVERAGE_FILE'] = os.path.join(testdir, '.coverage') cov = coverage.coverage(source=os.path.join(testdir, '..'), include=os.path.join(testdir, '..', 'ofStateManager.py')) cov.erase() subprocess.call('coverage run -m py.test ' + arguments, shell=True, cwd=testdir) cov.combine() cov.html_report(directory=os.path.join(testdir, 'htmlcov')) cov.report(show_missing=False) if __name__ == '__main__': main()
main: Fix bux when using Git directory If a Git directory is passed in, it needs to be in a list of one.
#!/usr/bin/env python """Script for updating a directory of repositories.""" import logging import os import click from .actions import update_repo @click.command() @click.option('-d', '--debug', help='Set DEBUG level logging.', is_flag=True) @click.argument('dir', default='.') def main(**kwargs): """Update repositories in a directory. By default, the current working directory list is used for finding valid repositories. """ logging.basicConfig( level=logging.INFO, format='[%(levelname)s] %(name)s:%(funcName)s - %(message)s') log = logging.getLogger(__name__) if kwargs['debug']: logging.root.setLevel(logging.DEBUG) main_dir = kwargs['dir'] log.info('Finding directories in %s', main_dir) dir_list = os.listdir(main_dir) log.debug('List of directories: %s', dir_list) # Git directory was passed in, not a directory of Git directories if '.git' in dir_list: dir_list = [kwargs['dir']] for directory in dir_list: update_repo(os.path.join(main_dir, directory)) if __name__ == '__main__': main()
#!/usr/bin/env python """Script for updating a directory of repositories.""" import logging import os import click from .actions import update_repo @click.command() @click.option('-d', '--debug', help='Set DEBUG level logging.', is_flag=True) @click.argument('dir', default='.') def main(**kwargs): """Update repositories in a directory. By default, the current working directory list is used for finding valid repositories. """ logging.basicConfig( level=logging.INFO, format='[%(levelname)s] %(name)s:%(funcName)s - %(message)s') log = logging.getLogger(__name__) if kwargs['debug']: logging.root.setLevel(logging.DEBUG) main_dir = kwargs['dir'] log.info('Finding directories in %s', main_dir) dir_list = os.listdir(main_dir) log.debug('List of directories: %s', dir_list) # Git directory was passed in, not a directory of Git directories if '.git' in dir_list: dir_list = kwargs['dir'] for directory in dir_list: update_repo(os.path.join(main_dir, directory)) if __name__ == '__main__': main()
Remove duplicate make_channel from test
/** * A simple request test. This measures the time between creation of the request channel * and first delivery of the data and time needed to deliver all data expected plus an overall * time to complete the load. The request must succeed otherwise the test fails. */ var startTime = null; var firstDataTime = null; var endTime = null; listener = { onStartRequest: function() { }, onDataAvailable: function() { if (!firstDataTime) { firstDataTime = new Date(); firstDataTime = firstDataTime.getMilliseconds(); } }, onStopRequest: function(request, context, status) { //do_check(status === 0, "request to '" + request.name + "' failed"); endTime = new Date(); endTime = endTime.getMilliseconds(); do_write_result("latency", startTime, firstDataTime); do_write_result("data_delivery", firstDataTime, endTime); do_write_result("total", startTime, endTime); do_test_finish(); } }; function run_test() // The entry point { startTime = new Date(); startTime = startTime.getMilliseconds(); var channel = make_channel("http://example.org/"); channel.asyncOpen(listener, null); }
/** * A simple request test. This measures the time between creation of the request channel * and first delivery of the data and time needed to deliver all data expected plus an overall * time to complete the load. The request must succeed otherwise the test fails. */ var startTime = null; var firstDataTime = null; var endTime = null; function make_channel(url) { var IOService = Components.classes["@mozilla.org/network/io-service;1"].getService( Components.interfaces.nsIIOService); return IOService.newChannel(url, "", null); } listener = { onStartRequest: function() { }, onDataAvailable: function() { if (!firstDataTime) { firstDataTime = new Date(); firstDataTime = firstDataTime.getMilliseconds(); } }, onStopRequest: function(request, context, status) { //do_check(status === 0, "request to '" + request.name + "' failed"); endTime = new Date(); endTime = endTime.getMilliseconds(); do_write_result("latency", startTime, firstDataTime); do_write_result("data_delivery", firstDataTime, endTime); do_write_result("total", startTime, endTime); do_test_finish(); } }; function run_test() // The entry point { startTime = new Date(); startTime = startTime.getMilliseconds(); var channel = make_channel("http://example.org/"); channel.asyncOpen(listener, null); }
Support `root` as direct argument
'use strict'; module.exports = function (deck/*, options*/) { var options = arguments[1], root, update, activateSlide; if (typeof options === 'string') { root = options; } else { options = Object(options); root = options.root || '/'; } activateSlide = function (index) { if (index === deck.slide()) return; deck.slide(index); }; update = function (e) { var id = location.pathname.slice(root.length, -1); if (!id) return; if (isNaN(id)) { deck.slides.forEach(function (slide, i) { if (slide.getAttribute('data-bespoke-id') === id) activateSlide(i); }); return; } activateSlide(Number(id)); }; setTimeout(function () { update(); var first = deck.slides[0].getAttribute('data-bespoke-id') || '1'; deck.on('activate', function (e) { var urlSearch = location.search , slideName = e.slide.getAttribute('data-bespoke-id') || String(e.index + 1); history.pushState({}, '', root + ((slideName === first) ? '' : (slideName + '/')) + urlSearch); }); window.addEventListener('popstate', update); }, 0); };
'use strict'; module.exports = function (deck/*, options*/) { var options = Object(arguments[1]), root = options.root || '/' , update, activateSlide; activateSlide = function (index) { if (index === deck.slide()) return; deck.slide(index); }; update = function (e) { var id = location.pathname.slice(root.length, -1); if (!id) return; if (isNaN(id)) { deck.slides.forEach(function (slide, i) { if (slide.getAttribute('data-bespoke-id') === id) activateSlide(i); }); return; } activateSlide(Number(id)); }; setTimeout(function () { update(); var first = deck.slides[0].getAttribute('data-bespoke-id') || '1'; deck.on('activate', function (e) { var urlSearch = location.search , slideName = e.slide.getAttribute('data-bespoke-id') || String(e.index + 1); history.pushState({}, '', root + ((slideName === first) ? '' : (slideName + '/')) + urlSearch); }); window.addEventListener('popstate', update); }, 0); };
Fix eslint warnings about global Config and Log objects.
#!/usr/bin/env node /* global Config, Log */ 'use strict'; const args = require('yargs') .usage('Usage: $0 [args]') .option('c', { alias: 'config', describe: 'Load configuration from file', type: 'string' }) .help('help') .argv; const express = require('express'); const http = require('http'); global.Config = require('../lib/config').load(args.cf); global.Log = require('../lib/logger').attach(global.Config); const host = Config.get('service:hostname'); const port = Config.get('service:port'); const app = express(); const server = http.createServer(app); require('../lib/control/v1/core').attach(app); require('../lib/control/v1/conqueso').attach(app); server.listen(port, host, () => { Log.info('Listening on ' + host + ':' + port); });
#!/usr/bin/env node 'use strict'; const args = require('yargs') .usage('Usage: $0 [args]') .option('c', { alias: 'config', describe: 'Load configuration from file', type: 'string' }) .help('help') .argv; const express = require('express'); const http = require('http'); global.Config = require('../lib/config').load(args.cf); global.Log = require('../lib/logger').attach(global.Config); const host = Config.get('service:hostname'); const port = Config.get('service:port'); const app = express(); const server = http.createServer(app); require('../lib/control/v1/core').attach(app); require('../lib/control/v1/conqueso').attach(app); server.listen(port, host, () => { Log.info('Listening on ' + host + ':' + port); });
Fix bug which load_required_modules always returns list which length is 1
#!/usr/bin/env python # coding: utf-8 import os import re from setuptools import setup, find_packages def load_required_modules(): with open(os.path.join(os.path.dirname(__file__), "requirements.txt")) as f: return [line.strip() for line in f.readlines() if line.strip()] setup( name='dictmixin', __version__=re.search( r'__version__\s*=\s*[\'"]([^\'"]*)[\'"]', # It excludes inline comment too open('dictmixin/__init__.py').read()).group(1), description='Parsing mixin which converts `data class instance`, `dict object`, and `json string` each other.', license='MIT', author='tadashi-aikawa', author_email='syou.maman@gmail.com', maintainer='tadashi-aikawa', maintainer_email='tadashi-aikawa', url='https://github.com/tadashi-aikawa/dictmixin.git', keywords='dict json convert parse each other', packages=find_packages(exclude=['tests*']), install_requires=load_required_modules(), classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Intended Audience :: Developers', 'Topic :: Software Development :: Build Tools', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', ], )
#!/usr/bin/env python # coding: utf-8 import os import re from setuptools import setup, find_packages def load_required_modules(): with open(os.path.join(os.path.dirname(__file__), "requirements.txt")) as f: return [line.strip() for line in f.read().strip().split(os.linesep) if line.strip()] setup( name='dictmixin', __version__=re.search( r'__version__\s*=\s*[\'"]([^\'"]*)[\'"]', # It excludes inline comment too open('dictmixin/__init__.py').read()).group(1), description='Parsing mixin which converts `data class instance`, `dict object`, and `json string` each other.', license='MIT', author='tadashi-aikawa', author_email='syou.maman@gmail.com', maintainer='tadashi-aikawa', maintainer_email='tadashi-aikawa', url='https://github.com/tadashi-aikawa/dictmixin.git', keywords='dict json convert parse each other', packages=find_packages(exclude=['tests*']), install_requires=load_required_modules(), classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Intended Audience :: Developers', 'Topic :: Software Development :: Build Tools', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', ], )
Fix systemd unit_file_dir flag name for consistency
package main import ( "os" log "github.com/Sirupsen/logrus" logx "github.com/cerana/cerana/pkg/logrusx" "github.com/cerana/cerana/provider" "github.com/cerana/cerana/providers/systemd" flag "github.com/spf13/pflag" ) func main() { log.SetFormatter(&logx.JSONFormatter{}) config := systemd.NewConfig(nil, nil) flag.StringP("unit_file_dir", "d", "", "directory in which to create unit files") flag.Parse() dieOnError(config.LoadConfig()) dieOnError(config.SetupLogging()) server, err := provider.NewServer(config.Config) dieOnError(err) s, err := systemd.New(config) dieOnError(err) s.RegisterTasks(server) if len(server.RegisteredTasks()) != 0 { dieOnError(server.Start()) server.StopOnSignal() } else { log.Warn("no registered tasks, exiting") } } func dieOnError(err error) { if err != nil { log.Fatal("encountered an error during startup, error:", err) os.Exit(1) } }
package main import ( "os" log "github.com/Sirupsen/logrus" logx "github.com/cerana/cerana/pkg/logrusx" "github.com/cerana/cerana/provider" "github.com/cerana/cerana/providers/systemd" flag "github.com/spf13/pflag" ) func main() { log.SetFormatter(&logx.JSONFormatter{}) config := systemd.NewConfig(nil, nil) flag.StringP("unit-file-dir", "d", "", "directory in which to create unit files") flag.Parse() dieOnError(config.LoadConfig()) dieOnError(config.SetupLogging()) server, err := provider.NewServer(config.Config) dieOnError(err) s, err := systemd.New(config) dieOnError(err) s.RegisterTasks(server) if len(server.RegisteredTasks()) != 0 { dieOnError(server.Start()) server.StopOnSignal() } else { log.Warn("no registered tasks, exiting") } } func dieOnError(err error) { if err != nil { log.Fatal("encountered an error during startup, error:", err) os.Exit(1) } }
Add `getBody()` on all responses
<?php namespace Algolia\AlgoliaSearch\Response; abstract class AbstractResponse implements \ArrayAccess { /** * @var array Full response from Algolia API */ protected $apiResponse; abstract public function wait($requestOptions = array()); /** * @return array The actual response from Algolia API */ public function getBody() { return $this->apiResponse; } /** * {@inheritdoc} */ public function offsetExists($offset) { return isset($this->apiResponse[$offset]); } /** * {@inheritdoc} */ public function offsetGet($offset) { return $this->apiResponse[$offset]; } /** * {@inheritdoc} */ public function offsetSet($offset, $value) { $this->apiResponse[$offset] = $value; } /** * {@inheritdoc} */ public function offsetUnset($offset) { unset($this->apiResponse[$offset]); } }
<?php namespace Algolia\AlgoliaSearch\Response; abstract class AbstractResponse implements \ArrayAccess { /** * @var array Full response from Algolia API */ protected $apiResponse; abstract public function wait($requestOptions = array()); /** * {@inheritdoc} */ public function offsetExists($offset) { return isset($this->apiResponse[$offset]); } /** * {@inheritdoc} */ public function offsetGet($offset) { return $this->apiResponse[$offset]; } /** * {@inheritdoc} */ public function offsetSet($offset, $value) { $this->apiResponse[$offset] = $value; } /** * {@inheritdoc} */ public function offsetUnset($offset) { unset($this->apiResponse[$offset]); } }
Add custom schema method: compare passwords (psw against hash)
var mongoose = require('mongoose'); var bcrypt = require('bcrypt'); var Schema = mongoose.Schema; var UserSchema = new Schema({ username : { type : String, required : true, index : { unique : true } }, password : { type : String, required : true, select : false } }); UserSchema.pre('save', function (next) { var user = this; if (!user.isModified('password')) return next(); bcrypt.hash(user.password, 10, function (err, hash) { if (err) return next(err); user.password = hash; next(); }); }); UserSchema.methods.comparePassword = function (password, callback) { var user = this; bcrypt.compare(password, user.password, function (err, isValid) { if (err) return callback(err); callback(null, isValid); }); }; module.exports = mongoose.model('User', UserSchema);
var mongoose = require('mongoose'); var bcrypt = require('bcrypt'); var Schema = mongoose.Schema; var UserSchema = new Schema({ name : String, username : { type : String, required : true, index : { unique : true } }, password : { type : String, required : true, select : false } }); UserSchema.pre('save', function (next) { var user = this; if (!user.isModified('password')) return next(); bcrypt.hash(user.password, 10, function (err, hash) { if (err) return next(err); user.password = hash; next(); }); }); module.exports = mongoose.model('User', UserSchema);
Add comments to public functions
package pull import ( "fmt" "io" "net/http" "os" "path" "github.com/mitchellh/ioprogress" ) // NewRelease creates a new Release instance func NewRelease(cache string) *Release { return &Release{CacheDir: cache} } // Release is a BOSH release with a configurable cache dir type Release struct { CacheDir string } // Pull downloads the specified Release to the local cache dir func (s *Release) Pull(url string) (filename string, err error) { name := path.Base(url) filename = s.CacheDir + "/" + name if _, err = os.Stat(filename); os.IsNotExist(err) { fmt.Println("Could not find release in local cache. Downloading now.") var out *os.File out, err = os.Create(filename) if err != nil { return } var resp *http.Response resp, err = http.Get(url) if err != nil { return } defer func() { if cerr := resp.Body.Close(); cerr != nil { err = cerr } }() progressR := &ioprogress.Reader{ Reader: resp.Body, Size: resp.ContentLength, } _, err = io.Copy(out, progressR) } return }
package pull import ( "fmt" "io" "net/http" "os" "path" "github.com/mitchellh/ioprogress" ) func NewRelease(cache string) *Release { return &Release{CacheDir: cache} } type Release struct { CacheDir string } // Pull downloads the specified Release to the local cache dir func (s *Release) Pull(url string) (filename string, err error) { name := path.Base(url) filename = s.CacheDir + "/" + name if _, err = os.Stat(filename); os.IsNotExist(err) { fmt.Println("Could not find release in local cache. Downloading now.") var out *os.File out, err = os.Create(filename) if err != nil { return } var resp *http.Response resp, err = http.Get(url) if err != nil { return } defer func() { if cerr := resp.Body.Close(); cerr != nil { err = cerr } }() progressR := &ioprogress.Reader{ Reader: resp.Body, Size: resp.ContentLength, } _, err = io.Copy(out, progressR) } return }
phpdoc: Use class level method definition to re-define method return type
<?php /** * Zend Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@zend.com so we can send you a copy immediately. * * @category Zend * @package Zend_Cache * @subpackage Storage * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ namespace Zend\Cache\Storage; /** * @category Zend * @package Zend_Cache * @subpackage Storage * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * * @method IteratorInterface getIterator() Get the storage iterator */ interface IterableInterface extends \IteratorAggregate { }
<?php /** * Zend Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@zend.com so we can send you a copy immediately. * * @category Zend * @package Zend_Cache * @subpackage Storage * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ namespace Zend\Cache\Storage; /** * @category Zend * @package Zend_Cache * @subpackage Storage * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ interface IterableInterface extends \IteratorAggregate { /** * Get the storage iterator * * @return IteratorInterface */ // PHP 5.3.3: Fatal error: Can't inherit abstract function IteratorAggregate::getIterator() // (previously declared abstract in Zend\Cache\Storage\IterableInterface) //public function getIterator(); }
Convert k8s pod spec into dict structure to make sure that it's json serializable. PiperOrigin-RevId: 279162159
# Lint as: python2, python3 # Copyright 2019 Google LLC. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by 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. """Component config for Kubernets Pod execution.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from typing import Any, Dict, Text, Union from kubernetes import client from tfx.orchestration.config import base_component_config from tfx.orchestration.launcher import container_common class KubernetesComponentConfig(base_component_config.BaseComponentConfig): """Component config which holds Kubernetes Pod execution args. Attributes: pod: the spec for a Pod. It can either be an instance of client.V1Pod or a dict of a Pod spec. The spec details are: https://github.com/kubernetes-client/python/blob/master/kubernetes/docs/V1Pod.md """ def __init__(self, pod: Union[client.V1Pod, Dict[Text, Any]]): if not pod: raise ValueError('pod must have a value.') self.pod = container_common.to_swagger_dict(pod)
# Lint as: python2, python3 # Copyright 2019 Google LLC. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by 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. """Component config for Kubernets Pod execution.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from typing import Any, Dict, Text, Union from kubernetes import client from tfx.orchestration.config import base_component_config class KubernetesComponentConfig(base_component_config.BaseComponentConfig): """Component config which holds Kubernetes Pod execution args. Attributes: pod: the spec for a Pod. It can either be an instance of client.V1Pod or a dict of a Pod spec. The spec details are: https://github.com/kubernetes-client/python/blob/master/kubernetes/docs/V1Pod.md """ def __init__(self, pod: Union[client.V1Pod, Dict[Text, Any]]): if not pod: raise ValueError('pod must have a value.') self.pod = pod
PURGE is not defined in HTTP RFCs
<?php namespace Awesomite\Chariot; class HttpMethods { const METHOD_ANY = '*'; const METHOD_HEAD = 'HEAD'; const METHOD_GET = 'GET'; const METHOD_POST = 'POST'; const METHOD_PUT = 'PUT'; const METHOD_DELETE = 'DELETE'; const METHOD_PATCH = 'PATCH'; const METHOD_CONNECT = 'CONNECT'; const METHOD_OPTIONS = 'OPTIONS'; const METHOD_TRACE = 'TRACE'; const ALL_METHODS = [ self::METHOD_ANY, self::METHOD_HEAD, self::METHOD_GET, self::METHOD_POST, self::METHOD_PUT, self::METHOD_DELETE, self::METHOD_PATCH, self::METHOD_CONNECT, self::METHOD_OPTIONS, self::METHOD_TRACE, ]; }
<?php namespace Awesomite\Chariot; class HttpMethods { const METHOD_ANY = '*'; const METHOD_HEAD = 'HEAD'; const METHOD_GET = 'GET'; const METHOD_POST = 'POST'; const METHOD_PUT = 'PUT'; const METHOD_DELETE = 'DELETE'; const METHOD_PATCH = 'PATCH'; const METHOD_CONNECT = 'CONNECT'; const METHOD_OPTIONS = 'OPTIONS'; const METHOD_TRACE = 'TRACE'; const METHOD_PURGE = 'PURGE'; const ALL_METHODS = [ self::METHOD_ANY, self::METHOD_HEAD, self::METHOD_GET, self::METHOD_POST, self::METHOD_PUT, self::METHOD_DELETE, self::METHOD_PATCH, self::METHOD_CONNECT, self::METHOD_OPTIONS, self::METHOD_TRACE, self::METHOD_PURGE, ]; }
Add header to process XML correctly
<?php header("Content-type: text/xml"); echo '<?xml version="1.0" encoding="UTF-8"?>'; echo '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">'; $results = $db->query('SELECT `link`,`change_freq`,`priority` FROM `pages`;'); foreach($results as $row){ echo '<url>'; echo '<loc>'.$instance->href($row['link']).'</loc>'; // get lastmod if file exists $row['link'] = 'pages/'.substr_replace($row['link'], 'php', strrpos($row['link'], '.') +1); if(file_exists($row['link'])){ echo '<lastmod>'.date('c', filemtime($row['link'])).'</lastmod>'; } echo '<changefreq>'.$row['change_freq'].'</changefreq>'; echo '<priority>'.$row['priority'].'</priority>'; echo '</url>'; } echo '</urlset>'; ?>
<?php echo '<?xml version="1.0" encoding="UTF-8"?>'; echo '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">'; $results = $db->query('SELECT `link`,`change_freq`,`priority` FROM `pages`;'); foreach($results as $row){ echo '<url>'; echo '<loc>'.$instance->href($row['link']).'</loc>'; // get lastmod if file exists $row['link'] = 'pages/'.substr_replace($row['link'], 'php', strrpos($row['link'], '.') +1); if(file_exists($row['link'])){ echo '<lastmod>'.date('c', filemtime($row['link'])).'</lastmod>'; } echo '<changefreq>'.$row['change_freq'].'</changefreq>'; echo '<priority>'.$row['priority'].'</priority>'; echo '</url>'; } echo '</urlset>'; ?>
Handle the situation where in old message the 'username' key does not exists With this commit processing an old message with fedmsg_meta will not break if that old message does not have the 'username' key.
# This file is part of fedmsg. # Copyright (C) 2012 Red Hat, Inc. # # fedmsg is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # fedmsg 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 # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with fedmsg; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA # # Authors: Ralph Bean <rbean@redhat.com> # from fedmsg.meta.base import BaseProcessor class AnnounceProcessor(BaseProcessor): __name__ = "announce" __description__ = "Official Fedora Announcements" __link__ = "http://fedoraproject.org/" __docs__ = "http://fedoraproject.org/" __obj__ = "Announcements" def subtitle(self, msg, **config): return msg['msg']['message'] def link(self, msg, **config): return msg['msg']['link'] def usernames(self, msg, **config): users = set() if 'username' in msg: users.update(set([msg['username']])) return users
# This file is part of fedmsg. # Copyright (C) 2012 Red Hat, Inc. # # fedmsg is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # fedmsg 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 # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with fedmsg; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA # # Authors: Ralph Bean <rbean@redhat.com> # from fedmsg.meta.base import BaseProcessor class AnnounceProcessor(BaseProcessor): __name__ = "announce" __description__ = "Official Fedora Announcements" __link__ = "http://fedoraproject.org/" __docs__ = "http://fedoraproject.org/" __obj__ = "Announcements" def subtitle(self, msg, **config): return msg['msg']['message'] def link(self, msg, **config): return msg['msg']['link'] def usernames(self, msg, **config): return set([msg['username']])
Add recipe for deluxe cheeseburger
package net.shadowfacts.foodies.recipe; import cpw.mods.fml.common.registry.GameRegistry; import net.minecraft.init.Items; import net.minecraft.item.ItemStack; import net.shadowfacts.foodies.item.FItems; /** * A helper class for registering recipes. * @author shadowfacts */ public class FRecipes { public static void preInit() { // Shapeless GameRegistry.addShapelessRecipe(new ItemStack(FItems.hamburger), new ItemStack(FItems.toast), new ItemStack(FItems.beefPattie), new ItemStack(FItems.toast)); GameRegistry.addShapelessRecipe(new ItemStack(FItems.cheeseburger), new ItemStack(FItems.hamburger), new ItemStack(FItems.cheese)); GameRegistry.addShapelessRecipe(new ItemStack(FItems.deluxeCheeseburger), new ItemStack(FItems.cheeseburger), new ItemStack(FItems.lettuce), new ItemStack(FItems.tomato)); // Shaped registerSmelting(); } private static void registerSmelting() { // Smelting GameRegistry.addSmelting(Items.bread, new ItemStack(FItems.toast), 0.2f); GameRegistry.addSmelting(Items.cooked_beef, new ItemStack(FItems.beefPattie), 0.3f); } public static void load() { } public static void postInit() { } }
package net.shadowfacts.foodies.recipe; import cpw.mods.fml.common.registry.GameRegistry; import net.minecraft.init.Items; import net.minecraft.item.ItemStack; import net.shadowfacts.foodies.item.FItems; /** * A helper class for registering recipes. * @author shadowfacts */ public class FRecipes { public static void preInit() { // Shapeless GameRegistry.addShapelessRecipe(new ItemStack(FItems.hamburger), new ItemStack(FItems.toast), new ItemStack(FItems.beefPattie), new ItemStack(FItems.toast)); GameRegistry.addShapelessRecipe(new ItemStack(FItems.cheeseburger), new ItemStack(FItems.hamburger), new ItemStack(FItems.cheese)); // Shaped registerSmelting(); } private static void registerSmelting() { // Smelting GameRegistry.addSmelting(Items.bread, new ItemStack(FItems.toast), 0.2f); GameRegistry.addSmelting(Items.cooked_beef, new ItemStack(FItems.beefPattie), 0.3f); } public static void load() { } public static void postInit() { } }
Fix formToDictionary() special case for empty tree.species
// Helper functions for fields defined by the field.html template "use strict"; var $ = require('jquery'), _ = require('underscore'); exports.getField = function getField($fields, name) { return $fields.filter('[data-field="' + name + '"]'); }; exports.formToDictionary = function ($form, $editFields) { var result = {}; _.each($form.serializeArray(), function(item) { var type = exports.getField($editFields, item.name).data('type'); if (type === 'bool'){ return; } else if (item.value === '' && (type === 'int' || type === 'float')) { // convert empty numeric fields to null result[item.name] = null; } else if (item.value === '' && item.name === 'tree.species') { // convert empty species id strings to null result[item.name] = null; } else { result[item.name] = item.value; } }); $form.find('input[name][type="checkbox"]').each(function() { result[this.name] = this.checked; }); return result; };
// Helper functions for fields defined by the field.html template "use strict"; var $ = require('jquery'), _ = require('underscore'); exports.getField = function getField($fields, name) { return $fields.filter('[data-field="' + name + '"]'); }; exports.formToDictionary = function ($form, $editFields) { var result = {}; _.each($form.serializeArray(), function(item) { var type = exports.getField($editFields, item.name).data('type'); if (type === 'bool'){ return; } else if (item.value === '' && (type === 'int' || type === 'float')) { // convert empty numeric fields to null result[item.name] = null; } else if (item.name === 'tree.species') { // convert empty species id strings to null result[item.name] = null; } else { result[item.name] = item.value; } }); $form.find('input[name][type="checkbox"]').each(function() { result[this.name] = this.checked; }); return result; };
Add jest to E2E test
/* global beforeAll, afterAll, test, expect */ const webdriver = require('selenium-webdriver') // Input capabilities const capabilities = { os: 'windows', os_version: '10', browserName: 'chrome', browser_version: 'latest', 'browserstack.local': 'true', build: process.env.BROWSERSTACK_BUILD_NAME, project: process.env.BROWSERSTACK_PROJECT_NAME, 'browserstack.localIdentifier': process.env.BROWSERSTACK_LOCAL_IDENTIFIER, 'browserstack.user': process.env.BROWSERSTACK_USERNAME, 'browserstack.key': process.env.BROWSERSTACK_ACCESS_KEY } const driver = new webdriver.Builder() .usingServer('http://hub-cloud.browserstack.com/wd/hub') .withCapabilities(capabilities) .build() beforeAll(async () => { // HTTP Server should be running on 8099 port of GitHub runner driver.get('http://localhost:8099/test/browser.e2e.html') }, 20000) afterAll(async () => { await driver.quit() }) test('test something', async () => { const title = await driver.getTitle() expect(title).toBe('BrowserStack Tests') }, 5000)
const webdriver = require('selenium-webdriver') // Input capabilities const capabilities = { os: 'windows', os_version: '10', browserName: 'chrome', browser_version: 'latest', 'browserstack.local': 'true', build: process.env.BROWSERSTACK_BUILD_NAME, project: process.env.BROWSERSTACK_PROJECT_NAME, 'browserstack.localIdentifier': process.env.BROWSERSTACK_LOCAL_IDENTIFIER, 'browserstack.user': process.env.BROWSERSTACK_USERNAME, 'browserstack.key': process.env.BROWSERSTACK_ACCESS_KEY } const driver = new webdriver.Builder() .usingServer('http://hub-cloud.browserstack.com/wd/hub') .withCapabilities(capabilities) .build() // HTTP Server should be running on 8099 port of GitHub runner driver.get('http://localhost:8099/test/browser.e2e.html').then(function () { driver.getTitle().then(function (title) { console.log(title) driver.quit() }) })
Fix unicode issue in example code for python2.x
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import, print_function import sys import time from pyspin import spin def show(name, frames): s = spin.Spinner(frames) print(name) for i in range(50): print(u"\r{0}".format(s.next()), end="") sys.stdout.flush() time.sleep(0.1) print('\n') def main(): show("Default", spin.Default) show("Box1", spin.Box1) show("Box2", spin.Box2) show("Box3", spin.Box3) show("Box4", spin.Box4) show("Box5", spin.Box5) show("Box6", spin.Box6) show("Box7", spin.Box7) show("Spin1", spin.Spin1) show("Spin2", spin.Spin2) show("Spin3", spin.Spin3) show("Spin4", spin.Spin4) show("Spin5", spin.Spin5) show("Spin6", spin.Spin6) show("Spin7", spin.Spin7) show("Spin8", spin.Spin8) show("Spin9", spin.Spin9) if __name__ == '__main__': main()
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import, print_function import sys import time from pyspin import spin def show(name, frames): s = spin.Spinner(frames) print(name) for i in range(50): time.sleep(0.1) print("\r{0}".format(s.next()), end="") sys.stdout.flush() print('\n') def main(): show("Default", spin.Default) show("Box1", spin.Box1) show("Box2", spin.Box2) show("Box3", spin.Box3) show("Box4", spin.Box4) show("Box5", spin.Box5) show("Box6", spin.Box6) show("Box7", spin.Box7) show("Spin1", spin.Spin1) show("Spin2", spin.Spin2) show("Spin3", spin.Spin3) show("Spin4", spin.Spin4) show("Spin5", spin.Spin5) show("Spin6", spin.Spin6) show("Spin7", spin.Spin7) show("Spin8", spin.Spin8) show("Spin9", spin.Spin9) if __name__ == '__main__': main()
Fix "ReferenceError: Bob is not defined" for correct use of module.exports
var Bob = require('./bob'); describe("Bob", function() { var bob = new Bob(); it("stating something", function() { var result = bob.hey('Tom-ay-to, tom-aaaah-to.'); expect(result).toEqual('Whatever.'); }); xit("shouting", function() { var result = bob.hey('WATCH OUT!'); expect(result).toEqual('Woah, chill out!'); }); xit("asking a question", function() { var result = bob.hey('Does this cryogenic chamber make me look fat?'); expect(result).toEqual('Sure.'); }); xit("talking forcefully", function() { var result = bob.hey("Let's go make out behind the gym!"); expect(result).toEqual('Whatever.'); }); xit("shouting numbers", function() { var result = bob.hey('1, 2, 3 GO!'); expect(result).toEqual('Woah, chill out!'); }); xit("shouting with special characters", function() { var result = bob.hey('ZOMG THE %^*@#$(*^ ZOMBIES ARE COMING!!11!!1!'); expect(result).toEqual('Woah, chill out!'); }); xit("silence", function() { var result = bob.hey(''); expect(result).toEqual('Fine, be that way!'); }); });
require('./bob'); describe("Bob", function() { var bob = new Bob(); it("stating something", function() { var result = bob.hey('Tom-ay-to, tom-aaaah-to.'); expect(result).toEqual('Whatever.'); }); xit("shouting", function() { var result = bob.hey('WATCH OUT!'); expect(result).toEqual('Woah, chill out!'); }); xit("asking a question", function() { var result = bob.hey('Does this cryogenic chamber make me look fat?'); expect(result).toEqual('Sure.'); }); xit("talking forcefully", function() { var result = bob.hey("Let's go make out behind the gym!"); expect(result).toEqual('Whatever.'); }); xit("shouting numbers", function() { var result = bob.hey('1, 2, 3 GO!'); expect(result).toEqual('Woah, chill out!'); }); xit("shouting with special characters", function() { var result = bob.hey('ZOMG THE %^*@#$(*^ ZOMBIES ARE COMING!!11!!1!'); expect(result).toEqual('Woah, chill out!'); }); xit("silence", function() { var result = bob.hey(''); expect(result).toEqual('Fine, be that way!'); }); });
Support a final URL after potential redirects
'use strict'; module.exports = Response; /** * A response from a web request * * @param {Number} statusCode * @param {Object} headers * @param {Buffer} body */ function Response(statusCode, headers, body, url) { if (typeof statusCode !== 'number') { throw new TypeError('statusCode must be a number but was ' + (typeof statusCode)); } if (headers === null) { throw new TypeError('headers cannot be null'); } if (typeof headers !== 'object') { throw new TypeError('headers must be an object but was ' + (typeof headers)); } this.statusCode = statusCode; this.headers = {}; for (var key in headers) { this.headers[key.toLowerCase()] = headers[key]; } this.body = body; this.url = url; } Response.prototype.getBody = function (encoding) { if (this.statusCode >= 300) { var err = new Error('Server responded with status code ' + this.statusCode + ':\n' + this.body.toString()); err.statusCode = this.statusCode; err.headers = this.headers; err.body = this.body; throw err; } return encoding ? this.body.toString(encoding) : this.body; };
'use strict'; module.exports = Response; /** * A response from a web request * * @param {Number} statusCode * @param {Object} headers * @param {Buffer} body */ function Response(statusCode, headers, body) { if (typeof statusCode !== 'number') { throw new TypeError('statusCode must be a number but was ' + (typeof statusCode)); } if (headers === null) { throw new TypeError('headers cannot be null'); } if (typeof headers !== 'object') { throw new TypeError('headers must be an object but was ' + (typeof headers)); } this.statusCode = statusCode; this.headers = {}; for (var key in headers) { this.headers[key.toLowerCase()] = headers[key]; } this.body = body; } Response.prototype.getBody = function (encoding) { if (this.statusCode >= 300) { var err = new Error('Server responded with status code ' + this.statusCode + ':\n' + this.body.toString()); err.statusCode = this.statusCode; err.headers = this.headers; err.body = this.body; throw err; } return encoding ? this.body.toString(encoding) : this.body; };
Use lazy connection for mysql
'use strict' var express = require('express') var mysql = require('mysql') var crypto = require('crypto') var config = require('./config.json') var connection = mysql.createConnection(config.mysql) var app = express() app.use(express.static(__dirname + '/public/', { index: 'index.htm' })) app.get('/get', function(req, res) { var md5 = req.query.md5 connection.query('SELECT * FROM md5 WHERE ?', { md5: md5 }, function(err, result) { if (err) throw new Error(err) res.send(result[0] && result[0].str) }) }) app.get('/set', function(req, res) { var str = req.query.str || '' var md5 = crypto.createHash('md5').update(str).digest('hex') connection.query('INSERT IGNORE INTO md5 set ?', { str: str, md5: md5 }, function(err, result) { if (err) throw new Error(err) res.send(md5) }) }) app.listen(config.port) console.log('now listening to port', config.port)
'use strict' var express = require('express') var mysql = require('mysql') var crypto = require('crypto') var config = require('./config.json') var connection = mysql.createConnection(config.mysql) connection.connect(function(err) { if (err) throw new Error(err) }) var app = express() app.use(express.static(__dirname + '/public/', { index: 'index.htm' })) app.get('/get', function(req, res) { var md5 = req.query.md5 connection.query('SELECT * FROM md5 WHERE ?', { md5: md5 }, function(err, result) { if (err) throw new Error(err) res.send(result[0] && result[0].str) }) }) app.get('/set', function(req, res) { var str = req.query.str || '' var md5 = crypto.createHash('md5').update(str).digest('hex') connection.query('INSERT IGNORE INTO md5 set ?', { str: str, md5: md5 }, function(err, result) { if (err) throw new Error(err) res.send(md5) }) }) app.listen(config.port) console.log('now listening to port', config.port)
Fix python module package thanks to landscape.io
# -*- encoding: utf-8 -*- # # In here you will find all the handlers that are tasked with handling the # requests specified in the API. # # From these handlers we will be instantiating models objects that will take care # of our business logic and the generation of the output to be sent to GLClient. # # In here we are also tasked with doing the validation of the user supplied # input. This must be done before instantiating any models object. # Validation of input may be done with the functions inside of # globaleaks.rest. # # See base.BaseHandler for details on the handlers. __all__ = ['admin', 'base', 'files', 'public', 'receiver', 'rtip', 'submission', 'wbtip']
# -*- encoding: utf-8 -*- # # In here you will find all the handlers that are tasked with handling the # requests specified in the API. # # From these handlers we will be instantiating models objects that will take care # of our business logic and the generation of the output to be sent to GLClient. # # In here we are also tasked with doing the validation of the user supplied # input. This must be done before instantiating any models object. # Validation of input may be done with the functions inside of # globaleaks.rest. # # See base.BaseHandler for details on the handlers. __all__ = ['admin', 'base', 'files', 'node', 'receiver', 'rtip', 'submission', 'wbtip']
Fix default location selected (now uses allowed locations only)
<?php class Item_lib { var $CI; function __construct() { $this->CI =& get_instance(); } function get_item_location() { if(!$this->CI->session->userdata('item_location')) { $stock_locations = $this->CI->Stock_locations->get_allowed_locations(); $key=current(array_keys($stock_locations)); $location_name = $stock_locations[$key]['location_id']; $this->set_item_location($location_name); } return $this->CI->session->userdata('item_location'); } function set_item_location($location) { $this->CI->session->set_userdata('item_location',$location); } function clear_item_location() { $this->CI->session->unset_userdata('item_location'); } } ?>
<?php class Item_lib { var $CI; function __construct() { $this->CI =& get_instance(); } function get_item_location() { if(!$this->CI->session->userdata('item_location')) { $stock_locations = $this->CI->Stock_locations->get_undeleted_all()->result_array(); $location_name = $stock_locations[0]['location_id']; $this->set_item_location($location_name); } return $this->CI->session->userdata('item_location'); } function set_item_location($location) { $this->CI->session->set_userdata('item_location',$location); } function clear_item_location() { $this->CI->session->unset_userdata('item_location'); } } ?>
Change type to shipment in dispatching.
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class EcontDispatching extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::setConnection(DB::connection(Config::get('econt.connection')))->create('econt_dispatching', function (Blueprint $table) { $table->unsignedInteger('settlement_id'); $table->enum('direction', ['from', 'to'])->index('idx_direction'); $table->enum('shipment', ['courier', 'cargo_pallet', 'cargo_express', 'post'])->index('idx_shipment'); $table->unsignedInteger('office_code'); $table->primary(['settlement_id', 'direction', 'shipment']); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::setConnection(DB::connection(Config::get('econt.connection')))->dropIfExists('econt_dispatching'); } }
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class EcontDispatching extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::setConnection(DB::connection(Config::get('econt.connection')))->create('econt_dispatching', function (Blueprint $table) { $table->unsignedInteger('settlement_id'); $table->enum('direction', ['from', 'to'])->index('idx_direction'); $table->enum('shipment', ['courier', 'cargo_pallet', 'cargo_express', 'post'])->index('idx_shipment'); $table->unsignedInteger('office_code'); $table->primary(['settlement_id', 'direction', 'shipment', 'office_code']); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::setConnection(DB::connection(Config::get('econt.connection')))->dropIfExists('econt_dispatching'); } }
Fix build issues when sharedscripts10 is not available. By calling project.install with --no-spawn, we can avoid an error that happened during build: [ben10] Resource not found "sharedscripts10".
from __future__ import unicode_literals from aasimar.shared_commands import BuildCommand from ben10.foundation.decorators import Override #=================================================================================================== # Ben10BuildCommand #=================================================================================================== class Ben10BuildCommand(BuildCommand): PLATFORMS = ['win32', 'win64', 'redhat64', 'centos64'] @Override(BuildCommand.EvBuild) def EvBuild(self, args): self.Clean() self.Install(no_spawn=True) self.IsClean() self.RunTests( jobs=self.shared_script['hudson_test_jobs'], use_cache=not self.opts.no_cache, xml=True, verbose=4 ) @Override(BuildCommand.EvPublish) def EvPublish(self, args): self.CiPublish(installer=False, all_platforms='win32,win64,redhat64', force=True)
from __future__ import unicode_literals from aasimar.shared_commands import BuildCommand from ben10.foundation.decorators import Override #=================================================================================================== # Ben10BuildCommand #=================================================================================================== class Ben10BuildCommand(BuildCommand): PLATFORMS = ['win32', 'win64', 'redhat64', 'centos64'] @Override(BuildCommand.EvBuild) def EvBuild(self, args): self.Clean() self.Install() self.IsClean() self.RunTests( jobs=self.shared_script['hudson_test_jobs'], use_cache=not self.opts.no_cache, xml=True, verbose=4 ) @Override(BuildCommand.EvPublish) def EvPublish(self, args): self.CiPublish(installer=False, all_platforms='win32,win64,redhat64', force=True)
[Android] Use library Context to get Inflater for shared mode For color picker on Android, it uses ColorPickerAdvanced and ColorPickerSimple which is customized view. So the inflater should contain the ClassLoader which has loaded the relevant classes. As for shared mode, it's library Context. BUG=https://crosswalk-project.org/jira/browse/XWALK-1534
// Copyright (c) 2013 Intel Corporation. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.xwalk.runtime; import android.content.Context; import android.content.ContextWrapper; import android.content.Intent; import android.content.ServiceConnection; /** * MixedContext provides ApplicationContext for the contextImpl object * created by Context.CreatePackageContext(). * * For cross package usage, the library part need the possibility to * get both the application's context and the library itself's context. * */ class MixedContext extends ContextWrapper { private Context mActivityCtx; public MixedContext(Context base, Context activity) { super(base); mActivityCtx = activity; } @Override public Context getApplicationContext() { return mActivityCtx.getApplicationContext(); } @Override public boolean bindService(Intent in, ServiceConnection conn, int flags) { return getApplicationContext().bindService(in, conn, flags); } @Override public void unbindService(ServiceConnection conn) { getApplicationContext().unbindService(conn); } @Override public Object getSystemService(String name) { if (name.equals(Context.LAYOUT_INFLATER_SERVICE)) { return super.getSystemService(name); } return mActivityCtx.getSystemService(name); } }
// Copyright (c) 2013 Intel Corporation. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.xwalk.runtime; import android.content.Context; import android.content.ContextWrapper; import android.content.Intent; import android.content.ServiceConnection; /** * MixedContext provides ApplicationContext for the contextImpl object * created by Context.CreatePackageContext(). * * For cross package usage, the library part need the possibility to * get both the application's context and the library itself's context. * */ class MixedContext extends ContextWrapper { private Context mActivityCtx; public MixedContext(Context base, Context activity) { super(base); mActivityCtx = activity; } @Override public Context getApplicationContext() { return mActivityCtx.getApplicationContext(); } @Override public boolean bindService(Intent in, ServiceConnection conn, int flags) { return getApplicationContext().bindService(in, conn, flags); } @Override public void unbindService(ServiceConnection conn) { getApplicationContext().unbindService(conn); } @Override public Object getSystemService(String name) { return mActivityCtx.getSystemService(name); } }
admin_auth: Use passwordinput in password field.
# -*- coding: utf-8 -*- from django import forms from uni_form.helper import FormHelper from uni_form.layout import Submit, Layout, Fieldset, ButtonHolder class LoginForm(forms.Form): username = forms.CharField(label=u"Käyttäjätunnus", help_text=u"Admin-paneelin käyttäjätunnuksesi. Huom! OpenID-tunnukset eivät kelpaa!") password = forms.CharField(label=u"Salasana", widget=forms.PasswordInput) def __init__(self, *args, **kwargs): super(LoginForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.layout = Layout( Fieldset( u'', 'username', 'password', ButtonHolder ( Submit('submit', 'Kirjaudu sisään') ) ) )
# -*- coding: utf-8 -*- from django import forms from uni_form.helper import FormHelper from uni_form.layout import Submit, Layout, Fieldset, ButtonHolder class LoginForm(forms.Form): username = forms.CharField(label=u"Käyttäjätunnus", help_text=u"Admin-paneelin käyttäjätunnuksesi. Huom! OpenID-tunnukset eivät kelpaa!") password = forms.CharField(label=u"Salasana") def __init__(self, *args, **kwargs): super(LoginForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.layout = Layout( Fieldset( u'', 'username', 'password', ButtonHolder ( Submit('submit', 'Kirjaudu sisään') ) ) )
Fix unit tests for the blacklist
import unittest import config import ntokloapi class BlacklistTest(unittest.TestCase): def setUp(self): self.blacklist = ntokloapi.Blacklist(config.TEST_KEY, config.TEST_SECRET) def test_blacklist_add_singleitem(self): response = self.blacklist.add(productid=['10201', ]) assert response == 204 def test_blacklist_add_multipleitems(self): response = self.blacklist.add(productid=['10202', '10203']) assert response == 204 def test_blacklist_add_empty_elements(self): response = self.blacklist.add(productid=['10204', '10205', '', '']) assert response == 204 def test_blacklist_remove_singleitem(self): response = self.blacklist.remove(productid=['10201', ]) assert response == 204 def test_blacklist_remove_multipleitems(self): response = self.blacklist.remove(productid=['10202', '10203']) assert response == 204 def test_blacklist_remove_empty_elements(self): response = self.blacklist.remove(productid=['10204', '10205', '', '']) assert response == 204 def test_blacklist_show_items(self): response = self.blacklist.list() assert not response
import unittest import config from .. import ntokloapi class BlacklistTest(unittest.TestCase): def setUp(self): self.blacklist = ntokloapi.Blacklist(config.TEST_KEY, config.TEST_SECRET) def test_blacklist_add_singleitem(self): response = self.blacklist.add(productid=['10201', ]) assert response == "204" def test_blacklist_add_multipleitems(self): response = self.blacklist.add(productid=['10202', '10203']) assert response == "204" def test_blacklist_add_empty_elements(self): response = self.blacklist.add(productid=['10204', '10205', '', '']) assert response == "204" def test_blacklist_remove_singleitem(self): response = self.blacklist.remove(productid=['10201', ]) assert response == "204" def test_blacklist_remove_multipleitems(self): response = self.blacklist.remove(productid=['10202', '10203']) assert response == "204" def test_blacklist_remove_empty_elements(self): response = self.blacklist.remove(productid=['10204', '10205', '', '']) assert response == "204" def test_blacklist_show_items(self): response = self.blacklist.list() assert not response
Use the option "watch" in Grunt compass task
/*jshint strict:true, browser:true, jquery:true, devel:true, curly:true, eqeqeq:true, immed:true, latedef:true, plusplus:true, undef:true, unused:true, laxbreak:true, nonew:false */ /*global module */ module.exports = function(grunt) { "use strict"; grunt.initConfig({ compass: { dist: { options: { httpPath: '/', sassDir: 'scss', cssDir: 'public/css', sourcemap: true, watch: true } } }, watch: { scss: { files: ['scss/**'], tasks: ['compass'], options: { interrupt: true } } }, }); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-contrib-sass'); grunt.loadNpmTasks('grunt-contrib-compass'); grunt.registerTask("default", []); };
/*jshint strict:true, browser:true, jquery:true, devel:true, curly:true, eqeqeq:true, immed:true, latedef:true, plusplus:true, undef:true, unused:true, laxbreak:true, nonew:false */ /*global module */ module.exports = function(grunt) { "use strict"; grunt.initConfig({ compass: { dist: { options: { httpPath: '/', sassDir: 'scss', cssDir: 'public/css', sourcemap: true } } }, watch: { scss: { files: ['scss/**'], tasks: ['compass'], options: { interrupt: true } } }, }); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-contrib-sass'); grunt.loadNpmTasks('grunt-contrib-compass'); grunt.registerTask("default", []); };
Fix break caused by Cadence changes.
var cadence = require('cadence') var logger = require('prolific.logger').createLogger('mingle.srv') var sprintf = require('sprintf-js').sprintf module.exports = cadence(function (async, dns, name, format) { async([function () { dns.resolve(name, 'SRV', async()) }, function (error) { logger.error('resolve.SRV', { stack: error.stack }) return [ async.break, [] ] }], function (records) { async.map(function (record) { var block = async([function () { dns.resolve(record.name, 'A', async()) }, function (error) { logger.error('resolve.A', { stack: error.stack, record: record }) return [ block.break, null ] }], function (address) { return [ block.break, sprintf(format, address, +record.port) ] })() })(records) }, function (discovered) { return [ discovered ] }) })
var cadence = require('cadence') var logger = require('prolific.logger').createLogger('mingle.srv') var sprintf = require('sprintf-js').sprintf module.exports = cadence(function (async, dns, name, format) { async([function () { dns.resolve(name, 'SRV', async()) }, function (error) { logger.error('resolve.SRV', { stack: error.stack }) return [ async.break, [] ] }], function (records) { async.map(function (record) { async([function () { dns.resolve(record.name, 'A', async()) }, function (error) { logger.error('resolve.A', { stack: error.stack, record: record }) return [ async.break, null ] }], function (address) { return [ sprintf(format, address, +record.port) ] }) })(records) }, function (discovered) { return [ discovered ] }) })
Make the thing work, for now
<?php namespace Mini\Model\TypeCrawler; use \Mini\Model\TypeCrawler\Storage\StorageFactory; //TODO do this right use \Mini\Model\TypeCrawler\ModBot; class TypeCrawlerController { /** @var array */ private $crawlers; /** @var StorageFactory */ private $storage; function __construct(StorageFactory $storageFactory) { $this->crawlers = array(); $this->storage = $storageFactory; $this->registerCrawler('ModBot'); } public function registerCrawler(string $crawler) { $this->crawlers[] = new $crawler($this->storage->getStorage($crawler::$type)); } public function triggerCrawl(): array { $ret = array(); foreach($this->crawlers as $crawler) { $ret = array_merge($ret, $crawler->crawl()); } } }
<?php namespace Mini\Model\TypeCrawler; use \Mini\Model\TypeCrawler\Storage\StorageFactory; class TypeCrawlerController { /** @var array */ private $crawlers; /** @var StorageFactory */ private $storage; function __construct(StorageFactory $storageFactory) { $this->crawlers = array(); $this->storage = $storageFactory; $this->registerCrawler('ModBot'); } public function registerCrawler(string $crawler) { $this->crawlers[] = new $crawler($this->storage->getStorage($crawler::$type)); } public function triggerCrawl(): array { $ret = array(); foreach($this->crawlers as $crawler) { $ret = array_merge($ret, $crawler->crawl()); } } }
Mark "Enter your postcode" for translation in a form field label
from django import forms from django.utils.translation import gettext_lazy as _ from localflavor.gb.forms import GBPostcodeField class PostcodeLookupForm(forms.Form): postcode = GBPostcodeField(label=_("Enter your postcode")) class AddressSelectForm(forms.Form): address = forms.ChoiceField( choices=(), label="", initial="", widget=forms.Select( attrs={ "class": "select_multirow", "size": 10, "aria-describedby": "address_picker", } ), required=True, ) postcode = None def __init__(self, choices, postcode, *args, **kwargs): super(AddressSelectForm, self).__init__(*args, **kwargs) self.fields["address"].choices = choices self.postcode = postcode
from django import forms from localflavor.gb.forms import GBPostcodeField class PostcodeLookupForm(forms.Form): postcode = GBPostcodeField(label="Enter your postcode") class AddressSelectForm(forms.Form): address = forms.ChoiceField( choices=(), label="", initial="", widget=forms.Select( attrs={ "class": "select_multirow", "size": 10, "aria-describedby": "address_picker", } ), required=True, ) postcode = None def __init__(self, choices, postcode, *args, **kwargs): super(AddressSelectForm, self).__init__(*args, **kwargs) self.fields["address"].choices = choices self.postcode = postcode
Remove unused parameters and variables
// Copyright 2015 Yahoo! Inc. // Copyrights licensed under the Mit License. See the accompanying LICENSE file for terms. var CoreBase = require('preceptor-core').Base; /** * @class Base * @extends CoreBase * @module Configuration */ var Base = CoreBase.extend( { /** * Parses object information * * @method _parseObject * @param {object|Image} value * @param {object} Constr Constructor of data-type * @param {string} typeStr Textual type description of object * @return {object} * @private */ _parseObject: function (value, Constr, typeStr) { if (typeof value == 'object' && !value instanceof Constr) { value = new Constr(value); } if (value instanceof Constr) { return value; } else { throw new Error('Unknown ' + typeStr + ' descriptor.'); } } }, { /** * @property TYPE * @type {string} * @static */ TYPE: 'CONFIGURATION_BASE' } );
// Copyright 2015 Yahoo! Inc. // Copyrights licensed under the Mit License. See the accompanying LICENSE file for terms. var CoreBase = require('preceptor-core').Base; var Image = require('./image'); var Comparison = require('./comparison'); var Threshold = require('./atoms/threshold'); var Color = require('./atoms/color'); var Output = require('./output'); var Rect = require('./atoms/rect'); /** * @class Base * @extends CoreBase * @module Configuration * * @property {boolean} debug * @property {boolean} verbose * @property {Image} _imageA * @property {Image} _imageB * @property {Comparison[]} _comparisons * @property {Threshold} _threshold * @property {Color} _backgroundColor * @property {Color} _ignoreColor * @property {Output} _output */ var Base = CoreBase.extend( { /** * Parses object information * * @method _parseObject * @param {object|Image} value * @param {object} Constr Constructor of data-type * @param {string} typeStr Textual type description of object * @return {object} * @private */ _parseObject: function (value, Constr, typeStr) { if (typeof value == 'object' && !value instanceof Constr) { value = new Constr(value); } if (value instanceof Constr) { return value; } else { throw new Error('Unknown ' + typeStr + ' descriptor.'); } } }, { /** * @property TYPE * @type {string} * @static */ TYPE: 'CONFIGURATION_BASE' } );
Stop console error about content security policy
/* jshint node: true */ module.exports = function(environment) { var ENV = { modulePrefix: 'smallprint', environment: environment, baseURL: '/', locationType: 'auto', EmberENV: { FEATURES: { // Here you can enable experimental features on an ember canary build // e.g. 'with-controller': true } }, contentSecurityPolicy: { 'style-src': "'self' 'unsafe-inline'", }, APP: { // Here you can pass flags/options to your application instance // when it is created } }; if (environment === 'development') { // ENV.APP.LOG_RESOLVER = true; // ENV.APP.LOG_ACTIVE_GENERATION = true; // ENV.APP.LOG_TRANSITIONS = true; // ENV.APP.LOG_TRANSITIONS_INTERNAL = true; // ENV.APP.LOG_VIEW_LOOKUPS = true; } if (environment === 'test') { // Testem prefers this... ENV.baseURL = '/'; ENV.locationType = 'none'; // keep test console output quieter ENV.APP.LOG_ACTIVE_GENERATION = false; ENV.APP.LOG_VIEW_LOOKUPS = false; ENV.APP.rootElement = '#ember-testing'; } if (environment === 'production') { } return ENV; };
/* jshint node: true */ module.exports = function(environment) { var ENV = { modulePrefix: 'smallprint', environment: environment, baseURL: '/', locationType: 'auto', EmberENV: { FEATURES: { // Here you can enable experimental features on an ember canary build // e.g. 'with-controller': true } }, APP: { // Here you can pass flags/options to your application instance // when it is created } }; if (environment === 'development') { // ENV.APP.LOG_RESOLVER = true; // ENV.APP.LOG_ACTIVE_GENERATION = true; // ENV.APP.LOG_TRANSITIONS = true; // ENV.APP.LOG_TRANSITIONS_INTERNAL = true; // ENV.APP.LOG_VIEW_LOOKUPS = true; } if (environment === 'test') { // Testem prefers this... ENV.baseURL = '/'; ENV.locationType = 'none'; // keep test console output quieter ENV.APP.LOG_ACTIVE_GENERATION = false; ENV.APP.LOG_VIEW_LOOKUPS = false; ENV.APP.rootElement = '#ember-testing'; } if (environment === 'production') { } return ENV; };
Remove unused variables from config.
<?php // Example of config file, add your own values here, all are imaginary $config = array( 'release_title' => 'Freya', 'release_version' => '0.3.2', 'stripe_sk' => 'sk_test_hoigesrjgoisrhgilgjrsfjs', 'stripe_pk' => 'pk_test_hoigesrjgoisrhgilgjrsfjs', 'slack_token' => 'asdf-1234567890-7418529630-a7854123692-8412487519', 'twitter_consumer_key' => 'test_ckey', 'twitter_consumer_secret' => 'test_csecret', 'twitter_access_token' => 'test_atoken', 'twitter_access_secret' => 'test_asecret', );
<?php // Example of config file, add your own values here, all are imaginary $config = array( 'release_title' => 'Freya', 'release_version' => '0.3.2', 'stripe_sk' => 'sk_test_hoigesrjgoisrhgilgjrsfjs', 'stripe_pk' => 'pk_test_hoigesrjgoisrhgilgjrsfjs', 'slack_token' => 'asdf-1234567890-7418529630-a7854123692-8412487519', 'twitter_consumer_key' => 'test_ckey', 'twitter_consumer_secret' => 'test_csecret', 'twitter_access_token' => 'test_atoken', 'twitter_access_secret' => 'test_asecret', 'sourceforge_iso_i386' => 'http://sourceforge.net/projects/elementaryos/files/stable/elementaryos-freya-i386.20150411.iso/download', 'sourceforge_iso_amd64' => 'http://sourceforge.net/projects/elementaryos/files/stable/elementaryos-freya-amd64.20150411.iso/download', );
[ALIEN-2755] Allow specific handling of docker image artifact update in the editor, util fix.
package org.alien4cloud.tosca.utils; import static alien4cloud.utils.AlienUtils.safe; import java.util.Map; import java.util.Optional; import org.alien4cloud.tosca.model.definitions.ImplementationArtifact; import org.alien4cloud.tosca.model.definitions.Interface; import org.alien4cloud.tosca.model.definitions.Operation; public final class InterfaceUtils { private InterfaceUtils() { } public static ImplementationArtifact getArtifact(Map<String, Interface> interfaceMap, String interfaceName, String operationName) { Interface interfaz = safe(interfaceMap).get(interfaceName); if (interfaz == null) { return null; } Operation operation = safe(interfaz.getOperations()).get(operationName); if(operation == null) { return null; } return operation.getImplementationArtifact(); } }
package org.alien4cloud.tosca.utils; import static alien4cloud.utils.AlienUtils.safe; import java.util.Map; import java.util.Optional; import org.alien4cloud.tosca.model.definitions.ImplementationArtifact; import org.alien4cloud.tosca.model.definitions.Interface; import org.alien4cloud.tosca.model.definitions.Operation; public final class InterfaceUtils { private InterfaceUtils() { } public static ImplementationArtifact getArtifact(Map<String, Interface> interfaceMap, String interfaceName, String operationName) { Optional.of(safe(interfaceMap).get(interfaceName)).map() Interface interfaz = safe(interfaceMap).get(interfaceName); if (interfaz == null) { return null; } Operation operation = safe(interfaz.getOperations()).get(operationName); if(operation == null) { return null; } return operation.getImplementationArtifact(); } }
Edit search pattern for FPD vulnerability scan
/** * wpscan module fpd-vulnerability.js * Scan a PHP file for Full Path Disclosure */ /** * Required modules */ const request = require( 'request' ).defaults( { followRedirect: false } ) const fs = require( '../fs' ) const log = require( '../log' ) /** * Initiator method * * @param {Object} data Data object with request values * @return void */ exports.fire = ( data ) => { const { wpURL, siteURL, userAgent, silentMode } = data const filterName = fs.fileName( __filename, '.js' ) const logObj = { silentMode, filterName } const targetURL = `${wpURL}/wp-includes/rss.php` request( { 'url': targetURL, 'method': 'GET', 'headers': { 'User-Agent': userAgent } }, ( error, response, body ) => { if ( error || response.statusCode === 404 ) { return log.info( `${targetURL} is not found`, logObj ) } if ( body.includes( '_deprecated_file' ) ) { return log.warn( `${siteURL} is affected by FPD vulnerability`, logObj ) } return log.ok( `${siteURL} is not affected by FPD vulnerability`, logObj ) } ) }
/** * wpscan module fpd-vulnerability.js * Scan a PHP file for Full Path Disclosure */ /** * Required modules */ const request = require( 'request' ).defaults( { followRedirect: false } ) const fs = require( '../fs' ) const log = require( '../log' ) /** * Initiator method * * @param {Object} data Data object with request values * @return void */ exports.fire = ( data ) => { const { wpURL, siteURL, userAgent, silentMode } = data const filterName = fs.fileName( __filename, '.js' ) const logObj = { silentMode, filterName } const targetURL = `${wpURL}/wp-includes/rss.php` request( { 'url': targetURL, 'method': 'GET', 'headers': { 'User-Agent': userAgent } }, ( error, response, body ) => { if ( error || response.statusCode === 404 ) { return log.info( `${targetURL} is not found`, logObj ) } if ( body.includes( '.php' ) ) { return log.warn( `${siteURL} is affected by FPD vulnerability`, logObj ) } return log.ok( `${siteURL} is not affected by FPD vulnerability`, logObj ) } ) }
Fix scoreboard team using wrong packet idTeam
package protocolsupport.protocol.packet.middleimpl.writeable.play.v_5_6; import io.netty.buffer.ByteBuf; import net.md_5.bungee.protocol.packet.Team; import protocolsupport.protocol.packet.id.LegacyPacketId; import protocolsupport.protocol.packet.middleimpl.writeable.LegacySingleWriteablePacket; import protocolsupport.protocol.serializer.StringSerializer; public class ScoreboardTeamPacket extends LegacySingleWriteablePacket<Team> { public ScoreboardTeamPacket() { super(LegacyPacketId.Clientbound.PLAY_SCOREBOARD_TEAM); } @Override protected void write(ByteBuf data, Team packet) { StringSerializer.writeShortUTF16BEString(data, packet.getName()); int mode = packet.getMode(); data.writeByte(mode); if ((mode == 0) || (mode == 2)) { StringSerializer.writeShortUTF16BEString(data, packet.getDisplayName()); StringSerializer.writeShortUTF16BEString(data, packet.getPrefix()); StringSerializer.writeShortUTF16BEString(data, packet.getSuffix()); data.writeByte(packet.getFriendlyFire()); } if ((mode == 0) || (mode == 3) || (mode == 4)) { data.writeShort(packet.getPlayers().length); for (String player : packet.getPlayers()) { StringSerializer.writeShortUTF16BEString(data, player); } } } }
package protocolsupport.protocol.packet.middleimpl.writeable.play.v_5_6; import io.netty.buffer.ByteBuf; import net.md_5.bungee.protocol.packet.Team; import protocolsupport.protocol.packet.id.LegacyPacketId; import protocolsupport.protocol.packet.middleimpl.writeable.LegacySingleWriteablePacket; import protocolsupport.protocol.serializer.StringSerializer; public class ScoreboardTeamPacket extends LegacySingleWriteablePacket<Team> { public ScoreboardTeamPacket() { super(LegacyPacketId.Clientbound.PLAY_SCOREBOARD_SCORE); } @Override protected void write(ByteBuf data, Team packet) { StringSerializer.writeShortUTF16BEString(data, packet.getName()); int mode = packet.getMode(); data.writeByte(mode); if ((mode == 0) || (mode == 2)) { StringSerializer.writeShortUTF16BEString(data, packet.getDisplayName()); StringSerializer.writeShortUTF16BEString(data, packet.getPrefix()); StringSerializer.writeShortUTF16BEString(data, packet.getSuffix()); data.writeByte(packet.getFriendlyFire()); } if ((mode == 0) || (mode == 3) || (mode == 4)) { data.writeShort(packet.getPlayers().length); for (String player : packet.getPlayers()) { StringSerializer.writeShortUTF16BEString(data, player); } } } }
Compress built JS and generate sourcemaps Uncompressed JS is unnecessarily large, but compressing it makes it difficult to debug. Sourcemaps allow for both optimal size and easy debugging.
'use strict'; module.exports = function(grunt) { grunt.config.set('requirejs', { prod: { options: { baseUrl: '.', mainConfigFile: 'src/requirejs-config.js', insertRequire: ['main'], name: 'bower_components/almond/almond', out: 'prod/app.js', optimize: 'uglify2', generateSourceMaps: true, preserveLicenseComments: false, // Because we override the application `baseUrl` to be the root of the // projuct during the build (see above), the paths to the `main` script // and the `modules` directory has to be modified to include `src/`. paths: { main: 'src/main', modules: 'src/modules', }, }, }, }); grunt.loadNpmTasks('grunt-contrib-requirejs'); };
'use strict'; module.exports = function(grunt) { grunt.config.set('requirejs', { prod: { options: { baseUrl: '.', mainConfigFile: 'src/requirejs-config.js', insertRequire: ['main'], name: 'bower_components/almond/almond', out: 'prod/app.js', // Because we override the application `baseUrl` to be the root of the // projuct during the build (see above), the paths to the `main` script // and the `modules` directory has to be modified to include `src/`. paths: { main: 'src/main', modules: 'src/modules', }, }, }, }); grunt.loadNpmTasks('grunt-contrib-requirejs'); };
Add more tests for RandomService
<?php namespace Raffle; final class RandomServiceTest extends \PHPUnit_Framework_TestCase { /** * @var RandomService */ private $service; public function setUp() { $this->service = new RandomService(); } public function test_amount_of_random_numbers_returned() { $numbers = $this->service->getRandomNumbers(10); $this->assertCount(10, $numbers); } public function test_list_of_random_numbers_are_unique() { $numbers = $this->service->getRandomNumbers(10); $uniqueNumbers = array_unique($numbers); $this->assertSame($numbers, $uniqueNumbers); } public function test_list_is_empty_when_amount_zero() { // The service should not return any numbers if the amount is zero $this->assertEmpty($this->service->getRandomNumbers(0)); } public function test_list_includes_zero() { // The service should return _all_ numbers for $amount in random order $this->assertContains(0, $this->service->getRandomNumbers(1)); $this->assertContains(0, $this->service->getRandomNumbers(2)); } }
<?php namespace Raffle; final class RandomServiceTest extends \PHPUnit_Framework_TestCase { /** * @var RandomService */ private $service; public function setUp() { $this->service = new RandomService(); } public function test_amount_of_random_numbers_returned() { $numbers = $this->service->getRandomNumbers(10); $this->assertCount(10, $numbers); } public function test_list_of_random_numbers_are_unique() { $numbers = $this->service->getRandomNumbers(10); $uniqueNumbers = array_unique($numbers); $this->assertSame($numbers, $uniqueNumbers); } }
Check if go get should upate
package main import ( "errors" "fmt" "log" "os/exec" "github.com/mtibben/gogpm/vcs" ) // Iterates over Godep file dependencies and sets // the specified version on each of them. func install() error { deps, err := readDepFile() if err != nil { return err } _, err = exec.LookPath("go") if err != nil { return errors.New("Go is currently not installed or in your PATH\n") } for dep, version := range deps { log.Printf("Getting %s\n", dep) update := "" rr, err := vcs.RepoRootForImportPath(dep) if err == nil { absoluteVcsPath := installPath(rr.Root) cur, _ := rr.Vcs.CurrentTag(absoluteVcsPath) if cur != version { update = "-u" } } out, err := execCmd(fmt.Sprintf(`go get -d %s "%s/..."`, update, dep)) if err != nil { log.Println(out) return err } err = setPackageToVersion(dep, version) if err != nil { return err } } log.Println("All Done") return nil }
package main import ( "errors" "fmt" "log" "os/exec" ) // Iterates over Godep file dependencies and sets // the specified version on each of them. func install() error { deps, err := readDepFile() if err != nil { return err } _, err = exec.LookPath("go") if err != nil { return errors.New("Go is currently not installed or in your PATH\n") } for dep, version := range deps { log.Printf("Getting %s\n", dep) out, err := execCmd(fmt.Sprintf(`go get -d "%s/..."`, dep)) if err != nil { log.Println(out) return err } err = setPackageToVersion(dep, version) if err != nil { return err } } log.Println("All Done") return nil }
Fix out of memory error caused when generating timeslot
<?php namespace Igniter\Flame\Location; use DateInterval; use DatePeriod; use DateTimeInterface; use Illuminate\Support\Collection; class WorkingTimeslot extends Collection { public function generate(DateTimeInterface $date, DateInterval $interval, ?DateInterval $leadTime = null) { $items = []; foreach ($this->items as $range) { $start = $range->start()->toDateTime($date); $end = $range->end()->toDateTime($date); if ($range->endsNextDay()) $end->add(new DateInterval('P1D')); if (!is_null($leadTime)) $start = $start->add($leadTime); if ($interval->format('%i') < 5) $interval->i = 5; $datePeriod = new DatePeriod($start, $interval, $end); foreach ($datePeriod as $dateTime) { $items[] = $dateTime; } } return new static($items); } }
<?php namespace Igniter\Flame\Location; use DateInterval; use DatePeriod; use DateTimeInterface; use Illuminate\Support\Collection; class WorkingTimeslot extends Collection { public function generate(DateTimeInterface $date, DateInterval $interval, ?DateInterval $leadTime = null) { $items = []; foreach ($this->items as $range) { $start = $range->start()->toDateTime($date); $end = $range->end()->toDateTime($date); if ($range->endsNextDay()) $end->add(new DateInterval('P1D')); if (!is_null($leadTime)) $start = $start->add($leadTime); $datePeriod = new DatePeriod($start, $interval, $end); foreach ($datePeriod as $dateTime) { $items[] = $dateTime; } } return new static($items); } }
Fix syntax error in collector test
#!/usr/bin/python # coding=utf-8 ################################################################################ from test import CollectorTestCase from test import get_collector_config from test import unittest from mock import patch from diamond.collector import Collector from numa import NumaCollector ################################################################################ class TestExampleCollector(CollectorTestCase): def setUp(self): config = get_collector_config('NumaCollector', { 'interval': 10 }) self.collector = NumaCollector(config, None) def test_import(self): self.assertTrue(NumaCollector) @patch.object(Collector, 'publish') def test(self, publish_mock): self.collector.collect() metrics = { 'node_0_free_MB': 42, 'node_0_size_MB': 402 } self.setDocNuma(collector=self.collector.__class__.__name__, metrics=metrics, defaultpath=self.collector.config['path']) self.assertPublishedMany(publish_mock, metrics) ################################################################################ if __name__ == "__main__": unittest.main()
#!/usr/bin/python # coding=utf-8 ################################################################################ from test import CollectorTestCase from test import get_collector_config from test import unittest from mock import patch from diamond.collector import Collector from numa import NumaCollector ################################################################################ class TestExampleCollector(CollectorTestCase): def setUp(self): config = get_collector_config('NumaCollector', { 'interval': 10 }) self.collector = NumaCollector(config, None) def test_import(self): self.assertTrue(NumaCollector) @patch.object(Collector, 'publish') def test(self, publish_mock): self.collector.collect() metrics = { 'node_0_free_MB': 42 'node_0_size_MB': 402 } self.setDocNuma(collector=self.collector.__class__.__name__, metrics=metrics, defaultpath=self.collector.config['path']) self.assertPublishedMany(publish_mock, metrics) ################################################################################ if __name__ == "__main__": unittest.main()
Fix missing require to correctly display local time
// This is a manifest file that'll be compiled into application.js, which will include all the files // listed below. // // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, // or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path. // // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // compiled file. // // Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details // about supported directives. // //= require jquery //= require jquery_ujs //= require turbolinks //= require foundation //= require ckeditor/init //= require d3 //= require js-routes //= require local_time //= require_tree . $(document).on('page:change', function(){ $(document).foundation({ offcanvas : { open_method: 'move' // Sets method in which offcanvas opens, can also be 'overlap' } }); });
// This is a manifest file that'll be compiled into application.js, which will include all the files // listed below. // // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, // or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path. // // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // compiled file. // // Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details // about supported directives. // //= require jquery //= require jquery_ujs //= require turbolinks //= require foundation //= require ckeditor/init //= require d3 //= require js-routes //= require_tree . $(document).on('page:change', function(){ $(document).foundation({ offcanvas : { open_method: 'move' // Sets method in which offcanvas opens, can also be 'overlap' } }); });
Correct typo in logging count of items
const logger = require('logger'); const weapon = require('weapon.js'); class ItemDatabase { constructor(itemType) { this.itemType = itemType; this.itemMap = new Map(); fateBus.subscribe(module, 'fate.'+this.itemType+'DataFetched', this.refresh.bind(this)); } refresh(message, newItemData) { this.itemMap.clear(); const dataLines = newItemData.split(/[\r\n]+/); for (let line of dataLines) { this.createItemFromData(line.split('\t')); } logger.log('itemDatabase.js ('+this.itemType+'): Found ('+(dataLines.length)+') items'); } createItemFromData(data) { // Overidden in subclasses } contains(itemName) { return this.itemMap.has(itemName); } get(itemName) { return this.itemMap.get(itemName); } } exports.ItemDatabase = ItemDatabase;
const logger = require('logger'); const weapon = require('weapon.js'); class ItemDatabase { constructor(itemType) { this.itemType = itemType; this.itemMap = new Map(); fateBus.subscribe(module, 'fate.'+this.itemType+'DataFetched', this.refresh.bind(this)); } refresh(message, newItemData) { this.itemMap.clear(); const dataLines = newItemData.split(/[\r\n]+/); for (let line of dataLines) { this.createItemFromData(line.split('\t')); } logger.log('itemDatabase.js ('+this.itemType+'): Found ('+(dataLines.length-1)+') items'); } createItemFromData(data) { // Overidden in subclasses } contains(itemName) { return this.itemMap.has(itemName); } get(itemName) { return this.itemMap.get(itemName); } } exports.ItemDatabase = ItemDatabase;
Use Assets key as Manifest Key Instead
var path = require('path'), fs = require('fs'); function AssetManifestPlugin(output) { this.output = output; } AssetManifestPlugin.prototype.apply = function(compiler) { var assets = {}, output = this.output; var outputPath = compiler.options.output.path, publicPath = compiler.options.output.publicPath; function publicRelative(url) { return path.join(publicPath, url.replace(outputPath, '')); } function keyForModule(module) { return Object.keys(module.assets)[0]; } compiler.plugin('compilation', function(compilation) { compilation.plugin('module-asset', function(module, file) { assets[keyForModule(module)] = publicRelative(file); }); }); compiler.plugin('done', function() { fs.writeFileSync(output, JSON.stringify(assets, null, 2)); }); }; module.exports = AssetManifestPlugin;
var path = require('path'), fs = require('fs'); function AssetManifestPlugin(output, keyRoot) { this.output = output; this.keyRoot = keyRoot; } AssetManifestPlugin.prototype.apply = function(compiler) { var assets = {}, output = this.output, keyRoot = this.keyRoot; var outputPath = compiler.options.output.path, publicPath = compiler.options.output.publicPath; function publicRelative(url) { return path.join(publicPath, url.replace(outputPath, '')); } function removeLeadSlash(path) { if(path[0] === '/') { return path.slice(1); } return path; } function formatKey(path) { var keyRootPath = path.replace(keyRoot, ''); return removeLeadSlash(keyRootPath); } compiler.plugin('compilation', function(compilation) { compilation.plugin('module-asset', function(module, file) { assets[formatKey(module.userRequest)] = publicRelative(file); }); }); compiler.plugin('done', function() { fs.writeFileSync(output, JSON.stringify(assets, null, 2)); }); }; module.exports = AssetManifestPlugin;
Trim filter string before splitting it into words
export function filterContainers() { // Fetch DOM elements, break each word in input filter. let filterValues = document.querySelector('#filter').value.trim().split(' '); let containers = document.querySelectorAll('.container'); // Iterate through each container. for (let i = 0; i < containers.length; i++) { // Get container title. let spanText = containers[i].querySelector('span').innerHTML; // Define hidden by default. let hide = true; // Iterate through each word, show if any are found. for (let j = 0; j < filterValues.length; j++) { if (spanText.indexOf(filterValues[j]) >= 0) { hide = false; break; } } // Display or hide container, based on filter. if (hide) { containers[i].classList.add('hide'); containers[i].classList.remove('show'); } else { containers[i].classList.remove('hide'); containers[i].classList.add('show'); } } }
export function filterContainers() { // Fetch DOM elements, break each word in input filter. let filterValues = document.querySelector('#filter').value.split(' '); let containers = document.querySelectorAll('.container'); // Iterate through each container. for (let i = 0; i < containers.length; i++) { // Get container title. let spanText = containers[i].querySelector('span').innerHTML; // Define hidden by default. let hide = true; // Iterate through each word, show if any are found. for (let j = 0; j < filterValues.length; j++) { if (spanText.indexOf(filterValues[j]) >= 0) { hide = false; break; } } // Display or hide container, based on filter. if (hide) { containers[i].classList.add('hide'); containers[i].classList.remove('show'); } else { containers[i].classList.remove('hide'); containers[i].classList.add('show'); } } }
Use empty struct as chan element type
package main import ( "fmt" "net" "os" "sync" "time" ) var ( host string // The host address to scan ) func init() { if len(os.Args) != 2 { fmt.Fprintf(os.Stderr, "Usage: %s host\n", os.Args[0]) os.Exit(1) } host = os.Args[1] } func main() { d := net.Dialer{Timeout: 10 * time.Second} p := make(chan struct{}, 500) // make 500 parallel connection wg := sync.WaitGroup{} c := func(port int) { conn, err := d.Dial(`tcp`, fmt.Sprintf(`%s:%d`, host, port)) if err == nil { conn.Close() fmt.Printf("%d passed\n", port) } <-p wg.Done() } wg.Add(65536) for i := 0; i < 65536; i++ { p <- struct{}{} go c(i) } wg.Wait() }
package main import ( "fmt" "net" "os" "sync" "time" ) var ( host string // The host address to scan ) func init() { if len(os.Args) != 2 { fmt.Fprintf(os.Stderr, "Usage: %s host\n", os.Args[0]) os.Exit(1) } host = os.Args[1] } func main() { d := net.Dialer{Timeout: 10 * time.Second} p := make(chan bool, 500) // make 500 parallel connection wg := sync.WaitGroup{} c := func(port int) { conn, err := d.Dial(`tcp`, fmt.Sprintf(`%s:%d`, host, port)) if err == nil { conn.Close() fmt.Printf("%d passed\n", port) } <-p wg.Done() } wg.Add(65536) for i := 0; i < 65536; i++ { p <- true go c(i) } wg.Wait() }
Remove sets from tests Since python 2.6 does not have literal set syntax
import unittest from robber import expect from robber.matchers.contain import Contain class TestAbove(unittest.TestCase): def test_matches(self): expect(Contain({'key': 'value'}, 'key').matches()) == True expect(Contain([1, 2, 3], 2).matches()) == True expect(Contain((1, 2, 3), 3).matches()) == True expect(Contain({'key': 'value'}, 'other').matches()) == False expect(Contain([1, 2, 3], 4).matches()) == False expect(Contain((1, 2, 3), 4).matches()) == False def test_failure_message(self): contain = Contain([1, 2, 3], 4) expect(contain.failure_message()) == 'Expected {} to contain 4'.format([1, 2, 3]) def test_register(self): expect(expect.matcher('contain')) == Contain
import unittest from robber import expect from robber.matchers.contain import Contain class TestAbove(unittest.TestCase): def test_matches(self): expect(Contain({'key': 'value'}, 'key').matches()) == True expect(Contain({1, 2, 3}, 1).matches()) == True expect(Contain([1, 2, 3], 2).matches()) == True expect(Contain((1, 2, 3), 3).matches()) == True expect(Contain({'key': 'value'}, 'other').matches()) == False expect(Contain({1, 2, 3}, 4).matches()) == False expect(Contain([1, 2, 3], 4).matches()) == False expect(Contain((1, 2, 3), 4).matches()) == False def test_failure_message(self): contain = Contain([1, 2, 3], 4) expect(contain.failure_message()) == 'Expected {} to contain 4'.format([1, 2, 3]) def test_register(self): expect(expect.matcher('contain')) == Contain
Embed compressed images instead of original ones
@extends('map.base') @section('title', '靜態地圖 - 攤位地圖') @section('main_content') <div class="mt-2"> <a href="https://i.imgur.com/0NsiJbU.jpg" target="_blank"> <img src="https://i.imgur.com/19fh3hk.jpg" class="img-fluid w-100" alt="static map"> </a> </div> <div class="mt-2"> <a href="https://i.imgur.com/bYkjBCT.jpg" target="_blank"> <img src="https://i.imgur.com/13jqLjz.jpg" class="img-fluid w-100" alt="static map"> </a> </div> <div class="mt-2"> <a href="https://i.imgur.com/YwOALyy.jpg" target="_blank"> <img src="https://i.imgur.com/OnhQzT1.jpg" class="img-fluid w-100" alt="static map"> </a> </div> @endsection
@extends('map.base') @section('title', '靜態地圖 - 攤位地圖') @section('main_content') <div class="mt-2"> <a href="https://i.imgur.com/0NsiJbU.jpg" target="_blank"> <img src="https://i.imgur.com/0NsiJbUh.jpg" class="img-fluid w-100" alt="static map"> </a> </div> <div class="mt-2"> <a href="https://i.imgur.com/bYkjBCT.jpg" target="_blank"> <img src="https://i.imgur.com/bYkjBCTh.jpg" class="img-fluid w-100" alt="static map"> </a> </div> <div class="mt-2"> <a href="https://i.imgur.com/YwOALyy.jpg" target="_blank"> <img src="https://i.imgur.com/YwOALyyh.jpg" class="img-fluid w-100" alt="static map"> </a> </div> @endsection
Fix event leaderboard total test
<?php namespace Konsulting\JustGivingApiSdk\Tests\ResourceClients; class LeaderboardTest extends ResourceClientTestCase { /** @test */ public function it_retrieves_the_charity_leaderboard_listing_for_a_charity_id() { $response = $this->client->leaderboard->getCharityLeaderboard(2050); $this->assertObjectHasAttributes(['charityId', 'currency', 'pages'], $response->body); } /** @test */ public function it_retrieves_the_event_leaderboard_listing_for_an_event_id() { $response = $this->client->leaderboard->getEventLeaderboard(479546); $this->assertEquals('GBP', $response->body->currency); $this->assertEquals([], $response->body->pages); $this->assertEquals(49006.22, $response->body->raisedAmount); } }
<?php namespace Konsulting\JustGivingApiSdk\Tests\ResourceClients; class LeaderboardTest extends ResourceClientTestCase { /** @test */ public function it_retrieves_the_charity_leaderboard_listing_for_a_charity_id() { $response = $this->client->leaderboard->getCharityLeaderboard(2050); $this->assertObjectHasAttributes(['charityId', 'currency', 'pages'], $response->body); } /** @test */ public function it_retrieves_the_event_leaderboard_listing_for_an_event_id() { $response = $this->client->leaderboard->getEventLeaderboard(479546); $this->assertEquals('GBP', $response->body->currency); $this->assertEquals([], $response->body->pages); $this->assertEquals(49006.2, $response->body->raisedAmount); } }
Remove install information because it's picked up by PyPI
#!/usr/bin/env python # -*- coding: utf-8 -*- """ gifshare - A command-line tool to upload images to S3. """ from setuptools import setup import os.path HERE = os.path.dirname(__file__) setup( name="gifshare", version="0.0.4", description="Store images in S3", long_description=__doc__, author='Mark Smith', author_email='mark.smith@practicalpoetry.co.uk', url='https://github.com/judy2k/gifshare', license='MIT License', entry_points={ 'console_scripts': [ 'gifshare = gifshare:main', ] }, packages=['gifshare'], classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Console', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', ], install_requires=open( os.path.join(HERE, 'requirements/_base.txt') ).readlines(), zip_safe=False, )
#!/usr/bin/env python # -*- coding: utf-8 -*- """ gifshare - A command-line tool to upload images to S3. Run with `python setup.py install` to install gifshare into your default Python environment. """ from setuptools import setup import os.path HERE = os.path.dirname(__file__) setup( name="gifshare", version="0.0.4", description="Store images in S3", long_description=__doc__, author='Mark Smith', author_email='mark.smith@practicalpoetry.co.uk', url='https://github.com/judy2k/gifshare', license='MIT License', entry_points={ 'console_scripts': [ 'gifshare = gifshare:main', ] }, packages=['gifshare'], classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Console', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', ], install_requires=open( os.path.join(HERE, 'requirements/_base.txt') ).readlines(), zip_safe=False, )
Remove style hardcoding (margin: '-5px') in Title component
import React from 'react' import PropTypes from 'prop-types' import EditableLabel from 'components/widgets/EditableLabel' import {Title, LaneHeader, RightContent } from 'styles/Base' import LaneMenu from './LaneHeader/LaneMenu' const LaneHeaderComponent = ({ updateTitle, canAddLanes, onDelete, onDoubleClick, inlineEditTitle, label, title, titleStyle, labelStyle, t }) => { return ( <LaneHeader onDoubleClick={onDoubleClick}> <Title style={titleStyle}> {inlineEditTitle ? <EditableLabel value={title} border placeholder={t('placeholder.title')} onSave={updateTitle} /> : title } </Title> {label && ( <RightContent> <span style={labelStyle}>{label}</span> </RightContent> )} {canAddLanes && <LaneMenu t={t} onDelete={onDelete}/>} </LaneHeader> ) } LaneHeaderComponent.propTypes = { updateTitle: PropTypes.func, inlineEditTitle: PropTypes.bool, canAddLanes: PropTypes.bool, label: PropTypes.string, title: PropTypes.string, onDelete: PropTypes.func, onDoubleClick: PropTypes.func, t: PropTypes.func.isRequired } LaneHeaderComponent.defaultProps = { updateTitle: () => {}, inlineEditTitle: false, canAddLanes: false } export default LaneHeaderComponent;
import React from 'react' import PropTypes from 'prop-types' import EditableLabel from 'components/widgets/EditableLabel' import {Title, LaneHeader, RightContent } from 'styles/Base' import LaneMenu from './LaneHeader/LaneMenu' const LaneHeaderComponent = ({ updateTitle, canAddLanes, onDelete, onDoubleClick, inlineEditTitle, label, title, titleStyle, labelStyle, t }) => { return ( <LaneHeader onDoubleClick={onDoubleClick}> <Title style={{...titleStyle, margin: '-5px'}}> {inlineEditTitle ? <EditableLabel value={title} border placeholder={t('placeholder.title')} onSave={updateTitle} /> : title } </Title> {label && ( <RightContent> <span style={labelStyle}>{label}</span> </RightContent> )} {canAddLanes && <LaneMenu t={t} onDelete={onDelete}/>} </LaneHeader> ) } LaneHeaderComponent.propTypes = { updateTitle: PropTypes.func, inlineEditTitle: PropTypes.bool, canAddLanes: PropTypes.bool, label: PropTypes.string, title: PropTypes.string, onDelete: PropTypes.func, onDoubleClick: PropTypes.func, t: PropTypes.func.isRequired } LaneHeaderComponent.defaultProps = { updateTitle: () => {}, inlineEditTitle: false, canAddLanes: false } export default LaneHeaderComponent;
Save test results to XML added
import unittest import requests import lxml.html import xmlrunner class TestHtmlTask(unittest.TestCase): def setUp(self): self.urls = open("urls.txt", 'r') self.url_google = self.urls.readline() self.url_habr = self.urls.readline() self.urls.close() def test_1(self): expected_response_1 = 200 r = requests.get(self.url_google.strip()) self.assertEqual(r.status_code, expected_response_1, msg='{0}, {1}') def test_2(self): expected_response_2 = "Game Development" t = lxml.html.parse(self.url_habr) title = t.find(".//title").text.split('/') self.assertEqual(title[0].rstrip(), expected_response_2) if __name__ == '__main__': unittest.main(testRunner=xmlrunner.XMLTestRunner(output='test-reports'))
import unittest import requests import lxml.html class TestHtmlTask(unittest.TestCase): def setUp(self): self.ulr_google = "https://www.google.com.ua/" self.url_habr = "http://habrahabr.ru/hub/gdev/" def test_1(self): expected_response_1 = 200 r = requests.get(self.ulr_google) self.assertEqual(r.status_code, expected_response_1) def test_2(self): expected_response_2 = "Game Development" t = lxml.html.parse(self.url_habr) title = t.find(".//title").text.split('/') self.assertEqual(title[0].rstrip(), expected_response_2) if __name__ == '__main__': unittest.main()
Fix for weird signal we send ourselves
from django.core.exceptions import ValidationError from django.dispatch import receiver from django.forms.models import model_to_dict from django_fsm import pre_transition, post_transition @receiver(pre_transition) def validate_transition_form(sender, instance, name=None, method_kwargs=None, **kwargs): if not method_kwargs: return transition = method_kwargs['transition'] if transition.form: form = transition.form(data=model_to_dict(instance)) if form.errors: raise ValidationError( dict( (form.fields[field].label, errors) for field, errors in form.errors.items() ) ) @receiver(post_transition) def transition_messages(sender, instance, name=None, method_kwargs=None, **kwargs): if not method_kwargs: return # Only try to send messages if 'send_messages' is not False. transition = method_kwargs['transition'] if method_kwargs.get('send_messages'): for message in getattr(transition, 'messages', []): message(instance).compose_and_send()
from django.core.exceptions import ValidationError from django.dispatch import receiver from django.forms.models import model_to_dict from django_fsm import pre_transition, post_transition @receiver(pre_transition) def validate_transition_form(sender, instance, name, method_kwargs, **kwargs): transition = method_kwargs['transition'] if transition.form: form = transition.form(data=model_to_dict(instance)) if form.errors: raise ValidationError( dict( (form.fields[field].label, errors) for field, errors in form.errors.items() ) ) @receiver(post_transition) def transition_messages(sender, instance, name, method_kwargs, **kwargs): # Only try to send messages if 'send_messages' is not False. transition = method_kwargs['transition'] if method_kwargs.get('send_messages'): for message in getattr(transition, 'messages', []): message(instance).compose_and_send()
Add MiniMock to the list of unittest dependencies.
#!/usr/bin/env python # -*- coding: utf-8 -*- import os from setuptools import setup, find_packages setup( name = 'cloudsizzle', fullname = 'CloudSizzle', version = '0.1', author = '', author_email = '', license = 'MIT', url = 'http://cloudsizzle.cs.hut.fi', description = 'Social study plan9er for Aalto University students', install_requires = [ 'Django >= 1.1', 'Scrapy == 0.8', 'kpwrapper >= 1.0.0', 'asi >= 0.9', ], packages = find_packages(), include_package_data = True, test_suite = 'cloudsizzle.tests.suite', tests_require = [ 'MiniMock >= 1.2', ], dependency_links = [ 'http://public.futurice.com/~ekan/eggs', 'http://ftp.edgewall.com/pub/bitten/', ], extras_require = { 'Bitten': ['bitten'], }, entry_points = { 'distutils.commands': [ 'unittest = bitten.util.testrunner:unittest [Bitten]' ], }, )
#!/usr/bin/env python # -*- coding: utf-8 -*- import os from setuptools import setup, find_packages setup( name = 'cloudsizzle', fullname = 'CloudSizzle', version = '0.1', author = '', author_email = '', license = 'MIT', url = 'http://cloudsizzle.cs.hut.fi', description = 'Social study plan9er for Aalto University students', install_requires = [ 'Django >= 1.1', 'Scrapy == 0.8', 'kpwrapper >= 1.0.0', 'asi >= 0.9', ], packages = find_packages(), include_package_data = True, test_suite = 'cloudsizzle.tests.suite', dependency_links = [ 'http://public.futurice.com/~ekan/eggs', 'http://ftp.edgewall.com/pub/bitten/', ], extras_require = { 'Bitten': ['bitten'], }, entry_points = { 'distutils.commands': [ 'unittest = bitten.util.testrunner:unittest [Bitten]' ], }, )
Move init DB in try block
package nuclibook.server; import com.j256.ormlite.jdbc.JdbcConnectionSource; import com.j256.ormlite.support.ConnectionSource; import com.j256.ormlite.table.TableUtils; import nuclibook.constants.C; import nuclibook.models.Radiographer; import nuclibook.models.RadiographerAvailability; import nuclibook.models.User; import java.sql.SQLException; public class SqlServerConnection { /* singleton pattern */ private SqlServerConnection() { } private static ConnectionSource connection = null; public static ConnectionSource acquireConnection() { if (connection == null) { try { connection = new JdbcConnectionSource(C.MYSQL_URI); ((JdbcConnectionSource) connection).setUsername(C.MYSQL_USERNAME); ((JdbcConnectionSource) connection).setPassword(C.MYSQL_PASSWORD); initDB(connection); } catch (Exception e) { e.printStackTrace(); // TODO deal with exception } } return connection; } public static void initDB(ConnectionSource connection) { try { TableUtils.createTableIfNotExists(connection, User.class); TableUtils.createTableIfNotExists(connection, Radiographer.class); TableUtils.createTableIfNotExists(connection, RadiographerAvailability.class); } catch (SQLException e) { e.printStackTrace(); // TODO deal with exception } } }
package nuclibook.server; import com.j256.ormlite.jdbc.JdbcConnectionSource; import com.j256.ormlite.support.ConnectionSource; import com.j256.ormlite.table.TableUtils; import nuclibook.constants.C; import nuclibook.models.Radiographer; import nuclibook.models.RadiographerAvailability; import nuclibook.models.User; import java.sql.SQLException; public class SqlServerConnection { /* singleton pattern */ private SqlServerConnection() { } private static ConnectionSource connection = null; public static ConnectionSource acquireConnection() { if (connection == null) { try { connection = new JdbcConnectionSource(C.MYSQL_URI); ((JdbcConnectionSource) connection).setUsername(C.MYSQL_USERNAME); ((JdbcConnectionSource) connection).setPassword(C.MYSQL_PASSWORD); } catch (Exception e) { e.printStackTrace(); // TODO deal with exception } initDB(connection); } return connection; } public static void initDB(ConnectionSource connection) { try { TableUtils.createTableIfNotExists(connection, User.class); TableUtils.createTableIfNotExists(connection, Radiographer.class); TableUtils.createTableIfNotExists(connection, RadiographerAvailability.class); } catch (SQLException e) { e.printStackTrace(); // TODO deal with exception } } }
[TASK] Make sure all stylesheets get parsed with autoprefixer while running the default grunt task
module.exports = function(grunt) { "use strict"; // Display the execution time of grunt tasks require("time-grunt")(grunt); // Load all grunt-tasks in 'Build/Grunt-Options'. var gruntOptionsObj = require("load-grunt-configs")(grunt, { "config" : { src: "Build/Grunt-Options/*.js" } }); grunt.initConfig(gruntOptionsObj); // Load all grunt-plugins that are specified in the 'package.json' file. require('jit-grunt')(grunt, { replace: 'grunt-text-replace', cssmetrics: 'grunt-css-metrics', bower: 'grunt-bower-task' }); /** * Default grunt task. * Compiles all .scss/.sass files with ':dev' options and * validates all js-files inside Resources/Private/Javascripts with JSHint. */ grunt.registerTask("default", ["css", "jshint"]); /** * Travis CI task * Test all specified grunt tasks. */ grunt.registerTask("travis", ["init", "replace:init", "jshint", "deploy", "undeploy"]); /** * Load custom tasks * Load all Grunt-Tasks inside the 'Build/Grunt-Tasks' dir. */ grunt.loadTasks("Build/Grunt-Tasks"); };
module.exports = function(grunt) { "use strict"; // Display the execution time of grunt tasks require("time-grunt")(grunt); // Load all grunt-tasks in 'Build/Grunt-Options'. var gruntOptionsObj = require("load-grunt-configs")(grunt, { "config" : { src: "Build/Grunt-Options/*.js" } }); grunt.initConfig(gruntOptionsObj); // Load all grunt-plugins that are specified in the 'package.json' file. require('jit-grunt')(grunt, { replace: 'grunt-text-replace', cssmetrics: 'grunt-css-metrics', bower: 'grunt-bower-task' }); /** * Default grunt task. * Compiles all .scss/.sass files with ':dev' options and * validates all js-files inside Resources/Private/Javascripts with JSHint. */ grunt.registerTask("default", ["sass:dev", "jshint"]); /** * Travis CI task * Test all specified grunt tasks. */ grunt.registerTask("travis", ["init", "replace:init", "jshint", "deploy", "undeploy"]); /** * Load custom tasks * Load all Grunt-Tasks inside the 'Build/Grunt-Tasks' dir. */ grunt.loadTasks("Build/Grunt-Tasks"); };
Update to ready the blog plugin for new layout changes.
<?php /** @var rtSitePage $rt_site_page */ use_helper('I18N', 'Date', 'rtText') ?> <div class="rt-section rt-site-page"> <!--RTAS <div class="rt-section-tools-header rt-admin-tools"> <?php echo link_to(__('Edit Page'), 'rtSitePageAdmin/edit?id='.$rt_site_page->getId(), array('class' => 'rt-admin-edit-tools-trigger')) ?> </div> RTAS--> <?php if(sfConfig::get('app_rt_templates_headers_embedded', true)): ?> <div class="rt-section-header"> <h1><?php echo $rt_site_page->getTitle() ?></h1> </div> <?php endif; ?> <div class="rt-section-content"> <?php echo markdown_to_html($rt_site_page->getContent(), $rt_site_page); ?> </div> </div>
<?php /** @var rtSitePage $rt_site_page */ use_helper('I18N', 'Date', 'rtText') ?> <div class="rt-section rt-site-page"> <div class="rt-section-tools-header rt-admin-tools"> <?php echo link_to(__('Edit Page'), 'rtSitePageAdmin/edit?id='.$rt_site_page->getId(), array('class' => 'rt-admin-edit-tools-trigger')) ?> </div> <?php if(sfConfig::get('app_rt_templates_headers_embedded', true)): ?> <div class="rt-section-header"> <h1><?php echo $rt_site_page->getTitle() ?></h1> </div> <?php endif; ?> <div class="rt-section-content"> <?php echo markdown_to_html($rt_site_page->getContent(), $rt_site_page); ?> </div> </div>
Include name of `rule` that caused error in text formatter
import columnify from 'columnify'; import figures from 'figures'; import chalk from 'chalk'; export default function TextFormatter(errorsGroupedByFile) { const files = Object.keys(errorsGroupedByFile); const errorsText = files .map(file => { return generateErrorsForFile(file, errorsGroupedByFile[file]); }) .join('\n\n'); const summary = generateSummary(errorsGroupedByFile); return errorsText + '\n\n' + summary + '\n'; } function generateErrorsForFile(file, errors) { const formattedErrors = errors.map(error => { const location = error.locations[0]; return { location: chalk.dim(`${location.line}:${location.column * 4}`), message: error.message, rule: chalk.dim(` ${error.ruleName}`), }; }); const errorsText = columnify(formattedErrors, { showHeaders: false, }); return chalk.underline(file) + '\n' + errorsText; } function generateSummary(errorsGroupedByFile) { const files = Object.keys(errorsGroupedByFile); const errorsCount = files.reduce((sum, file) => { return sum + errorsGroupedByFile[file].length; }, 0); if (errorsCount == 0) { return chalk.green(`${figures.tick} 0 errors detected\n`); } const summary = chalk.red( `${figures.cross} ${errorsCount} error` + (errorsCount > 1 ? 's' : '') + ' detected' ); return summary; }
import columnify from 'columnify'; import figures from 'figures'; import chalk from 'chalk'; export default function TextFormatter(errorsGroupedByFile) { const files = Object.keys(errorsGroupedByFile); const errorsText = files .map(file => { return generateErrorsForFile(file, errorsGroupedByFile[file]); }) .join('\n\n'); const summary = generateSummary(errorsGroupedByFile); return errorsText + '\n\n' + summary + '\n'; } function generateErrorsForFile(file, errors) { const formattedErrors = errors.map(error => { const location = error.locations[0]; return { location: chalk.dim(`${location.line}:${location.column * 4}`), message: error.message, // TODO: Add rule name }; }); const errorsText = columnify(formattedErrors, { showHeaders: false, }); return chalk.underline(file) + '\n' + errorsText; } function generateSummary(errorsGroupedByFile) { const files = Object.keys(errorsGroupedByFile); const errorsCount = files.reduce((sum, file) => { return sum + errorsGroupedByFile[file].length; }, 0); if (errorsCount == 0) { return chalk.green(`${figures.tick} 0 errors detected\n`); } const summary = chalk.red( `${figures.cross} ${errorsCount} error` + (errorsCount > 1 ? 's' : '') + ' detected' ); return summary; }
Change experiment to 50/50 split Summary: Moving up to 50/50 since I believe the experiment is lower risk than it was when these values were initially set. Reviewed By: ttsugriy fbshipit-source-id: 69768de
/* * Copyright 2018-present Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.facebook.buck.config; import com.facebook.buck.util.randomizedtrial.WithProbability; /** * Incremental action graph mode with A/B experiment support. * * <p>Note that only a stable experiment makes sense here, as incrementality requires at least two * runs in a row with the feature enabled to show any effect. */ public enum IncrementalActionGraphMode implements WithProbability { ENABLED(0.5), DISABLED(0.5), EXPERIMENT(0.0), ; public static final IncrementalActionGraphMode DEFAULT = DISABLED; private final double probability; IncrementalActionGraphMode(double probability) { this.probability = probability; } @Override public double getProbability() { return probability; } }
/* * Copyright 2018-present Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.facebook.buck.config; import com.facebook.buck.util.randomizedtrial.WithProbability; /** * Incremental action graph mode with A/B experiment support. * * <p>Note that only a stable experiment makes sense here, as incrementality requires at least two * runs in a row with the feature enabled to show any effect. */ public enum IncrementalActionGraphMode implements WithProbability { ENABLED(0.1), DISABLED(0.9), EXPERIMENT(0.0), ; public static final IncrementalActionGraphMode DEFAULT = DISABLED; private final double probability; IncrementalActionGraphMode(double probability) { this.probability = probability; } @Override public double getProbability() { return probability; } }
acronym: Remove test with mixed-case word see: https://github.com/exercism/x-common/pull/788
import unittest from acronym import abbreviate # test cases adapted from `x-common//canonical-data.json` @ version: 1.1.0 class AcronymTest(unittest.TestCase): def test_basic(self): self.assertEqual(abbreviate('Portable Network Graphics'), 'PNG') def test_lowercase_words(self): self.assertEqual(abbreviate('Ruby on Rails'), 'ROR') def test_punctuation(self): self.assertEqual(abbreviate('First In, First Out'), 'FIFO') def test_all_caps_words(self): self.assertEqual(abbreviate('PHP: Hypertext Preprocessor'), 'PHP') def test_non_acronym_all_caps_word(self): self.assertEqual(abbreviate('GNU Image Manipulation Program'), 'GIMP') def test_hyphenated(self): self.assertEqual( abbreviate('Complementary metal-oxide semiconductor'), 'CMOS') if __name__ == '__main__': unittest.main()
import unittest from acronym import abbreviate # test cases adapted from `x-common//canonical-data.json` @ version: 1.0.0 class AcronymTest(unittest.TestCase): def test_basic(self): self.assertEqual(abbreviate('Portable Network Graphics'), 'PNG') def test_lowercase_words(self): self.assertEqual(abbreviate('Ruby on Rails'), 'ROR') def test_camelcase(self): self.assertEqual(abbreviate('HyperText Markup Language'), 'HTML') def test_punctuation(self): self.assertEqual(abbreviate('First In, First Out'), 'FIFO') def test_all_caps_words(self): self.assertEqual(abbreviate('PHP: Hypertext Preprocessor'), 'PHP') def test_non_acronym_all_caps_word(self): self.assertEqual(abbreviate('GNU Image Manipulation Program'), 'GIMP') def test_hyphenated(self): self.assertEqual( abbreviate('Complementary metal-oxide semiconductor'), 'CMOS') if __name__ == '__main__': unittest.main()
Reset input value so that when you return previous url is cleared
const { h, Component } = require('preact') class UrlUI extends Component { constructor (props) { super(props) this.handleClick = this.handleClick.bind(this) } componentDidMount () { // My guess about why browser scrolls to top on focus: // Component is mounted right away, but the tab panel might be animating // still, so input element is positioned outside viewport. This fixes it. setTimeout(() => { this.input.focus({ preventScroll: true }) }, 150) } handleClick () { this.props.addFile(this.input.value) } render () { return <div class="uppy-Url"> <input class="uppy-c-textInput uppy-Url-input" type="text" placeholder={this.props.i18n('enterUrlToImport')} value="" ref={(input) => { this.input = input }} /> <button class="uppy-u-reset uppy-c-btn uppy-c-btn-primary uppy-Url-importButton" type="button" aria-label={this.props.i18n('addUrl')} onclick={this.handleClick}> {this.props.i18n('import')} </button> </div> } } module.exports = UrlUI
const { h, Component } = require('preact') class UrlUI extends Component { constructor (props) { super(props) this.handleClick = this.handleClick.bind(this) } componentDidMount () { // My guess about why browser scrolls to top on focus: // Component is mounted right away, but the tab panel might be animating // still, so input element is positioned outside viewport. This fixes it. setTimeout(() => { this.input.focus({ preventScroll: true }) }, 150) } handleClick () { this.props.addFile(this.input.value) } render () { return <div class="uppy-Url"> <input class="uppy-c-textInput uppy-Url-input" type="text" placeholder={this.props.i18n('enterUrlToImport')} ref={(input) => { this.input = input }} /> <button class="uppy-Url-importButton" type="button" aria-label={this.props.i18n('addUrl')} onclick={this.handleClick}> {this.props.i18n('import')} </button> </div> } } module.exports = UrlUI
Fix a problem with a migration between master and stable branch
# -*- coding: utf-8 -*- # Generated by Django 1.9.2 on 2016-05-30 10:04 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('projects', '0040_remove_memberships_of_cancelled_users_acounts'), ] operations = [ migrations.AlterField( model_name='project', name='owner', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='owned_projects', to=settings.AUTH_USER_MODEL, verbose_name='owner'), ), ]
# -*- coding: utf-8 -*- # Generated by Django 1.9.2 on 2016-05-30 10:04 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('projects', '0042_auto_20160525_0911'), ] operations = [ migrations.AlterField( model_name='project', name='owner', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='owned_projects', to=settings.AUTH_USER_MODEL, verbose_name='owner'), ), ]
Fix logout view so django stops complaining
"""voteswap URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.9/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf.urls import include from django.conf.urls import url from django.contrib import admin from django.contrib.auth.views import logout from voteswap.views import index from voteswap.views import landing_page from voteswap.views import signup urlpatterns = [ url(r'^admin/', admin.site.urls), url('', include('social.apps.django_app.urls', namespace='social')), url('^home/$', index, name='index'), url('^$', landing_page, name='landing_page'), url('^logout/$', logout, name='logout'), url('^user/', include('users.urls', namespace='users')), url('^signup/$', signup, name='signup'), ]
"""voteswap URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.9/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf.urls import include from django.conf.urls import url from django.contrib import admin from voteswap.views import index from voteswap.views import landing_page from voteswap.views import signup urlpatterns = [ url(r'^admin/', admin.site.urls), url('', include('social.apps.django_app.urls', namespace='social')), url('^home/$', index, name='index'), url('^$', landing_page, name='landing_page'), url('^logout/$', 'django.contrib.auth.views.logout', name='logout'), url('^user/', include('users.urls', namespace='users')), url('^signup/$', signup, name='signup'), ]
Use full import path for parent class Something seems off with the build for some reason. I'm trying to fix it this way.
# Copyright (c) 2017 Ultimaker B.V. # Uranium is released under the terms of the AGPLv3 or higher. import UM.Settings.Models.SettingVisibilityHandler class MaterialSettingsVisibilityHandler(UM.Settings.Models.SettingVisibilityHandler.SettingVisibilityHandler): def __init__(self, parent = None, *args, **kwargs): super().__init__(parent = parent, *args, **kwargs) material_settings = { "default_material_print_temperature", "material_bed_temperature", "material_standby_temperature", "cool_fan_speed", "retraction_amount", "retraction_speed", } self.setVisible(material_settings)
# Copyright (c) 2017 Ultimaker B.V. # Uranium is released under the terms of the AGPLv3 or higher. from UM.Settings.Models.SettingVisibilityHandler import SettingVisibilityHandler class MaterialSettingsVisibilityHandler(SettingVisibilityHandler): def __init__(self, parent = None, *args, **kwargs): super().__init__(parent = parent, *args, **kwargs) material_settings = { "default_material_print_temperature", "material_bed_temperature", "material_standby_temperature", "cool_fan_speed", "retraction_amount", "retraction_speed", } self.setVisible(material_settings)
Add more HTTP cache headers
<?php namespace Politix\PolitikportalBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; class MainController extends Controller { public function getHomepageAction() { $TopicModel = $this->get('TopicModel'); $topics = $TopicModel->getHomepageTopics(); $out['rows'][] = 'empty'; foreach ($topics as $topic) { $out['topics'][] = $TopicModel->getTopic($topic); } $response = $this->render('PolitikportalBundle:Default:topics.html.twig', $out); $response->setPublic(); $response->setMaxAge(60); $response->setSharedMaxAge(60); $lastModified = new \DateTime('yesterday'); $response->setLastModified($lastModified); $response->isNotModified($this->getRequest()); return $response; } }
<?php namespace Politix\PolitikportalBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; class MainController extends Controller { public function getHomepageAction() { $TopicModel = $this->get('TopicModel'); $topics = $TopicModel->getHomepageTopics(); $out['rows'][] = 'empty'; foreach ($topics as $topic) { $out['topics'][] = $TopicModel->getTopic($topic); } $response = $this->render('PolitikportalBundle:Default:topics.html.twig', $out); $lastModified = new \DateTime('yesterday'); $response->setLastModified($lastModified); $response->isNotModified($this->getRequest()); return $response; } }
Add archaic WebSocket error handling
new Vue({ el: '#app', // Using ES6 string litteral delimiters because // Go uses {{ . }} for its templates delimiters: ['${', '}'], data: { ws: null, message: '', chat: [], }, created: function() { let protocol = (window.location.protocol === 'https:') ? 'wss:' : 'ws:' this.ws = new WebSocket(`${protocol}//${window.location.host}/ws`) this.ws.addEventListener('message', (e) => { let { user, avatar, content } = JSON.parse(e.data) this.chat.push({ user, avatar, content }) }) this.ws.addEventListener('close', (e) => { this.ws = null }) this.ws.addEventListener('error', (e) => { this.ws = null }) }, methods: { send: function() { if (!this.message) { return } this.ws && this.ws.send( JSON.stringify({ content: this.message, }) ) this.message = '' }, } })
new Vue({ el: '#app', // Using ES6 string litteral delimiters because // Go uses {{ . }} for its templates delimiters: ['${', '}'], data: { ws: null, message: '', chat: [], }, created: function() { let protocol = (window.location.protocol === 'https:') ? 'wss:' : 'ws:' this.ws = new WebSocket(`${protocol}//${window.location.host}/ws`) this.ws.addEventListener('message', (e) => { let { user, avatar, content } = JSON.parse(e.data) this.chat.push({ user, avatar, content }) }) }, methods: { send: function() { if (!this.message) { return } this.ws.send( JSON.stringify({ content: this.message, }) ) this.message = '' }, } })
Remove line label for tax disc volumes
define([ 'require', 'vehicle-excise-duty/collections/services', 'vehicle-excise-duty/collections/channels', 'vehicle-excise-duty/views/timeseries-graph', 'extensions/views/timeseries-graph/timeseries-graph', './failures-module', 'common/controllers/availability-module' ], function (require, ServicesCollection, ChannelsCollection, ServicesTimeseriesGraph, TimeseriesGraph, failuresModule, availabilityModule) { return function () { var servicesCollection = new ServicesCollection([], {}); servicesCollection.fetch(); new ServicesTimeseriesGraph({ el: $('#vehicle-excise-duty-services'), collection: servicesCollection }); var taxDiscCollection = new ServicesCollection([], { seriesList: [{ id: 'successful_tax_disc', title: 'Tax-disc' }] }); taxDiscCollection.fetch(); new TimeseriesGraph({ el: $('#tax-disc-volumes'), collection: taxDiscCollection }); var channelsCollection = new ChannelsCollection([], {}); channelsCollection.fetch(); new ServicesTimeseriesGraph({ el: $('#vehicle-excise-duty-channels'), collection: channelsCollection }); failuresModule('#tax-disc-failures', 'tax-disc'); failuresModule('#sorn-failures', 'sorn'); availabilityModule('tax-disc', '#tax-disc-availability'); availabilityModule('register-sorn-statutory-off-road-notification', '#sorn-availability'); }; });
define([ 'require', 'vehicle-excise-duty/collections/services', 'vehicle-excise-duty/collections/channels', 'vehicle-excise-duty/views/timeseries-graph', './failures-module', 'common/controllers/availability-module' ], function (require, ServicesCollection, ChannelsCollection, TimeseriesGraph, failuresModule, availabilityModule) { return function () { var servicesCollection = new ServicesCollection([], {}); servicesCollection.fetch(); new TimeseriesGraph({ el: $('#vehicle-excise-duty-services'), collection: servicesCollection }); var taxDiscCollection = new ServicesCollection([], { seriesList: [{ id: 'successful_tax_disc', title: 'Tax-disc' }] }); taxDiscCollection.fetch(); new TimeseriesGraph({ el: $('#tax-disc-volumes'), collection: taxDiscCollection }); var channelsCollection = new ChannelsCollection([], {}); channelsCollection.fetch(); new TimeseriesGraph({ el: $('#vehicle-excise-duty-channels'), collection: channelsCollection }); failuresModule('#tax-disc-failures', 'tax-disc'); failuresModule('#sorn-failures', 'sorn'); availabilityModule('tax-disc', '#tax-disc-availability'); availabilityModule('register-sorn-statutory-off-road-notification', '#sorn-availability'); }; });
Fix usage of start, end properties now prohibited :wrench:
const createFixer = ({range, left, right, operator}, source) => fixer => { const [leftStart, leftEnd] = left.range; const [rightStart] = right.range; const operatorRange = [leftEnd, rightStart]; const operatorText = source.slice(...operatorRange); if (operator === '||') { const leftText = source.slice(leftStart, leftEnd); return [ fixer.replaceTextRange(operatorRange, operatorText.replace(operator, `? ${leftText} :`)) ]; } return [ fixer.replaceTextRange(operatorRange, operatorText.replace(operator, '?')), fixer.insertTextAfterRange(range, ' : null') ]; }; const create = context => ({ LogicalExpression: node => { if (node.right.type === 'JSXElement') { context.report({ node, message: 'JSX should not use logical expression', fix: createFixer(node, context.getSourceCode().getText()) }); } } }); module.exports = { create, createFixer, meta: { docs: { description: 'Prevent falsy values to be printed' }, fixable: 'code' } };
const createFixer = ({range, left, right, operator}, source) => fixer => { const {start: leftStart, end: leftEnd} = left; const {start: rightStart} = right; const operatorRange = [leftEnd, rightStart]; const operatorText = source.slice(...operatorRange); if (operator === '||') { const leftText = source.slice(leftStart, leftEnd); return [ fixer.replaceTextRange(operatorRange, operatorText.replace(operator, `? ${leftText} :`)) ]; } return [ fixer.replaceTextRange(operatorRange, operatorText.replace(operator, '?')), fixer.insertTextAfterRange(range, ' : null') ]; }; const create = context => ({ LogicalExpression: node => { if (node.right.type === 'JSXElement') { context.report({ node, message: 'JSX should not use logical expression', fix: createFixer(node, context.getSourceCode().getText()) }); } } }); module.exports = { create, createFixer, meta: { docs: { description: 'Prevent falsy values to be printed' }, fixable: 'code' } };
Mark log files mode 666 when creating them
<?php class Octopus_Logger_File { function __construct($file) { $this->file = $file; $this->_handle = null; } function _open() { if (!$this->_handle = @fopen($this->file, 'a')) { print "Can't open log file: $this->file."; exit(); } @chmod($this->file, 0666); } function log($line) { if (!$this->_handle) { $this->_open(); } if ($this->_handle) { $line = date('r') . ': ' . $line; @fwrite($this->_handle, $line . "\n"); } } }
<?php class Octopus_Logger_File { function __construct($file) { $this->file = $file; $this->_handle = null; } function _open() { if (!$this->_handle = @fopen($this->file, 'a')) { print "Can't open log file: $this->file."; } } function log($line) { if (!$this->_handle) { $this->_open(); } if ($this->_handle) { $line = date('r') . ': ' . $line; @fwrite($this->_handle, $line . "\n"); } } } ?>
Fix download_url, ver bump to coordinate
from setuptools import setup setup( name='kibana', packages=['kibana'], version='0.7', description='Kibana configuration index (.kibana) command line interface and python API (visualization import/export and mappings refresh)', author='Ryan Farley', author_email='rfarley@mitre.org', url='https://github.com/rfarley3/Kibana', download_url='https://github.com/rfarley3/Kibana/tarball/0.7', keywords=['kibana', 'config', 'import', 'export', 'mappings'], classifiers=[], install_requires=( 'elasticsearch', 'argparse', 'requests', ), entry_points={ 'console_scripts': [ 'dotkibana = kibana.__main__:main', ] }, )
from setuptools import setup setup( name='kibana', packages=['kibana'], version='0.6', description='Kibana configuration index (.kibana) command line interface and python API (visualization import/export and mappings refresh)', author='Ryan Farley', author_email='rfarley@mitre.org', url='https://github.com/rfarley3/Kibana', download_url='https://github.com/rfarley3/Kibana/tarball/0.4', keywords=['kibana', 'config', 'import', 'export', 'mappings'], classifiers=[], install_requires=( 'elasticsearch', 'argparse', 'requests', ), entry_points={ 'console_scripts': [ 'dotkibana = kibana.__main__:main', ] }, )
Fix route definitions of cloud_federation_api Signed-off-by: Joas Schilling <ab43a7c9cb5b2380afc4ddf8b3e2583169b39a02@schilljs.com>
<?php declare(strict_types=1); /** * @copyright Copyright (c) 2020 Joas Schilling <coding@schilljs.com> * * @license GNU AGPL version 3 or any later version * * 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/>. * */ return [ 'routes' => [ [ 'name' => 'RequestHandler#addShare', 'url' => '/ocm/shares', 'verb' => 'POST', 'root' => '', ], [ 'name' => 'RequestHandler#receiveNotification', 'url' => '/ocm/notifications', 'verb' => 'POST', 'root' => '', ], ], ];
<?php declare(strict_types=1); /** * @copyright Copyright (c) 2020 Joas Schilling <coding@schilljs.com> * * @license GNU AGPL version 3 or any later version * * 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/>. * */ return [ [ 'name' => 'RequestHandler#addShare', 'url' => '/ocm/shares', 'verb' => 'POST', 'root' => '', ], [ 'name' => 'RequestHandler#receiveNotification', 'url' => '/ocm/notifications', 'verb' => 'POST', 'root' => '', ], ];
[FIX] Revert r49045 which caused rogue ~np~ tags to appear in searchindex results. Still looking for a better fix for the original {list} plugin double-parsing issues... (thanks Nelson) git-svn-id: fe65cb8b726aa1bab0c239f321eb4f822d15ce08@49435 b456876b-0849-0410-b77d-98878d47e9d5
<?php // (c) Copyright 2002-2013 by authors of the Tiki Wiki CMS Groupware Project // // All Rights Reserved. See copyright.txt for details and a complete list of authors. // Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details. // $Id$ class Search_Formatter_ValueFormatter_Snippet extends Search_Formatter_ValueFormatter_Abstract { private $length = 240; private $suffix = '...'; function __construct($arguments) { if (isset($arguments['length'])) { $this->length = (int) $arguments['length']; } if (isset($arguments['suffix'])) { $this->suffix = $arguments['suffix']; } } function render($name, $value, array $entry) { $snippet = TikiLib::lib('tiki')->get_snippet($value, 'n', '', $this->length + 1); if (function_exists('mb_strlen')) { if (mb_strlen($snippet) > $this->length) { $snippet = mb_substr($snippet, 0, -1) . $this->suffix; } } else { if (strlen($snippet) > $this->length) { $snippet = substr($snippet, 0, -1) . $this->suffix; } } return $snippet; } }
<?php // (c) Copyright 2002-2013 by authors of the Tiki Wiki CMS Groupware Project // // All Rights Reserved. See copyright.txt for details and a complete list of authors. // Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details. // $Id$ class Search_Formatter_ValueFormatter_Snippet extends Search_Formatter_ValueFormatter_Abstract { private $length = 240; private $suffix = '...'; function __construct($arguments) { if (isset($arguments['length'])) { $this->length = (int) $arguments['length']; } if (isset($arguments['suffix'])) { $this->suffix = $arguments['suffix']; } } function render($name, $value, array $entry) { $snippet = TikiLib::lib('tiki')->get_snippet($value, 'n', '', $this->length + 1); if (function_exists('mb_strlen')) { if (mb_strlen($snippet) > $this->length) { $snippet = mb_substr($snippet, 0, -1) . $this->suffix; } } else { if (strlen($snippet) > $this->length) { $snippet = substr($snippet, 0, -1) . $this->suffix; } } return '~np~' . $snippet . '~/np~'; } }
Update SoftwarePackageTestCase to use ObjectFactoryMixIn
""" Unit tests of the Dashboard application """ from django.test import TestCase from django.db import IntegrityError from launch_control.utils.call_helper import ObjectFactoryMixIn from launch_control.dashboard_app.models import ( SoftwarePackage, ) class SoftwarePackageTestCase(TestCase, ObjectFactoryMixIn): class Dummy: class SoftwarePackage: name = 'libfoo' version = '1.2.0' def test_creation_1(self): dummy, sw_package = self.make_and_get_dummy(SoftwarePackage) self.assertEqual(sw_package.name, dummy.name) self.assertEqual(sw_package.version, dummy.version) def test_uniqueness(self): pkg1 = self.make(SoftwarePackage) pkg1.save() pkg2 = self.make(SoftwarePackage) self.assertRaises(IntegrityError, pkg2.save)
""" Unit tests of the Dashboard application """ from django.test import TestCase from django.db import IntegrityError from launch_control.dashboard_app.models import ( SoftwarePackage, ) class SoftwarePackageTestCase(TestCase): def test_creation_1(self): sw_package = SoftwarePackage.objects.create(name='libfoo', version='1.2.0') self.assertEqual(sw_package.name, 'libfoo') self.assertEqual(sw_package.version, '1.2.0') def test_uniqueness(self): SoftwarePackage.objects.create(name='a', version='0') self.assertRaises(IntegrityError, SoftwarePackage.objects.create, name='a', version='0')
Add middleware group option and populate 'web' group. Closes #104. Signed-off-by: crynobone <e1a543840a942eb68427510a8a483282a7bfeddf@gmail.com>
<?php namespace Orchestra\Testbench\Http; use Exception; class Kernel extends \Illuminate\Foundation\Http\Kernel { /** * The bootstrap classes for the application. * * @return void */ protected $bootstrappers = []; /** * The application's middleware stack. * * @var array */ protected $middleware = [ \Illuminate\Session\Middleware\StartSession::class, \Illuminate\View\Middleware\ShareErrorsFromSession::class, ]; /** * The application's route middleware groups. * * @var array */ protected $middlewareGroups = [ 'web' => [ \Illuminate\Session\Middleware\StartSession::class, \Illuminate\View\Middleware\ShareErrorsFromSession::class, ], 'api' => [ 'throttle:60,1', ], ]; /** * Report the exception to the exception handler. * * @param \Exception $e * * @return void * * @throws \Exception */ protected function reportException(Exception $e) { throw $e; } }
<?php namespace Orchestra\Testbench\Http; use Exception; class Kernel extends \Illuminate\Foundation\Http\Kernel { /** * The bootstrap classes for the application. * * @return void */ protected $bootstrappers = []; /** * The application's middleware stack. * * @var array */ protected $middleware = [ \Illuminate\Session\Middleware\StartSession::class, \Illuminate\View\Middleware\ShareErrorsFromSession::class, ]; /** * Report the exception to the exception handler. * * @param \Exception $e * * @return void * * @throws \Exception */ protected function reportException(Exception $e) { throw $e; } }
Update the list of internal modules
module.exports = { options: { auth: require('./options/auth'), body: require('./options/body'), callback: require('./options/callback'), cookie: require('./options/cookie'), encoding: require('./options/encoding'), end: require('./options/end'), form: require('./options/form'), gzip: require('./options/gzip'), json: require('./options/json'), length: require('./options/length'), multipart: require('./options/multipart'), parse: require('./options/parse'), proxy: require('./options/proxy'), qs: require('./options/qs'), redirect: require('./options/redirect'), timeout: require('./options/timeout'), tunnel: require('./options/tunnel') }, config: require('./config'), HTTPDuplex: require('./http-duplex'), modules: require('./modules'), request: require('./request'), response: require('./response'), utils: require('./utils') }
module.exports = { options: { auth: require('./options/auth'), body: require('./options/body'), callback: require('./options/callback'), cookie: require('./options/cookie'), encoding: require('./options/encoding'), end: require('./options/end'), form: require('./options/form'), gzip: require('./options/gzip'), json: require('./options/json'), length: require('./options/length'), multipart: require('./options/multipart'), parse: require('./options/parse'), proxy: require('./options/proxy'), qs: require('./options/qs'), redirect: require('./options/redirect') }, config: require('./config'), HTTPDuplex: require('./http-duplex'), modules: require('./modules'), request: require('./request'), response: require('./response'), utils: require('./utils') }
Order Benchmark by name in the Admin
# -*- coding: utf-8 -*- from codespeed.models import Project, Revision, Executable, Benchmark, Result, Environment from django.contrib import admin class ProjectAdmin(admin.ModelAdmin): list_display = ('name', 'repo_type', 'repo_path', 'track') admin.site.register(Project, ProjectAdmin) class RevisionAdmin(admin.ModelAdmin): list_display = ('commitid', 'project', 'tag', 'date') list_filter = ('project', 'tag', 'date') search_fields = ['commitid'] admin.site.register(Revision, RevisionAdmin) class ExecutableAdmin(admin.ModelAdmin): list_display = ('name', 'description', 'id') admin.site.register(Executable, ExecutableAdmin) class BenchmarkAdmin(admin.ModelAdmin): list_display = ('name', 'benchmark_type', 'description', 'units_title', 'units', 'lessisbetter') ordering = ['name'] admin.site.register(Benchmark, BenchmarkAdmin) class EnvironmentAdmin(admin.ModelAdmin): list_display = ('name', 'cpu', 'memory', 'os', 'kernel') admin.site.register(Environment, EnvironmentAdmin) class ResultAdmin(admin.ModelAdmin): list_display = ('revision', 'benchmark', 'executable', 'environment', 'value', 'date', 'environment') list_filter = ('date', 'executable', 'benchmark', 'environment') admin.site.register(Result, ResultAdmin)
# -*- coding: utf-8 -*- from codespeed.models import Project, Revision, Executable, Benchmark, Result, Environment from django.contrib import admin class ProjectAdmin(admin.ModelAdmin): list_display = ('name', 'repo_type', 'repo_path', 'track') admin.site.register(Project, ProjectAdmin) class RevisionAdmin(admin.ModelAdmin): list_display = ('commitid', 'project', 'tag', 'date') list_filter = ('project', 'tag', 'date') search_fields = ['commitid'] admin.site.register(Revision, RevisionAdmin) class ExecutableAdmin(admin.ModelAdmin): list_display = ('name', 'description', 'id') admin.site.register(Executable, ExecutableAdmin) class BenchmarkAdmin(admin.ModelAdmin): list_display = ('name', 'benchmark_type', 'description', 'units_title', 'units', 'lessisbetter') admin.site.register(Benchmark, BenchmarkAdmin) class EnvironmentAdmin(admin.ModelAdmin): list_display = ('name', 'cpu', 'memory', 'os', 'kernel') admin.site.register(Environment, EnvironmentAdmin) class ResultAdmin(admin.ModelAdmin): list_display = ('revision', 'benchmark', 'executable', 'environment', 'value', 'date', 'environment') list_filter = ('date', 'executable', 'benchmark', 'environment') admin.site.register(Result, ResultAdmin)
Make the hash function a parameter
import sys import itertools import re from md5 import md5 puzzle_input = 'yjdafjpo' def basic_hash(n): return md5(puzzle_input + str(n)).hexdigest() def otp_keys(horizon, hash_func): lookahead = {k: -1 for k in '0123456789abcdef'} def update_lookahead(n): for quint in re.finditer(r'(.)\1{4}', hash_func(n)): lookahead[quint.group(1)] = n for i in xrange(1, horizon): update_lookahead(i) for i in itertools.count(): update_lookahead(i + horizon) triple = re.search(r'(.)\1{2}', hash_func(i)) if triple: if lookahead[triple.group(1)] > i: yield i if __name__ == '__main__': part1 = otp_keys(1000, basic_hash) print itertools.islice(part1, 63, 64).next()
import sys import itertools import re from md5 import md5 puzzle_input = 'yjdafjpo' def key(n): return md5(puzzle_input + str(n)).hexdigest() def otp_keys(horizon): lookahead = {k: -1 for k in '0123456789abcdef'} def update_lookahead(n): for quint in re.finditer(r'(.)\1{4}', key(n)): lookahead[quint.group(1)] = n for i in xrange(1, horizon): update_lookahead(i) for i in itertools.count(): update_lookahead(i + horizon) triple = re.search(r'(.)\1{2}', key(i)) if triple: if lookahead[triple.group(1)] > i: yield i if __name__ == '__main__': keys = otp_keys(1000) print itertools.islice(keys, 63, 64).next()
Reduce sleep duration in PluginManager.stop() test
import socket import time from unittest import TestCase from PluginManager import PluginManager class TestPluginManager(TestCase): def test_stop(self): class Plugin: def __init__(self): sock = socket.socket() sock.bind(('', 0)) # bind to any available port self._port = sock.getsockname()[1] sock.close() def get_port(self): return self._port plugin_manager = PluginManager(Plugin(), lambda: None) plugin_manager.start() time.sleep(0.01) plugin_manager.stop() plugin_manager.join() self.assertFalse(plugin_manager.is_alive())
import socket import time from unittest import TestCase from PluginManager import PluginManager class TestPluginManager(TestCase): def test_stop(self): class Plugin: def __init__(self): sock = socket.socket() sock.bind(('', 0)) # bind to any available port self._port = sock.getsockname()[1] sock.close() def get_port(self): return self._port plugin_manager = PluginManager(Plugin(), lambda: None) plugin_manager.start() time.sleep(1) plugin_manager.stop() plugin_manager.join() self.assertFalse(plugin_manager.is_alive())
Add test files to gulp linting
const path = require('path'); const gulp = require('gulp'); const babel = require('gulp-babel'); const eslint = require('gulp-eslint'); const Server = require('karma').Server; const src = 'src/*.js'; gulp.task('lint', () => ( gulp.src([src, 'test/index.js?(x)']) .pipe(eslint()) .pipe(eslint.format()) )); gulp.task('test', ['lint'], (done) => { new Server({ configFile: path.join(__dirname, '/karma.conf.js'), singleRun: true, autoWatch: false, }, done).start(); }); gulp.task('tdd', (done) => { new Server({ configFile: path.join(__dirname, '/karma.conf.js'), }, done).start(); }); gulp.task('build', ['test'], () => ( gulp.src(src) .pipe(babel()) .pipe(gulp.dest('lib')) )); gulp.task('default', ['build']);
const path = require('path'); const gulp = require('gulp'); const babel = require('gulp-babel'); const eslint = require('gulp-eslint'); const Server = require('karma').Server; const src = 'src/*.js'; gulp.task('lint', () => ( gulp.src(src) .pipe(eslint()) .pipe(eslint.format()) )); gulp.task('test', ['lint'], (done) => { new Server({ configFile: path.join(__dirname, '/karma.conf.js'), singleRun: true, autoWatch: false, }, done).start(); }); gulp.task('tdd', (done) => { new Server({ configFile: path.join(__dirname, '/karma.conf.js'), }, done).start(); }); gulp.task('build', ['test'], () => ( gulp.src(src) .pipe(babel()) .pipe(gulp.dest('lib')) )); gulp.task('default', ['build']);
Remove libraries not required for most use cases
import os from setuptools import setup # Ensure that the ssdeep library is built, otherwise install will fail os.environ['BUILD_LIB'] = '1' setup( name="stoq", version="0.10.16", author="Marcus LaFerrera", author_email="marcus@punchcyber.com", description="A framework for simplifying analysis.", license="Apache License 2.0", url="https://github.com/PUNCH-Cyber/stoq", packages=['stoq'], package_dir={'stoq': 'stoq-framework'}, include_package_data=True, install_requires=['beautifulsoup4', 'requests', 'python-magic', 'ssdeep', 'yapsy', 'demjson', 'jinja2', 'yara-python', 'python-json-logger'], )
import os from setuptools import setup # Ensure that the ssdeep library is built, otherwise install will fail os.environ['BUILD_LIB'] = '1' setup( name="stoq", version="0.10.16", author="Marcus LaFerrera", author_email="marcus@punchcyber.com", description="A framework for simplifying analysis.", license="Apache License 2.0", url="https://github.com/PUNCH-Cyber/stoq", packages=['stoq'], package_dir={'stoq': 'stoq-framework'}, include_package_data=True, install_requires=['beautifulsoup4', 'requests', 'python-magic', 'ssdeep', 'lxml', 'yapsy', 'demjson', 'jinja2', 'hydra', 'Cython', 'yara-python', 'python-json-logger'], )