text
stringlengths 16
4.96k
| positive
stringlengths 321
2.24k
| negative
stringlengths 310
2.21k
|
|---|---|---|
Improve sidebar a bit - remove long class names from navigation
git-svn-id: e2c3038d01fb1e63d9a6e7e9a258c7088cd26e08@1160300 13f79535-47bb-0310-9956-ffa450edef68
|
package org.apache.karaf.webconsole.core.internal;
import org.apache.wicket.Page;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.link.BookmarkablePageLink;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.ListView;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.util.ListModel;
public class SidebarPanel extends Panel {
public SidebarPanel(String id, Class<? extends Page> basePage, ListModel<Class<? extends Page>> listModel) {
super(id, listModel);
add(new BookmarkablePageLink<Page>("masterPageLink", basePage).add(new Label("masterPageLabel", basePage.getSimpleName())));
add(new ListView<Class<? extends Page>>("subPageLinks", listModel) {
@Override
protected void populateItem(ListItem<Class<? extends Page>> item) {
Class<? extends Page> page = item.getModelObject();
BookmarkablePageLink<Page> link = new BookmarkablePageLink<Page>("subPageLink", page);
link.add(new Label("subPageLabel", page.getSimpleName()));
item.add(link);
}
});
}
}
|
package org.apache.karaf.webconsole.core.internal;
import org.apache.wicket.Page;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.link.BookmarkablePageLink;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.ListView;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.util.ListModel;
public class SidebarPanel extends Panel {
public SidebarPanel(String id, Class<? extends Page> basePage, ListModel<Class<? extends Page>> listModel) {
super(id, listModel);
add(new BookmarkablePageLink<Page>("masterPageLink", basePage).add(new Label("masterPageLabel", basePage.getName())));
add(new ListView<Class<? extends Page>>("subPageLinks", listModel) {
@Override
protected void populateItem(ListItem<Class<? extends Page>> item) {
BookmarkablePageLink<Page> link = new BookmarkablePageLink<Page>("subPageLink", item.getModelObject());
link.add(new Label("subPageLabel", item.getModelObject().getName()));
item.add(link);
}
});
}
}
|
Hide comments meant as unseen
|
from ckan.plugins import toolkit as tk
def archiver_resource_show(resource_id):
data_dict = {'id': resource_id}
return tk.get_action('archiver_resource_show')(data_dict)
def archiver_is_resource_broken_html(resource):
archival = resource.get('archiver')
if not archival:
return tk.literal('<!-- No archival info for this resource -->')
extra_vars = {'resource': resource}
extra_vars.update(archival)
return tk.literal(
tk.render('archiver/is_resource_broken.html',
extra_vars=extra_vars))
def archiver_is_resource_cached_html(resource):
archival = resource.get('archiver')
if not archival:
return tk.literal('<!-- No archival info for this resource -->')
extra_vars = {'resource': resource}
extra_vars.update(archival)
return tk.literal(
tk.render('archiver/is_resource_cached.html',
extra_vars=extra_vars))
# Replacement for the core ckan helper 'format_resource_items'
# but with our own blacklist
def archiver_format_resource_items(items):
blacklist = ['archiver', 'qa']
items_ = [item for item in items
if item[0] not in blacklist]
import ckan.lib.helpers as ckan_helpers
return ckan_helpers.format_resource_items(items_)
|
from ckan.plugins import toolkit as tk
def archiver_resource_show(resource_id):
data_dict = {'id': resource_id}
return tk.get_action('archiver_resource_show')(data_dict)
def archiver_is_resource_broken_html(resource):
archival = resource.get('archiver')
if not archival:
return '<!-- No archival info for this resource -->'
extra_vars = {'resource': resource}
extra_vars.update(archival)
return tk.literal(
tk.render('archiver/is_resource_broken.html',
extra_vars=extra_vars))
def archiver_is_resource_cached_html(resource):
archival = resource.get('archiver')
if not archival:
return '<!-- No archival info for this resource -->'
extra_vars = {'resource': resource}
extra_vars.update(archival)
return tk.literal(
tk.render('archiver/is_resource_cached.html',
extra_vars=extra_vars))
# Replacement for the core ckan helper 'format_resource_items'
# but with our own blacklist
def archiver_format_resource_items(items):
blacklist = ['archiver', 'qa']
items_ = [item for item in items
if item[0] not in blacklist]
import ckan.lib.helpers as ckan_helpers
return ckan_helpers.format_resource_items(items_)
|
Check if dir exists before calling listdir
Changes along the way to how we clean up and detach after
copying an image to a volume exposed a problem in the cleanup
of the brick/initiator routines.
The clean up in the initiator detach was doing a blind listdir
of /dev/disk/by-path, however due to detach and cleanup being
called upon completion of the image download to the volume if
there are no other devices mapped in this directory the directory
is removed.
The result was that even though the create and copy of the image
was succesful, the HostDriver code called os.lisdir on a directory
that doesn't exist any longer and raises an unhandled exception that
cause the taskflow mechanism to mark the volume as failed.
Change-Id: I488755c1a49a77f42efbb58a7a4eb6f4f084df07
Closes-bug: #1243980
(cherry picked from commit 1766a5acc5c948288b4cd81c62d0c1507c55f727)
|
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2013 OpenStack Foundation.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import os
class HostDriver(object):
def get_all_block_devices(self):
"""Get the list of all block devices seen in /dev/disk/by-path/."""
files = []
dir = "/dev/disk/by-path/"
if os.path.isdir(dir):
files = os.listdir(dir)
devices = []
for file in files:
devices.append(dir + file)
return devices
|
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2013 OpenStack Foundation.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import os
class HostDriver(object):
def get_all_block_devices(self):
"""Get the list of all block devices seen in /dev/disk/by-path/."""
dir = "/dev/disk/by-path/"
files = os.listdir(dir)
devices = []
for file in files:
devices.append(dir + file)
return devices
|
Update "Girls With Slingshots" after feed change
|
from comics.aggregator.crawler import CrawlerBase, CrawlerImage
from comics.core.comic_data import ComicDataBase
class ComicData(ComicDataBase):
name = "Girls With Slingshots"
language = "en"
url = "http://www.girlswithslingshots.com/"
start_date = "2004-09-30"
rights = "Danielle Corsetto"
class Crawler(CrawlerBase):
history_capable_days = 30
schedule = "Mo,Tu,We,Th,Fr"
time_zone = "US/Eastern"
def crawl(self, pub_date):
feed = self.parse_feed("http://www.girlswithslingshots.com/feed/")
for entry in feed.for_date(pub_date):
page = self.parse_page(entry.link)
url = page.src("img#cc-comic")
title = entry.title.replace("Girls with Slingshots - ", "")
text = page.title("img#cc-comic")
return CrawlerImage(url, title, text)
|
from comics.aggregator.crawler import CrawlerBase, CrawlerImage
from comics.core.comic_data import ComicDataBase
class ComicData(ComicDataBase):
name = "Girls With Slingshots"
language = "en"
url = "http://www.girlswithslingshots.com/"
start_date = "2004-09-30"
rights = "Danielle Corsetto"
class Crawler(CrawlerBase):
history_capable_days = 30
schedule = "Mo,Tu,We,Th,Fr"
time_zone = "US/Eastern"
def crawl(self, pub_date):
feed = self.parse_feed("http://www.girlswithslingshots.com/feed/")
for entry in feed.for_date(pub_date):
page = self.parse_page(entry.link)
url = page.src("img#comic")
title = entry.title.replace("Girls with Slingshots - ", "")
text = page.title("img#comic")
return CrawlerImage(url, title, text)
|
Add backup and restore functions
|
import sys
from corvus.client import Corvus
def backup(corvus, filename):
total_sectors = corvus.get_drive_capacity(1)
with open(filename, "wb") as f:
for i in range(total_sectors):
data = corvus.read_sector_512(1, i)
f.write(''.join([ chr(d) for d in data ]))
sys.stdout.write("\r%d bytes" % (i * 512))
sys.stdout.flush()
sys.stdout.write("\n")
def restore(corvus, filename):
total_sectors = corvus.get_drive_capacity(1)
with open(filename, "rb") as f:
for i in range(total_sectors):
data = [ ord(d) for d in f.read(512) ]
if len(data) < 512:
break
corvus.write_sector_512(1, i, data)
sys.stdout.write("\r%d bytes" % (i * 512))
sys.stdout.flush()
sys.stdout.write("\n")
def main():
corvus = Corvus()
corvus.init_drive()
backup(corvus, "image.bin")
if __name__ == "__main__":
main()
|
import sys
from corvus.client import Corvus
def main():
corvus = Corvus()
corvus.init_drive()
total_sectors = corvus.get_drive_capacity(1)
with open("image.bin", "wb") as f:
for i in range(total_sectors):
orig_data = corvus.read_sector_512(1, i)
corvus.write_sector_512(1, i, orig_data)
data = corvus.read_sector_512(1, i)
if data != orig_data: raise ValueError(i)
f.write(''.join([chr(d) for d in data]))
f.flush()
sys.stdout.write("\r%d bytes" % (i * 512))
sys.stdout.flush()
if __name__ == "__main__":
main()
|
Handle both possible JSON formats for data bag items.
This won't work if there is an actual data bag
item key called 'json_class', but that would be silly.
|
import abc
import collections
from chef.base import ChefObject, ChefQuery, ChefObjectMeta
class DataBagMeta(ChefObjectMeta, abc.ABCMeta):
"""A metaclass to allow DataBag to use multiple inheritance."""
class DataBag(ChefObject, ChefQuery):
__metaclass__ = DataBagMeta
url = '/data'
def _populate(self, data):
self.obj_class = DataBagItem
self.names = data.keys()
self.parent = self
class DataBagItem(ChefObject, collections.Mapping):
__metaclass__ = DataBagMeta
url = '/data'
attributes = {
'raw_data': dict,
}
def __init__(self, name, api=None, skip_load=False, parent=None):
self.bag = parent
super(DataBagItem, self).__init__(parent.name+'/'+name, api=api, skip_load=skip_load)
self.name = name
def _populate(self, data):
if 'json_class' in data:
self.raw_data = data['json_class']
else:
self.raw_data = data
def __len__(self):
return len(self.raw_data)
def __iter__(self):
return iter(self.raw_data)
def __getitem__(self, key):
return self.raw_data[key]
|
import abc
import collections
from chef.base import ChefObject, ChefQuery, ChefObjectMeta
class DataBagMeta(ChefObjectMeta, abc.ABCMeta):
"""A metaclass to allow DataBag to use multiple inheritance."""
class DataBag(ChefObject, ChefQuery):
__metaclass__ = DataBagMeta
url = '/data'
def _populate(self, data):
self.obj_class = DataBagItem
self.names = data.keys()
self.parent = self
class DataBagItem(ChefObject, collections.Mapping):
__metaclass__ = DataBagMeta
url = '/data'
def __init__(self, name, api=None, skip_load=False, parent=None):
self.bag = parent
super(DataBagItem, self).__init__(parent.name+'/'+name, api=api, skip_load=skip_load)
self.name = name
def _populate(self, data):
self.data = data
def __len__(self):
return len(self.data)
def __iter__(self):
return iter(self.data)
def __getitem__(self, key):
return self.data[key]
|
Add first type(array) check method.
|
// is.js 0.0.1
// Author Aras Atasaygin
;(function() {
// Baseline
// --------
// root object is window in the browser
var root = this;
// define is object, current version and configs
var is = {};
is.version = '0.0.1';
is.config = {};
// TODO: Add AMD and CommonJS support
// is object set global to the browser window
root.is = is;
// Type checks
// -----------
// is a given value array
is.array = Array.isArray || function(value) { // check native isArray first
return Object.prototype.toString.call(value) === '[object Array]';
}
// Presence checks
// ---------------
// Regexp checks
// -------------
// Environment checks
// ------------------
// Arithmetic checks
// -----------------
// Time checks
// -----------
// Array checks
// ------------
// Object checks
// -------------
// DOM checks
// ----------
// Syntax checks
// ----------
// String checks
// ----------
// ES6 checks
// ----------
}.call(this));
|
// is.js 0.0.1
// Author Aras Atasaygin
;(function() {
// Baseline
// --------
// root object is window in the browser
var root = this;
// define is object, current version and configs
var is = {};
is.version = '0.0.1';
is.config = {};
// TODO: Add AMD and CommonJS support
// is object set global to the browser window
root.is = is;
// Type checks
// -----------
// Test check
is.testCheck = function(a) {
console.log('test check ' + a);
}
// Presence checks
// ---------------
// Regexp checks
// -------------
// Environment checks
// ------------------
// Arithmetic checks
// -----------------
// Time checks
// -----------
// Array checks
// ------------
// Object checks
// -------------
// DOM checks
// ----------
// Syntax checks
// ----------
// String checks
// ----------
// ES6 checks
// ----------
}.call(this));
|
Store + Shipping + Menus
* Using new Store feature from Elcodi
* Added Store management in Admin
* Changed all definitions that was depending on such implementation
* Removed under construction logic and tests
* Removed menu fixtures
* Defined them as dynamic content. Some of them are generated dinamically, and
some of them statically.
* Added neede menu builders in every Admin bundle
* Changed the way menu is loaded in Admin
* Removed dependency with Configuration and Configuration annotation, in order to use
new implementation.
* Removed configuration elements
* Removed all `elcodi_config` twig extension usage
* Moved custom shipping logic from elcodi/elcodi to elcodi-plugins/*
* Added full repo inside Plugin folder
* Using new Shipping engine
* Updated some code in order to be compatible with Sf2.7 deprecations
Ready for Elcodi Beta! Auu! Auu!
|
<?php
/*
* This file is part of the Elcodi package.
*
* Copyright (c) 2014-2015 Elcodi.com
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* Feel free to edit as you please, and have fun.
*
* @author Marc Morera <yuhu@mmoreram.com>
* @author Aldo Chiecchia <zimage@tiscali.it>
* @author Elcodi Team <tech@elcodi.com>
*/
namespace Elcodi\Plugin\TwitterBundle;
use Symfony\Component\Console\Application;
use Symfony\Component\DependencyInjection\Extension\ExtensionInterface;
use Symfony\Component\HttpKernel\Bundle\Bundle;
use Elcodi\Component\Plugin\Interfaces\PluginInterface;
use Elcodi\Plugin\TwitterBundle\DependencyInjection\ElcodiTwitterExtension;
/**
* Class ElcodiTwitterBundle
*/
class ElcodiTwitterBundle extends Bundle implements PluginInterface
{
/**
* Returns the bundle's container extension.
*
* @return ExtensionInterface The container extension
*/
public function getContainerExtension()
{
return new ElcodiTwitterExtension();
}
/**
* Register Commands.
*
* Disabled as commands are registered as services.
*
* @param Application $application An Application instance
*
* @return null
*/
public function registerCommands(Application $application)
{
return null;
}
}
|
<?php
/*
* This file is part of the Elcodi package.
*
* Copyright (c) 2014-2015 Elcodi.com
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* Feel free to edit as you please, and have fun.
*
* @author Marc Morera <yuhu@mmoreram.com>
* @author Aldo Chiecchia <zimage@tiscali.it>
* @author Elcodi Team <tech@elcodi.com>
*/
namespace Elcodi\Plugin\TwitterBundle;
use Symfony\Component\Console\Application;
use Symfony\Component\DependencyInjection\Extension\ExtensionInterface;
use Symfony\Component\HttpKernel\Bundle\Bundle;
use Elcodi\Component\Plugin\Interfaces\PluginInterface;
use Elcodi\Plugin\TwitterBundle\DependencyInjection\ElcodiTwitterExtension;
/**
* Class ElcodiTwitterBundle
*/
class ElcodiTwitterBundle extends Bundle implements PluginInterface
{
/**
* Returns the bundle's container extension.
*
* @return ExtensionInterface The container extension
*/
public function getContainerExtension()
{
return new ElcodiTwitterExtension();
}
/**
* Register Commands.
*
* Disabled as commands are registered as services.
*
* @param Application $application An Application instance
*/
public function registerCommands(Application $application)
{
return null;
}
}
|
Add test for `play_track` function
New tests make sure that `play_track` raises a TrackError when an
invalid track is requested.
|
"""
test_itunes.py
Copyright © 2015 Alex Danoff. All Rights Reserved.
2015-08-02
This file tests the functionality provided by the itunes module.
"""
import unittest
from datetime import datetime
from itunes.itunes import parse_value, run_applescript, play_track
from itunes.exceptions import AppleScriptError, TrackError
class ITunesTests(unittest.TestCase):
"""
Test cases for iTunes functionality.
"""
def test_parse_value(self):
self.assertEquals(parse_value("10"), 10)
self.assertEquals(parse_value("1.0"), 1.0)
self.assertTrue(parse_value("true"))
self.assertFalse(parse_value("false"))
self.assertIsNone(parse_value(""))
self.assertIsNone(parse_value('""'))
self.assertIsNone(parse_value("missing value"))
self.assertEquals(parse_value('date: "Saturday, March 13, 2010 at ' \
'5:02:22 PM"'), datetime.fromtimestamp(1268517742))
def test_run_applescript(self):
self.assertRaises(AppleScriptError, run_applescript, "THIS IS INVALID" \
" APPLESCRIPT")
def test_play_track(self):
self.assertRaises(TrackError, play_track, "~~~~---`-`-`")
|
"""
test_itunes.py
Copyright © 2015 Alex Danoff. All Rights Reserved.
2015-08-02
This file tests the functionality provided by the itunes module.
"""
import unittest
from datetime import datetime
from itunes.itunes import parse_value, run_applescript
from itunes.exceptions import AppleScriptError
class ITunesTests(unittest.TestCase):
"""
Test cases for iTunes functionality.
"""
def test_parse_value(self):
self.assertEquals(parse_value("10"), 10)
self.assertEquals(parse_value("1.0"), 1.0)
self.assertTrue(parse_value("true"))
self.assertFalse(parse_value("false"))
self.assertIsNone(parse_value(""))
self.assertIsNone(parse_value('""'))
self.assertIsNone(parse_value("missing value"))
self.assertEquals(parse_value('date: "Saturday, March 13, 2010 at ' \
'5:02:22 PM"'), datetime.fromtimestamp(1268517742))
def test_run_applescript(self):
self.assertRaises(AppleScriptError, run_applescript, "THIS IS INVALID" \
" APPLESCRIPT")
|
Use start of tick so that all processing happens before MC.
Fixes #190
|
package invtweaks.forge;
import cpw.mods.fml.client.FMLClientHandler;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import cpw.mods.fml.common.gameevent.TickEvent;
import invtweaks.InvTweaks;
import net.minecraft.client.Minecraft;
public class ForgeClientTick {
private InvTweaks instance;
public ForgeClientTick(InvTweaks inst) {
instance = inst;
}
@SubscribeEvent
public void onTick(TickEvent.ClientTickEvent tick) {
if(tick.phase == TickEvent.Phase.START) {
Minecraft mc = FMLClientHandler.instance().getClient();
if(mc.theWorld != null) {
if(mc.currentScreen != null) {
instance.onTickInGUI(mc.currentScreen);
} else {
instance.onTickInGame();
}
}
}
}
}
|
package invtweaks.forge;
import cpw.mods.fml.client.FMLClientHandler;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import cpw.mods.fml.common.gameevent.TickEvent;
import invtweaks.InvTweaks;
import net.minecraft.client.Minecraft;
public class ForgeClientTick {
private InvTweaks instance;
public ForgeClientTick(InvTweaks inst) {
instance = inst;
}
@SubscribeEvent
public void onTick(TickEvent.ClientTickEvent tick) {
if(tick.phase == TickEvent.Phase.END) {
Minecraft mc = FMLClientHandler.instance().getClient();
if(mc.theWorld != null) {
if(mc.currentScreen != null) {
instance.onTickInGUI(mc.currentScreen);
} else {
instance.onTickInGame();
}
}
}
}
}
|
Fix 'Number too big' weirdness
|
#
# Sivakumar Kailasam and lowliet
#
import sublime, sublime_plugin
class RepeatMacroCommand(sublime_plugin.TextCommand):
def run(self, edit):
self.view.window().show_input_panel("Repeat count or [Enter] to run till end of file", "", self.__execute, None, None)
def __execute(self, text):
if not text.isdigit() and len(text) > 0:
print("Repeat Macro | Wrong number")
# elif len(text) > 0 and int(text) > (self.__get_last_line() - self.__get_current_line()):
# print("Repeat Macro | Number too big (bigger than number of lines in file)")
else:
current_line = self.__get_current_line()
last_line = current_line + int(text) if len(text) > 0 else self.__get_last_line()
for i in range(current_line, last_line):
self.view.run_command("run_macro")
def __get_current_line(self):
return self.view.rowcol(self.view.sel()[0].begin())[0] + 1
def __get_last_line(self):
return self.view.rowcol(self.view.size())[0] + 2
|
#
# Sivakumar Kailasam and lowliet
#
import sublime, sublime_plugin
class RepeatMacroCommand(sublime_plugin.TextCommand):
def run(self, edit):
self.view.window().show_input_panel("Repeat count or [Enter] to run till end of file", "", self.__execute, None, None)
def __execute(self, text):
if not text.isdigit() and len(text) > 0:
print("Repeat Macro | Wrong number")
elif len(text) > 0 and int(text) > (self.__get_last_line() - self.__get_current_line()):
print("Repeat Macro | Number too big (bigger than number of lines in file)")
else:
current_line = self.__get_current_line()
last_line = current_line + int(text) if len(text) > 0 else self.__get_last_line()
for i in range(current_line, last_line):
self.view.run_command("run_macro")
def __get_current_line(self):
return self.view.rowcol(self.view.sel()[0].begin())[0] + 1
def __get_last_line(self):
return self.view.rowcol(self.view.size())[0] + 2
|
Disable block dropping for destroyBlock().
|
package de.craften.plugins.educraft.luaapi.functions;
import de.craften.plugins.educraft.environment.LivingArmorStandBehavior;
import de.craften.plugins.educraft.luaapi.EduCraftApiFunction;
import org.bukkit.Material;
import org.bukkit.inventory.ItemStack;
import org.luaj.vm2.LuaValue;
import org.luaj.vm2.Varargs;
/**
* Lua API function to destroy the block in front of the entity.
*/
public class DestroyBlockFunction extends EduCraftApiFunction {
@Override
public Varargs execute(Varargs varargs) {
LivingArmorStandBehavior armorStand = (LivingArmorStandBehavior) getApi().getEntity().getBehaviors(LivingArmorStandBehavior.class).iterator().next();
armorStand.setItemInHand(new ItemStack(Material.DIAMOND_PICKAXE));
if (getApi().getEnvironment().contains(getApi().getBlockAhead().getLocation())) {
getApi().getBlockAhead().setType(Material.AIR);
}
return LuaValue.NIL;
}
@Override
protected void afterExecute() {
LivingArmorStandBehavior armorStand = (LivingArmorStandBehavior) getApi().getEntity().getBehaviors(LivingArmorStandBehavior.class).iterator().next();
armorStand.setItemInHand(null);
}
}
|
package de.craften.plugins.educraft.luaapi.functions;
import de.craften.plugins.educraft.environment.LivingArmorStandBehavior;
import de.craften.plugins.educraft.luaapi.EduCraftApiFunction;
import org.bukkit.Material;
import org.bukkit.inventory.ItemStack;
import org.luaj.vm2.LuaValue;
import org.luaj.vm2.Varargs;
/**
* Lua API function to destroy the block in front of the entity.
*/
public class DestroyBlockFunction extends EduCraftApiFunction {
@Override
public Varargs execute(Varargs varargs) {
LivingArmorStandBehavior armorStand = (LivingArmorStandBehavior) getApi().getEntity().getBehaviors(LivingArmorStandBehavior.class).iterator().next();
armorStand.setItemInHand(new ItemStack(Material.DIAMOND_PICKAXE));
if (getApi().getEnvironment().contains(getApi().getBlockAhead().getLocation())) {
getApi().getBlockAhead().breakNaturally();
}
return LuaValue.NIL;
}
@Override
protected void afterExecute() {
LivingArmorStandBehavior armorStand = (LivingArmorStandBehavior) getApi().getEntity().getBehaviors(LivingArmorStandBehavior.class).iterator().next();
armorStand.setItemInHand(null);
}
}
|
Add form classes for User and UserProfile
|
from django import forms
from django.contrib.auth.models import User
from rango.models import Category, Page, UserProfile
class CategoryForm(forms.ModelForm):
name = forms.CharField(max_length=128, help_text="Please enter a category name")
views = forms.IntegerField(widget=forms.HiddenInput(), initial = 0)
likes = forms.IntegerField(widget=forms.HiddenInput(), initial = 0)
slug = forms.CharField(widget=forms.HiddenInput(), required=False)
class Meta:
model = Category
# tuple specifying the classes we want to use
fields = ('name', )
class PageForm(forms.ModelForm):
title = forms.CharField(max_length=128, help_text="Please enter the title of the page.")
url = forms.URLField(max_length=200, help_text="Please enter the URL of the page.")
views = forms.IntegerField(widget=forms.HiddenInput(), initial=0)
class Meta:
model = Page
# excluding the category foreign key field from the form
exclude = ('category', 'slug')
class UserForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput(), help_text="Enter your password")
class Meta:
model = User
fields = ('username', 'email', 'password')
class UserProfileForm(forms.ModelForm):
class Meta:
model = UserProfile
fields = ('website', 'picture')
|
from django import forms
from rango.models import Category, Page
class CategoryForm(forms.ModelForm):
name = forms.CharField(max_length=128, help_text="Please enter a category name")
views = forms.IntegerField(widget=forms.HiddenInput(), initial = 0)
likes = forms.IntegerField(widget=forms.HiddenInput(), initial = 0)
slug = forms.CharField(widget=forms.HiddenInput(), required=False)
class Meta:
model = Category
# tuple specifying the classes we want to use
fields = ('name', )
class PageForm(forms.ModelForm):
title = forms.CharField(max_length=128, help_text="Please enter the title of the page.")
url = forms.URLField(max_length=200, help_text="Please enter the URL of the page.")
views = forms.IntegerField(widget=forms.HiddenInput(), initial=0)
class Meta:
model = Page
# excluding the category foreign key field from the form
exclude = ('category', 'slug')
|
Change class definitions from old style to new style
|
# encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""
from __future__ import unicode_literals
from ipaddress import ip_address
import itertools
import pytest
import six
from typepy import (
Typecode,
StrictLevel,
)
from typepy.type import IpAddress
nan = float("nan")
inf = float("inf")
class Test_IpAddress_is_type(object):
@pytest.mark.parametrize(
["value", "strict_level", "expected"],
list(itertools.product(
["", " ", six.MAXSIZE, str(six.MAXSIZE), inf, nan, None],
[StrictLevel.MIN, StrictLevel.MAX],
[False]
)) + list(itertools.product(
[
"127.0.0.1", "::1",
ip_address("127.0.0.1"), ip_address("::1"),
],
[StrictLevel.MIN, StrictLevel.MAX],
[True],
)))
def test_normal(self, value, strict_level, expected):
type_checker = IpAddress(value, strict_level=strict_level)
assert type_checker.is_type() == expected
assert type_checker.typecode == Typecode.IP_ADDRESS
|
# encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""
from __future__ import unicode_literals
from ipaddress import ip_address
import itertools
import pytest
import six
from typepy import (
Typecode,
StrictLevel,
)
from typepy.type import IpAddress
nan = float("nan")
inf = float("inf")
class Test_IpAddress_is_type:
@pytest.mark.parametrize(
["value", "strict_level", "expected"],
list(itertools.product(
["", " ", six.MAXSIZE, str(six.MAXSIZE), inf, nan, None],
[StrictLevel.MIN, StrictLevel.MAX],
[False]
)) + list(itertools.product(
[
"127.0.0.1", "::1",
ip_address("127.0.0.1"), ip_address("::1"),
],
[StrictLevel.MIN, StrictLevel.MAX],
[True],
)))
def test_normal(self, value, strict_level, expected):
type_checker = IpAddress(value, strict_level=strict_level)
assert type_checker.is_type() == expected
assert type_checker.typecode == Typecode.IP_ADDRESS
|
Load actions from correct path
|
import { connect } from 'react-redux'
import {
addTableRow,
editTableRow,
saveTableRow
} from '../actions/actions'
import InventoryTable from '../Components/InventoryTable'
const getMaltInventory = (tableRows) => {
return tableRows.filter((tableRow) => {
return tableRow.tableName === "maltInventory"
})
}
const mapStateToProps = state => {
return{
tableRows: getMaltInventory(state.tableRows)
}
}
const mapDispatchToProps = dispatch => {
return {
addRow: tableRow => {
dispatch(addTableRow(tableRow))
},
setEditing: id => {
dispatch(editTableRow(id))
},
saveTableRow: cells => {
dispatch(saveTableRow(cells))
}
}
}
const MaltInventory = connect(
mapStateToProps,
mapDispatchToProps
)(InventoryTable)
export default MaltInventory
|
import { connect } from 'react-redux'
import {
addTableRow,
editTableRow,
saveTableRow
} from '../actions'
import InventoryTable from '../Components/InventoryTable'
const getMaltInventory = (tableRows) => {
return tableRows.filter((tableRow) => {
return tableRow.tableName === "maltInventory"
})
}
const mapStateToProps = state => {
return{
tableRows: getMaltInventory(state.tableRows)
}
}
const mapDispatchToProps = dispatch => {
return {
addRow: tableRow => {
dispatch(addTableRow(tableRow))
},
setEditing: id => {
dispatch(editTableRow(id))
},
saveTableRow: cells => {
dispatch(saveTableRow(cells))
}
}
}
const MaltInventory = connect(
mapStateToProps,
mapDispatchToProps
)(InventoryTable)
export default MaltInventory
|
var-space-rule: Fix nested JSON obj false positive
When using compact form nested JSON object within a
Jinja2 context as shown in the following example:
set_fact:"{{ {'test': {'subtest': variable}} }}"
'variable}}' will raise a false positive [206] error.
This commit adds an intermediate step within 206
(VariableHasSpacesRule.py) rule to exclude nested
JSON object before matching for an actual error.
Fixes: #665
Signed-off-by: Simon Kheng <765fd267c62104898c4dfafd2f027edd838d8b13@gmail.com>
|
# Copyright (c) 2016, Will Thames and contributors
# Copyright (c) 2018, Ansible Project
from ansiblelint import AnsibleLintRule
import re
class VariableHasSpacesRule(AnsibleLintRule):
id = '206'
shortdesc = 'Variables should have spaces before and after: {{ var_name }}'
description = 'Variables should have spaces before and after: ``{{ var_name }}``'
severity = 'LOW'
tags = ['formatting']
version_added = 'v4.0.0'
variable_syntax = re.compile(r"{{.*}}")
bracket_regex = re.compile(r"{{[^{' -]|[^ '}-]}}")
def match(self, file, line):
if not self.variable_syntax.search(line):
return
line_exclude_json = re.sub(r"[^{]{'\w+': ?[^{]{.*?}}", "", line)
return self.bracket_regex.search(line_exclude_json)
|
# Copyright (c) 2016, Will Thames and contributors
# Copyright (c) 2018, Ansible Project
from ansiblelint import AnsibleLintRule
import re
class VariableHasSpacesRule(AnsibleLintRule):
id = '206'
shortdesc = 'Variables should have spaces before and after: {{ var_name }}'
description = 'Variables should have spaces before and after: ``{{ var_name }}``'
severity = 'LOW'
tags = ['formatting']
version_added = 'v4.0.0'
variable_syntax = re.compile(r"{{.*}}")
bracket_regex = re.compile(r"{{[^{' -]|[^ '}-]}}")
def match(self, file, line):
if not self.variable_syntax.search(line):
return
return self.bracket_regex.search(line)
|
Add test to show disk usage ratio per partition.
|
package com.alibaba.rocketmq.example.verify;
import com.alibaba.rocketmq.common.UtilAll;
import org.apache.commons.cli.*;
public class SelectPartition {
public static void main(String[] args) throws ParseException {
Options options = new Options();
Option option = new Option("p", "path", true, "Paths in CSV");
options.addOption(option);
CommandLineParser parser = new DefaultParser();
CommandLine commandLine = parser.parse(options, args);
if (!commandLine.hasOption('p')) {
HelpFormatter helpFormatter = new HelpFormatter();
helpFormatter.printHelp("Select Partition", options);
return;
}
String pathCSV = commandLine.getOptionValue("p");
UtilAll.selectPath(pathCSV);
double ratio = UtilAll.getDiskPartitionSpaceUsedPercent(pathCSV);
System.out.println(ratio);
}
}
|
package com.alibaba.rocketmq.example.verify;
import com.alibaba.rocketmq.common.UtilAll;
import org.apache.commons.cli.*;
public class SelectPartition {
public static void main(String[] args) throws ParseException {
Options options = new Options();
Option option = new Option("p", "path", true, "Paths in CSV");
options.addOption(option);
CommandLineParser parser = new DefaultParser();
CommandLine commandLine = parser.parse(options, args);
if (!commandLine.hasOption('p')) {
HelpFormatter helpFormatter = new HelpFormatter();
helpFormatter.printHelp("Select Partition", options);
return;
}
String pathCSV = commandLine.getOptionValue("p");
UtilAll.selectPath(pathCSV);
UtilAll.getDiskPartitionSpaceUsedPercent(pathCSV);
}
}
|
Initialize Parser with aliases at startup
|
package jfdi.logic;
import jfdi.logic.commands.InvalidCommand;
import jfdi.logic.interfaces.Command;
import jfdi.logic.interfaces.ILogic;
import jfdi.parser.InputParser;
import jfdi.parser.exceptions.InvalidInputException;
import jfdi.storage.apis.AliasDb;
import jfdi.storage.apis.MainStorage;
import jfdi.storage.exceptions.FilesReplacedException;
/**
* @author Liu Xinan
*/
public class ControlCenter implements ILogic {
private static ControlCenter ourInstance = new ControlCenter();
private ControlCenter() {
initStorage();
initParser();
}
public static ControlCenter getInstance() {
return ourInstance;
}
@Override
public void handleInput(String input) {
InputParser parser = InputParser.getInstance();
Command command;
try {
command = parser.parse(input);
} catch (InvalidInputException e) {
command = new InvalidCommand.Builder().build();
}
command.execute();
}
private void initStorage() {
try {
MainStorage.getInstance().initialize();
} catch (FilesReplacedException e) {
e.printStackTrace();
}
}
private void initParser() {
InputParser.getInstance().setAliases(AliasDb.getInstance().getAll());
}
}
|
package jfdi.logic;
import jfdi.logic.commands.InvalidCommand;
import jfdi.logic.interfaces.Command;
import jfdi.logic.interfaces.ILogic;
import jfdi.parser.InputParser;
import jfdi.parser.exceptions.InvalidInputException;
import jfdi.storage.apis.MainStorage;
import jfdi.storage.exceptions.FilesReplacedException;
/**
* @author Liu Xinan
*/
public class ControlCenter implements ILogic {
private static ControlCenter ourInstance = new ControlCenter();
private ControlCenter() {
try {
MainStorage.getInstance().initialize();
} catch (FilesReplacedException e) {
e.printStackTrace();
}
}
public static ControlCenter getInstance() {
return ourInstance;
}
@Override
public void handleInput(String input) {
InputParser parser = InputParser.getInstance();
Command command;
try {
command = parser.parse(input);
} catch (InvalidInputException e) {
command = new InvalidCommand.Builder().build();
}
command.execute();
}
}
|
Fix detection tests silent fails
CC @sourrust
|
'use strict';
var bluebird = require('bluebird');
var fs = bluebird.promisifyAll(require('fs'));
var hljs = require('../../build');
var path = require('path');
var utility = require('../utility');
function testAutoDetection(language) {
var languagePath = utility.buildPath('detect', language);
it('should have test for ' + language, function(done) {
fs.exists(languagePath, function(testExistence) {
testExistence.should.be.true;
done();
});
});
it('should be detected as ' + language, function(done) {
fs.readdirAsync(languagePath)
.map(function(example) {
var filename = path.join(languagePath, example);
return fs.readFileAsync(filename, 'utf-8');
})
.each(function(content) {
var expected = language,
actual = hljs.highlightAuto(content).language;
actual.should.equal(expected);
})
.done(function () {
done();
}, function (error) {
done(error);
});
});
}
describe('.highlightAuto', function() {
var languages = hljs.listLanguages();
languages.forEach(testAutoDetection);
});
|
'use strict';
var bluebird = require('bluebird');
var fs = bluebird.promisifyAll(require('fs'));
var hljs = require('../../build');
var path = require('path');
var utility = require('../utility');
function testAutoDetection(language) {
var languagePath = utility.buildPath('detect', language);
it('should have test for ' + language, function(done) {
fs.exists(languagePath, function(testExistence) {
testExistence.should.be.true;
done();
});
});
it('should be detected as ' + language, function(done) {
fs.readdirAsync(languagePath)
.map(function(example) {
var filename = path.join(languagePath, example);
return fs.readFileAsync(filename, 'utf-8');
})
.each(function(content) {
var expected = language,
actual = hljs.highlightAuto(content).language;
actual.should.equal(expected);
})
.finally(done);
});
}
describe('.highlightAuto', function() {
var languages = hljs.listLanguages();
languages.forEach(testAutoDetection);
});
|
Disable user activity recording for now
|
<?php
namespace OpenDominion\Providers;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
use OpenDominion\Events\UserRegisteredEvent;
use OpenDominion\Listeners\SendUserRegistrationNotification;
use OpenDominion\Listeners\Subscribers\AnalyticsSubscriber;
//use OpenDominion\Events\UserLoginEvent;
//use OpenDominion\Listeners\User\ActivityListener;
class EventServiceProvider extends ServiceProvider
{
/**
* The event listener mappings for the application.
*
* @var array
*/
protected $listen = [
UserRegisteredEvent::class => [
SendUserRegistrationNotification::class,
],
];
/**
* The subscriber classes to register.
*
* @var array
*/
protected $subscribe = [
// \OpenDominion\Listeners\User\Auth\ActivitySubscriber::class,
AnalyticsSubscriber::class,
];
/**
* Register any other events for your application.
*
* @return void
*/
public function boot()
{
parent::boot();
//
}
}
|
<?php
namespace OpenDominion\Providers;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
use OpenDominion\Events\UserRegisteredEvent;
use OpenDominion\Listeners\SendUserRegistrationNotification;
use OpenDominion\Listeners\Subscribers\AnalyticsSubscriber;
//use OpenDominion\Events\UserLoginEvent;
//use OpenDominion\Listeners\User\ActivityListener;
class EventServiceProvider extends ServiceProvider
{
/**
* The event listener mappings for the application.
*
* @var array
*/
protected $listen = [
UserRegisteredEvent::class => [
SendUserRegistrationNotification::class,
],
];
/**
* The subscriber classes to register.
*
* @var array
*/
protected $subscribe = [
\OpenDominion\Listeners\User\Auth\ActivitySubscriber::class,
AnalyticsSubscriber::class,
];
/**
* Register any other events for your application.
*
* @return void
*/
public function boot()
{
parent::boot();
//
}
}
|
Print usage info on no-args
Closes #5
|
var readJson = require('read-package-json');
var minimist = require('minimist');
var path = require('path');
var url = require('url');
var shields = require('../');
var argv = minimist(process.argv.slice(2));
// no args
if (!argv._.length) {
var usage = [
'Shield generator for your current project.',
'',
'Usage:',
' shields [travis] [gemnasium]'
];
console.log(usage.join('\n'));
return;
}
var p = path.resolve('./package.json');
readJson(p, function(error, pkg) {
if (error) {
throw error;
}
var slug = url.parse(pkg.repository.url).path.slice(1);
var links = [''];
argv._.forEach(function(service) {
var shield = shields(slug, service);
var status = service === 'travis' ? 'Build' : 'Dependency';
console.log('[![' + status + ' Status][' + service + '-svg]][' + service + ']');
links.push(' [' + service + ']: ' + shield.link);
links.push(' [' + service + '-svg]: ' + shield.svg);
});
console.log(links.join('\n'));
});
|
var readJson = require('read-package-json');
var minimist = require('minimist');
var path = require('path');
var url = require('url');
var shields = require('../');
var argv = minimist(process.argv.slice(2));
var p = path.resolve('./package.json');
readJson(p, function(error, pkg) {
if (error) {
throw error;
}
var slug = url.parse(pkg.repository.url).path.slice(1);
var links = [''];
argv._.forEach(function(service) {
var shield = shields(slug, service);
var status = service === 'travis' ? 'Build' : 'Dependency';
console.log('[![' + status + ' Status][' + service + '-svg]][' + service + ']');
links.push(' [' + service + ']: ' + shield.link);
links.push(' [' + service + '-svg]: ' + shield.svg);
});
console.log(links.join('\n'));
});
|
Fix presentation of toggle button in narrower screen resolutions
* Remove incorrect attribute escaping of translation exported to JS.
* Restore amp-validation-error-detail-toggle to webpack config.
|
/* global require, module, __dirname */
const path = require( 'path' );
module.exports = {
entry: {
'./assets/js/amp-blocks-compiled': './blocks/index.js',
'./assets/js/amp-block-editor-toggle-compiled': './assets/src/amp-block-editor-toggle',
'./assets/js/amp-validation-error-detail-toggle-compiled': './assets/src/amp-validation-error-detail-toggle',
'./assets/js/amp-validation-single-error-url-details-compiled': './assets/src/amp-validation-single-error-url-details'
},
output: {
path: path.resolve( __dirname ),
filename: '[name].js'
},
externals: {
'amp-validation-i18n': 'ampValidationI18n'
},
devtool: 'cheap-eval-source-map',
module: {
rules: [
{
test: /\.js$/,
exclude: /(node_modules)/,
use: {
loader: 'babel-loader'
}
}
]
}
};
|
/* global require, module, __dirname */
const path = require( 'path' );
module.exports = {
entry: {
'./assets/js/amp-blocks-compiled': './blocks/index.js',
'./assets/js/amp-block-editor-toggle-compiled': './assets/src/amp-block-editor-toggle',
'./assets/js/amp-validation-single-error-url-details-compiled': './assets/src/amp-validation-single-error-url-details'
},
output: {
path: path.resolve( __dirname ),
filename: '[name].js'
},
externals: {
'amp-validation-i18n': 'ampValidationI18n'
},
devtool: 'cheap-eval-source-map',
module: {
rules: [
{
test: /\.js$/,
exclude: /(node_modules)/,
use: {
loader: 'babel-loader'
}
}
]
}
};
|
Use consistent auth token variable
Other snippets for installations auth token is called `installationToken` using that here instead.
|
const firebase = require("firebase");
async function deleteInstallation() {
try {
// [START delete_installation]
await firebase.installations().delete();
// [END delete_installation]
} catch (err) {
console.error('Unable to delete installation: ', err);
}
}
async function getInstallationId() {
try {
// [START get_installation_id]
const installationId = await firebase.installations().getId();
console.log(installationId);
// [END get_installation_id]
} catch (err) {
console.error('Unable to get Installation ID: ', err);
}
}
async function getAuthenticationToken() {
try {
// [START get_auth_token]
const installationToken = await firebase.installations()
.getToken(/* forceRefresh */ true);
console.log(installationToken);
// [END get_auth_token]
} catch (err) {
console.error('Unable to get auth token: ', err);
}
}
async function setOnIdChangeHandler() {
try {
// [START set_id_change_handler]
await firebase.installations().onIdChange((newId) => {
console.log(newId);
// TODO: Handle new installation ID.
});
// [START set_id_change_handler]
} catch (err) {
console.error('Unable to set ID change handler: ', err);
}
}
|
const firebase = require("firebase");
async function deleteInstallation() {
try {
// [START delete_installation]
await firebase.installations().delete();
// [END delete_installation]
} catch (err) {
console.error('Unable to delete installation: ', err);
}
}
async function getInstallationId() {
try {
// [START get_installation_id]
const installationId = await firebase.installations().getId();
console.log(installationId);
// [END get_installation_id]
} catch (err) {
console.error('Unable to get Installation ID: ', err);
}
}
async function getAuthenticationToken() {
try {
// [START get_auth_token]
const authToken = await firebase.installations()
.getToken(/* forceRefresh */ true);
console.log(authToken);
// [END get_auth_token]
} catch (err) {
console.error('Unable to get auth token: ', err);
}
}
async function setOnIdChangeHandler() {
try {
// [START set_id_change_handler]
await firebase.installations().onIdChange((newId) => {
console.log(newId);
// TODO: Handle new installation ID.
});
// [START set_id_change_handler]
} catch (err) {
console.error('Unable to set ID change handler: ', err);
}
}
|
Fix promotion and approval for media fields
|
/*
* #%L
* BroadleafCommerce Framework
* %%
* Copyright (C) 2009 - 2014 Broadleaf Commerce
* %%
* 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.
* #L%
*/
package org.broadleafcommerce.openadmin.server.service.persistence.module.provider.extension;
import org.broadleafcommerce.common.extension.ExtensionHandler;
import org.broadleafcommerce.common.extension.ExtensionResultHolder;
import org.broadleafcommerce.common.extension.ExtensionResultStatusType;
import org.broadleafcommerce.common.media.domain.Media;
/**
* For internal usage. Allows extending API calls without subclassing the entity.
*
* @author Jeff Fischer
*/
public interface MediaFieldPersistenceProviderExtensionHandler extends ExtensionHandler {
ExtensionResultStatusType transformId(Media media, ExtensionResultHolder<Long> resultHolder);
public static final int DEFAULT_PRIORITY = Integer.MAX_VALUE;
}
|
/*
* #%L
* BroadleafCommerce Framework
* %%
* Copyright (C) 2009 - 2014 Broadleaf Commerce
* %%
* 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.
* #L%
*/
package org.broadleafcommerce.openadmin.server.service.persistence.module.provider.extension;
import org.broadleafcommerce.common.extension.ExtensionHandler;
import org.broadleafcommerce.common.extension.ExtensionResultHolder;
import org.broadleafcommerce.common.extension.ExtensionResultStatusType;
import org.broadleafcommerce.common.media.domain.Media;
import java.io.Serializable;
/**
* For internal usage. Allows extending API calls without subclassing the entity.
*
* @author Jeff Fischer
*/
public interface MediaFieldPersistenceProviderExtensionHandler extends ExtensionHandler {
ExtensionResultStatusType transformId(Media media, ExtensionResultHolder<Long> resultHolder);
public static final int DEFAULT_PRIORITY = Integer.MAX_VALUE;
}
|
Update setListener() warning for iOS.
|
/**
* Copyright 2012 The PlayN Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package playn.ios;
import playn.core.Keyboard;
import playn.core.PlayN;
import playn.core.util.Callback;
class IOSKeyboard implements Keyboard
{
@Override
public void setListener(Listener listener) {
PlayN.log().warn("iOS cannot generate keyboard events. Use Keyboard.getText() instead");
}
@Override
public boolean hasHardwareKeyboard() {
return false;
}
@Override
public void getText(TextType textType, String label, String initVal, Callback<String> callback) {
callback.onFailure(new UnsupportedOperationException("Not yet implemented."));
}
}
|
/**
* Copyright 2012 The PlayN Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package playn.ios;
import playn.core.Keyboard;
import playn.core.PlayN;
import playn.core.util.Callback;
class IOSKeyboard implements Keyboard
{
@Override
public void setListener(Listener listener) {
PlayN.log().warn("Keyboard not (currently) supported on iOS.");
}
@Override
public boolean hasHardwareKeyboard() {
return false;
}
@Override
public void getText(TextType textType, String label, String initVal, Callback<String> callback) {
callback.onFailure(new UnsupportedOperationException("Not yet implemented."));
}
}
|
Correct off by one error in trial count
|
#!/usr/bin/pyton
from __future__ import division
import random
initial_items = int(raw_input("how many items do you have at the start?: ") or "50")
iteration_days = int(raw_input("how many days do you have to multiple them?: ") or "100")
trials = 1000
def iterate_n_days(n, initial_items):
current_items = initial_items
for x in range(1, n):
new_items = 0;
for y in range (1,current_items):
if (random.random() < 0.01):
new_items =new_items +1
current_items=current_items+new_items;
print "day=",y," m=",current_items
return current_items
total_items_accumulated = 0
for y in range(trials):
total_items_accumulated += iterate_n_days(iteration_days,initial_items)
average_items_accumulated = total_items_accumulated / trials
print "average items after ", iteration_days, " days over", trials, " trials", average_items_accumulated
print "This assumes that you are moving items to new MUFG capsules when the capsule reaches 90 or so items and keeping your inventory from becoming overfull."
|
#!/usr/bin/pyton
from __future__ import division
import random
initial_items = int(raw_input("how many items do you have at the start?: ") or "50")
iteration_days = int(raw_input("how many days do you have to multiple them?: ") or "100")
trials = 1000
def iterate_n_days(n, initial_items):
current_items = initial_items
for x in range(1, n):
new_items = 0;
for y in range (1,current_items):
if (random.random() < 0.01):
new_items =new_items +1
current_items=current_items+new_items;
print "day=",y," m=",current_items
return current_items
total_items_accumulated = 0
for y in range(1,trials):
total_items_accumulated += iterate_n_days(iteration_days,initial_items)
average_items_accumulated = total_items_accumulated / trials
print "average items after ", iteration_days, " days over", trials, " trials", average_items_accumulated
print "This assumes that you are moving items to new MUFG capsules when the capsule reaches 90 or so items and keeping your inventory from becoming overfull."
|
Fix an integer out of range error with a migration to the transient integer bounds field (superseded by a float bounds field).
|
# -*- coding: utf-8 -*-
# Generated by Django 1.11.2 on 2017-06-27 19:14
from __future__ import unicode_literals
import django.contrib.postgres.fields.ranges
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('climate_data', '0025_auto_20170627_1850'),
]
operations = [
migrations.AddField(
model_name='datatype',
name='bounds_2',
field=django.contrib.postgres.fields.ranges.FloatRangeField(default='[-2147483648,2147483647)'),
),
migrations.AlterField(
model_name='datatype',
name='bounds',
field=django.contrib.postgres.fields.ranges.IntegerRangeField(default='[-2147483648,2147483646]'),
),
]
|
# -*- coding: utf-8 -*-
# Generated by Django 1.11.2 on 2017-06-27 19:14
from __future__ import unicode_literals
import django.contrib.postgres.fields.ranges
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('climate_data', '0025_auto_20170627_1850'),
]
operations = [
migrations.AddField(
model_name='datatype',
name='bounds_2',
field=django.contrib.postgres.fields.ranges.FloatRangeField(default='[-2147483648,2147483647)'),
),
migrations.AlterField(
model_name='datatype',
name='bounds',
field=django.contrib.postgres.fields.ranges.IntegerRangeField(default='[-2147483648,2147483647]'),
),
]
|
Remove newrelic from the project.
|
'use strict';
const common = require('../common/common');
const db = require('./db');
const logger = require('./logger');
const httpServer = require('./staticHttpServer');
const createWsServer = require('./createWsServer');
const PORT = Number(process.env.PORT || common.PORT);
process.title = 'jcm2018-server';
db.connect();
httpServer.listen(PORT, () => {
logger.info(`Server is listening on port ${PORT}.`);
});
const requestAllowed = wsRequest => {
/* webSocketRequest.origin is only advisory and Same origin policy cannot rely on it.
Rather, we disallow http in production and employ authentication-protected API. */
if (process.env.NODE_ENV && process.env.NODE_ENV === 'production') {
const proto = wsRequest.httpRequest.headers['x-forwarded-proto'];
if (proto === 'https') {
logger.debug(`Allowing originating protocol '${proto}' in production.`);
return true;
}
logger.debug(`Disallowing originating protocol '${proto}' in production.`);
logger.silly(JSON.stringify(wsRequest.httpRequest.headers));
return false;
}
logger.debug('Allowing any access, not in production.');
return true;
};
createWsServer({ httpServer, requestAllowed });
|
'use strict';
require('newrelic');
const common = require('../common/common');
const db = require('./db');
const logger = require('./logger');
const httpServer = require('./staticHttpServer');
const createWsServer = require('./createWsServer');
const PORT = Number(process.env.PORT || common.PORT);
process.title = 'jcm2018-server';
db.connect();
httpServer.listen(PORT, () => {
logger.info(`Server is listening on port ${PORT}.`);
});
const requestAllowed = wsRequest => {
/* webSocketRequest.origin is only advisory and Same origin policy cannot rely on it.
Rather, we disallow http in production and employ authentication-protected API. */
if (process.env.NODE_ENV && process.env.NODE_ENV === 'production') {
const proto = wsRequest.httpRequest.headers['x-forwarded-proto'];
if (proto === 'https') {
logger.debug(`Allowing originating protocol '${proto}' in production.`);
return true;
}
logger.debug(`Disallowing originating protocol '${proto}' in production.`);
logger.silly(JSON.stringify(wsRequest.httpRequest.headers));
return false;
}
logger.debug('Allowing any access, not in production.');
return true;
};
createWsServer({ httpServer, requestAllowed });
|
Remove the stupid fake spam detection crap why is this even here holy fuuuuuuuuu
|
package main
import (
"fmt"
)
func handleMessages(in <-chan Message) {
for {
msg := <-in
fmt.Println("Got message\n", msg, "\n")
}
}
func main() {
messages := make(chan Message)
server := NewServer(messages, SMTPConfig{
Ip4address: "127.0.0.1",
Ip4port: 25,
Domain: "local",
AllowedHosts: "localhost",
TrustedHosts: "127.0.0.1",
MaxRecipients: 100,
MaxIdleSeconds: 300,
MaxClients: 500,
MaxMessageBytes: 20480000,
PubKey: "",
PrvKey: "",
Debug: false,
DebugPath: "",
})
server.Start()
server.Drain()
}
|
package main
import (
"fmt"
)
func handleMessages(in <-chan Message) {
for {
msg := <-in
fmt.Println("Got message\n", msg, "\n")
}
}
func main() {
messages := make(chan Message)
server := NewServer(messages, SMTPConfig{
Ip4address: "127.0.0.1",
Ip4port: 25,
Domain: "local",
AllowedHosts: "localhost",
TrustedHosts: "127.0.0.1",
MaxRecipients: 100,
MaxIdleSeconds: 300,
MaxClients: 500,
MaxMessageBytes: 20480000,
PubKey: "",
PrvKey: "",
Debug: false,
DebugPath: "",
SpamRegex: "",
})
server.Start()
server.Drain()
}
|
Support return of live channel
|
<?php
/**
* @package api
* @subpackage objects.factory
*/
class KalturaEntryFactory
{
/**
* @param int $type
* @param bool $isAdmin
* @return KalturaBaseEntry
*/
static function getInstanceByType ($type, $isAdmin = false)
{
switch ($type)
{
case KalturaEntryType::MEDIA_CLIP:
$obj = new KalturaMediaEntry();
break;
case KalturaEntryType::MIX:
$obj = new KalturaMixEntry();
break;
case KalturaEntryType::PLAYLIST:
$obj = new KalturaPlaylist();
break;
case KalturaEntryType::DATA:
$obj = new KalturaDataEntry();
break;
case KalturaEntryType::LIVE_STREAM:
if($isAdmin)
{
$obj = new KalturaLiveStreamAdminEntry();
}
else
{
$obj = new KalturaLiveStreamEntry();
}
break;
case KalturaEntryType::LIVE_CHANNEL:
$obj = new KalturaLiveChannel();
break;
default:
$obj = KalturaPluginManager::loadObject('KalturaBaseEntry', $type);
if(!$obj)
$obj = new KalturaBaseEntry();
break;
}
return $obj;
}
}
|
<?php
/**
* @package api
* @subpackage objects.factory
*/
class KalturaEntryFactory
{
/**
* @param int $type
* @param bool $isAdmin
* @return KalturaBaseEntry
*/
static function getInstanceByType ($type, $isAdmin = false)
{
switch ($type)
{
case KalturaEntryType::MEDIA_CLIP:
$obj = new KalturaMediaEntry();
break;
case KalturaEntryType::MIX:
$obj = new KalturaMixEntry();
break;
case KalturaEntryType::PLAYLIST:
$obj = new KalturaPlaylist();
break;
case KalturaEntryType::DATA:
$obj = new KalturaDataEntry();
break;
case KalturaEntryType::LIVE_STREAM:
if($isAdmin)
{
$obj = new KalturaLiveStreamAdminEntry();
}
else
{
$obj = new KalturaLiveStreamEntry();
}
break;
default:
$obj = KalturaPluginManager::loadObject('KalturaBaseEntry', $type);
if(!$obj)
$obj = new KalturaBaseEntry();
break;
}
return $obj;
}
}
|
Use an actually random transcript; update stats immediately
|
import random
from django.core.management.base import BaseCommand
from django.contrib.auth.models import User
from mla_game.apps.accounts.models import Profile
from ...models import (
Transcript, TranscriptPhraseDownvote
)
from ...tasks import update_transcript_stats
class Command(BaseCommand):
help = 'Creates random votes for 5 phrases in a random transcript'
def handle(self, *args, **options):
users = User.objects.all()
transcript = Transcript.objects.random_transcript(in_progress=False).first()
phrases = transcript.phrases.all()[:5]
for user in users:
profile = Profile.objects.get(user=user)
profile.considered_phrases.add(
*[phrase.pk for phrase in phrases]
)
for phrase in phrases:
for user in users:
if random.choice([True, False]):
TranscriptPhraseDownvote.objects.create(
transcript_phrase=phrase,
user=user
)
update_transcript_stats(transcript)
|
import random
from django.core.management.base import BaseCommand
from django.contrib.auth.models import User
from mla_game.apps.accounts.models import Profile
from ...models import (
Transcript, TranscriptPhraseDownvote
)
class Command(BaseCommand):
help = 'Creates random votes for 5 phrases in a random transcript'
def handle(self, *args, **options):
users = User.objects.all()
transcript = Transcript.objects.random_transcript().first()
phrases = transcript.phrases.all()[:5]
for user in users:
profile = Profile.objects.get(user=user)
profile.considered_phrases.add(
*[phrase.pk for phrase in phrases]
)
for phrase in phrases:
for user in users:
if random.choice([True, False]):
TranscriptPhraseDownvote.objects.create(
transcript_phrase=phrase,
user=user
)
|
Add Bootstrap JavaScript to build
|
/* global require, module */
var EmberApp = require('ember-cli/lib/broccoli/ember-app');
var app = new EmberApp({
'ember-cli-jquery-ui': {
'theme': 'redmond'
},
'ember-cli-bootstrap-sass': {
'importBootstrapJS': true
},
vendorFiles: {
'handlebars.js': {
production: 'bower_components/handlebars/handlebars.js'
}
}
});
// Use `app.import` to add additional libraries to the generated
// output files.
//
// If you need to use different assets in different
// environments, specify an object as the first parameter. That
// object's keys should be the environment name and the values
// should be the asset to use in that environment.
//
// If the library that you are including contains AMD or ES6
// modules that you would like to import into your application
// please specify an object with the list of modules as keys
// along with the exports of each module as its value.
app.import('vendor/js/jquery-knob/jquery.knob.js');
module.exports = app.toTree();
|
/* global require, module */
var EmberApp = require('ember-cli/lib/broccoli/ember-app');
var app = new EmberApp({
'ember-cli-jquery-ui': {
'theme': 'redmond'
},
vendorFiles: {
'handlebars.js': {
production: 'bower_components/handlebars/handlebars.js'
}
}
});
// Use `app.import` to add additional libraries to the generated
// output files.
//
// If you need to use different assets in different
// environments, specify an object as the first parameter. That
// object's keys should be the environment name and the values
// should be the asset to use in that environment.
//
// If the library that you are including contains AMD or ES6
// modules that you would like to import into your application
// please specify an object with the list of modules as keys
// along with the exports of each module as its value.
app.import('vendor/js/jquery-knob/jquery.knob.js');
module.exports = app.toTree();
|
Update the PyPI version to 0.2.9
|
# -*- coding: utf-8 -*-
import os
from setuptools import setup
def read(fname):
try:
return open(os.path.join(os.path.dirname(__file__), fname)).read()
except:
return ''
setup(
name='todoist-python',
version='0.2.9',
packages=['todoist', 'todoist.managers'],
author='Doist Team',
author_email='info@todoist.com',
license='BSD',
description='todoist-python - The official Todoist Python API library',
long_description = read('README.md'),
install_requires=[
'requests',
],
# see here for complete list of classifiers
# http://pypi.python.org/pypi?%3Aaction=list_classifiers
classifiers=(
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python',
),
)
|
# -*- coding: utf-8 -*-
import os
from setuptools import setup
def read(fname):
try:
return open(os.path.join(os.path.dirname(__file__), fname)).read()
except:
return ''
setup(
name='todoist-python',
version='0.2.8',
packages=['todoist', 'todoist.managers'],
author='Doist Team',
author_email='info@todoist.com',
license='BSD',
description='todoist-python - The official Todoist Python API library',
long_description = read('README.md'),
install_requires=[
'requests',
],
# see here for complete list of classifiers
# http://pypi.python.org/pypi?%3Aaction=list_classifiers
classifiers=(
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python',
),
)
|
Make it apply only to variation databases
|
package org.ensembl.healthcheck.testcase.eg_core;
import java.sql.Connection;
import org.ensembl.healthcheck.DatabaseType;
import org.ensembl.healthcheck.Team;
/**
* @author mnuhn
*
* <p>
* Test for correctness of variation schemas, suggests a patch, if the schemas
* differ.
* </p>
*
*/
public class EGCompareVariationSchema extends EGAbstractCompareSchema {
public EGCompareVariationSchema() {
setTeamResponsible(Team.ENSEMBL_GENOMES);
}
@Override
public void types() {
addAppliesToType(DatabaseType.VARIATION);
}
@Override
protected String getDefinitionFileKey() {
return "variation_schema.file";
}
@Override
protected String getMasterSchemaKey() {
return "master.variation_schema";
}
@Override
protected boolean assertSchemaCompatibility(
Connection masterCon,
Connection checkCon
) {
return
assertSchemaTypesCompatible(masterCon, checkCon);
}
}
|
package org.ensembl.healthcheck.testcase.eg_core;
import java.sql.Connection;
import org.ensembl.healthcheck.DatabaseType;
import org.ensembl.healthcheck.Team;
/**
* @author mnuhn
*
* <p>
* Test for correctness of variation schemas, suggests a patch, if the schemas
* differ.
* </p>
*
*/
public class EGCompareVariationSchema extends EGAbstractCompareSchema {
public EGCompareVariationSchema() {
setTeamResponsible(Team.ENSEMBL_GENOMES);
addAppliesToType(DatabaseType.VARIATION);
}
@Override
protected String getDefinitionFileKey() {
return "variation_schema.file";
}
@Override
protected String getMasterSchemaKey() {
return "master.variation_schema";
}
@Override
protected boolean assertSchemaCompatibility(
Connection masterCon,
Connection checkCon
) {
return
assertSchemaTypesCompatible(masterCon, checkCon);
}
}
|
Change solution of get config from config file
|
var logger = require('log4js').getLogger('APP_LOG');
function verifiyMessage(config, receiver, message, botname, sender, password) {
//If miss message, return error message
if (message === undefined || message === null) {
return 'Bad Request: Missing message';
}
//If receiver not found, return error message
if (config.receivers[receiver] === undefined) {
return 'Bad Request: Wrong receiver name';
}
//If sender not found, return error message
if (config.senders[sender] === undefined) {
return 'Bad Request: Sender not found';
}
//If bot not found, return error message
if (config.bots[botname] === undefined) {
return 'Bad Request: Wrong bot name';
}
//If password missmatch, return error message
if (password !== config.senders[sender].password1 &&
password !== config.senders[sender].password2) {
return 'Bad Request: Password not match';
}
//If there are not any error, return Success
return 'Message verified';
}
module.exports = {
'verifiyMessage': verifiyMessage
};
|
var logger = require('log4js').getLogger('APP_LOG');
function verifiyMessage(config, receiver, message, botname, sender, password) {
//If miss message, return error message
if (message === undefined || message === null) {
return 'Bad Request: Missing message';
}
//If receiver not found, return error message
if (config.get(receiver) === undefined) {
return 'Bad Request: Wrong receiver name';
}
//If sender not found, return error message
if (config.get(sender) === undefined) {
return 'Bad Request: Sender not found';
}
//If bot not found, return error message
if (config.get(botname) === undefined) {
return 'Bad Request: Wrong bot name';
}
//If password missmatch, return error message
if (password !== config.get(sender).password1 &&
password !== config.get(sender).password2) {
return 'Bad Request: Password not match';
}
//If there are not any error, return Success
return 'Message verified';
}
module.exports = {
'verifiyMessage': verifiyMessage
};
|
Add missing py2py3 compatibility imports
|
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import torch
from . import Kernel
from gpytorch.lazy import DiagLazyVariable, ZeroLazyVariable
class WhiteNoiseKernel(Kernel):
def __init__(self, variances):
super(WhiteNoiseKernel, self).__init__()
self.register_buffer("variances", variances)
def forward(self, x1, x2):
if self.training:
return DiagLazyVariable(self.variances.unsqueeze(0))
elif x1.size(-2) == x2.size(-2) and x1.size(-2) == self.variances.size(-1) and torch.equal(x1, x2):
return DiagLazyVariable(self.variances.unsqueeze(0))
else:
return ZeroLazyVariable(x1.size(-3), x1.size(-2), x2.size(-2))
|
import torch
from . import Kernel
from gpytorch.lazy import DiagLazyVariable, ZeroLazyVariable
class WhiteNoiseKernel(Kernel):
def __init__(self, variances):
super(WhiteNoiseKernel, self).__init__()
self.register_buffer("variances", variances)
def forward(self, x1, x2):
if self.training:
return DiagLazyVariable(self.variances.unsqueeze(0))
elif x1.size(-2) == x2.size(-2) and x1.size(-2) == self.variances.size(-1) and torch.equal(x1, x2):
return DiagLazyVariable(self.variances.unsqueeze(0))
else:
return ZeroLazyVariable(x1.size(-3), x1.size(-2), x2.size(-2))
|
Fix changelog url open bug.
|
console.log( "=== simpread version load ===" )
import {browser} from 'browser';
/**
* Manifest.json version
*/
const version = browser.runtime.getManifest().version;
/**
* Verify version
*
* @param {string} local version
* @param {object} simpread data structure
*/
function Verify( curver, data ) {
/*
if ( curver == "1.0.0" ) {
data.option.pocket = { "consumer": "", "access": "" };
curver = "1.0.1";
}
if ( curver == "1.0.1" ) {
data.read.custom = "";
curver = "2.0.0";
}
*/
data.version = version;
return data;
}
/**
* Notify with type and version
*
* @param {string} type, include: firstload, update
* @param {string} ver, e.g. 1.0.0, 1.0.1
*/
function Notify( type, ver ) {
let str = type == "firstload" ? "安装" : "更新";
return `${str} 到最新版本 ${ver} ,详细请看 <a href="http://ksria.com/simpread/changelog.html" target="_blank">更新日志</a>`;
}
export {
version,
Verify,
Notify,
}
|
console.log( "=== simpread version load ===" )
import {browser} from 'browser';
/**
* Manifest.json version
*/
const version = browser.runtime.getManifest().version;
/**
* Verify version
*
* @param {string} local version
* @param {object} simpread data structure
*/
function Verify( curver, data ) {
/*
if ( curver == "1.0.0" ) {
data.option.pocket = { "consumer": "", "access": "" };
curver = "1.0.1";
}
if ( curver == "1.0.1" ) {
data.read.custom = "";
curver = "2.0.0";
}
*/
data.version = version;
return data;
}
/**
* Notify with type and version
*
* @param {string} type, include: firstload, update
* @param {string} ver, e.g. 1.0.0, 1.0.1
*/
function Notify( type, ver ) {
let str = type == "firstload" ? "安装" : "更新";
return `${str} 到最新版本 ${ver} ,详细请看 <a href="http://ksria.com/simpread/changelog.html">更新日志</a>`;
}
export {
version,
Verify,
Notify,
}
|
Change default compileMode to while typing
|
'use babel'
export default {
moieExec: {
type: 'string',
default: '/home/user/moie.jar',
description: 'Full path to moie-server'
},
javaExec: {
type: 'string',
default: '/usr/bin/java',
description: 'Full path to java; `whereis java`'
},
startServer: {
type: 'boolean',
default: false,
description: 'Start a new instance of moie-server if none running'
},
interface: {
type: "string",
default: "localhost"
},
port: {
type: "integer",
default: 9001
},
compileMode: {
type: 'string',
default: 'while typing',
enum: [
'on demand',
'while typing'
]
}
}
|
'use babel'
export default {
moieExec: {
type: 'string',
default: '/home/user/moie.jar',
description: 'Full path to moie-server'
},
javaExec: {
type: 'string',
default: '/usr/bin/java',
description: 'Full path to java; `whereis java`'
},
startServer: {
type: 'boolean',
default: false,
description: 'Start a new instance of moie-server if none running'
},
interface: {
type: "string",
default: "localhost"
},
port: {
type: "integer",
default: 9001
},
compileMode: {
type: 'string',
default: 'on demand',
enum: [
'on demand',
'while typing'
]
}
}
|
FIX: Remove empty field, hangover from access keys module
|
<?php
class FacebookMetadataSiteConfig extends DataExtension {
static $db = array(
'SkipToMainContentAccessKey' => 'VarChar(1)'
);
static $has_one = array(
'FacebookLogo' => 'Image'
);
public function updateCMSFields(FieldList $fields) {
$fields->renameField("SkipToMainContentAccessKey", _t('AccessKey.SKIP_TO_MAIN_CONTENT_ACCESS_KEY'));
$fields->addFieldToTab("Root.FacebookMetadata", new UploadField("FacebookLogo", _t('Facebook.METADATA_LOGO',
'Image that will show in facebook when linking to this site. The image should be a square of minimum size 200px')));
}
}
?>
|
<?php
class FacebookMetadataSiteConfig extends DataExtension {
static $db = array(
'SkipToMainContentAccessKey' => 'VarChar(1)'
);
static $has_one = array(
'FacebookLogo' => 'Image'
);
public function updateCMSFields(FieldList $fields) {
$tf2 = new TextField('SkipToMainContentAccessKey');
$tf2->setMaxLength(1);
$fields->addFieldToTab('Root.FacebookMetadata', $tf2);
$fields->renameField("SkipToMainContentAccessKey", _t('AccessKey.SKIP_TO_MAIN_CONTENT_ACCESS_KEY'));
$fields->addFieldToTab("Root.FacebookMetadata", new UploadField("FacebookLogo", _t('Facebook.METADATA_LOGO', 'Image that will show in facebook when linking to this site. The image should be a square')));
}
}
?>
|
Add sources to example scrape.
|
from pupa.scrape import Scraper
from pupa.models import Person, Organization
class PersonScraper(Scraper):
def get_people(self):
# committee
tech = Organization('Technology', classification='committee')
tech.add_post('Chairman', 'chairman')
tech.add_source('https://example.com')
yield tech
# subcommittee
ecom = Organization('Subcommittee on E-Commerce',
parent=tech,
classification='committee')
ecom.add_source('https://example.com')
yield ecom
p = Person('Paul Tagliamonte', district='6', chamber='upper',
party='Independent')
p.add_committee_membership('Finance')
p.add_membership(tech, role='chairman')
p.add_source('https://example.com')
yield p
|
from pupa.scrape import Scraper
from pupa.models import Person, Organization
class PersonScraper(Scraper):
def get_people(self):
# committee
tech = Organization('Technology', classification='committee')
tech.add_post('Chairman', 'chairman')
yield tech
# subcommittee
ecom = Organization('Subcommittee on E-Commerce',
parent=tech,
classification='committee')
yield ecom
p = Person('Paul Tagliamonte', district='6', chamber='upper',
party='Independent')
p.add_committee_membership('Finance')
p.add_membership(tech, role='chairman')
yield p
|
Fix python version syntax errors, bump minimum to 3.6 [no ci]
|
from setuptools import setup
import sys
import cozify
with open('README.rst') as file:
long_description = file.read()
setup(
name='cozify',
version=cozify.__version__,
python_requires='>=3.6',
author='artanicus',
author_email='python-cozify@nocturnal.fi',
url='https://github.com/Artanicus/python-cozify',
project_urls={"Documentation": "https://python-cozify.readthedocs.io/"},
description='Unofficial Python3 client library for the Cozify API.',
long_description=long_description,
license='MIT',
packages=['cozify'],
setup_requires=['pytest-runner'],
tests_require=['pytest'],
install_requires=['requests', 'absl-py'],
classifiers=[
'License :: OSI Approved :: MIT License',
'Development Status :: 3 - Alpha',
'Topic :: Utilities',
'Intended Audience :: Developers',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
'Programming Language :: Python :: 3.9'
]) # yapf: disable
|
from setuptools import setup
import sys
import cozify
with open('README.rst') as file:
long_description = file.read()
setup(
name='cozify',
version=cozify.__version__,
python_requires='>=3.5',
author='artanicus',
author_email='python-cozify@nocturnal.fi',
url='https://github.com/Artanicus/python-cozify',
project_urls={"Documentation": "https://python-cozify.readthedocs.io/"},
description='Unofficial Python3 client library for the Cozify API.',
long_description=long_description,
license='MIT',
packages=['cozify'],
setup_requires=['pytest-runner'],
tests_require=['pytest'],
install_requires=['requests', 'absl-py'],
classifiers=[
'License :: OSI Approved :: MIT License',
'Development Status :: 3 - Alpha',
'Topic :: Utilities',
'Intended Audience :: Developers',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.6'
'Programming Language :: Python :: 3.7'
'Programming Language :: Python :: 3.8'
'Programming Language :: Python :: 3.9'
]) # yapf: disable
|
Remove webpack dev server definition
|
let webpack = require('webpack');
let path = require('path');
module.exports = {
entry: ['babel-polyfill', './source/client.js'],
output: {
filename: 'index.js',
path: path.resolve(__dirname, 'public/')
},
plugins:[
new webpack.DefinePlugin({
'process.env':{
'NODE_ENV': JSON.stringify('production')
}
}),
new webpack.optimize.UglifyJsPlugin({
compress:{
warnings: false,
drop_console: true
}
})
],
module: {
loaders: [
{
test: /\.js$/,
exclude: /(node_modules)/,
loader: 'babel-loader',
query: {
presets: ['es2015', 'react']
}
}
]
}
};
|
let webpack = require('webpack');
let path = require('path');
module.exports = {
entry: ['babel-polyfill', './source/client.js'],
output: {
filename: 'index.js',
path: path.resolve(__dirname, 'public/')
},
plugins:[
new webpack.DefinePlugin({
'process.env':{
'NODE_ENV': JSON.stringify('production')
}
}),
new webpack.optimize.UglifyJsPlugin({
compress:{
warnings: false,
drop_console: true
}
})
],
module: {
loaders: [
{
test: /\.js$/,
exclude: /(node_modules)/,
loader: 'babel-loader',
query: {
presets: ['es2015', 'react']
}
}
]
}
};
/*
devServer: {
inline: true,
contentBase: './public',
port: 3000,
host: '0.0.0.0'
},
*/
|
Fix out redirection in python2
|
# -*- coding: utf-8 -*-
# vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright (C) 2017 GEM Foundation
#
# OpenQuake is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# OpenQuake is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with OpenQuake. If not, see <http://www.gnu.org/licenses/>.
from __future__ import print_function
from sys import stdout
try:
import __builtin__
except ImportError:
# Python 3
import builtins as __builtin__
def print(*args, **kwargs):
ret_str = ()
# when stdout is redirected to a file, python 2 uses ascii for the writer;
# python 3 uses what is configured in the system (i.e. 'utf-8')
str_encoding = stdout.encoding if stdout.encoding is not None else 'ascii'
for s in args:
ret_str = s.encode('utf-8').decode(str_encoding, 'ignore')
return __builtin__.print(ret_str, **kwargs)
|
# -*- coding: utf-8 -*-
# vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright (C) 2017 GEM Foundation
#
# OpenQuake is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# OpenQuake is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with OpenQuake. If not, see <http://www.gnu.org/licenses/>.
from __future__ import print_function
import sys
try:
import __builtin__
except ImportError:
# Python 3
import builtins as __builtin__
def print(*args, **kwargs):
conv_str = ()
for s in args:
conv_str = s.encode('utf-8').decode(sys.stdout.encoding, 'ignore')
return __builtin__.print(conv_str, **kwargs)
|
Add url mapping for github callback
|
"""ssoproject URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.9/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url
from django.contrib import admin
from sso import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$', views.main, name='main'),
url(r'^signin$', views.signin, name='signin'),
url(r'^signout$', views.signout, name='signout'),
url(r'^signup$', views.signup, name='signup'),
url(r'^verify$', views.verify, name='verify'),
url(r'^welcome$', views.welcome, name='welcome'),
url(r'^callback/github$', views.auth_with_github, name='auth with github'),
]
|
"""ssoproject URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.9/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url
from django.contrib import admin
from sso import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$', views.main, name='main'),
url(r'^signin$', views.signin, name='signin'),
url(r'^signout$', views.signout, name='signout'),
url(r'^signup$', views.signup, name='signup'),
url(r'^verify$', views.verify, name='verify'),
url(r'^welcome$', views.welcome, name='welcome'),
]
|
Fix problème de timezone.
Le client peut envoyer des dates en timezone UTC, on compare alors des objets equivalent mais pas dans la meme timezone.
Le hash d'un datetime ne doit pas dépendre de la timezone
|
<?php
namespace AppBundle\Entity;
use DateTime;
use Doctrine\ORM\Mapping as ORM;
use JMS\Serializer\Annotation\Type;
/**
* @ORM\Entity
* @ORM\Table(name="actualite_eleveur")
*/
class Actualite implements StatePersistableInterface
{
use Persistable;
/**
* @var string
* @ORM\Column(type="string", length=1000, nullable=true)
*/
private $contenu;
/**
* @var DateTime
* @Type("DateTime")
* @ORM\Column(type="datetime")
*/
private $date;
/**
* @param string $contenu
* @param DateTime $date
*/
public function __construct($contenu, DateTime $date)
{
$this->contenu = $contenu;
$this->date = $date;
}
/**
* @return string
*/
public function getContenu()
{
return $this->contenu;
}
/**
* @return DateTime
*/
public function getDate()
{
return $this->date;
}
public function hashCode()
{
return substr(md5(serialize([$this->contenu, $this->date->getTimestamp()])), 0, 16);
}
}
|
<?php
namespace AppBundle\Entity;
use DateTime;
use Doctrine\ORM\Mapping as ORM;
use JMS\Serializer\Annotation\Type;
/**
* @ORM\Entity
* @ORM\Table(name="actualite_eleveur")
*/
class Actualite implements StatePersistableInterface
{
use Persistable;
/**
* @var string
* @ORM\Column(type="string", length=1000, nullable=true)
*/
private $contenu;
/**
* @var DateTime
* @Type("DateTime")
* @ORM\Column(type="datetime")
*/
private $date;
/**
* @param string $contenu
* @param DateTime $date
*/
public function __construct($contenu, DateTime $date)
{
$this->contenu = $contenu;
$this->date = $date;
}
/**
* @return string
*/
public function getContenu()
{
return $this->contenu;
}
/**
* @return DateTime
*/
public function getDate()
{
return $this->date;
}
public function hashCode()
{
return substr(md5(serialize([$this->contenu, $this->date])), 0, 16);
}
}
|
Add sign out button to banner.
|
import React, { Component } from 'react';
import { Navbar } from 'react-bootstrap';
import SignOutButton from './SignOut';
import 'bootstrap/dist/css/bootstrap.css';
import './Banner.css';
class Banner extends Component {
render() {
return (
<Navbar bg="light" variant="light" sticky="top">
<Navbar.Brand bsPrefix="banner-title">PICTOPHONE</Navbar.Brand>
<Navbar.Toggle />
<Navbar.Collapse className="justify-content-end">
<Navbar.Text className="banner-log-out">
<SignOutButton />
</Navbar.Text>
</Navbar.Collapse>
</Navbar>
);
}
}
export default Banner;
|
import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import { Navbar } from 'react-bootstrap';
import 'bootstrap/dist/css/bootstrap.css';
import './Banner.css';
class Banner extends Component {
render() {
return (
<Navbar bg="light" variant="light" sticky="top">
<Navbar.Brand bsPrefix="banner-title">PICTOPHONE</Navbar.Brand>
<Navbar.Toggle />
<Navbar.Collapse className="justify-content-end">
<Navbar.Text className="banner-log-out">
<b>sherb</b> <Link to="/">(log out)</Link>
</Navbar.Text>
</Navbar.Collapse>
</Navbar>
);
}
}
export default Banner;
|
Rewrite header handling in websocket disconnect event
|
import WebSocketRequestContext from './WebSocketRequestContext.js'
import { parseHeaders, parseMultiValueHeaders } from '../../utils/index.js'
export default class WebSocketDisconnectEvent {
constructor(connectionId) {
this._connectionId = connectionId
}
create() {
// TODO FIXME not sure where the headers come from
const rawHeaders = ['Host', 'localhost', 'x-api-key', '', 'x-restapi', '']
const headers = parseHeaders(rawHeaders)
const multiValueHeaders = parseMultiValueHeaders(rawHeaders)
const requestContext = new WebSocketRequestContext(
'DISCONNECT',
'$disconnect',
this._connectionId,
).create()
return {
headers,
isBase64Encoded: false,
multiValueHeaders,
requestContext,
}
}
}
|
import WebSocketRequestContext from './WebSocketRequestContext.js'
// TODO this should be probably moved to utils, and combined with other header
// functions and utilities
function createMultiValueHeaders(headers) {
return Object.entries(headers).reduce((acc, [key, value]) => {
acc[key] = [value]
return acc
}, {})
}
export default class WebSocketDisconnectEvent {
constructor(connectionId) {
this._connectionId = connectionId
}
create() {
const headers = {
Host: 'localhost',
'x-api-key': '',
'x-restapi': '',
}
const multiValueHeaders = createMultiValueHeaders(headers)
const requestContext = new WebSocketRequestContext(
'DISCONNECT',
'$disconnect',
this._connectionId,
).create()
return {
headers,
isBase64Encoded: false,
multiValueHeaders,
requestContext,
}
}
}
|
Remove WKPB from geosearch - also change other test
|
import unittest
from datapunt_geosearch import config
from datapunt_geosearch import datasource
class TestBAGDataset(unittest.TestCase):
def test_query(self):
x = 120993
y = 485919
ds = datasource.BagDataSource(dsn=config.DSN_BAG)
results = ds.query(x, y)
self.assertEqual(len(results['features']), 6)
self.assertIn('distance', results['features'][0]['properties'])
def test_query_wgs84(self):
x = 52.36011
y = 4.88798
ds = datasource.BagDataSource(dsn=config.DSN_BAG)
results = ds.query(x, y, rd=False)
self.assertEqual(len(results['features']), 6)
if __name__ == '__main__':
unittest.main()
|
import unittest
from datapunt_geosearch import config
from datapunt_geosearch import datasource
class TestBAGDataset(unittest.TestCase):
def test_query(self):
x = 120993
y = 485919
ds = datasource.BagDataSource(dsn=config.DSN_BAG)
results = ds.query(x, y)
self.assertEqual(len(results['features']), 7)
self.assertIn('distance', results['features'][0]['properties'])
def test_query_wgs84(self):
x = 52.36011
y = 4.88798
ds = datasource.BagDataSource(dsn=config.DSN_BAG)
results = ds.query(x, y, rd=False)
self.assertEqual(len(results['features']), 6)
if __name__ == '__main__':
unittest.main()
|
Fix a bug where the correct link wasn't rendering
Previously, the href tag wasn't being set, at all. So the default route
was always being linked to, instead of the add new feed route. This
corrects that behaviour.
|
<?php
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
/**
* Short description for file
*
* Long description for file (if any)...
*
* PHP version 5.4
*
* @category CategoryName
* @package PackageName
* @author Matthew Setter <matthew@maltblue.com>
* @copyright 2014 Client/Author
* @see Enter if required
* @since File available since Release/Tag:
*/
namespace BabyMonitor\View\Helper;
use Zend\View\Helper\AbstractHelper;
/**
* Display a link to the manage action of the feeds
*
* @package BabyMonitor\View\Helper
* @return string
*/
class NoFeedsAvailable extends AbstractHelper
{
public function __invoke()
{
return sprintf(
"%s <a href='%s' title='%s'>%s</a>",
$this->view->translate("No available records."),
$this->view->url('feeds', array('action' => 'manage')),
$this->view->translate("add the first record"),
$this->view->translate("Care to add one?")
);
}
}
|
<?php
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
/**
* Short description for file
*
* Long description for file (if any)...
*
* PHP version 5.4
*
* @category CategoryName
* @package PackageName
* @author Matthew Setter <matthew@maltblue.com>
* @copyright 2014 Client/Author
* @see Enter if required
* @since File available since Release/Tag:
*/
namespace BabyMonitor\View\Helper;
use Zend\View\Helper\AbstractHelper;
/**
* Display a link to the manage action of the feeds
*
* @package BabyMonitor\View\Helper
* @return string
*/
class NoFeedsAvailable extends AbstractHelper
{
public function __invoke()
{
return sprintf(
"%s <a href='' title='%s'>%s</a>",
$this->view->translate("No available records."),
$this->view->url('feeds', array('action' => 'manage')),
$this->view->translate("add the first record"),
$this->view->translate("Care to add one?")
);
}
}
|
Add temp directory config setting
|
<?php
/**
* Config class
* Configuration for Skeleton\Core
*
* @author Christophe Gosiau <christophe@tigron.be>
* @author Gerry Demaret <gerry@tigron.be>
*/
namespace Skeleton\Core;
class Config {
/**
* Application directory
*
* @access public
* @var string $application_dir
*/
public static $application_dir = null;
/**
* Asset directory
*
* A directory which will be searched for media failes in addition to the
* application's media path
*
* @access public
* @var string $asset_dir
*/
public static $asset_dir = null;
/**
* Temp directory
*
* @access public
* @var string $tmp_dir
*/
public static $tmp_dir = null;
/**
* Name of the module that handles 403 errors
*
* @access public
* @var string $module_403
*/
public static $module_403 = null;
/**
* Name of the session
*
* @access public
* @var string $session_name
*/
public static $session_name = 'APP';
/**
* Name of the variable to store the sticky session object in
*
* @access public
* @var string $sticky_session_namse
*/
public static $sticky_session_name = 'sys_sticky_session';
}
|
<?php
/**
* Config class
* Configuration for Skeleton\Core
*
* @author Christophe Gosiau <christophe@tigron.be>
* @author Gerry Demaret <gerry@tigron.be>
*/
namespace Skeleton\Core;
class Config {
/**
* Application directory
*
* @access public
* @var string $application_dir
*/
public static $application_dir = null;
/**
* Asset directory
*
* A directory which will be searched for media failes in addition to the
* application's media path
*
* @access public
* @var string $asset_dir
*/
public static $asset_dir = null;
/**
* Name of the module that handles 403 errors
*
* @access public
* @var string $module_403
*/
public static $module_403 = null;
/**
* Name of the session
*
* @access public
* @var string $session_name
*/
public static $session_name = 'APP';
/**
* Name of the variable to store the sticky session object in
*
* @access public
* @var string $sticky_session_namse
*/
public static $sticky_session_name = 'sys_sticky_session';
}
|
Remove not needed fields from schema
|
const mongoose = require("mongoose");
const shortid = require("shortid");
const ProcessorItem = require("./ProcessorItem");
const originals = require("mongoose-originals");
const Address = new mongoose.Schema({
_id: {
type: String,
default: shortid.generate,
},
processor: {
type: ProcessorItem,
default: ProcessorItem,
},
name: String,
country: String,
postalCode: String,
createdAt: Date,
updatedAt: Date,
});
Address.plugin(originals, {
fields: [
"phone",
"company",
"name",
"country",
"locality",
"streetAddress",
"extendedAddress",
"postalCode",
],
});
module.exports = Address;
|
const mongoose = require("mongoose");
const shortid = require("shortid");
const ProcessorItem = require("./ProcessorItem");
const originals = require("mongoose-originals");
const Address = new mongoose.Schema({
_id: {
type: String,
default: shortid.generate,
},
processor: {
type: ProcessorItem,
default: ProcessorItem,
},
phone: String,
company: String,
name: String,
country: String,
locality: String,
streetAddress: String,
extendedAddress: String,
postalCode: String,
createdAt: Date,
updatedAt: Date,
});
Address.plugin(originals, {
fields: [
"phone",
"company",
"name",
"country",
"locality",
"streetAddress",
"extendedAddress",
"postalCode",
],
});
module.exports = Address;
|
Use const instead of var
|
#!/usr/bin/env node
const stdin = require('get-stdin')
const parseTorrent = require('../')
function usage () {
console.error('Usage: parse-torrent /path/to/torrent')
console.error(' parse-torrent magnet_uri')
console.error(' parse-torrent --stdin')
}
function error (err) {
console.error(err.message)
process.exit(1)
}
const arg = process.argv[2]
if (!arg) {
console.error('Missing required argument')
usage()
process.exit(1)
}
if (arg === '--stdin' || arg === '-') stdin.buffer().then(onTorrentId).catch(error)
else if (arg === '--version' || arg === '-v') console.log(require('../package.json').version)
else onTorrentId(arg)
function onTorrentId (torrentId) {
parseTorrent.remote(torrentId, function (err, parsedTorrent) {
if (err) return error(err)
delete parsedTorrent.info
delete parsedTorrent.infoBuffer
delete parsedTorrent.infoHashBuffer
console.log(JSON.stringify(parsedTorrent, undefined, 2))
})
}
|
#!/usr/bin/env node
var stdin = require('get-stdin')
var parseTorrent = require('../')
function usage () {
console.error('Usage: parse-torrent /path/to/torrent')
console.error(' parse-torrent magnet_uri')
console.error(' parse-torrent --stdin')
}
function error (err) {
console.error(err.message)
process.exit(1)
}
var arg = process.argv[2]
if (!arg) {
console.error('Missing required argument')
usage()
process.exit(1)
}
if (arg === '--stdin' || arg === '-') stdin.buffer().then(onTorrentId).catch(error)
else if (arg === '--version' || arg === '-v') console.log(require('../package.json').version)
else onTorrentId(arg)
function onTorrentId (torrentId) {
parseTorrent.remote(torrentId, function (err, parsedTorrent) {
if (err) return error(err)
delete parsedTorrent.info
delete parsedTorrent.infoBuffer
delete parsedTorrent.infoHashBuffer
console.log(JSON.stringify(parsedTorrent, undefined, 2))
})
}
|
Add translation messages to generated command
|
<?php
/**
*@file
* Contains \Drupal\AppConsole\Generator\CommandGenerator.
*/
namespace Drupal\AppConsole\Generator;
class CommandGenerator extends Generator
{
/**
* Generator Plugin Block
* @param string $module Module name
* @param string $command Command name
* @param string $class_name class name for plugin block
* @param array $container Access to container class
*/
public function generate($module, $command, $class_name, $container)
{
$command_key_root = 'command.' . str_replace(':','.', $command);
$parameters = [
'module_name' => $module,
'command' => $command,
'name' => [
'class' => $class_name,
],
'container' => $container,
'command_key_root' => $command_key_root
];
$messages[$command_key_root . '.description'] = 'Greet someone';
$messages[$command_key_root . '.arguments.name'] = 'Who do you want to greet?';
$messages[$command_key_root . '.options.yell'] = 'If set, the task will yell in uppercase letters';
$translator = $this->getTranslator();
$translator->writeTranslationsByModule($module, $messages);
$this->renderFile(
'module/src/Command/command.php.twig',
$this->getCommandPath($module).'/'.$class_name.'.php',
$parameters
);
}
}
|
<?php
/**
*@file
* Contains \Drupal\AppConsole\Generator\CommandGenerator.
*/
namespace Drupal\AppConsole\Generator;
class CommandGenerator extends Generator
{
/**
* Generator Plugin Block
* @param string $module Module name
* @param string $command Command name
* @param string $class_name class name for plugin block
* @param array $container Access to container class
*/
public function generate($module, $command, $class_name, $container)
{
$parameters = [
'module_name' => $module,
'command' => $command,
'name' => [
'class' => $class_name,
],
'container' => $container,
];
$this->renderFile(
'module/src/Command/command.php.twig',
$this->getCommandPath($module).'/'.$class_name.'.php',
$parameters
);
}
}
|
Use correct name for twit package
|
var Twit = Npm.require('twit');
PostTweetForFlight = {
post: function (flight) {
var tweetMessage = "✈✈✈ Flight #" + flight.number + " on @airstripio - http://airstrip.io/f/" + flight.date + " #digitalnomad";
this.twitterAPI.post('statuses/update', {status: tweetMessage}, function (err, data, response) {
console.log(data);
if (err)
console.log(err);
});
},
twitterAPI: new Twit({
consumer_key: 'kqAQtrale59wg7ymyppxnNQYY',
consumer_secret: process.env.TWITTER_CONSUMER_SECRET,
access_token: '3244714110-yatEahozepvmYNPIp7ODzjzS2MCYeG57D0QC6q1',
access_token_secret: process.env.TWITTER_ACCESS_TOKEN_SECRET
})
};
|
var Twit = Npm.require('Twit');
PostTweetForFlight = {
post: function (flight) {
var tweetMessage = "✈✈✈ Flight #" + flight.number + " on @airstripio - http://airstrip.io/f/" + flight.date + " #digitalnomad";
this.twitterAPI.post('statuses/update', {status: tweetMessage}, function (err, data, response) {
console.log(data);
if (err)
console.log(err);
});
},
twitterAPI: new Twit({
consumer_key: 'kqAQtrale59wg7ymyppxnNQYY',
consumer_secret: process.env.TWITTER_CONSUMER_SECRET,
access_token: '3244714110-yatEahozepvmYNPIp7ODzjzS2MCYeG57D0QC6q1',
access_token_secret: process.env.TWITTER_ACCESS_TOKEN_SECRET
})
};
|
Fix spacing in one more file
|
/*
* Zorbage: an algebraic data hierarchy for use in numeric processing.
*
* Copyright (C) 2016-2020 Barry DeZonia
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package nom.bdezonia.zorbage.algebra;
/**
*
* @author Barry DeZonia
*
*/
public interface Ring<T extends Ring<T,U>,U>
extends
AdditiveGroup<T,U>,
Multiplication<U>
{
}
|
/*
* Zorbage: an algebraic data hierarchy for use in numeric processing.
*
* Copyright (C) 2016-2020 Barry DeZonia
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package nom.bdezonia.zorbage.algebra;
/**
*
* @author Barry DeZonia
*
*/
public interface Ring<T extends Ring<T,U>,U>
extends
AdditiveGroup<T,U>,
Multiplication<U>
{
}
|
Revert "Remove apparently superfluous call to fill_recommended_bugs_cache."
This reverts commit 83ca8575e68fe9b2b59431e73e94b3247e3485d4.
|
import datetime
import logging
from django.core.management.base import BaseCommand
import mysite.profile.tasks
import mysite.search.models
import mysite.search.tasks
## FIXME: Move to a search management command?
def periodically_check_if_bug_epoch_eclipsed_the_cached_search_epoch():
logging.info("Checking if bug epoch eclipsed the cached search epoch")
cache_time = mysite.search.models.Epoch.get_for_string('search_cache')
bug_time = mysite.search.models.Epoch.get_for_string('search_cache')
if cache_time < bug_time:
mysite.search.tasks.clear_search_cache()
mysite.search.models.Epoch.bump_for_string('search_cache')
logging.info("Finished dealing with bug epoch vs. cached search epoch.")
class Command(BaseCommand):
help = "Run this once hourly for the OpenHatch profile app."
def handle(self, *args, **options):
mysite.profile.tasks.sync_bug_epoch_from_model_then_fill_recommended_bugs_cache()
mysite.profile.tasks.fill_recommended_bugs_cache()
# Every 4 hours, clear search cache
if (datetime.datetime.utcnow().hour % 4) == 0:
periodically_check_if_bug_epoch_eclipsed_the_cached_search_epoch()
|
import datetime
import logging
from django.core.management.base import BaseCommand
import mysite.profile.tasks
import mysite.search.models
import mysite.search.tasks
## FIXME: Move to a search management command?
def periodically_check_if_bug_epoch_eclipsed_the_cached_search_epoch():
logging.info("Checking if bug epoch eclipsed the cached search epoch")
cache_time = mysite.search.models.Epoch.get_for_string('search_cache')
bug_time = mysite.search.models.Epoch.get_for_string('search_cache')
if cache_time < bug_time:
mysite.search.tasks.clear_search_cache()
mysite.search.models.Epoch.bump_for_string('search_cache')
logging.info("Finished dealing with bug epoch vs. cached search epoch.")
class Command(BaseCommand):
help = "Run this once hourly for the OpenHatch profile app."
def handle(self, *args, **options):
mysite.profile.tasks.sync_bug_epoch_from_model_then_fill_recommended_bugs_cache()
# Every 4 hours, clear search cache
if (datetime.datetime.utcnow().hour % 4) == 0:
periodically_check_if_bug_epoch_eclipsed_the_cached_search_epoch()
|
Increase size of the alternative field
- NC-87
|
from __future__ import unicode_literals
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth.models import AbstractUser
from django.conf import settings
from uuidfield import UUIDField
class UuidMixin(models.Model):
"""
Mixin to identify models by UUID.
"""
class Meta(object):
abstract = True
uuid = UUIDField(auto=True, unique=True)
class User(UuidMixin, AbstractUser):
alternative_name = models.CharField(_('alternative name'), max_length=60, blank=True)
civil_number = models.CharField(_('civil number'), max_length=40, blank=True)
phone_number = models.CharField(_('phone number'), max_length=40, blank=True)
description = models.TextField(_('description'), blank=True)
organization = models.CharField(_('organization'), max_length=80, blank=True)
job_title = models.CharField(_('job title'), max_length=40, blank=True)
@python_2_unicode_compatible
class SshPublicKey(UuidMixin, models.Model):
"""
User public key.
Used for injection into VMs for remote access.
"""
user = models.ForeignKey(settings.AUTH_USER_MODEL, db_index=True)
name = models.CharField(max_length=50, blank=True)
public_key = models.TextField(max_length=2000)
def __str__(self):
return self.name
|
from __future__ import unicode_literals
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth.models import AbstractUser
from django.conf import settings
from uuidfield import UUIDField
class UuidMixin(models.Model):
"""
Mixin to identify models by UUID.
"""
class Meta(object):
abstract = True
uuid = UUIDField(auto=True, unique=True)
class User(UuidMixin, AbstractUser):
alternative_name = models.CharField(_('alternative name'), max_length=40, blank=True)
civil_number = models.CharField(_('civil number'), max_length=40, blank=True)
phone_number = models.CharField(_('phone number'), max_length=40, blank=True)
description = models.TextField(_('description'), blank=True)
organization = models.CharField(_('organization'), max_length=80, blank=True)
job_title = models.CharField(_('job title'), max_length=40, blank=True)
@python_2_unicode_compatible
class SshPublicKey(UuidMixin, models.Model):
"""
User public key.
Used for injection into VMs for remote access.
"""
user = models.ForeignKey(settings.AUTH_USER_MODEL, db_index=True)
name = models.CharField(max_length=50, blank=True)
public_key = models.TextField(max_length=2000)
def __str__(self):
return self.name
|
Add a Println-based test of expandPathnameTemplate
|
// Copyright (C) 2017 Damon Revoe. All rights reserved.
// Use of this source code is governed by the MIT
// license, which can be found in the LICENSE file.
package main
import (
"fmt"
"strings"
"testing"
)
func substTestCase(t *testing.T, node *verbatim, expected string) {
var result string
for {
result += node.text
if node.next == nil {
break
}
result += "[" + strings.Join(node.next.paramValues, ", ") + "]"
node = &node.next.continuation
}
if result != expected {
t.Error("Error: \"" + result + "\" != \"" + expected + "\"")
}
}
func TestSubst(t *testing.T) {
v := verbatim{"{Greetings}, {Who}!", nil}
v.subst("Who", "Human")
v.subst("Greetings", []string{"Hello", "Hi"})
substTestCase(t, &v, "[Hello, Hi], Human!")
v = verbatim{"{What}, {What} {Where}", nil}
v.subst("What", "Mirror")
v.subst("Where", "on the Wall")
substTestCase(t, &v, "Mirror, Mirror on the Wall")
}
func TestExpandPathnameTemplate(t *testing.T) {
fmt.Println(expandPathnameTemplate("{nil}{dir}/{name}.{ext}",
map[string]interface{}{
"nil": []string{},
"dir": []string{"red", "blue", "yellow", "green"},
"name": []string{"foo", "bar"},
"ext": []string{"js", "go", "rs"}}))
}
|
// Copyright (C) 2017 Damon Revoe. All rights reserved.
// Use of this source code is governed by the MIT
// license, which can be found in the LICENSE file.
package main
import (
"strings"
"testing"
)
func substTestCase(t *testing.T, node *verbatim, expected string) {
var result string
for {
result += node.text
if node.next == nil {
break
}
result += "[" + strings.Join(node.next.paramValues, ", ") + "]"
node = &node.next.continuation
}
if result != expected {
t.Error("Error: \"" + result + "\" != \"" + expected + "\"")
}
}
func TestSubst(t *testing.T) {
v := verbatim{"{Greetings}, {Who}!", nil}
v.subst("Who", "Human")
v.subst("Greetings", []string{"Hello", "Hi"})
substTestCase(t, &v, "[Hello, Hi], Human!")
v = verbatim{"{What}, {What} {Where}", nil}
v.subst("What", "Mirror")
v.subst("Where", "on the Wall")
substTestCase(t, &v, "Mirror, Mirror on the Wall")
}
|
Add requests as a dependency
|
from setuptools import setup, find_packages
setup(
name = 'plumbing',
version = '2.9.9',
description = 'Helps with plumbing-type programing in python.',
license = 'MIT',
url = 'http://github.com/xapple/plumbing/',
author = 'Lucas Sinclair',
author_email = 'lucas.sinclair@me.com',
packages = find_packages(),
install_requires = ['autopaths>=1.4.2', 'six', 'pandas', 'numpy', 'matplotlib',
'retry', 'tzlocal', 'packaging', 'requests'],
long_description = open('README.md').read(),
long_description_content_type = 'text/markdown',
include_package_data = True,
)
|
from setuptools import setup, find_packages
setup(
name = 'plumbing',
version = '2.9.9',
description = 'Helps with plumbing-type programing in python.',
license = 'MIT',
url = 'http://github.com/xapple/plumbing/',
author = 'Lucas Sinclair',
author_email = 'lucas.sinclair@me.com',
packages = find_packages(),
install_requires = ['autopaths>=1.4.2', 'six', 'pandas', 'numpy', 'matplotlib',
'retry', 'tzlocal', 'packaging'],
long_description = open('README.md').read(),
long_description_content_type = 'text/markdown',
include_package_data = True,
)
|
Make core activator extendable of Plugin class
|
package org.jetbrains.kotlin.core;
import static org.eclipse.core.resources.ResourcesPlugin.getWorkspace;
import org.eclipse.core.resources.IResourceChangeEvent;
import org.eclipse.core.resources.IResourceChangeListener;
import org.eclipse.core.runtime.Plugin;
import org.jetbrains.kotlin.core.builder.ResourceChangeListener;
import org.osgi.framework.BundleContext;
public class Activator extends Plugin {
private static Activator plugin;
private final IResourceChangeListener resourceChangeListener = new ResourceChangeListener();
public static final String PLUGIN_ID = "org.jetbrains.kotlin.core";
public Activator() {
plugin = this;
}
public static Activator getDefault() {
return plugin;
}
@Override
public void start(BundleContext bundleContext) throws Exception {
getWorkspace().addResourceChangeListener(resourceChangeListener, IResourceChangeEvent.POST_CHANGE);
super.start(bundleContext);
}
@Override
public void stop(BundleContext bundleContext) throws Exception {
getWorkspace().removeResourceChangeListener(resourceChangeListener);
plugin = null;
}
}
|
package org.jetbrains.kotlin.core;
import static org.eclipse.core.resources.ResourcesPlugin.getWorkspace;
import org.eclipse.core.resources.IResourceChangeEvent;
import org.eclipse.core.resources.IResourceChangeListener;
import org.jetbrains.kotlin.core.builder.ResourceChangeListener;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
public class Activator implements BundleActivator {
private static BundleContext context;
private final IResourceChangeListener resourceChangeListener = new ResourceChangeListener();
public static final String PLUGIN_ID = "org.jetbrains.kotlin.core";
static BundleContext getContext() {
return context;
}
@Override
public void start(BundleContext bundleContext) throws Exception {
Activator.context = bundleContext;
getWorkspace().addResourceChangeListener(resourceChangeListener, IResourceChangeEvent.POST_CHANGE);
}
@Override
public void stop(BundleContext bundleContext) throws Exception {
Activator.context = null;
getWorkspace().removeResourceChangeListener(resourceChangeListener);
}
}
|
Make calendar schedule options translatable
Signed-off-by: Julius Härtl <bf353fa4999f2f148afcc6d8ee6cb1ee74cc07c3@bitgrid.net>
|
<?php
style('dav', 'schedule-response');
?>
<div class="update">
<form action="" method="post">
<fieldset id="partStat">
<h2><?php p($l->t('Are you accepting the invitation?')); ?></h2>
<div id="selectPartStatForm">
<input type="radio" id="partStatAccept" name="partStat" value="ACCEPTED" checked />
<label for="partStatAccept">
<span><?php p($l->t('Accept')); ?></span>
</label>
<input type="radio" id="partStatTentative" name="partStat" value="TENTATIVE" />
<label for="partStatTentative">
<span><?php p($l->t('Tentative')); ?></span>
</label>
<input type="radio" class="declined" id="partStatDeclined" name="partStat" value="DECLINED" />
<label for="partStatDeclined">
<span><?php p($l->t('Decline')); ?></span>
</label>
</div>
</fieldset>
<fieldset id="more_options">
<input type="number" min="0" name="guests" placeholder="<?php p($l->t('Number of guests')); ?>" />
<input type="text" name="comment" placeholder="<?php p($l->t('Comment')); ?>" />
</fieldset>
<fieldset>
<input type="submit" value="<?php p($l->t('Save'));?>">
</fieldset>
</form>
</div>
|
<?php
style('dav', 'schedule-response');
?>
<div class="update">
<form action="" method="post">
<fieldset id="partStat">
<h2><?php p($l->t('Are you accepting the invitation?')); ?></h2>
<div id="selectPartStatForm">
<input type="radio" id="partStatAccept" name="partStat" value="ACCEPTED" checked />
<label for="partStatAccept">
<span><?php p($l->t('Accept')); ?></span>
</label>
<input type="radio" id="partStatTentative" name="partStat" value="TENTATIVE" />
<label for="partStatTentative">
<span><?php p($l->t('Tentative')); ?></span>
</label>
<input type="radio" class="declined" id="partStatDeclined" name="partStat" value="DECLINED" />
<label for="partStatDeclined">
<span><?php p($l->t('Decline')); ?></span>
</label>
</div>
</fieldset>
<fieldset id="more_options">
<input type="number" min="0" name="guests" placeholder="Guests" />
<input type="text" name="comment" placeholder="Comment" />
</fieldset>
<fieldset>
<input type="submit" value="<?php p($l->t('Save'));?>">
</fieldset>
</form>
</div>
|
Change props.route to actual value
|
import Component from 'react-pure-render/component';
import React, {PropTypes} from 'react';
// RouterHandler is back since suggested solution via React.cloneElement sucks.
// https://github.com/rackt/react-router/blob/master/UPGRADE_GUIDE.md#routehandler
// This is just syntax sugar for react-router 1.0.0 filtering children in props.
// https://github.com/este/este/issues/535
// Note React does not validate propTypes that are specified via cloneElement.
// It is recommended to make such propTypes optional.
// https://github.com/facebook/react/issues/4494#issuecomment-125068868
export default class RouterHandler extends Component {
static propTypes = {
children: PropTypes.object
};
render() {
const {children} = this.props;
// No children means nothing to render.
if (!children) return null;
// That makes nested routes working.
const propsForChildren = {...this.props};
delete propsForChildren.children;
// Delete route to prevent overwrite of correct value.
delete propsForChildren.route;
return React.cloneElement(children, propsForChildren);
}
}
|
import Component from 'react-pure-render/component';
import React, {PropTypes} from 'react';
// RouterHandler is back since suggested solution via React.cloneElement sucks.
// https://github.com/rackt/react-router/blob/master/UPGRADE_GUIDE.md#routehandler
// This is just syntax sugar for react-router 1.0.0 filtering children in props.
// https://github.com/este/este/issues/535
// Note React does not validate propTypes that are specified via cloneElement.
// It is recommended to make such propTypes optional.
// https://github.com/facebook/react/issues/4494#issuecomment-125068868
export default class RouterHandler extends Component {
static propTypes = {
children: PropTypes.object
};
render() {
const {children} = this.props;
// No children means nothing to render.
if (!children) return null;
// That makes nested routes working.
const propsWithoutChildren = {...this.props};
delete propsWithoutChildren.children;
return React.cloneElement(children, propsWithoutChildren);
}
}
|
Remove uneeded boot to make compatible with Laravel 5
Removing this because this package does not use any resources and thus
is not needed for Laravel 4.
|
<?php namespace SimpleSoftwareIO\QrCode;
/**
* Simple Laravel QrCode Generator
* A simple wrapper for the popular BaconQrCode made for Laravel.
*
* @link http://www.simplesoftware.io
* @author SimpleSoftware support@simplesoftware.io
*
*/
use Illuminate\Support\ServiceProvider;
class QrCodeServiceProvider extends ServiceProvider {
/**
* Indicates if loading of the provider is deferred.
*
* @var bool
*/
protected $defer = true;
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->app->bindShared('qrcode', function()
{
return new BaconQrCodeGenerator;
});
}
/**
* Get the services provided by the provider.
*
* @return array
*/
public function provides()
{
return array('qrcode');
}
}
|
<?php namespace SimpleSoftwareIO\QrCode;
/**
* Simple Laravel QrCode Generator
* A simple wrapper for the popular BaconQrCode made for Laravel.
*
* @link http://www.simplesoftware.io
* @author SimpleSoftware support@simplesoftware.io
*
*/
use Illuminate\Support\ServiceProvider;
class QrCodeServiceProvider extends ServiceProvider {
/**
* Indicates if loading of the provider is deferred.
*
* @var bool
*/
protected $defer = true;
/**
* Bootstrap the application events.
*
* @return void
*/
public function boot()
{
$this->package('simplesoftwareio/simple-qrcode');
}
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->app->bindShared('qrcode', function()
{
return new BaconQrCodeGenerator;
});
}
/**
* Get the services provided by the provider.
*
* @return array
*/
public function provides()
{
return array('qrcode');
}
}
|
Set connection driver as `postgres` by default.
|
import typeorm from 'typeorm';
import {
resetCache
} from '../src';
import User from './entity/UserSchema';
beforeEach(resetCache);
export const createConnection = () => {
const {TYPE, DB_HOST, DB_USER, DB_PASSWORD, DB_DATABASE} = process.env;
const driverOptions = {
type: TYPE || 'postgres',
port: 5432,
host: DB_HOST,
username: DB_USER,
password: DB_PASSWORD,
database: DB_DATABASE
};
return typeorm.createConnection({
driver: driverOptions,
entitySchemas: [User],
autoSchemaSync: true,
logging: {
logQueries: false,
logFailedQueryError: true,
}
})
.catch((error) => {
console.error('===> Error: ', error);
});
};
export const randint = (min = 1, max = 10000) => Math.floor(Math.random() * (max - min + 1)) + min;
|
import typeorm from 'typeorm';
import {
resetCache
} from '../src';
import User from './entity/UserSchema';
beforeEach(resetCache);
export const createConnection = () => {
const {TYPE, DB_HOST, DB_USER, DB_PASSWORD, DB_DATABASE} = process.env;
const driverOptions = {
type: TYPE,
port: 5432,
host: DB_HOST,
username: DB_USER,
password: DB_PASSWORD,
database: DB_DATABASE
};
return typeorm.createConnection({
driver: driverOptions,
entitySchemas: [User],
autoSchemaSync: true,
logging: {
logQueries: false,
logFailedQueryError: true,
}
})
.catch((error) => {
console.error('===> Error: ', error);
});
};
export const randint = (min = 1, max = 10000) => Math.floor(Math.random() * (max - min + 1)) + min;
|
Add missing space to jslint config line.
|
/*jslint forin: true */
var log = console.log;
exports.report = function(file, lint) {
log(file);
var options = [], key, value,
i, len, pad, e;
for (key in lint.options) {
value = lint.options[key];
options.push(key + ": " + value);
}
log("/*jslint " + options.join(", ") + " */");
if (!lint.ok) {
len = lint.errors.length;
for (i=0; i<len; i++) {
pad = '' + (i + 1);
while (pad.length < 3) {
pad = ' ' + pad;
}
e = lint.errors[i];
if (e) {
log(pad + ' ' + e.line + ',' + e.character + ': ' + e.reason);
log( ' ' + (e.evidence || '').replace(/^\s+|\s+$/, ""));
}
}
} else {
log("ok!");
}
return lint.ok;
};
|
/*jslint forin: true */
var log = console.log;
exports.report = function(file, lint) {
log(file);
var options = [], key, value,
i, len, pad, e;
for (key in lint.options) {
value = lint.options[key];
options.push(key + ": " + value);
}
log("/*jslint " + options.join(", ") + "*/");
if (!lint.ok) {
len = lint.errors.length;
for (i=0; i<len; i++) {
pad = '' + (i + 1);
while (pad.length < 3) {
pad = ' ' + pad;
}
e = lint.errors[i];
if (e) {
log(pad + ' ' + e.line + ',' + e.character + ': ' + e.reason);
log( ' ' + (e.evidence || '').replace(/^\s+|\s+$/, ""));
}
}
} else {
log("ok!");
}
return lint.ok;
};
|
Fix calls to request object
|
<!DOCTYPE html>
<html class="koowa-html" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<link rel="stylesheet"
href="<?php echo KObjectManager::getInstance()->getObject('request')->getBaseUrl('site'); ?>/media/koowa/com_koowa/css/bootstrap.min.css"
type="text/css"/>
<link rel="stylesheet"
href="<?php echo KObjectManager::getInstance()->getObject('request')->getBaseUrl('site'); ?>/templates/system/css/general.css"
type="text/css"/>
<jdoc:include type="head" />
</head>
<body class="koowa koowa_template">
<!--[if lte IE 8 ]>
<div class="old-ie"> <![endif]-->
<div class="koowa_template_container">
<jdoc:include type="message" />
<jdoc:include type="component" />
</div>
<!--[if lte IE 8 ]></div><![endif]-->
</body>
</html>
|
<!DOCTYPE html>
<html class="koowa-html" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<link rel="stylesheet" href="<?php echo $this->getObject('request')->getBaseUrl('site'); ?>/media/koowa/com_koowa/css/bootstrap.min.css"
type="text/css"/>
<link rel="stylesheet" href="<?php echo $this->getObject('request')->getBaseUrl('site'); ?>/templates/system/css/general.css" type="text/css"/>
<jdoc:include type="head" />
</head>
<body class="koowa koowa_template">
<!--[if lte IE 8 ]>
<div class="old-ie"> <![endif]-->
<div class="koowa_template_container">
<jdoc:include type="message" />
<jdoc:include type="component" />
</div>
<!--[if lte IE 8 ]></div><![endif]-->
</body>
</html>
|
storage: Add alias for VariantAnnotation.geneCancerAssociations to handle property renaming
|
/*
* Copyright 2015-2017 OpenCB
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.opencb.opencga.storage.core.variant.io.json.mixin;
import com.fasterxml.jackson.annotation.JsonAlias;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import org.opencb.biodata.models.variant.avro.GeneCancerAssociation;
import java.util.List;
/**
* Created by jacobo on 2/02/15.
*/
@JsonIgnoreProperties({"proteinSubstitutionScores", "variantTraitAssociation"})
public abstract class VariantAnnotationMixin {
@JsonAlias("cancerGeneAssociations")
public abstract List<GeneCancerAssociation> getGeneCancerAssociations();
}
|
/*
* Copyright 2015-2017 OpenCB
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.opencb.opencga.storage.core.variant.io.json.mixin;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
/**
* Created by jacobo on 2/02/15.
*/
@JsonIgnoreProperties({"proteinSubstitutionScores", "variantTraitAssociation"})
public abstract class VariantAnnotationMixin {
}
|
Use argparse for 4D to 3D
|
#!/usr/bin/env python
''' Tiny script to write 4D files in any format that we read (nifti,
analyze, MINC, at the moment, as nifti 3D files '''
import os
import nipy.externals.argparse as argparse
import nipy.io.imageformats as nii
def main():
# create the parser
parser = argparse.ArgumentParser()
# add the arguments
parser.add_argument('filename', type=str,
help='4D image filename')
# parse the command line
args = parser.parse_args()
img = nii.load(args.filename)
imgs = nii.four_to_three(img)
froot, ext = os.path.splitext(args.filename)
if ext in ('.gz', '.bz2'):
froot, ext = os.path.splitext(froot)
for i, img3d in enumerate(imgs):
fname3d = '%s_%04d.nii' % (froot, i)
nii.save(img3d, fname3d)
if __name__ == '__main__':
main()
|
#!/usr/bin/env python
''' Tiny script to write 4D files in any format that we read (nifti,
analyze, MINC, at the moment, as nifti 3D files '''
import os
import sys
import nipy.io.imageformats as nii
if __name__ == '__main__':
try:
fname = sys.argv[1]
except IndexError:
raise OSError('Expecting 4d image filename')
img = nii.load(fname)
imgs = nii.four_to_three(img)
froot, ext = os.path.splitext(fname)
if ext in ('.gz', '.bz2'):
froot, ext = os.path.splitext(froot)
for i, img3d in enumerate(imgs):
fname3d = '%s_%04d.nii' % (froot, i)
nii.save(img3d, fname3d)
|
Change yield from to yield
...because `yield from` doesn't actually work in that context.
|
#!/usr/bin/env php
<?php
require dirname(__DIR__) . '/vendor/autoload.php';
use Icicle\Coroutine;
use Icicle\Dns\Resolver\Resolver;
use Icicle\Loop;
if (2 > $argc) {
throw new InvalidArgumentException('Too few arguments provided. Usage: {DomainName}');
}
$domain = $argv[1];
$coroutine = Coroutine\create(function ($query, $timeout = 1) {
printf("Query: %s\n", $query);
$resolver = new Resolver();
$ips = yield $resolver->resolve($query, ['timeout' => $timeout]);
foreach ($ips as $ip) {
printf("IP: %s\n", $ip);
}
}, $domain);
$coroutine->capture(function (Exception $e) {
printf("Exception: %s\n", $e->getMessage());
});
Loop\run();
|
#!/usr/bin/env php
<?php
require dirname(__DIR__) . '/vendor/autoload.php';
use Icicle\Coroutine;
use Icicle\Dns\Resolver\Resolver;
use Icicle\Loop;
if (2 > $argc) {
throw new InvalidArgumentException('Too few arguments provided. Usage: {DomainName}');
}
$domain = $argv[1];
$coroutine = Coroutine\create(function ($query, $timeout = 1) {
printf("Query: %s\n", $query);
$resolver = new Resolver();
$ips = yield from $resolver->resolve($query, ['timeout' => $timeout]);
foreach ($ips as $ip) {
printf("IP: %s\n", $ip);
}
}, $domain);
$coroutine->capture(function (Exception $e) {
printf("Exception: %s\n", $e->getMessage());
});
Loop\run();
|
Add support for token query-param as fallback
|
'use strict';
var authHeader = require('auth-header');
var tokenUtils = require('./token');
module.exports = function (options) {
return function (req, res, next) {
var authorization = req.get('authorization') || req.query.token;
req.challenge = authorization;
var auth = authHeader.parse(authorization);
if (auth && auth.values && auth.values.length) {
auth = auth.values[0];
if (auth.scheme !== 'Bearer') {
return res.status(400).json('Invalid authorization scheme, expected \'Bearer\'');
}
tokenUtils.decode(auth.token, options, function (err, decoded) {
if (err) {
console.error(err);
req.authenticated = false;
req.authentication = err;
}
else {
req.authenticated = true;
req.authentication = decoded;
}
next();
});
}
else {
return res.status(400).json('Authorization token is missing');
}
};
};
|
'use strict';
var authHeader = require('auth-header');
var tokenUtils = require('./token');
module.exports = function (options) {
return function (req, res, next) {
var authorization = req.get('authorization');
req.challenge = authorization;
var auth = authHeader.parse(authorization);
if (auth && auth.values && auth.values.length) {
auth = auth.values[0];
if (auth.scheme !== 'Bearer') {
return res.status(400).json('Invalid authorization scheme, expected \'Bearer\'');
}
tokenUtils.decode(auth.token, options, function (err, decoded) {
if (err) {
console.error(err);
req.authenticated = false;
req.authentication = err;
}
else {
req.authenticated = true;
req.authentication = decoded;
}
next();
});
}
else {
return res.status(400).json('Authorization token is missing');
}
};
};
|
Check if there are encodings before trying to delete them
|
<?php namespace Bkwld\Decoy\Observers;
/**
* Trigger encoding or delete the encodings rows
*/
class Encoding {
/**
* Start a new encode if a new encodable file was uploaded
*
* @param Bkwld\Decoy\Models\Base $model
* @return void
*/
public function onSaving($model) {
if (!$this->isEncodable($model)) return;
foreach($model->getDirtyEncodableAttributes() as $attribute) {
// If the attribute has a value, encode the attribute
if ($model->getAttribute($attribute)) $model->encodeOnSave($attribute);
// Otherwise delete encoding references
else if ($encoding = $model->encoding($attribute)) $encoding->delete();
}
}
/**
* Delete all encodes on the model
*
* @param Bkwld\Decoy\Models\Base $model
* @return void
*/
public function onDeleted($model) {
if (!$this->isEncodable($model)) return;
$model->deleteEncodings();
}
/**
* Check if a model should be encoded
*
* @param Bkwld\Decoy\Models\Base $model
* @return boolean
*/
public function isEncodable($model) {
if (!method_exists($model, 'getDirtyEncodableAttributes')) return false;
if (is_a($model, 'Bkwld\Decoy\Models\Element')
&& $model->getAttribute('type') != 'video-encoder') return false;
return true;
}
}
|
<?php namespace Bkwld\Decoy\Observers;
/**
* Trigger encoding or delete the encodings rows
*/
class Encoding {
/**
* Start a new encode if a new encodable file was uploaded
*
* @param Bkwld\Decoy\Models\Base $model
* @return void
*/
public function onSaving($model) {
if (!$this->isEncodable($model)) return;
foreach($model->getDirtyEncodableAttributes() as $attribute) {
// If the attribute has a value, encode the attribute
if (isset($model->$attribute)) $model->encodeOnSave($attribute);
// Otherwise delete encoding references
else $model->encoding($attribute)->delete();
}
}
/**
* Delete all encodes on the model
*
* @param Bkwld\Decoy\Models\Base $model
* @return void
*/
public function onDeleted($model) {
if (!$this->isEncodable($model)) return;
$model->deleteEncodings();
}
/**
* Check if a model should be encoded
*
* @param Bkwld\Decoy\Models\Base $model
* @return boolean
*/
public function isEncodable($model) {
if (!method_exists($model, 'getDirtyEncodableAttributes')) return false;
if (is_a($model, 'Bkwld\Decoy\Models\Element')
&& $model->getAttribute('type') != 'video-encoder') return false;
return true;
}
}
|
Use range so code works with python 3
|
import re
def ensure_trailing_slash(mystr):
if not mystr.endswith('/'):
mystr = mystr + '/'
return mystr
def remove_trailing_slash(mystr):
if mystr.endswith('/'):
mystr = mystr[:-1]
return mystr
def split_s3_bucket_key(s3_path):
if s3_path.startswith('s3://'):
s3_path = s3_path[5:]
parts = s3_path.split('/')
return parts[0], '/'.join(parts[1:])
def underscore(mystr):
mystr = re.sub(r'([A-Z]+)([A-Z][a-z])', r'\1_\2', mystr)
mystr = re.sub(r'([a-z\d])([A-Z])', r'\1_\2', mystr)
mystr = mystr.replace('-', '_')
return mystr.lower()
def chunks(l, n):
for i in range(0, len(l), n):
yield l[i:i+n]
|
import re
def ensure_trailing_slash(mystr):
if not mystr.endswith('/'):
mystr = mystr + '/'
return mystr
def remove_trailing_slash(mystr):
if mystr.endswith('/'):
mystr = mystr[:-1]
return mystr
def split_s3_bucket_key(s3_path):
if s3_path.startswith('s3://'):
s3_path = s3_path[5:]
parts = s3_path.split('/')
return parts[0], '/'.join(parts[1:])
def underscore(mystr):
mystr = re.sub(r'([A-Z]+)([A-Z][a-z])', r'\1_\2', mystr)
mystr = re.sub(r'([a-z\d])([A-Z])', r'\1_\2', mystr)
mystr = mystr.replace('-', '_')
return mystr.lower()
def chunks(l, n):
for i in xrange(0, len(l), n):
yield l[i:i+n]
|
Fix - in cli mode PROJECT_ROOT was not empty when script was run not from project.
|
<?
define('E_REPORTING', E_ALL & ~E_NOTICE);
error_reporting(E_REPORTING);
ini_set('display_errors', 'On');
define('TIME_START', microtime(true));
define('ROOT', dirname(dirname(__FILE__)));
define('CONFIG_ROOT', dirname(dirname(dirname(__FILE__))).'/config');
define('PROJECT', strtolower(isset($_ENV["PROJECT"]) ? $_ENV["PROJECT"] : null));
define('PROJECT_ROOT', PROJECT ? dirname(ROOT).'/appers/'.PROJECT : null);
define('PROJECTS_ROOT', dirname(ROOT).'/appers');
define('EXEC_PATH', __FILE__);
require ROOT.'/lib/application/loader.php';
loader::init();
config::init();
if(config::get('restartWorkersOnChange')) {
if(loader::isFilesChanged()) {
bg::restartWorkers();
}
}
cli::run(array_slice($argv,1));
|
<?
define('E_REPORTING', E_ALL & ~E_NOTICE);
error_reporting(E_REPORTING);
ini_set('display_errors', 'On');
define('TIME_START', microtime(true));
define('ROOT', dirname(dirname(__FILE__)));
define('CONFIG_ROOT', dirname(dirname(dirname(__FILE__))).'/config');
define('PROJECT', strtolower(isset($_ENV["PROJECT"]) ? $_ENV["PROJECT"] : null));
define('PROJECT_ROOT', dirname(ROOT).'/appers/'.PROJECT);
define('PROJECTS_ROOT', dirname(ROOT).'/appers');
define('EXEC_PATH', __FILE__);
require ROOT.'/lib/application/loader.php';
loader::init();
config::init();
if(config::get('restartWorkersOnChange')) {
if(loader::isFilesChanged()) {
bg::restartWorkers();
}
}
cli::run(array_slice($argv,1));
|
Add requirement for fork version of gnupg
|
#!/usr/bin/env python
from setuptools import setup, find_packages
import sys
with open('README.md') as f:
readme = f.read()
install_requires = [
'gnupg>=2.0.2',
'seria',
'python-gnupg'
]
setup(
name='figgypy',
version='0.3.dev',
description='Simple configuration tool. Get config from yaml, json, or xml.',
long_description=readme,
author='Herkermer Sherwood',
author_email='theherk@gmail.com',
url='https://github.com/theherk/figgypy',
download_url='https://github.com/theherk/figgypy/archive/0.3.dev.zip',
packages=find_packages(),
platforms=['all'],
license='MIT',
install_requires=install_requires,
classifiers=[
'Development Status :: 4 - Beta',
'License :: Other/Proprietary License',
'License :: OSI Approved :: MIT License',
'Environment :: Console',
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'Operating System :: MacOS :: MacOS X',
'Operating System :: Unix',
'Operating System :: POSIX',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Topic :: Utilities',
],
)
|
#!/usr/bin/env python
from setuptools import setup, find_packages
import sys
with open('README.md') as f:
readme = f.read()
install_requires = [
'seria',
'python-gnupg'
]
setup(
name='figgypy',
version='0.3.dev',
description='Simple configuration tool. Get config from yaml, json, or xml.',
long_description=readme,
author='Herkermer Sherwood',
author_email='theherk@gmail.com',
url='https://github.com/theherk/figgypy',
download_url='https://github.com/theherk/figgypy/archive/0.3.dev.zip',
packages=find_packages(),
platforms=['all'],
license='MIT',
install_requires=install_requires,
classifiers=[
'Development Status :: 4 - Beta',
'License :: Other/Proprietary License',
'License :: OSI Approved :: MIT License',
'Environment :: Console',
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'Operating System :: MacOS :: MacOS X',
'Operating System :: Unix',
'Operating System :: POSIX',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Topic :: Utilities',
],
)
|
Make sliding token lifetime defaults a bit more conservative
|
from __future__ import unicode_literals
from datetime import timedelta
from django.conf import settings
from rest_framework.settings import APISettings
USER_SETTINGS = getattr(settings, 'SIMPLE_JWT', None)
DEFAULTS = {
'AUTH_HEADER_TYPE': 'Bearer',
'USER_ID_FIELD': 'id',
'USER_ID_CLAIM': 'user_id',
'TOKEN_TYPE_CLAIM': 'token_type',
'SLIDING_REFRESH_EXP_CLAIM': 'refresh_exp',
'SLIDING_TOKEN_LIFETIME': timedelta(minutes=5),
'SLIDING_TOKEN_REFRESH_LIFETIME': timedelta(days=1),
'ACCESS_TOKEN_LIFETIME': timedelta(minutes=5),
'REFRESH_TOKEN_LIFETIME': timedelta(days=1),
'SECRET_KEY': settings.SECRET_KEY,
# Undocumented settings. Changing these may lead to unexpected behavior.
# Make sure you know what you're doing. These might become part of the
# public API eventually but that would require some adjustments.
'AUTH_TOKEN_CLASS': 'rest_framework_simplejwt.tokens.AccessToken',
'TOKEN_BACKEND_CLASS': 'rest_framework_simplejwt.backends.PythonJOSEBackend',
'ALGORITHM': 'HS256',
}
IMPORT_STRING_SETTINGS = (
'AUTH_TOKEN_CLASS',
'TOKEN_BACKEND_CLASS',
)
api_settings = APISettings(USER_SETTINGS, DEFAULTS, IMPORT_STRING_SETTINGS)
|
from __future__ import unicode_literals
from datetime import timedelta
from django.conf import settings
from rest_framework.settings import APISettings
USER_SETTINGS = getattr(settings, 'SIMPLE_JWT', None)
DEFAULTS = {
'AUTH_HEADER_TYPE': 'Bearer',
'USER_ID_FIELD': 'id',
'USER_ID_CLAIM': 'user_id',
'TOKEN_TYPE_CLAIM': 'token_type',
'SLIDING_REFRESH_EXP_CLAIM': 'refresh_exp',
'SLIDING_TOKEN_LIFETIME': timedelta(days=1),
'SLIDING_TOKEN_REFRESH_LIFETIME': timedelta(days=3),
'ACCESS_TOKEN_LIFETIME': timedelta(minutes=5),
'REFRESH_TOKEN_LIFETIME': timedelta(days=1),
'SECRET_KEY': settings.SECRET_KEY,
# Undocumented settings. Changing these may lead to unexpected behavior.
# Make sure you know what you're doing. These might become part of the
# public API eventually but that would require some adjustments.
'AUTH_TOKEN_CLASS': 'rest_framework_simplejwt.tokens.AccessToken',
'TOKEN_BACKEND_CLASS': 'rest_framework_simplejwt.backends.PythonJOSEBackend',
'ALGORITHM': 'HS256',
}
IMPORT_STRING_SETTINGS = (
'AUTH_TOKEN_CLASS',
'TOKEN_BACKEND_CLASS',
)
api_settings = APISettings(USER_SETTINGS, DEFAULTS, IMPORT_STRING_SETTINGS)
|
Send to server as json
|
var App = window.App || {};
App.Create = (function ($, w) {
'use strict';
function Create ($el, options) {
this.options = $.extend({}, Create.defaults, options);
$($el).midgardCreate();
w.Backbone.sync = this.sync.bind(this);
}
// Override Backbone.sync
Create.prototype.sync = function(method, model, options) {
// only update implemented
if (method !== 'update') {
return options.error(model);
}
this.id = Create.extractId(model.id);
$.ajax({
url: '/pages/' + this.id,
type: 'put',
data: model.toJSON(),
dataType: 'json',
success: function () {
options.success(model);
},
error: function () {
options.error(model);
}
});
};
Create.extractId = function(id) {
return parseInt(id.replace(/<\/pages\/(\d+)>/, '$1'), 10);
};
Create.defauts = {
};
return Create;
}(jQuery, window));
|
var App = window.App || {};
App.Create = (function ($, w) {
'use strict';
function Create ($el, options) {
this.options = $.extend({}, Create.defaults, options);
$($el).midgardCreate();
w.Backbone.sync = this.sync.bind(this);
}
// Override Backbone.sync
Create.prototype.sync = function(method, model, options) {
// only update implemented
if (method !== 'update') {
return options.error(model);
}
this.id = Create.extractId(model.id);
$.ajax({
url: '/pages/' + this.id,
type: 'put',
data: model.attributes,
success: function () {
options.success(model);
},
error: function () {
options.error(model);
}
});
};
Create.extractId = function(id) {
return parseInt(id.replace(/<\/pages\/(\d+)>/, '$1'), 10);
};
Create.defauts = {
};
return Create;
}(jQuery, window));
|
Disable the "read and upload" step (not working yet)
|
module.exports = {
model: 'step_type',
data: [
{
id: 1,
name: 'Announcement Message',
description: 'No response from the user to move the next step'
},
{
id: 2,
name: 'Question Step',
description: 'Owner must enter a question and the confirmation word that the user must enter to move on in the Flow'
},
{
id: 3,
name: 'Multiple Choice Step',
description: 'Owner specifies a list of possible options, end user replies with 1,2,3 or 4 etc'
},
{
id: 4,
name: 'Upload Document Step',
description: 'Owner specifies some instructions and the end user must upload a document to complete the step'
},
{
id: 5,
name: 'Read Document Step',
description: 'Owner must upload a document and the end user must read it'
},
// {
// id: 6,
// name: 'Read & Upload Document Step',
// description: 'Owner upload a document and the end user must read it and upload a new one to complete the step'
// },
{
id: 7,
name: 'People to meet',
description: 'A Spark room would be created between the person being onboarded and the people specified'
},
]
};
|
module.exports = {
model: 'step_type',
data: [
{
id: 1,
name: 'Announcement Message',
description: 'No response from the user to move the next step'
},
{
id: 2,
name: 'Question Step',
description: 'Owner must enter a question and the confirmation word that the user must enter to move on in the Flow'
},
{
id: 3,
name: 'Multiple Choice Step',
description: 'Owner specifies a list of possible options, end user replies with 1,2,3 or 4 etc'
},
{
id: 4,
name: 'Upload Document Step',
description: 'Owner specifies some instructions and the end user must upload a document to complete the step'
},
{
id: 5,
name: 'Read Document Step',
description: 'Owner must upload a document and the end user must read it'
},
{
id: 6,
name: 'Read & Upload Document Step',
description: 'Owner upload a document and the end user must read it and upload a new one to complete the step'
},
{
id: 7,
name: 'People to meet',
description: 'A Spark room would be created between the person being onboarded and the people specified'
},
]
};
|
Add R language key for matrix column
|
import Ember from 'ember';
var configKeys, configKeysMap, languageConfigKeys;
languageConfigKeys = {
go: 'Go',
php: 'PHP',
node_js: 'Node.js',
perl: 'Perl',
perl6: 'Perl6',
python: 'Python',
scala: 'Scala',
smalltalk: 'Smalltalk',
ruby: 'Ruby',
d: 'D',
julia: 'Julia',
csharp: 'C#',
mono: 'Mono',
dart: 'Dart',
elixir: 'Elixir',
ghc: 'GHC',
haxe: 'Haxe',
jdk: 'JDK',
rvm: 'Ruby',
otp_release: 'OTP Release',
rust: 'Rust',
c: 'C',
cpp: 'C++',
clojure: 'Clojure',
lein: 'Lein',
compiler: 'Compiler',
crystal: 'Crystal',
osx_image: 'Xcode',
r: 'R'
};
configKeys = {
env: 'ENV',
gemfile: 'Gemfile',
xcode_sdk: 'Xcode SDK',
xcode_scheme: 'Xcode Scheme',
compiler: 'Compiler',
os: 'OS'
};
configKeysMap = Ember.merge(configKeys, languageConfigKeys);
export default configKeysMap;
export { languageConfigKeys, configKeys };
|
import Ember from 'ember';
var configKeys, configKeysMap, languageConfigKeys;
languageConfigKeys = {
go: 'Go',
php: 'PHP',
node_js: 'Node.js',
perl: 'Perl',
perl6: 'Perl6',
python: 'Python',
scala: 'Scala',
smalltalk: 'Smalltalk',
ruby: 'Ruby',
d: 'D',
julia: 'Julia',
csharp: 'C#',
mono: 'Mono',
dart: 'Dart',
elixir: 'Elixir',
ghc: 'GHC',
haxe: 'Haxe',
jdk: 'JDK',
rvm: 'Ruby',
otp_release: 'OTP Release',
rust: 'Rust',
c: 'C',
cpp: 'C++',
clojure: 'Clojure',
lein: 'Lein',
compiler: 'Compiler',
crystal: 'Crystal',
osx_image: 'Xcode'
};
configKeys = {
env: 'ENV',
gemfile: 'Gemfile',
xcode_sdk: 'Xcode SDK',
xcode_scheme: 'Xcode Scheme',
compiler: 'Compiler',
os: 'OS'
};
configKeysMap = Ember.merge(configKeys, languageConfigKeys);
export default configKeysMap;
export { languageConfigKeys, configKeys };
|
Update build script for Rollup change
|
import * as p from 'path';
import * as fs from 'fs';
import {rollup} from 'rollup';
import babel from 'rollup-plugin-babel';
const copyright = (
`/*
* Copyright ${new Date().getFullYear()}, Yahoo Inc.
* Copyrights licensed under the New BSD License.
* See the accompanying LICENSE file for terms.
*/
`
);
let babelConfig = JSON.parse(fs.readFileSync('src/.babelrc', 'utf8'));
babelConfig.babelrc = false;
babelConfig.presets = babelConfig.presets.map((preset) => {
return preset === 'es2015' ? 'es2015-rollup' : preset;
});
let bundle = rollup({
entry: p.resolve('src/index.js'),
external: [
p.resolve('locale-data/index.js'),
],
plugins: [
babel(babelConfig),
],
});
bundle.then(({write}) => write({
dest: p.resolve('lib/index.js'),
format: 'cjs',
banner: copyright,
}));
bundle.then(({write}) => write({
dest: p.resolve('lib/index.es.js'),
format: 'es',
banner: copyright,
}));
process.on('unhandledRejection', (reason) => {throw reason;});
|
import * as p from 'path';
import * as fs from 'fs';
import {rollup} from 'rollup';
import babel from 'rollup-plugin-babel';
const copyright = (
`/*
* Copyright ${new Date().getFullYear()}, Yahoo Inc.
* Copyrights licensed under the New BSD License.
* See the accompanying LICENSE file for terms.
*/
`
);
let babelConfig = JSON.parse(fs.readFileSync('src/.babelrc', 'utf8'));
babelConfig.babelrc = false;
babelConfig.presets = babelConfig.presets.map((preset) => {
return preset === 'es2015' ? 'es2015-rollup' : preset;
});
let bundle = rollup({
entry: p.resolve('src/index.js'),
external: [
p.resolve('locale-data/index.js'),
],
plugins: [
babel(babelConfig),
],
});
bundle.then(({write}) => write({
dest: p.resolve('lib/index.js'),
format: 'cjs',
banner: copyright,
}));
bundle.then(({write}) => write({
dest: p.resolve('lib/index.es.js'),
format: 'es6',
banner: copyright,
}));
process.on('unhandledRejection', (reason) => {throw reason;});
|
Remove the decorate `facts` from mapper `Hostname`
- And update the class comment
|
from .. import Mapper, mapper
@mapper("hostname")
class Hostname(Mapper):
"""Class for parsing ``hostname`` command output.
Attributes:
fqdn: The fully qualified domain name of the host. The same to
``hostname`` when domain part is not set.
hostname: The hostname.
domain: The domain get from the fqdn.
"""
def parse_content(self, content):
raw = None
if len(content) == 1:
raw = content[0].strip()
self.fqdn = raw
self.hostname = raw.split(".")[0] if raw else None
self.domain = ".".join(raw.split(".")[1:]) if raw else None
|
from .. import Mapper, mapper
@mapper("facts")
@mapper("hostname")
class Hostname(Mapper):
def parse_content(self, content):
fqdn = None
if len(content) == 1:
fqdn = content[0].strip()
elif len(content) > 1:
for line in content:
if line.startswith('fqdn'):
fqdn = line.split()[-1]
self.fqdn = fqdn
self.hostname = fqdn.split(".")[0] if fqdn else None
self.domain = ".".join(fqdn.split(".")[1:]) if fqdn else None
|
Change exemple code to generate OTP link
|
import binascii
import base64
import os.path
def __content(f):
return open(os.path.join(os.path.dirname(__file__), f)).read()
crypto_js = __content('crypto.js')
hotp_js = __content('hotp.js')
myotp_js = __content('my-otp.js')
def dataize(document, type='text/html'):
return 'data:%s;base64,%s' % (type, base64.b64encode(document))
def otp_doc(secret):
key = binascii.hexlify(secret)
doc = ''''<html>
<body>
<script type="text/javascript">%s;history.back()</script>
</body>
</html>''' % (crypto_js + ';' + hotp_js + ';' + myotp_js.replace('FAFA',key))
return dataize(doc)
if __name__ == '__main__':
import sys
print '''<html><body><a href="%s" title="Drag me to your bookmark">OTP Password</a></body></html>''' % otp_doc(sys.argv[1])
|
import binascii
import base64
import os.path
def __content(f):
return open(os.path.join(os.path.dirname(__file__), f)).read()
crypto_js = __content('crypto.js')
hotp_js = __content('hotp.js')
myotp_js = __content('my-otp.js')
def dataize(document, type='text/html'):
return 'data:%s;base64,%s' % (type, base64.b64encode(document))
def otp_doc(secret):
key = binascii.hexlify(secret)
doc = ''''<html>
<body>
<script type="text/javascript">%s;history.back()</script>
</body>
</html>''' % (crypto_js + ';' + hotp_js + ';' + myotp_js.replace('FAFA',key))
return dataize(doc)
if __name__ == '__main__':
import sys
print '''
<html>
<body>
<a href="%s">OTP Link</a>
</body>
</html>''' % otp_doc(sys.argv[1])
|
Add a print with file where mistake is
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import print_function
from xml.etree.ElementTree import ParseError
import xml.etree.ElementTree as ET
import glob
import sys
def eprint(*args, **kwargs):
print(*args, file=sys.stderr, **kwargs)
def parse():
for infile in glob.glob('*.xml'):
try:
tree = ET.parse(infile)
root = tree.getroot()
if root.findall('.//FatalError'):
eprint("Error detected")
print(infile)
sys.exit(1)
except ParseError:
eprint("The file xml isn't correct. There were some mistakes in the tests ")
sys.exit(1)
def main():
parse()
if __name__ == '__main__':
main()
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import print_function
from xml.etree.ElementTree import ParseError
import xml.etree.ElementTree as ET
import glob
import sys
def eprint(*args, **kwargs):
print(*args, file=sys.stderr, **kwargs)
def parse():
for infile in glob.glob('*.xml'):
try:
tree = ET.parse(infile)
root = tree.getroot()
if root.findall('.//FatalError'):
eprint("Error detected")
sys.exit(1)
except ParseError:
eprint("The file xml isn't correct. There were some mistakes in the tests ")
sys.exit(1)
def main():
parse()
if __name__ == '__main__':
main()
|
Change test to use card concept
|
var tape = require("tape"),
jsdom = require("jsdom"),
d3 = Object.assign(require("../"), require("d3-selection"));
/*************************************
************ Components *************
*************************************/
// Leveraging create hook with selection as first argument.
var card = d3.component("div", "card")
.create(function (selection){
selection
.append("div").attr("class", "card-block")
.append("div").attr("class", "card-text");
})
.render(function (selection, props){
selection
.select(".card-text")
.text(props.text);
});
/*************************************
************** Tests ****************
*************************************/
tape("Create hook should pass selection on enter.", function(test) {
var div = d3.select(jsdom.jsdom().body).append("div");
div.call(card, { text: "I'm in a card." });
test.equal(div.html(), [
'<div class="card">',
'<div class="card-block">',
'<div class="card-text">',
"I\'m in a card.",
"</div>",
"</div>",
"</div>"
].join(""));
test.end();
});
|
var tape = require("tape"),
jsdom = require("jsdom"),
d3 = Object.assign(require("../"), require("d3-selection"));
/*************************************
************ Components *************
*************************************/
// Leveraging create hook with selection as first argument.
var checkboxHTML = `
<label class="form-check-label">
<input type="checkbox" class="form-check-input">
<span class="checkbox-label-span"></span>
</label>
`,
checkbox = d3.component("div", "form-check")
.create(function (selection){
selection.html(checkboxHTML);
})
.render(function (selection, props){
if(props && props.label){
selection.select(".checkbox-label-span")
.text(props.label);
}
});
/*************************************
************** Tests ****************
*************************************/
tape("Create hook should pass selection on enter.", function(test) {
var div = d3.select(jsdom.jsdom().body).append("div");
div.call(checkbox);
test.equal(div.html(), `<div class="form-check">${checkboxHTML}</div>`);
test.end();
});
tape("Render should have access to selection content from create hook.", function(test) {
var div = d3.select(jsdom.jsdom().body).append("div");
div.call(checkbox, { label: "My Checkbox"});
test.equal(div.select(".checkbox-label-span").text(), "My Checkbox");
test.end();
});
|
Allow public on list of subscribers
Summary: Fixes T7317, allows public to be set on this list controller.
Test Plan: Tested a list of subscribers on a logged in and logged out Diff.
Reviewers: btrahan, epriestley
Reviewed By: epriestley
Subscribers: Korvin, epriestley
Maniphest Tasks: T7317
Differential Revision: https://secure.phabricator.com/D11801
|
<?php
final class PhabricatorSubscriptionsListController
extends PhabricatorController {
private $phid;
public function willProcessRequest(array $data) {
$this->phid = idx($data, 'phid');
}
public function shouldAllowPublic() {
return true;
}
public function processRequest() {
$request = $this->getRequest();
$viewer = $request->getUser();
$phid = $this->phid;
$object = id(new PhabricatorObjectQuery())
->setViewer($viewer)
->withPHIDs(array($phid))
->executeOne();
if ($object instanceof PhabricatorSubscribableInterface) {
$subscriber_phids = PhabricatorSubscribersQuery::loadSubscribersForPHID(
$phid);
}
$handle_phids = $subscriber_phids;
$handle_phids[] = $phid;
$handles = id(new PhabricatorHandleQuery())
->setViewer($viewer)
->withPHIDs($handle_phids)
->execute();
$object_handle = $handles[$phid];
$dialog = id(new SubscriptionListDialogBuilder())
->setViewer($viewer)
->setTitle(pht('Subscribers'))
->setObjectPHID($phid)
->setHandles($handles)
->buildDialog();
return id(new AphrontDialogResponse())->setDialog($dialog);
}
}
|
<?php
final class PhabricatorSubscriptionsListController
extends PhabricatorController {
private $phid;
public function willProcessRequest(array $data) {
$this->phid = idx($data, 'phid');
}
public function processRequest() {
$request = $this->getRequest();
$viewer = $request->getUser();
$phid = $this->phid;
$object = id(new PhabricatorObjectQuery())
->setViewer($viewer)
->withPHIDs(array($phid))
->executeOne();
if ($object instanceof PhabricatorSubscribableInterface) {
$subscriber_phids = PhabricatorSubscribersQuery::loadSubscribersForPHID(
$phid);
}
$handle_phids = $subscriber_phids;
$handle_phids[] = $phid;
$handles = id(new PhabricatorHandleQuery())
->setViewer($viewer)
->withPHIDs($handle_phids)
->execute();
$object_handle = $handles[$phid];
$dialog = id(new SubscriptionListDialogBuilder())
->setViewer($viewer)
->setTitle(pht('Subscribers'))
->setObjectPHID($phid)
->setHandles($handles)
->buildDialog();
return id(new AphrontDialogResponse())->setDialog($dialog);
}
}
|
Use LargeBitList instead of BitBuffer.
|
package net.katsuster.strview.media.ts;
import net.katsuster.strview.io.*;
import net.katsuster.strview.media.*;
/**
* @author katsuhiro
*/
public class TSPacketList extends AbstractLargeList<TSPacket> {
public LargeBitList buf;
public TSPacketList() {
super(LENGTH_UNKNOWN);
}
public TSPacketList(LargeBitList l) {
super(LENGTH_UNKNOWN);
buf = l;
}
@Override
public void count() {
setLength(buf.length() / 188 / 8);
}
@Override
protected TSPacket getInner(long index) {
TSPacket p = new TSPacket();
FromBitListConverter c = new FromBitListConverter(buf);
c.doInit();
c.position(index * 188 * 8);
p.setNumber(index);
p.setLevel(0);
p.read(c);
c.doFinal();
return p;
}
@Override
protected void setInner(long index, TSPacket data) {
}
}
|
package net.katsuster.strview.media.ts;
import net.katsuster.strview.io.*;
import net.katsuster.strview.media.*;
/**
* @author katsuhiro
*/
public class TSPacketList extends AbstractLargeList<TSPacket> {
public LargeBitList buf;
public TSPacketList() {
super(LENGTH_UNKNOWN);
}
public TSPacketList(LargeBitList l) {
super(LENGTH_UNKNOWN);
buf = l;
}
@Override
public void count() {
setLength(buf.length() / 188 / 8);
}
@Override
protected TSPacket getInner(long index) {
TSPacket p = new TSPacket();
FromBitBufferConverter c = new FromBitBufferConverter(BitBuffer.wrap(buf));
c.doInit();
c.position(index * 188 * 8);
p.setNumber(index);
p.setLevel(0);
p.read(c);
c.doFinal();
return p;
}
@Override
protected void setInner(long index, TSPacket data) {
}
}
|
Use enum for subtype as well
|
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateWatches extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('watches', function (Blueprint $table) {
$table->bigIncrements('id');
$table->bigInteger('user_id')->unsigned();
$table->enum('notifiable_type', ['beatmapset', 'build', 'news_post']);
$table->bigInteger('notifiable_id')->unsigned();
$table->enum('subtype', ['comment']);
$table->timestampsTz();
$table->unique(['user_id', 'notifiable_type', 'notifiable_id', 'subtype']);
$table->index(['notifiable_type', 'notifiable_id']);
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('watches');
}
}
|
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateWatches extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('watches', function (Blueprint $table) {
$table->bigIncrements('id');
$table->bigInteger('user_id')->unsigned();
$table->enum('notifiable_type', ['beatmapset', 'build', 'news_post']);
$table->bigInteger('notifiable_id')->unsigned();
$table->string('subtype');
$table->timestampsTz();
$table->unique(['user_id', 'notifiable_type', 'notifiable_id', 'subtype']);
$table->index(['notifiable_type', 'notifiable_id']);
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('watches');
}
}
|
Add custom repository methods to obtain only placed orders
|
<?php
/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sylius\Component\Order\Repository;
use Sylius\Component\Order\Model\OrderInterface;
use Sylius\Component\Resource\Repository\RepositoryInterface;
use Sylius\Component\Sequence\Repository\HashSubjectRepositoryInterface;
/**
* @author Paweł Jędrzejewski <pawel@sylius.org>
*/
interface OrderRepositoryInterface extends RepositoryInterface, HashSubjectRepositoryInterface
{
/**
* @param int $amount
*
* @return OrderInterface[]
*/
public function findRecentOrders($amount = 10);
/**
* @param int|string $number
*
* @return bool
*/
public function isNumberUsed($number);
/**
* @param string $orderNumber
*
* @return OrderInterface|null
*/
public function findOneByNumber($orderNumber);
}
|
<?php
/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sylius\Component\Order\Repository;
use Sylius\Component\Order\Model\OrderInterface;
use Sylius\Component\Resource\Repository\RepositoryInterface;
use Sylius\Component\Sequence\Repository\HashSubjectRepositoryInterface;
/**
* @author Paweł Jędrzejewski <pawel@sylius.org>
*/
interface OrderRepositoryInterface extends RepositoryInterface, HashSubjectRepositoryInterface
{
/**
* @param int $amount
*
* @return OrderInterface[]
*/
public function findRecentOrders($amount = 10);
/**
* @param int|string $number
*
* @return bool
*/
public function isNumberUsed($number);
}
|
Enable parsing of more modules
This was failing due to having a `git@` URL in the `repository` field
https://github.com/sveltejs/svelte-loader/blob/d4e2c2025e8cf0cf448d61a5f5206d6e77ee0d9a/package.json#L35
|
// This can't be replaced with `new URL()` because browsers don't support git+http urls
const protocol = '(?:([^:]+:)?(?://)?)?';
const auth = '(?:(\\S+(?::\\S*)?)@)?';
const host = '([^/:]*)';
const path = '([/]?[^#]*)';
const hash = '(#.+)?';
const urlLaxRegex = new RegExp(protocol + auth + host + path + hash);
export function parse(url) {
const match = url.match(urlLaxRegex);
if (match) {
let path = match[4];
if (path && path[0] !== '/') {
path = `/${path}`;
}
return {
protocol: match[1],
auth: match[2],
host: match[3],
path,
hash: match[5]
};
}
}
const URL = window.URL;
export {URL};
|
// This can't be replaced with `new URL()` because browsers don't support git+http urls
const protocol = '(?:([^:]+:)?(?://)?)?';
const auth = '(?:(\\S+(?::\\S*)?)@)?';
const host = '([^/:]*)';
const path = '([/]?[^#]*)';
const hash = '(#.+)?';
const urlLaxRegex = new RegExp(protocol + auth + host + path + hash);
export function parse(url) {
const match = url.match(urlLaxRegex);
if (match) {
let path = match[4];
if (path && path[0] !== '/') {
path = `/${path}`;
}
return {
protocol: match[1],
auth: match[2],
host: match[3],
path,
hash: match[5]
};
}
}
|
Change dependencies to load only in backend
|
<?php
class Kwc_Basic_Link_Trl_Component extends Kwc_Abstract_Composite_Trl_Component
{
public static function getSettings($mainComponentClass)
{
$ret = parent::getSettings($mainComponentClass);
$ret['ownModel'] = Kwc_Abstract::getSetting($mainComponentClass, 'ownModel');
$ret['assetsAdmin']['dep'][] = 'ExtFormFields';
$ret['assetsAdmin']['files'][] = 'kwf/Kwc/Basic/Link/Trl/CopyButton.js';
$ret['throwHasContentChangedOnRowColumnsUpdate'] = 'text';
return $ret;
}
public function getTemplateVars(Kwf_Component_Renderer_Abstract $renderer = null)
{
$ret = parent::getTemplateVars($renderer);
$ret['text'] = $this->_getRow()->text;
return $ret;
}
public function hasContent()
{
if (!$this->_getRow()->text) return false;
return parent::hasContent();
}
}
|
<?php
class Kwc_Basic_Link_Trl_Component extends Kwc_Abstract_Composite_Trl_Component
{
public static function getSettings($mainComponentClass)
{
$ret = parent::getSettings($mainComponentClass);
$ret['ownModel'] = Kwc_Abstract::getSetting($mainComponentClass, 'ownModel');
$ret['assets']['dep'][] = 'ExtFormFields';
$ret['assets']['files'][] = 'kwf/Kwc/Basic/Link/Trl/CopyButton.js';
$ret['throwHasContentChangedOnRowColumnsUpdate'] = 'text';
return $ret;
}
public function getTemplateVars(Kwf_Component_Renderer_Abstract $renderer = null)
{
$ret = parent::getTemplateVars($renderer);
$ret['text'] = $this->_getRow()->text;
return $ret;
}
public function hasContent()
{
if (!$this->_getRow()->text) return false;
return parent::hasContent();
}
}
|
Change sample using sftp to not run if prelive is down
|
package com.litle.sdk.samples;
import com.litle.sdk.*;
import com.litle.sdk.generate.AccountUpdateFileRequestData;
import com.litle.sdk.generate.RFRRequest;
import java.util.Calendar;
public class RfrLitleExample {
public static void main(String[] args) {
String preliveStatus = System.getenv("preliveStatus");
if(preliveStatus != null && preliveStatus.equalsIgnoreCase("down")){
return;
}
String merchantId = "0180";
String requestFileName = "litleSdk-testRFRFile-fileConfigSFTP.xml";
RFRRequest rfrRequest = new RFRRequest();
AccountUpdateFileRequestData data = new AccountUpdateFileRequestData();
data.setMerchantId(merchantId);
data.setPostDay(Calendar.getInstance());
rfrRequest.setAccountUpdateFileRequestData(data);
LitleRFRFileRequest request = new LitleRFRFileRequest(requestFileName, rfrRequest);
try{
LitleRFRFileResponse response = request.sendToLitleSFTP();
String message=response.getLitleRFRResponse().getRFRResponseMessage();
}
catch(Exception e){
}
}
}
|
package com.litle.sdk.samples;
import com.litle.sdk.*;
import com.litle.sdk.generate.AccountUpdateFileRequestData;
import com.litle.sdk.generate.RFRRequest;
import java.util.Calendar;
public class RfrLitleExample {
public static void main(String[] args) {
String merchantId = "0180";
String requestFileName = "litleSdk-testRFRFile-fileConfigSFTP.xml";
RFRRequest rfrRequest = new RFRRequest();
AccountUpdateFileRequestData data = new AccountUpdateFileRequestData();
data.setMerchantId(merchantId);
data.setPostDay(Calendar.getInstance());
rfrRequest.setAccountUpdateFileRequestData(data);
LitleRFRFileRequest request = new LitleRFRFileRequest(requestFileName, rfrRequest);
try{
LitleRFRFileResponse response = request.sendToLitleSFTP();
String message=response.getLitleRFRResponse().getRFRResponseMessage();
}
catch(Exception e){
}
}
}
|
Add a FORM_POST method with streamResponse=true
|
/**
* Copyright 2010-2012 Ralph Schaer <ralphschaer@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ch.ralscha.extdirectspring_itest;
import org.springframework.stereotype.Service;
import ch.ralscha.extdirectspring.annotation.ExtDirectMethod;
import ch.ralscha.extdirectspring.annotation.ExtDirectMethodType;
import ch.ralscha.extdirectspring.bean.ExtDirectFormPostResponse;
@Service
public class InfoService {
@ExtDirectMethod(value = ExtDirectMethodType.FORM_POST, group = "itest_info_service", streamResponse = true)
public ExtDirectFormPostResponse updateInfo(Info info) {
ExtDirectFormPostResponse resp = new ExtDirectFormPostResponse();
resp.addResultProperty("user-name-lower-case", info.getUserName().toLowerCase());
return resp;
}
}
|
/**
* Copyright 2010-2012 Ralph Schaer <ralphschaer@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ch.ralscha.extdirectspring_itest;
import org.springframework.stereotype.Service;
import ch.ralscha.extdirectspring.annotation.ExtDirectMethod;
import ch.ralscha.extdirectspring.annotation.ExtDirectMethodType;
import ch.ralscha.extdirectspring.bean.ExtDirectFormPostResponse;
@Service
public class InfoService {
@ExtDirectMethod(value = ExtDirectMethodType.FORM_POST, group = "itest_info_service")
public ExtDirectFormPostResponse updateInfo(Info info) {
ExtDirectFormPostResponse resp = new ExtDirectFormPostResponse();
resp.addResultProperty("user-name-lower-case", info.getUserName().toLowerCase());
return resp;
}
}
|
Test the failure branch in BaseEntityJSONDecoder
|
from test_provider_gtfs import provider
from busbus.entity import BaseEntityJSONEncoder
import json
import pytest
@pytest.fixture(scope='module')
def agency(provider):
return next(provider.agencies)
def test_entity_repr(agency):
assert 'DTA' in repr(agency)
def test_entity_failed_getattr(agency):
with pytest.raises(AttributeError):
agency.the_weather_in_london
def test_entity_failed_getitem(agency):
with pytest.raises(KeyError):
agency['the_weather_in_london']
def test_entity_to_dict(agency):
assert dict(agency)['id'] == 'DTA'
def test_entity_to_json(provider):
json_str = BaseEntityJSONEncoder().encode(next(provider.arrivals))
json.loads(json_str)
def test_bad_json():
with pytest.raises(TypeError):
BaseEntityJSONEncoder().encode(set())
|
from test_provider_gtfs import provider
from busbus.entity import BaseEntityJSONEncoder
import json
import pytest
@pytest.fixture(scope='module')
def agency(provider):
return next(provider.agencies)
def test_entity_repr(agency):
assert 'DTA' in repr(agency)
def test_entity_failed_getattr(agency):
with pytest.raises(AttributeError):
agency.the_weather_in_london
def test_entity_failed_getitem(agency):
with pytest.raises(KeyError):
agency['the_weather_in_london']
def test_entity_to_dict(agency):
assert dict(agency)['id'] == 'DTA'
def test_entity_to_json(provider):
json_str = BaseEntityJSONEncoder().encode(next(provider.arrivals))
json.loads(json_str)
|
Fix 'last chance' reminder email
Both payment reminder emails were accidentally configured to go out at the same time.
|
from uber.config import c
from uber.automated_emails import MarketplaceEmailFixture
from uber.utils import days_before
MarketplaceEmailFixture(
'Your {EVENT_NAME} ({EVENT_DATE}) Dealer registration is due in one week',
'dealers/payment_reminder.txt',
lambda g: g.status == c.APPROVED and days_before(7, g.dealer_payment_due, 2)() and g.is_unpaid,
needs_approval=False,
ident='dealer_reg_payment_reminder_due_soon_mff')
MarketplaceEmailFixture(
'Last chance to pay for your {EVENT_NAME} ({EVENT_DATE}) Dealer registration',
'dealers/payment_reminder.txt',
lambda g: g.status == c.APPROVED and days_before(2, g.dealer_payment_due)() and g.is_unpaid,
needs_approval=False,
ident='dealer_reg_payment_reminder_last_chance_mff')
|
from uber.config import c
from uber.automated_emails import MarketplaceEmailFixture
from uber.utils import days_before
MarketplaceEmailFixture(
'Your {EVENT_NAME} ({EVENT_DATE}) Dealer registration is due in one week',
'dealers/payment_reminder.txt',
lambda g: g.status == c.APPROVED and days_before(7, g.dealer_payment_due, 2)() and g.is_unpaid,
needs_approval=False,
ident='dealer_reg_payment_reminder_due_soon_mff')
MarketplaceEmailFixture(
'Last chance to pay for your {EVENT_NAME} ({EVENT_DATE}) Dealer registration',
'dealers/payment_reminder.txt',
lambda g: g.status == c.APPROVED and days_before(7, g.dealer_payment_due, 2)() and g.is_unpaid,
needs_approval=False,
ident='dealer_reg_payment_reminder_last_chance_mff')
|
Fix the way index redirect works for latest Ember
|
define([
'ember',
'JST/index',
],
function (Em) {
'use strict';
var IndexRoute = Em.Route.extend({
actions: {
// error handler for when descendent
// routes fail to resolve their model promises.
// 'reason' is the value passed to the rejected promise.
error: function (reason) {
alert('Error transitioning to IndexRoute! The reason is: ' + reason);
// you can try transitioning into another route.
// descendent routes can implement this error handler too;
// if it returns true, it'll bubble up to the parent's handler.
// In this case, that's ApplicationRoute.
// return true;
},
},
beforeModel: function () {
this.transitionTo('groups');
},
});
return IndexRoute;
});
|
define([
'ember',
'JST/index',
],
function (Em) {
'use strict';
var IndexRoute = Em.Route.extend({
actions: {
// error handler for when descendent
// routes fail to resolve their model promises.
// 'reason' is the value passed to the rejected promise.
error: function (reason) {
alert('Error transitioning to IndexRoute! The reason is: ' + reason);
// you can try transitioning into another route.
// descendent routes can implement this error handler too;
// if it returns true, it'll bubble up to the parent's handler.
// In this case, that's ApplicationRoute.
// return true;
},
},
redirect: function () {
this.transitionTo('groups');
},
model: function () {
},
});
return IndexRoute;
});
|
Fix Babel config env being shared.
|
module.exports = () => {
const env = process.env.BABEL_ENV || process.env.NODE_ENV || 'development';
const browsers = process.env.BROWSERSLIST;
const targets = {};
if (browsers) {
targets.browsers = browsers;
}
if (env === 'production') {
targets.uglify = true;
}
if (env === 'testing') {
targets.node = 'current';
}
const preset = {
presets: [
['env', {
modules: false,
loose: env === 'production',
targets
}],
'react'
],
plugins: [
'syntax-dynamic-import',
'transform-object-rest-spread',
'transform-class-properties',
'transform-export-extensions',
['transform-runtime', { polyfill: false }]
]
};
if (env === 'development') {
preset.plugins.push('react-hot-loader/babel');
}
if (env === 'production') {
preset.plugins.push(
'transform-react-constant-elements',
'transform-react-inline-elements',
['transform-react-remove-prop-types', { mode: 'wrap' }]
);
}
if (env === 'testing') {
preset.plugins.push('istanbul');
}
return preset;
};
|
const env = process.env.BABEL_ENV || process.env.NODE_ENV || 'development';
const browsers = process.env.BROWSERSLIST;
const targets = {};
if (browsers) {
targets.browsers = browsers;
}
if (env === 'production') {
targets.uglify = true;
}
if (env === 'testing') {
targets.node = 'current';
}
const preset = {
presets: [
['env', {
modules: false,
loose: env === 'production',
targets
}],
'react'
],
plugins: [
'syntax-dynamic-import',
'transform-object-rest-spread',
'transform-class-properties',
'transform-export-extensions',
['transform-runtime', { polyfill: false }]
]
};
if (env === 'development') {
preset.plugins.push('react-hot-loader/babel');
}
if (env === 'production') {
preset.plugins.push(
'transform-react-constant-elements',
'transform-react-inline-elements',
['transform-react-remove-prop-types', { mode: 'wrap' }]
);
}
if (env === 'testing') {
preset.plugins.push('istanbul');
}
module.exports = preset;
|
Increase timeouts for async query compilation even more.
|
import slimdom from 'slimdom';
import blueprint from 'fontoxml-blueprints/readOnlyBlueprint';
import createSelectorFromXPathAsync from 'fontoxml-selectors/parsing/createSelectorFromXPathAsync';
import evaluateXPath from 'fontoxml-selectors/evaluateXPath';
describe('createSelectorFromXPathAsync', () => {
let documentNode;
beforeEach(() => {
documentNode = slimdom.createDocument();
});
it('can compile a selector asynchronously', () => {
return createSelectorFromXPathAsync('1 + 1')
.then(
function (selector) {
// Assume selector to be ok
chai.expect(
evaluateXPath(selector, documentNode, blueprint, {}, evaluateXPath.NUMBER_TYPE)
).to.equal(2);
},
() => {
chai.expect.fail();
});
}).timeout(10000);
it('throws when compilation fails', () => {
return createSelectorFromXPathAsync(']] Not valid at all! [[')
.then(function (selector) {
chai.expect.fail();
}, function (error) {
chai.expect(error).to.be.instanceOf(Error);
});
}).timeout(10000);
});
|
import slimdom from 'slimdom';
import blueprint from 'fontoxml-blueprints/readOnlyBlueprint';
import createSelectorFromXPathAsync from 'fontoxml-selectors/parsing/createSelectorFromXPathAsync';
import evaluateXPath from 'fontoxml-selectors/evaluateXPath';
describe('createSelectorFromXPathAsync', () => {
let documentNode;
beforeEach(() => {
documentNode = slimdom.createDocument();
});
it('can compile a selector asynchronously', () => {
return createSelectorFromXPathAsync('1 + 1')
.then(
function (selector) {
// Assume selector to be ok
chai.expect(
evaluateXPath(selector, documentNode, blueprint, {}, evaluateXPath.NUMBER_TYPE)
).to.equal(2);
},
() => {
chai.expect.fail();
});
}).timeout(5000);
it('throws when compilation fails', () => {
return createSelectorFromXPathAsync(']] Not valid at all! [[')
.then(function (selector) {
chai.expect.fail();
}, function (error) {
chai.expect(error).to.be.instanceOf(Error);
});
});
});
|
Remove trailing comma to appease JSHint.
|
(function () {
"use strict";
var delay, jitter, blacklist;
safari.application.addEventListener('message', function (event) {
if (event.name === 'getSettings') {
delay = safari.extension.settings.delay;
jitter = safari.extension.settings.jitter;
blacklist = safari.extension.settings.blacklist;
if (jitter) {
delay -= jitter;
delay += 2 * jitter * Math.random();
}
delay *= 1000;
blacklist = blacklist.split(/\s+/).filter(function (hostname) {
return hostname.toLowerCase();
});
event.target.page.dispatchMessage('settings', {
'delay': delay,
'blacklist': blacklist
});
}
}, false);
}());
|
(function () {
"use strict";
var delay, jitter, blacklist;
safari.application.addEventListener('message', function (event) {
if (event.name === 'getSettings') {
delay = safari.extension.settings.delay;
jitter = safari.extension.settings.jitter;
blacklist = safari.extension.settings.blacklist;
if (jitter) {
delay -= jitter;
delay += 2 * jitter * Math.random();
}
delay *= 1000;
blacklist = blacklist.split(/\s+/).filter(function (hostname) {
return hostname.toLowerCase();
});
event.target.page.dispatchMessage('settings', {
'delay': delay,
'blacklist': blacklist,
});
}
}, false);
}());
|
Revert "Use the native Object.keys if it's available."
This reverts commit 60689993d75db32701e99f7eb9110ce8eff54610.
|
"use strict";
// modified from https://github.com/es-shims/es6-shim
var keys = require('object-keys');
var isObject = function (obj) {
return typeof obj !== 'undefined' && obj !== null;
};
var assignShim = function assign(target, source) {
var s, i, props;
if (!isObject(target)) { throw new TypeError('target must be an object'); }
target = Object(target);
for (s = 1; s < arguments.length; ++s) {
source = arguments[s];
if (!isObject(source)) { throw new TypeError('source ' + s + ' must be an object'); }
props = keys(Object(source));
for (i = 0; i < props.length; ++i) {
target[props[i]] = source[props[i]];
}
}
return target;
};
assignShim.shim = function shimObjectAssign() {
if (!Object.assign) {
Object.assign = assignShim;
}
return Object.assign || assignShim;
};
module.exports = assignShim;
|
"use strict";
// modified from https://github.com/es-shims/es6-shim
var keys = Object.keys || require('object-keys');
var isObject = function (obj) {
return typeof obj !== 'undefined' && obj !== null;
};
var assignShim = function assign(target, source) {
var s, i, props;
if (!isObject(target)) { throw new TypeError('target must be an object'); }
target = Object(target);
for (s = 1; s < arguments.length; ++s) {
source = arguments[s];
if (!isObject(source)) { throw new TypeError('source ' + s + ' must be an object'); }
props = keys(Object(source));
for (i = 0; i < props.length; ++i) {
target[props[i]] = source[props[i]];
}
}
return target;
};
assignShim.shim = function shimObjectAssign() {
if (!Object.assign) {
Object.assign = assignShim;
}
return Object.assign || assignShim;
};
module.exports = assignShim;
|
Move option parsing outside of loadAccount
|
package main
import (
"fmt"
"log"
"github.com/jessevdk/go-flags"
"github.com/k0kubun/go-readline"
)
type Options struct {
ScreenName string `short:"a" long:"account" description:"login as an account of selected screen_name"`
}
func main() {
options := new(Options)
if _, err := flags.Parse(options); err != nil {
log.Fatal(err)
}
account := loadAccount(options)
startUserStream(account)
invokeInteractiveShell(account)
}
func loadAccount(options *Options) *Account {
if len(options.ScreenName) > 0 {
return AccountByScreenName(options.ScreenName)
} else {
return DefaultAccount()
}
}
func invokeInteractiveShell(account *Account) {
readline.CatchSignals(0)
for {
currentLine := readline.Readline(prompt(account))
if currentLine == nil || *currentLine == ":exit" {
return
}
err := executeCommand(account, *currentLine)
if err != nil {
fmt.Print(err.Error())
}
readline.AddHistory(*currentLine)
}
}
func prompt(account *Account) *string {
prompt := fmt.Sprintf("[%s] ", coloredScreenName(account.ScreenName))
return &prompt
}
|
package main
import (
"fmt"
"log"
"github.com/jessevdk/go-flags"
"github.com/k0kubun/go-readline"
)
type Options struct {
ScreenName string `short:"a" long:"account" description:"login as an account of selected screen_name"`
}
func main() {
account := loadAccount()
startUserStream(account)
invokeInteractiveShell(account)
}
func loadAccount() *Account {
options := new(Options)
if _, err := flags.Parse(options); err != nil {
log.Fatal(err)
}
if len(options.ScreenName) > 0 {
return AccountByScreenName(options.ScreenName)
} else {
return DefaultAccount()
}
}
func invokeInteractiveShell(account *Account) {
readline.CatchSignals(0)
for {
currentLine := readline.Readline(prompt(account))
if currentLine == nil || *currentLine == ":exit" {
return
}
err := executeCommand(account, *currentLine)
if err != nil {
fmt.Print(err.Error())
}
readline.AddHistory(*currentLine)
}
}
func prompt(account *Account) *string {
prompt := fmt.Sprintf("[%s] ", coloredScreenName(account.ScreenName))
return &prompt
}
|
Return if PR doesn't exist
|
var request = require('request')
// With username parsed from request, check that the user has submitted a
// PR to jlord/Patchwork.
// Because PRs are merged so fast by @RR, we loop through each of the closed
// issues to find the user's PR.
// called by: checkPR(username, function(err, pr){ prStatus(res, err, pr) })
// callback includes a function which sends the pr boolean on as a response
module.exports = function (username, callback) {
var options = {
url: 'https://api.github.com/repos/jlord/patchwork/issues?state=closed',
json: true,
headers: {
'User-Agent': 'request',
'Authorization': 'token ' + process.env['REPOROBOT_TOKEN']
}
}
request(options, getIssues)
function getIssues (error, response, body) {
if (error) return callback(error, null)
var issues = body
var pr = false
for (var i = 0; i < issues.length; i++) {
var issue = issues[i]
var user = issue.user.login.toLowerCase()
// what is the max number of issues that it returns?
if (!issue.pull_request) return callback(null, pr)
if (user.match(username.toLowerCase())) {
pr = true
return callback(null, pr)
}
}
}
}
|
var request = require('request')
// With username parsed from request, check that the user has submitted a
// PR to jlord/Patchwork.
// Because PRs are merged so fast by @RR, we loop through each of the closed
// issues to find the user's PR.
// called by: checkPR(username, function(err, pr){ prStatus(res, err, pr) })
// callback includes a function which sends the pr boolean on as a response
module.exports = function (username, callback) {
var options = {
url: 'https://api.github.com/repos/jlord/patchwork/issues?state=closed',
json: true,
headers: {
'User-Agent': 'request',
'Authorization': 'token ' + process.env['REPOROBOT_TOKEN']
}
}
request(options, getIssues)
function getIssues (error, response, body) {
if (error) return callback(error, null)
var issues = body
var pr = false
for (var i = 0; i < issues.length; i++) {
var issue = issues[i]
var user = issue.user.login.toLowerCase()
// what is the max number of issues that it returns?
var prStatus = issue.pull_request.html_url
if (user.match(username.toLowerCase()) && prStatus != null) {
pr = true
return callback(null, pr)
}
}
// TODO why this here, shouldn't it fail early?
// Check for non 200 responses
callback(error, pr)
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.