commit
stringlengths
40
40
old_file
stringlengths
6
152
new_file
stringlengths
6
152
old_contents
stringlengths
1.5k
3.26k
new_contents
stringlengths
22
2.94k
subject
stringlengths
18
317
message
stringlengths
20
1.49k
lang
stringclasses
10 values
license
stringclasses
13 values
repos
stringlengths
7
33.9k
config
stringclasses
10 values
content
stringlengths
1.79k
5.86k
a67ccbd9031dde4168428521b1cdaa752300739a
app/models/EloquentBuilder.php
app/models/EloquentBuilder.php
<?php class EloquentBuilder extends \Illuminate\Database\Eloquent\Builder { /** * Eager load pivot relations. * * @param array $models * @return void */ protected function loadPivotRelations($models) { $query = head($models)->pivot->newQuery()->with('unit'); $pivots = array_pluck($models, 'pivot'); $pivots = head($pivots)->newCollection($pivots); $pivots->load($this->getPivotRelations()); } /** * Get the pivot relations to be eager loaded. * * @return array */ protected function getPivotRelations() { $relations = array_filter(array_keys($this->eagerLoad), function ($relation) { return $relation != 'pivot'; }); return array_map(function ($relation) { return substr($relation, strlen('pivot.')); }, $relations); } /** * Override. Eager load relations of pivot models. * Eagerly load the relationship on a set of models. * * @param array $models * @param string $name * @param \Closure $constraints * @return array */ protected function loadRelation(array $models, $name, Closure $constraints) { // In this part, if the relation name is 'pivot', // therefore there are relations in a pivot to be eager loaded. if ($name === 'pivot') { $this->loadPivotRelations($models); return $models; } return parent::loadRelation($models, $name, $constraints); } }
<?php class EloquentBuilder extends \Illuminate\Database\Eloquent\Builder { /** * Eager load pivot relations. * * @param array $models * @return void */ protected function loadPivotRelations($models) { $query = head($models)->pivot->newQuery()->with('unit'); $pivots = array_pluck($models, 'pivot'); $pivots = head($pivots)->newCollection($pivots); $pivots->load($this->getPivotRelations()); } /** * Get the pivot relations to be eager loaded. * * @return array */ protected function getPivotRelations() { $relations = array_filter(array_keys($this->eagerLoad), function ($relation) { return $relation != 'pivot' && str_contains($relation, 'pivot'); }); return array_map(function ($relation) { return substr($relation, strlen('pivot.')); }, $relations); } /** * Override. Eager load relations of pivot models. * Eagerly load the relationship on a set of models. * * @param array $models * @param string $name * @param \Closure $constraints * @return array */ protected function loadRelation(array $models, $name, Closure $constraints) { // In this part, if the relation name is 'pivot', // therefore there are relations in a pivot to be eager loaded. if ($name === 'pivot') { $this->loadPivotRelations($models); return $models; } return parent::loadRelation($models, $name, $constraints); } }
Fix condition, make sure not to include non-pivot relations
Fix condition, make sure not to include non-pivot relations
PHP
mit
ajcastro/iprocure,ajcastro/iprocure
php
## Code Before: <?php class EloquentBuilder extends \Illuminate\Database\Eloquent\Builder { /** * Eager load pivot relations. * * @param array $models * @return void */ protected function loadPivotRelations($models) { $query = head($models)->pivot->newQuery()->with('unit'); $pivots = array_pluck($models, 'pivot'); $pivots = head($pivots)->newCollection($pivots); $pivots->load($this->getPivotRelations()); } /** * Get the pivot relations to be eager loaded. * * @return array */ protected function getPivotRelations() { $relations = array_filter(array_keys($this->eagerLoad), function ($relation) { return $relation != 'pivot'; }); return array_map(function ($relation) { return substr($relation, strlen('pivot.')); }, $relations); } /** * Override. Eager load relations of pivot models. * Eagerly load the relationship on a set of models. * * @param array $models * @param string $name * @param \Closure $constraints * @return array */ protected function loadRelation(array $models, $name, Closure $constraints) { // In this part, if the relation name is 'pivot', // therefore there are relations in a pivot to be eager loaded. if ($name === 'pivot') { $this->loadPivotRelations($models); return $models; } return parent::loadRelation($models, $name, $constraints); } } ## Instruction: Fix condition, make sure not to include non-pivot relations ## Code After: <?php class EloquentBuilder extends \Illuminate\Database\Eloquent\Builder { /** * Eager load pivot relations. * * @param array $models * @return void */ protected function loadPivotRelations($models) { $query = head($models)->pivot->newQuery()->with('unit'); $pivots = array_pluck($models, 'pivot'); $pivots = head($pivots)->newCollection($pivots); $pivots->load($this->getPivotRelations()); } /** * Get the pivot relations to be eager loaded. * * @return array */ protected function getPivotRelations() { $relations = array_filter(array_keys($this->eagerLoad), function ($relation) { return $relation != 'pivot' && str_contains($relation, 'pivot'); }); return array_map(function ($relation) { return substr($relation, strlen('pivot.')); }, $relations); } /** * Override. Eager load relations of pivot models. * Eagerly load the relationship on a set of models. * * @param array $models * @param string $name * @param \Closure $constraints * @return array */ protected function loadRelation(array $models, $name, Closure $constraints) { // In this part, if the relation name is 'pivot', // therefore there are relations in a pivot to be eager loaded. if ($name === 'pivot') { $this->loadPivotRelations($models); return $models; } return parent::loadRelation($models, $name, $constraints); } }
2f42b4af34396bef942330a0ca7545e1c30627c1
src/Repositories/RepositoryFactory.php
src/Repositories/RepositoryFactory.php
<?php namespace GearHub\LaravelEnhancementSuite\Repositories; use GearHub\LaravelEnhancementSuite\Contracts\Repositories\RepositoryFactory as RepositoryFactoryContract; class RepositoryFactory implements RepositoryFactoryContract { /** * Mapping keys to repositories. Takes precidence over the dynamic resolution. * * @var array */ protected $overrides = []; /** * Create new instance of RepositoryFactory. * * @param array $overrides * * @return void */ public function __construct(array $overrides = []) { $this->overrides = $overrides; } /** * Get repository for the corresponding model. * If $key is null return instance of the factory. * * @param string|null $key * * @return mixed */ public function get($key = null) { if (!empty($key)) { $class = null; if (array_has($this->overrides, $key)) { $class = array_get($this->overrides, $key); } else { $class = $this->build($key); } return resolve($class); } return $this; } /** * Build the path of the Repository class. * * @param string $key * * @return string */ protected function build($key) { return app()->getNamespace() . $this->laravel['config']['les.repository_namespace'] . '\\' . studly_case(str_singular($key)) . 'Repository'; } }
<?php namespace GearHub\LaravelEnhancementSuite\Repositories; use GearHub\LaravelEnhancementSuite\Contracts\Repositories\RepositoryFactory as RepositoryFactoryContract; class RepositoryFactory implements RepositoryFactoryContract { /** * Mapping keys to repositories. Takes precidence over the dynamic resolution. * * @var array */ protected $overrides = []; /** * Create new instance of RepositoryFactory. * * @param array $overrides * * @return void */ public function __construct(array $overrides = []) { $this->overrides = $overrides; } /** * Get repository for the corresponding model. * If $key is null return instance of the factory. * * @param string|null $key * * @return mixed */ public function get($key = null) { if (!empty($key)) { $class = null; if (array_has($this->overrides, $key)) { $class = array_get($this->overrides, $key); } else { $class = $this->build($key); } return resolve($class); } return $this; } /** * Build the path of the Repository class. * * @param string $key * * @return string */ protected function build($key) { return app()->getNamespace() . config('les.repository_namespace') . '\\' . studly_case(str_singular($key)) . 'Repository'; } }
Call to config helper function instead of an instance of the container
Call to config helper function instead of an instance of the container
PHP
mit
gearhub/laravel-enhancement-suite
php
## Code Before: <?php namespace GearHub\LaravelEnhancementSuite\Repositories; use GearHub\LaravelEnhancementSuite\Contracts\Repositories\RepositoryFactory as RepositoryFactoryContract; class RepositoryFactory implements RepositoryFactoryContract { /** * Mapping keys to repositories. Takes precidence over the dynamic resolution. * * @var array */ protected $overrides = []; /** * Create new instance of RepositoryFactory. * * @param array $overrides * * @return void */ public function __construct(array $overrides = []) { $this->overrides = $overrides; } /** * Get repository for the corresponding model. * If $key is null return instance of the factory. * * @param string|null $key * * @return mixed */ public function get($key = null) { if (!empty($key)) { $class = null; if (array_has($this->overrides, $key)) { $class = array_get($this->overrides, $key); } else { $class = $this->build($key); } return resolve($class); } return $this; } /** * Build the path of the Repository class. * * @param string $key * * @return string */ protected function build($key) { return app()->getNamespace() . $this->laravel['config']['les.repository_namespace'] . '\\' . studly_case(str_singular($key)) . 'Repository'; } } ## Instruction: Call to config helper function instead of an instance of the container ## Code After: <?php namespace GearHub\LaravelEnhancementSuite\Repositories; use GearHub\LaravelEnhancementSuite\Contracts\Repositories\RepositoryFactory as RepositoryFactoryContract; class RepositoryFactory implements RepositoryFactoryContract { /** * Mapping keys to repositories. Takes precidence over the dynamic resolution. * * @var array */ protected $overrides = []; /** * Create new instance of RepositoryFactory. * * @param array $overrides * * @return void */ public function __construct(array $overrides = []) { $this->overrides = $overrides; } /** * Get repository for the corresponding model. * If $key is null return instance of the factory. * * @param string|null $key * * @return mixed */ public function get($key = null) { if (!empty($key)) { $class = null; if (array_has($this->overrides, $key)) { $class = array_get($this->overrides, $key); } else { $class = $this->build($key); } return resolve($class); } return $this; } /** * Build the path of the Repository class. * * @param string $key * * @return string */ protected function build($key) { return app()->getNamespace() . config('les.repository_namespace') . '\\' . studly_case(str_singular($key)) . 'Repository'; } }
3bfcd86532a3c068e804e3f569de38f6412d8e90
core/src/main/java/bisq/core/btc/model/InputsAndChangeOutput.java
core/src/main/java/bisq/core/btc/model/InputsAndChangeOutput.java
/* * This file is part of Bisq. * * Bisq is free software: you can redistribute it and/or modify it * under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at * your option) any later version. * * Bisq is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public * License for more details. * * You should have received a copy of the GNU Affero General Public License * along with Bisq. If not, see <http://www.gnu.org/licenses/>. */ package bisq.core.btc.model; import java.util.ArrayList; import javax.annotation.Nullable; import static com.google.common.base.Preconditions.checkArgument; public class InputsAndChangeOutput { public final ArrayList<RawTransactionInput> rawTransactionInputs; // Is set to 0L in case we don't have an output public final long changeOutputValue; @Nullable public final String changeOutputAddress; public InputsAndChangeOutput(ArrayList<RawTransactionInput> rawTransactionInputs, long changeOutputValue, @Nullable String changeOutputAddress) { checkArgument(!rawTransactionInputs.isEmpty(), "rawInputs.isEmpty()"); this.rawTransactionInputs = rawTransactionInputs; this.changeOutputValue = changeOutputValue; this.changeOutputAddress = changeOutputAddress; } }
/* * This file is part of Bisq. * * Bisq is free software: you can redistribute it and/or modify it * under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at * your option) any later version. * * Bisq is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public * License for more details. * * You should have received a copy of the GNU Affero General Public License * along with Bisq. If not, see <http://www.gnu.org/licenses/>. */ package bisq.core.btc.model; import java.util.List; import javax.annotation.Nullable; import static com.google.common.base.Preconditions.checkArgument; public class InputsAndChangeOutput { public final List<RawTransactionInput> rawTransactionInputs; // Is set to 0L in case we don't have an output public final long changeOutputValue; @Nullable public final String changeOutputAddress; public InputsAndChangeOutput(List<RawTransactionInput> rawTransactionInputs, long changeOutputValue, @Nullable String changeOutputAddress) { checkArgument(!rawTransactionInputs.isEmpty(), "rawInputs.isEmpty()"); this.rawTransactionInputs = rawTransactionInputs; this.changeOutputValue = changeOutputValue; this.changeOutputAddress = changeOutputAddress; } }
Use List instead of ArrayList as type
Use List instead of ArrayList as type
Java
agpl-3.0
bitsquare/bitsquare,bisq-network/exchange,bisq-network/exchange,bitsquare/bitsquare
java
## Code Before: /* * This file is part of Bisq. * * Bisq is free software: you can redistribute it and/or modify it * under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at * your option) any later version. * * Bisq is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public * License for more details. * * You should have received a copy of the GNU Affero General Public License * along with Bisq. If not, see <http://www.gnu.org/licenses/>. */ package bisq.core.btc.model; import java.util.ArrayList; import javax.annotation.Nullable; import static com.google.common.base.Preconditions.checkArgument; public class InputsAndChangeOutput { public final ArrayList<RawTransactionInput> rawTransactionInputs; // Is set to 0L in case we don't have an output public final long changeOutputValue; @Nullable public final String changeOutputAddress; public InputsAndChangeOutput(ArrayList<RawTransactionInput> rawTransactionInputs, long changeOutputValue, @Nullable String changeOutputAddress) { checkArgument(!rawTransactionInputs.isEmpty(), "rawInputs.isEmpty()"); this.rawTransactionInputs = rawTransactionInputs; this.changeOutputValue = changeOutputValue; this.changeOutputAddress = changeOutputAddress; } } ## Instruction: Use List instead of ArrayList as type ## Code After: /* * This file is part of Bisq. * * Bisq is free software: you can redistribute it and/or modify it * under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at * your option) any later version. * * Bisq is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public * License for more details. * * You should have received a copy of the GNU Affero General Public License * along with Bisq. If not, see <http://www.gnu.org/licenses/>. */ package bisq.core.btc.model; import java.util.List; import javax.annotation.Nullable; import static com.google.common.base.Preconditions.checkArgument; public class InputsAndChangeOutput { public final List<RawTransactionInput> rawTransactionInputs; // Is set to 0L in case we don't have an output public final long changeOutputValue; @Nullable public final String changeOutputAddress; public InputsAndChangeOutput(List<RawTransactionInput> rawTransactionInputs, long changeOutputValue, @Nullable String changeOutputAddress) { checkArgument(!rawTransactionInputs.isEmpty(), "rawInputs.isEmpty()"); this.rawTransactionInputs = rawTransactionInputs; this.changeOutputValue = changeOutputValue; this.changeOutputAddress = changeOutputAddress; } }
f3033ed163de4fa8c56f034cae861e7f6556ac4c
lib/dry/types/enum.rb
lib/dry/types/enum.rb
require 'dry/types/decorator' module Dry module Types class Enum include Type include Dry::Equalizer(:type, :options, :mapping) include Decorator # @return [Array] attr_reader :values # @return [Hash] attr_reader :mapping # @param [Type] type # @param [Hash] options # @option options [Array] :values def initialize(type, options) super @mapping = options.fetch(:mapping).freeze @values = @mapping.keys.freeze.each(&:freeze) end # @param [Object] input # @return [Object] def call(input = Undefined) value = if input.equal?(Undefined) type.call elsif values.include?(input) input elsif mapping.key?(input) mapping[input] elsif mapping.values.include?(input) mapping.key(input) else input end type[value] end alias_method :[], :call def default(*) raise '.enum(*values).default(value) is not supported. Call '\ '.default(value).enum(*values) instead' end # Check whether a value is in the enum # @param [Object] value # @return [Boolean] alias_method :include?, :valid? # @api public # # @see Definition#to_ast def to_ast(meta: true) [:enum, [type.to_ast(meta: meta), mapping, meta ? self.meta : EMPTY_HASH]] end end end end
require 'dry/types/decorator' module Dry module Types class Enum include Type include Dry::Equalizer(:type, :options, :mapping) include Decorator # @return [Array] attr_reader :values # @return [Hash] attr_reader :mapping # @return [Hash] attr_reader :inverted_mapping # @param [Type] type # @param [Hash] options # @option options [Array] :values def initialize(type, options) super @mapping = options.fetch(:mapping).freeze @values = @mapping.keys.freeze @inverted_mapping = @mapping.invert.freeze freeze end # @param [Object] input # @return [Object] def call(input = Undefined) value = if input.equal?(Undefined) type.call elsif mapping.key?(input) input else inverted_mapping.fetch(input, input) end type[value] end alias_method :[], :call def default(*) raise '.enum(*values).default(value) is not supported. Call '\ '.default(value).enum(*values) instead' end # Check whether a value is in the enum # @param [Object] value # @return [Boolean] alias_method :include?, :valid? # @api public # # @see Definition#to_ast def to_ast(meta: true) [:enum, [type.to_ast(meta: meta), mapping, meta ? self.meta : EMPTY_HASH]] end end end end
Replace array search with hash lookup
Replace array search with hash lookup
Ruby
mit
dryrb/dry-data,dryrb/dry-types,dryrb/dry-data,dryrb/dry-types
ruby
## Code Before: require 'dry/types/decorator' module Dry module Types class Enum include Type include Dry::Equalizer(:type, :options, :mapping) include Decorator # @return [Array] attr_reader :values # @return [Hash] attr_reader :mapping # @param [Type] type # @param [Hash] options # @option options [Array] :values def initialize(type, options) super @mapping = options.fetch(:mapping).freeze @values = @mapping.keys.freeze.each(&:freeze) end # @param [Object] input # @return [Object] def call(input = Undefined) value = if input.equal?(Undefined) type.call elsif values.include?(input) input elsif mapping.key?(input) mapping[input] elsif mapping.values.include?(input) mapping.key(input) else input end type[value] end alias_method :[], :call def default(*) raise '.enum(*values).default(value) is not supported. Call '\ '.default(value).enum(*values) instead' end # Check whether a value is in the enum # @param [Object] value # @return [Boolean] alias_method :include?, :valid? # @api public # # @see Definition#to_ast def to_ast(meta: true) [:enum, [type.to_ast(meta: meta), mapping, meta ? self.meta : EMPTY_HASH]] end end end end ## Instruction: Replace array search with hash lookup ## Code After: require 'dry/types/decorator' module Dry module Types class Enum include Type include Dry::Equalizer(:type, :options, :mapping) include Decorator # @return [Array] attr_reader :values # @return [Hash] attr_reader :mapping # @return [Hash] attr_reader :inverted_mapping # @param [Type] type # @param [Hash] options # @option options [Array] :values def initialize(type, options) super @mapping = options.fetch(:mapping).freeze @values = @mapping.keys.freeze @inverted_mapping = @mapping.invert.freeze freeze end # @param [Object] input # @return [Object] def call(input = Undefined) value = if input.equal?(Undefined) type.call elsif mapping.key?(input) input else inverted_mapping.fetch(input, input) end type[value] end alias_method :[], :call def default(*) raise '.enum(*values).default(value) is not supported. Call '\ '.default(value).enum(*values) instead' end # Check whether a value is in the enum # @param [Object] value # @return [Boolean] alias_method :include?, :valid? # @api public # # @see Definition#to_ast def to_ast(meta: true) [:enum, [type.to_ast(meta: meta), mapping, meta ? self.meta : EMPTY_HASH]] end end end end
1979204ddddcb1b0d07f649ebc6614a4ec0d5fe4
lib/carto/db/migration_helper.rb
lib/carto/db/migration_helper.rb
module Carto module Db module MigrationHelper LOCK_TIMEOUT_MS = 1000 MAX_RETRIES = 3 WAIT_BETWEEN_RETRIES_S = 2 def migration(up_block, down_block) Sequel.migration do # Forces this migration to run under a transaction (controlled by Sequel) transaction up do lock_safe_migration(&up_block) end down do lock_safe_migration(&down_block) end end end private def lock_safe_migration(&block) run "SET lock_timeout TO #{LOCK_TIMEOUT_MS}" # As the external transaction is controlled by Sequel, we cannot ROLLBACK and BEGIN a new one # Instead, we use SAVEPOINTs (https://www.postgresql.org/docs/current/static/sql-savepoint.html) # to start a "sub-transaction" that we can rollback without affecting Sequel run 'SAVEPOINT before_migration' (1..MAX_RETRIES).each do begin instance_eval &block return rescue Sequel::DatabaseError => e if e.message.include?('lock timeout') # In case of timeout, we retry by reexecuting the code since the SAVEPOINT run 'ROLLBACK TO SAVEPOINT before_migration' sleep WAIT_BETWEEN_RETRIES_S else raise e end end end # Raising an exception forces Sequel to rollback the entire transaction raise 'Retries exceeded during database migration' ensure run "SET lock_timeout TO DEFAULT" end end end end
module Carto module Db module MigrationHelper LOCK_TIMEOUT_MS = 1000 MAX_RETRIES = 3 WAIT_BETWEEN_RETRIES_S = 2 def migration(up_block, down_block) Sequel.migration do # Forces this migration to run under a transaction (controlled by Sequel) transaction up do lock_safe_migration(&up_block) end down do lock_safe_migration(&down_block) end end end private def lock_safe_migration(&block) run "SET lock_timeout TO #{LOCK_TIMEOUT_MS}" # As the external transaction is controlled by Sequel, we cannot ROLLBACK and BEGIN a new one # Instead, we use SAVEPOINTs (https://www.postgresql.org/docs/current/static/sql-savepoint.html) # to start a "sub-transaction" that we can rollback without affecting Sequel run 'SAVEPOINT before_migration' (1..MAX_RETRIES).each do begin instance_eval &block return rescue Sequel::DatabaseError => e if e.message.include?('lock timeout') # In case of timeout, we retry by reexecuting the code since the SAVEPOINT run 'ROLLBACK TO SAVEPOINT before_migration' sleep WAIT_BETWEEN_RETRIES_S else puts e.message raise e end end end # Raising an exception forces Sequel to rollback the entire transaction raise 'Retries exceeded during database migration' ensure run "SET lock_timeout TO DEFAULT" end end end end
Add extra error information to migration helper
Add extra error information to migration helper
Ruby
bsd-3-clause
CartoDB/cartodb,CartoDB/cartodb,splashblot/dronedb,splashblot/dronedb,CartoDB/cartodb,CartoDB/cartodb,CartoDB/cartodb,splashblot/dronedb,splashblot/dronedb,splashblot/dronedb
ruby
## Code Before: module Carto module Db module MigrationHelper LOCK_TIMEOUT_MS = 1000 MAX_RETRIES = 3 WAIT_BETWEEN_RETRIES_S = 2 def migration(up_block, down_block) Sequel.migration do # Forces this migration to run under a transaction (controlled by Sequel) transaction up do lock_safe_migration(&up_block) end down do lock_safe_migration(&down_block) end end end private def lock_safe_migration(&block) run "SET lock_timeout TO #{LOCK_TIMEOUT_MS}" # As the external transaction is controlled by Sequel, we cannot ROLLBACK and BEGIN a new one # Instead, we use SAVEPOINTs (https://www.postgresql.org/docs/current/static/sql-savepoint.html) # to start a "sub-transaction" that we can rollback without affecting Sequel run 'SAVEPOINT before_migration' (1..MAX_RETRIES).each do begin instance_eval &block return rescue Sequel::DatabaseError => e if e.message.include?('lock timeout') # In case of timeout, we retry by reexecuting the code since the SAVEPOINT run 'ROLLBACK TO SAVEPOINT before_migration' sleep WAIT_BETWEEN_RETRIES_S else raise e end end end # Raising an exception forces Sequel to rollback the entire transaction raise 'Retries exceeded during database migration' ensure run "SET lock_timeout TO DEFAULT" end end end end ## Instruction: Add extra error information to migration helper ## Code After: module Carto module Db module MigrationHelper LOCK_TIMEOUT_MS = 1000 MAX_RETRIES = 3 WAIT_BETWEEN_RETRIES_S = 2 def migration(up_block, down_block) Sequel.migration do # Forces this migration to run under a transaction (controlled by Sequel) transaction up do lock_safe_migration(&up_block) end down do lock_safe_migration(&down_block) end end end private def lock_safe_migration(&block) run "SET lock_timeout TO #{LOCK_TIMEOUT_MS}" # As the external transaction is controlled by Sequel, we cannot ROLLBACK and BEGIN a new one # Instead, we use SAVEPOINTs (https://www.postgresql.org/docs/current/static/sql-savepoint.html) # to start a "sub-transaction" that we can rollback without affecting Sequel run 'SAVEPOINT before_migration' (1..MAX_RETRIES).each do begin instance_eval &block return rescue Sequel::DatabaseError => e if e.message.include?('lock timeout') # In case of timeout, we retry by reexecuting the code since the SAVEPOINT run 'ROLLBACK TO SAVEPOINT before_migration' sleep WAIT_BETWEEN_RETRIES_S else puts e.message raise e end end end # Raising an exception forces Sequel to rollback the entire transaction raise 'Retries exceeded during database migration' ensure run "SET lock_timeout TO DEFAULT" end end end end
72691fbefd2d04a57a66dd3b1cd88b2a1b9478d2
src/FOM/CoreBundle/Resources/public/js/widgets/dropdown.js
src/FOM/CoreBundle/Resources/public/js/widgets/dropdown.js
$(function() { $('.dropdown').each(function() { var element = $(this); var dropdownList = element.find(".dropdownList"); if(dropdownList.children().length === 0) { element.find("option").each(function(i, e) { $(e).addClass("opt-" + i); dropdownList.append($('<li class="item-' + i + '">' + $(e).text() + '</li>')); }); } var select = element.find("select").val(); element.find(".dropdownValue").text(element.find('option[value="' + select + '"]').text()) }).on('click', function() { var me = $(this); var list = me.find(".dropdownList"); var opts = me.find(".hiddenDropdown"); if(list.css("display") == "block") { list.hide(); } else { $(".dropdownList").hide(); list.show(); list.find("li").one("click", function(event) { event.stopPropagation(); list.hide().find("li").off("click"); var me2 = $(this); var opt = me2.attr("class").replace("item", "opt"); me.find(".dropdownValue").text(me2.text()); opts.find("[selected=selected]").removeAttr("selected"); var val = opts.find("." + opt).attr("selected", "selected").val(); opts.val(val).trigger('change'); }) } $(document).one("click", function() { list.hide().find("li").off("mouseout").off("click"); }); return false; }) });
$(function() { $('.dropdown').each(function() { var me = $(this); var dropdownList = me.find(".dropdownList"); if(dropdownList.children().length === 0) { me.find("option").each(function(i, e) { $(e).addClass("opt-" + i); dropdownList.append($('<li class="item-' + i + '">' + $(e).text() + '</li>')); }); } var select = me.find("select").val(); me.find(".dropdownValue").text(me.find('option[value="' + select + '"]').text()) }); $(document).on("click", ".dropdown", function() { var me = $(this); var list = me.find(".dropdownList"); var opts = me.find(".hiddenDropdown"); if(list.css("display") == "block") { list.hide(); } else { $(".dropdownList").hide(); list.show(); list.find("li").one("click", function(event) { event.stopPropagation(); list.hide().find("li").off("click"); var me2 = $(this); var opt = me2.attr("class").replace("item", "opt"); me.find(".dropdownValue").text(me2.text()); opts.find("[selected=selected]").removeAttr("selected"); var val = opts.find("." + opt).attr("selected", "selected").val(); opts.val(val).trigger('change'); }) } $(document).one("click", function() { list.hide().find("li").off("mouseout").off("click"); }); return false; }); });
Fix select element global listener
Fix select element global listener
JavaScript
mit
mapbender/fom,mapbender/fom,mapbender/fom
javascript
## Code Before: $(function() { $('.dropdown').each(function() { var element = $(this); var dropdownList = element.find(".dropdownList"); if(dropdownList.children().length === 0) { element.find("option").each(function(i, e) { $(e).addClass("opt-" + i); dropdownList.append($('<li class="item-' + i + '">' + $(e).text() + '</li>')); }); } var select = element.find("select").val(); element.find(".dropdownValue").text(element.find('option[value="' + select + '"]').text()) }).on('click', function() { var me = $(this); var list = me.find(".dropdownList"); var opts = me.find(".hiddenDropdown"); if(list.css("display") == "block") { list.hide(); } else { $(".dropdownList").hide(); list.show(); list.find("li").one("click", function(event) { event.stopPropagation(); list.hide().find("li").off("click"); var me2 = $(this); var opt = me2.attr("class").replace("item", "opt"); me.find(".dropdownValue").text(me2.text()); opts.find("[selected=selected]").removeAttr("selected"); var val = opts.find("." + opt).attr("selected", "selected").val(); opts.val(val).trigger('change'); }) } $(document).one("click", function() { list.hide().find("li").off("mouseout").off("click"); }); return false; }) }); ## Instruction: Fix select element global listener ## Code After: $(function() { $('.dropdown').each(function() { var me = $(this); var dropdownList = me.find(".dropdownList"); if(dropdownList.children().length === 0) { me.find("option").each(function(i, e) { $(e).addClass("opt-" + i); dropdownList.append($('<li class="item-' + i + '">' + $(e).text() + '</li>')); }); } var select = me.find("select").val(); me.find(".dropdownValue").text(me.find('option[value="' + select + '"]').text()) }); $(document).on("click", ".dropdown", function() { var me = $(this); var list = me.find(".dropdownList"); var opts = me.find(".hiddenDropdown"); if(list.css("display") == "block") { list.hide(); } else { $(".dropdownList").hide(); list.show(); list.find("li").one("click", function(event) { event.stopPropagation(); list.hide().find("li").off("click"); var me2 = $(this); var opt = me2.attr("class").replace("item", "opt"); me.find(".dropdownValue").text(me2.text()); opts.find("[selected=selected]").removeAttr("selected"); var val = opts.find("." + opt).attr("selected", "selected").val(); opts.val(val).trigger('change'); }) } $(document).one("click", function() { list.hide().find("li").off("mouseout").off("click"); }); return false; }); });
0c35ee2a8a71bf776001ebebc186b236ab34e7d3
library/src/main/java/com/novoda/downloadmanager/NotificationDispatcher.java
library/src/main/java/com/novoda/downloadmanager/NotificationDispatcher.java
package com.novoda.downloadmanager; import static com.novoda.downloadmanager.DownloadBatchStatus.Status.DELETION; import static com.novoda.downloadmanager.DownloadBatchStatus.Status.DOWNLOADED; class NotificationDispatcher { private final Object waitForDownloadService; private final NotificationCreator<DownloadBatchStatus> notificationCreator; private DownloadService downloadService; NotificationDispatcher(Object waitForDownloadService, NotificationCreator<DownloadBatchStatus> notificationCreator) { this.waitForDownloadService = waitForDownloadService; this.notificationCreator = notificationCreator; } void updateNotification(DownloadBatchStatus downloadBatchStatus) { WaitForDownloadService.<Void>waitFor(downloadService, waitForDownloadService) .thenPerform(executeUpdateNotification(downloadBatchStatus)); } private WaitForDownloadService.ThenPerform.Action<Void> executeUpdateNotification(DownloadBatchStatus downloadBatchStatus) { return () -> { NotificationInformation notificationInformation = notificationCreator.createNotification(downloadBatchStatus); if (downloadBatchStatus.status() == DOWNLOADED || downloadBatchStatus.status() == DELETION) { downloadService.stackNotification(notificationInformation); } else { downloadService.updateNotification(notificationInformation); } return null; }; } void setDownloadService(DownloadService downloadService) { this.downloadService = downloadService; } }
package com.novoda.downloadmanager; import android.support.annotation.WorkerThread; import static com.novoda.downloadmanager.DownloadBatchStatus.Status.DELETION; import static com.novoda.downloadmanager.DownloadBatchStatus.Status.DOWNLOADED; class NotificationDispatcher { private final Object waitForDownloadService; private final NotificationCreator<DownloadBatchStatus> notificationCreator; private DownloadService downloadService; NotificationDispatcher(Object waitForDownloadService, NotificationCreator<DownloadBatchStatus> notificationCreator) { this.waitForDownloadService = waitForDownloadService; this.notificationCreator = notificationCreator; } @WorkerThread void updateNotification(DownloadBatchStatus downloadBatchStatus) { WaitForDownloadService.<Void>waitFor(downloadService, waitForDownloadService) .thenPerform(executeUpdateNotification(downloadBatchStatus)); } private WaitForDownloadService.ThenPerform.Action<Void> executeUpdateNotification(DownloadBatchStatus downloadBatchStatus) { return () -> { NotificationInformation notificationInformation = notificationCreator.createNotification(downloadBatchStatus); if (downloadBatchStatus.status() == DOWNLOADED || downloadBatchStatus.status() == DELETION) { downloadService.stackNotification(notificationInformation); } else { downloadService.updateNotification(notificationInformation); } return null; }; } void setDownloadService(DownloadService downloadService) { this.downloadService = downloadService; } }
Add worker thread annotation to update notification.
Add worker thread annotation to update notification.
Java
apache-2.0
novoda/download-manager
java
## Code Before: package com.novoda.downloadmanager; import static com.novoda.downloadmanager.DownloadBatchStatus.Status.DELETION; import static com.novoda.downloadmanager.DownloadBatchStatus.Status.DOWNLOADED; class NotificationDispatcher { private final Object waitForDownloadService; private final NotificationCreator<DownloadBatchStatus> notificationCreator; private DownloadService downloadService; NotificationDispatcher(Object waitForDownloadService, NotificationCreator<DownloadBatchStatus> notificationCreator) { this.waitForDownloadService = waitForDownloadService; this.notificationCreator = notificationCreator; } void updateNotification(DownloadBatchStatus downloadBatchStatus) { WaitForDownloadService.<Void>waitFor(downloadService, waitForDownloadService) .thenPerform(executeUpdateNotification(downloadBatchStatus)); } private WaitForDownloadService.ThenPerform.Action<Void> executeUpdateNotification(DownloadBatchStatus downloadBatchStatus) { return () -> { NotificationInformation notificationInformation = notificationCreator.createNotification(downloadBatchStatus); if (downloadBatchStatus.status() == DOWNLOADED || downloadBatchStatus.status() == DELETION) { downloadService.stackNotification(notificationInformation); } else { downloadService.updateNotification(notificationInformation); } return null; }; } void setDownloadService(DownloadService downloadService) { this.downloadService = downloadService; } } ## Instruction: Add worker thread annotation to update notification. ## Code After: package com.novoda.downloadmanager; import android.support.annotation.WorkerThread; import static com.novoda.downloadmanager.DownloadBatchStatus.Status.DELETION; import static com.novoda.downloadmanager.DownloadBatchStatus.Status.DOWNLOADED; class NotificationDispatcher { private final Object waitForDownloadService; private final NotificationCreator<DownloadBatchStatus> notificationCreator; private DownloadService downloadService; NotificationDispatcher(Object waitForDownloadService, NotificationCreator<DownloadBatchStatus> notificationCreator) { this.waitForDownloadService = waitForDownloadService; this.notificationCreator = notificationCreator; } @WorkerThread void updateNotification(DownloadBatchStatus downloadBatchStatus) { WaitForDownloadService.<Void>waitFor(downloadService, waitForDownloadService) .thenPerform(executeUpdateNotification(downloadBatchStatus)); } private WaitForDownloadService.ThenPerform.Action<Void> executeUpdateNotification(DownloadBatchStatus downloadBatchStatus) { return () -> { NotificationInformation notificationInformation = notificationCreator.createNotification(downloadBatchStatus); if (downloadBatchStatus.status() == DOWNLOADED || downloadBatchStatus.status() == DELETION) { downloadService.stackNotification(notificationInformation); } else { downloadService.updateNotification(notificationInformation); } return null; }; } void setDownloadService(DownloadService downloadService) { this.downloadService = downloadService; } }
d691798551ae3e894d683c5ea142ac1f6b64393b
lib/query_string_search/comparator.rb
lib/query_string_search/comparator.rb
module QueryStringSearch module Comparator def self.using(operator) create_comparison comparison.operator = operator self end def self.does(subject) create_comparison comparison.subject = subject self end def self.equal?(other) comparison.operator = "=" compare_with?(other) end def self.contain?(other) comparison.operator = "∈" compare_with?(other) end def self.compare_with?(other) comparison.other = other resolve end private def self.create_comparison @comparison ||= Comparison.new end def self.comparison @comparison end def self.resolve ret = @comparison.compare @comparison = nil ret end end end module QueryStringSearch module Comparator class Comparison attr_accessor :subject, :operator, :other def compare if operator == "=" equal? elsif operator == "∈" contain? elsif ["<",">","<=",">="] inequal? end end def inequal? eval("#{other} #{operator} #{subject}") end def equal? normalize(subject) == normalize(other) end def contain? normalize(subject).include?(normalize(other)) end def normalize(unnormalized) if unnormalized.respond_to?(:each) unnormalized.map(&:to_s).map(&:upcase) else unnormalized.to_s.upcase end end end end end
module QueryStringSearch module Comparator def self.using(operator) create_comparison comparison.operator = operator self end def self.does(subject) create_comparison comparison.subject = subject self end def self.equal?(other) comparison.operator = "=" compare_with?(other) end def self.contain?(other) comparison.operator = "∈" compare_with?(other) end def self.compare_with?(other) comparison.other = other resolve end private def self.create_comparison @comparison ||= Comparison.new end def self.comparison @comparison end def self.resolve ret = @comparison.compare @comparison = nil ret end end end module QueryStringSearch module Comparator class Comparison attr_accessor :subject, :operator, :other def compare if ["=".to_sym].include?(operator) equal? elsif [:∈].include?(operator) contain? elsif [:<, :>, :<=, :>=].include?(operator) inequal? else false end end def operator=(x) @operator = x.to_sym end def inequal? other.to_i.public_send(operator, subject.to_i) end def equal? normalize(other).public_send(:==, normalize(subject)) end def contain? normalize(subject).public_send(:&, [normalize(other)]).any? end def normalize(unnormalized) if unnormalized.respond_to?(:each) unnormalized.map(&:to_s).map(&:upcase) else unnormalized.to_s.upcase end end end end end
Move from strings & eval to symbols and public_send
Move from strings & eval to symbols and public_send Seems like an obvious change. This works, but it's obviously not in a final state yet.
Ruby
mit
umn-asr/query_string_search
ruby
## Code Before: module QueryStringSearch module Comparator def self.using(operator) create_comparison comparison.operator = operator self end def self.does(subject) create_comparison comparison.subject = subject self end def self.equal?(other) comparison.operator = "=" compare_with?(other) end def self.contain?(other) comparison.operator = "∈" compare_with?(other) end def self.compare_with?(other) comparison.other = other resolve end private def self.create_comparison @comparison ||= Comparison.new end def self.comparison @comparison end def self.resolve ret = @comparison.compare @comparison = nil ret end end end module QueryStringSearch module Comparator class Comparison attr_accessor :subject, :operator, :other def compare if operator == "=" equal? elsif operator == "∈" contain? elsif ["<",">","<=",">="] inequal? end end def inequal? eval("#{other} #{operator} #{subject}") end def equal? normalize(subject) == normalize(other) end def contain? normalize(subject).include?(normalize(other)) end def normalize(unnormalized) if unnormalized.respond_to?(:each) unnormalized.map(&:to_s).map(&:upcase) else unnormalized.to_s.upcase end end end end end ## Instruction: Move from strings & eval to symbols and public_send Seems like an obvious change. This works, but it's obviously not in a final state yet. ## Code After: module QueryStringSearch module Comparator def self.using(operator) create_comparison comparison.operator = operator self end def self.does(subject) create_comparison comparison.subject = subject self end def self.equal?(other) comparison.operator = "=" compare_with?(other) end def self.contain?(other) comparison.operator = "∈" compare_with?(other) end def self.compare_with?(other) comparison.other = other resolve end private def self.create_comparison @comparison ||= Comparison.new end def self.comparison @comparison end def self.resolve ret = @comparison.compare @comparison = nil ret end end end module QueryStringSearch module Comparator class Comparison attr_accessor :subject, :operator, :other def compare if ["=".to_sym].include?(operator) equal? elsif [:∈].include?(operator) contain? elsif [:<, :>, :<=, :>=].include?(operator) inequal? else false end end def operator=(x) @operator = x.to_sym end def inequal? other.to_i.public_send(operator, subject.to_i) end def equal? normalize(other).public_send(:==, normalize(subject)) end def contain? normalize(subject).public_send(:&, [normalize(other)]).any? end def normalize(unnormalized) if unnormalized.respond_to?(:each) unnormalized.map(&:to_s).map(&:upcase) else unnormalized.to_s.upcase end end end end end
b00876c7c5563839179364762053dfff7f74c124
test/Permissions/Editor/Create/NotAvailable/FieldEditPermissionTest.php
test/Permissions/Editor/Create/NotAvailable/FieldEditPermissionTest.php
<?php namespace ProcessWire\GraphQL\Test\Permissions; use ProcessWire\GraphQL\Test\GraphqlTestCase; use ProcessWire\GraphQL\Utils; use function ProcessWire\GraphQL\Test\Assert\assertTypePathNotExists; class EditorCreateNotAvailableFieldEditPermissionTest extends GraphqlTestCase { /** * + For editor. * + The template is legal. * + The configured parent template is legal. * + All required fields are legal. * + Editor has all required permissions for templates. * - Editor does not have edit permission on required field. (title) */ public static function getSettings() { $editorRole = Utils::roles()->get("editor"); return [ 'login' => 'editor', 'legalTemplates' => ['skyscraper', 'city'], 'legalFields' => ['title', 'images'], 'access' => [ 'templates' => [ [ 'name' => 'skyscraper', 'roles' => [$editorRole->id], 'editRoles' => [$editorRole->id], 'createRoles' => [$editorRole->id], ], [ 'name' => 'city', 'roles' => [$editorRole->id], 'addRoles' => [$editorRole->id], ] ], 'fields' => [ [ 'name' => 'images', 'editRoles' => [$editorRole->id], ] ] ] ]; } public function testPermission() { assertTypePathNotExists( ['Mutation', 'createSkyscraper'], 'createSkyscraper mutation field should not be available if one of the required fields is not legal.' ); } }
<?php namespace ProcessWire\GraphQL\Test\Permissions; use ProcessWire\GraphQL\Test\GraphqlTestCase; use function ProcessWire\GraphQL\Test\Assert\assertTypePathNotExists; class EditorCreateNotAvailableFieldEditPermissionTest extends GraphqlTestCase { /** * + For editor. * + The template is legal. * + The configured parent template is legal. * + All required fields are legal. * + Editor has all required permissions for templates. * - Editor does not have edit permission on required field. (title) */ public static function getSettings() { return [ 'login' => 'editor', 'legalTemplates' => ['skyscraper', 'city'], 'legalFields' => ['title', 'images'], 'access' => [ 'templates' => [ [ 'name' => 'skyscraper', 'roles' => ['editor'], 'editRoles' => ['editor'], 'createRoles' => ['editor'], ], [ 'name' => 'city', 'roles' => ['editor'], 'addRoles' => ['editor'], ] ], 'fields' => [ [ 'name' => 'images', 'editRoles' => ['editor'], ], [ 'name' => 'title', // 'editRoles' => ['editor'], // <-- has no edit permission to the required "title" field. ], ] ] ]; } public function testPermission() { assertTypePathNotExists( ['Mutation', 'createSkyscraper'], 'createSkyscraper mutation field should not be available if user has no edit permission on the required field.' ); } }
Update test case create is not available because of field edit permission.
Update test case create is not available because of field edit permission.
PHP
mit
dadish/ProcessGraphQL,dadish/ProcessGraphQL
php
## Code Before: <?php namespace ProcessWire\GraphQL\Test\Permissions; use ProcessWire\GraphQL\Test\GraphqlTestCase; use ProcessWire\GraphQL\Utils; use function ProcessWire\GraphQL\Test\Assert\assertTypePathNotExists; class EditorCreateNotAvailableFieldEditPermissionTest extends GraphqlTestCase { /** * + For editor. * + The template is legal. * + The configured parent template is legal. * + All required fields are legal. * + Editor has all required permissions for templates. * - Editor does not have edit permission on required field. (title) */ public static function getSettings() { $editorRole = Utils::roles()->get("editor"); return [ 'login' => 'editor', 'legalTemplates' => ['skyscraper', 'city'], 'legalFields' => ['title', 'images'], 'access' => [ 'templates' => [ [ 'name' => 'skyscraper', 'roles' => [$editorRole->id], 'editRoles' => [$editorRole->id], 'createRoles' => [$editorRole->id], ], [ 'name' => 'city', 'roles' => [$editorRole->id], 'addRoles' => [$editorRole->id], ] ], 'fields' => [ [ 'name' => 'images', 'editRoles' => [$editorRole->id], ] ] ] ]; } public function testPermission() { assertTypePathNotExists( ['Mutation', 'createSkyscraper'], 'createSkyscraper mutation field should not be available if one of the required fields is not legal.' ); } } ## Instruction: Update test case create is not available because of field edit permission. ## Code After: <?php namespace ProcessWire\GraphQL\Test\Permissions; use ProcessWire\GraphQL\Test\GraphqlTestCase; use function ProcessWire\GraphQL\Test\Assert\assertTypePathNotExists; class EditorCreateNotAvailableFieldEditPermissionTest extends GraphqlTestCase { /** * + For editor. * + The template is legal. * + The configured parent template is legal. * + All required fields are legal. * + Editor has all required permissions for templates. * - Editor does not have edit permission on required field. (title) */ public static function getSettings() { return [ 'login' => 'editor', 'legalTemplates' => ['skyscraper', 'city'], 'legalFields' => ['title', 'images'], 'access' => [ 'templates' => [ [ 'name' => 'skyscraper', 'roles' => ['editor'], 'editRoles' => ['editor'], 'createRoles' => ['editor'], ], [ 'name' => 'city', 'roles' => ['editor'], 'addRoles' => ['editor'], ] ], 'fields' => [ [ 'name' => 'images', 'editRoles' => ['editor'], ], [ 'name' => 'title', // 'editRoles' => ['editor'], // <-- has no edit permission to the required "title" field. ], ] ] ]; } public function testPermission() { assertTypePathNotExists( ['Mutation', 'createSkyscraper'], 'createSkyscraper mutation field should not be available if user has no edit permission on the required field.' ); } }
d5d303b3bad1c3451457acf6dc98d673f2e98f2f
java/example/default/index.html
java/example/default/index.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <title>Hello MapReduce</title> </head> <body> <h1>Hello MapReduce!</h1> <table> <tr> <td>This is an example Map Reduce that demos parallel computation. <br /> For the purposes of illustration this MapReduce looks for collisions in Java's Random number generator. (There are not any.) <br /> Here a collision is defined as multiple seed values that when next is called produce the same output value. <br /> The input source is a range of numbers to test, and any collisions are logged and written out to a file in Google Cloud Storage. (Which in this case will be empty.) <br /> <a href="/randomcollisions">Random collisions example.</a> </td> </tr> <tr> <td>There is also a second more complex example that chains three MapReduces together:<br /> The first MapReduce creates some datastore entities <br /> The second MapReduce does some analysis on them <br /> and the third MapReduce deletes them. <br /> On the whole it does not do anything useful, but it shows how to chain mapreduce jobs together, and how to interact with the datastore from mapreduce jobs. <br /> It also gives an example of validating a request using a token. <br /> <a href="/entitycount">Entity counting example.</a> </td> </tr> </table> </body> </html>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <title>Hello MapReduce</title> </head> <body> <h1>MapReduce Sample Programs</h1> <table> <tr> <td><Big>Random collisions example</Big><br /> This example demonstrates parallel computation. It looks for collisions in Java's random number generator, <br /> where a collision is defined as multiple seed values that produce the same output value when <code>next()</code> is called. <br /> The input source is a range of numbers to test. Collisions are logged and written out to a file in Google Cloud Storage. <br /> (No collisions occur so the file will be empty.) <br /> <a href="/randomcollisions">Run the example.</a> <br /></td> </tr> <tr> <td><br /><Big>Entity counting example</Big><br /> The example shows how to “chain" MapReduce jobs together, running them sequentially, one after the other. <br /> It runs three MapReduce jobs: <br /> The first job creates some datastore entities, the second job analyzes them, and the third job deletes them. <br /> The example also shows how to access the datastore from a MapReduce job, and how to validate a request using a token. <br /> <a href="/entitycount">Run the example.</a> </td> </tr> </table> </body> </html>
Add some formatting to landing page.
Java: Add some formatting to landing page. Revision created by MOE tool push_codebase. MOE_MIGRATION=6869
HTML
apache-2.0
soundofjw/appengine-mapreduce,vendasta/appengine-mapreduce,lordzuko/appengine-mapreduce,vendasta/appengine-mapreduce,rbruyere/appengine-mapreduce,VirusTotal/appengine-mapreduce,soundofjw/appengine-mapreduce,VirusTotal/appengine-mapreduce,lordzuko/appengine-mapreduce,Candreas/mapreduce,ankit318/appengine-mapreduce,rbruyere/appengine-mapreduce,ankit318/appengine-mapreduce,mikelambert/appengine-mapreduce,Candreas/mapreduce,Candreas/mapreduce,talele08/appengine-mapreduce,aozarov/appengine-mapreduce,GoogleCloudPlatform/appengine-mapreduce,mikelambert/appengine-mapreduce,bmenasha/appengine-mapreduce,aozarov/appengine-mapreduce,chargrizzle/appengine-mapreduce,VirusTotal/appengine-mapreduce,westerhofffl/appengine-mapreduce,GoogleCloudPlatform/appengine-mapreduce,chargrizzle/appengine-mapreduce,ankit318/appengine-mapreduce,bmenasha/appengine-mapreduce,potatolondon/potato-mapreduce,soundofjw/appengine-mapreduce,rbruyere/appengine-mapreduce,GoogleCloudPlatform/appengine-mapreduce,bmenasha/appengine-mapreduce,aozarov/appengine-mapreduce,ankit318/appengine-mapreduce,westerhofffl/appengine-mapreduce,soundofjw/appengine-mapreduce,westerhofffl/appengine-mapreduce,aozarov/appengine-mapreduce,talele08/appengine-mapreduce,VirusTotal/appengine-mapreduce,talele08/appengine-mapreduce,vendasta/appengine-mapreduce,vendasta/appengine-mapreduce,aozarov/appengine-mapreduce,mikelambert/appengine-mapreduce,talele08/appengine-mapreduce,Candreas/mapreduce,GoogleCloudPlatform/appengine-mapreduce,bmenasha/appengine-mapreduce,westerhofffl/appengine-mapreduce,rbruyere/appengine-mapreduce,bmenasha/appengine-mapreduce,Candreas/mapreduce,chargrizzle/appengine-mapreduce,ankit318/appengine-mapreduce,GoogleCloudPlatform/appengine-mapreduce,talele08/appengine-mapreduce,mikelambert/appengine-mapreduce,VirusTotal/appengine-mapreduce,lordzuko/appengine-mapreduce,mikelambert/appengine-mapreduce,potatolondon/potato-mapreduce,westerhofffl/appengine-mapreduce,chargrizzle/appengine-mapreduce,soundofjw/appengine-mapreduce,lordzuko/appengine-mapreduce,potatolondon/potato-mapreduce,vendasta/appengine-mapreduce,chargrizzle/appengine-mapreduce,rbruyere/appengine-mapreduce,lordzuko/appengine-mapreduce
html
## Code Before: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <title>Hello MapReduce</title> </head> <body> <h1>Hello MapReduce!</h1> <table> <tr> <td>This is an example Map Reduce that demos parallel computation. <br /> For the purposes of illustration this MapReduce looks for collisions in Java's Random number generator. (There are not any.) <br /> Here a collision is defined as multiple seed values that when next is called produce the same output value. <br /> The input source is a range of numbers to test, and any collisions are logged and written out to a file in Google Cloud Storage. (Which in this case will be empty.) <br /> <a href="/randomcollisions">Random collisions example.</a> </td> </tr> <tr> <td>There is also a second more complex example that chains three MapReduces together:<br /> The first MapReduce creates some datastore entities <br /> The second MapReduce does some analysis on them <br /> and the third MapReduce deletes them. <br /> On the whole it does not do anything useful, but it shows how to chain mapreduce jobs together, and how to interact with the datastore from mapreduce jobs. <br /> It also gives an example of validating a request using a token. <br /> <a href="/entitycount">Entity counting example.</a> </td> </tr> </table> </body> </html> ## Instruction: Java: Add some formatting to landing page. Revision created by MOE tool push_codebase. MOE_MIGRATION=6869 ## Code After: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <title>Hello MapReduce</title> </head> <body> <h1>MapReduce Sample Programs</h1> <table> <tr> <td><Big>Random collisions example</Big><br /> This example demonstrates parallel computation. It looks for collisions in Java's random number generator, <br /> where a collision is defined as multiple seed values that produce the same output value when <code>next()</code> is called. <br /> The input source is a range of numbers to test. Collisions are logged and written out to a file in Google Cloud Storage. <br /> (No collisions occur so the file will be empty.) <br /> <a href="/randomcollisions">Run the example.</a> <br /></td> </tr> <tr> <td><br /><Big>Entity counting example</Big><br /> The example shows how to “chain" MapReduce jobs together, running them sequentially, one after the other. <br /> It runs three MapReduce jobs: <br /> The first job creates some datastore entities, the second job analyzes them, and the third job deletes them. <br /> The example also shows how to access the datastore from a MapReduce job, and how to validate a request using a token. <br /> <a href="/entitycount">Run the example.</a> </td> </tr> </table> </body> </html>
734903c777fb237509c21a988f79318ec14e997d
st2api/st2api/controllers/sensors.py
st2api/st2api/controllers/sensors.py
import six from pecan import abort from pecan.rest import RestController from mongoengine import ValidationError from st2common import log as logging from st2common.persistence.reactor import SensorType from st2common.models.base import jsexpose from st2common.models.api.reactor import SensorTypeAPI http_client = six.moves.http_client LOG = logging.getLogger(__name__) class SensorTypeController(RestController): @jsexpose(str) def get_one(self, id): """ Get sensortype by id. Handle: GET /sensortype/1 """ LOG.info('GET /sensortype/ with id=%s', id) try: sensor_type_db = SensorType.get_by_id(id) except (ValueError, ValidationError): LOG.exception('Database lookup for id="%s" resulted in exception.', id) abort(http_client.NOT_FOUND) return sensor_type_api = SensorTypeAPI.from_model(sensor_type_db) LOG.debug('GET /sensortype/ with id=%s, client_result=%s', id, sensor_type_api) return sensor_type_api @jsexpose(str) def get_all(self, **kw): """ List all sensor types. Handles requests: GET /sensortypes/ """ LOG.info('GET all /sensortypes/ with filters=%s', kw) sensor_type_dbs = SensorType.get_all(**kw) sensor_type_apis = [SensorTypeAPI.from_model(sensor_type_db) for sensor_type_db in sensor_type_dbs] return sensor_type_apis
import six from st2common import log as logging from st2common.persistence.reactor import SensorType from st2common.models.api.reactor import SensorTypeAPI from st2api.controllers.resource import ResourceController http_client = six.moves.http_client LOG = logging.getLogger(__name__) class SensorTypeController(ResourceController): model = SensorTypeAPI access = SensorType supported_filters = { 'name': 'name', 'pack': 'content_pack' } options = { 'sort': ['content_pack', 'name'] }
Use ResourceController instead of duplicating logic.
Use ResourceController instead of duplicating logic.
Python
apache-2.0
pinterb/st2,armab/st2,peak6/st2,pixelrebel/st2,Plexxi/st2,armab/st2,Plexxi/st2,punalpatel/st2,grengojbo/st2,jtopjian/st2,jtopjian/st2,StackStorm/st2,alfasin/st2,dennybaa/st2,lakshmi-kannan/st2,lakshmi-kannan/st2,pinterb/st2,grengojbo/st2,nzlosh/st2,StackStorm/st2,StackStorm/st2,pixelrebel/st2,alfasin/st2,emedvedev/st2,pixelrebel/st2,Itxaka/st2,Itxaka/st2,jtopjian/st2,nzlosh/st2,tonybaloney/st2,emedvedev/st2,punalpatel/st2,peak6/st2,tonybaloney/st2,tonybaloney/st2,Plexxi/st2,dennybaa/st2,emedvedev/st2,peak6/st2,StackStorm/st2,nzlosh/st2,pinterb/st2,armab/st2,nzlosh/st2,Itxaka/st2,grengojbo/st2,punalpatel/st2,Plexxi/st2,dennybaa/st2,lakshmi-kannan/st2,alfasin/st2
python
## Code Before: import six from pecan import abort from pecan.rest import RestController from mongoengine import ValidationError from st2common import log as logging from st2common.persistence.reactor import SensorType from st2common.models.base import jsexpose from st2common.models.api.reactor import SensorTypeAPI http_client = six.moves.http_client LOG = logging.getLogger(__name__) class SensorTypeController(RestController): @jsexpose(str) def get_one(self, id): """ Get sensortype by id. Handle: GET /sensortype/1 """ LOG.info('GET /sensortype/ with id=%s', id) try: sensor_type_db = SensorType.get_by_id(id) except (ValueError, ValidationError): LOG.exception('Database lookup for id="%s" resulted in exception.', id) abort(http_client.NOT_FOUND) return sensor_type_api = SensorTypeAPI.from_model(sensor_type_db) LOG.debug('GET /sensortype/ with id=%s, client_result=%s', id, sensor_type_api) return sensor_type_api @jsexpose(str) def get_all(self, **kw): """ List all sensor types. Handles requests: GET /sensortypes/ """ LOG.info('GET all /sensortypes/ with filters=%s', kw) sensor_type_dbs = SensorType.get_all(**kw) sensor_type_apis = [SensorTypeAPI.from_model(sensor_type_db) for sensor_type_db in sensor_type_dbs] return sensor_type_apis ## Instruction: Use ResourceController instead of duplicating logic. ## Code After: import six from st2common import log as logging from st2common.persistence.reactor import SensorType from st2common.models.api.reactor import SensorTypeAPI from st2api.controllers.resource import ResourceController http_client = six.moves.http_client LOG = logging.getLogger(__name__) class SensorTypeController(ResourceController): model = SensorTypeAPI access = SensorType supported_filters = { 'name': 'name', 'pack': 'content_pack' } options = { 'sort': ['content_pack', 'name'] }
d7025f92a240284d130ce455b6975ede42d0228e
chalice/cli/filewatch/eventbased.py
chalice/cli/filewatch/eventbased.py
import threading # noqa from typing import Callable, Optional # noqa import watchdog.observers from watchdog.events import FileSystemEventHandler from watchdog.events import FileSystemEvent # noqa from chalice.cli.filewatch import FileWatcher, WorkerProcess class WatchdogWorkerProcess(WorkerProcess): """Worker that runs the chalice dev server.""" def _start_file_watcher(self, project_dir): # type: (str) -> None restart_callback = WatchdogRestarter(self._restart_event) watcher = WatchdogFileWatcher() watcher.watch_for_file_changes( project_dir, restart_callback) class WatchdogFileWatcher(FileWatcher): def watch_for_file_changes(self, root_dir, callback): # type: (str, Callable[[], None]) -> None observer = watchdog.observers.Observer() observer.schedule(callback, root_dir, recursive=True) observer.start() class WatchdogRestarter(FileSystemEventHandler): def __init__(self, restart_event): # type: (threading.Event) -> None # The reason we're using threading self.restart_event = restart_event def on_any_event(self, event): # type: (FileSystemEvent) -> None # If we modify a file we'll get a FileModifiedEvent # as well as a DirectoryModifiedEvent. # We only care about reloading is a file is modified. if event.is_directory: return self() def __call__(self): # type: () -> None self.restart_event.set()
import threading # noqa from typing import Callable, Optional # noqa import watchdog.observers # pylint: disable=import-error from watchdog import events # pylint: disable=import-error from chalice.cli.filewatch import FileWatcher, WorkerProcess class WatchdogWorkerProcess(WorkerProcess): """Worker that runs the chalice dev server.""" def _start_file_watcher(self, project_dir): # type: (str) -> None restart_callback = WatchdogRestarter(self._restart_event) watcher = WatchdogFileWatcher() watcher.watch_for_file_changes( project_dir, restart_callback) class WatchdogFileWatcher(FileWatcher): def watch_for_file_changes(self, root_dir, callback): # type: (str, Callable[[], None]) -> None observer = watchdog.observers.Observer() observer.schedule(callback, root_dir, recursive=True) observer.start() class WatchdogRestarter(events.FileSystemEventHandler): def __init__(self, restart_event): # type: (threading.Event) -> None # The reason we're using threading self.restart_event = restart_event def on_any_event(self, event): # type: (events.FileSystemEvent) -> None # If we modify a file we'll get a FileModifiedEvent # as well as a DirectoryModifiedEvent. # We only care about reloading is a file is modified. if event.is_directory: return self() def __call__(self): # type: () -> None self.restart_event.set()
Make prcheck pass without needing cond deps
Make prcheck pass without needing cond deps
Python
apache-2.0
awslabs/chalice
python
## Code Before: import threading # noqa from typing import Callable, Optional # noqa import watchdog.observers from watchdog.events import FileSystemEventHandler from watchdog.events import FileSystemEvent # noqa from chalice.cli.filewatch import FileWatcher, WorkerProcess class WatchdogWorkerProcess(WorkerProcess): """Worker that runs the chalice dev server.""" def _start_file_watcher(self, project_dir): # type: (str) -> None restart_callback = WatchdogRestarter(self._restart_event) watcher = WatchdogFileWatcher() watcher.watch_for_file_changes( project_dir, restart_callback) class WatchdogFileWatcher(FileWatcher): def watch_for_file_changes(self, root_dir, callback): # type: (str, Callable[[], None]) -> None observer = watchdog.observers.Observer() observer.schedule(callback, root_dir, recursive=True) observer.start() class WatchdogRestarter(FileSystemEventHandler): def __init__(self, restart_event): # type: (threading.Event) -> None # The reason we're using threading self.restart_event = restart_event def on_any_event(self, event): # type: (FileSystemEvent) -> None # If we modify a file we'll get a FileModifiedEvent # as well as a DirectoryModifiedEvent. # We only care about reloading is a file is modified. if event.is_directory: return self() def __call__(self): # type: () -> None self.restart_event.set() ## Instruction: Make prcheck pass without needing cond deps ## Code After: import threading # noqa from typing import Callable, Optional # noqa import watchdog.observers # pylint: disable=import-error from watchdog import events # pylint: disable=import-error from chalice.cli.filewatch import FileWatcher, WorkerProcess class WatchdogWorkerProcess(WorkerProcess): """Worker that runs the chalice dev server.""" def _start_file_watcher(self, project_dir): # type: (str) -> None restart_callback = WatchdogRestarter(self._restart_event) watcher = WatchdogFileWatcher() watcher.watch_for_file_changes( project_dir, restart_callback) class WatchdogFileWatcher(FileWatcher): def watch_for_file_changes(self, root_dir, callback): # type: (str, Callable[[], None]) -> None observer = watchdog.observers.Observer() observer.schedule(callback, root_dir, recursive=True) observer.start() class WatchdogRestarter(events.FileSystemEventHandler): def __init__(self, restart_event): # type: (threading.Event) -> None # The reason we're using threading self.restart_event = restart_event def on_any_event(self, event): # type: (events.FileSystemEvent) -> None # If we modify a file we'll get a FileModifiedEvent # as well as a DirectoryModifiedEvent. # We only care about reloading is a file is modified. if event.is_directory: return self() def __call__(self): # type: () -> None self.restart_event.set()
5a92b2d340c78f0a58f059543b38efc8cb0e84f6
PocketForecast/AppDelegate.swift
PocketForecast/AppDelegate.swift
//////////////////////////////////////////////////////////////////////////////// // // TYPHOON FRAMEWORK // Copyright 2013, Jasper Blues & Contributors // All Rights Reserved. // // NOTICE: The authors permit you to use, modify, and distribute this file // in accordance with the terms of the license agreement accompanying it. // //////////////////////////////////////////////////////////////////////////////// import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? var cityDao: CityDao? var rootViewController: RootViewController? private func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { ICLoader.setImageName("cloud_icon.png") ICLoader.setLabelFontName(UIFont.applicationFontOfSize(size: 10).fontName) UIApplication.shared.setStatusBarStyle(.lightContent, animated: true) UINavigationBar.appearance().titleTextAttributes = [ NSFontAttributeName : UIFont.applicationFontOfSize(size: 20), NSForegroundColorAttributeName : UIColor.white ] self.window = UIWindow(frame: UIScreen.main.bounds) self.window?.rootViewController = self.rootViewController self.window?.makeKeyAndVisible() let selectedCity : String! = cityDao!.loadSelectedCity() if (selectedCity == nil) { rootViewController?.showCitiesListController() } return true } }
//////////////////////////////////////////////////////////////////////////////// // // TYPHOON FRAMEWORK // Copyright 2013, Jasper Blues & Contributors // All Rights Reserved. // // NOTICE: The authors permit you to use, modify, and distribute this file // in accordance with the terms of the license agreement accompanying it. // //////////////////////////////////////////////////////////////////////////////// import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? var cityDao: CityDao? var rootViewController: RootViewController? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool { ICLoader.setImageName("cloud_icon.png") ICLoader.setLabelFontName(UIFont.applicationFontOfSize(size: 10).fontName) UIApplication.shared.setStatusBarStyle(.lightContent, animated: true) UINavigationBar.appearance().titleTextAttributes = [ NSFontAttributeName : UIFont.applicationFontOfSize(size: 20), NSForegroundColorAttributeName : UIColor.white ] self.window = UIWindow(frame: UIScreen.main.bounds) self.window?.rootViewController = self.rootViewController self.window?.makeKeyAndVisible() let selectedCity : String! = cityDao!.loadSelectedCity() if (selectedCity == nil) { rootViewController?.showCitiesListController() } return true } }
Update application didiFinishLaunching method with Swift 3 syntax
Update application didiFinishLaunching method with Swift 3 syntax
Swift
apache-2.0
appsquickly/Typhoon-Swift-Example,appsquickly/Typhoon-Swift-Example
swift
## Code Before: //////////////////////////////////////////////////////////////////////////////// // // TYPHOON FRAMEWORK // Copyright 2013, Jasper Blues & Contributors // All Rights Reserved. // // NOTICE: The authors permit you to use, modify, and distribute this file // in accordance with the terms of the license agreement accompanying it. // //////////////////////////////////////////////////////////////////////////////// import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? var cityDao: CityDao? var rootViewController: RootViewController? private func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { ICLoader.setImageName("cloud_icon.png") ICLoader.setLabelFontName(UIFont.applicationFontOfSize(size: 10).fontName) UIApplication.shared.setStatusBarStyle(.lightContent, animated: true) UINavigationBar.appearance().titleTextAttributes = [ NSFontAttributeName : UIFont.applicationFontOfSize(size: 20), NSForegroundColorAttributeName : UIColor.white ] self.window = UIWindow(frame: UIScreen.main.bounds) self.window?.rootViewController = self.rootViewController self.window?.makeKeyAndVisible() let selectedCity : String! = cityDao!.loadSelectedCity() if (selectedCity == nil) { rootViewController?.showCitiesListController() } return true } } ## Instruction: Update application didiFinishLaunching method with Swift 3 syntax ## Code After: //////////////////////////////////////////////////////////////////////////////// // // TYPHOON FRAMEWORK // Copyright 2013, Jasper Blues & Contributors // All Rights Reserved. // // NOTICE: The authors permit you to use, modify, and distribute this file // in accordance with the terms of the license agreement accompanying it. // //////////////////////////////////////////////////////////////////////////////// import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? var cityDao: CityDao? var rootViewController: RootViewController? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool { ICLoader.setImageName("cloud_icon.png") ICLoader.setLabelFontName(UIFont.applicationFontOfSize(size: 10).fontName) UIApplication.shared.setStatusBarStyle(.lightContent, animated: true) UINavigationBar.appearance().titleTextAttributes = [ NSFontAttributeName : UIFont.applicationFontOfSize(size: 20), NSForegroundColorAttributeName : UIColor.white ] self.window = UIWindow(frame: UIScreen.main.bounds) self.window?.rootViewController = self.rootViewController self.window?.makeKeyAndVisible() let selectedCity : String! = cityDao!.loadSelectedCity() if (selectedCity == nil) { rootViewController?.showCitiesListController() } return true } }
8e275a22aa419297eee0acc5ef65fc0cce4aa3cb
clients/web/test/spec/swaggerSpec.js
clients/web/test/spec/swaggerSpec.js
function jasmineTests() { var jasmineEnv = jasmine.getEnv(); var consoleReporter = new jasmine.ConsoleReporter(); window.jasmine_phantom_reporter = consoleReporter; jasmineEnv.addReporter(consoleReporter); function waitAndExecute() { if (!jasmineEnv.currentRunner().suites_.length) { window.setTimeout(waitAndExecute, 10); return; } jasmineEnv.execute(); } waitAndExecute(); describe('Test the swagger pages', function () { it('Test swagger', function () { waitsFor(function () { return $('li#resource_system.resource').length > 0; }, 'swagger docs to appear'); runs(function () { $('li#resource_system.resource .heading h2 a').click(); }); waitsFor(function () { return $('#system_getVersion:visible').length > 0; }, 'end points to be visible'); runs(function () { $('#system_getVersion h3 a').click(); }); waitsFor(function () { return $('#system_getVersion .sandbox_header input.submit[name="commit"]:visible').length > 0; }, 'version try out button to be visible'); runs(function () { $('#system_getVersion .sandbox_header input.submit[name="commit"]').click(); }); waitsFor(function () { return $('#system_getVersion .response_body.json').text().indexOf('apiVersion') >= 0; }, 'version information was returned'); }); }); } $(function () { $.getScript('/static/built/testing-no-cover.min.js', jasmineTests); });
function jasmineTests() { var jasmineEnv = jasmine.getEnv(); var consoleReporter = new jasmine.ConsoleReporter(); window.jasmine_phantom_reporter = consoleReporter; jasmineEnv.addReporter(consoleReporter); function waitAndExecute() { if (!jasmineEnv.currentRunner().suites_.length) { window.setTimeout(waitAndExecute, 10); return; } jasmineEnv.execute(); } waitAndExecute(); describe('Test the swagger pages', function () { it('Test swagger', function () { waitsFor(function () { return $('li#resource_system.resource').length > 0; }, 'swagger docs to appear'); runs(function () { $('li#resource_system.resource .heading h2 a').click(); }); waitsFor(function () { return $('#system_system_getVersion:visible').length > 0; }, 'end points to be visible'); runs(function () { $('#system_system_getVersion h3 a').click(); }); waitsFor(function () { return $('#system_system_getVersion .sandbox_header input.submit:visible').length > 0; }, 'version try out button to be visible'); runs(function () { $('#system_system_getVersion .sandbox_header input.submit').click(); }); waitsFor(function () { return $('#system_system_getVersion .response_body.json').text().indexOf('apiVersion') >= 0; }, 'version information was returned'); }); }); } $(function () { $.getScript('/static/built/testing-no-cover.min.js', jasmineTests); });
Update web client swagger test for swagger-ui 2.1.4
Update web client swagger test for swagger-ui 2.1.4
JavaScript
apache-2.0
adsorensen/girder,kotfic/girder,data-exp-lab/girder,jbeezley/girder,Kitware/girder,jbeezley/girder,adsorensen/girder,RafaelPalomar/girder,kotfic/girder,girder/girder,sutartmelson/girder,Xarthisius/girder,sutartmelson/girder,sutartmelson/girder,manthey/girder,data-exp-lab/girder,RafaelPalomar/girder,data-exp-lab/girder,manthey/girder,data-exp-lab/girder,RafaelPalomar/girder,Xarthisius/girder,adsorensen/girder,kotfic/girder,data-exp-lab/girder,adsorensen/girder,RafaelPalomar/girder,RafaelPalomar/girder,girder/girder,sutartmelson/girder,jbeezley/girder,adsorensen/girder,manthey/girder,Xarthisius/girder,kotfic/girder,Kitware/girder,girder/girder,Kitware/girder,Kitware/girder,sutartmelson/girder,Xarthisius/girder,girder/girder,manthey/girder,jbeezley/girder,kotfic/girder,Xarthisius/girder
javascript
## Code Before: function jasmineTests() { var jasmineEnv = jasmine.getEnv(); var consoleReporter = new jasmine.ConsoleReporter(); window.jasmine_phantom_reporter = consoleReporter; jasmineEnv.addReporter(consoleReporter); function waitAndExecute() { if (!jasmineEnv.currentRunner().suites_.length) { window.setTimeout(waitAndExecute, 10); return; } jasmineEnv.execute(); } waitAndExecute(); describe('Test the swagger pages', function () { it('Test swagger', function () { waitsFor(function () { return $('li#resource_system.resource').length > 0; }, 'swagger docs to appear'); runs(function () { $('li#resource_system.resource .heading h2 a').click(); }); waitsFor(function () { return $('#system_getVersion:visible').length > 0; }, 'end points to be visible'); runs(function () { $('#system_getVersion h3 a').click(); }); waitsFor(function () { return $('#system_getVersion .sandbox_header input.submit[name="commit"]:visible').length > 0; }, 'version try out button to be visible'); runs(function () { $('#system_getVersion .sandbox_header input.submit[name="commit"]').click(); }); waitsFor(function () { return $('#system_getVersion .response_body.json').text().indexOf('apiVersion') >= 0; }, 'version information was returned'); }); }); } $(function () { $.getScript('/static/built/testing-no-cover.min.js', jasmineTests); }); ## Instruction: Update web client swagger test for swagger-ui 2.1.4 ## Code After: function jasmineTests() { var jasmineEnv = jasmine.getEnv(); var consoleReporter = new jasmine.ConsoleReporter(); window.jasmine_phantom_reporter = consoleReporter; jasmineEnv.addReporter(consoleReporter); function waitAndExecute() { if (!jasmineEnv.currentRunner().suites_.length) { window.setTimeout(waitAndExecute, 10); return; } jasmineEnv.execute(); } waitAndExecute(); describe('Test the swagger pages', function () { it('Test swagger', function () { waitsFor(function () { return $('li#resource_system.resource').length > 0; }, 'swagger docs to appear'); runs(function () { $('li#resource_system.resource .heading h2 a').click(); }); waitsFor(function () { return $('#system_system_getVersion:visible').length > 0; }, 'end points to be visible'); runs(function () { $('#system_system_getVersion h3 a').click(); }); waitsFor(function () { return $('#system_system_getVersion .sandbox_header input.submit:visible').length > 0; }, 'version try out button to be visible'); runs(function () { $('#system_system_getVersion .sandbox_header input.submit').click(); }); waitsFor(function () { return $('#system_system_getVersion .response_body.json').text().indexOf('apiVersion') >= 0; }, 'version information was returned'); }); }); } $(function () { $.getScript('/static/built/testing-no-cover.min.js', jasmineTests); });
6bdc335ebb8ed009cbc926e681ee6be8f475f323
reviewboard/reviews/features.py
reviewboard/reviews/features.py
"""Feature definitions for reviews.""" from __future__ import unicode_literals from django.utils.translation import ugettext_lazy as _ from djblets.features import Feature, FeatureLevel class GeneralCommentsFeature(Feature): """A feature for general comments. General comments allow comments to be created directly on a review request without accompanying file attachment or diff. These can be used to raise issues with the review request itself, such as its summary or description, or general implementation issues. """ feature_id = 'reviews.general_comments' name = _('General Comments') level = FeatureLevel.STABLE summary = _('Allow comments on review requests without an associated file ' 'attachment or diff.') class StatusUpdatesFeature(Feature): """A feature for status updates. A status update is a way for third-party tools to provide feedback on a review request. In the past, this was done just as a normal review. Status updates allow those tools (via some integration like Review Bot) to mark their state (such as pending, success, failure, or error) and then associate that with a review. """ feature_id = 'reviews.status_updates' name = _('Status Updates') summary = _('A way for external tools to do checks on a review request ' 'and report the results of those checks.') general_comments_feature = GeneralCommentsFeature() status_updates_feature = StatusUpdatesFeature()
"""Feature definitions for reviews.""" from __future__ import unicode_literals from django.utils.translation import ugettext_lazy as _ from djblets.features import Feature, FeatureLevel class GeneralCommentsFeature(Feature): """A feature for general comments. General comments allow comments to be created directly on a review request without accompanying file attachment or diff. These can be used to raise issues with the review request itself, such as its summary or description, or general implementation issues. """ feature_id = 'reviews.general_comments' name = _('General Comments') level = FeatureLevel.STABLE summary = _('Allow comments on review requests without an associated file ' 'attachment or diff.') class StatusUpdatesFeature(Feature): """A feature for status updates. A status update is a way for third-party tools to provide feedback on a review request. In the past, this was done just as a normal review. Status updates allow those tools (via some integration like Review Bot) to mark their state (such as pending, success, failure, or error) and then associate that with a review. """ feature_id = 'reviews.status_updates' name = _('Status Updates') level = FeatureLevel.STABLE summary = _('A way for external tools to do checks on a review request ' 'and report the results of those checks.') general_comments_feature = GeneralCommentsFeature() status_updates_feature = StatusUpdatesFeature()
Mark status updates as stable.
Mark status updates as stable. This allows people to actually use the feature without turning it on in their `settings_local.py`. Reviewed at https://reviews.reviewboard.org/r/8569/
Python
mit
sgallagher/reviewboard,brennie/reviewboard,chipx86/reviewboard,chipx86/reviewboard,chipx86/reviewboard,davidt/reviewboard,reviewboard/reviewboard,davidt/reviewboard,reviewboard/reviewboard,chipx86/reviewboard,brennie/reviewboard,sgallagher/reviewboard,davidt/reviewboard,sgallagher/reviewboard,davidt/reviewboard,brennie/reviewboard,sgallagher/reviewboard,reviewboard/reviewboard,brennie/reviewboard,reviewboard/reviewboard
python
## Code Before: """Feature definitions for reviews.""" from __future__ import unicode_literals from django.utils.translation import ugettext_lazy as _ from djblets.features import Feature, FeatureLevel class GeneralCommentsFeature(Feature): """A feature for general comments. General comments allow comments to be created directly on a review request without accompanying file attachment or diff. These can be used to raise issues with the review request itself, such as its summary or description, or general implementation issues. """ feature_id = 'reviews.general_comments' name = _('General Comments') level = FeatureLevel.STABLE summary = _('Allow comments on review requests without an associated file ' 'attachment or diff.') class StatusUpdatesFeature(Feature): """A feature for status updates. A status update is a way for third-party tools to provide feedback on a review request. In the past, this was done just as a normal review. Status updates allow those tools (via some integration like Review Bot) to mark their state (such as pending, success, failure, or error) and then associate that with a review. """ feature_id = 'reviews.status_updates' name = _('Status Updates') summary = _('A way for external tools to do checks on a review request ' 'and report the results of those checks.') general_comments_feature = GeneralCommentsFeature() status_updates_feature = StatusUpdatesFeature() ## Instruction: Mark status updates as stable. This allows people to actually use the feature without turning it on in their `settings_local.py`. Reviewed at https://reviews.reviewboard.org/r/8569/ ## Code After: """Feature definitions for reviews.""" from __future__ import unicode_literals from django.utils.translation import ugettext_lazy as _ from djblets.features import Feature, FeatureLevel class GeneralCommentsFeature(Feature): """A feature for general comments. General comments allow comments to be created directly on a review request without accompanying file attachment or diff. These can be used to raise issues with the review request itself, such as its summary or description, or general implementation issues. """ feature_id = 'reviews.general_comments' name = _('General Comments') level = FeatureLevel.STABLE summary = _('Allow comments on review requests without an associated file ' 'attachment or diff.') class StatusUpdatesFeature(Feature): """A feature for status updates. A status update is a way for third-party tools to provide feedback on a review request. In the past, this was done just as a normal review. Status updates allow those tools (via some integration like Review Bot) to mark their state (such as pending, success, failure, or error) and then associate that with a review. """ feature_id = 'reviews.status_updates' name = _('Status Updates') level = FeatureLevel.STABLE summary = _('A way for external tools to do checks on a review request ' 'and report the results of those checks.') general_comments_feature = GeneralCommentsFeature() status_updates_feature = StatusUpdatesFeature()
7da7354668187167ccc6143ee0f469158c858ed3
lib/economic/proxies/actions/creditor_contact_proxy/find_by_name.rb
lib/economic/proxies/actions/creditor_contact_proxy/find_by_name.rb
module Economic module Proxies module Actions module CreditorContactProxy class FindByName attr_reader :name def initialize(caller, name) @caller = caller @name = name end def call # Get a list of CreditorContactHandles from e-conomic response = request('FindByName', { 'name' => name }) # Make sure we always have an array of handles even if the result only contains one handles = [response[:creditor_contact_handle]].flatten.reject(&:blank?) # Create partial CreditorContact entities contacts = handles.collect do |handle| creditor_contact = build creditor_contact.partial = true creditor_contact.persisted = true creditor_contact.handle = handle creditor_contact.id = handle[:id] creditor_contact.number = handle[:number] creditor_contact end if owner.is_a?(Creditor) # Scope to the owner contacts.select do |creditor_contact| creditor_contact.get_data creditor_contact.creditor.handle == owner.handle end else contacts end end private def build(*options) @caller.build(options) end def owner @caller.owner end def request(action, data) @caller.request(action, data) end end end end end end
module Economic module Proxies module Actions module CreditorContactProxy class FindByName attr_reader :name def initialize(caller, name) @caller = caller @name = name end def call # Get a list of CreditorContactHandles from e-conomic handles = [response[:creditor_contact_handle]].flatten.reject(&:blank?) contacts = build_partial_contact_entities(handles) scope_to_owner(contacts) end private def build(*options) @caller.build(options) end def build_partial_contact_entities(handles) handles.collect do |handle| creditor_contact = build creditor_contact.partial = true creditor_contact.persisted = true creditor_contact.handle = handle creditor_contact.id = handle[:id] creditor_contact.number = handle[:number] creditor_contact end end def owner @caller.owner end def request(action, data) @caller.request(action, data) end def response request('FindByName', {'name' => name}) end def scope_to_owner(contacts) if owner.is_a?(Creditor) # Scope to the owner contacts.select do |creditor_contact| creditor_contact.get_data creditor_contact.creditor.handle == owner.handle end else contacts end end end end end end end
Clean up FindByName a bit
Clean up FindByName a bit
Ruby
mit
anderslime/rconomic,kongens-net/rconomic,substancelab/rconomic,lokalebasen/rconomic
ruby
## Code Before: module Economic module Proxies module Actions module CreditorContactProxy class FindByName attr_reader :name def initialize(caller, name) @caller = caller @name = name end def call # Get a list of CreditorContactHandles from e-conomic response = request('FindByName', { 'name' => name }) # Make sure we always have an array of handles even if the result only contains one handles = [response[:creditor_contact_handle]].flatten.reject(&:blank?) # Create partial CreditorContact entities contacts = handles.collect do |handle| creditor_contact = build creditor_contact.partial = true creditor_contact.persisted = true creditor_contact.handle = handle creditor_contact.id = handle[:id] creditor_contact.number = handle[:number] creditor_contact end if owner.is_a?(Creditor) # Scope to the owner contacts.select do |creditor_contact| creditor_contact.get_data creditor_contact.creditor.handle == owner.handle end else contacts end end private def build(*options) @caller.build(options) end def owner @caller.owner end def request(action, data) @caller.request(action, data) end end end end end end ## Instruction: Clean up FindByName a bit ## Code After: module Economic module Proxies module Actions module CreditorContactProxy class FindByName attr_reader :name def initialize(caller, name) @caller = caller @name = name end def call # Get a list of CreditorContactHandles from e-conomic handles = [response[:creditor_contact_handle]].flatten.reject(&:blank?) contacts = build_partial_contact_entities(handles) scope_to_owner(contacts) end private def build(*options) @caller.build(options) end def build_partial_contact_entities(handles) handles.collect do |handle| creditor_contact = build creditor_contact.partial = true creditor_contact.persisted = true creditor_contact.handle = handle creditor_contact.id = handle[:id] creditor_contact.number = handle[:number] creditor_contact end end def owner @caller.owner end def request(action, data) @caller.request(action, data) end def response request('FindByName', {'name' => name}) end def scope_to_owner(contacts) if owner.is_a?(Creditor) # Scope to the owner contacts.select do |creditor_contact| creditor_contact.get_data creditor_contact.creditor.handle == owner.handle end else contacts end end end end end end end
0f08bdd49437340fd087c753be383f33e70f810a
public/views/content/directives/contentEditRouteModal.tpl.html
public/views/content/directives/contentEditRouteModal.tpl.html
<div class="modal" tabindex="-1" role="dialog"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header" ng-show="title"> <button type="button" class="close" ng-click="vm.editRouteModal.closeModal()">&times;</button> <h4 class="modal-title" translate="{{title}}"></h4> </div> <div class="modal-body"> <form name="contentRouteForm" novalidate> <div class="row"> <div class="col-lg-9"> <!-- Title Form input --> <div class="form-group"> <label for="title">{{ 'PERMALINK' | translate }} <strong class="text-danger">*</strong></label> <input id="title" name="title" type="text" class="form-control" required ng-model="vm.contentRoute"> </div> </div> </div> </form> </div> <div class="modal-footer"> <button type="button" class="btn btn-success" ng-click="vm.editRouteModal.closeModal()"> {{ (vm.hideSubmitButton) ? 'OK' : 'CANCEL' | translate }} </button> <button type="button" class="btn btn-primary" ng-click="vm.editRouteModal.saveContentRoute()"> <i class="glyphicon glyphicon-ok-circle"></i> {{ 'SAVE' | translate }} </button> </div> </div> </div> </div>
<div class="modal" tabindex="-1" role="dialog"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header" ng-show="title"> <button type="button" class="close" ng-click="vm.editRouteModal.closeModal()">&times;</button> <h4 class="modal-title" translate="{{title}}"></h4> </div> <div class="modal-body"> <form name="contentRouteForm" novalidate> <div class="row"> <div class="col-lg-9"> <!-- Title Form input --> <div class="form-group"> <label for="title">{{ 'PERMALINK' | translate }} <strong class="text-danger">*</strong></label> <input id="title" name="title" type="text" class="form-control" required ng-model="vm.contentRoute"> </div> </div> </div> </form> </div> <div class="modal-footer"> <button type="button" class="btn btn-success" ng-click="vm.editRouteModal.closeModal()"> {{ (vm.hideSubmitButton) ? 'OK' : 'CANCEL' | translate }} </button> <button type="button" class="btn btn-primary" ng-disabled="contentRouteForm.$invalid" ng-click="vm.editRouteModal.saveContentRoute()"> <i class="glyphicon glyphicon-ok-circle"></i> {{ 'SAVE' | translate }} </button> </div> </div> </div> </div>
Edit route modal disable button if form is not valid
Edit route modal disable button if form is not valid
HTML
mit
GrupaZero/admin,GrupaZero/admin,GrupaZero/admin
html
## Code Before: <div class="modal" tabindex="-1" role="dialog"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header" ng-show="title"> <button type="button" class="close" ng-click="vm.editRouteModal.closeModal()">&times;</button> <h4 class="modal-title" translate="{{title}}"></h4> </div> <div class="modal-body"> <form name="contentRouteForm" novalidate> <div class="row"> <div class="col-lg-9"> <!-- Title Form input --> <div class="form-group"> <label for="title">{{ 'PERMALINK' | translate }} <strong class="text-danger">*</strong></label> <input id="title" name="title" type="text" class="form-control" required ng-model="vm.contentRoute"> </div> </div> </div> </form> </div> <div class="modal-footer"> <button type="button" class="btn btn-success" ng-click="vm.editRouteModal.closeModal()"> {{ (vm.hideSubmitButton) ? 'OK' : 'CANCEL' | translate }} </button> <button type="button" class="btn btn-primary" ng-click="vm.editRouteModal.saveContentRoute()"> <i class="glyphicon glyphicon-ok-circle"></i> {{ 'SAVE' | translate }} </button> </div> </div> </div> </div> ## Instruction: Edit route modal disable button if form is not valid ## Code After: <div class="modal" tabindex="-1" role="dialog"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header" ng-show="title"> <button type="button" class="close" ng-click="vm.editRouteModal.closeModal()">&times;</button> <h4 class="modal-title" translate="{{title}}"></h4> </div> <div class="modal-body"> <form name="contentRouteForm" novalidate> <div class="row"> <div class="col-lg-9"> <!-- Title Form input --> <div class="form-group"> <label for="title">{{ 'PERMALINK' | translate }} <strong class="text-danger">*</strong></label> <input id="title" name="title" type="text" class="form-control" required ng-model="vm.contentRoute"> </div> </div> </div> </form> </div> <div class="modal-footer"> <button type="button" class="btn btn-success" ng-click="vm.editRouteModal.closeModal()"> {{ (vm.hideSubmitButton) ? 'OK' : 'CANCEL' | translate }} </button> <button type="button" class="btn btn-primary" ng-disabled="contentRouteForm.$invalid" ng-click="vm.editRouteModal.saveContentRoute()"> <i class="glyphicon glyphicon-ok-circle"></i> {{ 'SAVE' | translate }} </button> </div> </div> </div> </div>
44728ce3574b7459e2c9304383fe2c1dc2dc0b8b
Source/Model/Connecting/Socket/Tcp/Method/MConnectingSocketTcpMethodTypeFactory.swift
Source/Model/Connecting/Socket/Tcp/Method/MConnectingSocketTcpMethodTypeFactory.swift
import Foundation extension MConnectingSocketTcpMethodType { private static func factoryMethod( type:MConnectingSocketTcpMethodType) -> MConnectingSocketTcpMethodProtocol.Type { switch type { case MConnectingSocketTcpMethodType.showpin: return MConnectingSocketTcpMethodShowpin.self case MConnectingSocketTcpMethodType.register: return MConnectingSocketTcpMethodRegister.self case MConnectingSocketTcpMethodType.registerResult: return MConnectingSocketTcpMethodRegisterResult.self case MConnectingSocketTcpMethodType.registerCancel: return MConnectingSocketTcpMethodRegisterCancel.self case MConnectingSocketTcpMethodType.connect: return MConnectingSocketTcpMethodConnect.self case MConnectingSocketTcpMethodType.standby: return MConnectingSocketTcpMethodStandby.self } } //MARK: internal static func factoryMethod( name:String, received:String) -> MConnectingSocketTcpMethodProtocol? { guard let type:MConnectingSocketTcpMethodType = MConnectingSocketTcpMethodType( rawValue:name) else { return nil } let methodType:MConnectingSocketTcpMethodProtocol.Type = factoryMethod( type:type) let method:MConnectingSocketTcpMethodProtocol = methodType.init( received:received) return method } }
import Foundation extension MConnectingSocketTcpMethodType { private static let kMethodMap:[ MConnectingSocketTcpMethodType: MConnectingSocketTcpMethodProtocol.Type] = [ MConnectingSocketTcpMethodType.showpin: MConnectingSocketTcpMethodShowpin.self, MConnectingSocketTcpMethodType.register: MConnectingSocketTcpMethodRegister.self, MConnectingSocketTcpMethodType.registerResult: MConnectingSocketTcpMethodRegisterResult.self, MConnectingSocketTcpMethodType.registerCancel: MConnectingSocketTcpMethodRegisterCancel.self, MConnectingSocketTcpMethodType.connect: MConnectingSocketTcpMethodConnect.self, MConnectingSocketTcpMethodType.standby: MConnectingSocketTcpMethodStandby.self] //MARK: internal static func factoryMethod( name:String, received:String) -> MConnectingSocketTcpMethodProtocol? { guard let type:MConnectingSocketTcpMethodType = MConnectingSocketTcpMethodType( rawValue:name), let methodType:MConnectingSocketTcpMethodProtocol.Type = kMethodMap[ type] else { return nil } let method:MConnectingSocketTcpMethodProtocol = methodType.init( received:received) return method } }
Replace switch with method map
Replace switch with method map
Swift
mit
devpunk/velvet_room,devpunk/velvet_room
swift
## Code Before: import Foundation extension MConnectingSocketTcpMethodType { private static func factoryMethod( type:MConnectingSocketTcpMethodType) -> MConnectingSocketTcpMethodProtocol.Type { switch type { case MConnectingSocketTcpMethodType.showpin: return MConnectingSocketTcpMethodShowpin.self case MConnectingSocketTcpMethodType.register: return MConnectingSocketTcpMethodRegister.self case MConnectingSocketTcpMethodType.registerResult: return MConnectingSocketTcpMethodRegisterResult.self case MConnectingSocketTcpMethodType.registerCancel: return MConnectingSocketTcpMethodRegisterCancel.self case MConnectingSocketTcpMethodType.connect: return MConnectingSocketTcpMethodConnect.self case MConnectingSocketTcpMethodType.standby: return MConnectingSocketTcpMethodStandby.self } } //MARK: internal static func factoryMethod( name:String, received:String) -> MConnectingSocketTcpMethodProtocol? { guard let type:MConnectingSocketTcpMethodType = MConnectingSocketTcpMethodType( rawValue:name) else { return nil } let methodType:MConnectingSocketTcpMethodProtocol.Type = factoryMethod( type:type) let method:MConnectingSocketTcpMethodProtocol = methodType.init( received:received) return method } } ## Instruction: Replace switch with method map ## Code After: import Foundation extension MConnectingSocketTcpMethodType { private static let kMethodMap:[ MConnectingSocketTcpMethodType: MConnectingSocketTcpMethodProtocol.Type] = [ MConnectingSocketTcpMethodType.showpin: MConnectingSocketTcpMethodShowpin.self, MConnectingSocketTcpMethodType.register: MConnectingSocketTcpMethodRegister.self, MConnectingSocketTcpMethodType.registerResult: MConnectingSocketTcpMethodRegisterResult.self, MConnectingSocketTcpMethodType.registerCancel: MConnectingSocketTcpMethodRegisterCancel.self, MConnectingSocketTcpMethodType.connect: MConnectingSocketTcpMethodConnect.self, MConnectingSocketTcpMethodType.standby: MConnectingSocketTcpMethodStandby.self] //MARK: internal static func factoryMethod( name:String, received:String) -> MConnectingSocketTcpMethodProtocol? { guard let type:MConnectingSocketTcpMethodType = MConnectingSocketTcpMethodType( rawValue:name), let methodType:MConnectingSocketTcpMethodProtocol.Type = kMethodMap[ type] else { return nil } let method:MConnectingSocketTcpMethodProtocol = methodType.init( received:received) return method } }
aded5c6d0c859d34cd5af3cf4d15f28a924b6072
resources/frontend/app/pods/tournament/team/route.js
resources/frontend/app/pods/tournament/team/route.js
import Ember from 'ember'; const { Route, RSVP } = Ember; export default Route.extend({ deactivate() { this.store.peekAll('team-member').forEach((team) => { if (team.get('isNew')) { this.store.deleteRecord(team); } }); }, actions: { assignMember(member) { const flashMessages = Ember.get(this, 'flashMessages'); return member.save().then(() => { this.currentModel.get('teamMembers').addObject(member); flashMessages.success(member.get('name')+' has been assigned to the team'); }).catch(() => { member.rollback(); flashMessages.danger('Unable to assign member to the team'); }); }, removeMember(member) { const flashMessages = Ember.get(this, 'flashMessages'); return member.destroyRecord().then(() => { flashMessages.success(member.get('name')+' has been removed from the team'); }).catch(() => { member.rollback(); flashMessages.danger('Unable to remove member from the team'); }); } }, model: function (params) { const store = this.store; const teamId = params.id; const tournament = this.modelFor('tournament'); return RSVP.hash({ team: store.find('team', teamId), matches: store.query('match', {tournamentId: tournament.get('id'), teamId}), teamMembers: store.query('team-member', {teamId}) }).then((hash) => { hash.team.set('teamMembers', hash.teamMembers); return hash; }); } });
import Ember from 'ember'; const { Route, RSVP } = Ember; export default Route.extend({ deactivate() { this.store.peekAll('team-member').forEach((team) => { if (team.get('isNew')) { this.store.deleteRecord(team); } }); }, actions: { assignMember(member) { const flashMessages = Ember.get(this, 'flashMessages'); return member.save().then(() => { flashMessages.success(member.get('name')+' has been assigned to the team'); }).catch(() => { member.rollback(); flashMessages.danger('Unable to assign member to the team'); }); }, removeMember(member) { const flashMessages = Ember.get(this, 'flashMessages'); return member.destroyRecord().then(() => { flashMessages.success(member.get('name')+' has been removed from the team'); }).catch(() => { member.rollback(); flashMessages.danger('Unable to remove member from the team'); }); } }, model: function (params) { const store = this.store; const teamId = params.id; const tournament = this.modelFor('tournament'); return RSVP.hash({ team: store.find('team', teamId), matches: store.query('match', {tournamentId: tournament.get('id'), teamId}), teamMembers: store.query('team-member', {teamId}) }).then((hash) => { hash.team.set('teamMembers', hash.teamMembers); return hash; }); } });
Fix assign member to the team
Fix assign member to the team
JavaScript
mit
nixsolutions/ggf,nixsolutions/ggf,nixsolutions/ggf,nixsolutions/ggf
javascript
## Code Before: import Ember from 'ember'; const { Route, RSVP } = Ember; export default Route.extend({ deactivate() { this.store.peekAll('team-member').forEach((team) => { if (team.get('isNew')) { this.store.deleteRecord(team); } }); }, actions: { assignMember(member) { const flashMessages = Ember.get(this, 'flashMessages'); return member.save().then(() => { this.currentModel.get('teamMembers').addObject(member); flashMessages.success(member.get('name')+' has been assigned to the team'); }).catch(() => { member.rollback(); flashMessages.danger('Unable to assign member to the team'); }); }, removeMember(member) { const flashMessages = Ember.get(this, 'flashMessages'); return member.destroyRecord().then(() => { flashMessages.success(member.get('name')+' has been removed from the team'); }).catch(() => { member.rollback(); flashMessages.danger('Unable to remove member from the team'); }); } }, model: function (params) { const store = this.store; const teamId = params.id; const tournament = this.modelFor('tournament'); return RSVP.hash({ team: store.find('team', teamId), matches: store.query('match', {tournamentId: tournament.get('id'), teamId}), teamMembers: store.query('team-member', {teamId}) }).then((hash) => { hash.team.set('teamMembers', hash.teamMembers); return hash; }); } }); ## Instruction: Fix assign member to the team ## Code After: import Ember from 'ember'; const { Route, RSVP } = Ember; export default Route.extend({ deactivate() { this.store.peekAll('team-member').forEach((team) => { if (team.get('isNew')) { this.store.deleteRecord(team); } }); }, actions: { assignMember(member) { const flashMessages = Ember.get(this, 'flashMessages'); return member.save().then(() => { flashMessages.success(member.get('name')+' has been assigned to the team'); }).catch(() => { member.rollback(); flashMessages.danger('Unable to assign member to the team'); }); }, removeMember(member) { const flashMessages = Ember.get(this, 'flashMessages'); return member.destroyRecord().then(() => { flashMessages.success(member.get('name')+' has been removed from the team'); }).catch(() => { member.rollback(); flashMessages.danger('Unable to remove member from the team'); }); } }, model: function (params) { const store = this.store; const teamId = params.id; const tournament = this.modelFor('tournament'); return RSVP.hash({ team: store.find('team', teamId), matches: store.query('match', {tournamentId: tournament.get('id'), teamId}), teamMembers: store.query('team-member', {teamId}) }).then((hash) => { hash.team.set('teamMembers', hash.teamMembers); return hash; }); } });
66fed655a9b41f6e270acec19fe66f787049063b
src/atom10/feed.php
src/atom10/feed.php
<?php namespace ComplexPie\Atom10; class Feed { private static $aliases = array( 'description' => 'subtitle', 'tagline' => 'subtitle', 'copyright' => 'rights', ); private static $elements = array( 'title' => array( 'element' => 'atom:title', 'type' => 'atomTextConstruct', 'single' => true ), 'subtitle' => array( 'element' => 'atom:subtitle', 'type' => 'atomTextConstruct', 'single' => true ), 'rights' => array( 'element' => 'atom:rights', 'type' => 'atomTextConstruct', 'single' => true ), ); public function __invoke($dom, $name) { if (isset(self::$elements[$name])) { return $this->elements_table($dom, $name); } elseif (isset(self::$aliases[$name])) { return $this->__invoke($dom, self::$aliases[$name]); } } private function elements_table($dom, $name) { $element = self::$elements[$name]; if ($return = \ComplexPie\Misc::get_descendant($dom, $element['element'], array('atom' => XMLNS), $element['single'])) { switch ($element['type']) { case 'atomTextConstruct': return Content::from_text_construct($return); default: throw new \Exception('Um, this shouldn\'t happen'); } } } }
<?php namespace ComplexPie\Atom10; class Feed { private static $aliases = array( 'description' => 'subtitle', 'tagline' => 'subtitle', 'copyright' => 'rights', ); private static $elements = array( 'title' => array( 'element' => 'atom:title', 'contentConstructor' => 'ComplexPie\\Atom10\\Content::from_text_construct', 'single' => true ), 'subtitle' => array( 'element' => 'atom:subtitle', 'contentConstructor' => 'ComplexPie\\Atom10\\Content::from_text_construct', 'single' => true ), 'rights' => array( 'element' => 'atom:rights', 'contentConstructor' => 'ComplexPie\\Atom10\\Content::from_text_construct', 'single' => true ), ); public function __invoke($dom, $name) { if (isset(self::$elements[$name])) { return $this->elements_table($dom, $name); } elseif (isset(self::$aliases[$name])) { return $this->__invoke($dom, self::$aliases[$name]); } } private function elements_table($dom, $name) { $element = self::$elements[$name]; if ($return = \ComplexPie\Misc::get_descendant($dom, $element['element'], array('atom' => XMLNS), $element['single'])) { return call_user_func($element['contentConstructor'], $return); } } }
Make this a bit cleaner.
Make this a bit cleaner.
PHP
bsd-3-clause
gsnedders/complexpie
php
## Code Before: <?php namespace ComplexPie\Atom10; class Feed { private static $aliases = array( 'description' => 'subtitle', 'tagline' => 'subtitle', 'copyright' => 'rights', ); private static $elements = array( 'title' => array( 'element' => 'atom:title', 'type' => 'atomTextConstruct', 'single' => true ), 'subtitle' => array( 'element' => 'atom:subtitle', 'type' => 'atomTextConstruct', 'single' => true ), 'rights' => array( 'element' => 'atom:rights', 'type' => 'atomTextConstruct', 'single' => true ), ); public function __invoke($dom, $name) { if (isset(self::$elements[$name])) { return $this->elements_table($dom, $name); } elseif (isset(self::$aliases[$name])) { return $this->__invoke($dom, self::$aliases[$name]); } } private function elements_table($dom, $name) { $element = self::$elements[$name]; if ($return = \ComplexPie\Misc::get_descendant($dom, $element['element'], array('atom' => XMLNS), $element['single'])) { switch ($element['type']) { case 'atomTextConstruct': return Content::from_text_construct($return); default: throw new \Exception('Um, this shouldn\'t happen'); } } } } ## Instruction: Make this a bit cleaner. ## Code After: <?php namespace ComplexPie\Atom10; class Feed { private static $aliases = array( 'description' => 'subtitle', 'tagline' => 'subtitle', 'copyright' => 'rights', ); private static $elements = array( 'title' => array( 'element' => 'atom:title', 'contentConstructor' => 'ComplexPie\\Atom10\\Content::from_text_construct', 'single' => true ), 'subtitle' => array( 'element' => 'atom:subtitle', 'contentConstructor' => 'ComplexPie\\Atom10\\Content::from_text_construct', 'single' => true ), 'rights' => array( 'element' => 'atom:rights', 'contentConstructor' => 'ComplexPie\\Atom10\\Content::from_text_construct', 'single' => true ), ); public function __invoke($dom, $name) { if (isset(self::$elements[$name])) { return $this->elements_table($dom, $name); } elseif (isset(self::$aliases[$name])) { return $this->__invoke($dom, self::$aliases[$name]); } } private function elements_table($dom, $name) { $element = self::$elements[$name]; if ($return = \ComplexPie\Misc::get_descendant($dom, $element['element'], array('atom' => XMLNS), $element['single'])) { return call_user_func($element['contentConstructor'], $return); } } }
9a733935a16bf898dcb785316e3a1fc98ac91226
package/src/frontend/media/createMediaPlayer.js
package/src/frontend/media/createMediaPlayer.js
import {browser} from '../browser'; import {VideoPlayer} from '../VideoPlayer'; export const createMediaPlayer = function (options) { options.tagName = options.tagName || 'video'; let isAudio = options.tagName == 'audio'; let playsInline = options.playsInline; let mediaElementTemplate = document.createElement(options.tagName); mediaElementTemplate.setAttribute('id', 'pageflow_media_element_'+options.playerId); mediaElementTemplate.setAttribute('crossorigin', 'anonymous'); const player = new VideoPlayer(mediaElementTemplate, { controlBar: false, loadingSpinner: false, bigPlayButton: false, errorDisplay: false, textTrackSettings: false, poster: options.poster, loop: options.loop, controls: options.controls, html5: { nativeCaptions: !isAudio && browser.has('iphone platform') }, bufferUnderrunWaiting: true, useSlimPlayerControlsDuringPhonePlayback: !playsInline && !isAudio, fullscreenDuringPhonePlayback: !playsInline && !isAudio, fallbackToMutedAutoplay: !isAudio, volumeFading: true, //should be turned on later hooks: undefined, mediaEvents: true, context: options.mediaContext }); if (playsInline) { player.playsinline(true); } player.textTrackSettings = { getValues() { return {}; } }; player.playOrPlayOnLoad = function () { if (this.readyState() > 0) { player.play(); } else { player.on('loadedmetadata', player.play); } }; player.addClass('video-js'); player.addClass('player'); return player; };
import {browser} from '../browser'; import {VideoPlayer} from '../VideoPlayer'; export const createMediaPlayer = function (options) { options.tagName = options.tagName || 'video'; let isAudio = options.tagName == 'audio'; let playsInline = options.playsInline; let mediaElementTemplate = document.createElement(options.tagName); mediaElementTemplate.setAttribute('id', 'pageflow_media_element_'+options.playerId); mediaElementTemplate.setAttribute('crossorigin', 'anonymous'); const player = new VideoPlayer(mediaElementTemplate, { controlBar: false, loadingSpinner: false, bigPlayButton: false, errorDisplay: false, textTrackSettings: false, poster: options.poster, loop: options.loop, controls: options.controls, html5: { nativeCaptions: !isAudio && browser.has('iphone platform') }, bufferUnderrunWaiting: true, fallbackToMutedAutoplay: !isAudio, volumeFading: true, //should be turned on later hooks: undefined, mediaEvents: true, context: options.mediaContext }); if (playsInline) { player.playsinline(true); } player.textTrackSettings = { getValues() { return {}; } }; player.playOrPlayOnLoad = function () { if (this.readyState() > 0) { player.play(); } else { player.on('loadedmetadata', player.play); } }; player.addClass('video-js'); player.addClass('player'); return player; };
Remove paged specific options from scrolled media player
Remove paged specific options from scrolled media player * `fullscreenDuringPhonePlayback` is unused legacy. * `useSlimPlayerControlsDuringPhonePlayback` refers to paged widget types.
JavaScript
mit
tf/pageflow,codevise/pageflow,codevise/pageflow,codevise/pageflow,tf/pageflow,tf/pageflow,codevise/pageflow,tf/pageflow
javascript
## Code Before: import {browser} from '../browser'; import {VideoPlayer} from '../VideoPlayer'; export const createMediaPlayer = function (options) { options.tagName = options.tagName || 'video'; let isAudio = options.tagName == 'audio'; let playsInline = options.playsInline; let mediaElementTemplate = document.createElement(options.tagName); mediaElementTemplate.setAttribute('id', 'pageflow_media_element_'+options.playerId); mediaElementTemplate.setAttribute('crossorigin', 'anonymous'); const player = new VideoPlayer(mediaElementTemplate, { controlBar: false, loadingSpinner: false, bigPlayButton: false, errorDisplay: false, textTrackSettings: false, poster: options.poster, loop: options.loop, controls: options.controls, html5: { nativeCaptions: !isAudio && browser.has('iphone platform') }, bufferUnderrunWaiting: true, useSlimPlayerControlsDuringPhonePlayback: !playsInline && !isAudio, fullscreenDuringPhonePlayback: !playsInline && !isAudio, fallbackToMutedAutoplay: !isAudio, volumeFading: true, //should be turned on later hooks: undefined, mediaEvents: true, context: options.mediaContext }); if (playsInline) { player.playsinline(true); } player.textTrackSettings = { getValues() { return {}; } }; player.playOrPlayOnLoad = function () { if (this.readyState() > 0) { player.play(); } else { player.on('loadedmetadata', player.play); } }; player.addClass('video-js'); player.addClass('player'); return player; }; ## Instruction: Remove paged specific options from scrolled media player * `fullscreenDuringPhonePlayback` is unused legacy. * `useSlimPlayerControlsDuringPhonePlayback` refers to paged widget types. ## Code After: import {browser} from '../browser'; import {VideoPlayer} from '../VideoPlayer'; export const createMediaPlayer = function (options) { options.tagName = options.tagName || 'video'; let isAudio = options.tagName == 'audio'; let playsInline = options.playsInline; let mediaElementTemplate = document.createElement(options.tagName); mediaElementTemplate.setAttribute('id', 'pageflow_media_element_'+options.playerId); mediaElementTemplate.setAttribute('crossorigin', 'anonymous'); const player = new VideoPlayer(mediaElementTemplate, { controlBar: false, loadingSpinner: false, bigPlayButton: false, errorDisplay: false, textTrackSettings: false, poster: options.poster, loop: options.loop, controls: options.controls, html5: { nativeCaptions: !isAudio && browser.has('iphone platform') }, bufferUnderrunWaiting: true, fallbackToMutedAutoplay: !isAudio, volumeFading: true, //should be turned on later hooks: undefined, mediaEvents: true, context: options.mediaContext }); if (playsInline) { player.playsinline(true); } player.textTrackSettings = { getValues() { return {}; } }; player.playOrPlayOnLoad = function () { if (this.readyState() > 0) { player.play(); } else { player.on('loadedmetadata', player.play); } }; player.addClass('video-js'); player.addClass('player'); return player; };
4233dd881c2166a89712d6265c412d205ae6e544
src/renderware/gzip_renderware.js
src/renderware/gzip_renderware.js
module.exports = (function() { "use strict"; const Nodal = require('nodal'); const zlib = require('zlib'); class GzipMiddleware extends Nodal.Middleware { exec(controller, data, callback) { let contentType = controller.getHeader('Content-Type', '').split(';')[0]; let acceptEncoding = controller._request.headers['accept-encoding'] || ''; let canCompress = !!{ 'text/plain': 1, 'text/html': 1, 'text/xml': 1, 'text/json': 1, 'text/javascript': 1, 'application/json': 1, 'application/xml': 1, 'application/javascript': 1, 'application/octet-stream': 1 }[contentType]; if (canCompress) { if (acceptEncoding.match(/\bgzip\b/)) { zlib.gzip(data, function(err, result) { if (!err) { controller.setHeader('Content-Encoding', 'gzip'); callback(null, result); return; } callback(null, data); }); return true; } else if(acceptEncoding.match(/\bdeflate\b/)) { zlib.deflate(data, function(err, result) { if (!err) { controller.setHeader('Content-Encoding', 'deflate'); callback(null, result); return; } callback(null, data); }); return true; } } callback(null, data); return false; } } return GzipMiddleware; })();
module.exports = (function() { "use strict"; const Nodal = require('nodal'); const zlib = require('zlib'); class GzipRenderware extends Nodal.Renderware { exec(controller, data, callback) { let contentType = controller.getHeader('Content-Type', '').split(';')[0]; let acceptEncoding = controller._request.headers['accept-encoding'] || ''; let canCompress = !!{ 'text/plain': 1, 'text/html': 1, 'text/xml': 1, 'text/json': 1, 'text/javascript': 1, 'application/json': 1, 'application/xml': 1, 'application/javascript': 1, 'application/octet-stream': 1 }[contentType]; if (canCompress) { if (acceptEncoding.match(/\bgzip\b/)) { zlib.gzip(data, function(err, result) { if (!err) { controller.setHeader('Content-Encoding', 'gzip'); callback(null, result); return; } callback(null, data); }); return true; } else if(acceptEncoding.match(/\bdeflate\b/)) { zlib.deflate(data, function(err, result) { if (!err) { controller.setHeader('Content-Encoding', 'deflate'); callback(null, result); return; } callback(null, data); }); return true; } } callback(null, data); return false; } } return GzipRenderware; })();
Add renderware to generated apps
Add renderware to generated apps
JavaScript
mit
abossard/nodal,nsipplswezey/nodal,IrregularShed/nodal,IrregularShed/nodal,nsipplswezey/nodal,rlugojr/nodal,nsipplswezey/nodal,abossard/nodal,keithwhor/nodal
javascript
## Code Before: module.exports = (function() { "use strict"; const Nodal = require('nodal'); const zlib = require('zlib'); class GzipMiddleware extends Nodal.Middleware { exec(controller, data, callback) { let contentType = controller.getHeader('Content-Type', '').split(';')[0]; let acceptEncoding = controller._request.headers['accept-encoding'] || ''; let canCompress = !!{ 'text/plain': 1, 'text/html': 1, 'text/xml': 1, 'text/json': 1, 'text/javascript': 1, 'application/json': 1, 'application/xml': 1, 'application/javascript': 1, 'application/octet-stream': 1 }[contentType]; if (canCompress) { if (acceptEncoding.match(/\bgzip\b/)) { zlib.gzip(data, function(err, result) { if (!err) { controller.setHeader('Content-Encoding', 'gzip'); callback(null, result); return; } callback(null, data); }); return true; } else if(acceptEncoding.match(/\bdeflate\b/)) { zlib.deflate(data, function(err, result) { if (!err) { controller.setHeader('Content-Encoding', 'deflate'); callback(null, result); return; } callback(null, data); }); return true; } } callback(null, data); return false; } } return GzipMiddleware; })(); ## Instruction: Add renderware to generated apps ## Code After: module.exports = (function() { "use strict"; const Nodal = require('nodal'); const zlib = require('zlib'); class GzipRenderware extends Nodal.Renderware { exec(controller, data, callback) { let contentType = controller.getHeader('Content-Type', '').split(';')[0]; let acceptEncoding = controller._request.headers['accept-encoding'] || ''; let canCompress = !!{ 'text/plain': 1, 'text/html': 1, 'text/xml': 1, 'text/json': 1, 'text/javascript': 1, 'application/json': 1, 'application/xml': 1, 'application/javascript': 1, 'application/octet-stream': 1 }[contentType]; if (canCompress) { if (acceptEncoding.match(/\bgzip\b/)) { zlib.gzip(data, function(err, result) { if (!err) { controller.setHeader('Content-Encoding', 'gzip'); callback(null, result); return; } callback(null, data); }); return true; } else if(acceptEncoding.match(/\bdeflate\b/)) { zlib.deflate(data, function(err, result) { if (!err) { controller.setHeader('Content-Encoding', 'deflate'); callback(null, result); return; } callback(null, data); }); return true; } } callback(null, data); return false; } } return GzipRenderware; })();
5b29dd7ebb53226552d83551cc1e5acb37331d9b
lib/vagrant/ansible_auto/cap/guest/posix/gateway_addresses.rb
lib/vagrant/ansible_auto/cap/guest/posix/gateway_addresses.rb
require 'set' module VagrantPlugins module AnsibleAuto module Cap module Guest module POSIX class GatewayAddresses class << self def gateway_addresses(machine) with_default_gateway_addresses(machine).to_a.compact end private def with_default_gateway_addresses(machine) return enum_for(__method__, machine) unless block_given? seen_addresses = Set.new yield_unseen_address = lambda do |a| yield a unless seen_addresses.include? a seen_addresses << a end machine.communicate.execute('ip route show', error_check: false) do |type, data| if type == :stdout data.lines.each do |line| if line.start_with?('default') yield_unseen_address.call(line.split[2]) end end end end machine.communicate.execute('route -n', error_check: false) do |type, data| if type == :stdout data.lines.each do |line| if line.start_with?('0.0.0.0') yield_unseen_address.call(line.split[1]) end end end end machine.communicate.execute('netstat -rn', error_check: false) do |type, data| if type == :stdout data.lines.each do |line| if line.start_with?('0.0.0.0') yield_unseen_address.call(line.split[1]) end end end end end end end end end end end end
require 'set' module VagrantPlugins module AnsibleAuto module Cap module Guest module POSIX class GatewayAddresses class << self def gateway_addresses(machine) with_default_gateway_addresses(machine).to_a.compact end private def with_default_gateway_addresses(machine) return enum_for(__method__, machine) unless block_given? machine.communicate.execute('ip route show', error_check: false) do |type, data| if type == :stdout data.each_line { |l| yield l.split[2] if l.start_with? 'default' } end end machine.communicate.execute('route -n', error_check: false) do |type, data| if type == :stdout data.each_line { |l| yield l.split[1] if l.start_with? '0.0.0.0' } end end machine.communicate.execute('netstat -rn', error_check: false) do |type, data| if type == :stdout data.each_line { |l| yield l.split[1] if l.start_with? '0.0.0.0' } end end end end end end end end end end
Simplify iteration over candidate gateway IP addresses
Simplify iteration over candidate gateway IP addresses
Ruby
mit
BaxterStockman/vagrant-ansible_auto
ruby
## Code Before: require 'set' module VagrantPlugins module AnsibleAuto module Cap module Guest module POSIX class GatewayAddresses class << self def gateway_addresses(machine) with_default_gateway_addresses(machine).to_a.compact end private def with_default_gateway_addresses(machine) return enum_for(__method__, machine) unless block_given? seen_addresses = Set.new yield_unseen_address = lambda do |a| yield a unless seen_addresses.include? a seen_addresses << a end machine.communicate.execute('ip route show', error_check: false) do |type, data| if type == :stdout data.lines.each do |line| if line.start_with?('default') yield_unseen_address.call(line.split[2]) end end end end machine.communicate.execute('route -n', error_check: false) do |type, data| if type == :stdout data.lines.each do |line| if line.start_with?('0.0.0.0') yield_unseen_address.call(line.split[1]) end end end end machine.communicate.execute('netstat -rn', error_check: false) do |type, data| if type == :stdout data.lines.each do |line| if line.start_with?('0.0.0.0') yield_unseen_address.call(line.split[1]) end end end end end end end end end end end end ## Instruction: Simplify iteration over candidate gateway IP addresses ## Code After: require 'set' module VagrantPlugins module AnsibleAuto module Cap module Guest module POSIX class GatewayAddresses class << self def gateway_addresses(machine) with_default_gateway_addresses(machine).to_a.compact end private def with_default_gateway_addresses(machine) return enum_for(__method__, machine) unless block_given? machine.communicate.execute('ip route show', error_check: false) do |type, data| if type == :stdout data.each_line { |l| yield l.split[2] if l.start_with? 'default' } end end machine.communicate.execute('route -n', error_check: false) do |type, data| if type == :stdout data.each_line { |l| yield l.split[1] if l.start_with? '0.0.0.0' } end end machine.communicate.execute('netstat -rn', error_check: false) do |type, data| if type == :stdout data.each_line { |l| yield l.split[1] if l.start_with? '0.0.0.0' } end end end end end end end end end end
e4c288af36bf36188e5c1c25513877718883adb6
tests/integration/components/license-picker/component-test.js
tests/integration/components/license-picker/component-test.js
import Ember from 'ember'; import FakeServer, { stubRequest } from 'ember-cli-fake-server'; import config from 'ember-get-config'; import { moduleForComponent, test } from 'ember-qunit'; moduleForComponent('license-picker', 'Integration | Component | license picker', { integration: true }); function render(ctx, args) { let noop = () => {}; this.set('noop', noop); let licenses = [{ name: 'Without', text: 'This is a license without input fields', requiredFields: [] }, { name: 'No license', text: '{{yearRequired}} {{copyrightHolders}}', required_fields: ['yearRequired', 'copyrightHolders'] }] ctx.set('licenses', licenses); return ctx.render(Ember.HTMLBars.compile(`{{license-picker ${args && args.indexOf('editLicense') === -1 ? 'editLicense=(action noop)' : ''} allowDismiss=false licenses=licenses pressSubmit=(action noop) ${args || ''} }}`)); } test('it renders', function(assert) { render(this); assert.ok(true); }); test('default values cause autosave to trigger', function(assert) { let called = false; const autosaveFunc = () => { called = true; } this.set('autosaveFunc', autosaveFunc); let currentValues = {}; this.set('currentValues', currentValues); render(this, 'editLicense=autosaveFunc autosave=true currentValues=currentValues'); assert.ok(called); }); test('passing currentValues does not trigger autosave', function(assert) { let called = false; const autosaveFunc = () => { called = true; } this.set('autosaveFunc', autosaveFunc); let currentValues = { year: '2017', copyrightHolders: 'Henrique', nodeLicense: { id: 'a license' } }; this.set('currentValues', currentValues); render(this, 'editLicense=autosaveFunc autosave=true currentValues=currentValues'); assert.ok(!called); });
import Ember from 'ember'; import { moduleForComponent, test } from 'ember-qunit'; moduleForComponent('license-picker', 'Integration | Component | license picker', { integration: true }); function render(ctx, args) { ctx.set('currentValues', {}); ctx.set('noop', () => {}); ctx.set('licenses', [{ name: 'Without', text: 'This is a license without input fields', requiredFields: [] }, { name: 'No license', text: '{{yearRequired}} {{copyrightHolders}}', required_fields: ['yearRequired', 'copyrightHolders'] }]); return ctx.render(Ember.HTMLBars.compile(`{{license-picker ${args && args.indexOf('editLicense') === -1 ? 'editLicense=(action noop)' : ''} allowDismiss=false licenses=licenses currentValues=currentValues pressSubmit=(action noop) ${args || ''} }}`)); } test('it renders', function(assert) { render(this); assert.ok(true); });
Fix linting, remove tests dependent on observables
Fix linting, remove tests dependent on observables
JavaScript
apache-2.0
binoculars/ember-osf,CenterForOpenScience/ember-osf,binoculars/ember-osf,jamescdavis/ember-osf,baylee-d/ember-osf,crcresearch/ember-osf,jamescdavis/ember-osf,chrisseto/ember-osf,CenterForOpenScience/ember-osf,baylee-d/ember-osf,chrisseto/ember-osf,crcresearch/ember-osf
javascript
## Code Before: import Ember from 'ember'; import FakeServer, { stubRequest } from 'ember-cli-fake-server'; import config from 'ember-get-config'; import { moduleForComponent, test } from 'ember-qunit'; moduleForComponent('license-picker', 'Integration | Component | license picker', { integration: true }); function render(ctx, args) { let noop = () => {}; this.set('noop', noop); let licenses = [{ name: 'Without', text: 'This is a license without input fields', requiredFields: [] }, { name: 'No license', text: '{{yearRequired}} {{copyrightHolders}}', required_fields: ['yearRequired', 'copyrightHolders'] }] ctx.set('licenses', licenses); return ctx.render(Ember.HTMLBars.compile(`{{license-picker ${args && args.indexOf('editLicense') === -1 ? 'editLicense=(action noop)' : ''} allowDismiss=false licenses=licenses pressSubmit=(action noop) ${args || ''} }}`)); } test('it renders', function(assert) { render(this); assert.ok(true); }); test('default values cause autosave to trigger', function(assert) { let called = false; const autosaveFunc = () => { called = true; } this.set('autosaveFunc', autosaveFunc); let currentValues = {}; this.set('currentValues', currentValues); render(this, 'editLicense=autosaveFunc autosave=true currentValues=currentValues'); assert.ok(called); }); test('passing currentValues does not trigger autosave', function(assert) { let called = false; const autosaveFunc = () => { called = true; } this.set('autosaveFunc', autosaveFunc); let currentValues = { year: '2017', copyrightHolders: 'Henrique', nodeLicense: { id: 'a license' } }; this.set('currentValues', currentValues); render(this, 'editLicense=autosaveFunc autosave=true currentValues=currentValues'); assert.ok(!called); }); ## Instruction: Fix linting, remove tests dependent on observables ## Code After: import Ember from 'ember'; import { moduleForComponent, test } from 'ember-qunit'; moduleForComponent('license-picker', 'Integration | Component | license picker', { integration: true }); function render(ctx, args) { ctx.set('currentValues', {}); ctx.set('noop', () => {}); ctx.set('licenses', [{ name: 'Without', text: 'This is a license without input fields', requiredFields: [] }, { name: 'No license', text: '{{yearRequired}} {{copyrightHolders}}', required_fields: ['yearRequired', 'copyrightHolders'] }]); return ctx.render(Ember.HTMLBars.compile(`{{license-picker ${args && args.indexOf('editLicense') === -1 ? 'editLicense=(action noop)' : ''} allowDismiss=false licenses=licenses currentValues=currentValues pressSubmit=(action noop) ${args || ''} }}`)); } test('it renders', function(assert) { render(this); assert.ok(true); });
450a1f64a21afce008392e321fff2d268bb9fc41
setup.py
setup.py
from distutils.core import setup from distutils.extension import Extension from Cython.Distutils import build_ext import numpy ALGPATH = "clusterpy/core/toolboxes/cluster/componentsAlg/" ALGPKG = "clusterpy.core.toolboxes.cluster.componentsAlg." CLUSPATH = "clusterpy/core/toolboxes/cluster/" CLUSPKG = "clusterpy.core.toolboxes.cluster." setup( name='clusterPy', version='0.9.9', description='Library of spatially constrained clustering algorithms', long_description=""" clusterPy is a Python library with algorithms for spatially constrained clustering. clusterPy offers you some of the most cited algorithms for spatial aggregation.""", author='RiSE Group', author_email='software@rise-group.org', url='http://www.rise-group.org/section/Software/clusterPy/', packages=['clusterpy','clusterpy.core','clusterpy.core.data', 'clusterpy.core.geometry','clusterpy.core.toolboxes', 'clusterpy.core.toolboxes.cluster', 'clusterpy.core.toolboxes.cluster.componentsAlg'], ext_modules = [Extension(CLUSPKG+"arisel", [CLUSPATH+"arisel.pyx"], extra_link_args=['-fopenmp'], extra_compile_args=['-fopenmp'] ), Extension(ALGPKG+"distanceFunctions", [ALGPATH+"distanceFunctions.pyx"]), Extension(ALGPKG+"dist2Regions", [ALGPATH+"dist2Regions.pyx"]), Extension(ALGPKG+"selectionTypeFunctions", [ALGPATH+"selectionTypeFunctions.pyx"]), Extension(ALGPKG+"init", [ALGPATH+"init.pyx"]), Extension(ALGPKG+"objFunctions", [ALGPATH+"objFunctions.pyx"]) ], cmdclass = {'build_ext': build_ext} )
from distutils.core import setup from distutils.extension import Extension setup( name='clusterPy', version='0.9.9', description='Library of spatially constrained clustering algorithms', long_description=""" clusterPy is a Python library with algorithms for spatially constrained clustering. clusterPy offers you some of the most cited algorithms for spatial aggregation.""", author='RiSE Group', author_email='software@rise-group.org', url='http://www.rise-group.org/section/Software/clusterPy/', packages=['clusterpy','clusterpy.core','clusterpy.core.data', 'clusterpy.core.geometry','clusterpy.core.toolboxes', 'clusterpy.core.toolboxes.cluster', 'clusterpy.core.toolboxes.cluster.componentsAlg'], )
Remove cython Extension builder and build_ext from Setup
Remove cython Extension builder and build_ext from Setup
Python
bsd-3-clause
clusterpy/clusterpy,clusterpy/clusterpy
python
## Code Before: from distutils.core import setup from distutils.extension import Extension from Cython.Distutils import build_ext import numpy ALGPATH = "clusterpy/core/toolboxes/cluster/componentsAlg/" ALGPKG = "clusterpy.core.toolboxes.cluster.componentsAlg." CLUSPATH = "clusterpy/core/toolboxes/cluster/" CLUSPKG = "clusterpy.core.toolboxes.cluster." setup( name='clusterPy', version='0.9.9', description='Library of spatially constrained clustering algorithms', long_description=""" clusterPy is a Python library with algorithms for spatially constrained clustering. clusterPy offers you some of the most cited algorithms for spatial aggregation.""", author='RiSE Group', author_email='software@rise-group.org', url='http://www.rise-group.org/section/Software/clusterPy/', packages=['clusterpy','clusterpy.core','clusterpy.core.data', 'clusterpy.core.geometry','clusterpy.core.toolboxes', 'clusterpy.core.toolboxes.cluster', 'clusterpy.core.toolboxes.cluster.componentsAlg'], ext_modules = [Extension(CLUSPKG+"arisel", [CLUSPATH+"arisel.pyx"], extra_link_args=['-fopenmp'], extra_compile_args=['-fopenmp'] ), Extension(ALGPKG+"distanceFunctions", [ALGPATH+"distanceFunctions.pyx"]), Extension(ALGPKG+"dist2Regions", [ALGPATH+"dist2Regions.pyx"]), Extension(ALGPKG+"selectionTypeFunctions", [ALGPATH+"selectionTypeFunctions.pyx"]), Extension(ALGPKG+"init", [ALGPATH+"init.pyx"]), Extension(ALGPKG+"objFunctions", [ALGPATH+"objFunctions.pyx"]) ], cmdclass = {'build_ext': build_ext} ) ## Instruction: Remove cython Extension builder and build_ext from Setup ## Code After: from distutils.core import setup from distutils.extension import Extension setup( name='clusterPy', version='0.9.9', description='Library of spatially constrained clustering algorithms', long_description=""" clusterPy is a Python library with algorithms for spatially constrained clustering. clusterPy offers you some of the most cited algorithms for spatial aggregation.""", author='RiSE Group', author_email='software@rise-group.org', url='http://www.rise-group.org/section/Software/clusterPy/', packages=['clusterpy','clusterpy.core','clusterpy.core.data', 'clusterpy.core.geometry','clusterpy.core.toolboxes', 'clusterpy.core.toolboxes.cluster', 'clusterpy.core.toolboxes.cluster.componentsAlg'], )
ddec6067054cc4408ac174e3ea4ffeca2a962201
regulations/views/notice_home.py
regulations/views/notice_home.py
from __future__ import unicode_literals from operator import itemgetter import logging from django.http import Http404 from django.template.response import TemplateResponse from django.views.generic.base import View from regulations.generator.api_reader import ApiReader from regulations.views.preamble import ( notice_data, CommentState) logger = logging.getLogger(__name__) class NoticeHomeView(View): """ Basic view that provides a list of regulations and notices to the context. """ template_name = None # We should probably have a default notice template. def get(self, request, *args, **kwargs): notices = ApiReader().notices().get("results", []) context = {} notices_meta = [] for notice in notices: try: if notice.get("document_number"): _, meta, _ = notice_data(notice["document_number"]) notices_meta.append(meta) except Http404: pass notices_meta = sorted(notices_meta, key=itemgetter("publication_date"), reverse=True) context["notices"] = notices_meta # Django templates won't show contents of CommentState as an Enum, so: context["comment_state"] = {state.name: state.value for state in CommentState} assert self.template_name template = self.template_name return TemplateResponse(request=request, template=template, context=context)
from __future__ import unicode_literals from operator import itemgetter import logging from django.http import Http404 from django.template.response import TemplateResponse from django.views.generic.base import View from regulations.generator.api_reader import ApiReader from regulations.views.preamble import ( notice_data, CommentState) logger = logging.getLogger(__name__) class NoticeHomeView(View): """ Basic view that provides a list of regulations and notices to the context. """ template_name = None # We should probably have a default notice template. def get(self, request, *args, **kwargs): notices = ApiReader().notices().get("results", []) context = {} notices_meta = [] for notice in notices: try: if notice.get("document_number"): _, meta, _ = notice_data(notice["document_number"]) notices_meta.append(meta) except Http404: pass notices_meta = sorted(notices_meta, key=itemgetter("publication_date"), reverse=True) context["notices"] = notices_meta # Django templates won't show contents of CommentState as an Enum, so: context["comment_state"] = {state.name: state.value for state in CommentState} template = self.template_name return TemplateResponse(request=request, template=template, context=context)
Remove unnecessary assert from view for Notice home.
Remove unnecessary assert from view for Notice home.
Python
cc0-1.0
18F/regulations-site,18F/regulations-site,eregs/regulations-site,tadhg-ohiggins/regulations-site,tadhg-ohiggins/regulations-site,tadhg-ohiggins/regulations-site,eregs/regulations-site,eregs/regulations-site,eregs/regulations-site,tadhg-ohiggins/regulations-site,18F/regulations-site,18F/regulations-site
python
## Code Before: from __future__ import unicode_literals from operator import itemgetter import logging from django.http import Http404 from django.template.response import TemplateResponse from django.views.generic.base import View from regulations.generator.api_reader import ApiReader from regulations.views.preamble import ( notice_data, CommentState) logger = logging.getLogger(__name__) class NoticeHomeView(View): """ Basic view that provides a list of regulations and notices to the context. """ template_name = None # We should probably have a default notice template. def get(self, request, *args, **kwargs): notices = ApiReader().notices().get("results", []) context = {} notices_meta = [] for notice in notices: try: if notice.get("document_number"): _, meta, _ = notice_data(notice["document_number"]) notices_meta.append(meta) except Http404: pass notices_meta = sorted(notices_meta, key=itemgetter("publication_date"), reverse=True) context["notices"] = notices_meta # Django templates won't show contents of CommentState as an Enum, so: context["comment_state"] = {state.name: state.value for state in CommentState} assert self.template_name template = self.template_name return TemplateResponse(request=request, template=template, context=context) ## Instruction: Remove unnecessary assert from view for Notice home. ## Code After: from __future__ import unicode_literals from operator import itemgetter import logging from django.http import Http404 from django.template.response import TemplateResponse from django.views.generic.base import View from regulations.generator.api_reader import ApiReader from regulations.views.preamble import ( notice_data, CommentState) logger = logging.getLogger(__name__) class NoticeHomeView(View): """ Basic view that provides a list of regulations and notices to the context. """ template_name = None # We should probably have a default notice template. def get(self, request, *args, **kwargs): notices = ApiReader().notices().get("results", []) context = {} notices_meta = [] for notice in notices: try: if notice.get("document_number"): _, meta, _ = notice_data(notice["document_number"]) notices_meta.append(meta) except Http404: pass notices_meta = sorted(notices_meta, key=itemgetter("publication_date"), reverse=True) context["notices"] = notices_meta # Django templates won't show contents of CommentState as an Enum, so: context["comment_state"] = {state.name: state.value for state in CommentState} template = self.template_name return TemplateResponse(request=request, template=template, context=context)
fa62ad541d147e740bedd97f470390aafe882e8f
app/js/arethusa.core/directives/foreign_keys.js
app/js/arethusa.core/directives/foreign_keys.js
'use strict'; angular.module('arethusa.core').directive('foreignKeys',[ 'keyCapture', 'languageSettings', function (keyCapture, languageSettings) { return { restrict: 'A', scope: { ngChange: '&', ngModel: '@', foreignKeys: '=' }, link: function (scope, element, attrs) { var parent = scope.$parent; function extractLanguage() { return (languageSettings.getFor('treebank') || {}).lang; } function lang() { return scope.foreignKeys || extractLanguage(); } // This will not detect changes right now function placeHolderText() { var language = languageSettings.langNames[lang()]; return language ? language + ' input enabled!' : ''; } element.attr('placeholder', placeHolderText); element.on('keydown', function (event) { var input = event.target.value; if (lang) { var fK = keyCapture.getForeignKey(event, lang); if (fK === false) { return false; } if (fK === undefined) { return true; } else { event.target.value = input + fK; scope.$apply(function() { parent.$eval(scope.ngModel + ' = i + k', { i: input, k: fK }); scope.ngChange(); }); return false; } } else { return true; } }); } }; } ]);
'use strict'; angular.module('arethusa.core').directive('foreignKeys',[ 'keyCapture', 'languageSettings', function (keyCapture, languageSettings) { return { restrict: 'A', scope: { ngChange: '&', ngModel: '@', foreignKeys: '=' }, link: function (scope, element, attrs) { var parent = scope.$parent; function extractLanguage() { return (languageSettings.getFor('treebank') || {}).lang; } function lang() { return scope.foreignKeys || extractLanguage(); } // This will not detect changes right now function placeHolderText() { var language = languageSettings.langNames[lang()]; return language ? language + ' input enabled!' : ''; } element.attr('placeholder', placeHolderText); element.on('keydown', function (event) { var input = event.target.value; var l = lang(); if (l) { var fK = keyCapture.getForeignKey(event, l); if (fK === false) { return false; } if (fK === undefined) { return true; } else { event.target.value = input + fK; scope.$apply(function() { parent.$eval(scope.ngModel + ' = i + k', { i: input, k: fK }); scope.ngChange(); }); return false; } } else { return true; } }); } }; } ]);
Fix minor mistake in foreignKeys
Fix minor mistake in foreignKeys
JavaScript
mit
latin-language-toolkit/arethusa,PonteIneptique/arethusa,fbaumgardt/arethusa,Masoumeh/arethusa,latin-language-toolkit/arethusa,alpheios-project/arethusa,fbaumgardt/arethusa,fbaumgardt/arethusa,alpheios-project/arethusa,alpheios-project/arethusa,Masoumeh/arethusa,PonteIneptique/arethusa
javascript
## Code Before: 'use strict'; angular.module('arethusa.core').directive('foreignKeys',[ 'keyCapture', 'languageSettings', function (keyCapture, languageSettings) { return { restrict: 'A', scope: { ngChange: '&', ngModel: '@', foreignKeys: '=' }, link: function (scope, element, attrs) { var parent = scope.$parent; function extractLanguage() { return (languageSettings.getFor('treebank') || {}).lang; } function lang() { return scope.foreignKeys || extractLanguage(); } // This will not detect changes right now function placeHolderText() { var language = languageSettings.langNames[lang()]; return language ? language + ' input enabled!' : ''; } element.attr('placeholder', placeHolderText); element.on('keydown', function (event) { var input = event.target.value; if (lang) { var fK = keyCapture.getForeignKey(event, lang); if (fK === false) { return false; } if (fK === undefined) { return true; } else { event.target.value = input + fK; scope.$apply(function() { parent.$eval(scope.ngModel + ' = i + k', { i: input, k: fK }); scope.ngChange(); }); return false; } } else { return true; } }); } }; } ]); ## Instruction: Fix minor mistake in foreignKeys ## Code After: 'use strict'; angular.module('arethusa.core').directive('foreignKeys',[ 'keyCapture', 'languageSettings', function (keyCapture, languageSettings) { return { restrict: 'A', scope: { ngChange: '&', ngModel: '@', foreignKeys: '=' }, link: function (scope, element, attrs) { var parent = scope.$parent; function extractLanguage() { return (languageSettings.getFor('treebank') || {}).lang; } function lang() { return scope.foreignKeys || extractLanguage(); } // This will not detect changes right now function placeHolderText() { var language = languageSettings.langNames[lang()]; return language ? language + ' input enabled!' : ''; } element.attr('placeholder', placeHolderText); element.on('keydown', function (event) { var input = event.target.value; var l = lang(); if (l) { var fK = keyCapture.getForeignKey(event, l); if (fK === false) { return false; } if (fK === undefined) { return true; } else { event.target.value = input + fK; scope.$apply(function() { parent.$eval(scope.ngModel + ' = i + k', { i: input, k: fK }); scope.ngChange(); }); return false; } } else { return true; } }); } }; } ]);
6e939d27b0b6cff6f71f7af6ab66794a0ef6c02b
src/auth/IdBroker.php
src/auth/IdBroker.php
<?php namespace Sil\SilAuth\auth; use Psr\Log\LoggerInterface; use Sil\Idp\IdBroker\Client\IdBrokerClient; class IdBroker { /** @var IdBrokerClient */ protected $client; /** @var LoggerInterface */ protected $logger; /** * * @param string $baseUri The base of the API's URL. * Example: 'https://api.example.com/'. * @param string $accessToken Your authorization access (bearer) token. * @param LoggerInterface $logger */ public function __construct($baseUri, $accessToken, LoggerInterface $logger) { $this->logger = $logger; $this->client = new IdBrokerClient($baseUri, $accessToken); } /** * Attempt to authenticate with the given username and password, returning * the attributes for that user if the credentials were acceptable (or null * if they were not acceptable, since there is no authenticated user in that * situation). * * @param string $username The username. * @param string $password The password. * @return array|null The user's attributes (if successful), otherwise null. */ public function getAuthenticatedUser(string $username, string $password) { $result = $this->client->authenticate([ 'username' => $username, 'password' => $password, ]); $statusCode = $result['statusCode'] ?? null; if (intval($statusCode) === 200) { unset($result['statusCode']); return $result; } return null; } }
<?php namespace Sil\SilAuth\auth; use Psr\Log\LoggerInterface; use Sil\Idp\IdBroker\Client\IdBrokerClient; class IdBroker { /** @var IdBrokerClient */ protected $client; /** @var LoggerInterface */ protected $logger; /** * * @param string $baseUri The base of the API's URL. * Example: 'https://api.example.com/'. * @param string $accessToken Your authorization access (bearer) token. * @param LoggerInterface $logger */ public function __construct( string $baseUri, string $accessToken, LoggerInterface $logger ) { $this->logger = $logger; $this->client = new IdBrokerClient($baseUri, $accessToken); } /** * Attempt to authenticate with the given username and password, returning * the attributes for that user if the credentials were acceptable (or null * if they were not acceptable, since there is no authenticated user in that * situation). * * @param string $username The username. * @param string $password The password. * @return array|null The user's attributes (if successful), otherwise null. */ public function getAuthenticatedUser(string $username, string $password) { $result = $this->client->authenticate([ 'username' => $username, 'password' => $password, ]); $statusCode = $result['statusCode'] ?? null; if (intval($statusCode) === 200) { unset($result['statusCode']); return $result; } return null; } }
Make argument types more specific.
Make argument types more specific.
PHP
mit
silinternational/simplesamlphp-module-silauth,silinternational/simplesamlphp-module-silauth
php
## Code Before: <?php namespace Sil\SilAuth\auth; use Psr\Log\LoggerInterface; use Sil\Idp\IdBroker\Client\IdBrokerClient; class IdBroker { /** @var IdBrokerClient */ protected $client; /** @var LoggerInterface */ protected $logger; /** * * @param string $baseUri The base of the API's URL. * Example: 'https://api.example.com/'. * @param string $accessToken Your authorization access (bearer) token. * @param LoggerInterface $logger */ public function __construct($baseUri, $accessToken, LoggerInterface $logger) { $this->logger = $logger; $this->client = new IdBrokerClient($baseUri, $accessToken); } /** * Attempt to authenticate with the given username and password, returning * the attributes for that user if the credentials were acceptable (or null * if they were not acceptable, since there is no authenticated user in that * situation). * * @param string $username The username. * @param string $password The password. * @return array|null The user's attributes (if successful), otherwise null. */ public function getAuthenticatedUser(string $username, string $password) { $result = $this->client->authenticate([ 'username' => $username, 'password' => $password, ]); $statusCode = $result['statusCode'] ?? null; if (intval($statusCode) === 200) { unset($result['statusCode']); return $result; } return null; } } ## Instruction: Make argument types more specific. ## Code After: <?php namespace Sil\SilAuth\auth; use Psr\Log\LoggerInterface; use Sil\Idp\IdBroker\Client\IdBrokerClient; class IdBroker { /** @var IdBrokerClient */ protected $client; /** @var LoggerInterface */ protected $logger; /** * * @param string $baseUri The base of the API's URL. * Example: 'https://api.example.com/'. * @param string $accessToken Your authorization access (bearer) token. * @param LoggerInterface $logger */ public function __construct( string $baseUri, string $accessToken, LoggerInterface $logger ) { $this->logger = $logger; $this->client = new IdBrokerClient($baseUri, $accessToken); } /** * Attempt to authenticate with the given username and password, returning * the attributes for that user if the credentials were acceptable (or null * if they were not acceptable, since there is no authenticated user in that * situation). * * @param string $username The username. * @param string $password The password. * @return array|null The user's attributes (if successful), otherwise null. */ public function getAuthenticatedUser(string $username, string $password) { $result = $this->client->authenticate([ 'username' => $username, 'password' => $password, ]); $statusCode = $result['statusCode'] ?? null; if (intval($statusCode) === 200) { unset($result['statusCode']); return $result; } return null; } }
9e85c73a21a2f907ef6df4ef1fe56fb2ceb9bf07
library/src/main/java/com/novoda/downloadmanager/LiteDownloadsNetworkRecoveryEnabled.java
library/src/main/java/com/novoda/downloadmanager/LiteDownloadsNetworkRecoveryEnabled.java
package com.novoda.downloadmanager; import android.content.Context; import android.util.Log; import com.evernote.android.job.JobManager; import com.evernote.android.job.JobRequest; import java.util.concurrent.TimeUnit; class LiteDownloadsNetworkRecoveryEnabled implements DownloadsNetworkRecovery { private final ConnectionType connectionType; LiteDownloadsNetworkRecoveryEnabled(Context context, DownloadManager downloadManager, ConnectionType connectionType) { this.connectionType = connectionType; JobManager jobManager = JobManager.create(context); jobManager.addJobCreator(new LiteJobCreator(downloadManager)); } @Override public void scheduleRecovery() { JobRequest.Builder builder = new JobRequest.Builder(LiteJobCreator.TAG) .setExecutionWindow(TimeUnit.SECONDS.toMillis(1), TimeUnit.DAYS.toMillis(1)); switch (connectionType) { case ALL: builder.setRequiredNetworkType(JobRequest.NetworkType.CONNECTED); break; case UNMETERED: builder.setRequiredNetworkType(JobRequest.NetworkType.UNMETERED); break; case METERED: builder.setRequiredNetworkType(JobRequest.NetworkType.METERED); break; default: Log.w(getClass().getSimpleName(), "Unknown ConnectionType: " + connectionType); break; } JobRequest jobRequest = builder.build(); JobManager jobManager = JobManager.instance(); jobManager.schedule(jobRequest); } }
package com.novoda.downloadmanager; import android.content.Context; import com.evernote.android.job.JobManager; import com.evernote.android.job.JobRequest; import com.novoda.notils.logger.simple.Log; import java.util.concurrent.TimeUnit; class LiteDownloadsNetworkRecoveryEnabled implements DownloadsNetworkRecovery { private final ConnectionType connectionType; LiteDownloadsNetworkRecoveryEnabled(Context context, DownloadManager downloadManager, ConnectionType connectionType) { this.connectionType = connectionType; JobManager jobManager = JobManager.create(context); jobManager.addJobCreator(new LiteJobCreator(downloadManager)); } @Override public void scheduleRecovery() { JobRequest.Builder builder = new JobRequest.Builder(LiteJobCreator.TAG) .setExecutionWindow(TimeUnit.SECONDS.toMillis(1), TimeUnit.DAYS.toMillis(1)); switch (connectionType) { case ALL: builder.setRequiredNetworkType(JobRequest.NetworkType.CONNECTED); break; case UNMETERED: builder.setRequiredNetworkType(JobRequest.NetworkType.UNMETERED); break; case METERED: builder.setRequiredNetworkType(JobRequest.NetworkType.METERED); break; default: Log.w("Unknown ConnectionType: " + connectionType); break; } JobRequest jobRequest = builder.build(); JobManager jobManager = JobManager.instance(); jobManager.schedule(jobRequest); Log.v("Scheduling Network Recovery."); } }
Add some logs to scheduling.
Add some logs to scheduling.
Java
apache-2.0
novoda/download-manager
java
## Code Before: package com.novoda.downloadmanager; import android.content.Context; import android.util.Log; import com.evernote.android.job.JobManager; import com.evernote.android.job.JobRequest; import java.util.concurrent.TimeUnit; class LiteDownloadsNetworkRecoveryEnabled implements DownloadsNetworkRecovery { private final ConnectionType connectionType; LiteDownloadsNetworkRecoveryEnabled(Context context, DownloadManager downloadManager, ConnectionType connectionType) { this.connectionType = connectionType; JobManager jobManager = JobManager.create(context); jobManager.addJobCreator(new LiteJobCreator(downloadManager)); } @Override public void scheduleRecovery() { JobRequest.Builder builder = new JobRequest.Builder(LiteJobCreator.TAG) .setExecutionWindow(TimeUnit.SECONDS.toMillis(1), TimeUnit.DAYS.toMillis(1)); switch (connectionType) { case ALL: builder.setRequiredNetworkType(JobRequest.NetworkType.CONNECTED); break; case UNMETERED: builder.setRequiredNetworkType(JobRequest.NetworkType.UNMETERED); break; case METERED: builder.setRequiredNetworkType(JobRequest.NetworkType.METERED); break; default: Log.w(getClass().getSimpleName(), "Unknown ConnectionType: " + connectionType); break; } JobRequest jobRequest = builder.build(); JobManager jobManager = JobManager.instance(); jobManager.schedule(jobRequest); } } ## Instruction: Add some logs to scheduling. ## Code After: package com.novoda.downloadmanager; import android.content.Context; import com.evernote.android.job.JobManager; import com.evernote.android.job.JobRequest; import com.novoda.notils.logger.simple.Log; import java.util.concurrent.TimeUnit; class LiteDownloadsNetworkRecoveryEnabled implements DownloadsNetworkRecovery { private final ConnectionType connectionType; LiteDownloadsNetworkRecoveryEnabled(Context context, DownloadManager downloadManager, ConnectionType connectionType) { this.connectionType = connectionType; JobManager jobManager = JobManager.create(context); jobManager.addJobCreator(new LiteJobCreator(downloadManager)); } @Override public void scheduleRecovery() { JobRequest.Builder builder = new JobRequest.Builder(LiteJobCreator.TAG) .setExecutionWindow(TimeUnit.SECONDS.toMillis(1), TimeUnit.DAYS.toMillis(1)); switch (connectionType) { case ALL: builder.setRequiredNetworkType(JobRequest.NetworkType.CONNECTED); break; case UNMETERED: builder.setRequiredNetworkType(JobRequest.NetworkType.UNMETERED); break; case METERED: builder.setRequiredNetworkType(JobRequest.NetworkType.METERED); break; default: Log.w("Unknown ConnectionType: " + connectionType); break; } JobRequest jobRequest = builder.build(); JobManager jobManager = JobManager.instance(); jobManager.schedule(jobRequest); Log.v("Scheduling Network Recovery."); } }
c5fd49edb029cf0fb290bb957d9bdc138e156402
datasets/templates/datasets/taxonomy_node_mini_info.html
datasets/templates/datasets/taxonomy_node_mini_info.html
{% load dataset_templatetags %} <table class="ui unstackable table" width="100%"> <tbody> <td>Hierarchy</td> <td> <div class="ui list"> {% for hierarchy_path in node.hierarchy_paths %} <div class="item"> <div class="ui horizontal list"> <div class="item"> <i class="tree icon"></i> </div> {% for node_id in hierarchy_path %} {% taxonomy_node_minimal_data dataset node_id as sub_node_data %} <div class="item" style="margin-left:0px;margin-right:5px;"> > <a href="" target="_blank">{{ sub_node_data.name }}</a> </div> {% endfor %} </div> </div> {% empty %} <div class="item">-</div> {% endfor %} </div> </td> </tr> <tr> <td class="three wide">Description</td> <td>{{ node.description }}</td> </tr> {% if node.freesound_examples %} <tr><td>Examples</td> <td> {% for fsid in node.freesound_examples %} {{ fsid| fs_embed | safe }} {% endfor %} </td> </tr> {% endif %} </div> </div> </tbody> </table>
{% load dataset_templatetags %} <table class="ui unstackable table" width="100%"> <tbody> <td>Hierarchy</td> <td> <div class="ui list"> {% for hierarchy_path in node.hierarchy_paths %} <div class="item"> <div class="ui horizontal list"> <div class="item"> <i class="tree icon"></i> </div> {% for node_id in hierarchy_path %} {% taxonomy_node_minimal_data dataset node_id as sub_node_data %} <div class="item" style="margin-left:0px;margin-right:5px;"> > <a href="{% url 'dataset-explore-taxonomy-node' dataset.short_name sub_node_data.url_id %}" target="_blank">{{ sub_node_data.name }}</a> </div> {% endfor %} </div> </div> {% empty %} <div class="item">-</div> {% endfor %} </div> </td> </tr> <tr> <td class="three wide">Description</td> <td>{{ node.description }}</td> </tr> {% if node.freesound_examples %} <tr><td>Examples</td> <td> {% for fsid in node.freesound_examples %} {{ fsid| fs_embed | safe }} {% endfor %} </td> </tr> {% endif %} </div> </div> </tbody> </table>
Add link to categories in popup
Add link to categories in popup
HTML
agpl-3.0
MTG/freesound-datasets,MTG/freesound-datasets,MTG/freesound-datasets,MTG/freesound-datasets
html
## Code Before: {% load dataset_templatetags %} <table class="ui unstackable table" width="100%"> <tbody> <td>Hierarchy</td> <td> <div class="ui list"> {% for hierarchy_path in node.hierarchy_paths %} <div class="item"> <div class="ui horizontal list"> <div class="item"> <i class="tree icon"></i> </div> {% for node_id in hierarchy_path %} {% taxonomy_node_minimal_data dataset node_id as sub_node_data %} <div class="item" style="margin-left:0px;margin-right:5px;"> > <a href="" target="_blank">{{ sub_node_data.name }}</a> </div> {% endfor %} </div> </div> {% empty %} <div class="item">-</div> {% endfor %} </div> </td> </tr> <tr> <td class="three wide">Description</td> <td>{{ node.description }}</td> </tr> {% if node.freesound_examples %} <tr><td>Examples</td> <td> {% for fsid in node.freesound_examples %} {{ fsid| fs_embed | safe }} {% endfor %} </td> </tr> {% endif %} </div> </div> </tbody> </table> ## Instruction: Add link to categories in popup ## Code After: {% load dataset_templatetags %} <table class="ui unstackable table" width="100%"> <tbody> <td>Hierarchy</td> <td> <div class="ui list"> {% for hierarchy_path in node.hierarchy_paths %} <div class="item"> <div class="ui horizontal list"> <div class="item"> <i class="tree icon"></i> </div> {% for node_id in hierarchy_path %} {% taxonomy_node_minimal_data dataset node_id as sub_node_data %} <div class="item" style="margin-left:0px;margin-right:5px;"> > <a href="{% url 'dataset-explore-taxonomy-node' dataset.short_name sub_node_data.url_id %}" target="_blank">{{ sub_node_data.name }}</a> </div> {% endfor %} </div> </div> {% empty %} <div class="item">-</div> {% endfor %} </div> </td> </tr> <tr> <td class="three wide">Description</td> <td>{{ node.description }}</td> </tr> {% if node.freesound_examples %} <tr><td>Examples</td> <td> {% for fsid in node.freesound_examples %} {{ fsid| fs_embed | safe }} {% endfor %} </td> </tr> {% endif %} </div> </div> </tbody> </table>
3c6a6677be6aca24d73182505772dbc6f2b49684
Sources/TAR/DataWithPointer+Tar.swift
Sources/TAR/DataWithPointer+Tar.swift
// Copyright (c) 2017 Timofey Solomko // Licensed under MIT License // // See LICENSE for license information import Foundation extension DataWithPointer { func nullEndedBuffer(cutoff: Int) -> [UInt8] { let startIndex = index var buffer = [UInt8]() while index - startIndex < cutoff { let byte = self.byte() if byte == 0 { index -= 1 break } buffer.append(byte) } index += cutoff - (index - startIndex) return buffer } func nullEndedAsciiString(cutoff: Int) throws -> String { if let string = String(bytes: self.nullEndedBuffer(cutoff: cutoff), encoding: .ascii) { return string } else { throw TarError.notAsciiString } } func nullSpaceEndedBuffer(cutoff: Int) -> [UInt8] { let startIndex = index var buffer = [UInt8]() while index - startIndex < cutoff { let byte = self.byte() if byte == 0 || byte == 0x20 { index -= 1 break } buffer.append(byte) } index += cutoff - (index - startIndex) return buffer } func nullSpaceEndedAsciiString(cutoff: Int) throws -> String { if let string = String(bytes: self.nullSpaceEndedBuffer(cutoff: cutoff), encoding: .ascii) { return string } else { throw TarError.notAsciiString } } }
// Copyright (c) 2017 Timofey Solomko // Licensed under MIT License // // See LICENSE for license information import Foundation extension DataWithPointer { private func nullEndedBuffer(cutoff: Int) -> [UInt8] { let startIndex = index var buffer = [UInt8]() while index - startIndex < cutoff { let byte = self.byte() if byte == 0 { index -= 1 break } buffer.append(byte) } index += cutoff - (index - startIndex) return buffer } func nullEndedAsciiString(cutoff: Int) throws -> String { if let string = String(bytes: self.nullEndedBuffer(cutoff: cutoff), encoding: .ascii) { return string } else { throw TarError.notAsciiString } } private func nullSpaceEndedBuffer(cutoff: Int) -> [UInt8] { let startIndex = index var buffer = [UInt8]() while index - startIndex < cutoff { let byte = self.byte() if byte == 0 || byte == 0x20 { index -= 1 break } buffer.append(byte) } index += cutoff - (index - startIndex) return buffer } func nullSpaceEndedAsciiString(cutoff: Int) throws -> String { if let string = String(bytes: self.nullSpaceEndedBuffer(cutoff: cutoff), encoding: .ascii) { return string } else { throw TarError.notAsciiString } } }
Make private couple of dwp+tar functions
Make private couple of dwp+tar functions
Swift
mit
tsolomko/SWCompression,tsolomko/SWCompression,tsolomko/SWCompression
swift
## Code Before: // Copyright (c) 2017 Timofey Solomko // Licensed under MIT License // // See LICENSE for license information import Foundation extension DataWithPointer { func nullEndedBuffer(cutoff: Int) -> [UInt8] { let startIndex = index var buffer = [UInt8]() while index - startIndex < cutoff { let byte = self.byte() if byte == 0 { index -= 1 break } buffer.append(byte) } index += cutoff - (index - startIndex) return buffer } func nullEndedAsciiString(cutoff: Int) throws -> String { if let string = String(bytes: self.nullEndedBuffer(cutoff: cutoff), encoding: .ascii) { return string } else { throw TarError.notAsciiString } } func nullSpaceEndedBuffer(cutoff: Int) -> [UInt8] { let startIndex = index var buffer = [UInt8]() while index - startIndex < cutoff { let byte = self.byte() if byte == 0 || byte == 0x20 { index -= 1 break } buffer.append(byte) } index += cutoff - (index - startIndex) return buffer } func nullSpaceEndedAsciiString(cutoff: Int) throws -> String { if let string = String(bytes: self.nullSpaceEndedBuffer(cutoff: cutoff), encoding: .ascii) { return string } else { throw TarError.notAsciiString } } } ## Instruction: Make private couple of dwp+tar functions ## Code After: // Copyright (c) 2017 Timofey Solomko // Licensed under MIT License // // See LICENSE for license information import Foundation extension DataWithPointer { private func nullEndedBuffer(cutoff: Int) -> [UInt8] { let startIndex = index var buffer = [UInt8]() while index - startIndex < cutoff { let byte = self.byte() if byte == 0 { index -= 1 break } buffer.append(byte) } index += cutoff - (index - startIndex) return buffer } func nullEndedAsciiString(cutoff: Int) throws -> String { if let string = String(bytes: self.nullEndedBuffer(cutoff: cutoff), encoding: .ascii) { return string } else { throw TarError.notAsciiString } } private func nullSpaceEndedBuffer(cutoff: Int) -> [UInt8] { let startIndex = index var buffer = [UInt8]() while index - startIndex < cutoff { let byte = self.byte() if byte == 0 || byte == 0x20 { index -= 1 break } buffer.append(byte) } index += cutoff - (index - startIndex) return buffer } func nullSpaceEndedAsciiString(cutoff: Int) throws -> String { if let string = String(bytes: self.nullSpaceEndedBuffer(cutoff: cutoff), encoding: .ascii) { return string } else { throw TarError.notAsciiString } } }
201fc9a9d6f81ed3ae39f9d0512bb2221f241d8d
lib/active_job/stats/callbacks.rb
lib/active_job/stats/callbacks.rb
module ActiveJob module Stats module Callbacks extend ActiveSupport::Concern included do before_enqueue :after_enqueue_stats, if: :monitored after_enqueue :after_enqueue_stats, if: :monitored before_perform :before_perform_stats, if: :monitored after_perform :after_perform_stats, if: :monitored around_perform :benchmark_stats, if: :benchmarked private def benchmark_stats require 'active_support/core_ext/benchmark' benchmark = Benchmark.ms { yield } ActiveJob::Stats.reporter.timing("#{self.class.queue_name}.processed", benchmark) ActiveJob::Stats.reporter.timing("#{self.class}.processed", benchmark) end def before_perform_stats ActiveJob::Stats.reporter.increment("#{self.class.queue_name}.started") ActiveJob::Stats.reporter.increment("#{self.class}.started") ActiveJob::Stats.reporter.increment('total.started') end def after_enqueue_stats ActiveJob::Stats.reporter.increment("#{self.class.queue_name}.enqueued") ActiveJob::Stats.reporter.increment("#{self.class}.enqueued") ActiveJob::Stats.reporter.increment('total.enqueued') end def after_perform_stats ActiveJob::Stats.reporter.increment("#{self.class.queue_name}.finished") ActiveJob::Stats.reporter.increment("#{self.class}.finished") ActiveJob::Stats.reporter.increment('total.finished') end delegate :benchmarked, :monitored, to: :class end end end end
module ActiveJob module Stats module Callbacks extend ActiveSupport::Concern included do before_enqueue :after_enqueue_stats, if: :monitored after_enqueue :after_enqueue_stats, if: :monitored before_perform :before_perform_stats, if: :monitored after_perform :after_perform_stats, if: :monitored around_perform :benchmark_stats, if: :benchmarked private def benchmark_stats require 'active_support/core_ext/benchmark' benchmark = Benchmark.ms { yield } ActiveJob::Stats.reporter.timing("#{queue_name}.processed", benchmark) ActiveJob::Stats.reporter.timing("#{self.class}.processed", benchmark) end def before_perform_stats ActiveJob::Stats.reporter.increment("#{queue_name}.started") ActiveJob::Stats.reporter.increment("#{self.class}.started") ActiveJob::Stats.reporter.increment('total.started') end def after_enqueue_stats ActiveJob::Stats.reporter.increment("#{queue_name}.enqueued") ActiveJob::Stats.reporter.increment("#{self.class}.enqueued") ActiveJob::Stats.reporter.increment('total.enqueued') end def after_perform_stats ActiveJob::Stats.reporter.increment("#{queue_name}.finished") ActiveJob::Stats.reporter.increment("#{self.class}.finished") ActiveJob::Stats.reporter.increment('total.finished') end delegate :benchmarked, :monitored, to: :class end end end end
Use job instance's queue_name instead of class's
fix:dev: Use job instance's queue_name instead of class's Two good reasons: - The job instance can be enqueued with a different queue_name than its class normally has. - The job class can pass a Proc to queue_name to dynamically determine the name. The queue_name is still set on the job instance.
Ruby
mit
seuros/activejob-stats
ruby
## Code Before: module ActiveJob module Stats module Callbacks extend ActiveSupport::Concern included do before_enqueue :after_enqueue_stats, if: :monitored after_enqueue :after_enqueue_stats, if: :monitored before_perform :before_perform_stats, if: :monitored after_perform :after_perform_stats, if: :monitored around_perform :benchmark_stats, if: :benchmarked private def benchmark_stats require 'active_support/core_ext/benchmark' benchmark = Benchmark.ms { yield } ActiveJob::Stats.reporter.timing("#{self.class.queue_name}.processed", benchmark) ActiveJob::Stats.reporter.timing("#{self.class}.processed", benchmark) end def before_perform_stats ActiveJob::Stats.reporter.increment("#{self.class.queue_name}.started") ActiveJob::Stats.reporter.increment("#{self.class}.started") ActiveJob::Stats.reporter.increment('total.started') end def after_enqueue_stats ActiveJob::Stats.reporter.increment("#{self.class.queue_name}.enqueued") ActiveJob::Stats.reporter.increment("#{self.class}.enqueued") ActiveJob::Stats.reporter.increment('total.enqueued') end def after_perform_stats ActiveJob::Stats.reporter.increment("#{self.class.queue_name}.finished") ActiveJob::Stats.reporter.increment("#{self.class}.finished") ActiveJob::Stats.reporter.increment('total.finished') end delegate :benchmarked, :monitored, to: :class end end end end ## Instruction: fix:dev: Use job instance's queue_name instead of class's Two good reasons: - The job instance can be enqueued with a different queue_name than its class normally has. - The job class can pass a Proc to queue_name to dynamically determine the name. The queue_name is still set on the job instance. ## Code After: module ActiveJob module Stats module Callbacks extend ActiveSupport::Concern included do before_enqueue :after_enqueue_stats, if: :monitored after_enqueue :after_enqueue_stats, if: :monitored before_perform :before_perform_stats, if: :monitored after_perform :after_perform_stats, if: :monitored around_perform :benchmark_stats, if: :benchmarked private def benchmark_stats require 'active_support/core_ext/benchmark' benchmark = Benchmark.ms { yield } ActiveJob::Stats.reporter.timing("#{queue_name}.processed", benchmark) ActiveJob::Stats.reporter.timing("#{self.class}.processed", benchmark) end def before_perform_stats ActiveJob::Stats.reporter.increment("#{queue_name}.started") ActiveJob::Stats.reporter.increment("#{self.class}.started") ActiveJob::Stats.reporter.increment('total.started') end def after_enqueue_stats ActiveJob::Stats.reporter.increment("#{queue_name}.enqueued") ActiveJob::Stats.reporter.increment("#{self.class}.enqueued") ActiveJob::Stats.reporter.increment('total.enqueued') end def after_perform_stats ActiveJob::Stats.reporter.increment("#{queue_name}.finished") ActiveJob::Stats.reporter.increment("#{self.class}.finished") ActiveJob::Stats.reporter.increment('total.finished') end delegate :benchmarked, :monitored, to: :class end end end end
6ecfb54eec58e078a3e405fc6652576fd9a3f229
dplace_app/static/partials/search/language.html
dplace_app/static/partials/search/language.html
<div ng-controller="LanguageCtrl"> <h4>Search by Language Family / Phylogeny</h4> <form class="form-inline" role="form"> <div class="panel panel-default" ng-repeat="languageFilter in language.languageFilters"> <div class="panel-heading"> <div class="row"> <div ng-repeat="levelObject in language.levels" class="form-group col-xs-4"> <select ng-model="languageFilter[levelObject.level - 1].selectedItem" class="form-control" style="width:100%" ng-change="selectionChanged(languageFilter,levelObject)" ng-options="item.name for item in languageFilter[levelObject.level - 1].items" > <option value="">{{ levelObject.name }}</option> </select> </div> </div> </div> <div class="panel-body"> <div ng-repeat="classification in languageFilter.classifications"> <span class="language-label">{{ classification.language.name }}</span> <input class="pull-right" type="checkbox" ng-model="classification.isSelected"> </div> </div> </div> <div> <button class="btn btn-primary form-control" ng-disabled="true" ng-click="doSearch()">{{ searchButton.text }} (not yet functional)</button> </div> </form> </div>
<div ng-controller="LanguageCtrl"> <h4>Search by Language Family</h4> <form class="form-inline" role="form"> <div class="panel panel-default" ng-repeat="languageFilter in language.languageFilters"> <div class="panel-heading"> <div class="row"> <div ng-repeat="levelObject in language.levels" class="form-group col-xs-4"> <select ng-model="languageFilter[levelObject.level - 1].selectedItem" class="form-control" style="width:100%" ng-change="selectionChanged(languageFilter,levelObject)" ng-options="item.name for item in languageFilter[levelObject.level - 1].items" > <option value="">{{ levelObject.name }}</option> </select> </div> </div> </div> <div class="panel-body"> <div ng-repeat="classification in languageFilter.classifications"> <span class="language-label">{{ classification.language.name }}</span> <input class="pull-right" type="checkbox" ng-model="classification.isSelected"> </div> </div> </div> <div> <button class="btn btn-primary form-control" ng-disabled="true" ng-click="doSearch()">{{ searchButton.text }} (not yet functional)</button> </div> </form> </div>
Remove phylogeny from search title
Remove phylogeny from search title
HTML
mit
shh-dlce/dplace,stefelisabeth/dplace,shh-dlce/dplace,D-PLACE/dplace,NESCent/dplace,D-PLACE/dplace,shh-dlce/dplace,D-PLACE/dplace,D-PLACE/dplace,NESCent/dplace,stefelisabeth/dplace,NESCent/dplace,stefelisabeth/dplace,shh-dlce/dplace,stefelisabeth/dplace,NESCent/dplace
html
## Code Before: <div ng-controller="LanguageCtrl"> <h4>Search by Language Family / Phylogeny</h4> <form class="form-inline" role="form"> <div class="panel panel-default" ng-repeat="languageFilter in language.languageFilters"> <div class="panel-heading"> <div class="row"> <div ng-repeat="levelObject in language.levels" class="form-group col-xs-4"> <select ng-model="languageFilter[levelObject.level - 1].selectedItem" class="form-control" style="width:100%" ng-change="selectionChanged(languageFilter,levelObject)" ng-options="item.name for item in languageFilter[levelObject.level - 1].items" > <option value="">{{ levelObject.name }}</option> </select> </div> </div> </div> <div class="panel-body"> <div ng-repeat="classification in languageFilter.classifications"> <span class="language-label">{{ classification.language.name }}</span> <input class="pull-right" type="checkbox" ng-model="classification.isSelected"> </div> </div> </div> <div> <button class="btn btn-primary form-control" ng-disabled="true" ng-click="doSearch()">{{ searchButton.text }} (not yet functional)</button> </div> </form> </div> ## Instruction: Remove phylogeny from search title ## Code After: <div ng-controller="LanguageCtrl"> <h4>Search by Language Family</h4> <form class="form-inline" role="form"> <div class="panel panel-default" ng-repeat="languageFilter in language.languageFilters"> <div class="panel-heading"> <div class="row"> <div ng-repeat="levelObject in language.levels" class="form-group col-xs-4"> <select ng-model="languageFilter[levelObject.level - 1].selectedItem" class="form-control" style="width:100%" ng-change="selectionChanged(languageFilter,levelObject)" ng-options="item.name for item in languageFilter[levelObject.level - 1].items" > <option value="">{{ levelObject.name }}</option> </select> </div> </div> </div> <div class="panel-body"> <div ng-repeat="classification in languageFilter.classifications"> <span class="language-label">{{ classification.language.name }}</span> <input class="pull-right" type="checkbox" ng-model="classification.isSelected"> </div> </div> </div> <div> <button class="btn btn-primary form-control" ng-disabled="true" ng-click="doSearch()">{{ searchButton.text }} (not yet functional)</button> </div> </form> </div>
e1d7c7583d2eb6f54438431c9e3abe26e02d630f
lumify-web-war/src/main/webapp/js/util/withAsyncQueue.js
lumify-web-war/src/main/webapp/js/util/withAsyncQueue.js
define([], function() { 'use strict'; return withAsyncQueue; function withAsyncQueue() { this.before('initialize', function() { var self = this, deferreds = {}, stacks = {}; this.setupAsyncQueue = function(name) { var stack = stacks[name] = [], objectData; self[name + 'Ready'] = function(callback) { if (callback) { // Legacy non-promise if (objectData) { callback.call(self, objectData); } else { stack.push(callback); } } else { return deferreds[name] || (deferreds[name] = $.Deferred()); } }; self[name + 'IsReady'] = function() { if (deferreds[name]) { return deferreds[name].isResolved(); } return objectData !== undefined; }; self[name + 'MarkReady'] = function(data) { if (!data) throw "No object passed to " + name + "MarkReady"; if (deferreds[name]) { deferreds[name].resolve(data); } else { deferreds[name] = $.Deferred(); deferreds[name].resolve(data); } objectData = data; stack.forEach(function(c) { c.call(self, objectData); }); stack.length = 0; }; self[name + 'Unload'] = function() { deferreds[name] = null; objectData = null; }; }; }); } });
define([], function() { 'use strict'; return withAsyncQueue; function withAsyncQueue() { this.before('initialize', function() { var self = this, deferreds = {}, stacks = {}; this.setupAsyncQueue = function(name) { var stack = stacks[name] = [], objectData; self[name + 'Ready'] = function(callback) { if (callback) { // Legacy non-promise if (objectData) { callback.call(self, objectData); } else { stack.push(callback); } } else { return deferreds[name] || (deferreds[name] = $.Deferred()); } }; self[name + 'IsReady'] = function() { if (deferreds[name]) { return deferreds[name].state() == 'resolved'; } return objectData !== undefined; }; self[name + 'MarkReady'] = function(data) { if (!data) throw "No object passed to " + name + "MarkReady"; if (deferreds[name]) { deferreds[name].resolve(data); } else { deferreds[name] = $.Deferred(); deferreds[name].resolve(data); } objectData = data; stack.forEach(function(c) { c.call(self, objectData); }); stack.length = 0; }; self[name + 'Unload'] = function() { deferreds[name] = null; objectData = null; }; }; }); } });
Fix error from removed api after upgrading jquery
Fix error from removed api after upgrading jquery
JavaScript
apache-2.0
j-bernardo/lumify,RavenB/lumify,Steimel/lumify,TeamUDS/lumify,Steimel/lumify,RavenB/lumify,TeamUDS/lumify,dvdnglnd/lumify,lumifyio/lumify,bings/lumify,j-bernardo/lumify,lumifyio/lumify,j-bernardo/lumify,lumifyio/lumify,dvdnglnd/lumify,RavenB/lumify,Steimel/lumify,dvdnglnd/lumify,lumifyio/lumify,bings/lumify,bings/lumify,bings/lumify,Steimel/lumify,TeamUDS/lumify,RavenB/lumify,TeamUDS/lumify,RavenB/lumify,j-bernardo/lumify,dvdnglnd/lumify,lumifyio/lumify,dvdnglnd/lumify,TeamUDS/lumify,bings/lumify,Steimel/lumify,j-bernardo/lumify
javascript
## Code Before: define([], function() { 'use strict'; return withAsyncQueue; function withAsyncQueue() { this.before('initialize', function() { var self = this, deferreds = {}, stacks = {}; this.setupAsyncQueue = function(name) { var stack = stacks[name] = [], objectData; self[name + 'Ready'] = function(callback) { if (callback) { // Legacy non-promise if (objectData) { callback.call(self, objectData); } else { stack.push(callback); } } else { return deferreds[name] || (deferreds[name] = $.Deferred()); } }; self[name + 'IsReady'] = function() { if (deferreds[name]) { return deferreds[name].isResolved(); } return objectData !== undefined; }; self[name + 'MarkReady'] = function(data) { if (!data) throw "No object passed to " + name + "MarkReady"; if (deferreds[name]) { deferreds[name].resolve(data); } else { deferreds[name] = $.Deferred(); deferreds[name].resolve(data); } objectData = data; stack.forEach(function(c) { c.call(self, objectData); }); stack.length = 0; }; self[name + 'Unload'] = function() { deferreds[name] = null; objectData = null; }; }; }); } }); ## Instruction: Fix error from removed api after upgrading jquery ## Code After: define([], function() { 'use strict'; return withAsyncQueue; function withAsyncQueue() { this.before('initialize', function() { var self = this, deferreds = {}, stacks = {}; this.setupAsyncQueue = function(name) { var stack = stacks[name] = [], objectData; self[name + 'Ready'] = function(callback) { if (callback) { // Legacy non-promise if (objectData) { callback.call(self, objectData); } else { stack.push(callback); } } else { return deferreds[name] || (deferreds[name] = $.Deferred()); } }; self[name + 'IsReady'] = function() { if (deferreds[name]) { return deferreds[name].state() == 'resolved'; } return objectData !== undefined; }; self[name + 'MarkReady'] = function(data) { if (!data) throw "No object passed to " + name + "MarkReady"; if (deferreds[name]) { deferreds[name].resolve(data); } else { deferreds[name] = $.Deferred(); deferreds[name].resolve(data); } objectData = data; stack.forEach(function(c) { c.call(self, objectData); }); stack.length = 0; }; self[name + 'Unload'] = function() { deferreds[name] = null; objectData = null; }; }; }); } });
0a249892a80422e2d919ae1049e2cccfb8adccbb
modules/preferences/src/appleMain/kotlin/splitties/preferences/Changes.kt
modules/preferences/src/appleMain/kotlin/splitties/preferences/Changes.kt
/* * Copyright 2019 Louis Cognault Ayeva Derman. Use of this source code is governed by the Apache 2.0 license. */ package splitties.preferences import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.channels.awaitClose import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.channelFlow import kotlinx.coroutines.flow.conflate import platform.Foundation.NSNotificationCenter import platform.Foundation.NSUserDefaultsDidChangeNotification @UseExperimental(ExperimentalCoroutinesApi::class) internal actual fun SharedPreferences.changesFlow( key: String, emitAfterRegister: Boolean ): Flow<Unit> = channelFlow<Unit> { if (this@changesFlow is NSUserDefaultsBackedSharedPreferences && useNotificationCenterForChanges ) { val defaultNotificationCenter = NSNotificationCenter.defaultCenter val observer = defaultNotificationCenter.addObserverForName( name = NSUserDefaultsDidChangeNotification, `object` = userDefaults, queue = null ) { runCatching { offer(Unit) } } if (emitAfterRegister) runCatching { offer(Unit) } awaitClose { defaultNotificationCenter.removeObserver(observer) } } else { val listener = OnSharedPreferenceChangeListener { _, changedKey -> if (key == changedKey) runCatching { offer(Unit) } } registerOnSharedPreferenceChangeListener(listener) if (emitAfterRegister) runCatching { offer(Unit) } awaitClose { unregisterOnSharedPreferenceChangeListener(listener) } } }.conflate()
/* * Copyright 2019 Louis Cognault Ayeva Derman. Use of this source code is governed by the Apache 2.0 license. */ package splitties.preferences import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.channels.awaitClose import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.channelFlow import kotlinx.coroutines.flow.conflate import platform.Foundation.NSNotificationCenter import platform.Foundation.NSOperationQueue import platform.Foundation.NSUserDefaultsDidChangeNotification import splitties.mainthread.isMainThread @UseExperimental(ExperimentalCoroutinesApi::class) internal actual fun SharedPreferences.changesFlow( key: String, emitAfterRegister: Boolean ): Flow<Unit> = channelFlow<Unit> { if (this@changesFlow is NSUserDefaultsBackedSharedPreferences && useNotificationCenterForChanges ) { val defaultNotificationCenter = NSNotificationCenter.defaultCenter val observer = defaultNotificationCenter.addObserverForName( name = NSUserDefaultsDidChangeNotification, `object` = userDefaults, queue = if (isMainThread) NSOperationQueue.mainQueue else null ) { runCatching { offer(Unit) } } if (emitAfterRegister) runCatching { offer(Unit) } awaitClose { defaultNotificationCenter.removeObserver(observer) } } else { val listener = OnSharedPreferenceChangeListener { _, changedKey -> if (key == changedKey) runCatching { offer(Unit) } } registerOnSharedPreferenceChangeListener(listener) if (emitAfterRegister) runCatching { offer(Unit) } awaitClose { unregisterOnSharedPreferenceChangeListener(listener) } } }.conflate()
Use NSOperationQueue.mainQueue if on main thread
Use NSOperationQueue.mainQueue if on main thread
Kotlin
apache-2.0
LouisCAD/Splitties,LouisCAD/Splitties,LouisCAD/Splitties
kotlin
## Code Before: /* * Copyright 2019 Louis Cognault Ayeva Derman. Use of this source code is governed by the Apache 2.0 license. */ package splitties.preferences import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.channels.awaitClose import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.channelFlow import kotlinx.coroutines.flow.conflate import platform.Foundation.NSNotificationCenter import platform.Foundation.NSUserDefaultsDidChangeNotification @UseExperimental(ExperimentalCoroutinesApi::class) internal actual fun SharedPreferences.changesFlow( key: String, emitAfterRegister: Boolean ): Flow<Unit> = channelFlow<Unit> { if (this@changesFlow is NSUserDefaultsBackedSharedPreferences && useNotificationCenterForChanges ) { val defaultNotificationCenter = NSNotificationCenter.defaultCenter val observer = defaultNotificationCenter.addObserverForName( name = NSUserDefaultsDidChangeNotification, `object` = userDefaults, queue = null ) { runCatching { offer(Unit) } } if (emitAfterRegister) runCatching { offer(Unit) } awaitClose { defaultNotificationCenter.removeObserver(observer) } } else { val listener = OnSharedPreferenceChangeListener { _, changedKey -> if (key == changedKey) runCatching { offer(Unit) } } registerOnSharedPreferenceChangeListener(listener) if (emitAfterRegister) runCatching { offer(Unit) } awaitClose { unregisterOnSharedPreferenceChangeListener(listener) } } }.conflate() ## Instruction: Use NSOperationQueue.mainQueue if on main thread ## Code After: /* * Copyright 2019 Louis Cognault Ayeva Derman. Use of this source code is governed by the Apache 2.0 license. */ package splitties.preferences import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.channels.awaitClose import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.channelFlow import kotlinx.coroutines.flow.conflate import platform.Foundation.NSNotificationCenter import platform.Foundation.NSOperationQueue import platform.Foundation.NSUserDefaultsDidChangeNotification import splitties.mainthread.isMainThread @UseExperimental(ExperimentalCoroutinesApi::class) internal actual fun SharedPreferences.changesFlow( key: String, emitAfterRegister: Boolean ): Flow<Unit> = channelFlow<Unit> { if (this@changesFlow is NSUserDefaultsBackedSharedPreferences && useNotificationCenterForChanges ) { val defaultNotificationCenter = NSNotificationCenter.defaultCenter val observer = defaultNotificationCenter.addObserverForName( name = NSUserDefaultsDidChangeNotification, `object` = userDefaults, queue = if (isMainThread) NSOperationQueue.mainQueue else null ) { runCatching { offer(Unit) } } if (emitAfterRegister) runCatching { offer(Unit) } awaitClose { defaultNotificationCenter.removeObserver(observer) } } else { val listener = OnSharedPreferenceChangeListener { _, changedKey -> if (key == changedKey) runCatching { offer(Unit) } } registerOnSharedPreferenceChangeListener(listener) if (emitAfterRegister) runCatching { offer(Unit) } awaitClose { unregisterOnSharedPreferenceChangeListener(listener) } } }.conflate()
98bdb678a9092c5c19bc2b379cca74a2ed33c457
libqtile/layout/subverttile.py
libqtile/layout/subverttile.py
from base import SubLayout, Rect from sublayouts import HorizontalStack from subtile import SubTile class SubVertTile(SubTile): arrangements = ["top", "bottom"] def _init_sublayouts(self): ratio = self.ratio expand = self.expand master_windows = self.master_windows arrangement = self.arrangement class MasterWindows(HorizontalStack): def filter(self, client): return self.index_of(client) < master_windows def request_rectangle(self, r, windows): return (r, Rect()) class SlaveWindows(HorizontalStack): def filter(self, client): return self.index_of(client) >= master_windows def request_rectangle(self, r, windows): if self.autohide and not windows: return (Rect(), r) else: if arrangement == "top": rmaster, rslave = r.split_horizontal(ratio=ratio) else: rslave, rmaster = r.split_horizontal(ratio=(1-ratio)) return (rslave, rmaster) self.sublayouts.append(SlaveWindows(self.clientStack, self.theme, parent=self, autohide=self.expand ) ) self.sublayouts.append(MasterWindows(self.clientStack, self.theme, parent=self, autohide=self.expand ) )
from base import SubLayout, Rect from sublayouts import HorizontalStack from subtile import SubTile class SubVertTile(SubTile): arrangements = ["top", "bottom"] def _init_sublayouts(self): class MasterWindows(HorizontalStack): def filter(self, client): return self.index_of(client) < self.parent.master_windows def request_rectangle(self, r, windows): return (r, Rect()) class SlaveWindows(HorizontalStack): def filter(self, client): return self.index_of(client) >= self.parent.master_windows def request_rectangle(self, r, windows): if self.autohide and not windows: return (Rect(), r) else: if self.parent.arrangement == "top": rmaster, rslave = r.split_horizontal(ratio=self.parent.ratio) else: rslave, rmaster = r.split_horizontal(ratio=(1-self.parent.ratio)) return (rslave, rmaster) self.sublayouts.append(SlaveWindows(self.clientStack, self.theme, parent=self, autohide=self.expand ) ) self.sublayouts.append(MasterWindows(self.clientStack, self.theme, parent=self, autohide=self.expand ) )
Refactor SubVertTile - make sublayout use the parents' variables
Refactor SubVertTile - make sublayout use the parents' variables
Python
mit
rxcomm/qtile,de-vri-es/qtile,EndPointCorp/qtile,zordsdavini/qtile,bavardage/qtile,nxnfufunezn/qtile,encukou/qtile,andrewyoung1991/qtile,ramnes/qtile,himaaaatti/qtile,de-vri-es/qtile,frostidaho/qtile,encukou/qtile,andrewyoung1991/qtile,w1ndy/qtile,frostidaho/qtile,nxnfufunezn/qtile,StephenBarnes/qtile,farebord/qtile,kopchik/qtile,rxcomm/qtile,jdowner/qtile,flacjacket/qtile,w1ndy/qtile,cortesi/qtile,aniruddhkanojia/qtile,qtile/qtile,himaaaatti/qtile,ramnes/qtile,xplv/qtile,flacjacket/qtile,soulchainer/qtile,kynikos/qtile,dequis/qtile,cortesi/qtile,jdowner/qtile,kseistrup/qtile,kiniou/qtile,apinsard/qtile,kiniou/qtile,kynikos/qtile,qtile/qtile,kopchik/qtile,kseistrup/qtile,tych0/qtile,tych0/qtile,apinsard/qtile,xplv/qtile,zordsdavini/qtile,soulchainer/qtile,dequis/qtile,farebord/qtile,aniruddhkanojia/qtile,EndPointCorp/qtile,StephenBarnes/qtile
python
## Code Before: from base import SubLayout, Rect from sublayouts import HorizontalStack from subtile import SubTile class SubVertTile(SubTile): arrangements = ["top", "bottom"] def _init_sublayouts(self): ratio = self.ratio expand = self.expand master_windows = self.master_windows arrangement = self.arrangement class MasterWindows(HorizontalStack): def filter(self, client): return self.index_of(client) < master_windows def request_rectangle(self, r, windows): return (r, Rect()) class SlaveWindows(HorizontalStack): def filter(self, client): return self.index_of(client) >= master_windows def request_rectangle(self, r, windows): if self.autohide and not windows: return (Rect(), r) else: if arrangement == "top": rmaster, rslave = r.split_horizontal(ratio=ratio) else: rslave, rmaster = r.split_horizontal(ratio=(1-ratio)) return (rslave, rmaster) self.sublayouts.append(SlaveWindows(self.clientStack, self.theme, parent=self, autohide=self.expand ) ) self.sublayouts.append(MasterWindows(self.clientStack, self.theme, parent=self, autohide=self.expand ) ) ## Instruction: Refactor SubVertTile - make sublayout use the parents' variables ## Code After: from base import SubLayout, Rect from sublayouts import HorizontalStack from subtile import SubTile class SubVertTile(SubTile): arrangements = ["top", "bottom"] def _init_sublayouts(self): class MasterWindows(HorizontalStack): def filter(self, client): return self.index_of(client) < self.parent.master_windows def request_rectangle(self, r, windows): return (r, Rect()) class SlaveWindows(HorizontalStack): def filter(self, client): return self.index_of(client) >= self.parent.master_windows def request_rectangle(self, r, windows): if self.autohide and not windows: return (Rect(), r) else: if self.parent.arrangement == "top": rmaster, rslave = r.split_horizontal(ratio=self.parent.ratio) else: rslave, rmaster = r.split_horizontal(ratio=(1-self.parent.ratio)) return (rslave, rmaster) self.sublayouts.append(SlaveWindows(self.clientStack, self.theme, parent=self, autohide=self.expand ) ) self.sublayouts.append(MasterWindows(self.clientStack, self.theme, parent=self, autohide=self.expand ) )
a06739083e48bdc11823e5299823aefc54c5501f
lib/fog/google/models/compute/images.rb
lib/fog/google/models/compute/images.rb
require 'fog/core/collection' require 'fog/google/models/compute/image' module Fog module Compute class Google class Images < Fog::Collection model Fog::Compute::Google::Image GLOBAL_PROJECTS = [ 'google', 'debian-cloud', 'centos-cloud', ] def all data = [] all_projects = GLOBAL_PROJECTS + [ self.service.project ] all_projects.each do |project| images = service.list_images(project).body["items"] || [] # Keep track of the project in which we found the image(s) images.each { |img| img[:project] = project } data += images end load(data) end def get(identity) # Search own project before global projects all_projects = [ self.service.project ] + GLOBAL_PROJECTS data = nil all_projects.each do |project| begin data = service.get_image(identity, project).body data[:project] = project rescue Fog::Errors::Error next else break end end # If it wasn't found in any project, raise if data.nil? raise Fog::Errors::Error.new('Unable to find the specified image '\ 'in the following projects: '\ "#{all_projects.join(', ')}") end new(data) end end end end end
require 'fog/core/collection' require 'fog/google/models/compute/image' module Fog module Compute class Google class Images < Fog::Collection model Fog::Compute::Google::Image GLOBAL_PROJECTS = [ 'google', 'debian-cloud', 'centos-cloud', 'rhel-cloud', ] def all data = [] all_projects = GLOBAL_PROJECTS + [ self.service.project ] all_projects.each do |project| images = service.list_images(project).body["items"] || [] # Keep track of the project in which we found the image(s) images.each { |img| img[:project] = project } data += images end load(data) end def get(identity) # Search own project before global projects all_projects = [ self.service.project ] + GLOBAL_PROJECTS data = nil all_projects.each do |project| begin data = service.get_image(identity, project).body data[:project] = project rescue Fog::Errors::Error next else break end end # If it wasn't found in any project, raise if data.nil? raise Fog::Errors::Error.new('Unable to find the specified image '\ 'in the following projects: '\ "#{all_projects.join(', ')}") end new(data) end end end end end
Add rhel-cloud to project search list
[google][compute] Add rhel-cloud to project search list
Ruby
mit
github/fog,NETWAYS/fog,ack/fog,covario-cdiaz/fog,sapcc/fog,surminus/fog,bryanl/fog,martinb3/fog,brandondunne/fog,dhague/fog,b0ric/fog,brilliomsinterop/fog,MSOpenTech/fog,lwander/fog,mavenlink/fog,yyuu/fog,unorthodoxgeek/fog,phillbaker/fog,eLobato/fog,petems/fog,phillbaker/fog,pravi/fog,joshmyers/fog,covario-cdiaz/fog,ManageIQ/fog,icco/fog,adamleff/fog,petems/fog,brilliomsinterop/fog,theforeman/fog,pravi/fog,ack/fog,ManageIQ/fog,mohitsethi/fog,dLobatog/fog,zephyrean/fog,fog/fog,Programatica/fog,github/fog,dhague/fog,alphagov/fog,rackspace/fog,theforeman/fog,mitchlloyd/fog,papedaniel/fog,backupify/fog,mitchlloyd/fog,runtimerevolution/fog,joshmyers/fog,sapcc/fog,brilliomsinterop/fog,pyama86/fog,runtimerevolution/fog,dustacio/fog,lwander/fog,glennpratt/fog,unorthodoxgeek/fog,asebastian-r7/fog,eLobato/fog,surminus/fog,plribeiro3000/fog,nandhanurrevanth/fog,MSOpenTech/fog,alphagov/fog,sideci-sample/sideci-sample-fog,icco/fog,adecarolis/fog,Ladas/fog,dtdream/fog,SpryBTS/fog,glennpratt/fog,plribeiro3000/fog,nandhanurrevanth/fog,joshisa/fog,SpryBTS/fog,nicolasbrechet/fog,NETWAYS/fog,mavenlink/fog,phillbaker/fog,asebastian-r7/fog,rackspace/fog,bdunne/fog,nalabjp/fog,kongslund/fog,cocktail-io/fog,yyuu/fog,duhast/fog,adamleff/fog,displague/fog,dustacio/fog,mohitsethi/fog,papedaniel/fog,10io/fog,duhast/fog,TerryHowe/fog,joshisa/fog,seanhandley/fog,kongslund/fog,pyama86/fog,TerryHowe/fog,nicolasbrechet/fog,nandhanurrevanth/fog,backupify/fog,b0ric/fog,zephyrean/fog,dtdream/fog,Ladas/fog,zephyrean/fog,Programatica/fog,fog/fog,dLobatog/fog,martinb3/fog,seanhandley/fog,cocktail-io/fog,10io/fog,nalabjp/fog,adecarolis/fog,bryanl/fog,displague/fog,sideci-sample/sideci-sample-fog
ruby
## Code Before: require 'fog/core/collection' require 'fog/google/models/compute/image' module Fog module Compute class Google class Images < Fog::Collection model Fog::Compute::Google::Image GLOBAL_PROJECTS = [ 'google', 'debian-cloud', 'centos-cloud', ] def all data = [] all_projects = GLOBAL_PROJECTS + [ self.service.project ] all_projects.each do |project| images = service.list_images(project).body["items"] || [] # Keep track of the project in which we found the image(s) images.each { |img| img[:project] = project } data += images end load(data) end def get(identity) # Search own project before global projects all_projects = [ self.service.project ] + GLOBAL_PROJECTS data = nil all_projects.each do |project| begin data = service.get_image(identity, project).body data[:project] = project rescue Fog::Errors::Error next else break end end # If it wasn't found in any project, raise if data.nil? raise Fog::Errors::Error.new('Unable to find the specified image '\ 'in the following projects: '\ "#{all_projects.join(', ')}") end new(data) end end end end end ## Instruction: [google][compute] Add rhel-cloud to project search list ## Code After: require 'fog/core/collection' require 'fog/google/models/compute/image' module Fog module Compute class Google class Images < Fog::Collection model Fog::Compute::Google::Image GLOBAL_PROJECTS = [ 'google', 'debian-cloud', 'centos-cloud', 'rhel-cloud', ] def all data = [] all_projects = GLOBAL_PROJECTS + [ self.service.project ] all_projects.each do |project| images = service.list_images(project).body["items"] || [] # Keep track of the project in which we found the image(s) images.each { |img| img[:project] = project } data += images end load(data) end def get(identity) # Search own project before global projects all_projects = [ self.service.project ] + GLOBAL_PROJECTS data = nil all_projects.each do |project| begin data = service.get_image(identity, project).body data[:project] = project rescue Fog::Errors::Error next else break end end # If it wasn't found in any project, raise if data.nil? raise Fog::Errors::Error.new('Unable to find the specified image '\ 'in the following projects: '\ "#{all_projects.join(', ')}") end new(data) end end end end end
2c53233bfe77601c6fc0a4a50226d5641709863a
lib/data_mapper/relationship/one_to_many.rb
lib/data_mapper/relationship/one_to_many.rb
module DataMapper class Relationship class OneToMany < self module Iterator # Iterate over the loaded domain objects # # TODO: refactor this and add support for multi-include # # @see Mapper::Relation#each # # @example # # DataMapper[Person].include(:tasks).each do |person| # person.tasks.each do |task| # puts task.name # end # end # # @yield [object] the loaded domain objects # # @yieldparam [Object] object # the loaded domain object that is yielded # # @return [self] # # @api public def each return to_enum unless block_given? tuples = @relation.to_a parent_key = @attributes.key name = @attributes.detect { |attribute| attribute.kind_of?(Mapper::Attribute::EmbeddedCollection) }.name parents = tuples.each_with_object({}) do |tuple, hash| key = parent_key.map { |attribute| tuple[attribute.field] } hash[key] = @attributes.primitives.each_with_object({}) { |attribute, parent| parent[attribute.field] = tuple[attribute.field] } end parents.each do |key, parent| parent[name] = tuples.map do |tuple| current_key = parent_key.map { |attribute| tuple[attribute.field] } if key == current_key tuple end end.compact end parents.each_value { |parent| yield(load(parent)) } self end end # module Iterator # Returns if the relationship has collection target # # @return [Boolean] # # @api private def collection_target? true end # @see Options#default_source_key # def default_source_key :id end # @see Options#default_target_key # def default_target_key self.class.foreign_key_name(source_model.name) end end # class OneToMany end # class Relationship end # module DataMapper
module DataMapper class Relationship class OneToMany < self # Returns if the relationship has collection target # # @return [Boolean] # # @api private def collection_target? true end # @see Options#default_source_key # def default_source_key :id end # @see Options#default_target_key # def default_target_key self.class.foreign_key_name(source_model.name) end end # class OneToMany end # class Relationship end # module DataMapper
Remove Iterator from OneToMany since it was moved to a separate file
Remove Iterator from OneToMany since it was moved to a separate file
Ruby
mit
cored/rom,pvcarrera/rom,denyago/rom,endash/rom,pdswan/rom,dcarral/rom,pxlpnk/rom,dekz/rom,rom-rb/rom,rom-rb/rom,Snuff/rom,jeremyf/rom,vrish88/rom,kwando/rom,rom-rb/rom
ruby
## Code Before: module DataMapper class Relationship class OneToMany < self module Iterator # Iterate over the loaded domain objects # # TODO: refactor this and add support for multi-include # # @see Mapper::Relation#each # # @example # # DataMapper[Person].include(:tasks).each do |person| # person.tasks.each do |task| # puts task.name # end # end # # @yield [object] the loaded domain objects # # @yieldparam [Object] object # the loaded domain object that is yielded # # @return [self] # # @api public def each return to_enum unless block_given? tuples = @relation.to_a parent_key = @attributes.key name = @attributes.detect { |attribute| attribute.kind_of?(Mapper::Attribute::EmbeddedCollection) }.name parents = tuples.each_with_object({}) do |tuple, hash| key = parent_key.map { |attribute| tuple[attribute.field] } hash[key] = @attributes.primitives.each_with_object({}) { |attribute, parent| parent[attribute.field] = tuple[attribute.field] } end parents.each do |key, parent| parent[name] = tuples.map do |tuple| current_key = parent_key.map { |attribute| tuple[attribute.field] } if key == current_key tuple end end.compact end parents.each_value { |parent| yield(load(parent)) } self end end # module Iterator # Returns if the relationship has collection target # # @return [Boolean] # # @api private def collection_target? true end # @see Options#default_source_key # def default_source_key :id end # @see Options#default_target_key # def default_target_key self.class.foreign_key_name(source_model.name) end end # class OneToMany end # class Relationship end # module DataMapper ## Instruction: Remove Iterator from OneToMany since it was moved to a separate file ## Code After: module DataMapper class Relationship class OneToMany < self # Returns if the relationship has collection target # # @return [Boolean] # # @api private def collection_target? true end # @see Options#default_source_key # def default_source_key :id end # @see Options#default_target_key # def default_target_key self.class.foreign_key_name(source_model.name) end end # class OneToMany end # class Relationship end # module DataMapper
1f1d294a1a5a467554d873b4c076d79fbf7b42fb
Sources/FluentTester/Tester+InsertAndFind.swift
Sources/FluentTester/Tester+InsertAndFind.swift
extension Tester { public func testInsertAndFind() throws { Atom.database = database try Atom.prepare(database) defer { try! Atom.revert(database) } let hydrogen = Atom(id: "asdf", name: "Hydrogen", protons: 1, weight: 1.007) guard hydrogen.exists == false else { throw Error.failed("Exists should be false since not yet saved.") } try hydrogen.save() guard hydrogen.id?.string == "asdf" else { throw Error.failed("Saved ID not equal to set id.") } guard hydrogen.exists == true else { throw Error.failed("Exists should be true since just saved.") } guard let id = hydrogen.id else { throw Error.failed("ID not set on Atom after save.") } guard let found = try Atom.find(id) else { throw Error.failed("Could not find Atom by id.") } guard hydrogen.id == found.id else { throw Error.failed("ID retrieved different than what was saved.") } guard hydrogen.name == found.name else { throw Error.failed("Name retrieved different than what was saved.") } guard hydrogen.protons == found.protons else { throw Error.failed("Protons retrieved different than what was saved.") } guard hydrogen.weight == found.weight else { throw Error.failed("Weight retrieved different than what was saved.") } } }
extension Tester { public func testInsertAndFind() throws { Atom.database = database try Atom.prepare(database) defer { try! Atom.revert(database) } let uuid = UUID() let hydrogen = Atom(id: Identifier(uuid.uuidString), name: "Hydrogen", protons: 1, weight: 1.007) guard hydrogen.exists == false else { throw Error.failed("Exists should be false since not yet saved.") } try hydrogen.save() guard hydrogen.id?.string?.lowercased() == uuid.uuidString.lowercased() else { throw Error.failed("Saved ID not equal to set id.") } guard hydrogen.exists == true else { throw Error.failed("Exists should be true since just saved.") } guard let id = hydrogen.id else { throw Error.failed("ID not set on Atom after save.") } guard let found = try Atom.find(id) else { throw Error.failed("Could not find Atom by id.") } guard hydrogen.id == found.id else { throw Error.failed("ID retrieved different than what was saved.") } guard hydrogen.name == found.name else { throw Error.failed("Name retrieved different than what was saved.") } guard hydrogen.protons == found.protons else { throw Error.failed("Protons retrieved different than what was saved.") } guard hydrogen.weight == found.weight else { throw Error.failed("Weight retrieved different than what was saved.") } } }
Use valid UUID for insert-and-fix
Use valid UUID for insert-and-fix Postgres – unlike MySQL – actually validates the UUIDs sent as values, so the tests of postgresql-driver were silently broken by the Fluent 2.0.1 release. This commit fixes the test by using a valid UUID instead of just `"asdf"`. I noticed that PG returns UUID fields as all lowercase, so I changed the comparison to be case insensitive. (It shouldn't be a problem as we're talking about the string representation of an otherwise fixed binary entity and the hex numbers still match.)
Swift
mit
qutheory/fluent,vapor/fluent
swift
## Code Before: extension Tester { public func testInsertAndFind() throws { Atom.database = database try Atom.prepare(database) defer { try! Atom.revert(database) } let hydrogen = Atom(id: "asdf", name: "Hydrogen", protons: 1, weight: 1.007) guard hydrogen.exists == false else { throw Error.failed("Exists should be false since not yet saved.") } try hydrogen.save() guard hydrogen.id?.string == "asdf" else { throw Error.failed("Saved ID not equal to set id.") } guard hydrogen.exists == true else { throw Error.failed("Exists should be true since just saved.") } guard let id = hydrogen.id else { throw Error.failed("ID not set on Atom after save.") } guard let found = try Atom.find(id) else { throw Error.failed("Could not find Atom by id.") } guard hydrogen.id == found.id else { throw Error.failed("ID retrieved different than what was saved.") } guard hydrogen.name == found.name else { throw Error.failed("Name retrieved different than what was saved.") } guard hydrogen.protons == found.protons else { throw Error.failed("Protons retrieved different than what was saved.") } guard hydrogen.weight == found.weight else { throw Error.failed("Weight retrieved different than what was saved.") } } } ## Instruction: Use valid UUID for insert-and-fix Postgres – unlike MySQL – actually validates the UUIDs sent as values, so the tests of postgresql-driver were silently broken by the Fluent 2.0.1 release. This commit fixes the test by using a valid UUID instead of just `"asdf"`. I noticed that PG returns UUID fields as all lowercase, so I changed the comparison to be case insensitive. (It shouldn't be a problem as we're talking about the string representation of an otherwise fixed binary entity and the hex numbers still match.) ## Code After: extension Tester { public func testInsertAndFind() throws { Atom.database = database try Atom.prepare(database) defer { try! Atom.revert(database) } let uuid = UUID() let hydrogen = Atom(id: Identifier(uuid.uuidString), name: "Hydrogen", protons: 1, weight: 1.007) guard hydrogen.exists == false else { throw Error.failed("Exists should be false since not yet saved.") } try hydrogen.save() guard hydrogen.id?.string?.lowercased() == uuid.uuidString.lowercased() else { throw Error.failed("Saved ID not equal to set id.") } guard hydrogen.exists == true else { throw Error.failed("Exists should be true since just saved.") } guard let id = hydrogen.id else { throw Error.failed("ID not set on Atom after save.") } guard let found = try Atom.find(id) else { throw Error.failed("Could not find Atom by id.") } guard hydrogen.id == found.id else { throw Error.failed("ID retrieved different than what was saved.") } guard hydrogen.name == found.name else { throw Error.failed("Name retrieved different than what was saved.") } guard hydrogen.protons == found.protons else { throw Error.failed("Protons retrieved different than what was saved.") } guard hydrogen.weight == found.weight else { throw Error.failed("Weight retrieved different than what was saved.") } } }
b16dfa38b3fdf6443eab90fe7f328435aa9163ac
src/javascript/binary/websocket_pages/user/account/settings/iphistory/iphistory.init.js
src/javascript/binary/websocket_pages/user/account/settings/iphistory/iphistory.init.js
var IPHistory = (function() { 'use strict'; var no_messages_error = "Your account has no Login/Logout activity."; function updateTable(batch) { IPHistoryUI.updateTable(batch); if (batch.length) { return; } $('#login-history-table tbody') .append($('<tr/>', {class: 'flex-tr'}) .append($('<td/>', {colspan: 6}) .append($('<p/>', { class: 'notice-msg center-text', text: text.localize(no_messages_error) }) ) ) ); } function handler(response) { if (response.error && response.error.message) { document.getElementById('err').textContent = response.error.message; return; } updateTable(response.login_history); } // localize, title, create tables // register the callback on IPHistoryQueue function init() { var titleElement = document.getElementById('login_history-title').firstElementChild; titleElement.textContent = text.localize(titleElement.textContent); IPHistoryUI.createEmptyTable().appendTo('#login_history-ws-container'); IPHistoryQueue.register(handler); IPHistoryQueue.fetchNext({limit: 50}); } function clean() { $('#login_history-ws-container .error-msg').text(''); IPHistoryUI.clearTableContent(); IPHistoryQueue.clear(); } return { init: init, clean: clean, }; })();
var IPHistory = (function() { 'use strict'; var no_messages_error = "Your account has no Login/Logout activity."; function updateTable(batch) { IPHistoryUI.updateTable(batch); if (batch.length) { return; } $('#login-history-table tbody') .append($('<tr/>', {class: 'flex-tr'}) .append($('<td/>', {colspan: 6}) .append($('<p/>', { class: 'notice-msg center-text', text: text.localize(no_messages_error) }) ) ) ); } function handler(response) { if (response.error && response.error.message) { $('#err').text(response.error.message); return; } updateTable(response.login_history); } // localize, title, create tables // register the callback on IPHistoryQueue function init() { var $title = $('#login_history-title').children().first(); $title.text(text.localize($title.text())); IPHistoryUI.createEmptyTable().appendTo('#login_history-ws-container'); IPHistoryQueue.register(handler); IPHistoryQueue.fetchNext({limit: 50}); } function clean() { $('#login_history-ws-container .error-msg').text(''); IPHistoryUI.clearTableContent(); IPHistoryQueue.clear(); } return { init: init, clean: clean, }; })();
Use jQuery for misc. UI code
Use jQuery for misc. UI code
JavaScript
apache-2.0
teo-binary/binary-static,4p00rv/binary-static,negar-binary/binary-static,binary-com/binary-static,ashkanx/binary-static,fayland/binary-static,ashkanx/binary-static,fayland/binary-static,raunakkathuria/binary-static,teo-binary/binary-static,fayland/binary-static,fayland/binary-static,raunakkathuria/binary-static,kellybinary/binary-static,binary-com/binary-static,teo-binary/binary-static,negar-binary/binary-static,kellybinary/binary-static,binary-com/binary-static,binary-static-deployed/binary-static,binary-static-deployed/binary-static,teo-binary/binary-static,4p00rv/binary-static,binary-static-deployed/binary-static,raunakkathuria/binary-static,negar-binary/binary-static,4p00rv/binary-static,kellybinary/binary-static,ashkanx/binary-static
javascript
## Code Before: var IPHistory = (function() { 'use strict'; var no_messages_error = "Your account has no Login/Logout activity."; function updateTable(batch) { IPHistoryUI.updateTable(batch); if (batch.length) { return; } $('#login-history-table tbody') .append($('<tr/>', {class: 'flex-tr'}) .append($('<td/>', {colspan: 6}) .append($('<p/>', { class: 'notice-msg center-text', text: text.localize(no_messages_error) }) ) ) ); } function handler(response) { if (response.error && response.error.message) { document.getElementById('err').textContent = response.error.message; return; } updateTable(response.login_history); } // localize, title, create tables // register the callback on IPHistoryQueue function init() { var titleElement = document.getElementById('login_history-title').firstElementChild; titleElement.textContent = text.localize(titleElement.textContent); IPHistoryUI.createEmptyTable().appendTo('#login_history-ws-container'); IPHistoryQueue.register(handler); IPHistoryQueue.fetchNext({limit: 50}); } function clean() { $('#login_history-ws-container .error-msg').text(''); IPHistoryUI.clearTableContent(); IPHistoryQueue.clear(); } return { init: init, clean: clean, }; })(); ## Instruction: Use jQuery for misc. UI code ## Code After: var IPHistory = (function() { 'use strict'; var no_messages_error = "Your account has no Login/Logout activity."; function updateTable(batch) { IPHistoryUI.updateTable(batch); if (batch.length) { return; } $('#login-history-table tbody') .append($('<tr/>', {class: 'flex-tr'}) .append($('<td/>', {colspan: 6}) .append($('<p/>', { class: 'notice-msg center-text', text: text.localize(no_messages_error) }) ) ) ); } function handler(response) { if (response.error && response.error.message) { $('#err').text(response.error.message); return; } updateTable(response.login_history); } // localize, title, create tables // register the callback on IPHistoryQueue function init() { var $title = $('#login_history-title').children().first(); $title.text(text.localize($title.text())); IPHistoryUI.createEmptyTable().appendTo('#login_history-ws-container'); IPHistoryQueue.register(handler); IPHistoryQueue.fetchNext({limit: 50}); } function clean() { $('#login_history-ws-container .error-msg').text(''); IPHistoryUI.clearTableContent(); IPHistoryQueue.clear(); } return { init: init, clean: clean, }; })();
98c4e0f4228a92248ccfca4fc1bc5c5302529eee
src/Http/Routing/Router.php
src/Http/Routing/Router.php
<?php namespace RandomState\LaravelApi\Http\Routing; use Illuminate\Contracts\Routing\Registrar; use Illuminate\Contracts\Support\Responsable; use ArrayObject; use Illuminate\Support\Facades\App; use JsonSerializable; use Illuminate\Http\Response; use Illuminate\Http\JsonResponse; use Illuminate\Contracts\Support\Jsonable; use Illuminate\Contracts\Support\Arrayable; use Psr\Http\Message\ResponseInterface as PsrResponseInterface; use RandomState\LaravelApi\Http\Response\ResponseFactory; use Symfony\Bridge\PsrHttpMessage\Factory\HttpFoundationFactory; use Symfony\Component\HttpFoundation\Response as SymfonyResponse; class Router extends \Illuminate\Routing\Router implements Registrar { /** * @var \Illuminate\Routing\Router */ protected $router; public static function prepareResponse($request, $response) { if($response instanceof Responsable) { $response = $response->toResponse($request); } if($response instanceof PsrResponseInterface) { $response = (new HttpFoundationFactory)->createResponse($response); } elseif( ! $response instanceof SymfonyResponse) { $response = App::make(ResponseFactory::class)->build($response); $response = new Response($response); } elseif( ! $response instanceof SymfonyResponse && ($response instanceof Arrayable || $response instanceof Jsonable || $response instanceof ArrayObject || $response instanceof JsonSerializable || is_array($response))) { $response = new JsonResponse($response); } if($response->getStatusCode() === Response::HTTP_NOT_MODIFIED) { $response->setNotModified(); } return $response->prepare($request); } }
<?php namespace RandomState\LaravelApi\Http\Routing; use Illuminate\Contracts\Routing\Registrar; use RandomState\LaravelApi\Http\Response\ResponseFactory; class Router extends \Illuminate\Routing\Router implements Registrar { /** * @var \Illuminate\Routing\Router */ protected $router; public static function prepareResponse($request, $response) { $response = app(ResponseFactory::class)->build($response); return parent::prepareResponse($request,$response); } }
Clean up router to defer to base router as much as possible.
Clean up router to defer to base router as much as possible.
PHP
mit
randomstate/laravel-api
php
## Code Before: <?php namespace RandomState\LaravelApi\Http\Routing; use Illuminate\Contracts\Routing\Registrar; use Illuminate\Contracts\Support\Responsable; use ArrayObject; use Illuminate\Support\Facades\App; use JsonSerializable; use Illuminate\Http\Response; use Illuminate\Http\JsonResponse; use Illuminate\Contracts\Support\Jsonable; use Illuminate\Contracts\Support\Arrayable; use Psr\Http\Message\ResponseInterface as PsrResponseInterface; use RandomState\LaravelApi\Http\Response\ResponseFactory; use Symfony\Bridge\PsrHttpMessage\Factory\HttpFoundationFactory; use Symfony\Component\HttpFoundation\Response as SymfonyResponse; class Router extends \Illuminate\Routing\Router implements Registrar { /** * @var \Illuminate\Routing\Router */ protected $router; public static function prepareResponse($request, $response) { if($response instanceof Responsable) { $response = $response->toResponse($request); } if($response instanceof PsrResponseInterface) { $response = (new HttpFoundationFactory)->createResponse($response); } elseif( ! $response instanceof SymfonyResponse) { $response = App::make(ResponseFactory::class)->build($response); $response = new Response($response); } elseif( ! $response instanceof SymfonyResponse && ($response instanceof Arrayable || $response instanceof Jsonable || $response instanceof ArrayObject || $response instanceof JsonSerializable || is_array($response))) { $response = new JsonResponse($response); } if($response->getStatusCode() === Response::HTTP_NOT_MODIFIED) { $response->setNotModified(); } return $response->prepare($request); } } ## Instruction: Clean up router to defer to base router as much as possible. ## Code After: <?php namespace RandomState\LaravelApi\Http\Routing; use Illuminate\Contracts\Routing\Registrar; use RandomState\LaravelApi\Http\Response\ResponseFactory; class Router extends \Illuminate\Routing\Router implements Registrar { /** * @var \Illuminate\Routing\Router */ protected $router; public static function prepareResponse($request, $response) { $response = app(ResponseFactory::class)->build($response); return parent::prepareResponse($request,$response); } }
ca8d51a2ef6edcd94501d38fde799c9163b7d770
app/src/main/java/in/testpress/testpress/events/SmsReceivingEvent.java
app/src/main/java/in/testpress/testpress/events/SmsReceivingEvent.java
package in.testpress.testpress.events; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.telephony.SmsMessage; import in.testpress.testpress.R; import in.testpress.testpress.authenticator.CodeVerificationActivity.Timer; import in.testpress.testpress.core.Constants; public class SmsReceivingEvent extends BroadcastReceiver { public String code; private Timer timer; public SmsReceivingEvent(Timer timer) { this.timer = timer; } @Override public void onReceive(Context context, Intent intent) { // Retrieves a map of extended data from the intent. final Bundle bundle = intent.getExtras(); try { if (bundle != null) { final Object[] pdusObj = (Object[]) bundle.get("pdus"); SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[0]); String senderNum = currentMessage.getDisplayOriginatingAddress(); if (senderNum.matches(".*TSTPRS")) { //check whether TSTPRS present in senderAddress String smsContent = currentMessage.getDisplayMessageBody(); //get the code from smsContent code = smsContent.replaceAll(".*(?<=Thank you for registering at +"+Constants.Http.URL_BASE +"+. Your authorization code is )([^\n]*)(?=.).*", "$1"); timer.cancel(); timer.onFinish(); } } // bundle is null } catch (Exception e) { timer.cancel(); timer.onFinish(); } } }
package in.testpress.testpress.events; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.telephony.SmsMessage; import in.testpress.testpress.authenticator.CodeVerificationActivity.Timer; public class SmsReceivingEvent extends BroadcastReceiver { public String code; private Timer timer; public SmsReceivingEvent(Timer timer) { this.timer = timer; } @Override public void onReceive(Context context, Intent intent) { // Retrieves a map of extended data from the intent. final Bundle bundle = intent.getExtras(); try { if (bundle != null) { final Object[] pdusObj = (Object[]) bundle.get("pdus"); SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[0]); String senderNum = currentMessage.getDisplayOriginatingAddress(); if (senderNum.matches(".*TSTPRS")) { //check whether TSTPRS present in senderAddress String smsContent = currentMessage.getDisplayMessageBody(); //get the code from smsContent code = smsContent.replaceAll(".*(?=.*)(?<=Your authorization code is )([^\n]*)(?=.).*", "$1"); timer.cancel(); timer.onFinish(); } } // bundle is null } catch (Exception e) { timer.cancel(); timer.onFinish(); } } }
Modify sms format in sms receiving event
Modify sms format in sms receiving event Sms regex format is changed to support all institutes names.
Java
mit
testpress/android,testpress/android,testpress/android,testpress/android,testpress/android
java
## Code Before: package in.testpress.testpress.events; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.telephony.SmsMessage; import in.testpress.testpress.R; import in.testpress.testpress.authenticator.CodeVerificationActivity.Timer; import in.testpress.testpress.core.Constants; public class SmsReceivingEvent extends BroadcastReceiver { public String code; private Timer timer; public SmsReceivingEvent(Timer timer) { this.timer = timer; } @Override public void onReceive(Context context, Intent intent) { // Retrieves a map of extended data from the intent. final Bundle bundle = intent.getExtras(); try { if (bundle != null) { final Object[] pdusObj = (Object[]) bundle.get("pdus"); SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[0]); String senderNum = currentMessage.getDisplayOriginatingAddress(); if (senderNum.matches(".*TSTPRS")) { //check whether TSTPRS present in senderAddress String smsContent = currentMessage.getDisplayMessageBody(); //get the code from smsContent code = smsContent.replaceAll(".*(?<=Thank you for registering at +"+Constants.Http.URL_BASE +"+. Your authorization code is )([^\n]*)(?=.).*", "$1"); timer.cancel(); timer.onFinish(); } } // bundle is null } catch (Exception e) { timer.cancel(); timer.onFinish(); } } } ## Instruction: Modify sms format in sms receiving event Sms regex format is changed to support all institutes names. ## Code After: package in.testpress.testpress.events; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.telephony.SmsMessage; import in.testpress.testpress.authenticator.CodeVerificationActivity.Timer; public class SmsReceivingEvent extends BroadcastReceiver { public String code; private Timer timer; public SmsReceivingEvent(Timer timer) { this.timer = timer; } @Override public void onReceive(Context context, Intent intent) { // Retrieves a map of extended data from the intent. final Bundle bundle = intent.getExtras(); try { if (bundle != null) { final Object[] pdusObj = (Object[]) bundle.get("pdus"); SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[0]); String senderNum = currentMessage.getDisplayOriginatingAddress(); if (senderNum.matches(".*TSTPRS")) { //check whether TSTPRS present in senderAddress String smsContent = currentMessage.getDisplayMessageBody(); //get the code from smsContent code = smsContent.replaceAll(".*(?=.*)(?<=Your authorization code is )([^\n]*)(?=.).*", "$1"); timer.cancel(); timer.onFinish(); } } // bundle is null } catch (Exception e) { timer.cancel(); timer.onFinish(); } } }
82fb1b1486e2cd391bdd3e505cbb397eee73341e
src/main/java/com/speedledger/measure/jenkins/ElasticsearchPlugin.java
src/main/java/com/speedledger/measure/jenkins/ElasticsearchPlugin.java
package com.speedledger.measure.jenkins; import hudson.Plugin; import hudson.model.Descriptor; import hudson.model.Items; import net.sf.json.JSONObject; import org.kohsuke.stapler.StaplerRequest; import javax.servlet.ServletException; import java.io.IOException; /** * Elasticsearch plugin to Jenkins. * Reports build information to Elasticsearch on build completion. * * This class only handles loading and saving the configuration of Elasticsearch, see {@link Config}. */ public class ElasticsearchPlugin extends Plugin { private Config config; @Override public void start() throws Exception { Items.XSTREAM.registerConverter(new Config.ConverterImpl()); load(); } @Override public void configure(StaplerRequest req, JSONObject jsonObject) throws IOException, ServletException, Descriptor.FormException { String url = jsonObject.getString("url"); String indexName = jsonObject.getString("indexName"); String typeName = jsonObject.getString("typeName"); config = new Config(url, indexName, typeName); save(); } public Config getConfig() { return config; } // Used by Jelly public String getUrl() { return config == null ? null : config.getUrl(); } // Used by Jelly public String getIndexName() { return config == null ? null : config.getIndexName(); } // Used by Jelly public String getTypeName() { return config == null ? null : config.getTypeName(); } }
package com.speedledger.measure.jenkins; import hudson.Plugin; import hudson.model.Descriptor; import hudson.model.Items; import net.sf.json.JSONObject; import org.kohsuke.stapler.StaplerRequest; import javax.servlet.ServletException; import java.io.IOException; /** * Elasticsearch plugin to Jenkins. * Reports build information to Elasticsearch on build completion. * * This class only handles loading and saving the configuration of Elasticsearch, see {@link Config}. */ public class ElasticsearchPlugin extends Plugin { private Config config; @Override public void start() throws Exception { Items.XSTREAM.registerConverter(new Config.ConverterImpl()); load(); } @Override public void configure(StaplerRequest req, JSONObject jsonObject) throws IOException, ServletException, Descriptor.FormException { String url = jsonObject.getString("elasticsearchUrl"); String indexName = jsonObject.getString("elasticsearchIndexName"); String typeName = jsonObject.getString("elasticsearchTypeName"); config = new Config(url, indexName, typeName); save(); } public Config getConfig() { return config; } // Used by Jelly public String getUrl() { return config == null ? null : config.getUrl(); } // Used by Jelly public String getIndexName() { return config == null ? null : config.getIndexName(); } // Used by Jelly public String getTypeName() { return config == null ? null : config.getTypeName(); } }
Fix reading wrong keys from config form response
Fix reading wrong keys from config form response
Java
mit
speedledger/elasticsearch-jenkins
java
## Code Before: package com.speedledger.measure.jenkins; import hudson.Plugin; import hudson.model.Descriptor; import hudson.model.Items; import net.sf.json.JSONObject; import org.kohsuke.stapler.StaplerRequest; import javax.servlet.ServletException; import java.io.IOException; /** * Elasticsearch plugin to Jenkins. * Reports build information to Elasticsearch on build completion. * * This class only handles loading and saving the configuration of Elasticsearch, see {@link Config}. */ public class ElasticsearchPlugin extends Plugin { private Config config; @Override public void start() throws Exception { Items.XSTREAM.registerConverter(new Config.ConverterImpl()); load(); } @Override public void configure(StaplerRequest req, JSONObject jsonObject) throws IOException, ServletException, Descriptor.FormException { String url = jsonObject.getString("url"); String indexName = jsonObject.getString("indexName"); String typeName = jsonObject.getString("typeName"); config = new Config(url, indexName, typeName); save(); } public Config getConfig() { return config; } // Used by Jelly public String getUrl() { return config == null ? null : config.getUrl(); } // Used by Jelly public String getIndexName() { return config == null ? null : config.getIndexName(); } // Used by Jelly public String getTypeName() { return config == null ? null : config.getTypeName(); } } ## Instruction: Fix reading wrong keys from config form response ## Code After: package com.speedledger.measure.jenkins; import hudson.Plugin; import hudson.model.Descriptor; import hudson.model.Items; import net.sf.json.JSONObject; import org.kohsuke.stapler.StaplerRequest; import javax.servlet.ServletException; import java.io.IOException; /** * Elasticsearch plugin to Jenkins. * Reports build information to Elasticsearch on build completion. * * This class only handles loading and saving the configuration of Elasticsearch, see {@link Config}. */ public class ElasticsearchPlugin extends Plugin { private Config config; @Override public void start() throws Exception { Items.XSTREAM.registerConverter(new Config.ConverterImpl()); load(); } @Override public void configure(StaplerRequest req, JSONObject jsonObject) throws IOException, ServletException, Descriptor.FormException { String url = jsonObject.getString("elasticsearchUrl"); String indexName = jsonObject.getString("elasticsearchIndexName"); String typeName = jsonObject.getString("elasticsearchTypeName"); config = new Config(url, indexName, typeName); save(); } public Config getConfig() { return config; } // Used by Jelly public String getUrl() { return config == null ? null : config.getUrl(); } // Used by Jelly public String getIndexName() { return config == null ? null : config.getIndexName(); } // Used by Jelly public String getTypeName() { return config == null ? null : config.getTypeName(); } }
fd5bfd9f71903895b3643264316ef5d9113ea75f
lib/probes/active_record.rb
lib/probes/active_record.rb
module Probes module ActiveRecord module Base module ClassMethods def find_by_sql_with_probes(sql) Dtrace::Probe::ActionController.find_by_sql_start do |p| p.fire(sql) end results = find_by_sql_without_probes(sql) Dtrace::Probe::ActiveRecord.find_by_sql_finish do |p| p.fire(results.length) end results end end def self.included(base) base.extend ClassMethods Dtrace::Provider.create :active_record do |p| p.probe :find_by_sql_start, :string p.probe :find_by_sql_finish, :integer end base.class_eval do class << self alias_method_chain :find_by_sql, :probes end end end end module ConnectionAdapters module MysqlAdapter def execute_with_probes(sql, name = nil) Dtrace::Probe::ActiveRecordMysql.execute_start do |p| p.fire(sql) end results = execute_without_probes(sql, name) Dtrace::Probe::ActiveRecordMysql.execute_finish do |p| p.fire(results.inspect) end results end def self.included(base) Dtrace::Provider.create :active_record_mysql do |p| p.probe :execute_start, :string p.probe :execute_finish, :string end base.alias_method_chain :execute, :probes end end end end end
module Probes module ActiveRecord module Base module ClassMethods def find_by_sql_with_probes(sql) Dtrace::Probe::ActiveRecord.find_by_sql_start do |p| p.fire(sql) end results = find_by_sql_without_probes(sql) Dtrace::Probe::ActiveRecord.find_by_sql_finish do |p| p.fire(results.length) end results end end def self.included(base) base.extend ClassMethods Dtrace::Provider.create :active_record do |p| p.probe :find_by_sql_start, :string p.probe :find_by_sql_finish, :integer end base.class_eval do class << self alias_method_chain :find_by_sql, :probes end end end end module ConnectionAdapters module MysqlAdapter def execute_with_probes(sql, name = nil) Dtrace::Probe::ActiveRecordMysql.execute_start do |p| p.fire(sql) end results = execute_without_probes(sql, name) Dtrace::Probe::ActiveRecordMysql.execute_finish do |p| p.fire(results.inspect) end results end def self.included(base) Dtrace::Provider.create :active_record_mysql do |p| p.probe :execute_start, :string p.probe :execute_finish, :string end base.alias_method_chain :execute, :probes end end end end end
Correct call to ActiveRecord.find_by_sql probe, prompting exception on bad call to probes in ruby-dtrace.
Correct call to ActiveRecord.find_by_sql probe, prompting exception on bad call to probes in ruby-dtrace. git-svn-id: ee21a9573714ad23dc07274cc891719afe0bb9d1@358 0a37a38d-5523-0410-8951-9484fa28833c
Ruby
mit
chrisa/ruby-dtrace,chrisa/ruby-dtrace
ruby
## Code Before: module Probes module ActiveRecord module Base module ClassMethods def find_by_sql_with_probes(sql) Dtrace::Probe::ActionController.find_by_sql_start do |p| p.fire(sql) end results = find_by_sql_without_probes(sql) Dtrace::Probe::ActiveRecord.find_by_sql_finish do |p| p.fire(results.length) end results end end def self.included(base) base.extend ClassMethods Dtrace::Provider.create :active_record do |p| p.probe :find_by_sql_start, :string p.probe :find_by_sql_finish, :integer end base.class_eval do class << self alias_method_chain :find_by_sql, :probes end end end end module ConnectionAdapters module MysqlAdapter def execute_with_probes(sql, name = nil) Dtrace::Probe::ActiveRecordMysql.execute_start do |p| p.fire(sql) end results = execute_without_probes(sql, name) Dtrace::Probe::ActiveRecordMysql.execute_finish do |p| p.fire(results.inspect) end results end def self.included(base) Dtrace::Provider.create :active_record_mysql do |p| p.probe :execute_start, :string p.probe :execute_finish, :string end base.alias_method_chain :execute, :probes end end end end end ## Instruction: Correct call to ActiveRecord.find_by_sql probe, prompting exception on bad call to probes in ruby-dtrace. git-svn-id: ee21a9573714ad23dc07274cc891719afe0bb9d1@358 0a37a38d-5523-0410-8951-9484fa28833c ## Code After: module Probes module ActiveRecord module Base module ClassMethods def find_by_sql_with_probes(sql) Dtrace::Probe::ActiveRecord.find_by_sql_start do |p| p.fire(sql) end results = find_by_sql_without_probes(sql) Dtrace::Probe::ActiveRecord.find_by_sql_finish do |p| p.fire(results.length) end results end end def self.included(base) base.extend ClassMethods Dtrace::Provider.create :active_record do |p| p.probe :find_by_sql_start, :string p.probe :find_by_sql_finish, :integer end base.class_eval do class << self alias_method_chain :find_by_sql, :probes end end end end module ConnectionAdapters module MysqlAdapter def execute_with_probes(sql, name = nil) Dtrace::Probe::ActiveRecordMysql.execute_start do |p| p.fire(sql) end results = execute_without_probes(sql, name) Dtrace::Probe::ActiveRecordMysql.execute_finish do |p| p.fire(results.inspect) end results end def self.included(base) Dtrace::Provider.create :active_record_mysql do |p| p.probe :execute_start, :string p.probe :execute_finish, :string end base.alias_method_chain :execute, :probes end end end end end
208081800ab7e6217ec0f88e76c2dffd32187db1
whyp/shell.py
whyp/shell.py
import os from pysyte.types.paths import path def value(key): """A value from the shell environment, defaults to empty string >>> value('SHELL') is not None True """ try: return os.environ[key] except KeyError: return '' def paths(name=None): """A list of paths in the environment's PATH >>> '/bin' in paths() True """ path_value = value(name or 'PATH') path_strings = path_value.split(':') path_paths = [path(_) for _ in path_strings] return path_paths def path_commands(): """Gives a dictionary of all executable files in the environment's PATH >>> path_commands()['python'] == sys.executable or True True """ commands = {} for path_dir in paths(): for file_path in path_dir.list_files(): if not file_path.isexec(): continue if file_path.name in commands: continue commands[file_path.name] = file_path return commands _path_commands = path_commands() def which(name): """Looks for the name as an executable is shell's PATH If name is not found, look for name.exe If still not found, return empty string >>> which('python') == sys.executable or True True """ try: commands = _path_commands return commands[name] except KeyError: if name.endswith('.exe'): return '' return which('%s.exe' % name) def is_path_command(name): return name in _path_commands
import os from pysyte.types.paths import path def value(key): """A value from the shell environment, defaults to empty string >>> value('SHELL') is not None True """ try: return os.environ[key] except KeyError: return '' def paths(name=None): """A list of paths in the environment's PATH >>> '/bin' in paths() True """ path_value = value(name or 'PATH') path_strings = path_value.split(':') path_paths = [path(_) for _ in path_strings] return path_paths def path_commands(): """Gives a dictionary of all executable files in the environment's PATH >>> path_commands()['python'] == sys.executable or True True """ commands = {} for path_dir in paths(): if not path_dir.isdir(): continue for file_path in path_dir.list_files(): if not file_path.isexec(): continue if file_path.name in commands: continue commands[file_path.name] = file_path return commands _path_commands = path_commands() def which(name): """Looks for the name as an executable is shell's PATH If name is not found, look for name.exe If still not found, return empty string >>> which('python') == sys.executable or True True """ try: commands = _path_commands return commands[name] except KeyError: if name.endswith('.exe'): return '' return which('%s.exe' % name) def is_path_command(name): return name in _path_commands
Allow for missing directories in $PATH
Allow for missing directories in $PATH
Python
mit
jalanb/what,jalanb/what
python
## Code Before: import os from pysyte.types.paths import path def value(key): """A value from the shell environment, defaults to empty string >>> value('SHELL') is not None True """ try: return os.environ[key] except KeyError: return '' def paths(name=None): """A list of paths in the environment's PATH >>> '/bin' in paths() True """ path_value = value(name or 'PATH') path_strings = path_value.split(':') path_paths = [path(_) for _ in path_strings] return path_paths def path_commands(): """Gives a dictionary of all executable files in the environment's PATH >>> path_commands()['python'] == sys.executable or True True """ commands = {} for path_dir in paths(): for file_path in path_dir.list_files(): if not file_path.isexec(): continue if file_path.name in commands: continue commands[file_path.name] = file_path return commands _path_commands = path_commands() def which(name): """Looks for the name as an executable is shell's PATH If name is not found, look for name.exe If still not found, return empty string >>> which('python') == sys.executable or True True """ try: commands = _path_commands return commands[name] except KeyError: if name.endswith('.exe'): return '' return which('%s.exe' % name) def is_path_command(name): return name in _path_commands ## Instruction: Allow for missing directories in $PATH ## Code After: import os from pysyte.types.paths import path def value(key): """A value from the shell environment, defaults to empty string >>> value('SHELL') is not None True """ try: return os.environ[key] except KeyError: return '' def paths(name=None): """A list of paths in the environment's PATH >>> '/bin' in paths() True """ path_value = value(name or 'PATH') path_strings = path_value.split(':') path_paths = [path(_) for _ in path_strings] return path_paths def path_commands(): """Gives a dictionary of all executable files in the environment's PATH >>> path_commands()['python'] == sys.executable or True True """ commands = {} for path_dir in paths(): if not path_dir.isdir(): continue for file_path in path_dir.list_files(): if not file_path.isexec(): continue if file_path.name in commands: continue commands[file_path.name] = file_path return commands _path_commands = path_commands() def which(name): """Looks for the name as an executable is shell's PATH If name is not found, look for name.exe If still not found, return empty string >>> which('python') == sys.executable or True True """ try: commands = _path_commands return commands[name] except KeyError: if name.endswith('.exe'): return '' return which('%s.exe' % name) def is_path_command(name): return name in _path_commands
6983e30713a77476ae3a0419ff955bce988c1229
js/main.js
js/main.js
/* -------------------------------------------------------------------------- Initialize --------------------------------------------------------------------------- */ $(document).ready(function() { /* Syntax Highlighter --------------------------------------------------------------------------- */ SyntaxHighlighter.defaults['toolbar'] = false; SyntaxHighlighter.defaults['gutter'] = false; SyntaxHighlighter.all(); SyntaxHighlighter.highlight(); }); /* -------------------------------------------------------------------------- Follow sidebar --------------------------------------------------------------------------- */ $(function() { var $sidebar = $(".sidebar"), $window = $(window), $start = $sidebar.offset().top - 98; $window.scroll(function() { if ($window.scrollTop() > $start) { $sidebar.addClass("sidebar-scrolled"); } else { $sidebar.removeClass("sidebar-scrolled"); } }); }); /* -------------------------------------------------------------------------- Smooth scrolling and add style on click section --------------------------------------------------------------------------- */ /* https://css-tricks.com/snippets/jquery/smooth-scrolling/ */ $(function() { $('.sidebar-menu-element a').click(function() { if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) { var target = $(this.hash); target = target.length ? target : $('[name=' + this.hash.slice(1) + ']'); if (target.length) { $('.sidebar-menu-element a').removeClass('is-active'); $(this).addClass('is-active'); $('html,body').animate({ scrollTop: target.offset().top }, 700); return false; } } }); });
/* -------------------------------------------------------------------------- Initialize --------------------------------------------------------------------------- */ $(document).ready(function() { /* Syntax Highlighter --------------------------------------------------------------------------- */ SyntaxHighlighter.defaults['toolbar'] = false; SyntaxHighlighter.defaults['gutter'] = false; SyntaxHighlighter.all(); SyntaxHighlighter.highlight(); }); /* -------------------------------------------------------------------------- Follow sidebar --------------------------------------------------------------------------- */ $(function() { var $sidebar = $(".sidebar"), $window = $(window), $start = $sidebar.offset().top - 98; $window.scroll(function() { if ($window.scrollTop() > $start) { $sidebar.addClass("sidebar-scrolled"); } else { $sidebar.removeClass("sidebar-scrolled"); } }); }); /* -------------------------------------------------------------------------- Smooth scrolling and add style on click section --------------------------------------------------------------------------- */ /* https://css-tricks.com/snippets/jquery/smooth-scrolling/ */ $(function() { $('.sidebar-menu-element a').click(function() { if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) { var target = $(this.hash); target = target.length ? target : $('[name=' + this.hash.slice(1) + ']'); if (target.length) { // Add class on click sidebar element /*$('.sidebar-menu-element a').removeClass('is-active'); $(this).addClass('is-active');*/ $('html,body').animate({ scrollTop: target.offset().top }, 700); return false; } } }); });
Comment code to add class on click sidebar element
Comment code to add class on click sidebar element
JavaScript
mit
AitorRodriguez990/documentation-template,AitorRodriguez990/documentation-template
javascript
## Code Before: /* -------------------------------------------------------------------------- Initialize --------------------------------------------------------------------------- */ $(document).ready(function() { /* Syntax Highlighter --------------------------------------------------------------------------- */ SyntaxHighlighter.defaults['toolbar'] = false; SyntaxHighlighter.defaults['gutter'] = false; SyntaxHighlighter.all(); SyntaxHighlighter.highlight(); }); /* -------------------------------------------------------------------------- Follow sidebar --------------------------------------------------------------------------- */ $(function() { var $sidebar = $(".sidebar"), $window = $(window), $start = $sidebar.offset().top - 98; $window.scroll(function() { if ($window.scrollTop() > $start) { $sidebar.addClass("sidebar-scrolled"); } else { $sidebar.removeClass("sidebar-scrolled"); } }); }); /* -------------------------------------------------------------------------- Smooth scrolling and add style on click section --------------------------------------------------------------------------- */ /* https://css-tricks.com/snippets/jquery/smooth-scrolling/ */ $(function() { $('.sidebar-menu-element a').click(function() { if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) { var target = $(this.hash); target = target.length ? target : $('[name=' + this.hash.slice(1) + ']'); if (target.length) { $('.sidebar-menu-element a').removeClass('is-active'); $(this).addClass('is-active'); $('html,body').animate({ scrollTop: target.offset().top }, 700); return false; } } }); }); ## Instruction: Comment code to add class on click sidebar element ## Code After: /* -------------------------------------------------------------------------- Initialize --------------------------------------------------------------------------- */ $(document).ready(function() { /* Syntax Highlighter --------------------------------------------------------------------------- */ SyntaxHighlighter.defaults['toolbar'] = false; SyntaxHighlighter.defaults['gutter'] = false; SyntaxHighlighter.all(); SyntaxHighlighter.highlight(); }); /* -------------------------------------------------------------------------- Follow sidebar --------------------------------------------------------------------------- */ $(function() { var $sidebar = $(".sidebar"), $window = $(window), $start = $sidebar.offset().top - 98; $window.scroll(function() { if ($window.scrollTop() > $start) { $sidebar.addClass("sidebar-scrolled"); } else { $sidebar.removeClass("sidebar-scrolled"); } }); }); /* -------------------------------------------------------------------------- Smooth scrolling and add style on click section --------------------------------------------------------------------------- */ /* https://css-tricks.com/snippets/jquery/smooth-scrolling/ */ $(function() { $('.sidebar-menu-element a').click(function() { if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) { var target = $(this.hash); target = target.length ? target : $('[name=' + this.hash.slice(1) + ']'); if (target.length) { // Add class on click sidebar element /*$('.sidebar-menu-element a').removeClass('is-active'); $(this).addClass('is-active');*/ $('html,body').animate({ scrollTop: target.offset().top }, 700); return false; } } }); });
7c6af226c601e337a4d4a11f345a0be5034fab42
src/router/index.js
src/router/index.js
import Vue from 'vue'; import VueResource from 'vue-resource'; import Router from 'vue-router'; import Endpoint from '@/components/Endpoint'; import EndpointList from '@/components/EndpointList'; import Home from '@/components/Home'; import yaml from 'js-yaml'; Vue.use(Router); Vue.use(VueResource); const router = new Router({ routes: [ { path: '/', name: 'Home', component: Home, }, ], }); const yamlPath = '/static/yaml'; Vue.http.get(`${yamlPath}/base/base_endpoints.yaml`).then((response) => { const baseEndpoints = yaml.load(response.body); const routes = []; baseEndpoints.forEach((base) => { const { title, name } = base; routes.push({ path: `/${name}`, name: title, component: EndpointList, }); Vue.http.get(`${yamlPath}/endpoints/${name}.yaml`).then((endResp) => { const endpointRoutes = []; const { body } = endResp; const data = yaml.load(body); const basePath = data.base_path; const { endpoints } = data; endpoints.forEach((end) => { const { route } = end; const path = `${basePath}/${route}`; endpointRoutes.push({ path, name: path, component: Endpoint, }); }); router.addRoutes(endpointRoutes); }); }); router.addRoutes(routes); }); export default router;
import Vue from 'vue'; import VueResource from 'vue-resource'; import Router from 'vue-router'; import Endpoint from '@/components/Endpoint'; import EndpointList from '@/components/EndpointList'; import Home from '@/components/Home'; import yaml from 'js-yaml'; Vue.use(Router); Vue.use(VueResource); const router = new Router({ routes: [ { path: '/', name: 'Home', component: Home, }, ], }); const yamlPath = '/static/yaml'; Vue.http.get(`${yamlPath}/base/base_endpoints.yaml`).then((response) => { const baseEndpoints = yaml.load(response.body); const routes = []; baseEndpoints.forEach((base) => { const { title, name } = base; routes.push({ path: `/${name}`, name: title, component: EndpointList, }); }); router.addRoutes(routes); }); export default router;
Remove unnecessary routes for specific routes
Remove unnecessary routes for specific routes
JavaScript
mit
Decicus/DecAPI-Docs,Decicus/DecAPI-Docs
javascript
## Code Before: import Vue from 'vue'; import VueResource from 'vue-resource'; import Router from 'vue-router'; import Endpoint from '@/components/Endpoint'; import EndpointList from '@/components/EndpointList'; import Home from '@/components/Home'; import yaml from 'js-yaml'; Vue.use(Router); Vue.use(VueResource); const router = new Router({ routes: [ { path: '/', name: 'Home', component: Home, }, ], }); const yamlPath = '/static/yaml'; Vue.http.get(`${yamlPath}/base/base_endpoints.yaml`).then((response) => { const baseEndpoints = yaml.load(response.body); const routes = []; baseEndpoints.forEach((base) => { const { title, name } = base; routes.push({ path: `/${name}`, name: title, component: EndpointList, }); Vue.http.get(`${yamlPath}/endpoints/${name}.yaml`).then((endResp) => { const endpointRoutes = []; const { body } = endResp; const data = yaml.load(body); const basePath = data.base_path; const { endpoints } = data; endpoints.forEach((end) => { const { route } = end; const path = `${basePath}/${route}`; endpointRoutes.push({ path, name: path, component: Endpoint, }); }); router.addRoutes(endpointRoutes); }); }); router.addRoutes(routes); }); export default router; ## Instruction: Remove unnecessary routes for specific routes ## Code After: import Vue from 'vue'; import VueResource from 'vue-resource'; import Router from 'vue-router'; import Endpoint from '@/components/Endpoint'; import EndpointList from '@/components/EndpointList'; import Home from '@/components/Home'; import yaml from 'js-yaml'; Vue.use(Router); Vue.use(VueResource); const router = new Router({ routes: [ { path: '/', name: 'Home', component: Home, }, ], }); const yamlPath = '/static/yaml'; Vue.http.get(`${yamlPath}/base/base_endpoints.yaml`).then((response) => { const baseEndpoints = yaml.load(response.body); const routes = []; baseEndpoints.forEach((base) => { const { title, name } = base; routes.push({ path: `/${name}`, name: title, component: EndpointList, }); }); router.addRoutes(routes); }); export default router;
f23eee6f5fa754c5553b17d95ac2ec3515e7ff01
server/test/controllers/user-controller.js
server/test/controllers/user-controller.js
const should = require('should'); const sinon = require('sinon'); require('should-sinon'); const proxyquire = require('proxyquire'); const httpMocks = require('node-mocks-http'); // Mock Service const mockObj = { getAllUsers() { return Promise.resolve(['item 1', 'item 2']); } }; const userController = proxyquire('../../app/controllers/user-controller', { '../services/user-service': mockObj }); describe('User controller tests', function () { it('should not fail and send a JSON parsed data', async function () { // Given const res = httpMocks.createResponse(); const req = httpMocks.createRequest({ method: 'GET', url: '/user/', params: {} }); // When await userController.getAllUsers(req, res); // Then res._isEndCalled().should.be.true(); res._isJSON().should.be.true(); res._getData().should.be.equal('["item 1","item 2"]'); }); it('should fail correctly if there is a problem in service', async function () { // Given const res = httpMocks.createResponse(); const req = httpMocks.createRequest({ method: 'GET', url: '/user/', params: {} }); const serviceStub = sinon.stub(mockObj, 'getAllUsers'); serviceStub.throws(); // When await userController.getAllUsers(req, res); // Then res._isEndCalled().should.be.true(); res.statusCode.should.be.equal(500); serviceStub.restore(); }); });
const should = require('should'); const sinon = require('sinon'); require('should-sinon'); const proxyquire = require('proxyquire'); const httpMocks = require('node-mocks-http'); // Mock Service const mockObj = { getAllUsers() { return Promise.resolve(['item 1', 'item 2']); } }; const userController = proxyquire('../../app/controllers/user-controller', { '../services/user-service': mockObj }); describe('User controller tests', function () { it('should not fail and send a JSON parsed data', async function () { // Given const res = httpMocks.createResponse(); const req = httpMocks.createRequest({ method: 'GET', url: '/user/', params: {} }); // When await userController.getAllUsers(req, res); // Then res._isEndCalled().should.be.true(); res._isJSON().should.be.true(); res._getData().should.be.equal('["item 1","item 2"]'); }); });
Remove test for fail case (handled by express)
[tests] Remove test for fail case (handled by express)
JavaScript
apache-2.0
K-Fet/K-App,K-Fet/K-App,K-Fet/K-App,K-Fet/K-App
javascript
## Code Before: const should = require('should'); const sinon = require('sinon'); require('should-sinon'); const proxyquire = require('proxyquire'); const httpMocks = require('node-mocks-http'); // Mock Service const mockObj = { getAllUsers() { return Promise.resolve(['item 1', 'item 2']); } }; const userController = proxyquire('../../app/controllers/user-controller', { '../services/user-service': mockObj }); describe('User controller tests', function () { it('should not fail and send a JSON parsed data', async function () { // Given const res = httpMocks.createResponse(); const req = httpMocks.createRequest({ method: 'GET', url: '/user/', params: {} }); // When await userController.getAllUsers(req, res); // Then res._isEndCalled().should.be.true(); res._isJSON().should.be.true(); res._getData().should.be.equal('["item 1","item 2"]'); }); it('should fail correctly if there is a problem in service', async function () { // Given const res = httpMocks.createResponse(); const req = httpMocks.createRequest({ method: 'GET', url: '/user/', params: {} }); const serviceStub = sinon.stub(mockObj, 'getAllUsers'); serviceStub.throws(); // When await userController.getAllUsers(req, res); // Then res._isEndCalled().should.be.true(); res.statusCode.should.be.equal(500); serviceStub.restore(); }); }); ## Instruction: [tests] Remove test for fail case (handled by express) ## Code After: const should = require('should'); const sinon = require('sinon'); require('should-sinon'); const proxyquire = require('proxyquire'); const httpMocks = require('node-mocks-http'); // Mock Service const mockObj = { getAllUsers() { return Promise.resolve(['item 1', 'item 2']); } }; const userController = proxyquire('../../app/controllers/user-controller', { '../services/user-service': mockObj }); describe('User controller tests', function () { it('should not fail and send a JSON parsed data', async function () { // Given const res = httpMocks.createResponse(); const req = httpMocks.createRequest({ method: 'GET', url: '/user/', params: {} }); // When await userController.getAllUsers(req, res); // Then res._isEndCalled().should.be.true(); res._isJSON().should.be.true(); res._getData().should.be.equal('["item 1","item 2"]'); }); });
89a4f3df4e6b3b6927ebac31bdbb33617f8a934f
code/index.js
code/index.js
'use strict' const fs = require('fs') const path = require('path') const mkdirp = require('mkdirp') const assign = require('lodash.assign') const makeTemplate = require('./make-template.js') const defaultDirectives = require('./default-directives.js') module.exports = function (directory, settings) { settings = settings || {} directory = path.resolve(process.cwd(), directory) + '/' settings.cacheDirectory = settings.cacheDirectory || directory + 'compiled/' + (new Date()).getTime() + '/' var directives = assign({}, defaultDirectives, settings.directives || {}) var promises = {} return function load (name) { if (!promises[name]) { promises[name] = new Promise(function (resolve, reject) { fs.readFile(directory + name, { encoding: 'utf-8' }, function (err, result) { if (err) throw err makeTemplate(result, load, directives, function (err, result) { if (err) throw err mkdirp(path.dirname(settings.cacheDirectory + name + '.js'), function (err) { if (err) throw err fs.writeFile(settings.cacheDirectory + name + '.js', result, function (err) { if (err) throw err resolve(settings.cacheDirectory + name + '.js') }) }) }) }) }) } return promises[name].then(function (path) { var Template = require(path) return Promise.resolve(function (content) { return (new Template()).render(content) }) }) } }
'use strict' const fs = require('fs') const path = require('path') const mkdirp = require('mkdirp') const assign = require('lodash.assign') const makeTemplate = require('./make-template.js') const defaultDirectives = require('./default-directives.js') module.exports = function (directory, settings) { settings = settings || {} directory = path.resolve(process.cwd(), directory) + '/' settings.cacheDirectory = settings.cacheDirectory || directory + 'compiled/' var directives = assign({}, defaultDirectives, settings.directives || {}) var promises = {} return function load (name) { if (!promises[name]) { promises[name] = new Promise(function (resolve, reject) { fs.readFile(directory + name, { encoding: 'utf-8' }, function (err, result) { if (err) throw err makeTemplate(result, load, directives, function (err, result) { if (err) throw err mkdirp(path.dirname(settings.cacheDirectory + name + '.js'), function (err) { if (err) throw err fs.writeFile(settings.cacheDirectory + name + '.js', result, function (err) { if (err) throw err resolve(settings.cacheDirectory + name + '.js') }) }) }) }) }) } return promises[name].then(function (path) { delete require.cache[path] var Template = require(path) return Promise.resolve(function (content) { return (new Template()).render(content) }) }) } }
Delete require cache rather than create endless directories
Delete require cache rather than create endless directories
JavaScript
mit
erickmerchant/atlatl
javascript
## Code Before: 'use strict' const fs = require('fs') const path = require('path') const mkdirp = require('mkdirp') const assign = require('lodash.assign') const makeTemplate = require('./make-template.js') const defaultDirectives = require('./default-directives.js') module.exports = function (directory, settings) { settings = settings || {} directory = path.resolve(process.cwd(), directory) + '/' settings.cacheDirectory = settings.cacheDirectory || directory + 'compiled/' + (new Date()).getTime() + '/' var directives = assign({}, defaultDirectives, settings.directives || {}) var promises = {} return function load (name) { if (!promises[name]) { promises[name] = new Promise(function (resolve, reject) { fs.readFile(directory + name, { encoding: 'utf-8' }, function (err, result) { if (err) throw err makeTemplate(result, load, directives, function (err, result) { if (err) throw err mkdirp(path.dirname(settings.cacheDirectory + name + '.js'), function (err) { if (err) throw err fs.writeFile(settings.cacheDirectory + name + '.js', result, function (err) { if (err) throw err resolve(settings.cacheDirectory + name + '.js') }) }) }) }) }) } return promises[name].then(function (path) { var Template = require(path) return Promise.resolve(function (content) { return (new Template()).render(content) }) }) } } ## Instruction: Delete require cache rather than create endless directories ## Code After: 'use strict' const fs = require('fs') const path = require('path') const mkdirp = require('mkdirp') const assign = require('lodash.assign') const makeTemplate = require('./make-template.js') const defaultDirectives = require('./default-directives.js') module.exports = function (directory, settings) { settings = settings || {} directory = path.resolve(process.cwd(), directory) + '/' settings.cacheDirectory = settings.cacheDirectory || directory + 'compiled/' var directives = assign({}, defaultDirectives, settings.directives || {}) var promises = {} return function load (name) { if (!promises[name]) { promises[name] = new Promise(function (resolve, reject) { fs.readFile(directory + name, { encoding: 'utf-8' }, function (err, result) { if (err) throw err makeTemplate(result, load, directives, function (err, result) { if (err) throw err mkdirp(path.dirname(settings.cacheDirectory + name + '.js'), function (err) { if (err) throw err fs.writeFile(settings.cacheDirectory + name + '.js', result, function (err) { if (err) throw err resolve(settings.cacheDirectory + name + '.js') }) }) }) }) }) } return promises[name].then(function (path) { delete require.cache[path] var Template = require(path) return Promise.resolve(function (content) { return (new Template()).render(content) }) }) } }
cb89d3e13f63f46ba25c3549ba7d9609f4f5c145
Grid/Column/ActionsColumn.php
Grid/Column/ActionsColumn.php
<?php /* * This file is part of the DataGridBundle. * * (c) Stanislav Turza <sorien@mail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Sorien\DataGridBundle\Grid\Column; use Sorien\DataGridBundle\Grid\Action\RowAction; class ActionsColumn extends Column { private $rowActions; public function __construct($column, $title, array $rowActions = array()) { $this->rowActions = $rowActions; parent::__construct(array('id' => $column, 'title' => $title, 'sortable' => false, 'source' => false)); } public function getRouteParameters($row, $action) { $actionParameters = $action->getRouteParameters(); if(!empty($actionParameters)){ $routeParameters = array(); foreach ($actionParameters as $name => $parameter) { if(is_numeric($name)){ $routeParameters[$parameter] = $row->getField($parameter); } else { $routeParameters[$name] = $parameter; } } return $routeParameters; } $routeParameters = array_merge( array($row->getPrimaryField() => $row->getPrimaryFieldValue()), $action->getRouteParameters() ); return $routeParameters; } public function getRowActions() { return $this->rowActions; } public function setRowActions(array $rowActions) { $this->rowActions = $rowActions; } public function getType() { return 'actions'; } }
<?php /* * This file is part of the DataGridBundle. * * (c) Stanislav Turza <sorien@mail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Sorien\DataGridBundle\Grid\Column; use Sorien\DataGridBundle\Grid\Action\RowAction; class ActionsColumn extends Column { private $rowActions; public function __construct($column, $title, array $rowActions = array()) { $this->rowActions = $rowActions; parent::__construct(array('id' => $column, 'title' => $title, 'sortable' => false, 'source' => false)); } public function getRouteParameters($row, $action) { $actionParameters = $action->getRouteParameters(); if(!empty($actionParameters)){ $routeParameters = array(); foreach ($actionParameters as $name => $parameter) { if(is_numeric($name)){ $routeParameters[$parameter] = $row->getField($parameter); } else { $routeParameters[$name] = $parameter; } } } return array_merge( array($row->getPrimaryField() => $row->getPrimaryFieldValue()), $routeParameters ); } public function getRowActions() { return $this->rowActions; } public function setRowActions(array $rowActions) { $this->rowActions = $rowActions; } public function getType() { return 'actions'; } }
Fix route parameters for a row action
Fix route parameters for a row action
PHP
mit
lashus/APYDataGridBundle,ibuildingsnl/APYDataGridBundle,matthieuauger/APYDataGridBundle,CiscoVE/APYDataGridBundle,rafacouto/APYDataGridBundle,rogamoore/APYDataGridBundle,Abhoryo/APYDataGridBundle,ustrugany/APYDataGridBundle,andreia/APYDataGridBundle,ibuildingsnl/APYDataGridBundle,APY/APYDataGridBundle,lukaszsobieraj/APYDataGridBundle,ufik/APYDataGridBundle,lukaszsobieraj/APYDataGridBundle,b-durand/APYDataGridBundle,tunght13488/APYDataGridBundle,unrealevil/GvnGridBundle,medinadato/APYDataGridBundle,LewisW/APYDataGridBundle,pierredup/APYDataGridBundle,maximechagnolleau/APYDataGridBundle,fastsupply/APYDataGridBundle,sygnisoft/APYDataGridBundle,tamago-db/APYDataGridBundle,qferr/APYDataGridBundle,sixty-nine/APYDataGridBundle,mdzzohrabi/APYDataGridBundle,dnacreative/APYDataGridBundle,darnel/APYDataGridBundle,mdzzohrabi/APYDataGridBundle,qferr/APYDataGridBundle,delasallejean/APYDataGridBundle,unrealevil/GvnGridBundle,fastsupply/APYDataGridBundle,tomcyr/APYDataGridBundle,Abhoryo/APYDataGridBundle,delasallejean/APYDataGridBundle,CiscoVE/APYDataGridBundle,dnacreative/APYDataGridBundle,ip512/APYDataGridBundle
php
## Code Before: <?php /* * This file is part of the DataGridBundle. * * (c) Stanislav Turza <sorien@mail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Sorien\DataGridBundle\Grid\Column; use Sorien\DataGridBundle\Grid\Action\RowAction; class ActionsColumn extends Column { private $rowActions; public function __construct($column, $title, array $rowActions = array()) { $this->rowActions = $rowActions; parent::__construct(array('id' => $column, 'title' => $title, 'sortable' => false, 'source' => false)); } public function getRouteParameters($row, $action) { $actionParameters = $action->getRouteParameters(); if(!empty($actionParameters)){ $routeParameters = array(); foreach ($actionParameters as $name => $parameter) { if(is_numeric($name)){ $routeParameters[$parameter] = $row->getField($parameter); } else { $routeParameters[$name] = $parameter; } } return $routeParameters; } $routeParameters = array_merge( array($row->getPrimaryField() => $row->getPrimaryFieldValue()), $action->getRouteParameters() ); return $routeParameters; } public function getRowActions() { return $this->rowActions; } public function setRowActions(array $rowActions) { $this->rowActions = $rowActions; } public function getType() { return 'actions'; } } ## Instruction: Fix route parameters for a row action ## Code After: <?php /* * This file is part of the DataGridBundle. * * (c) Stanislav Turza <sorien@mail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Sorien\DataGridBundle\Grid\Column; use Sorien\DataGridBundle\Grid\Action\RowAction; class ActionsColumn extends Column { private $rowActions; public function __construct($column, $title, array $rowActions = array()) { $this->rowActions = $rowActions; parent::__construct(array('id' => $column, 'title' => $title, 'sortable' => false, 'source' => false)); } public function getRouteParameters($row, $action) { $actionParameters = $action->getRouteParameters(); if(!empty($actionParameters)){ $routeParameters = array(); foreach ($actionParameters as $name => $parameter) { if(is_numeric($name)){ $routeParameters[$parameter] = $row->getField($parameter); } else { $routeParameters[$name] = $parameter; } } } return array_merge( array($row->getPrimaryField() => $row->getPrimaryFieldValue()), $routeParameters ); } public function getRowActions() { return $this->rowActions; } public function setRowActions(array $rowActions) { $this->rowActions = $rowActions; } public function getType() { return 'actions'; } }
28607d4d8237d0b7b536b9e5ab95a1fc8bd5abf0
index.html
index.html
--- layout: default title: Civic Hacking in Burlington, VT --- <header id="overview" class="code-for-btv"> <h1>Code for BTV</h1> <h2>A Code for America Brigade</h2> <p>Join over 50 developers, technology integrators, designers and hackers of all types in building and maintaining <a href="#projects">civic software and open data projects</a> in the greater Burlington, VT area.</p> </header> <section class="next"> <article> <p>Our next event is in Burlington on January 11. <a href="#code-for-btv-meetup" class="button">Join Us</a></p> </article> </section> <section id="code-for-btv" class="vevent"> <h1>Stay Involved</h1> <article id="code-for-btv-events"> <h1>Code for BTV</h1> <p>Code for BTV is an ongoing effort to support civic hacking in the greater Burlington, VT area.</p> <p>Periodically, we'll host events for hackers to come together and work on building and reusing civic apps and supporting open data initiatives.</p> <nav> <ul> <li><strong>Stay in the loop about future events</strong> with our <a href="http://eepurl.com/zjEWf">newsletter</a> or follow <a href="https://twitter.com/CodeForBTV">@CodeForBTV</a>.</li> </ul> </nav> </article> <article id="code-for-btv-meetup"> <h1 class="summary"><abbr title="Code for BTV Meetup">Meetup</abbr></h1> <p class="description">Participate in the next Code for BTV meetup. Participants will continue working on the <a href="#projects">civic hacking projects</a> that are actively being developed and/or maintained.</p> <p class="time"><time class="dtstart" datetime="2014-01-11T13:00-04:00">Saturday, January 11, 2014 1pm</time>-<time class="dtend" datetime="2014-01-11T17:00-04:00">5pm</time></p> <p class="location">Office Squared, 110 Main Street (Second Floor), Burlington, VT 05401</p> </article> </section>
--- layout: default title: Civic Hacking in Burlington, VT --- <header id="overview" class="code-for-btv"> <h1>Code for BTV</h1> <h2>A Code for America Brigade</h2> <p>Join over 50 developers, technology integrators, designers and hackers of all types in building and maintaining <a href="#projects">civic software and open data projects</a> in the greater Burlington, VT area.</p> </header>
Remove sections about upcoming event.
Remove sections about upcoming event.
HTML
bsd-3-clause
nfloersch/codeforbtv.github.com,nfloersch/codeforbtv.github.com,nfloersch/codeforbtv.github.com
html
## Code Before: --- layout: default title: Civic Hacking in Burlington, VT --- <header id="overview" class="code-for-btv"> <h1>Code for BTV</h1> <h2>A Code for America Brigade</h2> <p>Join over 50 developers, technology integrators, designers and hackers of all types in building and maintaining <a href="#projects">civic software and open data projects</a> in the greater Burlington, VT area.</p> </header> <section class="next"> <article> <p>Our next event is in Burlington on January 11. <a href="#code-for-btv-meetup" class="button">Join Us</a></p> </article> </section> <section id="code-for-btv" class="vevent"> <h1>Stay Involved</h1> <article id="code-for-btv-events"> <h1>Code for BTV</h1> <p>Code for BTV is an ongoing effort to support civic hacking in the greater Burlington, VT area.</p> <p>Periodically, we'll host events for hackers to come together and work on building and reusing civic apps and supporting open data initiatives.</p> <nav> <ul> <li><strong>Stay in the loop about future events</strong> with our <a href="http://eepurl.com/zjEWf">newsletter</a> or follow <a href="https://twitter.com/CodeForBTV">@CodeForBTV</a>.</li> </ul> </nav> </article> <article id="code-for-btv-meetup"> <h1 class="summary"><abbr title="Code for BTV Meetup">Meetup</abbr></h1> <p class="description">Participate in the next Code for BTV meetup. Participants will continue working on the <a href="#projects">civic hacking projects</a> that are actively being developed and/or maintained.</p> <p class="time"><time class="dtstart" datetime="2014-01-11T13:00-04:00">Saturday, January 11, 2014 1pm</time>-<time class="dtend" datetime="2014-01-11T17:00-04:00">5pm</time></p> <p class="location">Office Squared, 110 Main Street (Second Floor), Burlington, VT 05401</p> </article> </section> ## Instruction: Remove sections about upcoming event. ## Code After: --- layout: default title: Civic Hacking in Burlington, VT --- <header id="overview" class="code-for-btv"> <h1>Code for BTV</h1> <h2>A Code for America Brigade</h2> <p>Join over 50 developers, technology integrators, designers and hackers of all types in building and maintaining <a href="#projects">civic software and open data projects</a> in the greater Burlington, VT area.</p> </header>
925706f9e892eb1fbdf4e08a954acb193886bb70
tasks/browser_extension.js
tasks/browser_extension.js
/* * grunt-browser-extension * https://github.com/addmitriev/grunt-browser-extension * * Copyright (c) 2015 Aleksey Dmitriev * Licensed under the MIT license. */ 'use strict'; var util = require('util'); var path = require('path'); var fs = require('fs-extra'); module.exports = function (grunt) { var BrowserExtension = require('./lib/browser-extension')(grunt); grunt.registerMultiTask('browser_extension', 'Grunt plugin to create any browser website extension', function () { if(this.target){ var options = this.options(); var required_options = []; for(var required_options_id in required_options){ if(required_options_id){ var required_option = required_options[required_options_id]; if(!options[required_option]){ grunt.fail.fatal("Please set up all required options. All options must be string value! You have not setted " + required_option); } } } var pluginRoot = path.join(path.dirname(fs.realpathSync(__filename)), '../'); var bExt = new BrowserExtension(pluginRoot, options, this.target, grunt); bExt.copyUserFiles(); grunt.verbose.ok('User files copied'); bExt.copyBrowserFiles(); grunt.verbose.ok('Extension files copied'); bExt.buildNsisIE(); grunt.verbose.ok('NSIS installer for IE builded'); bExt.build(); grunt.verbose.ok('Extensions builded'); } }); };
/* * grunt-browser-extension * https://github.com/addmitriev/grunt-browser-extension * * Copyright (c) 2015 Aleksey Dmitriev * Licensed under the MIT license. */ 'use strict'; var util = require('util'); var path = require('path'); var fs = require('fs-extra'); module.exports = function (grunt) { var BrowserExtension = require('./lib/browser-extension')(grunt); grunt.registerMultiTask('browser_extension', 'Grunt plugin to create any browser website extension', function () { if(this.target){ var options = this.options(); var required_options = []; for(var required_options_id in required_options){ if(required_options_id){ var required_option = required_options[required_options_id]; if(!util.isString(options[required_option])){ grunt.fail.fatal("Please set up all required options. All options must be string value! You have not setted " + required_option); } } } var pluginRoot = path.join(path.dirname(fs.realpathSync(__filename)), '../'); var bExt = new BrowserExtension(pluginRoot, options, this.target, grunt); bExt.copyUserFiles(); grunt.verbose.ok('User files copied'); bExt.copyBrowserFiles(); grunt.verbose.ok('Extension files copied'); bExt.buildNsisIE(); grunt.verbose.ok('NSIS installer for IE builded'); bExt.build(); grunt.verbose.ok('Extensions builded'); } }); };
Check config and show what required options not exists
Check config and show what required options not exists
JavaScript
mit
Tuguusl/grunt-browser-extension,Tuguusl/grunt-browser-extension
javascript
## Code Before: /* * grunt-browser-extension * https://github.com/addmitriev/grunt-browser-extension * * Copyright (c) 2015 Aleksey Dmitriev * Licensed under the MIT license. */ 'use strict'; var util = require('util'); var path = require('path'); var fs = require('fs-extra'); module.exports = function (grunt) { var BrowserExtension = require('./lib/browser-extension')(grunt); grunt.registerMultiTask('browser_extension', 'Grunt plugin to create any browser website extension', function () { if(this.target){ var options = this.options(); var required_options = []; for(var required_options_id in required_options){ if(required_options_id){ var required_option = required_options[required_options_id]; if(!options[required_option]){ grunt.fail.fatal("Please set up all required options. All options must be string value! You have not setted " + required_option); } } } var pluginRoot = path.join(path.dirname(fs.realpathSync(__filename)), '../'); var bExt = new BrowserExtension(pluginRoot, options, this.target, grunt); bExt.copyUserFiles(); grunt.verbose.ok('User files copied'); bExt.copyBrowserFiles(); grunt.verbose.ok('Extension files copied'); bExt.buildNsisIE(); grunt.verbose.ok('NSIS installer for IE builded'); bExt.build(); grunt.verbose.ok('Extensions builded'); } }); }; ## Instruction: Check config and show what required options not exists ## Code After: /* * grunt-browser-extension * https://github.com/addmitriev/grunt-browser-extension * * Copyright (c) 2015 Aleksey Dmitriev * Licensed under the MIT license. */ 'use strict'; var util = require('util'); var path = require('path'); var fs = require('fs-extra'); module.exports = function (grunt) { var BrowserExtension = require('./lib/browser-extension')(grunt); grunt.registerMultiTask('browser_extension', 'Grunt plugin to create any browser website extension', function () { if(this.target){ var options = this.options(); var required_options = []; for(var required_options_id in required_options){ if(required_options_id){ var required_option = required_options[required_options_id]; if(!util.isString(options[required_option])){ grunt.fail.fatal("Please set up all required options. All options must be string value! You have not setted " + required_option); } } } var pluginRoot = path.join(path.dirname(fs.realpathSync(__filename)), '../'); var bExt = new BrowserExtension(pluginRoot, options, this.target, grunt); bExt.copyUserFiles(); grunt.verbose.ok('User files copied'); bExt.copyBrowserFiles(); grunt.verbose.ok('Extension files copied'); bExt.buildNsisIE(); grunt.verbose.ok('NSIS installer for IE builded'); bExt.build(); grunt.verbose.ok('Extensions builded'); } }); };
507d665f6d754ffdef5f494ee9e58aa833177b94
capstone/src/main/webapp/dashboard-loader.js
capstone/src/main/webapp/dashboard-loader.js
document.body.prepend(dynamicButton); window.addEventListener('authorized', getClassrooms); function createClassroom(subject) { var auth2 = gapi.auth2.getAuthInstance(); var name = ""; var email = ""; if (auth2.isSignedIn.get()) { name = auth2.currentUser.get().getBasicProfile().getName(); email = auth2.currentUser.get().getBasicProfile().getEmail(); } var classroomData = JSON.stringify({ "nickname": name, "userId": email, "subject": subject }); fetch("/dashboard", {method: "POST", headers: new Headers({ID_TOKEN}), body: classroomData}).then((resp) => { if (resp.ok){ getClassrooms(); } else { console.log("Error has occured"); } }); } function getClassrooms() { fetch("/dashboard", {method: "GET", headers: new Headers({ID_TOKEN})}).then(response => response.json()).then((classroomsList) => { const classroomElement = document.getElementById("classroom-container"); classroomElement.innerHTML = ""; for (classroom of classroomsList) { classroomElement.appendChild(createClassroomDivElement(classroom)); }; }); } function createClassroomDivElement(classroom) { let domparser = new DOMParser(); let doc = domparser.parseFromString(` <div class="classroom"> <h2>${classroom.entity.propertyMap.subject}</h2> <p><a href="form.html">Classroom Link</a></p> </div> `, "text/html"); return doc.body; }
document.body.prepend(dynamicButton); window.addEventListener('authorized', getClassrooms); function createClassroom(subject) { var classroomData = JSON.stringify({"subject": subject}); fetch("/dashboard", {method: "POST", headers: new Headers({ID_TOKEN}), body: classroomData}).then((resp) => { if (resp.ok){ getClassrooms(); } else { console.log("Error has occured"); } }); } function getClassrooms() { fetch("/dashboard", {method: "GET", headers: new Headers({ID_TOKEN})}).then(response => response.json()).then((classroomsList) => { const classroomElement = document.getElementById("classroom-container"); classroomElement.innerHTML = ""; for (classroom of classroomsList) { classroomElement.appendChild(createClassroomDivElement(classroom)); }; }); } function createClassroomDivElement(classroom) { let domparser = new DOMParser(); let doc = domparser.parseFromString(` <div class="classroom"> <h2>${classroom.entity.propertyMap.subject}</h2> <p><a href="form.html">Classroom Link</a></p> </div> `, "text/html"); return doc.body; }
Remove unneeded user info in request
Remove unneeded user info in request
JavaScript
apache-2.0
googleinterns/step152-2020,googleinterns/step152-2020,googleinterns/step152-2020,googleinterns/step152-2020
javascript
## Code Before: document.body.prepend(dynamicButton); window.addEventListener('authorized', getClassrooms); function createClassroom(subject) { var auth2 = gapi.auth2.getAuthInstance(); var name = ""; var email = ""; if (auth2.isSignedIn.get()) { name = auth2.currentUser.get().getBasicProfile().getName(); email = auth2.currentUser.get().getBasicProfile().getEmail(); } var classroomData = JSON.stringify({ "nickname": name, "userId": email, "subject": subject }); fetch("/dashboard", {method: "POST", headers: new Headers({ID_TOKEN}), body: classroomData}).then((resp) => { if (resp.ok){ getClassrooms(); } else { console.log("Error has occured"); } }); } function getClassrooms() { fetch("/dashboard", {method: "GET", headers: new Headers({ID_TOKEN})}).then(response => response.json()).then((classroomsList) => { const classroomElement = document.getElementById("classroom-container"); classroomElement.innerHTML = ""; for (classroom of classroomsList) { classroomElement.appendChild(createClassroomDivElement(classroom)); }; }); } function createClassroomDivElement(classroom) { let domparser = new DOMParser(); let doc = domparser.parseFromString(` <div class="classroom"> <h2>${classroom.entity.propertyMap.subject}</h2> <p><a href="form.html">Classroom Link</a></p> </div> `, "text/html"); return doc.body; } ## Instruction: Remove unneeded user info in request ## Code After: document.body.prepend(dynamicButton); window.addEventListener('authorized', getClassrooms); function createClassroom(subject) { var classroomData = JSON.stringify({"subject": subject}); fetch("/dashboard", {method: "POST", headers: new Headers({ID_TOKEN}), body: classroomData}).then((resp) => { if (resp.ok){ getClassrooms(); } else { console.log("Error has occured"); } }); } function getClassrooms() { fetch("/dashboard", {method: "GET", headers: new Headers({ID_TOKEN})}).then(response => response.json()).then((classroomsList) => { const classroomElement = document.getElementById("classroom-container"); classroomElement.innerHTML = ""; for (classroom of classroomsList) { classroomElement.appendChild(createClassroomDivElement(classroom)); }; }); } function createClassroomDivElement(classroom) { let domparser = new DOMParser(); let doc = domparser.parseFromString(` <div class="classroom"> <h2>${classroom.entity.propertyMap.subject}</h2> <p><a href="form.html">Classroom Link</a></p> </div> `, "text/html"); return doc.body; }
a719ab4c77418b25881e5214dad2eed9af9a7a7d
DependencyInjection/Compiler/AddParamConverterPass.php
DependencyInjection/Compiler/AddParamConverterPass.php
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Sensio\Bundle\FrameworkExtraBundle\DependencyInjection\Compiler; use Symfony\Component\DependencyInjection\Reference; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; /** * Adds tagged request.param_converter services to converter.manager service * * @author Fabien Potencier <fabien@symfony.com> */ class AddParamConverterPass implements CompilerPassInterface { public function process(ContainerBuilder $container) { if (false === $container->hasDefinition('sensio_framework_extra.converter.manager')) { return; } $definition = $container->getDefinition('sensio_framework_extra.converter.manager'); foreach ($container->findTaggedServiceIds('request.param_converter') as $id => $converters) { foreach ($converters as $converter) { $name = isset($converter[0]['converter']) ? $converter[0]['converter'] : null; $priority = isset($converter[0]['priority']) ? $converter[0]['priority'] : 0; if ($priority == "false") { $priority = null; } $definition->addMethodCall('add', array(new Reference($id), $priority, $name)); } } } }
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Sensio\Bundle\FrameworkExtraBundle\DependencyInjection\Compiler; use Symfony\Component\DependencyInjection\Reference; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; /** * Adds tagged request.param_converter services to converter.manager service * * @author Fabien Potencier <fabien@symfony.com> */ class AddParamConverterPass implements CompilerPassInterface { public function process(ContainerBuilder $container) { if (false === $container->hasDefinition('sensio_framework_extra.converter.manager')) { return; } $definition = $container->getDefinition('sensio_framework_extra.converter.manager'); foreach ($container->findTaggedServiceIds('request.param_converter') as $id => $converters) { foreach ($converters as $converter) { $name = isset($converter['converter']) ? $converter['converter'] : null; $priority = isset($converter['priority']) ? $converter['priority'] : 0; if ($priority == "false") { $priority = null; } $definition->addMethodCall('add', array(new Reference($id), $priority, $name)); } } } }
Fix bug introduced with CompilerPass refactoring
Fix bug introduced with CompilerPass refactoring
PHP
mit
sensiolabs/SensioFrameworkExtraBundle,xabbuh/SensioFrameworkExtraBundle,chalasr/SensioFrameworkExtraBundle,chalasr/SensioFrameworkExtraBundle,henrikbjorn/ParamConverter
php
## Code Before: <?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Sensio\Bundle\FrameworkExtraBundle\DependencyInjection\Compiler; use Symfony\Component\DependencyInjection\Reference; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; /** * Adds tagged request.param_converter services to converter.manager service * * @author Fabien Potencier <fabien@symfony.com> */ class AddParamConverterPass implements CompilerPassInterface { public function process(ContainerBuilder $container) { if (false === $container->hasDefinition('sensio_framework_extra.converter.manager')) { return; } $definition = $container->getDefinition('sensio_framework_extra.converter.manager'); foreach ($container->findTaggedServiceIds('request.param_converter') as $id => $converters) { foreach ($converters as $converter) { $name = isset($converter[0]['converter']) ? $converter[0]['converter'] : null; $priority = isset($converter[0]['priority']) ? $converter[0]['priority'] : 0; if ($priority == "false") { $priority = null; } $definition->addMethodCall('add', array(new Reference($id), $priority, $name)); } } } } ## Instruction: Fix bug introduced with CompilerPass refactoring ## Code After: <?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Sensio\Bundle\FrameworkExtraBundle\DependencyInjection\Compiler; use Symfony\Component\DependencyInjection\Reference; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; /** * Adds tagged request.param_converter services to converter.manager service * * @author Fabien Potencier <fabien@symfony.com> */ class AddParamConverterPass implements CompilerPassInterface { public function process(ContainerBuilder $container) { if (false === $container->hasDefinition('sensio_framework_extra.converter.manager')) { return; } $definition = $container->getDefinition('sensio_framework_extra.converter.manager'); foreach ($container->findTaggedServiceIds('request.param_converter') as $id => $converters) { foreach ($converters as $converter) { $name = isset($converter['converter']) ? $converter['converter'] : null; $priority = isset($converter['priority']) ? $converter['priority'] : 0; if ($priority == "false") { $priority = null; } $definition->addMethodCall('add', array(new Reference($id), $priority, $name)); } } } }
d6eafa5c08839d1fc10c5f6dadb53afc694a3c08
src/main/java/com/nincraft/ninbot/command/DabCommand.java
src/main/java/com/nincraft/ninbot/command/DabCommand.java
package com.nincraft.ninbot.command; import com.nincraft.ninbot.util.MessageUtils; import lombok.val; import net.dv8tion.jda.core.entities.Message; import net.dv8tion.jda.core.events.message.MessageReceivedEvent; public class DabCommand extends AbstractCommand { public DabCommand() { length = 3; name = "dab"; description = "Adds all dab emojis to the last message of the user named"; } @Override public void executeCommand(MessageReceivedEvent event) { val content = event.getMessage().getContent(); if (isCommandLengthCorrect(content)) { val channel = event.getChannel(); val dabUser = content.split(" ")[2]; int count = 0; int maxDab = 10; for (Message message : channel.getIterableHistory()) { if (message.getAuthor().getName().equalsIgnoreCase(dabUser)) { dabOnMessage(message); break; } if (count >= maxDab) { MessageUtils.reactUnsuccessfulResponse(event.getMessage()); break; } count++; } } else { MessageUtils.reactUnsuccessfulResponse(event.getMessage()); } } private void dabOnMessage(Message message) { val guild = message.getGuild(); for (val emote : guild.getEmotes()) { if (emote.getName().contains("dab")) { MessageUtils.addReaction(message, emote); } } } }
package com.nincraft.ninbot.command; import com.nincraft.ninbot.util.MessageUtils; import lombok.val; import net.dv8tion.jda.core.entities.Message; import net.dv8tion.jda.core.events.message.MessageReceivedEvent; public class DabCommand extends AbstractCommand { public DabCommand() { length = 3; name = "dab"; description = "Adds all dab emojis to the last message of the user named"; } @Override public void executeCommand(MessageReceivedEvent event) { val content = event.getMessage().getContent(); if (isCommandLengthCorrect(content)) { val channel = event.getChannel(); val dabUser = content.split(" ")[2].replaceFirst("@", ""); int count = 0; int maxDab = 10; for (Message message : channel.getIterableHistory()) { if (message.getAuthor().getName().equalsIgnoreCase(dabUser)) { dabOnMessage(message); break; } if (count >= maxDab) { MessageUtils.reactUnsuccessfulResponse(event.getMessage()); break; } count++; } } else { MessageUtils.reactUnsuccessfulResponse(event.getMessage()); } } private void dabOnMessage(Message message) { val guild = message.getGuild(); for (val emote : guild.getEmotes()) { if (emote.getName().contains("dab")) { MessageUtils.addReaction(message, emote); } } } }
Remove @ from user on Dab command
Remove @ from user on Dab command
Java
mit
Nincodedo/Ninbot
java
## Code Before: package com.nincraft.ninbot.command; import com.nincraft.ninbot.util.MessageUtils; import lombok.val; import net.dv8tion.jda.core.entities.Message; import net.dv8tion.jda.core.events.message.MessageReceivedEvent; public class DabCommand extends AbstractCommand { public DabCommand() { length = 3; name = "dab"; description = "Adds all dab emojis to the last message of the user named"; } @Override public void executeCommand(MessageReceivedEvent event) { val content = event.getMessage().getContent(); if (isCommandLengthCorrect(content)) { val channel = event.getChannel(); val dabUser = content.split(" ")[2]; int count = 0; int maxDab = 10; for (Message message : channel.getIterableHistory()) { if (message.getAuthor().getName().equalsIgnoreCase(dabUser)) { dabOnMessage(message); break; } if (count >= maxDab) { MessageUtils.reactUnsuccessfulResponse(event.getMessage()); break; } count++; } } else { MessageUtils.reactUnsuccessfulResponse(event.getMessage()); } } private void dabOnMessage(Message message) { val guild = message.getGuild(); for (val emote : guild.getEmotes()) { if (emote.getName().contains("dab")) { MessageUtils.addReaction(message, emote); } } } } ## Instruction: Remove @ from user on Dab command ## Code After: package com.nincraft.ninbot.command; import com.nincraft.ninbot.util.MessageUtils; import lombok.val; import net.dv8tion.jda.core.entities.Message; import net.dv8tion.jda.core.events.message.MessageReceivedEvent; public class DabCommand extends AbstractCommand { public DabCommand() { length = 3; name = "dab"; description = "Adds all dab emojis to the last message of the user named"; } @Override public void executeCommand(MessageReceivedEvent event) { val content = event.getMessage().getContent(); if (isCommandLengthCorrect(content)) { val channel = event.getChannel(); val dabUser = content.split(" ")[2].replaceFirst("@", ""); int count = 0; int maxDab = 10; for (Message message : channel.getIterableHistory()) { if (message.getAuthor().getName().equalsIgnoreCase(dabUser)) { dabOnMessage(message); break; } if (count >= maxDab) { MessageUtils.reactUnsuccessfulResponse(event.getMessage()); break; } count++; } } else { MessageUtils.reactUnsuccessfulResponse(event.getMessage()); } } private void dabOnMessage(Message message) { val guild = message.getGuild(); for (val emote : guild.getEmotes()) { if (emote.getName().contains("dab")) { MessageUtils.addReaction(message, emote); } } } }
dcfb66925c5a73d79c4bd5c986de38f48a65f4b0
laravel/webpack.config.js
laravel/webpack.config.js
require('dotenv').config(); const webpack = require('webpack'); // I don't really like doing it this way but it works for a limited number // of configuration options. const socketsEnabled = process.env.WEBSOCKETS_ENABLED && process.env.WEBSOCKETS_ENABLED != ('false' || '0'); const appEntry = socketsEnabled ? './resources/app.js' : './resources/app_nosockets.js'; module.exports = { entry: { main: appEntry }, output: { filename: './public/js/bundle.js' }, module: { rules: [ { test: /\.s[ac]ss$/i, use: [ // Creates `style` nodes from JS strings 'style-loader', // Translates CSS into CommonJS 'css-loader', // Compiles Sass to CSS 'sass-loader', ], }, { test: /\.html\.tpl$/, loader: 'ejs-loader', options: { variable: 'data', } }, { test: /\.js$/, exclude: /(node_modules|bower_components)/, use: { loader: 'babel-loader', options: { presets: ['@babel/preset-env'] } } } ] }, plugins: [ new webpack.ProvidePlugin({ _: 'lodash' }) ] };
require('dotenv').config(); const path = require('path'); const webpack = require('webpack'); // I don't really like doing it this way but it works for a limited number // of configuration options. const socketsEnabled = process.env.WEBSOCKETS_ENABLED && process.env.WEBSOCKETS_ENABLED != ('false' || '0'); const appEntry = socketsEnabled ? './resources/app.js' : './resources/app_nosockets.js'; module.exports = { entry: { main: appEntry }, output: { filename: "bundle.js", path: path.resolve(__dirname, "./public/js/"), publicPath: "/js/" }, module: { rules: [ { test: /\.s[ac]ss$/i, use: [ // Creates `style` nodes from JS strings 'style-loader', // Translates CSS into CommonJS 'css-loader', // Compiles Sass to CSS 'sass-loader', ], }, { test: /\.html\.tpl$/, loader: 'ejs-loader', options: { variable: 'data', } }, { test: /\.js$/, exclude: /(node_modules|bower_components)/, use: { loader: 'babel-loader', options: { presets: ['@babel/preset-env'] } } } ] }, plugins: [ new webpack.ProvidePlugin({ _: 'lodash' }) ] };
Fix the webpack putting files into dist/ by mistake
Fix the webpack putting files into dist/ by mistake
JavaScript
agpl-3.0
playasoft/laravel-voldb,playasoft/laravel-voldb,playasoft/laravel-voldb,itsrachelfish/laravel-voldb,itsrachelfish/laravel-voldb
javascript
## Code Before: require('dotenv').config(); const webpack = require('webpack'); // I don't really like doing it this way but it works for a limited number // of configuration options. const socketsEnabled = process.env.WEBSOCKETS_ENABLED && process.env.WEBSOCKETS_ENABLED != ('false' || '0'); const appEntry = socketsEnabled ? './resources/app.js' : './resources/app_nosockets.js'; module.exports = { entry: { main: appEntry }, output: { filename: './public/js/bundle.js' }, module: { rules: [ { test: /\.s[ac]ss$/i, use: [ // Creates `style` nodes from JS strings 'style-loader', // Translates CSS into CommonJS 'css-loader', // Compiles Sass to CSS 'sass-loader', ], }, { test: /\.html\.tpl$/, loader: 'ejs-loader', options: { variable: 'data', } }, { test: /\.js$/, exclude: /(node_modules|bower_components)/, use: { loader: 'babel-loader', options: { presets: ['@babel/preset-env'] } } } ] }, plugins: [ new webpack.ProvidePlugin({ _: 'lodash' }) ] }; ## Instruction: Fix the webpack putting files into dist/ by mistake ## Code After: require('dotenv').config(); const path = require('path'); const webpack = require('webpack'); // I don't really like doing it this way but it works for a limited number // of configuration options. const socketsEnabled = process.env.WEBSOCKETS_ENABLED && process.env.WEBSOCKETS_ENABLED != ('false' || '0'); const appEntry = socketsEnabled ? './resources/app.js' : './resources/app_nosockets.js'; module.exports = { entry: { main: appEntry }, output: { filename: "bundle.js", path: path.resolve(__dirname, "./public/js/"), publicPath: "/js/" }, module: { rules: [ { test: /\.s[ac]ss$/i, use: [ // Creates `style` nodes from JS strings 'style-loader', // Translates CSS into CommonJS 'css-loader', // Compiles Sass to CSS 'sass-loader', ], }, { test: /\.html\.tpl$/, loader: 'ejs-loader', options: { variable: 'data', } }, { test: /\.js$/, exclude: /(node_modules|bower_components)/, use: { loader: 'babel-loader', options: { presets: ['@babel/preset-env'] } } } ] }, plugins: [ new webpack.ProvidePlugin({ _: 'lodash' }) ] };
33239257ff65e7079574eec65d432750add01f3a
tests/Properties/DelegatingAdditionalPropertiesResolverTest.php
tests/Properties/DelegatingAdditionalPropertiesResolverTest.php
<?php namespace SimpleBus\Asynchronous\Tests\Properties; use PHPUnit\Framework\TestCase; use SimpleBus\Asynchronous\Properties\AdditionalPropertiesResolver; use SimpleBus\Asynchronous\Properties\DelegatingAdditionalPropertiesResolver; class DelegatingAdditionalPropertiesResolverTest extends TestCase { /** * @test */ public function it_should_merge_multiple_resolvers() { $message = $this->messageDummy(); $resolver = new DelegatingAdditionalPropertiesResolver(array( $this->getResolver($message, array('test' => 'a')), $this->getResolver($message, array('test' => 'b', 'priority' => 123)), )); $this->assertSame(['test' => 'b', 'priority' => 123], $resolver->resolveAdditionalPropertiesFor($message)); } /** * @param object $message * @param array $data * * @return \PHPUnit\Framework\MockObject\MockObject|AdditionalPropertiesResolver */ private function getResolver($message, array $data) { $resolver = $this->createMock('SimpleBus\Asynchronous\Properties\AdditionalPropertiesResolver'); $resolver->expects($this->once()) ->method('resolveAdditionalPropertiesFor') ->with($this->identicalTo($message)) ->will($this->returnValue($data)); return $resolver; } /** * @return \PHPUnit\Framework\MockObject\MockObject|object */ private function messageDummy() { return new \stdClass(); } }
<?php namespace SimpleBus\Asynchronous\Tests\Properties; use PHPUnit\Framework\TestCase; use SimpleBus\Asynchronous\Properties\AdditionalPropertiesResolver; use SimpleBus\Asynchronous\Properties\DelegatingAdditionalPropertiesResolver; class DelegatingAdditionalPropertiesResolverTest extends TestCase { /** * @test */ public function it_should_merge_multiple_resolvers() { $message = $this->messageDummy(); $resolver = new DelegatingAdditionalPropertiesResolver([ $this->getResolver($message, ['test' => 'a']), $this->getResolver($message, ['test' => 'b', 'priority' => 123]), ]); $this->assertSame(['test' => 'b', 'priority' => 123], $resolver->resolveAdditionalPropertiesFor($message)); } /** * @param object $message * @param array $data * * @return \PHPUnit\Framework\MockObject\MockObject|AdditionalPropertiesResolver */ private function getResolver($message, array $data) { $resolver = $this->createMock('SimpleBus\Asynchronous\Properties\AdditionalPropertiesResolver'); $resolver->expects($this->once()) ->method('resolveAdditionalPropertiesFor') ->with($this->identicalTo($message)) ->will($this->returnValue($data)); return $resolver; } /** * @return \PHPUnit\Framework\MockObject\MockObject|object */ private function messageDummy() { return new \stdClass(); } }
Add PHP-CS-Fixer with a simple baseline
Add PHP-CS-Fixer with a simple baseline
PHP
mit
SimpleBus/Asynchronous
php
## Code Before: <?php namespace SimpleBus\Asynchronous\Tests\Properties; use PHPUnit\Framework\TestCase; use SimpleBus\Asynchronous\Properties\AdditionalPropertiesResolver; use SimpleBus\Asynchronous\Properties\DelegatingAdditionalPropertiesResolver; class DelegatingAdditionalPropertiesResolverTest extends TestCase { /** * @test */ public function it_should_merge_multiple_resolvers() { $message = $this->messageDummy(); $resolver = new DelegatingAdditionalPropertiesResolver(array( $this->getResolver($message, array('test' => 'a')), $this->getResolver($message, array('test' => 'b', 'priority' => 123)), )); $this->assertSame(['test' => 'b', 'priority' => 123], $resolver->resolveAdditionalPropertiesFor($message)); } /** * @param object $message * @param array $data * * @return \PHPUnit\Framework\MockObject\MockObject|AdditionalPropertiesResolver */ private function getResolver($message, array $data) { $resolver = $this->createMock('SimpleBus\Asynchronous\Properties\AdditionalPropertiesResolver'); $resolver->expects($this->once()) ->method('resolveAdditionalPropertiesFor') ->with($this->identicalTo($message)) ->will($this->returnValue($data)); return $resolver; } /** * @return \PHPUnit\Framework\MockObject\MockObject|object */ private function messageDummy() { return new \stdClass(); } } ## Instruction: Add PHP-CS-Fixer with a simple baseline ## Code After: <?php namespace SimpleBus\Asynchronous\Tests\Properties; use PHPUnit\Framework\TestCase; use SimpleBus\Asynchronous\Properties\AdditionalPropertiesResolver; use SimpleBus\Asynchronous\Properties\DelegatingAdditionalPropertiesResolver; class DelegatingAdditionalPropertiesResolverTest extends TestCase { /** * @test */ public function it_should_merge_multiple_resolvers() { $message = $this->messageDummy(); $resolver = new DelegatingAdditionalPropertiesResolver([ $this->getResolver($message, ['test' => 'a']), $this->getResolver($message, ['test' => 'b', 'priority' => 123]), ]); $this->assertSame(['test' => 'b', 'priority' => 123], $resolver->resolveAdditionalPropertiesFor($message)); } /** * @param object $message * @param array $data * * @return \PHPUnit\Framework\MockObject\MockObject|AdditionalPropertiesResolver */ private function getResolver($message, array $data) { $resolver = $this->createMock('SimpleBus\Asynchronous\Properties\AdditionalPropertiesResolver'); $resolver->expects($this->once()) ->method('resolveAdditionalPropertiesFor') ->with($this->identicalTo($message)) ->will($this->returnValue($data)); return $resolver; } /** * @return \PHPUnit\Framework\MockObject\MockObject|object */ private function messageDummy() { return new \stdClass(); } }
060d23439de45065aec734b031e4be2445acbd40
src/processTailwindFeatures.js
src/processTailwindFeatures.js
import _ from 'lodash' import postcss from 'postcss' import substituteTailwindAtRules from './lib/substituteTailwindAtRules' import evaluateTailwindFunctions from './lib/evaluateTailwindFunctions' import substituteVariantsAtRules from './lib/substituteVariantsAtRules' import substituteResponsiveAtRules from './lib/substituteResponsiveAtRules' import substituteScreenAtRules from './lib/substituteScreenAtRules' import substituteClassApplyAtRules from './lib/substituteClassApplyAtRules' import processPlugins from './util/processPlugins' import defaultPlugins from './defaultPlugins' export default function(getConfig) { return function(css) { const config = getConfig() const processedPlugins = processPlugins([...defaultPlugins(config), ...config.plugins], config) return postcss([ substituteTailwindAtRules(config, processedPlugins, processedPlugins.utilities), evaluateTailwindFunctions(config), substituteVariantsAtRules(config, processedPlugins), substituteResponsiveAtRules(config), substituteScreenAtRules(config), substituteClassApplyAtRules(config, processedPlugins.utilities), // This quick plugin is necessary to avoid a serious performance // hit due to nodes created by postcss-js having an empty `raws` // value, and PostCSS not providing a default `raws.semicolon` // value. This turns determining what value to use there into an // O(n) operation instead of an O(1) operation. // // The latest version of PostCSS 7.x has this patched internally, // but patching from userland until we upgrade from v6 to v7. function(root) { root.rawCache = { colon: ': ', indent: ' ', beforeDecl: '\n', beforeRule: '\n', beforeOpen: ' ', beforeClose: '\n', beforeComment: '\n', after: '\n', emptyBody: '', commentLeft: ' ', commentRight: ' ', semicolon: false, } }, ]).process(css, { from: _.get(css, 'source.input.file') }) } }
import _ from 'lodash' import postcss from 'postcss' import substituteTailwindAtRules from './lib/substituteTailwindAtRules' import evaluateTailwindFunctions from './lib/evaluateTailwindFunctions' import substituteVariantsAtRules from './lib/substituteVariantsAtRules' import substituteResponsiveAtRules from './lib/substituteResponsiveAtRules' import substituteScreenAtRules from './lib/substituteScreenAtRules' import substituteClassApplyAtRules from './lib/substituteClassApplyAtRules' import processPlugins from './util/processPlugins' import defaultPlugins from './defaultPlugins' export default function(getConfig) { return function(css) { const config = getConfig() const processedPlugins = processPlugins([...defaultPlugins(config), ...config.plugins], config) return postcss([ substituteTailwindAtRules(config, processedPlugins, processedPlugins.utilities), evaluateTailwindFunctions(config), substituteVariantsAtRules(config, processedPlugins), substituteResponsiveAtRules(config), substituteScreenAtRules(config), substituteClassApplyAtRules(config, processedPlugins.utilities), ]).process(css, { from: _.get(css, 'source.input.file') }) } }
Remove code obsoleted by upgrading PostCSS
Remove code obsoleted by upgrading PostCSS
JavaScript
mit
tailwindlabs/tailwindcss,tailwindcss/tailwindcss,tailwindlabs/tailwindcss,tailwindlabs/tailwindcss
javascript
## Code Before: import _ from 'lodash' import postcss from 'postcss' import substituteTailwindAtRules from './lib/substituteTailwindAtRules' import evaluateTailwindFunctions from './lib/evaluateTailwindFunctions' import substituteVariantsAtRules from './lib/substituteVariantsAtRules' import substituteResponsiveAtRules from './lib/substituteResponsiveAtRules' import substituteScreenAtRules from './lib/substituteScreenAtRules' import substituteClassApplyAtRules from './lib/substituteClassApplyAtRules' import processPlugins from './util/processPlugins' import defaultPlugins from './defaultPlugins' export default function(getConfig) { return function(css) { const config = getConfig() const processedPlugins = processPlugins([...defaultPlugins(config), ...config.plugins], config) return postcss([ substituteTailwindAtRules(config, processedPlugins, processedPlugins.utilities), evaluateTailwindFunctions(config), substituteVariantsAtRules(config, processedPlugins), substituteResponsiveAtRules(config), substituteScreenAtRules(config), substituteClassApplyAtRules(config, processedPlugins.utilities), // This quick plugin is necessary to avoid a serious performance // hit due to nodes created by postcss-js having an empty `raws` // value, and PostCSS not providing a default `raws.semicolon` // value. This turns determining what value to use there into an // O(n) operation instead of an O(1) operation. // // The latest version of PostCSS 7.x has this patched internally, // but patching from userland until we upgrade from v6 to v7. function(root) { root.rawCache = { colon: ': ', indent: ' ', beforeDecl: '\n', beforeRule: '\n', beforeOpen: ' ', beforeClose: '\n', beforeComment: '\n', after: '\n', emptyBody: '', commentLeft: ' ', commentRight: ' ', semicolon: false, } }, ]).process(css, { from: _.get(css, 'source.input.file') }) } } ## Instruction: Remove code obsoleted by upgrading PostCSS ## Code After: import _ from 'lodash' import postcss from 'postcss' import substituteTailwindAtRules from './lib/substituteTailwindAtRules' import evaluateTailwindFunctions from './lib/evaluateTailwindFunctions' import substituteVariantsAtRules from './lib/substituteVariantsAtRules' import substituteResponsiveAtRules from './lib/substituteResponsiveAtRules' import substituteScreenAtRules from './lib/substituteScreenAtRules' import substituteClassApplyAtRules from './lib/substituteClassApplyAtRules' import processPlugins from './util/processPlugins' import defaultPlugins from './defaultPlugins' export default function(getConfig) { return function(css) { const config = getConfig() const processedPlugins = processPlugins([...defaultPlugins(config), ...config.plugins], config) return postcss([ substituteTailwindAtRules(config, processedPlugins, processedPlugins.utilities), evaluateTailwindFunctions(config), substituteVariantsAtRules(config, processedPlugins), substituteResponsiveAtRules(config), substituteScreenAtRules(config), substituteClassApplyAtRules(config, processedPlugins.utilities), ]).process(css, { from: _.get(css, 'source.input.file') }) } }
817f340f4313553cc0c8a386cc4984d244a0bc2c
app/models/user.rb
app/models/user.rb
class User < ActiveRecord::Base has_secure_password has_many :photo_queues has_many :photos, through: :photo_queues validates :username, :email, presence: true validates :username, :email, uniqueness: true validates :username, format: { with: /\A[a-zA-Z0-9]+\z/, message: "only allows letters and numbers" } validates :username, length: { in: 2..25 } validates :password, length: { in: 8..48 }, allow_nil: true serialize :unsplash_token def add_photos_to_queue(photos_to_add) photos.create(photos_to_add) if invalid? invalid_ids = photos.map {|x| x.unsplash_id if x.invalid?}.compact in_db = Photo.where(unsplash_id: invalid_ids) in_queue = photo_queues.where(photo_id: in_db).pluck(:photo_id) photos << in_db.select {|x| !in_queue.include?(x.id)} end # existing_photos = Photo.where(unsplash_id: unsplash_ids) # existing_queues = PhotoQueue. # includes(:photos). # where(photo_id: existing_photos) # photos_to_add.each do |photo| # photos.find_or_create_by(unsplash_id: photo[:unsplash_id]) do |x| # x.width = photo[:width] # x.height = photo[:height] # x.photographer_name = photo[:photographer_name] # x.photographer_link = photo[:photographer_link] # x.raw_url = photo[:raw_url] # x.full_url = photo[:full_url] # x.regular_url = photo[:regular_url] # x.small_url = photo[:small_url] # x.thumb_url = photo[:thumb_url] # x.link = photo[:link] # end # end end end
class User < ActiveRecord::Base has_secure_password has_many :photo_queues has_many :photos, through: :photo_queues validates :username, :email, presence: true validates :username, :email, uniqueness: true validates :username, format: { with: /\A[a-zA-Z0-9]+\z/, message: "only allows letters and numbers" } validates :username, length: { in: 2..25 } validates :password, length: { in: 8..48 }, allow_nil: true serialize :unsplash_token def add_photos_to_queue(photos_to_add) photos.create(photos_to_add) if invalid? invalid_ids = photos.map {|x| x.unsplash_id if x.invalid?}.compact in_db = Photo.where(unsplash_id: invalid_ids) in_queue = photo_queues.where(photo_id: in_db).pluck(:photo_id) photos << in_db.select {|x| !in_queue.include?(x.id)} end end end
Remove unused code in User model
Remove unused code in User model
Ruby
mit
snsavage/photovistas,snsavage/photovistas
ruby
## Code Before: class User < ActiveRecord::Base has_secure_password has_many :photo_queues has_many :photos, through: :photo_queues validates :username, :email, presence: true validates :username, :email, uniqueness: true validates :username, format: { with: /\A[a-zA-Z0-9]+\z/, message: "only allows letters and numbers" } validates :username, length: { in: 2..25 } validates :password, length: { in: 8..48 }, allow_nil: true serialize :unsplash_token def add_photos_to_queue(photos_to_add) photos.create(photos_to_add) if invalid? invalid_ids = photos.map {|x| x.unsplash_id if x.invalid?}.compact in_db = Photo.where(unsplash_id: invalid_ids) in_queue = photo_queues.where(photo_id: in_db).pluck(:photo_id) photos << in_db.select {|x| !in_queue.include?(x.id)} end # existing_photos = Photo.where(unsplash_id: unsplash_ids) # existing_queues = PhotoQueue. # includes(:photos). # where(photo_id: existing_photos) # photos_to_add.each do |photo| # photos.find_or_create_by(unsplash_id: photo[:unsplash_id]) do |x| # x.width = photo[:width] # x.height = photo[:height] # x.photographer_name = photo[:photographer_name] # x.photographer_link = photo[:photographer_link] # x.raw_url = photo[:raw_url] # x.full_url = photo[:full_url] # x.regular_url = photo[:regular_url] # x.small_url = photo[:small_url] # x.thumb_url = photo[:thumb_url] # x.link = photo[:link] # end # end end end ## Instruction: Remove unused code in User model ## Code After: class User < ActiveRecord::Base has_secure_password has_many :photo_queues has_many :photos, through: :photo_queues validates :username, :email, presence: true validates :username, :email, uniqueness: true validates :username, format: { with: /\A[a-zA-Z0-9]+\z/, message: "only allows letters and numbers" } validates :username, length: { in: 2..25 } validates :password, length: { in: 8..48 }, allow_nil: true serialize :unsplash_token def add_photos_to_queue(photos_to_add) photos.create(photos_to_add) if invalid? invalid_ids = photos.map {|x| x.unsplash_id if x.invalid?}.compact in_db = Photo.where(unsplash_id: invalid_ids) in_queue = photo_queues.where(photo_id: in_db).pluck(:photo_id) photos << in_db.select {|x| !in_queue.include?(x.id)} end end end
317926c18ac2e139d2018acd767d10b4f53428f3
installer/installer_config/views.py
installer/installer_config/views.py
from django.shortcuts import render from django.shortcuts import render_to_response from django.views.generic import CreateView, UpdateView, DeleteView from installer_config.models import EnvironmentProfile, UserChoice, Step from installer_config.forms import EnvironmentForm from django.core.urlresolvers import reverse from django.http import HttpResponseRedirect class CreateEnvironmentProfile(CreateView): model = EnvironmentProfile template_name = 'env_profile_form.html' form_class = EnvironmentForm success_url = '/profile' def form_valid(self, form): form.instance.user = self.request.user return super(CreateEnvironmentProfile, self).form_valid(form) def post(self, request, *args, **kwargs): form_class = self.get_form_class() form = form_class(request.POST) if form.is_valid(): config_profile = form.save(commit=False) config_profile.user = request.user config_profile.save() return HttpResponseRedirect(reverse('profile:profile')) return self.render_to_response({'form': form}) class UpdateEnvironmentProfile(UpdateView): model = EnvironmentProfile context_object_name = 'profile' template_name = 'env_profile_form.html' form_class = EnvironmentForm success_url = '/profile' class DeleteEnvironmentProfile(DeleteView): model = EnvironmentProfile success_url = '/profile' def download_profile_view(request, **kwargs): choices = UserChoice.objects.filter(profiles=kwargs['pk']).all() # import pdb; pdb.set_trace() response = render_to_response('installer_template.py', {'choices': choices}, content_type='application') response['Content-Disposition'] = 'attachment; filename=something.py' return response
from django.shortcuts import render from django.shortcuts import render_to_response from django.views.generic import CreateView, UpdateView, DeleteView from installer_config.models import EnvironmentProfile, UserChoice, Step from installer_config.forms import EnvironmentForm from django.core.urlresolvers import reverse class CreateEnvironmentProfile(CreateView): model = EnvironmentProfile template_name = 'env_profile_form.html' form_class = EnvironmentForm success_url = '/profile' def form_valid(self, form): form.instance.user = self.request.user return super(CreateEnvironmentProfile, self).form_valid(form) class UpdateEnvironmentProfile(UpdateView): model = EnvironmentProfile context_object_name = 'profile' template_name = 'env_profile_form.html' form_class = EnvironmentForm success_url = '/profile' class DeleteEnvironmentProfile(DeleteView): model = EnvironmentProfile success_url = '/profile' def download_profile_view(request, **kwargs): choices = UserChoice.objects.filter(profiles=kwargs['pk']).all() response = render_to_response('installer_template.py', {'choices': choices}, content_type='application') response['Content-Disposition'] = 'attachment; filename=something.py' return response
Remove unneeded post method from CreateEnvProfile view
Remove unneeded post method from CreateEnvProfile view
Python
mit
ezPy-co/ezpy,alibulota/Package_Installer,ezPy-co/ezpy,alibulota/Package_Installer
python
## Code Before: from django.shortcuts import render from django.shortcuts import render_to_response from django.views.generic import CreateView, UpdateView, DeleteView from installer_config.models import EnvironmentProfile, UserChoice, Step from installer_config.forms import EnvironmentForm from django.core.urlresolvers import reverse from django.http import HttpResponseRedirect class CreateEnvironmentProfile(CreateView): model = EnvironmentProfile template_name = 'env_profile_form.html' form_class = EnvironmentForm success_url = '/profile' def form_valid(self, form): form.instance.user = self.request.user return super(CreateEnvironmentProfile, self).form_valid(form) def post(self, request, *args, **kwargs): form_class = self.get_form_class() form = form_class(request.POST) if form.is_valid(): config_profile = form.save(commit=False) config_profile.user = request.user config_profile.save() return HttpResponseRedirect(reverse('profile:profile')) return self.render_to_response({'form': form}) class UpdateEnvironmentProfile(UpdateView): model = EnvironmentProfile context_object_name = 'profile' template_name = 'env_profile_form.html' form_class = EnvironmentForm success_url = '/profile' class DeleteEnvironmentProfile(DeleteView): model = EnvironmentProfile success_url = '/profile' def download_profile_view(request, **kwargs): choices = UserChoice.objects.filter(profiles=kwargs['pk']).all() # import pdb; pdb.set_trace() response = render_to_response('installer_template.py', {'choices': choices}, content_type='application') response['Content-Disposition'] = 'attachment; filename=something.py' return response ## Instruction: Remove unneeded post method from CreateEnvProfile view ## Code After: from django.shortcuts import render from django.shortcuts import render_to_response from django.views.generic import CreateView, UpdateView, DeleteView from installer_config.models import EnvironmentProfile, UserChoice, Step from installer_config.forms import EnvironmentForm from django.core.urlresolvers import reverse class CreateEnvironmentProfile(CreateView): model = EnvironmentProfile template_name = 'env_profile_form.html' form_class = EnvironmentForm success_url = '/profile' def form_valid(self, form): form.instance.user = self.request.user return super(CreateEnvironmentProfile, self).form_valid(form) class UpdateEnvironmentProfile(UpdateView): model = EnvironmentProfile context_object_name = 'profile' template_name = 'env_profile_form.html' form_class = EnvironmentForm success_url = '/profile' class DeleteEnvironmentProfile(DeleteView): model = EnvironmentProfile success_url = '/profile' def download_profile_view(request, **kwargs): choices = UserChoice.objects.filter(profiles=kwargs['pk']).all() response = render_to_response('installer_template.py', {'choices': choices}, content_type='application') response['Content-Disposition'] = 'attachment; filename=something.py' return response
9132ed970a4425ff8d0dca691de90136c21379c7
packages/strapi-plugin-content-manager/services/utils/configuration/settings.js
packages/strapi-plugin-content-manager/services/utils/configuration/settings.js
'use strict'; const _ = require('lodash'); const { isSortable } = require('./attributes'); const getDefaultMainField = schema => { if (schema.modelType == 'group') { // find first group attribute that is sortable return ( Object.keys(schema.attributes).find(key => isSortable(schema, key)) || 'id' ); } return 'id'; }; /** * Retunrs a configuration default settings */ async function createDefaultSettings(schema) { const generalSettings = await strapi.plugins[ 'content-manager' ].services.generalsettings.getGeneralSettings(); let defaultField = getDefaultMainField(schema); return { ...generalSettings, mainField: defaultField, defaultSortBy: defaultField, defaultSortOrder: 'ASC', ..._.pick(_.get(schema, ['config', 'settings'], {}), [ 'searchable', 'filterable', 'bulkable', 'pageSize', 'mainField', 'defaultSortBy', 'defaultSortOrder', ]), }; } /** Synchronisation functions */ async function syncSettings(configuration, schema) { if (_.isEmpty(configuration.settings)) return createDefaultSettings(schema); let defaultField = getDefaultMainField(schema); const { mainField = defaultField, defaultSortBy = defaultField } = configuration.settings || {}; return { ...configuration.settings, mainField: isSortable(schema, mainField) ? mainField : defaultField, defaultSortBy: isSortable(schema, defaultSortBy) ? defaultSortBy : defaultField, }; } module.exports = { createDefaultSettings, syncSettings, };
'use strict'; const _ = require('lodash'); const { isSortable } = require('./attributes'); const getDefaultMainField = schema => Object.keys(schema.attributes).find( key => schema.attributes[key].type === 'string' ) || 'id'; /** * Retunrs a configuration default settings */ async function createDefaultSettings(schema) { const generalSettings = await strapi.plugins[ 'content-manager' ].services.generalsettings.getGeneralSettings(); let defaultField = getDefaultMainField(schema); return { ...generalSettings, mainField: defaultField, defaultSortBy: defaultField, defaultSortOrder: 'ASC', ..._.pick(_.get(schema, ['config', 'settings'], {}), [ 'searchable', 'filterable', 'bulkable', 'pageSize', 'mainField', 'defaultSortBy', 'defaultSortOrder', ]), }; } /** Synchronisation functions */ async function syncSettings(configuration, schema) { if (_.isEmpty(configuration.settings)) return createDefaultSettings(schema); let defaultField = getDefaultMainField(schema); const { mainField = defaultField, defaultSortBy = defaultField } = configuration.settings || {}; return { ...configuration.settings, mainField: isSortable(schema, mainField) ? mainField : defaultField, defaultSortBy: isSortable(schema, defaultSortBy) ? defaultSortBy : defaultField, }; } module.exports = { createDefaultSettings, syncSettings, };
Set content type mainField to be a string if possible else id
Set content type mainField to be a string if possible else id
JavaScript
mit
wistityhq/strapi,wistityhq/strapi
javascript
## Code Before: 'use strict'; const _ = require('lodash'); const { isSortable } = require('./attributes'); const getDefaultMainField = schema => { if (schema.modelType == 'group') { // find first group attribute that is sortable return ( Object.keys(schema.attributes).find(key => isSortable(schema, key)) || 'id' ); } return 'id'; }; /** * Retunrs a configuration default settings */ async function createDefaultSettings(schema) { const generalSettings = await strapi.plugins[ 'content-manager' ].services.generalsettings.getGeneralSettings(); let defaultField = getDefaultMainField(schema); return { ...generalSettings, mainField: defaultField, defaultSortBy: defaultField, defaultSortOrder: 'ASC', ..._.pick(_.get(schema, ['config', 'settings'], {}), [ 'searchable', 'filterable', 'bulkable', 'pageSize', 'mainField', 'defaultSortBy', 'defaultSortOrder', ]), }; } /** Synchronisation functions */ async function syncSettings(configuration, schema) { if (_.isEmpty(configuration.settings)) return createDefaultSettings(schema); let defaultField = getDefaultMainField(schema); const { mainField = defaultField, defaultSortBy = defaultField } = configuration.settings || {}; return { ...configuration.settings, mainField: isSortable(schema, mainField) ? mainField : defaultField, defaultSortBy: isSortable(schema, defaultSortBy) ? defaultSortBy : defaultField, }; } module.exports = { createDefaultSettings, syncSettings, }; ## Instruction: Set content type mainField to be a string if possible else id ## Code After: 'use strict'; const _ = require('lodash'); const { isSortable } = require('./attributes'); const getDefaultMainField = schema => Object.keys(schema.attributes).find( key => schema.attributes[key].type === 'string' ) || 'id'; /** * Retunrs a configuration default settings */ async function createDefaultSettings(schema) { const generalSettings = await strapi.plugins[ 'content-manager' ].services.generalsettings.getGeneralSettings(); let defaultField = getDefaultMainField(schema); return { ...generalSettings, mainField: defaultField, defaultSortBy: defaultField, defaultSortOrder: 'ASC', ..._.pick(_.get(schema, ['config', 'settings'], {}), [ 'searchable', 'filterable', 'bulkable', 'pageSize', 'mainField', 'defaultSortBy', 'defaultSortOrder', ]), }; } /** Synchronisation functions */ async function syncSettings(configuration, schema) { if (_.isEmpty(configuration.settings)) return createDefaultSettings(schema); let defaultField = getDefaultMainField(schema); const { mainField = defaultField, defaultSortBy = defaultField } = configuration.settings || {}; return { ...configuration.settings, mainField: isSortable(schema, mainField) ? mainField : defaultField, defaultSortBy: isSortable(schema, defaultSortBy) ? defaultSortBy : defaultField, }; } module.exports = { createDefaultSettings, syncSettings, };
f0bc01603b491f14e593cc24329c18efc2beaf40
lib/amazon/metadata-config.js
lib/amazon/metadata-config.js
// -------------------------------------------------------------------------------------------------------------------- // // metadata-config.js - config for AWS Instance Metadata // // Copyright (c) 2011, 2012 AppsAttic Ltd - http://www.appsattic.com/ // Written by Andrew Chilton <chilts@appsattic.com> // // License: http://opensource.org/licenses/MIT // // -------------------------------------------------------------------------------------------------------------------- function pathCategory(options, args) { return '/' + args.Version + args.Category; } function pathLatest(options, args) { return '/latest/' + args.Category; } // -------------------------------------------------------------------------------------------------------------------- // From: http://docs.amazonwebservices.com/AWSEC2/latest/UserGuide/AESDG-chapter-instancedata.html module.exports = { 'ListApiVersions' : { // request 'path' : '/', // response 'body' : 'blob', }, 'Get' : { // request 'path' : pathCategory, 'args' : { Category : { 'required' : true, 'type' : 'special', }, Version : { 'required' : true, 'type' : 'special', }, }, // response 'body' : 'blob', }, }; // --------------------------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------------------------- // // metadata-config.js - config for AWS Instance Metadata // // Copyright (c) 2011, 2012 AppsAttic Ltd - http://www.appsattic.com/ // Written by Andrew Chilton <chilts@appsattic.com> // // License: http://opensource.org/licenses/MIT // // -------------------------------------------------------------------------------------------------------------------- function path(options, args) { return '/' + args.Version + args.Category; } // -------------------------------------------------------------------------------------------------------------------- // From: http://docs.amazonwebservices.com/AWSEC2/latest/UserGuide/AESDG-chapter-instancedata.html module.exports = { 'ListApiVersions' : { // request 'path' : '/', // response 'extractBody' : 'blob', }, 'Get' : { // request 'path' : path, 'args' : { Category : { 'required' : true, 'type' : 'special', }, Version : { 'required' : true, 'type' : 'special', }, }, // response 'extractBody' : 'blob', }, }; // --------------------------------------------------------------------------------------------------------------------
Make sure the extractBody is set (not just body)
Make sure the extractBody is set (not just body)
JavaScript
mit
chilts/awssum
javascript
## Code Before: // -------------------------------------------------------------------------------------------------------------------- // // metadata-config.js - config for AWS Instance Metadata // // Copyright (c) 2011, 2012 AppsAttic Ltd - http://www.appsattic.com/ // Written by Andrew Chilton <chilts@appsattic.com> // // License: http://opensource.org/licenses/MIT // // -------------------------------------------------------------------------------------------------------------------- function pathCategory(options, args) { return '/' + args.Version + args.Category; } function pathLatest(options, args) { return '/latest/' + args.Category; } // -------------------------------------------------------------------------------------------------------------------- // From: http://docs.amazonwebservices.com/AWSEC2/latest/UserGuide/AESDG-chapter-instancedata.html module.exports = { 'ListApiVersions' : { // request 'path' : '/', // response 'body' : 'blob', }, 'Get' : { // request 'path' : pathCategory, 'args' : { Category : { 'required' : true, 'type' : 'special', }, Version : { 'required' : true, 'type' : 'special', }, }, // response 'body' : 'blob', }, }; // -------------------------------------------------------------------------------------------------------------------- ## Instruction: Make sure the extractBody is set (not just body) ## Code After: // -------------------------------------------------------------------------------------------------------------------- // // metadata-config.js - config for AWS Instance Metadata // // Copyright (c) 2011, 2012 AppsAttic Ltd - http://www.appsattic.com/ // Written by Andrew Chilton <chilts@appsattic.com> // // License: http://opensource.org/licenses/MIT // // -------------------------------------------------------------------------------------------------------------------- function path(options, args) { return '/' + args.Version + args.Category; } // -------------------------------------------------------------------------------------------------------------------- // From: http://docs.amazonwebservices.com/AWSEC2/latest/UserGuide/AESDG-chapter-instancedata.html module.exports = { 'ListApiVersions' : { // request 'path' : '/', // response 'extractBody' : 'blob', }, 'Get' : { // request 'path' : path, 'args' : { Category : { 'required' : true, 'type' : 'special', }, Version : { 'required' : true, 'type' : 'special', }, }, // response 'extractBody' : 'blob', }, }; // --------------------------------------------------------------------------------------------------------------------
abb7024f69410852fae10885434f068b89ce50d0
lib/crispy/crispy_internal/class_spy.rb
lib/crispy/crispy_internal/class_spy.rb
module Crispy module CrispyInternal class ClassSpy < ::Module include SpyMixin include WithStubber @registry = {} def initialize klass, stubs_map = {} super() @received_messages = [] initialize_stubber stubs_map prepend_stubber klass sneak_into Target.new(klass) end def define_wrapper method_name #return method_name if method_name == :initialize return method_name if method_name == :method_missing p method_name define_method method_name do|*arguments, &attached_block| #::Kernel.print "e" # <= with this statement, prepend-ing :method_missing doesn't cause the segfault. ::Crispy::CrispyInternal::ClassSpy.of_class(::Kernel.p self.class).received_messages << ::Crispy::CrispyReceivedMessageWithReceiver.new(self, method_name, *arguments, &attached_block) super(*arguments, &attached_block) end method_name end private :define_wrapper class Target def initialize klass @target_class = klass end def as_class @target_class end # define accessor after prepending to avoid to spy unexpectedly. def pass_spy_through spy ::Crispy::CrispyInternal::ClassSpy.register spy: spy, of_class: @target_class end end def self.register(spy: nil, of_class: nil) @registry[of_class] = spy end def self.of_class(klass) @registry[klass] end end end end
module Crispy module CrispyInternal class ClassSpy < ::Module include SpyMixin include WithStubber @registry = {} def initialize klass, stubs_map = {} super() @received_messages = [] initialize_stubber stubs_map prepend_stubber klass sneak_into Target.new(klass) end def define_wrapper method_name define_method method_name do|*arguments, &attached_block| ::Crispy::CrispyInternal::ClassSpy.of_class(self.class).received_messages << ::Crispy::CrispyReceivedMessageWithReceiver.new(self, method_name, *arguments, &attached_block) super(*arguments, &attached_block) end method_name end private :define_wrapper class Target def initialize klass @target_class = klass end def as_class @target_class end # define accessor after prepending to avoid to spy unexpectedly. def pass_spy_through spy ::Crispy::CrispyInternal::ClassSpy.register spy: spy, of_class: @target_class end end def self.register(spy: nil, of_class: nil) @registry[of_class] = spy end def self.of_class(klass) @registry[klass] end end end end
Revert "add more codes to reproduce segfault more."
Revert "add more codes to reproduce segfault more." This reverts commit a56586e48bf3a88dd9d19068d53fdb67f3e2faac.
Ruby
mit
igrep/crispy
ruby
## Code Before: module Crispy module CrispyInternal class ClassSpy < ::Module include SpyMixin include WithStubber @registry = {} def initialize klass, stubs_map = {} super() @received_messages = [] initialize_stubber stubs_map prepend_stubber klass sneak_into Target.new(klass) end def define_wrapper method_name #return method_name if method_name == :initialize return method_name if method_name == :method_missing p method_name define_method method_name do|*arguments, &attached_block| #::Kernel.print "e" # <= with this statement, prepend-ing :method_missing doesn't cause the segfault. ::Crispy::CrispyInternal::ClassSpy.of_class(::Kernel.p self.class).received_messages << ::Crispy::CrispyReceivedMessageWithReceiver.new(self, method_name, *arguments, &attached_block) super(*arguments, &attached_block) end method_name end private :define_wrapper class Target def initialize klass @target_class = klass end def as_class @target_class end # define accessor after prepending to avoid to spy unexpectedly. def pass_spy_through spy ::Crispy::CrispyInternal::ClassSpy.register spy: spy, of_class: @target_class end end def self.register(spy: nil, of_class: nil) @registry[of_class] = spy end def self.of_class(klass) @registry[klass] end end end end ## Instruction: Revert "add more codes to reproduce segfault more." This reverts commit a56586e48bf3a88dd9d19068d53fdb67f3e2faac. ## Code After: module Crispy module CrispyInternal class ClassSpy < ::Module include SpyMixin include WithStubber @registry = {} def initialize klass, stubs_map = {} super() @received_messages = [] initialize_stubber stubs_map prepend_stubber klass sneak_into Target.new(klass) end def define_wrapper method_name define_method method_name do|*arguments, &attached_block| ::Crispy::CrispyInternal::ClassSpy.of_class(self.class).received_messages << ::Crispy::CrispyReceivedMessageWithReceiver.new(self, method_name, *arguments, &attached_block) super(*arguments, &attached_block) end method_name end private :define_wrapper class Target def initialize klass @target_class = klass end def as_class @target_class end # define accessor after prepending to avoid to spy unexpectedly. def pass_spy_through spy ::Crispy::CrispyInternal::ClassSpy.register spy: spy, of_class: @target_class end end def self.register(spy: nil, of_class: nil) @registry[of_class] = spy end def self.of_class(klass) @registry[klass] end end end end
ba6d4125830adb7308588947a5e91cfbdb49c00a
DataCollector/MemcachedDataCollector.php
DataCollector/MemcachedDataCollector.php
<?php namespace Blablacar\MemcachedBundle\DataCollector; use Symfony\Component\HttpKernel\DataCollector\DataCollector; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Blablacar\MemcachedBundle\Memcached\ClientLogger; class MemcachedDataCollector extends DataCollector { protected $clients = array(); public function addClient($name, ClientLogger $client) { $this->clients[$name] = $client; } /** * {@inheritDoc} */ public function collect(Request $request, Response $response, \Exception $exception = null) { foreach ($this->clients as $name => $client) { foreach ($client->getCommands() as $command) { $this->data[] = array( 'command' => $command['name'], 'arguments' => implode(', ', $command['arguments']), 'duration' => $command['duration'], 'connection' => $name, 'return' => implode(', ', $command['return']) ); } $client->reset(); } } /** * {@inheritDoc} */ public function getName() { return 'memcached'; } /** * getCommands * * @return array */ public function getCommands() { return $this->data; } /** * getDuration * * @return int */ public function getDuration() { $time = 0; foreach ($this->data as $data) { $time += $data['duration']; } return $time; } }
<?php namespace Blablacar\MemcachedBundle\DataCollector; use Symfony\Component\HttpKernel\DataCollector\DataCollector; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Blablacar\MemcachedBundle\Memcached\ClientLogger; class MemcachedDataCollector extends DataCollector { protected $clients = array(); public function addClient($name, ClientLogger $client) { $this->clients[$name] = $client; } /** * {@inheritDoc} */ public function collect(Request $request, Response $response, \Exception $exception = null) { foreach ($this->clients as $name => $client) { foreach ($client->getCommands() as $command) { $this->data[] = array( 'command' => $command['name'], 'arguments' => implode(', ', $command['arguments']), 'duration' => $command['duration'], 'connection' => $name, 'return' => implode(', ', $command['return']) ); } $client->reset(); } } /** * {@inheritDoc} */ public function getName() { return 'memcached'; } /** * getCommands * * @return array */ public function getCommands() { return $this->data; } /** * getDuration * * @return int */ public function getDuration() { if (null === $this->data) { return 0; } $time = 0; foreach ($this->data as $data) { $time += $data['duration']; } return $time; } }
Correct duration when no commands is logged
Correct duration when no commands is logged
PHP
mit
odolbeau/BlablacarMemcachedBundle,odolbeau/BlablacarMemcachedBundle,blablacar/BlablacarMemcachedBundle,blablacar/BlablacarMemcachedBundle
php
## Code Before: <?php namespace Blablacar\MemcachedBundle\DataCollector; use Symfony\Component\HttpKernel\DataCollector\DataCollector; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Blablacar\MemcachedBundle\Memcached\ClientLogger; class MemcachedDataCollector extends DataCollector { protected $clients = array(); public function addClient($name, ClientLogger $client) { $this->clients[$name] = $client; } /** * {@inheritDoc} */ public function collect(Request $request, Response $response, \Exception $exception = null) { foreach ($this->clients as $name => $client) { foreach ($client->getCommands() as $command) { $this->data[] = array( 'command' => $command['name'], 'arguments' => implode(', ', $command['arguments']), 'duration' => $command['duration'], 'connection' => $name, 'return' => implode(', ', $command['return']) ); } $client->reset(); } } /** * {@inheritDoc} */ public function getName() { return 'memcached'; } /** * getCommands * * @return array */ public function getCommands() { return $this->data; } /** * getDuration * * @return int */ public function getDuration() { $time = 0; foreach ($this->data as $data) { $time += $data['duration']; } return $time; } } ## Instruction: Correct duration when no commands is logged ## Code After: <?php namespace Blablacar\MemcachedBundle\DataCollector; use Symfony\Component\HttpKernel\DataCollector\DataCollector; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Blablacar\MemcachedBundle\Memcached\ClientLogger; class MemcachedDataCollector extends DataCollector { protected $clients = array(); public function addClient($name, ClientLogger $client) { $this->clients[$name] = $client; } /** * {@inheritDoc} */ public function collect(Request $request, Response $response, \Exception $exception = null) { foreach ($this->clients as $name => $client) { foreach ($client->getCommands() as $command) { $this->data[] = array( 'command' => $command['name'], 'arguments' => implode(', ', $command['arguments']), 'duration' => $command['duration'], 'connection' => $name, 'return' => implode(', ', $command['return']) ); } $client->reset(); } } /** * {@inheritDoc} */ public function getName() { return 'memcached'; } /** * getCommands * * @return array */ public function getCommands() { return $this->data; } /** * getDuration * * @return int */ public function getDuration() { if (null === $this->data) { return 0; } $time = 0; foreach ($this->data as $data) { $time += $data['duration']; } return $time; } }
10d170fa4b12345c2450bb3d83f92c2abc0eab3c
app/src/main/java/org/zeropage/apps/zeropage/database/notification/NotificationHistory.java
app/src/main/java/org/zeropage/apps/zeropage/database/notification/NotificationHistory.java
package org.zeropage.apps.zeropage.database.notification; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import org.zeropage.apps.zeropage.notification.Notification; import java.util.ArrayList; import java.util.List; public class NotificationHistory { private static NotificationHistory sInstance; private SQLiteDatabase mDatabase; public NotificationHistory getInstance(Context context) { sInstance = new Notifi } private NotificationHistory(Context context) { mDatabase = new NotificationOpenHelper(context).getWritableDatabase(); } public void addToHistory(Notification newNotification) { ContentValues values = NotificationTable.getContentValues(newNotification); mDatabase.insert(NotificationTable.NAME, null, values); } public List<Notification> getAllHistory() { List<Notification> notifications = new ArrayList<>(); try (NotificationCursorWrapper wrapper = queryHistory(null, null)) { wrapper.moveToFirst(); while (!wrapper.isAfterLast()) { notifications.add(wrapper.getNotification()); wrapper.moveToNext(); } } return notifications; } private NotificationCursorWrapper queryHistory(String whereClause, String[] whereArgs) { Cursor cursor = mDatabase.query(NotificationTable.NAME, null, whereClause, whereArgs, null, null, null, null); return new NotificationCursorWrapper(cursor); } }
package org.zeropage.apps.zeropage.database.notification; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import org.zeropage.apps.zeropage.notification.Notification; import java.util.ArrayList; import java.util.List; public class NotificationHistory { private static NotificationHistory sInstance; private SQLiteDatabase mDatabase; public synchronized static NotificationHistory getInstance(Context context) { if (sInstance == null) { sInstance = new NotificationHistory(context.getApplicationContext()); } return sInstance; } private NotificationHistory(Context context) { mDatabase = new NotificationOpenHelper(context).getWritableDatabase(); } public void addToHistory(Notification newNotification) { ContentValues values = NotificationTable.getContentValues(newNotification); mDatabase.insert(NotificationTable.NAME, null, values); } public List<Notification> getAllHistory() { List<Notification> notifications = new ArrayList<>(); try (NotificationCursorWrapper wrapper = queryHistory(null, null)) { wrapper.moveToFirst(); while (!wrapper.isAfterLast()) { notifications.add(wrapper.getNotification()); wrapper.moveToNext(); } } return notifications; } private NotificationCursorWrapper queryHistory(String whereClause, String[] whereArgs) { Cursor cursor = mDatabase.query(NotificationTable.NAME, null, whereClause, whereArgs, null, null, null, null); return new NotificationCursorWrapper(cursor); } }
Add Helper singleton class for querying/adding notification to db.
Add Helper singleton class for querying/adding notification to db.
Java
mit
ZeroPage/i_have_no_apps
java
## Code Before: package org.zeropage.apps.zeropage.database.notification; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import org.zeropage.apps.zeropage.notification.Notification; import java.util.ArrayList; import java.util.List; public class NotificationHistory { private static NotificationHistory sInstance; private SQLiteDatabase mDatabase; public NotificationHistory getInstance(Context context) { sInstance = new Notifi } private NotificationHistory(Context context) { mDatabase = new NotificationOpenHelper(context).getWritableDatabase(); } public void addToHistory(Notification newNotification) { ContentValues values = NotificationTable.getContentValues(newNotification); mDatabase.insert(NotificationTable.NAME, null, values); } public List<Notification> getAllHistory() { List<Notification> notifications = new ArrayList<>(); try (NotificationCursorWrapper wrapper = queryHistory(null, null)) { wrapper.moveToFirst(); while (!wrapper.isAfterLast()) { notifications.add(wrapper.getNotification()); wrapper.moveToNext(); } } return notifications; } private NotificationCursorWrapper queryHistory(String whereClause, String[] whereArgs) { Cursor cursor = mDatabase.query(NotificationTable.NAME, null, whereClause, whereArgs, null, null, null, null); return new NotificationCursorWrapper(cursor); } } ## Instruction: Add Helper singleton class for querying/adding notification to db. ## Code After: package org.zeropage.apps.zeropage.database.notification; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import org.zeropage.apps.zeropage.notification.Notification; import java.util.ArrayList; import java.util.List; public class NotificationHistory { private static NotificationHistory sInstance; private SQLiteDatabase mDatabase; public synchronized static NotificationHistory getInstance(Context context) { if (sInstance == null) { sInstance = new NotificationHistory(context.getApplicationContext()); } return sInstance; } private NotificationHistory(Context context) { mDatabase = new NotificationOpenHelper(context).getWritableDatabase(); } public void addToHistory(Notification newNotification) { ContentValues values = NotificationTable.getContentValues(newNotification); mDatabase.insert(NotificationTable.NAME, null, values); } public List<Notification> getAllHistory() { List<Notification> notifications = new ArrayList<>(); try (NotificationCursorWrapper wrapper = queryHistory(null, null)) { wrapper.moveToFirst(); while (!wrapper.isAfterLast()) { notifications.add(wrapper.getNotification()); wrapper.moveToNext(); } } return notifications; } private NotificationCursorWrapper queryHistory(String whereClause, String[] whereArgs) { Cursor cursor = mDatabase.query(NotificationTable.NAME, null, whereClause, whereArgs, null, null, null, null); return new NotificationCursorWrapper(cursor); } }
f8561caa2c981a6f09b02bad89e931cb0419de0c
src/cpp/desktop/DesktopNetworkAccessManager.cpp
src/cpp/desktop/DesktopNetworkAccessManager.cpp
/* * DesktopNetworkAccessManager.cpp * * Copyright (C) 2009-11 by RStudio, Inc. * * This program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ #include "DesktopNetworkAccessManager.hpp" #include <QNetworkDiskCache> #include <QDesktopServices> #include <core/FilePath.hpp> using namespace core; NetworkAccessManager::NetworkAccessManager(QString secret, QObject *parent) : QNetworkAccessManager(parent), secret_(secret) { setProxy(QNetworkProxy::NoProxy); // initialize cache QString cacheDir = QDesktopServices::storageLocation(QDesktopServices::CacheLocation); FilePath cachePath(cacheDir.toUtf8().constData()); FilePath browserCachePath = cachePath.complete("RStudioWebkit"); Error error = browserCachePath.ensureDirectory(); if (!error) { QNetworkDiskCache* pCache = new QNetworkDiskCache(parent); QString browserCacheDir = QString::fromUtf8( browserCachePath.absolutePath().c_str()); pCache->setCacheDirectory(browserCacheDir); setCache(pCache); } else { LOG_ERROR(error); } } QNetworkReply* NetworkAccessManager::createRequest( Operation op, const QNetworkRequest& req, QIODevice* outgoingData) { QNetworkRequest req2 = req; req2.setRawHeader("X-Shared-Secret", secret_.toAscii()); return this->QNetworkAccessManager::createRequest(op, req2, outgoingData); }
/* * DesktopNetworkAccessManager.cpp * * Copyright (C) 2009-11 by RStudio, Inc. * * This program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ #include "DesktopNetworkAccessManager.hpp" NetworkAccessManager::NetworkAccessManager(QString secret, QObject *parent) : QNetworkAccessManager(parent), secret_(secret) { setProxy(QNetworkProxy::NoProxy); } QNetworkReply* NetworkAccessManager::createRequest( Operation op, const QNetworkRequest& req, QIODevice* outgoingData) { QNetworkRequest req2 = req; req2.setRawHeader("X-Shared-Secret", secret_.toAscii()); return this->QNetworkAccessManager::createRequest(op, req2, outgoingData); }
Revert "use file based webkit cache in desktop mode" (was crashing when opening the history pane on linux)
Revert "use file based webkit cache in desktop mode" (was crashing when opening the history pane on linux)
C++
agpl-3.0
JanMarvin/rstudio,sfloresm/rstudio,maligulzar/Rstudio-instrumented,jar1karp/rstudio,githubfun/rstudio,pssguy/rstudio,brsimioni/rstudio,suribes/rstudio,jzhu8803/rstudio,pssguy/rstudio,vbelakov/rstudio,githubfun/rstudio,edrogers/rstudio,nvoron23/rstudio,maligulzar/Rstudio-instrumented,jar1karp/rstudio,piersharding/rstudio,john-r-mcpherson/rstudio,john-r-mcpherson/rstudio,vbelakov/rstudio,JanMarvin/rstudio,jar1karp/rstudio,jar1karp/rstudio,more1/rstudio,edrogers/rstudio,jar1karp/rstudio,thklaus/rstudio,thklaus/rstudio,vbelakov/rstudio,githubfun/rstudio,vbelakov/rstudio,sfloresm/rstudio,vbelakov/rstudio,jar1karp/rstudio,tbarrongh/rstudio,nvoron23/rstudio,piersharding/rstudio,suribes/rstudio,jzhu8803/rstudio,Sage-Bionetworks/rstudio,pssguy/rstudio,piersharding/rstudio,maligulzar/Rstudio-instrumented,john-r-mcpherson/rstudio,Sage-Bionetworks/rstudio,jrnold/rstudio,JanMarvin/rstudio,JanMarvin/rstudio,Sage-Bionetworks/rstudio,pssguy/rstudio,more1/rstudio,john-r-mcpherson/rstudio,jrnold/rstudio,jar1karp/rstudio,JanMarvin/rstudio,jzhu8803/rstudio,brsimioni/rstudio,suribes/rstudio,tbarrongh/rstudio,sfloresm/rstudio,piersharding/rstudio,maligulzar/Rstudio-instrumented,piersharding/rstudio,nvoron23/rstudio,john-r-mcpherson/rstudio,more1/rstudio,jzhu8803/rstudio,piersharding/rstudio,sfloresm/rstudio,suribes/rstudio,thklaus/rstudio,jzhu8803/rstudio,more1/rstudio,thklaus/rstudio,more1/rstudio,nvoron23/rstudio,jzhu8803/rstudio,nvoron23/rstudio,jrnold/rstudio,vbelakov/rstudio,piersharding/rstudio,brsimioni/rstudio,john-r-mcpherson/rstudio,edrogers/rstudio,githubfun/rstudio,pssguy/rstudio,maligulzar/Rstudio-instrumented,john-r-mcpherson/rstudio,vbelakov/rstudio,githubfun/rstudio,brsimioni/rstudio,more1/rstudio,edrogers/rstudio,jrnold/rstudio,jrnold/rstudio,brsimioni/rstudio,maligulzar/Rstudio-instrumented,edrogers/rstudio,maligulzar/Rstudio-instrumented,edrogers/rstudio,JanMarvin/rstudio,tbarrongh/rstudio,brsimioni/rstudio,pssguy/rstudio,piersharding/rstudio,jrnold/rstudio,maligulzar/Rstudio-instrumented,suribes/rstudio,more1/rstudio,jrnold/rstudio,githubfun/rstudio,edrogers/rstudio,thklaus/rstudio,edrogers/rstudio,jzhu8803/rstudio,jar1karp/rstudio,sfloresm/rstudio,tbarrongh/rstudio,Sage-Bionetworks/rstudio,jrnold/rstudio,sfloresm/rstudio,john-r-mcpherson/rstudio,Sage-Bionetworks/rstudio,githubfun/rstudio,brsimioni/rstudio,tbarrongh/rstudio,JanMarvin/rstudio,thklaus/rstudio,jar1karp/rstudio,jzhu8803/rstudio,JanMarvin/rstudio,suribes/rstudio,more1/rstudio,jrnold/rstudio,sfloresm/rstudio,sfloresm/rstudio,tbarrongh/rstudio,Sage-Bionetworks/rstudio,suribes/rstudio,maligulzar/Rstudio-instrumented,githubfun/rstudio,nvoron23/rstudio,brsimioni/rstudio,thklaus/rstudio,tbarrongh/rstudio,tbarrongh/rstudio,pssguy/rstudio,vbelakov/rstudio,pssguy/rstudio,nvoron23/rstudio,suribes/rstudio,JanMarvin/rstudio,piersharding/rstudio,Sage-Bionetworks/rstudio,thklaus/rstudio
c++
## Code Before: /* * DesktopNetworkAccessManager.cpp * * Copyright (C) 2009-11 by RStudio, Inc. * * This program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ #include "DesktopNetworkAccessManager.hpp" #include <QNetworkDiskCache> #include <QDesktopServices> #include <core/FilePath.hpp> using namespace core; NetworkAccessManager::NetworkAccessManager(QString secret, QObject *parent) : QNetworkAccessManager(parent), secret_(secret) { setProxy(QNetworkProxy::NoProxy); // initialize cache QString cacheDir = QDesktopServices::storageLocation(QDesktopServices::CacheLocation); FilePath cachePath(cacheDir.toUtf8().constData()); FilePath browserCachePath = cachePath.complete("RStudioWebkit"); Error error = browserCachePath.ensureDirectory(); if (!error) { QNetworkDiskCache* pCache = new QNetworkDiskCache(parent); QString browserCacheDir = QString::fromUtf8( browserCachePath.absolutePath().c_str()); pCache->setCacheDirectory(browserCacheDir); setCache(pCache); } else { LOG_ERROR(error); } } QNetworkReply* NetworkAccessManager::createRequest( Operation op, const QNetworkRequest& req, QIODevice* outgoingData) { QNetworkRequest req2 = req; req2.setRawHeader("X-Shared-Secret", secret_.toAscii()); return this->QNetworkAccessManager::createRequest(op, req2, outgoingData); } ## Instruction: Revert "use file based webkit cache in desktop mode" (was crashing when opening the history pane on linux) ## Code After: /* * DesktopNetworkAccessManager.cpp * * Copyright (C) 2009-11 by RStudio, Inc. * * This program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ #include "DesktopNetworkAccessManager.hpp" NetworkAccessManager::NetworkAccessManager(QString secret, QObject *parent) : QNetworkAccessManager(parent), secret_(secret) { setProxy(QNetworkProxy::NoProxy); } QNetworkReply* NetworkAccessManager::createRequest( Operation op, const QNetworkRequest& req, QIODevice* outgoingData) { QNetworkRequest req2 = req; req2.setRawHeader("X-Shared-Secret", secret_.toAscii()); return this->QNetworkAccessManager::createRequest(op, req2, outgoingData); }
2c833f57eb12a31cd4eeba9e5e515bba8508fe8b
src/Elements/HttpResponseElement.php
src/Elements/HttpResponseElement.php
<?php namespace Hmaus\Reynaldo\Elements; class HttpResponseElement extends BaseElement implements ApiElement, ApiHttpResponse { public function getStatusCode() { return (int)$this->attributes['statusCode']; } public function getHeaders() { $headersFromAttributes = $this->getAttribute('headers'); if (!$headersFromAttributes) { return []; } $headers = []; foreach ($headersFromAttributes['content'] as $header) { $headers[$header['content']['key']['content']] = $header['content']['value']['content']; } return $headers; } public function hasMessageBody() { return $this->getMessageBodyAsset() !== null; } public function getMessageBodyAsset() { return $this->getFirstAssetByClass('messageBody'); } /** * @param $className * @return AssetElement|null */ private function getFirstAssetByClass($className) { $assets = $this->getElementsByType(AssetElement::class); /** @var AssetElement $asset */ foreach ($assets as $asset) { if ($asset->hasClass($className)) { return $asset; } } return null; } public function hasMessageBodySchema() { return $this->getMessageBodySchemaAsset() !== null; } public function getMessageBodySchemaAsset() { return $this->getFirstAssetByClass('messageBodySchema'); } public function getDataStructure() { return $this->getFirstElementByType(DataStructureElement::class); } }
<?php namespace Hmaus\Reynaldo\Elements; class HttpResponseElement extends BaseElement implements ApiElement, ApiHttpResponse { public function getStatusCode() { return isset($this->attributes['statusCode']) ? (int)$this->attributes['statusCode'] : 0; } public function getHeaders() { $headersFromAttributes = $this->getAttribute('headers'); if (!$headersFromAttributes) { return []; } $headers = []; foreach ($headersFromAttributes['content'] as $header) { $headers[$header['content']['key']['content']] = $header['content']['value']['content']; } return $headers; } public function hasMessageBody() { return $this->getMessageBodyAsset() !== null; } public function getMessageBodyAsset() { return $this->getFirstAssetByClass('messageBody'); } /** * @param $className * @return AssetElement|null */ private function getFirstAssetByClass($className) { $assets = $this->getElementsByType(AssetElement::class); /** @var AssetElement $asset */ foreach ($assets as $asset) { if ($asset->hasClass($className)) { return $asset; } } return null; } public function hasMessageBodySchema() { return $this->getMessageBodySchemaAsset() !== null; } public function getMessageBodySchemaAsset() { return $this->getFirstAssetByClass('messageBodySchema'); } public function getDataStructure() { return $this->getFirstElementByType(DataStructureElement::class); } }
Fix NOTICE error on PHP 7.4: Trying to access array offset on value of type null
Fix NOTICE error on PHP 7.4: Trying to access array offset on value of type null
PHP
mit
hendrikmaus/reynaldo
php
## Code Before: <?php namespace Hmaus\Reynaldo\Elements; class HttpResponseElement extends BaseElement implements ApiElement, ApiHttpResponse { public function getStatusCode() { return (int)$this->attributes['statusCode']; } public function getHeaders() { $headersFromAttributes = $this->getAttribute('headers'); if (!$headersFromAttributes) { return []; } $headers = []; foreach ($headersFromAttributes['content'] as $header) { $headers[$header['content']['key']['content']] = $header['content']['value']['content']; } return $headers; } public function hasMessageBody() { return $this->getMessageBodyAsset() !== null; } public function getMessageBodyAsset() { return $this->getFirstAssetByClass('messageBody'); } /** * @param $className * @return AssetElement|null */ private function getFirstAssetByClass($className) { $assets = $this->getElementsByType(AssetElement::class); /** @var AssetElement $asset */ foreach ($assets as $asset) { if ($asset->hasClass($className)) { return $asset; } } return null; } public function hasMessageBodySchema() { return $this->getMessageBodySchemaAsset() !== null; } public function getMessageBodySchemaAsset() { return $this->getFirstAssetByClass('messageBodySchema'); } public function getDataStructure() { return $this->getFirstElementByType(DataStructureElement::class); } } ## Instruction: Fix NOTICE error on PHP 7.4: Trying to access array offset on value of type null ## Code After: <?php namespace Hmaus\Reynaldo\Elements; class HttpResponseElement extends BaseElement implements ApiElement, ApiHttpResponse { public function getStatusCode() { return isset($this->attributes['statusCode']) ? (int)$this->attributes['statusCode'] : 0; } public function getHeaders() { $headersFromAttributes = $this->getAttribute('headers'); if (!$headersFromAttributes) { return []; } $headers = []; foreach ($headersFromAttributes['content'] as $header) { $headers[$header['content']['key']['content']] = $header['content']['value']['content']; } return $headers; } public function hasMessageBody() { return $this->getMessageBodyAsset() !== null; } public function getMessageBodyAsset() { return $this->getFirstAssetByClass('messageBody'); } /** * @param $className * @return AssetElement|null */ private function getFirstAssetByClass($className) { $assets = $this->getElementsByType(AssetElement::class); /** @var AssetElement $asset */ foreach ($assets as $asset) { if ($asset->hasClass($className)) { return $asset; } } return null; } public function hasMessageBodySchema() { return $this->getMessageBodySchemaAsset() !== null; } public function getMessageBodySchemaAsset() { return $this->getFirstAssetByClass('messageBodySchema'); } public function getDataStructure() { return $this->getFirstElementByType(DataStructureElement::class); } }
c03a3d0ad3e073f0df66c029394b6e9d304fa24a
lib/undo/serializer/active_model.rb
lib/undo/serializer/active_model.rb
require "active_support/core_ext/hash" require "active_support/core_ext/string" module Undo module Serializer class ActiveModel VERSION = "0.0.2" def initialize(*args) options = args.extract_options! @serializer = args.first @serializer_source = options.fetch :serializer, ->(object) { object.active_model_serializer.new object } end def serialize(object) serializer(object).as_json end def deserialize(hash) hash.each do |object_class, data| next unless data.is_a? Hash data.stringify_keys! object_class = object_class.to_s.camelize.constantize object = object_class.where(id: data.fetch("id")).first_or_initialize data.each do |field, value| next if "id" == field && object.persisted? _, association = field.to_s.split("___") if association deserialize_association(association, value) else object.send "#{field}=", value # not public_send! end end object.save! return object end end private attr_reader :serializer_source def serializer(object) @serializer ||= serializer_source.call object end def deserialize_association(association, values) Array.wrap(values).each do |value| deserialize(association.singularize => value) end end end end end
module Undo module Serializer class ActiveModel VERSION = "0.0.2" def initialize(*args) options = args.extract_options! @serializer = args.first @serializer_source = options.fetch :serializer, ->(object) { object.active_model_serializer.new object } end def serialize(object) serializer(object).as_json end def deserialize(hash) hash.each do |object_class, data| next unless data.is_a? Hash data.stringify_keys! object_class = object_class.to_s.camelize.constantize object = object_class.where(id: data.fetch("id")).first_or_initialize data.each do |field, value| next if "id" == field && object.persisted? _, association = field.to_s.split("___") if association deserialize_association(association, value) else object.send "#{field}=", value # not public_send! end end object.save! return object end end private attr_reader :serializer_source def serializer(object) @serializer ||= serializer_source.call object end def deserialize_association(association, values) Array.wrap(values).each do |value| deserialize(association.singularize => value) end end end end end
Revert "load hash and object core_ext"
Revert "load hash and object core_ext" This reverts commit 9ded0797e3e6eebef5adab1f4d02bf991780aa63.
Ruby
mit
AlexParamonov/undo-serializer-active_model
ruby
## Code Before: require "active_support/core_ext/hash" require "active_support/core_ext/string" module Undo module Serializer class ActiveModel VERSION = "0.0.2" def initialize(*args) options = args.extract_options! @serializer = args.first @serializer_source = options.fetch :serializer, ->(object) { object.active_model_serializer.new object } end def serialize(object) serializer(object).as_json end def deserialize(hash) hash.each do |object_class, data| next unless data.is_a? Hash data.stringify_keys! object_class = object_class.to_s.camelize.constantize object = object_class.where(id: data.fetch("id")).first_or_initialize data.each do |field, value| next if "id" == field && object.persisted? _, association = field.to_s.split("___") if association deserialize_association(association, value) else object.send "#{field}=", value # not public_send! end end object.save! return object end end private attr_reader :serializer_source def serializer(object) @serializer ||= serializer_source.call object end def deserialize_association(association, values) Array.wrap(values).each do |value| deserialize(association.singularize => value) end end end end end ## Instruction: Revert "load hash and object core_ext" This reverts commit 9ded0797e3e6eebef5adab1f4d02bf991780aa63. ## Code After: module Undo module Serializer class ActiveModel VERSION = "0.0.2" def initialize(*args) options = args.extract_options! @serializer = args.first @serializer_source = options.fetch :serializer, ->(object) { object.active_model_serializer.new object } end def serialize(object) serializer(object).as_json end def deserialize(hash) hash.each do |object_class, data| next unless data.is_a? Hash data.stringify_keys! object_class = object_class.to_s.camelize.constantize object = object_class.where(id: data.fetch("id")).first_or_initialize data.each do |field, value| next if "id" == field && object.persisted? _, association = field.to_s.split("___") if association deserialize_association(association, value) else object.send "#{field}=", value # not public_send! end end object.save! return object end end private attr_reader :serializer_source def serializer(object) @serializer ||= serializer_source.call object end def deserialize_association(association, values) Array.wrap(values).each do |value| deserialize(association.singularize => value) end end end end end
3af0ea079e7710f16599de9565c9c9f07f666d4c
lib/ui/views/targetSelector.js
lib/ui/views/targetSelector.js
/* * Copyright 2014 BlackBerry Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ var TargetSelectorView, targetSelectorTemplate; TargetSelectorView = Backbone.View.extend({ initialize: function () { // Find the template and save it $.get("pages/targetSelector.html", function (data) { targetSelectorTemplate = data; }); }, render: function () { // Use the template to create the html to display var view = this, showDevices = view.model.get("buildSettings").device, template; if (typeof showDevices === "undefined") { showDevices = true; } this.model.targetFilter(showDevices, function (filteredTargets) { template = _.template(targetSelectorTemplate, { targetNameList: Object.keys(filteredTargets) }); // Put the new html inside of the assigned element view.$el.html(template); }); }, events: { }, display: function (model) { this.model = model; this.render(); } }); module.exports = TargetSelectorView;
/* * Copyright 2014 BlackBerry Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ var TargetSelectorView, targetSelectorTemplate; TargetSelectorView = Backbone.View.extend({ initialize: function () { // Find the template and save it $.get("pages/targetSelector.html", function (data) { targetSelectorTemplate = data; }); }, render: function () { // Use the template to create the html to display var view = this, buildSettings = view.model.get("buildSettings"), showDevices = !buildSettings || typeof buildSettings.device === "undefined" || buildSettings.device, template; this.model.targetFilter(showDevices, function (filteredTargets) { template = _.template(targetSelectorTemplate, { targetNameList: Object.keys(filteredTargets) }); // Put the new html inside of the assigned element view.$el.html(template); }); }, events: { }, display: function (model) { this.model = model; this.render(); } }); module.exports = TargetSelectorView;
Fix target selector for imported projects
Fix target selector for imported projects
JavaScript
apache-2.0
blackberry/webworks-gui,blackberry-webworks/webworks-gui,blackberry/webworks-gui,blackberry-webworks/webworks-gui
javascript
## Code Before: /* * Copyright 2014 BlackBerry Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ var TargetSelectorView, targetSelectorTemplate; TargetSelectorView = Backbone.View.extend({ initialize: function () { // Find the template and save it $.get("pages/targetSelector.html", function (data) { targetSelectorTemplate = data; }); }, render: function () { // Use the template to create the html to display var view = this, showDevices = view.model.get("buildSettings").device, template; if (typeof showDevices === "undefined") { showDevices = true; } this.model.targetFilter(showDevices, function (filteredTargets) { template = _.template(targetSelectorTemplate, { targetNameList: Object.keys(filteredTargets) }); // Put the new html inside of the assigned element view.$el.html(template); }); }, events: { }, display: function (model) { this.model = model; this.render(); } }); module.exports = TargetSelectorView; ## Instruction: Fix target selector for imported projects ## Code After: /* * Copyright 2014 BlackBerry Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ var TargetSelectorView, targetSelectorTemplate; TargetSelectorView = Backbone.View.extend({ initialize: function () { // Find the template and save it $.get("pages/targetSelector.html", function (data) { targetSelectorTemplate = data; }); }, render: function () { // Use the template to create the html to display var view = this, buildSettings = view.model.get("buildSettings"), showDevices = !buildSettings || typeof buildSettings.device === "undefined" || buildSettings.device, template; this.model.targetFilter(showDevices, function (filteredTargets) { template = _.template(targetSelectorTemplate, { targetNameList: Object.keys(filteredTargets) }); // Put the new html inside of the assigned element view.$el.html(template); }); }, events: { }, display: function (model) { this.model = model; this.render(); } }); module.exports = TargetSelectorView;
8d7ae6963b99fa5a4909470fa0058a3ec5f99e86
src/Ajax/Controller.php
src/Ajax/Controller.php
<?php namespace Solid\Ajax\Controllers; use Illuminate\Routing\Controller as BaseController; class Controller extends BaseController { /** * Execute an action on the controller. * * @param string $method * @param array $parameters * @return \Symfony\Component\HttpFoundation\Response */ public function callAction($method, $parameters) { $result = parent::callAction($method, $parameters); if (app('ajax.helper')->isFrameworkAjax()) { $result = $this->prepareAjaxActionResponse($result); } return $result; } /** * Prepare response to make it compatible with * front end Ajax Framework * * @param mixed $result * * @return JsonResponse */ protected function prepareAjaxActionResponse($result) { if ($result instanceof \Illuminate\View\View) { return $this->ajaxResponse(['result' => $result->render()]); } if (is_array($result)) { foreach ($result as $key => $value) { if ($value instanceof \Illuminate\View\View) { $result[$key] = $value->render(); } } } return $this->ajaxResponse($result); } /** * Convert given result to format expected by front end framework * * @param mixed $result * * @return JsonResponse */ protected function ajaxResponse($result) { return response()->json($result); } }
<?php namespace Solid\Ajax; use Illuminate\Routing\Controller as BaseController; class Controller extends BaseController { /** * Execute an action on the controller. * * @param string $method * @param array $parameters * @return \Symfony\Component\HttpFoundation\Response */ public function callAction($method, $parameters) { $result = parent::callAction($method, $parameters); if (app('ajax.helper')->isFrameworkAjax()) { $result = $this->prepareAjaxActionResponse($result); } return $result; } /** * Prepare response to make it compatible with * front end Ajax Framework * * @param mixed $result * * @return JsonResponse */ protected function prepareAjaxActionResponse($result) { if ($result instanceof \Illuminate\View\View) { return $this->ajaxResponse(['result' => $result->render()]); } if (is_array($result)) { foreach ($result as $key => $value) { if ($value instanceof \Illuminate\View\View) { $result[$key] = $value->render(); } } } return $this->ajaxResponse($result); } /** * Convert given result to format expected by front end framework * * @param mixed $result * * @return JsonResponse */ protected function ajaxResponse($result) { return response()->json($result); } }
Fix namespace on solid ajax.
Fix namespace on solid ajax.
PHP
apache-2.0
true-agency/solid,true-agency/solid,true-agency/solid
php
## Code Before: <?php namespace Solid\Ajax\Controllers; use Illuminate\Routing\Controller as BaseController; class Controller extends BaseController { /** * Execute an action on the controller. * * @param string $method * @param array $parameters * @return \Symfony\Component\HttpFoundation\Response */ public function callAction($method, $parameters) { $result = parent::callAction($method, $parameters); if (app('ajax.helper')->isFrameworkAjax()) { $result = $this->prepareAjaxActionResponse($result); } return $result; } /** * Prepare response to make it compatible with * front end Ajax Framework * * @param mixed $result * * @return JsonResponse */ protected function prepareAjaxActionResponse($result) { if ($result instanceof \Illuminate\View\View) { return $this->ajaxResponse(['result' => $result->render()]); } if (is_array($result)) { foreach ($result as $key => $value) { if ($value instanceof \Illuminate\View\View) { $result[$key] = $value->render(); } } } return $this->ajaxResponse($result); } /** * Convert given result to format expected by front end framework * * @param mixed $result * * @return JsonResponse */ protected function ajaxResponse($result) { return response()->json($result); } } ## Instruction: Fix namespace on solid ajax. ## Code After: <?php namespace Solid\Ajax; use Illuminate\Routing\Controller as BaseController; class Controller extends BaseController { /** * Execute an action on the controller. * * @param string $method * @param array $parameters * @return \Symfony\Component\HttpFoundation\Response */ public function callAction($method, $parameters) { $result = parent::callAction($method, $parameters); if (app('ajax.helper')->isFrameworkAjax()) { $result = $this->prepareAjaxActionResponse($result); } return $result; } /** * Prepare response to make it compatible with * front end Ajax Framework * * @param mixed $result * * @return JsonResponse */ protected function prepareAjaxActionResponse($result) { if ($result instanceof \Illuminate\View\View) { return $this->ajaxResponse(['result' => $result->render()]); } if (is_array($result)) { foreach ($result as $key => $value) { if ($value instanceof \Illuminate\View\View) { $result[$key] = $value->render(); } } } return $this->ajaxResponse($result); } /** * Convert given result to format expected by front end framework * * @param mixed $result * * @return JsonResponse */ protected function ajaxResponse($result) { return response()->json($result); } }
a3f650473ee323fece222576e4bd8f6d4bdefc55
src/main/java/co/phoenixlab/discord/api/entities/ReadyMessage.java
src/main/java/co/phoenixlab/discord/api/entities/ReadyMessage.java
package co.phoenixlab.discord.api.entities; import com.google.gson.annotations.SerializedName; public class ReadyMessage { @SerializedName("v") private int version; private User user; private String sessionId; @SerializedName("read_state") private ReadState[] readState; @SerializedName("private_channels") private PrivateChannel[] privateChannels; @SerializedName("heartbeat_interval") private long heartbeatInterval; @SerializedName("guilds") private Server[] servers; public ReadyMessage() { } public int getVersion() { return version; } public User getUser() { return user; } public String getSessionId() { return sessionId; } public ReadState[] getReadState() { return readState; } public PrivateChannel[] getPrivateChannels() { return privateChannels; } public long getHeartbeatInterval() { return heartbeatInterval; } public Server[] getServers() { return servers; } class ReadState { @SerializedName("mention_count") private int mentionCount; @SerializedName("last_message_id") private String lastMessageId; private String id; public int getMentionCount() { return mentionCount; } public String getLastMessageId() { return lastMessageId; } public String getId() { return id; } } }
package co.phoenixlab.discord.api.entities; import com.google.gson.annotations.SerializedName; public class ReadyMessage { @SerializedName("v") private int version; private User user; @SerializedName("session_id") private String sessionId; @SerializedName("read_state") private ReadState[] readState; @SerializedName("private_channels") private PrivateChannel[] privateChannels; @SerializedName("heartbeat_interval") private long heartbeatInterval; @SerializedName("guilds") private Server[] servers; public ReadyMessage() { } public int getVersion() { return version; } public User getUser() { return user; } public String getSessionId() { return sessionId; } public ReadState[] getReadState() { return readState; } public PrivateChannel[] getPrivateChannels() { return privateChannels; } public long getHeartbeatInterval() { return heartbeatInterval; } public Server[] getServers() { return servers; } class ReadState { @SerializedName("mention_count") private int mentionCount; @SerializedName("last_message_id") private String lastMessageId; private String id; public int getMentionCount() { return mentionCount; } public String getLastMessageId() { return lastMessageId; } public String getId() { return id; } } }
Fix missing serialized name annotation
Fix missing serialized name annotation
Java
mit
vincentzhang96/VahrhedralBot
java
## Code Before: package co.phoenixlab.discord.api.entities; import com.google.gson.annotations.SerializedName; public class ReadyMessage { @SerializedName("v") private int version; private User user; private String sessionId; @SerializedName("read_state") private ReadState[] readState; @SerializedName("private_channels") private PrivateChannel[] privateChannels; @SerializedName("heartbeat_interval") private long heartbeatInterval; @SerializedName("guilds") private Server[] servers; public ReadyMessage() { } public int getVersion() { return version; } public User getUser() { return user; } public String getSessionId() { return sessionId; } public ReadState[] getReadState() { return readState; } public PrivateChannel[] getPrivateChannels() { return privateChannels; } public long getHeartbeatInterval() { return heartbeatInterval; } public Server[] getServers() { return servers; } class ReadState { @SerializedName("mention_count") private int mentionCount; @SerializedName("last_message_id") private String lastMessageId; private String id; public int getMentionCount() { return mentionCount; } public String getLastMessageId() { return lastMessageId; } public String getId() { return id; } } } ## Instruction: Fix missing serialized name annotation ## Code After: package co.phoenixlab.discord.api.entities; import com.google.gson.annotations.SerializedName; public class ReadyMessage { @SerializedName("v") private int version; private User user; @SerializedName("session_id") private String sessionId; @SerializedName("read_state") private ReadState[] readState; @SerializedName("private_channels") private PrivateChannel[] privateChannels; @SerializedName("heartbeat_interval") private long heartbeatInterval; @SerializedName("guilds") private Server[] servers; public ReadyMessage() { } public int getVersion() { return version; } public User getUser() { return user; } public String getSessionId() { return sessionId; } public ReadState[] getReadState() { return readState; } public PrivateChannel[] getPrivateChannels() { return privateChannels; } public long getHeartbeatInterval() { return heartbeatInterval; } public Server[] getServers() { return servers; } class ReadState { @SerializedName("mention_count") private int mentionCount; @SerializedName("last_message_id") private String lastMessageId; private String id; public int getMentionCount() { return mentionCount; } public String getLastMessageId() { return lastMessageId; } public String getId() { return id; } } }
3eac6ac01a9fa22c058926ab623d1aadfcee9ed1
lib/shapes/builder/struct.rb
lib/shapes/builder/struct.rb
module Shapes module Builder class Struct attr_reader :data attr_accessor :builder_strategy, :resource def initialize(data) @data = data @builder_strategy = if(data.is_a?(XML::Node)) StructFromXml.new else StructFromHash.new end end def build_resource @resource = @builder_strategy.build_object @data end class StructFromXml def build_object(node) struct = Shapes::Struct.new struct.xml_node = node struct.read_from_node struct.ident = node['ident'].to_s struct.description = node['description'].to_s struct.resource_type = 'Struct' struct end end class StructFromHash def build_object(hash) struct = Shapes::Struct.new hash struct.ident = hash[:ident] struct.description = hash[:description] struct.struct_name = hash[:type] build_children(hash).each do |child| struct << child end struct end private def build_children(hash) shape_struct = ShapeStruct.find_by_name hash[:type] shape_struct.primitives.collect do |primitive| # hash[:struct][primitive.ident.to_sym] for empty checkboxes primitive_hash = hash[:struct] && hash[:struct][primitive.ident.to_sym] ? hash[:struct][primitive.ident.to_sym] : {} primitive.build_primitive primitive_hash end end end end end end
module Shapes module Builder class Struct attr_reader :data attr_accessor :builder_strategy, :resource def initialize(data) @data = data @builder_strategy = if(data.is_a?(XML::Node)) StructFromXml.new else StructFromHash.new end end def build_resource @resource = @builder_strategy.build_object @data end class StructFromXml def build_object(node) struct = Shapes::Struct.new struct.xml_node = node struct.read_from_node struct.ident = node['ident'].to_s struct.description = node['description'].to_s struct end end class StructFromHash def build_object(hash) struct = Shapes::Struct.new hash struct.ident = hash[:ident] struct.description = hash[:description] struct.struct_name = hash[:type] struct.resource_type = 'Struct' build_children(hash).each do |child| struct << child end struct end private def build_children(hash) shape_struct = ShapeStruct.find_by_name hash[:type] shape_struct.primitives.collect do |primitive| # hash[:struct][primitive.ident.to_sym] for empty checkboxes primitive_hash = hash[:struct] && hash[:struct][primitive.ident.to_sym] ? hash[:struct][primitive.ident.to_sym] : {} primitive.build_primitive primitive_hash end end end end end end
Add resource-type in StructFromHash not in StructFromXml
Add resource-type in StructFromHash not in StructFromXml
Ruby
mit
fork/shapes,fork/shapes
ruby
## Code Before: module Shapes module Builder class Struct attr_reader :data attr_accessor :builder_strategy, :resource def initialize(data) @data = data @builder_strategy = if(data.is_a?(XML::Node)) StructFromXml.new else StructFromHash.new end end def build_resource @resource = @builder_strategy.build_object @data end class StructFromXml def build_object(node) struct = Shapes::Struct.new struct.xml_node = node struct.read_from_node struct.ident = node['ident'].to_s struct.description = node['description'].to_s struct.resource_type = 'Struct' struct end end class StructFromHash def build_object(hash) struct = Shapes::Struct.new hash struct.ident = hash[:ident] struct.description = hash[:description] struct.struct_name = hash[:type] build_children(hash).each do |child| struct << child end struct end private def build_children(hash) shape_struct = ShapeStruct.find_by_name hash[:type] shape_struct.primitives.collect do |primitive| # hash[:struct][primitive.ident.to_sym] for empty checkboxes primitive_hash = hash[:struct] && hash[:struct][primitive.ident.to_sym] ? hash[:struct][primitive.ident.to_sym] : {} primitive.build_primitive primitive_hash end end end end end end ## Instruction: Add resource-type in StructFromHash not in StructFromXml ## Code After: module Shapes module Builder class Struct attr_reader :data attr_accessor :builder_strategy, :resource def initialize(data) @data = data @builder_strategy = if(data.is_a?(XML::Node)) StructFromXml.new else StructFromHash.new end end def build_resource @resource = @builder_strategy.build_object @data end class StructFromXml def build_object(node) struct = Shapes::Struct.new struct.xml_node = node struct.read_from_node struct.ident = node['ident'].to_s struct.description = node['description'].to_s struct end end class StructFromHash def build_object(hash) struct = Shapes::Struct.new hash struct.ident = hash[:ident] struct.description = hash[:description] struct.struct_name = hash[:type] struct.resource_type = 'Struct' build_children(hash).each do |child| struct << child end struct end private def build_children(hash) shape_struct = ShapeStruct.find_by_name hash[:type] shape_struct.primitives.collect do |primitive| # hash[:struct][primitive.ident.to_sym] for empty checkboxes primitive_hash = hash[:struct] && hash[:struct][primitive.ident.to_sym] ? hash[:struct][primitive.ident.to_sym] : {} primitive.build_primitive primitive_hash end end end end end end
f016f03079f9c9c5065b6ce4227b4323a32e610e
core/src/main/java/foundation/stack/datamill/db/impl/UnsubscribeOnNextOperator.java
core/src/main/java/foundation/stack/datamill/db/impl/UnsubscribeOnNextOperator.java
package foundation.stack.datamill.db.impl; import rx.Observable; import rx.Subscriber; import rx.exceptions.Exceptions; import java.util.concurrent.atomic.AtomicBoolean; /** * @author Ravi Chodavarapu (rchodava@gmail.com) */ public class UnsubscribeOnNextOperator<T> implements Observable.Operator<T, T> { private final AtomicBoolean completed = new AtomicBoolean(); @Override public Subscriber<? super T> call(Subscriber<? super T> subscriber) { return new Subscriber<T>() { @Override public void onCompleted() { this.unsubscribe(); if (!subscriber.isUnsubscribed()) { if (completed.compareAndSet(false, true)) { subscriber.onCompleted(); } } } @Override public void onError(Throwable e) { this.unsubscribe(); if (!subscriber.isUnsubscribed()) { if (completed.compareAndSet(false, true)) { subscriber.onError(e); } } } @Override public void onNext(T t) { this.unsubscribe(); if (!subscriber.isUnsubscribed()) { if (completed.compareAndSet(false, true)) { try { subscriber.onNext(t); subscriber.onCompleted(); } catch (Throwable e) { Exceptions.throwIfFatal(e); subscriber.onError(e); } } } } }; } }
package foundation.stack.datamill.db.impl; import rx.Observable; import rx.Subscriber; import rx.exceptions.Exceptions; import java.util.concurrent.atomic.AtomicBoolean; /** * @author Ravi Chodavarapu (rchodava@gmail.com) */ public class UnsubscribeOnNextOperator<T> implements Observable.Operator<T, T> { @Override public Subscriber<? super T> call(Subscriber<? super T> subscriber) { return new Subscriber<T>() { private final AtomicBoolean completed = new AtomicBoolean(); @Override public void onCompleted() { this.unsubscribe(); if (!subscriber.isUnsubscribed()) { if (completed.compareAndSet(false, true)) { subscriber.onCompleted(); } } } @Override public void onError(Throwable e) { this.unsubscribe(); if (!subscriber.isUnsubscribed()) { if (completed.compareAndSet(false, true)) { subscriber.onError(e); } } } @Override public void onNext(T t) { this.unsubscribe(); if (!subscriber.isUnsubscribed()) { if (completed.compareAndSet(false, true)) { try { subscriber.onNext(t); subscriber.onCompleted(); } catch (Throwable e) { Exceptions.throwIfFatal(e); subscriber.onError(e); } } } } }; } }
Fix to ensure the unsubscribe on next operator used for database queries can be reused
Fix to ensure the unsubscribe on next operator used for database queries can be reused
Java
isc
rchodava/datamill
java
## Code Before: package foundation.stack.datamill.db.impl; import rx.Observable; import rx.Subscriber; import rx.exceptions.Exceptions; import java.util.concurrent.atomic.AtomicBoolean; /** * @author Ravi Chodavarapu (rchodava@gmail.com) */ public class UnsubscribeOnNextOperator<T> implements Observable.Operator<T, T> { private final AtomicBoolean completed = new AtomicBoolean(); @Override public Subscriber<? super T> call(Subscriber<? super T> subscriber) { return new Subscriber<T>() { @Override public void onCompleted() { this.unsubscribe(); if (!subscriber.isUnsubscribed()) { if (completed.compareAndSet(false, true)) { subscriber.onCompleted(); } } } @Override public void onError(Throwable e) { this.unsubscribe(); if (!subscriber.isUnsubscribed()) { if (completed.compareAndSet(false, true)) { subscriber.onError(e); } } } @Override public void onNext(T t) { this.unsubscribe(); if (!subscriber.isUnsubscribed()) { if (completed.compareAndSet(false, true)) { try { subscriber.onNext(t); subscriber.onCompleted(); } catch (Throwable e) { Exceptions.throwIfFatal(e); subscriber.onError(e); } } } } }; } } ## Instruction: Fix to ensure the unsubscribe on next operator used for database queries can be reused ## Code After: package foundation.stack.datamill.db.impl; import rx.Observable; import rx.Subscriber; import rx.exceptions.Exceptions; import java.util.concurrent.atomic.AtomicBoolean; /** * @author Ravi Chodavarapu (rchodava@gmail.com) */ public class UnsubscribeOnNextOperator<T> implements Observable.Operator<T, T> { @Override public Subscriber<? super T> call(Subscriber<? super T> subscriber) { return new Subscriber<T>() { private final AtomicBoolean completed = new AtomicBoolean(); @Override public void onCompleted() { this.unsubscribe(); if (!subscriber.isUnsubscribed()) { if (completed.compareAndSet(false, true)) { subscriber.onCompleted(); } } } @Override public void onError(Throwable e) { this.unsubscribe(); if (!subscriber.isUnsubscribed()) { if (completed.compareAndSet(false, true)) { subscriber.onError(e); } } } @Override public void onNext(T t) { this.unsubscribe(); if (!subscriber.isUnsubscribed()) { if (completed.compareAndSet(false, true)) { try { subscriber.onNext(t); subscriber.onCompleted(); } catch (Throwable e) { Exceptions.throwIfFatal(e); subscriber.onError(e); } } } } }; } }
d0818c7dcabebe7697444b73b6b8f30ade73958d
openedx/core/djangoapps/appsembler/eventtracking/utils.py
openedx/core/djangoapps/appsembler/eventtracking/utils.py
from django.core.exceptions import MultipleObjectsReturned from . import exceptions def get_site_config_for_event(event_props): """ Try multiple strategies to find a SiteConfiguration object to use for evaluating and processing an event. Return a SiteConfiguration object if found; otherwise, None. """ from openedx.core.djangoapps.appsembler.sites import utils from openedx.core.djangoapps.site_configuration import helpers from organizations import models # try first via request obj in thread site_configuration = helpers.get_current_site_configuration() if not site_configuration: try: if 'org' in event_props: org_name = event_props['org'] org = models.Organization.objects.get(short_name=org_name) # try by OrganizationCourse relationship if event has a course_id property elif 'course_id' in event_props: course_id = event_props['course_id'] # allow to fail if more than one Organization to avoid sharing data orgcourse = models.OrganizationCourse.objects.get(course_id=args) org = orgcourse.organization site = utils.get_site_by_organization(org) site_configuration = site.configuration except ( AttributeError, TypeError, MultipleObjectsReturned, models.Organization.DoesNotExist, models.OrganizationCourse.DoesNotExist ) as e: raise exceptions.EventProcessingError(e) return site_configuration
from django.core.exceptions import MultipleObjectsReturned from . import exceptions def get_site_config_for_event(event_props): """ Try multiple strategies to find a SiteConfiguration object to use for evaluating and processing an event. Return a SiteConfiguration object if found; otherwise, None. """ from openedx.core.djangoapps.appsembler.sites import utils from openedx.core.djangoapps.site_configuration import helpers from organizations import models # try first via request obj in thread site_configuration = helpers.get_current_site_configuration() if not site_configuration: try: if 'org' in event_props: org_name = event_props['org'] org = models.Organization.objects.get(short_name=org_name) # try by OrganizationCourse relationship if event has a course_id property elif 'course_id' in event_props: course_id = event_props['course_id'] # allow to fail if more than one Organization to avoid sharing data orgcourse = models.OrganizationCourse.objects.get(course_id=args) org = orgcourse.organization else: raise exceptions.EventProcessingError( "There isn't and org or course_id attribute set in the " "segment event, so we couldn't determine the site." ) site = utils.get_site_by_organization(org) site_configuration = site.configuration except ( AttributeError, TypeError, MultipleObjectsReturned, models.Organization.DoesNotExist, models.OrganizationCourse.DoesNotExist ) as e: raise exceptions.EventProcessingError(e) return site_configuration
Return exeption if cannot get the site config in event
Return exeption if cannot get the site config in event
Python
agpl-3.0
appsembler/edx-platform,appsembler/edx-platform,appsembler/edx-platform,appsembler/edx-platform
python
## Code Before: from django.core.exceptions import MultipleObjectsReturned from . import exceptions def get_site_config_for_event(event_props): """ Try multiple strategies to find a SiteConfiguration object to use for evaluating and processing an event. Return a SiteConfiguration object if found; otherwise, None. """ from openedx.core.djangoapps.appsembler.sites import utils from openedx.core.djangoapps.site_configuration import helpers from organizations import models # try first via request obj in thread site_configuration = helpers.get_current_site_configuration() if not site_configuration: try: if 'org' in event_props: org_name = event_props['org'] org = models.Organization.objects.get(short_name=org_name) # try by OrganizationCourse relationship if event has a course_id property elif 'course_id' in event_props: course_id = event_props['course_id'] # allow to fail if more than one Organization to avoid sharing data orgcourse = models.OrganizationCourse.objects.get(course_id=args) org = orgcourse.organization site = utils.get_site_by_organization(org) site_configuration = site.configuration except ( AttributeError, TypeError, MultipleObjectsReturned, models.Organization.DoesNotExist, models.OrganizationCourse.DoesNotExist ) as e: raise exceptions.EventProcessingError(e) return site_configuration ## Instruction: Return exeption if cannot get the site config in event ## Code After: from django.core.exceptions import MultipleObjectsReturned from . import exceptions def get_site_config_for_event(event_props): """ Try multiple strategies to find a SiteConfiguration object to use for evaluating and processing an event. Return a SiteConfiguration object if found; otherwise, None. """ from openedx.core.djangoapps.appsembler.sites import utils from openedx.core.djangoapps.site_configuration import helpers from organizations import models # try first via request obj in thread site_configuration = helpers.get_current_site_configuration() if not site_configuration: try: if 'org' in event_props: org_name = event_props['org'] org = models.Organization.objects.get(short_name=org_name) # try by OrganizationCourse relationship if event has a course_id property elif 'course_id' in event_props: course_id = event_props['course_id'] # allow to fail if more than one Organization to avoid sharing data orgcourse = models.OrganizationCourse.objects.get(course_id=args) org = orgcourse.organization else: raise exceptions.EventProcessingError( "There isn't and org or course_id attribute set in the " "segment event, so we couldn't determine the site." ) site = utils.get_site_by_organization(org) site_configuration = site.configuration except ( AttributeError, TypeError, MultipleObjectsReturned, models.Organization.DoesNotExist, models.OrganizationCourse.DoesNotExist ) as e: raise exceptions.EventProcessingError(e) return site_configuration
a36a13b99918e22706aeea57b66bd56826d54fc5
src/simple-slider.html
src/simple-slider.html
<link rel="import" href="../bower_components/polymer/polymer.html"> <script src="../bower_components/SimpleSlider/dist/simpleslider.min.js"></script> <polymer-element name="simple-slider" constructor="SimpleSliderElement" attributes="transition-property transition-duration transition-delay start-value visible-value end-value auto-play"> <script> var options = {}; var element; options.created = function () { element = new window.SimpleSlider(this, { transitionProperty: this['transition-property'], transitionDuration: this['transition-duration'], transitionDelay: this['transition-delay'], startValue: this['start-value'], visibleValue: this['visible-value'], endValue: this['end-value'], autoPlay: this['auto-play'] }); }; // Dispose slider on element detach options.detached = function () { element.dispose(); }; // Define slider methods on polymer element options.actualIndex = function() { return element.actualIndex; }; options.change = function(index) { element.change(index); }; options.next = function() { element.next(); }; options.prev = function() { element.prev(); }; options.prevIndex = function() { return element.prevIndex(); }; options.nextIndex = function() { return element.nextIndex(); }; options.dispose = function() { element.dispose(); }; Polymer('simple-slider', options); </script> </polymer-element>
<link rel="import" href="../../polymer/polymer.html"> <script src="../../SimpleSlider/dist/simpleslider.min.js"></script> <polymer-element name="simple-slider" constructor="SimpleSliderElement" attributes="transition-property transition-duration transition-delay start-value visible-value end-value auto-play"> <script> var options = {}; var element; options.created = function () { element = new window.SimpleSlider(this, { transitionProperty: this['transition-property'], transitionDuration: this['transition-duration'], transitionDelay: this['transition-delay'], startValue: this['start-value'], visibleValue: this['visible-value'], endValue: this['end-value'], autoPlay: this['auto-play'] }); }; // Dispose slider on element detach options.detached = function () { element.dispose(); }; // Define slider methods on polymer element options.actualIndex = function() { return element.actualIndex; }; options.change = function(index) { element.change(index); }; options.next = function() { element.next(); }; options.prev = function() { element.prev(); }; options.prevIndex = function() { return element.prevIndex(); }; options.nextIndex = function() { return element.nextIndex(); }; options.dispose = function() { element.dispose(); }; Polymer('simple-slider', options); </script> </polymer-element>
Use paths to polymer/SimpleSlider without bower_components
Use paths to polymer/SimpleSlider without bower_components
HTML
mit
ruyadorno/polymer-simple-slider,ruyadorno/polymer-simple-slider
html
## Code Before: <link rel="import" href="../bower_components/polymer/polymer.html"> <script src="../bower_components/SimpleSlider/dist/simpleslider.min.js"></script> <polymer-element name="simple-slider" constructor="SimpleSliderElement" attributes="transition-property transition-duration transition-delay start-value visible-value end-value auto-play"> <script> var options = {}; var element; options.created = function () { element = new window.SimpleSlider(this, { transitionProperty: this['transition-property'], transitionDuration: this['transition-duration'], transitionDelay: this['transition-delay'], startValue: this['start-value'], visibleValue: this['visible-value'], endValue: this['end-value'], autoPlay: this['auto-play'] }); }; // Dispose slider on element detach options.detached = function () { element.dispose(); }; // Define slider methods on polymer element options.actualIndex = function() { return element.actualIndex; }; options.change = function(index) { element.change(index); }; options.next = function() { element.next(); }; options.prev = function() { element.prev(); }; options.prevIndex = function() { return element.prevIndex(); }; options.nextIndex = function() { return element.nextIndex(); }; options.dispose = function() { element.dispose(); }; Polymer('simple-slider', options); </script> </polymer-element> ## Instruction: Use paths to polymer/SimpleSlider without bower_components ## Code After: <link rel="import" href="../../polymer/polymer.html"> <script src="../../SimpleSlider/dist/simpleslider.min.js"></script> <polymer-element name="simple-slider" constructor="SimpleSliderElement" attributes="transition-property transition-duration transition-delay start-value visible-value end-value auto-play"> <script> var options = {}; var element; options.created = function () { element = new window.SimpleSlider(this, { transitionProperty: this['transition-property'], transitionDuration: this['transition-duration'], transitionDelay: this['transition-delay'], startValue: this['start-value'], visibleValue: this['visible-value'], endValue: this['end-value'], autoPlay: this['auto-play'] }); }; // Dispose slider on element detach options.detached = function () { element.dispose(); }; // Define slider methods on polymer element options.actualIndex = function() { return element.actualIndex; }; options.change = function(index) { element.change(index); }; options.next = function() { element.next(); }; options.prev = function() { element.prev(); }; options.prevIndex = function() { return element.prevIndex(); }; options.nextIndex = function() { return element.nextIndex(); }; options.dispose = function() { element.dispose(); }; Polymer('simple-slider', options); </script> </polymer-element>
7942b0f27712af17062795577d7dbc82de4d781b
dallinger/frontend/templates/base/dashboard.html
dallinger/frontend/templates/base/dashboard.html
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <title>{% block title %}{{title}} - {{app_id}} Dashboard{% endblock %}</title> {% block replace_stylesheets %} <link rel="stylesheet" href="/static/css/bootstrap.min.css" type="text/css"> {% block stylesheets %} {% endblock %} {% endblock %} {% block head %} {% endblock %} </head> <body> <div class="container"> {% block navigation %} <nav id="dashboard-navigation"> <ul> {% for tab_title, route in config.get('dashboard_tabs',()) %} <li><a href="{{ url_for(route) }}">{{ tab_title }}</a></li> {% endfor %} </ul> </nav> {% endblock %} {% block messages %} {% with messages = get_flashed_messages(with_categories=true) %} {% if messages %} {% for category, message in messages %} <div class="alert alert-{{ category }}" role="alert">{{ message }}</div> {% endfor %} {% endif %} {% endwith %} {% endblock %} {% block body %} {% endblock %} <footer> {% block footer %} <a class="btn logout" href="{{ url_for('dashboard.logout') }}">Logout</a> {% endblock %} </footer> </div> </body> </html>
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <title>{% block title %}{{title}} - {{app_id}} Dashboard{% endblock %}</title> {% block replace_stylesheets %} <link rel="stylesheet" href="/static/css/bootstrap.min.css" type="text/css"> {% block stylesheets %} {% endblock %} {% endblock %} {% block head %} {% endblock %} </head> <body> <div class="container"> {% block navigation %} <nav id="dashboard-navigation"> <ul class="nav nav-pills"> {% for tab_title, route in config.get('dashboard_tabs',()) %} <li class="nav-item{{ route == request.endpoint and ' active' or ''}}"> <a class="nav-link" href="{{ url_for(route) }}">{{ tab_title }}</a> </li> {% endfor %} </ul> </nav> {% endblock %} {% block messages %} {% with messages = get_flashed_messages(with_categories=true) %} {% if messages %} {% for category, message in messages %} <div class="alert alert-{{ category }}" role="alert">{{ message }}</div> {% endfor %} {% endif %} {% endwith %} {% endblock %} {% block body %} {% endblock %} <footer> {% block footer %} <a class="btn logout" href="{{ url_for('dashboard.logout') }}">Logout</a> {% endblock %} </footer> </div> </body> </html>
Add some bootstrap navigation styling.
Add some bootstrap navigation styling.
HTML
mit
Dallinger/Dallinger,Dallinger/Dallinger,Dallinger/Dallinger,Dallinger/Dallinger,Dallinger/Dallinger
html
## Code Before: <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <title>{% block title %}{{title}} - {{app_id}} Dashboard{% endblock %}</title> {% block replace_stylesheets %} <link rel="stylesheet" href="/static/css/bootstrap.min.css" type="text/css"> {% block stylesheets %} {% endblock %} {% endblock %} {% block head %} {% endblock %} </head> <body> <div class="container"> {% block navigation %} <nav id="dashboard-navigation"> <ul> {% for tab_title, route in config.get('dashboard_tabs',()) %} <li><a href="{{ url_for(route) }}">{{ tab_title }}</a></li> {% endfor %} </ul> </nav> {% endblock %} {% block messages %} {% with messages = get_flashed_messages(with_categories=true) %} {% if messages %} {% for category, message in messages %} <div class="alert alert-{{ category }}" role="alert">{{ message }}</div> {% endfor %} {% endif %} {% endwith %} {% endblock %} {% block body %} {% endblock %} <footer> {% block footer %} <a class="btn logout" href="{{ url_for('dashboard.logout') }}">Logout</a> {% endblock %} </footer> </div> </body> </html> ## Instruction: Add some bootstrap navigation styling. ## Code After: <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <title>{% block title %}{{title}} - {{app_id}} Dashboard{% endblock %}</title> {% block replace_stylesheets %} <link rel="stylesheet" href="/static/css/bootstrap.min.css" type="text/css"> {% block stylesheets %} {% endblock %} {% endblock %} {% block head %} {% endblock %} </head> <body> <div class="container"> {% block navigation %} <nav id="dashboard-navigation"> <ul class="nav nav-pills"> {% for tab_title, route in config.get('dashboard_tabs',()) %} <li class="nav-item{{ route == request.endpoint and ' active' or ''}}"> <a class="nav-link" href="{{ url_for(route) }}">{{ tab_title }}</a> </li> {% endfor %} </ul> </nav> {% endblock %} {% block messages %} {% with messages = get_flashed_messages(with_categories=true) %} {% if messages %} {% for category, message in messages %} <div class="alert alert-{{ category }}" role="alert">{{ message }}</div> {% endfor %} {% endif %} {% endwith %} {% endblock %} {% block body %} {% endblock %} <footer> {% block footer %} <a class="btn logout" href="{{ url_for('dashboard.logout') }}">Logout</a> {% endblock %} </footer> </div> </body> </html>
6fe46f6746a6a444548d26333f3c3d47c1cb42bf
src/main/java/org/aesh/command/impl/operator/AppendOutputRedirectionOperator.java
src/main/java/org/aesh/command/impl/operator/AppendOutputRedirectionOperator.java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package org.aesh.command.impl.operator; import java.io.BufferedWriter; import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.StandardOpenOption; import org.aesh.command.invocation.CommandInvocationConfiguration; import org.aesh.readline.AeshContext; /** * * @author jdenise@redhat.com */ /** * * @author jdenise@redhat.com */ public class AppendOutputRedirectionOperator implements ConfigurationOperator { private class OutputDelegateImpl extends FileOutputDelegate { private OutputDelegateImpl(String file) throws IOException { super(context, file); } @Override protected BufferedWriter buildWriter(File f) throws IOException { return Files.newBufferedWriter(f.toPath(), StandardCharsets.UTF_8, StandardOpenOption.APPEND); } } private CommandInvocationConfiguration config; private String argument; private final AeshContext context; public AppendOutputRedirectionOperator(AeshContext context) { this.context = context; } @Override public CommandInvocationConfiguration getConfiguration() throws IOException { if (config == null) { config = new CommandInvocationConfiguration(context, new OutputDelegateImpl(argument)); } return config; } @Override public void setArgument(String argument) { this.argument = argument; } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package org.aesh.command.impl.operator; import java.io.BufferedWriter; import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.StandardOpenOption; import org.aesh.command.invocation.CommandInvocationConfiguration; import org.aesh.readline.AeshContext; /** * * @author jdenise@redhat.com */ /** * * @author jdenise@redhat.com */ public class AppendOutputRedirectionOperator implements ConfigurationOperator { private class OutputDelegateImpl extends FileOutputDelegate { private OutputDelegateImpl(String file) throws IOException { super(context, file); } @Override protected BufferedWriter buildWriter(File f) throws IOException { return Files.newBufferedWriter(f.toPath(), StandardCharsets.UTF_8, StandardOpenOption.APPEND, StandardOpenOption.CREATE); } } private CommandInvocationConfiguration config; private String argument; private final AeshContext context; public AppendOutputRedirectionOperator(AeshContext context) { this.context = context; } @Override public CommandInvocationConfiguration getConfiguration() throws IOException { if (config == null) { config = new CommandInvocationConfiguration(context, new OutputDelegateImpl(argument)); } return config; } @Override public void setArgument(String argument) { this.argument = argument; } }
Fix >> to create a new file
Fix >> to create a new file
Java
apache-2.0
aeshell/aesh,jfdenise/aesh,stalep/aesh
java
## Code Before: /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package org.aesh.command.impl.operator; import java.io.BufferedWriter; import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.StandardOpenOption; import org.aesh.command.invocation.CommandInvocationConfiguration; import org.aesh.readline.AeshContext; /** * * @author jdenise@redhat.com */ /** * * @author jdenise@redhat.com */ public class AppendOutputRedirectionOperator implements ConfigurationOperator { private class OutputDelegateImpl extends FileOutputDelegate { private OutputDelegateImpl(String file) throws IOException { super(context, file); } @Override protected BufferedWriter buildWriter(File f) throws IOException { return Files.newBufferedWriter(f.toPath(), StandardCharsets.UTF_8, StandardOpenOption.APPEND); } } private CommandInvocationConfiguration config; private String argument; private final AeshContext context; public AppendOutputRedirectionOperator(AeshContext context) { this.context = context; } @Override public CommandInvocationConfiguration getConfiguration() throws IOException { if (config == null) { config = new CommandInvocationConfiguration(context, new OutputDelegateImpl(argument)); } return config; } @Override public void setArgument(String argument) { this.argument = argument; } } ## Instruction: Fix >> to create a new file ## Code After: /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package org.aesh.command.impl.operator; import java.io.BufferedWriter; import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.StandardOpenOption; import org.aesh.command.invocation.CommandInvocationConfiguration; import org.aesh.readline.AeshContext; /** * * @author jdenise@redhat.com */ /** * * @author jdenise@redhat.com */ public class AppendOutputRedirectionOperator implements ConfigurationOperator { private class OutputDelegateImpl extends FileOutputDelegate { private OutputDelegateImpl(String file) throws IOException { super(context, file); } @Override protected BufferedWriter buildWriter(File f) throws IOException { return Files.newBufferedWriter(f.toPath(), StandardCharsets.UTF_8, StandardOpenOption.APPEND, StandardOpenOption.CREATE); } } private CommandInvocationConfiguration config; private String argument; private final AeshContext context; public AppendOutputRedirectionOperator(AeshContext context) { this.context = context; } @Override public CommandInvocationConfiguration getConfiguration() throws IOException { if (config == null) { config = new CommandInvocationConfiguration(context, new OutputDelegateImpl(argument)); } return config; } @Override public void setArgument(String argument) { this.argument = argument; } }
2bba64bf352c3897cc21157e9af41fb903e68f51
www/LocalStorageHandle.js
www/LocalStorageHandle.js
var NativeStorageError = require('./NativeStorageError'); // args = [reference, variable] function LocalStorageHandle(success, error, intent, operation, args) { var reference = args[0]; var variable = args[1]; if (operation.startsWith('put') || operation.startsWith('set')) { try { var varAsString = JSON.stringify(variable); if (reference === null) { error(new NativeStorageError(NativeStorageError.NULL_REFERENCE, "JS", "")); return; } localStorage.setItem(reference, varAsString); success(variable); } catch (err) { error(new NativeStorageError(NativeStorageError.JSON_ERROR, "JS", err)); } } else if (operation.startsWith('get')) { var item = {}; item = localStorage.getItem(reference); if (item === null) { error(new NativeStorageError(NativeStorageError.ITEM_NOT_FOUND,"JS","")); return; } try { var obj = JSON.parse(item); //console.log("LocalStorage Reading: "+obj); success(obj); } catch (err) { error(new NativeStorageError(NativeStorageError.JSON_ERROR, "JS", err)); } } else if(operation === 'keys') { const keys = []; let key = localStorage.key(0); if(!key) { return success(keys); } let i = 0; while(key) { keys.push(key); i++; key = localStorage.key(i); } success(keys); } } module.exports = LocalStorageHandle;
var NativeStorageError = require('./NativeStorageError'); // args = [reference, variable] function LocalStorageHandle(success, error, intent, operation, args) { var reference = args[0]; var variable = args[1]; if (operation.startsWith('put') || operation.startsWith('set')) { try { var varAsString = JSON.stringify(variable); if (reference === null) { error(new NativeStorageError(NativeStorageError.NULL_REFERENCE, "JS", "")); return; } localStorage.setItem(reference, varAsString); success(variable); } catch (err) { error(new NativeStorageError(NativeStorageError.JSON_ERROR, "JS", err)); } } else if (operation.startsWith('get')) { var item = {}; item = localStorage.getItem(reference); if (item === null) { error(new NativeStorageError(NativeStorageError.ITEM_NOT_FOUND,"JS","")); return; } try { var obj = JSON.parse(item); //console.log("LocalStorage Reading: "+obj); success(obj); } catch (err) { error(new NativeStorageError(NativeStorageError.JSON_ERROR, "JS", err)); } } else if (operation === 'keys') { var keys = []; var key = localStorage.key(0); if(!key) { return success(keys); } var i = 0; while(key) { keys.push(key); i++; key = localStorage.key(i); } success(keys); } } module.exports = LocalStorageHandle;
Use var for compatibility with Android 4.x
Use var for compatibility with Android 4.x
JavaScript
apache-2.0
TheCocoaProject/cordova-plugin-nativestorage,TheCocoaProject/cordova-plugin-nativestorage
javascript
## Code Before: var NativeStorageError = require('./NativeStorageError'); // args = [reference, variable] function LocalStorageHandle(success, error, intent, operation, args) { var reference = args[0]; var variable = args[1]; if (operation.startsWith('put') || operation.startsWith('set')) { try { var varAsString = JSON.stringify(variable); if (reference === null) { error(new NativeStorageError(NativeStorageError.NULL_REFERENCE, "JS", "")); return; } localStorage.setItem(reference, varAsString); success(variable); } catch (err) { error(new NativeStorageError(NativeStorageError.JSON_ERROR, "JS", err)); } } else if (operation.startsWith('get')) { var item = {}; item = localStorage.getItem(reference); if (item === null) { error(new NativeStorageError(NativeStorageError.ITEM_NOT_FOUND,"JS","")); return; } try { var obj = JSON.parse(item); //console.log("LocalStorage Reading: "+obj); success(obj); } catch (err) { error(new NativeStorageError(NativeStorageError.JSON_ERROR, "JS", err)); } } else if(operation === 'keys') { const keys = []; let key = localStorage.key(0); if(!key) { return success(keys); } let i = 0; while(key) { keys.push(key); i++; key = localStorage.key(i); } success(keys); } } module.exports = LocalStorageHandle; ## Instruction: Use var for compatibility with Android 4.x ## Code After: var NativeStorageError = require('./NativeStorageError'); // args = [reference, variable] function LocalStorageHandle(success, error, intent, operation, args) { var reference = args[0]; var variable = args[1]; if (operation.startsWith('put') || operation.startsWith('set')) { try { var varAsString = JSON.stringify(variable); if (reference === null) { error(new NativeStorageError(NativeStorageError.NULL_REFERENCE, "JS", "")); return; } localStorage.setItem(reference, varAsString); success(variable); } catch (err) { error(new NativeStorageError(NativeStorageError.JSON_ERROR, "JS", err)); } } else if (operation.startsWith('get')) { var item = {}; item = localStorage.getItem(reference); if (item === null) { error(new NativeStorageError(NativeStorageError.ITEM_NOT_FOUND,"JS","")); return; } try { var obj = JSON.parse(item); //console.log("LocalStorage Reading: "+obj); success(obj); } catch (err) { error(new NativeStorageError(NativeStorageError.JSON_ERROR, "JS", err)); } } else if (operation === 'keys') { var keys = []; var key = localStorage.key(0); if(!key) { return success(keys); } var i = 0; while(key) { keys.push(key); i++; key = localStorage.key(i); } success(keys); } } module.exports = LocalStorageHandle;
4543063fc5ba86aaf73d93277726bc6b3ee34169
lib/json/streamer/json_streamer.rb
lib/json/streamer/json_streamer.rb
require_relative 'conditions' require_relative 'parser' module Json module Streamer class JsonStreamer attr_reader :parser def initialize(file_io = nil, chunk_size = 1000, event_generator = :default) @event_generator = make_event_generator(event_generator) @file_io = file_io @chunk_size = chunk_size end def <<(data) parser << data end def get(nesting_level: -1, key: nil, yield_values: true, symbolize_keys: false) conditions = Conditions.new(yield_level: nesting_level, yield_key: key) conditions.yield_value = ->(aggregator:, value:) { false } unless yield_values # TODO: deprecate symbolize_keys and move to initialize @parser = Parser.new(@event_generator, symbolize_keys: symbolize_keys) parser.get(conditions) do |obj| yield obj end process_io end def get_with_conditions(conditions, options = {}) @parser = Parser.new(@event_generator, symbolize_keys: options[:symbolize_keys]) parser.get(conditions) do |obj| yield obj end process_io end def aggregator parser.aggregator end private def process_io @file_io.each(@chunk_size) { |chunk| parser << chunk } if @file_io end def make_event_generator(generator) case generator when :default require 'json/stream' JSON::Stream::Parser.new else generator end end end end end
require_relative 'conditions' require_relative 'parser' module Json module Streamer class JsonStreamer attr_reader :parser def initialize(file_io = nil, chunk_size = 1000, event_generator = :default) @event_generator = make_event_generator(event_generator) @file_io = file_io @chunk_size = chunk_size end def <<(data) parser << data end def get(nesting_level: -1, key: nil, yield_values: true, symbolize_keys: false) conditions = Conditions.new(yield_level: nesting_level, yield_key: key) conditions.yield_value = ->(aggregator:, value:) { false } unless yield_values @parser = Parser.new(@event_generator, symbolize_keys: symbolize_keys) parser.get(conditions) do |obj| yield obj end process_io end def get_with_conditions(conditions, options = {}) @parser = Parser.new(@event_generator, symbolize_keys: options[:symbolize_keys]) parser.get(conditions) do |obj| yield obj end process_io end def aggregator parser.aggregator end private def process_io @file_io.each(@chunk_size) { |chunk| parser << chunk } if @file_io end def make_event_generator(generator) case generator when :default require 'json/stream' JSON::Stream::Parser.new else generator end end end end end
Remove todo comment, wont do
Remove todo comment, wont do
Ruby
mit
thisismydesign/json-streamer,csapagyi/json-streamer,thisismydesign/json-streamer,csapagyi/json-streamer
ruby
## Code Before: require_relative 'conditions' require_relative 'parser' module Json module Streamer class JsonStreamer attr_reader :parser def initialize(file_io = nil, chunk_size = 1000, event_generator = :default) @event_generator = make_event_generator(event_generator) @file_io = file_io @chunk_size = chunk_size end def <<(data) parser << data end def get(nesting_level: -1, key: nil, yield_values: true, symbolize_keys: false) conditions = Conditions.new(yield_level: nesting_level, yield_key: key) conditions.yield_value = ->(aggregator:, value:) { false } unless yield_values # TODO: deprecate symbolize_keys and move to initialize @parser = Parser.new(@event_generator, symbolize_keys: symbolize_keys) parser.get(conditions) do |obj| yield obj end process_io end def get_with_conditions(conditions, options = {}) @parser = Parser.new(@event_generator, symbolize_keys: options[:symbolize_keys]) parser.get(conditions) do |obj| yield obj end process_io end def aggregator parser.aggregator end private def process_io @file_io.each(@chunk_size) { |chunk| parser << chunk } if @file_io end def make_event_generator(generator) case generator when :default require 'json/stream' JSON::Stream::Parser.new else generator end end end end end ## Instruction: Remove todo comment, wont do ## Code After: require_relative 'conditions' require_relative 'parser' module Json module Streamer class JsonStreamer attr_reader :parser def initialize(file_io = nil, chunk_size = 1000, event_generator = :default) @event_generator = make_event_generator(event_generator) @file_io = file_io @chunk_size = chunk_size end def <<(data) parser << data end def get(nesting_level: -1, key: nil, yield_values: true, symbolize_keys: false) conditions = Conditions.new(yield_level: nesting_level, yield_key: key) conditions.yield_value = ->(aggregator:, value:) { false } unless yield_values @parser = Parser.new(@event_generator, symbolize_keys: symbolize_keys) parser.get(conditions) do |obj| yield obj end process_io end def get_with_conditions(conditions, options = {}) @parser = Parser.new(@event_generator, symbolize_keys: options[:symbolize_keys]) parser.get(conditions) do |obj| yield obj end process_io end def aggregator parser.aggregator end private def process_io @file_io.each(@chunk_size) { |chunk| parser << chunk } if @file_io end def make_event_generator(generator) case generator when :default require 'json/stream' JSON::Stream::Parser.new else generator end end end end end
38fdaa34df2383b3af00ba1149a8f60b0f0c3ab6
lib/Spark/Controller/Base.php
lib/Spark/Controller/Base.php
<?php namespace Spark\Controller; use Silex\Application; use Symfony\Component\HttpFoundation\Response; use Spark\Core\ApplicationAware; abstract class Base implements ApplicationAware { use ActionHelper\Filters; use ActionHelper\Redirect; use ActionHelper\Layout; protected $application; protected $response; protected $flash; function __construct() { $this->response = new Response; $this->setup(); } function setup() {} function render($options = []) { $attributes = $this->request()->attributes; if (!$options) { $options['script'] = $attributes->get('controller') . '/' . $attributes->get('action'); } if (isset($options['status'])) { $this->response()->setStatusCode($options['status']); unset($options['status']); } return $this->application['spark.render_pipeline']->render($options, $this->response()); } function request() { return $this->application['request']; } function response() { return $this->response; } function flash() { return $this->flash ?: $this->flash = $this->application['session']->getFlashBag(); } function session() { return $this->application['session']; } function application() { return $this->application; } function setApplication(Application $application) { $this->application = $application; } }
<?php namespace Spark\Controller; use Silex\Application; use Symfony\Component\HttpFoundation\Response; use Spark\Core\ApplicationAware; abstract class Base implements ApplicationAware { use ActionHelper\Filters; use ActionHelper\Redirect; use ActionHelper\Layout; protected $application; protected $response; protected $flash; function __construct() { $this->response = new Response; $this->setup(); } function setup() {} function render($options = []) { $attributes = $this->request()->attributes; if (!$options) { $options['script'] = $attributes->get('controller') . '/' . $attributes->get('action'); } if (isset($options['status'])) { $this->response()->setStatusCode($options['status']); unset($options['status']); } if (isset($options['response'])) { $response = $options['response']; unset($options['response']); } else { $response = $this->response(); } return $this->application['spark.render_pipeline']->render($options, $response); } function request() { return $this->application['request']; } function response() { return $this->response; } function flash() { return $this->flash ?: $this->flash = $this->application['session']->getFlashBag(); } function session() { return $this->application['session']; } function application() { return $this->application; } function setApplication(Application $application) { $this->application = $application; } }
Add option 'response' to render
Add option 'response' to render
PHP
mit
sparkframework/spark
php
## Code Before: <?php namespace Spark\Controller; use Silex\Application; use Symfony\Component\HttpFoundation\Response; use Spark\Core\ApplicationAware; abstract class Base implements ApplicationAware { use ActionHelper\Filters; use ActionHelper\Redirect; use ActionHelper\Layout; protected $application; protected $response; protected $flash; function __construct() { $this->response = new Response; $this->setup(); } function setup() {} function render($options = []) { $attributes = $this->request()->attributes; if (!$options) { $options['script'] = $attributes->get('controller') . '/' . $attributes->get('action'); } if (isset($options['status'])) { $this->response()->setStatusCode($options['status']); unset($options['status']); } return $this->application['spark.render_pipeline']->render($options, $this->response()); } function request() { return $this->application['request']; } function response() { return $this->response; } function flash() { return $this->flash ?: $this->flash = $this->application['session']->getFlashBag(); } function session() { return $this->application['session']; } function application() { return $this->application; } function setApplication(Application $application) { $this->application = $application; } } ## Instruction: Add option 'response' to render ## Code After: <?php namespace Spark\Controller; use Silex\Application; use Symfony\Component\HttpFoundation\Response; use Spark\Core\ApplicationAware; abstract class Base implements ApplicationAware { use ActionHelper\Filters; use ActionHelper\Redirect; use ActionHelper\Layout; protected $application; protected $response; protected $flash; function __construct() { $this->response = new Response; $this->setup(); } function setup() {} function render($options = []) { $attributes = $this->request()->attributes; if (!$options) { $options['script'] = $attributes->get('controller') . '/' . $attributes->get('action'); } if (isset($options['status'])) { $this->response()->setStatusCode($options['status']); unset($options['status']); } if (isset($options['response'])) { $response = $options['response']; unset($options['response']); } else { $response = $this->response(); } return $this->application['spark.render_pipeline']->render($options, $response); } function request() { return $this->application['request']; } function response() { return $this->response; } function flash() { return $this->flash ?: $this->flash = $this->application['session']->getFlashBag(); } function session() { return $this->application['session']; } function application() { return $this->application; } function setApplication(Application $application) { $this->application = $application; } }
16faaa2413cbb9c88008b3d25e61f5c8bc1bfb6b
config/application.rb
config/application.rb
require File.expand_path('../boot', __FILE__) require 'rails/all' Bundler.require(*Rails.groups) Dotenv::Railtie.load module Horizon class Application < Rails::Application # middlewarezez unless ENV["DISABLE_RATE_LIMIT"] == "true" config.middleware.use Rack::Attack end config.middleware.insert_before 0, "Rack::Cors" do allow do origins '*' resource '*', :headers => :any, :methods => [:get, :post, :delete, :put, :options, :head, :patch] end end require "#{config.root}/lib/request_metrics" config.middleware.insert_before ActionDispatch::ShowExceptions, RequestMetrics, Metriks::Registry.default require "#{config.root}/lib/problem_renderer" config.exceptions_app = ProblemRenderer # custom configs config.stellard_url = ENV["STELLARD_URL"] raise "STELLARD_URL environment variable unset" if config.stellard_url.blank? # if ENV["CACHE_URL"].present? servers = ENV["CACHE_URL"].split(",") config.cache_store = Memcached::Rails.new(servers) else config.cache_store = :memory_store end config.autoload_paths << "#{config.root}/lib" config.autoload_paths << "#{config.root}/app/errors" config.autoload_paths << "#{config.root}/app/serializers" config.generators do |g| g.orm :active_record g.test_framework :rspec, fixture: false, views: false g.template_engine false g.stylesheets false g.javascripts false g.helper false end end end
require File.expand_path('../boot', __FILE__) require 'rails/all' Bundler.require(*Rails.groups) Dotenv::Railtie.load module Horizon class Application < Rails::Application require "#{config.root}/lib/request_metrics" config.middleware.insert_before ActionDispatch::ShowExceptions, RequestMetrics, Metriks::Registry.default require "#{config.root}/lib/problem_renderer" config.exceptions_app = ProblemRenderer # custom configs config.stellard_url = ENV["STELLARD_URL"] raise "STELLARD_URL environment variable unset" if config.stellard_url.blank? # if ENV["CACHE_URL"].present? servers = ENV["CACHE_URL"].split(",") config.cache_store = Memcached::Rails.new(servers) else config.cache_store = :memory_store end config.autoload_paths << "#{config.root}/lib" config.autoload_paths << "#{config.root}/app/errors" config.autoload_paths << "#{config.root}/app/serializers" config.generators do |g| g.orm :active_record g.test_framework :rspec, fixture: false, views: false g.template_engine false g.stylesheets false g.javascripts false g.helper false end end end
Remove middlewares that are not needed since go-horizon provides them
Remove middlewares that are not needed since go-horizon provides them
Ruby
apache-2.0
FredericHeem/horizon,stellar/horizon-importer,masonforest/horizon-importer,malandrina/horizon,matschaffer/horizon
ruby
## Code Before: require File.expand_path('../boot', __FILE__) require 'rails/all' Bundler.require(*Rails.groups) Dotenv::Railtie.load module Horizon class Application < Rails::Application # middlewarezez unless ENV["DISABLE_RATE_LIMIT"] == "true" config.middleware.use Rack::Attack end config.middleware.insert_before 0, "Rack::Cors" do allow do origins '*' resource '*', :headers => :any, :methods => [:get, :post, :delete, :put, :options, :head, :patch] end end require "#{config.root}/lib/request_metrics" config.middleware.insert_before ActionDispatch::ShowExceptions, RequestMetrics, Metriks::Registry.default require "#{config.root}/lib/problem_renderer" config.exceptions_app = ProblemRenderer # custom configs config.stellard_url = ENV["STELLARD_URL"] raise "STELLARD_URL environment variable unset" if config.stellard_url.blank? # if ENV["CACHE_URL"].present? servers = ENV["CACHE_URL"].split(",") config.cache_store = Memcached::Rails.new(servers) else config.cache_store = :memory_store end config.autoload_paths << "#{config.root}/lib" config.autoload_paths << "#{config.root}/app/errors" config.autoload_paths << "#{config.root}/app/serializers" config.generators do |g| g.orm :active_record g.test_framework :rspec, fixture: false, views: false g.template_engine false g.stylesheets false g.javascripts false g.helper false end end end ## Instruction: Remove middlewares that are not needed since go-horizon provides them ## Code After: require File.expand_path('../boot', __FILE__) require 'rails/all' Bundler.require(*Rails.groups) Dotenv::Railtie.load module Horizon class Application < Rails::Application require "#{config.root}/lib/request_metrics" config.middleware.insert_before ActionDispatch::ShowExceptions, RequestMetrics, Metriks::Registry.default require "#{config.root}/lib/problem_renderer" config.exceptions_app = ProblemRenderer # custom configs config.stellard_url = ENV["STELLARD_URL"] raise "STELLARD_URL environment variable unset" if config.stellard_url.blank? # if ENV["CACHE_URL"].present? servers = ENV["CACHE_URL"].split(",") config.cache_store = Memcached::Rails.new(servers) else config.cache_store = :memory_store end config.autoload_paths << "#{config.root}/lib" config.autoload_paths << "#{config.root}/app/errors" config.autoload_paths << "#{config.root}/app/serializers" config.generators do |g| g.orm :active_record g.test_framework :rspec, fixture: false, views: false g.template_engine false g.stylesheets false g.javascripts false g.helper false end end end
8b1b109193042a0411926739baf81f30c686dcb4
libhijack/arch/aarch64/hijack_machdep.h
libhijack/arch/aarch64/hijack_machdep.h
/* * Copyright (c) 2017, Shawn Webb * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef _HIJACK_MACHDEP #define _HIJACK_MACHDEP #define BASEADDR 0x00400000 #define SYSCALLSEARCH "\x0f\x05" #define MMAPSYSCALL 477 #endif /* !_HIJACK_MACHDEP */
/* * Copyright (c) 2017, Shawn Webb * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef _HIJACK_MACHDEP #define _HIJACK_MACHDEP #define BASEADDR 0x00400000 #define SYSCALLSEARCH "\x01\x00\x00\xd4" #define MMAPSYSCALL 477 #endif /* !_HIJACK_MACHDEP */
Use the right opcode for the svc instruction
Use the right opcode for the svc instruction This is a NOP on arm64 right now. Signed-off-by: Shawn Webb <63bc49e2baae731b3d1a43666c374487dee71f11@hardenedbsd.org>
C
bsd-2-clause
SoldierX/libhijack
c
## Code Before: /* * Copyright (c) 2017, Shawn Webb * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef _HIJACK_MACHDEP #define _HIJACK_MACHDEP #define BASEADDR 0x00400000 #define SYSCALLSEARCH "\x0f\x05" #define MMAPSYSCALL 477 #endif /* !_HIJACK_MACHDEP */ ## Instruction: Use the right opcode for the svc instruction This is a NOP on arm64 right now. Signed-off-by: Shawn Webb <63bc49e2baae731b3d1a43666c374487dee71f11@hardenedbsd.org> ## Code After: /* * Copyright (c) 2017, Shawn Webb * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef _HIJACK_MACHDEP #define _HIJACK_MACHDEP #define BASEADDR 0x00400000 #define SYSCALLSEARCH "\x01\x00\x00\xd4" #define MMAPSYSCALL 477 #endif /* !_HIJACK_MACHDEP */
fe35c1c3aed03cfd5332c78dd38423a726c71d93
src/main/ed/security/Security.java
src/main/ed/security/Security.java
// Security.java package ed.security; import ed.js.engine.*; public class Security { public final static boolean OFF = Boolean.getBoolean( "NO-SECURITY" ); final static boolean TEST_BYPASS = Boolean.getBoolean("ed.js.engine.SECURITY_BYPASS"); final static String SECURE[] = new String[]{ Convert.DEFAULT_PACKAGE + "._data_corejs_" , Convert.DEFAULT_PACKAGE + "._data_sites_admin_" , Convert.DEFAULT_PACKAGE + "._data_sites_www_" , Convert.DEFAULT_PACKAGE + ".lastline" }; public static boolean isCoreJS(){ if ( OFF ) return true; String topjs = getTopJS(); if ( topjs == null ) { return false; } if (TEST_BYPASS && _isTestFrameworkHack()) { return true; } for ( int i=0; i<SECURE.length; i++ ) if ( topjs.startsWith( SECURE[i] ) ) return true; return false; } static boolean _isTestFrameworkHack() { StackTraceElement[] st = Thread.currentThread().getStackTrace(); for(StackTraceElement e : st) { if ( e.getClassName().startsWith("ed.js.engine.JSTestInstance")) return true; } return false; } public static String getTopJS(){ StackTraceElement[] st = Thread.currentThread().getStackTrace(); for ( int i=0; i<st.length; i++ ){ StackTraceElement e = st[i]; if ( e.getClassName().startsWith( Convert.DEFAULT_PACKAGE + "." ) ) return e.getClassName(); } return null; } }
// Security.java package ed.security; import ed.js.engine.*; public class Security { public final static boolean OFF = Boolean.getBoolean( "NO-SECURITY" ); final static String SECURE[] = new String[]{ Convert.DEFAULT_PACKAGE + "._data_corejs_" , Convert.DEFAULT_PACKAGE + "._data_sites_admin_" , Convert.DEFAULT_PACKAGE + "._data_sites_www_" , Convert.DEFAULT_PACKAGE + ".lastline" }; public static boolean isCoreJS(){ if ( OFF ) return true; String topjs = getTopJS(); if ( topjs == null ) { return false; } for ( int i=0; i<SECURE.length; i++ ) if ( topjs.startsWith( SECURE[i] ) ) return true; return false; } public static String getTopJS(){ StackTraceElement[] st = Thread.currentThread().getStackTrace(); for ( int i=0; i<st.length; i++ ){ StackTraceElement e = st[i]; if ( e.getClassName().startsWith( Convert.DEFAULT_PACKAGE + "." ) ) return e.getClassName(); } return null; } }
Remove the security bypass hack. It's not needed anymore.
Remove the security bypass hack. It's not needed anymore.
Java
apache-2.0
babble/babble,babble/babble,babble/babble,babble/babble,babble/babble,babble/babble
java
## Code Before: // Security.java package ed.security; import ed.js.engine.*; public class Security { public final static boolean OFF = Boolean.getBoolean( "NO-SECURITY" ); final static boolean TEST_BYPASS = Boolean.getBoolean("ed.js.engine.SECURITY_BYPASS"); final static String SECURE[] = new String[]{ Convert.DEFAULT_PACKAGE + "._data_corejs_" , Convert.DEFAULT_PACKAGE + "._data_sites_admin_" , Convert.DEFAULT_PACKAGE + "._data_sites_www_" , Convert.DEFAULT_PACKAGE + ".lastline" }; public static boolean isCoreJS(){ if ( OFF ) return true; String topjs = getTopJS(); if ( topjs == null ) { return false; } if (TEST_BYPASS && _isTestFrameworkHack()) { return true; } for ( int i=0; i<SECURE.length; i++ ) if ( topjs.startsWith( SECURE[i] ) ) return true; return false; } static boolean _isTestFrameworkHack() { StackTraceElement[] st = Thread.currentThread().getStackTrace(); for(StackTraceElement e : st) { if ( e.getClassName().startsWith("ed.js.engine.JSTestInstance")) return true; } return false; } public static String getTopJS(){ StackTraceElement[] st = Thread.currentThread().getStackTrace(); for ( int i=0; i<st.length; i++ ){ StackTraceElement e = st[i]; if ( e.getClassName().startsWith( Convert.DEFAULT_PACKAGE + "." ) ) return e.getClassName(); } return null; } } ## Instruction: Remove the security bypass hack. It's not needed anymore. ## Code After: // Security.java package ed.security; import ed.js.engine.*; public class Security { public final static boolean OFF = Boolean.getBoolean( "NO-SECURITY" ); final static String SECURE[] = new String[]{ Convert.DEFAULT_PACKAGE + "._data_corejs_" , Convert.DEFAULT_PACKAGE + "._data_sites_admin_" , Convert.DEFAULT_PACKAGE + "._data_sites_www_" , Convert.DEFAULT_PACKAGE + ".lastline" }; public static boolean isCoreJS(){ if ( OFF ) return true; String topjs = getTopJS(); if ( topjs == null ) { return false; } for ( int i=0; i<SECURE.length; i++ ) if ( topjs.startsWith( SECURE[i] ) ) return true; return false; } public static String getTopJS(){ StackTraceElement[] st = Thread.currentThread().getStackTrace(); for ( int i=0; i<st.length; i++ ){ StackTraceElement e = st[i]; if ( e.getClassName().startsWith( Convert.DEFAULT_PACKAGE + "." ) ) return e.getClassName(); } return null; } }
5d29122a6316ff7722278e1c95d1de4df78fc2d2
week-5/calculate-mode/my_solution.rb
week-5/calculate-mode/my_solution.rb
=begin # Calculate the mode Pairing Challenge # I worked on this challenge [by myself, with: ] # I spent [] hours on this challenge. # Complete each step below according to the challenge directions and # include it in this file. Also make sure everything that isn't code # is commented. # 0. Pseudocode # What is the input? - an array of fixed numbers or strings # What is the output? (i.e. What should the code return?) - an array of the most frequent values # What are the steps needed to solve the problem? CREATE a most_frequent array and set it equal to the array argument # 1. Initial Solution =end def mode(array) histogram = Hash.new array.each do |item| histogram[item] = 0 end array.each do |item| histogram[item] += 1 end histogram.each do |key, val| puts "#{key}:#{val}" end #NOW I WANT TO MOVE THE KEY(S) WITH THE HIGHEST VALUE(S) INTO AN ARRAY #THEN I WANT TO RETURN THAT ARRAY end # mode([1,2,3,3,-2,"cat", "dog", "cat"]) mode(["who", "what", "where", "who"]) # 3. Refactored Solution =begin # 4. Reflection Which data structure did you and your pair decide to implement and why? Were you more successful breaking this problem down into implementable pseudocode than the last with a pair? What issues/successes did you run into when translating your pseudocode to code? What methods did you use to iterate through the content? Did you find any good ones when you were refactoring? Were they difficult to implement? =end
=begin # Calculate the mode Pairing Challenge # I worked on this challenge [with: Alan Alcesto] # I spent [] hours on this challenge. # Complete each step below according to the challenge directions and # include it in this file. Also make sure everything that isn't code # is commented. # 0. Pseudocode # What is the input? - an array of fixed numbers or strings # What is the output? (i.e. What should the code return?) - an array of the most frequent values # What are the steps needed to solve the problem? CREATE a most_frequent array and set it equal to the array argument # 1. Initial Solution =end def mode(array) end # 3. Refactored Solution =begin # 4. Reflection Which data structure did you and your pair decide to implement and why? Were you more successful breaking this problem down into implementable pseudocode than the last with a pair? What issues/successes did you run into when translating your pseudocode to code? What methods did you use to iterate through the content? Did you find any good ones when you were refactoring? Were they difficult to implement? =end
Add my initial pseudocode for 5.3
Add my initial pseudocode for 5.3
Ruby
mit
sheamunion/phase-0,sheamunion/phase-0,sheamunion/phase-0-unit-1,sheamunion/phase-0,sheamunion/phase-0-unit-1,sheamunion/phase-0,sheamunion/phase-0-unit-1,sheamunion/phase-0-unit-1
ruby
## Code Before: =begin # Calculate the mode Pairing Challenge # I worked on this challenge [by myself, with: ] # I spent [] hours on this challenge. # Complete each step below according to the challenge directions and # include it in this file. Also make sure everything that isn't code # is commented. # 0. Pseudocode # What is the input? - an array of fixed numbers or strings # What is the output? (i.e. What should the code return?) - an array of the most frequent values # What are the steps needed to solve the problem? CREATE a most_frequent array and set it equal to the array argument # 1. Initial Solution =end def mode(array) histogram = Hash.new array.each do |item| histogram[item] = 0 end array.each do |item| histogram[item] += 1 end histogram.each do |key, val| puts "#{key}:#{val}" end #NOW I WANT TO MOVE THE KEY(S) WITH THE HIGHEST VALUE(S) INTO AN ARRAY #THEN I WANT TO RETURN THAT ARRAY end # mode([1,2,3,3,-2,"cat", "dog", "cat"]) mode(["who", "what", "where", "who"]) # 3. Refactored Solution =begin # 4. Reflection Which data structure did you and your pair decide to implement and why? Were you more successful breaking this problem down into implementable pseudocode than the last with a pair? What issues/successes did you run into when translating your pseudocode to code? What methods did you use to iterate through the content? Did you find any good ones when you were refactoring? Were they difficult to implement? =end ## Instruction: Add my initial pseudocode for 5.3 ## Code After: =begin # Calculate the mode Pairing Challenge # I worked on this challenge [with: Alan Alcesto] # I spent [] hours on this challenge. # Complete each step below according to the challenge directions and # include it in this file. Also make sure everything that isn't code # is commented. # 0. Pseudocode # What is the input? - an array of fixed numbers or strings # What is the output? (i.e. What should the code return?) - an array of the most frequent values # What are the steps needed to solve the problem? CREATE a most_frequent array and set it equal to the array argument # 1. Initial Solution =end def mode(array) end # 3. Refactored Solution =begin # 4. Reflection Which data structure did you and your pair decide to implement and why? Were you more successful breaking this problem down into implementable pseudocode than the last with a pair? What issues/successes did you run into when translating your pseudocode to code? What methods did you use to iterate through the content? Did you find any good ones when you were refactoring? Were they difficult to implement? =end
c3a04018a280b0c7e852fbc41f7a7b582c37b70f
Example/Tests/Tests.swift
Example/Tests/Tests.swift
// https://github.com/Quick/Quick import Quick import Nimble import LoginKit class LoginKitSpec: QuickSpec { override func spec() { describe("testing travis ci"){ it("failure") { expect(2) == 1 } it("success") { expect(1) == 1 } } describe("LoginKitConfig"){ it("logoImage is an image"){ expect(LoginKitConfig.logoImage).to(beAnInstanceOf(UIImage)) } it("authType is JWT by default"){ expect(LoginKitConfig.authType) == AuthType.JWT } } describe("LoginController") { // it("save password ticked"){ // let loginController = LoginController() // expect(LoginService.storePassword) == false // loginController.savePasswordTapped() // expect(LoginService.storePassword) == true // } // // it("can read") { // expect("number") == "string" // } // // it("will eventually fail") { // expect("time").toEventually( equal("done") ) // } // // context("these will pass") { // // it("can do maths") { // expect(23) == 23 // } // // it("can read") { // expect("🐮") == "🐮" // } // // it("will eventually pass") { // var time = "passing" // // dispatch_async(dispatch_get_main_queue()) { // time = "done" // } // // waitUntil { done in // NSThread.sleepForTimeInterval(0.5) // expect(time) == "done" // // done() // } // } // } } } }
// https://github.com/Quick/Quick import Quick import Nimble @testable import LoginKit class LoginKitSpec: QuickSpec { override func spec() { describe("testing travis ci"){ it("failure") { expect(2) == 1 } it("success") { expect(1) == 1 } } describe("LoginKitConfig"){ it("logoImage is an image"){ expect(LoginKitConfig.logoImage).to(beAnInstanceOf(UIImage)) } it("authType is JWT by default"){ expect(LoginKitConfig.authType) == AuthType.JWT } } describe("LoginController") { it("saves password on tap"){ let lc = LoginController() let _ = lc.view expect(lc.savePasswordButton.selected) == false lc.savePasswordTapped() expect(lc.savePasswordButton.selected) == true } } } }
Improve tests for private methods testing
Improve tests for private methods testing
Swift
bsd-3-clause
TigerWolf/LoginKit,TigerWolf/LoginKit,TigerWolf/LoginKit
swift
## Code Before: // https://github.com/Quick/Quick import Quick import Nimble import LoginKit class LoginKitSpec: QuickSpec { override func spec() { describe("testing travis ci"){ it("failure") { expect(2) == 1 } it("success") { expect(1) == 1 } } describe("LoginKitConfig"){ it("logoImage is an image"){ expect(LoginKitConfig.logoImage).to(beAnInstanceOf(UIImage)) } it("authType is JWT by default"){ expect(LoginKitConfig.authType) == AuthType.JWT } } describe("LoginController") { // it("save password ticked"){ // let loginController = LoginController() // expect(LoginService.storePassword) == false // loginController.savePasswordTapped() // expect(LoginService.storePassword) == true // } // // it("can read") { // expect("number") == "string" // } // // it("will eventually fail") { // expect("time").toEventually( equal("done") ) // } // // context("these will pass") { // // it("can do maths") { // expect(23) == 23 // } // // it("can read") { // expect("🐮") == "🐮" // } // // it("will eventually pass") { // var time = "passing" // // dispatch_async(dispatch_get_main_queue()) { // time = "done" // } // // waitUntil { done in // NSThread.sleepForTimeInterval(0.5) // expect(time) == "done" // // done() // } // } // } } } } ## Instruction: Improve tests for private methods testing ## Code After: // https://github.com/Quick/Quick import Quick import Nimble @testable import LoginKit class LoginKitSpec: QuickSpec { override func spec() { describe("testing travis ci"){ it("failure") { expect(2) == 1 } it("success") { expect(1) == 1 } } describe("LoginKitConfig"){ it("logoImage is an image"){ expect(LoginKitConfig.logoImage).to(beAnInstanceOf(UIImage)) } it("authType is JWT by default"){ expect(LoginKitConfig.authType) == AuthType.JWT } } describe("LoginController") { it("saves password on tap"){ let lc = LoginController() let _ = lc.view expect(lc.savePasswordButton.selected) == false lc.savePasswordTapped() expect(lc.savePasswordButton.selected) == true } } } }
20f815c42f14c39a4182079ea5be995ec5b29e72
rocket-chat-android-widgets/src/main/java/chat/rocket/android/widget/RocketChatWidgets.java
rocket-chat-android-widgets/src/main/java/chat/rocket/android/widget/RocketChatWidgets.java
package chat.rocket.android.widget; import android.content.Context; import chat.rocket.android.widget.fresco.CustomImageFormatConfigurator; import com.facebook.common.logging.FLog; import com.facebook.drawee.backends.pipeline.DraweeConfig; import com.facebook.drawee.backends.pipeline.Fresco; import com.facebook.imagepipeline.backends.okhttp3.OkHttpImagePipelineConfigFactory; import com.facebook.imagepipeline.core.ImagePipelineConfig; import com.facebook.imagepipeline.listener.RequestListener; import com.facebook.imagepipeline.listener.RequestLoggingListener; import java.util.HashSet; import java.util.Set; import okhttp3.OkHttpClient; public class RocketChatWidgets { public static void initialize(Context context, OkHttpClient okHttpClient) { FLog.setMinimumLoggingLevel(FLog.VERBOSE); Set<RequestListener> listeners = new HashSet<>(); listeners.add(new RequestLoggingListener()); ImagePipelineConfig imagePipelineConfig = OkHttpImagePipelineConfigFactory .newBuilder(context, okHttpClient) .setRequestListeners(listeners) .setImageDecoderConfig(CustomImageFormatConfigurator.createImageDecoderConfig()) .setDownsampleEnabled(true) .experiment().setBitmapPrepareToDraw(true) .experiment().setPartialImageCachingEnabled(true) .build(); DraweeConfig.Builder draweeConfigBuilder = DraweeConfig.newBuilder(); CustomImageFormatConfigurator.addCustomDrawableFactories(draweeConfigBuilder); Fresco.initialize(context, imagePipelineConfig, draweeConfigBuilder.build()); FLog.setMinimumLoggingLevel(FLog.ERROR); } }
package chat.rocket.android.widget; import android.content.Context; import chat.rocket.android.widget.fresco.CustomImageFormatConfigurator; import com.facebook.common.logging.FLog; import com.facebook.drawee.backends.pipeline.DraweeConfig; import com.facebook.drawee.backends.pipeline.Fresco; import com.facebook.imagepipeline.backends.okhttp3.OkHttpImagePipelineConfigFactory; import com.facebook.imagepipeline.core.ImagePipelineConfig; import com.facebook.imagepipeline.listener.RequestListener; import com.facebook.imagepipeline.listener.RequestLoggingListener; import java.util.HashSet; import java.util.Set; import okhttp3.OkHttpClient; public class RocketChatWidgets { public static void initialize(Context context, OkHttpClient okHttpClient) { FLog.setMinimumLoggingLevel(FLog.VERBOSE); Set<RequestListener> listeners = new HashSet<>(); listeners.add(new RequestLoggingListener()); ImagePipelineConfig imagePipelineConfig = OkHttpImagePipelineConfigFactory .newBuilder(context, okHttpClient) .setRequestListeners(listeners) .setImageDecoderConfig(CustomImageFormatConfigurator.createImageDecoderConfig()) .setDownsampleEnabled(true) .experiment().setBitmapPrepareToDraw(true) .experiment().setPartialImageCachingEnabled(true) .build(); DraweeConfig.Builder draweeConfigBuilder = DraweeConfig.newBuilder(); CustomImageFormatConfigurator.addCustomDrawableFactories(draweeConfigBuilder); Fresco.initialize(context, imagePipelineConfig, draweeConfigBuilder.build()); } }
Set back Fresco logger to verbose
Set back Fresco logger to verbose
Java
mit
RocketChat/Rocket.Chat.Android.Lily,RocketChat/Rocket.Chat.Android,RocketChat/Rocket.Chat.Android.Lily,RocketChat/Rocket.Chat.Android
java
## Code Before: package chat.rocket.android.widget; import android.content.Context; import chat.rocket.android.widget.fresco.CustomImageFormatConfigurator; import com.facebook.common.logging.FLog; import com.facebook.drawee.backends.pipeline.DraweeConfig; import com.facebook.drawee.backends.pipeline.Fresco; import com.facebook.imagepipeline.backends.okhttp3.OkHttpImagePipelineConfigFactory; import com.facebook.imagepipeline.core.ImagePipelineConfig; import com.facebook.imagepipeline.listener.RequestListener; import com.facebook.imagepipeline.listener.RequestLoggingListener; import java.util.HashSet; import java.util.Set; import okhttp3.OkHttpClient; public class RocketChatWidgets { public static void initialize(Context context, OkHttpClient okHttpClient) { FLog.setMinimumLoggingLevel(FLog.VERBOSE); Set<RequestListener> listeners = new HashSet<>(); listeners.add(new RequestLoggingListener()); ImagePipelineConfig imagePipelineConfig = OkHttpImagePipelineConfigFactory .newBuilder(context, okHttpClient) .setRequestListeners(listeners) .setImageDecoderConfig(CustomImageFormatConfigurator.createImageDecoderConfig()) .setDownsampleEnabled(true) .experiment().setBitmapPrepareToDraw(true) .experiment().setPartialImageCachingEnabled(true) .build(); DraweeConfig.Builder draweeConfigBuilder = DraweeConfig.newBuilder(); CustomImageFormatConfigurator.addCustomDrawableFactories(draweeConfigBuilder); Fresco.initialize(context, imagePipelineConfig, draweeConfigBuilder.build()); FLog.setMinimumLoggingLevel(FLog.ERROR); } } ## Instruction: Set back Fresco logger to verbose ## Code After: package chat.rocket.android.widget; import android.content.Context; import chat.rocket.android.widget.fresco.CustomImageFormatConfigurator; import com.facebook.common.logging.FLog; import com.facebook.drawee.backends.pipeline.DraweeConfig; import com.facebook.drawee.backends.pipeline.Fresco; import com.facebook.imagepipeline.backends.okhttp3.OkHttpImagePipelineConfigFactory; import com.facebook.imagepipeline.core.ImagePipelineConfig; import com.facebook.imagepipeline.listener.RequestListener; import com.facebook.imagepipeline.listener.RequestLoggingListener; import java.util.HashSet; import java.util.Set; import okhttp3.OkHttpClient; public class RocketChatWidgets { public static void initialize(Context context, OkHttpClient okHttpClient) { FLog.setMinimumLoggingLevel(FLog.VERBOSE); Set<RequestListener> listeners = new HashSet<>(); listeners.add(new RequestLoggingListener()); ImagePipelineConfig imagePipelineConfig = OkHttpImagePipelineConfigFactory .newBuilder(context, okHttpClient) .setRequestListeners(listeners) .setImageDecoderConfig(CustomImageFormatConfigurator.createImageDecoderConfig()) .setDownsampleEnabled(true) .experiment().setBitmapPrepareToDraw(true) .experiment().setPartialImageCachingEnabled(true) .build(); DraweeConfig.Builder draweeConfigBuilder = DraweeConfig.newBuilder(); CustomImageFormatConfigurator.addCustomDrawableFactories(draweeConfigBuilder); Fresco.initialize(context, imagePipelineConfig, draweeConfigBuilder.build()); } }
7aa89902f8af2ca1f4b3c9e356a62062cc74696b
bot/anime_searcher.py
bot/anime_searcher.py
from itertools import chain from typing import Iterable from minoshiro import Medium, Minoshiro, Site from minoshiro.helpers import get_synonyms class AnimeSearcher(Minoshiro): async def get(self, query: str, medium: Medium, sites: Iterable[Site] = None, *, timeout=3): sites = sites if sites else list(Site) cached_data, cached_id = await self.__get_cached(query, medium) to_be_cached = {} names = [] return_val = {} for site in sites: res, id_ = await self.__get_result( cached_data, cached_id, query, names, site, medium, timeout ) if res: return_val[site] = res for title in get_synonyms(res, site): names.append(title) if id_: to_be_cached[site] = id_ return return_val, to_be_cached, names, medium async def cache(self, to_be_cached, names, medium): """ Cache search results into the db. :param to_be_cached: items to be cached. :param names: all names for the item. :param medium: the medium type. """ itere = set(chain(*names)) for site, id_ in to_be_cached.items(): await self.cache_one(site, id_, medium, itere) async def cache_one(self, site, id_, medium, iterator): """ Cache one id. :param site: the site. :param id_: the id. :param medium: the medium type. :param iterator: an iterator for all names. """ for name in iterator: if name: await self.db_controller.set_identifier( name, medium, site, id_ )
from typing import Iterable from minoshiro import Medium, Minoshiro, Site from minoshiro.helpers import get_synonyms class AnimeSearcher(Minoshiro): async def get(self, query: str, medium: Medium, sites: Iterable[Site] = None, *, timeout=3): sites = sites if sites else list(Site) cached_data, cached_id = await self._get_cached(query, medium) to_be_cached = {} names = [] return_val = {} for site in sites: res, id_ = await self._get_result( cached_data, cached_id, query, names, site, medium, timeout ) if res: return_val[site] = res for title in get_synonyms(res, site): names.append(title) if id_: to_be_cached[site] = id_ return return_val, to_be_cached, names, medium async def cache(self, to_be_cached, names, medium): await super()._cache(to_be_cached, names, medium)
Update anime searcher implementation to use super class methods
Update anime searcher implementation to use super class methods
Python
apache-2.0
MaT1g3R/YasenBaka
python
## Code Before: from itertools import chain from typing import Iterable from minoshiro import Medium, Minoshiro, Site from minoshiro.helpers import get_synonyms class AnimeSearcher(Minoshiro): async def get(self, query: str, medium: Medium, sites: Iterable[Site] = None, *, timeout=3): sites = sites if sites else list(Site) cached_data, cached_id = await self.__get_cached(query, medium) to_be_cached = {} names = [] return_val = {} for site in sites: res, id_ = await self.__get_result( cached_data, cached_id, query, names, site, medium, timeout ) if res: return_val[site] = res for title in get_synonyms(res, site): names.append(title) if id_: to_be_cached[site] = id_ return return_val, to_be_cached, names, medium async def cache(self, to_be_cached, names, medium): """ Cache search results into the db. :param to_be_cached: items to be cached. :param names: all names for the item. :param medium: the medium type. """ itere = set(chain(*names)) for site, id_ in to_be_cached.items(): await self.cache_one(site, id_, medium, itere) async def cache_one(self, site, id_, medium, iterator): """ Cache one id. :param site: the site. :param id_: the id. :param medium: the medium type. :param iterator: an iterator for all names. """ for name in iterator: if name: await self.db_controller.set_identifier( name, medium, site, id_ ) ## Instruction: Update anime searcher implementation to use super class methods ## Code After: from typing import Iterable from minoshiro import Medium, Minoshiro, Site from minoshiro.helpers import get_synonyms class AnimeSearcher(Minoshiro): async def get(self, query: str, medium: Medium, sites: Iterable[Site] = None, *, timeout=3): sites = sites if sites else list(Site) cached_data, cached_id = await self._get_cached(query, medium) to_be_cached = {} names = [] return_val = {} for site in sites: res, id_ = await self._get_result( cached_data, cached_id, query, names, site, medium, timeout ) if res: return_val[site] = res for title in get_synonyms(res, site): names.append(title) if id_: to_be_cached[site] = id_ return return_val, to_be_cached, names, medium async def cache(self, to_be_cached, names, medium): await super()._cache(to_be_cached, names, medium)
83ceca04758c6546c41d5bc7f96583d838f25e11
src/mmw/apps/user/backends.py
src/mmw/apps/user/backends.py
from django.core.exceptions import ObjectDoesNotExist from django.contrib.auth.backends import BaseBackend from django.contrib.auth.models import User from apps.user.models import ItsiUser, ConcordUser class SSOAuthenticationBackend(BaseBackend): """ A custom authentication back-end for Single Sign On providers. Before we can call django.contrib.auth.login on an SSO user, we must first authenticate them. This must be done using a custom authentication back- end, which sets the backend attribute on the user model. This class should be instantiated with an SSO provider user model, such as ItsiUser or ConcordUser, before it can be used. """ def __init__(self, model, field): self.SSOUserModel = model self.SSOField = field def authenticate(self, sso_id=None): if sso_id is not None: try: query = {self.SSOField: sso_id} user = self.SSOUserModel.objects.get(**query).user return user except ObjectDoesNotExist: return None return None def get_user(self, user_id): try: return User.objects.get(pk=user_id) except User.DoesNotExist: return None class ItsiAuthenticationBackend(SSOAuthenticationBackend): def __init__(self): super(ItsiAuthenticationBackend, self).__init__( ItsiUser, 'itsi_id') class ConcordAuthenticationBackend(SSOAuthenticationBackend): def __init__(self): super(ConcordAuthenticationBackend, self).__init__( ConcordUser, 'concord_id')
from django.core.exceptions import ObjectDoesNotExist from django.contrib.auth.backends import BaseBackend from django.contrib.auth.models import User from apps.user.models import ItsiUser, ConcordUser class SSOAuthenticationBackend(BaseBackend): """ A custom authentication back-end for Single Sign On providers. Before we can call django.contrib.auth.login on an SSO user, we must first authenticate them. This must be done using a custom authentication back- end, which sets the backend attribute on the user model. This class should be instantiated with an SSO provider user model, such as ItsiUser or ConcordUser, before it can be used. """ def __init__(self, model, field): self.SSOUserModel = model self.SSOField = field def authenticate(self, request=None, sso_id=None): if sso_id is not None: try: query = {self.SSOField: sso_id} user = self.SSOUserModel.objects.get(**query).user return user except ObjectDoesNotExist: return None return None def get_user(self, user_id): try: return User.objects.get(pk=user_id) except User.DoesNotExist: return None class ItsiAuthenticationBackend(SSOAuthenticationBackend): def __init__(self): super(ItsiAuthenticationBackend, self).__init__( ItsiUser, 'itsi_id') class ConcordAuthenticationBackend(SSOAuthenticationBackend): def __init__(self): super(ConcordAuthenticationBackend, self).__init__( ConcordUser, 'concord_id')
Add request parameter to backend.authenticate
Add request parameter to backend.authenticate Without this, the signature of our custom backend does not match that of the function call. This signature is tested in django.contrib.auth.authenticate here: https://github.com/django/django/blob/fdf209eab8949ddc345aa0212b349c79fc6fdebb/django/contrib/auth/__init__.py#L69 and `request` was added to that signature in Django 1.11 in https://github.com/django/django/commit/4b9330ccc04575f9e5126529ec355a450d12e77c. With this, the Concord users are authenticated correctly.
Python
apache-2.0
WikiWatershed/model-my-watershed,WikiWatershed/model-my-watershed,WikiWatershed/model-my-watershed,WikiWatershed/model-my-watershed,WikiWatershed/model-my-watershed
python
## Code Before: from django.core.exceptions import ObjectDoesNotExist from django.contrib.auth.backends import BaseBackend from django.contrib.auth.models import User from apps.user.models import ItsiUser, ConcordUser class SSOAuthenticationBackend(BaseBackend): """ A custom authentication back-end for Single Sign On providers. Before we can call django.contrib.auth.login on an SSO user, we must first authenticate them. This must be done using a custom authentication back- end, which sets the backend attribute on the user model. This class should be instantiated with an SSO provider user model, such as ItsiUser or ConcordUser, before it can be used. """ def __init__(self, model, field): self.SSOUserModel = model self.SSOField = field def authenticate(self, sso_id=None): if sso_id is not None: try: query = {self.SSOField: sso_id} user = self.SSOUserModel.objects.get(**query).user return user except ObjectDoesNotExist: return None return None def get_user(self, user_id): try: return User.objects.get(pk=user_id) except User.DoesNotExist: return None class ItsiAuthenticationBackend(SSOAuthenticationBackend): def __init__(self): super(ItsiAuthenticationBackend, self).__init__( ItsiUser, 'itsi_id') class ConcordAuthenticationBackend(SSOAuthenticationBackend): def __init__(self): super(ConcordAuthenticationBackend, self).__init__( ConcordUser, 'concord_id') ## Instruction: Add request parameter to backend.authenticate Without this, the signature of our custom backend does not match that of the function call. This signature is tested in django.contrib.auth.authenticate here: https://github.com/django/django/blob/fdf209eab8949ddc345aa0212b349c79fc6fdebb/django/contrib/auth/__init__.py#L69 and `request` was added to that signature in Django 1.11 in https://github.com/django/django/commit/4b9330ccc04575f9e5126529ec355a450d12e77c. With this, the Concord users are authenticated correctly. ## Code After: from django.core.exceptions import ObjectDoesNotExist from django.contrib.auth.backends import BaseBackend from django.contrib.auth.models import User from apps.user.models import ItsiUser, ConcordUser class SSOAuthenticationBackend(BaseBackend): """ A custom authentication back-end for Single Sign On providers. Before we can call django.contrib.auth.login on an SSO user, we must first authenticate them. This must be done using a custom authentication back- end, which sets the backend attribute on the user model. This class should be instantiated with an SSO provider user model, such as ItsiUser or ConcordUser, before it can be used. """ def __init__(self, model, field): self.SSOUserModel = model self.SSOField = field def authenticate(self, request=None, sso_id=None): if sso_id is not None: try: query = {self.SSOField: sso_id} user = self.SSOUserModel.objects.get(**query).user return user except ObjectDoesNotExist: return None return None def get_user(self, user_id): try: return User.objects.get(pk=user_id) except User.DoesNotExist: return None class ItsiAuthenticationBackend(SSOAuthenticationBackend): def __init__(self): super(ItsiAuthenticationBackend, self).__init__( ItsiUser, 'itsi_id') class ConcordAuthenticationBackend(SSOAuthenticationBackend): def __init__(self): super(ConcordAuthenticationBackend, self).__init__( ConcordUser, 'concord_id')
b311626d133211e9ca29bd32470fe74e06db71dd
app/htdocs/js/Paste/new.js
app/htdocs/js/Paste/new.js
$(function(){ $('ul.radio-optiongroups').each(function(){ var $list = $(this), $select = $('<select />', {'class': 'hg'}); $list .children('li.field').children('label').find('input[type="radio"]') .each(function(){ var $radio = $(this), $label = $radio.closest('label'); $select .append( $('<option />', { 'text': $label.text(), 'value': $radio.val() }) .data({ 'radio': $radio, 'suboptions': $radio.closest('li.field') }) ); if ($radio.is(':checked')) { $select.val($radio.val()); } $label .hide() .insertBefore($list); }); $select .appendTo($list.closest('fieldset').find('legend:first').html('')) .change(function(){ $(this).find(':selected').data('suboptions') .siblings(':visible') .slideUp() .end() .slideDown(); }) .find(':selected').data('suboptions') .siblings() .hide() .end() .show(); }); });
$(function(){ $('.holoform .field_error').live('click', function(e){ $('.field.recently-focused') .removeClass('recently-focused'); $(this) .closest('.field') .addClass('recently-focused'); }); $('ul.radio-optiongroups').each(function(){ var $list = $(this), $select = $('<select />', {'class': 'hg'}); $list .children('li.field').children('label').find('input[type="radio"]') .each(function(){ var $radio = $(this), $label = $radio.closest('label'); $select .append( $('<option />', { 'text': $label.text(), 'value': $radio.val() }) .data({ 'radio': $radio, 'suboptions': $radio.closest('li.field') }) ); if ($radio.is(':checked')) { $select.val($radio.val()); } $label .hide() .insertBefore($list); }); $select .appendTo($list.closest('fieldset').find('legend:first').html('')) .change(function(){ $(this).find(':selected').data('suboptions') .siblings(':visible') .slideUp() .end() .slideDown(); }) .find(':selected').data('suboptions') .siblings() .hide() .end() .show(); }); });
Bring error message to the top, when clicked.
Bring error message to the top, when clicked.
JavaScript
mit
marek-saji/nyopaste,marek-saji/nyopaste
javascript
## Code Before: $(function(){ $('ul.radio-optiongroups').each(function(){ var $list = $(this), $select = $('<select />', {'class': 'hg'}); $list .children('li.field').children('label').find('input[type="radio"]') .each(function(){ var $radio = $(this), $label = $radio.closest('label'); $select .append( $('<option />', { 'text': $label.text(), 'value': $radio.val() }) .data({ 'radio': $radio, 'suboptions': $radio.closest('li.field') }) ); if ($radio.is(':checked')) { $select.val($radio.val()); } $label .hide() .insertBefore($list); }); $select .appendTo($list.closest('fieldset').find('legend:first').html('')) .change(function(){ $(this).find(':selected').data('suboptions') .siblings(':visible') .slideUp() .end() .slideDown(); }) .find(':selected').data('suboptions') .siblings() .hide() .end() .show(); }); }); ## Instruction: Bring error message to the top, when clicked. ## Code After: $(function(){ $('.holoform .field_error').live('click', function(e){ $('.field.recently-focused') .removeClass('recently-focused'); $(this) .closest('.field') .addClass('recently-focused'); }); $('ul.radio-optiongroups').each(function(){ var $list = $(this), $select = $('<select />', {'class': 'hg'}); $list .children('li.field').children('label').find('input[type="radio"]') .each(function(){ var $radio = $(this), $label = $radio.closest('label'); $select .append( $('<option />', { 'text': $label.text(), 'value': $radio.val() }) .data({ 'radio': $radio, 'suboptions': $radio.closest('li.field') }) ); if ($radio.is(':checked')) { $select.val($radio.val()); } $label .hide() .insertBefore($list); }); $select .appendTo($list.closest('fieldset').find('legend:first').html('')) .change(function(){ $(this).find(':selected').data('suboptions') .siblings(':visible') .slideUp() .end() .slideDown(); }) .find(':selected').data('suboptions') .siblings() .hide() .end() .show(); }); });
1717a4b4c82cf04832d532ef14c846b7c800c80e
src/lib/objectionPlugins/timestamps.js
src/lib/objectionPlugins/timestamps.js
'use strict'; // Exports export default (BaseModel) => { class Model extends BaseModel { $toDatabaseJson() { const omit = this.constructor.getRelations(); return this.$$toJson(true, omit, null); } $beforeValidate(jsonSchema, json, opt) { const schema = super.$beforeValidate(jsonSchema, json, opt); if (this.constructor.timestamps && schema && schema.properties) { if (this.constructor.camelCase) { jsonSchema.properties.createdAt = jsonSchema.properties.updatedAt = { type: 'string', format: 'date-time' }; } else { jsonSchema.properties.created_at = jsonSchema.properties.updated_at = { type: 'string', format: 'date-time' }; } } return schema; } $beforeInsert(...args) { if (this.constructor.timestamps) { const datetime = new Date().toISOString(); if (this.constructor.camelCase) { this.createdAt = datetime; this.updatedAt = datetime; } else { this.created_at = datetime; this.updated_at = datetime; } } return super.$beforeInsert(...args); } $beforeUpdate(...args) { if (this.constructor.timestamps) { const datetime = new Date().toISOString(); if (this.constructor.camelCase) this.updatedAt = datetime; else this.updated_at = datetime; } return super.$beforeUpdate(...args); } } return Model; };
'use strict'; // Exports export default (BaseModel) => { class Model extends BaseModel { $toDatabaseJson() { const jsonSchema = this.constructor.jsonSchema; const pick = jsonSchema && jsonSchema.properties; let omit; if (!pick) { omit = this.constructor.getRelations(); } else { if (this.constructor.camelCase) { pick.createdAt = pick.updatedAt = { type: 'string', format: 'date-time' }; } else { pick.created_at = pick.updated_at = { type: 'string', format: 'date-time' }; } } return this.$$toJson(true, omit, pick); } $beforeInsert(...args) { if (this.constructor.timestamps) { const datetime = new Date().toISOString(); if (this.constructor.camelCase) { this.createdAt = datetime; this.updatedAt = datetime; } else { this.created_at = datetime; this.updated_at = datetime; } } return super.$beforeInsert(...args); } $beforeUpdate(...args) { if (this.constructor.timestamps) { const datetime = new Date().toISOString(); if (this.constructor.camelCase) this.updatedAt = datetime; else this.updated_at = datetime; } return super.$beforeUpdate(...args); } } return Model; };
Fix bug where additional properties in objection models were not be omitted
Fix bug where additional properties in objection models were not be omitted
JavaScript
mit
komapijs/komapi,komapijs/komapi
javascript
## Code Before: 'use strict'; // Exports export default (BaseModel) => { class Model extends BaseModel { $toDatabaseJson() { const omit = this.constructor.getRelations(); return this.$$toJson(true, omit, null); } $beforeValidate(jsonSchema, json, opt) { const schema = super.$beforeValidate(jsonSchema, json, opt); if (this.constructor.timestamps && schema && schema.properties) { if (this.constructor.camelCase) { jsonSchema.properties.createdAt = jsonSchema.properties.updatedAt = { type: 'string', format: 'date-time' }; } else { jsonSchema.properties.created_at = jsonSchema.properties.updated_at = { type: 'string', format: 'date-time' }; } } return schema; } $beforeInsert(...args) { if (this.constructor.timestamps) { const datetime = new Date().toISOString(); if (this.constructor.camelCase) { this.createdAt = datetime; this.updatedAt = datetime; } else { this.created_at = datetime; this.updated_at = datetime; } } return super.$beforeInsert(...args); } $beforeUpdate(...args) { if (this.constructor.timestamps) { const datetime = new Date().toISOString(); if (this.constructor.camelCase) this.updatedAt = datetime; else this.updated_at = datetime; } return super.$beforeUpdate(...args); } } return Model; }; ## Instruction: Fix bug where additional properties in objection models were not be omitted ## Code After: 'use strict'; // Exports export default (BaseModel) => { class Model extends BaseModel { $toDatabaseJson() { const jsonSchema = this.constructor.jsonSchema; const pick = jsonSchema && jsonSchema.properties; let omit; if (!pick) { omit = this.constructor.getRelations(); } else { if (this.constructor.camelCase) { pick.createdAt = pick.updatedAt = { type: 'string', format: 'date-time' }; } else { pick.created_at = pick.updated_at = { type: 'string', format: 'date-time' }; } } return this.$$toJson(true, omit, pick); } $beforeInsert(...args) { if (this.constructor.timestamps) { const datetime = new Date().toISOString(); if (this.constructor.camelCase) { this.createdAt = datetime; this.updatedAt = datetime; } else { this.created_at = datetime; this.updated_at = datetime; } } return super.$beforeInsert(...args); } $beforeUpdate(...args) { if (this.constructor.timestamps) { const datetime = new Date().toISOString(); if (this.constructor.camelCase) this.updatedAt = datetime; else this.updated_at = datetime; } return super.$beforeUpdate(...args); } } return Model; };
0294f0b2b86431298f09b22966c27743dfb82728
tests/functional/helloworld.js
tests/functional/helloworld.js
define([ "intern!object", "intern/chai!assert", "require", "tests/support/helper" ], function ( registerSuite, assert, require, testHelper ) { var signIn = testHelper.getAppUrl( "admin/signin" ); var mainPage = testHelper.getAppUrl( "" ); registerSuite({ name: "Main page.", /** Check if link to profile configuration is added. */ "Main page is loading.": function () { return this.remote .get( mainPage ) .setFindTimeout( 1000 ) /** Check if $panel property is null at first. */ .execute( function () { document.getElementsByTagName( "table" )[ 0 ].style.width = "500px"; }); // .setFindTimeout( 3000 ) // /** Open panel by clicking entry. */ // .findByCssSelector( "body.application" ) // .isDisplayed() // .then( function ( visible ) { // assert.ok( visible, "Sign in form loaded." ); // }); } }); registerSuite({ name: "Admin auth.", /** Check if link to profile configuration is added. */ "Panel is loading.": function () { return this.remote .get( signIn ) .setFindTimeout( 3000 ) /** Open panel by clicking entry. */ .findByCssSelector( "div.admin-auth" ) .isDisplayed() .then( function ( visible ) { assert.ok( visible, "Sign in form loaded." ); }); } }); });
define([ "intern!object", "intern/chai!assert", "require", "tests/support/helper" ], function ( registerSuite, assert, require, testHelper ) { var signIn = testHelper.getAppUrl( "admin/signin" ); var mainPage = testHelper.getAppUrl( "" ); registerSuite({ name: "Main page.", "Main page is loading.": function () { return this.remote .get( mainPage ) .setExecuteAsyncTimeout( 10000 ) .executeAsync( function () { window.scrollTo( 1000, 0 ); }); // .setFindTimeout( 3000 ) // .findByCssSelector( "body.application" ) // .isDisplayed() // .then( function ( visible ) { // assert.ok( visible, "Sign in form loaded." ); // }); } }); return; registerSuite({ name: "Admin auth.", "Panel is loading.": function () { return this.remote .get( signIn ) .setFindTimeout( 3000 ) .findByCssSelector( "div.admin-auth" ) .isDisplayed() .then( function ( visible ) { assert.ok( visible, "Sign in form loaded." ); }); } }); });
Bring ZF2 error into view
Bring ZF2 error into view
JavaScript
mit
cezarykluczynski/ComicCMS2,cezarykluczynski/ComicCMS2,cezarykluczynski/ComicCMS2
javascript
## Code Before: define([ "intern!object", "intern/chai!assert", "require", "tests/support/helper" ], function ( registerSuite, assert, require, testHelper ) { var signIn = testHelper.getAppUrl( "admin/signin" ); var mainPage = testHelper.getAppUrl( "" ); registerSuite({ name: "Main page.", /** Check if link to profile configuration is added. */ "Main page is loading.": function () { return this.remote .get( mainPage ) .setFindTimeout( 1000 ) /** Check if $panel property is null at first. */ .execute( function () { document.getElementsByTagName( "table" )[ 0 ].style.width = "500px"; }); // .setFindTimeout( 3000 ) // /** Open panel by clicking entry. */ // .findByCssSelector( "body.application" ) // .isDisplayed() // .then( function ( visible ) { // assert.ok( visible, "Sign in form loaded." ); // }); } }); registerSuite({ name: "Admin auth.", /** Check if link to profile configuration is added. */ "Panel is loading.": function () { return this.remote .get( signIn ) .setFindTimeout( 3000 ) /** Open panel by clicking entry. */ .findByCssSelector( "div.admin-auth" ) .isDisplayed() .then( function ( visible ) { assert.ok( visible, "Sign in form loaded." ); }); } }); }); ## Instruction: Bring ZF2 error into view ## Code After: define([ "intern!object", "intern/chai!assert", "require", "tests/support/helper" ], function ( registerSuite, assert, require, testHelper ) { var signIn = testHelper.getAppUrl( "admin/signin" ); var mainPage = testHelper.getAppUrl( "" ); registerSuite({ name: "Main page.", "Main page is loading.": function () { return this.remote .get( mainPage ) .setExecuteAsyncTimeout( 10000 ) .executeAsync( function () { window.scrollTo( 1000, 0 ); }); // .setFindTimeout( 3000 ) // .findByCssSelector( "body.application" ) // .isDisplayed() // .then( function ( visible ) { // assert.ok( visible, "Sign in form loaded." ); // }); } }); return; registerSuite({ name: "Admin auth.", "Panel is loading.": function () { return this.remote .get( signIn ) .setFindTimeout( 3000 ) .findByCssSelector( "div.admin-auth" ) .isDisplayed() .then( function ( visible ) { assert.ok( visible, "Sign in form loaded." ); }); } }); });
c82dee5e7aa8ced12906875b7f44ff7b7671eacb
telegram-bot-api/src/main/kotlin/com/github/telegram/domain/Update.kt
telegram-bot-api/src/main/kotlin/com/github/telegram/domain/Update.kt
package com.github.telegram.domain import com.google.gson.annotations.SerializedName as Name /** * This object represents an incoming update. * Only *one* of the optional parameters can be present in any given update. * * @property updateId The update‘s unique identifier. * Update identifiers start from a certain positive number and increase sequentially. * @property message New incoming message of any kind — text, photo, sticker, etc. * @property editedMessage New version of a message that is known to the bot and was edited. * @property inlineQuery New incoming inline query. * @property chosenInlineResult The result of an inline query that was chosen by a user and sent to their chat partner. * @property callbackQuery New incoming callback query. */ data class Update( @Name("update_id") val updateId: Long, @Name("message") val message: Message?, @Name("edited_message") val editedMessage: Message?, @Name("inline_query") val inlineQuery: InlineQuery?, @Name("chosen_inline_result") val chosenInlineResult: ChosenInlineResult?, @Name("callback_query") val callbackQuery: CallbackQuery?) { val senderId: Long get() { return when { message != null -> message.chat.id editedMessage != null -> editedMessage.chat.id inlineQuery != null -> inlineQuery.from.id chosenInlineResult != null -> chosenInlineResult.from.id callbackQuery != null -> callbackQuery.from.id else -> throw IllegalStateException("Everything is null.") } } }
package com.github.telegram.domain import com.google.gson.annotations.SerializedName as Name /** * This object represents an incoming update. * Only *one* of the optional parameters can be present in any given update. * * @property updateId The update‘s unique identifier. * Update identifiers start from a certain positive number and increase sequentially. * @property message New incoming message of any kind — text, photo, sticker, etc. * @property editedMessage New version of a message that is known to the bot and was edited. * @property inlineQuery New incoming inline query. * @property chosenInlineResult The result of an inline query that was chosen by a user and sent to their chat partner. * @property callbackQuery New incoming callback query. */ data class Update( @Name("update_id") val updateId: Long, @Name("message") val message: Message?, @Name("edited_message") val editedMessage: Message?, @Name("inline_query") val inlineQuery: InlineQuery?, @Name("chosen_inline_result") val chosenInlineResult: ChosenInlineResult?, @Name("callback_query") val callbackQuery: CallbackQuery?) { val senderId: Long get() { return when { message != null -> message.chat.id editedMessage != null -> editedMessage.chat.id inlineQuery != null -> inlineQuery.from.id chosenInlineResult != null -> chosenInlineResult.from.id callbackQuery != null -> callbackQuery.from.id else -> throw IllegalStateException("Cannot evaluate sender for update: $this") } } }
Add more detailed exception message.
Add more detailed exception message.
Kotlin
mit
denzelby/telegram-bot-bumblebee,fare1990/telegram-bot-bumblebee,fare1990/telegram-bot-bumblebee,fare1990/telegram-bot-bumblebee
kotlin
## Code Before: package com.github.telegram.domain import com.google.gson.annotations.SerializedName as Name /** * This object represents an incoming update. * Only *one* of the optional parameters can be present in any given update. * * @property updateId The update‘s unique identifier. * Update identifiers start from a certain positive number and increase sequentially. * @property message New incoming message of any kind — text, photo, sticker, etc. * @property editedMessage New version of a message that is known to the bot and was edited. * @property inlineQuery New incoming inline query. * @property chosenInlineResult The result of an inline query that was chosen by a user and sent to their chat partner. * @property callbackQuery New incoming callback query. */ data class Update( @Name("update_id") val updateId: Long, @Name("message") val message: Message?, @Name("edited_message") val editedMessage: Message?, @Name("inline_query") val inlineQuery: InlineQuery?, @Name("chosen_inline_result") val chosenInlineResult: ChosenInlineResult?, @Name("callback_query") val callbackQuery: CallbackQuery?) { val senderId: Long get() { return when { message != null -> message.chat.id editedMessage != null -> editedMessage.chat.id inlineQuery != null -> inlineQuery.from.id chosenInlineResult != null -> chosenInlineResult.from.id callbackQuery != null -> callbackQuery.from.id else -> throw IllegalStateException("Everything is null.") } } } ## Instruction: Add more detailed exception message. ## Code After: package com.github.telegram.domain import com.google.gson.annotations.SerializedName as Name /** * This object represents an incoming update. * Only *one* of the optional parameters can be present in any given update. * * @property updateId The update‘s unique identifier. * Update identifiers start from a certain positive number and increase sequentially. * @property message New incoming message of any kind — text, photo, sticker, etc. * @property editedMessage New version of a message that is known to the bot and was edited. * @property inlineQuery New incoming inline query. * @property chosenInlineResult The result of an inline query that was chosen by a user and sent to their chat partner. * @property callbackQuery New incoming callback query. */ data class Update( @Name("update_id") val updateId: Long, @Name("message") val message: Message?, @Name("edited_message") val editedMessage: Message?, @Name("inline_query") val inlineQuery: InlineQuery?, @Name("chosen_inline_result") val chosenInlineResult: ChosenInlineResult?, @Name("callback_query") val callbackQuery: CallbackQuery?) { val senderId: Long get() { return when { message != null -> message.chat.id editedMessage != null -> editedMessage.chat.id inlineQuery != null -> inlineQuery.from.id chosenInlineResult != null -> chosenInlineResult.from.id callbackQuery != null -> callbackQuery.from.id else -> throw IllegalStateException("Cannot evaluate sender for update: $this") } } }
a4e5dad36c7d87cc6a7b1482440ee5a69734f535
lib/assets/javascripts/new-dashboard/store/notifications/index.js
lib/assets/javascripts/new-dashboard/store/notifications/index.js
const notifications = { namespaced: true, state: { isFetching: false, isErrored: false, error: [], notifications: [] }, computed: {}, getters: {}, mutations: { setNotifications (state, notifications) { state.notifications = notifications; state.isFetching = false; state.isErrored = false; state.error = []; }, setRequestError (state, error) { state.isFetching = false; state.isErrored = true; state.error = error; state.notifications = []; }, setFetchingState (state) { state.isFetching = true; state.isErrored = false; state.error = []; state.notifications = []; } }, actions: { fetchNotifications (context, options) { context.commit('setFetchingState'); context.rootState.client.getConfig(function (err, _, data) { if (err) { context.commit('setRequestError', err); return; } context.commit('setNotifications', data.unfiltered_organization_notifications); context.dispatch('markNotificationsAsRead', options); }); }, markNotificationsAsRead (context, options) { const now = new Date(); context.state.notifications.forEach(notification => { const { userId, apiKey } = options; if (!notification.read_at) { const notificationCopy = { ...notification, read_at: now.toISOString() }; context.rootState.client.updateNotification(userId, apiKey, notificationCopy); } }); } } }; export default notifications;
const notifications = { namespaced: true, state: { isFetching: false, isErrored: false, error: [], notifications: [] }, computed: {}, getters: {}, mutations: { setNotifications (state, notifications) { state.notifications = notifications; state.isFetching = false; state.isErrored = false; state.error = []; }, setRequestError (state, error) { state.isFetching = false; state.isErrored = true; state.error = error; state.notifications = []; }, setFetchingState (state) { state.isFetching = true; state.isErrored = false; state.error = []; state.notifications = []; } }, actions: { fetchNotifications (context, options) { context.commit('setFetchingState'); context.rootState.client.getConfig(function (err, _, data) { if (err) { context.commit('setRequestError', err); return; } context.commit('setNotifications', data.unfiltered_organization_notifications); context.dispatch('markNotificationsAsRead', options); }); }, markNotificationsAsRead (context, options) { const nowString = new Date().toISOString(); context.state.notifications.forEach(notification => { const { userId, apiKey } = options; if (!notification.read_at) { const notificationCopy = { ...notification, read_at: nowString }; context.rootState.client.updateNotification(userId, apiKey, notificationCopy); } }); } } }; export default notifications;
Declare now as a string
refactor: Declare now as a string
JavaScript
bsd-3-clause
CartoDB/cartodb,CartoDB/cartodb,CartoDB/cartodb,CartoDB/cartodb,CartoDB/cartodb
javascript
## Code Before: const notifications = { namespaced: true, state: { isFetching: false, isErrored: false, error: [], notifications: [] }, computed: {}, getters: {}, mutations: { setNotifications (state, notifications) { state.notifications = notifications; state.isFetching = false; state.isErrored = false; state.error = []; }, setRequestError (state, error) { state.isFetching = false; state.isErrored = true; state.error = error; state.notifications = []; }, setFetchingState (state) { state.isFetching = true; state.isErrored = false; state.error = []; state.notifications = []; } }, actions: { fetchNotifications (context, options) { context.commit('setFetchingState'); context.rootState.client.getConfig(function (err, _, data) { if (err) { context.commit('setRequestError', err); return; } context.commit('setNotifications', data.unfiltered_organization_notifications); context.dispatch('markNotificationsAsRead', options); }); }, markNotificationsAsRead (context, options) { const now = new Date(); context.state.notifications.forEach(notification => { const { userId, apiKey } = options; if (!notification.read_at) { const notificationCopy = { ...notification, read_at: now.toISOString() }; context.rootState.client.updateNotification(userId, apiKey, notificationCopy); } }); } } }; export default notifications; ## Instruction: refactor: Declare now as a string ## Code After: const notifications = { namespaced: true, state: { isFetching: false, isErrored: false, error: [], notifications: [] }, computed: {}, getters: {}, mutations: { setNotifications (state, notifications) { state.notifications = notifications; state.isFetching = false; state.isErrored = false; state.error = []; }, setRequestError (state, error) { state.isFetching = false; state.isErrored = true; state.error = error; state.notifications = []; }, setFetchingState (state) { state.isFetching = true; state.isErrored = false; state.error = []; state.notifications = []; } }, actions: { fetchNotifications (context, options) { context.commit('setFetchingState'); context.rootState.client.getConfig(function (err, _, data) { if (err) { context.commit('setRequestError', err); return; } context.commit('setNotifications', data.unfiltered_organization_notifications); context.dispatch('markNotificationsAsRead', options); }); }, markNotificationsAsRead (context, options) { const nowString = new Date().toISOString(); context.state.notifications.forEach(notification => { const { userId, apiKey } = options; if (!notification.read_at) { const notificationCopy = { ...notification, read_at: nowString }; context.rootState.client.updateNotification(userId, apiKey, notificationCopy); } }); } } }; export default notifications;
5ecd614c1e2ca420d1d9629c375ddea04ff32cc0
robolectric/src/main/java/org/robolectric/android/fakes/RoboMonitoringInstrumentation.java
robolectric/src/main/java/org/robolectric/android/fakes/RoboMonitoringInstrumentation.java
package org.robolectric.android.fakes; import android.app.Activity; import android.content.Intent; import android.content.pm.ActivityInfo; import androidx.test.runner.MonitoringInstrumentation; import org.robolectric.Robolectric; import org.robolectric.android.controller.ActivityController; public class RoboMonitoringInstrumentation extends MonitoringInstrumentation { @Override protected void specifyDexMakerCacheProperty() { // ignore, unnecessary for robolectric } @Override protected void installMultidex() { // ignore, unnecessary for robolectric } @Override public void setInTouchMode(boolean inTouch) { // ignore } @Override public void waitForIdleSync() { // ignore } @Override public Activity startActivitySync(final Intent intent) { ActivityInfo ai = intent.resolveActivityInfo(getTargetContext().getPackageManager(), 0); try { Class<? extends Activity> activityClass = Class.forName(ai.name).asSubclass(Activity.class); ActivityController<? extends Activity> controller = Robolectric.buildActivity(activityClass, intent); Activity activity = controller.get(); callActivityOnCreate(activity, null); controller.postCreate(null); callActivityOnStart(activity); callActivityOnResume(activity); controller.visible().windowFocusChanged(true); return activity; } catch (ClassNotFoundException e) { throw new RuntimeException("Could not load activity " + ai.name, e); } } @Override public void runOnMainSync(Runnable runner) { runner.run(); } }
package org.robolectric.android.fakes; import android.app.Activity; import android.content.Intent; import android.content.pm.ActivityInfo; import androidx.test.runner.MonitoringInstrumentation; import org.robolectric.Robolectric; import org.robolectric.android.controller.ActivityController; import org.robolectric.shadows.ShadowLooper; public class RoboMonitoringInstrumentation extends MonitoringInstrumentation { @Override protected void specifyDexMakerCacheProperty() { // ignore, unnecessary for robolectric } @Override protected void installMultidex() { // ignore, unnecessary for robolectric } @Override public void setInTouchMode(boolean inTouch) { // ignore } @Override public void waitForIdleSync() { ShadowLooper.getShadowMainLooper().idle(); } @Override public Activity startActivitySync(final Intent intent) { ActivityInfo ai = intent.resolveActivityInfo(getTargetContext().getPackageManager(), 0); try { Class<? extends Activity> activityClass = Class.forName(ai.name).asSubclass(Activity.class); ActivityController<? extends Activity> controller = Robolectric.buildActivity(activityClass, intent); Activity activity = controller.get(); callActivityOnCreate(activity, null); controller.postCreate(null); callActivityOnStart(activity); callActivityOnResume(activity); controller.visible().windowFocusChanged(true); return activity; } catch (ClassNotFoundException e) { throw new RuntimeException("Could not load activity " + ai.name, e); } } @Override public void runOnMainSync(Runnable runner) { runner.run(); } }
Call through to ShadowLooper on Instrumentation.waitForIdleSync
Call through to ShadowLooper on Instrumentation.waitForIdleSync PiperOrigin-RevId: 203801396
Java
mit
jongerrish/robolectric,spotify/robolectric,spotify/robolectric,spotify/robolectric,jongerrish/robolectric,jongerrish/robolectric,jongerrish/robolectric
java
## Code Before: package org.robolectric.android.fakes; import android.app.Activity; import android.content.Intent; import android.content.pm.ActivityInfo; import androidx.test.runner.MonitoringInstrumentation; import org.robolectric.Robolectric; import org.robolectric.android.controller.ActivityController; public class RoboMonitoringInstrumentation extends MonitoringInstrumentation { @Override protected void specifyDexMakerCacheProperty() { // ignore, unnecessary for robolectric } @Override protected void installMultidex() { // ignore, unnecessary for robolectric } @Override public void setInTouchMode(boolean inTouch) { // ignore } @Override public void waitForIdleSync() { // ignore } @Override public Activity startActivitySync(final Intent intent) { ActivityInfo ai = intent.resolveActivityInfo(getTargetContext().getPackageManager(), 0); try { Class<? extends Activity> activityClass = Class.forName(ai.name).asSubclass(Activity.class); ActivityController<? extends Activity> controller = Robolectric.buildActivity(activityClass, intent); Activity activity = controller.get(); callActivityOnCreate(activity, null); controller.postCreate(null); callActivityOnStart(activity); callActivityOnResume(activity); controller.visible().windowFocusChanged(true); return activity; } catch (ClassNotFoundException e) { throw new RuntimeException("Could not load activity " + ai.name, e); } } @Override public void runOnMainSync(Runnable runner) { runner.run(); } } ## Instruction: Call through to ShadowLooper on Instrumentation.waitForIdleSync PiperOrigin-RevId: 203801396 ## Code After: package org.robolectric.android.fakes; import android.app.Activity; import android.content.Intent; import android.content.pm.ActivityInfo; import androidx.test.runner.MonitoringInstrumentation; import org.robolectric.Robolectric; import org.robolectric.android.controller.ActivityController; import org.robolectric.shadows.ShadowLooper; public class RoboMonitoringInstrumentation extends MonitoringInstrumentation { @Override protected void specifyDexMakerCacheProperty() { // ignore, unnecessary for robolectric } @Override protected void installMultidex() { // ignore, unnecessary for robolectric } @Override public void setInTouchMode(boolean inTouch) { // ignore } @Override public void waitForIdleSync() { ShadowLooper.getShadowMainLooper().idle(); } @Override public Activity startActivitySync(final Intent intent) { ActivityInfo ai = intent.resolveActivityInfo(getTargetContext().getPackageManager(), 0); try { Class<? extends Activity> activityClass = Class.forName(ai.name).asSubclass(Activity.class); ActivityController<? extends Activity> controller = Robolectric.buildActivity(activityClass, intent); Activity activity = controller.get(); callActivityOnCreate(activity, null); controller.postCreate(null); callActivityOnStart(activity); callActivityOnResume(activity); controller.visible().windowFocusChanged(true); return activity; } catch (ClassNotFoundException e) { throw new RuntimeException("Could not load activity " + ai.name, e); } } @Override public void runOnMainSync(Runnable runner) { runner.run(); } }
2fc72052c487b60fe523e69983a58a8e0fbb6c39
lib/util/makeSerializable.js
lib/util/makeSerializable.js
/* MIT License http://www.opensource.org/licenses/mit-license.php */ "use strict"; const createHash = require("./createHash"); const { register } = require("./serialization"); const getPrototypeChain = C => { const chain = []; let current = C.prototype; while (current !== Object.prototype) { chain.push(current); current = Object.getPrototypeOf(current); } return chain; }; class ClassSerializer { constructor(Constructor) { this.Constructor = Constructor; this.hash = null; } _createHash() { const hash = createHash("md4"); const prototypeChain = getPrototypeChain(this.Constructor); if (typeof this.Constructor.deserialize === "function") hash.update(this.Constructor.deserialize.toString()); for (const p of prototypeChain) { if (typeof p.serialize === "function") { hash.update(p.serialize.toString()); } if (typeof p.deserialize === "function") { hash.update(p.deserialize.toString()); } } this.hash = hash.digest("base64"); } serialize(obj, context) { if (!this.hash) this._createHash(); context.write(this.hash); obj.serialize(context); } deserialize(context) { if (!this.hash) this._createHash(); const hash = context.read(); if (this.hash !== hash) throw new Error(`Version mismatch for class ${this.Constructor.name}`); if (typeof this.Constructor.deserialize === "function") { return this.Constructor.deserialize(context); } const obj = new this.Constructor(); obj.deserialize(context); return obj; } } module.exports = (Constructor, request, name = null) => { register(Constructor, request, name, new ClassSerializer(Constructor)); };
/* MIT License http://www.opensource.org/licenses/mit-license.php */ "use strict"; const { register } = require("./serialization"); class ClassSerializer { constructor(Constructor) { this.Constructor = Constructor; this.hash = null; } serialize(obj, context) { obj.serialize(context); } deserialize(context) { if (typeof this.Constructor.deserialize === "function") { return this.Constructor.deserialize(context); } const obj = new this.Constructor(); obj.deserialize(context); return obj; } } module.exports = (Constructor, request, name = null) => { register(Constructor, request, name, new ClassSerializer(Constructor)); };
Remove hashing from ClassSerializer as buildDeps take care of this now
Remove hashing from ClassSerializer as buildDeps take care of this now
JavaScript
mit
SimenB/webpack,SimenB/webpack,EliteScientist/webpack,EliteScientist/webpack,webpack/webpack,NekR/webpack,webpack/webpack,SimenB/webpack,SimenB/webpack,NekR/webpack,webpack/webpack,webpack/webpack
javascript
## Code Before: /* MIT License http://www.opensource.org/licenses/mit-license.php */ "use strict"; const createHash = require("./createHash"); const { register } = require("./serialization"); const getPrototypeChain = C => { const chain = []; let current = C.prototype; while (current !== Object.prototype) { chain.push(current); current = Object.getPrototypeOf(current); } return chain; }; class ClassSerializer { constructor(Constructor) { this.Constructor = Constructor; this.hash = null; } _createHash() { const hash = createHash("md4"); const prototypeChain = getPrototypeChain(this.Constructor); if (typeof this.Constructor.deserialize === "function") hash.update(this.Constructor.deserialize.toString()); for (const p of prototypeChain) { if (typeof p.serialize === "function") { hash.update(p.serialize.toString()); } if (typeof p.deserialize === "function") { hash.update(p.deserialize.toString()); } } this.hash = hash.digest("base64"); } serialize(obj, context) { if (!this.hash) this._createHash(); context.write(this.hash); obj.serialize(context); } deserialize(context) { if (!this.hash) this._createHash(); const hash = context.read(); if (this.hash !== hash) throw new Error(`Version mismatch for class ${this.Constructor.name}`); if (typeof this.Constructor.deserialize === "function") { return this.Constructor.deserialize(context); } const obj = new this.Constructor(); obj.deserialize(context); return obj; } } module.exports = (Constructor, request, name = null) => { register(Constructor, request, name, new ClassSerializer(Constructor)); }; ## Instruction: Remove hashing from ClassSerializer as buildDeps take care of this now ## Code After: /* MIT License http://www.opensource.org/licenses/mit-license.php */ "use strict"; const { register } = require("./serialization"); class ClassSerializer { constructor(Constructor) { this.Constructor = Constructor; this.hash = null; } serialize(obj, context) { obj.serialize(context); } deserialize(context) { if (typeof this.Constructor.deserialize === "function") { return this.Constructor.deserialize(context); } const obj = new this.Constructor(); obj.deserialize(context); return obj; } } module.exports = (Constructor, request, name = null) => { register(Constructor, request, name, new ClassSerializer(Constructor)); };
6234258c41964298520b98ec49eae914262af5a5
src/main/java/xyz/upperlevel/uppercore/task/Countdown.java
src/main/java/xyz/upperlevel/uppercore/task/Countdown.java
package xyz.upperlevel.uppercore.task; import lombok.Getter; import org.bukkit.scheduler.BukkitRunnable; import xyz.upperlevel.uppercore.Uppercore; import java.text.SimpleDateFormat; import java.util.Date; import java.util.function.Consumer; public abstract class Countdown extends BukkitRunnable { @Getter private final long startAt, repeatEach; @Getter private long currentTick; public Countdown(long startAt, long repeatEach) { this.startAt = startAt; this.repeatEach = repeatEach; } public void start() { currentTick = startAt; runTaskTimer(Uppercore.plugin(), 0, repeatEach); } public long getTime() { return currentTick / repeatEach; } protected abstract void onTick(long time); protected abstract void onEnd(); @Override public void run() { onTick(currentTick / repeatEach); if (currentTick > 0) currentTick -= repeatEach; else { onEnd(); super.cancel(); } } public String toString(String pattern) { return new SimpleDateFormat(pattern).format(new Date(currentTick * 50)); } public static Countdown create(long startAt, long repeatEach, Consumer<Long> onTick, Runnable onEnd) { return new Countdown(startAt, repeatEach) { @Override protected void onTick(long tick) { onTick.accept(tick); } @Override protected void onEnd() { onEnd.run(); } }; } }
package xyz.upperlevel.uppercore.task; import lombok.Getter; import org.bukkit.scheduler.BukkitRunnable; import xyz.upperlevel.uppercore.Uppercore; import java.text.SimpleDateFormat; import java.util.Date; import java.util.function.Consumer; public abstract class Countdown extends BukkitRunnable { @Getter private final long startAt, repeatEach; @Getter private long currentTick; public Countdown(long startAt, long repeatEach) { this.startAt = startAt; this.repeatEach = repeatEach; } public void start() { currentTick = startAt + repeatEach; runTaskTimer(Uppercore.plugin(), 0, repeatEach); } public long getTime() { return currentTick / repeatEach; } protected abstract void onTick(long time); protected abstract void onEnd(); @Override public void run() { currentTick -= repeatEach; if (currentTick == 0) { onEnd(); super.cancel(); } else { onTick(currentTick / repeatEach); } } public String toString(String pattern) { return new SimpleDateFormat(pattern).format(new Date(currentTick * 50)); } public static Countdown create(long startAt, long repeatEach, Consumer<Long> onTick, Runnable onEnd) { return new Countdown(startAt, repeatEach) { @Override protected void onTick(long tick) { onTick.accept(tick); } @Override protected void onEnd() { onEnd.run(); } }; } }
Fix countdown time sudden change during board updates
Fix countdown time sudden change during board updates
Java
mit
upperlevel/uppercore
java
## Code Before: package xyz.upperlevel.uppercore.task; import lombok.Getter; import org.bukkit.scheduler.BukkitRunnable; import xyz.upperlevel.uppercore.Uppercore; import java.text.SimpleDateFormat; import java.util.Date; import java.util.function.Consumer; public abstract class Countdown extends BukkitRunnable { @Getter private final long startAt, repeatEach; @Getter private long currentTick; public Countdown(long startAt, long repeatEach) { this.startAt = startAt; this.repeatEach = repeatEach; } public void start() { currentTick = startAt; runTaskTimer(Uppercore.plugin(), 0, repeatEach); } public long getTime() { return currentTick / repeatEach; } protected abstract void onTick(long time); protected abstract void onEnd(); @Override public void run() { onTick(currentTick / repeatEach); if (currentTick > 0) currentTick -= repeatEach; else { onEnd(); super.cancel(); } } public String toString(String pattern) { return new SimpleDateFormat(pattern).format(new Date(currentTick * 50)); } public static Countdown create(long startAt, long repeatEach, Consumer<Long> onTick, Runnable onEnd) { return new Countdown(startAt, repeatEach) { @Override protected void onTick(long tick) { onTick.accept(tick); } @Override protected void onEnd() { onEnd.run(); } }; } } ## Instruction: Fix countdown time sudden change during board updates ## Code After: package xyz.upperlevel.uppercore.task; import lombok.Getter; import org.bukkit.scheduler.BukkitRunnable; import xyz.upperlevel.uppercore.Uppercore; import java.text.SimpleDateFormat; import java.util.Date; import java.util.function.Consumer; public abstract class Countdown extends BukkitRunnable { @Getter private final long startAt, repeatEach; @Getter private long currentTick; public Countdown(long startAt, long repeatEach) { this.startAt = startAt; this.repeatEach = repeatEach; } public void start() { currentTick = startAt + repeatEach; runTaskTimer(Uppercore.plugin(), 0, repeatEach); } public long getTime() { return currentTick / repeatEach; } protected abstract void onTick(long time); protected abstract void onEnd(); @Override public void run() { currentTick -= repeatEach; if (currentTick == 0) { onEnd(); super.cancel(); } else { onTick(currentTick / repeatEach); } } public String toString(String pattern) { return new SimpleDateFormat(pattern).format(new Date(currentTick * 50)); } public static Countdown create(long startAt, long repeatEach, Consumer<Long> onTick, Runnable onEnd) { return new Countdown(startAt, repeatEach) { @Override protected void onTick(long tick) { onTick.accept(tick); } @Override protected void onEnd() { onEnd.run(); } }; } }
49ea86d93d75afb1c3a3f95dd72a78b6d78f04cc
sitecustomize.py
sitecustomize.py
import sys import os from combinator.branchmgr import theBranchManager theBranchManager.addPaths() for key in sys.modules.keys(): # Unload all Combinator modules that had to be loaded in order to call # addPaths(). Although the very very beginning of this script needs to # load the trunk combinator (or whichever one your shell points at), once # the path has been set up, newer versions of combinator may be used; for # example, the 'whbranch', 'chbranch' and 'mkbranch' commands should all # import Combinator from the current Divmod branch. This is especially # required so that Combinator's tests can be run on the currently-active # Combinator rather than the one responsible for setting up the # environment. if key == 'combinator' or key.startswith('combinator'): del sys.modules[key] # Install stuff as a user, by default. if sys.platform != 'darwin': # For use with setup.py... if sys.platform.startswith('win'): execprefix = os.path.abspath(os.path.expanduser("~/Python")) else: # Don't exactly know how Darwin fits in here - I think distutils is # buggy...? execprefix = os.path.abspath(os.path.expanduser("~/.local")) import sys class DistSysProxy: def __getattr__(self, attr): if attr in ('prefix', 'exec_prefix'): return execprefix else: return getattr(sys, attr) sys.modules['distutils.command.sys'] = DistSysProxy()
import sys import os from combinator.branchmgr import theBranchManager theBranchManager.addPaths() for key in sys.modules.keys(): # Unload all Combinator modules that had to be loaded in order to call # addPaths(). Although the very very beginning of this script needs to # load the trunk combinator (or whichever one your shell points at), once # the path has been set up, newer versions of combinator may be used; for # example, the 'whbranch', 'chbranch' and 'mkbranch' commands should all # import Combinator from the current Divmod branch. This is especially # required so that Combinator's tests can be run on the currently-active # Combinator rather than the one responsible for setting up the # environment. if key == 'combinator' or key.startswith('combinator'): del sys.modules[key]
Remove distutils-mangling code from Combinator which breaks setuptools.
Remove distutils-mangling code from Combinator which breaks setuptools. After this change, Combinator will no longer attempt to force 'python setup.py install' to put things into your home directory. Use `setup.py --prefix ~/.local`, or, if your package is trying to use setuptools, `python setup.py --site-dirs ~/.local/lib/python2.5/site-packages --prefix ~/.local install`. Author: glyph Reviewer: dried Fixes #493
Python
mit
habnabit/Combinator,habnabit/Combinator
python
## Code Before: import sys import os from combinator.branchmgr import theBranchManager theBranchManager.addPaths() for key in sys.modules.keys(): # Unload all Combinator modules that had to be loaded in order to call # addPaths(). Although the very very beginning of this script needs to # load the trunk combinator (or whichever one your shell points at), once # the path has been set up, newer versions of combinator may be used; for # example, the 'whbranch', 'chbranch' and 'mkbranch' commands should all # import Combinator from the current Divmod branch. This is especially # required so that Combinator's tests can be run on the currently-active # Combinator rather than the one responsible for setting up the # environment. if key == 'combinator' or key.startswith('combinator'): del sys.modules[key] # Install stuff as a user, by default. if sys.platform != 'darwin': # For use with setup.py... if sys.platform.startswith('win'): execprefix = os.path.abspath(os.path.expanduser("~/Python")) else: # Don't exactly know how Darwin fits in here - I think distutils is # buggy...? execprefix = os.path.abspath(os.path.expanduser("~/.local")) import sys class DistSysProxy: def __getattr__(self, attr): if attr in ('prefix', 'exec_prefix'): return execprefix else: return getattr(sys, attr) sys.modules['distutils.command.sys'] = DistSysProxy() ## Instruction: Remove distutils-mangling code from Combinator which breaks setuptools. After this change, Combinator will no longer attempt to force 'python setup.py install' to put things into your home directory. Use `setup.py --prefix ~/.local`, or, if your package is trying to use setuptools, `python setup.py --site-dirs ~/.local/lib/python2.5/site-packages --prefix ~/.local install`. Author: glyph Reviewer: dried Fixes #493 ## Code After: import sys import os from combinator.branchmgr import theBranchManager theBranchManager.addPaths() for key in sys.modules.keys(): # Unload all Combinator modules that had to be loaded in order to call # addPaths(). Although the very very beginning of this script needs to # load the trunk combinator (or whichever one your shell points at), once # the path has been set up, newer versions of combinator may be used; for # example, the 'whbranch', 'chbranch' and 'mkbranch' commands should all # import Combinator from the current Divmod branch. This is especially # required so that Combinator's tests can be run on the currently-active # Combinator rather than the one responsible for setting up the # environment. if key == 'combinator' or key.startswith('combinator'): del sys.modules[key]
29ea7bc48cc4ef81466764bdda3729ac44345154
annotation-rest/src/main/java/uk/ac/ebi/quickgo/annotation/service/statistics/RequiredStatisticsProvider.java
annotation-rest/src/main/java/uk/ac/ebi/quickgo/annotation/service/statistics/RequiredStatisticsProvider.java
package uk.ac.ebi.quickgo.annotation.service.statistics; import java.util.List; /** * A source of {@link RequiredStatistics} instances. * * @author Tony Wardell * Date: 19/12/2017 * Time: 11:04 * Created with IntelliJ IDEA. */ public class RequiredStatisticsProvider { private final RequiredStatistics standardUsage; private final RequiredStatistics downloadUsage; private final RequiredStatistics standardUsageWithGeneProductFiltering; private final RequiredStatistics downloadUsageWithGeneProductFiltering; public RequiredStatisticsProvider(StatisticsTypeConfigurer standardConfiguration, StatisticsTypeConfigurer downloadConfiguration) { standardUsage = new RequiredStatistics(standardConfiguration); downloadUsage = new RequiredStatistics(downloadConfiguration); standardUsageWithGeneProductFiltering = new RequiredStatisticsWithGeneProduct(standardConfiguration); downloadUsageWithGeneProductFiltering = new RequiredStatisticsWithGeneProduct(downloadConfiguration); } public List<RequiredStatistic> getStandardUsage() { return standardUsage.getRequiredStatistics(); } public List<RequiredStatistic> getDownloadUsage() { return downloadUsage.getRequiredStatistics(); } public List<RequiredStatistic> getStandardUsageWithGeneProductFiltering() { return standardUsageWithGeneProductFiltering.getRequiredStatistics(); } public List<RequiredStatistic> getDownloadUsageWithGeneProductFiltering() { return downloadUsageWithGeneProductFiltering.getRequiredStatistics(); } }
package uk.ac.ebi.quickgo.annotation.service.statistics; import java.util.List; import java.util.Objects; import static com.google.common.base.Preconditions.checkArgument; /** * A source of {@link RequiredStatistics} instances. * * @author Tony Wardell * Date: 19/12/2017 * Time: 11:04 * Created with IntelliJ IDEA. */ public class RequiredStatisticsProvider { private final RequiredStatistics standardUsage; private final RequiredStatistics downloadUsage; private final RequiredStatistics standardUsageWithGeneProductFiltering; private final RequiredStatistics downloadUsageWithGeneProductFiltering; public RequiredStatisticsProvider(StatisticsTypeConfigurer standardConfiguration, StatisticsTypeConfigurer downloadConfiguration) { checkArgument(Objects.nonNull(standardConfiguration), "The standard StatisticsTypeConfigurer instance cannot" + " be null"); checkArgument(Objects.nonNull(standardConfiguration), "The download StatisticsTypeConfigurer instance cannot" + " be null"); standardUsage = new RequiredStatistics(standardConfiguration); downloadUsage = new RequiredStatistics(downloadConfiguration); standardUsageWithGeneProductFiltering = new RequiredStatisticsWithGeneProduct(standardConfiguration); downloadUsageWithGeneProductFiltering = new RequiredStatisticsWithGeneProduct(downloadConfiguration); } public List<RequiredStatistic> getStandardUsage() { return standardUsage.getRequiredStatistics(); } public List<RequiredStatistic> getDownloadUsage() { return downloadUsage.getRequiredStatistics(); } public List<RequiredStatistic> getStandardUsageWithGeneProductFiltering() { return standardUsageWithGeneProductFiltering.getRequiredStatistics(); } public List<RequiredStatistic> getDownloadUsageWithGeneProductFiltering() { return downloadUsageWithGeneProductFiltering.getRequiredStatistics(); } }
Check configuration objects passed to the constructor are not null.
Check configuration objects passed to the constructor are not null.
Java
apache-2.0
ebi-uniprot/QuickGOBE,ebi-uniprot/QuickGOBE,ebi-uniprot/QuickGOBE,ebi-uniprot/QuickGOBE,ebi-uniprot/QuickGOBE
java
## Code Before: package uk.ac.ebi.quickgo.annotation.service.statistics; import java.util.List; /** * A source of {@link RequiredStatistics} instances. * * @author Tony Wardell * Date: 19/12/2017 * Time: 11:04 * Created with IntelliJ IDEA. */ public class RequiredStatisticsProvider { private final RequiredStatistics standardUsage; private final RequiredStatistics downloadUsage; private final RequiredStatistics standardUsageWithGeneProductFiltering; private final RequiredStatistics downloadUsageWithGeneProductFiltering; public RequiredStatisticsProvider(StatisticsTypeConfigurer standardConfiguration, StatisticsTypeConfigurer downloadConfiguration) { standardUsage = new RequiredStatistics(standardConfiguration); downloadUsage = new RequiredStatistics(downloadConfiguration); standardUsageWithGeneProductFiltering = new RequiredStatisticsWithGeneProduct(standardConfiguration); downloadUsageWithGeneProductFiltering = new RequiredStatisticsWithGeneProduct(downloadConfiguration); } public List<RequiredStatistic> getStandardUsage() { return standardUsage.getRequiredStatistics(); } public List<RequiredStatistic> getDownloadUsage() { return downloadUsage.getRequiredStatistics(); } public List<RequiredStatistic> getStandardUsageWithGeneProductFiltering() { return standardUsageWithGeneProductFiltering.getRequiredStatistics(); } public List<RequiredStatistic> getDownloadUsageWithGeneProductFiltering() { return downloadUsageWithGeneProductFiltering.getRequiredStatistics(); } } ## Instruction: Check configuration objects passed to the constructor are not null. ## Code After: package uk.ac.ebi.quickgo.annotation.service.statistics; import java.util.List; import java.util.Objects; import static com.google.common.base.Preconditions.checkArgument; /** * A source of {@link RequiredStatistics} instances. * * @author Tony Wardell * Date: 19/12/2017 * Time: 11:04 * Created with IntelliJ IDEA. */ public class RequiredStatisticsProvider { private final RequiredStatistics standardUsage; private final RequiredStatistics downloadUsage; private final RequiredStatistics standardUsageWithGeneProductFiltering; private final RequiredStatistics downloadUsageWithGeneProductFiltering; public RequiredStatisticsProvider(StatisticsTypeConfigurer standardConfiguration, StatisticsTypeConfigurer downloadConfiguration) { checkArgument(Objects.nonNull(standardConfiguration), "The standard StatisticsTypeConfigurer instance cannot" + " be null"); checkArgument(Objects.nonNull(standardConfiguration), "The download StatisticsTypeConfigurer instance cannot" + " be null"); standardUsage = new RequiredStatistics(standardConfiguration); downloadUsage = new RequiredStatistics(downloadConfiguration); standardUsageWithGeneProductFiltering = new RequiredStatisticsWithGeneProduct(standardConfiguration); downloadUsageWithGeneProductFiltering = new RequiredStatisticsWithGeneProduct(downloadConfiguration); } public List<RequiredStatistic> getStandardUsage() { return standardUsage.getRequiredStatistics(); } public List<RequiredStatistic> getDownloadUsage() { return downloadUsage.getRequiredStatistics(); } public List<RequiredStatistic> getStandardUsageWithGeneProductFiltering() { return standardUsageWithGeneProductFiltering.getRequiredStatistics(); } public List<RequiredStatistic> getDownloadUsageWithGeneProductFiltering() { return downloadUsageWithGeneProductFiltering.getRequiredStatistics(); } }
bc7fa0de7dcd55cce585151016e5092de7f7416b
lib/acts_as_simple_translatable/class_methods.rb
lib/acts_as_simple_translatable/class_methods.rb
module ActsAsSimpleTranslatable module ClassMethods def acts_as_simple_translatable_on(*fields) # scope :with_translations, -> (locale) { joins(:translations).where(translations: {locale: locale}).preload(:translations) } scope :with_translations, -> { includes(:translations) } has_many :translations, as: :translatable, dependent: :destroy accepts_nested_attributes_for :translations, reject_if: :all_blank, allow_destroy: :true @locale_fields = fields class << self attr_accessor :locale_fields end # Loop through fields to define methods such as "name" and "description" fields.each do |field| define_method "#{field}" do |default_message = 'NO TRANSLATION'| content = (I18n.locale == I18n.default_locale) ? super() : locale_translations[field] content.present? ? content : default_message end define_method "#{field}_original" do super() end define_method "#{field}?" do !send("#{field}").blank? end end define_method :locale_translations do # load translations unless @locale_translations @locale_translations = {} translations.select { |t| t.locale == I18n.locale.to_s }.each do |translation| @locale_translations ||= {} @locale_translations[translation.translatable_field.to_sym] = translation.content end end @locale_translations end end end end
module ActsAsSimpleTranslatable module ClassMethods def acts_as_simple_translatable_on(*fields) # scope :with_translations, -> (locale) { joins(:translations).where(translations: {locale: locale}).preload(:translations) } scope :with_translations, -> { includes(:translations) } has_many :translations, as: :translatable, dependent: :destroy accepts_nested_attributes_for :translations, reject_if: :all_blank, allow_destroy: :true @locale_fields = fields class << self attr_accessor :locale_fields end # Loop through fields to define methods such as "name" and "description" fields.each do |field| define_method "#{field}" do |default_message = 'NO TRANSLATION'| content = (I18n.locale == I18n.default_locale) ? super() : locale_translations[field] content.present? || (I18n.locale == I18n.default_locale) ? content : default_message end define_method "#{field}_original" do super() end define_method "#{field}?" do !send("#{field}").blank? end end define_method :locale_translations do # load translations unless @locale_translations @locale_translations = {} translations.select { |t| t.locale == I18n.locale.to_s }.each do |translation| @locale_translations ||= {} @locale_translations[translation.translatable_field.to_sym] = translation.content end end @locale_translations end end end end
Hide default translation message when default locale is active
Hide default translation message when default locale is active
Ruby
mit
d4be4st/acts_as_simple_translatable
ruby
## Code Before: module ActsAsSimpleTranslatable module ClassMethods def acts_as_simple_translatable_on(*fields) # scope :with_translations, -> (locale) { joins(:translations).where(translations: {locale: locale}).preload(:translations) } scope :with_translations, -> { includes(:translations) } has_many :translations, as: :translatable, dependent: :destroy accepts_nested_attributes_for :translations, reject_if: :all_blank, allow_destroy: :true @locale_fields = fields class << self attr_accessor :locale_fields end # Loop through fields to define methods such as "name" and "description" fields.each do |field| define_method "#{field}" do |default_message = 'NO TRANSLATION'| content = (I18n.locale == I18n.default_locale) ? super() : locale_translations[field] content.present? ? content : default_message end define_method "#{field}_original" do super() end define_method "#{field}?" do !send("#{field}").blank? end end define_method :locale_translations do # load translations unless @locale_translations @locale_translations = {} translations.select { |t| t.locale == I18n.locale.to_s }.each do |translation| @locale_translations ||= {} @locale_translations[translation.translatable_field.to_sym] = translation.content end end @locale_translations end end end end ## Instruction: Hide default translation message when default locale is active ## Code After: module ActsAsSimpleTranslatable module ClassMethods def acts_as_simple_translatable_on(*fields) # scope :with_translations, -> (locale) { joins(:translations).where(translations: {locale: locale}).preload(:translations) } scope :with_translations, -> { includes(:translations) } has_many :translations, as: :translatable, dependent: :destroy accepts_nested_attributes_for :translations, reject_if: :all_blank, allow_destroy: :true @locale_fields = fields class << self attr_accessor :locale_fields end # Loop through fields to define methods such as "name" and "description" fields.each do |field| define_method "#{field}" do |default_message = 'NO TRANSLATION'| content = (I18n.locale == I18n.default_locale) ? super() : locale_translations[field] content.present? || (I18n.locale == I18n.default_locale) ? content : default_message end define_method "#{field}_original" do super() end define_method "#{field}?" do !send("#{field}").blank? end end define_method :locale_translations do # load translations unless @locale_translations @locale_translations = {} translations.select { |t| t.locale == I18n.locale.to_s }.each do |translation| @locale_translations ||= {} @locale_translations[translation.translatable_field.to_sym] = translation.content end end @locale_translations end end end end
d7e9eba6fb3628f0736bd468ae76e05099b9d651
space/decorators.py
space/decorators.py
from django.http import HttpResponseBadRequest, HttpResponseForbidden from django.views.decorators.csrf import csrf_exempt from incubator.settings import STATUS_SECRETS def one_or_zero(arg): """Typecast to 1 or 0""" if arg == '1': return 1 elif arg == '0': return 0 raise ValueError("not one or zero") def private_api(**required_params): """ Filter incoming private API requests, and perform parameter validation and extraction """ def outer(some_view): @csrf_exempt def inner(request, *args, **kwargs): if request.method != 'POST': return HttpResponseBadRequest("Only POST is allowed") if 'secret' not in request.POST.keys(): return HttpResponseBadRequest( "You must query this endpoint with a secret.") if request.POST['secret'] not in STATUS_SECRETS: message = 'Bad secret {} is not in the allowed list'.format( request.POST['secret']) return HttpResponseForbidden(message) params = {} for name, typecast in required_params.items(): if name not in request.POST.keys(): return HttpResponseBadRequest( "Parameter %s is required" % name) try: params[name] = typecast(request.POST[name]) except ValueError: return HttpResponseBadRequest( "Did not understood %s=%s" % (name, request.POST[name])) return some_view(request, **params) return inner return outer
from django.http import HttpResponseBadRequest, HttpResponseForbidden from django.views.decorators.csrf import csrf_exempt from django.conf import settings def one_or_zero(arg): """Typecast to 1 or 0""" if arg == '1': return 1 elif arg == '0': return 0 raise ValueError("not one or zero") def private_api(**required_params): """ Filter incoming private API requests, and perform parameter validation and extraction """ def outer(some_view): @csrf_exempt def inner(request, *args, **kwargs): if request.method != 'POST': return HttpResponseBadRequest("Only POST is allowed") if 'secret' not in request.POST.keys(): return HttpResponseBadRequest( "You must query this endpoint with a secret.") if request.POST['secret'] not in settings.STATUS_SECRETS: message = 'Bad secret {} is not in the allowed list'.format( request.POST['secret']) return HttpResponseForbidden(message) params = {} for name, typecast in required_params.items(): if name not in request.POST.keys(): return HttpResponseBadRequest( "Parameter %s is required" % name) try: params[name] = typecast(request.POST[name]) except ValueError: return HttpResponseBadRequest( "Did not understood %s=%s" % (name, request.POST[name])) return some_view(request, **params) return inner return outer
Use from django.conf import settings
Use from django.conf import settings
Python
agpl-3.0
UrLab/incubator,UrLab/incubator,UrLab/incubator,UrLab/incubator
python
## Code Before: from django.http import HttpResponseBadRequest, HttpResponseForbidden from django.views.decorators.csrf import csrf_exempt from incubator.settings import STATUS_SECRETS def one_or_zero(arg): """Typecast to 1 or 0""" if arg == '1': return 1 elif arg == '0': return 0 raise ValueError("not one or zero") def private_api(**required_params): """ Filter incoming private API requests, and perform parameter validation and extraction """ def outer(some_view): @csrf_exempt def inner(request, *args, **kwargs): if request.method != 'POST': return HttpResponseBadRequest("Only POST is allowed") if 'secret' not in request.POST.keys(): return HttpResponseBadRequest( "You must query this endpoint with a secret.") if request.POST['secret'] not in STATUS_SECRETS: message = 'Bad secret {} is not in the allowed list'.format( request.POST['secret']) return HttpResponseForbidden(message) params = {} for name, typecast in required_params.items(): if name not in request.POST.keys(): return HttpResponseBadRequest( "Parameter %s is required" % name) try: params[name] = typecast(request.POST[name]) except ValueError: return HttpResponseBadRequest( "Did not understood %s=%s" % (name, request.POST[name])) return some_view(request, **params) return inner return outer ## Instruction: Use from django.conf import settings ## Code After: from django.http import HttpResponseBadRequest, HttpResponseForbidden from django.views.decorators.csrf import csrf_exempt from django.conf import settings def one_or_zero(arg): """Typecast to 1 or 0""" if arg == '1': return 1 elif arg == '0': return 0 raise ValueError("not one or zero") def private_api(**required_params): """ Filter incoming private API requests, and perform parameter validation and extraction """ def outer(some_view): @csrf_exempt def inner(request, *args, **kwargs): if request.method != 'POST': return HttpResponseBadRequest("Only POST is allowed") if 'secret' not in request.POST.keys(): return HttpResponseBadRequest( "You must query this endpoint with a secret.") if request.POST['secret'] not in settings.STATUS_SECRETS: message = 'Bad secret {} is not in the allowed list'.format( request.POST['secret']) return HttpResponseForbidden(message) params = {} for name, typecast in required_params.items(): if name not in request.POST.keys(): return HttpResponseBadRequest( "Parameter %s is required" % name) try: params[name] = typecast(request.POST[name]) except ValueError: return HttpResponseBadRequest( "Did not understood %s=%s" % (name, request.POST[name])) return some_view(request, **params) return inner return outer