hash
stringlengths
40
40
diff
stringlengths
131
114k
message
stringlengths
7
980
project
stringlengths
5
67
split
stringclasses
1 value
e0e6f7b03821addf5a3463b0f11c90b1e3e68a9b
diff --git a/spyder/plugins/pylint/widgets/pylintgui.py b/spyder/plugins/pylint/widgets/pylintgui.py index <HASH>..<HASH> 100644 --- a/spyder/plugins/pylint/widgets/pylintgui.py +++ b/spyder/plugins/pylint/widgets/pylintgui.py @@ -457,7 +457,8 @@ class PylintWidget(QWidget): pylint_item = (module, items["line_nb"], items["message"], items["msg_id"], items["message_name"]) act_result = results[line[0] + ':'] - if len(act_result) < self.parent.get_option('max_entries'): + if (self.parent is not None and + len(act_result) < self.parent.get_option('max_entries')): results[line[0] + ':'].append(pylint_item) # Rate
verify if self.parent is not None
spyder-ide_spyder
train
18c596633e298f30bad09ab29dc9a3ea219c525b
diff --git a/housekeeper/pipelines/cli.py b/housekeeper/pipelines/cli.py index <HASH>..<HASH> 100644 --- a/housekeeper/pipelines/cli.py +++ b/housekeeper/pipelines/cli.py @@ -1,10 +1,14 @@ # -*- coding: utf-8 -*- +import logging + import click from housekeeper.store import get_manager from .mip import analysis as mip_analysis from .general import commit_analysis +log = logging.getLogger(__name__) + @click.group() @click.pass_context @@ -18,6 +22,7 @@ def add(context): @click.pass_context def mip(context, config): """Add MIP analysis.""" + log.info("adding analysis with config: %s", config) new_analysis = mip_analysis(config) commit_analysis(context.obj['db'], new_analysis) - click.echo("added new analysis: ", new_analysis.name) + click.echo("added new analysis: {}".format(new_analysis.name))
log config file and fix bug in echo success
Clinical-Genomics_housekeeper
train
821515474983a900464c11d41e7b021ca5a3d771
diff --git a/environs/openstack/config_test.go b/environs/openstack/config_test.go index <HASH>..<HASH> 100644 --- a/environs/openstack/config_test.go +++ b/environs/openstack/config_test.go @@ -245,12 +245,33 @@ var configTests = []configTest{ }, err: ".*expected string, got 666", }, { + summary: "missing tenant in environment", + err: "required environment variable not set for credentials attribute: TenantName", + envVars: map[string]string{ + "OS_USERNAME": "user", + "OS_PASSWORD": "secret", + "OS_AUTH_URL": "http://auth", + "OS_TENANT_NAME": "", + "NOVA_PROJECT_ID": "", + "OS_REGION_NAME": "region", + }, + }, { summary: "invalid auth-url type", config: attrs{ "auth-url": 666, }, err: ".*expected string, got 666", }, { + summary: "missing auth-url in environment", + err: "required environment variable not set for credentials attribute: URL", + envVars: map[string]string{ + "OS_USERNAME": "user", + "OS_PASSWORD": "secret", + "OS_AUTH_URL": "", + "OS_TENANT_NAME": "sometenant", + "OS_REGION_NAME": "region", + }, + }, { summary: "invalid authorization mode", config: attrs{ "auth-mode": "invalid-mode", @@ -394,24 +415,6 @@ func (s *ConfigSuite) setupEnvCredentials() { os.Setenv("OS_REGION_NAME", "region") } -var regionTestConfig = configTests[0] - -func (s *ConfigSuite) TestMissingTenant(c *C) { - s.setupEnvCredentials() - os.Setenv("OS_TENANT_NAME", "") - os.Setenv("NOVA_PROJECT_ID", "") - test := regionTestConfig - test.err = "required environment variable not set for credentials attribute: TenantName" - test.check(c) -} - -func (s *ConfigSuite) TestMissingAuthUrl(c *C) { - s.setupEnvCredentials() - os.Setenv("OS_AUTH_URL", "") - test := regionTestConfig - test.err = "required environment variable not set for credentials attribute: URL" - test.check(c) -} func (s *ConfigSuite) TestCredentialsFromEnv(c *C) { // Specify a basic configuration without credentials.
Get rid of the regionTestConfig-based tests completely.
juju_juju
train
c1a88b512f10bde3f484e0d8bc015fced5d31c31
diff --git a/haphilipsjs/__init__.py b/haphilipsjs/__init__.py index <HASH>..<HASH> 100644 --- a/haphilipsjs/__init__.py +++ b/haphilipsjs/__init__.py @@ -114,15 +114,12 @@ class PhilipsTV(object): self.channel_id = id def getChannelLists(self): - if self.api_version >= '6': - r = self._getReq('channeldb/tv') - if r: - # could be alltv and allsat - return [l['id'] for l in r.get('channelLists', [])] - else: - return [] + r = self._getReq('channeldb/tv') + if r: + # could be alltv and allsat + return [l['id'] for l in r.get('channelLists', [])] else: - return ['alltv'] + return [] def getSources(self): self.sources = []
Get channel list is working in API version 5.
danielperna84_ha-philipsjs
train
54ca6d01078f0667a82ae2e12021a7479549bc7c
diff --git a/bootstrap.php b/bootstrap.php index <HASH>..<HASH> 100644 --- a/bootstrap.php +++ b/bootstrap.php @@ -8,6 +8,7 @@ require_once __DIR__ . '/vendor/autoload.php'; (new Dotenv())->load(__DIR__ . '/.env'); $config = [ + 'appDir' => __DIR__, 'env' => $_SERVER['APP_ENV'] ?? 'dev', ]; diff --git a/src/Application.php b/src/Application.php index <HASH>..<HASH> 100644 --- a/src/Application.php +++ b/src/Application.php @@ -30,7 +30,7 @@ class Application extends BaseApplication $this->register(new ServiceProvider\CommandProvider()); $this->register(new MonologServiceProvider(), [ 'monolog.name' => self::NAME, - 'monolog.logfile' => dirname(__DIR__) . "/var/log/{$this['env']}.log", + 'monolog.logfile' => "{$this['appDir']}/var/log/{$this['env']}.log", 'monolog.use_error_handler' => true, ]); }
setup appDir variable. allowing to override this
glensc_slack-unfurl
train
12ebfb52cbe009e37f7bb1df7a98e286aca1a9eb
diff --git a/test/haml/engine_test.rb b/test/haml/engine_test.rb index <HASH>..<HASH> 100644 --- a/test/haml/engine_test.rb +++ b/test/haml/engine_test.rb @@ -1299,7 +1299,7 @@ HAML def test_local_assigns_dont_modify_class assert_haml_ugly("= foo", :locals => {:foo => 'bar'}) - assert_equal(nil, defined?(foo)) + assert_nil(defined?(foo)) end def test_object_ref_with_nil_id; skip # object reference diff --git a/test/test_helper.rb b/test/test_helper.rb index <HASH>..<HASH> 100644 --- a/test/test_helper.rb +++ b/test/test_helper.rb @@ -58,8 +58,7 @@ class Haml::TestCase < BASE_TEST_CLASS def render(text, options = {}, base = nil, &block) options = { escape_html: false }.merge(options) # incompatible default - options.delete(:ugly) - options.delete(:suppress_eval) + %i[attr_wrapper cdata suppress_eval ugly].each { |opt| options.delete(opt) } eval Hamlit::Engine.new(options).call(text) end
Resolve more warnings from haml test
haml_haml
train
dc2712a063c33d4c6fce6e42e5f45e7e97d46539
diff --git a/raven/lib/raven/client.rb b/raven/lib/raven/client.rb index <HASH>..<HASH> 100644 --- a/raven/lib/raven/client.rb +++ b/raven/lib/raven/client.rb @@ -16,7 +16,7 @@ module Raven attr_reader :server, :public_key, :secret_key, :project_id - def initialize(dsn, options={}) + def initialize(dsn=nil, options={}, &block) if options.empty? && dsn.is_a?(Hash) dsn, options = nil, dsn end @@ -32,10 +32,15 @@ module Raven options[:public_key] = uri.user options[:secret_key] = uri.password end - @server = options[:server] - @public_key = options[:public_key] - @secret_key = options[:secret_key] - @project_id = options[:project_id] + self.server = options[:server] + self.public_key = options[:public_key] + self.secret_key = options[:secret_key] + self.project_id = options[:project_id] + block.call(self) if block + raise Error.new('No server specified') unless self.server + raise Error.new('No public key specified') unless self.public_key + raise Error.new('No secret key specified') unless self.secret_key + raise Error.new('No project ID specified') unless self.project_id end def conn
Add block init and validation to Client.
getsentry_raven-ruby
train
8149ace52cb1f6fccb50a95011e68df881fa2452
diff --git a/internal/restorable/images_test.go b/internal/restorable/images_test.go index <HASH>..<HASH> 100644 --- a/internal/restorable/images_test.go +++ b/internal/restorable/images_test.go @@ -443,4 +443,40 @@ func TestDrawImageAndReplacePixels(t *testing.T) { } } +func TestDispose(t *testing.T) { + base0 := image.NewRGBA(image.Rect(0, 0, 1, 1)) + img0 := newImageFromImage(base0) + defer img0.Dispose() + + base1 := image.NewRGBA(image.Rect(0, 0, 1, 1)) + img1 := newImageFromImage(base1) + + base2 := image.NewRGBA(image.Rect(0, 0, 1, 1)) + base2.Pix[0] = 0xff + base2.Pix[1] = 0xff + base2.Pix[2] = 0xff + base2.Pix[3] = 0xff + img2 := newImageFromImage(base2) + defer img2.Dispose() + + img1.DrawImage(img2, 0, 0, 1, 1, nil, nil, opengl.CompositeModeCopy, graphics.FilterNearest) + img0.DrawImage(img1, 0, 0, 1, 1, nil, nil, opengl.CompositeModeCopy, graphics.FilterNearest) + img1.Dispose() + + if err := ResolveStaleImages(); err != nil { + t.Fatal(err) + } + if err := Restore(); err != nil { + t.Fatal(err) + } + got, err := img0.At(0, 0) + if err != nil { + t.Fatal(err) + } + want := color.RGBA{0xff, 0xff, 0xff, 0xff} + if !sameColors(got, want, 1) { + t.Errorf("got: %v, want: %v", got, want) + } +} + // TODO: How about volatile/screen images?
restorable: Add TestDispose
hajimehoshi_ebiten
train
0aa60c87a7b228c2165c7f05987fa6a858cdae56
diff --git a/lib/ohai/plugins/windows/virtualization.rb b/lib/ohai/plugins/windows/virtualization.rb index <HASH>..<HASH> 100644 --- a/lib/ohai/plugins/windows/virtualization.rb +++ b/lib/ohai/plugins/windows/virtualization.rb @@ -1,6 +1,8 @@ # # Author:: Pavel Yudin (<[email protected]>) +# Author:: Tim Smith (<[email protected]>) # Copyright:: Copyright (c) 2015 Pavel Yudin +# Copyright:: Copyright (c) 2015 Chef Software, Inc. # License:: Apache License, Version 2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -16,29 +18,35 @@ # limitations under the License. # -require 'ohai/util/file_helper' - -include Ohai::Util::FileHelper +require 'wmi-lite/wmi' Ohai.plugin(:Virtualization) do - provides "virtualization" - - def powershell_exists? - which('powershell.exe') - end + provides 'virtualization' collect_data(:windows) do virtualization Mash.new unless virtualization virtualization[:systems] = Mash.new unless virtualization[:systems] - # Detect Parallels virtual machine from BIOS information - if powershell_exists? - so = shell_out('powershell.exe "Get-WmiObject -Class Win32_BIOS"') - if so.stdout =~ /Parallels Software International Inc./ - virtualization[:system] = 'parallels' - virtualization[:role] = 'guest' - virtualization[:systems][:parallels] = 'guest' - end + # Grab BIOS data from WMI to determine vendor information + wmi = WmiLite::Wmi.new + bios = wmi.instances_of('Win32_BIOS') + + case bios[0]['manufacturer'] + when 'innotek GmbH' + virtualization[:system] = 'vbox' + virtualization[:role] = 'guest' + virtualization[:systems][:vbox] = 'guest' + when 'Parallels Software International Inc.' + virtualization[:system] = 'parallels' + virtualization[:role] = 'guest' + virtualization[:systems][:parallels] = 'guest' + end + + # vmware fusion detection + if bios[0]['serialnumber'] == /VMware/ + virtualization[:system] = 'vmware' + virtualization[:role] = 'guest' + virtualization[:systems][:vmware] = 'guest' end end end
Detect vbox/vmware on Windows and speed up runs Fetch WMI data within Ruby vs. shelling out to Powershell. This should be WAY faster.
chef_ohai
train
7fb2105aae9c3fff9910ee08fb8188ee75fab15b
diff --git a/core/src/main/java/lucee/runtime/op/Decision.java b/core/src/main/java/lucee/runtime/op/Decision.java index <HASH>..<HASH> 100755 --- a/core/src/main/java/lucee/runtime/op/Decision.java +++ b/core/src/main/java/lucee/runtime/op/Decision.java @@ -918,7 +918,7 @@ public final class Decision { int len = path.length(); for (int i = 0; i < len; i++) { - if ("?<>:*|\"".indexOf(path.charAt(i)) > -1) return false; + if ("?<>*|\"".indexOf(path.charAt(i)) > -1) return false; } } }
Added a fix for LDEV-<I>
lucee_Lucee
train
3a027bfa68a1e3e84d25e1f07708800dfccbc1bb
diff --git a/template/app/view/Comments.js b/template/app/view/Comments.js index <HASH>..<HASH> 100644 --- a/template/app/view/Comments.js +++ b/template/app/view/Comments.js @@ -365,19 +365,5 @@ Ext.define('Docs.view.Comments', { Docs.view.auth.LoginHelper.renderToComments(newComment); } }, this); - }, - - showMember: function(cls, member) { - var memberEl = Ext.get(member).down('.long'), - id = ('class-' + cls + '-' + member).replace(/\./g, '-'); - - if (!memberEl.hasCls('renderedComment')) { - this.commentsMetaTpl.append(memberEl, { - num: 0, - id: id - }); - memberEl.addCls('renderedComment'); - Docs.App.getController('CommentsMeta').commentIdMap['comments-' + id] = ['class', cls, member]; - } } });
Remove unused Docs.view.Comments#showMember method.
senchalabs_jsduck
train
4779f91b9361d9be6f7a681d66788bf5db587b27
diff --git a/src/Common/Model/Base.php b/src/Common/Model/Base.php index <HASH>..<HASH> 100644 --- a/src/Common/Model/Base.php +++ b/src/Common/Model/Base.php @@ -1758,14 +1758,11 @@ abstract class Base $oTemp = new \stdClass(); $oTemp->key = $oField->Field; - $oTemp->label = null; + $oTemp->label = $this->describeFieldsPrepareLabel($oTemp->key); $oTemp->type = null; $oTemp->allow_null = $oField->Null === 'YES'; $oTemp->validation = []; - // Prepare the label - $this->describeFieldsPrepareLabel($oTemp); - // Guess the field's type and some basic validation $this->describeFieldsGuessType($oTemp, $oField->Type); $this->describeFieldsGuessValidation($oTemp, $oField->Type); @@ -1781,12 +1778,16 @@ abstract class Base /** * Generates a human friendly label from the field's key * - * @param \stdClass $oField the field object + * @param string $sLabel The label to format + * + * @return string */ - protected function describeFieldsPrepareLabel(&$oField) + protected function describeFieldsPrepareLabel($sLabel) { - $oField->label = ucwords(preg_replace('/[\-_]/', ' ', $oField->key)); - $oField->label = str_ireplace(['id'], ['ID'], $oField->label); + $sLabel = ucwords(preg_replace('/[\-_]/', ' ', $sLabel)); + $sLabel = str_ireplace(['id'], ['ID'], $sLabel); + + return $sLabel; } // -------------------------------------------------------------------------- @@ -1799,10 +1800,11 @@ abstract class Base */ protected function describeFieldsGuessType(&$oField, $sType) { - preg_match('/^(.*?)(\((\d+?)\)(.*))?$/', $sType, $aMatches); + preg_match('/^(.*?)(\((.+?)\)(.*))?$/', $sType, $aMatches); - $sType = getFromArray(1, $aMatches, 'text'); - $iLength = getFromArray(3, $aMatches); + $sType = getFromArray(1, $aMatches, 'text'); + $sTypeConfig = trim(getFromArray(3, $aMatches)); + $iLength = is_numeric($sTypeConfig) ? (int) $sTypeConfig : null; switch ($sType) { @@ -1848,6 +1850,18 @@ abstract class Base break; /** + * ENUM + */ + case 'enum': + $oField->type = 'dropdown'; + $oField->class = 'select2'; + $aOptions = explode("','", substr($sTypeConfig, 1, -1)); + $aLabels = array_map('strtolower', $aOptions); + $aLabels = array_map([$this, 'describeFieldsPrepareLabel'], $aLabels); + $oField->options = array_combine($aOptions, $aLabels); + break; + + /** * Default to basic string */ default:
Added support for enums in describeFields()
nails_common
train
3bf38cbe4d8508a9a0e2ce0f753f1d15fcc1467b
diff --git a/lib/akashi/rds/subnet_group.rb b/lib/akashi/rds/subnet_group.rb index <HASH>..<HASH> 100644 --- a/lib/akashi/rds/subnet_group.rb +++ b/lib/akashi/rds/subnet_group.rb @@ -6,7 +6,7 @@ module Akashi response = Akashi::Aws.rds.client.create_db_subnet_group( db_subnet_group_name: Akashi.name, db_subnet_group_description: Akashi.name, - subnet_ids: subnets.map(&:id) + subnet_ids: Array.wrap(subnets).map(&:id) ) id = response[:db_subnet_group_name]
Use Array.wrap to an argument which expect Array
spice-life_akashi
train
2e86f58b83a622e4a4249fb52bd5a649392f8da6
diff --git a/web/concrete/core/controllers/blocks/form.php b/web/concrete/core/controllers/blocks/form.php index <HASH>..<HASH> 100644 --- a/web/concrete/core/controllers/blocks/form.php +++ b/web/concrete/core/controllers/blocks/form.php @@ -79,8 +79,19 @@ class Concrete5_Controller_Block_Form extends BlockController { } public function on_page_view() { - $this->addFooterItem(Loader::helper('html')->css('jquery.ui.css')); - $this->addFooterItem(Loader::helper('html')->javascript('jquery.ui.js')); + if ($this->viewRequiresJqueryUI()) { + $this->addHeaderItem(Loader::helper('html')->css('jquery.ui.css')); + $this->addFooterItem(Loader::helper('html')->javascript('jquery.ui.js')); + } + } + + //Internal helper function + private function viewRequiresJqueryUI() { + $whereInputTypes = "inputType = 'date' OR inputType = 'datetime'"; + $sql = "SELECT COUNT(*) FROM {$this->btQuestionsTablename} WHERE questionSetID = ? AND bID = ? AND ({$whereInputTypes})"; + $vals = array(intval($this->questionSetId), intval($this->bID)); + $JQUIFieldCount = Loader::db()->GetOne($sql, $vals); + return (bool)$JQUIFieldCount; } public function getDefaultThankYouMsg() {
don't output unnecessary jquery UI in form block Take 2 (see <URL>). Also outputs CSS to header (not footer) if needed. Former-commit-id: <I>f<I>ba0af<I>e5d<I>e<I>cf<I>a
concrete5_concrete5
train
e8b4a95c6b2e5a937e61c25b12d56c5d9a1c0c0d
diff --git a/face/geomajas-face-puregwt/client-impl/src/main/java/org/geomajas/puregwt/client/gfx/GfxUtilImpl.java b/face/geomajas-face-puregwt/client-impl/src/main/java/org/geomajas/puregwt/client/gfx/GfxUtilImpl.java index <HASH>..<HASH> 100644 --- a/face/geomajas-face-puregwt/client-impl/src/main/java/org/geomajas/puregwt/client/gfx/GfxUtilImpl.java +++ b/face/geomajas-face-puregwt/client-impl/src/main/java/org/geomajas/puregwt/client/gfx/GfxUtilImpl.java @@ -27,6 +27,7 @@ import com.google.gwt.event.dom.client.TouchEndEvent; import com.google.gwt.event.dom.client.TouchMoveEvent; import com.google.gwt.event.dom.client.TouchStartEvent; import com.google.gwt.event.shared.HandlerRegistration; +import com.google.gwt.user.client.DOM; import com.google.inject.Inject; /** @@ -56,6 +57,14 @@ public final class GfxUtilImpl implements GfxUtil { if (style.getStrokeWidth() >= 0) { shape.setStrokeWidth(style.getStrokeWidth()); } + if (style.getDashArray() != null) { + String strokeDashArrayHTMLFormat = style.getDashArray().trim(); + strokeDashArrayHTMLFormat = strokeDashArrayHTMLFormat.replaceAll("[ \t]+", ","); + if (!strokeDashArrayHTMLFormat.isEmpty()) { + DOM.setStyleAttribute(shape.getElement(), "strokeDasharray", strokeDashArrayHTMLFormat); + } + } + } public List<HandlerRegistration> applyController(Shape shape, MapController mapController) {
Fix PURE-<I> - Stroke Dash array property of a feature style is ignored
geomajas_geomajas-project-server
train
d091480f71d4514c1d96d701e0e87018279a0f31
diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/groupadministration/KickChatMember.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/groupadministration/KickChatMember.java index <HASH>..<HASH> 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/groupadministration/KickChatMember.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/groupadministration/KickChatMember.java @@ -1,5 +1,6 @@ package org.telegram.telegrambots.meta.api.methods.groupadministration; +import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.type.TypeReference; @@ -9,6 +10,9 @@ import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException; import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; import java.io.IOException; +import java.time.Duration; +import java.time.Instant; +import java.time.ZonedDateTime; import java.util.Objects; import static com.google.common.base.Preconditions.checkNotNull; @@ -81,11 +85,25 @@ public class KickChatMember extends BotApiMethod<Boolean> { return untilDate; } - public KickChatMember setUntilDate(Integer untilDate) { - this.untilDate = untilDate; + public KickChatMember setUntilDate(Integer untilDateInSeconds) { + this.untilDate = untilDateInSeconds; return this; } + @JsonIgnore + public KickChatMember setUntilDate(Instant instant) { + return setUntilDate((int) instant.getEpochSecond()); + } + + @JsonIgnore + public KickChatMember setUntilDate(ZonedDateTime date) { + return setUntilDate(date.toInstant()); + } + + public KickChatMember forTimePeriod(Duration duration) { + return setUntilDate(Instant.now().plusMillis(duration.toMillis())); + } + @Override public String getMethod() { return PATH; diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/groupadministration/RestrictChatMember.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/groupadministration/RestrictChatMember.java index <HASH>..<HASH> 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/groupadministration/RestrictChatMember.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/groupadministration/RestrictChatMember.java @@ -1,5 +1,6 @@ package org.telegram.telegrambots.meta.api.methods.groupadministration; +import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.type.TypeReference; import org.telegram.telegrambots.meta.api.methods.BotApiMethod; @@ -8,6 +9,9 @@ import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException; import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; import java.io.IOException; +import java.time.Duration; +import java.time.Instant; +import java.time.ZonedDateTime; import java.util.Objects; import static com.google.common.base.Preconditions.checkNotNull; @@ -89,11 +93,25 @@ public class RestrictChatMember extends BotApiMethod<Boolean> { return untilDate; } - public RestrictChatMember setUntilDate(Integer untilDate) { - this.untilDate = untilDate; + public RestrictChatMember setUntilDate(Integer untilDateInSeconds) { + this.untilDate = untilDateInSeconds; return this; } + @JsonIgnore + public RestrictChatMember setUntilDate(Instant instant) { + return setUntilDate((int) instant.getEpochSecond()); + } + + @JsonIgnore + public RestrictChatMember setUntilDate(ZonedDateTime date) { + return setUntilDate(date.toInstant()); + } + + public RestrictChatMember forTimePeriod(Duration duration) { + return setUntilDate(Instant.now().plusMillis(duration.toMillis())); + } + public Boolean getCanSendMessages() { return canSendMessages; } diff --git a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/ChatMember.java b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/ChatMember.java index <HASH>..<HASH> 100644 --- a/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/ChatMember.java +++ b/telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/objects/ChatMember.java @@ -4,6 +4,8 @@ import com.fasterxml.jackson.annotation.JsonProperty; import org.telegram.telegrambots.meta.api.interfaces.BotApiObject; +import java.time.Instant; + /** * @author Ruben Bermudez * @version 1.0 @@ -77,6 +79,13 @@ public class ChatMember implements BotApiObject { return untilDate; } + public Instant getUntilDateAsInstant() { + if (untilDate == null) { + return null; + } + return Instant.ofEpochSecond(untilDate); + } + public Boolean getCanBeEdited() { return canBeEdited; }
Ability to set time periods with Instant, Duration and ZonedDateTime
rubenlagus_TelegramBots
train
3bf6acf3368b0521a2378ddcb997d4851962dd73
diff --git a/pdf/api/config.py b/pdf/api/config.py index <HASH>..<HASH> 100644 --- a/pdf/api/config.py +++ b/pdf/api/config.py @@ -1,9 +1,8 @@ import os -from pdf.api._version import __version__ APP_NAME = 'pdfconduit' -VERSION = __version__ +VERSION = 1.0 UPLOAD_FOLDER = os.path.join(os.path.dirname(__file__), 'uploads') ALLOWED_EXTENSIONS = {'pdf'}
FIX api version declaration, broke link between api and PyPi versions
mrstephenneal_pdfconduit
train
59db26ee4fbf5e119163d4a18885437a537a9353
diff --git a/src/Route/Query/QueryRoute.php b/src/Route/Query/QueryRoute.php index <HASH>..<HASH> 100644 --- a/src/Route/Query/QueryRoute.php +++ b/src/Route/Query/QueryRoute.php @@ -85,7 +85,7 @@ class QueryRoute implements RouteInterface, StaticFactoryInterface throw new InvalidQueryString($parameter, $result); } - if (($this->parameters[$parameter] ?? null) !== ($parameters[$parameter] ?? null)) { + if (($this->getParameters()[$parameter] ?? null) !== ($parameters[$parameter] ?? null)) { $query[$parameter] = $parameters[$parameter]; } }
Replaced direct property access with getter.
extendsframework_extends-router
train
7dbb0174cdeba44858d56912dc974f48c0f22354
diff --git a/lib/unparser/cli.rb b/lib/unparser/cli.rb index <HASH>..<HASH> 100644 --- a/lib/unparser/cli.rb +++ b/lib/unparser/cli.rb @@ -149,11 +149,11 @@ module Unparser files = case when File.directory?(file_name) - Dir.glob(File.join(file_name, '**/*.rb')) + Dir.glob(File.join(file_name, '**/*.rb')).sort when File.file?(file_name) [file_name] else - Dir.glob(file_name) + Dir.glob(file_name).sort end files.map(&Source::File.method(:new)) diff --git a/lib/unparser/emitter/literal/primitive.rb b/lib/unparser/emitter/literal/primitive.rb index <HASH>..<HASH> 100644 --- a/lib/unparser/emitter/literal/primitive.rb +++ b/lib/unparser/emitter/literal/primitive.rb @@ -14,7 +14,7 @@ module Unparser # Emitter for primitives based on Object#inspect class Inspect < self - handle :float, :sym, :str + handle :sym, :str private @@ -30,9 +30,9 @@ module Unparser end # Inspect - class Int < self + class Numeric < self - handle :int + handle :int, :float private @@ -47,7 +47,8 @@ module Unparser write(value.inspect) end end - end + + end # Numeric # Literal emitter with macro regeneration base class class MacroSafe < self diff --git a/rubyspec.sh b/rubyspec.sh index <HASH>..<HASH> 100755 --- a/rubyspec.sh +++ b/rubyspec.sh @@ -1,10 +1,13 @@ #!/bin/sh -exec bundle exec bin/unparser ../rubyspec --fail-fast \ - --ignore '../rubyspec/core/array/pack/{b,h,u}_spec.rb' \ - --ignore '../rubyspec/language/versions/*1.8*' \ - --ignore '../rubyspec/core/array/pack/shared/float.rb' \ - --ignore '../rubyspec/core/array/pack/shared/integer.rb' \ - --ignore '../rubyspec/core/array/pack/{c,m,w}_spec.rb' \ - --ignore '../rubyspec/core/regexp/shared/new.rb' \ - --ignore '../rubyspec/core/regexp/shared/quote.rb' \ +exec bundle exec bin/unparser ../rubyspec --fail-fast \ + --ignore '../rubyspec/core/array/pack/{b,h,u}_spec.rb' \ + --ignore '../rubyspec/language/versions/*1.8*' \ + --ignore '../rubyspec/core/array/pack/shared/float.rb' \ + --ignore '../rubyspec/core/array/pack/shared/integer.rb' \ + --ignore '../rubyspec/core/array/pack/{c,m,w}_spec.rb' \ + --ignore '../rubyspec/core/regexp/shared/new.rb' \ + --ignore '../rubyspec/core/regexp/shared/quote.rb' \ + --ignore '../rubyspec/core/encoding/compatible_spec.rb' \ + --ignore '../rubyspec/core/io/readpartial_spec.rb' \ + --ignore '../rubyspec/core/env/element_reference_spec.rb' \ $* diff --git a/spec/unit/unparser_spec.rb b/spec/unit/unparser_spec.rb index <HASH>..<HASH> 100644 --- a/spec/unit/unparser_spec.rb +++ b/spec/unit/unparser_spec.rb @@ -1296,6 +1296,7 @@ describe Unparser do context 'binary operator methods' do %w(+ - * / & | << >> == === != <= < <=> > >= =~ !~ ^ **).each do |operator| assert_source "(-1) #{operator} 2" + assert_source "(-1.2) #{operator} 2" assert_source "left.#{operator}(*foo)" assert_source "left.#{operator}(a, b)" assert_source "self #{operator} b"
Emit negative float correctly in binary operator method
mbj_unparser
train
df0170ec87fa621f236c2a490c39d8006b7aa2d4
diff --git a/core/src/main/java/hudson/tasks/MailSender.java b/core/src/main/java/hudson/tasks/MailSender.java index <HASH>..<HASH> 100644 --- a/core/src/main/java/hudson/tasks/MailSender.java +++ b/core/src/main/java/hudson/tasks/MailSender.java @@ -90,7 +90,7 @@ public class MailSender { Address[] allRecipients = mail.getAllRecipients(); if (allRecipients != null) { - StringBuffer buf = new StringBuffer("Sending e-mails to:"); + StringBuilder buf = new StringBuilder("Sending e-mails to:"); for (Address a : allRecipients) buf.append(' ').append(a); listener.getLogger().println(buf); @@ -156,7 +156,7 @@ public class MailSender { MimeMessage msg = createEmptyMail(build, listener); msg.setSubject(getSubject(build, "Hudson build is back to " + subject + ": "),MAIL_CHARSET); - StringBuffer buf = new StringBuffer(); + StringBuilder buf = new StringBuilder(); appendBuildUrl(build, buf); msg.setText(buf.toString(),MAIL_CHARSET); @@ -169,29 +169,37 @@ public class MailSender { String subject = "Hudson build is unstable: "; AbstractBuild<?, ?> prev = build.getPreviousBuild(); + boolean still = false; if(prev!=null) { if(prev.getResult()==Result.SUCCESS) subject = "Hudson build became unstable: "; - if(prev.getResult()==Result.UNSTABLE) + else if(prev.getResult()==Result.UNSTABLE) { subject = "Hudson build is still unstable: "; + still = true; + } } msg.setSubject(getSubject(build, subject),MAIL_CHARSET); - StringBuffer buf = new StringBuffer(); - appendBuildUrl(build, buf); + StringBuilder buf = new StringBuilder(); + // Link to project changes summary for "still unstable" if this or last build has changes + if (still && !(build.getChangeSet().isEmptySet() && prev.getChangeSet().isEmptySet())) + appendUrl(Util.encode(build.getProject().getUrl()) + "changes", buf); + else + appendBuildUrl(build, buf); msg.setText(buf.toString(), MAIL_CHARSET); return msg; } - private void appendBuildUrl(AbstractBuild<?, ?> build, StringBuffer buf) { + private void appendBuildUrl(AbstractBuild<?, ?> build, StringBuilder buf) { + appendUrl(Util.encode(build.getUrl()) + + (build.getChangeSet().isEmptySet() ? "" : "changes"), buf); + } + + private void appendUrl(String url, StringBuilder buf) { String baseUrl = Mailer.descriptor().getUrl(); - if (baseUrl != null) { - buf.append("See <").append(baseUrl).append(Util.encode(build.getUrl())); - if(!build.getChangeSet().isEmptySet()) - buf.append("changes"); - buf.append(">\n\n"); - } + if (baseUrl != null) + buf.append("See <").append(baseUrl).append(url).append(">\n\n"); } private MimeMessage createFailureMail(AbstractBuild<?, ?> build, BuildListener listener) throws MessagingException, InterruptedException { @@ -199,7 +207,7 @@ public class MailSender { msg.setSubject(getSubject(build, "Build failed in Hudson: "),MAIL_CHARSET); - StringBuffer buf = new StringBuffer(); + StringBuilder buf = new StringBuilder(); appendBuildUrl(build, buf); boolean firstChange = true;
[FIXED HUDSON-<I>] Link to project changes summary instead of this build's changes for "still unstable" email. Also changed StringBuffers to StringBuilders. git-svn-id: <URL>
jenkinsci_jenkins
train
034844ddc9a450f51d7da99d17fba82e595b7339
diff --git a/src/main/java/hex/rf/Confusion.java b/src/main/java/hex/rf/Confusion.java index <HASH>..<HASH> 100644 --- a/src/main/java/hex/rf/Confusion.java +++ b/src/main/java/hex/rf/Confusion.java @@ -124,7 +124,7 @@ public class Confusion extends MRTask { _data = ValueArray.value(DKV.get(_datakey)); _model = UKV.get(_modelKey, new RFModel()); _modelDataMap = _model.columnMapping(_data.colNames()); - assert !_computeOOB || _model._dataKey==_datakey ; + assert !_computeOOB || _model._dataKey==_datakey : _computeOOB + " || " + _model._dataKey + " == " + _datakey ; Column c = _data._cols[_classcol]; _N = (int)((c._max - c._min)+1); assert _N > 0;
Assertion refined (for EC2 testing)
h2oai_h2o-2
train
b1dbd1cab64d0f18146026e49769f0dec073258a
diff --git a/superset/assets/src/SqlLab/components/QueryAutoRefresh.jsx b/superset/assets/src/SqlLab/components/QueryAutoRefresh.jsx index <HASH>..<HASH> 100644 --- a/superset/assets/src/SqlLab/components/QueryAutoRefresh.jsx +++ b/superset/assets/src/SqlLab/components/QueryAutoRefresh.jsx @@ -26,7 +26,7 @@ class QueryAutoRefresh extends React.PureComponent { return ( queriesLastUpdate > 0 && Object.values(queries).some( - q => ['running', 'started', 'pending', 'fetching', 'rendering'].indexOf(q.state) >= 0 && + q => ['running', 'started', 'pending', 'fetching'].indexOf(q.state) >= 0 && now - q.startDttm < MAX_QUERY_AGE_TO_POLL, ) ); diff --git a/superset/assets/src/SqlLab/constants.js b/superset/assets/src/SqlLab/constants.js index <HASH>..<HASH> 100644 --- a/superset/assets/src/SqlLab/constants.js +++ b/superset/assets/src/SqlLab/constants.js @@ -5,7 +5,6 @@ export const STATE_BSSTYLE_MAP = { fetching: 'info', running: 'warning', stopped: 'danger', - rendering: 'info', success: 'success', }; diff --git a/superset/assets/src/SqlLab/reducers/sqlLab.js b/superset/assets/src/SqlLab/reducers/sqlLab.js index <HASH>..<HASH> 100644 --- a/superset/assets/src/SqlLab/reducers/sqlLab.js +++ b/superset/assets/src/SqlLab/reducers/sqlLab.js @@ -164,7 +164,7 @@ export default function sqlLabReducer(state = {}, action) { progress: 100, results: action.results, rows, - state: 'rendering', + state: 'success', errorMessage: null, cached: false, };
[bugfix] show results in query history & revert #<I> (#<I>) * revert <I> * nit
apache_incubator-superset
train
4574473753d0f56d54ea91ecaff91548536d9402
diff --git a/pkg/controller/volume/attachdetach/attach_detach_controller.go b/pkg/controller/volume/attachdetach/attach_detach_controller.go index <HASH>..<HASH> 100644 --- a/pkg/controller/volume/attachdetach/attach_detach_controller.go +++ b/pkg/controller/volume/attachdetach/attach_detach_controller.go @@ -24,7 +24,7 @@ import ( "time" authenticationv1 "k8s.io/api/authentication/v1" - "k8s.io/api/core/v1" + v1 "k8s.io/api/core/v1" apierrors "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/labels" "k8s.io/apimachinery/pkg/types" @@ -779,7 +779,7 @@ func (adc *attachDetachController) DeleteServiceAccountTokenFunc() func(types.UI } func (adc *attachDetachController) GetExec(pluginName string) mount.Exec { - return mount.NewOsExec() + return mount.NewOSExec() } func (adc *attachDetachController) addNodeToDswp(node *v1.Node, nodeName types.NodeName) { diff --git a/pkg/controller/volume/expand/expand_controller.go b/pkg/controller/volume/expand/expand_controller.go index <HASH>..<HASH> 100644 --- a/pkg/controller/volume/expand/expand_controller.go +++ b/pkg/controller/volume/expand/expand_controller.go @@ -24,7 +24,7 @@ import ( "k8s.io/klog" authenticationv1 "k8s.io/api/authentication/v1" - "k8s.io/api/core/v1" + v1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/types" "k8s.io/apimachinery/pkg/util/runtime" @@ -374,7 +374,7 @@ func (expc *expandController) GetMounter(pluginName string) mount.Interface { } func (expc *expandController) GetExec(pluginName string) mount.Exec { - return mount.NewOsExec() + return mount.NewOSExec() } func (expc *expandController) GetHostName() string { diff --git a/pkg/controller/volume/persistentvolume/volume_host.go b/pkg/controller/volume/persistentvolume/volume_host.go index <HASH>..<HASH> 100644 --- a/pkg/controller/volume/persistentvolume/volume_host.go +++ b/pkg/controller/volume/persistentvolume/volume_host.go @@ -21,7 +21,7 @@ import ( "net" authenticationv1 "k8s.io/api/authentication/v1" - "k8s.io/api/core/v1" + v1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/types" clientset "k8s.io/client-go/kubernetes" "k8s.io/client-go/tools/record" @@ -117,7 +117,7 @@ func (ctrl *PersistentVolumeController) DeleteServiceAccountTokenFunc() func(typ } func (adc *PersistentVolumeController) GetExec(pluginName string) mount.Exec { - return mount.NewOsExec() + return mount.NewOSExec() } func (ctrl *PersistentVolumeController) GetNodeLabels() (map[string]string, error) { diff --git a/pkg/kubelet/volume_host.go b/pkg/kubelet/volume_host.go index <HASH>..<HASH> 100644 --- a/pkg/kubelet/volume_host.go +++ b/pkg/kubelet/volume_host.go @@ -24,7 +24,7 @@ import ( "k8s.io/klog" authenticationv1 "k8s.io/api/authentication/v1" - "k8s.io/api/core/v1" + v1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/types" "k8s.io/apimachinery/pkg/util/wait" utilfeature "k8s.io/apiserver/pkg/util/feature" @@ -294,7 +294,7 @@ func (kvh *kubeletVolumeHost) GetExec(pluginName string) mount.Exec { exec = nil } if exec == nil { - return mount.NewOsExec() + return mount.NewOSExec() } return exec } diff --git a/pkg/util/mount/exec.go b/pkg/util/mount/exec.go index <HASH>..<HASH> 100644 --- a/pkg/util/mount/exec.go +++ b/pkg/util/mount/exec.go @@ -18,8 +18,8 @@ package mount import "k8s.io/utils/exec" -// NewOsExec returns a new Exec interface implementation based on exec() -func NewOsExec() Exec { +// NewOSExec returns a new Exec interface implementation based on exec() +func NewOSExec() Exec { return &osExec{} } diff --git a/pkg/volume/azure_dd/azure_common_test.go b/pkg/volume/azure_dd/azure_common_test.go index <HASH>..<HASH> 100644 --- a/pkg/volume/azure_dd/azure_common_test.go +++ b/pkg/volume/azure_dd/azure_common_test.go @@ -125,7 +125,7 @@ func TestIoHandler(t *testing.T) { if runtime.GOOS != "windows" && runtime.GOOS != "linux" { t.Skipf("TestIoHandler not supported on GOOS=%s", runtime.GOOS) } - disk, err := findDiskByLun(lun, &fakeIOHandler{}, mount.NewOsExec()) + disk, err := findDiskByLun(lun, &fakeIOHandler{}, mount.NewOSExec()) if runtime.GOOS == "windows" { if err != nil { t.Errorf("no data disk found: disk %v err %v", disk, err)
Rename mount.NewOsExec to mount.NewOSExec
kubernetes_kubernetes
train
fff875dd8a27e434fd36c620d874e9a9ac06a9b0
diff --git a/lib/preset-patterns.js b/lib/preset-patterns.js index <HASH>..<HASH> 100644 --- a/lib/preset-patterns.js +++ b/lib/preset-patterns.js @@ -18,10 +18,10 @@ module.exports = { */ function suitSelector(componentName, presetOptions) { var ns = (presetOptions && presetOptions.namespace) ? presetOptions.namespace + '-' : ''; - var OPTIONAL_PART = '(?:-[a-z][a-zA-Z0-9]+)?'; - var OPTIONAL_MODIFIER = '(?:--[a-z][a-zA-Z0-9]+)?'; + var OPTIONAL_PART = '(?:-[a-z][a-zA-Z0-9]*)?'; + var OPTIONAL_MODIFIER = '(?:--[a-z][a-zA-Z0-9]*)?'; var OPTIONAL_ATTRIBUTE = '(?:\\[\\S+\\])?'; - var OPTIONAL_STATE = '(?:\\.is-[a-z][a-zA-Z0-9]+)?'; + var OPTIONAL_STATE = '(?:\\.is-[a-z][a-zA-Z0-9]*)?'; var OPTIONAL = OPTIONAL_PART + OPTIONAL_MODIFIER + OPTIONAL_ATTRIBUTE +
Allow single char in component selectors `.Component-a`
postcss_postcss-bem-linter
train
fbec43f79e116a54fe537b3da08e9739c562f4b0
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -30,6 +30,10 @@ setup(name=PACKAGE_NAME, 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: Implementation :: CPython'], + dependency_links=[ + ('https://github.com/bboe/betamax_matchers/tarball/json_body_short_' + 'circuit_pass#egg=betamax_matchers-0.3.0') + ], description='Low-level communication layer for PRAW 4+.', install_requires=['requests >=2.9.1, <3.0'], keywords='praw reddit api',
Depend on development version of betamax_matchers.
praw-dev_prawcore
train
ec87cb0b0fd4812f2429bdeee1559d64952d9606
diff --git a/functions/scripts.php b/functions/scripts.php index <HASH>..<HASH> 100644 --- a/functions/scripts.php +++ b/functions/scripts.php @@ -13,10 +13,10 @@ */ /* Register Hybrid Core scripts. */ -add_action( 'wp_enqueue_scripts', 'hybrid_register_scripts', 1 ); +add_action( 'wp_enqueue_scripts', 'hybrid_register_scripts', 0 ); /* Load Hybrid Core scripts. */ -add_action( 'wp_enqueue_scripts', 'hybrid_enqueue_scripts' ); +add_action( 'wp_enqueue_scripts', 'hybrid_enqueue_scripts', 5 ); /** * Registers JavaScript files for the framework. This function merely registers scripts with WordPress using diff --git a/functions/styles.php b/functions/styles.php index <HASH>..<HASH> 100644 --- a/functions/styles.php +++ b/functions/styles.php @@ -13,16 +13,16 @@ */ /* Register Hybrid Core styles. */ -add_action( 'wp_enqueue_scripts', 'hybrid_register_styles', 1 ); +add_action( 'wp_enqueue_scripts', 'hybrid_register_styles', 0 ); /* Load Hybrid Core styles. */ add_action( 'wp_enqueue_scripts', 'hybrid_enqueue_styles', 5 ); /* Load the development stylsheet in script debug mode. */ -add_filter( 'stylesheet_uri', 'hybrid_min_stylesheet_uri', 10, 2 ); +add_filter( 'stylesheet_uri', 'hybrid_min_stylesheet_uri', 5, 2 ); /* Filters the WP locale stylesheet. */ -add_filter( 'locale_stylesheet_uri', 'hybrid_locale_stylesheet_uri' ); +add_filter( 'locale_stylesheet_uri', 'hybrid_locale_stylesheet_uri', 5 ); /** * Registers stylesheets for the framework. This function merely registers styles with WordPress using
Minor alterations to the scripts/styles filters.
justintadlock_hybrid-core
train
f9d6de8e46b9f9121e97242196a090767e4d91a4
diff --git a/lib/clever-ruby.rb b/lib/clever-ruby.rb index <HASH>..<HASH> 100644 --- a/lib/clever-ruby.rb +++ b/lib/clever-ruby.rb @@ -3,6 +3,8 @@ require 'rest_client' require 'multi_json' require 'open-uri' require 'set' +require 'uri' +require 'cgi' require 'clever-ruby/version' @@ -72,7 +74,9 @@ module Clever def self.create_payload(method, url, params) case method.to_s.downcase.to_sym when :get, :head, :delete - url += convert_to_query_string params + url_parsed = URI.parse url + params = CGI.parse(url_parsed.query).merge params unless url_parsed.query.nil? + url = url.split('?')[0] + convert_to_query_string(params) payload = nil else payload = params
allow urls with query params to work in Clever.request
Clever_clever-ruby
train
ec870c8a3bb4c420132dc4a8dec1cf6ad1dae968
diff --git a/connection/connection.js b/connection/connection.js index <HASH>..<HASH> 100644 --- a/connection/connection.js +++ b/connection/connection.js @@ -23,6 +23,7 @@ var connections = {}; * @class * @param {string} options.host The server host * @param {number} options.port The server port + * @param {number} options.family Version of IP stack. Defaults to 4. * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled * @param {number} [options.keepAliveInitialDelay=0] Initial delay before TCP keep alive enabled * @param {boolean} [options.noDelay=true] TCP Connection no delay @@ -73,6 +74,7 @@ var Connection = function(messageHandler, options) { // Default options this.port = options.port || 27017; this.host = options.host || 'localhost'; + this.family = typeof options.family == 'number' ? options.family : 4; this.keepAlive = typeof options.keepAlive == 'boolean' ? options.keepAlive : true; this.keepAliveInitialDelay = options.keepAliveInitialDelay || 0; this.noDelay = typeof options.noDelay == 'boolean' ? options.noDelay : true; @@ -396,9 +398,10 @@ Connection.prototype.connect = function(_options) { } // Create new connection instance - self.connection = self.domainSocket - ? net.createConnection(self.host) - : net.createConnection(self.port, self.host); + var connection_options = self.domainSocket + ? {path: self.host} + : {port: self.port, host: self.host, family: self.family}; + self.connection = net.createConnection(connection_options); // Set the options for the connection self.connection.setKeepAlive(self.keepAlive, self.keepAliveInitialDelay);
'family' was added to socket options to provide high priority for ipv6 addresses
mongodb_node-mongodb-native
train
1e5220bdb36554a0f01ad46f6042ab6598cd9580
diff --git a/addons/docs/src/frameworks/web-components/config.js b/addons/docs/src/frameworks/web-components/config.js index <HASH>..<HASH> 100644 --- a/addons/docs/src/frameworks/web-components/config.js +++ b/addons/docs/src/frameworks/web-components/config.js @@ -32,7 +32,7 @@ addParameters({ sections.attributes = mapData(metaData.attributes); } if (metaData.properties) { - sections.props = mapData(metaData.properties); + sections.properties = mapData(metaData.properties); } if (metaData.events) { sections.events = mapData(metaData.events);
[Addon-docs][Web Components] Update 'props' to 'properties' Update 'props' section title to 'properties'
storybooks_storybook
train
b6b1dccf27f522f45abbc6f1ad91f3f6cac88d9e
diff --git a/rio/blueprints/event/views.py b/rio/blueprints/event/views.py index <HASH>..<HASH> 100644 --- a/rio/blueprints/event/views.py +++ b/rio/blueprints/event/views.py @@ -70,7 +70,14 @@ def emit_event(project_slug, action_slug): # execute event event = {'uuid': uuid4(), 'project': project['slug'], 'action': action['slug']} - payload = request.values.to_dict() + + if request.headers.get('Content-Type') == 'application/json': + payload = request.get_json() + elif request.method == 'POST': + payload = request.form.to_dict() + else: + payload = request.args.to_dict() + res = exec_event(event, action['webhooks'], payload) # response
accept json payload for emit
soasme_rio
train
f2b81e27d1fef92975eec31ff5beb927e9fb3151
diff --git a/lib/rfunk/maybe/none.rb b/lib/rfunk/maybe/none.rb index <HASH>..<HASH> 100644 --- a/lib/rfunk/maybe/none.rb +++ b/lib/rfunk/maybe/none.rb @@ -26,6 +26,10 @@ module RFunk [] end + def to_hash + {} + end + protected def enum diff --git a/lib/rfunk/maybe/some.rb b/lib/rfunk/maybe/some.rb index <HASH>..<HASH> 100644 --- a/lib/rfunk/maybe/some.rb +++ b/lib/rfunk/maybe/some.rb @@ -40,6 +40,10 @@ module RFunk value end + def to_hash + value + end + def_delegators :@value, :to_s, :inspect, :respond_to? protected diff --git a/spec/rfunk/maybe/coerce_spec.rb b/spec/rfunk/maybe/coerce_spec.rb index <HASH>..<HASH> 100644 --- a/spec/rfunk/maybe/coerce_spec.rb +++ b/spec/rfunk/maybe/coerce_spec.rb @@ -21,6 +21,11 @@ describe 'Coerce' do When(:result) { Option(['a']) + Option(['b']) } Then { result == Some(%w(a b)) } end + + context 'Hash' do + When(:result) { Option({ a: 1 }).merge(Option({ b: 1 })) } + Then { result == Some({ a: 1, b: 1 }) } + end end context 'None' do @@ -43,5 +48,10 @@ describe 'Coerce' do When(:result) { Option(['a']) + None() } Then { result == Some(%w(a)) } end + + context 'Hash' do + When(:result) { Option({ a: 1 }).merge(None()) } + Then { result == Some({ a: 1 }) } + end end end
Added Hash support for coerce.
alexfalkowski_rfunk
train
4fa59c2fd882a6cf33635a4f11f311c17c5a382b
diff --git a/gridfs/__init__.py b/gridfs/__init__.py index <HASH>..<HASH> 100644 --- a/gridfs/__init__.py +++ b/gridfs/__init__.py @@ -54,8 +54,10 @@ class GridFS(object): self.__collection = database[collection] self.__files = self.__collection.files self.__chunks = self.__collection.chunks - self.__chunks.ensure_index([("files_id", ASCENDING), ("n", ASCENDING)], - unique=True) + if not database.slave_okay and not database.read_preference: + self.__chunks.ensure_index([("files_id", ASCENDING), + ("n", ASCENDING)], + unique=True) def new_file(self, **kwargs): """Create a new file in GridFS. @@ -166,8 +168,10 @@ class GridFS(object): Accept keyword arguments to find files by custom metadata. .. versionadded:: 1.9 """ - self.__files.ensure_index([("filename", ASCENDING), - ("uploadDate", DESCENDING)]) + database = self.__database + if not database.slave_okay and not database.read_preference: + self.__files.ensure_index([("filename", ASCENDING), + ("uploadDate", DESCENDING)]) query = kwargs if filename is not None:
Query GridFS from a secondary/slave PYTHON-<I>
mongodb_mongo-python-driver
train
13cc0c80518364f04b2e185fafbea0f2b97c7a02
diff --git a/src/AbstractValidator.php b/src/AbstractValidator.php index <HASH>..<HASH> 100644 --- a/src/AbstractValidator.php +++ b/src/AbstractValidator.php @@ -18,7 +18,7 @@ namespace Inpsyde\Validator; * @author Christian Brรผckner <[email protected]> * @package inpsyde-validator * @license http://opensource.org/licenses/MIT MIT - * @deprecated + * @deprecated Implement ErrorAwareValidatorInterface for custom validators */ abstract class AbstractValidator implements ValidatorInterface { @@ -48,6 +48,7 @@ abstract class AbstractValidator implements ValidatorInterface { * @param array $message_templates * * @return \Inpsyde\Validator\AbstractValidator + * @deprecated */ public function __construct( array $options = [ ], array $message_templates = [ ] ) { @@ -62,6 +63,7 @@ abstract class AbstractValidator implements ValidatorInterface { /** * {@inheritdoc} + * @deprecated */ public function get_error_messages() { @@ -72,6 +74,7 @@ abstract class AbstractValidator implements ValidatorInterface { * Returns the stored messages templates. * * @return array + * @deprecated */ public function get_message_templates() { @@ -84,6 +87,8 @@ abstract class AbstractValidator implements ValidatorInterface { * @param String $name * * @return String $template + * + * @deprecated */ public function get_message_template( $name ) { @@ -98,6 +103,8 @@ abstract class AbstractValidator implements ValidatorInterface { * Returns the stored options. * * @return array + * + * @deprecated */ public function get_options() { @@ -110,6 +117,8 @@ abstract class AbstractValidator implements ValidatorInterface { * @param mixed $value * * @return ValidatorInterface + * + * @deprecated */ protected function set_error_message( $message_name, $value ) { @@ -125,6 +134,8 @@ abstract class AbstractValidator implements ValidatorInterface { * @param String $value * * @return Null|String + * + * @deprecated */ protected function create_error_message( $message_name, $value ) { @@ -152,6 +163,8 @@ abstract class AbstractValidator implements ValidatorInterface { * @param mixed $value * * @return string $type + * + * @deprecated */ protected function get_value_as_string( $value ) {
Mark AbstractValidator as deprecated
inpsyde_inpsyde-validator
train
68f0c12c95b9014164bd38cdf07b9b05526f1396
diff --git a/src/Codeception/Module/MongoDb.php b/src/Codeception/Module/MongoDb.php index <HASH>..<HASH> 100644 --- a/src/Codeception/Module/MongoDb.php +++ b/src/Codeception/Module/MongoDb.php @@ -310,12 +310,12 @@ class MongoDb extends CodeceptionModule implements RequiresPackage * * ``` php * <?php - * $cursor = $I->grabFromCollection('users', array('name' => 'miles')); + * $user = $I->grabFromCollection('users', array('name' => 'miles')); * ``` * * @param $collection * @param array $criteria - * @return \MongoCursor + * @return array */ public function grabFromCollection($collection, $criteria = []) {
[MongoDb] Updated documentation of grabFromCollection (#<I>)
Codeception_Codeception
train
1c66391492f4e44da85b7ae838308f16c174f378
diff --git a/src/main/java/com/github/theholywaffle/lolchatapi/wrapper/Friend.java b/src/main/java/com/github/theholywaffle/lolchatapi/wrapper/Friend.java index <HASH>..<HASH> 100644 --- a/src/main/java/com/github/theholywaffle/lolchatapi/wrapper/Friend.java +++ b/src/main/java/com/github/theholywaffle/lolchatapi/wrapper/Friend.java @@ -177,8 +177,22 @@ public class Friend extends Wrapper<RosterEntry> { * @return The name of this Friend or null if no name is assigned. */ public String getName() { + return getName(false); + } + + /** + * Gets the name of this friend. If the name was null then we try to fetch + * the name with your Riot API Key if provided. Enable forcedUpdate to + * always fetch the latest name of this Friend even when the name is not + * null. + * + * @param forcedUpdate + * True will force to update the name even when it is not null. + * @return The name of this Friend or null if no name is assigned. + */ + public String getName(boolean forcedUpdate) { String name = get().getName(); - if (name == null && api.getRiotApi() != null) { + if ((name == null || forcedUpdate) && api.getRiotApi() != null) { try { name = api.getRiotApi().getName(getUserId()); setName(name);
Added method to force update name of Friend
TheHolyWaffle_League-of-Legends-XMPP-Chat-Library
train
64ccda5024043bec5b13f0062c5186863605271c
diff --git a/lib/connect-mongo.js b/lib/connect-mongo.js index <HASH>..<HASH> 100644 --- a/lib/connect-mongo.js +++ b/lib/connect-mongo.js @@ -129,9 +129,10 @@ module.exports = function(connect) { if (err) { throw new Error('Error setting TTL index on collection : ' + self.db_collection_name); } + + callback && callback(self.collection); }); - callback && callback(self.collection); } }); }
Only return collection after ensuring the TTL index
jdesboeufs_connect-mongo
train
f0442887d0d250a558bc381fe77adc6424d22f21
diff --git a/lettuce/plugins/smtp_mail_queue.py b/lettuce/plugins/smtp_mail_queue.py index <HASH>..<HASH> 100644 --- a/lettuce/plugins/smtp_mail_queue.py +++ b/lettuce/plugins/smtp_mail_queue.py @@ -6,7 +6,6 @@ from email import message_from_string from smtpd import SMTPServer -from django.core.mail import EmailMessage, EmailMultiAlternatives from lettuce import after, before @@ -37,6 +36,9 @@ def _get_content(msg): def _convert_to_django_msg(msg): + + from django.core.mail import EmailMessage, EmailMultiAlternatives + body, alternatives = _get_content(msg) if alternatives: email = EmailMultiAlternatives(body=body,
Import django modules only if they are used. This commit solves the issue #<I>.
aloetesting_aloe_django
train
d14ce9347e564f589048dd95eafdf80f691f8721
diff --git a/backend.py b/backend.py index <HASH>..<HASH> 100644 --- a/backend.py +++ b/backend.py @@ -342,6 +342,10 @@ class LDAPObject(object): debug("attribute cache is empty") debug("attribute modify:", (mod_op, mod_type, mod_vals)) + if mod_vals is not None: + if not isinstance(mod_vals, list): + mod_vals = [ mod_vals ] + if mod_op == ldap.MOD_ADD: # reverse of MOD_ADD is MOD_DELETE reverse = (ldap.MOD_DELETE,mod_type,mod_vals) @@ -349,25 +353,29 @@ class LDAPObject(object): # also carry out simulation in cache if mod_type not in result: result[mod_type] = [] - if isinstance(mod_vals, list): - for val in mod_vals: - result[mod_type].append(val) - else: - result[mod_type].append(mod_vals) + + for val in mod_vals: + if val in result[mod_type]: + raise ldap.TYPE_OR_VALUE_EXISTS("%s value %s already exists"%(mod_type,val)) + result[mod_type].append(val) + elif mod_op == ldap.MOD_DELETE and mod_vals is not None: # Reverse of MOD_DELETE is MOD_ADD, but only if value is given # if mod_vals is None, this means all values where deleted. reverse = (ldap.MOD_ADD,mod_type,mod_vals) # also carry out simulation in cache - if mod_type in result: - if isinstance(mod_vals, list): - for val in mod_vals: - result[mod_type].remove(val) - else: - result[mod_type].remove(mod_vals) - if len(result[mod_type]) == 0: - del result[mod_type] + if mod_type not in result: + raise ldap.NO_SUCH_ATTRIBUTE("%s value doesn't exist"%mod_type) + + for val in mod_vals: + if val not in result[mod_type]: + raise ldap.NO_SUCH_ATTRIBUTE("%s value %s doesn't exist"%(mod_type,val)) + result[mod_type].remove(val) + + if len(result[mod_type]) == 0: + del result[mod_type] + elif mod_op == ldap.MOD_DELETE or mod_op == ldap.MOD_REPLACE: if mod_type in result: # If MOD_DELETE with no values or MOD_REPLACE then we
Simplify code and ensure tests pass. Correctly generates errors modifying attributes.
Karaage-Cluster_python-tldap
train
0e883457d7ba7f9b61df024f0c8368924fb6897b
diff --git a/Resources/public/js/uamdatatables.js b/Resources/public/js/uamdatatables.js index <HASH>..<HASH> 100644 --- a/Resources/public/js/uamdatatables.js +++ b/Resources/public/js/uamdatatables.js @@ -73,5 +73,5 @@ } ( window.jQuery ); $( document ).ready(function() { - $( ".uamdatatables" ).uamdatatables( uamdatatables ); + $( ".uamdatatables" ).uamdatatables( "undefined" === typeof uamdatatables ? {} : uamdatatables ); });
fixed script loading on page if uamdatatables var is not defined
opichon_UAMDatatablesBundle
train
a6005e22c0fe346659da3dfa0979108891bf02bd
diff --git a/colly.go b/colly.go index <HASH>..<HASH> 100644 --- a/colly.go +++ b/colly.go @@ -65,6 +65,10 @@ type Collector struct { // Async turns on asynchronous network communication. Use Collector.Wait() to // be sure all requests have been finished. Async bool + // ParseHTTPErrorResponse allows parsing HTTP responses with non 2xx status codes. + // By default, Colly parses only successful HTTP responses. Set ParseHTTPErrorResponse + // to true to enable it. + ParseHTTPErrorResponse bool // ID is the unique identifier of a collector ID uint32 // DetectCharset can enable character encoding detection for non-utf8 response bodies @@ -173,6 +177,13 @@ func AllowedDomains(domains ...string) func(*Collector) { } } +// ParseHTTPErrorResponse allows parsing responses with HTTP errors +func ParseHTTPErrorResponse() func(*Collector) { + return func(c *Collector) { + c.ParseHTTPErrorResponse = true + } +} + // DisallowedDomains sets the domain blacklist used by the Collector. func DisallowedDomains(domains ...string) func(*Collector) { return func(c *Collector) { @@ -795,7 +806,7 @@ func (c *Collector) handleOnXML(resp *Response) { } func (c *Collector) handleOnError(response *Response, err error, request *Request, ctx *Context) error { - if err == nil && response.StatusCode < 203 { + if err == nil && (c.ParseHTTPErrorResponse || response.StatusCode < 203) { return nil } if err == nil { @@ -873,26 +884,27 @@ func (c *Collector) Cookies(URL string) []*http.Cookie { // between collectors. func (c *Collector) Clone() *Collector { return &Collector{ - AllowedDomains: c.AllowedDomains, - CacheDir: c.CacheDir, - DisallowedDomains: c.DisallowedDomains, - ID: atomic.AddUint32(&collectorCounter, 1), - IgnoreRobotsTxt: c.IgnoreRobotsTxt, - MaxBodySize: c.MaxBodySize, - MaxDepth: c.MaxDepth, - URLFilters: c.URLFilters, - UserAgent: c.UserAgent, - store: c.store, - backend: c.backend, - debugger: c.debugger, - Async: c.Async, - errorCallbacks: make([]ErrorCallback, 0, 8), - htmlCallbacks: make([]*htmlCallbackContainer, 0, 8), - lock: c.lock, - requestCallbacks: make([]RequestCallback, 0, 8), - responseCallbacks: make([]ResponseCallback, 0, 8), - robotsMap: c.robotsMap, - wg: c.wg, + AllowedDomains: c.AllowedDomains, + CacheDir: c.CacheDir, + DisallowedDomains: c.DisallowedDomains, + ID: atomic.AddUint32(&collectorCounter, 1), + IgnoreRobotsTxt: c.IgnoreRobotsTxt, + MaxBodySize: c.MaxBodySize, + MaxDepth: c.MaxDepth, + URLFilters: c.URLFilters, + ParseHTTPErrorResponse: c.ParseHTTPErrorResponse, + UserAgent: c.UserAgent, + store: c.store, + backend: c.backend, + debugger: c.debugger, + Async: c.Async, + errorCallbacks: make([]ErrorCallback, 0, 8), + htmlCallbacks: make([]*htmlCallbackContainer, 0, 8), + lock: c.lock, + requestCallbacks: make([]RequestCallback, 0, 8), + responseCallbacks: make([]ResponseCallback, 0, 8), + robotsMap: c.robotsMap, + wg: c.wg, } } diff --git a/colly_test.go b/colly_test.go index <HASH>..<HASH> 100644 --- a/colly_test.go +++ b/colly_test.go @@ -94,6 +94,12 @@ func newTestServer() *httptest.Server { w.Write([]byte("ok")) }) + mux.HandleFunc("/500", func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Conent-Type", "text/html") + w.WriteHeader(500) + w.Write([]byte("<p>error</p>")) + }) + return httptest.NewServer(mux) } @@ -486,6 +492,37 @@ func TestIgnoreRobotsWhenDisallowed(t *testing.T) { } +func TestParseHTTPErrorResponse(t *testing.T) { + contentCount := 0 + ts := newTestServer() + defer ts.Close() + + c := NewCollector( + AllowURLRevisit(), + ) + + c.OnHTML("p", func(e *HTMLElement) { + if e.Text == "error" { + contentCount++ + } + }) + + c.Visit(ts.URL + "/500") + + if contentCount != 0 { + t.Fatal("Content is parsed without ParseHTTPErrorResponse enabled") + } + + c.ParseHTTPErrorResponse = true + + c.Visit(ts.URL + "/500") + + if contentCount != 1 { + t.Fatal("Content isn't parsed with ParseHTTPErrorResponse enabled") + } + +} + func TestHTMLElement(t *testing.T) { ctx := &Context{} resp := &Response{
[enh] add option to allow parsing errored responses closes #<I>
gocolly_colly
train
1d476121c79bdbc75bcf0b64ccac878c2bbd53cd
diff --git a/src/Probability/Distribution/Multivariate/Multinomial.php b/src/Probability/Distribution/Multivariate/Multinomial.php index <HASH>..<HASH> 100644 --- a/src/Probability/Distribution/Multivariate/Multinomial.php +++ b/src/Probability/Distribution/Multivariate/Multinomial.php @@ -52,7 +52,13 @@ class Multinomial if (count($frequencies) !== count($this->probabilities)) { throw new Exception\BadDataException('Number of frequencies does not match number of probabilities.'); } + foreach ($frequencies as $frequency) { + if (!is_int($frequency)) { + throw new Exception\BadDataException("Frequencies must be integers. $frequency is not an int."); + } + } + /** @var int $n */ $n = array_sum($frequencies); $n๏ผ = Combinatorics::factorial($n); diff --git a/tests/Probability/Distribution/Multivariate/MultinomialTest.php b/tests/Probability/Distribution/Multivariate/MultinomialTest.php index <HASH>..<HASH> 100644 --- a/tests/Probability/Distribution/Multivariate/MultinomialTest.php +++ b/tests/Probability/Distribution/Multivariate/MultinomialTest.php @@ -8,13 +8,13 @@ class MultinomialTest extends \PHPUnit\Framework\TestCase { /** * @testCase pmf - * @dataProvider dataProviderForPMF + * @dataProvider dataProviderForPmf * @param array $frequencies * @param array $probabilities * @param $expectedPmf * @throws \Exception */ - public function testPMF(array $frequencies, array $probabilities, $expectedPmf) + public function testPmf(array $frequencies, array $probabilities, $expectedPmf) { // Given $multinomial = new Multinomial($probabilities); @@ -29,7 +29,7 @@ class MultinomialTest extends \PHPUnit\Framework\TestCase /** * @return array */ - public function dataProviderForPMF(): array + public function dataProviderForPmf(): array { return [ [ [1, 1], [0.5, 0.5], 0.5 ], @@ -45,7 +45,7 @@ class MultinomialTest extends \PHPUnit\Framework\TestCase * @testCase pmf throws Exception\BadDataException if the number of frequencies does not match the number of probabilities * @throws \Exception */ - public function testPMFExceptionCountFrequenciesAndProbabilitiesDoNotMatch() + public function testPmfExceptionCountFrequenciesAndProbabilitiesDoNotMatch() { // Given $probabilities = [0.3, 0.4, 0.2, 0.1]; @@ -60,6 +60,24 @@ class MultinomialTest extends \PHPUnit\Framework\TestCase } /** + * @testCase pmf throws Exception\BadDataException if one of the frequencies is not an int + * @throws \Exception + */ + public function testPmfExceptionFrequenciesAreNotAllIntegers() + { + // Given + $probabilities = [0.3, 0.4, 0.2, 0.1]; + $frequencies = [1, 2.3, 3, 4.4]; + $multinomial = new Multinomial($probabilities); + + // Then + $this->expectException(Exception\BadDataException::class); + + // when + $multinomial->pmf($frequencies); + } + + /** * @testCase constructor throws Exception\BadDataException if the probabilities do not add up to 1 * @throws \Exception */
Add Multinomial check on frequencies that they are integers. Add unit test.
markrogoyski_math-php
train
0dcbc7086cd0c932ed0b7fa0ade8ba3c1a38a117
diff --git a/python/bigdl/dllib/nn/layer.py b/python/bigdl/dllib/nn/layer.py index <HASH>..<HASH> 100644 --- a/python/bigdl/dllib/nn/layer.py +++ b/python/bigdl/dllib/nn/layer.py @@ -3251,6 +3251,65 @@ class ReLU6(Layer): super(ReLU6, self).__init__(None, bigdl_type, inplace) +class SReLU(Layer): + + '''S-shaped Rectified Linear Unit. + + It follows: + `f(x) = t^r + a^r(x - t^r) for x >= t^r`, + `f(x) = x for t^r > x > t^l`, + `f(x) = t^l + a^l(x - t^l) for x <= t^l`. + + # References + - [Deep Learning with S-shaped Rectified Linear Activation Units](http://arxiv.org/abs/1512.07030) + + + + :param shared_axes: the axes along which to share learnable + parameters for the activation function. + For example, if the incoming feature maps + are from a 2D convolution + with output shape `(batch, height, width, channels)`, + and you wish to share parameters across space + so that each filter only has one set of parameters, + set `shared_axes=[1, 2]`. + + >>> srelu = SReLU() + creating: createSReLU + >>> srelu = SReLU((1, 2)) + creating: createSReLU + ''' + + def __init__(self, + share_axes=None, + bigdl_type="float"): + super(SReLU, self).__init__(None, bigdl_type, + share_axes) + + def set_init_method(self, tLeftInit = None, aLeftInit = None, + tRightInit = None, aRightInit = None): + callBigDlFunc(self.bigdl_type, "setInitMethod", self.value, + tLeftInit, aLeftInit, tRightInit, aRightInit) + return self + +class ActivityRegularization(Layer): + + ''' + Layer that applies an update to the cost function based input activity. + + :param l1: L1 regularization factor (positive float). + :param l2: L2 regularization factor (positive float). + + + >>> ar = ActivityRegularization(0.1, 0.02) + creating: createActivityRegularization + ''' + + def __init__(self, + l1=0.0, + l2=0.0, + bigdl_type="float"): + super(ActivityRegularization, self).__init__(None, bigdl_type, l1, l2) class Replicate(Layer): diff --git a/python/bigdl/dllib/optim/optimizer.py b/python/bigdl/dllib/optim/optimizer.py index <HASH>..<HASH> 100644 --- a/python/bigdl/dllib/optim/optimizer.py +++ b/python/bigdl/dllib/optim/optimizer.py @@ -818,6 +818,16 @@ class L1L2Regularizer(JavaValue): def __init__(self, l1, l2, bigdl_type="float"): JavaValue.__init__(self, None, bigdl_type, l1, l2) +class ActivityRegularization(JavaValue): + """ + Apply both L1 and L2 regularization + + :param l1 l1 regularization rate + :param l2 l2 regularization rate + + """ + def __init__(self, l1, l2, bigdl_type="float"): + JavaValue.__init__(self, None, bigdl_type, l1, l2) class L1Regularizer(JavaValue): """
feat: SReLU and ActivityRegularization support (#<I>) * feat: SReLU and ActivityRegularization support * fix: update doc * fix: refactor the weights and gradWeights of SReLU * fix: serialization for srelu * fix: backward computing errors * fix: ActivityRegularization to layer * fix: change test location * fix: add python api * fix: shared axes have not consider enough
intel-analytics_BigDL
train
5da155608c8f2e310e7c893f25842180c100f73c
diff --git a/lib/index.js b/lib/index.js index <HASH>..<HASH> 100644 --- a/lib/index.js +++ b/lib/index.js @@ -30,13 +30,17 @@ exports = M.init(); */ // Public {{{1 -exports.browserConfig = true; - -M.content(); - M.scope = 'fs'; M.kind('./dir', 'dir'); M.kind('./file', 'file'); -var Sources = require('ose-media/lib/sources'); -Sources.add('file', 'fs', 'dir'); +M.content(); + +exports.browserConfig = true; + +exports.config = function() { + if (Ose.media && Ose.media.sources) { + Ose.media.sources.add('file', 'fs', 'dir'); + } +}; +
Change: Register media source only when media package is activated.
OpenSmartEnvironment_ose-fs
train
5ed8c988f44f108fd584e91c2e10f23b47fae61c
diff --git a/lib/voog_api/version.rb b/lib/voog_api/version.rb index <HASH>..<HASH> 100644 --- a/lib/voog_api/version.rb +++ b/lib/voog_api/version.rb @@ -1,3 +1,3 @@ module Voog - VERSION = '0.0.6' + VERSION = '0.0.7' end
Update gem version to <I>
Voog_voog.rb
train
c8e7194d2660ce6c7a256e79c16fc1130d95cd48
diff --git a/test/streaming/p000.js b/test/streaming/p000.js index <HASH>..<HASH> 100755 --- a/test/streaming/p000.js +++ b/test/streaming/p000.js @@ -6,7 +6,7 @@ var fs = require('fs'); var co = require('co'); var ugrid = require('../..'); -var s1 = fs.createReadStream('./f', {encoding: 'utf8'}); +var s1 = fs.createReadStream(__dirname + '/f', {encoding: 'utf8'}); co(function *() { var uc = yield ugrid.context(); diff --git a/test/streaming/p001.js b/test/streaming/p001.js index <HASH>..<HASH> 100755 --- a/test/streaming/p001.js +++ b/test/streaming/p001.js @@ -6,7 +6,7 @@ var fs = require('fs'); var co = require('co'); var ugrid = require('../..'); -var s1 = fs.createReadStream('./f', {encoding: 'utf8'}); +var s1 = fs.createReadStream(__dirname + '/f', {encoding: 'utf8'}); co(function *() { var uc = yield ugrid.context(); diff --git a/test/streaming/p002.js b/test/streaming/p002.js index <HASH>..<HASH> 100755 --- a/test/streaming/p002.js +++ b/test/streaming/p002.js @@ -6,7 +6,7 @@ var fs = require('fs'); var co = require('co'); var ugrid = require('../..'); -var s1 = fs.createReadStream('./f', {encoding: 'utf8'}); +var s1 = fs.createReadStream(__dirname + '/f', {encoding: 'utf8'}); co(function *() { var uc = yield ugrid.context(); diff --git a/test/streaming/p003.js b/test/streaming/p003.js index <HASH>..<HASH> 100755 --- a/test/streaming/p003.js +++ b/test/streaming/p003.js @@ -7,8 +7,8 @@ var fs = require('fs'); var co = require('co'); var ugrid = require('../..'); -var s1 = fs.createReadStream('./f', {encoding: 'utf8'}); -var s2 = fs.createReadStream('./f2', {encoding: 'utf8'}); +var s1 = fs.createReadStream(__dirname + '/f', {encoding: 'utf8'}); +var s2 = fs.createReadStream(__dirname + '/f2', {encoding: 'utf8'}); co(function *() { var uc = yield ugrid.context(); diff --git a/test/streaming/p004.js b/test/streaming/p004.js index <HASH>..<HASH> 100755 --- a/test/streaming/p004.js +++ b/test/streaming/p004.js @@ -6,8 +6,8 @@ var fs = require('fs'); var co = require('co'); var ugrid = require('../..'); -var s1 = fs.createReadStream('./f', {encoding: 'utf8'}); -var s2 = fs.createReadStream('./f2', {encoding: 'utf8'}); +var s1 = fs.createReadStream(__dirname + '/f', {encoding: 'utf8'}); +var s2 = fs.createReadStream(__dirname + '/f2', {encoding: 'utf8'}); co(function *() { var uc = yield ugrid.context(); diff --git a/test/streaming/p005.js b/test/streaming/p005.js index <HASH>..<HASH> 100755 --- a/test/streaming/p005.js +++ b/test/streaming/p005.js @@ -6,8 +6,8 @@ var fs = require('fs'); var co = require('co'); var ugrid = require('../..'); -var s1 = fs.createReadStream('./f', {encoding: 'utf8'}); -var s2 = fs.createReadStream('./f3', {encoding: 'utf8'}); +var s1 = fs.createReadStream(__dirname + '/f', {encoding: 'utf8'}); +var s2 = fs.createReadStream(__dirname + '/f3', {encoding: 'utf8'}); co(function *() { var uc = yield ugrid.context(); diff --git a/test/streaming/p006.js b/test/streaming/p006.js index <HASH>..<HASH> 100755 --- a/test/streaming/p006.js +++ b/test/streaming/p006.js @@ -6,7 +6,7 @@ var fs = require('fs'); var co = require('co'); var ugrid = require('../..'); -var s1 = fs.createReadStream('./f', {encoding: 'utf8'}); +var s1 = fs.createReadStream(__dirname + '/f', {encoding: 'utf8'}); co(function *() { var uc = yield ugrid.context();
fix file paths for streaming tests Former-commit-id: <I>e<I>a<I>f<I>e5e<I>e4e2b<I>ea<I>ae<I>f2
skale-me_skale
train
9a8552eb3fd3ed1474876650d594bb11a03c2a29
diff --git a/glances/glances.py b/glances/glances.py index <HASH>..<HASH> 100644 --- a/glances/glances.py +++ b/glances/glances.py @@ -387,7 +387,15 @@ class Config: """ for path in self.get_paths_list(): if os.path.isfile(path) and os.path.getsize(path) > 0: - self.parser.read(path) + try: + if sys.version_info >= (3, 2): + self.parser.read(path, encoding='utf-8') + else: + self.parser.read(path) + except UnicodeDecodeError as e: + print(_("Error decoding config file '%s': %s") % (path, e)) + sys.exit(1) + break def get_paths_list(self):
UTF-8 config file for python 3 [issue #<I>]
nicolargo_glances
train
9326b1694febbf0840af72ed2a067ab6ed698f6e
diff --git a/index.js b/index.js index <HASH>..<HASH> 100644 --- a/index.js +++ b/index.js @@ -2,4 +2,5 @@ exports.Account = require('./account/'); exports.Analysis = require('./analysis/'); exports.Device = require('./device/'); -exports.Services = require('./services/'); \ No newline at end of file +exports.Services = require('./services/'); +exports.Utils = require('./utils/'); \ No newline at end of file
Added utils to index.js
tago-io_tago-sdk-js
train
82390fa64812b3943417b18a1174c915aaa18735
diff --git a/spec/exchange/currency_spec.rb b/spec/exchange/currency_spec.rb index <HASH>..<HASH> 100644 --- a/spec/exchange/currency_spec.rb +++ b/spec/exchange/currency_spec.rb @@ -105,7 +105,7 @@ describe "Exchange::Currency" do end it "should be able to multiply by another currency value" do mock_api("https://raw.github.com/currencybot/open-exchange-rates/master/latest.json", fixture('api_responses/example_json_api.json'), 2) - (subject / Exchange::Currency.new(10, :chf)).value.round(4).should == 3.6502 + (subject / Exchange::Currency.new(10, :chf)).value.round(2).should == BigDecimal.new("3.65") (subject / Exchange::Currency.new(23.3, :eur)).currency.should == :usd end it "should raise when currencies get mixed and the configuration does not allow it" do diff --git a/spec/exchange/external_api/currency_bot_spec.rb b/spec/exchange/external_api/currency_bot_spec.rb index <HASH>..<HASH> 100644 --- a/spec/exchange/external_api/currency_bot_spec.rb +++ b/spec/exchange/external_api/currency_bot_spec.rb @@ -24,7 +24,7 @@ describe "Exchange::ExternalAPI::CurrencyBot" do mock_api("https://raw.github.com/currencybot/open-exchange-rates/master/latest.json", fixture('api_responses/example_json_api.json')) end it "should convert right" do - subject.convert(80, 'eur', 'usd').round(2).should == 105.76 + subject.convert(80, 'eur', 'usd').round(4).should == BigDecimal.new("105.764") end it "should convert negative numbers right" do subject.convert(-70, 'chf', 'usd').round(2).should == BigDecimal.new("-76.71") @@ -37,7 +37,7 @@ describe "Exchange::ExternalAPI::CurrencyBot" do subject { Exchange::ExternalAPI::CurrencyBot.new } it "should convert and be able to use history" do mock_api("https://raw.github.com/currencybot/open-exchange-rates/master/historical/2011-09-09.json", fixture('api_responses/example_json_api.json')) - subject.convert(70, 'eur', 'usd', :at => Time.gm(2011,9,9)).round(2).should == BigDecimal.new("92.54") + subject.convert(70, 'eur', 'usd', :at => Time.gm(2011,9,9)).round(4).should == BigDecimal.new("92.5435") end it "should convert negative numbers right" do mock_api("https://raw.github.com/currencybot/open-exchange-rates/master/historical/2011-09-09.json", fixture('api_responses/example_json_api.json'))
! specs for <I>
beatrichartz_exchange
train
b8e57e9262bec9b48a865ca5b6cf1767edd7652e
diff --git a/docs/source/conf.py b/docs/source/conf.py index <HASH>..<HASH> 100644 --- a/docs/source/conf.py +++ b/docs/source/conf.py @@ -111,7 +111,7 @@ todo_include_todos = False # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. -html_theme = 'alabaster' +html_theme = 'sphinx-rtd-theme' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the
Why wouldn't I want the RTD theme?
python-hyper_brotlipy
train
3f3cbc91aee1e31ef8f83252459b4d4ef68049c7
diff --git a/server.py b/server.py index <HASH>..<HASH> 100644 --- a/server.py +++ b/server.py @@ -59,6 +59,12 @@ def fromWebsocket(data): return unquote(data,encoding='latin-1') +def encodeIfPyGT3(data): + if not pyLessThan3: + data = data.encode('latin-1') + return data + + def get_method_by(rootNode, idname): if idname.isdigit(): return get_method_by_id(rootNode, idname) @@ -453,6 +459,7 @@ ws.onerror = function(evt){ \ return def process_all(self, function, paramDict, isPost): + encoding='latin-1' ispath = True snake = None doNotCallMain = False @@ -493,14 +500,13 @@ ws.onerror = function(evt){ \ self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() - - self.wfile.write(self.client.attachments.encode('latin-1')) - self.wfile.write(( + + self.wfile.write(encodeIfPyGT3(self.client.attachments)) + self.wfile.write(encodeIfPyGT3( "<link href='" + BASE_ADDRESS + - "style.css' rel='stylesheet' />").encode('latin-1')) - - self.wfile.write(repr(self.client.root).encode('latin-1')) + "style.css' rel='stylesheet' />")) + self.wfile.write(encodeIfPyGT3(repr(self.client.root))) else: # here is the function that should return the content type self.send_response(200) @@ -511,13 +517,13 @@ ws.onerror = function(evt){ \ # if is requested a widget, but not by post, so we suppose is # requested to show a new page, we attach javascript and style if(ret[1] == 'text/html' and isPost == False): - self.wfile.write(self.client.attachments.encode('latin-1')) - self.wfile.write(( + self.wfile.write(encodeIfPyGT3(self.client.attachments)) + self.wfile.write(encodeIfPyGT3( "<link href='" + BASE_ADDRESS + - "style.css' rel='stylesheet' />").encode('latin-1')) + "style.css' rel='stylesheet' />")) - self.wfile.write(ret[0].encode('latin-1')) + self.wfile.write(encodeIfPyGT3(ret[0])) else: self.send_response(200)
Encoding compatibility with python<I> fixed.
dddomodossola_remi
train
5e9cec83848fe92d89dd9b4e60bd57c11f11e81c
diff --git a/ghost/admin/config/environment.js b/ghost/admin/config/environment.js index <HASH>..<HASH> 100644 --- a/ghost/admin/config/environment.js +++ b/ghost/admin/config/environment.js @@ -21,7 +21,7 @@ module.exports = function (environment) { // override the default version string which contains git info from // https://github.com/cibernox/git-repo-version. Only include the // `major.minor` version numbers - version: require('../package.json').version.replace(/\.\d+$/, '') + version: require('../package.json').version.match(/^(\d+\.)?(\d+)/)[0] }, 'ember-simple-auth': { diff --git a/ghost/admin/tests/integration/services/store-test.js b/ghost/admin/tests/integration/services/store-test.js index <HASH>..<HASH> 100644 --- a/ghost/admin/tests/integration/services/store-test.js +++ b/ghost/admin/tests/integration/services/store-test.js @@ -37,7 +37,6 @@ describeModule( store.find('post', 1).catch(() => { let [request] = server.handledRequests; - console.log(request); expect(request.requestHeaders['X-Ghost-Version']).to.equal(version); done(); });
Minor version header fixes refs #<I> - use same version regex as `safeVersion` does on the server - remove errant `console.log` from store service test
TryGhost_Ghost
train
b4528873c4a76815441e40d4e9210e7980f365e1
diff --git a/src/Kunstmaan/MenuBundle/Twig/MenuTwigExtension.php b/src/Kunstmaan/MenuBundle/Twig/MenuTwigExtension.php index <HASH>..<HASH> 100644 --- a/src/Kunstmaan/MenuBundle/Twig/MenuTwigExtension.php +++ b/src/Kunstmaan/MenuBundle/Twig/MenuTwigExtension.php @@ -72,9 +72,15 @@ class MenuTwigExtension extends \Twig_Extension $activeClass = $options['activeClass']; } - $options = array_merge($this->getDefaultOptions($activeClass), $options); + $options = array_merge( + $this->getDefaultOptions( + isset($options['linkClass']) ? $options['linkClass'] : false, + isset($options['activeClass']) ? $options['activeClass'] : false + ), + $options + ); - $html = $menuRepo->buildTree($arrayResult, $options); + $html = $repo->buildTree($arrayResult, $options); return $html; } @@ -94,14 +100,14 @@ class MenuTwigExtension extends \Twig_Extension 'rootClose' => '</ul>', 'childOpen' => '<li>', 'childClose' => '</li>', - 'nodeDecorator' => function ($node) use ($router, $activeClass) { - $active = false; + 'nodeDecorator' => function($node) use ($router, $linkClass, $activeClass) { + $class = explode(' ', $linkClass); if ($node['type'] == MenuItem::TYPE_PAGE_LINK) { $url = $router->generate('_slug', array('url' => $node['nodeTranslation']['url'])); if ($activeClass && $router->getContext()->getPathInfo() == $url) { - $active = true; + $class[] = $activeClass; } } else { $url = $node['url']; @@ -117,8 +123,12 @@ class MenuTwigExtension extends \Twig_Extension $title = $node['title']; } - return '<a href="'.$url.'"'.($active ? ' class="'.$activeClass.'"' : '').($node['newWindow'] ? ' target="_blank"' : '').'>'.$title.'</a>'; - }, + // Format attributes. + $attributes = empty($class) ? '' : ' class="' . implode(' ', $class) . '"'; + $attributes .= $node['newWindow'] ? ' target="_blank"' : ''; + + return sprintf('<a href="%s"%s>%s</a>', $url, $attributes, $title); + }, ); }
Let define extra link classes to decorator.
Kunstmaan_KunstmaanBundlesCMS
train
f5aea1d099248058cb76791834351bbf3b9bcc9a
diff --git a/lib/jsi/base.rb b/lib/jsi/base.rb index <HASH>..<HASH> 100644 --- a/lib/jsi/base.rb +++ b/lib/jsi/base.rb @@ -145,11 +145,11 @@ module JSI end if thing.is_a?(Base) warn "assigning instance to a Base instance is incorrect. received: #{thing.pretty_inspect.chomp}" - @instance = JSI.deep_stringify_symbol_keys(thing.instance) + @instance = thing.instance elsif thing.is_a?(JSI::JSON::Node) - @instance = JSI.deep_stringify_symbol_keys(thing) + @instance = thing else - @instance = JSI::JSON::Node.new_doc(JSI.deep_stringify_symbol_keys(thing)) + @instance = JSI::JSON::Node.new_doc(thing) end end
no longer going to deep_stringify_symbol_keys on JSI initialize. this is seriously half-assing it, and I don't like it.
notEthan_jsi
train
13896bbf3f14852f23f583cde745d73d7ab3d641
diff --git a/qiime_tools/biom_calc.py b/qiime_tools/biom_calc.py index <HASH>..<HASH> 100644 --- a/qiime_tools/biom_calc.py +++ b/qiime_tools/biom_calc.py @@ -1,7 +1,7 @@ ''' Created on Feb 19, 2013 -@author: Shareef Dabdoub +:author: Shareef Dabdoub This module provides methods for calculating various metrics with regards to each OTU in an input OTU abundance table. This is currently used by iTol.py diff --git a/qiime_tools/otu_calc.py b/qiime_tools/otu_calc.py index <HASH>..<HASH> 100644 --- a/qiime_tools/otu_calc.py +++ b/qiime_tools/otu_calc.py @@ -146,7 +146,7 @@ def print_membership(entry): :type entry: list :param entry: SampleID's from the output dict of assign_otu_membership(). - :rrtype: str + :rtype: str :return: Returns OTU name and percentage relative abundance as membership for the given list of SampleID's. """ diff --git a/qiime_tools/util.py b/qiime_tools/util.py index <HASH>..<HASH> 100644 --- a/qiime_tools/util.py +++ b/qiime_tools/util.py @@ -1,7 +1,7 @@ ''' Created on Feb 2, 2013 -@author: Shareef Dabdoub +:author: Shareef Dabdoub ''' from collections import namedtuple, OrderedDict import os @@ -41,7 +41,7 @@ def parseFASTA(fastaFNH): iterated through, such as a list or an open file handle. :rtype: tuple - :return:FASTA records containing entries for id, description and data. + :return: FASTA records containing entries for id, description and data. """ recs = [] seq = []
Updated API script for documentation. Changed script syntax for better visualization for documentation. [ci skip]
smdabdoub_phylotoast
train
12812ad5da77a672c3798fdd345ca4ae26857f2d
diff --git a/admin/cli/install.php b/admin/cli/install.php index <HASH>..<HASH> 100644 --- a/admin/cli/install.php +++ b/admin/cli/install.php @@ -135,7 +135,7 @@ $CFG->wwwroot = "http://localhost"; $CFG->httpswwwroot = $CFG->wwwroot; $CFG->dataroot = str_replace('\\', '/', dirname(dirname(dirname(dirname(__FILE__)))).'/moodledata'); $CFG->tempdir = $CFG->dataroot.'/temp'; -$CFG->cachedir = $CFG->dataroot.'/temp'; +$CFG->cachedir = $CFG->dataroot.'/cache'; $CFG->docroot = 'http://docs.moodle.org'; $CFG->running_installer = true; $CFG->early_install_lang = true; diff --git a/install.php b/install.php index <HASH>..<HASH> 100644 --- a/install.php +++ b/install.php @@ -166,7 +166,7 @@ $CFG->wwwroot = install_guess_wwwroot(); // can not be changed - pp $CFG->httpswwwroot = $CFG->wwwroot; $CFG->dataroot = $config->dataroot; $CFG->tempdir = $CFG->dataroot.'/temp'; -$CFG->cachedir = $CFG->dataroot.'/temp'; +$CFG->cachedir = $CFG->dataroot.'/cache'; $CFG->admin = $config->admin; $CFG->docroot = 'http://docs.moodle.org'; $CFG->langotherroot = $CFG->dataroot.'/lang';
MDL-<I> Fixed path to the cache directory in installers This fixes the patch f<I>c0f6e<I>c<I>a<I>d<I>f<I>bca<I>c1e introduced in MDL-<I>.
moodle_moodle
train
72e5fe306f663f2194e7ee752e56a80471fb8874
diff --git a/findbugs/src/java/edu/umd/cs/findbugs/UsageTracker.java b/findbugs/src/java/edu/umd/cs/findbugs/UsageTracker.java index <HASH>..<HASH> 100644 --- a/findbugs/src/java/edu/umd/cs/findbugs/UsageTracker.java +++ b/findbugs/src/java/edu/umd/cs/findbugs/UsageTracker.java @@ -125,7 +125,7 @@ class UsageTracker { conn.setRequestMethod("POST"); conn.connect(); OutputStream out = conn.getOutputStream(); - XMLOutput xmlOutput = new OutputStreamXMLOutput(out); + OutputStreamXMLOutput xmlOutput = new OutputStreamXMLOutput(out); xmlOutput.beginDocument(); xmlOutput.startTag("findbugs-invocation"); xmlOutput.addAttribute("version", Version.RELEASE); @@ -159,14 +159,14 @@ class UsageTracker { } xmlOutput.closeTag("findbugs-invocation"); - xmlOutput.finish(); + xmlOutput.flush(); int responseCode = conn.getResponseCode(); if (responseCode != 200) { logError(SystemProperties.ASSERTIONS_ENABLED ? Level.WARNING : Level.FINE, "Error submitting anonymous usage data to " + trackerUrl + ": " + responseCode + " - " + conn.getResponseMessage()); } parseUpdateXml(trackerUrl, plugins, conn.getInputStream()); - out.close(); + xmlOutput.finish(); conn.disconnect(); } diff --git a/findbugs/src/java/edu/umd/cs/findbugs/xml/OutputStreamXMLOutput.java b/findbugs/src/java/edu/umd/cs/findbugs/xml/OutputStreamXMLOutput.java index <HASH>..<HASH> 100644 --- a/findbugs/src/java/edu/umd/cs/findbugs/xml/OutputStreamXMLOutput.java +++ b/findbugs/src/java/edu/umd/cs/findbugs/xml/OutputStreamXMLOutput.java @@ -183,6 +183,9 @@ public class OutputStreamXMLOutput implements XMLOutput { newLine = false; } + public void flush() throws IOException { + out.flush(); + } @DischargesObligation public void finish() throws IOException { out.close();
don't close XMLOutput until we receive message back, just flush it. git-svn-id: <URL>
spotbugs_spotbugs
train
27c3b94a04985f75b166f2925560bfecf22ff94d
diff --git a/compilers/amd.js b/compilers/amd.js index <HASH>..<HASH> 100644 --- a/compilers/amd.js +++ b/compilers/amd.js @@ -339,6 +339,14 @@ AMDDefineRegisterTransformer.prototype.transformCallExpression = function(tree) }; exports.AMDDefineRegisterTransformer = AMDDefineRegisterTransformer; +function dedupe(deps) { + var newDeps = []; + for (var i = 0, l = deps.length; i < l; i++) + if (newDeps.indexOf(deps[i]) == -1) + newDeps.push(deps[i]) + return newDeps; +} + // override System instantiate to handle AMD dependencies exports.attach = function(loader) { var systemInstantiate = loader.instantiate; @@ -365,7 +373,7 @@ exports.attach = function(loader) { } return { - deps: depTransformer.deps, + deps: dedupe(depTransformer.deps), execute: function() {} }; }
dedupe amd dependencies in builder
systemjs_builder
train
8ae0dbcf4636c62cb31e6296f1458f0228d5ddaf
diff --git a/src/OAuth2/Util/SecureKey.php b/src/OAuth2/Util/SecureKey.php index <HASH>..<HASH> 100644 --- a/src/OAuth2/Util/SecureKey.php +++ b/src/OAuth2/Util/SecureKey.php @@ -4,7 +4,7 @@ namespace OAuth2\Util; class SecureKey { - public static function make($len = 42) + public static function make($len = 40) { // We generate twice as many bytes here because we want to ensure we have // enough after we base64 encode it to get the length we need because we
Default to <I> characters (as that is what the DB table columns are set to)
thephpleague_oauth2-server
train
cc9b6ca1b7650c21a7e996649df35ba3bd08d295
diff --git a/girder/api/v1/resource.py b/girder/api/v1/resource.py index <HASH>..<HASH> 100644 --- a/girder/api/v1/resource.py +++ b/girder/api/v1/resource.py @@ -65,20 +65,24 @@ class Resource(BaseResource): .errorResponse('Invalid type list format.') ) def search(self, q, mode, types, level, limit, offset): + """This function return an empty dict if the mode isn't in the search mode + registry, else it call the search mode handler. + """ + results = {} level = AccessType.validate(level) user = self.getCurrentUser() + handler = search_mode_utilities.getSearchModeHandler(mode) - if self._isDefaultSearchMode(mode): - return search_mode_utilities.defaultSearchModeHandler( - q, mode, types, user, level, limit, offset - ) - else: - return search_mode_utilities.searchModeHandler( - q, mode, types, user, level, limit, offset + if handler is not None: + results = handler( + query=q, + types=types, + user=user, + limit=limit, + offset=offset, + level=level ) - - def _isDefaultSearchMode(self, mode): - return mode in {'text', 'prefix'} + return results def _validateResourceSet(self, resources, allowedModels=None): """ diff --git a/girder/utility/search_mode_utilities.py b/girder/utility/search_mode_utilities.py index <HASH>..<HASH> 100644 --- a/girder/utility/search_mode_utilities.py +++ b/girder/utility/search_mode_utilities.py @@ -16,6 +16,8 @@ # See the License for the specific language governing permissions and # limitations under the License. ############################################################################### +from functools import partial + from girder.models.assetstore import Assetstore from girder.models.collection import Collection from girder.models.folder import Folder @@ -34,8 +36,8 @@ Their handlers are directly define in the base model. _allowedSearchMode = {} -def defaultSearchModeHandler(q, mode, types, user, level, limit, offset): - method = getSearchModeHandler(mode) +def defaultSearchModeHandler(query, mode, types, user, level, limit, offset): + method = '%sSearch' % mode results = {} for modelName in types: @@ -44,24 +46,11 @@ def defaultSearchModeHandler(q, mode, types, user, level, limit, offset): if model is not None: results[modelName] = [ model.filter(d, user) for d in getattr(model, method)( - query=q, user=user, limit=limit, offset=offset, level=level) + query=query, user=user, limit=limit, offset=offset, level=level) ] return results -def searchModeHandler(q, mode, types, user, level, limit, offset): - """This function return an empty dict if the mode isn't in the search mode - registry, else it call the search mode handler. - """ - results = {} - method = getSearchModeHandler(mode) - - if method is not None: - results = method(query=q, types=types, user=user, limit=limit, offset=offset, level=level) - - return results - - def getSearchModeHandler(mode): if mode in _allowedSearchMode: return _allowedSearchMode[mode] @@ -70,14 +59,14 @@ def getSearchModeHandler(mode): def addSearchMode(mode, handler): """This function is able to modify an existing search mode.""" - _allowedSearchMode.update({ - mode: handler - }) + _allowedSearchMode[mode] = handler def removeSearchMode(mode): - """Return False if the mode wasn't in the search mode registry.""" - return _allowedSearchMode.pop(mode, False) + """Return a boolean to know if the mode was removed from the search mode registry or not.""" + if _allowedSearchMode.pop(mode, None) is not None: + return True + return False def _getModel(name): @@ -98,5 +87,5 @@ def _getModel(name): # Add dynamically the default search mode -addSearchMode('text', 'textSearch') -addSearchMode('prefix', 'prefixSearch') +addSearchMode('text', partial(defaultSearchModeHandler, mode='text')) +addSearchMode('prefix', partial(defaultSearchModeHandler, mode='prefix'))
correct some logical issue and use partial function for default search mode.
girder_girder
train
c83abda1839a80b74b60d6a238b7e84968fd0eea
diff --git a/lxd/db/networks.go b/lxd/db/networks.go index <HASH>..<HASH> 100644 --- a/lxd/db/networks.go +++ b/lxd/db/networks.go @@ -422,7 +422,7 @@ func (c *Cluster) GetNetworks(project string) ([]string, error) { return c.networks(project, "") } -// GetCreatedNetworks returns the names of all networks that are not in state networkCreated. +// GetCreatedNetworks returns the names of all networks that are in state networkCreated. func (c *Cluster) GetCreatedNetworks(project string) ([]string, error) { return c.networks(project, "state=?", networkCreated) }
lxd/db/networks: Corrects comment on GetCreatedNetworks
lxc_lxd
train
7250186c2683cae560624d1837c2761be88747b9
diff --git a/moto/s3/models.py b/moto/s3/models.py index <HASH>..<HASH> 100644 --- a/moto/s3/models.py +++ b/moto/s3/models.py @@ -8,6 +8,7 @@ import itertools import codecs import six +from bisect import insort from moto.core import BaseBackend from moto.core.utils import iso_8601_datetime_with_milliseconds, rfc_1123_datetime from .exceptions import BucketAlreadyExists, MissingBucket @@ -118,6 +119,7 @@ class FakeMultipart(object): self.key_name = key_name self.metadata = metadata self.parts = {} + self.partlist = [] # ordered list of part ID's rand_b64 = base64.b64encode(os.urandom(UPLOAD_ID_BYTES)) self.id = rand_b64.decode('utf-8').replace('=', '').replace('+', '') @@ -125,18 +127,19 @@ class FakeMultipart(object): decode_hex = codecs.getdecoder("hex_codec") total = bytearray() md5s = bytearray() - last_part_name = len(self.list_parts()) - for part in self.list_parts(): - if part.name != last_part_name and len(part.value) < UPLOAD_PART_MIN_SIZE: + last = None + for index, part in enumerate(self.list_parts(), start=1): + if last is not None and len(last.value) < UPLOAD_PART_MIN_SIZE: return None, None part_etag = part.etag.replace('"', '') md5s.extend(decode_hex(part_etag)[0]) total.extend(part.value) + last = part etag = hashlib.md5() etag.update(bytes(md5s)) - return total, "{0}-{1}".format(etag.hexdigest(), last_part_name) + return total, "{0}-{1}".format(etag.hexdigest(), index) def set_part(self, part_id, value): if part_id < 1: @@ -144,18 +147,12 @@ class FakeMultipart(object): key = FakeKey(part_id, value) self.parts[part_id] = key + insort(self.partlist, part_id) return key def list_parts(self): - parts = [] - - for part_id, index in enumerate(sorted(self.parts.keys()), start=1): - # Make sure part ids are continuous - if part_id != index: - return - parts.append(self.parts[part_id]) - - return parts + for part_id in self.partlist: + yield self.parts[part_id] class FakeBucket(object): @@ -297,7 +294,7 @@ class S3Backend(BaseBackend): def list_multipart(self, bucket_name, multipart_id): bucket = self.get_bucket(bucket_name) - return bucket.multiparts[multipart_id].list_parts() + return list(bucket.multiparts[multipart_id].list_parts()) def get_all_multiparts(self, bucket_name): bucket = self.get_bucket(bucket_name)
support multipart uploads when parts are uploaded out of order
spulec_moto
train
c053a2f35007f662fdfbab44c8cfd9c48701e882
diff --git a/gns3server/compute/traceng/traceng_vm.py b/gns3server/compute/traceng/traceng_vm.py index <HASH>..<HASH> 100644 --- a/gns3server/compute/traceng/traceng_vm.py +++ b/gns3server/compute/traceng/traceng_vm.py @@ -168,6 +168,7 @@ class TraceNGVM(BaseNode): if not self.is_running(): nio = self._ethernet_adapter.get_nio(0) command = self._build_command(destination) + yield from self._stop_ubridge() # make use we start with a fresh uBridge instance try: log.info("Starting TraceNG: {}".format(command)) flags = subprocess.CREATE_NEW_CONSOLE @@ -176,6 +177,7 @@ class TraceNGVM(BaseNode): cwd=self.working_dir, creationflags=flags) monitor_process(self._process, self._termination_callback) + yield from self._start_ubridge() if nio: yield from self.add_ubridge_udp_connection("TraceNG-{}".format(self._id), self._local_udp_tunnel[1], nio) @@ -242,6 +244,9 @@ class TraceNGVM(BaseNode): """ log.info("Stopping TraceNG instance {} PID={}".format(self.name, self._process.pid)) + #if sys.platform.startswith("win32"): + # self._process.send_signal(signal.CTRL_BREAK_EVENT) + #else: try: self._process.terminate() # Sometime the process may already be dead when we garbage collect @@ -395,6 +400,7 @@ class TraceNGVM(BaseNode): nio = self._local_udp_tunnel[0] if nio and isinstance(nio, NIOUDP): # UDP tunnel + command.extend(["-u"]) # enable UDP tunnel command.extend(["-c", str(nio.lport)]) # source UDP port command.extend(["-v", str(nio.rport)]) # destination UDP port try: @@ -402,6 +408,7 @@ class TraceNGVM(BaseNode): except socket.gaierror as e: raise TraceNGError("Can't resolve hostname {}: {}".format(nio.rhost, e)) + command.extend(["-s", "ICMP"]) # Use ICMP probe type by default command.extend(["-f", self._ip_address]) # source IP address to trace from command.extend([destination]) # host or IP to trace return command
Enable UDP tunnel option and use ICMP probing by default.
GNS3_gns3-server
train
48b86415254f2b9a87ae4fb7792877caef75ca8e
diff --git a/src/action.py b/src/action.py index <HASH>..<HASH> 100644 --- a/src/action.py +++ b/src/action.py @@ -88,7 +88,7 @@ class Action: self.process = subprocess.Popen(shlex.split(self.command), stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True) except OSError as exp: print "FUCK:", exp - self.output = exp + self.output = exp.__str__() self.exit_status = 2 self.status = 'done' self.execution_time = time.time() - self.check_time diff --git a/src/modules/livestatus_broker/livestatus.py b/src/modules/livestatus_broker/livestatus.py index <HASH>..<HASH> 100644 --- a/src/modules/livestatus_broker/livestatus.py +++ b/src/modules/livestatus_broker/livestatus.py @@ -165,7 +165,7 @@ class LiveStatus: 'description' : { 'prop' : 'service_description' }, 'display_name' : { }, 'downtimes' : { }, - 'event_handler' : { }, + 'event_handler' : { 'depythonize' : 'call' }, 'event_handler_enabled' : { 'depythonize' : from_bool_to_string }, 'execution_time' : { 'converter' : float }, 'first_notification_delay' : { 'converter' : int },
*Fix a bug in the livestatus module. Eventhandler command is now serializable *Fix a bug in execute_unix. If there is an exception during plugin execution, use it's string representation as plugin_output
Alignak-monitoring_alignak
train
44d00fa2f464b2c130dbaeddc82aebdab8cf21a1
diff --git a/src/handler-runner/WorkerThreadRunner.js b/src/handler-runner/WorkerThreadRunner.js index <HASH>..<HASH> 100644 --- a/src/handler-runner/WorkerThreadRunner.js +++ b/src/handler-runner/WorkerThreadRunner.js @@ -17,6 +17,9 @@ module.exports = class WorkerThreadRunner { if (this._workerThread == null) { this._workerThread = new Worker(workerThreadHelperPath, { + // note: although env by default is set to process.env, it only uses the + // original (unmodified) process.env, so we have to pass it explicitly + env: process.env, workerData: { functionName, handlerName,
Fix, pass process.env explicitly to worker thread
dherault_serverless-offline
train
b4950c63ed7054d14ffaace19e3f3f2e5eea53d1
diff --git a/lxd/cluster/membership.go b/lxd/cluster/membership.go index <HASH>..<HASH> 100644 --- a/lxd/cluster/membership.go +++ b/lxd/cluster/membership.go @@ -7,6 +7,7 @@ import ( "fmt" "os" "path/filepath" + "sync" "time" "github.com/canonical/go-dqlite/app" @@ -545,13 +546,25 @@ func notifyNodesUpdate(raftNodes []db.RaftNode, id uint64, networkCert *shared.C nodes[i].ID = int64(raftNode.ID) nodes[i].Address = raftNode.Address } + hbState.Update(false, raftNodes, nodes, 0) + + // Notify all other members of the change in membership. + var wg sync.WaitGroup for _, node := range raftNodes { if node.ID == id { continue } - go HeartbeatNode(context.Background(), node.Address, networkCert, serverCert, hbState) + + wg.Add(1) + go func(address string) { + HeartbeatNode(context.Background(), address, networkCert, serverCert, hbState) + wg.Done() + }(node.Address) } + + // Wait until all members have been notified (or at least have had a change to be notified). + wg.Wait() } // Rebalance the raft cluster, trying to see if we have a spare online node
lxd/cluster/membership: Update notifyNodesUpdate to wait until all heartbeats have been sent So that we ensure all members are notified of changes before returning.
lxc_lxd
train
7dd88a6e7fb885292f87252e9b07c6f3e003af17
diff --git a/spring-cloud-commons/src/main/java/org/springframework/cloud/configuration/SpringBootVersionVerifier.java b/spring-cloud-commons/src/main/java/org/springframework/cloud/configuration/SpringBootVersionVerifier.java index <HASH>..<HASH> 100644 --- a/spring-cloud-commons/src/main/java/org/springframework/cloud/configuration/SpringBootVersionVerifier.java +++ b/spring-cloud-commons/src/main/java/org/springframework/cloud/configuration/SpringBootVersionVerifier.java @@ -87,7 +87,8 @@ class SpringBootVersionVerifier implements CompatibilityVerifier { if (log.isDebugEnabled()) { log.debug("Version found in Boot manifest [" + version + "]"); } - return StringUtils.hasText(version) && version.startsWith(s); + return StringUtils.hasText(version) + && version.startsWith(stripWildCardFromVersion(s)); } String getVersionFromManifest() { @@ -216,7 +217,7 @@ class SpringBootVersionVerifier implements CompatibilityVerifier { else { // 2.0, 2.1 CompatibilityPredicate predicate = this.ACCEPTED_VERSIONS - .get(acceptedVersionWithoutX(acceptedVersion)); + .get(stripWildCardFromVersion(acceptedVersion)); if (predicate != null && predicate.isCompatible()) { if (log.isDebugEnabled()) { log.debug("Predicate [" + predicate + "] was matched"); @@ -228,11 +229,11 @@ class SpringBootVersionVerifier implements CompatibilityVerifier { return false; } - private String acceptedVersionWithoutX(String acceptedVersion) { - if (acceptedVersion.endsWith(".x")) { - return acceptedVersion.substring(0, acceptedVersion.indexOf(".x")); + static String stripWildCardFromVersion(String version) { + if (version.endsWith(".x")) { + return version.substring(0, version.indexOf(".x")); } - return acceptedVersion; + return version; } } diff --git a/spring-cloud-commons/src/test/java/org/springframework/cloud/configuration/CompatibilityVerifierAutoConfigurationTests.java b/spring-cloud-commons/src/test/java/org/springframework/cloud/configuration/CompatibilityVerifierAutoConfigurationTests.java index <HASH>..<HASH> 100644 --- a/spring-cloud-commons/src/test/java/org/springframework/cloud/configuration/CompatibilityVerifierAutoConfigurationTests.java +++ b/spring-cloud-commons/src/test/java/org/springframework/cloud/configuration/CompatibilityVerifierAutoConfigurationTests.java @@ -20,13 +20,17 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.SpringBootVersion; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.test.context.junit4.SpringRunner; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; import static org.assertj.core.api.BDDAssertions.then; +import static org.springframework.cloud.configuration.SpringBootVersionVerifier.stripWildCardFromVersion; /** * @author Marcin Grzejszczak @@ -38,11 +42,29 @@ public class CompatibilityVerifierAutoConfigurationTests { @Autowired MyCompatibilityVerifier myMismatchVerifier; + @Autowired + CompatibilityVerifierProperties verifierProperties; + @Test public void contextLoads() { then(this.myMismatchVerifier.called).isTrue(); } + @Test + public void verifierPropertiesContainsCurrentBootVersion() { + String version = SpringBootVersion.getVersion(); + assertThat(version).isNotBlank(); + + for (String compatibleVersion : verifierProperties.getCompatibleBootVersions()) { + if (version.startsWith(stripWildCardFromVersion(compatibleVersion))) { + // success we found the current boot version in our list of compatible + // versions. + return; + } + } + fail(version + " not found in " + verifierProperties.getCompatibleBootVersions()); + } + @Configuration(proxyBeanMethods = false) @EnableAutoConfiguration static class TestConfiguration { diff --git a/spring-cloud-commons/src/test/java/org/springframework/cloud/configuration/SpringBootDependencyTests.java b/spring-cloud-commons/src/test/java/org/springframework/cloud/configuration/SpringBootDependencyTests.java index <HASH>..<HASH> 100644 --- a/spring-cloud-commons/src/test/java/org/springframework/cloud/configuration/SpringBootDependencyTests.java +++ b/spring-cloud-commons/src/test/java/org/springframework/cloud/configuration/SpringBootDependencyTests.java @@ -144,7 +144,12 @@ public class SpringBootDependencyTests { @Test public void should_match_against_current_manifest() { - List<String> acceptedVersions = Collections.singletonList("2.3"); + verifyCurrentVersionFromManifest("2.3"); + verifyCurrentVersionFromManifest("2.3.x"); + } + + private void verifyCurrentVersionFromManifest(String version) { + List<String> acceptedVersions = Collections.singletonList(version); SpringBootVersionVerifier versionVerifier = new SpringBootVersionVerifier( acceptedVersions); versionVerifier.ACCEPTED_VERSIONS.clear();
Verifies current boot version is in CompatibilityVerifierProperties. Also fixes support for wildcard <I>.x beyond boot <I>.x fixes gh-<I>
spring-cloud_spring-cloud-commons
train
36000e1c7584143ffcb481de977ae089fdff6741
diff --git a/src/video/canvas_renderer.js b/src/video/canvas_renderer.js index <HASH>..<HASH> 100644 --- a/src/video/canvas_renderer.js +++ b/src/video/canvas_renderer.js @@ -173,7 +173,7 @@ * @param {Number} y - the y position to draw at */ api.drawFont = function (fontObject, text, x, y) { - fontObject.draw(backBufferContext2D, x, y, text); + fontObject.draw(backBufferContext2D, text, x, y); }; /** diff --git a/src/video/webgl_renderer.js b/src/video/webgl_renderer.js index <HASH>..<HASH> 100644 --- a/src/video/webgl_renderer.js +++ b/src/video/webgl_renderer.js @@ -178,7 +178,7 @@ var tx1 = sx / image.width; var ty1 = 1.0 - (sy / image.height); var tx2 = ((sx + sw) / image.width); - var ty2 = 1.0 - ((sy + sw) / image.height); + var ty2 = 1.0 - ((sy + sh) / image.height); var x1 = dx; var y1 = dy;
fixed font draw, and another issue with texture coords
melonjs_melonJS
train
e15c4f42095c855802c7ead0590338f9442f5805
diff --git a/src/utils/Droppable.js b/src/utils/Droppable.js index <HASH>..<HASH> 100644 --- a/src/utils/Droppable.js +++ b/src/utils/Droppable.js @@ -41,6 +41,7 @@ export default class Droppable { sorter.endMove(); } + em.runDefault(); em.trigger('canvas:dragend', ev); } @@ -65,11 +66,14 @@ export default class Droppable { // as I need it for the Sorter context I will use `dragContent` or just // any not empty element const content = em.get('dragContent') || '<br>'; + const container = canvas.getBody(); + em.stopDefault(); if (em.inAbsoluteMode()) { const wrapper = em.get('DomComponents').getWrapper(); const target = wrapper.append({})[0]; em.get('Commands').run('core:component-drag', { + event: ev, guidesInfo: 1, center: 1, target, @@ -78,12 +82,10 @@ export default class Droppable { const comp = wrapper.append(content)[0]; const { left, top, position } = target.getStyle(); comp.setStyle({ left, top, position }); - em.setSelected(comp); + this.handleDragEnd(comp, dt); } - target.remove(); - }, - event: ev + } }); } else { this.sorter = new utils.Sorter({ @@ -92,18 +94,12 @@ export default class Droppable { nested: 1, canvasRelative: 1, direction: 'a', - container: canvas.getBody(), + container, placer: canvas.getPlacerEl(), - eventMoving: 'mousemove dragover', containerSel: '*', itemSel: '*', pfx: 'gjs-', - onStart: () => em.stopDefault(), - onEndMove: model => { - em.runDefault(); - em.set('dragResult', model); - model && em.trigger('canvas:drop', dt, model); - }, + onEndMove: model => this.handleDragEnd(model, dt), document: canvas.getFrameEl().contentDocument }); this.sorter.setDropContent(content); @@ -113,6 +109,13 @@ export default class Droppable { em.trigger('canvas:dragenter', dt, content); } + handleDragEnd(model, dt) { + if (!model) return; + const { em } = this; + em.set('dragResult', model); + em.trigger('canvas:drop', dt, model); + } + /** * Always need to have this handler active for enabling the drop * @param {Event} ev
Update handlers in Droppable
artf_grapesjs
train
5c9943466834c12dc066a1499739199c6a6a6259
diff --git a/include/font_metrics.cls.php b/include/font_metrics.cls.php index <HASH>..<HASH> 100644 --- a/include/font_metrics.cls.php +++ b/include/font_metrics.cls.php @@ -217,10 +217,19 @@ class Font_Metrics { */ static function save_font_families() { // replace the path to the DOMPDF font directories with the corresponding constants (allows for more portability) - $cache_data = var_export(self::$_font_lookup, true); - $cache_data = str_replace('\''.DOMPDF_FONT_DIR , 'DOMPDF_FONT_DIR . \'' , $cache_data); - $cache_data = str_replace('\''.DOMPDF_DIR , 'DOMPDF_DIR . \'' , $cache_data); - $cache_data = "<"."?php return $cache_data ?".">"; + $cache_data = sprintf("<?php return array (%s", PHP_EOL); + foreach (self::$_font_lookup as $family => $variants) { + $cache_data .= sprintf("'%s' => array(%s", addslashes($family), PHP_EOL); + foreach ($variants as $variant => $path) { + $path = sprintf("'%s'", $path); + $path = str_replace('\'' . DOMPDF_FONT_DIR , 'DOMPDF_FONT_DIR . \'' , $path); + $path = str_replace('\'' . DOMPDF_DIR , 'DOMPDF_DIR . \'' , $path); + $path = str_replace('\'' . strtolower(DOMPDF_DIR) , 'DOMPDF_DIR . \'' , $path); + $cache_data .= sprintf("'%s' => %s,%s", $variant, $path, PHP_EOL); + } + $cache_data .= sprintf("),%s", PHP_EOL); + } + $cache_data .= ") ?>"; file_put_contents(self::CACHE_FILE, $cache_data); } @@ -249,13 +258,18 @@ class Font_Metrics { return; } - self::$_font_lookup = require_once self::CACHE_FILE; + $cache_data = require_once self::CACHE_FILE; // If the font family cache is still in the old format if ( self::$_font_lookup === 1 ) { $cache_data = file_get_contents(self::CACHE_FILE); file_put_contents(self::CACHE_FILE, "<"."?php return $cache_data ?".">"); - self::$_font_lookup = require_once self::CACHE_FILE; + $cache_data = require_once self::CACHE_FILE; + } + + self::$_font_lookup = array(); + foreach ($cache_data as $key => $value) { + self::$_font_lookup[stripslashes($key)] = $value; } // Merge provided fonts
Safely export/eval font family cache The dompdf_font_family_cache.php file is susceptible to exploit because unfiltered user-supplied strings are present in the file. This update modifies how the file is created so that user strings are escaped and excluded from processing that is performed to improve portability.
dompdf_dompdf
train
64986c0b1a5376a257272fae63bdba077aab3c52
diff --git a/pyscroll/__init__.py b/pyscroll/__init__.py index <HASH>..<HASH> 100644 --- a/pyscroll/__init__.py +++ b/pyscroll/__init__.py @@ -2,7 +2,7 @@ from contextlib import contextmanager from pygame import Rect -__version__ = 2, 17, 8 +__version__ = 2, 17, 9 __author__ = 'bitcraft' __author_email__ = '[email protected]' __description__ = 'Pygame Scrolling - Python 2.7 & 3.3+' diff --git a/pyscroll/orthographic.py b/pyscroll/orthographic.py index <HASH>..<HASH> 100644 --- a/pyscroll/orthographic.py +++ b/pyscroll/orthographic.py @@ -124,26 +124,26 @@ class BufferedRenderer(object): dx = int(left - self._tile_view.left) dy = int(top - self._tile_view.top) - if right > mw: - left = mw - vw - self._x_offset += dx * tw - self._anchored_view = False - - elif left < 0: + if mw < vw or left < 0: left = 0 self._x_offset = x - self._half_width self._anchored_view = False - if bottom > mh: - top = mh - vh - self._y_offset += dy * th + elif right > mw: + left = mw - vw + self._x_offset += dx * tw self._anchored_view = False - elif top < 0: + if mh < vh or top < 0: top = 0 self._y_offset = y - self._half_height self._anchored_view = False + elif bottom > mh: + top = mh - vh + self._y_offset += dy * th + self._anchored_view = False + # adjust the view if the view has changed without a redraw dx = int(left - self._tile_view.left) dy = int(top - self._tile_view.top) diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -4,7 +4,7 @@ from setuptools import setup setup(name='pyscroll', - version='2.17.8', + version='2.17.9', description='Scrolling maps library for pygame and python 2.7 & 3.3+', author='bitcraft', author_email='[email protected]',
bug fix for maps smaller than the view
bitcraft_pyscroll
train
64f335c466b621fc0cba18f068773655eb10909e
diff --git a/src/test/java/io/reactivex/internal/operators/flowable/FlowableIgnoreElementsTest.java b/src/test/java/io/reactivex/internal/operators/flowable/FlowableIgnoreElementsTest.java index <HASH>..<HASH> 100644 --- a/src/test/java/io/reactivex/internal/operators/flowable/FlowableIgnoreElementsTest.java +++ b/src/test/java/io/reactivex/internal/operators/flowable/FlowableIgnoreElementsTest.java @@ -221,7 +221,7 @@ public class FlowableIgnoreElementsTest { // .ignoreElements() // - .subscribe(new ResourceCompletableObserver() { + .subscribe(new DisposableCompletableObserver() { @Override public void onComplete() { } diff --git a/src/test/java/io/reactivex/internal/operators/observable/ObservableBufferTest.java b/src/test/java/io/reactivex/internal/operators/observable/ObservableBufferTest.java index <HASH>..<HASH> 100644 --- a/src/test/java/io/reactivex/internal/operators/observable/ObservableBufferTest.java +++ b/src/test/java/io/reactivex/internal/operators/observable/ObservableBufferTest.java @@ -763,7 +763,7 @@ public class ObservableBufferTest { final Observer<Object> o = TestHelper.mockObserver(); final CountDownLatch cdl = new CountDownLatch(1); - ResourceObserver<Object> s = new ResourceObserver<Object>() { + DisposableObserver<Object> s = new DisposableObserver<Object>() { @Override public void onNext(Object t) { o.onNext(t); diff --git a/src/test/java/io/reactivex/observers/SerializedObserverTest.java b/src/test/java/io/reactivex/observers/SerializedObserverTest.java index <HASH>..<HASH> 100644 --- a/src/test/java/io/reactivex/observers/SerializedObserverTest.java +++ b/src/test/java/io/reactivex/observers/SerializedObserverTest.java @@ -375,7 +375,7 @@ public class SerializedObserverTest { AtomicInteger p2 = new AtomicInteger(); o.onSubscribe(Disposables.empty()); - ResourceObserver<String> as1 = new ResourceObserver<String>() { + DisposableObserver<String> as1 = new DisposableObserver<String>() { @Override public void onNext(String t) { o.onNext(t); @@ -392,7 +392,7 @@ public class SerializedObserverTest { } }; - ResourceObserver<String> as2 = new ResourceObserver<String>() { + DisposableObserver<String> as2 = new DisposableObserver<String>() { @Override public void onNext(String t) { o.onNext(t);
Replace 'resource' observers with plain 'disposable' observers in tests. (#<I>)
ReactiveX_RxJava
train
4bca7a447b63c6bef7c83c40d49e3db8dfbaf4fe
diff --git a/aws/sign.go b/aws/sign.go index <HASH>..<HASH> 100644 --- a/aws/sign.go +++ b/aws/sign.go @@ -199,7 +199,7 @@ func payloadHash(req *http.Request) (string, error) { return "", err } } - req.Body = ioutil.NopCloser(bytes.NewBuffer(b)) + req.Body = ioutil.NopCloser(bytes.NewReader(b)) return hash(string(b)), nil }
Use a reader for signed rquests.
aws_aws-sdk-go
train
be64e81b83a6cb7cd9ad7ae7df0eec513ae6f8c0
diff --git a/src/Orchestra/Story/Routing/HomeController.php b/src/Orchestra/Story/Routing/HomeController.php index <HASH>..<HASH> 100644 --- a/src/Orchestra/Story/Routing/HomeController.php +++ b/src/Orchestra/Story/Routing/HomeController.php @@ -29,7 +29,7 @@ class HomeController extends Controller { */ public function showPosts() { - $posts = Content::post()->publish()->paginate(Config::get('orchestra/story::per_page', 10)); + $posts = Content::post()->latestPublish()->paginate(Config::get('orchestra/story::per_page', 10)); return Facile::view('orchestra/story::posts')->with(compact('posts'))->render(); }
Fixed a bug where latest posts isn't sort by published date.
orchestral_story
train
012f40c12b36dd67274e611f4f44ed932ae155d5
diff --git a/unix_transport/unix_transport_test.go b/unix_transport/unix_transport_test.go index <HASH>..<HASH> 100644 --- a/unix_transport/unix_transport_test.go +++ b/unix_transport/unix_transport_test.go @@ -7,6 +7,7 @@ import ( "net" "net/http" "net/http/httptest" + "runtime" "strings" "github.com/nu7hatch/gouuid" @@ -22,6 +23,12 @@ var _ = Describe("Unix transport", func() { client http.Client ) + BeforeEach(func() { + if runtime.GOOS == "windows" { + Skip("Skipping Unix transport tests on Windows") + } + }) + Context("with server listening", func() { var (
Skip Unix transport tests on Windows. [#<I>]
cloudfoundry_cfhttp
train
b0b48469978af3f79f0ce6df7ddc8735aa9b8da2
diff --git a/lib/declarative_authorization/obligation_scope.rb b/lib/declarative_authorization/obligation_scope.rb index <HASH>..<HASH> 100644 --- a/lib/declarative_authorization/obligation_scope.rb +++ b/lib/declarative_authorization/obligation_scope.rb @@ -234,6 +234,7 @@ module Authorization # Parses all of the defined obligation joins and defines the scope's :joins or :includes option. # TODO: Support non-linear association paths. Right now, we just break down the longest path parsed. def rebuild_join_options! + #joins = (@proxy_options[:joins] || []) + (@proxy_options[:includes] || []) joins = @proxy_options[:joins] || [] reflections.keys.each do |path| @@ -246,13 +247,13 @@ module Authorization case [existing_join.class, path_join.class] when [Symbol, Hash] - joins[joins.index(existing_join)] = path_join + joins[joins.index(existing_join)] = path_join when [Hash, Hash] joins[joins.index(existing_join)] = path_join.deep_merge(existing_join) when [NilClass, Hash], [NilClass, Symbol] joins << path_join end - end + end case obligation_conditions.length when 0 then diff --git a/test/model_test.rb b/test/model_test.rb index <HASH>..<HASH> 100644 --- a/test/model_test.rb +++ b/test/model_test.rb @@ -992,4 +992,38 @@ class ModelTest < Test::Unit::TestCase TestModel.delete_all TestAttr.delete_all end + + def test_named_scope_with_ored_rules_and_reoccuring_tables + reader = Authorization::Reader::DSLReader.new + reader.parse %{ + authorization do + role :test_role do + has_permission_on :test_attrs, :to => :read do + if_attribute :test_another_model => { :content => 'test_1_2' }, + :test_model => { :content => 'test_1_1' } + end + has_permission_on :test_attrs, :to => :read do + if_attribute :test_another_model => { :content => 'test_2_2' }, + :test_model => { :test_attrs => contains {user.test_attr} } + end + end + end + } + Authorization::Engine.instance(reader) + + test_attr_1 = TestAttr.create!( + :test_model => TestModel.create!(:content => 'test_1_1'), + :test_another_model => TestModel.create!(:content => 'test_1_2') + ) + test_attr_2 = TestAttr.create!( + :test_model => TestModel.create!(:content => 'test_2_1'), + :test_another_model => TestModel.create!(:content => 'test_2_2') + ) + test_attr_2.test_model.test_attrs.create! + + user = MockUser.new(:test_role, :test_attr => test_attr_2.test_model.test_attrs.last) + assert_equal 2, TestAttr.with_permissions_to(:read, :user => user).length + TestModel.delete_all + TestAttr.delete_all + end end
Failing test that is fixed by glongman's patch
stffn_declarative_authorization
train
7b5f38a33b74b52c5860e7c1e56b58599e8b33f4
diff --git a/nodeconductor/iaas/tests/test_provisioning.py b/nodeconductor/iaas/tests/test_provisioning.py index <HASH>..<HASH> 100644 --- a/nodeconductor/iaas/tests/test_provisioning.py +++ b/nodeconductor/iaas/tests/test_provisioning.py @@ -98,8 +98,7 @@ class InstanceApiPermissionTest(UrlResolverMixin, test.APISimpleTestCase): data['description'] = 'changed description1' response = self.client.put(self._get_instance_url(inaccessible_instance), data) - #TODO Discuss about formularity of updates - self.assertIsNot(response.status_code, status.HTTP_200_OK) + self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND) def test_user_can_change_description_single_field_of_instance_he_is_administrator_of(self): data = {
Fix instance description change test assertions NC-<I>
opennode_waldur-core
train
2d5dcbcddedd0074572ce9aeb35b9763240c9d69
diff --git a/sprd/model/Registration.js b/sprd/model/Registration.js index <HASH>..<HASH> 100644 --- a/sprd/model/Registration.js +++ b/sprd/model/Registration.js @@ -27,8 +27,6 @@ define(["sprd/data/SprdModel", var Newsletter = Entity.inherit('sprd.model.Registration.Newsletter', { defaults: { lists: { - service: true, - survey: true, customer: true } }, @@ -44,6 +42,7 @@ define(["sprd/data/SprdModel", setListType: function (type, enabled) { this.$.lists[type] = !!enabled; }, + compose: function () { var data = this.callBase();
DEV-<I> - As a KA I want my consumers to subscribe to my newsletter
spreadshirt_rAppid.js-sprd
train
20f1218608eb339ce8dcf28f0280be30dccce618
diff --git a/src/Dialect.php b/src/Dialect.php index <HASH>..<HASH> 100644 --- a/src/Dialect.php +++ b/src/Dialect.php @@ -554,7 +554,7 @@ class Dialect */ public function isOperator($operator) { - return ($operator && $operator[0] === ':') || isset($this->_operators[$operator]); + return (is_string($operator) && $operator[0] === ':') || isset($this->_operators[$operator]); } /**
Fix a PHP <I> issue.
crysalead_sql-dialect
train
d2f329fa39ebe649c4456cf278f787e4e131e86b
diff --git a/lib/Skeleton/Pager/Web/Pager.php b/lib/Skeleton/Pager/Web/Pager.php index <HASH>..<HASH> 100644 --- a/lib/Skeleton/Pager/Web/Pager.php +++ b/lib/Skeleton/Pager/Web/Pager.php @@ -150,17 +150,6 @@ class Pager { } /** - * remove condition - * - * @access public - * @param string $field - */ - public function remove_condition($field) { - $field = $this->expand_field_name($field); - unset($this->options['conditions'][$field]); - } - - /** * Has condition * * @access public
error made by me go back to version before merge
tigron_skeleton-pager
train
5caab82485132370bbb7c8ca1a1f15d018d399f3
diff --git a/value.go b/value.go index <HASH>..<HASH> 100644 --- a/value.go +++ b/value.go @@ -1396,9 +1396,13 @@ func (vlog *valueLog) updateDiscardStats(stats map[uint32]int64) error { // flushDiscardStats inserts discard stats into badger. Returns error on failure. func (vlog *valueLog) flushDiscardStats() error { + vlog.lfDiscardStats.Lock() if len(vlog.lfDiscardStats.m) == 0 { + vlog.lfDiscardStats.Unlock() return nil } + vlog.lfDiscardStats.Unlock() + entries := []*Entry{{ Key: y.KeyWithTs(lfDiscardStatsKey, 1), Value: vlog.encodedDiscardStats(),
Fix race condition in flushDiscardStats function (#<I>) A couple of builds failed on teamcity with data race error. See <URL>
dgraph-io_badger
train
a631cf0b2882ee6f184a39d3814c3986ff9c70d3
diff --git a/state/cloudcredentials.go b/state/cloudcredentials.go index <HASH>..<HASH> 100644 --- a/state/cloudcredentials.go +++ b/state/cloudcredentials.go @@ -349,7 +349,7 @@ func (st *State) AllCloudCredentials(user names.UserTag) ([]Credential, error) { } // CredentialModels returns all models that use given cloud credential. -func (st *State) CredentialModels(tag names.CloudCredentialTag) (map[names.ModelTag]string, error) { +func (st *State) CredentialModels(tag names.CloudCredentialTag) (map[string]string, error) { coll, cleanup := st.db().GetCollection(modelsC) defer cleanup() @@ -362,9 +362,9 @@ func (st *State) CredentialModels(tag names.CloudCredentialTag) (map[names.Model return nil, errors.NotFoundf("models that use cloud credentials %q", tag.Id()) } - results := make(map[names.ModelTag]string, len(docs)) + results := make(map[string]string, len(docs)) for _, model := range docs { - results[names.NewModelTag(model.UUID)] = model.Name + results[model.UUID] = model.Name } return results, nil } @@ -372,7 +372,7 @@ func (st *State) CredentialModels(tag names.CloudCredentialTag) (map[names.Model // CredentialOwnerModelAccess stores cloud credential model information for the credential owner // or an error retrieving it. type CredentialOwnerModelAccess struct { - ModelTag names.ModelTag + ModelUUID string ModelName string OwnerAccess permission.Access Error error @@ -386,18 +386,18 @@ func (st *State) CredentialModelsAndOwnerAccess(tag names.CloudCredentialTag) ([ return nil, errors.Trace(err) } - results := []CredentialOwnerModelAccess{} - for modelTag, name := range models { - ownerAccess, err := st.UserAccess(tag.Owner(), modelTag) + var results []CredentialOwnerModelAccess + for uuid, name := range models { + ownerAccess, err := st.UserAccess(tag.Owner(), names.NewModelTag(uuid)) if err != nil { if errors.IsNotFound(err) { - results = append(results, CredentialOwnerModelAccess{ModelName: name, ModelTag: modelTag, OwnerAccess: permission.NoAccess}) + results = append(results, CredentialOwnerModelAccess{ModelName: name, ModelUUID: uuid, OwnerAccess: permission.NoAccess}) continue } - results = append(results, CredentialOwnerModelAccess{ModelName: name, ModelTag: modelTag, Error: errors.Trace(err)}) + results = append(results, CredentialOwnerModelAccess{ModelName: name, ModelUUID: uuid, Error: errors.Trace(err)}) continue } - results = append(results, CredentialOwnerModelAccess{ModelName: name, ModelTag: modelTag, OwnerAccess: ownerAccess.Access}) + results = append(results, CredentialOwnerModelAccess{ModelName: name, ModelUUID: uuid, OwnerAccess: ownerAccess.Access}) } return results, nil } diff --git a/state/credentialmodels_test.go b/state/credentialmodels_test.go index <HASH>..<HASH> 100644 --- a/state/credentialmodels_test.go +++ b/state/credentialmodels_test.go @@ -70,7 +70,7 @@ func (s *CredentialModelsSuite) TestCredentialModelsAndOwnerAccess(c *gc.C) { out, err := s.State.CredentialModelsAndOwnerAccess(s.credentialTag) c.Assert(err, jc.ErrorIsNil) c.Assert(out, gc.DeepEquals, []state.CredentialOwnerModelAccess{ - {ModelName: "abcmodel", OwnerAccess: permission.AdminAccess, ModelTag: s.abcModelTag}, + {ModelName: "abcmodel", OwnerAccess: permission.AdminAccess, ModelUUID: s.abcModelTag.Id()}, }) } @@ -85,8 +85,8 @@ func (s *CredentialModelsSuite) TestCredentialModelsAndOwnerAccessMany(c *gc.C) out, err := s.State.CredentialModelsAndOwnerAccess(s.credentialTag) c.Assert(err, jc.ErrorIsNil) c.Assert(out, gc.DeepEquals, []state.CredentialOwnerModelAccess{ - {ModelName: "abcmodel", OwnerAccess: permission.AdminAccess, ModelTag: s.abcModelTag}, - {ModelName: "xyzmodel", OwnerAccess: permission.AdminAccess, ModelTag: xyzModelTag}, + {ModelName: "abcmodel", OwnerAccess: permission.AdminAccess, ModelUUID: s.abcModelTag.Id()}, + {ModelName: "xyzmodel", OwnerAccess: permission.AdminAccess, ModelUUID: xyzModelTag.Id()}, }) } @@ -101,7 +101,7 @@ func (s *CredentialModelsSuite) TestCredentialModelsAndOwnerAccessNoModels(c *gc func (s *CredentialModelsSuite) TestCredentialModels(c *gc.C) { out, err := s.State.CredentialModels(s.credentialTag) c.Assert(err, jc.ErrorIsNil) - c.Assert(out, gc.DeepEquals, map[names.ModelTag]string{s.abcModelTag: "abcmodel"}) + c.Assert(out, gc.DeepEquals, map[string]string{s.abcModelTag.Id(): "abcmodel"}) } func (s *CredentialModelsSuite) TestCredentialNoModels(c *gc.C) {
change tag to be uuid on return.
juju_juju
train
22be5bf800f97a14e2059ce0f8bb9afece646f04
diff --git a/pypsa/networkclustering.py b/pypsa/networkclustering.py index <HASH>..<HASH> 100644 --- a/pypsa/networkclustering.py +++ b/pypsa/networkclustering.py @@ -34,7 +34,7 @@ from . import Network def _consense(x): v = x.iat[0] - assert (x == v).all() + #assert (x == v).all() return v def _haversine(coords): @@ -190,3 +190,86 @@ try: except ImportError: pass + + +################ +# k-Means clustering based on bus properties + +try: + # available using pip as scikit-learn + from sklearn.cluster import KMeans + + def busmap_by_kmeans(network,bus_weightings,n_clusters): + """ + Create a bus map from the clustering of buses in space with a weighting. + + Parameters + ---------- + network : pypsa.Network + The buses must have coordinates x,y. + bus_property : pandas.Series + Series of integer weights for buses, indexed by bus names. + n_clusters : int + Final number of clusters desired. + + Returns + ------- + busmap : pandas.Series + Mapping of network.buses to k-means clusters (indexed by non-negative integers). + + """ + + join = pd.merge(network.buses[["x","y"]],pd.DataFrame({"weighting" :bus_weightings}),how="left",left_index=True,right_index=True) + + #initial points to cluster + points = join[join["weighting"] != 0][["x","y"]].values + + #since one cannot weight points directly in k-means, just add + #additional points at same position + for i in join.index: + multiplicity = join.at[i,"weighting"] + for j in range(int(multiplicity)-1): + points = np.vstack((points,join.loc[i,["x","y"]].values)) + + kmeans = KMeans(init='k-means++', n_clusters=n_clusters) + + kmeans.fit(points) + + clusters = kmeans.cluster_centers_ + + busmap = pd.Series(data=kmeans.predict(network.buses[["x","y"]]),index=network.buses.index) + + return busmap + + def kmeans_clustering(network, bus_weightings, n_clusters): + """ + Cluster then network according to k-means clustering of the buses. + + Buses can be weighted by an integer in the series `bus_weightings`. + + Note that this clustering method completely ignores the branches of the network. + + Parameters + ---------- + network : pypsa.Network + The buses must have coordinates x,y. + bus_property : pandas.Series + Series of integer weights for buses, indexed by bus names. + n_clusters : int + Final number of clusters desired. + + Returns + ------- + Clustering : named tuple + A named tuple containing network, busmap and linemap + """ + + busmap = busmap_by_kmeans(network,bus_weightings,n_clusters) + buses, linemap, lines = get_buses_linemap_and_lines(network, busmap) + return Clustering(_build_network_from_buses_lines(buses, lines), busmap, linemap) + + + + +except ImportError: + pass
Add k-means network clustering algorithm
PyPSA_PyPSA
train
ac6cad9d7d896f810f00e4e8bbff822c19d95255
diff --git a/src/wa_kat/rest_api/to_marc.py b/src/wa_kat/rest_api/to_marc.py index <HASH>..<HASH> 100755 --- a/src/wa_kat/rest_api/to_marc.py +++ b/src/wa_kat/rest_api/to_marc.py @@ -11,16 +11,77 @@ from os.path import join from marcxml_parser import MARCXMLRecord from bottle import post +from bottle import SimpleTemplate from bottle_rest import form_to_params from shared import API_PATH +from keywords import keyword_to_info # Variables =================================================================== # Functions & classes ========================================================= +def template_context(fn): + return os.path.join( + os.path.dirname(__file__), + "../templates/", + fn + ) + + +def template(fn): + with open(template_context(fn)) as f: + return f.read() + + +def compile_keywords(keywords): + cz_keywords = [] + en_keywords = [] + for keyword in keywords: + keyword = keyword_to_info(keyword) + + if not keyword: + continue + + cz_keywords.append( + { + "uid": keyword["uid"], + "zahlavi": keyword["zahlavi"], + "zdroj": "czenas", + } + ) + if "angl_ekvivalent" in keyword: + en_keywords.append({ + "zahlavi": keyword["angl_ekvivalent"], + "zdroj": keyword.get("zdroj_angl_ekvivalentu") or "eczenas", + }) + + return cz_keywords, en_keywords + + +def render_mrc(data): + template_body = template("sablona_katalogizace_eperiodika.mrc") + + return SimpleTemplate(template_body).render(**data) + + @post(join(API_PATH, "to_marc")) @form_to_params def to_marc(data): data = json.loads(data) + if "keywords" in data: + cz_keywords, en_keywords = compile_keywords(data["keywords"]) + del data["keywords"] + + data["cz_keywords"] = cz_keywords + data["en_keywords"] = en_keywords + + data["annotation"] = data["annotation"].replace("\n", " ") + + out = { + "mrc": render_mrc(data), + } + + # with open("name") + return "ok"
#<I>: Added partialy-done function for output conversion.
WebarchivCZ_WA-KAT
train
955a693b353242f1b86b69d1a7b575082b186ae5
diff --git a/client/blocks/stats-navigation/index.js b/client/blocks/stats-navigation/index.js index <HASH>..<HASH> 100644 --- a/client/blocks/stats-navigation/index.js +++ b/client/blocks/stats-navigation/index.js @@ -14,7 +14,7 @@ import NavItem from 'components/section-nav/item'; import NavTabs from 'components/section-nav/tabs'; import Intervals from './intervals'; import FollowersCount from 'blocks/followers-count'; -import { isPluginActive } from 'state/selectors'; +import { isPluginActive, isSiteAutomatedTransfer } from 'state/selectors'; import { isJetpackSite } from 'state/sites/selectors'; import { navItems, intervals as intervalConstants } from './constants'; import { getJetpackSites } from 'state/selectors'; @@ -33,10 +33,10 @@ class StatsNavigation extends Component { }; isValidItem = item => { - const { isStore, isJetpack } = this.props; + const { isStore, isAtomic, isJetpack } = this.props; switch ( item ) { case 'activity': - return config.isEnabled( 'jetpack/activity-log' ) && isJetpack; + return config.isEnabled( 'jetpack/activity-log' ) && isJetpack && ! isAtomic; case 'store': return isStore; default: @@ -83,6 +83,7 @@ export default connect( ( state, { siteId } ) => { return { isJetpack, jetPackSites: getJetpackSites( state ), + isAtomic: isSiteAutomatedTransfer( state, siteId ), isStore: isJetpack && isPluginActive( state, siteId, 'woocommerce' ), siteId, };
Hide Activity tab in My Sites > Stats for Atomic sites (#<I>)
Automattic_wp-calypso
train
767a7f5131de3fc744e8baa2b05a00b951497e7b
diff --git a/cmd/influxd/run/command.go b/cmd/influxd/run/command.go index <HASH>..<HASH> 100644 --- a/cmd/influxd/run/command.go +++ b/cmd/influxd/run/command.go @@ -214,9 +214,8 @@ func (cmd *Command) ParseConfig(path string) (*Config, error) { var usage = `usage: run [flags] -run starts the broker and data node server. If this is the first time running -the command then a new cluster will be initialized unless the -join argument -is used. +run starts the InfluxDB server. If this is the first time running the command +then a new cluster will be initialized unless the -join argument is used. -config <path> Set the path to the configuration file.
'broker' and 'data' are obsolete
influxdata_influxdb
train
1c9e478fdc26f29fb4064e32245857dcd3175a07
diff --git a/resources/lang/mn-MN/forms.php b/resources/lang/mn-MN/forms.php index <HASH>..<HASH> 100644 --- a/resources/lang/mn-MN/forms.php +++ b/resources/lang/mn-MN/forms.php @@ -168,7 +168,7 @@ return [ 'analytics' => [ 'analytics_google' => 'Google Analytics code', 'analytics_gosquared' => 'GoSquared Analytics code', - 'analytics_piwik_url' => 'URL of your Piwik instance (without http(s)://)', + 'analytics_piwik_url' => 'URL of your Piwik instance', 'analytics_piwik_siteid' => 'Piwik\'s site id', ], 'localization' => [ @@ -229,6 +229,11 @@ return [ 'timezone' => 'Select Timezone', ], + 'seo' => [ + 'title' => 'SEO Title', + 'description' => 'SEO Description', + ], + // Buttons 'add' => 'Add', 'save' => 'Save',
New translations forms.php (Mongolian)
CachetHQ_Cachet
train
cd7637e5b6cda6014bd23bde5ebbbb87225931e3
diff --git a/src/MetaModels/DcGeneral/Dca/Builder/Builder.php b/src/MetaModels/DcGeneral/Dca/Builder/Builder.php index <HASH>..<HASH> 100644 --- a/src/MetaModels/DcGeneral/Dca/Builder/Builder.php +++ b/src/MetaModels/DcGeneral/Dca/Builder/Builder.php @@ -1170,16 +1170,18 @@ class Builder } } - if (!$command->getLabel() && !isset($extraValues['label'])) { + if (!$command->getLabel()) { $command->setLabel($operationName . '.0'); - } elseif (!$command->getLabel() && isset($extraValues['label'])) { - $command->setLabel($extraValues['label']); + if (isset($extraValues['label'])) { + $command->setLabel($extraValues['label']); + } } - if (!$command->getDescription() && !isset($extraValues['description'])) { + if (!$command->getDescription()) { $command->setDescription($operationName . '.1'); - } elseif (!$command->getDescription() && isset($extraValues['description'])) { - $command->setDescription($extraValues['description']); + if (isset($extraValues['description'])) { + $command->setDescription($extraValues['description']); + } } $extra = $command->getExtra();
Cyclomatic complexity refactoring.
MetaModels_core
train
12953ac4dce5855eb35ed7a0a7d42245ae4ba4d1
diff --git a/src/BoomCMS/Core/Auth/PermissionsProvider.php b/src/BoomCMS/Core/Auth/PermissionsProvider.php index <HASH>..<HASH> 100644 --- a/src/BoomCMS/Core/Auth/PermissionsProvider.php +++ b/src/BoomCMS/Core/Auth/PermissionsProvider.php @@ -36,7 +36,7 @@ class PermissionsProvider if ($result === null) { $page = $page->getParent(); } - } while ($result === null); + } while ($result === null && $page !== null); return (bool) $result; }
Fixed bug in page permissions check due to getParent() now returning null at root
boomcms_boom-core
train
ec60a26200e6acdd34667c887f1593128483b4e8
diff --git a/src/widgets/TextInputWidget.js b/src/widgets/TextInputWidget.js index <HASH>..<HASH> 100644 --- a/src/widgets/TextInputWidget.js +++ b/src/widgets/TextInputWidget.js @@ -127,7 +127,7 @@ OO.ui.TextInputWidget = function OoUiTextInputWidget( config ) { .append( this.$icon, this.$indicator ); this.setReadOnly( !!config.readOnly ); this.updateSearchIndicator(); - if ( config.placeholder ) { + if ( config.placeholder !== undefined ) { this.$input.attr( 'placeholder', config.placeholder ); } if ( config.maxLength !== undefined ) {
TextInputWidget: Treat empty placeholder the same in PHP and JS When placeholder is '', do not set the attribute. Issue exposed by I9a0a<I>ef<I>bbecaf<I>a<I>c1cef<I>c2. Change-Id: I2c<I>d<I>da3fac<I>a<I>bc4f<I>e<I>
wikimedia_oojs-ui
train
229ab3c2f4a2b7b7b349531ad8528372cbd65c41
diff --git a/lib/arjdbc/postgresql/adapter.rb b/lib/arjdbc/postgresql/adapter.rb index <HASH>..<HASH> 100644 --- a/lib/arjdbc/postgresql/adapter.rb +++ b/lib/arjdbc/postgresql/adapter.rb @@ -698,8 +698,6 @@ module ActiveRecord::ConnectionAdapters super # configure_connection happens in super - @table_alias_length = nil - initialize_type_map(@type_map = Type::HashLookupTypeMap.new) @use_insert_returning = @config.key?(:insert_returning) ?
[postgres] We don't need the table name length variable since we map it to the identifier length
jruby_activerecord-jdbc-adapter
train
f4714228416fe83b2c94e6f0ecb7b45d99f4f096
diff --git a/hrv/classical.py b/hrv/classical.py index <HASH>..<HASH> 100644 --- a/hrv/classical.py +++ b/hrv/classical.py @@ -4,6 +4,7 @@ import numpy as np from scipy.signal import welch from spectrum import pburg +from hrv.rri import RRi from hrv.utils import (validate_rri, _interpolate_rri, validate_frequency_domain_arguments) @@ -35,6 +36,9 @@ def frequency_domain(rri, time=None, fs=4.0, method='welch', interp_method='cubic', vlf_band=(0, 0.04), lf_band=(0.04, 0.15), hf_band=(0.15, 0.4), **kwargs): + if isinstance(rri, RRi) and time is None: + time = rri.time + if interp_method is not None: rri = _interpolate_rri(rri, time, fs, interp_method) diff --git a/tests/test_classical.py b/tests/test_classical.py index <HASH>..<HASH> 100644 --- a/tests/test_classical.py +++ b/tests/test_classical.py @@ -1,11 +1,14 @@ # coding: utf-8 -import unittest.mock +import unittest + +from unittest import mock import numpy as np from spectrum import marple_data from hrv.classical import (time_domain, frequency_domain, _auc, _poincare, _nn50, _pnn50, _calc_pburg_psd) +from hrv.rri import RRi from hrv.utils import read_from_text from tests.test_utils import FAKE_RRI @@ -91,15 +94,15 @@ class FrequencyDomainTestCase(unittest.TestCase): np.testing.assert_almost_equal(results['lfnu'], 30.5, decimal=0) np.testing.assert_almost_equal(results['hfnu'], 69.5, decimal=0) - @unittest.mock.patch('hrv.classical.pburg') + @mock.patch('hrv.classical.pburg') def test_pburg_method_being_called(self, _pburg): _calc_pburg_psd(rri=[1, 2, 3], fs=4.0) _pburg.assert_called_once_with(data=[1, 2, 3], NFFT=None, sampling=4.0, order=16) - @unittest.mock.patch('hrv.classical._auc') - @unittest.mock.patch('hrv.classical._interpolate_rri') - @unittest.mock.patch('hrv.classical._calc_pburg_psd') + @mock.patch('hrv.classical._auc') + @mock.patch('hrv.classical._interpolate_rri') + @mock.patch('hrv.classical._calc_pburg_psd') def test_frequency_domain_function_using_pburg(self, _pburg_psd, _irr, _auc): fake_rri = [1, 2, 3, 4] @@ -127,6 +130,19 @@ class FrequencyDomainTestCase(unittest.TestCase): np.testing.assert_almost_equal(np.mean(pxx), 0.400, decimal=2) + @mock.patch('hrv.classical._interpolate_rri') + def test_using_rri_class(self, _interp): + """ + Test if no time is passed as argument the frequency domain function + uses time array from RRi class + """ + _interp.return_value = [800, 810, 790, 815] + rri = RRi([800, 810, 790, 815]) + + frequency_domain(rri) + + _interp.assert_called_once_with(rri, rri.time, 4.0, 'cubic') + class NonLinearTestCase(unittest.TestCase): def test_correct_response_from_poincare(self):
Test if frequency domain is using time from RRi class
rhenanbartels_hrv
train
037fa0697dbade9a092eecf54051b43df33e0988
diff --git a/Config/bootstrap.php b/Config/bootstrap.php index <HASH>..<HASH> 100644 --- a/Config/bootstrap.php +++ b/Config/bootstrap.php @@ -1,5 +1,9 @@ <?php +Configure::write('TwigView', array( + 'Cache' => CakePlugin::path('TwigView') . 'tmp' . DS . 'views', +)); + App::uses('CakeEventManager', 'Event'); App::uses('TwigRegisterTwigExtentionsListener', 'TwigView.Event'); diff --git a/View/TwigView.php b/View/TwigView.php index <HASH>..<HASH> 100644 --- a/View/TwigView.php +++ b/View/TwigView.php @@ -16,11 +16,6 @@ */ App::uses('View', 'View'); - -if (!defined('TWIG_VIEW_CACHE')) { - define('TWIG_VIEW_CACHE', CakePlugin::path('TwigView') . 'tmp' . DS . 'views'); -} - App::uses('Twig_Loader_Cakephp', 'TwigView.Lib'); /** @@ -40,6 +35,7 @@ class TwigView extends View { * @var string */ const EXT = '.tpl'; + /** * File extension * @@ -71,7 +67,7 @@ class TwigView extends View { */ public function __construct(Controller $Controller = null) { $this->Twig = new Twig_Environment(new Twig_Loader_Cakephp(array()), array( - 'cache' => TWIG_VIEW_CACHE, + 'cache' => Configure::read('TwigView.Cache'), 'charset' => strtolower(Configure::read('App.encoding')), 'auto_reload' => Configure::read('debug') > 0, 'autoescape' => false,
Using Configure instead of a constant for the cache location
WyriHaximus_TwigView
train
cc36bcaf401cffa085d72ba704a276f61169171b
diff --git a/deliver/lib/deliver/version.rb b/deliver/lib/deliver/version.rb index <HASH>..<HASH> 100644 --- a/deliver/lib/deliver/version.rb +++ b/deliver/lib/deliver/version.rb @@ -1,4 +1,4 @@ module Deliver - VERSION = "1.12.0" + VERSION = "1.13.0" DESCRIPTION = 'Upload screenshots, metadata and your app to the App Store using a single command' end
[deliver] Version bump Changes since release <I>: * Add :itc_provider option for deliver and pilot * Ads Apple Developer Id to itunes_transporter.rb. Allows deliver to work with multiple iTunes Providers * Revert "Allow deliver to work with multiple iTunes Providers" (#<I>) * Enabled fastlane plugins for all the tools (#<I>) * Make deliver setup honor the skip_screenshots flag (#<I>)
fastlane_fastlane
train
e1948bb2de23909d4664d210bae7b6ef3f3d984f
diff --git a/source/awesome_tool/statemachine/states/execution_state.py b/source/awesome_tool/statemachine/states/execution_state.py index <HASH>..<HASH> 100644 --- a/source/awesome_tool/statemachine/states/execution_state.py +++ b/source/awesome_tool/statemachine/states/execution_state.py @@ -31,6 +31,7 @@ class ExecutionState(State, yaml.YAMLObject): State.__init__(self, name, state_id, input_keys, output_keys, outcomes, path, filename, state_type=StateType.EXECUTION, check_path=check_path) + self.logger = log.get_logger(self.name) def print_state_information(self): """Prints information about the state @@ -45,6 +46,7 @@ class ExecutionState(State, yaml.YAMLObject): """ self.script.load_and_build_module() + outcome_id = self.script.execute(self, execute_inputs, execute_outputs) if outcome_id in self.outcomes.keys(): return self.outcomes[outcome_id] diff --git a/source/awesome_tool/statemachine/states/hierarchy_state.py b/source/awesome_tool/statemachine/states/hierarchy_state.py index <HASH>..<HASH> 100644 --- a/source/awesome_tool/statemachine/states/hierarchy_state.py +++ b/source/awesome_tool/statemachine/states/hierarchy_state.py @@ -82,7 +82,9 @@ class HierarchyState(ContainerState, yaml.YAMLObject): state.input_data = state_input state.output_data = state_output #execute the state - state.run() + # TODO: test as it was before: state.run() + state.start() + state.join() self.add_state_execution_output_to_scoped_data(state.output_data, state) self.update_scoped_variables_with_output_dictionary(state.output_data, state) # not explicitly connected preempted outcomes are implicit connected to parent preempted outcome
add logger to execution state - fix bug in hierarchy state: state.start() is now called instead of state.run()
DLR-RM_RAFCON
train
bd90380bde308c57b86ce1f9a28d4fdf3780e59c
diff --git a/src/server/admin/server/api_server.go b/src/server/admin/server/api_server.go index <HASH>..<HASH> 100644 --- a/src/server/admin/server/api_server.go +++ b/src/server/admin/server/api_server.go @@ -477,7 +477,7 @@ func (a *apiServer) Restore(restoreServer admin.API_RestoreServer) (retErr error // | โ†“ | // | start/startFromURL // (reads ops from stream in a loop) | // | โ†“ | -// | validateAndApplyOp โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€-โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎ | +// | validateAndApplyOp โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎ | // | โ†“ โ†“ โ†“ โ†“ โ†“ | // | applyOp1_7 โ†’ applyOp1_8 โ†’ applyOp1_9 โ†’ applyOp1_10 โ†’ applyOp1_11 โ†’ applyOp | type restoreCtx struct {
Fix commit in admin/server/api_server.go
pachyderm_pachyderm
train
09a20e014ccef36e7dca49112b9c4e7cd923b533
diff --git a/lib/db/mongodb/schemas/content.js b/lib/db/mongodb/schemas/content.js index <HASH>..<HASH> 100644 --- a/lib/db/mongodb/schemas/content.js +++ b/lib/db/mongodb/schemas/content.js @@ -10,7 +10,8 @@ module.exports = (function(){ node : { type: ObjectId, ref: 'nodes'}, type : { type: ObjectId, ref: 'contentTypes'}, labelfield: { type: String }, - lastmodified: { type: Date, default: Date.now } + lastmodified: { type: Date, default: Date.now }, + created: { type: Date, default: Date.now } }, fields: {} },{collection: 'content'});
added a created date to the content meta data.
grasshopper-cms_grasshopper-core-nodejs
train
43ea829f507d22bb2427b8b33bab3ad49bda8250
diff --git a/lib/faraday_middleware/response/caching.rb b/lib/faraday_middleware/response/caching.rb index <HASH>..<HASH> 100644 --- a/lib/faraday_middleware/response/caching.rb +++ b/lib/faraday_middleware/response/caching.rb @@ -1,5 +1,6 @@ require 'faraday' require 'forwardable' +require 'digest/sha1' # fixes normalizing query strings: require 'faraday_middleware/addressable_patch' if defined? ::Addressable::URI @@ -66,7 +67,8 @@ module FaradayMiddleware url.query = params.any? ? build_query(params) : nil end url.normalize! - url.request_uri + + Digest::SHA1.hexdigest(url.request_uri) end def params_to_ignore diff --git a/spec/unit/caching_spec.rb b/spec/unit/caching_spec.rb index <HASH>..<HASH> 100644 --- a/spec/unit/caching_spec.rb +++ b/spec/unit/caching_spec.rb @@ -82,7 +82,7 @@ describe FaradayMiddleware::Caching do let(:options) { {:write_options => {:expires_in => 9000 } } } it "passes on the options when writing to the cache" do - expect(@cache).to receive(:write).with("/", + expect(@cache).to receive(:write).with(Digest::SHA1.hexdigest("/"), instance_of(Faraday::Response), options[:write_options]) get('/') @@ -92,7 +92,7 @@ describe FaradayMiddleware::Caching do let(:options) { {} } it "doesn't pass a third options parameter to the cache's #write" do - expect(@cache).to receive(:write).with("/", instance_of(Faraday::Response)) + expect(@cache).to receive(:write).with(Digest::SHA1.hexdigest("/"), instance_of(Faraday::Response)) get('/') end end
Hash request URIs before using them as a cache key (#<I>)
lostisland_faraday_middleware
train
21a288e27247069b6782fd985579b2170b9eae3e
diff --git a/packages/@ember/-internals/runtime/lib/system/core_object.js b/packages/@ember/-internals/runtime/lib/system/core_object.js index <HASH>..<HASH> 100644 --- a/packages/@ember/-internals/runtime/lib/system/core_object.js +++ b/packages/@ember/-internals/runtime/lib/system/core_object.js @@ -4,6 +4,7 @@ import { FACTORY_FOR } from '@ember/-internals/container'; import { assign, _WeakSet as WeakSet } from '@ember/polyfills'; +import { getOwner, setOwner } from '@ember/-internals/owner'; import { guidFor, getName, @@ -40,12 +41,14 @@ const factoryMap = new WeakMap(); const prototypeMixinMap = new WeakMap(); -let PASSED_FROM_CREATE; +let OWNER_PLACEHOLDER; +let passedFromCreate; let initCalled; // only used in debug builds to enable the proxy trap // using DEBUG here to avoid the extraneous variable when not needed if (DEBUG) { - PASSED_FROM_CREATE = Symbol(); + OWNER_PLACEHOLDER = Object.freeze({}); + passedFromCreate = new WeakSet(); initCalled = new WeakSet(); } @@ -215,7 +218,7 @@ class CoreObject { factoryMap.set(this, factory); } - constructor(properties) { + constructor(owner) { // pluck off factory let initFactory = factoryMap.get(this.constructor); if (initFactory !== undefined) { @@ -284,12 +287,20 @@ class CoreObject { m.setInitializing(); - assert( - `An EmberObject based class, ${ - this.constructor - }, was not instantiated correctly. You may have either used \`new\` instead of \`.create()\`, or not passed arguments to your call to super in the constructor: \`super(...arguments)\`. If you are trying to use \`new\`, consider using native classes without extending from EmberObject.`, - properties[PASSED_FROM_CREATE] - ); + if (DEBUG) { + assert( + `An EmberObject based class, ${ + this.constructor + }, was not instantiated correctly. You may have either used \`new\` instead of \`.create()\`, or not passed arguments to your call to super in the constructor: \`super(...arguments)\`. If you are trying to use \`new\`, consider using native classes without extending from EmberObject.`, + passedFromCreate.has(owner) || owner === OWNER_PLACEHOLDER + ); + + if (owner !== OWNER_PLACEHOLDER) { + setOwner(this, owner); + } + } else { + setOwner(this, owner); + } // only return when in debug builds and `self` is the proxy created above if (DEBUG && self !== this) { @@ -764,7 +775,22 @@ class CoreObject { */ static create(props, extra) { let C = this; - let instance = DEBUG ? new C(Object.freeze({ [PASSED_FROM_CREATE]: true })) : new C(); + + let owner = typeof props === 'object' && props !== null ? getOwner(props) : undefined; + + if (DEBUG) { + if (owner) { + passedFromCreate.add(owner); + } else { + owner = OWNER_PLACEHOLDER; + } + } + + let instance = new C(owner); + + if (DEBUG) { + passedFromCreate.delete(owner); + } if (extra === undefined) { initialize(instance, props); diff --git a/packages/@ember/-internals/runtime/tests/system/core_object_test.js b/packages/@ember/-internals/runtime/tests/system/core_object_test.js index <HASH>..<HASH> 100644 --- a/packages/@ember/-internals/runtime/tests/system/core_object_test.js +++ b/packages/@ember/-internals/runtime/tests/system/core_object_test.js @@ -29,6 +29,31 @@ moduleFor( }, /You may have either used `new` instead of `.create\(\)`/); } + ['@test tunnels the owner through to the base constructor'](assert) { + assert.expect(2); + + let owner = {}; + let props = { + someOtherProp: 'foo', + }; + + setOwner(props, owner); + + class Route extends CoreObject { + constructor() { + super(...arguments); + assert.equal( + getOwner(this), + owner, + 'owner was assigned properly in the root constructor' + ); + assert.equal(this.someOtherProp, undefined, 'other props were not yet assigned'); + } + } + + Route.create(props); + } + ['@test toString should be not be added as a property when calling toString()'](assert) { let obj = CoreObject.create({ firstName: 'Foo',
[FEATURE beta] Passes the owner through to classic classes
emberjs_ember.js
train
1925d6b139ce8b346ba4f24c47439561c459fb7d
diff --git a/vent/core/file_drop/file_drop.py b/vent/core/file_drop/file_drop.py index <HASH>..<HASH> 100644 --- a/vent/core/file_drop/file_drop.py +++ b/vent/core/file_drop/file_drop.py @@ -18,7 +18,7 @@ class GZHandler(PatternMatchingEventHandler): patterns = ["*"] # want to ignore certain pcap files from splitter as they contain junk - ignore_patterns = ["*ignore*"] + ignore_patterns = ["*-miscellaneous*"] # don't want to process files in on_modified for files that have already # been created and processed created_files = set()
update file_drop to look for new junk file naming convention
CyberReboot_vent
train
54a694124fc0b33376d2f7a1eff02e2f2f7b439f
diff --git a/lib/unicorn_wrangler.rb b/lib/unicorn_wrangler.rb index <HASH>..<HASH> 100644 --- a/lib/unicorn_wrangler.rb +++ b/lib/unicorn_wrangler.rb @@ -69,7 +69,7 @@ module UnicornWrangler report_status "Killing", reason, memory, requests, request_time - Process.kill(:QUIT, Process.pid) + Process.kill(:TERM, Process.pid) end # expensive, do not run on every request diff --git a/spec/unicorn_wrangler_spec.rb b/spec/unicorn_wrangler_spec.rb index <HASH>..<HASH> 100644 --- a/spec/unicorn_wrangler_spec.rb +++ b/spec/unicorn_wrangler_spec.rb @@ -182,7 +182,7 @@ describe UnicornWrangler do expect(stats).to receive(:increment) expect(stats).to receive(:histogram).exactly(3) - expect(Process).to receive(:kill).with(:QUIT, Process.pid) + expect(Process).to receive(:kill).with(:TERM, Process.pid) wrangler.send(:kill, :foobar, 1, 2, 3) end end
term our workers instead of graceful shutdown since they should be done at this point
grosser_unicorn_wrangler
train