text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Use the core, make example more useful.
import sys import os import ctypes import pyglet.window from pyglet.gl import * from pyglet import clock from pyglet import image if len(sys.argv) != 2: print 'Usage: %s <PNG/JPEG filename>'%sys.argv[0] sys.exit() window = pyglet.window.Window(width=400, height=400) image = image.load(sys.argv[1]) imx = imy = 0 @window.event def on_mouse_drag(x, y, dx, dy, buttons, modifiers): global imx, imy imx += dx imy += dy clock.set_fps_limit(30) while not window.has_exit: clock.tick() window.dispatch_events() glClear(GL_COLOR_BUFFER_BIT) image.blit(imx, imy, 0) window.flip()
import sys import os import pyglet.window from pyglet.gl import * from pyglet import clock from pyglet.ext.scene2d import Image2d from ctypes import * if len(sys.argv) != 2: print 'Usage: %s <PNG/JPEG filename>'%sys.argv[0] sys.exit() window = pyglet.window.Window(width=400, height=400) image = Image2d.load(sys.argv[1]) s = max(image.width, image.height) c = clock.Clock(60) glMatrixMode(GL_PROJECTION) glLoadIdentity() gluPerspective(60., 1., 1., 100.) glEnable(GL_COLOR_MATERIAL) glMatrixMode(GL_MODELVIEW) glClearColor(0, 0, 0, 0) glColor4f(1, 1, 1, 1) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) glEnable(GL_BLEND) while not window.has_exit: c.tick() window.dispatch_events() glClear(GL_COLOR_BUFFER_BIT) glLoadIdentity() glScalef(1./s, 1./s, 1.) glTranslatef(-image.width/2, -image.height/2, -1.) image.draw() window.flip()
Use Paramiko to retrieve the entire 'show version' output from pynet-rtr2.
# Use Paramiko to retrieve the entire 'show version' output from pynet-rtr2. #!/usr/bin/python from getpass import getpass import time import paramiko def main(): ip_addr = '50.76.53.27' username = 'pyclass' password = getpass() ssh_port = 8022 remote_conn_pre = paramiko.SSHClient() remote_conn_pre.set_missing_host_key_policy(paramiko.AutoAddPolicy()) remote_conn_pre.connect(ip_addr, username=username, password=password, look_for_keys=False, allow_agent=False, port=ssh_port) remote_conn = remote_conn_pre.invoke_shell() output = remote_conn.recv(65535) print output outp = remote_conn.send("terminal length 0\n") time.sleep(2) outp = remote_conn.recv(65535) print outp remote_conn.send("show version\n") time.sleep(2) output = remote_conn.recv(65535) print output if __name__ == "__main__": main()
#!/usr/bin/python from getpass import getpass import time import paramiko def main(): ip_addr = '50.76.53.27' username = 'pyclass' password = getpass() ssh_port = 8022 remote_conn_pre = paramiko.SSHClient() remote_conn_pre.set_missing_host_key_policy(paramiko.AutoAddPolicy()) remote_conn_pre.connect(ip_addr, username=username, password=password, look_for_keys=False, allow_agent=False, port=ssh_port) remote_conn = remote_conn_pre.invoke_shell() output = remote_conn.recv(65535) print output outp = remote_conn.send("terminal length 0\n") time.sleep(2) outp = remote_conn.recv(65535) print outp remote_conn.send("show version\n") time.sleep(2) output = remote_conn.recv(65535) print output if __name__ == "__main__": main()
Fix arguments with async functions
const Redis = require('ioredis'); module.exports = url => { const redis = new Redis(url); redis.setJSON = async (...arguments) => { arguments[1] = JSON.stringify(arguments[1]); if (typeof arguments[2] === 'object' && arguments[2].asSeconds) { arguments[2] = parseInt(arguments[2].asSeconds()); } if (typeof arguments[2] === 'number') { arguments[3] = parseInt(arguments[2]); arguments[2] = 'EX'; } return await redis.set.apply(redis, arguments); } redis.getJSON = async key => { const value = await redis.get(key); if (value) { return JSON.parse(value); } return value; } return redis; };
const Redis = require('ioredis'); module.exports = url => { const redis = new Redis(url); redis.setJSON = async () => { arguments[1] = JSON.stringify(arguments[1]); if (typeof arguments[2] === 'object' && arguments[2].asSeconds) { arguments[2] = parseInt(arguments[2].asSeconds()); } if (typeof arguments[2] === 'number') { arguments[3] = parseInt(arguments[2]); arguments[2] = 'EX'; } return await redis.set.apply(redis, arguments); } redis.getJSON = async key => { const value = await redis.get(key); if (value) { return JSON.parse(value); } return value; } return redis; };
Implement create and delete methods for DeviceCredentials
from .rest import RestClient class DeviceCredentials(object): def __init__(self, domain, jwt_token): url = 'https://%s/api/v2/device-credentials' % domain self.client = RestClient(endpoint=url, jwt=jwt_token) def get(self, user_id=None, client_id=None, type=None, fields=[], include_fields=True): params = { 'fields': ','.join(fields) or None, 'include_fields': str(include_fields).lower(), 'user_id': user_id, 'client_id': client_id, 'type': type, } return self.client.get(params=params) def create(self, body): return self.client.post(data=body) def delete(self, id): return self.client.delete(id=id)
from .rest import RestClient class DeviceCredentials(object): def __init__(self, domain, jwt_token): url = 'https://%s/api/v2/device-credentials' % domain self.client = RestClient(endpoint=url, jwt=jwt_token) def get(self, user_id=None, client_id=None, type=None, fields=[], include_fields=True): params = { 'fields': ','.join(fields) or None, 'include_fields': str(include_fields).lower(), 'user_id': user_id, 'client_id': client_id, 'type': type, } return self.client.get(params=params)
Switch Django version from 1.0 to 1.1
"""Configuration.""" import logging import os import re from google.appengine.ext.appstats import recording logging.info('Loading %s from %s', __name__, __file__) # Custom webapp middleware to add Appstats. def webapp_add_wsgi_middleware(app): app = recording.appstats_wsgi_middleware(app) return app # Appstats URL. # TODO: Drop this once it is the default. appstats_stats_url = '/_ah/stats' # Custom Appstats path normalization. def appstats_normalize_path(path): if path.startswith('/user/'): return '/user/X' if path.startswith('/user_popup/'): return '/user_popup/X' if path.startswith('/rss/'): i = path.find('/', 5) if i > 0: return path[:i] + '/X' return re.sub(r'\d+', 'X', path) # Declare the Django version we need. from google.appengine.dist import use_library use_library('django', '1.1') # Fail early if we can't import Django 1.x. Log identifying information. import django logging.info('django.__file__ = %r, django.VERSION = %r', django.__file__, django.VERSION) assert django.VERSION[0] >= 1, "This Django version is too old"
"""Configuration.""" import logging import os import re from google.appengine.ext.appstats import recording logging.info('Loading %s from %s', __name__, __file__) # Custom webapp middleware to add Appstats. def webapp_add_wsgi_middleware(app): app = recording.appstats_wsgi_middleware(app) return app # Appstats URL. # TODO: Drop this once it is the default. appstats_stats_url = '/_ah/stats' # Custom Appstats path normalization. def appstats_normalize_path(path): if path.startswith('/user/'): return '/user/X' if path.startswith('/user_popup/'): return '/user_popup/X' if path.startswith('/rss/'): i = path.find('/', 5) if i > 0: return path[:i] + '/X' return re.sub(r'\d+', 'X', path) # Declare the Django version we need. from google.appengine.dist import use_library use_library('django', '1.0') # Fail early if we can't import Django 1.x. Log identifying information. import django logging.info('django.__file__ = %r, django.VERSION = %r', django.__file__, django.VERSION) assert django.VERSION[0] >= 1, "This Django version is too old"
Fix PersonaBar loading when within an iframe
'use strict'; define(['jquery'], function ($) { return { init: function () { var inIframe = window.parent && typeof window.parent.dnn !== "undefined"; var tabId = inIframe ? window.parent.dnn.getVar('sf_tabId') : ''; var siteRoot = inIframe ? window.parent.dnn.getVar('sf_siteRoot') : ''; var antiForgeryToken = inIframe ? window.parent.document.getElementsByName('__RequestVerificationToken')[0].value : ''; var config = $.extend({}, { tabId: tabId, siteRoot: siteRoot, antiForgeryToken: antiForgeryToken }, inIframe ? window.parent['personaBarSettings'] : {}); return config; } }; });
'use strict'; define(['jquery'], function ($) { return { init: function () { var inIframe = window !== window.top && typeof window.top.dnn !== "undefined"; var tabId = inIframe ? window.top.dnn.getVar('sf_tabId') : ''; var siteRoot = inIframe ? window.top.dnn.getVar('sf_siteRoot') : ''; var antiForgeryToken = inIframe ? window.top.document.getElementsByName('__RequestVerificationToken')[0].value : ''; var config = $.extend({}, { tabId: tabId, siteRoot: siteRoot, antiForgeryToken: antiForgeryToken }, inIframe ? window.parent['personaBarSettings'] : {}); return config; } }; });
Add finalise action handling in pages reducer
/** * mSupply Mobile * Sustainable Solutions (NZ) Ltd. 2019 */ import { DataTablePageReducer } from '../pages/dataTableUtilities/reducer/DataTablePageReducer'; import getPageInitialiser from '../pages/dataTableUtilities/getPageInitialiser'; import { FINALISE_ACTIONS } from '../actions/FinaliseActions'; /** * Redux reducer controlling the `pages` field. * @param {Object} state Redux state, `pages` field. * @param {Object} action An action object, following the FSA-standard for action objects */ export const PagesReducer = (state = {}, action) => { const { type } = action; switch (type) { case 'Navigation/BACK': { const { payload } = action; const { prevRouteName } = payload || {}; return { ...state, currentRoute: prevRouteName }; } case FINALISE_ACTIONS.CONFIRM_FINALISE: { return { ...state }; } case 'Navigation/REPLACE': case 'Navigation/NAVIGATE': { const { routeName, params } = action; const { pageObject } = params; const pageInitialiser = getPageInitialiser(routeName); const pageInitialState = pageInitialiser?.(pageObject); return { ...state, [routeName]: pageInitialState, currentRoute: routeName }; } default: { const { payload } = action; const { route } = payload || {}; const newState = route ? { ...state, [route]: DataTablePageReducer(state[route], action) } : state; return newState; } } };
/** * mSupply Mobile * Sustainable Solutions (NZ) Ltd. 2019 */ import { DataTablePageReducer } from '../pages/dataTableUtilities/reducer/DataTablePageReducer'; import getPageInitialiser from '../pages/dataTableUtilities/getPageInitialiser'; /** * Redux reducer controlling the `pages` field. * @param {Object} state Redux state, `pages` field. * @param {Object} action An action object, following the FSA-standard for action objects */ export const PagesReducer = (state = {}, action) => { const { type } = action; switch (type) { case 'Navigation/BACK': { const { payload } = action; const { prevRouteName } = payload || {}; return { ...state, currentRoute: prevRouteName }; } case 'Navigation/REPLACE': case 'Navigation/NAVIGATE': { const { routeName, params } = action; const { pageObject } = params; const pageInitialiser = getPageInitialiser(routeName); const pageInitialState = pageInitialiser?.(pageObject); return { ...state, [routeName]: pageInitialState, currentRoute: routeName }; } default: { const { payload } = action; const { route } = payload || {}; const newState = route ? { ...state, [route]: DataTablePageReducer(state[route], action) } : state; return newState; } } };
Add a presubmit script that runs pylint in catapult/dashboard. Also, resolve current issues in catapult/dashboard that pylint warns about. (Note: these were also resolved in cl/95586698.) Review URL: https://codereview.chromium.org/1188483002
# Copyright 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Top-level presubmit script for catapult. See https://www.chromium.org/developers/how-tos/depottools/presubmit-scripts for more details about the presubmit API built into depot_tools. """ def GetPreferredTryMasters(project, change): # pylint: disable=unused-argument return { 'tryserver.client.catapult': { 'Catapult Linux Tryserver': {'defaulttests'}, 'Catapult Mac Tryserver': {'defaulttests'}, 'Catapult Windows Tryserver': {'defaulttests'}, } } def _CommonChecks(input_api, output_api): results = [] results.extend(input_api.canned_checks.PanProjectChecks( input_api, output_api)) return results def CheckChangeOnUpload(input_api, output_api): results = [] results.extend(_CommonChecks(input_api, output_api)) results.extend(_RunPylint(input_api, output_api)) return results def CheckChangeOnCommit(input_api, output_api): results = [] results.extend(_CommonChecks(input_api, output_api)) return results def _RunPylint(input_api, output_api): tests = input_api.canned_checks.GetPylint(input_api, output_api) return input_api.RunTests(tests)
# Copyright (c) 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Top-level presubmit script for catapult. See https://www.chromium.org/developers/how-tos/depottools/presubmit-scripts for more details about the presubmit API built into depot_tools. """ def GetPreferredTryMasters(project, change): # pylint: disable=unused-argument return { 'tryserver.client.catapult': { 'Catapult Linux Tryserver': {'defaulttests'}, 'Catapult Mac Tryserver': {'defaulttests'}, 'Catapult Windows Tryserver': {'defaulttests'}, } } def _CommonChecks(input_api, output_api): results = [] results.extend(input_api.canned_checks.PanProjectChecks( input_api, output_api)) return results def CheckChangeOnUpload(input_api, output_api): results = [] results.extend(_CommonChecks(input_api, output_api)) return results def CheckChangeOnCommit(input_api, output_api): results = [] results.extend(_CommonChecks(input_api, output_api)) return results
Remove `consul` from the check labels
package mesos import ( "fmt" "strings" "github.com/CiscoCloud/mesos-consul/registry" ) func (sj *StateJSON) GetFollowerById(id string) (string, error) { for _, f := range sj.Followers { if f.Id == id { return f.Hostname, nil } } return "", fmt.Errorf("Follower not found: %s", id) } // Task Methods // GetCheck() // Build a Check structure from the Task labels // func (t *Task) GetCheck() *registry.Check { c := registry.DefaultCheck() for _, l := range t.Labels { k := strings.ToLower(l.Key) switch k { case "check_http": c.HTTP = l.Value case "check_script": c.Script = l.Value case "check_ttl": c.TTL = l.Value case "check_interval": c.Interval = l.Value } } return c }
package mesos import ( "fmt" "strings" "github.com/CiscoCloud/mesos-consul/registry" ) func (sj *StateJSON) GetFollowerById(id string) (string, error) { for _, f := range sj.Followers { if f.Id == id { return f.Hostname, nil } } return "", fmt.Errorf("Follower not found: %s", id) } // Task Methods // GetCheck() // Build a Check structure from the Task labels // func (t *Task) GetCheck() *registry.Check { c := registry.DefaultCheck() for _, l := range t.Labels { k := strings.ToLower(l.Key) switch k { case "consul_http_check": c.HTTP = l.Value case "consul_script_check": c.Script = l.Value case "consul_ttl_check": c.TTL = l.Value case "consul_check_interval": c.Interval = l.Value } } return c }
Add support for apicalls in Bash package
#!/usr/bin/env python # Copyright (C) 2015 Dmitry Rodionov # This file is part of my GSoC'15 project for Cuckoo Sandbox: # http://www.cuckoosandbox.org # This software may be modified and distributed under the terms # of the MIT license. See the LICENSE file for details. from lib.core.packages import Package class Bash(Package): """ Bash shell script analysys package. """ def start(self): # Some scripts are not executable, so we have to use /bin/bash to # invoke them self.args = [self.target] + self.args self.target = "/bin/bash" if "method" in self.options: method = self.options["method"] else: # fallback to dtruss method = "dtruss" if "dtruss" in method: for x in self._start_dtruss(): yield x elif "apicalls" in method: for x in self._start_apicalls(): yield x else: yield "Invalid analysis method \"%S\" for package \"Bash\"" % method
#!/usr/bin/env python # Copyright (C) 2015 Dmitry Rodionov # This file is part of my GSoC'15 project for Cuckoo Sandbox: # http://www.cuckoosandbox.org # This software may be modified and distributed under the terms # of the MIT license. See the LICENSE file for details. from lib.core.packages import Package class Bash(Package): """ Bash shell script analysys package. """ def start(self): # Some scripts are not executable, so we have to use /bin/bash to # invoke them self.args = [self.target] + self.args self.target = "/bin/bash" if "method" in self.options: method = self.options["method"] else: # fallback to dtruss method = "dtruss" if "dtruss" in method: for x in self._start_dtruss(): yield x else: yield "Invalid analysis method \"%S\" for package \"Bash\"" % method
Add 'public' visibilty to abstract 'getContainer' method.
<?php namespace Robo; trait TaskAccessor { /** * Commands that use TaskAccessor must provide 'getContainer()'. */ public abstract function getContainer(); /** * Convenience function. Use: * * $this->task('Foo', $a, $b); * * instead of: * * $this->getContainer()->get('taskFoo', [$a, $b]); * * Note that most tasks will define another convenience * function, $this->taskFoo($a, $b), declared in a * 'loadTasks' trait in the task's namespace. These * 'loadTasks' convenience functions typically will call * $this->task() to ensure that task objects are fetched * from the container, so that their dependencies may be * automatically resolved. */ protected function task() { $args = func_get_args(); $name = array_shift($args); // We'll allow callers to include the literal 'task' // or not, as they wish; however, the container object // that we fetch must always begin with 'task' if (!preg_match('#^task#', $name)) { $name = "task$name"; } return $this->getContainer()->get($name, $args); } }
<?php namespace Robo; trait TaskAccessor { /** * Commands that use TaskAccessor must provide 'getContainer()'. */ abstract function getContainer(); /** * Convenience function. Use: * * $this->task('Foo', $a, $b); * * instead of: * * $this->getContainer()->get('taskFoo', [$a, $b]); * * Note that most tasks will define another convenience * function, $this->taskFoo($a, $b), declared in a * 'loadTasks' trait in the task's namespace. These * 'loadTasks' convenience functions typically will call * $this->task() to ensure that task objects are fetched * from the container, so that their dependencies may be * automatically resolved. */ protected function task() { $args = func_get_args(); $name = array_shift($args); // We'll allow callers to include the literal 'task' // or not, as they wish; however, the container object // that we fetch must always begin with 'task' if (!preg_match('#^task#', $name)) { $name = "task$name"; } return $this->getContainer()->get($name, $args); } }
Use uitools.sip instead of straight sip
try: from uitools.sip import wrapinstance from uitools.qt import QtCore import maya.OpenMayaUI as apiUI # These modules will not exist while building the docs. except ImportError: import os if os.environ.get('SPHINX') != 'True': raise def get_maya_window(): """Get the main Maya window as a QtGui.QMainWindow.""" ptr = apiUI.MQtUtil.mainWindow() if ptr is not None: return wrapinstance(long(ptr), QtCore.QObject) def maya_to_qt(maya_object): """Convert a Maya UI path to a Qt object. :param str maya_object: The path of the Maya UI object to convert. :returns: QtCore.QObject or None """ ptr = ( apiUI.MQtUtil.findControl(maya_object) or apiUI.MQtUtil.findLayout(maya_object) or apiUI.MQtUtil.findMenuItem(maya_object) ) if ptr is not None: return wrapinstance(long(ptr), QtCore.QObject)
try: import sip from uitools.qt import QtCore import maya.OpenMayaUI as apiUI # These modules will not exist while building the docs. except ImportError: import os if os.environ.get('SPHINX') != 'True': raise def get_maya_window(): """Get the main Maya window as a QtGui.QMainWindow.""" ptr = apiUI.MQtUtil.mainWindow() if ptr is not None: return sip.wrapinstance(long(ptr), QtCore.QObject) def maya_to_qt(maya_object): """Convert a Maya UI path to a Qt object. :param str maya_object: The path of the Maya UI object to convert. :returns: QtCore.QObject or None """ ptr = ( apiUI.MQtUtil.findControl(maya_object) or apiUI.MQtUtil.findLayout(maya_object) or apiUI.MQtUtil.findMenuItem(maya_object) ) if ptr is not None: return sip.wrapinstance(long(ptr), QtCore.QObject)
Update defineProperty for old IE
Object.defineProperty = function defineProperty(object, property, descriptor) { // handle object if (object === null || typeof object !== 'object') { throw new TypeError('Object must be an object'); } // handle descriptor if (descriptor === null || typeof descriptor !== 'object') { throw new TypeError('Descriptor must be an object'); } var propertyString = String(property), Element = window.Element || {}; // handle descriptor.get if ('get' in descriptor) { object[propertyString] = object === Element.prototype ? new Element.__getter__(descriptor.get) : descriptor.get.call(object); } // handle descriptor.value else { object[propertyString] = descriptor.value; } // handle descriptor.set if ('set' in descriptor && object.constructor === Element) { object.attachEvent('onpropertychange', function callee(event) { object.detachEvent('onpropertychange', callee); if (event.propertyName === propertyString) { object[propertyString] = descriptor.set.call(object, object[propertyString]); } object.attachEvent('onpropertychange', callee); }); } // return object return object; };
Object.defineProperty = function defineProperty(object, property, descriptor) { // handle object if (object === null || typeof object !== 'object') { throw new TypeError('Object must be an object'); } // handle descriptor if (descriptor === null || typeof descriptor !== 'object') { throw new TypeError('Descriptor must be an object'); } var propertyString = String(property), Element = window.Element || {}; // handle descriptor.get if ('get' in descriptor) { object[propertyString] = object === Element.prototype ? Element.__defineGetter__(propertyString, descriptor.get) : descriptor.get.call(object); } // handle descriptor.value else { object[propertyString] = descriptor.value; } // handle descriptor.set if ('set' in descriptor && object.constructor === Element) { object.attachEvent('onpropertychange', function callee(event) { object.detachEvent('onpropertychange', callee); if (event.propertyName === propertyString) { object[propertyString] = descriptor.set.call(object, object[propertyString]); } object.attachEvent('onpropertychange', callee); }); } // return object return object; };
Add additional table to cassandra variant store
#!/usr/bin/env python import argparse import getpass from cassandra import query from cassandra.cqlengine.management import sync_table from cassandra.cqlengine.management import create_keyspace_simple from cassandra.cluster import Cluster from cassandra.cqlengine import connection from cassandra.auth import PlainTextAuthProvider from variantstore import Variant from variantstore import SampleVariant from variantstore import TargetVariant if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument('-a', '--address', help="IP Address for Cassandra connection", default='127.0.0.1') parser.add_argument('-u', '--username', help='Cassandra username for login', default=None) parser.add_argument('-r', '--replication_factor', help="Cassandra replication factor", default=3) args = parser.parse_args() if args.username: password = getpass.getpass() auth_provider = PlainTextAuthProvider(username=args.username, password=password) cluster = Cluster([args.address], auth_provider=auth_provider) session = cluster.connect() session.row_factory = query.dict_factory else: cluster = Cluster([args.address]) session = cluster.connect() session.row_factory = query.dict_factory connection.set_session(session) create_keyspace_simple("variantstore", args.replication_factor) sync_table(Variant) sync_table(SampleVariant) sync_table(TargetVariant)
#!/usr/bin/env python import argparse import getpass from cassandra import query from cassandra.cqlengine.management import sync_table from cassandra.cqlengine.management import create_keyspace_simple from cassandra.cluster import Cluster from cassandra.cqlengine import connection from cassandra.auth import PlainTextAuthProvider from variantstore import Variant from variantstore import SampleVariant if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument('-a', '--address', help="IP Address for Cassandra connection", default='127.0.0.1') parser.add_argument('-u', '--username', help='Cassandra username for login', default=None) parser.add_argument('-r', '--replication_factor', help="Cassandra replication factor", default=3) args = parser.parse_args() if args.username: password = getpass.getpass() auth_provider = PlainTextAuthProvider(username=args.username, password=password) cluster = Cluster([args.address], auth_provider=auth_provider) session = cluster.connect() session.row_factory = query.dict_factory else: cluster = Cluster([args.address]) session = cluster.connect() session.row_factory = query.dict_factory connection.set_session(session) create_keyspace_simple("variantstore", args.replication_factor) sync_table(Variant) sync_table(SampleVariant)
Set fade duration to 1
package me.eddiep.lifxbulb.rave.system; import com.github.besherman.lifx.LFXHSBKColor; import com.github.besherman.lifx.LFXLight; import java.awt.*; public class LightHolder { private LFXLight light; private Color originalColor; private int r, g, b; private int kelvin; public LightHolder(LFXLight light) { this.light = light; LFXHSBKColor color = light.getColor(); this.originalColor = Color.getHSBColor(color.getHue(), color.getSaturation(), color.getBrightness()); this.r = originalColor.getRed(); this.g = originalColor.getGreen(); this.b = originalColor.getBlue(); this.kelvin = color.getKelvin(); } public void raveWithValue(float num) { int newR = Math.min((int)(r * num), 255), newG = Math.min((int)(g * num), 255), newB = Math.min((int)(b * num), 255); Color color = new Color(newR, newG, newB); light.setColor(new LFXHSBKColor(color, kelvin), 1); } }
package me.eddiep.lifxbulb.rave.system; import com.github.besherman.lifx.LFXHSBKColor; import com.github.besherman.lifx.LFXLight; import java.awt.*; public class LightHolder { private LFXLight light; private Color originalColor; private int r, g, b; private int kelvin; public LightHolder(LFXLight light) { this.light = light; LFXHSBKColor color = light.getColor(); this.originalColor = Color.getHSBColor(color.getHue(), color.getSaturation(), color.getBrightness()); this.r = originalColor.getRed(); this.g = originalColor.getGreen(); this.b = originalColor.getBlue(); this.kelvin = color.getKelvin(); } public void raveWithValue(float num) { int newR = Math.min((int)(r * num), 255), newG = Math.min((int)(g * num), 255), newB = Math.min((int)(b * num), 255); Color color = new Color(newR, newG, newB); light.setColor(new LFXHSBKColor(color, kelvin)); } }
Add 'six' to known_third_party for SortImports six was being sorted incorrectly due to being classed as first party.
# coding: utf-8 from __future__ import absolute_import, division, print_function from pathlib import Path from isort import SortImports from shovel import task # isort multi_line_output modes GRID = 0 VERTICAL = 1 HANGING_INDENT = 2 VERTICAL_HANGING_INDENT = 3 HANGING_GRID = 4 HANGING_GRID_GROUPED = 5 @task def format_imports(): """Sort imports into a consistent style.""" astrodynamics_dir = Path('astrodynamics') constants_dir = astrodynamics_dir / 'constants' for initfile in astrodynamics_dir.glob('**/__init__.py'): if constants_dir in initfile.parents: continue SortImports(str(initfile), multi_line_output=VERTICAL_HANGING_INDENT, not_skip=['__init__.py']) # Exclude __init__.py # Exclude generated constants/ python files for pyfile in astrodynamics_dir.glob('**/*.py'): if constants_dir in pyfile.parents and pyfile.stem != 'constant': continue SortImports(str(pyfile), multi_line_output=HANGING_GRID, skip=['__init__.py'], known_third_party=['six'])
# coding: utf-8 from __future__ import absolute_import, division, print_function from pathlib import Path from isort import SortImports from shovel import task # isort multi_line_output modes GRID = 0 VERTICAL = 1 HANGING_INDENT = 2 VERTICAL_HANGING_INDENT = 3 HANGING_GRID = 4 HANGING_GRID_GROUPED = 5 @task def format_imports(): """Sort imports into a consistent style.""" astrodynamics_dir = Path('astrodynamics') constants_dir = astrodynamics_dir / 'constants' for initfile in astrodynamics_dir.glob('**/__init__.py'): if constants_dir in initfile.parents: continue SortImports(str(initfile), multi_line_output=VERTICAL_HANGING_INDENT, not_skip=['__init__.py']) # Exclude __init__.py # Exclude generated constants/ python files for pyfile in astrodynamics_dir.glob('**/*.py'): if constants_dir in pyfile.parents and pyfile.stem != 'constant': continue SortImports(str(pyfile), multi_line_output=HANGING_GRID, skip=['__init__.py'])
Add playlist attribute to playlist controller
import logging import time from mopidy.exceptions import MpdNotImplemented from mopidy.models import Playlist logger = logging.getLogger('backends.base') class BaseBackend(object): current_playlist = None library = None playback = None stored_playlists = None uri_handlers = [] class BaseCurrentPlaylistController(object): def __init__(self, backend): self.backend = backend self.playlist = Playlist() def add(self, track, at_position=None): raise NotImplementedError class BasePlaybackController(object): PAUSED = 'paused' PLAYING = 'playing' STOPPED = 'stopped' def __init__(self, backend): self.backend = backend self.state = self.STOPPED self.current_track = None self.playlist_position = None def play(self, id=None, position=None): raise NotImplementedError def next(self): raise NotImplementedError
import logging import time from mopidy.exceptions import MpdNotImplemented from mopidy.models import Playlist logger = logging.getLogger('backends.base') class BaseBackend(object): current_playlist = None library = None playback = None stored_playlists = None uri_handlers = [] class BaseCurrentPlaylistController(object): def __init__(self, backend): self.backend = backend def add(self, track, at_position=None): raise NotImplementedError class BasePlaybackController(object): PAUSED = 'paused' PLAYING = 'playing' STOPPED = 'stopped' def __init__(self, backend): self.backend = backend self.state = self.STOPPED self.current_track = None self.playlist_position = None def play(self, id=None, position=None): raise NotImplementedError def next(self): raise NotImplementedError
Transform broken reference to malformed-payload error
package qemuengine import ( "fmt" "os" "github.com/taskcluster/taskcluster-worker/engines/qemu/image" "github.com/taskcluster/taskcluster-worker/runtime" "github.com/taskcluster/taskcluster-worker/runtime/fetcher" ) // A fetcher for downloading images. var imageFetcher = fetcher.Combine( // Allow fetching images from URL fetcher.URL, // Allow fetching images from queue artifacts fetcher.Artifact, ) type fetchImageContext struct { *runtime.TaskContext } func (c fetchImageContext) Progress(description string, percent float64) { c.Log(fmt.Sprintf("Fetching image: %s - %f %%", description, percent)) } func imageDownloader(c *runtime.TaskContext, image interface{}) image.Downloader { return func(imageFile string) error { target, err := os.Create(imageFile) if err != nil { return err } err = imageFetcher.Fetch(fetchImageContext{c}, image, &fetcher.FileReseter{File: target}) if err != nil { defer target.Close() if fetcher.IsBrokenReferenceError(err) { return runtime.NewMalformedPayloadError("unable to fetch image, error:", err) } return err } return target.Close() } }
package qemuengine import ( "fmt" "os" "github.com/taskcluster/taskcluster-worker/engines/qemu/image" "github.com/taskcluster/taskcluster-worker/runtime" "github.com/taskcluster/taskcluster-worker/runtime/fetcher" ) // A fetcher for downloading images. var imageFetcher = fetcher.Combine( // Allow fetching images from URL fetcher.URL, // Allow fetching images from queue artifacts fetcher.Artifact, ) type fetchImageContext struct { *runtime.TaskContext } func (c fetchImageContext) Progress(description string, percent float64) { c.Log(fmt.Sprintf("Fetching image: %s - %f %%", description, percent)) } func imageDownloader(c *runtime.TaskContext, image interface{}) image.Downloader { return func(imageFile string) error { target, err := os.Create(imageFile) if err != nil { return err } err = imageFetcher.Fetch(fetchImageContext{c}, image, &fetcher.FileReseter{File: target}) if err != nil { defer target.Close() return err } return target.Close() } }
DPRO-2637: Set shorted TTL for editorial content cache
package org.ambraproject.wombat.config; import javax.cache.expiry.Duration; import java.util.concurrent.TimeUnit; public enum RemoteCacheSpace { ARTICLE_API("articleApi"), USER_API("userApi"), ARTICLE_HTML("articleHtml"), AMENDMENT_BODY("amendmentBody"), SITE_CONTENT_METADATA("siteContentMetadata"), EXTERNAL_RESOURCE("externalResource"), EDITORIAL_CONTENT("editorialContent", new Duration(TimeUnit.MINUTES, 30)); private final String cacheName; private final Duration timeToLive; private RemoteCacheSpace(String cacheName) { this(cacheName, null); // would be DEFAULT_TTL but static vars aren't accessible here; check in getter instead } private RemoteCacheSpace(String cacheName, Duration timeToLive) { this.cacheName = cacheName; this.timeToLive = timeToLive; } private static final Duration DEFAULT_TTL = new Duration(TimeUnit.HOURS, 1); /** * @return the name to provide to {@link javax.cache.CacheManager} when creating or getting a cache */ String getCacheName() { return cacheName; } Duration getTimeToLive() { return (timeToLive == null) ? DEFAULT_TTL : timeToLive; } }
package org.ambraproject.wombat.config; import javax.cache.expiry.Duration; import java.util.concurrent.TimeUnit; public enum RemoteCacheSpace { ARTICLE_API("articleApi"), USER_API("userApi"), ARTICLE_HTML("articleHtml"), AMENDMENT_BODY("amendmentBody"), SITE_CONTENT_METADATA("siteContentMetadata"), EXTERNAL_RESOURCE("externalResource"), EDITORIAL_CONTENT("editorialContent"); private final String cacheName; private final Duration timeToLive; private RemoteCacheSpace(String cacheName) { this(cacheName, null); // would be DEFAULT_TTL but static vars aren't accessible here; check in getter instead } private RemoteCacheSpace(String cacheName, Duration timeToLive) { this.cacheName = cacheName; this.timeToLive = timeToLive; } private static final Duration DEFAULT_TTL = new Duration(TimeUnit.HOURS, 1); /** * @return the name to provide to {@link javax.cache.CacheManager} when creating or getting a cache */ String getCacheName() { return cacheName; } Duration getTimeToLive() { return (timeToLive == null) ? DEFAULT_TTL : timeToLive; } }
Add mongolab mongodb hosting (free...)
'use strict'; var express = require('express'), favicon = require('serve-favicon'), routes = require('./app/routes/index.js'), mongo = require('mongodb').MongoClient; var app = express(); var mongoURL = process.env.MONGOLAB_URI || 'mongodb://localhost:27017/timolawlurlshortener'; mongo.connect(mongoURL, function(err, db) { if (err) { throw new Error('Database failed to connect!'); } else { console.log('MongoDB successfully connected on port 27017.'); } app.set('port', (process.env.PORT || 5000)); app.use('/public', express.static(process.cwd() + '/public')); app.use(favicon(process.cwd() + '/public/images/favicon.ico')); routes(app, db); app.listen(app.get('port'), function() { console.log('Node app is running on port', app.get('port')); }); });
'use strict'; var express = require('express'), favicon = require('serve-favicon'), routes = require('./app/routes/index.js'), mongo = require('mongodb').MongoClient; var app = express(); mongo.connect('mongodb://localhost:27017/timolawlurlshortener', function(err, db) { if (err) { throw new Error('Database failed to connect!'); } else { console.log('MongoDB successfully connected on port 27017.'); } app.set('port', (process.env.PORT || 5000)); app.use('/public', express.static(process.cwd() + '/public')); app.use(favicon(process.cwd() + '/public/images/favicon.ico')); routes(app, db); app.listen(app.get('port'), function() { console.log('Node app is running on port', app.get('port')); }); });
Fix module name in module docstring
""" byceps.services.brand.dbmodels.brand ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2022 Jochen Kupperschmidt :License: Revised BSD (see `LICENSE` file for details) """ from typing import Optional from ....database import db from ....typing import BrandID from ....util.instances import ReprBuilder class Brand(db.Model): """A party brand.""" __tablename__ = 'brands' id = db.Column(db.UnicodeText, primary_key=True) title = db.Column(db.UnicodeText, unique=True, nullable=False) image_filename = db.Column(db.UnicodeText, nullable=True) archived = db.Column(db.Boolean, default=False, nullable=False) def __init__( self, brand_id: BrandID, title: str, *, image_filename: Optional[str] = None, ) -> None: self.id = brand_id self.title = title self.image_filename = image_filename def __repr__(self) -> str: return ReprBuilder(self) \ .add_with_lookup('id') \ .build()
""" byceps.services.dbbrand.models.brand ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2022 Jochen Kupperschmidt :License: Revised BSD (see `LICENSE` file for details) """ from typing import Optional from ....database import db from ....typing import BrandID from ....util.instances import ReprBuilder class Brand(db.Model): """A party brand.""" __tablename__ = 'brands' id = db.Column(db.UnicodeText, primary_key=True) title = db.Column(db.UnicodeText, unique=True, nullable=False) image_filename = db.Column(db.UnicodeText, nullable=True) archived = db.Column(db.Boolean, default=False, nullable=False) def __init__( self, brand_id: BrandID, title: str, *, image_filename: Optional[str] = None, ) -> None: self.id = brand_id self.title = title self.image_filename = image_filename def __repr__(self) -> str: return ReprBuilder(self) \ .add_with_lookup('id') \ .build()
Add more keywords to ruby sandbox
const {VM} = require('vm2') const exec = require('child_process').exec module.exports = { js: code => { const vm = new VM() try { return vm.run(code).toString() } catch (e) { return e.toString(); } }, rb: code => { return new Promise((resolve, reject) => { const unsafe = new RegExp(/(`|%x|system|exec|method|call|unpack|eval|require|Dir|File|ENV|Process|send|Object)/, 'g') const formattedCode = code.replace(/'/g, '"') if(unsafe.test(formattedCode)){ resolve('Unsafe characters found') } else { exec(`ruby -e 'puts ${formattedCode}'`, (err, stdout, stderr) => { if(err){ reject(err) } resolve(stdout) }) } }) } }
const {VM} = require('vm2') const exec = require('child_process').exec module.exports = { js: code => { const vm = new VM() try { return vm.run(code).toString() } catch (e) { return e.toString(); } }, rb: code => { return new Promise((resolve, reject) => { const unsafe = new RegExp(/(`|%x|system|exec|unpack|eval|require|Dir|File|ENV|Process|send|Object)/, 'g') const formattedCode = code.replace(/'/g, '"') if(unsafe.test(formattedCode)){ resolve('Unsafe characters found') } else { exec(`ruby -e 'puts ${formattedCode}'`, (err, stdout, stderr) => { if(err){ reject(err) } resolve(stdout) }) } }) } }
Return a 404 if there is no post with the provided ID
<?php namespace SymfonyDay\Bundle\BlogBundle\Controller; use Symfony\Component\HttpFoundation\Response; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template; class DefaultController extends Controller { /** * @Route("/blog", name="blog") * @Template() */ public function indexAction() { $em = $this->getDoctrine()->getEntityManager(); $posts = $em->getRepository('SymfonyDayBlogBundle:Post')->findAll(); return array('posts' => $posts); } /** * @Route("/blog/{id}", requirements={ "id"="\d+" }, name="post") * @Template() */ public function postAction($id) { $em = $this->getDoctrine()->getEntityManager(); $post = $em->getRepository('SymfonyDayBlogBundle:Post')->find($id); if (!$post) { throw $this->createNotFoundException(sprintf('The post object identified by #%u does not exist.', $id)); } return array('post' => $post); } }
<?php namespace SymfonyDay\Bundle\BlogBundle\Controller; use Symfony\Component\HttpFoundation\Response; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template; class DefaultController extends Controller { /** * @Route("/blog", name="blog") * @Template() */ public function indexAction() { $em = $this->getDoctrine()->getEntityManager(); $posts = $em->getRepository('SymfonyDayBlogBundle:Post')->findAll(); return array('posts' => $posts); } /** * @Route("/blog/{id}", requirements={ "id"="\d+" }, name="post") * @Template() */ public function postAction($id) { $em = $this->getDoctrine()->getEntityManager(); $post = $em->getRepository('SymfonyDayBlogBundle:Post')->find($id); return array('post' => $post); } }
Make the lib imports work on other computers than Simon's Signed-off-by: Simon Willison <088e16a1019277b15d58faf0541e11910eb756f6@simonwillison.net>
#!/usr/bin/env python import sys, os root = os.path.dirname(__file__) paths = ( os.path.join(root), os.path.join(root, "djangopeople", "lib"), ) for path in paths: if not path in sys.path: sys.path.insert(0, path) from django.core.management import execute_manager try: import settings # Assumed to be in the same directory. except ImportError: import sys sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__) sys.exit(1) if __name__ == "__main__": execute_manager(settings)
#!/usr/bin/env python import sys paths = ( '/home/simon/sites/djangopeople.net', '/home/simon/sites/djangopeople.net/djangopeoplenet', '/home/simon/sites/djangopeople.net/djangopeoplenet/djangopeople/lib', ) for path in paths: if not path in sys.path: sys.path.insert(0, path) from django.core.management import execute_manager try: import settings # Assumed to be in the same directory. except ImportError: import sys sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__) sys.exit(1) if __name__ == "__main__": execute_manager(settings)
Fix search box with initial value after search
define(['jquery', 'DoughBaseComponent'], function($, DoughBaseComponent) { 'use strict'; var ClearInput, uiEvents = { 'keydown [data-dough-clear-input]' : 'updateResetButton', 'click [data-dough-clear-input-button]' : 'resetForm' }; ClearInput = function($el, config) { this.uiEvents = uiEvents; ClearInput.baseConstructor.call(this, $el, config); this.$resetInput = this.$el.find('[data-dough-clear-input]'); this.$resetButton = this.$el.find('[data-dough-clear-input-button]'); this.updateResetButton(); }; /** * Inherit from base module, for shared methods and interface */ DoughBaseComponent.extend(ClearInput); /** * Set up and populate the model from the form inputs * @param {Promise} initialised */ ClearInput.prototype.init = function(initialised) { this._initialisedSuccess(initialised); }; ClearInput.prototype.updateResetButton = function() { var fn = this.$resetInput.val() === '' ? 'removeClass' : 'addClass'; this.$resetButton[fn]('is-active'); }; // We are progressively enhancing the form with JS. The CSS button, type 'reset' // resets the form faster than the JS can run, so we need to invoke reset() to ensure the correct behaviour. ClearInput.prototype.resetForm = function(e) { this.$resetInput.val(''); this.updateResetButton(); this.$resetInput.focus(); e.preventDefault(); }; return ClearInput; });
define(['jquery', 'DoughBaseComponent'], function($, DoughBaseComponent) { 'use strict'; var ClearInput, uiEvents = { 'keydown [data-dough-clear-input]' : 'updateResetButton', 'click [data-dough-clear-input-button]' : 'resetForm' }; ClearInput = function($el, config) { this.uiEvents = uiEvents; ClearInput.baseConstructor.call(this, $el, config); this.$resetInput = this.$el.find('[data-dough-clear-input]'); this.$resetButton = this.$el.find('[data-dough-clear-input-button]'); }; /** * Inherit from base module, for shared methods and interface */ DoughBaseComponent.extend(ClearInput); /** * Set up and populate the model from the form inputs * @param {Promise} initialised */ ClearInput.prototype.init = function(initialised) { this._initialisedSuccess(initialised); }; ClearInput.prototype.updateResetButton = function() { var fn = this.$resetInput.val() === '' ? 'removeClass' : 'addClass'; this.$resetButton[fn]('is-active'); }; // We are progressively enhancing the form with JS. The CSS button, type 'reset' // resets the form faster than the JS can run, so we need to invoke reset() to ensure the correct behaviour. ClearInput.prototype.resetForm = function() { this.$el[0].reset(); this.updateResetButton(); }; return ClearInput; });
Add a newline after each imported asset, fixes LESS compile errors
<?php namespace Pipe; class ImportProcessor extends \MetaTemplate\Template\Base { const IMPORT_PATTERN = '/ @import[\s]*(?:"([^"]+)"|url\\((.+)\\)); /xm'; function render($context = null, $vars = array()) { $data = preg_replace_callback(self::IMPORT_PATTERN, function($matches) use ($context) { if (!empty($matches[1])) { $path = $matches[1]; } else if (!empty($matches[2])) { $path = $matches[2]; } $resolvedPath = $context->resolve($path); if (!$resolvedPath) { return $matches[0]; } $context->dependOn($resolvedPath); # Import source code without processing, for LESS files. return $context->evaluate($resolvedPath, array('processors' => array())) . "\n"; }, $this->getData()); return $data; } }
<?php namespace Pipe; class ImportProcessor extends \MetaTemplate\Template\Base { const IMPORT_PATTERN = '/ @import[\s]*(?:"([^"]+)"|url\\((.+)\\)); /xm'; function render($context = null, $vars = array()) { $data = preg_replace_callback(self::IMPORT_PATTERN, function($matches) use ($context) { if (!empty($matches[1])) { $path = $matches[1]; } else if (!empty($matches[2])) { $path = $matches[2]; } $resolvedPath = $context->resolve($path); if (!$resolvedPath) { return $matches[0]; } $context->dependOn($resolvedPath); # Import source code without processing, for LESS files. return $context->evaluate($resolvedPath, array('processors' => array())); }, $this->getData()); return $data; } }
Check whether element has tag type instead of whether name exists
var Issue = require('../issue'); module.exports = { name: 'table-req-header', on: ['tag'], filter: ['table'], desc: [ 'If set, each `table` tag must contain a header: a `thead` tag', 'or a `tr` tag with a `th` child.' ].join('\n') }; module.exports.lint = function (ele, opts) { var children = ele.children, childIndex = 0, child; //ffwd to first relevant table child while ((child = children[childIndex]) && ( child.type !== "tag" || // skip text nodes (child.name && child.name.match(/(caption|colgroup)/i)) ) ) { childIndex++; } if (child && child.name && child.name.match(/thead/i)) { return []; } if (child && child.name && child.name.match(/tr/i)) { // Check if any child in first row is `<th>`, not just first child (which could be a text node) for (var i=0, l=child.children.length; i<l; i++) { if (child.children[i].name && child.children[i].name == 'th') { return [] } } } return new Issue('E035', ele.openLineCol); };
var Issue = require('../issue'); module.exports = { name: 'table-req-header', on: ['tag'], filter: ['table'], desc: [ 'If set, each `table` tag must contain a header: a `thead` tag', 'or a `tr` tag with a `th` child.' ].join('\n') }; module.exports.lint = function (ele, opts) { var children = ele.children, childIndex = 0, child; //ffwd to first relevant table child while ((child = children[childIndex]) && ( child.name === undefined || // skip text nodes (child.name && child.name.match(/(caption|colgroup)/i)) ) ) { childIndex++; } if (child && child.name && child.name.match(/thead/i)) { return []; } if (child && child.name && child.name.match(/tr/i)) { // Check if any child in first row is `<th>`, not just first child (which could be a text node) for (var i=0, l=child.children.length; i<l; i++) { if (child.children[i].name && child.children[i].name == 'th') { return [] } } } return new Issue('E035', ele.openLineCol); };
Add new agent to API type
// Copyright 2018 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.vespa.hosted.controller.api.integration.noderepository; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; /** * Wire class for node-repository representation of the history of a node * * @author smorgrav */ @JsonIgnoreProperties(ignoreUnknown = true) @JsonInclude(JsonInclude.Include.NON_NULL) public class NodeHistory { @JsonProperty("at") public Long at; @JsonProperty("agent") public Agent agent; @JsonProperty("event") public String event; public Long getAt() { return at; } public Agent getAgent() { return agent; } public String getEvent() { return event; } public enum Agent { operator, application, system, NodeFailer, Rebalancer, DirtyExpirer, FailedExpirer, InactiveExpirer, ProvisionedExpirer, ReservationExpirer, DynamicProvisioningMaintainer, RetiringUpgrader } }
// Copyright 2018 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.vespa.hosted.controller.api.integration.noderepository; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; /** * Wire class for node-repository representation of the history of a node * * @author smorgrav */ @JsonIgnoreProperties(ignoreUnknown = true) @JsonInclude(JsonInclude.Include.NON_NULL) public class NodeHistory { @JsonProperty("at") public Long at; @JsonProperty("agent") public Agent agent; @JsonProperty("event") public String event; public Long getAt() { return at; } public Agent getAgent() { return agent; } public String getEvent() { return event; } public enum Agent { operator, application, system, NodeFailer, Rebalancer, DirtyExpirer, FailedExpirer, InactiveExpirer, ProvisionedExpirer, ReservationExpirer, DynamicProvisioningMaintainer } }
Fix bug if number is null
export const formatNumber = (number = 0, settings) => { const x = 3; const re = '\\d(?=(\\d{' + x + '})+' + (settings.decimal_number > 0 ? '\\D' : '$') + ')'; let num = (number || 0).toFixed(Math.max(0, ~~ settings.decimal_number)); return (settings.decimal_separator ? num.replace('.', settings.decimal_separator) : num).replace(new RegExp(re, 'g'), '$&' + (settings.thousand_separator)); }; const amountPattern = '{amount}'; export const formatCurrency = (number = 0, settings) => { return settings.currency_format.replace(amountPattern, formatNumber(number, settings)); } export const getThumbnailUrl = (originalUrl, width) => { if(originalUrl && originalUrl.length > 0) { const pos = originalUrl.lastIndexOf('/'); const thumbnailUrl = originalUrl.substring(0, pos) + `/${width}/` + originalUrl.substring(pos + 1); return thumbnailUrl; } else { return ''; } } export const getParentIds = (categories, categoryId) => { let parentIds = []; let parentExists = false; do { const category = categories.find(item => item.id === categoryId); parentExists = category && category.parent_id; if(parentExists){ parentIds.push(category.parent_id) categoryId = category.parent_id; } } while(parentExists) return parentIds; }
export const formatNumber = (number = 0, settings) => { const x = 3; const re = '\\d(?=(\\d{' + x + '})+' + (settings.decimal_number > 0 ? '\\D' : '$') + ')'; let num = number.toFixed(Math.max(0, ~~ settings.decimal_number)); return (settings.decimal_separator ? num.replace('.', settings.decimal_separator) : num).replace(new RegExp(re, 'g'), '$&' + (settings.thousand_separator)); }; const amountPattern = '{amount}'; export const formatCurrency = (number = 0, settings) => { return settings.currency_format.replace(amountPattern, formatNumber(number, settings)); } export const getThumbnailUrl = (originalUrl, width) => { if(originalUrl && originalUrl.length > 0) { const pos = originalUrl.lastIndexOf('/'); const thumbnailUrl = originalUrl.substring(0, pos) + `/${width}/` + originalUrl.substring(pos + 1); return thumbnailUrl; } else { return ''; } } export const getParentIds = (categories, categoryId) => { let parentIds = []; let parentExists = false; do { const category = categories.find(item => item.id === categoryId); parentExists = category && category.parent_id; if(parentExists){ parentIds.push(category.parent_id) categoryId = category.parent_id; } } while(parentExists) return parentIds; }
Add handling set prescriber action
/** * mSupply Mobile * Sustainable Solutions (NZ) Ltd. 2019 */ import { PRESCRIBER_ACTIONS } from '../actions/PrescriberActions'; const prescriberInitialState = () => ({ currentPrescriber: null, isEditingPrescriber: false, isCreatingPrescriber: false, }); export const PrescriberReducer = (state = prescriberInitialState(), action) => { const { type } = action; switch (type) { case PRESCRIBER_ACTIONS.EDIT: { const { payload } = action; const { prescriber } = payload; return { ...state, isEditingPrescriber: true, currentPrescriber: prescriber }; } case PRESCRIBER_ACTIONS.CREATE: { return { ...state, isCreatingPrescriber: true }; } case PRESCRIBER_ACTIONS.COMPLETE: { return prescriberInitialState(); } case PRESCRIBER_ACTIONS.SET: { const { payload } = action; const { prescriber } = payload; return { ...state, currentPrescriber: prescriber }; } default: { return state; } } };
/** * mSupply Mobile * Sustainable Solutions (NZ) Ltd. 2019 */ import { PRESCRIBER_ACTIONS } from '../actions/PrescriberActions'; const prescriberInitialState = () => ({ currentPrescriber: null, isEditingPrescriber: false, isCreatingPrescriber: false, }); export const PrescriberReducer = (state = prescriberInitialState(), action) => { const { type } = action; switch (type) { case PRESCRIBER_ACTIONS.EDIT: { const { payload } = action; const { prescriber } = payload; return { ...state, isEditingPrescriber: true, currentPrescriber: prescriber }; } case PRESCRIBER_ACTIONS.CREATE: { return { ...state, isCreatingPrescriber: true }; } case PRESCRIBER_ACTIONS.COMPLETE: { return prescriberInitialState(); } default: { return state; } } };
Send the origin IP in x-forwarded-for
var express = require('express'); var superagent = require('superagent'); var constants = require('../constants'); var proxy_headers = [ 'Accept-Charset', 'Accept-Language', 'Accept-Datetime', 'User-Agent', ]; var router = express.Router(); router.get('/rss/:feed', function(req, res) { var feedName = req.params.feed; if (!(feedName in constants.RSS_FEEDS)) { res.status(404).end(); return; } var url = constants.RSS_FEEDS[feedName]; var rssReq = superagent.get(url); console.log('Requesting ' + url); proxy_headers.forEach(function(h) { var userH = req.get(h); if (!userH) return; rssReq = rssReq.set(h, userH); }); rssReq.set('x-forwarded-for', req.ip); rssReq.buffer() .end(function(err, resp) { if (err) { res.status(500).end(); return; } res.type('rss').send(resp.text); }); }); module.exports = router;
var express = require('express'); var superagent = require('superagent'); var constants = require('../constants'); var proxy_headers = [ 'Accept-Charset', 'Accept-Language', 'Accept-Datetime', 'User-Agent', ]; var router = express.Router(); router.get('/rss/:feed', function(req, res) { var feedName = req.params.feed; if (!(feedName in constants.RSS_FEEDS)) { res.status(404).end(); return; } var url = constants.RSS_FEEDS[feedName]; var rssReq = superagent.get(url); console.log('Requesting ' + url); proxy_headers.forEach(function(h) { var userH = req.get(h); if (!userH) return; rssReq = rssReq.set(h, userH); }); rssReq.buffer() .end(function(err, resp) { if (err) { res.status(500).end(); return; } res.type('rss').send(resp.text); }); }); module.exports = router;
Fix long_description loading for PyPI
import os from setuptools import setup README_PATH = 'README.rst' longDesc = "" if os.path.exists(README_PATH): with open(README_PATH) as readme: longDesc = readme.read() setup( name = "pytesseract", version = "0.1.7", author = "Samuel Hoffstaetter", author_email="pytesseract@madmaze.net", maintainer = "Matthias Lee", maintainer_email = "pytesseract@madmaze.net", description = ("Python-tesseract is a python wrapper for google's Tesseract-OCR"), long_description = longDesc, license = "GPLv3", keywords = "python-tesseract OCR Python", url = "https://github.com/madmaze/python-tesseract", packages=['pytesseract'], package_dir={'pytesseract': 'src'}, package_data = {'pytesseract': ['*.png','*.jpg']}, entry_points = {'console_scripts': ['pytesseract = pytesseract.pytesseract:main']}, classifiers = [ 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', ] )
import os from setuptools import setup longDesc = "" if os.path.exists("README.rst"): longDesc = open("README.rst").read().strip() setup( name = "pytesseract", version = "0.1.7", author = "Samuel Hoffstaetter", author_email="pytesseract@madmaze.net", maintainer = "Matthias Lee", maintainer_email = "pytesseract@madmaze.net", description = ("Python-tesseract is a python wrapper for google's Tesseract-OCR"), long_description = longDesc, license = "GPLv3", keywords = "python-tesseract OCR Python", url = "https://github.com/madmaze/python-tesseract", packages=['pytesseract'], package_dir={'pytesseract': 'src'}, package_data = {'pytesseract': ['*.png','*.jpg']}, entry_points = {'console_scripts': ['pytesseract = pytesseract.pytesseract:main']}, classifiers = [ 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', ] )
Fix UDF test, take two Change-Id: I817389d94dab665199d2c1b7365e8ce0d1495c41 Reviewed-on: http://gerrit.ent.cloudera.com:8080/504 Reviewed-by: Skye Wanderman-Milne <6d4b168ab637b0a20cc9dbf96abb2537f372f946@cloudera.com> Tested-by: Skye Wanderman-Milne <6d4b168ab637b0a20cc9dbf96abb2537f372f946@cloudera.com>
#!/usr/bin/env python # Copyright (c) 2012 Cloudera, Inc. All rights reserved. from tests.common.test_vector import * from tests.common.impala_test_suite import * class TestUdfs(ImpalaTestSuite): @classmethod def get_workload(cls): return 'functional-query' @classmethod def add_test_dimensions(cls): super(TestUdfs, cls).add_test_dimensions() # UDFs require codegen cls.TestMatrix.add_constraint( lambda v: v.get_value('exec_option')['disable_codegen'] == False) # There is no reason to run these tests using all dimensions. cls.TestMatrix.add_constraint(lambda v:\ v.get_value('table_format').file_format == 'text' and\ v.get_value('table_format').compression_codec == 'none') # This must run serially because other tests executing 'invalidate metadata' will nuke # all loaded functions. # TODO: This can be run in parallel once functions are persisted correctly. @pytest.mark.execute_serially def test_udfs(self, vector): self.run_test_case('QueryTest/udf', vector)
#!/usr/bin/env python # Copyright (c) 2012 Cloudera, Inc. All rights reserved. from tests.common.test_vector import * from tests.common.impala_test_suite import * class TestUdfs(ImpalaTestSuite): @classmethod def get_workload(cls): return 'functional-query' @classmethod def add_test_dimensions(cls): super(TestUdfs, cls).add_test_dimensions() # UDFs require codegen cls.TestMatrix.add_constraint( lambda v: v.get_value('exec_option')['disable_codegen'] == False) # There is no reason to run these tests using all dimensions. cls.TestMatrix.add_constraint(lambda v:\ v.get_value('table_format').file_format == 'text' and\ v.get_value('table_format').compression_codec == 'none') def test_udfs(self, vector): self.run_test_case('QueryTest/udf', vector)
Revert "Updated What Im Working On File" This reverts commit 51a8e6d27f762fa131da4ad94b8bdf409409f6c6, reversing changes made to 40cc2cc801557622af48530c37c15a25403e44a2.
package com.allforfunmc.easyoreapi; import cpw.mods.fml.common.Mod; import cpw.mods.fml.common.Mod.EventHandler; import cpw.mods.fml.common.Mod.Instance; import cpw.mods.fml.common.SidedProxy; import cpw.mods.fml.common.event.FMLInitializationEvent; @Mod (modid="oreapi", name="AllForFun's EasyOreAPI", version="Dev") public class EasyOreApi { @Instance (value="GenericModID") public static EasyOreApi instance; @SidedProxy(clientSide="com.allforfunmc.easyoreapi.ClientProxy",serverSide="com.allforfunmc.easyoreapi.CommonProxy") public static CommonProxy proxy; @EventHandler() public void load(FMLInitializationEvent event) { proxy.registerRenderers(); } @EventHandler() public void Init(FMLInitializationEvent event) { } @EventHandler() public void postInit(FMLInitializationEvent event){ } }
package com.allforfunmc.easyoreapi; import cpw.mods.fml.common.IWorldGenerator; import cpw.mods.fml.common.Mod; import cpw.mods.fml.common.Mod.EventHandler; import cpw.mods.fml.common.Mod.Instance; import cpw.mods.fml.common.SidedProxy; import cpw.mods.fml.common.event.FMLInitializationEvent; import cpw.mods.fml.common.registry.GameRegistry; @Mod (modid="oreapi", name="AllForFun's EasyOreAPI", version="Dev") public class EasyOreApi { @Instance (value="GenericModID") public static EasyOreApi instance; @SidedProxy(clientSide="com.allforfunmc.easyoreapi.ClientProxy",serverSide="com.allforfunmc.easyoreapi.CommonProxy") public static CommonProxy proxy; @EventHandler() public void load(FMLInitializationEvent event) { proxy.registerRenderers(); } @EventHandler() public void Init(FMLInitializationEvent event) { } @EventHandler() public void postInit(FMLInitializationEvent event){ IWorldGenerator generator = new Generator(); GameRegistry.registerWorldGenerator(generator, 21); } }
Fix option value join test after serialization change
<?php namespace Civi\Test\Api4\Query; use Civi\Api4\Query\Api4SelectQuery; use Civi\Test\Api4\UnitTestCase; /** * @group headless */ class OptionValueJoinTest extends UnitTestCase { public function setUpHeadless() { $relatedTables = [ 'civicrm_contact', 'civicrm_address', 'civicrm_email', 'civicrm_phone', 'civicrm_openid', 'civicrm_im', 'civicrm_website', 'civicrm_option_group', 'civicrm_option_value', 'civicrm_activity', 'civicrm_activity_contact', ]; $this->cleanup(['tablesToTruncate' => $relatedTables]); $this->loadDataSet('SingleContact'); return parent::setUpHeadless(); } public function testCommunicationMethodJoin() { $query = new Api4SelectQuery('Contact', FALSE); $query->select[] = 'first_name'; $query->select[] = 'preferred_communication_method.label'; $results = $query->run(); $first = array_shift($results); $firstPreferredMethod = array_shift($first['preferred_communication_method']); $this->assertEquals( 'Phone', $firstPreferredMethod['label'] ); } }
<?php namespace Civi\Test\Api4\Query; use Civi\Api4\Query\Api4SelectQuery; use Civi\Test\Api4\UnitTestCase; /** * @group headless */ class OptionValueJoinTest extends UnitTestCase { public function setUpHeadless() { $relatedTables = [ 'civicrm_contact', 'civicrm_address', 'civicrm_email', 'civicrm_phone', 'civicrm_openid', 'civicrm_im', 'civicrm_website', 'civicrm_option_group', 'civicrm_option_value', 'civicrm_activity', 'civicrm_activity_contact', ]; $this->cleanup(['tablesToTruncate' => $relatedTables]); $this->loadDataSet('SingleContact'); return parent::setUpHeadless(); } public function testCommunicationMethodJoin() { $query = new Api4SelectQuery('Contact', FALSE); $query->select[] = 'first_name'; $query->select[] = 'preferred_communication_method.label'; $results = $query->run(); $this->assertEquals( 'Phone', $results[0]['preferred_communication_method']['label'] ); } }
Notification: Add some method to notificationcontent
package models import "github.com/koding/bongo" func (nc *NotificationContent) AfterCreate() { bongo.B.AfterCreate(nc) } func (nc *NotificationContent) AfterUpdate() { bongo.B.AfterUpdate(nc) } func (nc *NotificationContent) AfterDelete() { bongo.B.AfterDelete(nc) } func NewNotificationContent() *NotificationContent { return &NotificationContent{} } func (n *NotificationContent) GetId() int64 { return n.Id } func (n NotificationContent) TableName() string { return "notification.notification_content" } // Create checks for NotificationContent using type_constant and target_id // and creates new one if it does not exist. func (n *NotificationContent) Create() error { if err := n.FindByTarget(); err != nil { if err != bongo.RecordNotFound { return err } return bongo.B.Create(n) } return nil } func (n *NotificationContent) One(q *bongo.Query) error { return bongo.B.One(n, n, q) } func (n *NotificationContent) ById(id int64) error { return bongo.B.ById(n, id) } func (n *NotificationContent) Some(data interface{}, q *bongo.Query) error { return bongo.B.Some(n, data, q) }
package models import "github.com/koding/bongo" func (nc *NotificationContent) AfterCreate() { bongo.B.AfterCreate(nc) } func (nc *NotificationContent) AfterUpdate() { bongo.B.AfterUpdate(nc) } func (nc *NotificationContent) AfterDelete() { bongo.B.AfterDelete(nc) } func NewNotificationContent() *NotificationContent { return &NotificationContent{} } func (n *NotificationContent) GetId() int64 { return n.Id } func (n NotificationContent) TableName() string { return "notification.notification_content" } // Create checks for NotificationContent using type_constant and target_id // and creates new one if it does not exist. func (n *NotificationContent) Create() error { if err := n.FindByTarget(); err != nil { if err != bongo.RecordNotFound { return err } return bongo.B.Create(n) } return nil } func (n *NotificationContent) One(q *bongo.Query) error { return bongo.B.One(n, n, q) } func (n *NotificationContent) ById(id int64) error { return bongo.B.ById(n, id) }
Add test for credentials reload
import json import keyring from pyutrack import Credentials from tests import PyutrackTest class CredentialsTests(PyutrackTest): def test_empty(self): c = Credentials('root') self.assertIsNone(c.password) self.assertIsNone(c.cookies) def test_persistence(self): c = Credentials('root', 'passwd', {"key": "value"}) c.persist() self.assertEqual( keyring.get_password(Credentials.KEYRING_PASSWORD, 'root'), 'passwd' ) self.assertEqual( json.loads(keyring.get_password(Credentials.KEYRING_COOKIE, 'root')), {"key": "value"} ) def test_reload(self): Credentials('root', 'passwd', {"key": "value"}).persist() c = Credentials('root') self.assertEqual( keyring.get_password(Credentials.KEYRING_PASSWORD, 'root'), 'passwd' ) self.assertEqual( json.loads(keyring.get_password(Credentials.KEYRING_COOKIE, 'root')), {"key": "value"} )
import json import keyring from pyutrack import Credentials from tests import PyutrackTest class CredentialsTests(PyutrackTest): def test_empty(self): c = Credentials('root') self.assertIsNone(c.password) self.assertIsNone(c.cookies) def test_persistence(self): c = Credentials('root', 'passwd', {"key": "value"}) c.persist() self.assertEqual( keyring.get_password(Credentials.KEYRING_PASSWORD, 'root'), 'passwd' ) self.assertEqual( json.loads(keyring.get_password(Credentials.KEYRING_COOKIE, 'root')), {"key": "value"} )
Docblocks: Update return values, explain what generateSecret() does
<?php namespace eien\Http\Controllers; use Illuminate\Http\Request; use ParagonIE\ConstantTime\Base32; use PragmaRX\Google2FA\Vendor\Laravel\Facade as Google2FA; class TFAController extends Controller { /** * @param Request $request * @return \Illuminate\View\View */ public function enable(Request $request) { $secret = $this->generateSecret(); $user = $request->user(); $user->twofa_secret = $secret; $user->save(); $qrUri = Google2FA::getQRCodeInline('永遠', $user->email, $secret); return view('TFA.enable', ['image' => $qrUri, 'secret' => $secret]); } /** * @param Request $request * @return \Illuminate\View\View */ public function disable(Request $request) { $user = $request->user(); $user->twofa_secret = null; $user->save(); return view('TFA.disable'); } /** * Generate a secure secret with the constant time library. * * @return string */ public function generateSecret() { $randomBytes = random_bytes(10); return Base32::encode($randomBytes); } }
<?php namespace eien\Http\Controllers; use Illuminate\Http\Request; use ParagonIE\ConstantTime\Base32; use PragmaRX\Google2FA\Vendor\Laravel\Facade as Google2FA; class TFAController extends Controller { /** * @param Request $request */ public function enable(Request $request) { $secret = $this->generateSecret(); $user = $request->user(); $user->twofa_secret = $secret; $user->save(); $qrUri = Google2FA::getQRCodeInline('永遠', $user->email, $secret); return view('TFA.enable', ['image' => $qrUri, 'secret' => $secret]); } /** * @param Request $request */ public function disable(Request $request) { $user = $request->user(); $user->twofa_secret = null; $user->save(); return view('TFA.disable'); } /** * @return string */ public function generateSecret() { $randomBytes = random_bytes(10); return Base32::encode($randomBytes); } }
Add ~/.python to PYTHONPATH and import rc
import vx import math import os import sys _tick_functions = [] def _register_tick_function(f, front=False): if front: _tick_functions.insert(0, f) else: _tick_functions.append(f) def _tick(): for f in _tick_functions: f() vx.my_vx = _tick vx.register_tick_function = _register_tick_function vx.files = sys.argv[1:] import utils import scheduler import keybindings import windows import prompt def _default_start(): if len(vx.files) == 0: win = vx.window(vx.rows, vx.cols, 0, 0) win.blank() win.focus() else: d = math.floor(vx.rows / (len(vx.files))) y = 0 for f in vx.files: win = vx.window(d, vx.cols, y, 0) win.attach_file(f) y += d win.focus() vx.default_start = _default_start sys.path.append(os.path.expanduser('~/.python')) import rc
import vx import math from sys import argv _tick_functions = [] def _register_tick_function(f, front=False): if front: _tick_functions.insert(0, f) else: _tick_functions.append(f) def _tick(): for f in _tick_functions: f() vx.my_vx = _tick vx.register_tick_function = _register_tick_function vx.files = argv[1:] import utils import scheduler import keybindings import windows import prompt def _default_start(): if len(vx.files) == 0: win = vx.window(vx.rows, vx.cols, 0, 0) win.blank() win.focus() else: d = math.floor(vx.rows / (len(vx.files))) y = 0 for f in vx.files: win = vx.window(d, vx.cols, y, 0) win.attach_file(f) y += d win.focus() vx.default_start = _default_start
Fix for PHP < 5 error
<?php # let people know if they are running an unsupported version of PHP if(phpversion() < 5) { echo '<h3>Stacey requires PHP/5.0 or higher.<br>You are currently running PHP/".phpversion().".</h3><p>You should contact your host to see if they can upgrade your version of PHP.</p>'; } else { # require helpers class so we can use rglob require_once './app/helpers.inc.php'; # include any php files which sit in the app folder foreach(Helpers::rglob('./app/**.inc.php') as $include) include_once $include; try { # try start the app new Stacey($_GET); } catch(Exception $e) { if($e->getMessage() == "404") { # return 404 headers header('HTTP/1.0 404 Not Found'); if(file_exists('./public/404.html')) echo file_get_contents('./public/404.html'); else echo '<h1>404</h1><h2>Page could not be found.</h2><p>Unfortunately, the page you were looking for does not exist here.</p>'; } else { echo '<h3>'.$e->getMessage().'</h3>'; } } } ?>
<?php # let people know if they are running an unsupported version of PHP if(phpversion() < 5) { echo '<h3>Stacey requires PHP/5.0 or higher.<br>You are currently running PHP/".phpversion().".</h3><p>You should contact your host to see if they can upgrade your version of PHP.</p>'; return; } # require helpers class so we can use rglob require_once './app/helpers.inc.php'; # include any php files which sit in the app folder foreach(Helpers::rglob('./app/**.inc.php') as $include) include_once $include; try { # try start the app new Stacey($_GET); } catch(Exception $e) { if($e->getMessage() == "404") { # return 404 headers header('HTTP/1.0 404 Not Found'); if(file_exists('./public/404.html')) echo file_get_contents('./public/404.html'); else echo '<h1>404</h1><h2>Page could not be found.</h2><p>Unfortunately, the page you were looking for does not exist here.</p>'; } else { echo '<h3>'.$e->getMessage().'</h3>'; } } ?>
Add pako as a webpack external dependency
var webpack = require('webpack'), path = require('path'), yargs = require('yargs'); var libraryName = 'hdrhistogram', plugins = [], outputFile; if (yargs.argv.p) { plugins.push(new webpack.optimize.UglifyJsPlugin({ minimize: true })); outputFile = libraryName + '.min.js'; } else { outputFile = libraryName + '.js'; } var config = { entry: [ __dirname + '/src/index.ts' ], devtool: 'source-map', output: { path: path.join(__dirname, '/dist'), filename: outputFile, library: libraryName, libraryTarget: 'umd', umdNamedDefine: true }, module: { loaders: [ { test: /\.tsx?$/, loader: 'ts', exclude: /node_modules/ } ] }, resolve: { root: path.resolve('./src'), extensions: [ '', '.js', '.ts', '.jsx', '.tsx' ] }, externals: { "pako": "pako", "pako/lib/deflate": "pako", "pako/lib/inflate": "pako" }, plugins: plugins }; module.exports = config;
var webpack = require('webpack'), path = require('path'), yargs = require('yargs'); var libraryName = 'hdrhistogram', plugins = [], outputFile; if (yargs.argv.p) { //plugins.push(new webpack.optimize.UglifyJsPlugin({ minimize: true })); outputFile = libraryName + '.min.js'; } else { outputFile = libraryName + '.js'; } var config = { entry: [ __dirname + '/src/index.ts' ], devtool: 'source-map', output: { path: path.join(__dirname, '/dist'), filename: outputFile, library: libraryName, libraryTarget: 'umd', umdNamedDefine: true }, module: { loaders: [ { test: /\.tsx?$/, loader: 'ts', exclude: /node_modules/ } ] }, resolve: { root: path.resolve('./src'), extensions: [ '', '.js', '.ts', '.jsx', '.tsx' ] }, plugins: plugins }; module.exports = config;
Fix license header to use BSD
/** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule setTextContent */ 'use strict'; var ExecutionEnvironment = require('ExecutionEnvironment'); var escapeTextContentForBrowser = require('escapeTextContentForBrowser'); var setInnerHTML = require('setInnerHTML'); /** * Set the textContent property of a node, ensuring that whitespace is preserved * even in IE8. innerText is a poor substitute for textContent and, among many * issues, inserts <br> instead of the literal newline chars. innerHTML behaves * as it should. * * @param {DOMElement} node * @param {string} text * @internal */ var setTextContent = function(node, text) { node.textContent = text; }; if (ExecutionEnvironment.canUseDOM) { if (!('textContent' in document.documentElement)) { setTextContent = function(node, text) { setInnerHTML(node, escapeTextContentForBrowser(text)); }; } } module.exports = setTextContent;
/** * Copyright 2013-2014 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. * * @providesModule setTextContent */ 'use strict'; var ExecutionEnvironment = require('ExecutionEnvironment'); var escapeTextContentForBrowser = require('escapeTextContentForBrowser'); var setInnerHTML = require('setInnerHTML'); /** * Set the textContent property of a node, ensuring that whitespace is preserved * even in IE8. innerText is a poor substitute for textContent and, among many * issues, inserts <br> instead of the literal newline chars. innerHTML behaves * as it should. * * @param {DOMElement} node * @param {string} text * @internal */ var setTextContent = function(node, text) { node.textContent = text; }; if (ExecutionEnvironment.canUseDOM) { if (!('textContent' in document.documentElement)) { setTextContent = function(node, text) { setInnerHTML(node, escapeTextContentForBrowser(text)); }; } } module.exports = setTextContent;
Use node7's async and await methods
#!/usr/bin/env node --harmony var program = require('commander'); var fetch = require('node-fetch'); var base64 = require('base-64'); program .arguments('<uri>') .version('0.0.2') .description('A command line tool to retrieve that URI to the latest artifact from an Artifactory repo') .option('-u, --username <username>', 'The user to authenticate as') .option('-p, --password <password>', 'The user\'s password') .action(function (uri) { const { username, password } = program; console.log('user: %s \npass: %s \nuri: %s', program.username, program.password, uri); fetchArtifactList(uri, username, password) .then(json => { console.log(JSON.stringify(json, null, 2)); }); }) .parse(process.argv); async function fetchArtifactList(uri, username, password) { const response = await fetch(uri, { method: 'get', headers: { 'Authorization': 'Basic ' + base64.encode(username + ':' + password) }, }); return await response.json(); }
#!/usr/bin/env node --harmony var program = require('commander'); var fetch = require('node-fetch'); var base64 = require('base-64'); program .arguments('<uri>') .version('0.0.2') .description('A command line tool to retrieve that URI to the latest artifact from an Artifactory repo') .option('-u, --username <username>', 'The user to authenticate as') .option('-p, --password <password>', 'The user\'s password') .action(function (uri) { const { username, password } = program; console.log('user: %s pass: %s uri: %s', program.username, program.password, uri); fetch(uri, { method: 'get', headers: { 'Authorization': 'Basic ' + base64.encode(username + ':' + password) }, }) .then(res => res.json()) .then(json => console.log(json)) .catch(err => console.error(err)); }) .parse(process.argv);
Add redux devtools to generator
import React from 'react' import {combineReducers, createStore, applyMiddleware, compose} from 'redux' import thunk from 'redux-thunk' import { Provider } from 'react-redux' import { render } from 'react-dom' import createHistory from 'history/createBrowserHistory' import Breezy from '@jho406/breezy' // Mapping between your props template to Component // e.g {'posts/new': PostNew} const screenToComponentMapping = { } const history = createHistory({}) const initialPage = window.BREEZY_INITIAL_PAGE_STATE const baseUrl = '' //The Nav is pretty bare bones //Feel free to replace the implementation const {reducer, initialState, Nav, connect} = Breezy.start({ window, initialPage, baseUrl, history }) const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose const store = createStore( combineReducers({ ...reducer, }), initialState, composeEnhancers(applyMiddleware(thunk)) ) connect(store) class App extends React.Component { render() { return <Provider store={store}> <Nav mapping={this.props.mapping}/> </Provider> } } document.addEventListener("DOMContentLoaded", function() { render(<App mapping={screenToComponentMapping}/>, document.getElementById('app')) })
import React from 'react' import {combineReducers, createStore, applyMiddleware} from 'redux' import thunk from 'redux-thunk' import { Provider } from 'react-redux' import { render } from 'react-dom' import createHistory from 'history/createBrowserHistory' import Breezy from '@jho406/breezy' // Mapping between your props template to Component // e.g {'posts/new': PostNew} const screenToComponentMapping = { } const history = createHistory({}) const initialPage = window.BREEZY_INITIAL_PAGE_STATE const baseUrl = '' //The Nav is pretty bare bones //Feel free to replace the implementation const {reducer, initialState, Nav, connect} = Breezy.start({ window, initialPage, baseUrl, history }) const store = createStore( combineReducers({ ...reducer, }), initialState, applyMiddleware(thunk) ) connect(store) class App extends React.Component { render() { return <Provider store={store}> <Nav mapping={this.props.mapping}/> </Provider> } } document.addEventListener("DOMContentLoaded", function() { render(<App mapping={screenToComponentMapping}/>, document.getElementById('app')) })
Remove code available in upstream. Signed-off-by: Mior Muhammad Zaki <e1a543840a942eb68427510a8a483282a7bfeddf@gmail.com>
<?php namespace Orchestra\View; use Illuminate\Support\Collection; use Illuminate\View\FileViewFinder as LaravelViewFinder; class FileViewFinder extends LaravelViewFinder { const HINT_PATH_DELIMITER = '::'; /** * {@inheritdoc} */ protected function findNamespacedView($name) { [$namespace, $view] = $this->parseNamespaceSegments($name); // Prepend global view paths to namespace hints path. This would // allow theme to take priority if such view exist. return $this->findInPaths($view, Collection::make($this->paths)->map(static function ($path) use ($namespace) { return "{$path}/packages/{$namespace}"; })->merge($this->hints[$namespace])->all()); } }
<?php namespace Orchestra\View; use Illuminate\Support\Collection; use Illuminate\View\FileViewFinder as LaravelViewFinder; class FileViewFinder extends LaravelViewFinder { const HINT_PATH_DELIMITER = '::'; /** * {@inheritdoc} */ protected function findNamespacedView($name) { [$namespace, $view] = $this->parseNamespaceSegments($name); // Prepend global view paths to namespace hints path. This would // allow theme to take priority if such view exist. return $this->findInPaths($view, Collection::make($this->paths)->map(static function ($path) use ($namespace) { return "{$path}/packages/{$namespace}"; })->merge($this->hints[$namespace])->all()); } /** * Set the active view paths. * * @param array $paths * * @return $this */ public function setPaths($paths) { $this->paths = $paths; return $this; } }
Add array constructor to polygon
package me.itszooti.geojson; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class GeoPolygon extends GeoGeometry { private List<GeoPosition> exterior; private List<List<GeoPosition>> interiors; public GeoPolygon(List<GeoPosition> exterior) { this.exterior = new ArrayList<GeoPosition>(exterior); this.interiors = new ArrayList<List<GeoPosition>>(); } public GeoPolygon(List<GeoPosition> exterior, List<List<GeoPosition>> interiors) { this(exterior); for (List<GeoPosition> interior : interiors) { this.interiors.add(new ArrayList<GeoPosition>(interior)); } } public GeoPolygon(GeoPosition[] exterior) { this(Arrays.asList(exterior)); } public GeoPolygon(GeoPosition[] exterior, GeoPosition[][] interiors) { this(Arrays.asList(exterior)); for (int i = 0; i < interiors.length; i++) { this.interiors.add(Arrays.asList(interiors[i])); } } public int getNumInteriors() { return interiors.size(); } public GeoPosition[] getInterior(int index) { List<GeoPosition> interior = interiors.get(index); return interior.toArray(new GeoPosition[interior.size()]); } public GeoPosition[] getExterior() { return exterior.toArray(new GeoPosition[exterior.size()]); } }
package me.itszooti.geojson; import java.util.ArrayList; import java.util.List; public class GeoPolygon extends GeoGeometry { private List<GeoPosition> exterior; private List<List<GeoPosition>> interiors; public GeoPolygon(List<GeoPosition> exterior) { this.exterior = new ArrayList<GeoPosition>(exterior); this.interiors = new ArrayList<List<GeoPosition>>(); } public GeoPolygon(List<GeoPosition> exterior, List<List<GeoPosition>> interiors) { this(exterior); for (List<GeoPosition> interior : interiors) { this.interiors.add(new ArrayList<GeoPosition>(interior)); } } public int getNumInteriors() { return interiors.size(); } public GeoPosition[] getInterior(int index) { List<GeoPosition> interior = interiors.get(index); return interior.toArray(new GeoPosition[interior.size()]); } public GeoPosition[] getExterior() { return exterior.toArray(new GeoPosition[exterior.size()]); } }
Trim last added new line
'use strict'; var path = require('path') , common = require('path2/common') , defaultReadFile = require('fs2/read-file') , cssAid = require('css-aid') , dirname = path.dirname, resolve = path.resolve; module.exports = function (indexPath, readFile) { var rootPath, indexDir; if (!readFile) readFile = defaultReadFile; indexPath = resolve(indexPath); indexDir = dirname(indexPath); return readFile(indexPath, 'utf8')(function (content) { var filenames = content.trim().split('\n').filter(Boolean).map(function (name) { return resolve(indexDir, name); }); rootPath = common.apply(null, filenames); return filenames; }).map(function (filename) { return readFile(filename, 'utf8')(function (content) { return { filename: filename.slice(rootPath.length + 1), content: content }; }); })(function (data) { return cssAid(data.reduce(function (content, data) { return content + '/* ' + data.filename + ' */\n\n' + data.content + '\n'; }, '').slice(0, -1)); }); };
'use strict'; var path = require('path') , common = require('path2/common') , defaultReadFile = require('fs2/read-file') , cssAid = require('css-aid') , dirname = path.dirname, resolve = path.resolve; module.exports = function (indexPath, readFile) { var rootPath, indexDir; if (!readFile) readFile = defaultReadFile; indexPath = resolve(indexPath); indexDir = dirname(indexPath); return readFile(indexPath, 'utf8')(function (content) { var filenames = content.trim().split('\n').filter(Boolean).map(function (name) { return resolve(indexDir, name); }); rootPath = common.apply(null, filenames); return filenames; }).map(function (filename) { return readFile(filename, 'utf8')(function (content) { return { filename: filename.slice(rootPath.length + 1), content: content }; }); })(function (data) { return cssAid(data.reduce(function (content, data) { return content + '/* ' + data.filename + ' */\n\n' + data.content + '\n'; }, '')); }); };
Fix for lazy loading of request.user
from django.http import Http404 from django.contrib.auth import get_user_model from django.shortcuts import render, get_object_or_404 from django.utils.translation import ugettext as _ from django.views.generic import ListView, edit from .models import Message class MessageList(ListView): template_name = "message_list.html" model = Message class MyMessageList(MessageList): def get_queryset(self): queryset = super().get_queryset() return queryset.filter(user_id=self.request.user.id) class FilteredMessageList(MessageList): def get_queryset(self): # Check to see if user exists. 404 if not. username = self.kwargs.get('username') user = get_object_or_404(get_user_model(), username=username) # Filter messages by the user as author. queryset = super().get_queryset() return queryset.filter(user=user) class CreateMessage(edit.CreateView): model = Message fields = ['text'] template_name = "message_form.html" def form_valid(self, form): obj = form.save(commit=False) obj.user = self.request.user obj.save() return super().form_valid(form)
from django.http import Http404 from django.contrib.auth import get_user_model from django.shortcuts import render, get_object_or_404 from django.utils.translation import ugettext as _ from django.views.generic import ListView, edit from .models import Message class MessageList(ListView): template_name = "message_list.html" model = Message class MyMessageList(MessageList): def get_queryset(self): queryset = super().get_queryset() return queryset.filter(user=self.request.user) class FilteredMessageList(MessageList): def get_queryset(self): # Check to see if user exists. 404 if not. username = self.kwargs.get('username') user = get_object_or_404(get_user_model(), username=username) # Filter messages by the user as author. queryset = super().get_queryset() return queryset.filter(user=user) class CreateMessage(edit.CreateView): model = Message fields = ['text'] template_name = "message_form.html" def form_valid(self, form): obj = form.save(commit=False) obj.user = self.request.user obj.save() return super().form_valid(form)
feat: Add skin to User model.
const bcrypt = require('bcryptjs'); const Sequelize = require('sequelize'); const db = require('../index'); const User = db.define('users', { name: Sequelize.STRING, displayName: Sequelize.STRING, skin: Sequelize.STRING, email: { type: Sequelize.STRING, validate: { isEmail: true, notEmpty: true } }, // For Google OAuth googleId: Sequelize.STRING, // OAuth -> users may or may not have passwords. password_digest: Sequelize.STRING, password: Sequelize.VIRTUAL }, { indexes: [{ fields: ['email'], unique: true }], hooks: { beforeCreate: setEmailAndPassword, beforeUpdate: setEmailAndPassword }, instanceMethods: { authenticate (plaintext) { return new Promise((resolve, reject) => bcrypt.compare(plaintext, this.password_digest, (err, result) => err ? reject(err) : resolve(result)) ); } } }); function setEmailAndPassword (user) { user.email = user.email && user.email.toLowerCase(); if (!user.password) return Promise.resolve(user); return new Promise((resolve, reject) => bcrypt.hash(user.get('password'), 10, (err, hash) => { if (err) reject(err); user.set('password_digest', hash); resolve(user); }) ); } module.exports = User;
const bcrypt = require('bcryptjs'); const Sequelize = require('sequelize'); const db = require('../index'); const User = db.define('users', { name: Sequelize.STRING, displayName: Sequelize.STRING, email: { type: Sequelize.STRING, validate: { isEmail: true, notEmpty: true } }, // For Google OAuth googleId: Sequelize.STRING, // OAuth -> users may or may not have passwords. password_digest: Sequelize.STRING, password: Sequelize.VIRTUAL }, { indexes: [{ fields: ['email'], unique: true }], hooks: { beforeCreate: setEmailAndPassword, beforeUpdate: setEmailAndPassword }, instanceMethods: { authenticate (plaintext) { return new Promise((resolve, reject) => bcrypt.compare(plaintext, this.password_digest, (err, result) => err ? reject(err) : resolve(result)) ); } } }); function setEmailAndPassword (user) { user.email = user.email && user.email.toLowerCase(); if (!user.password) return Promise.resolve(user); return new Promise((resolve, reject) => bcrypt.hash(user.get('password'), 10, (err, hash) => { if (err) reject(err); user.set('password_digest', hash); resolve(user); }) ); } module.exports = User;
Make boolean checkbox looks great on Firefox.
import React from 'react'; const styles = { display: 'table-cell', boxSizing: 'border-box', verticalAlign: 'top', height: 21, outline: 'none', border: '1px solid #ececec', fontSize: '12px', color: '#555', }; class BooleanType extends React.Component { render() { const { knob, onChange } = this.props; return ( <input id={knob.name} ref="input" style={styles} type="checkbox" onChange={() => onChange(this.refs.input.checked)} checked={knob.value} /> ); } } BooleanType.propTypes = { knob: React.PropTypes.object, onChange: React.PropTypes.func, }; BooleanType.serialize = function (value) { return String(value); }; BooleanType.deserialize = function (value) { if (!value) return false; return value.trim() === 'true'; }; export default BooleanType;
import React from 'react'; const styles = { display: 'table-cell', boxSizing: 'border-box', verticalAlign: 'top', height: 21, width: '100%', outline: 'none', border: '1px solid #ececec', fontSize: '12px', color: '#555', }; class BooleanType extends React.Component { render() { const { knob, onChange } = this.props; return ( <input id={knob.name} ref="input" style={styles} type="checkbox" onChange={() => onChange(this.refs.input.checked)} checked={knob.value} /> ); } } BooleanType.propTypes = { knob: React.PropTypes.object, onChange: React.PropTypes.func, }; BooleanType.serialize = function (value) { return String(value); }; BooleanType.deserialize = function (value) { if (!value) return false; return value.trim() === 'true'; }; export default BooleanType;
Use buffered channel so that all crawlers get a chance to execute
package main import ( "fmt" "github.com/nitishparkar/muffliato/crawler" "io/ioutil" "strings" ) const sitesFile string = "sites.txt" func main() { data, err := ioutil.ReadFile(sitesFile) if err != nil { panic(err) } sites := strings.Split(string(data), "\n") validSites := make([]string, 0) for _, site := range sites { t := strings.TrimSpace(site) if t != "" { validSites = append(validSites, t) } } done := make(chan bool, len(validSites)) for _, site := range validSites { go func(site string) { crawler := crawler.NewCrawler(site) crawler.Crawl() done <- true }(site) } for _ = range done { } fmt.Println("Exiting") }
package main import ( "fmt" "github.com/nitishparkar/muffliato/crawler" "io/ioutil" "strings" ) const sitesFile string = "sites.txt" func main() { data, err := ioutil.ReadFile(sitesFile) if err != nil { panic(err) } sites := strings.Split(string(data), "\n") validSites := make([]string, 0) for _, site := range sites { t := strings.TrimSpace(site) if t != "" { validSites = append(validSites, t) } } done := make(chan bool) for _, site := range validSites { go func(site string) { crawler := crawler.NewCrawler(site) crawler.Crawl() done <- true }(site) } <-done fmt.Println("Exiting") }
CSPACE-649: Remove an extra comma that was causing IE to fail to load the page.
/* Copyright 2009 University of Toronto Licensed under the Educational Community License (ECL), Version 2.0. ou may not use this file except in compliance with this License. You may obtain a copy of the ECL 2.0 License at https://source.collectionspace.org/collection-space/LICENSE.txt */ /*global jQuery, window, cspace*/ var demo = demo || {}; (function ($) { demo.setup = function () { var csid = cspace.util.getUrlParameter("csid"); var isLocal = cspace.util.isLocal(); var oeOpts = { alternateFields: ["accessionNumber", "objectTitle"], uiSpecUrl: isLocal ? "./schemas/collection-object/schema.json" : "../../chain/objects/schema" }; if (csid) { oeOpts.csid = csid; } if (isLocal) { oeOpts.dataContext = cspace.util.setupTestDataContext("collection-object"); } var objEntry = cspace.dataEntry(".csc-object-entry-container", oeOpts); }; })(jQuery);
/* Copyright 2009 University of Toronto Licensed under the Educational Community License (ECL), Version 2.0. ou may not use this file except in compliance with this License. You may obtain a copy of the ECL 2.0 License at https://source.collectionspace.org/collection-space/LICENSE.txt */ /*global jQuery, window, cspace*/ var demo = demo || {}; (function ($) { demo.setup = function () { var csid = cspace.util.getUrlParameter("csid"); var isLocal = cspace.util.isLocal(); var oeOpts = { alternateFields: ["accessionNumber", "objectTitle"], uiSpecUrl: isLocal ? "./schemas/collection-object/schema.json" : "../../chain/objects/schema", }; if (csid) { oeOpts.csid = csid; } if (isLocal) { oeOpts.dataContext = cspace.util.setupTestDataContext("collection-object"); } var objEntry = cspace.dataEntry(".csc-object-entry-container", oeOpts); }; })(jQuery);
Add success=true to satisfy Ext
from base64 import b64encode import os.path import re from pyramid.httpexceptions import HTTPBadRequest from pyramid.response import Response from pyramid.view import view_config def json_base64_encode_chunks(file, chunk_size=65536): """ Generate a JSON-wrapped base64-encoded string. See http://en.wikipedia.org/wiki/Base64 """ yield '{"data":"' while True: line = file.read(chunk_size) if not line: break yield b64encode(line) yield '","success":true}' @view_config(route_name='echo') def echo(request): """ Echo an uploaded file back to the client as an text/html document so it can be handled by Ext. The response is JSON-wrapped and base64-encoded to ensure that there are no special HTML characters or charset problems and so that braindead ext doesn't barf on it. We use an iterator to avoid loading the whole file into memory. See http://docs.sencha.com/ext-js/3-4/#!/api/Ext.form.BasicForm-cfg-fileUpload """ if request.method != 'POST': raise HTTPBadRequest() try: file = request.POST['file'] except KeyError: raise HTTPBadRequest() response = Response() response.app_iter = json_base64_encode_chunks(file.file) response.content_type = 'text/html' return response
from base64 import b64encode import os.path import re from pyramid.httpexceptions import HTTPBadRequest from pyramid.response import Response from pyramid.view import view_config def json_base64_encode_chunks(file, chunk_size=65536): """ Generate a JSON-wrapped base64-encoded string. See http://en.wikipedia.org/wiki/Base64 """ yield '{"data":"' while True: line = file.read(chunk_size) if not line: break yield b64encode(line) yield '"}' @view_config(route_name='echo') def echo(request): """ Echo an uploaded file back to the client as an text/html document so it can be handled by Ext. The response is JSON-wrapped and base64-encoded to ensure that there are no special HTML characters or charset problems and so that braindead ext doesn't barf on it. We use an iterator to avoid loading the whole file into memory. See http://docs.sencha.com/ext-js/3-4/#!/api/Ext.form.BasicForm-cfg-fileUpload """ if request.method != 'POST': raise HTTPBadRequest() try: file = request.POST['file'] except KeyError: raise HTTPBadRequest() response = Response() response.app_iter = json_base64_encode_chunks(file.file) response.content_type = 'text/html' return response
Add cookieParser and session to express setup
var path = require('path'), express = require('express'), http = require('http'), mongoose = require('mongoose'), config = require('./config'); var app = express(); // Configuration app.configure(function(){ app.set('views', __dirname + '/views'); app.set('view engine', 'jade'); app.set('view options', { layout: false }); app.use(express.logger()); app.use(express.bodyParser()); app.use(express.methodOverride()); app.use(express.cookieParser('your secret here')); app.use(express.session()); app.use(app.router); app.use(express.static(path.join(__dirname, 'public'))); }); app.configure('development', function(){ app.use(express.errorHandler({ dumpExceptions: true, showStack: true })); }); app.configure('production', function(){ app.use(express.errorHandler()); }); mongoose.connect(config.db.url); require('./helpers')(app); require('./routes')(app); http.createServer(app).listen(config.port, config.address, function() { console.log("Express server listening on %s:%d in %s mode", config.address, config.port, app.settings.env); });
var path = require('path'), express = require('express'), http = require('http'), mongoose = require('mongoose'), config = require('./config'); var app = express(); // Configuration app.configure(function(){ app.set('views', __dirname + '/views'); app.set('view engine', 'jade'); app.set('view options', { layout: false }); app.use(express.logger()); app.use(express.bodyParser()); app.use(express.methodOverride()); app.use(app.router); app.use(express.static(path.join(__dirname, 'public'))); }); app.configure('development', function(){ app.use(express.errorHandler({ dumpExceptions: true, showStack: true })); }); app.configure('production', function(){ app.use(express.errorHandler()); }); mongoose.connect(config.db.url); require('./helpers')(app); require('./routes')(app); http.createServer(app).listen(config.port, config.address, function() { console.log("Express server listening on %s:%d in %s mode", config.address, config.port, app.settings.env); });
Update get e post for mongoose
var express = require('express'), mongoose = require('mongoose'); var Schema = mongoose.Schema; var db = mongoose.connect('mongodb://127.0.0.1:27017/bookApi'); var Book = require('./models/bookModel'); var app = express(); var port = process.env.PORT || 3000; var bookRouter = express.Router(); bookRouter.route('/books') .get(function(req,res){ Book.find({},function(err,books){ console.log("aki"); if(err) res.status(500).send(err); else res.json(books); }); }); bookRouter.route('/books') .post(function(req,res){ Book.create(req.body,function(err,books){ if(err) res.status(500).send(err); else res.json(books); }); }); app.use('/api', bookRouter); app.get('/',function(req,res){ res.send('Welcome to API'); }); app.listen(port, function(){ console.log('Running on port' + port); });
var express = require('express'), mongoose = require('mongoose'); var db = mongoose.connect('mongodb://192.168.88.103:27017/bookApi'); var Book = require('./models/bookModel'); var app = express(); var port = process.env.PORT || 3000; var bookRouter = express.Router(); bookRouter.route('/books') .get(function(req,res){ Book.find(function(err,books){ if(err) res.status(500).send(err); else res.json(books) }); }); app.use('/api', bookRouter); app.get('/',function(req,res){ res.send('Welcome to API'); }); app.listen(port, function(){ console.log('Running on port' + port); });
Fix ce firsttime visit page
<?php namespace App\Http\Middleware; use Closure; use DB; use Session; use Route; use Request; use Redirect; use EtuUTT; class Dashboard { /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, Closure $next) { if (!EtuUTT::isAuth()) { return Redirect::route('index'); } else if (!EtuUTT::student()->volunteer && Request::route()->getName() != 'dashboard.students.profil' && Request::route()->getName() != 'dashboard.students.profil.submit' && Request::route()->getName() != 'dashboard.ce.firsttime') { return Redirect::route('dashboard.students.profil')->withError('Veuillez remplir ce formulaire pour continuer :)'); } return $next($request); } }
<?php namespace App\Http\Middleware; use Closure; use DB; use Session; use Route; use Request; use Redirect; use EtuUTT; class Dashboard { /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, Closure $next) { if (!EtuUTT::isAuth()) { return Redirect::route('index'); } else if (!EtuUTT::student()->volunteer && Request::route()->getName() != 'dashboard.students.profil' && Request::route()->getName() != 'dashboard.students.profil.submit') { return Redirect::route('dashboard.students.profil')->withError('Veuillez remplir ce formulaire pour continuer :)'); } return $next($request); } }
Use a sliding window to track acknowledged values.
package com.yahoo.ycsb.generator; import java.util.concurrent.locks.ReentrantLock; /** * A CounterGenerator that reports generated integers via lastInt() * only after they have been acknowledged. */ public class AcknowledgedCounterGenerator extends CounterGenerator { private static final int WINDOW_SIZE = 10000; private ReentrantLock lock; private boolean[] window; private int limit; /** * Create a counter that starts at countstart. */ public AcknowledgedCounterGenerator(int countstart) { super(countstart); lock = new ReentrantLock(); window = new boolean[WINDOW_SIZE]; limit = countstart - 1; } /** * In this generator, the highest acknowledged counter value * (as opposed to the highest generated counter value). */ @Override public int lastInt() { return limit; } /** * Make a generated counter value available via lastInt(). */ public void acknowledge(int value) { if (value > limit + WINDOW_SIZE) { throw new RuntimeException("This should be a different exception."); } window[value % WINDOW_SIZE] = true; if (lock.tryLock()) { // move a contiguous sequence from the window // over to the "limit" variable try { int index; for (index = limit + 1; index <= value; ++index) { int slot = index % WINDOW_SIZE; if (!window[slot]) { break; } window[slot] = false; } limit = index - 1; } finally { lock.unlock(); } } } }
package com.yahoo.ycsb.generator; import java.util.PriorityQueue; /** * A CounterGenerator that reports generated integers via lastInt() * only after they have been acknowledged. */ public class AcknowledgedCounterGenerator extends CounterGenerator { private PriorityQueue<Integer> ack; private int limit; /** * Create a counter that starts at countstart. */ public AcknowledgedCounterGenerator(int countstart) { super(countstart); ack = new PriorityQueue<Integer>(); limit = countstart - 1; } /** * In this generator, the highest acknowledged counter value * (as opposed to the highest generated counter value). */ @Override public int lastInt() { return limit; } /** * Make a generated counter value available via lastInt(). */ public synchronized void acknowledge(int value) { ack.add(value); // move a contiguous sequence from the priority queue // over to the "limit" variable Integer min; while ((min = ack.peek()) != null && min == limit + 1) { limit = ack.poll(); } } }
Set convenient .from method in address
package io.scalecube.services.api; import java.util.Objects; public class Address { private final String host; private final int port; private Address(String host, int port) { this.host = host; this.port = port; } /** * Create address. * * @param host host * @param port port * @return address */ public static Address create(String host, int port) { return new Address(host, port); } /** * Create address. * * @param hostAndPort host:port * @return address */ public static Address from(String hostAndPort) { String[] split = hostAndPort.split(":"); if (split.length != 2) { throw new IllegalArgumentException(); } String host = split[0]; int port = Integer.parseInt(split[1]); return new Address(host, port); } public String host() { return this.host; } public int port() { return this.port; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Address address = (Address) o; return port == address.port && Objects.equals(host, address.host); } @Override public int hashCode() { return Objects.hash(host, port); } @Override public String toString() { return this.host + ":" + this.port; } }
package io.scalecube.services.api; import java.util.Objects; public class Address { private final String host; private final int port; public static Address create(String host, int port) { return new Address(host, port); } private Address(String host, int port) { this.host = host; this.port = port; } public String host() { return this.host; } public int port() { return this.port; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Address address = (Address) o; return port == address.port && Objects.equals(host, address.host); } @Override public int hashCode() { return Objects.hash(host, port); } @Override public String toString() { return this.host + ":" + this.port; } }
Set version number to 0.6.2.
from setuptools import setup setup( name='slacker', version='0.6.2', packages=['slacker'], description='Slack API client', author='Oktay Sancak', author_email='oktaysancak@gmail.com', url='http://github.com/os/slacker/', install_requires=['requests >= 2.2.1'], license='http://www.apache.org/licenses/LICENSE-2.0', test_suite='tests', classifiers=( 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache Software License', 'Natural Language :: English', 'Programming Language :: Python', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4' ), keywords='slack api' )
from setuptools import setup setup( name='slacker', version='0.6.1', packages=['slacker'], description='Slack API client', author='Oktay Sancak', author_email='oktaysancak@gmail.com', url='http://github.com/os/slacker/', install_requires=['requests >= 2.2.1'], license='http://www.apache.org/licenses/LICENSE-2.0', test_suite='tests', classifiers=( 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache Software License', 'Natural Language :: English', 'Programming Language :: Python', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4' ), keywords='slack api' )
Add percentage value to points points contained their ending % position and original decimal value however did not contain a percentage value from the total of the series, this has been added.
// @flow import type Series from '../series/Series'; type Config = { key: string }; export default function normalizeToPercentage(config: Config) { const {key} = config; return (series: Series) => { series.preprocess.normalizeToPercentage = true; series.preprocess.stacked = true; series.preprocess.stackType = 'points'; const next = series.mapPoints((point) => { const total = point.reduce((rr, point) => rr + (point[key] || 0), 0); let sum = 0; const nextPoints = point.map(point => { let next = Object.assign({}, point); next.originalValue = next[key]; next.percentValue = ((next[key] || 0) / total); sum += (next[key] || 0); next[key] = sum / total; return next; }); return nextPoints; }); return next; }; }
// @flow import type Series from '../series/Series'; type Config = { key: string }; export default function normalizeToPercentage(config: Config) { const {key} = config; return (series: Series) => { series.preprocess.normalizeToPercentage = true; series.preprocess.stacked = true; series.preprocess.stackType = 'points'; const next = series.mapPoints((point) => { const total = point.reduce((rr, point) => rr + (point[key] || 0), 0); let sum = 0; const nextPoints = point.map(point => { let next = Object.assign({}, point); next.originalValue = next[key]; sum += (next[key] || 0); next[key] = sum / total; return next; }); return nextPoints; }); return next; }; }
[Validator] Allow DateTime objects as valid DateTimes
<?php namespace Symfony\Component\Validator\Constraints; use Symfony\Component\Validator\Constraint; use Symfony\Component\Validator\ConstraintValidator; use Symfony\Component\Validator\Exception\UnexpectedTypeException; class DateTimeValidator extends ConstraintValidator { const PATTERN = '/^(\d{4})-(\d{2})-(\d{2}) (0[0-9]|1[0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])$/'; public function isValid($value, Constraint $constraint) { if ($value === null) { return true; } if ($value instanceof \DateTime) { return true; } if (!is_scalar($value) && !(is_object($value) && method_exists($value, '__toString()'))) { throw new UnexpectedTypeException($value, 'string'); } $value = (string)$value; if (!preg_match(self::PATTERN, $value, $matches)) { $this->setMessage($constraint->message, array('value' => $value)); return false; } return checkdate($matches[2], $matches[3], $matches[1]); } }
<?php namespace Symfony\Component\Validator\Constraints; use Symfony\Component\Validator\Constraint; use Symfony\Component\Validator\ConstraintValidator; use Symfony\Component\Validator\Exception\UnexpectedTypeException; class DateTimeValidator extends ConstraintValidator { const PATTERN = '/^(\d{4})-(\d{2})-(\d{2}) (0[0-9]|1[0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])$/'; public function isValid($value, Constraint $constraint) { if ($value === null) { return true; } if (!is_scalar($value) && !(is_object($value) && method_exists($value, '__toString()'))) { throw new UnexpectedTypeException($value, 'string'); } $value = (string)$value; if (!preg_match(self::PATTERN, $value, $matches)) { $this->setMessage($constraint->message, array('value' => $value)); return false; } return checkdate($matches[2], $matches[3], $matches[1]); } }
Update python version for better error handling
import grpc import hello_pb2 import hello_pb2_grpc def run(): channel = grpc.insecure_channel('localhost:50051') stub = hello_pb2_grpc.HelloServiceStub(channel) # ideally, you should have try catch block here too response = stub.SayHello(hello_pb2.HelloReq(Name='Euler')) print(response.Result) try: response = stub.SayHelloStrict(hello_pb2.HelloReq( Name='Leonhard Euler')) except grpc.RpcError as e: # ouch! # lets print the gRPC error message # which is "Length of `Name` cannot be more than 10 characters" print(e.details()) # lets access the error code, which is `INVALID_ARGUMENT` # `type` of `status_code` is `grpc.StatusCode` status_code = e.code() # should print `INVALID_ARGUMENT` print(status_code.name) # should print `(3, 'invalid argument')` print(status_code.value) # want to do some specific action based on the error? if grpc.StatusCode.INVALID_ARGUMENT == status_code: # do your stuff here pass else: print(response.Result) if __name__ == '__main__': run()
import grpc import hello_pb2 import hello_pb2_grpc def run(): channel = grpc.insecure_channel('localhost:50051') stub = hello_pb2_grpc.HelloServiceStub(channel) # ideally, you should have try catch block here too response = stub.SayHello(hello_pb2.HelloReq(Name='Euler')) print(response.Result) try: response = stub.SayHelloStrict(hello_pb2.HelloReq( Name='Leonhard Euler')) except grpc.RpcError as e: # ouch! # lets print the gRPC error message # which is "Length of `Name` cannot be more than 10 characters" print(e.details()) # lets access the error code, which is `INVALID_ARGUMENT` # `type` of `status_code` is `grpc.StatusCode` status_code = e.code() # should print `INVALID_ARGUMENT` print(status_code.name) # should print `(3, 'invalid argument')` print(status_code.value) else: print(response.Result) if __name__ == '__main__': run()
Add twitter API functionality test
""" Tests for TwitterSA These tests might be overkill, it's my first time messing around with unit tests. Jesse Mu """ import TwitterSA import unittest class TwitterSATestCase(unittest.TestCase): def setUp(self): TwitterSA.app.config['TESTING'] = True self.app = TwitterSA.app.test_client() def tearDown(self): pass def test_twitter_api(self): """Test to make sure the API is getting tweets""" tweets = TwitterSA.api.search(q='hello') assert tweets and len(tweets) def test_invalid_search_query(self): """Test for invalid search queries""" rv = self.app.get('/search?q=') assert 'Invalid search query' in rv.data rv = self.app.get('/search?nonsense=nonsense') assert 'Invalid search query' in rv.data def test_invalid_user_id(self): """Test for invalid user ids""" rv = self.app.get('/user?uid=') assert 'Invalid user id' in rv.data rv = self.app.get('/user?nonsense=nonsense') assert 'Invalid user id' in rv.data if __name__ == '__main__': unittest.main()
""" Tests for TwitterSA These tests might be overkill, it's my first time messing around with unit tests. Jesse Mu """ import TwitterSA import unittest class TwitterSATestCase(unittest.TestCase): def setUp(self): TwitterSA.app.config['TESTING'] = True self.app = TwitterSA.app.test_client() def tearDown(self): pass def test_invalid_search_query(self): """Test for invalid search queries""" rv = self.app.get('/search?q=') assert 'Invalid search query' in rv.data rv = self.app.get('/search?nonsense=nonsense') assert 'Invalid search query' in rv.data def test_invalid_user_id(self): """Test for invalid user ids""" rv = self.app.get('/user?uid=') assert 'Invalid user id' in rv.data rv = self.app.get('/user?nonsense=nonsense') assert 'Invalid user id' in rv.data if __name__ == '__main__': unittest.main()
Add more comments to the CasperJS test
/** * homepage.js - Homepage tests. */ var x = require('casper').selectXPath; casper.options.viewportSize = {width: 1920, height: 961}; casper.on('page.error', function(msg, trace) { this.echo('Error: ' + msg, 'ERROR'); for(var i=0; i<trace.length; i++) { var step = trace[i]; this.echo(' ' + step.file + ' (line ' + step.line + ')', 'ERROR'); } }); casper.on('remote.message', function(message) { this.echo('Message: ' + message); }); casper.test.begin('Tests homepage structure', function suite(test) { casper.start('http://web', function() { // This works because the title is set in the "parent" template. test.assertTitle("TestProject", "Title is correct"); casper.wait(2000); // This fails, I'm guessing because the h2 is only in the "child" template, // it seems that CasperJS doesn't render the angular2 app correctly // and the child route templates are not injected into the page correctly. test.assertVisible('h2'); }); casper.run(function() { test.done(); }); });
/** * homepage.js - Homepage tests. */ var x = require('casper').selectXPath; casper.options.viewportSize = {width: 1920, height: 961}; casper.on('page.error', function(msg, trace) { this.echo('Error: ' + msg, 'ERROR'); for(var i=0; i<trace.length; i++) { var step = trace[i]; this.echo(' ' + step.file + ' (line ' + step.line + ')', 'ERROR'); } }); casper.on('remote.message', function(message) { this.echo('Message: ' + message); }); casper.test.begin('Tests homepage structure', function suite(test) { casper.start('http://web', function() { test.assertTitle("TestProject", "Title is correct"); casper.wait(2000); test.assertVisible('h2'); }); casper.run(function() { test.done(); }); });
Add ACF options & split_content function
<?php use Dedato\SoluForce\Setup; /* ========================================================================== Timber Setup ========================================================================== */ if ( ! class_exists( 'Timber' ) ) { add_action( 'admin_notices', function() { echo '<div class="error"><p>Timber not activated. Make sure you activate the plugin in <a href="' . esc_url( admin_url( 'plugins.php#timber' ) ) . '">' . esc_url( admin_url( 'plugins.php' ) ) . '</a></p></div>'; } ); return; } Timber::$dirname = array('views'); class StarterSite extends TimberSite { function __construct() { add_filter( 'timber_context', array( $this, 'add_to_context' ) ); parent::__construct(); } function add_to_context( $context ) { $context['top_menu'] = new TimberMenu('top_navigation'); $context['main_menu'] = new TimberMenu('primary_navigation'); $context['footer_menu'] = new TimberMenu('footer_navigation'); $context['site'] = $this; $context['display_sidebar'] = Setup\display_sidebar(); $context['sidebar_primary'] = Timber::get_widgets('sidebar-primary'); $context['options'] = get_fields('option'); $context['split_content'] = TimberHelper::function_wrapper('Dedato\SoluForce\Extras\split_more_content'); return $context; } } new StarterSite();
<?php use Dedato\SoluForce\Setup; /* ========================================================================== Timber Setup ========================================================================== */ if ( ! class_exists( 'Timber' ) ) { add_action( 'admin_notices', function() { echo '<div class="error"><p>Timber not activated. Make sure you activate the plugin in <a href="' . esc_url( admin_url( 'plugins.php#timber' ) ) . '">' . esc_url( admin_url( 'plugins.php' ) ) . '</a></p></div>'; } ); return; } Timber::$dirname = array('views'); class StarterSite extends TimberSite { function __construct() { add_filter( 'timber_context', array( $this, 'add_to_context' ) ); parent::__construct(); } function add_to_context( $context ) { $context['top_menu'] = new TimberMenu('top_navigation'); $context['main_menu'] = new TimberMenu('primary_navigation'); $context['footer_menu'] = new TimberMenu('footer_navigation'); $context['site'] = $this; $context['display_sidebar'] = Setup\display_sidebar(); $context['sidebar_primary'] = Timber::get_widgets('sidebar-primary'); return $context; } } new StarterSite();
Add default 'size' and 'start' parameters
(function(){ 'use strict'; angular.module('events') .service('eventService', ['$q', '$http', '$filter', 'ApiUrl', EventService]); /** * Events DataService * Events embedded, hard-coded data model; acts asynchronously to simulate * remote data service call(s). * * @returns {{loadAll: Function}} * @constructor */ function EventService($q, $http, $filter, ApiUrl){ this.get = function(startDate, pageSize, pageStart) { var deferredEvents = $q.defer(); var isoStartDate = $filter('date')(startDate || new Date(),'yyyy-MM-ddTHH:mm:ss'); var config = { params: { size : pageSize || 50, start : pageStart || 0 } }; $http.get(ApiUrl.get() + 'startDate/' + isoStartDate + 'Z', config) .then(function(data) { deferredEvents.resolve(data); }, function(reason) { deferredEvents.reject(reason); }); return deferredEvents.promise; }; } })();
(function(){ 'use strict'; angular.module('events') .service('eventService', ['$q', '$http', '$filter', 'ApiUrl', EventService]); /** * Events DataService * Events embedded, hard-coded data model; acts asynchronously to simulate * remote data service call(s). * * @returns {{loadAll: Function}} * @constructor */ function EventService($q, $http, $filter, ApiUrl){ this.get = function(startDate) { var deferredEvents = $q.defer(); var isoStartDate = $filter('date')(startDate,'yyyy-MM-ddTHH:mm:ss'); $http.get(ApiUrl.get() + 'startDate/' + isoStartDate + 'Z') .then(function(data) { deferredEvents.resolve(data); }, function(reason) { deferredEvents.reject(reason); }); return deferredEvents.promise; }; } })();
Copy files and dirs recursively
const mix = require('laravel-mix'); const fs = require('fs'); mix.config.detectHotReloading() if (mix.config.hmr) { // There's a bug with Mix/copy plugin which prevents HMR from working: // https://github.com/JeffreyWay/laravel-mix/issues/150 console.log('In HMR mode. If assets are missing, Ctr+C and run `yarn dev` first.'); // Somehow public/hot isn't being removed by Mix. We'll handle it ourselves. process.on('SIGINT', () => { try { fs.unlinkSync(mix.config.publicPath + '/hot'); } catch (e) {} process.exit(); }); } else { mix.copy('resources/assets/img', 'public/img', false) .copy('node_modules/font-awesome/fonts', 'public/fonts', false); } mix.js('resources/assets/js/app.js', 'public/js') .sass('resources/assets/sass/app.scss', 'public/css'); if (mix.config.inProduction) { mix.version(); mix.disableNotifications(); }
const mix = require('laravel-mix'); const fs = require('fs'); mix.config.detectHotReloading() if (mix.config.hmr) { // There's a bug with Mix/copy plugin which prevents HMR from working: // https://github.com/JeffreyWay/laravel-mix/issues/150 console.log('In HMR mode. If assets are missing, Ctr+C and run `yarn dev` first.'); // Somehow public/hot isn't being removed by Mix. We'll handle it ourselves. process.on('SIGINT', () => { try { fs.unlinkSync(mix.config.publicPath + '/hot'); } catch (e) {} process.exit(); }); } else { mix.copy('resources/assets/img', 'public/img', false) .copy('node_modules/font-awesome/fonts', 'public/fonts'); } mix.js('resources/assets/js/app.js', 'public/js') .sass('resources/assets/sass/app.scss', 'public/css'); if (mix.config.inProduction) { mix.version(); mix.disableNotifications(); }
Fix the headers sent by the GitHub renderer.
from flask import abort, json import requests def render_content(text, gfm=False, context=None, username=None, password=None): """Renders the specified markup using the GitHub API.""" if gfm: url = 'https://api.github.com/markdown' data = {'text': text, 'mode': 'gfm'} if context: data['context'] = context data = json.dumps(data) headers = {'content-type': 'application/json'} else: url = 'https://api.github.com/markdown/raw' data = text headers = {'content-type': 'text/x-markdown'} auth = (username, password) if username else None r = requests.post(url, headers=headers, data=data, auth=auth) # Relay HTTP errors if r.status_code != 200: try: message = r.json()['message'] except: message = r.text abort(r.status_code, message) return r.text
from flask import abort, json import requests def render_content(text, gfm=False, context=None, username=None, password=None): """Renders the specified markup using the GitHub API.""" if gfm: url = 'https://api.github.com/markdown' data = {'text': text, 'mode': 'gfm'} if context: data['context'] = context data = json.dumps(data) else: url = 'https://api.github.com/markdown/raw' data = text headers = {'content-type': 'text/plain'} auth = (username, password) if username else None r = requests.post(url, headers=headers, data=data, auth=auth) # Relay HTTP errors if r.status_code != 200: try: message = r.json()['message'] except: message = r.text abort(r.status_code, message) return r.text
Load Segment in register method
<?php namespace CachetHQ\Segment; use Illuminate\Support\ServiceProvider; use Segment; class SegmentServiceProvider extends ServiceProvider { /** * Boot the service provider. * * @return void */ public function boot() { $this->package('cachethq/segment'); } /** * Register the service provider. * * @return void */ public function register() { $this->app['segment'] = $this->app->share(function(app) { /** * Load the Segment.io configuration. */ $writeKey = $this->app->config->get('segment::config.write_key'); return Segment::init($writeKey); }); } /** * Get the services provided by the provider. * * @return array */ public function provides() { return array(); } }
<?php namespace CachetHQ\Segment; use Illuminate\Support\ServiceProvider; use Segment; class SegmentServiceProvider extends ServiceProvider { /** * Boot the service provider. * * @return void */ public function boot() { $this->package('cachethq/segment'); /** * Load the Segment.io configuration. */ $writeKey = $this->app->config->get('segment::config.write_key'); Segment::init($writeKey); } /** * Register the service provider. * * @return void */ public function register() { // } /** * Get the services provided by the provider. * * @return array */ public function provides() { return array(); } }
Add back in running of extra tests
#!/usr/bin/env python import os import sys from unittest import defaultTestLoader, TextTestRunner, TestSuite TESTS = ('form', 'fields', 'validators', 'widgets', 'webob_wrapper', 'translations', 'ext_csrf', 'ext_i18n') def make_suite(prefix='', extra=()): tests = TESTS + extra test_names = list(prefix + x for x in tests) suite = TestSuite() suite.addTest(defaultTestLoader.loadTestsFromNames(test_names)) return suite def additional_tests(): """ This is called automatically by setup.py test """ return make_suite('tests.') def main(): extra_tests = tuple(x for x in sys.argv[1:] if '-' not in x) suite = make_suite('', extra_tests) sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))) runner = TextTestRunner(verbosity=(sys.argv.count('-v') - sys.argv.count('-q') + 1)) result = runner.run(suite) sys.exit(not result.wasSuccessful()) if __name__ == '__main__': main()
#!/usr/bin/env python import os import sys from unittest import defaultTestLoader, TextTestRunner, TestSuite TESTS = ('form', 'fields', 'validators', 'widgets', 'webob_wrapper', 'translations', 'ext_csrf', 'ext_i18n') def make_suite(prefix='', extra=()): tests = TESTS + extra test_names = list(prefix + x for x in tests) suite = TestSuite() suite.addTest(defaultTestLoader.loadTestsFromNames(test_names)) return suite def additional_tests(): """ This is called automatically by setup.py test """ return make_suite('tests.') def main(): extra_tests = tuple(x for x in sys.argv[1:] if '-' not in x) suite = make_suite('', ) sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))) runner = TextTestRunner(verbosity=(sys.argv.count('-v') - sys.argv.count('-q') + 1)) result = runner.run(suite) sys.exit(not result.wasSuccessful()) if __name__ == '__main__': main()
Fix a NPE in MobHealthDisplayUpdateTask Band aid for broken isValid() function. Fixes #1396
package com.gmail.nossr50.runnables; import org.bukkit.entity.LivingEntity; import org.bukkit.scheduler.BukkitRunnable; import com.gmail.nossr50.mcMMO; public class MobHealthDisplayUpdaterTask extends BukkitRunnable { private LivingEntity target; private String oldName; private boolean oldNameVisible; public MobHealthDisplayUpdaterTask(LivingEntity target) { if (target.isValid()) { this.target = target; this.oldName = target.getMetadata(mcMMO.customNameKey).get(0).asString(); this.oldNameVisible = target.getMetadata(mcMMO.customVisibleKey).get(0).asBoolean(); } } @Override public void run() { if (target != null && target.isValid()) { target.setCustomNameVisible(oldNameVisible); target.setCustomName(oldName); target.removeMetadata(mcMMO.customNameKey, mcMMO.p); target.removeMetadata(mcMMO.customVisibleKey, mcMMO.p); } } }
package com.gmail.nossr50.runnables; import org.bukkit.entity.LivingEntity; import org.bukkit.scheduler.BukkitRunnable; import com.gmail.nossr50.mcMMO; public class MobHealthDisplayUpdaterTask extends BukkitRunnable { private LivingEntity target; private String oldName; private boolean oldNameVisible; public MobHealthDisplayUpdaterTask(LivingEntity target) { if (target.isValid()) { this.target = target; this.oldName = target.getMetadata(mcMMO.customNameKey).get(0).asString(); this.oldNameVisible = target.getMetadata(mcMMO.customVisibleKey).get(0).asBoolean(); } } @Override public void run() { if (target.isValid()) { target.setCustomNameVisible(oldNameVisible); target.setCustomName(oldName); target.removeMetadata(mcMMO.customNameKey, mcMMO.p); target.removeMetadata(mcMMO.customVisibleKey, mcMMO.p); } } }
Change title from mwSnapshots to Snapshots
<?php // BaseTool & Localization require_once( __DIR__ . '/lib/basetool/InitTool.php' ); require_once( KR_TSINT_START_INC ); // Class for this tool require_once( __DIR__ . '/class.php' ); $kgTool = new KrMwSnapshots(); $I18N = new TsIntuition( 'Mwsnapshots' ); $toolConfig = array( 'displayTitle' => 'Snapshots', 'krinklePrefix' => false, 'remoteBasePath' => dirname( $kgConf->getRemoteBase() ). '/', 'revisionId' => '0.1.2', 'styles' => array( 'main.css', ), 'scripts' => array( 'main.js', ), ); // Local settings require_once( __DIR__ . '/local.php' ); $kgBaseTool = BaseTool::newFromArray( $toolConfig ); $kgBaseTool->setSourceInfoGithub( 'Krinkle', 'ts-krinkle-mwSnapshots', __DIR__ );
<?php // BaseTool & Localization require_once( __DIR__ . '/lib/basetool/InitTool.php' ); require_once( KR_TSINT_START_INC ); // Class for this tool require_once( __DIR__ . '/class.php' ); $kgTool = new KrMwSnapshots(); $I18N = new TsIntuition( 'Mwsnapshots' ); $toolConfig = array( 'displayTitle' => 'mwSnapshots', 'krinklePrefix' => false, 'remoteBasePath' => dirname( $kgConf->getRemoteBase() ). '/', 'revisionId' => '0.1.2', 'styles' => array( 'main.css', ), 'scripts' => array( 'main.js', ), ); // Local settings require_once( __DIR__ . '/local.php' ); $kgBaseTool = BaseTool::newFromArray( $toolConfig ); $kgBaseTool->setSourceInfoGithub( 'Krinkle', 'ts-krinkle-mwSnapshots', __DIR__ );
Add _sheet to client style sheet
function createStyleTag(media) { const style = document.createElement('style'); style.setAttribute("media", media); // WebKit hack :( style.appendChild(document.createTextNode('')); document.head.appendChild(style); return style; } export default function createStyleSheet(opts = {}) { const { sheets = {} } = opts; function insert(media, sel, rule) { const isAtRule = sel.length && sel.charAt(0) === '@'; let styleTag; if (sheets.hasOwnProperty(media)) { styleTag = sheets[media]; } else { styleTag = createStyleTag(media); sheets[media] = styleTag; } if (process.env.NODE_ENV !== 'production') { if (isAtRule) { styleTag.insertBefore(document.createTextNode(sel), styleTag.firstChild); } else { styleTag.appendChild(document.createTextNode(`${sel}{${rule}}`)); } } else { if (isAtRule) { styleTag.sheet.insertRule(sel, 0); } else { const { sheet } = styleTag; sheet.insertRule(`${sel}{${rule}}`, sheet.cssRules.length); } } } return { insert, _sheets: sheets // for test only }; }
function createStyleTag(media) { const style = document.createElement('style'); style.setAttribute("media", media); // WebKit hack :( style.appendChild(document.createTextNode('')); document.head.appendChild(style); return style; } export default function createStyleSheet(opts = {}) { const { sheets = {} } = opts; function insert(media, sel, rule) { const isAtRule = sel.length && sel.charAt(0) === '@'; let styleTag; if (sheets.hasOwnProperty(media)) { styleTag = sheets[media]; } else { styleTag = createStyleTag(media); sheets[media] = styleTag; } if (process.env.NODE_ENV !== 'production') { if (isAtRule) { styleTag.insertBefore(document.createTextNode(sel), styleTag.firstChild); } else { styleTag.appendChild(document.createTextNode(`${sel}{${rule}}`)); } } else { if (isAtRule) { styleTag.sheet.insertRule(sel, 0); } else { const { sheet } = styleTag; sheet.insertRule(`${sel}{${rule}}`, sheet.cssRules.length); } } } return { insert }; }
Add missing dependency for pyuv.
# # This file is part of gruvi. Gruvi is free software available under the terms # of the MIT license. See the file "LICENSE" that was provided together with # this source file for the licensing terms. # # Copyright (c) 2012 the gruvi authors. See the file "AUTHORS" for a complete # list. from setuptools import setup version_info = { 'name': 'gruvi', 'version': '0.1', 'description': 'Synchronous evented IO', 'author': 'Geert Jansen', 'author_email': 'geertj@gmail.com', 'url': 'https://github.com/geertj/gruvi', 'license': 'MIT', 'classifiers': [ 'Development Status :: 3 - Alpha', 'License :: OSI Approved :: MIT License', 'Operating System :: POSIX', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3' ] } setup( package_dir = { '': 'lib' }, packages = [ 'gruvi', 'gruvi.test' ], requires = ['greenlet', 'pyuv'], install_requires = ['setuptools'], test_suite = 'nose.collector', **version_info )
# # This file is part of gruvi. Gruvi is free software available under the terms # of the MIT license. See the file "LICENSE" that was provided together with # this source file for the licensing terms. # # Copyright (c) 2012 the gruvi authors. See the file "AUTHORS" for a complete # list. from setuptools import setup version_info = { 'name': 'gruvi', 'version': '0.1', 'description': 'Synchronous evented IO', 'author': 'Geert Jansen', 'author_email': 'geertj@gmail.com', 'url': 'https://github.com/geertj/gruvi', 'license': 'MIT', 'classifiers': [ 'Development Status :: 3 - Alpha', 'License :: OSI Approved :: MIT License', 'Operating System :: POSIX', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3' ] } setup( package_dir = { '': 'lib' }, packages = [ 'gruvi', 'gruvi.test' ], requires = ['greenlet'], install_requires = ['setuptools'], test_suite = 'nose.collector', **version_info )
Use native `map`, `filter` for Python 3
from setuptools import setup, find_packages try: from itertools import imap, ifilter except ImportError: imap = map ifilter = filter from os import path from ast import parse if __name__ == '__main__': package_name = 'gitim' get_vals = lambda var0, var1: imap(lambda buf: next(imap(lambda e: e.value.s, parse(buf).body)), ifilter(lambda line: line.startswith(var0) or line.startswith(var1), f)) with open('gitim.py') as f: __author__, __version__ = get_vals('__version__', '__author__') setup( name=package_name, author=__author__, version=__version__, license='MIT', install_requires=['pygithub'], py_modules=['gitim'] )
from setuptools import setup, find_packages from itertools import imap, ifilter from os import path from ast import parse if __name__ == '__main__': package_name = 'gitim' get_vals = lambda var0, var1: imap(lambda buf: next(imap(lambda e: e.value.s, parse(buf).body)), ifilter(lambda line: line.startswith(var0) or line.startswith(var1), f)) with open('gitim.py') as f: __author__, __version__ = get_vals('__version__', '__author__') setup( name=package_name, author=__author__, version=__version__, license='MIT', install_requires=['pygithub'], py_modules=['gitim'] )
Test db should have data now Didn’t realize that child_process functions don’t return promises
/* eslint-env jest */ const util = require('util') const exec = util.promisify(require('child_process').exec) const request = require('supertest') let app // start a mongo instance loaded with test data using docker beforeAll(async () => { await exec('docker run --name scraper_test_db -d --rm -p 27017:27017 mongo') await exec('docker cp __tests__/dump/ scraper_test_db:/dump') await exec('docker exec scraper_test_db mongorestore /dump') app = require('../app') await twoSeconds() }) afterAll(done => exec('docker kill scraper_test_db', done)) describe('courses endpoint', () => { test('/courses succeeds', async () => { const response = await request(app).get('/courses') expect(response.type).toBe('application/json') expect(response.statusCode).toBe(200) }) test('/courses returns an Array', async () => { const response = await request(app).get('/courses') expect(Array.isArray(response.body)).toBeTruthy() }) }) function twoSeconds () { return new Promise(resolve => { setTimeout(() => { resolve() }, 2000) }) }
/* eslint-env jest */ const { exec } = require('child_process') const request = require('supertest') let app // start a mongo instance loaded with test data using docker beforeAll(async () => { await exec('docker run --name scraper_test_db -d --rm -p 27017:27017 mongo') await exec('docker cp dump/ scraper_test_db:/dump') await exec('docker exec scraper_test_db mongorestore /dump') app = await require('../app') await twoSeconds() }) afterAll(done => exec('docker kill scraper_test_db', done)) describe('courses endpoint', () => { test('/courses succeeds', async () => { const response = await request(app).get('/courses') expect(response.type).toBe('application/json') expect(response.statusCode).toBe(200) }) test('/courses returns an Array', async () => { const response = await request(app).get('/courses') expect(Array.isArray(response.body)).toBeTruthy() }) }) function twoSeconds () { return new Promise(resolve => { setTimeout(() => { resolve() }, 2000) }) }
Use gulp command instead of npm run because that requires them to have the scripts entries in the package.json.
'use strict'; var cmd = require('commander'); var pkg = require('../lib/package'); var replace = require('../lib/replace'); var semver = require('semver'); var sh = require('shelljs'); cmd .option('-s, --semver [version]', 'The semantic version to release in lieu of --type. This takes precedence over --type.') .option('-t, --type [major, minor or patch]', 'The type of release being performed in lieu of --semver.') .parse(process.argv); module.exports = function () { var currentVersion = pkg.version; var nextVersion = cmd.semver || semver.inc( currentVersion, cmd.type || 'patch' ); sh.exec('gulp lint'); sh.exec('gulp test'); replace('bower.json', currentVersion, nextVersion); replace('package.json', currentVersion, nextVersion); sh.exec('gulp dist'); sh.exec('gulp lib'); sh.exec('git commit -am "' + currentVersion + ' -> ' + nextVersion + '"'); sh.exec('git tag -a ' + nextVersion + ' -m ' + nextVersion); sh.exec('git push'); sh.exec('git push --tags'); sh.exec('npm publish'); };
'use strict'; var cmd = require('commander'); var pkg = require('../lib/package'); var replace = require('../lib/replace'); var semver = require('semver'); var sh = require('shelljs'); cmd .option('-s, --semver [version]', 'The semantic version to release in lieu of --type. This takes precedence over --type.') .option('-t, --type [major, minor or patch]', 'The type of release being performed in lieu of --semver.') .parse(process.argv); module.exports = function () { var currentVersion = pkg.version; var nextVersion = cmd.semver || semver.inc( currentVersion, cmd.type || 'patch' ); sh.exec('npm run lint'); sh.exec('npm run test'); replace('bower.json', currentVersion, nextVersion); replace('package.json', currentVersion, nextVersion); sh.exec('npm run dist'); sh.exec('npm run lib'); sh.exec('git commit -am "' + currentVersion + ' -> ' + nextVersion + '"'); sh.exec('git tag -a ' + nextVersion + ' -m ' + nextVersion); sh.exec('git push'); sh.exec('git push --tags'); sh.exec('npm publish'); };
Connect decorator should pass props into select function
import React from 'react'; import Connector from './Connector'; import getDisplayName from '../utils/getDisplayName'; import shallowEqualScalar from '../utils/shallowEqualScalar'; export default function connect(select) { return DecoratedComponent => class ConnectorDecorator { static displayName = `Connector(${getDisplayName(DecoratedComponent)})`; shouldComponentUpdate(nextProps) { return !shallowEqualScalar(this.props, nextProps); } constructor() { this.renderChild = this.renderChild.bind(this); } render() { return ( <Connector select={state => select(state, this.props)}> {this.renderChild} </Connector> ); } renderChild(state) { const { props } = this; return <DecoratedComponent {...props} {...state} />; } }; }
import React from 'react'; import Connector from './Connector'; import getDisplayName from '../utils/getDisplayName'; import shallowEqualScalar from '../utils/shallowEqualScalar'; export default function connect(select) { return DecoratedComponent => class ConnectorDecorator { static displayName = `Connector(${getDisplayName(DecoratedComponent)})`; shouldComponentUpdate(nextProps) { return !shallowEqualScalar(this.props, nextProps); } constructor() { this.renderChild = this.renderChild.bind(this); } render() { return ( <Connector select={select}> {this.renderChild} </Connector> ); } renderChild(state) { const { props } = this; return <DecoratedComponent {...props} {...state} />; } }; }
Use our own custom ConsoleSupportServiceProvider
<?php /* * NOTICE OF LICENSE * * Part of the Cortex Foundation Module. * * This source file is subject to The MIT License (MIT) * that is bundled with this package in the LICENSE file. * * Package: Cortex Foundation Module * License: The MIT License (MIT) * Link: https://rinvex.com */ namespace Cortex\Foundation\Providers; use Rinvex\Module\ModuleServiceProvider; use Illuminate\Support\AggregateServiceProvider as BaseAggregateServiceProvider; class AggregateServiceProvider extends BaseAggregateServiceProvider { /** * The provider class names. * * @var array */ protected $providers = [ ModuleServiceProvider::class, FoundationServiceProvider::class, ConsoleSupportServiceProvider::class, FortServiceProvider::class, ]; }
<?php /* * NOTICE OF LICENSE * * Part of the Cortex Foundation Module. * * This source file is subject to The MIT License (MIT) * that is bundled with this package in the LICENSE file. * * Package: Cortex Foundation Module * License: The MIT License (MIT) * Link: https://rinvex.com */ namespace Cortex\Foundation\Providers; use Rinvex\Module\ModuleServiceProvider; use Illuminate\Foundation\Providers\ConsoleSupportServiceProvider; use Illuminate\Support\AggregateServiceProvider as BaseAggregateServiceProvider; class AggregateServiceProvider extends BaseAggregateServiceProvider { /** * The provider class names. * * @var array */ protected $providers = [ ModuleServiceProvider::class, FoundationServiceProvider::class, ConsoleSupportServiceProvider::class, FortServiceProvider::class, ]; }
Add missing 'logging' module import
import logging import requests def input_file(filename): """ Read a file and return list of usernames. Assumes one username per line and ignores blank lines. """ with open(filename, 'r') as f: return list(line.strip() for line in f if line.strip()) def org_members(org_name): """ Query Github API and return list of members from a Github organization. """ # TODO: Return github org members, not a placeholder return ['supermitch', 'Jollyra'] def svg_data(username): """ Returns the contribution streak SVG file contents from Github for a specific username. """ url = 'https://github.com/users/{}/contributions'.format(username) try: r = requests.get(url) except requests.exceptions.ConnectionError: logging.warn('Connection error trying to get url: [{}]'.format(url)) return None return r.text
import requests def input_file(filename): """ Read a file and return list of usernames. Assumes one username per line and ignores blank lines. """ with open(filename, 'r') as f: return list(line.strip() for line in f if line.strip()) def org_members(org_name): """ Query Github API and return list of members from a Github organization. """ # TODO: Return github org members, not a placeholder return ['supermitch', 'Jollyra'] def svg_data(username): """ Returns the contribution streak SVG file contents from Github for a specific username. """ url = 'https://github.com/users/{}/contributions'.format(username) try: r = requests.get(url) except requests.exceptions.ConnectionError: logging.warn('Connection error trying to get url: [{}]'.format(url)) return None return r.text
Fix message processing for sticker comments.
var config = require('../config.json'); var modIDs = config.modIDs; /** * A single Facebook post or comment. * @class */ var Post = module.exports = function (id) { /** @member {string} */ this.id = id; /** @member {string} */ this.from = ''; /** @member {string} */ this.message = ''; }; /** * Converts a raw JSON-formatted post from a response body into an object. * @param {Object} raw * @return {Post} */ Post.fromRaw = function (raw) { var post = new Post(raw.id); post.from = raw.from ? raw.from.id : '0'; post.message = raw.message || ''; return post; }; /** * Determines if the poster was a group moderator. * @returns {boolean} */ Post.prototype.isMod = function () { return modIDs.indexOf(this.from) !== -1; }; /** * Determines if the post contains a moderative command. Commands begin with a * forward slash, followed by any number of alphanumeric characters. * @param {string} cmd * @returns {boolean} */ Post.prototype.hasCommand = function (cmd) { return this.message.match('^/' + cmd + '(?: |$)'); };
var config = require('../config.json'); var modIDs = config.modIDs; /** * A single Facebook post or comment. * @class */ var Post = module.exports = function (id) { /** @member {string} */ this.id = id; /** @member {string} */ this.from = ''; /** @member {string} */ this.message = ''; }; /** * Converts a raw JSON-formatted post from a response body into an object. * @param {Object} raw * @return {Post} */ Post.fromRaw = function (raw) { var post = new Post(raw.id); post.from = raw.from ? raw.from.id : '0'; post.message = raw.message; return post; }; /** * Determines if the poster was a group moderator. * @returns {boolean} */ Post.prototype.isMod = function () { return modIDs.indexOf(this.from) !== -1; }; /** * Determines if the post contains a moderative command. Commands begin with a * forward slash, followed by any number of alphanumeric characters. * @param {string} cmd * @returns {boolean} */ Post.prototype.hasCommand = function (cmd) { return this.message.match('^/' + cmd + '(?: |$)'); };
Correct the path to the config file
<?php namespace Thatdamnqa\MancMetFeed; require_once '../config/config.php'; use Thatdamnqa\MancMetFeed\Services\TwitterNotifierClientFactory; require __DIR__ . '/../vendor/autoload.php'; $tweetClass = new Tweet(TwitterNotifierClientFactory::getClient()); $metrolinkClass = new Metrolink(new \DateTimeImmutable()); $websiteHandlerClass = new WebsiteHandler(MMS_API_URL); $statusClass = new Status($websiteHandlerClass, $metrolinkClass); $statusString = $statusClass->getStatusString(); $tweets = $tweetClass->generate($statusString); if (null == $tweets) { } else { $first_tweet_id = null; foreach ($tweets as $key => $t) { $tweetid = $tweetClass->post($t, $first_tweet_id); if ($key == 0 && $tweetid) { $first_tweet_id = $tweetid; } if (MMS_DEBUG === true) { echo "---\n"; } } }
<?php namespace Thatdamnqa\MancMetFeed; require_once 'config/config.php'; use Thatdamnqa\MancMetFeed\Services\TwitterNotifierClientFactory; require __DIR__ . '/../vendor/autoload.php'; $tweetClass = new Tweet(TwitterNotifierClientFactory::getClient()); $metrolinkClass = new Metrolink(new \DateTimeImmutable()); $websiteHandlerClass = new WebsiteHandler(MMS_API_URL); $statusClass = new Status($websiteHandlerClass, $metrolinkClass); $statusString = $statusClass->getStatusString(); $tweets = $tweetClass->generate($statusString); if (null == $tweets) { } else { $first_tweet_id = null; foreach ($tweets as $key => $t) { $tweetid = $tweetClass->post($t, $first_tweet_id); if ($key == 0 && $tweetid) { $first_tweet_id = $tweetid; } if (MMS_DEBUG === true) { echo "---\n"; } } }
Remove at exit handler it doesnt work...
import subprocess from delivery.models.execution import ExecutionResult, Execution class ExternalProgramService(): @staticmethod def run(cmd): p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE) return Execution(pid=p.pid, process_obj=p) @staticmethod def run_and_wait(cmd): execution = ExternalProgramService.run(cmd) out, err = execution.process_obj.communicate() status_code = execution.process_obj.wait() return ExecutionResult(out, err, status_code)
import subprocess import atexit from delivery.models.execution import ExecutionResult, Execution class ExternalProgramService(): @staticmethod def run(cmd): p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE) # On exiting the main program, make sure that the subprocess # gets killed. atexit.register(p.terminate) return Execution(pid=p.pid, process_obj=p) @staticmethod def run_and_wait(cmd): execution = ExternalProgramService.run(cmd) out, err = execution.process_obj.communicate() status_code = execution.process_obj.wait() return ExecutionResult(out, err, status_code)
Fix LinkTag mit mehreren News Komponenten es wurde immer die erste ausgewählt = != ==
<?php class Vpc_Basic_LinkTag_News_Form extends Vpc_Abstract_Form { protected function _initFields() { parent::_initFields(); } public function __construct($name, $class, $id = null) { parent::__construct($name, $class, $id); $this->add(new Vps_Form_Field_Select('news_id', trlVps('News'))) ->setDisplayField('title') ->setStoreUrl( Vpc_Admin::getInstance($class)->getControllerUrl('News').'/json-data' ) ->setListWidth(210) ->setAllowBlank(false); } public function getIsCurrentLinkTag($parentRow) { $row = $this->getRow($parentRow); $c = Vps_Component_Data_Root::getInstance()->getComponentByDbId('news_'.$row->news_id); return 'news_'.$c->parent->dbId == $this->getName(); } }
<?php class Vpc_Basic_LinkTag_News_Form extends Vpc_Abstract_Form { protected function _initFields() { parent::_initFields(); } public function __construct($name, $class, $id = null) { parent::__construct($name, $class, $id); $this->add(new Vps_Form_Field_Select('news_id', trlVps('News'))) ->setDisplayField('title') ->setStoreUrl( Vpc_Admin::getInstance($class)->getControllerUrl('News').'/json-data' ) ->setListWidth(210) ->setAllowBlank(false); } public function getIsCurrentLinkTag($parentRow) { $row = $this->getRow($parentRow); $c = Vps_Component_Data_Root::getInstance()->getComponentByDbId('news_'.$row->news_id); return 'news_'.$c->parent->dbId = $this->getName(); } }
Enable sale using card reference ("token")
<?php namespace Omnipay\BluePay\Message; /** * BluePay Sale Request */ class SaleRequest extends AbstractRequest { protected $action = 'SALE'; public function getData() { $data = $this->getBaseData(); if ($cardReference = $this->getCardReference()) { $data['MASTER_ID'] = $cardReference; // $data['CARD_EXPIRE'] = $this->getCard()->getExpiryDate('my'); } elseif ($card = $this->getCard()) { $card->validate(); $data['PAYMENT_ACCOUNT'] = $card->getNumber(); $data['CARD_EXPIRE'] = $card->getExpiryDate('my'); $data['CARD_CVV2'] = $card->getCvv(); } return array_merge($data, $this->getBillingData()); } }
<?php namespace Omnipay\BluePay\Message; /** * BluePay Sale Request */ class SaleRequest extends AbstractRequest { protected $action = 'SALE'; public function getData() { $data = $this->getBaseData(); if ($card = $this->getCard()) { $card->validate(); $data['PAYMENT_ACCOUNT'] = $this->getCard()->getNumber(); $data['CARD_EXPIRE'] = $this->getCard()->getExpiryDate('my'); $data['CARD_CVV2'] = $this->getCard()->getCvv(); } return array_merge($data, $this->getBillingData()); } }
Fix test for change in panel text
import sys import pytest from PyQt5 import QtGui, QtWidgets # Local from sas.qtgui.MainWindow.WelcomePanel import WelcomePanel class WelcomePanelTest: '''Test the WelcomePanel''' @pytest.fixture(autouse=True) def widget(self, qapp): '''Create/Destroy the WelcomePanel''' w = WelcomePanel(None) yield w w.close() def testDefaults(self, widget): '''Test the GUI in its default state''' assert isinstance(widget, QtWidgets.QDialog) assert widget.windowTitle() == "Welcome" def testVersion(self, widget): '''Test the version string''' version = widget.lblVersion assert isinstance(version, QtWidgets.QLabel) assert "SasView" in version.text() for inst in "UTK, UMD, ESS, NIST, ORNL, ISIS, ILL, DLS, TUD, BAM, ANSTO".split(", "): assert inst in version.text()
import sys import pytest from PyQt5 import QtGui, QtWidgets # Local from sas.qtgui.MainWindow.WelcomePanel import WelcomePanel class WelcomePanelTest: '''Test the WelcomePanel''' @pytest.fixture(autouse=True) def widget(self, qapp): '''Create/Destroy the WelcomePanel''' w = WelcomePanel(None) yield w w.close() def testDefaults(self, widget): '''Test the GUI in its default state''' assert isinstance(widget, QtWidgets.QDialog) assert widget.windowTitle() == "Welcome" def testVersion(self, widget): '''Test the version string''' version = widget.lblVersion assert isinstance(version, QtWidgets.QLabel) assert "SasView" in version.text() assert "Build:" in version.text() for inst in "UTK, UMD, ESS, NIST, ORNL, ISIS, ILL, DLS, TUD, BAM, ANSTO".split(", "): assert inst in version.text()
Make metric_name option of monitored_batch_queue
import functools import tensorflow as tf from . import cnn_dailymail_rc from .. import collections from ..flags import FLAGS from ..util import func_scope, dtypes from .util import batch_queue, add_queue_runner READERS = { "cnn_dailymail_rc": cnn_dailymail_rc.read_files } @func_scope() def read_files(file_pattern, file_format): return monitored_batch_queue( *READERS[file_format](_file_pattern_to_names(file_pattern))) @func_scope() def _file_pattern_to_names(pattern): return tf.train.string_input_producer(tf.train.match_filenames_once(pattern), num_epochs=FLAGS.num_epochs, capacity=FLAGS.filename_queue_capacity) @func_scope() def monitored_batch_queue(*tensors, metric_name="batches_in_queue"): queue = batch_queue(dtypes(*tensors)) collections.add_metric(queue.size(), metric_name) add_queue_runner(queue, [queue.enqueue(tensors)]) results = queue.dequeue() for tensor, result in zip(tensors, results): result.set_shape(tensor.get_shape()) return results
import functools import tensorflow as tf from . import cnn_dailymail_rc from .. import collections from ..flags import FLAGS from ..util import func_scope, dtypes from .util import batch_queue, add_queue_runner READERS = { "cnn_dailymail_rc": cnn_dailymail_rc.read_files } @func_scope() def read_files(file_pattern, file_format): return monitored_batch_queue( *READERS[file_format](_file_pattern_to_names(file_pattern))) @func_scope() def _file_pattern_to_names(pattern): return tf.train.string_input_producer(tf.train.match_filenames_once(pattern), num_epochs=FLAGS.num_epochs, capacity=FLAGS.filename_queue_capacity) @func_scope() def monitored_batch_queue(*tensors): queue = batch_queue(dtypes(*tensors)) collections.add_metric(queue.size(), "batches_in_queue") add_queue_runner(queue, [queue.enqueue(tensors)]) results = queue.dequeue() for tensor, result in zip(tensors, results): result.set_shape(tensor.get_shape()) return results
Allow connection from localhost only
/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- vim:set ts=4 sw=4 sts=4 et: */ package jp.oist.flint.rpc; import com.sun.net.httpserver.HttpServer; import java.io.IOException; import java.net.BindException; import java.net.InetAddress; import java.net.InetSocketAddress; public class Server { static final int PORT = 20465; private final HttpServer mHttpServer; public Server(ICallee callee) throws BindException, IOException { InetSocketAddress isa = new InetSocketAddress(InetAddress.getLoopbackAddress(), PORT); mHttpServer = HttpServer.create(isa, 0); // use the default value for the socket backlog mHttpServer.createContext("/open-model", new OpenModelRequestHandler(callee)); mHttpServer.createContext("/run", new RunRequestHandler(callee)); } public void start() { mHttpServer.setExecutor(null); // create a default executor mHttpServer.start(); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { mHttpServer.stop(0); } }); } }
/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- vim:set ts=4 sw=4 sts=4 et: */ package jp.oist.flint.rpc; import com.sun.net.httpserver.HttpServer; import java.io.IOException; import java.net.BindException; import java.net.InetSocketAddress; public class Server { static final int PORT = 20465; private final HttpServer mHttpServer; public Server(ICallee callee) throws BindException, IOException { InetSocketAddress isa = new InetSocketAddress(PORT); mHttpServer = HttpServer.create(isa, 0); // use the default value for the socket backlog mHttpServer.createContext("/open-model", new OpenModelRequestHandler(callee)); mHttpServer.createContext("/run", new RunRequestHandler(callee)); } public void start() { mHttpServer.setExecutor(null); // create a default executor mHttpServer.start(); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { mHttpServer.stop(0); } }); } }
Add default values for login credentials in test base
from flask.ext.testing import TestCase import unittest from app import create_app, db class BaseTestCase(TestCase): def create_app(self): return create_app('config.TestingConfiguration') def setUp(self): db.create_all() def tearDown(self): db.session.remove() db.drop_all() def login(self, username='admin', password='changeme'): return self.client.post('/login', data=dict( username=username, password=password ), follow_redirects=True) def logout(self): return self.client.get('/logout', follow_redirects=True) if __name__ == '__main__': unittest.main()
from flask.ext.testing import TestCase import unittest from app import create_app, db class BaseTestCase(TestCase): def create_app(self): return create_app('config.TestingConfiguration') def setUp(self): db.create_all() def tearDown(self): db.session.remove() db.drop_all() def login(self, username, password): return self.client.post('/login', data=dict( username=username, password=password ), follow_redirects=True) def logout(self): return self.client.get('/logout', follow_redirects=True) if __name__ == '__main__': unittest.main()
Fix bug where filepath is a string
<?php namespace App\Importer; class ImportDataFactory { /** * Instanciate an import data class depending on given file. * * @param string $filepath * @return \Gallib\Macope\Importer\ImportDataInterface */ public static function create($filepath) { $factory = new PostFinanceImport($filepath); if ($factory->isValid()) { return $factory; } $factory = new MigrosBankImport($filepath); if ($factory->isValid()) { return $factory; } throw new \InvalidArgumentException("File is not valid"); } }
<?php namespace App\Importer; class ImportDataFactory { /** * Instanciate an import data class depending on given file. * * @param string $filepath * @return \Gallib\Macope\Importer\ImportDataInterface */ public static function create($filepath) { $factory = new PostFinanceImport($filepath); if ($factory->isValid()) { return $factory; } $factory = new MigrosBankImport($filepath); if ($factory->isValid()) { return $factory; } throw new \InvalidArgumentException("{$filepath->getClientOriginalName()} is not a valid file"); } }
Add support for start and end ranges at query time
module.exports = TimestreamDB module.exports.open = function (path, options, callback) { // TODO force valueEncoding = json? if (callback) { levelup(path, options, function (err, db) { if (err) return callback(err) callback(err, TimestreamDB(db, options)) }) } else return TimestreamDB(levelup(path, options), options) } var levelup = require("levelup") var Version = require("level-version") var through2map = require("through2-map") var ts = require("timestream") var toTimestream = through2map.ctor({objectMode: true}, function _transform(record) { var tsRecord = record.value tsRecord._t = record.version tsRecord._key = record.key return tsRecord } ) /** * Create a new TimestreamDB * @param {LevelUp} instance A LevelUp instance * @param {object} options Configuration options for level-version */ function TimestreamDB(instance, options) { if (!(this instanceof TimestreamDB)) return new TimestreamDB(instance, options) var db = Version(instance, options) db.ts = function (key, options) { var opts = {reverse: true} if (options.start) opts.minVersion = options.start if (options.until) opts.maxVersion = options.until return ts(db.versionStream(key, opts).pipe(toTimestream())) } db.timeStream = db.ts return db }
module.exports = TimestreamDB module.exports.open = function (path, options, callback) { // TODO force valueEncoding = json? if (callback) { levelup(path, options, function (err, db) { if (err) return callback(err) callback(err, TimestreamDB(db, options)) }) } else return TimestreamDB(levelup(path, options), options) } var levelup = require("levelup") var Version = require("level-version") var through2map = require("through2-map") var ts = require("timestream") var toTimestream = through2map.ctor({objectMode: true}, function _transform(record) { var tsRecord = record.value tsRecord._t = record.version tsRecord._key = record.key return tsRecord } ) /** * Create a new TimestreamDB * @param {LevelUp} instance A LevelUp instance * @param {object} options Configuration options for level-version */ function TimestreamDB(instance, options) { if (!(this instanceof TimestreamDB)) return new TimestreamDB(instance, options) var db = Version(instance, options) db.ts = function (key) { return ts(db.versionStream(key, {reverse: true}).pipe(toTimestream())) } db.timeStream = db.ts return db }
Modify Model::reload() function behaviour to sync with original attributes when model is not persisted and to always load from the database otherwise.
<?php namespace Baum\Extensions; trait ModelExtensions { /** * Reloads the model from the database. * * @return \Baum\Node */ public function reload() { if ( !$this->exists ) { $this->syncOriginal(); } else { $fresh = static::find($this->getKey()); $this->setRawAttributes($fresh->getAttributes(), true); } return $this; } /** * Find first model. * * @return \Illuminate\Database\Eloquent\Model */ public static function first() { $instance = new static; return $instance->newQuery()->orderBy($instance->getKeyName(), 'asc')->first(); } /** * Find last model. * * @return \Illuminate\Database\Eloquent\Model */ public static function last() { $instance = new static; return $instance->newQuery()->orderBy($instance->getKeyName(), 'desc')->first(); } }
<?php namespace Baum\Extensions; trait ModelExtensions { /** * Reloads the model from the database. * * @return \Baum\Node */ public function reload() { if ( !$this->exists ) return $this; $dirty = $this->getDirty(); if ( count($dirty) === 0 ) return $this; $fresh = static::find($this->getKey()); $this->setRawAttributes($fresh->getAttributes(), true); return $this; } /** * Find first model. * * @return \Illuminate\Database\Eloquent\Model */ public static function first() { $instance = new static; return $instance->newQuery()->orderBy($instance->getKeyName(), 'asc')->first(); } /** * Find last model. * * @return \Illuminate\Database\Eloquent\Model */ public static function last() { $instance = new static; return $instance->newQuery()->orderBy($instance->getKeyName(), 'desc')->first(); } }
Fix for input options in make_t_matrix function
#solarnmf_main_ts.py #Will Barnes #31 March 2015 #Import needed modules import solarnmf_functions as snf import solarnmf_plot_routines as spr #Read in and format the time series results = snf.make_t_matrix("simulation",format="timeseries",nx=100,ny=100,p=10,filename='/home/wtb2/Desktop/gaussian_test.dat') #Get the dimensions of the T matrix ny,nx = results['T'].shape #Set the number of guessed sources Q = 10 #Initialize the U, V, and A matrices uva_initial = snf.initialize_uva(nx,ny,Q,5,10,results['T']) #Start the minimizer min_results = snf.minimize_div(uva_initial['u'],uva_initial['v'],results['T'],uva_initial['A'],100,1.0e-5) #Show the initial and final matrices side-by-side spr.plot_mat_obsVpred(results['T'],min_results['A']) #Show the initial and final 1d time series curves spr.plot_ts_obsVpred(results['x'],min_results['A']) #Show the constituents of the time series on top of the original vector spr.plot_ts_reconstruction(results['x'],min_results['u'],min_results['v'])
#solarnmf_main_ts.py #Will Barnes #31 March 2015 #Import needed modules import solarnmf_functions as snf import solarnmf_plot_routines as spr #Read in and format the time series results = snf.make_t_matrix("simulation",format="timeseries",filename='/home/wtb2/Desktop/gaussian_test.dat') #Get the dimensions of the T matrix ny,nx = results['T'].shape #Set the number of guessed sources Q = 10 #Initialize the U, V, and A matrices uva_initial = snf.initialize_uva(nx,ny,Q,5,5,results['T']) #Start the minimizer min_results = snf.minimize_div(uva_initial['u'],uva_initial['v'],results['T'],uva_initial['A'],200,1.0e-5) #Show the initial and final matrices side-by-side spr.plot_mat_obsVpred(results['T'],min_results['A']) #Show the initial and final 1d time series curves spr.plot_ts_obsVpred(results['x'],min_results['A']) #Show the constituents of the time series on top of the original vector spr.plot_ts_reconstruction(results['x'],min_results['u'],min_results['v'])
Bring formified inputs into the world of the filter.
$(function(){ $('.more-or-less').each(function(i, el) { console.log(el); $(el).find("li a").click(function() { $(el).find("button").html($(this).text() + ' <span class="caret"></span>'); $(el).find("input.more-or-less-type").val($(this).text()); }); }); $(".formify").each(function (_, element) { var value = $(element).find("[data-selected='true']").first().addClass("active").data("value"); $(element).append('<input class="formify-value" type="hidden" name="filter[' + $(this).data('name') + ']" value="' + value + '" >'); }); $(".formify .btn").click(function () { $(this).addClass("active"); var val = $(this).data("value"); var input = $(this).parent().find(".formify-value") console.log(val) $(input).val(val) }); $(".incident").click(function() { $(this).toggleClass("selected"); }); $(".select-all").click(function(event) { $(event.target).parent().parent().find("input").prop("checked", true); event.preventDefault(); }); $(".clear-all").click(function(event) { $(event.target).parent().parent().find("input").prop("checked", false); event.preventDefault(); }); })
$(function(){ $('.more-or-less').each(function(i, el) { console.log(el); $(el).find("li a").click(function() { $(el).find("button").html($(this).text() + ' <span class="caret"></span>'); $(el).find("input.more-or-less-type").val($(this).text()); }); }); $(".formify").each(function (_, element) { var value = $(element).find("[data-selected='true']").first().addClass("active").data("value"); $(element).append('<input class="formify-value" type="hidden" name="' + $(this).data('name') + '" value="' + value + '" >'); }); $(".formify .btn").click(function () { $(this).addClass("active"); var val = $(this).data("value"); var input = $(this).parent().find(".formify-value") console.log(val) $(input).val(val) }); $(".incident").click(function() { $(this).toggleClass("selected"); }); $(".select-all").click(function(event) { $(event.target).parent().parent().find("input").prop("checked", true); event.preventDefault(); }); $(".clear-all").click(function(event) { $(event.target).parent().parent().find("input").prop("checked", false); event.preventDefault(); }); })
Change populate method, allow empty array
<?php namespace Aedart\Util\Interfaces; /** * Interface Populatable * * <br /> * * Components implementing this interface promise, that the given component can * be populated with some kind of data and thereby set its internal properties or * states to the given value(s) * * <br /> * * What kind of properties can be populated / set, is completely implementation * dependent. * * @author Alin Eugen Deac <aedart@gmail.com> * @package Aedart\Util\Interfaces */ interface Populatable { /** * Populate this component via an array * * <br /> * * If an empty array is provided, nothing is populated. * * <br /> * * If a value or property is not given via $data, then it * is NOT modified / changed. * * @param array $data Key-value pair, where the key corresponds to a * property name and the value to be set, e.g. <p> * <pre> * [ * 'myProperty' => 'myPropertyValue', * 'myOtherProperty' => 42.5 * ] * </pre> * </p> * * @return void * * @throws \Exception In case that one or more of the given array entries are invalid */ public function populate(array $data = []); }
<?php namespace Aedart\Util\Interfaces; /** * Interface Populatable * * Components implementing this interface promise, that the given component can * be populated with some kind of data and thereby set its internal properties or * states to the given value(s) * * What kind of properties can be populated / set, is completely implementation * dependent. * * @author Alin Eugen Deac <aedart@gmail.com> * @package Aedart\Util\Interfaces */ interface Populatable { /** * Populate this component via an array * * @param array $data Key-value pair, where the key corresponds to a * property name and the value to be set, e.g. <p> * <pre> * [ * 'myProperty' => 'myPropertyValue', * 'myOtherProperty' => 42.5 * ] * </pre> * </p> * * @return void * * @throws \Exception In case that one or more of the given array entries are invalid */ public function populate(array $data); }
Support new location of ProxyFix helper
# flake8: noqa from flask import Flask try: from werkzeug.middleware.proxy_fix import ProxyFix except ImportError: from werkzeug.contrib.fixers import ProxyFix __version__ = '1.0.1' app = Flask(__name__) app.config.from_object('oauthclientbridge.default_settings') app.config.from_envvar('OAUTH_SETTINGS', silent=True) if app.config['OAUTH_NUM_PROXIES']: wrapper = ProxyFix(app.wsgi_app, app.config['OAUTH_NUM_PROXIES']) app.wsgi_app = wrapper # type: ignore try: import sentry_sdk from sentry_sdk.integrations.flask import FlaskIntegration if app.config['OAUTH_SENTRY_DSN']: sentry_sdk.init( dsn=app.config['OAUTH_SENTRY_DSN'], integrations=[FlaskIntegration()], ) except ImportError as e: app.logger.info('Failed to import sentry: %s', e) import oauthclientbridge.cli import oauthclientbridge.logging import oauthclientbridge.views
# flake8: noqa from flask import Flask from werkzeug.contrib.fixers import ProxyFix __version__ = '1.0.1' app = Flask(__name__) app.config.from_object('oauthclientbridge.default_settings') app.config.from_envvar('OAUTH_SETTINGS', silent=True) if app.config['OAUTH_NUM_PROXIES']: wrapper = ProxyFix(app.wsgi_app, app.config['OAUTH_NUM_PROXIES']) app.wsgi_app = wrapper # type: ignore try: import sentry_sdk from sentry_sdk.integrations.flask import FlaskIntegration if app.config['OAUTH_SENTRY_DSN']: sentry_sdk.init( dsn=app.config['OAUTH_SENTRY_DSN'], integrations=[FlaskIntegration()], ) except ImportError as e: app.logger.info('Failed to import sentry: %s', e) import oauthclientbridge.cli import oauthclientbridge.logging import oauthclientbridge.views
Send query param to backend send query param ?mark_as_seen=true on route /find-broadcasts so the backend can create impressions with a neutral response
import Ember from 'ember'; export default Ember.Controller.extend({ session: Ember.inject.service('session'), intl: Ember.inject.service(), queryParams: ['mark_as_seen', 'page', 'perPage', 'sort', 'q', 'medium', 'station'], sort: 'random', q: null, medium: null, station: null, mark_as_seen: true, page: 1, perPage: 6, totalPages: Ember.computed.alias("content.broadcasts.totalPages"), positiveImpressionsWithoutAmount: Ember.computed.filterBy('model.impressions','needsAmount', true), actions: { searchAction(query){ this.send('setQuery', query); this.set('page', 1); }, browse(step){ this.set('page', step); }, respond(broadcast){ broadcast.get('impressions.firstObject').save(); }, loginAction(){ this.send('login'); }, sortBroadcasts(direction) { this.set('sort', direction); this.get('filterParams').sort = direction; }, } });
import Ember from 'ember'; export default Ember.Controller.extend({ session: Ember.inject.service('session'), intl: Ember.inject.service(), queryParams: ['page', 'perPage', 'sort', 'q', 'medium', 'station'], sort: 'random', q: null, medium: null, station: null, page: 1, perPage: 6, totalPages: Ember.computed.alias("content.broadcasts.totalPages"), positiveImpressionsWithoutAmount: Ember.computed.filterBy('model.impressions','needsAmount', true), actions: { searchAction(query){ this.send('setQuery', query); this.set('page', 1); }, browse(step){ this.set('page', step); }, respond(broadcast){ broadcast.get('impressions.firstObject').save(); }, loginAction(){ this.send('login'); }, sortBroadcasts(direction) { this.set('sort', direction); this.get('filterParams').sort = direction; }, } });
Use proper formatting for `options.outputPaths.testSupport.js` Fixes #5852
/* global require, module */ var EmberApp = require('ember-cli/lib/broccoli/ember-app'); module.exports = function (defaults) { var app = new EmberApp(defaults, { outputPaths: { app: { html: 'my-app.html', css: { 'app': '/css/app.css', 'theme': '/css/theme/a.css' }, js: '/js/app.js' }, vendor: { css: '/css/vendor.css', js: '/js/vendor.js' }, testSupport: { css: '/css/test-support.css', js: { testSupport: '/js/test-support.js', testLoader: '/js/test-loader.js' } } } }); return app.toTree(); };
/* global require, module */ var EmberApp = require('ember-cli/lib/broccoli/ember-app'); module.exports = function (defaults) { var app = new EmberApp(defaults, { outputPaths: { app: { html: 'my-app.html', css: { 'app': '/css/app.css', 'theme': '/css/theme/a.css' }, js: '/js/app.js' }, vendor: { css: '/css/vendor.css', js: '/js/vendor.js' }, testSupport: { css: '/css/test-support.css', js: '/js/test-support.js' } } }); return app.toTree(); };
Clean up of plugin info git-svn-id: 9bac41f8ebc9458fc3e28d41abfab39641e8bd1c@31083 b456876b-0849-0410-b77d-98878d47e9d5
<?php // (c) Copyright 2002-2010 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$ function wikiplugin_rcontent_info() { return array( 'name' => tra( 'Random Dynamic Content' ), 'documentation' => tra('PluginRcontent'), 'description' => tra( 'Includes random content from the dynamic content system.' ), 'prefs' => array( 'feature_dynamic_content', 'wikiplugin_rcontent' ), 'params' => array( 'id' => array( 'required' => true, 'name' => tra('Content ID'), 'description' => tra('Numeric value representing the content ID'), 'default' => '', ) ) ); } function wikiplugin_rcontent( $data, $params, $offset, $parseOptions) { global $dcslib; include_once('lib/dcs/dcslib.php'); $lang = null; if( isset( $parseOptions['language'] ) ) { $lang = $parseOptions['language']; } if( $params['id'] ) return $dcslib->get_random_content((int) $params['id'], $lang); }
<?php // (c) Copyright 2002-2010 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$ function wikiplugin_rcontent_info() { return array( 'name' => tra( 'Random Dynamic Content' ), 'documentation' => 'PluginRcontent', 'description' => tra( 'Includes random content from the dynamic content system.' ), 'prefs' => array( 'feature_dynamic_content', 'wikiplugin_rcontent' ), 'params' => array( 'id' => array( 'required' => true, 'name' => tra('Content ID'), 'description' => tra('Numeric value.'), ), ), ); } function wikiplugin_rcontent( $data, $params, $offset, $parseOptions) { global $dcslib; include_once('lib/dcs/dcslib.php'); $lang = null; if( isset( $parseOptions['language'] ) ) { $lang = $parseOptions['language']; } if( $params['id'] ) return $dcslib->get_random_content((int) $params['id'], $lang); }
FIX Only updateList for objects that have the FluentVersionedExtension Prevents breaking when fluent is not enabled, or querying objects that are not fluent
<?php namespace TractorCow\Fluent\Extension; use SilverStripe\Core\Extension; use SilverStripe\Core\Injector\Injector; use SilverStripe\ORM\DataList; use TractorCow\Fluent\State\FluentState; /** * Available since SilverStripe 4.3.x */ class FluentReadVersionsExtension extends Extension { /** * Set a filter on the current locale in SourceLocale alias field. This field is added by * FluentExtension::augmentSQL, and this list is used in the history viewer via a GraphQL query. * * @param DataList &$list */ public function updateList(DataList &$list) { if (Injector::inst()->get($list->dataClass())->hasExtension(FluentVersionedExtension::class)) { return; } $locale = FluentState::singleton()->getLocale(); $query = $list->dataQuery(); $query->having(['"SourceLocale" = ?' => $locale]); $list = $list->setDataQuery($query); } }
<?php namespace TractorCow\Fluent\Extension; use SilverStripe\Core\Extension; use SilverStripe\ORM\DataList; use TractorCow\Fluent\State\FluentState; /** * Available since SilverStripe 4.3.x */ class FluentReadVersionsExtension extends Extension { /** * Set a filter on the current locale in SourceLocale alias field. This field is added by * FluentExtension::augmentSQL, and this list is used in the history viewer via a GraphQL query. * * @param DataList &$list */ public function updateList(DataList &$list) { $locale = FluentState::singleton()->getLocale(); $query = $list->dataQuery(); $query->having(['"SourceLocale" = ?' => $locale]); $list = $list->setDataQuery($query); } }