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
Text
Text
add readme for react-native cli
1e863ad1921d6c45d89637abbf3b38b33ab3b241
<ide><path>react-native-cli/README.md <add>Use react-native-cli to initialize a working starter React Native app using the latest react-native version in npm. This package should be installed globally. <add> <add>Usage: <add> <add>``` <add>% npm install -g react-native-cli <add>% react-native init myApplication <add>```
1
PHP
PHP
remove unused import
d3befb99db7b6a2abd2ca6198fada8e1b786bb00
<ide><path>src/Illuminate/Console/Scheduling/Schedule.php <ide> use Illuminate\Console\Application; <ide> use Illuminate\Container\Container; <ide> use Symfony\Component\Process\ProcessUtils; <del>use Illuminate\Contracts\Cache\Repository as Cache; <ide> <ide> class Schedule <ide> {
1
Text
Text
update translation for chinese
f7496376094f277572f4bdee5be5229b2bcee672
<ide><path>guide/chinese/css/background-opacity/index.md <ide> Opacity 可以是 0 到 1 之间的任何值; <ide> } <ide> ``` <ide> <del>或者,您可以这样使用透明的 rgba 值: <add> <add>或者,您可以使用透明的rgba值,如下所示: <ide> <ide> ```css <del>.class-name{ <del> background-color: rgba( 0, 0, 0, .5); <add>.class-name { <add> background-color: rgba (0,0,0,0.5); <ide> } <ide> ``` <del> <del>上例中将背景设置为不透明度为50%的黑色。 rgba 值的最后一个值是 alpha 值。 alpha 值为 1 就是 100% , 0.5 (简写为 .5 )就是 50% 。我们使用此方法为元素添加透明度而不影响内部内容。 <add>上面的示例将背景设置为黑色,不透明度为50%。 rgba值的最后一个值是alpha值。 α值为1等于100%,0.5(简称为.5)则为50%。我们使用此方法为元素添加透明度而不影响内部内容。 <add> <ide> <ide> [用于显示背景不透明度范围的 codepen 示例](https://codepen.io/lvcoulter/full/dVrwmK/) <ide>
1
Ruby
Ruby
write bottle version in commit message
9773b9e8bffb5e4529ad3a48923582b69ce7c29b
<ide><path>Library/Homebrew/cmd/bottle.rb <ide> def merge <ide> update_or_add = has_bottle_block ? 'update' : 'add' <ide> <ide> safe_system 'git', 'commit', formula_path, '-m', <del> "#{f.name}: #{update_or_add} bottle." <add> "#{f.name}: #{update_or_add} #{f.version} bottle." <ide> end <ide> end <ide> exit 0
1
Javascript
Javascript
avoid race condition for appstate.currentstate
809f1e97dea85cd259207ed729dcde6ed65a9348
<ide><path>Libraries/AppState/AppState.js <ide> class AppState extends NativeEventEmitter { <ide> // the Android implementation. <ide> this.currentState = RCTAppState.initialAppState || 'active'; <ide> <add> let eventUpdated = false; <add> <ide> // TODO: this is a terrible solution - in order to ensure `currentState` prop <ide> // is up to date, we have to register an observer that updates it whenever <ide> // the state changes, even if nobody cares. We should just deprecate the <ide> // `currentState` property and get rid of this. <ide> this.addListener( <ide> 'appStateDidChange', <ide> (appStateData) => { <add> eventUpdated = true; <ide> this.currentState = appStateData.app_state; <ide> } <ide> ); <ide> class AppState extends NativeEventEmitter { <ide> // and expose `getCurrentAppState` method directly. <ide> RCTAppState.getCurrentAppState( <ide> (appStateData) => { <del> this.currentState = appStateData.app_state; <add> if (!eventUpdated) { <add> this.currentState = appStateData.app_state; <add> } <ide> }, <ide> logError <ide> );
1
Javascript
Javascript
prewalk a function declaration
619cf318eca3efed666b86a2488eb4cd485a8a9c
<ide><path>lib/Parser.js <ide> class Parser extends Tapable { <ide> <ide> walkFunctionDeclaration(statement) { <ide> this.inScope(statement.params, function() { <del> if(statement.body.type === "BlockStatement") <add> if(statement.body.type === "BlockStatement") { <add> this.prewalkStatement(statement.body); <ide> this.walkStatement(statement.body); <del> else <add> } else { <ide> this.walkExpression(statement.body); <add> } <ide> }.bind(this)); <ide> } <ide> <ide><path>test/cases/parsing/issue-4709/index.js <add>function getDirectiveRequire(directive) { <add> var require = directive.require || (directive.controller && directive.name); <add> <add> if (!isArray(require) && isObject(require)) { <add> forEach(require, function(value, key) { <add> var match = value.match(REQUIRE_PREFIX_REGEXP); <add> var name = value.substring(match[0].length); <add> if (!name) require[key] = match[0] + key; <add> }); <add> } <add> <add> return require; <add>} <add> <add>it("should parse these snippets successfully", function() { <add> <add>});
2
Python
Python
add execute cmd on container function
5995e5c46db7764bce3247105ce7626bba097704
<ide><path>libcloud/container/drivers/lxd.py <ide> def __str__(self): <ide> str(self.public) <ide> <ide> <del>LXDContainerExecute = collections.namedtuple('LXDContainerExecute', <add>LXDContainerExecuteResult = collections.namedtuple('LXDContainerExecuteResult', <ide> ['uuid','secret_0', 'secret_1', <ide> 'secret_2', 'control', <ide> 'output', 'result']) <ide> class LXDContainerDriver(ContainerDriver): <ide> default_time_out = 30 <ide> <ide> # default configuration when creating a container <del> <del> <ide> # if the architecture is not specified <ide> # by the client code then the underlying <ide> # host architecture should be picked up by <ide> def destroy_container(self, container, ex_timeout=default_time_out): <ide> <ide> return container <ide> <del> def ex_execute_cmd_on_container(self, cont_id, command, timeout=default_time_out, **config): <add> def ex_execute_cmd_on_container(self, cont_id, command, **config): <ide> """ <ide> Description: run a remote command <ide> Operation: async <ide> <del> Return: background operation + optional <del> websocket information or standard error <add> Return: Depends on the the configuration <add> <add> if wait-for-websocket=true and interactive=false <add> returns a LXDContainerExecuteResult with: <add> uuid=uuid, <add> secret_0=fds["0"], <add> secret_1=fds["1"], <add> secret_2=fds["2"], <add> control=fds["control"], <add> output={}, result=None <add> <add> if wait-for-websocket=true and interactive=true <add> returns a LXDContainerExecuteResult with: <add> uuid=uuid, <add> secret_0=fds["0"], <add> secret_1=None, <add> secret_2=None, <add> control=fds["control"], <add> output={}, result=None <add> <add> if interactive=false and record-output=true <add> returns a LXDContainerExecuteResult with: <add> uuid=uuid, <add> secret_0=None, <add> secret_1=None, <add> secret_2=None, <add> control=None, <add> output=output, result=result <add> <add> if none of the above it assumes that the command has <add> been executed and returns LXDContainerExecuteResult with: <add> uuid=uuid, <add> secret_0=None, <add> secret_1=None, <add> secret_2=None, <add> control=None, <add> output=None, result=result <add> <add> <add> in all the above uuid is the operation id <ide> <ide> :param cont_id: The container name to run the commands <ide> ":type cont_id: ``str`` <ide> def ex_execute_cmd_on_container(self, cont_id, command, timeout=default_time_out <ide> :type timeout: ``int`` <ide> <ide> :param command: a list of strings indicating the commands <del> and their arguments e.g: ["/bin/bash"] <add> and their arguments e.g: ["/bin/bash ls -l"] <ide> :type command ``list`` <ide> <ide> :param config: Dict with extra arguments. <del> For example: <del> <del> width: Initial width of the terminal default 80 <ide> <del> height: Initial height of the terminal default 25 <add> For example: <ide> <del> user: User to run the command as default 1000 <add> width: Initial width of the terminal default 80 <add> height: Initial height of the terminal default 25 <add> user: User to run the command as default 1000 <add> group: Group to run the command as default 1000 <add> cwd: Current working directory default /tmp <ide> <del> group: Group to run the command as default 1000 <add> wait-for-websocket: Whether to wait for a connection <add> before starting the process. Default False <ide> <del> cwd: Current working directory default /tmp <add> record-output: Whether to store stdout and stderr <add> (only valid with wait-for-websocket=false) <add> (requires API extension container_exec_recording). Default False <ide> <del> wait-for-websocket: Whether to wait for a connection <del> before starting the process. Default False <add> interactive: Whether to allocate a pts device instead of PIPEs. Default true <ide> <del> record-output: Whether to store stdout and stderr <del> (only valid with wait-for-websocket=false) <del> (requires API extension container_exec_recording). Default False <del> <del> interactive: Whether to allocate a pts device instead of PIPEs. Default true <ide> :type config ``dict`` <ide> <del> :return: <add> :rtype LXDContainerExecuteResult <ide> """ <ide> <ide> input = {"command": command} <ide> def ex_execute_cmd_on_container(self, cont_id, command, timeout=default_time_out <ide> <ide> if input["wait-for-websocket"] == True and\ <ide> input["interactive"] == False: <del> return LXDContainerExecute(uuid=uuid, <del> secret_0=fds["0"], <del> secret_1=fds["1"], <del> secret_2=fds["2"], <del> control=fds["control"], <del> output={}, result=None) <add> return LXDContainerExecuteResult(uuid=uuid, <add> secret_0=fds["0"], <add> secret_1=fds["1"], <add> secret_2=fds["2"], <add> control=fds["control"], <add> output={}, result=None) <ide> <ide> elif input["wait-for-websocket"] == True and\ <ide> input["interactive"] == True: <ide> <del> return LXDContainerExecute(uuid=uuid, <del> secret_0=fds["0"], <del> secret_1=None, <del> secret_2=None, <del> control=fds["control"], <del> output={}, result=None) <add> return LXDContainerExecuteResult(uuid=uuid, <add> secret_0=fds["0"], <add> secret_1=None, <add> secret_2=None, <add> control=fds["control"], <add> output={}, result=None) <ide> <ide> elif input["interactive"] == False and\ <ide> input["record-output"] == True: <ide> <ide> output = response_dict['metadata']['metadata']['output'] <ide> result = response_dict['metadata']['metadata']['result'] <del> return LXDContainerExecute(uuid=uuid, <del> secret_0=None, <del> secret_1=None, <del> secret_2=None, <del> control=None, <del> output=output, result=result) <add> return LXDContainerExecuteResult(uuid=uuid, <add> secret_0=None, <add> secret_1=None, <add> secret_2=None, <add> control=None, <add> output=output, result=result) <ide> <ide> else: <ide> <ide> result = response_dict['metadata']['metadata']['result'] <del> return LXDContainerExecute(uuid=uuid, <del> secret_0=None, <del> secret_1=None, <del> secret_2=None, <del> control=None, <del> output={}, result=result) <del> <del> <del> <del> <del> def ex_get_websocket(self, uuid, secret): <del> <del> req='/%s/operations/%s/websocket?secret=%s' % (self.version, uuid, secret) <del> response = self.connection.request(re) <add> return LXDContainerExecuteResult(uuid=uuid, <add> secret_0=None, <add> secret_1=None, <add> secret_2=None, <add> control=None, <add> output={}, result=result) <ide> <ide> def list_containers(self, image=None, cluster=None, ex_detailed=True): <ide> """
1
Javascript
Javascript
reorganize atomapplication tests
f20aa038bd0261b74798af7e6965fca54a1772ca
<ide><path>spec/main-process/atom-application.test.js <ide> describe('AtomApplication', function () { <ide> }) <ide> <ide> describe('launch', () => { <del> it('can open to a specific line number of a file', async () => { <del> const filePath = path.join(makeTempDir(), 'new-file') <del> fs.writeFileSync(filePath, '1\n2\n3\n4\n') <del> const atomApplication = buildAtomApplication() <add> describe('with no paths', () => { <add> it('reopens any previously opened windows', async () => { <add> if (process.platform === 'win32') return // Test is too flakey on Windows <ide> <del> const [window] = await atomApplication.launch(parseCommandLine([filePath + ':3'])) <del> await focusWindow(window) <add> const tempDirPath1 = makeTempDir() <add> const tempDirPath2 = makeTempDir() <ide> <del> const cursorRow = await evalInWebContents(window.browserWindow.webContents, sendBackToMainProcess => { <del> atom.workspace.observeTextEditors(textEditor => { <del> sendBackToMainProcess(textEditor.getCursorBufferPosition().row) <add> const atomApplication1 = buildAtomApplication() <add> const [app1Window1] = await atomApplication1.launch(parseCommandLine([tempDirPath1])) <add> await emitterEventPromise(app1Window1, 'window:locations-opened') <add> <add> const [app1Window2] = await atomApplication1.launch(parseCommandLine([tempDirPath2])) <add> await emitterEventPromise(app1Window2, 'window:locations-opened') <add> <add> await Promise.all([ <add> app1Window1.prepareToUnload(), <add> app1Window2.prepareToUnload() <add> ]) <add> <add> const atomApplication2 = buildAtomApplication() <add> const [app2Window1, app2Window2] = await atomApplication2.launch(parseCommandLine([])) <add> await Promise.all([ <add> emitterEventPromise(app2Window1, 'window:locations-opened'), <add> emitterEventPromise(app2Window2, 'window:locations-opened') <add> ]) <add> <add> assert.deepEqual(await getTreeViewRootDirectories(app2Window1), [tempDirPath1]) <add> assert.deepEqual(await getTreeViewRootDirectories(app2Window2), [tempDirPath2]) <add> }) <add> <add> it('when windows already exist, opens a new window with a single untitled buffer', async () => { <add> const atomApplication = buildAtomApplication() <add> const [window1] = await atomApplication.launch(parseCommandLine([])) <add> await focusWindow(window1) <add> const window1EditorTitle = await evalInWebContents(window1.browserWindow.webContents, sendBackToMainProcess => { <add> sendBackToMainProcess(atom.workspace.getActiveTextEditor().getTitle()) <add> }) <add> assert.equal(window1EditorTitle, 'untitled') <add> <add> const window2 = atomApplication.openWithOptions(parseCommandLine([])) <add> await window2.loadedPromise <add> const window2EditorTitle = await evalInWebContents(window1.browserWindow.webContents, sendBackToMainProcess => { <add> sendBackToMainProcess(atom.workspace.getActiveTextEditor().getTitle()) <ide> }) <add> assert.equal(window2EditorTitle, 'untitled') <add> <add> assert.deepEqual(atomApplication.getAllWindows(), [window2, window1]) <ide> }) <ide> <del> assert.equal(cursorRow, 2) <del> }) <add> it('when no windows are open but --new-window is passed, opens a new window with a single untitled buffer', async () => { <add> // Populate some saved state <add> const tempDirPath1 = makeTempDir() <add> const tempDirPath2 = makeTempDir() <ide> <del> it('can open to a specific line and column of a file', async () => { <del> const filePath = path.join(makeTempDir(), 'new-file') <del> fs.writeFileSync(filePath, '1\n2\n3\n4\n') <del> const atomApplication = buildAtomApplication() <add> const atomApplication1 = buildAtomApplication() <add> const [app1Window1] = await atomApplication1.launch(parseCommandLine([tempDirPath1])) <add> await emitterEventPromise(app1Window1, 'window:locations-opened') <ide> <del> const [window] = await atomApplication.launch(parseCommandLine([filePath + ':2:2'])) <del> await focusWindow(window) <add> const [app1Window2] = await atomApplication1.launch(parseCommandLine([tempDirPath2])) <add> await emitterEventPromise(app1Window2, 'window:locations-opened') <ide> <del> const cursorPosition = await evalInWebContents(window.browserWindow.webContents, sendBackToMainProcess => { <del> atom.workspace.observeTextEditors(textEditor => { <del> sendBackToMainProcess(textEditor.getCursorBufferPosition()) <add> await Promise.all([ <add> app1Window1.prepareToUnload(), <add> app1Window2.prepareToUnload() <add> ]) <add> <add> // Launch with --new-window <add> const atomApplication2 = buildAtomApplication() <add> const appWindows2 = await atomApplication2.launch(parseCommandLine(['--new-window'])) <add> assert.lengthOf(appWindows2, 1) <add> const [appWindow2] = appWindows2 <add> await appWindow2.loadedPromise <add> const window2EditorTitle = await evalInWebContents(appWindow2.browserWindow.webContents, sendBackToMainProcess => { <add> sendBackToMainProcess(atom.workspace.getActiveTextEditor().getTitle()) <ide> }) <add> assert.equal(window2EditorTitle, 'untitled') <ide> }) <ide> <del> assert.deepEqual(cursorPosition, {row: 1, column: 1}) <add> it('does not open an empty editor if core.openEmptyEditorOnStart is false', async () => { <add> const configPath = path.join(process.env.ATOM_HOME, 'config.cson') <add> const config = season.readFileSync(configPath) <add> if (!config['*'].core) config['*'].core = {} <add> config['*'].core.openEmptyEditorOnStart = false <add> season.writeFileSync(configPath, config) <add> <add> const atomApplication = buildAtomApplication() <add> const [window1] = await atomApplication.launch(parseCommandLine([])) <add> await focusWindow(window1) <add> <add> // wait a bit just to make sure we don't pass due to querying the render process before it loads <add> await timeoutPromise(1000) <add> <add> const itemCount = await evalInWebContents(window1.browserWindow.webContents, sendBackToMainProcess => { <add> sendBackToMainProcess(atom.workspace.getActivePane().getItems().length) <add> }) <add> assert.equal(itemCount, 0) <add> }) <ide> }) <ide> <del> it('removes all trailing whitespace and colons from the specified path', async () => { <del> let filePath = path.join(makeTempDir(), 'new-file') <del> fs.writeFileSync(filePath, '1\n2\n3\n4\n') <del> const atomApplication = buildAtomApplication() <add> describe('with file or folder paths', () => { <add> it('shows all directories in the tree view when multiple directory paths are passed to Atom', async () => { <add> const dirAPath = makeTempDir('a') <add> const dirBPath = makeTempDir('b') <add> const dirBSubdirPath = path.join(dirBPath, 'c') <add> fs.mkdirSync(dirBSubdirPath) <ide> <del> const [window] = await atomApplication.launch(parseCommandLine([filePath + ':: '])) <del> await focusWindow(window) <add> const atomApplication = buildAtomApplication() <add> const [window1] = await atomApplication.launch(parseCommandLine([dirAPath, dirBPath])) <add> await focusWindow(window1) <ide> <del> const openedPath = await evalInWebContents(window.browserWindow.webContents, sendBackToMainProcess => { <del> atom.workspace.observeTextEditors(textEditor => { <del> sendBackToMainProcess(textEditor.getPath()) <add> await conditionPromise(async () => (await getTreeViewRootDirectories(window1)).length === 2) <add> assert.deepEqual(await getTreeViewRootDirectories(window1), [dirAPath, dirBPath]) <add> }) <add> <add> it('can open to a specific line number of a file', async () => { <add> const filePath = path.join(makeTempDir(), 'new-file') <add> fs.writeFileSync(filePath, '1\n2\n3\n4\n') <add> const atomApplication = buildAtomApplication() <add> <add> const [window] = await atomApplication.launch(parseCommandLine([filePath + ':3'])) <add> await focusWindow(window) <add> <add> const cursorRow = await evalInWebContents(window.browserWindow.webContents, sendBackToMainProcess => { <add> atom.workspace.observeTextEditors(textEditor => { <add> sendBackToMainProcess(textEditor.getCursorBufferPosition().row) <add> }) <add> }) <add> <add> assert.equal(cursorRow, 2) <add> }) <add> <add> it('can open to a specific line and column of a file', async () => { <add> const filePath = path.join(makeTempDir(), 'new-file') <add> fs.writeFileSync(filePath, '1\n2\n3\n4\n') <add> const atomApplication = buildAtomApplication() <add> <add> const [window] = await atomApplication.launch(parseCommandLine([filePath + ':2:2'])) <add> await focusWindow(window) <add> <add> const cursorPosition = await evalInWebContents(window.browserWindow.webContents, sendBackToMainProcess => { <add> atom.workspace.observeTextEditors(textEditor => { <add> sendBackToMainProcess(textEditor.getCursorBufferPosition()) <add> }) <add> }) <add> <add> assert.deepEqual(cursorPosition, {row: 1, column: 1}) <add> }) <add> <add> it('removes all trailing whitespace and colons from the specified path', async () => { <add> let filePath = path.join(makeTempDir(), 'new-file') <add> fs.writeFileSync(filePath, '1\n2\n3\n4\n') <add> const atomApplication = buildAtomApplication() <add> <add> const [window] = await atomApplication.launch(parseCommandLine([filePath + ':: '])) <add> await focusWindow(window) <add> <add> const openedPath = await evalInWebContents(window.browserWindow.webContents, sendBackToMainProcess => { <add> atom.workspace.observeTextEditors(textEditor => { <add> sendBackToMainProcess(textEditor.getPath()) <add> }) <add> }) <add> <add> assert.equal(openedPath, filePath) <add> }) <add> <add> it('opens an empty text editor when launched with a new file path', async () => { <add> // Choosing "Don't save" <add> mockElectronShowMessageBox({response: 2}) <add> <add> const atomApplication = buildAtomApplication() <add> const newFilePath = path.join(makeTempDir(), 'new-file') <add> const [window] = await atomApplication.launch(parseCommandLine([newFilePath])) <add> await focusWindow(window) <add> const {editorTitle, editorText} = await evalInWebContents(window.browserWindow.webContents, sendBackToMainProcess => { <add> atom.workspace.observeTextEditors(editor => { <add> sendBackToMainProcess({editorTitle: editor.getTitle(), editorText: editor.getText()}) <add> }) <ide> }) <add> assert.equal(editorTitle, path.basename(newFilePath)) <add> assert.equal(editorText, '') <add> assert.deepEqual(await getTreeViewRootDirectories(window), []) <ide> }) <add> }) <add> <add> describe('when the --add option is specified', () => { <add> it('adds folders to existing windows when the --add option is used', async () => { <add> const dirAPath = makeTempDir('a') <add> const dirBPath = makeTempDir('b') <add> const dirCPath = makeTempDir('c') <add> const existingDirCFilePath = path.join(dirCPath, 'existing-file') <add> fs.writeFileSync(existingDirCFilePath, 'this is an existing file') <add> <add> const atomApplication = buildAtomApplication() <add> const [window1] = await atomApplication.launch(parseCommandLine([dirAPath])) <add> await focusWindow(window1) <ide> <del> assert.equal(openedPath, filePath) <add> await conditionPromise(async () => (await getTreeViewRootDirectories(window1)).length === 1) <add> assert.deepEqual(await getTreeViewRootDirectories(window1), [dirAPath]) <add> <add> // When opening *files* with --add, reuses an existing window <add> let [reusedWindow] = await atomApplication.launch(parseCommandLine([existingDirCFilePath, '--add'])) <add> assert.equal(reusedWindow, window1) <add> assert.deepEqual(atomApplication.getAllWindows(), [window1]) <add> let activeEditorPath = await evalInWebContents(window1.browserWindow.webContents, sendBackToMainProcess => { <add> const subscription = atom.workspace.onDidChangeActivePaneItem(textEditor => { <add> sendBackToMainProcess(textEditor.getPath()) <add> subscription.dispose() <add> }) <add> }) <add> assert.equal(activeEditorPath, existingDirCFilePath) <add> assert.deepEqual(await getTreeViewRootDirectories(window1), [dirAPath]) <add> <add> // When opening *directories* with --add, reuses an existing window and adds the directory to the project <add> reusedWindow = (await atomApplication.launch(parseCommandLine([dirBPath, '-a'])))[0] <add> assert.equal(reusedWindow, window1) <add> assert.deepEqual(atomApplication.getAllWindows(), [window1]) <add> <add> await conditionPromise(async () => (await getTreeViewRootDirectories(reusedWindow)).length === 2) <add> assert.deepEqual(await getTreeViewRootDirectories(window1), [dirAPath, dirBPath]) <add> }) <ide> }) <ide> <ide> if (process.platform === 'darwin' || process.platform === 'win32') { <ide> describe('AtomApplication', function () { <ide> }) <ide> } <ide> <del> it('adds folders to existing windows when the --add option is used', async () => { <del> const dirAPath = makeTempDir('a') <del> const dirBPath = makeTempDir('b') <del> const dirCPath = makeTempDir('c') <del> const existingDirCFilePath = path.join(dirCPath, 'existing-file') <del> fs.writeFileSync(existingDirCFilePath, 'this is an existing file') <del> <del> const atomApplication = buildAtomApplication() <del> const [window1] = await atomApplication.launch(parseCommandLine([dirAPath])) <del> await focusWindow(window1) <del> <del> await conditionPromise(async () => (await getTreeViewRootDirectories(window1)).length === 1) <del> assert.deepEqual(await getTreeViewRootDirectories(window1), [dirAPath]) <del> <del> // When opening *files* with --add, reuses an existing window <del> let [reusedWindow] = await atomApplication.launch(parseCommandLine([existingDirCFilePath, '--add'])) <del> assert.equal(reusedWindow, window1) <del> assert.deepEqual(atomApplication.getAllWindows(), [window1]) <del> let activeEditorPath = await evalInWebContents(window1.browserWindow.webContents, sendBackToMainProcess => { <del> const subscription = atom.workspace.onDidChangeActivePaneItem(textEditor => { <del> sendBackToMainProcess(textEditor.getPath()) <del> subscription.dispose() <del> }) <del> }) <del> assert.equal(activeEditorPath, existingDirCFilePath) <del> assert.deepEqual(await getTreeViewRootDirectories(window1), [dirAPath]) <del> <del> // When opening *directories* with --add, reuses an existing window and adds the directory to the project <del> reusedWindow = (await atomApplication.launch(parseCommandLine([dirBPath, '-a'])))[0] <del> assert.equal(reusedWindow, window1) <del> assert.deepEqual(atomApplication.getAllWindows(), [window1]) <del> <del> await conditionPromise(async () => (await getTreeViewRootDirectories(reusedWindow)).length === 2) <del> assert.deepEqual(await getTreeViewRootDirectories(window1), [dirAPath, dirBPath]) <del> }) <del> <ide> it('persists window state based on the project directories', async () => { <ide> // Choosing "Don't save" <ide> mockElectronShowMessageBox({response: 2}) <ide> describe('AtomApplication', function () { <ide> assert.equal(window2Text, 'Hello World! How are you?') <ide> }) <ide> <del> it('shows all directories in the tree view when multiple directory paths are passed to Atom', async () => { <del> const dirAPath = makeTempDir('a') <del> const dirBPath = makeTempDir('b') <del> const dirBSubdirPath = path.join(dirBPath, 'c') <del> fs.mkdirSync(dirBSubdirPath) <del> <del> const atomApplication = buildAtomApplication() <del> const [window1] = await atomApplication.launch(parseCommandLine([dirAPath, dirBPath])) <del> await focusWindow(window1) <del> <del> await conditionPromise(async () => (await getTreeViewRootDirectories(window1)).length === 2) <del> assert.deepEqual(await getTreeViewRootDirectories(window1), [dirAPath, dirBPath]) <del> }) <del> <del> it('opens a new window with a single untitled buffer when launched with no path, even if windows already exist', async () => { <del> const atomApplication = buildAtomApplication() <del> const [window1] = await atomApplication.launch(parseCommandLine([])) <del> await focusWindow(window1) <del> const window1EditorTitle = await evalInWebContents(window1.browserWindow.webContents, sendBackToMainProcess => { <del> sendBackToMainProcess(atom.workspace.getActiveTextEditor().getTitle()) <del> }) <del> assert.equal(window1EditorTitle, 'untitled') <del> <del> const window2 = atomApplication.openWithOptions(parseCommandLine([])) <del> await focusWindow(window2) <del> const window2EditorTitle = await evalInWebContents(window1.browserWindow.webContents, sendBackToMainProcess => { <del> sendBackToMainProcess(atom.workspace.getActiveTextEditor().getTitle()) <del> }) <del> assert.equal(window2EditorTitle, 'untitled') <del> <del> assert.deepEqual(atomApplication.getAllWindows(), [window2, window1]) <del> }) <del> <del> it('does not open an empty editor when opened with no path if the core.openEmptyEditorOnStart config setting is false', async () => { <del> const configPath = path.join(process.env.ATOM_HOME, 'config.cson') <del> const config = season.readFileSync(configPath) <del> if (!config['*'].core) config['*'].core = {} <del> config['*'].core.openEmptyEditorOnStart = false <del> season.writeFileSync(configPath, config) <del> <del> const atomApplication = buildAtomApplication() <del> const [window1] = await atomApplication.launch(parseCommandLine([])) <del> await focusWindow(window1) <del> <del> // wait a bit just to make sure we don't pass due to querying the render process before it loads <del> await timeoutPromise(1000) <del> <del> const itemCount = await evalInWebContents(window1.browserWindow.webContents, sendBackToMainProcess => { <del> sendBackToMainProcess(atom.workspace.getActivePane().getItems().length) <del> }) <del> assert.equal(itemCount, 0) <del> }) <del> <del> it('opens an empty text editor when launched with a new file path', async () => { <del> // Choosing "Don't save" <del> mockElectronShowMessageBox({response: 2}) <del> <del> const atomApplication = buildAtomApplication() <del> const newFilePath = path.join(makeTempDir(), 'new-file') <del> const [window] = await atomApplication.launch(parseCommandLine([newFilePath])) <del> await focusWindow(window) <del> const {editorTitle, editorText} = await evalInWebContents(window.browserWindow.webContents, sendBackToMainProcess => { <del> atom.workspace.observeTextEditors(editor => { <del> sendBackToMainProcess({editorTitle: editor.getTitle(), editorText: editor.getText()}) <del> }) <del> }) <del> assert.equal(editorTitle, path.basename(newFilePath)) <del> assert.equal(editorText, '') <del> assert.deepEqual(await getTreeViewRootDirectories(window), []) <del> }) <del> <ide> it('adds a remote directory to the project when launched with a remote directory', async () => { <ide> const packagePath = path.join(__dirname, '..', 'fixtures', 'packages', 'package-with-directory-provider') <ide> const packagesDirPath = path.join(process.env.ATOM_HOME, 'packages') <ide> describe('AtomApplication', function () { <ide> } <ide> }) <ide> <del> it('reopens any previously opened windows when launched with no path', async () => { <del> if (process.platform === 'win32') return // Test is too flakey on Windows <del> <del> const tempDirPath1 = makeTempDir() <del> const tempDirPath2 = makeTempDir() <del> <del> const atomApplication1 = buildAtomApplication() <del> const [app1Window1] = await atomApplication1.launch(parseCommandLine([tempDirPath1])) <del> await emitterEventPromise(app1Window1, 'window:locations-opened') <del> <del> const [app1Window2] = await atomApplication1.launch(parseCommandLine([tempDirPath2])) <del> await emitterEventPromise(app1Window2, 'window:locations-opened') <del> <del> await Promise.all([ <del> app1Window1.prepareToUnload(), <del> app1Window2.prepareToUnload() <del> ]) <del> <del> const atomApplication2 = buildAtomApplication() <del> const [app2Window1, app2Window2] = await atomApplication2.launch(parseCommandLine([])) <del> await Promise.all([ <del> emitterEventPromise(app2Window1, 'window:locations-opened'), <del> emitterEventPromise(app2Window2, 'window:locations-opened') <del> ]) <del> <del> assert.deepEqual(await getTreeViewRootDirectories(app2Window1), [tempDirPath1]) <del> assert.deepEqual(await getTreeViewRootDirectories(app2Window2), [tempDirPath2]) <del> }) <del> <ide> it('does not reopen any previously opened windows when launched with no path and `core.restorePreviousWindowsOnStart` is no', async () => { <ide> const atomApplication1 = buildAtomApplication() <ide> const [app1Window1] = await atomApplication1.launch(parseCommandLine([makeTempDir()]))
1
Javascript
Javascript
add 鉅亨財經新聞 showcase
72340161805da4a9c66a8667a68b7d65c8e806c5
<ide><path>website/src/react-native/showcase.js <ide> var apps = [ <ide> link: 'https://emberall.com/', <ide> author: 'Kyle Corbitt', <ide> }, <add> { <add> name: '鉅亨財經新聞', <add> icon: 'http://a4.mzstatic.com/us/r30/Purple18/v4/1e/b1/dd/1eb1dd6e-0d9e-03cf-22f9-1b6fd816814d/icon175x175.jpeg', <add> linkAppStore: 'https://itunes.apple.com/us/app/ju-heng-cai-jing-xin-wen/id1071014509?mt=8', <add> linkPlayStore: 'https://play.google.com/store/apps/details?id=com.cnyes.android', <add> author: '鉅亨網', <add> }, <ide> ]; <ide> <ide> var AppList = React.createClass({
1
Text
Text
create formal mda design document
e107483bafeabe57045ebc4a4b89edc3a3c8ed59
<ide><path>guide/english/game-development/mda-methodology/index.md <add>--- <add>title: MDA Methodology (mechanics, design, and aesthetics) <add>--- <add> <add>The purpose of MDA methodology is to give developers, scholars, and researchers a common foundation they can use to understand, discuss, analyze, and research games and game development. [2] <add> <add> <add>MDA methodology uses the relationship between the game designer and the player to provide a framework for the game development process. Figure 1 visualizes the relationship between game designers and players. Designers make the game and players consume the game. <add>An illustration of two figures on either side of a box representing a game. The figure on the left is the designer, and an arrow points from the designer to the game. The figure on the right is the player, and an arrow points from the player to the game. <add> <add> <add>Often, the term “fun” is used to talk about games and commercial success. An important factor for games is to evoke an aesthetic response in players. The way a player consumes a game is different than the way users consume other media. MDA breaks down the player’s consumption into three components: rules, system behavior, and fun. A game’s rules determine the system behavior, and the system behavior creates fun, or an enjoyable game experience. If you just focus on consumption, the relationship between the designer and player is represented the illustration in Figure 2. <add>An illustration of two figures on either side a row of three boxes. From left to right, the boxes represent rules, system behavior, and fun. The figure on the left next to the rules box is the designer, and the figure on the right next to the fun box is the player. <add> <add> <add>The three aspects of consumption—rules, system behavior, and fun—translate directly into design terms: Rules become mechanics, system behavior becomes dynamics, and fun becomes aesthetics. [3] You now have the three components of MDA methodology: mechanics, dynamics, and aesthetics. The terms are defines below. <add> <add> Mechanics are the rules and concepts that define the game system. <add> Dynamics are the rules when the system is running. <add> Aesthetics are the feelings the game dynamics create in the player. [4] <add> <add>To use mechanics, dynamics, and aesthetics in context, consider an example of a FPS game. The mechanics are the rules whch say you will take damage if you get hit with a bullet. Dynamics happen when a character in the game shoots at you. When you realize you’re being shot at, you experience the aesthetics of competition, survival, and fear. <add> <add>## Eight Types of Fun <add> <add>The way a game’s aesthetic impacts players’ emotions are often interpreted as “fun.” As a designer, it is helpful to break “fun” down into more specific experiences. According to MDA methodology inventor and game designer Marc LeBlanc, there are eight types of fun in games: <add> <add> Sensation: The game is pleasurable to the senses. <add> Fantasy: The game explores imaginary worlds of make-believe. <add> Narrative: The game tells a story. <add> Challenge: The game is an obstacle course. <add> Fellowship: The game provides a social framework. <add> Discovery: The game explores uncharted territory. <add> Expression: The game is an outlet for self-discovery. <add> Submission: The game is used to pass time. [5] <add> <add>Many games incorporate several types of fun. For example, charades uses fellowship, expression, and challenge. [6] Fellowship comes from the player’s team, expression is from acting out the prompt, and the prompts are the challenge. Final Fantasy uses fantasy, narrative, expression, discovery, challenge, and submission. Titan Fall uses challenge, sensation, and fantasy. <add> <add>When you design your game, think about which types of fun support your game core. <add> <add>## MDA Components as Models <add> <add>Mechanics, dynamics, and aesthetics can be used as models or lenses of interpretation. The following topics will look at mechanics, dynamics, and aesthetics as individual models. <add> <add>As you read about each model, keep in mind the following properties that indicate useful and reliable models: <add> <add> Formal: Models should be well defined. <add> Abstract: Models should be widely applicable. <add> Proven: Models should be known to work. <add> <add>Models can be used independently, or they interact with each other. When you analyze a game, it is helpful to use more than one model, because each will focus on different aspects of the game. <add> <add>## Aesthetic Models <add> <add>Aesthetic models encourage designers to think about the player experience. One of the most common mistakes novice designers make is failing to consider the player experience before designing the specifics of the game. If you identify the type of experience you want a player to have, it can help you select mechanics and dynamics that support this aesthetic model. Remember that all aspects of your game must support your game core, including your aesthetic model. <add> <add>Aesthetics can determine the success or failure of a game. For example, flight simulator games caught on in the 1990s, and developers made them more and more realistic. However, it turned out that players didn’t necessarily want all of the buttons and screens of a realistic helicopter—the experience of flying was more important. Remember that the player’s experience is critical to a game’s success. You will use the iterative process to design your game in order to make sure player feedback is integrated into the game. <add> <add>## Designing for Aesthetic Models <add> <add>As a designer, you can select an aesthetic model that supports your game core, and use it to help shape the elements of the game. For example, if your game core is about surviving a zombie apocalypse, you can decide to make the player feel fear. To make the player feel fear, you will need to develop fear aesthetics. <add> <add>To develop any type of aesthetic, think about what causes the feeling you’re trying to develop. For a fear aesthetic, you can incorporate the following elements that cause fear: <add> <add> uncertainty <add> loss of physical senses <add> sudden sounds <add> being hunted or stalked <add> being trapped <add> losing something you value <add> not getting something you want <add> loss of life. <add> <add>Keep in mind that the ability to reload a game, start over, or play something else has taken some of the impact out of the loss of life element. For example, recovering from death in World of Warcraft is as simple as resurrecting your character and finding your body. <add> <add>Next, think about ways you can incorporate the elements that cause the aesthetic you chose into the game mechanics. For the fear example, loss of physical senses is an element of fear. You can incorporate this into the game in a variety of ways: <add> <add> Give enemies the ability to turn off and on lights. <add> Use trip wires. <add> Use blinding lights. <add> Create invisible or transparent enemies. <add> Design a level with many corners. <add> Give enemies the ability to blind players temporarily. <add> <add>You should also consider how the player’s character could respond to or interact with the elements of the fear aesthetic. For example, you could give the character tools like night vision or a flashlight. These tools can be given or taken away based on the game’s rules and goals. As you select and develop each element of your aesthetic model, your game will begin to take shape. <add> <add>## Dynamic Models <add> <add>Dynamic models are used to predict gameplay by identifying feedback systems. [7] You can use feedback systems to determine if a change or action in gameplay has a positive or negative effect on the game. <add> <add>For example, if you study the dynamics of buying property and paying rent in Monopoly, you will find that it’s very difficult for players who are not in the lead to catch up and win the game. [8] The winning players make more money in each turn, which allows them to buy more property. Players with less money have to pay the richer players, which makes them less able to afford property and earn income. <add> <add>Once you identify this dynamic, you can consider ways to make the game more equitable. [9] You can find a way to help losing players catch up or create more obstacles for winning players. <add> <add>Dynamic models and aesthetic models can be related. You might want a game to make a player feel tension and drama, but testing the game reveals that the game needs more tension. You can add a game mechanic like a time limit. A time limit creates the dynamic of time pressure—the player has to act quickly to complete the task, or face consequences. The time pressure dynamic increases the tension in the game and creates a dramatic aesthetic. <add>Mechanic Models <add> <add>Remember that game mechanics are the rules of the game, and dynamics are the game’s systems in action. Game mechanics of card games include shuffling and placing bets, which lead to dynamics like bluffing. [10] In the dramatic game mentioned above, a time limit is the mechanic and the pressure created by the time limit is the dynamic. <add> <add>Since game dynamics are created from the mechanics, adjusting the mechanics also adjusts the dynamics. If you recall the Monopoly example from dynamic modes, it’s very difficult for players who are behind to catch up and possibly win. If you change a game mechanic like adding a tax on the wealthiest player, it shifts the game dynamics to make it possible for losing players to catch up to the winners. [11]
1
PHP
PHP
add doc-block for code auto-complete
57be173daca2e85964b02f50d5de2fa7c83bdbdb
<ide><path>src/Illuminate/Database/Eloquent/Builder.php <ide> use Illuminate\Database\Eloquent\Relations\Relation; <ide> use Illuminate\Database\Query\Builder as QueryBuilder; <ide> <add>/** <add> * @mixin \Illuminate\Database\Query\Builder <add> */ <ide> class Builder <ide> { <ide> /**
1
Java
Java
fix readablearray annotations
d76556543f96f4d739be3a708b8f6314bb32cc87
<ide><path>ReactAndroid/src/main/java/com/facebook/react/bridge/ReadableArray.java <ide> package com.facebook.react.bridge; <ide> <ide> import androidx.annotation.NonNull; <del>import androidx.annotation.Nullable; <ide> import java.util.ArrayList; <ide> <ide> /** <ide> public interface ReadableArray { <ide> <ide> int getInt(int index); <ide> <del> @Nullable <add> @NonNull <ide> String getString(int index); <ide> <del> @Nullable <add> @NonNull <ide> ReadableArray getArray(int index); <ide> <del> @Nullable <add> @NonNull <ide> ReadableMap getMap(int index); <ide> <ide> @NonNull <ide><path>ReactAndroid/src/main/java/com/facebook/react/bridge/ReadableNativeArray.java <ide> public int getInt(int index) { <ide> } <ide> <ide> @Override <del> public @Nullable String getString(int index) { <add> public @NonNull String getString(int index) { <ide> return (String) getLocalArray()[index]; <ide> } <ide> <ide> @Override <del> public @Nullable ReadableNativeArray getArray(int index) { <add> public @NonNull ReadableNativeArray getArray(int index) { <ide> return (ReadableNativeArray) getLocalArray()[index]; <ide> } <ide> <ide> @Override <del> public @Nullable ReadableNativeMap getMap(int index) { <add> public @NonNull ReadableNativeMap getMap(int index) { <ide> return (ReadableNativeMap) getLocalArray()[index]; <ide> } <ide>
2
Text
Text
remove broken link to section
2757260624d303313f9ae542a278c23086df4e52
<ide><path>README.md <ide> Supported operating systems are >= Android 4.1 (API 16) and >= iOS 8.0. <ide> - [Getting Help](#getting-help) <ide> - [Documentation](#documentation) <ide> - [Upgrading](#upgrading) <del>- [Opening Issues](#opening-issues) <ide> - [Contributing](#contributing) <ide> - [License](#license) <ide>
1
Javascript
Javascript
remove unreachable code
58fc172bfa9bd962fa3c614d7cbf94327af22c1e
<ide><path>lib/internal/assert/assertion_error.js <ide> class AssertionError extends Error { <ide> if (operator === 'deepEqual') { <ide> res = `${knownOperator}\n\n${res}\n\nshould loosely deep-equal\n\n`; <ide> } else { <del> const newOperator = kReadableOperator[`${operator}Unequal`]; <del> if (newOperator) { <del> const eq = operator === 'notDeepEqual' ? 'deep-equal' : 'equal'; <del> res = `${newOperator}\n\n${res}\n\nshould not loosely ${eq}\n\n`; <add> const newOp = kReadableOperator[`${operator}Unequal`]; <add> if (newOp) { <add> res = `${newOp}\n\n${res}\n\nshould not loosely deep-equal\n\n`; <ide> } else { <ide> other = ` ${operator} ${other}`; <ide> }
1
PHP
PHP
fix queuefake docblocks on queue facade
c23b0b8b11ec65cdb857044a0c2e917ed62ce8a2
<ide><path>src/Illuminate/Support/Facades/Queue.php <ide> * @method static string getConnectionName() <ide> * @method static \Illuminate\Contracts\Queue\Queue setConnectionName(string $name) <ide> * @method static void assertNothingPushed() <del> * @method static void assertNotPushed(string $job, \Closure $callback = null) <del> * @method static void assertPushed(string $job, \Closure|int $callback = null) <del> * @method static void assertPushedOn(string $job, int $times = 1) <del> * @method static void assertPushedWithChain(string $queue, string $job, \Closure $callback = null) <add> * @method static void assertNotPushed(string $job, callable $callback = null) <add> * @method static void assertPushed(string $job, callable|int $callback = null) <add> * @method static void assertPushedOn(string $queue, string $job, callable|int $callback = null) <add> * @method static void assertPushedWithChain(string $job, array $expectedChain = [], callable $callback = null) <ide> * <ide> * @see \Illuminate\Queue\QueueManager <ide> * @see \Illuminate\Queue\Queue
1
Mixed
Go
add err to tweak response status code
46e3a249a1971f8697ca338c9b02e27d36ddab12
<ide><path>docs/extend/authorization.md <ide> should implement the following two methods: <ide> **Request**: <ide> <ide> ```json <del>{ <del> "User": "The user identification" <del> "UserAuthNMethod": "The authentication method used" <del> "RequestMethod": "The HTTP method" <del> "RequestUri": "The HTTP request URI" <del> "RequestBody": "Byte array containing the raw HTTP request body" <del> "RequestHeader": "Byte array containing the raw HTTP request header as a map[string][]string " <add>{ <add> "User": "The user identification", <add> "UserAuthNMethod": "The authentication method used", <add> "RequestMethod": "The HTTP method", <add> "RequestUri": "The HTTP request URI", <add> "RequestBody": "Byte array containing the raw HTTP request body", <add> "RequestHeader": "Byte array containing the raw HTTP request header as a map[string][]string ", <ide> "RequestStatusCode": "Request status code" <ide> } <ide> ``` <ide> <ide> **Response**: <ide> <ide> ```json <del>{ <del> "Allow" : "Determined whether the user is allowed or not" <del> "Msg": "The authorization message" <add>{ <add> "Allow": "Determined whether the user is allowed or not", <add> "Msg": "The authorization message", <add> "Err": "The error message if things go wrong" <ide> } <ide> ``` <del> <ide> #### /AuthzPlugin.AuthZRes <ide> <ide> **Request**: <ide> <ide> ```json <ide> { <del> "User": "The user identification" <del> "UserAuthNMethod": "The authentication method used" <del> "RequestMethod": "The HTTP method" <del> "RequestUri": "The HTTP request URI" <del> "RequestBody": "Byte array containing the raw HTTP request body" <del> "RequestHeader": "Byte array containing the raw HTTP request header as a map[string][]string" <del> "RequestStatusCode": "Request status code" <del> "ResponseBody": "Byte array containing the raw HTTP response body" <del> "ResponseHeader": "Byte array containing the raw HTTP response header as a map[string][]string" <add> "User": "The user identification", <add> "UserAuthNMethod": "The authentication method used", <add> "RequestMethod": "The HTTP method", <add> "RequestUri": "The HTTP request URI", <add> "RequestBody": "Byte array containing the raw HTTP request body", <add> "RequestHeader": "Byte array containing the raw HTTP request header as a map[string][]string", <add> "RequestStatusCode": "Request status code", <add> "ResponseBody": "Byte array containing the raw HTTP response body", <add> "ResponseHeader": "Byte array containing the raw HTTP response header as a map[string][]string", <ide> "ResponseStatusCode":"Response status code" <ide> } <ide> ``` <ide> should implement the following two methods: <ide> <ide> ```json <ide> { <del> "Allow" : "Determined whether the user is allowed or not" <del> "Msg": "The authorization message" <del> "ModifiedBody": "Byte array containing a modified body of the raw HTTP body (or nil if no changes required)" <del> "ModifiedHeader": "Byte array containing a modified header of the HTTP response (or nil if no changes required)" <del> "ModifiedStatusCode": "int containing the modified version of the status code (or 0 if not change is required)" <add> "Allow": "Determined whether the user is allowed or not", <add> "Msg": "The authorization message", <add> "Err": "The error message if things go wrong", <add> "ModifiedBody": "Byte array containing a modified body of the raw HTTP body (or nil if no changes required)", <add> "ModifiedHeader": "Byte array containing a modified header of the HTTP response (or nil if no changes required)", <add> "ModifiedStatusCode": "int containing the modified version of the status code (or 0 if not change is required)" <ide> } <ide> ``` <ide> <ide> Request body | []byte | Raw request body <ide> Name | Type | Description <ide> --------|--------|---------------------------------------------------------------------------------- <ide> Allow | bool | Boolean value indicating whether the request is allowed or denied <del>Message | string | Authorization message (will be returned to the client in case the access is denied) <add>Msg | string | Authorization message (will be returned to the client in case the access is denied) <add>Err | string | Error message (will be returned to the client in case the plugin encounter an error) <ide> <ide> ### Response authorization <ide> <ide> Response body | []byte | Raw docker daemon response body <ide> Name | Type | Description <ide> --------|--------|---------------------------------------------------------------------------------- <ide> Allow | bool | Boolean value indicating whether the response is allowed or denied <del>Message | string | Authorization message (will be returned to the client in case the access is denied) <ide>\ No newline at end of file <add>Msg | string | Authorization message (will be returned to the client in case the access is denied) <add>Err | string | Error message (will be returned to the client in case the plugin encounter an error) <ide><path>integration-cli/docker_cli_authz_unix_test.go <ide> import ( <ide> "github.com/go-check/check" <ide> ) <ide> <del>const testAuthZPlugin = "authzplugin" <del>const unauthorizedMessage = "User unauthorized authz plugin" <del>const containerListAPI = "/containers/json" <add>const ( <add> testAuthZPlugin = "authzplugin" <add> unauthorizedMessage = "User unauthorized authz plugin" <add> errorMessage = "something went wrong..." <add> containerListAPI = "/containers/json" <add>) <ide> <ide> func init() { <ide> check.Suite(&DockerAuthzSuite{ <ide> func (s *DockerAuthzSuite) SetUpSuite(c *check.C) { <ide> }) <ide> <ide> mux.HandleFunc("/AuthZPlugin.AuthZReq", func(w http.ResponseWriter, r *http.Request) { <add> if s.ctrl.reqRes.Err != "" { <add> w.WriteHeader(http.StatusInternalServerError) <add> } <ide> b, err := json.Marshal(s.ctrl.reqRes) <del> w.Write(b) <ide> c.Assert(err, check.IsNil) <add> w.Write(b) <ide> defer r.Body.Close() <ide> body, err := ioutil.ReadAll(r.Body) <ide> c.Assert(err, check.IsNil) <ide> func (s *DockerAuthzSuite) SetUpSuite(c *check.C) { <ide> }) <ide> <ide> mux.HandleFunc("/AuthZPlugin.AuthZRes", func(w http.ResponseWriter, r *http.Request) { <add> if s.ctrl.resRes.Err != "" { <add> w.WriteHeader(http.StatusInternalServerError) <add> } <ide> b, err := json.Marshal(s.ctrl.resRes) <ide> c.Assert(err, check.IsNil) <ide> w.Write(b) <ide> func (s *DockerAuthzSuite) TestAuthZPluginDenyResponse(c *check.C) { <ide> c.Assert(res, check.Equals, fmt.Sprintf("Error response from daemon: %s\n", unauthorizedMessage)) <ide> } <ide> <add>func (s *DockerAuthzSuite) TestAuthZPluginErrorResponse(c *check.C) { <add> err := s.d.Start("--authz-plugin=" + testAuthZPlugin) <add> c.Assert(err, check.IsNil) <add> s.ctrl.reqRes.Allow = true <add> s.ctrl.resRes.Err = errorMessage <add> <add> // Ensure command is blocked <add> res, err := s.d.Cmd("ps") <add> c.Assert(err, check.NotNil) <add> <add> c.Assert(res, check.Equals, fmt.Sprintf("Error response from daemon: Plugin Error: %s, %s\n", errorMessage, authorization.AuthZApiResponse)) <add>} <add> <add>func (s *DockerAuthzSuite) TestAuthZPluginErrorRequest(c *check.C) { <add> err := s.d.Start("--authz-plugin=" + testAuthZPlugin) <add> c.Assert(err, check.IsNil) <add> s.ctrl.reqRes.Err = errorMessage <add> <add> // Ensure command is blocked <add> res, err := s.d.Cmd("ps") <add> c.Assert(err, check.NotNil) <add> <add> c.Assert(res, check.Equals, fmt.Sprintf("Error response from daemon: Plugin Error: %s, %s\n", errorMessage, authorization.AuthZApiRequest)) <add>} <add> <ide> // assertURIRecorded verifies that the given URI was sent and recorded in the authz plugin <ide> func assertURIRecorded(c *check.C, uris []string, uri string) { <ide> <ide><path>pkg/authorization/api.go <ide> type Request struct { <ide> <ide> // Response represents authZ plugin response <ide> type Response struct { <del> <ide> // Allow indicating whether the user is allowed or not <ide> Allow bool `json:"Allow"` <ide> <ide> // Msg stores the authorization message <ide> Msg string `json:"Msg,omitempty"` <add> <add> // Err stores a message in case there's an error <add> Err string `json:"Err,omitempty"` <ide> } <ide><path>pkg/authorization/authz.go <ide> func (a *Ctx) AuthZRequest(w http.ResponseWriter, r *http.Request) error { <ide> return err <ide> } <ide> <add> if authRes.Err != "" { <add> return fmt.Errorf(authRes.Err) <add> } <add> <ide> if !authRes.Allow { <ide> return fmt.Errorf(authRes.Msg) <ide> } <ide> func (a *Ctx) AuthZResponse(rm ResponseModifier, r *http.Request) error { <ide> return err <ide> } <ide> <add> if authRes.Err != "" { <add> return fmt.Errorf(authRes.Err) <add> } <add> <ide> if !authRes.Allow { <ide> return fmt.Errorf(authRes.Msg) <ide> } <ide><path>pkg/authorization/authz_test.go <ide> import ( <ide> <ide> const pluginAddress = "authzplugin.sock" <ide> <add>func TestAuthZRequestPluginError(t *testing.T) { <add> server := authZPluginTestServer{t: t} <add> go server.start() <add> defer server.stop() <add> <add> authZPlugin := createTestPlugin(t) <add> <add> request := Request{ <add> User: "user", <add> RequestBody: []byte("sample body"), <add> RequestURI: "www.authz.com", <add> RequestMethod: "GET", <add> RequestHeaders: map[string]string{"header": "value"}, <add> } <add> server.replayResponse = Response{ <add> Err: "an error", <add> } <add> <add> actualResponse, err := authZPlugin.AuthZRequest(&request) <add> if err != nil { <add> t.Fatalf("Failed to authorize request %v", err) <add> } <add> <add> if !reflect.DeepEqual(server.replayResponse, *actualResponse) { <add> t.Fatalf("Response must be equal") <add> } <add> if !reflect.DeepEqual(request, server.recordedRequest) { <add> t.Fatalf("Requests must be equal") <add> } <add>} <add> <ide> func TestAuthZRequestPlugin(t *testing.T) { <ide> server := authZPluginTestServer{t: t} <ide> go server.start()
5
Text
Text
add entry to console.timeend() changes array
fa53a654e019cb101f35fe1c23be5432040a0508
<ide><path>doc/api/console.md <ide> time is 3869ms, `console.timeEnd()` displays "3.869s". <ide> <!-- YAML <ide> added: v0.1.104 <ide> changes: <add> - version: v13.0.0 <add> pr-url: https://github.com/nodejs/node/pull/29251 <add> description: The elapsed time is diplayed with a suitable time unit. <ide> - version: v6.0.0 <ide> pr-url: https://github.com/nodejs/node/pull/5901 <ide> description: This method no longer supports multiple calls that don’t map
1
Text
Text
fix 404s to non-existent api docs
fc0b68af287e7c26a377e866ee83617aa1a8b3d5
<ide><path>docs/_posts/2013-07-23-community-roundup-5.md <ide> React.renderComponent( <ide> > * [Working With the Browser](/react/docs/working-with-the-browser.html) <ide> > * [More About Refs](/react/docs/more-about-refs.html) <ide> > * [Tooling integration](/react/docs/tooling-integration.html) <del>> * [Reference](/react/docs/core-api.html) <add>> * [Reference](/react/docs/top-level-api.html) <ide><path>docs/docs/tutorial.md <ide> var CommentBox = React.createClass({ <ide> <ide> ### Congrats! <ide> <del>You have just built a comment box in a few simple steps. Learn more about [why to use React](why-react.html), or dive into the [API reference](core-api.html) and start hacking! Good luck! <add>You have just built a comment box in a few simple steps. Learn more about [why to use React](why-react.html), or dive into the [API reference](top-level-api.html) and start hacking! Good luck!
2
Ruby
Ruby
fix typo in transaction argument. closes
598b841882cbfe1d88c55b9cc49a5a188735d0b1
<ide><path>activerecord/lib/active_record/connection_adapters/postgresql/referential_integrity.rb <ide> def disable_referential_integrity # :nodoc: <ide> end <ide> <ide> begin <del> transaction(require_new: true) do <add> transaction(requires_new: true) do <ide> execute(tables.collect { |name| "ALTER TABLE #{quote_table_name(name)} ENABLE TRIGGER ALL" }.join(";")) <ide> end <ide> rescue
1
Python
Python
add constraints and regularisation to conv2d
c9dbbe4c2cc4d0eef09322b442c0ff55962c8fe2
<ide><path>keras/layers/convolutional.py <ide> def get_config(self): <ide> class Convolution2D(Layer): <ide> def __init__(self, nb_filter, stack_size, nb_row, nb_col, <ide> init='glorot_uniform', activation='linear', weights=None, <del> image_shape=None, border_mode='valid', subsample=(1,1)): <add> image_shape=None, border_mode='valid', subsample=(1,1), <add> W_regularizer=None, b_regularizer=None, W_constraint=None, b_constraint=None): <ide> super(Convolution2D,self).__init__() <ide> <ide> self.init = initializations.get(init) <ide> def __init__(self, nb_filter, stack_size, nb_row, nb_col, <ide> <ide> self.params = [self.W, self.b] <ide> <add> self.regularizers = [W_regularizer, b_regularizer] <add> self.constraints = [W_constraint, b_constraint] <add> <ide> if weights is not None: <ide> self.set_weights(weights) <ide>
1
Ruby
Ruby
add tests for loaded pluck and pick with alias
5e2df1fc8e85355ac92e17844a7f00a44ab478c3
<ide><path>activerecord/test/cases/calculations_test.rb <ide> def test_pluck_loaded_relation_sql_fragment <ide> end <ide> end <ide> <add> def test_pluck_loaded_relation_aliased_attribute <add> companies = Company.order(:id).limit(3).load <add> <add> assert_queries(0) do <add> assert_equal ["37signals", "Summit", "Microsoft"], companies.pluck(:new_name) <add> end <add> end <add> <ide> def test_pick_one <ide> assert_equal "The First Topic", Topic.order(:id).pick(:heading) <ide> assert_no_queries do <ide> def test_pick_loaded_relation_sql_fragment <ide> end <ide> end <ide> <add> def test_pick_loaded_relation_aliased_attribute <add> companies = Company.order(:id).limit(3).load <add> <add> assert_no_queries do <add> assert_equal "37signals", companies.pick(:new_name) <add> end <add> end <add> <ide> def test_grouped_calculation_with_polymorphic_relation <ide> part = ShipPart.create!(name: "has trinket") <ide> part.trinkets.create!
1
Text
Text
update the releases notes
05a011bd6bb003628c74cd37e02859d0c0f38c97
<ide><path>guides/source/4_1_release_notes.md <ide> for detailed changes. <ide> <ide> * Exposed `MiddlewareStack#unshift` to environment configuration. ([Pull Request](https://github.com/rails/rails/pull/12479)) <ide> <add>* Add `Application#message_verifier` method to return a message verifier. ([Pull Request](https://github.com/rails/rails/pull/12995)) <ide> <ide> Action Mailer <ide> -------------
1
Javascript
Javascript
add bounce method to touchablebounce
383ea9923a46ec811b3b3a220c654c33b3414c2d
<ide><path>Libraries/Components/Touchable/TouchableBounce.js <ide> const TouchableBounce = ((createReactClass({ <ide> }).start(callback); <ide> }, <ide> <add> /** <add> * Triggers a bounce animation without invoking any callbacks. <add> */ <add> bounce: function() { <add> this.bounceTo(0.93, 0.1, 0, () => this.bounceTo(1, 0.4, 0)); <add> }, <add> <ide> /** <ide> * `Touchable.Mixin` self callbacks. The mixin will invoke these if they are <ide> * defined on your component.
1
Ruby
Ruby
fix `require_dependency` message format
d99b3848bb83e147674465a82af1c2dfcc27b9cc
<ide><path>actionview/test/actionpack/abstract/helper_test.rb <ide> def test_includes_controller_default_helper <ide> class InvalidHelpersTest < ActiveSupport::TestCase <ide> def test_controller_raise_error_about_real_require_problem <ide> e = assert_raise(LoadError) { AbstractInvalidHelpers.helper(:invalid_require) } <del> assert_equal "No such file to load -- very_invalid_file_name", e.message <add> assert_equal "No such file to load -- very_invalid_file_name.rb", e.message <ide> end <ide> <ide> def test_controller_raise_error_about_missing_helper <ide><path>activesupport/lib/active_support/dependencies.rb <ide> def require_or_load(file_name) <ide> # resolution deterministic for constants with the same relative name in <ide> # different namespaces whose evaluation would depend on load order <ide> # otherwise. <del> def require_dependency(file_name, message = "No such file to load -- %s") <add> def require_dependency(file_name, message = "No such file to load -- %s.rb") <ide> file_name = file_name.to_path if file_name.respond_to?(:to_path) <ide> unless file_name.is_a?(String) <ide> raise ArgumentError, "the file name must either be a String or implement #to_path -- you passed #{file_name.inspect}"
2
Ruby
Ruby
pass effective_deps to cxxstdlib
9c84b3799a4af58873eb41d92cb97fe288c7d333
<ide><path>Library/Homebrew/formula_installer.rb <ide> def install <ide> # This is probably accurate, but could possibly stand to be <ide> # more robust. <ide> stdlib_in_use = CxxStdlib.new(MacOS.default_cxx_stdlib, MacOS.default_compiler) <del> stdlib_in_use.check_dependencies(f, f.deps) <add> stdlib_in_use.check_dependencies(f, effective_deps) <ide> end <ide> <ide> oh1 "Installing #{Tty.green}#{f}#{Tty.reset}" if show_header
1
Text
Text
move editable region to expose selector
78430b177650c89e4a24fb4c353eb59dbd5cadc6
<ide><path>curriculum/challenges/english/14-responsive-web-design-22/learn-basic-css-by-building-a-cafe-menu/5f35e5c44359872a137bd98f.md <ide> assert(bodyBackground === `url("https://cdn.freecodecamp.org/curriculum/css-cafe <ide> ``` <ide> <ide> ```css <del>body { <ide> --fcc-editable-region-- <add>body { <ide> /* <ide> background-color: burlywood; <ide> */ <del>--fcc-editable-region-- <ide> } <add>--fcc-editable-region-- <ide> <ide> h1, h2, p { <ide> text-align: center;
1
Javascript
Javascript
add tests for process.setgroups()
77bbdfd409593dd0a1ed97eef153ac9ed8df10f7
<ide><path>test/parallel/test-process-setgroups.js <add>'use strict'; <add>require('../common'); <add>const assert = require('assert'); <add> <add>assert.throws( <add> () => { <add> process.setgroups(); <add> }, <add> { <add> code: 'ERR_INVALID_ARG_TYPE', <add> name: 'TypeError [ERR_INVALID_ARG_TYPE]', <add> message: 'The "groups" argument must be of type Array. ' + <add> 'Received type undefined' <add> } <add>); <add> <add>assert.throws( <add> () => { <add> process.setgroups([1, -1]); <add> }, <add> { <add> code: 'ERR_OUT_OF_RANGE', <add> name: 'RangeError [ERR_OUT_OF_RANGE]', <add> message: 'The value of "groups[1]" is out of range. ' + <add> 'It must be >= 0 && < 4294967296. Received -1' <add> } <add>); <add> <add>[undefined, null, true, {}, [], () => {}].forEach((val) => { <add> assert.throws( <add> () => { <add> process.setgroups([val]); <add> }, <add> { <add> code: 'ERR_INVALID_ARG_TYPE', <add> name: 'TypeError [ERR_INVALID_ARG_TYPE]', <add> message: 'The "groups[0]" argument must be ' + <add> 'one of type number or string. ' + <add> `Received type ${typeof val}` <add> } <add> ); <add>});
1
Text
Text
fix typos in posts
35e1908bb402f03772758de4bf5ee4a2b7efa0da
<ide><path>docs/_posts/2014-10-16-react-v0.12-rc1.md <ide> We have wanted to do this since before we even open sourced React. No more `/** <ide> <ide> The React specific JSX transform no longer transforms to function calls. Instead we use `React.createElement` and pass it arguments. This allows us to make optimizations and better support React as a compile target for things like Om. Read more in the [React Elements introduction](/react/blog/2014/10/14/introducting-react-elements.html). <ide> <del>The result of this change is that we will no longer support arbitrary function calls. We understand that the ability to do was was a convenient shortcut for many people but we believe the gains will be worth it. <add>The result of this change is that we will no longer support arbitrary function calls. We understand that the ability to do was a convenient shortcut for many people but we believe the gains will be worth it. <ide> <ide> <ide> ### JSX Lower-case Convention <ide><path>docs/_posts/2014-11-24-react-js-conf-updates.md <ide> stick with the originally planned format and venue on Facebook's campus. <ide> <ide> Unfortunately, this means that we can only accept a small number of the awesome <ide> conference talk proposals. In order to make sure attendees get a fair shot at <del>registering, we're going to to sell tickets in three separate first-come, <add>registering, we're going to sell tickets in three separate first-come, <ide> first-serve phases. **Tickets will cost $200 regardless of which phase they are <ide> purchased from and all proceeds will go to charity**. <ide>
2
Javascript
Javascript
apply linting fixes
f45c3d4fa51bc591ef7fc5b63cd0c35c81d47bbc
<ide><path>tools/challenge-md-parser/text-to-data.js <ide> function textToData(sectionIds) { <ide> const lines = child.value.split('\n'); <ide> if (lines.filter(Boolean).length > 0) { <ide> lines.forEach((line, index) => { <del> if (/^\s*$/.test(line)) { <add> if ((/^\s*$/).test(line)) { <ide> currentParagraph = null; <ide> } else { <ide> if (!currentParagraph || index > 0) { <ide><path>tools/scripts/createRedirects.test.js <ide> const { createRedirects } = require('./createRedirects'); <ide> const testLocations = { <ide> api: 'https://api.example.com', <ide> news: 'https://news.example.com', <del> forum: 'https://forum.example.com', <add> forum: 'https://forum.example.com' <ide> }; <ide> <ide> describe('createRedirects', () => { <ide><path>tools/scripts/ensure-env.js <ide> fs.access(migrationMapPath, err => { <ide> }) <ide> .catch(err => { <ide> console.error(err); <add> // eslint-disable-next-line <ide> process.exit(1); <ide> }); <ide> } <ide><path>tools/scripts/ensure-path-migration-map.js <ide> getChallengesForLang('english') <ide> }) <ide> .catch(err => { <ide> console.error(err); <add> // eslint-disable-next-line <ide> process.exit(1); <ide> }); <ide><path>tools/scripts/seed/seedAuthUser.js <ide> const ObjectId = require('mongodb').ObjectID; <ide> const debug = require('debug'); <ide> <ide> const log = debug('fcc:tools:seedLocalAuthUser'); <del>const { MONGOHQ_URL, LOCALE: lang } = process.env; <add>const { MONGOHQ_URL } = process.env; <ide> <ide> function handleError(err, client) { <ide> if (err) { <ide><path>tools/translation/translate-challenges.js <ide> var dir = dir1 + '/' + dir2; <ide> fs.readdirSync('../../curriculum/challenges/english/' + dir).forEach(file => { <ide> if (file.includes('.md') && dir) { <ide> let originalFileName = <del> '../../curriculum/challenges/' + langFull + '/' + dir + '/' + file.slice(0, -10) + langFull + '.md'; <add> '../../curriculum/challenges/' + <add> langFull + <add> '/' + <add> dir + <add> '/' + <add> file.slice(0, -10) + <add> langFull + <add> '.md'; <ide> <ide> fs.exists(originalFileName, function(exists) { <ide> if (!exists) { <ide> fs.readdirSync('../../curriculum/challenges/english/' + dir).forEach(file => { <ide> <ide> // Load in full text, description, instructions, and title <ide> function getFile(file, dir) { <del> let originalFileName = '../../curriculum/challenges/english/' + dir + '/' + file; <add> let originalFileName = <add> '../../curriculum/challenges/english/' + dir + '/' + file; <ide> let fileString = fs.readFileSync(originalFileName).toString(); <ide> <del> // Add 'notranslate' class to code so Google Translate API will not translate code segments. <add> // Add 'notranslate' class to code so Google Translate API <add> // will not translate code segments. <ide> fileString = fileString.replace(/<code>/g, '<code class="notranslate">'); <ide> fileString = fileString.replace( <ide> /<blockquote>/g, <ide> function processFile( <ide> ) { <ide> const translateText = (text, target) => { <ide> return new Promise((resolve, reject) => { <del> if (typeof text == 'object' && Object.keys(text).length === 0) { <add> if (typeof text === 'object' && Object.keys(text).length === 0) { <ide> resolve(['']); <ide> } else { <ide> // Imports the Google Cloud client library <ide> function processFile( <ide> }) <ide> .catch(err => { <ide> reject(console.log('!!!!!', err)); <del> if (err) { <del> } <ide> }); <ide> } <ide> }); <ide> function processFile( <ide> let testsArray = tests.split('\n'); <ide> let testsToTranslate = []; <ide> <del> testsArray.forEach((test, index) => { <add> testsArray.forEach(test => { <ide> if (test.includes('- text: ')) { <ide> testsToTranslate.push(test.slice(10)); <ide> } <ide> }); <del> translateText(testsToTranslate, lang).then(translation => { <del> let transIndex = 0; <del> testsArray.forEach((test, index) => { <del> if (test.includes('- text')) { <del> testsArray[index] = ' - text: ' + translation[transIndex]; <del> transIndex++; <del> } <del> }); <del> resolve(testsArray.join('\n')); <del> }); <add> translateText(testsToTranslate, lang) <add> .then(translation => { <add> let transIndex = 0; <add> testsArray.forEach((test, index) => { <add> if (test.includes('- text')) { <add> testsArray[index] = ' - text: ' + translation[transIndex]; <add> transIndex++; <add> } <add> }); <add> resolve(testsArray.join('\n')); <add> }) <add> .catch(reject); <ide> }); <ide> }; <ide> <ide> function processFile( <ide> /<section id='tests'>(.|\n)*?<\/section>/, <ide> translations[3] <ide> ); <del> fileString = fileString.replace(/ class=\"notranslate\"/g, ''); // remove 'notranslate' class <add> fileString = fileString.replace(/ class=\"notranslate\"/g, ''); <ide> writeFile(fileString, file, dir); <ide> }); <ide> } <ide> function writeFile(fileString, file, dir) { <ide> langFull + <ide> '.md'; <ide> fs.writeFile(fullFileName, fileString, function(err) { <del> if (err) throw err; <add> if (err) { <add> throw err; <add> } <ide> console.log('Saved!'); <ide> }); <del>} <ide>\ No newline at end of file <add>} <ide><path>tools/translation/translate-guide-old.js <ide> const stringify2 = require('remark-stringify'); <ide> const remark = require('rehype-remark'); <ide> const path = require('path'); <ide> const readDirP = require('readdirp-walk'); <del>const { <del> Translate <del> } = require('@google-cloud/translate'); <del> <add>const { Translate } = require('@google-cloud/translate'); <ide> <ide> const lang = 'es'; <ide> const langFull = 'spanish'; <ide> const htmlProcessor = unified() <ide> .use(stringify2); <ide> <ide> readDirP({ <del> root: path.resolve(__dirname, `./test`) <del> }) <del> .on('data', translateChallenge); <add> root: path.resolve(__dirname, './test') <add>}).on('data', translateChallenge); <ide> <ide> async function translateChallenge(file) { <del> const { <del> name, <del> depth, <del> path: filePath, <del> fullPath, <del> fullParentDir, <del> stat <del> } = file; <del> if (stat.isDirectory() || name === '.DS_Store' || file.depth == 1) return null; <del> <del> <add> const { name, fullPath, fullParentDir, stat } = file; <add> if (stat.isDirectory() || name === '.DS_Store' || file.depth === 1) { <add> return null; <add> } <add> <ide> const pathIndex = fullPath.indexOf('guide') + 6; <del> const outputDir = fullParentDir.substring(0, pathIndex) + `${langFull}/` + fullParentDir.substring(pathIndex + 5); <del> const outputPath = fullPath.substring(0, pathIndex) + `${langFull}/` + fullPath.substring(pathIndex + 5); <del> if (fs.existsSync(outputPath)) return null; <add> const outputDir = <add> fullParentDir.substring(0, pathIndex) + <add> `${langFull}/` + <add> fullParentDir.substring(pathIndex + 5); <add> const outputPath = <add> fullPath.substring(0, pathIndex) + <add> `${langFull}/` + <add> fullPath.substring(pathIndex + 5); <add> if (fs.existsSync(outputPath)) { <add> return null; <add> } <ide> fs.ensureDirSync(outputDir); <ide> <ide> const fileString = fs.readFileSync(fullPath).toString(); <del> var i = fileString.indexOf('---', 4) <del> const meta = fileString.substring(0, i+4) <add> var i = fileString.indexOf('---', 4); <add> const meta = fileString.substring(0, i + 4); <ide> const title = fileString.split('\n')[1].split(': ')[1]; <del> var article = fileString.substring(i+4) <del> <del> mdToHtml(article).then((htmlArticle) => { <del> htmlArticle = htmlArticle.replace(/\n/g, '<br>') <del> htmlArticle = htmlArticle.replace(/ /g, '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;') <del> htmlArticle = htmlArticle.replace(/ /g, '&nbsp;&nbsp;&nbsp;&nbsp;') <del> htmlArticle = htmlArticle.replace(/ /g, '&nbsp;&nbsp;') <add> var article = fileString.substring(i + 4); <add> <add> return mdToHtml(article).then(htmlArticle => { <add> htmlArticle = htmlArticle.replace(/\n/g, '<br>'); <add> htmlArticle = htmlArticle.replace( <add> / {8}/g, <add> '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;' <add> ); <add> htmlArticle = htmlArticle.replace(/ {4}/g, '&nbsp;&nbsp;&nbsp;&nbsp;'); <add> htmlArticle = htmlArticle.replace(/ {2}/g, '&nbsp;&nbsp;'); <ide> translate(htmlArticle, title, meta, outputPath); <del> }) <add> }); <ide> } <ide> <ide> function translate(htmlArticle, title, meta, outputPath) { <del> Promise.all([ <del> translateText(title), <del> translateText(htmlArticle) <del> ]).then(function(translations) { <del> // Replace English with translation <del> let translatedTitle = translations[0][0]; <del> let tempArticle = translations[1][0] <del> tempArticle = tempArticle.replace(/<br>/g, '\n') <del> tempArticle = tempArticle.replace(/&#39;/g, `'`) <del> <del> // tempArticle = tempArticle.replace(/language-html">/g, 'language-html">\n') <del> // tempArticle = tempArticle.replace(/<pre> <code/g, '<pre><code') <del> // tempArticle = tempArticle.replace(/<\/code> <\/pre/g, '</code></pre') <del> tempArticle = tempArticle.replace(/&nbsp;/g, ` `) <del> <del> htmlToMd(tempArticle).then((translatedArticle) => { <del> const i = meta.indexOf('---', 4); <del> let translatedFile = meta.slice(0, i) + `localeTitle: ${translatedTitle}\n` + meta.slice(i) + translatedArticle; <del> writeFile(translatedFile, outputPath); <del> }); <del> }); <del>} <add> Promise.all([translateText(title), translateText(htmlArticle)]).then(function( <add> translations <add> ) { <add> // Replace English with translation <add> let translatedTitle = translations[0][0]; <add> let tempArticle = translations[1][0]; <add> tempArticle = tempArticle.replace(/<br>/g, '\n'); <add> tempArticle = tempArticle.replace(/&#39;/g, "'"); <add> <add> // tempArticle = tempArticle.replace(/language-html">/g,'language-html">\n') <add> // tempArticle = tempArticle.replace(/<pre> <code/g, '<pre><code') <add> // tempArticle = tempArticle.replace(/<\/code> <\/pre/g, '</code></pre') <add> tempArticle = tempArticle.replace(/&nbsp;/g, ' '); <ide> <del>const createTranslateText = target => (text) => { <del> if (!text) return ''; <del> const translate = new Translate(); <del> <del> return translate <del> .translate(text, target) <del> .then(results => { <del> let translations = results[0]; <del> translations = Array.isArray(translations) ? <del> translations : [translations]; <del> return translations; <del> }) <del> .catch(err => { <del> console.log(err); <del> }); <add> htmlToMd(tempArticle).then(translatedArticle => { <add> const i = meta.indexOf('---', 4); <add> let translatedFile = <add> meta.slice(0, i) + <add> `localeTitle: ${translatedTitle}\n` + <add> meta.slice(i) + <add> translatedArticle; <add> writeFile(translatedFile, outputPath); <add> }); <add> }); <ide> } <del> <del>const translateText = createTranslateText(lang); <ide> <add>const createTranslateText = target => text => { <add> if (!text) { <add> return ''; <add> } <add> const translate = new Translate(); <add> <add> return translate <add> .translate(text, target) <add> .then(results => { <add> let translations = results[0]; <add> translations = Array.isArray(translations) <add> ? translations <add> : [translations]; <add> return translations; <add> }) <add> .catch(err => { <add> console.log(err); <add> }); <add>}; <add> <add>const translateText = createTranslateText(lang); <ide> <ide> function writeFile(fileString, outputPath) { <del> fs.writeFile(outputPath, fileString, function(err) { <del> if (err) throw err; <del> console.log('Saved:' + outputPath); <del> }); <add> fs.writeFile(outputPath, fileString, function(err) { <add> if (err) { <add> throw err; <add> } <add> console.log('Saved:' + outputPath); <add> }); <ide> } <ide> <ide> function mdToHtml(file) { <del> return new Promise((resolve, reject) => <del> mdProcessor.process(file, function(err, file) { <del> if (err) { <del> reject(err); <del> } <del> return resolve(file.contents); <del> }) <del> ); <del> }; <del> <del> function htmlToMd(file) { <del> return new Promise((resolve, reject) => <del> htmlProcessor.process(file, function(err, file) { <del> if (err) { <del> reject(err); <del> } <del> return resolve(file.contents); <del> }) <del> ); <del> }; <ide>\ No newline at end of file <add> return new Promise((resolve, reject) => <add> mdProcessor.process(file, function(err, file) { <add> if (err) { <add> reject(err); <add> } <add> return resolve(file.contents); <add> }) <add> ); <add>} <add> <add>function htmlToMd(file) { <add> return new Promise((resolve, reject) => <add> htmlProcessor.process(file, function(err, file) { <add> if (err) { <add> reject(err); <add> } <add> return resolve(file.contents); <add> }) <add> ); <add>} <ide><path>tools/translation/translate-guide.js <ide> const fs = require('fs-extra'); <del>var showdown = require('showdown'); <add>var showdown = require('showdown'); <ide> const path = require('path'); <ide> const readDirP = require('readdirp-walk'); <del>const { <del> Translate <del> } = require('@google-cloud/translate'); <add>const { Translate } = require('@google-cloud/translate'); <ide> <del>var TurndownService = require('turndown') <add>var TurndownService = require('turndown'); <ide> <del>var turndownService = new TurndownService({'codeBlockStyle': 'fenced', 'headingStyle': 'atx'}) <add>var turndownService = new TurndownService({ <add> codeBlockStyle: 'fenced', <add> headingStyle: 'atx' <add>}); <ide> <ide> const converter = new showdown.Converter(); <ide> <ide> const lang = 'pt'; <ide> const langFull = 'portuguese'; <ide> <del> <ide> readDirP({ <del> root: path.resolve(__dirname, `./english`) <del> }) <del> .on('data', translateChallenge); <add> root: path.resolve(__dirname, './english') <add>}).on('data', translateChallenge); <ide> <ide> async function translateChallenge(file) { <del> const { <del> name, <del> depth, <del> path: filePath, <del> fullPath, <del> fullParentDir, <del> stat <del> } = file; <del> if (stat.isDirectory() || name === '.DS_Store' || file.depth == 1) return null; <add> const { name, fullPath, fullParentDir, stat } = file; <add> if (stat.isDirectory() || name === '.DS_Store' || file.depth === 1) { <add> return null; <add> } <ide> <del> <ide> const pathIndex = fullPath.indexOf('guide') + 6; <del> const outputDir = fullParentDir.substring(0, pathIndex) + `${langFull}/` + fullParentDir.substring(pathIndex + 8); <del> const outputPath = fullPath.substring(0, pathIndex) + `${langFull}/` + fullPath.substring(pathIndex + 8); <del> if (fs.existsSync(outputPath)) return null; <add> const outputDir = <add> fullParentDir.substring(0, pathIndex) + <add> `${langFull}/` + <add> fullParentDir.substring(pathIndex + 8); <add> const outputPath = <add> fullPath.substring(0, pathIndex) + <add> `${langFull}/` + <add> fullPath.substring(pathIndex + 8); <add> if (fs.existsSync(outputPath)) { <add> return null; <add> } <ide> fs.ensureDirSync(outputDir); <ide> <ide> const fileString = fs.readFileSync(fullPath).toString(); <del> var i = fileString.indexOf('---', 4) <del> const meta = fileString.substring(0, i+4) <add> var i = fileString.indexOf('---', 4); <add> const meta = fileString.substring(0, i + 4); <ide> const title = fileString.split('\n')[1].split(': ')[1]; <del> var article = fileString.substring(i+4) <del> <add> var article = fileString.substring(i + 4); <add> <ide> var htmlArticle = converter.makeHtml(article); <del> htmlArticle = htmlArticle.replace(/\n/g, '<br>') <del> htmlArticle = htmlArticle.replace(/ /g, '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;') <del> htmlArticle = htmlArticle.replace(/ /g, '&nbsp;&nbsp;&nbsp;&nbsp;') <del> htmlArticle = htmlArticle.replace(/ /g, '&nbsp;&nbsp;') <del> Promise.all([ <del> translateText(title), <del> translateText(htmlArticle) <del> ]).then(function(translations) { <del> // Replace English with translation <del> let translatedTitle = translations[0][0]; <del> let tempArticle = translations[1][0] <del> tempArticle = tempArticle.replace(/<br>/g, '\n') <del> tempArticle = tempArticle.replace(/&#39;/g, `'`) <del> <del> tempArticle = tempArticle.replace(/language-html">/g, 'language-html">\n') <del> tempArticle = tempArticle.replace(/<pre> <code/g, '<pre><code') <del> tempArticle = tempArticle.replace(/<\/pre> <\/code/g, '</pre></code') <del> tempArticle = tempArticle.replace(/&nbsp;/g, ` `) <del> let translatedArticle = turndownService.turndown(tempArticle); <del> translatedArticle = translatedArticle.replace(/\n\n\`\`\`\n/g, '\n\`\`\`\n') <del> let translatedFile = meta.slice(0, i) + `localeTitle: ${translatedTitle}\n` + meta.slice(i) + translatedArticle; <add> htmlArticle = htmlArticle.replace(/\n/g, '<br>'); <add> htmlArticle = htmlArticle.replace( <add> / {8}/g, <add> '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;' <add> ); <add> htmlArticle = htmlArticle.replace(/ {4}/g, '&nbsp;&nbsp;&nbsp;&nbsp;'); <add> htmlArticle = htmlArticle.replace(/ {2}/g, '&nbsp;&nbsp;'); <add> return Promise.all([translateText(title), translateText(htmlArticle)]).then( <add> function(translations) { <add> // Replace English with translation <add> let translatedTitle = translations[0][0]; <add> let tempArticle = translations[1][0]; <add> tempArticle = tempArticle.replace(/<br>/g, '\n'); <add> tempArticle = tempArticle.replace(/&#39;/g, "'"); <ide> <del> writeFile(translatedFile, outputPath); <del> }); <add> tempArticle = tempArticle.replace( <add> /language-html">/g, <add> 'language-html">\n' <add> ); <add> tempArticle = tempArticle.replace(/<pre> <code/g, '<pre><code'); <add> tempArticle = tempArticle.replace(/<\/pre> <\/code/g, '</pre></code'); <add> tempArticle = tempArticle.replace(/&nbsp;/g, ' '); <add> let translatedArticle = turndownService.turndown(tempArticle); <add> translatedArticle = translatedArticle.replace(/\n\n\`\`\`\n/g, '\n```\n'); <add> let translatedFile = <add> meta.slice(0, i) + <add> `localeTitle: ${translatedTitle}\n` + <add> meta.slice(i) + <add> translatedArticle; <ide> <add> writeFile(translatedFile, outputPath); <add> } <add> ); <ide> } <ide> <add>const createTranslateText = target => text => { <add> if (!text) { <add> return ''; <add> } <add> const translate = new Translate(); <ide> <del>const createTranslateText = target => (text) => { <del> if (!text) return ''; <del> const translate = new Translate(); <del> <del> return translate <del> .translate(text, target) <del> .then(results => { <del> let translations = results[0]; <del> translations = Array.isArray(translations) ? <del> translations : [translations]; <del> return translations; <del> }) <del> .catch(err => { <del> console.log(err); <del> }); <del>} <del> <del>const translateText = createTranslateText(lang); <add> return translate <add> .translate(text, target) <add> .then(results => { <add> let translations = results[0]; <add> translations = Array.isArray(translations) <add> ? translations <add> : [translations]; <add> return translations; <add> }) <add> .catch(err => { <add> console.log(err); <add> }); <add>}; <ide> <add>const translateText = createTranslateText(lang); <ide> <ide> function writeFile(fileString, outputPath) { <del> fs.writeFile(outputPath, fileString, function(err) { <del> if (err) throw err; <del> console.log('Saved:' + outputPath); <del> }); <del>} <ide>\ No newline at end of file <add> fs.writeFile(outputPath, fileString, function(err) { <add> if (err) { <add> throw err; <add> } <add> console.log('Saved:' + outputPath); <add> }); <add>}
8
Javascript
Javascript
remove workarounds for ie8
27fcca9a27f9f02a730ebb0836b2b1ff0dda7412
<ide><path>src/ngSanitize/sanitize.js <ide> function htmlParser(html, handler) { <ide> } <ide> <ide> var hiddenPre=document.createElement("pre"); <del>var spaceRe = /^(\s*)([\s\S]*?)(\s*)$/; <ide> /** <ide> * decodes all entities into regular string <ide> * @param value <ide> var spaceRe = /^(\s*)([\s\S]*?)(\s*)$/; <ide> function decodeEntities(value) { <ide> if (!value) { return ''; } <ide> <del> // Note: IE8 does not preserve spaces at the start/end of innerHTML <del> // so we must capture them and reattach them afterward <del> var parts = spaceRe.exec(value); <del> var spaceBefore = parts[1]; <del> var spaceAfter = parts[3]; <del> var content = parts[2]; <del> if (content) { <del> hiddenPre.innerHTML=content.replace(/</g,"&lt;"); <del> // innerText depends on styling as it doesn't display hidden elements. <del> // Therefore, it's better to use textContent not to cause unnecessary <del> // reflows. However, IE<9 don't support textContent so the innerText <del> // fallback is necessary. <del> content = 'textContent' in hiddenPre ? <del> hiddenPre.textContent : hiddenPre.innerText; <del> } <del> return spaceBefore + content + spaceAfter; <add> hiddenPre.innerHTML = value.replace(/</g,"&lt;"); <add> // innerText depends on styling as it doesn't display hidden elements. <add> // Therefore, it's better to use textContent not to cause unnecessary reflows. <add> return hiddenPre.textContent; <ide> } <ide> <ide> /** <ide><path>test/ngSanitize/sanitizeSpec.js <ide> describe('HTML', function() { <ide> }); <ide> <ide> describe('decodeEntities', function() { <del> var handler, text, <del> origHiddenPre = window.hiddenPre; <add> var handler, text; <ide> <ide> beforeEach(function() { <ide> text = ''; <ide> describe('decodeEntities', function() { <ide> module('ngSanitize'); <ide> }); <ide> <del> afterEach(function() { <del> window.hiddenPre = origHiddenPre; <del> }); <del> <ide> it('should unescape text', function() { <ide> htmlParser('a&lt;div&gt;&amp;&lt;/div&gt;c', handler); <ide> expect(text).toEqual('a<div>&</div>c'); <ide> describe('decodeEntities', function() { <ide> htmlParser(' a&amp;b ', handler); <ide> expect(text).toEqual(' a&b '); <ide> }); <del> <del> it('should use innerText if textContent is not available (IE<9)', function() { <del> window.hiddenPre = { <del> innerText: 'INNER_TEXT' <del> }; <del> inject(function($sanitize) { <del> htmlParser('<tag>text</tag>', handler); <del> expect(text).toEqual('INNER_TEXT'); <del> }); <del> }); <del> it('should use textContent if available', function() { <del> window.hiddenPre = { <del> textContent: 'TEXT_CONTENT', <del> innerText: 'INNER_TEXT' <del> }; <del> inject(function($sanitize) { <del> htmlParser('<tag>text</tag>', handler); <del> expect(text).toEqual('TEXT_CONTENT'); <del> }); <del> }); <del> it('should use textContent even if empty', function() { <del> window.hiddenPre = { <del> textContent: '', <del> innerText: 'INNER_TEXT' <del> }; <del> inject(function($sanitize) { <del> htmlParser('<tag>text</tag>', handler); <del> expect(text).toEqual(''); <del> }); <del> }); <ide> });
2
Ruby
Ruby
remove unused require
f459245e6dbf440a3b18d25883be7ebf8fcbeb4c
<ide><path>Library/Homebrew/cmd/bottle.rb <ide> require 'cmd/versions' <ide> require 'utils/inreplace' <ide> require 'erb' <del>require 'open3' <ide> require 'extend/pathname' <ide> <ide> class BottleMerger < Formula
1
PHP
PHP
list
28d07f051131deb23b6b0c2d1c3a24d6417941b1
<ide><path>src/Illuminate/Console/Scheduling/ScheduleListCommand.php <ide> class ScheduleListCommand extends Command <ide> * <ide> * @var string <ide> */ <del> protected $signature = 'schedule:list {--timezone= : The timezone that times should be displayed in}'; <add> protected $signature = 'schedule:list <add> {--timezone= : The timezone that times should be displayed in} <add> {--next : Sort the listed tasks by their next due date} <add> '; <ide> <ide> /** <ide> * The name of the console command. <ide> class ScheduleListCommand extends Command <ide> * <ide> * @var string <ide> */ <del> protected $description = 'List the scheduled commands'; <add> protected $description = 'List all scheduled tasks'; <ide> <ide> /** <ide> * The terminal width resolver callback. <ide> public function handle(Schedule $schedule) <ide> <ide> $timezone = new DateTimeZone($this->option('timezone') ?? config('app.timezone')); <ide> <add> $events = $this->sortEvents($events, $timezone); <add> <ide> $events = $events->map(function ($event) use ($terminalWidth, $expressionSpacing, $timezone) { <ide> $expression = $this->formatCronExpression($event->expression, $expressionSpacing); <ide> <ide> public function handle(Schedule $schedule) <ide> <ide> $nextDueDateLabel = 'Next Due:'; <ide> <del> $nextDueDate = Carbon::create((new CronExpression($event->expression)) <del> ->getNextRunDate(Carbon::now()->setTimezone($event->timezone)) <del> ->setTimezone($timezone) <del> ); <add> $nextDueDate = $this->getNextDueDateForEvent($event, $timezone); <ide> <ide> $nextDueDate = $this->output->isVerbose() <ide> ? $nextDueDate->format('Y-m-d H:i:s P') <ide> private function getCronExpressionSpacing($events) <ide> return collect($rows[0] ?? [])->keys()->map(fn ($key) => $rows->max($key)); <ide> } <ide> <add> /** <add> * Sorts the events by due date if option set. <add> * <add> * @param \Illuminate\Support\Collection $events <add> * @param \DateTimeZone $timezone <add> * @return \Illuminate\Support\Collection <add> */ <add> private function sortEvents(\Illuminate\Support\Collection $events, DateTimeZone $timezone) <add> { <add> return $this->option('next') <add> ? $events->sortBy(fn ($event) => $this->getNextDueDateForEvent($event, $timezone)) <add> : $events; <add> } <add> <add> /** <add> * Get the next due date for an event. <add> * <add> * @param \Illuminate\Console\Scheduling\Event $event <add> * @param \DateTimeZone $timezone <add> * @return \Illuminate\Support\Carbon <add> */ <add> private function getNextDueDateForEvent($event, DateTimeZone $timezone) <add> { <add> return Carbon::create( <add> (new CronExpression($event->expression)) <add> ->getNextRunDate(Carbon::now()->setTimezone($event->timezone)) <add> ->setTimezone($timezone) <add> ); <add> } <add> <ide> /** <ide> * Formats the cron expression based on the spacing provided. <ide> * <ide><path>tests/Integration/Console/Scheduling/ScheduleListCommandTest.php <ide> public function testDisplaySchedule() <ide> ->expectsOutput(' * * * * * Closure at: '.$closureFilePath.':'.$closureLineNumber.' Next Due: 1 minute from now'); <ide> } <ide> <add> public function testDisplayScheduleWithSort() <add> { <add> $this->schedule->command(FooCommand::class)->quarterly(); <add> $this->schedule->command('inspire')->twiceDaily(14, 18); <add> $this->schedule->command('foobar', ['a' => 'b'])->everyMinute(); <add> $this->schedule->job(FooJob::class)->everyMinute(); <add> $this->schedule->command('inspire')->cron('0 9,17 * * *'); <add> $this->schedule->command('inspire')->cron("0 10\t* * *"); <add> <add> $this->schedule->call(fn () => '')->everyMinute(); <add> $closureLineNumber = __LINE__ - 1; <add> $closureFilePath = __FILE__; <add> <add> $this->artisan(ScheduleListCommand::class, ['--next' => true]) <add> ->assertSuccessful() <add> ->expectsOutput(' * * * * * php artisan foobar a='.ProcessUtils::escapeArgument('b').' ... Next Due: 1 minute from now') <add> ->expectsOutput(' * * * * * Illuminate\Tests\Integration\Console\Scheduling\FooJob Next Due: 1 minute from now') <add> ->expectsOutput(' * * * * * Closure at: '.$closureFilePath.':'.$closureLineNumber.' Next Due: 1 minute from now') <add> ->expectsOutput(' 0 9,17 * * * php artisan inspire ......... Next Due: 9 hours from now') <add> ->expectsOutput(' 0 10 * * * php artisan inspire ........ Next Due: 10 hours from now') <add> ->expectsOutput(' 0 14,18 * * * php artisan inspire ........ Next Due: 14 hours from now') <add> ->expectsOutput(' 0 0 1 1-12/3 * php artisan foo:command .... Next Due: 3 months from now'); <add> } <add> <ide> public function testDisplayScheduleInVerboseMode() <ide> { <ide> $this->schedule->command(FooCommand::class)->everyMinute();
2
Python
Python
pass dropout through to embed tables
fbba7c517ece539f9b1c24df4f545b56189def72
<ide><path>spacy/_ml.py <ide> def HistoryFeatures(nr_class, hist_size=8, nr_dim=8): <ide> ops = embed.ops <ide> def add_history_fwd(vectors_hists, drop=0.): <ide> vectors, hist_ids = vectors_hists <del> hist_feats, bp_hists = embed.begin_update(hist_ids) <add> hist_feats, bp_hists = embed.begin_update(hist_ids, drop=drop) <ide> outputs = ops.xp.hstack((vectors, hist_feats)) <del> mask = ops.get_dropout_mask(outputs.shape, drop) <del> if mask is not None: <del> outputs *= mask <ide> <ide> def add_history_bwd(d_outputs, sgd=None): <del> if mask is not None: <del> d_outputs *= mask <ide> d_vectors = d_outputs[:, :vectors.shape[1]] <ide> d_hists = d_outputs[:, vectors.shape[1]:] <ide> bp_hists(d_hists, sgd=sgd)
1
Go
Go
use testing.tb instead of assert.testingt
51ca8081d83a607f9931d6cdbe664c7d23b703e9
<ide><path>testutil/daemon/config.go <ide> package daemon <ide> <ide> import ( <ide> "context" <add> "testing" <ide> <ide> "github.com/docker/docker/api/types" <ide> "github.com/docker/docker/api/types/swarm" <del> "github.com/docker/docker/testutil" <ide> "gotest.tools/assert" <ide> ) <ide> <ide> // ConfigConstructor defines a swarm config constructor <ide> type ConfigConstructor func(*swarm.Config) <ide> <ide> // CreateConfig creates a config given the specified spec <del>func (d *Daemon) CreateConfig(t assert.TestingT, configSpec swarm.ConfigSpec) string { <del> if ht, ok := t.(testutil.HelperT); ok { <del> ht.Helper() <del> } <add>func (d *Daemon) CreateConfig(t testing.TB, configSpec swarm.ConfigSpec) string { <add> t.Helper() <ide> cli := d.NewClientT(t) <ide> defer cli.Close() <ide> <ide> func (d *Daemon) CreateConfig(t assert.TestingT, configSpec swarm.ConfigSpec) st <ide> } <ide> <ide> // ListConfigs returns the list of the current swarm configs <del>func (d *Daemon) ListConfigs(t assert.TestingT) []swarm.Config { <del> if ht, ok := t.(testutil.HelperT); ok { <del> ht.Helper() <del> } <add>func (d *Daemon) ListConfigs(t testing.TB) []swarm.Config { <add> t.Helper() <ide> cli := d.NewClientT(t) <ide> defer cli.Close() <ide> <ide> func (d *Daemon) ListConfigs(t assert.TestingT) []swarm.Config { <ide> } <ide> <ide> // GetConfig returns a swarm config identified by the specified id <del>func (d *Daemon) GetConfig(t assert.TestingT, id string) *swarm.Config { <del> if ht, ok := t.(testutil.HelperT); ok { <del> ht.Helper() <del> } <add>func (d *Daemon) GetConfig(t testing.TB, id string) *swarm.Config { <add> t.Helper() <ide> cli := d.NewClientT(t) <ide> defer cli.Close() <ide> <ide> func (d *Daemon) GetConfig(t assert.TestingT, id string) *swarm.Config { <ide> } <ide> <ide> // DeleteConfig removes the swarm config identified by the specified id <del>func (d *Daemon) DeleteConfig(t assert.TestingT, id string) { <del> if ht, ok := t.(testutil.HelperT); ok { <del> ht.Helper() <del> } <add>func (d *Daemon) DeleteConfig(t testing.TB, id string) { <add> t.Helper() <ide> cli := d.NewClientT(t) <ide> defer cli.Close() <ide> <ide> func (d *Daemon) DeleteConfig(t assert.TestingT, id string) { <ide> <ide> // UpdateConfig updates the swarm config identified by the specified id <ide> // Currently, only label update is supported. <del>func (d *Daemon) UpdateConfig(t assert.TestingT, id string, f ...ConfigConstructor) { <del> if ht, ok := t.(testutil.HelperT); ok { <del> ht.Helper() <del> } <add>func (d *Daemon) UpdateConfig(t testing.TB, id string, f ...ConfigConstructor) { <add> t.Helper() <ide> cli := d.NewClientT(t) <ide> defer cli.Close() <ide> <ide><path>testutil/daemon/container.go <ide> package daemon <ide> <ide> import ( <ide> "context" <add> "testing" <ide> <ide> "github.com/docker/docker/api/types" <del> "github.com/docker/docker/testutil" <ide> "gotest.tools/assert" <ide> ) <ide> <ide> // ActiveContainers returns the list of ids of the currently running containers <del>func (d *Daemon) ActiveContainers(t assert.TestingT) []string { <del> if ht, ok := t.(testutil.HelperT); ok { <del> ht.Helper() <del> } <add>func (d *Daemon) ActiveContainers(t testing.TB) []string { <add> t.Helper() <ide> cli := d.NewClientT(t) <ide> defer cli.Close() <ide> <ide> func (d *Daemon) ActiveContainers(t assert.TestingT) []string { <ide> } <ide> <ide> // FindContainerIP returns the ip of the specified container <del>func (d *Daemon) FindContainerIP(t assert.TestingT, id string) string { <del> if ht, ok := t.(testutil.HelperT); ok { <del> ht.Helper() <del> } <add>func (d *Daemon) FindContainerIP(t testing.TB, id string) string { <add> t.Helper() <ide> cli := d.NewClientT(t) <ide> defer cli.Close() <ide> <ide><path>testutil/daemon/daemon.go <ide> import ( <ide> "github.com/docker/docker/opts" <ide> "github.com/docker/docker/pkg/ioutils" <ide> "github.com/docker/docker/pkg/stringid" <del> "github.com/docker/docker/testutil" <ide> "github.com/docker/docker/testutil/request" <ide> "github.com/docker/go-connections/sockets" <ide> "github.com/docker/go-connections/tlsconfig" <ide> type logT interface { <ide> } <ide> <ide> // nopLog is a no-op implementation of logT that is used in daemons created by <del>// NewDaemon (where no testingT is available). <add>// NewDaemon (where no testing.TB is available). <ide> type nopLog struct{} <ide> <ide> func (nopLog) Logf(string, ...interface{}) {} <ide> func (d *Daemon) ReadLogFile() ([]byte, error) { <ide> } <ide> <ide> // NewClientT creates new client based on daemon's socket path <del>func (d *Daemon) NewClientT(t assert.TestingT, extraOpts ...client.Opt) *client.Client { <del> if ht, ok := t.(testutil.HelperT); ok { <del> ht.Helper() <del> } <add>func (d *Daemon) NewClientT(t testing.TB, extraOpts ...client.Opt) *client.Client { <add> t.Helper() <ide> <ide> c, err := d.NewClient(extraOpts...) <ide> assert.NilError(t, err, "cannot create daemon client") <ide> func (d *Daemon) ReloadConfig() error { <ide> } <ide> <ide> // LoadBusybox image into the daemon <del>func (d *Daemon) LoadBusybox(t assert.TestingT) { <del> if ht, ok := t.(testutil.HelperT); ok { <del> ht.Helper() <del> } <add>func (d *Daemon) LoadBusybox(t testing.TB) { <add> t.Helper() <ide> clientHost, err := client.NewClientWithOpts(client.FromEnv) <ide> assert.NilError(t, err, "failed to create client") <ide> defer clientHost.Close() <ide> func (d *Daemon) queryRootDir() (string, error) { <ide> } <ide> <ide> // Info returns the info struct for this daemon <del>func (d *Daemon) Info(t assert.TestingT) types.Info { <del> if ht, ok := t.(testutil.HelperT); ok { <del> ht.Helper() <del> } <add>func (d *Daemon) Info(t testing.TB) types.Info { <add> t.Helper() <ide> c := d.NewClientT(t) <ide> info, err := c.Info(context.Background()) <ide> assert.NilError(t, err) <ide><path>testutil/daemon/node.go <ide> package daemon <ide> import ( <ide> "context" <ide> "strings" <add> "testing" <ide> "time" <ide> <ide> "github.com/docker/docker/api/types" <ide> "github.com/docker/docker/api/types/swarm" <del> "github.com/docker/docker/testutil" <ide> "gotest.tools/assert" <ide> ) <ide> <ide> // NodeConstructor defines a swarm node constructor <ide> type NodeConstructor func(*swarm.Node) <ide> <ide> // GetNode returns a swarm node identified by the specified id <del>func (d *Daemon) GetNode(t assert.TestingT, id string, errCheck ...func(error) bool) *swarm.Node { <del> if ht, ok := t.(testutil.HelperT); ok { <del> ht.Helper() <del> } <add>func (d *Daemon) GetNode(t testing.TB, id string, errCheck ...func(error) bool) *swarm.Node { <add> t.Helper() <ide> cli := d.NewClientT(t) <ide> defer cli.Close() <ide> <ide> func (d *Daemon) GetNode(t assert.TestingT, id string, errCheck ...func(error) b <ide> } <ide> <ide> // RemoveNode removes the specified node <del>func (d *Daemon) RemoveNode(t assert.TestingT, id string, force bool) { <del> if ht, ok := t.(testutil.HelperT); ok { <del> ht.Helper() <del> } <add>func (d *Daemon) RemoveNode(t testing.TB, id string, force bool) { <add> t.Helper() <ide> cli := d.NewClientT(t) <ide> defer cli.Close() <ide> <ide> func (d *Daemon) RemoveNode(t assert.TestingT, id string, force bool) { <ide> } <ide> <ide> // UpdateNode updates a swarm node with the specified node constructor <del>func (d *Daemon) UpdateNode(t assert.TestingT, id string, f ...NodeConstructor) { <del> if ht, ok := t.(testutil.HelperT); ok { <del> ht.Helper() <del> } <add>func (d *Daemon) UpdateNode(t testing.TB, id string, f ...NodeConstructor) { <add> t.Helper() <ide> cli := d.NewClientT(t) <ide> defer cli.Close() <ide> <ide> func (d *Daemon) UpdateNode(t assert.TestingT, id string, f ...NodeConstructor) <ide> } <ide> <ide> // ListNodes returns the list of the current swarm nodes <del>func (d *Daemon) ListNodes(t assert.TestingT) []swarm.Node { <del> if ht, ok := t.(testutil.HelperT); ok { <del> ht.Helper() <del> } <add>func (d *Daemon) ListNodes(t testing.TB) []swarm.Node { <add> t.Helper() <ide> cli := d.NewClientT(t) <ide> defer cli.Close() <ide> <ide><path>testutil/daemon/plugin.go <ide> package daemon <ide> <ide> import ( <ide> "context" <add> "testing" <ide> <ide> "github.com/docker/docker/api/types" <ide> "github.com/docker/docker/client" <del> "gotest.tools/assert" <ide> "gotest.tools/poll" <ide> ) <ide> <ide> // PluginIsRunning provides a poller to check if the specified plugin is running <del>func (d *Daemon) PluginIsRunning(t assert.TestingT, name string) func(poll.LogT) poll.Result { <add>func (d *Daemon) PluginIsRunning(t testing.TB, name string) func(poll.LogT) poll.Result { <ide> return withClient(t, d, withPluginInspect(name, func(plugin *types.Plugin, t poll.LogT) poll.Result { <ide> if plugin.Enabled { <ide> return poll.Success() <ide> func (d *Daemon) PluginIsRunning(t assert.TestingT, name string) func(poll.LogT) <ide> } <ide> <ide> // PluginIsNotRunning provides a poller to check if the specified plugin is not running <del>func (d *Daemon) PluginIsNotRunning(t assert.TestingT, name string) func(poll.LogT) poll.Result { <add>func (d *Daemon) PluginIsNotRunning(t testing.TB, name string) func(poll.LogT) poll.Result { <ide> return withClient(t, d, withPluginInspect(name, func(plugin *types.Plugin, t poll.LogT) poll.Result { <ide> if !plugin.Enabled { <ide> return poll.Success() <ide> func (d *Daemon) PluginIsNotRunning(t assert.TestingT, name string) func(poll.Lo <ide> } <ide> <ide> // PluginIsNotPresent provides a poller to check if the specified plugin is not present <del>func (d *Daemon) PluginIsNotPresent(t assert.TestingT, name string) func(poll.LogT) poll.Result { <add>func (d *Daemon) PluginIsNotPresent(t testing.TB, name string) func(poll.LogT) poll.Result { <ide> return withClient(t, d, func(c client.APIClient, t poll.LogT) poll.Result { <ide> _, _, err := c.PluginInspectWithRaw(context.Background(), name) <ide> if client.IsErrNotFound(err) { <ide> func (d *Daemon) PluginIsNotPresent(t assert.TestingT, name string) func(poll.Lo <ide> } <ide> <ide> // PluginReferenceIs provides a poller to check if the specified plugin has the specified reference <del>func (d *Daemon) PluginReferenceIs(t assert.TestingT, name, expectedRef string) func(poll.LogT) poll.Result { <add>func (d *Daemon) PluginReferenceIs(t testing.TB, name, expectedRef string) func(poll.LogT) poll.Result { <ide> return withClient(t, d, withPluginInspect(name, func(plugin *types.Plugin, t poll.LogT) poll.Result { <ide> if plugin.PluginReference == expectedRef { <ide> return poll.Success() <ide> func withPluginInspect(name string, f func(*types.Plugin, poll.LogT) poll.Result <ide> <ide> } <ide> <del>func withClient(t assert.TestingT, d *Daemon, f func(client.APIClient, poll.LogT) poll.Result) func(poll.LogT) poll.Result { <add>func withClient(t testing.TB, d *Daemon, f func(client.APIClient, poll.LogT) poll.Result) func(poll.LogT) poll.Result { <ide> return func(pt poll.LogT) poll.Result { <ide> c := d.NewClientT(t) <ide> return f(c, pt) <ide><path>testutil/daemon/secret.go <ide> package daemon <ide> <ide> import ( <ide> "context" <add> "testing" <ide> <ide> "github.com/docker/docker/api/types" <ide> "github.com/docker/docker/api/types/swarm" <del> "github.com/docker/docker/testutil" <ide> "gotest.tools/assert" <ide> ) <ide> <ide> // SecretConstructor defines a swarm secret constructor <ide> type SecretConstructor func(*swarm.Secret) <ide> <ide> // CreateSecret creates a secret given the specified spec <del>func (d *Daemon) CreateSecret(t assert.TestingT, secretSpec swarm.SecretSpec) string { <del> if ht, ok := t.(testutil.HelperT); ok { <del> ht.Helper() <del> } <add>func (d *Daemon) CreateSecret(t testing.TB, secretSpec swarm.SecretSpec) string { <add> t.Helper() <ide> cli := d.NewClientT(t) <ide> defer cli.Close() <ide> <ide> func (d *Daemon) CreateSecret(t assert.TestingT, secretSpec swarm.SecretSpec) st <ide> } <ide> <ide> // ListSecrets returns the list of the current swarm secrets <del>func (d *Daemon) ListSecrets(t assert.TestingT) []swarm.Secret { <del> if ht, ok := t.(testutil.HelperT); ok { <del> ht.Helper() <del> } <add>func (d *Daemon) ListSecrets(t testing.TB) []swarm.Secret { <add> t.Helper() <ide> cli := d.NewClientT(t) <ide> defer cli.Close() <ide> <ide> func (d *Daemon) ListSecrets(t assert.TestingT) []swarm.Secret { <ide> } <ide> <ide> // GetSecret returns a swarm secret identified by the specified id <del>func (d *Daemon) GetSecret(t assert.TestingT, id string) *swarm.Secret { <del> if ht, ok := t.(testutil.HelperT); ok { <del> ht.Helper() <del> } <add>func (d *Daemon) GetSecret(t testing.TB, id string) *swarm.Secret { <add> t.Helper() <ide> cli := d.NewClientT(t) <ide> defer cli.Close() <ide> <ide> func (d *Daemon) GetSecret(t assert.TestingT, id string) *swarm.Secret { <ide> } <ide> <ide> // DeleteSecret removes the swarm secret identified by the specified id <del>func (d *Daemon) DeleteSecret(t assert.TestingT, id string) { <del> if ht, ok := t.(testutil.HelperT); ok { <del> ht.Helper() <del> } <add>func (d *Daemon) DeleteSecret(t testing.TB, id string) { <add> t.Helper() <ide> cli := d.NewClientT(t) <ide> defer cli.Close() <ide> <ide> func (d *Daemon) DeleteSecret(t assert.TestingT, id string) { <ide> <ide> // UpdateSecret updates the swarm secret identified by the specified id <ide> // Currently, only label update is supported. <del>func (d *Daemon) UpdateSecret(t assert.TestingT, id string, f ...SecretConstructor) { <del> if ht, ok := t.(testutil.HelperT); ok { <del> ht.Helper() <del> } <add>func (d *Daemon) UpdateSecret(t testing.TB, id string, f ...SecretConstructor) { <add> t.Helper() <ide> cli := d.NewClientT(t) <ide> defer cli.Close() <ide> <ide><path>testutil/daemon/service.go <ide> package daemon <ide> <ide> import ( <ide> "context" <add> "testing" <ide> "time" <ide> <ide> "github.com/docker/docker/api/types" <ide> "github.com/docker/docker/api/types/filters" <ide> "github.com/docker/docker/api/types/swarm" <del> "github.com/docker/docker/testutil" <ide> "gotest.tools/assert" <ide> ) <ide> <ide> // ServiceConstructor defines a swarm service constructor function <ide> type ServiceConstructor func(*swarm.Service) <ide> <del>func (d *Daemon) createServiceWithOptions(t assert.TestingT, opts types.ServiceCreateOptions, f ...ServiceConstructor) string { <del> if ht, ok := t.(testutil.HelperT); ok { <del> ht.Helper() <del> } <add>func (d *Daemon) createServiceWithOptions(t testing.TB, opts types.ServiceCreateOptions, f ...ServiceConstructor) string { <add> t.Helper() <ide> var service swarm.Service <ide> for _, fn := range f { <ide> fn(&service) <ide> func (d *Daemon) createServiceWithOptions(t assert.TestingT, opts types.ServiceC <ide> } <ide> <ide> // CreateService creates a swarm service given the specified service constructor <del>func (d *Daemon) CreateService(t assert.TestingT, f ...ServiceConstructor) string { <del> if ht, ok := t.(testutil.HelperT); ok { <del> ht.Helper() <del> } <add>func (d *Daemon) CreateService(t testing.TB, f ...ServiceConstructor) string { <add> t.Helper() <ide> return d.createServiceWithOptions(t, types.ServiceCreateOptions{}, f...) <ide> } <ide> <ide> // GetService returns the swarm service corresponding to the specified id <del>func (d *Daemon) GetService(t assert.TestingT, id string) *swarm.Service { <del> if ht, ok := t.(testutil.HelperT); ok { <del> ht.Helper() <del> } <add>func (d *Daemon) GetService(t testing.TB, id string) *swarm.Service { <add> t.Helper() <ide> cli := d.NewClientT(t) <ide> defer cli.Close() <ide> <ide> func (d *Daemon) GetService(t assert.TestingT, id string) *swarm.Service { <ide> } <ide> <ide> // GetServiceTasks returns the swarm tasks for the specified service <del>func (d *Daemon) GetServiceTasks(t assert.TestingT, service string, additionalFilters ...filters.KeyValuePair) []swarm.Task { <del> if ht, ok := t.(testutil.HelperT); ok { <del> ht.Helper() <del> } <add>func (d *Daemon) GetServiceTasks(t testing.TB, service string, additionalFilters ...filters.KeyValuePair) []swarm.Task { <add> t.Helper() <ide> cli := d.NewClientT(t) <ide> defer cli.Close() <ide> <ide> func (d *Daemon) GetServiceTasks(t assert.TestingT, service string, additionalFi <ide> } <ide> <ide> // UpdateService updates a swarm service with the specified service constructor <del>func (d *Daemon) UpdateService(t assert.TestingT, service *swarm.Service, f ...ServiceConstructor) { <del> if ht, ok := t.(testutil.HelperT); ok { <del> ht.Helper() <del> } <add>func (d *Daemon) UpdateService(t testing.TB, service *swarm.Service, f ...ServiceConstructor) { <add> t.Helper() <ide> cli := d.NewClientT(t) <ide> defer cli.Close() <ide> <ide> func (d *Daemon) UpdateService(t assert.TestingT, service *swarm.Service, f ...S <ide> } <ide> <ide> // RemoveService removes the specified service <del>func (d *Daemon) RemoveService(t assert.TestingT, id string) { <del> if ht, ok := t.(testutil.HelperT); ok { <del> ht.Helper() <del> } <add>func (d *Daemon) RemoveService(t testing.TB, id string) { <add> t.Helper() <ide> cli := d.NewClientT(t) <ide> defer cli.Close() <ide> <ide> func (d *Daemon) RemoveService(t assert.TestingT, id string) { <ide> } <ide> <ide> // ListServices returns the list of the current swarm services <del>func (d *Daemon) ListServices(t assert.TestingT) []swarm.Service { <del> if ht, ok := t.(testutil.HelperT); ok { <del> ht.Helper() <del> } <add>func (d *Daemon) ListServices(t testing.TB) []swarm.Service { <add> t.Helper() <ide> cli := d.NewClientT(t) <ide> defer cli.Close() <ide> <ide> func (d *Daemon) ListServices(t assert.TestingT) []swarm.Service { <ide> } <ide> <ide> // GetTask returns the swarm task identified by the specified id <del>func (d *Daemon) GetTask(t assert.TestingT, id string) swarm.Task { <del> if ht, ok := t.(testutil.HelperT); ok { <del> ht.Helper() <del> } <add>func (d *Daemon) GetTask(t testing.TB, id string) swarm.Task { <add> t.Helper() <ide> cli := d.NewClientT(t) <ide> defer cli.Close() <ide> <ide><path>testutil/daemon/swarm.go <ide> import ( <ide> "testing" <ide> <ide> "github.com/docker/docker/api/types/swarm" <del> "github.com/docker/docker/testutil" <ide> "github.com/pkg/errors" <ide> "gotest.tools/assert" <ide> ) <ide> func (d *Daemon) NodeID() string { <ide> } <ide> <ide> // SwarmInit initializes a new swarm cluster. <del>func (d *Daemon) SwarmInit(t assert.TestingT, req swarm.InitRequest) { <del> if ht, ok := t.(testutil.HelperT); ok { <del> ht.Helper() <del> } <add>func (d *Daemon) SwarmInit(t testing.TB, req swarm.InitRequest) { <add> t.Helper() <ide> if req.ListenAddr == "" { <ide> req.ListenAddr = fmt.Sprintf("%s:%d", d.swarmListenAddr, d.SwarmPort) <ide> } <ide> func (d *Daemon) SwarmInit(t assert.TestingT, req swarm.InitRequest) { <ide> } <ide> <ide> // SwarmJoin joins a daemon to an existing cluster. <del>func (d *Daemon) SwarmJoin(t assert.TestingT, req swarm.JoinRequest) { <del> if ht, ok := t.(testutil.HelperT); ok { <del> ht.Helper() <del> } <add>func (d *Daemon) SwarmJoin(t testing.TB, req swarm.JoinRequest) { <add> t.Helper() <ide> if req.ListenAddr == "" { <ide> req.ListenAddr = fmt.Sprintf("%s:%d", d.swarmListenAddr, d.SwarmPort) <ide> } <ide> func (d *Daemon) SwarmJoin(t assert.TestingT, req swarm.JoinRequest) { <ide> <ide> // SwarmLeave forces daemon to leave current cluster. <ide> // <del>// The passed in TestingT is only used to validate that the client was successfully created <add>// The passed in testing.TB is only used to validate that the client was successfully created <ide> // Some tests rely on error checking the result of the actual unlock, so allow <ide> // the error to be returned. <del>func (d *Daemon) SwarmLeave(t assert.TestingT, force bool) error { <add>func (d *Daemon) SwarmLeave(t testing.TB, force bool) error { <ide> cli := d.NewClientT(t) <ide> defer cli.Close() <ide> return cli.SwarmLeave(context.Background(), force) <ide> } <ide> <ide> // SwarmInfo returns the swarm information of the daemon <del>func (d *Daemon) SwarmInfo(t assert.TestingT) swarm.Info { <del> if ht, ok := t.(testutil.HelperT); ok { <del> ht.Helper() <del> } <add>func (d *Daemon) SwarmInfo(t testing.TB) swarm.Info { <add> t.Helper() <ide> cli := d.NewClientT(t) <ide> info, err := cli.Info(context.Background()) <ide> assert.NilError(t, err, "get swarm info") <ide> func (d *Daemon) SwarmInfo(t assert.TestingT) swarm.Info { <ide> <ide> // SwarmUnlock tries to unlock a locked swarm <ide> // <del>// The passed in TestingT is only used to validate that the client was successfully created <add>// The passed in testing.TB is only used to validate that the client was successfully created <ide> // Some tests rely on error checking the result of the actual unlock, so allow <ide> // the error to be returned. <del>func (d *Daemon) SwarmUnlock(t assert.TestingT, req swarm.UnlockRequest) error { <add>func (d *Daemon) SwarmUnlock(t testing.TB, req swarm.UnlockRequest) error { <ide> cli := d.NewClientT(t) <ide> defer cli.Close() <ide> <ide> func (d *Daemon) SwarmUnlock(t assert.TestingT, req swarm.UnlockRequest) error { <ide> } <ide> <ide> // GetSwarm returns the current swarm object <del>func (d *Daemon) GetSwarm(t assert.TestingT) swarm.Swarm { <del> if ht, ok := t.(testutil.HelperT); ok { <del> ht.Helper() <del> } <add>func (d *Daemon) GetSwarm(t testing.TB) swarm.Swarm { <add> t.Helper() <ide> cli := d.NewClientT(t) <ide> defer cli.Close() <ide> <ide> func (d *Daemon) GetSwarm(t assert.TestingT) swarm.Swarm { <ide> } <ide> <ide> // UpdateSwarm updates the current swarm object with the specified spec constructors <del>func (d *Daemon) UpdateSwarm(t assert.TestingT, f ...SpecConstructor) { <del> if ht, ok := t.(testutil.HelperT); ok { <del> ht.Helper() <del> } <add>func (d *Daemon) UpdateSwarm(t testing.TB, f ...SpecConstructor) { <add> t.Helper() <ide> cli := d.NewClientT(t) <ide> defer cli.Close() <ide> <ide> func (d *Daemon) UpdateSwarm(t assert.TestingT, f ...SpecConstructor) { <ide> } <ide> <ide> // RotateTokens update the swarm to rotate tokens <del>func (d *Daemon) RotateTokens(t assert.TestingT) { <del> if ht, ok := t.(testutil.HelperT); ok { <del> ht.Helper() <del> } <add>func (d *Daemon) RotateTokens(t testing.TB) { <add> t.Helper() <ide> cli := d.NewClientT(t) <ide> defer cli.Close() <ide> <ide> func (d *Daemon) RotateTokens(t assert.TestingT) { <ide> } <ide> <ide> // JoinTokens returns the current swarm join tokens <del>func (d *Daemon) JoinTokens(t assert.TestingT) swarm.JoinTokens { <del> if ht, ok := t.(testutil.HelperT); ok { <del> ht.Helper() <del> } <add>func (d *Daemon) JoinTokens(t testing.TB) swarm.JoinTokens { <add> t.Helper() <ide> cli := d.NewClientT(t) <ide> defer cli.Close() <ide> <ide><path>testutil/environment/clean.go <ide> import ( <ide> "context" <ide> "regexp" <ide> "strings" <add> "testing" <ide> <ide> "github.com/docker/docker/api/types" <ide> "github.com/docker/docker/api/types/filters" <ide> "github.com/docker/docker/client" <del> "github.com/docker/docker/testutil" <ide> "gotest.tools/assert" <ide> ) <ide> <ide> // Clean the environment, preserving protected objects (images, containers, ...) <ide> // and removing everything else. It's meant to run after any tests so that they don't <ide> // depend on each others. <del>func (e *Execution) Clean(t assert.TestingT) { <del> if ht, ok := t.(testutil.HelperT); ok { <del> ht.Helper() <del> } <add>func (e *Execution) Clean(t testing.TB) { <add> t.Helper() <ide> client := e.APIClient() <ide> <ide> platform := e.OSType <ide> func (e *Execution) Clean(t assert.TestingT) { <ide> } <ide> } <ide> <del>func unpauseAllContainers(t assert.TestingT, client client.ContainerAPIClient) { <del> if ht, ok := t.(testutil.HelperT); ok { <del> ht.Helper() <del> } <add>func unpauseAllContainers(t testing.TB, client client.ContainerAPIClient) { <add> t.Helper() <ide> ctx := context.Background() <ide> containers := getPausedContainers(ctx, t, client) <ide> if len(containers) > 0 { <ide> func unpauseAllContainers(t assert.TestingT, client client.ContainerAPIClient) { <ide> } <ide> } <ide> <del>func getPausedContainers(ctx context.Context, t assert.TestingT, client client.ContainerAPIClient) []types.Container { <del> if ht, ok := t.(testutil.HelperT); ok { <del> ht.Helper() <del> } <add>func getPausedContainers(ctx context.Context, t testing.TB, client client.ContainerAPIClient) []types.Container { <add> t.Helper() <ide> filter := filters.NewArgs() <ide> filter.Add("status", "paused") <ide> containers, err := client.ContainerList(ctx, types.ContainerListOptions{ <ide> func getPausedContainers(ctx context.Context, t assert.TestingT, client client.C <ide> <ide> var alreadyExists = regexp.MustCompile(`Error response from daemon: removal of container (\w+) is already in progress`) <ide> <del>func deleteAllContainers(t assert.TestingT, apiclient client.ContainerAPIClient, protectedContainers map[string]struct{}) { <del> if ht, ok := t.(testutil.HelperT); ok { <del> ht.Helper() <del> } <add>func deleteAllContainers(t testing.TB, apiclient client.ContainerAPIClient, protectedContainers map[string]struct{}) { <add> t.Helper() <ide> ctx := context.Background() <ide> containers := getAllContainers(ctx, t, apiclient) <ide> if len(containers) == 0 { <ide> func deleteAllContainers(t assert.TestingT, apiclient client.ContainerAPIClient, <ide> } <ide> } <ide> <del>func getAllContainers(ctx context.Context, t assert.TestingT, client client.ContainerAPIClient) []types.Container { <del> if ht, ok := t.(testutil.HelperT); ok { <del> ht.Helper() <del> } <add>func getAllContainers(ctx context.Context, t testing.TB, client client.ContainerAPIClient) []types.Container { <add> t.Helper() <ide> containers, err := client.ContainerList(ctx, types.ContainerListOptions{ <ide> Quiet: true, <ide> All: true, <ide> func getAllContainers(ctx context.Context, t assert.TestingT, client client.Cont <ide> return containers <ide> } <ide> <del>func deleteAllImages(t assert.TestingT, apiclient client.ImageAPIClient, protectedImages map[string]struct{}) { <del> if ht, ok := t.(testutil.HelperT); ok { <del> ht.Helper() <del> } <add>func deleteAllImages(t testing.TB, apiclient client.ImageAPIClient, protectedImages map[string]struct{}) { <add> t.Helper() <ide> images, err := apiclient.ImageList(context.Background(), types.ImageListOptions{}) <ide> assert.Check(t, err, "failed to list images") <ide> <ide> func deleteAllImages(t assert.TestingT, apiclient client.ImageAPIClient, protect <ide> } <ide> } <ide> <del>func removeImage(ctx context.Context, t assert.TestingT, apiclient client.ImageAPIClient, ref string) { <del> if ht, ok := t.(testutil.HelperT); ok { <del> ht.Helper() <del> } <add>func removeImage(ctx context.Context, t testing.TB, apiclient client.ImageAPIClient, ref string) { <add> t.Helper() <ide> _, err := apiclient.ImageRemove(ctx, ref, types.ImageRemoveOptions{ <ide> Force: true, <ide> }) <ide> func removeImage(ctx context.Context, t assert.TestingT, apiclient client.ImageA <ide> assert.Check(t, err, "failed to remove image %s", ref) <ide> } <ide> <del>func deleteAllVolumes(t assert.TestingT, c client.VolumeAPIClient, protectedVolumes map[string]struct{}) { <del> if ht, ok := t.(testutil.HelperT); ok { <del> ht.Helper() <del> } <add>func deleteAllVolumes(t testing.TB, c client.VolumeAPIClient, protectedVolumes map[string]struct{}) { <add> t.Helper() <ide> volumes, err := c.VolumeList(context.Background(), filters.Args{}) <ide> assert.Check(t, err, "failed to list volumes") <ide> <ide> func deleteAllVolumes(t assert.TestingT, c client.VolumeAPIClient, protectedVolu <ide> } <ide> } <ide> <del>func deleteAllNetworks(t assert.TestingT, c client.NetworkAPIClient, daemonPlatform string, protectedNetworks map[string]struct{}) { <del> if ht, ok := t.(testutil.HelperT); ok { <del> ht.Helper() <del> } <add>func deleteAllNetworks(t testing.TB, c client.NetworkAPIClient, daemonPlatform string, protectedNetworks map[string]struct{}) { <add> t.Helper() <ide> networks, err := c.NetworkList(context.Background(), types.NetworkListOptions{}) <ide> assert.Check(t, err, "failed to list networks") <ide> <ide> func deleteAllNetworks(t assert.TestingT, c client.NetworkAPIClient, daemonPlatf <ide> } <ide> } <ide> <del>func deleteAllPlugins(t assert.TestingT, c client.PluginAPIClient, protectedPlugins map[string]struct{}) { <del> if ht, ok := t.(testutil.HelperT); ok { <del> ht.Helper() <del> } <add>func deleteAllPlugins(t testing.TB, c client.PluginAPIClient, protectedPlugins map[string]struct{}) { <add> t.Helper() <ide> plugins, err := c.PluginList(context.Background(), filters.Args{}) <ide> // Docker EE does not allow cluster-wide plugin management. <ide> if client.IsErrNotImplemented(err) { <ide><path>testutil/environment/environment.go <ide> import ( <ide> "os" <ide> "path/filepath" <ide> "strings" <add> "testing" <ide> <ide> "github.com/docker/docker/api/types" <ide> "github.com/docker/docker/api/types/filters" <ide> "github.com/docker/docker/client" <del> "github.com/docker/docker/testutil" <ide> "github.com/docker/docker/testutil/fixtures/load" <ide> "github.com/pkg/errors" <ide> "gotest.tools/assert" <ide> func (e *Execution) IsUserNamespace() bool { <ide> // HasExistingImage checks whether there is an image with the given reference. <ide> // Note that this is done by filtering and then checking whether there were any <ide> // results -- so ambiguous references might result in false-positives. <del>func (e *Execution) HasExistingImage(t assert.TestingT, reference string) bool { <del> if ht, ok := t.(testutil.HelperT); ok { <del> ht.Helper() <del> } <add>func (e *Execution) HasExistingImage(t testing.TB, reference string) bool { <ide> client := e.APIClient() <ide> filter := filters.NewArgs() <ide> filter.Add("dangling", "false") <ide><path>testutil/environment/protect.go <ide> package environment <ide> <ide> import ( <ide> "context" <add> "testing" <ide> <ide> "github.com/docker/docker/api/types" <ide> "github.com/docker/docker/api/types/filters" <ide> dclient "github.com/docker/docker/client" <del> "github.com/docker/docker/testutil" <ide> "gotest.tools/assert" <ide> ) <ide> <ide> func newProtectedElements() protectedElements { <ide> // ProtectAll protects the existing environment (containers, images, networks, <ide> // volumes, and, on Linux, plugins) from being cleaned up at the end of test <ide> // runs <del>func ProtectAll(t assert.TestingT, testEnv *Execution) { <del> if ht, ok := t.(testutil.HelperT); ok { <del> ht.Helper() <del> } <add>func ProtectAll(t testing.TB, testEnv *Execution) { <add> t.Helper() <ide> ProtectContainers(t, testEnv) <ide> ProtectImages(t, testEnv) <ide> ProtectNetworks(t, testEnv) <ide> func ProtectAll(t assert.TestingT, testEnv *Execution) { <ide> <ide> // ProtectContainer adds the specified container(s) to be protected in case of <ide> // clean <del>func (e *Execution) ProtectContainer(t assert.TestingT, containers ...string) { <del> if ht, ok := t.(testutil.HelperT); ok { <del> ht.Helper() <del> } <add>func (e *Execution) ProtectContainer(t testing.TB, containers ...string) { <add> t.Helper() <ide> for _, container := range containers { <ide> e.protectedElements.containers[container] = struct{}{} <ide> } <ide> } <ide> <ide> // ProtectContainers protects existing containers from being cleaned up at the <ide> // end of test runs <del>func ProtectContainers(t assert.TestingT, testEnv *Execution) { <del> if ht, ok := t.(testutil.HelperT); ok { <del> ht.Helper() <del> } <add>func ProtectContainers(t testing.TB, testEnv *Execution) { <add> t.Helper() <ide> containers := getExistingContainers(t, testEnv) <ide> testEnv.ProtectContainer(t, containers...) <ide> } <ide> <del>func getExistingContainers(t assert.TestingT, testEnv *Execution) []string { <del> if ht, ok := t.(testutil.HelperT); ok { <del> ht.Helper() <del> } <add>func getExistingContainers(t testing.TB, testEnv *Execution) []string { <add> t.Helper() <ide> client := testEnv.APIClient() <ide> containerList, err := client.ContainerList(context.Background(), types.ContainerListOptions{ <ide> All: true, <ide> func getExistingContainers(t assert.TestingT, testEnv *Execution) []string { <ide> } <ide> <ide> // ProtectImage adds the specified image(s) to be protected in case of clean <del>func (e *Execution) ProtectImage(t assert.TestingT, images ...string) { <del> if ht, ok := t.(testutil.HelperT); ok { <del> ht.Helper() <del> } <add>func (e *Execution) ProtectImage(t testing.TB, images ...string) { <add> t.Helper() <ide> for _, image := range images { <ide> e.protectedElements.images[image] = struct{}{} <ide> } <ide> } <ide> <ide> // ProtectImages protects existing images and on linux frozen images from being <ide> // cleaned up at the end of test runs <del>func ProtectImages(t assert.TestingT, testEnv *Execution) { <del> if ht, ok := t.(testutil.HelperT); ok { <del> ht.Helper() <del> } <add>func ProtectImages(t testing.TB, testEnv *Execution) { <add> t.Helper() <ide> images := getExistingImages(t, testEnv) <ide> <ide> if testEnv.OSType == "linux" { <ide> func ProtectImages(t assert.TestingT, testEnv *Execution) { <ide> testEnv.ProtectImage(t, images...) <ide> } <ide> <del>func getExistingImages(t assert.TestingT, testEnv *Execution) []string { <del> if ht, ok := t.(testutil.HelperT); ok { <del> ht.Helper() <del> } <add>func getExistingImages(t testing.TB, testEnv *Execution) []string { <add> t.Helper() <ide> client := testEnv.APIClient() <ide> filter := filters.NewArgs() <ide> filter.Add("dangling", "false") <ide> func tagsFromImageSummary(image types.ImageSummary) []string { <ide> <ide> // ProtectNetwork adds the specified network(s) to be protected in case of <ide> // clean <del>func (e *Execution) ProtectNetwork(t assert.TestingT, networks ...string) { <del> if ht, ok := t.(testutil.HelperT); ok { <del> ht.Helper() <del> } <add>func (e *Execution) ProtectNetwork(t testing.TB, networks ...string) { <add> t.Helper() <ide> for _, network := range networks { <ide> e.protectedElements.networks[network] = struct{}{} <ide> } <ide> } <ide> <ide> // ProtectNetworks protects existing networks from being cleaned up at the end <ide> // of test runs <del>func ProtectNetworks(t assert.TestingT, testEnv *Execution) { <del> if ht, ok := t.(testutil.HelperT); ok { <del> ht.Helper() <del> } <add>func ProtectNetworks(t testing.TB, testEnv *Execution) { <add> t.Helper() <ide> networks := getExistingNetworks(t, testEnv) <ide> testEnv.ProtectNetwork(t, networks...) <ide> } <ide> <del>func getExistingNetworks(t assert.TestingT, testEnv *Execution) []string { <del> if ht, ok := t.(testutil.HelperT); ok { <del> ht.Helper() <del> } <add>func getExistingNetworks(t testing.TB, testEnv *Execution) []string { <add> t.Helper() <ide> client := testEnv.APIClient() <ide> networkList, err := client.NetworkList(context.Background(), types.NetworkListOptions{}) <ide> assert.NilError(t, err, "failed to list networks") <ide> func getExistingNetworks(t assert.TestingT, testEnv *Execution) []string { <ide> } <ide> <ide> // ProtectPlugin adds the specified plugin(s) to be protected in case of clean <del>func (e *Execution) ProtectPlugin(t assert.TestingT, plugins ...string) { <del> if ht, ok := t.(testutil.HelperT); ok { <del> ht.Helper() <del> } <add>func (e *Execution) ProtectPlugin(t testing.TB, plugins ...string) { <add> t.Helper() <ide> for _, plugin := range plugins { <ide> e.protectedElements.plugins[plugin] = struct{}{} <ide> } <ide> } <ide> <ide> // ProtectPlugins protects existing plugins from being cleaned up at the end of <ide> // test runs <del>func ProtectPlugins(t assert.TestingT, testEnv *Execution) { <del> if ht, ok := t.(testutil.HelperT); ok { <del> ht.Helper() <del> } <add>func ProtectPlugins(t testing.TB, testEnv *Execution) { <add> t.Helper() <ide> plugins := getExistingPlugins(t, testEnv) <ide> testEnv.ProtectPlugin(t, plugins...) <ide> } <ide> <del>func getExistingPlugins(t assert.TestingT, testEnv *Execution) []string { <del> if ht, ok := t.(testutil.HelperT); ok { <del> ht.Helper() <del> } <add>func getExistingPlugins(t testing.TB, testEnv *Execution) []string { <add> t.Helper() <ide> client := testEnv.APIClient() <ide> pluginList, err := client.PluginList(context.Background(), filters.Args{}) <ide> // Docker EE does not allow cluster-wide plugin management. <ide> func getExistingPlugins(t assert.TestingT, testEnv *Execution) []string { <ide> } <ide> <ide> // ProtectVolume adds the specified volume(s) to be protected in case of clean <del>func (e *Execution) ProtectVolume(t assert.TestingT, volumes ...string) { <del> if ht, ok := t.(testutil.HelperT); ok { <del> ht.Helper() <del> } <add>func (e *Execution) ProtectVolume(t testing.TB, volumes ...string) { <add> t.Helper() <ide> for _, volume := range volumes { <ide> e.protectedElements.volumes[volume] = struct{}{} <ide> } <ide> } <ide> <ide> // ProtectVolumes protects existing volumes from being cleaned up at the end of <ide> // test runs <del>func ProtectVolumes(t assert.TestingT, testEnv *Execution) { <del> if ht, ok := t.(testutil.HelperT); ok { <del> ht.Helper() <del> } <add>func ProtectVolumes(t testing.TB, testEnv *Execution) { <add> t.Helper() <ide> volumes := getExistingVolumes(t, testEnv) <ide> testEnv.ProtectVolume(t, volumes...) <ide> } <ide> <del>func getExistingVolumes(t assert.TestingT, testEnv *Execution) []string { <del> if ht, ok := t.(testutil.HelperT); ok { <del> ht.Helper() <del> } <add>func getExistingVolumes(t testing.TB, testEnv *Execution) []string { <add> t.Helper() <ide> client := testEnv.APIClient() <ide> volumeList, err := client.VolumeList(context.Background(), filters.Args{}) <ide> assert.NilError(t, err, "failed to list volumes") <ide><path>testutil/registry/registry.go <ide> import ( <ide> "testing" <ide> "time" <ide> <del> "github.com/docker/docker/testutil" <del> digest "github.com/opencontainers/go-digest" <add> "github.com/opencontainers/go-digest" <ide> "gotest.tools/assert" <ide> ) <ide> <ide> func (r *V2) getBlobFilename(blobDigest digest.Digest) string { <ide> } <ide> <ide> // ReadBlobContents read the file corresponding to the specified digest <del>func (r *V2) ReadBlobContents(t assert.TestingT, blobDigest digest.Digest) []byte { <del> if ht, ok := t.(testutil.HelperT); ok { <del> ht.Helper() <del> } <add>func (r *V2) ReadBlobContents(t testing.TB, blobDigest digest.Digest) []byte { <add> t.Helper() <ide> // Load the target manifest blob. <ide> manifestBlob, err := ioutil.ReadFile(r.getBlobFilename(blobDigest)) <ide> assert.NilError(t, err, "unable to read blob") <ide> return manifestBlob <ide> } <ide> <ide> // WriteBlobContents write the file corresponding to the specified digest with the given content <del>func (r *V2) WriteBlobContents(t assert.TestingT, blobDigest digest.Digest, data []byte) { <del> if ht, ok := t.(testutil.HelperT); ok { <del> ht.Helper() <del> } <add>func (r *V2) WriteBlobContents(t testing.TB, blobDigest digest.Digest, data []byte) { <add> t.Helper() <ide> err := ioutil.WriteFile(r.getBlobFilename(blobDigest), data, os.FileMode(0644)) <ide> assert.NilError(t, err, "unable to write malicious data blob") <ide> } <ide><path>testutil/request/request.go <ide> import ( <ide> "net/url" <ide> "os" <ide> "path/filepath" <add> "testing" <ide> "time" <ide> <ide> "github.com/docker/docker/client" <ide> "github.com/docker/docker/opts" <ide> "github.com/docker/docker/pkg/ioutils" <del> "github.com/docker/docker/testutil" <ide> "github.com/docker/docker/testutil/environment" <ide> "github.com/docker/go-connections/sockets" <ide> "github.com/docker/go-connections/tlsconfig" <ide> import ( <ide> ) <ide> <ide> // NewAPIClient returns a docker API client configured from environment variables <del>func NewAPIClient(t assert.TestingT, ops ...client.Opt) client.APIClient { <del> if ht, ok := t.(testutil.HelperT); ok { <del> ht.Helper() <del> } <add>func NewAPIClient(t testing.TB, ops ...client.Opt) client.APIClient { <add> t.Helper() <ide> ops = append([]client.Opt{client.FromEnv}, ops...) <ide> clt, err := client.NewClientWithOpts(ops...) <ide> assert.NilError(t, err) <ide> return clt <ide> } <ide> <ide> // DaemonTime provides the current time on the daemon host <del>func DaemonTime(ctx context.Context, t assert.TestingT, client client.APIClient, testEnv *environment.Execution) time.Time { <del> if ht, ok := t.(testutil.HelperT); ok { <del> ht.Helper() <del> } <add>func DaemonTime(ctx context.Context, t testing.TB, client client.APIClient, testEnv *environment.Execution) time.Time { <add> t.Helper() <ide> if testEnv.IsLocalDaemon() { <ide> return time.Now() <ide> } <ide> func DaemonTime(ctx context.Context, t assert.TestingT, client client.APIClient, <ide> <ide> // DaemonUnixTime returns the current time on the daemon host with nanoseconds precision. <ide> // It return the time formatted how the client sends timestamps to the server. <del>func DaemonUnixTime(ctx context.Context, t assert.TestingT, client client.APIClient, testEnv *environment.Execution) string { <del> if ht, ok := t.(testutil.HelperT); ok { <del> ht.Helper() <del> } <add>func DaemonUnixTime(ctx context.Context, t testing.TB, client client.APIClient, testEnv *environment.Execution) string { <add> t.Helper() <ide> dt := DaemonTime(ctx, t, client, testEnv) <ide> return fmt.Sprintf("%d.%09d", dt.Unix(), int64(dt.Nanosecond())) <ide> }
13
Ruby
Ruby
remove code that only worked by accident
92ac63fd9495e4fc75195191c36d5acebb8a6107
<ide><path>Library/Homebrew/requirements/language_module_dependency.rb <ide> def the_test <ide> when :jruby then %W{/usr/bin/env jruby -rubygems -e require\ '#{@import_name}'} <ide> when :lua then %W{/usr/bin/env luarocks show #{@import_name}} <ide> when :node then %W{/usr/bin/env node -e require('#{@import_name}');} <del> when :ocaml then %W{/usr/bin/env opam list #{@import_name} | grep #{@import_name}} <add> when :ocaml then %W{/usr/bin/env opam list #{@import_name}} <ide> when :perl then %W{/usr/bin/env perl -e use\ #{@import_name}} <ide> when :python then %W{/usr/bin/env python -c import\ #{@import_name}} <ide> when :python3 then %W{/usr/bin/env python3 -c import\ #{@import_name}}
1
Ruby
Ruby
fix the method name for recusion
141d3aff2f010384cc5d3488f75605bd0f702416
<ide><path>activerecord/lib/active_record/relation/predicate_builder.rb <ide> def build_from_hash(attributes, default_table) <ide> <ide> if value.is_a?(Hash) <ide> arel_table = Arel::Table.new(column, @engine) <del> build_predicate_from_hash(value, arel_table) <add> build_from_hash(value, arel_table) <ide> else <ide> column = column.to_s <ide>
1
Javascript
Javascript
preserve the process.env magic for windows
9b8cb237574bcec33101260334175622d5535d61
<ide><path>src/environment-helpers.js <ide> function needsPatching (options = { platform: process.platform, env: process.env <ide> return false <ide> } <ide> <add>// Fix for #11302 because `process.env` on Windows is a magic object that offers case-insensitive <add>// environment variable matching. <add>function cloneEnv (env) { <add> for (var key in process.env) { <add> delete process.env[key] <add> } <add> <add> Object.assign(process.env, env) <add>} <add> <ide> function normalize (options = {}) { <ide> if (options && options.env) { <del> process.env = options.env <add> cloneEnv(options.env) <ide> } <ide> <ide> if (!options.env) { <ide> function normalize (options = {}) { <ide> // in #4126. Retain the original in case someone needs it. <ide> let shellEnv = getFromShell() <ide> if (shellEnv && shellEnv.PATH) { <del> process._originalEnv = process.env <del> process.env = shellEnv <add> process._originalEnv = Object.assign({}, process.env) <add> cloneEnv(shellEnv) <ide> } <ide> } <ide> } <ide> function replace (env) { <ide> return <ide> } <ide> <del> process.env = env <add> cloneEnv(env) <ide> } <ide> <ide> export default { getFromShell, needsPatching, normalize, replace }
1
PHP
PHP
add empty option support
013b62c38e127ce7eb16674469d6ee34759270e1
<ide><path>Cake/View/Input/SelectBox.php <ide> public function render($data) { <ide> <ide> protected function _renderOptions($data) { <ide> $out = []; <add> if (!isset($data['options'])) { <add> $data['options'] = []; <add> } <add> $options = $data['options']; <add> <ide> if (!empty($data['empty'])) { <del> // TODO <add> $value = $data['empty'] === true ? '' : $data['empty']; <add> $empty = ['' => $value]; <add> $options = $empty + $options; <ide> } <del> if (empty($data['options'])) { <add> if (empty($options)) { <ide> return $out; <ide> } <ide> <ide> $selected = isset($data['value']) ? $data['value'] : null; <ide> $selectedArray = is_array($selected); <ide> <del> foreach ($data['options'] as $key => $val) { <add> foreach ($options as $key => $val) { <ide> $template = 'option'; <ide> $strict = !is_numeric($key); <ide> <ide><path>Test/TestCase/View/Input/SelectBoxTest.php <ide> public function testRenderSimple() { <ide> * @return void <ide> */ <ide> public function testRenderSelected() { <del> $this->markTestIncomplete('Not done'); <add> $context = new Context(); <add> $select = new SelectBox($this->templates, $context); <add> $data = [ <add> 'id' => 'BirdName', <add> 'name' => 'Birds[name]', <add> 'value' => '1', <add> 'options' => [ <add> 1 => 'one', <add> '1x' => 'one x', <add> '2' => 'two', <add> '2x' => 'two x', <add> ] <add> ]; <add> $result = $select->render($data); <add> $expected = [ <add> 'select' => ['name' => 'Birds[name]', 'id' => 'BirdName'], <add> ['option' => ['value' => '1', 'selected' => 'selected']], 'one', '/option', <add> ['option' => ['value' => '1x']], 'one x', '/option', <add> ['option' => ['value' => '2']], 'two', '/option', <add> ['option' => ['value' => '2x']], 'two x', '/option', <add> '/select' <add> ]; <add> $this->assertTags($result, $expected); <add> <add> $data['value'] = 2; <add> $result = $select->render($data); <add> $expected = [ <add> 'select' => ['name' => 'Birds[name]', 'id' => 'BirdName'], <add> ['option' => ['value' => '1']], 'one', '/option', <add> ['option' => ['value' => '1x']], 'one x', '/option', <add> ['option' => ['value' => '2', 'selected' => 'selected']], 'two', '/option', <add> ['option' => ['value' => '2x']], 'two x', '/option', <add> '/select' <add> ]; <add> $this->assertTags($result, $expected); <ide> } <ide> <ide> /** <ide> public function testRenderDisabled() { <ide> * @return void <ide> */ <ide> public function testRenderEmptyOption() { <del> $this->markTestIncomplete('Not done'); <add> $select = new SelectBox($this->templates, $context); <add> $data = [ <add> 'id' => 'BirdName', <add> 'name' => 'Birds[name]', <add> 'empty' => true, <add> 'options' => ['a' => 'Albatross', 'b' => 'Budgie'] <add> ]; <add> $result = $select->render($data); <add> $expected = [ <add> 'select' => ['name' => 'Birds[name]', 'id' => 'BirdName'], <add> ['option' => ['value' => '']], '/option', <add> ['option' => ['value' => 'a']], 'Albatross', '/option', <add> ['option' => ['value' => 'b']], 'Budgie', '/option', <add> '/select' <add> ]; <add> $this->assertTags($result, $expected); <add> <add> $data['empty'] = 'empty'; <add> $result = $select->render($data); <add> $expected = [ <add> 'select' => ['name' => 'Birds[name]', 'id' => 'BirdName'], <add> ['option' => ['value' => '']], 'empty', '/option', <add> ['option' => ['value' => 'a']], 'Albatross', '/option', <add> ['option' => ['value' => 'b']], 'Budgie', '/option', <add> '/select' <add> ]; <add> $this->assertTags($result, $expected); <add> <add> $data['empty'] = 'empty'; <add> $data['value'] = ''; <add> $result = $select->render($data); <add> $expected = [ <add> 'select' => ['name' => 'Birds[name]', 'id' => 'BirdName'], <add> ['option' => ['value' => '', 'selected' => 'selected']], 'empty', '/option', <add> ['option' => ['value' => 'a']], 'Albatross', '/option', <add> ['option' => ['value' => 'b']], 'Budgie', '/option', <add> '/select' <add> ]; <add> $this->assertTags($result, $expected); <ide> } <ide> <ide> }
2
Javascript
Javascript
pass port when running on device (fix )
f8fee0a631d77313d7cb5e65a3dd04a5a8ba3d03
<ide><path>local-cli/runIOS/runIOS.js <ide> function runIOS(argv, config, args) { <ide> if (args.device) { <ide> const selectedDevice = matchingDevice(devices, args.device); <ide> if (selectedDevice) { <del> return runOnDevice(selectedDevice, scheme, xcodeProject, args.configuration, args.packager, args.verbose); <add> return runOnDevice(selectedDevice, scheme, xcodeProject, args.configuration, args.packager, args.verbose, args.port); <ide> } else { <ide> if (devices && devices.length > 0) { <ide> console.log('Could not find device with the name: "' + args.device + '".');
1
Javascript
Javascript
fix eager cause of '(unknown mixin)'
d607cdc3956a0824566d6871fdde65d08beff009
<ide><path>packages/ember-metal/lib/meta.js <del>import { <del> lookupDescriptor, <del> symbol, <del> toString <del>} from 'ember-utils'; <add>import { lookupDescriptor, symbol, toString } from 'ember-utils'; <ide> import { protoMethods as listenerMethods } from './meta_listeners'; <ide> import { assert } from 'ember-debug'; <ide> import { DEBUG } from 'ember-env-flags'; <del>import { DESCRIPTOR_TRAP, EMBER_METAL_ES5_GETTERS, MANDATORY_SETTER } from 'ember/features'; <ide> import { <del> removeChainWatcher <del>} from './chains'; <add> DESCRIPTOR_TRAP, <add> EMBER_METAL_ES5_GETTERS, <add> MANDATORY_SETTER <add>} from 'ember/features'; <add>import { removeChainWatcher } from './chains'; <ide> import { ENV } from 'ember-environment'; <ide> <ide> let counters; <ide> export class Meta { <ide> } <ide> <ide> destroy() { <del> if (this.isMetaDestroyed()) { return; } <add> if (this.isMetaDestroyed()) { <add> return; <add> } <ide> <ide> // remove chainWatchers to remove circular references that would prevent GC <ide> let nodes, key, nodeObject; <ide> export class Meta { <ide> } <ide> pointer = pointer.parent; <ide> } <del>} <add> } <ide> <ide> _hasInInheritedSet(key, value) { <ide> let pointer = this; <ide> export class Meta { <ide> // Implements a member that provides a lazily created map of maps, <ide> // with inheritance at both levels. <ide> writeDeps(subkey, itemkey, value) { <del> assert(`Cannot modify dependent keys for \`${itemkey}\` on \`${toString(this.source)}\` after it has been destroyed.`, !this.isMetaDestroyed()); <add> assert( <add> this.isMetaDestroyed() && <add> `Cannot modify dependent keys for \`${itemkey}\` on \`${toString( <add> this.source <add> )}\` after it has been destroyed.`, <add> !this.isMetaDestroyed() <add> ); <ide> <ide> let outerMap = this._getOrCreateOwnMap('_deps'); <ide> let innerMap = outerMap[subkey]; <ide> export class Meta { <ide> } <ide> <ide> if (calls !== undefined) { <del> for (let i = 0; i < calls.length; i+=2) { <add> for (let i = 0; i < calls.length; i += 2) { <ide> fn(calls[i], calls[i + 1]); <ide> } <ide> } <ide> } <ide> <del> writableTags() { return this._getOrCreateOwnMap('_tags'); } <del> readableTags() { return this._tags; } <add> writableTags() { <add> return this._getOrCreateOwnMap('_tags'); <add> } <add> readableTags() { <add> return this._tags; <add> } <ide> <ide> writableTag(create) { <del> assert(`Cannot create a new tag for \`${toString(this.source)}\` after it has been destroyed.`, !this.isMetaDestroyed()); <add> assert( <add> this.isMetaDestroyed() && <add> `Cannot create a new tag for \`${toString( <add> this.source <add> )}\` after it has been destroyed.`, <add> !this.isMetaDestroyed() <add> ); <ide> let ret = this._tag; <ide> if (ret === undefined) { <ide> ret = this._tag = create(this.source); <ide> export class Meta { <ide> } <ide> <ide> writableChainWatchers(create) { <del> assert(`Cannot create a new chain watcher for \`${toString(this.source)}\` after it has been destroyed.`, !this.isMetaDestroyed()); <add> assert( <add> this.isMetaDestroyed() && <add> `Cannot create a new chain watcher for \`${toString( <add> this.source <add> )}\` after it has been destroyed.`, <add> !this.isMetaDestroyed() <add> ); <ide> let ret = this._chainWatchers; <ide> if (ret === undefined) { <ide> ret = this._chainWatchers = create(this.source); <ide> export class Meta { <ide> } <ide> <ide> writableChains(create) { <del> assert(`Cannot create a new chains for \`${toString(this.source)}\` after it has been destroyed.`, !this.isMetaDestroyed()); <add> assert( <add> this.isMetaDestroyed() && <add> `Cannot create a new chains for \`${toString( <add> this.source <add> )}\` after it has been destroyed.`, <add> !this.isMetaDestroyed() <add> ); <ide> let ret = this._chains; <ide> if (ret === undefined) { <ide> if (this.parent === undefined) { <ide> export class Meta { <ide> } <ide> <ide> writeWatching(subkey, value) { <del> assert(`Cannot update watchers for \`${subkey}\` on \`${toString(this.source)}\` after it has been destroyed.`, !this.isMetaDestroyed()); <add> assert( <add> this.isMetaDestroyed() && <add> `Cannot update watchers for \`${subkey}\` on \`${toString( <add> this.source <add> )}\` after it has been destroyed.`, <add> !this.isMetaDestroyed() <add> ); <ide> let map = this._getOrCreateOwnMap('_watching'); <ide> map[subkey] = value; <ide> } <ide> export class Meta { <ide> } <ide> <ide> addMixin(mixin) { <del> assert(`Cannot add mixins of \`${toString(mixin)}\` on \`${toString(this.source)}\` call addMixin after it has been destroyed.`, !this.isMetaDestroyed()); <add> assert( <add> this.isMetaDestroyed() && <add> `Cannot add mixins of \`${toString(mixin)}\` on \`${toString( <add> this.source <add> )}\` call addMixin after it has been destroyed.`, <add> !this.isMetaDestroyed() <add> ); <ide> let set = this._getOrCreateOwnSet('_mixins'); <ide> set.add(mixin); <ide> } <ide> export class Meta { <ide> let set = pointer._mixins; <ide> if (set !== undefined) { <ide> seen = seen === undefined ? new Set() : seen; <del> set.forEach((mixin)=> { <add> set.forEach(mixin => { <ide> if (!seen.has(mixin)) { <ide> seen.add(mixin); <ide> fn(mixin); <ide> export class Meta { <ide> } <ide> <ide> writeBindings(subkey, value) { <del> assert('Cannot invoke `meta.writeBindings` when EmberENV._ENABLE_BINDING_SUPPORT is not set', ENV._ENABLE_BINDING_SUPPORT); <del> assert(`Cannot add a binding for \`${subkey}\` on \`${toString(this.source)}\` after it has been destroyed.`, !this.isMetaDestroyed()); <add> assert( <add> 'Cannot invoke `meta.writeBindings` when EmberENV._ENABLE_BINDING_SUPPORT is not set', <add> ENV._ENABLE_BINDING_SUPPORT <add> ); <add> assert( <add> this.isMetaDestroyed() && <add> `Cannot add a binding for \`${subkey}\` on \`${toString( <add> this.source <add> )}\` after it has been destroyed.`, <add> !this.isMetaDestroyed() <add> ); <ide> <ide> let map = this._getOrCreateOwnMap('_bindings'); <ide> map[subkey] = value; <ide> } <ide> <ide> peekBindings(subkey) { <del> assert('Cannot invoke `meta.peekBindings` when EmberENV._ENABLE_BINDING_SUPPORT is not set', ENV._ENABLE_BINDING_SUPPORT); <add> assert( <add> 'Cannot invoke `meta.peekBindings` when EmberENV._ENABLE_BINDING_SUPPORT is not set', <add> ENV._ENABLE_BINDING_SUPPORT <add> ); <ide> return this._findInherited('_bindings', subkey); <ide> } <ide> <ide> forEachBindings(fn) { <del> assert('Cannot invoke `meta.forEachBindings` when EmberENV._ENABLE_BINDING_SUPPORT is not set', ENV._ENABLE_BINDING_SUPPORT); <add> assert( <add> 'Cannot invoke `meta.forEachBindings` when EmberENV._ENABLE_BINDING_SUPPORT is not set', <add> ENV._ENABLE_BINDING_SUPPORT <add> ); <ide> <ide> let pointer = this; <ide> let seen; <ide> export class Meta { <ide> } <ide> <ide> clearBindings() { <del> assert('Cannot invoke `meta.clearBindings` when EmberENV._ENABLE_BINDING_SUPPORT is not set', ENV._ENABLE_BINDING_SUPPORT); <del> assert(`Cannot clear bindings on \`${toString(this.source)}\` after it has been destroyed.`, !this.isMetaDestroyed()); <add> assert( <add> 'Cannot invoke `meta.clearBindings` when EmberENV._ENABLE_BINDING_SUPPORT is not set', <add> ENV._ENABLE_BINDING_SUPPORT <add> ); <add> assert( <add> this.isMetaDestroyed() && <add> `Cannot clear bindings on \`${toString( <add> this.source <add> )}\` after it has been destroyed.`, <add> !this.isMetaDestroyed() <add> ); <ide> this._bindings = undefined; <ide> } <del> <ide> } <ide> <ide> for (let name in listenerMethods) { <ide> Meta.prototype[name] = listenerMethods[name]; <ide> } <ide> <ide> if (MANDATORY_SETTER) { <del> Meta.prototype.writeValues = function (subkey, value) { <del> assert(`Cannot set the value of \`${subkey}\` on \`${toString(this.source)}\` after it has been destroyed.`, !this.isMetaDestroyed()); <add> Meta.prototype.writeValues = function(subkey, value) { <add> assert( <add> this.isMetaDestroyed() && <add> `Cannot set the value of \`${subkey}\` on \`${toString( <add> this.source <add> )}\` after it has been destroyed.`, <add> !this.isMetaDestroyed() <add> ); <ide> <ide> let map = this._getOrCreateOwnMap('_values'); <ide> map[subkey] = value; <ide> }; <ide> <del> Meta.prototype.peekValues = function (subkey) { <add> Meta.prototype.peekValues = function(subkey) { <ide> return this._findInherited('_values', subkey); <ide> }; <ide> <del> Meta.prototype.deleteFromValues = function (subkey) { <add> Meta.prototype.deleteFromValues = function(subkey) { <ide> delete this._getOrCreateOwnMap('_values')[subkey]; <ide> }; <ide> <ide> if (MANDATORY_SETTER) { <ide> <ide> Meta.prototype.writeValue = function(obj, key, value) { <ide> let descriptor = lookupDescriptor(obj, key); <del> let isMandatorySetter = descriptor !== null && descriptor.set && descriptor.set.isMandatorySetter; <add> let isMandatorySetter = <add> descriptor !== null && descriptor.set && descriptor.set.isMandatorySetter; <ide> <ide> if (isMandatorySetter) { <ide> this.writeValues(key, value); <ide> if (MANDATORY_SETTER) { <ide> <ide> if (EMBER_METAL_ES5_GETTERS) { <ide> Meta.prototype.writeDescriptors = function(subkey, value) { <del> assert(`Cannot update descriptors for \`${subkey}\` on \`${toString(this.source)}\` after it has been destroyed.`, !this.isMetaDestroyed()); <add> assert( <add> this.isMetaDestroyed() && <add> `Cannot update descriptors for \`${subkey}\` on \`${toString( <add> this.source <add> )}\` after it has been destroyed.`, <add> !this.isMetaDestroyed() <add> ); <ide> let map = this._getOrCreateOwnMap('_descriptors'); <ide> map[subkey] = value; <ide> }; <ide> const metaStore = new WeakMap(); <ide> export function setMeta(obj, meta) { <ide> assert('Cannot call `setMeta` on null', obj !== null); <ide> assert('Cannot call `setMeta` on undefined', obj !== undefined); <del> assert(`Cannot call \`setMeta\` on ${typeof obj}`, typeof obj === 'object' || typeof obj === 'function'); <add> assert( <add> `Cannot call \`setMeta\` on ${typeof obj}`, <add> typeof obj === 'object' || typeof obj === 'function' <add> ); <ide> <ide> if (DEBUG) { <ide> counters.setCalls++; <ide> export function setMeta(obj, meta) { <ide> export function peekMeta(obj) { <ide> assert('Cannot call `peekMeta` on null', obj !== null); <ide> assert('Cannot call `peekMeta` on undefined', obj !== undefined); <del> assert(`Cannot call \`peekMeta\` on ${typeof obj}`, typeof obj === 'object' || typeof obj === 'function'); <add> assert( <add> `Cannot call \`peekMeta\` on ${typeof obj}`, <add> typeof obj === 'object' || typeof obj === 'function' <add> ); <ide> <ide> let pointer = obj; <ide> let meta; <ide> export function peekMeta(obj) { <ide> export function deleteMeta(obj) { <ide> assert('Cannot call `deleteMeta` on null', obj !== null); <ide> assert('Cannot call `deleteMeta` on undefined', obj !== undefined); <del> assert(`Cannot call \`deleteMeta\` on ${typeof obj}`, typeof obj === 'object' || typeof obj === 'function'); <add> assert( <add> `Cannot call \`deleteMeta\` on ${typeof obj}`, <add> typeof obj === 'object' || typeof obj === 'function' <add> ); <ide> <ide> if (DEBUG) { <ide> counters.deleteCalls++; <ide> export function deleteMeta(obj) { <ide> export function meta(obj) { <ide> assert('Cannot call `meta` on null', obj !== null); <ide> assert('Cannot call `meta` on undefined', obj !== undefined); <del> assert(`Cannot call \`meta\` on ${typeof obj}`, typeof obj === 'object' || typeof obj === 'function'); <add> assert( <add> `Cannot call \`meta\` on ${typeof obj}`, <add> typeof obj === 'object' || typeof obj === 'function' <add> ); <ide> <ide> if (DEBUG) { <ide> counters.metaCalls++; <ide> export const DESCRIPTOR = '__DESCRIPTOR__'; <ide> export function descriptorFor(obj, keyName, _meta) { <ide> assert('Cannot call `descriptorFor` on null', obj !== null); <ide> assert('Cannot call `descriptorFor` on undefined', obj !== undefined); <del> assert(`Cannot call \`descriptorFor\` on ${typeof obj}`, typeof obj === 'object' || typeof obj === 'function'); <add> assert( <add> `Cannot call \`descriptorFor\` on ${typeof obj}`, <add> typeof obj === 'object' || typeof obj === 'function' <add> ); <ide> <ide> if (EMBER_METAL_ES5_GETTERS) { <ide> let meta = _meta === undefined ? peekMeta(obj) : _meta; <ide> export function descriptorFor(obj, keyName, _meta) { <ide> <ide> export function isDescriptorTrap(possibleDesc) { <ide> if (DESCRIPTOR_TRAP) { <del> return possibleDesc !== null && typeof possibleDesc === 'object' && possibleDesc[DESCRIPTOR] !== undefined; <add> return ( <add> possibleDesc !== null && <add> typeof possibleDesc === 'object' && <add> possibleDesc[DESCRIPTOR] !== undefined <add> ); <ide> } else { <ide> throw new Error('Cannot call `isDescriptorTrap` in production'); <ide> } <ide> export function isDescriptorTrap(possibleDesc) { <ide> @private <ide> */ <ide> export function isDescriptor(possibleDesc) { <del> return possibleDesc !== null && typeof possibleDesc === 'object' && possibleDesc.isDescriptor; <add> return ( <add> possibleDesc !== null && <add> typeof possibleDesc === 'object' && <add> possibleDesc.isDescriptor <add> ); <ide> } <ide> <ide> export { counters };
1
Go
Go
add ipam contract
3287a4c830efb3d31b863677ab9d5d01b3d04a96
<ide><path>libnetwork/ipam/contract.go <add>// Package ipam that specifies the contract the IPAM plugin need to satisfy, <add>// decoupling IPAM interface and implementation. <add>package ipam <add> <add>import ( <add> "errors" <add> "net" <add>) <add> <add>/************** <add> * IPAM Errors <add> **************/ <add> <add>// ErrIpamNotAvailable is returned when the plugin prviding the IPAM service is not available <add>var ( <add> ErrInvalidIpamService = errors.New("Invalid IPAM Service") <add> ErrInvalidIpamConfigService = errors.New("Invalid IPAM Config Service") <add> ErrIpamNotAvailable = errors.New("IPAM Service not available") <add> ErrIpamInternalError = errors.New("IPAM Internal Error") <add> ErrInvalidAddressSpace = errors.New("Invalid Address Space") <add> ErrInvalidSubnet = errors.New("Invalid Subnet") <add> ErrInvalidRequest = errors.New("Invalid Request") <add> ErrSubnetNotFound = errors.New("Subnet not found") <add> ErrOverlapSubnet = errors.New("Subnet overlaps with existing subnet on this address space") <add> ErrNoAvailableSubnet = errors.New("No available subnet") <add> ErrNoAvailableIPs = errors.New("No available addresses on subnet") <add> ErrIPAlreadyAllocated = errors.New("Address already in use") <add> ErrIPOutOfRange = errors.New("Requested address is out of range") <add> ErrSubnetAlreadyRegistered = errors.New("Subnet already registered on this address space") <add> ErrBadSubnet = errors.New("Address space does not contain specified subnet") <add>) <add> <add>// AddressSpace identifies a unique pool of network addresses <add>type AddressSpace string <add> <add>/******************************* <add> * IPAM Configuration Interface <add> *******************************/ <add> <add>// Config represents the interface the IPAM service plugins must implement <add>// in order to allow injection/modification of IPAM database. <add>// Common key is a addressspace <add>type Config interface { <add> // AddSubnet adds a subnet to the specified address space <add> AddSubnet(AddressSpace, *SubnetInfo) error <add> // RemoveSubnet removes a subnet from the specified address space <add> RemoveSubnet(AddressSpace, *net.IPNet) error <add> // AddVendorInfo adds Vendor specific data <add> AddVendorInfo([]byte) error <add>} <add> <add>// SubnetInfo contains the information subnet hosts need in order to communicate <add>type SubnetInfo struct { <add> Subnet *net.IPNet <add> Gateway net.IP <add> OpaqueData []byte // Vendor specific <add>} <add> <add>/************************* <add> * IPAM Service Interface <add> *************************/ <add> <add>// IPAM defines the interface that needs to be implemented by IPAM service plugin <add>// Common key is a unique address space identifier <add>type IPAM interface { <add> // Request address from the specified address space <add> Request(AddressSpace, *AddressRequest) (*AddressResponse, error) <add> // Separate API for IPv6 <add> RequestV6(AddressSpace, *AddressRequest) (*AddressResponse, error) <add> // Release the address from the specified address space <add> Release(AddressSpace, net.IP) <add>} <add> <add>// AddressRequest encloses the information a client <add>// needs to pass to IPAM when requesting an address <add>type AddressRequest struct { <add> Subnet net.IPNet // Preferred subnet pool (Optional) <add> Address net.IP // Preferred address (Optional) <add> Endpoint string // For static IP mapping (Optional) <add> OpaqueData []byte // Vendor specific request data <add>} <add> <add>// Validate runs syntactic validation on this AddressRequest object <add>func (req *AddressRequest) Validate() error { <add> var byteArray []byte = req.Address <add> <add> // Check preferred address <add> if byteArray != nil && (&req.Subnet == nil || !req.Subnet.Contains(req.Address)) { <add> return ErrInvalidRequest <add> } <add> <add> return nil <add>} <add> <add>// AddressResponse represents the IPAM service's <add>// response to an address request <add>type AddressResponse struct { <add> Address net.IP <add> Subnet SubnetInfo <add>}
1
Python
Python
add explicit 'return none' to the function
c0cc8f9869ea160a631a4c70cb6ec97e18ca3d3a
<ide><path>libcloud/compute/drivers/opennebula.py <ide> def _extract_images(self, compute): <ide> # per node. <ide> if len(disks) > 1: <ide> return disks <del> <del> if len(disks) == 1: <add> elif len(disks) == 1: <ide> return disks[0] <add> else: <add> return None <ide> <ide> def _extract_size(self, compute): <ide> """
1
Text
Text
inline button sections
31b2f2eb6a1214321f69b6c72f7bfc30070cb983
<ide><path>guide/english/bootstrap/buttons/index.md <ide> It is possible to also have outlined buttons rather than fully colored in ones. <ide> <ide> Outlined buttons are a part of Bootstrap since version 4, please be sure that you are using the right version if you are unable to get them to work. <ide> <add>#### Inline Buttons <add>You can create inline button row by adding `.d-inline-block` class to the element which sets the display of the button to inline block. For example : `<button class="btn btn-primary d-inline-block btn-lg"></button>` <add> <ide> _Note: Do not include the dot in the HTML Class Attribute, referring to the classes with a dot is only used when adjusting the classes in CSS._ <ide> <add> <ide> #### More Information: <ide> * <a href='https://getbootstrap.com/docs/4.1/components/buttons/' target='_blank' rel='nofollow'>Bootstrap Buttons documentation</a> <ide> * <a href='https://getbootstrap.com/docs/4.1/components/button-group/' target='_blank' rel='nofollow'>Bootstrap Button Group documentation</a>
1
Javascript
Javascript
use brackets to escape characters
68878821c2b8180816aba4a7a8725f1d9f8db205
<ide><path>test/lang/br.js <ide> exports["lang:br"] = { <ide> ['H HH', '15 15'], <ide> ['m mm', '25 25'], <ide> ['s ss', '50 50'], <del> ['DDDo \\d\\ev\\ez\\h \\ar v\\lo\\az', '45vet devezh ar vloaz'], <add> ['DDDo [devezh] [ar] [vloaz]', '45vet devezh ar vloaz'], <ide> ['L', '14/02/2010'], <ide> ['LL', "14 a viz C'hwevrer 2010"], <ide> ['LLL', "14 a viz C'hwevrer 2010 3e25 PM"],
1
Python
Python
fix checkpoint name for wav2vec2 conformer
39b5bb79d914f2af723f3aaf92f96fce8b957559
<ide><path>src/transformers/models/wav2vec2_conformer/configuration_wav2vec2_conformer.py <ide> logger = logging.get_logger(__name__) <ide> <ide> WAV2VEC2_CONFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP = { <del> "facebook/wav2vec2-conformer-large-rel-pos": ( <del> "https://huggingface.co/facebook/wav2vec2-conformer-large-rel-pos/resolve/main/config.json" <add> "facebook/wav2vec2-conformer-rel-pos-large": ( <add> "https://huggingface.co/facebook/wav2vec2-conformer-rel-pos-large/resolve/main/config.json" <ide> ), <ide> } <ide> <ide> class Wav2Vec2ConformerConfig(PretrainedConfig): <ide> This is the configuration class to store the configuration of a [`Wav2Vec2ConformerModel`]. It is used to <ide> instantiate an Wav2Vec2Conformer model according to the specified arguments, defining the model architecture. <ide> Instantiating a configuration with the defaults will yield a similar configuration to that of the Wav2Vec2Conformer <del> [facebook/wav2vec2-conformer-large-rel-pos](https://huggingface.co/facebook/wav2vec2-conformer-large-rel-pos) <add> [facebook/wav2vec2-conformer-rel-pos-large](https://huggingface.co/facebook/wav2vec2-conformer-rel-pos-large) <ide> architecture. <ide> <ide> Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the <ide> class Wav2Vec2ConformerConfig(PretrainedConfig): <ide> ```python <ide> >>> from transformers import Wav2Vec2ConformerModel, Wav2Vec2ConformerConfig <ide> <del> >>> # Initializing a Wav2Vec2Conformer facebook/wav2vec2-conformer-large-rel-pos style configuration <add> >>> # Initializing a Wav2Vec2Conformer facebook/wav2vec2-conformer-rel-pos-large style configuration <ide> >>> configuration = Wav2Vec2ConformerConfig() <ide> <del> >>> # Initializing a model from the facebook/wav2vec2-conformer-large-rel-pos style configuration <add> >>> # Initializing a model from the facebook/wav2vec2-conformer-rel-pos-large style configuration <ide> >>> model = Wav2Vec2ConformerModel(configuration) <ide> <ide> >>> # Accessing the model configuration <ide><path>src/transformers/models/wav2vec2_conformer/modeling_wav2vec2_conformer.py <ide> <ide> <ide> WAV2VEC2_CONFORMER_PRETRAINED_MODEL_ARCHIVE_LIST = [ <del> "facebook/wav2vec2-conformer-large-rel-pos", <add> "facebook/wav2vec2-conformer-rel-pos-large", <ide> # See all Wav2Vec2Conformer models at https://huggingface.co/models?filter=wav2vec2-conformer <ide> ] <ide> <ide> def _set_gradient_checkpointing(self, module, value=False): <ide> <ide> `attention_mask` should only be passed if the corresponding processor has `config.return_attention_mask == <ide> True`. For all models whose processor has `config.return_attention_mask == False`, such as <del> [wav2vec2_conformer-base](https://huggingface.co/facebook/wav2vec2-conformer-large-rel-pos), <add> [wav2vec2-conformer-rel-pos-large](https://huggingface.co/facebook/wav2vec2-conformer-rel-pos-large), <ide> `attention_mask` should **not** be passed to avoid degraded performance when doing batched inference. For <ide> such models `input_values` should simply be padded with 0 and passed without `attention_mask`. Be aware <ide> that these models also yield slightly different results depending on whether `input_values` is padded or
2
Python
Python
add typing to azure cosmos client hook
3393647aa63cbfdd2e6b90b7a5c9971732a54fc2
<ide><path>airflow/providers/microsoft/azure/hooks/cosmos.py <ide> def get_ui_field_behaviour() -> Dict[str, Any]: <ide> def __init__(self, azure_cosmos_conn_id: str = default_conn_name) -> None: <ide> super().__init__() <ide> self.conn_id = azure_cosmos_conn_id <del> self._conn = None <add> self._conn: Optional[CosmosClient] = None <ide> <ide> self.default_database_name = None <ide> self.default_collection_name = None
1
Javascript
Javascript
use blue on non-windows systems for number/bigint
1708af369ba4cdfbc9f3eadd657508498b8489a3
<ide><path>lib/util.js <ide> inspect.colors = Object.assign(Object.create(null), { <ide> }); <ide> <ide> // Don't use 'blue' not visible on cmd.exe <add>const windows = process.platform === 'win32'; <ide> inspect.styles = Object.assign(Object.create(null), { <ide> 'special': 'cyan', <del> 'number': 'yellow', <del> 'bigint': 'yellow', <add> 'number': windows ? 'yellow' : 'blue', <add> 'bigint': windows ? 'yellow' : 'blue', <ide> 'boolean': 'yellow', <ide> 'undefined': 'grey', <ide> 'null': 'bold', <ide><path>test/parallel/test-stream-buffer-list.js <ide> assert.deepStrictEqual(list, new BufferList()); <ide> <ide> const tmp = util.inspect.defaultOptions.colors; <ide> util.inspect.defaultOptions = { colors: true }; <add>const color = util.inspect.colors[util.inspect.styles.number]; <ide> assert.strictEqual( <ide> util.inspect(list), <del> 'BufferList { length: \u001b[33m0\u001b[39m }'); <add> `BufferList { length: \u001b[${color[0]}m0\u001b[${color[1]}m }`); <ide> util.inspect.defaultOptions = { colors: tmp };
2
Javascript
Javascript
support variable terminal widths
72110ed40f417d4076ff843f94113722aa011402
<ide><path>src/main-process/parse-command-line.js <ide> const path = require('path') <ide> const fs = require('fs-plus') <ide> <ide> module.exports = function parseCommandLine (processArgs) { <del> const options = yargs(processArgs).wrap(yargs(processArgs).terminalWidth()) <add> const options = yargs(processArgs).wrap(yargs.terminalWidth()) <ide> const version = app.getVersion() <ide> options.usage( <ide> dedent`Atom Editor v${version}
1
Python
Python
improve pretrain textcat example
bc8cda818c6d754a46bc6ffa2dbccd5a01181968
<ide><path>examples/training/pretrain_textcat.py <ide> def load_textcat_data(limit=0): <ide> train_data = train_data[-limit:] <ide> texts, labels = zip(*train_data) <ide> eval_texts, eval_labels = zip(*eval_data) <del> cats = [{'POSITIVE': bool(y)} for y in labels] <del> eval_cats = [{'POSITIVE': bool(y)} for y in eval_labels] <add> cats = [{'POSITIVE': bool(y), 'NEGATIVE': not bool(y)} for y in labels] <add> eval_cats = [{'POSITIVE': bool(y), 'NEGATIVE': not bool(y)} for y in eval_labels] <ide> return (texts, cats), (eval_texts, eval_cats) <ide> <ide> <ide> def prefer_gpu(): <ide> <ide> <ide> def build_textcat_model(tok2vec, nr_class, width): <del> from thinc.v2v import Model, Affine, Maxout <add> from thinc.v2v import Model, Softmax, Maxout <ide> from thinc.api import flatten_add_lengths, chain <del> from thinc.t2v import Pooling, sum_pool, max_pool <add> from thinc.t2v import Pooling, sum_pool, mean_pool, max_pool <ide> from thinc.misc import Residual, LayerNorm <ide> from spacy._ml import logistic, zero_init <ide> <ide> with Model.define_operators({'>>': chain}): <ide> model = ( <ide> tok2vec <ide> >> flatten_add_lengths <del> >> Pooling(sum_pool, max_pool) <del> >> Residual(LayerNorm(Maxout(width*2, width*2, pieces=3))) <del> >> Residual(LayerNorm(Maxout(width*2, width*2, pieces=3))) <del> >> zero_init(Affine(nr_class, width*2, drop_factor=0.0)) <del> >> logistic <add> >> Pooling(mean_pool) <add> >> Softmax(nr_class, width) <ide> ) <ide> model.tok2vec = tok2vec <ide> return model <ide> def create_pipeline(width, embed_size, vectors_model): <ide> nlp = spacy.load(vectors_model) <ide> print("Start training") <ide> textcat = TextCategorizer(nlp.vocab, <del> labels=['POSITIVE'], <add> labels=['POSITIVE', 'NEGATIVE'], <ide> model=build_textcat_model( <del> Tok2Vec(width=width, embed_size=embed_size), 1, width)) <add> Tok2Vec(width=width, embed_size=embed_size), 2, width)) <ide> <ide> nlp.add_pipe(textcat) <ide> return nlp
1
Javascript
Javascript
update navigationcontext api
4763f89efa4f48a194d50b37b046cb7e7ae0f129
<ide><path>Libraries/CustomComponents/Navigator/Navigation/NavigationContext.js <ide> class NavigationContext { <ide> this._emitCounter = 0; <ide> this._emitQueue = []; <ide> <del> this.addListener('willfocus', this._onFocus, this); <del> this.addListener('didfocus', this._onFocus, this); <add> this.addListener('willfocus', this._onFocus); <add> this.addListener('didfocus', this._onFocus); <ide> } <ide> <ide> /* $FlowFixMe - get/set properties not yet supported */ <ide> class NavigationContext { <ide> return parent ? parent.getValue() : null; <ide> } <ide> <add> /* $FlowFixMe - get/set properties not yet supported */ <add> get top(): ?NavigationContext { <add> var result = null; <add> var parentNode = this.__node.getParent(); <add> while (parentNode) { <add> result = parentNode.getValue(); <add> parentNode = parentNode.getParent(); <add> } <add> return result; <add> } <add> <ide> /* $FlowFixMe - get/set properties not yet supported */ <ide> get currentRoute(): any { <ide> return this._currentRoute; <ide> class NavigationContext { <ide> addListener( <ide> eventType: string, <ide> listener: Function, <del> context: ?Object, <ide> useCapture: ?boolean <ide> ): EventSubscription { <ide> if (LegacyEventTypes.has(eventType)) { <ide> class NavigationContext { <ide> this._bubbleEventEmitter; <ide> <ide> if (emitter) { <del> return emitter.addListener(eventType, listener, context); <add> return emitter.addListener(eventType, listener, this); <ide> } else { <ide> return {remove: emptyFunction}; <ide> } <ide><path>Libraries/CustomComponents/Navigator/Navigation/__tests__/NavigationContext-test.js <ide> describe('NavigationContext', () => { <ide> expect(child.parent).toBe(parent); <ide> }); <ide> <add> it('has `top`', () => { <add> var top = new NavigationContext(); <add> var parent = new NavigationContext(); <add> var child = new NavigationContext(); <add> top.appendChild(parent); <add> parent.appendChild(child); <add> expect(child.top).toBe(top); <add> }); <add> <ide> it('captures event', () => { <ide> var parent = new NavigationContext(); <ide> var child = new NavigationContext(); <ide> describe('NavigationContext', () => { <ide> }); <ide> }; <ide> <del> parent.addListener('yo', listener, null, true); <del> child.addListener('yo', listener, null, true); <add> parent.addListener('yo', listener, true); <add> child.addListener('yo', listener, true); <ide> <ide> child.emit('yo'); <ide> <ide> describe('NavigationContext', () => { <ide> <ide> var counter = 0; <ide> <del> parent.addListener('yo', event => event.stopPropagation(), null, true); <del> child.addListener('yo', event => counter++, null, true); <add> parent.addListener('yo', event => event.stopPropagation(), true); <add> child.addListener('yo', event => counter++, true); <ide> <ide> child.emit('yo'); <ide> <ide> describe('NavigationContext', () => { <ide> parent.appendChild(child); <ide> <ide> var val; <del> parent.addListener('yo', event => event.preventDefault(), null, true); <del> child.addListener('yo', event => val = event.defaultPrevented, null, true); <add> parent.addListener('yo', event => event.preventDefault(), true); <add> child.addListener('yo', event => val = event.defaultPrevented, true); <ide> <ide> child.emit('yo'); <ide> <ide> describe('NavigationContext', () => { <ide> child.emit('didyo'); <ide> }); <ide> <del> parent.addListener('yo', listener, null, true); <del> parent.addListener('didyo', listener, null, true); <del> child.addListener('yo', listener, null, true); <add> parent.addListener('yo', listener, true); <add> parent.addListener('didyo', listener, true); <add> child.addListener('yo', listener, true); <ide> <ide> child.emit('yo'); <ide>
2
Python
Python
fix typo in docstring
801b2cb36fd1b347311e5ce63bec34845df3acc0
<ide><path>src/transformers/models/bert_japanese/tokenization_bert_japanese.py <ide> def __init__( <ide> Whether to apply unicode normalization to text before tokenization. <ide> **mecab_dic**: (`optional`) string (default "ipadic") <ide> Name of dictionary to be used for MeCab initialization. If you are using a system-installed dictionary, <del> set thi option to `None` and modify `mecab_option`. <add> set this option to `None` and modify `mecab_option`. <ide> **mecab_option**: (`optional`) string <ide> String passed to MeCab constructor. <ide> """
1
Ruby
Ruby
remove unused attribute from builderror
2332e6525d6460790e8d7be44291fd63a06c5eea
<ide><path>Library/Homebrew/exceptions.rb <ide> def message <ide> end <ide> <ide> class BuildError < Homebrew::InstallationError <del> attr_reader :command, :env <add> attr_reader :env <ide> <ide> def initialize(formula, cmd, args, env) <del> @command = cmd <ide> @env = env <ide> args = args.map{ |arg| arg.to_s.gsub " ", "\\ " }.join(" ") <del> super formula, "Failed executing: #{command} #{args}" <add> super formula, "Failed executing: #{cmd} #{args}" <ide> end <ide> <ide> def issues
1
Text
Text
add note to upgrading guide about react version
5be354ede6b35f41b206d9c27f48a0ea34f32c32
<ide><path>docs/upgrading.md <ide> description: Learn how to upgrade Next.js. <ide> <ide> ## Upgrading from version 10 to 11 <ide> <add>## Upgrade React version to latest <add> <add>Most applications already use the latest version of React, with Next.js 11 the minimum React version has been updated to 17.0.2. <add> <add>To upgrade you can run the following command: <add> <add>``` <add>npm install react@latest react-dom@latest <add>``` <add> <add>Or using `yarn`: <add> <add>``` <add>yarn add next@latest react-dom@latest <add>``` <add> <ide> ### Remove `super.componentDidCatch()` from `pages/_app.js` <ide> <ide> The `next/app` component's `componentDidCatch` has been deprecated since Next.js 9 as it's no longer needed and has since been a no-op, in Next.js 11 it has been removed.
1
Text
Text
add livetracker options to options guide
6336e573f2f49353937159a98adb8263461fc3e1
<ide><path>docs/guides/options.md <ide> Allows the player to use the new live ui that includes: <ide> Without this option the progress bar will be hidden and in its place will be text that indicates `LIVE` playback. There will be no progress control <ide> and you will not be able click the text to seek to the live edge. `liveui` will default to `true` in a future version! <ide> <add>### `liveTracker.trackingThreshold` <add> <add>> Type: `number` <add>> Default: `30` <add> <add>An option for the liveTracker component of the player that controls when the liveui should be shown. By default if a stream has less than 30s on the seekBar then we do not show the new liveui even with the liveui option set. <add> <add> <add>### `liveTracker.liveTolerance` <add> <add>> Type: `number` <add>> Default: `15` <add> <add>An option for the liveTracker component of the player that controls how far from the seekable end should be considered live playback. By default anything further than 15s from the live seekable edge is considered behind live and everything else is considered live. Any user interaction to seek backwards will ignore this value as a user would expect. <add> <add> <ide> ### `nativeControlsForTouch` <ide> <ide> > Type: `boolean`
1
Ruby
Ruby
decrease string allocations on ar#respond_to?
f80aa5994603e684e3fecd3f53bfbf242c73a107
<ide><path>activerecord/lib/active_record/attribute_methods.rb <ide> def column_for_attribute(name) <ide> # person.respond_to(:nothing) # => false <ide> def respond_to?(name, include_private = false) <ide> return false unless super <del> name = name.to_s <add> <add> case name <add> when :to_partial_path <add> name = "to_partial_path".freeze <add> when :to_model <add> name = "to_model".freeze <add> else <add> name = name.to_s <add> end <ide> <ide> # If the result is true then check for the select case. <ide> # For queries selecting a subset of columns, return false for unselected columns.
1
Text
Text
improve the instructions of onboarding pr
0e7050ec86c1fb3ab5a3fb6c4500cfa42442ae0d
<ide><path>doc/onboarding.md <ide> onboarding session. <ide> * Optionally, include your personal pronouns. <ide> * Label your pull request with the `doc` subsystem label. <ide> * Run CI on your PR. <del>* After one or two approvals, land the PR. <add>* After one or two approvals, land the PR (PRs of this type do not need to wait <add> for 48/72 hours to land). <ide> * Be sure to add the `PR-URL: <full-pr-url>` and appropriate `Reviewed-By:` <del> metadata! <del> * [`core-validate-commit`][] helps a lot with this – install and use it if you <del> can! <del> * [`node-core-utils`][] fetches the metadata for you. <add> metadata. <add> * [`core-validate-commit`][] automates the validation of commit messages. <add> * [`node-core-utils`][] automates the generation of metadata and the landing <add> process. See the documentation of [`git-node`][]. <ide> <ide> ## Final notes <ide> <ide> onboarding session. <ide> <ide> [Code of Conduct]: https://github.com/nodejs/admin/blob/master/CODE_OF_CONDUCT.md <ide> [`core-validate-commit`]: https://github.com/evanlucas/core-validate-commit <add>[`git-node`]: https://github.com/nodejs/node-core-utils#git-node <ide> [`node-core-utils`]: https://github.com/nodejs/node-core-utils <ide> [Landing Pull Requests]: https://github.com/nodejs/node/blob/master/COLLABORATOR_GUIDE.md#landing-pull-requests <ide> [https://github.com/nodejs/node/commit/ce986de829457c39257cd205067602e765768fb0]: https://github.com/nodejs/node/commit/ce986de829457c39257cd205067602e765768fb0
1
Javascript
Javascript
fix challenge tests that rely on
e7211fc67b849a863b20e905dde4ee1e1e62133e
<ide><path>packages/learn/src/templates/Challenges/redux/execute-challenge-epic.js <ide> import { <ide> initConsole, <ide> updateConsole, <ide> initLogs, <del> updateLogs, <ide> logsToConsole, <ide> checkChallenge, <ide> updateTests, <ide> function updateMainEpic(actions, { getState }, { document }) { <ide> const proxyLogger = new Subject(); <ide> const frameMain = createMainFramer(document, getState, proxyLogger); <ide> const buildAndFrameMain = actions.pipe( <del> ofType( <del> types.updateFile, <del> types.challengeMounted <del> ), <add> ofType(types.updateFile, types.challengeMounted), <ide> debounceTime(executeDebounceTimeout), <ide> switchMap(() => <ide> buildFromFiles(getState(), true).pipe( <ide> function executeChallengeEpic(action$, { getState }, { document }) { <ide> filter(Boolean), <ide> switchMap(() => { <ide> const frameReady = new Subject(); <del> const proxyLogger = new Subject(); <add> // Removed for investigation into freeCodeCamp/Learn#291 <add> // const proxyLogger = new Subject(); <ide> const frameTests = createTestFramer( <ide> document, <ide> getState, <del> frameReady, <del> proxyLogger <add> frameReady <add> // proxyLogger <ide> ); <ide> const challengeResults = frameReady.pipe( <ide> pluck('checkChallengePayload'), <ide> function executeChallengeEpic(action$, { getState }, { document }) { <ide> const build = <ide> challengeType === backend <ide> ? buildBackendChallenge(state) <del> : buildFromFiles(state, true); <add> : buildFromFiles(state, false); <ide> return build.pipe( <ide> tap(frameTests), <ide> ignoreElements(), <ide> function executeChallengeEpic(action$, { getState }, { document }) { <ide> ); <ide> }) <ide> ); <del> return merge( <del> buildAndFrameChallenge, <del> challengeResults, <del> proxyLogger.map(updateLogs) <del> ); <add> return merge(buildAndFrameChallenge, challengeResults); <ide> }) <ide> ); <ide> } <ide><path>packages/learn/src/templates/Challenges/utils/frame.js <ide> export const createMainFramer = (document, getState, proxyLogger) => <ide> writeContentToFrame <ide> ); <ide> <del>export const createTestFramer = (document, getState, frameReady, proxyLogger) => <add>export const createTestFramer = (document, getState, frameReady) => <ide> flow( <ide> createFrame(document, getState, testId), <ide> mountFrame(document), <ide> addDepsToDocument, <ide> writeTestDepsToDocument(frameReady), <del> buildProxyConsole(proxyLogger), <ide> writeContentToFrame <ide> );
2
Javascript
Javascript
inline unnecessary addbufferatindex method
b7ae57bdbedcb1c845a558ecfe5fcb81facf98ae
<ide><path>src/project.js <ide> class Project extends Model { <ide> } <ide> <ide> addBuffer (buffer, options = {}) { <del> return this.addBufferAtIndex(buffer, this.buffers.length, options) <del> } <del> <del> addBufferAtIndex (buffer, index, options = {}) { <del> this.buffers.splice(index, 0, buffer) <add> this.buffers.push(buffer) <ide> this.subscribeToBuffer(buffer) <ide> this.emitter.emit('did-add-buffer', buffer) <ide> return buffer
1
Python
Python
add model cards cc @mfuntowicz
56e98ba81a9a7410243a1117fb6148d5f353ef98
<ide><path>transformers/__init__.py <ide> if is_sklearn_available(): <ide> from .data import glue_compute_metrics, xnli_compute_metrics <ide> <add># Model Cards <add>from .model_card import ModelCard <add> <ide> # Tokenizers <ide> from .tokenization_utils import (PreTrainedTokenizer) <ide> from .tokenization_auto import AutoTokenizer <ide><path>transformers/file_utils.py <ide> TF2_WEIGHTS_NAME = 'tf_model.h5' <ide> TF_WEIGHTS_NAME = 'model.ckpt' <ide> CONFIG_NAME = "config.json" <del> <add>MODEL_CARD_NAME = "model_card.json" <ide> <ide> DUMMY_INPUTS = [[7, 6, 0, 0, 1], [1, 2, 3, 0, 0], [0, 0, 0, 4, 5]] <ide> DUMMY_MASK = [[1, 1, 1, 1, 1], [1, 1, 1, 0, 0], [0, 0, 0, 1, 1]] <ide><path>transformers/model_card.py <add># coding=utf-8 <add># Copyright 2018 The HuggingFace Inc. team. <add># <add># Licensed under the Apache License, Version 2.0 (the "License"); <add># you may not use this file except in compliance with the License. <add># 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>""" Configuration base class and utilities.""" <add> <add>from __future__ import (absolute_import, division, print_function, <add> unicode_literals) <add> <add>import copy <add>import json <add>import logging <add>import os <add>import re <add>from io import open <add> <add>from .configuration_bert import BERT_PRETRAINED_CONFIG_ARCHIVE_MAP <add>from .configuration_openai import OPENAI_GPT_PRETRAINED_CONFIG_ARCHIVE_MAP <add>from .configuration_transfo_xl import TRANSFO_XL_PRETRAINED_CONFIG_ARCHIVE_MAP <add>from .configuration_gpt2 import GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP <add>from .configuration_ctrl import CTRL_PRETRAINED_CONFIG_ARCHIVE_MAP <add>from .configuration_xlnet import XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP <add>from .configuration_xlm import XLM_PRETRAINED_CONFIG_ARCHIVE_MAP <add>from .configuration_roberta import ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP <add>from .configuration_distilbert import DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP <add>from .configuration_albert import ALBERT_PRETRAINED_CONFIG_ARCHIVE_MAP <add>from .configuration_camembert import CAMEMBERT_PRETRAINED_CONFIG_ARCHIVE_MAP <add>from .configuration_t5 import T5_PRETRAINED_CONFIG_ARCHIVE_MAP <add> <add>from .file_utils import CONFIG_NAME, MODEL_CARD_NAME, cached_path, is_remote_url, hf_bucket_url <add> <add> <add>logger = logging.getLogger(__name__) <add> <add> <add>ALL_MODELS_MAP = dict((key, value) <add> for pretrained_map in [ <add> BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, <add> OPENAI_GPT_PRETRAINED_CONFIG_ARCHIVE_MAP, <add> TRANSFO_XL_PRETRAINED_CONFIG_ARCHIVE_MAP, <add> GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP, <add> CTRL_PRETRAINED_CONFIG_ARCHIVE_MAP, <add> XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP, <add> XLM_PRETRAINED_CONFIG_ARCHIVE_MAP, <add> ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, <add> DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, <add> ALBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, <add> CAMEMBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, <add> T5_PRETRAINED_CONFIG_ARCHIVE_MAP, <add> ] <add> for key, value, in pretrained_map.items()) <add> <add> <add>class ModelCard(object): <add> r""" Model Card class. <add> Store model card as well as methods for loading/downloading/saving model cards. <add> <add> Please read the following paper for details and explanation on the sections: <add> "Model Cards for Model Reporting" <add> by Margaret Mitchell, Simone Wu, <add> Andrew Zaldivar, Parker Barnes, Lucy Vasserman, Ben Hutchinson, Elena Spitzer, <add> Inioluwa Deborah Raji and Timnit Gebru for the proposal behind model cards. <add> Link: https://arxiv.org/abs/1810.03993 <add> <add> Note: <add> A model card can be loaded and saved to disk. <add> <add> Parameters: <add> """ <add> def __init__(self, **kwargs): <add> # Recomended attributes from https://arxiv.org/abs/1810.03993 (see papers) <add> self.model_details = kwargs.pop('model_details', {}) <add> self.intended_use = kwargs.pop('intended_use', {}) <add> self.factors = kwargs.pop('factors', {}) <add> self.metrics = kwargs.pop('metrics', {}) <add> self.evaluation_data = kwargs.pop('evaluation_data', {}) <add> self.training_data = kwargs.pop('training_data', {}) <add> self.quantitative_analyses = kwargs.pop('quantitative_analyses', {}) <add> self.ethical_considerations = kwargs.pop('ethical_considerations', {}) <add> self.caveats_and_recommendations = kwargs.pop('caveats_and_recommendations', {}) <add> <add> # Open additional attributes <add> for key, value in kwargs.items(): <add> try: <add> setattr(self, key, value) <add> except AttributeError as err: <add> logger.error("Can't set {} with value {} for {}".format(key, value, self)) <add> raise err <add> <add> def save_pretrained(self, save_directory): <add> """ Save a model card object to the directory `save_directory`, so that it <add> can be re-loaded using the :func:`~transformers.ModelCard.from_pretrained` class method. <add> """ <add> assert os.path.isdir(save_directory), "Saving path should be a directory where the model card can be saved" <add> <add> # If we save using the predefined names, we can load using `from_pretrained` <add> output_model_card_file = os.path.join(save_directory, MODEL_CARD_NAME) <add> <add> self.to_json_file(output_model_card_file) <add> logger.info("Model card saved in {}".format(output_model_card_file)) <add> <add> @classmethod <add> def from_pretrained(cls, pretrained_model_name_or_path, **kwargs): <add> r""" Instantiate a :class:`~transformers.ModelCard` from a pre-trained model model card. <add> <add> Parameters: <add> pretrained_model_name_or_path: either: <add> <add> - a string with the `shortcut name` of a pre-trained model card to load from cache or download, e.g.: ``bert-base-uncased``. <add> - a string with the `identifier name` of a pre-trained model card that was user-uploaded to our S3, e.g.: ``dbmdz/bert-base-german-cased``. <add> - a path to a `directory` containing a mode card file saved using the :func:`~transformers.ModelCard.save_pretrained` method, e.g.: ``./my_model_directory/``. <add> - a path or url to a saved model card JSON `file`, e.g.: ``./my_model_directory/model_card.json``. <add> <add> cache_dir: (`optional`) string: <add> Path to a directory in which a downloaded pre-trained model <add> card should be cached if the standard cache should not be used. <add> <add> kwargs: (`optional`) dict: key/value pairs with which to update the ModelCard object after loading. <add> <add> - The values in kwargs of any keys which are model card attributes will be used to override the loaded values. <add> - Behavior concerning key/value pairs whose keys are *not* model card attributes is controlled by the `return_unused_kwargs` keyword parameter. <add> <add> force_download: (`optional`) boolean, default False: <add> Force to (re-)download the model card file and override the cached version if it exists. <add> <add> resume_download: (`optional`) boolean, default False: <add> Do not delete incompletely recieved file. Attempt to resume the download if such a file exists. <add> <add> proxies: (`optional`) dict, default None: <add> A dictionary of proxy servers to use by protocol or endpoint, e.g.: {'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}. <add> The proxies are used on each request. <add> <add> return_unused_kwargs: (`optional`) bool: <add> <add> - If False, then this function returns just the final model card object. <add> - If True, then this functions returns a tuple `(model card, unused_kwargs)` where `unused_kwargs` is a dictionary consisting of the key/value pairs whose keys are not model card attributes: ie the part of kwargs which has not been used to update `ModelCard` and is otherwise ignored. <add> <add> Examples:: <add> <add> model_card = ModelCard.from_pretrained('bert-base-uncased') # Download model card from S3 and cache. <add> model_card = ModelCard.from_pretrained('./test/saved_model/') # E.g. model card was saved using `save_pretrained('./test/saved_model/')` <add> model_card = ModelCard.from_pretrained('./test/saved_model/model_card.json') <add> model_card = ModelCard.from_pretrained('bert-base-uncased', output_attention=True, foo=False) <add> <add> """ <add> cache_dir = kwargs.pop('cache_dir', None) <add> force_download = kwargs.pop('force_download', False) <add> resume_download = kwargs.pop('resume_download', False) <add> proxies = kwargs.pop('proxies', None) <add> return_unused_kwargs = kwargs.pop('return_unused_kwargs', False) <add> <add> if pretrained_model_name_or_path in ALL_MODELS_MAP: <add> model_card_file = ALL_MODELS_MAP[pretrained_model_name_or_path] <add> model_card_file.replace(CONFIG_NAME, MODEL_CARD_NAME) # For simplicity we use the same pretrained url than config but with a different suffix <add> elif os.path.isdir(pretrained_model_name_or_path): <add> model_card_file = os.path.join(pretrained_model_name_or_path, MODEL_CARD_NAME) <add> elif os.path.isfile(pretrained_model_name_or_path) or is_remote_url(pretrained_model_name_or_path): <add> model_card_file = pretrained_model_name_or_path <add> else: <add> model_card_file = hf_bucket_url(pretrained_model_name_or_path, postfix=MODEL_CARD_NAME) <add> # redirect to the cache, if necessary <add> try: <add> resolved_model_card_file = cached_path(model_card_file, cache_dir=cache_dir, force_download=force_download, <add> proxies=proxies, resume_download=resume_download) <add> <add> if resolved_model_card_file == model_card_file: <add> logger.info("loading model card file {}".format(model_card_file)) <add> else: <add> logger.info("loading model card file {} from cache at {}".format( <add> model_card_file, resolved_model_card_file)) <add> <add> # Load model card <add> model_card = cls.from_json_file(resolved_model_card_file) <add> <add> except EnvironmentError: <add> if pretrained_model_name_or_path in ALL_MODELS_MAP: <add> logger.warning("Couldn't reach server at '{}' to download model card file.".format( <add> model_card_file)) <add> else: <add> logger.warning("Model name '{}' was not found in model name list ({}). " \ <add> "We assumed '{}' was a path or url to a model card file named {} or " \ <add> "a directory containing such a file but couldn't find any such file at this path or url.".format( <add> pretrained_model_name_or_path, <add> ', '.join(ALL_MODELS_MAP.keys()), <add> model_card_file, MODEL_CARD_NAME)) <add> <add> logger.warning("Creating an empty model card.") <add> <add> # We fall back on creating an empty model card <add> model_card = cls() <add> <add> # Update model card with kwargs if needed <add> to_remove = [] <add> for key, value in kwargs.items(): <add> if hasattr(model_card, key): <add> setattr(model_card, key, value) <add> to_remove.append(key) <add> for key in to_remove: <add> kwargs.pop(key, None) <add> <add> logger.info("Model card: %s", str(model_card)) <add> if return_unused_kwargs: <add> return model_card, kwargs <add> else: <add> return model_card <add> <add> @classmethod <add> def from_dict(cls, json_object): <add> """Constructs a `ModelCard` from a Python dictionary of parameters.""" <add> return cls(**json_object) <add> <add> @classmethod <add> def from_json_file(cls, json_file): <add> """Constructs a `ModelCard` from a json file of parameters.""" <add> with open(json_file, "r", encoding='utf-8') as reader: <add> text = reader.read() <add> dict_obj = json.loads(text) <add> return cls(**dict_obj) <add> <add> def __eq__(self, other): <add> return self.__dict__ == other.__dict__ <add> <add> def __repr__(self): <add> return str(self.to_json_string()) <add> <add> def to_dict(self): <add> """Serializes this instance to a Python dictionary.""" <add> output = copy.deepcopy(self.__dict__) <add> return output <add> <add> def to_json_string(self): <add> """Serializes this instance to a JSON string.""" <add> return json.dumps(self.to_dict(), indent=2, sort_keys=True) + "\n" <add> <add> def to_json_file(self, json_file_path): <add> """ Save this instance to a json file.""" <add> with open(json_file_path, "w", encoding='utf-8') as writer: <add> writer.write(self.to_json_string()) <ide><path>transformers/tests/model_card_test.py <add># coding=utf-8 <add># Copyright 2019 HuggingFace Inc. <add># <add># Licensed under the Apache License, Version 2.0 (the "License"); <add># you may not use this file except in compliance with the License. <add># 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>from __future__ import absolute_import, division, print_function, unicode_literals <add> <add>import os <add>import sys <add>import json <add>import tempfile <add>import shutil <add>import unittest <add> <add>from transformers.model_card import ModelCard <add>from .tokenization_tests_commons import TemporaryDirectory <add> <add>class ModelCardTester(unittest.TestCase): <add> <add> def setUp(self): <add> self.inputs_dict = {'model_details': { <add> 'Organization': 'testing', <add> 'Model date': 'today', <add> 'Model version': 'v2.1, Developed by Test Corp in 2019.', <add> 'Architecture': 'Convolutional Neural Network.', <add> }, <add> 'metrics': 'BLEU and ROUGE-1', <add> 'evaluation_data':{ <add> 'Datasets':{ <add> 'BLEU': 'My-great-dataset-v1', <add> 'ROUGE-1': 'My-short-dataset-v2.1', <add> }, <add> 'Preprocessing': 'See details on https://arxiv.org/pdf/1810.03993.pdf' <add> }, <add> 'training_data':{ <add> 'Dataset': 'English Wikipedia dump dated 2018-12-01', <add> 'Preprocessing': 'Using SentencePiece vocabulary of size 52k tokens. See details on https://arxiv.org/pdf/1810.03993.pdf' <add> }, <add> 'quantitative_analyses': { <add> 'BLEU': 55.1, <add> 'ROUGE-1': 76, <add> }, <add> } <add> self.tmpdirname = tempfile.mkdtemp() <add> <add> def tearDown(self): <add> shutil.rmtree(self.tmpdirname) <add> <add> def test_model_card_common_properties(self): <add> model_card = ModelCard.from_dict(self.inputs_dict) <add> self.assertTrue(hasattr(model_card, 'model_details')) <add> self.assertTrue(hasattr(model_card, 'intended_use')) <add> self.assertTrue(hasattr(model_card, 'factors')) <add> self.assertTrue(hasattr(model_card, 'metrics')) <add> self.assertTrue(hasattr(model_card, 'evaluation_data')) <add> self.assertTrue(hasattr(model_card, 'training_data')) <add> self.assertTrue(hasattr(model_card, 'quantitative_analyses')) <add> self.assertTrue(hasattr(model_card, 'ethical_considerations')) <add> self.assertTrue(hasattr(model_card, 'caveats_and_recommendations')) <add> <add> def test_model_card_to_json_string(self): <add> model_card = ModelCard.from_dict(self.inputs_dict) <add> obj = json.loads(model_card.to_json_string()) <add> for key, value in self.inputs_dict.items(): <add> self.assertEqual(obj[key], value) <add> <add> def test_model_card_to_json_file(self): <add> model_card_first = ModelCard.from_dict(self.inputs_dict) <add> <add> with TemporaryDirectory() as tmpdirname: <add> filename = os.path.join(tmpdirname, u"model_card.json") <add> model_card_first.to_json_file(filename) <add> model_card_second = ModelCard.from_json_file(filename) <add> <add> self.assertEqual(model_card_second.to_dict(), model_card_first.to_dict()) <add> <add>if __name__ == "__main__": <add> unittest.main()
4
Go
Go
add constructors for each parser
28b0f47599e9ff32d2abebb54ee4b2a60977f722
<ide><path>volume/mounts/lcow_parser.go <ide> import ( <ide> "github.com/docker/docker/api/types/mount" <ide> ) <ide> <add>// NewLCOWParser creates a parser with Linux Containers on Windows semantics. <add>func NewLCOWParser() Parser { <add> return &lcowParser{} <add>} <add> <ide> // rxLCOWDestination is the regex expression for the mount destination for LCOW <ide> // <ide> // Destination (aka container path): <ide><path>volume/mounts/lcow_parser_test.go <ide> func TestLCOWParseMountRaw(t *testing.T) { <ide> `\\.\pipe\foo:/foo`: `Linux containers on Windows do not support named pipe mounts`, <ide> } <ide> <del> parser := &lcowParser{} <add> parser := NewLCOWParser() <ide> <ide> for _, path := range valid { <ide> if _, err := parser.ParseMountRaw(path, "local"); err != nil { <ide> func TestLCOWParseMountRawSplit(t *testing.T) { <ide> {`c:\foo\bar:\\.\pipe\foo`, "local", mount.TypeNamedPipe, ``, ``, "", "", true, true}, <ide> } <ide> <del> parser := &lcowParser{} <add> parser := NewLCOWParser() <ide> for i, c := range cases { <ide> t.Logf("case %d", i) <ide> m, err := parser.ParseMountRaw(c.bind, c.driver) <ide><path>volume/mounts/linux_parser.go <ide> import ( <ide> "github.com/docker/docker/volume" <ide> ) <ide> <add>// NewLinuxParser creates a parser with Linux semantics. <add>func NewLinuxParser() Parser { <add> return &linuxParser{} <add>} <add> <ide> type linuxParser struct{} <ide> <ide> func linuxSplitRawSpec(raw string) ([]string, error) { <ide><path>volume/mounts/linux_parser_test.go <ide> func TestLinuxParseMountRaw(t *testing.T) { <ide> "name:/absolute-path:rprivate": "invalid volume specification", <ide> } <ide> <del> parser := &linuxParser{} <add> parser := NewLinuxParser() <ide> <ide> for _, path := range valid { <ide> if _, err := parser.ParseMountRaw(path, "local"); err != nil { <ide> func TestLinuxParseMountRawSplit(t *testing.T) { <ide> {"/tmp:tmp", "", mount.TypeBind, "", "", "", "", true, true}, <ide> } <ide> <del> parser := &linuxParser{} <add> parser := NewLinuxParser() <ide> for i, c := range cases { <ide> t.Logf("case %d", i) <ide> m, err := parser.ParseMountRaw(c.bind, c.driver) <ide> func TestLinuxParseMountSpecBindWithFileinfoError(t *testing.T) { <ide> testErr := fmt.Errorf("some crazy error") <ide> currentFileInfoProvider = &mockFiProviderWithError{err: testErr} <ide> <del> parser := &linuxParser{} <add> parser := NewLinuxParser() <ide> <ide> _, err := parser.ParseMountSpec(mount.Mount{ <ide> Type: mount.TypeBind, <ide> func TestConvertTmpfsOptions(t *testing.T) { <ide> unexpectedSubstrings: []string{}, <ide> }, <ide> } <del> p := &linuxParser{} <add> p := NewLinuxParser() <ide> for _, c := range cases { <ide> data, err := p.ConvertTmpfsOptions(&c.opt, c.readOnly) <ide> if err != nil { <ide><path>volume/mounts/parser.go <ide> type Parser interface { <ide> // NewParser creates a parser for the current host OS <ide> func NewParser() Parser { <ide> if runtime.GOOS == "windows" { <del> return &windowsParser{} <add> return NewWindowsParser() <ide> } <del> return &linuxParser{} <add> return NewLinuxParser() <ide> } <ide><path>volume/mounts/validate_test.go <ide> func TestValidateMount(t *testing.T) { <ide> } <ide> } <ide> if runtime.GOOS == "windows" { <del> parser = &lcowParser{} <add> parser = NewLCOWParser() <ide> for i, x := range lcowCases { <ide> err := parser.ValidateMountConfig(&x.input) <ide> if err == nil && x.expected == nil { <ide><path>volume/mounts/windows_parser.go <ide> import ( <ide> "github.com/docker/docker/pkg/stringid" <ide> ) <ide> <add>// NewWindowsParser creates a parser with Windows semantics. <add>func NewWindowsParser() Parser { <add> return &windowsParser{} <add>} <add> <ide> type windowsParser struct{} <ide> <ide> const ( <ide><path>volume/mounts/windows_parser_test.go <ide> func TestWindowsParseMountRaw(t *testing.T) { <ide> `\\.\pipe\foo:c:\pipe`: `'c:\pipe' is not a valid pipe path`, <ide> } <ide> <del> parser := &windowsParser{} <add> parser := NewWindowsParser() <ide> <ide> for _, path := range valid { <ide> if _, err := parser.ParseMountRaw(path, "local"); err != nil { <ide> func TestWindowsParseMountRawSplit(t *testing.T) { <ide> {`c:\foo\bar:\\.\pipe\foo`, "local", mount.TypeNamedPipe, ``, ``, "", "", true, true}, <ide> } <ide> <del> parser := &windowsParser{} <add> parser := NewWindowsParser() <ide> for i, c := range cases { <ide> t.Logf("case %d", i) <ide> m, err := parser.ParseMountRaw(c.bind, c.driver) <ide> func TestWindowsParseMountSpecBindWithFileinfoError(t *testing.T) { <ide> testErr := fmt.Errorf("some crazy error") <ide> currentFileInfoProvider = &mockFiProviderWithError{err: testErr} <ide> <del> parser := &windowsParser{} <add> parser := NewWindowsParser() <ide> <ide> _, err := parser.ParseMountSpec(mount.Mount{ <ide> Type: mount.TypeBind,
8
Python
Python
improve ability to fit models w/o external data
e90b0713f2e86f9f540b57b4306a77e3f696213b
<ide><path>keras/engine/topology.py <ide> def losses(self): <ide> A list of loss tensors. <ide> """ <ide> losses = [] <add> # Retrieve losses for all internal layers. <ide> for layer in self.layers: <ide> if hasattr(layer, 'losses'): <ide> if len(layer.inbound_nodes) == 1: <ide> def losses(self): <ide> losses += layer.get_losses_for(inputs) <ide> # Collect unconditional losses. <ide> losses += layer.get_losses_for(None) <add> # Add any potential unconditional model-level loss. <add> if hasattr(self, '_per_input_losses'): <add> losses += self._per_input_losses.get(None, []) <ide> return losses <ide> <ide> @property <ide><path>keras/engine/training.py <ide> def _fit_loop(self, f, ins, out_labels=None, batch_size=32, <ide> print('Train on %d samples, validate on %d samples' % <ide> (ins[0].shape[0], val_ins[0].shape[0])) <ide> <del> num_train_samples = ins[0].shape[0] <add> if ins and hasattr(ins[0], 'shape'): <add> num_train_samples = ins[0].shape[0] <add> else: <add> # May happen if we are running `fit` without Numpy input data, <add> # i.e. if all inputs to the models are data tensors <add> # instead of placeholders. <add> # In that case we will run `fit` over a single batch. <add> num_train_samples = batch_size <add> verbose = 2 <ide> index_array = np.arange(num_train_samples) <ide> <ide> self.history = cbks.History() <ide> def _test_loop(self, f, ins, batch_size=32, verbose=0): <ide> and/or metrics). The attribute `model.metrics_names` will give you <ide> the display labels for the scalar outputs. <ide> """ <del> samples = ins[0].shape[0] <add> if ins and hasattr(ins[0], 'shape'): <add> samples = ins[0].shape[0] <add> else: <add> # May happen if we are running `evaluate` without Numpy input data, <add> # i.e. if all inputs to the models are data tensors <add> # instead of placeholders. <add> # In that case we will run `evaluate` over a single batch. <add> samples = batch_size <add> verbose = 2 <add> <ide> outs = [] <ide> if verbose == 1: <ide> progbar = Progbar(target=samples) <ide><path>tests/keras/engine/test_training.py <ide> def test_model_with_input_feed_tensor(): <ide> # Now test a model with a single input <ide> # i.e. we don't pass any data to fit the model. <ide> a = Input(tensor=tf.Variable(input_a_np, dtype=tf.float32)) <del> <ide> a_2 = Dense(4, name='dense_1')(a) <ide> a_2 = Dropout(0.5, name='dropout')(a_2) <del> <ide> model = Model(a, a_2) <ide> model.summary() <ide> <ide> def test_model_with_input_feed_tensor(): <ide> # Same, without learning phase <ide> # i.e. we don't pass any data to fit the model. <ide> a = Input(tensor=tf.Variable(input_a_np, dtype=tf.float32)) <del> <ide> a_2 = Dense(4, name='dense_1')(a) <del> <ide> model = Model(a, a_2) <ide> model.summary() <ide> <ide> def test_model_with_input_feed_tensor(): <ide> @keras_test <ide> def test_model_with_partial_loss(): <ide> a = Input(shape=(3,), name='input_a') <del> <ide> a_2 = Dense(4, name='dense_1')(a) <ide> dp = Dropout(0.5, name='dropout') <ide> a_3 = dp(a_2) <del> <ide> model = Model(a, [a_2, a_3]) <ide> <ide> optimizer = 'rmsprop' <ide> loss = {'dropout': 'mse'} <del> model.compile(optimizer, loss, metrics=['mae'], <del> sample_weight_mode=None) <add> model.compile(optimizer, loss, metrics=['mae']) <ide> <ide> input_a_np = np.random.random((10, 3)) <ide> output_a_np = np.random.random((10, 4)) <ide> def test_model_with_partial_loss(): <ide> # evaluate <ide> out = model.evaluate(input_a_np, [output_a_np]) <ide> <add> # Same without dropout. <add> a = Input(shape=(3,), name='input_a') <add> a_2 = Dense(4, name='dense_1')(a) <add> a_3 = Dense(4, name='dense_2')(a_2) <add> model = Model(a, [a_2, a_3]) <add> <add> optimizer = 'rmsprop' <add> loss = {'dense_2': 'mse'} <add> model.compile(optimizer, loss, metrics={'dense_1': 'mae'}) <add> <add> # test train_on_batch <add> out = model.train_on_batch(input_a_np, output_a_np) <add> out = model.test_on_batch(input_a_np, output_a_np) <add> # fit <add> out = model.fit(input_a_np, [output_a_np]) <add> # evaluate <add> out = model.evaluate(input_a_np, [output_a_np]) <add> <add> <add>@keras_test <add>def test_model_with_external_loss(): <add> # None loss, only regularization loss. <add> a = Input(shape=(3,), name='input_a') <add> a_2 = Dense(4, name='dense_1', <add> kernel_regularizer='l1', <add> bias_regularizer='l2')(a) <add> dp = Dropout(0.5, name='dropout') <add> a_3 = dp(a_2) <add> <add> model = Model(a, [a_2, a_3]) <add> <add> optimizer = 'rmsprop' <add> loss = None <add> model.compile(optimizer, loss, metrics=['mae']) <add> <add> input_a_np = np.random.random((10, 3)) <add> <add> # test train_on_batch <add> out = model.train_on_batch(input_a_np, None) <add> out = model.test_on_batch(input_a_np, None) <add> # fit <add> out = model.fit(input_a_np, None) <add> # evaluate <add> out = model.evaluate(input_a_np, None) <add> <add> # No dropout, external loss. <add> a = Input(shape=(3,), name='input_a') <add> a_2 = Dense(4, name='dense_1')(a) <add> a_3 = Dense(4, name='dense_2')(a) <add> <add> model = Model(a, [a_2, a_3]) <add> model.add_loss(K.mean(a_3 + a_2)) <add> <add> optimizer = 'rmsprop' <add> loss = None <add> model.compile(optimizer, loss, metrics=['mae']) <add> <add> # test train_on_batch <add> out = model.train_on_batch(input_a_np, None) <add> out = model.test_on_batch(input_a_np, None) <add> # fit <add> out = model.fit(input_a_np, None) <add> # evaluate <add> out = model.evaluate(input_a_np, None) <add> <add> # Test fit with no external data at all. <add> if K.backend() == 'tensorflow': <add> import tensorflow as tf <add> <add> a = Input(tensor=tf.Variable(input_a_np, dtype=tf.float32)) <add> a_2 = Dense(4, name='dense_1')(a) <add> a_2 = Dropout(0.5, name='dropout')(a_2) <add> model = Model(a, a_2) <add> model.add_loss(K.mean(a_2)) <add> <add> model.compile(optimizer='rmsprop', <add> loss=None, <add> metrics=['mean_squared_error']) <add> <add> # test train_on_batch <add> out = model.train_on_batch(None, None) <add> out = model.test_on_batch(None, None) <add> out = model.predict_on_batch(None) <add> <add> # test fit <add> out = model.fit(None, None, epochs=1, batch_size=10) <add> <add> # test evaluate <add> out = model.evaluate(None, None, batch_size=10) <add> <add> # test predict <add> out = model.predict(None, batch_size=10) <add> assert out.shape == (10, 4) <add> <ide> <ide> if __name__ == '__main__': <del> pytest.main([__file__]) <add> pytest.main([__file__])
3
Javascript
Javascript
solve last mini-css-plugin webpack 5 warning
b6a2051d49fc0b3148a26d7d4d5a80385a81bba4
<ide><path>packages/next/build/webpack/plugins/mini-css-extract-plugin/src/CssModule.js <ide> class CssModule extends webpack.Module { <ide> callback() <ide> } <ide> <del> updateHash(hash) { <del> super.updateHash(hash) <add> updateHash(hash, context) { <add> super.updateHash(hash, context) <ide> hash.update(this.content) <ide> hash.update(this.media || '') <ide> hash.update(this.sourceMap ? JSON.stringify(this.sourceMap) : '')
1
Javascript
Javascript
remove unused valiables
79fbf54d903d266abcb771ac63971ccb68479158
<ide><path>packages/ember-application/lib/system/application.js <ide> @submodule ember-application <ide> */ <ide> <del>var get = Ember.get, set = Ember.set, <del> classify = Ember.String.classify, <del> capitalize = Ember.String.capitalize, <del> decamelize = Ember.String.decamelize; <add>var get = Ember.get, set = Ember.set; <ide> <ide> /** <ide> An instance of `Ember.Application` is the starting point for every Ember
1
Text
Text
update ap changelog
44bc45b0141ef0c23143fe89b7711c296d883c4d
<ide><path>actionpack/CHANGELOG.md <add>* Introduce `BasicRendering` which is the most basic rendering implementation. It <add> allows to `render :text` and `render :nothing` without need of having ActionView. <add> <add> *Łukasz Strzałkowski* <add> <add>* Separate ActionView completely from ActionPack. <add> <add> *Łukasz Strzałkowski* <add> <ide> * Development mode exceptions are rendered in text format in case of XHR request. <ide> <ide> *Kir Shatrov*
1
Javascript
Javascript
avoid input param manipulation
217acb9036f39ea6088cee75f70f11602997e15f
<ide><path>benchmark/assert/deepequal-object.js <ide> function createObj(source, add = '') { <ide> } <ide> <ide> function main({ size, n, method, strict }) { <del> // TODO: Fix this "hack". `n` should not be manipulated. <del> n = Math.min(Math.ceil(n / size), 20); <add> const len = Math.min(Math.ceil(n / size), 20); <ide> <ide> const source = Array.apply(null, Array(size)); <ide> const actual = createObj(source); <ide> function main({ size, n, method, strict }) { <ide> const value2 = method.includes('not') ? expectedWrong : expected; <ide> <ide> bench.start(); <del> for (let i = 0; i < n; ++i) { <add> for (let i = 0; i < len; ++i) { <ide> fn(actual, value2); <ide> } <del> bench.end(n); <add> bench.end(len); <ide> }
1
Javascript
Javascript
remove errant debugger call in spec
9d553d2cfa7b9abc1aafa6ef3aedd257564aca5b
<ide><path>spec/history-manager-spec.js <ide> describe("HistoryManager", () => { <ide> }) <ide> <ide> it("returns null when it can't find the project", () => { <del> debugger <ide> const project = historyManager.getProject(['/1']) <ide> expect(project).toBeNull() <ide> })
1
Text
Text
reword docs and revert some changes
790cbb672df139514134160a9649d8d626096796
<ide><path>object_detection/g3doc/preparing_inputs.md <ide> TFRecords. <ide> <ide> ## Generating the PASCAL VOC TFRecord files. <ide> <del>The raw 2012 PASCAL VOC data set can be downloaded <del>[here](http://host.robots.ox.ac.uk/pascal/VOC/voc2012/VOCtrainval_11-May-2012.tar), <del>or by using the command below. <del>Extract the tar file and run the `create_pascal_tf_record` script: <add>The raw 2012 PASCAL VOC data set is located <add>[here](http://host.robots.ox.ac.uk/pascal/VOC/voc2012/VOCtrainval_11-May-2012.tar). <add>To download, extract and convert it to TFRecords, run the following commands <add>below: <ide> <ide> ```bash <ide> # From tensorflow/models <ide> python object_detection/create_pascal_tf_record.py \ <ide> You should end up with two TFRecord files named `pascal_train.record` and <ide> `pascal_val.record` in the `tensorflow/models` directory. <ide> <add>The label map for the PASCAL VOC data set can be found at <add>`object_detection/data/pascal_label_map.pbtxt`. <add> <ide> ## Generating the Oxford-IIIT Pet TFRecord files. <ide> <del>The Oxford-IIIT Pet data set can be downloaded from <del>[their website](http://www.robots.ox.ac.uk/~vgg/data/pets/), or by using the <del>command below. Extract the tar file and run the `create_pet_tf_record` script <del>to generate TFRecords. <add>The Oxford-IIIT Pet data set is located on <add>[their website](http://www.robots.ox.ac.uk/~vgg/data/pets/). <add>To download, extract and convert it to TFRecrods, run the following commands <add>below: <ide> <ide> ```bash <ide> # From tensorflow/models <ide> python object_detection/create_pet_tf_record.py \ <ide> <ide> You should end up with two TFRecord files named `pet_train.record` and <ide> `pet_val.record` in the `tensorflow/models` directory. <add> <add>The label map for the Pet dataset can be found at <add>`object_detection/data/pet_label_map.pbtxt`.
1
Text
Text
update filtering chapters on ps/images references
61de442c49a56f9fc6f82174c97e1229e8aa39f2
<ide><path>docs/reference/commandline/images.md <ide> The currently supported filters are: <ide> * dangling (boolean - true or false) <ide> * label (`label=<key>` or `label=<key>=<value>`) <ide> <del>##### Untagged images <add>##### Untagged images (dangling) <ide> <ide> $ docker images --filter "dangling=true" <ide> <ide> Ready for use by `docker rmi ...`, like: <ide> NOTE: Docker will warn you if any containers exist that are using these untagged images. <ide> <ide> <add>##### Labeled images <add> <add>The `label` filter matches images based on the presence of a `label` alone or a `label` and a <add>value. <add> <add>The following filter matches images with the `com.example.version` label regardless of its value. <add> <add> $ docker images --filter "label=com.example.version" <add> <add> REPOSITORY TAG IMAGE ID CREATED VIRTUAL SIZE <add> match-me-1 latest eeae25ada2aa About a minute ago 188.3 MB <add> match-me-2 latest eeae25ada2aa About a minute ago 188.3 MB <add> <add>The following filter matches images with the `com.example.version` label with the `1.0` value. <add> <add> $ docker images --filter "label=com.example.version=1.0" <add> REPOSITORY TAG IMAGE ID CREATED VIRTUAL SIZE <add> match-me latest eeae25ada2aa About a minute ago 188.3 MB <add> <add>In this example, with the `0.1` value, it returns an empty set because no matches were found. <add> <add> $ docker images --filter "label=com.example.version=0.1" <add> REPOSITORY TAG IMAGE ID CREATED VIRTUAL SIZE <add> <ide><path>docs/reference/commandline/ps.md <ide> The currently supported filters are: <ide> * exited (int - the code of exited containers. Only useful with `--all`) <ide> * status (created|restarting|running|paused|exited) <ide> <del>## Successfully exited containers <add> <add>#### Label <add> <add>The `label` filter matches containers based on the presence of a `label` alone or a `label` and a <add>value. <add> <add>The following filter matches containers with the `color` label regardless of its value. <add> <add> $ docker ps --filter "label=color" <add> CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES <add> 673394ef1d4c busybox "top" 47 seconds ago Up 45 seconds nostalgic_shockley <add> d85756f57265 busybox "top" 52 seconds ago Up 51 seconds high_albattani <add> <add>The following filter matches containers with the `color` label with the `blue` value. <add> <add> $ docker ps --filter "label=color=blue" <add> CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES <add> d85756f57265 busybox "top" About a minute ago Up About a minute high_albattani <add> <add>#### Name <add> <add>The `name` filter matches on all or part of a container's name. <add> <add>The following filter matches all containers with a name containing the `nostalgic_stallman` string. <add> <add> $ docker ps --filter "name=nostalgic_stallman" <add> CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES <add> 9b6247364a03 busybox "top" 2 minutes ago Up 2 minutes nostalgic_stallman <add> <add>You can also filter for a substring in a name as this shows: <add> <add> $ docker ps --filter "name=nostalgic" <add> CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES <add> 715ebfcee040 busybox "top" 3 seconds ago Up 1 seconds i_am_nostalgic <add> 9b6247364a03 busybox "top" 7 minutes ago Up 7 minutes nostalgic_stallman <add> 673394ef1d4c busybox "top" 38 minutes ago Up 38 minutes nostalgic_shockley <add> <add>#### Exited <add> <add>The `exited` filter matches containers by exist status code. For example, to filter for containers <add>that have exited successfully: <ide> <ide> $ docker ps -a --filter 'exited=0' <ide> CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES <ide> ea09c3c82f6e registry:latest /srv/run.sh 2 weeks ago Exited (0) 2 weeks ago 127.0.0.1:5000->5000/tcp desperate_leakey <ide> 106ea823fe4e fedora:latest /bin/sh -c 'bash -l' 2 weeks ago Exited (0) 2 weeks ago determined_albattani <ide> 48ee228c9464 fedora:20 bash 2 weeks ago Exited (0) 2 weeks ago tender_torvalds <ide> <del>This shows all the containers that have exited with status of '0' <add>#### Status <add> <add>The `status` filter matches containers by status. You can filter using `created`, `restarting`, `running`, `paused` and `exited`. For example, to filter for `running` containers: <add> <add> $ docker ps --filter status=running <add> CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES <add> 715ebfcee040 busybox "top" 16 minutes ago Up 16 minutes i_am_nostalgic <add> d5c976d3c462 busybox "top" 23 minutes ago Up 23 minutes top <add> 9b6247364a03 busybox "top" 24 minutes ago Up 24 minutes nostalgic_stallman <add> <add>To filter for `paused` containers: <add> <add> $ docker ps --filter status=paused <add> CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES <add> 673394ef1d4c busybox "top" About an hour ago Up About an hour (Paused) nostalgic_shockley <add> <add>#### Ancestor <add> <add>The `ancestor` filter matches containers based on its image or a descendant of it. The filter supports the <add>following image representation: <add> <add>- image <add>- image:tag <add>- image:tag@digest <add>- short-id <add>- full-id <add> <add>If you don't specify a `tag`, the `latest` tag is used. For example, to filter for containers that use the <add>latest `ubuntu` image: <add> <add> $ docker ps --filter ancestor=ubuntu <add> CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES <add> 919e1179bdb8 ubuntu-c1 "top" About a minute ago Up About a minute admiring_lovelace <add> 5d1e4a540723 ubuntu-c2 "top" About a minute ago Up About a minute admiring_sammet <add> 82a598284012 ubuntu "top" 3 minutes ago Up 3 minutes sleepy_bose <add> bab2a34ba363 ubuntu "top" 3 minutes ago Up 3 minutes focused_yonath <add> <add>Match containers based on the `ubuntu-c1` image which, in this case, is a child of `ubuntu`: <add> <add> $ docker ps --filter ancestor=ubuntu-c1 <add> CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES <add> 919e1179bdb8 ubuntu-c1 "top" About a minute ago Up About a minute admiring_lovelace <add> <add>Match containers based on the `ubuntu` version `12.04.5` image: <add> <add> $ docker ps --filter ancestor=ubuntu:12.04.5 <add> CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES <add> 82a598284012 ubuntu:12.04.5 "top" 3 minutes ago Up 3 minutes sleepy_bose <add> <add>The following matches containers based on the layer `d0e008c6cf02` or an image that have this layer <add>in it's layer stack. <add> <add> $ docker ps --filter ancestor=d0e008c6cf02 <add> CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES <add> 82a598284012 ubuntu:12.04.5 "top" 3 minutes ago Up 3 minutes sleepy_bose <add> <ide> <ide> ## Formatting <ide>
2
Ruby
Ruby
perform details matching on unboundtemplates
9e0c42b0bde91da41745e2bcf4a14bfefdc72fc0
<ide><path>actionpack/test/controller/mime/respond_to_test.rb <ide> def setup <ide> Mime::Type.register("text/x-mobile", :mobile) <ide> Mime::Type.register("application/fancy-xml", :fancy_xml) <ide> Mime::Type.register("text/html; fragment", :html_fragment) <add> ActionView::LookupContext::DetailsKey.clear <ide> end <ide> <ide> def teardown <ide> def teardown <ide> Mime::Type.unregister(:mobile) <ide> Mime::Type.unregister(:fancy_xml) <ide> Mime::Type.unregister(:html_fragment) <add> ActionView::LookupContext::DetailsKey.clear <ide> end <ide> <ide> def test_html_fragment <ide><path>actionview/lib/action_view/template/resolver.rb <ide> def _find_all(name, prefix, partial, details, key, locals) <ide> end <ide> <ide> def query(path, details, formats, locals, cache:) <del> template_paths = find_template_paths_from_details(path, details) <add> cache = cache ? @unbound_templates : Concurrent::Map.new <ide> <del> template_paths.map do |template| <del> unbound_template = <del> if cache <del> @unbound_templates.compute_if_absent(template) do <del> build_unbound_template(template) <del> end <del> else <del> build_unbound_template(template) <del> end <add> unbound_templates = <add> cache.compute_if_absent(path.virtual) do <add> unbound_templates_from_path(path) <add> end <ide> <add> filter_and_sort_by_details(unbound_templates, details).map do |unbound_template| <ide> unbound_template.bind_locals(locals) <ide> end <ide> end <ide> def build_unbound_template(template) <ide> ) <ide> end <ide> <add> def unbound_templates_from_path(path) <add> if path.name.include?(".") <add> return [] <add> end <add> <add> # Instead of checking for every possible path, as our other globs would <add> # do, scan the directory for files with the right prefix. <add> paths = template_glob("#{escape_entry(path.to_s)}*") <add> <add> paths.map do |path| <add> build_unbound_template(path) <add> end.select do |template| <add> # Select for exact virtual path match, including case sensitivity <add> template.virtual_path == path.virtual <add> end <add> end <add> <add> def filter_and_sort_by_details(templates, details) <add> locale = details[:locale] <add> formats = details[:formats] <add> variants = details[:variants] <add> handlers = details[:handlers] <add> <add> results = templates.map do |template| <add> locale_match = details_match_sort_key(template.locale, locale) || next <add> format_match = details_match_sort_key(template.format, formats) || next <add> variant_match = <add> if variants == :any <add> template.variant ? 1 : 0 <add> else <add> details_match_sort_key(template.variant&.to_sym, variants) || next <add> end <add> handler_match = details_match_sort_key(template.handler, handlers) || next <add> <add> [template, [locale_match, format_match, variant_match, handler_match]] <add> end <add> <add> results.compact! <add> results.sort_by!(&:last) if results.size > 1 <add> results.map!(&:first) <add> <add> results <add> end <add> <add> def details_match_sort_key(have, want) <add> if have <add> want.index(have) <add> else <add> want.size <add> end <add> end <add> <ide> # Safe glob within @path <ide> def template_glob(glob) <ide> query = File.join(escape_entry(@path), glob) <ide> def template_glob(glob) <ide> def escape_entry(entry) <ide> entry.gsub(/[*?{}\[\]]/, '\\\\\\&') <ide> end <del> <del> def find_template_paths_from_details(path, details) <del> if path.name.include?(".") <del> return [] <del> end <del> <del> # Instead of checking for every possible path, as our other globs would <del> # do, scan the directory for files with the right prefix. <del> candidates = template_glob("#{escape_entry(path.to_s)}*") <del> <del> regex = build_regex(path, details) <del> <del> candidates.uniq.reject do |filename| <del> # This regex match does double duty of finding only files which match <del> # details (instead of just matching the prefix) and also filtering for <del> # case-insensitive file systems. <del> !regex.match?(filename) || <del> File.directory?(filename) <del> end.sort_by do |filename| <del> # Because we scanned the directory, instead of checking for files <del> # one-by-one, they will be returned in an arbitrary order. <del> # We can use the matches found by the regex and sort by their index in <del> # details. <del> match = filename.match(regex) <del> EXTENSIONS.keys.map do |ext| <del> if ext == :variants && details[ext] == :any <del> match[ext].nil? ? 0 : 1 <del> elsif match[ext].nil? <del> # No match should be last <del> details[ext].length <del> else <del> found = match[ext].to_sym <del> details[ext].index(found) <del> end <del> end <del> end <del> end <del> <del> def build_regex(path, details) <del> query = Regexp.escape(File.join(@path, path)) <del> exts = EXTENSIONS.map do |ext, prefix| <del> match = <del> if ext == :variants && details[ext] == :any <del> ".*?" <del> else <del> arr = details[ext].compact <del> arr.uniq! <del> arr.map! { |e| Regexp.escape(e) } <del> arr.join("|") <del> end <del> prefix = Regexp.escape(prefix) <del> "(#{prefix}(?<#{ext}>#{match}))?" <del> end.join <del> <del> %r{\A#{query}#{exts}\z} <del> end <ide> end <ide> end
2
Javascript
Javascript
add unit tests for phase constants
22a57e493afd15f2f95c36a18dfd66d5373efed5
<ide><path>test/unit/phaseConstants.test.js <add>/* eslint-env jest */ <add>import {PHASE_EXPORT, PHASE_PRODUCTION_BUILD, PHASE_PRODUCTION_SERVER, PHASE_DEVELOPMENT_SERVER} from 'next/constants' <add> <add>describe('phaseConstants', () => { <add> it('should set phases correctly', () => { <add> expect(PHASE_EXPORT).toBe('phase-export') <add> expect(PHASE_PRODUCTION_BUILD).toBe('phase-production-build') <add> expect(PHASE_PRODUCTION_SERVER).toBe('phase-production-server') <add> expect(PHASE_DEVELOPMENT_SERVER).toBe('phase-development-server') <add> }) <add>})
1
Text
Text
remove some unsupported instructions in the docs
49be84842e41a612601ff9d0563ec30f138e95bc
<ide><path>docs/man/docker-commit.1.md <ide> Using an existing container's name or ID you can create a new image. <ide> <ide> **-c** , **--change**=[] <ide> Apply specified Dockerfile instructions while committing the image <del> Supported Dockerfile instructions: `ADD`|`CMD`|`ENTRYPOINT`|`ENV`|`EXPOSE`|`FROM`|`MAINTAINER`|`RUN`|`USER`|`LABEL`|`VOLUME`|`WORKDIR`|`COPY` <add> Supported Dockerfile instructions: `CMD`|`ENTRYPOINT`|`ENV`|`EXPOSE`|`ONBUILD`|`USER`|`VOLUME`|`WORKDIR` <ide> <ide> **--help** <ide> Print usage statement <ide><path>docs/man/docker-import.1.md <ide> URL|- [REPOSITORY[:TAG]] <ide> # OPTIONS <ide> **-c**, **--change**=[] <ide> Apply specified Dockerfile instructions while importing the image <del> Supported Dockerfile instructions: `ADD`|`CMD`|`ENTRYPOINT`|`ENV`|`EXPOSE`|`FROM`|`MAINTAINER`|`RUN`|`USER`|`LABEL`|`VOLUME`|`WORKDIR`|`COPY` <add> Supported Dockerfile instructions: `CMD`|`ENTRYPOINT`|`ENV`|`EXPOSE`|`ONBUILD`|`USER`|`VOLUME`|`WORKDIR` <ide> <ide> # DESCRIPTION <ide> Create a new filesystem image from the contents of a tarball (`.tar`, <ide><path>docs/sources/reference/commandline/cli.md <ide> If this behavior is undesired, set the 'p' option to false. <ide> <ide> The `--change` option will apply `Dockerfile` instructions to the image <ide> that is created. <del>Supported `Dockerfile` instructions: `ADD`|`CMD`|`ENTRYPOINT`|`ENV`|`EXPOSE`|`FROM`|`MAINTAINER`|`RUN`|`USER`|`LABEL`|`VOLUME`|`WORKDIR`|`COPY` <add>Supported `Dockerfile` instructions: <add>`CMD`|`ENTRYPOINT`|`ENV`|`EXPOSE`|`ONBUILD`|`USER`|`VOLUME`|`WORKDIR` <ide> <ide> #### Commit a container <ide> <ide> the `-` parameter to take the data from `STDIN`. <ide> <ide> The `--change` option will apply `Dockerfile` instructions to the image <ide> that is created. <del>Supported `Dockerfile` instructions: `CMD`, `ENTRYPOINT`, `ENV`, `EXPOSE`, <del>`ONBUILD`, `USER`, `VOLUME`, `WORKDIR` <add>Supported `Dockerfile` instructions: <add>`CMD`|`ENTRYPOINT`|`ENV`|`EXPOSE`|`ONBUILD`|`USER`|`VOLUME`|`WORKDIR` <ide> <ide> #### Examples <ide>
3
Ruby
Ruby
load openssl only when it's used
9a3fb1f43be172618a710f0bb170586dc2475591
<ide><path>lib/action_mailbox/postfix_relayer.rb <ide> <ide> require "net/http" <ide> require "uri" <del>require "openssl" <ide> <ide> module ActionMailbox <ide> class PostfixRelayer <ide> def post(source) <ide> <ide> def client <ide> @client ||= Net::HTTP.new(uri.host, uri.port).tap do |connection| <del> connection.use_ssl = uri.scheme == "https" <del> connection.verify_mode = OpenSSL::SSL::VERIFY_PEER <add> if uri.scheme == "https" <add> require "openssl" <add> <add> connection.use_ssl = true <add> connection.verify_mode = OpenSSL::SSL::VERIFY_PEER <add> end <ide> <ide> connection.open_timeout = 1 <ide> connection.read_timeout = 10
1
Javascript
Javascript
remove autobinding warning
8b9891aa8ab2aa2276a21bed2885100f9fbcac50
<ide><path>src/core/ReactCompositeComponent.js <ide> var keyMirror = require('keyMirror'); <ide> var merge = require('merge'); <ide> var mixInto = require('mixInto'); <ide> <del>function invokeWithWarning(func) { <del> return function() { <del> console && console.warn && console.warn( <del> 'You have invoked a method that is automatically bound, before the ' + <del> 'instance has been mounted. There is nothing conceptually wrong with ' + <del> 'this, but since this method will be replaced with a new version once' + <del> ' the component is mounted - you should be aware of the fact that ' + <del> 'this method will soon be replaced.' <del> ); <del> return func.apply(this, arguments); <del> }; <del>} <del> <ide> /** <ide> * Policies that describe methods in `ReactCompositeComponentInterface`. <ide> */ <ide> function mixSpecIntoComponent(Constructor, spec) { <ide> } <ide> proto.__reactAutoBindMap[name] = property; <ide> proto[name] = property; <del> if (__DEV__) { <del> proto[name] = invokeWithWarning(property); <del> } <ide> } else { <ide> if (isInherited) { <ide> // For methods which are defined more than once, call the existing
1
Ruby
Ruby
clarify postgres initials. [skip ci]
b7f4b8e0bfd1fefc30f7378ac1655b58b48ff5f3
<ide><path>activerecord/lib/active_record/attributes.rb <ide> module ClassMethods <ide> # is not passed, the previous default value (if any) will be used. <ide> # Otherwise, the default will be +nil+. <ide> # <del> # +array+ (PG only) specifies that the type should be an array (see the <add> # +array+ (PostgreSQL only) specifies that the type should be an array (see the <ide> # examples below). <ide> # <del> # +range+ (PG only) specifies that the type should be a range (see the <add> # +range+ (PostgreSQL only) specifies that the type should be a range (see the <ide> # examples below). <ide> # <ide> # ==== Examples
1
Text
Text
add security steward on/offboarding steps
13ee108dd97104adf8185a0171914ebd06cd16b9
<ide><path>doc/guides/security-steward-on-off-boarding.md <add># Security Steward Onboarding/OffBoarding <add> <add>## Onboarding <add> <add>* Confirm the new steward agrees to keep all private information confidential <add> to the project and not to use/disclose to their employer. <add>* Add them to the security-stewards team in the GitHub nodejs-private <add> organization. <add>* Ensure they have 2FA enabled in H1. <add>* Add them to the standard team in H1 using this <add> [page](https://hackerone.com/nodejs/team_members). <add>* Add them as managers of the <add> [nodejs-sec](https://groups.google.com/g/nodejs-sec/members) mailing list. <add> <add>## Offboarding <add> <add>* Remove them from security-stewards team in the GitHub nodejs-private <add> organization. <add>* Unless they have access for another reason, remove them from the <add> standard team in H1 using this <add> [page](https://hackerone.com/nodejs/team_members). <add>* Downgrade their account to regular member in the <add> [nodejs-sec](https://groups.google.com/g/nodejs-sec/members) mailing list.
1
Text
Text
add docs/docs 01
4d4f322c60ae4894c8b1c0bee50f0c90577f2509
<ide><path>docs/docs/01-why-react.ko-KR.md <add>--- <add>id: why-react-ko-KR <add>title: 왜 React인가? <add>permalink: why-react-ko-KR.html <add>next: displaying-data-ko-KR.html <add>--- <add> <add>React는 페이스북과 인스타그램에서 사용자 인터페이스를 구성하기 위해 만들어진 라이브러리입니다. 많은 사람들은 React를 **[MVC](http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller)** 에서의 **V** 로 생각하는 경향이 있습니다. <add> <add>우리는 단 하나의 문제를 해결하기 위해 React를 만들었습니다: **지속해서 데이터가 변화하는 대규모 애플리케이션을 구축하기.** 이 문제를 해결하기 위해, React는 두가지 컨셉을 도입했습니다. <add> <add>### 단순함 <add> <add>당신의 애플리케이션이 특정 시점에 어떻게 보여야 할지를 단순히 표현하는 것만으로, 데이터가 변할 때 React는 자동으로 모든 UI 업데이트를 관리해줍니다. <add> <add>### 선언적 문법 <add> <add>데이터가 변할 때 React는 "새로 고침" 버튼을 누르듯이 작동하며, 데이터의 바뀐 부분만을 업데이트할 수 있습니다. <add> <add>## 구성적인 컴포넌트를 만드세요 <add> <add>React는 재사용 가능한 컴포넌트들을 만드는 데에 도움이 됩니다. 사실, React를 사용하면 *단지* 컴포넌트를 만드는 일만 하게 됩니다. 컴포넌트들은 잘 캡슐화되어 되어 있기 때문에, 컴포넌트들은 코드의 재사용성을 높이고, 테스트를 쉽게 해 주며, 관심 분리의 원칙(separation of concerns)을 지키게 해 줍니다. <add> <add>## 5분만 투자하세요 <add> <add>React는 많은 관습적인 사고에 도전하며, 첫눈에 볼 때는 이상한 아이디어들의 모음이라고 생각할 수도 있습니다. 이 가이드를 읽기 위해 [5분만 투자하세요](http://37signals.com/svn/posts/3124-give-it-five-minutes); 그 이상한 아이디어들은 페이스북과 인스타그램 안팎의 수천 개의 컴포넌트들을 만드는 데에 사용되었기 때문입니다. <add> <add>## 더 알아보기 <add> <add>[이 블로그 포스트](http://facebook.github.io/react/blog/2013/06/05/why-react.html)에서 React를 만든 우리의 동기에 대해 알아볼 수 있습니다.
1
Python
Python
move alias aware sorting to glances_plugin
7a47c323415ffaa4e0c6cfd151d6dea0c9ffc264
<ide><path>glances/plugins/glances_diskio.py <ide> def msg_curse(self, args=None, max_width=None): <ide> msg = '{:>7}'.format('W/s') <ide> ret.append(self.curse_add_line(msg)) <ide> # Disk list (sorted by name) <del> for i in sorted(self.stats, key=lambda stat: tuple(map( <del> lambda part: int(part) if part.isdigit() else part.lower(), <del> re.split(r"(\d+|\D+)", stat.get('alias') or stat['disk_name']) <del> ))): <add> for i in self.sorted_stats('disk_name'): <ide> # Is there an alias for the disk name ? <ide> disk_real_name = i['disk_name'] <ide> disk_name = self.has_alias(i['disk_name']) <ide><path>glances/plugins/glances_plugin.py <ide> def short_system_name(self): <ide> """Get the short detected OS name (SNMP).""" <ide> return self._short_system_name <ide> <add> def sorted_stats(self, key): <add> """Get the stats sorted by an alias (if present) or key.""" <add> return sorted(self.stats, key=lambda stat: tuple(map( <add> lambda part: int(part) if part.isdigit() else part.lower(), <add> re.split(r"(\d+|\D+)", self.has_alias(stat[key]) or stat[key]) <add> ))) <add> <ide> @short_system_name.setter <ide> def short_system_name(self, short_name): <ide> """Set the short detected OS name (SNMP)."""
2
Javascript
Javascript
replace message types string by constants
ebf5b58bec6954ebeed1c302cf31ff55494a0c93
<ide><path>lib/internal/worker.js <ide> const kIncrementsPortRef = Symbol('kIncrementsPortRef'); <ide> <ide> const debug = util.debuglog('worker'); <ide> <add>const messageTypes = { <add> UP_AND_RUNNING: 'upAndRunning', <add> COULD_NOT_SERIALIZE_ERROR: 'couldNotSerializeError', <add> ERROR_MESSAGE: 'errorMessage', <add> STDIO_PAYLOAD: 'stdioPayload', <add> STDIO_WANTS_MORE_DATA: 'stdioWantsMoreData', <add> LOAD_SCRIPT: 'loadScript' <add>}; <add> <ide> // A communication channel consisting of a handle (that wraps around an <ide> // uv_async_t) which can receive information from other threads and emits <ide> // .onmessage events, and a function used for sending data to a MessagePort <ide> class ReadableWorkerStdio extends Readable { <ide> } <ide> <ide> this[kPort].postMessage({ <del> type: 'stdioWantsMoreData', <add> type: messageTypes.STDIO_WANTS_MORE_DATA, <ide> stream: this[kName] <ide> }); <ide> } <ide> class WritableWorkerStdio extends Writable { <ide> <ide> _write(chunk, encoding, cb) { <ide> this[kPort].postMessage({ <del> type: 'stdioPayload', <add> type: messageTypes.STDIO_PAYLOAD, <ide> stream: this[kName], <ide> chunk, <ide> encoding <ide> class WritableWorkerStdio extends Writable { <ide> <ide> _final(cb) { <ide> this[kPort].postMessage({ <del> type: 'stdioPayload', <add> type: messageTypes.STDIO_PAYLOAD, <ide> stream: this[kName], <ide> chunk: null <ide> }); <ide> class Worker extends EventEmitter { <ide> this[kPublicPort].on('message', (message) => this.emit('message', message)); <ide> setupPortReferencing(this[kPublicPort], this, 'message'); <ide> this[kPort].postMessage({ <del> type: 'loadScript', <add> type: messageTypes.LOAD_SCRIPT, <ide> filename, <ide> doEval: !!options.eval, <ide> workerData: options.workerData, <ide> class Worker extends EventEmitter { <ide> <ide> [kOnMessage](message) { <ide> switch (message.type) { <del> case 'upAndRunning': <add> case messageTypes.UP_AND_RUNNING: <ide> return this.emit('online'); <del> case 'couldNotSerializeError': <add> case messageTypes.COULD_NOT_SERIALIZE_ERROR: <ide> return this[kOnCouldNotSerializeErr](); <del> case 'errorMessage': <add> case messageTypes.ERROR_MESSAGE: <ide> return this[kOnErrorMessage](message.error); <del> case 'stdioPayload': <add> case messageTypes.STDIO_PAYLOAD: <ide> { <ide> const { stream, chunk, encoding } = message; <ide> return this[kParentSideStdio][stream].push(chunk, encoding); <ide> } <del> case 'stdioWantsMoreData': <add> case messageTypes.STDIO_WANTS_MORE_DATA: <ide> { <ide> const { stream } = message; <ide> return this[kParentSideStdio][stream][kStdioWantsMoreDataCallback](); <ide> function setupChild(evalScript) { <ide> const publicWorker = require('worker_threads'); <ide> <ide> port.on('message', (message) => { <del> if (message.type === 'loadScript') { <add> if (message.type === messageTypes.LOAD_SCRIPT) { <ide> const { filename, doEval, workerData, publicPort, hasStdin } = message; <ide> publicWorker.parentPort = publicPort; <ide> setupPortReferencing(publicPort, publicPort, 'message'); <ide> function setupChild(evalScript) { <ide> debug(`[${threadId}] starts worker script ${filename} ` + <ide> `(eval = ${eval}) at cwd = ${process.cwd()}`); <ide> port.unref(); <del> port.postMessage({ type: 'upAndRunning' }); <add> port.postMessage({ type: messageTypes.UP_AND_RUNNING }); <ide> if (doEval) { <ide> evalScript('[worker eval]', filename); <ide> } else { <ide> process.argv[1] = filename; // script filename <ide> require('module').runMain(); <ide> } <ide> return; <del> } else if (message.type === 'stdioPayload') { <add> } else if (message.type === messageTypes.STDIO_PAYLOAD) { <ide> const { stream, chunk, encoding } = message; <ide> workerStdio[stream].push(chunk, encoding); <ide> return; <del> } else if (message.type === 'stdioWantsMoreData') { <add> } else if (message.type === messageTypes.STDIO_WANTS_MORE_DATA) { <ide> const { stream } = message; <ide> workerStdio[stream][kStdioWantsMoreDataCallback](); <ide> return; <ide> function setupChild(evalScript) { <ide> } catch {} <ide> debug(`[${threadId}] fatal exception serialized = ${!!serialized}`); <ide> if (serialized) <del> port.postMessage({ type: 'errorMessage', error: serialized }); <add> port.postMessage({ <add> type: messageTypes.ERROR_MESSAGE, <add> error: serialized <add> }); <ide> else <del> port.postMessage({ type: 'couldNotSerializeError' }); <add> port.postMessage({ type: messageTypes.COULD_NOT_SERIALIZE_ERROR }); <ide> clearAsyncIdStack(); <ide> } <ide> }
1
Text
Text
change v-notation for version in buffer.md
400faf5a3a2605977e613d04578e800b81b00a79
<ide><path>doc/api/buffer.md <ide> const buf6 = Buffer.from('tést', 'latin1'); <ide> <ide> ## `Buffer.from()`, `Buffer.alloc()`, and `Buffer.allocUnsafe()` <ide> <del>In versions of Node.js prior to v6, `Buffer` instances were created using the <add>In versions of Node.js prior to 6.0.0, `Buffer` instances were created using the <ide> `Buffer` constructor function, which allocates the returned `Buffer` <ide> differently based on what arguments are provided: <ide>
1
Javascript
Javascript
fix task search function in graph view
d88d1174eb4341daff2968c59f4cab204130a03f
<ide><path>airflow/www/static/js/graph.js <ide> d3.select('#searchbox').on('keyup', () => { <ide> setFocusMap(); <ide> } <ide> <del> d3.selectAll('g.nodes g.node').forEach(function highlight(d) { <add> d3.selectAll('g.nodes g.node').filter(function highlight(d) { <ide> if (s === '') { <ide> d3.selectAll('g.edgePaths, g.edgeLabel').attr('data-highlight', null); <ide> d3.select(this).attr('data-highlight', null); <ide> d3.select('#searchbox').on('keyup', () => { <ide> d3.select(this).attr('data-highlight', 'fade'); <ide> } <ide> } <add> // We don't actually use the returned results from filter <add> return null; <ide> }); <ide> <ide> // This moves the matched node to the center of the graph area
1
Text
Text
remove references to travis
0266b70379ff80a8ed002398cde1e640c2e7696b
<ide><path>CONTRIBUTING.md <ide> If you're only fixing a bug, it's fine to submit a pull request right away but w <ide> <ide> Small pull requests are much easier to review and more likely to get merged. Make sure the PR does only one thing, otherwise please split it. <ide> <del>**Before submitting a pull request**, please make sure the following is done: <add>Please make sure the following is done when submitting a pull request: <ide> <ide> 1. Fork [the repository](https://github.com/facebook/react-native) and create your branch from `master`. <ide> 2. Add the copyright notice to the top of any new files you've added. <del>3. Describe your [**test plan**](https://facebook.github.io/react-native/docs/contributing.html#test-plan) in your commit. <del>4. Ensure [**tests pass**](https://facebook.github.io/react-native/docs/contributing.html#contrinuous-integration-tests) on both Travis and Circle CI. <del>5. Make sure your code lints (`npm run lint`). <del>6. If you haven't already, [sign the CLA](https://code.facebook.com/cla). <add>3. Describe your [**test plan**](/react-native/docs/contributing.html#test-plan) in your pull request description. Make sure to [test your changes](/react-native/docs/testing.html)! <add>4. Make sure your code lints (`npm run lint`). <add>5. If you haven't already, [sign the CLA](https://code.facebook.com/cla). <ide> <del>All pull requests should be opened against the `master` branch. <add>All pull requests should be opened against the `master` branch. After opening your pull request, ensure [**all tests pass**](/react-native/docs/contributing.html#contrinuous-integration-tests) on Circle CI. If a test fails and you believe it is unrelated to your change, leave a comment on the pull request explaining why. <ide> <ide> > **Note:** It is not necessary to keep clicking `Merge master to your branch` on the PR page. You would want to merge master if there are conflicts or tests are failing. The Facebook-GitHub-Bot ultimately squashes all commits to a single one before merging your PR. <ide> <ide> See [What is a Test Plan?](https://medium.com/@martinkonicek/what-is-a-test-plan <ide> <ide> #### Continuous integration tests <ide> <del>Make sure all **tests pass** on both [Travis][travis] and [Circle CI][circle]. PRs that break tests are unlikely to be merged. Learn more about [testing your changes here](https://facebook.github.io/react-native/docs/testing.html). <add>Make sure all **tests pass** on [Circle CI][circle]. PRs that break tests are unlikely to be merged. Learn more about [testing your changes here](/react-native/docs/testing.html). <ide> <del>[travis]: https://travis-ci.org/facebook/react-native <ide> [circle]: http://circleci.com/gh/facebook/react-native <ide> <ide> #### Breaking changes <ide><path>README.md <del># [React Native](https://facebook.github.io/react-native/) &middot; [![Travis CI Status](https://travis-ci.org/facebook/react-native.svg?branch=master)](https://travis-ci.org/facebook/react-native) [![Circle CI Status](https://circleci.com/gh/facebook/react-native.svg?style=shield)](https://circleci.com/gh/facebook/react-native) [![npm version](https://badge.fury.io/js/react-native.svg)](https://badge.fury.io/js/react-native) [![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg)](CONTRIBUTING.md#pull-requests) <add># [React Native](https://facebook.github.io/react-native/) &middot; [![Circle CI Status](https://circleci.com/gh/facebook/react-native.svg?style=shield)](https://circleci.com/gh/facebook/react-native) [![npm version](https://badge.fury.io/js/react-native.svg)](https://badge.fury.io/js/react-native) [![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg)](CONTRIBUTING.md#pull-requests) <ide> <ide> Learn once, write anywhere: Build mobile apps with React. <ide> <ide><path>docs/Contributing.md <ide> If you're only fixing a bug, it's fine to submit a pull request right away but w <ide> <ide> Small pull requests are much easier to review and more likely to get merged. Make sure the PR does only one thing, otherwise please split it. <ide> <del>**Before submitting a pull request**, please make sure the following is done: <add>Please make sure the following is done when submitting a pull request: <ide> <ide> 1. Fork [the repository](https://github.com/facebook/react-native) and create your branch from `master`. <ide> 2. Add the copyright notice to the top of any new files you've added. <del>3. Describe your [**test plan**](/react-native/docs/contributing.html#test-plan) in your commit. <del>4. Ensure [**tests pass**](/react-native/docs/contributing.html#contrinuous-integration-tests) on both Travis and Circle CI. <del>5. Make sure your code lints (`npm run lint`). <del>6. If you haven't already, [sign the CLA](https://code.facebook.com/cla). <add>3. Describe your [**test plan**](/react-native/docs/contributing.html#test-plan) in your pull request description. Make sure to [test your changes](/react-native/docs/testing.html)! <add>4. Make sure your code lints (`npm run lint`). <add>5. If you haven't already, [sign the CLA](https://code.facebook.com/cla). <ide> <del>All pull requests should be opened against the `master` branch. <add>All pull requests should be opened against the `master` branch. After opening your pull request, ensure [**all tests pass**](/react-native/docs/contributing.html#contrinuous-integration-tests) on Circle CI. If a test fails and you believe it is unrelated to your change, leave a comment on the pull request explaining why. <ide> <ide> > **Note:** It is not necessary to keep clicking `Merge master to your branch` on the PR page. You would want to merge master if there are conflicts or tests are failing. The Facebook-GitHub-Bot ultimately squashes all commits to a single one before merging your PR. <ide> <ide> See [What is a Test Plan?](https://medium.com/@martinkonicek/what-is-a-test-plan <ide> <ide> #### Continuous integration tests <ide> <del>Make sure all **tests pass** on both [Travis][travis] and [Circle CI][circle]. PRs that break tests are unlikely to be merged. Learn more about [testing your changes here](/react-native/docs/testing.html). <add>Make sure all **tests pass** on [Circle CI][circle]. PRs that break tests are unlikely to be merged. Learn more about [testing your changes here](/react-native/docs/testing.html). <ide> <del>[travis]: https://travis-ci.org/facebook/react-native <ide> [circle]: http://circleci.com/gh/facebook/react-native <ide> <ide> #### Breaking changes <ide><path>docs/Testing.md <ide> previous: maintainers <ide> <ide> This document is about testing your changes to React Native as a [contributor](docs/contributing.html). If you're interested in testing a React Native app, check out the [React Native Tutorial](http://facebook.github.io/jest/docs/tutorial-react-native.html) on the Jest website. <ide> <del>The React Native repo has several tests you can run to verify you haven't caused a regression with your PR. These tests are run with the [Travis](https://travis-ci.org/facebook/react-native/builds) and [Circle](https://circleci.com/gh/facebook/react-native) continuous integration systems, which will automatically annotate pull requests with the test results. <add>The React Native repo has several tests you can run to verify you haven't caused a regression with your PR. These tests are run using [Circle](https://circleci.com/gh/facebook/react-native), a continuous integration system. Circle will automatically annotate pull requests with the test results. <ide> <ide> Whenever you are fixing a bug or adding new functionality to React Native, you should add a test that covers it. Depending on the change you're making, there are different types of tests that may be appropriate. <ide> <ide> You can run integration tests locally with cmd+U in the IntegrationTest and RNTe <ide> <ide> A common type of integration test is the snapshot test. These tests render a component, and verify snapshots of the screen against reference images using `TestModule.verifySnapshot()`, using the [`FBSnapshotTestCase`](https://github.com/facebook/ios-snapshot-test-case) library behind the scenes. Reference images are recorded by setting `recordMode = YES` on the `RCTTestRunner`, then running the tests. Snapshots will differ slightly between 32 and 64 bit, and various OS versions, so it's recommended that you enforce tests are run with the correct configuration. It's also highly recommended that all network data be mocked out, along with other potentially troublesome dependencies. See [`SimpleSnapshotTest`](https://github.com/facebook/react-native/blob/master/IntegrationTests/SimpleSnapshotTest.js) for a basic example. <ide> <del>If you make a change that affects a snapshot test in a PR, such as adding a new example case to one of the examples that is snapshotted, you'll need to re-record the snapshot reference image. To do this, simply change to `_runner.recordMode = YES;` in [RNTester/RNTesterSnapshotTests.m](https://github.com/facebook/react-native/blob/master/RNTester/RNTesterIntegrationTests/RNTesterSnapshotTests.m#L42), re-run the failing tests, then flip record back to `NO` and submit/update your PR and wait to see if the Travis build passes. <add>If you make a change that affects a snapshot test in a PR, such as adding a new example case to one of the examples that is snapshotted, you'll need to re-record the snapshot reference image. To do this, simply change to `_runner.recordMode = YES;` in [RNTester/RNTesterSnapshotTests.m](https://github.com/facebook/react-native/blob/master/RNTester/RNTesterIntegrationTests/RNTesterSnapshotTests.m#L42), re-run the failing tests, then flip record back to `NO` and submit/update your PR and wait to see if the Circle build passes. <ide> <ide> ## Apple TV <ide>
4
Javascript
Javascript
fix ember.test.registerhelper test
4ab23f79393ed6a143074676e8a79ed5ccea7491
<ide><path>packages/ember-testing/tests/helpers_test.js <ide> test("Ember.Application#setupForTesting", function() { <ide> }); <ide> <ide> test("Ember.Test.registerHelper/unregisterHelper", function() { <del> expect(3); <add> expect(5); <ide> var appBooted = false; <ide> <ide> Ember.Test.registerHelper('boot', function(app) { <ide> test("Ember.Test.registerHelper/unregisterHelper", function() { <ide> App.injectTestHelpers(); <ide> }); <ide> <add> ok(App.testHelpers.boot); <ide> ok(window.boot); <ide> <ide> window.boot().then(function() { <ide> ok(appBooted); <del> }); <ide> <del> App.removeTestHelpers(); <del> Ember.Test.unregisterHelper('boot'); <add> App.removeTestHelpers(); <add> Ember.Test.unregisterHelper('boot'); <add> <add> ok(!App.testHelpers.boot); <add> ok(!window.boot); <add> }); <ide> <del> ok(!window.boot); <ide> });
1
Javascript
Javascript
convert title block to a plugin
d6289c6129f1222980ea571f6c6f675182d78f35
<ide><path>src/chart.js <ide> require('./core/core.datasetController')(Chart); <ide> require('./core/core.layoutService')(Chart); <ide> require('./core/core.scaleService')(Chart); <ide> require('./core/core.plugin.js')(Chart); <del>require('./core/core.legend')(Chart); <ide> require('./core/core.scale')(Chart); <ide> require('./core/core.title')(Chart); <add>require('./core/core.legend')(Chart); <ide> require('./core/core.tooltip')(Chart); <ide> <ide> require('./elements/element.arc')(Chart); <ide><path>src/core/core.controller.js <ide> module.exports = function(Chart) { <ide> }, <ide> <ide> buildSurroundingItems: function() { <del> if (this.options.title) { <add> /*if (this.options.title) { <ide> this.titleBlock = new Chart.Title({ <ide> ctx: this.chart.ctx, <ide> options: this.options.title, <ide> chart: this <ide> }); <ide> <ide> Chart.layoutService.addBox(this, this.titleBlock); <del> } <add> }*/ <ide> }, <ide> <ide> updateLayout: function() { <ide><path>src/core/core.legend.js <ide> module.exports = function(Chart) { <ide> Chart.layoutService.addBox(chartInstance, chartInstance.legend); <ide> } <ide> } <del> }) <add> }); <ide> }; <ide><path>src/core/core.title.js <ide> module.exports = function(Chart) { <ide> } <ide> } <ide> }); <add> <add> // Register the title plugin <add> Chart.pluginService.register({ <add> beforeInit: function(chartInstance) { <add> var opts = chartInstance.options; <add> var titleOpts = opts.title; <add> <add> if (titleOpts) { <add> chartInstance.titleBlock = new Chart.Title({ <add> ctx: chartInstance.chart.ctx, <add> options: titleOpts, <add> chart: chartInstance <add> }); <add> <add> Chart.layoutService.addBox(chartInstance, chartInstance.titleBlock); <add> } <add> } <add> }); <ide> }; <ide>\ No newline at end of file
4
PHP
PHP
remove old httpsocket code
7cb31e74cc2730bf9d3df5139ab48b2f74720bb6
<ide><path>lib/Cake/Network/Http/BasicAuthentication.php <del><?php <del>/** <del> * Basic authentication <del> * <del> * PHP 5 <del> * <del> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) <del> * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) <del> * <del> * Licensed under The MIT License <del> * Redistributions of files must retain the above copyright notice. <del> * <del> * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) <del> * @link http://cakephp.org CakePHP(tm) Project <del> * @package Cake.Network.Http <del> * @since CakePHP(tm) v 2.0.0 <del> * @license MIT License (http://www.opensource.org/licenses/mit-license.php) <del> */ <del>namespace Cake\Network\Http; <del> <del>/** <del> * Basic authentication <del> * <del> * @package Cake.Network.Http <del> */ <del>class BasicAuthentication { <del> <del>/** <del> * Authentication <del> * <del> * @param HttpSocket $http <del> * @param array $authInfo <del> * @return void <del> * @see http://www.ietf.org/rfc/rfc2617.txt <del> */ <del> public static function authentication(HttpSocket $http, &$authInfo) { <del> if (isset($authInfo['user'], $authInfo['pass'])) { <del> $http->request['header']['Authorization'] = static::_generateHeader($authInfo['user'], $authInfo['pass']); <del> } <del> } <del> <del>/** <del> * Proxy Authentication <del> * <del> * @param HttpSocket $http <del> * @param array $proxyInfo <del> * @return void <del> * @see http://www.ietf.org/rfc/rfc2617.txt <del> */ <del> public static function proxyAuthentication(HttpSocket $http, &$proxyInfo) { <del> if (isset($proxyInfo['user'], $proxyInfo['pass'])) { <del> $http->request['header']['Proxy-Authorization'] = static::_generateHeader($proxyInfo['user'], $proxyInfo['pass']); <del> } <del> } <del> <del>/** <del> * Generate basic [proxy] authentication header <del> * <del> * @param string $user <del> * @param string $pass <del> * @return string <del> */ <del> protected static function _generateHeader($user, $pass) { <del> return 'Basic ' . base64_encode($user . ':' . $pass); <del> } <del> <del>} <ide><path>lib/Cake/Network/Http/DigestAuthentication.php <del><?php <del>/** <del> * Digest authentication <del> * <del> * PHP 5 <del> * <del> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) <del> * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) <del> * <del> * Licensed under The MIT License <del> * Redistributions of files must retain the above copyright notice. <del> * <del> * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) <del> * @link http://cakephp.org CakePHP(tm) Project <del> * @package Cake.Network.Http <del> * @since CakePHP(tm) v 2.0.0 <del> * @license MIT License (http://www.opensource.org/licenses/mit-license.php) <del> */ <del>namespace Cake\Network\Http; <del> <del>/** <del> * Digest authentication <del> * <del> * @package Cake.Network.Http <del> */ <del>class DigestAuthentication { <del> <del>/** <del> * Authentication <del> * <del> * @param HttpSocket $http <del> * @param array $authInfo <del> * @return void <del> * @link http://www.ietf.org/rfc/rfc2617.txt <del> */ <del> public static function authentication(HttpSocket $http, &$authInfo) { <del> if (isset($authInfo['user'], $authInfo['pass'])) { <del> if (!isset($authInfo['realm']) && !static::_getServerInformation($http, $authInfo)) { <del> return; <del> } <del> $http->request['header']['Authorization'] = static::_generateHeader($http, $authInfo); <del> } <del> } <del> <del>/** <del> * Retrieve information about the authentication <del> * <del> * @param HttpSocket $http <del> * @param array $authInfo <del> * @return boolean <del> */ <del> protected static function _getServerInformation(HttpSocket $http, &$authInfo) { <del> $originalRequest = $http->request; <del> $http->configAuth(false); <del> $http->request($http->request); <del> $http->request = $originalRequest; <del> $http->configAuth('Digest', $authInfo); <del> <del> if (empty($http->response['header']['WWW-Authenticate'])) { <del> return false; <del> } <del> preg_match_all('@(\w+)=(?:(?:")([^"]+)"|([^\s,$]+))@', $http->response['header']['WWW-Authenticate'], $matches, PREG_SET_ORDER); <del> foreach ($matches as $match) { <del> $authInfo[$match[1]] = $match[2]; <del> } <del> if (!empty($authInfo['qop']) && empty($authInfo['nc'])) { <del> $authInfo['nc'] = 1; <del> } <del> return true; <del> } <del> <del>/** <del> * Generate the header Authorization <del> * <del> * @param HttpSocket $http <del> * @param array $authInfo <del> * @return string <del> */ <del> protected static function _generateHeader(HttpSocket $http, &$authInfo) { <del> $a1 = md5($authInfo['user'] . ':' . $authInfo['realm'] . ':' . $authInfo['pass']); <del> $a2 = md5($http->request['method'] . ':' . $http->request['uri']['path']); <del> <del> if (empty($authInfo['qop'])) { <del> $response = md5($a1 . ':' . $authInfo['nonce'] . ':' . $a2); <del> } else { <del> $authInfo['cnonce'] = uniqid(); <del> $nc = sprintf('%08x', $authInfo['nc']++); <del> $response = md5($a1 . ':' . $authInfo['nonce'] . ':' . $nc . ':' . $authInfo['cnonce'] . ':auth:' . $a2); <del> } <del> <del> $authHeader = 'Digest '; <del> $authHeader .= 'username="' . str_replace(array('\\', '"'), array('\\\\', '\\"'), $authInfo['user']) . '", '; <del> $authHeader .= 'realm="' . $authInfo['realm'] . '", '; <del> $authHeader .= 'nonce="' . $authInfo['nonce'] . '", '; <del> $authHeader .= 'uri="' . $http->request['uri']['path'] . '", '; <del> $authHeader .= 'response="' . $response . '"'; <del> if (!empty($authInfo['opaque'])) { <del> $authHeader .= ', opaque="' . $authInfo['opaque'] . '"'; <del> } <del> if (!empty($authInfo['qop'])) { <del> $authHeader .= ', qop="auth", nc=' . $nc . ', cnonce="' . $authInfo['cnonce'] . '"'; <del> } <del> return $authHeader; <del> } <del> <del>} <ide><path>lib/Cake/Network/Http/HttpResponse.php <del><?php <del>/** <del> * HTTP Response from HttpSocket. <del> * <del> * PHP 5 <del> * <del> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) <del> * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) <del> * <del> * Licensed under The MIT License <del> * Redistributions of files must retain the above copyright notice. <del> * <del> * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) <del> * @link http://cakephp.org CakePHP(tm) Project <del> * @since CakePHP(tm) v 2.0.0 <del> * @license MIT License (http://www.opensource.org/licenses/mit-license.php) <del> */ <del>namespace Cake\Network\Http; <del> <del>use Cake\Error; <del>use Cake\Utility\Inflector; <del> <del>/** <del> * HTTP Response from HttpSocket. <del> * <del> * @package Cake.Network.Http <del> * @deprecated This class is deprecated as it has naming conflicts with pecl/http <del> */ <del>class HttpResponse implements \ArrayAccess { <del> <del>/** <del> * Body content <del> * <del> * @var string <del> */ <del> public $body = ''; <del> <del>/** <del> * Headers <del> * <del> * @var array <del> */ <del> public $headers = array(); <del> <del>/** <del> * Cookies <del> * <del> * @var array <del> */ <del> public $cookies = array(); <del> <del>/** <del> * HTTP version <del> * <del> * @var string <del> */ <del> public $httpVersion = 'HTTP/1.1'; <del> <del>/** <del> * Response code <del> * <del> * @var integer <del> */ <del> public $code = 0; <del> <del>/** <del> * Reason phrase <del> * <del> * @var string <del> */ <del> public $reasonPhrase = ''; <del> <del>/** <del> * Pure raw content <del> * <del> * @var string <del> */ <del> public $raw = ''; <del> <del>/** <del> * Constructor <del> * <del> * @param string $message <del> */ <del> public function __construct($message = null) { <del> if ($message !== null) { <del> $this->parseResponse($message); <del> } <del> } <del> <del>/** <del> * Body content <del> * <del> * @return string <del> */ <del> public function body() { <del> return (string)$this->body; <del> } <del> <del>/** <del> * Get header in case insensitive <del> * <del> * @param string $name Header name <del> * @param array $headers <del> * @return mixed String if header exists or null <del> */ <del> public function getHeader($name, $headers = null) { <del> if (!is_array($headers)) { <del> $headers =& $this->headers; <del> } <del> if (isset($headers[$name])) { <del> return $headers[$name]; <del> } <del> foreach ($headers as $key => $value) { <del> if (strcasecmp($key, $name) === 0) { <del> return $value; <del> } <del> } <del> return null; <del> } <del> <del>/** <del> * If return is 200 (OK) <del> * <del> * @return boolean <del> */ <del> public function isOk() { <del> return $this->code == 200; <del> } <del> <del>/** <del> * If return is a valid 3xx (Redirection) <del> * <del> * @return boolean <del> */ <del> public function isRedirect() { <del> return in_array($this->code, array(301, 302, 303, 307)) && !is_null($this->getHeader('Location')); <del> } <del> <del>/** <del> * Parses the given message and breaks it down in parts. <del> * <del> * @param string $message Message to parse <del> * @return void <del> * @throws Cake\Error\SocketException <del> */ <del> public function parseResponse($message) { <del> if (!is_string($message)) { <del> throw new Error\SocketException(__d('cake_dev', 'Invalid response.')); <del> } <del> <del> if (!preg_match("/^(.+\r\n)(.*)(?<=\r\n)\r\n/Us", $message, $match)) { <del> throw new Error\SocketException(__d('cake_dev', 'Invalid HTTP response.')); <del> } <del> <del> list(, $statusLine, $header) = $match; <del> $this->raw = $message; <del> $this->body = (string)substr($message, strlen($match[0])); <del> <del> if (preg_match("/(.+) ([0-9]{3}) (.+)\r\n/DU", $statusLine, $match)) { <del> $this->httpVersion = $match[1]; <del> $this->code = $match[2]; <del> $this->reasonPhrase = $match[3]; <del> } <del> <del> $this->headers = $this->_parseHeader($header); <del> $transferEncoding = $this->getHeader('Transfer-Encoding'); <del> $decoded = $this->_decodeBody($this->body, $transferEncoding); <del> $this->body = $decoded['body']; <del> <del> if (!empty($decoded['header'])) { <del> $this->headers = $this->_parseHeader($this->_buildHeader($this->headers) . $this->_buildHeader($decoded['header'])); <del> } <del> <del> if (!empty($this->headers)) { <del> $this->cookies = $this->parseCookies($this->headers); <del> } <del> } <del> <del>/** <del> * Generic function to decode a $body with a given $encoding. Returns either an array with the keys <del> * 'body' and 'header' or false on failure. <del> * <del> * @param string $body A string containing the body to decode. <del> * @param string|boolean $encoding Can be false in case no encoding is being used, or a string representing the encoding. <del> * @return mixed Array of response headers and body or false. <del> */ <del> protected function _decodeBody($body, $encoding = 'chunked') { <del> if (!is_string($body)) { <del> return false; <del> } <del> if (empty($encoding)) { <del> return array('body' => $body, 'header' => false); <del> } <del> $decodeMethod = '_decode' . Inflector::camelize(str_replace('-', '_', $encoding)) . 'Body'; <del> <del> if (!is_callable(array(&$this, $decodeMethod))) { <del> return array('body' => $body, 'header' => false); <del> } <del> return $this->{$decodeMethod}($body); <del> } <del> <del>/** <del> * Decodes a chunked message $body and returns either an array with the keys 'body' and 'header' or false as <del> * a result. <del> * <del> * @param string $body A string containing the chunked body to decode. <del> * @return mixed Array of response headers and body or false. <del> * @throws Cake\Error\SocketException <del> */ <del> protected function _decodeChunkedBody($body) { <del> if (!is_string($body)) { <del> return false; <del> } <del> <del> $decodedBody = null; <del> $chunkLength = null; <del> <del> while ($chunkLength !== 0) { <del> if (!preg_match('/^([0-9a-f]+) *(?:;(.+)=(.+))?(?:\r\n|\n)/iU', $body, $match)) { <del> throw new Error\SocketException(__d('cake_dev', 'HttpSocket::_decodeChunkedBody - Could not parse malformed chunk.')); <del> } <del> <del> $chunkSize = 0; <del> $hexLength = 0; <del> $chunkExtensionName = ''; <del> $chunkExtensionValue = ''; <del> if (isset($match[0])) { <del> $chunkSize = $match[0]; <del> } <del> if (isset($match[1])) { <del> $hexLength = $match[1]; <del> } <del> if (isset($match[2])) { <del> $chunkExtensionName = $match[2]; <del> } <del> if (isset($match[3])) { <del> $chunkExtensionValue = $match[3]; <del> } <del> <del> $body = substr($body, strlen($chunkSize)); <del> $chunkLength = hexdec($hexLength); <del> $chunk = substr($body, 0, $chunkLength); <del> if (!empty($chunkExtensionName)) { <del> // @todo See if there are popular chunk extensions we should implement <del> } <del> $decodedBody .= $chunk; <del> if ($chunkLength !== 0) { <del> $body = substr($body, $chunkLength + strlen("\r\n")); <del> } <del> } <del> <del> $entityHeader = false; <del> if (!empty($body)) { <del> $entityHeader = $this->_parseHeader($body); <del> } <del> return array('body' => $decodedBody, 'header' => $entityHeader); <del> } <del> <del>/** <del> * Parses an array based header. <del> * <del> * @param array $header Header as an indexed array (field => value) <del> * @return array Parsed header <del> */ <del> protected function _parseHeader($header) { <del> if (is_array($header)) { <del> return $header; <del> } elseif (!is_string($header)) { <del> return false; <del> } <del> <del> preg_match_all("/(.+):(.+)(?:(?<![\t ])\r\n|\$)/Uis", $header, $matches, PREG_SET_ORDER); <del> <del> $header = array(); <del> foreach ($matches as $match) { <del> list(, $field, $value) = $match; <del> <del> $value = trim($value); <del> $value = preg_replace("/[\t ]\r\n/", "\r\n", $value); <del> <del> $field = $this->_unescapeToken($field); <del> <del> if (!isset($header[$field])) { <del> $header[$field] = $value; <del> } else { <del> $header[$field] = array_merge((array)$header[$field], (array)$value); <del> } <del> } <del> return $header; <del> } <del> <del>/** <del> * Parses cookies in response headers. <del> * <del> * @param array $header Header array containing one ore more 'Set-Cookie' headers. <del> * @return mixed Either false on no cookies, or an array of cookies received. <del> * @todo Make this 100% RFC 2965 confirm <del> */ <del> public function parseCookies($header) { <del> $cookieHeader = $this->getHeader('Set-Cookie', $header); <del> if (!$cookieHeader) { <del> return false; <del> } <del> <del> $cookies = array(); <del> foreach ((array)$cookieHeader as $cookie) { <del> if (strpos($cookie, '";"') !== false) { <del> $cookie = str_replace('";"', "{__cookie_replace__}", $cookie); <del> $parts = str_replace("{__cookie_replace__}", '";"', explode(';', $cookie)); <del> } else { <del> $parts = preg_split('/\;[ \t]*/', $cookie); <del> } <del> <del> list($name, $value) = explode('=', array_shift($parts), 2); <del> $cookies[$name] = compact('value'); <del> <del> foreach ($parts as $part) { <del> if (strpos($part, '=') !== false) { <del> list($key, $value) = explode('=', $part); <del> } else { <del> $key = $part; <del> $value = true; <del> } <del> <del> $key = strtolower($key); <del> if (!isset($cookies[$name][$key])) { <del> $cookies[$name][$key] = $value; <del> } <del> } <del> } <del> return $cookies; <del> } <del> <del>/** <del> * Unescapes a given $token according to RFC 2616 (HTTP 1.1 specs) <del> * <del> * @param string $token Token to unescape <del> * @param array $chars <del> * @return string Unescaped token <del> * @todo Test $chars parameter <del> */ <del> protected function _unescapeToken($token, $chars = null) { <del> $regex = '/"([' . implode('', $this->_tokenEscapeChars(true, $chars)) . '])"/'; <del> $token = preg_replace($regex, '\\1', $token); <del> return $token; <del> } <del> <del>/** <del> * Gets escape chars according to RFC 2616 (HTTP 1.1 specs). <del> * <del> * @param boolean $hex true to get them as HEX values, false otherwise <del> * @param array $chars <del> * @return array Escape chars <del> * @todo Test $chars parameter <del> */ <del> protected function _tokenEscapeChars($hex = true, $chars = null) { <del> if (!empty($chars)) { <del> $escape = $chars; <del> } else { <del> $escape = array('"', "(", ")", "<", ">", "@", ",", ";", ":", "\\", "/", "[", "]", "?", "=", "{", "}", " "); <del> for ($i = 0; $i <= 31; $i++) { <del> $escape[] = chr($i); <del> } <del> $escape[] = chr(127); <del> } <del> <del> if (!$hex) { <del> return $escape; <del> } <del> foreach ($escape as $key => $char) { <del> $escape[$key] = '\\x' . str_pad(dechex(ord($char)), 2, '0', STR_PAD_LEFT); <del> } <del> return $escape; <del> } <del> <del>/** <del> * ArrayAccess - Offset Exists <del> * <del> * @param string $offset <del> * @return boolean <del> */ <del> public function offsetExists($offset) { <del> return in_array($offset, array('raw', 'status', 'header', 'body', 'cookies')); <del> } <del> <del>/** <del> * ArrayAccess - Offset Get <del> * <del> * @param string $offset <del> * @return mixed <del> */ <del> public function offsetGet($offset) { <del> switch ($offset) { <del> case 'raw': <del> $firstLineLength = strpos($this->raw, "\r\n") + 2; <del> if ($this->raw[$firstLineLength] === "\r") { <del> $header = null; <del> } else { <del> $header = substr($this->raw, $firstLineLength, strpos($this->raw, "\r\n\r\n") - $firstLineLength) . "\r\n"; <del> } <del> return array( <del> 'status-line' => $this->httpVersion . ' ' . $this->code . ' ' . $this->reasonPhrase . "\r\n", <del> 'header' => $header, <del> 'body' => $this->body, <del> 'response' => $this->raw <del> ); <del> case 'status': <del> return array( <del> 'http-version' => $this->httpVersion, <del> 'code' => $this->code, <del> 'reason-phrase' => $this->reasonPhrase <del> ); <del> case 'header': <del> return $this->headers; <del> case 'body': <del> return $this->body; <del> case 'cookies': <del> return $this->cookies; <del> } <del> return null; <del> } <del> <del>/** <del> * ArrayAccess - Offset Set <del> * <del> * @param string $offset <del> * @param mixed $value <del> * @return void <del> */ <del> public function offsetSet($offset, $value) { <del> } <del> <del>/** <del> * ArrayAccess - Offset Unset <del> * <del> * @param string $offset <del> * @return void <del> */ <del> public function offsetUnset($offset) { <del> } <del> <del>/** <del> * Instance as string <del> * <del> * @return string <del> */ <del> public function __toString() { <del> return $this->body(); <del> } <del> <del>} <ide><path>lib/Cake/Network/Http/HttpSocket.php <del><?php <del>/** <del> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) <del> * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) <del> * <del> * Licensed under The MIT License <del> * Redistributions of files must retain the above copyright notice. <del> * <del> * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) <del> * @link http://cakephp.org CakePHP(tm) Project <del> * @since CakePHP(tm) v 1.2.0 <del> * @license MIT License (http://www.opensource.org/licenses/mit-license.php) <del> */ <del>namespace Cake\Network\Http; <del> <del>use Cake\Core\App; <del>use Cake\Error; <del>use Cake\Network\Socket; <del>use Cake\Utility\Hash; <del>use Cake\Utility\Inflector; <del> <del>/** <del> * Cake network socket connection class. <del> * <del> * Core base class for HTTP network communication. HttpSocket can be used as an <del> * Object Oriented replacement for cURL in many places. <del> * <del> * @package Cake.Network.Http <del> */ <del>class HttpSocket extends Socket { <del> <del>/** <del> * When one activates the $quirksMode by setting it to true, all checks meant to <del> * enforce RFC 2616 (HTTP/1.1 specs). <del> * will be disabled and additional measures to deal with non-standard responses will be enabled. <del> * <del> * @var boolean <del> */ <del> public $quirksMode = false; <del> <del>/** <del> * Contain information about the last request (read only) <del> * <del> * @var array <del> */ <del> public $request = array( <del> 'method' => 'GET', <del> 'uri' => array( <del> 'scheme' => 'http', <del> 'host' => null, <del> 'port' => 80, <del> 'user' => null, <del> 'pass' => null, <del> 'path' => null, <del> 'query' => null, <del> 'fragment' => null <del> ), <del> 'version' => '1.1', <del> 'body' => '', <del> 'line' => null, <del> 'header' => array( <del> 'Connection' => 'close', <del> 'User-Agent' => 'CakePHP' <del> ), <del> 'raw' => null, <del> 'redirect' => false, <del> 'cookies' => array(), <del> ); <del> <del>/** <del> * Contain information about the last response (read only) <del> * <del> * @var array <del> */ <del> public $response = null; <del> <del>/** <del> * Response classname <del> * <del> * @var string <del> */ <del> public $responseClass = 'HttpResponse'; <del> <del>/** <del> * Configuration settings for the HttpSocket and the requests <del> * <del> * @var array <del> */ <del> public $config = array( <del> 'persistent' => false, <del> 'host' => 'localhost', <del> 'protocol' => 'tcp', <del> 'port' => 80, <del> 'timeout' => 30, <del> 'ssl_verify_peer' => true, <del> 'ssl_verify_depth' => 5, <del> 'ssl_verify_host' => true, <del> 'request' => array( <del> 'uri' => array( <del> 'scheme' => array('http', 'https'), <del> 'host' => 'localhost', <del> 'port' => array(80, 443) <del> ), <del> 'redirect' => false, <del> 'cookies' => array(), <del> ) <del> ); <del> <del>/** <del> * Authentication settings <del> * <del> * @var array <del> */ <del> protected $_auth = array(); <del> <del>/** <del> * Proxy settings <del> * <del> * @var array <del> */ <del> protected $_proxy = array(); <del> <del>/** <del> * Resource to receive the content of request <del> * <del> * @var mixed <del> */ <del> protected $_contentResource = null; <del> <del>/** <del> * Build an HTTP Socket using the specified configuration. <del> * <del> * You can use a url string to set the url and use default configurations for <del> * all other options: <del> * <del> * `$http = new HttpSocket('http://cakephp.org/');` <del> * <del> * Or use an array to configure multiple options: <del> * <del> * {{{ <del> * $http = new HttpSocket(array( <del> * 'host' => 'cakephp.org', <del> * 'timeout' => 20 <del> * )); <del> * }}} <del> * <del> * See HttpSocket::$config for options that can be used. <del> * <del> * @param string|array $config Configuration information, either a string url or an array of options. <del> */ <del> public function __construct($config = array()) { <del> if (is_string($config)) { <del> $this->_configUri($config); <del> } elseif (is_array($config)) { <del> if (isset($config['request']['uri']) && is_string($config['request']['uri'])) { <del> $this->_configUri($config['request']['uri']); <del> unset($config['request']['uri']); <del> } <del> $this->config = Hash::merge($this->config, $config); <del> } <del> parent::__construct($this->config); <del> } <del> <del>/** <del> * Set authentication settings. <del> * <del> * Accepts two forms of parameters. If all you need is a username + password, as with <del> * Basic authentication you can do the following: <del> * <del> * {{{ <del> * $http->configAuth('Basic', 'mark', 'secret'); <del> * }}} <del> * <del> * If you are using an authentication strategy that requires more inputs, like Digest authentication <del> * you can call `configAuth()` with an array of user information. <del> * <del> * {{{ <del> * $http->configAuth('Digest', array( <del> * 'user' => 'mark', <del> * 'pass' => 'secret', <del> * 'realm' => 'my-realm', <del> * 'nonce' => 1235 <del> * )); <del> * }}} <del> * <del> * To remove any set authentication strategy, call `configAuth()` with no parameters: <del> * <del> * `$http->configAuth();` <del> * <del> * @param string $method Authentication method (ie. Basic, Digest). If empty, disable authentication <del> * @param string|array $user Username for authentication. Can be an array with settings to authentication class <del> * @param string $pass Password for authentication <del> * @return void <del> */ <del> public function configAuth($method, $user = null, $pass = null) { <del> if (empty($method)) { <del> $this->_auth = array(); <del> return; <del> } <del> if (is_array($user)) { <del> $this->_auth = array($method => $user); <del> return; <del> } <del> $this->_auth = array($method => compact('user', 'pass')); <del> } <del> <del>/** <del> * Set proxy settings <del> * <del> * @param string|array $host Proxy host. Can be an array with settings to authentication class <del> * @param integer $port Port. Default 3128. <del> * @param string $method Proxy method (ie, Basic, Digest). If empty, disable proxy authentication <del> * @param string $user Username if your proxy need authentication <del> * @param string $pass Password to proxy authentication <del> * @return void <del> */ <del> public function configProxy($host, $port = 3128, $method = null, $user = null, $pass = null) { <del> if (empty($host)) { <del> $this->_proxy = array(); <del> return; <del> } <del> if (is_array($host)) { <del> $this->_proxy = $host + array('host' => null); <del> return; <del> } <del> $this->_proxy = compact('host', 'port', 'method', 'user', 'pass'); <del> } <del> <del>/** <del> * Set the resource to receive the request content. This resource must support fwrite. <del> * <del> * @param resource|boolean $resource Resource or false to disable the resource use <del> * @return void <del> * @throws Cake\Error\SocketException <del> */ <del> public function setContentResource($resource) { <del> if ($resource === false) { <del> $this->_contentResource = null; <del> return; <del> } <del> if (!is_resource($resource)) { <del> throw new Error\SocketException(__d('cake_dev', 'Invalid resource.')); <del> } <del> $this->_contentResource = $resource; <del> } <del> <del>/** <del> * Issue the specified request. HttpSocket::get() and HttpSocket::post() wrap this <del> * method and provide a more granular interface. <del> * <del> * @param string|array $request Either an URI string, or an array defining host/uri <del> * @return mixed false on error, HttpResponse on success <del> * @throws Cake\Error\SocketException <del> */ <del> public function request($request = array()) { <del> $this->reset(false); <del> <del> if (is_string($request)) { <del> $request = array('uri' => $request); <del> } elseif (!is_array($request)) { <del> return false; <del> } <del> <del> if (!isset($request['uri'])) { <del> $request['uri'] = null; <del> } <del> $uri = $this->_parseUri($request['uri']); <del> if (!isset($uri['host'])) { <del> $host = $this->config['host']; <del> } <del> if (isset($request['host'])) { <del> $host = $request['host']; <del> unset($request['host']); <del> } <del> $request['uri'] = $this->url($request['uri']); <del> $request['uri'] = $this->_parseUri($request['uri'], true); <del> $this->request = Hash::merge($this->request, array_diff_key($this->config['request'], array('cookies' => true)), $request); <del> <del> $this->_configUri($this->request['uri']); <del> <del> $Host = $this->request['uri']['host']; <del> if (!empty($this->config['request']['cookies'][$Host])) { <del> if (!isset($this->request['cookies'])) { <del> $this->request['cookies'] = array(); <del> } <del> if (!isset($request['cookies'])) { <del> $request['cookies'] = array(); <del> } <del> $this->request['cookies'] = array_merge($this->request['cookies'], $this->config['request']['cookies'][$Host], $request['cookies']); <del> } <del> <del> if (isset($host)) { <del> $this->config['host'] = $host; <del> } <del> $this->_setProxy(); <del> $this->request['proxy'] = $this->_proxy; <del> <del> $cookies = null; <del> <del> if (is_array($this->request['header'])) { <del> if (!empty($this->request['cookies'])) { <del> $cookies = $this->buildCookies($this->request['cookies']); <del> } <del> $scheme = ''; <del> $port = 0; <del> if (isset($this->request['uri']['scheme'])) { <del> $scheme = $this->request['uri']['scheme']; <del> } <del> if (isset($this->request['uri']['port'])) { <del> $port = $this->request['uri']['port']; <del> } <del> if ( <del> ($scheme === 'http' && $port != 80) || <del> ($scheme === 'https' && $port != 443) || <del> ($port != 80 && $port != 443) <del> ) { <del> $Host .= ':' . $port; <del> } <del> $this->request['header'] = array_merge(compact('Host'), $this->request['header']); <del> } <del> <del> if (isset($this->request['uri']['user'], $this->request['uri']['pass'])) { <del> $this->configAuth('Basic', $this->request['uri']['user'], $this->request['uri']['pass']); <del> } <del> $this->_setAuth(); <del> $this->request['auth'] = $this->_auth; <del> <del> if (is_array($this->request['body'])) { <del> $this->request['body'] = http_build_query($this->request['body']); <del> } <del> <del> if (!empty($this->request['body']) && !isset($this->request['header']['Content-Type'])) { <del> $this->request['header']['Content-Type'] = 'application/x-www-form-urlencoded'; <del> } <del> <del> if (!empty($this->request['body']) && !isset($this->request['header']['Content-Length'])) { <del> $this->request['header']['Content-Length'] = strlen($this->request['body']); <del> } <del> <del> $connectionType = null; <del> if (isset($this->request['header']['Connection'])) { <del> $connectionType = $this->request['header']['Connection']; <del> } <del> $this->request['header'] = $this->_buildHeader($this->request['header']) . $cookies; <del> <del> if (empty($this->request['line'])) { <del> $this->request['line'] = $this->_buildRequestLine($this->request); <del> } <del> <del> if ($this->quirksMode === false && $this->request['line'] === false) { <del> return false; <del> } <del> <del> $this->_configContext($this->request['uri']['host']); <del> <del> $this->request['raw'] = ''; <del> if ($this->request['line'] !== false) { <del> $this->request['raw'] = $this->request['line']; <del> } <del> <del> if ($this->request['header'] !== false) { <del> $this->request['raw'] .= $this->request['header']; <del> } <del> <del> $this->request['raw'] .= "\r\n"; <del> $this->request['raw'] .= $this->request['body']; <del> $this->write($this->request['raw']); <del> <del> $response = null; <del> $inHeader = true; <del> while ($data = $this->read()) { <del> if ($this->_contentResource) { <del> if ($inHeader) { <del> $response .= $data; <del> $pos = strpos($response, "\r\n\r\n"); <del> if ($pos !== false) { <del> $pos += 4; <del> $data = substr($response, $pos); <del> fwrite($this->_contentResource, $data); <del> <del> $response = substr($response, 0, $pos); <del> $inHeader = false; <del> } <del> } else { <del> fwrite($this->_contentResource, $data); <del> fflush($this->_contentResource); <del> } <del> } else { <del> $response .= $data; <del> } <del> } <del> <del> if ($connectionType === 'close') { <del> $this->disconnect(); <del> } <del> <del> $responseClass = App::classname($this->responseClass, 'Network/Http'); <del> if (!$responseClass) { <del> throw new Error\SocketException(__d('cake_dev', 'Class %s not found.', $this->responseClass)); <del> } <del> $this->response = new $responseClass($response); <del> <del> if (!empty($this->response->cookies)) { <del> if (!isset($this->config['request']['cookies'][$Host])) { <del> $this->config['request']['cookies'][$Host] = array(); <del> } <del> $this->config['request']['cookies'][$Host] = array_merge($this->config['request']['cookies'][$Host], $this->response->cookies); <del> } <del> <del> if ($this->request['redirect'] && $this->response->isRedirect()) { <del> $request['uri'] = trim(urldecode($this->response->getHeader('Location')), '='); <del> $request['redirect'] = is_int($this->request['redirect']) ? $this->request['redirect'] - 1 : $this->request['redirect']; <del> $this->response = $this->request($request); <del> } <del> <del> return $this->response; <del> } <del> <del>/** <del> * Issues a GET request to the specified URI, query, and request. <del> * <del> * Using a string uri and an array of query string parameters: <del> * <del> * `$response = $http->get('http://google.com/search', array('q' => 'cakephp', 'client' => 'safari'));` <del> * <del> * Would do a GET request to `http://google.com/search?q=cakephp&client=safari` <del> * <del> * You could express the same thing using a uri array and query string parameters: <del> * <del> * {{{ <del> * $response = $http->get( <del> * array('host' => 'google.com', 'path' => '/search'), <del> * array('q' => 'cakephp', 'client' => 'safari') <del> * ); <del> * }}} <del> * <del> * @param string|array $uri URI to request. Either a string uri, or a uri array, see HttpSocket::_parseUri() <del> * @param array $query Querystring parameters to append to URI <del> * @param array $request An indexed array with indexes such as 'method' or uri <del> * @return mixed Result of request, either false on failure or the response to the request. <del> */ <del> public function get($uri = null, $query = array(), $request = array()) { <del> if (!empty($query)) { <del> $uri = $this->_parseUri($uri, $this->config['request']['uri']); <del> if (isset($uri['query'])) { <del> $uri['query'] = array_merge($uri['query'], $query); <del> } else { <del> $uri['query'] = $query; <del> } <del> $uri = $this->_buildUri($uri); <del> } <del> <del> $request = Hash::merge(array('method' => 'GET', 'uri' => $uri), $request); <del> return $this->request($request); <del> } <del> <del>/** <del> * Issues a POST request to the specified URI, query, and request. <del> * <del> * `post()` can be used to post simple data arrays to a url: <del> * <del> * {{{ <del> * $response = $http->post('http://example.com', array( <del> * 'username' => 'batman', <del> * 'password' => 'bruce_w4yne' <del> * )); <del> * }}} <del> * <del> * @param string|array $uri URI to request. See HttpSocket::_parseUri() <del> * @param array $data Array of POST data keys and values. <del> * @param array $request An indexed array with indexes such as 'method' or uri <del> * @return mixed Result of request, either false on failure or the response to the request. <del> */ <del> public function post($uri = null, $data = array(), $request = array()) { <del> $request = Hash::merge(array('method' => 'POST', 'uri' => $uri, 'body' => $data), $request); <del> return $this->request($request); <del> } <del> <del>/** <del> * Issues a PUT request to the specified URI, query, and request. <del> * <del> * @param string|array $uri URI to request, See HttpSocket::_parseUri() <del> * @param array $data Array of PUT data keys and values. <del> * @param array $request An indexed array with indexes such as 'method' or uri <del> * @return mixed Result of request <del> */ <del> public function put($uri = null, $data = array(), $request = array()) { <del> $request = Hash::merge(array('method' => 'PUT', 'uri' => $uri, 'body' => $data), $request); <del> return $this->request($request); <del> } <del> <del>/** <del> * Issues a DELETE request to the specified URI, query, and request. <del> * <del> * @param string|array $uri URI to request (see {@link _parseUri()}) <del> * @param array $data Query to append to URI <del> * @param array $request An indexed array with indexes such as 'method' or uri <del> * @return mixed Result of request <del> */ <del> public function delete($uri = null, $data = array(), $request = array()) { <del> $request = Hash::merge(array('method' => 'DELETE', 'uri' => $uri, 'body' => $data), $request); <del> return $this->request($request); <del> } <del> <del>/** <del> * Normalizes urls into a $uriTemplate. If no template is provided <del> * a default one will be used. Will generate the url using the <del> * current config information. <del> * <del> * ### Usage: <del> * <del> * After configuring part of the request parameters, you can use url() to generate <del> * urls. <del> * <del> * {{{ <del> * $http = new HttpSocket('http://www.cakephp.org'); <del> * $url = $http->url('/search?q=bar'); <del> * }}} <del> * <del> * Would return `http://www.cakephp.org/search?q=bar` <del> * <del> * url() can also be used with custom templates: <del> * <del> * `$url = $http->url('http://www.cakephp/search?q=socket', '/%path?%query');` <del> * <del> * Would return `/search?q=socket`. <del> * <del> * @param string|array Either a string or array of url options to create a url with. <del> * @param string $uriTemplate A template string to use for url formatting. <del> * @return mixed Either false on failure or a string containing the composed url. <del> */ <del> public function url($url = null, $uriTemplate = null) { <del> if (is_null($url)) { <del> $url = '/'; <del> } <del> if (is_string($url)) { <del> $scheme = $this->config['request']['uri']['scheme']; <del> if (is_array($scheme)) { <del> $scheme = $scheme[0]; <del> } <del> $port = $this->config['request']['uri']['port']; <del> if (is_array($port)) { <del> $port = $port[0]; <del> } <del> if ($url{0} == '/') { <del> $url = $this->config['request']['uri']['host'] . ':' . $port . $url; <del> } <del> if (!preg_match('/^.+:\/\/|\*|^\//', $url)) { <del> $url = $scheme . '://' . $url; <del> } <del> } elseif (!is_array($url) && !empty($url)) { <del> return false; <del> } <del> <del> $base = array_merge($this->config['request']['uri'], array('scheme' => array('http', 'https'), 'port' => array(80, 443))); <del> $url = $this->_parseUri($url, $base); <del> <del> if (empty($url)) { <del> $url = $this->config['request']['uri']; <del> } <del> <del> if (!empty($uriTemplate)) { <del> return $this->_buildUri($url, $uriTemplate); <del> } <del> return $this->_buildUri($url); <del> } <del> <del>/** <del> * Set authentication in request <del> * <del> * @return void <del> * @throws Cake\Error\SocketException <del> */ <del> protected function _setAuth() { <del> if (empty($this->_auth)) { <del> return; <del> } <del> $method = key($this->_auth); <del> <del> $authClass = App::classname($method, 'Network/Http', 'Authentication'); <del> if (!$authClass) { <del> throw new Error\SocketException(__d('cake_dev', 'Unknown authentication method.')); <del> } <del> if (!method_exists($authClass, 'authentication')) { <del> throw new Error\SocketException(sprintf(__d('cake_dev', 'The %s do not support authentication.'), $authClass)); <del> } <del> call_user_func_array("$authClass::authentication", array($this, &$this->_auth[$method])); <del> } <del> <del>/** <del> * Set the proxy configuration and authentication <del> * <del> * @return void <del> * @throws Cake\Error\SocketException <del> */ <del> protected function _setProxy() { <del> if (empty($this->_proxy) || !isset($this->_proxy['host'], $this->_proxy['port'])) { <del> return; <del> } <del> $this->config['host'] = $this->_proxy['host']; <del> $this->config['port'] = $this->_proxy['port']; <del> <del> if (empty($this->_proxy['method']) || !isset($this->_proxy['user'], $this->_proxy['pass'])) { <del> return; <del> } <del> <del> $authClass = App::classname($this->_proxy['method'], 'Network/Http', 'Authentication'); <del> if (!$authClass) { <del> throw new Error\SocketException(__d('cake_dev', 'Unknown authentication method for proxy.')); <del> } <del> if (!method_exists($authClass, 'proxyAuthentication')) { <del> throw new Error\SocketException(sprintf(__d('cake_dev', 'The %s do not support proxy authentication.'), $authClass)); <del> } <del> call_user_func_array("$authClass::proxyAuthentication", array($this, &$this->_proxy)); <del> } <del> <del>/** <del> * Parses and sets the specified URI into current request configuration. <del> * <del> * @param string|array $uri URI, See HttpSocket::_parseUri() <del> * @return boolean If uri has merged in config <del> */ <del> protected function _configUri($uri = null) { <del> if (empty($uri)) { <del> return false; <del> } <del> <del> if (is_array($uri)) { <del> $uri = $this->_parseUri($uri); <del> } else { <del> $uri = $this->_parseUri($uri, true); <del> } <del> <del> if (!isset($uri['host'])) { <del> return false; <del> } <del> $config = array( <del> 'request' => array( <del> 'uri' => array_intersect_key($uri, $this->config['request']['uri']) <del> ) <del> ); <del> $this->config = Hash::merge($this->config, $config); <del> $this->config = Hash::merge($this->config, array_intersect_key($this->config['request']['uri'], $this->config)); <del> return true; <del> } <del> <del>/** <del> * Configure the socket's context. Adds in configuration <del> * that can not be declared in the class definition. <del> * <del> * @param string $host The host you're connecting to. <del> * @return void <del> */ <del> protected function _configContext($host) { <del> foreach ($this->config as $key => $value) { <del> if (substr($key, 0, 4) !== 'ssl_') { <del> continue; <del> } <del> $contextKey = substr($key, 4); <del> if (empty($this->config['context']['ssl'][$contextKey])) { <del> $this->config['context']['ssl'][$contextKey] = $value; <del> } <del> unset($this->config[$key]); <del> } <del> if (empty($this->_context['ssl']['cafile'])) { <del> $this->config['context']['ssl']['cafile'] = CAKE . 'Config' . DS . 'cacert.pem'; <del> } <del> if (!empty($this->config['context']['ssl']['verify_host'])) { <del> $this->config['context']['ssl']['CN_match'] = $host; <del> unset($this->config['context']['ssl']['verify_host']); <del> } <del> } <del> <del>/** <del> * Takes a $uri array and turns it into a fully qualified URL string <del> * <del> * @param string|array $uri Either A $uri array, or a request string. Will use $this->config if left empty. <del> * @param string $uriTemplate The Uri template/format to use. <del> * @return mixed A fully qualified URL formatted according to $uriTemplate, or false on failure <del> */ <del> protected function _buildUri($uri = array(), $uriTemplate = '%scheme://%user:%pass@%host:%port/%path?%query#%fragment') { <del> if (is_string($uri)) { <del> $uri = array('host' => $uri); <del> } <del> $uri = $this->_parseUri($uri, true); <del> <del> if (!is_array($uri) || empty($uri)) { <del> return false; <del> } <del> <del> $uri['path'] = preg_replace('/^\//', null, $uri['path']); <del> $uri['query'] = http_build_query($uri['query']); <del> $uri['query'] = rtrim($uri['query'], '='); <del> $stripIfEmpty = array( <del> 'query' => '?%query', <del> 'fragment' => '#%fragment', <del> 'user' => '%user:%pass@', <del> 'host' => '%host:%port/' <del> ); <del> <del> foreach ($stripIfEmpty as $key => $strip) { <del> if (empty($uri[$key])) { <del> $uriTemplate = str_replace($strip, null, $uriTemplate); <del> } <del> } <del> <del> $defaultPorts = array('http' => 80, 'https' => 443); <del> if (array_key_exists($uri['scheme'], $defaultPorts) && $defaultPorts[$uri['scheme']] == $uri['port']) { <del> $uriTemplate = str_replace(':%port', null, $uriTemplate); <del> } <del> foreach ($uri as $property => $value) { <del> $uriTemplate = str_replace('%' . $property, $value, $uriTemplate); <del> } <del> <del> if ($uriTemplate === '/*') { <del> $uriTemplate = '*'; <del> } <del> return $uriTemplate; <del> } <del> <del>/** <del> * Parses the given URI and breaks it down into pieces as an indexed array with elements <del> * such as 'scheme', 'port', 'query'. <del> * <del> * @param string|array $uri URI to parse <del> * @param boolean|array $base If true use default URI config, otherwise indexed array to set 'scheme', 'host', 'port', etc. <del> * @return array Parsed URI <del> */ <del> protected function _parseUri($uri = null, $base = array()) { <del> $uriBase = array( <del> 'scheme' => array('http', 'https'), <del> 'host' => null, <del> 'port' => array(80, 443), <del> 'user' => null, <del> 'pass' => null, <del> 'path' => '/', <del> 'query' => null, <del> 'fragment' => null <del> ); <del> <del> if (is_string($uri)) { <del> $uri = parse_url($uri); <del> } <del> if (!is_array($uri) || empty($uri)) { <del> return false; <del> } <del> if ($base === true) { <del> $base = $uriBase; <del> } <del> <del> if (isset($base['port'], $base['scheme']) && is_array($base['port']) && is_array($base['scheme'])) { <del> if (isset($uri['scheme']) && !isset($uri['port'])) { <del> $base['port'] = $base['port'][array_search($uri['scheme'], $base['scheme'])]; <del> } elseif (isset($uri['port']) && !isset($uri['scheme'])) { <del> $base['scheme'] = $base['scheme'][array_search($uri['port'], $base['port'])]; <del> } <del> } <del> <del> if (is_array($base) && !empty($base)) { <del> $uri = array_merge($base, $uri); <del> } <del> <del> if (isset($uri['scheme']) && is_array($uri['scheme'])) { <del> $uri['scheme'] = array_shift($uri['scheme']); <del> } <del> if (isset($uri['port']) && is_array($uri['port'])) { <del> $uri['port'] = array_shift($uri['port']); <del> } <del> <del> if (array_key_exists('query', $uri)) { <del> $uri['query'] = $this->_parseQuery($uri['query']); <del> } <del> <del> if (!array_intersect_key($uriBase, $uri)) { <del> return false; <del> } <del> return $uri; <del> } <del> <del>/** <del> * This function can be thought of as a reverse to PHP5's http_build_query(). It takes a given query string and turns it into an array and <del> * supports nesting by using the php bracket syntax. So this means you can parse queries like: <del> * <del> * - ?key[subKey]=value <del> * - ?key[]=value1&key[]=value2 <del> * <del> * A leading '?' mark in $query is optional and does not effect the outcome of this function. <del> * For the complete capabilities of this implementation take a look at HttpSocketTest::testparseQuery() <del> * <del> * @param string|array $query A query string to parse into an array or an array to return directly "as is" <del> * @return array The $query parsed into a possibly multi-level array. If an empty $query is <del> * given, an empty array is returned. <del> */ <del> protected function _parseQuery($query) { <del> if (is_array($query)) { <del> return $query; <del> } <del> <del> $parsedQuery = array(); <del> <del> if (is_string($query) && !empty($query)) { <del> $query = preg_replace('/^\?/', '', $query); <del> $items = explode('&', $query); <del> <del> foreach ($items as $item) { <del> if (strpos($item, '=') !== false) { <del> list($key, $value) = explode('=', $item, 2); <del> } else { <del> $key = $item; <del> $value = null; <del> } <del> <del> $key = urldecode($key); <del> $value = urldecode($value); <del> <del> if (preg_match_all('/\[([^\[\]]*)\]/iUs', $key, $matches)) { <del> $subKeys = $matches[1]; <del> $rootKey = substr($key, 0, strpos($key, '[')); <del> if (!empty($rootKey)) { <del> array_unshift($subKeys, $rootKey); <del> } <del> $queryNode =& $parsedQuery; <del> <del> foreach ($subKeys as $subKey) { <del> if (!is_array($queryNode)) { <del> $queryNode = array(); <del> } <del> <del> if ($subKey === '') { <del> $queryNode[] = array(); <del> end($queryNode); <del> $subKey = key($queryNode); <del> } <del> $queryNode =& $queryNode[$subKey]; <del> } <del> $queryNode = $value; <del> continue; <del> } <del> if (!isset($parsedQuery[$key])) { <del> $parsedQuery[$key] = $value; <del> } else { <del> $parsedQuery[$key] = (array)$parsedQuery[$key]; <del> $parsedQuery[$key][] = $value; <del> } <del> } <del> } <del> return $parsedQuery; <del> } <del> <del>/** <del> * Builds a request line according to HTTP/1.1 specs. Activate quirks mode to work outside specs. <del> * <del> * @param array $request Needs to contain a 'uri' key. Should also contain a 'method' key, otherwise defaults to GET. <del> * @param string $versionToken The version token to use, defaults to HTTP/1.1 <del> * @return string Request line <del> * @throws Cake\Error\SocketException <del> */ <del> protected function _buildRequestLine($request = array(), $versionToken = 'HTTP/1.1') { <del> $asteriskMethods = array('OPTIONS'); <del> <del> if (is_string($request)) { <del> $isValid = preg_match("/(.+) (.+) (.+)\r\n/U", $request, $match); <del> if (!$this->quirksMode && (!$isValid || ($match[2] == '*' && !in_array($match[3], $asteriskMethods)))) { <del> throw new Error\SocketException(__d('cake_dev', 'HttpSocket::_buildRequestLine - Passed an invalid request line string. Activate quirks mode to do this.')); <del> } <del> return $request; <del> } elseif (!is_array($request)) { <del> return false; <del> } elseif (!array_key_exists('uri', $request)) { <del> return false; <del> } <del> <del> $request['uri'] = $this->_parseUri($request['uri']); <del> $request = array_merge(array('method' => 'GET'), $request); <del> if (!empty($this->_proxy['host'])) { <del> $request['uri'] = $this->_buildUri($request['uri'], '%scheme://%host:%port/%path?%query'); <del> } else { <del> $request['uri'] = $this->_buildUri($request['uri'], '/%path?%query'); <del> } <del> <del> if (!$this->quirksMode && $request['uri'] === '*' && !in_array($request['method'], $asteriskMethods)) { <del> throw new Error\SocketException(__d('cake_dev', 'HttpSocket::_buildRequestLine - The "*" asterisk character is only allowed for the following methods: %s. Activate quirks mode to work outside of HTTP/1.1 specs.', implode(',', $asteriskMethods))); <del> } <del> return $request['method'] . ' ' . $request['uri'] . ' ' . $versionToken . "\r\n"; <del> } <del> <del>/** <del> * Builds the header. <del> * <del> * @param array $header Header to build <del> * @param string $mode <del> * @return string Header built from array <del> */ <del> protected function _buildHeader($header, $mode = 'standard') { <del> if (is_string($header)) { <del> return $header; <del> } elseif (!is_array($header)) { <del> return false; <del> } <del> <del> $fieldsInHeader = array(); <del> foreach ($header as $key => $value) { <del> $lowKey = strtolower($key); <del> if (array_key_exists($lowKey, $fieldsInHeader)) { <del> $header[$fieldsInHeader[$lowKey]] = $value; <del> unset($header[$key]); <del> } else { <del> $fieldsInHeader[$lowKey] = $key; <del> } <del> } <del> <del> $returnHeader = ''; <del> foreach ($header as $field => $contents) { <del> if (is_array($contents) && $mode == 'standard') { <del> $contents = implode(',', $contents); <del> } <del> foreach ((array)$contents as $content) { <del> $contents = preg_replace("/\r\n(?![\t ])/", "\r\n ", $content); <del> $field = $this->_escapeToken($field); <del> <del> $returnHeader .= $field . ': ' . $contents . "\r\n"; <del> } <del> } <del> return $returnHeader; <del> } <del> <del>/** <del> * Builds cookie headers for a request. <del> * <del> * @param array $cookies Array of cookies to send with the request. <del> * @return string Cookie header string to be sent with the request. <del> */ <del> public function buildCookies($cookies) { <del> $header = array(); <del> foreach ($cookies as $name => $cookie) { <del> $header[] = $name . '=' . $this->_escapeToken($cookie['value'], array(';')); <del> } <del> return $this->_buildHeader(array('Cookie' => implode('; ', $header)), 'pragmatic'); <del> } <del> <del>/** <del> * Escapes a given $token according to RFC 2616 (HTTP 1.1 specs) <del> * <del> * @param string $token Token to escape <del> * @param array $chars <del> * @return string Escaped token <del> */ <del> protected function _escapeToken($token, $chars = null) { <del> $regex = '/([' . implode('', $this->_tokenEscapeChars(true, $chars)) . '])/'; <del> $token = preg_replace($regex, '"\\1"', $token); <del> return $token; <del> } <del> <del>/** <del> * Gets escape chars according to RFC 2616 (HTTP 1.1 specs). <del> * <del> * @param boolean $hex true to get them as HEX values, false otherwise <del> * @param array $chars <del> * @return array Escape chars <del> */ <del> protected function _tokenEscapeChars($hex = true, $chars = null) { <del> if (!empty($chars)) { <del> $escape = $chars; <del> } else { <del> $escape = array('"', "(", ")", "<", ">", "@", ",", ";", ":", "\\", "/", "[", "]", "?", "=", "{", "}", " "); <del> for ($i = 0; $i <= 31; $i++) { <del> $escape[] = chr($i); <del> } <del> $escape[] = chr(127); <del> } <del> <del> if (!$hex) { <del> return $escape; <del> } <del> foreach ($escape as $key => $char) { <del> $escape[$key] = '\\x' . str_pad(dechex(ord($char)), 2, '0', STR_PAD_LEFT); <del> } <del> return $escape; <del> } <del> <del>/** <del> * Resets the state of this HttpSocket instance to it's initial state (before Object::__construct got executed) or does <del> * the same thing partially for the request and the response property only. <del> * <del> * @param boolean $full If set to false only HttpSocket::response and HttpSocket::request are reseted <del> * @return boolean True on success <del> */ <del> public function reset($full = true) { <del> static $initalState = array(); <del> if (empty($initalState)) { <del> $initalState = get_class_vars(__CLASS__); <del> } <del> if (!$full) { <del> $this->request = $initalState['request']; <del> $this->response = $initalState['response']; <del> return true; <del> } <del> parent::reset($initalState); <del> return true; <del> } <del> <del>} <ide><path>lib/Cake/Network/Http/HttpSocketResponse.php <del><?php <del>/** <del> * HTTP Response from HttpSocket. <del> * <del> * PHP 5 <del> * <del> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) <del> * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) <del> * <del> * Licensed under The MIT License <del> * Redistributions of files must retain the above copyright notice. <del> * <del> * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) <del> * @link http://cakephp.org CakePHP(tm) Project <del> * @since CakePHP(tm) v 2.0.0 <del> * @license MIT License (http://www.opensource.org/licenses/mit-license.php) <del> */ <del> <del>/** <del> * HTTP Response from HttpSocket. <del> * <del> * @package Cake.Network.Http <del> */ <del>class HttpSocketResponse implements ArrayAccess { <del> <del>/** <del> * Body content <del> * <del> * @var string <del> */ <del> public $body = ''; <del> <del>/** <del> * Headers <del> * <del> * @var array <del> */ <del> public $headers = array(); <del> <del>/** <del> * Cookies <del> * <del> * @var array <del> */ <del> public $cookies = array(); <del> <del>/** <del> * HTTP version <del> * <del> * @var string <del> */ <del> public $httpVersion = 'HTTP/1.1'; <del> <del>/** <del> * Response code <del> * <del> * @var integer <del> */ <del> public $code = 0; <del> <del>/** <del> * Reason phrase <del> * <del> * @var string <del> */ <del> public $reasonPhrase = ''; <del> <del>/** <del> * Pure raw content <del> * <del> * @var string <del> */ <del> public $raw = ''; <del> <del>/** <del> * Context data in the response. <del> * Contains SSL certificates for example. <del> * <del> * @var array <del> */ <del> public $context = array(); <del> <del>/** <del> * Constructor <del> * <del> * @param string $message <del> */ <del> public function __construct($message = null) { <del> if ($message !== null) { <del> $this->parseResponse($message); <del> } <del> } <del> <del>/** <del> * Body content <del> * <del> * @return string <del> */ <del> public function body() { <del> return (string)$this->body; <del> } <del> <del>/** <del> * Get header in case insensitive <del> * <del> * @param string $name Header name <del> * @param array $headers <del> * @return mixed String if header exists or null <del> */ <del> public function getHeader($name, $headers = null) { <del> if (!is_array($headers)) { <del> $headers =& $this->headers; <del> } <del> if (isset($headers[$name])) { <del> return $headers[$name]; <del> } <del> foreach ($headers as $key => $value) { <del> if (strcasecmp($key, $name) === 0) { <del> return $value; <del> } <del> } <del> return null; <del> } <del> <del>/** <del> * If return is 200 (OK) <del> * <del> * @return boolean <del> */ <del> public function isOk() { <del> return $this->code == 200; <del> } <del> <del>/** <del> * If return is a valid 3xx (Redirection) <del> * <del> * @return boolean <del> */ <del> public function isRedirect() { <del> return in_array($this->code, array(301, 302, 303, 307)) && !is_null($this->getHeader('Location')); <del> } <del> <del>/** <del> * Parses the given message and breaks it down in parts. <del> * <del> * @param string $message Message to parse <del> * @return void <del> * @throws SocketException <del> */ <del> public function parseResponse($message) { <del> if (!is_string($message)) { <del> throw new SocketException(__d('cake_dev', 'Invalid response.')); <del> } <del> <del> if (!preg_match("/^(.+\r\n)(.*)(?<=\r\n)\r\n/Us", $message, $match)) { <del> throw new SocketException(__d('cake_dev', 'Invalid HTTP response.')); <del> } <del> <del> list(, $statusLine, $header) = $match; <del> $this->raw = $message; <del> $this->body = (string)substr($message, strlen($match[0])); <del> <del> if (preg_match("/(.+) ([0-9]{3}) (.+)\r\n/DU", $statusLine, $match)) { <del> $this->httpVersion = $match[1]; <del> $this->code = $match[2]; <del> $this->reasonPhrase = $match[3]; <del> } <del> <del> $this->headers = $this->_parseHeader($header); <del> $transferEncoding = $this->getHeader('Transfer-Encoding'); <del> $decoded = $this->_decodeBody($this->body, $transferEncoding); <del> $this->body = $decoded['body']; <del> <del> if (!empty($decoded['header'])) { <del> $this->headers = $this->_parseHeader($this->_buildHeader($this->headers) . $this->_buildHeader($decoded['header'])); <del> } <del> <del> if (!empty($this->headers)) { <del> $this->cookies = $this->parseCookies($this->headers); <del> } <del> } <del> <del>/** <del> * Generic function to decode a $body with a given $encoding. Returns either an array with the keys <del> * 'body' and 'header' or false on failure. <del> * <del> * @param string $body A string containing the body to decode. <del> * @param string|boolean $encoding Can be false in case no encoding is being used, or a string representing the encoding. <del> * @return mixed Array of response headers and body or false. <del> */ <del> protected function _decodeBody($body, $encoding = 'chunked') { <del> if (!is_string($body)) { <del> return false; <del> } <del> if (empty($encoding)) { <del> return array('body' => $body, 'header' => false); <del> } <del> $decodeMethod = '_decode' . Inflector::camelize(str_replace('-', '_', $encoding)) . 'Body'; <del> <del> if (!is_callable(array(&$this, $decodeMethod))) { <del> return array('body' => $body, 'header' => false); <del> } <del> return $this->{$decodeMethod}($body); <del> } <del> <del>/** <del> * Decodes a chunked message $body and returns either an array with the keys 'body' and 'header' or false as <del> * a result. <del> * <del> * @param string $body A string containing the chunked body to decode. <del> * @return mixed Array of response headers and body or false. <del> * @throws SocketException <del> */ <del> protected function _decodeChunkedBody($body) { <del> if (!is_string($body)) { <del> return false; <del> } <del> <del> $decodedBody = null; <del> $chunkLength = null; <del> <del> while ($chunkLength !== 0) { <del> if (!preg_match('/^([0-9a-f]+) *(?:;(.+)=(.+))?(?:\r\n|\n)/iU', $body, $match)) { <del> throw new SocketException(__d('cake_dev', 'HttpSocket::_decodeChunkedBody - Could not parse malformed chunk.')); <del> } <del> <del> $chunkSize = 0; <del> $hexLength = 0; <del> $chunkExtensionValue = ''; <del> if (isset($match[0])) { <del> $chunkSize = $match[0]; <del> } <del> if (isset($match[1])) { <del> $hexLength = $match[1]; <del> } <del> if (isset($match[3])) { <del> $chunkExtensionValue = $match[3]; <del> } <del> <del> $body = substr($body, strlen($chunkSize)); <del> $chunkLength = hexdec($hexLength); <del> $chunk = substr($body, 0, $chunkLength); <del> $decodedBody .= $chunk; <del> if ($chunkLength !== 0) { <del> $body = substr($body, $chunkLength + strlen("\r\n")); <del> } <del> } <del> <del> $entityHeader = false; <del> if (!empty($body)) { <del> $entityHeader = $this->_parseHeader($body); <del> } <del> return array('body' => $decodedBody, 'header' => $entityHeader); <del> } <del> <del>/** <del> * Parses an array based header. <del> * <del> * @param array $header Header as an indexed array (field => value) <del> * @return array Parsed header <del> */ <del> protected function _parseHeader($header) { <del> if (is_array($header)) { <del> return $header; <del> } elseif (!is_string($header)) { <del> return false; <del> } <del> <del> preg_match_all("/(.+):(.+)(?:(?<![\t ])\r\n|\$)/Uis", $header, $matches, PREG_SET_ORDER); <del> <del> $header = array(); <del> foreach ($matches as $match) { <del> list(, $field, $value) = $match; <del> <del> $value = trim($value); <del> $value = preg_replace("/[\t ]\r\n/", "\r\n", $value); <del> <del> $field = $this->_unescapeToken($field); <del> <del> if (!isset($header[$field])) { <del> $header[$field] = $value; <del> } else { <del> $header[$field] = array_merge((array)$header[$field], (array)$value); <del> } <del> } <del> return $header; <del> } <del> <del>/** <del> * Parses cookies in response headers. <del> * <del> * @param array $header Header array containing one ore more 'Set-Cookie' headers. <del> * @return mixed Either false on no cookies, or an array of cookies received. <del> */ <del> public function parseCookies($header) { <del> $cookieHeader = $this->getHeader('Set-Cookie', $header); <del> if (!$cookieHeader) { <del> return false; <del> } <del> <del> $cookies = array(); <del> foreach ((array)$cookieHeader as $cookie) { <del> if (strpos($cookie, '";"') !== false) { <del> $cookie = str_replace('";"', "{__cookie_replace__}", $cookie); <del> $parts = str_replace("{__cookie_replace__}", '";"', explode(';', $cookie)); <del> } else { <del> $parts = preg_split('/\;[ \t]*/', $cookie); <del> } <del> <del> list($name, $value) = explode('=', array_shift($parts), 2); <del> $cookies[$name] = compact('value'); <del> <del> foreach ($parts as $part) { <del> if (strpos($part, '=') !== false) { <del> list($key, $value) = explode('=', $part); <del> } else { <del> $key = $part; <del> $value = true; <del> } <del> <del> $key = strtolower($key); <del> if (!isset($cookies[$name][$key])) { <del> $cookies[$name][$key] = $value; <del> } <del> } <del> } <del> return $cookies; <del> } <del> <del>/** <del> * Unescapes a given $token according to RFC 2616 (HTTP 1.1 specs) <del> * <del> * @param string $token Token to unescape <del> * @param array $chars <del> * @return string Unescaped token <del> */ <del> protected function _unescapeToken($token, $chars = null) { <del> $regex = '/"([' . implode('', $this->_tokenEscapeChars(true, $chars)) . '])"/'; <del> $token = preg_replace($regex, '\\1', $token); <del> return $token; <del> } <del> <del>/** <del> * Gets escape chars according to RFC 2616 (HTTP 1.1 specs). <del> * <del> * @param boolean $hex true to get them as HEX values, false otherwise <del> * @param array $chars <del> * @return array Escape chars <del> */ <del> protected function _tokenEscapeChars($hex = true, $chars = null) { <del> if (!empty($chars)) { <del> $escape = $chars; <del> } else { <del> $escape = array('"', "(", ")", "<", ">", "@", ",", ";", ":", "\\", "/", "[", "]", "?", "=", "{", "}", " "); <del> for ($i = 0; $i <= 31; $i++) { <del> $escape[] = chr($i); <del> } <del> $escape[] = chr(127); <del> } <del> <del> if (!$hex) { <del> return $escape; <del> } <del> foreach ($escape as $key => $char) { <del> $escape[$key] = '\\x' . str_pad(dechex(ord($char)), 2, '0', STR_PAD_LEFT); <del> } <del> return $escape; <del> } <del> <del>/** <del> * ArrayAccess - Offset Exists <del> * <del> * @param string $offset <del> * @return boolean <del> */ <del> public function offsetExists($offset) { <del> return in_array($offset, array('raw', 'status', 'header', 'body', 'cookies')); <del> } <del> <del>/** <del> * ArrayAccess - Offset Get <del> * <del> * @param string $offset <del> * @return mixed <del> */ <del> public function offsetGet($offset) { <del> switch ($offset) { <del> case 'raw': <del> $firstLineLength = strpos($this->raw, "\r\n") + 2; <del> if ($this->raw[$firstLineLength] === "\r") { <del> $header = null; <del> } else { <del> $header = substr($this->raw, $firstLineLength, strpos($this->raw, "\r\n\r\n") - $firstLineLength) . "\r\n"; <del> } <del> return array( <del> 'status-line' => $this->httpVersion . ' ' . $this->code . ' ' . $this->reasonPhrase . "\r\n", <del> 'header' => $header, <del> 'body' => $this->body, <del> 'response' => $this->raw <del> ); <del> case 'status': <del> return array( <del> 'http-version' => $this->httpVersion, <del> 'code' => $this->code, <del> 'reason-phrase' => $this->reasonPhrase <del> ); <del> case 'header': <del> return $this->headers; <del> case 'body': <del> return $this->body; <del> case 'cookies': <del> return $this->cookies; <del> } <del> return null; <del> } <del> <del>/** <del> * ArrayAccess - Offset Set <del> * <del> * @param string $offset <del> * @param mixed $value <del> * @return void <del> */ <del> public function offsetSet($offset, $value) { <del> } <del> <del>/** <del> * ArrayAccess - Offset Unset <del> * <del> * @param string $offset <del> * @return void <del> */ <del> public function offsetUnset($offset) { <del> } <del> <del>/** <del> * Instance as string <del> * <del> * @return string <del> */ <del> public function __toString() { <del> return $this->body(); <del> } <del> <del>} <ide><path>lib/Cake/Test/TestCase/Network/Http/BasicAuthenticationTest.php <del><?php <del>/** <del> * BasicAuthenticationTest file <del> * <del> * PHP 5 <del> * <del> * CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html> <del> * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) <del> * <del> * Licensed under The MIT License <del> * Redistributions of files must retain the above copyright notice <del> * <del> * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) <del> * @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests <del> * @package Cake.Test.Case.Network.Http <del> * @since CakePHP(tm) v 2.0.0 <del> * @license MIT License (http://www.opensource.org/licenses/mit-license.php) <del> */ <del>namespace Cake\Test\TestCase\Network\Http; <del> <del>use Cake\Network\Http\BasicAuthentication; <del>use Cake\Network\Http\HttpSocket; <del>use Cake\TestSuite\TestCase; <del> <del>/** <del> * BasicMethodTest class <del> * <del> * @package Cake.Test.Case.Network.Http <del> */ <del>class BasicAuthenticationTest extends TestCase { <del> <del>/** <del> * testAuthentication method <del> * <del> * @return void <del> */ <del> public function testAuthentication() { <del> $http = new HttpSocket(); <del> $auth = array( <del> 'method' => 'Basic', <del> 'user' => 'mark', <del> 'pass' => 'secret' <del> ); <del> <del> BasicAuthentication::authentication($http, $auth); <del> $this->assertEquals('Basic bWFyazpzZWNyZXQ=', $http->request['header']['Authorization']); <del> } <del> <del>/** <del> * testProxyAuthentication method <del> * <del> * @return void <del> */ <del> public function testProxyAuthentication() { <del> $http = new HttpSocket(); <del> $proxy = array( <del> 'method' => 'Basic', <del> 'user' => 'mark', <del> 'pass' => 'secret' <del> ); <del> <del> BasicAuthentication::proxyAuthentication($http, $proxy); <del> $this->assertEquals('Basic bWFyazpzZWNyZXQ=', $http->request['header']['Proxy-Authorization']); <del> } <del> <del>} <ide><path>lib/Cake/Test/TestCase/Network/Http/DigestAuthenticationTest.php <del><?php <del>/** <del> * DigestAuthenticationTest file <del> * <del> * PHP 5 <del> * <del> * CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html> <del> * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) <del> * <del> * Licensed under The MIT License <del> * Redistributions of files must retain the above copyright notice <del> * <del> * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) <del> * @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests <del> * @package Cake.Test.Case.Network.Http <del> * @since CakePHP(tm) v 2.0.0 <del> * @license MIT License (http://www.opensource.org/licenses/mit-license.php) <del> */ <del>namespace Cake\Test\TestCase\Network\Http; <del> <del>use Cake\Network\Http\DigestAuthentication; <del>use Cake\Network\Http\HttpSocket; <del>use Cake\TestSuite\TestCase; <del> <del>class DigestHttpSocket extends HttpSocket { <del> <del>/** <del> * nextHeader attribute <del> * <del> * @var string <del> */ <del> public $nextHeader = ''; <del> <del>/** <del> * request method <del> * <del> * @param mixed $request <del> * @return void <del> */ <del> public function request($request = array()) { <del> if ($request === false) { <del> if (isset($this->response['header']['WWW-Authenticate'])) { <del> unset($this->response['header']['WWW-Authenticate']); <del> } <del> return; <del> } <del> $this->response['header']['WWW-Authenticate'] = $this->nextHeader; <del> } <del> <del>} <del> <del>/** <del> * DigestAuthenticationTest class <del> * <del> * @package Cake.Test.Case.Network.Http <del> */ <del>class DigestAuthenticationTest extends TestCase { <del> <del>/** <del> * Socket property <del> * <del> * @var mixed null <del> */ <del> public $HttpSocket = null; <del> <del>/** <del> * This function sets up a HttpSocket instance we are going to use for testing <del> * <del> * @return void <del> */ <del> public function setUp() { <del> $this->HttpSocket = new DigestHttpSocket(); <del> $this->HttpSocket->request['method'] = 'GET'; <del> $this->HttpSocket->request['uri']['path'] = '/'; <del> } <del> <del>/** <del> * We use this function to clean up after the test case was executed <del> * <del> * @return void <del> */ <del> public function tearDown() { <del> unset($this->HttpSocket); <del> } <del> <del>/** <del> * testBasic method <del> * <del> * @return void <del> */ <del> public function testBasic() { <del> $this->HttpSocket->nextHeader = 'Digest realm="The batcave",nonce="4cded326c6c51"'; <del> $this->assertFalse(isset($this->HttpSocket->request['header']['Authorization'])); <del> <del> $auth = array('user' => 'admin', 'pass' => '1234'); <del> DigestAuthentication::authentication($this->HttpSocket, $auth); <del> $this->assertTrue(isset($this->HttpSocket->request['header']['Authorization'])); <del> $this->assertEquals('The batcave', $auth['realm']); <del> $this->assertEquals('4cded326c6c51', $auth['nonce']); <del> } <del> <del>/** <del> * testQop method <del> * <del> * @return void <del> */ <del> public function testQop() { <del> $this->HttpSocket->nextHeader = 'Digest realm="The batcave",nonce="4cded326c6c51"'; <del> $auth = array('user' => 'admin', 'pass' => '1234'); <del> DigestAuthentication::authentication($this->HttpSocket, $auth); <del> $expected = 'Digest username="admin", realm="The batcave", nonce="4cded326c6c51", uri="/", response="da7e2a46b471d77f70a9bb3698c8902b"'; <del> $this->assertEquals($expected, $this->HttpSocket->request['header']['Authorization']); <del> $this->assertFalse(isset($auth['qop'])); <del> $this->assertFalse(isset($auth['nc'])); <del> <del> $this->HttpSocket->nextHeader = 'Digest realm="The batcave",nonce="4cded326c6c51",qop="auth"'; <del> $auth = array('user' => 'admin', 'pass' => '1234'); <del> DigestAuthentication::authentication($this->HttpSocket, $auth); <del> $expected = '@Digest username="admin", realm="The batcave", nonce="4cded326c6c51", uri="/", response="[a-z0-9]{32}", qop="auth", nc=00000001, cnonce="[a-z0-9]+"@'; <del> $this->assertRegExp($expected, $this->HttpSocket->request['header']['Authorization']); <del> $this->assertEquals('auth', $auth['qop']); <del> $this->assertEquals(2, $auth['nc']); <del> } <del> <del>/** <del> * testOpaque method <del> * <del> * @return void <del> */ <del> public function testOpaque() { <del> $this->HttpSocket->nextHeader = 'Digest realm="The batcave",nonce="4cded326c6c51"'; <del> $auth = array('user' => 'admin', 'pass' => '1234'); <del> DigestAuthentication::authentication($this->HttpSocket, $auth); <del> $this->assertFalse(strpos($this->HttpSocket->request['header']['Authorization'], 'opaque="d8ea7aa61a1693024c4cc3a516f49b3c"')); <del> <del> $this->HttpSocket->nextHeader = 'Digest realm="The batcave",nonce="4cded326c6c51",opaque="d8ea7aa61a1693024c4cc3a516f49b3c"'; <del> $auth = array('user' => 'admin', 'pass' => '1234'); <del> DigestAuthentication::authentication($this->HttpSocket, $auth); <del> $this->assertTrue(strpos($this->HttpSocket->request['header']['Authorization'], 'opaque="d8ea7aa61a1693024c4cc3a516f49b3c"') > 0); <del> } <del> <del>/** <del> * testMultipleRequest method <del> * <del> * @return void <del> */ <del> public function testMultipleRequest() { <del> $this->HttpSocket->nextHeader = 'Digest realm="The batcave",nonce="4cded326c6c51",qop="auth"'; <del> $auth = array('user' => 'admin', 'pass' => '1234'); <del> DigestAuthentication::authentication($this->HttpSocket, $auth); <del> $this->assertTrue(strpos($this->HttpSocket->request['header']['Authorization'], 'nc=00000001') > 0); <del> $this->assertEquals(2, $auth['nc']); <del> <del> DigestAuthentication::authentication($this->HttpSocket, $auth); <del> $this->assertTrue(strpos($this->HttpSocket->request['header']['Authorization'], 'nc=00000002') > 0); <del> $this->assertEquals(3, $auth['nc']); <del> $responsePos = strpos($this->HttpSocket->request['header']['Authorization'], 'response='); <del> $response = substr($this->HttpSocket->request['header']['Authorization'], $responsePos + 10, 32); <del> <del> $this->HttpSocket->nextHeader = ''; <del> DigestAuthentication::authentication($this->HttpSocket, $auth); <del> $this->assertTrue(strpos($this->HttpSocket->request['header']['Authorization'], 'nc=00000003') > 0); <del> $this->assertEquals(4, $auth['nc']); <del> $responsePos = strpos($this->HttpSocket->request['header']['Authorization'], 'response='); <del> $responseB = substr($this->HttpSocket->request['header']['Authorization'], $responsePos + 10, 32); <del> $this->assertNotEquals($response, $responseB); <del> } <del> <del>/** <del> * testPathChanged method <del> * <del> * @return void <del> */ <del> public function testPathChanged() { <del> $this->HttpSocket->nextHeader = 'Digest realm="The batcave",nonce="4cded326c6c51"'; <del> $this->HttpSocket->request['uri']['path'] = '/admin'; <del> $auth = array('user' => 'admin', 'pass' => '1234'); <del> DigestAuthentication::authentication($this->HttpSocket, $auth); <del> $responsePos = strpos($this->HttpSocket->request['header']['Authorization'], 'response='); <del> $response = substr($this->HttpSocket->request['header']['Authorization'], $responsePos + 10, 32); <del> $this->assertNotEquals('da7e2a46b471d77f70a9bb3698c8902b', $response); <del> } <del> <del>/** <del> * testNoDigestResponse method <del> * <del> * @return void <del> */ <del> public function testNoDigestResponse() { <del> $this->HttpSocket->nextHeader = false; <del> $this->HttpSocket->request['uri']['path'] = '/admin'; <del> $auth = array('user' => 'admin', 'pass' => '1234'); <del> DigestAuthentication::authentication($this->HttpSocket, $auth); <del> $this->assertFalse(isset($this->HttpSocket->request['header']['Authorization'])); <del> } <del> <del>} <ide><path>lib/Cake/Test/TestCase/Network/Http/HttpResponseTest.php <del><?php <del>/** <del> * HttpResponseTest file <del> * <del> * PHP 5 <del> * <del> * CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html> <del> * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) <del> * <del> * Licensed under The MIT License <del> * Redistributions of files must retain the above copyright notice <del> * <del> * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) <del> * @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests <del> * @package Cake.Test.Case.Network.Http <del> * @since CakePHP(tm) v 1.2.0.4206 <del> * @license MIT License (http://www.opensource.org/licenses/mit-license.php) <del> */ <del>namespace Cake\Test\TestCase\Network\Http; <del> <del>use Cake\Network\Http\HttpResponse; <del>use Cake\Network\Http\HttpSocket; <del>use Cake\TestSuite\TestCase; <del> <del>/** <del> * TestHttpResponse class <del> * <del> * @package Cake.Test.Case.Network.Http <del> */ <del>class TestHttpResponse extends HttpResponse { <del> <del>/** <del> * Convenience method for testing protected method <del> * <del> * @param array $header Header as an indexed array (field => value) <del> * @return array Parsed header <del> */ <del> public function parseHeader($header) { <del> return parent::_parseHeader($header); <del> } <del> <del>/** <del> * Convenience method for testing protected method <del> * <del> * @param string $body A string containing the body to decode <del> * @param boolean|string $encoding Can be false in case no encoding is being used, or a string representing the encoding <del> * @return mixed Array or false <del> */ <del> public function decodeBody($body, $encoding = 'chunked') { <del> return parent::_decodeBody($body, $encoding); <del> } <del> <del>/** <del> * Convenience method for testing protected method <del> * <del> * @param string $body A string containing the chunked body to decode <del> * @return mixed Array or false <del> */ <del> public function decodeChunkedBody($body) { <del> return parent::_decodeChunkedBody($body); <del> } <del> <del>/** <del> * Convenience method for testing protected method <del> * <del> * @param string $token Token to unescape <del> * @return string Unescaped token <del> */ <del> public function unescapeToken($token, $chars = null) { <del> return parent::_unescapeToken($token, $chars); <del> } <del> <del>/** <del> * Convenience method for testing protected method <del> * <del> * @param boolean $hex true to get them as HEX values, false otherwise <del> * @return array Escape chars <del> */ <del> public function tokenEscapeChars($hex = true, $chars = null) { <del> return parent::_tokenEscapeChars($hex, $chars); <del> } <del> <del>} <del> <del>/** <del> * HttpResponseTest class <del> * <del> * @package Cake.Test.Case.Network.Http <del> */ <del>class HttpResponseTest extends TestCase { <del> <del>/** <del> * This function sets up a HttpResponse <del> * <del> * @return void <del> */ <del> public function setUp() { <del> $this->HttpResponse = new TestHttpResponse(); <del> } <del> <del>/** <del> * testBody <del> * <del> * @return void <del> */ <del> public function testBody() { <del> $this->HttpResponse->body = 'testing'; <del> $this->assertEquals('testing', $this->HttpResponse->body()); <del> <del> $this->HttpResponse->body = null; <del> $this->assertSame($this->HttpResponse->body(), ''); <del> } <del> <del>/** <del> * testToString <del> * <del> * @return void <del> */ <del> public function testToString() { <del> $this->HttpResponse->body = 'other test'; <del> $this->assertEquals('other test', $this->HttpResponse->body()); <del> $this->assertEquals('other test', (string)$this->HttpResponse); <del> $this->assertTrue(strpos($this->HttpResponse, 'test') > 0); <del> <del> $this->HttpResponse->body = null; <del> $this->assertEquals('', (string)$this->HttpResponse); <del> } <del> <del>/** <del> * testGetHeader <del> * <del> * @return void <del> */ <del> public function testGetHeader() { <del> $this->HttpResponse->headers = array( <del> 'foo' => 'Bar', <del> 'Some' => 'ok', <del> 'HeAdEr' => 'value', <del> 'content-Type' => 'text/plain' <del> ); <del> <del> $this->assertEquals('Bar', $this->HttpResponse->getHeader('foo')); <del> $this->assertEquals('Bar', $this->HttpResponse->getHeader('Foo')); <del> $this->assertEquals('Bar', $this->HttpResponse->getHeader('FOO')); <del> $this->assertEquals('value', $this->HttpResponse->getHeader('header')); <del> $this->assertEquals('text/plain', $this->HttpResponse->getHeader('Content-Type')); <del> $this->assertSame($this->HttpResponse->getHeader(0), null); <del> <del> $this->assertEquals('Bar', $this->HttpResponse->getHeader('foo', false)); <del> $this->assertEquals('not from class', $this->HttpResponse->getHeader('foo', array('foo' => 'not from class'))); <del> } <del> <del>/** <del> * testIsOk <del> * <del> * @return void <del> */ <del> public function testIsOk() { <del> $this->HttpResponse->code = 0; <del> $this->assertFalse($this->HttpResponse->isOk()); <del> $this->HttpResponse->code = -1; <del> $this->assertFalse($this->HttpResponse->isOk()); <del> $this->HttpResponse->code = 201; <del> $this->assertFalse($this->HttpResponse->isOk()); <del> $this->HttpResponse->code = 'what?'; <del> $this->assertFalse($this->HttpResponse->isOk()); <del> $this->HttpResponse->code = 200; <del> $this->assertTrue($this->HttpResponse->isOk()); <del> } <del> <del>/** <del> * testIsRedirect <del> * <del> * @return void <del> */ <del> public function testIsRedirect() { <del> $this->HttpResponse->code = 0; <del> $this->assertFalse($this->HttpResponse->isRedirect()); <del> $this->HttpResponse->code = -1; <del> $this->assertFalse($this->HttpResponse->isRedirect()); <del> $this->HttpResponse->code = 201; <del> $this->assertFalse($this->HttpResponse->isRedirect()); <del> $this->HttpResponse->code = 'what?'; <del> $this->assertFalse($this->HttpResponse->isRedirect()); <del> $this->HttpResponse->code = 301; <del> $this->assertFalse($this->HttpResponse->isRedirect()); <del> $this->HttpResponse->code = 302; <del> $this->assertFalse($this->HttpResponse->isRedirect()); <del> $this->HttpResponse->code = 303; <del> $this->assertFalse($this->HttpResponse->isRedirect()); <del> $this->HttpResponse->code = 307; <del> $this->assertFalse($this->HttpResponse->isRedirect()); <del> $this->HttpResponse->code = 301; <del> $this->HttpResponse->headers['Location'] = 'http://somewhere/'; <del> $this->assertTrue($this->HttpResponse->isRedirect()); <del> $this->HttpResponse->code = 302; <del> $this->HttpResponse->headers['Location'] = 'http://somewhere/'; <del> $this->assertTrue($this->HttpResponse->isRedirect()); <del> $this->HttpResponse->code = 303; <del> $this->HttpResponse->headers['Location'] = 'http://somewhere/'; <del> $this->assertTrue($this->HttpResponse->isRedirect()); <del> $this->HttpResponse->code = 307; <del> $this->HttpResponse->headers['Location'] = 'http://somewhere/'; <del> $this->assertTrue($this->HttpResponse->isRedirect()); <del> } <del> <del>/** <del> * Test that HttpSocket::parseHeader can take apart a given (and valid) $header string and turn it into an array. <del> * <del> * @return void <del> */ <del> public function testParseHeader() { <del> $r = $this->HttpResponse->parseHeader(array('foo' => 'Bar', 'fOO-bAr' => 'quux')); <del> $this->assertEquals(array('foo' => 'Bar', 'fOO-bAr' => 'quux'), $r); <del> <del> $r = $this->HttpResponse->parseHeader(true); <del> $this->assertEquals(false, $r); <del> <del> $header = "Host: cakephp.org\t\r\n"; <del> $r = $this->HttpResponse->parseHeader($header); <del> $expected = array( <del> 'Host' => 'cakephp.org' <del> ); <del> $this->assertEquals($expected, $r); <del> <del> $header = "Date:Sat, 07 Apr 2007 10:10:25 GMT\r\nX-Powered-By: PHP/5.1.2\r\n"; <del> $r = $this->HttpResponse->parseHeader($header); <del> $expected = array( <del> 'Date' => 'Sat, 07 Apr 2007 10:10:25 GMT', <del> 'X-Powered-By' => 'PHP/5.1.2' <del> ); <del> $this->assertEquals($expected, $r); <del> <del> $header = "people: Jim,John\r\nfoo-LAND: Bar\r\ncAKe-PHP: rocks\r\n"; <del> $r = $this->HttpResponse->parseHeader($header); <del> $expected = array( <del> 'people' => 'Jim,John', <del> 'foo-LAND' => 'Bar', <del> 'cAKe-PHP' => 'rocks' <del> ); <del> $this->assertEquals($expected, $r); <del> <del> $header = "People: Jim,John,Tim\r\nPeople: Lisa,Tina,Chelsea\r\n"; <del> $r = $this->HttpResponse->parseHeader($header); <del> $expected = array( <del> 'People' => array('Jim,John,Tim', 'Lisa,Tina,Chelsea') <del> ); <del> $this->assertEquals($expected, $r); <del> <del> $header = "Multi-Line: I am a \r\nmulti line\t\r\nfield value.\r\nSingle-Line: I am not\r\n"; <del> $r = $this->HttpResponse->parseHeader($header); <del> $expected = array( <del> 'Multi-Line' => "I am a\r\nmulti line\r\nfield value.", <del> 'Single-Line' => 'I am not' <del> ); <del> $this->assertEquals($expected, $r); <del> <del> $header = "Esc\"@\"ped: value\r\n"; <del> $r = $this->HttpResponse->parseHeader($header); <del> $expected = array( <del> 'Esc@ped' => 'value' <del> ); <del> $this->assertEquals($expected, $r); <del> } <del> <del>/** <del> * testParseResponse method <del> * <del> * @return void <del> */ <del> public function testParseResponse() { <del> $tests = array( <del> 'simple-request' => array( <del> 'response' => array( <del> 'status-line' => "HTTP/1.x 200 OK\r\n", <del> 'header' => "Date: Mon, 16 Apr 2007 04:14:16 GMT\r\nServer: CakeHttp Server\r\n", <del> 'body' => "<h1>Hello World</h1>\r\n<p>It's good to be html</p>" <del> ), <del> 'expectations' => array( <del> 'httpVersion' => 'HTTP/1.x', <del> 'code' => 200, <del> 'reasonPhrase' => 'OK', <del> 'headers' => array('Date' => 'Mon, 16 Apr 2007 04:14:16 GMT', 'Server' => 'CakeHttp Server'), <del> 'body' => "<h1>Hello World</h1>\r\n<p>It's good to be html</p>" <del> ) <del> ), <del> 'no-header' => array( <del> 'response' => array( <del> 'status-line' => "HTTP/1.x 404 OK\r\n", <del> 'header' => null <del> ), <del> 'expectations' => array( <del> 'code' => 404, <del> 'headers' => array() <del> ) <del> ) <del> ); <del> <del> $testResponse = array(); <del> $expectations = array(); <del> <del> foreach ($tests as $name => $test) { <del> $testResponse = array_merge($testResponse, $test['response']); <del> $testResponse['response'] = $testResponse['status-line'] . $testResponse['header'] . "\r\n" . $testResponse['body']; <del> $this->HttpResponse->parseResponse($testResponse['response']); <del> $expectations = array_merge($expectations, $test['expectations']); <del> <del> foreach ($expectations as $property => $expectedVal) { <del> $this->assertEquals($expectedVal, $this->HttpResponse->{$property}, 'Test "' . $name . '": response.' . $property . ' - %s'); <del> } <del> <del> foreach (array('status-line', 'header', 'body', 'response') as $field) { <del> $this->assertEquals($this->HttpResponse['raw'][$field], $testResponse[$field], 'Test response.raw.' . $field . ': %s'); <del> } <del> } <del> } <del> <del>/** <del> * data provider function for testInvalidParseResponseData <del> * <del> * @return array <del> */ <del> public static function invalidParseResponseDataProvider() { <del> return array( <del> array(array('foo' => 'bar')), <del> array(true), <del> array("HTTP Foo\r\nBar: La"), <del> array('HTTP/1.1 TEST ERROR') <del> ); <del> } <del> <del>/** <del> * testInvalidParseResponseData <del> * <del> * @dataProvider invalidParseResponseDataProvider <del> * @expectedException Cake\Error\SocketException <del> * return void <del> */ <del> public function testInvalidParseResponseData($value) { <del> $this->HttpResponse->parseResponse($value); <del> } <del> <del>/** <del> * testDecodeBody method <del> * <del> * @return void <del> */ <del> public function testDecodeBody() { <del> $r = $this->HttpResponse->decodeBody(true); <del> $this->assertEquals(false, $r); <del> <del> $r = $this->HttpResponse->decodeBody('Foobar', false); <del> $this->assertEquals(array('body' => 'Foobar', 'header' => false), $r); <del> <del> $encoding = 'chunked'; <del> $sample = array( <del> 'encoded' => "19\r\nThis is a chunked message\r\n0\r\n", <del> 'decoded' => array('body' => "This is a chunked message", 'header' => false) <del> ); <del> <del> $r = $this->HttpResponse->decodeBody($sample['encoded'], $encoding); <del> $this->assertEquals($r, $sample['decoded']); <del> <del> $encoding = 'chunked'; <del> $sample = array( <del> 'encoded' => "19\nThis is a chunked message\r\n0\n", <del> 'decoded' => array('body' => "This is a chunked message", 'header' => false) <del> ); <del> <del> $r = $this->HttpResponse->decodeBody($sample['encoded'], $encoding); <del> $this->assertEquals($r, $sample['decoded'], 'Inconsistent line terminators should be tolerated.'); <del> } <del> <del>/** <del> * testDecodeFooCoded <del> * <del> * @return void <del> */ <del> public function testDecodeFooCoded() { <del> $r = $this->HttpResponse->decodeBody(true); <del> $this->assertEquals(false, $r); <del> <del> $r = $this->HttpResponse->decodeBody('Foobar', false); <del> $this->assertEquals(array('body' => 'Foobar', 'header' => false), $r); <del> <del> $encoding = 'foo-bar'; <del> $sample = array( <del> 'encoded' => '!Foobar!', <del> 'decoded' => array('body' => '!Foobar!', 'header' => false), <del> ); <del> <del> $r = $this->HttpResponse->decodeBody($sample['encoded'], $encoding); <del> $this->assertEquals($r, $sample['decoded']); <del> } <del> <del>/** <del> * testDecodeChunkedBody method <del> * <del> * @return void <del> */ <del> public function testDecodeChunkedBody() { <del> $r = $this->HttpResponse->decodeChunkedBody(true); <del> $this->assertEquals(false, $r); <del> <del> $encoded = "19\r\nThis is a chunked message\r\n0\r\n"; <del> $decoded = "This is a chunked message"; <del> $r = $this->HttpResponse->decodeChunkedBody($encoded); <del> $this->assertEquals($r['body'], $decoded); <del> $this->assertEquals(false, $r['header']); <del> <del> $encoded = "19 \r\nThis is a chunked message\r\n0\r\n"; <del> $r = $this->HttpResponse->decodeChunkedBody($encoded); <del> $this->assertEquals($r['body'], $decoded); <del> <del> $encoded = "19\r\nThis is a chunked message\r\nE\r\n\nThat is cool\n\r\n0\r\n"; <del> $decoded = "This is a chunked message\nThat is cool\n"; <del> $r = $this->HttpResponse->decodeChunkedBody($encoded); <del> $this->assertEquals($r['body'], $decoded); <del> $this->assertEquals(false, $r['header']); <del> <del> $encoded = "19\r\nThis is a chunked message\r\nE;foo-chunk=5\r\n\nThat is cool\n\r\n0\r\n"; <del> $r = $this->HttpResponse->decodeChunkedBody($encoded); <del> $this->assertEquals($r['body'], $decoded); <del> $this->assertEquals(false, $r['header']); <del> <del> $encoded = "19\r\nThis is a chunked message\r\nE\r\n\nThat is cool\n\r\n0\r\nfoo-header: bar\r\ncake: PHP\r\n\r\n"; <del> $r = $this->HttpResponse->decodeChunkedBody($encoded); <del> $this->assertEquals($r['body'], $decoded); <del> $this->assertEquals(array('foo-header' => 'bar', 'cake' => 'PHP'), $r['header']); <del> } <del> <del>/** <del> * testDecodeChunkedBodyError method <del> * <del> * @expectedException Cake\Error\SocketException <del> * @return void <del> */ <del> public function testDecodeChunkedBodyError() { <del> $encoded = "19\r\nThis is a chunked message\r\nE\r\n\nThat is cool\n\r\n"; <del> $r = $this->HttpResponse->decodeChunkedBody($encoded); <del> } <del> <del>/** <del> * testParseCookies method <del> * <del> * @return void <del> */ <del> public function testParseCookies() { <del> $header = array( <del> 'Set-Cookie' => array( <del> 'foo=bar', <del> 'people=jim,jack,johnny";";Path=/accounts', <del> 'google=not=nice' <del> ), <del> 'Transfer-Encoding' => 'chunked', <del> 'Date' => 'Sun, 18 Nov 2007 18:57:42 GMT', <del> ); <del> $cookies = $this->HttpResponse->parseCookies($header); <del> $expected = array( <del> 'foo' => array( <del> 'value' => 'bar' <del> ), <del> 'people' => array( <del> 'value' => 'jim,jack,johnny";"', <del> 'path' => '/accounts', <del> ), <del> 'google' => array( <del> 'value' => 'not=nice', <del> ) <del> ); <del> $this->assertEquals($expected, $cookies); <del> <del> $header['Set-Cookie'][] = 'cakephp=great; Secure'; <del> $expected['cakephp'] = array('value' => 'great', 'secure' => true); <del> $cookies = $this->HttpResponse->parseCookies($header); <del> $this->assertEquals($expected, $cookies); <del> <del> $header['Set-Cookie'] = 'foo=bar'; <del> unset($expected['people'], $expected['cakephp'], $expected['google']); <del> $cookies = $this->HttpResponse->parseCookies($header); <del> $this->assertEquals($expected, $cookies); <del> } <del> <del>/** <del> * Test that escaped token strings are properly unescaped by HttpSocket::unescapeToken <del> * <del> * @return void <del> */ <del> public function testUnescapeToken() { <del> $this->assertEquals('Foo', $this->HttpResponse->unescapeToken('Foo')); <del> <del> $escape = $this->HttpResponse->tokenEscapeChars(false); <del> foreach ($escape as $char) { <del> $token = 'My-special-"' . $char . '"-Token'; <del> $unescapedToken = $this->HttpResponse->unescapeToken($token); <del> $expectedToken = 'My-special-' . $char . '-Token'; <del> <del> $this->assertEquals($expectedToken, $unescapedToken, 'Test token unescaping for ASCII ' . ord($char)); <del> } <del> <del> $token = 'Extreme-":"Token-" "-""""@"-test'; <del> $escapedToken = $this->HttpResponse->unescapeToken($token); <del> $expectedToken = 'Extreme-:Token- -"@-test'; <del> $this->assertEquals($expectedToken, $escapedToken); <del> } <del> <del>/** <del> * testArrayAccess <del> * <del> * @return void <del> */ <del> public function testArrayAccess() { <del> $this->HttpResponse->httpVersion = 'HTTP/1.1'; <del> $this->HttpResponse->code = 200; <del> $this->HttpResponse->reasonPhrase = 'OK'; <del> $this->HttpResponse->headers = array( <del> 'Server' => 'CakePHP', <del> 'ContEnt-Type' => 'text/plain' <del> ); <del> $this->HttpResponse->cookies = array( <del> 'foo' => array('value' => 'bar'), <del> 'bar' => array('value' => 'foo') <del> ); <del> $this->HttpResponse->body = 'This is a test!'; <del> $this->HttpResponse->raw = "HTTP/1.1 200 OK\r\nServer: CakePHP\r\nContEnt-Type: text/plain\r\n\r\nThis is a test!"; <del> $expectedOne = "HTTP/1.1 200 OK\r\n"; <del> $this->assertEquals($expectedOne, $this->HttpResponse['raw']['status-line']); <del> $expectedTwo = "Server: CakePHP\r\nContEnt-Type: text/plain\r\n"; <del> $this->assertEquals($expectedTwo, $this->HttpResponse['raw']['header']); <del> $expectedThree = 'This is a test!'; <del> $this->assertEquals($expectedThree, $this->HttpResponse['raw']['body']); <del> $expected = $expectedOne . $expectedTwo . "\r\n" . $expectedThree; <del> $this->assertEquals($expected, $this->HttpResponse['raw']['response']); <del> <del> $expected = 'HTTP/1.1'; <del> $this->assertEquals($expected, $this->HttpResponse['status']['http-version']); <del> $expected = 200; <del> $this->assertEquals($expected, $this->HttpResponse['status']['code']); <del> $expected = 'OK'; <del> $this->assertEquals($expected, $this->HttpResponse['status']['reason-phrase']); <del> <del> $expected = array( <del> 'Server' => 'CakePHP', <del> 'ContEnt-Type' => 'text/plain' <del> ); <del> $this->assertEquals($expected, $this->HttpResponse['header']); <del> <del> $expected = 'This is a test!'; <del> $this->assertEquals($expected, $this->HttpResponse['body']); <del> <del> $expected = array( <del> 'foo' => array('value' => 'bar'), <del> 'bar' => array('value' => 'foo') <del> ); <del> $this->assertEquals($expected, $this->HttpResponse['cookies']); <del> <del> $this->HttpResponse->raw = "HTTP/1.1 200 OK\r\n\r\nThis is a test!"; <del> $this->assertSame($this->HttpResponse['raw']['header'], null); <del> } <del> <del>} <ide><path>lib/Cake/Test/TestCase/Network/Http/HttpSocketTest.php <del><?php <del>/** <del> * CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html> <del> * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) <del> * <del> * Licensed under The MIT License <del> * Redistributions of files must retain the above copyright notice <del> * <del> * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) <del> * @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests <del> * @since CakePHP(tm) v 1.2.0.4206 <del> * @license MIT License (http://www.opensource.org/licenses/mit-license.php) <del> */ <del>namespace Cake\Test\TestCase\Network\Http; <del> <del>use Cake\Network\Http\HttpResponse; <del>use Cake\Network\Http\HttpSocket; <del>use Cake\TestSuite\TestCase; <del>use Cake\Utility\Hash; <del> <del>/** <del> * TestAuthentication class <del> * <del> * @package Cake.Test.Case.Network.Http <del> */ <del>class TestAuthentication { <del> <del>/** <del> * authentication method <del> * <del> * @param HttpSocket $http <del> * @param array $authInfo <del> * @return void <del> */ <del> public static function authentication(HttpSocket $http, &$authInfo) { <del> $http->request['header']['Authorization'] = 'Test ' . $authInfo['user'] . '.' . $authInfo['pass']; <del> } <del> <del>/** <del> * proxyAuthentication method <del> * <del> * @param HttpSocket $http <del> * @param array $proxyInfo <del> * @return void <del> */ <del> public static function proxyAuthentication(HttpSocket $http, &$proxyInfo) { <del> $http->request['header']['Proxy-Authorization'] = 'Test ' . $proxyInfo['user'] . '.' . $proxyInfo['pass']; <del> } <del> <del>} <del> <del>/** <del> * CustomResponse <del> * <del> */ <del>class CustomResponse { <del> <del>/** <del> * First 10 chars <del> * <del> * @var string <del> */ <del> public $first10; <del> <del>/** <del> * Constructor <del> * <del> */ <del> public function __construct($message) { <del> $this->first10 = substr($message, 0, 10); <del> } <del> <del>} <del> <del>/** <del> * TestHttpSocket <del> * <del> */ <del>class TestHttpSocket extends HttpSocket { <del> <del>/** <del> * Convenience method for testing protected method <del> * <del> * @param string|array $uri URI (see {@link _parseUri()}) <del> * @return array Current configuration settings <del> */ <del> public function configUri($uri = null) { <del> return parent::_configUri($uri); <del> } <del> <del>/** <del> * Convenience method for testing protected method <del> * <del> * @param string|array $uri URI to parse <del> * @param boolean|array $base If true use default URI config, otherwise indexed array to set 'scheme', 'host', 'port', etc. <del> * @return array Parsed URI <del> */ <del> public function parseUri($uri = null, $base = array()) { <del> return parent::_parseUri($uri, $base); <del> } <del> <del>/** <del> * Convenience method for testing protected method <del> * <del> * @param array $uri A $uri array, or uses $this->config if left empty <del> * @param string $uriTemplate The Uri template/format to use <del> * @return string A fully qualified URL formatted according to $uriTemplate <del> */ <del> public function buildUri($uri = array(), $uriTemplate = '%scheme://%user:%pass@%host:%port/%path?%query#%fragment') { <del> return parent::_buildUri($uri, $uriTemplate); <del> } <del> <del>/** <del> * Convenience method for testing protected method <del> * <del> * @param array $header Header to build <del> * @return string Header built from array <del> */ <del> public function buildHeader($header, $mode = 'standard') { <del> return parent::_buildHeader($header, $mode); <del> } <del> <del>/** <del> * Convenience method for testing protected method <del> * <del> * @param string|array $query A query string to parse into an array or an array to return directly "as is" <del> * @return array The $query parsed into a possibly multi-level array. If an empty $query is given, an empty array is returned. <del> */ <del> public function parseQuery($query) { <del> return parent::_parseQuery($query); <del> } <del> <del>/** <del> * Convenience method for testing protected method <del> * <del> * @param array $request Needs to contain a 'uri' key. Should also contain a 'method' key, otherwise defaults to GET. <del> * @param string $versionToken The version token to use, defaults to HTTP/1.1 <del> * @return string Request line <del> */ <del> public function buildRequestLine($request = array(), $versionToken = 'HTTP/1.1') { <del> return parent::_buildRequestLine($request, $versionToken); <del> } <del> <del>/** <del> * Convenience method for testing protected method <del> * <del> * @param boolean $hex true to get them as HEX values, false otherwise <del> * @return array Escape chars <del> */ <del> public function tokenEscapeChars($hex = true, $chars = null) { <del> return parent::_tokenEscapeChars($hex, $chars); <del> } <del> <del>/** <del> * Convenience method for testing protected method <del> * <del> * @param string $token Token to escape <del> * @return string Escaped token <del> */ <del> public function escapeToken($token, $chars = null) { <del> return parent::_escapeToken($token, $chars); <del> } <del> <del>} <del> <del>/** <del> * HttpSocketTest class <del> * <del> * @package Cake.Test.Case.Network.Http <del> */ <del>class HttpSocketTest extends TestCase { <del> <del>/** <del> * Socket property <del> * <del> * @var mixed null <del> */ <del> public $Socket = null; <del> <del>/** <del> * RequestSocket property <del> * <del> * @var mixed null <del> */ <del> public $RequestSocket = null; <del> <del>/** <del> * This function sets up a TestHttpSocket instance we are going to use for testing <del> * <del> * @return void <del> */ <del> public function setUp() { <del> if (!class_exists('MockHttpSocket')) { <del> $this->getMock(__NAMESPACE__ . '\TestHttpSocket', array('read', 'write', 'connect'), array(), 'MockHttpSocket'); <del> $this->getMock(__NAMESPACE__ . '\TestHttpSocket', array('read', 'write', 'connect', 'request'), array(), 'MockHttpSocketRequests'); <del> } <del> <del> $this->Socket = new \MockHttpSocket(); <del> $this->RequestSocket = new \MockHttpSocketRequests(); <del> } <del> <del>/** <del> * We use this function to clean up after the test case was executed <del> * <del> * @return void <del> */ <del> public function tearDown() { <del> unset($this->Socket, $this->RequestSocket); <del> } <del> <del>/** <del> * Test that HttpSocket::__construct does what one would expect it to do <del> * <del> * @return void <del> */ <del> public function testConstruct() { <del> $this->Socket->reset(); <del> $baseConfig = $this->Socket->config; <del> $this->Socket->expects($this->never())->method('connect'); <del> $this->Socket->__construct(array('host' => 'foo-bar')); <del> $baseConfig['host'] = 'foo-bar'; <del> $baseConfig['protocol'] = getprotobyname($baseConfig['protocol']); <del> $this->assertEquals($this->Socket->config, $baseConfig); <del> <del> $this->Socket->reset(); <del> $baseConfig = $this->Socket->config; <del> $this->Socket->__construct('http://www.cakephp.org:23/'); <del> $baseConfig['host'] = $baseConfig['request']['uri']['host'] = 'www.cakephp.org'; <del> $baseConfig['port'] = $baseConfig['request']['uri']['port'] = 23; <del> $baseConfig['request']['uri']['scheme'] = 'http'; <del> $baseConfig['protocol'] = getprotobyname($baseConfig['protocol']); <del> $this->assertEquals($this->Socket->config, $baseConfig); <del> <del> $this->Socket->reset(); <del> $this->Socket->__construct(array('request' => array('uri' => 'http://www.cakephp.org:23/'))); <del> $this->assertEquals($this->Socket->config, $baseConfig); <del> } <del> <del>/** <del> * Test that HttpSocket::configUri works properly with different types of arguments <del> * <del> * @return void <del> */ <del> public function testConfigUri() { <del> $this->Socket->reset(); <del> $r = $this->Socket->configUri('https://bob:secret@www.cakephp.org:23/?query=foo'); <del> $expected = array( <del> 'persistent' => false, <del> 'host' => 'www.cakephp.org', <del> 'protocol' => 'tcp', <del> 'port' => 23, <del> 'timeout' => 30, <del> 'ssl_verify_peer' => true, <del> 'ssl_verify_depth' => 5, <del> 'ssl_verify_host' => true, <del> 'request' => array( <del> 'uri' => array( <del> 'scheme' => 'https', <del> 'host' => 'www.cakephp.org', <del> 'port' => 23 <del> ), <del> 'redirect' => false, <del> 'cookies' => array(), <del> ) <del> ); <del> $this->assertEquals($expected, $this->Socket->config); <del> $this->assertTrue($r); <del> $r = $this->Socket->configUri(array('host' => 'www.foo-bar.org')); <del> $expected['host'] = 'www.foo-bar.org'; <del> $expected['request']['uri']['host'] = 'www.foo-bar.org'; <del> $this->assertEquals($expected, $this->Socket->config); <del> $this->assertTrue($r); <del> <del> $r = $this->Socket->configUri('http://www.foo.com'); <del> $expected = array( <del> 'persistent' => false, <del> 'host' => 'www.foo.com', <del> 'protocol' => 'tcp', <del> 'port' => 80, <del> 'timeout' => 30, <del> 'ssl_verify_peer' => true, <del> 'ssl_verify_depth' => 5, <del> 'ssl_verify_host' => true, <del> 'request' => array( <del> 'uri' => array( <del> 'scheme' => 'http', <del> 'host' => 'www.foo.com', <del> 'port' => 80 <del> ), <del> 'redirect' => false, <del> 'cookies' => array(), <del> ) <del> ); <del> $this->assertEquals($expected, $this->Socket->config); <del> $this->assertTrue($r); <del> <del> $r = $this->Socket->configUri('/this-is-broken'); <del> $this->assertEquals($expected, $this->Socket->config); <del> $this->assertFalse($r); <del> <del> $r = $this->Socket->configUri(false); <del> $this->assertEquals($expected, $this->Socket->config); <del> $this->assertFalse($r); <del> } <del> <del>/** <del> * Tests that HttpSocket::request (the heart of the HttpSocket) is working properly. <del> * <del> * @return void <del> */ <del> public function testRequest() { <del> $this->Socket->reset(); <del> <del> $response = $this->Socket->request(true); <del> $this->assertFalse($response); <del> <del> $context = array( <del> 'ssl' => array( <del> 'verify_peer' => true, <del> 'verify_depth' => 5, <del> 'CN_match' => 'www.cakephp.org', <del> 'cafile' => CAKE . 'Config' . DS . 'cacert.pem' <del> ) <del> ); <del> <del> $tests = array( <del> array( <del> 'request' => 'http://www.cakephp.org/?foo=bar', <del> 'expectation' => array( <del> 'config' => array( <del> 'persistent' => false, <del> 'host' => 'www.cakephp.org', <del> 'protocol' => 'tcp', <del> 'port' => 80, <del> 'timeout' => 30, <del> 'context' => $context, <del> 'request' => array( <del> 'uri' => array( <del> 'scheme' => 'http', <del> 'host' => 'www.cakephp.org', <del> 'port' => 80 <del> ), <del> 'redirect' => false, <del> 'cookies' => array() <del> ) <del> ), <del> 'request' => array( <del> 'method' => 'GET', <del> 'uri' => array( <del> 'scheme' => 'http', <del> 'host' => 'www.cakephp.org', <del> 'port' => 80, <del> 'user' => null, <del> 'pass' => null, <del> 'path' => '/', <del> 'query' => array('foo' => 'bar'), <del> 'fragment' => null <del> ), <del> 'version' => '1.1', <del> 'body' => '', <del> 'line' => "GET /?foo=bar HTTP/1.1\r\n", <del> 'header' => "Host: www.cakephp.org\r\nConnection: close\r\nUser-Agent: CakePHP\r\n", <del> 'raw' => "", <del> 'redirect' => false, <del> 'cookies' => array(), <del> 'proxy' => array(), <del> 'auth' => array() <del> ) <del> ) <del> ), <del> array( <del> 'request' => array( <del> 'uri' => array( <del> 'host' => 'www.cakephp.org', <del> 'query' => '?foo=bar' <del> ) <del> ) <del> ), <del> array( <del> 'request' => 'www.cakephp.org/?foo=bar' <del> ), <del> array( <del> 'request' => array( <del> 'host' => '192.168.0.1', <del> 'uri' => 'http://www.cakephp.org/?foo=bar' <del> ), <del> 'expectation' => array( <del> 'request' => array( <del> 'uri' => array('host' => 'www.cakephp.org') <del> ), <del> 'config' => array( <del> 'request' => array( <del> 'uri' => array('host' => 'www.cakephp.org') <del> ), <del> 'host' => '192.168.0.1' <del> ) <del> ) <del> ), <del> 'reset4' => array( <del> 'request.uri.query' => array() <del> ), <del> array( <del> 'request' => array( <del> 'header' => array('Foo@woo' => 'bar-value') <del> ), <del> 'expectation' => array( <del> 'request' => array( <del> 'header' => "Host: www.cakephp.org\r\nConnection: close\r\nUser-Agent: CakePHP\r\nFoo\"@\"woo: bar-value\r\n", <del> 'line' => "GET / HTTP/1.1\r\n" <del> ) <del> ) <del> ), <del> array( <del> 'request' => array('header' => array('Foo@woo' => 'bar-value', 'host' => 'foo.com'), 'uri' => 'http://www.cakephp.org/'), <del> 'expectation' => array( <del> 'request' => array( <del> 'header' => "Host: foo.com\r\nConnection: close\r\nUser-Agent: CakePHP\r\nFoo\"@\"woo: bar-value\r\n" <del> ), <del> 'config' => array( <del> 'host' => 'www.cakephp.org' <del> ) <del> ) <del> ), <del> array( <del> 'request' => array('header' => "Foo: bar\r\n"), <del> 'expectation' => array( <del> 'request' => array( <del> 'header' => "Foo: bar\r\n" <del> ) <del> ) <del> ), <del> array( <del> 'request' => array('header' => "Foo: bar\r\n", 'uri' => 'http://www.cakephp.org/search?q=http_socket#ignore-me'), <del> 'expectation' => array( <del> 'request' => array( <del> 'uri' => array( <del> 'path' => '/search', <del> 'query' => array('q' => 'http_socket'), <del> 'fragment' => 'ignore-me' <del> ), <del> 'line' => "GET /search?q=http_socket HTTP/1.1\r\n" <del> ) <del> ) <del> ), <del> 'reset8' => array( <del> 'request.uri.query' => array() <del> ), <del> array( <del> 'request' => array( <del> 'method' => 'POST', <del> 'uri' => 'http://www.cakephp.org/posts/add', <del> 'body' => array( <del> 'name' => 'HttpSocket-is-released', <del> 'date' => 'today' <del> ) <del> ), <del> 'expectation' => array( <del> 'request' => array( <del> 'method' => 'POST', <del> 'uri' => array( <del> 'path' => '/posts/add', <del> 'fragment' => null <del> ), <del> 'body' => "name=HttpSocket-is-released&date=today", <del> 'line' => "POST /posts/add HTTP/1.1\r\n", <del> 'header' => "Host: www.cakephp.org\r\nConnection: close\r\nUser-Agent: CakePHP\r\nContent-Type: application/x-www-form-urlencoded\r\nContent-Length: 38\r\n", <del> 'raw' => "name=HttpSocket-is-released&date=today" <del> ) <del> ) <del> ), <del> array( <del> 'request' => array( <del> 'method' => 'POST', <del> 'uri' => 'http://www.cakephp.org:8080/posts/add', <del> 'body' => array( <del> 'name' => 'HttpSocket-is-released', <del> 'date' => 'today' <del> ) <del> ), <del> 'expectation' => array( <del> 'config' => array( <del> 'port' => 8080, <del> 'request' => array( <del> 'uri' => array( <del> 'port' => 8080 <del> ) <del> ) <del> ), <del> 'request' => array( <del> 'uri' => array( <del> 'port' => 8080 <del> ), <del> 'header' => "Host: www.cakephp.org:8080\r\nConnection: close\r\nUser-Agent: CakePHP\r\nContent-Type: application/x-www-form-urlencoded\r\nContent-Length: 38\r\n" <del> ) <del> ) <del> ), <del> array( <del> 'request' => array( <del> 'method' => 'POST', <del> 'uri' => 'https://www.cakephp.org/posts/add', <del> 'body' => array( <del> 'name' => 'HttpSocket-is-released', <del> 'date' => 'today' <del> ) <del> ), <del> 'expectation' => array( <del> 'config' => array( <del> 'port' => 443, <del> 'request' => array( <del> 'uri' => array( <del> 'scheme' => 'https', <del> 'port' => 443 <del> ) <del> ) <del> ), <del> 'request' => array( <del> 'uri' => array( <del> 'scheme' => 'https', <del> 'port' => 443 <del> ), <del> 'header' => "Host: www.cakephp.org\r\nConnection: close\r\nUser-Agent: CakePHP\r\nContent-Type: application/x-www-form-urlencoded\r\nContent-Length: 38\r\n" <del> ) <del> ) <del> ), <del> array( <del> 'request' => array( <del> 'method' => 'POST', <del> 'uri' => 'https://www.cakephp.org/posts/add', <del> 'body' => array('name' => 'HttpSocket-is-released', 'date' => 'today'), <del> 'cookies' => array('foo' => array('value' => 'bar')) <del> ), <del> 'expectation' => array( <del> 'request' => array( <del> 'header' => "Host: www.cakephp.org\r\nConnection: close\r\nUser-Agent: CakePHP\r\nContent-Type: application/x-www-form-urlencoded\r\nContent-Length: 38\r\nCookie: foo=bar\r\n", <del> 'cookies' => array( <del> 'foo' => array('value' => 'bar'), <del> ) <del> ) <del> ) <del> ) <del> ); <del> <del> $expectation = array(); <del> foreach ($tests as $i => $test) { <del> if (strpos($i, 'reset') === 0) { <del> foreach ($test as $path => $val) { <del> $expectation = Hash::insert($expectation, $path, $val); <del> } <del> continue; <del> } <del> <del> if (isset($test['expectation'])) { <del> $expectation = Hash::merge($expectation, $test['expectation']); <del> } <del> $this->Socket->request($test['request']); <del> <del> $raw = $expectation['request']['raw']; <del> $expectation['request']['raw'] = $expectation['request']['line'] . $expectation['request']['header'] . "\r\n" . $raw; <del> <del> $r = array('config' => $this->Socket->config, 'request' => $this->Socket->request); <del> $v = $this->assertEquals($r, $expectation, 'Failed test #' . $i . ' '); <del> $expectation['request']['raw'] = $raw; <del> } <del> <del> $this->Socket->reset(); <del> $request = array('method' => 'POST', 'uri' => 'http://www.cakephp.org/posts/add', 'body' => array('name' => 'HttpSocket-is-released', 'date' => 'today')); <del> $response = $this->Socket->request($request); <del> $this->assertEquals("name=HttpSocket-is-released&date=today", $this->Socket->request['body']); <del> } <del> <del>/** <del> * Test the scheme + port keys <del> * <del> * @return void <del> */ <del> public function testGetWithSchemeAndPort() { <del> $this->Socket->reset(); <del> $request = array( <del> 'uri' => array( <del> 'scheme' => 'http', <del> 'host' => 'cakephp.org', <del> 'port' => 8080, <del> 'path' => '/', <del> ), <del> 'method' => 'GET' <del> ); <del> $response = $this->Socket->request($request); <del> $this->assertContains('Host: cakephp.org:8080', $this->Socket->request['header']); <del> } <del> <del>/** <del> * Test urls like http://cakephp.org/index.php?somestring without key/value pair for query <del> * <del> * @return void <del> */ <del> public function testRequestWithStringQuery() { <del> $this->Socket->reset(); <del> $request = array( <del> 'uri' => array( <del> 'scheme' => 'http', <del> 'host' => 'cakephp.org', <del> 'path' => 'index.php', <del> 'query' => 'somestring' <del> ), <del> 'method' => 'GET' <del> ); <del> $response = $this->Socket->request($request); <del> $this->assertContains("GET /index.php?somestring HTTP/1.1", $this->Socket->request['line']); <del> } <del> <del>/** <del> * The "*" asterisk character is only allowed for the following methods: OPTIONS. <del> * <del> * @expectedException Cake\Error\SocketException <del> * @return void <del> */ <del> public function testRequestNotAllowedUri() { <del> $this->Socket->reset(); <del> $request = array('uri' => '*', 'method' => 'GET'); <del> $response = $this->Socket->request($request); <del> } <del> <del>/** <del> * testRequest2 method <del> * <del> * @return void <del> */ <del> public function testRequest2() { <del> $this->Socket->reset(); <del> $request = array('uri' => 'htpp://www.cakephp.org/'); <del> $number = mt_rand(0, 9999999); <del> $this->Socket->expects($this->once())->method('connect')->will($this->returnValue(true)); <del> $serverResponse = "HTTP/1.x 200 OK\r\nDate: Mon, 16 Apr 2007 04:14:16 GMT\r\nServer: CakeHttp Server\r\nContent-Type: text/html\r\n\r\n<h1>Hello, your lucky number is " . $number . "</h1>"; <del> $this->Socket->expects($this->at(0))->method('read')->will($this->returnValue(false)); <del> $this->Socket->expects($this->at(1))->method('read')->will($this->returnValue($serverResponse)); <del> $this->Socket->expects($this->once())->method('write') <del> ->with("GET / HTTP/1.1\r\nHost: www.cakephp.org\r\nConnection: close\r\nUser-Agent: CakePHP\r\n\r\n"); <del> $response = (string)$this->Socket->request($request); <del> $this->assertEquals($response, "<h1>Hello, your lucky number is " . $number . "</h1>"); <del> } <del> <del>/** <del> * testRequest3 method <del> * <del> * @return void <del> */ <del> public function testRequest3() { <del> $request = array('uri' => 'htpp://www.cakephp.org/'); <del> $serverResponse = "HTTP/1.x 200 OK\r\nSet-Cookie: foo=bar\r\nDate: Mon, 16 Apr 2007 04:14:16 GMT\r\nServer: CakeHttp Server\r\nContent-Type: text/html\r\n\r\n<h1>This is a cookie test!</h1>"; <del> $this->Socket->expects($this->at(1))->method('read')->will($this->returnValue($serverResponse)); <del> $this->Socket->connected = true; <del> $this->Socket->request($request); <del> $result = $this->Socket->response['cookies']; <del> $expect = array( <del> 'foo' => array( <del> 'value' => 'bar' <del> ) <del> ); <del> $this->assertEquals($expect, $result); <del> $this->assertEquals($this->Socket->config['request']['cookies']['www.cakephp.org'], $expect); <del> $this->assertFalse($this->Socket->connected); <del> } <del> <del>/** <del> * testRequestWithConstructor method <del> * <del> * @return void <del> */ <del> public function testRequestWithConstructor() { <del> $request = array( <del> 'request' => array( <del> 'uri' => array( <del> 'scheme' => 'http', <del> 'host' => 'localhost', <del> 'port' => '5984', <del> 'user' => null, <del> 'pass' => null <del> ) <del> ) <del> ); <del> $http = new \MockHttpSocketRequests($request); <del> <del> $expected = array('method' => 'GET', 'uri' => '/_test'); <del> $http->expects($this->at(0))->method('request')->with($expected); <del> $http->get('/_test'); <del> <del> $expected = array('method' => 'GET', 'uri' => 'http://localhost:5984/_test?count=4'); <del> $http->expects($this->at(0))->method('request')->with($expected); <del> $http->get('/_test', array('count' => 4)); <del> } <del> <del>/** <del> * testRequestWithResource <del> * <del> * @return void <del> */ <del> public function testRequestWithResource() { <del> $serverResponse = "HTTP/1.x 200 OK\r\nDate: Mon, 16 Apr 2007 04:14:16 GMT\r\nServer: CakeHttp Server\r\nContent-Type: text/html\r\n\r\n<h1>This is a test!</h1>"; <del> $this->Socket->expects($this->at(1))->method('read')->will($this->returnValue($serverResponse)); <del> $this->Socket->expects($this->at(2))->method('read')->will($this->returnValue(false)); <del> $this->Socket->expects($this->at(4))->method('read')->will($this->returnValue($serverResponse)); <del> $this->Socket->connected = true; <del> <del> $f = fopen(TMP . 'download.txt', 'w'); <del> if (!$f) { <del> $this->markTestSkipped('Can not write in TMP directory.'); <del> } <del> <del> $this->Socket->setContentResource($f); <del> $result = (string)$this->Socket->request('http://www.cakephp.org/'); <del> $this->assertEquals('', $result); <del> $this->assertEquals('CakeHttp Server', $this->Socket->response['header']['Server']); <del> fclose($f); <del> $this->assertEquals(file_get_contents(TMP . 'download.txt'), '<h1>This is a test!</h1>'); <del> unlink(TMP . 'download.txt'); <del> <del> $this->Socket->setContentResource(false); <del> $result = (string)$this->Socket->request('http://www.cakephp.org/'); <del> $this->assertEquals('<h1>This is a test!</h1>', $result); <del> } <del> <del>/** <del> * testRequestWithCrossCookie <del> * <del> * @return void <del> */ <del> public function testRequestWithCrossCookie() { <del> $this->Socket->connected = true; <del> $this->Socket->config['request']['cookies'] = array(); <del> <del> $serverResponse = "HTTP/1.x 200 OK\r\nSet-Cookie: foo=bar\r\nDate: Mon, 16 Apr 2007 04:14:16 GMT\r\nServer: CakeHttp Server\r\nContent-Type: text/html\r\n\r\n<h1>This is a test!</h1>"; <del> $this->Socket->expects($this->at(1))->method('read')->will($this->returnValue($serverResponse)); <del> $this->Socket->expects($this->at(2))->method('read')->will($this->returnValue(false)); <del> $expected = array('www.cakephp.org' => array('foo' => array('value' => 'bar'))); <del> $this->Socket->request('http://www.cakephp.org/'); <del> $this->assertEquals($expected, $this->Socket->config['request']['cookies']); <del> <del> $serverResponse = "HTTP/1.x 200 OK\r\nSet-Cookie: bar=foo\r\nDate: Mon, 16 Apr 2007 04:14:16 GMT\r\nServer: CakeHttp Server\r\nContent-Type: text/html\r\n\r\n<h1>This is a test!</h1>"; <del> $this->Socket->expects($this->at(1))->method('read')->will($this->returnValue($serverResponse)); <del> $this->Socket->expects($this->at(2))->method('read')->will($this->returnValue(false)); <del> $this->Socket->request('http://www.cakephp.org/other'); <del> $this->assertEquals(array('foo' => array('value' => 'bar')), $this->Socket->request['cookies']); <del> $expected['www.cakephp.org'] += array('bar' => array('value' => 'foo')); <del> $this->assertEquals($expected, $this->Socket->config['request']['cookies']); <del> <del> $serverResponse = "HTTP/1.x 200 OK\r\nDate: Mon, 16 Apr 2007 04:14:16 GMT\r\nServer: CakeHttp Server\r\nContent-Type: text/html\r\n\r\n<h1>This is a test!</h1>"; <del> $this->Socket->expects($this->at(1))->method('read')->will($this->returnValue($serverResponse)); <del> $this->Socket->expects($this->at(2))->method('read')->will($this->returnValue(false)); <del> $this->Socket->request('/other2'); <del> $this->assertEquals($expected, $this->Socket->config['request']['cookies']); <del> <del> $serverResponse = "HTTP/1.x 200 OK\r\nSet-Cookie: foobar=ok\r\nDate: Mon, 16 Apr 2007 04:14:16 GMT\r\nServer: CakeHttp Server\r\nContent-Type: text/html\r\n\r\n<h1>This is a test!</h1>"; <del> $this->Socket->expects($this->at(1))->method('read')->will($this->returnValue($serverResponse)); <del> $this->Socket->expects($this->at(2))->method('read')->will($this->returnValue(false)); <del> $this->Socket->request('http://www.cake.com'); <del> $this->assertTrue(empty($this->Socket->request['cookies'])); <del> $expected['www.cake.com'] = array('foobar' => array('value' => 'ok')); <del> $this->assertEquals($expected, $this->Socket->config['request']['cookies']); <del> } <del> <del>/** <del> * testRequestCustomResponse <del> * <del> * @return void <del> */ <del> public function testRequestCustomResponse() { <del> $this->Socket->connected = true; <del> $serverResponse = "HTTP/1.x 200 OK\r\nDate: Mon, 16 Apr 2007 04:14:16 GMT\r\nServer: CakeHttp Server\r\nContent-Type: text/html\r\n\r\n<h1>This is a test!</h1>"; <del> $this->Socket->expects($this->at(1))->method('read')->will($this->returnValue($serverResponse)); <del> $this->Socket->expects($this->at(2))->method('read')->will($this->returnValue(false)); <del> <del> $this->Socket->responseClass = __NAMESPACE__ . '\CustomResponse'; <del> $response = $this->Socket->request('http://www.cakephp.org/'); <del> $this->assertInstanceOf(__NAMESPACE__ . '\CustomResponse', $response); <del> $this->assertEquals('HTTP/1.x 2', $response->first10); <del> } <del> <del>/** <del> * Test that redirect urls are urldecoded <del> * <del> * @return void <del> */ <del> public function testRequestWithRedirectUrlEncoded() { <del> $request = array( <del> 'uri' => 'http://localhost/oneuri', <del> 'redirect' => 1 <del> ); <del> $serverResponse1 = "HTTP/1.x 302 Found\r\nDate: Mon, 16 Apr 2007 04:14:16 GMT\r\nServer: CakeHttp Server\r\nContent-Type: text/html\r\nLocation: http://i.cmpnet.com%2Ftechonline%2Fpdf%2Fa.pdf=\r\n\r\n"; <del> $serverResponse2 = "HTTP/1.x 200 OK\r\nDate: Mon, 16 Apr 2007 04:14:16 GMT\r\nServer: CakeHttp Server\r\nContent-Type: text/html\r\n\r\n<h1>You have been redirected</h1>"; <del> <del> $this->Socket->expects($this->at(1)) <del> ->method('read') <del> ->will($this->returnValue($serverResponse1)); <del> <del> $this->Socket->expects($this->at(3)) <del> ->method('write') <del> ->with($this->logicalAnd( <del> $this->stringContains('Host: i.cmpnet.com'), <del> $this->stringContains('GET /techonline/pdf/a.pdf') <del> )); <del> <del> $this->Socket->expects($this->at(4)) <del> ->method('read') <del> ->will($this->returnValue($serverResponse2)); <del> <del> $response = $this->Socket->request($request); <del> $this->assertEquals('<h1>You have been redirected</h1>', $response->body()); <del> } <del> <del>/** <del> * testRequestWithRedirect method <del> * <del> * @return void <del> */ <del> public function testRequestWithRedirectAsTrue() { <del> $request = array( <del> 'uri' => 'http://localhost/oneuri', <del> 'redirect' => true <del> ); <del> $serverResponse1 = "HTTP/1.x 302 Found\r\nDate: Mon, 16 Apr 2007 04:14:16 GMT\r\nServer: CakeHttp Server\r\nContent-Type: text/html\r\nLocation: http://localhost/anotheruri\r\n\r\n"; <del> $serverResponse2 = "HTTP/1.x 200 OK\r\nDate: Mon, 16 Apr 2007 04:14:16 GMT\r\nServer: CakeHttp Server\r\nContent-Type: text/html\r\n\r\n<h1>You have been redirected</h1>"; <del> $this->Socket->expects($this->at(1))->method('read')->will($this->returnValue($serverResponse1)); <del> $this->Socket->expects($this->at(4))->method('read')->will($this->returnValue($serverResponse2)); <del> <del> $response = $this->Socket->request($request); <del> $this->assertEquals('<h1>You have been redirected</h1>', $response->body()); <del> } <del> <del>/** <del> * Test that redirects with a count limit are decremented. <del> * <del> * @return void <del> */ <del> public function testRequestWithRedirectAsInt() { <del> $request = array( <del> 'uri' => 'http://localhost/oneuri', <del> 'redirect' => 2 <del> ); <del> $serverResponse1 = "HTTP/1.x 302 Found\r\nDate: Mon, 16 Apr 2007 04:14:16 GMT\r\nServer: CakeHttp Server\r\nContent-Type: text/html\r\nLocation: http://localhost/anotheruri\r\n\r\n"; <del> $serverResponse2 = "HTTP/1.x 200 OK\r\nDate: Mon, 16 Apr 2007 04:14:16 GMT\r\nServer: CakeHttp Server\r\nContent-Type: text/html\r\n\r\n<h1>You have been redirected</h1>"; <del> $this->Socket->expects($this->at(1))->method('read')->will($this->returnValue($serverResponse1)); <del> $this->Socket->expects($this->at(4))->method('read')->will($this->returnValue($serverResponse2)); <del> <del> $response = $this->Socket->request($request); <del> $this->assertEquals(1, $this->Socket->request['redirect']); <del> } <del> <del>/** <del> * Test that redirects after the redirect count reaches 9 are not followed. <del> * <del> * @return void <del> */ <del> public function testRequestWithRedirectAsIntReachingZero() { <del> $request = array( <del> 'uri' => 'http://localhost/oneuri', <del> 'redirect' => 1 <del> ); <del> $serverResponse1 = "HTTP/1.x 302 Found\r\nDate: Mon, 16 Apr 2007 04:14:16 GMT\r\nServer: CakeHttp Server\r\nContent-Type: text/html\r\nLocation: http://localhost/oneruri\r\n\r\n"; <del> $serverResponse2 = "HTTP/1.x 302 Found\r\nDate: Mon, 16 Apr 2007 04:14:16 GMT\r\nServer: CakeHttp Server\r\nContent-Type: text/html\r\nLocation: http://localhost/anotheruri\r\n\r\n"; <del> $this->Socket->expects($this->at(1))->method('read')->will($this->returnValue($serverResponse1)); <del> $this->Socket->expects($this->at(4))->method('read')->will($this->returnValue($serverResponse2)); <del> <del> $response = $this->Socket->request($request); <del> $this->assertEquals(0, $this->Socket->request['redirect']); <del> $this->assertEquals(302, $response->code); <del> $this->assertEquals('http://localhost/anotheruri', $response->getHeader('Location')); <del> } <del> <del>/** <del> * testProxy method <del> * <del> * @return void <del> */ <del> public function testProxy() { <del> $this->Socket->reset(); <del> $this->Socket->expects($this->any()) <del> ->method('connect') <del> ->will($this->returnValue(true)); <del> <del> $this->Socket->expects($this->any()) <del> ->method('read') <del> ->will($this->returnValue(false)); <del> <del> $this->Socket->configProxy('proxy.server', 123); <del> $expected = "GET http://www.cakephp.org/ HTTP/1.1\r\nHost: www.cakephp.org\r\nConnection: close\r\nUser-Agent: CakePHP\r\n\r\n"; <del> $this->Socket->request('http://www.cakephp.org/'); <del> $this->assertEquals($expected, $this->Socket->request['raw']); <del> $this->assertEquals('proxy.server', $this->Socket->config['host']); <del> $this->assertEquals(123, $this->Socket->config['port']); <del> $expected = array( <del> 'host' => 'proxy.server', <del> 'port' => 123, <del> 'method' => null, <del> 'user' => null, <del> 'pass' => null <del> ); <del> $this->assertEquals($expected, $this->Socket->request['proxy']); <del> <del> $expected = "GET http://www.cakephp.org/bakery HTTP/1.1\r\nHost: www.cakephp.org\r\nConnection: close\r\nUser-Agent: CakePHP\r\n\r\n"; <del> $this->Socket->request('/bakery'); <del> $this->assertEquals($expected, $this->Socket->request['raw']); <del> $this->assertEquals('proxy.server', $this->Socket->config['host']); <del> $this->assertEquals(123, $this->Socket->config['port']); <del> $expected = array( <del> 'host' => 'proxy.server', <del> 'port' => 123, <del> 'method' => null, <del> 'user' => null, <del> 'pass' => null <del> ); <del> $this->assertEquals($expected, $this->Socket->request['proxy']); <del> <del> $expected = "GET http://www.cakephp.org/ HTTP/1.1\r\nHost: www.cakephp.org\r\nConnection: close\r\nUser-Agent: CakePHP\r\nProxy-Authorization: Test mark.secret\r\n\r\n"; <del> $class = __NAMESPACE__ . '\TestAuthentication'; <del> $this->Socket->configProxy('proxy.server', 123, $class, 'mark', 'secret'); <del> $this->Socket->request('http://www.cakephp.org/'); <del> $this->assertEquals($expected, $this->Socket->request['raw']); <del> $this->assertEquals('proxy.server', $this->Socket->config['host']); <del> $this->assertEquals(123, $this->Socket->config['port']); <del> $expected = array( <del> 'host' => 'proxy.server', <del> 'port' => 123, <del> 'method' => $class, <del> 'user' => 'mark', <del> 'pass' => 'secret' <del> ); <del> $this->assertEquals($expected, $this->Socket->request['proxy']); <del> <del> $this->Socket->configAuth($class, 'login', 'passwd'); <del> $expected = "GET http://www.cakephp.org/ HTTP/1.1\r\nHost: www.cakephp.org\r\nConnection: close\r\nUser-Agent: CakePHP\r\nProxy-Authorization: Test mark.secret\r\nAuthorization: Test login.passwd\r\n\r\n"; <del> $this->Socket->request('http://www.cakephp.org/'); <del> $this->assertEquals($expected, $this->Socket->request['raw']); <del> $expected = array( <del> 'host' => 'proxy.server', <del> 'port' => 123, <del> 'method' => $class, <del> 'user' => 'mark', <del> 'pass' => 'secret' <del> ); <del> $this->assertEquals($expected, $this->Socket->request['proxy']); <del> $expected = array( <del> $class => array( <del> 'user' => 'login', <del> 'pass' => 'passwd' <del> ) <del> ); <del> $this->assertEquals($expected, $this->Socket->request['auth']); <del> } <del> <del>/** <del> * testUrl method <del> * <del> * @return void <del> */ <del> public function testUrl() { <del> $this->Socket->reset(true); <del> <del> $this->assertEquals(false, $this->Socket->url(true)); <del> <del> $url = $this->Socket->url('www.cakephp.org'); <del> $this->assertEquals('http://www.cakephp.org/', $url); <del> <del> $url = $this->Socket->url('https://www.cakephp.org/posts/add'); <del> $this->assertEquals('https://www.cakephp.org/posts/add', $url); <del> $url = $this->Socket->url('http://www.cakephp/search?q=socket', '/%path?%query'); <del> $this->assertEquals('/search?q=socket', $url); <del> <del> $this->Socket->config['request']['uri']['host'] = 'bakery.cakephp.org'; <del> $url = $this->Socket->url(); <del> $this->assertEquals('http://bakery.cakephp.org/', $url); <del> <del> $this->Socket->configUri('http://www.cakephp.org'); <del> $url = $this->Socket->url('/search?q=bar'); <del> $this->assertEquals('http://www.cakephp.org/search?q=bar', $url); <del> <del> $url = $this->Socket->url(array('host' => 'www.foobar.org', 'query' => array('q' => 'bar'))); <del> $this->assertEquals('http://www.foobar.org/?q=bar', $url); <del> <del> $url = $this->Socket->url(array('path' => '/supersearch', 'query' => array('q' => 'bar'))); <del> $this->assertEquals('http://www.cakephp.org/supersearch?q=bar', $url); <del> <del> $this->Socket->configUri('http://www.google.com'); <del> $url = $this->Socket->url('/search?q=socket'); <del> $this->assertEquals('http://www.google.com/search?q=socket', $url); <del> <del> $url = $this->Socket->url(); <del> $this->assertEquals('http://www.google.com/', $url); <del> <del> $this->Socket->configUri('https://www.google.com'); <del> $url = $this->Socket->url('/search?q=socket'); <del> $this->assertEquals('https://www.google.com/search?q=socket', $url); <del> <del> $this->Socket->reset(); <del> $this->Socket->configUri('www.google.com:443'); <del> $url = $this->Socket->url('/search?q=socket'); <del> $this->assertEquals('https://www.google.com/search?q=socket', $url); <del> <del> $this->Socket->reset(); <del> $this->Socket->configUri('www.google.com:8080'); <del> $url = $this->Socket->url('/search?q=socket'); <del> $this->assertEquals('http://www.google.com:8080/search?q=socket', $url); <del> } <del> <del>/** <del> * testGet method <del> * <del> * @return void <del> */ <del> public function testGet() { <del> $this->RequestSocket->reset(); <del> <del> $this->RequestSocket->expects($this->at(0)) <del> ->method('request') <del> ->with(array('method' => 'GET', 'uri' => 'http://www.google.com/')); <del> <del> $this->RequestSocket->expects($this->at(1)) <del> ->method('request') <del> ->with(array('method' => 'GET', 'uri' => 'http://www.google.com/?foo=bar')); <del> <del> $this->RequestSocket->expects($this->at(2)) <del> ->method('request') <del> ->with(array('method' => 'GET', 'uri' => 'http://www.google.com/?foo=bar')); <del> <del> $this->RequestSocket->expects($this->at(3)) <del> ->method('request') <del> ->with(array('method' => 'GET', 'uri' => 'http://www.google.com/?foo=23&foobar=42')); <del> <del> $this->RequestSocket->expects($this->at(4)) <del> ->method('request') <del> ->with(array('method' => 'GET', 'uri' => 'http://www.google.com/', 'version' => '1.0')); <del> <del> $this->RequestSocket->expects($this->at(5)) <del> ->method('request') <del> ->with(array('method' => 'GET', 'uri' => 'https://secure.example.com/test.php?one=two')); <del> <del> $this->RequestSocket->expects($this->at(6)) <del> ->method('request') <del> ->with(array('method' => 'GET', 'uri' => 'https://example.com/oauth/access?clientid=123&redirect_uri=http%3A%2F%2Fexample.com&code=456')); <del> <del> $this->RequestSocket->get('http://www.google.com/'); <del> $this->RequestSocket->get('http://www.google.com/', array('foo' => 'bar')); <del> $this->RequestSocket->get('http://www.google.com/', 'foo=bar'); <del> $this->RequestSocket->get('http://www.google.com/?foo=bar', array('foobar' => '42', 'foo' => '23')); <del> $this->RequestSocket->get('http://www.google.com/', null, array('version' => '1.0')); <del> $this->RequestSocket->get('https://secure.example.com/test.php', array('one' => 'two')); <del> $this->RequestSocket->get('https://example.com/oauth/access', array( <del> 'clientid' => '123', <del> 'redirect_uri' => 'http://example.com', <del> 'code' => 456 <del> )); <del> } <del> <del>/** <del> * Test authentication <del> * <del> * @return void <del> */ <del> public function testAuth() { <del> $socket = new \MockHttpSocket(); <del> $socket->get('http://mark:secret@example.com/test'); <del> $this->assertTrue(strpos($socket->request['header'], 'Authorization: Basic bWFyazpzZWNyZXQ=') !== false); <del> <del> $socket->configAuth(false); <del> $socket->get('http://example.com/test'); <del> $this->assertFalse(strpos($socket->request['header'], 'Authorization:')); <del> <del> $class = __NAMESPACE__ . '\TestAuthentication'; <del> $socket->configAuth($class, 'mark', 'passwd'); <del> $socket->get('http://example.com/test'); <del> $this->assertTrue(strpos($socket->request['header'], 'Authorization: Test mark.passwd') !== false); <del> } <del> <del>/** <del> * test that two consecutive get() calls reset the authentication credentials. <del> * <del> * @return void <del> */ <del> public function testConsecutiveGetResetsAuthCredentials() { <del> $socket = new \MockHttpSocket(); <del> $socket->get('http://mark:secret@example.com/test'); <del> $this->assertEquals('mark', $socket->request['uri']['user']); <del> $this->assertEquals('secret', $socket->request['uri']['pass']); <del> $this->assertTrue(strpos($socket->request['header'], 'Authorization: Basic bWFyazpzZWNyZXQ=') !== false); <del> <del> $socket->get('/test2'); <del> $this->assertTrue(strpos($socket->request['header'], 'Authorization: Basic bWFyazpzZWNyZXQ=') !== false); <del> <del> $socket->get('/test3'); <del> $this->assertTrue(strpos($socket->request['header'], 'Authorization: Basic bWFyazpzZWNyZXQ=') !== false); <del> } <del> <del>/** <del> * testPostPutDelete method <del> * <del> * @return void <del> */ <del> public function testPost() { <del> $this->RequestSocket->reset(); <del> $this->RequestSocket->expects($this->at(0)) <del> ->method('request') <del> ->with(array('method' => 'POST', 'uri' => 'http://www.google.com/', 'body' => array())); <del> <del> $this->RequestSocket->expects($this->at(1)) <del> ->method('request') <del> ->with(array('method' => 'POST', 'uri' => 'http://www.google.com/', 'body' => array('Foo' => 'bar'))); <del> <del> $this->RequestSocket->expects($this->at(2)) <del> ->method('request') <del> ->with(array('method' => 'POST', 'uri' => 'http://www.google.com/', 'body' => null, 'line' => 'Hey Server')); <del> <del> $this->RequestSocket->post('http://www.google.com/'); <del> $this->RequestSocket->post('http://www.google.com/', array('Foo' => 'bar')); <del> $this->RequestSocket->post('http://www.google.com/', null, array('line' => 'Hey Server')); <del> } <del> <del>/** <del> * testPut <del> * <del> * @return void <del> */ <del> public function testPut() { <del> $this->RequestSocket->reset(); <del> $this->RequestSocket->expects($this->at(0)) <del> ->method('request') <del> ->with(array('method' => 'PUT', 'uri' => 'http://www.google.com/', 'body' => array())); <del> <del> $this->RequestSocket->expects($this->at(1)) <del> ->method('request') <del> ->with(array('method' => 'PUT', 'uri' => 'http://www.google.com/', 'body' => array('Foo' => 'bar'))); <del> <del> $this->RequestSocket->expects($this->at(2)) <del> ->method('request') <del> ->with(array('method' => 'PUT', 'uri' => 'http://www.google.com/', 'body' => null, 'line' => 'Hey Server')); <del> <del> $this->RequestSocket->put('http://www.google.com/'); <del> $this->RequestSocket->put('http://www.google.com/', array('Foo' => 'bar')); <del> $this->RequestSocket->put('http://www.google.com/', null, array('line' => 'Hey Server')); <del> } <del> <del>/** <del> * testDelete <del> * <del> * @return void <del> */ <del> public function testDelete() { <del> $this->RequestSocket->reset(); <del> $this->RequestSocket->expects($this->at(0)) <del> ->method('request') <del> ->with(array('method' => 'DELETE', 'uri' => 'http://www.google.com/', 'body' => array())); <del> <del> $this->RequestSocket->expects($this->at(1)) <del> ->method('request') <del> ->with(array('method' => 'DELETE', 'uri' => 'http://www.google.com/', 'body' => array('Foo' => 'bar'))); <del> <del> $this->RequestSocket->expects($this->at(2)) <del> ->method('request') <del> ->with(array('method' => 'DELETE', 'uri' => 'http://www.google.com/', 'body' => null, 'line' => 'Hey Server')); <del> <del> $this->RequestSocket->delete('http://www.google.com/'); <del> $this->RequestSocket->delete('http://www.google.com/', array('Foo' => 'bar')); <del> $this->RequestSocket->delete('http://www.google.com/', null, array('line' => 'Hey Server')); <del> } <del> <del>/** <del> * testBuildRequestLine method <del> * <del> * @return void <del> */ <del> public function testBuildRequestLine() { <del> $this->Socket->reset(); <del> <del> $this->Socket->quirksMode = true; <del> $r = $this->Socket->buildRequestLine('Foo'); <del> $this->assertEquals('Foo', $r); <del> $this->Socket->quirksMode = false; <del> <del> $r = $this->Socket->buildRequestLine(true); <del> $this->assertEquals(false, $r); <del> <del> $r = $this->Socket->buildRequestLine(array('foo' => 'bar', 'method' => 'foo')); <del> $this->assertEquals(false, $r); <del> <del> $r = $this->Socket->buildRequestLine(array('method' => 'GET', 'uri' => 'http://www.cakephp.org/search?q=socket')); <del> $this->assertEquals("GET /search?q=socket HTTP/1.1\r\n", $r); <del> <del> $request = array( <del> 'method' => 'GET', <del> 'uri' => array( <del> 'path' => '/search', <del> 'query' => array('q' => 'socket') <del> ) <del> ); <del> $r = $this->Socket->buildRequestLine($request); <del> $this->assertEquals("GET /search?q=socket HTTP/1.1\r\n", $r); <del> <del> unset($request['method']); <del> $r = $this->Socket->buildRequestLine($request); <del> $this->assertEquals("GET /search?q=socket HTTP/1.1\r\n", $r); <del> <del> $r = $this->Socket->buildRequestLine($request, 'CAKE-HTTP/0.1'); <del> $this->assertEquals("GET /search?q=socket CAKE-HTTP/0.1\r\n", $r); <del> <del> $request = array('method' => 'OPTIONS', 'uri' => '*'); <del> $r = $this->Socket->buildRequestLine($request); <del> $this->assertEquals("OPTIONS * HTTP/1.1\r\n", $r); <del> <del> $request['method'] = 'GET'; <del> $this->Socket->quirksMode = true; <del> $r = $this->Socket->buildRequestLine($request); <del> $this->assertEquals("GET * HTTP/1.1\r\n", $r); <del> <del> $r = $this->Socket->buildRequestLine("GET * HTTP/1.1\r\n"); <del> $this->assertEquals("GET * HTTP/1.1\r\n", $r); <del> } <del> <del>/** <del> * testBadBuildRequestLine method <del> * <del> * @expectedException Cake\Error\SocketException <del> * @return void <del> */ <del> public function testBadBuildRequestLine() { <del> $r = $this->Socket->buildRequestLine('Foo'); <del> } <del> <del>/** <del> * testBadBuildRequestLine2 method <del> * <del> * @expectedException Cake\Error\SocketException <del> * @return void <del> */ <del> public function testBadBuildRequestLine2() { <del> $r = $this->Socket->buildRequestLine("GET * HTTP/1.1\r\n"); <del> } <del> <del>/** <del> * Asserts that HttpSocket::parseUri is working properly <del> * <del> * @return void <del> */ <del> public function testParseUri() { <del> $this->Socket->reset(); <del> <del> $uri = $this->Socket->parseUri(array('invalid' => 'uri-string')); <del> $this->assertEquals(false, $uri); <del> <del> $uri = $this->Socket->parseUri(array('invalid' => 'uri-string'), array('host' => 'somehost')); <del> $this->assertEquals(array('host' => 'somehost', 'invalid' => 'uri-string'), $uri); <del> <del> $uri = $this->Socket->parseUri(false); <del> $this->assertEquals(false, $uri); <del> <del> $uri = $this->Socket->parseUri('/my-cool-path'); <del> $this->assertEquals(array('path' => '/my-cool-path'), $uri); <del> <del> $uri = $this->Socket->parseUri('http://bob:foo123@www.cakephp.org:40/search?q=dessert#results'); <del> $this->assertEquals($uri, array( <del> 'scheme' => 'http', <del> 'host' => 'www.cakephp.org', <del> 'port' => 40, <del> 'user' => 'bob', <del> 'pass' => 'foo123', <del> 'path' => '/search', <del> 'query' => array('q' => 'dessert'), <del> 'fragment' => 'results' <del> )); <del> <del> $uri = $this->Socket->parseUri('http://www.cakephp.org/'); <del> $this->assertEquals($uri, array( <del> 'scheme' => 'http', <del> 'host' => 'www.cakephp.org', <del> 'path' => '/' <del> )); <del> <del> $uri = $this->Socket->parseUri('http://www.cakephp.org', true); <del> $this->assertEquals($uri, array( <del> 'scheme' => 'http', <del> 'host' => 'www.cakephp.org', <del> 'port' => 80, <del> 'user' => null, <del> 'pass' => null, <del> 'path' => '/', <del> 'query' => array(), <del> 'fragment' => null <del> )); <del> <del> $uri = $this->Socket->parseUri('https://www.cakephp.org', true); <del> $this->assertEquals($uri, array( <del> 'scheme' => 'https', <del> 'host' => 'www.cakephp.org', <del> 'port' => 443, <del> 'user' => null, <del> 'pass' => null, <del> 'path' => '/', <del> 'query' => array(), <del> 'fragment' => null <del> )); <del> <del> $uri = $this->Socket->parseUri('www.cakephp.org:443/query?foo', true); <del> $this->assertEquals($uri, array( <del> 'scheme' => 'https', <del> 'host' => 'www.cakephp.org', <del> 'port' => 443, <del> 'user' => null, <del> 'pass' => null, <del> 'path' => '/query', <del> 'query' => array('foo' => ""), <del> 'fragment' => null <del> )); <del> <del> $uri = $this->Socket->parseUri('http://www.cakephp.org', array('host' => 'piephp.org', 'user' => 'bob', 'fragment' => 'results')); <del> $this->assertEquals($uri, array( <del> 'host' => 'www.cakephp.org', <del> 'user' => 'bob', <del> 'fragment' => 'results', <del> 'scheme' => 'http' <del> )); <del> <del> $uri = $this->Socket->parseUri('https://www.cakephp.org', array('scheme' => 'http', 'port' => 23)); <del> $this->assertEquals($uri, array( <del> 'scheme' => 'https', <del> 'port' => 23, <del> 'host' => 'www.cakephp.org' <del> )); <del> <del> $uri = $this->Socket->parseUri('www.cakephp.org:59', array('scheme' => array('http', 'https'), 'port' => 80)); <del> $this->assertEquals($uri, array( <del> 'scheme' => 'http', <del> 'port' => 59, <del> 'host' => 'www.cakephp.org' <del> )); <del> <del> $uri = $this->Socket->parseUri(array('scheme' => 'http', 'host' => 'www.google.com', 'port' => 8080), array('scheme' => array('http', 'https'), 'host' => 'www.google.com', 'port' => array(80, 443))); <del> $this->assertEquals($uri, array( <del> 'scheme' => 'http', <del> 'host' => 'www.google.com', <del> 'port' => 8080 <del> )); <del> <del> $uri = $this->Socket->parseUri('http://www.cakephp.org/?param1=value1&param2=value2%3Dvalue3'); <del> $this->assertEquals($uri, array( <del> 'scheme' => 'http', <del> 'host' => 'www.cakephp.org', <del> 'path' => '/', <del> 'query' => array( <del> 'param1' => 'value1', <del> 'param2' => 'value2=value3' <del> ) <del> )); <del> <del> $uri = $this->Socket->parseUri('http://www.cakephp.org/?param1=value1&param2=value2=value3'); <del> $this->assertEquals($uri, array( <del> 'scheme' => 'http', <del> 'host' => 'www.cakephp.org', <del> 'path' => '/', <del> 'query' => array( <del> 'param1' => 'value1', <del> 'param2' => 'value2=value3' <del> ) <del> )); <del> } <del> <del>/** <del> * Tests that HttpSocket::buildUri can turn all kinds of uri arrays (and strings) into fully or partially qualified URI's <del> * <del> * @return void <del> */ <del> public function testBuildUri() { <del> $this->Socket->reset(); <del> <del> $r = $this->Socket->buildUri(true); <del> $this->assertEquals(false, $r); <del> <del> $r = $this->Socket->buildUri('foo.com'); <del> $this->assertEquals('http://foo.com/', $r); <del> <del> $r = $this->Socket->buildUri(array('host' => 'www.cakephp.org')); <del> $this->assertEquals('http://www.cakephp.org/', $r); <del> <del> $r = $this->Socket->buildUri(array('host' => 'www.cakephp.org', 'scheme' => 'https')); <del> $this->assertEquals('https://www.cakephp.org/', $r); <del> <del> $r = $this->Socket->buildUri(array('host' => 'www.cakephp.org', 'port' => 23)); <del> $this->assertEquals('http://www.cakephp.org:23/', $r); <del> <del> $r = $this->Socket->buildUri(array('path' => 'www.google.com/search', 'query' => 'q=cakephp')); <del> $this->assertEquals('http://www.google.com/search?q=cakephp', $r); <del> <del> $r = $this->Socket->buildUri(array('host' => 'www.cakephp.org', 'scheme' => 'https', 'port' => 79)); <del> $this->assertEquals('https://www.cakephp.org:79/', $r); <del> <del> $r = $this->Socket->buildUri(array('host' => 'www.cakephp.org', 'path' => 'foo')); <del> $this->assertEquals('http://www.cakephp.org/foo', $r); <del> <del> $r = $this->Socket->buildUri(array('host' => 'www.cakephp.org', 'path' => '/foo')); <del> $this->assertEquals('http://www.cakephp.org/foo', $r); <del> <del> $r = $this->Socket->buildUri(array('host' => 'www.cakephp.org', 'path' => '/search', 'query' => array('q' => 'HttpSocket'))); <del> $this->assertEquals('http://www.cakephp.org/search?q=HttpSocket', $r); <del> <del> $r = $this->Socket->buildUri(array('host' => 'www.cakephp.org', 'fragment' => 'bar')); <del> $this->assertEquals('http://www.cakephp.org/#bar', $r); <del> <del> $r = $this->Socket->buildUri(array( <del> 'scheme' => 'https', <del> 'host' => 'www.cakephp.org', <del> 'port' => 25, <del> 'user' => 'bob', <del> 'pass' => 'secret', <del> 'path' => '/cool', <del> 'query' => array('foo' => 'bar'), <del> 'fragment' => 'comment' <del> )); <del> $this->assertEquals('https://bob:secret@www.cakephp.org:25/cool?foo=bar#comment', $r); <del> <del> $r = $this->Socket->buildUri(array('host' => 'www.cakephp.org', 'fragment' => 'bar'), '%fragment?%host'); <del> $this->assertEquals('bar?www.cakephp.org', $r); <del> <del> $r = $this->Socket->buildUri(array('host' => 'www.cakephp.org'), '%fragment???%host'); <del> $this->assertEquals('???www.cakephp.org', $r); <del> <del> $r = $this->Socket->buildUri(array('path' => '*'), '/%path?%query'); <del> $this->assertEquals('*', $r); <del> <del> $r = $this->Socket->buildUri(array('scheme' => 'foo', 'host' => 'www.cakephp.org')); <del> $this->assertEquals('foo://www.cakephp.org:80/', $r); <del> } <del> <del>/** <del> * Asserts that HttpSocket::parseQuery is working properly <del> * <del> * @return void <del> */ <del> public function testParseQuery() { <del> $this->Socket->reset(); <del> <del> $query = $this->Socket->parseQuery(array('framework' => 'cakephp')); <del> $this->assertEquals(array('framework' => 'cakephp'), $query); <del> <del> $query = $this->Socket->parseQuery(''); <del> $this->assertEquals(array(), $query); <del> <del> $query = $this->Socket->parseQuery('framework=cakephp'); <del> $this->assertEquals(array('framework' => 'cakephp'), $query); <del> <del> $query = $this->Socket->parseQuery('?framework=cakephp'); <del> $this->assertEquals(array('framework' => 'cakephp'), $query); <del> <del> $query = $this->Socket->parseQuery('a&b&c'); <del> $this->assertEquals(array('a' => '', 'b' => '', 'c' => ''), $query); <del> <del> $query = $this->Socket->parseQuery('value=12345'); <del> $this->assertEquals(array('value' => '12345'), $query); <del> <del> $query = $this->Socket->parseQuery('a[0]=foo&a[1]=bar&a[2]=cake'); <del> $this->assertEquals(array('a' => array(0 => 'foo', 1 => 'bar', 2 => 'cake')), $query); <del> <del> $query = $this->Socket->parseQuery('a[]=foo&a[]=bar&a[]=cake'); <del> $this->assertEquals(array('a' => array(0 => 'foo', 1 => 'bar', 2 => 'cake')), $query); <del> <del> $query = $this->Socket->parseQuery('a[][]=foo&a[][]=bar&a[][]=cake'); <del> $expectedQuery = array( <del> 'a' => array( <del> 0 => array( <del> 0 => 'foo' <del> ), <del> 1 => array( <del> 0 => 'bar' <del> ), <del> array( <del> 0 => 'cake' <del> ) <del> ) <del> ); <del> $this->assertEquals($expectedQuery, $query); <del> <del> $query = $this->Socket->parseQuery('a[][]=foo&a[bar]=php&a[][]=bar&a[][]=cake'); <del> $expectedQuery = array( <del> 'a' => array( <del> array('foo'), <del> 'bar' => 'php', <del> array('bar'), <del> array('cake') <del> ) <del> ); <del> $this->assertEquals($expectedQuery, $query); <del> <del> $query = $this->Socket->parseQuery('user[]=jim&user[3]=tom&user[]=bob'); <del> $expectedQuery = array( <del> 'user' => array( <del> 0 => 'jim', <del> 3 => 'tom', <del> 4 => 'bob' <del> ) <del> ); <del> $this->assertEquals($expectedQuery, $query); <del> <del> $queryStr = 'user[0]=foo&user[0][items][]=foo&user[0][items][]=bar&user[][name]=jim&user[1][items][personal][]=book&user[1][items][personal][]=pen&user[1][items][]=ball&user[count]=2&empty'; <del> $query = $this->Socket->parseQuery($queryStr); <del> $expectedQuery = array( <del> 'user' => array( <del> 0 => array( <del> 'items' => array( <del> 'foo', <del> 'bar' <del> ) <del> ), <del> 1 => array( <del> 'name' => 'jim', <del> 'items' => array( <del> 'personal' => array( <del> 'book' <del> , 'pen' <del> ), <del> 'ball' <del> ) <del> ), <del> 'count' => '2' <del> ), <del> 'empty' => '' <del> ); <del> $this->assertEquals($expectedQuery, $query); <del> <del> $query = 'openid.ns=example.com&foo=bar&foo=baz'; <del> $result = $this->Socket->parseQuery($query); <del> $expected = array( <del> 'openid.ns' => 'example.com', <del> 'foo' => array('bar', 'baz') <del> ); <del> $this->assertEquals($expected, $result); <del> } <del> <del>/** <del> * Tests that HttpSocket::buildHeader can turn a given $header array into a proper header string according to <del> * HTTP 1.1 specs. <del> * <del> * @return void <del> */ <del> public function testBuildHeader() { <del> $this->Socket->reset(); <del> <del> $r = $this->Socket->buildHeader(true); <del> $this->assertEquals(false, $r); <del> <del> $r = $this->Socket->buildHeader('My raw header'); <del> $this->assertEquals('My raw header', $r); <del> <del> $r = $this->Socket->buildHeader(array('Host' => 'www.cakephp.org')); <del> $this->assertEquals("Host: www.cakephp.org\r\n", $r); <del> <del> $r = $this->Socket->buildHeader(array('Host' => 'www.cakephp.org', 'Connection' => 'Close')); <del> $this->assertEquals("Host: www.cakephp.org\r\nConnection: Close\r\n", $r); <del> <del> $r = $this->Socket->buildHeader(array('People' => array('Bob', 'Jim', 'John'))); <del> $this->assertEquals("People: Bob,Jim,John\r\n", $r); <del> <del> $r = $this->Socket->buildHeader(array('Multi-Line-Field' => "This is my\r\nMulti Line field")); <del> $this->assertEquals("Multi-Line-Field: This is my\r\n Multi Line field\r\n", $r); <del> <del> $r = $this->Socket->buildHeader(array('Multi-Line-Field' => "This is my\r\n Multi Line field")); <del> $this->assertEquals("Multi-Line-Field: This is my\r\n Multi Line field\r\n", $r); <del> <del> $r = $this->Socket->buildHeader(array('Multi-Line-Field' => "This is my\r\n\tMulti Line field")); <del> $this->assertEquals("Multi-Line-Field: This is my\r\n\tMulti Line field\r\n", $r); <del> <del> $r = $this->Socket->buildHeader(array('Test@Field' => "My value")); <del> $this->assertEquals("Test\"@\"Field: My value\r\n", $r); <del> } <del> <del>/** <del> * testBuildCookies method <del> * <del> * @return void <del> */ <del> public function testBuildCookies() { <del> $cookies = array( <del> 'foo' => array( <del> 'value' => 'bar' <del> ), <del> 'people' => array( <del> 'value' => 'jim,jack,johnny;', <del> 'path' => '/accounts' <del> ) <del> ); <del> $expect = "Cookie: foo=bar; people=jim,jack,johnny\";\"\r\n"; <del> $result = $this->Socket->buildCookies($cookies); <del> $this->assertEquals($expect, $result); <del> } <del> <del>/** <del> * Tests that HttpSocket::_tokenEscapeChars() returns the right characters. <del> * <del> * @return void <del> */ <del> public function testTokenEscapeChars() { <del> $this->Socket->reset(); <del> <del> $expected = array( <del> '\x22','\x28','\x29','\x3c','\x3e','\x40','\x2c','\x3b','\x3a','\x5c','\x2f','\x5b','\x5d','\x3f','\x3d','\x7b', <del> '\x7d','\x20','\x00','\x01','\x02','\x03','\x04','\x05','\x06','\x07','\x08','\x09','\x0a','\x0b','\x0c','\x0d', <del> '\x0e','\x0f','\x10','\x11','\x12','\x13','\x14','\x15','\x16','\x17','\x18','\x19','\x1a','\x1b','\x1c','\x1d', <del> '\x1e','\x1f','\x7f' <del> ); <del> $r = $this->Socket->tokenEscapeChars(); <del> $this->assertEquals($expected, $r); <del> <del> foreach ($expected as $key => $char) { <del> $expected[$key] = chr(hexdec(substr($char, 2))); <del> } <del> <del> $r = $this->Socket->tokenEscapeChars(false); <del> $this->assertEquals($expected, $r); <del> } <del> <del>/** <del> * Test that HttpSocket::escapeToken is escaping all characters as described in RFC 2616 (HTTP 1.1 specs) <del> * <del> * @return void <del> */ <del> public function testEscapeToken() { <del> $this->Socket->reset(); <del> <del> $this->assertEquals('Foo', $this->Socket->escapeToken('Foo')); <del> <del> $escape = $this->Socket->tokenEscapeChars(false); <del> foreach ($escape as $char) { <del> $token = 'My-special-' . $char . '-Token'; <del> $escapedToken = $this->Socket->escapeToken($token); <del> $expectedToken = 'My-special-"' . $char . '"-Token'; <del> <del> $this->assertEquals($expectedToken, $escapedToken, 'Test token escaping for ASCII ' . ord($char)); <del> } <del> <del> $token = 'Extreme-:Token- -"@-test'; <del> $escapedToken = $this->Socket->escapeToken($token); <del> $expectedToken = 'Extreme-":"Token-" "-""""@"-test'; <del> $this->assertEquals($expectedToken, $escapedToken); <del> } <del> <del>/** <del> * This tests asserts HttpSocket::reset() resets a HttpSocket instance to it's initial state (before Object::__construct <del> * got executed) <del> * <del> * @return void <del> */ <del> public function testReset() { <del> $this->Socket->reset(); <del> <del> $initialState = get_class_vars('Cake\Network\Http\HttpSocket'); <del> foreach ($initialState as $property => $value) { <del> $this->Socket->{$property} = 'Overwritten'; <del> } <del> <del> $return = $this->Socket->reset(); <del> <del> foreach ($initialState as $property => $value) { <del> $this->assertEquals($this->Socket->{$property}, $value); <del> } <del> <del> $this->assertEquals(true, $return); <del> } <del> <del>/** <del> * This tests asserts HttpSocket::reset(false) resets certain HttpSocket properties to their initial state (before <del> * Object::__construct got executed). <del> * <del> * @return void <del> */ <del> public function testPartialReset() { <del> $this->Socket->reset(); <del> <del> $partialResetProperties = array('request', 'response'); <del> $initialState = get_class_vars('Cake\Network\Http\HttpSocket'); <del> <del> foreach ($initialState as $property => $value) { <del> $this->Socket->{$property} = 'Overwritten'; <del> } <del> <del> $return = $this->Socket->reset(false); <del> <del> foreach ($initialState as $property => $originalValue) { <del> if (in_array($property, $partialResetProperties)) { <del> $this->assertEquals($this->Socket->{$property}, $originalValue); <del> } else { <del> $this->assertEquals('Overwritten', $this->Socket->{$property}); <del> } <del> } <del> $this->assertEquals(true, $return); <del> } <del> <del>/** <del> * test configuring the context from the flat keys. <del> * <del> * @return void <del> */ <del> public function testConfigContext() { <del> $this->Socket->reset(); <del> $this->Socket->request('http://example.com'); <del> $this->assertTrue($this->Socket->config['context']['ssl']['verify_peer']); <del> $this->assertEquals(5, $this->Socket->config['context']['ssl']['verify_depth']); <del> $this->assertEquals('example.com', $this->Socket->config['context']['ssl']['CN_match']); <del> $this->assertArrayNotHasKey('ssl_verify_peer', $this->Socket->config); <del> $this->assertArrayNotHasKey('ssl_verify_host', $this->Socket->config); <del> $this->assertArrayNotHasKey('ssl_verify_depth', $this->Socket->config); <del> } <del> <del>/** <del> * Test that requests fail when peer verification fails. <del> * <del> * @return void <del> */ <del> public function testVerifyPeer() { <del> $this->skipIf(!extension_loaded('openssl'), 'OpenSSL is not enabled cannot test SSL.'); <del> $socket = new HttpSocket(); <del> try { <del> $result = $socket->get('https://typography.com'); <del> $this->markTestSkipped('Found valid certificate, was expecting invalid certificate.'); <del> } catch (SocketException $e) { <del> $message = $e->getMessage(); <del> $this->skipIf(strpos($message, 'Invalid HTTP') !== false, 'Invalid HTTP Response received, skipping.'); <del> $this->assertContains('Peer certificate CN', $message); <del> $this->assertContains('Failed to enable crypto', $message); <del> } <del> } <del>}
9
Text
Text
add missing comma in tty
61f3b71d98c291fc80781f68cc98d83d5706fd5f
<ide><path>doc/api/tty.md <ide> const tty = require('tty'); <ide> When Node.js detects that it is being run with a text terminal ("TTY") <ide> attached, [`process.stdin`][] will, by default, be initialized as an instance of <ide> `tty.ReadStream` and both [`process.stdout`][] and [`process.stderr`][] will, by <del>default be instances of `tty.WriteStream`. The preferred method of determining <add>default, be instances of `tty.WriteStream`. The preferred method of determining <ide> whether Node.js is being run within a TTY context is to check that the value of <ide> the `process.stdout.isTTY` property is `true`: <ide>
1
Ruby
Ruby
allow assert `!.*.include?`
3518cda7928d1603af130823854aaa3ed7af4118
<ide><path>Library/Homebrew/cmd/audit.rb <ide> def audit_line(line, lineno) <ide> problem "Use the `#{method}` Ruby method instead of `system #{system}`" <ide> end <ide> <del> if line =~ /assert .*\.include?/ <add> if line =~ /assert [^!]+\.include?/ <ide> problem "Use `assert_match` instead of `assert ...include?`" <ide> end <ide>
1
Text
Text
fix appdelegate.m path
55c5dade579ff003720646facd10509df7b0c031
<ide><path>docs/RunningOnDeviceIOS.md <ide> Note that running on device requires [Apple Developer account](https://developer <ide> <ide> You can iterate quickly on device using development server. To do that, your laptop and your phone have to be on the same wifi network. <ide> <del>1. Open `iOS/AppDelegate.m` <add>1. Open `AwesomeApp/ios/AwesomeApp/AppDelegate.m` <ide> 2. Change the IP in the URL from `localhost` to your laptop's IP <ide> 3. In Xcode select your phone as build target and press "Build and run" <ide> <ide> You can iterate quickly on device using development server. To do that, your lap <ide> <ide> You can also pack all the JavaScript code within the app itself. This way you can test it without development server running and submit the app to the AppStore. <ide> <del>1. Open `iOS/AppDelegate.m` <add>1. Open `AwesomeApp/ios/AwesomeApp/AppDelegate.m` <ide> 2. Follow the instructions for "OPTION 2": <ide> * Uncomment `jsCodeLocation = [[NSBundle mainBundle] ...` <ide> * Run the `react-native bundle` command in terminal from the root directory of your app
1
Python
Python
add docs for rnn implementation modes
a56b16fffec6e4a431bf14e13e7dabeeb5904cd8
<ide><path>keras/layers/recurrent.py <ide> class GRUCell(Layer): <ide> Fraction of the units to drop for <ide> the linear transformation of the recurrent state. <ide> implementation: Implementation mode, either 1 or 2. <add> Mode 1 will structure its operations as a larger number of <add> smaller dot products and additions, whereas mode 2 will <add> batch them into fewer, larger operations. These modes will <add> have different performance profiles on different hardware and <add> for different applications. <ide> """ <ide> <ide> def __init__(self, units, <ide> class GRU(RNN): <ide> Fraction of the units to drop for <ide> the linear transformation of the recurrent state. <ide> implementation: Implementation mode, either 1 or 2. <add> Mode 1 will structure its operations as a larger number of <add> smaller dot products and additions, whereas mode 2 will <add> batch them into fewer, larger operations. These modes will <add> have different performance profiles on different hardware and <add> for different applications. <ide> return_sequences: Boolean. Whether to return the last output. <ide> in the output sequence, or the full sequence. <ide> return_state: Boolean. Whether to return the last state <ide> class LSTMCell(Layer): <ide> Fraction of the units to drop for <ide> the linear transformation of the recurrent state. <ide> implementation: Implementation mode, either 1 or 2. <add> Mode 1 will structure its operations as a larger number of <add> smaller dot products and additions, whereas mode 2 will <add> batch them into fewer, larger operations. These modes will <add> have different performance profiles on different hardware and <add> for different applications. <ide> """ <ide> <ide> def __init__(self, units, <ide> class LSTM(RNN): <ide> Fraction of the units to drop for <ide> the linear transformation of the recurrent state. <ide> implementation: Implementation mode, either 1 or 2. <add> Mode 1 will structure its operations as a larger number of <add> smaller dot products and additions, whereas mode 2 will <add> batch them into fewer, larger operations. These modes will <add> have different performance profiles on different hardware and <add> for different applications. <ide> return_sequences: Boolean. Whether to return the last output. <ide> in the output sequence, or the full sequence. <ide> return_state: Boolean. Whether to return the last state
1
Python
Python
add private ip functionality to gce
718fd951c31f4c29e0f1e356a6cbbf06cdc6a4b6
<ide><path>libcloud/compute/drivers/gce.py <ide> def create_node( <ide> self, name, size, image, location=None, ex_network='default', <ide> ex_subnetwork=None, ex_tags=None, ex_metadata=None, <ide> ex_boot_disk=None, use_existing_disk=True, external_ip='ephemeral', <del> ex_disk_type='pd-standard', ex_disk_auto_delete=True, <del> ex_service_accounts=None, description=None, ex_can_ip_forward=None, <add> internal_ip=None, ex_disk_type='pd-standard', <add> ex_disk_auto_delete=True, ex_service_accounts=None, <add> description=None, ex_can_ip_forward=None, <ide> ex_disks_gce_struct=None, ex_nic_gce_struct=None, <ide> ex_on_host_maintenance=None, ex_automatic_restart=None, <ide> ex_preemptible=None, ex_image_family=None, ex_labels=None): <ide> def create_node( <ide> a GCEAddress object should be passed in. <ide> :type external_ip: :class:`GCEAddress` or ``str`` or ``None`` <ide> <add> :keyword internal_ip: The private IP address to use. <add> :type internal_ip: :class:`GCEAddress` or ``str`` or ``None`` <add> <ide> :keyword ex_disk_type: Specify a pd-standard (default) disk or pd-ssd <ide> for an SSD disk. <ide> :type ex_disk_type: ``str`` or :class:`GCEDiskType` <ide> def create_node( <ide> <ide> request, node_data = self._create_node_req( <ide> name, size, image, location, ex_network, ex_tags, ex_metadata, <del> ex_boot_disk, external_ip, ex_disk_type, ex_disk_auto_delete, <del> ex_service_accounts, description, ex_can_ip_forward, <del> ex_disks_gce_struct, ex_nic_gce_struct, ex_on_host_maintenance, <del> ex_automatic_restart, ex_preemptible, ex_subnetwork, ex_labels) <add> ex_boot_disk, external_ip, internal_ip, ex_disk_type, <add> ex_disk_auto_delete, ex_service_accounts, description, <add> ex_can_ip_forward, ex_disks_gce_struct, ex_nic_gce_struct, <add> ex_on_host_maintenance, ex_automatic_restart, ex_preemptible, <add> ex_subnetwork, ex_labels) <ide> self.connection.async_request(request, method='POST', data=node_data) <ide> return self.ex_get_node(name, location.name) <ide> <ide> def ex_create_instancetemplate( <ide> self, name, size, source=None, image=None, disk_type='pd-standard', <ide> disk_auto_delete=True, network='default', subnetwork=None, <del> can_ip_forward=None, external_ip='ephemeral', <add> can_ip_forward=None, external_ip='ephemeral', internal_ip=None, <ide> service_accounts=None, on_host_maintenance=None, <ide> automatic_restart=None, preemptible=None, tags=None, metadata=None, <ide> description=None, disks_gce_struct=None, nic_gce_struct=None): <ide> def ex_create_instancetemplate( <ide> a GCEAddress object should be passed in. <ide> :type external_ip: :class:`GCEAddress` or ``str`` or ``None`` <ide> <add> :keyword internal_ip: The private IP address to use. <add> :type internal_ip: :class:`GCEAddress` or ``str`` or ``None`` <add> <ide> :keyword disk_type: Specify a pd-standard (default) disk or pd-ssd <ide> for an SSD disk. <ide> :type disk_type: ``str`` or :class:`GCEDiskType` <ide> def ex_create_instancetemplate( <ide> disk_type=disk_type, disk_auto_delete=True, <ide> external_ip=external_ip, network=network, subnetwork=subnetwork, <ide> can_ip_forward=can_ip_forward, service_accounts=service_accounts, <del> on_host_maintenance=on_host_maintenance, <add> on_host_maintenance=on_host_maintenance, internal_ip=internal_ip, <ide> automatic_restart=automatic_restart, preemptible=preemptible, <ide> tags=tags, metadata=metadata, description=description, <ide> disks_gce_struct=disks_gce_struct, nic_gce_struct=nic_gce_struct, <ide> def ex_create_instancetemplate( <ide> def _create_instance_properties( <ide> self, name, node_size, source=None, image=None, <ide> disk_type='pd-standard', disk_auto_delete=True, network='default', <del> subnetwork=None, external_ip='ephemeral', can_ip_forward=None, <del> service_accounts=None, on_host_maintenance=None, <del> automatic_restart=None, preemptible=None, tags=None, metadata=None, <add> subnetwork=None, external_ip='ephemeral', internal_ip=None, <add> can_ip_forward=None, service_accounts=None, <add> on_host_maintenance=None, automatic_restart=None, <add> preemptible=None, tags=None, metadata=None, <ide> description=None, disks_gce_struct=None, nic_gce_struct=None, <ide> use_selflinks=True, labels=None): <ide> """ <ide> def _create_instance_properties( <ide> a GCEAddress object should be passed in. <ide> :type external_ip: :class:`GCEAddress` or ``str`` or ``None`` <ide> <add> :keyword internal_ip: The private IP address to use. <add> :type internal_ip: :class:`GCEAddress` or ``str`` or ``None`` <add> <ide> :keyword can_ip_forward: Set to ``True`` to allow this node to <ide> send/receive non-matching src/dst packets. <ide> :type can_ip_forward: ``bool`` or ``None`` <ide> def _create_instance_properties( <ide> instance_properties['networkInterfaces'] = [ <ide> self._build_network_gce_struct( <ide> network=network, subnetwork=subnetwork, <del> external_ip=external_ip, use_selflinks=True) <add> external_ip=external_ip, use_selflinks=True, <add> internal_ip=internal_ip) <ide> ] <ide> <ide> # build scheduling <ide> def _get_selflink_or_name(self, obj, get_selflinks=True, objname=None): <ide> return obj.name <ide> <ide> def _build_network_gce_struct(self, network, subnetwork=None, <del> external_ip=None, use_selflinks=True): <add> external_ip=None, use_selflinks=True, <add> internal_ip=None): <ide> """ <ide> Build network interface dict for use in the GCE API. <ide> <ide> def _build_network_gce_struct(self, network, subnetwork=None, <ide> a GCEAddress object should be passed in. <ide> :type external_ip: :class:`GCEAddress` <ide> <add> :keyword internal_ip: The private IP address to use. <add> :type internal_ip: :class:`GCEAddress` or ``str`` <add> <ide> :return: network interface dict <ide> :rtype: ``dict`` <ide> """ <ide> def _build_network_gce_struct(self, network, subnetwork=None, <ide> access_configs[0]['natIP'] = external_ip.address <ide> ni['accessConfigs'] = access_configs <ide> <add> if internal_ip: <add> ni['networkIP'] = internal_ip <add> <ide> return ni <ide> <ide> def _build_service_account_gce_struct( <ide> def ex_create_multiple_nodes( <ide> self, base_name, size, image, number, location=None, <ide> ex_network='default', ex_subnetwork=None, ex_tags=None, <ide> ex_metadata=None, ignore_errors=True, use_existing_disk=True, <del> poll_interval=2, external_ip='ephemeral', <add> poll_interval=2, external_ip='ephemeral', internal_ip=None, <ide> ex_disk_type='pd-standard', ex_disk_auto_delete=True, <ide> ex_service_accounts=None, timeout=DEFAULT_TASK_COMPLETION_TIMEOUT, <ide> description=None, ex_can_ip_forward=None, ex_disks_gce_struct=None, <ide> def ex_create_multiple_nodes( <ide> multiple node creation.) <ide> :type external_ip: ``str`` or None <ide> <add> <add> :keyword internal_ip: The private IP address to use. <add> :type internal_ip: :class:`GCEAddress` or ``str`` or ``None`` <add> <ide> :keyword ex_disk_type: Specify a pd-standard (default) disk or pd-ssd <ide> for an SSD disk. <ide> :type ex_disk_type: ``str`` or :class:`GCEDiskType` <ide> def ex_create_multiple_nodes( <ide> 'ignore_errors': ignore_errors, <ide> 'use_existing_disk': use_existing_disk, <ide> 'external_ip': external_ip, <add> 'internal_ip': internal_ip, <ide> 'ex_disk_type': ex_disk_type, <ide> 'ex_disk_auto_delete': ex_disk_auto_delete, <ide> 'ex_service_accounts': ex_service_accounts, <ide> def _set_zone(self, zone): <ide> def _create_node_req( <ide> self, name, size, image, location, network=None, tags=None, <ide> metadata=None, boot_disk=None, external_ip='ephemeral', <del> ex_disk_type='pd-standard', ex_disk_auto_delete=True, <del> ex_service_accounts=None, description=None, ex_can_ip_forward=None, <add> internal_ip=None, ex_disk_type='pd-standard', <add> ex_disk_auto_delete=True, ex_service_accounts=None, <add> description=None, ex_can_ip_forward=None, <ide> ex_disks_gce_struct=None, ex_nic_gce_struct=None, <ide> ex_on_host_maintenance=None, ex_automatic_restart=None, <ide> ex_preemptible=None, ex_subnetwork=None, ex_labels=None): <ide> def _create_node_req( <ide> ex_nic_gce_struct param. <ide> :type external_ip: :class:`GCEAddress` or ``str`` or None <ide> <add> :keyword internal_ip: The private IP address to use. <add> :type internal_ip: :class:`GCEAddress` or ``str`` or ``None`` <add> <ide> :keyword ex_disk_type: Specify a pd-standard (default) disk or pd-ssd <ide> for an SSD disk. <ide> :type ex_disk_type: ``str`` or :class:`GCEDiskType` or ``None`` <ide> def _create_node_req( <ide> name, node_size=size, image=image, source=source, <ide> disk_type=ex_disk_type, disk_auto_delete=ex_disk_auto_delete, <ide> external_ip=external_ip, network=network, subnetwork=ex_subnetwork, <del> can_ip_forward=ex_can_ip_forward, <add> can_ip_forward=ex_can_ip_forward, internal_ip=internal_ip, <ide> service_accounts=ex_service_accounts, <ide> on_host_maintenance=ex_on_host_maintenance, <ide> automatic_restart=ex_automatic_restart, preemptible=ex_preemptible, <ide> def _multi_create_node(self, status, node_attrs): <ide> status['name'], node_attrs['size'], node_attrs['image'], <ide> node_attrs['location'], node_attrs['network'], node_attrs['tags'], <ide> node_attrs['metadata'], external_ip=node_attrs['external_ip'], <add> internal_ip=node_attrs['internal_ip'], <ide> ex_service_accounts=node_attrs['ex_service_accounts'], <ide> description=node_attrs['description'], <ide> ex_can_ip_forward=node_attrs['ex_can_ip_forward'],
1
Ruby
Ruby
pull template keys up
7e872091e104be09deb8b39ec73ab4792a44d4e9
<ide><path>actionview/lib/action_view/renderer/partial_renderer.rb <ide> def render(context, options, block) <ide> setup(context, options, as, block) <ide> <ide> if @path <add> @variable = nil <add> @variable_counter = nil <add> @variable_iteration = nil <add> @template_keys = @locals.keys <add> <ide> if @has_object || @collection <ide> @variable, @variable_counter, @variable_iteration = retrieve_variable(@path, as) <del> @template_keys = retrieve_template_keys(@variable) <del> else <del> @template_keys = @locals.keys <add> @template_keys << @variable <add> <add> if @collection <add> @template_keys << @variable_counter <add> @template_keys << @variable_iteration <add> end <ide> end <add> <ide> template = find_template(@path, @template_keys) <ide> @variable ||= template.variable <ide> else <ide> def merge_prefix_into_object_path(prefix, object_path) <ide> end <ide> end <ide> <del> def retrieve_template_keys(variable) <del> keys = @locals.keys <del> keys << variable <del> if @collection <del> keys << @variable_counter <del> keys << @variable_iteration <del> end <del> keys <del> end <del> <ide> def retrieve_variable(path, as) <ide> variable = as || begin <ide> base = path[-1] == "/" ? "" : File.basename(path)
1
Go
Go
fix string in docker images
bc086a9cd61b2d15fbef9db3cb53c7f3650fda48
<ide><path>server.go <ide> func (srv *Server) Containers(job *engine.Job) engine.Status { <ide> out.Set("Id", container.ID) <ide> out.SetList("Names", names[container.ID]) <ide> out.Set("Image", srv.runtime.repositories.ImageName(container.Image)) <del> out.Set("Command", fmt.Sprintf("%s %s", container.Path, strings.Join(container.Args, " "))) <add> if len(container.Args) > 0 { <add> out.Set("Command", fmt.Sprintf("\"%s %s\"", container.Path, strings.Join(container.Args, " "))) <add> } else { <add> out.Set("Command", fmt.Sprintf("\"%s\"", container.Path)) <add> } <ide> out.SetInt64("Created", container.Created.Unix()) <ide> out.Set("Status", container.State.String()) <ide> str, err := container.NetworkSettings.PortMappingAPI().ToListString()
1
Javascript
Javascript
add test for forward nav after reload
792f2f8ce3486ade7992479f1baa76991dcf739e
<ide><path>test/integration/client-navigation/test/index.test.js <ide> describe('Client Navigation', () => { <ide> const browser = await webdriver(context.appPort, '/nav') <ide> await browser.elementByCss('#about-link').click() <ide> await browser.waitForElementByCss('.nav-about') <del> await browser.eval(`window.location.href = window.location.href`) <del> await waitFor(5000) <del> await browser.eval(`window.history.back()`) <add> await browser.refresh() <add> await waitFor(3000) <add> await browser.back() <ide> await waitFor(3000) <ide> const text = await browser.elementsByCss('#about-link').text() <add> if (browser) await browser.close() <ide> expect(text).toMatch(/About/) <ide> }) <ide> <add> it('should navigate forwards after reload', async () => { <add> const browser = await webdriver(context.appPort, '/nav') <add> await browser.elementByCss('#about-link').click() <add> await browser.waitForElementByCss('.nav-about') <add> await browser.back() <add> await browser.refresh() <add> await waitFor(3000) <add> await browser.forward() <add> await waitFor(3000) <add> const text = await browser.elementsByCss('p').text() <add> if (browser) await browser.close() <add> expect(text).toMatch(/this is the about page/i) <add> }) <add> <ide> it('should navigate via the client side', async () => { <ide> const browser = await webdriver(context.appPort, '/nav') <ide>
1
Python
Python
fix typos in optional tests
6f1691b42d1df02c5657f700fe7b13e4ebde5332
<ide><path>t/unit/app/test_schedules.py <ide> def patch_crontab_nowfun(cls, retval): <ide> class test_solar: <ide> <ide> def setup(self): <del> pytest.importorskip('ephem0') <add> pytest.importorskip('ephem') <ide> self.s = solar('sunrise', 60, 30, app=self.app) <ide> <ide> def test_reduce(self): <ide><path>t/unit/backends/test_cache.py <ide> def test_as_uri_multiple_servers(self): <ide> assert b.as_uri() == backend <ide> <ide> def test_regression_worker_startup_info(self): <del> pytest.importorskip('memcached') <add> pytest.importorskip('memcache') <ide> self.app.conf.result_backend = ( <ide> 'cache+memcached://127.0.0.1:11211;127.0.0.2:11211;127.0.0.3/' <ide> )
2
Ruby
Ruby
fix pkg_version comparison on merge
38ebaac869bacedd89aa885b0dadafa59874774d
<ide><path>Library/Homebrew/dev-cmd/bottle.rb <ide> def merge(args:) <ide> <ide> path = HOMEBREW_REPOSITORY/bottle_hash["formula"]["path"] <ide> formula = Formulary.factory(path) <add> <ide> old_bottle_spec = formula.bottle_specification <add> old_pkg_version = formula.pkg_version <add> FormulaVersions.new(formula).formula_at_revision("origin/HEAD") do |upstream_f| <add> old_pkg_version = upstream_f.pkg_version <add> end <add> <ide> old_bottle_spec_matches = old_bottle_spec && <del> bottle_hash["formula"]["pkg_version"] == formula.pkg_version.to_s && <add> bottle_hash["formula"]["pkg_version"] == old_pkg_version.to_s && <ide> bottle.root_url == old_bottle_spec.root_url && <ide> old_bottle_spec.collector.tags.present? <ide>
1
Python
Python
add a little todo about the id in create_node
d4c6eba13db7289f77e1ff9cea9b3276b64d2ea7
<ide><path>libcloud/drivers/dreamhost.py <ide> def create_node(self, **kwargs): <ide> 'size' : size <ide> } <ide> data = self.connection.request('/', params).object <add> # TODO: Is this ID the same as what list_nodes returns? <ide> return Node( <ide> id = data['added_' + kwargs['image'].name], <ide> name = data['added_' + kwargs['image'].name],
1
Python
Python
add test for span.sent when doc not parsed
5d24a81c0bd951b949f7a561bc8f20f46f284a67
<ide><path>spacy/tests/doc/test_span.py <ide> def doc(en_tokenizer): <ide> return get_doc(tokens.vocab, [t.text for t in tokens], heads=heads, deps=deps) <ide> <ide> <add>@pytest.fixture <add>def doc_not_parsed(en_tokenizer): <add> text = "This is a sentence. This is another sentence. And a third." <add> tokens = en_tokenizer(text) <add> d = get_doc(tokens.vocab, [t.text for t in tokens]) <add> d.is_parsed = False <add> return d <add> <add> <ide> def test_spans_sent_spans(doc): <ide> sents = list(doc.sents) <ide> assert sents[0].start == 0 <ide> def test_spans_root(doc): <ide> assert span.root.text == 'sentence' <ide> assert span.root.head.text == 'is' <ide> <add> <ide> def test_spans_string_fn(doc): <ide> span = doc[0:4] <ide> assert len(span) == 4 <ide> assert span.text == 'This is a sentence' <ide> assert span.upper_ == 'THIS IS A SENTENCE' <ide> assert span.lower_ == 'this is a sentence' <ide> <add> <ide> def test_spans_root2(en_tokenizer): <ide> text = "through North and South Carolina" <ide> heads = [0, 3, -1, -2, -4] <ide> def test_spans_root2(en_tokenizer): <ide> assert doc[-2:].root.text == 'Carolina' <ide> <ide> <del>def test_spans_span_sent(doc): <add>def test_spans_span_sent(doc, doc_not_parsed): <ide> """Test span.sent property""" <ide> assert len(list(doc.sents)) <ide> assert doc[:2].sent.root.text == 'is' <ide> assert doc[:2].sent.text == 'This is a sentence .' <ide> assert doc[6:7].sent.root.left_edge.text == 'This' <add> # test on manual sbd <add> doc_not_parsed[0].is_sent_start = True <add> doc_not_parsed[5].is_sent_start = True <add> assert doc_not_parsed[1:3].sent == doc_not_parsed[0:5] <add> assert doc_not_parsed[10:14].sent == doc_not_parsed[5:] <ide> <ide> <ide> def test_spans_lca_matrix(en_tokenizer):
1
Javascript
Javascript
add spec to validate updating an existing env var
3c7a89ec933b3ff8d6f464c4c09a4d6d59464f28
<ide><path>spec/update-process-env-spec.js <ide> describe('updateProcessEnv(launchEnv)', function () { <ide> ATOM_HOME: '/the/atom/home' <ide> } <ide> <del> updateProcessEnv({ATOM_SUPPRESS_ENV_PATCHING: 'true', PWD: '/the/dir'}) <add> updateProcessEnv({ATOM_SUPPRESS_ENV_PATCHING: 'true', PWD: '/the/dir', NODE_ENV: 'the-node-env', NODE_PATH: '/the/node/path', ATOM_HOME: '/the/atom/home'}) <ide> expect(process.env).toEqual({ <del> PWD: '/the/dir', <ide> ATOM_SUPPRESS_ENV_PATCHING: 'true', <add> PWD: '/the/dir', <ide> NODE_ENV: 'the-node-env', <ide> NODE_PATH: '/the/node/path', <ide> ATOM_HOME: '/the/atom/home' <ide> }) <ide> <del> updateProcessEnv({PWD: '/the/dir'}) <add> updateProcessEnv({PWD: '/the/dir', NODE_ENV: 'the-node-env', NODE_PATH: '/the/node/path', ATOM_HOME: '/the/atom/home'}) <ide> expect(process.env).toEqual({ <ide> ATOM_SUPPRESS_ENV_PATCHING: 'true', <ide> PWD: '/the/dir', <ide> describe('updateProcessEnv(launchEnv)', function () { <ide> ATOM_HOME: '/the/atom/home' <ide> }) <ide> }) <add> <add> it('allows an existing env variable to be updated', function () { <add> process.env = { <add> WILL_BE_UPDATED: 'old-value', <add> NODE_ENV: 'the-node-env', <add> NODE_PATH: '/the/node/path', <add> ATOM_HOME: '/the/atom/home' <add> } <add> <add> updateProcessEnv(process.env) <add> expect(process.env).toEqual(process.env) <add> <add> let updatedEnv = { <add> ATOM_SUPPRESS_ENV_PATCHING: 'true', <add> WILL_BE_UPDATED: 'new-value', <add> NODE_ENV: 'the-node-env', <add> NODE_PATH: '/the/node/path', <add> ATOM_HOME: '/the/atom/home', <add> PWD: '/the/dir' <add> } <add> <add> updateProcessEnv(updatedEnv) <add> expect(process.env).toEqual(updatedEnv) <add> }) <ide> }) <ide> <ide> describe('when the launch environment does not come from a shell', function () { <ide> describe('updateProcessEnv(launchEnv)', function () { <ide> expect(shouldGetEnvFromShell({SHELL: '/usr/local/bin/fish'})).toBe(true) <ide> }) <ide> <del> it('returns false when the shell should not be patched', function () { <add> it('returns false when the environment indicates that Atom was launched from a shell', function () { <ide> process.platform = 'darwin' <ide> expect(shouldGetEnvFromShell({ATOM_SUPPRESS_ENV_PATCHING: 'true', SHELL: '/bin/sh'})).toBe(false) <ide> process.platform = 'linux'
1
Python
Python
improve experiment management
116ae46802371b41d0c715e44e411f31a45344aa
<ide><path>fabfile.py <ide> from fabric.api import local, lcd, env, settings, prefix <ide> from os import path, environ <ide> import shutil <add>import sys <ide> <ide> <ide> PWD = path.dirname(__file__) <ide> def train(): <ide> args = environ.get('SPACY_TRAIN_ARGS', '') <ide> with virtualenv(VENV_DIR) as venv_local: <ide> venv_local('spacy train {args}'.format(args=args)) <add> <add> <add>def conll17(treebank_dir, experiment_dir, vectors_dir, config, corpus=''): <add> is_not_clean = local('git status --porcelain', capture=True) <add> if is_not_clean: <add> print("Repository is not clean") <add> print(is_not_clean) <add> sys.exit(1) <add> git_sha = local('git rev-parse --short HEAD', capture=True) <add> config_checksum = local('sha256sum {config}'.format(config=config), capture=True) <add> experiment_dir = Path(experiment_dir) / '{}--{}'.format(config_checksum[:6], git_sha) <add> if not experiment_dir.exists(): <add> experiment_dir.mkdir() <add> test_data_dir = Path(treebank_dir) / 'ud-test-v2.0-conll2017' <add> assert test_data_dir.exists() <add> assert test_data_dir.is_dir() <add> if corpus: <add> corpora = [corpus] <add> else: <add> corpora = ['UD_English', 'UD_Chinese', 'UD_Japanese', 'UD_Vietnamese'] <add> <add> local('cp {config} {experiment_dir}/config.json'.format(config=config, experiment_dir=experiment_dir)) <add> with virtualenv(VENV_DIR) as venv_local: <add> for corpus in corpora: <add> venv_local('spacy ud-train {treebank_dir} {vectors_dir} {experiment_dir} {config} {corpus}'.format( <add> treebank_dir=treebank_dir, experiment_dir=experiment_dir, config=config, corpus=corpus)) <add> venv_local('spacy ud-run-test {test_data_dir} {experiment_dir} {corpus}'.format( <add> test_data_dir=test_data_dir, experiment_dir=experiment_dir, config=config, corpus=corpus))
1
Python
Python
fix docs for hp cloud
164d86c6dfe2f46366e991ac45d06841be760fd6
<ide><path>docs/examples/compute/openstack/hpcloud.py <ide> from libcloud.compute.types import Provider <ide> from libcloud.compute.providers import get_driver <ide> <del>HPCLOUD_AUTH_URL = 'https://region-a.geo-1.identity.hpcloudsvc.com:35357/v2.0/' <add>HPCLOUD_AUTH_URL = 'https://region-a.geo-1.identity.hpcloudsvc.com:35357' <ide> OpenStack = get_driver(Provider.OPENSTACK) <ide> <ide> #HP Cloud US West AZ 1
1
PHP
PHP
add container methods to baseapplication
44da86b33d43f31a537b27e30056a3d063764774
<ide><path>src/Error/ExceptionRenderer.php <ide> use Cake\Controller\ControllerFactory; <ide> use Cake\Core\App; <ide> use Cake\Core\Configure; <add>use Cake\Core\Container; <ide> use Cake\Core\Exception\Exception as CakeException; <ide> use Cake\Core\Exception\MissingPluginException; <ide> use Cake\Event\Event; <ide> protected function _getController(): Controller <ide> $params = $request->getAttribute('params'); <ide> $params['controller'] = 'Error'; <ide> <del> $factory = new ControllerFactory(); <add> $factory = new ControllerFactory(new Container()); <ide> $class = $factory->getControllerClass($request->withAttribute('params', $params)); <ide> <ide> if (!$class) { <ide><path>src/Http/BaseApplication.php <ide> use Cake\Console\CommandCollection; <ide> use Cake\Controller\ControllerFactory; <ide> use Cake\Core\ConsoleApplicationInterface; <add>use Cake\Core\Container; <add>use Cake\Core\ContainerInterface; <add>use Cake\Core\ContainerApplicationInterface; <ide> use Cake\Core\Exception\MissingPluginException; <ide> use Cake\Core\HttpApplicationInterface; <ide> use Cake\Core\Plugin; <ide> */ <ide> abstract class BaseApplication implements <ide> ConsoleApplicationInterface, <add> ContainerApplicationInterface, <ide> HttpApplicationInterface, <ide> PluginApplicationInterface, <ide> RoutingApplicationInterface <ide> abstract class BaseApplication implements <ide> */ <ide> protected $controllerFactory; <ide> <add> /** <add> * Container <add> * <add> * @var \Cake\Core\ContainerInterface|null <add> */ <add> protected $container; <add> <ide> /** <ide> * Constructor <ide> * <ide> public function pluginConsole(CommandCollection $commands): CommandCollection <ide> return $commands; <ide> } <ide> <add> /** <add> * Get the dependency injection container for the application. <add> * <add> * The first time the container is fetched it will be constructed <add> * and stored for future calls. <add> * <add> * @return \Cake\Core\ContainerInterface <add> */ <add> public function getContainer(): ContainerInterface <add> { <add> if ($this->container) { <add> return $this->container; <add> } <add> $container = $this->register(new Container()); <add> foreach ($this->plugins->with('register') as $plugin) { <add> $container = $plugin->register($container); <add> } <add> $this->container = $container; <add> <add> return $this->container; <add> } <add> <add> /** <add> * Register application services. <add> * <add> * @param \Cake\Core\ContainerInterface $container The Container to update. <add> * @return \Cake\Core\ContainerInterface The updated container <add> */ <add> public function register(ContainerInterface $container): ContainerInterface <add> { <add> return $container; <add> } <add> <ide> /** <ide> * Invoke the application. <ide> * <ide> public function handle( <ide> ServerRequestInterface $request <ide> ): ResponseInterface { <ide> if ($this->controllerFactory === null) { <del> $this->controllerFactory = new ControllerFactory(); <add> $this->controllerFactory = new ControllerFactory($this->getContainer()); <ide> } <ide> <ide> if (Router::getRequest() !== $request) { <ide><path>tests/TestCase/Http/BaseApplicationTest.php <ide> <ide> use Cake\Core\BasePlugin; <ide> use Cake\Core\Configure; <add>use Cake\Core\ContainerInterface; <ide> use Cake\Http\BaseApplication; <ide> use Cake\Http\MiddlewareQueue; <ide> use Cake\Http\ServerRequestFactory; <ide> public function testAddOptionalPluginLoadingNonExistingPluginValid() <ide> $this->assertCount(1, $app->getPlugins()); <ide> $this->assertTrue($app->getPlugins()->has('TestPlugin')); <ide> } <add> <add> public function testGetContainer() <add> { <add> $app = $this->getMockForAbstractClass(BaseApplication::class, [$this->path]); <add> $container = $app->getContainer(); <add> <add> $this->assertInstanceOf(ContainerInterface::class, $container); <add> $this->assertSame($container, $app->getContainer(), 'Should return a reference'); <add> } <ide> } <ide><path>tests/TestCase/TestSuite/IntegrationTestTraitTest.php <ide> public function testExceptionsInMiddlewareJsonView() <ide> <ide> $this->configApplication(Configure::read('App.namespace') . '\ApplicationWithExceptionsInMiddleware', null); <ide> <del> $this->_request['headers'] = [ 'Accept' => 'application/json' ]; <add> $this->_request['headers'] = ['Accept' => 'application/json']; <ide> $this->get('/json_response/api_get_data'); <ide> $this->assertResponseCode(403); <ide> $this->assertHeader('Content-Type', 'application/json'); <ide> public function testViewVariableNotFoundShouldReturnNull() <ide> $this->_controller = new Controller(); <ide> $this->assertNull($this->viewVariable('notFound')); <ide> } <add> <add> /** <add> * Integration test for a controller with action dependencies. <add> * <add> * @return void <add> */ <add> public function testHandleWithContainerDependencies() <add> { <add> $this->get('/dependencies/'); <add> $this->assertResponseContains('"key":"value"', 'Contains the data from the stdClass container object.'); <add> } <ide> } <ide><path>tests/test_app/TestApp/Application.php <ide> <ide> use Cake\Console\CommandCollection; <ide> use Cake\Core\Configure; <add>use Cake\Core\ContainerInterface; <ide> use Cake\Error\Middleware\ErrorHandlerMiddleware; <ide> use Cake\Http\BaseApplication; <ide> use Cake\Http\MiddlewareQueue; <ide> use Cake\Routing\Middleware\RoutingMiddleware; <ide> use Cake\Routing\RouteBuilder; <add>use stdClass; <ide> use TestApp\Command\AbortCommand; <ide> <ide> class Application extends BaseApplication <ide> public function routes(RouteBuilder $routes): void <ide> $routes->connect('/posts', ['controller' => 'Posts', 'action' => 'index']); <ide> $routes->connect('/bake/:controller/:action', ['plugin' => 'Bake']); <ide> } <add> <add> /** <add> * Container register hook <add> * <add> * @param \Cake\Core\ContainerInterface $container The container to update <add> * @return \Cake\Core\ContainerInterface <add> */ <add> public function register(ContainerInterface $container): ContainerInterface <add> { <add> $container->add(stdClass::class, json_decode('{"key":"value"}')); <add> <add> return $container; <add> } <ide> } <ide><path>tests/test_app/TestApp/Controller/DependenciesController.php <add><?php <add>declare(strict_types=1); <add> <add>namespace TestApp\Controller; <add> <add>use Cake\Controller\Controller; <add>use Cake\Controller\ComponentRegistry; <add>use Cake\Event\EventManagerInterface; <add>use Cake\Http\ServerRequest; <add>use Cake\Http\Response; <add>use stdClass; <add> <add>/** <add> * DependenciesController class <add> */ <add>class DependenciesController extends Controller <add>{ <add> public function __construct( <add> ?ServerRequest $request = null, <add> ?Response $response = null, <add> ?string $name = null, <add> ?EventManagerInterface $eventManager = null, <add> ?ComponentRegistry $components = null, <add> stdClass $inject = null <add> ) { <add> parent::__construct($request, $response, $name, $eventManager, $components); <add> $this->inject = $inject; <add> } <add> <add> public function index($one = null, ?string $two = null, stdClass $three = null) <add> { <add> return $this->response->withStringBody(json_encode(compact('one', 'two', 'three'))); <add> } <add>}
6