hash
stringlengths
40
40
diff
stringlengths
131
114k
message
stringlengths
7
980
project
stringlengths
5
67
split
stringclasses
1 value
81e74682035087ff959b35c99c8b40dbac63d1c7
diff --git a/browser/lib/token.js b/browser/lib/token.js index <HASH>..<HASH> 100755 --- a/browser/lib/token.js +++ b/browser/lib/token.js @@ -267,6 +267,16 @@ base.fn.nextNW = function() { } +base.fn.lineStart = function(breakFn) { + return this.findRev(function() { + var x = this + if(this.rbracket) return this.matching + x = x.prev + if(x.lbracket && x.curly && this.blockType != "object") return true + if(x.whitespace || x.semi) return true + // if(breakFn && breakFn.call(x,x)) return true + }) +} base.fn.expressionStart = function(breakFn) { return this.findRev(function() { diff --git a/expectations/bang b/expectations/bang index <HASH>..<HASH> 100644 --- a/expectations/bang +++ b/expectations/bang @@ -96,4 +96,25 @@ function() { to: function() { get(function(_bang, _bang2) { x = _bang, y = _bang2 }) -} \ No newline at end of file +} + +compiles: +function() { + x = get!().length +} + +to: +function() { + get(function(_bang) { x = _bang.length }) +} + +compiles: +function() { + x = get!.length +} + +to: +function() { + get(function(_bang) { x = _bang.length }) +} + diff --git a/lib/plugins/bang.js b/lib/plugins/bang.js index <HASH>..<HASH> 100644 --- a/lib/plugins/bang.js +++ b/lib/plugins/bang.js @@ -11,10 +11,14 @@ module.exports = function(stream) { var lbracket = token.next; - var indent = token.indent(); - if(!lbracket || !lbracket.bracket || !lbracket.round) - throw "missing ( in banged function" + + if(!lbracket || !lbracket.bracket || !lbracket.round) { + this.after("()") + lbracket = token.next; + } + + var indent = token.indent(); var func = token.expressionStart() var func_before = func.prev @@ -23,6 +27,7 @@ module.exports = function(stream) { var rbracket = lbracket.matching var before_start = func.prev.expressionStart() + //var before_start = func.lineStart () var vars = [] if(func_before && func_before.assign) { diff --git a/lib/token.js b/lib/token.js index <HASH>..<HASH> 100755 --- a/lib/token.js +++ b/lib/token.js @@ -265,6 +265,31 @@ base.fn.nextNW = function() { +base.fn.lineStart = function(breakFn) { + var s = this.findRev(function() { + var x = this + + if(this.rbracket) return this.matching + x = x.prev + y = x.prev + + if(x.lbracket && x.curly && this.blockType != "object") return true + if(x.assign) return true + if(x.semi) { + return true + } + if(x.whitespace) { + if(y.word) return true + if(y.rbracket) return true + if(y.whitespace) return true + } + + + // if(breakFn && breakFn.call(x,x)) return true + }) + + return s +} base.fn.expressionStart = function(breakFn) { return this.findRev(function() { var x = this
added support for missing () after bang
weepy_kaffeine
train
9123d76742f35990d366f369c68261070919e5a9
diff --git a/sos/actions.py b/sos/actions.py index <HASH>..<HASH> 100644 --- a/sos/actions.py +++ b/sos/actions.py @@ -282,8 +282,10 @@ def sos_run(workflow=None, targets=None, shared=[], args={}, **kwargs): return Base_Executor(wf, args=args, shared=shared, config={'config_file': env.sos_dict['__config_file__']}).dryrun(targets=targets) elif env.run_mode in ('run', 'interactive'): - env.logger.info('Executing workflow ``{}`` with input ``{}``' - .format(workflow, short_repr(env.sos_dict['_input'], True))) + args_output = ', '.join('{}={}'.format(x, short_repr(y)) for x,y in args.items() if not x.startswith('__')) + env.logger.info('Executing workflow ``{}`` with input ``{}`` and {}' + .format(workflow, short_repr(env.sos_dict['_input'], True), + 'no args' if not args_output else args_output)) if env.__task_engine__: import pkg_resources diff --git a/sos/sos_executor.py b/sos/sos_executor.py index <HASH>..<HASH> 100755 --- a/sos/sos_executor.py +++ b/sos/sos_executor.py @@ -303,7 +303,7 @@ class Base_Executor: res = analyze_section(section) # # build DAG with input and output files of step - env.logger.info('Adding step {} with output {}'.format(res['step_name'], target)) + env.logger.info('Adding step {} with output {}'.format(res['step_name'], short_repr(res['step_output']))) if isinstance(mo[0][1], dict): context = mo[0][1] else: @@ -359,7 +359,7 @@ class Base_Executor: res = analyze_section(section) # # build DAG with input and output files of step - env.logger.info('Adding step {} with output {}'.format(res['step_name'], target)) + env.logger.info('Adding step {} with output {}'.format(res['step_name'], short_repr(res['step_output']))) if isinstance(mo[0][1], dict): context = mo[0][1] else: diff --git a/sos/sos_step.py b/sos/sos_step.py index <HASH>..<HASH> 100755 --- a/sos/sos_step.py +++ b/sos/sos_step.py @@ -635,7 +635,10 @@ class Base_Step_Executor: self.step.sigil ) ) - task_id = '{}_{}_{}'.format(self.step.step_name(), env.sos_dict['_index'], self.step.md5) + # temporarily create task signature to obtain sig_id + task_id = RuntimeInfo(self.step.md5, self.step.task, task_vars['_input'], + task_vars['_output'], task_vars['_depends'], + task_vars['__signature_vars__'], task_vars).sig_id job_file = os.path.join(os.path.expanduser('~'), '.sos', task_id + '.task') with open(job_file, 'wb') as jf: try:
Use unique task IDs for tasks with different input (#<I>)
vatlab_SoS
train
1611d9b9177a20a900ca9b016e8b8a39b2444120
diff --git a/src/League/OAuth2/Client/Provider/Facebook.php b/src/League/OAuth2/Client/Provider/Facebook.php index <HASH>..<HASH> 100755 --- a/src/League/OAuth2/Client/Provider/Facebook.php +++ b/src/League/OAuth2/Client/Provider/Facebook.php @@ -28,7 +28,7 @@ class Facebook extends IdentityProvider $user = new User; $user->uid = $response->id; - $user->nickname = $response->username; + $user->nickname = isset($response->username) ? $response->username : null; $user->name = $response->name; $user->firstName = $response->first_name; $user->lastName = $response->last_name;
Fix issue if Facebook user doesn't have a username
thephpleague_oauth2-client
train
9ab8a1b8a42feea91400a83df3b80e1524d2e4f1
diff --git a/librosa/decompose.py b/librosa/decompose.py index <HASH>..<HASH> 100644 --- a/librosa/decompose.py +++ b/librosa/decompose.py @@ -155,10 +155,10 @@ def hpss(S, kernel_size=31, power=2.0, mask=False): # Compute median filters. Pre-allocation here preserves memory layout. harm = np.empty_like(S) - harm[:] = scipy.signal.medfilt(S, kernel_size=(1, win_harm)) + harm[:] = scipy.signal.medfilt2d(S, kernel_size=(1, win_harm)) perc = np.empty_like(S) - perc[:] = scipy.signal.medfilt(S, kernel_size=(win_perc, 1)) + perc[:] = scipy.signal.medfilt2d(S, kernel_size=(win_perc, 1)) if mask or power == 0: mask_harm = (harm > perc).astype(float)
reverted to medfilt2d, much faster
librosa_librosa
train
6c70411ffe9b909c1bfe3f9e863f61f6abf84d2c
diff --git a/lib/droplet_kit/mappings/droplet_mapping.rb b/lib/droplet_kit/mappings/droplet_mapping.rb index <HASH>..<HASH> 100644 --- a/lib/droplet_kit/mappings/droplet_mapping.rb +++ b/lib/droplet_kit/mappings/droplet_mapping.rb @@ -35,6 +35,7 @@ module DropletKit property :image, scopes: [:create] property :ssh_keys, scopes: [:create] property :backups, scopes: [:create] + property :monitoring, scopes: [:create] property :ipv6, scopes: [:create] property :user_data, scopes: [:create] property :private_networking, scopes: [:create] diff --git a/lib/droplet_kit/models/droplet.rb b/lib/droplet_kit/models/droplet.rb index <HASH>..<HASH> 100644 --- a/lib/droplet_kit/models/droplet.rb +++ b/lib/droplet_kit/models/droplet.rb @@ -11,6 +11,7 @@ module DropletKit attribute :volumes attribute :ssh_keys attribute :backups + attribute :monitoring attribute :size attribute :ipv6 attribute :user_data diff --git a/spec/lib/droplet_kit/resources/droplet_resource_spec.rb b/spec/lib/droplet_kit/resources/droplet_resource_spec.rb index <HASH>..<HASH> 100644 --- a/spec/lib/droplet_kit/resources/droplet_resource_spec.rb +++ b/spec/lib/droplet_kit/resources/droplet_resource_spec.rb @@ -120,6 +120,7 @@ RSpec.describe DropletKit::DropletResource do image: 'ubuntu-14-04-x86', ssh_keys: [123], backups: true, + monitoring: true, ipv6: true, private_networking: true, user_data: "#cloud-config\nruncmd\n\t- echo 'Hello!'" @@ -132,6 +133,7 @@ RSpec.describe DropletKit::DropletResource do expect(as_hash['image']).to eq(droplet.image) expect(as_hash['ssh_keys']).to eq(droplet.ssh_keys) expect(as_hash['backups']).to eq(droplet.backups) + expect(as_hash['monitoring']).to eq(droplet.monitoring) expect(as_hash['ipv6']).to eq(droplet.ipv6) expect(as_hash['private_networking']).to eq(droplet.private_networking) expect(as_hash['user_data']).to eq(droplet.user_data)
Add monitoring option to droplet create.
digitalocean_droplet_kit
train
7376458a65a7ef7784347b5b48a222260faf2f76
diff --git a/lib/wwtd.rb b/lib/wwtd.rb index <HASH>..<HASH> 100644 --- a/lib/wwtd.rb +++ b/lib/wwtd.rb @@ -138,7 +138,7 @@ module WWTD end with_clean_env do - rvm = "rvm #{config["rvm"]} do " if config["rvm"] + rvm = "rvm #{ruby_version(config["rvm"])} do " if config["rvm"] if wants_bundle flock("#{lock}/#{config["rvm"] || "rvm"}") do @@ -156,6 +156,14 @@ module WWTD end end + # Taken from https://github.com/travis-ci/travis-build/blob/master/lib/travis/build/script/rvm.rb + def ruby_version(rvm) + rvm.to_s. + gsub(/-(1[89]|2[01])mode$/, '-d\1'). + gsub(/^rbx$/, 'rbx-weekly-d18'). + gsub(/^rbx-d(\d{2})$/, 'rbx-weekly-d\1') + end + def committed?(file) @committed_files ||= (File.exist?(".git") && `git ls-files`.split("\n")) || [] @committed_files.include?(file) diff --git a/spec/wwtd_spec.rb b/spec/wwtd_spec.rb index <HASH>..<HASH> 100644 --- a/spec/wwtd_spec.rb +++ b/spec/wwtd_spec.rb @@ -78,6 +78,14 @@ describe WWTD do wwtd("").should include "RUBY: #{other}" end + it "runs with given travis version" do + other_travis_version = (RUBY_VERSION == "1.9.3" ? "jruby-20mode" : "jruby-19mode") + other_rvm_version = (RUBY_VERSION == "1.9.3" ? "2.0.0" : "1.9.3") + write ".travis.yml", "rvm: #{other_travis_version}" + write "Rakefile", "task(:default) { puts %Q{RUBY: \#{RUBY_VERSION}} }" + wwtd("").should include "RUBY: #{other_rvm_version}" + end + it "runs with given gemfile" do write_default_gemfile bundle
Adds support for Travis Ruby versions [#1]
grosser_wwtd
train
d9b00ef71d83b7c4fc6545086b79ee9be4d5568f
diff --git a/great_expectations/data_context/data_context.py b/great_expectations/data_context/data_context.py index <HASH>..<HASH> 100644 --- a/great_expectations/data_context/data_context.py +++ b/great_expectations/data_context/data_context.py @@ -538,7 +538,7 @@ class BaseDataContext(object): return self.validation_operators[validation_operator_name].run( assets_to_validate=assets_to_validate, run_id=run_id, - evaluation_parameters=evaluation_parameters + evaluation_parameters=evaluation_parameters, **kwargs )
eval lookback missing comma
great-expectations_great_expectations
train
dfb16c08a1be2e3f5c0e3638d8293f1d0f79975f
diff --git a/lib/graphicsmagick/image.rb b/lib/graphicsmagick/image.rb index <HASH>..<HASH> 100644 --- a/lib/graphicsmagick/image.rb +++ b/lib/graphicsmagick/image.rb @@ -45,19 +45,19 @@ module GraphicsMagick FileUtils.copy_file(path, output_path) # gm mogrify [options] file - option_str = command_options.collect {|opt| "#{opt.key} #{opt.value}"}.join(" ") + option_str = command_options.collect {|opt| "#{opt.name} #{opt.args}"}.join(" ") "gm mogrify #{option_str} #{output_path}" elsif utility == "convert" # gm convert [options] input-path [options] output-path options1 = command_options.shift - option_str1 = options1.collect {|opt| "#{opt.key} #{opt.value}"}.join(" ") - option_str2 = command_options.collect {|opt| "#{opt.key} #{opt.value}"}.join(" ") + option_str1 = options1.collect {|opt| "#{opt.name} #{opt.args}"}.join(" ") + option_str2 = command_options.collect {|opt| "#{opt.name} #{opt.args}"}.join(" ") "gm convert #{option_str1} #{path} #{option_str2} #{output_path}" elsif utility == "composite" # gm convert [options] change-path base-path mask-path output-path - option_str = command_options.collect {|opt| "#{opt.key} #{opt.value}"}.join(" ") + option_str = command_options.collect {|opt| "#{opt.name} #{opt.args}"}.join(" ") "gm composite #{option_str} #{path} #{base_path} #{mask_path} #{output_path}" end @@ -67,7 +67,7 @@ module GraphicsMagick def write! command = if utility == "mogrify" - option_str = command_options.collect {|opt| "#{opt.key} #{opt.value}"}.join(" ") + option_str = command_options.collect {|opt| "#{opt.name} #{opt.args}"}.join(" ") "gm mogrify #{option_str} #{path}" else raise NoMethodError, "You must use Image#write(output) with the #{utility} command" @@ -88,7 +88,7 @@ module GraphicsMagick def add_option option_name, *args option_args = args.collect { |a| Shellwords.escape(a.to_s) } option_args = nil if option_args.is_a?(Array) && option_args.empty? - command_options << {option_name => option_args} + command_options << {:name => option_name, :args => option_args} self end
changed command_options hash structure
dignoe_graphicsmagick
train
cf3a4235d04cddf34fa514e8128a1181282b2778
diff --git a/gosu-core/src/main/java/gw/internal/gosu/parser/expressions/FeatureLiteral.java b/gosu-core/src/main/java/gw/internal/gosu/parser/expressions/FeatureLiteral.java index <HASH>..<HASH> 100644 --- a/gosu-core/src/main/java/gw/internal/gosu/parser/expressions/FeatureLiteral.java +++ b/gosu-core/src/main/java/gw/internal/gosu/parser/expressions/FeatureLiteral.java @@ -14,6 +14,7 @@ import gw.lang.parser.expressions.IFeatureLiteralExpression; import gw.lang.reflect.FunctionType; import gw.lang.reflect.IConstructorInfo; import gw.lang.reflect.IFeatureInfo; +import gw.lang.reflect.IHasParameterInfos; import gw.lang.reflect.IInvocableType; import gw.lang.reflect.IMethodInfo; import gw.lang.reflect.IParameterInfo; @@ -33,6 +34,7 @@ import gw.lang.reflect.features.MethodReference; import gw.lang.reflect.features.PropertyReference; import gw.lang.reflect.features.SimplePropertyChainReference; import gw.lang.reflect.java.JavaTypes; +import gw.util.GosuObjectUtil; import java.util.ArrayList; import java.util.Arrays; @@ -92,6 +94,9 @@ public class FeatureLiteral extends Expression implements IFeatureLiteralExpress { methodInfo = typeInfo.getMethod( methodName, argTypes ); } + + methodInfo = ensureExactMatch(methodInfo, argTypes); + if( methodInfo == null && argTypes.length == 0) { if( typeInfo instanceof IRelativeTypeInfo ) @@ -115,6 +120,28 @@ public class FeatureLiteral extends Expression implements IFeatureLiteralExpress } } + private <T extends IHasParameterInfos> T ensureExactMatch( T methodInfo, IType[] argTypes ) + { + if( methodInfo == null ) + { + return null; + } + IParameterInfo[] parameters = methodInfo.getParameters(); + if( argTypes.length != parameters.length ) + { + return null; + } + for( int i = 0; i < parameters.length; i++ ) + { + IType parameter = parameters[i].getFeatureType(); + if( !GosuObjectUtil.equals( parameter, argTypes[i] ) ) + { + return null; + } + } + return methodInfo; + } + private IMethodInfo findSingleMethodMatchingName( String methodName, List<? extends IMethodInfo> methods ) { IMethodInfo match = null; @@ -151,6 +178,9 @@ public class FeatureLiteral extends Expression implements IFeatureLiteralExpress constructorInfo = typeInfo.getConstructor( argTypes ); } } + + constructorInfo = ensureExactMatch(constructorInfo, argTypes); + if( constructorInfo == null ) { if( typeInfo instanceof IRelativeTypeInfo )
Ensure exact match between specified types and parameter types in method and constructor literals.
gosu-lang_gosu-lang
train
5d0fad48eca3ae9b6b1d76b92be1a28965e622a5
diff --git a/main.py b/main.py index <HASH>..<HASH> 100644 --- a/main.py +++ b/main.py @@ -206,8 +206,16 @@ class WsockHandler(tornado.websocket.WebSocketHandler): def check_origin(self, origin): return True + def get_addr(self): + ip = self.request.headers.get_list('X-Real-Ip') + port = self.request.headers.get_list('X-Real-Port') + addr = ':'.join(ip + port) + if not addr: + addr = '{}:{}'.format(*self.stream.socket.getpeername()) + return addr + def open(self): - self.src_addr = '{}:{}'.format(*self.stream.socket.getpeername()) + self.src_addr = self.get_addr() logging.info('Connected from {}'.format(self.src_addr)) worker = workers.pop(self.get_argument('id'), None) if not worker:
Added get_addr to get real client addr
huashengdun_webssh
train
8eb3b1d0d96f45335b76150d9ead41fdabfa3636
diff --git a/angr/factory.py b/angr/factory.py index <HASH>..<HASH> 100644 --- a/angr/factory.py +++ b/angr/factory.py @@ -77,7 +77,7 @@ class AngrObjectFactory(object): whitelist=stmt_whitelist, last_stmt=last_stmt) - def sim_run(self, state, addr=None, jumpkind=None, **block_opts): + def sim_run(self, state, addr=None, jumpkind=None, extra_stop_points=None, **block_opts): """ Returns a simuvex SimRun object (supporting refs() and exits()), automatically choosing whether to create a SimIRSB or a SimProcedure. @@ -96,6 +96,7 @@ class AngrObjectFactory(object): :param insn_bytes: a string of bytes to use for the block instead of the project. :param max_size: the maximum size of the block, in bytes. :param num_inst: the maximum number of instructions. + :param extra_stop_points: addresses to stop at, other than hooked functions :param traceflags: traceflags to be passed to VEX. Default: 0 """ @@ -130,7 +131,11 @@ class AngrObjectFactory(object): elif o.UNICORN in state.options and state.unicorn.check(): l.info('Creating SimUnicorn at %#x', addr) - r = SimUnicorn(state, stop_points=self._project._sim_procedures.keys()) + stops = self._project._sim_procedures.keys() + if extra_stop_points is not None: + stops.extend(extra_stop_points) + + r = SimUnicorn(state, stop_points=stops) if r.success: return r else:
add the capability to pass extra stop points to unicorn
angr_angr
train
1b82960ab83e9dcd1a50929793bdad45feeff32e
diff --git a/impact_functions/inundation/dki_flood_building_impact.py b/impact_functions/inundation/dki_flood_building_impact.py index <HASH>..<HASH> 100644 --- a/impact_functions/inundation/dki_flood_building_impact.py +++ b/impact_functions/inundation/dki_flood_building_impact.py @@ -1,5 +1,6 @@ from impact_functions.core import FunctionProvider from impact_functions.core import get_hazard_layer, get_exposure_layer +from impact_functions.core import get_question from storage.vector import Vector from storage.utilities import ugettext as _ from impact_functions.tables import (Table, TableRow) @@ -30,6 +31,10 @@ class DKIFloodBuildingImpactFunction(FunctionProvider): H = get_hazard_layer(layers) # Depth E = get_exposure_layer(layers) # Building locations + question = get_question(H.get_name(), + E.get_name(), + self.plugin_name.lower()) + # Interpolate hazard level to building locations if H.is_raster: I = H.interpolate(E, attribute_name='depth') @@ -100,12 +105,7 @@ class DKIFloodBuildingImpactFunction(FunctionProvider): del affected_buildings[usage] # Generate impact report for the pdf map - Hname = H.get_name() - Ename = E.get_name() - - # Generate impact report for the pdf map - table_body = [_('In case of "%s" the estimated impact to ' - '"%s" is:') % (Hname, Ename), + table_body = [question, TableRow([_('Building type'), _('Flooded'), _('Total')], header=True)] diff --git a/impact_functions/inundation/flood_population_evacuation.py b/impact_functions/inundation/flood_population_evacuation.py index <HASH>..<HASH> 100644 --- a/impact_functions/inundation/flood_population_evacuation.py +++ b/impact_functions/inundation/flood_population_evacuation.py @@ -1,6 +1,7 @@ import numpy from impact_functions.core import FunctionProvider from impact_functions.core import get_hazard_layer, get_exposure_layer +from impact_functions.core import get_question from impact_functions.styles import flood_population_style as style_info from storage.raster import Raster from storage.utilities import ugettext as _ @@ -32,6 +33,12 @@ class FloodEvacuationFunction(FunctionProvider): layers: List of layers expected to contain H: Raster layer of flood depth P: Raster layer of population data on the same grid as H + + Counts number of people exposed to flood levels exceeding specified threshold. + + Return + Map of population exposed to flood levels exceeding the threshold + Table with number of people evacuated and supplies required """ # Depth above which people are regarded affected [m] @@ -40,8 +47,10 @@ class FloodEvacuationFunction(FunctionProvider): # Identify hazard and exposure layers inundation = get_hazard_layer(layers) # Flood inundation [m] population = get_exposure_layer(layers) - iname = inundation.get_name() - pname = population.get_name() + + question = get_question(inundation.get_name(), + population.get_name(), + self.plugin_name) # Extract data as numeric arrays D = inundation.get_data(nan=0.0) # Depth @@ -61,15 +70,14 @@ class FloodEvacuationFunction(FunctionProvider): evacuated = evacuated // 1000 * 1000 # Calculate estimated needs based on BNPB Perka 7/2008 minimum bantuan - rice = int(evacuated * 2.8) - drinking_water = int(evacuated * 17.5) + rice = evacuated * 2.8 + drinking_water = evacuated * 17.5 water = evacuated * 67 family_kits = evacuated / 5 toilets = evacuated / 20 # Generate impact report for the pdf map - table_body = [_('In the event of %s how many ' - '%s might %s') % (iname, pname, plugin_name), + table_body = [question, TableRow([_('People needing evacuation'), '%i' % evacuated], header=True), @@ -97,7 +105,7 @@ class FloodEvacuationFunction(FunctionProvider): R = Raster(I, projection=inundation.get_projection(), geotransform=inundation.get_geotransform(), - name=_('Population which %s' % (self.plugin_name.lower())), + name=_('Population which %s') % self.plugin_name.lower(), keywords={'impact_summary': impact_summary, 'impact_table': impact_table, 'map_title': map_title},
Updated flood impact functions with tables, translation and tlc
inasafe_inasafe
train
115afb0c6863585f05794bc0a9e94b08a7e3ae26
diff --git a/conf/http.js b/conf/http.js index <HASH>..<HASH> 100644 --- a/conf/http.js +++ b/conf/http.js @@ -4,7 +4,6 @@ * MIT Licensed * * Configuration file for Express server in nodegame-server - * --- */ module.exports = configure; diff --git a/conf/loggers.js b/conf/loggers.js index <HASH>..<HASH> 100644 --- a/conf/loggers.js +++ b/conf/loggers.js @@ -4,7 +4,6 @@ * MIT Licensed * * Configuration file for Winston.js in nodegame-server - * --- */ module.exports = configure; diff --git a/conf/servernode.js b/conf/servernode.js index <HASH>..<HASH> 100644 --- a/conf/servernode.js +++ b/conf/servernode.js @@ -9,7 +9,6 @@ * @see ServerNode * * http://www.nodegame.org - * --- */ module.exports = configure; diff --git a/conf/sio.js b/conf/sio.js index <HASH>..<HASH> 100644 --- a/conf/sio.js +++ b/conf/sio.js @@ -4,7 +4,6 @@ * MIT Licensed * * Configuration file for Socket.io server in nodegame-server - * --- */ module.exports = configure; diff --git a/index.js b/index.js index <HASH>..<HASH> 100644 --- a/index.js +++ b/index.js @@ -6,7 +6,6 @@ * Server component for nodeGame * * http://www.nodegame.org - * --- */ exports.ServerNode = require('./lib/ServerNode.js'); @@ -14,6 +13,3 @@ exports.ServerNode = require('./lib/ServerNode.js'); exports.express = require('express'); exports.winston = require('winston'); exports.sio = require('socket.io'); - - -
Removed horizontal lines in doc comments
nodeGame_nodegame-server
train
dd748eda19f4e94ba5701dff45a006f00842a550
diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mustache/MustacheAutoConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mustache/MustacheAutoConfiguration.java index <HASH>..<HASH> 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mustache/MustacheAutoConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mustache/MustacheAutoConfiguration.java @@ -108,6 +108,7 @@ public class MustacheAutoConfiguration { resolver.setCache(this.mustache.isCache()); resolver.setViewNames(this.mustache.getViewNames()); resolver.setContentType(this.mustache.getContentType()); + resolver.setCharset(this.mustache.getCharset()); resolver.setCompiler(mustacheCompiler); resolver.setOrder(Ordered.LOWEST_PRECEDENCE - 10); return resolver; diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mustache/web/MustacheViewResolver.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mustache/web/MustacheViewResolver.java index <HASH>..<HASH> 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mustache/web/MustacheViewResolver.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mustache/web/MustacheViewResolver.java @@ -34,12 +34,15 @@ import com.samskivert.mustache.Template; * Spring MVC {@link ViewResolver} for Mustache. * * @author Dave Syer + * @author Andy Wilkinson * @since 1.2.2 */ public class MustacheViewResolver extends UrlBasedViewResolver { private Compiler compiler = Mustache.compiler(); + private String charset; + public MustacheViewResolver() { setViewClass(MustacheView.class); } @@ -51,6 +54,13 @@ public class MustacheViewResolver extends UrlBasedViewResolver { this.compiler = compiler; } + /** + * @param charset the charset to set + */ + public void setCharset(String charset) { + this.charset = charset; + } + @Override protected View loadView(String viewName, Locale locale) throws Exception { Resource resource = resolveResource(viewName, locale); @@ -64,7 +74,9 @@ public class MustacheViewResolver extends UrlBasedViewResolver { } private Template createTemplate(Resource resource) throws IOException { - return this.compiler.compile(new InputStreamReader(resource.getInputStream())); + return this.charset == null ? this.compiler.compile(new InputStreamReader( + resource.getInputStream())) : this.compiler + .compile(new InputStreamReader(resource.getInputStream(), this.charset)); } private Resource resolveResource(String viewName, Locale locale) {
Use the configured charset, if any, in MustacheViewResolver Closes gh-<I>
spring-projects_spring-boot
train
f0208c0a2407ab6ca1f50900f11cedefd64b07bc
diff --git a/ui/app/components/primary-metric.js b/ui/app/components/primary-metric.js index <HASH>..<HASH> 100644 --- a/ui/app/components/primary-metric.js +++ b/ui/app/components/primary-metric.js @@ -79,8 +79,8 @@ export default Component.extend({ poller: task(function*() { do { - yield this.get('tracker').poll(); - yield timeout(2000); + yield this.get('tracker.poll').perform(); + yield timeout(10); } while (!Ember.testing); }), diff --git a/ui/app/utils/classes/abstract-stats-tracker.js b/ui/app/utils/classes/abstract-stats-tracker.js index <HASH>..<HASH> 100644 --- a/ui/app/utils/classes/abstract-stats-tracker.js +++ b/ui/app/utils/classes/abstract-stats-tracker.js @@ -1,5 +1,6 @@ import Mixin from '@ember/object/mixin'; import { assert } from '@ember/debug'; +import { task, timeout } from 'ember-concurrency'; export default Mixin.create({ url: '', @@ -16,12 +17,18 @@ export default Mixin.create({ ); }, - poll() { + // Uses EC as a form of debounce to prevent multiple + // references to the same tracker from flooding the tracker, + // but also avoiding the issue where different places where the + // same tracker is used needs to coordinate. + poll: task(function*() { const url = this.get('url'); assert('Url must be defined', url); - return this.get('fetch')(url) + yield this.get('fetch')(url) .then(res => res.json()) .then(frame => this.append(frame)); - }, + + yield timeout(2000); + }).drop(), });
Add request throttling to the abstract stats tracker This is the best of three options 1. Users of stats trackers control polling (old method) 2. Stat tracker is stateful and has start/stop methods (like logging) 3. Stat trackers blindly throttle requests This is the best option because it means N number of concurrent users of a stats tracker can request polling without inundating the tracker with redundant frames (or the network with redundant requests), but they also don't have to coordinate amongst themselves to determine what state a tracker should be in.
hashicorp_nomad
train
fe18c5b34c1e28364dd81625cc973bd1502f0043
diff --git a/saltcloud/clouds/ibmsce.py b/saltcloud/clouds/ibmsce.py index <HASH>..<HASH> 100644 --- a/saltcloud/clouds/ibmsce.py +++ b/saltcloud/clouds/ibmsce.py @@ -156,6 +156,17 @@ def create(vm_): 'system for the password.' ) + saltcloud.utils.fire_event( + 'event', + 'starting create', + 'salt.cloud.create', + { + 'name': vm_['name'], + 'profile': vm_['profile'], + 'provider': vm_['provider'], + }, + ) + log.info('Creating Cloud VM {0}'.format(vm_['name'])) conn = get_conn() @@ -176,6 +187,17 @@ def create(vm_): time.strftime('%H:%M:%S') ) ) + + saltcloud.utils.fire_event( + 'event', + 'requesting instance', + 'salt.cloud.create', + {'kwargs': {'name': kwargs['name'], + 'image': kwargs['image'].name, + 'size': kwargs['size'].name, + 'location': kwargs['location'].name}}, + ) + try: data = conn.create_node(**kwargs) except Exception as exc: @@ -276,6 +298,13 @@ def create(vm_): # Store what was used to the deploy the VM ret['deploy_kwargs'] = deploy_kwargs + saltcloud.utils.fire_event( + 'event', + 'executing deploy script', + 'salt.cloud.create', + {'kwargs': deploy_kwargs}, + ) + deployed = saltcloud.utils.deploy_script(**deploy_kwargs) if deployed: log.info('Salt installed on {0}'.format(vm_['name'])) @@ -291,4 +320,16 @@ def create(vm_): ) ) ret.update(data.__dict__) + + saltcloud.utils.fire_event( + 'event', + 'created instance', + 'salt.cloud.create', + { + 'name': vm_['name'], + 'profile': vm_['profile'], + 'provider': vm_['provider'], + }, + ) + return ret
Adding events to ibmsce
saltstack_salt
train
d08500030be3a216a825cf46d9e952d350e30c7b
diff --git a/lib/multi_exiftool/writer.rb b/lib/multi_exiftool/writer.rb index <HASH>..<HASH> 100644 --- a/lib/multi_exiftool/writer.rb +++ b/lib/multi_exiftool/writer.rb @@ -60,7 +60,7 @@ module MultiExiftool end def parse_results - @errors = @stderr.readlines + @errors = @stderr.read.split(/\n/) @errors.empty? end diff --git a/test/test_writer.rb b/test/test_writer.rb index <HASH>..<HASH> 100644 --- a/test/test_writer.rb +++ b/test/test_writer.rb @@ -108,7 +108,7 @@ class TestWriter < Test::Unit::TestCase context 'write method' do - test 'succsessfull write' do + test 'successful write' do mocking_open3('exiftool -author=janfri a.jpg b.tif c.bmp', '', '') @writer.filenames = %w(a.jpg b.tif c.bmp) @writer.values = {:author => 'janfri'} @@ -117,6 +117,17 @@ class TestWriter < Test::Unit::TestCase assert_equal true, rc end + test 'unsuccessful write' do + stdout = " 1 image files updated\n 1 files weren't updated due to errors" + stderr = "Warning: Tag 'foo' does not exist\nError: File not found - xxx" + mocking_open3('exiftool -author=janfri -foo=x a.jpg xxx', stdout, stderr) + @writer.filenames = %w(a.jpg xxx) + @writer.values = {author: 'janfri', foo: 'x'} + rc = @writer.write + assert_equal stderr, @writer.errors.join("\n") + assert_equal false, rc + end + end end
New test: Unsuccessful write.
janfri_multi_exiftool
train
937ec146b86091f0d422c8bb44ebb7c39e95f8d0
diff --git a/src/test/java/pl/domzal/junit/docker/rule/AssertHtml.java b/src/test/java/pl/domzal/junit/docker/rule/AssertHtml.java index <HASH>..<HASH> 100644 --- a/src/test/java/pl/domzal/junit/docker/rule/AssertHtml.java +++ b/src/test/java/pl/domzal/junit/docker/rule/AssertHtml.java @@ -13,7 +13,7 @@ public class AssertHtml { public static boolean pageContainsString(String remotePageUrl, String containsString) { try { - Content content = Request.Get(remotePageUrl).execute().returnContent(); + Content content = Request.Get(remotePageUrl).connectTimeout(1000).socketTimeout(1000).execute().returnContent(); String pageContent = content.asString(); log.debug("\n"+pageContent); return pageContent.contains(containsString);
add timeouts on http get to make them less fragile
tdomzal_junit-docker-rule
train
11db2e658d25787dbd7456aa339c4af27d7efcec
diff --git a/eli5/formatters/features.py b/eli5/formatters/features.py index <HASH>..<HASH> 100644 --- a/eli5/formatters/features.py +++ b/eli5/formatters/features.py @@ -11,7 +11,11 @@ class EscapedFeatureName(object): return str(self.value) def __eq__(self, other): - return str(self) == other + return (isinstance(other, EscapedFeatureName) and + self.value == other.value) + + def __hash__(self): + return hash(self.value) def __repr__(self): return '<{} {!r}>'.format(self.__class__.__name__, self.value)
EscapedFeatureName: better __eq__ def, add __hash__
TeamHG-Memex_eli5
train
9652bb146379485d78f6c7534638f3701d651324
diff --git a/win_unicode_console/streams.py b/win_unicode_console/streams.py index <HASH>..<HASH> 100644 --- a/win_unicode_console/streams.py +++ b/win_unicode_console/streams.py @@ -2,7 +2,7 @@ import io import sys import time -from ctypes import byref, windll, c_ulong +from ctypes import byref, c_ulong from .buffer import get_buffer from .info import WINDOWS, PY2
Fix no-op on other platforms I forgot to remove the unconditional import of `windll` in `streams` module.
Drekin_win-unicode-console
train
0c671e342b44d95a19bc6ea6c4c3caf238c0678f
diff --git a/nifstd/nifstd_tools/docs.py b/nifstd/nifstd_tools/docs.py index <HASH>..<HASH> 100755 --- a/nifstd/nifstd_tools/docs.py +++ b/nifstd/nifstd_tools/docs.py @@ -78,9 +78,18 @@ class FixLinks: def __init__(self, current_file): print('========================================') print(current_file) - self.current_file = current_file - self.working_dir = get_working_dir(self.current_file) - self.repo = Repo(self.working_dir) + self.current_file = Path(current_file).resolve() + self.working_dir = self.current_file.working_dir + if self.working_dir is None: + # cannot proceed without git + raise FileNotFoundError(f'No working directory found for {self.current_file}') + #self.repo_name = 'NOREPO' + #self.netloc = 'NOWHERE' + #self.netloc_raw = 'NOWHERE' + #self.group = 'NOGROUP' + + self.repo = self.working_dir.repo + self.repo_name = self.working_dir.name self.remote_url = next(self.repo.remote().urls) if self.remote_url.startswith('git@'): self.remote_url = 'ssh://' + self.remote_url @@ -102,8 +111,6 @@ class FixLinks: else: raise NotImplementedError(self.remote_url) - - def __call__(self, org): org = re.sub(rb'\[\[\.\/', b'[[file:', org) # run this once at the start org = re.sub(rb'\[\[\.\.\/', b'[[file:../', org) # run this once at the start @@ -199,15 +206,20 @@ class FixLinks: rest = '' if not any(name.startswith(p) for p in ('$', '#')): - try: - rel = (self.current_file.parent / - (name + suffix)).resolve().relative_to(self.working_dir) - except ValueError as e: - log.error('path went outside current repo') - return name + suffix + rest + if self.working_dir is None: + log.warning('no working directory found, you will have broken links') + rel = Path(name + suffix) + else: + try: + rel = ((self.current_file.parent / (name + suffix)).resolve() + .relative_to(self.working_dir)) + except ValueError as e: + log.error('path went outside current repo') + return name + suffix + rest if suffix in ('.md', '.org', '.ipynb'): rel = rel.with_suffix('.html') + rel_path = rel.as_posix() + rest #print('aaaaaaaaaaa', suffix, rel, rel_path) return self.base + rel_path @@ -222,9 +234,12 @@ class FixLinks: sub_nothing = SubRel(f"we're off to see the inline src block maker") out_m1 = re.sub(r'^file:(\$)(.*)(#.+)*$', sub_nothing, out) + if self.working_dir is None: + log.warning('no working directory found, you will have broken links') + #print('----------------------------------------') # TODO consider htmlifying these ourselves and serving them directly - sub_github = SubRel(f'https://{self.netloc}/{self.group}/{self.working_dir.name}/blob/master/') + sub_github = SubRel(f'https://{self.netloc}/{self.group}/{self.repo_name}/blob/master/') # source file and/or code extensions regex # TODO folders that simply end code_regex = (r'(\.(?:el|py|sh|ttl|graphml|yml|yaml|spec|example|xlsx|svg)' @@ -236,7 +251,7 @@ class FixLinks: #print('----------------------------------------') # FIXME for the future, can't hotlink to svg from github - #sub_github_raw = SubRel(f'https://{self.netloc_raw}/{self.group}/{self.working_dir.name}/master/') + #sub_github_raw = SubRel(f'https://{self.netloc_raw}/{self.group}/{self.repo_name}/master/') #out0_5 = re.sub(r'^file:(.*)' + # r'(\.svg)' + # r'(#.+)*$', @@ -244,7 +259,7 @@ class FixLinks: #print('----------------------------------------') # FIXME won't work if the outer folder does not match the github project name - sub_docs = SubRel(f'hrefl:/docs/{self.working_dir.name}/') + sub_docs = SubRel(f'hrefl:/docs/{self.repo_name}/') out1 = re.sub(r'^file:(.*)' r'(\.(?:md|org|ipynb))' r'(#.+)*$', sub_docs, out0) diff --git a/nifstd/test/test_docs.py b/nifstd/test/test_docs.py index <HASH>..<HASH> 100644 --- a/nifstd/test/test_docs.py +++ b/nifstd/test/test_docs.py @@ -1,6 +1,7 @@ import re import unittest from pathlib import Path +import pytest from pyontutils.utils import get_working_dir from nifstd_tools.docs import FixLinks @@ -22,6 +23,7 @@ class TestRegex(unittest.TestCase): assert len(ml.groups()) == 2, ml +@pytest.mark.skipif(working_dir is None, reason='Not in git repo so not testing.') # FIXME create a temp repo? class TestFixLinks(unittest.TestCase): path_nasty_good = ( (Path(__file__), '[[file:${HOME}/.ssh/config][your ssh config file]]', '=${HOME}/.ssh/config='),
ont-docs and tests updated to fail/skip on missing git repo
tgbugs_pyontutils
train
92c0f17d6d2a958d3a6285b0e5408e9e0e7122e1
diff --git a/activesupport/lib/active_support/testing/performance.rb b/activesupport/lib/active_support/testing/performance.rb index <HASH>..<HASH> 100644 --- a/activesupport/lib/active_support/testing/performance.rb +++ b/activesupport/lib/active_support/testing/performance.rb @@ -260,16 +260,14 @@ begin end protected - # Ruby 1.9 + extented GC profiler patch - if defined?(GC::Profiler) and GC::Profiler.respond_to?(:data) + # Ruby 1.9 with GC::Profiler + if defined?(GC::Profiler) def with_gc_stats - GC.start - GC.disable GC::Profiler.enable + GC.start yield ensure GC::Profiler.disable - GC.enable end # Ruby 1.8 + ruby-prof wrapper (enable/disable stats for Benchmarker) @@ -294,7 +292,7 @@ begin end def format(measurement) - if measurement < 2 + if measurement < 1 '%d ms' % (measurement * 1000) else '%.2f sec' % measurement @@ -335,14 +333,10 @@ begin class Memory < Base Mode = RubyProf::MEMORY if RubyProf.const_defined?(:MEMORY) - # Ruby 1.9 + extended GC profiler patch - if defined?(GC::Profiler) and GC::Profiler.respond_to?(:data) + # Ruby 1.9 + GCdata patch + if GC.respond_to?(:malloc_allocated_size) def measure - GC.enable - GC.start - kb = GC::Profiler.data.last[:HEAP_USE_SIZE] / 1024.0 - GC.disable - kb + GC.malloc_allocated_size / 1024.0 end # Ruby 1.8 + ruby-prof wrapper @@ -360,14 +354,10 @@ begin class Objects < Base Mode = RubyProf::ALLOCATIONS if RubyProf.const_defined?(:ALLOCATIONS) - # Ruby 1.9 + extented GC profiler patch - if defined?(GC::Profiler) and GC::Profiler.respond_to?(:data) + # Ruby 1.9 + GCdata patch + if GC.respond_to?(:malloc_allocations) def measure - GC.enable - GC.start - count = GC::Profiler.data.last[:HEAP_TOTAL_OBJECTS] - GC.disable - count + GC.malloc_allocations end # Ruby 1.8 + ruby-prof wrapper @@ -385,14 +375,10 @@ begin class GcRuns < Base Mode = RubyProf::GC_RUNS if RubyProf.const_defined?(:GC_RUNS) - # Ruby 1.9 + extented GC profiler patch - if defined?(GC::Profiler) and GC::Profiler.respond_to?(:data) + # Ruby 1.9 + if GC.respond_to?(:count) def measure - GC.enable - GC.start - count = GC::Profiler.data.last[:GC_RUNS] - GC.disable - count + GC.count end # Ruby 1.8 + ruby-prof wrapper @@ -410,25 +396,21 @@ begin class GcTime < Base Mode = RubyProf::GC_TIME if RubyProf.const_defined?(:GC_TIME) - # Ruby 1.9 + extented GC profiler patch - if defined?(GC::Profiler) and GC::Profiler.respond_to?(:data) + # Ruby 1.9 with GC::Profiler + if GC.respond_to?(:total_time) def measure - GC.enable - GC.start - sec = GC::Profiler.data.inject(0) { |total, run| total += run[:GC_TIME] } - GC.disable - sec + GC::Profiler.total_time end # Ruby 1.8 + ruby-prof wrapper elsif RubyProf.respond_to?(:measure_gc_time) def measure - RubyProf.measure_gc_time + RubyProf.measure_gc_time / 1000 end end def format(measurement) - '%d ms' % (measurement / 1000) + '%.2f ms' % measurement end end end
performance tests now working accurately on <I>, using Ruby with the GCdata patch
rails_rails
train
edff867a9012e4cd2f722020498e0f885e696932
diff --git a/km.php b/km.php index <HASH>..<HASH> 100755 --- a/km.php +++ b/km.php @@ -237,7 +237,7 @@ class KM return $logs[$type]; } - static protected function log_query($msg) { self::log('query',$msg); } + static protected function log_query($msg) { self::log('query',$msg . CHR(13)); } static protected function log_send($msg) { self::log('send',$msg); }
Fixed log file corruption due to missing EOL marker
kissmetrics_KISSmetrics
train
d7825cf87cd61a65b20fc2277b8f5e52bd7ec5f7
diff --git a/simpleclient/src/main/java/io/prometheus/client/DoubleAdder.java b/simpleclient/src/main/java/io/prometheus/client/DoubleAdder.java index <HASH>..<HASH> 100644 --- a/simpleclient/src/main/java/io/prometheus/client/DoubleAdder.java +++ b/simpleclient/src/main/java/io/prometheus/client/DoubleAdder.java @@ -94,8 +94,37 @@ public class DoubleAdder extends Striped64 implements Serializable { * @return the sum */ public double sum() { - Cell[] as = cells; - double sum = Double.longBitsToDouble(base); + // On concurrent `sum` and `set`, it is acceptable to `get` an outdated `value`. + // On concurrent `sum` and `add`, it is acceptable to `get` an outdated `value`. + // On concurrent `sum` and `set` and `add`, it is possible to `get` an outdated `value`. + + // Correctness is guaranteed by `volatile` memory access ordering and visibility semantics. + // Program order: + // - writes in `set` - `busy` (CAS), `cells` (Wc), `base` (Wb), `busy` + // - reads in `sum` - `cells` (Rc), `base` (Rb), `busy`, `cells` (Cc), `base` (Cb) + // Note that: + // - `busy` is written after `cells` and `base` + // - `busy` is read after `cells` and `base`, then `cells` and `base` is re-read after `busy` + // In other words: + // - if we see the write to `busy`, then we must see the write to `cells` and `busy` on re-read + // - if we don't see the write to `busy`, then we must retry as we have no guarantees + // Execution order (in the former case): + // - serial + // - old result - Rc, Rb, Cc, Cb, Wc, Wb + // - new result - Wc, Wb, Rc, Rb, Cc, Cb + // - concurrent + // - old result - Rc, Wc, Rb, Wb, Cc, Cb - retry (superfluous) + // - new result - Wc, Rc, Wb, Rb, Cc, Cb + // - invalid result - Rc, Wc, Wb, Rb, Cc, Cb - retry + // - invalid result - Wc, Rc, Rb, Wb, Cc, Cb - retry + Cell[] as = cells; long b = base; + while (as != null && !(busy == 0 && cells == as && base == b)) { + // busy waiting, retry loop + Thread.yield(); + as = cells; b = base; + } + + double sum = Double.longBitsToDouble(b); if (as != null) { int n = as.length; for (int i = 0; i < n; ++i) { @@ -118,6 +147,41 @@ public class DoubleAdder extends Striped64 implements Serializable { internalReset(0L); } + public void set(double x) { + // On concurrent `set` and `set`, it should be acceptable to lose one `set` measurement. + // On concurrent `set` and `add`, it should be acceptable to lose the `add` measurement. + + // Correctness is ensured by different techniques: + // - `set` waits on contention (blocking) + // - `add` avoids contention (non-blocking) + // - `sum` retries on conflicts (non-blocking) + // Performance characteristics by use cases: + // - only `set` - `cells` is always `null` - no allocations + // - only `add` - `cells` allocated on contention + // - mixed `set` and `add` - `cells` allocated on contention, `cells` deallocated on `set` + for (;;) { + Cell[] as; + if ((as = cells) != null) { // have cells + if (busy == 0 && casBusy()) { + try { + if (cells == as) { // recheck under lock + // update cells and base (not atomic) + cells = null; + base = Double.doubleToLongBits(x); + break; + } + } finally { + busy = 0; + } + } + } else { // no cells + // update base (atomic) + base = Double.doubleToLongBits(x); + break; + } + } + } + /** * Equivalent in effect to {@link #sum} followed by {@link * #reset}. This method may apply for example during quiescent diff --git a/simpleclient/src/main/java/io/prometheus/client/Gauge.java b/simpleclient/src/main/java/io/prometheus/client/Gauge.java index <HASH>..<HASH> 100644 --- a/simpleclient/src/main/java/io/prometheus/client/Gauge.java +++ b/simpleclient/src/main/java/io/prometheus/client/Gauge.java @@ -134,6 +134,7 @@ public class Gauge extends SimpleCollector<Gauge.Child> implements Collector.Des * {@link SimpleCollector#remove} or {@link SimpleCollector#clear}, */ public static class Child { + private final DoubleAdder value = new DoubleAdder(); static TimeProvider timeProvider = new TimeProvider(); @@ -166,13 +167,7 @@ public class Gauge extends SimpleCollector<Gauge.Child> implements Collector.Des * Set the gauge to the given value. */ public void set(double val) { - synchronized(this) { - value.reset(); - // If get() were called here it'd see an invalid value, so use a lock. - // inc()/dec() don't need locks, as all the possible outcomes - // are still possible if set() were atomic so no new races are introduced. - value.add(val); - } + value.set(val); } /** * Set the gauge to the current unixtime. @@ -234,9 +229,7 @@ public class Gauge extends SimpleCollector<Gauge.Child> implements Collector.Des * Get the value of the gauge. */ public double get() { - synchronized(this) { - return value.sum(); - } + return value.sum(); } }
Use atomics instead of synchronized for Gauge (#<I>) * Use atomic update instead of synchronized for Gauge * Introduce DoubleAdder#set to avoid allocations in Gauge#set
prometheus_client_java
train
d240b2024697ff318e143857904a9e3c97d0e67c
diff --git a/envconfig.go b/envconfig.go index <HASH>..<HASH> 100644 --- a/envconfig.go +++ b/envconfig.go @@ -39,7 +39,7 @@ func Process(prefix string, spec interface{}) error { f := s.Field(i) if f.CanSet() { if typeOfSpec.Field(i).Anonymous && f.Kind() == reflect.Struct { - embeddedPtr := reflect.New(f.Type()).Interface() + embeddedPtr := f.Addr().Interface() if err := Process(prefix, embeddedPtr); err != nil { return err }
Simplify grabbing a pointer to process an embedded struct Thanks @metcalf!
kelseyhightower_envconfig
train
d6be2685cff08311774c70b7070daf86f5381593
diff --git a/core/src/main/java/com/google/errorprone/bugpatterns/NumericEquality.java b/core/src/main/java/com/google/errorprone/bugpatterns/NumericEquality.java index <HASH>..<HASH> 100644 --- a/core/src/main/java/com/google/errorprone/bugpatterns/NumericEquality.java +++ b/core/src/main/java/com/google/errorprone/bugpatterns/NumericEquality.java @@ -48,14 +48,14 @@ public class NumericEquality extends AbstractReferenceEquality { return false; } Symbol sym = ASTHelpers.getSymbol(tree); - if (isFinal(sym) && sym.isStatic()) { - // Using a static final object as a sentinel is OK + if (sym instanceof Symbol.VarSymbol && isFinal(sym) && sym.isStatic()) { + // Using a static final field as a sentinel is OK return false; } return true; } public static boolean isFinal(Symbol s) { - return (s.flags() & Flags.FINAL) != 0; + return (s.flags() & Flags.FINAL) == Flags.FINAL; } } diff --git a/core/src/test/java/com/google/errorprone/bugpatterns/NumericEqualityTest.java b/core/src/test/java/com/google/errorprone/bugpatterns/NumericEqualityTest.java index <HASH>..<HASH> 100644 --- a/core/src/test/java/com/google/errorprone/bugpatterns/NumericEqualityTest.java +++ b/core/src/test/java/com/google/errorprone/bugpatterns/NumericEqualityTest.java @@ -46,4 +46,21 @@ public class NumericEqualityTest { compilationHelper.addSourceFile("NumericEqualityNegativeCases.java").doTest(); } + // regression test for #415 + @Test + public void testParenthesized() { + compilationHelper + .addSourceLines( + "Test.java", + "class Test {", + " void f() {", + " final Long constValue = new Long(1000L);", + " Long assignedValue;", + " // BUG: Diagnostic contains:" + + " (!(assignedValue = new Long(1000L)).equals(constValue))", + " boolean retVal = ((assignedValue = new Long(1000L)) != constValue);", + " }", + "}") + .doTest(); + } }
Fix crash in NumericEquality Assuming that the arguments have symbols isn't correct. Fixes #<I> MOE_MIGRATED_REVID=<I>
google_error-prone
train
bdf20d26fdfa355eba794f64a108ed00e39a880c
diff --git a/src/view/helpers/contextMethods.js b/src/view/helpers/contextMethods.js index <HASH>..<HASH> 100644 --- a/src/view/helpers/contextMethods.js +++ b/src/view/helpers/contextMethods.js @@ -89,7 +89,7 @@ function getBinding () { } function setBinding ( value ) { - this.ractive.set( this.getBindingPath(), value ); + return this.ractive.set( this.getBindingPath(), value ); } // deprecated getters
return promise when setting bound value from context helper
ractivejs_ractive
train
c8f8df7dccf3994d8285be8d8b657e64730f786e
diff --git a/wcomponents-examples/src/main/java/com/github/bordertech/wcomponents/examples/HtmlClassPropertiesExample.java b/wcomponents-examples/src/main/java/com/github/bordertech/wcomponents/examples/HtmlClassPropertiesExample.java index <HASH>..<HASH> 100644 --- a/wcomponents-examples/src/main/java/com/github/bordertech/wcomponents/examples/HtmlClassPropertiesExample.java +++ b/wcomponents-examples/src/main/java/com/github/bordertech/wcomponents/examples/HtmlClassPropertiesExample.java @@ -4,8 +4,8 @@ import com.github.bordertech.wcomponents.HeadingLevel; import com.github.bordertech.wcomponents.WButton; import com.github.bordertech.wcomponents.WHeading; import com.github.bordertech.wcomponents.WPanel; -import com.github.bordertech.wcomponents.WStyledText; import com.github.bordertech.wcomponents.WText; +import com.github.bordertech.wcomponents.examples.common.ExplanatoryText; import com.github.bordertech.wcomponents.util.HtmlClassProperties; import com.github.bordertech.wcomponents.util.HtmlIconUtil; @@ -194,25 +194,22 @@ public class HtmlClassPropertiesExample extends WPanel { button.setHtmlClass(HtmlClassProperties.ICON_CANCEL_AFTER); add(button); + add(new WHeading(HeadingLevel.H3, "Menu icons")); + button = new WButton("\u200b"); // \u200b is a zero-width space. + button.setToolTip("Menu"); + button.setHtmlClass(HtmlClassProperties.ICON_MENU); + add(button); + button = new WButton("Menu"); + button.setHtmlClass(HtmlClassProperties.ICON_MENU_BEFORE); + add(button); + button = new WButton("Menu"); + button.setHtmlClass(HtmlClassProperties.ICON_MENU_AFTER); + add(button); add(new WHeading(HeadingLevel.H2, "Non-standard icons")); - add(new WHeading(HeadingLevel.H3, "Before text content")); - WStyledText text = new WStyledText("Fort Awesome"); - add(text); - text.setHtmlClass(HtmlClassProperties.ICON_BEFORE.toString() + " fa-fort-awesome"); - add(new WHeading(HeadingLevel.H3, "After text content")); - text = new WStyledText("Fort Awesome"); - add(text); - text.setHtmlClass(HtmlClassProperties.ICON_AFTER.toString() + " fa-fort-awesome"); - add(new WHeading(HeadingLevel.H3, "As content")); - text = new WStyledText("\u200b"); - add(text); - text.setHtmlClass(HtmlClassProperties.ICON.toString() + " fa-fort-awesome"); - - + add(new ExplanatoryText("This example shows how to add a Font Awesome icon not in the set exposed by HtmlClassProperties.")); // using the icon helpers String cogIcon = "fa-cog"; - add(new WHeading(HeadingLevel.H3, "Cog icons")); button = new WButton("\u200b"); // \u200b is a zero-width space. button.setToolTip("Settings"); button.setHtmlClass(HtmlIconUtil.getIconClasses(cogIcon));
Examples Updated HtmlClassPropertiesExample to include ICON_MENU.
BorderTech_wcomponents
train
ccea904fbb4ec7b44695747189c90d7e85ea4fa3
diff --git a/hydpy/models/hstream/hstream_model.py b/hydpy/models/hstream/hstream_model.py index <HASH>..<HASH> 100644 --- a/hydpy/models/hstream/hstream_model.py +++ b/hydpy/models/hstream/hstream_model.py @@ -131,6 +131,9 @@ class Pick_Q_V1(modeltools.Method): class Pass_Q_V1(modeltools.Method): """Assing the actual value of the lower joint of of the subreach downstream to the outlet sequence.""" + DERIVEDPARAMETERS = ( + hstream_derived.NmbSegments, + ) REQUIREDSEQUENCES = ( hstream_states.QJoints, )
Fix wrong variable selections for the methods of base model `hstream`.
hydpy-dev_hydpy
train
f0f6acf0b8407461ee9feefc04f1e1a7e4e5f7df
diff --git a/buttersink/Butter.py b/buttersink/Butter.py index <HASH>..<HASH> 100644 --- a/buttersink/Butter.py +++ b/buttersink/Butter.py @@ -78,6 +78,9 @@ class Butter: if Store.skipDryRun(logger, self.dryrun)("Command: %s", cmd): return None + if not os.path.exists(directory): + os.makedirs(directory) + process = subprocess.Popen( cmd, stdin=subprocess.PIPE,
fix: create destination directory if it doesn't exist
AmesCornish_buttersink
train
c5e40653ea75b1926bedb954ba47dc8aca6f917b
diff --git a/Eloquent/FactoryBuilder.php b/Eloquent/FactoryBuilder.php index <HASH>..<HASH> 100644 --- a/Eloquent/FactoryBuilder.php +++ b/Eloquent/FactoryBuilder.php @@ -53,9 +53,9 @@ class FactoryBuilder /** * The number of models to build. * - * @var int + * @var int|null */ - protected $amount = 1; + protected $amount = null; /** * Create an new builder instance. @@ -112,12 +112,10 @@ class FactoryBuilder { $results = $this->make($attributes); - if ($this->amount === 1) { + if ($results instanceof Model) { $results->save(); } else { - foreach ($results as $result) { - $result->save(); - } + $result->each->save(); } return $results; @@ -131,12 +129,12 @@ class FactoryBuilder */ public function make(array $attributes = []) { - if ($this->amount < 1) { - return (new $this->class)->newCollection(); + if ($this->amount === null) { + return $this->makeInstance($attributes); } - if ($this->amount === 1) { - return $this->makeInstance($attributes); + if ($this->amount < 1) { + return (new $this->class)->newCollection(); } return (new $this->class)->newCollection(array_map(function () use ($attributes) {
Always return collection from factory when amount is set (#<I>)
illuminate_database
train
25e2b8b4d3541ca85f8eecd9616803f96cc0d7bf
diff --git a/src/main/java/com/stratio/qa/specs/GosecSpec.java b/src/main/java/com/stratio/qa/specs/GosecSpec.java index <HASH>..<HASH> 100644 --- a/src/main/java/com/stratio/qa/specs/GosecSpec.java +++ b/src/main/java/com/stratio/qa/specs/GosecSpec.java @@ -43,6 +43,7 @@ public class GosecSpec extends BaseGSpec { private final Logger logger = LoggerFactory.getLogger(GosecSpec.class); RestSpec restSpec; + /** * Generic constructor. * @@ -390,9 +391,12 @@ public class GosecSpec extends BaseGSpec { } } - @When("^I get id from profile with name '(.+?)' and save it in environment variable '(.+?)'$") - public void getProfiled(String profileName, String envVar) throws Exception { + @When("^I get id from profile with name '(.+?)'( in tenant '(.+?)')? and save it in environment variable '(.+?)'$") + public void getProfiled(String profileName, String tenant, String envVar) throws Exception { String endPoint = "/service/gosec-identities-daas/identities/profiles"; + if (tenant != null) { + endPoint = "/service/gosec-identities-daas/identities/profiles?tid=" + tenant; + } assertThat(commonspec.getRestHost().isEmpty() || commonspec.getRestPort().isEmpty()); restSpec.sendRequestNoDataTable("GET", endPoint, null, null, null); @@ -661,8 +665,9 @@ public class GosecSpec extends BaseGSpec { /** * Removes user or group from tenant if the resource exists and has been assigned previously - * @param resource : type of resource (user or group) - * @param resourceId : userId or groupId + * + * @param resource : type of resource (user or group) + * @param resourceId : userId or groupId * @throws Exception if the resource does not exists or the request fails */ @When("^I remove '(user|group)' '(.+?)' from tenant '(.+?)'$")
[GS-<I>] Get profile from provided tenant (#<I>)
Stratio_bdt
train
2f68bdb473ef22aa5b15cb62db42698ea14af152
diff --git a/src/meerkat/logs/boxes.py b/src/meerkat/logs/boxes.py index <HASH>..<HASH> 100644 --- a/src/meerkat/logs/boxes.py +++ b/src/meerkat/logs/boxes.py @@ -3,8 +3,6 @@ from __future__ import unicode_literals import json -import re -from os.path import join from django.conf import settings from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator diff --git a/src/meerkat/logs/models.py b/src/meerkat/logs/models.py index <HASH>..<HASH> 100644 --- a/src/meerkat/logs/models.py +++ b/src/meerkat/logs/models.py @@ -7,7 +7,6 @@ import threading import time from django.conf import settings from django.db import models -from django.utils.encoding import python_2_unicode_compatible from django.utils.translation import ugettext_lazy as _ from meerkat.logs.parsers import NginXAccessLogParser @@ -25,18 +24,30 @@ class Geolocation(models.Model): # request. Therefore, these geolocations must be stored in the DB # if we want to compute statistical data about it. We cannot query # web-services each time we want to do this (data changed over time). - latitude = models.CharField(max_length=255) - longitude = models.CharField(max_length=255) - hostname = models.CharField(max_length=255) - city = models.CharField(max_length=255) - city_code = models.CharField(max_length=255, blank=True) - region = models.CharField(max_length=255) - region_code = models.CharField(max_length=255, blank=True) - country = models.CharField(max_length=255) - country_code = models.CharField(max_length=255, blank=True) - continent = models.CharField(max_length=255, blank=True) - continent_code = models.CharField(max_length=255, blank=True) - org = models.CharField(max_length=255) + latitude = models.CharField( + verbose_name=_(''), max_length=255) + longitude = models.CharField( + verbose_name=_(''), max_length=255) + hostname = models.CharField( + verbose_name=_(''), max_length=255) + city = models.CharField( + verbose_name=_(''), max_length=255) + city_code = models.CharField( + verbose_name=_(''), max_length=255, blank=True) + region = models.CharField( + verbose_name=_(''), max_length=255) + region_code = models.CharField( + verbose_name=_(''), max_length=255, blank=True) + country = models.CharField( + verbose_name=_(''), max_length=255) + country_code = models.CharField( + verbose_name=_(''), max_length=255, blank=True) + continent = models.CharField( + verbose_name=_(''), max_length=255, blank=True) + continent_code = models.CharField( + verbose_name=_(''), max_length=255, blank=True) + org = models.CharField( + verbose_name=_(''), max_length=255) class Meta: unique_together = ('latitude', 'longitude', 'hostname', @@ -66,9 +77,12 @@ class Geolocation(models.Model): class GeolocationCheck(models.Model): - ip_address = models.IPAddressField(unique=True) - date = models.DateField(default=datetime.date.today) - geolocation = models.ForeignKey(Geolocation) + ip_address = models.IPAddressField( + verbose_name=_(''), unique=True) + date = models.DateField( + verbose_name=_(''), default=datetime.date.today) + geolocation = models.ForeignKey( + Geolocation, verbose_name=_('')) class Meta: verbose_name = _('Geolocation check') @@ -240,5 +254,3 @@ class RequestLog(models.Model): t.daemon = True t.start() return t - -
Fix build, prepare verbose names
Genida_django-meerkat
train
22a3416298523d5e8ecb432a263e4bee9441e6c5
diff --git a/railties/CHANGELOG b/railties/CHANGELOG index <HASH>..<HASH> 100644 --- a/railties/CHANGELOG +++ b/railties/CHANGELOG @@ -10,6 +10,8 @@ redirect_to users_path, notice: "User has been created" + You can also passing `--old-style-hash` to make Rails generate old style hash even you're on Ruby 1.9 + * Changed scaffold_controller generator to create format block for JSON instead of XML [Prem Sichanugrist] * Add using Turn with natural language test case names for test_help.rb when running with minitest (Ruby 1.9.2+) [DHH] diff --git a/railties/lib/rails/generators/app_base.rb b/railties/lib/rails/generators/app_base.rb index <HASH>..<HASH> 100644 --- a/railties/lib/rails/generators/app_base.rb +++ b/railties/lib/rails/generators/app_base.rb @@ -53,6 +53,9 @@ module Rails class_option :help, :type => :boolean, :aliases => "-h", :group => :rails, :desc => "Show this help message and quit" + + class_option :old_style_hash, :type => :boolean, :default => false, + :desc => "Force using old style hash (:foo => 'bar') on Ruby >= 1.9" end def initialize(*args) @@ -177,7 +180,7 @@ module Rails # Returns Ruby 1.9 style key-value pair if current code is running on # Ruby 1.9.x. Returns the old-style (with hash rocket) otherwise. def key_value(key, value) - if RUBY_VERSION < '1.9' + if options[:old_style_hash] || RUBY_VERSION < '1.9' ":#{key} => #{value}" else "#{key}: #{value}" diff --git a/railties/lib/rails/generators/named_base.rb b/railties/lib/rails/generators/named_base.rb index <HASH>..<HASH> 100644 --- a/railties/lib/rails/generators/named_base.rb +++ b/railties/lib/rails/generators/named_base.rb @@ -8,6 +8,9 @@ module Rails class_option :skip_namespace, :type => :boolean, :default => false, :desc => "Skip namespace (affects only isolated applications)" + class_option :old_style_hash, :type => :boolean, :default => false, + :desc => "Force using old style hash (:foo => 'bar') on Ruby >= 1.9" + def initialize(args, *options) #:nodoc: # Unfreeze name in case it's given as a frozen string args[0] = args[0].dup if args[0].is_a?(String) && args[0].frozen? @@ -185,7 +188,7 @@ module Rails # Returns Ruby 1.9 style key-value pair if current code is running on # Ruby 1.9.x. Returns the old-style (with hash rocket) otherwise. def key_value(key, value) - if RUBY_VERSION < '1.9' + if options[:old_style_hash] || RUBY_VERSION < '1.9' ":#{key} => #{value}" else "#{key}: #{value}" diff --git a/railties/test/generators/app_generator_test.rb b/railties/test/generators/app_generator_test.rb index <HASH>..<HASH> 100644 --- a/railties/test/generators/app_generator_test.rb +++ b/railties/test/generators/app_generator_test.rb @@ -226,6 +226,14 @@ class AppGeneratorTest < Rails::Generators::TestCase end end end + + def test_force_old_style_hash + run_generator [destination_root, "--old-style-hash"] + assert_file "config/initializers/session_store.rb" do |file| + assert_match /config.session_store :cookie_store, :key => '_.+_session'/, file + end + end + protected def action(*args, &block) diff --git a/railties/test/generators/scaffold_controller_generator_test.rb b/railties/test/generators/scaffold_controller_generator_test.rb index <HASH>..<HASH> 100644 --- a/railties/test/generators/scaffold_controller_generator_test.rb +++ b/railties/test/generators/scaffold_controller_generator_test.rb @@ -133,4 +133,11 @@ class ScaffoldControllerGeneratorTest < Rails::Generators::TestCase end end end + + def test_force_old_style_hash + run_generator ["User", "--old-style-hash"] + assert_file "app/controllers/users_controller.rb" do |content| + assert_match /\{ render :action => "new" \}/, content + end + end end
Add --old-style-hash option to force creating old style hash on Ruby <I> That means if you don't like the new syntax, you can pass --old-style-hash to force Rails to generate code with hash rockets.
rails_rails
train
01f791cf5ed25d48734218a9fb30ad7ae489f52b
diff --git a/bioc/iterparse.py b/bioc/iterparse.py index <HASH>..<HASH> 100755 --- a/bioc/iterparse.py +++ b/bioc/iterparse.py @@ -81,13 +81,13 @@ class iterparse: elif self.__state == 1: if event == 'start': if elem.tag == 'source': - self.__collection.source = self.__gettext() + self.__collection.source = elem.text elif elem.tag == 'data': - self.__collection.date = self.__gettext() + self.__collection.date = elem.text elif elem.tag == 'key': - self.__collection.key = self.__gettext() + self.__collection.key = elem.text elif elem.tag == 'infon': - self.__collection.infons[elem.get('key')] = self.__gettext() + self.__collection.infons[elem.get('key')] = elem.text elif elem.tag == 'document': self.__document = BioCDocument() self.__state = 2 @@ -100,9 +100,9 @@ class iterparse: elif self.__state == 2: if event == 'start': if elem.tag == 'id': - self.__document.id = self.__gettext() + self.__document.id = elem.text elif elem.tag == 'infon': - self.__document.infons[elem.get('key')] = self.__gettext() + self.__document.infons[elem.get('key')] = elem.text elif elem.tag == 'passage': self.__passage = BioCPassage() self.__state = 3 @@ -117,11 +117,11 @@ class iterparse: elif self.__state == 3: if event == 'start': if elem.tag == 'offset': - self.__passage.offset = int(self.__gettext()) + self.__passage.offset = int(elem.text) elif elem.tag == 'text': - self.__passage.text = self.__gettext() + self.__passage.text = elem.text elif elem.tag == 'infon': - self.__passage.infons[elem.get('key')] = self.__gettext() + self.__passage.infons[elem.get('key')] = elem.text elif elem.tag == 'sentence': self.__sentence = BioCSentence() self.__state = 4 @@ -137,11 +137,11 @@ class iterparse: elif self.__state == 4: if event == 'start': if elem.tag == 'offset': - self.__sentence.offset = int(self.__gettext()) + self.__sentence.offset = int(elem.text) elif elem.tag == 'text': - self.__sentence.text = self.__gettext() + self.__sentence.text = elem.text elif elem.tag == 'infon': - self.__sentence.infons[elem.get('key')] = self.__gettext() + self.__sentence.infons[elem.get('key')] = elem.text elif elem.tag == 'annotation': self.__sentence.add_annotation(self.__read_annotation(elem)) elif elem.tag == 'relation': @@ -159,9 +159,9 @@ class iterparse: event, elem = self.__next_event() if event == 'start': if elem.tag == 'text': - ann.text = self.__gettext() + ann.text = elem.text elif elem.tag == 'infon': - ann.infons[elem.get('key')] = self.__gettext() + ann.infons[elem.get('key')] = elem.text elif elem.tag == 'location': ann.add_location( BioCLocation(int(elem.get('offset')), int(elem.get('length')))) @@ -178,7 +178,7 @@ class iterparse: event, elem = self.__next_event() if event == 'start': if elem.tag == 'infon': - rel.infons[elem.get('key')] = self.__gettext() + rel.infons[elem.get('key')] = elem.text elif elem.tag == 'node': rel.add_node(BioCNode(elem.get('refid'), elem.get('role'))) elif event == 'end': @@ -187,13 +187,13 @@ class iterparse: raise RuntimeError("should not reach here") return None - def __gettext(self, elem=None): - if self.__has_next(): - event, nextelem = self.__next_event() - assert ((elem is None) or (elem.tag == nextelem.tag)), \ - 'cannot read tag[%s] text' % elem.tag - return nextelem.text - return None + # def __gettext(self, elem=None): + # if self.__has_next(): + # event, nextelem = self.__next_event() + # assert ((elem is None) or (elem.tag == nextelem.tag)), \ + # 'cannot read tag[%s] text' % elem.tag + # return nextelem.text + # return None def __has_next(self): try: diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100755 --- a/setup.py +++ b/setup.py @@ -3,7 +3,7 @@ __author__ = 'Yifan Peng' from distutils.core import setup setup( name = 'bioc', - version = '1.0.dev8', + version = '1.0.dev9', description = 'Data structures and code to read/write BioC XML.', author = 'Yifan Peng', author_email = 'yfpeng@udel.edu',
fix the bug to read text in the element
yfpeng_bioc
train
bb8d2ccb5ef8f89df0d2286674efd8803855331c
diff --git a/src/keypad.controller.spec.js b/src/keypad.controller.spec.js index <HASH>..<HASH> 100644 --- a/src/keypad.controller.spec.js +++ b/src/keypad.controller.spec.js @@ -61,10 +61,11 @@ describe('KeypadController', () => { }); it('should add to the number model when small', () => { - const numberButton = element[0].querySelectorAll('.bc-keypad__button')[2]; - angular.element(numberButton).triggerHandler('click'); + const ORIGINAL_LENGTH = vm.bcNumberModel.length; + const NUMBER = 3; + vm.setNumber(NUMBER); - expect(vm.bcNumberModel).toEqual('3'); + expect(vm.bcNumberModel.length).toEqual(ORIGINAL_LENGTH + 1); }); it('should add to the number model when large', () => { @@ -72,11 +73,11 @@ describe('KeypadController', () => { // Set the model to a long number vm.bcNumberModel = LONG_NUMBER; + const ORIGINAL_LENGTH = vm.bcNumberModel.length; + const NUMBER = 3; + vm.setNumber(NUMBER); - const numberButton = element[0].querySelectorAll('.bc-keypad__button')[2]; - angular.element(numberButton).triggerHandler('click'); - - expect(vm.bcNumberModel).toEqual(LONG_NUMBER + '3'); + expect(vm.bcNumberModel.length).toEqual(ORIGINAL_LENGTH + 1); }); }); @@ -108,8 +109,8 @@ describe('KeypadController', () => { // Set to partial length vm.bcNumberModel = '12'; const ORIGINAL_LENGTH = vm.bcNumberModel.length; - const numberButton = element[0].querySelectorAll('.bc-keypad__button')[2]; - angular.element(numberButton).triggerHandler('click'); + const NUMBER = 3; + vm.setNumber(NUMBER); expect(vm.bcNumberModel.length).toEqual(ORIGINAL_LENGTH + 1); }); @@ -118,9 +119,8 @@ describe('KeypadController', () => { // Set to max length vm.bcNumberModel = '1234'; const ORIGINAL_LENGTH = vm.bcNumberModel.length; - - const numberButton = element[0].querySelectorAll('.bc-keypad__button')[2]; - angular.element(numberButton).triggerHandler('click'); + const NUMBER = 3; + vm.setNumber(NUMBER); expect(vm.bcNumberModel.length).toEqual(ORIGINAL_LENGTH); }); @@ -129,5 +129,31 @@ describe('KeypadController', () => { }); + describe('button interaction', () => { + let $scope; + let element; + let vm; + + beforeEach(() => { + $scope = $rootScope.$new(); + $scope.numbers = '12'; + element = angular.element( + '<bc-keypad bc-number-model="numbers"></bc-keypad>' + ); + element = $compile(element)($scope); + $scope.$apply(); + vm = element.isolateScope().vm; + }); + + it('should add to the number model when triggered', () => { + const ORIGINAL_LENGTH = vm.bcNumberModel.length; + const numberButton = element[0].querySelectorAll('.bc-keypad__button')[2]; + angular.element(numberButton).triggerHandler('click'); + + expect(vm.bcNumberModel.length).toEqual(ORIGINAL_LENGTH + 1); + }); + + }); + });
added test for button interaction, now interacting directly with setNumber method
benjamincharity_angular-keypad
train
9453482dd9eb7cc8f16067e066a6c11bdc20b56b
diff --git a/system/modules/generalDriver/DcGeneral/Callbacks/CallbacksInterface.php b/system/modules/generalDriver/DcGeneral/Callbacks/CallbacksInterface.php index <HASH>..<HASH> 100644 --- a/system/modules/generalDriver/DcGeneral/Callbacks/CallbacksInterface.php +++ b/system/modules/generalDriver/DcGeneral/Callbacks/CallbacksInterface.php @@ -273,6 +273,13 @@ interface CallbacksInterface public function onModelUpdateCallback($objModel); /** + * Generate the backend breadcrumb. + * + * @return array|null + */ + public function generateBreadcrumb(); + + /** * Call the custom filter callback for a field. * * Return true if the processing has been successfully applied, false otherwise. diff --git a/system/modules/generalDriver/DcGeneral/Callbacks/ContaoStyleCallbacks.php b/system/modules/generalDriver/DcGeneral/Callbacks/ContaoStyleCallbacks.php index <HASH>..<HASH> 100644 --- a/system/modules/generalDriver/DcGeneral/Callbacks/ContaoStyleCallbacks.php +++ b/system/modules/generalDriver/DcGeneral/Callbacks/ContaoStyleCallbacks.php @@ -677,6 +677,34 @@ class ContaoStyleCallbacks extends \System implements CallbacksInterface } } + public function generateBreadcrumb() + { + // Load DCA + $arrDCA = $this->objDC->getDCA(); + $arrCallback = $arrDCA['list']['presentation']['breadcrumb_callback']; + + if (!is_array($arrCallback) || count($arrCallback) == 0) + { + return null; + } + + // Get data from callback + $strClass = $arrCallback[0]; + $strMethod = $arrCallback[1]; + + // FIXME: implement this some better way. + $objCallback = (in_array('getInstance', get_class_methods($strClass))) ? call_user_func(array($strClass, 'getInstance')) : new $strClass(); + $arrReturn = $objCallback->$strMethod($this->objDC); + + // Check if we have a result with elements + if (!is_array($arrReturn) || count($arrReturn) == 0) + { + return null; + } + + return $arrReturn; + } + /** * Call the custom filter callback for a field. * diff --git a/system/modules/generalDriver/DcGeneral/Callbacks/PhpNativeCallbacks.php b/system/modules/generalDriver/DcGeneral/Callbacks/PhpNativeCallbacks.php index <HASH>..<HASH> 100644 --- a/system/modules/generalDriver/DcGeneral/Callbacks/PhpNativeCallbacks.php +++ b/system/modules/generalDriver/DcGeneral/Callbacks/PhpNativeCallbacks.php @@ -540,6 +540,24 @@ class PhpNativeCallbacks extends \System implements CallbacksInterface } } + public function generateBreadcrumb() + { + // Load DCA + $arrDCA = $this->getDC()->getDCA(); + + if (is_array($arrDCA['list']['presentation']['breadcrumb_callback'])) + { + if (is_callable($arrDCA['list']['presentation']['breadcrumb_callback'])) { + return call_user_func( + $arrDCA['list']['presentation']['breadcrumb_callback'], + $this->getDC() + ); + } + } + + return null; + } + /** * {@inheritdoc} */
Added method generateBreadcrumb() to callback interface and all classes.
contao-community-alliance_dc-general
train
2dfcded782468980e063d0f675705d1fb011d486
diff --git a/gwpy/timeseries/core.py b/gwpy/timeseries/core.py index <HASH>..<HASH> 100644 --- a/gwpy/timeseries/core.py +++ b/gwpy/timeseries/core.py @@ -1296,4 +1296,3 @@ class TimeSeriesBaseList(list): def __getslice__(self, i, j): return type(self)(*super(TimeSeriesBaseList, self).__getslice__(i, j)) - __getslice__.__doc__ = list.__getslice__.__doc__
TimeSeriesBaseList.__getslice__: removed __doc__ in python3 `list` doesn't have `__getslice__`, and we don't really need a docstring anyway
gwpy_gwpy
train
2054bd42b0746b8fbb7834020f11ffbc43c3263f
diff --git a/lib/rubyXL/objects/document_properties.rb b/lib/rubyXL/objects/document_properties.rb index <HASH>..<HASH> 100644 --- a/lib/rubyXL/objects/document_properties.rb +++ b/lib/rubyXL/objects/document_properties.rb @@ -4,7 +4,7 @@ require 'rubyXL/objects/container_nodes' module RubyXL # http://www.schemacentral.com/sc/ooxml/e-extended-properties_Properties.html - class DocumentProperties < OOXMLTopLevelObject + class DocumentPropertiesFile < OOXMLTopLevelObject attr_accessor :workbook define_child_node(RubyXL::StringNode, :node_name => :Template) @@ -82,7 +82,7 @@ module RubyXL end - class CoreProperties < OOXMLTopLevelObject + class CorePropertiesFile < OOXMLTopLevelObject attr_accessor :workbook define_child_node(RubyXL::StringNode, :node_name => 'dc:creator') diff --git a/lib/rubyXL/objects/storage.rb b/lib/rubyXL/objects/storage.rb index <HASH>..<HASH> 100644 --- a/lib/rubyXL/objects/storage.rb +++ b/lib/rubyXL/objects/storage.rb @@ -21,11 +21,11 @@ module RubyXL related_files = relationship_container.related_files related_files.each_pair { |rid, rf| case rf - when RubyXL::ThumbmailFile then self.thumbnail = rf - when RubyXL::CoreProperties then self.core_properties = rf - when RubyXL::DocumentProperties then self.document_properties = rf - when RubyXL::CustomProperties then self.custom_properties = rf - when RubyXL::Workbook then self.workbook = rf + when RubyXL::ThumbnailFile then self.thumbnail = rf + when RubyXL::CorePropertiesFile then self.core_properties = rf + when RubyXL::DocumentPropertiesFile then self.document_properties = rf + when RubyXL::CustomPropertiesFile then self.custom_properties = rf + when RubyXL::Workbook then self.workbook = rf else puts "-! DEBUG: #{self.class}: unattached: #{rf.class}" self.generic_storage << rf @@ -41,8 +41,8 @@ puts "-! DEBUG: #{self.class}: unattached: #{rf.class}" def self.default obj = self.new - obj.document_properties = RubyXL::DocumentProperties.new - obj.core_properties = RubyXL::CoreProperties.new + obj.document_properties = RubyXL::DocumentPropertiesFile.new + obj.core_properties = RubyXL::CorePropertiesFile.new obj.relationship_container = RubyXL::RootRelationships.new obj end @@ -242,7 +242,7 @@ puts "-! DEBUG: #{self.class}: unattached: #{rf.class}" end end - class ThumbmailFile < GenericStorageObject + class ThumbnailFile < GenericStorageObject def self.rel_type 'http://schemas.openxmlformats.org/package/2006/relationships/metadata/thumbnail' end
Ensuring proper attachment of custom properties
weshatheleopard_rubyXL
train
29b2e4ca7c62056dbc8a576e36e2c8e00d66c083
diff --git a/public/assets/appCore.js b/public/assets/appCore.js index <HASH>..<HASH> 100644 --- a/public/assets/appCore.js +++ b/public/assets/appCore.js @@ -344,7 +344,7 @@ async function getJSON(url) { url = url.replace(HOME, ""); let isView = new RegExp("^view\/", "i"); if (isView.test(url)) - location.reload(); + location.href = HOME + "network"; else toast("Sem Conexão!", 7000, "toast-error"); throw err
when view offline, send to no network
edineibauer_uebConfig
train
ef81317e9b1b492ed41b39d0df8afccdeb757dd1
diff --git a/core/tests.py b/core/tests.py index <HASH>..<HASH> 100755 --- a/core/tests.py +++ b/core/tests.py @@ -107,6 +107,8 @@ assert s2 // s3 == [ from core.transforms import transpose, reverse, stretch, invert +# transpose + assert s1 | transpose(12) == [ {MIDI_PITCH: 62, OFFSET_64: 16, DURATION_64: 16}, {MIDI_PITCH: 64, OFFSET_64: 32, DURATION_64: 16} @@ -114,17 +116,30 @@ assert s1 | transpose(12) == [ assert s1 | transpose(5) | transpose(-5) == s1 +# reverse + assert s1 | reverse() == [ {MIDI_PITCH: 52, OFFSET_64: 0, DURATION_64: 16}, - {MIDI_PITCH: 50, OFFSET_64: 16, DURATION_64: 16} + {MIDI_PITCH: 50, OFFSET_64: 16, DURATION_64: 16}, + {OFFSET_64: 48} ] +assert s1 | reverse() | reverse() == s1 + +# stretch + assert s1 | stretch(2) == [ {MIDI_PITCH: 50, OFFSET_64: 32, DURATION_64: 32}, {MIDI_PITCH: 52, OFFSET_64: 64, DURATION_64: 32} ] +assert s1 | stretch(2) | stretch(0.5) == s1 + +# invert + assert s1 | invert(50) == [ {DURATION_64: 16, OFFSET_64: 16, MIDI_PITCH: 50}, {DURATION_64: 16, OFFSET_64: 32, MIDI_PITCH: 48} -] \ No newline at end of file +] + +assert s1 | invert(100) | invert(100) == s1
new unit tests (mostly identity checks)
jtauber_sebastian
train
016ffbd752afcfbf5265d3f1334b35d548a17f62
diff --git a/lib/weblib.php b/lib/weblib.php index <HASH>..<HASH> 100644 --- a/lib/weblib.php +++ b/lib/weblib.php @@ -86,7 +86,7 @@ $ALLOWED_TAGS = */ $ALLOWED_PROTOCOLS = array('http', 'https', 'ftp', 'news', 'mailto', 'rtsp', 'teamspeak', 'gopher', 'mms', 'color', 'callto', 'cursor', 'text-align', 'font-size', 'font-weight', 'font-style', - 'border', 'margin', 'padding'); // CSS as well to get through kses + 'border', 'margin', 'padding', 'background'); // CSS as well to get through kses /// Functions
Bug #<I> - Highlighting a question text fragment with different color; merged from MOODLE_<I>_STABLE
moodle_moodle
train
21bb4fe234d6863f7b49888d653e76c0e71f44f3
diff --git a/lib/db/query/bound.js b/lib/db/query/bound.js index <HASH>..<HASH> 100644 --- a/lib/db/query/bound.js +++ b/lib/db/query/bound.js @@ -24,13 +24,8 @@ var BoundQuery = BaseQuery.extend(Where, /** @lends BoundQuery# */{ init: function() { throw new Error('BoundQuery must be spawned.'); }, _create: function(table) { - // bound query may be subclassed & have new queries spawned from an - // existing bound query. we don't want to force the subclass to implement - // a create function that also specifies a table, so we'll use the table - // name that's given to us or the one that's already defined (which we - // probably got via a `spawn` and a `take`). this._super(); - this._table = table || this._table; + this._table = table; }, _take: function(orig) {
BoundQuery is no longer subclassed.
wbyoung_azul
train
89889337ae412712157b509ab0ad60bdee7afb3b
diff --git a/topdown/resolver.go b/topdown/resolver.go index <HASH>..<HASH> 100644 --- a/topdown/resolver.go +++ b/topdown/resolver.go @@ -66,7 +66,7 @@ func (t *resolverTrie) mktree(ctx context.Context, in resolver.Input) (ast.Value } obj := ast.NewObject() for k, child := range t.children { - v, err := child.mktree(ctx, in) + v, err := child.mktree(ctx, resolver.Input{Ref: append(in.Ref, ast.NewTerm(k)), Input: in.Input}) if err != nil { return nil, err }
topdown: Pass the current ref into resolvers.Eval()
open-policy-agent_opa
train
eb9355e69810db9648ceae7b697cf0d42a8e0c37
diff --git a/tests/integration/components/freestyle-palette/component-test.js b/tests/integration/components/freestyle-palette/component-test.js index <HASH>..<HASH> 100644 --- a/tests/integration/components/freestyle-palette/component-test.js +++ b/tests/integration/components/freestyle-palette/component-test.js @@ -17,22 +17,20 @@ const COLOR_PALETTE = { module('Integration | Component | freestyle-palette', function (hooks) { setupRenderingTest(hooks); + hooks.beforeEach(function () { + this.colorPalette = {}; + }); + test('it renders a color palette', async function (assert) { await render(hbs` <FreestylePalette - @colorPalette={{hash}} + @colorPalette={{this.colorPalette}} /> `); assert.dom('.FreestylePaletteItem').doesNotExist(); - this.colorPalette = COLOR_PALETTE; - - await render(hbs` - <FreestylePalette - @colorPalette={{this.colorPalette}} - /> - `); + this.set('colorPalette', COLOR_PALETTE); assert.dom('.FreestylePaletteItem').exists({ count: 2 }); @@ -54,7 +52,7 @@ module('Integration | Component | freestyle-palette', function (hooks) { test('it renders a title', async function (assert) { await render(hbs` <FreestylePalette - @colorPalette={{hash}} + @colorPalette={{this.colorPalette}} /> `); @@ -62,7 +60,7 @@ module('Integration | Component | freestyle-palette', function (hooks) { await render(hbs` <FreestylePalette - @colorPalette={{hash}} + @colorPalette={{this.colorPalette}} @title="Different Title" /> `); @@ -73,7 +71,7 @@ module('Integration | Component | freestyle-palette', function (hooks) { test('it renders a description', async function (assert) { await render(hbs` <FreestylePalette - @colorPalette={{hash}} + @colorPalette={{this.colorPalette}} /> `); @@ -83,7 +81,7 @@ module('Integration | Component | freestyle-palette', function (hooks) { await render(hbs` <FreestylePalette - @colorPalette={{hash}} + @colorPalette={{this.colorPalette}} @description="Different description." /> `); diff --git a/tests/integration/components/freestyle-usage/component-test.js b/tests/integration/components/freestyle-usage/component-test.js index <HASH>..<HASH> 100644 --- a/tests/integration/components/freestyle-usage/component-test.js +++ b/tests/integration/components/freestyle-usage/component-test.js @@ -84,19 +84,17 @@ module('Integration | Component | freestyle usage', function (hooks) { this.set('emberFreestyle.showCode', true); await render(hbs` - {{!-- template-lint-disable no-curly-component-invocation --}} - {{!-- template-lint-disable no-implicit-this --}} <FreestyleUsage @slug='componentA'> - {{this.indented-far-before-blank-line}} + {{this.indentedFarBeforeBlankLine}} - {{after-blank-line}} + {{this.afterBlankLine}} </FreestyleUsage> `); let rawSnippet = usage.usageSection.rawSource; assert.equal( rawSnippet.trim().split('\n').get('lastObject'), - '{{after-blank-line}}' + '{{this.afterBlankLine}}' ); });
test: resolve deprecations when running test suite
chrislopresto_ember-freestyle
train
d1ae2ad380f1c25a3af17b6d40992848716377e0
diff --git a/ui/src/components/btn/QBtn.js b/ui/src/components/btn/QBtn.js index <HASH>..<HASH> 100644 --- a/ui/src/components/btn/QBtn.js +++ b/ui/src/components/btn/QBtn.js @@ -126,7 +126,7 @@ export default Vue.extend({ if (touchTarget !== this.$el) { touchTarget !== void 0 && this.__cleanup() touchTarget = this.$el - const target = getTouchTarget(touchTarget) + const target = this.touchTargetEl = getTouchTarget(e.target) target.addEventListener('touchcancel', this.__onPressEnd, passiveCapture) target.addEventListener('touchend', this.__onPressEnd, passiveCapture) } @@ -183,10 +183,10 @@ export default Vue.extend({ } if (touchTarget === this.$el) { - const target = getTouchTarget(touchTarget) + const target = this.touchTargetEl target.removeEventListener('touchcancel', this.__onPressEnd, passiveCapture) target.removeEventListener('touchend', this.__onPressEnd, passiveCapture) - touchTarget = void 0 + touchTarget = this.touchTargetEl = void 0 } if (mouseTarget === this.$el) {
fix(QBtn): touchtarget management #<I>
quasarframework_quasar
train
0390dea5b1b6a53bcfba587f7ba8e808b05f868f
diff --git a/src/Propel/Generator/Behavior/Sortable/SortableBehaviorObjectBuilderModifier.php b/src/Propel/Generator/Behavior/Sortable/SortableBehaviorObjectBuilderModifier.php index <HASH>..<HASH> 100644 --- a/src/Propel/Generator/Behavior/Sortable/SortableBehaviorObjectBuilderModifier.php +++ b/src/Propel/Generator/Behavior/Sortable/SortableBehaviorObjectBuilderModifier.php @@ -623,7 +623,7 @@ public function insertAtRank(\$rank, ?ConnectionInterface \$con = null) * * @param ConnectionInterface \$con optional connection * - * @return \$this the current object + * @return \$this The current object * * @throws PropelException */ @@ -649,7 +649,7 @@ public function insertAtBottom(?ConnectionInterface \$con = null) * Insert in the first rank * The modifications are not persisted until the object is saved. * - * @return \$this the current object + * @return \$this The current object */ public function insertAtTop() { @@ -676,7 +676,7 @@ public function insertAtTop() * @param int \$newRank rank value * @param ConnectionInterface \$con optional connection * - * @return \$this the current object + * @return \$this The current object * * @throws PropelException */ @@ -726,7 +726,7 @@ public function moveToRank(\$newRank, ?ConnectionInterface \$con = null) * @param {$this->objectClassName} \$object * @param ConnectionInterface \$con optional connection * - * @return \$this the current object + * @return \$this The current object * * @throws Exception if the database cannot execute the two updates */ @@ -775,7 +775,7 @@ public function swapWith(\$object, ?ConnectionInterface \$con = null) * * @param ConnectionInterface \$con optional connection * - * @return \$this the current object + * @return \$this The current object */ public function moveUp(?ConnectionInterface \$con = null) { @@ -808,7 +808,7 @@ public function moveUp(?ConnectionInterface \$con = null) * * @param ConnectionInterface \$con optional connection * - * @return \$this the current object + * @return \$this The current object */ public function moveDown(?ConnectionInterface \$con = null) { @@ -841,7 +841,7 @@ public function moveDown(?ConnectionInterface \$con = null) * * @param ConnectionInterface \$con optional connection * - * @return \$this the current object + * @return \$this The current object */ public function moveToTop(?ConnectionInterface \$con = null) { @@ -870,22 +870,25 @@ public function moveToTop(?ConnectionInterface \$con = null) * * @param ConnectionInterface \$con optional connection * - * @return \$this|{$this->objectClassName}|null The old object's rank or null if already last + * @return \$this The current object */ public function moveToBottom(?ConnectionInterface \$con = null) { if (\$this->isLast(\$con)) { - return null; + return \$this; } - if (null === \$con) { + + if (\$con === null) { \$con = Propel::getServiceContainer()->getWriteConnection({$this->tableMapClassName}::DATABASE_NAME); } - return \$con->transaction(function () use (\$con) { + \$con->transaction(function () use (\$con) { \$bottom = {$this->queryClassName}::create()->getMaxRankArray(" . ($useScope ? '$this->getScopeValue(), ' : '') . "\$con); - return \$this->moveToRank(\$bottom, \$con); + \$this->moveToRank(\$bottom, \$con); }); + + return \$this; } "; } @@ -903,7 +906,7 @@ public function moveToBottom(?ConnectionInterface \$con = null) * Removes the current object from the list" . ($useScope ? ' (moves it to the null scope)' : '') . ". * The modifications are not persisted until the object is saved. * - * @return \$this the current object + * @return \$this The current object */ public function removeFromList() {"; diff --git a/tests/Propel/Tests/Generator/Behavior/Sortable/SortableBehaviorObjectBuilderModifierTest.php b/tests/Propel/Tests/Generator/Behavior/Sortable/SortableBehaviorObjectBuilderModifierTest.php index <HASH>..<HASH> 100644 --- a/tests/Propel/Tests/Generator/Behavior/Sortable/SortableBehaviorObjectBuilderModifierTest.php +++ b/tests/Propel/Tests/Generator/Behavior/Sortable/SortableBehaviorObjectBuilderModifierTest.php @@ -318,7 +318,7 @@ class SortableBehaviorObjectBuilderModifierTest extends TestCase $expected = [1 => 'row1', 2 => 'row3', 3 => 'row4', 4 => 'row2']; $this->assertEquals($expected, $this->getFixturesArray(), 'moveToBottom() moves to the bottom'); $res = $t2->moveToBottom(); - $this->assertNull($res, 'moveToBottom() returns null when called on the bottom node'); + $this->assertEquals($t2, $res, 'moveToBottom() returns the current object'); $expected = [1 => 'row1', 2 => 'row3', 3 => 'row4', 4 => 'row2']; $this->assertEquals($expected, $this->getFixturesArray(), 'moveToBottom() changes nothing when called on the bottom node'); }
Adjusted sortable behavior to be consistent. (#<I>) * Adjusted sortable behavior to be consistent.
propelorm_Propel2
train
d0a575614a58137ef51c5c5abbdf7cd928a3d6c1
diff --git a/src/Adapter/Filesystem/FilesystemCachePool.php b/src/Adapter/Filesystem/FilesystemCachePool.php index <HASH>..<HASH> 100644 --- a/src/Adapter/Filesystem/FilesystemCachePool.php +++ b/src/Adapter/Filesystem/FilesystemCachePool.php @@ -25,8 +25,6 @@ use Psr\Cache\CacheItemInterface; */ class FilesystemCachePool extends AbstractCachePool implements TaggablePoolInterface { - const CACHE_PATH = 'cache'; - use TaggablePoolTrait; /** @@ -35,12 +33,30 @@ class FilesystemCachePool extends AbstractCachePool implements TaggablePoolInter private $filesystem; /** + * The folder should not begin nor end with a slash. Example: path/to/cache. + * + * @type string + */ + private $folder; + + /** * @param Filesystem $filesystem + * @param string $folder */ - public function __construct(Filesystem $filesystem) + public function __construct(Filesystem $filesystem, $folder = 'cache') { + $this->folder = $folder; + $this->filesystem = $filesystem; - $this->filesystem->createDir(self::CACHE_PATH); + $this->filesystem->createDir($this->folder); + } + + /** + * @param string $folder + */ + public function setFolder($folder) + { + $this->folder = $folder; } /** @@ -71,8 +87,8 @@ class FilesystemCachePool extends AbstractCachePool implements TaggablePoolInter */ protected function clearAllObjectsFromCache() { - $this->filesystem->deleteDir(self::CACHE_PATH); - $this->filesystem->createDir(self::CACHE_PATH); + $this->filesystem->deleteDir($this->folder); + $this->filesystem->createDir($this->folder); return true; } @@ -122,7 +138,7 @@ class FilesystemCachePool extends AbstractCachePool implements TaggablePoolInter throw new InvalidArgumentException(sprintf('Invalid key "%s". Valid keys must match [a-zA-Z0-9_\.! ].', $key)); } - return sprintf('%s/%s', self::CACHE_PATH, $key); + return sprintf('%s/%s', $this->folder, $key); } /** diff --git a/src/Adapter/Filesystem/README.md b/src/Adapter/Filesystem/README.md index <HASH>..<HASH> 100644 --- a/src/Adapter/Filesystem/README.md +++ b/src/Adapter/Filesystem/README.md @@ -31,6 +31,13 @@ $filesystem = new Filesystem($filesystemAdapter); $pool = new FilesystemCachePool($filesystem); ``` +You can change the folder the cache pool will write to through the `setFolder` setter: + +```php +$pool = new FilesystemCachePool($filesystem); +$pool->setFolder('path/to/cache'); +``` + ### Contribute Contributions are very welcome! Send a pull request to the [main repository](https://github.com/php-cache/cache) or diff --git a/src/Adapter/Filesystem/Tests/FilesystemCachePoolTest.php b/src/Adapter/Filesystem/Tests/FilesystemCachePoolTest.php index <HASH>..<HASH> 100644 --- a/src/Adapter/Filesystem/Tests/FilesystemCachePoolTest.php +++ b/src/Adapter/Filesystem/Tests/FilesystemCachePoolTest.php @@ -44,4 +44,13 @@ class FilesystemCachePoolTest extends \PHPUnit_Framework_TestCase $this->assertFalse($item->isHit()); $this->assertFalse($this->getFilesystem()->has('cache/test_ttl_null')); } + + public function testChangeFolder() + { + $pool = $this->createCachePool(); + $pool->setFolder('foobar'); + + $pool->save($pool->getItem('test_path')); + $this->assertTrue($this->getFilesystem()->has('foobar/test_path')); + } }
Add ability to change cache path in FilesystemCachePool (#<I>) * Add ability to change cache path in FilesystemCachePool
php-cache_cache
train
94ab626fa970c9545a0d3e9639aaeff75dad1b53
diff --git a/src/Schema/utils.php b/src/Schema/utils.php index <HASH>..<HASH> 100644 --- a/src/Schema/utils.php +++ b/src/Schema/utils.php @@ -73,6 +73,11 @@ function escapeQuote(string $line): string */ function printLines(array $lines): string { + // Don't print empty lines + $lines = \array_filter($lines, function (string $line) { + return $line !== ''; + }); + return printArray("\n", $lines); }
Don't print empty lines Without this every field that has no description will be preseeded by an empty line, since the description is one line of zero length
digiaonline_graphql-php
train
8ec38fba3c3e319d16dc6fffa14f1cf0171ecdec
diff --git a/includes/class-freemius.php b/includes/class-freemius.php index <HASH>..<HASH> 100755 --- a/includes/class-freemius.php +++ b/includes/class-freemius.php @@ -6860,7 +6860,7 @@ */ function _sync_cron_method( array $blog_ids, $current_blog_id = null ) { if ( $this->is_registered() ) { - $this->sync_user_beta_mode(); + $this->sync_site_beta_mode(); if ( $this->has_paid_plan() ) { // Initiate background plan sync. @@ -13243,26 +13243,25 @@ self::shoot_ajax_failure(); } - $user = $this->get_api_user_scope()->call( + $site = $this->get_api_site_scope()->call( '', 'put', array( - 'plugin_id' => $this->get_id(), 'is_beta' => ( 'true' == $is_beta ), 'fields' => 'is_beta' ) ); - if ( ! $this->is_api_result_entity( $user ) ) { + if ( ! $this->is_api_result_entity( $site ) ) { self::shoot_ajax_failure( - FS_Api::is_api_error_object( $user ) ? - $user->error->message : + FS_Api::is_api_error_object( $site ) ? + $site->error->message : fs_text_inline( "An unknown error has occurred while trying to set the user's beta mode.", 'unknown-error-occurred', $this->get_slug() ) ); } - $this->_user->is_beta = $user->is_beta; - $this->_store_user(); + $this->_site->is_beta = $site->is_beta; + $this->_store_site(); self::shoot_ajax_response( array( 'success' => true ) ); } @@ -16457,12 +16456,12 @@ * @author Leo Fajardo (@leorw) * @since 2.3.0 */ - private function sync_user_beta_mode() { - $user = $this->get_api_user_scope()->get( '/?plugin_id=' . $this->get_id() . '&fields=is_beta' ); + private function sync_site_beta_mode() { + $site = $this->get_api_site_scope()->get( '/?fields=is_beta' ); - if ( $this->is_api_result_entity( $user ) ) { - $this->_user->is_beta = $user->is_beta; - $this->_store_user(); + if ( $this->is_api_result_entity( $site ) ) { + $this->_site->is_beta = $site->is_beta; + $this->_store_site(); } } @@ -21303,7 +21302,7 @@ if ( $this->has_secret_key() ) { $endpoint = add_query_arg( 'type', 'all', $endpoint ); - } else if ( $this->is_registered() && $this->_user->is_beta() ) { + } else if ( $this->is_registered() && $this->_site->is_beta() ) { $endpoint = add_query_arg( 'type', 'beta', $endpoint ); } diff --git a/includes/entities/class-fs-site.php b/includes/entities/class-fs-site.php index <HASH>..<HASH> 100755 --- a/includes/entities/class-fs-site.php +++ b/includes/entities/class-fs-site.php @@ -102,6 +102,12 @@ * @var bool */ public $is_uninstalled = false; + /** + * @author Edgar Melkonyan + * + * @var bool + */ + public $is_beta; /** * @param stdClass|bool $site @@ -233,4 +239,13 @@ function is_tracking_prohibited() { return ! $this->is_tracking_allowed(); } + + /** + * @author Edgar Melkonyan + * + * @return bool + */ + function is_beta() { + return ( isset( $this->is_beta ) && true === $this->is_beta ); + } } \ No newline at end of file diff --git a/includes/entities/class-fs-user.php b/includes/entities/class-fs-user.php index <HASH>..<HASH> 100755 --- a/includes/entities/class-fs-user.php +++ b/includes/entities/class-fs-user.php @@ -31,13 +31,6 @@ */ public $is_verified; /** - * @author Leo Fajardo (@leorw) - * @since 2.3.0 - * - * @var bool - */ - public $is_beta; - /** * @var string|null */ public $customer_id; @@ -63,16 +56,6 @@ return ( isset( $this->is_verified ) && true === $this->is_verified ); } - /** - * @author Leo Fajardo (@leorw) - * @since 2.3.0 - * - * @return bool - */ - function is_beta() { - return ( isset( $this->is_beta ) && true === $this->is_beta ); - } - static function get_type() { return 'user'; } diff --git a/templates/account.php b/templates/account.php index <HASH>..<HASH> 100755 --- a/templates/account.php +++ b/templates/account.php @@ -437,7 +437,7 @@ $profile[] = array( 'id' => 'beta_program', 'title' => '', - 'value' => $user->is_beta + 'value' => $site->is_beta ); }
[beta] [program] [site] Made changes for Beta program, related to API endpoints changes.
Freemius_wordpress-sdk
train
2305c7182490e6a28f2335f6b209438d0bc6555e
diff --git a/Tsugi/UI/CrudForm.php b/Tsugi/UI/CrudForm.php index <HASH>..<HASH> 100644 --- a/Tsugi/UI/CrudForm.php +++ b/Tsugi/UI/CrudForm.php @@ -183,10 +183,8 @@ class CrudForm { echo('<input type="submit" name="doDelete" class="btn btn-danger" value="'._m("Delete").'"'); echo(" onclick=\"return confirm('Are you sure you want to delete this record?');\">\n"); } - echo("</form>\n"); echo("<p>\n"); - if ( $do_edit ) echo('<form method="post">'."\n"); for($i=0; $i < count($fields); $i++ ) { $field = $fields[$i]; @@ -229,9 +227,7 @@ class CrudForm { } echo("</label>\n</div>"); } - if ( $do_edit ) { - echo('</form>'."\n"); - } + echo('</form>'."\n"); return true; }
Missed the nesting of form tags
tsugiproject_tsugi-php
train
5fe4f694fa9318ff130ba0195a650d2c70b71a9d
diff --git a/cli/src/commands/runTests.js b/cli/src/commands/runTests.js index <HASH>..<HASH> 100644 --- a/cli/src/commands/runTests.js +++ b/cli/src/commands/runTests.js @@ -130,13 +130,15 @@ async function getOrderedFlowBinVersions( return false; } - // Temporary fix for https://github.com/flowtype/flow-typed/issues/2422 - if (rel.tag_name === 'v0.63.0') { + // Temporary fixes for https://github.com/flowtype/flow-typed/issues/2422 + if (rel.tag_name === 'v0.63.0' || rel.tag_name === 'v0.70.0') { console.log( '==========================================================================================', ); console.log( - 'We are tempoarily skipping v0.63.0 due to https://github.com/flowtype/flow-typed/issues/2422', + `We are tempoarily skipping ${ + rel.tag_name + } due to https://github.com/flowtype/flow-typed/issues/2422`, ); console.log( '==========================================================================================',
Skip <I> to address segfaults on travis (#<I>)
flow-typed_flow-typed
train
99f8173f72ee0918cc6199d3933afc60c31abb9c
diff --git a/pmagpy_tests/test_imports3.py b/pmagpy_tests/test_imports3.py index <HASH>..<HASH> 100644 --- a/pmagpy_tests/test_imports3.py +++ b/pmagpy_tests/test_imports3.py @@ -243,6 +243,21 @@ class Test_iodp_srm_magic(unittest.TestCase): self.assertEqual(outfile, os.path.join('measurements.txt')) + def test_iodp_with_one_file_long_path(self): + options = {} + #dir_path = os.path.join(WD, 'data_files', 'Measurement_Import', + # 'iodp_srm_magic') + dir_path = os.path.join('data_files', 'UTESTA', 'SRM_data') + options['dir_path'] = dir_path + options['dir_path'] = WD #dir_path + options['input_dir_path'] = "fake/path" + options['csv_file'] = os.path.join(dir_path, 'srmsection-XXX-UTEST-A.csv') + program_ran, outfile = iodp_srm_magic.convert(**options) + self.assertEqual(program_ran, True) + self.assertEqual(outfile, os.path.join('measurements.txt')) + + + class Test_iodp_dscr_magic(unittest.TestCase): def setUp(self): diff --git a/programs/conversion_scripts/iodp_srm_magic.py b/programs/conversion_scripts/iodp_srm_magic.py index <HASH>..<HASH> 100755 --- a/programs/conversion_scripts/iodp_srm_magic.py +++ b/programs/conversion_scripts/iodp_srm_magic.py @@ -60,7 +60,6 @@ def convert(**kwargs): if csv_file=="": filelist=os.listdir(input_dir_path) # read in list of files to import else: - csv_file = os.path.join(input_dir_path, csv_file) filelist=[csv_file] # parsing the data @@ -69,9 +68,11 @@ def convert(**kwargs): for f in filelist: # parse each file year_warning = True if f[-3:].lower()=='csv': + print('processing:', f) file_found = True - print('processing: ',f) - full_file = open(os.path.join(input_dir_path, f)) + # get correct full filename and read data + fname = pmag.resolve_file_name(f, input_dir_path) + full_file = open(fname) file_input=full_file.readlines() full_file.close() keys=file_input[0].replace('\n','').split(',') # splits on underscores
use resolve_file_name in iodp_srm_magic, addresses #<I>
PmagPy_PmagPy
train
f93d96f56bbf9eb3acc8be2218114bedb3d70b93
diff --git a/src/models/Media.php b/src/models/Media.php index <HASH>..<HASH> 100644 --- a/src/models/Media.php +++ b/src/models/Media.php @@ -1,5 +1,7 @@ <?php namespace Devfactory\Media\Models; +use Illuminate\Support\Facades\URL; + class Media extends \Eloquent { protected $table = 'media'; @@ -21,7 +23,7 @@ class Media extends \Eloquent { } public function getUrlAttribute() { - return \Url::asset(\Config::get('media::files_directory') . $this->filename); + return Url::asset(config('media.config.files_directory') . $this->filename); } public function getTitleAttribute($value) {
#5 - Fixed bug with code from laravel 4 using facades that no longer exist when getting Url Attribute on model
DevFactoryCH_media
train
7f43db7916f1700125be67efc6dd3ba918d71673
diff --git a/lib/node_modules/@stdlib/math/base/utils/is-even/README.md b/lib/node_modules/@stdlib/math/base/utils/is-even/README.md index <HASH>..<HASH> 100644 --- a/lib/node_modules/@stdlib/math/base/utils/is-even/README.md +++ b/lib/node_modules/@stdlib/math/base/utils/is-even/README.md @@ -20,6 +20,9 @@ var bool = isEven( 5.0 ); bool = isEven( -2.0 ); // returns true +bool = isEven( 0.0 ); +// returns true + bool = isEven( NaN ); // returns false ``` diff --git a/lib/node_modules/@stdlib/math/base/utils/is-even/lib/index.js b/lib/node_modules/@stdlib/math/base/utils/is-even/lib/index.js index <HASH>..<HASH> 100644 --- a/lib/node_modules/@stdlib/math/base/utils/is-even/lib/index.js +++ b/lib/node_modules/@stdlib/math/base/utils/is-even/lib/index.js @@ -14,6 +14,9 @@ * bool = isEven( -2.0 ); * // returns true * +* bool = isEven( 0.0 ); +* // returns true +* * bool = isEven( NaN ); * // returns false */ diff --git a/lib/node_modules/@stdlib/math/base/utils/is-even/lib/iseven.js b/lib/node_modules/@stdlib/math/base/utils/is-even/lib/iseven.js index <HASH>..<HASH> 100644 --- a/lib/node_modules/@stdlib/math/base/utils/is-even/lib/iseven.js +++ b/lib/node_modules/@stdlib/math/base/utils/is-even/lib/iseven.js @@ -20,6 +20,9 @@ var isInteger = require( '@stdlib/math/base/utils/is-integer' ); * var bool = isEven( -2.0 ); * // returns true * @example +* var bool = isEven( 0.0 ); +* // returns true +* @example * var bool = isEven( NaN ); * // returns false */
Update examples to include <I>
stdlib-js_stdlib
train
5a771db1e0a654c9992be7709d383f49ebdef743
diff --git a/lib/docker/compose/mapper.rb b/lib/docker/compose/mapper.rb index <HASH>..<HASH> 100644 --- a/lib/docker/compose/mapper.rb +++ b/lib/docker/compose/mapper.rb @@ -98,11 +98,13 @@ module Docker::Compose raise NoService, "Service '#{service}' not running, or does not publish port '#{port}'" end + private + # Map a single string, replacing service names with IPs and container ports # with the host ports that they have been mapped to. # @param [String] value # @return [String] - private def map_scalar(value) + def map_scalar(value) uri = begin URI.parse(value) rescue diff --git a/lib/docker/compose/rake_tasks.rb b/lib/docker/compose/rake_tasks.rb index <HASH>..<HASH> 100644 --- a/lib/docker/compose/rake_tasks.rb +++ b/lib/docker/compose/rake_tasks.rb @@ -73,7 +73,9 @@ module Docker::Compose define end - private def define + private + + def define namespace rake_namespace do desc 'Print bash exports with IP/ports of running services' task :env do @@ -107,7 +109,7 @@ module Docker::Compose # Substitute and set environment variables that point to network ports # published by docker-compose services. Optionally also print bash export # statements so this information can be made available to a user's shell. - private def export_env(print:) + def export_env(print:) Docker::Compose::Mapper.map(host_env, session: @session, net_info: @net_info) do |k, v| @@ -124,7 +126,7 @@ module Docker::Compose # Transform a Ruby value into a String that can be stored in the # environment. This accepts nil, String, or Array and returns nil, String # or JSON-serialized Array. - private def serialize_for_env(v) + def serialize_for_env(v) case v when String v @@ -138,7 +140,7 @@ module Docker::Compose end # Print an export or unset statement suitable for user's shell - private def print_env(k, v) + def print_env(k, v) if v puts @shell_printer.export(k, v) else @@ -146,7 +148,7 @@ module Docker::Compose end end - private def print_usage + def print_usage command = "rake #{rake_namespace}:env" command = 'bundle exec ' + command if defined?(Bundler) puts @shell_printer.comment('To export these variables to your shell, run:')
Fix Ruby <I> compatibility issues. Fixes #<I>.
xeger_docker-compose
train
62ec8f616941a38d96672c52d3a2616a3c77ecbe
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 @@ -128,7 +128,7 @@ class EBRupture(object): self.source_id = source_id self.trt_id = trt_id self.serial = serial - self.weight = 1 # set later on, before saving + self.weight = len(indices) * len(events) # changed in set_weight @property def etags(self): @@ -156,12 +156,15 @@ class EBRupture(object): """ return len(self.events) - def set_weight(self, num_rlzs_by_trt_id={}, num_assets_by_site={}): + def set_weight(self, num_rlzs_by_trt_id, num_assets_by_site_id): """ Set the weight attribute of each rupture with the formula weight = multiplicity * affected_sites * realizations + + :param num_rlzs_by_trt_id: dictionary, possibly empty + :param num_assets_by_site_id: dictionary, possibly empty """ - num_assets = sum(num_assets_by_site.get(sid, 1) + num_assets = sum(num_assets_by_site_id.get(sid, 1) for sid in self.indices) self.weight = (len(self.events) * num_assets * num_rlzs_by_trt_id.get(self.trt_id, 1)) @@ -402,9 +405,9 @@ def get_gmvs_by_sid(gmfa): """ def to_array(group): # this works with numpy 1.6 too records = list(group) - return numpy.array([record['gmv'] for record in records], records[0]['gmv'].dtype) + return numpy.array([record['gmv'] for record in records], + records[0]['gmv'].dtype) return groupby(gmfa, operator.itemgetter('sid'), to_array) - def fix_minimum_intensity(min_iml, imts): @@ -489,20 +492,12 @@ class EventBasedRuptureCalculator(ClassicalCalculator): """ logging.info('Generated %d EBRuptures', sum(len(v) for v in result.values())) - rlzs_by_tr_id = self.rlzs_assoc.get_rlzs_by_trt_id() - num_rlzs = {t: len(rlzs) for t, rlzs in rlzs_by_tr_id.items()} - if hasattr(self, 'assets_by_site'): - num_assets = {sid: len(self.assets_by_site[sid]) - for sid in self.sitecol.sids} - else: - num_assets = {} with self.monitor('saving ruptures', autoflush=True): # ordering ruptures sescollection = [] weights = [] for trt_id in result: for ebr in result[trt_id]: - ebr.set_weight(num_rlzs, num_assets) weights.append(ebr.weight) sescollection.append(ebr) sescollection.sort(key=operator.attrgetter('serial')) @@ -631,9 +626,13 @@ class EventBasedCalculator(ClassicalCalculator): (if any). If there were pre-existing files, they will be erased. """ super(EventBasedCalculator, self).pre_execute() + rlzs_by_tr_id = self.rlzs_assoc.get_rlzs_by_trt_id() + num_rlzs = {t: len(rlzs) for t, rlzs in rlzs_by_tr_id.items()} self.sesruptures = [] for serial in self.datastore['sescollection']: - self.sesruptures.append(self.datastore['sescollection/' + serial]) + sr = self.datastore['sescollection/' + serial] + sr.set_weight(num_rlzs, {}) + self.sesruptures.append(sr) self.sesruptures.sort(key=operator.attrgetter('serial')) gmv_dt = calc.gmf.gmv_dt(self.oqparam.imtls) if self.oqparam.ground_motion_fields: diff --git a/openquake/calculators/event_based_risk.py b/openquake/calculators/event_based_risk.py index <HASH>..<HASH> 100644 --- a/openquake/calculators/event_based_risk.py +++ b/openquake/calculators/event_based_risk.py @@ -247,9 +247,15 @@ class EventBasedRiskCalculator(base.RiskCalculator): self.N = len(self.assetcol) self.E = len(self.etags) logging.info('Populating the risk inputs') + rlzs_by_tr_id = self.rlzs_assoc.get_rlzs_by_trt_id() + num_rlzs = {t: len(rlzs) for t, rlzs in rlzs_by_tr_id.items()} + num_assets = {sid: len(self.assets_by_site[sid]) + for sid in self.sitecol.sids} all_ruptures = [] for serial in self.datastore['sescollection']: - all_ruptures.append(self.datastore['sescollection/' + serial]) + rup = self.datastore['sescollection/' + serial] + rup.set_weight(num_rlzs, num_assets) + all_ruptures.append(rup) all_ruptures.sort(key=operator.attrgetter('weight'), reverse=True) if not self.riskmodel.covs: # do not generate epsilons
Computed the rupture weight twice, one per hazard and one per risk
gem_oq-engine
train
b9d446a99b36a6424d32aebcea00e55b48c0d330
diff --git a/src/Guardian/HasGuardianTrait.php b/src/Guardian/HasGuardianTrait.php index <HASH>..<HASH> 100644 --- a/src/Guardian/HasGuardianTrait.php +++ b/src/Guardian/HasGuardianTrait.php @@ -22,9 +22,8 @@ trait HasGuardianTrait { public function permissions() { return $this->belongsToMany( - config('guardian.permission_model'), config('guardian.permission_user_table'), 'user_id', - config('guardian.permission_key') - ); + config('guardian.permission_model'), config('guardian.permission_user_table'), 'user_id', config('guardian.permission_key') + )->withPivot('value'); } } \ No newline at end of file diff --git a/src/Guardian/Permission.php b/src/Guardian/Permission.php index <HASH>..<HASH> 100644 --- a/src/Guardian/Permission.php +++ b/src/Guardian/Permission.php @@ -31,9 +31,8 @@ class Permission extends Model { public function roles() { return $this->belongsToMany( - config('guardian.role_model'), config('guardian.permission_role_table'), config('guardian.permission_key'), - config('guardian.role_key') - ); + config('guardian.role_model'), config('guardian.permission_role_table'), config('guardian.permission_key'), config('guardian.role_key') + )->withPivot('value'); } /** @@ -45,7 +44,7 @@ class Permission extends Model { { return $this->belongsToMany( config('auth.model'), config('guardian.permission_user_table'), config('guardian.permission_key'), 'user_id' - ); + )->withPivot('value'); } } \ No newline at end of file diff --git a/src/Guardian/Role.php b/src/Guardian/Role.php index <HASH>..<HASH> 100644 --- a/src/Guardian/Role.php +++ b/src/Guardian/Role.php @@ -43,9 +43,8 @@ class Role extends Model { public function permissions() { return $this->belongsToMany( - config('guardian.permission_model'), config('guardian.permission_role_table'), config('guardian.role_key'), - config('guardian.permission_key') - ); + config('guardian.permission_model'), config('guardian.permission_role_table'), config('guardian.role_key'), config('guardian.permission_key') + )->withPivot('value'); } } \ No newline at end of file diff --git a/src/resources/migrations/2015_02_23_161104_create_guardian_permission_user_table.php b/src/resources/migrations/2015_02_23_161104_create_guardian_permission_user_table.php index <HASH>..<HASH> 100644 --- a/src/resources/migrations/2015_02_23_161104_create_guardian_permission_user_table.php +++ b/src/resources/migrations/2015_02_23_161104_create_guardian_permission_user_table.php @@ -21,6 +21,8 @@ class CreateGuardianPermissionUserTable extends Migration { $table->foreign(config('guardian.permission_key', 'permission_id'))->references('id') ->on(config('guardian.permission_table', 'permissions')) ->onDelete('cascade'); + + $table->tinyInteger('value')->default(-1); }); } diff --git a/src/resources/migrations/2015_02_23_161105_create_guardian_permission_role_table.php b/src/resources/migrations/2015_02_23_161105_create_guardian_permission_role_table.php index <HASH>..<HASH> 100644 --- a/src/resources/migrations/2015_02_23_161105_create_guardian_permission_role_table.php +++ b/src/resources/migrations/2015_02_23_161105_create_guardian_permission_role_table.php @@ -23,6 +23,8 @@ class CreateGuardianPermissionRoleTable extends Migration { $table->foreign(config('guardian.role_key', 'role_id'))->references('id') ->on(config('guardian.role_table', 'roles')) ->onDelete('cascade'); + + $table->tinyInteger('value')->default(-1); }); }
Added value to store the permission value.
artesaos_defender
train
a01c43978a15d3ee5e7464b9a7cad715b190b146
diff --git a/pysparkling/sql/expressions/expressions.py b/pysparkling/sql/expressions/expressions.py index <HASH>..<HASH> 100644 --- a/pysparkling/sql/expressions/expressions.py +++ b/pysparkling/sql/expressions/expressions.py @@ -136,3 +136,15 @@ class Expression(object): child.expr.recursive_pre_evaluation_schema(schema) elif isinstance(child, (list, set, tuple)): Expression.children_pre_evaluation_schema(child, schema) + + +class UnaryExpression(Expression): + def __init__(self, column): + super(UnaryExpression, self).__init__(column) + self.column = column + + def eval(self, row, schema): + raise NotImplementedError + + def __str__(self): + raise NotImplementedError
Add a UnaryExpression class
svenkreiss_pysparkling
train
3960c00e3cf129c60b01fecdfe2851ba9ef7ba59
diff --git a/lib/filelib.php b/lib/filelib.php index <HASH>..<HASH> 100644 --- a/lib/filelib.php +++ b/lib/filelib.php @@ -2021,11 +2021,7 @@ function readfile_accel($file, $mimetype, $accelerate) { header('Last-Modified: '. gmdate('D, d M Y H:i:s', $lastmodified) .' GMT'); if (is_object($file)) { - if (empty($_SERVER['HTTP_RANGE'])) { - // Use Etag only when not byteserving, - // is it tag of this range or whole file? - header('Etag: ' . $file->get_contenthash()); - } + header('ETag: ' . $file->get_contenthash()); if (isset($_SERVER['HTTP_IF_NONE_MATCH']) and $_SERVER['HTTP_IF_NONE_MATCH'] === $file->get_contenthash()) { header('HTTP/1.1 304 Not Modified'); return; @@ -2675,10 +2671,6 @@ function byteserving_send_file($handle, $mimetype, $ranges, $filesize) { // better turn off any kind of compression and buffering @ini_set('zlib.output_compression', 'Off'); - // Remove Etag because is is not strictly defined for byteserving, - // is it tag of this range or whole file? - header_remove('Etag'); - $chunksize = 1*(1024*1024); // 1MB chunks - must be less than 2MB! if ($handle === false) { die; diff --git a/lib/xsendfilelib.php b/lib/xsendfilelib.php index <HASH>..<HASH> 100644 --- a/lib/xsendfilelib.php +++ b/lib/xsendfilelib.php @@ -68,12 +68,6 @@ function xsendfile($filepath) { } } - // Remove Etag because is is not strictly defined for byteserving, - // is it tag of this range or whole file? - if (!empty($_SERVER['HTTP_RANGE'])) { - header_remove('Etag'); - } - if ($CFG->xsendfile === 'X-LIGHTTPD-send-file') { // http://redmine.lighttpd.net/projects/lighttpd/wiki/X-LIGHTTPD-send-file says 1.4 it does not support byteserving header('Accept-Ranges: none');
MDL-<I> Files: Revert MDL-<I> commit, f<I>fe<I>a<I>ae<I>e3bf<I>d<I>bf<I>a1 MDL-<I> has been successful in providing a solution for the issue but further investigations done in MDL-<I> have got the evidence that the given solution is more likely a workaround.
moodle_moodle
train
5b549e39bc2450f31080467e97b4c1701691ef82
diff --git a/lib/twitter/base.rb b/lib/twitter/base.rb index <HASH>..<HASH> 100644 --- a/lib/twitter/base.rb +++ b/lib/twitter/base.rb @@ -31,7 +31,12 @@ module Twitter # @return [Twitter::Base] def self.fetch(attrs) @@identity_map[self] ||= {} - @@identity_map[self][Marshal.dump(attrs)] + if object = @@identity_map[self][Marshal.dump(attrs)] + return object + end + + return yield if block_given? + raise Twitter::IdentityMapKeyError, 'key not found' end # Stores an object in the identity map and returns the newly created @@ -39,9 +44,9 @@ module Twitter # # @param attrs [Hash] # @return [Twitter::Base] - def self.store(attrs) + def self.store(object) @@identity_map[self] ||= {} - @@identity_map[self][Marshal.dump(attrs)] = self.new(attrs) + @@identity_map[self][Marshal.dump(object.attrs)] = object end # Returns a new object based on the response hash @@ -58,7 +63,10 @@ module Twitter # @param attrs [Hash] # @return [Twitter::Base] def self.fetch_or_store(attrs={}) - self.fetch(attrs) || self.store(attrs) + self.fetch(attrs) do + object = self.new(attrs) + self.store(object) + end end # Initializes a new object diff --git a/lib/twitter/identity_map.rb b/lib/twitter/identity_map.rb index <HASH>..<HASH> 100644 --- a/lib/twitter/identity_map.rb +++ b/lib/twitter/identity_map.rb @@ -5,4 +5,7 @@ module Twitter class IdentityMap < Hash end + class IdentityMapKeyError < ::StandardError + end + end diff --git a/spec/twitter/base_spec.rb b/spec/twitter/base_spec.rb index <HASH>..<HASH> 100644 --- a/spec/twitter/base_spec.rb +++ b/spec/twitter/base_spec.rb @@ -3,7 +3,8 @@ require 'helper' describe Twitter::Base do before do - @base = Twitter::Base.store(:id => 1) + object = Twitter::Base.new(:id => 1) + @base = Twitter::Base.store(object) end describe "#[]" do @@ -37,14 +38,29 @@ describe Twitter::Base do Twitter::Base.fetch(:id => 1).should be end - it "retuns nil for objects that don't exist" do - Twitter::Base.fetch(:id => 2).should_not be + it "raises an error on objects that don't exist" do + lambda { + Twitter::Base.fetch(:id => 6) + }.should raise_error(Twitter::IdentityMapKeyError) end end describe '.store' do it 'stores Twitter::Base objects' do - Twitter::Base.store(:id => 1).should be_a Twitter::Base + object = Twitter::Base.new(:id => 4) + Twitter::Base.store(object).should be_a Twitter::Base + end + end + + describe '.fetch_or_store' do + it 'returns existing objects' do + Twitter::Base.fetch_or_store(:id => 1).should be + end + + it 'creates new objects and stores them' do + Twitter::Base.fetch_or_store(:id => 2).should be + + Twitter::Base.fetch(:id => 2).should be end end end
let Twitter::Base#fetch accept a block
sferik_twitter
train
d22c683bb68708269d3adf64ca0317c815400b5c
diff --git a/lib/thinreports/layout/legacy_schema.rb b/lib/thinreports/layout/legacy_schema.rb index <HASH>..<HASH> 100644 --- a/lib/thinreports/layout/legacy_schema.rb +++ b/lib/thinreports/layout/legacy_schema.rb @@ -349,7 +349,7 @@ module Thinreports end def line_height(legacy_line_height) - legacy_line_height == '' ? '' : legacy_line_height.to_f + blank_value?(legacy_line_height) ? '' : legacy_line_height.to_f end def letter_spacing(legacy_letter_spacing) diff --git a/test/unit/layout/test_legacy_schema.rb b/test/unit/layout/test_legacy_schema.rb index <HASH>..<HASH> 100644 --- a/test/unit/layout/test_legacy_schema.rb +++ b/test/unit/layout/test_legacy_schema.rb @@ -537,6 +537,7 @@ class Thinreports::Layout::TestLegacySchema < Minitest::Test def test_line_height assert_equal '', layout_legacy_schema.line_height('') + assert_equal '', layout_legacy_schema.line_height(nil) assert_equal 20.1, layout_legacy_schema.line_height('20.1') end
Fixed bug that line-height of text-block is always set to 0
thinreports_thinreports-generator
train
650bcc54db1c93a9b1022f144af22df62195a67d
diff --git a/lib/hawkins.rb b/lib/hawkins.rb index <HASH>..<HASH> 100644 --- a/lib/hawkins.rb +++ b/lib/hawkins.rb @@ -7,8 +7,8 @@ require 'stringex_lite' require 'thor' require 'hawkins/cli' -require 'hawkins/version' require 'hawkins/guard' +require 'hawkins/version' module Hawkins DEFAULT_EXTENSIONS = %w( diff --git a/lib/hawkins/cli.rb b/lib/hawkins/cli.rb index <HASH>..<HASH> 100644 --- a/lib/hawkins/cli.rb +++ b/lib/hawkins/cli.rb @@ -56,7 +56,7 @@ module Hawkins entire site. This option will ignore all files except the ones you specify in order to speed regeneration. - Keep in mind that Jekyll's exclusion mechanism is not aware of + Keep in mind that Jekyll's inclusion mechanism is not aware of subdirectories so this command operates on the basename of all files that match the file or glob you provide. LONGDESC @@ -97,10 +97,12 @@ module Hawkins isolation_config['include'].uniq! + # We have to write the isolation config out to a file so that the Guard + # can detect when the configuration changes. create_file(Hawkins::ISOLATION_FILE, YAML.dump(isolation_config)) begin - invoke(:serve, []) + serve ensure remove_file(Hawkins::ISOLATION_FILE) end @@ -108,22 +110,22 @@ module Hawkins desc "serve", "render and serve the site" def serve - isolation_config = jekyll_config.clone + config_files = jekyll_config.config_files({}) || [] if File.exist?(Hawkins::ISOLATION_FILE) - isolation_config.read_config_file(Hawkins::ISOLATION_FILE) + config_files << Hawkins::ISOLATION_FILE end - # TODO set ignore to jekyll_config['destination'] but by default Jekyll - # uses the absolute path and Guard doesn't so we need to fix that. + # By default Jekyll uses the absolute path and Guard doesn't so we need to fix that. + dest = Pathname.new(jekyll_config['destination']).relative_path_from(Pathname.new(Dir.pwd)) # FIXME: Figure out how to turn off interactor contents = <<-GUARDFILE.gsub(/^\s*/,'') # interactor :off notification :off guard 'hawkins', - :config_hash => #{isolation_config} do + :config => #{config_files} do watch %r{.*} - ignore %r{^_site} + ignore %r{^#{dest}} end guard 'livereload', diff --git a/lib/hawkins/isolation.rb b/lib/hawkins/isolation.rb index <HASH>..<HASH> 100644 --- a/lib/hawkins/isolation.rb +++ b/lib/hawkins/isolation.rb @@ -8,10 +8,12 @@ require 'set' module Hawkins class IsolationInjector attr_reader :site_root + attr_reader :isolation_file def initialize(options={}) @options = options @site_root = @options[:site_root] || Jekyll.configuration({})['destination'] + @isolation_file = @options[:isolation_file] || Hawkins::ISOLATION_FILE SafeYAML::OPTIONS[:default_mode] = :safe end @@ -46,38 +48,38 @@ module Hawkins end def handle_404(req, true_path) - if File.exist?(Hawkins::ISOLATION_FILE) + if File.exist?(isolation_file) file = true_path # Use a wildcard since the origin file could be anything file = "#{File.basename(file, File.extname(file))}.*".force_encoding('utf-8') - old_config = SafeYAML.load_file(ISOLATION_FILE) + config = SafeYAML.load_file(isolation_file) - file_set = Set.new(old_config['include']) + file_set = Set.new(config['include']) # Prevent loops. If it's already in 'include' # then we've gone through here before. return static_error if file_set.include?(file) - old_config['include'] = file_set.add(file).to_a + config['include'] = file_set.add(file).to_a - File.open(ISOLATION_FILE, 'w') do |f| - YAML.dump(old_config, f) + File.open(isolation_file, 'w') do |f| + YAML.dump(config, f) end response = <<-PAGE.gsub(/^\s*/, '') - <!DOCTYPE HTML> - <html lang="en-US"> - <head> - <meta charset="UTF-8"> - <title>Rendering #{req.path_info}</title> - </head> - <body> - <h1>Hold on while I render that page for you!</h1> - </body> + <!DOCTYPE HTML> + <html lang="en-US"> + <head> + <meta charset="UTF-8"> + <title>Rendering #{req.path_info}</title> + </head> + <body> + <h1>Hold on while I render that page for you!</h1> + </body> PAGE - headers ||= {} + headers = {} headers['Content-Length'] = response.bytesize.to_s headers['Content-Type'] = 'text/html' headers['Connection'] = 'keep-alive'
Skip using Thor's invoke; Read config from files. Since the isolation middleware needs to modify the isolation config Guard needs to read that config from a file (or else I need to figure out how to pass a hash back and forth).
awood_hawkins
train
278222cc8eb1e3474c38eb82f9857dfaa06f5a1e
diff --git a/spec/country_spec.rb b/spec/country_spec.rb index <HASH>..<HASH> 100644 --- a/spec/country_spec.rb +++ b/spec/country_spec.rb @@ -48,7 +48,7 @@ describe ISO3166::Country do end it 'should return alternate names' do - expect(country.names).to eq(['United States', 'Vereinigte Staaten von Amerika', 'États-Unis', 'Estados Unidos', 'アメリカ合衆国', 'Verenigde Staten']) + expect(country.names).to eq(['United States', 'Murica', 'Vereinigte Staaten von Amerika', 'États-Unis', 'Estados Unidos', 'アメリカ合衆国', 'Verenigde Staten']) end it 'should return translations' do
Fixes failing rspec assertions after cache update
hexorx_countries
train
28dd5d71eaa45c015a612c4a97caa26046dd2ba9
diff --git a/README.md b/README.md index <HASH>..<HASH> 100644 --- a/README.md +++ b/README.md @@ -20,15 +20,15 @@ For use in the browser, use [browserify](https://github.com/substack/node-browse var isPermutation = require( 'validate.io-permutation' ); ``` -#### isPermutation( value, arr ) +#### isPermutation( arr, value ) -Validates if a `value` is a permutation. The second argument defines the list of values which can be permuted. The list `array` need not be unique. +Validates if a `value` is an `array` permutation. The first argument defines the list of values which can be permuted. The list `array` need not be unique. ``` javascript var arr = [1,2,3], value = [2,3,1]; -var bool = isPermutation( value, arr ); +var bool = isPermutation( arr, value ); // returns true ``` @@ -38,13 +38,13 @@ var bool = isPermutation( value, arr ); ``` javascript var isPermutation = require( 'validate.io-permutation' ); -console.log( isPermutation( [2,3,1], [1,2,3] ) ); +console.log( isPermutation( [1,2,3], [2,3,1] ) ); // returns true -console.log( isPermutation( [1,4,3], [1,2,3] ) ); +console.log( isPermutation( [1,2,3], [1,4,3] ) ); // returns false -console.log( isPermutation( ['a','b'], ['a','c','b'] ) ); +console.log( isPermutation( ['a','c','b'], ['a','b'] ) ); // returns false ``` diff --git a/examples/index.js b/examples/index.js index <HASH>..<HASH> 100644 --- a/examples/index.js +++ b/examples/index.js @@ -2,11 +2,11 @@ var isPermutation = require( './../lib' ); -console.log( isPermutation( [2,3,1], [1,2,3] ) ); +console.log( isPermutation( [1,2,3], [2,3,1] ) ); // returns true -console.log( isPermutation( [1,4,3], [1,2,3] ) ); +console.log( isPermutation( [1,2,3], [1,4,3] ) ); // returns false -console.log( isPermutation( ['a','b'], ['a','c','b'] ) ); +console.log( isPermutation( ['a','c','b'], ['a','b'] ) ); // returns false diff --git a/lib/index.js b/lib/index.js index <HASH>..<HASH> 100644 --- a/lib/index.js +++ b/lib/index.js @@ -36,14 +36,14 @@ var isArray = require( 'validate.io-array' ); // ISPERMUTATION // /** -* FUNCTION: isPermutation( value, arr ) +* FUNCTION: isPermutation( arr, value ) * Validates if a value is a permutation. * -* @param {*} value - value to be validated * @param {Array} arr - array containing elements which can be permuted +* @param {*} value - value to be validated * @returns {Boolean} boolean indicating if a value is a permutation */ -function isPermutation( value, arr ) { +function isPermutation( arr, value ) { var len, N, x, i, j; if ( !isArray( arr ) ) { throw new TypeError( 'isPermutation()::invalid input argument. Second argument must be an array. Value: `' + arr + '`.' ); diff --git a/test/test.js b/test/test.js index <HASH>..<HASH> 100644 --- a/test/test.js +++ b/test/test.js @@ -41,13 +41,13 @@ describe( 'validate.io-permutation', function tests() { } function badValue( value ) { return function() { - isPermutation( [], value ); + isPermutation( value, [] ); }; } }); it( 'should positively validate', function test() { - var bool = isPermutation( [2,3,1], [1,2,3] ); + var bool = isPermutation( [1,2,3], [2,3,1] ); assert.ok( bool ); }); @@ -71,7 +71,7 @@ describe( 'validate.io-permutation', function tests() { assert.notOk( badValue( values[i] ) ); } function badValue( value ) { - return isPermutation( value, [1,2,3] ); + return isPermutation( [1,2,3], value ); } }); @@ -84,7 +84,7 @@ describe( 'validate.io-permutation', function tests() { list = [ obj, arr, obj, arr ]; value = [ arr, arr, obj, obj ]; - assert.ok( isPermutation( value, list ) ); + assert.ok( isPermutation( list, value ) ); }); });
[UPDATE] switch arg order.
validate-io_permutation
train
56fd74e0e8bde7e3a907382e7a1d56d55cd689ab
diff --git a/lib/ooor/naming.rb b/lib/ooor/naming.rb index <HASH>..<HASH> 100644 --- a/lib/ooor/naming.rb +++ b/lib/ooor/naming.rb @@ -21,13 +21,13 @@ module Ooor module ClassMethods def model_name @_model_name ||= begin - unless self.respond_to? :openerp_model - super - else + if self.respond_to? :openerp_model namespace = self.parents.detect do |n| n.respond_to?(:use_relative_model_naming?) && n.use_relative_model_naming? end Ooor::Naming::Name.new(self, namespace) + else + super end end end
minor change in naming.rb
akretion_ooor
train
7cf0b685cd571cf0c1d10b201dec0d6c712ae586
diff --git a/eZ/Publish/Core/REST/Common/Input/Dispatcher.php b/eZ/Publish/Core/REST/Common/Input/Dispatcher.php index <HASH>..<HASH> 100644 --- a/eZ/Publish/Core/REST/Common/Input/Dispatcher.php +++ b/eZ/Publish/Core/REST/Common/Input/Dispatcher.php @@ -106,6 +106,10 @@ class Dispatcher { $rootNodeArray['__url'] = $message->headers['Url']; } + if ( isset( $message->headers['__publish'] ) ) + { + $rootNodeArray['__publish'] = $message->headers['__publish']; + } return $this->parsingDispatcher->parse( $rootNodeArray, $media diff --git a/eZ/Publish/Core/REST/Server/Controller/ContentType.php b/eZ/Publish/Core/REST/Server/Controller/ContentType.php index <HASH>..<HASH> 100644 --- a/eZ/Publish/Core/REST/Server/Controller/ContentType.php +++ b/eZ/Publish/Core/REST/Server/Controller/ContentType.php @@ -275,6 +275,7 @@ class ContentType extends RestController public function createContentType( $contentTypeGroupId ) { $contentTypeGroup = $this->contentTypeService->loadContentTypeGroup( $contentTypeGroupId ); + $publish = ( $this->request->query->has( 'publish' ) && $this->request->query->get( 'publish' ) === 'true' ); try { @@ -283,6 +284,8 @@ class ContentType extends RestController new Message( array( 'Content-Type' => $this->request->headers->get( 'Content-Type' ), + // @todo Needs refactoring! Temporary solution so parser has access to get parameters + '__publish' => $publish ), $this->request->getContent() ) @@ -303,7 +306,7 @@ class ContentType extends RestController throw new BadRequestException( $e->getMessage() ); } - if ( $this->request->query->has( 'publish' ) && $this->request->query->get( 'publish' ) === 'true' ) + if ( $publish ) { $this->contentTypeService->publishContentTypeDraft( $contentTypeDraft, 'bla' ); diff --git a/eZ/Publish/Core/REST/Server/Input/Parser/ContentTypeCreate.php b/eZ/Publish/Core/REST/Server/Input/Parser/ContentTypeCreate.php index <HASH>..<HASH> 100644 --- a/eZ/Publish/Core/REST/Server/Input/Parser/ContentTypeCreate.php +++ b/eZ/Publish/Core/REST/Server/Input/Parser/ContentTypeCreate.php @@ -162,10 +162,25 @@ class ContentTypeCreate extends Base $contentTypeCreateStruct->creatorId = $this->requestParser->parseHref( $data['User']['_href'], 'userId' ); } - if ( !array_key_exists( 'FieldDefinitions', $data ) || !is_array( $data['FieldDefinitions'] ) || - !array_key_exists( 'FieldDefinition', $data['FieldDefinitions'] ) || !is_array( $data['FieldDefinitions']['FieldDefinition'] ) ) + if ( !array_key_exists( 'FieldDefinitions', $data ) ) { - throw new Exceptions\Parser( "Missing or invalid 'FieldDefinitions' element for ContentTypeCreate." ); + throw new Exceptions\Parser( "Missing 'FieldDefinitions' element for ContentTypeCreate." ); + } + + if ( + !is_array( $data['FieldDefinitions'] ) || + !array_key_exists( 'FieldDefinition', $data['FieldDefinitions'] ) || + !is_array( $data['FieldDefinitions']['FieldDefinition'] ) + ) + { + throw new Exceptions\Parser( "Invalid 'FieldDefinitions' element for ContentTypeCreate." ); + } + + // With no field definitions given and when ContentType is immediately published we must return HTTP 400 BadRequest, + // instead of relying on service to throw InvalidArgumentException + if ( isset( $data["__publish"] ) && $data["__publish"] === true && empty( $data['FieldDefinitions']['FieldDefinition'] ) ) + { + throw new Exceptions\Parser( "ContentTypeCreate should provide at least one field definition." ); } foreach ( $data['FieldDefinitions']['FieldDefinition'] as $fieldDefinitionData )
EZP-<I>: handle creating content type with immediate publish
ezsystems_ezpublish-kernel
train
223c93f69dd3095effd5c59e3df4a2ac5d3d656f
diff --git a/payload/builder.go b/payload/builder.go index <HASH>..<HASH> 100644 --- a/payload/builder.go +++ b/payload/builder.go @@ -16,7 +16,7 @@ type aps struct { Category string `json:"category,omitempty"` ContentAvailable int `json:"content-available,omitempty"` MutableContent int `json:"mutable-content,omitempty"` - Sound string `json:"sound,omitempty"` + Sound interface{} `json:"sound,omitempty"` ThreadID string `json:"thread-id,omitempty"` URLArgs []string `json:"url-args,omitempty"` } @@ -34,6 +34,12 @@ type alert struct { TitleLocKey string `json:"title-loc-key,omitempty"` } +type sound struct { + Critical int `json:"critical,omitempty"` + Name string `json:"name,omitempty"` + Volume float32 `json:"volume,omitempty"` +} + // NewPayload returns a new Payload struct func NewPayload() *Payload { return &Payload{ @@ -84,7 +90,7 @@ func (p *Payload) UnsetBadge() *Payload { // This will play a sound from the app bundle, or the default sound otherwise. // // {"aps":{"sound":sound}} -func (p *Payload) Sound(sound string) *Payload { +func (p *Payload) Sound(sound interface{}) *Payload { p.aps().Sound = sound return p } @@ -274,6 +280,26 @@ func (p *Payload) URLArgs(urlArgs []string) *Payload { return p } +// SoundName sets the name value on the aps sound dictionary. +// This function makes the notification a critical alert, which should be pre-approved by Apple. +// See: https://developer.apple.com/contact/request/notifications-critical-alerts-entitlement/ +// +// {"aps":{"sound":{"critical":1,"name":name,"volume":1.0}}} +func (p *Payload) SoundName(name string) *Payload { + p.aps().sound().Name = name + return p +} + +// SoundVolume sets the volume value on the aps sound dictionary. +// This function makes the notification a critical alert, which should be pre-approved by Apple. +// See: https://developer.apple.com/contact/request/notifications-critical-alerts-entitlement/ +// +// {"aps":{"sound":{"critical":1,"name":"default","volume":volume}}} +func (p *Payload) SoundVolume(volume float32) *Payload { + p.aps().sound().Volume = volume + return p +} + // MarshalJSON returns the JSON encoded version of the Payload func (p *Payload) MarshalJSON() ([]byte, error) { return json.Marshal(p.content) @@ -289,3 +315,10 @@ func (a *aps) alert() *alert { } return a.Alert.(*alert) } + +func (a *aps) sound() *sound { + if _, ok := a.Sound.(*sound); !ok { + a.Sound = &sound{Critical: 1, Name: "default", Volume: 1.0} + } + return a.Sound.(*sound) +} diff --git a/payload/builder_test.go b/payload/builder_test.go index <HASH>..<HASH> 100644 --- a/payload/builder_test.go +++ b/payload/builder_test.go @@ -44,6 +44,16 @@ func TestSound(t *testing.T) { assert.Equal(t, `{"aps":{"sound":"Default.caf"}}`, string(b)) } +func TestSoundDictionary(t *testing.T) { + payload := NewPayload().Sound(map[string]interface{}{ + "critical": 1, + "name": "default", + "volume": 0.8, + }) + b, _ := json.Marshal(payload) + assert.Equal(t, `{"aps":{"sound":{"critical":1,"name":"default","volume":0.8}}}`, string(b)) +} + func TestContentAvailable(t *testing.T) { payload := NewPayload().ContentAvailable() b, _ := json.Marshal(payload) @@ -154,6 +164,18 @@ func TestURLArgs(t *testing.T) { assert.Equal(t, `{"aps":{"url-args":["a","b"]}}`, string(b)) } +func TestSoundName(t *testing.T) { + payload := NewPayload().SoundName("test") + b, _ := json.Marshal(payload) + assert.Equal(t, `{"aps":{"sound":{"critical":1,"name":"test","volume":1}}}`, string(b)) +} + +func TestSoundVolume(t *testing.T) { + payload := NewPayload().SoundVolume(0.5) + b, _ := json.Marshal(payload) + assert.Equal(t, `{"aps":{"sound":{"critical":1,"name":"default","volume":0.5}}}`, string(b)) +} + func TestCombined(t *testing.T) { payload := NewPayload().Alert("hello").Badge(1).Sound("Default.caf").Custom("key", "val") b, _ := json.Marshal(payload)
Support iOS <I> Critical Alerts (#<I>) * Support sound dictionaries for critical alerts
sideshow_apns2
train
a0aea912e4bd8932ec1d833b0a718d9192356083
diff --git a/activerecord/lib/active_record/associations/singular_association.rb b/activerecord/lib/active_record/associations/singular_association.rb index <HASH>..<HASH> 100644 --- a/activerecord/lib/active_record/associations/singular_association.rb +++ b/activerecord/lib/active_record/associations/singular_association.rb @@ -56,9 +56,9 @@ module ActiveRecord end binds = AssociationScope.get_bind_values(owner, reflection.chain) - if record = sc.execute(binds, klass, conn).first + sc.execute(binds, klass, conn) do |record| set_inverse_instance record - end + end.first end def replace(record)
Pass `set_inverse_instance` block to `sc.execute` for `SingularAssociation` Follow up to caa<I>c. caa<I>c updated all code which sets inverse instances on newly loaded associations to use block. But `SingularAssociation` was forgotten it.
rails_rails
train
3efd901b4d632a2ec6f5cb58193080924495058d
diff --git a/extension-impl/remoting-resteasy/src/main/java/com/alipay/sofa/rpc/server/rest/SofaRestRequestHandler.java b/extension-impl/remoting-resteasy/src/main/java/com/alipay/sofa/rpc/server/rest/SofaRestRequestHandler.java index <HASH>..<HASH> 100644 --- a/extension-impl/remoting-resteasy/src/main/java/com/alipay/sofa/rpc/server/rest/SofaRestRequestHandler.java +++ b/extension-impl/remoting-resteasy/src/main/java/com/alipay/sofa/rpc/server/rest/SofaRestRequestHandler.java @@ -120,6 +120,10 @@ public class SofaRestRequestHandler extends SimpleChannelInboundHandler { response.finish(); } } finally { + /** + * issue: https://github.com/sofastack/sofa-rpc/issues/592 + */ + request.releaseContentBuffer(); if (EventBus.isEnable(ServerEndHandleEvent.class)) { EventBus.post(new ServerEndHandleEvent()); }
Fix resteasy memory leak. (#<I>)
alipay_sofa-rpc
train
02531d03894c2850b1c7d159194370049c4edd63
diff --git a/lib/lolita/mapping.rb b/lib/lolita/mapping.rb index <HASH>..<HASH> 100644 --- a/lib/lolita/mapping.rb +++ b/lib/lolita/mapping.rb @@ -18,13 +18,15 @@ module Lolita # Also eahc request containers information with mapping related to it. class Mapping attr_reader :class_name,:path,:singular,:plural,:path_prefix,:module,:controllers,:as - attr_reader :visible, :only, :append_to + attr_reader :visible, :only, :append_to, :title alias :name :singular def initialize(name,options={}) # TODO how it is when lolita plugin extend default path and there is module is this not break the logic? @as=options[:as] + @title = options[:title] + @to = options[:to].is_a?(String) ? options[:to].constantize : options[:to] @visible = options.keys.include?(:visible) ? options[:visible] : true @append_to = options[:append_to] @only = options[:only] || nil @@ -43,7 +45,7 @@ module Lolita # Return class that is related with mapping. def to - @ref.constantize rescue nil + @to || (@ref.constantize rescue nil) end # full path of current mapping @@ -69,7 +71,7 @@ module Lolita tree = parent_branch.children end unless tree.branches.detect{|b| b.object.is_a?(Lolita::Mapping) && b.object.to==self.to} - tree.append(self) + tree.append(self, :title => @title) end end end diff --git a/lib/lolita/navigation/branch.rb b/lib/lolita/navigation/branch.rb index <HASH>..<HASH> 100644 --- a/lib/lolita/navigation/branch.rb +++ b/lib/lolita/navigation/branch.rb @@ -26,7 +26,9 @@ module Lolita if @title && @title.respond_to?(:call) @title.call(self) else - @title || (self.object.to && self.object.to.model_name.human(:count=>2)) + @title || + (self.object.to && (object.to.respond_to?(:model_name) && self.object.to.model_name.human(:count=>2)) || self.object.to.to_s) || + ::I18n.t("lolita.navigation.#{object.name}") end end diff --git a/lib/lolita/rails/routes.rb b/lib/lolita/rails/routes.rb index <HASH>..<HASH> 100644 --- a/lib/lolita/rails/routes.rb +++ b/lib/lolita/rails/routes.rb @@ -51,7 +51,6 @@ module ActionDispatch::Routing options[:module] ||= @scope[:module] if @scope[:module].present? options[:path_prefix] ||= @scope[:path] if @scope[:path].present? resources.map!(&:to_sym) - all_resource_classes=[] resources.each{|resource| mapping = Lolita.add_mapping(resource,options)
mapping updated to have #title and #to; branch#title updated to fallback to simpler titles for object
ithouse_lolita
train
59211a4e5fb900b0fdf06ac5586276645ead66c4
diff --git a/lib/bolt/cli.rb b/lib/bolt/cli.rb index <HASH>..<HASH> 100644 --- a/lib/bolt/cli.rb +++ b/lib/bolt/cli.rb @@ -109,7 +109,7 @@ HELP opts.on_tail('--verbose', 'Display verbose logging') do |_| Bolt.log_level = Logger::INFO end - opts.on_tail('--debug', 'Display verbose logging') do |_| + opts.on_tail('--debug', 'Display debug logging') do |_| Bolt.log_level = Logger::DEBUG end opts.on_tail('--version', 'Display the version') do |_|
(maint) Correct help message for debug flag Previously both --debug and --verbose had the same help text.
puppetlabs_bolt
train
b9dfb969c97303e50823857939312ef6380b2e67
diff --git a/liquibase-extension-testing/src/main/java/liquibase/extension/testing/testsystem/core/MSSQLTestSystem.java b/liquibase-extension-testing/src/main/java/liquibase/extension/testing/testsystem/core/MSSQLTestSystem.java index <HASH>..<HASH> 100644 --- a/liquibase-extension-testing/src/main/java/liquibase/extension/testing/testsystem/core/MSSQLTestSystem.java +++ b/liquibase-extension-testing/src/main/java/liquibase/extension/testing/testsystem/core/MSSQLTestSystem.java @@ -35,7 +35,7 @@ public class MSSQLTestSystem extends DatabaseTestSystem { public String getConnectionUrl() { final JdbcDatabaseContainer container = ((DockerDatabaseWrapper) wrapper).getContainer(); - return "jdbc:sqlserver://" + container.getHost() + ":" + container.getMappedPort(MSSQLServerContainer.MS_SQL_SERVER_PORT)+";databaseName="+getCatalog()+";encrypt=false"; + return "jdbc:sqlserver://" + container.getHost() + ":" + container.getMappedPort(MSSQLServerContainer.MS_SQL_SERVER_PORT)+";databaseName="+getCatalog()+";trustServerCertificate=true;encrypt=false"; } @Override protected String[] getSetupSql() {
driver version upgrade requires to add trustServerCertificate to be added to jdbc url
liquibase_liquibase
train
4c393fb987e82f9c94205a2b609104561b0053ea
diff --git a/shardingsphere-proxy/shardingsphere-proxy-backend/src/test/java/org/apache/shardingsphere/proxy/backend/communication/jdbc/connection/JDBCBackendConnectionTest.java b/shardingsphere-proxy/shardingsphere-proxy-backend/src/test/java/org/apache/shardingsphere/proxy/backend/communication/jdbc/connection/JDBCBackendConnectionTest.java index <HASH>..<HASH> 100644 --- a/shardingsphere-proxy/shardingsphere-proxy-backend/src/test/java/org/apache/shardingsphere/proxy/backend/communication/jdbc/connection/JDBCBackendConnectionTest.java +++ b/shardingsphere-proxy/shardingsphere-proxy-backend/src/test/java/org/apache/shardingsphere/proxy/backend/communication/jdbc/connection/JDBCBackendConnectionTest.java @@ -202,27 +202,6 @@ public final class JDBCBackendConnectionTest { } @Test - public void assertMultiThreadsGetConnection() throws SQLException, InterruptedException { - MockConnectionUtil.setCachedConnections(backendConnection, "ds1", 10); - when(backendDataSource.getConnections(anyString(), anyString(), eq(2), any())).thenReturn(MockConnectionUtil.mockNewConnections(2)); - Thread thread1 = new Thread(this::assertOneThreadResult); - Thread thread2 = new Thread(this::assertOneThreadResult); - thread1.start(); - thread2.start(); - thread1.join(); - thread2.join(); - } - - @SneakyThrows(SQLException.class) - private void assertOneThreadResult() { - connectionSession.getTransactionStatus().setInTransaction(true); - List<Connection> actualConnections = backendConnection.getConnections("ds1", 12, ConnectionMode.MEMORY_STRICTLY); - assertThat(actualConnections.size(), is(12)); - assertThat(backendConnection.getConnectionSize(), is(12)); - assertTrue(connectionSession.getTransactionStatus().isInTransaction()); - } - - @Test public void assertIsNotSerialExecuteWhenNotInTransaction() { connectionSession.getTransactionStatus().setInTransaction(false); assertFalse(backendConnection.isSerialExecute());
delete invoid test case (#<I>)
apache_incubator-shardingsphere
train
445b344d028193fc693bc1fa10858f27cf15f50e
diff --git a/src/Kunstmaan/FormBundle/Tests/Entity/PageParts/SingleLineTextPagePartTest.php b/src/Kunstmaan/FormBundle/Tests/Entity/PageParts/SingleLineTextPagePartTest.php index <HASH>..<HASH> 100644 --- a/src/Kunstmaan/FormBundle/Tests/Entity/PageParts/SingleLineTextPagePartTest.php +++ b/src/Kunstmaan/FormBundle/Tests/Entity/PageParts/SingleLineTextPagePartTest.php @@ -7,7 +7,7 @@ use ArrayObject; use Kunstmaan\FormBundle\Entity\PageParts\SingleLineTextPagePart; use Kunstmaan\FormBundle\Form\SingleLineTextPagePartAdminType; -use Symfony\Component\Form\FormBuilderInterface;; +use Symfony\Component\Form\FormBuilderInterface; /** * Tests for SingleLineTextPagePart diff --git a/src/Kunstmaan/NodeBundle/Tests/Helper/Menu/ActionsMenuBuilderTest.php b/src/Kunstmaan/NodeBundle/Tests/Helper/Menu/ActionsMenuBuilderTest.php index <HASH>..<HASH> 100644 --- a/src/Kunstmaan/NodeBundle/Tests/Helper/Menu/ActionsMenuBuilderTest.php +++ b/src/Kunstmaan/NodeBundle/Tests/Helper/Menu/ActionsMenuBuilderTest.php @@ -122,10 +122,10 @@ class ActionsMenuBuilderTest extends \PHPUnit_Framework_TestCase $this->assertNull($menu->getChild('action.save')); if ((null !== $nodeTranslation->getNode()->getParent() || $nodeTranslation->getNode()->getChildren()->isEmpty())) { - $this->assertNotNull($menu->getChild('action.delete'));; + $this->assertNotNull($menu->getChild('action.delete')); } else { - $this->assertNull($menu->getChild('action.delete'));; + $this->assertNull($menu->getChild('action.delete')); } $this->assertEquals('page-main-actions js-auto-collapse-buttons', $menu->getChildrenAttribute('class')); @@ -154,10 +154,10 @@ class ActionsMenuBuilderTest extends \PHPUnit_Framework_TestCase $this->assertNotNull($menu->getChild('action.publish')); $this->assertNull($menu->getChild('action.unpublish')); if ((null !== $nodeTranslation->getNode()->getParent() || $nodeTranslation->getNode()->getChildren()->isEmpty())) { - $this->assertNotNull($menu->getChild('action.delete'));; + $this->assertNotNull($menu->getChild('action.delete')); } else { - $this->assertNull($menu->getChild('action.delete'));; + $this->assertNull($menu->getChild('action.delete')); } $nodeTranslation->setOnline(true); @@ -169,10 +169,10 @@ class ActionsMenuBuilderTest extends \PHPUnit_Framework_TestCase $this->assertNull($menu->getChild('action.publish')); $this->assertNotNull($menu->getChild('action.unpublish')); if ((null !== $nodeTranslation->getNode()->getParent() || $nodeTranslation->getNode()->getChildren()->isEmpty())) { - $this->assertNotNull($menu->getChild('action.delete'));; + $this->assertNotNull($menu->getChild('action.delete')); } else { - $this->assertNull($menu->getChild('action.delete'));; + $this->assertNull($menu->getChild('action.delete')); } $this->assertEquals('page-main-actions js-auto-collapse-buttons', $menu->getChildrenAttribute('class')); diff --git a/src/Kunstmaan/TranslatorBundle/Command/ExportTranslationsCommand.php b/src/Kunstmaan/TranslatorBundle/Command/ExportTranslationsCommand.php index <HASH>..<HASH> 100644 --- a/src/Kunstmaan/TranslatorBundle/Command/ExportTranslationsCommand.php +++ b/src/Kunstmaan/TranslatorBundle/Command/ExportTranslationsCommand.php @@ -14,11 +14,11 @@ class ExportTranslationsCommand extends ContainerAwareCommand protected function configure() { $this - ->setName('kuma:translator:export') - ->setDescription('Export stashed translations into files (gzip compressed)') - ->addOption('domains', 'd', InputOption::VALUE_REQUIRED, 'Specify which domains to export, default all domains in the stash') - ->addOption('format', 'f', InputOption::VALUE_REQUIRED, 'Specify which format files should be, default is yaml') - ->addOption('locales', 'l', InputOption::VALUE_REQUIRED, 'Specifiy which locales to export, default all in the stash'); + ->setName('kuma:translator:export') + ->setDescription('Export stashed translations into files (gzip compressed)') + ->addOption('domains', 'd', InputOption::VALUE_REQUIRED, 'Specify which domains to export, default all domains in the stash') + ->addOption('format', 'f', InputOption::VALUE_REQUIRED, 'Specify which format files should be, default is yaml') + ->addOption('locales', 'l', InputOption::VALUE_REQUIRED, 'Specifiy which locales to export, default all in the stash') ; }
Remove double (unnecessary) semicolon
Kunstmaan_KunstmaanBundlesCMS
train
fb3c01fe1ca78453920c3c2e4d245de4e0ebd40d
diff --git a/manticore/core/cpu/x86.py b/manticore/core/cpu/x86.py index <HASH>..<HASH> 100644 --- a/manticore/core/cpu/x86.py +++ b/manticore/core/cpu/x86.py @@ -889,7 +889,13 @@ class X86Cpu(Cpu): :param dest: destination operand. :param src: source operand. ''' - res = dest.write(dest.read() & src.read()) + # XXX bypass a capstone bug that incorrectly extends and computes operands sizes + # the bug has been fixed since capstone 4.0.alpha2 (commit de8dd26) + if src.size == 64 and src.type == 'immediate' and dest.size == 64: + arg1 = Operators.SEXTEND(src.read(), 32, 64) + else: + arg1 = src.read() + res = dest.write(dest.read() & arg1) # Defined Flags: szp cpu._calculate_logic_flags(dest.size, res) diff --git a/tests/test_cpu_manual.py b/tests/test_cpu_manual.py index <HASH>..<HASH> 100644 --- a/tests/test_cpu_manual.py +++ b/tests/test_cpu_manual.py @@ -711,6 +711,42 @@ class SymCPUTest(unittest.TestCase): self.assertTrue(solver.check(cs)) + # regression test for issue #560 + def test_AND_1(self): + ''' Instruction AND + Groups: + 0x7ffff7de390a: and rax, 0xfc000000 + ''' + mem = Memory64() + cpu = AMD64Cpu(mem) + mem.mmap(0x7ffff7de3000, 0x1000, 'rwx') + mem[0x7ffff7de390a] = '\x48' + mem[0x7ffff7de390b] = '\x25' + mem[0x7ffff7de390c] = '\x00' + mem[0x7ffff7de390d] = '\x00' + mem[0x7ffff7de390e] = '\x00' + mem[0x7ffff7de390f] = '\xfc' + cpu.PF = True + cpu.RAX = 0x7ffff7ff7658 + cpu.OF = False + cpu.ZF = False + cpu.CF = False + cpu.RIP = 0x7ffff7de390a + cpu.SF = False + cpu.execute() + self.assertEqual(mem[0x7ffff7de390a], '\x48') + self.assertEqual(mem[0x7ffff7de390b], '\x25') + self.assertEqual(mem[0x7ffff7de390c], '\x00') + self.assertEqual(mem[0x7ffff7de390d], '\x00') + self.assertEqual(mem[0x7ffff7de390e], '\x00') + self.assertEqual(mem[0x7ffff7de390f], '\xfc') + self.assertEqual(cpu.PF, True) + self.assertEqual(cpu.RAX, 0x7ffff4000000) + self.assertEqual(cpu.OF, False) + self.assertEqual(cpu.ZF, False) + self.assertEqual(cpu.CF, False) + self.assertEqual(cpu.RIP, 0x7ffff7de3910) + self.assertEqual(cpu.SF, False) def test_CMPXCHG8B_symbolic(self): '''CMPXCHG8B'''
Sign extends x<I> AND operand (capstone bug) (#<I>) * Sign extends x<I> AND operand (capstone bug) Fixes #<I> * Regression test for X<I> AND with sign extension For issue #<I>
trailofbits_manticore
train
907d4beff33cbeccd4ab5c81cff8ed020a1dba2f
diff --git a/abydos/distance/_token_distance.py b/abydos/distance/_token_distance.py index <HASH>..<HASH> 100644 --- a/abydos/distance/_token_distance.py +++ b/abydos/distance/_token_distance.py @@ -118,7 +118,7 @@ class _TokenDistance(_Distance): if 'alphabet' in self.params: if isinstance(self.params['alphabet'], str): self.params['alphabet'] = set(self.params['alphabet']) - if isinstance(QGrams, self.params['tokenizer']): + if isinstance(self.params['tokenizer'], QGrams): self.params['alphabet'] |= set( self.params['tokenizer'].start_stop ) @@ -129,7 +129,7 @@ class _TokenDistance(_Distance): if hasattr(self.params['alphabet'], '__len__'): self.params['alphabet'] = len(self.params['alphabet']) else: - if isinstance(QGrams, self.params['tokenizer']): + if isinstance(self.params['tokenizer'], QGrams): self.params['alphabet'] = ( 26 + len(set(self.params['tokenizer'].start_stop)) ) ** self.params['tokenizer'].qval @@ -250,7 +250,7 @@ class _TokenDistance(_Distance): """Return the cardinality of the complement of the total.""" if self.params['alphabet'] is None: return 0 - elif isinstance(Counter, self.params['alphabet']): + elif isinstance(self.params['alphabet'], Counter): return sum((self.params['alphabet']).values() - self.total()) return self.params['alphabet'] - len(self.total().values())
corrected order of args for isinstance
chrislit_abydos
train
235ffc234de42b9eac7f8f94aa11a04dc1bb9abf
diff --git a/server/config.go b/server/config.go index <HASH>..<HASH> 100644 --- a/server/config.go +++ b/server/config.go @@ -37,7 +37,7 @@ type Config struct { MaxRetryAttempts int `toml:"max_retry_attempts" env:"ETCD_MAX_RETRY_ATTEMPTS"` Name string `toml:"name" env:"ETCD_NAME"` Snapshot bool `toml:"snapshot" env:"ETCD_SNAPSHOT"` - SnapCount int `toml:"snap_count" env:"ETCD_SNAPCOUNT"` + SnapCount int `toml:"snapshot_count" env:"ETCD_SNAPSHOTCOUNT"` Verbose bool `toml:"verbose" env:"ETCD_VERBOSE"` VeryVerbose bool `toml:"very_verbose" env:"ETCD_VERY_VERBOSE"` WebURL string `toml:"web_url" env:"ETCD_WEB_URL"` @@ -203,7 +203,7 @@ func (c *Config) LoadFlags(arguments []string) error { f.StringVar(&cors, "cors", "", "whitelist origins for cross-origin resource sharing (e.g. '*' or 'http://localhost:8001,etc')") f.BoolVar(&c.Snapshot, "snapshot", c.Snapshot, "open or close snapshot") - f.IntVar(&c.SnapCount, "snapCount", c.SnapCount, "save the in memory logs and states to a snapshot file after snapCount transactions") + f.IntVar(&c.SnapCount, "snapshotCount", c.SnapCount, "save the in memory logs and states to a snapshot file after snapCount transactions") // These flags are ignored since they were already parsed. var path string diff --git a/tests/functional/simple_snapshot_test.go b/tests/functional/simple_snapshot_test.go index <HASH>..<HASH> 100644 --- a/tests/functional/simple_snapshot_test.go +++ b/tests/functional/simple_snapshot_test.go @@ -13,7 +13,7 @@ import ( func TestSimpleSnapshot(t *testing.T) { procAttr := new(os.ProcAttr) procAttr.Files = []*os.File{nil, os.Stdout, os.Stderr} - args := []string{"etcd", "-n=node1", "-d=/tmp/node1", "-snapshot=true", "-snapCount=500"} + args := []string{"etcd", "-n=node1", "-d=/tmp/node1", "-snapshot=true", "-snapshotCount=500"} process, err := os.StartProcess(EtcdBinPath, append(args, "-f"), procAttr) if err != nil {
refactor change cmd argument snapCount to snapshotCount
etcd-io_etcd
train
1b45eafaab0c7413d0d14e6cb7d8c6e79ceb799c
diff --git a/src/java/arjdbc/postgresql/PostgreSQLRubyJdbcConnection.java b/src/java/arjdbc/postgresql/PostgreSQLRubyJdbcConnection.java index <HASH>..<HASH> 100644 --- a/src/java/arjdbc/postgresql/PostgreSQLRubyJdbcConnection.java +++ b/src/java/arjdbc/postgresql/PostgreSQLRubyJdbcConnection.java @@ -27,6 +27,7 @@ package arjdbc.postgresql; import java.io.ByteArrayInputStream; import java.io.InputStream; +import java.lang.StringBuilder; import java.sql.Array; import java.sql.Connection; import java.sql.PreparedStatement; @@ -71,10 +72,32 @@ import org.postgresql.util.PGobject; public class PostgreSQLRubyJdbcConnection extends arjdbc.jdbc.RubyJdbcConnection { private static final long serialVersionUID = 7235537759545717760L; private static final int HSTORE_TYPE = 100000 + 1111; + private static final Pattern binaryStringPattern = Pattern.compile("^[01]+$"); private static final Pattern uuidPattern = Pattern.compile("^\\p{XDigit}{8}-(?:\\p{XDigit}{4}-){3}\\p{XDigit}{12}$"); + private static final String[] binaryStrings = { + "0000", + "0001", + "0010", + "0011", + "0100", + "0101", + "0110", + "0111", + "1000", + "1001", + "1010", + "1011", + "1100", + "1101", + "1110", + "1111" + }; + private static final Map<String, Integer> POSTGRES_JDBC_TYPE_FOR = new HashMap<String, Integer>(32, 1); static { + POSTGRES_JDBC_TYPE_FOR.put("bit", Types.OTHER); + POSTGRES_JDBC_TYPE_FOR.put("bit_varying", Types.OTHER); POSTGRES_JDBC_TYPE_FOR.put("citext", Types.OTHER); POSTGRES_JDBC_TYPE_FOR.put("daterange", Types.OTHER); POSTGRES_JDBC_TYPE_FOR.put("hstore", Types.OTHER); @@ -242,6 +265,11 @@ public class PostgreSQLRubyJdbcConnection extends arjdbc.jdbc.RubyJdbcConnection final String columnType = attributeSQLType(context, attribute).asJavaString(); switch ( columnType ) { + case "bit": + case "bit_varying": + setBitStringParameter(statement, index, value); + break; + case "cidr": case "citext": case "hstore": @@ -275,6 +303,28 @@ public class PostgreSQLRubyJdbcConnection extends arjdbc.jdbc.RubyJdbcConnection } } + // value should be a ActiveRecord::ConnectionAdapters::PostgreSQL::OID::Bit::Data + private void setBitStringParameter(final PreparedStatement statement, final int index, final Object value) throws SQLException { + + String valueForDB = value.toString(); + int length = valueForDB.length(); + + /* + This means that if somebody sets their binary string to be "111" it + will always be assumed to be in binary. This matches the AR (5.0) functionality. + If it is meant to be a hex string they should use "0x111". + */ + if (length > 0 && !binaryStringPattern.matcher(valueForDB).matches()) { + StringBuilder builder = new StringBuilder(length * 4); + for (int i = 0; i < length; i++) { + builder.append(binaryStrings[Character.digit(valueForDB.charAt(i), 16)]); + } + valueForDB = builder.toString(); + } + + setPGobjectParameter(statement, index, valueForDB, "bit"); + } + private void setJsonParameter(final ThreadContext context, final PreparedStatement statement, final int index, final IRubyObject attribute, final String columnType) throws SQLException {
Fixed bit string support in postgres when using prepared statements
jruby_activerecord-jdbc-adapter
train
5666842784a9ff4917e11b8fe206999b42a77d2d
diff --git a/lib/puppet/parser/environment_compiler.rb b/lib/puppet/parser/environment_compiler.rb index <HASH>..<HASH> 100644 --- a/lib/puppet/parser/environment_compiler.rb +++ b/lib/puppet/parser/environment_compiler.rb @@ -65,12 +65,16 @@ class Puppet::Parser::EnvironmentCompiler < Puppet::Parser::Compiler # Get downstream vertexes returns a hash where the keys are the resources and values nesting level rooted_in_main = @catalog.downstream_from_vertex(the_main_class_resource).keys + + to_be_removed = if the_site_resource keep_from_site = @catalog.downstream_from_vertex(the_site_resource).keys keep_from_site << the_site_resource + rooted_in_main - keep_from_site + else + rooted_in_main end - to_be_removed = rooted_in_main - keep_from_site @catalog.remove_resource(*to_be_removed) # The compiler keeps a list of added resources, this shadows that list with the now pruned result @pruned_resources = @catalog.resources diff --git a/spec/unit/appmgmt_spec.rb b/spec/unit/appmgmt_spec.rb index <HASH>..<HASH> 100644 --- a/spec/unit/appmgmt_spec.rb +++ b/spec/unit/appmgmt_spec.rb @@ -243,6 +243,14 @@ EOS describe "in the environment catalog" do + it "does not fail if there is no site expression" do + expect { + catalog = compile_to_env_catalog(<<-EOC).to_resource + notify { 'ignore me':} + EOC + }.to_not raise_error() + end + it "includes components and capability resources" do catalog = compile_to_env_catalog(MANIFEST).to_resource apps = catalog.resources.select do |res|
(PUP-<I>) Fix ref to nil in environment_compiler Before this there was a problem if an environment compiler compiled a manifest that did not have a site expression. The final pruning step would then end up with a nil reference instead of an array of elements to keep from the site expression.
puppetlabs_puppet
train
691cd8e165a85a8e0730fc3fbef0846e421d49b1
diff --git a/classes/bors/system/js/touch.php b/classes/bors/system/js/touch.php index <HASH>..<HASH> 100644 --- a/classes/bors/system/js/touch.php +++ b/classes/bors/system/js/touch.php @@ -7,7 +7,7 @@ class bors_system_js_touch extends bors_js $module_htmls = array(); if($modules = bors()->request()->data('modules')) { - if(preg_match('/^\[\{/', $modules)) // JSON + if(preg_match('/^\[/', $modules)) // JSON { foreach(json_decode($modules, true) as $args) { @@ -15,12 +15,14 @@ class bors_system_js_touch extends bors_js $module_htmls[] = array('id' => md5($x->internal_uri_ascii()), 'html' => $x->html()); } } - else + elseif(is_array($modules)) { foreach($modules as $uri) if($x = bors_load_uri($uri)) $module_htmls[] = array('id' => md5($uri), 'html' => $x->html()); } + else + bors_debug::syslog('error-data', "Is not array: ".print_r($modules, true)); } // А то на pre_show от модуля вылезает content-type от pors_page
fix for empty json array.
Balancer_bors-core
train
de84dfbc7563577f5cdbe7c5d7dfceb705d11bcb
diff --git a/example/classic/models/tests.js b/example/classic/models/tests.js index <HASH>..<HASH> 100644 --- a/example/classic/models/tests.js +++ b/example/classic/models/tests.js @@ -5,7 +5,7 @@ var mongoose = require('mongoose'), ObjectId = SchemaTypes.ObjectId; fWidgets = require('../../../').widgets; -module.exports = new Schema({ +var schema = module.exports = new Schema({ string: { type: String }, string_req: { type: String, required: true, label: 'Name' }, ref: { type: SchemaTypes.ObjectId, ref: 'pages' }, @@ -63,11 +63,15 @@ module.exports = new Schema({ }, mixed: SchemaTypes.Mixed }); -module.exports.methods.toString = function () {return this.string_req}; +schema.methods.toString = function () {return this.string_req}; -module.exports.formage = { +schema.formage = { filters: ['ref'], - list: ['embeded.name1', 'ref', 'image'], + list: ['embeded.name1', 'ref', 'image', 'swizzle'], subCollections: [{label: 'Sub Tests', model: 'pages', field:'ref'}], list_populate: ['ref'] }; + +schema.virtual('swizzle').get(function() { + return (this.get('string_req') || '').split('').reverse().join(''); +}); diff --git a/index.js b/index.js index <HASH>..<HASH> 100644 --- a/index.js +++ b/index.js @@ -1 +1,2 @@ +require('lodash-contrib'); module.exports = require('./lib/index'); diff --git a/lib/adapters/mongoose.js b/lib/adapters/mongoose.js index <HASH>..<HASH> 100644 --- a/lib/adapters/mongoose.js +++ b/lib/adapters/mongoose.js @@ -40,7 +40,7 @@ function queryDocuments(listFields, dbModel, filters, sorts, populates, start, c return q .skip(start) .limit(count) - .select(listFields.join(' ')) +// .select(listFields.join(' ')) // might break virtuals .exec(); } diff --git a/lib/controllers.js b/lib/controllers.js index <HASH>..<HASH> 100644 --- a/lib/controllers.js +++ b/lib/controllers.js @@ -368,13 +368,17 @@ module.exports = function (registry) { var paths = registry.adapter.getPaths(modelConfig.model); var table = { header: modelConfig.fieldsInTable.map(function (field_path) { + var capitalized = _.capitalize(field_path).replace(/_/g, ' '); var fieldConfig = paths.find({db_path: field_path}); + if (!fieldConfig) { + return {label: capitalized}; + } + var label = fieldConfig.label || capitalized; var key = String(field_path); if (req.query.order_by == field_path) { key = '-' + key; } var link = makeLink('order_by', key); - var label = fieldConfig.label || field_path[0].toUpperCase() + field_path.slice(1).replace(/_/g, ' '); var obj = { href: link, label: label diff --git a/lib/index.js b/lib/index.js index <HASH>..<HASH> 100644 --- a/lib/index.js +++ b/lib/index.js @@ -12,6 +12,13 @@ try { //noinspection EmptyCatchBlockJS,UnusedCatchParameterJS try { var mongoose = module.parent.require('mongoose'); + var mpromise = require('mpromise'); + var mpromise_index = _.find(require.cache, function (val, key) {return /.*formage.node_modules.mpromise.index.js/.test(key);}); + var mpromise_promise = _.find(require.cache, function (val, key) {return /.*formage.node_modules.mpromise.lib.promise.js/.test(key);}); + _.forEach(require.cache, function (val, key, cache) { + if (/.*mpromise.index.js/.test(key)) cache[key] = mpromise_index; + if (/.*mpromise.lib.promise.js/.test(key)) cache[key] = mpromise_promise; + }); require('formage-mongoose-types/mongoose-types').loadTypes_DI(mongoose); } catch (e) {} diff --git a/package.json b/package.json index <HASH>..<HASH> 100644 --- a/package.json +++ b/package.json @@ -31,6 +31,7 @@ ], "dependencies": { "lodash": "> 2.4.0", + "lodash-contrib": "> 2.4.0", "async": ">= 0.2.6", "cloudinary": "", "nodestrum": "", diff --git a/test/test-mongoose.js b/test/test-mongoose.js index <HASH>..<HASH> 100644 --- a/test/test-mongoose.js +++ b/test/test-mongoose.js @@ -1,4 +1,5 @@ 'use strict'; +require('longjohn'); /*global makeRes,mock_req_proto,mock_res_proto,should */ describe("high level REST requests on mongoose", function () { var ctx = {};
Fix #<I> and Fix #<I> + Monkey patch mongoose to latest mpromise (otherwise we don't get exceptions) Depends on LearnBoost/mongoose#<I>
node4good_formage
train
f2ae255c5c867a101dc074044bc2eaa660e38652
diff --git a/lib/gh/response.rb b/lib/gh/response.rb index <HASH>..<HASH> 100644 --- a/lib/gh/response.rb +++ b/lib/gh/response.rb @@ -34,7 +34,7 @@ module GH # # Returns new Response instance. def dup - super.dup! + super.dup_ivars end # Public: Returns the Response body as a String. @@ -44,7 +44,7 @@ module GH protected - def dup! + def dup_ivars @headers, @data, @body = @headers.dup, @data.dup, @body.dup self end
quick, before @mattmatt sees this :D
travis-ci_gh
train
d4cda04a0aaa4dacb7d93dedc4ef4ca9ffb40733
diff --git a/src/Check/CheckInterface.php b/src/Check/CheckInterface.php index <HASH>..<HASH> 100644 --- a/src/Check/CheckInterface.php +++ b/src/Check/CheckInterface.php @@ -25,4 +25,21 @@ interface CheckInterface * @return string */ public function getName(); + + /** + * Which Exercise Type this + * checks applies to + * @see \PhpSchool\PhpWorkshop\Exercise\ExerciseType + * + * @return ExerciseType + */ + public function appliesTo(); + + /** + * This returns the interface the exercise should implement + * when requiring this check + * + * @return string + */ + public function getExerciseInterface(); }
Add additional methods for the exercise type and interface
php-school_php-workshop
train
f829ff67a12e7834e6f471677b246d4a9f11f48d
diff --git a/nox/src/main/java/com/github/pedrovgs/nox/path/SpiralPath.java b/nox/src/main/java/com/github/pedrovgs/nox/path/SpiralPath.java index <HASH>..<HASH> 100644 --- a/nox/src/main/java/com/github/pedrovgs/nox/path/SpiralPath.java +++ b/nox/src/main/java/com/github/pedrovgs/nox/path/SpiralPath.java @@ -51,7 +51,7 @@ class SpiralPath extends Path { } @Override public int getMaxX() { - return (int) (maxX + getPathConfig().getFirstItemSize()); + return maxX; } @Override public int getMinY() { @@ -59,6 +59,6 @@ class SpiralPath extends Path { } @Override public int getMaxY() { - return (int) (maxY + getPathConfig().getFirstItemSize()); + return maxY; } }
Implemented scroll feature for SpiralPath
pedrovgs_Nox
train
e18b0909022affe9edc4e574a4efc86eedffca31
diff --git a/lib/NativeReactor.php b/lib/NativeReactor.php index <HASH>..<HASH> 100644 --- a/lib/NativeReactor.php +++ b/lib/NativeReactor.php @@ -24,7 +24,7 @@ class NativeReactor implements Reactor { if (empty($e)) { return; } elseif ($this->onError) { - call_user_func($this->onError, $e); + \call_user_func($this->onError, $e); } else { throw $e; } @@ -122,7 +122,7 @@ class NativeReactor implements Reactor { $this->immediates[$watcherId], $this->watchers[$watcherId] ); - $result = call_user_func($watcher->callback, $this, $watcherId, $watcher->callbackData); + $result = \call_user_func($watcher->callback, $this, $watcherId, $watcher->callbackData); if ($result instanceof \Generator) { resolve($result, $this)->when($this->onCoroutineResolution); } @@ -140,7 +140,7 @@ class NativeReactor implements Reactor { $timeToNextAlarm = 1; } else { if ($this->isTimerSortNeeded) { - asort($this->timerOrder); + \asort($this->timerOrder); $this->isTimerSortNeeded = false; } // This reset() is important ... don't remove it! @@ -184,7 +184,7 @@ class NativeReactor implements Reactor { foreach ($r as $readableStream) { $streamId = (int) $readableStream; foreach ($this->readWatchers[$streamId] as $watcherId => $watcher) { - $result = call_user_func($watcher->callback, $this, $watcherId, $readableStream, $watcher->callbackData); + $result = \call_user_func($watcher->callback, $this, $watcherId, $readableStream, $watcher->callbackData); if ($result instanceof \Generator) { resolve($result, $this)->when($this->onCoroutineResolution); } @@ -193,7 +193,7 @@ class NativeReactor implements Reactor { foreach ($w as $writableStream) { $streamId = (int) $writableStream; foreach ($this->writeWatchers[$streamId] as $watcherId => $watcher) { - $result = call_user_func($watcher->callback, $this, $watcherId, $writableStream, $watcher->callbackData); + $result = \call_user_func($watcher->callback, $this, $watcherId, $writableStream, $watcher->callbackData); if ($result instanceof \Generator) { resolve($result, $this)->when($this->onCoroutineResolution); } @@ -220,7 +220,7 @@ class NativeReactor implements Reactor { $watcher = $this->watchers[$watcherId]; - $result = call_user_func($watcher->callback, $this, $watcherId, $watcher->callbackData); + $result = \call_user_func($watcher->callback, $this, $watcherId, $watcher->callbackData); if ($result instanceof \Generator) { resolve($result, $this)->when($this->onCoroutineResolution); } @@ -300,7 +300,7 @@ class NativeReactor implements Reactor { assert(($msInterval >= 0), "\$msInterval at Argument 2 expects integer >= 0"); $msDelay = isset($options["ms_delay"]) ? $options["ms_delay"] : (int) $msInterval; assert(($msDelay >= 0), "ms_delay option expects integer >= 0"); - + /* In the php7 branch we use an anonymous class with Struct for this. * Using a stdclass isn't terribly readable and it's prone to error but * it's the easiest way to minimize the distance between 5.x and 7 code
use fully qualified namespace for global functions
amphp_amp
train
0d8dbd3c15970952d4ded1c1d994f1b033febecc
diff --git a/deployment-scanner/src/test/java/org/jboss/as/server/deployment/scanner/AutoDeployTestSupport.java b/deployment-scanner/src/test/java/org/jboss/as/server/deployment/scanner/AutoDeployTestSupport.java index <HASH>..<HASH> 100644 --- a/deployment-scanner/src/test/java/org/jboss/as/server/deployment/scanner/AutoDeployTestSupport.java +++ b/deployment-scanner/src/test/java/org/jboss/as/server/deployment/scanner/AutoDeployTestSupport.java @@ -76,19 +76,10 @@ public class AutoDeployTestSupport { ClassLoader tccl = Thread.currentThread().getContextClassLoader(); URL webxml = tccl.getResource("basic.war/web.xml"); WebArchive war = ShrinkWrap.create(WebArchive.class, "basic.war"); - File index = null; - try { - URL resource = tccl.getResource("basic.war/index.html"); - if (resource == null) - throw new IllegalStateException("basic.war/index.html not found"); - index = new File(resource.toURI().getRawPath()); - } catch (URISyntaxException e) { - IllegalArgumentException ex = new IllegalArgumentException(e.getMessage()); - ex.setStackTrace(e.getStackTrace()); - ex.initCause(e.getCause()); - throw ex; - } - war.addResource(index); + URL resource = tccl.getResource("basic.war/index.html"); + if (resource == null) + throw new IllegalStateException("basic.war/index.html not found"); + war.addResource(resource, "index.html"); war.setWebXML(webxml); basicWar = new File(tmpDir, "basic.war"); diff --git a/testsuite/integration/src/test/java/org/jboss/as/testsuite/integration/websecurity/WebSecurityFORMTestCase.java b/testsuite/integration/src/test/java/org/jboss/as/testsuite/integration/websecurity/WebSecurityFORMTestCase.java index <HASH>..<HASH> 100644 --- a/testsuite/integration/src/test/java/org/jboss/as/testsuite/integration/websecurity/WebSecurityFORMTestCase.java +++ b/testsuite/integration/src/test/java/org/jboss/as/testsuite/integration/websecurity/WebSecurityFORMTestCase.java @@ -65,8 +65,8 @@ public class WebSecurityFORMTestCase extends WebSecurityPasswordBasedBase { File loginJSP = new File(tccl.getResource("web-secure.war/login.jsp").getPath()); File errorJSP = new File(tccl.getResource("web-secure.war/error.jsp").getPath()); - war.addResource(loginJSP); - war.addResource(errorJSP); + war.addResource(tccl.getResource("web-secure.war/login.jsp"), "login.jsp"); + war.addResource(tccl.getResource("web-secure.war/error.jsp"), "error.jsp"); WebSecurityPasswordBasedBase.printWar(war); return war; diff --git a/testsuite/integration/src/test/java/org/jboss/as/testsuite/integration/websecurity/WebSecurityPasswordBasedBase.java b/testsuite/integration/src/test/java/org/jboss/as/testsuite/integration/websecurity/WebSecurityPasswordBasedBase.java index <HASH>..<HASH> 100644 --- a/testsuite/integration/src/test/java/org/jboss/as/testsuite/integration/websecurity/WebSecurityPasswordBasedBase.java +++ b/testsuite/integration/src/test/java/org/jboss/as/testsuite/integration/websecurity/WebSecurityPasswordBasedBase.java @@ -51,11 +51,9 @@ public abstract class WebSecurityPasswordBasedBase { war.addClass(servletClass); ClassLoader tccl = Thread.currentThread().getContextClassLoader(); - File userProp = new File(tccl.getResource("security/users.properties").getPath()); - File roleProp = new File(tccl.getResource("security/roles.properties").getPath()); - war.addResource(userProp, "/WEB-INF/classes/users.properties"); - war.addResource(roleProp, "/WEB-INF/classes/roles.properties"); + war.addResource(tccl.getResource("security/users.properties"), "/WEB-INF/classes/users.properties"); + war.addResource(tccl.getResource("security/roles.properties"), "/WEB-INF/classes/roles.properties"); if (webxml != null) { war.setWebXML(webxml);
Use URLs instead of files with tests that lookup resources on TCCL
wildfly_wildfly
train
f6c80923bf250ef523282c47e061c442a6bf5860
diff --git a/auth/ldap/auth.php b/auth/ldap/auth.php index <HASH>..<HASH> 100644 --- a/auth/ldap/auth.php +++ b/auth/ldap/auth.php @@ -1485,6 +1485,11 @@ class auth_plugin_ldap extends auth_plugin_base { ldap_set_option($connresult, LDAP_OPT_PROTOCOL_VERSION, $this->config->version); } + // Fix MDL-10921 + if ($this->config->user_type == 'ad') { + ldap_set_option($connresult, LDAP_OPT_REFERRALS, 0); + } + if (!empty($binddn)) { //bind with search-user //$debuginfo .= 'Using bind user'.$binddn.'and password:'.$bindpwd;
MDL-<I> LDAP Auth to Active Directory requires LDAP_OPT_REFERRALS option set
moodle_moodle
train
c68ac0d91f55b316655668be748594b004079fdd
diff --git a/source/core/oxconfig.php b/source/core/oxconfig.php index <HASH>..<HASH> 100644 --- a/source/core/oxconfig.php +++ b/source/core/oxconfig.php @@ -793,23 +793,19 @@ class oxConfig extends oxSuperCfg public function getShopId() { if (is_null($this->_iShopId)) { - $this->setShopId($this->calculateActiveShopId()); + $shopId = $this->calculateActiveShopId(); + $this->setShopId($shopId); + + if (!$this->_isValidShopId($shopId)) { + $shopId = $this->getBaseShopId(); + } + $this->setShopId($shopId); } return $this->_iShopId; } /** - * Returns active shop id. - * - * @return string - */ - protected function calculateActiveShopId() - { - return $this->getBaseShopId(); - } - - /** * Set is shop url * * @param bool $blIsSsl - state bool value @@ -2270,4 +2266,26 @@ class oxConfig extends oxSuperCfg { return $this->getShopConfVar($sParameterName, $this->getBaseShopId()); } + + /** + * Returns whether given shop id is valid. + * + * @param string $shopId + * + * @return bool + */ + protected function _isValidShopId($shopId) + { + return !empty($shopId); + } + + /** + * Returns active shop id. + * + * @return string + */ + protected function calculateActiveShopId() + { + return $this->getBaseShopId(); + } }
Refactor shop id calculation and assignment Assign shop id before validation
OXID-eSales_oxideshop_ce
train
938020cfbe39a42102ceecffa293ceb28b480335
diff --git a/src/WebMidi.js b/src/WebMidi.js index <HASH>..<HASH> 100644 --- a/src/WebMidi.js +++ b/src/WebMidi.js @@ -12,9 +12,17 @@ import {Enumerations} from "./Enumerations.js"; // convoluted way to prevent Webpack from automatically bundling it in browser bundles where it // isn't needed. if (Utilities.isNode) { - let jzz; - eval('jzz = require("jzz")'); - global["navigator"] = jzz; + + // Some environments may have both Node.js and browser runtimes (Electron, NW.js, React Native, + // etc.) so we also check for the presence of the window.navigator property. + try { + window.navigator; + } catch (err) { + let jzz; + eval('jzz = require("jzz")'); + global["navigator"] = jzz; + } + } /*END-CJS*/ @@ -220,10 +228,18 @@ class WebMidi extends EventEmitter { // package.json file), then we must import the `jzz` module. I import it in this convoluted way // to prevent Webpack from automatically bundling it in browser bundles where it isn't needed. if (Utilities.isNode) { - global["navigator"] = await Object.getPrototypeOf(async function() {}).constructor(` + + // Some environments may have both Node.js and browser runtimes (Electron, NW.js, React + // Native, etc.) so we also check for the presence of the window.navigator property. + try { + window.navigator; + } catch (err) { + global["navigator"] = await Object.getPrototypeOf(async function() {}).constructor(` jzz = await import("jzz"); return jzz.default; `)(); + } + } /*END-ESM*/ @@ -379,7 +395,7 @@ class WebMidi extends EventEmitter { return this._destroyInputsAndOutputs().then(() => { - if (typeof navigator.close === "function") navigator.close(); + if (navigator && typeof navigator.close === "function") navigator.close(); // jzz if (this.interface) this.interface.onstatechange = undefined; this.interface = null; // also resets enabled, sysexEnabled
Improve support for environments with both Node.js and browser runtimes
djipco_webmidi
train
e3f8a83cd9e05e5177cf44ccf5f5fda09b128bf9
diff --git a/lib/active_rest_client/proxy_base.rb b/lib/active_rest_client/proxy_base.rb index <HASH>..<HASH> 100644 --- a/lib/active_rest_client/proxy_base.rb +++ b/lib/active_rest_client/proxy_base.rb @@ -39,6 +39,7 @@ module ActiveRestClient end def translate(result) + result = OpenStruct.new(status:result.status, headers:result.headers, body:result.body) obj = Oj.load(result.body) result.body = yield obj result
Attempt to get translate working with Patron
whichdigital_active-rest-client
train
81e7aa659a86b91574444b50749ba3107093b4ed
diff --git a/graphitesend/graphitesend.py b/graphitesend/graphitesend.py index <HASH>..<HASH> 100644 --- a/graphitesend/graphitesend.py +++ b/graphitesend/graphitesend.py @@ -292,12 +292,21 @@ class GraphiteClient(object): self.socket.sendall(message.encode("ascii")) def _send_and_reconnect(self, message): + """Send _message_ to Graphite Server and attempt reconnect on failure. + If _autoreconnect_ was specified, attempt to reconnect if first send + fails. + + :raises AttributeError: When the socket has not been set. + :raises socket.error: When the socket connection is no longer valid. + """ try: self.socket.sendall(message.encode("ascii")) - except socket.error: + except (AttributeError, socket.error): if not self.autoreconnect(): raise + else: + self.socket.sendall(message.encode("ascii")) def _presend(self, message): """
fix: Try send message again when socket empty Seems like the expected behaviour of _send_and_reconnect() would be to reconnect to Graphite if the first sendall() fails. If we get to this spot without initializing the socket, we should attempt to connect then try again.
daniellawrence_graphitesend
train
337c7fbc5e2b610fa6d98dc1c34a050ecc028262
diff --git a/src/JaztecBase/Mapper/AbstractDoctrineMapper.php b/src/JaztecBase/Mapper/AbstractDoctrineMapper.php index <HASH>..<HASH> 100644 --- a/src/JaztecBase/Mapper/AbstractDoctrineMapper.php +++ b/src/JaztecBase/Mapper/AbstractDoctrineMapper.php @@ -69,16 +69,18 @@ abstract class AbstractDoctrineMapper extends AbstractMapper // Testing on input parameters if (!$repo instanceof \Doctrine\Common\Persistence\ObjectRepository && !is_array($repo)) { - throw new Exception(__CLASS__ . ' expects an array or a - \Doctrine\Common\Persistence\ObjectRepository. ' . - class_name($repo) . ' given.'); + throw new Exception( + __CLASS__ . ' expects an array or a + \Doctrine\Common\Persistence\ObjectRepository. ' . + class_name($repo) . ' given.' + ); } switch ($type) { case AbstractDoctrineMapper::TYPE_SERIALIZEDARRAY: $result = array(); foreach ($repo as $obj) { /* @var $obj \JaztecBase\Entity\EntityInterface */ - if($obj instanceof \JaztecBase\Entity\EntityInterface) { + if ($obj instanceof \JaztecBase\Entity\EntityInterface) { $result[] = $obj->toArray(); } elseif (is_array($obj)) { $result[] = $obj; @@ -86,7 +88,7 @@ abstract class AbstractDoctrineMapper extends AbstractMapper } break; case AbstractDoctrineMapper::TYPE_ENTITYARRAY: - if(!is_array($repo)) { + if (!is_array($repo)) { $repo = array($repo); } $result = $repo;
Some more cleanup, code-style is tedious
jaztec_jaztec-base
train
82e77a6cff029b4b0fdf3c97785aedde61de2f1a
diff --git a/presto-main/src/main/java/com/facebook/presto/operator/SortedPositionLinks.java b/presto-main/src/main/java/com/facebook/presto/operator/SortedPositionLinks.java index <HASH>..<HASH> 100644 --- a/presto-main/src/main/java/com/facebook/presto/operator/SortedPositionLinks.java +++ b/presto-main/src/main/java/com/facebook/presto/operator/SortedPositionLinks.java @@ -120,7 +120,7 @@ public final class SortedPositionLinks @Override public Factory build() { - ArrayPositionLinks.FactoryBuilder builder = ArrayPositionLinks.builder(size); + ArrayPositionLinks.FactoryBuilder arrayPositionLinksFactoryBuilder = ArrayPositionLinks.builder(size); int[][] sortedPositionLinks = new int[size][]; for (Int2ObjectMap.Entry<IntArrayList> entry : positionLinks.int2ObjectEntrySet()) { @@ -137,19 +137,19 @@ public final class SortedPositionLinks // tail to head, so we must add them in descending order to have // smallest element as a head for (int i = positions.size() - 2; i >= 0; i--) { - builder.link(positions.get(i), positions.get(i + 1)); + arrayPositionLinksFactoryBuilder.link(positions.get(i), positions.get(i + 1)); } // add link from starting position to position links chain if (!positions.isEmpty()) { - builder.link(key, positions.get(0)); + arrayPositionLinksFactoryBuilder.link(key, positions.get(0)); } } return lessThanFunction -> { checkState(lessThanFunction.isPresent(), "Using SortedPositionLinks without lessThanFunction"); return new SortedPositionLinks( - builder.build().create(lessThanFunction), + arrayPositionLinksFactoryBuilder.build().create(lessThanFunction), sortedPositionLinks, lessThanFunction.get()); };
Rename variable There are couple builder and factories used in this method. Renaming this variable makes this code more clear.
prestodb_presto
train
933d2c5eb77e4e2e15a771a88039555182818965
diff --git a/src/managers/GuildManager.js b/src/managers/GuildManager.js index <HASH>..<HASH> 100644 --- a/src/managers/GuildManager.js +++ b/src/managers/GuildManager.js @@ -253,7 +253,7 @@ class GuildManager extends CachedManager { * @typedef {Object} FetchGuildsOptions * @property {Snowflake} [before] Get guilds before this guild id * @property {Snowflake} [after] Get guilds after this guild id - * @property {number} [limit=100] Maximum number of guilds to request (1-100) + * @property {number} [limit=200] Maximum number of guilds to request (1-200) */ /**
docs(GuildManager): increase fetch limit to <I> (#<I>)
discordjs_discord.js
train
07feec67e459d03288431cc4e7291eac272fdbcd
diff --git a/parsl/app/app.py b/parsl/app/app.py index <HASH>..<HASH> 100644 --- a/parsl/app/app.py +++ b/parsl/app/app.py @@ -50,6 +50,7 @@ class AppBase (object): self.executor = executor self.exec_type = exec_type self.status = 'created' + self.sites = sites sig = signature(func) self.kwargs = {} @@ -98,6 +99,6 @@ def App(apptype, executor, walltime=60, sites='all'): from parsl import APP_FACTORY_FACTORY def Exec(f): - return APP_FACTORY_FACTORY.make(apptype, executor, f, walltime=walltime) + return APP_FACTORY_FACTORY.make(apptype, executor, f, sites=sites, walltime=walltime) return Exec diff --git a/parsl/app/app_factory.py b/parsl/app/app_factory.py index <HASH>..<HASH> 100644 --- a/parsl/app/app_factory.py +++ b/parsl/app/app_factory.py @@ -15,7 +15,7 @@ class AppFactory(object): ''' AppFactory streamlines creation of apps ''' - def __init__(self, app_class, executor, func, walltime=60, sites='all'): + def __init__(self, app_class, executor, func, sites='all', walltime=60): ''' Construct an AppFactory for a particular app_class Args: @@ -57,6 +57,7 @@ class AppFactory(object): # Create and call the new App object app_obj = self.app_class(self.func, self.executor, + sites=self.sites, walltime=self.walltime) return app_obj(*args, **kwargs)
Updating to support sites option in app decorators
Parsl_parsl
train
cf32a3571ee45d94ebfec6eb4407482b714bb147
diff --git a/broker.go b/broker.go index <HASH>..<HASH> 100644 --- a/broker.go +++ b/broker.go @@ -53,8 +53,11 @@ func (b *broker) connect() (err error) { return err } + b.requests = make(chan responsePromise) + b.responses = make(chan responsePromise) + go b.sendRequestLoop() - go b.rcvresponsePromiseLoop() + go b.rcvResponseLoop() return nil } @@ -112,7 +115,7 @@ func (b *broker) sendRequestLoop() { } } -func (b *broker) rcvresponsePromiseLoop() { +func (b *broker) rcvResponseLoop() { header := make([]byte, 8) for response := range b.responses { _, err := io.ReadFull(b.conn, header)
Actually make channels for the broker to communicate over
Shopify_sarama
train
04ec5c0f37ad1ae37139099c7a23397532226a3d
diff --git a/src/Models/Page.php b/src/Models/Page.php index <HASH>..<HASH> 100644 --- a/src/Models/Page.php +++ b/src/Models/Page.php @@ -166,13 +166,11 @@ class Page extends Model implements PageContract, Sortable parent::boot(); // Auto generate slugs early before validation - static::registerModelEvent('validating', function (self $attribute) { - if (! $attribute->slug) { - if ($attribute->exists && $attribute->getSlugOptions()->generateSlugsOnUpdate) { - $attribute->generateSlugOnUpdate(); - } elseif (! $attribute->exists && $attribute->getSlugOptions()->generateSlugsOnCreate) { - $attribute->generateSlugOnCreate(); - } + static::validating(function (self $attribute) { + if ($attribute->exists && $attribute->getSlugOptions()->generateSlugsOnUpdate) { + $attribute->generateSlugOnUpdate(); + } elseif (! $attribute->exists && $attribute->getSlugOptions()->generateSlugsOnCreate) { + $attribute->generateSlugOnCreate(); } }); }
Assure unique slugs generated at all times
rinvex_laravel-pages
train
9e6315e6554b19f61a1e71d9622cc2ae99c3d358
diff --git a/ui/app/components/scale-events-chart.js b/ui/app/components/scale-events-chart.js index <HASH>..<HASH> 100644 --- a/ui/app/components/scale-events-chart.js +++ b/ui/app/components/scale-events-chart.js @@ -1,19 +1,17 @@ -import Component from '@ember/component'; +import Component from '@glimmer/component'; +import { tracked } from '@glimmer/tracking'; +import { get } from '@ember/object'; import { copy } from 'ember-copy'; -import { computed, get } from '@ember/object'; -import { tagName } from '@ember-decorators/component'; -import classic from 'ember-classic-decorator'; -@classic -@tagName('') export default class ScaleEventsChart extends Component { - events = []; + /** Args + events = [] + */ - activeEvent = null; + @tracked activeEvent = null; - @computed('annotations', 'events.[]') get data() { - const data = this.events.filterBy('hasCount').sortBy('time'); + const data = this.args.events.filterBy('hasCount').sortBy('time'); // Extend the domain of the chart to the current time data.push({ @@ -33,9 +31,8 @@ export default class ScaleEventsChart extends Component { return data; } - @computed('events.[]') get annotations() { - return this.events.rejectBy('hasCount').map(ev => ({ + return this.args.events.rejectBy('hasCount').map(ev => ({ type: ev.error ? 'error' : 'info', time: ev.time, event: copy(ev), @@ -46,11 +43,11 @@ export default class ScaleEventsChart extends Component { if (this.activeEvent && get(this.activeEvent, 'event.uid') === get(ev, 'event.uid')) { this.closeEventDetails(); } else { - this.set('activeEvent', ev); + this.activeEvent = ev; } } closeEventDetails() { - this.set('activeEvent', null); + this.activeEvent = null; } } diff --git a/ui/tests/unit/components/scale-events-chart-test.js b/ui/tests/unit/components/scale-events-chart-test.js index <HASH>..<HASH> 100644 --- a/ui/tests/unit/components/scale-events-chart-test.js +++ b/ui/tests/unit/components/scale-events-chart-test.js @@ -1,9 +1,11 @@ import { module, test } from 'qunit'; import { setupTest } from 'ember-qunit'; import sinon from 'sinon'; +import setupGlimmerComponentFactory from 'nomad-ui/tests/helpers/glimmer-factory'; module('Unit | Component | scale-events-chart', function(hooks) { setupTest(hooks); + setupGlimmerComponentFactory(hooks, 'scale-events-chart'); hooks.beforeEach(function() { this.refTime = new Date(); @@ -16,13 +18,12 @@ module('Unit | Component | scale-events-chart', function(hooks) { }); test('the current date is appended as a datum for the line chart to render', function(assert) { - const chart = this.owner.factoryFor('component:scale-events-chart').create(); const events = [ { time: new Date('2020-08-02T04:06:00'), count: 2, hasCount: true }, { time: new Date('2020-08-01T04:06:00'), count: 2, hasCount: true }, ]; - chart.set('events', events); + const chart = this.createComponent({ events }); assert.equal(chart.data.length, events.length + 1); assert.deepEqual(chart.data.slice(0, events.length), events.sortBy('time')); @@ -33,7 +34,6 @@ module('Unit | Component | scale-events-chart', function(hooks) { }); test('if the earliest annotation is outside the domain of the events, the earliest annotation time is added as a datum for the line chart to render', function(assert) { - const chart = this.owner.factoryFor('component:scale-events-chart').create(); const annotationOutside = [ { time: new Date('2020-08-01T04:06:00'), hasCount: false, error: true }, { time: new Date('2020-08-02T04:06:00'), count: 2, hasCount: true }, @@ -45,7 +45,7 @@ module('Unit | Component | scale-events-chart', function(hooks) { { time: new Date('2020-08-03T04:06:00'), count: 2, hasCount: true }, ]; - chart.set('events', annotationOutside); + const chart = this.createComponent({ events: annotationOutside }); assert.equal(chart.data.length, annotationOutside.length + 1); assert.deepEqual( @@ -57,7 +57,7 @@ module('Unit | Component | scale-events-chart', function(hooks) { assert.equal(appendedDatum.count, annotationOutside[1].count); assert.equal(+appendedDatum.time, +annotationOutside[0].time); - chart.set('events', annotationInside); + chart.args.events = annotationInside; assert.equal(chart.data.length, annotationOutside.length); assert.deepEqual(
Convert ScaleEventsChart into a glimmer component
hashicorp_nomad
train
c50200dad8d03a37dfd14312adfa33fdcf0b0ef4
diff --git a/src/components/tabs/__tests__/CdrTabs.spec.js b/src/components/tabs/__tests__/CdrTabs.spec.js index <HASH>..<HASH> 100644 --- a/src/components/tabs/__tests__/CdrTabs.spec.js +++ b/src/components/tabs/__tests__/CdrTabs.spec.js @@ -325,7 +325,42 @@ describe('CdrTabs', () => { }); }); + it('accesibility', (done) => { + const spyUpdateUnderline = jest.fn(); + const wrapper = mount(CdrTabs, { + stubs: { + 'cdr-tab-panel': CdrTabPanel, + }, + slots: { + default: ['<cdr-tab-panel name="tab1"/>', '<cdr-tab-panel name="tab2"/>'] + }, + methods: { + updateUnderline: spyUpdateUnderline, + }, + }); + Vue.nextTick(() => { + const tab1 = wrapper.vm.getTabEl(wrapper.vm.tabs[0]); + const tab2 = wrapper.vm.getTabEl(wrapper.vm.tabs[1]); + + // aria-selected + expect(tab1.data.attrs['aria-selected']).toBe(true); + expect(tab2.data.attrs['aria-selected']).toBe(false); + + // tabIndex + expect(tab1.data.attrs.tabIndex).toBe(0); + expect(tab2.data.attrs.tabIndex).toBe(-1); + + // tab role + expect(tab1.data.attrs.role).toBe('tab'); + expect(tab2.data.attrs.role).toBe('tab'); + + // tablist role + expect(wrapper.vm.$refs.cdrTabsHeader.hasAttribute('role', 'tablist')).toBe(true); + + done(); + }); + }); // it('click tab changes active tab lower index variation', (done) => { // const wrapper = mount(CdrTabs, {
test(tabs): add accessibility tests
rei_rei-cedar
train