content_type
stringclasses
8 values
main_lang
stringclasses
7 values
message
stringlengths
1
50
sha
stringlengths
40
40
patch
stringlengths
52
962k
file_count
int64
1
300
Python
Python
fix bugs for multilevel_native_crop_and_resize
eb4b727d66c09987ad5c7464f68e7508b3aa0c10
<ide><path>research/object_detection/utils/spatial_transform_ops.py <ide> def multilevel_roi_align(features, boxes, box_levels, output_size, <ide> <ide> def multilevel_native_crop_and_resize(images, boxes, box_levels, <ide> crop_size, scope=None): <del> #FIXME: fix docstring <del> """doc string.""" <add> """Multilevel native crop and resize. <add> <add> Same as `multilevel_matmul_crop_and_resize` but uses tf.image.crop_and_resize. <add> """ <ide> if box_levels is None: <ide> return native_crop_and_resize(images[0], boxes, crop_size, scope=None) <del> croped_feature_list = [] <add> cropped_feature_list = [] <ide> for level, image in enumerate(images): <del> # indicies = tf.boolean_mask(tf.range(0, boxes[0]), box_levels == level) <del> # print(indicies) <del> # level_boxes = tf.gather(boxes, indicies) <del> # print(level_boxes) <del> # level_boxes = boxes[box_levels == level] <del> # level_boxes = tf.reshape(level_boxes, <del> # [1, -1] + level_boxes.shape.as_list()[1:]) <add> # For each level, crop the feature according to all boxes <add> # set the cropped feature not at this level to 0 tensor. <ide> cropped = native_crop_and_resize(image, boxes, crop_size) <del> print(cropped) <del> cond = tf.tile(tf.equal(box_levels, level)[:, :, tf.newaxis], [1, 1] + [tf.math.reduce_prod(cropped.shape.as_list()[2:])]) <add> cond = tf.tile(tf.equal(box_levels, level)[:, :, tf.newaxis], <add> [1, 1] + [tf.math.reduce_prod(cropped.shape.as_list()[2:])]) <ide> cond = tf.reshape(cond, cropped.shape) <del> print(cond) <ide> cropped_final = tf.where(cond, cropped, tf.zeros_like(cropped)) <del> # cropped[tf.where(box_levels != level)] = tf.zeros(crop_size) <del> print(cropped_final) <del> croped_feature_list.append(cropped_final) <del> return tf.concat(croped_feature_list, axis=0) <add> cropped_feature_list.append(cropped_final) <add> return tf.math.reduce_sum(cropped_feature_list, axis=0) <ide> <ide> <ide> def native_crop_and_resize(image, boxes, crop_size, scope=None): <ide> def get_box_inds(proposals): <ide> <ide> def multilevel_matmul_crop_and_resize(images, boxes, box_levels, crop_size, <ide> extrapolation_value=0.0, scope=None): <del> #FIXME: fix docstring <del> """doc string.""" <add> """Multilevel native crop and resize. <add> <add> Same as `matmul_crop_and_resize` but crop images according to box levels. <add> <add> Args: <add> images: A list of 4-D tensor of shape <add> [batch, image_height, image_width, depth] representing features of <add> different size. <add> boxes: A `Tensor` of type `float32` or 'bfloat16'. <add> A 3-D tensor of shape `[batch, num_boxes, 4]`. The boxes are specified in <add> normalized coordinates and are of the form `[y1, x1, y2, x2]`. A <add> normalized coordinate value of `y` is mapped to the image coordinate at <add> `y * (image_height - 1)`, so as the `[0, 1]` interval of normalized image <add> height is mapped to `[0, image_height - 1] in image height coordinates. <add> We do allow y1 > y2, in which case the sampled crop is an up-down flipped <add> version of the original image. The width dimension is treated similarly. <add> Normalized coordinates outside the `[0, 1]` range are allowed, in which <add> case we use `extrapolation_value` to extrapolate the input image values. <add> box_levels: A 2-D tensor of shape [batch, num_boxes] representing the level <add> of the box. <add> crop_size: A list of two integers `[crop_height, crop_width]`. All <add> cropped image patches are resized to this size. The aspect ratio of the <add> image content is not preserved. Both `crop_height` and `crop_width` need <add> to be positive. <add> extrapolation_value: a float value to use for extrapolation. <add> scope: A name for the operation (optional). <add> <add> Returns: <add> A 5-D tensor of shape `[batch, num_boxes, crop_height, crop_width, depth]` <add> """ <ide> with tf.name_scope(scope, 'MatMulCropAndResize'): <ide> if box_levels is None: <ide> box_levels = tf.zeros(tf.shape(boxes)[:2], dtype=tf.int32)
1
PHP
PHP
use own method instead
afb36eecf2b9e14b6cf3541d436e587b1e77261b
<ide><path>src/View/Helper/PaginatorHelper.php <ide> class PaginatorHelper extends Helper { <ide> public function __construct(View $View, array $config = array()) { <ide> parent::__construct($View, $config); <ide> <add> $this->setUpUrl(); <add> } <add> <add>/** <add> * Merges passed args with URL options. <add> * <add> * @return void <add> */ <add> public function setUpUrl() { <ide> $this->config( <ide> 'options.url', <ide> array_merge($this->request->params['pass'], $this->request->query) <ide><path>tests/TestCase/View/Helper/PaginatorHelperTest.php <ide> public function testPassedArgsMergingWithUrlOptions() { <ide> <ide> $this->Paginator->request->params['pass'] = array(2); <ide> $this->Paginator->request->query = array('page' => 1, 'foo' => 'bar', 'x' => 'y'); <del> $this->Paginator->__construct($this->View); <add> $this->Paginator->setUpUrl(); <ide> <ide> $result = $this->Paginator->sort('title'); <ide> $expected = array(
2
Go
Go
ignore failure to save hns endpoint to store
8b400916cef1fd9d7f8681b20453c8d0af8b863c
<ide><path>libnetwork/drivers/windows/windows.go <ide> func (d *driver) CreateEndpoint(nid, eid string, ifInfo driverapi.InterfaceInfo, <ide> } <ide> <ide> if err = d.storeUpdate(endpoint); err != nil { <del> return fmt.Errorf("failed to save endpoint %s to store: %v", endpoint.id[0:7], err) <add> logrus.Errorf("Failed to save endpoint %s to store: %v", endpoint.id[0:7], err) <ide> } <ide> <ide> return nil
1
Go
Go
allow concurrent calls to agentclose
efc25da851bd68e52e6505e7c65f209bcb1fdfe4
<ide><path>libnetwork/agent.go <ide> func (c *controller) agentDriverNotify(d driverapi.Driver) { <ide> } <ide> <ide> func (c *controller) agentClose() { <del> if c.agent == nil { <add> // Acquire current agent instance and reset its pointer <add> // then run closing functions <add> c.Lock() <add> agent := c.agent <add> c.agent = nil <add> c.Unlock() <add> <add> if agent == nil { <ide> return <ide> } <ide> <del> for _, cancelFuncs := range c.agent.driverCancelFuncs { <add> for _, cancelFuncs := range agent.driverCancelFuncs { <ide> for _, cancel := range cancelFuncs { <ide> cancel() <ide> } <ide> } <del> c.agent.epTblCancel() <ide> <del> c.agent.networkDB.Close() <add> agent.epTblCancel() <ide> <del> c.Lock() <del> c.agent = nil <del> c.Unlock() <add> agent.networkDB.Close() <ide> } <ide> <ide> func (n *network) isClusterEligible() bool {
1
Javascript
Javascript
remove some useless bits of code
d1d66211644eee43292a874ec076b6bfb0169a6a
<ide><path>PDFFont.js <ide> var Type1Parser = function(aAsciiStream, aBinaryStream) { <ide> * as descrived in 'Using Subroutines' of 'Adobe Type 1 Font Format', <ide> * chapter 8. <ide> */ <del> this.flattenCharstring = function(aCharstring, aDefaultWidth, aNominalWidth, aSubrs) { <add> this.flattenCharstring = function(aCharstring, aDefaultWidth, aSubrs) { <ide> operandStack.clear(); <ide> executionStack.clear(); <ide> executionStack.push(aCharstring); <ide> var Type1Parser = function(aAsciiStream, aBinaryStream) { <ide> leftSidebearing = operandStack.pop(); <ide> <ide> if (charWidthVector != aDefaultWidth) <del> operandStack.push(charWidthVector - aNominalWidth); <add> operandStack.push(charWidthVector - aDefaultWidth); <add> break; <add> <add> case "rmoveto": <add> var dy = operandStack.pop(); <add> var dx = operandStack.pop(); <add> <add> if (leftSidebearing) { <add> dx += leftSidebearing; <add> leftSidebearing = 0; <add> } <add> <add> operandStack.push(dx); <add> operandStack.push(dy); <add> operandStack.push("rmoveto"); <ide> break; <ide> <ide> case "setcurrentpoint": <ide> var Type1Parser = function(aAsciiStream, aBinaryStream) { <ide> operandStack.push("hstem"); <ide> break; <ide> <del> case "rmoveto": <del> var dy = operandStack.pop(); <del> var dx = operandStack.pop(); <del> <del> if (leftSidebearing) { <del> dx += leftSidebearing; <del> leftSidebearing = 0; <del> } <del> <del> operandStack.push(dx); <del> operandStack.push(dy); <del> operandStack.push("rmoveto"); <del> break; <del> <del> <ide> case "callsubr": <ide> var index = operandStack.pop(); <ide> executionStack.push(aSubrs[index].slice()); <ide> var Type1Font = function(aFontName, aFontFile) { <ide> <ide> this.parser = new Type1Parser(ASCIIStream, binaryStream); <ide> var fontName = this.parser.parse(); <del> this.convertToOTF(fontName); <add> var font = Fonts.get(fontName); <add> this.convertToOTF(this.convertToCFF(font), font); <add> <ide> var end = Date.now(); <ide> log("Time to parse font is:" + (end - start)); <ide> } <ide> }; <ide> <ide> Type1Font.prototype = { <del> getDefaultWidths: function(aCharstrings) { <add> getDefaultWidth: function(aCharstrings) { <ide> var defaultWidth = 0; <ide> var defaultUsedCount = 0; <ide> <ide> Type1Font.prototype = { <ide> <ide> widths[width] = usedCount; <ide> } <del> defaultWidth = parseInt(defaultWidth); <del> <del> var maxNegDistance = 0, maxPosDistance = 0; <del> for (var width in widths) { <del> var diff = width - defaultWidth; <del> if (diff < 0 && diff < maxNegDistance) { <del> maxNegDistance = diff; <del> } else if (diff > 0 && diff > maxPosDistance) { <del> maxPosDistance = diff; <del> } <del> } <del> <del> return { <del> default: defaultWidth, <del> nominal: defaultWidth + (maxPosDistance + maxNegDistance) / 2 <del> }; <add> return parseInt(defaultWidth); <ide> }, <ide> <del> <ide> createCFFIndexHeader: function(aObjects, aIsByte) { <ide> var data = []; <ide> <ide> Type1Font.prototype = { <ide> } <ide> }, <ide> <del> convertToOTF: function(aFontName) { <del> var font = Fonts.get(aFontName); <del> <del> var charstrings = font.get("CharStrings") <del> var defaultWidths = this.getDefaultWidths(charstrings); <del> var defaultWidth = defaultWidths.default; <del> var nominalWidth = defaultWidths.nominal; <add> convertToCFF: function(aFont) { <add> var charstrings = aFont.get("CharStrings") <add> var defaultWidth = this.getDefaultWidth(charstrings); <ide> <ide> log("defaultWidth to used: " + defaultWidth); <del> log("nominalWidth to used: " + nominalWidth); <del> log("Hack nonimal:" + (nominalWidth = 615)); <ide> <add> var charstringsCount = 0; <add> var charstringsDataLength = 0; <ide> <ide> var glyphs = {}; <del> var subrs = font.get("Private").get("Subrs"); <add> var subrs = aFont.get("Private").get("Subrs"); <ide> var parser = new Type1Parser(); <ide> for (var glyph in charstrings.map) { <ide> var charstring = charstrings.get(glyph); <del> glyphs[glyph] = parser.flattenCharstring(charstring, defaultWidth, nominalWidth, subrs); <add> glyphs[glyph] = parser.flattenCharstring(charstring, defaultWidth, subrs); <add> charstringsCount++; <add> charstringsDataLength += glyphs[glyph].length; <ide> } <ide> <add> log("There is " + charstringsCount + " glyphs (size: " + charstringsDataLength + ")"); <add> <ide> // Create a CFF font data <ide> var cff = new Uint8Array(20000); <ide> var currentOffset = 0; <ide> Type1Font.prototype = { <ide> cff.set(header); <ide> <ide> // Names Index <del> var nameIndex = this.createCFFIndexHeader([aFontName]); <add> var nameIndex = this.createCFFIndexHeader([aFont.get("FontName")]); <ide> cff.set(nameIndex, currentOffset); <ide> currentOffset += nameIndex.length; <ide> <ide> Type1Font.prototype = { <ide> // Private Data <ide> var privateData = [ <ide> 248, 136, 20, <del> 248, 251, 21, <add> 248, 136, 21, <ide> 119, 159, 248, 97, 159, 247, 87, 159, 6, <ide> 30, 10, 3, 150, 37, 255, 12, 9, <ide> 139, 12, 10, <ide> Type1Font.prototype = { <ide> <ide> <ide> log("==================== debug ===================="); <add> /* <ide> log("== parse"); <ide> var file = new Uint8Array(cff, 0, currentOffset); <ide> var parser = new Type2Parser(); <ide> parser.parse(new Stream(file)); <add> */ <ide> <ide> var data = []; <ide> for (var i = 0; i < currentOffset; i++) <ide> data.push(cff[i]); <ide> <ide> log("== write to file"); <ide> writeToFile(data, "/tmp/pdf.js.cff"); <add> <add> return data; <add> }, <add> <add> convertToOTF: function(aData, aFont) { <ide> } <ide> }; <ide>
1
Java
Java
use mono.fromdirect for jetty reactiverespnose
2533ba5253ed285c00dd6f883d114eb7a0f3b29f
<ide><path>spring-web/src/main/java/org/springframework/http/client/reactive/JettyClientHttpConnector.java <ide> public Mono<ClientHttpResponse> connect(HttpMethod method, URI uri, <ide> Request request = this.httpClient.newRequest(uri).method(method.toString()); <ide> <ide> return requestCallback.apply(new JettyClientHttpRequest(request, this.bufferFactory)) <del> .then(Mono.from(ReactiveRequest.newBuilder(request).build() <add> .then(Mono.fromDirect(ReactiveRequest.newBuilder(request).build() <ide> .response((reactiveResponse, chunkPublisher) -> { <ide> Flux<DataBuffer> content = Flux.from(chunkPublisher).map(this::toDataBuffer); <ide> return Mono.just(new JettyClientHttpResponse(reactiveResponse, content));
1
Ruby
Ruby
fix support for `homebrew_editor` with args
75aa369102b882e916f35821e57bd4ba1045604d
<ide><path>Library/Homebrew/utils.rb <ide> def which_editor <ide> <ide> def exec_editor(*args) <ide> puts "Editing #{args.join "\n"}" <del> with_homebrew_path { safe_system(which_editor, *args) } <add> with_homebrew_path { safe_system(*which_editor.shellsplit, *args) } <ide> end <ide> <ide> def exec_browser(*args)
1
Text
Text
remove unwanted images
527dd68f0161e8b341c7e4620f0c0866cd47f0e1
<ide><path>guide/english/sql/sql-server-convert-function/index.md <ide> Converts from one data type to another data type. <ide> <ide> `SELECT CONVERT(INT, 23.456) as IntegerNumber` <ide> <del>![convert a decimal number to integer number](https://user-images.githubusercontent.com/12566249/31314884-6c94db4a-ac57-11e7-842f-710fad511131.png) <add> <ide> <ide> Note: The result is truncated. <ide> <ide> ### Example: Convert a String to a Date <ide> `SELECT CONVERT(DATE, '20161030') as Date` <ide> <del>![convert a string to a date type](https://user-images.githubusercontent.com/12566249/31314912-c25bbb52-ac57-11e7-880d-6d81041b1728.png) <add> <ide> <ide> <ide> ### Example: Convert a Decimal to a String <ide> `SELECT CONVERT(nvarchar, 20.123) as StringData` <ide> <del>![convert a decimal to a string](https://user-images.githubusercontent.com/12566249/31314923-fb04e410-ac57-11e7-9646-94061e1f0ec2.png) <add> <ide> <ide> ### Example: Convert an Integer Number to a Decimal Number <ide> `SELECT CONVERT(DECIMAL (15,3), 13) as DecimalNumber` <ide> <del>![convert an integer to a decimal number](https://user-images.githubusercontent.com/12566249/31314932-1c8668ca-ac58-11e7-8cee-4d57fc523704.png) <ide> <ide> ### Example: Convert a String to Date Format in USA Date Style <ide> `SELECT CONVERT(DATE, '20171030' , 110) To_USA_DateFormat` <ide> <del>![convert a string to date format in usa date style](https://user-images.githubusercontent.com/12566249/31314937-35155d06-ac58-11e7-9d5d-823b66c41d0d.png) <ide> <ide> ### More Information: <ide> - Information on Convert function: <a href='https://docs.microsoft.com/en-us/sql/t-sql/functions/cast-and-convert-transact-sql' target='_blank' rel='nofollow'>Microsoft</a>
1
PHP
PHP
add coverage for memory limit increases
0c541b7141f3cc249393363b769599ccc546a1e8
<ide><path>src/Error/BaseErrorHandler.php <ide> public function register() <ide> if ($megabytes === null) { <ide> $megabytes = 4; <ide> } <del> if ($megabytes !== false && $megabytes > 0) { <del> static::increaseMemoryLimit($megabytes * 1024); <add> if ($megabytes > 0) { <add> $this->increaseMemoryLimit($megabytes * 1024); <ide> } <ide> $error = error_get_last(); <ide> if (!is_array($error)) { <ide> public function register() <ide> } <ide> $this->handleFatalError( <ide> $error['type'], <del> $error['message'], <add> $error['message'], <ide> $error['file'], <ide> $error['line'] <ide> ); <ide> public function handleFatalError($code, $description, $file, $line) <ide> /** <ide> * Increases the PHP "memory_limit" ini setting by the specified amount <ide> * in kilobytes <del> * <add> * <ide> * @param string $additionalKb Number in kilobytes <ide> * @return void <ide> */ <del> public static function increaseMemoryLimit($additionalKb) <add> public function increaseMemoryLimit($additionalKb) <ide> { <del> $limit = ini_get("memory_limit"); <del> if (!is_string($limit) || !strlen($limit)) { <add> $limit = ini_get('memory_limit'); <add> if (!strlen($limit) || $limit === '-1') { <ide> return; <ide> } <ide> $limit = trim($limit); <ide> $units = strtoupper(substr($limit, -1)); <ide> $current = substr($limit, 0, strlen($limit) - 1); <del> if ($units === "M") { <add> if ($units === 'M') { <ide> $current = $current * 1024; <del> $units = "K"; <add> $units = 'K'; <ide> } <del> if ($units === "G") { <add> if ($units === 'G') { <ide> $current = $current * 1024 * 1024; <del> $units = "K"; <add> $units = 'K'; <ide> } <ide> <del> if ($units === "K") { <del> ini_set("memory_limit", ceil($current + $additionalKb) . "K"); <add> if ($units === 'K') { <add> ini_set('memory_limit', ceil($current + $additionalKb) . 'K'); <ide> } <ide> } <ide> <ide><path>tests/TestCase/Error/ErrorHandlerTest.php <ide> public function testHandlePHP7Error() <ide> $errorHandler->handleException($error); <ide> $this->assertContains('Unexpected variable foo', $errorHandler->response->body(), 'message missing.'); <ide> } <add> <add> /** <add> * Data provider for memory limit changing. <add> * <add> * @return array <add> */ <add> public function memoryLimitProvider() <add> { <add> return [ <add> // start, adjust, expected <add> ['256M', 4, '262148K'], <add> ['262144K', 4, '262148K'], <add> ['1G', 128, '1048704K'], <add> ]; <add> } <add> <add> /** <add> * Test increasing the memory limit. <add> * <add> * @dataProvider memoryLimitProvider <add> * @return void <add> */ <add> public function testIncreaseMemoryLimit($start, $adjust, $expected) <add> { <add> $initial = ini_get('memory_limit'); <add> $this->skipIf(strlen($initial) === 0, 'Cannot read memory limit, and cannot test increasing it.'); <add> <add> // phpunit.xml often has -1 as memory limit <add> ini_set('memory_limit', $start); <add> <add> $errorHandler = new TestErrorHandler(); <add> $this->assertNull($errorHandler->increaseMemoryLimit($adjust)); <add> $new = ini_get('memory_limit'); <add> $this->assertEquals($expected, $new, 'memory limit did not get increased.'); <add> <add> ini_set('memory_limit', $initial); <add> } <ide> }
2
Text
Text
add comment about ulimit format
9292859fcef2306caeb494ee0eaf0ef98aa190d6
<ide><path>docs/sources/reference/commandline/cli.md <ide> set on the daemon. <ide> > `as` option is disabled now. In other words, the following script is not supported: <ide> > `$ docker run -it --ulimit as=1024 fedora /bin/bash` <ide> <add>The values are sent to the appropriate `syscall` as they are set. <add>Docker doesn't perform any byte conversion. Take this into account when setting the values. <add> <ide> ## save <ide> <ide> Usage: docker save [OPTIONS] IMAGE [IMAGE...]
1
Text
Text
revert the guide after removing varargs from `in?`
62c62bc360bf1ce3db0a11be47a974fcc0777362
<ide><path>guides/source/active_support_core_extensions.md <ide> NOTE: Defined in `active_support/core_ext/kernel/reporting.rb`. <ide> <ide> ### `in?` <ide> <del>The predicate `in?` tests if an object is included in another object or a list of objects. An `ArgumentError` exception will be raised if a single argument is passed and it does not respond to `include?`. <add>The predicate `in?` tests if an object is included in another object. An `ArgumentError` exception will be raised if the argument passed does not respond to `include?`. <ide> <ide> Examples of `in?`: <ide> <ide> ```ruby <del>1.in?(1,2) # => true <ide> 1.in?([1,2]) # => true <ide> "lo".in?("hello") # => true <ide> 25.in?(30..50) # => false
1
Javascript
Javascript
remove last argument in assert.strictequal()
1066b688bf56b490cb46d26d87e7b619037db151
<ide><path>test/addons-napi/test_env_sharing/test.js <ide> const storeEnv = require(`./build/${common.buildType}/store_env`); <ide> const compareEnv = require(`./build/${common.buildType}/compare_env`); <ide> const assert = require('assert'); <ide> <del>assert.strictEqual(compareEnv(storeEnv), true, <del> 'N-API environment pointers in two different modules have ' + <del> 'the same value'); <add>// N-API environment pointers in two different modules have the same value <add>assert.strictEqual(compareEnv(storeEnv), true);
1
Python
Python
fix mypy errors at graph_list
bc09ba9abfa220c893b23969a4b8de05f5ced1e1
<ide><path>graphs/graph_list.py <ide> # Author: OMKAR PATHAK, Nwachukwu Chidiebere <ide> <ide> # Use a Python dictionary to construct the graph. <add>from __future__ import annotations <ide> <ide> from pprint import pformat <add>from typing import Generic, TypeVar <ide> <add>T = TypeVar("T") <ide> <del>class GraphAdjacencyList: <add> <add>class GraphAdjacencyList(Generic[T]): <ide> """ <ide> Adjacency List type Graph Data Structure that accounts for directed and undirected <ide> Graphs. Initialize graph object indicating whether it's directed or undirected. <ide> class GraphAdjacencyList: <ide> 5: [1, 4], <ide> 6: [2], <ide> 7: [2]} <add> >>> char_graph = GraphAdjacencyList(directed=False) <add> >>> char_graph.add_edge('a', 'b') <add> {'a': ['b'], 'b': ['a']} <add> >>> char_graph.add_edge('b', 'c').add_edge('b', 'e').add_edge('b', 'f') <add> {'a': ['b'], 'b': ['a', 'c', 'e', 'f'], 'c': ['b'], 'e': ['b'], 'f': ['b']} <add> >>> print(char_graph) <add> {'a': ['b'], 'b': ['a', 'c', 'e', 'f'], 'c': ['b'], 'e': ['b'], 'f': ['b']} <ide> """ <ide> <del> def __init__(self, directed: bool = True): <add> def __init__(self, directed: bool = True) -> None: <ide> """ <ide> Parameters: <ide> directed: (bool) Indicates if graph is directed or undirected. Default is True. <ide> """ <ide> <del> self.adj_list = {} # dictionary of lists <add> self.adj_list: dict[T, list[T]] = {} # dictionary of lists <ide> self.directed = directed <ide> <del> def add_edge(self, source_vertex: int, destination_vertex: int) -> object: <add> def add_edge( <add> self, source_vertex: T, destination_vertex: T <add> ) -> GraphAdjacencyList[T]: <ide> """ <ide> Connects vertices together. Creates and Edge from source vertex to destination <ide> vertex. <ide> def add_edge(self, source_vertex: int, destination_vertex: int) -> object: <ide> <ide> def __repr__(self) -> str: <ide> return pformat(self.adj_list) <del> <del> <del>if __name__ == "__main__": <del> import doctest <del> <del> doctest.testmod()
1
PHP
PHP
apply suggestions from code review
88b8c8a955e15699661e2f16b5d3eb805a9e4280
<ide><path>src/Error/Debugger.php <ide> public static function exportVar($var, int $maxDepth = 3): string <ide> * @param int $maxDepth The depth to generate nodes to. Defaults to 3. <ide> * @return \Cake\Error\Debug\NodeInterface The root node of the tree. <ide> */ <del> public static function exportNodes($var, int $maxDepth = 3): NodeInterface <add> public static function exportVarAsNodes($var, int $maxDepth = 3): NodeInterface <ide> { <ide> return static::export($var, new DebugContext($maxDepth)); <ide> } <ide><path>tests/TestCase/Error/DebuggerTest.php <ide> public function testExportNodes() <ide> 1 => 'Index one', <ide> 5 => 'Index five', <ide> ]; <del> $result = Debugger::exportNodes($data); <add> $result = Debugger::exportVarAsNodes($data); <ide> $this->assertInstanceOf(NodeInterface::class, $result); <ide> $this->assertCount(2, $result->getChildren()); <ide>
2
PHP
PHP
apply fixes from styleci
cd366a40124818c8a550e5caeeded126025c2b42
<ide><path>src/Illuminate/View/Compilers/ComponentTagCompiler.php <ide> use Illuminate\Contracts\View\Factory; <ide> use Illuminate\Support\Str; <ide> use Illuminate\View\AnonymousComponent; <del>use Illuminate\View\Compilers\BladeCompiler; <ide> use InvalidArgumentException; <ide> use ReflectionClass; <ide>
1
Python
Python
remove class attribute
d7aff47ec72a0796b858613e5c70f9e49699732e
<ide><path>libcloud/compute/drivers/vsphere.py <ide> class VSphereNodeDriver(NodeDriver): <ide> name = 'VMware vSphere' <ide> website = 'http://www.vmware.com/products/vsphere/' <ide> type = Provider.VSPHERE <del> host = '' <ide> <ide> NODE_STATE_MAP = { <ide> 'poweredOn': NodeState.RUNNING, <ide> def __init__(self, host, username, password): <ide> """Initialize a connection by providing a hostname, <ide> username and password <ide> """ <add> self.host = host <ide> try: <ide> self.connection = connect.SmartConnect(host=host, user=username, <ide> pwd=password) <ide> atexit.register(connect.Disconnect, self.connection) <del> self.host = host <ide> except Exception as exc: <ide> error_message = str(exc).lower() <ide> if 'incorrect user name' in error_message:
1
Python
Python
add a placeholder test
82628b0fc921e5e3f250bcad10f2b3c54111c17f
<ide><path>transformers/__init__.py <ide> BertForMaskedLM, BertForNextSentencePrediction, <ide> BertForSequenceClassification, BertForMultipleChoice, <ide> BertForTokenClassification, BertForQuestionAnswering, <del> load_tf_weights_in_bert, BERT_PRETRAINED_MODEL_ARCHIVE_MAP) <add> load_tf_weights_in_bert, BERT_PRETRAINED_MODEL_ARCHIVE_MAP, Bert2Bert) <ide> from .modeling_openai import (OpenAIGPTPreTrainedModel, OpenAIGPTModel, <ide> OpenAIGPTLMHeadModel, OpenAIGPTDoubleHeadsModel, <ide> load_tf_weights_in_openai_gpt, OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_MAP) <ide><path>transformers/tests/modeling_bert_test.py <ide> <ide> if is_torch_available(): <ide> from transformers import (BertConfig, BertModel, BertForMaskedLM, <del> BertForNextSentencePrediction, BertForPreTraining, <del> BertForQuestionAnswering, BertForSequenceClassification, <del> BertForTokenClassification, BertForMultipleChoice) <add> BertForNextSentencePrediction, BertForPreTraining, <add> BertForQuestionAnswering, BertForSequenceClassification, <add> BertForTokenClassification, BertForMultipleChoice, Bert2Bert) <ide> from transformers.modeling_bert import BERT_PRETRAINED_MODEL_ARCHIVE_MAP <ide> else: <ide> pytestmark = pytest.mark.skip("Require Torch") <ide> class BertModelTest(CommonTestCases.CommonModelTester): <ide> <ide> all_model_classes = (BertModel, BertForMaskedLM, BertForNextSentencePrediction, <del> BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification, <del> BertForTokenClassification) if is_torch_available() else () <add> BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification, <add> BertForTokenClassification) if is_torch_available() else () <ide> <ide> class BertModelTester(object): <ide> <ide> def __init__(self, <ide> num_labels=3, <ide> num_choices=4, <ide> scope=None, <del> ): <add> ): <ide> self.parent = parent <ide> self.batch_size = batch_size <ide> self.seq_length = seq_length <ide> def create_and_check_bert_model(self, config, input_ids, token_type_ids, input_m <ide> [self.batch_size, self.seq_length, self.hidden_size]) <ide> self.parent.assertListEqual(list(result["pooled_output"].size()), [self.batch_size, self.hidden_size]) <ide> <del> <ide> def create_and_check_bert_for_masked_lm(self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels): <ide> model = BertForMaskedLM(config=config) <ide> model.eval() <ide> def create_and_check_bert_for_next_sequence_prediction(self, config, input_ids, <ide> [self.batch_size, 2]) <ide> self.check_loss_output(result) <ide> <del> <ide> def create_and_check_bert_for_pretraining(self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels): <ide> model = BertForPreTraining(config=config) <ide> model.eval() <ide> def create_and_check_bert_for_pretraining(self, config, input_ids, token_type_id <ide> [self.batch_size, 2]) <ide> self.check_loss_output(result) <ide> <del> <ide> def create_and_check_bert_for_question_answering(self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels): <ide> model = BertForQuestionAnswering(config=config) <ide> model.eval() <ide> def create_and_check_bert_for_question_answering(self, config, input_ids, token_ <ide> [self.batch_size, self.seq_length]) <ide> self.check_loss_output(result) <ide> <del> <ide> def create_and_check_bert_for_sequence_classification(self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels): <ide> config.num_labels = self.num_labels <ide> model = BertForSequenceClassification(config) <ide> def create_and_check_bert_for_sequence_classification(self, config, input_ids, t <ide> [self.batch_size, self.num_labels]) <ide> self.check_loss_output(result) <ide> <del> <ide> def create_and_check_bert_for_token_classification(self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels): <ide> config.num_labels = self.num_labels <ide> model = BertForTokenClassification(config=config) <ide> def create_and_check_bert_for_token_classification(self, config, input_ids, toke <ide> [self.batch_size, self.seq_length, self.num_labels]) <ide> self.check_loss_output(result) <ide> <del> <ide> def create_and_check_bert_for_multiple_choice(self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels): <ide> config.num_choices = self.num_choices <ide> model = BertForMultipleChoice(config=config) <ide> def create_and_check_bert_for_multiple_choice(self, config, input_ids, token_typ <ide> [self.batch_size, self.num_choices]) <ide> self.check_loss_output(result) <ide> <add> def create_and_check_bert2bert(self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels): <add> config.num_choices = self.num_choices <add> model = Bert2Bert(config=config) <add> model.eval() <add> bert2bert_inputs_ids = input_ids.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous() <add> bert2bert_token_type_ids = token_type_ids.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous() <add> bert2bert_input_mask = input_mask.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous() <add> _ = model(bert2bert_inputs_ids, <add> attention_mask=bert2bert_input_mask, <add> token_type_ids=bert2bert_token_type_ids) <ide> <ide> def prepare_config_and_inputs_for_common(self): <ide> config_and_inputs = self.prepare_config_and_inputs() <ide> def test_model_from_pretrained(self): <ide> shutil.rmtree(cache_dir) <ide> self.assertIsNotNone(model) <ide> <add> <ide> if __name__ == "__main__": <ide> unittest.main()
2
Javascript
Javascript
check inspect array with empty string key
21a3ae35740e8a89395d05c68dd40814264d4bb0
<ide><path>test/parallel/test-util-inspect.js <ide> if (typeof Symbol !== 'undefined') { <ide> assert.strictEqual(util.inspect(x), '{}'); <ide> } <ide> <add>{ <add> const x = []; <add> x[''] = 1; <add> assert.strictEqual(util.inspect(x), '[ \'\': 1 ]'); <add>} <add> <ide> // The following maxArrayLength tests were introduced after v6.0.0 was released. <ide> // Do not backport to v5/v4 unless all of <ide> // https://github.com/nodejs/node/pull/6334 is backported.
1
Text
Text
add a statement in the documentation
50103bff5bf9098d48a41dba9568efb20408768f
<ide><path>doc/api/string_decoder.md <ide> substitution characters appropriate for the character encoding. <ide> <ide> If the `buffer` argument is provided, one final call to `stringDecoder.write()` <ide> is performed before returning the remaining input. <add>After `end()` is called, the `stringDecoder` object can be reused for new input. <ide> <ide> ### `stringDecoder.write(buffer)` <ide> <!-- YAML
1
Python
Python
remove extraeneous spaces
4faea59a79bd6a038b964619560646d56ed66577
<ide><path>research/object_detection/models/faster_rcnn_resnet_v1_fpn_keras_feature_extractor.py <ide> def get_proposal_feature_extractor_model(self, name=None): <ide> self._conv_hyperparams.build_activation_layer( <ide> name=layer_name)) <ide> self._coarse_feature_layers.append(layers) <del> <add> <ide> feature_maps = [] <ide> for level in range(self._fpn_min_level, self._base_fpn_max_level + 1): <ide> feature_maps.append(fpn_features['top_down_block{}'.format(level-1)])
1
Go
Go
add test for force-new-cluster
1acb8ef82572c52994b1ff00fe5c86aac53be4b8
<ide><path>integration-cli/docker_api_swarm_test.go <ide> func (s *DockerSwarmSuite) TestApiSwarmPromoteDemote(c *check.C) { <ide> break <ide> } <ide> if i > 100 { <del> c.Errorf("node did not turn into manager") <add> c.Errorf("node did not turn into worker") <ide> } else { <ide> break <ide> } <ide> func (s *DockerSwarmSuite) TestApiSwarmInvalidAddress(c *check.C) { <ide> c.Assert(status, checker.Equals, http.StatusInternalServerError) <ide> } <ide> <add>func (s *DockerSwarmSuite) TestApiSwarmForceNewCluster(c *check.C) { <add> d1 := s.AddDaemon(c, true, true) <add> d2 := s.AddDaemon(c, true, true) <add> <add> instances := 2 <add> id := d1.createService(c, simpleTestService, setInstances(instances)) <add> waitAndAssert(c, defaultReconciliationTimeout, reducedCheck(sumAsIntegers, d1.checkActiveContainerCount, d2.checkActiveContainerCount), checker.Equals, instances) <add> <add> c.Assert(d2.Stop(), checker.IsNil) <add> <add> time.Sleep(5 * time.Second) <add> <add> c.Assert(d1.Init(swarm.InitRequest{ <add> ForceNewCluster: true, <add> Spec: swarm.Spec{ <add> AcceptancePolicy: autoAcceptPolicy, <add> }, <add> }), checker.IsNil) <add> <add> waitAndAssert(c, defaultReconciliationTimeout, d1.checkActiveContainerCount, checker.Equals, instances) <add> <add> d3 := s.AddDaemon(c, true, true) <add> info, err := d3.info() <add> c.Assert(err, checker.IsNil) <add> c.Assert(info.ControlAvailable, checker.Equals, true) <add> c.Assert(info.LocalNodeState, checker.Equals, swarm.LocalNodeStateActive) <add> <add> instances = 4 <add> d3.updateService(c, d3.getService(c, id), setInstances(instances)) <add> <add> waitAndAssert(c, defaultReconciliationTimeout, reducedCheck(sumAsIntegers, d1.checkActiveContainerCount, d3.checkActiveContainerCount), checker.Equals, instances) <add>} <add> <ide> func simpleTestService(s *swarm.Service) { <ide> var ureplicas uint64 <ide> ureplicas = 1
1
Go
Go
fix docker rmi via id
5a934fc923af316a6e82b9dd11169484b3b744f6
<ide><path>server.go <ide> func (srv *Server) deleteImageAndChildren(id string, imgs *[]APIRmi) error { <ide> if len(srv.runtime.repositories.ByID()[id]) != 0 { <ide> return ErrImageReferenced <ide> } <del> <ide> // If the image is not referenced but has children, go recursive <ide> referenced := false <ide> byParents, err := srv.runtime.graph.ByParent() <ide> func (srv *Server) deleteImageParents(img *Image, imgs *[]APIRmi) error { <ide> } <ide> <ide> func (srv *Server) deleteImage(img *Image, repoName, tag string) ([]APIRmi, error) { <del> //Untag the current image <ide> imgs := []APIRmi{} <add> <add> //If delete by id, see if the id belong only to one repository <add> if strings.Contains(img.ID, repoName) && tag == "" { <add> for _, repoAndTag := range srv.runtime.repositories.ByID()[img.ID] { <add> parsedRepo := strings.Split(repoAndTag, ":")[0] <add> if strings.Contains(img.ID, repoName) { <add> repoName = parsedRepo <add> } else if repoName != parsedRepo { <add> // the id belongs to multiple repos, like base:latest and user:test, <add> // in that case return conflict <add> return imgs, nil <add> } <add> } <add> } <add> //Untag the current image <ide> tagDeleted, err := srv.runtime.repositories.Delete(repoName, tag) <ide> if err != nil { <ide> return nil, err
1
Ruby
Ruby
remove unnecessary require
5ec52ea4da260d2f7abfc765fdcd2819076bd212
<ide><path>Library/Homebrew/test/testing_env.rb <ide> def shutup <ide> <ide> require 'test/unit' # must be after at_exit <ide> require 'extend/ARGV' # needs to be after test/unit to avoid conflict with OptionsParser <del>require 'extend/ENV' <ide> ARGV.extend(HomebrewArgvExtension) <ide> <ide> begin
1
PHP
PHP
correct url generation
22471c4da005b936da686656d7e199fe82788edf
<ide><path>src/View/Helper/PaginatorHelper.php <ide> public function generateUrl(array $options = array(), $model = null, $full = fal <ide> ]; <ide> <ide> if (!empty($this->_config['options']['url'])) { <del> $url = array_merge($this->_config['options']['url'], $url); <add> $url = array_merge($url, $this->_config['options']['url']); <ide> } <ide> $url = array_merge(array_filter($url), $options); <ide>
1
Javascript
Javascript
fix bug with unref var
8db37875445e3fc664b79261f14c222a152709d1
<ide><path>pdf.js <ide> var IndexedCS = (function() { <ide> return this.base.getRgb(c); <ide> }, <ide> getRgbBuffer: function indexcs_getRgbBuffer(input) { <add> var base = this.base; <ide> var numComps = base.numComps; <ide> var lookup = this.lookup; <ide> var length = input.length; <ide> var IndexedCS = (function() { <ide> } <ide> } <ide> <del> return this.base.getRgbBuffer(baseBuf); <add> return base.getRgbBuffer(baseBuf); <ide> } <ide> }; <ide> return constructor;
1
Text
Text
add changelog entry for
dbf6dbb147903bb1af497eb6c8da1cb9310aa435
<ide><path>activesupport/CHANGELOG.md <add>* Raises an `ArgumentError` when the first argument of `ActiveSupport::Notification.subscribe` is <add> invalid. <add> <add> *Vipul A M* <add> <ide> * `HashWithIndifferentAccess#deep_transform_keys` now returns a `HashWithIndifferentAccess` instead of a `Hash`. <ide> <ide> *Nathaniel Woodthorpe*
1
Java
Java
fix javadoc in pathpattern
0636ba68d76727daba0e7a54ff06d447f33c5225
<ide><path>spring-web/src/main/java/org/springframework/web/util/pattern/PathPattern.java <ide> * <li><code>/resources/{&#42;path}</code> &mdash; matches all files <ide> * underneath the {@code /resources/} path and captures their relative path in <ide> * a variable named "path"; {@code /resources/image.png} will match with <del> * "spring" &rarr; "/image.png", and {@code /resources/css/spring.css} will match <del> * with "spring" &rarr; "/css/spring.css"</li> <add> * "path" &rarr; "/image.png", and {@code /resources/css/spring.css} will match <add> * with "path" &rarr; "/css/spring.css"</li> <ide> * <li><code>/resources/{filename:\\w+}.dat</code> will match {@code /resources/spring.dat} <ide> * and assign the value {@code "spring"} to the {@code filename} variable</li> <ide> * </ul>
1
Text
Text
add iarna to collaborators
7b09aade8468e1c930f36b9c81e6ac2ed5bc8732
<ide><path>README.md <ide> information about the governance of the Node.js project, see <ide> * [domenic](https://github.com/domenic) - **Domenic Denicola** &lt;d@domenic.me&gt; <ide> * [evanlucas](https://github.com/evanlucas) - **Evan Lucas** &lt;evanlucas@me.com&gt; <ide> * [geek](https://github.com/geek) - **Wyatt Preul** &lt;wpreul@gmail.com&gt; <add>* [iarna](https://github.com/iarna) - **Rebecca Turner** &lt;me@re-becca.org&gt; <ide> * [isaacs](https://github.com/isaacs) - **Isaac Z. Schlueter** &lt;i@izs.me&gt; <ide> * [jbergstroem](https://github.com/jbergstroem) - **Johan Bergström** &lt;bugs@bergstroem.nu&gt; <ide> * [joaocgreis](https://github.com/joaocgreis) - **João Reis** &lt;reis@janeasystems.com&gt;
1
PHP
PHP
remove options retrieving from broadcaster
16ed752928a59e0b3003ab54675fcb3096b23d96
<ide><path>src/Illuminate/Broadcasting/Broadcasters/Broadcaster.php <ide> public function channel($channel, $callback, array $options = []) <ide> * @return mixed <ide> * @throws \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException <ide> */ <del> protected function verifyUserCanAccessChannel($request, $channel) <add> protected function verifyUserCanAccessChannel($request, $channel, $options = []) <ide> { <del> $options = []; <del> <del> foreach ($this->channelsOptions as $pattern => $opts) { <del> if (! Str::is(preg_replace('/\{(.*?)\}/', '*', $pattern), $channel)) { <del> continue; <del> } <del> <del> $options = $opts; <del> } <del> <del> <ide> foreach ($this->channels as $pattern => $callback) { <ide> if (! Str::is(preg_replace('/\{(.*?)\}/', '*', $pattern), $channel)) { <ide> continue; <ide> protected function verifyUserCanAccessChannel($request, $channel) <ide> $handler = $this->normalizeChannelHandlerToCallable($callback); <ide> <ide> if ($result = $handler($request->user($options['guard'] ?? null), ...$parameters)) { <del> return $this->validAuthenticationResponse($request, $result); <add> return $this->validAuthenticationResponse($request, $result, $options); <ide> } <ide> } <ide>
1
PHP
PHP
fix validator docblock
45bd699fd8a37148bc5a9dfbebce722b4d17d436
<ide><path>src/Illuminate/Validation/Validator.php <ide> protected function validateImage($attribute, $value) <ide> * Validate the MIME type of a file upload attribute is in a set of MIME types. <ide> * <ide> * @param string $attribute <del> * @param array $value <add> * @param mixed $value <ide> * @param array $parameters <ide> * @return bool <ide> */
1
Python
Python
ensure closables in request.files get closed.
6d4d4dfd046e85253194f6bfe33574c080abf432
<ide><path>rest_framework/request.py <ide> def _load_data_and_files(self): <ide> else: <ide> self._full_data = self._data <ide> <add> # copy files refs to the underlying request so that closable <add> # objects are handled appropriately. <add> self._request._files = self._files <add> <ide> def _load_stream(self): <ide> """ <ide> Return the content body of the request, as a stream. <ide><path>tests/test_fields.py <ide> class TestDateTimeField(FieldValues): <ide> valid_inputs = { <ide> '2001-01-01 13:00': datetime.datetime(2001, 1, 1, 13, 00, tzinfo=utc), <ide> '2001-01-01T13:00': datetime.datetime(2001, 1, 1, 13, 00, tzinfo=utc), <del> '2001-01-01T13:00Z': datetime.datetime(2001, 1, 1, 13, 00, tzinfo=utc) <add> '2001-01-01T13:00Z': datetime.datetime(2001, 1, 1, 13, 00, tzinfo=utc), <ide> datetime.datetime(2001, 1, 1, 13, 00): datetime.datetime(2001, 1, 1, 13, 00, tzinfo=utc), <ide> datetime.datetime(2001, 1, 1, 13, 00, tzinfo=utc): datetime.datetime(2001, 1, 1, 13, 00, tzinfo=utc), <ide> } <ide><path>tests/test_request.py <ide> """ <ide> from __future__ import unicode_literals <ide> <add>import os.path <add>import tempfile <add> <ide> from django.conf.urls import url <ide> from django.contrib.auth import authenticate, login, logout <ide> from django.contrib.auth.models import User <ide> def post(self, request): <ide> <ide> return Response(status=status.HTTP_500_INTERNAL_SERVER_ERROR) <ide> <add> <add>class FileUploadView(APIView): <add> def post(self, request): <add> filenames = [file.temporary_file_path() for file in request.FILES.values()] <add> <add> for filename in filenames: <add> assert os.path.exists(filename) <add> <add> return Response(status=status.HTTP_200_OK, data=filenames) <add> <add> <ide> urlpatterns = [ <ide> url(r'^$', MockView.as_view()), <add> url(r'^upload/$', FileUploadView.as_view()) <ide> ] <ide> <ide> <add>@override_settings( <add> ROOT_URLCONF='tests.test_request', <add> FILE_UPLOAD_HANDLERS=['django.core.files.uploadhandler.TemporaryFileUploadHandler']) <add>class FileUploadTests(TestCase): <add> <add> def test_fileuploads_closed_at_request_end(self): <add> with tempfile.NamedTemporaryFile() as f: <add> response = self.client.post('/upload/', {'file': f}) <add> <add> # sanity check that file was processed <add> assert len(response.data) == 1 <add> <add> for file in response.data: <add> assert not os.path.exists(file) <add> <add> <ide> @override_settings(ROOT_URLCONF='tests.test_request') <ide> class TestContentParsingWithAuthentication(TestCase): <ide> def setUp(self):
3
PHP
PHP
remove undefined parameters from docblocks
f493e7a0878c9145b9dda1c8854732c80d84eacc
<ide><path>src/Illuminate/Contracts/Bus/Dispatcher.php <ide> interface Dispatcher <ide> * Dispatch a command to its appropriate handler. <ide> * <ide> * @param mixed $command <del> * @param \Closure|null $afterResolving <ide> * @return mixed <ide> */ <ide> public function dispatch($command); <ide> public function dispatch($command); <ide> * Dispatch a command to its appropriate handler in the current process. <ide> * <ide> * @param mixed $command <del> * @param \Closure|null $afterResolving <ide> * @return mixed <ide> */ <ide> public function dispatchNow($command);
1
Text
Text
move correct example to the top
6f1f8627ee3becdcedd90d909ccda9b830ac9bf3
<ide><path>docs/recipes/structuring-reducers/ImmutableUpdatePatterns.md <ide> The articles listed in [Prerequisite Concepts#Immutable Data Management](Prerequ <ide> <ide> The key to updating nested data is **that _every_ level of nesting must be copied and updated appropriately**. This is often a difficult concept for those learning Redux, and there are some specific problems that frequently occur when trying to update nested objects. These lead to accidental direct mutation, and should be avoided. <ide> <add>##### Correct Approach: Copying All Levels of Nested Data <add> <add>Unfortunately, the process of correctly applying immutable updates to deeply nested state can easily become verbose and hard to read. Here's what an example of updating `state.first.second[someId].fourth` might look like: <add> <add>```js <add>function updateVeryNestedField(state, action) { <add> return { <add> ...state, <add> first: { <add> ...state.first, <add> second: { <add> ...state.first.second, <add> [action.someId]: { <add> ...state.first.second[action.someId], <add> fourth: action.someValue <add> } <add> } <add> } <add> } <add>} <add>``` <add> <add>Obviously, each layer of nesting makes this harder to read, and gives more chances to make mistakes. This is one of several reasons why you are encouraged to keep your state flattened, and compose reducers as much as possible. <add> <ide> ##### Common Mistake #1: New variables that point to the same objects <ide> <ide> Defining a new variable does _not_ create a new actual object - it only creates another reference to the same object. An example of this error would be: <ide> function updateNestedState(state, action) { <ide> <ide> Doing a shallow copy of the top level is _not_ sufficient - the `nestedState` object should be copied as well. <ide> <del>##### Correct Approach: Copying All Levels of Nested Data <del> <del>Unfortunately, the process of correctly applying immutable updates to deeply nested state can easily become verbose and hard to read. Here's what an example of updating `state.first.second[someId].fourth` might look like: <del> <del>```js <del>function updateVeryNestedField(state, action) { <del> return { <del> ...state, <del> first: { <del> ...state.first, <del> second: { <del> ...state.first.second, <del> [action.someId]: { <del> ...state.first.second[action.someId], <del> fourth: action.someValue <del> } <del> } <del> } <del> } <del>} <del>``` <del> <del>Obviously, each layer of nesting makes this harder to read, and gives more chances to make mistakes. This is one of several reasons why you are encouraged to keep your state flattened, and compose reducers as much as possible. <del> <ide> ## Inserting and Removing Items in Arrays <ide> <ide> Normally, a Javascript array's contents are modified using mutative functions like `push`, `unshift`, and `splice`. Since we don't want to mutate state directly in reducers, those should normally be avoided. Because of that, you might see "insert" or "remove" behavior written like this:
1
Javascript
Javascript
remove getmaxprecision from webglstate
42520325677e0ae51c157e87ffd0c065ff8770c6
<ide><path>src/renderers/webgl/WebGLState.js <ide> THREE.WebGLState = function ( gl, extensions, paramThreeToGL ) { <ide> <ide> }; <ide> <del> this.getMaxPrecision = function ( precision ) { <del> <del> if ( precision === 'highp' ) { <del> <del> if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.HIGH_FLOAT ).precision > 0 && <del> gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.HIGH_FLOAT ).precision > 0 ) { <del> <del> return 'highp'; <del> <del> } <del> <del> precision = 'mediump'; <del> <del> } <del> <del> if ( precision === 'mediump' ) { <del> <del> if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.MEDIUM_FLOAT ).precision > 0 && <del> gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT ).precision > 0 ) { <del> <del> return 'mediump'; <del> <del> } <del> <del> } <del> <del> return 'lowp'; <del> <del> }; <del> <ide> this.setBlending = function ( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha ) { <ide> <ide> if ( blending !== currentBlending ) {
1
Python
Python
print a stacktrace on cli error (closes )
5b7fd9ad889e54d4d694d310b559c921d7df75cf
<ide><path>flask/cli.py <ide> <ide> import os <ide> import sys <add>import traceback <ide> from threading import Lock, Thread <ide> from functools import update_wrapper <ide> <ide> def list_commands(self, ctx): <ide> # want the help page to break if the app does not exist. <ide> # If someone attempts to use the command we try to create <ide> # the app again and this will give us the error. <add> # However, we will not do so silently because that would confuse <add> # users. <add> traceback.print_exc() <ide> pass <ide> return sorted(rv) <ide>
1
Mixed
Javascript
support uint8array input to methods
627ecee9edd9df247e7541ee8084d925f85ede7f
<ide><path>doc/api/child_process.md <ide> added: v0.11.12 <ide> * `args` {Array} List of string arguments <ide> * `options` {Object} <ide> * `cwd` {String} Current working directory of the child process <del> * `input` {String|Buffer} The value which will be passed as stdin to the <del> spawned process <add> * `input` {String|Buffer|Uint8Array} The value which will be passed as stdin <add> to the spawned process <ide> - supplying this value will override `stdio[0]` <ide> * `stdio` {String | Array} Child's stdio configuration. (Default: `'pipe'`) <ide> - `stderr` by default will be output to the parent process' stderr unless <ide> added: v0.11.12 <ide> * `command` {String} The command to run <ide> * `options` {Object} <ide> * `cwd` {String} Current working directory of the child process <del> * `input` {String|Buffer} The value which will be passed as stdin to the <del> spawned process <add> * `input` {String|Buffer|Uint8Array} The value which will be passed as stdin <add> to the spawned process <ide> - supplying this value will override `stdio[0]` <ide> * `stdio` {String | Array} Child's stdio configuration. (Default: `'pipe'`) <ide> - `stderr` by default will be output to the parent process' stderr unless <ide> added: v0.11.12 <ide> * `args` {Array} List of string arguments <ide> * `options` {Object} <ide> * `cwd` {String} Current working directory of the child process <del> * `input` {String|Buffer} The value which will be passed as stdin to the <del> spawned process <add> * `input` {String|Buffer|Uint8Array} The value which will be passed as stdin <add> to the spawned process <ide> - supplying this value will override `stdio[0]` <ide> * `stdio` {String | Array} Child's stdio configuration. <ide> * `env` {Object} Environment key-value pairs <ide><path>lib/child_process.js <ide> const uv = process.binding('uv'); <ide> const spawn_sync = process.binding('spawn_sync'); <ide> const Buffer = require('buffer').Buffer; <ide> const Pipe = process.binding('pipe_wrap').Pipe; <add>const { isUint8Array } = process.binding('util'); <ide> const child_process = require('internal/child_process'); <ide> <ide> const errnoException = util._errnoException; <ide> function spawnSync(/*file, args, options*/) { <ide> var input = options.stdio[i] && options.stdio[i].input; <ide> if (input != null) { <ide> var pipe = options.stdio[i] = util._extend({}, options.stdio[i]); <del> if (Buffer.isBuffer(input)) <add> if (isUint8Array(input)) <ide> pipe.input = input; <ide> else if (typeof input === 'string') <ide> pipe.input = Buffer.from(input, options.encoding); <ide> else <ide> throw new TypeError(util.format( <del> 'stdio[%d] should be Buffer or string not %s', <add> 'stdio[%d] should be Buffer, Uint8Array or string not %s', <ide> i, <ide> typeof input)); <ide> } <ide><path>lib/internal/child_process.js <ide> 'use strict'; <ide> <ide> const StringDecoder = require('string_decoder').StringDecoder; <del>const Buffer = require('buffer').Buffer; <ide> const EventEmitter = require('events'); <ide> const net = require('net'); <ide> const dgram = require('dgram'); <ide> const TTY = process.binding('tty_wrap').TTY; <ide> const TCP = process.binding('tcp_wrap').TCP; <ide> const UDP = process.binding('udp_wrap').UDP; <ide> const SocketList = require('internal/socket_list'); <add>const { isUint8Array } = process.binding('util'); <ide> <ide> const errnoException = util._errnoException; <ide> const SocketListSend = SocketList.SocketListSend; <ide> function _validateStdio(stdio, sync) { <ide> wrapType: getHandleWrapType(handle), <ide> handle: handle <ide> }); <del> } else if (stdio instanceof Buffer || typeof stdio === 'string') { <add> } else if (isUint8Array(stdio) || typeof stdio === 'string') { <ide> if (!sync) { <ide> cleanup(); <del> throw new TypeError('Asynchronous forks do not support Buffer input: ' + <add> throw new TypeError('Asynchronous forks do not support ' + <add> 'Buffer, Uint8Array or string input: ' + <ide> util.inspect(stdio)); <ide> } <ide> } else { <ide><path>test/parallel/test-child-process-spawnsync-input.js <ide> var options = { <ide> <ide> assert.throws(function() { <ide> spawnSync('cat', [], options); <del>}, /TypeError:.*should be Buffer or string not number/); <add>}, /TypeError:.*should be Buffer, Uint8Array or string not number/); <ide> <ide> <ide> options = { <ide> checkSpawnSyncRet(ret); <ide> assert.deepStrictEqual(ret.stdout, options.input); <ide> assert.deepStrictEqual(ret.stderr, Buffer.from('')); <ide> <add>options = { <add> input: Uint8Array.from(Buffer.from('hello world')) <add>}; <add> <add>ret = spawnSync('cat', [], options); <add> <add>checkSpawnSyncRet(ret); <add>assert.deepStrictEqual(ret.stdout, options.input); <add>assert.deepStrictEqual(ret.stderr, Buffer.from('')); <add> <ide> verifyBufOutput(spawnSync(process.execPath, args)); <ide> <ide> ret = spawnSync(process.execPath, args, { encoding: 'utf8' });
4
Text
Text
enclose a value of variable in back quote
f0a7b5df642b376a80f6ded3bea886826d55a45f
<ide><path>docs/docs/07-forms.md <ide> Using form components such as `<input>` in React presents a challenge that is ab <ide> <input type="text" name="title" value="Untitled" /> <ide> ``` <ide> <del>This renders an input *initialized* with the value, `Untitled`. When the user updates the input, the node's value *property* will change. However, `node.getAttribute('value')` will still return the value used at initialization time, `Untitled`. <add>This renders an input *initialized* with the value, `Untitled`. When the user updates the input, the node's `value` *property* will change. However, `node.getAttribute('value')` will still return the value used at initialization time, `Untitled`. <ide> <ide> Unlike HTML, React components must represent the state of the view at any point in time and not only at initialization time. For example, in React: <ide>
1
Javascript
Javascript
fix the combineurl function
220a8e4f0e8690c0ab9a0ad8e34edc176febb716
<ide><path>src/shared/util.js <ide> function combineUrl(baseUrl, url) { <ide> if (url.charAt(0) == '/') { <ide> // absolute path <ide> var i = baseUrl.indexOf('://'); <del> i = baseUrl.indexOf('/', i + 3); <add> if (url.charAt(1) === '/') { <add> ++i; <add> } else { <add> i = baseUrl.indexOf('/', i + 3); <add> } <ide> return baseUrl.substring(0, i) + url; <ide> } else { <ide> // relative path
1
Javascript
Javascript
simplify constructor retrieval in inspect()
f43d1ca3b0edf4181aaa4943e859a5875c5855a8
<ide><path>lib/internal/util/inspect.js <ide> const { <ide> Array, <ide> ArrayIsArray, <del> BigInt64Array, <ide> BigIntPrototypeValueOf, <del> BigUint64Array, <ide> BooleanPrototypeValueOf, <ide> DatePrototypeGetTime, <ide> DatePrototypeToISOString, <ide> DatePrototypeToString, <ide> ErrorPrototypeToString, <del> Float32Array, <del> Float64Array, <ide> FunctionPrototypeCall, <ide> FunctionPrototypeToString, <del> Int8Array, <del> Int16Array, <del> Int32Array, <ide> JSONStringify, <ide> Map, <ide> MapPrototypeGetSize, <ide> const { <ide> SymbolIterator, <ide> SymbolToStringTag, <ide> TypedArrayPrototypeGetLength, <del> Uint16Array, <del> Uint32Array, <add> TypedArrayPrototypeGetSymbolToStringTag, <ide> Uint8Array, <del> Uint8ClampedArray, <ide> uncurryThis, <ide> } = primordials; <ide> <ide> const { <ide> isNumberObject, <ide> isBooleanObject, <ide> isBigIntObject, <del> isUint8Array, <del> isUint8ClampedArray, <del> isUint16Array, <del> isUint32Array, <del> isInt8Array, <del> isInt16Array, <del> isInt32Array, <del> isFloat32Array, <del> isFloat64Array, <del> isBigInt64Array, <del> isBigUint64Array <ide> } = require('internal/util/types'); <ide> <ide> const assert = require('internal/assert'); <ide> function formatProxy(ctx, proxy, recurseTimes) { <ide> ctx, res, '', ['Proxy [', ']'], kArrayExtrasType, recurseTimes); <ide> } <ide> <del>function findTypedConstructor(value) { <del> for (const [check, clazz] of [ <del> [isUint8Array, Uint8Array], <del> [isUint8ClampedArray, Uint8ClampedArray], <del> [isUint16Array, Uint16Array], <del> [isUint32Array, Uint32Array], <del> [isInt8Array, Int8Array], <del> [isInt16Array, Int16Array], <del> [isInt32Array, Int32Array], <del> [isFloat32Array, Float32Array], <del> [isFloat64Array, Float64Array], <del> [isBigInt64Array, BigInt64Array], <del> [isBigUint64Array, BigUint64Array] <del> ]) { <del> if (check(value)) { <del> return clazz; <del> } <del> } <del>} <del> <ide> // Note: using `formatValue` directly requires the indentation level to be <ide> // corrected by setting `ctx.indentationLvL += diff` and then to decrease the <ide> // value afterwards again. <ide> function formatRaw(ctx, value, recurseTimes, typedArray) { <ide> let bound = value; <ide> let fallback = ''; <ide> if (constructor === null) { <del> const constr = findTypedConstructor(value); <del> fallback = constr.name; <add> fallback = TypedArrayPrototypeGetSymbolToStringTag(value); <ide> // Reconstruct the array information. <del> bound = new constr(value); <add> bound = new primordials[fallback](value); <ide> } <ide> const size = TypedArrayPrototypeGetLength(value); <ide> const prefix = getPrefix(constructor, tag, fallback, `(${size})`);
1
Text
Text
add a link to the metrics document
8a8ef43ffcf8d95d2880da073bbcee73e51aad48
<ide><path>docs/templates/getting-started/sequential-model-guide.md <ide> Before training a model, you need to configure the learning process, which is do <ide> <ide> - An optimizer. This could be the string identifier of an existing optimizer (such as `rmsprop` or `adagrad`), or an instance of the `Optimizer` class. See: [optimizers](/optimizers). <ide> - A loss function. This is the objective that the model will try to minimize. It can be the string identifier of an existing loss function (such as `categorical_crossentropy` or `mse`), or it can be an objective function. See: [losses](/losses). <del>- A list of metrics. For any classification problem you will want to set this to `metrics=['accuracy']`. A metric could be the string identifier of an existing metric or a custom metric function. <add>- A list of metrics. For any classification problem you will want to set this to `metrics=['accuracy']`. A metric could be the string identifier of an existing metric or a custom metric function. See: [metrics](/metrics). <ide> <ide> ```python <ide> # For a multi-class classification problem
1
Javascript
Javascript
add jsdoc for the copy() method
7cb7fb91c673c006612c38a2ef07d850f642c8df
<ide><path>src/Angular.js <ide> function isLeafNode (node) { <ide> return false; <ide> } <ide> <add>/** <add> * Copies stuff. <add> * <add> * If destination is not provided and source is an object or an array, a copy is created & returned, <add> * otherwise the source is returned. <add> * <add> * If destination is provided, all of its properties will be deleted and if source is an object or <add> * an array, all of its members will be copied into the destination object. Finally the destination <add> * is returned just for kicks. <add> * <add> * @param {*} source The source to be used during copy. <add> * Can be any type including primitives, null and undefined. <add> * @param {(Object|Array)=} destination Optional destination into which the source is copied <add> * @return {*} <add> */ <ide> function copy(source, destination){ <ide> if (!destination) { <ide> if (source) {
1
Go
Go
inspect changes to a container's filesystem
bdb66012a830e06103d0ed6913c38bbc69a09bca
<ide><path>dockerd/dockerd.go <ide> import ( <ide> "text/tabwriter" <ide> "sort" <ide> "os" <add> "archive/tar" <ide> ) <ide> <ide> func (docker *Docker) CmdHelp(stdin io.ReadCloser, stdout io.Writer, args ...string) error { <ide> func (docker *Docker) CmdHelp(stdin io.ReadCloser, stdout io.Writer, args ...str <ide> {"wait", "Wait for the state of a container to change"}, <ide> {"stop", "Stop a running container"}, <ide> {"logs", "Fetch the logs of a container"}, <del> {"export", "Extract changes to a container's filesystem into a new layer"}, <add> {"diff", "Inspect changes on a container's filesystem"}, <ide> {"attach", "Attach to the standard inputs and outputs of a running container"}, <ide> {"info", "Display system-wide information"}, <ide> {"web", "Generate a web UI"}, <ide> func (docker *Docker) CmdPut(stdin io.ReadCloser, stdout io.Writer, args ...stri <ide> return nil <ide> } <ide> <del>func (docker *Docker) CmdExport(stdin io.ReadCloser, stdout io.Writer, args ...string) error { <add>func (docker *Docker) CmdDiff(stdin io.ReadCloser, stdout io.Writer, args ...string) error { <ide> flags := Subcmd(stdout, <del> "export", "CONTAINER LAYER", <del> "Create a new layer from the changes on a container's filesystem") <del> _ = flags.Bool("s", false, "Stream the new layer to the client intead of storing it on the docker") <add> "diff", "CONTAINER [OPTIONS]", <add> "Inspect changes on a container's filesystem") <add> fl_bytes := flags.Bool("b", false, "Show how many bytes have been changes") <add> fl_list := flags.Bool("l", false, "Show a list of changed files") <add> fl_download := flags.Bool("d", false, "Download the changes as gzipped tar stream") <add> fl_create := flags.String("c", "", "Create a new layer from the changes") <ide> if err := flags.Parse(args); err != nil { <ide> return nil <ide> } <del> if flags.NArg() < 2 { <add> if flags.NArg() < 1 { <ide> return errors.New("Not enough arguments") <ide> } <add> if !(*fl_bytes || *fl_list || *fl_download || *fl_create != "") { <add> flags.Usage() <add> return nil <add> } <ide> if container, exists := docker.containers[flags.Arg(0)]; !exists { <ide> return errors.New("No such container") <del> } else { <del> // Extract actual changes here <del> layer := docker.addLayer(flags.Arg(1), "export:" + container.Id, container.BytesChanged) <add> } else if *fl_bytes { <add> if *fl_list || *fl_download || *fl_create != "" { <add> flags.Usage() <add> return nil <add> } <add> fmt.Fprintf(stdout, "%d\n", container.BytesChanged) <add> } else if *fl_list { <add> if *fl_bytes || *fl_download || *fl_create != "" { <add> flags.Usage() <add> return nil <add> } <add> // FAKE <add> fmt.Fprintf(stdout, strings.Join([]string{ <add> "/etc/postgres/pg.conf", <add> "/etc/passwd", <add> "/var/lib/postgres", <add> "/usr/bin/postgres", <add> "/usr/bin/psql", <add> "/var/log/postgres", <add> "/var/log/postgres/postgres.log", <add> "/var/log/postgres/postgres.log.0", <add> "/var/log/postgres/postgres.log.1.gz"}, "\n")) <add> } else if *fl_download { <add> if *fl_bytes || *fl_list || *fl_create != "" { <add> flags.Usage() <add> return nil <add> } <add> if data, err := FakeTar(); err != nil { <add> return err <add> } else if _, err := io.Copy(stdout, data); err != nil { <add> return err <add> } <add> return nil <add> } else if *fl_create != "" { <add> if *fl_bytes || *fl_list || *fl_download { <add> flags.Usage() <add> return nil <add> } <add> layer := docker.addLayer(*fl_create, "export:" + container.Id, container.BytesChanged) <ide> fmt.Fprintln(stdout, layer.Id) <add> } else { <add> flags.Usage() <add> return nil <ide> } <ide> return nil <ide> } <ide> func Subcmd(output io.Writer, name, signature, description string) *flag.FlagSet <ide> return flags <ide> } <ide> <add> <add>func FakeTar() (io.Reader, error) { <add> content := []byte("Hello world!\n") <add> buf := new(bytes.Buffer) <add> tw := tar.NewWriter(buf) <add> for _, name := range []string {"/etc/postgres/postgres.conf", "/etc/passwd", "/var/log/postgres", "/var/log/postgres/postgres.conf"} { <add> hdr := new(tar.Header) <add> hdr.Size = int64(len(content)) <add> hdr.Name = name <add> if err := tw.WriteHeader(hdr); err != nil { <add> return nil, err <add> } <add> tw.Write([]byte(content)) <add> } <add> tw.Close() <add> return buf, nil <add>}
1
Ruby
Ruby
remove autocorrection of some urls
1c2d76c4e4903322197c3cf854188e31d5a41838
<ide><path>Library/Homebrew/rubocops/patches.rb <ide> def patch_problems(patch_url_node) <ide> end <ide> <ide> if regex_match_group(patch_url_node, %r{https://github.com/[^/]*/[^/]*/commit/[a-fA-F0-9]*\.diff}) <del> problem "GitHub patches should end with .patch, not .diff: #{patch_url}" do |corrector| <del> correct = patch_url_node.source.gsub(/\.diff/, ".patch") <del> corrector.replace(patch_url_node.source_range, correct) <del> end <add> problem "GitHub patches should end with .patch, not .diff: #{patch_url}" <ide> end <ide> <ide> if regex_match_group(patch_url_node, %r{.*gitlab.*/commit/[a-fA-F0-9]*\.diff}) <del> problem "GitLab patches should end with .patch, not .diff: #{patch_url}" do |corrector| <del> correct = patch_url_node.source.gsub(/\.diff/, ".patch") <del> corrector.replace(patch_url_node.source_range, correct) <del> end <add> problem "GitLab patches should end with .patch, not .diff: #{patch_url}" <ide> end <ide> <ide> gh_patch_param_pattern = %r{https?://github\.com/.+/.+/(?:commit|pull)/[a-fA-F0-9]*.(?:patch|diff)} <ide> if regex_match_group(patch_url_node, gh_patch_param_pattern) && !patch_url.match?(/\?full_index=\w+$/) <del> problem "GitHub patches should use the full_index parameter: #{patch_url}?full_index=1" do |corrector| <del> corrector.replace(patch_url_node.source_range, "\"#{patch_url}?full_index=1\"") <del> end <add> problem "GitHub patches should use the full_index parameter: #{patch_url}?full_index=1" <ide> end <ide> <ide> gh_patch_patterns = Regexp.union([%r{/raw\.github\.com/},
1
Ruby
Ruby
use activesupport hash#deep_merge
0c6331878f0a0c33b3f22dbd6cd6ebf1fb9232ae
<ide><path>Library/Homebrew/dev-cmd/bottle.rb <ide> def merge <ide> write = args.write? <ide> <ide> bottles_hash = ARGV.named.reduce({}) do |hash, json_file| <del> deep_merge_hashes hash, JSON.parse(IO.read(json_file)) <add> hash.deep_merge(JSON.parse(IO.read(json_file))) <ide> end <ide> <ide> bottles_hash.each do |formula_name, bottle_hash| <ide><path>Library/Homebrew/global.rb <ide> def auditing? <ide> require "extend/predicable" <ide> require "extend/string" <ide> require "active_support/core_ext/object/blank" <add>require "active_support/core_ext/hash/deep_merge" <ide> <ide> require "constants" <ide> require "exceptions" <ide><path>Library/Homebrew/utils.rb <ide> require "utils/formatter" <ide> require "utils/git" <ide> require "utils/github" <del>require "utils/hash" <ide> require "utils/inreplace" <ide> require "utils/link" <ide> require "utils/popen" <ide><path>Library/Homebrew/utils/hash.rb <del>def deep_merge_hashes(hash1, hash2) <del> merger = proc do |_key, v1, v2| <del> if v1.is_a?(Hash) && v2.is_a?(Hash) <del> v1.merge v2, &merger <del> else <del> v2 <del> end <del> end <del> hash1.merge hash2, &merger <del>end <ide><path>Library/Homebrew/vendor/bundle-standalone/ruby/2.3.0/gems/activesupport-5.2.1/lib/active_support/core_ext/hash/deep_merge.rb <add># frozen_string_literal: true <add> <add>class Hash <add> # Returns a new hash with +self+ and +other_hash+ merged recursively. <add> # <add> # h1 = { a: true, b: { c: [1, 2, 3] } } <add> # h2 = { a: false, b: { x: [3, 4, 5] } } <add> # <add> # h1.deep_merge(h2) # => { a: false, b: { c: [1, 2, 3], x: [3, 4, 5] } } <add> # <add> # Like with Hash#merge in the standard library, a block can be provided <add> # to merge values: <add> # <add> # h1 = { a: 100, b: 200, c: { c1: 100 } } <add> # h2 = { b: 250, c: { c1: 200 } } <add> # h1.deep_merge(h2) { |key, this_val, other_val| this_val + other_val } <add> # # => { a: 100, b: 450, c: { c1: 300 } } <add> def deep_merge(other_hash, &block) <add> dup.deep_merge!(other_hash, &block) <add> end <add> <add> # Same as +deep_merge+, but modifies +self+. <add> def deep_merge!(other_hash, &block) <add> merge!(other_hash) do |key, this_val, other_val| <add> if this_val.is_a?(Hash) && other_val.is_a?(Hash) <add> this_val.deep_merge(other_val, &block) <add> elsif block_given? <add> block.call(key, this_val, other_val) <add> else <add> other_val <add> end <add> end <add> end <add>end
5
Ruby
Ruby
exclude documentation from `brew list --unbrewed`
e537fc41de8baad61c9296d8628a9feb6edb4385
<ide><path>Library/Homebrew/cmd/list.rb <ide> def list <ide> lib/gio/* <ide> lib/node_modules/* <ide> lib/python[23].[0-9]/* <add> share/doc/homebrew/* <ide> share/info/dir <ide> share/man/man1/brew.1 <ide> share/man/whatis
1
Javascript
Javascript
emend the comment
1e58a4287c065a6cd19b731dadf1868ab3ff0a57
<ide><path>Libraries/Components/ScrollView/ScrollView.js <ide> var ScrollView = React.createClass({ <ide> snapToInterval: PropTypes.number, <ide> /** <ide> * When `snapToInterval` is set, `snapToAlignment` will define the relationship <del> * of the the snapping to the scroll view. <add> * of the snapping to the scroll view. <ide> * - `start` (the default) will align the snap at the left (horizontal) or top (vertical) <ide> * - `center` will align the snap in the center <ide> * - `end` will align the snap at the right (horizontal) or bottom (vertical)
1
Javascript
Javascript
fix style in sys.js
d62b0f442a8bffc8f01a7edbece2c7c554a80948
<ide><path>lib/sys.js <ide> var events = require('events'); <ide> <add> <ide> exports.print = function () { <ide> for (var i = 0, len = arguments.length; i < len; ++i) { <ide> process.stdout.write(arguments[i]); <ide> } <ide> }; <ide> <add> <ide> exports.puts = function () { <ide> for (var i = 0, len = arguments.length; i < len; ++i) { <ide> process.stdout.write(arguments[i] + '\n'); <ide> } <ide> }; <ide> <add> <ide> exports.debug = function (x) { <ide> process.binding('stdio').writeError("DEBUG: " + x + "\n"); <ide> }; <ide> <add> <ide> var error = exports.error = function (x) { <ide> for (var i = 0, len = arguments.length; i < len; ++i) { <ide> process.binding('stdio').writeError(arguments[i] + '\n'); <ide> } <ide> }; <ide> <add> <ide> /** <ide> * Echos the value of a value. Trys to print the value out <ide> * in the best way possible given the different types. <ide> * <ide> * @param {Object} value The object to print out <del> * @param {Boolean} showHidden Flag that shows hidden (not enumerable) properties of objects. <add> * @param {Boolean} showHidden Flag that shows hidden (not enumerable) <add> * properties of objects. <ide> */ <ide> exports.inspect = function (obj, showHidden, depth) { <ide> var seen = []; <ide> exports.inspect = function (obj, showHidden, depth) { <ide> // Primitive types cannot have properties <ide> switch (typeof value) { <ide> case 'undefined': return 'undefined'; <del> case 'string': return JSON.stringify(value).replace(/'/g, "\\'").replace(/\\"/g, '"').replace(/(^"|"$)/g, "'"); <add> case 'string': return JSON.stringify(value).replace(/'/g, "\\'") <add> .replace(/\\"/g, '"') <add> .replace(/(^"|"$)/g, "'"); <ide> case 'number': return '' + value; <ide> case 'boolean': return '' + value; <ide> } <ide> exports.inspect = function (obj, showHidden, depth) { <ide> name = name.substr(1, name.length-2); <ide> } <ide> else { <del> name = name.replace(/'/g, "\\'").replace(/\\"/g, '"').replace(/(^"|"$)/g, "'"); <add> name = name.replace(/'/g, "\\'") <add> .replace(/\\"/g, '"') <add> .replace(/(^"|"$)/g, "'"); <ide> } <ide> } <ide> <ide> exports.inspect = function (obj, showHidden, depth) { <ide> },0); <ide> <ide> if (length > 50) { <del> output = braces[0] + (base === '' ? '' : base + '\n ') + ' ' + output.join('\n, ') + (numLinesEst > 1 ? '\n' : ' ') + braces[1]; <add> output = braces[0] <add> + (base === '' ? '' : base + '\n ') <add> + ' ' <add> + output.join('\n, ') <add> + (numLinesEst > 1 ? '\n' : ' ') <add> + braces[1] <add> ; <ide> } <ide> else { <ide> output = braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; <ide> exports.inspect = function (obj, showHidden, depth) { <ide> } <ide> return format(obj, (typeof depth === 'undefined' ? 2 : depth)); <ide> }; <add> <add> <ide> function isArray (ar) { <ide> return ar instanceof Array <ide> || Array.isArray(ar) <ide> || (ar && ar !== Object.prototype && isArray(ar.__proto__)); <ide> } <add> <add> <ide> function isRegExp (re) { <ide> var s = ""+re; <ide> return re instanceof RegExp // easy case <ide> function isRegExp (re) { <ide> && s.charAt(0) === "/" <ide> && s.substr(-1) === "/"; <ide> } <add> <add> <ide> function isDate (d) { <ide> if (d instanceof Date) return true; <ide> if (typeof d !== "object") return false; <ide> function isDate (d) { <ide> return JSON.stringify(proto) === JSON.stringify(properties); <ide> } <ide> <add> <ide> var pWarning; <ide> <ide> exports.p = function () { <ide> exports.p = function () { <ide> } <ide> }; <ide> <add> <ide> function pad (n) { <ide> return n < 10 ? '0' + n.toString(10) : n.toString(10); <ide> } <ide> <add> <ide> var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; <ide> <ide> // 26 Feb 16:19:34 <ide> function timestamp () { <ide> ].join(' '); <ide> } <ide> <add> <ide> exports.log = function (msg) { <ide> exports.puts(timestamp() + ' - ' + msg.toString()); <del>} <add>}; <add> <ide> <ide> var execWarning; <ide> exports.exec = function () { <ide> exports.exec = function () { <ide> error(execWarning); <ide> } <ide> return require('child_process').exec.apply(this, arguments); <del>} <add>}; <add> <ide> <ide> /** <ide> * Inherit the prototype methods from one constructor into another. <ide> exports.inherits = function (ctor, superCtor) { <ide> ctor.prototype = new tempCtor(); <ide> ctor.prototype.constructor = ctor; <ide> }; <del> <del>
1
Ruby
Ruby
add database specific string concatenation
83c47c1962827698eb0ed58d191f121cedf89385
<ide><path>lib/arel/nodes/infix_operation.rb <ide> def initialize left, right <ide> end <ide> end <ide> <add> class Concat < InfixOperation <add> def initialize left, right <add> super('||', left, right) <add> end <add> end <ide> end <del>end <ide>\ No newline at end of file <add>end <ide><path>lib/arel/predications.rb <ide> def when right <ide> Nodes::Case.new(self).when quoted_node(right) <ide> end <ide> <add> def concat other <add> Nodes::Concat.new self, other <add> end <add> <ide> private <ide> <ide> def grouping_any method_id, others, *extras <ide><path>lib/arel/visitors/depth_first.rb <ide> def binary o <ide> alias :visit_Arel_Nodes_As :binary <ide> alias :visit_Arel_Nodes_Assignment :binary <ide> alias :visit_Arel_Nodes_Between :binary <add> alias :visit_Arel_Nodes_Concat :binary <ide> alias :visit_Arel_Nodes_DeleteStatement :binary <ide> alias :visit_Arel_Nodes_DoesNotMatch :binary <ide> alias :visit_Arel_Nodes_Equality :binary <ide><path>lib/arel/visitors/dot.rb <ide> def binary o <ide> alias :visit_Arel_Nodes_As :binary <ide> alias :visit_Arel_Nodes_Assignment :binary <ide> alias :visit_Arel_Nodes_Between :binary <add> alias :visit_Arel_Nodes_Concat :binary <ide> alias :visit_Arel_Nodes_DoesNotMatch :binary <ide> alias :visit_Arel_Nodes_Equality :binary <ide> alias :visit_Arel_Nodes_GreaterThan :binary <ide><path>lib/arel/visitors/mysql.rb <ide> def visit_Arel_Nodes_UpdateStatement o, collector <ide> maybe_visit o.limit, collector <ide> end <ide> <add> def visit_Arel_Nodes_Concat o, collector <add> collector << " CONCAT(" <add> visit o.left, collector <add> collector << ", " <add> visit o.right, collector <add> collector << ") " <add> collector <add> end <ide> end <ide> end <ide> end <ide><path>test/visitors/test_depth_first.rb <ide> def test_right_outer_join <ide> [ <ide> Arel::Nodes::Assignment, <ide> Arel::Nodes::Between, <add> Arel::Nodes::Concat, <ide> Arel::Nodes::DoesNotMatch, <ide> Arel::Nodes::Equality, <ide> Arel::Nodes::GreaterThan, <ide><path>test/visitors/test_mysql.rb <ide> def compile node <ide> compile(node).must_be_like "LOCK IN SHARE MODE" <ide> end <ide> end <add> <add> describe "concat" do <add> it "concats columns" do <add> @table = Table.new(:users) <add> query = @table[:name].concat(@table[:name]) <add> compile(query).must_be_like %{ <add> CONCAT("users"."name", "users"."name") <add> } <add> end <add> <add> it "concats a string" do <add> @table = Table.new(:users) <add> query = @table[:name].concat(Nodes.build_quoted('abc')) <add> compile(query).must_be_like %{ <add> CONCAT("users"."name", 'abc') <add> } <add> end <add> end <ide> end <ide> end <ide> end <ide><path>test/visitors/test_to_sql.rb <ide> def quote value, column = nil <ide> compile(node).must_equal %(("products"."price" - 7)) <ide> end <ide> <add> it "should handle Concatination" do <add> table = Table.new(:users) <add> node = table[:name].concat(table[:name]) <add> compile(node).must_equal %("users"."name" || "users"."name") <add> end <add> <ide> it "should handle arbitrary operators" do <ide> node = Arel::Nodes::InfixOperation.new( <del> '||', <add> '&&', <ide> Arel::Attributes::String.new(Table.new(:products), :name), <ide> Arel::Attributes::String.new(Table.new(:products), :name) <ide> ) <del> compile(node).must_equal %("products"."name" || "products"."name") <add> compile(node).must_equal %("products"."name" && "products"."name") <ide> end <ide> end <ide>
8
PHP
PHP
add interface for http client adapters
065556fdbe590e494a4ceb5724f25400632ea9bb
<ide><path>src/Http/Client/Adapter/Stream.php <ide> namespace Cake\Http\Client\Adapter; <ide> <ide> use Cake\Core\Exception\Exception; <add>use Cake\Http\Client\AdapterInterface; <ide> use Cake\Http\Client\Request; <ide> use Cake\Http\Client\Response; <ide> use Cake\Http\Exception\HttpException; <ide> * <ide> * This approach and implementation is partly inspired by Aura.Http <ide> */ <del>class Stream <add>class Stream implements AdapterInterface <ide> { <ide> <ide> /** <ide> class Stream <ide> protected $_connectionErrors = []; <ide> <ide> /** <del> * Send a request and get a response back. <del> * <del> * @param \Cake\Http\Client\Request $request The request object to send. <del> * @param array $options Array of options for the stream. <del> * @return array Array of populated Response objects <add> * {@inheritDoc} <ide> */ <ide> public function send(Request $request, array $options) <ide> { <ide><path>src/Http/Client/AdapterInterface.php <add><?php <add>/** <add> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <add> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <add> * <add> * Licensed under The MIT License <add> * Redistributions of files must retain the above copyright notice. <add> * <add> * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <add> * @link https://cakephp.org CakePHP(tm) Project <add> * @since 3.7.0 <add> * @license https://opensource.org/licenses/mit-license.php MIT License <add> */ <add>namespace Cake\Http\Client; <add> <add>use Cake\Http\Client\Request; <add> <add>interface AdapterInterface <add>{ <add> /** <add> * Send a request and get a response back. <add> * <add> * @param \Cake\Http\Client\Request $request The request object to send. <add> * @param array $options Array of options for the stream. <add> * @return \Cake\Http\Client\Response[] Array of populated Response objects <add> */ <add> public function send(Request $request, array $options); <add>}
2
Go
Go
move runtime and container into sub pkg
36c3614fdde079fad178390f651945fba884668a
<ide><path>buildfile.go <ide> import ( <ide> "github.com/dotcloud/docker/auth" <ide> "github.com/dotcloud/docker/registry" <ide> "github.com/dotcloud/docker/runconfig" <add> "github.com/dotcloud/docker/runtime" <ide> "github.com/dotcloud/docker/utils" <ide> "io" <ide> "io/ioutil" <ide> type BuildFile interface { <ide> } <ide> <ide> type buildFile struct { <del> runtime *Runtime <add> runtime *runtime.Runtime <ide> srv *Server <ide> <ide> image string <ide> func (b *buildFile) clearTmp(containers map[string]struct{}) { <ide> } <ide> <ide> func (b *buildFile) CmdFrom(name string) error { <del> image, err := b.runtime.repositories.LookupImage(name) <add> image, err := b.runtime.Repositories().LookupImage(name) <ide> if err != nil { <del> if b.runtime.graph.IsNotExist(err) { <add> if b.runtime.Graph().IsNotExist(err) { <ide> remote, tag := utils.ParseRepositoryTag(name) <ide> pullRegistryAuth := b.authConfig <ide> if len(b.configFile.Configs) > 0 { <ide> func (b *buildFile) CmdFrom(name string) error { <ide> if err := job.Run(); err != nil { <ide> return err <ide> } <del> image, err = b.runtime.repositories.LookupImage(name) <add> image, err = b.runtime.Repositories().LookupImage(name) <ide> if err != nil { <ide> return err <ide> } <ide> func (b *buildFile) CmdFrom(name string) error { <ide> b.config = image.Config <ide> } <ide> if b.config.Env == nil || len(b.config.Env) == 0 { <del> b.config.Env = append(b.config.Env, "HOME=/", "PATH="+defaultPathEnv) <add> b.config.Env = append(b.config.Env, "HOME=/", "PATH="+runtime.DefaultPathEnv) <ide> } <ide> // Process ONBUILD triggers if they exist <ide> if nTriggers := len(b.config.OnBuild); nTriggers != 0 { <ide> func (b *buildFile) checkPathForAddition(orig string) error { <ide> return nil <ide> } <ide> <del>func (b *buildFile) addContext(container *Container, orig, dest string, remote bool) error { <add>func (b *buildFile) addContext(container *runtime.Container, orig, dest string, remote bool) error { <ide> var ( <ide> origPath = path.Join(b.contextPath, orig) <ide> destPath = path.Join(container.BasefsPath(), dest) <ide> func (sf *StderrFormater) Write(buf []byte) (int, error) { <ide> return len(buf), err <ide> } <ide> <del>func (b *buildFile) create() (*Container, error) { <add>func (b *buildFile) create() (*runtime.Container, error) { <ide> if b.image == "" { <ide> return nil, fmt.Errorf("Please provide a source image with `from` prior to run") <ide> } <ide> func (b *buildFile) create() (*Container, error) { <ide> return c, nil <ide> } <ide> <del>func (b *buildFile) run(c *Container) error { <add>func (b *buildFile) run(c *runtime.Container) error { <ide> var errCh chan error <ide> <ide> if b.verbose { <ide><path>integration/api_test.go <ide> import ( <ide> "bytes" <ide> "encoding/json" <ide> "fmt" <del> "github.com/dotcloud/docker" <ide> "github.com/dotcloud/docker/api" <ide> "github.com/dotcloud/docker/dockerversion" <ide> "github.com/dotcloud/docker/engine" <ide> "github.com/dotcloud/docker/image" <ide> "github.com/dotcloud/docker/runconfig" <add> "github.com/dotcloud/docker/runtime" <ide> "github.com/dotcloud/docker/utils" <ide> "github.com/dotcloud/docker/vendor/src/code.google.com/p/go/src/pkg/archive/tar" <ide> "io" <ide> func TestGetContainersByName(t *testing.T) { <ide> t.Fatal(err) <ide> } <ide> assertHttpNotError(r, t) <del> outContainer := &docker.Container{} <add> outContainer := &runtime.Container{} <ide> if err := json.Unmarshal(r.Body.Bytes(), outContainer); err != nil { <ide> t.Fatal(err) <ide> } <ide><path>integration/commands_test.go <ide> package docker <ide> import ( <ide> "bufio" <ide> "fmt" <del> "github.com/dotcloud/docker" <ide> "github.com/dotcloud/docker/api" <ide> "github.com/dotcloud/docker/engine" <ide> "github.com/dotcloud/docker/image" <ide> "github.com/dotcloud/docker/pkg/term" <add> "github.com/dotcloud/docker/runtime" <ide> "github.com/dotcloud/docker/utils" <ide> "io" <ide> "io/ioutil" <ide> func closeWrap(args ...io.Closer) error { <ide> return nil <ide> } <ide> <del>func setRaw(t *testing.T, c *docker.Container) *term.State { <add>func setRaw(t *testing.T, c *runtime.Container) *term.State { <ide> pty, err := c.GetPtyMaster() <ide> if err != nil { <ide> t.Fatal(err) <ide> func setRaw(t *testing.T, c *docker.Container) *term.State { <ide> return state <ide> } <ide> <del>func unsetRaw(t *testing.T, c *docker.Container, state *term.State) { <add>func unsetRaw(t *testing.T, c *runtime.Container, state *term.State) { <ide> pty, err := c.GetPtyMaster() <ide> if err != nil { <ide> t.Fatal(err) <ide> } <ide> term.RestoreTerminal(pty.Fd(), state) <ide> } <ide> <del>func waitContainerStart(t *testing.T, timeout time.Duration) *docker.Container { <del> var container *docker.Container <add>func waitContainerStart(t *testing.T, timeout time.Duration) *runtime.Container { <add> var container *runtime.Container <ide> <ide> setTimeout(t, "Waiting for the container to be started timed out", timeout, func() { <ide> for { <ide><path>integration/runtime_test.go <ide> package docker <ide> import ( <ide> "bytes" <ide> "fmt" <del> "github.com/dotcloud/docker" <ide> "github.com/dotcloud/docker/engine" <ide> "github.com/dotcloud/docker/image" <ide> "github.com/dotcloud/docker/nat" <ide> "github.com/dotcloud/docker/runconfig" <add> "github.com/dotcloud/docker/runtime" <ide> "github.com/dotcloud/docker/sysinit" <ide> "github.com/dotcloud/docker/utils" <ide> "io" <ide> import ( <ide> "net/url" <ide> "os" <ide> "path/filepath" <del> "runtime" <add> goruntime "runtime" <ide> "strconv" <ide> "strings" <ide> "syscall" <ide> const ( <ide> <ide> var ( <ide> // FIXME: globalRuntime is deprecated by globalEngine. All tests should be converted. <del> globalRuntime *docker.Runtime <add> globalRuntime *runtime.Runtime <ide> globalEngine *engine.Engine <ide> startFds int <ide> startGoroutines int <ide> ) <ide> <ide> // FIXME: nuke() is deprecated by Runtime.Nuke() <del>func nuke(runtime *docker.Runtime) error { <add>func nuke(runtime *runtime.Runtime) error { <ide> return runtime.Nuke() <ide> } <ide> <ide> func init() { <ide> <ide> // Create the "global runtime" with a long-running daemon for integration tests <ide> spawnGlobalDaemon() <del> startFds, startGoroutines = utils.GetTotalUsedFds(), runtime.NumGoroutine() <add> startFds, startGoroutines = utils.GetTotalUsedFds(), goruntime.NumGoroutine() <ide> } <ide> <ide> func setupBaseImage() { <ide> func spawnGlobalDaemon() { <ide> <ide> // FIXME: test that ImagePull(json=true) send correct json output <ide> <del>func GetTestImage(runtime *docker.Runtime) *image.Image { <add>func GetTestImage(runtime *runtime.Runtime) *image.Image { <ide> imgs, err := runtime.Graph().Map() <ide> if err != nil { <ide> log.Fatalf("Unable to get the test image: %s", err) <ide> func TestGet(t *testing.T) { <ide> <ide> } <ide> <del>func startEchoServerContainer(t *testing.T, proto string) (*docker.Runtime, *docker.Container, string) { <add>func startEchoServerContainer(t *testing.T, proto string) (*runtime.Runtime, *runtime.Container, string) { <ide> var ( <ide> err error <ide> id string <ide><path>integration/utils_test.go <ide> import ( <ide> "github.com/dotcloud/docker/builtins" <ide> "github.com/dotcloud/docker/engine" <ide> "github.com/dotcloud/docker/runconfig" <add> "github.com/dotcloud/docker/runtime" <ide> "github.com/dotcloud/docker/utils" <ide> ) <ide> <ide> import ( <ide> <ide> // Create a temporary runtime suitable for unit testing. <ide> // Call t.Fatal() at the first error. <del>func mkRuntime(f utils.Fataler) *docker.Runtime { <add>func mkRuntime(f utils.Fataler) *runtime.Runtime { <ide> eng := newTestEngine(f, false, "") <ide> return mkRuntimeFromEngine(eng, f) <ide> // FIXME: <ide> func assertHttpError(r *httptest.ResponseRecorder, t utils.Fataler) { <ide> } <ide> } <ide> <del>func getContainer(eng *engine.Engine, id string, t utils.Fataler) *docker.Container { <add>func getContainer(eng *engine.Engine, id string, t utils.Fataler) *runtime.Container { <ide> runtime := mkRuntimeFromEngine(eng, t) <ide> c := runtime.Get(id) <ide> if c == nil { <ide> func mkServerFromEngine(eng *engine.Engine, t utils.Fataler) *docker.Server { <ide> return srv <ide> } <ide> <del>func mkRuntimeFromEngine(eng *engine.Engine, t utils.Fataler) *docker.Runtime { <add>func mkRuntimeFromEngine(eng *engine.Engine, t utils.Fataler) *runtime.Runtime { <ide> iRuntime := eng.Hack_GetGlobalVar("httpapi.runtime") <ide> if iRuntime == nil { <ide> panic("Legacy runtime field not set in engine") <ide> } <del> runtime, ok := iRuntime.(*docker.Runtime) <add> runtime, ok := iRuntime.(*runtime.Runtime) <ide> if !ok { <del> panic("Legacy runtime field in engine does not cast to *docker.Runtime") <add> panic("Legacy runtime field in engine does not cast to *runtime.Runtime") <ide> } <ide> return runtime <ide> } <ide> func readFile(src string, t *testing.T) (content string) { <ide> // dynamically replaced by the current test image. <ide> // The caller is responsible for destroying the container. <ide> // Call t.Fatal() at the first error. <del>func mkContainer(r *docker.Runtime, args []string, t *testing.T) (*docker.Container, *runconfig.HostConfig, error) { <add>func mkContainer(r *runtime.Runtime, args []string, t *testing.T) (*runtime.Container, *runconfig.HostConfig, error) { <ide> config, hc, _, err := runconfig.Parse(args, nil) <ide> defer func() { <ide> if err != nil && t != nil { <ide> func mkContainer(r *docker.Runtime, args []string, t *testing.T) (*docker.Contai <ide> // and return its standard output as a string. <ide> // The image name (eg. the XXX in []string{"-i", "-t", "XXX", "bash"}, is dynamically replaced by the current test image. <ide> // If t is not nil, call t.Fatal() at the first error. Otherwise return errors normally. <del>func runContainer(eng *engine.Engine, r *docker.Runtime, args []string, t *testing.T) (output string, err error) { <add>func runContainer(eng *engine.Engine, r *runtime.Runtime, args []string, t *testing.T) (output string, err error) { <ide> defer func() { <ide> if err != nil && t != nil { <ide> t.Fatal(err) <add><path>runtime/container.go <del><path>container.go <del>package docker <add>package runtime <ide> <ide> import ( <ide> "encoding/json" <ide> import ( <ide> "time" <ide> ) <ide> <del>const defaultPathEnv = "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" <add>const DefaultPathEnv = "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" <ide> <ide> var ( <ide> ErrNotATTY = errors.New("The PTY is not a file") <ide> func (container *Container) ToDisk() (err error) { <ide> if err != nil { <ide> return <ide> } <del> return container.writeHostConfig() <add> return container.WriteHostConfig() <ide> } <ide> <ide> func (container *Container) readHostConfig() error { <ide> func (container *Container) readHostConfig() error { <ide> return json.Unmarshal(data, container.hostConfig) <ide> } <ide> <del>func (container *Container) writeHostConfig() (err error) { <add>func (container *Container) WriteHostConfig() (err error) { <ide> data, err := json.Marshal(container.hostConfig) <ide> if err != nil { <ide> return <ide> func (container *Container) Start() (err error) { <ide> // Setup environment <ide> env := []string{ <ide> "HOME=/", <del> "PATH=" + defaultPathEnv, <add> "PATH=" + DefaultPathEnv, <ide> "HOSTNAME=" + container.Config.Hostname, <ide> } <ide> <ide> func (container *Container) allocateNetwork() error { <ide> return err <ide> } <ide> container.Config.PortSpecs = nil <del> if err := container.writeHostConfig(); err != nil { <add> if err := container.WriteHostConfig(); err != nil { <ide> return err <ide> } <ide> } <ide> func (container *Container) allocateNetwork() error { <ide> } <ide> bindings[port] = binding <ide> } <del> container.writeHostConfig() <add> container.WriteHostConfig() <ide> <ide> container.NetworkSettings.Ports = bindings <ide> <ide> func (container *Container) cleanup() { <ide> } <ide> } <ide> <del>func (container *Container) kill(sig int) error { <add>func (container *Container) KillSig(sig int) error { <ide> container.Lock() <ide> defer container.Unlock() <ide> <ide> func (container *Container) Kill() error { <ide> } <ide> <ide> // 1. Send SIGKILL <del> if err := container.kill(9); err != nil { <add> if err := container.KillSig(9); err != nil { <ide> return err <ide> } <ide> <ide> func (container *Container) Stop(seconds int) error { <ide> } <ide> <ide> // 1. Send a SIGTERM <del> if err := container.kill(15); err != nil { <add> if err := container.KillSig(15); err != nil { <ide> utils.Debugf("Error sending kill SIGTERM: %s", err) <ide> log.Print("Failed to send SIGTERM to the process, force killing") <del> if err := container.kill(9); err != nil { <add> if err := container.KillSig(9); err != nil { <ide> return err <ide> } <ide> } <ide> func (container *Container) GetPtyMaster() (*os.File, error) { <ide> } <ide> return ttyConsole.Master(), nil <ide> } <add> <add>func (container *Container) HostConfig() *runconfig.HostConfig { <add> return container.hostConfig <add>} <add> <add>func (container *Container) SetHostConfig(hostConfig *runconfig.HostConfig) { <add> container.hostConfig = hostConfig <add>} <add> <add>func (container *Container) DisableLink(name string) { <add> if container.activeLinks != nil { <add> if link, exists := container.activeLinks[name]; exists { <add> link.Disable() <add> } else { <add> utils.Debugf("Could not find active link for %s", name) <add> } <add> } <add>} <add><path>runtime/container_unit_test.go <del><path>container_unit_test.go <del>package docker <add>package runtime <ide> <ide> import ( <ide> "github.com/dotcloud/docker/nat" <ide> func TestParseNetworkOptsUdp(t *testing.T) { <ide> } <ide> <ide> func TestGetFullName(t *testing.T) { <del> name, err := getFullName("testing") <add> name, err := GetFullContainerName("testing") <ide> if err != nil { <ide> t.Fatal(err) <ide> } <ide> if name != "/testing" { <ide> t.Fatalf("Expected /testing got %s", name) <ide> } <del> if _, err := getFullName(""); err == nil { <add> if _, err := GetFullContainerName(""); err == nil { <ide> t.Fatal("Error should not be nil") <ide> } <ide> } <add><path>runtime/runtime.go <del><path>runtime.go <del>package docker <add>package runtime <ide> <ide> import ( <ide> "container/list" <ide> import ( <ide> const MaxImageDepth = 127 <ide> <ide> var ( <del> defaultDns = []string{"8.8.8.8", "8.8.4.4"} <add> DefaultDns = []string{"8.8.8.8", "8.8.4.4"} <ide> validContainerNameChars = `[a-zA-Z0-9_.-]` <ide> validContainerNamePattern = regexp.MustCompile(`^/?` + validContainerNameChars + `+$`) <ide> ) <ide> type Runtime struct { <ide> idIndex *utils.TruncIndex <ide> sysInfo *sysinfo.SysInfo <ide> volumes *graph.Graph <del> srv *Server <add> srv Server <ide> eng *engine.Engine <ide> config *daemonconfig.Config <ide> containerGraph *graphdb.Database <ide> func (runtime *Runtime) Create(config *runconfig.Config, name string) (*Containe <ide> } <ide> <ide> if len(config.Dns) == 0 && len(runtime.config.Dns) == 0 && utils.CheckLocalDns(resolvConf) { <del> //"WARNING: Docker detected local DNS server on resolv.conf. Using default external servers: %v", defaultDns <del> runtime.config.Dns = defaultDns <add> runtime.config.Dns = DefaultDns <ide> } <ide> <ide> // If custom dns exists, then create a resolv.conf for the container <ide> func (runtime *Runtime) Commit(container *Container, repository, tag, comment, a <ide> return img, nil <ide> } <ide> <del>func getFullName(name string) (string, error) { <add>func GetFullContainerName(name string) (string, error) { <ide> if name == "" { <ide> return "", fmt.Errorf("Container name cannot be empty") <ide> } <ide> func getFullName(name string) (string, error) { <ide> } <ide> <ide> func (runtime *Runtime) GetByName(name string) (*Container, error) { <del> fullName, err := getFullName(name) <add> fullName, err := GetFullContainerName(name) <ide> if err != nil { <ide> return nil, err <ide> } <ide> func (runtime *Runtime) GetByName(name string) (*Container, error) { <ide> } <ide> <ide> func (runtime *Runtime) Children(name string) (map[string]*Container, error) { <del> name, err := getFullName(name) <add> name, err := GetFullContainerName(name) <ide> if err != nil { <ide> return nil, err <ide> } <ide> func (runtime *Runtime) Graph() *graph.Graph { <ide> return runtime.graph <ide> } <ide> <add>func (runtime *Runtime) Repositories() *graph.TagStore { <add> return runtime.repositories <add>} <add> <add>func (runtime *Runtime) Config() *daemonconfig.Config { <add> return runtime.config <add>} <add> <add>func (runtime *Runtime) SystemConfig() *sysinfo.SysInfo { <add> return runtime.sysInfo <add>} <add> <add>func (runtime *Runtime) SystemInitPath() string { <add> return runtime.sysInitPath <add>} <add> <add>func (runtime *Runtime) GraphDriver() graphdriver.Driver { <add> return runtime.driver <add>} <add> <add>func (runtime *Runtime) ExecutionDriver() execdriver.Driver { <add> return runtime.execDriver <add>} <add> <add>func (runtime *Runtime) Volumes() *graph.Graph { <add> return runtime.volumes <add>} <add> <add>func (runtime *Runtime) ContainerGraph() *graphdb.Database { <add> return runtime.containerGraph <add>} <add> <add>func (runtime *Runtime) SetServer(server Server) { <add> runtime.srv = server <add>} <add> <ide> // History is a convenience type for storing a list of containers, <ide> // ordered by creation date. <ide> type History []*Container <ide><path>runtime/server.go <add>package runtime <add> <add>import ( <add> "github.com/dotcloud/docker/utils" <add>) <add> <add>type Server interface { <add> LogEvent(action, id, from string) *utils.JSONMessage <add>} <add><path>runtime/sorter.go <del><path>sorter.go <del>package docker <add>package runtime <ide> <ide> import "sort" <ide> <add><path>runtime/state.go <del><path>state.go <del>package docker <add>package runtime <ide> <ide> import ( <ide> "fmt" <ide><path>runtime/utils.go <add>package runtime <add> <add>import ( <add> "github.com/dotcloud/docker/nat" <add> "github.com/dotcloud/docker/pkg/namesgenerator" <add> "github.com/dotcloud/docker/runconfig" <add>) <add> <add>func migratePortMappings(config *runconfig.Config, hostConfig *runconfig.HostConfig) error { <add> if config.PortSpecs != nil { <add> ports, bindings, err := nat.ParsePortSpecs(config.PortSpecs) <add> if err != nil { <add> return err <add> } <add> config.PortSpecs = nil <add> if len(bindings) > 0 { <add> if hostConfig == nil { <add> hostConfig = &runconfig.HostConfig{} <add> } <add> hostConfig.PortBindings = bindings <add> } <add> <add> if config.ExposedPorts == nil { <add> config.ExposedPorts = make(nat.PortSet, len(ports)) <add> } <add> for k, v := range ports { <add> config.ExposedPorts[k] = v <add> } <add> } <add> return nil <add>} <add> <add>type checker struct { <add> runtime *Runtime <add>} <add> <add>func (c *checker) Exists(name string) bool { <add> return c.runtime.containerGraph.Exists("/" + name) <add>} <add> <add>// Generate a random and unique name <add>func generateRandomName(runtime *Runtime) (string, error) { <add> return namesgenerator.GenerateRandomName(&checker{runtime}) <add>} <add><path>runtime/volumes.go <del><path>volumes.go <del>package docker <add>package runtime <ide> <ide> import ( <ide> "fmt" <ide><path>server.go <ide> import ( <ide> "github.com/dotcloud/docker/pkg/graphdb" <ide> "github.com/dotcloud/docker/registry" <ide> "github.com/dotcloud/docker/runconfig" <add> "github.com/dotcloud/docker/runtime" <ide> "github.com/dotcloud/docker/utils" <ide> "io" <ide> "io/ioutil" <ide> import ( <ide> "os/signal" <ide> "path" <ide> "path/filepath" <del> "runtime" <add> goruntime "runtime" <ide> "strconv" <ide> "strings" <ide> "sync" <ide> func InitServer(job *engine.Job) engine.Status { <ide> if err != nil { <ide> return job.Error(err) <ide> } <del> if srv.runtime.config.Pidfile != "" { <add> if srv.runtime.Config().Pidfile != "" { <ide> job.Logf("Creating pidfile") <del> if err := utils.CreatePidFile(srv.runtime.config.Pidfile); err != nil { <add> if err := utils.CreatePidFile(srv.runtime.Config().Pidfile); err != nil { <ide> // FIXME: do we need fatal here instead of returning a job error? <ide> log.Fatal(err) <ide> } <ide> func InitServer(job *engine.Job) engine.Status { <ide> go func() { <ide> sig := <-c <ide> log.Printf("Received signal '%v', exiting\n", sig) <del> utils.RemovePidFile(srv.runtime.config.Pidfile) <add> utils.RemovePidFile(srv.runtime.Config().Pidfile) <ide> srv.Close() <ide> os.Exit(0) <ide> }() <ide> func (srv *Server) ContainerKill(job *engine.Job) engine.Status { <ide> if err := container.Kill(); err != nil { <ide> return job.Errorf("Cannot kill container %s: %s", name, err) <ide> } <del> srv.LogEvent("kill", container.ID, srv.runtime.repositories.ImageName(container.Image)) <add> srv.LogEvent("kill", container.ID, srv.runtime.Repositories().ImageName(container.Image)) <ide> } else { <ide> // Otherwise, just send the requested signal <del> if err := container.kill(int(sig)); err != nil { <add> if err := container.KillSig(int(sig)); err != nil { <ide> return job.Errorf("Cannot kill container %s: %s", name, err) <ide> } <ide> // FIXME: Add event for signals <ide> func (srv *Server) ContainerExport(job *engine.Job) engine.Status { <ide> return job.Errorf("%s: %s", name, err) <ide> } <ide> // FIXME: factor job-specific LogEvent to engine.Job.Run() <del> srv.LogEvent("export", container.ID, srv.runtime.repositories.ImageName(container.Image)) <add> srv.LogEvent("export", container.ID, srv.runtime.Repositories().ImageName(container.Image)) <ide> return engine.StatusOK <ide> } <ide> return job.Errorf("No such container: %s", name) <ide> func (srv *Server) ImageExport(job *engine.Job) engine.Status { <ide> <ide> utils.Debugf("Serializing %s", name) <ide> <del> rootRepo, err := srv.runtime.repositories.Get(name) <add> rootRepo, err := srv.runtime.Repositories().Get(name) <ide> if err != nil { <ide> return job.Error(err) <ide> } <ide> func (srv *Server) Build(job *engine.Job) engine.Status { <ide> return job.Error(err) <ide> } <ide> if repoName != "" { <del> srv.runtime.repositories.Set(repoName, tag, id, false) <add> srv.runtime.Repositories().Set(repoName, tag, id, false) <ide> } <ide> return engine.StatusOK <ide> } <ide> func (srv *Server) ImageLoad(job *engine.Job) engine.Status { <ide> <ide> for imageName, tagMap := range repositories { <ide> for tag, address := range tagMap { <del> if err := srv.runtime.repositories.Set(imageName, tag, address, true); err != nil { <add> if err := srv.runtime.Repositories().Set(imageName, tag, address, true); err != nil { <ide> return job.Error(err) <ide> } <ide> } <ide> func (srv *Server) recursiveLoad(address, tmpImageDir string) error { <ide> return err <ide> } <ide> if img.Parent != "" { <del> if !srv.runtime.graph.Exists(img.Parent) { <add> if !srv.runtime.Graph().Exists(img.Parent) { <ide> if err := srv.recursiveLoad(img.Parent, tmpImageDir); err != nil { <ide> return err <ide> } <ide> } <ide> } <del> if err := srv.runtime.graph.Register(imageJson, layer, img); err != nil { <add> if err := srv.runtime.Graph().Register(imageJson, layer, img); err != nil { <ide> return err <ide> } <ide> } <ide> func (srv *Server) ImageInsert(job *engine.Job) engine.Status { <ide> sf := utils.NewStreamFormatter(job.GetenvBool("json")) <ide> <ide> out := utils.NewWriteFlusher(job.Stdout) <del> img, err := srv.runtime.repositories.LookupImage(name) <add> img, err := srv.runtime.Repositories().LookupImage(name) <ide> if err != nil { <ide> return job.Error(err) <ide> } <ide> func (srv *Server) ImageInsert(job *engine.Job) engine.Status { <ide> } <ide> defer file.Body.Close() <ide> <del> config, _, _, err := runconfig.Parse([]string{img.ID, "echo", "insert", url, path}, srv.runtime.sysInfo) <add> config, _, _, err := runconfig.Parse([]string{img.ID, "echo", "insert", url, path}, srv.runtime.SystemConfig()) <ide> if err != nil { <ide> return job.Error(err) <ide> } <ide> func (srv *Server) ImageInsert(job *engine.Job) engine.Status { <ide> } <ide> <ide> func (srv *Server) ImagesViz(job *engine.Job) engine.Status { <del> images, _ := srv.runtime.graph.Map() <add> images, _ := srv.runtime.Graph().Map() <ide> if images == nil { <ide> return engine.StatusOK <ide> } <ide> func (srv *Server) ImagesViz(job *engine.Job) engine.Status { <ide> <ide> reporefs := make(map[string][]string) <ide> <del> for name, repository := range srv.runtime.repositories.Repositories { <add> for name, repository := range srv.runtime.Repositories().Repositories { <ide> for tag, id := range repository { <ide> reporefs[utils.TruncateID(id)] = append(reporefs[utils.TruncateID(id)], fmt.Sprintf("%s:%s", name, tag)) <ide> } <ide> func (srv *Server) Images(job *engine.Job) engine.Status { <ide> err error <ide> ) <ide> if job.GetenvBool("all") { <del> allImages, err = srv.runtime.graph.Map() <add> allImages, err = srv.runtime.Graph().Map() <ide> } else { <del> allImages, err = srv.runtime.graph.Heads() <add> allImages, err = srv.runtime.Graph().Heads() <ide> } <ide> if err != nil { <ide> return job.Error(err) <ide> } <ide> lookup := make(map[string]*engine.Env) <del> for name, repository := range srv.runtime.repositories.Repositories { <add> for name, repository := range srv.runtime.Repositories().Repositories { <ide> if job.Getenv("filter") != "" { <ide> if match, _ := path.Match(job.Getenv("filter"), name); !match { <ide> continue <ide> } <ide> } <ide> for tag, id := range repository { <del> image, err := srv.runtime.graph.Get(id) <add> image, err := srv.runtime.Graph().Get(id) <ide> if err != nil { <ide> log.Printf("Warning: couldn't load %s from %s/%s: %s", id, name, tag, err) <ide> continue <ide> func (srv *Server) Images(job *engine.Job) engine.Status { <ide> } <ide> <ide> func (srv *Server) DockerInfo(job *engine.Job) engine.Status { <del> images, _ := srv.runtime.graph.Map() <add> images, _ := srv.runtime.Graph().Map() <ide> var imgcount int <ide> if images == nil { <ide> imgcount = 0 <ide> func (srv *Server) DockerInfo(job *engine.Job) engine.Status { <ide> initPath := utils.DockerInitPath("") <ide> if initPath == "" { <ide> // if that fails, we'll just return the path from the runtime <del> initPath = srv.runtime.sysInitPath <add> initPath = srv.runtime.SystemInitPath() <ide> } <ide> <ide> v := &engine.Env{} <ide> v.SetInt("Containers", len(srv.runtime.List())) <ide> v.SetInt("Images", imgcount) <del> v.Set("Driver", srv.runtime.driver.String()) <del> v.SetJson("DriverStatus", srv.runtime.driver.Status()) <del> v.SetBool("MemoryLimit", srv.runtime.sysInfo.MemoryLimit) <del> v.SetBool("SwapLimit", srv.runtime.sysInfo.SwapLimit) <del> v.SetBool("IPv4Forwarding", !srv.runtime.sysInfo.IPv4ForwardingDisabled) <add> v.Set("Driver", srv.runtime.GraphDriver().String()) <add> v.SetJson("DriverStatus", srv.runtime.GraphDriver().Status()) <add> v.SetBool("MemoryLimit", srv.runtime.SystemConfig().MemoryLimit) <add> v.SetBool("SwapLimit", srv.runtime.SystemConfig().SwapLimit) <add> v.SetBool("IPv4Forwarding", !srv.runtime.SystemConfig().IPv4ForwardingDisabled) <ide> v.SetBool("Debug", os.Getenv("DEBUG") != "") <ide> v.SetInt("NFd", utils.GetTotalUsedFds()) <del> v.SetInt("NGoroutines", runtime.NumGoroutine()) <del> v.Set("ExecutionDriver", srv.runtime.execDriver.Name()) <add> v.SetInt("NGoroutines", goruntime.NumGoroutine()) <add> v.Set("ExecutionDriver", srv.runtime.ExecutionDriver().Name()) <ide> v.SetInt("NEventsListener", len(srv.listeners)) <ide> v.Set("KernelVersion", kernelVersion) <ide> v.Set("IndexServerAddress", auth.IndexServerAddress()) <ide> func (srv *Server) ImageHistory(job *engine.Job) engine.Status { <ide> return job.Errorf("Usage: %s IMAGE", job.Name) <ide> } <ide> name := job.Args[0] <del> foundImage, err := srv.runtime.repositories.LookupImage(name) <add> foundImage, err := srv.runtime.Repositories().LookupImage(name) <ide> if err != nil { <ide> return job.Error(err) <ide> } <ide> <ide> lookupMap := make(map[string][]string) <del> for name, repository := range srv.runtime.repositories.Repositories { <add> for name, repository := range srv.runtime.Repositories().Repositories { <ide> for tag, id := range repository { <ide> // If the ID already has a reverse lookup, do not update it unless for "latest" <ide> if _, exists := lookupMap[id]; !exists { <ide> func (srv *Server) ContainerTop(job *engine.Job) engine.Status { <ide> if !container.State.IsRunning() { <ide> return job.Errorf("Container %s is not running", name) <ide> } <del> pids, err := srv.runtime.execDriver.GetPidsForContainer(container.ID) <add> pids, err := srv.runtime.ExecutionDriver().GetPidsForContainer(container.ID) <ide> if err != nil { <ide> return job.Error(err) <ide> } <ide> func (srv *Server) Containers(job *engine.Job) engine.Status { <ide> outs := engine.NewTable("Created", 0) <ide> <ide> names := map[string][]string{} <del> srv.runtime.containerGraph.Walk("/", func(p string, e *graphdb.Entity) error { <add> srv.runtime.ContainerGraph().Walk("/", func(p string, e *graphdb.Entity) error { <ide> names[e.ID()] = append(names[e.ID()], p) <ide> return nil <ide> }, -1) <ide> func (srv *Server) Containers(job *engine.Job) engine.Status { <ide> out := &engine.Env{} <ide> out.Set("Id", container.ID) <ide> out.SetList("Names", names[container.ID]) <del> out.Set("Image", srv.runtime.repositories.ImageName(container.Image)) <add> out.Set("Image", srv.runtime.Repositories().ImageName(container.Image)) <ide> if len(container.Args) > 0 { <ide> out.Set("Command", fmt.Sprintf("\"%s %s\"", container.Path, strings.Join(container.Args, " "))) <ide> } else { <ide> func (srv *Server) ImageTag(job *engine.Job) engine.Status { <ide> if len(job.Args) == 3 { <ide> tag = job.Args[2] <ide> } <del> if err := srv.runtime.repositories.Set(job.Args[1], tag, job.Args[0], job.GetenvBool("force")); err != nil { <add> if err := srv.runtime.Repositories().Set(job.Args[1], tag, job.Args[0], job.GetenvBool("force")); err != nil { <ide> return job.Error(err) <ide> } <ide> return engine.StatusOK <ide> func (srv *Server) pullImage(r *registry.Registry, out io.Writer, imgID, endpoin <ide> } <ide> defer srv.poolRemove("pull", "layer:"+id) <ide> <del> if !srv.runtime.graph.Exists(id) { <add> if !srv.runtime.Graph().Exists(id) { <ide> out.Write(sf.FormatProgress(utils.TruncateID(id), "Pulling metadata", nil)) <ide> imgJSON, imgSize, err := r.GetRemoteImageJSON(id, endpoint, token) <ide> if err != nil { <ide> func (srv *Server) pullImage(r *registry.Registry, out io.Writer, imgID, endpoin <ide> return err <ide> } <ide> defer layer.Close() <del> if err := srv.runtime.graph.Register(imgJSON, utils.ProgressReader(layer, imgSize, out, sf, false, utils.TruncateID(id), "Downloading"), img); err != nil { <add> if err := srv.runtime.Graph().Register(imgJSON, utils.ProgressReader(layer, imgSize, out, sf, false, utils.TruncateID(id), "Downloading"), img); err != nil { <ide> out.Write(sf.FormatProgress(utils.TruncateID(id), "Error downloading dependent layers", nil)) <ide> return err <ide> } <ide> func (srv *Server) pullRepository(r *registry.Registry, out io.Writer, localName <ide> if askedTag != "" && tag != askedTag { <ide> continue <ide> } <del> if err := srv.runtime.repositories.Set(localName, tag, id, true); err != nil { <add> if err := srv.runtime.Repositories().Set(localName, tag, id, true); err != nil { <ide> return err <ide> } <ide> } <del> if err := srv.runtime.repositories.Save(); err != nil { <add> if err := srv.runtime.Repositories().Save(); err != nil { <ide> return err <ide> } <ide> <ide> func (srv *Server) getImageList(localRepo map[string]string) ([]string, map[stri <ide> <ide> tagsByImage[id] = append(tagsByImage[id], tag) <ide> <del> for img, err := srv.runtime.graph.Get(id); img != nil; img, err = img.GetParent() { <add> for img, err := srv.runtime.Graph().Get(id); img != nil; img, err = img.GetParent() { <ide> if err != nil { <ide> return nil, nil, err <ide> } <ide> func (srv *Server) pushRepository(r *registry.Registry, out io.Writer, localName <ide> <ide> func (srv *Server) pushImage(r *registry.Registry, out io.Writer, remote, imgID, ep string, token []string, sf *utils.StreamFormatter) (checksum string, err error) { <ide> out = utils.NewWriteFlusher(out) <del> jsonRaw, err := ioutil.ReadFile(path.Join(srv.runtime.graph.Root, imgID, "json")) <add> jsonRaw, err := ioutil.ReadFile(path.Join(srv.runtime.Graph().Root, imgID, "json")) <ide> if err != nil { <ide> return "", fmt.Errorf("Cannot retrieve the path for {%s}: %s", imgID, err) <ide> } <ide> func (srv *Server) pushImage(r *registry.Registry, out io.Writer, remote, imgID, <ide> return "", err <ide> } <ide> <del> layerData, err := srv.runtime.graph.TempLayerArchive(imgID, archive.Uncompressed, sf, out) <add> layerData, err := srv.runtime.Graph().TempLayerArchive(imgID, archive.Uncompressed, sf, out) <ide> if err != nil { <ide> return "", fmt.Errorf("Failed to generate layer archive: %s", err) <ide> } <ide> func (srv *Server) ImagePush(job *engine.Job) engine.Status { <ide> return job.Error(err) <ide> } <ide> <del> img, err := srv.runtime.graph.Get(localName) <add> img, err := srv.runtime.Graph().Get(localName) <ide> r, err2 := registry.NewRegistry(authConfig, srv.HTTPRequestFactory(metaHeaders), endpoint) <ide> if err2 != nil { <ide> return job.Error(err2) <ide> } <ide> <ide> if err != nil { <del> reposLen := len(srv.runtime.repositories.Repositories[localName]) <add> reposLen := len(srv.runtime.Repositories().Repositories[localName]) <ide> job.Stdout.Write(sf.FormatStatus("", "The push refers to a repository [%s] (len: %d)", localName, reposLen)) <ide> // If it fails, try to get the repository <del> if localRepo, exists := srv.runtime.repositories.Repositories[localName]; exists { <add> if localRepo, exists := srv.runtime.Repositories().Repositories[localName]; exists { <ide> if err := srv.pushRepository(r, job.Stdout, localName, remoteName, localRepo, sf); err != nil { <ide> return job.Error(err) <ide> } <ide> func (srv *Server) ImageImport(job *engine.Job) engine.Status { <ide> defer progressReader.Close() <ide> archive = progressReader <ide> } <del> img, err := srv.runtime.graph.Create(archive, "", "", "Imported from "+src, "", nil, nil) <add> img, err := srv.runtime.Graph().Create(archive, "", "", "Imported from "+src, "", nil, nil) <ide> if err != nil { <ide> return job.Error(err) <ide> } <ide> // Optionally register the image at REPO/TAG <ide> if repo != "" { <del> if err := srv.runtime.repositories.Set(repo, tag, img.ID, true); err != nil { <add> if err := srv.runtime.Repositories().Set(repo, tag, img.ID, true); err != nil { <ide> return job.Error(err) <ide> } <ide> } <ide> func (srv *Server) ContainerCreate(job *engine.Job) engine.Status { <ide> if config.Memory != 0 && config.Memory < 524288 { <ide> return job.Errorf("Minimum memory limit allowed is 512k") <ide> } <del> if config.Memory > 0 && !srv.runtime.sysInfo.MemoryLimit { <add> if config.Memory > 0 && !srv.runtime.SystemConfig().MemoryLimit { <ide> job.Errorf("Your kernel does not support memory limit capabilities. Limitation discarded.\n") <ide> config.Memory = 0 <ide> } <del> if config.Memory > 0 && !srv.runtime.sysInfo.SwapLimit { <add> if config.Memory > 0 && !srv.runtime.SystemConfig().SwapLimit { <ide> job.Errorf("Your kernel does not support swap limit capabilities. Limitation discarded.\n") <ide> config.MemorySwap = -1 <ide> } <ide> resolvConf, err := utils.GetResolvConf() <ide> if err != nil { <ide> return job.Error(err) <ide> } <del> if !config.NetworkDisabled && len(config.Dns) == 0 && len(srv.runtime.config.Dns) == 0 && utils.CheckLocalDns(resolvConf) { <del> job.Errorf("Local (127.0.0.1) DNS resolver found in resolv.conf and containers can't use it. Using default external servers : %v\n", defaultDns) <del> config.Dns = defaultDns <add> if !config.NetworkDisabled && len(config.Dns) == 0 && len(srv.runtime.Config().Dns) == 0 && utils.CheckLocalDns(resolvConf) { <add> job.Errorf("Local (127.0.0.1) DNS resolver found in resolv.conf and containers can't use it. Using default external servers : %v\n", runtime.DefaultDns) <add> config.Dns = runtime.DefaultDns <ide> } <ide> <ide> container, buildWarnings, err := srv.runtime.Create(config, name) <ide> if err != nil { <del> if srv.runtime.graph.IsNotExist(err) { <add> if srv.runtime.Graph().IsNotExist(err) { <ide> _, tag := utils.ParseRepositoryTag(config.Image) <ide> if tag == "" { <ide> tag = graph.DEFAULTTAG <ide> func (srv *Server) ContainerCreate(job *engine.Job) engine.Status { <ide> } <ide> return job.Error(err) <ide> } <del> if !container.Config.NetworkDisabled && srv.runtime.sysInfo.IPv4ForwardingDisabled { <add> if !container.Config.NetworkDisabled && srv.runtime.SystemConfig().IPv4ForwardingDisabled { <ide> job.Errorf("IPv4 forwarding is disabled.\n") <ide> } <del> srv.LogEvent("create", container.ID, srv.runtime.repositories.ImageName(container.Image)) <add> srv.LogEvent("create", container.ID, srv.runtime.Repositories().ImageName(container.Image)) <ide> // FIXME: this is necessary because runtime.Create might return a nil container <ide> // with a non-nil error. This should not happen! Once it's fixed we <ide> // can remove this workaround. <ide> func (srv *Server) ContainerRestart(job *engine.Job) engine.Status { <ide> if err := container.Restart(int(t)); err != nil { <ide> return job.Errorf("Cannot restart container %s: %s\n", name, err) <ide> } <del> srv.LogEvent("restart", container.ID, srv.runtime.repositories.ImageName(container.Image)) <add> srv.LogEvent("restart", container.ID, srv.runtime.Repositories().ImageName(container.Image)) <ide> } else { <ide> return job.Errorf("No such container: %s\n", name) <ide> } <ide> func (srv *Server) ContainerDestroy(job *engine.Job) engine.Status { <ide> if container == nil { <ide> return job.Errorf("No such link: %s", name) <ide> } <del> name, err := getFullName(name) <add> name, err := runtime.GetFullContainerName(name) <ide> if err != nil { <ide> job.Error(err) <ide> } <ide> parent, n := path.Split(name) <ide> if parent == "/" { <ide> return job.Errorf("Conflict, cannot remove the default name of the container") <ide> } <del> pe := srv.runtime.containerGraph.Get(parent) <add> pe := srv.runtime.ContainerGraph().Get(parent) <ide> if pe == nil { <ide> return job.Errorf("Cannot get parent %s for name %s", parent, name) <ide> } <ide> parentContainer := srv.runtime.Get(pe.ID()) <ide> <del> if parentContainer != nil && parentContainer.activeLinks != nil { <del> if link, exists := parentContainer.activeLinks[n]; exists { <del> link.Disable() <del> } else { <del> utils.Debugf("Could not find active link for %s", name) <del> } <add> if parentContainer != nil { <add> parentContainer.DisableLink(n) <ide> } <ide> <del> if err := srv.runtime.containerGraph.Delete(name); err != nil { <add> if err := srv.runtime.ContainerGraph().Delete(name); err != nil { <ide> return job.Error(err) <ide> } <ide> return engine.StatusOK <ide> func (srv *Server) ContainerDestroy(job *engine.Job) engine.Status { <ide> if err := srv.runtime.Destroy(container); err != nil { <ide> return job.Errorf("Cannot destroy container %s: %s", name, err) <ide> } <del> srv.LogEvent("destroy", container.ID, srv.runtime.repositories.ImageName(container.Image)) <add> srv.LogEvent("destroy", container.ID, srv.runtime.Repositories().ImageName(container.Image)) <ide> <ide> if removeVolume { <ide> var ( <ide> volumes = make(map[string]struct{}) <ide> binds = make(map[string]struct{}) <del> usedVolumes = make(map[string]*Container) <add> usedVolumes = make(map[string]*runtime.Container) <ide> ) <ide> <ide> // the volume id is always the base of the path <ide> func (srv *Server) ContainerDestroy(job *engine.Job) engine.Status { <ide> } <ide> <ide> // populate bind map so that they can be skipped and not removed <del> for _, bind := range container.hostConfig.Binds { <add> for _, bind := range container.HostConfig().Binds { <ide> source := strings.Split(bind, ":")[0] <ide> // TODO: refactor all volume stuff, all of it <ide> // this is very important that we eval the link <ide> func (srv *Server) ContainerDestroy(job *engine.Job) engine.Status { <ide> log.Printf("The volume %s is used by the container %s. Impossible to remove it. Skipping.\n", volumeId, c.ID) <ide> continue <ide> } <del> if err := srv.runtime.volumes.Delete(volumeId); err != nil { <add> if err := srv.runtime.Volumes().Delete(volumeId); err != nil { <ide> return job.Errorf("Error calling volumes.Delete(%q): %v", volumeId, err) <ide> } <ide> } <ide> func (srv *Server) DeleteImage(name string, imgs *engine.Table, first, force boo <ide> tag = graph.DEFAULTTAG <ide> } <ide> <del> img, err := srv.runtime.repositories.LookupImage(name) <add> img, err := srv.runtime.Repositories().LookupImage(name) <ide> if err != nil { <del> if r, _ := srv.runtime.repositories.Get(repoName); r != nil { <add> if r, _ := srv.runtime.Repositories().Get(repoName); r != nil { <ide> return fmt.Errorf("No such image: %s:%s", repoName, tag) <ide> } <ide> return fmt.Errorf("No such image: %s", name) <ide> func (srv *Server) DeleteImage(name string, imgs *engine.Table, first, force boo <ide> tag = "" <ide> } <ide> <del> byParents, err := srv.runtime.graph.ByParent() <add> byParents, err := srv.runtime.Graph().ByParent() <ide> if err != nil { <ide> return err <ide> } <ide> <ide> //If delete by id, see if the id belong only to one repository <ide> if repoName == "" { <del> for _, repoAndTag := range srv.runtime.repositories.ByID()[img.ID] { <add> for _, repoAndTag := range srv.runtime.Repositories().ByID()[img.ID] { <ide> parsedRepo, parsedTag := utils.ParseRepositoryTag(repoAndTag) <ide> if repoName == "" || repoName == parsedRepo { <ide> repoName = parsedRepo <ide> func (srv *Server) DeleteImage(name string, imgs *engine.Table, first, force boo <ide> <ide> //Untag the current image <ide> for _, tag := range tags { <del> tagDeleted, err := srv.runtime.repositories.Delete(repoName, tag) <add> tagDeleted, err := srv.runtime.Repositories().Delete(repoName, tag) <ide> if err != nil { <ide> return err <ide> } <ide> func (srv *Server) DeleteImage(name string, imgs *engine.Table, first, force boo <ide> srv.LogEvent("untag", img.ID, "") <ide> } <ide> } <del> tags = srv.runtime.repositories.ByID()[img.ID] <add> tags = srv.runtime.Repositories().ByID()[img.ID] <ide> if (len(tags) <= 1 && repoName == "") || len(tags) == 0 { <ide> if len(byParents[img.ID]) == 0 { <ide> if err := srv.canDeleteImage(img.ID); err != nil { <ide> return err <ide> } <del> if err := srv.runtime.repositories.DeleteAll(img.ID); err != nil { <add> if err := srv.runtime.Repositories().DeleteAll(img.ID); err != nil { <ide> return err <ide> } <del> if err := srv.runtime.graph.Delete(img.ID); err != nil { <add> if err := srv.runtime.Graph().Delete(img.ID); err != nil { <ide> return err <ide> } <ide> out := &engine.Env{} <ide> func (srv *Server) ImageDelete(job *engine.Job) engine.Status { <ide> <ide> func (srv *Server) canDeleteImage(imgID string) error { <ide> for _, container := range srv.runtime.List() { <del> parent, err := srv.runtime.repositories.LookupImage(container.Image) <add> parent, err := srv.runtime.Repositories().LookupImage(container.Image) <ide> if err != nil { <ide> return err <ide> } <ide> func (srv *Server) canDeleteImage(imgID string) error { <ide> func (srv *Server) ImageGetCached(imgID string, config *runconfig.Config) (*image.Image, error) { <ide> <ide> // Retrieve all images <del> images, err := srv.runtime.graph.Map() <add> images, err := srv.runtime.Graph().Map() <ide> if err != nil { <ide> return nil, err <ide> } <ide> func (srv *Server) ImageGetCached(imgID string, config *runconfig.Config) (*imag <ide> // Loop on the children of the given image and check the config <ide> var match *image.Image <ide> for elem := range imageMap[imgID] { <del> img, err := srv.runtime.graph.Get(elem) <add> img, err := srv.runtime.Graph().Get(elem) <ide> if err != nil { <ide> return nil, err <ide> } <ide> func (srv *Server) ImageGetCached(imgID string, config *runconfig.Config) (*imag <ide> return match, nil <ide> } <ide> <del>func (srv *Server) RegisterLinks(container *Container, hostConfig *runconfig.HostConfig) error { <add>func (srv *Server) RegisterLinks(container *runtime.Container, hostConfig *runconfig.HostConfig) error { <ide> runtime := srv.runtime <ide> <ide> if hostConfig != nil && hostConfig.Links != nil { <ide> func (srv *Server) RegisterLinks(container *Container, hostConfig *runconfig.Hos <ide> // After we load all the links into the runtime <ide> // set them to nil on the hostconfig <ide> hostConfig.Links = nil <del> if err := container.writeHostConfig(); err != nil { <add> if err := container.WriteHostConfig(); err != nil { <ide> return err <ide> } <ide> } <ide> func (srv *Server) ContainerStart(job *engine.Job) engine.Status { <ide> if err := srv.RegisterLinks(container, hostConfig); err != nil { <ide> return job.Error(err) <ide> } <del> container.hostConfig = hostConfig <add> container.SetHostConfig(hostConfig) <ide> container.ToDisk() <ide> } <ide> if err := container.Start(); err != nil { <ide> return job.Errorf("Cannot start container %s: %s", name, err) <ide> } <del> srv.LogEvent("start", container.ID, runtime.repositories.ImageName(container.Image)) <add> srv.LogEvent("start", container.ID, runtime.Repositories().ImageName(container.Image)) <ide> <ide> return engine.StatusOK <ide> } <ide> func (srv *Server) ContainerStop(job *engine.Job) engine.Status { <ide> if err := container.Stop(int(t)); err != nil { <ide> return job.Errorf("Cannot stop container %s: %s\n", name, err) <ide> } <del> srv.LogEvent("stop", container.ID, srv.runtime.repositories.ImageName(container.Image)) <add> srv.LogEvent("stop", container.ID, srv.runtime.Repositories().ImageName(container.Image)) <ide> } else { <ide> return job.Errorf("No such container: %s\n", name) <ide> } <ide> func (srv *Server) ContainerAttach(job *engine.Job) engine.Status { <ide> return engine.StatusOK <ide> } <ide> <del>func (srv *Server) ContainerInspect(name string) (*Container, error) { <add>func (srv *Server) ContainerInspect(name string) (*runtime.Container, error) { <ide> if container := srv.runtime.Get(name); container != nil { <ide> return container, nil <ide> } <ide> return nil, fmt.Errorf("No such container: %s", name) <ide> } <ide> <ide> func (srv *Server) ImageInspect(name string) (*image.Image, error) { <del> if image, err := srv.runtime.repositories.LookupImage(name); err == nil && image != nil { <add> if image, err := srv.runtime.Repositories().LookupImage(name); err == nil && image != nil { <ide> return image, nil <ide> } <ide> return nil, fmt.Errorf("No such image: %s", name) <ide> func (srv *Server) JobInspect(job *engine.Job) engine.Status { <ide> return job.Error(errContainer) <ide> } <ide> object = &struct { <del> *Container <add> *runtime.Container <ide> HostConfig *runconfig.HostConfig <del> }{container, container.hostConfig} <add> }{container, container.HostConfig()} <ide> default: <ide> return job.Errorf("Unknown kind: %s", kind) <ide> } <ide> func (srv *Server) ContainerCopy(job *engine.Job) engine.Status { <ide> } <ide> <ide> func NewServer(eng *engine.Engine, config *daemonconfig.Config) (*Server, error) { <del> runtime, err := NewRuntime(config, eng) <add> runtime, err := runtime.NewRuntime(config, eng) <ide> if err != nil { <ide> return nil, err <ide> } <ide> func NewServer(eng *engine.Engine, config *daemonconfig.Config) (*Server, error) <ide> listeners: make(map[string]chan utils.JSONMessage), <ide> running: true, <ide> } <del> runtime.srv = srv <add> runtime.SetServer(srv) <ide> return srv, nil <ide> } <ide> <ide> func (srv *Server) Close() error { <ide> <ide> type Server struct { <ide> sync.RWMutex <del> runtime *Runtime <add> runtime *runtime.Runtime <ide> pullingPool map[string]chan struct{} <ide> pushingPool map[string]chan struct{} <ide> events []utils.JSONMessage <ide><path>utils.go <ide> package docker <ide> <ide> import ( <ide> "github.com/dotcloud/docker/archive" <del> "github.com/dotcloud/docker/nat" <del> "github.com/dotcloud/docker/pkg/namesgenerator" <del> "github.com/dotcloud/docker/runconfig" <ide> "github.com/dotcloud/docker/utils" <ide> ) <ide> <ide> type Change struct { <ide> archive.Change <ide> } <ide> <del>func migratePortMappings(config *runconfig.Config, hostConfig *runconfig.HostConfig) error { <del> if config.PortSpecs != nil { <del> ports, bindings, err := nat.ParsePortSpecs(config.PortSpecs) <del> if err != nil { <del> return err <del> } <del> config.PortSpecs = nil <del> if len(bindings) > 0 { <del> if hostConfig == nil { <del> hostConfig = &runconfig.HostConfig{} <del> } <del> hostConfig.PortBindings = bindings <del> } <del> <del> if config.ExposedPorts == nil { <del> config.ExposedPorts = make(nat.PortSet, len(ports)) <del> } <del> for k, v := range ports { <del> config.ExposedPorts[k] = v <del> } <del> } <del> return nil <del>} <del> <ide> // Links come in the format of <ide> // name:alias <ide> func parseLink(rawLink string) (map[string]string, error) { <ide> return utils.PartParser("name:alias", rawLink) <ide> } <del> <del>type checker struct { <del> runtime *Runtime <del>} <del> <del>func (c *checker) Exists(name string) bool { <del> return c.runtime.containerGraph.Exists("/" + name) <del>} <del> <del>// Generate a random and unique name <del>func generateRandomName(runtime *Runtime) (string, error) { <del> return namesgenerator.GenerateRandomName(&checker{runtime}) <del>}
15
Ruby
Ruby
replace sleep with synchronization
dae525eec8062bfbbe39141de448053b127d4756
<ide><path>activerecord/test/cases/scoping/default_scoping_test.rb <ide> require "models/computer" <ide> require "models/vehicle" <ide> require "models/cat" <add>require "concurrent/atomic/cyclic_barrier" <ide> <ide> class DefaultScopingTest < ActiveRecord::TestCase <ide> fixtures :developers, :posts, :comments <ide> def test_default_scope_is_threadsafe <ide> threads = [] <ide> assert_not_equal 1, ThreadsafeDeveloper.unscoped.count <ide> <add> barrier_1 = Concurrent::CyclicBarrier.new(2) <add> barrier_2 = Concurrent::CyclicBarrier.new(2) <add> <ide> threads << Thread.new do <del> Thread.current[:long_default_scope] = true <add> Thread.current[:default_scope_delay] = -> { barrier_1.wait; barrier_2.wait } <ide> assert_equal 1, ThreadsafeDeveloper.all.to_a.count <ide> ThreadsafeDeveloper.connection.close <ide> end <ide> threads << Thread.new do <add> Thread.current[:default_scope_delay] = -> { barrier_2.wait } <add> barrier_1.wait <ide> assert_equal 1, ThreadsafeDeveloper.all.to_a.count <ide> ThreadsafeDeveloper.connection.close <ide> end <ide><path>activerecord/test/models/developer.rb <ide> class ThreadsafeDeveloper < ActiveRecord::Base <ide> self.table_name = "developers" <ide> <ide> def self.default_scope <del> sleep 0.05 if Thread.current[:long_default_scope] <add> Thread.current[:default_scope_delay].call <ide> limit(1) <ide> end <ide> end
2
Ruby
Ruby
raise error if no watchlist
9f7e471382d61b5a6ea61c48767271edcedcebe2
<ide><path>Library/Homebrew/dev-cmd/livecheck.rb <ide> def livecheck <ide> rescue Errno::ENOENT => e <ide> onoe e <ide> end <add> else <add> raise UsageError, "ENV['HOMEBREW_LIVECHECK_WATCHLIST'] or ~/.brew_livecheck_watchlist is required " \ <add> "if no formula or cask argument is passed" <ide> end&.sort_by do |formula_or_cask| <ide> formula_or_cask.respond_to?(:token) ? formula_or_cask.token : formula_or_cask.name <ide> end
1
PHP
PHP
fix doc block in test
f9fbead4b61be40d3b3544d0fb5c37e508ff5f66
<ide><path>tests/test_app/TestApp/Controller/AuthTestController.php <ide> class AuthTestController extends Controller <ide> /** <ide> * testUrl property <ide> * <del> * @var mixed <add> * @var string|array <ide> */ <ide> public $testUrl = null; <ide> <ide> /** <ide> * construct method <add> * <add> * @param \Cake\Http\ServerRequest|null $request Request object for this controller. Can be null for testing, <add> * but expect that features that use the request parameters will not work. <add> * @param \Cake\Network\Response|null $response Response object for this controller. <ide> */ <ide> public function __construct($request = null, $response = null) <ide> { <ide> public function camelCase() <ide> /** <ide> * redirect method <ide> * <del> * @param mixed $url <del> * @param mixed $status <del> * @return void|\Cake\Network\Response <add> * @param string|array $url <add> * @param int $status <add> * @return \Cake\Network\Response|null <ide> */ <ide> public function redirect($url, $status = null) <ide> {
1
Javascript
Javascript
remove ngview manual transclusion system
b7a54497b51061d0f5d9ae74b74f5dd7c8eae51d
<ide><path>src/ngRoute/directive/ngView.js <ide> 'use strict'; <ide> <add>ngRouteModule.directive('ngView', ngViewFactory); <add> <ide> /** <ide> * @ngdoc directive <ide> * @name ngRoute.directive:ngView <ide> * @description <ide> * Emitted every time the ngView content is reloaded. <ide> */ <del>var NG_VIEW_PRIORITY = 500; <del>var ngViewDirective = ['$route', '$anchorScroll', '$compile', '$controller', '$animate', <del> function($route, $anchorScroll, $compile, $controller, $animate) { <add>ngViewFactory.$inject = ['$route', '$anchorScroll', '$compile', '$controller', '$animate']; <add>function ngViewFactory( $route, $anchorScroll, $compile, $controller, $animate) { <ide> return { <ide> restrict: 'ECA', <ide> terminal: true, <del> priority: NG_VIEW_PRIORITY, <del> compile: function(element, attr) { <del> var onloadExp = attr.onload || ''; <del> <del> element.html(''); <del> var anchor = jqLite(document.createComment(' ngView ')); <del> element.replaceWith(anchor); <del> <del> return function(scope) { <del> var currentScope, currentElement; <add> transclude: 'element', <add> compile: function(element, attr, linker) { <add> return function(scope, $element, attr) { <add> var currentScope, <add> currentElement, <add> onloadExp = attr.onload || ''; <ide> <ide> scope.$on('$routeChangeSuccess', update); <ide> update(); <ide> var ngViewDirective = ['$route', '$anchorScroll', '$compile', '$controller', '$a <ide> template = locals && locals.$template; <ide> <ide> if (template) { <del> cleanupLastView(); <del> <del> currentScope = scope.$new(); <del> currentElement = element.clone(); <del> currentElement.html(template); <del> $animate.enter(currentElement, null, anchor); <del> <del> var link = $compile(currentElement, false, NG_VIEW_PRIORITY - 1), <del> current = $route.current; <del> <del> if (current.controller) { <del> locals.$scope = currentScope; <del> var controller = $controller(current.controller, locals); <del> if (current.controllerAs) { <del> currentScope[current.controllerAs] = controller; <add> var newScope = scope.$new(); <add> linker(newScope, function(clone) { <add> cleanupLastView(); <add> <add> clone.html(template); <add> $animate.enter(clone, null, $element); <add> <add> var link = $compile(clone.contents()), <add> current = $route.current; <add> <add> currentScope = current.scope = newScope; <add> currentElement = clone; <add> <add> if (current.controller) { <add> locals.$scope = currentScope; <add> var controller = $controller(current.controller, locals); <add> if (current.controllerAs) { <add> currentScope[current.controllerAs] = controller; <add> } <add> clone.data('$ngControllerController', controller); <add> clone.contents().data('$ngControllerController', controller); <ide> } <del> currentElement.data('$ngControllerController', controller); <del> currentElement.children().data('$ngControllerController', controller); <del> } <del> <del> current.scope = currentScope; <ide> <del> link(currentScope); <add> link(currentScope); <add> currentScope.$emit('$viewContentLoaded'); <add> currentScope.$eval(onloadExp); <ide> <del> currentScope.$emit('$viewContentLoaded'); <del> currentScope.$eval(onloadExp); <del> <del> // $anchorScroll might listen on event... <del> $anchorScroll(); <add> // $anchorScroll might listen on event... <add> $anchorScroll(); <add> }); <ide> } else { <ide> cleanupLastView(); <ide> } <ide> } <ide> } <ide> } <ide> }; <del>}]; <del> <del>ngRouteModule.directive('ngView', ngViewDirective); <add>}
1
PHP
PHP
update assetfilter to use response methods
a11ab397f8eecad3a601dd5e11a92a5e9cb2ba99
<ide><path>src/Routing/Filter/AssetFilter.php <ide> public function beforeDispatch(Event $event) <ide> <ide> $pathSegments = explode('.', $url); <ide> $ext = array_pop($pathSegments); <del> $this->_deliverAsset($request, $response, $assetFile, $ext); <del> <del> return $response; <add> return $this->_deliverAsset($request, $response, $assetFile, $ext); <ide> } <ide> <ide> /** <ide> protected function _deliverAsset(Request $request, Response $response, $assetFil <ide> $response->header('Content-Length', filesize($assetFile)); <ide> } <ide> $response->cache(filemtime($assetFile), $this->_cacheTime); <del> $response->sendHeaders(); <del> readfile($assetFile); <del> if ($compressionEnabled) { <del> ob_end_flush(); <del> } <add> $response->file($assetFile); <add> return $response; <ide> } <ide> } <ide><path>tests/TestCase/Routing/Filter/AssetFilterTest.php <ide> public function testAsset($url, $file) <ide> $request = new Request($url); <ide> $event = new Event('Dispatcher.beforeDispatch', $this, compact('request', 'response')); <ide> <del> ob_start(); <del> $filter->beforeDispatch($event); <del> $result = ob_get_contents(); <del> ob_end_clean(); <add> $response = $filter->beforeDispatch($event); <add> $result = $response->getFile(); <ide> <ide> $path = TEST_APP . str_replace('/', DS, $file); <ide> $file = file_get_contents($path); <del> $this->assertEquals($file, $result); <add> $this->assertEquals($file, $result->read()); <ide> <ide> $expected = filesize($path); <ide> $headers = $response->header();
2
Ruby
Ruby
clarify xquartz warning
4cbaeb6d61f10db1abcb3f844c3bc234107732c5
<ide><path>Library/Homebrew/cmd/doctor.rb <ide> def check_xcode_license_approved <ide> end <ide> <ide> def check_for_latest_xquartz <del> quartz = MacOS::XQuartz.version <del> return unless quartz <add> return unless MacOS::XQuartz.installed? <ide> return if MacOS::XQuartz.provided_by_apple? <ide> <del> quartz = Version.new(quartz) <del> latest = Version.new(MacOS::XQuartz.latest_version) <add> installed_version = Version.new(MacOS::XQuartz.version) <add> latest_version = Version.new(MacOS::XQuartz.latest_version) <ide> <del> return if quartz >= latest <add> return if installed_version >= latest_version <ide> <del> <<-EOS.undent <del> Your XQuartz (#{quartz}) is outdated <del> Please install XQuartz #{latest}. <del> EOS <add> case MacOS.version <add> when "10.9" then <<-EOS.undent <add> Your XQuartz (#{installed_version}) is outdated <add> OS X Mavericks requires XQuartz #{latest_version}: <add> http://xquartz.macosforge.org/trac/wiki/X112.7.5 <add> EOS <add> else <<-EOS.undent <add> Your XQuartz (#{installed_version}) is outdated <add> Please install XQuartz #{latest_version}: <add> https://xquartz.macosforge.org <add> EOS <add> end <ide> end <ide> end # end class Checks <ide>
1
Python
Python
add tests for new response classes
2d3e1deb1e4e5c7a225ff0f271f249cb7e56b0af
<ide><path>test/test_response_classes.py <add># Licensed to the Apache Software Foundation (ASF) under one or more <add># contributor license agreements. See the NOTICE file distributed with <add># this work for additional information regarding copyright ownership. <add># The ASF licenses this file to You under the Apache License, Version 2.0 <add># (the "License"); you may not use this file except in compliance with <add># the License. You may obtain a copy of the License at <add># <add># http://www.apache.org/licenses/LICENSE-2.0 <add># <add># Unless required by applicable law or agreed to in writing, software <add># distributed under the License is distributed on an "AS IS" BASIS, <add># WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add># See the License for the specific language governing permissions and <add># limitations under the License. <add> <add>import sys <add>import unittest <add>import httplib <add> <add>from mock import Mock <add> <add>from libcloud.common.base import XmlResponse, JsonResponse <add>from libcloud.common.types import MalformedResponseError <add> <add> <add>class ResponseClassesTests(unittest.TestCase): <add> def setUp(self): <add> self._mock_response = Mock() <add> self._mock_response.getheaders.return_value = [] <add> self._mock_response.status = httplib.OK <add> self._mock_connection = Mock() <add> <add> def test_XmlResponse_class(self): <add> self._mock_response.read.return_value = '<foo>bar</foo>' <add> response = XmlResponse(response=self._mock_response, <add> connection=self._mock_connection) <add> <add> parsed = response.parse_body() <add> self.assertEqual(parsed.tag, 'foo') <add> self.assertEqual(parsed.text, 'bar') <add> <add> def test_XmlResponse_class_malformed_response(self): <add> self._mock_response.read.return_value = '<foo>' <add> <add> try: <add> XmlResponse(response=self._mock_response, <add> connection=self._mock_connection) <add> except MalformedResponseError: <add> pass <add> else: <add> self.fail('Exception was not thrown') <add> <add> def test_XmlResponse_class_zero_length_body_strip(self): <add> self._mock_response.read.return_value = ' ' <add> <add> response = XmlResponse(response=self._mock_response, <add> connection=self._mock_connection) <add> <add> parsed = response.parse_body() <add> self.assertEqual(parsed, '') <add> <add> def test_JsonResponse_class_success(self): <add> self._mock_response.read.return_value = '{"foo": "bar"}' <add> response = JsonResponse(response=self._mock_response, <add> connection=self._mock_connection) <add> <add> parsed = response.parse_body() <add> self.assertEqual(parsed, {'foo': 'bar'}) <add> <add> def test_JsonResponse_class_malformed_response(self): <add> self._mock_response.read.return_value = '{"foo": "bar' <add> <add> try: <add> JsonResponse(response=self._mock_response, <add> connection=self._mock_connection) <add> except MalformedResponseError: <add> pass <add> else: <add> self.fail('Exception was not thrown') <add> <add> def test_JsonResponse_class_zero_length_body_strip(self): <add> self._mock_response.read.return_value = ' ' <add> <add> response = JsonResponse(response=self._mock_response, <add> connection=self._mock_connection) <add> <add> parsed = response.parse_body() <add> self.assertEqual(parsed, '') <add> <add> <add>if __name__ == '__main__': <add> sys.exit(unittest.main())
1
PHP
PHP
add route macro
7f08a725e0fdf34a7569bc62ec51220d8af9581f
<ide><path>src/Illuminate/Routing/Router.php <ide> use Illuminate\Pipeline\Pipeline; <ide> use Illuminate\Support\Collection; <ide> use Illuminate\Container\Container; <add>use Illuminate\Support\Traits\Macroable; <ide> use Illuminate\Contracts\Events\Dispatcher; <ide> use Illuminate\Contracts\Routing\Registrar as RegistrarContract; <ide> use Symfony\Component\HttpFoundation\Response as SymfonyResponse; <ide> use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; <ide> <ide> class Router implements RegistrarContract { <ide> <add> use Macroable; <add> <ide> /** <ide> * The event dispatcher instance. <ide> * <ide><path>tests/Routing/RoutingRouteTest.php <ide> public function testBasicDispatchingOfRoutes() <ide> } <ide> <ide> <add> public function testMacro() <add> { <add> $router = $this->getRouter(); <add> $router->macro('webhook', function() use ($router) <add> { <add> $router->match(['GET', 'POST'], 'webhook', function() { return 'OK'; }); <add> }); <add> $router->webhook(); <add> $this->assertEquals('OK', $router->dispatch(Request::create('webhook', 'GET'))->getContent()); <add> $this->assertEquals('OK', $router->dispatch(Request::create('webhook', 'POST'))->getContent()); <add> } <add> <add> <ide> public function testClassesCanBeInjectedIntoRoutes() <ide> { <ide> unset($_SERVER['__test.route_inject']);
2
Javascript
Javascript
improve docs and examples further
74ef7f14a49662ebf389a515b86e6dd68e746811
<ide><path>src/auto/injector.js <ide> function annotate(fn) { <ide> * <ide> * @description <ide> * <del> * Use `$provide` to register new providers with the `$injector`. The providers are the factories for the instance. <del> * The providers share the same name as the instance they create with `Provider` suffixed to them. <del> * <del> * A provider is an object with a `$get()` method. The injector calls the `$get` method to create a new instance of <del> * a service. The Provider can have additional methods which would allow for configuration of the provider. <del> * <del> * <pre> <del> * function TrackingProvider() { <del> * this.$get = function($http) { <del> * var observed = {}; <del> * return { <del> * event: function(event) { <del> * var current = observed[event]; <del> * return observed[event] = current ? current + 1 : 1; <del> * }, <del> * save: function() { <del> * $http.post("/track",observed); <del> * } <del> * }; <del> * }; <del> * } <del> * <del> * describe('Tracking', function() { <del> * var mocked; <del> * beforeEach(module(function($provide) { <del> * $provide.provider('tracking', TrackingProvider); <del> * mocked = {post: jasmine.createSpy('postSpy')}; <del> * $provide.value('$http',mocked); <del> * })); <del> * it('allows events to be tracked', inject(function(tracking) { <del> * expect(tracking.event('login')).toEqual(1); <del> * expect(tracking.event('login')).toEqual(2); <del> * })); <del> * <del> * it('posts to save', inject(function(tracking) { <del> * tracking.save(); <del> * expect(mocked.post.callCount).toEqual(1); <del> * })); <del> * }); <del> * </pre> <del> * <del> * There are also shorthand methods to define services that don't need to be configured beyond their `$get()` method. <del> * <del> * `service()` registers a constructor function which will be invoked with `new` to create the instance. You can specify services that will be provided by the injector. <del> * <del> * <pre> <del> * function TrackingProvider($http) { <del> * var observed = {}; <del> * this.event = function(event) { <del> * var current = observed[event]; <del> * return observed[event] = current ? current + 1 : 1; <del> * }; <del> * this.save = function() { <del> * $http.post("/track",observed); <del> * }; <del> * } <del> * $provider.service('tracking',TrackingProvider); <del> * </pre> <del> * <del> * `factory()` registers a function whose return value is the instance. Again, you can specify services that will be provided by the injector. <del> * <del> * <pre> <del> * function TrackingProvider($http) { <del> * var observed = {}; <del> * return { <del> * event: function(event) { <del> * var current = observed[event]; <del> * return observed[event] = current ? current + 1 : 1; <del> * }, <del> * save: function() { <del> * $http.post("/track",observed); <del> * } <del> * }; <del> * } <del> * $provider.factory('tracking',TrackingProvider); <del> * </pre> <del> * <add> * The {@link AUTO.$provide $provide} service has a number of methods for registering components with <add> * the {@link AUTO.$injector $injector}. Many of these functions are also exposed on {@link angular.Module}. <add> * <add> * An Angular **service** is a singleton object created by a **service factory**. These **service <add> * factories** are functions which, in turn, are created by a **service provider**. <add> * The **service providers** are constructor functions. When instantiated they must contain a property <add> * called `$get`, which holds the **service factory** function. <add> * <add> * When you request a service, the {@link AUTO.$injector $injector} is responsible for finding the <add> * correct **service provider**, instantiating it and then calling its `$get` **service factory** <add> * function to get the instance of the **service**. <add> * <add> * Often services have no configuration options and there is no need to add methods to the service <add> * provider. The provider will be no more than a constructor function with a `$get` property. For <add> * these cases the {@link AUTO.$provide $provide} service has additional helper methods to register <add> * services without specifying a provider. <add> * <add> * * {@link AUTO.$provide#provider provider(provider)} - registers a **service provider** with the <add> * {@link AUTO.$injector $injector} <add> * * {@link AUTO.$provide#constant constant(obj)} - registers a value/object that can be accessed by <add> * providers and services. <add> * * {@link AUTO.$provide#value value(obj)} - registers a value/object that can only be accessed by <add> * services, not providers. <add> * * {@link AUTO.$provide#factory factory(fn)} - registers a service **factory function**, `fn`, that <add> * will be wrapped in a **service provider** object, whose `$get` property will contain the given <add> * factory function. <add> * * {@link AUTO.$provide#service service(class)} - registers a **constructor function**, `class` that <add> * will be wrapped in a **service provider** object, whose `$get` property will instantiate a new <add> * object using the given constructor function. <add> * <add> * See the individual methods for more information and examples. <ide> */ <ide> <ide> /** <ide> function annotate(fn) { <ide> * @methodOf AUTO.$provide <ide> * @description <ide> * <del> * Register a provider for a service. The providers can be retrieved and can have additional configuration methods. <add> * Register a **provider function** with the {@link AUTO.$injector $injector}. Provider functions are <add> * constructor functions, whose instances are responsible for "providing" a factory for a service. <add> * <add> * Service provider names start with the name of the service they provide followed by `Provider`. <add> * For example, the {@link ng.$log $log} service has a provider called {@link ng.$logProvider $logProvider}. <add> * <add> * Service provider objects can have additional methods which allow configuration of the provider and <add> * its service. Importantly, you can configure what kind of service is created by the `$get` method, <add> * or how that service will act. For example, the {@link ng.$logProvider $logProvider} has a method <add> * {@link ng.$logProvider#debugEnabled debugEnabled} <add> * which lets you specify whether the {@link ng.$log $log} service will log debug messages to the <add> * console or not. <ide> * <ide> * @param {string} name The name of the instance. NOTE: the provider will be available under `name + 'Provider'` key. <ide> * @param {(Object|function())} provider If the provider is: <ide> function annotate(fn) { <ide> * {@link AUTO.$injector#instantiate $injector.instantiate()}, then treated as `object`. <ide> * <ide> * @returns {Object} registered provider instance <add> <add> * @example <add> * <add> * The following example shows how to create a simple event tracking service and register it using <add> * {@link AUTO.$provide#provider $provide.provider()}. <add> * <add> * <pre> <add> * // Define the eventTracker provider <add> * function EventTrackerProvider() { <add> * var trackingUrl = '/track'; <add> * <add> * // A provider method for configuring where the tracked events should been saved <add> * this.setTrackingUrl = function(url) { <add> * trackingUrl = url; <add> * }; <add> * <add> * // The service factory function <add> * this.$get = ['$http', function($http) { <add> * var trackedEvents = {}; <add> * return { <add> * // Call this to track an event <add> * event: function(event) { <add> * var count = trackedEvents[event] || 0; <add> * count += 1; <add> * trackedEvents[event] = count; <add> * return count; <add> * }, <add> * // Call this to save the tracked events to the trackingUrl <add> * save: function() { <add> * $http.post(trackingUrl, trackedEvents); <add> * } <add> * }; <add> * }]; <add> * } <add> * <add> * describe('eventTracker', function() { <add> * var postSpy; <add> * <add> * beforeEach(module(function($provide) { <add> * // Register the eventTracker provider <add> * $provide.provider('eventTracker', EventTrackerProvider); <add> * })); <add> * <add> * beforeEach(module(function(eventTrackerProvider) { <add> * // Configure eventTracker provider <add> * eventTrackerProvider.setTrackingUrl('/custom-track'); <add> * })); <add> * <add> * it('tracks events', inject(function(eventTracker) { <add> * expect(eventTracker.event('login')).toEqual(1); <add> * expect(eventTracker.event('login')).toEqual(2); <add> * })); <add> * <add> * it('saves to the tracking url', inject(function(eventTracker, $http) { <add> * postSpy = spyOn($http, 'post'); <add> * eventTracker.event('login'); <add> * eventTracker.save(); <add> * expect(postSpy).toHaveBeenCalled(); <add> * expect(postSpy.mostRecentCall.args[0]).not.toEqual('/track'); <add> * expect(postSpy.mostRecentCall.args[0]).toEqual('/custom-track'); <add> * expect(postSpy.mostRecentCall.args[1]).toEqual({ 'login': 1 }); <add> * })); <add> * }); <add> * </pre> <ide> */ <ide> <ide> /** <ide> function annotate(fn) { <ide> * @methodOf AUTO.$provide <ide> * @description <ide> * <del> * A service whose instance is the return value of `$getFn`. Short hand for configuring services if only `$get` method is required. <add> * Register a **service factory**, which will be called to return the service instance. <add> * This is short for registering a service where its provider consists of only a `$get` property, <add> * which is the given service factory function. <add> * You should use {@link AUTO.$provide#factory $provide.factor(getFn)} if you do not need to configure <add> * your service in a provider. <ide> * <ide> * @param {string} name The name of the instance. <ide> * @param {function()} $getFn The $getFn for the instance creation. Internally this is a short hand for <ide> * `$provide.provider(name, {$get: $getFn})`. <ide> * @returns {Object} registered provider instance <add> * <add> * @example <add> * Here is an example of registering a service <add> * <pre> <add> * $provide.factory('ping', ['$http', function($http) { <add> * return function ping() { <add> * return $http.send('/ping'); <add> * }; <add> * }]); <add> * </pre> <add> * You would then inject and use this service like this: <add> * <pre> <add> * someModule.controller('Ctrl', ['ping', function(ping) { <add> * ping(); <add> * }]); <add> * </pre> <ide> */ <ide> <ide> <ide> function annotate(fn) { <ide> * @methodOf AUTO.$provide <ide> * @description <ide> * <del> * A service whose instance is created by invoking `constructor` with `new`. A short hand for registering services which use a constructor. <add> * Register a **service constructor**, which will be invoked with `new` to create the service instance. <add> * This is short for registering a service where its provider's `$get` property is the service <add> * constructor function that will be used to instantiate the service instance. <add> * <add> * You should use {@link AUTO.$provide#service $provide.service(class)} if you define your service <add> * as a type/class. This is common when using {@link http://coffeescript.org CoffeeScript}. <ide> * <ide> * @param {string} name The name of the instance. <ide> * @param {Function} constructor A class (constructor function) that will be instantiated. <ide> * @returns {Object} registered provider instance <add> * <add> * @example <add> * Here is an example of registering a service using {@link AUTO.$provide#service $provide.service(class)} <add> * that is defined as a CoffeeScript class. <add> * <pre> <add> * class Ping <add> * constructor: (@$http)-> <add> * send: ()=> <add> * @$http.get('/ping') <add> * <add> * $provide.service('ping', ['$http', Ping]) <add> * </pre> <add> * You would then inject and use this service like this: <add> * <pre> <add> * someModule.controller 'Ctrl', ['ping', (ping)-> <add> * ping.send() <add> * ] <add> * </pre> <ide> */ <ide> <ide> <ide> function annotate(fn) { <ide> * @methodOf AUTO.$provide <ide> * @description <ide> * <del> * A short hand for configuring services if the `$get` method is a constant. <add> * Register a **value service** with the {@link AUTO.$injector $injector}, such as a string, a number, <add> * an array, an object or a function. This is short for registering a service where its provider's <add> * `$get` property is a factory function that takes no arguments and returns the **value service**. <ide> * <add> * Value services are similar to constant services, except that they cannot be injected into a module <add> * configuration function (see {@link angular.Module#config}) but they can be overridden by an Angular <add> * {@link AUTO.$provide#decorator decorator}. <add> * <ide> * @param {string} name The name of the instance. <ide> * @param {*} value The value. <ide> * @returns {Object} registered provider instance <add> * <add> * @example <add> * Here are some examples of creating value services. <add> * <pre> <add> * $provide.constant('ADMIN_USER', 'admin'); <add> * <add> * $provide.constant('RoleLookup', { admin: 0, writer: 1, reader: 2 }); <add> * <add> * $provide.constant('halfOf', function(value) { <add> * return value / 2; <add> * }); <add> * </pre> <ide> */ <ide> <ide> <ide> function annotate(fn) { <ide> * @methodOf AUTO.$provide <ide> * @description <ide> * <del> * A constant value, but unlike {@link AUTO.$provide#value value} it can be injected <del> * into configuration function (other modules) and it is not interceptable by <del> * {@link AUTO.$provide#decorator decorator}. <add> * Register a **constant service**, such as a string, a number, an array, an object or a function, with <add> * the {@link AUTO.$injector $injector}. Unlike {@link AUTO.$provide#value value} it can be injected <add> * into a module configuration function (see {@link angular.Module#config}) and it cannot be <add> * overridden by an Angular {@link AUTO.$provide#decorator decorator}. <ide> * <ide> * @param {string} name The name of the constant. <ide> * @param {*} value The constant value. <ide> * @returns {Object} registered instance <add> * <add> * @example <add> * Here a some examples of creating constants: <add> * <pre> <add> * $provide.constant('SHARD_HEIGHT', 306); <add> * <add> * $provide.constant('MY_COLOURS', ['red', 'blue', 'grey']); <add> * <add> * $provide.constant('double', function(value) { <add> * return value * 2; <add> * }); <add> * </pre> <ide> */ <ide> <ide> <ide> function annotate(fn) { <ide> * @methodOf AUTO.$provide <ide> * @description <ide> * <del> * Decoration of service, allows the decorator to intercept the service instance creation. The <del> * returned instance may be the original instance, or a new instance which delegates to the <del> * original instance. <add> * Register a **service decorator** with the {@link AUTO.$injector $injector}. A service decorator <add> * intercepts the creation of a service, allowing it to override or modify the behaviour of the <add> * service. The object returned by the decorator may be the original service, or a new service object <add> * which replaces or wraps and delegates to the original service. <ide> * <ide> * @param {string} name The name of the service to decorate. <ide> * @param {function()} decorator This function will be invoked when the service needs to be <del> * instantiated. The function is called using the {@link AUTO.$injector#invoke <del> * injector.invoke} method and is therefore fully injectable. Local injection arguments: <add> * instantiated and should return the decorated service instance. The function is called using <add> * the {@link AUTO.$injector#invoke injector.invoke} method and is therefore fully injectable. <add> * Local injection arguments: <ide> * <ide> * * `$delegate` - The original service instance, which can be monkey patched, configured, <ide> * decorated or delegated to. <add> * <add> * @example <add> * Here we decorate the {@link ng.$log $log} service to convert warnings to errors by intercepting <add> * calls to {@link ng.$log#error $log.warn()}. <add> * <pre> <add> * $provider.decorator('$log', ['$delegate', function($delegate) { <add> * $delegate.warn = $delegate.error; <add> * return $delegate; <add> * }]); <add> * </pre> <ide> */ <ide> <ide>
1
PHP
PHP
remove invalid throws. restore typehint for ide
28756542b171fa2261a38a2ae35fa56d2840eba0
<ide><path>src/Database/Type/DecimalType.php <ide> public function toDatabase($value, DriverInterface $driver) <ide> * @param mixed $value The value to convert. <ide> * @param \Cake\Database\DriverInterface $driver The driver instance to convert with. <ide> * @return string|null <del> * @throws \Cake\Core\Exception\Exception <ide> */ <ide> public function toPHP($value, DriverInterface $driver): ?string <ide> { <ide> public function marshal($value): ?string <ide> * <ide> * @param bool $enable Whether or not to enable <ide> * @return $this <add> * @throws \RuntimeException <ide> */ <ide> public function useLocaleParser(bool $enable = true) <ide> { <ide> public function useLocaleParser(bool $enable = true) <ide> */ <ide> protected function _parseValue(string $value): string <ide> { <add> /* @var \Cake\I18n\Number $class */ <ide> $class = static::$numberClass; <ide> <ide> return (string)$class::parseFloat($value);
1
Go
Go
make daemon initialization in main goroutine
181fea24aac7499a3d6dc0c8c9de67e6c0036140
<ide><path>docker/daemon.go <ide> import ( <ide> "io" <ide> "os" <ide> "path/filepath" <del> "strings" <ide> <ide> "github.com/Sirupsen/logrus" <ide> apiserver "github.com/docker/docker/api/server" <ide> func mainDaemon() { <ide> } <ide> daemonCfg.TrustKeyPath = *flTrustKey <ide> <del> registryService := registry.NewService(registryCfg) <del> // load the daemon in the background so we can immediately start <del> // the http api so that connections don't fail while the daemon <del> // is booting <del> daemonInitWait := make(chan error) <del> go func() { <del> d, err := daemon.NewDaemon(daemonCfg, eng, registryService) <del> if err != nil { <del> daemonInitWait <- err <del> return <del> } <del> <del> logrus.WithFields(logrus.Fields{ <del> "version": dockerversion.VERSION, <del> "commit": dockerversion.GITCOMMIT, <del> "execdriver": d.ExecutionDriver().Name(), <del> "graphdriver": d.GraphDriver().String(), <del> }).Info("Docker daemon") <del> <del> if err := d.Install(eng); err != nil { <del> daemonInitWait <- err <del> return <del> } <del> <del> b := &builder.BuilderJob{eng, d} <del> b.Install() <del> <del> // after the daemon is done setting up we can tell the api to start <del> // accepting connections <del> apiserver.AcceptConnections() <del> <del> daemonInitWait <- nil <del> }() <del> <ide> serverConfig := &apiserver.ServerConfig{ <ide> Logging: true, <ide> EnableCors: daemonCfg.EnableCors, <ide> func mainDaemon() { <ide> serveAPIWait <- nil <ide> }() <ide> <del> // Wait for the daemon startup goroutine to finish <del> // This makes sure we can actually cleanly shutdown the daemon <del> logrus.Debug("waiting for daemon to initialize") <del> errDaemon := <-daemonInitWait <del> if errDaemon != nil { <add> registryService := registry.NewService(registryCfg) <add> d, err := daemon.NewDaemon(daemonCfg, eng, registryService) <add> if err != nil { <ide> eng.Shutdown() <del> outStr := fmt.Sprintf("Shutting down daemon due to errors: %v", errDaemon) <del> if strings.Contains(errDaemon.Error(), "engine is shutdown") { <del> // if the error is "engine is shutdown", we've already reported (or <del> // will report below in API server errors) the error <del> outStr = "Shutting down daemon due to reported errors" <del> } <del> // we must "fatal" exit here as the API server may be happy to <del> // continue listening forever if the error had no impact to API <del> logrus.Fatal(outStr) <del> } else { <del> logrus.Info("Daemon has completed initialization") <add> logrus.Fatalf("Error starting daemon: %v", err) <ide> } <ide> <add> if err := d.Install(eng); err != nil { <add> eng.Shutdown() <add> logrus.Fatalf("Error starting daemon: %v", err) <add> } <add> <add> logrus.Info("Daemon has completed initialization") <add> <add> logrus.WithFields(logrus.Fields{ <add> "version": dockerversion.VERSION, <add> "commit": dockerversion.GITCOMMIT, <add> "execdriver": d.ExecutionDriver().Name(), <add> "graphdriver": d.GraphDriver().String(), <add> }).Info("Docker daemon") <add> <add> b := &builder.BuilderJob{eng, d} <add> b.Install() <add> <add> // after the daemon is done setting up we can tell the api to start <add> // accepting connections <add> apiserver.AcceptConnections() <add> <ide> // Daemon is fully initialized and handling API traffic <ide> // Wait for serve API job to complete <ide> errAPI := <-serveAPIWait <del> // If we have an error here it is unique to API (as daemonErr would have <del> // exited the daemon process above) <ide> eng.Shutdown() <ide> if errAPI != nil { <ide> logrus.Fatalf("Shutting down due to ServeAPI error: %v", errAPI) <ide><path>integration-cli/docker_cli_daemon_test.go <ide> func TestDaemonExitOnFailure(t *testing.T) { <ide> t.Fatalf("Expected daemon not to start, got %v", err) <ide> } <ide> // look in the log and make sure we got the message that daemon is shutting down <del> runCmd := exec.Command("grep", "Shutting down daemon due to", d.LogfileName()) <add> runCmd := exec.Command("grep", "Error starting daemon", d.LogfileName()) <ide> if out, _, err := runCommandWithOutput(runCmd); err != nil { <del> t.Fatalf("Expected 'shutting down daemon due to error' message; but doesn't exist in log: %q, err: %v", out, err) <add> t.Fatalf("Expected 'Error starting daemon' message; but doesn't exist in log: %q, err: %v", out, err) <ide> } <ide> } else { <ide> //if we didn't get an error and the daemon is running, this is a failure
2
Python
Python
apply suggestions from code review
74df99926a2d561cd756d6df87f27af264213933
<ide><path>numpy/__init__.py <ide> ) <ide> for n, n2 in [("long", "int"), ("unicode", "str")] <ide> }) <add> # Numpy 1.20.0, 2020-10-19 <ide> __deprecated_attrs__["typeDict"] = ( <del> getattr(core.numerictypes, "typeDict"), <add> core.numerictypes.typeDict, <ide> "`np.typeDict` is a deprecated alias for `np.sctypeDict`." <ide> ) <ide> <ide><path>numpy/core/numerictypes.py <ide> def sctype2char(sctype): <ide> 'All':'?bhilqpBHILQPefdgFDGSUVOMm'} <ide> <ide> # backwards compatibility --- deprecated name <del># Formal deprecation: Numpy 1.20.0, 2020-10-19 <add># Formal deprecation: Numpy 1.20.0, 2020-10-19 (see numpy/__init__.py) <ide> typeDict = sctypeDict <ide> <ide> # b -> boolean <ide><path>numpy/core/tests/test_scalarmath.py <ide> def test_iinfo_long_values(self): <ide> assert_(res == tgt) <ide> <ide> for code in np.typecodes['AllInteger']: <del> res = np.sctypeDict[code](np.iinfo(code).max) <add> res = np.dtype(code).type(np.iinfo(code).max) <ide> tgt = np.iinfo(code).max <ide> assert_(res == tgt) <ide>
3
PHP
PHP
remove unnecessary variable
602efbadde06601577904c66608829087f2ce771
<ide><path>tests/Broadcasting/BroadcasterTest.php <ide> public function testNotFoundThrowsHttpException() <ide> $broadcaster = new FakeBroadcaster(); <ide> $callback = function ($user, BroadcasterTestEloquentModelNotFoundStub $model) { <ide> }; <del> $parameters = $broadcaster->extractAuthParameters('asd.{model}', 'asd.1', $callback); <add> $broadcaster->extractAuthParameters('asd.{model}', 'asd.1', $callback); <ide> } <ide> } <ide>
1
Text
Text
add 0.68.3 changelog
bd17d83be112c2a0482c99d2a3e5d54ec7a6319c
<ide><path>CHANGELOG.md <ide> <ide> - Encode URL params in URLSearchParams.toString() ([1042a8012f](https://github.com/facebook/react-native/commit/1042a8012fb472bd5c882b469fe507dd6279d562) by [@sshic](https://github.com/sshic)) <ide> <add>## v0.68.3 <add> <add>### Changed <add> <add>#### Android specific <add> <add>- Let's not build reactnativeutilsjni shared library ([af9225ec5f](https://github.com/facebook/react-native/commit/af9225ec5fd22da802e3da4d786fa7f6ec956b0f) by [@SparshaSaha](https://github.com/SparshaSaha)) <add>- Modified **getDefaultJSExecutorFactory** method ([87cfd386cb](https://github.com/facebook/react-native/commit/87cfd386cb2e02bfa440c94706d9d0274f83070c) by [@KunalFarmah98](https://github.com/KunalFarmah98)) <add> <add>### Fixed <add> <add>- Use monotonic clock for performance.now() ([114d31feee](https://github.com/facebook/react-native/commit/114d31feeeb47f5a57419e5088c3cbe9340f757a)) <add> <add>#### Android specific <add> <add>- Logging a soft error when ReactRootView has an id other than -1 instead of crashing the app in hybrid apps ([1ca2c24930](https://github.com/facebook/react-native/commit/1ca2c2493027c1b027146cd41e17dd8a4fc33a41) by [@Kunal-Airtel2022](https://github.com/Kunal-Airtel2022)) <ide> <ide> ## v0.68.2 <ide>
1
Mixed
Ruby
use official database name [ci skip]
96f0114e082b116856e945b075abd747eff0e63e
<ide><path>activerecord/CHANGELOG.md <ide> bulk deletes by `delete_all`. <ide> <ide> Supports skipping or upserting duplicates through the `ON CONFLICT` syntax <del> for Postgres (9.5+) and Sqlite (3.24+) and `ON DUPLICATE KEY UPDATE` syntax <add> for PostgreSQL (9.5+) and SQLite (3.24+) and `ON DUPLICATE KEY UPDATE` syntax <ide> for MySQL. <ide> <ide> *Bob Lail* <ide><path>activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb <ide> def foreign_keys(table_name) <ide> # [<tt>:on_update</tt>] <ide> # Action that happens <tt>ON UPDATE</tt>. Valid values are +:nullify+, +:cascade+ and +:restrict+ <ide> # [<tt>:validate</tt>] <del> # (Postgres only) Specify whether or not the constraint should be validated. Defaults to +true+. <add> # (PostgreSQL only) Specify whether or not the constraint should be validated. Defaults to +true+. <ide> def add_foreign_key(from_table, to_table, options = {}) <ide> return unless supports_foreign_keys? <ide> <ide><path>activerecord/lib/active_record/integration.rb <ide> def can_use_fast_cache_version?(timestamp) <ide> # raw_timestamp_to_cache_version(timestamp) <ide> # # => "20181015200215266505" <ide> # <del> # Postgres truncates trailing zeros, <add> # PostgreSQL truncates trailing zeros, <ide> # https://github.com/postgres/postgres/commit/3e1beda2cde3495f41290e1ece5d544525810214 <ide> # to account for this we pad the output with zeros <ide> def raw_timestamp_to_cache_version(timestamp) <ide><path>activerecord/lib/active_record/persistence.rb <ide> def insert(attributes, returning: nil, unique_by: nil) <ide> # ==== Options <ide> # <ide> # [:returning] <del> # (Postgres-only) An array of attributes to return for all successfully <add> # (PostgreSQL only) An array of attributes to return for all successfully <ide> # inserted records, which by default is the primary key. <ide> # Pass <tt>returning: %w[ id name ]</tt> for both id and name <ide> # or <tt>returning: false</tt> to omit the underlying <tt>RETURNING</tt> SQL <ide> # clause entirely. <ide> # <ide> # [:unique_by] <del> # (Postgres and SQLite only) By default rows are considered to be unique <add> # (PostgreSQL and SQLite only) By default rows are considered to be unique <ide> # by every unique index on the table. Any duplicate rows are skipped. <ide> # <ide> # To skip rows according to just one unique index pass <tt>:unique_by</tt>. <ide> def insert!(attributes, returning: nil) <ide> # ==== Options <ide> # <ide> # [:returning] <del> # (Postgres-only) An array of attributes to return for all successfully <add> # (PostgreSQL only) An array of attributes to return for all successfully <ide> # inserted records, which by default is the primary key. <ide> # Pass <tt>returning: %w[ id name ]</tt> for both id and name <ide> # or <tt>returning: false</tt> to omit the underlying <tt>RETURNING</tt> SQL <ide> def upsert(attributes, returning: nil, unique_by: nil) <ide> # ==== Options <ide> # <ide> # [:returning] <del> # (Postgres-only) An array of attributes to return for all successfully <add> # (PostgreSQL only) An array of attributes to return for all successfully <ide> # inserted records, which by default is the primary key. <ide> # Pass <tt>returning: %w[ id name ]</tt> for both id and name <ide> # or <tt>returning: false</tt> to omit the underlying <tt>RETURNING</tt> SQL <ide> # clause entirely. <ide> # <ide> # [:unique_by] <del> # (Postgres and SQLite only) By default rows are considered to be unique <add> # (PostgreSQL and SQLite only) By default rows are considered to be unique <ide> # by every unique index on the table. Any duplicate rows are skipped. <ide> # <ide> # To skip rows according to just one unique index pass <tt>:unique_by</tt>. <ide><path>activerecord/test/cases/adapters/mysql2/schema_test.rb <ide> def test_float_limits <ide> column_24 = @connection.columns(:mysql_doubles).find { |c| c.name == "float_24" } <ide> column_25 = @connection.columns(:mysql_doubles).find { |c| c.name == "float_25" } <ide> <del> # Mysql floats are precision 0..24, Mysql doubles are precision 25..53 <add> # MySQL floats are precision 0..24, MySQL doubles are precision 25..53 <ide> assert_equal 24, column_no_limit.limit <ide> assert_equal 24, column_short.limit <ide> assert_equal 53, column_long.limit <ide><path>guides/source/active_record_basics.md <ide> depending on the purpose of these columns. <ide> fields that Active Record will look for when you create associations between <ide> your models. <ide> * **Primary keys** - By default, Active Record will use an integer column named <del> `id` as the table's primary key (`bigint` for Postgres and MYSQL, `integer` <add> `id` as the table's primary key (`bigint` for PostgreSQL and MySQL, `integer` <ide> for SQLite). When using [Active Record Migrations](active_record_migrations.html) <ide> to create your tables, this column will be automatically created. <ide> <ide><path>guides/source/i18n.md <ide> The I18n API described in this guide is primarily intended for translating inter <ide> Several gems can help with this: <ide> <ide> * [Globalize](https://github.com/globalize/globalize): Store translations on separate translation tables, one for each translated model <del>* [Mobility](https://github.com/shioyama/mobility): Provides support for storing translations in many formats, including translation tables, json columns (Postgres), etc. <add>* [Mobility](https://github.com/shioyama/mobility): Provides support for storing translations in many formats, including translation tables, json columns (PostgreSQL), etc. <ide> * [Traco](https://github.com/barsoom/traco): Translatable columns for Rails 3 and 4, stored in the model table itself <ide> <ide> Conclusion
7
Text
Text
update hall of fame verbiage
9e1bac4807d0268c561bb8ddad84fffac8ee07e1
<ide><path>HoF.md <ide> # Responsible Disclosure <ide> <del>freeCodeCamp appreciates any responsible disclosure of vulnerabilities which might impact the integrity of the platform or the users associated with it. Although we do not offer any bounties or swags at the moment, we'll be happy to list your name in our Hall of Fame list below: <add>We appreciate any responsible disclosure of vulnerabilities that might impact the integrity of our platforms and users. While we do not offer any bounties or swags at the moment, we are grateful to these awesome people for helping us keep the platform safe for everyone: <ide> <del>1. Mehul Mohan from [codedamn](https://codedamn.com) ([@mehulmpt](https://twitter.com/mehulmpt)) - [Vulnerability Fix](https://github.com/freeCodeCamp/freeCodeCamp/blob/bb5a9e815313f1f7c91338e171bfe5acb8f3e346/client/src/components/Flash/index.js) <add>- Mehul Mohan from [codedamn](https://codedamn.com) ([@mehulmpt](https://twitter.com/mehulmpt)) - [Vulnerability Fix](https://github.com/freeCodeCamp/freeCodeCamp/blob/bb5a9e815313f1f7c91338e171bfe5acb8f3e346/client/src/components/Flash/index.js) <add> <add>> ### Thank you for your contributions :pray:
1
Ruby
Ruby
fix documentation for connected_to
59ef3c8e70dd8562d5ced4c3a87c37da66a61a30
<ide><path>activerecord/lib/active_record/connection_handling.rb <ide> def connects_to(database: {}, shards: {}) <ide> # Dog.create! # throws exception because we're on a replica <ide> # end <ide> # <del> # If only a shard is passed, Active Record will look up the shard on the <del> # current role. If a non-existent shard is passed, an <del> # `ActiveRecord::ConnectionNotEstablished` error will be raised. <add> # When swapping to a shard, the role must be passed as well. If a non-existent <add> # shard is passed, an `ActiveRecord::ConnectionNotEstablished` error will be <add> # raised. <ide> # <del> # ActiveRecord::Base.connected_to(shard: :default) do <del> # # Dog.create! # creates dog in shard with the default key <del> # end <del> # <del> # If a shard and role is passed, Active Record will first lookup the role, <add> # When a shard and role is passed, Active Record will first lookup the role, <ide> # and then look up the connection by shard key. <ide> # <ide> # ActiveRecord::Base.connected_to(role: :reading, shard: :shard_one_replica) do <del> # # Dog.create! # would raise as we're on a readonly connection <add> # Dog.first # finds first Dog record stored on the shard one replica <ide> # end <ide> # <ide> # The database kwarg is deprecated and will be removed in 6.2.0 without replacement.
1
Python
Python
add support about region of '''cn-northwest-1'
358b9fa8ad124a088bb1f8a0a97012c78aeac3b7
<ide><path>libcloud/storage/drivers/s3.py <ide> import base64 <ide> import hmac <ide> import time <del> <ide> from hashlib import sha1 <ide> <ide> import libcloud.utils.py3 <add> <ide> try: <ide> if libcloud.utils.py3.DEFAULT_LXML: <ide> from lxml.etree import Element, SubElement <ide> from libcloud.storage.types import ObjectDoesNotExistError <ide> from libcloud.storage.types import ObjectHashMismatchError <ide> <del> <ide> # How long before the token expires <ide> EXPIRATION_SECONDS = 15 * 60 <ide> <ide> S3_US_WEST_OREGON_HOST = 's3-us-west-2.amazonaws.com' <ide> S3_US_GOV_WEST_HOST = 's3-us-gov-west-1.amazonaws.com' <ide> S3_CN_NORTH_HOST = 's3.cn-north-1.amazonaws.com.cn' <add>S3_CN_NORTHWEST_HOST = 's3.cn-northwest-1.amazonaws.com.cn' <ide> S3_EU_WEST_HOST = 's3-eu-west-1.amazonaws.com' <ide> S3_EU_WEST2_HOST = 's3-eu-west-2.amazonaws.com' <ide> S3_EU_CENTRAL_HOST = 's3-eu-central-1.amazonaws.com' <ide> def finder(node, text): <ide> # pylint: disable=maybe-no-member <ide> for node in body.findall(fixxpath(xpath='Upload', <ide> namespace=self.namespace)): <del> <ide> initiator = node.find(fixxpath(xpath='Initiator', <ide> namespace=self.namespace)) <ide> owner = node.find(fixxpath(xpath='Owner', <ide> class S3USGovWestStorageDriver(S3StorageDriver): <ide> region_name = 'us-gov-west-1' <ide> <ide> <add>class S3CNNorthWestConnection(S3SignatureV4Connection): <add> host = S3_CN_NORTHWEST_HOST <add> <add> <add>class S3CNNorthWestStorageDriver(S3StorageDriver): <add> name = 'Amazon S3 (cn-northwest-1)' <add> connectionCls = S3CNNorthWestConnection <add> ex_location_name = 'cn-northwest-1' <add> region_name = 'cn-northwest-1' <add> <add> <ide> class S3CNNorthConnection(S3SignatureV4Connection): <ide> host = S3_CN_NORTH_HOST <ide> <ide> class S3APSE2StorageDriver(S3StorageDriver): <ide> class S3APNE1Connection(S3SignatureV4Connection): <ide> host = S3_AP_NORTHEAST1_HOST <ide> <add> <ide> S3APNEConnection = S3APNE1Connection <ide> <ide> <ide> class S3APNE1StorageDriver(S3StorageDriver): <ide> ex_location_name = 'ap-northeast-1' <ide> region_name = 'ap-northeast-1' <ide> <add> <ide> S3APNEStorageDriver = S3APNE1StorageDriver <ide> <ide> <ide><path>libcloud/storage/providers.py <ide> # See the License for the specific language governing permissions and <ide> # limitations under the License. <ide> <del>from libcloud.storage.types import Provider <del>from libcloud.storage.types import OLD_CONSTANT_TO_NEW_MAPPING <ide> from libcloud.common.providers import get_driver as _get_provider_driver <ide> from libcloud.common.providers import set_driver as _set_provider_driver <add>from libcloud.storage.types import OLD_CONSTANT_TO_NEW_MAPPING <add>from libcloud.storage.types import Provider <ide> <ide> DRIVERS = { <ide> Provider.DUMMY: <del> ('libcloud.storage.drivers.dummy', 'DummyStorageDriver'), <add> ('libcloud.storage.drivers.dummy', 'DummyStorageDriver'), <ide> Provider.CLOUDFILES: <del> ('libcloud.storage.drivers.cloudfiles', 'CloudFilesStorageDriver'), <add> ('libcloud.storage.drivers.cloudfiles', 'CloudFilesStorageDriver'), <ide> Provider.OPENSTACK_SWIFT: <del> ('libcloud.storage.drivers.cloudfiles', 'OpenStackSwiftStorageDriver'), <add> ('libcloud.storage.drivers.cloudfiles', 'OpenStackSwiftStorageDriver'), <ide> Provider.S3: <del> ('libcloud.storage.drivers.s3', 'S3StorageDriver'), <add> ('libcloud.storage.drivers.s3', 'S3StorageDriver'), <ide> Provider.S3_US_EAST2: <del> ('libcloud.storage.drivers.s3', 'S3USEast2StorageDriver'), <add> ('libcloud.storage.drivers.s3', 'S3USEast2StorageDriver'), <ide> Provider.S3_US_WEST: <del> ('libcloud.storage.drivers.s3', 'S3USWestStorageDriver'), <add> ('libcloud.storage.drivers.s3', 'S3USWestStorageDriver'), <ide> Provider.S3_US_WEST_OREGON: <del> ('libcloud.storage.drivers.s3', 'S3USWestOregonStorageDriver'), <add> ('libcloud.storage.drivers.s3', 'S3USWestOregonStorageDriver'), <ide> Provider.S3_US_GOV_WEST: <del> ('libcloud.storage.drivers.s3', 'S3USGovWestStorageDriver'), <add> ('libcloud.storage.drivers.s3', 'S3USGovWestStorageDriver'), <ide> Provider.S3_CN_NORTH: <del> ('libcloud.storage.drivers.s3', 'S3CNNorthStorageDriver'), <add> ('libcloud.storage.drivers.s3', 'S3CNNorthStorageDriver'), <add> Provider.S3_CN_NORTHQWEST: <add> ('libcloud.storage.drivers.s3', 'S3CNNorthWestStorageDriver'), <ide> Provider.S3_EU_WEST: <del> ('libcloud.storage.drivers.s3', 'S3EUWestStorageDriver'), <add> ('libcloud.storage.drivers.s3', 'S3EUWestStorageDriver'), <ide> Provider.S3_EU_WEST2: <del> ('libcloud.storage.drivers.s3', 'S3EUWest2StorageDriver'), <add> ('libcloud.storage.drivers.s3', 'S3EUWest2StorageDriver'), <ide> Provider.S3_EU_CENTRAL: <del> ('libcloud.storage.drivers.s3', 'S3EUCentralStorageDriver'), <add> ('libcloud.storage.drivers.s3', 'S3EUCentralStorageDriver'), <ide> Provider.S3_AP_SOUTH: <del> ('libcloud.storage.drivers.s3', 'S3APSouthStorageDriver'), <add> ('libcloud.storage.drivers.s3', 'S3APSouthStorageDriver'), <ide> Provider.S3_AP_SOUTHEAST: <del> ('libcloud.storage.drivers.s3', 'S3APSEStorageDriver'), <add> ('libcloud.storage.drivers.s3', 'S3APSEStorageDriver'), <ide> Provider.S3_AP_SOUTHEAST2: <del> ('libcloud.storage.drivers.s3', 'S3APSE2StorageDriver'), <add> ('libcloud.storage.drivers.s3', 'S3APSE2StorageDriver'), <ide> Provider.S3_AP_NORTHEAST: <del> ('libcloud.storage.drivers.s3', 'S3APNE1StorageDriver'), <add> ('libcloud.storage.drivers.s3', 'S3APNE1StorageDriver'), <ide> Provider.S3_AP_NORTHEAST1: <del> ('libcloud.storage.drivers.s3', 'S3APNE1StorageDriver'), <add> ('libcloud.storage.drivers.s3', 'S3APNE1StorageDriver'), <ide> Provider.S3_AP_NORTHEAST2: <del> ('libcloud.storage.drivers.s3', 'S3APNE2StorageDriver'), <add> ('libcloud.storage.drivers.s3', 'S3APNE2StorageDriver'), <ide> Provider.S3_SA_EAST: <del> ('libcloud.storage.drivers.s3', 'S3SAEastStorageDriver'), <add> ('libcloud.storage.drivers.s3', 'S3SAEastStorageDriver'), <ide> Provider.S3_CA_CENTRAL: <del> ('libcloud.storage.drivers.s3', 'S3CACentralStorageDriver'), <add> ('libcloud.storage.drivers.s3', 'S3CACentralStorageDriver'), <ide> Provider.S3_RGW: <del> ('libcloud.storage.drivers.rgw', 'S3RGWStorageDriver'), <add> ('libcloud.storage.drivers.rgw', 'S3RGWStorageDriver'), <ide> Provider.S3_RGW_OUTSCALE: <del> ('libcloud.storage.drivers.rgw', 'S3RGWOutscaleStorageDriver'), <add> ('libcloud.storage.drivers.rgw', 'S3RGWOutscaleStorageDriver'), <ide> Provider.NINEFOLD: <del> ('libcloud.storage.drivers.ninefold', 'NinefoldStorageDriver'), <add> ('libcloud.storage.drivers.ninefold', 'NinefoldStorageDriver'), <ide> Provider.GOOGLE_STORAGE: <del> ('libcloud.storage.drivers.google_storage', 'GoogleStorageDriver'), <add> ('libcloud.storage.drivers.google_storage', 'GoogleStorageDriver'), <ide> Provider.NIMBUS: <del> ('libcloud.storage.drivers.nimbus', 'NimbusStorageDriver'), <add> ('libcloud.storage.drivers.nimbus', 'NimbusStorageDriver'), <ide> Provider.LOCAL: <del> ('libcloud.storage.drivers.local', 'LocalStorageDriver'), <add> ('libcloud.storage.drivers.local', 'LocalStorageDriver'), <ide> Provider.AZURE_BLOBS: <del> ('libcloud.storage.drivers.azure_blobs', 'AzureBlobsStorageDriver'), <add> ('libcloud.storage.drivers.azure_blobs', 'AzureBlobsStorageDriver'), <ide> Provider.KTUCLOUD: <del> ('libcloud.storage.drivers.ktucloud', 'KTUCloudStorageDriver'), <add> ('libcloud.storage.drivers.ktucloud', 'KTUCloudStorageDriver'), <ide> Provider.AURORAOBJECTS: <del> ('libcloud.storage.drivers.auroraobjects', 'AuroraObjectsStorageDriver'), <add> ('libcloud.storage.drivers.auroraobjects', 'AuroraObjectsStorageDriver'), <ide> Provider.BACKBLAZE_B2: <del> ('libcloud.storage.drivers.backblaze_b2', 'BackblazeB2StorageDriver'), <add> ('libcloud.storage.drivers.backblaze_b2', 'BackblazeB2StorageDriver'), <ide> Provider.ALIYUN_OSS: <del> ('libcloud.storage.drivers.oss', 'OSSStorageDriver'), <add> ('libcloud.storage.drivers.oss', 'OSSStorageDriver'), <ide> Provider.DIGITALOCEAN_SPACES: <del> ('libcloud.storage.drivers.digitalocean_spaces', <del> 'DigitalOceanSpacesStorageDriver'), <add> ('libcloud.storage.drivers.digitalocean_spaces', <add> 'DigitalOceanSpacesStorageDriver'), <ide> } <ide> <ide> <ide><path>libcloud/storage/types.py <ide> class Provider(object): <ide> S3_AP_SOUTHEAST2 = 's3_ap_southeast2' <ide> S3_CA_CENTRAL = 's3_ca_central' <ide> S3_CN_NORTH = 's3_cn_north' <add> S3_CN_NORTHQWEST='s3_cn_northwest' <ide> S3_EU_WEST = 's3_eu_west' <ide> S3_EU_WEST2 = 's3_eu_west_2' <ide> S3_EU_CENTRAL = 's3_eu_central'
3
Python
Python
fix bart slow test
f5516805c2d0ea39797d46d9433dab43f769bea1
<ide><path>tests/test_modeling_bart.py <ide> def test_inference_no_head(self): <ide> output = model.forward(**inputs_dict)[0] <ide> expected_shape = torch.Size((1, 11, 1024)) <ide> self.assertEqual(output.shape, expected_shape) <del> expected_slice = torch.Tensor( <add> expected_slice = torch.tensor( <ide> [[0.7144, 0.8143, -1.2813], [0.7144, 0.8143, -1.2813], [-0.0467, 2.5911, -2.1845]], device=torch_device <ide> ) <ide> self.assertTrue(torch.allclose(output[:, :3, :3], expected_slice, atol=TOLERANCE))
1
Go
Go
add katie bouman to names generator
191c0fec8c827ca4822baee72446ac155e63425e
<ide><path>pkg/namesgenerator/names-generator.go <ide> var ( <ide> // Satyendra Nath Bose - He provided the foundation for Bose–Einstein statistics and the theory of the Bose–Einstein condensate. - https://en.wikipedia.org/wiki/Satyendra_Nath_Bose <ide> "bose", <ide> <add> // Katherine Louise Bouman is an imaging scientist and Assistant Professor of Computer Science at the California Institute of Technology. She researches computational methods for imaging, and developed an algorithm that made possible the picture first visualization of a black hole using the Event Horizon Telescope. - https://en.wikipedia.org/wiki/Katie_Bouman <add> "bouman", <add> <ide> // Evelyn Boyd Granville - She was one of the first African-American woman to receive a Ph.D. in mathematics; she earned it in 1949 from Yale University. https://en.wikipedia.org/wiki/Evelyn_Boyd_Granville <ide> "boyd", <ide>
1
Python
Python
fix document about response_check in httpsensor
ccd28cbf443b411731efce22e7a5e275f172691f
<ide><path>airflow/providers/http/sensors/http.py <ide> class HttpSensor(BaseSensorOperator): <ide> <ide> The response check can access the template context to the operator: <ide> <add> .. code-block:: python <add> <ide> def response_check(response, task_instance): <ide> # The task_instance is injected, so you can pull data form xcom <ide> # Other context variables such as dag, ds, execution_date are also available. <del> xcom_data = task_instance.xcom_pull(task_ids='pushing_task') <add> xcom_data = task_instance.xcom_pull(task_ids="pushing_task") <ide> # In practice you would do something more sensible with this data.. <ide> print(xcom_data) <ide> return True <ide> <del> HttpSensor(task_id='my_http_sensor', ..., response_check=response_check) <add> <add> HttpSensor(task_id="my_http_sensor", ..., response_check=response_check) <ide> <ide> .. seealso:: <ide> For more information on how to use this operator, take a look at the guide:
1
Text
Text
add brief description of "user stories"
846a221493cc893d7ed2b1d85b431924371a9d9b
<ide><path>guide/english/agile/sprints/index.md <ide> title: Sprints <ide> In Scrum, the **Sprint** is a period of working time usually between one and four weeks in which the delivery team works on your project. Sprints are iterative, and continue until the project is completed. Each sprint begins with a Sprint Planning session, and ends with Sprint Review and Retrospective meetings. Using sprints, as opposed to months-long waterfall or linear sequential development methodologies, allows regular feedback loops between project owners and stakeholders on the output from the delivery team. <ide> <ide> ## Properties of a Sprint <del> <ide> - A sprint should not be terminated prematurely if at all possible. If the stories within the sprint become obsolete, the team may decide to close them and pull new stories off of the product backlog. <del>- The team works to break up the User Stories to a size that can be completed within the duration of the Sprint without carrying over to the next. <add>- The team works to break up the User Stories, a non-technical description of what the user expects to see and/or do, to a size that can be completed within the duration of the Sprint without carrying over to the next. <ide> - "Sprint" and "Iteration" are often used interchangeably. <ide> <ide> #### More Information:
1
Go
Go
modify id to chainid to avoid confusing
1b0f2d71a1aa9e529357e2ffe342af2a12d7c145
<ide><path>layer/empty_test.go <ide> import ( <ide> <ide> func TestEmptyLayer(t *testing.T) { <ide> if EmptyLayer.ChainID() != ChainID(DigestSHA256EmptyTar) { <del> t.Fatal("wrong ID for empty layer") <add> t.Fatal("wrong ChainID for empty layer") <ide> } <ide> <ide> if EmptyLayer.DiffID() != DigestSHA256EmptyTar { <ide><path>layer/layer_test.go <ide> func cacheID(l Layer) string { <ide> <ide> func assertLayerEqual(t *testing.T, l1, l2 Layer) { <ide> if l1.ChainID() != l2.ChainID() { <del> t.Fatalf("Mismatched ID: %s vs %s", l1.ChainID(), l2.ChainID()) <add> t.Fatalf("Mismatched ChainID: %s vs %s", l1.ChainID(), l2.ChainID()) <ide> } <ide> if l1.DiffID() != l2.DiffID() { <ide> t.Fatalf("Mismatched DiffID: %s vs %s", l1.DiffID(), l2.DiffID())
2
Javascript
Javascript
support filespec dictionary in annotations
4efab13c589516900a6436e4c8d9a351b14596a9
<ide><path>src/core.js <ide> var Page = (function PageClosure() { <ide> break; <ide> case 'GoToR': <ide> var url = a.get('F'); <add> if (isDict(url)) { <add> // We assume that the 'url' is a Filspec dictionary <add> // and fetch the url without checking any further <add> url = url.get('F') || ''; <add> } <add> <ide> // TODO: pdf reference says that GoToR <ide> // can also have 'NewWindow' attribute <ide> if (!isValidUrl(url))
1
Python
Python
add stdev to the dense layer.
fa28535d2940adf24c5e668c4bdba46379286aec
<ide><path>official/resnet/keras/resnet_cifar_model.py <ide> import functools <ide> import tensorflow as tf <ide> from tensorflow.python.keras import backend <add>from tensorflow.python.keras import initializers <ide> from tensorflow.python.keras import layers <ide> from tensorflow.python.keras import regularizers <ide> <ide> def resnet(num_blocks, classes=10, training=None): <ide> <ide> rm_axes = [1, 2] if backend.image_data_format() == 'channels_last' else [2, 3] <ide> x = layers.Lambda(lambda x: backend.mean(x, rm_axes), name='reduce_mean')(x) <del> x = layers.Dense(classes, activation='softmax', <del> # kernel_initializer='he_normal', <add> x = layers.Dense(classes, <add> activation='softmax', <add> kernel_initializer=initializers.RandomNormal(stddev=0.01), <ide> kernel_regularizer=regularizers.l2(L2_WEIGHT_DECAY), <add> bias_regularizer=regularizers.l2(L2_WEIGHT_DECAY), <ide> name='fc10')(x) <ide> <ide> inputs = img_input <ide><path>official/resnet/keras/resnet_model.py <ide> from __future__ import division <ide> from __future__ import print_function <ide> <del>import os <del>import warnings <del> <ide> from tensorflow.python.keras import backend <add>from tensorflow.python.keras import initializers <ide> from tensorflow.python.keras import layers <ide> from tensorflow.python.keras import models <ide> from tensorflow.python.keras import regularizers <del>from tensorflow.python.keras import utils <ide> <ide> <ide> L2_WEIGHT_DECAY = 1e-4 <ide> def identity_block(input_tensor, kernel_size, filters, stage, block): <ide> """The identity block is the block that has no conv layer at shortcut. <ide> <del> # Arguments <del> input_tensor: input tensor <del> kernel_size: default 3, the kernel size of <del> middle conv layer at main path <del> filters: list of integers, the filters of 3 conv layer at main path <del> stage: integer, current stage label, used for generating layer names <del> block: 'a','b'..., current block label, used for generating layer names <add> Args: <add> input_tensor: input tensor <add> kernel_size: default 3, the kernel size of middle conv layer at main path <add> filters: list of integers, the filters of 3 conv layer at main path <add> stage: integer, current stage label, used for generating layer names <add> block: 'a','b'..., current block label, used for generating layer names <ide> <del> # Returns <del> Output tensor for the block. <add> Returns: <add> Output tensor for the block. <ide> """ <ide> filters1, filters2, filters3 = filters <ide> if backend.image_data_format() == 'channels_last': <ide> def conv_block(input_tensor, <ide> strides=(2, 2)): <ide> """A block that has a conv layer at shortcut. <ide> <del> # Arguments <del> input_tensor: input tensor <del> kernel_size: default 3, the kernel size of <del> middle conv layer at main path <del> filters: list of integers, the filters of 3 conv layer at main path <del> stage: integer, current stage label, used for generating layer names <del> block: 'a','b'..., current block label, used for generating layer names <del> strides: Strides for the second conv layer in the block. <del> <del> # Returns <del> Output tensor for the block. <del> <ide> Note that from stage 3, <ide> the second conv layer at main path is with strides=(2, 2) <ide> And the shortcut should have strides=(2, 2) as well <add> <add> Args: <add> input_tensor: input tensor <add> kernel_size: default 3, the kernel size of middle conv layer at main path <add> filters: list of integers, the filters of 3 conv layer at main path <add> stage: integer, current stage label, used for generating layer names <add> block: 'a','b'..., current block label, used for generating layer names <add> strides: Strides for the second conv layer in the block. <add> <add> Returns: <add> Output tensor for the block. <ide> """ <ide> filters1, filters2, filters3 = filters <ide> if backend.image_data_format() == 'channels_last': <ide> def conv_block(input_tensor, <ide> <ide> <ide> def resnet50(num_classes, dtype='float32', batch_size=None): <del> # TODO(tfboyd): add training argument, just lik resnet56. <ide> """Instantiates the ResNet50 architecture. <ide> <ide> Args: <ide> num_classes: `int` number of classes for image classification. <add> dtype: dtype to use float32 or float16 are most common. <add> batch_size: Size of the batches for each step. <ide> <ide> Returns: <ide> A Keras model instance. <ide> def resnet50(num_classes, dtype='float32', batch_size=None): <ide> x = layers.Lambda(lambda x: backend.mean(x, rm_axes), name='reduce_mean')(x) <ide> x = layers.Dense( <ide> num_classes, <add> kernel_initializer=initializers.RandomNormal(stddev=0.01), <ide> kernel_regularizer=regularizers.l2(L2_WEIGHT_DECAY), <ide> bias_regularizer=regularizers.l2(L2_WEIGHT_DECAY), <ide> name='fc1000')(x) <add> <ide> # TODO(reedwm): Remove manual casts once mixed precision can be enabled with a <ide> # single line of code. <ide> x = backend.cast(x, 'float32')
2
Javascript
Javascript
minimize memory usage of font-related arrays
c7f02d2c8ee1d1c7cbb26c9600c910ab3b33603f
<ide><path>src/core/fonts.js <ide> var Font = (function FontClosure() { <ide> // length <ide> var length = data.length; <ide> <del> // Per spec tables must be 4-bytes align so add padding as needed <del> while (data.length & 3) { <del> data.push(0x00); <add> // Per spec tables must be 4-bytes align so add padding as needed. <add> var paddedLength = length; <add> while (paddedLength & 3) { <add> paddedLength++; <ide> } <add> var i; <add> var padding = paddedLength - length; <add> if (padding !== 0) { <add> // Padding is required. |data| can be an Array, Uint8Array, or <add> // Uint16Array. In the latter two cases we need to create slightly larger <add> // typed arrays and copy the old contents in. Fortunately that's not a <add> // common case. <add> var data2; <add> if (data instanceof Array) { <add> for (i = 0; i < padding; i++) { <add> data.push(0); <add> } <add> } else if (data instanceof Uint8Array) { <add> data2 = new Uint8Array(paddedLength); <add> data2.set(data); <add> data = data2; <add> } else if (data instanceof Uint16Array) { <add> data2 = new Uint16Array(paddedLength); <add> data2.set(data); <add> data = data2; <add> } else { <add> error('bad array kind in createTableEntry'); <add> } <add> } <add> <ide> while (file.virtualOffset & 3) { <ide> file.virtualOffset++; <ide> } <ide> <ide> // checksum <ide> var checksum = 0, n = data.length; <del> for (var i = 0; i < n; i += 4) { <add> for (i = 0; i < n; i += 4) { <ide> checksum = (checksum + int32(data[i], data[i + 1], data[i + 2], <ide> data[i + 3])) | 0; <ide> } <ide> var Font = (function FontClosure() { <ide> string32(offset) + string32(length)); <ide> file.file += tableEntry; <ide> file.virtualOffset += data.length; <add> <add> return data; <ide> } <ide> <ide> function isTrueTypeFile(file) { <ide> var Font = (function FontClosure() { <ide> // rewrite the tables but tweak offsets <ide> for (i = 0; i < numTables; i++) { <ide> table = tables[tablesNames[i]]; <del> var data = []; <del> <del> tableData = table.data; <del> for (var j = 0, jj = tableData.length; j < jj; j++) { <del> data.push(tableData[j]); <del> } <del> createTableEntry(ttf, table.tag, data); <add> table.data = createTableEntry(ttf, table.tag, table.data); <ide> } <ide> <ide> // Add the table datas <ide> var Font = (function FontClosure() { <ide> <ide> var field; <ide> for (field in fields) { <del> createTableEntry(otf, field, fields[field]); <add> fields[field] = createTableEntry(otf, field, fields[field]); <ide> } <ide> for (field in fields) { <ide> var table = fields[field]; <ide><path>src/shared/util.js <ide> function bytesToString(bytes) { <ide> <ide> function stringToArray(str) { <ide> var length = str.length; <del> var array = []; <add> var array = new Uint16Array(length); <ide> for (var i = 0; i < length; ++i) { <ide> array[i] = str.charCodeAt(i); <ide> }
2
Text
Text
create model card for asafaya/bert-mini-arabic
3cdf8b7ec2ac7b638bac7495870f1fd152314251
<ide><path>model_cards/asafaya/bert-mini-arabic/README.md <add>--- <add>language: arabic <add>datasets: <add>- oscar <add>- wikipedia <add>--- <add> <add># Arabic BERT Mini Model <add> <add>Pretrained BERT Mini language model for Arabic <add> <add>_If you use this model in your work, please cite this paper (to appear in 2020):_ <add> <add>``` <add>@inproceedings{ <add> title={KUISAIL at SemEval-2020 Task 12: BERT-CNN for Offensive Speech Identification in Social Media}, <add> author={Safaya, Ali and Abdullatif, Moutasem and Yuret, Deniz}, <add> booktitle={Proceedings of the International Workshop on Semantic Evaluation (SemEval)}, <add> year={2020} <add>} <add>``` <add> <add>## Pretraining Corpus <add> <add>`arabic-bert-mini` model was pretrained on ~8.2 Billion words: <add> <add>- Arabic version of [OSCAR](https://traces1.inria.fr/oscar/) - filtered from [Common Crawl](http://commoncrawl.org/) <add>- Recent dump of Arabic [Wikipedia](https://dumps.wikimedia.org/backup-index.html) <add> <add>and other Arabic resources which sum up to ~95GB of text. <add> <add>__Notes on training data:__ <add> <add>- Our final version of corpus contains some non-Arabic words inlines, which we did not remove from sentences since that would affect some tasks like NER. <add>- Although non-Arabic characters were lowered as a preprocessing step, since Arabic characters does not have upper or lower case, there is no cased and uncased version of the model. <add>- The corpus and vocabulary set are not restricted to Modern Standard Arabic, they contain some dialectical Arabic too. <add> <add>## Pretraining details <add> <add>- This model was trained using Google BERT's github [repository](https://github.com/google-research/bert) on a single TPU v3-8 provided for free from [TFRC](https://www.tensorflow.org/tfrc). <add>- Our pretraining procedure follows training settings of bert with some changes: trained for 3M training steps with batchsize of 128, instead of 1M with batchsize of 256. <add> <add>## Load Pretrained Model <add> <add>You can use this model by installing `torch` or `tensorflow` and Huggingface library `transformers`. And you can use it directly by initializing it like this: <add> <add>```python <add>from transformers import AutoTokenizer, AutoModel <add> <add>tokenizer = AutoTokenizer.from_pretrained("asafaya/bert-mini-arabic") <add>model = AutoModel.from_pretrained("asafaya/bert-mini-arabic") <add>``` <add> <add>## Results <add> <add>For further details on the models performance or any other queries, please refer to [Arabic-BERT](https://github.com/alisafaya/Arabic-BERT) <add> <add>## Acknowledgement <add> <add>Thanks to Google for providing free TPU for the training process and for Huggingface for hosting this model on their servers 😊 <add>
1
Javascript
Javascript
add auth option case for url.format
9e0fb1acefe938843aee37c0c8bfa682f948f447
<ide><path>test/parallel/test-url-format-whatwg.js <ide> if (!common.hasIntl) <ide> const assert = require('assert'); <ide> const url = require('url'); <ide> <del>const myURL = new URL('http://xn--lck1c3crb1723bpq4a.com/a?a=b#c'); <add>const myURL = new URL('http://user:pass@xn--lck1c3crb1723bpq4a.com/a?a=b#c'); <ide> <ide> assert.strictEqual( <ide> url.format(myURL), <del> 'http://xn--lck1c3crb1723bpq4a.com/a?a=b#c' <add> 'http://user:pass@xn--lck1c3crb1723bpq4a.com/a?a=b#c' <ide> ); <ide> <ide> assert.strictEqual( <ide> url.format(myURL, {}), <del> 'http://xn--lck1c3crb1723bpq4a.com/a?a=b#c' <add> 'http://user:pass@xn--lck1c3crb1723bpq4a.com/a?a=b#c' <ide> ); <ide> <ide> { <ide> assert.strictEqual( <ide> // Any falsy value other than undefined will be treated as false. <ide> // Any truthy value will be treated as true. <ide> <add>assert.strictEqual( <add> url.format(myURL, { auth: false }), <add> 'http://xn--lck1c3crb1723bpq4a.com/a?a=b#c' <add>); <add> <add>assert.strictEqual( <add> url.format(myURL, { auth: '' }), <add> 'http://xn--lck1c3crb1723bpq4a.com/a?a=b#c' <add>); <add> <add>assert.strictEqual( <add> url.format(myURL, { auth: 0 }), <add> 'http://xn--lck1c3crb1723bpq4a.com/a?a=b#c' <add>); <add> <add>assert.strictEqual( <add> url.format(myURL, { auth: 1 }), <add> 'http://user:pass@xn--lck1c3crb1723bpq4a.com/a?a=b#c' <add>); <add> <add>assert.strictEqual( <add> url.format(myURL, { auth: {} }), <add> 'http://user:pass@xn--lck1c3crb1723bpq4a.com/a?a=b#c' <add>); <add> <ide> assert.strictEqual( <ide> url.format(myURL, { fragment: false }), <del> 'http://xn--lck1c3crb1723bpq4a.com/a?a=b' <add> 'http://user:pass@xn--lck1c3crb1723bpq4a.com/a?a=b' <ide> ); <ide> <ide> assert.strictEqual( <ide> url.format(myURL, { fragment: '' }), <del> 'http://xn--lck1c3crb1723bpq4a.com/a?a=b' <add> 'http://user:pass@xn--lck1c3crb1723bpq4a.com/a?a=b' <ide> ); <ide> <ide> assert.strictEqual( <ide> url.format(myURL, { fragment: 0 }), <del> 'http://xn--lck1c3crb1723bpq4a.com/a?a=b' <add> 'http://user:pass@xn--lck1c3crb1723bpq4a.com/a?a=b' <ide> ); <ide> <ide> assert.strictEqual( <ide> url.format(myURL, { fragment: 1 }), <del> 'http://xn--lck1c3crb1723bpq4a.com/a?a=b#c' <add> 'http://user:pass@xn--lck1c3crb1723bpq4a.com/a?a=b#c' <ide> ); <ide> <ide> assert.strictEqual( <ide> url.format(myURL, { fragment: {} }), <del> 'http://xn--lck1c3crb1723bpq4a.com/a?a=b#c' <add> 'http://user:pass@xn--lck1c3crb1723bpq4a.com/a?a=b#c' <ide> ); <ide> <ide> assert.strictEqual( <ide> url.format(myURL, { search: false }), <del> 'http://xn--lck1c3crb1723bpq4a.com/a#c' <add> 'http://user:pass@xn--lck1c3crb1723bpq4a.com/a#c' <ide> ); <ide> <ide> assert.strictEqual( <ide> url.format(myURL, { search: '' }), <del> 'http://xn--lck1c3crb1723bpq4a.com/a#c' <add> 'http://user:pass@xn--lck1c3crb1723bpq4a.com/a#c' <ide> ); <ide> <ide> assert.strictEqual( <ide> url.format(myURL, { search: 0 }), <del> 'http://xn--lck1c3crb1723bpq4a.com/a#c' <add> 'http://user:pass@xn--lck1c3crb1723bpq4a.com/a#c' <ide> ); <ide> <ide> assert.strictEqual( <ide> url.format(myURL, { search: 1 }), <del> 'http://xn--lck1c3crb1723bpq4a.com/a?a=b#c' <add> 'http://user:pass@xn--lck1c3crb1723bpq4a.com/a?a=b#c' <ide> ); <ide> <ide> assert.strictEqual( <ide> url.format(myURL, { search: {} }), <del> 'http://xn--lck1c3crb1723bpq4a.com/a?a=b#c' <add> 'http://user:pass@xn--lck1c3crb1723bpq4a.com/a?a=b#c' <ide> ); <ide> <ide> assert.strictEqual( <ide> url.format(myURL, { unicode: true }), <del> 'http://理容ナカムラ.com/a?a=b#c' <add> 'http://user:pass@理容ナカムラ.com/a?a=b#c' <ide> ); <ide> <ide> assert.strictEqual( <ide> url.format(myURL, { unicode: 1 }), <del> 'http://理容ナカムラ.com/a?a=b#c' <add> 'http://user:pass@理容ナカムラ.com/a?a=b#c' <ide> ); <ide> <ide> assert.strictEqual( <ide> url.format(myURL, { unicode: {} }), <del> 'http://理容ナカムラ.com/a?a=b#c' <add> 'http://user:pass@理容ナカムラ.com/a?a=b#c' <ide> ); <ide> <ide> assert.strictEqual( <ide> url.format(myURL, { unicode: false }), <del> 'http://xn--lck1c3crb1723bpq4a.com/a?a=b#c' <add> 'http://user:pass@xn--lck1c3crb1723bpq4a.com/a?a=b#c' <ide> ); <ide> <ide> assert.strictEqual( <ide> url.format(myURL, { unicode: 0 }), <del> 'http://xn--lck1c3crb1723bpq4a.com/a?a=b#c' <add> 'http://user:pass@xn--lck1c3crb1723bpq4a.com/a?a=b#c' <ide> ); <ide> <ide> assert.strictEqual( <del> url.format(new URL('http://xn--0zwm56d.com:8080/path'), { unicode: true }), <del> 'http://测试.com:8080/path' <add> url.format(new URL('http://user:pass@xn--0zwm56d.com:8080/path'), { unicode: true }), <add> 'http://user:pass@测试.com:8080/path' <ide> );
1
Ruby
Ruby
pull mock initialization code into initialize
df7756aeb9bbf13d3dc2a65fa291ff6625a48e69
<ide><path>Library/Homebrew/test/test_updater.rb <ide> <ide> class UpdaterTests < Test::Unit::TestCase <ide> class UpdaterMock < ::Updater <add> def initialize(*args) <add> super <add> @outputs = Hash.new { |h, k| h[k] = [] } <add> @expected = [] <add> @called = [] <add> end <add> <ide> def in_repo_expect(cmd, output = '') <del> @outputs ||= Hash.new { |h,k| h[k] = [] } <del> @expected ||= [] <ide> @expected << cmd <ide> @outputs[cmd] << output <ide> end <ide> <ide> def `(cmd, *args) <ide> cmd = "#{cmd} #{args*' '}".strip <ide> if @expected.include?(cmd) and !@outputs[cmd].empty? <del> @called ||= [] <ide> @called << cmd <ide> @outputs[cmd].shift <ide> else
1
Javascript
Javascript
deprecate direct use of coreview
c6747547f5c1f73c64167c443e633c31867b2172
<ide><path>packages/ember-views/lib/main.js <ide> import { <ide> states <ide> } from "ember-views/views/states"; <ide> <del>import CoreView from "ember-views/views/core_view"; <add>import { DeprecatedCoreView } from "ember-views/views/core_view"; <ide> import View from "ember-views/views/view"; <ide> import ContainerView from "ember-views/views/container_view"; <ide> import CollectionView from "ember-views/views/collection_view"; <ide> ViewUtils.isSimpleClick = isSimpleClick; <ide> ViewUtils.getViewClientRects = getViewClientRects; <ide> ViewUtils.getViewBoundingClientRect = getViewBoundingClientRect; <ide> <del>Ember.CoreView = CoreView; <add>Ember.CoreView = DeprecatedCoreView; <ide> Ember.View = View; <ide> Ember.View.states = states; <ide> Ember.View.cloneStates = cloneStates; <ide><path>packages/ember-views/lib/views/core_view.js <ide> var renderer; <ide> @class CoreView <ide> @namespace Ember <ide> @extends Ember.Object <add> @deprecated Use `Ember.View` instead. <ide> @uses Ember.Evented <ide> @uses Ember.ActionHandler <ide> */ <ide> CoreView.reopenClass({ <ide> isViewClass: true <ide> }); <ide> <add>export var DeprecatedCoreView = CoreView.extend({ <add> init: function() { <add> Ember.deprecate('Ember.CoreView is deprecated. Please use Ember.View.', false); <add> this._super.apply(this, arguments); <add> } <add>}); <add> <ide> export default CoreView; <ide><path>packages/ember-views/tests/views/exports_test.js <add>import Ember from "ember-views"; <add> <add>QUnit.module("ember-view exports"); <add> <add>QUnit.test("should export a disabled CoreView", function() { <add> expectDeprecation(function() { <add> Ember.CoreView.create(); <add> }, 'Ember.CoreView is deprecated. Please use Ember.View.'); <add>});
3
Python
Python
add default arguments for project euler problem 6
ddf83ec886373e1cb35318690b9bc2c737fc9f9b
<ide><path>project_euler/problem_06/sol1.py <ide> """ <del>Problem: <add>Problem 6: https://projecteuler.net/problem=6 <ide> <ide> The sum of the squares of the first ten natural numbers is, <ide> 1^2 + 2^2 + ... + 10^2 = 385 <ide> """ <ide> <ide> <del>def solution(n: int) -> int: <add>def solution(n: int = 100) -> int: <ide> """Returns the difference between the sum of the squares of the first n <ide> natural numbers and the square of the sum. <ide> <ide> def solution(n: int) -> int: <ide> 41230 <ide> >>> solution(50) <ide> 1582700 <add> >>> solution() <add> 25164150 <ide> """ <ide> sum_of_squares = 0 <ide> sum_of_ints = 0 <ide><path>project_euler/problem_06/sol2.py <ide> """ <del>Problem: <add>Problem 6: https://projecteuler.net/problem=6 <ide> <ide> The sum of the squares of the first ten natural numbers is, <ide> 1^2 + 2^2 + ... + 10^2 = 385 <ide> """ <ide> <ide> <del>def solution(n: int) -> int: <add>def solution(n: int = 100) -> int: <ide> """Returns the difference between the sum of the squares of the first n <ide> natural numbers and the square of the sum. <ide> <ide> def solution(n: int) -> int: <ide> 41230 <ide> >>> solution(50) <ide> 1582700 <add> >>> solution() <add> 25164150 <ide> """ <ide> sum_cubes = (n * (n + 1) // 2) ** 2 <ide> sum_squares = n * (n + 1) * (2 * n + 1) // 6 <ide><path>project_euler/problem_06/sol3.py <ide> """ <del>Problem: <add>Problem 6: https://projecteuler.net/problem=6 <ide> <ide> The sum of the squares of the first ten natural numbers is, <ide> 1^2 + 2^2 + ... + 10^2 = 385 <ide> import math <ide> <ide> <del>def solution(n: int) -> int: <add>def solution(n: int = 100) -> int: <ide> """Returns the difference between the sum of the squares of the first n <ide> natural numbers and the square of the sum. <ide> <ide> def solution(n: int) -> int: <ide> 41230 <ide> >>> solution(50) <ide> 1582700 <add> >>> solution() <add> 25164150 <ide> """ <ide> sum_of_squares = sum([i * i for i in range(1, n + 1)]) <ide> square_of_sum = int(math.pow(sum(range(1, n + 1)), 2)) <ide><path>project_euler/problem_06/sol4.py <ide> """ <del>Problem: <add>Problem 6: https://projecteuler.net/problem=6 <ide> <ide> The sum of the squares of the first ten natural numbers is, <ide> 1^2 + 2^2 + ... + 10^2 = 385 <ide> """ <ide> <ide> <del>def solution(n: int) -> int: <add>def solution(n: int = 100) -> int: <ide> """Returns the difference between the sum of the squares of the first n <ide> natural numbers and the square of the sum. <ide> <ide> def solution(n: int) -> int: <ide> 41230 <ide> >>> solution(50) <ide> 1582700 <del> >>> solution(100) <add> >>> solution() <ide> 25164150 <ide> """ <ide> sum_of_squares = n * (n + 1) * (2 * n + 1) / 6 <ide><path>project_euler/problem_06/test_solutions.py <del>from .sol1 import solution as sol1 <del>from .sol2 import solution as sol2 <del>from .sol3 import solution as sol3 <del>from .sol4 import solution as sol4 <del> <del> <del>def test_solutions() -> None: <del> """ <del> >>> test_solutions() <del> """ <del> assert sol1(10) == sol2(10) == sol3(10) == sol4(10) == 2640 <del> assert sol1(15) == sol2(15) == sol3(15) == sol4(15) == 13160 <del> assert sol1(20) == sol2(20) == sol3(20) == sol4(20) == 41230 <del> assert sol1(50) == sol2(50) == sol3(50) == sol4(50) == 1582700 <del> <del> <del>if __name__ == "__main__": <del> test_solutions()
5
Ruby
Ruby
update xcode checks and urls
6345ceef1fa13830b720dbf425c7408100ce2570
<ide><path>install_homebrew.rb <ide> def macos_version <ide> warn "/usr/local/bin is not in your PATH." unless ENV['PATH'].split(':').include? '/usr/local/bin' <ide> <ide> if macos_version < 10.7 <del> warn "Now install Xcode: http://developer.apple.com/technologies/xcode.html" unless Kernel.system "/usr/bin/which -s gcc" <add> warn "Now install Xcode: https://developer.apple.com/xcode/" unless File.exist? "/usr/bin/cc" <ide> else <del> warn "Install \"Command Line Tools for Xcode\": http://developer.apple.com/downloads" unless File.file? "/usr/bin/xcrun" <add> warn "Now install the \"Command Line Tools for Xcode\": http://connect.apple.com" unless File.file? "/usr/bin/xcrun" <ide> end <ide> <ide> ohai "Installation successful!"
1
Python
Python
fix typo in retag_images.py
0d6e29abb0f47937e7546b564b9a445322d8c9b1
<ide><path>dev/retag_docker_images.py <ide> <ide> <ide> GHCR_IO_IMAGES = [ <del> "{prefix}/{repo}/{branch}/ci/python{python_version}:latest", <del> "{prefix}/{repo}/{branch}/prod/python{python_version}:latest", <add> "{prefix}/{repo}/{branch}/ci/python{python}:latest", <add> "{prefix}/{repo}/{branch}/prod/python{python}:latest", <ide> ] <ide> <ide>
1
PHP
PHP
return responses from blackhole callbacks
4b7a8060708c886b8fae3ae77863ff452a2b141e
<ide><path>src/Controller/Component/SecurityComponent.php <ide> public function startup(Event $event) <ide> $isNotRequestAction && <ide> $this->_config['validatePost'] <ide> ) { <del> $this->_validatePost($controller); <add> $this->_validatePost($controller); <ide> } <ide> } catch (SecurityException $se) { <del> $this->blackHole($controller, $se->getType(), $se); <add> return $this->blackHole($controller, $se->getType(), $se); <ide> } <ide> <ide> $request = $this->generateToken($request); <ide><path>tests/TestCase/Controller/Component/SecurityComponentTest.php <ide> use Cake\Controller\Exception\SecurityException; <ide> use Cake\Core\Configure; <ide> use Cake\Event\Event; <add>use Cake\Http\Response; <ide> use Cake\Http\ServerRequest; <ide> use Cake\Http\Session; <ide> use Cake\Routing\Router; <ide> public function testExceptionWhenActionIsBlackholeCallback() <ide> $this->assertTrue($this->Controller->failed, 'Request was blackholed.'); <ide> } <ide> <add> /** <add> * test blackholeCallback returning a response <add> * <add> * @return void <add> */ <add> public function testBlackholeReturnResponse() <add> { <add> $request = new ServerRequest([ <add> 'url' => 'posts/index', <add> 'session' => $this->Security->session, <add> 'method' => 'POST', <add> 'params' => [ <add> 'controller' => 'posts', <add> 'action' => 'index' <add> ], <add> 'post' => [ <add> 'key' => 'value' <add> ] <add> ]); <add> $Controller = new \TestApp\Controller\SomePagesController($request); <add> $event = new Event('Controller.startup', $Controller); <add> $Security = new SecurityComponent($Controller->components()); <add> $Security->setConfig('blackHoleCallback', 'responseGenerator'); <add> <add> $result = $Security->startup($event); <add> $this->assertInstanceOf(Response::class, $result); <add> } <add> <ide> /** <ide> * testConstructorSettingProperties method <ide> * <ide><path>tests/test_app/TestApp/Controller/SomePagesController.php <ide> public function index() <ide> */ <ide> public function responseGenerator() <ide> { <del> $this->response->body('new response'); <del> <del> return $this->response; <add> return $this->response->withStringBody('new response'); <ide> } <ide> <ide> protected function _fail()
3
Python
Python
return global attentions (see )
b3544e4cc5f29c97e84992b7869edd66e52e46b6
<ide><path>src/transformers/models/longformer/modeling_longformer.py <ide> def forward( <ide> logits=prediction_scores, <ide> hidden_states=outputs.hidden_states, <ide> attentions=outputs.attentions, <add> global_attentions=outputs.global_attentions, <ide> ) <ide> <ide> <ide> def forward( <ide> logits=logits, <ide> hidden_states=outputs.hidden_states, <ide> attentions=outputs.attentions, <add> global_attentions=outputs.global_attentions, <ide> ) <ide> <ide> <ide> def forward( <ide> logits=logits, <ide> hidden_states=outputs.hidden_states, <ide> attentions=outputs.attentions, <add> global_attentions=outputs.global_attentions, <ide> ) <ide> <ide>
1
Javascript
Javascript
use has_native_symbol consistently
f2dfd1393acf7abe4d00fa82acb13c918f13598c
<ide><path>packages/@ember/-internals/glimmer/tests/integration/content-test.js <ide> import { set, computed } from '@ember/-internals/metal'; <ide> import { getDebugFunction, setDebugFunction } from '@ember/debug'; <ide> import { readOnly } from '@ember/object/computed'; <ide> import { Object as EmberObject, ObjectProxy } from '@ember/-internals/runtime'; <add>import { HAS_NATIVE_SYMBOL } from '@ember/-internals/utils'; <ide> import { constructStyleDeprecationMessage } from '@ember/-internals/views'; <ide> import { Component, SafeString, htmlSafe } from '../utils/helpers'; <ide> <ide> let GlimmerContentTestCases = new ContentTestGenerator([ <ide> [Object.create(null), EMPTY, 'an object with no toString'], <ide> ]); <ide> <del>if (typeof Symbol !== 'undefined') { <add>if (HAS_NATIVE_SYMBOL) { <ide> GlimmerContentTestCases.cases.push([Symbol('debug'), 'Symbol(debug)', 'a symbol']); <ide> } <ide> <ide><path>packages/@ember/-internals/utils/tests/guid_for_test.js <del>import { guidFor } from '..'; <add>import { guidFor, HAS_NATIVE_SYMBOL } from '..'; <ide> import { moduleFor, AbstractTestCase as TestCase } from 'internal-test-helpers'; <ide> <ide> function sameGuid(assert, a, b, message) { <ide> moduleFor( <ide> } <ide> <ide> ['@test symbols'](assert) { <del> if (typeof Symbol === 'undefined') { <add> if (HAS_NATIVE_SYMBOL) { <ide> assert.ok(true, 'symbols are not supported on this browser'); <ide> return; <ide> }
2
Text
Text
remove trailing whitespace. [ci skip]
e83a6ff5b75fa8407fa8f3733a39b365dace141a
<ide><path>guides/source/caching_with_rails.md <ide> This method generates a cache key that depends on all products and can be used i <ide> <% end %> <ide> ``` <ide> <del>If you want to cache a fragment under certain condition you can use `cache_if` or `cache_unless` <add>If you want to cache a fragment under certain condition you can use `cache_if` or `cache_unless` <ide> <ide> ```erb <ide> <% cache_if (condition, cache_key_for_products) do %> <ide><path>guides/source/upgrading_ruby_on_rails.md <ide> secrets, you need to: <ide> <ide> 2. Use your existing `secret_key_base` from the `secret_token.rb` initializer to <ide> set the SECRET_KEY_BASE environment variable for whichever users run the Rails <del> app in production mode. Alternately, you can simply copy the existing <del> `secret_key_base` from the `secret_token.rb` initializer to `secrets.yml` <add> app in production mode. Alternately, you can simply copy the existing <add> `secret_key_base` from the `secret_token.rb` initializer to `secrets.yml` <ide> under the `production` section, replacing '<%= ENV["SECRET_KEY_BASE"] %>'. <del> <add> <ide> 3. Remove the `secret_token.rb` initializer. <ide> <ide> 4. Use `rake secret` to generate new keys for the `development` and `test` sections.
2
Javascript
Javascript
remove the unnecessary 'var' in `runverbose`
f799fa13b838d84bc9fe62ba7b30b80002085552
<ide><path>react-native-cli/index.js <ide> function run(root, projectName, rnPackage) { <ide> <ide> checkNodeVersion(); <ide> <del> var cli = require(CLI_MODULE_PATH()); <add> cli = require(CLI_MODULE_PATH()); <ide> cli.init(root, projectName); <ide> }); <ide> }
1
Javascript
Javascript
fix lint errors
e777c0de8e258bea76e3e53025c6642316858ba9
<ide><path>src/history-manager.js <ide> export class HistoryManager { <ide> } <ide> <ide> addProject (paths, lastOpened) { <del> if (paths.length == 0) return <add> if (paths.length === 0) return <ide> <ide> let project = this.getProject(paths) <ide> if (!project) { <ide> export class HistoryManager { <ide> } <ide> } <ide> <del>function arrayEquivalent(a, b) { <del> if (a.length != b.length) return false <del> for (var i=0; i < a.length; i++) { <add>function arrayEquivalent (a, b) { <add> if (a.length !== b.length) return false <add> for (var i = 0; i < a.length; i++) { <ide> if (a[i] !== b[i]) return false <ide> } <ide> return true
1
Mixed
Ruby
introduce a benchmark template [ci skip]
f2f9b8868590bb4be8965583096862e29b9f83fb
<ide><path>guides/bug_report_templates/benchmark.rb <add>begin <add> require "bundler/inline" <add>rescue LoadError => e <add> $stderr.puts "Bundler version 1.10 or later is required. Please update your Bundler" <add> raise e <add>end <add> <add>gemfile(true) do <add> source "https://rubygems.org" <add> gem "rails", github: "rails/rails" <add> gem "benchmark-ips" <add>end <add> <add>require "active_support" <add>require "active_support/core_ext/object/blank" <add> <add># Your patch goes here. <add>class String <add> def fast_blank? <add> true <add> end <add>end <add> <add># Enumerate some representative scenarios here. <add># <add># It is very easy to make an optimization that improves performance for a <add># specific scenario you care about but regresses on other common cases. <add># Therefore, you should test your change against a list of representative <add># scenarios. Ideally, they should be based on real-world scenarios extracted <add># from production applications. <add>SCENARIOS = { <add> "Empty" => "", <add> "Single Space" => " ", <add> "Two Spaces" => " ", <add> "Mixed Whitspaces" => " \t\r\n", <add> "Very Long String" => " " * 100 <add>} <add> <add>SCENARIOS.each_pair do |name, value| <add> puts <add> puts " #{name} ".center(80, "=") <add> puts <add> <add> Benchmark.ips do |x| <add> x.report('blank?') { value.blank? } <add> x.report('fast_blank?') { value.fast_blank? } <add> x.compare! <add> end <add>end <ide><path>guides/source/contributing_to_ruby_on_rails.md <ide> The above are guidelines - please use your best judgment in using them. <ide> <ide> ### Benchmark Your Code <ide> <del>If your change has an impact on the performance of Rails, please use the <del>[benchmark-ips](https://github.com/evanphx/benchmark-ips) gem to provide <del>benchmark results for comparison. <del> <del>Here's an example of using benchmark-ips: <del> <del>```ruby <del>require 'benchmark/ips' <del> <del>Benchmark.ips do |x| <del> x.report('addition') { 1 + 2 } <del> x.report('addition with send') { 1.send(:+, 2) } <del>end <del>``` <del> <del>This will generate a report with the following information: <del> <del>``` <del>Calculating ------------------------------------- <del> addition 132.013k i/100ms <del> addition with send 125.413k i/100ms <del>------------------------------------------------- <del> addition 9.677M (± 1.7%) i/s - 48.449M <del> addition with send 6.794M (± 1.1%) i/s - 33.987M <del>``` <del> <del>Please see the benchmark/ips [README](https://github.com/evanphx/benchmark-ips/blob/master/README.md) for more information. <add>For changes that might have an impact on performance, please benchmark your <add>code and measure the impact. Please share the benchmark script you used as well <add>as the results. You should consider including these information in your commit <add>message, which allows future contributors to easily verify your findings and <add>determine if they are still relevant. (For example, future optimizations in the <add>Ruby VM might render certain optimizations unnecessary.) <add> <add>It is very easy to make an optimization that improves performance for a <add>specific scenario you care about but regresses on other common cases. <add>Therefore, you should test your change against a list of representative <add>scenarios. Ideally, they should be based on real-world scenarios extracted <add>from production applications. <add> <add>You can use the [benchmark template](https://github.com/rails/rails/blob/master/guides/bug_report_templates/benchmark.rb) <add>as a starting point. It includes the boilerplate code to setup a benchmark <add>using the [benchmark-ips](https://github.com/evanphx/benchmark-ips) gem. The <add>template is designed for testing relatively self-contained changes that can be <add>inlined into the script. <ide> <ide> ### Running Tests <ide>
2
Ruby
Ruby
read version from sdksettings
8c81a2822cb1a2af4794d5d08ee38c8d376f43e2
<ide><path>Library/Homebrew/os/mac/sdk.rb <ide> module Mac <ide> # <ide> # @api private <ide> class SDK <add> VERSIONED_SDK_REGEX = /MacOSX(\d+\.\d+)\.sdk$/.freeze <add> <ide> attr_reader :version, :path, :source <ide> <ide> def initialize(version, path, source) <ide> class BaseSDKLocator <ide> class NoSDKError < StandardError; end <ide> <ide> def sdk_for(v) <del> path = sdk_paths[v] <del> raise NoSDKError if path.nil? <add> sdk = all_sdks.find { |s| s.version == v } <add> raise NoSDKError if sdk.nil? <ide> <del> SDK.new v, path, source <add> sdk <ide> end <ide> <ide> def all_sdks <del> sdk_paths.map { |v, p| SDK.new v, p, source } <add> return @all_sdks if @all_sdks <add> <add> @all_sdks = [] <add> <add> # Bail out if there is no SDK prefix at all <add> return @all_sdks unless File.directory? sdk_prefix <add> <add> # Use unversioned SDK path on Big Sur to avoid issues such as: <add> # https://github.com/Homebrew/homebrew-core/issues/67075 <add> unversioned_sdk_path = Pathname.new("#{sdk_prefix}/MacOSX.sdk") <add> version = read_sdk_version(unversioned_sdk_path) <add> if version && version >= :big_sur <add> unversioned_sdk_version = version <add> @all_sdks << SDK.new(unversioned_sdk_version, unversioned_sdk_path, source) <add> end <add> <add> Dir["#{sdk_prefix}/MacOSX*.sdk"].each do |sdk_path| <add> next unless sdk_path.match?(SDK::VERSIONED_SDK_REGEX) <add> <add> version = read_sdk_version(Pathname.new(sdk_path)) <add> next if version.nil? || version == unversioned_sdk_version <add> <add> @all_sdks << SDK.new(version, sdk_path, source) <add> end <add> <add> @all_sdks <ide> end <ide> <ide> def sdk_if_applicable(v = nil) <ide> def sdk_prefix <ide> "" <ide> end <ide> <del> def sdk_paths <del> @sdk_paths ||= begin <del> # Bail out if there is no SDK prefix at all <del> if File.directory? sdk_prefix <del> paths = {} <del> <del> Dir[File.join(sdk_prefix, "MacOSX*.sdk")].each do |sdk_path| <del> version = sdk_path[/MacOSX(\d+\.\d+)u?\.sdk$/, 1] <del> paths[OS::Mac::Version.new(version)] = sdk_path if version.present? <del> end <del> <del> # Use unversioned SDK path on Big Sur to avoid issues such as: <del> # https://github.com/Homebrew/homebrew-core/issues/67075 <del> # This creates an entry in `paths` whose key is the OS major version <del> sdk_path = Pathname.new("#{sdk_prefix}/MacOSX.sdk") <del> sdk_settings = sdk_path/"SDKSettings.json" <del> if sdk_settings.exist? && <del> (sdk_settings_string = sdk_settings.read.presence) && <del> (sdk_settings_json = JSON.parse(sdk_settings_string).presence) && <del> (version_string = sdk_settings_json.fetch("Version", nil).presence) && <del> (version = version_string[/(\d+)\./, 1].presence) <del> paths[OS::Mac::Version.new(version)] = sdk_path <del> end <del> <del> paths <del> else <del> {} <del> end <del> end <add> def latest_sdk <add> all_sdks.max_by(&:version) <ide> end <ide> <del> # NOTE: This returns a versioned SDK path, even on Big Sur <del> def latest_sdk <del> return if sdk_paths.empty? <add> def read_sdk_version(sdk_path) <add> sdk_settings = sdk_path/"SDKSettings.json" <add> sdk_settings_string = sdk_settings.read if sdk_settings.exist? <ide> <del> v, path = sdk_paths.max { |(v1, _), (v2, _)| v1 <=> v2 } <del> SDK.new v, path, source <add> # Pre-10.14 SDKs <add> sdk_settings = sdk_path/"SDKSettings.plist" <add> if sdk_settings_string.blank? && sdk_settings.exist? <add> result = system_command("plutil", args: ["-convert", "json", "-o", "-", sdk_settings]) <add> sdk_settings_string = result.stdout if result.success? <add> end <add> <add> return if sdk_settings_string.blank? <add> <add> sdk_settings_json = JSON.parse(sdk_settings_string) <add> return if sdk_settings_json.blank? <add> <add> version_string = sdk_settings_json.fetch("Version", nil) <add> return if version_string.blank? <add> <add> begin <add> OS::Mac::Version.new(version_string).strip_patch <add> rescue MacOSVersionError <add> nil <add> end <ide> end <ide> end <ide> private_constant :BaseSDKLocator
1
Python
Python
set version to v2.1.4
3aceeeaaeb0d27d1cfa3f1d5b7671c49ccc9174a
<ide><path>spacy/about.py <ide> # fmt: off <ide> <ide> __title__ = "spacy" <del>__version__ = "2.1.4.dev1" <add>__version__ = "2.1.4" <ide> __summary__ = "Industrial-strength Natural Language Processing (NLP) with Python and Cython" <ide> __uri__ = "https://spacy.io" <ide> __author__ = "Explosion AI"
1
Text
Text
fix internal hyperlink typo
be57c8eeef69ec22edc577e6aba17eb8609ad65b
<ide><path>README.md <ide> This implementation is provided with [Google's pre-trained models](https://githu <ide> | [Doc](#doc) | Detailed documentation | <ide> | [Examples](#examples) | Detailed examples on how to fine-tune Bert | <ide> | [Notebooks](#notebooks) | Introduction on the provided Jupyter Notebooks | <del>| [TPU](#tup) | Notes on TPU support and pretraining scripts | <add>| [TPU](#tpu) | Notes on TPU support and pretraining scripts | <ide> | [Command-line interface](#Command-line-interface) | Convert a TensorFlow checkpoint in a PyTorch dump | <ide> <ide> ## Installation
1
Python
Python
fix printing of limits
1775a591a73fe76162ea871f07349648620ac5b5
<ide><path>numpy/lib/getlimits.py <ide> def __new__(cls, dtype): <ide> return obj <ide> <ide> def _init(self, dtype): <del> self.dtype = dtype <add> self.dtype = np.dtype(dtype) <ide> if dtype is ntypes.double: <ide> itype = ntypes.int64 <ide> fmt = '%24.16e' <ide> def _init(self, dtype): <ide> self.nexp = machar.iexp <ide> self.nmant = machar.it <ide> self.machar = machar <del> self._str_tiny = machar._str_xmin <del> self._str_max = machar._str_xmax <del> self._str_epsneg = machar._str_epsneg <del> self._str_eps = machar._str_eps <del> self._str_resolution = machar._str_resolution <add> self._str_tiny = machar._str_xmin.strip() <add> self._str_max = machar._str_xmax.strip() <add> self._str_epsneg = machar._str_epsneg.strip() <add> self._str_eps = machar._str_eps.strip() <add> self._str_resolution = machar._str_resolution.strip() <ide> return self <ide> <ide> def __str__(self): <ide> return '''\ <ide> Machine parameters for %(dtype)s <ide> --------------------------------------------------------------------- <del>precision=%(precision)3s resolution=%(_str_resolution)s <del>machep=%(machep)6s eps= %(_str_eps)s <del>negep =%(negep)6s epsneg= %(_str_epsneg)s <del>minexp=%(minexp)6s tiny= %(_str_tiny)s <del>maxexp=%(maxexp)6s max= %(_str_max)s <del>nexp =%(nexp)6s min= -max <add>precision=%(precision)3s resolution= %(_str_resolution)s <add>machep=%(machep)6s eps= %(_str_eps)s <add>negep =%(negep)6s epsneg= %(_str_epsneg)s <add>minexp=%(minexp)6s tiny= %(_str_tiny)s <add>maxexp=%(maxexp)6s max= %(_str_max)s <add>nexp =%(nexp)6s min= -max <ide> --------------------------------------------------------------------- <ide> ''' % self.__dict__ <ide> <ide> def max(self): <ide> <ide> max = property(max) <ide> <add> def __str__(self): <add> """String representation.""" <add> return ''' <add>Machine parameters for %(dtype)s <add>--------------------------------------------------------------------- <add>min = %(min)s <add>max = %(max)s <add>--------------------------------------------------------------------- <add>''' % {'dtype': self.dtype, 'min': self.min, 'max': self.max} <add> <add> <ide> if __name__ == '__main__': <ide> f = finfo(ntypes.single) <ide> print 'single epsilon:',f.eps
1
Javascript
Javascript
use prefetchimage method in image
0167dff2094e1b1c42d981c0b97f9baf3707921f
<ide><path>Libraries/Image/Image.ios.js <ide> function getSizeWithHeaders( <ide> } <ide> <ide> function prefetch(url: string): any { <del> return ImageViewManager.prefetchImage(url); <add> return NativeImageLoader.prefetchImage(url); <ide> } <ide> <ide> async function queryCache(
1
Python
Python
fix import error
7e1a13ffbd212e928e866c2e4cf5d92d85660f86
<ide><path>examples/minitwit/minitwit/__init__.py <del>from minitwit import app <ide>\ No newline at end of file <add>from .minitwit import app
1
PHP
PHP
load cakephp-plugins when searching paths
703b4860b7f3b827e609bb59c16ff79860e1eb99
<ide><path>src/Core/PluginCollection.php <ide> protected function loadConfig() <ide> */ <ide> public function findPath($name) <ide> { <add> $this->loadConfig(); <add> <ide> $path = Configure::read('plugins.' . $name); <ide> if ($path) { <ide> return $path; <ide><path>tests/TestCase/Core/PluginCollectionTest.php <ide> public function testFindPathNoConfigureData() <ide> $this->assertEquals(TEST_APP . 'Plugin' . DS . 'TestPlugin' . DS, $path); <ide> } <ide> <add> public function testFindPathLoadsConfigureData() <add> { <add> $configPath = ROOT . DS . 'cakephp-plugins.php'; <add> $this->skipIf(file_exists($configPath), 'cakephp-plugins.php exists, skipping overwrite'); <add> $file = <<<PHP <add><?php <add>return [ <add> 'plugins' => [ <add> 'TestPlugin' => '/config/path' <add> ] <add>]; <add>PHP; <add> file_put_contents($configPath, $file); <add> <add> Configure::delete('plugins'); <add> $plugins = new PluginCollection(); <add> $path = $plugins->findPath('TestPlugin'); <add> unlink($configPath); <add> <add> $this->assertEquals('/config/path', $path); <add> } <add> <ide> public function testFindPathConfigureData() <ide> { <ide> Configure::write('plugins', ['TestPlugin' => '/some/path']);
2
PHP
PHP
add alias for call silent
7f3101bf6e8a0f048a243a55be7fc79eb359b609
<ide><path>src/Illuminate/Console/Concerns/CallsCommands.php <ide> public function call($command, array $arguments = []) <ide> } <ide> <ide> /** <del> * Call another console command silently. <add> * Call another console command without output. <ide> * <ide> * @param \Symfony\Component\Console\Command\Command|string $command <ide> * @param array $arguments <ide> public function callSilent($command, array $arguments = []) <ide> return $this->runCommand($command, $arguments, new NullOutput); <ide> } <ide> <add> /** <add> * Call another console command without output. <add> * <add> * @param \Symfony\Component\Console\Command\Command|string $command <add> * @param array $arguments <add> * @return int <add> */ <add> public function callWithoutOutput($command, array $arguments = []) <add> { <add> return $this->callSilent($command, $arguments); <add> } <add> <ide> /** <ide> * Run the given the console command. <ide> *
1
Go
Go
remove lcow bits
c33b9bcfd420049b95936092282fe33c1ab9917c
<ide><path>libcontainerd/local/local_windows.go <ide> package local // import "github.com/docker/docker/libcontainerd/local" <ide> <ide> import ( <ide> "context" <del> "encoding/json" <ide> "fmt" <ide> "io/ioutil" <ide> "os" <ide> type container struct { <ide> // have access to the Spec <ide> ociSpec *specs.Spec <ide> <del> isWindows bool <ide> hcsContainer hcsshim.Container <ide> <ide> id string <ide> func (c *client) createWindows(id string, spec *specs.Spec, runtimeOptions inter <ide> ctr := &container{ <ide> id: id, <ide> execs: make(map[string]*process), <del> isWindows: true, <ide> ociSpec: spec, <ide> hcsContainer: hcsContainer, <ide> status: containerd.Created, <ide> func (c *client) Start(_ context.Context, id, _ string, withStdin bool, attachSt <ide> createProcessParms.Environment = setupEnvironmentVariables(ctr.ociSpec.Process.Env) <ide> <ide> // Configure the CommandLine/CommandArgs <del> setCommandLineAndArgs(ctr.isWindows, ctr.ociSpec.Process, createProcessParms) <del> if ctr.isWindows { <del> logger.Debugf("start commandLine: %s", createProcessParms.CommandLine) <del> } <add> setCommandLineAndArgs(ctr.ociSpec.Process, createProcessParms) <add> logger.Debugf("start commandLine: %s", createProcessParms.CommandLine) <ide> <ide> createProcessParms.User = ctr.ociSpec.Process.User.Username <ide> <del> // LCOW requires the raw OCI spec passed through HCS and onwards to <del> // GCS for the utility VM. <del> if !ctr.isWindows { <del> ociBuf, err := json.Marshal(ctr.ociSpec) <del> if err != nil { <del> return -1, err <del> } <del> ociRaw := json.RawMessage(ociBuf) <del> createProcessParms.OCISpecification = &ociRaw <del> } <del> <ide> ctr.Lock() <ide> <ide> // Start the command running in the container. <ide> func (c *client) Start(_ context.Context, id, _ string, withStdin bool, attachSt <ide> } <ide> <ide> // setCommandLineAndArgs configures the HCS ProcessConfig based on an OCI process spec <del>func setCommandLineAndArgs(isWindows bool, process *specs.Process, createProcessParms *hcsshim.ProcessConfig) { <del> if isWindows { <del> if process.CommandLine != "" { <del> createProcessParms.CommandLine = process.CommandLine <del> } else { <del> createProcessParms.CommandLine = system.EscapeArgs(process.Args) <del> } <add>func setCommandLineAndArgs(process *specs.Process, createProcessParms *hcsshim.ProcessConfig) { <add> if process.CommandLine != "" { <add> createProcessParms.CommandLine = process.CommandLine <ide> } else { <del> createProcessParms.CommandArgs = process.Args <add> createProcessParms.CommandLine = system.EscapeArgs(process.Args) <ide> } <ide> } <ide> <ide> func (c *client) Exec(ctx context.Context, containerID, processID string, spec * <ide> createProcessParms.Environment = setupEnvironmentVariables(spec.Env) <ide> <ide> // Configure the CommandLine/CommandArgs <del> setCommandLineAndArgs(ctr.isWindows, spec, createProcessParms) <add> setCommandLineAndArgs(spec, createProcessParms) <ide> logger.Debugf("exec commandLine: %s", createProcessParms.CommandLine) <ide> <ide> createProcessParms.User = spec.User.Username
1
PHP
PHP
update use of deprecated class name
48d6eddca0cbf46521974feb2575e48f05184272
<ide><path>src/Database/Expression/TupleComparison.php <ide> * This expression represents SQL fragments that are used for comparing one tuple <ide> * to another, one tuple to a set of other tuples or one tuple to an expression <ide> */ <del>class TupleComparison extends Comparison <add>class TupleComparison extends ComparisonExpression <ide> { <ide> /** <ide> * The type to be used for casting the value to a database representation
1