text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Fix bool logic in mask test & add test criteria
import numpy as np import pytest import yatsm._cyprep as cyprep def test_get_valid_mask(): n_bands, n_images, n_mask = 8, 500, 50 data = np.random.randint(0, 10000, size=(n_bands, n_images)).astype(np.int32) # Add in bad data _idx = np.arange(0, n_images) for b in range(n_bands): idx = np.random.choice(_idx, size=n_mask, replace=False) data[b, idx] = 16000 mins = np.repeat(0, n_bands).astype(np.int16) maxes = np.repeat(10000, n_bands).astype(np.int16) truth = np.all([((b >= _min) & (b <= _max)) for b, _min, _max in zip(data, mins, maxes)], axis=0) test = cyprep.get_valid_mask(data, mins, maxes).astype(np.bool) test_min = data[:, test].min(axis=1) test_max = data[:, test].max(axis=1) assert np.array_equal(truth, test) assert np.array_equal(data[:, truth].min(axis=1), test_min) assert np.array_equal(data[:, truth].max(axis=1), test_max) assert np.all(test_min >= mins) assert np.all(test_max <= maxes)
import numpy as np import pytest import yatsm._cyprep as cyprep def test_get_valid_mask(): n_bands, n_images, n_mask = 8, 500, 50 data = np.random.randint(0, 10000, size=(n_bands, n_images)).astype(np.int32) # Add in bad data _idx = np.arange(0, n_images) for b in range(n_bands): idx = np.random.choice(_idx, size=n_mask, replace=False) data[b, idx] = 16000 mins = np.repeat(0, n_bands).astype(np.int16) maxes = np.repeat(10000, n_bands).astype(np.int16) truth = np.all([((b > _min) & (b < _max)) for b, _min, _max in zip(np.rollaxis(data, 0), mins, maxes)], axis=0) np.testing.assert_equal(truth, cyprep.get_valid_mask(data, mins, maxes))
Fix for quotation marks in redirect URL Some websites use quotation marks around the url= query in the meta-refresh tag. Example: https://presse.stuttgart-tourist.de/die-weihnachtsmaerkte-in-der-region-stuttgart <meta HTTP-EQUIV="refresh" content="0;url='https://presse.stuttgart-tourist.de/die-weihnachtsmaerkte-in-der-region-stuttgart?PageSpeed=noscript'" /> Those have to be trimmed or an error (GuzzleHttp\Psr7\Exception\MalformedUriException: A relative URI must not have a path beginning with a segment containing a colon) is triggered
<?php declare(strict_types = 1); namespace Embed\Detectors; use Psr\Http\Message\UriInterface; class Redirect extends Detector { public function detect(): ?UriInterface { $document = $this->extractor->getDocument(); $value = $document->select('.//meta', ['http-equiv' => 'refresh'])->str('content'); return $value ? $this->extract($value) : null; } private function extract(string $value): ?UriInterface { if (preg_match('/url=(.+)$/i', $value, $match)) { return $this->extractor->resolveUri(trim($match[1], '\'"')); } return null; } }
<?php declare(strict_types = 1); namespace Embed\Detectors; use Psr\Http\Message\UriInterface; class Redirect extends Detector { public function detect(): ?UriInterface { $document = $this->extractor->getDocument(); $value = $document->select('.//meta', ['http-equiv' => 'refresh'])->str('content'); return $value ? $this->extract($value) : null; } private function extract(string $value): ?UriInterface { if (preg_match('/url=(.+)$/i', $value, $match)) { return $this->extractor->resolveUri($match[1]); } return null; } }
[Core] Fix class loading on Windows Fixes: #1540
package cucumber.runtime.io; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; class FileResource implements Resource { private final File root; private final File file; private final boolean classpathFileResource; static FileResource createFileResource(File root, File file) { return new FileResource(root, file, false); } static FileResource createClasspathFileResource(File root, File file) { return new FileResource(root, file, true); } private FileResource(File root, File file, boolean classpathFileResource) { this.root = root; this.file = file; this.classpathFileResource = classpathFileResource; if (!file.getAbsolutePath().startsWith(root.getAbsolutePath())) { throw new IllegalArgumentException(file.getAbsolutePath() + " is not a parent of " + root.getAbsolutePath()); } } @Override public String getPath() { if (classpathFileResource) { String relativePath = file.getAbsolutePath().substring(root.getAbsolutePath().length() + 1); return relativePath.replace(File.separatorChar, '/'); } else { return file.getPath(); } } @Override public InputStream getInputStream() throws IOException { return new FileInputStream(file); } }
package cucumber.runtime.io; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; class FileResource implements Resource { private final File root; private final File file; private final boolean classpathFileResource; static FileResource createFileResource(File root, File file) { return new FileResource(root, file, false); } static FileResource createClasspathFileResource(File root, File file) { return new FileResource(root, file, true); } private FileResource(File root, File file, boolean classpathFileResource) { this.root = root; this.file = file; this.classpathFileResource = classpathFileResource; if (!file.getAbsolutePath().startsWith(root.getAbsolutePath())) { throw new IllegalArgumentException(file.getAbsolutePath() + " is not a parent of " + root.getAbsolutePath()); } } @Override public String getPath() { if (classpathFileResource) { return file.getAbsolutePath().substring(root.getAbsolutePath().length() + 1); } else { return file.getPath(); } } @Override public InputStream getInputStream() throws IOException { return new FileInputStream(file); } }
Add attribution for macro used
<?php // Inspired from: http://forums.laravel.io/viewtopic.php?id=827 HTML::macro('nav_item', function($url, $text, $a_attr = [], $active_class = 'active', $li_attrs = []) { $href = HTML::link($url, $text, $a_attr); $response = ''; if( Request::is($url) || Request::is($url . '/*') ) { if(isset($li_attrs['class'])) { $li_attrs['class'] .= ' ' . $active_class; } else { $li_attrs['class'] = $active_class; } } return '<li ' . HTML::attributes($li_attrs) . '>' . $href . '</li>'; });
<?php HTML::macro('nav_item', function($url, $text, $a_attr = [], $active_class = 'active', $li_attrs = []) { $href = HTML::link($url, $text, $a_attr); $response = ''; if( Request::is($url) || Request::is($url . '/*') ) { if(isset($li_attrs['class'])) { $li_attrs['class'] .= ' ' . $active_class; } else { $li_attrs['class'] = $active_class; } } return '<li ' . HTML::attributes($li_attrs) . '>' . $href . '</li>'; });
Set the default prefix for ProjectSurveys to gsoc_program.
#!/usr/bin/python2.5 # # Copyright 2009 the Melange 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. """This module contains the ProjectSurvey model. """ __authors__ = [ '"Daniel Diniz" <ajaksu@gmail.com>', '"Lennard de Rijk" <ljvderijk@gmail.com>', ] from soc.models.survey import Survey class ProjectSurvey(Survey): """Survey for Students that have a StudentProject. """ def __init__(self, *args, **kwargs): super(ProjectSurvey, self).__init__(*args, **kwargs) self.prefix = 'gsoc_program' self.taking_access = 'student'
#!/usr/bin/python2.5 # # Copyright 2009 the Melange 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. """This module contains the ProjectSurvey model. """ __authors__ = [ '"Daniel Diniz" <ajaksu@gmail.com>', '"Lennard de Rijk" <ljvderijk@gmail.com>', ] from soc.models.survey import Survey class ProjectSurvey(Survey): """Survey for Students that have a StudentProject. """ def __init__(self, *args, **kwargs): super(ProjectSurvey, self).__init__(*args, **kwargs) # TODO: prefix has to be set to gsoc_program once data has been transferred self.prefix = 'program' self.taking_access = 'student'
Remove cms dependency in test-runner
HELPER_SETTINGS = { 'SITE_ID': 1, 'TIME_ZONE': 'Europe/Zurich', 'LANGUAGES': ( ('en', 'English'), ('de', 'German'), ('fr', 'French'), ), 'INSTALLED_APPS': [ 'parler', 'treebeard', 'aldryn_categories', ], 'PARLER_LANGUAGES': { 1: ( {'code': 'de', }, {'code': 'en', }, {'code': 'fr', }, ), 'default': { # Do not remove or change this value or tests may break. 'hide_untranslated': True, # Do not remove or change this value or tests may break. 'fallback': 'fr', } } } def run(): from djangocms_helper import runner runner.run('aldryn_categories') if __name__ == "__main__": run()
HELPER_SETTINGS = { 'SITE_ID': 1, 'TIME_ZONE': 'Europe/Zurich', 'LANGUAGES': ( ('en', 'English'), ('de', 'German'), ('fr', 'French'), ), 'INSTALLED_APPS': [ 'parler', 'treebeard', 'aldryn_categories', ], 'PARLER_LANGUAGES': { 1: ( {'code': 'de', }, {'code': 'en', }, {'code': 'fr', }, ), 'default': { # Do not remove or change this value or tests may break. 'hide_untranslated': True, # Do not remove or change this value or tests may break. 'fallback': 'fr', } } } def run(): from djangocms_helper import runner runner.cms('aldryn_categories') if __name__ == "__main__": run()
Update action item distribution alert text to better reflect current application logic
export default { "prime-directive": { alert: null, confirmationMessage: "Are you sure want to proceed to the Idea Generation stage? This will commence the retro in earnest.", nextStage: "idea-generation", button: { copy: "Proceed to Idea Generation", iconClass: "arrow right", }, }, "idea-generation": { alert: null, confirmationMessage: "Are you sure you would like to proceed to the action items stage?", nextStage: "action-items", button: { copy: "Proceed to Action Items", iconClass: "arrow right", }, }, "action-items": { alert: null, confirmationMessage: null, nextStage: "action-item-distribution", button: { copy: "Send Action Items", iconClass: "send", }, }, "action-item-distribution": { alert: { headerText: "Action Items Distributed", bodyText: "The facilitator has distributed this retro's action items. You will receive an email breakdown shortly!", }, confirmationMessage: null, nextStage: null, button: null, }, }
export default { "prime-directive": { alert: null, confirmationMessage: "Are you sure want to proceed to the Idea Generation stage? This will commence the retro in earnest.", nextStage: "idea-generation", button: { copy: "Proceed to Idea Generation", iconClass: "arrow right", }, }, "idea-generation": { alert: null, confirmationMessage: "Are you sure you would like to proceed to the action items stage?", nextStage: "action-items", button: { copy: "Proceed to Action Items", iconClass: "arrow right", }, }, "action-items": { alert: null, confirmationMessage: null, nextStage: "action-item-distribution", button: { copy: "Send Action Items", iconClass: "send", }, }, "action-item-distribution": { alert: { headerText: "Retro Closed!", bodyText: "The facilitator has closed this retrospective. You will receive an email containing the retrospective's action items shortly.", }, confirmationMessage: null, nextStage: null, button: null, }, }
Add APA websites to URL patterns where client is known to be embedded. URL patterns provided by Kadidra McCloud at APA. Fixes https://github.com/hypothesis/product-backlog/issues/814
import fnmatch import re from urllib.parse import urlparse # Hardcoded URL patterns where client is assumed to be embedded. # # Only the hostname and path are included in the pattern. The path must be # specified; use "example.com/*" to match all URLs on a particular domain. # # Patterns are shell-style wildcards ('*' matches any number of chars, '?' # matches a single char). PATTERNS = [ # Hypothesis websites. "h.readthedocs.io/*", "web.hypothes.is/blog/*", # Publisher partners: # American Psychological Organization. "psycnet.apa.org/fulltext/*", "awspntest.apa.org/fulltext/*", ] COMPILED_PATTERNS = [re.compile(fnmatch.translate(pat)) for pat in PATTERNS] def url_embeds_client(url): """ Test whether ``url`` is known to embed the client. This currently just tests the URL against the pattern list ``PATTERNS``. Only the hostname and path of the URL are tested. Returns false for non-HTTP URLs. :return: True if the URL matches a pattern. """ parsed_url = urlparse(url) if not parsed_url.scheme.startswith("http"): return False path = parsed_url.path if not path: path = "/" netloc_and_path = parsed_url.netloc + path for pat in COMPILED_PATTERNS: if pat.fullmatch(netloc_and_path): return True return False
import fnmatch import re from urllib.parse import urlparse # Hardcoded URL patterns where client is assumed to be embedded. # # Only the hostname and path are included in the pattern. The path must be # specified; use "example.com/*" to match all URLs on a particular domain. # # Patterns are shell-style wildcards ('*' matches any number of chars, '?' # matches a single char). PATTERNS = [ "h.readthedocs.io/*", "web.hypothes.is/blog/*", ] COMPILED_PATTERNS = [re.compile(fnmatch.translate(pat)) for pat in PATTERNS] def url_embeds_client(url): """ Test whether ``url`` is known to embed the client. This currently just tests the URL against the pattern list ``PATTERNS``. Only the hostname and path of the URL are tested. Returns false for non-HTTP URLs. :return: True if the URL matches a pattern. """ parsed_url = urlparse(url) if not parsed_url.scheme.startswith("http"): return False path = parsed_url.path if not path: path = "/" netloc_and_path = parsed_url.netloc + path for pat in COMPILED_PATTERNS: if pat.fullmatch(netloc_and_path): return True return False
Make NetworkDevice serializable to help with potential cache implementations.
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.btisystems.pronx.ems.core.model; import com.btisystems.pronx.ems.core.snmp.IVariableBindingHandler; import java.io.Serializable; /** * Manages the creation and population of entities for a discovered device. */ public interface INetworkDevice extends IVariableBindingHandler, Serializable { /** * @return the root entity containing the tree of managed objects */ AbstractRootEntity getRootObject(); }
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.btisystems.pronx.ems.core.model; import com.btisystems.pronx.ems.core.snmp.IVariableBindingHandler; /** * Manages the creation and population of entities for a discovered device. */ public interface INetworkDevice extends IVariableBindingHandler { /** * @return the root entity containing the tree of managed objects */ AbstractRootEntity getRootObject(); }
Fix bug with how Pantheon is disabling updates
<?php // Only in Test and Live Environments... if ( in_array( $_ENV['PANTHEON_ENVIRONMENT'], Array('test', 'live') ) ) { // // Disable Core Updates EVERYWHERE (use git upstream) // function _pantheon_disable_wp_updates() { include ABSPATH . WPINC . '/version.php'; return (object) array( 'updates' => array(), 'version_checked' => $wp_version, 'last_checked' => time(), ); } add_filter( 'pre_site_transient_update_core', '_pantheon_disable_wp_updates' ); // // Disable Plugin Updates // add_action('admin_menu','hide_admin_notices'); function hide_admin_notices() { remove_action( 'admin_notices', 'update_nag', 3 ); } remove_action( 'load-update-core.php', 'wp_update_plugins' ); add_filter( 'pre_site_transient_update_plugins', '_pantheon_disable_wp_updates' ); // // Disable Theme Updates // remove_action( 'load-update-core.php', 'wp_update_themes' ); add_filter( 'pre_site_transient_update_themes', '_pantheon_disable_wp_updates' ); }
<?php // Only in Test and Live Environments... if ( in_array( $_ENV['PANTHEON_ENVIRONMENT'], Array('test', 'live') ) ) { // // Disable Core Updates EVERYWHERE (use git upstream) // add_filter( 'pre_site_transient_update_core', create_function( '$a', "return null;" ) ); // // Disable Plugin Updates // add_action('admin_menu','hide_admin_notices'); function hide_admin_notices() { remove_action( 'admin_notices', 'update_nag', 3 ); } remove_action( 'load-update-core.php', 'wp_update_plugins' ); add_filter( 'pre_site_transient_update_plugins', create_function( '$a', "return null;" ) ); // // Disable Theme Updates // remove_action( 'load-update-core.php', 'wp_update_themes' ); add_filter( 'pre_site_transient_update_themes', create_function( '$a', "return null;" ) ); }
Fix LINE login procedure: 1. First fire App() so that assertions are not interrupted by LINE login 2. LINE login redirect URI fix: location.href already includes location.search. Repeating that will result in incorrect url token
import 'core-js'; import 'normalize.css'; import './index.scss'; import { isDuringLiffRedirect } from './lib'; import App from './App.svelte'; liff.init({ liffId: LIFF_ID }).then(() => { // liff.init should have corrected the path now, don't initialize app and just wait... // Ref: https://www.facebook.com/groups/linebot/permalink/2380490388948200/?comment_id=2380868955577010 if (isDuringLiffRedirect) return; document.getElementById('loading').remove(); // Cleanup loading // Kickstart app loading; fire assertions new App({ target: document.body }); // For devs (and users on LINE desktop, which is rare) if (!liff.isLoggedIn()) { liff.login({ // https://github.com/line/line-liff-v2-starter/issues/4 redirectUri: location.href, }); } });
import 'core-js'; import 'normalize.css'; import './index.scss'; import { isDuringLiffRedirect } from './lib'; import App from './App.svelte'; liff.init({ liffId: LIFF_ID }).then(() => { // liff.init should have corrected the path now, don't initialize app and just wait... // Ref: https://www.facebook.com/groups/linebot/permalink/2380490388948200/?comment_id=2380868955577010 if (isDuringLiffRedirect) return; if (!liff.isLoggedIn()) { liff.login({ // https://github.com/line/line-liff-v2-starter/issues/4 redirectUri: `${location.href}${location.search}`, }); } // Cleanup loading document.getElementById('loading').remove(); new App({ target: document.body }); });
Add missing conditional for spring-security Without it, if spring security is not present, it creates a runtime exception due to AuthenticationEntryPointr not being in the classpath
package org.zalando.problem.spring.web.autoconfigure.security; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.zalando.problem.spring.web.advice.security.SecurityProblemSupport; /** * Registers exception handling in spring-security */ @Configuration @ConditionalOnClass(WebSecurityConfigurerAdapter.class) //only when spring-security is in classpath @Import(SecurityProblemSupport.class) public class SecurityConfiguration extends WebSecurityConfigurerAdapter { @Autowired private SecurityProblemSupport problemSupport; @Override public void configure(final HttpSecurity http) throws Exception { http.exceptionHandling() .authenticationEntryPoint(problemSupport) .accessDeniedHandler(problemSupport); } }
package org.zalando.problem.spring.web.autoconfigure.security; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.zalando.problem.spring.web.advice.security.SecurityProblemSupport; /** * Registers exception handling in spring-security */ @Configuration @Import(SecurityProblemSupport.class) public class SecurityConfiguration extends WebSecurityConfigurerAdapter { @Autowired private SecurityProblemSupport problemSupport; @Override public void configure(final HttpSecurity http) throws Exception { http.exceptionHandling() .authenticationEntryPoint(problemSupport) .accessDeniedHandler(problemSupport); } }
Fix error in loading trees Former-commit-id: 6fda03a47c5fa2d65c143ebdd81e158ba5e1ccda
#! /usr/bin/env python3 import os import shutil import datetime import sys from ete3 import Tree DEFAULT_FORMAT = 1 class TreeIndex: def __init__(self,tree_newick_fn,format=DEFAULT_FORMAT): self.tree_newick_fn=tree_newick_fn self.tree=Tree(tree_newick_fn,format=format) def process_node(self,node): if node.is_leaf(): if hasattr(node,"fastapath"): fastas_fn=node.fastapath.split("@") for fasta_fn in fastas_fn: print(fasta_fn) else: children=node.get_children() for child in children: self.process_node(child) if __name__ == "__main__": assert(len(sys.argv)==2) newick_fn=sys.argv[1] ti=TreeIndex( tree_newick_fn=newick_fn, ) ti.process_node(ti.tree.get_tree_root())
#! /usr/bin/env python3 import os import shutil import datetime import sys import argparse from ete3 import Tree import logging DEFAULT_FORMAT = 1 class TreeIndex: def __init__(self,tree_newick_fn,format=DEFAULT_FORMAT): self.tree_newick_fn=tree_newick_fn self.tree=read_newick(tree_newick_fn,format=format) def process_node(self,node): if node.is_leaf(): if hasattr(node,"fastapath"): fastas_fn=node.fastapath.split("@") for fasta_fn in fastas_fn: print(fasta_fn) else: children=node.get_children() for child in children: self.process_node(child) if __name__ == "__main__": assert(len(sys.argv)==2) newick_fn=sys.argv[1] ti=TreeIndex( tree_newick_fn=newick_fn, ) ti.process_node(ti.tree.get_tree_root())
Clean up nicely upon $destruction.
'use strict'; angular.module('ngClipboard', []). value('ZeroClipboardConfig', { path: '//cdnjs.cloudflare.com/ajax/libs/zeroclipboard/1.2.3/ZeroClipboard.swf' }). directive('clipCopy', ['$window', 'ZeroClipboardConfig', function ($window, ZeroClipboardConfig) { return { scope: { clipCopy: '&', clipClick: '&' }, restrict: 'A', link: function (scope, element, attrs) { // Create the clip object var clip = new ZeroClipboard( element, { moviePath: ZeroClipboardConfig.path, trustedDomains: ['*'], allowScriptAccess: "always" }); var onMousedown = function (client) { client.setText(scope.$eval(scope.clipCopy)); if (angular.isDefined(attrs.clipClick)) { scope.$apply(scope.clipClick); } }; clip.on('mousedown', onMousedown); scope.$on('$destroy', function() { clip.off('mousedown', onMousedown); clip.unglue(element); }); } } }]);
'use strict'; angular.module('ngClipboard', []). value('ZeroClipboardConfig', { path: '//cdnjs.cloudflare.com/ajax/libs/zeroclipboard/1.2.3/ZeroClipboard.swf' }). directive('clipCopy', ['$window', 'ZeroClipboardConfig', function ($window, ZeroClipboardConfig) { return { scope: { clipCopy: '&', clipClick: '&' }, restrict: 'A', link: function (scope, element, attrs) { // Create the clip object var clip = new ZeroClipboard( element, { moviePath: ZeroClipboardConfig.path, trustedDomains: ['*'], allowScriptAccess: "always" }); clip.on( 'mousedown', function(client) { client.setText(scope.$eval(scope.clipCopy)); if (angular.isDefined(attrs.clipClick)) { scope.$apply(scope.clipClick); } }); } } }]);
Tweak documentation for market listener in matching engine
package org.jvirtanen.parity.match; /** * The interface for outbound events from the matching engine. */ public interface MarketListener { /** * Match an incoming order to a resting order in the order book. The match * occurs at the price of the order in the order book. * * @param restingOrderId the order identifier of the resting order * @param incomingOrderId the order identifier of the incoming order * @param incomingSide the side of the incoming order * @param price the execution price * @param executedQuantity the executed quantity * @param remainingQuantity the remaining quantity of the resting order */ void match(long restingOrderId, long incomingOrderId, Side incomingSide, long price, long executedQuantity, long remainingQuantity); /** * Add an order to the order book. * * @param orderId the order identifier * @param side the side * @param price the limit price * @param size the size */ void add(long orderId, Side side, long price, long size); /** * Cancel a quantity of an order. * * @param orderId the order identifier * @param canceledQuantity the canceled quantity * @param remainingQuantity the remaining quantity */ void cancel(long orderId, long canceledQuantity, long remainingQuantity); }
package org.jvirtanen.parity.match; /** * <code>MarketListener</code> is the interface for outbound events from the * matching engine. */ public interface MarketListener { /** * Match an incoming order to a resting order in the order book. The match * occurs at the price of the order in the order book. * * @param restingOrderId the order identifier of the resting order * @param incomingOrderId the order identifier of the incoming order * @param incomingSide the side of the incoming order * @param price the execution price * @param executedQuantity the executed quantity * @param remainingQuantity the remaining quantity of the resting order */ void match(long restingOrderId, long incomingOrderId, Side incomingSide, long price, long executedQuantity, long remainingQuantity); /** * Add an order to the order book. * * @param orderId the order identifier * @param side the side * @param price the limit price * @param size the size */ void add(long orderId, Side side, long price, long size); /** * Cancel a quantity of an order. * * @param orderId the order identifier * @param canceledQuantity the canceled quantity * @param remainingQuantity the remaining quantity */ void cancel(long orderId, long canceledQuantity, long remainingQuantity); }
Add name attribute to function
package net.ssehub.kernel_haven.code_model.ast; import net.ssehub.kernel_haven.util.logic.Formula; import net.ssehub.kernel_haven.util.null_checks.NonNull; public class Function extends SyntaxElementWithChildreen { private @NonNull String name; private @NonNull SyntaxElement header; public Function(@NonNull Formula presenceCondition, @NonNull String name, @NonNull SyntaxElement header) { super(presenceCondition); this.header = header; this.name = name; } public @NonNull SyntaxElement getHeader() { return header; } public @NonNull String getName() { return name; } @Override protected @NonNull String elementToString(@NonNull String indentation) { return "Function " + name + "\n" + header.toString(indentation + "\t"); } @Override public void accept(@NonNull ISyntaxElementVisitor visitor) { visitor.visitFunction(this); } }
package net.ssehub.kernel_haven.code_model.ast; import net.ssehub.kernel_haven.util.logic.Formula; import net.ssehub.kernel_haven.util.null_checks.NonNull; public class Function extends SyntaxElementWithChildreen { private @NonNull SyntaxElement header; public Function(@NonNull Formula presenceCondition, @NonNull SyntaxElement header) { super(presenceCondition); this.header = header; } public @NonNull SyntaxElement getHeader() { return header; } @Override protected @NonNull String elementToString(@NonNull String indentation) { return "Function\n" + header.toString(indentation + "\t"); } @Override public void accept(@NonNull ISyntaxElementVisitor visitor) { visitor.visitFunction(this); } }
Update env - only load dotenv in development
'use strict'; var express = require('express'); var routes = require('./app/routes/index.js'); var mongoose = require('mongoose'); var passport = require('passport'); var session = require('express-session'); var bodyParser = require('body-parser'); var hbs = require('hbs'); var app = express(); if(process.env.NODE_ENV != "production") { require('dotenv').load(); }; require('./app/config/passport')(passport); mongoose.connect(process.env.MONGO_URI); mongoose.Promise = global.Promise; hbs.registerPartials(process.cwd() + '/app/views/partials'); app.use('/controllers', express.static(process.cwd() + '/app/controllers')); app.use('/public', express.static(process.cwd() + '/public')); app.use('/common', express.static(process.cwd() + '/app/common')); app.engine('html', hbs.__express); app.set('views', './app/views'); app.set('view engine', 'html'); app.use(session({ secret: 'secretClementine', resave: false, saveUninitialized: true })); app.use(passport.initialize()); app.use(passport.session()); app.use(bodyParser.urlencoded({ extend: true })); routes(app, passport); var port = process.env.PORT || 8080; app.listen(port, function () { console.log('Node.js listening on port ' + port + '...'); });
'use strict'; var express = require('express'); var routes = require('./app/routes/index.js'); var mongoose = require('mongoose'); var passport = require('passport'); var session = require('express-session'); var bodyParser = require('body-parser'); var hbs = require('hbs'); var app = express(); require('dotenv').load(); require('./app/config/passport')(passport); mongoose.connect(process.env.MONGO_URI); mongoose.Promise = global.Promise; hbs.registerPartials(process.cwd() + '/app/views/partials'); app.use('/controllers', express.static(process.cwd() + '/app/controllers')); app.use('/public', express.static(process.cwd() + '/public')); app.use('/common', express.static(process.cwd() + '/app/common')); app.engine('html', hbs.__express); app.set('views', './app/views'); app.set('view engine', 'html'); app.use(session({ secret: 'secretClementine', resave: false, saveUninitialized: true })); app.use(passport.initialize()); app.use(passport.session()); app.use(bodyParser.urlencoded({ extend: true })); routes(app, passport); var port = process.env.PORT || 8080; app.listen(port, function () { console.log('Node.js listening on port ' + port + '...'); });
Add label so we know where it came from
package comments import ( "log" "os" "github.com/google/go-github/github" ) var ( pendingFeedbackLabel = "pending-feedback" HandlerPendingFeedbackLabel = func(client *github.Client, event github.IssueCommentEvent) error { // if the comment is from the issue author & issue has the "pending-feedback", remove the label if os.Getenv("AUTO_REPLY_DEBUG") == "true" { log.Println("[pending_feedback_label]: received event:", event) } if *event.Sender.ID == *event.Issue.User.ID && hasLabel(event.Issue.Labels, pendingFeedbackLabel) { owner, name, number := *event.Repo.Owner.Login, *event.Repo.Name, *event.Issue.Number _, err := client.Issues.RemoveLabelForIssue(owner, name, number, pendingFeedbackLabel) if err != nil { log.Printf("[pending_feedback_label]: error removing label (%s/%s#%d): %v", owner, name, number, err) return err } return nil } return nil } ) func hasLabel(labels []github.Label, desiredLabel string) bool { for _, label := range labels { if *label.Name == desiredLabel { return true } } return false }
package comments import ( "log" "os" "github.com/google/go-github/github" ) var ( pendingFeedbackLabel = "pending-feedback" HandlerPendingFeedbackLabel = func(client *github.Client, event github.IssueCommentEvent) error { // if the comment is from the issue author & issue has the "pending-feedback", remove the label if os.Getenv("AUTO_REPLY_DEBUG") == "true" { log.Println("received event:", event) } if *event.Sender.ID == *event.Issue.User.ID && hasLabel(event.Issue.Labels, pendingFeedbackLabel) { owner, name, number := *event.Repo.Owner.Login, *event.Repo.Name, *event.Issue.Number _, err := client.Issues.RemoveLabelForIssue(owner, name, number, pendingFeedbackLabel) if err != nil { log.Printf("[pending_feedback_label]: error removing label (%s/%s#%d): %v", owner, name, number, err) return err } return nil } return nil } ) func hasLabel(labels []github.Label, desiredLabel string) bool { for _, label := range labels { if *label.Name == desiredLabel { return true } } return false }
Put ExcelWriter in pandas namespace
# pylint: disable-msg=W0614,W0401,W0611,W0622 __docformat__ = 'restructuredtext' from datetime import datetime import numpy as np try: import pandas._tseries as lib except Exception, e: # pragma: no cover if 'No module named' in str(e): raise ImportError('C extensions not built: if you installed already ' 'verify that you are not importing from the source ' 'directory') else: raise from pandas.version import version as __version__ from pandas.info import __doc__ from pandas.core.api import * from pandas.sparse.api import * from pandas.stats.api import * from pandas.core.format import (set_printoptions, reset_printoptions, set_eng_float_format) from pandas.io.parsers import read_csv, read_table, read_clipboard, ExcelFile, ExcelWriter from pandas.io.pytables import HDFStore from pandas.util.testing import debug from pandas.tools.merge import merge, concat from pandas.tools.pivot import pivot_table, crosstab from pandas.tools.describe import value_range
# pylint: disable-msg=W0614,W0401,W0611,W0622 __docformat__ = 'restructuredtext' from datetime import datetime import numpy as np try: import pandas._tseries as lib except Exception, e: # pragma: no cover if 'No module named' in str(e): raise ImportError('C extensions not built: if you installed already ' 'verify that you are not importing from the source ' 'directory') else: raise from pandas.version import version as __version__ from pandas.info import __doc__ from pandas.core.api import * from pandas.sparse.api import * from pandas.stats.api import * from pandas.core.format import (set_printoptions, reset_printoptions, set_eng_float_format) from pandas.io.parsers import read_csv, read_table, read_clipboard, ExcelFile from pandas.io.pytables import HDFStore from pandas.util.testing import debug from pandas.tools.merge import merge, concat from pandas.tools.pivot import pivot_table, crosstab from pandas.tools.describe import value_range
Fix brackets in the user number migration.
"""hide user numbers Revision ID: 2945717e3720 Revises: f8acbd22162 Create Date: 2016-01-31 00:43:02.777003 """ from alembic import op import sqlalchemy as sa from sqlalchemy.sql import table, column # revision identifiers, used by Alembic. revision = '2945717e3720' down_revision = 'f8acbd22162' branch_labels = None depends_on = None def upgrade(): ### commands auto generated by Alembic - please adjust! ### op.add_column('chat_users', sa.Column('show_user_numbers', sa.Boolean(), nullable=False, server_default=True)) op.add_column('users', sa.Column('show_user_numbers', sa.Boolean(), nullable=False, server_default=True)) ### end Alembic commands ### def downgrade(): ### commands auto generated by Alembic - please adjust! ### op.drop_column('users', 'show_user_numbers') op.drop_column('chat_users', 'show_user_numbers') ### end Alembic commands ###
"""hide user numbers Revision ID: 2945717e3720 Revises: f8acbd22162 Create Date: 2016-01-31 00:43:02.777003 """ from alembic import op import sqlalchemy as sa from sqlalchemy.sql import table, column # revision identifiers, used by Alembic. revision = '2945717e3720' down_revision = 'f8acbd22162' branch_labels = None depends_on = None def upgrade(): ### commands auto generated by Alembic - please adjust! ### op.add_column('chat_users', sa.Column('show_user_numbers', sa.Boolean()), nullable=False, server_default=True) op.add_column('users', sa.Column('show_user_numbers', sa.Boolean()), nullable=False, server_default=True) ### end Alembic commands ### def downgrade(): ### commands auto generated by Alembic - please adjust! ### op.drop_column('users', 'show_user_numbers') op.drop_column('chat_users', 'show_user_numbers') ### end Alembic commands ###
Use computeIfAbsent to avoid concurrency issues (cherry picked from commit a79513112c7e3b46370deca6d3bb1b47432df00b)
package liquibase.executor; import liquibase.database.Database; import liquibase.exception.UnexpectedLiquibaseException; import liquibase.servicelocator.ServiceLocator; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; public class ExecutorService { private static ExecutorService instance = new ExecutorService(); private Map<Database, Executor> executors = new ConcurrentHashMap<>(); private ExecutorService() { } public static ExecutorService getInstance() { return instance; } public Executor getExecutor(Database database) { return executors.computeIfAbsent(database, db -> { try { Executor executor = (Executor) ServiceLocator.getInstance().newInstance(Executor.class); executor.setDatabase(db); return executor; } catch (Exception e) { throw new UnexpectedLiquibaseException(e); } }); } public void setExecutor(Database database, Executor executor) { executors.put(database, executor); } public void clearExecutor(Database database) { executors.remove(database); } public void reset() { executors.clear(); } }
package liquibase.executor; import liquibase.database.Database; import liquibase.exception.UnexpectedLiquibaseException; import liquibase.servicelocator.ServiceLocator; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; public class ExecutorService { private static ExecutorService instance = new ExecutorService(); private Map<Database, Executor> executors = new ConcurrentHashMap<>(); private ExecutorService() { } public static ExecutorService getInstance() { return instance; } public Executor getExecutor(Database database) { if (!executors.containsKey(database)) { try { Executor executor = (Executor) ServiceLocator.getInstance().newInstance(Executor.class); executor.setDatabase(database); executors.put(database, executor); } catch (Exception e) { throw new UnexpectedLiquibaseException(e); } } return executors.get(database); } public void setExecutor(Database database, Executor executor) { executors.put(database, executor); } public void clearExecutor(Database database) { executors.remove(database); } public void reset() { executors.clear(); } }
[tracker] Add + button to add a model
<?php /* ---------------------------------------------------------------------- GLPI - Gestionnaire Libre de Parc Informatique Copyright (C) 2003-2008 by the INDEPNET Development Team. http://indepnet.net/ http://glpi-project.org/ ---------------------------------------------------------------------- LICENSE This file is part of GLPI. GLPI is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. GLPI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with GLPI; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ------------------------------------------------------------------------ */ // Original Author of file: David DURIEUX // Purpose of file: // ---------------------------------------------------------------------- if (!defined('GLPI_ROOT')) { define('GLPI_ROOT', '../../..'); } $NEEDED_ITEMS=array("tracker"); include (GLPI_ROOT."/inc/includes.php"); commonHeader($LANGTRACKER["title"][0],$_SERVER["PHP_SELF"],"plugins","tracker","models"); plugin_tracker_checkRight("errors","r"); echo plugin_tracker_models_infos(); commonFooter(); ?>
<?php /* ---------------------------------------------------------------------- GLPI - Gestionnaire Libre de Parc Informatique Copyright (C) 2003-2008 by the INDEPNET Development Team. http://indepnet.net/ http://glpi-project.org/ ---------------------------------------------------------------------- LICENSE This file is part of GLPI. GLPI is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. GLPI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with GLPI; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ------------------------------------------------------------------------ */ // Original Author of file: David DURIEUX // Purpose of file: // ---------------------------------------------------------------------- if (!defined('GLPI_ROOT')) { define('GLPI_ROOT', '../../..'); } $NEEDED_ITEMS=array("tracker"); include (GLPI_ROOT."/inc/includes.php"); commonHeader($LANGTRACKER["title"][0],$_SERVER["PHP_SELF"],"plugins","tracker"); plugin_tracker_checkRight("errors","r"); echo plugin_tracker_models_infos(); commonFooter(); ?>
Fix an error on the test
<?php namespace PiradoIV\Munchitos\Test; use \PiradoIV\Munchitos\Munchitos; class ImagesTest extends TestCase { public function setUp() { parent::setUp(); $this->html = <<<HTML <!doctype html> <html> <body> <a href="http://www.example.org/"> <img src="images/testing.png" alt="Testing alt" /> </a> </body> </html>> HTML; $this->munchitos = new Munchitos; $this->munchitos->html($this->html); } public function testCanFetchImages() { $images = $this->munchitos->images(); $this->assertEquals(1, count($images)); } public function testImagesAltText() { $images = $this->munchitos->images(); $this->assertEquals('Testing alt', $images[0]->altText()); } }
<?php namespace PiradoIV\Munchitos\Test; use \PiradoIV\Munchitos\Munchitos; class ImagesTest extends TestCase { public function setUp() { parent::setUp(); $this->html = <<<HTML <!doctype html> <html> <body> <a href="http://www.example.org/"> <img src="images/testing.png" alt="Testing alt" /> </a> </body> </html>> HTML; $this->munchitos = new Munchitos; $this->munchitos->html($this->html); } public function testCanFetchImages() { $images = $this->munchitos->images(); $this->assertEquals(1, count($images)); } public function testImagesAltText() { $images = $this->munchitos()->images(); $this->assertEquals('Testing alt', $images[0]->altText()); } }
Break the build for kicks
import { addError } from './codeship-notifications'; describe('codeship-notifications/add-error', () => { beforeAll(() => { global.atom = { notifications: { addError: jest.fn(), }, }; }); afterAll(() => { global.atom = undefined; }); it('adds error notification to atom', () => { addError({ project: { id: '123', name: 'test', }, branch: 'test-feature', build: { id: 'abc', }, commit: { message: 'making some changes', }, }); expect(atom.notifications.addError).toHaveBeenCalledTimes(0); }); });
import { addError } from './codeship-notifications'; describe('codeship-notifications/add-error', () => { beforeAll(() => { global.atom = { notifications: { addError: jest.fn(), }, }; }); afterAll(() => { global.atom = undefined; }); it('adds error notification to atom', () => { addError({ project: { id: '123', name: 'test', }, branch: 'test-feature', build: { id: 'abc', }, commit: { message: 'making some changes', }, }); expect(atom.notifications.addError).toHaveBeenCalledTimes(1); }); });
Update for plug-in : wallhaven.cc
var hoverZoomPlugins = hoverZoomPlugins || []; hoverZoomPlugins.push({ name: 'wallhaven.cc', version:'3.0', prepareImgLinks: function (callback) { var res = []; hoverZoom.urlReplace(res, 'img[src*="/th.wallhaven.cc/"]', /\/th.wallhaven.cc\/(.*)\/(.*)\/(.*)\.(.*)$/, '/w.wallhaven.cc/full/$2/wallhaven-$3.jpg' ); hoverZoom.urlReplace(res, 'img[src]', /\/avatar\/\d+\//, '/avatar/200/' ); $('body').on('mouseenter', 'a[href*="/wallhaven.cc/w/"]', function () { hoverZoom.prepareFromDocument($(this), this.href, function (doc) { var img = doc.getElementById('wallpaper'); return img ? img.src : false; }); }); callback($(res)); }, });
var hoverZoomPlugins = hoverZoomPlugins || []; hoverZoomPlugins.push({ name: 'wallhaven.cc', prepareImgLinks: function (callback) { var res = []; hoverZoom.urlReplace(res, 'img[src*="/th.wallhaven.cc/"]', /\/th.wallhaven.cc\/(.*)\/(.*)\/(.*)\.(.*)$/, '/w.wallhaven.cc/full/$2/wallhaven-$3.jpg' ); $('body').on('mouseenter', 'a[href*="/wallhaven.cc/w/"]', function () { hoverZoom.prepareFromDocument($(this), this.href, function (doc) { var img = doc.getElementById('wallpaper'); return img ? img.src : false; }); }); callback($(res)); }, });
Remove Babel dependency and convert to standard code style
const TabStop = require('./tab-stop') class TabStopList { constructor (snippet) { this.snippet = snippet this.list = {} } get length () { return Object.keys(this.list).length } findOrCreate ({ index, snippet }) { if (!this.list[index]) { this.list[index] = new TabStop({ index, snippet }) } return this.list[index] } forEachIndex (iterator) { let indices = Object.keys(this.list).sort((a1, a2) => a1 - a2) indices.forEach(iterator) } getInsertions () { let results = [] this.forEachIndex(index => { results.push(...this.list[index].insertions) }) return results } toArray () { let results = [] this.forEachIndex(index => { let tabStop = this.list[index] if (!tabStop.isValid()) return results.push(tabStop) }) return results } } module.exports = TabStopList
/** @babel */ import TabStop from './tab-stop'; class TabStopList { constructor (snippet) { this.snippet = snippet; this.list = {}; } get length () { return Object.keys(this.list).length; } findOrCreate({ index, snippet }) { if (!this.list[index]) { this.list[index] = new TabStop({ index, snippet }); } return this.list[index]; } forEachIndex (iterator) { let indices = Object.keys(this.list).sort((a1, a2) => a1 - a2); indices.forEach(iterator); } getInsertions () { let results = []; this.forEachIndex(index => { results.push(...this.list[index].insertions); }); return results; } toArray () { let results = []; this.forEachIndex(index => { let tabStop = this.list[index]; if (!tabStop.isValid()) return; results.push(tabStop); }); return results; } } export default TabStopList;
Remove focus effect on readonly fields
$(window).load(function(){ var selector = '.settings-nav li'; $(selector).not(".collapse-li").click(function () { $(selector).not(".collapse-li").removeClass('active'); }); // Show the relevant tab from url var url = document.location.toString(); if (url.match('#')) { $('.settings-nav a[href="#' + url.split('#')[1] + '"]').tab('show'); } else { $('.settings-content > .tab-pane:first-child').addClass('active'); $('.settings-nav > ul > li:first-child a').removeClass('collapsed'); $('#profile-menu li:first-child').addClass('active'); } $( ".sub-menu" ).each(function( index ) { if ($(this).children('li').hasClass('active')) { $(this).addClass('in'); } }); // Change hash for select tab $('.settings-nav a, .sub-menu a').on('shown.bs.tab', function (e) { window.location.hash = e.target.hash; $(window).scrollTop(0); }); $('input[readonly]').on('focus', function () { this.blur(); }); });
$(window).load(function(){ var selector = '.settings-nav li'; $(selector).not(".collapse-li").click(function () { $(selector).not(".collapse-li").removeClass('active'); }); // Show the relevant tab from url var url = document.location.toString(); if (url.match('#')) { $('.settings-nav a[href="#' + url.split('#')[1] + '"]').tab('show'); } else { $('.settings-content > .tab-pane:first-child').addClass('active'); $('.settings-nav > ul > li:first-child a').removeClass('collapsed'); $('#profile-menu li:first-child').addClass('active'); } $( ".sub-menu" ).each(function( index ) { if ($(this).children('li').hasClass('active')) { $(this).addClass('in'); } }); // Change hash for select tab $('.settings-nav a, .sub-menu a').on('shown.bs.tab', function (e) { window.location.hash = e.target.hash; $(window).scrollTop(0); }); });
Add necessary behaviors and validation rules.
<?php namespace common\models\comments; use yii\db\ActiveRecord; use yii\behaviors\TimestampBehavior; use yii\behaviors\BlameableBehavior; abstract class Comment extends ActiveRecord { public static function instantiate($row) { return new AdjacencyListComment(); } public static function create($config = []) { return new AdjacencyListComment($config); } /** * @inheritdoc */ public function behaviors() { return [ TimestampBehavior::className(), ['class' => BlameableBehavior::className(), 'createdByAttribute' => 'author_id', 'updatedByAttribute' => false], ]; } public function rules() { return [ ['text', 'filter', 'filter' => 'trim'], ['text', 'required'], ['text', 'string', 'min' => 5, 'max' => 10000], ]; } }
<?php namespace common\models\comments; use yii\db\ActiveRecord; use yii\behaviors\TimestampBehavior; use yii\behaviors\BlameableBehavior; abstract class Comment extends ActiveRecord { public static function instantiate($row) { return new AdjacencyListComment(); } public static function create($config = []) { return new AdjacencyListComment($config); } /** * @inheritdoc */ public function behaviors() { return [ TimestampBehavior::className(), ['class' => BlameableBehavior::className(), 'createdByAttribute' => 'author_id', 'updatedByAttribute' => false], ]; } public function rules() { return [ ['text', 'filter', 'filter' => 'trim'], ['text', 'required'], ['text', 'string', 'min' => 10, 'max' => 10000], ]; } }
Fix typo in inventory API test script.
#!/usr/bin/env python import json import sys from optparse import OptionParser parser = OptionParser() parser.add_option('-l', '--list', default=False, dest="list_hosts", action="store_true") parser.add_option('-H', '--host', default=None, dest="host") parser.add_option('-e', '--extra-vars', default=None, dest="extra") options, args = parser.parse_args() systems = { "ungrouped": [ "jupiter", "saturn" ], "greek": [ "zeus", "hera", "poseidon" ], "norse": [ "thor", "odin", "loki" ] } variables = { "thor": { "hammer": True } } if options.list_hosts == True: print json.dumps(systems) sys.exit(0) if options.host is not None: if options.extra: k,v = options.extra.split("=") variables[options.host][k] = v print json.dumps(variables[options.host]) sys.exit(0) parser.print_help() sys.exit(1)
#!/usr/bin/env python import json import sys from optparse import OptionParser parser = OptionParser() parser.add_option('-l', '--list', default=False, dest="list_hosts", action="store_true") parser.add_option('-H', '--host', default=None, dest="host") parser.add_option('-e', '--extra-vars', default=None, dest="extra") options, args = parser.parse_args() systems = { "ungouped": [ "jupiter", "saturn" ], "greek": [ "zeus", "hera", "poseidon" ], "norse": [ "thor", "odin", "loki" ] } variables = { "thor": { "hammer": True } } if options.list_hosts == True: print json.dumps(systems) sys.exit(0) if options.host is not None: if options.extra: k,v = options.extra.split("=") variables[options.host][k] = v print json.dumps(variables[options.host]) sys.exit(0) parser.print_help() sys.exit(1)
Write function to deal with colons in url
import React from 'react' import {connect} from 'react-redux'; const Article = ({article, channelName}) => { return ( <div> <h1>{article.title}</h1> <img src={article.urlToImage} className="image"/> <h5>Posted at: {article.publishedAt}</h5> <p>{article.description}</p> <a href={article.url} target="_blank">Read full article on {channelName}</a> </div> ) } //Fix glitch in Match object encoding so match.params matches article.title function fixMatchParams(matchParams) { if (matchParams.split("%3A")) { return matchParams.split("%3A").join(":") } else { return matchParams } } function mapStateToProps(state, ownProps) { const matchParams = fixMatchParams(ownProps.match.params.article) var articles = [] if (state.articles.find(channel => channel.name === ownProps.channelName)) { articles = state.articles.find(channel => channel.name === ownProps.channelName).articles; } const article = articles.find(article => article.title === matchParams) if (article) { return { article: article } } else { return { article: {} } } } export default connect(mapStateToProps)(Article)
import React from 'react' import {connect} from 'react-redux'; const Article = ({article, channelName}) => { return ( <div> <h1>{article.title}</h1> <img src={article.urlToImage} className="image"/> <h5>Posted at: {article.publishedAt}</h5> <p>{article.description}</p> <a href={article.url} target="_blank">Read full article on {channelName}</a> </div> ) } function mapStateToProps(state, ownProps) { var articles = [] if (state.articles.find(channel => channel.name === ownProps.channelName)) { articles = state.articles.find(channel => channel.name === ownProps.channelName).articles; } const article = articles.find(article => article.title === ownProps.match.params.article) if (article) { return { article: article } } else { return { article: {} } } } export default connect(mapStateToProps)(Article)
Make sure s.Relevance is normalized (0, 1)
package scoring import ( "fmt" "math" "time" ) // A point of reference Score.Update and Score.Relevance use to reference the // current time. It is used in testing, so we always have the same current // time. This is okay for this programs as it won't run for long. var Now time.Time // Represents a weight of a score and the age of it. type Score struct { Weight int64 Age time.Time } // Update the weight and age of the current score. func (s *Score) Update() { s.Weight++ s.Age = Now } // Relevance of a score is the difference between the current time and when the // score was last updated. func (s *Score) Relevance() float64 { return float64(s.Age.Unix()) / float64(Now.Unix()) } // Calculate the final score from the score weight and the age. func (s *Score) Calculate() float64 { return float64(s.Weight) * math.Log(s.Relevance()) } // Calculate the final score from the score weight and the age. func (s *Score) String() string { return fmt.Sprintf("{%s %s}", s.Weight, s.Age) } // Create a new score object with default weight of 1 and age set to now. func NewScore() *Score { return &Score{1, Now} } func init() { Now = time.Now() }
package scoring import ( "fmt" "math" "time" ) // A point of reference Score.Update and Score.Relevance use to reference the // current time. It is used in testing, so we always have the same current // time. This is okay for this programs as it won't run for long. var Now time.Time // Represents a weight of a score and the age of it. type Score struct { Weight int64 Age time.Time } // Update the weight and age of the current score. func (s *Score) Update() { s.Weight++ s.Age = Now } // Relevance of a score is the difference between the current time and when the // score was last updated. func (s *Score) Relevance() time.Duration { return Now.Sub(s.Age) } // Calculate the final score from the score weight and the age. func (s *Score) Calculate() float64 { return float64(s.Weight) * math.Log(float64(s.Relevance())) } // Calculate the final score from the score weight and the age. func (s *Score) String() string { return fmt.Sprintf("{%s %s}", s.Weight, s.Age) } // Create a new score object with default weight of 1 and age set to now. func NewScore() *Score { return &Score{1, Now} } func init() { Now = time.Now() }
Fix provider constant in the example. git-svn-id: 353d90d4d8d13dcb4e0402680a9155a727f61a5a@1090630 13f79535-47bb-0310-9956-ffa450edef68
# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from pprint import pprint from libcloud.storage.types import Provider from libcloud.storage.providers import get_driver CloudFiles = get_driver(Provider.CLOUDFILES) driver = CloudFiles('access key id', 'secret key') containers = driver.list_containers() container_objects = driver.list_container_objects(containers[0]) pprint(containers) pprint(container_objects)
# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from pprint import pprint from libcloud.storage.types import Provider from libcloud.storage.providers import get_driver CloudFiles = get_driver(Provider.CloudFiles) driver = CloudFiles('access key id', 'secret key') containers = driver.list_containers() container_objects = driver.list_container_objects(containers[0]) pprint(containers) pprint(container_objects)
Add a comment to explain fsCall() safety checks
//go:build js package syscall import ( "syscall/js" ) // fsCall emulates a file system-related syscall via a corresponding NodeJS fs // API. // // This version is similar to the upstream, but it gracefully handles missing fs // methods (allowing for smaller prelude) and removes a workaround for an // obsolete NodeJS version. func fsCall(name string, args ...interface{}) (js.Value, error) { type callResult struct { val js.Value err error } c := make(chan callResult, 1) f := js.FuncOf(func(this js.Value, args []js.Value) interface{} { var res callResult // Check that args has at least one element, then check both IsUndefined() and IsNull() on // that element. In some situations, BrowserFS calls the callback without arguments or with // an undefined argument: https://github.com/gopherjs/gopherjs/pull/1118 if len(args) >= 1 { if jsErr := args[0]; !jsErr.IsUndefined() && !jsErr.IsNull() { res.err = mapJSError(jsErr) } } res.val = js.Undefined() if len(args) >= 2 { res.val = args[1] } c <- res return nil }) defer f.Release() if jsFS.Get(name).IsUndefined() { return js.Undefined(), ENOSYS } jsFS.Call(name, append(args, f)...) res := <-c return res.val, res.err }
//go:build js package syscall import ( "syscall/js" ) // fsCall emulates a file system-related syscall via a corresponding NodeJS fs // API. // // This version is similar to the upstream, but it gracefully handles missing fs // methods (allowing for smaller prelude) and removes a workaround for an // obsolete NodeJS version. func fsCall(name string, args ...interface{}) (js.Value, error) { type callResult struct { val js.Value err error } c := make(chan callResult, 1) f := js.FuncOf(func(this js.Value, args []js.Value) interface{} { var res callResult if len(args) >= 1 { if jsErr := args[0]; !jsErr.IsUndefined() && !jsErr.IsNull() { res.err = mapJSError(jsErr) } } res.val = js.Undefined() if len(args) >= 2 { res.val = args[1] } c <- res return nil }) defer f.Release() if jsFS.Get(name).IsUndefined() { return js.Undefined(), ENOSYS } jsFS.Call(name, append(args, f)...) res := <-c return res.val, res.err }
Add more modules to vendor entry
var path = require('path'); var webpack = require('webpack'); var ExtractTextPlugin = require('extract-text-webpack-plugin'); var BundleTracker = require('webpack-bundle-tracker'); var CommonsChunkPlugin = require("webpack/lib/optimize/CommonsChunkPlugin"); module.exports = { context: __dirname, devtool: 'eval-source-map', entry: { // Used to extract common libraries vendor: [ 'classnames', 'es6-promise', 'isomorphic-fetch', 'moment', 'react', 'react-bootstrap', 'react-dom' ], frontpageEvents: [ './assets/js/frontpage/events/index' ] }, output: { path: path.resolve('./assets/webpack_bundles/'), filename: '[name]-[hash].js' }, module: { loaders: [ { test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader' }, { test: /\.less$/, loader: ExtractTextPlugin.extract('style', 'css!less'), } ] }, lessLoader: { includePath: [path.resolve(__dirname, './styles')] }, plugins: [ new CommonsChunkPlugin({ names: ['vendor'], minChunks: Infinity }), new BundleTracker({filename: './webpack-stats.json'}) ] };
var path = require('path'); var webpack = require('webpack'); var ExtractTextPlugin = require('extract-text-webpack-plugin'); var BundleTracker = require('webpack-bundle-tracker'); var CommonsChunkPlugin = require("webpack/lib/optimize/CommonsChunkPlugin"); module.exports = { context: __dirname, devtool: 'eval-source-map', entry: { // Used to extract common libraries vendor: ['react', 'react-dom'], frontpageEvents: [ './assets/js/frontpage/events/index' ] }, output: { path: path.resolve('./assets/webpack_bundles/'), filename: '[name]-[hash].js' }, module: { loaders: [ { test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader' }, { test: /\.less$/, loader: ExtractTextPlugin.extract('style', 'css!less'), } ] }, lessLoader: { includePath: [path.resolve(__dirname, './styles')] }, plugins: [ new CommonsChunkPlugin({ names: ['vendor'], minChunks: Infinity }), new BundleTracker({filename: './webpack-stats.json'}) ] };
Correct permission tests for organization stats
from __future__ import absolute_import from django.core.urlresolvers import reverse from sentry.testutils import TestCase, PermissionTestCase class OrganizationStatsPermissionTest(PermissionTestCase): def setUp(self): super(OrganizationStatsPermissionTest, self).setUp() self.path = reverse('sentry-organization-stats', args=[self.organization.slug]) def test_teamless_admin_cannot_load(self): self.assert_teamless_admin_cannot_access(self.path) def test_org_member_can_load(self): self.assert_org_member_can_access(self.path) class OrganizationStatsTest(TestCase): def test_renders_with_context(self): organization = self.create_organization(name='foo', owner=self.user) team_1 = self.create_team(name='foo', organization=organization) team_2 = self.create_team(name='bar', organization=organization) path = reverse('sentry-organization-stats', args=[organization.slug]) self.login_as(self.user) resp = self.client.get(path) assert resp.status_code == 200 self.assertTemplateUsed(resp, 'sentry/organization-stats.html') assert resp.context['organization'] == organization
from __future__ import absolute_import from django.core.urlresolvers import reverse from sentry.testutils import TestCase, PermissionTestCase class OrganizationStatsPermissionTest(PermissionTestCase): def setUp(self): super(OrganizationStatsPermissionTest, self).setUp() self.path = reverse('sentry-organization-stats', args=[self.organization.slug]) def test_teamless_admin_cannot_load(self): self.assert_teamless_admin_cannot_access(self.path) def test_org_member_cannot_load(self): self.assert_org_member_cannot_access(self.path) def test_org_admin_can_load(self): self.assert_org_admin_can_access(self.path) class OrganizationStatsTest(TestCase): def test_renders_with_context(self): organization = self.create_organization(name='foo', owner=self.user) team_1 = self.create_team(name='foo', organization=organization) team_2 = self.create_team(name='bar', organization=organization) path = reverse('sentry-organization-stats', args=[organization.slug]) self.login_as(self.user) resp = self.client.get(path) assert resp.status_code == 200 self.assertTemplateUsed(resp, 'sentry/organization-stats.html') assert resp.context['organization'] == organization
Allow POST requests on server side
"""Web app that serves proselint's API.""" from flask import Flask, request import subprocess from flask_cors import CORS, cross_origin import uuid import os import re import urllib2 import json app = Flask(__name__) cors = CORS(app) app.config['CORS_HEADERS'] = "Origin, X-Requested-With,Content-Type, Accept" @app.route('/v1/', methods=['GET', 'POST']) @cross_origin() # allow all origins all methods. def lint(): """Run linter on the provided text and return the results.""" id = uuid.uuid4() filename = os.path.join("tmp", "{}.md".format(id)) text = urllib2.unquote(request.values['text']) with open(filename, "w+") as f: f.write(text) out = subprocess.check_output("proselint {}".format(filename), shell=True) r = re.compile( "(?:.*).md:(?P<line>\d*):(?P<column>\d*): (?P<err>\w{6}) (?P<msg>.*)") out2 = sorted([r.search(line).groupdict() for line in out.splitlines()]) return json.dumps(out2) if __name__ == '__main__': app.debug = True app.run()
"""Web app that serves proselint's API.""" from flask import Flask, request import subprocess from flask_cors import CORS, cross_origin import uuid import os import re import urllib2 import json app = Flask(__name__) cors = CORS(app) app.config['CORS_HEADERS'] = "Origin, X-Requested-With,Content-Type, Accept" @app.route('/v1/') @cross_origin() # allow all origins all methods. def lint(): """Run linter on the provided text and return the results.""" id = uuid.uuid4() filename = os.path.join("tmp", "{}.md".format(id)) text = urllib2.unquote(request.values['text']) with open(filename, "w+") as f: f.write(text) out = subprocess.check_output("proselint {}".format(filename), shell=True) r = re.compile( "(?:.*).md:(?P<line>\d*):(?P<column>\d*): (?P<err>\w{6}) (?P<msg>.*)") out2 = sorted([r.search(line).groupdict() for line in out.splitlines()]) return json.dumps(out2) if __name__ == '__main__': app.debug = True app.run()
Fix broken list_methods due to inspect behaviour
#!/usr/bin/env python # vim: set fileencoding=UTF-8 : import inspect class DynamicMethods(object): def list_methods(self, predicate): """Find all transform methods within the class that satisfies the predicate. Returns: A list of tuples containing method names and corresponding methods that can be called with a tree as the argument for each method. """ methods = [member[0] for member in inspect.getmembers(self, predicate=inspect.ismethod)] return [getattr(self, method) for method in methods if not method.startswith('_') and method != 'list_methods' and predicate(method)] class Comparable(object): def __ne__(self, other): return not self.__eq__(other) def __ge__(self, other): return not self.__lt__(other) def __gt__(self, other): return not self.__eq__(other) and not self.__lt__(other) def __le__(self, other): return not self.__gt__(other)
#!/usr/bin/env python # vim: set fileencoding=UTF-8 : import inspect class DynamicMethods(object): def list_methods(self, predicate): """Find all transform methods within the class that satisfies the predicate. Returns: A list of tuples containing method names and corresponding methods that can be called with a tree as the argument for each method. """ methods = [member[0] for member in inspect.getmembers( self.__class__, predicate=inspect.ismethod)] return [getattr(self, method) for method in methods if not method.startswith('_') and method != 'list_methods' and predicate(method)] class Comparable(object): def __ne__(self, other): return not self.__eq__(other) def __ge__(self, other): return not self.__lt__(other) def __gt__(self, other): return not self.__eq__(other) and not self.__lt__(other) def __le__(self, other): return not self.__gt__(other)
[ProductVariant] Add locale to product variant query builders
<?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\Product\Repository; use Doctrine\ORM\QueryBuilder; use Sylius\Component\Product\Model\ProductInterface; use Sylius\Component\Product\Model\ProductVariantInterface; use Sylius\Component\Resource\Repository\RepositoryInterface; /** * @author Łukasz Chruściel <lukasz.chrusciel@lakion.com> */ interface ProductVariantRepositoryInterface extends RepositoryInterface { /** * @param string $locale * @param mixed $productId * * @return QueryBuilder */ public function createQueryBuilderByProductId($locale, $productId); /** * @param string $name * @param string $locale * * @return ProductVariantInterface[] */ public function findByName($name, $locale); /** * @param string $name * @param string $locale * @param ProductInterface $product * * @return ProductVariantInterface[] */ public function findByNameAndProduct($name, $locale, ProductInterface $product); }
<?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\Product\Repository; use Doctrine\ORM\QueryBuilder; use Sylius\Component\Product\Model\ProductInterface; use Sylius\Component\Product\Model\ProductVariantInterface; use Sylius\Component\Resource\Repository\RepositoryInterface; /** * @author Łukasz Chruściel <lukasz.chrusciel@lakion.com> */ interface ProductVariantRepositoryInterface extends RepositoryInterface { /** * @param mixed $productId * * @return QueryBuilder */ public function createQueryBuilderByProductId($productId); /** * @param string $name * @param string $locale * * @return ProductVariantInterface[] */ public function findByName($name, $locale); /** * @param string $name * @param string $locale * @param ProductInterface $product * * @return ProductVariantInterface[] */ public function findByNameAndProduct($name, $locale, ProductInterface $product); }
Allow opening a database (bolt, leveldb, mongo) through Go API
package cayley import ( "github.com/google/cayley/graph" _ "github.com/google/cayley/graph/memstore" "github.com/google/cayley/graph/path" "github.com/google/cayley/quad" _ "github.com/google/cayley/writer" ) type Iterator graph.Iterator type QuadStore graph.QuadStore type QuadWriter graph.QuadWriter type Path path.Path var StartMorphism = path.StartMorphism var StartPath = path.StartPath var RawNext = graph.Next type Handle struct { graph.QuadStore graph.QuadWriter } func Quad(subject, predicate, object, label string) quad.Quad { return quad.Quad{subject, predicate, object, label} } func NewGraph(name, dbpath string, opts graph.Options) (*Handle, error) { qs, err := graph.NewQuadStore(name, dbpath, opts) if err != nil { return nil, err } qw, err := graph.NewQuadWriter("single", qs, nil) if err != nil { return nil, err } return &Handle{qs, qw}, nil } func NewMemoryGraph() (*Handle, error) { return NewGraph("memstore", "", nil) } func (h *Handle) Close() { h.QuadStore.Close() h.QuadWriter.Close() }
package cayley import ( "github.com/google/cayley/graph" _ "github.com/google/cayley/graph/memstore" "github.com/google/cayley/graph/path" "github.com/google/cayley/quad" _ "github.com/google/cayley/writer" ) type Iterator graph.Iterator type QuadStore graph.QuadStore type QuadWriter graph.QuadWriter type Path path.Path var StartMorphism = path.StartMorphism var StartPath = path.StartPath var RawNext = graph.Next type Handle struct { graph.QuadStore graph.QuadWriter } func Quad(subject, predicate, object, label string) quad.Quad { return quad.Quad{subject, predicate, object, label} } func NewMemoryGraph() (*Handle, error) { qs, err := graph.NewQuadStore("memstore", "", nil) if err != nil { return nil, err } qw, err := graph.NewQuadWriter("single", qs, nil) if err != nil { return nil, err } return &Handle{qs, qw}, nil } func (h *Handle) Close() { h.QuadStore.Close() h.QuadWriter.Close() }
Add defined() guard around define(ARTISAN_BINARY)
<?php namespace OpenDominion; use Illuminate\Foundation\Application as LaravelApplication; class Application extends LaravelApplication { protected $appPath; public function __construct($basePath) { parent::__construct($basePath); $this->appPath = ($this->basePath() . DIRECTORY_SEPARATOR . 'app'); $this->bindPathsInContainer(); if (!defined('ARTISAN_BINARY')) { define('ARTISAN_BINARY', 'bin/artisan'); } } public function path($path = '') { return ($this->basePath . DIRECTORY_SEPARATOR . 'src'); } public function bootstrapPath($path = '') { return ($this->appPath . DIRECTORY_SEPARATOR . 'bootstrap'); } public function configPath($path = '') { return ($this->appPath . DIRECTORY_SEPARATOR . 'config'); } public function databasePath($path = '') { return ($this->appPath . DIRECTORY_SEPARATOR . 'database'); } public function langPath() { return ($this->appPath . DIRECTORY_SEPARATOR . 'resources' . DIRECTORY_SEPARATOR . 'lang'); } public function storagePath() { return ($this->appPath . DIRECTORY_SEPARATOR . 'storage'); } }
<?php namespace OpenDominion; use Illuminate\Foundation\Application as LaravelApplication; class Application extends LaravelApplication { protected $appPath; public function __construct($basePath) { parent::__construct($basePath); $this->appPath = ($this->basePath() . DIRECTORY_SEPARATOR . 'app'); $this->bindPathsInContainer(); define('ARTISAN_BINARY', 'bin/artisan'); } public function path($path = '') { return ($this->basePath . DIRECTORY_SEPARATOR . 'src'); } public function bootstrapPath($path = '') { return ($this->appPath . DIRECTORY_SEPARATOR . 'bootstrap'); } public function configPath($path = '') { return ($this->appPath . DIRECTORY_SEPARATOR . 'config'); } public function databasePath($path = '') { return ($this->appPath . DIRECTORY_SEPARATOR . 'database'); } public function langPath() { return ($this->appPath . DIRECTORY_SEPARATOR . 'resources' . DIRECTORY_SEPARATOR . 'lang'); } public function storagePath() { return ($this->appPath . DIRECTORY_SEPARATOR . 'storage'); } }
Add finally blocks to ensure tests always clean up
#!/usr/bin/env python # -*- coding: utf-8 -*- from contextlib import contextmanager from io import BytesIO import sys import mock_modules import yv_suggest.shared as yvs @contextmanager def redirect_stdout(): """temporarily redirect stdout to new output stream""" original_stdout = sys.stdout out = BytesIO() try: sys.stdout = out yield out finally: sys.stdout = original_stdout @contextmanager def preserve_prefs(): """safely retrieve and restore preferences""" original_prefs = yvs.get_prefs() try: yield original_prefs.copy() finally: yvs.update_prefs(original_prefs) @contextmanager def preserve_recent_refs(): """safely retrieve and restore list of recent references""" original_recent_refs = yvs.get_recent_refs() try: yield original_recent_refs[:] finally: yvs.update_recent_refs(original_recent_refs) @contextmanager def mock_webbrowser(yvs): mock = mock_modules.WebbrowserMock() original_webbrowser = yvs.webbrowser yvs.webbrowser = mock try: yield mock finally: yvs.webbrowser = original_webbrowser
#!/usr/bin/env python # -*- coding: utf-8 -*- from contextlib import contextmanager from io import BytesIO import sys import mock_modules import yv_suggest.shared as yvs @contextmanager def redirect_stdout(): """temporarily redirect stdout to new output stream""" original_stdout = sys.stdout out = BytesIO() try: sys.stdout = out yield out finally: sys.stdout = original_stdout @contextmanager def preserve_prefs(): """safely retrieve and restore preferences""" original_prefs = yvs.get_prefs() yield original_prefs.copy() yvs.update_prefs(original_prefs) @contextmanager def preserve_recent_refs(): """safely retrieve and restore list of recent references""" original_recent_refs = yvs.get_recent_refs() yield original_recent_refs[:] yvs.update_recent_refs(original_recent_refs) @contextmanager def mock_webbrowser(yvs): mock = mock_modules.WebbrowserMock() original_webbrowser = yvs.webbrowser yvs.webbrowser = mock yield mock yvs.webbrowser = original_webbrowser
Hide the button after adding the page
$('#likes').click(function() { var catid; catid = $(this).attr('data-catid'); $.get('/rango/like_category/', {category_id: catid}, function(data) { $('#like_count').html(data); $('#likes').hide(); }); }); $('#suggestion').keyup(function () { var query; query = $(this).val(); $.get('/rango/suggest_category/', {suggestion: query}, function(data) { $('#cats').html(data); }); }); $('.rango-add').click(function() { var catid, title, url; catid = $(this).attr('data-catid'); title = $(this).attr('data-title'); url = $(this).attr('data-url'); var $this = $(this); $.get('/rango/auto_add_page/', {category_id: catid, title: title, url: url}, function(data) { $('#pages').html(data); $this.hide(); }); });
$('#likes').click(function() { var catid; catid = $(this).attr('data-catid'); $.get('/rango/like_category/', {category_id: catid}, function(data) { $('#like_count').html(data); $('#likes').hide(); }); }); $('#suggestion').keyup(function () { var query; query = $(this).val(); $.get('/rango/suggest_category/', {suggestion: query}, function(data) { $('#cats').html(data); }); }); $('.rango-add').click(function() { var catid, title, url; catid = $(this).attr('data-catid'); title = $(this).attr('data-title'); url = $(this).attr('data-url'); $.get('/rango/auto_add_page/', {category_id: catid, title: title, url: url}, function(data) { $('#pages').html(data); }); });
Add example of scheme_eval_v usage
#! /usr/bin/env python # # values.py # """ An example of using values via Python API """ from opencog.atomspace import AtomSpace, TruthValue from opencog.type_constructors import * from opencog.scheme_wrapper import scheme_eval_v atomspace = AtomSpace() set_type_ctor_atomspace(atomspace) a = FloatValue([1.0, 2.0, 3.0]) b = FloatValue([1.0, 2.0, 3.0]) c = FloatValue(1.0) print('{} == {}: {}'.format(a, b, a == b)) print('{} == {}: {}'.format(a, c, a == c)) featureValue = FloatValue([1.0, 2]) print('new value created: {}'.format(featureValue)) boundingBox = ConceptNode('boundingBox') featureKey = PredicateNode('features') boundingBox.set_value(featureKey, featureValue) print('set value to atom: {}'.format(boundingBox)) print('get value from atom: {}'.format(boundingBox.get_value(featureKey))) value = scheme_eval_v(atomspace, '(ValueOf (ConceptNode "boundingBox") ' '(PredicateNode "features"))') value = boundingBox.get_value(featureKey) print('get value from atom using Scheme program: {}'.format(value))
#! /usr/bin/env python # # values.py # """ An example of using values via Python API """ from opencog.atomspace import AtomSpace, TruthValue from opencog.type_constructors import * a = AtomSpace() set_type_ctor_atomspace(a) a = FloatValue([1.0, 2.0, 3.0]) b = FloatValue([1.0, 2.0, 3.0]) c = FloatValue(1.0) print('{} == {}: {}'.format(a, b, a == b)) print('{} == {}: {}'.format(a, c, a == c)) featureValue = FloatValue([1.0, 2]) print('new value created: {}'.format(featureValue)) boundingBox = ConceptNode('boundingBox') featureKey = PredicateNode('features') boundingBox.set_value(featureKey, featureValue) print('set value to atom: {}'.format(boundingBox)) print('get value from atom: {}'.format(boundingBox.get_value(featureKey)))
Add "is it" as option to ask for temperature
module.exports = { 'responses': { 'GREET': 'Hello! How are you doing today :\)', 'HELP': 'I can help you with a bunch of things around your house.\n\n' + 'You can check in on your security cameras, ask me the temperature, and much more!\n' + 'I will also notify you during events such as a visitor at your door.', 'TFLUK': 'Okay. Thanks for letting me know.' }, 'words': { 'DISPLAY': ['tell', 'give', 'show', 'what', 'what\'s', 'display', 'how', 'is it'], 'TEMPERATURE': ['temperature', 'temp', 'heat', 'hot', 'warm', 'cold'], 'GREET': ['hello', 'hi', 'hey', 'good day', 'what\'s up', 'whats up', 'sup', 'good morning', 'good evening'], 'STATE': ['i am', 'i\'m', 'im '], 'CAM': ['cam', 'camera', 'pic', 'picture', 'see', 'film'] } }
module.exports = { 'responses': { 'GREET': 'Hello! How are you doing today :\)', 'HELP': 'I can help you with a bunch of things around your house.\n\n' + 'You can check in on your security cameras, ask me the temperature, and much more!\n' + 'I will also notify you during events such as a visitor at your door.', 'TFLUK': 'Okay. Thanks for letting me know.' }, 'words': { 'DISPLAY': ['tell', 'give', 'show', 'what', 'what\'s', 'display', 'how'], 'TEMPERATURE': ['temperature', 'temp', 'heat', 'hot', 'warm', 'cold'], 'GREET': ['hello', 'hi', 'hey', 'good day', 'what\'s up', 'whats up', 'sup', 'good morning', 'good evening'], 'STATE': ['i am', 'i\'m', 'im '], 'CAM': ['cam', 'camera', 'pic', 'picture', 'see', 'film'] } }
Add ifEnabled function for idea-hub and wrap main exports.
/** * Idea Hub module initialization. * * Site Kit by Google, Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Internal dependencies */ import { STORE_NAME } from './datastore/constants'; import { registerStore as registerDataStore } from './datastore'; import IdeaHubIcon from '../../../svg/idea-hub.svg'; import { isFeatureEnabled } from '../../features'; const ifEnabled = ( func ) => ( ...args ) => { if ( isFeatureEnabled( 'ideaHubModule' ) ) { func( ...args ); } }; export const registerStore = ifEnabled( registerDataStore ); export const registerModule = ifEnabled( ( modules ) => { modules.registerModule( 'idea-hub', { storeName: STORE_NAME, Icon: IdeaHubIcon, } ); } );
/** * Idea Hub module initialization. * * Site Kit by Google, Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Internal dependencies */ import { STORE_NAME } from './datastore/constants'; import IdeaHubIcon from '../../../svg/idea-hub.svg'; export { registerStore } from './datastore'; export const registerModule = ( modules ) => { modules.registerModule( 'idea-hub', { storeName: STORE_NAME, Icon: IdeaHubIcon, } ); };
42: Add direct inferred edges as part of loading SciGraph Task-Url: https://github.com/SciCrunch/SciGraph/issues/issue/42 Removes test to resolve inference issues
package edu.sdsc.scigraph.owlapi.cases; import static com.google.common.collect.Iterables.getOnlyElement; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import org.junit.Ignore; import org.junit.Test; import org.neo4j.graphdb.Direction; import org.neo4j.graphdb.Node; import org.neo4j.graphdb.Relationship; import edu.sdsc.scigraph.owlapi.OwlRelationships; @Ignore public class TestInferredEdges extends OwlTestCase { @Test public void testInferredEdges() { Node cx = getNode("http://example.org/cx"); Node dx = getNode("http://example.org/dx"); Iterable<Relationship> superclasses = dx.getRelationships(OwlRelationships.RDF_SUBCLASS_OF, Direction.OUTGOING); Relationship r = getOnlyElement(superclasses); assertThat(r.getOtherNode(dx), is(cx)); } }
package edu.sdsc.scigraph.owlapi.cases; import static com.google.common.collect.Iterables.getOnlyElement; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import org.junit.Test; import org.neo4j.graphdb.Direction; import org.neo4j.graphdb.Node; import org.neo4j.graphdb.Relationship; import edu.sdsc.scigraph.owlapi.OwlRelationships; public class TestInferredEdges extends OwlTestCase { @Test public void testInferredEdges() { Node cx = getNode("http://example.org/cx"); Node dx = getNode("http://example.org/dx"); Iterable<Relationship> superclasses = dx.getRelationships(OwlRelationships.RDF_SUBCLASS_OF, Direction.OUTGOING); Relationship r = getOnlyElement(superclasses); assertThat(r.getOtherNode(dx), is(cx)); } }
Fix 'zero length field name in format' error
from django.db import models class Metric(models.Model): class Meta: db_table = 'metric' def __unicode__(self): return self.name name = models.CharField(max_length=128) explanation_url = models.CharField(max_length=256) units = models.CharField(max_length=128) class Environment(models.Model): class Meta: db_table = 'environment' class Procedure(models.Model): class Meta: db_table = 'procedure' class Sample(models.Model): class Meta: db_table = 'samples' ordering = ['metric', 'sample_date'] unique_together = ('metric', 'sample_date') def __unicode__(self): return '{0}/{1}: {2}'.format(self.sample_date, self.metric.name, self.value) metric = models.ForeignKey(Metric) sample_date = models.DateField() value = models.FloatField() environment = models.ForeignKey(Environment, blank=True, null=True) procedure = models.ForeignKey(Procedure, blank=True, null=True) # vim: set et sw=4 ts=4:
from django.db import models class Metric(models.Model): class Meta: db_table = 'metric' def __unicode__(self): return self.name name = models.CharField(max_length=128) explanation_url = models.CharField(max_length=256) units = models.CharField(max_length=128) class Environment(models.Model): class Meta: db_table = 'environment' class Procedure(models.Model): class Meta: db_table = 'procedure' class Sample(models.Model): class Meta: db_table = 'samples' ordering = ['metric', 'sample_date'] unique_together = ('metric', 'sample_date') def __unicode__(self): return '{}/{}: {}'.format(self.sample_date, self.metric.name, self.value) metric = models.ForeignKey(Metric) sample_date = models.DateField() value = models.FloatField() environment = models.ForeignKey(Environment, blank=True, null=True) procedure = models.ForeignKey(Procedure, blank=True, null=True) # vim: set et sw=4 ts=4:
Move import back to the top
# Color palette returns an array of colors (rainbow) from matplotlib import pyplot as plt import numpy as np from plantcv.plantcv import params def color_palette(num): """color_palette: Returns a list of colors length num Inputs: num = number of colors to return. Returns: colors = a list of color lists (RGB values) :param num: int :return colors: list """ # If a previous palette is saved, return it if params.saved_color_scale is not None: return params.saved_color_scale else: # Retrieve the matplotlib colormap cmap = plt.get_cmap(params.color_scale) # Get num evenly spaced colors colors = cmap(np.linspace(0, 1, num), bytes=True) colors = colors[:, 0:3].tolist() # colors are sequential, if params.color_sequence is random then shuffle the colors if params.color_sequence == "random": np.random.shuffle(colors) # Save the color scale for further use params.saved_color_scale = colors return colors
# Color palette returns an array of colors (rainbow) import numpy as np from plantcv.plantcv import params def color_palette(num): """color_palette: Returns a list of colors length num Inputs: num = number of colors to return. Returns: colors = a list of color lists (RGB values) :param num: int :return colors: list """ from matplotlib import pyplot as plt # If a previous palette is saved, return it if params.saved_color_scale is not None: return params.saved_color_scale else: # Retrieve the matplotlib colormap cmap = plt.get_cmap(params.color_scale) # Get num evenly spaced colors colors = cmap(np.linspace(0, 1, num), bytes=True) colors = colors[:, 0:3].tolist() # colors are sequential, if params.color_sequence is random then shuffle the colors if params.color_sequence == "random": np.random.shuffle(colors) # Save the color scale for further use params.saved_color_scale = colors return colors
Rename babel to transpile for consistency with socket.io repo
var gulp = require('gulp'); var mocha = require('gulp-mocha'); var babel = require("gulp-babel"); var TESTS = 'test/*.js'; var REPORTER = 'dot'; gulp.task("default", ["transpile"]); gulp.task('test', function(){ return gulp.src(TESTS, {read: false}) .pipe(mocha({ slow: 500, reporter: REPORTER, bail: true })) .once('error', function(){ process.exit(1); }) .once('end', function(){ process.exit(); }); }); // By default, individual js files are transformed by babel and exported to /dist gulp.task("transpile", function(){ return gulp.src(["lib/*.js","lib/transports/*.js"], { base: 'lib' }) .pipe(babel({ "presets": ["es2015"] })) .pipe(gulp.dest("dist")); });
var gulp = require('gulp'); var mocha = require('gulp-mocha'); var babel = require("gulp-babel"); var TESTS = 'test/*.js'; var REPORTER = 'dot'; gulp.task("default", ["babel"]); gulp.task('test', function(){ return gulp.src(TESTS, {read: false}) .pipe(mocha({ slow: 500, reporter: REPORTER, bail: true })) .once('error', function(){ process.exit(1); }) .once('end', function(){ process.exit(); }); }); // By default, individual js files are transformed by babel and exported to /dist gulp.task("babel", function(){ return gulp.src(["lib/*.js","lib/transports/*.js"], { base: 'lib' }) .pipe(babel({ "presets": ["es2015"] })) .pipe(gulp.dest("dist")); });
Make autosuggest getSuggestionalValue with 'id' style default
import React from 'react' import Autosuggest from 'react-autosuggest' import style from './bpk-autosuggest.scss' const defaultTheme = { container: 'bpk-autosuggest__container', containerOpen: 'bpk-autosuggest__container--open', input: 'bpk-autosuggest__input', suggestionsContainer: 'bpk-autosuggest__suggestions-container', suggestionsList: 'bpk-autosuggest__suggestions-list', suggestion: 'bpk-autosuggest__suggestion', suggestionFocused: 'bpk-autosuggest__suggestion--focused', sectionContainer: 'bpk-autosuggest__section-container', sectionTitle: 'bpk-autosuggest__section-title' } const BpkAutosuggest = (props) => { const inputProps = { value: props.value, onChange: props.onChange } return ( <Autosuggest suggestions={props.suggestions} onSuggestionsUpdateRequested={props.onSuggestionsUpdateRequested} onSuggestionsClearRequested={props.onSuggestionsClearRequested || (() => {})} getSuggestionValue={props.getSuggestionValue || ((suggestion) => suggestion)} renderSuggestion={props.renderSuggestion} onSuggestionSelected={props.onSuggestionSelected || (() => {})} inputProps={inputProps} theme={defaultTheme} /> ) } export default BpkAutosuggest
import React from 'react' import Autosuggest from 'react-autosuggest' import style from './bpk-autosuggest.scss' const defaultTheme = { container: 'bpk-autosuggest__container', containerOpen: 'bpk-autosuggest__container--open', input: 'bpk-autosuggest__input', suggestionsContainer: 'bpk-autosuggest__suggestions-container', suggestionsList: 'bpk-autosuggest__suggestions-list', suggestion: 'bpk-autosuggest__suggestion', suggestionFocused: 'bpk-autosuggest__suggestion--focused', sectionContainer: 'bpk-autosuggest__section-container', sectionTitle: 'bpk-autosuggest__section-title' } const BpkAutosuggest = (props) => { const inputProps = { value: props.value, onChange: props.onChange } return ( <Autosuggest suggestions={props.suggestions} onSuggestionsUpdateRequested={props.onSuggestionsUpdateRequested} onSuggestionsClearRequested={props.onSuggestionsClearRequested || (() => {})} getSuggestionValue={props.getSuggestionValue} renderSuggestion={props.renderSuggestion} onSuggestionSelected={props.onSuggestionSelected || (() => {})} inputProps={inputProps} theme={defaultTheme} /> ) } export default BpkAutosuggest
Fix Markdown integration tests due to server changes
package org.sagebionetworks.markdown; import static org.junit.Assert.assertEquals; import java.util.Arrays; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = {"classpath:test-context.xml"}) public class MarkdownDaoImplIntegrationTest { @Autowired MarkdownDao dao; @Test public void testSimpleText() throws Exception { String rawMarkdown = "## a heading"; String outputType = "html"; String result = "<h2 toc=\"true\">a heading</h2>\n"; assertEquals(result, dao.convertMarkdown(rawMarkdown, outputType)); } @Test public void testEntityId() throws Exception { String rawMarkdown = "syn12345"; String outputType = "html"; String result = "<p><a href=\"https://www.synapse.org/#!Synapse:syn12345\" target=\"_blank\" ref=\"noopener noreferrer\">syn12345</a></p>\n"; assertEquals(result, dao.convertMarkdown(rawMarkdown, outputType)); } }
package org.sagebionetworks.markdown; import static org.junit.Assert.assertEquals; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = {"classpath:test-context.xml"}) public class MarkdownDaoImplIntegrationTest { @Autowired MarkdownDao dao; @Test public void testSimpleText() throws Exception { String rawMarkdown = "## a heading"; String outputType = "html"; String result = "<h2 toc=\"true\">a heading</h2>\n"; assertEquals(result, dao.convertMarkdown(rawMarkdown, outputType)); } @Test public void testEntityId() throws Exception { String rawMarkdown = "syn12345"; String outputType = "html"; String result = "<p><a href=\"https://www.synapse.org/#!Synapse:syn12345\" target=\"_blank\">syn12345</a></p>\n"; assertEquals(result, dao.convertMarkdown(rawMarkdown, outputType)); } }
Add back empty line removed previously by zuuperman while committing debug statements
<?php /** * @file */ namespace CultuurNet\UDB3\EventHandling; use Broadway\Domain\DomainMessage; trait DelegateEventHandlingToSpecificMethodTrait { /** * {@inheritDoc} */ public function handle(DomainMessage $domainMessage) { $event = $domainMessage->getPayload(); $method = $this->getHandleMethod($event); if (!method_exists($this, $method)) { return; } try { $parameter = new \ReflectionParameter(array($this, $method), 0); } catch (\ReflectionException $e) { // No parameter for the method, so we ignore it. return; } $expectedClass = $parameter->getClass(); if ($expectedClass->getName() == get_class($event)) { $this->$method($event, $domainMessage); } } private function getHandleMethod($event) { $classParts = explode('\\', get_class($event)); return 'apply' . end($classParts); } }
<?php /** * @file */ namespace CultuurNet\UDB3\EventHandling; use Broadway\Domain\DomainMessage; trait DelegateEventHandlingToSpecificMethodTrait { /** * {@inheritDoc} */ public function handle(DomainMessage $domainMessage) { $event = $domainMessage->getPayload(); $method = $this->getHandleMethod($event); if (!method_exists($this, $method)) { return; } try { $parameter = new \ReflectionParameter(array($this, $method), 0); } catch (\ReflectionException $e) { // No parameter for the method, so we ignore it. return; } $expectedClass = $parameter->getClass(); if ($expectedClass->getName() == get_class($event)) { $this->$method($event, $domainMessage); } } private function getHandleMethod($event) { $classParts = explode('\\', get_class($event)); return 'apply' . end($classParts); } }
Use normal without extra libs
<?php defined('BASEPATH') OR exit('No direct script access allowed'); ?> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Generate hastag from a webpage</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous"> </head> <body> <div class="container-fluid"> <h1>Generate hastag from a webpage</h1> <?php $this->load->helper('form'); echo "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"; echo form_open("/Hashtags/generate_tags",array('class'=>'form-inline')); ?> <div class="form-group"> <input type="text" class="form-control" name="url" placeholder="Enter the site url here" required> </div> <button type="submit" class="btn btn-primary">Go!</button> </form> </div> </body> </html>
<?php defined('BASEPATH') OR exit('No direct script access allowed'); ?> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Generate hastag from a webpage</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous"> </head> <body> <div class="container-fluid"> <h1>Generate hastag from a webpage</h1> <?php $this->load->helper('form'); echo form_open("/Hashtags/generate_tags",array('class'=>'form-inline')); ?> <div class="form-group"> <input type="text" class="form-control" name="url" placeholder="Enter the site url here" required> </div> <button type="submit" class="btn btn-primary">Go!</button> </form> </div> </body> </html>
Simplify pubtator test to only check for entities, not exact number
import kindred def test_pubtator_pmid(): corpus = kindred.pubtator.load(19894120) assert isinstance(corpus,kindred.Corpus) docCount = len(corpus.documents) entityCount = sum([ len(d.entities) for d in corpus.documents ]) relationCount = sum([ len(d.relations) for d in corpus.documents ]) assert docCount == 2 assert relationCount == 0 assert entityCount > 0 def test_pubtator_pmids(): corpus = kindred.pubtator.load([19894120,19894121]) assert isinstance(corpus,kindred.Corpus) docCount = len(corpus.documents) entityCount = sum([ len(d.entities) for d in corpus.documents ]) relationCount = sum([ len(d.relations) for d in corpus.documents ]) assert docCount == 4 assert relationCount == 0 assert entityCount > 0 if __name__ == '__main__': test_pubtator()
import kindred def test_pubtator_pmid(): corpus = kindred.pubtator.load(19894120) assert isinstance(corpus,kindred.Corpus) docCount = len(corpus.documents) entityCount = sum([ len(d.entities) for d in corpus.documents ]) relationCount = sum([ len(d.relations) for d in corpus.documents ]) assert docCount == 2 assert relationCount == 0 assert entityCount == 16 def test_pubtator_pmids(): corpus = kindred.pubtator.load([19894120,19894121]) assert isinstance(corpus,kindred.Corpus) docCount = len(corpus.documents) entityCount = sum([ len(d.entities) for d in corpus.documents ]) relationCount = sum([ len(d.relations) for d in corpus.documents ]) assert docCount == 4 assert relationCount == 0 assert entityCount == 38 if __name__ == '__main__': test_pubtator()
SEC-1996: Fix javadoc to work with jdk 1.5 The javadoc did not work with JDK 1.5 due to a JDK bug fixed in JDK 1.6. This changed the javadoc that had a tag that started with <a and was not closed to escape the < >. This resolves the issue with the JDK 1.5 javadoc bug.
package org.springframework.security.config; /** * Contains globally used default Bean IDs for beans created by the namespace support in Spring Security 2. * <p> * These are intended for internal use. * * @author Ben Alex * @author Luke Taylor */ public abstract class BeanIds { private static final String PREFIX = "org.springframework.security."; /** The "global" AuthenticationManager instance, registered by the &lt;authentication-manager&gt; element */ public static final String AUTHENTICATION_MANAGER = PREFIX + "authenticationManager"; /** External alias for FilterChainProxy bean, for use in web.xml files */ public static final String SPRING_SECURITY_FILTER_CHAIN = "springSecurityFilterChain"; public static final String CONTEXT_SOURCE_SETTING_POST_PROCESSOR = PREFIX + "contextSettingPostProcessor"; public static final String USER_DETAILS_SERVICE = PREFIX + "userDetailsService"; public static final String USER_DETAILS_SERVICE_FACTORY = PREFIX + "userDetailsServiceFactory"; public static final String METHOD_ACCESS_MANAGER = PREFIX + "defaultMethodAccessManager"; public static final String FILTER_CHAIN_PROXY = PREFIX + "filterChainProxy"; public static final String FILTER_CHAINS = PREFIX + "filterChains"; public static final String METHOD_SECURITY_METADATA_SOURCE_ADVISOR = PREFIX + "methodSecurityMetadataSourceAdvisor"; public static final String EMBEDDED_APACHE_DS = PREFIX + "apacheDirectoryServerContainer"; public static final String CONTEXT_SOURCE = PREFIX + "securityContextSource"; public static final String DEBUG_FILTER = PREFIX + "debugFilter"; }
package org.springframework.security.config; /** * Contains globally used default Bean IDs for beans created by the namespace support in Spring Security 2. * <p> * These are intended for internal use. * * @author Ben Alex * @author Luke Taylor */ public abstract class BeanIds { private static final String PREFIX = "org.springframework.security."; /** The "global" AuthenticationManager instance, registered by the <authentication-manager> element */ public static final String AUTHENTICATION_MANAGER = PREFIX + "authenticationManager"; /** External alias for FilterChainProxy bean, for use in web.xml files */ public static final String SPRING_SECURITY_FILTER_CHAIN = "springSecurityFilterChain"; public static final String CONTEXT_SOURCE_SETTING_POST_PROCESSOR = PREFIX + "contextSettingPostProcessor"; public static final String USER_DETAILS_SERVICE = PREFIX + "userDetailsService"; public static final String USER_DETAILS_SERVICE_FACTORY = PREFIX + "userDetailsServiceFactory"; public static final String METHOD_ACCESS_MANAGER = PREFIX + "defaultMethodAccessManager"; public static final String FILTER_CHAIN_PROXY = PREFIX + "filterChainProxy"; public static final String FILTER_CHAINS = PREFIX + "filterChains"; public static final String METHOD_SECURITY_METADATA_SOURCE_ADVISOR = PREFIX + "methodSecurityMetadataSourceAdvisor"; public static final String EMBEDDED_APACHE_DS = PREFIX + "apacheDirectoryServerContainer"; public static final String CONTEXT_SOURCE = PREFIX + "securityContextSource"; public static final String DEBUG_FILTER = PREFIX + "debugFilter"; }
Add logger for uncatched exceptions
package eu.europa.esig.dss.web.controller; import javax.servlet.http.HttpServletRequest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.core.annotation.AnnotationUtils; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.servlet.ModelAndView; @ControllerAdvice public class GlobalExceptionHandler { private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class); public static final String DEFAULT_ERROR_VIEW = "error"; @ExceptionHandler(value = Exception.class) public ModelAndView defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception { // If the exception is annotated with @ResponseStatus rethrow it and let // the framework handle it (for personal and annotated Exception) if (AnnotationUtils.findAnnotation(e.getClass(), ResponseStatus.class) != null) { throw e; } logger.error("Unhandle exception occured : " + e.getMessage(), e); ModelAndView mav = new ModelAndView(); mav.addObject("exception", e); mav.addObject("url", req.getRequestURL()); mav.setViewName(DEFAULT_ERROR_VIEW); return mav; } }
package eu.europa.esig.dss.web.controller; import javax.servlet.http.HttpServletRequest; import org.springframework.core.annotation.AnnotationUtils; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.servlet.ModelAndView; @ControllerAdvice public class GlobalExceptionHandler { public static final String DEFAULT_ERROR_VIEW = "error"; @ExceptionHandler(value = Exception.class) public ModelAndView defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception { // If the exception is annotated with @ResponseStatus rethrow it and let // the framework handle it (for personal and annotated Exception) if (AnnotationUtils.findAnnotation(e.getClass(), ResponseStatus.class) != null) { throw e; } ModelAndView mav = new ModelAndView(); mav.addObject("exception", e); mav.addObject("url", req.getRequestURL()); mav.setViewName(DEFAULT_ERROR_VIEW); return mav; } }
Fix error when creating categories Resolves #267
import React from 'react'; import emoji from '../../../common/services/js-emoji'; export default function CategoryListItem(props) { const { category, isOnline, onClickDelete, onClickEdit } = props; const deleteIsDisabled = !isOnline; const categoryEmojiHtml = { __html: '' }; if (category.emoji) { categoryEmojiHtml.__html = emoji.replace_colons(category.emoji); } return ( <li className="resource-list-item category-list-item"> <button className="category-list-item-label-btn" onClick={() => onClickEdit(category)}> <span className="category-list-item-emoji" dangerouslySetInnerHTML={categoryEmojiHtml}/> <span className="category-list-item-label"> {category.label} </span> </button> <button className="resource-list-item-delete" onClick={() => onClickDelete(category)} disabled={deleteIsDisabled}> Delete </button> </li> ); }
import React from 'react'; import emoji from '../../../common/services/js-emoji'; export default function CategoryListItem(props) { const { category, isOnline, onClickDelete, onClickEdit } = props; const deleteIsDisabled = !isOnline; const categoryEmojiHtml = { __html: emoji.replace_colons(category.emoji) }; return ( <li className="resource-list-item category-list-item"> <button className="category-list-item-label-btn" onClick={() => onClickEdit(category)}> <span className="category-list-item-emoji" dangerouslySetInnerHTML={categoryEmojiHtml}/> <span className="category-list-item-label"> {category.label} </span> </button> <button className="resource-list-item-delete" onClick={() => onClickDelete(category)} disabled={deleteIsDisabled}> Delete </button> </li> ); }
Move inf to shortest_path_d for clarity
from __future__ import absolute_import from __future__ import print_function from __future__ import division from ds_binary_heap_tuple import BinaryHeap def dijkstra(weighted_graph_d, start_vertex): shortest_path_d = { vertex: float('inf') for vertex in weighted_graph_d } shortest_path_d[start_vertex] = 0 bh = BinaryHeap() # TODO: Continue Dijkstra's algorithm. def main(): weighted_graph_d = { 'u': {'v': 2, 'w': 5, 'x': 1}, 'v': {'u': 2, 'w': 3, 'x': 2}, 'w': {'u': 5, 'v': 3, 'x': 3, 'y': 1, 'z': 5}, 'x': {'u': 1, 'v': 2, 'w': 3, 'y': 1}, 'y': {'w': 1, 'x': 1, 'z': 1}, 'z': {'w': 5, 'y': 1} } if __name__ == '__main__': main()
from __future__ import absolute_import from __future__ import print_function from __future__ import division from ds_binary_heap_tuple import BinaryHeap def dijkstra(weighted_graph_d, start_vertex): inf = float('inf') shortest_path_d = { vertex: inf for vertex in weighted_graph_d } shortest_path_d[start_vertex] = 0 bh = BinaryHeap() # TODO: Continue Dijkstra's algorithm. def main(): weighted_graph_d = { 'u': {'v': 2, 'w': 5, 'x': 1}, 'v': {'u': 2, 'w': 3, 'x': 2}, 'w': {'u': 5, 'v': 3, 'x': 3, 'y': 1, 'z': 5}, 'x': {'u': 1, 'v': 2, 'w': 3, 'y': 1}, 'y': {'w': 1, 'x': 1, 'z': 1}, 'z': {'w': 5, 'y': 1} } if __name__ == '__main__': main()
Add an actual message for a missing lethe-data.json
var fs = require('fs'); var exports = { saved: { videos: {}, }, }; var FILENAME = 'lethe-data.json'; exports.read = function() { try { fs.readFile(FILENAME, 'utf8', (err, data) => { if (err) { if (err.message.indexOf('ENOENT') > -1) { // File doesn't exist console.log(`The lethe-data.json file doesn't exist! This is not an error.`); } else { console.log(err); } } else { exports.saved = JSON.parse(data); } }); } catch (e) { console.log(e); } }; exports.write = function() { fs.writeFile(FILENAME, JSON.stringify(exports.saved), (err) => { if (err) { console.log(err); } }); }; exports.possiblyRetrieveVideo = function(argument) { if (exports.saved.videos.hasOwnProperty(argument)) return exports.saved.videos[argument].vid; else return argument; }; module.exports = exports;
var fs = require('fs'); var exports = { saved: { videos: {}, }, }; var FILENAME = 'lethe-data.json'; exports.read = function() { try { fs.readFile(FILENAME, 'utf8', (err, data) => { if (err) { // Probably the file just doesn't exist, so don't do anything else console.log(err); } else { exports.saved = JSON.parse(data); } }); } catch (e) { console.log(e); } }; exports.write = function() { fs.writeFile(FILENAME, JSON.stringify(exports.saved), (err) => { if (err) { console.log(err); } }); }; exports.possiblyRetrieveVideo = function(argument) { if (exports.saved.videos.hasOwnProperty(argument)) return exports.saved.videos[argument].vid; else return argument; }; module.exports = exports;
Correct translation of the description.
module.exports = { title: 'Animación', subtitle: '', description: ` Para hacer animaciones con glamorous, puedes usar las transiciones regulares de CSS para cosas sencillas, y para cosas más avanzadas, puedes usar ~keyframes~ a través de la API ~css.keyframes~ de ~glamor~. ~~~js // importamos css desde glamor import { css } from 'glamor' // Definimos los estilos de animación const animationStyles = props => { const bounce = css.keyframes({ '0%': { transform: ~scale(1.01)~ }, '100%': { transform: ~scale(0.99)~ } }) return {animation: ~\${bounce} 0.2s infinite ease-in-out alternate~} } // Definimos el elemento const AnimatedDiv = glamorous.div(animationStyles) // Y lo utilizamos en una función render <AnimatedDiv> Bounce. </AnimatedDiv> ~~~ `.replace(/~/g, '`'), codeSandboxId: '31VMyP7XO', codeSandboxSummary: 'Ejemplo de animación', filename: __filename, }
module.exports = { title: 'Animación', subtitle: '', description: ` Para hacer animaciones con glamorous, puedes usar las transiciones regulares de CSS para cosas sencillas, y para cosas más avanzadas, puedes usar ~keyframes~ vía ~glamor~'s ~css.keyframes~ API. ~~~js // importamos css desde glamor import { css } from 'glamor' // Definimos los estilos de animación const animationStyles = props => { const bounce = css.keyframes({ '0%': { transform: ~scale(1.01)~ }, '100%': { transform: ~scale(0.99)~ } }) return {animation: ~\${bounce} 0.2s infinite ease-in-out alternate~} } // Definimos el elemento const AnimatedDiv = glamorous.div(animationStyles) // Y lo Utilizamos en una función render <AnimatedDiv> Bounce. </AnimatedDiv> ~~~ `.replace(/~/g, '`'), codeSandboxId: '31VMyP7XO', codeSandboxSummary: 'Ejemplo de animación', filename: __filename, }
Make sure not to scale null values
function halfBandwidth(scale: Function): number { if(scale.bandwidth) { return scale.bandwidth() / 2; } return 0; } /** * applyScaledValue * * Because primitive dimensions correlate to an onScreen pixel value the need * a slightly different calculation when applying the scale. This is abstracted away * to save the headache of knowing to recaclulate. * * * @param {string} dimensionName * @param {Function} scale * @param {any} value * @param {object} props A chart elements inherited props * @return {any} */ export default function applyScaledValue(dimensionName: string, scale: Function, value: *, props: Object): * { if(value === null) { return value; } switch (dimensionName) { case 'x': return scale(value) + halfBandwidth(scale); case 'y': return props.height - (scale(value) + halfBandwidth(scale)); default: // the default behavior is to apply current column through current scale return scale(value); } }
function halfBandwidth(scale: Function): number { if(scale.bandwidth) { return scale.bandwidth() / 2; } return 0; } /** * applyScaledValue * * Because primitive dimensions correlate to an onScreen pixel value the need * a slightly different calculation when applying the scale. This is abstracted away * to save the headache of knowing to recaclulate. * * * @param {string} dimensionName * @param {Function} scale * @param {any} value * @param {object} props A chart elements inherited props * @return {any} */ export default function applyScaledValue(dimensionName: sting, scale: Function, value: *, props: Object): * { // console.log(dimensionName, typeof scale, value); switch (dimensionName) { case 'x': return scale(value) + halfBandwidth(scale); case 'y': return props.height - (scale(value) + halfBandwidth(scale)); default: // the default behavior is to apply current column through current scale return scale(value); } }
Make tests pass in Django 1.4.
# -*- coding: utf-8 -*- DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', }, } CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'TIMEOUT': 36000, 'KEY_PREFIX': 'post-office', }, 'post_office': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'TIMEOUT': 36000, 'KEY_PREFIX': 'post-office', } } POST_OFFICE = { # 'CONTEXT_FIELD_CLASS': 'picklefield.fields.PickledObjectField', } INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'post_office', ) SECRET_KEY = 'a' ROOT_URLCONF = 'post_office.test_urls' DEFAULT_FROM_EMAIL = 'webmaster@example.com' MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', )
# -*- coding: utf-8 -*- DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', }, } CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'TIMEOUT': 36000, 'KEY_PREFIX': 'post-office', }, 'post_office': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'TIMEOUT': 36000, 'KEY_PREFIX': 'post-office', } } POST_OFFICE = { # 'CONTEXT_FIELD_CLASS': 'picklefield.fields.PickledObjectField', } INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'post_office', ) SECRET_KEY = 'a' ROOT_URLCONF = 'post_office.test_urls' DEFAULT_FROM_EMAIL = 'webmaster@example.com' MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', ) #TEST_RUNNER = 'django.test.simple.DjangoTestSuiteRunner'
Fix case typo in 'to_dataframe' abstract method return type. Also updates abstract property to abstract method. PiperOrigin-RevId: 339248589
# Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================= # Lint as: python3 """A generic Materialized Artifact definition.""" import abc import pandas as pd class MaterializedArtifact(abc.ABC): """Abstract base class for materialized artifacts. Represents an output of a tfx component that has been materialized on disk. Subclasses provide implementations to load and display a specific artifact type. """ @abc.abstractmethod def show(self) -> None: """Displays respective visualization for artifact type.""" @abc.abstractmethod def to_dataframe(self) -> pd.DataFrame: """Returns dataframe representation of the artifact."""
# Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================= # Lint as: python3 """A generic Materialized Artifact definition.""" import abc import pandas as pd class MaterializedArtifact(abc.ABC): """Abstract base class for materialized artifacts. Represents an output of a tfx component that has been materialized on disk. Subclasses provide implementations to load and display a specific artifact type. """ @abc.abstractmethod def show(self) -> None: """Displays respective visualization for artifact type.""" @abc.abstractproperty def to_dataframe(self) -> pd.Dataframe: """Returns dataframe representation of the artifact."""
Use improved animation code as it was used inline
var updateClock = (function() { var sDial = document.getElementById("secondDial"); var mDial = document.getElementById("minuteDial"); var hDial = document.getElementById("hourDial"); function moveDials(hours, minutes, seconds) { hDeg = (360 / 12) * (hours + minutes/60); mDeg = (360 / 60) * minutes; sDeg = (360 / 60) * seconds; sDial.setAttribute("transform", "rotate("+sDeg+")"); mDial.setAttribute("transform", "rotate("+mDeg+")"); hDial.setAttribute("transform", "rotate("+hDeg+")"); } function update() { var currentTime = new Date(); moveDials(currentTime.getHours(), currentTime.getMinutes(), currentTime.getSeconds()); }; return update; })(); // update every 50ms, just to be sure setInterval(updateClock, 50);
var clock = function() { var sDial = document.getElementsByClassName("seconds")[0]; var mDial = document.getElementsByClassName("minutes")[0]; var hDial = document.getElementsByClassName("hours")[0]; function moveDials(hours, minutes, seconds) { hDeg = (360 / 12) * hours; mDeg = (360 / 60) * minutes; sDeg = (360 / 60) * seconds; sDial.setAttribute("transform", "rotate("+sDeg+")"); mDial.setAttribute("transform", "rotate("+mDeg+")"); hDial.setAttribute("transform", "rotate("+hDeg+")"); } function update() { var currentTime = new Date(); moveDials(currentTime.getHours(), currentTime.getMinutes(), currentTime.getSeconds()); }; update(); } setInterval(clock, 50);
Kickass: Remove ? from show title when searching
import cache import network import scraper import urllib KICKASS_URL = 'http://kickass.so' ################################################################################ def movie(movie_info): return __search('category:{0} imdb:{1}'.format('movies', movie_info['imdb_id'][2:])) ################################################################################ def episode(show_info, episode_info): clean_title = show_info['title'].replace('?', '') return __search('category:{0} {1} season:{2} episode:{3}'.format('tv', clean_title, episode_info['season_index'], episode_info['episode_index'])) ################################################################################ def __search(query): magnet_infos = [] rss_data = network.rss_get_cached_optional(KICKASS_URL + '/usearch/{0}'.format(urllib.quote(query)), expiration=cache.HOUR, params={ 'field': 'seeders', 'sorder': 'desc', 'rss': '1' }) if rss_data: for rss_item in rss_data.entries: magnet_infos.append(scraper.Magnet(rss_item.torrent_magneturi, rss_item.title, int(rss_item.torrent_seeds), int(rss_item.torrent_peers))) return magnet_infos
import cache import network import scraper import urllib KICKASS_URL = 'http://kickass.so' ################################################################################ def movie(movie_info): return __search('category:{0} imdb:{1}'.format('movies', movie_info['imdb_id'][2:])) ################################################################################ def episode(show_info, episode_info): return __search('category:{0} {1} season:{2} episode:{3}'.format('tv', show_info['title'], episode_info['season_index'], episode_info['episode_index'])) ################################################################################ def __search(query): magnet_infos = [] rss_data = network.rss_get_cached_optional(KICKASS_URL + '/usearch/{0}'.format(urllib.quote(query)), expiration=cache.HOUR, params={ 'field': 'seeders', 'sorder': 'desc', 'rss': '1' }) if rss_data: for rss_item in rss_data.entries: magnet_infos.append(scraper.Magnet(rss_item.torrent_magneturi, rss_item.title, int(rss_item.torrent_seeds), int(rss_item.torrent_peers))) return magnet_infos
Revert "remove unnecessary ./ from relative url" This reverts commit dbd8e6a59f41cc761446f2580fa82c055b17033e.
/** * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * main.js is used to load necessary functions for the request.jsp page into * the global namespace. This is done so that all code can be written as ES * modules, allowing the global namespace to contain only the minimum number of * necessary members. */ import {addTicket, deleteTicket} from './tickets.js'; /* Add necessary functions to the global namespace. */ /** * Add a ticket to the request form. */ window.addTicket = async () => { try{ addTicket(); } catch (error) { alert('Could not add ticket to the request form. Please try again.'); } } /** * Delete a ticket from the request form. */ window.deleteTicket = async (element) => { try{ deleteTicket(element); } catch (error) { alert('Could not delete ticket from the request form. Please try again.') } };
/** * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * main.js is used to load necessary functions for the request.jsp page into * the global namespace. This is done so that all code can be written as ES * modules, allowing the global namespace to contain only the minimum number of * necessary members. */ import {addTicket, deleteTicket} from 'tickets.js'; /* Add necessary functions to the global namespace. */ /** * Add a ticket to the request form. */ window.addTicket = async () => { try{ addTicket(); } catch (error) { alert('Could not add ticket to the request form. Please try again.'); } } /** * Delete a ticket from the request form. */ window.deleteTicket = async (element) => { try{ deleteTicket(element); } catch (error) { alert('Could not delete ticket from the request form. Please try again.') } };
[Optimization] Use lazyLoadChunks API to load small chunks at a time
/*! * Copyright 2016 Joji Doi * Licensed under the MIT license */ function getMediaFilePath(mediaItem) { return "ext-content/" + mediaItem.dir + '/' + mediaItem.title + mediaItem.file_ext; } function getMediaThumbFilePath(mediaItem) { return "ext-content/" + mediaItem.dir + '/thumbs/' + mediaItem.title + mediaItem.file_ext; } /* * Load media_list from the json file */ $.getJSON("data/media_files_list.json", function(result) { var mediaFiles = $(result).filter(function() { return this.category == "photos"; }); var datas = []; $.each(mediaFiles, function(i, mediaItem) { datas.push({ image: getMediaFilePath(mediaItem), thumb: getMediaThumbFilePath(mediaItem) }); }); Galleria.run('.galleria', { thumbnails: "lazy", dataSource: datas, responsive: true, height: 0.5, autoplay: true }); // lazy load small chunks of thumbnails at a time Galleria.ready(function() { this.lazyLoadChunks(30, 1000); // 30 thumbs per second }) }); // end of getJSON()
/*! * Copyright 2016 Joji Doi * Licensed under the MIT license */ function getMediaFilePath(mediaItem) { return "ext-content/" + mediaItem.dir + '/' + mediaItem.title + mediaItem.file_ext; } function getMediaThumbFilePath(mediaItem) { return "ext-content/" + mediaItem.dir + '/thumbs/' + mediaItem.title + mediaItem.file_ext; } /* * Load media_list from the json file */ $.getJSON("data/media_files_list.json", function(result) { var mediaFiles = $(result).filter(function() { return this.category == "photos"; }); $.each(mediaFiles, function(i, mediaItem) { var aTag = $("<a/>", { "href": getMediaFilePath(mediaItem) }); var img = $("<img/>", { "src": getMediaThumbFilePath(mediaItem) }); img.appendTo(aTag); aTag.appendTo("#files_list"); }); $(".galleria").galleria({ responsive: true, height: 0.5 }); Galleria.run('.galleria'); }); // end of getJSON()
Send context for on event listeners
console.log('background.js'); config.background = true; /** * Create an app with the config and accounts */ app = new App({ model: config, collection: accounts, }); /** * Wire events */ config.on('ready', app.ready, app); accounts.on('ready', app.ready, app); config.on('change:frequency', app.changeInterval, app); app.on('interval', interactions.checkForNew, interactions); app.on('interval', mentions.checkForNew, mentions); interactions.on('add', interactions.renderNotification, interactions); mentions.on('add', mentions.renderNotification, mentions); /** * omnibox events */ chrome.omnibox.setDefaultSuggestion({ description: 'Post to App.net <match>%s</match>' }); chrome.omnibox.onInputEntered.addListener(window.omniboxview.onInputEntered); chrome.omnibox.onInputChanged.addListener(window.omniboxview.onInputChanged); accounts.on('ready', function() { if (accounts.length === 0) { var n = new TextNotificationView({ url: accounts.buildAuthUrl(), title: 'Connect your App.net account', body: 'Click to connect your App.net account and get started with the awesomeness of Succynct.', image: chrome.extension.getURL('/img/angle.png') }); n.render(); } });
console.log('background.js'); config.background = true; /** * Create an app with the config and accounts */ app = new App({ model: config, collection: accounts, }); /** * Wire events */ config.on('ready', app.ready); accounts.on('ready', app.ready); config.on('change:frequency', app.changeInterval); app.on('interval', interactions.checkForNew); app.on('interval', mentions.checkForNew); interactions.on('add', interactions.renderNotification); mentions.on('add', mentions.renderNotification); /** * omnibox events */ chrome.omnibox.setDefaultSuggestion({ description: 'Post to App.net <match>%s</match>' }); chrome.omnibox.onInputEntered.addListener(window.omniboxview.onInputEntered); chrome.omnibox.onInputChanged.addListener(window.omniboxview.onInputChanged); accounts.on('ready', function() { if (accounts.length === 0) { var n = new TextNotificationView({ url: accounts.buildAuthUrl(), title: 'Connect your App.net account', body: 'Click to connect your App.net account and get started with the awesomeness of Succynct.', image: chrome.extension.getURL('/img/angle.png') }); n.render(); } });
Correct and simplify calculation of miliseconds Signed-off-by: TeaPackCZ <a78d8486eff6e2cb08b2d9907449b92187b8e215@gmail.com>
import time class Logger(): def __init__(self, name = "defaultLogFile"): timestamp = time.strftime('%Y_%m_%d-%H_%M_%S') self.name = "Logs/" + timestamp + "_" + name + ".txt" try: self.logfile = open(self.name, 'w') self.opened = True except: self.opened = False def save_line(self,data): time_s = time.time() time_ms = int((time_s - int(time_s))*1000.0) timestamp = time.strftime(('%H_%M_%S'), time.localtime(time_s))+"_" +str(time_ms) + " : " if(self.opened): self.logfile.write(timestamp+data) self.logfile.flush() return 0,"" else: return 1,str(timestamp+data) def close(self): if(self.opened): self.logfile.flush() self.logfile.close() self.opened = False return 0 else: return 1
import time class Logger(): def __init__(self, name = "defaultLogFile"): timestamp = time.strftime('%Y_%m_%d-%H_%M_%S') self.name = "Logs/" + timestamp + "_" + name + ".txt" try: self.logfile = open(self.name, 'w') self.opened = True except: self.opened = False def save_line(self,data): time_s = time.time() time_ms = int(round((time_s - round(time_s))*1000)) timestamp = time.strftime(('%H_%M_%S'), time.localtime(time_s))+"_" +str(time_ms) + " : " if(self.opened): self.logfile.write(timestamp+data) self.logfile.flush() return 0,"" else: return 1,str(timestamp+data) def close(self): if(self.opened): self.logfile.flush() self.logfile.close() self.opened = False return 0 else: return 1
Move the `/* @var` syntax above
<?php namespace SimpleBus\DoctrineORMBridge\MessageBus; use Doctrine\ORM\EntityManager; use Doctrine\Persistence\ManagerRegistry; use SimpleBus\Message\Bus\Middleware\MessageBusMiddleware; use Throwable; class WrapsMessageHandlingInTransaction implements MessageBusMiddleware { /** * @var ManagerRegistry */ private $managerRegistry; /** * @var string */ private $entityManagerName; /** * @param string $entityManagerName */ public function __construct(ManagerRegistry $managerRegistry, $entityManagerName) { $this->managerRegistry = $managerRegistry; $this->entityManagerName = $entityManagerName; } public function handle($message, callable $next) { /** @var $entityManager EntityManager */ $entityManager = $this->managerRegistry->getManager($this->entityManagerName); try { $entityManager->transactional( function () use ($message, $next) { $next($message); } ); } catch (Throwable $error) { $this->managerRegistry->resetManager($this->entityManagerName); throw $error; } } }
<?php namespace SimpleBus\DoctrineORMBridge\MessageBus; use Doctrine\ORM\EntityManager; use Doctrine\Persistence\ManagerRegistry; use SimpleBus\Message\Bus\Middleware\MessageBusMiddleware; use Throwable; class WrapsMessageHandlingInTransaction implements MessageBusMiddleware { /** * @var ManagerRegistry */ private $managerRegistry; /** * @var string */ private $entityManagerName; /** * @param string $entityManagerName */ public function __construct(ManagerRegistry $managerRegistry, $entityManagerName) { $this->managerRegistry = $managerRegistry; $this->entityManagerName = $entityManagerName; } public function handle($message, callable $next) { $entityManager = $this->managerRegistry->getManager($this->entityManagerName); /* @var $entityManager EntityManager */ try { $entityManager->transactional( function () use ($message, $next) { $next($message); } ); } catch (Throwable $error) { $this->managerRegistry->resetManager($this->entityManagerName); throw $error; } } }
Fix UUID column error in membership seeder
module.exports = { up: (queryInterface, Sequelize) => { return queryInterface.bulkInsert('Memberships', [ { id: '047fbd50-2d5a-4800-86f0-05583673fd7f', memberId: '75b936c0-ba72-11e7-84e1-058ffffd96c5', groupId: 'c46ebe90-bd68-11e7-922f-4d48c5331440', userRole: 'admin', createdAt: new Date(), updatedAt: new Date() }, { id: '75ba1746-bc81-47e5-b43f-cc1aa304db84', memberId: '9ee489d0-9c6f-11e7-a4d2-3b6a4940d978', groupId: 'c46ebe90-bd68-11e7-922f-4d48c5331440', userRole: 'member', createdAt: new Date(), updatedAt: new Date() } ], {}); }, down: (queryInterface) => { return queryInterface.bulkDelete('Memberships', null, {}); } };
module.exports = { up: (queryInterface, Sequelize) => { return queryInterface.bulkInsert('Memberships', [ { id: new Sequelize.UUIDV1(), memberId: '75b936c0-ba72-11e7-84e1-058ffffd96c5', groupId: 'c46ebe90-bd68-11e7-922f-4d48c5331440', userRole: 'admin', createdAt: new Date(), updatedAt: new Date() }, { id: new Sequelize.UUIDV1(), memberId: '9ee489d0-9c6f-11e7-a4d2-3b6a4940d978', groupId: 'c46ebe90-bd68-11e7-922f-4d48c5331440', userRole: 'member', createdAt: new Date(), updatedAt: new Date() } ], {}); }, down: (queryInterface) => { return queryInterface.bulkDelete('Memberships', null, {}); } };
Use destructuring assignment to improve readability
const dataviews = require('./'); module.exports = class DataviewFactory { static get dataviews() { return Object.keys(dataviews).reduce((allDataviews, dataviewClassName) => { allDataviews[dataviewClassName.toLowerCase()] = dataviews[dataviewClassName]; return allDataviews; }, {}); } static getDataview (query, dataviewDefinition) { const { type, options, sql } = dataviewDefinition; if (!this.dataviews[type]) { throw new Error('Invalid dataview type: "' + type + '"'); } return new this.dataviews[type](query, options, sql); } };
const dataviews = require('./'); module.exports = class DataviewFactory { static get dataviews() { return Object.keys(dataviews).reduce((allDataviews, dataviewClassName) => { allDataviews[dataviewClassName.toLowerCase()] = dataviews[dataviewClassName]; return allDataviews; }, {}); } static getDataview (query, dataviewDefinition) { const type = dataviewDefinition.type; if (!this.dataviews[type]) { throw new Error('Invalid dataview type: "' + type + '"'); } return new this.dataviews[type](query, dataviewDefinition.options, dataviewDefinition.sql); } };
Add some more spice to those lovely messages
window.lovelyTabMessage = (function(){ var stringTree = { comeBackIMissYou: { de: 'Komm zurück, ich vermisse dich.', en: 'Come back, i miss you.' } } // Let's see what lovely options we have to build our very romantic string var lovelyOptions = Object.keys(stringTree); var lovelyHearts = ['❤','💓','💖','💗','💘','💝','💕']; // Shuffle the dices of love and get our string base! var lovelyOption = lovelyOptions[Math.floor(Math.random() * (lovelyOptions.length))]; var lovelyHeart = lovelyHearts[Math.floor(Math.random() * (lovelyHearts.length))]; // Maybe we can make our users REALLY happy by using their native language? var lang = (window && window.navigator && window.navigator.userLanguage || window.navigator.language);; // Now let's glue our lovely string together! return ( stringTree[lovelyOption][lang] || stringTree[lovelyOption]['en'] ) + ' ' + lovelyHeart; })() window.cachedTitle = document.title; window.onblur = function () { document.title= window.lovelyTabMessage; } window.onfocus = function () { document.title= window.cachedTitle; }
window.lovelyTabMessage = (function(){ var hearts = ['❤','💓','💖','💗','💘','💝','💕']; var heart = hearts[Math.floor(Math.random() * (hearts.length))]; var lang = (window && window.navigator && window.navigator.language || 'en'); switch(lang){ case 'en': return 'Come back, i miss you. '+heart; case 'de': return 'Komm zurück, ich vermisse dich. '+heart; default: return 'Come back, i miss you. '+heart; } })() window.cachedTitle = document.title; window.onblur = function () { document.title= window.lovelyTabMessage; } window.onfocus = function () { document.title= window.cachedTitle; }
Make test fails for CI
var _ = require('lodash'); var gulp = require('gulp'); var gulp_mocha = require('gulp-mocha'); var gulp_jshint = require('gulp-jshint'); var gulp_jsdoc = require("gulp-jsdoc"); var files = ['lib/**/*.js']; var tests = ['test/**/*.spec.js']; var alljs = files.concat(tests); var readme = 'README.md'; function ignoreError(err) { this.emit('end'); } function testAllFiles() { return gulp.src(tests).pipe(new gulp_mocha({reporter: 'spec'})); } gulp.task('test', testAllFiles); gulp.task('test-nofail', function() { return testAllFiles().on('error', ignoreError); }); gulp.task('watch:test', function() { // TODO: Only run tests that are linked to file changes by doing // something smart like reading through the require statements return gulp.watch(alljs, ['test-nofail']); }); gulp.task('jsdoc', function() { return gulp.src(files.concat([readme])) .pipe(gulp_jsdoc.parser()) .pipe(gulp_jsdoc.generator('./docs', { path: 'ink-docstrap', theme: 'flatly', })) }); gulp.task('lint', function() { return gulp.src(alljs) .pipe(gulp_jshint()) .pipe(gulp_jshint.reporter('default')); }); gulp.task('default', ['lint', 'jsdoc', 'test']);
var _ = require('lodash'); var gulp = require('gulp'); var gulp_mocha = require('gulp-mocha'); var gulp_jshint = require('gulp-jshint'); var gulp_jsdoc = require("gulp-jsdoc"); var files = ['lib/**/*.js']; var tests = ['test/**/*.spec.js']; var alljs = files.concat(tests); var readme = 'README.md'; function ignoreError(err) { this.emit('end'); } gulp.task('test', function() { return gulp.src(tests).pipe(new gulp_mocha({reporter: 'spec'})).on('error', ignoreError); }); gulp.task('watch:test', function() { // TODO: Only run tests that are linked to file changes by doing // something smart like reading through the require statements return gulp.watch(alljs, ['test']); }); gulp.task('jsdoc', function() { return gulp.src(files.concat([readme])) .pipe(gulp_jsdoc.parser()) .pipe(gulp_jsdoc.generator('./docs', { path: 'ink-docstrap', theme: 'flatly', })) }); gulp.task('lint', function() { return gulp.src(alljs) .pipe(gulp_jshint()) .pipe(gulp_jshint.reporter('default')); }); gulp.task('default', ['lint', 'jsdoc', 'test']);
Move all PPL* records to locality Looking at localadmins vs localities, this is the right choice.
var through2 = require('through2'); function featureCodeToLayer(featureCode) { switch (featureCode) { case 'PCLI': return 'country'; case 'ADM1': return 'region'; case 'ADM2': return 'county'; case 'ADMD': return 'localadmin'; case 'PPL': case 'PPLA': case 'PPLA2': case 'PPLA3': case 'PPLA4': case 'PPLC': case 'PPLF': case 'PPLG': case 'PPLL': case 'STLMT': return 'locality'; case 'ADM4': case 'ADM5': case 'PPLX': return 'neighborhood'; default: return 'venue'; } } function create() { return through2.obj(function(data, enc, next) { data.layer = featureCodeToLayer(data.feature_code); next(null, data); }); } module.exports = { featureCodeToLayer: featureCodeToLayer, create: create };
var through2 = require('through2'); function featureCodeToLayer(featureCode) { switch (featureCode) { case 'PCLI': return 'country'; case 'ADM1': return 'region'; case 'ADM2': return 'county'; case 'ADMD': case 'PPLA': case 'PPLA2': case 'PPLA3': case 'PPLA4': case 'PPLC': case 'PPLG': return 'localadmin'; case 'PPL': case 'PPLF': case 'PPLL': case 'STLMT': return 'locality'; case 'ADM4': case 'ADM5': case 'PPLX': return 'neighborhood'; default: return 'venue'; } } function create() { return through2.obj(function(data, enc, next) { data.layer = featureCodeToLayer(data.feature_code); next(null, data); }); } module.exports = { featureCodeToLayer: featureCodeToLayer, create: create };
Change database interface to return List<>.
package eic.beike.projectx.network.projectXServer; import eic.beike.projectx.util.ScoreEntry; import java.util.List; /** * Used to interact with the database, these are long running network operations and should not be called * from the UI thread. * * @Author alex */ public interface IDatabase { /** * Register a name for the given id. * @return True if registration succeded, false if it failed. */ boolean register(String id, String name); /** * @return True if score was recorded correctly, false if it failed. */ boolean recordScore(String playerId, int score, long time, String bus); /** * @return The best ten scores for all players on all buses. */ List<ScoreEntry> getTopTen(); /** * @return The best ten scores for the given player. */ List<ScoreEntry> getPlayerTopTen(String playerId); }
package eic.beike.projectx.network.projectXServer; import eic.beike.projectx.util.ScoreEntry; /** * Used to interact with the database, these are long running network operations and should not be called * from the UI thread. * * Created by alex on 10/1/15. */ public interface IDatabase { /** * Register a name for the given id. * @return True if registration succeded, false if it failed. */ boolean register(String id, String name); /** * @return True if score was recorded correctly, false if it failed. */ boolean recordScore(String playerId, int score, long time, String bus); /** * @return The best ten scores for all players on all buses. */ ScoreEntry[] getTopTen(); /** * @return The best ten scores for the given player. */ ScoreEntry[] getPlayerTopTen(String playerId); }
Fix base url for public generation
from base64 import urlsafe_b64encode from datetime import timedelta from marshmallow import Schema, fields, post_load from zeus.models import Hook from zeus.utils import timezone class HookSchema(Schema): id = fields.UUID(dump_only=True) provider = fields.Str() token = fields.Method('get_token', dump_only=True) secret_uri = fields.Method('get_secret_uri', dump_only=True) public_uri = fields.Method('get_public_uri', dump_only=True) created_at = fields.DateTime(attribute="date_created", dump_only=True) @post_load def make_hook(self, data): return Hook(**data) def get_token(self, obj): # we allow visibility of tokens for 24 hours if obj.date_created > timezone.now() - timedelta(days=1): return urlsafe_b64encode(obj.token).decode('utf-8') return None def get_public_uri(self, obj): return '/hooks/{}/public'.format(str(obj.id)) def get_secret_uri(self, obj): return '/hooks/{}/{}'.format(str(obj.id), obj.get_signature())
from base64 import urlsafe_b64encode from datetime import timedelta from marshmallow import Schema, fields, post_load from zeus.models import Hook from zeus.utils import timezone class HookSchema(Schema): id = fields.UUID(dump_only=True) provider = fields.Str() token = fields.Method('get_token', dump_only=True) secret_uri = fields.Method('get_secret_uri', dump_only=True) public_uri = fields.Method('get_public_uri', dump_only=True) created_at = fields.DateTime(attribute="date_created", dump_only=True) @post_load def make_hook(self, data): return Hook(**data) def get_token(self, obj): # we allow visibility of tokens for 24 hours if obj.date_created > timezone.now() - timedelta(days=1): return urlsafe_b64encode(obj.token).decode('utf-8') return None def get_public_uri(self, obj): return '/hooks/{}'.format(str(obj.id)) def get_secret_uri(self, obj): return '/hooks/{}/{}'.format(str(obj.id), obj.get_signature())
feat(middleware): Add state name and action name to the middleware object
/** * Created by thram on 16/01/17. */ import {getState, setState, resetState} from "./store"; let dicts = {}, middlewares = []; export const register = (key, dict) => dicts[key] = dict; export const addMiddleware = (middleware) => middlewares.push(middleware); export const dispatch = (keyType, data) => { const [key, type] = keyType.split(':'), dict = dicts[key], action = dict && dict[type]; if (action) { const value = action.map(data), nextValue = action.reducer(value); middlewares.forEach((middleware) => middleware({ state : key, action : type, prev : getState(key), payload: value, next : nextValue })); setState(key, action.reducer(action.map(data))); } }; export const state = getState; export const clearState = resetState; export const createDict = (map, reducer) => ({map, reducer});
/** * Created by thram on 16/01/17. */ import {getState, setState, resetState} from "./store"; let dicts = {}, middlewares = []; export const register = (key, dict) => dicts[key] = dict; export const addMiddleware = (middleware) => middlewares.push(middleware); export const dispatch = (keyType, data) => { const [key, type] = keyType.split(':'), dict = dicts[key], action = dict && dict[type]; if (action) { const value = action.map(data), nextValue = action.reducer(value); middlewares.forEach((middleware) => middleware({prev: getState(key), payload: value, next: nextValue})); setState(key, action.reducer(action.map(data))); } }; export const state = getState; export const clearState = resetState; export const createDict = (map, reducer) => ({map, reducer});
Normalize already returns encoded value.
import unicodedata import urllib def normalize(name): if not isinstance(name, unicode): name = name.decode('utf-8') return unicodedata.normalize('NFKC', name.replace("'", '')).encode('utf-8') def quote(name): if isinstance(name, unicode): name = normalize(name) return urllib.quote(name) def make_icon_url(region, icon, size='large'): if not icon: return '' if size == 'small': size = 18 else: size = 56 return 'http://%s.media.blizzard.com/wow/icons/%d/%s.jpg' % (region, size, icon) def make_connection(): if not hasattr(make_connection, 'Connection'): from .connection import Connection make_connection.Connection = Connection return make_connection.Connection()
import unicodedata import urllib def normalize(name): if not isinstance(name, unicode): name = name.decode('utf-8') return unicodedata.normalize('NFKC', name.replace("'", '')).encode('utf-8') def quote(name): if isinstance(name, unicode): name = normalize(name).encode('utf8') return urllib.quote(name) def make_icon_url(region, icon, size='large'): if not icon: return '' if size == 'small': size = 18 else: size = 56 return 'http://%s.media.blizzard.com/wow/icons/%d/%s.jpg' % (region, size, icon) def make_connection(): if not hasattr(make_connection, 'Connection'): from .connection import Connection make_connection.Connection = Connection return make_connection.Connection()
Fix name field for empty values
from django.db import models from django.contrib.auth.models import AbstractUser from django.utils.translation import ugettext_lazy as _ from django.template.defaultfilters import slugify class BaseUser(AbstractUser): slug = models.SlugField(_('slug'), max_length=255) name = models.CharField(_('name'), max_length=255, blank=True) first_login = models.BooleanField(_('first login'), default=True) image = models.ImageField(_('image'), blank=True, null=True, upload_to="images/avatars/%Y/%m/%d", max_length=255) class Meta: abstract = True def save(self, *args, **kwargs): # Create slug from username. Altough field is not unique at database # level, it will be as long as username stays unique as well. if not self.id: self.slug = slugify(self.username) # Assign username as name if empty if not self.name.strip(): if not self.first_name: self.first_name = self.username name = "%s %s" % (self.first_name, self.last_name) self.name = name.strip() super(BaseUser, self).save(*args, **kwargs) def get_display_name(self): return self.name or self.username
from django.db import models from django.contrib.auth.models import AbstractUser from django.utils.translation import ugettext_lazy as _ from django.template.defaultfilters import slugify class BaseUser(AbstractUser): slug = models.SlugField(_('slug'), max_length=255) name = models.CharField(_('name'), max_length=255, blank=True) first_login = models.BooleanField(_('first login'), default=True) image = models.ImageField(_('image'), blank=True, null=True, upload_to="images/avatars/%Y/%m/%d", max_length=255) class Meta: abstract = True def save(self, *args, **kwargs): if not self.id: self.slug = slugify(self.username) if not self.name.strip(): self.name = "%s %s" % (self.first_name, self.last_name) super(BaseUser, self).save(*args, **kwargs) def get_display_name(self): return self.name or self.username
Change name of output file in example --HG-- extra : convert_revision : svn%3A3ed01bd8-26fb-0310-9e4c-ca1a4053419f/networkx/trunk%401549
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Example using the NetworkX ego_graph() function to return the main egonet of the largest hub in a Barabási-Albert network. """ __author__="""Drew Conway (drew.conway@nyu.edu)""" from operator import itemgetter import networkx as nx import matplotlib.pyplot as plt if __name__ == '__main__': # Create a BA model graph n=1000 m=2 G=nx.generators.barabasi_albert_graph(n,m) # find node with largest degree node_and_degree=G.degree(with_labels=True) (largest_hub,degree)=sorted(node_and_degree.items(),key=itemgetter(1))[-1] # Create ego graph of main hub hub_ego=nx.ego_graph(G,largest_hub) # Draw graph pos=nx.spring_layout(hub_ego) nx.draw(hub_ego,pos,node_color='b',node_size=50,with_labels=False) # Draw ego as large and red nx.draw_networkx_nodes(hub_ego,pos,nodelist=[largest_hub],node_size=300,node_color='r') plt.savefig('ego_graph.png') plt.show()
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Example using the NetworkX ego_graph() function to return the main egonet of the largest hub in a Barabási-Albert network. """ __author__="""Drew Conway (drew.conway@nyu.edu)""" from operator import itemgetter import networkx as nx import matplotlib.pyplot as plt if __name__ == '__main__': # Create a BA model graph n=1000 m=2 G=nx.generators.barabasi_albert_graph(n,m) # find node with largest degree node_and_degree=G.degree(with_labels=True) (largest_hub,degree)=sorted(node_and_degree.items(),key=itemgetter(1))[-1] # Create ego graph of main hub hub_ego=nx.ego_graph(G,largest_hub) # Draw graph pos=nx.spring_layout(hub_ego) nx.draw(hub_ego,pos,node_color='b',node_size=50,with_labels=False) # Draw ego as large and red nx.draw_networkx_nodes(hub_ego,pos,nodelist=[largest_hub],node_size=300,node_color='r') plt.savefig('main_ego.png') plt.show()
Add note that 'ALLOW_UPDATE_WITHOUT_OLD' causes problems
# Enables detailed tracebacks and an interactive Python console on errors. # Never use in production! #DEBUG = True # Makes the server more performant at sending static files when the # server is being proxied by a server that supports X-Sendfile. #USE_X_SENDFILE = True # Address to listen for clients on HOST = "0.0.0.0" # Port to listen on PORT = 8000 # File to store the JSON server list data in. FILENAME = "list.json" # Ammount of time, is seconds, after which servers are removed from the list # if they haven't updated their listings. Note: By default Minetest servers # only announce once every 5 minutes, so this should be more than 300. PURGE_TIME = 350 # List of banned IP addresses. BANLIST = [] # Creates server entries if a server sends an 'update' and there is no entry yet # This should only be used to populate the server list after list.json was deleted. # This WILL cause problems such as mapgen, mods and privilege information missing from the list ALLOW_UPDATE_WITHOUT_OLD = False
# Enables detailed tracebacks and an interactive Python console on errors. # Never use in production! #DEBUG = True # Makes the server more performant at sending static files when the # server is being proxied by a server that supports X-Sendfile. #USE_X_SENDFILE = True # Address to listen for clients on HOST = "0.0.0.0" # Port to listen on PORT = 8000 # File to store the JSON server list data in. FILENAME = "list.json" # Ammount of time, is seconds, after which servers are removed from the list # if they haven't updated their listings. Note: By default Minetest servers # only announce once every 5 minutes, so this should be more than 300. PURGE_TIME = 350 # List of banned IP addresses. BANLIST = [] # Creates server entries if a server sends an 'update' and there is no entry yet # This should only be used to populate the server list after list.json was deleted. ALLOW_UPDATE_WITHOUT_OLD = False
Include redux devtools through compose
import React from 'react' import ReactDOM from 'react-dom' import getRoutes from './config/routes' import { createStore, applyMiddleware, compose } from 'redux' import { Provider } from 'react-redux' import users from 'redux/modules/users' import thunk from 'redux-thunk' import { checkIfAuthed } from 'helpers/auth' const store = createStore(users, compose( applyMiddleware(thunk), window.devToolsExtension ? window.devToolsExtension() : (f) => f )) function checkAuth (nextState, replace) { const isAuthed = checkIfAuthed(store) const nextPathName = nextState.location.pathname if (nextPathName === '/' || nextPathName === '/auth') { if (isAuthed === true) { replace('/feed') } } else { if (isAuthed !== true) { replace('/auth') } } } ReactDOM.render( <Provider store={store}> {getRoutes(checkAuth)} </Provider>, document.getElementById('app') )
import React from 'react' import ReactDOM from 'react-dom' import getRoutes from './config/routes' import { createStore, applyMiddleware } from 'redux' import { Provider } from 'react-redux' import users from 'redux/modules/users' import thunk from 'redux-thunk' import { checkIfAuthed } from 'helpers/auth' const store = createStore(users, applyMiddleware(thunk)) function checkAuth (nextState, replace) { const isAuthed = checkIfAuthed(store) const nextPathName = nextState.location.pathname if (nextPathName === '/' || nextPathName === '/auth') { if (isAuthed === true) { replace('/feed') } } else { if (isAuthed !== true) { replace('/auth') } } } ReactDOM.render( <Provider store={store}> {getRoutes(checkAuth)} </Provider>, document.getElementById('app') )
Add common in import statement
# -*- coding: utf-8 -*- ############################################################################## # # Copyright (c) 2010 Camptocamp SA (http://www.camptocamp.com) # All Right Reserved # # Author : Nicolas Bessi (Camptocamp) # # WARNING: This program as such is intended to be used by professional # programmers who take the whole responsability of assessing all potential # consequences resulting from its eventual inadequacies and bugs # End users who are looking for a ready-to-use solution with commercial # garantees and support are strongly adviced to contract a Free Software # Service Company # # This program is Free Software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. # ############################################################################## from . import payment_slip_from_invoice from . import reports_common
# -*- coding: utf-8 -*- ############################################################################## # # Copyright (c) 2010 Camptocamp SA (http://www.camptocamp.com) # All Right Reserved # # Author : Nicolas Bessi (Camptocamp) # # WARNING: This program as such is intended to be used by professional # programmers who take the whole responsability of assessing all potential # consequences resulting from its eventual inadequacies and bugs # End users who are looking for a ready-to-use solution with commercial # garantees and support are strongly adviced to contract a Free Software # Service Company # # This program is Free Software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. # ############################################################################## from . import payment_slip_from_invoice
Solve 'invalid target element' error
import React from 'react'; import ClipboardJS from 'clipboard'; export default class CopyButton extends React.PureComponent { constructor(props) { super(props); this.btnRef = React.createRef(); this.clipboardRef = React.createRef(); } static defaultProps = { content: '', }; componentDidMount() { this.clipboardRef.current = new ClipboardJS(this.btnRef.current, { text: () => this.props.content, }); } render() { return ( <button ref={this.btnRef} key="copy" onClick={() => {}} className="btn-copy" > 複製到剪貼簿 <style jsx>{` .btn-copy { margin-left: 10px; } `}</style> </button> ); } }
import React from 'react'; import ClipboardJS from 'clipboard'; export default class CopyButton extends React.PureComponent { constructor(props) { super(props); this.btnRef = React.createRef(); this.clipboardRef = React.createRef(); } static defaultProps = { content: '', }; componentDidMount() { this.clipboardRef.current = new ClipboardJS(this.btnRef.current, { text: () => this.props.content, }); } render() { return ( <button ref={this.btnRef} key="copy" onClick={() => {}} className="btn-copy" data-clipboard-target="#testCopyTarget" > 複製到剪貼簿 <style jsx>{` .btn-copy { margin-left: 10px; } `}</style> </button> ); } }
Move python rl history file just to help clean up ~/
# pylint: disable=unused-import, unused-variable, missing-docstring def _readline(): try: import readline except ImportError: print("Module readline not available.") else: import rlcompleter readline.parse_and_bind("tab: complete") import os histfile = os.path.join(os.environ["HOME"], 'python', '.history') try: readline.read_history_file(histfile) except IOError: pass import atexit atexit.register(readline.write_history_file, histfile) del os, histfile _readline() del _readline import sys sys.ps1 = "\001\033[01;33m\002>>>\001\033[00m\002 " sys.ps2 = "\001\033[01;33m\002...\001\033[00m\002 "
# pylint: disable=unused-import, unused-variable, missing-docstring def _readline(): try: import readline except ImportError: print("Module readline not available.") else: import rlcompleter readline.parse_and_bind("tab: complete") import os histfile = os.path.join(os.environ["HOME"], '.python_history') try: readline.read_history_file(histfile) except IOError: pass import atexit atexit.register(readline.write_history_file, histfile) del os, histfile _readline() del _readline import sys sys.ps1 = "\001\033[01;33m\002>>>\001\033[00m\002 " sys.ps2 = "\001\033[01;33m\002...\001\033[00m\002 "
Use icosahedron instead of sphere for less faces
/* globals AFRAME THREE */ AFRAME.registerBrush('single-sphere', { init: function (color, width) { this.material = new THREE.MeshStandardMaterial({ color: this.data.color, roughness: 0.6, metalness: 0.2, side: THREE.FrontSide, shading: THREE.SmoothShading }); this.geometry = new THREE.IcosahedronGeometry(0.5, 2); this.mesh = new THREE.Mesh(this.geometry, this.material); this.object3D.add(this.mesh); this.mesh.visible = false }, addPoint: function (position, orientation, pointerPosition, pressure, timestamp) { if (!this.firstPoint) { this.firstPoint = pointerPosition.clone(); this.mesh.position.set(this.firstPoint.x, this.firstPoint.y, this.firstPoint.z) } this.mesh.visible = true var distance = this.firstPoint.distanceTo(pointerPosition) * 2; this.mesh.scale.set(distance, distance, distance); return true; } }, {thumbnail: 'brushes/thumb_single_sphere.png', spacing: 0.0} );
/* globals AFRAME THREE */ AFRAME.registerBrush('single-sphere', { init: function (color, width) { this.material = new THREE.MeshStandardMaterial({ color: this.data.color, roughness: 0.6, metalness: 0.2, side: THREE.FrontSide, shading: THREE.SmoothShading }); this.geometry = new THREE.SphereGeometry(0.5, 16, 16); this.mesh = new THREE.Mesh(this.geometry, this.material); this.object3D.add(this.mesh); this.mesh.visible = false }, addPoint: function (position, orientation, pointerPosition, pressure, timestamp) { if (!this.firstPoint) { this.firstPoint = pointerPosition.clone(); this.mesh.position.set(this.firstPoint.x, this.firstPoint.y, this.firstPoint.z) } this.mesh.visible = true var distance = this.firstPoint.distanceTo(pointerPosition) * 2; this.mesh.scale.set(distance, distance, distance); return true; } }, {thumbnail: 'brushes/thumb_single_sphere.png', spacing: 0.0} );
Fix persistence in private tabs
import localForage from 'localforage'; import { withClientState } from 'apollo-link-state'; import { DialerInfo } from './queries'; import { CONFERENCE_PHONE_NUMBER } from '../config'; // TODO refactor after https://github.com/apollographql/apollo-link-state/issues/119 is resolved let persistedPhoneNumber; (async () => { persistedPhoneNumber = await localForage.getItem('dialer/PHONE_NUMBER'); })(); export default withClientState({ Query: { dialer: () => ({ __typename: 'Dialer', phoneNumber: persistedPhoneNumber || CONFERENCE_PHONE_NUMBER, }), }, Mutation: { updateDialer: (_, { input: { phoneNumber } = {} }, { cache }) => { const currentDialerQuery = cache.readQuery({ query: DialerInfo, variables: {} }); const updatedDialer = { ...currentDialerQuery.dialer, phoneNumber, }; cache.writeQuery({ query: DialerInfo, data: { dialer: updatedDialer, }, }); localForage.setItem('dialer/PHONE_NUMBER', phoneNumber); return updatedDialer; }, }, });
import localForage from 'localforage'; import { withClientState } from 'apollo-link-state'; import { DialerInfo } from './queries'; import { CONFERENCE_PHONE_NUMBER } from '../config'; let defaultPhoneNumber; (async () => { defaultPhoneNumber = (await localForage.getItem('dialer/CONFERENCE_PHONE_NUMBER')) || CONFERENCE_PHONE_NUMBER; })(); export default withClientState({ Query: { dialer: () => ({ __typename: 'Dialer', phoneNumber: defaultPhoneNumber, }), }, Mutation: { updateDialer: (_, { input: { phoneNumber } = {} }, { cache }) => { const currentDialerQuery = cache.readQuery({ query: DialerInfo, variables: {} }); const updatedDialer = { ...currentDialerQuery.dialer, phoneNumber, }; cache.writeQuery({ query: DialerInfo, data: { dialer: updatedDialer, }, }); localForage.setItem('dialer/CONFERENCE_PHONE_NUMBER', phoneNumber); return updatedDialer; }, }, });
Fix issue when API wasn't returning correct service dialog results
(function() { 'use strict'; angular.module('app.states') .run(appRun); /** @ngInject */ function appRun(routerHelper) { routerHelper.configureStates(getStates()); } function getStates() { return { 'marketplace.details': { url: '/:serviceTemplateId', templateUrl: 'app/states/marketplace/details/details.html', controller: StateController, controllerAs: 'vm', title: 'Service Template Details', resolve: { dialogs: resolveDialogs, serviceTemplate: resolveServiceTemplate } } }; } /** @ngInject */ function resolveServiceTemplate($stateParams, CollectionsApi) { var options = {attributes: ['picture', 'picture.image_href']}; return CollectionsApi.get('service_templates', $stateParams.serviceTemplateId, options); } /** @ngInject */ function resolveDialogs($stateParams, CollectionsApi) { var options = {expand: 'resources', attributes: 'content'}; return CollectionsApi.query('service_templates/' + $stateParams.serviceTemplateId + '/service_dialogs', options); } /** @ngInject */ function StateController(dialogs, serviceTemplate) { var vm = this; vm.title = 'Service Template Details'; vm.dialogs = dialogs.resources[0].content; vm.serviceTemplate = serviceTemplate; } })();
(function() { 'use strict'; angular.module('app.states') .run(appRun); /** @ngInject */ function appRun(routerHelper) { routerHelper.configureStates(getStates()); } function getStates() { return { 'marketplace.details': { url: '/:serviceTemplateId', templateUrl: 'app/states/marketplace/details/details.html', controller: StateController, controllerAs: 'vm', title: 'Service Template Details', resolve: { dialogs: resolveDialogs, serviceTemplate: resolveServiceTemplate } } }; } /** @ngInject */ function resolveServiceTemplate($stateParams, CollectionsApi) { var options = {attributes: ['picture', 'picture.image_href']}; return CollectionsApi.get('service_templates', $stateParams.serviceTemplateId, options); } /** @ngInject */ function resolveDialogs($stateParams, CollectionsApi) { var options = {expand: true, attributes: 'content'}; return CollectionsApi.query('service_templates/' + $stateParams.serviceTemplateId + '/service_dialogs', options); } /** @ngInject */ function StateController(dialogs, serviceTemplate) { var vm = this; vm.title = 'Service Template Details'; vm.dialogs = dialogs.resources[0].content; vm.serviceTemplate = serviceTemplate; } })();
Add a test for a date missing from English historical calendars.
import unittest from datetime import date import qual class TestProlepticGregorianCalendar(unittest.TestCase): def setUp(self): self.calendar = qual.ProlepticGregorianCalendar() def check_valid_date(self, year, month, day): d = self.calendar.date(year, month, day) self.assertIsNotNone(d) def check_invalid_date(self, year, month, day): self.assertRaises(Exception, lambda : self.calendar(year, month, day)) def test_leap_year_from_before_1582(self): """Pope Gregory introduced the calendar in 1582""" self.check_valid_date(1200, 2, 29) def test_day_missed_out_in_British_calendar_change(self): """This date never happened in English law: It was missed when changing from the Julian to Gregorian. This test proves that we are not using a historical British calendar.""" self.check_valid_date(1752, 9, 3) def test_Julian_leap_day_is_not_a_valid_date(self): """This day /was/ a leap day contemporaneously, but is not a valid date of the Gregorian calendar.""" self.check_invalid_date(1300, 2, 29)
import unittest from datetime import date import qual class TestProlepticGregorianCalendar(unittest.TestCase): def setUp(self): self.calendar = qual.ProlepticGregorianCalendar() def check_valid_date(self, year, month, day): d = self.calendar.date(year, month, day) self.assertIsNotNone(d) def check_invalid_date(self, year, month, day): self.assertRaises(Exception, lambda : self.calendar(year, month, day)) def test_leap_year_from_before_1582(self): """Pope Gregory introduced the calendar in 1582""" self.check_valid_date(1200, 2, 29) def test_Julian_leap_day_is_not_a_valid_date(self): """This day /was/ a leap day contemporaneously, but is not a valid date of the Gregorian calendar.""" self.check_invalid_date(1300, 2, 29)
Add support for BS4 menu items
import cx from 'classnames'; import {noop} from 'lodash'; import React from 'react'; import menuItemContainer from './containers/menuItemContainer'; class BaseMenuItem extends React.Component { displayName = 'BaseMenuItem'; constructor(props) { super(props); this._handleClick = this._handleClick.bind(this); } render() { const {active, children, className, disabled} = this.props; const conditionalClassNames = { 'active': active, 'disabled': disabled, }; return ( <li className={cx(conditionalClassNames, className)}> <a className={cx('dropdown-item', conditionalClassNames)} href="#" onClick={this._handleClick} role="button"> {children} </a> </li> ); } _handleClick(e) { const {disabled, onClick} = this.props; e.preventDefault(); !disabled && onClick(e); } } BaseMenuItem.defaultProps = { onClick: noop, }; const MenuItem = menuItemContainer(BaseMenuItem); export {BaseMenuItem}; export default MenuItem;
import cx from 'classnames'; import {noop} from 'lodash'; import React from 'react'; import menuItemContainer from './containers/menuItemContainer'; class BaseMenuItem extends React.Component { displayName = 'BaseMenuItem'; constructor(props) { super(props); this._handleClick = this._handleClick.bind(this); } render() { const {active, children, className, disabled} = this.props; return ( <li className={cx({ 'active': active, 'disabled': disabled, }, className)}> <a onClick={this._handleClick} role="button"> {children} </a> </li> ); } _handleClick(e) { const {disabled, onClick} = this.props; e.preventDefault(); !disabled && onClick(e); } } BaseMenuItem.defaultProps = { onClick: noop, }; const MenuItem = menuItemContainer(BaseMenuItem); export {BaseMenuItem}; export default MenuItem;
Fix typo when renaming ingestor -> ingester
#!/usr/bin/env python from setuptools import setup setup( name='datacube-experiments', description='Experimental Datacube v2 Ingestor', version='0.0.1', packages=['ingester'], url='http://github.com/omad/datacube-experiments', install_requires=[ 'click', 'eodatasets', 'eotools', 'gdal', 'pathlib', 'pyyaml', 'numpy', 'netCDF4', ], tests_require=[ 'pytest', ], entry_points={ 'console_scripts': [ 'datacube_ingest = ingester.datacube_ingester:main', 'print_image = ingester.utils:print_image', ] }, )
#!/usr/bin/env python from setuptools import setup setup( name='datacube-experiments', description='Experimental Datacube v2 Ingestor', version='0.0.1', packages=['ingester'], url='http://github.com/omad/datacube-experiments', install_requires=[ 'click', 'eodatasets', 'eotools', 'gdal', 'pathlib', 'pyyaml', 'numpy', 'netCDF4', ], tests_require=[ 'pytest', ], entry_points={ 'console_scripts': [ 'datacube_ingest = ingester.datacube_ingestor:main', 'print_image = ingester.utils:print_image', ] }, )
Change on account id for enablestudents
EnableStudentController.$inject = ['$rootScope', 'toaster', 'TbUtils', '$state', 'students']; function EnableStudentController ($rootScope, toaster, TbUtils, $state, students) { const vm = this; vm.email = ""; vm.accountId = ""; vm.password = ""; vm.submitting = false; vm.enableStudent = EnableStudent; function EnableStudent(){ vm.submitting = true; let student = { AccountId: vm.accountId.toString(), Email: vm.email, Password: vm.password } students.enableStudent(vm.student, enableStudentSuccess, enableStudentFail); } function enableStudentSuccess(response){ vm.submitting = false; TbUtils.displayNotification('success', 'Alumno habilitado exitosamente!', 'Habilitado'); $state.go('landing.login'); } function enableStudentFail(response){ vm.submitting = false; TbUtils.showErrorMessage('error', 'No se encontro una cuenta valida con los datos ingresados', 'Error de Habilitacion'); } } module.exports = { name: 'EnableStudentController', ctrl: EnableStudentController };
EnableStudentController.$inject = ['$rootScope', 'toaster', 'TbUtils', '$state', 'students']; function EnableStudentController ($rootScope, toaster, TbUtils, $state, students) { const vm = this; vm.email = ""; vm.accountId = ""; vm.password = ""; vm.enableStudent = EnableStudent; function EnableStudent(){ let student = { AccountId: vm.AccountId, Email: vm.email, Password: vm.password } console.log("Data that is going to be sent: "+JSON.stringify(student)); students.enableStudent(vm.student, enableStudentSuccess, enableStudentFail); } function enableStudentSuccess(response){ console.log(response); TbUtils.displayNotification('success', 'Alumno habilitado exitosamente!', 'Habilitado'); $state.go('landing.login'); } function enableStudentFail(response){ console.log(response); TbUtils.showErrorMessage('error', 'No se encontro una cuenta valida con los datos ingresados', 'Error de Habilitacion'); } } module.exports = { name: 'EnableStudentController', ctrl: EnableStudentController };
Fix unit test of voice function
import unittest from tests import PluginTest from plugins import voice from CmdInterpreter import JarvisAPI from Jarvis import Jarvis # this test class contains test cases for the plugins "gtts" and "disable_gtts" # which are included in the "voice.py" file in the "plugins" folder class VoiceTest(PluginTest): # test "gtts" plugin def setUp(self): self.test_gtts = self.load_plugin(voice.gtts) def test_gtts(self): # run "gtts" plugin code self.test_gtts.gtts(jarvis, self) # verify that "gtts" plugin code works self.assertEqual(self.jarvis_api.get_data('gtts_status'), True) # test "disable_gtts" plugin def setUp(self): self.test_disable_gtts = self.load_plugin(voice.disable_gtts) def test_disable_gtts(self): # run "disable_gtts" plugin code self.test_disable_gtts.disable_gtts(jarvis, self) # verify that "disable_gtts" plugin code works self.assertEqual(self.jarvis_api.get_data('gtts_status'), False) if __name__ == '__main__': unittest.main()
import unittest from tests import PluginTest from plugins import voice from CmdInterpreter import JarvisAPI from Jarvis import Jarvis # this test class contains test cases for the plugins "gtts" and "disable_gtts" # which are included in the "voice.py" file in the "plugins" folder class VoiceTest(PluginTest): # test "gtts" plugin def setUp(self): self.test_gtts = self.load_plugin(voice.gtts) def test_gtts(self): # run "gtts" plugin code self.test_gtts.run(voice.gtts) # verify that "gtts" plugin code works self.assertEqual(self.jarvis_api.get_data('gtts_status'), True) # test "disable_gtts" plugin def setUp(self): self.test_disable_gtts = self.load_plugin(voice.disable_gtts) def test_disable_gtts(self): # run "disable_gtts" plugin code self.test_disable_gtts.run(voice.disable_gtts) # verify that "disable_gtts" plugin code works self.assertEqual(self.jarvis_api.get_data('gtts_status'), False) if __name__ == '__main__': unittest.main()
Order qualifier corresponding to Java conventions.
package nerd.tuxmobil.fahrplan.congress.navigation; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import java.util.HashMap; import java.util.Map; public class RoomForC3NavConverter { private static final Map<String, String> ROOM_TO_C3NAV_MAPPING = new HashMap<String, String>() {{ put("HALL 1", "h1"); put("HALL 2", "h2"); put("HALL 3", "h3"); put("HALL 6", "h6"); put("HALL 13", "h13"); put("HALL 14", "h14"); put("HALL B", "hb"); put("HALL G", "hg"); put("HALL F", "hf"); }}; @Nullable public static String convert(@NonNull final String venue, @Nullable final String room) { if (room != null && venue.toUpperCase().equals("CCH")) { return ROOM_TO_C3NAV_MAPPING.get(room.toUpperCase()); } return null; } }
package nerd.tuxmobil.fahrplan.congress.navigation; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import java.util.HashMap; import java.util.Map; public class RoomForC3NavConverter { private final static Map<String, String> ROOM_TO_C3NAV_MAPPING = new HashMap<String, String>() {{ put("HALL 1", "h1"); put("HALL 2", "h2"); put("HALL 3", "h3"); put("HALL 6", "h6"); put("HALL 13", "h13"); put("HALL 14", "h14"); put("HALL B", "hb"); put("HALL G", "hg"); put("HALL F", "hf"); }}; @Nullable public static String convert(@NonNull final String venue, @Nullable final String room) { if (room != null && venue.toUpperCase().equals("CCH")) { return ROOM_TO_C3NAV_MAPPING.get(room.toUpperCase()); } return null; } }
Add logic to show elapsed time in windows
package battery import ( "math" "syscall" "unsafe" ) var ( modkernel32 = syscall.NewLazyDLL("kernel32") procGetSystemPowerStatus = modkernel32.NewProc("GetSystemPowerStatus") ) type SYSTEM_POWER_STATUS struct { ACLineStatus byte BatteryFlag byte BatteryLifePercent byte Reserved1 byte BatteryLifeTime uint32 BatteryFullLifeTime uint32 } func Info() (int, int, bool, error) { var sps SYSTEM_POWER_STATUS _, r1, err := procGetSystemPowerStatus.Call(uintptr(unsafe.Pointer(&sps))) if r1 != 0 { if err != nil { return 0, 0, false, err } } percent := int(sps.BatteryLifePercent) var elapsed int // BatteryLifeTime has MaxUint32 (2^32-1) when it cannot be detected. if sps.BatteryLifeTime != math.MaxUint32 { elapsed = int(float64(sps.BatteryLifeTime) / 60) } return percent, elapsed, sps.ACLineStatus == 1, nil }
package battery import ( "syscall" "unsafe" ) var ( modkernel32 = syscall.NewLazyDLL("kernel32") procGetSystemPowerStatus = modkernel32.NewProc("GetSystemPowerStatus") ) type SYSTEM_POWER_STATUS struct { ACLineStatus byte BatteryFlag byte BatteryLifePercent byte Reserved1 byte BatteryLifeTime uint32 BatteryFullLifeTime uint32 } func Info() (int, bool, error) { var sps SYSTEM_POWER_STATUS _, r1, err := procGetSystemPowerStatus.Call(uintptr(unsafe.Pointer(&sps))) if r1 != 0 { if err != nil { return 0, false, err } } return int(sps.BatteryLifePercent), sps.ACLineStatus == 1, nil }
Improve choose_nodes method (set problem)
#!/usr/bin/env python from utils import read_input from constants import EURISTIC_FACTOR from collections import Counter import sys def choose_nodes(nodes, neighbours_iterable): neighbours_count = len(neighbours_iterable) unpacked_list = [] for t in neighbours_iterable: unpacked_list += t[1:] c = Counter(unpacked_list) nodes_set = set(nodes) return tuple(k for k, v in c.items() if v >= neighbours_count * EURISTIC_FACTOR and k not in nodes_set) def main(separator='\t'): """ Choose the next node to be added to the subgraph. Take as input: - iterable of nodes (ordered) as key - iterable of iterable as value """ data = read_input(sys.stdin) for nodes, neighbours_iterable in data: nodes = eval(nodes) neighbours_iterable = eval(neighbours_iterable) next_nodes = choose_nodes(nodes, neighbours_iterable) for n in next_nodes: print("{}\t{}".format(sorted(nodes + (n, )), neighbours_iterable)) if __name__ == '__main__': main()
#!/usr/bin/env python from utils import read_input from constants import EURISTIC_FACTOR from collections import Counter import sys def choose_nodes(nodes, neighbours_iterable): neighbours_count = len(neighbours_iterable) unpacked_list = [] for t in neighbours_iterable: unpacked_list += t[1:] c = Counter(unpacked_list) return tuple(k for k, v in c.items() if v >= neighbours_count * EURISTIC_FACTOR and k not in set(nodes)) def main(separator='\t'): """ Choose the next node to be added to the subgraph. Take as input: - iterable of nodes (ordered) as key - iterable of iterable as value """ data = read_input(sys.stdin) for nodes, neighbours_iterable in data: nodes = eval(nodes) neighbours_iterable = eval(neighbours_iterable) next_nodes = choose_nodes(nodes, neighbours_iterable) for n in next_nodes: print("{}\t{}".format(sorted(nodes + (n, )), neighbours_iterable)) if __name__ == '__main__': main()
Refactor internals to store date in a Map instead of Object
class FakeStorage { #data = new Map(); get length() { return this.#data.size; } key(n) { n = Number.parseInt(n, 10); const iterator = this.#data.keys(); let i = 0; let result = iterator.next(); while (!result.done) { if (i === n) { return result.value; } i += 1; result = iterator.next(); } return null; } getItem(key) { return this.#data.get(`${key}`) ?? null; } setItem(key, value) { this.#data.set(`${key}`, `${value}`); } removeItem(key) { this.#data.delete(`${key}`); } clear() { this.#data.clear(); } } export default FakeStorage;
class FakeStorage { #data = {}; get length() { return Object.keys(this.#data).length; } key(n) { return Object.keys(this.#data)[Number.parseInt(n, 10)] ?? null; } getItem(key) { const _data = this.#data; const _key = `${key}`; return _data.hasOwnProperty(_key) ? _data[_key] : null; } setItem(key, value) { this.#data[`${key}`] = `${value}`; } removeItem(key, value) { const _data = this.#data; const _key = `${key}`; if (_data.hasOwnProperty(_key)) { delete _data[_key]; } } clear(key, value) { this.#data = {}; } } export default FakeStorage;
Change for L.Class and add zombie function
var TC = require('tangram.cartodb'); var LeafletLayerView = require('./leaflet-layer-view'); var L = require('leaflet'); var LeafletCartoDBVectorLayerGroupView = L.Class.extend({ includes: [ LeafletLayerView.prototype ], options: { minZoom: 0, maxZoom: 28, tileSize: 256, zoomOffset: 0, tileBuffer: 50 }, events: { featureOver: null, featureOut: null, featureClick: null }, initialize: function (layerGroupModel, map) { LeafletLayerView.call(this, layerGroupModel, this, map); layerGroupModel.bind('change:urls', this._onURLsChanged, this); this.tangram = new TC(map); layerGroupModel.each(this._onLayerAdded, this); layerGroupModel.onLayerAdded(this._onLayerAdded.bind(this)); }, onAdd: function (map) { L.Layer.prototype.onAdd.call(this, map); }, _onLayerAdded: function (layer) { var self = this; layer.bind('change:meta', function (e) { self.tangram.addLayer(e.attributes); }); }, setZIndex: function (zIndex) {}, _onURLsChanged: function (e, res) { this.tangram.addDataSource(res.tiles[0]); } }); module.exports = LeafletCartoDBVectorLayerGroupView;
var TC = require('tangram.cartodb'); var LeafletLayerView = require('./leaflet-layer-view'); var L = require('leaflet'); var LeafletCartoDBVectorLayerGroupView = L.Layer.extend({ includes: [ LeafletLayerView.prototype ], options: { minZoom: 0, maxZoom: 28, tileSize: 256, zoomOffset: 0, tileBuffer: 50 }, events: { featureOver: null, featureOut: null, featureClick: null }, initialize: function (layerGroupModel, map) { LeafletLayerView.call(this, layerGroupModel, this, map); layerGroupModel.bind('change:urls', this._onURLsChanged, this); this.tangram = new TC(map); layerGroupModel.each(this._onLayerAdded, this); layerGroupModel.onLayerAdded(this._onLayerAdded.bind(this)); }, onAdd: function (map) { L.Layer.prototype.onAdd.call(this, map); }, _onLayerAdded: function (layer) { var self = this; layer.bind('change:meta', function (e) { self.tangram.addLayer(e.attributes); }); }, _onURLsChanged: function (e, res) { this.tangram.addDataSource(res.tiles[0]); } }); module.exports = LeafletCartoDBVectorLayerGroupView;
Add pull to load remote chagnes in before
<?php namespace Kironuniversity\Git\Controllers; use BackendMenu; use Backend\Classes\Controller; use GitWrapper\GitWrapper; use Flash; /** * Deploy Back-end Controller */ class Deploy extends Controller { public function __construct() { parent::__construct(); BackendMenu::setContext('Kironuniversity.Git', 'git', 'deploy'); } public function index(){ $wrapper = new GitWrapper('git'); $git = $wrapper->workingCopy('.'); $this->vars['changed'] = $git->hasChanges(); $this->vars['changes'] = nl2br($git->status(['porcelain' => true, 'u' => true])->getOutput()); } public function onPush(){ $wrapper = new GitWrapper('git'); $wrapper->git('config --global push.default simple'); $git = $wrapper->workingCopy('.'); $git->checkout('dev'); $pushLog = ''; $mergeLog = ''; if($git->hasChanges()){ $pushLog = nl2br($git->add('.')->commit('content updates')->pull()->push()->getOutput()); $mergeLog = nl2br($git->checkout('master')->merge('dev')->push()->checkout('dev')->getOutput()); } Flash::success('Done'); return ['#output' => '<p>'.$pushLog.'</p><p>'.$mergeLog.'</p>']; } }
<?php namespace Kironuniversity\Git\Controllers; use BackendMenu; use Backend\Classes\Controller; use GitWrapper\GitWrapper; use Flash; /** * Deploy Back-end Controller */ class Deploy extends Controller { public function __construct() { parent::__construct(); BackendMenu::setContext('Kironuniversity.Git', 'git', 'deploy'); } public function index(){ $wrapper = new GitWrapper('git'); $git = $wrapper->workingCopy('.'); $this->vars['changed'] = $git->hasChanges(); $this->vars['changes'] = nl2br($git->status(['porcelain' => true, 'u' => true])->getOutput()); } public function onPush(){ $wrapper = new GitWrapper('git'); $wrapper->git('config --global push.default simple'); $git = $wrapper->workingCopy('.'); $git->checkout('dev'); $pushLog = ''; $mergeLog = ''; if($git->hasChanges()){ $pushLog = nl2br($git->add('.')->commit('content updates')->push()->getOutput()); $mergeLog = nl2br($git->checkout('master')->merge('dev')->push()->checkout('dev')->getOutput()); } Flash::success('Done'); return ['#output' => '<p>'.$pushLog.'</p><p>'.$mergeLog.'</p>']; } }