hash
stringlengths 40
40
| diff
stringlengths 131
26.7k
| message
stringlengths 7
694
| project
stringlengths 5
67
| split
stringclasses 1
value | diff_languages
stringlengths 2
24
|
---|---|---|---|---|---|
b138ec60ba1aec03921c7d10f91e6b0d4f8ad402 | diff --git a/src/cart/ServerOrderPurchase.php b/src/cart/ServerOrderPurchase.php
index <HASH>..<HASH> 100644
--- a/src/cart/ServerOrderPurchase.php
+++ b/src/cart/ServerOrderPurchase.php
@@ -48,10 +48,10 @@ class ServerOrderPurchase extends AbstractServerPurchase
public function execute()
{
if (parent::execute()) {
- Yii::$app->getView()->params['remarks'][] = Yii::t('hipanel/server/order', 'You will receive an email with server access information right after setup.');
+ Yii::$app->getView()->params['remarks'][] = Yii::t('hipanel/server/order', 'You will receive an email with server access information right after setup');
if (is_array($this->_result) && isset($this->_result['_action_pending'])) {
- throw new PendingPurchaseException(Yii::t('hipanel/server/order', 'Server setup will be performed as soon as manager confirms your account verification. Please wait.'), $this->position);
+ throw new PendingPurchaseException(Yii::t('hipanel/server/order', 'Server setup will be performed as soon as manager confirms your account verification. Pleas wait.'), $this);
}
return true; | ServerOrderPurchase - fixed passing object to PendingPurchaseException | hiqdev_hipanel-module-server | train | php |
d37149bea662c8c0d0922f3461458cedd4a98074 | diff --git a/pyang/statements.py b/pyang/statements.py
index <HASH>..<HASH> 100644
--- a/pyang/statements.py
+++ b/pyang/statements.py
@@ -146,6 +146,10 @@ class Statement(object):
if len(minel) > 0 and int(minel[0].arg) > 0:
self.optional = False
return
+ subst._mark_optional()
+ if not subst.optional:
+ self.optional = False
+ return
elif subst.keyword == "uses":
ref = subst.arg
if ":" in ref: # prefixed?
@@ -158,8 +162,7 @@ class Statement(object):
grp = ext_mod.search_grouping(ident)
else:
grp = self.search_grouping(ref)
- grp._mark_optional()
- if not grp.optional:
+ if not grp.is_optional():
self.optional = False
return
self.optional = True | Corrected bug in Statement._mark_optional method. | mbj4668_pyang | train | py |
03891514fedc1653bb6418448b34e74b3b10a23b | diff --git a/lib/relations/has_many_overrides.js b/lib/relations/has_many_overrides.js
index <HASH>..<HASH> 100644
--- a/lib/relations/has_many_overrides.js
+++ b/lib/relations/has_many_overrides.js
@@ -66,7 +66,8 @@ module.exports = Mixin.create(/** @lends HasMany# */ {
* @see {@link BaseRelation#methods}
*/
save: function(instance) {
- return instance._super.apply(instance, arguments)
+ var args = _.rest(arguments);
+ return instance._super.apply(instance, args)
.tap(this._executeSaveActions.bind(this, instance));
}, | Fixed issue with arguments from previous commit. | wbyoung_azul | train | js |
4a420f77bb144916bd52f70fb077c2f19287e3da | diff --git a/spec/functional/plausibility_spec.rb b/spec/functional/plausibility_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/functional/plausibility_spec.rb
+++ b/spec/functional/plausibility_spec.rb
@@ -358,6 +358,15 @@ describe 'plausibility' do
Phony.plausible?('+599 12345678').should be_false # too long
end
+ it 'is correct for New Zeland' do
+ Phony.plausible?('+64 21 123 456').should be_true
+ Phony.plausible?('+64 21 123 4567').should be_true
+ Phony.plausible?('+64 9 379 1234').should be_true
+ Phony.plausible?('+64 21 1234 5678').should be_true
+ Phony.plausible?('+64 21 1234 56789').should be_false # to long
+ Phony.plausible?('+64 21 12345').should be_false # to short
+ end
+
it 'is correct for Nigerian numbers' do
Phony.plausible?('+234 807 766 1234').should be_true
Phony.plausible?('+234 807 766 123').should be_false | Plausibility specs for NZ phone numbers. | floere_phony | train | rb |
df15cd36ef14cfdf283d645daf1c52304225dc3b | diff --git a/tests/test_async_client.py b/tests/test_async_client.py
index <HASH>..<HASH> 100644
--- a/tests/test_async_client.py
+++ b/tests/test_async_client.py
@@ -442,7 +442,7 @@ class TestHedgehogClientAPI(object):
@pytest.mark.asyncio
async def test_speaker_action(self, connect_dummy):
- frequency = 0
+ frequency = None
async with connect_dummy(Commands.speaker_action, frequency) as client:
assert await client.set_speaker(frequency) is None
diff --git a/tests/test_sync_client.py b/tests/test_sync_client.py
index <HASH>..<HASH> 100644
--- a/tests/test_sync_client.py
+++ b/tests/test_sync_client.py
@@ -394,7 +394,7 @@ class TestHedgehogClientAPI(object):
assert client.get_imu_pose() == (x, y, z)
def test_speaker_action(self, connect_dummy):
- frequency = 0
+ frequency = None
with connect_dummy(Commands.speaker_action, frequency) as client:
assert client.set_speaker(frequency) is None | speaker now uses None instead of 0 | PRIArobotics_HedgehogClient | train | py,py |
94ad567fc4c40654f14c048099fd60cf2e7f7197 | diff --git a/src/components/Modal.js b/src/components/Modal.js
index <HASH>..<HASH> 100644
--- a/src/components/Modal.js
+++ b/src/components/Modal.js
@@ -10,7 +10,7 @@ import { polyfill } from "react-lifecycles-compat";
export const portalClassName = "ReactModalPortal";
export const bodyOpenClassName = "ReactModal__Body--open";
-const isReact16 = ReactDOM.createPortal !== undefined;
+const isReact16 = canUseDOM && ReactDOM.createPortal !== undefined;
const getCreatePortal = () =>
isReact16 | [fixed] don't access ReactDOM.createPortal if DOM not available | reactjs_react-modal | train | js |
9e3806e5a557d3041dacb34801aed3e4a1dc654e | diff --git a/setuptools/tests/test_build_meta.py b/setuptools/tests/test_build_meta.py
index <HASH>..<HASH> 100644
--- a/setuptools/tests/test_build_meta.py
+++ b/setuptools/tests/test_build_meta.py
@@ -108,7 +108,7 @@ defns = [
'setup.cfg': DALS("""
[metadata]
name = foo
- version='0.0.0'
+ version = 0.0.0
[options]
py_modules=hello | Fix syntax in test_build_meta, version should not have quotes. Bug was masked by LegacyVersion parsing. | pypa_setuptools | train | py |
68f6d836ab693e45848bbd17c5e2c42832e547b5 | diff --git a/lib/t/cli.rb b/lib/t/cli.rb
index <HASH>..<HASH> 100644
--- a/lib/t/cli.rb
+++ b/lib/t/cli.rb
@@ -557,7 +557,7 @@ module T
number = retweets.length
say "@#{@rcfile.active_profile[0]} retweeted #{pluralize(number, 'tweet')}."
say
- say "Run `#{File.basename($0)} delete status #{retweets.map(&:id).join(' ')}` to undo."
+ say "Run `#{File.basename($0)} delete status #{retweets.map{|tweet| tweet.retweeted_status.id}.join(' ')}` to undo."
end
map %w(rt) => :retweet | Display correct status ids to delete | sferik_t | train | rb |
42779f5cde97a90ebe27cb71e3ca50dd393d23ee | diff --git a/simpleai/search/viewers.py b/simpleai/search/viewers.py
index <HASH>..<HASH> 100644
--- a/simpleai/search/viewers.py
+++ b/simpleai/search/viewers.py
@@ -31,7 +31,7 @@ class BaseViewer(object):
self.successor_color = '#DD4814'
self.fringe_color = '#20a0c0'
self.solution_color = '#adeba8'
- self.font_size = 11
+ self.font_size = "11"
self.last_event = None
self.events = []
@@ -152,7 +152,8 @@ class BaseViewer(object):
g_node.set_fillcolor(self.fringe_color)
if in_fringe:
g_node.set_color(self.fringe_color)
- g_node.set_penwidth(3)
+ # TODO find a way to do this in the new graphviz version:
+ # g_node.set_penwidth(3)
if in_successors:
g_node.set_color(self.successor_color)
g_node.set_fontcolor(self.successor_color) | Changes to make it work with the new graphviz version | simpleai-team_simpleai | train | py |
ca55f860d7099851c4932174390f8f77ec30ba1e | diff --git a/jwt/verify.go b/jwt/verify.go
index <HASH>..<HASH> 100644
--- a/jwt/verify.go
+++ b/jwt/verify.go
@@ -139,7 +139,7 @@ func (t *Token) Verify(options ...Option) error {
if tv := t.issuedAt; tv != nil {
now := clock.Now().Truncate(time.Second)
ttv := tv.Time.Truncate(time.Second)
- if !now.After(ttv.Add(-1 * skew)) {
+ if now != ttv && !now.After(ttv.Add(-1 * skew)) {
return errors.New(`iat not satisfied`)
}
} | Allow iat == now (truncated to seconds) | lestrrat-go_jwx | train | go |
4fc75c1ab14d7696727fc14e3d184d3159683fec | diff --git a/angr/procedures/libc/ungetc.py b/angr/procedures/libc/ungetc.py
index <HASH>..<HASH> 100644
--- a/angr/procedures/libc/ungetc.py
+++ b/angr/procedures/libc/ungetc.py
@@ -14,6 +14,9 @@ class ungetc(angr.SimProcedure):
# TODO THIS DOESN'T WORK IN ANYTHING BUT THE TYPICAL CASE
fd_offset = io_file_data_for_arch(self.state.arch)['fd']
fileno = self.state.mem[file_ptr + fd_offset:].int.concrete
- self.state.posix.fd[fileno]._pos -= 1
+ if hasattr(self.state.posix.fd[fileno], '_read_pos'):
+ self.state.posix.fd[fileno]._read_pos -= 1
+ else:
+ self.state.posix.fd[fileno]._pos -= 1
return c & 0xff | Dumb solution to #<I> | angr_angr | train | py |
2ead8b1c9a3e85a60d511b25dda4c97f8f1fb234 | diff --git a/packages/meta/index.js b/packages/meta/index.js
index <HASH>..<HASH> 100755
--- a/packages/meta/index.js
+++ b/packages/meta/index.js
@@ -179,7 +179,7 @@ function generateMeta (_options) {
options.ogImage = false
}
} else if (typeof options.ogImage === 'string') {
- options.ogImage = {src: options.ogImage}
+ options.ogImage = {path: options.ogImage}
}
if (options.ogImage && !find(this.options.head.meta, 'property', 'og:image') && !find(this.options.head.meta, 'name', 'og:image')) {
if (options.ogHost) { | fix og:image option
please let me know if i am mistaken, what exactly the syntax is | nuxt-community_pwa-module | train | js |
72f9e29a27ed9add6347c7e0f7e0afb47943debb | diff --git a/app/models/filter.rb b/app/models/filter.rb
index <HASH>..<HASH> 100644
--- a/app/models/filter.rb
+++ b/app/models/filter.rb
@@ -39,10 +39,10 @@ class Filter < ActiveRecord::Base
prod_diff = self.products - cvd.resulting_products
repo_diff = self.repositories - cvd.repos
unless prod_diff.empty?
- errors.add(:base, _("cannot contain filters whose products do not belong this content view definition"))
+ errors.add(:base, _("cannot contain filters whose products do not belong to this content view definition"))
end
unless repo_diff.empty?
- errors.add(:base, _("cannot contain filters whose repositories do not belong this content view definition"))
+ errors.add(:base, _("cannot contain filters whose repositories do not belong to this content view definition"))
end
end | Fixed a notification message for content views. | Katello_katello | train | rb |
aff3e5a3ecbfb98b433423a487b67b39be972582 | diff --git a/sling/core/pckgmgr/src/main/java/com/composum/sling/core/pckgmgr/PackageServlet.java b/sling/core/pckgmgr/src/main/java/com/composum/sling/core/pckgmgr/PackageServlet.java
index <HASH>..<HASH> 100644
--- a/sling/core/pckgmgr/src/main/java/com/composum/sling/core/pckgmgr/PackageServlet.java
+++ b/sling/core/pckgmgr/src/main/java/com/composum/sling/core/pckgmgr/PackageServlet.java
@@ -749,7 +749,7 @@ public class PackageServlet extends AbstractServiceServlet {
RequestParameter file = parameters.getValue(AbstractServiceServlet.PARAM_FILE);
if (file != null) {
InputStream input = file.getInputStream();
- boolean force = RequestUtil.getParameter(request, PARAM_FORCE, false);
+ boolean force = RequestUtil.getParameter(request, PARAM_FORCE, true);
JcrPackageManager manager = PackageUtil.createPackageManager(request);
JcrPackage jcrPackage = manager.upload(input, force); | #<I> fix for the fix: set force to ‚true‘ by default for the ‚service‘ operation | ist-dresden_composum | train | java |
d3bced0d614e0671cce69bd58d3a3940155ec08a | diff --git a/django_enumfield/db/fields.py b/django_enumfield/db/fields.py
index <HASH>..<HASH> 100644
--- a/django_enumfield/db/fields.py
+++ b/django_enumfield/db/fields.py
@@ -77,6 +77,8 @@ class EnumField(six.with_metaclass(models.SubfieldBase, models.IntegerField)):
def deconstruct(self):
name, path, args, kwargs = super(EnumField, self).deconstruct()
path = "django.db.models.fields.IntegerField"
+ if django.VERSION >= (1, 9):
+ kwargs['enum'] = self.enum
if 'choices' in kwargs:
del kwargs['choices']
return name, path, args, kwargs | Fix deconstruct for Django <I> | 5monkeys_django-enumfield | train | py |
a954633875c5f732e6c1f107031c8a8651b65b71 | diff --git a/user/index.php b/user/index.php
index <HASH>..<HASH> 100644
--- a/user/index.php
+++ b/user/index.php
@@ -252,7 +252,18 @@
if ($roles = get_roles_used_in_context($context)) {
- foreach ($roles as $role) {
+
+ // We should exclude "admin" users (those with "doanything" at site level) because
+ // Otherwise they appear in every participant list
+
+ $sitecontext = get_context_instance(CONTEXT_SYSTEM);
+ $doanythingroles = get_roles_with_capability('moodle/site:doanything', CAP_ALLOW, $sitecontext);
+
+ foreach ($roles as $role) {
+ if (isset($doanythingroles[$role->id])) { // Avoid this role (ie admin)
+ unset($roles[$role->id]);
+ continue;
+ }
$rolenames[$role->id] = strip_tags(format_string($role->name)); // Used in menus etc later on
}
} | HIde admins from partipant listings in courses | moodle_moodle | train | php |
70de6cfa66c73a510a064c15dee9ef9132e3e299 | diff --git a/src/Bartlett/Reflect/ConsoleApplication.php b/src/Bartlett/Reflect/ConsoleApplication.php
index <HASH>..<HASH> 100644
--- a/src/Bartlett/Reflect/ConsoleApplication.php
+++ b/src/Bartlett/Reflect/ConsoleApplication.php
@@ -140,12 +140,14 @@ class ConsoleApplication extends Application
if (file_exists($manifest)) {
$out = file_get_contents($manifest);
+ $exitCode = 0;
} else {
$fmt = $this->getHelperSet()->get('formatter');
$out = $fmt->formatBlock('No manifest defined', 'error');
+ $exitCode = 1;
}
$output->writeln($out);
- return 0;
+ return $exitCode;
}
$exitCode = parent::doRun($input, $output); | fixed exit code on --manifest option | llaville_php-reflect | train | php |
d6b7eaa4ae87f0ff77092170a45626a6e4fafa72 | diff --git a/src/Resources/AbstractResource.php b/src/Resources/AbstractResource.php
index <HASH>..<HASH> 100644
--- a/src/Resources/AbstractResource.php
+++ b/src/Resources/AbstractResource.php
@@ -82,7 +82,7 @@ abstract class AbstractResource
return $this->data;
}
- protected function check()
+ public function check()
{
return $this->data !== null;
}
diff --git a/src/Resources/UserSession.php b/src/Resources/UserSession.php
index <HASH>..<HASH> 100644
--- a/src/Resources/UserSession.php
+++ b/src/Resources/UserSession.php
@@ -58,16 +58,6 @@ class UserSession extends AbstractResource
}
/**
- * Check if user is logged in
- *
- * @return boolean
- */
- public function check()
- {
- return $this->check();
- }
-
- /**
* Get logged in user data
*
* @return Array | Now can use the check method from all endpoints | updivision_matrix-php-sdk | train | php,php |
dff63a153702a6a70d10263221f51a0bd44aec3b | diff --git a/src/python/pants/option/global_options.py b/src/python/pants/option/global_options.py
index <HASH>..<HASH> 100644
--- a/src/python/pants/option/global_options.py
+++ b/src/python/pants/option/global_options.py
@@ -343,7 +343,7 @@ class GlobalOptionsRegistrar(SubsystemClientMixin, Optionable):
register('--watchman-supportdir', advanced=True, default='bin/watchman',
help='Find watchman binaries under this dir. Used as part of the path to lookup '
'the binary with --binaries-baseurls and --pants-bootstrapdir.')
- register('--watchman-startup-timeout', type=float, advanced=True, default=30.0,
+ register('--watchman-startup-timeout', type=float, advanced=True, default=60.0,
help='The watchman socket timeout (in seconds) for the initial `watch-project` command. '
'This may need to be set higher for larger repos due to watchman startup cost.')
register('--watchman-socket-timeout', type=float, advanced=True, default=0.1, | Bump the default watchman startup timeout to <I> seconds. (#<I>)
The old default of <I> seconds was sometimes not sufficient
even in a small repo like toolchain's. | pantsbuild_pants | train | py |
4919d95d4761bd1e74b387fb8e28d2177920fe29 | diff --git a/java/com/couchbase/lite/Views.java b/java/com/couchbase/lite/Views.java
index <HASH>..<HASH> 100644
--- a/java/com/couchbase/lite/Views.java
+++ b/java/com/couchbase/lite/Views.java
@@ -544,7 +544,7 @@ public class Views extends CBLiteTestCase {
emitter.emit(document.get("_id"), cost);
}
}
- }, new CBLReducer() {
+ }, new Reducer() {
@Override
public Object reduce(List<Object> keys, List<Object> values,
@@ -632,7 +632,7 @@ public class Views extends CBLiteTestCase {
key.add(document.get("track"));
emitter.emit(key, document.get("time"));
}
- }, new CBLReducer() {
+ }, new Reducer() {
@Override
public Object reduce(List<Object> keys, List<Object> values,
@@ -820,7 +820,7 @@ public class Views extends CBLiteTestCase {
}
}
- }, new CBLReducer() {
+ }, new Reducer() {
@Override
public Object reduce(List<Object> keys, List<Object> values, | CBLReducer -> Reducer | couchbase_couchbase-lite-android | train | java |
3c5d9d0701cf0c212573cc0847497eff7a7a0efc | diff --git a/code/controllers/FrontEndWorkflowController.php b/code/controllers/FrontEndWorkflowController.php
index <HASH>..<HASH> 100644
--- a/code/controllers/FrontEndWorkflowController.php
+++ b/code/controllers/FrontEndWorkflowController.php
@@ -10,6 +10,8 @@
abstract class FrontEndWorkflowController extends Controller {
public $transitionID;
+
+ protected $contextObj;
abstract function start();
@@ -44,4 +46,17 @@ abstract class FrontEndWorkflowController extends Controller {
return $form;
}
+ public function getCurrentTransition() {
+ $trans = null;
+
+ if ($this->transitionID) {
+ $trans = DataObject::get_by_id('WorkflowTransition',$this->transitionID);
+ }
+
+ return $trans;
+ }
+
+ /* Save the form Data */
+ abstract function save(array $data, Form $form, SS_HTTPRequest $request);
+
}
\ No newline at end of file | added save abstract method, and transition retrieval | symbiote_silverstripe-advancedworkflow | train | php |
9b2daf5659cd6bdf505e5f807d570f7ff3f06c72 | diff --git a/psiturk/experiment.py b/psiturk/experiment.py
index <HASH>..<HASH> 100644
--- a/psiturk/experiment.py
+++ b/psiturk/experiment.py
@@ -405,8 +405,8 @@ def start_exp():
request.user_agent.browser
platform = "UNKNOWN" if not request.user_agent.platform else \
request.user_agent.platform
- language = "UNKNOWN" if not request.user_agent.language else \
- request.user_agent.language
+ language = "UNKNOWN" if not request.accept_languages else \
+ request.accept_languages.best
# Set condition here and insert into database.
participant_attributes = dict( | better language detection (fixes #<I>) | NYUCCL_psiTurk | train | py |
a08e6a46b0a5b4561e47e89b266841121c12c53d | diff --git a/test/EventExport/PriceFormatterTest.php b/test/EventExport/PriceFormatterTest.php
index <HASH>..<HASH> 100644
--- a/test/EventExport/PriceFormatterTest.php
+++ b/test/EventExport/PriceFormatterTest.php
@@ -50,7 +50,7 @@ class PriceFormatterTest extends \PHPUnit_Framework_TestCase
[2, 10.555, '10.56'],
[2, 10.001, '10'],
[2, 10.005, '10.01'],
- [2, 0.45, '0.45']
+ [2, 0.45, '0.45'],
];
} | III-<I>: Fix minor coding standard violation: add comma behind last item of an array | cultuurnet_udb3-php | train | php |
eb212177d3537b38dbcb3c8aa1f2c7590cc40593 | diff --git a/blocks/alert/alert.ng.js b/blocks/alert/alert.ng.js
index <HASH>..<HASH> 100644
--- a/blocks/alert/alert.ng.js
+++ b/blocks/alert/alert.ng.js
@@ -16,8 +16,7 @@
$.each(ring('alerts', 'getAlertTypes')(), function (name, type) {
service[type] = function (message, opt_timeout) {
- return ring('alerts', 'add')(message, type, null,
- opt_timeout);
+ return ring('alerts', 'add')(message, type, true, opt_timeout);
};
}); | Preserve line breaks in multiline inline editor
Former-commit-id: <I>eb9d6e<I>f5ffcc8d<I>fd<I>b8f<I>d7 | JetBrains_ring-ui | train | js |
7d1ee26c9ff7360e3d0b4500adb68d1e9d2b6a84 | diff --git a/libraries/joomla/application/web.php b/libraries/joomla/application/web.php
index <HASH>..<HASH> 100644
--- a/libraries/joomla/application/web.php
+++ b/libraries/joomla/application/web.php
@@ -290,9 +290,6 @@ class JWeb
$this->loadDispatcher();
}
- // Trigger the onAfterInitialise event.
- $this->triggerEvent('onAfterInitialise');
-
return $this;
}
@@ -305,6 +302,9 @@ class JWeb
*/
public function execute()
{
+ // Trigger the onBeforeExecute event.
+ $this->triggerEvent('onBeforeExecute');
+
// Perform application routines.
$this->doExecute();
@@ -702,6 +702,7 @@ class JWeb
{
$previous = $this->config->get($key);
$this->config->set($key, $value);
+
return $previous;
}
@@ -721,6 +722,7 @@ class JWeb
{
$this->response->cachable = (bool) $allow;
}
+
return $this->response->cachable;
} | Changing onAfterInitialise to onBeforeExecute in JWeb | joomla_joomla-framework | train | php |
ce38d6c42b4dcdc43e211960d718e6dad8e3b408 | diff --git a/lib/grape/middleware/formatter.rb b/lib/grape/middleware/formatter.rb
index <HASH>..<HASH> 100644
--- a/lib/grape/middleware/formatter.rb
+++ b/lib/grape/middleware/formatter.rb
@@ -63,7 +63,7 @@ module Grape
def mime_array
accept = headers['accept'] or return []
- accept.gsub(/\b/,'').scan(%r((\w+/[\w+.-]+))).map {|(mime)|
+ accept.gsub(/\b/,'').scan(%r((\w+/[\w+.-]+)(?:(?:;[^,]*?)?;\s*q=([\d.]+))?)).sort_by { |_, q| -q.to_f }.map {|mime, _|
mime.sub(%r(vnd\.[^+]+\+), '')
}
end | Reimplement quality sorting in mime_array | ruby-grape_grape | train | rb |
0894e393e5fb2d36c9e4f523176b663618e54042 | diff --git a/gwpy/io/gwf.py b/gwpy/io/gwf.py
index <HASH>..<HASH> 100755
--- a/gwpy/io/gwf.py
+++ b/gwpy/io/gwf.py
@@ -243,7 +243,7 @@ def iter_channel_names(framefile):
an iterator that will loop over the names of channels as read from
the table of contents of the given GWF file
"""
- for name, type_ in _iter_channels(framefile):
+ for name, _ in _iter_channels(framefile):
yield name | gwpy.io.gwf: ignore second argument in iterator | gwpy_gwpy | train | py |
3c07383bfb20ca8db4266e55154d8ccdd303360f | diff --git a/src/Symfony/Components/Console/Command/HelpCommand.php b/src/Symfony/Components/Console/Command/HelpCommand.php
index <HASH>..<HASH> 100644
--- a/src/Symfony/Components/Console/Command/HelpCommand.php
+++ b/src/Symfony/Components/Console/Command/HelpCommand.php
@@ -47,11 +47,11 @@ class HelpCommand extends Command
->setHelp(<<<EOF
The <info>help</info> command displays help for a given command:
- <info>./symfony help test:all</info>
+ <info>./symfony help list</info>
You can also output the help as XML by using the <comment>--xml</comment> option:
- <info>./symfony help --xml test:all</info>
+ <info>./symfony help --xml list</info>
EOF
);
} | [Console] Removed reference to old test:all task. | symfony_symfony | train | php |
b1a7debb24a52bafeee2ffb43f8f91d22667dd10 | diff --git a/lib/octopusci/version.rb b/lib/octopusci/version.rb
index <HASH>..<HASH> 100644
--- a/lib/octopusci/version.rb
+++ b/lib/octopusci/version.rb
@@ -1,3 +1,3 @@
module Octopusci
- Version = VERSION = '0.0.7'
+ Version = VERSION = '0.0.8'
end
\ No newline at end of file | Bumped to version <I> | drewdeponte_octopusci | train | rb |
23343eb3316a3d304a3b021519b9a470f9c2446b | diff --git a/django_bcrypt/models.py b/django_bcrypt/models.py
index <HASH>..<HASH> 100644
--- a/django_bcrypt/models.py
+++ b/django_bcrypt/models.py
@@ -17,8 +17,11 @@ def bcrypt_check_password(self, raw_password):
return _check_password(self, raw_password)
def bcrypt_set_password(self, raw_password):
- salt = bcrypt.gensalt(rounds)
- self.password = 'bc$' + bcrypt.hashpw(raw_password, salt)
+ if raw_password is None:
+ self.set_unusable_password()
+ else:
+ salt = bcrypt.gensalt(rounds)
+ self.password = 'bc$' + bcrypt.hashpw(raw_password, salt)
User.check_password = bcrypt_check_password
User.set_password = bcrypt_set_password | Allow users to be created with blank (unusable) passwords. | dwaiter_django-bcrypt | train | py |
dcf6624f5249de98021d31d52b31185ebabcdccd | diff --git a/webapps/ui/cockpit/plugins/base/app/views/processInstance/userTasksTable.js b/webapps/ui/cockpit/plugins/base/app/views/processInstance/userTasksTable.js
index <HASH>..<HASH> 100644
--- a/webapps/ui/cockpit/plugins/base/app/views/processInstance/userTasksTable.js
+++ b/webapps/ui/cockpit/plugins/base/app/views/processInstance/userTasksTable.js
@@ -157,7 +157,7 @@ module.exports = function(ngModule) {
var userTask = editForm.context;
var copy = taskCopies[userTask.id];
var defaultParams = {id: userTask.id};
- var params = {userId : editForm.value};
+ var params = {userId : editForm.value || null};
TaskResource.setAssignee(defaultParams, params).$promise.then(
// success | fix(cockpit): set assignee to null when input is empty string
Related to CAM-<I> | camunda_camunda-bpm-platform | train | js |
a471f9a4ce975251b1212c451c0726e9c97d3460 | diff --git a/src/AppKernel.php b/src/AppKernel.php
index <HASH>..<HASH> 100644
--- a/src/AppKernel.php
+++ b/src/AppKernel.php
@@ -60,7 +60,7 @@ class AppKernel extends Kernel
\Symfony\Bundle\DebugBundle\DebugBundle::class,
\Symfony\Bundle\WebProfilerBundle\WebProfilerBundle::class,
\Sensio\Bundle\DistributionBundle\SensioDistributionBundle::class,
- // \Sensio\Bundle\GeneratorBundle\SensioGeneratorBundle::class,
+ \Sensio\Bundle\GeneratorBundle\SensioGeneratorBundle::class,
],
]; | CHANGE: Activates generator bundle in the AppKernel. | Katwizy_katwizy | train | php |
a6bf010e69a7d3e63da1144e0ea4130be4ba511c | diff --git a/src/AbstractDataObject.php b/src/AbstractDataObject.php
index <HASH>..<HASH> 100644
--- a/src/AbstractDataObject.php
+++ b/src/AbstractDataObject.php
@@ -458,10 +458,12 @@ abstract class AbstractDataObject extends ArrayObject implements DataObjectInter
// Iterator
// ------------------------------------------------------------------------------
+ /**
+ * @return ArrayIterator<string, mixed>
+ */
public function getIterator(): Iterator
{
return new ArrayIterator($this->attributes);
}
-
} | Added iterator docblock for better phpstan compatibility | czim_laravel-dataobject | train | php |
8fd382bfbea2ba80d4ae09d0696d6d637cf46a89 | diff --git a/lib/qs/runner.rb b/lib/qs/runner.rb
index <HASH>..<HASH> 100644
--- a/lib/qs/runner.rb
+++ b/lib/qs/runner.rb
@@ -8,13 +8,13 @@ module Qs
attr_reader :logger, :message, :params
def initialize(handler_class, args = nil)
- @handler_class = handler_class
- @handler = @handler_class.new(self)
-
args ||= {}
@logger = args[:logger] || Qs::NullLogger.new
@message = args[:message]
@params = args[:params] || {}
+
+ @handler_class = handler_class
+ @handler = @handler_class.new(self)
end
def run | hotfix - runner: build the handler last
This allows the handler's init logic and callbacks to use the
runners state. This was previously in place but was changed in the
latest round of updates. It shouldn't have been changed in the
first place.
/cc @jcredding | redding_qs | train | rb |
73528e656ec3e2c082e3aa66e823087fb3f4ee4b | diff --git a/django_deployer/providers.py b/django_deployer/providers.py
index <HASH>..<HASH> 100644
--- a/django_deployer/providers.py
+++ b/django_deployer/providers.py
@@ -21,13 +21,17 @@ class PaaSProvider(object):
setup_instructions = ""
PYVERSIONS = {}
- def init(self, site):
- self._create_configs(site)
+ @classmethod
+ def init(cls, site):
+ cls._create_configs(site)
+ print self.setup_instructions
- def deploy(self):
+ @classmethod
+ def deploy(cls):
raise NotImplementedError()
- def delete(self):
+ @classmethod
+ def delete(cls):
raise NotImplementedError()
@@ -79,14 +83,15 @@ Just a few more steps before you're ready to deploy your app!
the Stackato client, and then add the executable somewhere in your PATH.
If you're not sure where to place it, you can simply drop it in your
project's root directory (the same directory as the fabfile.py created
- by django-deployer.
+ by django-deployer).
-2. Once you've done that, target the stackto api with:
+2. Once you've done that, target the stackato api with:
stackato target api.stacka.to
and then login. You can find your sandbox password at
- https://account.activestate.com, which you'll when using the command:
+ https://account.activestate.com, which you'll need when
+ using the command:
stackato login --email <email> | Touch up stackato setup_instructions, actually print them, switch main
provider methods to classmethods | natea_django-deployer | train | py |
4d5bd451bbf41afb3031b47a7044d28966891b69 | diff --git a/tests/model/HTMLTextTest.php b/tests/model/HTMLTextTest.php
index <HASH>..<HASH> 100644
--- a/tests/model/HTMLTextTest.php
+++ b/tests/model/HTMLTextTest.php
@@ -103,6 +103,8 @@ class HTMLTextTest extends SapphireTest {
'<h1>should ignore</h1><p>First Mr. sentence. Second sentence.</p>' => 'First Mr. sentence.',
"<h1>should ignore</h1><p>Sentence with {$many}words. Second sentence.</p>"
=> "Sentence with {$many}words.",
+ '<p>This classic picture book features a repetitive format that lends itself to audience interaction. Illustrator Eric Carle submitted new, bolder artwork for the 25th anniversary edition.</p>'
+ => 'This classic picture book features a repetitive format that lends itself to audience interaction.'
);
foreach($cases as $orig => $match) { | Updated HTMLTextTest to test for correct testFirstSentence, specifically a past failing test case. fixes #<I> | silverstripe_silverstripe-framework | train | php |
ff9cc60bc75cf04aa081d8554673faad476df170 | diff --git a/shinken/modulesctx.py b/shinken/modulesctx.py
index <HASH>..<HASH> 100644
--- a/shinken/modulesctx.py
+++ b/shinken/modulesctx.py
@@ -64,7 +64,7 @@ class ModulesContext(object):
sys.path.append(mod_dir)
try:
return load_it()
- except ImportError as err:
+ except Exception as err:
logger.warning("Importing module %s failed: %s ; backtrace=%s",
mod_name, err, traceback.format_exc())
sys.path.remove(mod_dir) | Fix: imp.load_compiled/load_source can raise OSError instead of ImportError if file not found.
Just catch Exception. | Alignak-monitoring_alignak | train | py |
fc451d9cd7b5bfd13cc34668dcbbf1abe65a63f6 | diff --git a/openquake/calculators/event_based.py b/openquake/calculators/event_based.py
index <HASH>..<HASH> 100644
--- a/openquake/calculators/event_based.py
+++ b/openquake/calculators/event_based.py
@@ -431,7 +431,8 @@ class EventBasedCalculator(base.HazardCalculator):
hmap = calc.make_hmap(pmap, oq.imtls, oq.poes)
for sid in hmap:
ds[sid, s] = hmap[sid].array
- elif result and oq.maximum_intensity and oq.intensity_measure_types:
+ elif (result and oq.maximum_intensity and oq.intensity_measure_types
+ and oq.investigation_time):
logging.info('Computing mean hcurves')
with self.monitor('computing mean hcurves'):
self.datastore['hcurves-stats'] = gmvs_to_mean_hcurves( | Cleanup [skip CI] | gem_oq-engine | train | py |
9cf879c7469432adda0f2969f579d8ce70459d5e | diff --git a/dwave/cloud/package_info.py b/dwave/cloud/package_info.py
index <HASH>..<HASH> 100644
--- a/dwave/cloud/package_info.py
+++ b/dwave/cloud/package_info.py
@@ -14,7 +14,7 @@
__packagename__ = 'dwave-cloud-client'
__title__ = 'D-Wave Cloud Client'
-__version__ = '0.6.0'
+__version__ = '0.6.1'
__author__ = 'D-Wave Systems Inc.'
__description__ = 'A minimal client for interacting with D-Wave cloud resources.'
__url__ = 'https://github.com/dwavesystems/dwave-cloud-client' | Release version <I>
Changes since <I>:
- Ignore answer ETA in polling scheduling (#<I>)
- Tolerate 5xx errors during polling (#<I>) | dwavesystems_dwave-cloud-client | train | py |
ddc174897dd299654b6a37e52c4c5e57c041475a | diff --git a/pkg/identity/identity_test.go b/pkg/identity/identity_test.go
index <HASH>..<HASH> 100644
--- a/pkg/identity/identity_test.go
+++ b/pkg/identity/identity_test.go
@@ -48,7 +48,7 @@ func (s *IdentityTestSuite) TestReservedID(c *C) {
// This is an obsoleted identity, we verify that it returns 0
i = GetReservedID("cluster")
c.Assert(i, Equals, NumericIdentity(0))
- c.Assert(i.String(), Equals, "0")
+ c.Assert(i.String(), Equals, "unknown")
i = GetReservedID("health")
c.Assert(i, Equals, NumericIdentity(4))
diff --git a/pkg/identity/numericidentity.go b/pkg/identity/numericidentity.go
index <HASH>..<HASH> 100644
--- a/pkg/identity/numericidentity.go
+++ b/pkg/identity/numericidentity.go
@@ -287,6 +287,7 @@ var (
labels.IDNameRemoteNode: ReservedIdentityRemoteNode,
}
reservedIdentityNames = map[NumericIdentity]string{
+ IdentityUnknown: "unknown",
ReservedIdentityHost: labels.IDNameHost,
ReservedIdentityWorld: labels.IDNameWorld,
ReservedIdentityUnmanaged: labels.IDNameUnmanaged, | identity: Add unknown to the reserved identities
The main objective is to display a proper human-readable identity in
cilium monitor for the 0 (unknown) identity. | cilium_cilium | train | go,go |
ddb1a45e6bbdc4b2ced9d0ddd864d2cb6a2755d0 | diff --git a/flask_boost/project/application/__init__.py b/flask_boost/project/application/__init__.py
index <HASH>..<HASH> 100644
--- a/flask_boost/project/application/__init__.py
+++ b/flask_boost/project/application/__init__.py
@@ -43,7 +43,9 @@ def create_app():
app.wsgi_app = SharedDataMiddleware(app.wsgi_app, {
'/uploads': os.path.join(app.config.get('PROJECT_PATH'), 'uploads')
})
- else:
+
+ # Enable Sentry in production mode
+ if not app.debug and not app.testing:
from .utils.sentry import sentry
sentry.init_app(app, dsn=app.config.get('SENTRY_DSN'))
@@ -182,6 +184,7 @@ def register_uploadsets(app):
def register_hooks(app):
"""注册Hooks"""
+
@app.before_request
def before_request():
g.user = get_current_user() | Enable Sentry only in production mode. | hustlzp_Flask-Boost | train | py |
52289febd7a3d42c8731e0c853868597aadec12c | diff --git a/LiSE/LiSE/character.py b/LiSE/LiSE/character.py
index <HASH>..<HASH> 100644
--- a/LiSE/LiSE/character.py
+++ b/LiSE/LiSE/character.py
@@ -567,7 +567,7 @@ class Facade(AbstractCharacter, nx.DiGraph):
self.facade.node.patch(d)
def ThingPlaceMapping(self, *args):
- return CompositeDict(self.thing, self.place)
+ return CompositeDict(self.place, self.thing)
class PortalSuccessorsMapping(FacadePortalMapping):
cls = FacadePortalSuccessors | Make Facade.node set Places by default | LogicalDash_LiSE | train | py |
5a0ab70aeae647e9c19ed9f356f8bcd12d73d102 | diff --git a/index.js b/index.js
index <HASH>..<HASH> 100644
--- a/index.js
+++ b/index.js
@@ -83,11 +83,13 @@ class Cache {
this.routes[key].cacheKeyArgs.query = [ this.routes[key].cacheKeyArgs.query ]
}
- if (this.routes[key].cacheKeyArgs.headers instanceof Array)
- this.routes[key].cacheKeyArgs.headers = this.routes[key].cacheKeyArgs.headers.sort()
+ if (this.routes[key].cacheKeyArgs) {
+ if (this.routes[key].cacheKeyArgs.headers instanceof Array)
+ this.routes[key].cacheKeyArgs.headers = this.routes[key].cacheKeyArgs.headers.sort()
- if (this.routes[key].cacheKeyArgs.query instanceof Array)
- this.routes[key].cacheKeyArgs.query = this.routes[key].cacheKeyArgs.query.sort()
+ if (this.routes[key].cacheKeyArgs.query instanceof Array)
+ this.routes[key].cacheKeyArgs.query = this.routes[key].cacheKeyArgs.query.sort()
+ }
// parse caching route params
if (key.indexOf(':') !== -1) { | check if cacheKeyArgs are defined before sorting header/query arrays | mkozjak_koa-cache-lite | train | js |
afaf1321458d6ce749c4ba1cf10ad7cdce411191 | diff --git a/tools/grammar/src/test/java/org/opencypher/tools/grammar/Antlr4TestUtils.java b/tools/grammar/src/test/java/org/opencypher/tools/grammar/Antlr4TestUtils.java
index <HASH>..<HASH> 100644
--- a/tools/grammar/src/test/java/org/opencypher/tools/grammar/Antlr4TestUtils.java
+++ b/tools/grammar/src/test/java/org/opencypher/tools/grammar/Antlr4TestUtils.java
@@ -133,9 +133,9 @@ public class Antlr4TestUtils
}
@Override
- public void syntaxError( Recognizer<?,?> recognizer, Object o, int i, int i1, String s, RecognitionException e )
+ public void syntaxError( Recognizer<?,?> recognizer, Object o, int line, int charPositionInLine, String msg, RecognitionException e )
{
- fail( "syntax error in query: " + query );
+ fail( "syntax error in query at line " + line + ":" + charPositionInLine + ": " + msg + ": " + query );
}
@Override | Report details for syntax error in Antlr4 grammar tests | opencypher_openCypher | train | java |
2fa21166a99e1876c6adf3aa2da41999acf06143 | diff --git a/src/Form/FormElement/FormElement.php b/src/Form/FormElement/FormElement.php
index <HASH>..<HASH> 100644
--- a/src/Form/FormElement/FormElement.php
+++ b/src/Form/FormElement/FormElement.php
@@ -18,7 +18,7 @@ use vxPHP\Template\SimpleTemplate;
/**
* abstract base class for "simple" form elements
*
- * @version 0.12.0 2019-10-02
+ * @version 0.12.1 2020-08-11
* @author Gregor Kofler
*
*/
@@ -479,20 +479,16 @@ abstract class FormElement implements FormElementInterface {
return true;
}
- // handle a required checkboxes separately
+ // handle a required checkbox separately
- if(
- $this->required &&
- (
- (
- $this instanceof CheckboxElement &&
- !$this->getChecked()
- )
- ||
- empty($value)
- )
- ) {
- return false;
+ if($this->required) {
+ if ($this instanceof CheckboxElement) {
+ if (!$this->getChecked()) {
+ return false;
+ }
+ } else if ($value === '' || $value === null) {
+ return false;
+ }
}
// fail at the very first validator that does not validate | fix: FormElement::applyValidators() failed with required checkboxes which had no explicitly set value | Vectrex_vxPHP | train | php |
d7b1377429978a04d06dd9d0b4c073beb3c8f9dd | diff --git a/src/TemplatePassthroughManager.js b/src/TemplatePassthroughManager.js
index <HASH>..<HASH> 100644
--- a/src/TemplatePassthroughManager.js
+++ b/src/TemplatePassthroughManager.js
@@ -189,7 +189,7 @@ class TemplatePassthroughManager {
for (let path of passthroughPaths) {
let normalizedPath = this._normalizePaths(path);
debug(
- `TemplatePassthrough copying from non-matching file extension: ${normalizedPath}`
+ `TemplatePassthrough copying from non-matching file extension: ${normalizedPath.inputPath}`
);
promises.push(this.copyPath(normalizedPath));
} | Fix "[object Object]" in TemplatePassthrough debug message
Just something I noticed when running in debug mode. It's useful to see this path properly. | 11ty_eleventy | train | js |
f53811c8ba1afe4ca5f7b9d740b8220319963407 | diff --git a/closure/goog/events/actioneventwrapper.js b/closure/goog/events/actioneventwrapper.js
index <HASH>..<HASH> 100644
--- a/closure/goog/events/actioneventwrapper.js
+++ b/closure/goog/events/actioneventwrapper.js
@@ -54,9 +54,9 @@ goog.events.actionEventWrapper = new goog.events.ActionEventWrapper_();
*/
goog.events.ActionEventWrapper_.EVENT_TYPES_ = [
goog.events.EventType.CLICK,
- goog.userAgent.IE ?
- goog.events.EventType.KEYDOWN :
- goog.events.EventType.KEYPRESS
+ goog.userAgent.GECKO ?
+ goog.events.EventType.KEYPRESS :
+ goog.events.EventType.KEYDOWN
]; | Automated rollback
Reason: caused a bug
**** Original CL was
Make actionEventWrapper listen for 'keydown' only on IE. This avoids recieving extra 'keypress' events after action event has fired.
R=nicksantos
DELTA=3 (0 added, 0 deleted, 3 changed)
Revision created by MOE tool push_codebase.
MOE_MIGRATION=<I>
git-svn-id: <URL> | google_closure-library | train | js |
906551ff9032342cbc02e3550d37363157d0b9c6 | diff --git a/lib/client/affinity_group_api.rb b/lib/client/affinity_group_api.rb
index <HASH>..<HASH> 100644
--- a/lib/client/affinity_group_api.rb
+++ b/lib/client/affinity_group_api.rb
@@ -31,10 +31,12 @@ module OVIRT
end
def add_vm_to_affinity_group(affinity_group_id, vm_id, opts={})
+ cluster_id = opts[:cluster_id] || current_cluster.id
http_post("/clusters/%s/affinitygroups/%s/vms" % [cluster_id, affinity_group_id], "<vm id='%s'/>" % vm_id)
end
def delete_vm_from_affinity_group(affinity_group_id, vm_id, opts={})
+ cluster_id = opts[:cluster_id] || current_cluster.id
http_delete("/clusters/%s/affinitygroups/%s/vms/%s" % [cluster_id, affinity_group_id, vm_id])
end
end | Add cluster_id selection to add_vm_to_affinity_group and delete_vm_from_affinity_group | abenari_rbovirt | train | rb |
f1478bce2b6a9b69a7c5646ee77313c4fed6b1ec | diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -6,17 +6,17 @@ def read(fname):
setup(
name = "dockdev",
- version = "0.1.0",
+ version = "0.1.1",
author = "Ian Maddison",
author_email = "[email protected]",
description = ("A simple development setup tool for docker containerised apps"),
license = "MIT",
keywords = "docker container development setup",
- url = "http://packages.python.org/dockdev",
+ url = "https://github.com/alphagov/dockdev",
packages=['dockdev'],
scripts=['bin/dockdev'],
- install_requires=['docker-py', 'GitPython'],
- long_description=read('README'),
+ install_requires=['docker-py>=1.3.1', 'GitPython>=1.0.1'],
+ long_description=read('README.md'),
classifiers=[
"Development Status :: 4 - Beta",
"Topic :: Software Development :: Build Tools", | Explicit versions for dependencies. Prepare for next release | alphagov_dockdev | train | py |
a4bd16a6e05c71e091b2df1890357a10f43a7d3b | diff --git a/numexpr/tests/test_numexpr.py b/numexpr/tests/test_numexpr.py
index <HASH>..<HASH> 100644
--- a/numexpr/tests/test_numexpr.py
+++ b/numexpr/tests/test_numexpr.py
@@ -429,7 +429,7 @@ class test_evaluate(TestCase):
for func in vml_funcs:
strexpr = func+'(a)'
_, ex_uses_vml = numexpr.necompiler.getExprNames(strexpr, {})
- assert_equal(ex_uses_vml, True, strexpr)
+ assert_equal(ex_uses_vml, use_vml, strexpr)
if 'sparc' not in platform.machine():
# Execution order set here so as to not use too many threads | Expression can use VML only if it support for it is actually enabled | pydata_numexpr | train | py |
84b679937f220fd06b4f639320d8d992120875e5 | diff --git a/airflow/providers/tabular/hooks/tabular.py b/airflow/providers/tabular/hooks/tabular.py
index <HASH>..<HASH> 100644
--- a/airflow/providers/tabular/hooks/tabular.py
+++ b/airflow/providers/tabular/hooks/tabular.py
@@ -68,7 +68,7 @@ class TabularHook(BaseHook):
self.get_conn()
return True, "Successfully fetched token from Tabular"
except HTTPError as e:
- return False, f"HTTP Error: {e}"
+ return False, f"HTTP Error: {e}: {e.response.text}"
except Exception as e:
return False, str(e)
@@ -79,10 +79,9 @@ class TabularHook(BaseHook):
base_url = base_url.rstrip('/')
client_id = conn.login
client_secret = conn.password
- headers = {"Content-Type": "application/x-www-form-urlencoded"}
- data = {"client_id": client_id, "client_secret": client_secret}
+ data = {"client_id": client_id, "client_secret": client_secret, "grant_type": "client_credentials"}
- response = requests.post(f"{base_url}/{TOKENS_ENDPOINT}", data=data, headers=headers)
+ response = requests.post(f"{base_url}/{TOKENS_ENDPOINT}", data=data)
response.raise_for_status()
return response.json()["access_token"] | Set grant type of the Tabular hook (#<I>) | apache_airflow | train | py |
d10220b4434ec912be32c2f7a7f53db56419edae | diff --git a/resource/resourceadapters/apiserver.go b/resource/resourceadapters/apiserver.go
index <HASH>..<HASH> 100644
--- a/resource/resourceadapters/apiserver.go
+++ b/resource/resourceadapters/apiserver.go
@@ -32,7 +32,7 @@ func NewPublicFacade(st *corestate.State, _ *common.Resources, authorizer common
}
newClient := func(cURL *charm.URL, csMac *macaroon.Macaroon) (server.CharmStore, error) {
opener := newCharmstoreOpener(cURL, csMac)
- return opener.NewClient()
+ return opener.newClient()
}
facade, err := server.NewFacade(rst, newClient)
if err != nil { | Do not use the retry client for the resources facade. | juju_juju | train | go |
b3dff4690e90b1c4394969c517d5d8dc7cffdc55 | diff --git a/html/pfappserver/root/src/views/Configuration/switchGroups/_store.js b/html/pfappserver/root/src/views/Configuration/switchGroups/_store.js
index <HASH>..<HASH> 100644
--- a/html/pfappserver/root/src/views/Configuration/switchGroups/_store.js
+++ b/html/pfappserver/root/src/views/Configuration/switchGroups/_store.js
@@ -71,10 +71,13 @@ const actions = {
}
},
getSwitchGroup: ({ state, commit }, id) => {
+ commit('ITEM_REQUEST')
if (state.cache[id]) {
+ api.itemMembers(id).then(members => { // Always fetch members
+ commit('ITEM_UPDATED', { id, prop: 'members', data: members })
+ })
return Promise.resolve(state.cache[id]).then(cache => JSON.parse(JSON.stringify(cache)))
}
- commit('ITEM_REQUEST')
return api.item(id).then(item => {
commit('ITEM_REPLACED', item)
api.itemMembers(id).then(members => { // Fetch members | fix(admin(js)): ignore cache and refetch switch group members, reference #<I> | inverse-inc_packetfence | train | js |
c13e45e6c4f299e0a38a73ea9ec8d28b141702cc | diff --git a/producer_test.go b/producer_test.go
index <HASH>..<HASH> 100644
--- a/producer_test.go
+++ b/producer_test.go
@@ -279,6 +279,7 @@ func TestProducerFailureRetry(t *testing.T) {
config := NewProducerConfig()
config.FlushMsgCount = 10
config.AckSuccesses = true
+ config.RetryBackoff = 0
producer, err := NewProducer(client, config)
if err != nil {
t.Fatal(err)
@@ -357,6 +358,7 @@ func TestProducerBrokerBounce(t *testing.T) {
config := NewProducerConfig()
config.FlushMsgCount = 10
config.AckSuccesses = true
+ config.RetryBackoff = 0
producer, err := NewProducer(client, config)
if err != nil {
t.Fatal(err) | Don't use a RetryBackoff in tests
With mockbrokers we control the relevant ordering of messages and broker
starts/stops so it isn't necessary, all it does is slow down the tests and give
room for time-dependent behaviour to creep in.
Also shaves <I>ms off the test suite. | Shopify_sarama | train | go |
abb1cc28844c565ea7e4d80132f1a620e8b53443 | diff --git a/src/rendering.js b/src/rendering.js
index <HASH>..<HASH> 100644
--- a/src/rendering.js
+++ b/src/rendering.js
@@ -345,8 +345,8 @@ var Rendering = Class(Parent, function() {
*/
_buildHorizontalPath: function(nodeA, nodeB) {
const {dimensions, spacing} = this.properties.node;
- const distance = nodeB.x - nodeA.x + dimensions.width + spacing.vertical;
- const endPoint = distance - (this.properties.line.endMarker.height * this.properties.line.width);
+ const endPoint = nodeB.x - nodeA.x + dimensions.width + (this.properties.line.endMarker.width * this.properties.line.width);
+ const distance = endPoint + spacing.horizontal;
return (nodeA.y === nodeB.y)
? `M 0 0 h ${endPoint}` | fix: coordinates of an arrow to mixin | valerii-zinchenko_inheritance-diagram | train | js |
54e6ac92905924b3cc212f807dbb2e21ea157141 | diff --git a/lib/helpers/helpers-math.js b/lib/helpers/helpers-math.js
index <HASH>..<HASH> 100644
--- a/lib/helpers/helpers-math.js
+++ b/lib/helpers/helpers-math.js
@@ -41,14 +41,13 @@ var helpers = {
return Math.round(value);
},
+ // Attempt to parse the int, if not class it as 0
sum: function () {
var args = _.flatten(arguments);
var sum = 0;
var i = args.length - 1;
while (i--) {
- if ("number" === typeof args[i]) {
- sum += args[i];
- }
+ sum += _.parseInt(args[i]) || 0;
}
return Number(sum);
} | Get the sum to attempt to parse before it gives up | helpers_handlebars-helpers | train | js |
b1760815a7d2751c8ab4b45ad97f657753dc19de | diff --git a/test/integration/generated_gimarshallingtests_test.rb b/test/integration/generated_gimarshallingtests_test.rb
index <HASH>..<HASH> 100644
--- a/test/integration/generated_gimarshallingtests_test.rb
+++ b/test/integration/generated_gimarshallingtests_test.rb
@@ -727,18 +727,26 @@ describe GIMarshallingTests do
describe "its 'some-object' property" do
it "can be retrieved with #get_property" do
- skip
+ instance.get_property("some-object").must_be_nil
end
+
it "can be retrieved with #some_object" do
- skip
+ instance.some_object.must_be_nil
end
+
it "can be set with #set_property" do
- skip
+ ob = GIMarshallingTests::Object.new 42
+ instance.set_property "some-object", ob
+ instance.get_property("some-object").must_equal ob
end
+
it "can be set with #some_object=" do
- skip
+ ob = GIMarshallingTests::Object.new 42
+ instance.some_object = ob
+ instance.some_object.must_equal ob
end
end
+
describe "its 'some-strv' property" do
it "can be retrieved with #get_property" do
skip | Add tests for PropertiesObject's some-object property | mvz_gir_ffi | train | rb |
053427d24b13212ac2097137ed0d4aca7db7985c | diff --git a/aegean.py b/aegean.py
index <HASH>..<HASH> 100755
--- a/aegean.py
+++ b/aegean.py
@@ -497,9 +497,9 @@ def result_to_components(result, model, island_data, isflags):
source.psf_b = local_beam.b*3600
source.psf_pa = local_beam.pa
else:
- source.psf_a = None
- source.psf_b = None
- source.psf_pa = None
+ source.psf_a = 0
+ source.psf_b = 0
+ source.psf_pa = 0
sources.append(source)
log.debug(source) | psf is now (0,0,0) when the local beam cannot be found. | PaulHancock_Aegean | train | py |
9e76d73570e350784c10cbf4c203b94b070f94d7 | diff --git a/apps/sandbox/Module/DevModule.php b/apps/sandbox/Module/DevModule.php
index <HASH>..<HASH> 100644
--- a/apps/sandbox/Module/DevModule.php
+++ b/apps/sandbox/Module/DevModule.php
@@ -54,10 +54,11 @@ class DevModule extends AbstractModule
// install framework module
$tmpDir = dirname(__DIR__) . '/tmp';
$logDir = dirname(__DIR__) . '/log';
+ $this->bind('BEAR\Resource\Invokable')->to('BEAR\Resource\DevInvoker')->in(Scope::SINGLETON);
$this->install(new FrameworkModule($this->app, $tmpDir, $logDir));
- // install dev module
- $this->install(new TemplateEngine\DevRendererModule);
+ // install dev module
+ $this->install(new TemplateEngine\DevRendererModule);
// install application module
$this->install(new AppModule($this));
@@ -80,5 +81,7 @@ class DevModule extends AbstractModule
$this->matcher->any(),
[$logger]
);
+
+ // dev invoker
}
} | BEAR\Resource\DevInvoker in devmode.
DevInvoker records logs such as Interceptor, execution time or profile
ID. | bearsunday_BEAR.Sunday | train | php |
5d1b325b94363502bf8eb48af5e83b66599b0087 | diff --git a/app/jobs/bulk_create_media_job.rb b/app/jobs/bulk_create_media_job.rb
index <HASH>..<HASH> 100644
--- a/app/jobs/bulk_create_media_job.rb
+++ b/app/jobs/bulk_create_media_job.rb
@@ -54,6 +54,8 @@ class BulkCreateMediaJob < ApplicationJob
type: row_hash['Type (Media, Youtube)']
}
+ media_attributes = strip_attributes(media_attributes)
+
if row_hash['Type (Media, Youtube)'] == 'Media'
begin
media_attachment = zip_file.get_entry(row_hash['Filename'])
@@ -76,4 +78,11 @@ class BulkCreateMediaJob < ApplicationJob
@bulk_job.save!
end
+
+ def strip_attributes(attributes)
+ # Don't update nil attributes, but do clear out attributes with a value of 'N/A'
+ attributes.compact.transform_values do |attribute_value|
+ attribute_value == 'N/A' ? nil : attribute_value
+ end
+ end
end | feat: don't update Media records with nil CSV cell values during Bulk Upload, allow clearing of record values by specifying 'N/A' | cortex-cms_cortex | train | rb |
7312978f298752234f52b1ba018cca189467b8d9 | diff --git a/types.go b/types.go
index <HASH>..<HASH> 100644
--- a/types.go
+++ b/types.go
@@ -116,15 +116,19 @@ func MarshalAny(v interface{}) (*types.Any, error) {
// UnmarshalAny unmarshals the any type into a concrete type.
func UnmarshalAny(any *types.Any) (interface{}, error) {
- t, err := getTypeByUrl(any.TypeUrl)
+ return UnmarshalByTypeURL(any.TypeUrl, any.Value)
+}
+
+func UnmarshalByTypeURL(typeURL string, value []byte) (interface{}, error) {
+ t, err := getTypeByUrl(typeURL)
if err != nil {
return nil, err
}
v := reflect.New(t.t).Interface()
if t.isProto {
- err = proto.Unmarshal(any.Value, v.(proto.Message))
+ err = proto.Unmarshal(value, v.(proto.Message))
} else {
- err = json.Unmarshal(any.Value, v)
+ err = json.Unmarshal(value, v)
}
return v, err
} | typeurl: allow deserialization with decomposed Any | containerd_typeurl | train | go |
0f749d257bcdef7b4e88262bb3eaa0f60c289dfc | diff --git a/trunk/ipaddr.py b/trunk/ipaddr.py
index <HASH>..<HASH> 100644
--- a/trunk/ipaddr.py
+++ b/trunk/ipaddr.py
@@ -695,6 +695,9 @@ class _BaseNet(_IPAddrBase):
if other not in self:
raise ValueError('%s not contained in %s' % (str(other),
str(self)))
+ if other == self:
+ return []
+
ret_addrs = []
# Make sure we're comparing the network of other.
diff --git a/trunk/ipaddr_test.py b/trunk/ipaddr_test.py
index <HASH>..<HASH> 100755
--- a/trunk/ipaddr_test.py
+++ b/trunk/ipaddr_test.py
@@ -792,6 +792,7 @@ class IpaddrUnitTest(unittest.TestCase):
[ipaddr.IPNetwork('10.1.1.64/26'),
ipaddr.IPNetwork('10.1.1.128/25')])
self.assertRaises(ValueError, addr1.address_exclude, addr3)
+ self.assertEqual(addr1.address_exclude(addr1), [])
def testHash(self):
self.assertEquals(hash(ipaddr.IPNetwork('10.1.1.0/24')), | + fix issue where address exclude would puke if you tried to exclude
and address from itself.
git-svn-id: <URL> | google_ipaddr-py | train | py,py |
7f9a4b35c3689ec15c3ef7dbba93ca650bc0d174 | diff --git a/repository/boxnet/lib.php b/repository/boxnet/lib.php
index <HASH>..<HASH> 100644
--- a/repository/boxnet/lib.php
+++ b/repository/boxnet/lib.php
@@ -184,12 +184,14 @@ class repository_boxnet extends repository {
* @return array
*/
public function get_file($ref, $filename = '') {
+ global $CFG;
+
$ref = unserialize(self::convert_to_valid_reference($ref));
$path = $this->prepare_file($filename);
if (!empty($ref->downloadurl)) {
$c = new curl();
$result = $c->download_one($ref->downloadurl, null, array('filepath' => $filename,
- 'timeout' => self::GETFILE_TIMEOUT, 'followlocation' => true));
+ 'timeout' => $CFG->repositorygetfiletimeout, 'followlocation' => true));
$info = $c->get_info();
if ($result !== true || !isset($info['http_code']) || $info['http_code'] != 200) {
throw new moodle_exception('errorwhiledownload', 'repository', '', $result); | MDL-<I> repositories: Replaced const with configs for boxnet | moodle_moodle | train | php |
e6a29a9cffd7de1ba0391e57047c1905c513f9e4 | diff --git a/porespy/filters/__funcs__.py b/porespy/filters/__funcs__.py
index <HASH>..<HASH> 100644
--- a/porespy/filters/__funcs__.py
+++ b/porespy/filters/__funcs__.py
@@ -1542,7 +1542,10 @@ def chunked_func(func, divs=2, cores=None, im_arg=['input', 'image', 'im'],
>>> from skimage.morphology import ball
>>> im = ps.generators.blobs(shape=[100, 100, 100])
>>> f = spim.binary_dilation
- >>> im2 = ps.filters.chunked_func(func=f, input=im, structure=ball(3))
+ >>> im2 = ps.filters.chunked_func(func=f,
+ ... input=im,
+ ... structure=ball(3)) #doctest: +ELLIPSIS
+ Applying function to 8 subsections ...
>>> im3 = spim.binary_dilation(input=im, structure=ball(3))
>>> sp.all(im2 == im3)
True | Updated doctest to handle progress bar output | PMEAL_porespy | train | py |
9b166f1121fa6c4b0957b08b4439f246ddc9f155 | diff --git a/system/HTTP/DownloadResponse.php b/system/HTTP/DownloadResponse.php
index <HASH>..<HASH> 100644
--- a/system/HTTP/DownloadResponse.php
+++ b/system/HTTP/DownloadResponse.php
@@ -38,6 +38,7 @@
use CodeIgniter\HTTP\Exceptions\HTTPException;
use BadMethodCallException;
use CodeIgniter\Files\File;
+use Config\Mimes;
class DownloadResponse extends Message implements ResponseInterface
{
@@ -412,11 +413,27 @@ class DownloadResponse extends Message implements ResponseInterface
$this->setHeader('Content-Disposition', $this->getContentDisponsition());
$this->setHeader('Expires-Disposition', '0');
$this->setHeader('Content-Transfer-Encoding', 'binary');
- $this->setHeader('Content-Length', $this->getContentLength());
+ $this->setHeader('Content-Length', (string)$this->getContentLength());
$this->noCache();
}
/**
+ * output donload file text.
+ *
+ * @return DownloadResponse
+ */
+ public function sendBody()
+ {
+ if ($this->binary !== null) {
+ return $this->sendBodyByBinary();
+ } elseif ($this->file !== null) {
+ return $this->sendBodyByFilePath();
+ }
+
+ throw new RuntimeException();
+ }
+
+ /**
* output download text by file.
*
* @return string | fix: Fixed problem that header was not set correctly. | codeigniter4_CodeIgniter4 | train | php |
a67dd28329d640dfbfcad2de7cfa7eb5844e9a4f | diff --git a/dbt/model.py b/dbt/model.py
index <HASH>..<HASH> 100644
--- a/dbt/model.py
+++ b/dbt/model.py
@@ -241,11 +241,17 @@ class DBTSource(object):
return self.fqn
def tmp_name(self):
- if self.project.args.non_destructive:
+ if self.is_non_destructive():
return self.name
else:
return "{}__dbt_tmp".format(self.name)
+ def is_non_destructive(self):
+ if hasattr(self.project.args, 'non_destructive'):
+ return self.project.args.non_destructive
+ else:
+ return False
+
def rename_query(self, schema):
opts = {
"schema": schema,
@@ -368,8 +374,6 @@ class Model(DBTSource):
dist_qualifier = self.dist_qualifier(model_config)
sort_qualifier = self.sort_qualifier(model_config)
- is_non_destructive = self.project.args.non_destructive
-
if self.materialization == 'incremental':
identifier = self.name
if 'sql_where' not in model_config:
@@ -398,7 +402,7 @@ class Model(DBTSource):
"unique_key" : unique_key,
"pre-hooks" : pre_hooks,
"post-hooks" : post_hooks,
- "non_destructive": is_non_destructive
+ "non_destructive": self.is_non_destructive()
}
return create_template.wrap(opts) | fix non-destructive arg for non-run tasks | fishtown-analytics_dbt | train | py |
37aacb53b4671a18ce1bd1fec6bea33af48c9abf | diff --git a/xhtml2pdf/__init__.py b/xhtml2pdf/__init__.py
index <HASH>..<HASH> 100644
--- a/xhtml2pdf/__init__.py
+++ b/xhtml2pdf/__init__.py
@@ -41,8 +41,8 @@ try:
from xhtml2pdf.util import REPORTLAB22
if not REPORTLAB22:
- raise ImportError, "Reportlab Toolkit Version 2.2 or higher needed"
-except ImportError, e:
+ raise ImportError("Reportlab Toolkit Version 2.2 or higher needed")
+except ImportError as e:
import sys
sys.stderr.write(REQUIRED_INFO % e) | compatibility with python 3.x
using "as" keyword instead of comma in except statement | xhtml2pdf_xhtml2pdf | train | py |
3edb26ab764210b24579acba336bcb48729d5c0c | diff --git a/spec/record_spec.rb b/spec/record_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/record_spec.rb
+++ b/spec/record_spec.rb
@@ -802,6 +802,7 @@ RSpec.describe AttrJson::Record do
instance.save
found_record = klass.find(instance.id)
expect(found_record.attributes["str"]).to eq ['foo']
+ expect(found_record.str_changed?).to be(false)
end
end
end | test for not changed, since that's something we had to code for | jrochkind_attr_json | train | rb |
ef90a32696300361225ea6f0de203f0efff19337 | diff --git a/core/codegen/isagen/src/test/java/org/overturetool/cgisa/BinaryExpTest.java b/core/codegen/isagen/src/test/java/org/overturetool/cgisa/BinaryExpTest.java
index <HASH>..<HASH> 100644
--- a/core/codegen/isagen/src/test/java/org/overturetool/cgisa/BinaryExpTest.java
+++ b/core/codegen/isagen/src/test/java/org/overturetool/cgisa/BinaryExpTest.java
@@ -49,7 +49,10 @@ public class BinaryExpTest extends AbsExpTest
Object[] a3 = { "1*1", "(1 * 1)" };
Object[] a4 = { "1/1", "(1 / 1)" };
- return Arrays.asList(new Object[][] { a1, a2, a3,a4 });
+ Object[] a5 = { "1>1", "(1 > 1)" };
+ Object[] a6 = { "1<>1", "(1 <> 1)" };
+
+ return Arrays.asList(new Object[][] { a1, a2, a3,a4,a5,a6});
} | Add expressions tests for > and <> exps. | overturetool_overture | train | java |
024cc9e781c0710f70572b66bf49415a33856c6a | diff --git a/BackofficeBundle/Resources/public/ecmascript/OpenOrchestra/Application/View/Site/SiteFormView.js b/BackofficeBundle/Resources/public/ecmascript/OpenOrchestra/Application/View/Site/SiteFormView.js
index <HASH>..<HASH> 100644
--- a/BackofficeBundle/Resources/public/ecmascript/OpenOrchestra/Application/View/Site/SiteFormView.js
+++ b/BackofficeBundle/Resources/public/ecmascript/OpenOrchestra/Application/View/Site/SiteFormView.js
@@ -56,7 +56,7 @@ class SiteFormView extends mix(AbstractFormView).with(FormViewButtonsMixin)
let statusCodeForm = {
'422': $.proxy(this.refreshRender, this),
'200': Application.getContext().refreshContext,
- '201': Application.getContext().refreshContext
+ '201': $.proxy(this._redirectEditElement, this)
};
if ($(event.currentTarget).hasClass('submit-continue-form')) {
@@ -80,7 +80,8 @@ class SiteFormView extends mix(AbstractFormView).with(FormViewButtonsMixin)
siteId: siteId
});
Backbone.Events.trigger('form:deactivate', this);
- Backbone.history.navigate(url, true);
+ Backbone.history.navigate(url);
+ Application.getContext().refreshContext();
}
/** | fix redirect site with refresh context (#<I>) | open-orchestra_open-orchestra-cms-bundle | train | js |
9d9a9ac555ae479d93ea1fa4f504e0dbff6043af | diff --git a/user/users.go b/user/users.go
index <HASH>..<HASH> 100644
--- a/user/users.go
+++ b/user/users.go
@@ -330,15 +330,15 @@ func (m *DefaultManager) cleanupOrgUsers(uaaUsers *uaa.Users, input *config.OrgC
lo.G.Debugf("Users In Roles %+v", usersInRoles)
for _, orgUser := range orgUsers {
- uaaUser := uaaUsers.GetByID(orgUser.Guid)
+ uaaUser := uaaUsers.GetByID(orgUser.Username)
var guid string
if uaaUser == nil {
- lo.G.Infof("Unable to find users (%s) GUID from uaa using org user guid", orgUser)
+ lo.G.Infof("Unable to find users (%s) GUID from uaa using org user guid instead", orgUser)
guid = orgUser.Guid
} else {
- guid = orgUser.Guid
+ guid = uaaUser.GUID
}
- if !usersInRoles.HasUser(uaaUser.Username) {
+ if !usersInRoles.HasUser(orgUser.Username) {
if m.Peek {
lo.G.Infof("[dry-run]: Removing User %s from org %s", orgUser.Username, input.Org)
continue | address issue where org user cannot be found in uaa users - <URL> | pivotalservices_cf-mgmt | train | go |
0cbfdf09cd50fb51c254ed69adee13fc57108482 | diff --git a/lib/utils.js b/lib/utils.js
index <HASH>..<HASH> 100644
--- a/lib/utils.js
+++ b/lib/utils.js
@@ -84,6 +84,7 @@ module.exports.fileCommandJson = function(notifier, options, cb) {
}
return cp.execFile(notifier, options, function(error, stdout, stderr) {
if (error) return cb(error, stdout);
+ if (!stdout) return cb(error, {});
try {
var data = JSON.parse(stdout); | Fixes issue with non json output for macOS | mikaelbr_node-notifier | train | js |
6442bd4a6fac193710a26b1467dd104bb9a79a60 | diff --git a/go/mysql/server_test.go b/go/mysql/server_test.go
index <HASH>..<HASH> 100644
--- a/go/mysql/server_test.go
+++ b/go/mysql/server_test.go
@@ -1310,7 +1310,7 @@ func TestListenerShutdown(t *testing.T) {
Uname: "user1",
Pass: "password1",
}
- initialconnRefuse := connRefuse.Get()
+ connRefuse.Reset()
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
@@ -1326,9 +1326,7 @@ func TestListenerShutdown(t *testing.T) {
l.Shutdown()
- if connRefuse.Get()-initialconnRefuse != 1 {
- t.Errorf("Expected connRefuse delta=1, got %d", connRefuse.Get()-initialconnRefuse)
- }
+ assert.EqualValues(t, 1, connRefuse.Get(), "connRefuse")
if err := conn.Ping(); err != nil {
sqlErr, ok := err.(*SQLError) | tests: reset stat at the beginning of test | vitessio_vitess | train | go |
e5465f90f237c5b85e4feb80c3ced24d12fdf43f | diff --git a/outbound/hmail.js b/outbound/hmail.js
index <HASH>..<HASH> 100644
--- a/outbound/hmail.js
+++ b/outbound/hmail.js
@@ -124,6 +124,7 @@ HMailItem.prototype.read_todo = function () {
self.todo = JSON.parse(todo);
self.todo.rcpt_to = self.todo.rcpt_to.map(function (a) { return new Address (a); });
self.todo.mail_from = new Address (self.todo.mail_from);
+ self.todo.notes = new Notes(self.todo.notes);
self.emit('ready');
}
}); | notes needs get/set after JSON round trip (#<I>) | haraka_Haraka | train | js |
f986d0d6bba5c905950873e5cf275f13b14c655c | diff --git a/raven/contrib/flask/__init__.py b/raven/contrib/flask/__init__.py
index <HASH>..<HASH> 100644
--- a/raven/contrib/flask/__init__.py
+++ b/raven/contrib/flask/__init__.py
@@ -48,6 +48,7 @@ class Sentry(object):
servers=app.config.get('SENTRY_SERVERS'),
name=app.config.get('SENTRY_NAME'),
key=app.config.get('SENTRY_KEY'),
+ site=app.config.get('SENTRY_SITE_NAME'),
)
else:
client = self.client | Add config variable SENTRY_SITE_NAME for the flask integration to set a site name for the application. | elastic_apm-agent-python | train | py |
208b8a349c24bcd9300740d3c8815acd440864f0 | diff --git a/raft/raft.go b/raft/raft.go
index <HASH>..<HASH> 100644
--- a/raft/raft.go
+++ b/raft/raft.go
@@ -607,14 +607,14 @@ func (r *raft) maybeCommit() bool {
if cap(r.matchBuf) < len(r.prs) {
r.matchBuf = make(uint64Slice, len(r.prs))
}
- mis := r.matchBuf[:len(r.prs)]
+ r.matchBuf = r.matchBuf[:len(r.prs)]
idx := 0
for _, p := range r.prs {
- mis[idx] = p.Match
+ r.matchBuf[idx] = p.Match
idx++
}
- sort.Sort(mis)
- mci := mis[len(mis)-r.quorum()]
+ sort.Sort(&r.matchBuf)
+ mci := r.matchBuf[len(r.matchBuf)-r.quorum()]
return r.raftLog.maybeCommit(mci, r.Term)
} | raft: Avoid allocation when boxing slice in maybeCommit
By boxing a heap-allocated slice header instead of the slice
header on the stack, we can avoid an allocation when passing
through the sort.Interface interface.
This was responsible for <I>% of total allocations in an
experiment with <URL> | etcd-io_etcd | train | go |
f0de2caff79332cfcc204c290606c29e5beb4dcb | diff --git a/src/main/java/com/semanticcms/autogit/servlet/AutoGit.java b/src/main/java/com/semanticcms/autogit/servlet/AutoGit.java
index <HASH>..<HASH> 100644
--- a/src/main/java/com/semanticcms/autogit/servlet/AutoGit.java
+++ b/src/main/java/com/semanticcms/autogit/servlet/AutoGit.java
@@ -305,7 +305,7 @@ public class AutoGit {
// Empty lock class to help heap profile
}
private final ChangedLock changedLock = new ChangedLock();
- private boolean changed = false;
+ private boolean changed;
@SuppressWarnings({"SleepWhileInLoop", "UseSpecificCatch", "TooBroadCatch"})
private final Runnable watcherRunnable = () -> { | Performed automatic clean-up with org.openrewrite.java.cleanup.Cleanup | aoindustries_semanticcms-autogit-servlet | train | java |
a7f3cc6d884da8709210c64a561b80d773c7387a | diff --git a/base-server.js b/base-server.js
index <HASH>..<HASH> 100644
--- a/base-server.js
+++ b/base-server.js
@@ -1,3 +1,5 @@
+'use strict'
+
var ServerConnection = require('logux-sync').ServerConnection
var MemoryStore = require('logux-core').MemoryStore
var WebSocket = require('ws')
diff --git a/client.js b/client.js
index <HASH>..<HASH> 100644
--- a/client.js
+++ b/client.js
@@ -1,3 +1,5 @@
+'use strict'
+
var ServerSync = require('logux-sync').ServerSync
var SyncError = require('logux-sync').SyncError
var semver = require('semver')
diff --git a/server.js b/server.js
index <HASH>..<HASH> 100644
--- a/server.js
+++ b/server.js
@@ -1,3 +1,5 @@
+'use strict'
+
var BaseServer = require('./base-server')
var errorReporter = require('./reporters/human/error')
var processReporter = require('./reporters/human/process') | Try to fix node.js 4 support | logux_server | train | js,js,js |
8e38b2411b79f46dfbdafd9b24b7b4d121ee2cb6 | diff --git a/nanoget/extraction_functions.py b/nanoget/extraction_functions.py
index <HASH>..<HASH> 100644
--- a/nanoget/extraction_functions.py
+++ b/nanoget/extraction_functions.py
@@ -154,7 +154,11 @@ def process_bam(bam, **kwargs):
logging.info("Nanoget: Starting to collect statistics from bam file {}.".format(bam))
samfile = check_bam(bam)
chromosomes = samfile.references
- params = zip([bam] * len(chromosomes), chromosomes)
+ if len(chromosomes) > 100:
+ params = [(bam, None)]
+ logging.info("Nanoget: lots of contigs (>100), not running in separate processes")
+ else:
+ params = zip([bam] * len(chromosomes), chromosomes)
with cfutures.ProcessPoolExecutor(max_workers=kwargs["threads"]) as executor:
datadf = pd.DataFrame(
data=[res for sublist in executor.map(extract_from_bam, params) for res in sublist],
diff --git a/nanoget/version.py b/nanoget/version.py
index <HASH>..<HASH> 100644
--- a/nanoget/version.py
+++ b/nanoget/version.py
@@ -1 +1 @@
-__version__ = "1.10.0"
+__version__ = "1.11.0" | if ><I> contigs in bam, don't parse per contig but just one process
should solve long runtimes seen in
<URL> | wdecoster_nanoget | train | py,py |
9b77039ac64f1dcc955f51f512a0a305ae4c7170 | diff --git a/pandas/tests/indexing/test_iloc.py b/pandas/tests/indexing/test_iloc.py
index <HASH>..<HASH> 100644
--- a/pandas/tests/indexing/test_iloc.py
+++ b/pandas/tests/indexing/test_iloc.py
@@ -21,11 +21,13 @@ from pandas import (
Interval,
NaT,
Series,
+ Timestamp,
array,
concat,
date_range,
interval_range,
isna,
+ to_datetime,
)
import pandas._testing as tm
from pandas.api.types import is_scalar
@@ -1196,6 +1198,23 @@ class TestiLocBaseIndependent:
arr[2] = arr[-1]
assert ser[0] == arr[-1]
+ def test_iloc_setitem_multicolumn_to_datetime(self, using_array_manager):
+
+ # GH#20511
+ df = DataFrame({"A": ["2022-01-01", "2022-01-02"], "B": ["2021", "2022"]})
+
+ df.iloc[:, [0]] = DataFrame({"A": to_datetime(["2021", "2022"])})
+ expected = DataFrame(
+ {
+ "A": [
+ Timestamp("2021-01-01 00:00:00"),
+ Timestamp("2022-01-01 00:00:00"),
+ ],
+ "B": ["2021", "2022"],
+ }
+ )
+ tm.assert_frame_equal(df, expected, check_dtype=using_array_manager)
+
class TestILocErrors:
# NB: this test should work for _any_ Series we can pass as | TST: Assign back multiple column to datetime (#<I>) | pandas-dev_pandas | train | py |
19e7c29765732d49661b6644bdca1c9fc77660d4 | diff --git a/ui/src/mixins/virtual-scroll.js b/ui/src/mixins/virtual-scroll.js
index <HASH>..<HASH> 100644
--- a/ui/src/mixins/virtual-scroll.js
+++ b/ui/src/mixins/virtual-scroll.js
@@ -282,6 +282,11 @@ export default {
}
this.prevScrollStart = void 0
+ if (scrollDetails.scrollMaxSize <= 0) {
+ this.__setVirtualScrollSliceRange(scrollEl, scrollDetails, 0, 0)
+ return
+ }
+
this.__scrollViewSize !== scrollDetails.scrollViewSize && this.__setVirtualScrollSize(scrollDetails.scrollViewSize)
this.__updateVirtualScrollSizes(this.virtualScrollSliceRange.from) | fix(VirtualScroll): consider the case when the scrollEl has no height #<I> (#<I>)
* fix(VirtualScroll): consider the case when the scrollEl has no height #<I>
* Update virtual-scroll.js | quasarframework_quasar | train | js |
e92f41f52ca061f3288e55b92a3c1a1d0cb3477f | diff --git a/Gruntfile.js b/Gruntfile.js
index <HASH>..<HASH> 100644
--- a/Gruntfile.js
+++ b/Gruntfile.js
@@ -96,7 +96,7 @@ module.exports = function (grunt) {
'dist/*.css'
]
}, {
- src: ['plugin/*.js'],
+ src: ['plugin/**/*.js', 'lang/**/*.js'],
dest: 'dist/'
}]
} | Include plugin and lang files to zip file. | summernote_summernote | train | js |
9f29202c6e27b5543c58bb3a70f70a319d94d193 | diff --git a/embypy/emby.py b/embypy/emby.py
index <HASH>..<HASH> 100644
--- a/embypy/emby.py
+++ b/embypy/emby.py
@@ -52,6 +52,9 @@ class Emby(objects.EmbyObject):
items.append(self.process(item))
return items
+ def update(self):
+ self.extras = {}
+
@property
def albums(self):
items = self.extras.get('albums', []) | overloaded clearing function for main emby obj | andy29485_embypy | train | py |
43fdbe9c621f1f712131c6a338bb5421da67fc17 | diff --git a/extensions/data/behavior/Tree.php b/extensions/data/behavior/Tree.php
index <HASH>..<HASH> 100644
--- a/extensions/data/behavior/Tree.php
+++ b/extensions/data/behavior/Tree.php
@@ -137,7 +137,10 @@ class Tree extends \li3_behaviors\data\model\Behavior {
$data[] = $entity;
$data = array_reverse($data);
$model = $entity->model();
- return $model::connection()->item($model, $data, ['exists' => true, 'class' => 'set']);
+ return $model::create($data, [
+ 'exists' => true,
+ 'class' => 'set'
+ ]);
}
/** | Update itemization according the last changes in the core. | jails_li3_tree | train | php |
5bfda28d39d4dacb2dbf51751883880a6e5931df | diff --git a/cake/console/cake.php b/cake/console/cake.php
index <HASH>..<HASH> 100644
--- a/cake/console/cake.php
+++ b/cake/console/cake.php
@@ -25,6 +25,9 @@
* @lastmodified $Date$
* @license http://www.opensource.org/licenses/mit-license.php The MIT License
*/
+if (!defined('E_DEPRECATED')) {
+ define('E_DEPRECATED', 8192);
+}
/**
* Shell dispatcher
* | Adding E_DEPRECATED to console environment. | cakephp_cakephp | train | php |
1b1851fe71794a37e9fa22ebde37c870a710a187 | diff --git a/internal/services/bot/bot_service_azure_bot_resource_test.go b/internal/services/bot/bot_service_azure_bot_resource_test.go
index <HASH>..<HASH> 100644
--- a/internal/services/bot/bot_service_azure_bot_resource_test.go
+++ b/internal/services/bot/bot_service_azure_bot_resource_test.go
@@ -47,9 +47,9 @@ func TestAccBotServiceAzureBot_completeUpdate(t *testing.T) {
},
data.ImportStep(),
{
- Config: r.completeUpdate(data),
+ Config: r.update(data),
Check: acceptance.ComposeTestCheckFunc(
- check.That(data.ResourceType).ExistsInAzure(r),
+ check.That(data.ResourceName).ExistsInAzure(r),
),
},
data.ImportStep(),
@@ -99,7 +99,7 @@ resource "azurerm_bot_service_azure_bot" "test" {
`, data.RandomInteger, data.Locations.Primary)
}
-func (BotServiceAzureBotResource) completeUpdate(data acceptance.TestData) string {
+func (BotServiceAzureBotResource) update(data acceptance.TestData) string {
return fmt.Sprintf(`
provider "azurerm" {
features {} | fix check in test and rename test case | terraform-providers_terraform-provider-azurerm | train | go |
de70bbc7ce3aa7edbb188a974319212b1a08b8a3 | diff --git a/src/AssetTarget.php b/src/AssetTarget.php
index <HASH>..<HASH> 100644
--- a/src/AssetTarget.php
+++ b/src/AssetTarget.php
@@ -10,21 +10,25 @@ namespace AssetCompress;
class AssetTarget
{
protected $path;
- protected $files;
- protected $filters;
+ protected $files = [];
+ protected $filters = [];
+ protected $paths = [];
protected $themed;
/**
* @param string $path The output path or the asset target.
* @param array $files An array of AssetCompress\File\FileInterface
* @param array $filters An array of filter names for this target.
+ * @param array $paths A list of search paths for this asset. These paths
+ * are used by filters that allow additional resources to be included e.g. Sprockets
* @param bool $themed Whether or not this file should be themed.
*/
- public function __construct($path, $files = [], $filters = [], $themed = false)
+ public function __construct($path, $files = [], $filters = [], $paths = [], $themed = false)
{
$this->path = $path;
$this->files = $files;
$this->filters = $filters;
+ $this->paths = $paths;
$this->themed = $themed;
}
@@ -33,6 +37,11 @@ class AssetTarget
return $this->themed;
}
+ public function paths()
+ {
+ return $this->paths;
+ }
+
public function files()
{
return $this->files; | Add paths() to AssetTarget.
Because assets can have filters that need access to the look up paths,
they should be added to the target. This allows the Target to contain
all the information needed to build the target, and solves dependency
issues for filters like Sprockets and ImportInline. | markstory_asset_compress | train | php |
c67c99c0b1e518acc8ba18918c75051eff8c8de9 | diff --git a/nodeconductor/structure/views.py b/nodeconductor/structure/views.py
index <HASH>..<HASH> 100644
--- a/nodeconductor/structure/views.py
+++ b/nodeconductor/structure/views.py
@@ -1764,7 +1764,7 @@ class BaseServiceViewSet(UpdateOnlyByPaidCustomerMixin,
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
- customer = serializer.validated_data.pop('project').customer
+ customer = serializer.validated_data['project'].customer
if not request.user.is_staff and not customer.has_user(request.user):
raise PermissionDenied(
"Only customer owner or staff are allowed to perform this action.") | Fix resource import view. Don't modify serializer's data in view. | opennode_waldur-core | train | py |
8f2ef0d7d28a89b5daa3962621840cff412d9cb3 | diff --git a/consul/kvs_endpoint.go b/consul/kvs_endpoint.go
index <HASH>..<HASH> 100644
--- a/consul/kvs_endpoint.go
+++ b/consul/kvs_endpoint.go
@@ -58,7 +58,13 @@ func (k *KVS) Get(args *structs.KeyRequest, reply *structs.IndexedDirEntries) er
return 0, err
}
if ent == nil {
- reply.Index = index
+ // Must provide non-zero index to prevent blocking
+ // Index 1 is impossible anyways (due to Raft internals)
+ if index == 0 {
+ reply.Index = 1
+ } else {
+ reply.Index = index
+ }
reply.Entries = nil
} else {
reply.Index = ent.ModifyIndex
@@ -84,7 +90,13 @@ func (k *KVS) List(args *structs.KeyRequest, reply *structs.IndexedDirEntries) e
return 0, err
}
if len(ent) == 0 {
- reply.Index = index
+ // Must provide non-zero index to prevent blocking
+ // Index 1 is impossible anyways (due to Raft internals)
+ if index == 0 {
+ reply.Index = 1
+ } else {
+ reply.Index = index
+ }
reply.Entries = nil
} else {
// Determine the maximum affected index | consul: Fixing blocking query if set table is at index 0 | hashicorp_consul | train | go |
5c0d907925ba1aa456800cd2d00644426bf73763 | diff --git a/xwiki-commons-core/xwiki-commons-extension/xwiki-commons-extension-api/src/main/java/org/xwiki/extension/handler/internal/DefaultExtensionInitializer.java b/xwiki-commons-core/xwiki-commons-extension/xwiki-commons-extension-api/src/main/java/org/xwiki/extension/handler/internal/DefaultExtensionInitializer.java
index <HASH>..<HASH> 100644
--- a/xwiki-commons-core/xwiki-commons-extension/xwiki-commons-extension-api/src/main/java/org/xwiki/extension/handler/internal/DefaultExtensionInitializer.java
+++ b/xwiki-commons-core/xwiki-commons-extension/xwiki-commons-extension-api/src/main/java/org/xwiki/extension/handler/internal/DefaultExtensionInitializer.java
@@ -133,9 +133,6 @@ public class DefaultExtensionInitializer implements ExtensionInitializer, Initia
{
// Check if the extension can be available from this namespace
if (!installedExtension.isValid(namespace)) {
- this.logger.warn("Extension [{}] could not be initialized on namespace [{}] because it's invalid",
- installedExtension.getId(), namespace);
-
return false;
} | XCOMMONS-<I>: Too many logs produced when failing to initialize a JAR extension
* remove log added by mistake | xwiki_xwiki-commons | train | java |
9f20bc61f57dcf690aade1c1a56f554dcd5dbadf | diff --git a/src/main/java/org/javamoney/moneta/FastMoney.java b/src/main/java/org/javamoney/moneta/FastMoney.java
index <HASH>..<HASH> 100644
--- a/src/main/java/org/javamoney/moneta/FastMoney.java
+++ b/src/main/java/org/javamoney/moneta/FastMoney.java
@@ -1,5 +1,5 @@
/**
- * Copyright (c) 2012, 2014, Credit Suisse (Anatole Tresch), Werner Keil and others by the @author tag.
+ * Copyright (c) 2012, 2015, Credit Suisse (Anatole Tresch), Werner Keil and others by the @author tag.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of | Update FastMoney.java
adjusted year in header | JavaMoney_jsr354-ri | train | java |
2e1ed1d0954a41374ee0174775b6c03b1676f8a8 | diff --git a/ip_assembler/tasks.py b/ip_assembler/tasks.py
index <HASH>..<HASH> 100644
--- a/ip_assembler/tasks.py
+++ b/ip_assembler/tasks.py
@@ -200,14 +200,14 @@ class IPEMailChecker(PeriodicTask):
# iterate the mail indices and fetch the mails
ips_created = 0
for mail_index in mail_indices[0].split():
- logger.info('fetching mail %(mail_index)s...' % {'mail_index': mail_index})
+ logger.info('fetching mail %(mail_index)s...' % {'mail_index': int(mail_index)})
# mail data is a list with a tuple
sub_result, mail_data = box.fetch(mail_index, '(BODY[TEXT])')
if sub_result == 'OK':
# fetch the ips
ips = list_remove_duplicates(
- self.find_ips(''.join(mail_data[0]))
+ self.find_ips(''.join([str(data) for data in mail_data[0]]))
)
# if ips found, add them and delete the mail | fixing error where str where expected but bytes are given | dArignac_ip_assembler | train | py |
2e7212f883ebb4ca4bd87561299b7da1bd01e0dc | diff --git a/director/lib/director/cloud/vsphere/cloud.rb b/director/lib/director/cloud/vsphere/cloud.rb
index <HASH>..<HASH> 100644
--- a/director/lib/director/cloud/vsphere/cloud.rb
+++ b/director/lib/director/cloud/vsphere/cloud.rb
@@ -668,7 +668,7 @@ module VSphereCloud
response = @rest_client.get(url)
if response.code < 400
- response.body.content
+ response.body
elsif response.code == 404
nil
else | work around a HTTP client backward incompatible change | cloudfoundry_bosh | train | rb |
df050eda5d7c6ad6234d8ae7d94b46a4ddff8449 | diff --git a/tests/model/DatetimeTest.php b/tests/model/DatetimeTest.php
index <HASH>..<HASH> 100644
--- a/tests/model/DatetimeTest.php
+++ b/tests/model/DatetimeTest.php
@@ -35,6 +35,8 @@ class SS_DatetimeTest extends SapphireTest {
}
function testSetNullAndZeroValues() {
+ date_default_timezone_set('UTC');
+
$date = DBField::create('SS_Datetime', '');
$this->assertNull($date->getValue(), 'Empty string evaluates to NULL');
@@ -45,10 +47,10 @@ class SS_DatetimeTest extends SapphireTest {
$this->assertNull($date->getValue(), 'Boolean FALSE evaluates to NULL');
$date = DBField::create('SS_Datetime', '0');
- $this->assertEquals('1970-01-01 12:00:00', $date->getValue(), 'String zero is UNIX epoch time');
+ $this->assertEquals('1970-01-01 00:00:00', $date->getValue(), 'String zero is UNIX epoch time');
$date = DBField::create('SS_Datetime', 0);
- $this->assertEquals('1970-01-01 12:00:00', $date->getValue(), 'Numeric zero is UNIX epoch time');
+ $this->assertEquals('1970-01-01 00:00:00', $date->getValue(), 'Numeric zero is UNIX epoch time');
}
} | BUGFIX: Correct testSetNullAndZeroValues() of DatetimeTest
- Code was assuming NZ time zone
- Set the default timezone to UTC for the test
- Correct the expected times for the epoch from noon to <I>:<I>:<I> UTC | silverstripe_silverstripe-framework | train | php |
395f9506cf93462db4a1ece6a2d3056ffefa8d75 | diff --git a/usermanagment.go b/usermanagment.go
index <HASH>..<HASH> 100644
--- a/usermanagment.go
+++ b/usermanagment.go
@@ -365,13 +365,13 @@ func ListResources() Resources {
return toResources(resp)
}
-func GetResourceByType(resourcetype string, resourceid string) Resources {
+func GetResourceByType(resourcetype string, resourceid string) Resource {
path := um_resources_type_path(resourcetype, resourceid)
url := mk_url(path) + `?depth=` + Depth + `&pretty=` + strconv.FormatBool(Pretty)
req, _ := http.NewRequest("GET", url, nil)
req.Header.Add("Content-Type", FullHeader)
resp := do(req)
- return toResources(resp)
+ return toResource(resp)
}
func ListResourcesByType(resourcetype string) Resources {
@@ -391,3 +391,13 @@ func toResources(resp Resp) Resources {
col.StatusCode = resp.StatusCode
return col
}
+
+func toResource(resp Resp) Resource {
+ var col Resource
+ json.Unmarshal(resp.Body, &col)
+ col.Response = string(resp.Body)
+ col.Headers = &resp.Headers
+ col.StatusCode = resp.StatusCode
+ return col
+}
+ | Fixed return type of GetResourceByType method | profitbricks_profitbricks-sdk-go | train | go |
a4b7caeaa653116b60a5231e9019ab250293c331 | diff --git a/setuptools/dist.py b/setuptools/dist.py
index <HASH>..<HASH> 100644
--- a/setuptools/dist.py
+++ b/setuptools/dist.py
@@ -144,13 +144,11 @@ def read_pkg_file(self, file):
self.license_files = _read_list_from_msg(msg, 'license-file')
-def ensure_summary_single_line(val):
- """Validate that the summary does not have line breaks."""
+def single_line(val):
+ """Validate that the value does not have line breaks."""
# Ref: https://github.com/pypa/setuptools/issues/1390
if '\n' in val:
- raise ValueError(
- 'Newlines in the package distribution summary are not allowed',
- )
+ raise ValueError('Newlines are not allowed')
return val
@@ -166,7 +164,7 @@ def write_pkg_file(self, file): # noqa: C901 # is too complex (14) # FIXME
write_field('Metadata-Version', str(version))
write_field('Name', self.get_name())
write_field('Version', self.get_version())
- write_field('Summary', ensure_summary_single_line(self.get_description()))
+ write_field('Summary', single_line(self.get_description()))
write_field('Home-page', self.get_url())
optional_fields = ( | Restore single_line as a simple, universal validator. | pypa_setuptools | train | py |
727cf320665c22c5e29ed0088e79c435b8253f02 | diff --git a/tensorlayer/models/core.py b/tensorlayer/models/core.py
index <HASH>..<HASH> 100644
--- a/tensorlayer/models/core.py
+++ b/tensorlayer/models/core.py
@@ -212,10 +212,10 @@ class Model():
# results.append(z)
if not isinstance(self._outputs, list):
- return memory[self._outputs.name]
+ return memory[self._outputs.name].outputs
# return results[0]
else:
- return [memory[layer.name] for layer in self._outputs]
+ return [memory[layer.name].outputs for layer in self._outputs]
# return results
@property | put .outputs in model core forward | tensorlayer_tensorlayer | train | py |
b5e8db526f2f975ff5f0d06883d8acdc2aa4310d | diff --git a/src/Phpconsole/Config.php b/src/Phpconsole/Config.php
index <HASH>..<HASH> 100644
--- a/src/Phpconsole/Config.php
+++ b/src/Phpconsole/Config.php
@@ -51,6 +51,12 @@ class Config implements LoggerInterface
dirname(__FILE__).'/phpconsole_config.php'
);
+ if (function_exists('app_path')) {
+
+ $defaultLocations[] = app_path().'/config/phpconsole.php';
+ $defaultLocations[] = app_path().'/config/packages/phpconsole/phpconsole/config.php';
+ }
+
if (defined('PHPCONSOLE_CONFIG_LOCATION')) {
$this->log('Found \'PHPCONSOLE_CONFIG_LOCATION\' constant - adding to the list of locations to check');
array_unshift($defaultLocations, PHPCONSOLE_CONFIG_LOCATION); | Add more config locations for Laravel projects | phpconsole_phpconsole | train | php |
915f53af230756c88bd860d1122b4d13b20ec906 | diff --git a/internal/providercache/package_install.go b/internal/providercache/package_install.go
index <HASH>..<HASH> 100644
--- a/internal/providercache/package_install.go
+++ b/internal/providercache/package_install.go
@@ -53,6 +53,7 @@ func installFromHTTPURL(ctx context.Context, meta getproviders.PackageMeta, targ
return nil, fmt.Errorf("failed to open temporary file to download from %s", url)
}
defer f.Close()
+ defer os.Remove(f.Name())
// We'll borrow go-getter's "cancelable copy" implementation here so that
// the download can potentially be interrupted partway through. | internal: Clean up package install temp file
The installFromHTTPURL function downloads a package to a temporary file,
then delegates to installFromLocalArchive to install it. We were
previously not deleting the temporary file afterwards. This commit fixes
that. | hashicorp_terraform | train | go |
613214f1976f4f81a65f4cd4ebece07ed73611d3 | diff --git a/discord/message.py b/discord/message.py
index <HASH>..<HASH> 100644
--- a/discord/message.py
+++ b/discord/message.py
@@ -144,6 +144,32 @@ class Message(object):
"""
return re.findall(r'<#([0-9]+)>', self.content)
+ @utils.cached_property
+ def clean_content(self):
+ """A property that returns the content in a "cleaned up"
+ manner. This basically means that mentions are transformed
+ into the way the client shows it. e.g. ``<#id>`` will transform
+ into ``#name``.
+ """
+
+ transformations = {
+ re.escape('<#{0.id}>'.format(channel)): '#' + channel.name
+ for channel in self.channel_mentions
+ }
+
+ mention_transforms = {
+ re.escape('<@{0.id}>'.format(member)): '@' + member.name
+ for member in self.mentions
+ }
+
+ transformations.update(mention_transforms)
+
+ def repl(obj):
+ return transformations.get(re.escape(obj.group(0)), '')
+
+ pattern = re.compile('|'.join(transformations.keys()))
+ return pattern.sub(repl, self.content)
+
def _handle_upgrades(self, channel_id):
self.server = None
if self.channel is None: | Add Message.clean_content property to get prettified mentions. | Rapptz_discord.py | train | py |
Subsets and Splits