repo
stringlengths
8
50
commit
stringlengths
40
40
path
stringlengths
5
171
lang
stringclasses
5 values
license
stringclasses
13 values
message
stringlengths
21
1.33k
old_code
stringlengths
15
2.4k
new_code
stringlengths
140
2.61k
n_added
int64
0
81
n_removed
int64
0
58
n_hunks
int64
1
8
change_kind
stringclasses
3 values
udiff
stringlengths
88
3.33k
udiff-h
stringlengths
85
3.32k
udiff-l
stringlengths
95
3.57k
search-replace
stringlengths
89
3.36k
RocketChat/Rocket.Chat.Android.Lily
a9e41de1f8c765d44d6f38eed561a591e6a00cc9
app/src/main/java/chat/rocket/android/util/extensions/Animation.kt
kotlin
mit
Add function fadeIn and fadeOut (instead of having fadeInOrOut(...))
package chat.rocket.android.util.extensions import android.view.View import android.view.ViewAnimationUtils import android.view.animation.AccelerateInterpolator import android.view.animation.DecelerateInterpolator fun View.rotateBy(value: Float, duration: Long = 200) { animate() .rotationBy(value) .setDuration(duration) .start() } fun View.fadeInOrOut(startValue: Float, finishValue: Float, duration: Long = 200) { animate() .alpha(startValue) .setDuration(duration) .setInterpolator(DecelerateInterpolator()) .withEndAction({ animate() .alpha(finishValue) .setDuration(duration) .setInterpolator(AccelerateInterpolator()).start() }).start() if (startValue > finishValue) { setVisible(false) } else { setVisible(true) } } fun View.circularRevealOrUnreveal(centerX: Int, centerY: Int, startRadius: Float, endRadius: Float, duration: Long = 600) { val anim = ViewAnimationUtils.createCircularReveal(this, centerX, centerY, startRadius, endRadius) anim.duration = duration if (startRadius < endRadius) { setVisible(true) } else { setVisible(false) } anim.start() }
package chat.rocket.android.util.extensions import android.view.View import android.view.ViewAnimationUtils import android.view.animation.AccelerateInterpolator import android.view.animation.DecelerateInterpolator fun View.rotateBy(value: Float, duration: Long = 200) { animate() .rotationBy(value) .setDuration(duration) .start() } fun View.fadeIn(startValue: Float, finishValue: Float, duration: Long = 200) { animate() .alpha(startValue) .setDuration(duration) .setInterpolator(DecelerateInterpolator()) .withEndAction({ animate() .alpha(finishValue) .setDuration(duration) .setInterpolator(AccelerateInterpolator()).start() }).start() setVisible(true) } fun View.fadeOut(startValue: Float, finishValue: Float, duration: Long = 200) { animate() .alpha(startValue) .setDuration(duration) .setInterpolator(DecelerateInterpolator()) .withEndAction({ animate() .alpha(finishValue) .setDuration(duration) .setInterpolator(AccelerateInterpolator()).start() }).start() setVisible(false) } fun View.circularRevealOrUnreveal(centerX: Int, centerY: Int, startRadius: Float, endRadius: Float, duration: Long = 600) { val anim = ViewAnimationUtils.createCircularReveal(this, centerX, centerY, startRadius, endRadius) anim.duration = duration if (startRadius < endRadius) { setVisible(true) } else { setVisible(false) } anim.start() }
17
6
2
mixed
--- a/app/src/main/java/chat/rocket/android/util/extensions/Animation.kt +++ b/app/src/main/java/chat/rocket/android/util/extensions/Animation.kt @@ -14,3 +14,3 @@ -fun View.fadeInOrOut(startValue: Float, finishValue: Float, duration: Long = 200) { +fun View.fadeIn(startValue: Float, finishValue: Float, duration: Long = 200) { animate() @@ -26,7 +26,18 @@ - if (startValue > finishValue) { - setVisible(false) - } else { - setVisible(true) - } + setVisible(true) +} + +fun View.fadeOut(startValue: Float, finishValue: Float, duration: Long = 200) { + animate() + .alpha(startValue) + .setDuration(duration) + .setInterpolator(DecelerateInterpolator()) + .withEndAction({ + animate() + .alpha(finishValue) + .setDuration(duration) + .setInterpolator(AccelerateInterpolator()).start() + }).start() + + setVisible(false) }
--- a/app/src/main/java/chat/rocket/android/util/extensions/Animation.kt +++ b/app/src/main/java/chat/rocket/android/util/extensions/Animation.kt @@ ... @@ -fun View.fadeInOrOut(startValue: Float, finishValue: Float, duration: Long = 200) { +fun View.fadeIn(startValue: Float, finishValue: Float, duration: Long = 200) { animate() @@ ... @@ - if (startValue > finishValue) { - setVisible(false) - } else { - setVisible(true) - } + setVisible(true) +} + +fun View.fadeOut(startValue: Float, finishValue: Float, duration: Long = 200) { + animate() + .alpha(startValue) + .setDuration(duration) + .setInterpolator(DecelerateInterpolator()) + .withEndAction({ + animate() + .alpha(finishValue) + .setDuration(duration) + .setInterpolator(AccelerateInterpolator()).start() + }).start() + + setVisible(false) }
--- a/app/src/main/java/chat/rocket/android/util/extensions/Animation.kt +++ b/app/src/main/java/chat/rocket/android/util/extensions/Animation.kt @@ -14,3 +14,3 @@ CON DEL fun View.fadeInOrOut(startValue: Float, finishValue: Float, duration: Long = 200) { ADD fun View.fadeIn(startValue: Float, finishValue: Float, duration: Long = 200) { CON animate() @@ -26,7 +26,18 @@ CON DEL if (startValue > finishValue) { DEL setVisible(false) DEL } else { DEL setVisible(true) DEL } ADD setVisible(true) ADD } ADD ADD fun View.fadeOut(startValue: Float, finishValue: Float, duration: Long = 200) { ADD animate() ADD .alpha(startValue) ADD .setDuration(duration) ADD .setInterpolator(DecelerateInterpolator()) ADD .withEndAction({ ADD animate() ADD .alpha(finishValue) ADD .setDuration(duration) ADD .setInterpolator(AccelerateInterpolator()).start() ADD }).start() ADD ADD setVisible(false) CON }
<<<<<<< SEARCH } fun View.fadeInOrOut(startValue: Float, finishValue: Float, duration: Long = 200) { animate() .alpha(startValue) ======= } fun View.fadeIn(startValue: Float, finishValue: Float, duration: Long = 200) { animate() .alpha(startValue) >>>>>>> REPLACE <<<<<<< SEARCH }).start() if (startValue > finishValue) { setVisible(false) } else { setVisible(true) } } ======= }).start() setVisible(true) } fun View.fadeOut(startValue: Float, finishValue: Float, duration: Long = 200) { animate() .alpha(startValue) .setDuration(duration) .setInterpolator(DecelerateInterpolator()) .withEndAction({ animate() .alpha(finishValue) .setDuration(duration) .setInterpolator(AccelerateInterpolator()).start() }).start() setVisible(false) } >>>>>>> REPLACE
epeli/lean-redux
0c4be9373f7a6edb32fc245d00a3f65b13a7bf64
examples/DynamicCounters.js
javascript
mit
Remove counter data when it's removed
import React from "react"; import {connectLean} from "../src/lean"; import {range} from "lodash/fp"; import Counter from "./Counter"; var DynamicCounters = ({counterCount, scope, addCounter, removeCounter}) => ( <div> <button onClick={addCounter} >add counter</button> <button onClick={removeCounter} >remove counter</button> {range(0, counterCount).map(i => <Counter key={i} scope={[scope, "counters", i]} />)} </div> ); DynamicCounters = connectLean({ scope: "dynamicCounters", defaultProps: { counterCount: 1, }, handlers: { addCounter(e) { e.preventDefault(); // Instead of accessing the props from the arguments you can also // return a object of functions to get the previus value in the // key. return {counterCount: i => i + 1}; }, removeCounter(e) { e.preventDefault(); return {counterCount: i => Math.max(i - 1, 0)}; }, }, })(DynamicCounters); export default DynamicCounters;
import React from "react"; import {connectLean} from "../src/lean"; import {range} from "lodash/fp"; import Counter from "./Counter"; var DynamicCounters = ({counterCount, scope, addCounter, removeCounter}) => ( <div> <button onClick={addCounter} >add counter</button> <button onClick={removeCounter} >remove counter</button> {range(0, counterCount).map(i => <Counter key={i} scope={[scope, "counters", i]} />)} </div> ); DynamicCounters = connectLean({ scope: "dynamicCounters", defaultProps: { counterCount: 1, }, handlers: { addCounter(e) { e.preventDefault(); // Instead of accessing the props from the arguments you can also // return a object of functions to get the previus value in the // key. return {counterCount: i => i + 1}; }, removeCounter(e) { e.preventDefault(); return { counterCount: i => Math.max(i - 1, 0), counters: a => a.slice(0, -1), // Remove last from the counters array }; }, }, })(DynamicCounters); export default DynamicCounters;
4
1
1
mixed
--- a/examples/DynamicCounters.js +++ b/examples/DynamicCounters.js @@ -29,3 +29,6 @@ e.preventDefault(); - return {counterCount: i => Math.max(i - 1, 0)}; + return { + counterCount: i => Math.max(i - 1, 0), + counters: a => a.slice(0, -1), // Remove last from the counters array + }; },
--- a/examples/DynamicCounters.js +++ b/examples/DynamicCounters.js @@ ... @@ e.preventDefault(); - return {counterCount: i => Math.max(i - 1, 0)}; + return { + counterCount: i => Math.max(i - 1, 0), + counters: a => a.slice(0, -1), // Remove last from the counters array + }; },
--- a/examples/DynamicCounters.js +++ b/examples/DynamicCounters.js @@ -29,3 +29,6 @@ CON e.preventDefault(); DEL return {counterCount: i => Math.max(i - 1, 0)}; ADD return { ADD counterCount: i => Math.max(i - 1, 0), ADD counters: a => a.slice(0, -1), // Remove last from the counters array ADD }; CON },
<<<<<<< SEARCH removeCounter(e) { e.preventDefault(); return {counterCount: i => Math.max(i - 1, 0)}; }, }, ======= removeCounter(e) { e.preventDefault(); return { counterCount: i => Math.max(i - 1, 0), counters: a => a.slice(0, -1), // Remove last from the counters array }; }, }, >>>>>>> REPLACE
elpassion/mainframer-intellij-plugin
95e996ce27ba9c5f2ebf567fa0227ab67e658d48
src/test/kotlin/com/elpassion/intelijidea/common/MFCommandLineTest.kt
kotlin
apache-2.0
[Refactoring] Add command line factory for test purpose
package com.elpassion.intelijidea.common import com.elpassion.intelijidea.util.mfFilename import org.junit.Assert.assertEquals import org.junit.Test class MFCommandLineTest { @Test fun shouldGenerateCommandLineToExecute() { val commandLine = MFCommandLine( buildCommand = "./gradlew", taskName = "build") commandLine.verify() } @Test fun shouldGenerateProperCommandLineToExecute() { val commandLine = MFCommandLine( buildCommand = "gradle", taskName = "assembleDebug") commandLine.verify() } @Test fun shouldGenerateProperCommandLineWithCustomPathToExecute() { val commandLine = MFCommandLine( mfPath = "/customPath", buildCommand = "gradle", taskName = "build") commandLine.verify() } @Test fun shouldGenerateProperCommandLineWithWhiteSpacePathToExecute() { val commandLine = MFCommandLine( mfPath = "/White Spaced Path", buildCommand = "gradle", taskName = "build") commandLine.verify() } private fun MFCommandLine.verify() { val expectedParams = listOf( "${if (mfPath != null) "$mfPath/" else ""}$mfFilename", "$buildCommand $taskName" ).map { if (it.contains(" ")) "\"$it\"" else it } assertEquals("bash ${expectedParams.joinToString(separator = " ")}", commandLineString) } }
package com.elpassion.intelijidea.common import com.elpassion.intelijidea.util.mfFilename import org.junit.Assert.assertEquals import org.junit.Test class MFCommandLineTest { @Test fun shouldGenerateCommandLineToExecute() { val commandLine = createCommandLine() commandLine.verify() } @Test fun shouldGenerateProperCommandLineToExecute() { val commandLine = createCommandLine(buildCommand = "gradle", taskName = "assembleDebug") commandLine.verify() } @Test fun shouldGenerateProperCommandLineWithCustomPathToExecute() { val commandLine = createCommandLine(mfPath = "/customPath") commandLine.verify() } @Test fun shouldGenerateProperCommandLineWithWhiteSpacePathToExecute() { val commandLine = createCommandLine(mfPath = "/White Spaced Path") commandLine.verify() } private fun MFCommandLine.verify() { val expectedParams = listOf( "${if (mfPath != null) "$mfPath/" else ""}$mfFilename", "$buildCommand $taskName" ).map { if (it.contains(" ")) "\"$it\"" else it } assertEquals("bash ${expectedParams.joinToString(separator = " ")}", commandLineString) } private fun createCommandLine(mfPath: String = "", buildCommand: String = "./gradlew", taskName: String = "build") = MFCommandLine(mfPath, buildCommand, taskName) }
7
14
5
mixed
--- a/src/test/kotlin/com/elpassion/intelijidea/common/MFCommandLineTest.kt +++ b/src/test/kotlin/com/elpassion/intelijidea/common/MFCommandLineTest.kt @@ -10,5 +10,3 @@ fun shouldGenerateCommandLineToExecute() { - val commandLine = MFCommandLine( - buildCommand = "./gradlew", - taskName = "build") + val commandLine = createCommandLine() commandLine.verify() @@ -18,5 +16,3 @@ fun shouldGenerateProperCommandLineToExecute() { - val commandLine = MFCommandLine( - buildCommand = "gradle", - taskName = "assembleDebug") + val commandLine = createCommandLine(buildCommand = "gradle", taskName = "assembleDebug") commandLine.verify() @@ -26,6 +22,3 @@ fun shouldGenerateProperCommandLineWithCustomPathToExecute() { - val commandLine = MFCommandLine( - mfPath = "/customPath", - buildCommand = "gradle", - taskName = "build") + val commandLine = createCommandLine(mfPath = "/customPath") commandLine.verify() @@ -35,6 +28,3 @@ fun shouldGenerateProperCommandLineWithWhiteSpacePathToExecute() { - val commandLine = MFCommandLine( - mfPath = "/White Spaced Path", - buildCommand = "gradle", - taskName = "build") + val commandLine = createCommandLine(mfPath = "/White Spaced Path") commandLine.verify() @@ -49,2 +39,5 @@ } + + private fun createCommandLine(mfPath: String = "", buildCommand: String = "./gradlew", taskName: String = "build") + = MFCommandLine(mfPath, buildCommand, taskName) }
--- a/src/test/kotlin/com/elpassion/intelijidea/common/MFCommandLineTest.kt +++ b/src/test/kotlin/com/elpassion/intelijidea/common/MFCommandLineTest.kt @@ ... @@ fun shouldGenerateCommandLineToExecute() { - val commandLine = MFCommandLine( - buildCommand = "./gradlew", - taskName = "build") + val commandLine = createCommandLine() commandLine.verify() @@ ... @@ fun shouldGenerateProperCommandLineToExecute() { - val commandLine = MFCommandLine( - buildCommand = "gradle", - taskName = "assembleDebug") + val commandLine = createCommandLine(buildCommand = "gradle", taskName = "assembleDebug") commandLine.verify() @@ ... @@ fun shouldGenerateProperCommandLineWithCustomPathToExecute() { - val commandLine = MFCommandLine( - mfPath = "/customPath", - buildCommand = "gradle", - taskName = "build") + val commandLine = createCommandLine(mfPath = "/customPath") commandLine.verify() @@ ... @@ fun shouldGenerateProperCommandLineWithWhiteSpacePathToExecute() { - val commandLine = MFCommandLine( - mfPath = "/White Spaced Path", - buildCommand = "gradle", - taskName = "build") + val commandLine = createCommandLine(mfPath = "/White Spaced Path") commandLine.verify() @@ ... @@ } + + private fun createCommandLine(mfPath: String = "", buildCommand: String = "./gradlew", taskName: String = "build") + = MFCommandLine(mfPath, buildCommand, taskName) }
--- a/src/test/kotlin/com/elpassion/intelijidea/common/MFCommandLineTest.kt +++ b/src/test/kotlin/com/elpassion/intelijidea/common/MFCommandLineTest.kt @@ -10,5 +10,3 @@ CON fun shouldGenerateCommandLineToExecute() { DEL val commandLine = MFCommandLine( DEL buildCommand = "./gradlew", DEL taskName = "build") ADD val commandLine = createCommandLine() CON commandLine.verify() @@ -18,5 +16,3 @@ CON fun shouldGenerateProperCommandLineToExecute() { DEL val commandLine = MFCommandLine( DEL buildCommand = "gradle", DEL taskName = "assembleDebug") ADD val commandLine = createCommandLine(buildCommand = "gradle", taskName = "assembleDebug") CON commandLine.verify() @@ -26,6 +22,3 @@ CON fun shouldGenerateProperCommandLineWithCustomPathToExecute() { DEL val commandLine = MFCommandLine( DEL mfPath = "/customPath", DEL buildCommand = "gradle", DEL taskName = "build") ADD val commandLine = createCommandLine(mfPath = "/customPath") CON commandLine.verify() @@ -35,6 +28,3 @@ CON fun shouldGenerateProperCommandLineWithWhiteSpacePathToExecute() { DEL val commandLine = MFCommandLine( DEL mfPath = "/White Spaced Path", DEL buildCommand = "gradle", DEL taskName = "build") ADD val commandLine = createCommandLine(mfPath = "/White Spaced Path") CON commandLine.verify() @@ -49,2 +39,5 @@ CON } ADD ADD private fun createCommandLine(mfPath: String = "", buildCommand: String = "./gradlew", taskName: String = "build") ADD = MFCommandLine(mfPath, buildCommand, taskName) CON }
<<<<<<< SEARCH @Test fun shouldGenerateCommandLineToExecute() { val commandLine = MFCommandLine( buildCommand = "./gradlew", taskName = "build") commandLine.verify() } @Test fun shouldGenerateProperCommandLineToExecute() { val commandLine = MFCommandLine( buildCommand = "gradle", taskName = "assembleDebug") commandLine.verify() } @Test fun shouldGenerateProperCommandLineWithCustomPathToExecute() { val commandLine = MFCommandLine( mfPath = "/customPath", buildCommand = "gradle", taskName = "build") commandLine.verify() } @Test fun shouldGenerateProperCommandLineWithWhiteSpacePathToExecute() { val commandLine = MFCommandLine( mfPath = "/White Spaced Path", buildCommand = "gradle", taskName = "build") commandLine.verify() } ======= @Test fun shouldGenerateCommandLineToExecute() { val commandLine = createCommandLine() commandLine.verify() } @Test fun shouldGenerateProperCommandLineToExecute() { val commandLine = createCommandLine(buildCommand = "gradle", taskName = "assembleDebug") commandLine.verify() } @Test fun shouldGenerateProperCommandLineWithCustomPathToExecute() { val commandLine = createCommandLine(mfPath = "/customPath") commandLine.verify() } @Test fun shouldGenerateProperCommandLineWithWhiteSpacePathToExecute() { val commandLine = createCommandLine(mfPath = "/White Spaced Path") commandLine.verify() } >>>>>>> REPLACE <<<<<<< SEARCH assertEquals("bash ${expectedParams.joinToString(separator = " ")}", commandLineString) } } ======= assertEquals("bash ${expectedParams.joinToString(separator = " ")}", commandLineString) } private fun createCommandLine(mfPath: String = "", buildCommand: String = "./gradlew", taskName: String = "build") = MFCommandLine(mfPath, buildCommand, taskName) } >>>>>>> REPLACE
commonmark/commonmark-java
d70584fdc18d9eadcbc142c12f339e7d24ace996
commonmark-ext-heading-anchor/src/main/java/org/commonmark/ext/heading/anchor/internal/HeadingIdAttributeProvider.java
java
bsd-2-clause
Remove Java 8 string join method
package org.commonmark.ext.heading.anchor.internal; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.commonmark.html.AttributeProvider; import org.commonmark.node.AbstractVisitor; import org.commonmark.node.Code; import org.commonmark.node.Heading; import org.commonmark.node.Node; import org.commonmark.node.Text; import org.commonmark.ext.heading.anchor.UniqueIdentifierProvider; public class HeadingIdAttributeProvider implements AttributeProvider { private final UniqueIdentifierProvider idProvider; private HeadingIdAttributeProvider() { idProvider = new UniqueIdentifierProvider("heading"); } public static HeadingIdAttributeProvider create() { return new HeadingIdAttributeProvider(); } @Override public void setAttributes(Node node, final Map<String, String> attributes) { if (node instanceof Heading) { final List<String> wordList = new ArrayList<>(); node.accept(new AbstractVisitor() { @Override public void visit(Text text) { wordList.add(text.getLiteral()); } @Override public void visit(Code code) { wordList.add(code.getLiteral()); } }); attributes.put("id", idProvider.getUniqueIdentifier(String.join("", wordList)).toLowerCase()); } } }
package org.commonmark.ext.heading.anchor.internal; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.commonmark.html.AttributeProvider; import org.commonmark.node.AbstractVisitor; import org.commonmark.node.Code; import org.commonmark.node.Heading; import org.commonmark.node.Node; import org.commonmark.node.Text; import org.commonmark.ext.heading.anchor.UniqueIdentifierProvider; public class HeadingIdAttributeProvider implements AttributeProvider { private final UniqueIdentifierProvider idProvider; private HeadingIdAttributeProvider() { idProvider = new UniqueIdentifierProvider("heading"); } public static HeadingIdAttributeProvider create() { return new HeadingIdAttributeProvider(); } @Override public void setAttributes(Node node, final Map<String, String> attributes) { if (node instanceof Heading) { final List<String> wordList = new ArrayList<>(); node.accept(new AbstractVisitor() { @Override public void visit(Text text) { wordList.add(text.getLiteral()); } @Override public void visit(Code code) { wordList.add(code.getLiteral()); } }); String finalString = ""; for (String word : wordList) { finalString += word + " "; } finalString = finalString.trim().toLowerCase(); attributes.put("id", idProvider.getUniqueIdentifier(finalString)); } } }
7
1
1
mixed
--- a/commonmark-ext-heading-anchor/src/main/java/org/commonmark/ext/heading/anchor/internal/HeadingIdAttributeProvider.java +++ b/commonmark-ext-heading-anchor/src/main/java/org/commonmark/ext/heading/anchor/internal/HeadingIdAttributeProvider.java @@ -46,3 +46,9 @@ - attributes.put("id", idProvider.getUniqueIdentifier(String.join("", wordList)).toLowerCase()); + String finalString = ""; + for (String word : wordList) { + finalString += word + " "; + } + finalString = finalString.trim().toLowerCase(); + + attributes.put("id", idProvider.getUniqueIdentifier(finalString)); }
--- a/commonmark-ext-heading-anchor/src/main/java/org/commonmark/ext/heading/anchor/internal/HeadingIdAttributeProvider.java +++ b/commonmark-ext-heading-anchor/src/main/java/org/commonmark/ext/heading/anchor/internal/HeadingIdAttributeProvider.java @@ ... @@ - attributes.put("id", idProvider.getUniqueIdentifier(String.join("", wordList)).toLowerCase()); + String finalString = ""; + for (String word : wordList) { + finalString += word + " "; + } + finalString = finalString.trim().toLowerCase(); + + attributes.put("id", idProvider.getUniqueIdentifier(finalString)); }
--- a/commonmark-ext-heading-anchor/src/main/java/org/commonmark/ext/heading/anchor/internal/HeadingIdAttributeProvider.java +++ b/commonmark-ext-heading-anchor/src/main/java/org/commonmark/ext/heading/anchor/internal/HeadingIdAttributeProvider.java @@ -46,3 +46,9 @@ CON DEL attributes.put("id", idProvider.getUniqueIdentifier(String.join("", wordList)).toLowerCase()); ADD String finalString = ""; ADD for (String word : wordList) { ADD finalString += word + " "; ADD } ADD finalString = finalString.trim().toLowerCase(); ADD ADD attributes.put("id", idProvider.getUniqueIdentifier(finalString)); CON }
<<<<<<< SEARCH }); attributes.put("id", idProvider.getUniqueIdentifier(String.join("", wordList)).toLowerCase()); } } ======= }); String finalString = ""; for (String word : wordList) { finalString += word + " "; } finalString = finalString.trim().toLowerCase(); attributes.put("id", idProvider.getUniqueIdentifier(finalString)); } } >>>>>>> REPLACE
gradle/gradle
ca686ab1754855b79e9cc481b206b0109ffbd61d
subprojects/soak/soak.gradle.kts
kotlin
apache-2.0
Exclude `META-INF/*.kotlin_module` from `classycle` checks in `soak`
import org.gradle.gradlebuild.unittestandcompile.ModuleType plugins { gradlebuild.classycle `kotlin-library` } dependencies { testFixturesApi(project(":internalIntegTesting")) testImplementation(project(":kotlinDslTestFixtures")) } gradlebuildJava { moduleType = ModuleType.INTERNAL } testFixtures { from(":core") } tasks.matching { it.name in listOf("integTest", "java9IntegTest") }.configureEach { require(this is Test) options { require(this is JUnitOptions) excludeCategories("org.gradle.soak.categories.SoakTest") } } tasks.register("soakTest", org.gradle.gradlebuild.test.integrationtests.SoakTest::class) { val integTestSourceSet = sourceSets.integTest.get() testClassesDirs = integTestSourceSet.output.classesDirs classpath = integTestSourceSet.runtimeClasspath systemProperty("org.gradle.soaktest", "true") options { require(this is JUnitOptions) includeCategories("org.gradle.soak.categories.SoakTest") } }
import org.gradle.gradlebuild.unittestandcompile.ModuleType plugins { gradlebuild.classycle `kotlin-library` } dependencies { testFixturesApi(project(":internalIntegTesting")) testImplementation(project(":kotlinDslTestFixtures")) } gradlebuildJava { moduleType = ModuleType.INTERNAL } testFixtures { from(":core") } tasks.matching { it.name in listOf("integTest", "java9IntegTest") }.configureEach { require(this is Test) options { require(this is JUnitOptions) excludeCategories("org.gradle.soak.categories.SoakTest") } } tasks.register("soakTest", org.gradle.gradlebuild.test.integrationtests.SoakTest::class) { val integTestSourceSet = sourceSets.integTest.get() testClassesDirs = integTestSourceSet.output.classesDirs classpath = integTestSourceSet.runtimeClasspath systemProperty("org.gradle.soaktest", "true") options { require(this is JUnitOptions) includeCategories("org.gradle.soak.categories.SoakTest") } } classycle { excludePatterns.set(listOf("META-INF/*.kotlin_module")) }
4
0
1
add_only
--- a/subprojects/soak/soak.gradle.kts +++ b/subprojects/soak/soak.gradle.kts @@ -38 +38,5 @@ } + +classycle { + excludePatterns.set(listOf("META-INF/*.kotlin_module")) +}
--- a/subprojects/soak/soak.gradle.kts +++ b/subprojects/soak/soak.gradle.kts @@ ... @@ } + +classycle { + excludePatterns.set(listOf("META-INF/*.kotlin_module")) +}
--- a/subprojects/soak/soak.gradle.kts +++ b/subprojects/soak/soak.gradle.kts @@ -38 +38,5 @@ CON } ADD ADD classycle { ADD excludePatterns.set(listOf("META-INF/*.kotlin_module")) ADD }
<<<<<<< SEARCH } } ======= } } classycle { excludePatterns.set(listOf("META-INF/*.kotlin_module")) } >>>>>>> REPLACE
Br3nda/plow
0c98ade93d3524ed161967f99040a638d53c8826
server/src/main/java/com/breakersoft/plow/Signal.java
java
apache-2.0
Add signal for shutdown procs
package com.breakersoft.plow; public class Signal { /** * Exit signal for an aborted dispatch. */ public static final int NORMAL = 0; /** * Exit signal for an aborted dispatch. */ public static final int ABORTED_TASK = 667; /** * Exit signal for an orphaned task. */ public static final int ORPANED_TASK = 668; /** * Task was manually killed */ public static final int MANUAL_KILL = 669; /** * Task was manually retried */ public static final int MANUAL_RETRY = 670; /** * The node went down. */ public static final int NODE_DOWN = 671; }
package com.breakersoft.plow; public class Signal { /** * Exit signal for an aborted dispatch. */ public static final int NORMAL = 0; /** * Exit signal when a node is shutdown. */ public static final int NODE_SHUTDOWN = 86; /** * Exit signal for an aborted dispatch. */ public static final int ABORTED_TASK = 667; /** * Exit signal for an orphaned task. */ public static final int ORPANED_TASK = 668; /** * Task was manually killed */ public static final int MANUAL_KILL = 669; /** * Task was manually retried */ public static final int MANUAL_RETRY = 670; /** * The node went down. */ public static final int NODE_DOWN = 671; }
5
0
1
add_only
--- a/server/src/main/java/com/breakersoft/plow/Signal.java +++ b/server/src/main/java/com/breakersoft/plow/Signal.java @@ -8,2 +8,7 @@ public static final int NORMAL = 0; + + /** + * Exit signal when a node is shutdown. + */ + public static final int NODE_SHUTDOWN = 86;
--- a/server/src/main/java/com/breakersoft/plow/Signal.java +++ b/server/src/main/java/com/breakersoft/plow/Signal.java @@ ... @@ public static final int NORMAL = 0; + + /** + * Exit signal when a node is shutdown. + */ + public static final int NODE_SHUTDOWN = 86;
--- a/server/src/main/java/com/breakersoft/plow/Signal.java +++ b/server/src/main/java/com/breakersoft/plow/Signal.java @@ -8,2 +8,7 @@ CON public static final int NORMAL = 0; ADD ADD /** ADD * Exit signal when a node is shutdown. ADD */ ADD public static final int NODE_SHUTDOWN = 86; CON
<<<<<<< SEARCH */ public static final int NORMAL = 0; /** ======= */ public static final int NORMAL = 0; /** * Exit signal when a node is shutdown. */ public static final int NODE_SHUTDOWN = 86; /** >>>>>>> REPLACE
hwchen/keyring-rs
c56e221540c4df6e33abb3e55bd92ab9f719a37c
src/lib.rs
rust
apache-2.0
Add test for empty password Handling empty passwords properly. I don't have an explicit check for empty passwords in the keyring library (front-end or any of the backends). Instead, I rely on the system vaults (or as close as possible to that interface) to report back errors. I don't want to up-front assume that blank passwords are invalid (although I thought about doing it this way... and would have missed a bug). In the keyring library, the set_password fn for linux has a try! around every single function call which returns a result (all of which are basically wrappers around dbus secret-service calls). So, I was a bit surprised to find that fuzzing the keyring library caught a panic on empty string input! I expected a propagated error. Turns out it was an error in the secret-service library, in a non-IO call formatting the secret. I assumed that because there was no IO it could safely be unwrapped, but it turns out that the dbus library would return an empty array error when construting from an empty string! A very unexpected error! Anyways, now that error is no longer unwrapped, and is instead propogated up. This error was caught while fuzzing, although it would have been easy enough if I had more basic tests.
//! # Keyring library //! //! Allows for setting and getting passwords on Linux, OSX, and Windows // Configure for Linux #[cfg(target_os = "linux")] extern crate secret_service; #[cfg(target_os = "linux")] mod linux; #[cfg(target_os = "linux")] pub use linux::Keyring; // Configure for Windows #[cfg(target_os = "windows")] extern crate winapi; #[cfg(target_os = "windows")] extern crate advapi32; #[cfg(target_os = "windows")] mod windows; #[cfg(target_os = "windows")] pub use windows::Keyring; // Configure for OSX #[cfg(target_os = "macos")] extern crate rustc_serialize; #[cfg(target_os = "macos")] mod macos; #[cfg(target_os = "macos")] pub use macos::Keyring; mod error; pub use error::{KeyringError, Result};
//! # Keyring library //! //! Allows for setting and getting passwords on Linux, OSX, and Windows // Configure for Linux #[cfg(target_os = "linux")] extern crate secret_service; #[cfg(target_os = "linux")] mod linux; #[cfg(target_os = "linux")] pub use linux::Keyring; // Configure for Windows #[cfg(target_os = "windows")] extern crate winapi; #[cfg(target_os = "windows")] extern crate advapi32; #[cfg(target_os = "windows")] mod windows; #[cfg(target_os = "windows")] pub use windows::Keyring; // Configure for OSX #[cfg(target_os = "macos")] extern crate rustc_serialize; #[cfg(target_os = "macos")] mod macos; #[cfg(target_os = "macos")] pub use macos::Keyring; mod error; pub use error::{KeyringError, Result}; #[cfg(test)] mod tests { use super::*; #[test] #[should_panic] fn test_empty_password_input() { let pass = ""; let keyring = Keyring::new("test", "test"); match keyring.set_password(pass) { Ok(_) => (), Err(_) => { keyring.get_password().unwrap(); }, } } }
17
0
1
add_only
--- a/src/lib.rs +++ b/src/lib.rs @@ -33 +33,18 @@ +#[cfg(test)] +mod tests { + use super::*; + + #[test] + #[should_panic] + fn test_empty_password_input() { + let pass = ""; + let keyring = Keyring::new("test", "test"); + match keyring.set_password(pass) { + Ok(_) => (), + Err(_) => { + keyring.get_password().unwrap(); + }, + } + } +}
--- a/src/lib.rs +++ b/src/lib.rs @@ ... @@ +#[cfg(test)] +mod tests { + use super::*; + + #[test] + #[should_panic] + fn test_empty_password_input() { + let pass = ""; + let keyring = Keyring::new("test", "test"); + match keyring.set_password(pass) { + Ok(_) => (), + Err(_) => { + keyring.get_password().unwrap(); + }, + } + } +}
--- a/src/lib.rs +++ b/src/lib.rs @@ -33 +33,18 @@ CON ADD #[cfg(test)] ADD mod tests { ADD use super::*; ADD ADD #[test] ADD #[should_panic] ADD fn test_empty_password_input() { ADD let pass = ""; ADD let keyring = Keyring::new("test", "test"); ADD match keyring.set_password(pass) { ADD Ok(_) => (), ADD Err(_) => { ADD keyring.get_password().unwrap(); ADD }, ADD } ADD } ADD }
<<<<<<< SEARCH pub use error::{KeyringError, Result}; ======= pub use error::{KeyringError, Result}; #[cfg(test)] mod tests { use super::*; #[test] #[should_panic] fn test_empty_password_input() { let pass = ""; let keyring = Keyring::new("test", "test"); match keyring.set_password(pass) { Ok(_) => (), Err(_) => { keyring.get_password().unwrap(); }, } } } >>>>>>> REPLACE
ReactiveCircus/FlowBinding
2a3182984909118cd16af3414d4c8039e1a8c38a
flowbinding-lifecycle/src/main/java/reactivecircus/flowbinding/lifecycle/LifecycleEventFlow.kt
kotlin
apache-2.0
Replace deprecated @OnLifecycleEvent annotation with LifecycleEventObserver for LifecycleEvent bindings.
package reactivecircus.flowbinding.lifecycle import androidx.annotation.CheckResult import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleObserver import androidx.lifecycle.LifecycleOwner import androidx.lifecycle.OnLifecycleEvent import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.channels.awaitClose import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.callbackFlow import reactivecircus.flowbinding.common.checkMainThread /** * Create a [Flow] of [Lifecycle.Event]s on the [Lifecycle] instance. * * Note: Created flow keeps a strong reference to the [Lifecycle] instance * until the coroutine that launched the flow collector is cancelled. * * Example of usage: * * ``` * lifecycle.events() * .filter { it == Lifecycle.Event.ON_CREATE } * .onEach { event -> * // handle Lifecycle.Event.ON_CREATE event * } * .launchIn(uiScope) * ``` */ @CheckResult @OptIn(ExperimentalCoroutinesApi::class) public fun Lifecycle.events(): Flow<Lifecycle.Event> = callbackFlow { checkMainThread() val observer = object : LifecycleObserver { @Suppress("UNUSED_PARAMETER") @OnLifecycleEvent(Lifecycle.Event.ON_ANY) fun onEvent(owner: LifecycleOwner, event: Lifecycle.Event) { trySend(event) } } addObserver(observer) awaitClose { removeObserver(observer) } }
package reactivecircus.flowbinding.lifecycle import androidx.annotation.CheckResult import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleEventObserver import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.channels.awaitClose import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.callbackFlow import reactivecircus.flowbinding.common.checkMainThread /** * Create a [Flow] of [Lifecycle.Event]s on the [Lifecycle] instance. * * Note: Created flow keeps a strong reference to the [Lifecycle] instance * until the coroutine that launched the flow collector is cancelled. * * Example of usage: * * ``` * lifecycle.events() * .filter { it == Lifecycle.Event.ON_CREATE } * .onEach { event -> * // handle Lifecycle.Event.ON_CREATE event * } * .launchIn(uiScope) * ``` */ @CheckResult @OptIn(ExperimentalCoroutinesApi::class) public fun Lifecycle.events(): Flow<Lifecycle.Event> = callbackFlow { checkMainThread() val observer = LifecycleEventObserver { _, event -> trySend(event) } addObserver(observer) awaitClose { removeObserver(observer) } }
2
10
2
mixed
--- a/flowbinding-lifecycle/src/main/java/reactivecircus/flowbinding/lifecycle/LifecycleEventFlow.kt +++ b/flowbinding-lifecycle/src/main/java/reactivecircus/flowbinding/lifecycle/LifecycleEventFlow.kt @@ -4,5 +4,3 @@ import androidx.lifecycle.Lifecycle -import androidx.lifecycle.LifecycleObserver -import androidx.lifecycle.LifecycleOwner -import androidx.lifecycle.OnLifecycleEvent +import androidx.lifecycle.LifecycleEventObserver import kotlinx.coroutines.ExperimentalCoroutinesApi @@ -34,9 +32,3 @@ checkMainThread() - val observer = object : LifecycleObserver { - @Suppress("UNUSED_PARAMETER") - @OnLifecycleEvent(Lifecycle.Event.ON_ANY) - fun onEvent(owner: LifecycleOwner, event: Lifecycle.Event) { - trySend(event) - } - } + val observer = LifecycleEventObserver { _, event -> trySend(event) } addObserver(observer)
--- a/flowbinding-lifecycle/src/main/java/reactivecircus/flowbinding/lifecycle/LifecycleEventFlow.kt +++ b/flowbinding-lifecycle/src/main/java/reactivecircus/flowbinding/lifecycle/LifecycleEventFlow.kt @@ ... @@ import androidx.lifecycle.Lifecycle -import androidx.lifecycle.LifecycleObserver -import androidx.lifecycle.LifecycleOwner -import androidx.lifecycle.OnLifecycleEvent +import androidx.lifecycle.LifecycleEventObserver import kotlinx.coroutines.ExperimentalCoroutinesApi @@ ... @@ checkMainThread() - val observer = object : LifecycleObserver { - @Suppress("UNUSED_PARAMETER") - @OnLifecycleEvent(Lifecycle.Event.ON_ANY) - fun onEvent(owner: LifecycleOwner, event: Lifecycle.Event) { - trySend(event) - } - } + val observer = LifecycleEventObserver { _, event -> trySend(event) } addObserver(observer)
--- a/flowbinding-lifecycle/src/main/java/reactivecircus/flowbinding/lifecycle/LifecycleEventFlow.kt +++ b/flowbinding-lifecycle/src/main/java/reactivecircus/flowbinding/lifecycle/LifecycleEventFlow.kt @@ -4,5 +4,3 @@ CON import androidx.lifecycle.Lifecycle DEL import androidx.lifecycle.LifecycleObserver DEL import androidx.lifecycle.LifecycleOwner DEL import androidx.lifecycle.OnLifecycleEvent ADD import androidx.lifecycle.LifecycleEventObserver CON import kotlinx.coroutines.ExperimentalCoroutinesApi @@ -34,9 +32,3 @@ CON checkMainThread() DEL val observer = object : LifecycleObserver { DEL @Suppress("UNUSED_PARAMETER") DEL @OnLifecycleEvent(Lifecycle.Event.ON_ANY) DEL fun onEvent(owner: LifecycleOwner, event: Lifecycle.Event) { DEL trySend(event) DEL } DEL } ADD val observer = LifecycleEventObserver { _, event -> trySend(event) } CON addObserver(observer)
<<<<<<< SEARCH import androidx.annotation.CheckResult import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleObserver import androidx.lifecycle.LifecycleOwner import androidx.lifecycle.OnLifecycleEvent import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.channels.awaitClose ======= import androidx.annotation.CheckResult import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleEventObserver import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.channels.awaitClose >>>>>>> REPLACE <<<<<<< SEARCH public fun Lifecycle.events(): Flow<Lifecycle.Event> = callbackFlow { checkMainThread() val observer = object : LifecycleObserver { @Suppress("UNUSED_PARAMETER") @OnLifecycleEvent(Lifecycle.Event.ON_ANY) fun onEvent(owner: LifecycleOwner, event: Lifecycle.Event) { trySend(event) } } addObserver(observer) awaitClose { removeObserver(observer) } ======= public fun Lifecycle.events(): Flow<Lifecycle.Event> = callbackFlow { checkMainThread() val observer = LifecycleEventObserver { _, event -> trySend(event) } addObserver(observer) awaitClose { removeObserver(observer) } >>>>>>> REPLACE
dimkarakostas/unimeet
2ea049545f88a307f72d2de6223034cacf0e6e70
frontend/src/components/chat/connection/realtimeConnector.js
javascript
mit
Add code comment for server-start-chatting
import io from 'socket.io-client'; function realtimeConnector(cookie, realtimeUrl, roomId, handleNewMessageCallback, handleNextCallback, disableChatCallback) { this._chatting = false; this._socket = io.connect(realtimeUrl, {'forceNew': true}); this._socket.on('connect', () => { this._socket.emit('client-join-room', roomId, cookie); }); this._socket.on('server-start-chatting', () => { if (!this._chatting) { disableChatCallback(false); this._chatting = true; } }); this._socket.on('server-message', (message, from) => { handleNewMessageCallback(message, from); }); this._socket.on('server-next', () => { handleNextCallback(); }); this._socket.on('disconnect', () => { disableChatCallback(true); this._chatting = false; }); this.broadcastMessage = function(message) { this._socket.emit('client-message', message); }; this.broadcastNext = function() { this._socket.emit('client-next'); disableChatCallback(true); this._chatting = false; }; this.disconnect = function() { this._socket.disconnect(); } this.reconnect = function() { this._socket.connect(); } }; module.exports = realtimeConnector;
import io from 'socket.io-client'; function realtimeConnector(cookie, realtimeUrl, roomId, handleNewMessageCallback, handleNextCallback, disableChatCallback) { this._chatting = false; this._socket = io.connect(realtimeUrl, {'forceNew': true}); this._socket.on('connect', () => { this._socket.emit('client-join-room', roomId, cookie); }); this._socket.on('server-start-chatting', () => { // If already chatting, ignore this message if (!this._chatting) { disableChatCallback(false); this._chatting = true; } }); this._socket.on('server-message', (message, from) => { handleNewMessageCallback(message, from); }); this._socket.on('server-next', () => { handleNextCallback(); }); this._socket.on('disconnect', () => { disableChatCallback(true); this._chatting = false; }); this.broadcastMessage = function(message) { this._socket.emit('client-message', message); }; this.broadcastNext = function() { this._socket.emit('client-next'); disableChatCallback(true); this._chatting = false; }; this.disconnect = function() { this._socket.disconnect(); } this.reconnect = function() { this._socket.connect(); } }; module.exports = realtimeConnector;
1
0
1
add_only
--- a/frontend/src/components/chat/connection/realtimeConnector.js +++ b/frontend/src/components/chat/connection/realtimeConnector.js @@ -9,2 +9,3 @@ this._socket.on('server-start-chatting', () => { + // If already chatting, ignore this message if (!this._chatting) {
--- a/frontend/src/components/chat/connection/realtimeConnector.js +++ b/frontend/src/components/chat/connection/realtimeConnector.js @@ ... @@ this._socket.on('server-start-chatting', () => { + // If already chatting, ignore this message if (!this._chatting) {
--- a/frontend/src/components/chat/connection/realtimeConnector.js +++ b/frontend/src/components/chat/connection/realtimeConnector.js @@ -9,2 +9,3 @@ CON this._socket.on('server-start-chatting', () => { ADD // If already chatting, ignore this message CON if (!this._chatting) {
<<<<<<< SEARCH }); this._socket.on('server-start-chatting', () => { if (!this._chatting) { disableChatCallback(false); ======= }); this._socket.on('server-start-chatting', () => { // If already chatting, ignore this message if (!this._chatting) { disableChatCallback(false); >>>>>>> REPLACE
leonardinius/rust-guide
34f73812e496b7269a57652c1e04d20404db612b
2.12-arr-vec-slice/src/main.rs
rust
mit
Fix format trait errors (breaking change)
fn _12_1(){ println!("guide 12-1"); let a = [1i, 2i, 3i]; let mut m = [2i, 3i, 4i]; let b = [0i, ..20]; // shorthand for array of 20 elements all initialized to 0 println!("{}", b); m = [5i, 6i, 7i]; println!("{}", m); for i in m.iter() { println!("elem {}", i); } let names = ["Emilija", "Anzelika"]; println!("{} -> {}", names[1], names[0]); } fn _12_2(){ println!("guide 12-2"); let mut v = vec![1i, 2, 3]; v.push(4); println!("{}, len is {}", v, v.len()); } fn _12_3(){ println!("guide 12-3"); let mut a = vec![0i, 1, 2, 3, 4]; let middle = a.as_mut_slice(); middle[0] = 10i; for e in middle.iter() { println!("{}", e); } } fn main(){ println!("guide 12"); _12_1(); _12_2(); _12_3(); }
fn _12_1(){ println!("guide 12-1"); let a = [1i32, 2i32, 3i32]; let mut m = [2i32, 3i32, 4i32]; if false { println!("{:?} {:?}", a, m); } let b = [0i32; 20]; // shorthand for array of 20 elements all initialized to 0 println!("{:?}", b); m = [5i32, 6i32, 7i32]; println!("{:?}", m); for i in m.iter() { println!("elem {}", i); } let names = ["Emilija", "Anzelika"]; println!("{} -> {}", names[1], names[0]); } fn _12_2(){ println!("guide 12-2"); let mut v = vec![1i32, 2, 3]; v.push(4); println!("{:?}, len is {}", v, v.len()); } fn _12_3(){ println!("guide 12-3"); let mut a = vec![0i32, 1, 2, 3, 4]; let middle = a.as_mut_slice(); middle[0] = 10i32; for e in middle.iter() { println!("{}", e); } } fn main(){ println!("guide 12"); _12_1(); _12_2(); _12_3(); }
14
11
3
mixed
--- a/2.12-arr-vec-slice/src/main.rs +++ b/2.12-arr-vec-slice/src/main.rs @@ -3,9 +3,12 @@ - let a = [1i, 2i, 3i]; - let mut m = [2i, 3i, 4i]; + let a = [1i32, 2i32, 3i32]; + let mut m = [2i32, 3i32, 4i32]; + if false { + println!("{:?} {:?}", a, m); + } - let b = [0i, ..20]; // shorthand for array of 20 elements all initialized to 0 - println!("{}", b); - m = [5i, 6i, 7i]; - println!("{}", m); + let b = [0i32; 20]; // shorthand for array of 20 elements all initialized to 0 + println!("{:?}", b); + m = [5i32, 6i32, 7i32]; + println!("{:?}", m); @@ -22,5 +25,5 @@ - let mut v = vec![1i, 2, 3]; + let mut v = vec![1i32, 2, 3]; v.push(4); - println!("{}, len is {}", v, v.len()); + println!("{:?}, len is {}", v, v.len()); } @@ -30,6 +33,6 @@ - let mut a = vec![0i, 1, 2, 3, 4]; - let middle = a.as_mut_slice(); + let mut a = vec![0i32, 1, 2, 3, 4]; + let middle = a.as_mut_slice(); - middle[0] = 10i; + middle[0] = 10i32;
--- a/2.12-arr-vec-slice/src/main.rs +++ b/2.12-arr-vec-slice/src/main.rs @@ ... @@ - let a = [1i, 2i, 3i]; - let mut m = [2i, 3i, 4i]; + let a = [1i32, 2i32, 3i32]; + let mut m = [2i32, 3i32, 4i32]; + if false { + println!("{:?} {:?}", a, m); + } - let b = [0i, ..20]; // shorthand for array of 20 elements all initialized to 0 - println!("{}", b); - m = [5i, 6i, 7i]; - println!("{}", m); + let b = [0i32; 20]; // shorthand for array of 20 elements all initialized to 0 + println!("{:?}", b); + m = [5i32, 6i32, 7i32]; + println!("{:?}", m); @@ ... @@ - let mut v = vec![1i, 2, 3]; + let mut v = vec![1i32, 2, 3]; v.push(4); - println!("{}, len is {}", v, v.len()); + println!("{:?}, len is {}", v, v.len()); } @@ ... @@ - let mut a = vec![0i, 1, 2, 3, 4]; - let middle = a.as_mut_slice(); + let mut a = vec![0i32, 1, 2, 3, 4]; + let middle = a.as_mut_slice(); - middle[0] = 10i; + middle[0] = 10i32;
--- a/2.12-arr-vec-slice/src/main.rs +++ b/2.12-arr-vec-slice/src/main.rs @@ -3,9 +3,12 @@ CON DEL let a = [1i, 2i, 3i]; DEL let mut m = [2i, 3i, 4i]; ADD let a = [1i32, 2i32, 3i32]; ADD let mut m = [2i32, 3i32, 4i32]; ADD if false { ADD println!("{:?} {:?}", a, m); ADD } CON DEL let b = [0i, ..20]; // shorthand for array of 20 elements all initialized to 0 DEL println!("{}", b); DEL m = [5i, 6i, 7i]; DEL println!("{}", m); ADD let b = [0i32; 20]; // shorthand for array of 20 elements all initialized to 0 ADD println!("{:?}", b); ADD m = [5i32, 6i32, 7i32]; ADD println!("{:?}", m); CON @@ -22,5 +25,5 @@ CON DEL let mut v = vec![1i, 2, 3]; ADD let mut v = vec![1i32, 2, 3]; CON v.push(4); DEL println!("{}, len is {}", v, v.len()); ADD println!("{:?}, len is {}", v, v.len()); CON } @@ -30,6 +33,6 @@ CON DEL let mut a = vec![0i, 1, 2, 3, 4]; DEL let middle = a.as_mut_slice(); ADD let mut a = vec![0i32, 1, 2, 3, 4]; ADD let middle = a.as_mut_slice(); CON DEL middle[0] = 10i; ADD middle[0] = 10i32; CON
<<<<<<< SEARCH println!("guide 12-1"); let a = [1i, 2i, 3i]; let mut m = [2i, 3i, 4i]; let b = [0i, ..20]; // shorthand for array of 20 elements all initialized to 0 println!("{}", b); m = [5i, 6i, 7i]; println!("{}", m); for i in m.iter() { ======= println!("guide 12-1"); let a = [1i32, 2i32, 3i32]; let mut m = [2i32, 3i32, 4i32]; if false { println!("{:?} {:?}", a, m); } let b = [0i32; 20]; // shorthand for array of 20 elements all initialized to 0 println!("{:?}", b); m = [5i32, 6i32, 7i32]; println!("{:?}", m); for i in m.iter() { >>>>>>> REPLACE <<<<<<< SEARCH println!("guide 12-2"); let mut v = vec![1i, 2, 3]; v.push(4); println!("{}, len is {}", v, v.len()); } fn _12_3(){ println!("guide 12-3"); let mut a = vec![0i, 1, 2, 3, 4]; let middle = a.as_mut_slice(); middle[0] = 10i; for e in middle.iter() { ======= println!("guide 12-2"); let mut v = vec![1i32, 2, 3]; v.push(4); println!("{:?}, len is {}", v, v.len()); } fn _12_3(){ println!("guide 12-3"); let mut a = vec![0i32, 1, 2, 3, 4]; let middle = a.as_mut_slice(); middle[0] = 10i32; for e in middle.iter() { >>>>>>> REPLACE
Gwindow/WhatAPI
fa80d8d163fc657874aebc5a1bc5feedcb0ccd6b
src/api/forum/thread/Answer.java
java
bsd-2-clause
Add ability to update the votes for an answer in the poll This is needed by the app so we can update poll results after voting without needing to redownload the whole page
package api.forum.thread; /** * The Class Answer. * Stores information about an possible answer selection * for a Poll * * @author Gwindow */ public class Answer { /** * The answer text */ private String answer; /** * The percent of votes it's gotten */ private Number percent; /** * The ratio of votes it's gotten */ private Number ratio; /** * Get the answer text * * @return the answer text */ public String getAnswer(){ return this.answer; } /** * Get the percent of votes the answers received * * @return the percent of votes received */ public Number getPercent(){ return this.percent; } /** * Get the ratio of votes the answers received * * @return the ratio of votes received */ public Number getRatio(){ return this.ratio; } @Override public String toString(){ return "Answer [getAnswer=" + getAnswer() + ", getPercent=" + getPercent() + ", getRatio=" + getRatio() + "]"; } }
package api.forum.thread; /** * The Class Answer. * Stores information about an possible answer selection * for a Poll * * @author Gwindow */ public class Answer { /** * The answer text */ private String answer; /** * The percent of votes it's gotten */ private Number percent; /** * The ratio of votes it's gotten */ private Number ratio; /** * Get the answer text * * @return the answer text */ public String getAnswer(){ return this.answer; } /** * Get the percent of votes the answers received * * @return the percent of votes received */ public Number getPercent(){ return this.percent; } /** * Get the ratio of votes the answers received * * @return the ratio of votes received */ public Number getRatio(){ return this.ratio; } /** * Update the percentage of votes this answer has received * * @param votes votes for this answer * @param total total votes in the poll */ public void setVotes(int votes, int total){ percent = ((float)votes) / total; } @Override public String toString(){ return "Answer [getAnswer=" + getAnswer() + ", getPercent=" + getPercent() + ", getRatio=" + getRatio() + "]"; } }
10
0
1
add_only
--- a/src/api/forum/thread/Answer.java +++ b/src/api/forum/thread/Answer.java @@ -52,2 +52,12 @@ + /** + * Update the percentage of votes this answer has received + * + * @param votes votes for this answer + * @param total total votes in the poll + */ + public void setVotes(int votes, int total){ + percent = ((float)votes) / total; + } + @Override
--- a/src/api/forum/thread/Answer.java +++ b/src/api/forum/thread/Answer.java @@ ... @@ + /** + * Update the percentage of votes this answer has received + * + * @param votes votes for this answer + * @param total total votes in the poll + */ + public void setVotes(int votes, int total){ + percent = ((float)votes) / total; + } + @Override
--- a/src/api/forum/thread/Answer.java +++ b/src/api/forum/thread/Answer.java @@ -52,2 +52,12 @@ CON ADD /** ADD * Update the percentage of votes this answer has received ADD * ADD * @param votes votes for this answer ADD * @param total total votes in the poll ADD */ ADD public void setVotes(int votes, int total){ ADD percent = ((float)votes) / total; ADD } ADD CON @Override
<<<<<<< SEARCH } @Override public String toString(){ ======= } /** * Update the percentage of votes this answer has received * * @param votes votes for this answer * @param total total votes in the poll */ public void setVotes(int votes, int total){ percent = ((float)votes) / total; } @Override public String toString(){ >>>>>>> REPLACE
thombashi/sqliteschema
696a79069ad1db1caee4d6da0c3c48dbd79f9157
sqliteschema/_logger.py
python
mit
Modify to avoid excessive logger initialization
# encoding: utf-8 """ .. codeauthor:: Tsuyoshi Hombashi <[email protected]> """ from __future__ import absolute_import from __future__ import unicode_literals import logbook import pytablewriter import simplesqlite logger = logbook.Logger("sqliteschema") logger.disable() def set_logger(is_enable): pytablewriter.set_logger(is_enable=is_enable) simplesqlite.set_logger(is_enable=is_enable) if is_enable: logger.enable() else: logger.disable() def set_log_level(log_level): """ Set logging level of this module. Using `logbook <http://logbook.readthedocs.io/en/stable/>`__ module for logging. :param int log_level: One of the log level of `logbook <http://logbook.readthedocs.io/en/stable/api/base.html>`__. Disabled logging if ``log_level`` is ``logbook.NOTSET``. """ pytablewriter.set_log_level(log_level) simplesqlite.set_log_level(log_level) if log_level == logbook.NOTSET: set_logger(is_enable=False) else: set_logger(is_enable=True) logger.level = log_level
# encoding: utf-8 """ .. codeauthor:: Tsuyoshi Hombashi <[email protected]> """ from __future__ import absolute_import from __future__ import unicode_literals import logbook import pytablewriter import simplesqlite logger = logbook.Logger("sqliteschema") logger.disable() def set_logger(is_enable): if is_enable != logger.disabled: return if is_enable: logger.enable() else: logger.disable() pytablewriter.set_logger(is_enable=is_enable) simplesqlite.set_logger(is_enable=is_enable) def set_log_level(log_level): """ Set logging level of this module. Using `logbook <http://logbook.readthedocs.io/en/stable/>`__ module for logging. :param int log_level: One of the log level of `logbook <http://logbook.readthedocs.io/en/stable/api/base.html>`__. Disabled logging if ``log_level`` is ``logbook.NOTSET``. """ if log_level == logger.level: return if log_level == logbook.NOTSET: set_logger(is_enable=False) else: set_logger(is_enable=True) logger.level = log_level pytablewriter.set_log_level(log_level) simplesqlite.set_log_level(log_level)
10
4
4
mixed
--- a/sqliteschema/_logger.py +++ b/sqliteschema/_logger.py @@ -19,4 +19,4 @@ def set_logger(is_enable): - pytablewriter.set_logger(is_enable=is_enable) - simplesqlite.set_logger(is_enable=is_enable) + if is_enable != logger.disabled: + return @@ -26,2 +26,5 @@ logger.disable() + + pytablewriter.set_logger(is_enable=is_enable) + simplesqlite.set_logger(is_enable=is_enable) @@ -39,4 +42,4 @@ - pytablewriter.set_log_level(log_level) - simplesqlite.set_log_level(log_level) + if log_level == logger.level: + return @@ -47 +50,4 @@ logger.level = log_level + + pytablewriter.set_log_level(log_level) + simplesqlite.set_log_level(log_level)
--- a/sqliteschema/_logger.py +++ b/sqliteschema/_logger.py @@ ... @@ def set_logger(is_enable): - pytablewriter.set_logger(is_enable=is_enable) - simplesqlite.set_logger(is_enable=is_enable) + if is_enable != logger.disabled: + return @@ ... @@ logger.disable() + + pytablewriter.set_logger(is_enable=is_enable) + simplesqlite.set_logger(is_enable=is_enable) @@ ... @@ - pytablewriter.set_log_level(log_level) - simplesqlite.set_log_level(log_level) + if log_level == logger.level: + return @@ ... @@ logger.level = log_level + + pytablewriter.set_log_level(log_level) + simplesqlite.set_log_level(log_level)
--- a/sqliteschema/_logger.py +++ b/sqliteschema/_logger.py @@ -19,4 +19,4 @@ CON def set_logger(is_enable): DEL pytablewriter.set_logger(is_enable=is_enable) DEL simplesqlite.set_logger(is_enable=is_enable) ADD if is_enable != logger.disabled: ADD return CON @@ -26,2 +26,5 @@ CON logger.disable() ADD ADD pytablewriter.set_logger(is_enable=is_enable) ADD simplesqlite.set_logger(is_enable=is_enable) CON @@ -39,4 +42,4 @@ CON DEL pytablewriter.set_log_level(log_level) DEL simplesqlite.set_log_level(log_level) ADD if log_level == logger.level: ADD return CON @@ -47 +50,4 @@ CON logger.level = log_level ADD ADD pytablewriter.set_log_level(log_level) ADD simplesqlite.set_log_level(log_level)
<<<<<<< SEARCH def set_logger(is_enable): pytablewriter.set_logger(is_enable=is_enable) simplesqlite.set_logger(is_enable=is_enable) if is_enable: logger.enable() else: logger.disable() ======= def set_logger(is_enable): if is_enable != logger.disabled: return if is_enable: logger.enable() else: logger.disable() pytablewriter.set_logger(is_enable=is_enable) simplesqlite.set_logger(is_enable=is_enable) >>>>>>> REPLACE <<<<<<< SEARCH """ pytablewriter.set_log_level(log_level) simplesqlite.set_log_level(log_level) if log_level == logbook.NOTSET: ======= """ if log_level == logger.level: return if log_level == logbook.NOTSET: >>>>>>> REPLACE <<<<<<< SEARCH set_logger(is_enable=True) logger.level = log_level ======= set_logger(is_enable=True) logger.level = log_level pytablewriter.set_log_level(log_level) simplesqlite.set_log_level(log_level) >>>>>>> REPLACE
epicmonkey/pepyatka-html
e60843cae4eaacd33abd566c8705e56b689a6da1
public/js/app/models/Attachment.js
javascript
mit
Fix a check for an empty mediaType We need it for the old attachments.
define(["app/app"], function(App) { "use strict"; App.Attachment = DS.Model.extend({ file: DS.attr('file'), // FormData File object url: DS.attr('string'), thumbnailUrl: DS.attr('string'), fileName: DS.attr('string'), fileSize: DS.attr('number'), mediaType: DS.attr('string'), createdAt: DS.attr('string'), updatedAt: DS.attr('string'), createdBy: DS.belongsTo('user'), post: DS.belongsTo('post'), isImage: function() { return this.get('mediaType') === 'image' || this.get('mediaType') === null }.property('mediaType'), isGeneral: function() { return this.get('mediaType') === 'general' }.property('mediaType'), isAudio: function() { return this.get('mediaType') === 'audio' }.property('mediaType'), formatSize: function() { var decimals = 1 var bytes = this.get('fileSize') if (bytes == 0) return '0 Byte' var k = 1000 var dm = decimals + 1 || 3 var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'] var i = Math.floor(Math.log(bytes) / Math.log(k)) return (bytes / Math.pow(k, i)).toPrecision(dm) + ' ' + sizes[i] }.property('fileSize') }) })
define(["app/app"], function(App) { "use strict"; App.Attachment = DS.Model.extend({ file: DS.attr('file'), // FormData File object url: DS.attr('string'), thumbnailUrl: DS.attr('string'), fileName: DS.attr('string'), fileSize: DS.attr('number'), mediaType: DS.attr('string'), createdAt: DS.attr('string'), updatedAt: DS.attr('string'), createdBy: DS.belongsTo('user'), post: DS.belongsTo('post'), isImage: function() { return this.get('mediaType') === 'image' || Ember.isEmpty(this.get('mediaType')) }.property('mediaType'), isGeneral: function() { return this.get('mediaType') === 'general' }.property('mediaType'), isAudio: function() { return this.get('mediaType') === 'audio' }.property('mediaType'), formatSize: function() { var decimals = 1 var bytes = this.get('fileSize') if (bytes == 0) return '0 Byte' var k = 1000 var dm = decimals + 1 || 3 var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'] var i = Math.floor(Math.log(bytes) / Math.log(k)) return (bytes / Math.pow(k, i)).toPrecision(dm) + ' ' + sizes[i] }.property('fileSize') }) })
1
1
1
mixed
--- a/public/js/app/models/Attachment.js +++ b/public/js/app/models/Attachment.js @@ -19,3 +19,3 @@ return this.get('mediaType') === 'image' || - this.get('mediaType') === null + Ember.isEmpty(this.get('mediaType')) }.property('mediaType'),
--- a/public/js/app/models/Attachment.js +++ b/public/js/app/models/Attachment.js @@ ... @@ return this.get('mediaType') === 'image' || - this.get('mediaType') === null + Ember.isEmpty(this.get('mediaType')) }.property('mediaType'),
--- a/public/js/app/models/Attachment.js +++ b/public/js/app/models/Attachment.js @@ -19,3 +19,3 @@ CON return this.get('mediaType') === 'image' || DEL this.get('mediaType') === null ADD Ember.isEmpty(this.get('mediaType')) CON }.property('mediaType'),
<<<<<<< SEARCH isImage: function() { return this.get('mediaType') === 'image' || this.get('mediaType') === null }.property('mediaType'), ======= isImage: function() { return this.get('mediaType') === 'image' || Ember.isEmpty(this.get('mediaType')) }.property('mediaType'), >>>>>>> REPLACE
nickstenning/tagalog
a475fc39480b52d4f38d37e58b3e3c45e8335a1e
tagalog/command/logship.py
python
mit
Add support for elasticsearch bulk format Add a switch to logship to enable support for sending log data in elasticsearch bulk format.
from __future__ import print_function, unicode_literals import argparse import json import sys import textwrap from tagalog import io, stamp, tag from tagalog import shipper parser = argparse.ArgumentParser(description=textwrap.dedent(""" Ship log data from STDIN to somewhere else, timestamping and preprocessing each log entry into a JSON document along the way.""")) parser.add_argument('-t', '--tags', nargs='+') parser.add_argument('-s', '--shipper', default='redis') parser.add_argument('-k', '--key', default='logs') parser.add_argument('-u', '--urls', nargs='+', default=['redis://localhost:6379']) parser.add_argument('--no-stamp', action='store_true') def main(): args = parser.parse_args() shpr = shipper.get_shipper(args.shipper)(args) msgs = io.messages(sys.stdin) if not args.no_stamp: msgs = stamp(msgs) if args.tags: msgs = tag(msgs, args.tags) for msg in msgs: shpr.ship(json.dumps(msg)) if __name__ == '__main__': main()
from __future__ import print_function, unicode_literals import argparse import json import sys import textwrap from tagalog import io, stamp, tag from tagalog import shipper parser = argparse.ArgumentParser(description=textwrap.dedent(""" Ship log data from STDIN to somewhere else, timestamping and preprocessing each log entry into a JSON document along the way.""")) parser.add_argument('-t', '--tags', nargs='+', help='Tag each request with the specified string tags') parser.add_argument('-s', '--shipper', default='redis', help='Select the shipper to be used to ship logs') parser.add_argument('--no-stamp', action='store_true') parser.add_argument('--bulk', action='store_true', help='Send log data in elasticsearch bulk format') parser.add_argument('--bulk-index', default='logs', help='Name of the elasticsearch index (default: logs)') parser.add_argument('--bulk-type', default='message', help='Name of the elasticsearch type (default: message)') # TODO: make these the responsibility of the redis shipper parser.add_argument('-k', '--key', default='logs') parser.add_argument('-u', '--urls', nargs='+', default=['redis://localhost:6379']) def main(): args = parser.parse_args() shpr = shipper.get_shipper(args.shipper)(args) msgs = io.messages(sys.stdin) if not args.no_stamp: msgs = stamp(msgs) if args.tags: msgs = tag(msgs, args.tags) for msg in msgs: payload = json.dumps(msg) if args.bulk: command = json.dumps({'index': {'_index': args.bulk_index, '_type': args.bulk_type}}) payload = '{0}\n{1}\n'.format(command, payload) shpr.ship(payload) if __name__ == '__main__': main()
18
4
2
mixed
--- a/tagalog/command/logship.py +++ b/tagalog/command/logship.py @@ -12,7 +12,17 @@ each log entry into a JSON document along the way.""")) -parser.add_argument('-t', '--tags', nargs='+') -parser.add_argument('-s', '--shipper', default='redis') +parser.add_argument('-t', '--tags', nargs='+', + help='Tag each request with the specified string tags') +parser.add_argument('-s', '--shipper', default='redis', + help='Select the shipper to be used to ship logs') +parser.add_argument('--no-stamp', action='store_true') +parser.add_argument('--bulk', action='store_true', + help='Send log data in elasticsearch bulk format') +parser.add_argument('--bulk-index', default='logs', + help='Name of the elasticsearch index (default: logs)') +parser.add_argument('--bulk-type', default='message', + help='Name of the elasticsearch type (default: message)') + +# TODO: make these the responsibility of the redis shipper parser.add_argument('-k', '--key', default='logs') parser.add_argument('-u', '--urls', nargs='+', default=['redis://localhost:6379']) -parser.add_argument('--no-stamp', action='store_true') @@ -28,3 +38,7 @@ for msg in msgs: - shpr.ship(json.dumps(msg)) + payload = json.dumps(msg) + if args.bulk: + command = json.dumps({'index': {'_index': args.bulk_index, '_type': args.bulk_type}}) + payload = '{0}\n{1}\n'.format(command, payload) + shpr.ship(payload)
--- a/tagalog/command/logship.py +++ b/tagalog/command/logship.py @@ ... @@ each log entry into a JSON document along the way.""")) -parser.add_argument('-t', '--tags', nargs='+') -parser.add_argument('-s', '--shipper', default='redis') +parser.add_argument('-t', '--tags', nargs='+', + help='Tag each request with the specified string tags') +parser.add_argument('-s', '--shipper', default='redis', + help='Select the shipper to be used to ship logs') +parser.add_argument('--no-stamp', action='store_true') +parser.add_argument('--bulk', action='store_true', + help='Send log data in elasticsearch bulk format') +parser.add_argument('--bulk-index', default='logs', + help='Name of the elasticsearch index (default: logs)') +parser.add_argument('--bulk-type', default='message', + help='Name of the elasticsearch type (default: message)') + +# TODO: make these the responsibility of the redis shipper parser.add_argument('-k', '--key', default='logs') parser.add_argument('-u', '--urls', nargs='+', default=['redis://localhost:6379']) -parser.add_argument('--no-stamp', action='store_true') @@ ... @@ for msg in msgs: - shpr.ship(json.dumps(msg)) + payload = json.dumps(msg) + if args.bulk: + command = json.dumps({'index': {'_index': args.bulk_index, '_type': args.bulk_type}}) + payload = '{0}\n{1}\n'.format(command, payload) + shpr.ship(payload)
--- a/tagalog/command/logship.py +++ b/tagalog/command/logship.py @@ -12,7 +12,17 @@ CON each log entry into a JSON document along the way.""")) DEL parser.add_argument('-t', '--tags', nargs='+') DEL parser.add_argument('-s', '--shipper', default='redis') ADD parser.add_argument('-t', '--tags', nargs='+', ADD help='Tag each request with the specified string tags') ADD parser.add_argument('-s', '--shipper', default='redis', ADD help='Select the shipper to be used to ship logs') ADD parser.add_argument('--no-stamp', action='store_true') ADD parser.add_argument('--bulk', action='store_true', ADD help='Send log data in elasticsearch bulk format') ADD parser.add_argument('--bulk-index', default='logs', ADD help='Name of the elasticsearch index (default: logs)') ADD parser.add_argument('--bulk-type', default='message', ADD help='Name of the elasticsearch type (default: message)') ADD ADD # TODO: make these the responsibility of the redis shipper CON parser.add_argument('-k', '--key', default='logs') CON parser.add_argument('-u', '--urls', nargs='+', default=['redis://localhost:6379']) DEL parser.add_argument('--no-stamp', action='store_true') CON @@ -28,3 +38,7 @@ CON for msg in msgs: DEL shpr.ship(json.dumps(msg)) ADD payload = json.dumps(msg) ADD if args.bulk: ADD command = json.dumps({'index': {'_index': args.bulk_index, '_type': args.bulk_type}}) ADD payload = '{0}\n{1}\n'.format(command, payload) ADD shpr.ship(payload) CON
<<<<<<< SEARCH Ship log data from STDIN to somewhere else, timestamping and preprocessing each log entry into a JSON document along the way.""")) parser.add_argument('-t', '--tags', nargs='+') parser.add_argument('-s', '--shipper', default='redis') parser.add_argument('-k', '--key', default='logs') parser.add_argument('-u', '--urls', nargs='+', default=['redis://localhost:6379']) parser.add_argument('--no-stamp', action='store_true') def main(): ======= Ship log data from STDIN to somewhere else, timestamping and preprocessing each log entry into a JSON document along the way.""")) parser.add_argument('-t', '--tags', nargs='+', help='Tag each request with the specified string tags') parser.add_argument('-s', '--shipper', default='redis', help='Select the shipper to be used to ship logs') parser.add_argument('--no-stamp', action='store_true') parser.add_argument('--bulk', action='store_true', help='Send log data in elasticsearch bulk format') parser.add_argument('--bulk-index', default='logs', help='Name of the elasticsearch index (default: logs)') parser.add_argument('--bulk-type', default='message', help='Name of the elasticsearch type (default: message)') # TODO: make these the responsibility of the redis shipper parser.add_argument('-k', '--key', default='logs') parser.add_argument('-u', '--urls', nargs='+', default=['redis://localhost:6379']) def main(): >>>>>>> REPLACE <<<<<<< SEARCH msgs = tag(msgs, args.tags) for msg in msgs: shpr.ship(json.dumps(msg)) if __name__ == '__main__': ======= msgs = tag(msgs, args.tags) for msg in msgs: payload = json.dumps(msg) if args.bulk: command = json.dumps({'index': {'_index': args.bulk_index, '_type': args.bulk_type}}) payload = '{0}\n{1}\n'.format(command, payload) shpr.ship(payload) if __name__ == '__main__': >>>>>>> REPLACE
tam1m/SundtekTvInput
5194117d57d827717a04067f1b9423e6eb7fa86e
app/src/main/java/org/tb/sundtektvinput/MainFragment.java
java
apache-2.0
Change github url in WebView
/* * Copyright (C) 2015 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.tb.sundtektvinput; import android.app.Fragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.webkit.WebView; import android.webkit.WebViewClient; /** * Fragment that shows a web page for Sample TV Input introduction. */ public class MainFragment extends Fragment { private static final String URL = "http://github.com/googlesamples/androidtv-sample-inputs/blob/master/README.md"; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.main_fragment, null); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); WebView webView = (WebView) getView(); webView.setWebViewClient(new WebViewClient()); webView.loadUrl(URL); } }
/* * Copyright (C) 2015 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.tb.sundtektvinput; import android.app.Fragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.webkit.WebView; import android.webkit.WebViewClient; /** * Fragment that shows a web page for Sample TV Input introduction. */ public class MainFragment extends Fragment { private static final String URL = "https://github.com/tam1m/androidtv-sample-inputs"; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.main_fragment, null); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); WebView webView = (WebView) getView(); webView.setWebViewClient(new WebViewClient()); webView.loadUrl(URL); } }
1
1
1
mixed
--- a/app/src/main/java/org/tb/sundtektvinput/MainFragment.java +++ b/app/src/main/java/org/tb/sundtektvinput/MainFragment.java @@ -29,3 +29,3 @@ private static final String URL = - "http://github.com/googlesamples/androidtv-sample-inputs/blob/master/README.md"; + "https://github.com/tam1m/androidtv-sample-inputs";
--- a/app/src/main/java/org/tb/sundtektvinput/MainFragment.java +++ b/app/src/main/java/org/tb/sundtektvinput/MainFragment.java @@ ... @@ private static final String URL = - "http://github.com/googlesamples/androidtv-sample-inputs/blob/master/README.md"; + "https://github.com/tam1m/androidtv-sample-inputs";
--- a/app/src/main/java/org/tb/sundtektvinput/MainFragment.java +++ b/app/src/main/java/org/tb/sundtektvinput/MainFragment.java @@ -29,3 +29,3 @@ CON private static final String URL = DEL "http://github.com/googlesamples/androidtv-sample-inputs/blob/master/README.md"; ADD "https://github.com/tam1m/androidtv-sample-inputs"; CON
<<<<<<< SEARCH public class MainFragment extends Fragment { private static final String URL = "http://github.com/googlesamples/androidtv-sample-inputs/blob/master/README.md"; @Override ======= public class MainFragment extends Fragment { private static final String URL = "https://github.com/tam1m/androidtv-sample-inputs"; @Override >>>>>>> REPLACE
Techern/Netherrack
efe3527551ab2bd2fec6b27422b96c89953f6d45
src/io/operations/mod.rs
rust
apache-2.0
Test reading and writing signed and unsigned bytes on a Cursor<Vec<u8>>
//! I/O operations for Rust //! //! To be completed pub mod reader; pub mod writer;
//! I/O operations for Rust //! //! To be completed pub mod reader; pub mod writer; #[cfg(test)] mod test { use super::reader::Reader; use super::writer::Writer; use std::io::Cursor; impl Writer for Cursor<Vec<u8>> { } impl Reader for Cursor<Vec<u8>> { } #[test] fn test_read_write_u8() { let mut vector = Cursor::new(vec![0u8; 0]); assert!(vector.write_unsigned_byte(15).is_ok()); assert!(vector.write_unsigned_byte(62).is_ok()); vector.set_position(0); assert_eq!(15, vector.read_unsigned_byte().unwrap()); assert_eq!(62, vector.read_unsigned_byte().unwrap()); } #[test] fn test_read_write_i8() { let mut vector = Cursor::new(vec![0u8; 0]); assert!(vector.write_signed_byte(-43).is_ok()); assert!(vector.write_signed_byte(33).is_ok()); vector.set_position(0); assert_eq!(-43, vector.read_signed_byte().unwrap()); assert_eq!(33, vector.read_signed_byte().unwrap()); } }
48
0
1
add_only
--- a/src/io/operations/mod.rs +++ b/src/io/operations/mod.rs @@ -7 +7,49 @@ pub mod writer; + +#[cfg(test)] +mod test { + + use super::reader::Reader; + use super::writer::Writer; + + use std::io::Cursor; + + impl Writer for Cursor<Vec<u8>> { + + } + + impl Reader for Cursor<Vec<u8>> { + + } + + #[test] + fn test_read_write_u8() { + + let mut vector = Cursor::new(vec![0u8; 0]); + + assert!(vector.write_unsigned_byte(15).is_ok()); + assert!(vector.write_unsigned_byte(62).is_ok()); + + vector.set_position(0); + + assert_eq!(15, vector.read_unsigned_byte().unwrap()); + assert_eq!(62, vector.read_unsigned_byte().unwrap()); + + } + + #[test] + fn test_read_write_i8() { + + let mut vector = Cursor::new(vec![0u8; 0]); + + assert!(vector.write_signed_byte(-43).is_ok()); + assert!(vector.write_signed_byte(33).is_ok()); + + vector.set_position(0); + + assert_eq!(-43, vector.read_signed_byte().unwrap()); + assert_eq!(33, vector.read_signed_byte().unwrap()); + + } + +}
--- a/src/io/operations/mod.rs +++ b/src/io/operations/mod.rs @@ ... @@ pub mod writer; + +#[cfg(test)] +mod test { + + use super::reader::Reader; + use super::writer::Writer; + + use std::io::Cursor; + + impl Writer for Cursor<Vec<u8>> { + + } + + impl Reader for Cursor<Vec<u8>> { + + } + + #[test] + fn test_read_write_u8() { + + let mut vector = Cursor::new(vec![0u8; 0]); + + assert!(vector.write_unsigned_byte(15).is_ok()); + assert!(vector.write_unsigned_byte(62).is_ok()); + + vector.set_position(0); + + assert_eq!(15, vector.read_unsigned_byte().unwrap()); + assert_eq!(62, vector.read_unsigned_byte().unwrap()); + + } + + #[test] + fn test_read_write_i8() { + + let mut vector = Cursor::new(vec![0u8; 0]); + + assert!(vector.write_signed_byte(-43).is_ok()); + assert!(vector.write_signed_byte(33).is_ok()); + + vector.set_position(0); + + assert_eq!(-43, vector.read_signed_byte().unwrap()); + assert_eq!(33, vector.read_signed_byte().unwrap()); + + } + +}
--- a/src/io/operations/mod.rs +++ b/src/io/operations/mod.rs @@ -7 +7,49 @@ CON pub mod writer; ADD ADD #[cfg(test)] ADD mod test { ADD ADD use super::reader::Reader; ADD use super::writer::Writer; ADD ADD use std::io::Cursor; ADD ADD impl Writer for Cursor<Vec<u8>> { ADD ADD } ADD ADD impl Reader for Cursor<Vec<u8>> { ADD ADD } ADD ADD #[test] ADD fn test_read_write_u8() { ADD ADD let mut vector = Cursor::new(vec![0u8; 0]); ADD ADD assert!(vector.write_unsigned_byte(15).is_ok()); ADD assert!(vector.write_unsigned_byte(62).is_ok()); ADD ADD vector.set_position(0); ADD ADD assert_eq!(15, vector.read_unsigned_byte().unwrap()); ADD assert_eq!(62, vector.read_unsigned_byte().unwrap()); ADD ADD } ADD ADD #[test] ADD fn test_read_write_i8() { ADD ADD let mut vector = Cursor::new(vec![0u8; 0]); ADD ADD assert!(vector.write_signed_byte(-43).is_ok()); ADD assert!(vector.write_signed_byte(33).is_ok()); ADD ADD vector.set_position(0); ADD ADD assert_eq!(-43, vector.read_signed_byte().unwrap()); ADD assert_eq!(33, vector.read_signed_byte().unwrap()); ADD ADD } ADD ADD }
<<<<<<< SEARCH pub mod writer; ======= pub mod writer; #[cfg(test)] mod test { use super::reader::Reader; use super::writer::Writer; use std::io::Cursor; impl Writer for Cursor<Vec<u8>> { } impl Reader for Cursor<Vec<u8>> { } #[test] fn test_read_write_u8() { let mut vector = Cursor::new(vec![0u8; 0]); assert!(vector.write_unsigned_byte(15).is_ok()); assert!(vector.write_unsigned_byte(62).is_ok()); vector.set_position(0); assert_eq!(15, vector.read_unsigned_byte().unwrap()); assert_eq!(62, vector.read_unsigned_byte().unwrap()); } #[test] fn test_read_write_i8() { let mut vector = Cursor::new(vec![0u8; 0]); assert!(vector.write_signed_byte(-43).is_ok()); assert!(vector.write_signed_byte(33).is_ok()); vector.set_position(0); assert_eq!(-43, vector.read_signed_byte().unwrap()); assert_eq!(33, vector.read_signed_byte().unwrap()); } } >>>>>>> REPLACE
graphman65/linter-vhdl
3e10f0e640f4fd51007dd5c3dd966fc57f9b4550
lib/main.js
javascript
mit
Fix code to follow eslint rules
'use babel'; /* global atom */ import { exec } from 'child-process-promise'; import { dirname } from 'path'; export default { config: { vhdlCompiler: { title: 'VHDL Compiler', description: 'Path to your vhdl compiler', type: 'string', default: 'ghdl', }, }, provideLinter() { return { name: 'Vhdl Linter', scope: 'file', lintsOnChange: false, grammarScopes: ['source.vhdl'], lint: async (textEditor) => { const errorRegex = /.*.vhd:([0-9]+):([0-9]+): (.*)/g; const editorPath = textEditor.getPath(); const compiler = atom.config.get('linter-vhdl.vhdlCompiler'); const options = { cwd: dirname(editorPath) }; var results = []; try { await exec(`"${compiler}" -a "${editorPath}"`, options); } catch ({ stderr }) { var regexResult; while ((regexResult = errorRegex.exec(stderr)) !== null) { const [, line, col, message] = regexResult; const range = [[(+line) - 1, (+col) - 1], [(+line) - 1, 1000]]; results.push({ severity: 'error', location: { file: editorPath, position: range, }, excerpt: message, description: message, }); } } return results; }, }; }, };
'use babel'; /* global atom */ import { exec } from 'child-process-promise'; import { dirname } from 'path'; export default { config: { vhdlCompiler: { title: 'VHDL Compiler', description: 'Path to your vhdl compiler', type: 'string', default: 'ghdl', }, }, provideLinter() { return { name: 'Vhdl Linter', scope: 'file', lintsOnChange: false, grammarScopes: ['source.vhdl'], lint: async (textEditor) => { const errorRegex = /.*.vhd:([0-9]+):([0-9]+): (.*)/g; const editorPath = textEditor.getPath(); const compiler = atom.config.get('linter-vhdl.vhdlCompiler'); const options = { cwd: dirname(editorPath) }; const results = []; try { await exec(`"${compiler}" -a "${editorPath}"`, options); } catch ({ stderr }) { let regexResult = errorRegex.exec(stderr); while (regexResult !== null) { const [, line, col, message] = regexResult; const range = [[(+line) - 1, (+col) - 1], [(+line) - 1, 1000]]; results.push({ severity: 'error', location: { file: editorPath, position: range, }, excerpt: message, description: message, }); regexResult = errorRegex.exec(stderr); } } return results; }, }; }, };
4
3
3
mixed
--- a/lib/main.js +++ b/lib/main.js @@ -27,3 +27,3 @@ const options = { cwd: dirname(editorPath) }; - var results = []; + const results = []; try { @@ -31,4 +31,4 @@ } catch ({ stderr }) { - var regexResult; - while ((regexResult = errorRegex.exec(stderr)) !== null) { + let regexResult = errorRegex.exec(stderr); + while (regexResult !== null) { const [, line, col, message] = regexResult; @@ -44,2 +44,3 @@ }); + regexResult = errorRegex.exec(stderr); }
--- a/lib/main.js +++ b/lib/main.js @@ ... @@ const options = { cwd: dirname(editorPath) }; - var results = []; + const results = []; try { @@ ... @@ } catch ({ stderr }) { - var regexResult; - while ((regexResult = errorRegex.exec(stderr)) !== null) { + let regexResult = errorRegex.exec(stderr); + while (regexResult !== null) { const [, line, col, message] = regexResult; @@ ... @@ }); + regexResult = errorRegex.exec(stderr); }
--- a/lib/main.js +++ b/lib/main.js @@ -27,3 +27,3 @@ CON const options = { cwd: dirname(editorPath) }; DEL var results = []; ADD const results = []; CON try { @@ -31,4 +31,4 @@ CON } catch ({ stderr }) { DEL var regexResult; DEL while ((regexResult = errorRegex.exec(stderr)) !== null) { ADD let regexResult = errorRegex.exec(stderr); ADD while (regexResult !== null) { CON const [, line, col, message] = regexResult; @@ -44,2 +44,3 @@ CON }); ADD regexResult = errorRegex.exec(stderr); CON }
<<<<<<< SEARCH const compiler = atom.config.get('linter-vhdl.vhdlCompiler'); const options = { cwd: dirname(editorPath) }; var results = []; try { await exec(`"${compiler}" -a "${editorPath}"`, options); } catch ({ stderr }) { var regexResult; while ((regexResult = errorRegex.exec(stderr)) !== null) { const [, line, col, message] = regexResult; const range = [[(+line) - 1, (+col) - 1], [(+line) - 1, 1000]]; ======= const compiler = atom.config.get('linter-vhdl.vhdlCompiler'); const options = { cwd: dirname(editorPath) }; const results = []; try { await exec(`"${compiler}" -a "${editorPath}"`, options); } catch ({ stderr }) { let regexResult = errorRegex.exec(stderr); while (regexResult !== null) { const [, line, col, message] = regexResult; const range = [[(+line) - 1, (+col) - 1], [(+line) - 1, 1000]]; >>>>>>> REPLACE <<<<<<< SEARCH description: message, }); } } ======= description: message, }); regexResult = errorRegex.exec(stderr); } } >>>>>>> REPLACE
sjolicoeur/pivotal-ui
a92b96355bf7596c76b3fc7d751beb9fb6f7d2d6
styleguide/docs/react/copy-to-clipboard.js
javascript
mit
chore(styleguide): Add a note to the copy to clipboard example on styleguide
/*doc --- title: Copy To Clipboard name: copy_to_clipboard_react categories: - react_components_copy-to-clipboard - react_all --- <code class="pam"> <i class="fa fa-download" alt="Install the Component"></i> npm install pui-react-copy-to-clipboard --save </code> Require the subcomponents: ``` var CopyToClipboard = require('pui-react-copy-to-clipboard').CopyToClipboard; var CopyToClipboardButton = require('pui-react-copy-to-clipboard').CopyToClipboardButton; ``` ```react_example_table <CopyToClipboard text="I got copied by a button"><button>Click Me To Copy</button></CopyToClipboard> <CopyToClipboardButton text="I got copied by a good looking button"/> ``` The CopyToClipboard Components require the following property: Property | Type | Description ------------- | --------------| -------------------------------------------------------------------------- `text` | String | Text that is copied when the user clicks Below is a common example combining a readonly input and a copy button: ``` var Input = require('pui-react-inputs').Input ``` ```react_example_table <div className="copy-input"> <Input label="shareable link" value="bar.com/1234.jpg" readOnly /> <CopyToClipboardButton text="bar.com/1234.jpg"/> </div> ``` */
/*doc --- title: Copy To Clipboard name: copy_to_clipboard_react categories: - react_components_copy-to-clipboard - react_all --- <code class="pam"> <i class="fa fa-download" alt="Install the Component"></i> npm install pui-react-copy-to-clipboard --save </code> Require the subcomponents: ``` var CopyToClipboard = require('pui-react-copy-to-clipboard').CopyToClipboard; var CopyToClipboardButton = require('pui-react-copy-to-clipboard').CopyToClipboardButton; ``` ```react_example_table <CopyToClipboard text="I got copied by a button"><button>Click Me To Copy</button></CopyToClipboard> <CopyToClipboardButton text="I got copied by a good looking button"/> ``` The CopyToClipboard Components require the following property: Property | Type | Description ------------- | --------------| -------------------------------------------------------------------------- `text` | String | Text that is copied when the user clicks Below is a common example combining a readonly input and a copy button. Note that there is custom css on the styleguide to get the positioning right. ``` var Input = require('pui-react-inputs').Input ``` ```react_example_table <div className="copy-input"> <Input label="shareable link" value="bar.com/1234.jpg" readOnly /> <CopyToClipboardButton text="bar.com/1234.jpg"/> </div> ``` */
2
1
1
mixed
--- a/styleguide/docs/react/copy-to-clipboard.js +++ b/styleguide/docs/react/copy-to-clipboard.js @@ -35,3 +35,4 @@ -Below is a common example combining a readonly input and a copy button: +Below is a common example combining a readonly input and a copy button. +Note that there is custom css on the styleguide to get the positioning right.
--- a/styleguide/docs/react/copy-to-clipboard.js +++ b/styleguide/docs/react/copy-to-clipboard.js @@ ... @@ -Below is a common example combining a readonly input and a copy button: +Below is a common example combining a readonly input and a copy button. +Note that there is custom css on the styleguide to get the positioning right.
--- a/styleguide/docs/react/copy-to-clipboard.js +++ b/styleguide/docs/react/copy-to-clipboard.js @@ -35,3 +35,4 @@ CON DEL Below is a common example combining a readonly input and a copy button: ADD Below is a common example combining a readonly input and a copy button. ADD Note that there is custom css on the styleguide to get the positioning right. CON
<<<<<<< SEARCH Below is a common example combining a readonly input and a copy button: ``` ======= Below is a common example combining a readonly input and a copy button. Note that there is custom css on the styleguide to get the positioning right. ``` >>>>>>> REPLACE
radishengine/drowsy
aed2b5068e73b430967aab8edb29393ad9f2a8dc
mac/resources/open_ATXT.js
javascript
mit
Add text window data fields
define(['mac/roman'], function(macintoshRoman) { 'use strict'; return function(item) { return item.getBytes().then(function(bytes) { var text = macintoshRoman(bytes, 0, bytes.length); debugger; }); }; });
define(['mac/roman'], function(macintoshRoman) { 'use strict'; function open(item) { return item.getBytes().then(function(bytes) { item.setDataObject(new TextView(bytes.buffer, bytes.byteOffset, bytes.byteLength)); }); }; function TextView(buffer, byteOffset, byteLength) { this.dataView = new DataView(buffer, byteOffset, byteLength); }; TextView.prototype = { toJSON: function() { return { top: this.top, left: this.left, bottom: this.bottom, right: this.right, fontType: this.fontType, fontSize: this.fontSize, text: this.text, }; }, get top() { return this.dataView.getInt16(0, false); }, get left() { return this.dataView.getInt16(2, false); }, get bottom() { return this.dataView.getInt16(4, false); }, get right() { return this.dataView.getInt16(6, false); }, get fontType() { return this.dataView.getUint16(8, false); }, get fontSize() { return this.dataView.getUint16(10, false); }, get text() { return macRoman(this.bytes, 12); }, }; return open; });
42
3
1
mixed
--- a/mac/resources/open_ATXT.js +++ b/mac/resources/open_ATXT.js @@ -4,8 +4,47 @@ - return function(item) { + function open(item) { return item.getBytes().then(function(bytes) { - var text = macintoshRoman(bytes, 0, bytes.length); - debugger; + item.setDataObject(new TextView(bytes.buffer, bytes.byteOffset, bytes.byteLength)); }); }; + + function TextView(buffer, byteOffset, byteLength) { + this.dataView = new DataView(buffer, byteOffset, byteLength); + }; + TextView.prototype = { + toJSON: function() { + return { + top: this.top, + left: this.left, + bottom: this.bottom, + right: this.right, + fontType: this.fontType, + fontSize: this.fontSize, + text: this.text, + }; + }, + get top() { + return this.dataView.getInt16(0, false); + }, + get left() { + return this.dataView.getInt16(2, false); + }, + get bottom() { + return this.dataView.getInt16(4, false); + }, + get right() { + return this.dataView.getInt16(6, false); + }, + get fontType() { + return this.dataView.getUint16(8, false); + }, + get fontSize() { + return this.dataView.getUint16(10, false); + }, + get text() { + return macRoman(this.bytes, 12); + }, + }; + + return open;
--- a/mac/resources/open_ATXT.js +++ b/mac/resources/open_ATXT.js @@ ... @@ - return function(item) { + function open(item) { return item.getBytes().then(function(bytes) { - var text = macintoshRoman(bytes, 0, bytes.length); - debugger; + item.setDataObject(new TextView(bytes.buffer, bytes.byteOffset, bytes.byteLength)); }); }; + + function TextView(buffer, byteOffset, byteLength) { + this.dataView = new DataView(buffer, byteOffset, byteLength); + }; + TextView.prototype = { + toJSON: function() { + return { + top: this.top, + left: this.left, + bottom: this.bottom, + right: this.right, + fontType: this.fontType, + fontSize: this.fontSize, + text: this.text, + }; + }, + get top() { + return this.dataView.getInt16(0, false); + }, + get left() { + return this.dataView.getInt16(2, false); + }, + get bottom() { + return this.dataView.getInt16(4, false); + }, + get right() { + return this.dataView.getInt16(6, false); + }, + get fontType() { + return this.dataView.getUint16(8, false); + }, + get fontSize() { + return this.dataView.getUint16(10, false); + }, + get text() { + return macRoman(this.bytes, 12); + }, + }; + + return open;
--- a/mac/resources/open_ATXT.js +++ b/mac/resources/open_ATXT.js @@ -4,8 +4,47 @@ CON DEL return function(item) { ADD function open(item) { CON return item.getBytes().then(function(bytes) { DEL var text = macintoshRoman(bytes, 0, bytes.length); DEL debugger; ADD item.setDataObject(new TextView(bytes.buffer, bytes.byteOffset, bytes.byteLength)); CON }); CON }; ADD ADD function TextView(buffer, byteOffset, byteLength) { ADD this.dataView = new DataView(buffer, byteOffset, byteLength); ADD }; ADD TextView.prototype = { ADD toJSON: function() { ADD return { ADD top: this.top, ADD left: this.left, ADD bottom: this.bottom, ADD right: this.right, ADD fontType: this.fontType, ADD fontSize: this.fontSize, ADD text: this.text, ADD }; ADD }, ADD get top() { ADD return this.dataView.getInt16(0, false); ADD }, ADD get left() { ADD return this.dataView.getInt16(2, false); ADD }, ADD get bottom() { ADD return this.dataView.getInt16(4, false); ADD }, ADD get right() { ADD return this.dataView.getInt16(6, false); ADD }, ADD get fontType() { ADD return this.dataView.getUint16(8, false); ADD }, ADD get fontSize() { ADD return this.dataView.getUint16(10, false); ADD }, ADD get text() { ADD return macRoman(this.bytes, 12); ADD }, ADD }; ADD ADD return open; CON
<<<<<<< SEARCH 'use strict'; return function(item) { return item.getBytes().then(function(bytes) { var text = macintoshRoman(bytes, 0, bytes.length); debugger; }); }; }); ======= 'use strict'; function open(item) { return item.getBytes().then(function(bytes) { item.setDataObject(new TextView(bytes.buffer, bytes.byteOffset, bytes.byteLength)); }); }; function TextView(buffer, byteOffset, byteLength) { this.dataView = new DataView(buffer, byteOffset, byteLength); }; TextView.prototype = { toJSON: function() { return { top: this.top, left: this.left, bottom: this.bottom, right: this.right, fontType: this.fontType, fontSize: this.fontSize, text: this.text, }; }, get top() { return this.dataView.getInt16(0, false); }, get left() { return this.dataView.getInt16(2, false); }, get bottom() { return this.dataView.getInt16(4, false); }, get right() { return this.dataView.getInt16(6, false); }, get fontType() { return this.dataView.getUint16(8, false); }, get fontSize() { return this.dataView.getUint16(10, false); }, get text() { return macRoman(this.bytes, 12); }, }; return open; }); >>>>>>> REPLACE
joseph-roque/BowlingCompanion
a490eb5244d48d4255c47db4fe7c2377c2b525c2
app/src/main/java/ca/josephroque/bowlingcompanion/utils/Changelog.kt
kotlin
mit
Use existing function to ignore deprecation
package ca.josephroque.bowlingcompanion.utils import android.content.Context import android.os.Build import android.support.v7.app.AlertDialog import android.support.v7.widget.Toolbar import ca.josephroque.bowlingcompanion.R import android.widget.TextView import android.text.Html import android.view.View /** * Copyright (C) 2018 Joseph Roque * * Provides utilities to handle displaying the changelog of the application to the user * each time a new update becomes available. */ object Changelog { fun show(context: Context) { // FIXME: try to use ScrollableTextDialog instead of this custom alert dialog val changelogText = Files.retrieveTextFileAsset(context, "changelog.txt") ?: return val dialog = AlertDialog.Builder(context) val rootView = View.inflate(context, R.layout.dialog_scrollable_text, null) dialog.setView(rootView) val alertDialog = dialog.create() // Setting text of changelog based on Android SDK version if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { rootView.findViewById<TextView>(R.id.tv_scrollable).text = Html.fromHtml(changelogText.replace("\n", "<br />"), 0) } else { rootView.findViewById<TextView>(R.id.tv_scrollable).text = Html.fromHtml(changelogText.replace("\n", "<br />")) } rootView.findViewById<Toolbar>(R.id.toolbar_scrollable).apply { setTitle(R.string.changelog) setNavigationIcon(R.drawable.ic_dismiss) setNavigationOnClickListener { alertDialog.dismiss() } } alertDialog.show() } }
package ca.josephroque.bowlingcompanion.utils import android.content.Context import android.support.v7.app.AlertDialog import android.support.v7.widget.Toolbar import ca.josephroque.bowlingcompanion.R import android.widget.TextView import android.view.View /** * Copyright (C) 2018 Joseph Roque * * Provides utilities to handle displaying the changelog of the application to the user * each time a new update becomes available. */ object Changelog { fun show(context: Context) { // FIXME: try to use ScrollableTextDialog instead of this custom alert dialog val changelogText = Files.retrieveTextFileAsset(context, "changelog.txt") ?: return val dialog = AlertDialog.Builder(context) val rootView = View.inflate(context, R.layout.dialog_scrollable_text, null) dialog.setView(rootView) val alertDialog = dialog.create() rootView.findViewById<TextView>(R.id.tv_scrollable).text = changelogText.replace("\n", "<br />").toSpanned() rootView.findViewById<Toolbar>(R.id.toolbar_scrollable).apply { setTitle(R.string.changelog) setNavigationIcon(R.drawable.ic_dismiss) setNavigationOnClickListener { alertDialog.dismiss() } } alertDialog.show() } }
1
8
3
mixed
--- a/app/src/main/java/ca/josephroque/bowlingcompanion/utils/Changelog.kt +++ b/app/src/main/java/ca/josephroque/bowlingcompanion/utils/Changelog.kt @@ -3,3 +3,2 @@ import android.content.Context -import android.os.Build import android.support.v7.app.AlertDialog @@ -8,3 +7,2 @@ import android.widget.TextView -import android.text.Html import android.view.View @@ -29,8 +27,3 @@ - // Setting text of changelog based on Android SDK version - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { - rootView.findViewById<TextView>(R.id.tv_scrollable).text = Html.fromHtml(changelogText.replace("\n", "<br />"), 0) - } else { - rootView.findViewById<TextView>(R.id.tv_scrollable).text = Html.fromHtml(changelogText.replace("\n", "<br />")) - } + rootView.findViewById<TextView>(R.id.tv_scrollable).text = changelogText.replace("\n", "<br />").toSpanned()
--- a/app/src/main/java/ca/josephroque/bowlingcompanion/utils/Changelog.kt +++ b/app/src/main/java/ca/josephroque/bowlingcompanion/utils/Changelog.kt @@ ... @@ import android.content.Context -import android.os.Build import android.support.v7.app.AlertDialog @@ ... @@ import android.widget.TextView -import android.text.Html import android.view.View @@ ... @@ - // Setting text of changelog based on Android SDK version - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { - rootView.findViewById<TextView>(R.id.tv_scrollable).text = Html.fromHtml(changelogText.replace("\n", "<br />"), 0) - } else { - rootView.findViewById<TextView>(R.id.tv_scrollable).text = Html.fromHtml(changelogText.replace("\n", "<br />")) - } + rootView.findViewById<TextView>(R.id.tv_scrollable).text = changelogText.replace("\n", "<br />").toSpanned()
--- a/app/src/main/java/ca/josephroque/bowlingcompanion/utils/Changelog.kt +++ b/app/src/main/java/ca/josephroque/bowlingcompanion/utils/Changelog.kt @@ -3,3 +3,2 @@ CON import android.content.Context DEL import android.os.Build CON import android.support.v7.app.AlertDialog @@ -8,3 +7,2 @@ CON import android.widget.TextView DEL import android.text.Html CON import android.view.View @@ -29,8 +27,3 @@ CON DEL // Setting text of changelog based on Android SDK version DEL if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { DEL rootView.findViewById<TextView>(R.id.tv_scrollable).text = Html.fromHtml(changelogText.replace("\n", "<br />"), 0) DEL } else { DEL rootView.findViewById<TextView>(R.id.tv_scrollable).text = Html.fromHtml(changelogText.replace("\n", "<br />")) DEL } ADD rootView.findViewById<TextView>(R.id.tv_scrollable).text = changelogText.replace("\n", "<br />").toSpanned() CON
<<<<<<< SEARCH import android.content.Context import android.os.Build import android.support.v7.app.AlertDialog import android.support.v7.widget.Toolbar import ca.josephroque.bowlingcompanion.R import android.widget.TextView import android.text.Html import android.view.View ======= import android.content.Context import android.support.v7.app.AlertDialog import android.support.v7.widget.Toolbar import ca.josephroque.bowlingcompanion.R import android.widget.TextView import android.view.View >>>>>>> REPLACE <<<<<<< SEARCH val alertDialog = dialog.create() // Setting text of changelog based on Android SDK version if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { rootView.findViewById<TextView>(R.id.tv_scrollable).text = Html.fromHtml(changelogText.replace("\n", "<br />"), 0) } else { rootView.findViewById<TextView>(R.id.tv_scrollable).text = Html.fromHtml(changelogText.replace("\n", "<br />")) } rootView.findViewById<Toolbar>(R.id.toolbar_scrollable).apply { ======= val alertDialog = dialog.create() rootView.findViewById<TextView>(R.id.tv_scrollable).text = changelogText.replace("\n", "<br />").toSpanned() rootView.findViewById<Toolbar>(R.id.toolbar_scrollable).apply { >>>>>>> REPLACE
mneumann/hypernsga
ac9ca231b5f4c85064569d67361ff7a2b98947c6
src/behavioral_bitvec.rs
rust
mit
Add hamming distance and test cases
use primal_bit::BitVec; pub struct BehavioralBitvec { bitvec: BitVec, bitpos: usize, } impl BehavioralBitvec { pub fn new(n: usize) -> Self { BehavioralBitvec { bitvec: BitVec::from_elem(n, false), bitpos: 0, } } #[inline] pub fn push(&mut self, output: f64) { if output >= 0.0 { self.bitvec.set(self.bitpos, true); } self.bitpos += 1; } }
use primal_bit::BitVec; use hamming; pub struct BehavioralBitvec { bitvec: BitVec, bitpos: usize, } impl BehavioralBitvec { pub fn new(n: usize) -> Self { BehavioralBitvec { bitvec: BitVec::from_elem(n, false), bitpos: 0, } } pub fn hamming_distance(&self, other: &Self) -> u64 { hamming::distance_fast(self.bitvec.as_bytes(), other.bitvec.as_bytes()).unwrap() } #[inline] pub fn push(&mut self, output: f64) { if output >= 0.0 { self.bitvec.set(self.bitpos, true); } self.bitpos += 1; } } #[test] fn test_behavioral_bitvec() { let mut a = BehavioralBitvec::new(3); let mut b = BehavioralBitvec::new(3); // [1, 1, 0] a.push(1.0); a.push(2.0); a.push(-1.0); let ba: Vec<_> = a.bitvec.iter().collect(); // [0, 1, 1] b.push(-1.0); b.push(1.0); b.push(1.0); let bb: Vec<_> = b.bitvec.iter().collect(); assert_eq!(vec![true, true, false], ba); assert_eq!(vec![false, true, true], bb); let d1 = a.hamming_distance(&b); let d2 = b.hamming_distance(&a); assert_eq!(d1, d2); assert_eq!(2, d1); }
31
0
3
add_only
--- a/src/behavioral_bitvec.rs +++ b/src/behavioral_bitvec.rs @@ -1,2 +1,3 @@ use primal_bit::BitVec; +use hamming; @@ -15,2 +16,6 @@ + pub fn hamming_distance(&self, other: &Self) -> u64 { + hamming::distance_fast(self.bitvec.as_bytes(), other.bitvec.as_bytes()).unwrap() + } + #[inline] @@ -24 +29,27 @@ +#[test] +fn test_behavioral_bitvec() { + let mut a = BehavioralBitvec::new(3); + let mut b = BehavioralBitvec::new(3); + + // [1, 1, 0] + a.push(1.0); + a.push(2.0); + a.push(-1.0); + let ba: Vec<_> = a.bitvec.iter().collect(); + + // [0, 1, 1] + b.push(-1.0); + b.push(1.0); + b.push(1.0); + let bb: Vec<_> = b.bitvec.iter().collect(); + + assert_eq!(vec![true, true, false], ba); + assert_eq!(vec![false, true, true], bb); + + let d1 = a.hamming_distance(&b); + let d2 = b.hamming_distance(&a); + + assert_eq!(d1, d2); + assert_eq!(2, d1); +}
--- a/src/behavioral_bitvec.rs +++ b/src/behavioral_bitvec.rs @@ ... @@ use primal_bit::BitVec; +use hamming; @@ ... @@ + pub fn hamming_distance(&self, other: &Self) -> u64 { + hamming::distance_fast(self.bitvec.as_bytes(), other.bitvec.as_bytes()).unwrap() + } + #[inline] @@ ... @@ +#[test] +fn test_behavioral_bitvec() { + let mut a = BehavioralBitvec::new(3); + let mut b = BehavioralBitvec::new(3); + + // [1, 1, 0] + a.push(1.0); + a.push(2.0); + a.push(-1.0); + let ba: Vec<_> = a.bitvec.iter().collect(); + + // [0, 1, 1] + b.push(-1.0); + b.push(1.0); + b.push(1.0); + let bb: Vec<_> = b.bitvec.iter().collect(); + + assert_eq!(vec![true, true, false], ba); + assert_eq!(vec![false, true, true], bb); + + let d1 = a.hamming_distance(&b); + let d2 = b.hamming_distance(&a); + + assert_eq!(d1, d2); + assert_eq!(2, d1); +}
--- a/src/behavioral_bitvec.rs +++ b/src/behavioral_bitvec.rs @@ -1,2 +1,3 @@ CON use primal_bit::BitVec; ADD use hamming; CON @@ -15,2 +16,6 @@ CON ADD pub fn hamming_distance(&self, other: &Self) -> u64 { ADD hamming::distance_fast(self.bitvec.as_bytes(), other.bitvec.as_bytes()).unwrap() ADD } ADD CON #[inline] @@ -24 +29,27 @@ CON ADD #[test] ADD fn test_behavioral_bitvec() { ADD let mut a = BehavioralBitvec::new(3); ADD let mut b = BehavioralBitvec::new(3); ADD ADD // [1, 1, 0] ADD a.push(1.0); ADD a.push(2.0); ADD a.push(-1.0); ADD let ba: Vec<_> = a.bitvec.iter().collect(); ADD ADD // [0, 1, 1] ADD b.push(-1.0); ADD b.push(1.0); ADD b.push(1.0); ADD let bb: Vec<_> = b.bitvec.iter().collect(); ADD ADD assert_eq!(vec![true, true, false], ba); ADD assert_eq!(vec![false, true, true], bb); ADD ADD let d1 = a.hamming_distance(&b); ADD let d2 = b.hamming_distance(&a); ADD ADD assert_eq!(d1, d2); ADD assert_eq!(2, d1); ADD }
<<<<<<< SEARCH use primal_bit::BitVec; pub struct BehavioralBitvec { ======= use primal_bit::BitVec; use hamming; pub struct BehavioralBitvec { >>>>>>> REPLACE <<<<<<< SEARCH } #[inline] pub fn push(&mut self, output: f64) { ======= } pub fn hamming_distance(&self, other: &Self) -> u64 { hamming::distance_fast(self.bitvec.as_bytes(), other.bitvec.as_bytes()).unwrap() } #[inline] pub fn push(&mut self, output: f64) { >>>>>>> REPLACE <<<<<<< SEARCH } ======= } #[test] fn test_behavioral_bitvec() { let mut a = BehavioralBitvec::new(3); let mut b = BehavioralBitvec::new(3); // [1, 1, 0] a.push(1.0); a.push(2.0); a.push(-1.0); let ba: Vec<_> = a.bitvec.iter().collect(); // [0, 1, 1] b.push(-1.0); b.push(1.0); b.push(1.0); let bb: Vec<_> = b.bitvec.iter().collect(); assert_eq!(vec![true, true, false], ba); assert_eq!(vec![false, true, true], bb); let d1 = a.hamming_distance(&b); let d2 = b.hamming_distance(&a); assert_eq!(d1, d2); assert_eq!(2, d1); } >>>>>>> REPLACE
Sushma7785/OpenDayLight-Load-Balancer
97942010558a4b3e242b66607c1f62742a29e00f
opendaylight/netconf/config-netconf-connector/src/main/java/org/opendaylight/controller/netconf/confignetconfconnector/osgi/YangStoreServiceImpl.java
java
epl-1.0
Store yang store snapshot cache using soft reference. Change-Id: I9b159db83ba204b4a636f2314fd4fc2e7b6f654c Signed-off-by: Tomas Olvecky <[email protected]>
/* * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ package org.opendaylight.controller.netconf.confignetconfconnector.osgi; import org.opendaylight.yangtools.yang.model.api.SchemaContextProvider; import javax.annotation.concurrent.GuardedBy; public class YangStoreServiceImpl implements YangStoreService { private final SchemaContextProvider service; @GuardedBy("this") private YangStoreSnapshotImpl cache = null; public YangStoreServiceImpl(SchemaContextProvider service) { this.service = service; } @Override public synchronized YangStoreSnapshotImpl getYangStoreSnapshot() throws YangStoreException { if (cache == null) { cache = new YangStoreSnapshotImpl(service.getSchemaContext()); } return cache; } /** * Called when schema context changes, invalidates cache. */ public synchronized void refresh() { cache = null; } }
/* * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ package org.opendaylight.controller.netconf.confignetconfconnector.osgi; import java.lang.ref.SoftReference; import org.opendaylight.yangtools.yang.model.api.SchemaContextProvider; import javax.annotation.concurrent.GuardedBy; public class YangStoreServiceImpl implements YangStoreService { private final SchemaContextProvider service; @GuardedBy("this") private SoftReference<YangStoreSnapshotImpl> cache = new SoftReference<>(null); public YangStoreServiceImpl(SchemaContextProvider service) { this.service = service; } @Override public synchronized YangStoreSnapshotImpl getYangStoreSnapshot() throws YangStoreException { YangStoreSnapshotImpl yangStoreSnapshot = cache.get(); if (yangStoreSnapshot == null) { yangStoreSnapshot = new YangStoreSnapshotImpl(service.getSchemaContext()); cache = new SoftReference<>(yangStoreSnapshot); } return yangStoreSnapshot; } /** * Called when schema context changes, invalidates cache. */ public synchronized void refresh() { cache.clear(); } }
8
5
4
mixed
--- a/opendaylight/netconf/config-netconf-connector/src/main/java/org/opendaylight/controller/netconf/confignetconfconnector/osgi/YangStoreServiceImpl.java +++ b/opendaylight/netconf/config-netconf-connector/src/main/java/org/opendaylight/controller/netconf/confignetconfconnector/osgi/YangStoreServiceImpl.java @@ -10,2 +10,3 @@ +import java.lang.ref.SoftReference; import org.opendaylight.yangtools.yang.model.api.SchemaContextProvider; @@ -17,3 +18,3 @@ @GuardedBy("this") - private YangStoreSnapshotImpl cache = null; + private SoftReference<YangStoreSnapshotImpl> cache = new SoftReference<>(null); @@ -25,6 +26,8 @@ public synchronized YangStoreSnapshotImpl getYangStoreSnapshot() throws YangStoreException { - if (cache == null) { - cache = new YangStoreSnapshotImpl(service.getSchemaContext()); + YangStoreSnapshotImpl yangStoreSnapshot = cache.get(); + if (yangStoreSnapshot == null) { + yangStoreSnapshot = new YangStoreSnapshotImpl(service.getSchemaContext()); + cache = new SoftReference<>(yangStoreSnapshot); } - return cache; + return yangStoreSnapshot; } @@ -35,3 +38,3 @@ public synchronized void refresh() { - cache = null; + cache.clear(); }
--- a/opendaylight/netconf/config-netconf-connector/src/main/java/org/opendaylight/controller/netconf/confignetconfconnector/osgi/YangStoreServiceImpl.java +++ b/opendaylight/netconf/config-netconf-connector/src/main/java/org/opendaylight/controller/netconf/confignetconfconnector/osgi/YangStoreServiceImpl.java @@ ... @@ +import java.lang.ref.SoftReference; import org.opendaylight.yangtools.yang.model.api.SchemaContextProvider; @@ ... @@ @GuardedBy("this") - private YangStoreSnapshotImpl cache = null; + private SoftReference<YangStoreSnapshotImpl> cache = new SoftReference<>(null); @@ ... @@ public synchronized YangStoreSnapshotImpl getYangStoreSnapshot() throws YangStoreException { - if (cache == null) { - cache = new YangStoreSnapshotImpl(service.getSchemaContext()); + YangStoreSnapshotImpl yangStoreSnapshot = cache.get(); + if (yangStoreSnapshot == null) { + yangStoreSnapshot = new YangStoreSnapshotImpl(service.getSchemaContext()); + cache = new SoftReference<>(yangStoreSnapshot); } - return cache; + return yangStoreSnapshot; } @@ ... @@ public synchronized void refresh() { - cache = null; + cache.clear(); }
--- a/opendaylight/netconf/config-netconf-connector/src/main/java/org/opendaylight/controller/netconf/confignetconfconnector/osgi/YangStoreServiceImpl.java +++ b/opendaylight/netconf/config-netconf-connector/src/main/java/org/opendaylight/controller/netconf/confignetconfconnector/osgi/YangStoreServiceImpl.java @@ -10,2 +10,3 @@ CON ADD import java.lang.ref.SoftReference; CON import org.opendaylight.yangtools.yang.model.api.SchemaContextProvider; @@ -17,3 +18,3 @@ CON @GuardedBy("this") DEL private YangStoreSnapshotImpl cache = null; ADD private SoftReference<YangStoreSnapshotImpl> cache = new SoftReference<>(null); CON @@ -25,6 +26,8 @@ CON public synchronized YangStoreSnapshotImpl getYangStoreSnapshot() throws YangStoreException { DEL if (cache == null) { DEL cache = new YangStoreSnapshotImpl(service.getSchemaContext()); ADD YangStoreSnapshotImpl yangStoreSnapshot = cache.get(); ADD if (yangStoreSnapshot == null) { ADD yangStoreSnapshot = new YangStoreSnapshotImpl(service.getSchemaContext()); ADD cache = new SoftReference<>(yangStoreSnapshot); CON } DEL return cache; ADD return yangStoreSnapshot; CON } @@ -35,3 +38,3 @@ CON public synchronized void refresh() { DEL cache = null; ADD cache.clear(); CON }
<<<<<<< SEARCH package org.opendaylight.controller.netconf.confignetconfconnector.osgi; import org.opendaylight.yangtools.yang.model.api.SchemaContextProvider; ======= package org.opendaylight.controller.netconf.confignetconfconnector.osgi; import java.lang.ref.SoftReference; import org.opendaylight.yangtools.yang.model.api.SchemaContextProvider; >>>>>>> REPLACE <<<<<<< SEARCH private final SchemaContextProvider service; @GuardedBy("this") private YangStoreSnapshotImpl cache = null; public YangStoreServiceImpl(SchemaContextProvider service) { ======= private final SchemaContextProvider service; @GuardedBy("this") private SoftReference<YangStoreSnapshotImpl> cache = new SoftReference<>(null); public YangStoreServiceImpl(SchemaContextProvider service) { >>>>>>> REPLACE <<<<<<< SEARCH @Override public synchronized YangStoreSnapshotImpl getYangStoreSnapshot() throws YangStoreException { if (cache == null) { cache = new YangStoreSnapshotImpl(service.getSchemaContext()); } return cache; } ======= @Override public synchronized YangStoreSnapshotImpl getYangStoreSnapshot() throws YangStoreException { YangStoreSnapshotImpl yangStoreSnapshot = cache.get(); if (yangStoreSnapshot == null) { yangStoreSnapshot = new YangStoreSnapshotImpl(service.getSchemaContext()); cache = new SoftReference<>(yangStoreSnapshot); } return yangStoreSnapshot; } >>>>>>> REPLACE <<<<<<< SEARCH */ public synchronized void refresh() { cache = null; } } ======= */ public synchronized void refresh() { cache.clear(); } } >>>>>>> REPLACE
BafS/Quaris
7d0b32e31b2d4bb9b994e6df0bfc076b82557225
spring-server/src/main/java/ch/heigvd/quaris/config/CorsFilter.java
java
mit
Fix preflights for all rules
package ch.heigvd.quaris.config; import org.springframework.core.Ordered; import org.springframework.core.annotation.Order; import org.springframework.stereotype.Component; import org.springframework.web.filter.OncePerRequestFilter; import javax.servlet.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * Created by Fabien Salathe on 26.01.17. */ @Component @Order(Ordered.HIGHEST_PRECEDENCE) public class CorsFilter extends OncePerRequestFilter { /** * Enable CORS * * @param request * @param response * @param filterChain * @throws ServletException * @throws IOException */ @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { response.addHeader("Access-Control-Allow-Origin", request.getHeader("Origin")); response.addHeader("Access-Control-Allow-Headers", "Origin, Content-Type, Accept, Access-Control-Request-Method, Authorization"); response.addHeader("Access-Control-Expose-Headers", "Origin, Content-Type, Accept, Access-Control-Request-Method, Authorization"); response.addHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS, PUT, DELETE"); filterChain.doFilter(request, response); } }
package ch.heigvd.quaris.config; import org.springframework.core.Ordered; import org.springframework.core.annotation.Order; import org.springframework.stereotype.Component; import org.springframework.web.filter.OncePerRequestFilter; import javax.servlet.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * Created by Fabien Salathe on 26.01.17. */ @Component @Order(Ordered.HIGHEST_PRECEDENCE) public class CorsFilter extends OncePerRequestFilter { /** * Enable CORS * * @param request * @param response * @param filterChain * @throws ServletException * @throws IOException */ @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { response.addHeader("Access-Control-Allow-Origin", request.getHeader("Origin")); response.addHeader("Access-Control-Allow-Headers", "Origin, Content-Type, Accept, Access-Control-Request-Method, Authorization"); response.addHeader("Access-Control-Expose-Headers", "Origin, Content-Type, Accept, Access-Control-Request-Method, Authorization"); response.addHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS, PUT, DELETE"); if (!request.getMethod().equals("OPTIONS")) { filterChain.doFilter(request, response); } } }
3
1
1
mixed
--- a/spring-server/src/main/java/ch/heigvd/quaris/config/CorsFilter.java +++ b/spring-server/src/main/java/ch/heigvd/quaris/config/CorsFilter.java @@ -35,3 +35,5 @@ - filterChain.doFilter(request, response); + if (!request.getMethod().equals("OPTIONS")) { + filterChain.doFilter(request, response); + } }
--- a/spring-server/src/main/java/ch/heigvd/quaris/config/CorsFilter.java +++ b/spring-server/src/main/java/ch/heigvd/quaris/config/CorsFilter.java @@ ... @@ - filterChain.doFilter(request, response); + if (!request.getMethod().equals("OPTIONS")) { + filterChain.doFilter(request, response); + } }
--- a/spring-server/src/main/java/ch/heigvd/quaris/config/CorsFilter.java +++ b/spring-server/src/main/java/ch/heigvd/quaris/config/CorsFilter.java @@ -35,3 +35,5 @@ CON DEL filterChain.doFilter(request, response); ADD if (!request.getMethod().equals("OPTIONS")) { ADD filterChain.doFilter(request, response); ADD } CON }
<<<<<<< SEARCH response.addHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS, PUT, DELETE"); filterChain.doFilter(request, response); } ======= response.addHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS, PUT, DELETE"); if (!request.getMethod().equals("OPTIONS")) { filterChain.doFilter(request, response); } } >>>>>>> REPLACE
rnelson/adventofcode
2446e54f60cbaa60b294dc640f118d9b3c5eebf9
advent2018/src/main/kotlin/com/github/rnelson/adventofcode/days/Day05.kt
kotlin
mit
Remove poorly formatted Python solution
package com.github.rnelson.adventofcode.days import com.github.rnelson.adventofcode.Day class Day05: Day() { init { super.setup("05") } override fun solveA(): String { var newInput = input[0] var letterFound = true while (letterFound) { letterFound = false for (c in 'a'..'z') { val oneMix = "${c.toUpperCase()}$c" val twoMix = "$c${c.toUpperCase()}" var found = true while (found) { val fOneMix = newInput.indexOf(oneMix) val fTwoMix = newInput.indexOf(twoMix) if (fOneMix != -1) { newInput = newInput.replace(oneMix, "") letterFound = true } else if (fTwoMix != -1) { newInput = newInput.replace(twoMix, "") letterFound = true } else { found = false } } } } return newInput.length.toString() } override fun solveB(): String { return "" } } //from string import ascii_lowercase // //new_input = INPUT // //letter_found = True //while letter_found: //letter_found = False //for c in ascii_lowercase: //one_mix = c.upper() + c //two_mix = c + c.upper() // //found = True //while found: //f_one_mix = new_input.find(one_mix) //f_two_mix = new_input.find(two_mix) // //if f_one_mix != -1: //new_input = new_input.replace(one_mix, '') //letter_found = True //elif f_two_mix != -1: //new_input = new_input.replace(two_mix, '') //letter_found = True //else: //found = False // //print(len(new_input))
package com.github.rnelson.adventofcode.days import com.github.rnelson.adventofcode.Day class Day05: Day() { init { super.setup("05") } override fun solveA(): String { var newInput = input[0] var letterFound = true while (letterFound) { letterFound = false for (c in 'a'..'z') { val oneMix = "${c.toUpperCase()}$c" val twoMix = "$c${c.toUpperCase()}" var found = true while (found) { val fOneMix = newInput.indexOf(oneMix) val fTwoMix = newInput.indexOf(twoMix) if (fOneMix != -1) { newInput = newInput.replace(oneMix, "") letterFound = true } else if (fTwoMix != -1) { newInput = newInput.replace(twoMix, "") letterFound = true } else { found = false } } } } return newInput.length.toString() } override fun solveB(): String { return "" } }
0
27
1
del_only
--- a/advent2018/src/main/kotlin/com/github/rnelson/adventofcode/days/Day05.kt +++ b/advent2018/src/main/kotlin/com/github/rnelson/adventofcode/days/Day05.kt @@ -47,28 +47 @@ } - -//from string import ascii_lowercase -// -//new_input = INPUT -// -//letter_found = True -//while letter_found: -//letter_found = False -//for c in ascii_lowercase: -//one_mix = c.upper() + c -//two_mix = c + c.upper() -// -//found = True -//while found: -//f_one_mix = new_input.find(one_mix) -//f_two_mix = new_input.find(two_mix) -// -//if f_one_mix != -1: -//new_input = new_input.replace(one_mix, '') -//letter_found = True -//elif f_two_mix != -1: -//new_input = new_input.replace(two_mix, '') -//letter_found = True -//else: -//found = False -// -//print(len(new_input))
--- a/advent2018/src/main/kotlin/com/github/rnelson/adventofcode/days/Day05.kt +++ b/advent2018/src/main/kotlin/com/github/rnelson/adventofcode/days/Day05.kt @@ ... @@ } - -//from string import ascii_lowercase -// -//new_input = INPUT -// -//letter_found = True -//while letter_found: -//letter_found = False -//for c in ascii_lowercase: -//one_mix = c.upper() + c -//two_mix = c + c.upper() -// -//found = True -//while found: -//f_one_mix = new_input.find(one_mix) -//f_two_mix = new_input.find(two_mix) -// -//if f_one_mix != -1: -//new_input = new_input.replace(one_mix, '') -//letter_found = True -//elif f_two_mix != -1: -//new_input = new_input.replace(two_mix, '') -//letter_found = True -//else: -//found = False -// -//print(len(new_input))
--- a/advent2018/src/main/kotlin/com/github/rnelson/adventofcode/days/Day05.kt +++ b/advent2018/src/main/kotlin/com/github/rnelson/adventofcode/days/Day05.kt @@ -47,28 +47 @@ CON } DEL DEL //from string import ascii_lowercase DEL // DEL //new_input = INPUT DEL // DEL //letter_found = True DEL //while letter_found: DEL //letter_found = False DEL //for c in ascii_lowercase: DEL //one_mix = c.upper() + c DEL //two_mix = c + c.upper() DEL // DEL //found = True DEL //while found: DEL //f_one_mix = new_input.find(one_mix) DEL //f_two_mix = new_input.find(two_mix) DEL // DEL //if f_one_mix != -1: DEL //new_input = new_input.replace(one_mix, '') DEL //letter_found = True DEL //elif f_two_mix != -1: DEL //new_input = new_input.replace(two_mix, '') DEL //letter_found = True DEL //else: DEL //found = False DEL // DEL //print(len(new_input))
<<<<<<< SEARCH return "" } } //from string import ascii_lowercase // //new_input = INPUT // //letter_found = True //while letter_found: //letter_found = False //for c in ascii_lowercase: //one_mix = c.upper() + c //two_mix = c + c.upper() // //found = True //while found: //f_one_mix = new_input.find(one_mix) //f_two_mix = new_input.find(two_mix) // //if f_one_mix != -1: //new_input = new_input.replace(one_mix, '') //letter_found = True //elif f_two_mix != -1: //new_input = new_input.replace(two_mix, '') //letter_found = True //else: //found = False // //print(len(new_input)) ======= return "" } } >>>>>>> REPLACE
ethauvin/kobalt
0dee89c8be4adad65ee804bf031bd07ee473fbe5
modules/kobalt-plugin-api/src/main/kotlin/com/beust/kobalt/TestDirective.kt
kotlin
apache-2.0
Clear the test configurations before adding new ones.
package com.beust.kobalt import com.beust.kobalt.api.Project import com.beust.kobalt.api.annotation.Directive class TestConfig(val project: Project) { val testArgs = arrayListOf<String>() val jvmArgs = arrayListOf<String>() val testIncludes = arrayListOf("**/*Test.class") val testExcludes = arrayListOf<String>() fun args(vararg arg: String) { testArgs.addAll(arg) } fun jvmArgs(vararg arg: String) { jvmArgs.addAll(arg) } fun includes(vararg arg: String) { testIncludes.apply { clear() addAll(arg) } } fun excludes(vararg arg: String) { testExcludes.apply { clear() addAll(arg) } } } @Directive fun Project.test(init: TestConfig.() -> Unit) = this.testConfigs.add(TestConfig(this).apply { init() })
package com.beust.kobalt import com.beust.kobalt.api.Project import com.beust.kobalt.api.annotation.Directive class TestConfig(val project: Project) { val testArgs = arrayListOf<String>() val jvmArgs = arrayListOf<String>() val testIncludes = arrayListOf("**/*Test.class") val testExcludes = arrayListOf<String>() fun args(vararg arg: String) { testArgs.addAll(arg) } fun jvmArgs(vararg arg: String) { jvmArgs.addAll(arg) } fun includes(vararg arg: String) { testIncludes.apply { clear() addAll(arg) } } fun excludes(vararg arg: String) { testExcludes.apply { clear() addAll(arg) } } } @Directive fun Project.test(init: TestConfig.() -> Unit) = let { project -> with(this.testConfigs) { clear() add(TestConfig(project).apply { init() }) } }
6
1
1
mixed
--- a/modules/kobalt-plugin-api/src/main/kotlin/com/beust/kobalt/TestDirective.kt +++ b/modules/kobalt-plugin-api/src/main/kotlin/com/beust/kobalt/TestDirective.kt @@ -35,2 +35,7 @@ @Directive -fun Project.test(init: TestConfig.() -> Unit) = this.testConfigs.add(TestConfig(this).apply { init() }) +fun Project.test(init: TestConfig.() -> Unit) = let { project -> + with(this.testConfigs) { + clear() + add(TestConfig(project).apply { init() }) + } +}
--- a/modules/kobalt-plugin-api/src/main/kotlin/com/beust/kobalt/TestDirective.kt +++ b/modules/kobalt-plugin-api/src/main/kotlin/com/beust/kobalt/TestDirective.kt @@ ... @@ @Directive -fun Project.test(init: TestConfig.() -> Unit) = this.testConfigs.add(TestConfig(this).apply { init() }) +fun Project.test(init: TestConfig.() -> Unit) = let { project -> + with(this.testConfigs) { + clear() + add(TestConfig(project).apply { init() }) + } +}
--- a/modules/kobalt-plugin-api/src/main/kotlin/com/beust/kobalt/TestDirective.kt +++ b/modules/kobalt-plugin-api/src/main/kotlin/com/beust/kobalt/TestDirective.kt @@ -35,2 +35,7 @@ CON @Directive DEL fun Project.test(init: TestConfig.() -> Unit) = this.testConfigs.add(TestConfig(this).apply { init() }) ADD fun Project.test(init: TestConfig.() -> Unit) = let { project -> ADD with(this.testConfigs) { ADD clear() ADD add(TestConfig(project).apply { init() }) ADD } ADD }
<<<<<<< SEARCH @Directive fun Project.test(init: TestConfig.() -> Unit) = this.testConfigs.add(TestConfig(this).apply { init() }) ======= @Directive fun Project.test(init: TestConfig.() -> Unit) = let { project -> with(this.testConfigs) { clear() add(TestConfig(project).apply { init() }) } } >>>>>>> REPLACE
mfietz/fyydlin
b2830dda070ab7bf42d4530055b68806f0fe0203
src/main/kotlin/FyydClient.kt
kotlin
apache-2.0
Move constructor defaults to companion object
package de.mfietz.fyydlin import com.squareup.moshi.Moshi import com.squareup.moshi.Rfc3339DateJsonAdapter import okhttp3.OkHttpClient import retrofit2.Retrofit import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory import retrofit2.converter.moshi.MoshiConverterFactory import rx.Single import java.util.* class FyydClient( baseUrl: String = "https://api.fyyd.de", client: OkHttpClient = OkHttpClient() ) { val service: FyydService init { val moshi = Moshi.Builder() .add(Date::class.java, Rfc3339DateJsonAdapter()) .build() val retrofit = Retrofit.Builder() .baseUrl(baseUrl) .client(client) .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .addConverterFactory(MoshiConverterFactory.create(moshi)) .build() service = retrofit.create(FyydService::class.java) } fun findPodcasts(vararg query: String): Single<FyydResponse> { return service.findPodcast(query.joinToString(separator = ",")) } fun findPodcasts(vararg query: String, limit: Int): Single<FyydResponse> { return service.findPodcast(query.joinToString(separator = ","), limit.toString()) } }
package de.mfietz.fyydlin import com.squareup.moshi.Moshi import com.squareup.moshi.Rfc3339DateJsonAdapter import okhttp3.OkHttpClient import retrofit2.Retrofit import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory import retrofit2.converter.moshi.MoshiConverterFactory import rx.Single import java.util.* class FyydClient( client: OkHttpClient = defaultClient, baseUrl: String = defaultBaseUrl ) { companion object FyydClientDefaults { private val defaultClient by lazy { OkHttpClient() } private val defaultBaseUrl = "https://api.fyyd.de" } val service: FyydService init { val moshi = Moshi.Builder() .add(Date::class.java, Rfc3339DateJsonAdapter()) .build() val retrofit = Retrofit.Builder() .baseUrl(baseUrl) .client(client) .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .addConverterFactory(MoshiConverterFactory.create(moshi)) .build() service = retrofit.create(FyydService::class.java) } fun findPodcasts(vararg query: String): Single<FyydResponse> { return service.findPodcast(query.joinToString(separator = ",")) } fun findPodcasts(vararg query: String, limit: Int): Single<FyydResponse> { return service.findPodcast(query.joinToString(separator = ","), limit.toString()) } }
6
2
1
mixed
--- a/src/main/kotlin/FyydClient.kt +++ b/src/main/kotlin/FyydClient.kt @@ -12,6 +12,10 @@ class FyydClient( - baseUrl: String = "https://api.fyyd.de", - client: OkHttpClient = OkHttpClient() + client: OkHttpClient = defaultClient, + baseUrl: String = defaultBaseUrl ) { + companion object FyydClientDefaults { + private val defaultClient by lazy { OkHttpClient() } + private val defaultBaseUrl = "https://api.fyyd.de" + } val service: FyydService
--- a/src/main/kotlin/FyydClient.kt +++ b/src/main/kotlin/FyydClient.kt @@ ... @@ class FyydClient( - baseUrl: String = "https://api.fyyd.de", - client: OkHttpClient = OkHttpClient() + client: OkHttpClient = defaultClient, + baseUrl: String = defaultBaseUrl ) { + companion object FyydClientDefaults { + private val defaultClient by lazy { OkHttpClient() } + private val defaultBaseUrl = "https://api.fyyd.de" + } val service: FyydService
--- a/src/main/kotlin/FyydClient.kt +++ b/src/main/kotlin/FyydClient.kt @@ -12,6 +12,10 @@ CON class FyydClient( DEL baseUrl: String = "https://api.fyyd.de", DEL client: OkHttpClient = OkHttpClient() ADD client: OkHttpClient = defaultClient, ADD baseUrl: String = defaultBaseUrl CON ) { CON ADD companion object FyydClientDefaults { ADD private val defaultClient by lazy { OkHttpClient() } ADD private val defaultBaseUrl = "https://api.fyyd.de" ADD } CON val service: FyydService
<<<<<<< SEARCH class FyydClient( baseUrl: String = "https://api.fyyd.de", client: OkHttpClient = OkHttpClient() ) { val service: FyydService ======= class FyydClient( client: OkHttpClient = defaultClient, baseUrl: String = defaultBaseUrl ) { companion object FyydClientDefaults { private val defaultClient by lazy { OkHttpClient() } private val defaultBaseUrl = "https://api.fyyd.de" } val service: FyydService >>>>>>> REPLACE
LouisCAD/Splitties
320d9b7d54a720d4685b27d6d5b646f130265c5a
modules/views-dsl/build.gradle.kts
kotlin
apache-2.0
Remove no longer needed workaround that used old Kotlin backend
/* * Copyright 2019-2021 Louis Cognault Ayeva Derman. Use of this source code is governed by the Apache 2.0 license. */ plugins { id("com.android.library") kotlin("multiplatform") publish } android { setDefaults(generateBuildConfig = true) } kotlin { android() configure(targets) { configureMavenPublication(publishReleaseVariantOnly = false) } sourceSets { commonMain.dependencies { api(splitties("experimental")) } androidMain.dependencies { api(splitties("views")) api(AndroidX.annotation) implementation(splitties("collections")) implementation(splitties("exceptions")) implementation(splitties("appctx")) } all { languageSettings.apply { optIn("kotlin.contracts.ExperimentalContracts") optIn("splitties.experimental.InternalSplittiesApi") } } } } tasks.withType<org.jetbrains.kotlin.gradle.tasks.KotlinCompile> { kotlinOptions.useOldBackend = true //TODO: Remove when https://youtrack.jetbrains.com/issue/KT-44972 is addressed. // See this comment on why it's needed: https://youtrack.jetbrains.com/issue/KT-44972#focus=Comments-27-5014161.0-0 }
/* * Copyright 2019-2021 Louis Cognault Ayeva Derman. Use of this source code is governed by the Apache 2.0 license. */ plugins { id("com.android.library") kotlin("multiplatform") publish } android { setDefaults(generateBuildConfig = true) } kotlin { android() configure(targets) { configureMavenPublication(publishReleaseVariantOnly = false) } sourceSets { commonMain.dependencies { api(splitties("experimental")) } androidMain.dependencies { api(splitties("views")) api(AndroidX.annotation) implementation(splitties("collections")) implementation(splitties("exceptions")) implementation(splitties("appctx")) } all { languageSettings.apply { optIn("kotlin.contracts.ExperimentalContracts") optIn("splitties.experimental.InternalSplittiesApi") } } } }
0
5
1
del_only
--- a/modules/views-dsl/build.gradle.kts +++ b/modules/views-dsl/build.gradle.kts @@ -36,6 +36 @@ } - -tasks.withType<org.jetbrains.kotlin.gradle.tasks.KotlinCompile> { - kotlinOptions.useOldBackend = true //TODO: Remove when https://youtrack.jetbrains.com/issue/KT-44972 is addressed. - // See this comment on why it's needed: https://youtrack.jetbrains.com/issue/KT-44972#focus=Comments-27-5014161.0-0 -}
--- a/modules/views-dsl/build.gradle.kts +++ b/modules/views-dsl/build.gradle.kts @@ ... @@ } - -tasks.withType<org.jetbrains.kotlin.gradle.tasks.KotlinCompile> { - kotlinOptions.useOldBackend = true //TODO: Remove when https://youtrack.jetbrains.com/issue/KT-44972 is addressed. - // See this comment on why it's needed: https://youtrack.jetbrains.com/issue/KT-44972#focus=Comments-27-5014161.0-0 -}
--- a/modules/views-dsl/build.gradle.kts +++ b/modules/views-dsl/build.gradle.kts @@ -36,6 +36 @@ CON } DEL DEL tasks.withType<org.jetbrains.kotlin.gradle.tasks.KotlinCompile> { DEL kotlinOptions.useOldBackend = true //TODO: Remove when https://youtrack.jetbrains.com/issue/KT-44972 is addressed. DEL // See this comment on why it's needed: https://youtrack.jetbrains.com/issue/KT-44972#focus=Comments-27-5014161.0-0 DEL }
<<<<<<< SEARCH } } tasks.withType<org.jetbrains.kotlin.gradle.tasks.KotlinCompile> { kotlinOptions.useOldBackend = true //TODO: Remove when https://youtrack.jetbrains.com/issue/KT-44972 is addressed. // See this comment on why it's needed: https://youtrack.jetbrains.com/issue/KT-44972#focus=Comments-27-5014161.0-0 } ======= } } >>>>>>> REPLACE
mesuutt/snipper
f896d0fa40250a580fee584217c5a4c1d39d7388
snipper/snippet.py
python
mit
Add doc string to Snippet.get_files
import os from os import path import glob import json import subprocess class Snippet(object): def __init__(self, config, username, snippet_id): self.config = config self.username = username self.snippet_id = snippet_id repo_parent = path.join(self.config.get('snippet_home'), username) self.repo_path = glob.glob(path.join(repo_parent, '*{}'.format(self.snippet_id)))[0] @staticmethod def clone(url, clone_to): #TODO: Add log line for notifying user. # subprocess.DEVNULL subprocess.call(['git', 'clone', url, clone_to]) @staticmethod def pull(repo_dir): # TODO: Add log line for notifying user. subprocess.call(['git', '--git-dir={}/.git'.format(repo_dir), 'pull']) def get_files(self): metadata_file = path.join(self.config.get('snippet_home'), 'metadata.json') with open(metadata_file, 'r') as f: data = json.loads(f.read()) for item in data['values']: if item['id'] != self.snippet_id: continue return [f for f in os.listdir(self.repo_path) if path.isfile(path.join(self.repo_path, f))]
import os from os import path import glob import json import subprocess class Snippet(object): def __init__(self, config, username, snippet_id): self.config = config self.username = username self.snippet_id = snippet_id repo_parent = path.join(self.config.get('snippet_home'), username) self.repo_path = glob.glob(path.join(repo_parent, '*{}'.format(self.snippet_id)))[0] @staticmethod def clone(url, clone_to): #TODO: Add log line for notifying user. # subprocess.DEVNULL subprocess.call(['git', 'clone', url, clone_to]) @staticmethod def pull(repo_dir): # TODO: Add log line for notifying user. subprocess.call(['git', '--git-dir={}/.git'.format(repo_dir), 'pull']) def get_files(self): """ Return files of snippet """ metadata_file = path.join(self.config.get('snippet_home'), 'metadata.json') with open(metadata_file, 'r') as f: data = json.loads(f.read()) for item in data['values']: if item['id'] != self.snippet_id: continue return [f for f in os.listdir(self.repo_path) if path.isfile(path.join(self.repo_path, f))]
2
0
1
add_only
--- a/snipper/snippet.py +++ b/snipper/snippet.py @@ -29,2 +29,4 @@ def get_files(self): + """ Return files of snippet """ + metadata_file = path.join(self.config.get('snippet_home'), 'metadata.json')
--- a/snipper/snippet.py +++ b/snipper/snippet.py @@ ... @@ def get_files(self): + """ Return files of snippet """ + metadata_file = path.join(self.config.get('snippet_home'), 'metadata.json')
--- a/snipper/snippet.py +++ b/snipper/snippet.py @@ -29,2 +29,4 @@ CON def get_files(self): ADD """ Return files of snippet """ ADD CON metadata_file = path.join(self.config.get('snippet_home'), 'metadata.json')
<<<<<<< SEARCH def get_files(self): metadata_file = path.join(self.config.get('snippet_home'), 'metadata.json') with open(metadata_file, 'r') as f: ======= def get_files(self): """ Return files of snippet """ metadata_file = path.join(self.config.get('snippet_home'), 'metadata.json') with open(metadata_file, 'r') as f: >>>>>>> REPLACE
Monospark/ActionControl
fbd5fa946dada2daa23c7174a09feb9668e2cc58
src/main/java/org/monospark/actionpermissions/ActionPermissions.java
java
mit
Load the group config on startup
package org.monospark.actionpermissions; import org.spongepowered.api.plugin.Plugin; @Plugin(id = "actionpermissions", name = "ActionPermissions", version = "1.0") public class ActionPermissions { }
package org.monospark.actionpermissions; import java.nio.file.Path; import org.monospark.actionpermissions.config.ConfigParseException; import org.monospark.actionpermissions.group.Group; import org.monospark.actionpermissions.handler.ActionHandler; import org.spongepowered.api.Sponge; import org.spongepowered.api.config.ConfigDir; import org.spongepowered.api.event.Event; import org.spongepowered.api.event.Listener; import org.spongepowered.api.event.game.state.GameInitializationEvent; import org.spongepowered.api.plugin.Plugin; import com.google.inject.Inject; @Plugin(id = "actionpermissions", name = "ActionPermissions", version = "1.0") public class ActionPermissions { @Inject @ConfigDir(sharedRoot = false) private Path privateConfigDir; @Listener public void onServerInit(GameInitializationEvent event) { for(ActionHandler<?, ?> handler : ActionHandler.ALL) { registerActionHandler(handler); } try { Group.getRegistry().loadGroups(privateConfigDir); } catch (ConfigParseException e) { e.printStackTrace(); } } private <E extends Event> void registerActionHandler(ActionHandler<E, ?> handler) { Sponge.getGame().getEventManager().registerListener(this, handler.getEventClass(), handler); } }
33
1
2
mixed
--- a/src/main/java/org/monospark/actionpermissions/ActionPermissions.java +++ b/src/main/java/org/monospark/actionpermissions/ActionPermissions.java @@ -2,3 +2,15 @@ +import java.nio.file.Path; + +import org.monospark.actionpermissions.config.ConfigParseException; +import org.monospark.actionpermissions.group.Group; +import org.monospark.actionpermissions.handler.ActionHandler; +import org.spongepowered.api.Sponge; +import org.spongepowered.api.config.ConfigDir; +import org.spongepowered.api.event.Event; +import org.spongepowered.api.event.Listener; +import org.spongepowered.api.event.game.state.GameInitializationEvent; import org.spongepowered.api.plugin.Plugin; + +import com.google.inject.Inject; @@ -6,3 +18,23 @@ public class ActionPermissions { - + + @Inject + @ConfigDir(sharedRoot = false) + private Path privateConfigDir; + + @Listener + public void onServerInit(GameInitializationEvent event) { + for(ActionHandler<?, ?> handler : ActionHandler.ALL) { + registerActionHandler(handler); + } + + try { + Group.getRegistry().loadGroups(privateConfigDir); + } catch (ConfigParseException e) { + e.printStackTrace(); + } + } + + private <E extends Event> void registerActionHandler(ActionHandler<E, ?> handler) { + Sponge.getGame().getEventManager().registerListener(this, handler.getEventClass(), handler); + } }
--- a/src/main/java/org/monospark/actionpermissions/ActionPermissions.java +++ b/src/main/java/org/monospark/actionpermissions/ActionPermissions.java @@ ... @@ +import java.nio.file.Path; + +import org.monospark.actionpermissions.config.ConfigParseException; +import org.monospark.actionpermissions.group.Group; +import org.monospark.actionpermissions.handler.ActionHandler; +import org.spongepowered.api.Sponge; +import org.spongepowered.api.config.ConfigDir; +import org.spongepowered.api.event.Event; +import org.spongepowered.api.event.Listener; +import org.spongepowered.api.event.game.state.GameInitializationEvent; import org.spongepowered.api.plugin.Plugin; + +import com.google.inject.Inject; @@ ... @@ public class ActionPermissions { - + + @Inject + @ConfigDir(sharedRoot = false) + private Path privateConfigDir; + + @Listener + public void onServerInit(GameInitializationEvent event) { + for(ActionHandler<?, ?> handler : ActionHandler.ALL) { + registerActionHandler(handler); + } + + try { + Group.getRegistry().loadGroups(privateConfigDir); + } catch (ConfigParseException e) { + e.printStackTrace(); + } + } + + private <E extends Event> void registerActionHandler(ActionHandler<E, ?> handler) { + Sponge.getGame().getEventManager().registerListener(this, handler.getEventClass(), handler); + } }
--- a/src/main/java/org/monospark/actionpermissions/ActionPermissions.java +++ b/src/main/java/org/monospark/actionpermissions/ActionPermissions.java @@ -2,3 +2,15 @@ CON ADD import java.nio.file.Path; ADD ADD import org.monospark.actionpermissions.config.ConfigParseException; ADD import org.monospark.actionpermissions.group.Group; ADD import org.monospark.actionpermissions.handler.ActionHandler; ADD import org.spongepowered.api.Sponge; ADD import org.spongepowered.api.config.ConfigDir; ADD import org.spongepowered.api.event.Event; ADD import org.spongepowered.api.event.Listener; ADD import org.spongepowered.api.event.game.state.GameInitializationEvent; CON import org.spongepowered.api.plugin.Plugin; ADD ADD import com.google.inject.Inject; CON @@ -6,3 +18,23 @@ CON public class ActionPermissions { DEL ADD ADD @Inject ADD @ConfigDir(sharedRoot = false) ADD private Path privateConfigDir; ADD ADD @Listener ADD public void onServerInit(GameInitializationEvent event) { ADD for(ActionHandler<?, ?> handler : ActionHandler.ALL) { ADD registerActionHandler(handler); ADD } ADD ADD try { ADD Group.getRegistry().loadGroups(privateConfigDir); ADD } catch (ConfigParseException e) { ADD e.printStackTrace(); ADD } ADD } ADD ADD private <E extends Event> void registerActionHandler(ActionHandler<E, ?> handler) { ADD Sponge.getGame().getEventManager().registerListener(this, handler.getEventClass(), handler); ADD } CON }
<<<<<<< SEARCH package org.monospark.actionpermissions; import org.spongepowered.api.plugin.Plugin; @Plugin(id = "actionpermissions", name = "ActionPermissions", version = "1.0") public class ActionPermissions { } ======= package org.monospark.actionpermissions; import java.nio.file.Path; import org.monospark.actionpermissions.config.ConfigParseException; import org.monospark.actionpermissions.group.Group; import org.monospark.actionpermissions.handler.ActionHandler; import org.spongepowered.api.Sponge; import org.spongepowered.api.config.ConfigDir; import org.spongepowered.api.event.Event; import org.spongepowered.api.event.Listener; import org.spongepowered.api.event.game.state.GameInitializationEvent; import org.spongepowered.api.plugin.Plugin; import com.google.inject.Inject; @Plugin(id = "actionpermissions", name = "ActionPermissions", version = "1.0") public class ActionPermissions { @Inject @ConfigDir(sharedRoot = false) private Path privateConfigDir; @Listener public void onServerInit(GameInitializationEvent event) { for(ActionHandler<?, ?> handler : ActionHandler.ALL) { registerActionHandler(handler); } try { Group.getRegistry().loadGroups(privateConfigDir); } catch (ConfigParseException e) { e.printStackTrace(); } } private <E extends Event> void registerActionHandler(ActionHandler<E, ?> handler) { Sponge.getGame().getEventManager().registerListener(this, handler.getEventClass(), handler); } } >>>>>>> REPLACE
onepercentclub/bluebottle
80531076a713618cda6de815bdd6675bdf6f85f1
bluebottle/clients/management/commands/export_tenants.py
python
bsd-3-clause
Use client_name instead of schema_name
import json from rest_framework.authtoken.models import Token from django.contrib.contenttypes.models import ContentType from django.core.management.base import BaseCommand from bluebottle.clients import properties from bluebottle.clients.models import Client from bluebottle.clients.utils import LocalTenant class Command(BaseCommand): help = 'Export tenants, so that we can import them into the accounting app' def add_arguments(self, parser): parser.add_argument('--file', type=str, default=None, action='store') def handle(self, *args, **options): results = [] for client in Client.objects.all(): properties.set_tenant(client) with LocalTenant(client, clear_tenant=True): ContentType.objects.clear_cache() accounts = [] for merchant in properties.MERCHANT_ACCOUNTS: if merchant['merchant'] == 'docdata': accounts.append( { 'service_type': 'docdata', 'username': merchant['merchant_name'] } ) api_key = Token.objects.get(user__username='accounting').key results.append({ "name": client.schema_name, "domain": properties.TENANT_MAIL_PROPERTIES['website'], "api_key": api_key, "accounts": accounts }) if options['file']: text_file = open(options['file'], "w") text_file.write(json.dumps(results)) text_file.close() else: print json.dumps(results)
import json from rest_framework.authtoken.models import Token from django.contrib.contenttypes.models import ContentType from django.core.management.base import BaseCommand from bluebottle.clients import properties from bluebottle.clients.models import Client from bluebottle.clients.utils import LocalTenant class Command(BaseCommand): help = 'Export tenants, so that we can import them into the accounting app' def add_arguments(self, parser): parser.add_argument('--file', type=str, default=None, action='store') def handle(self, *args, **options): results = [] for client in Client.objects.all(): properties.set_tenant(client) with LocalTenant(client, clear_tenant=True): ContentType.objects.clear_cache() accounts = [] for merchant in properties.MERCHANT_ACCOUNTS: if merchant['merchant'] == 'docdata': accounts.append( { 'service_type': 'docdata', 'username': merchant['merchant_name'] } ) api_key = Token.objects.get(user__username='accounting').key results.append({ "name": client.client_name, "domain": properties.TENANT_MAIL_PROPERTIES['website'], "api_key": api_key, "accounts": accounts }) if options['file']: text_file = open(options['file'], "w") text_file.write(json.dumps(results)) text_file.close() else: print json.dumps(results)
1
1
1
mixed
--- a/bluebottle/clients/management/commands/export_tenants.py +++ b/bluebottle/clients/management/commands/export_tenants.py @@ -35,3 +35,3 @@ results.append({ - "name": client.schema_name, + "name": client.client_name, "domain": properties.TENANT_MAIL_PROPERTIES['website'],
--- a/bluebottle/clients/management/commands/export_tenants.py +++ b/bluebottle/clients/management/commands/export_tenants.py @@ ... @@ results.append({ - "name": client.schema_name, + "name": client.client_name, "domain": properties.TENANT_MAIL_PROPERTIES['website'],
--- a/bluebottle/clients/management/commands/export_tenants.py +++ b/bluebottle/clients/management/commands/export_tenants.py @@ -35,3 +35,3 @@ CON results.append({ DEL "name": client.schema_name, ADD "name": client.client_name, CON "domain": properties.TENANT_MAIL_PROPERTIES['website'],
<<<<<<< SEARCH api_key = Token.objects.get(user__username='accounting').key results.append({ "name": client.schema_name, "domain": properties.TENANT_MAIL_PROPERTIES['website'], "api_key": api_key, ======= api_key = Token.objects.get(user__username='accounting').key results.append({ "name": client.client_name, "domain": properties.TENANT_MAIL_PROPERTIES['website'], "api_key": api_key, >>>>>>> REPLACE
wozniakpiotr/java_training
4ad3b97fcc8ee3476a910d0a891eb66b069f2843
addressbook-web-tests/src/test/java/kurs/zadania/adressbook/appmanager/NavigationHelper.java
java
apache-2.0
Revert "Revert "optimization of the transition between the pages"" This reverts commit 44036d92de46456ee2269111275684c0e518e115.
package kurs.zadania.adressbook.appmanager; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; public class NavigationHelper extends HelperBase{ public NavigationHelper(WebDriver wd) { super(wd); } public void gotoGroupPage() { click(By.linkText("groups")); } public void gotoMainPage() { click(By.linkText("home")); } }
package kurs.zadania.adressbook.appmanager; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; public class NavigationHelper extends HelperBase{ public NavigationHelper(WebDriver wd) { super(wd); } // public void gotoGroupPage() { click(By.linkText("groups")); } /* sprawdzanie elementu na stronie i przejście po linku - wariant 1 public void gotoGroupPage() { if (!isElementPresent(By.tagName("h1")) || !wd.findElement(By.tagName("h1")).getText().equals("Groups") || !isElementPresent(By.name("new"))) { click(By.linkText("groups")); } } */ // sprawdzanie elementu na stronie i przejście po linku - wariant 2 lepszy public void gotoGroupPage() { if (isElementPresent(By.tagName("h1")) && !wd.findElement(By.tagName("h1")).getText().equals("Groups") && !isElementPresent(By.name("new"))) { return; } click(By.linkText("groups")); } public void gotoMainPage() { if (isElementPresent(By.id("maintable"))) { return; } click(By.linkText("home")); } }
21
1
1
mixed
--- a/addressbook-web-tests/src/test/java/kurs/zadania/adressbook/appmanager/NavigationHelper.java +++ b/addressbook-web-tests/src/test/java/kurs/zadania/adressbook/appmanager/NavigationHelper.java @@ -12,9 +12,29 @@ + // public void gotoGroupPage() { click(By.linkText("groups")); } + +/* sprawdzanie elementu na stronie i przejście po linku - wariant 1 public void gotoGroupPage() { + if (!isElementPresent(By.tagName("h1")) + || !wd.findElement(By.tagName("h1")).getText().equals("Groups") + || !isElementPresent(By.name("new"))) { click(By.linkText("groups")); + } } +*/ +// sprawdzanie elementu na stronie i przejście po linku - wariant 2 lepszy + + public void gotoGroupPage() { + if (isElementPresent(By.tagName("h1")) + && !wd.findElement(By.tagName("h1")).getText().equals("Groups") + && !isElementPresent(By.name("new"))) { + return; + } + click(By.linkText("groups")); + } public void gotoMainPage() { + if (isElementPresent(By.id("maintable"))) { + return; + } click(By.linkText("home")); - }
--- a/addressbook-web-tests/src/test/java/kurs/zadania/adressbook/appmanager/NavigationHelper.java +++ b/addressbook-web-tests/src/test/java/kurs/zadania/adressbook/appmanager/NavigationHelper.java @@ ... @@ + // public void gotoGroupPage() { click(By.linkText("groups")); } + +/* sprawdzanie elementu na stronie i przejście po linku - wariant 1 public void gotoGroupPage() { + if (!isElementPresent(By.tagName("h1")) + || !wd.findElement(By.tagName("h1")).getText().equals("Groups") + || !isElementPresent(By.name("new"))) { click(By.linkText("groups")); + } } +*/ +// sprawdzanie elementu na stronie i przejście po linku - wariant 2 lepszy + + public void gotoGroupPage() { + if (isElementPresent(By.tagName("h1")) + && !wd.findElement(By.tagName("h1")).getText().equals("Groups") + && !isElementPresent(By.name("new"))) { + return; + } + click(By.linkText("groups")); + } public void gotoMainPage() { + if (isElementPresent(By.id("maintable"))) { + return; + } click(By.linkText("home")); - }
--- a/addressbook-web-tests/src/test/java/kurs/zadania/adressbook/appmanager/NavigationHelper.java +++ b/addressbook-web-tests/src/test/java/kurs/zadania/adressbook/appmanager/NavigationHelper.java @@ -12,9 +12,29 @@ CON ADD // public void gotoGroupPage() { click(By.linkText("groups")); } ADD ADD /* sprawdzanie elementu na stronie i przejście po linku - wariant 1 CON public void gotoGroupPage() { ADD if (!isElementPresent(By.tagName("h1")) ADD || !wd.findElement(By.tagName("h1")).getText().equals("Groups") ADD || !isElementPresent(By.name("new"))) { CON click(By.linkText("groups")); ADD } CON } ADD */ ADD // sprawdzanie elementu na stronie i przejście po linku - wariant 2 lepszy ADD ADD public void gotoGroupPage() { ADD if (isElementPresent(By.tagName("h1")) ADD && !wd.findElement(By.tagName("h1")).getText().equals("Groups") ADD && !isElementPresent(By.name("new"))) { ADD return; ADD } ADD click(By.linkText("groups")); ADD } CON CON public void gotoMainPage() { ADD if (isElementPresent(By.id("maintable"))) { ADD return; ADD } CON click(By.linkText("home")); DEL CON }
<<<<<<< SEARCH } public void gotoGroupPage() { click(By.linkText("groups")); } public void gotoMainPage() { click(By.linkText("home")); } } ======= } // public void gotoGroupPage() { click(By.linkText("groups")); } /* sprawdzanie elementu na stronie i przejście po linku - wariant 1 public void gotoGroupPage() { if (!isElementPresent(By.tagName("h1")) || !wd.findElement(By.tagName("h1")).getText().equals("Groups") || !isElementPresent(By.name("new"))) { click(By.linkText("groups")); } } */ // sprawdzanie elementu na stronie i przejście po linku - wariant 2 lepszy public void gotoGroupPage() { if (isElementPresent(By.tagName("h1")) && !wd.findElement(By.tagName("h1")).getText().equals("Groups") && !isElementPresent(By.name("new"))) { return; } click(By.linkText("groups")); } public void gotoMainPage() { if (isElementPresent(By.id("maintable"))) { return; } click(By.linkText("home")); } } >>>>>>> REPLACE
zathras/misc
21f620f7bfd0e6492d37417ee1a7226ccab66d51
maven_import/build.gradle.kts
kotlin
mit
Switch away from Github Packages.
plugins { java kotlin("jvm") version "1.3.61" } group = "org.example" version = "1.0-SNAPSHOT" repositories { mavenCentral() maven { url = uri("https://maven.pkg.github.com/zathras/db9010") credentials { username = "zathras" password = "848e249a25d6c3da4b68287ba619aed81b6867a7" // It's a little weird that Github Packages requires a token // to access a maven repo that's part of a *public* github // repository. Since all of my github repos on this account // are public, I don't think there's any harm in publishing // this token, which only has "read:packages" permission. } } } dependencies { implementation(kotlin("stdlib-jdk8")) implementation("com.h2database", "h2", "1.4.200") implementation("com.jovial.db9010", "db9010", "0.1.0") testCompile("junit", "junit", "4.12") } configure<JavaPluginConvention> { sourceCompatibility = JavaVersion.VERSION_1_8 } tasks { compileKotlin { kotlinOptions.jvmTarget = "1.8" } compileTestKotlin { kotlinOptions.jvmTarget = "1.8" } }
plugins { java kotlin("jvm") version "1.3.61" } group = "org.example" version = "1.0-SNAPSHOT" repositories { mavenCentral() maven { url = uri("https://zathras.github.io/maven/") // For github pacakges: // url = uri("https://maven.pkg.github.com/zathras/db9010") // credentials { // username = "zathras" // password = "mumble" // } // // Strangely, Github Packages requires credentials for a public // repository. That's inconvenient, especially since Github prevents // one from publishing a credential -- even one that just allows read // access on packages. } } dependencies { implementation(kotlin("stdlib-jdk8")) implementation("com.h2database", "h2", "1.4.200") implementation("com.jovial", "db9010", "0.1.0") testCompile("junit", "junit", "4.12") } configure<JavaPluginConvention> { sourceCompatibility = JavaVersion.VERSION_1_8 } tasks { compileKotlin { kotlinOptions.jvmTarget = "1.8" } compileTestKotlin { kotlinOptions.jvmTarget = "1.8" } }
13
11
2
mixed
--- a/maven_import/build.gradle.kts +++ b/maven_import/build.gradle.kts @@ -11,12 +11,14 @@ maven { - url = uri("https://maven.pkg.github.com/zathras/db9010") - credentials { - username = "zathras" - password = "848e249a25d6c3da4b68287ba619aed81b6867a7" - // It's a little weird that Github Packages requires a token - // to access a maven repo that's part of a *public* github - // repository. Since all of my github repos on this account - // are public, I don't think there's any harm in publishing - // this token, which only has "read:packages" permission. - } + url = uri("https://zathras.github.io/maven/") + // For github pacakges: + // url = uri("https://maven.pkg.github.com/zathras/db9010") + // credentials { + // username = "zathras" + // password = "mumble" + // } + // + // Strangely, Github Packages requires credentials for a public + // repository. That's inconvenient, especially since Github prevents + // one from publishing a credential -- even one that just allows read + // access on packages. } @@ -27,3 +29,3 @@ implementation("com.h2database", "h2", "1.4.200") - implementation("com.jovial.db9010", "db9010", "0.1.0") + implementation("com.jovial", "db9010", "0.1.0") testCompile("junit", "junit", "4.12")
--- a/maven_import/build.gradle.kts +++ b/maven_import/build.gradle.kts @@ ... @@ maven { - url = uri("https://maven.pkg.github.com/zathras/db9010") - credentials { - username = "zathras" - password = "848e249a25d6c3da4b68287ba619aed81b6867a7" - // It's a little weird that Github Packages requires a token - // to access a maven repo that's part of a *public* github - // repository. Since all of my github repos on this account - // are public, I don't think there's any harm in publishing - // this token, which only has "read:packages" permission. - } + url = uri("https://zathras.github.io/maven/") + // For github pacakges: + // url = uri("https://maven.pkg.github.com/zathras/db9010") + // credentials { + // username = "zathras" + // password = "mumble" + // } + // + // Strangely, Github Packages requires credentials for a public + // repository. That's inconvenient, especially since Github prevents + // one from publishing a credential -- even one that just allows read + // access on packages. } @@ ... @@ implementation("com.h2database", "h2", "1.4.200") - implementation("com.jovial.db9010", "db9010", "0.1.0") + implementation("com.jovial", "db9010", "0.1.0") testCompile("junit", "junit", "4.12")
--- a/maven_import/build.gradle.kts +++ b/maven_import/build.gradle.kts @@ -11,12 +11,14 @@ CON maven { DEL url = uri("https://maven.pkg.github.com/zathras/db9010") DEL credentials { DEL username = "zathras" DEL password = "848e249a25d6c3da4b68287ba619aed81b6867a7" DEL // It's a little weird that Github Packages requires a token DEL // to access a maven repo that's part of a *public* github DEL // repository. Since all of my github repos on this account DEL // are public, I don't think there's any harm in publishing DEL // this token, which only has "read:packages" permission. DEL } ADD url = uri("https://zathras.github.io/maven/") ADD // For github pacakges: ADD // url = uri("https://maven.pkg.github.com/zathras/db9010") ADD // credentials { ADD // username = "zathras" ADD // password = "mumble" ADD // } ADD // ADD // Strangely, Github Packages requires credentials for a public ADD // repository. That's inconvenient, especially since Github prevents ADD // one from publishing a credential -- even one that just allows read ADD // access on packages. CON } @@ -27,3 +29,3 @@ CON implementation("com.h2database", "h2", "1.4.200") DEL implementation("com.jovial.db9010", "db9010", "0.1.0") ADD implementation("com.jovial", "db9010", "0.1.0") CON testCompile("junit", "junit", "4.12")
<<<<<<< SEARCH mavenCentral() maven { url = uri("https://maven.pkg.github.com/zathras/db9010") credentials { username = "zathras" password = "848e249a25d6c3da4b68287ba619aed81b6867a7" // It's a little weird that Github Packages requires a token // to access a maven repo that's part of a *public* github // repository. Since all of my github repos on this account // are public, I don't think there's any harm in publishing // this token, which only has "read:packages" permission. } } } ======= mavenCentral() maven { url = uri("https://zathras.github.io/maven/") // For github pacakges: // url = uri("https://maven.pkg.github.com/zathras/db9010") // credentials { // username = "zathras" // password = "mumble" // } // // Strangely, Github Packages requires credentials for a public // repository. That's inconvenient, especially since Github prevents // one from publishing a credential -- even one that just allows read // access on packages. } } >>>>>>> REPLACE <<<<<<< SEARCH implementation(kotlin("stdlib-jdk8")) implementation("com.h2database", "h2", "1.4.200") implementation("com.jovial.db9010", "db9010", "0.1.0") testCompile("junit", "junit", "4.12") } ======= implementation(kotlin("stdlib-jdk8")) implementation("com.h2database", "h2", "1.4.200") implementation("com.jovial", "db9010", "0.1.0") testCompile("junit", "junit", "4.12") } >>>>>>> REPLACE
pgrzesik/learning-rust
502fd29bd91cdee6b03ea548f012db9a0163b62c
24_iterators/src/lib.rs
rust
mit
Implement test showing that we can also use other iter methods
struct Counter { count: u32 } impl Counter { fn new() -> Counter { Counter { count: 0 } } } impl Iterator for Counter { type Item = u32; fn next(&mut self) -> Option<Self::Item> { self.count += 1; if self.count < 6 { Some(self.count) } else { None } } } #[test] fn calling_counter_next() { let mut counter = Counter::new(); assert_eq!(counter.next(), Some(1)); assert_eq!(counter.next(), Some(2)); assert_eq!(counter.next(), Some(3)); assert_eq!(counter.next(), Some(4)); assert_eq!(counter.next(), Some(5)); assert_eq!(counter.next(), None); }
struct Counter { count: u32 } impl Counter { fn new() -> Counter { Counter { count: 0 } } } impl Iterator for Counter { type Item = u32; fn next(&mut self) -> Option<Self::Item> { self.count += 1; if self.count < 6 { Some(self.count) } else { None } } } #[test] fn calling_counter_next() { let mut counter = Counter::new(); assert_eq!(counter.next(), Some(1)); assert_eq!(counter.next(), Some(2)); assert_eq!(counter.next(), Some(3)); assert_eq!(counter.next(), Some(4)); assert_eq!(counter.next(), Some(5)); assert_eq!(counter.next(), None); } #[test] fn using_other_iterator_trait_methods() { let sum: u32 = Counter::new().zip(Counter::new().skip(1)) .map(|(a, b)| a * b) .filter(|x| x % 3 == 0) .sum(); assert_eq!(sum, 18); }
9
0
1
add_only
--- a/24_iterators/src/lib.rs +++ b/24_iterators/src/lib.rs @@ -35 +35,10 @@ } + +#[test] +fn using_other_iterator_trait_methods() { + let sum: u32 = Counter::new().zip(Counter::new().skip(1)) + .map(|(a, b)| a * b) + .filter(|x| x % 3 == 0) + .sum(); + assert_eq!(sum, 18); +}
--- a/24_iterators/src/lib.rs +++ b/24_iterators/src/lib.rs @@ ... @@ } + +#[test] +fn using_other_iterator_trait_methods() { + let sum: u32 = Counter::new().zip(Counter::new().skip(1)) + .map(|(a, b)| a * b) + .filter(|x| x % 3 == 0) + .sum(); + assert_eq!(sum, 18); +}
--- a/24_iterators/src/lib.rs +++ b/24_iterators/src/lib.rs @@ -35 +35,10 @@ CON } ADD ADD #[test] ADD fn using_other_iterator_trait_methods() { ADD let sum: u32 = Counter::new().zip(Counter::new().skip(1)) ADD .map(|(a, b)| a * b) ADD .filter(|x| x % 3 == 0) ADD .sum(); ADD assert_eq!(sum, 18); ADD }
<<<<<<< SEARCH assert_eq!(counter.next(), Some(5)); assert_eq!(counter.next(), None); } ======= assert_eq!(counter.next(), Some(5)); assert_eq!(counter.next(), None); } #[test] fn using_other_iterator_trait_methods() { let sum: u32 = Counter::new().zip(Counter::new().skip(1)) .map(|(a, b)| a * b) .filter(|x| x % 3 == 0) .sum(); assert_eq!(sum, 18); } >>>>>>> REPLACE
ktorio/ktor
5497eae2b7790cd47eb5fb725633b55e59a90c40
ktor-client/ktor-client-tests/jvm/src/io/ktor/client/tests/utils/TestWithKtor.kt
kotlin
apache-2.0
Make client tests retry server startup if failed
/* * Copyright 2014-2019 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.client.tests.utils import ch.qos.logback.classic.* import ch.qos.logback.classic.Logger import io.ktor.server.engine.* import kotlinx.coroutines.debug.junit4.* import org.junit.* import org.slf4j.* import java.net.* import java.util.concurrent.* @Suppress("KDocMissingDocumentation") abstract class TestWithKtor { protected val serverPort: Int = ServerSocket(0).use { it.localPort } @get:Rule open val timeout = CoroutinesTimeout.seconds(3 * 60) abstract val server: ApplicationEngine init { (LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME) as? Logger)?.level = Level.ERROR } @Before fun startServer() { server.start() ensureServerRunning() } @After fun stopServer() { server.stop(0, 0, TimeUnit.SECONDS) } private fun ensureServerRunning() { do { try { Socket("localhost", serverPort).close() break } catch (_: Throwable) { Thread.sleep(100) } } while (true) } }
/* * Copyright 2014-2019 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.client.tests.utils import ch.qos.logback.classic.* import ch.qos.logback.classic.Logger import io.ktor.server.engine.* import kotlinx.coroutines.debug.junit4.* import org.junit.* import org.slf4j.* import java.net.* import java.util.concurrent.* @Suppress("KDocMissingDocumentation") abstract class TestWithKtor { protected val serverPort: Int = ServerSocket(0).use { it.localPort } @get:Rule open val timeout = CoroutinesTimeout.seconds(3 * 60) abstract val server: ApplicationEngine init { (LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME) as? Logger)?.level = Level.ERROR } @Before fun startServer() { var attempt = 0 do { attempt++ try { server.start() break } catch (cause: Throwable) { if (attempt >= 10) throw cause Thread.sleep(250L * attempt) } } while (true) ensureServerRunning() } @After fun stopServer() { server.stop(0, 0, TimeUnit.SECONDS) } private fun ensureServerRunning() { do { try { Socket("localhost", serverPort).close() break } catch (_: Throwable) { Thread.sleep(100) } } while (true) } }
13
1
1
mixed
--- a/ktor-client/ktor-client-tests/jvm/src/io/ktor/client/tests/utils/TestWithKtor.kt +++ b/ktor-client/ktor-client-tests/jvm/src/io/ktor/client/tests/utils/TestWithKtor.kt @@ -30,3 +30,15 @@ fun startServer() { - server.start() + var attempt = 0 + + do { + attempt++ + try { + server.start() + break + } catch (cause: Throwable) { + if (attempt >= 10) throw cause + Thread.sleep(250L * attempt) + } + } while (true) + ensureServerRunning()
--- a/ktor-client/ktor-client-tests/jvm/src/io/ktor/client/tests/utils/TestWithKtor.kt +++ b/ktor-client/ktor-client-tests/jvm/src/io/ktor/client/tests/utils/TestWithKtor.kt @@ ... @@ fun startServer() { - server.start() + var attempt = 0 + + do { + attempt++ + try { + server.start() + break + } catch (cause: Throwable) { + if (attempt >= 10) throw cause + Thread.sleep(250L * attempt) + } + } while (true) + ensureServerRunning()
--- a/ktor-client/ktor-client-tests/jvm/src/io/ktor/client/tests/utils/TestWithKtor.kt +++ b/ktor-client/ktor-client-tests/jvm/src/io/ktor/client/tests/utils/TestWithKtor.kt @@ -30,3 +30,15 @@ CON fun startServer() { DEL server.start() ADD var attempt = 0 ADD ADD do { ADD attempt++ ADD try { ADD server.start() ADD break ADD } catch (cause: Throwable) { ADD if (attempt >= 10) throw cause ADD Thread.sleep(250L * attempt) ADD } ADD } while (true) ADD CON ensureServerRunning()
<<<<<<< SEARCH @Before fun startServer() { server.start() ensureServerRunning() } ======= @Before fun startServer() { var attempt = 0 do { attempt++ try { server.start() break } catch (cause: Throwable) { if (attempt >= 10) throw cause Thread.sleep(250L * attempt) } } while (true) ensureServerRunning() } >>>>>>> REPLACE
wartman4404/servo
4afdbe89c2bb1820e25b586b52d3f2948f9d1988
src/servo/servo.rs
rust
mpl-2.0
Use SDL to display a window
fn main() { }
import azure::cairo; fn on_main(f: fn~()) { let builder = task::builder(); let opts = { sched: some({ mode: task::osmain, native_stack_size: none }) with task::get_opts(builder) }; task::set_opts(builder, opts); task::run(builder, f); } fn main() { on_main {|| sdl::init([ sdl::init_video ]); let screen = sdl::video::set_video_mode( 320, 200, 32, [sdl::video::swsurface], [sdl::video::doublebuf]); assert ptr::is_not_null(screen); let surface = sdl::video::create_rgb_surface( [sdl::video::swsurface], 320, 200, 32, 0x00FF0000u32, 0x0000FF00u32, 0x000000FFu32, 0x00000000u32 ); assert ptr::is_not_null(surface); loop { sdl::video::blit_surface(surface, ptr::null(), screen, ptr::null()); sdl::video::flip(screen); sdl::event::poll_event {|_event| } } sdl::quit(); } }
40
0
1
add_only
--- a/src/servo/servo.rs +++ b/src/servo/servo.rs @@ -1,4 +1,44 @@ +import azure::cairo; +fn on_main(f: fn~()) { + let builder = task::builder(); + let opts = { + sched: some({ + mode: task::osmain, + native_stack_size: none + }) + with task::get_opts(builder) + }; + task::set_opts(builder, opts); + task::run(builder, f); +} fn main() { + on_main {|| + sdl::init([ + sdl::init_video + ]); + let screen = sdl::video::set_video_mode( + 320, 200, 32, + [sdl::video::swsurface], + [sdl::video::doublebuf]); + assert ptr::is_not_null(screen); + let surface = sdl::video::create_rgb_surface( + [sdl::video::swsurface], + 320, 200, 32, + 0x00FF0000u32, + 0x0000FF00u32, + 0x000000FFu32, + 0x00000000u32 + ); + assert ptr::is_not_null(surface); + loop { + sdl::video::blit_surface(surface, ptr::null(), + screen, ptr::null()); + sdl::video::flip(screen); + sdl::event::poll_event {|_event| + } + } + sdl::quit(); + } }
--- a/src/servo/servo.rs +++ b/src/servo/servo.rs @@ ... @@ +import azure::cairo; +fn on_main(f: fn~()) { + let builder = task::builder(); + let opts = { + sched: some({ + mode: task::osmain, + native_stack_size: none + }) + with task::get_opts(builder) + }; + task::set_opts(builder, opts); + task::run(builder, f); +} fn main() { + on_main {|| + sdl::init([ + sdl::init_video + ]); + let screen = sdl::video::set_video_mode( + 320, 200, 32, + [sdl::video::swsurface], + [sdl::video::doublebuf]); + assert ptr::is_not_null(screen); + let surface = sdl::video::create_rgb_surface( + [sdl::video::swsurface], + 320, 200, 32, + 0x00FF0000u32, + 0x0000FF00u32, + 0x000000FFu32, + 0x00000000u32 + ); + assert ptr::is_not_null(surface); + loop { + sdl::video::blit_surface(surface, ptr::null(), + screen, ptr::null()); + sdl::video::flip(screen); + sdl::event::poll_event {|_event| + } + } + sdl::quit(); + } }
--- a/src/servo/servo.rs +++ b/src/servo/servo.rs @@ -1,4 +1,44 @@ ADD import azure::cairo; CON ADD fn on_main(f: fn~()) { ADD let builder = task::builder(); ADD let opts = { ADD sched: some({ ADD mode: task::osmain, ADD native_stack_size: none ADD }) ADD with task::get_opts(builder) ADD }; ADD task::set_opts(builder, opts); ADD task::run(builder, f); ADD } CON CON fn main() { ADD on_main {|| ADD sdl::init([ ADD sdl::init_video ADD ]); ADD let screen = sdl::video::set_video_mode( ADD 320, 200, 32, ADD [sdl::video::swsurface], ADD [sdl::video::doublebuf]); ADD assert ptr::is_not_null(screen); ADD let surface = sdl::video::create_rgb_surface( ADD [sdl::video::swsurface], ADD 320, 200, 32, ADD 0x00FF0000u32, ADD 0x0000FF00u32, ADD 0x000000FFu32, ADD 0x00000000u32 ADD ); ADD assert ptr::is_not_null(surface); ADD loop { ADD sdl::video::blit_surface(surface, ptr::null(), ADD screen, ptr::null()); ADD sdl::video::flip(screen); ADD sdl::event::poll_event {|_event| ADD } ADD } ADD sdl::quit(); ADD } CON }
<<<<<<< SEARCH fn main() { } ======= import azure::cairo; fn on_main(f: fn~()) { let builder = task::builder(); let opts = { sched: some({ mode: task::osmain, native_stack_size: none }) with task::get_opts(builder) }; task::set_opts(builder, opts); task::run(builder, f); } fn main() { on_main {|| sdl::init([ sdl::init_video ]); let screen = sdl::video::set_video_mode( 320, 200, 32, [sdl::video::swsurface], [sdl::video::doublebuf]); assert ptr::is_not_null(screen); let surface = sdl::video::create_rgb_surface( [sdl::video::swsurface], 320, 200, 32, 0x00FF0000u32, 0x0000FF00u32, 0x000000FFu32, 0x00000000u32 ); assert ptr::is_not_null(surface); loop { sdl::video::blit_surface(surface, ptr::null(), screen, ptr::null()); sdl::video::flip(screen); sdl::event::poll_event {|_event| } } sdl::quit(); } } >>>>>>> REPLACE
MacroData/skyprint
33106b55d6503c26b56a1a3da7e568762eb4a390
src/main/java/com/github/macrodata/skyprint/section/RootSection.java
java
apache-2.0
Change metadata type to map
package com.github.macrodata.skyprint.section; import lombok.Setter; import lombok.ToString; import java.util.List; import static com.github.macrodata.skyprint.section.SectionHelper.*; @ToString public class RootSection extends Section { @Setter private MetadataSection metadata; @Setter private String name; @Setter private List<ResourceSection> resources; @Setter private List<GroupSection> groups; public MetadataSection getMetadata() { if (metadata == null) lazy(this::setMetadata, get(this, MetadataSection.class)); return metadata; } public String getName() { if (name == null) lazy(this::setName, get(this, OverviewSection.class).getName()); return name; } @Override public String getDescription() { if (super.getDescription() == null) lazy(this::setDescription, get(this, OverviewSection.class).getDescription()); return super.getDescription(); } public List<ResourceSection> getResources() { if (resources == null) lazy(this::setResources, list(this, ResourceSection.class)); return resources; } public List<GroupSection> getGroups() { if (groups == null) lazy(this::setGroups, list(this, GroupSection.class)); return groups; } }
package com.github.macrodata.skyprint.section; import lombok.Setter; import lombok.ToString; import javax.xml.transform.stream.StreamSource; import java.util.List; import java.util.Map; import java.util.stream.Stream; import static com.github.macrodata.skyprint.section.SectionHelper.*; @ToString public class RootSection extends Section { @Setter private Map<String, String> metadata; @Setter private String name; @Setter private List<ResourceSection> resources; @Setter private List<GroupSection> groups; public Map<String, String> getMetadata() { if (metadata == null) lazy(this::setMetadata, get(this, MetadataSection.class)); return metadata; } public String getName() { if (name == null) lazy(this::setName, get(this, OverviewSection.class).getName()); return name; } @Override public String getDescription() { if (super.getDescription() == null) lazy(this::setDescription, get(this, OverviewSection.class).getDescription()); return super.getDescription(); } public List<ResourceSection> getResources() { if (resources == null) lazy(this::setResources, list(this, ResourceSection.class)); return resources; } public List<GroupSection> getGroups() { if (groups == null) lazy(this::setGroups, list(this, GroupSection.class)); return groups; } }
5
2
3
mixed
--- a/src/main/java/com/github/macrodata/skyprint/section/RootSection.java +++ b/src/main/java/com/github/macrodata/skyprint/section/RootSection.java @@ -5,3 +5,6 @@ +import javax.xml.transform.stream.StreamSource; import java.util.List; +import java.util.Map; +import java.util.stream.Stream; @@ -13,3 +16,3 @@ @Setter - private MetadataSection metadata; + private Map<String, String> metadata; @@ -24,3 +27,3 @@ - public MetadataSection getMetadata() { + public Map<String, String> getMetadata() { if (metadata == null)
--- a/src/main/java/com/github/macrodata/skyprint/section/RootSection.java +++ b/src/main/java/com/github/macrodata/skyprint/section/RootSection.java @@ ... @@ +import javax.xml.transform.stream.StreamSource; import java.util.List; +import java.util.Map; +import java.util.stream.Stream; @@ ... @@ @Setter - private MetadataSection metadata; + private Map<String, String> metadata; @@ ... @@ - public MetadataSection getMetadata() { + public Map<String, String> getMetadata() { if (metadata == null)
--- a/src/main/java/com/github/macrodata/skyprint/section/RootSection.java +++ b/src/main/java/com/github/macrodata/skyprint/section/RootSection.java @@ -5,3 +5,6 @@ CON ADD import javax.xml.transform.stream.StreamSource; CON import java.util.List; ADD import java.util.Map; ADD import java.util.stream.Stream; CON @@ -13,3 +16,3 @@ CON @Setter DEL private MetadataSection metadata; ADD private Map<String, String> metadata; CON @@ -24,3 +27,3 @@ CON DEL public MetadataSection getMetadata() { ADD public Map<String, String> getMetadata() { CON if (metadata == null)
<<<<<<< SEARCH import lombok.ToString; import java.util.List; import static com.github.macrodata.skyprint.section.SectionHelper.*; ======= import lombok.ToString; import javax.xml.transform.stream.StreamSource; import java.util.List; import java.util.Map; import java.util.stream.Stream; import static com.github.macrodata.skyprint.section.SectionHelper.*; >>>>>>> REPLACE <<<<<<< SEARCH @Setter private MetadataSection metadata; @Setter ======= @Setter private Map<String, String> metadata; @Setter >>>>>>> REPLACE <<<<<<< SEARCH private List<GroupSection> groups; public MetadataSection getMetadata() { if (metadata == null) lazy(this::setMetadata, get(this, MetadataSection.class)); ======= private List<GroupSection> groups; public Map<String, String> getMetadata() { if (metadata == null) lazy(this::setMetadata, get(this, MetadataSection.class)); >>>>>>> REPLACE
Techern/Netherrack
9233068da58cb6f3e833792aa75ccfdcfa851d4d
src/io/operations/reader.rs
rust
apache-2.0
Use matching while reading an unsigned byte instead of an if/else
//! Netherrack-specific reading I/O operations use io_operations::reader::Reader; extern crate varint; extern crate bit_utils; use self::bit_utils::BitInformation; pub trait NetherrackReader : Reader { /// Reads an unsigned 32-bit Varint from this NetherrackReader fn read_unsigned_varint_32(&mut self) -> Result<u32, &'static str> { // The number of bits to shift by. <<0, <<7, <<14, etc let mut shift_amount: u32 = 0; // The decoded value let mut decoded_value: u32 = 0; loop { let byte_value = self.read_unsigned_byte(); if byte_value.is_err() { return Err("Byte in read_unsigned_varint_32 returned an error"); } else { let byte_value: u8 = byte_value.unwrap(); decoded_value |= ((byte_value & 0b01111111) as u32) << shift_amount; // See if we're supposed to keep reading if byte_value.has_most_signifigant_bit() { shift_amount += 7; } else { return Ok(decoded_value); } } } } } impl NetherrackReader for ::std::io::Cursor<Vec<u8>> { } impl NetherrackReader for ::std::net::TcpStream { }
//! Netherrack-specific reading I/O operations use io_operations::reader::Reader; extern crate varint; extern crate bit_utils; use self::bit_utils::BitInformation; pub trait NetherrackReader : Reader { /// Reads an unsigned 32-bit Varint from this NetherrackReader fn read_unsigned_varint_32(&mut self) -> Result<u32, &'static str> { // The number of bits to shift by. <<0, <<7, <<14, etc let mut shift_amount: u32 = 0; // The decoded value let mut decoded_value: u32 = 0; loop { match self.read_unsigned_byte() { Err(error) => { error!("Got an error while reading a byte for an unsigned varint32: {}", error); return Err("Could not read an unsigned byte for an unsigned varint32"); } Ok(byte_value) => { decoded_value |= ((byte_value & 0b01111111) as u32) << shift_amount; // See if we're supposed to keep reading if byte_value.has_most_signifigant_bit() { shift_amount += 7; } else { return Ok(decoded_value); } } } } } } impl NetherrackReader for ::std::io::Cursor<Vec<u8>> { } impl NetherrackReader for ::std::net::TcpStream { }
13
12
1
mixed
--- a/src/io/operations/reader.rs +++ b/src/io/operations/reader.rs @@ -22,16 +22,17 @@ - let byte_value = self.read_unsigned_byte(); + match self.read_unsigned_byte() { + Err(error) => { + error!("Got an error while reading a byte for an unsigned varint32: {}", error); + return Err("Could not read an unsigned byte for an unsigned varint32"); + } - if byte_value.is_err() { - return Err("Byte in read_unsigned_varint_32 returned an error"); - } else { - let byte_value: u8 = byte_value.unwrap(); + Ok(byte_value) => { + decoded_value |= ((byte_value & 0b01111111) as u32) << shift_amount; - decoded_value |= ((byte_value & 0b01111111) as u32) << shift_amount; - - // See if we're supposed to keep reading - if byte_value.has_most_signifigant_bit() { - shift_amount += 7; - } else { - return Ok(decoded_value); + // See if we're supposed to keep reading + if byte_value.has_most_signifigant_bit() { + shift_amount += 7; + } else { + return Ok(decoded_value); + } }
--- a/src/io/operations/reader.rs +++ b/src/io/operations/reader.rs @@ ... @@ - let byte_value = self.read_unsigned_byte(); + match self.read_unsigned_byte() { + Err(error) => { + error!("Got an error while reading a byte for an unsigned varint32: {}", error); + return Err("Could not read an unsigned byte for an unsigned varint32"); + } - if byte_value.is_err() { - return Err("Byte in read_unsigned_varint_32 returned an error"); - } else { - let byte_value: u8 = byte_value.unwrap(); + Ok(byte_value) => { + decoded_value |= ((byte_value & 0b01111111) as u32) << shift_amount; - decoded_value |= ((byte_value & 0b01111111) as u32) << shift_amount; - - // See if we're supposed to keep reading - if byte_value.has_most_signifigant_bit() { - shift_amount += 7; - } else { - return Ok(decoded_value); + // See if we're supposed to keep reading + if byte_value.has_most_signifigant_bit() { + shift_amount += 7; + } else { + return Ok(decoded_value); + } }
--- a/src/io/operations/reader.rs +++ b/src/io/operations/reader.rs @@ -22,16 +22,17 @@ CON DEL let byte_value = self.read_unsigned_byte(); ADD match self.read_unsigned_byte() { ADD Err(error) => { ADD error!("Got an error while reading a byte for an unsigned varint32: {}", error); ADD return Err("Could not read an unsigned byte for an unsigned varint32"); ADD } CON DEL if byte_value.is_err() { DEL return Err("Byte in read_unsigned_varint_32 returned an error"); DEL } else { DEL let byte_value: u8 = byte_value.unwrap(); ADD Ok(byte_value) => { ADD decoded_value |= ((byte_value & 0b01111111) as u32) << shift_amount; CON DEL decoded_value |= ((byte_value & 0b01111111) as u32) << shift_amount; DEL DEL // See if we're supposed to keep reading DEL if byte_value.has_most_signifigant_bit() { DEL shift_amount += 7; DEL } else { DEL return Ok(decoded_value); ADD // See if we're supposed to keep reading ADD if byte_value.has_most_signifigant_bit() { ADD shift_amount += 7; ADD } else { ADD return Ok(decoded_value); ADD } CON }
<<<<<<< SEARCH loop { let byte_value = self.read_unsigned_byte(); if byte_value.is_err() { return Err("Byte in read_unsigned_varint_32 returned an error"); } else { let byte_value: u8 = byte_value.unwrap(); decoded_value |= ((byte_value & 0b01111111) as u32) << shift_amount; // See if we're supposed to keep reading if byte_value.has_most_signifigant_bit() { shift_amount += 7; } else { return Ok(decoded_value); } } ======= loop { match self.read_unsigned_byte() { Err(error) => { error!("Got an error while reading a byte for an unsigned varint32: {}", error); return Err("Could not read an unsigned byte for an unsigned varint32"); } Ok(byte_value) => { decoded_value |= ((byte_value & 0b01111111) as u32) << shift_amount; // See if we're supposed to keep reading if byte_value.has_most_signifigant_bit() { shift_amount += 7; } else { return Ok(decoded_value); } } } >>>>>>> REPLACE
florian/cookie.js
a28f54bb13ced42c6554fc650a900f367a5cffea
rollup.config.js
javascript
mit
Add UMD minified build in rollup
import resolve from 'rollup-plugin-node-resolve'; import commonjs from 'rollup-plugin-commonjs'; import pkg from './package.json'; export default [ // browser-friendly UMD build { input: 'src/cookie.js', output: { name: 'cookie', file: pkg.browser, format: 'umd' }, plugins: [ resolve(), // so Rollup can find `ms` commonjs() // so Rollup can convert `ms` to an ES module ] }, // CommonJS (for Node) and ES module (for bundlers) build. // (We could have three entries in the configuration array // instead of two, but it's quicker to generate multiple // builds from a single configuration where possible, using // an array for the `output` option, where we can specify // `file` and `format` for each target) { input: 'src/cookie.js', external: ['ms'], output: [ { file: pkg.main, format: 'cjs' }, { file: pkg.module, format: 'es' } ] } ];
import resolve from 'rollup-plugin-node-resolve'; import commonjs from 'rollup-plugin-commonjs'; import { terser } from 'rollup-plugin-terser'; import pkg from './package.json'; export default [ // browser-friendly UMD build { input: 'src/cookie.js', output: { name: 'cookie', file: pkg.browser, format: 'umd' }, plugins: [ resolve(), // so Rollup can find `ms` commonjs() // so Rollup can convert `ms` to an ES module ] }, // CommonJS (for Node) and ES module (for bundlers) build. // (We could have three entries in the configuration array // instead of two, but it's quicker to generate multiple // builds from a single configuration where possible, using // an array for the `output` option, where we can specify // `file` and `format` for each target) { input: 'src/cookie.js', external: ['ms'], output: [ { file: pkg.main, format: 'cjs' }, { file: pkg.module, format: 'es' } ] }, // browser-friendly UMD minified build { input: 'src/cookie.js', output: { name: 'cookie', file: 'dist/cookie.umd.min.js', format: 'umd', }, plugins: [ resolve(), // so Rollup can find `ms` commonjs(), // so Rollup can convert `ms` to an ES module terser() // mangler/compressor toolkit ] }, ];
43
27
2
mixed
--- a/rollup.config.js +++ b/rollup.config.js @@ -2,2 +2,3 @@ import commonjs from 'rollup-plugin-commonjs'; +import { terser } from 'rollup-plugin-terser'; import pkg from './package.json'; @@ -5,30 +6,45 @@ export default [ - // browser-friendly UMD build - { - input: 'src/cookie.js', - output: { - name: 'cookie', - file: pkg.browser, - format: 'umd' - }, - plugins: [ - resolve(), // so Rollup can find `ms` - commonjs() // so Rollup can convert `ms` to an ES module - ] - }, + // browser-friendly UMD build + { + input: 'src/cookie.js', + output: { + name: 'cookie', + file: pkg.browser, + format: 'umd' + }, + plugins: [ + resolve(), // so Rollup can find `ms` + commonjs() // so Rollup can convert `ms` to an ES module + ] + }, - // CommonJS (for Node) and ES module (for bundlers) build. - // (We could have three entries in the configuration array - // instead of two, but it's quicker to generate multiple - // builds from a single configuration where possible, using - // an array for the `output` option, where we can specify - // `file` and `format` for each target) - { - input: 'src/cookie.js', - external: ['ms'], - output: [ - { file: pkg.main, format: 'cjs' }, - { file: pkg.module, format: 'es' } - ] - } + // CommonJS (for Node) and ES module (for bundlers) build. + // (We could have three entries in the configuration array + // instead of two, but it's quicker to generate multiple + // builds from a single configuration where possible, using + // an array for the `output` option, where we can specify + // `file` and `format` for each target) + { + input: 'src/cookie.js', + external: ['ms'], + output: [ + { file: pkg.main, format: 'cjs' }, + { file: pkg.module, format: 'es' } + ] + }, + + // browser-friendly UMD minified build + { + input: 'src/cookie.js', + output: { + name: 'cookie', + file: 'dist/cookie.umd.min.js', + format: 'umd', + }, + plugins: [ + resolve(), // so Rollup can find `ms` + commonjs(), // so Rollup can convert `ms` to an ES module + terser() // mangler/compressor toolkit + ] + }, ];
--- a/rollup.config.js +++ b/rollup.config.js @@ ... @@ import commonjs from 'rollup-plugin-commonjs'; +import { terser } from 'rollup-plugin-terser'; import pkg from './package.json'; @@ ... @@ export default [ - // browser-friendly UMD build - { - input: 'src/cookie.js', - output: { - name: 'cookie', - file: pkg.browser, - format: 'umd' - }, - plugins: [ - resolve(), // so Rollup can find `ms` - commonjs() // so Rollup can convert `ms` to an ES module - ] - }, + // browser-friendly UMD build + { + input: 'src/cookie.js', + output: { + name: 'cookie', + file: pkg.browser, + format: 'umd' + }, + plugins: [ + resolve(), // so Rollup can find `ms` + commonjs() // so Rollup can convert `ms` to an ES module + ] + }, - // CommonJS (for Node) and ES module (for bundlers) build. - // (We could have three entries in the configuration array - // instead of two, but it's quicker to generate multiple - // builds from a single configuration where possible, using - // an array for the `output` option, where we can specify - // `file` and `format` for each target) - { - input: 'src/cookie.js', - external: ['ms'], - output: [ - { file: pkg.main, format: 'cjs' }, - { file: pkg.module, format: 'es' } - ] - } + // CommonJS (for Node) and ES module (for bundlers) build. + // (We could have three entries in the configuration array + // instead of two, but it's quicker to generate multiple + // builds from a single configuration where possible, using + // an array for the `output` option, where we can specify + // `file` and `format` for each target) + { + input: 'src/cookie.js', + external: ['ms'], + output: [ + { file: pkg.main, format: 'cjs' }, + { file: pkg.module, format: 'es' } + ] + }, + + // browser-friendly UMD minified build + { + input: 'src/cookie.js', + output: { + name: 'cookie', + file: 'dist/cookie.umd.min.js', + format: 'umd', + }, + plugins: [ + resolve(), // so Rollup can find `ms` + commonjs(), // so Rollup can convert `ms` to an ES module + terser() // mangler/compressor toolkit + ] + }, ];
--- a/rollup.config.js +++ b/rollup.config.js @@ -2,2 +2,3 @@ CON import commonjs from 'rollup-plugin-commonjs'; ADD import { terser } from 'rollup-plugin-terser'; CON import pkg from './package.json'; @@ -5,30 +6,45 @@ CON export default [ DEL // browser-friendly UMD build DEL { DEL input: 'src/cookie.js', DEL output: { DEL name: 'cookie', DEL file: pkg.browser, DEL format: 'umd' DEL }, DEL plugins: [ DEL resolve(), // so Rollup can find `ms` DEL commonjs() // so Rollup can convert `ms` to an ES module DEL ] DEL }, ADD // browser-friendly UMD build ADD { ADD input: 'src/cookie.js', ADD output: { ADD name: 'cookie', ADD file: pkg.browser, ADD format: 'umd' ADD }, ADD plugins: [ ADD resolve(), // so Rollup can find `ms` ADD commonjs() // so Rollup can convert `ms` to an ES module ADD ] ADD }, CON DEL // CommonJS (for Node) and ES module (for bundlers) build. DEL // (We could have three entries in the configuration array DEL // instead of two, but it's quicker to generate multiple DEL // builds from a single configuration where possible, using DEL // an array for the `output` option, where we can specify DEL // `file` and `format` for each target) DEL { DEL input: 'src/cookie.js', DEL external: ['ms'], DEL output: [ DEL { file: pkg.main, format: 'cjs' }, DEL { file: pkg.module, format: 'es' } DEL ] DEL } ADD // CommonJS (for Node) and ES module (for bundlers) build. ADD // (We could have three entries in the configuration array ADD // instead of two, but it's quicker to generate multiple ADD // builds from a single configuration where possible, using ADD // an array for the `output` option, where we can specify ADD // `file` and `format` for each target) ADD { ADD input: 'src/cookie.js', ADD external: ['ms'], ADD output: [ ADD { file: pkg.main, format: 'cjs' }, ADD { file: pkg.module, format: 'es' } ADD ] ADD }, ADD ADD // browser-friendly UMD minified build ADD { ADD input: 'src/cookie.js', ADD output: { ADD name: 'cookie', ADD file: 'dist/cookie.umd.min.js', ADD format: 'umd', ADD }, ADD plugins: [ ADD resolve(), // so Rollup can find `ms` ADD commonjs(), // so Rollup can convert `ms` to an ES module ADD terser() // mangler/compressor toolkit ADD ] ADD }, CON ];
<<<<<<< SEARCH import resolve from 'rollup-plugin-node-resolve'; import commonjs from 'rollup-plugin-commonjs'; import pkg from './package.json'; export default [ // browser-friendly UMD build { input: 'src/cookie.js', output: { name: 'cookie', file: pkg.browser, format: 'umd' }, plugins: [ resolve(), // so Rollup can find `ms` commonjs() // so Rollup can convert `ms` to an ES module ] }, // CommonJS (for Node) and ES module (for bundlers) build. // (We could have three entries in the configuration array // instead of two, but it's quicker to generate multiple // builds from a single configuration where possible, using // an array for the `output` option, where we can specify // `file` and `format` for each target) { input: 'src/cookie.js', external: ['ms'], output: [ { file: pkg.main, format: 'cjs' }, { file: pkg.module, format: 'es' } ] } ]; ======= import resolve from 'rollup-plugin-node-resolve'; import commonjs from 'rollup-plugin-commonjs'; import { terser } from 'rollup-plugin-terser'; import pkg from './package.json'; export default [ // browser-friendly UMD build { input: 'src/cookie.js', output: { name: 'cookie', file: pkg.browser, format: 'umd' }, plugins: [ resolve(), // so Rollup can find `ms` commonjs() // so Rollup can convert `ms` to an ES module ] }, // CommonJS (for Node) and ES module (for bundlers) build. // (We could have three entries in the configuration array // instead of two, but it's quicker to generate multiple // builds from a single configuration where possible, using // an array for the `output` option, where we can specify // `file` and `format` for each target) { input: 'src/cookie.js', external: ['ms'], output: [ { file: pkg.main, format: 'cjs' }, { file: pkg.module, format: 'es' } ] }, // browser-friendly UMD minified build { input: 'src/cookie.js', output: { name: 'cookie', file: 'dist/cookie.umd.min.js', format: 'umd', }, plugins: [ resolve(), // so Rollup can find `ms` commonjs(), // so Rollup can convert `ms` to an ES module terser() // mangler/compressor toolkit ] }, ]; >>>>>>> REPLACE
Altometrics/jsass
686cf8c22adfa70c99c2e174a9fda614cf152880
src/main/java/io/bit3/jsass/importer/JsassCustomHeaderImporter.java
java
mit
Throw ImportException instead of RuntimeException.
package io.bit3.jsass.importer; import io.bit3.jsass.context.ImportStack; import java.net.URI; import java.net.URISyntaxException; import java.util.Collection; import java.util.LinkedList; import java.util.List; public class JsassCustomHeaderImporter implements Importer { private final ImportStack importStack; public JsassCustomHeaderImporter(ImportStack importStack) { this.importStack = importStack; } @Override public Collection<Import> apply(String url, Import previous) { List<Import> list = new LinkedList<>(); list.add(createCustomHeaderImport(previous)); return list; } private Import createCustomHeaderImport(Import previous) { int id = importStack.register(previous); StringBuilder source = new StringBuilder(); // $jsass-void: jsass_import_stack_push(<id>) !global; source.append( String.format( "$jsass-void: jsass_import_stack_push(%d) !global;%n", id ) ); try { return new Import( new URI(previous.getAbsoluteUri() + "/JSASS_CUSTOM.scss"), new URI(previous.getAbsoluteUri() + "/JSASS_CUSTOM.scss"), source.toString() ); } catch (URISyntaxException e) { throw new RuntimeException(e); } } }
package io.bit3.jsass.importer; import io.bit3.jsass.context.ImportStack; import java.net.URI; import java.net.URISyntaxException; import java.util.Collection; import java.util.LinkedList; import java.util.List; public class JsassCustomHeaderImporter implements Importer { private final ImportStack importStack; public JsassCustomHeaderImporter(ImportStack importStack) { this.importStack = importStack; } @Override public Collection<Import> apply(String url, Import previous) { List<Import> list = new LinkedList<>(); list.add(createCustomHeaderImport(previous)); return list; } private Import createCustomHeaderImport(Import previous) { int id = importStack.register(previous); StringBuilder source = new StringBuilder(); // $jsass-void: jsass_import_stack_push(<id>) !global; source.append( String.format( "$jsass-void: jsass_import_stack_push(%d) !global;%n", id ) ); try { return new Import( new URI(previous.getAbsoluteUri() + "/JSASS_CUSTOM.scss"), new URI(previous.getAbsoluteUri() + "/JSASS_CUSTOM.scss"), source.toString() ); } catch (URISyntaxException e) { throw new ImportException(e); } } }
1
1
1
mixed
--- a/src/main/java/io/bit3/jsass/importer/JsassCustomHeaderImporter.java +++ b/src/main/java/io/bit3/jsass/importer/JsassCustomHeaderImporter.java @@ -47,3 +47,3 @@ } catch (URISyntaxException e) { - throw new RuntimeException(e); + throw new ImportException(e); }
--- a/src/main/java/io/bit3/jsass/importer/JsassCustomHeaderImporter.java +++ b/src/main/java/io/bit3/jsass/importer/JsassCustomHeaderImporter.java @@ ... @@ } catch (URISyntaxException e) { - throw new RuntimeException(e); + throw new ImportException(e); }
--- a/src/main/java/io/bit3/jsass/importer/JsassCustomHeaderImporter.java +++ b/src/main/java/io/bit3/jsass/importer/JsassCustomHeaderImporter.java @@ -47,3 +47,3 @@ CON } catch (URISyntaxException e) { DEL throw new RuntimeException(e); ADD throw new ImportException(e); CON }
<<<<<<< SEARCH ); } catch (URISyntaxException e) { throw new RuntimeException(e); } } ======= ); } catch (URISyntaxException e) { throw new ImportException(e); } } >>>>>>> REPLACE
PDXFinder/pdxfinder
a66e5d5aec8c5c22f891cff4237cee50d59490d0
admin/src/main/java/org/pdxfinder/admin/controllers/AjaxController.java
java
apache-2.0
Change url and param name
package org.pdxfinder.admin.controllers; import org.pdxfinder.admin.pojos.MappingContainer; import org.pdxfinder.services.MappingService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import java.util.Optional; /* * Created by csaba on 09/07/2018. */ @RestController public class AjaxController { private MappingService mappingService; @Value("${diagnosis.mappings.file}") private String savedDiagnosisMappingsFile; @Autowired public AjaxController(MappingService mappingService) { this.mappingService = mappingService; } @RequestMapping(value = "/getmissingdiagnosismappings") @ResponseBody public MappingContainer getMissingMappings(@RequestParam("datasource") Optional<String> dataSource){ String ds = null; if(dataSource.isPresent() && !dataSource.get().isEmpty()){ ds = dataSource.get(); } return mappingService.getMissingMappings(ds); } }
package org.pdxfinder.admin.controllers; import org.pdxfinder.admin.pojos.MappingContainer; import org.pdxfinder.services.MappingService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import java.util.Optional; /* * Created by csaba on 09/07/2018. */ @RestController public class AjaxController { private MappingService mappingService; @Value("${diagnosis.mappings.file}") private String savedDiagnosisMappingsFile; @Autowired public AjaxController(MappingService mappingService) { this.mappingService = mappingService; } @RequestMapping(value = "/api/missingmapping/diagnosis") @ResponseBody public MappingContainer getMissingMappings(@RequestParam("ds") Optional<String> dataSource){ String ds = null; if(dataSource.isPresent() && !dataSource.get().isEmpty()){ ds = dataSource.get(); } return mappingService.getMissingMappings(ds); } }
2
2
1
mixed
--- a/admin/src/main/java/org/pdxfinder/admin/controllers/AjaxController.java +++ b/admin/src/main/java/org/pdxfinder/admin/controllers/AjaxController.java @@ -30,5 +30,5 @@ - @RequestMapping(value = "/getmissingdiagnosismappings") + @RequestMapping(value = "/api/missingmapping/diagnosis") @ResponseBody - public MappingContainer getMissingMappings(@RequestParam("datasource") Optional<String> dataSource){ + public MappingContainer getMissingMappings(@RequestParam("ds") Optional<String> dataSource){
--- a/admin/src/main/java/org/pdxfinder/admin/controllers/AjaxController.java +++ b/admin/src/main/java/org/pdxfinder/admin/controllers/AjaxController.java @@ ... @@ - @RequestMapping(value = "/getmissingdiagnosismappings") + @RequestMapping(value = "/api/missingmapping/diagnosis") @ResponseBody - public MappingContainer getMissingMappings(@RequestParam("datasource") Optional<String> dataSource){ + public MappingContainer getMissingMappings(@RequestParam("ds") Optional<String> dataSource){
--- a/admin/src/main/java/org/pdxfinder/admin/controllers/AjaxController.java +++ b/admin/src/main/java/org/pdxfinder/admin/controllers/AjaxController.java @@ -30,5 +30,5 @@ CON DEL @RequestMapping(value = "/getmissingdiagnosismappings") ADD @RequestMapping(value = "/api/missingmapping/diagnosis") CON @ResponseBody DEL public MappingContainer getMissingMappings(@RequestParam("datasource") Optional<String> dataSource){ ADD public MappingContainer getMissingMappings(@RequestParam("ds") Optional<String> dataSource){ CON
<<<<<<< SEARCH } @RequestMapping(value = "/getmissingdiagnosismappings") @ResponseBody public MappingContainer getMissingMappings(@RequestParam("datasource") Optional<String> dataSource){ String ds = null; ======= } @RequestMapping(value = "/api/missingmapping/diagnosis") @ResponseBody public MappingContainer getMissingMappings(@RequestParam("ds") Optional<String> dataSource){ String ds = null; >>>>>>> REPLACE
ac-adekunle/secondlead
2413449e42d25178eb86489b5da6cd2f100b9d40
app/assets/javascripts/angular/common/models/review-model.js
javascript
mit
Add find and delete functions to ang review model
(function(){ 'use strict'; angular .module('secondLead') .factory('ReviewModel',['Restangular', 'store', function(Restangular, store) { var currentUser = store.get('user'); return { getAll: function(dramaID){ return Restangular.one('dramas', dramaID).getList('reviews').$object }, getOne: function(dramaID, reviewID) { return Restangular.one('dramas', dramaID).one('reviews', reviewID).get() }, create: function(dramaID, userID, review) { return Restangular.one('dramas', dramaID).getList('reviews').post({drama_id: dramaID, body: review, reviewer_id: userID}) }, update: function(dramaID, reviewID,review){ return Restangular.one('dramas', dramaID).one('reviews', reviewID).put({body: review}) } }; }]) })();
(function(){ 'use strict'; angular .module('secondLead') .factory('ReviewModel',['$http', 'Restangular', 'store', function($http, Restangular, store) { var currentUser = store.get('user'); function extract(result) { return result.data; }; return { getAll: function(dramaID){ return Restangular.one('dramas', dramaID).getList('reviews').$object }, getOne: function(dramaID, reviewID) { return Restangular.one('dramas', dramaID).one('reviews', reviewID).get() }, create: function(dramaID, userID, review) { return Restangular.one('dramas', dramaID).all('reviews').post({drama_id: dramaID, body: review, reviewer_id: userID}) }, find: function(dramaID, userID){ return $http.get('/reviews/find', {params: {drama_id: dramaID, reviewer_id: userID}}).then(extract); }, update: function(dramaID, reviewID,review){ return Restangular.one('dramas', dramaID).one('reviews', reviewID).put({body: review}) }, delete: function(dramaID, reviewID){ return Restangular.one('dramas', dramaID).one('reviews', reviewID).remove() } }; }]) })();
14
2
3
mixed
--- a/app/assets/javascripts/angular/common/models/review-model.js +++ b/app/assets/javascripts/angular/common/models/review-model.js @@ -6,4 +6,8 @@ - .factory('ReviewModel',['Restangular', 'store', function(Restangular, store) { + .factory('ReviewModel',['$http', 'Restangular', 'store', function($http, Restangular, store) { var currentUser = store.get('user'); + function extract(result) { + return result.data; + }; + return { @@ -19,3 +23,7 @@ create: function(dramaID, userID, review) { - return Restangular.one('dramas', dramaID).getList('reviews').post({drama_id: dramaID, body: review, reviewer_id: userID}) + return Restangular.one('dramas', dramaID).all('reviews').post({drama_id: dramaID, body: review, reviewer_id: userID}) + }, + + find: function(dramaID, userID){ + return $http.get('/reviews/find', {params: {drama_id: dramaID, reviewer_id: userID}}).then(extract); }, @@ -24,2 +32,6 @@ return Restangular.one('dramas', dramaID).one('reviews', reviewID).put({body: review}) + }, + + delete: function(dramaID, reviewID){ + return Restangular.one('dramas', dramaID).one('reviews', reviewID).remove() }
--- a/app/assets/javascripts/angular/common/models/review-model.js +++ b/app/assets/javascripts/angular/common/models/review-model.js @@ ... @@ - .factory('ReviewModel',['Restangular', 'store', function(Restangular, store) { + .factory('ReviewModel',['$http', 'Restangular', 'store', function($http, Restangular, store) { var currentUser = store.get('user'); + function extract(result) { + return result.data; + }; + return { @@ ... @@ create: function(dramaID, userID, review) { - return Restangular.one('dramas', dramaID).getList('reviews').post({drama_id: dramaID, body: review, reviewer_id: userID}) + return Restangular.one('dramas', dramaID).all('reviews').post({drama_id: dramaID, body: review, reviewer_id: userID}) + }, + + find: function(dramaID, userID){ + return $http.get('/reviews/find', {params: {drama_id: dramaID, reviewer_id: userID}}).then(extract); }, @@ ... @@ return Restangular.one('dramas', dramaID).one('reviews', reviewID).put({body: review}) + }, + + delete: function(dramaID, reviewID){ + return Restangular.one('dramas', dramaID).one('reviews', reviewID).remove() }
--- a/app/assets/javascripts/angular/common/models/review-model.js +++ b/app/assets/javascripts/angular/common/models/review-model.js @@ -6,4 +6,8 @@ CON DEL .factory('ReviewModel',['Restangular', 'store', function(Restangular, store) { ADD .factory('ReviewModel',['$http', 'Restangular', 'store', function($http, Restangular, store) { CON var currentUser = store.get('user'); ADD function extract(result) { ADD return result.data; ADD }; ADD CON return { @@ -19,3 +23,7 @@ CON create: function(dramaID, userID, review) { DEL return Restangular.one('dramas', dramaID).getList('reviews').post({drama_id: dramaID, body: review, reviewer_id: userID}) ADD return Restangular.one('dramas', dramaID).all('reviews').post({drama_id: dramaID, body: review, reviewer_id: userID}) ADD }, ADD ADD find: function(dramaID, userID){ ADD return $http.get('/reviews/find', {params: {drama_id: dramaID, reviewer_id: userID}}).then(extract); CON }, @@ -24,2 +32,6 @@ CON return Restangular.one('dramas', dramaID).one('reviews', reviewID).put({body: review}) ADD }, ADD ADD delete: function(dramaID, reviewID){ ADD return Restangular.one('dramas', dramaID).one('reviews', reviewID).remove() CON }
<<<<<<< SEARCH .module('secondLead') .factory('ReviewModel',['Restangular', 'store', function(Restangular, store) { var currentUser = store.get('user'); return { ======= .module('secondLead') .factory('ReviewModel',['$http', 'Restangular', 'store', function($http, Restangular, store) { var currentUser = store.get('user'); function extract(result) { return result.data; }; return { >>>>>>> REPLACE <<<<<<< SEARCH create: function(dramaID, userID, review) { return Restangular.one('dramas', dramaID).getList('reviews').post({drama_id: dramaID, body: review, reviewer_id: userID}) }, update: function(dramaID, reviewID,review){ return Restangular.one('dramas', dramaID).one('reviews', reviewID).put({body: review}) } ======= create: function(dramaID, userID, review) { return Restangular.one('dramas', dramaID).all('reviews').post({drama_id: dramaID, body: review, reviewer_id: userID}) }, find: function(dramaID, userID){ return $http.get('/reviews/find', {params: {drama_id: dramaID, reviewer_id: userID}}).then(extract); }, update: function(dramaID, reviewID,review){ return Restangular.one('dramas', dramaID).one('reviews', reviewID).put({body: review}) }, delete: function(dramaID, reviewID){ return Restangular.one('dramas', dramaID).one('reviews', reviewID).remove() } >>>>>>> REPLACE
corcoran/AndroidDeviceNames
1e0cc652462fa8ea5dc4c8cd0ea5aa72d022a9e3
dn/src/main/java/com/github/tslamic/dn/DatabaseImpl.kt
kotlin
apache-2.0
Check and create db dir if necessary
package com.github.tslamic.dn import android.content.Context import android.content.SharedPreferences import android.database.sqlite.SQLiteDatabase import java.io.File import java.io.InputStream import java.io.OutputStream class DatabaseImpl(val context: Context) : Database { val prefs: SharedPreferences = context.getSharedPreferences("__dn__", Context.MODE_PRIVATE) val database: File = context.getDatabasePath("dn.db") val version: Long = 2L override fun copyFromAssets() { val key = "version" if (!database.isValid() || version != prefs.getLong(key, 0)) { val src = context.assets.open("dn.db") copy(src, database.outputStream(), key, version) } } override fun instance(): SQLiteDatabase? { if (database.isValid()) { return SQLiteDatabase.openDatabase(database.absolutePath, null, SQLiteDatabase.OPEN_READONLY) } return null } private fun copy(src: InputStream, dst: OutputStream, key: String, version: Long) { src.use { s -> dst.use { d -> if (s.copyTo(d) > 0) { prefs.edit().putLong(key, version).apply() } } } } private fun File.isValid(): Boolean { return this.exists() && this.length() > 0 } }
package com.github.tslamic.dn import android.content.Context import android.content.SharedPreferences import android.database.sqlite.SQLiteDatabase import java.io.File import java.io.IOException import java.io.InputStream import java.io.OutputStream class DatabaseImpl(val context: Context) : Database { val prefs: SharedPreferences = context.getSharedPreferences("__dn__", Context.MODE_PRIVATE) val database: File = context.getDatabasePath("dn.db") val version: Long = 2L override fun copyFromAssets() { val key = "version" if (!database.isValid() || version != prefs.getLong(key, 0)) { if (!database.parentFile.exists() && !database.parentFile.mkdir()) { throw IOException("Couldn't create db dir") } val src = context.assets.open("dn.db") copy(src, database.outputStream(), key, version) } } override fun instance(): SQLiteDatabase? { if (database.isValid()) { return SQLiteDatabase.openDatabase(database.absolutePath, null, SQLiteDatabase.OPEN_READONLY) } return null } private fun copy(src: InputStream, dst: OutputStream, key: String, version: Long) { src.use { s -> dst.use { d -> if (s.copyTo(d) > 0) { prefs.edit().putLong(key, version).apply() } } } } private fun File.isValid(): Boolean { return this.exists() && this.length() > 0 } }
4
0
2
add_only
--- a/dn/src/main/java/com/github/tslamic/dn/DatabaseImpl.kt +++ b/dn/src/main/java/com/github/tslamic/dn/DatabaseImpl.kt @@ -6,2 +6,3 @@ import java.io.File +import java.io.IOException import java.io.InputStream @@ -17,2 +18,5 @@ if (!database.isValid() || version != prefs.getLong(key, 0)) { + if (!database.parentFile.exists() && !database.parentFile.mkdir()) { + throw IOException("Couldn't create db dir") + } val src = context.assets.open("dn.db")
--- a/dn/src/main/java/com/github/tslamic/dn/DatabaseImpl.kt +++ b/dn/src/main/java/com/github/tslamic/dn/DatabaseImpl.kt @@ ... @@ import java.io.File +import java.io.IOException import java.io.InputStream @@ ... @@ if (!database.isValid() || version != prefs.getLong(key, 0)) { + if (!database.parentFile.exists() && !database.parentFile.mkdir()) { + throw IOException("Couldn't create db dir") + } val src = context.assets.open("dn.db")
--- a/dn/src/main/java/com/github/tslamic/dn/DatabaseImpl.kt +++ b/dn/src/main/java/com/github/tslamic/dn/DatabaseImpl.kt @@ -6,2 +6,3 @@ CON import java.io.File ADD import java.io.IOException CON import java.io.InputStream @@ -17,2 +18,5 @@ CON if (!database.isValid() || version != prefs.getLong(key, 0)) { ADD if (!database.parentFile.exists() && !database.parentFile.mkdir()) { ADD throw IOException("Couldn't create db dir") ADD } CON val src = context.assets.open("dn.db")
<<<<<<< SEARCH import android.database.sqlite.SQLiteDatabase import java.io.File import java.io.InputStream import java.io.OutputStream ======= import android.database.sqlite.SQLiteDatabase import java.io.File import java.io.IOException import java.io.InputStream import java.io.OutputStream >>>>>>> REPLACE <<<<<<< SEARCH val key = "version" if (!database.isValid() || version != prefs.getLong(key, 0)) { val src = context.assets.open("dn.db") copy(src, database.outputStream(), key, version) ======= val key = "version" if (!database.isValid() || version != prefs.getLong(key, 0)) { if (!database.parentFile.exists() && !database.parentFile.mkdir()) { throw IOException("Couldn't create db dir") } val src = context.assets.open("dn.db") copy(src, database.outputStream(), key, version) >>>>>>> REPLACE
glyph/txsni
49ac4dc3e7506f35d2f3ad695afaf9c89f08720b
setup.py
python
mit
Install the tests and test utilities
import os from setuptools import setup base_dir = os.path.dirname(__file__) with open(os.path.join(base_dir, "README.rst")) as f: long_description = f.read() setup( name="TxSNI", description="easy-to-use SNI endpoint for twisted", packages=[ "txsni", "twisted.plugins", ], install_requires=[ "Twisted[tls]>=14.0", "pyOpenSSL>=0.14", ], version="0.1.6", long_description=long_description, license="MIT", url="https://github.com/glyph/txsni", classifiers=[ "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Natural Language :: English", "Operating System :: MacOS :: MacOS X", "Operating System :: POSIX", "Operating System :: POSIX :: Linux", "Programming Language :: Python", "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: Implementation :: CPython", "Programming Language :: Python :: Implementation :: PyPy", "Topic :: Security :: Cryptography", ], )
import os from setuptools import setup base_dir = os.path.dirname(__file__) with open(os.path.join(base_dir, "README.rst")) as f: long_description = f.read() setup( name="TxSNI", description="easy-to-use SNI endpoint for twisted", packages=[ "txsni", "txsni.test", "txsni.test.certs", "twisted.plugins", ], install_requires=[ "Twisted[tls]>=14.0", "pyOpenSSL>=0.14", ], version="0.1.6", long_description=long_description, license="MIT", url="https://github.com/glyph/txsni", classifiers=[ "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Natural Language :: English", "Operating System :: MacOS :: MacOS X", "Operating System :: POSIX", "Operating System :: POSIX :: Linux", "Programming Language :: Python", "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: Implementation :: CPython", "Programming Language :: Python :: Implementation :: PyPy", "Topic :: Security :: Cryptography", ], )
2
0
1
add_only
--- a/setup.py +++ b/setup.py @@ -15,2 +15,4 @@ "txsni", + "txsni.test", + "txsni.test.certs", "twisted.plugins",
--- a/setup.py +++ b/setup.py @@ ... @@ "txsni", + "txsni.test", + "txsni.test.certs", "twisted.plugins",
--- a/setup.py +++ b/setup.py @@ -15,2 +15,4 @@ CON "txsni", ADD "txsni.test", ADD "txsni.test.certs", CON "twisted.plugins",
<<<<<<< SEARCH packages=[ "txsni", "twisted.plugins", ], ======= packages=[ "txsni", "txsni.test", "txsni.test.certs", "twisted.plugins", ], >>>>>>> REPLACE
iKevinY/ultra
f201fac99b4ae0e6485121e166c926988c8328b9
src/lib.rs
rust
mit
Add length field to Rotor struct
use std::ascii::AsciiExt; struct Rotor<'a> { rotor: &'a [u8] } impl<'a> Rotor<'a> { pub fn new(rotor: &'a str) -> Rotor<'a> { Rotor { rotor: rotor.as_bytes(), } } fn substitute(&self, c: char) -> char { if !c.is_ascii() || !c.is_alphabetic() { return c; } let letter = c.to_ascii_uppercase(); let offset = ((letter as u8) - ('A' as u8)) as usize; self.rotor[offset] as char } } #[cfg(test)] mod tests { use super::Rotor; #[test] fn char_substitution() { let rotor = Rotor::new("XYZ"); assert!(rotor.substitute('A') == 'X'); assert!(rotor.substitute('b') == 'Y'); assert!(rotor.substitute('!') == '!'); assert!(rotor.substitute('é') == 'é'); } }
use std::ascii::AsciiExt; struct Rotor<'a> { rotor: &'a [u8], length: usize, } impl<'a> Rotor<'a> { pub fn new(rotor: &'a str) -> Rotor<'a> { Rotor { rotor: rotor.as_bytes(), length: rotor.len(), } } fn substitute(&self, c: char) -> char { if !c.is_ascii() || !c.is_alphabetic() { return c; } let letter = c.to_ascii_uppercase(); let offset = ((letter as u8) - ('A' as u8)) as usize; self.rotor[offset % self.length] as char } } #[cfg(test)] mod tests { use super::Rotor; #[test] fn char_substitution() { let rotor = Rotor::new("XYZ"); assert!(rotor.substitute('A') == 'X'); assert!(rotor.substitute('b') == 'Y'); assert!(rotor.substitute('F') == 'Z'); assert!(rotor.substitute('!') == '!'); assert!(rotor.substitute('é') == 'é'); } }
5
2
4
mixed
--- a/src/lib.rs +++ b/src/lib.rs @@ -3,3 +3,4 @@ struct Rotor<'a> { - rotor: &'a [u8] + rotor: &'a [u8], + length: usize, } @@ -10,2 +11,3 @@ rotor: rotor.as_bytes(), + length: rotor.len(), } @@ -21,3 +23,3 @@ - self.rotor[offset] as char + self.rotor[offset % self.length] as char } @@ -35,2 +37,3 @@ assert!(rotor.substitute('b') == 'Y'); + assert!(rotor.substitute('F') == 'Z'); assert!(rotor.substitute('!') == '!');
--- a/src/lib.rs +++ b/src/lib.rs @@ ... @@ struct Rotor<'a> { - rotor: &'a [u8] + rotor: &'a [u8], + length: usize, } @@ ... @@ rotor: rotor.as_bytes(), + length: rotor.len(), } @@ ... @@ - self.rotor[offset] as char + self.rotor[offset % self.length] as char } @@ ... @@ assert!(rotor.substitute('b') == 'Y'); + assert!(rotor.substitute('F') == 'Z'); assert!(rotor.substitute('!') == '!');
--- a/src/lib.rs +++ b/src/lib.rs @@ -3,3 +3,4 @@ CON struct Rotor<'a> { DEL rotor: &'a [u8] ADD rotor: &'a [u8], ADD length: usize, CON } @@ -10,2 +11,3 @@ CON rotor: rotor.as_bytes(), ADD length: rotor.len(), CON } @@ -21,3 +23,3 @@ CON DEL self.rotor[offset] as char ADD self.rotor[offset % self.length] as char CON } @@ -35,2 +37,3 @@ CON assert!(rotor.substitute('b') == 'Y'); ADD assert!(rotor.substitute('F') == 'Z'); CON assert!(rotor.substitute('!') == '!');
<<<<<<< SEARCH struct Rotor<'a> { rotor: &'a [u8] } ======= struct Rotor<'a> { rotor: &'a [u8], length: usize, } >>>>>>> REPLACE <<<<<<< SEARCH Rotor { rotor: rotor.as_bytes(), } } ======= Rotor { rotor: rotor.as_bytes(), length: rotor.len(), } } >>>>>>> REPLACE <<<<<<< SEARCH let offset = ((letter as u8) - ('A' as u8)) as usize; self.rotor[offset] as char } } ======= let offset = ((letter as u8) - ('A' as u8)) as usize; self.rotor[offset % self.length] as char } } >>>>>>> REPLACE <<<<<<< SEARCH assert!(rotor.substitute('A') == 'X'); assert!(rotor.substitute('b') == 'Y'); assert!(rotor.substitute('!') == '!'); assert!(rotor.substitute('é') == 'é'); ======= assert!(rotor.substitute('A') == 'X'); assert!(rotor.substitute('b') == 'Y'); assert!(rotor.substitute('F') == 'Z'); assert!(rotor.substitute('!') == '!'); assert!(rotor.substitute('é') == 'é'); >>>>>>> REPLACE
JCThePants/MusicalRegions
ca5be47355899ab8449c4176f5332a972fe03034
src/com/jcwhatever/bukkit/musical/MusicalRegions.java
java
mit
Add comments to GenericsPlugin, refactor GenericsPlugin.getSettings to getDataNode
package com.jcwhatever.bukkit.musical; import com.jcwhatever.bukkit.generic.GenericsPlugin; import com.jcwhatever.bukkit.musical.commands.CommandHandler; import com.jcwhatever.bukkit.musical.regions.RegionManager; import org.bukkit.ChatColor; public class MusicalRegions extends GenericsPlugin { private static MusicalRegions _instance; private RegionManager _regionManager; public static MusicalRegions getInstance() { return _instance; } public MusicalRegions() { super(); } @Override protected void init() { _instance = this; } @Override public String getChatPrefix() { return ChatColor.LIGHT_PURPLE + "[Music] " + ChatColor.RESET; } @Override public String getConsolePrefix() { return "[Music] "; } public RegionManager getRegionManager() { return _regionManager; } @Override protected void onEnablePlugin() { registerCommands(new CommandHandler()); registerEventListeners(new EventListener()); _regionManager = new RegionManager(this.getSettings().getNode("regions")); } @Override protected void onDisablePlugin() { } }
package com.jcwhatever.bukkit.musical; import com.jcwhatever.bukkit.generic.GenericsPlugin; import com.jcwhatever.bukkit.musical.commands.CommandHandler; import com.jcwhatever.bukkit.musical.regions.RegionManager; import org.bukkit.ChatColor; public class MusicalRegions extends GenericsPlugin { private static MusicalRegions _instance; private RegionManager _regionManager; public static MusicalRegions getInstance() { return _instance; } public MusicalRegions() { super(); } @Override protected void init() { _instance = this; } @Override public String getChatPrefix() { return ChatColor.LIGHT_PURPLE + "[Music] " + ChatColor.RESET; } @Override public String getConsolePrefix() { return "[Music] "; } public RegionManager getRegionManager() { return _regionManager; } @Override protected void onEnablePlugin() { registerCommands(new CommandHandler()); registerEventListeners(new EventListener()); _regionManager = new RegionManager(this.getDataNode().getNode("regions")); } @Override protected void onDisablePlugin() { } }
1
1
1
mixed
--- a/src/com/jcwhatever/bukkit/musical/MusicalRegions.java +++ b/src/com/jcwhatever/bukkit/musical/MusicalRegions.java @@ -46,3 +46,3 @@ - _regionManager = new RegionManager(this.getSettings().getNode("regions")); + _regionManager = new RegionManager(this.getDataNode().getNode("regions")); }
--- a/src/com/jcwhatever/bukkit/musical/MusicalRegions.java +++ b/src/com/jcwhatever/bukkit/musical/MusicalRegions.java @@ ... @@ - _regionManager = new RegionManager(this.getSettings().getNode("regions")); + _regionManager = new RegionManager(this.getDataNode().getNode("regions")); }
--- a/src/com/jcwhatever/bukkit/musical/MusicalRegions.java +++ b/src/com/jcwhatever/bukkit/musical/MusicalRegions.java @@ -46,3 +46,3 @@ CON DEL _regionManager = new RegionManager(this.getSettings().getNode("regions")); ADD _regionManager = new RegionManager(this.getDataNode().getNode("regions")); CON }
<<<<<<< SEARCH registerEventListeners(new EventListener()); _regionManager = new RegionManager(this.getSettings().getNode("regions")); } ======= registerEventListeners(new EventListener()); _regionManager = new RegionManager(this.getDataNode().getNode("regions")); } >>>>>>> REPLACE
cgwire/zou
7418079606a6e24cb0dccfa148b47c3f736e985f
zou/app/blueprints/persons/resources.py
python
agpl-3.0
Allow to set role while creating a person
from flask import abort from flask_restful import Resource, reqparse from flask_jwt_extended import jwt_required from zou.app.services import persons_service from zou.app.utils import auth, permissions class NewPersonResource(Resource): @jwt_required def post(self): permissions.check_admin_permissions() data = self.get_arguments() person = persons_service.create_person( data["email"], auth.encrypt_password("default"), data["first_name"], data["last_name"], data["phone"] ) return person, 201 def get_arguments(self): parser = reqparse.RequestParser() parser.add_argument( "email", help="The email is required.", required=True ) parser.add_argument( "first_name", help="The first name is required.", required=True ) parser.add_argument( "last_name", help="The last name is required.", required=True ) parser.add_argument("phone", default="") args = parser.parse_args() return args
from flask import abort from flask_restful import Resource, reqparse from flask_jwt_extended import jwt_required from zou.app.services import persons_service from zou.app.utils import auth, permissions class NewPersonResource(Resource): @jwt_required def post(self): permissions.check_admin_permissions() data = self.get_arguments() person = persons_service.create_person( data["email"], auth.encrypt_password("default"), data["first_name"], data["last_name"], data["phone"], role=data["role"] ) return person, 201 def get_arguments(self): parser = reqparse.RequestParser() parser.add_argument( "email", help="The email is required.", required=True ) parser.add_argument( "first_name", help="The first name is required.", required=True ) parser.add_argument( "last_name", help="The last name is required.", required=True ) parser.add_argument("phone", default="") parser.add_argument("role", default="user") args = parser.parse_args() return args
3
1
2
mixed
--- a/zou/app/blueprints/persons/resources.py +++ b/zou/app/blueprints/persons/resources.py @@ -19,3 +19,4 @@ data["last_name"], - data["phone"] + data["phone"], + role=data["role"] ) @@ -41,2 +42,3 @@ parser.add_argument("phone", default="") + parser.add_argument("role", default="user") args = parser.parse_args()
--- a/zou/app/blueprints/persons/resources.py +++ b/zou/app/blueprints/persons/resources.py @@ ... @@ data["last_name"], - data["phone"] + data["phone"], + role=data["role"] ) @@ ... @@ parser.add_argument("phone", default="") + parser.add_argument("role", default="user") args = parser.parse_args()
--- a/zou/app/blueprints/persons/resources.py +++ b/zou/app/blueprints/persons/resources.py @@ -19,3 +19,4 @@ CON data["last_name"], DEL data["phone"] ADD data["phone"], ADD role=data["role"] CON ) @@ -41,2 +42,3 @@ CON parser.add_argument("phone", default="") ADD parser.add_argument("role", default="user") CON args = parser.parse_args()
<<<<<<< SEARCH data["first_name"], data["last_name"], data["phone"] ) return person, 201 ======= data["first_name"], data["last_name"], data["phone"], role=data["role"] ) return person, 201 >>>>>>> REPLACE <<<<<<< SEARCH ) parser.add_argument("phone", default="") args = parser.parse_args() return args ======= ) parser.add_argument("phone", default="") parser.add_argument("role", default="user") args = parser.parse_args() return args >>>>>>> REPLACE
fitermay/intellij-community
232212c0f0a3b1fbcc09dd0d017caa6abcd8a9ea
platform/platform-impl/src/com/intellij/remote/RemoteConnectionType.java
java
apache-2.0
Return NONE connection type for null.
package com.intellij.remote; import com.intellij.openapi.diagnostic.Logger; /** * This class denotes the type of the source to obtain remote credentials. * * @author traff */ public enum RemoteConnectionType { /** * Currently selected SDK (e.g. <Project default>) */ DEFAULT_SDK, /** * Web deployment server */ DEPLOYMENT_SERVER, /** * Remote SDK */ REMOTE_SDK, /** * Current project vagrant */ CURRENT_VAGRANT, /** * No source is predefined - it would be asked on request */ NONE; private static final Logger LOG = Logger.getInstance(RemoteConnectionType.class); public static RemoteConnectionType findByName(String name) { try { return valueOf(name); } catch (Exception e) { LOG.error("Cant find RemoteConnectionType with the name " + name, e); return NONE; } } }
package com.intellij.remote; import com.intellij.openapi.diagnostic.Logger; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; /** * This class denotes the type of the source to obtain remote credentials. * * @author traff */ public enum RemoteConnectionType { /** * Currently selected SDK (e.g. <Project default>) */ DEFAULT_SDK, /** * Web deployment server */ DEPLOYMENT_SERVER, /** * Remote SDK */ REMOTE_SDK, /** * Current project vagrant */ CURRENT_VAGRANT, /** * No source is predefined - it would be asked on request */ NONE; private static final Logger LOG = Logger.getInstance(RemoteConnectionType.class); @NotNull public static RemoteConnectionType findByName(@Nullable String name) { if (name == null) { return NONE; } try { return valueOf(name); } catch (Exception e) { LOG.error("Cant find RemoteConnectionType with the name " + name, e); return NONE; } } }
7
1
2
mixed
--- a/platform/platform-impl/src/com/intellij/remote/RemoteConnectionType.java +++ b/platform/platform-impl/src/com/intellij/remote/RemoteConnectionType.java @@ -3,2 +3,4 @@ import com.intellij.openapi.diagnostic.Logger; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; @@ -33,3 +35,7 @@ - public static RemoteConnectionType findByName(String name) { + @NotNull + public static RemoteConnectionType findByName(@Nullable String name) { + if (name == null) { + return NONE; + } try {
--- a/platform/platform-impl/src/com/intellij/remote/RemoteConnectionType.java +++ b/platform/platform-impl/src/com/intellij/remote/RemoteConnectionType.java @@ ... @@ import com.intellij.openapi.diagnostic.Logger; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; @@ ... @@ - public static RemoteConnectionType findByName(String name) { + @NotNull + public static RemoteConnectionType findByName(@Nullable String name) { + if (name == null) { + return NONE; + } try {
--- a/platform/platform-impl/src/com/intellij/remote/RemoteConnectionType.java +++ b/platform/platform-impl/src/com/intellij/remote/RemoteConnectionType.java @@ -3,2 +3,4 @@ CON import com.intellij.openapi.diagnostic.Logger; ADD import org.jetbrains.annotations.NotNull; ADD import org.jetbrains.annotations.Nullable; CON @@ -33,3 +35,7 @@ CON DEL public static RemoteConnectionType findByName(String name) { ADD @NotNull ADD public static RemoteConnectionType findByName(@Nullable String name) { ADD if (name == null) { ADD return NONE; ADD } CON try {
<<<<<<< SEARCH import com.intellij.openapi.diagnostic.Logger; /** ======= import com.intellij.openapi.diagnostic.Logger; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; /** >>>>>>> REPLACE <<<<<<< SEARCH private static final Logger LOG = Logger.getInstance(RemoteConnectionType.class); public static RemoteConnectionType findByName(String name) { try { return valueOf(name); ======= private static final Logger LOG = Logger.getInstance(RemoteConnectionType.class); @NotNull public static RemoteConnectionType findByName(@Nullable String name) { if (name == null) { return NONE; } try { return valueOf(name); >>>>>>> REPLACE
eriol/circuits
0b5cc3f4702081eb565ef83c3175efc4e8b30e75
circuits/node/node.py
python
mit
Fix channel definition in add method
# Module: node # Date: ... # Author: ... """Node ... """ from .client import Client from .server import Server from circuits import handler, BaseComponent class Node(BaseComponent): """Node ... """ channel = "node" def __init__(self, bind=None, channel=channel, **kwargs): super(Node, self).__init__(channel=channel, **kwargs) self.bind = bind self.nodes = {} self.__client_event_firewall = kwargs.get( 'client_event_firewall', None ) if self.bind is not None: self.server = Server( self.bind, channel=channel, **kwargs ).register(self) else: self.server = None def add(self, name, host, port, **kwargs): channel = kwargs['channel'] if 'channel' in kwargs else \ '%s_client_%s' % (self.channel, name) node = Client(host, port, channel=channel, **kwargs) node.register(self) self.nodes[name] = node return channel @handler("remote") def _on_remote(self, event, e, client_name, channel=None): if self.__client_event_firewall and \ not self.__client_event_firewall(event, client_name, channel): return node = self.nodes[client_name] if channel is not None: e.channels = (channel,) return node.send(event, e)
# Module: node # Date: ... # Author: ... """Node ... """ from .client import Client from .server import Server from circuits import handler, BaseComponent class Node(BaseComponent): """Node ... """ channel = "node" def __init__(self, bind=None, channel=channel, **kwargs): super(Node, self).__init__(channel=channel, **kwargs) self.bind = bind self.nodes = {} self.__client_event_firewall = kwargs.get( 'client_event_firewall', None ) if self.bind is not None: self.server = Server( self.bind, channel=channel, **kwargs ).register(self) else: self.server = None def add(self, name, host, port, **kwargs): channel = kwargs.pop('channel', '%s_client_%s' % (self.channel, name)) node = Client(host, port, channel=channel, **kwargs) node.register(self) self.nodes[name] = node return channel @handler("remote") def _on_remote(self, event, e, client_name, channel=None): if self.__client_event_firewall and \ not self.__client_event_firewall(event, client_name, channel): return node = self.nodes[client_name] if channel is not None: e.channels = (channel,) return node.send(event, e)
1
2
1
mixed
--- a/circuits/node/node.py +++ b/circuits/node/node.py @@ -43,4 +43,3 @@ def add(self, name, host, port, **kwargs): - channel = kwargs['channel'] if 'channel' in kwargs else \ - '%s_client_%s' % (self.channel, name) + channel = kwargs.pop('channel', '%s_client_%s' % (self.channel, name)) node = Client(host, port, channel=channel, **kwargs)
--- a/circuits/node/node.py +++ b/circuits/node/node.py @@ ... @@ def add(self, name, host, port, **kwargs): - channel = kwargs['channel'] if 'channel' in kwargs else \ - '%s_client_%s' % (self.channel, name) + channel = kwargs.pop('channel', '%s_client_%s' % (self.channel, name)) node = Client(host, port, channel=channel, **kwargs)
--- a/circuits/node/node.py +++ b/circuits/node/node.py @@ -43,4 +43,3 @@ CON def add(self, name, host, port, **kwargs): DEL channel = kwargs['channel'] if 'channel' in kwargs else \ DEL '%s_client_%s' % (self.channel, name) ADD channel = kwargs.pop('channel', '%s_client_%s' % (self.channel, name)) CON node = Client(host, port, channel=channel, **kwargs)
<<<<<<< SEARCH def add(self, name, host, port, **kwargs): channel = kwargs['channel'] if 'channel' in kwargs else \ '%s_client_%s' % (self.channel, name) node = Client(host, port, channel=channel, **kwargs) node.register(self) ======= def add(self, name, host, port, **kwargs): channel = kwargs.pop('channel', '%s_client_%s' % (self.channel, name)) node = Client(host, port, channel=channel, **kwargs) node.register(self) >>>>>>> REPLACE
Davids89/KotlinChuck
625f9c4a101902876121a240a4151d67108c0a70
app/src/main/java/com/example/david/kotlinchuck/findJoke/FindJokePresenterImpl.kt
kotlin
apache-2.0
Call the view method when the event is successfull
package com.example.david.kotlinchuck.findJoke import com.example.david.kotlinchuck.findJoke.event.FindJokeEvent import com.example.david.kotlinchuck.findJoke.ui.FindJokeView import com.example.david.kotlinchuck.lib.EventBus import com.example.david.kotlinchuck.lib.GreenRobotEventBus import org.greenrobot.eventbus.Subscribe /** * Created by david on 28/6/17. */ class FindJokePresenterImpl(view: FindJokeView) : FindJokePresenter { var view: FindJokeView? = view var eventBus: EventBus = GreenRobotEventBus.INSTANCE var repository: FindJokeRepository = FindJokeRepositoryImpl() override fun onCreate() { if(view != null){ this.eventBus.register(this) } } override fun onDestroy() { this.eventBus.unregister(this) view = null } override fun findJoke(name: String, lastname: String) { var finalName: String? = null var finalLastName: String? = null if(!name.isEmpty()) finalName = name if(!lastname.isEmpty()) finalLastName = lastname repository.findJoke(name, lastname) } @Subscribe override fun onEventMainThread(event: FindJokeEvent) { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } }
package com.example.david.kotlinchuck.findJoke import com.example.david.kotlinchuck.findJoke.event.FindJokeEvent import com.example.david.kotlinchuck.findJoke.ui.FindJokeView import com.example.david.kotlinchuck.lib.EventBus import com.example.david.kotlinchuck.lib.GreenRobotEventBus import org.greenrobot.eventbus.Subscribe /** * Created by david on 28/6/17. */ class FindJokePresenterImpl(view: FindJokeView) : FindJokePresenter { var view: FindJokeView? = view var eventBus: EventBus = GreenRobotEventBus.INSTANCE var repository: FindJokeRepository = FindJokeRepositoryImpl() override fun onCreate() { if(view != null){ this.eventBus.register(this) } } override fun onDestroy() { this.eventBus.unregister(this) view = null } override fun findJoke(name: String, lastname: String) { var finalName: String? = null var finalLastName: String? = null if(!name.isEmpty()) finalName = name if(!lastname.isEmpty()) finalLastName = lastname repository.findJoke(name, lastname) } @Subscribe override fun onEventMainThread(event: FindJokeEvent) { when(event.type){ FindJokeEvent.onSuccess -> view?.jokeSuccess(event.joke!!) } } }
4
1
1
mixed
--- a/app/src/main/java/com/example/david/kotlinchuck/findJoke/FindJokePresenterImpl.kt +++ b/app/src/main/java/com/example/david/kotlinchuck/findJoke/FindJokePresenterImpl.kt @@ -45,3 +45,6 @@ override fun onEventMainThread(event: FindJokeEvent) { - TODO("not implemented") //To change body of created functions use File | Settings | File Templates. + + when(event.type){ + FindJokeEvent.onSuccess -> view?.jokeSuccess(event.joke!!) + } }
--- a/app/src/main/java/com/example/david/kotlinchuck/findJoke/FindJokePresenterImpl.kt +++ b/app/src/main/java/com/example/david/kotlinchuck/findJoke/FindJokePresenterImpl.kt @@ ... @@ override fun onEventMainThread(event: FindJokeEvent) { - TODO("not implemented") //To change body of created functions use File | Settings | File Templates. + + when(event.type){ + FindJokeEvent.onSuccess -> view?.jokeSuccess(event.joke!!) + } }
--- a/app/src/main/java/com/example/david/kotlinchuck/findJoke/FindJokePresenterImpl.kt +++ b/app/src/main/java/com/example/david/kotlinchuck/findJoke/FindJokePresenterImpl.kt @@ -45,3 +45,6 @@ CON override fun onEventMainThread(event: FindJokeEvent) { DEL TODO("not implemented") //To change body of created functions use File | Settings | File Templates. ADD ADD when(event.type){ ADD FindJokeEvent.onSuccess -> view?.jokeSuccess(event.joke!!) ADD } CON }
<<<<<<< SEARCH @Subscribe override fun onEventMainThread(event: FindJokeEvent) { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } ======= @Subscribe override fun onEventMainThread(event: FindJokeEvent) { when(event.type){ FindJokeEvent.onSuccess -> view?.jokeSuccess(event.joke!!) } } >>>>>>> REPLACE
BjoernPetersen/JMusicBot
88f879aa5010a343b0d78306fcac12c6ace3dcc5
src/main/kotlin/net/bjoernpetersen/musicbot/spi/plugin/predefined/AudioFilePlaybackFactory.kt
kotlin
mit
Make AacPlabackFactory deprecation a warning
package net.bjoernpetersen.musicbot.spi.plugin.predefined import net.bjoernpetersen.musicbot.api.plugin.Base /** * PlaybackFactory capable of playing `.aac` and `.m4a` files. */ @Base interface AacPlaybackFactory : FilePlaybackFactory /** * PlaybackFactory capable of playing `.aac` and `.m4a` files. */ @Deprecated( "Use non-typo version", ReplaceWith("AacPlaybackFactory"), level = DeprecationLevel.ERROR ) typealias AacPlabackFactory = AacPlaybackFactory /** * PlaybackFactory capable of playing `.flac` files. */ @Base interface FlacPlaybackFactory : FilePlaybackFactory /** * PlaybackFactory capable of playing `.mp3` files. */ @Base interface Mp3PlaybackFactory : FilePlaybackFactory /** * PlaybackFactory capable of playing `.opus` files. */ @Base interface OpusPlaybackFactory : FilePlaybackFactory /** * PlaybackFactory capable of playing `.ogg` and `.oga` files. */ @Base interface VorbisPlaybackFactory : FilePlaybackFactory /** * PlaybackFactory capable of playing `.wav` and `.wave` files. */ @Base interface WavePlaybackFactory : FilePlaybackFactory /** * PlaybackFactory capable of playing `.wma` files. */ @Base interface WmaPlaybackFactory : FilePlaybackFactory
package net.bjoernpetersen.musicbot.spi.plugin.predefined import net.bjoernpetersen.musicbot.api.plugin.Base /** * PlaybackFactory capable of playing `.aac` and `.m4a` files. */ @Base interface AacPlaybackFactory : FilePlaybackFactory /** * PlaybackFactory capable of playing `.aac` and `.m4a` files. */ @Deprecated( "Use non-typo version", ReplaceWith("AacPlaybackFactory") ) typealias AacPlabackFactory = AacPlaybackFactory /** * PlaybackFactory capable of playing `.flac` files. */ @Base interface FlacPlaybackFactory : FilePlaybackFactory /** * PlaybackFactory capable of playing `.mp3` files. */ @Base interface Mp3PlaybackFactory : FilePlaybackFactory /** * PlaybackFactory capable of playing `.opus` files. */ @Base interface OpusPlaybackFactory : FilePlaybackFactory /** * PlaybackFactory capable of playing `.ogg` and `.oga` files. */ @Base interface VorbisPlaybackFactory : FilePlaybackFactory /** * PlaybackFactory capable of playing `.wav` and `.wave` files. */ @Base interface WavePlaybackFactory : FilePlaybackFactory /** * PlaybackFactory capable of playing `.wma` files. */ @Base interface WmaPlaybackFactory : FilePlaybackFactory
1
2
1
mixed
--- a/src/main/kotlin/net/bjoernpetersen/musicbot/spi/plugin/predefined/AudioFilePlaybackFactory.kt +++ b/src/main/kotlin/net/bjoernpetersen/musicbot/spi/plugin/predefined/AudioFilePlaybackFactory.kt @@ -16,4 +16,3 @@ "Use non-typo version", - ReplaceWith("AacPlaybackFactory"), - level = DeprecationLevel.ERROR + ReplaceWith("AacPlaybackFactory") )
--- a/src/main/kotlin/net/bjoernpetersen/musicbot/spi/plugin/predefined/AudioFilePlaybackFactory.kt +++ b/src/main/kotlin/net/bjoernpetersen/musicbot/spi/plugin/predefined/AudioFilePlaybackFactory.kt @@ ... @@ "Use non-typo version", - ReplaceWith("AacPlaybackFactory"), - level = DeprecationLevel.ERROR + ReplaceWith("AacPlaybackFactory") )
--- a/src/main/kotlin/net/bjoernpetersen/musicbot/spi/plugin/predefined/AudioFilePlaybackFactory.kt +++ b/src/main/kotlin/net/bjoernpetersen/musicbot/spi/plugin/predefined/AudioFilePlaybackFactory.kt @@ -16,4 +16,3 @@ CON "Use non-typo version", DEL ReplaceWith("AacPlaybackFactory"), DEL level = DeprecationLevel.ERROR ADD ReplaceWith("AacPlaybackFactory") CON )
<<<<<<< SEARCH @Deprecated( "Use non-typo version", ReplaceWith("AacPlaybackFactory"), level = DeprecationLevel.ERROR ) typealias AacPlabackFactory = AacPlaybackFactory ======= @Deprecated( "Use non-typo version", ReplaceWith("AacPlaybackFactory") ) typealias AacPlabackFactory = AacPlaybackFactory >>>>>>> REPLACE
mossberg/relish
6ee768244b39680600e83deaa725afe20a666729
src/main.rs
rust
mit
Add executation of single commands - no arguments allowed - breaks on Ctrl-d, exits on Ctrl-c
use std::io; use std::io::Write; // need it to flush stdout static PROMPT: &'static str = "$ "; fn execute(cmd: &String) { println!("you entered [{}]", cmd); } fn main() { // we allocate a String for the user input let mut input: String = String::new(); loop { print!("{}", PROMPT); if let Err(why) = io::stdout().flush() { println!("error: {}", why); continue; } // input probably has stuff in it from the last command, so clear // it out input.clear(); // read input into our String. if there was an error, print the // error message and continue if let Err(why) = io::stdin().read_line(&mut input){ println!("error: {}", why); continue; } // trim the newline off and save it back input = input.trim().to_string(); execute(&input); if input == "exit" { println!("Exiting!"); break; } } }
use std::io; use std::io::Write; // need it to flush stdout use std::process; static PROMPT: &'static str = "$ "; fn execute(cmd: &String) { let ret = process::Command::new(cmd).output().unwrap(); println!("{}", String::from_utf8_lossy(&ret.stdout).trim()); } fn main() { // we allocate a String for the user input let mut input: String = String::new(); loop { print!("{}", PROMPT); if let Err(why) = io::stdout().flush() { println!("error: {}", why); continue; } // input probably has stuff in it from the last command, so clear // it out input.clear(); // read input into our String. if there was an error, print the // error message and continue if let Err(why) = io::stdin().read_line(&mut input){ println!("error: {}", why); continue; } // trim the newline off and save it back input = input.trim().to_string(); execute(&input); if input == "exit" { println!("Exiting!"); break; } } }
3
1
2
mixed
--- a/src/main.rs +++ b/src/main.rs @@ -2,2 +2,3 @@ use std::io::Write; // need it to flush stdout +use std::process; @@ -6,3 +7,4 @@ fn execute(cmd: &String) { - println!("you entered [{}]", cmd); + let ret = process::Command::new(cmd).output().unwrap(); + println!("{}", String::from_utf8_lossy(&ret.stdout).trim()); }
--- a/src/main.rs +++ b/src/main.rs @@ ... @@ use std::io::Write; // need it to flush stdout +use std::process; @@ ... @@ fn execute(cmd: &String) { - println!("you entered [{}]", cmd); + let ret = process::Command::new(cmd).output().unwrap(); + println!("{}", String::from_utf8_lossy(&ret.stdout).trim()); }
--- a/src/main.rs +++ b/src/main.rs @@ -2,2 +2,3 @@ CON use std::io::Write; // need it to flush stdout ADD use std::process; CON @@ -6,3 +7,4 @@ CON fn execute(cmd: &String) { DEL println!("you entered [{}]", cmd); ADD let ret = process::Command::new(cmd).output().unwrap(); ADD println!("{}", String::from_utf8_lossy(&ret.stdout).trim()); CON }
<<<<<<< SEARCH use std::io; use std::io::Write; // need it to flush stdout static PROMPT: &'static str = "$ "; fn execute(cmd: &String) { println!("you entered [{}]", cmd); } ======= use std::io; use std::io::Write; // need it to flush stdout use std::process; static PROMPT: &'static str = "$ "; fn execute(cmd: &String) { let ret = process::Command::new(cmd).output().unwrap(); println!("{}", String::from_utf8_lossy(&ret.stdout).trim()); } >>>>>>> REPLACE
neunkasulle/ChronoCommand
114dfdd30a3c93f52758453779e04b329cda07df
code/src/main/java/com/github/neunkasulle/chronocommand/control/MainControl.java
java
mit
Create users on startup for testing purposes
package com.github.neunkasulle.chronocommand.control; import com.github.neunkasulle.chronocommand.model.Category; import com.github.neunkasulle.chronocommand.model.CategoryDAO; import com.github.neunkasulle.chronocommand.model.DAOHelper; import org.hibernate.cfg.NotYetImplementedException; /** * Created by Janze on 18.01.2016. * Controling startup and shutdown */ public class MainControl extends Control { private static MainControl ourInstance = new MainControl(); private MainControl() { realm = new com.github.neunkasulle.chronocommand.security.Realm(); } public static MainControl getInstance() { return ourInstance; } private void exceptionHandling() { throw new NotYetImplementedException(); } public void startup() { DAOHelper.getInstance().startup(); CategoryDAO.getInstance().saveCategory(new Category("Programming")); CategoryDAO.getInstance().saveCategory(new Category("Procrastination")); // TODO initiate anything that needs initiating } public void shutdown() { DAOHelper.getInstance().shutdown(); // TODO initiate anything that needs initiating } }
package com.github.neunkasulle.chronocommand.control; import com.github.neunkasulle.chronocommand.model.Category; import com.github.neunkasulle.chronocommand.model.CategoryDAO; import com.github.neunkasulle.chronocommand.model.DAOHelper; import com.github.neunkasulle.chronocommand.model.UserDAO; import com.github.neunkasulle.chronocommand.model.User; import org.hibernate.cfg.NotYetImplementedException; /** * Created by Janze on 18.01.2016. * Controling startup and shutdown */ public class MainControl extends Control { private static MainControl ourInstance = new MainControl(); private MainControl() { realm = new com.github.neunkasulle.chronocommand.security.Realm(); } public static MainControl getInstance() { return ourInstance; } private void exceptionHandling() { throw new NotYetImplementedException(); } public void startup() { DAOHelper.getInstance().startup(); // TODO initiate anything that needs initiating // DEBUG fill database with data CategoryDAO.getInstance().saveCategory(new Category("Programming")); CategoryDAO.getInstance().saveCategory(new Category("Procrastination")); User tom = new User(); tom.setEmail("[email protected]"); tom.setPassword("cat"); tom.setUsername("tom"); UserDAO.getInstance().saveUser(tom); User matt = new User(); matt.setEmail("[email protected]"); matt.setPassword("matt"); matt.setUsername("matt"); matt.setSupervisor(tom); UserDAO.getInstance().saveUser(matt); } public void shutdown() { DAOHelper.getInstance().shutdown(); // TODO initiate anything that needs initiating } }
17
1
3
mixed
--- a/code/src/main/java/com/github/neunkasulle/chronocommand/control/MainControl.java +++ b/code/src/main/java/com/github/neunkasulle/chronocommand/control/MainControl.java @@ -5,2 +5,4 @@ import com.github.neunkasulle.chronocommand.model.DAOHelper; +import com.github.neunkasulle.chronocommand.model.UserDAO; +import com.github.neunkasulle.chronocommand.model.User; import org.hibernate.cfg.NotYetImplementedException; @@ -34,2 +36,5 @@ + // TODO initiate anything that needs initiating + + // DEBUG fill database with data CategoryDAO.getInstance().saveCategory(new Category("Programming")); @@ -37,3 +42,14 @@ - // TODO initiate anything that needs initiating + User tom = new User(); + tom.setEmail("[email protected]"); + tom.setPassword("cat"); + tom.setUsername("tom"); + UserDAO.getInstance().saveUser(tom); + + User matt = new User(); + matt.setEmail("[email protected]"); + matt.setPassword("matt"); + matt.setUsername("matt"); + matt.setSupervisor(tom); + UserDAO.getInstance().saveUser(matt); }
--- a/code/src/main/java/com/github/neunkasulle/chronocommand/control/MainControl.java +++ b/code/src/main/java/com/github/neunkasulle/chronocommand/control/MainControl.java @@ ... @@ import com.github.neunkasulle.chronocommand.model.DAOHelper; +import com.github.neunkasulle.chronocommand.model.UserDAO; +import com.github.neunkasulle.chronocommand.model.User; import org.hibernate.cfg.NotYetImplementedException; @@ ... @@ + // TODO initiate anything that needs initiating + + // DEBUG fill database with data CategoryDAO.getInstance().saveCategory(new Category("Programming")); @@ ... @@ - // TODO initiate anything that needs initiating + User tom = new User(); + tom.setEmail("[email protected]"); + tom.setPassword("cat"); + tom.setUsername("tom"); + UserDAO.getInstance().saveUser(tom); + + User matt = new User(); + matt.setEmail("[email protected]"); + matt.setPassword("matt"); + matt.setUsername("matt"); + matt.setSupervisor(tom); + UserDAO.getInstance().saveUser(matt); }
--- a/code/src/main/java/com/github/neunkasulle/chronocommand/control/MainControl.java +++ b/code/src/main/java/com/github/neunkasulle/chronocommand/control/MainControl.java @@ -5,2 +5,4 @@ CON import com.github.neunkasulle.chronocommand.model.DAOHelper; ADD import com.github.neunkasulle.chronocommand.model.UserDAO; ADD import com.github.neunkasulle.chronocommand.model.User; CON import org.hibernate.cfg.NotYetImplementedException; @@ -34,2 +36,5 @@ CON ADD // TODO initiate anything that needs initiating ADD ADD // DEBUG fill database with data CON CategoryDAO.getInstance().saveCategory(new Category("Programming")); @@ -37,3 +42,14 @@ CON DEL // TODO initiate anything that needs initiating ADD User tom = new User(); ADD tom.setEmail("[email protected]"); ADD tom.setPassword("cat"); ADD tom.setUsername("tom"); ADD UserDAO.getInstance().saveUser(tom); ADD ADD User matt = new User(); ADD matt.setEmail("[email protected]"); ADD matt.setPassword("matt"); ADD matt.setUsername("matt"); ADD matt.setSupervisor(tom); ADD UserDAO.getInstance().saveUser(matt); CON }
<<<<<<< SEARCH import com.github.neunkasulle.chronocommand.model.CategoryDAO; import com.github.neunkasulle.chronocommand.model.DAOHelper; import org.hibernate.cfg.NotYetImplementedException; ======= import com.github.neunkasulle.chronocommand.model.CategoryDAO; import com.github.neunkasulle.chronocommand.model.DAOHelper; import com.github.neunkasulle.chronocommand.model.UserDAO; import com.github.neunkasulle.chronocommand.model.User; import org.hibernate.cfg.NotYetImplementedException; >>>>>>> REPLACE <<<<<<< SEARCH DAOHelper.getInstance().startup(); CategoryDAO.getInstance().saveCategory(new Category("Programming")); CategoryDAO.getInstance().saveCategory(new Category("Procrastination")); // TODO initiate anything that needs initiating } ======= DAOHelper.getInstance().startup(); // TODO initiate anything that needs initiating // DEBUG fill database with data CategoryDAO.getInstance().saveCategory(new Category("Programming")); CategoryDAO.getInstance().saveCategory(new Category("Procrastination")); User tom = new User(); tom.setEmail("[email protected]"); tom.setPassword("cat"); tom.setUsername("tom"); UserDAO.getInstance().saveUser(tom); User matt = new User(); matt.setEmail("[email protected]"); matt.setPassword("matt"); matt.setUsername("matt"); matt.setSupervisor(tom); UserDAO.getInstance().saveUser(matt); } >>>>>>> REPLACE
ratan12/Atarashii
816c6239c4bab98562198b2dd4f87d1b2f7f7df6
Atarashii/src/net/somethingdreadful/MAL/LogoutConfirmationDialogFragment.java
java
bsd-2-clause
Fix Logout Dialog Recreating Home The logout dialog was launching a new instance of the home activity every time it was dismissed by touching outside the dialog instead of through the proper Cancel button. This commit is just a quick fix to fix that.
package net.somethingdreadful.MAL; import android.app.AlertDialog; import android.app.AlertDialog.Builder; import android.app.Dialog; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.view.ContextThemeWrapper; import com.actionbarsherlock.app.SherlockDialogFragment; public class LogoutConfirmationDialogFragment extends SherlockDialogFragment { public LogoutConfirmationDialogFragment() {} public interface LogoutConfirmationDialogListener { void onLogoutConfirmed(); } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { Builder builder = new AlertDialog.Builder(new ContextThemeWrapper(getActivity(), R.style.AlertDialog)); builder.setPositiveButton(R.string.dialog_logout_label_confirm, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int whichButton) { ((Home) getActivity()).onLogoutConfirmed(); dismiss(); } }) .setNegativeButton(R.string.dialog_label_cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int whichButton) { dismiss(); } }) .setTitle(R.string.dialog_logout_title).setMessage(R.string.dialog_logout_message); return builder.create(); } @Override public void onDismiss(DialogInterface dialog) {} @Override public void onCancel(DialogInterface dialog) { startActivity(new Intent(getActivity(), Home.class)); this.dismiss(); } }
package net.somethingdreadful.MAL; import android.app.AlertDialog; import android.app.AlertDialog.Builder; import android.app.Dialog; import android.content.DialogInterface; import android.os.Bundle; import android.view.ContextThemeWrapper; import com.actionbarsherlock.app.SherlockDialogFragment; public class LogoutConfirmationDialogFragment extends SherlockDialogFragment { public LogoutConfirmationDialogFragment() {} public interface LogoutConfirmationDialogListener { void onLogoutConfirmed(); } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { Builder builder = new AlertDialog.Builder(new ContextThemeWrapper(getActivity(), R.style.AlertDialog)); builder.setPositiveButton(R.string.dialog_logout_label_confirm, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int whichButton) { ((Home) getActivity()).onLogoutConfirmed(); dismiss(); } }) .setNegativeButton(R.string.dialog_label_cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int whichButton) { dismiss(); } }) .setTitle(R.string.dialog_logout_title).setMessage(R.string.dialog_logout_message); return builder.create(); } @Override public void onDismiss(DialogInterface dialog) {} @Override public void onCancel(DialogInterface dialog) { // startActivity(new Intent(getActivity(), Home.class)); //Relaunching Home without needing to, causes bad things this.dismiss(); } }
1
2
2
mixed
--- a/Atarashii/src/net/somethingdreadful/MAL/LogoutConfirmationDialogFragment.java +++ b/Atarashii/src/net/somethingdreadful/MAL/LogoutConfirmationDialogFragment.java @@ -6,3 +6,2 @@ import android.content.DialogInterface; -import android.content.Intent; import android.os.Bundle; @@ -47,3 +46,3 @@ public void onCancel(DialogInterface dialog) { - startActivity(new Intent(getActivity(), Home.class)); + // startActivity(new Intent(getActivity(), Home.class)); //Relaunching Home without needing to, causes bad things this.dismiss();
--- a/Atarashii/src/net/somethingdreadful/MAL/LogoutConfirmationDialogFragment.java +++ b/Atarashii/src/net/somethingdreadful/MAL/LogoutConfirmationDialogFragment.java @@ ... @@ import android.content.DialogInterface; -import android.content.Intent; import android.os.Bundle; @@ ... @@ public void onCancel(DialogInterface dialog) { - startActivity(new Intent(getActivity(), Home.class)); + // startActivity(new Intent(getActivity(), Home.class)); //Relaunching Home without needing to, causes bad things this.dismiss();
--- a/Atarashii/src/net/somethingdreadful/MAL/LogoutConfirmationDialogFragment.java +++ b/Atarashii/src/net/somethingdreadful/MAL/LogoutConfirmationDialogFragment.java @@ -6,3 +6,2 @@ CON import android.content.DialogInterface; DEL import android.content.Intent; CON import android.os.Bundle; @@ -47,3 +46,3 @@ CON public void onCancel(DialogInterface dialog) { DEL startActivity(new Intent(getActivity(), Home.class)); ADD // startActivity(new Intent(getActivity(), Home.class)); //Relaunching Home without needing to, causes bad things CON this.dismiss();
<<<<<<< SEARCH import android.app.Dialog; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.view.ContextThemeWrapper; ======= import android.app.Dialog; import android.content.DialogInterface; import android.os.Bundle; import android.view.ContextThemeWrapper; >>>>>>> REPLACE <<<<<<< SEARCH @Override public void onCancel(DialogInterface dialog) { startActivity(new Intent(getActivity(), Home.class)); this.dismiss(); } ======= @Override public void onCancel(DialogInterface dialog) { // startActivity(new Intent(getActivity(), Home.class)); //Relaunching Home without needing to, causes bad things this.dismiss(); } >>>>>>> REPLACE
sanity-io/sanity
6e7860be4eac855279f7e5560ab611c0ba5eb391
packages/@sanity/core/src/commands/dataset/datasetVisibilityCommand.js
javascript
mit
[core] Check if @sanity/cli has dataset edit capabilities before using it
export default { name: 'visibility', group: 'dataset', signature: 'get/set [dataset] [mode]', description: 'Set visibility of a dataset', // eslint-disable-next-line complexity action: async (args, context) => { const {apiClient, output} = context const [action, ds, aclMode] = args.argsWithoutOptions if (!action) { throw new Error('Action must be provided (get/set)') } if (!['set', 'get'].includes(action)) { throw new Error('Invalid action (only get/set allowed)') } if (!ds) { throw new Error('Dataset name must be provided') } if (action === 'set' && !aclMode) { throw new Error('Please provide a visibility mode (public/private)') } const dataset = `${ds}` const client = apiClient() const current = (await client.datasets.list()).find(curr => curr.name === dataset) if (!current) { throw new Error('Dataset not found') } if (action === 'get') { output.print(current.aclMode) return } if (current.aclMode === aclMode) { output.print(`Dataset already in "${aclMode}"-mode`) return } if (aclMode === 'private') { output.print( 'Please note that while documents are private, assets (files and images) are still public\n' ) } await apiClient().datasets.edit(dataset, {aclMode}) output.print('Dataset visibility changed') } }
export default { name: 'visibility', group: 'dataset', signature: 'get/set [dataset] [mode]', description: 'Set visibility of a dataset', // eslint-disable-next-line complexity action: async (args, context) => { const {apiClient, output} = context const [action, ds, aclMode] = args.argsWithoutOptions const client = apiClient() if (!client.datasets.edit) { throw new Error('@sanity/cli must be upgraded first:\n npm install -g @sanity/cli') } if (!action) { throw new Error('Action must be provided (get/set)') } if (!['set', 'get'].includes(action)) { throw new Error('Invalid action (only get/set allowed)') } if (!ds) { throw new Error('Dataset name must be provided') } if (action === 'set' && !aclMode) { throw new Error('Please provide a visibility mode (public/private)') } const dataset = `${ds}` const current = (await client.datasets.list()).find(curr => curr.name === dataset) if (!current) { throw new Error('Dataset not found') } if (action === 'get') { output.print(current.aclMode) return } if (current.aclMode === aclMode) { output.print(`Dataset already in "${aclMode}"-mode`) return } if (aclMode === 'private') { output.print( 'Please note that while documents are private, assets (files and images) are still public\n' ) } await client.datasets.edit(dataset, {aclMode}) output.print('Dataset visibility changed') } }
7
2
3
mixed
--- a/packages/@sanity/core/src/commands/dataset/datasetVisibilityCommand.js +++ b/packages/@sanity/core/src/commands/dataset/datasetVisibilityCommand.js @@ -9,2 +9,8 @@ const [action, ds, aclMode] = args.argsWithoutOptions + const client = apiClient() + + if (!client.datasets.edit) { + throw new Error('@sanity/cli must be upgraded first:\n npm install -g @sanity/cli') + } + if (!action) { @@ -26,3 +32,2 @@ const dataset = `${ds}` - const client = apiClient() const current = (await client.datasets.list()).find(curr => curr.name === dataset) @@ -49,3 +54,3 @@ - await apiClient().datasets.edit(dataset, {aclMode}) + await client.datasets.edit(dataset, {aclMode}) output.print('Dataset visibility changed')
--- a/packages/@sanity/core/src/commands/dataset/datasetVisibilityCommand.js +++ b/packages/@sanity/core/src/commands/dataset/datasetVisibilityCommand.js @@ ... @@ const [action, ds, aclMode] = args.argsWithoutOptions + const client = apiClient() + + if (!client.datasets.edit) { + throw new Error('@sanity/cli must be upgraded first:\n npm install -g @sanity/cli') + } + if (!action) { @@ ... @@ const dataset = `${ds}` - const client = apiClient() const current = (await client.datasets.list()).find(curr => curr.name === dataset) @@ ... @@ - await apiClient().datasets.edit(dataset, {aclMode}) + await client.datasets.edit(dataset, {aclMode}) output.print('Dataset visibility changed')
--- a/packages/@sanity/core/src/commands/dataset/datasetVisibilityCommand.js +++ b/packages/@sanity/core/src/commands/dataset/datasetVisibilityCommand.js @@ -9,2 +9,8 @@ CON const [action, ds, aclMode] = args.argsWithoutOptions ADD const client = apiClient() ADD ADD if (!client.datasets.edit) { ADD throw new Error('@sanity/cli must be upgraded first:\n npm install -g @sanity/cli') ADD } ADD CON if (!action) { @@ -26,3 +32,2 @@ CON const dataset = `${ds}` DEL const client = apiClient() CON const current = (await client.datasets.list()).find(curr => curr.name === dataset) @@ -49,3 +54,3 @@ CON DEL await apiClient().datasets.edit(dataset, {aclMode}) ADD await client.datasets.edit(dataset, {aclMode}) CON output.print('Dataset visibility changed')
<<<<<<< SEARCH const {apiClient, output} = context const [action, ds, aclMode] = args.argsWithoutOptions if (!action) { throw new Error('Action must be provided (get/set)') ======= const {apiClient, output} = context const [action, ds, aclMode] = args.argsWithoutOptions const client = apiClient() if (!client.datasets.edit) { throw new Error('@sanity/cli must be upgraded first:\n npm install -g @sanity/cli') } if (!action) { throw new Error('Action must be provided (get/set)') >>>>>>> REPLACE <<<<<<< SEARCH const dataset = `${ds}` const client = apiClient() const current = (await client.datasets.list()).find(curr => curr.name === dataset) ======= const dataset = `${ds}` const current = (await client.datasets.list()).find(curr => curr.name === dataset) >>>>>>> REPLACE <<<<<<< SEARCH } await apiClient().datasets.edit(dataset, {aclMode}) output.print('Dataset visibility changed') } ======= } await client.datasets.edit(dataset, {aclMode}) output.print('Dataset visibility changed') } >>>>>>> REPLACE
ShawnTe/guardian
937dcdccdae6ab3750fd8cb2c80a82f41220f38c
app/assets/javascripts/application.js
javascript
mit
Add ajax call to sms controller
$(document).ready(function(){ // var turbolinks = require('turbolinks') $("#walk-me-home").on("click", function(e){ e.preventDefault(); $.ajax({ url: "http://172.16.50.232:8080/start", crossDomain : true, }) .done(function(serverResponse){ $("#walk-me-home").hide(); $("#home-safely").show(); console.log(serverResponse + "This is the server response"); }) // need to add failure response }) $("#home-safely").on("click", function(e){ console.log("I'm home!!") e.preventDefault(); $.ajax({ url: "http://172.16.50.232:8080/end", crossDomain : true, }) .done(function(serverResponse){ $("#home-safely").hide(); $("#show-events").show(); console.log(serverResponse + "This is the server response"); }) }) });
$(document).ready(function(){ // var turbolinks = require('turbolinks') $("#walk-me-home").on("click", function(e){ e.preventDefault(); $.ajax({ url: "/sms/text_friend" }) .done(function(serverResponse){ console.log(serverResponse + " This is the server response"); }) .fail(function(serverResponse){ console.log("Request failed"); }) $.ajax({ url: "http://172.16.50.232:8080/start", crossDomain : true, }) .done(function(serverResponse){ $("#walk-me-home").hide(); $("#home-safely").show(); console.log(serverResponse + "This is the server response"); }) // need to add failure response }) $("#home-safely").on("click", function(e){ console.log("I'm home!!") e.preventDefault(); $.ajax({ url: "http://172.16.50.232:8080/end", crossDomain : true, }) .done(function(serverResponse){ $("#home-safely").hide(); $("#show-events").show(); console.log(serverResponse + "This is the server response"); }) }) });
13
0
1
add_only
--- a/app/assets/javascripts/application.js +++ b/app/assets/javascripts/application.js @@ -7,2 +7,15 @@ + $.ajax({ + url: "/sms/text_friend" + }) + .done(function(serverResponse){ + + console.log(serverResponse + " This is the server response"); + }) + + .fail(function(serverResponse){ + + console.log("Request failed"); + }) + $.ajax({
--- a/app/assets/javascripts/application.js +++ b/app/assets/javascripts/application.js @@ ... @@ + $.ajax({ + url: "/sms/text_friend" + }) + .done(function(serverResponse){ + + console.log(serverResponse + " This is the server response"); + }) + + .fail(function(serverResponse){ + + console.log("Request failed"); + }) + $.ajax({
--- a/app/assets/javascripts/application.js +++ b/app/assets/javascripts/application.js @@ -7,2 +7,15 @@ CON ADD $.ajax({ ADD url: "/sms/text_friend" ADD }) ADD .done(function(serverResponse){ ADD ADD console.log(serverResponse + " This is the server response"); ADD }) ADD ADD .fail(function(serverResponse){ ADD ADD console.log("Request failed"); ADD }) ADD CON $.ajax({
<<<<<<< SEARCH e.preventDefault(); $.ajax({ url: "http://172.16.50.232:8080/start", ======= e.preventDefault(); $.ajax({ url: "/sms/text_friend" }) .done(function(serverResponse){ console.log(serverResponse + " This is the server response"); }) .fail(function(serverResponse){ console.log("Request failed"); }) $.ajax({ url: "http://172.16.50.232:8080/start", >>>>>>> REPLACE
jongensvantechniek/Project-Euler
c7dccac66c5aea5df84f807fc5bd26438b13b599
problem12-java/Problem12.java
java
mit
Add comments to problem 12
public class Problem12 { public static void main(String[] args) { int triangles = 0; int count; // For each natural number up to forever for(int i = 1; ; i++) { // Get the next triangle number triangles = triangles + i; count = 0; // Let's test it against all possible divisors below the square root // of the triangle number itself. for(int j = 1; j <= Math.sqrt(triangles); j++) { if(triangles % j == 0) { // If the triangle number passes the test to find it's // divisor j you find two divisors, it takes two to tango // and two numbers to multiply. count = count + 2; } } // Break up the party if you find over fivehundred divisors. if(count > 500 ) { System.out.println(triangles); break; } } } }
/* The sequence of triangle numbers is generated by adding the natural numbers. So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten terms would be: 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ... Let us list the factors of the first seven triangle numbers: 1: 1 3: 1,3 6: 1,2,3,6 10: 1,2,5,10 15: 1,3,5,15 21: 1,3,7,21 28: 1,2,4,7,14,28 We can see that 28 is the first triangle number to have over five divisors. What is the value of the first triangle number to have over five hundred divisors? */ public class Problem12 { public static void main(String[] args) { int triangles = 0; int count; // For each natural number up to forever for(int i = 1; ; i++) { // Get the next triangle number triangles = triangles + i; count = 0; // Let's test it against all possible divisors below the square root // of the triangle number itself. for(int j = 1; j <= Math.sqrt(triangles); j++) { if(triangles % j == 0) { // If the triangle number passes the test to find it's // divisor j you find two divisors, it takes two to tango // and two numbers to multiply. count = count + 2; } } // Break up the party if you find over fivehundred divisors. if(count > 500 ) { System.out.println(triangles); break; } } } }
22
0
1
add_only
--- a/problem12-java/Problem12.java +++ b/problem12-java/Problem12.java @@ -1 +1,23 @@ +/* + +The sequence of triangle numbers is generated by adding the natural numbers. So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten terms would be: + +1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ... + +Let us list the factors of the first seven triangle numbers: + + 1: 1 + 3: 1,3 + 6: 1,2,3,6 + 10: 1,2,5,10 + 15: 1,3,5,15 + 21: 1,3,7,21 + 28: 1,2,4,7,14,28 + +We can see that 28 is the first triangle number to have over five divisors. + +What is the value of the first triangle number to have over five hundred divisors? + +*/ + public class Problem12 {
--- a/problem12-java/Problem12.java +++ b/problem12-java/Problem12.java @@ ... @@ +/* + +The sequence of triangle numbers is generated by adding the natural numbers. So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten terms would be: + +1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ... + +Let us list the factors of the first seven triangle numbers: + + 1: 1 + 3: 1,3 + 6: 1,2,3,6 + 10: 1,2,5,10 + 15: 1,3,5,15 + 21: 1,3,7,21 + 28: 1,2,4,7,14,28 + +We can see that 28 is the first triangle number to have over five divisors. + +What is the value of the first triangle number to have over five hundred divisors? + +*/ + public class Problem12 {
--- a/problem12-java/Problem12.java +++ b/problem12-java/Problem12.java @@ -1 +1,23 @@ ADD /* ADD ADD The sequence of triangle numbers is generated by adding the natural numbers. So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten terms would be: ADD ADD 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ... ADD ADD Let us list the factors of the first seven triangle numbers: ADD ADD 1: 1 ADD 3: 1,3 ADD 6: 1,2,3,6 ADD 10: 1,2,5,10 ADD 15: 1,3,5,15 ADD 21: 1,3,7,21 ADD 28: 1,2,4,7,14,28 ADD ADD We can see that 28 is the first triangle number to have over five divisors. ADD ADD What is the value of the first triangle number to have over five hundred divisors? ADD ADD */ ADD CON public class Problem12 {
<<<<<<< SEARCH public class Problem12 { public static void main(String[] args) { ======= /* The sequence of triangle numbers is generated by adding the natural numbers. So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten terms would be: 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ... Let us list the factors of the first seven triangle numbers: 1: 1 3: 1,3 6: 1,2,3,6 10: 1,2,5,10 15: 1,3,5,15 21: 1,3,7,21 28: 1,2,4,7,14,28 We can see that 28 is the first triangle number to have over five divisors. What is the value of the first triangle number to have over five hundred divisors? */ public class Problem12 { public static void main(String[] args) { >>>>>>> REPLACE
wibbe/tiny-rts
01e611ac3d74ef4a81ecf64c279fc619b3f5033f
src/cmd.rs
rust
mit
Return the newly created variable.
use std::rc::{Rc}; use std::cell::{RefCell}; use std::collections::HashMap; #[derive(Clone, Debug)] pub struct Var(Rc<RefCell<i32>>); impl Var { fn new() -> Var { Var(Rc::new(RefCell::new(0))) } pub fn set(&self, value: i32) { *self.0.borrow_mut() = value; } pub fn get(&self) -> i32 { *self.0.borrow() } } pub struct Function { } pub struct Cmd { vars: RefCell<HashMap<String, Var>>, } impl Cmd { pub fn new() -> Cmd { Cmd { vars: RefCell::new(HashMap::new()), } } pub fn register_var(&self, name: String) -> Result<(), String> { let mut vars = self.vars.borrow_mut(); if vars.contains_key(&name) { return Err("Variable already pressent".to_string()); } vars.insert(name, Var::new()); Ok(()) } pub fn register_func(&self, _name: String) -> Result<(), String> { Ok(()) } pub fn exec(&self, _line: String) -> Result<(), String> { Ok(()) } }
use std::rc::{Rc}; use std::cell::{RefCell}; use std::collections::HashMap; #[derive(Clone, Debug)] pub struct Var(Rc<RefCell<i32>>); impl Var { fn new() -> Var { Var(Rc::new(RefCell::new(0))) } pub fn set(&self, value: i32) { *self.0.borrow_mut() = value; } pub fn get(&self) -> i32 { *self.0.borrow() } } pub struct Function { } pub struct Cmd { vars: RefCell<HashMap<String, Var>>, } impl Cmd { pub fn new() -> Cmd { Cmd { vars: RefCell::new(HashMap::new()), } } pub fn register_var(&self, name: String) -> Result<Var, String> { let mut vars = self.vars.borrow_mut(); if vars.contains_key(&name) { return Err("Variable already pressent".to_string()); } let var = Var::new(); vars.insert(name, var.clone()); Ok(var.clone()) } pub fn register_func(&self, _name: String) -> Result<(), String> { Ok(()) } pub fn exec(&self, _line: String) -> Result<(), String> { Ok(()) } }
4
3
2
mixed
--- a/src/cmd.rs +++ b/src/cmd.rs @@ -38,3 +38,3 @@ - pub fn register_var(&self, name: String) -> Result<(), String> { + pub fn register_var(&self, name: String) -> Result<Var, String> { let mut vars = self.vars.borrow_mut(); @@ -45,4 +45,5 @@ - vars.insert(name, Var::new()); - Ok(()) + let var = Var::new(); + vars.insert(name, var.clone()); + Ok(var.clone()) }
--- a/src/cmd.rs +++ b/src/cmd.rs @@ ... @@ - pub fn register_var(&self, name: String) -> Result<(), String> { + pub fn register_var(&self, name: String) -> Result<Var, String> { let mut vars = self.vars.borrow_mut(); @@ ... @@ - vars.insert(name, Var::new()); - Ok(()) + let var = Var::new(); + vars.insert(name, var.clone()); + Ok(var.clone()) }
--- a/src/cmd.rs +++ b/src/cmd.rs @@ -38,3 +38,3 @@ CON DEL pub fn register_var(&self, name: String) -> Result<(), String> { ADD pub fn register_var(&self, name: String) -> Result<Var, String> { CON let mut vars = self.vars.borrow_mut(); @@ -45,4 +45,5 @@ CON DEL vars.insert(name, Var::new()); DEL Ok(()) ADD let var = Var::new(); ADD vars.insert(name, var.clone()); ADD Ok(var.clone()) CON }
<<<<<<< SEARCH } pub fn register_var(&self, name: String) -> Result<(), String> { let mut vars = self.vars.borrow_mut(); ======= } pub fn register_var(&self, name: String) -> Result<Var, String> { let mut vars = self.vars.borrow_mut(); >>>>>>> REPLACE <<<<<<< SEARCH } vars.insert(name, Var::new()); Ok(()) } ======= } let var = Var::new(); vars.insert(name, var.clone()); Ok(var.clone()) } >>>>>>> REPLACE
scottyab/rootbeer
c0840f172dfe0ec292f49b0a49baeba2dc26b8ed
app/src/main/java/com/scottyab/rootbeer/sample/CheckForRootWorker.kt
kotlin
apache-2.0
Remove debugging info accidentally committed to smaple app
package com.scottyab.rootbeer.sample import android.content.Context import com.scottyab.rootbeer.RootBeer import com.scottyab.rootbeer.util.Utils class CheckForRootWorker(context: Context) { private val rootBeer = RootBeer(context) suspend operator fun invoke(): List<RootItemResult> = getRootResults() private fun getRootResults() = listOf( RootItemResult( "Root Management Apps", rootBeer.detectRootManagementApps( arrayOf( "com.tippingcanoe.hukd", "com.google.android.gm", "bbc.mobile.weather" ) ) ), RootItemResult( "Potentially Dangerous Apps", rootBeer.detectPotentiallyDangerousApps( arrayOf( "com.tippingcanoe.hukd", "com.google.android.gm", "bbc.mobile.weather" ) ) ), RootItemResult( "Root Cloaking Apps", rootBeer.detectRootCloakingApps( arrayOf( "com.google.android.apps.photos", "com.alltrails.alltrails" ) ) ), RootItemResult("TestKeys", rootBeer.detectTestKeys()), RootItemResult("BusyBoxBinary", rootBeer.checkForBusyBoxBinary()), RootItemResult("SU Binary", rootBeer.checkForSuBinary()), RootItemResult("2nd SU Binary check", rootBeer.checkSuExists()), RootItemResult("For RW Paths", rootBeer.checkForRWPaths()), RootItemResult("Dangerous Props", rootBeer.checkForDangerousProps()), RootItemResult("Root via native check", rootBeer.checkForRootNative()), RootItemResult("SE linux Flag Is Enabled", Utils.isSelinuxFlagInEnabled()), RootItemResult("Magisk specific checks", rootBeer.checkForMagiskBinary()) ) }
package com.scottyab.rootbeer.sample import android.content.Context import com.scottyab.rootbeer.RootBeer import com.scottyab.rootbeer.util.Utils class CheckForRootWorker(context: Context) { private val rootBeer = RootBeer(context) suspend operator fun invoke(): List<RootItemResult> = getRootResults() private fun getRootResults() = listOf( RootItemResult("TestKeys", rootBeer.detectTestKeys()), RootItemResult("BusyBoxBinary", rootBeer.checkForBusyBoxBinary()), RootItemResult("SU Binary", rootBeer.checkForSuBinary()), RootItemResult("2nd SU Binary check", rootBeer.checkSuExists()), RootItemResult("For RW Paths", rootBeer.checkForRWPaths()), RootItemResult("Dangerous Props", rootBeer.checkForDangerousProps()), RootItemResult("Root via native check", rootBeer.checkForRootNative()), RootItemResult("SE linux Flag Is Enabled", Utils.isSelinuxFlagInEnabled()), RootItemResult("Magisk specific checks", rootBeer.checkForMagiskBinary()) ) }
0
24
1
del_only
--- a/app/src/main/java/com/scottyab/rootbeer/sample/CheckForRootWorker.kt +++ b/app/src/main/java/com/scottyab/rootbeer/sample/CheckForRootWorker.kt @@ -13,26 +13,2 @@ private fun getRootResults() = listOf( - RootItemResult( - "Root Management Apps", rootBeer.detectRootManagementApps( - arrayOf( - "com.tippingcanoe.hukd", - "com.google.android.gm", "bbc.mobile.weather" - ) - ) - ), - RootItemResult( - "Potentially Dangerous Apps", rootBeer.detectPotentiallyDangerousApps( - arrayOf( - "com.tippingcanoe.hukd", - "com.google.android.gm", "bbc.mobile.weather" - ) - ) - ), - RootItemResult( - "Root Cloaking Apps", rootBeer.detectRootCloakingApps( - arrayOf( - "com.google.android.apps.photos", - "com.alltrails.alltrails" - ) - ) - ), RootItemResult("TestKeys", rootBeer.detectTestKeys()),
--- a/app/src/main/java/com/scottyab/rootbeer/sample/CheckForRootWorker.kt +++ b/app/src/main/java/com/scottyab/rootbeer/sample/CheckForRootWorker.kt @@ ... @@ private fun getRootResults() = listOf( - RootItemResult( - "Root Management Apps", rootBeer.detectRootManagementApps( - arrayOf( - "com.tippingcanoe.hukd", - "com.google.android.gm", "bbc.mobile.weather" - ) - ) - ), - RootItemResult( - "Potentially Dangerous Apps", rootBeer.detectPotentiallyDangerousApps( - arrayOf( - "com.tippingcanoe.hukd", - "com.google.android.gm", "bbc.mobile.weather" - ) - ) - ), - RootItemResult( - "Root Cloaking Apps", rootBeer.detectRootCloakingApps( - arrayOf( - "com.google.android.apps.photos", - "com.alltrails.alltrails" - ) - ) - ), RootItemResult("TestKeys", rootBeer.detectTestKeys()),
--- a/app/src/main/java/com/scottyab/rootbeer/sample/CheckForRootWorker.kt +++ b/app/src/main/java/com/scottyab/rootbeer/sample/CheckForRootWorker.kt @@ -13,26 +13,2 @@ CON private fun getRootResults() = listOf( DEL RootItemResult( DEL "Root Management Apps", rootBeer.detectRootManagementApps( DEL arrayOf( DEL "com.tippingcanoe.hukd", DEL "com.google.android.gm", "bbc.mobile.weather" DEL ) DEL ) DEL ), DEL RootItemResult( DEL "Potentially Dangerous Apps", rootBeer.detectPotentiallyDangerousApps( DEL arrayOf( DEL "com.tippingcanoe.hukd", DEL "com.google.android.gm", "bbc.mobile.weather" DEL ) DEL ) DEL ), DEL RootItemResult( DEL "Root Cloaking Apps", rootBeer.detectRootCloakingApps( DEL arrayOf( DEL "com.google.android.apps.photos", DEL "com.alltrails.alltrails" DEL ) DEL ) DEL ), CON RootItemResult("TestKeys", rootBeer.detectTestKeys()),
<<<<<<< SEARCH private fun getRootResults() = listOf( RootItemResult( "Root Management Apps", rootBeer.detectRootManagementApps( arrayOf( "com.tippingcanoe.hukd", "com.google.android.gm", "bbc.mobile.weather" ) ) ), RootItemResult( "Potentially Dangerous Apps", rootBeer.detectPotentiallyDangerousApps( arrayOf( "com.tippingcanoe.hukd", "com.google.android.gm", "bbc.mobile.weather" ) ) ), RootItemResult( "Root Cloaking Apps", rootBeer.detectRootCloakingApps( arrayOf( "com.google.android.apps.photos", "com.alltrails.alltrails" ) ) ), RootItemResult("TestKeys", rootBeer.detectTestKeys()), RootItemResult("BusyBoxBinary", rootBeer.checkForBusyBoxBinary()), ======= private fun getRootResults() = listOf( RootItemResult("TestKeys", rootBeer.detectTestKeys()), RootItemResult("BusyBoxBinary", rootBeer.checkForBusyBoxBinary()), >>>>>>> REPLACE
erikrose/blessings
93d263666471b220880511a97aa3ee077bfd2910
setup.py
python
mit
Add the "Production" trove classifier.
import sys from setuptools import setup, find_packages extra_setup = {} if sys.version_info >= (3,): extra_setup['use_2to3'] = True setup( name='blessings', version='1.2', description='A thin, practical wrapper around terminal formatting, positioning, and more', long_description=open('README.rst').read(), author='Erik Rose', author_email='[email protected]', license='MIT', packages=find_packages(exclude=['ez_setup']), tests_require=['Nose'], url='https://github.com/erikrose/blessings', include_package_data=True, classifiers=[ 'Intended Audience :: Developers', 'Natural Language :: English', 'Environment :: Console', 'Environment :: Console :: Curses', 'License :: OSI Approved :: MIT License', 'Operating System :: POSIX', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.5', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.2', 'Topic :: Software Development :: Libraries', 'Topic :: Software Development :: User Interfaces', 'Topic :: Terminals' ], keywords=['terminal', 'tty', 'curses', 'ncurses', 'formatting', 'color', 'console'], **extra_setup )
import sys from setuptools import setup, find_packages extra_setup = {} if sys.version_info >= (3,): extra_setup['use_2to3'] = True setup( name='blessings', version='1.2', description='A thin, practical wrapper around terminal formatting, positioning, and more', long_description=open('README.rst').read(), author='Erik Rose', author_email='[email protected]', license='MIT', packages=find_packages(exclude=['ez_setup']), tests_require=['Nose'], url='https://github.com/erikrose/blessings', include_package_data=True, classifiers=[ 'Intended Audience :: Developers', 'Natural Language :: English', 'Development Status :: 5 - Production/Stable', 'Environment :: Console', 'Environment :: Console :: Curses', 'License :: OSI Approved :: MIT License', 'Operating System :: POSIX', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.5', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.2', 'Topic :: Software Development :: Libraries', 'Topic :: Software Development :: User Interfaces', 'Topic :: Terminals' ], keywords=['terminal', 'tty', 'curses', 'ncurses', 'formatting', 'color', 'console'], **extra_setup )
1
0
1
add_only
--- a/setup.py +++ b/setup.py @@ -24,2 +24,3 @@ 'Natural Language :: English', + 'Development Status :: 5 - Production/Stable', 'Environment :: Console',
--- a/setup.py +++ b/setup.py @@ ... @@ 'Natural Language :: English', + 'Development Status :: 5 - Production/Stable', 'Environment :: Console',
--- a/setup.py +++ b/setup.py @@ -24,2 +24,3 @@ CON 'Natural Language :: English', ADD 'Development Status :: 5 - Production/Stable', CON 'Environment :: Console',
<<<<<<< SEARCH 'Intended Audience :: Developers', 'Natural Language :: English', 'Environment :: Console', 'Environment :: Console :: Curses', ======= 'Intended Audience :: Developers', 'Natural Language :: English', 'Development Status :: 5 - Production/Stable', 'Environment :: Console', 'Environment :: Console :: Curses', >>>>>>> REPLACE
intellij-purescript/intellij-purescript
c05bc4d7c59c7eb54a3c9c553d9d04551b9f6f7d
src/main/java/org/purescript/PSLanguage.kt
kotlin
bsd-3-clause
Change build-in types and modules to be sets instead of lists
package org.purescript import com.intellij.lang.Language class PSLanguage : Language("Purescript", "text/purescript", "text/x-purescript", "application/x-purescript") { companion object { val INSTANCE = PSLanguage() /** * These modules are built into the purescript compiler, * and have no corresponding source files. * * See [https://pursuit.purescript.org/builtins/docs/Prim] for details. */ val BUILTIN_MODULES = listOf( "Prim", "Prim.Boolean", "Prim.Coerce", "Prim.Ordering", "Prim.Row", "Prim.RowList", "Prim.Symbol", "Prim.TypeError", ) /** * These types are built into the purescript compiles, * and are always available. * * See [https://pursuit.purescript.org/builtins/docs/Prim] for details. */ val BUILTIN_TYPES = listOf( "Int", "Number", "String", "Char", "Boolean", "Array", "Type", // TODO Type is really a kind, not a type ) } }
package org.purescript import com.intellij.lang.Language class PSLanguage : Language("Purescript", "text/purescript", "text/x-purescript", "application/x-purescript") { companion object { val INSTANCE = PSLanguage() /** * These modules are built into the purescript compiler, * and have no corresponding source files. * * See [https://pursuit.purescript.org/builtins/docs/Prim] for details. */ val BUILTIN_MODULES = setOf( "Prim", "Prim.Boolean", "Prim.Coerce", "Prim.Ordering", "Prim.Row", "Prim.RowList", "Prim.Symbol", "Prim.TypeError", ) /** * These types are built into the purescript compiles, * and are always available. * * See [https://pursuit.purescript.org/builtins/docs/Prim] for details. */ val BUILTIN_TYPES = setOf( "Int", "Number", "String", "Char", "Boolean", "Array", "Type", // TODO Type is really a kind, not a type ) } }
2
2
2
mixed
--- a/src/main/java/org/purescript/PSLanguage.kt +++ b/src/main/java/org/purescript/PSLanguage.kt @@ -14,3 +14,3 @@ */ - val BUILTIN_MODULES = listOf( + val BUILTIN_MODULES = setOf( "Prim", @@ -31,3 +31,3 @@ */ - val BUILTIN_TYPES = listOf( + val BUILTIN_TYPES = setOf( "Int",
--- a/src/main/java/org/purescript/PSLanguage.kt +++ b/src/main/java/org/purescript/PSLanguage.kt @@ ... @@ */ - val BUILTIN_MODULES = listOf( + val BUILTIN_MODULES = setOf( "Prim", @@ ... @@ */ - val BUILTIN_TYPES = listOf( + val BUILTIN_TYPES = setOf( "Int",
--- a/src/main/java/org/purescript/PSLanguage.kt +++ b/src/main/java/org/purescript/PSLanguage.kt @@ -14,3 +14,3 @@ CON */ DEL val BUILTIN_MODULES = listOf( ADD val BUILTIN_MODULES = setOf( CON "Prim", @@ -31,3 +31,3 @@ CON */ DEL val BUILTIN_TYPES = listOf( ADD val BUILTIN_TYPES = setOf( CON "Int",
<<<<<<< SEARCH * See [https://pursuit.purescript.org/builtins/docs/Prim] for details. */ val BUILTIN_MODULES = listOf( "Prim", "Prim.Boolean", ======= * See [https://pursuit.purescript.org/builtins/docs/Prim] for details. */ val BUILTIN_MODULES = setOf( "Prim", "Prim.Boolean", >>>>>>> REPLACE <<<<<<< SEARCH * See [https://pursuit.purescript.org/builtins/docs/Prim] for details. */ val BUILTIN_TYPES = listOf( "Int", "Number", ======= * See [https://pursuit.purescript.org/builtins/docs/Prim] for details. */ val BUILTIN_TYPES = setOf( "Int", "Number", >>>>>>> REPLACE
kee-org/browser-addon
734970ba25f7fb5f418a827c71aa84036bc6fafe
lib/i18n.js
javascript
agpl-3.0
Enable translation of multiple HTML attributes
[].forEach.call(document.querySelectorAll("[data-i18n]"), function(el) { const name = el.getAttribute("data-i18n"); const value = $STR(name); if (name.startsWith("list_")) { const values = value.split(";").map(v => v.trim()).filter(v => v != ""); if (values.length == 0) { el.textContent = "<empty>"; } else { const list = document.createElement("ul"); for (v of values) { const item = createListElement(v); list.appendChild(item); } el.appendChild(list); } } else { el.textContent = value; } }); function createListElement (text) { const item = document.createElement("li"); item.textContent = v; var options = { defaultProtocol: 'https', validate: { url: function (value) { return /^(http)s?:\/\//.test(value); } } }; linkifyElement(item, options, document); return item; }
[].forEach.call(document.querySelectorAll("[data-i18n]"), function(el) { const name = el.getAttribute("data-i18n"); const value = $STR(name); if (name.startsWith("list_")) { const values = value.split(";").map(v => v.trim()).filter(v => v != ""); if (values.length == 0) { el.textContent = "<empty>"; } else { const list = document.createElement("ul"); for (v of values) { const item = createListElement(v); list.appendChild(item); } el.appendChild(list); } } else { el.textContent = value; } }); [].forEach.call(document.querySelectorAll("[data-i18n-attr]"), function(el) { const config = el.getAttribute("data-i18n-attr"); const attrs = config.split(";").map(v => v.trim()).filter(v => v != ""); for (const attr of attrs) { const [name, key] = attr.split('='); const value = $STR(key); el.setAttribute(name, value); } }); function createListElement (text) { const item = document.createElement("li"); item.textContent = v; var options = { defaultProtocol: 'https', validate: { url: function (value) { return /^(http)s?:\/\//.test(value); } } }; linkifyElement(item, options, document); return item; }
10
0
1
add_only
--- a/lib/i18n.js +++ b/lib/i18n.js @@ -20,2 +20,12 @@ +[].forEach.call(document.querySelectorAll("[data-i18n-attr]"), function(el) { + const config = el.getAttribute("data-i18n-attr"); + const attrs = config.split(";").map(v => v.trim()).filter(v => v != ""); + for (const attr of attrs) { + const [name, key] = attr.split('='); + const value = $STR(key); + el.setAttribute(name, value); + } + }); + function createListElement (text) {
--- a/lib/i18n.js +++ b/lib/i18n.js @@ ... @@ +[].forEach.call(document.querySelectorAll("[data-i18n-attr]"), function(el) { + const config = el.getAttribute("data-i18n-attr"); + const attrs = config.split(";").map(v => v.trim()).filter(v => v != ""); + for (const attr of attrs) { + const [name, key] = attr.split('='); + const value = $STR(key); + el.setAttribute(name, value); + } + }); + function createListElement (text) {
--- a/lib/i18n.js +++ b/lib/i18n.js @@ -20,2 +20,12 @@ CON ADD [].forEach.call(document.querySelectorAll("[data-i18n-attr]"), function(el) { ADD const config = el.getAttribute("data-i18n-attr"); ADD const attrs = config.split(";").map(v => v.trim()).filter(v => v != ""); ADD for (const attr of attrs) { ADD const [name, key] = attr.split('='); ADD const value = $STR(key); ADD el.setAttribute(name, value); ADD } ADD }); ADD CON function createListElement (text) {
<<<<<<< SEARCH }); function createListElement (text) { const item = document.createElement("li"); ======= }); [].forEach.call(document.querySelectorAll("[data-i18n-attr]"), function(el) { const config = el.getAttribute("data-i18n-attr"); const attrs = config.split(";").map(v => v.trim()).filter(v => v != ""); for (const attr of attrs) { const [name, key] = attr.split('='); const value = $STR(key); el.setAttribute(name, value); } }); function createListElement (text) { const item = document.createElement("li"); >>>>>>> REPLACE
toastkidjp/Yobidashi_kt
53514a567932042adfb916e3f86bedc45f23cf7c
app/src/main/java/jp/toastkid/yobidashi/planning_poker/Adapter.kt
kotlin
epl-1.0
Clean up Planning Poker's adapter.
package jp.toastkid.yobidashi.planning_poker import android.databinding.DataBindingUtil import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.ViewGroup import jp.toastkid.yobidashi.R import jp.toastkid.yobidashi.databinding.CardItemBinding /** * RecyclerView's adapter. * @author toastkidjp */ internal class Adapter : RecyclerView.Adapter<CardViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CardViewHolder { return CardViewHolder( DataBindingUtil.inflate<CardItemBinding>( LayoutInflater.from(parent.context), R.layout.card_item, parent, false ) ) } override fun onBindViewHolder(holder: CardViewHolder, position: Int) { val text = Suite.values()[position % Suite.values().size].text() holder.setText(text) holder.itemView.setOnClickListener { v -> holder.open() } } override fun getItemCount(): Int { return MAXIMUM_SIZE } companion object { /** Maximum size. */ private val MAXIMUM_SIZE = Suite.values().size * 20 /** Medium. */ private val MEDIUM = MAXIMUM_SIZE / 2 fun medium(): Int { return MEDIUM } } }
package jp.toastkid.yobidashi.planning_poker import android.databinding.DataBindingUtil import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.ViewGroup import jp.toastkid.yobidashi.R import jp.toastkid.yobidashi.databinding.CardItemBinding /** * RecyclerView's adapter. * * @author toastkidjp */ internal class Adapter : RecyclerView.Adapter<CardViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CardViewHolder { return CardViewHolder( DataBindingUtil.inflate<CardItemBinding>( LayoutInflater.from(parent.context), R.layout.card_item, parent, false ) ) } override fun onBindViewHolder(holder: CardViewHolder, position: Int) { val text = Suite.values()[position % Suite.values().size].text() holder.setText(text) holder.itemView.setOnClickListener { v -> holder.open() } } override fun getItemCount(): Int = MAXIMUM_SIZE companion object { /** * Maximum size. */ private val MAXIMUM_SIZE = Suite.values().size * 20 /** * Medium. */ private val MEDIUM = MAXIMUM_SIZE / 2 /** * Return medium number. */ fun medium(): Int = MEDIUM } }
12
9
3
mixed
--- a/app/src/main/java/jp/toastkid/yobidashi/planning_poker/Adapter.kt +++ b/app/src/main/java/jp/toastkid/yobidashi/planning_poker/Adapter.kt @@ -12,3 +12,3 @@ * RecyclerView's adapter. - + * * @author toastkidjp @@ -34,5 +34,3 @@ - override fun getItemCount(): Int { - return MAXIMUM_SIZE - } + override fun getItemCount(): Int = MAXIMUM_SIZE @@ -40,11 +38,16 @@ - /** Maximum size. */ + /** + * Maximum size. + */ private val MAXIMUM_SIZE = Suite.values().size * 20 - /** Medium. */ + /** + * Medium. + */ private val MEDIUM = MAXIMUM_SIZE / 2 - fun medium(): Int { - return MEDIUM - } + /** + * Return medium number. + */ + fun medium(): Int = MEDIUM }
--- a/app/src/main/java/jp/toastkid/yobidashi/planning_poker/Adapter.kt +++ b/app/src/main/java/jp/toastkid/yobidashi/planning_poker/Adapter.kt @@ ... @@ * RecyclerView's adapter. - + * * @author toastkidjp @@ ... @@ - override fun getItemCount(): Int { - return MAXIMUM_SIZE - } + override fun getItemCount(): Int = MAXIMUM_SIZE @@ ... @@ - /** Maximum size. */ + /** + * Maximum size. + */ private val MAXIMUM_SIZE = Suite.values().size * 20 - /** Medium. */ + /** + * Medium. + */ private val MEDIUM = MAXIMUM_SIZE / 2 - fun medium(): Int { - return MEDIUM - } + /** + * Return medium number. + */ + fun medium(): Int = MEDIUM }
--- a/app/src/main/java/jp/toastkid/yobidashi/planning_poker/Adapter.kt +++ b/app/src/main/java/jp/toastkid/yobidashi/planning_poker/Adapter.kt @@ -12,3 +12,3 @@ CON * RecyclerView's adapter. DEL ADD * CON * @author toastkidjp @@ -34,5 +34,3 @@ CON DEL override fun getItemCount(): Int { DEL return MAXIMUM_SIZE DEL } ADD override fun getItemCount(): Int = MAXIMUM_SIZE CON @@ -40,11 +38,16 @@ CON DEL /** Maximum size. */ ADD /** ADD * Maximum size. ADD */ CON private val MAXIMUM_SIZE = Suite.values().size * 20 CON DEL /** Medium. */ ADD /** ADD * Medium. ADD */ CON private val MEDIUM = MAXIMUM_SIZE / 2 CON DEL fun medium(): Int { DEL return MEDIUM DEL } ADD /** ADD * Return medium number. ADD */ ADD fun medium(): Int = MEDIUM CON }
<<<<<<< SEARCH /** * RecyclerView's adapter. * @author toastkidjp */ ======= /** * RecyclerView's adapter. * * @author toastkidjp */ >>>>>>> REPLACE <<<<<<< SEARCH } override fun getItemCount(): Int { return MAXIMUM_SIZE } companion object { /** Maximum size. */ private val MAXIMUM_SIZE = Suite.values().size * 20 /** Medium. */ private val MEDIUM = MAXIMUM_SIZE / 2 fun medium(): Int { return MEDIUM } } } ======= } override fun getItemCount(): Int = MAXIMUM_SIZE companion object { /** * Maximum size. */ private val MAXIMUM_SIZE = Suite.values().size * 20 /** * Medium. */ private val MEDIUM = MAXIMUM_SIZE / 2 /** * Return medium number. */ fun medium(): Int = MEDIUM } } >>>>>>> REPLACE
elpassion/android-commons
d6d18bc5033ca61c3f3b54d848f6261c2dd817b7
view/src/androidTest/java/com/elpassion/android/view/ViewTest.kt
kotlin
apache-2.0
Add tests for isVisible and enable/disable functions
package com.elpassion.android.view import android.app.Application import android.test.ApplicationTestCase import android.view.View class ViewTest : ApplicationTestCase<Application>(Application::class.java) { fun testShouldSetViewVisibilityToVisible() { val view = View(context) view.visibility = View.INVISIBLE view.show() assertEquals(View.VISIBLE, view.visibility) } fun testShouldSetViewVisibilityToGone() { val view = View(context) view.hide() assertEquals(View.GONE, view.visibility) } }
package com.elpassion.android.view import android.app.Application import android.test.ApplicationTestCase import android.view.View import junit.framework.Assert class ViewTest : ApplicationTestCase<Application>(Application::class.java) { fun testShouldSetViewVisibilityToVisible() { val view = View(context) view.visibility = View.INVISIBLE view.show() assertEquals(View.VISIBLE, view.visibility) } fun testShouldSetViewVisibilityToGone() { val view = View(context) view.hide() assertEquals(View.GONE, view.visibility) } fun testShouldReturnThatViewIsVisibleWhenViewIsVisible() { val view = View(context) assertTrue(view.isVisible()) } fun testShouldReturnThatViewIsInvisibleWhenIsGone() { val view = View(context) view.visibility = View.GONE assertFalse(view.isVisible()) } fun testShouldReturnThatViewIsInvisibleWhenIsInvisible() { val view = View(context) view.visibility = View.INVISIBLE assertFalse(view.isVisible()) } fun testShouldEnableDisabledView() { val view = View(context).apply { isEnabled = false } view.enable() assertTrue(view.isEnabled) } fun testShouldDisableEnabledView() { val view = View(context) view.disable() Assert.assertFalse(view.isEnabled) } }
30
0
2
add_only
--- a/view/src/androidTest/java/com/elpassion/android/view/ViewTest.kt +++ b/view/src/androidTest/java/com/elpassion/android/view/ViewTest.kt @@ -5,2 +5,3 @@ import android.view.View +import junit.framework.Assert @@ -20,2 +21,31 @@ } + + fun testShouldReturnThatViewIsVisibleWhenViewIsVisible() { + val view = View(context) + assertTrue(view.isVisible()) + } + + fun testShouldReturnThatViewIsInvisibleWhenIsGone() { + val view = View(context) + view.visibility = View.GONE + assertFalse(view.isVisible()) + } + + fun testShouldReturnThatViewIsInvisibleWhenIsInvisible() { + val view = View(context) + view.visibility = View.INVISIBLE + assertFalse(view.isVisible()) + } + + fun testShouldEnableDisabledView() { + val view = View(context).apply { isEnabled = false } + view.enable() + assertTrue(view.isEnabled) + } + + fun testShouldDisableEnabledView() { + val view = View(context) + view.disable() + Assert.assertFalse(view.isEnabled) + } }
--- a/view/src/androidTest/java/com/elpassion/android/view/ViewTest.kt +++ b/view/src/androidTest/java/com/elpassion/android/view/ViewTest.kt @@ ... @@ import android.view.View +import junit.framework.Assert @@ ... @@ } + + fun testShouldReturnThatViewIsVisibleWhenViewIsVisible() { + val view = View(context) + assertTrue(view.isVisible()) + } + + fun testShouldReturnThatViewIsInvisibleWhenIsGone() { + val view = View(context) + view.visibility = View.GONE + assertFalse(view.isVisible()) + } + + fun testShouldReturnThatViewIsInvisibleWhenIsInvisible() { + val view = View(context) + view.visibility = View.INVISIBLE + assertFalse(view.isVisible()) + } + + fun testShouldEnableDisabledView() { + val view = View(context).apply { isEnabled = false } + view.enable() + assertTrue(view.isEnabled) + } + + fun testShouldDisableEnabledView() { + val view = View(context) + view.disable() + Assert.assertFalse(view.isEnabled) + } }
--- a/view/src/androidTest/java/com/elpassion/android/view/ViewTest.kt +++ b/view/src/androidTest/java/com/elpassion/android/view/ViewTest.kt @@ -5,2 +5,3 @@ CON import android.view.View ADD import junit.framework.Assert CON @@ -20,2 +21,31 @@ CON } ADD ADD fun testShouldReturnThatViewIsVisibleWhenViewIsVisible() { ADD val view = View(context) ADD assertTrue(view.isVisible()) ADD } ADD ADD fun testShouldReturnThatViewIsInvisibleWhenIsGone() { ADD val view = View(context) ADD view.visibility = View.GONE ADD assertFalse(view.isVisible()) ADD } ADD ADD fun testShouldReturnThatViewIsInvisibleWhenIsInvisible() { ADD val view = View(context) ADD view.visibility = View.INVISIBLE ADD assertFalse(view.isVisible()) ADD } ADD ADD fun testShouldEnableDisabledView() { ADD val view = View(context).apply { isEnabled = false } ADD view.enable() ADD assertTrue(view.isEnabled) ADD } ADD ADD fun testShouldDisableEnabledView() { ADD val view = View(context) ADD view.disable() ADD Assert.assertFalse(view.isEnabled) ADD } CON }
<<<<<<< SEARCH import android.test.ApplicationTestCase import android.view.View class ViewTest : ApplicationTestCase<Application>(Application::class.java) { ======= import android.test.ApplicationTestCase import android.view.View import junit.framework.Assert class ViewTest : ApplicationTestCase<Application>(Application::class.java) { >>>>>>> REPLACE <<<<<<< SEARCH assertEquals(View.GONE, view.visibility) } } ======= assertEquals(View.GONE, view.visibility) } fun testShouldReturnThatViewIsVisibleWhenViewIsVisible() { val view = View(context) assertTrue(view.isVisible()) } fun testShouldReturnThatViewIsInvisibleWhenIsGone() { val view = View(context) view.visibility = View.GONE assertFalse(view.isVisible()) } fun testShouldReturnThatViewIsInvisibleWhenIsInvisible() { val view = View(context) view.visibility = View.INVISIBLE assertFalse(view.isVisible()) } fun testShouldEnableDisabledView() { val view = View(context).apply { isEnabled = false } view.enable() assertTrue(view.isEnabled) } fun testShouldDisableEnabledView() { val view = View(context) view.disable() Assert.assertFalse(view.isEnabled) } } >>>>>>> REPLACE
minidmnv/Apple
9c5d5576969b0afcea55e064bf46fee11fb174b5
src/main/java/pl/minidmnv/apple/source/fixture/repository/FlashScoreFixtureRepository.java
java
apache-2.0
Prepare to supply fixtures from DOM elements
package pl.minidmnv.apple.source.fixture.repository; import java.util.ArrayList; import java.util.List; import java.util.Optional; import org.jsoup.nodes.Document; import org.jsoup.select.Elements; import pl.minidmnv.apple.source.fixture.data.Fixture; import pl.minidmnv.apple.source.fixture.repository.picker.FSFixtureDOMElementPicker; import pl.minidmnv.apple.source.fixture.tray.FixtureTray; /** * @author mnicinski. */ public class FlashScoreFixtureRepository implements FixtureRepository { private FixtureTray fixtureTray; private FSFixtureDOMElementPicker picker = new FSFixtureDOMElementPicker(); @Override public List<Fixture> getUpcomingFixtures(Integer limit) { List fixtures = new ArrayList(); Optional<Document> upcomingFixturesDocument = fixtureTray.getUpcomingFixturesDocument(); if (upcomingFixturesDocument.isPresent()) { Document doc = upcomingFixturesDocument.get(); picker.init(doc); fixtures = parseFixtures(doc); } return fixtures; } private List parseFixtures(Document document) { Elements elements = picker.pickUpcomingFixtures(); return null; } }
package pl.minidmnv.apple.source.fixture.repository; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import pl.minidmnv.apple.source.fixture.data.Fixture; import pl.minidmnv.apple.source.fixture.repository.picker.FSFixtureDOMElementPicker; import pl.minidmnv.apple.source.fixture.tray.FixtureTray; /** * @author mnicinski. */ public class FlashScoreFixtureRepository implements FixtureRepository { private FixtureTray fixtureTray; private FSFixtureDOMElementPicker picker = new FSFixtureDOMElementPicker(); @Override public List<Fixture> getUpcomingFixtures(Integer limit) { List fixtures = new ArrayList(); Optional<Document> upcomingFixturesDocument = fixtureTray.getUpcomingFixturesDocument(); if (upcomingFixturesDocument.isPresent()) { Document doc = upcomingFixturesDocument.get(); fixtures = parseFixtures(doc); } return fixtures; } private List parseFixtures(Document doc) { picker.init(doc); Elements elements = picker.pickUpcomingFixtures(); return elements.stream() .map(this::transformStageScheduledElementToFixture) .collect(Collectors.toList()); } private Fixture transformStageScheduledElementToFixture(Element e) { Fixture result = new Fixture(); return result; } }
15
3
4
mixed
--- a/src/main/java/pl/minidmnv/apple/source/fixture/repository/FlashScoreFixtureRepository.java +++ b/src/main/java/pl/minidmnv/apple/source/fixture/repository/FlashScoreFixtureRepository.java @@ -5,2 +5,3 @@ import java.util.Optional; +import java.util.stream.Collectors; @@ -8,2 +9,3 @@ +import org.jsoup.nodes.Element; import org.jsoup.select.Elements; @@ -28,3 +30,3 @@ Document doc = upcomingFixturesDocument.get(); - picker.init(doc); + fixtures = parseFixtures(doc); @@ -35,5 +37,15 @@ - private List parseFixtures(Document document) { + private List parseFixtures(Document doc) { + picker.init(doc); Elements elements = picker.pickUpcomingFixtures(); - return null; + + return elements.stream() + .map(this::transformStageScheduledElementToFixture) + .collect(Collectors.toList()); + } + + private Fixture transformStageScheduledElementToFixture(Element e) { + Fixture result = new Fixture(); + + return result; }
--- a/src/main/java/pl/minidmnv/apple/source/fixture/repository/FlashScoreFixtureRepository.java +++ b/src/main/java/pl/minidmnv/apple/source/fixture/repository/FlashScoreFixtureRepository.java @@ ... @@ import java.util.Optional; +import java.util.stream.Collectors; @@ ... @@ +import org.jsoup.nodes.Element; import org.jsoup.select.Elements; @@ ... @@ Document doc = upcomingFixturesDocument.get(); - picker.init(doc); + fixtures = parseFixtures(doc); @@ ... @@ - private List parseFixtures(Document document) { + private List parseFixtures(Document doc) { + picker.init(doc); Elements elements = picker.pickUpcomingFixtures(); - return null; + + return elements.stream() + .map(this::transformStageScheduledElementToFixture) + .collect(Collectors.toList()); + } + + private Fixture transformStageScheduledElementToFixture(Element e) { + Fixture result = new Fixture(); + + return result; }
--- a/src/main/java/pl/minidmnv/apple/source/fixture/repository/FlashScoreFixtureRepository.java +++ b/src/main/java/pl/minidmnv/apple/source/fixture/repository/FlashScoreFixtureRepository.java @@ -5,2 +5,3 @@ CON import java.util.Optional; ADD import java.util.stream.Collectors; CON @@ -8,2 +9,3 @@ CON ADD import org.jsoup.nodes.Element; CON import org.jsoup.select.Elements; @@ -28,3 +30,3 @@ CON Document doc = upcomingFixturesDocument.get(); DEL picker.init(doc); ADD CON fixtures = parseFixtures(doc); @@ -35,5 +37,15 @@ CON DEL private List parseFixtures(Document document) { ADD private List parseFixtures(Document doc) { ADD picker.init(doc); CON Elements elements = picker.pickUpcomingFixtures(); DEL return null; ADD ADD return elements.stream() ADD .map(this::transformStageScheduledElementToFixture) ADD .collect(Collectors.toList()); ADD } ADD ADD private Fixture transformStageScheduledElementToFixture(Element e) { ADD Fixture result = new Fixture(); ADD ADD return result; CON }
<<<<<<< SEARCH import java.util.List; import java.util.Optional; import org.jsoup.nodes.Document; import org.jsoup.select.Elements; import pl.minidmnv.apple.source.fixture.data.Fixture; ======= import java.util.List; import java.util.Optional; import java.util.stream.Collectors; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import pl.minidmnv.apple.source.fixture.data.Fixture; >>>>>>> REPLACE <<<<<<< SEARCH if (upcomingFixturesDocument.isPresent()) { Document doc = upcomingFixturesDocument.get(); picker.init(doc); fixtures = parseFixtures(doc); } ======= if (upcomingFixturesDocument.isPresent()) { Document doc = upcomingFixturesDocument.get(); fixtures = parseFixtures(doc); } >>>>>>> REPLACE <<<<<<< SEARCH } private List parseFixtures(Document document) { Elements elements = picker.pickUpcomingFixtures(); return null; } } ======= } private List parseFixtures(Document doc) { picker.init(doc); Elements elements = picker.pickUpcomingFixtures(); return elements.stream() .map(this::transformStageScheduledElementToFixture) .collect(Collectors.toList()); } private Fixture transformStageScheduledElementToFixture(Element e) { Fixture result = new Fixture(); return result; } } >>>>>>> REPLACE
pyamsoft/pydroid
f2872e0d2d96b8b01e0e0bacd36737f65d0424c6
ui/src/main/java/com/pyamsoft/pydroid/ui/rating/dialog/RatingChangelogUiComponent.kt
kotlin
apache-2.0
Fix changelog not displaying bug
/* * Copyright 2019 Peter Kenji Yamanaka * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.pyamsoft.pydroid.ui.rating.dialog import android.os.Bundle import androidx.lifecycle.LifecycleOwner import com.pyamsoft.pydroid.ui.arch.UiComponent import com.pyamsoft.pydroid.ui.arch.ViewEvent.EMPTY import io.reactivex.Observable internal class RatingChangelogUiComponent internal constructor( private val changelogView: RatingChangelogView, owner: LifecycleOwner ) : UiComponent<EMPTY>(owner) { override fun id(): Int { return changelogView.id() } override fun create(savedInstanceState: Bundle?) { changelogView.inflate(savedInstanceState) owner.run { changelogView.teardown() } } override fun saveState(outState: Bundle) { changelogView.saveState(outState) } override fun onUiEvent(): Observable<EMPTY> { return Observable.empty() } }
/* * Copyright 2019 Peter Kenji Yamanaka * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.pyamsoft.pydroid.ui.rating.dialog import android.os.Bundle import androidx.lifecycle.LifecycleOwner import com.pyamsoft.pydroid.ui.arch.UiComponent import com.pyamsoft.pydroid.ui.arch.ViewEvent.EMPTY import io.reactivex.Observable internal class RatingChangelogUiComponent internal constructor( private val changelogView: RatingChangelogView, owner: LifecycleOwner ) : UiComponent<EMPTY>(owner) { override fun id(): Int { return changelogView.id() } override fun create(savedInstanceState: Bundle?) { changelogView.inflate(savedInstanceState) owner.runOnDestroy { changelogView.teardown() } } override fun saveState(outState: Bundle) { changelogView.saveState(outState) } override fun onUiEvent(): Observable<EMPTY> { return Observable.empty() } }
1
1
1
mixed
--- a/ui/src/main/java/com/pyamsoft/pydroid/ui/rating/dialog/RatingChangelogUiComponent.kt +++ b/ui/src/main/java/com/pyamsoft/pydroid/ui/rating/dialog/RatingChangelogUiComponent.kt @@ -36,3 +36,3 @@ changelogView.inflate(savedInstanceState) - owner.run { changelogView.teardown() } + owner.runOnDestroy { changelogView.teardown() } }
--- a/ui/src/main/java/com/pyamsoft/pydroid/ui/rating/dialog/RatingChangelogUiComponent.kt +++ b/ui/src/main/java/com/pyamsoft/pydroid/ui/rating/dialog/RatingChangelogUiComponent.kt @@ ... @@ changelogView.inflate(savedInstanceState) - owner.run { changelogView.teardown() } + owner.runOnDestroy { changelogView.teardown() } }
--- a/ui/src/main/java/com/pyamsoft/pydroid/ui/rating/dialog/RatingChangelogUiComponent.kt +++ b/ui/src/main/java/com/pyamsoft/pydroid/ui/rating/dialog/RatingChangelogUiComponent.kt @@ -36,3 +36,3 @@ CON changelogView.inflate(savedInstanceState) DEL owner.run { changelogView.teardown() } ADD owner.runOnDestroy { changelogView.teardown() } CON }
<<<<<<< SEARCH override fun create(savedInstanceState: Bundle?) { changelogView.inflate(savedInstanceState) owner.run { changelogView.teardown() } } ======= override fun create(savedInstanceState: Bundle?) { changelogView.inflate(savedInstanceState) owner.runOnDestroy { changelogView.teardown() } } >>>>>>> REPLACE
Plain-Solutions/tt-core
b0a60e36aa43c35a901885fb547fa81d3df4b7b7
src/main/java/org/tt/core/dm/TTFactory.java
java
apache-2.0
Make setSQLManager forced to load queries to avoid NPE and misunderstanding
package org.tt.core.dm; import org.tt.core.fetch.AbstractDataFetcher; import org.tt.core.sql.AbstractQueries; import org.tt.core.sql.AbstractSQLManager; public class TTFactory { private static AbstractSQLManager sqlm; private static AbstractQueries qrs; private static AbstractDataFetcher df; private static TTFactory ttf; private TTFactory() { } public static TTFactory getInstance() { if (ttf == null) { ttf = new TTFactory(); } return ttf; } public void setSQLManager(AbstractSQLManager sqlm) { this.sqlm = sqlm; } public void setSQLQueries(AbstractQueries qrs) { this.qrs = qrs; } public void setDataFetcher(AbstractDataFetcher df) { this.df = df; } public TTUpdateManager produceUpdateManager() { return new TTUpdateManager(sqlm, df); } public TTDeliveryManager produceDeliveryManager() { return new TTDeliveryManager(sqlm); } }
package org.tt.core.dm; import org.tt.core.fetch.AbstractDataFetcher; import org.tt.core.sql.AbstractQueries; import org.tt.core.sql.AbstractSQLManager; public class TTFactory { private static AbstractSQLManager sqlm; private static AbstractDataFetcher df; private static TTFactory ttf; private TTFactory() { } public static TTFactory getInstance() { if (ttf == null) { ttf = new TTFactory(); } return ttf; } public void setSQLManager(AbstractSQLManager sqlm, AbstractQueries qrs) { this.sqlm = sqlm; this.sqlm.setQueries(qrs); } public void setDataFetcher(AbstractDataFetcher df) { this.df = df; } public TTUpdateManager produceUpdateManager() { return new TTUpdateManager(sqlm, df); } public TTDeliveryManager produceDeliveryManager() { return new TTDeliveryManager(sqlm); } }
2
6
2
mixed
--- a/src/main/java/org/tt/core/dm/TTFactory.java +++ b/src/main/java/org/tt/core/dm/TTFactory.java @@ -8,3 +8,2 @@ private static AbstractSQLManager sqlm; - private static AbstractQueries qrs; private static AbstractDataFetcher df; @@ -23,8 +22,5 @@ - public void setSQLManager(AbstractSQLManager sqlm) { + public void setSQLManager(AbstractSQLManager sqlm, AbstractQueries qrs) { this.sqlm = sqlm; - } - - public void setSQLQueries(AbstractQueries qrs) { - this.qrs = qrs; + this.sqlm.setQueries(qrs); }
--- a/src/main/java/org/tt/core/dm/TTFactory.java +++ b/src/main/java/org/tt/core/dm/TTFactory.java @@ ... @@ private static AbstractSQLManager sqlm; - private static AbstractQueries qrs; private static AbstractDataFetcher df; @@ ... @@ - public void setSQLManager(AbstractSQLManager sqlm) { + public void setSQLManager(AbstractSQLManager sqlm, AbstractQueries qrs) { this.sqlm = sqlm; - } - - public void setSQLQueries(AbstractQueries qrs) { - this.qrs = qrs; + this.sqlm.setQueries(qrs); }
--- a/src/main/java/org/tt/core/dm/TTFactory.java +++ b/src/main/java/org/tt/core/dm/TTFactory.java @@ -8,3 +8,2 @@ CON private static AbstractSQLManager sqlm; DEL private static AbstractQueries qrs; CON private static AbstractDataFetcher df; @@ -23,8 +22,5 @@ CON DEL public void setSQLManager(AbstractSQLManager sqlm) { ADD public void setSQLManager(AbstractSQLManager sqlm, AbstractQueries qrs) { CON this.sqlm = sqlm; DEL } DEL DEL public void setSQLQueries(AbstractQueries qrs) { DEL this.qrs = qrs; ADD this.sqlm.setQueries(qrs); CON }
<<<<<<< SEARCH public class TTFactory { private static AbstractSQLManager sqlm; private static AbstractQueries qrs; private static AbstractDataFetcher df; private static TTFactory ttf; ======= public class TTFactory { private static AbstractSQLManager sqlm; private static AbstractDataFetcher df; private static TTFactory ttf; >>>>>>> REPLACE <<<<<<< SEARCH } public void setSQLManager(AbstractSQLManager sqlm) { this.sqlm = sqlm; } public void setSQLQueries(AbstractQueries qrs) { this.qrs = qrs; } ======= } public void setSQLManager(AbstractSQLManager sqlm, AbstractQueries qrs) { this.sqlm = sqlm; this.sqlm.setQueries(qrs); } >>>>>>> REPLACE
aeleos/BoringOS
3f166960ac772d499c5cd6e4d8f7ce51c5b75f79
kernel/src/memory/allocator/mod.rs
rust
mit
Fix for GlobalAlloc on latest nightly
//! Provides the heap allocator for the kernel. mod linked_list_allocator; use self::linked_list_allocator::LinkedListAllocator; use alloc::allocator::{GlobalAlloc, Layout, Opaque}; use arch::{self, Architecture}; use memory::{Address, VirtualAddress}; use sync::mutex::Mutex; pub struct Allocator; unsafe impl GlobalAlloc for Allocator { // TODO: Read more on this trait and possibly make it more efficient. unsafe fn alloc(&self, layout: Layout) -> *mut Opaque { ALLOCATOR .lock() .allocate_first_fit(layout.size(), layout.align()) as *mut Opaque } unsafe fn dealloc(&self, ptr: *mut Opaque, layout: Layout) { ALLOCATOR .lock() .free(ptr as *mut u8, layout.size(), layout.align()); } } lazy_static! { /// The kernel heap allocator. static ref ALLOCATOR: Mutex<LinkedListAllocator> = Mutex::new(LinkedListAllocator::new(arch::Current::HEAP_AREA)); } /// Aligns the given address to the given alignment. /// /// The alignment must be a power of two. fn align(address: VirtualAddress, alignment: usize) -> VirtualAddress { debug_assert!(alignment.is_power_of_two()); if address.as_usize() % alignment == 0 { address } else { let alignment_bitmask = !(alignment - 1); VirtualAddress::from_usize((address.as_usize() & alignment_bitmask) + alignment) } }
//! Provides the heap allocator for the kernel. mod linked_list_allocator; use self::linked_list_allocator::LinkedListAllocator; use alloc::allocator::{GlobalAlloc, Layout}; use arch::{self, Architecture}; use memory::{Address, VirtualAddress}; use sync::mutex::Mutex; pub struct Allocator; unsafe impl GlobalAlloc for Allocator { // TODO: Read more on this trait and possibly make it more efficient. unsafe fn alloc(&self, layout: Layout) -> *mut u8 { ALLOCATOR .lock() .allocate_first_fit(layout.size(), layout.align()) } unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) { ALLOCATOR.lock().free(ptr, layout.size(), layout.align()); } } lazy_static! { /// The kernel heap allocator. static ref ALLOCATOR: Mutex<LinkedListAllocator> = Mutex::new(LinkedListAllocator::new(arch::Current::HEAP_AREA)); } /// Aligns the given address to the given alignment. /// /// The alignment must be a power of two. fn align(address: VirtualAddress, alignment: usize) -> VirtualAddress { debug_assert!(alignment.is_power_of_two()); if address.as_usize() % alignment == 0 { address } else { let alignment_bitmask = !(alignment - 1); VirtualAddress::from_usize((address.as_usize() & alignment_bitmask) + alignment) } }
5
7
2
mixed
--- a/kernel/src/memory/allocator/mod.rs +++ b/kernel/src/memory/allocator/mod.rs @@ -5,3 +5,3 @@ use self::linked_list_allocator::LinkedListAllocator; -use alloc::allocator::{GlobalAlloc, Layout, Opaque}; +use alloc::allocator::{GlobalAlloc, Layout}; use arch::{self, Architecture}; @@ -14,12 +14,10 @@ // TODO: Read more on this trait and possibly make it more efficient. - unsafe fn alloc(&self, layout: Layout) -> *mut Opaque { + unsafe fn alloc(&self, layout: Layout) -> *mut u8 { ALLOCATOR .lock() - .allocate_first_fit(layout.size(), layout.align()) as *mut Opaque + .allocate_first_fit(layout.size(), layout.align()) } - unsafe fn dealloc(&self, ptr: *mut Opaque, layout: Layout) { - ALLOCATOR - .lock() - .free(ptr as *mut u8, layout.size(), layout.align()); + unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) { + ALLOCATOR.lock().free(ptr, layout.size(), layout.align()); }
--- a/kernel/src/memory/allocator/mod.rs +++ b/kernel/src/memory/allocator/mod.rs @@ ... @@ use self::linked_list_allocator::LinkedListAllocator; -use alloc::allocator::{GlobalAlloc, Layout, Opaque}; +use alloc::allocator::{GlobalAlloc, Layout}; use arch::{self, Architecture}; @@ ... @@ // TODO: Read more on this trait and possibly make it more efficient. - unsafe fn alloc(&self, layout: Layout) -> *mut Opaque { + unsafe fn alloc(&self, layout: Layout) -> *mut u8 { ALLOCATOR .lock() - .allocate_first_fit(layout.size(), layout.align()) as *mut Opaque + .allocate_first_fit(layout.size(), layout.align()) } - unsafe fn dealloc(&self, ptr: *mut Opaque, layout: Layout) { - ALLOCATOR - .lock() - .free(ptr as *mut u8, layout.size(), layout.align()); + unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) { + ALLOCATOR.lock().free(ptr, layout.size(), layout.align()); }
--- a/kernel/src/memory/allocator/mod.rs +++ b/kernel/src/memory/allocator/mod.rs @@ -5,3 +5,3 @@ CON use self::linked_list_allocator::LinkedListAllocator; DEL use alloc::allocator::{GlobalAlloc, Layout, Opaque}; ADD use alloc::allocator::{GlobalAlloc, Layout}; CON use arch::{self, Architecture}; @@ -14,12 +14,10 @@ CON // TODO: Read more on this trait and possibly make it more efficient. DEL unsafe fn alloc(&self, layout: Layout) -> *mut Opaque { ADD unsafe fn alloc(&self, layout: Layout) -> *mut u8 { CON ALLOCATOR CON .lock() DEL .allocate_first_fit(layout.size(), layout.align()) as *mut Opaque ADD .allocate_first_fit(layout.size(), layout.align()) CON } CON DEL unsafe fn dealloc(&self, ptr: *mut Opaque, layout: Layout) { DEL ALLOCATOR DEL .lock() DEL .free(ptr as *mut u8, layout.size(), layout.align()); ADD unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) { ADD ALLOCATOR.lock().free(ptr, layout.size(), layout.align()); CON }
<<<<<<< SEARCH use self::linked_list_allocator::LinkedListAllocator; use alloc::allocator::{GlobalAlloc, Layout, Opaque}; use arch::{self, Architecture}; use memory::{Address, VirtualAddress}; ======= use self::linked_list_allocator::LinkedListAllocator; use alloc::allocator::{GlobalAlloc, Layout}; use arch::{self, Architecture}; use memory::{Address, VirtualAddress}; >>>>>>> REPLACE <<<<<<< SEARCH unsafe impl GlobalAlloc for Allocator { // TODO: Read more on this trait and possibly make it more efficient. unsafe fn alloc(&self, layout: Layout) -> *mut Opaque { ALLOCATOR .lock() .allocate_first_fit(layout.size(), layout.align()) as *mut Opaque } unsafe fn dealloc(&self, ptr: *mut Opaque, layout: Layout) { ALLOCATOR .lock() .free(ptr as *mut u8, layout.size(), layout.align()); } } ======= unsafe impl GlobalAlloc for Allocator { // TODO: Read more on this trait and possibly make it more efficient. unsafe fn alloc(&self, layout: Layout) -> *mut u8 { ALLOCATOR .lock() .allocate_first_fit(layout.size(), layout.align()) } unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) { ALLOCATOR.lock().free(ptr, layout.size(), layout.align()); } } >>>>>>> REPLACE
METASPACE2020/sm-engine
d8b3e511b00c9b5a8c7951e16d06173fe93d6501
engine/util.py
python
apache-2.0
Fix conditions in JSON encoder
import json import threading import Queue from datetime import datetime,date,timedelta import time from tornado import gen from tornado.ioloop import IOLoop @gen.coroutine def async_sleep(seconds): yield gen.Task(IOLoop.instance().add_timeout, time.time() + seconds) def delayed(seconds): def f(x): time.sleep(seconds) return x return f def call_in_background(f, *args): '''Call function in background in a separate thread / coroutine''' result = Queue.Queue(1) t = threading.Thread(target=lambda: result.put(f(*args))) t.start() return result def get_id_from_slug(slug): '''Remove '/' from a part of url if it is present''' return slug if slug[-1] != '/' else slug[:-1] def my_print(s): '''Pretty printing with timestamp''' print "[" + str(datetime.now()) + "] " + s class DateTimeEncoder(json.JSONEncoder): '''Auxuliary class that lets us encode dates in json''' def default(self, obj): if isinstance(obj, datetime): return obj.isoformat() elif isinstance(obj, date): return obj.isoformat() elif isinstance(obj, timedelta): return (datetime.min + obj).time().isoformat() else: return super(DateTimeEncoder, self).default(obj)
import json import threading import Queue from datetime import datetime,date,timedelta import time import numpy from tornado import gen from tornado.ioloop import IOLoop @gen.coroutine def async_sleep(seconds): yield gen.Task(IOLoop.instance().add_timeout, time.time() + seconds) def delayed(seconds): def f(x): time.sleep(seconds) return x return f def call_in_background(f, *args): '''Call function in background in a separate thread / coroutine''' result = Queue.Queue(1) t = threading.Thread(target=lambda: result.put(f(*args))) t.start() return result def get_id_from_slug(slug): '''Remove '/' from a part of url if it is present''' return slug if slug[-1] != '/' else slug[:-1] def my_print(s): '''Pretty printing with timestamp''' print "[" + str(datetime.now()) + "] " + s class DateTimeEncoder(json.JSONEncoder): '''Auxuliary class that lets us encode dates in json''' def default(self, obj): if hasattr(obj, 'isoformat'): return obj.isoformat() elif isinstance(obj, datetime): return obj.isoformat() elif isinstance(obj, date): return obj.isoformat() elif isinstance(obj, timedelta): return (datetime.min + obj).time().isoformat() elif isinstance(obj, numpy.generic): return numpy.asscalar(obj) else: return super(DateTimeEncoder, self).default(obj)
7
2
3
mixed
--- a/engine/util.py +++ b/engine/util.py @@ -6,2 +6,3 @@ import time +import numpy @@ -39,3 +40,5 @@ def default(self, obj): - if isinstance(obj, datetime): + if hasattr(obj, 'isoformat'): + return obj.isoformat() + elif isinstance(obj, datetime): return obj.isoformat() @@ -45,3 +48,5 @@ return (datetime.min + obj).time().isoformat() - else: + elif isinstance(obj, numpy.generic): + return numpy.asscalar(obj) + else: return super(DateTimeEncoder, self).default(obj)
--- a/engine/util.py +++ b/engine/util.py @@ ... @@ import time +import numpy @@ ... @@ def default(self, obj): - if isinstance(obj, datetime): + if hasattr(obj, 'isoformat'): + return obj.isoformat() + elif isinstance(obj, datetime): return obj.isoformat() @@ ... @@ return (datetime.min + obj).time().isoformat() - else: + elif isinstance(obj, numpy.generic): + return numpy.asscalar(obj) + else: return super(DateTimeEncoder, self).default(obj)
--- a/engine/util.py +++ b/engine/util.py @@ -6,2 +6,3 @@ CON import time ADD import numpy CON @@ -39,3 +40,5 @@ CON def default(self, obj): DEL if isinstance(obj, datetime): ADD if hasattr(obj, 'isoformat'): ADD return obj.isoformat() ADD elif isinstance(obj, datetime): CON return obj.isoformat() @@ -45,3 +48,5 @@ CON return (datetime.min + obj).time().isoformat() DEL else: ADD elif isinstance(obj, numpy.generic): ADD return numpy.asscalar(obj) ADD else: CON return super(DateTimeEncoder, self).default(obj)
<<<<<<< SEARCH from datetime import datetime,date,timedelta import time from tornado import gen ======= from datetime import datetime,date,timedelta import time import numpy from tornado import gen >>>>>>> REPLACE <<<<<<< SEARCH '''Auxuliary class that lets us encode dates in json''' def default(self, obj): if isinstance(obj, datetime): return obj.isoformat() elif isinstance(obj, date): return obj.isoformat() elif isinstance(obj, timedelta): return (datetime.min + obj).time().isoformat() else: return super(DateTimeEncoder, self).default(obj) ======= '''Auxuliary class that lets us encode dates in json''' def default(self, obj): if hasattr(obj, 'isoformat'): return obj.isoformat() elif isinstance(obj, datetime): return obj.isoformat() elif isinstance(obj, date): return obj.isoformat() elif isinstance(obj, timedelta): return (datetime.min + obj).time().isoformat() elif isinstance(obj, numpy.generic): return numpy.asscalar(obj) else: return super(DateTimeEncoder, self).default(obj) >>>>>>> REPLACE
AlexHill/mezzanine
61251afc42b53f7e72b13ad0543c4740d61f092e
mezzanine/core/sitemaps.py
python
bsd-2-clause
Add handling for multi-tenancy in sitemap.xml
from django.contrib.sitemaps import Sitemap from django.db.models import get_models from mezzanine.conf import settings from mezzanine.core.models import Displayable from mezzanine.utils.urls import home_slug blog_installed = "mezzanine.blog" in settings.INSTALLED_APPS if blog_installed: from mezzanine.blog.models import BlogPost class DisplayableSitemap(Sitemap): """ Sitemap class for Django's sitemaps framework that returns all published items for models that subclass ``Displayable``. """ def items(self): """ Return all published items for models that subclass ``Displayable``, excluding those that point to external sites. """ # Fake homepage object. home = Displayable() setattr(home, "get_absolute_url", home_slug) items = {home.get_absolute_url(): home} for model in get_models(): if issubclass(model, Displayable): for item in (model.objects.published() .exclude(slug__startswith="http://") .exclude(slug__startswith="https://")): items[item.get_absolute_url()] = item return items.values() def lastmod(self, obj): if blog_installed and isinstance(obj, BlogPost): return obj.publish_date
from django.contrib.sitemaps import Sitemap from django.contrib.sites.models import Site from django.db.models import get_models from mezzanine.conf import settings from mezzanine.core.models import Displayable from mezzanine.utils.sites import current_site_id from mezzanine.utils.urls import home_slug blog_installed = "mezzanine.blog" in settings.INSTALLED_APPS if blog_installed: from mezzanine.blog.models import BlogPost class DisplayableSitemap(Sitemap): """ Sitemap class for Django's sitemaps framework that returns all published items for models that subclass ``Displayable``. """ def items(self): """ Return all published items for models that subclass ``Displayable``, excluding those that point to external sites. """ # Fake homepage object. home = Displayable() setattr(home, "get_absolute_url", home_slug) items = {home.get_absolute_url(): home} for model in get_models(): if issubclass(model, Displayable): for item in (model.objects.published() .exclude(slug__startswith="http://") .exclude(slug__startswith="https://")): items[item.get_absolute_url()] = item return items.values() def lastmod(self, obj): if blog_installed and isinstance(obj, BlogPost): return obj.publish_date def get_urls(self, **kwargs): """ Ensure the correct host by injecting the current site. """ kwargs["site"] = Site.objects.get(id=current_site_id()) return super(DisplayableSitemap, self).get_urls(**kwargs)
9
0
3
add_only
--- a/mezzanine/core/sitemaps.py +++ b/mezzanine/core/sitemaps.py @@ -2,2 +2,3 @@ from django.contrib.sitemaps import Sitemap +from django.contrib.sites.models import Site from django.db.models import get_models @@ -6,2 +7,3 @@ from mezzanine.core.models import Displayable +from mezzanine.utils.sites import current_site_id from mezzanine.utils.urls import home_slug @@ -40 +42,8 @@ return obj.publish_date + + def get_urls(self, **kwargs): + """ + Ensure the correct host by injecting the current site. + """ + kwargs["site"] = Site.objects.get(id=current_site_id()) + return super(DisplayableSitemap, self).get_urls(**kwargs)
--- a/mezzanine/core/sitemaps.py +++ b/mezzanine/core/sitemaps.py @@ ... @@ from django.contrib.sitemaps import Sitemap +from django.contrib.sites.models import Site from django.db.models import get_models @@ ... @@ from mezzanine.core.models import Displayable +from mezzanine.utils.sites import current_site_id from mezzanine.utils.urls import home_slug @@ ... @@ return obj.publish_date + + def get_urls(self, **kwargs): + """ + Ensure the correct host by injecting the current site. + """ + kwargs["site"] = Site.objects.get(id=current_site_id()) + return super(DisplayableSitemap, self).get_urls(**kwargs)
--- a/mezzanine/core/sitemaps.py +++ b/mezzanine/core/sitemaps.py @@ -2,2 +2,3 @@ CON from django.contrib.sitemaps import Sitemap ADD from django.contrib.sites.models import Site CON from django.db.models import get_models @@ -6,2 +7,3 @@ CON from mezzanine.core.models import Displayable ADD from mezzanine.utils.sites import current_site_id CON from mezzanine.utils.urls import home_slug @@ -40 +42,8 @@ CON return obj.publish_date ADD ADD def get_urls(self, **kwargs): ADD """ ADD Ensure the correct host by injecting the current site. ADD """ ADD kwargs["site"] = Site.objects.get(id=current_site_id()) ADD return super(DisplayableSitemap, self).get_urls(**kwargs)
<<<<<<< SEARCH from django.contrib.sitemaps import Sitemap from django.db.models import get_models from mezzanine.conf import settings from mezzanine.core.models import Displayable from mezzanine.utils.urls import home_slug ======= from django.contrib.sitemaps import Sitemap from django.contrib.sites.models import Site from django.db.models import get_models from mezzanine.conf import settings from mezzanine.core.models import Displayable from mezzanine.utils.sites import current_site_id from mezzanine.utils.urls import home_slug >>>>>>> REPLACE <<<<<<< SEARCH if blog_installed and isinstance(obj, BlogPost): return obj.publish_date ======= if blog_installed and isinstance(obj, BlogPost): return obj.publish_date def get_urls(self, **kwargs): """ Ensure the correct host by injecting the current site. """ kwargs["site"] = Site.objects.get(id=current_site_id()) return super(DisplayableSitemap, self).get_urls(**kwargs) >>>>>>> REPLACE
michael/substance-1
9454abfc0af3071612e3b7b048097023e29fcb0a
test/index.js
javascript
mit
Enable throwing asserts for tests.
import './AnnotationCommand.test' import './annotationHelpers.test' import './ArrayOperation.test' import './ChangeHistory.test' import './Clipboard.test' import './Component.test' import './ContainerSelection.test' import './CustomSelection.test' import './DefaultDOMElement.test' import './Document.test' import './DocumentChange.test' import './documentHelpers.test' import './DocumentIndex.test' import './DOMElement.test' import './DOMImporter.test' import './DOMSelection.test' import './Editing.test' import './EditorSession.test' import './EditorSessionNew.test' import './Fragmenter.test' import './HTMLExporter.test' import './HTMLImporter.test' import './InlineNode.test' import './IsolatedNode.test' import './KeyboardManager.test' import './NodeSchema.test' import './ObjectOperation.test' import './OperationSerializer.test' import './ParentNode.test' import './paste.test' import './prettyPrintXML.test' import './RenderingEngine.test' import './sanitizeHTML.test' import './Surface.test' import './tableHelpers.test' import './TextOperation.test' import './TextPropertyComponent.test' import './TreeIndex.test' import './utils.test' import './XMLExporter.test' import './XMLImporter.test'
import './AnnotationCommand.test' import './annotationHelpers.test' import './ArrayOperation.test' import './ChangeHistory.test' import './Clipboard.test' import './Component.test' import './ContainerSelection.test' import './CustomSelection.test' import './DefaultDOMElement.test' import './Document.test' import './DocumentChange.test' import './documentHelpers.test' import './DocumentIndex.test' import './DOMElement.test' import './DOMImporter.test' import './DOMSelection.test' import './Editing.test' import './EditorSession.test' import './EditorSessionNew.test' import './Fragmenter.test' import './HTMLExporter.test' import './HTMLImporter.test' import './InlineNode.test' import './IsolatedNode.test' import './KeyboardManager.test' import './NodeSchema.test' import './ObjectOperation.test' import './OperationSerializer.test' import './ParentNode.test' import './paste.test' import './prettyPrintXML.test' import './RenderingEngine.test' import './sanitizeHTML.test' import './Surface.test' import './tableHelpers.test' import './TextOperation.test' import './TextPropertyComponent.test' import './TreeIndex.test' import './utils.test' import './XMLExporter.test' import './XMLImporter.test' import { substanceGlobals } from 'substance' // throw in failed asserts substanceGlobals.ASSERTS = true // enable this to see more info from the RenderingEngine // substanceGlobals.VERBOSE_RENDERING_ENGINE = true
6
0
1
add_only
--- a/test/index.js +++ b/test/index.js @@ -41 +41,7 @@ import './XMLImporter.test' + +import { substanceGlobals } from 'substance' +// throw in failed asserts +substanceGlobals.ASSERTS = true +// enable this to see more info from the RenderingEngine +// substanceGlobals.VERBOSE_RENDERING_ENGINE = true
--- a/test/index.js +++ b/test/index.js @@ ... @@ import './XMLImporter.test' + +import { substanceGlobals } from 'substance' +// throw in failed asserts +substanceGlobals.ASSERTS = true +// enable this to see more info from the RenderingEngine +// substanceGlobals.VERBOSE_RENDERING_ENGINE = true
--- a/test/index.js +++ b/test/index.js @@ -41 +41,7 @@ CON import './XMLImporter.test' ADD ADD import { substanceGlobals } from 'substance' ADD // throw in failed asserts ADD substanceGlobals.ASSERTS = true ADD // enable this to see more info from the RenderingEngine ADD // substanceGlobals.VERBOSE_RENDERING_ENGINE = true
<<<<<<< SEARCH import './XMLExporter.test' import './XMLImporter.test' ======= import './XMLExporter.test' import './XMLImporter.test' import { substanceGlobals } from 'substance' // throw in failed asserts substanceGlobals.ASSERTS = true // enable this to see more info from the RenderingEngine // substanceGlobals.VERBOSE_RENDERING_ENGINE = true >>>>>>> REPLACE
Logicalshift/gossyp
37508e1e12755366edaa33708b2f0f43397a845b
src/main.rs
rust
apache-2.0
Use the read_line tool to implement a basic REPL
extern crate silkthread_base; extern crate silkthread_toolkit; use silkthread_base::basic::*; use silkthread_toolkit::io::*; fn main() { // Start up let main_env = DynamicEnvironment::new(); main_env.import(IoTools::new_stdio()); // Display header let print_string = main_env.get_typed_tool::<String, ()>("print").unwrap(); print_string.invoke(format!("{} {} by {}\n", env!("CARGO_PKG_NAME"), env!("CARGO_PKG_VERSION"), env!("CARGO_PKG_AUTHORS")), &main_env).unwrap(); }
extern crate serde_json; extern crate silkthread_base; extern crate silkthread_toolkit; use serde_json::*; use silkthread_base::basic::*; use silkthread_toolkit::io::*; use silkthread_toolkit::io::tool::*; fn main() { // Start up let main_env = DynamicEnvironment::new(); main_env.import(IoTools::new_stdio()); // Display a header let print_string = main_env.get_typed_tool::<String, ()>("print").unwrap(); print_string.invoke(format!("{} {} by {}\n", env!("CARGO_PKG_NAME"), env!("CARGO_PKG_VERSION"), env!("CARGO_PKG_AUTHORS")), &main_env).unwrap(); // Start a REPL loop { let print_string = main_env.get_typed_tool::<String, ()>(PRINT).unwrap(); let print_value = main_env.get_typed_tool::<Value, ()>(PRINT).unwrap(); let read_line = main_env.get_typed_tool::<(), ReadLineResult>(READ_LINE).unwrap(); let display_prompt = main_env.get_typed_tool::<(), ()>("display-prompt"); // Display a prompt display_prompt .map(|tool| tool.invoke((), &main_env).unwrap()) .map_err(|_| print_string.invoke(String::from("\n=» "), &main_env).unwrap()) .unwrap_or(()); // Read the next line let next_line = read_line.invoke((), &main_env); match next_line { Ok(result) => { // Process the line // TODO! print_string.invoke(result.line, &main_env).unwrap(); print_string.invoke(String::from("\n"), &main_env).unwrap(); // Stop on EOF if result.eof { break; } }, Err(erm) => { // Stop if we hit an error print_string.invoke(String::from("Error while reading from prompt: "), &main_env).unwrap(); print_value.invoke(erm, &main_env).unwrap(); break; }, } } }
43
1
3
mixed
--- a/src/main.rs +++ b/src/main.rs @@ -1 +1,2 @@ +extern crate serde_json; extern crate silkthread_base; @@ -3,4 +4,7 @@ +use serde_json::*; + use silkthread_base::basic::*; use silkthread_toolkit::io::*; +use silkthread_toolkit::io::tool::*; @@ -11,5 +15,43 @@ - // Display header + // Display a header let print_string = main_env.get_typed_tool::<String, ()>("print").unwrap(); print_string.invoke(format!("{} {} by {}\n", env!("CARGO_PKG_NAME"), env!("CARGO_PKG_VERSION"), env!("CARGO_PKG_AUTHORS")), &main_env).unwrap(); + + // Start a REPL + loop { + let print_string = main_env.get_typed_tool::<String, ()>(PRINT).unwrap(); + let print_value = main_env.get_typed_tool::<Value, ()>(PRINT).unwrap(); + let read_line = main_env.get_typed_tool::<(), ReadLineResult>(READ_LINE).unwrap(); + let display_prompt = main_env.get_typed_tool::<(), ()>("display-prompt"); + + // Display a prompt + display_prompt + .map(|tool| tool.invoke((), &main_env).unwrap()) + .map_err(|_| print_string.invoke(String::from("\n=» "), &main_env).unwrap()) + .unwrap_or(()); + + // Read the next line + let next_line = read_line.invoke((), &main_env); + + match next_line { + Ok(result) => { + // Process the line + // TODO! + print_string.invoke(result.line, &main_env).unwrap(); + print_string.invoke(String::from("\n"), &main_env).unwrap(); + + // Stop on EOF + if result.eof { + break; + } + }, + + Err(erm) => { + // Stop if we hit an error + print_string.invoke(String::from("Error while reading from prompt: "), &main_env).unwrap(); + print_value.invoke(erm, &main_env).unwrap(); + break; + }, + } + } }
--- a/src/main.rs +++ b/src/main.rs @@ ... @@ +extern crate serde_json; extern crate silkthread_base; @@ ... @@ +use serde_json::*; + use silkthread_base::basic::*; use silkthread_toolkit::io::*; +use silkthread_toolkit::io::tool::*; @@ ... @@ - // Display header + // Display a header let print_string = main_env.get_typed_tool::<String, ()>("print").unwrap(); print_string.invoke(format!("{} {} by {}\n", env!("CARGO_PKG_NAME"), env!("CARGO_PKG_VERSION"), env!("CARGO_PKG_AUTHORS")), &main_env).unwrap(); + + // Start a REPL + loop { + let print_string = main_env.get_typed_tool::<String, ()>(PRINT).unwrap(); + let print_value = main_env.get_typed_tool::<Value, ()>(PRINT).unwrap(); + let read_line = main_env.get_typed_tool::<(), ReadLineResult>(READ_LINE).unwrap(); + let display_prompt = main_env.get_typed_tool::<(), ()>("display-prompt"); + + // Display a prompt + display_prompt + .map(|tool| tool.invoke((), &main_env).unwrap()) + .map_err(|_| print_string.invoke(String::from("\n=» "), &main_env).unwrap()) + .unwrap_or(()); + + // Read the next line + let next_line = read_line.invoke((), &main_env); + + match next_line { + Ok(result) => { + // Process the line + // TODO! + print_string.invoke(result.line, &main_env).unwrap(); + print_string.invoke(String::from("\n"), &main_env).unwrap(); + + // Stop on EOF + if result.eof { + break; + } + }, + + Err(erm) => { + // Stop if we hit an error + print_string.invoke(String::from("Error while reading from prompt: "), &main_env).unwrap(); + print_value.invoke(erm, &main_env).unwrap(); + break; + }, + } + } }
--- a/src/main.rs +++ b/src/main.rs @@ -1 +1,2 @@ ADD extern crate serde_json; CON extern crate silkthread_base; @@ -3,4 +4,7 @@ CON ADD use serde_json::*; ADD CON use silkthread_base::basic::*; CON use silkthread_toolkit::io::*; ADD use silkthread_toolkit::io::tool::*; CON @@ -11,5 +15,43 @@ CON DEL // Display header ADD // Display a header CON let print_string = main_env.get_typed_tool::<String, ()>("print").unwrap(); CON print_string.invoke(format!("{} {} by {}\n", env!("CARGO_PKG_NAME"), env!("CARGO_PKG_VERSION"), env!("CARGO_PKG_AUTHORS")), &main_env).unwrap(); ADD ADD // Start a REPL ADD loop { ADD let print_string = main_env.get_typed_tool::<String, ()>(PRINT).unwrap(); ADD let print_value = main_env.get_typed_tool::<Value, ()>(PRINT).unwrap(); ADD let read_line = main_env.get_typed_tool::<(), ReadLineResult>(READ_LINE).unwrap(); ADD let display_prompt = main_env.get_typed_tool::<(), ()>("display-prompt"); ADD ADD // Display a prompt ADD display_prompt ADD .map(|tool| tool.invoke((), &main_env).unwrap()) ADD .map_err(|_| print_string.invoke(String::from("\n=» "), &main_env).unwrap()) ADD .unwrap_or(()); ADD ADD // Read the next line ADD let next_line = read_line.invoke((), &main_env); ADD ADD match next_line { ADD Ok(result) => { ADD // Process the line ADD // TODO! ADD print_string.invoke(result.line, &main_env).unwrap(); ADD print_string.invoke(String::from("\n"), &main_env).unwrap(); ADD ADD // Stop on EOF ADD if result.eof { ADD break; ADD } ADD }, ADD ADD Err(erm) => { ADD // Stop if we hit an error ADD print_string.invoke(String::from("Error while reading from prompt: "), &main_env).unwrap(); ADD print_value.invoke(erm, &main_env).unwrap(); ADD break; ADD }, ADD } ADD } CON }
<<<<<<< SEARCH extern crate silkthread_base; extern crate silkthread_toolkit; use silkthread_base::basic::*; use silkthread_toolkit::io::*; fn main() { ======= extern crate serde_json; extern crate silkthread_base; extern crate silkthread_toolkit; use serde_json::*; use silkthread_base::basic::*; use silkthread_toolkit::io::*; use silkthread_toolkit::io::tool::*; fn main() { >>>>>>> REPLACE <<<<<<< SEARCH main_env.import(IoTools::new_stdio()); // Display header let print_string = main_env.get_typed_tool::<String, ()>("print").unwrap(); print_string.invoke(format!("{} {} by {}\n", env!("CARGO_PKG_NAME"), env!("CARGO_PKG_VERSION"), env!("CARGO_PKG_AUTHORS")), &main_env).unwrap(); } ======= main_env.import(IoTools::new_stdio()); // Display a header let print_string = main_env.get_typed_tool::<String, ()>("print").unwrap(); print_string.invoke(format!("{} {} by {}\n", env!("CARGO_PKG_NAME"), env!("CARGO_PKG_VERSION"), env!("CARGO_PKG_AUTHORS")), &main_env).unwrap(); // Start a REPL loop { let print_string = main_env.get_typed_tool::<String, ()>(PRINT).unwrap(); let print_value = main_env.get_typed_tool::<Value, ()>(PRINT).unwrap(); let read_line = main_env.get_typed_tool::<(), ReadLineResult>(READ_LINE).unwrap(); let display_prompt = main_env.get_typed_tool::<(), ()>("display-prompt"); // Display a prompt display_prompt .map(|tool| tool.invoke((), &main_env).unwrap()) .map_err(|_| print_string.invoke(String::from("\n=» "), &main_env).unwrap()) .unwrap_or(()); // Read the next line let next_line = read_line.invoke((), &main_env); match next_line { Ok(result) => { // Process the line // TODO! print_string.invoke(result.line, &main_env).unwrap(); print_string.invoke(String::from("\n"), &main_env).unwrap(); // Stop on EOF if result.eof { break; } }, Err(erm) => { // Stop if we hit an error print_string.invoke(String::from("Error while reading from prompt: "), &main_env).unwrap(); print_value.invoke(erm, &main_env).unwrap(); break; }, } } } >>>>>>> REPLACE
andars/rust-calculator
619cdcb09203e57c06ee21f136ad21d6c5c635b4
src/main.rs
rust
mit
Exit when ctrl-d is entered however, empty lines (e.g. just newline) do not terminate
use std::io; use std::io::prelude::*; use std::collections::HashMap; pub mod parser; fn evaluate(input: &str, env: &mut HashMap<String, f64>) -> Result<f64, String> { let mut p = parser::Parser::new(input); let ast = try!(p.parse()); match ast.eval(env) { Some(result) => Ok(result), None => Err("No value for that expression!".to_string()) } } pub fn main() { use std::f64; let mut env = HashMap::new(); env.insert("wow".to_string(), 35.0f64); env.insert("pi".to_string(), f64::consts::PI); let stdin = io::stdin(); loop { print!(">> "); io::stdout().flush().ok(); let mut input = String::new(); match stdin.read_line(&mut input) { Ok(_) => { let result = evaluate(&input.trim_right(), &mut env); match result { Ok(value) => { println!("=> {}", value); } Err(s) => { println!("Error: {}", s); } } io::stdout().flush().ok(); } Err(_) => { println!(""); break; } } } }
use std::io; use std::io::prelude::*; use std::collections::HashMap; pub mod parser; fn evaluate(input: &str, env: &mut HashMap<String, f64>) -> Result<f64, String> { let mut p = parser::Parser::new(input); let ast = try!(p.parse()); match ast.eval(env) { Some(result) => Ok(result), None => Err("No value for that expression!".to_string()) } } pub fn main() { use std::f64; let mut env = HashMap::new(); env.insert("wow".to_string(), 35.0f64); env.insert("pi".to_string(), f64::consts::PI); let stdin = io::stdin(); loop { print!(">> "); io::stdout().flush().ok(); let mut input = String::new(); match stdin.read_line(&mut input) { Ok(_) => { if input.len() == 0 { println!(""); return; } let expression_text = input.trim_right(); let result = evaluate(expression_text, &mut env); match result { Ok(value) => { println!("=> {}", value); } Err(s) => { println!("Error: {}", s); } } io::stdout().flush().ok(); } Err(_) => { println!(""); return; } } } }
10
2
2
mixed
--- a/src/main.rs +++ b/src/main.rs @@ -31,3 +31,11 @@ Ok(_) => { - let result = evaluate(&input.trim_right(), &mut env); + + if input.len() == 0 { + println!(""); + return; + } + + let expression_text = input.trim_right(); + + let result = evaluate(expression_text, &mut env); match result { @@ -44,3 +52,3 @@ println!(""); - break; + return; }
--- a/src/main.rs +++ b/src/main.rs @@ ... @@ Ok(_) => { - let result = evaluate(&input.trim_right(), &mut env); + + if input.len() == 0 { + println!(""); + return; + } + + let expression_text = input.trim_right(); + + let result = evaluate(expression_text, &mut env); match result { @@ ... @@ println!(""); - break; + return; }
--- a/src/main.rs +++ b/src/main.rs @@ -31,3 +31,11 @@ CON Ok(_) => { DEL let result = evaluate(&input.trim_right(), &mut env); ADD ADD if input.len() == 0 { ADD println!(""); ADD return; ADD } ADD ADD let expression_text = input.trim_right(); ADD ADD let result = evaluate(expression_text, &mut env); CON match result { @@ -44,3 +52,3 @@ CON println!(""); DEL break; ADD return; CON }
<<<<<<< SEARCH match stdin.read_line(&mut input) { Ok(_) => { let result = evaluate(&input.trim_right(), &mut env); match result { Ok(value) => { ======= match stdin.read_line(&mut input) { Ok(_) => { if input.len() == 0 { println!(""); return; } let expression_text = input.trim_right(); let result = evaluate(expression_text, &mut env); match result { Ok(value) => { >>>>>>> REPLACE <<<<<<< SEARCH Err(_) => { println!(""); break; } } ======= Err(_) => { println!(""); return; } } >>>>>>> REPLACE
lawremi/PerFabricaAdAstra
232c7c7550d913b06495a46b8863af694334d8bf
src/org/pfaa/block/CompositeBlock.java
java
artistic-2.0
Correct for internal adjustment to block resistance in getter.
package org.pfaa.block; import java.util.List; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.item.ItemStack; public abstract class CompositeBlock extends Block implements CompositeBlockAccessors { public CompositeBlock(int id, int textureIndex, Material material) { super(id, textureIndex, material); } public CompositeBlock(int id, Material material) { this(id, 0, material); } @Override public int damageDropped(int meta) { return meta; } @Override public int getBlockTextureFromSideAndMetadata(int side, int meta) { return blockIndexInTexture + damageDropped(meta); } /* (non-Javadoc) * @see org.pfaa.block.ICompositeBlock#getSubBlocks(int, net.minecraft.creativetab.CreativeTabs, java.util.List) */ @Override public void getSubBlocks(int id, CreativeTabs creativeTabs, List list) { for (int i = 0; i < getMetaCount(); ++i) { list.add(new ItemStack(id, 1, damageDropped(i))); } } public abstract int getMetaCount(); public float getBlockResistance() { return this.blockResistance; } }
package org.pfaa.block; import java.util.List; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.item.ItemStack; public abstract class CompositeBlock extends Block implements CompositeBlockAccessors { public CompositeBlock(int id, int textureIndex, Material material) { super(id, textureIndex, material); } public CompositeBlock(int id, Material material) { this(id, 0, material); } @Override public int damageDropped(int meta) { return meta; } @Override public int getBlockTextureFromSideAndMetadata(int side, int meta) { return blockIndexInTexture + damageDropped(meta); } /* (non-Javadoc) * @see org.pfaa.block.ICompositeBlock#getSubBlocks(int, net.minecraft.creativetab.CreativeTabs, java.util.List) */ @Override public void getSubBlocks(int id, CreativeTabs creativeTabs, List list) { for (int i = 0; i < getMetaCount(); ++i) { list.add(new ItemStack(id, 1, damageDropped(i))); } } public abstract int getMetaCount(); public float getBlockResistance() { return this.blockResistance / 3.0F; } }
1
1
1
mixed
--- a/src/org/pfaa/block/CompositeBlock.java +++ b/src/org/pfaa/block/CompositeBlock.java @@ -44,3 +44,3 @@ public float getBlockResistance() { - return this.blockResistance; + return this.blockResistance / 3.0F; }
--- a/src/org/pfaa/block/CompositeBlock.java +++ b/src/org/pfaa/block/CompositeBlock.java @@ ... @@ public float getBlockResistance() { - return this.blockResistance; + return this.blockResistance / 3.0F; }
--- a/src/org/pfaa/block/CompositeBlock.java +++ b/src/org/pfaa/block/CompositeBlock.java @@ -44,3 +44,3 @@ CON public float getBlockResistance() { DEL return this.blockResistance; ADD return this.blockResistance / 3.0F; CON }
<<<<<<< SEARCH public float getBlockResistance() { return this.blockResistance; } } ======= public float getBlockResistance() { return this.blockResistance / 3.0F; } } >>>>>>> REPLACE
ShivamSarodia/ShivyC
99177cdc64bdec740557007800b610bff07ce46a
shivyc.py
python
mit
Improve commenting on main function
#!/usr/bin/env python3 """Main executable for ShivyC compiler For usage, run "./shivyc.py --help". """ import argparse def get_arguments(): """Set up the argument parser and return an object storing the argument values. return - An object storing argument values, as returned by argparse.parse_args() """ parser = argparse.ArgumentParser(description="Compile C files.") # The file name of the C file to compile. The file name gets saved to the # file_name attribute of the returned object, but this parameter appears as # "filename" (no underscore) on the command line. parser.add_argument("file_name", metavar="filename") return parser.parse_args() def compile_code(source: str) -> str: """Compile the provided source code into assembly. source - The C source code to compile. return - The asm output """ return source def main(): """Load the input files, and dispatch to the compile function for the main processing. """ arguments = get_arguments() try: c_file = open(arguments.file_name) except IOError: print("shivyc: error: no such file or directory: '{}'" .format(arguments.file_name)) else: compile_code(c_file.read()) c_file.close() if __name__ == "__main__": main()
#!/usr/bin/env python3 """Main executable for ShivyC compiler For usage, run "./shivyc.py --help". """ import argparse def get_arguments(): """Set up the argument parser and return an object storing the argument values. return - An object storing argument values, as returned by argparse.parse_args() """ parser = argparse.ArgumentParser(description="Compile C files.") # The file name of the C file to compile. The file name gets saved to the # file_name attribute of the returned object, but this parameter appears as # "filename" (no underscore) on the command line. parser.add_argument("file_name", metavar="filename") return parser.parse_args() def compile_code(source: str) -> str: """Compile the provided source code into assembly. source - The C source code to compile. return - The asm output """ return source def main(): """Load the input files and dispatch to the compile function for the main processing. The main function handles interfacing with the user, like reading the command line arguments, printing errors, and generating output files. The compilation logic is in the compile_code function to facilitate testing. """ arguments = get_arguments() try: c_file = open(arguments.file_name) except IOError: print("shivyc: error: no such file or directory: '{}'" .format(arguments.file_name)) else: compile_code(c_file.read()) c_file.close() if __name__ == "__main__": main()
5
1
1
mixed
--- a/shivyc.py +++ b/shivyc.py @@ -37,4 +37,8 @@ def main(): - """Load the input files, and dispatch to the compile function for the main + """Load the input files and dispatch to the compile function for the main processing. + + The main function handles interfacing with the user, like reading the + command line arguments, printing errors, and generating output files. The + compilation logic is in the compile_code function to facilitate testing.
--- a/shivyc.py +++ b/shivyc.py @@ ... @@ def main(): - """Load the input files, and dispatch to the compile function for the main + """Load the input files and dispatch to the compile function for the main processing. + + The main function handles interfacing with the user, like reading the + command line arguments, printing errors, and generating output files. The + compilation logic is in the compile_code function to facilitate testing.
--- a/shivyc.py +++ b/shivyc.py @@ -37,4 +37,8 @@ CON def main(): DEL """Load the input files, and dispatch to the compile function for the main ADD """Load the input files and dispatch to the compile function for the main CON processing. ADD ADD The main function handles interfacing with the user, like reading the ADD command line arguments, printing errors, and generating output files. The ADD compilation logic is in the compile_code function to facilitate testing. CON
<<<<<<< SEARCH def main(): """Load the input files, and dispatch to the compile function for the main processing. """ ======= def main(): """Load the input files and dispatch to the compile function for the main processing. The main function handles interfacing with the user, like reading the command line arguments, printing errors, and generating output files. The compilation logic is in the compile_code function to facilitate testing. """ >>>>>>> REPLACE
dawoudt/JustWatchAPI
61448043a039543c38c5ca7b9828792cfc8afbb8
justwatch/justwatchapi.py
python
mit
Check and raise HTTP errors
import requests from babel import Locale class JustWatch: def __init__(self, country='AU', **kwargs): self.kwargs = kwargs self.country = country self.language = Locale.parse('und_{}'.format(self.country)).language def search_for_item(self, **kwargs): if kwargs: self.kwargs = kwargs null = None payload = { "content_types":null, "presentation_types":null, "providers":null, "genres":null, "languages":null, "release_year_from":null, "release_year_until":null, "monetization_types":null, "min_price":null, "max_price":null, "scoring_filter_types":null, "cinema_release":null, "query":null } for key, value in self.kwargs.items(): if key in payload.keys(): payload[key] = value else: print('{} is not a valid keyword'.format(key)) header = {'User-Agent':'JustWatch Python client (github.com/dawoudt/JustWatchAPI)'} api_url = 'https://api.justwatch.com/titles/{}_{}/popular'.format(self.language, self.country) r = requests.post(api_url, json=payload, headers=header) return r.json()
import requests from babel import Locale class JustWatch: def __init__(self, country='AU', **kwargs): self.kwargs = kwargs self.country = country self.language = Locale.parse('und_{}'.format(self.country)).language def search_for_item(self, **kwargs): if kwargs: self.kwargs = kwargs null = None payload = { "content_types":null, "presentation_types":null, "providers":null, "genres":null, "languages":null, "release_year_from":null, "release_year_until":null, "monetization_types":null, "min_price":null, "max_price":null, "scoring_filter_types":null, "cinema_release":null, "query":null } for key, value in self.kwargs.items(): if key in payload.keys(): payload[key] = value else: print('{} is not a valid keyword'.format(key)) header = {'User-Agent':'JustWatch Python client (github.com/dawoudt/JustWatchAPI)'} api_url = 'https://api.justwatch.com/titles/{}_{}/popular'.format(self.language, self.country) r = requests.post(api_url, json=payload, headers=header) # Client should deal with rate-limiting. JustWatch may send a 429 Too Many Requests response. r.raise_for_status() # Raises requests.exceptions.HTTPError if r.status_code != 200 return r.json()
4
0
1
add_only
--- a/justwatch/justwatchapi.py +++ b/justwatch/justwatchapi.py @@ -36,2 +36,6 @@ r = requests.post(api_url, json=payload, headers=header) + + # Client should deal with rate-limiting. JustWatch may send a 429 Too Many Requests response. + r.raise_for_status() # Raises requests.exceptions.HTTPError if r.status_code != 200 + return r.json()
--- a/justwatch/justwatchapi.py +++ b/justwatch/justwatchapi.py @@ ... @@ r = requests.post(api_url, json=payload, headers=header) + + # Client should deal with rate-limiting. JustWatch may send a 429 Too Many Requests response. + r.raise_for_status() # Raises requests.exceptions.HTTPError if r.status_code != 200 + return r.json()
--- a/justwatch/justwatchapi.py +++ b/justwatch/justwatchapi.py @@ -36,2 +36,6 @@ CON r = requests.post(api_url, json=payload, headers=header) ADD ADD # Client should deal with rate-limiting. JustWatch may send a 429 Too Many Requests response. ADD r.raise_for_status() # Raises requests.exceptions.HTTPError if r.status_code != 200 ADD CON return r.json()
<<<<<<< SEARCH api_url = 'https://api.justwatch.com/titles/{}_{}/popular'.format(self.language, self.country) r = requests.post(api_url, json=payload, headers=header) return r.json() ======= api_url = 'https://api.justwatch.com/titles/{}_{}/popular'.format(self.language, self.country) r = requests.post(api_url, json=payload, headers=header) # Client should deal with rate-limiting. JustWatch may send a 429 Too Many Requests response. r.raise_for_status() # Raises requests.exceptions.HTTPError if r.status_code != 200 return r.json() >>>>>>> REPLACE
akilman/appd-hackathon-2016
5ee3f28739700e97b91231a2b694f3ba78065e86
src/main/java/com/googlesource/gerrit/plugins/cookbook/HelloTopMenu.java
java
apache-2.0
Add example of extending Gerrit's top menu item Add a "Browse Repositories" item in the "Projects" menu. Change-Id: I67af5bca1a14288147b1bc43fb089ba0abe0d6b2
// Copyright (C) 2013 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.googlesource.gerrit.plugins.cookbook; import java.util.List; import com.google.common.collect.Lists; import com.google.gerrit.extensions.annotations.PluginName; import com.google.gerrit.extensions.webui.TopMenu; import com.google.inject.Inject; public class HelloTopMenu implements TopMenu { private final List<MenuEntry> menuEntries; @Inject public HelloTopMenu(@PluginName String pluginName) { String baseUrl = "/plugins/" + pluginName + "/"; List<MenuItem> menuItems = Lists.newArrayListWithCapacity(1); menuItems.add(new MenuItem("Documentation", baseUrl)); menuEntries = Lists.newArrayListWithCapacity(1); menuEntries.add(new MenuEntry("Cookbook", menuItems)); } @Override public List<MenuEntry> getEntries() { return menuEntries; } }
// Copyright (C) 2013 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.googlesource.gerrit.plugins.cookbook; import java.util.List; import com.google.common.collect.Lists; import com.google.gerrit.extensions.annotations.PluginName; import com.google.gerrit.extensions.webui.TopMenu; import com.google.inject.Inject; public class HelloTopMenu implements TopMenu { private final List<MenuEntry> menuEntries; @Inject public HelloTopMenu(@PluginName String pluginName) { String baseUrl = "/plugins/" + pluginName + "/"; List<MenuItem> menuItems = Lists.newArrayListWithCapacity(1); menuItems.add(new MenuItem("Documentation", baseUrl)); menuEntries = Lists.newArrayListWithCapacity(1); menuEntries.add(new MenuEntry("Cookbook", menuItems)); menuEntries.add(new MenuEntry("Projects", Lists.newArrayList( new MenuItem("Browse Repositories", "https://gerrit.googlesource.com/")))); } @Override public List<MenuEntry> getEntries() { return menuEntries; } }
2
0
1
add_only
--- a/src/main/java/com/googlesource/gerrit/plugins/cookbook/HelloTopMenu.java +++ b/src/main/java/com/googlesource/gerrit/plugins/cookbook/HelloTopMenu.java @@ -33,2 +33,4 @@ menuEntries.add(new MenuEntry("Cookbook", menuItems)); + menuEntries.add(new MenuEntry("Projects", Lists.newArrayList( + new MenuItem("Browse Repositories", "https://gerrit.googlesource.com/")))); }
--- a/src/main/java/com/googlesource/gerrit/plugins/cookbook/HelloTopMenu.java +++ b/src/main/java/com/googlesource/gerrit/plugins/cookbook/HelloTopMenu.java @@ ... @@ menuEntries.add(new MenuEntry("Cookbook", menuItems)); + menuEntries.add(new MenuEntry("Projects", Lists.newArrayList( + new MenuItem("Browse Repositories", "https://gerrit.googlesource.com/")))); }
--- a/src/main/java/com/googlesource/gerrit/plugins/cookbook/HelloTopMenu.java +++ b/src/main/java/com/googlesource/gerrit/plugins/cookbook/HelloTopMenu.java @@ -33,2 +33,4 @@ CON menuEntries.add(new MenuEntry("Cookbook", menuItems)); ADD menuEntries.add(new MenuEntry("Projects", Lists.newArrayList( ADD new MenuItem("Browse Repositories", "https://gerrit.googlesource.com/")))); CON }
<<<<<<< SEARCH menuEntries = Lists.newArrayListWithCapacity(1); menuEntries.add(new MenuEntry("Cookbook", menuItems)); } ======= menuEntries = Lists.newArrayListWithCapacity(1); menuEntries.add(new MenuEntry("Cookbook", menuItems)); menuEntries.add(new MenuEntry("Projects", Lists.newArrayList( new MenuItem("Browse Repositories", "https://gerrit.googlesource.com/")))); } >>>>>>> REPLACE
libspecinfra/specinfra
c038da2f6b1de2780e02fd1850ab25626225ca7b
tests/service.rs
rust
mit
Add test for shell systemd provider
#![cfg(feature="inline-systemd")] extern crate specinfra; use specinfra::backend; #[test] fn service_resource_with_inline_provider() { let b = backend::direct::Direct::new(); let s = specinfra::new(&b).unwrap(); test_service_resource(s); } fn test_service_resource(s: specinfra::Specinfra) { let dbus = s.service("dbus.service"); assert!(dbus.is_running().unwrap()); let dbus = s.service("dbus"); assert!(dbus.is_running().unwrap()); let sshd = s.service("sshd"); assert!(sshd.is_enabled().unwrap()); let nginx = s.service("nginx"); assert!(nginx.enable().unwrap()); assert!(nginx.is_enabled().unwrap()); assert!(nginx.disable().unwrap()); assert_eq!(nginx.is_enabled().unwrap(), false); assert!(nginx.start().unwrap()); assert!(nginx.is_running().unwrap()); assert!(nginx.reload().unwrap()); assert!(nginx.is_running().unwrap()); assert!(nginx.restart().unwrap()); assert!(nginx.is_running().unwrap()); assert!(nginx.stop().unwrap()); assert_eq!(nginx.is_running().unwrap(), false); }
#![cfg(feature="inline-systemd")] extern crate specinfra; use specinfra::backend; use specinfra::Specinfra; use specinfra::provider::service::inline::null::Null; #[test] fn service_resource_with_inline_provider() { let b = backend::direct::Direct::new(); let s = specinfra::new(&b).unwrap(); test_service_resource(s); } #[test] fn service_resource_with_shell_provider() { let b = backend::direct::Direct::new(); let mut s = specinfra::new(&b).unwrap(); s.providers.service.inline = Box::new(Null); test_service_resource(s); } fn test_service_resource(s: Specinfra) { let dbus = s.service("dbus.service"); assert!(dbus.is_running().unwrap()); let dbus = s.service("dbus"); assert!(dbus.is_running().unwrap()); let sshd = s.service("sshd"); assert!(sshd.is_enabled().unwrap()); let nginx = s.service("nginx"); assert!(nginx.enable().unwrap()); assert!(nginx.is_enabled().unwrap()); assert!(nginx.disable().unwrap()); assert_eq!(nginx.is_enabled().unwrap(), false); assert!(nginx.start().unwrap()); assert!(nginx.is_running().unwrap()); assert!(nginx.reload().unwrap()); assert!(nginx.is_running().unwrap()); assert!(nginx.restart().unwrap()); assert!(nginx.is_running().unwrap()); assert!(nginx.stop().unwrap()); assert_eq!(nginx.is_running().unwrap(), false); }
11
1
2
mixed
--- a/tests/service.rs +++ b/tests/service.rs @@ -4,2 +4,4 @@ use specinfra::backend; +use specinfra::Specinfra; +use specinfra::provider::service::inline::null::Null; @@ -12,3 +14,11 @@ -fn test_service_resource(s: specinfra::Specinfra) { +#[test] +fn service_resource_with_shell_provider() { + let b = backend::direct::Direct::new(); + let mut s = specinfra::new(&b).unwrap(); + s.providers.service.inline = Box::new(Null); + test_service_resource(s); +} + +fn test_service_resource(s: Specinfra) { let dbus = s.service("dbus.service");
--- a/tests/service.rs +++ b/tests/service.rs @@ ... @@ use specinfra::backend; +use specinfra::Specinfra; +use specinfra::provider::service::inline::null::Null; @@ ... @@ -fn test_service_resource(s: specinfra::Specinfra) { +#[test] +fn service_resource_with_shell_provider() { + let b = backend::direct::Direct::new(); + let mut s = specinfra::new(&b).unwrap(); + s.providers.service.inline = Box::new(Null); + test_service_resource(s); +} + +fn test_service_resource(s: Specinfra) { let dbus = s.service("dbus.service");
--- a/tests/service.rs +++ b/tests/service.rs @@ -4,2 +4,4 @@ CON use specinfra::backend; ADD use specinfra::Specinfra; ADD use specinfra::provider::service::inline::null::Null; CON @@ -12,3 +14,11 @@ CON DEL fn test_service_resource(s: specinfra::Specinfra) { ADD #[test] ADD fn service_resource_with_shell_provider() { ADD let b = backend::direct::Direct::new(); ADD let mut s = specinfra::new(&b).unwrap(); ADD s.providers.service.inline = Box::new(Null); ADD test_service_resource(s); ADD } ADD ADD fn test_service_resource(s: Specinfra) { CON let dbus = s.service("dbus.service");
<<<<<<< SEARCH use specinfra::backend; #[test] ======= use specinfra::backend; use specinfra::Specinfra; use specinfra::provider::service::inline::null::Null; #[test] >>>>>>> REPLACE <<<<<<< SEARCH } fn test_service_resource(s: specinfra::Specinfra) { let dbus = s.service("dbus.service"); assert!(dbus.is_running().unwrap()); ======= } #[test] fn service_resource_with_shell_provider() { let b = backend::direct::Direct::new(); let mut s = specinfra::new(&b).unwrap(); s.providers.service.inline = Box::new(Null); test_service_resource(s); } fn test_service_resource(s: Specinfra) { let dbus = s.service("dbus.service"); assert!(dbus.is_running().unwrap()); >>>>>>> REPLACE
keeperofdakeys/asn1-parse
e840c69d8b7b02ef5b1a4995ac0214c3a9df232a
utils/src/asn1-spec-dump.rs
rust
apache-2.0
Remove many0! from dump util, so errors get reported
extern crate asn1_parse; #[macro_use] extern crate nom; extern crate argparse; use std::io; use std::io::Read; use std::fs; use std::path::Path; use asn1_parse::parse::spec::asn1_spec; use argparse::{ArgumentParser, StoreOption}; fn main() { let opts = parse_args(); let bytes: Result<Vec<_>, _> = match opts.file { Some(ref p) => io::BufReader::new( fs::File::open(Path::new(p)).unwrap() ).bytes().collect(), None => io::stdin().bytes().collect(), }; let buffer = bytes.unwrap(); let elems: nom::IResult<_, _> = many0!(buffer.as_slice(), complete!(asn1_spec)); println!("{:#?}", elems); } struct ProgOpts { file: Option<String>, } fn parse_args() -> ProgOpts { let mut opts = ProgOpts { file: None, }; { let mut ap = ArgumentParser::new(); ap.set_description("Dump ASN.1 specification files"); ap.refer(&mut opts.file) .add_argument("file", StoreOption, "ASN.1 spec file to dump"); ap.parse_args_or_exit(); } opts }
extern crate asn1_parse; extern crate nom; extern crate argparse; use std::io; use std::io::Read; use std::fs; use std::path::Path; use asn1_parse::parse::spec::asn1_spec; use argparse::{ArgumentParser, StoreOption}; fn main() { let opts = parse_args(); let bytes: Result<Vec<_>, _> = match opts.file { Some(ref p) => io::BufReader::new( fs::File::open(Path::new(p)).unwrap() ).bytes().collect(), None => io::stdin().bytes().collect(), }; let buffer = bytes.unwrap(); let elems: nom::IResult<_, _> = asn1_spec(buffer.as_slice()); println!("{:#?}", elems); } struct ProgOpts { file: Option<String>, } fn parse_args() -> ProgOpts { let mut opts = ProgOpts { file: None, }; { let mut ap = ArgumentParser::new(); ap.set_description("Dump ASN.1 specification files"); ap.refer(&mut opts.file) .add_argument("file", StoreOption, "ASN.1 spec file to dump"); ap.parse_args_or_exit(); } opts }
1
2
2
mixed
--- a/utils/src/asn1-spec-dump.rs +++ b/utils/src/asn1-spec-dump.rs @@ -1,3 +1,2 @@ extern crate asn1_parse; -#[macro_use] extern crate nom; @@ -22,3 +21,3 @@ let buffer = bytes.unwrap(); - let elems: nom::IResult<_, _> = many0!(buffer.as_slice(), complete!(asn1_spec)); + let elems: nom::IResult<_, _> = asn1_spec(buffer.as_slice()); println!("{:#?}", elems);
--- a/utils/src/asn1-spec-dump.rs +++ b/utils/src/asn1-spec-dump.rs @@ ... @@ extern crate asn1_parse; -#[macro_use] extern crate nom; @@ ... @@ let buffer = bytes.unwrap(); - let elems: nom::IResult<_, _> = many0!(buffer.as_slice(), complete!(asn1_spec)); + let elems: nom::IResult<_, _> = asn1_spec(buffer.as_slice()); println!("{:#?}", elems);
--- a/utils/src/asn1-spec-dump.rs +++ b/utils/src/asn1-spec-dump.rs @@ -1,3 +1,2 @@ CON extern crate asn1_parse; DEL #[macro_use] CON extern crate nom; @@ -22,3 +21,3 @@ CON let buffer = bytes.unwrap(); DEL let elems: nom::IResult<_, _> = many0!(buffer.as_slice(), complete!(asn1_spec)); ADD let elems: nom::IResult<_, _> = asn1_spec(buffer.as_slice()); CON println!("{:#?}", elems);
<<<<<<< SEARCH extern crate asn1_parse; #[macro_use] extern crate nom; extern crate argparse; ======= extern crate asn1_parse; extern crate nom; extern crate argparse; >>>>>>> REPLACE <<<<<<< SEARCH }; let buffer = bytes.unwrap(); let elems: nom::IResult<_, _> = many0!(buffer.as_slice(), complete!(asn1_spec)); println!("{:#?}", elems); } ======= }; let buffer = bytes.unwrap(); let elems: nom::IResult<_, _> = asn1_spec(buffer.as_slice()); println!("{:#?}", elems); } >>>>>>> REPLACE
aidancully/rust
55e37f9f02af4eec5c52413e3219bef838beadab
src/libcore/num/int_macros.rs
rust
apache-2.0
Add examples to int macros
#![doc(hidden)] macro_rules! doc_comment { ($x:expr, $($tt:tt)*) => { #[doc = $x] $($tt)* }; } macro_rules! int_module { ($T:ident) => (int_module!($T, #[stable(feature = "rust1", since = "1.0.0")]);); ($T:ident, #[$attr:meta]) => ( doc_comment! { concat!("The smallest value that can be represented by this integer type. Use [`", stringify!($T), "::MIN", "`](../../std/primitive.", stringify!($T), ".html#associatedconstant.MIN) instead."), #[$attr] pub const MIN: $T = $T::MIN; } doc_comment! { concat!("The largest value that can be represented by this integer type. Use [`", stringify!($T), "::MAX", "`](../../std/primitive.", stringify!($T), ".html#associatedconstant.MAX) instead."), #[$attr] pub const MAX: $T = $T::MAX; } ) }
#![doc(hidden)] macro_rules! doc_comment { ($x:expr, $($tt:tt)*) => { #[doc = $x] $($tt)* }; } macro_rules! int_module { ($T:ident) => (int_module!($T, #[stable(feature = "rust1", since = "1.0.0")]);); ($T:ident, #[$attr:meta]) => ( doc_comment! { concat!("The smallest value that can be represented by this integer type. Use [`", stringify!($T), "::MIN", "`](../../std/primitive.", stringify!($T), ".html#associatedconstant.MIN) instead. # Examples ```rust // deprecated way let min = std::", stringify!($T), "::MIN; // intended way let min = ", stringify!($T), "::MIN; ``` "), #[$attr] pub const MIN: $T = $T::MIN; } doc_comment! { concat!("The largest value that can be represented by this integer type. Use [`", stringify!($T), "::MAX", "`](../../std/primitive.", stringify!($T), ".html#associatedconstant.MAX) instead. # Examples ```rust // deprecated way let max = std::", stringify!($T), "::MAX; // intended way let max = ", stringify!($T), "::MAX; ``` "), #[$attr] pub const MAX: $T = $T::MAX; } ) }
24
2
2
mixed
--- a/src/libcore/num/int_macros.rs +++ b/src/libcore/num/int_macros.rs @@ -14,3 +14,14 @@ concat!("The smallest value that can be represented by this integer type. -Use [`", stringify!($T), "::MIN", "`](../../std/primitive.", stringify!($T), ".html#associatedconstant.MIN) instead."), +Use [`", stringify!($T), "::MIN", "`](../../std/primitive.", stringify!($T), ".html#associatedconstant.MIN) instead. + +# Examples + +```rust +// deprecated way +let min = std::", stringify!($T), "::MIN; + +// intended way +let min = ", stringify!($T), "::MIN; +``` +"), #[$attr] @@ -21,3 +32,14 @@ concat!("The largest value that can be represented by this integer type. -Use [`", stringify!($T), "::MAX", "`](../../std/primitive.", stringify!($T), ".html#associatedconstant.MAX) instead."), +Use [`", stringify!($T), "::MAX", "`](../../std/primitive.", stringify!($T), ".html#associatedconstant.MAX) instead. + +# Examples + +```rust +// deprecated way +let max = std::", stringify!($T), "::MAX; + +// intended way +let max = ", stringify!($T), "::MAX; +``` +"), #[$attr]
--- a/src/libcore/num/int_macros.rs +++ b/src/libcore/num/int_macros.rs @@ ... @@ concat!("The smallest value that can be represented by this integer type. -Use [`", stringify!($T), "::MIN", "`](../../std/primitive.", stringify!($T), ".html#associatedconstant.MIN) instead."), +Use [`", stringify!($T), "::MIN", "`](../../std/primitive.", stringify!($T), ".html#associatedconstant.MIN) instead. + +# Examples + +```rust +// deprecated way +let min = std::", stringify!($T), "::MIN; + +// intended way +let min = ", stringify!($T), "::MIN; +``` +"), #[$attr] @@ ... @@ concat!("The largest value that can be represented by this integer type. -Use [`", stringify!($T), "::MAX", "`](../../std/primitive.", stringify!($T), ".html#associatedconstant.MAX) instead."), +Use [`", stringify!($T), "::MAX", "`](../../std/primitive.", stringify!($T), ".html#associatedconstant.MAX) instead. + +# Examples + +```rust +// deprecated way +let max = std::", stringify!($T), "::MAX; + +// intended way +let max = ", stringify!($T), "::MAX; +``` +"), #[$attr]
--- a/src/libcore/num/int_macros.rs +++ b/src/libcore/num/int_macros.rs @@ -14,3 +14,14 @@ CON concat!("The smallest value that can be represented by this integer type. DEL Use [`", stringify!($T), "::MIN", "`](../../std/primitive.", stringify!($T), ".html#associatedconstant.MIN) instead."), ADD Use [`", stringify!($T), "::MIN", "`](../../std/primitive.", stringify!($T), ".html#associatedconstant.MIN) instead. ADD ADD # Examples ADD ADD ```rust ADD // deprecated way ADD let min = std::", stringify!($T), "::MIN; ADD ADD // intended way ADD let min = ", stringify!($T), "::MIN; ADD ``` ADD "), CON #[$attr] @@ -21,3 +32,14 @@ CON concat!("The largest value that can be represented by this integer type. DEL Use [`", stringify!($T), "::MAX", "`](../../std/primitive.", stringify!($T), ".html#associatedconstant.MAX) instead."), ADD Use [`", stringify!($T), "::MAX", "`](../../std/primitive.", stringify!($T), ".html#associatedconstant.MAX) instead. ADD ADD # Examples ADD ADD ```rust ADD // deprecated way ADD let max = std::", stringify!($T), "::MAX; ADD ADD // intended way ADD let max = ", stringify!($T), "::MAX; ADD ``` ADD "), CON #[$attr]
<<<<<<< SEARCH doc_comment! { concat!("The smallest value that can be represented by this integer type. Use [`", stringify!($T), "::MIN", "`](../../std/primitive.", stringify!($T), ".html#associatedconstant.MIN) instead."), #[$attr] pub const MIN: $T = $T::MIN; ======= doc_comment! { concat!("The smallest value that can be represented by this integer type. Use [`", stringify!($T), "::MIN", "`](../../std/primitive.", stringify!($T), ".html#associatedconstant.MIN) instead. # Examples ```rust // deprecated way let min = std::", stringify!($T), "::MIN; // intended way let min = ", stringify!($T), "::MIN; ``` "), #[$attr] pub const MIN: $T = $T::MIN; >>>>>>> REPLACE <<<<<<< SEARCH doc_comment! { concat!("The largest value that can be represented by this integer type. Use [`", stringify!($T), "::MAX", "`](../../std/primitive.", stringify!($T), ".html#associatedconstant.MAX) instead."), #[$attr] pub const MAX: $T = $T::MAX; ======= doc_comment! { concat!("The largest value that can be represented by this integer type. Use [`", stringify!($T), "::MAX", "`](../../std/primitive.", stringify!($T), ".html#associatedconstant.MAX) instead. # Examples ```rust // deprecated way let max = std::", stringify!($T), "::MAX; // intended way let max = ", stringify!($T), "::MAX; ``` "), #[$attr] pub const MAX: $T = $T::MAX; >>>>>>> REPLACE
brechtm/rinohtype
fcc571d2f4c35ac8f0e94e51e6ac94a0c051062d
src/rinoh/__init__.py
python
agpl-3.0
Update the top-level rinoh package Make all symbols and modules relevant to users available directly from the rinoh package.
# This file is part of rinohtype, the Python document preparation system. # # Copyright (c) Brecht Machiels. # # Use of this source code is subject to the terms of the GNU Affero General # Public License v3. See the LICENSE file or http://www.gnu.org/licenses/. """rinohtype """ import os import sys from importlib import import_module from .version import __version__, __release_date__ if sys.version_info < (3, 3): print('rinohtype requires Python 3.3 or higher') sys.exit(1) CORE_MODULES = ['annotation', 'color', 'dimension', 'document', 'draw', 'float', 'flowable', 'highlight', 'index', 'inline', 'layout', 'number', 'paper', 'paragraph', 'reference', 'structure', 'style', 'table', 'text'] __all__ = CORE_MODULES + ['font', 'frontend', 'backend', 'styleds', 'styles'] DATA_PATH = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'data') # create proxies for the core classes/constants at the top level for easy access for name in CORE_MODULES: module = import_module('.' + name, __name__) module_dict, module_all = module.__dict__, module.__all__ globals().update({name: module_dict[name] for name in module_all}) __all__ += module_all
# This file is part of rinohtype, the Python document preparation system. # # Copyright (c) Brecht Machiels. # # Use of this source code is subject to the terms of the GNU Affero General # Public License v3. See the LICENSE file or http://www.gnu.org/licenses/. """rinohtype """ import os import sys from importlib import import_module from .version import __version__, __release_date__ if sys.version_info < (3, 3): print('rinohtype requires Python 3.3 or higher') sys.exit(1) CORE_MODULES = ['annotation', 'attribute', 'color', 'dimension', 'document', 'draw', 'element', 'float', 'flowable', 'highlight', 'index', 'inline', 'layout', 'number', 'paper', 'paragraph', 'reference', 'structure', 'style', 'table', 'template', 'text'] __all__ = CORE_MODULES + ['font', 'fonts', 'frontend', 'backend', 'resource', 'styleds', 'styles', 'stylesheets', 'templates', 'strings', 'language'] DATA_PATH = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'data') # create proxies for the core classes/constants at the top level for easy access for name in CORE_MODULES: module = import_module('.' + name, __name__) module_dict, module_all = module.__dict__, module.__all__ globals().update({name: module_dict[name] for name in module_all}) __all__ += module_all
7
5
1
mixed
--- a/src/rinoh/__init__.py +++ b/src/rinoh/__init__.py @@ -25,8 +25,10 @@ -CORE_MODULES = ['annotation', 'color', 'dimension', 'document', 'draw', 'float', - 'flowable', 'highlight', 'index', 'inline', 'layout', 'number', - 'paper', 'paragraph', 'reference', 'structure', 'style', - 'table', 'text'] +CORE_MODULES = ['annotation', 'attribute', 'color', 'dimension', 'document', + 'draw', 'element', 'float', 'flowable', 'highlight', 'index', + 'inline', 'layout', 'number', 'paper', 'paragraph', + 'reference', 'structure', 'style', 'table', 'template', 'text'] -__all__ = CORE_MODULES + ['font', 'frontend', 'backend', 'styleds', 'styles'] +__all__ = CORE_MODULES + ['font', 'fonts', 'frontend', 'backend', 'resource', + 'styleds', 'styles', 'stylesheets', 'templates', + 'strings', 'language']
--- a/src/rinoh/__init__.py +++ b/src/rinoh/__init__.py @@ ... @@ -CORE_MODULES = ['annotation', 'color', 'dimension', 'document', 'draw', 'float', - 'flowable', 'highlight', 'index', 'inline', 'layout', 'number', - 'paper', 'paragraph', 'reference', 'structure', 'style', - 'table', 'text'] +CORE_MODULES = ['annotation', 'attribute', 'color', 'dimension', 'document', + 'draw', 'element', 'float', 'flowable', 'highlight', 'index', + 'inline', 'layout', 'number', 'paper', 'paragraph', + 'reference', 'structure', 'style', 'table', 'template', 'text'] -__all__ = CORE_MODULES + ['font', 'frontend', 'backend', 'styleds', 'styles'] +__all__ = CORE_MODULES + ['font', 'fonts', 'frontend', 'backend', 'resource', + 'styleds', 'styles', 'stylesheets', 'templates', + 'strings', 'language']
--- a/src/rinoh/__init__.py +++ b/src/rinoh/__init__.py @@ -25,8 +25,10 @@ CON DEL CORE_MODULES = ['annotation', 'color', 'dimension', 'document', 'draw', 'float', DEL 'flowable', 'highlight', 'index', 'inline', 'layout', 'number', DEL 'paper', 'paragraph', 'reference', 'structure', 'style', DEL 'table', 'text'] ADD CORE_MODULES = ['annotation', 'attribute', 'color', 'dimension', 'document', ADD 'draw', 'element', 'float', 'flowable', 'highlight', 'index', ADD 'inline', 'layout', 'number', 'paper', 'paragraph', ADD 'reference', 'structure', 'style', 'table', 'template', 'text'] CON DEL __all__ = CORE_MODULES + ['font', 'frontend', 'backend', 'styleds', 'styles'] ADD __all__ = CORE_MODULES + ['font', 'fonts', 'frontend', 'backend', 'resource', ADD 'styleds', 'styles', 'stylesheets', 'templates', ADD 'strings', 'language'] CON
<<<<<<< SEARCH CORE_MODULES = ['annotation', 'color', 'dimension', 'document', 'draw', 'float', 'flowable', 'highlight', 'index', 'inline', 'layout', 'number', 'paper', 'paragraph', 'reference', 'structure', 'style', 'table', 'text'] __all__ = CORE_MODULES + ['font', 'frontend', 'backend', 'styleds', 'styles'] ======= CORE_MODULES = ['annotation', 'attribute', 'color', 'dimension', 'document', 'draw', 'element', 'float', 'flowable', 'highlight', 'index', 'inline', 'layout', 'number', 'paper', 'paragraph', 'reference', 'structure', 'style', 'table', 'template', 'text'] __all__ = CORE_MODULES + ['font', 'fonts', 'frontend', 'backend', 'resource', 'styleds', 'styles', 'stylesheets', 'templates', 'strings', 'language'] >>>>>>> REPLACE
samdoshi/portmidi-rs
d64d47f68606fc9b23755e738c2d2483da0cf5f7
examples/monitor.rs
rust
mit
Read at most `buffer_size` events
extern crate portmidi as pm; extern crate rustc_serialize; extern crate docopt; const USAGE: &'static str = r#" portmidi-rs: monitor-device example Usage: monitor-device <id> Options: -h --help Show this screen. Omitting <id> will list the available devices. "#; #[derive(Debug, RustcDecodable)] struct Args { arg_id: i32, } fn print_devices(pm: &pm::PortMidi) { for dev in pm.devices().unwrap() { println!("{}", dev); } } fn main() { let context = pm::PortMidi::new(1024).unwrap(); let args: Args = docopt::Docopt::new(USAGE).and_then(|d| d.decode()).unwrap_or_else(|err| { print_devices(&context); err.exit(); }); let info = context.device(args.arg_id).unwrap(); println!("Listening on: {}) {}", info.id(), info.name()); let mut in_port = context.input_port(info).unwrap(); while let Ok(_) = in_port.poll() { if let Ok(Some(event)) = in_port.read() { println!("{:?}", event); } } }
extern crate portmidi as pm; extern crate rustc_serialize; extern crate docopt; const USAGE: &'static str = r#" portmidi-rs: monitor-device example Usage: monitor-device <id> Options: -h --help Show this screen. Omitting <id> will list the available devices. "#; #[derive(Debug, RustcDecodable)] struct Args { arg_id: i32, } fn print_devices(pm: &pm::PortMidi) { for dev in pm.devices().unwrap() { println!("{}", dev); } } fn main() { let context = pm::PortMidi::new(1024).unwrap(); let args: Args = docopt::Docopt::new(USAGE).and_then(|d| d.decode()).unwrap_or_else(|err| { print_devices(&context); err.exit(); }); let info = context.device(args.arg_id).unwrap(); println!("Listening on: {}) {}", info.id(), info.name()); let mut in_port = context.input_port(info).unwrap(); while let Ok(_) = in_port.poll() { if let Ok(Some(event)) = in_port.read_n(1024) { println!("{:?}", event); } } }
1
1
1
mixed
--- a/examples/monitor.rs +++ b/examples/monitor.rs @@ -39,3 +39,3 @@ while let Ok(_) = in_port.poll() { - if let Ok(Some(event)) = in_port.read() { + if let Ok(Some(event)) = in_port.read_n(1024) { println!("{:?}", event);
--- a/examples/monitor.rs +++ b/examples/monitor.rs @@ ... @@ while let Ok(_) = in_port.poll() { - if let Ok(Some(event)) = in_port.read() { + if let Ok(Some(event)) = in_port.read_n(1024) { println!("{:?}", event);
--- a/examples/monitor.rs +++ b/examples/monitor.rs @@ -39,3 +39,3 @@ CON while let Ok(_) = in_port.poll() { DEL if let Ok(Some(event)) = in_port.read() { ADD if let Ok(Some(event)) = in_port.read_n(1024) { CON println!("{:?}", event);
<<<<<<< SEARCH let mut in_port = context.input_port(info).unwrap(); while let Ok(_) = in_port.poll() { if let Ok(Some(event)) = in_port.read() { println!("{:?}", event); } ======= let mut in_port = context.input_port(info).unwrap(); while let Ok(_) = in_port.poll() { if let Ok(Some(event)) = in_port.read_n(1024) { println!("{:?}", event); } >>>>>>> REPLACE
scijava/scijava-jupyter-kernel
b051489a2d4af2c4a3ef18f7b9a2ca0d176ad6db
src/main/java/org/scijava/notebook/converter/StringToHTMLNotebookConverter.java
java
apache-2.0
Fix converter to escape HTML characters
/*- * #%L * SciJava polyglot kernel for Jupyter. * %% * Copyright (C) 2017 Hadrien Mary * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ package org.scijava.notebook.converter; import org.scijava.Priority; import org.scijava.convert.Converter; import org.scijava.notebook.converter.ouput.HTMLNotebookOutput; import org.scijava.plugin.Plugin; @Plugin(type = Converter.class, priority = Priority.LOW_PRIORITY) public class StringToHTMLNotebookConverter extends NotebookOutputConverter<String, HTMLNotebookOutput> { @Override public Class<String> getInputType() { return String.class; } @Override public Class<HTMLNotebookOutput> getOutputType() { return HTMLNotebookOutput.class; } @Override public HTMLNotebookOutput convert(Object object) { return new HTMLNotebookOutput(HTMLNotebookOutput.getMimeType(), (String) object); } }
/*- * #%L * SciJava polyglot kernel for Jupyter. * %% * Copyright (C) 2017 Hadrien Mary * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ package org.scijava.notebook.converter; import org.apache.commons.lang3.StringEscapeUtils; import org.scijava.Priority; import org.scijava.convert.Converter; import org.scijava.notebook.converter.ouput.HTMLNotebookOutput; import org.scijava.plugin.Plugin; @Plugin(type = Converter.class, priority = Priority.LOW_PRIORITY) public class StringToHTMLNotebookConverter extends NotebookOutputConverter<String, HTMLNotebookOutput> { @Override public Class<String> getInputType() { return String.class; } @Override public Class<HTMLNotebookOutput> getOutputType() { return HTMLNotebookOutput.class; } @Override public HTMLNotebookOutput convert(Object object) { return new HTMLNotebookOutput(HTMLNotebookOutput.getMimeType(), StringEscapeUtils.escapeHtml4((String) object)); } }
2
1
2
mixed
--- a/src/main/java/org/scijava/notebook/converter/StringToHTMLNotebookConverter.java +++ b/src/main/java/org/scijava/notebook/converter/StringToHTMLNotebookConverter.java @@ -22,2 +22,3 @@ +import org.apache.commons.lang3.StringEscapeUtils; import org.scijava.Priority; @@ -44,3 +45,3 @@ return new HTMLNotebookOutput(HTMLNotebookOutput.getMimeType(), - (String) object); + StringEscapeUtils.escapeHtml4((String) object)); }
--- a/src/main/java/org/scijava/notebook/converter/StringToHTMLNotebookConverter.java +++ b/src/main/java/org/scijava/notebook/converter/StringToHTMLNotebookConverter.java @@ ... @@ +import org.apache.commons.lang3.StringEscapeUtils; import org.scijava.Priority; @@ ... @@ return new HTMLNotebookOutput(HTMLNotebookOutput.getMimeType(), - (String) object); + StringEscapeUtils.escapeHtml4((String) object)); }
--- a/src/main/java/org/scijava/notebook/converter/StringToHTMLNotebookConverter.java +++ b/src/main/java/org/scijava/notebook/converter/StringToHTMLNotebookConverter.java @@ -22,2 +22,3 @@ CON ADD import org.apache.commons.lang3.StringEscapeUtils; CON import org.scijava.Priority; @@ -44,3 +45,3 @@ CON return new HTMLNotebookOutput(HTMLNotebookOutput.getMimeType(), DEL (String) object); ADD StringEscapeUtils.escapeHtml4((String) object)); CON }
<<<<<<< SEARCH package org.scijava.notebook.converter; import org.scijava.Priority; import org.scijava.convert.Converter; ======= package org.scijava.notebook.converter; import org.apache.commons.lang3.StringEscapeUtils; import org.scijava.Priority; import org.scijava.convert.Converter; >>>>>>> REPLACE <<<<<<< SEARCH public HTMLNotebookOutput convert(Object object) { return new HTMLNotebookOutput(HTMLNotebookOutput.getMimeType(), (String) object); } ======= public HTMLNotebookOutput convert(Object object) { return new HTMLNotebookOutput(HTMLNotebookOutput.getMimeType(), StringEscapeUtils.escapeHtml4((String) object)); } >>>>>>> REPLACE
uber/kafka-node
4ee9ac2c023b7ebcfbaafcc97d77ec058df864ff
lib/partitioner.js
javascript
mit
Refactor Partitioner class: add class hierarchy.
var _ = require('lodash'); 'use strict'; function DefaultPartitioner() { this.getPartition = function (partitions) { if (partitions && _.isArray(partitions) && partitions.length > 0) { return partitions[0]; } else { return 0; } } } function RandomPartitioner() { this.getPartition = function (partitions) { return partitions[Math.floor(Math.random() * partitions.length)]; } } function KeyedPartitioner() { // Taken from oid package (Dan Bornstein) // Copyright The Obvious Corporation. function hashCode(string) { var hash = 0; var length = string.length; for (var i = 0; i < length; i++) { hash = ((hash * 31) + string.charCodeAt(i)) & 0x7fffffff; } return (hash === 0) ? 1 : hash; } this.getPartition = function (partitions, key) { key = key || '' var index = hashCode(key) % partitions.length; return partitions[index]; } } exports.DefaultPartitioner = DefaultPartitioner; exports.RandomPartitioner = RandomPartitioner; exports.KeyedPartitioner = KeyedPartitioner;
var util = require('util'); var _ = require('lodash'); 'use strict'; var Partitioner = function () { } var DefaultPartitioner = function () { } util.inherits(DefaultPartitioner, Partitioner); DefaultPartitioner.prototype.getPartition = function (partitions) { if (partitions && _.isArray(partitions) && partitions.length > 0) { return partitions[0]; } else { return 0; } } var RandomPartitioner = function () { } util.inherits(RandomPartitioner, Partitioner); RandomPartitioner.prototype.getPartition = function (partitions) { return partitions[Math.floor(Math.random() * partitions.length)]; } var KeyedPartitioner = function () { } util.inherits(KeyedPartitioner, Partitioner); // Taken from oid package (Dan Bornstein) // Copyright The Obvious Corporation. KeyedPartitioner.prototype.hashCode = function(string) { var hash = 0; var length = string.length; for (var i = 0; i < length; i++) { hash = ((hash * 31) + string.charCodeAt(i)) & 0x7fffffff; } return (hash === 0) ? 1 : hash; } KeyedPartitioner.prototype.getPartition = function (partitions, key) { key = key || '' var index = this.hashCode(key) % partitions.length; return partitions[index]; } exports.DefaultPartitioner = DefaultPartitioner; exports.RandomPartitioner = RandomPartitioner; exports.KeyedPartitioner = KeyedPartitioner;
37
27
3
mixed
--- a/lib/partitioner.js +++ b/lib/partitioner.js @@ -1,2 +1,3 @@ -var _ = require('lodash'); +var util = require('util'); +var _ = require('lodash'); @@ -4,9 +5,14 @@ -function DefaultPartitioner() { - this.getPartition = function (partitions) { - if (partitions && _.isArray(partitions) && partitions.length > 0) { - return partitions[0]; - } else { - return 0; - } +var Partitioner = function () { +} + +var DefaultPartitioner = function () { +} +util.inherits(DefaultPartitioner, Partitioner); + +DefaultPartitioner.prototype.getPartition = function (partitions) { + if (partitions && _.isArray(partitions) && partitions.length > 0) { + return partitions[0]; + } else { + return 0; } @@ -14,28 +20,32 @@ -function RandomPartitioner() { - this.getPartition = function (partitions) { - return partitions[Math.floor(Math.random() * partitions.length)]; - } +var RandomPartitioner = function () { +} +util.inherits(RandomPartitioner, Partitioner); + +RandomPartitioner.prototype.getPartition = function (partitions) { + return partitions[Math.floor(Math.random() * partitions.length)]; } -function KeyedPartitioner() { - // Taken from oid package (Dan Bornstein) - // Copyright The Obvious Corporation. - function hashCode(string) { - var hash = 0; - var length = string.length; +var KeyedPartitioner = function () { +} +util.inherits(KeyedPartitioner, Partitioner); - for (var i = 0; i < length; i++) { - hash = ((hash * 31) + string.charCodeAt(i)) & 0x7fffffff; - } +// Taken from oid package (Dan Bornstein) +// Copyright The Obvious Corporation. +KeyedPartitioner.prototype.hashCode = function(string) { + var hash = 0; + var length = string.length; - return (hash === 0) ? 1 : hash; + for (var i = 0; i < length; i++) { + hash = ((hash * 31) + string.charCodeAt(i)) & 0x7fffffff; } - this.getPartition = function (partitions, key) { - key = key || '' + return (hash === 0) ? 1 : hash; +} - var index = hashCode(key) % partitions.length; - return partitions[index]; - } +KeyedPartitioner.prototype.getPartition = function (partitions, key) { + key = key || '' + + var index = this.hashCode(key) % partitions.length; + return partitions[index]; }
--- a/lib/partitioner.js +++ b/lib/partitioner.js @@ ... @@ -var _ = require('lodash'); +var util = require('util'); +var _ = require('lodash'); @@ ... @@ -function DefaultPartitioner() { - this.getPartition = function (partitions) { - if (partitions && _.isArray(partitions) && partitions.length > 0) { - return partitions[0]; - } else { - return 0; - } +var Partitioner = function () { +} + +var DefaultPartitioner = function () { +} +util.inherits(DefaultPartitioner, Partitioner); + +DefaultPartitioner.prototype.getPartition = function (partitions) { + if (partitions && _.isArray(partitions) && partitions.length > 0) { + return partitions[0]; + } else { + return 0; } @@ ... @@ -function RandomPartitioner() { - this.getPartition = function (partitions) { - return partitions[Math.floor(Math.random() * partitions.length)]; - } +var RandomPartitioner = function () { +} +util.inherits(RandomPartitioner, Partitioner); + +RandomPartitioner.prototype.getPartition = function (partitions) { + return partitions[Math.floor(Math.random() * partitions.length)]; } -function KeyedPartitioner() { - // Taken from oid package (Dan Bornstein) - // Copyright The Obvious Corporation. - function hashCode(string) { - var hash = 0; - var length = string.length; +var KeyedPartitioner = function () { +} +util.inherits(KeyedPartitioner, Partitioner); - for (var i = 0; i < length; i++) { - hash = ((hash * 31) + string.charCodeAt(i)) & 0x7fffffff; - } +// Taken from oid package (Dan Bornstein) +// Copyright The Obvious Corporation. +KeyedPartitioner.prototype.hashCode = function(string) { + var hash = 0; + var length = string.length; - return (hash === 0) ? 1 : hash; + for (var i = 0; i < length; i++) { + hash = ((hash * 31) + string.charCodeAt(i)) & 0x7fffffff; } - this.getPartition = function (partitions, key) { - key = key || '' + return (hash === 0) ? 1 : hash; +} - var index = hashCode(key) % partitions.length; - return partitions[index]; - } +KeyedPartitioner.prototype.getPartition = function (partitions, key) { + key = key || '' + + var index = this.hashCode(key) % partitions.length; + return partitions[index]; }
--- a/lib/partitioner.js +++ b/lib/partitioner.js @@ -1,2 +1,3 @@ DEL var _ = require('lodash'); ADD var util = require('util'); ADD var _ = require('lodash'); CON @@ -4,9 +5,14 @@ CON DEL function DefaultPartitioner() { DEL this.getPartition = function (partitions) { DEL if (partitions && _.isArray(partitions) && partitions.length > 0) { DEL return partitions[0]; DEL } else { DEL return 0; DEL } ADD var Partitioner = function () { ADD } ADD ADD var DefaultPartitioner = function () { ADD } ADD util.inherits(DefaultPartitioner, Partitioner); ADD ADD DefaultPartitioner.prototype.getPartition = function (partitions) { ADD if (partitions && _.isArray(partitions) && partitions.length > 0) { ADD return partitions[0]; ADD } else { ADD return 0; CON } @@ -14,28 +20,32 @@ CON DEL function RandomPartitioner() { DEL this.getPartition = function (partitions) { DEL return partitions[Math.floor(Math.random() * partitions.length)]; DEL } ADD var RandomPartitioner = function () { ADD } ADD util.inherits(RandomPartitioner, Partitioner); ADD ADD RandomPartitioner.prototype.getPartition = function (partitions) { ADD return partitions[Math.floor(Math.random() * partitions.length)]; CON } CON DEL function KeyedPartitioner() { DEL // Taken from oid package (Dan Bornstein) DEL // Copyright The Obvious Corporation. DEL function hashCode(string) { DEL var hash = 0; DEL var length = string.length; ADD var KeyedPartitioner = function () { ADD } ADD util.inherits(KeyedPartitioner, Partitioner); CON DEL for (var i = 0; i < length; i++) { DEL hash = ((hash * 31) + string.charCodeAt(i)) & 0x7fffffff; DEL } ADD // Taken from oid package (Dan Bornstein) ADD // Copyright The Obvious Corporation. ADD KeyedPartitioner.prototype.hashCode = function(string) { ADD var hash = 0; ADD var length = string.length; CON DEL return (hash === 0) ? 1 : hash; ADD for (var i = 0; i < length; i++) { ADD hash = ((hash * 31) + string.charCodeAt(i)) & 0x7fffffff; CON } CON DEL this.getPartition = function (partitions, key) { DEL key = key || '' ADD return (hash === 0) ? 1 : hash; ADD } CON DEL var index = hashCode(key) % partitions.length; DEL return partitions[index]; DEL } ADD KeyedPartitioner.prototype.getPartition = function (partitions, key) { ADD key = key || '' ADD ADD var index = this.hashCode(key) % partitions.length; ADD return partitions[index]; CON }
<<<<<<< SEARCH var _ = require('lodash'); 'use strict'; function DefaultPartitioner() { this.getPartition = function (partitions) { if (partitions && _.isArray(partitions) && partitions.length > 0) { return partitions[0]; } else { return 0; } } } function RandomPartitioner() { this.getPartition = function (partitions) { return partitions[Math.floor(Math.random() * partitions.length)]; } } function KeyedPartitioner() { // Taken from oid package (Dan Bornstein) // Copyright The Obvious Corporation. function hashCode(string) { var hash = 0; var length = string.length; for (var i = 0; i < length; i++) { hash = ((hash * 31) + string.charCodeAt(i)) & 0x7fffffff; } return (hash === 0) ? 1 : hash; } this.getPartition = function (partitions, key) { key = key || '' var index = hashCode(key) % partitions.length; return partitions[index]; } } ======= var util = require('util'); var _ = require('lodash'); 'use strict'; var Partitioner = function () { } var DefaultPartitioner = function () { } util.inherits(DefaultPartitioner, Partitioner); DefaultPartitioner.prototype.getPartition = function (partitions) { if (partitions && _.isArray(partitions) && partitions.length > 0) { return partitions[0]; } else { return 0; } } var RandomPartitioner = function () { } util.inherits(RandomPartitioner, Partitioner); RandomPartitioner.prototype.getPartition = function (partitions) { return partitions[Math.floor(Math.random() * partitions.length)]; } var KeyedPartitioner = function () { } util.inherits(KeyedPartitioner, Partitioner); // Taken from oid package (Dan Bornstein) // Copyright The Obvious Corporation. KeyedPartitioner.prototype.hashCode = function(string) { var hash = 0; var length = string.length; for (var i = 0; i < length; i++) { hash = ((hash * 31) + string.charCodeAt(i)) & 0x7fffffff; } return (hash === 0) ? 1 : hash; } KeyedPartitioner.prototype.getPartition = function (partitions, key) { key = key || '' var index = this.hashCode(key) % partitions.length; return partitions[index]; } >>>>>>> REPLACE
zhenyuy-fb/presto
d3f8f502739fbe582404abd790fbb47df5448111
presto-hive/src/main/java/com/facebook/presto/hive/util/Types.java
java
apache-2.0
Add checkType that takes an error code
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.presto.hive.util; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; public final class Types { private Types() {} public static <A, B extends A> B checkType(A value, Class<B> target, String name) { checkNotNull(value, "%s is null", name); checkArgument(target.isInstance(value), "%s must be of type %s, not %s", name, target.getName(), value.getClass().getName()); return target.cast(value); } }
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.presto.hive.util; import com.facebook.presto.spi.ErrorCode; import com.facebook.presto.spi.PrestoException; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; public final class Types { private Types() {} public static <A, B extends A> B checkType(A value, Class<B> target, String name) { checkNotNull(value, "%s is null", name); checkArgument(target.isInstance(value), "%s must be of type %s, not %s", name, target.getName(), value.getClass().getName()); return target.cast(value); } public static <A, B extends A> B checkType(A value, Class<B> target, ErrorCode errorCode, String name) { checkNotNull(value, "%s is null", name); if (!target.isInstance(value)) { throw new PrestoException(errorCode, String.format( "%s must be of type %s, not %s", name, target.getName(), value.getClass().getName())); } return target.cast(value); } }
16
0
2
add_only
--- a/presto-hive/src/main/java/com/facebook/presto/hive/util/Types.java +++ b/presto-hive/src/main/java/com/facebook/presto/hive/util/Types.java @@ -14,2 +14,5 @@ package com.facebook.presto.hive.util; + +import com.facebook.presto.spi.ErrorCode; +import com.facebook.presto.spi.PrestoException; @@ -32,2 +35,15 @@ } + + public static <A, B extends A> B checkType(A value, Class<B> target, ErrorCode errorCode, String name) + { + checkNotNull(value, "%s is null", name); + if (!target.isInstance(value)) { + throw new PrestoException(errorCode, String.format( + "%s must be of type %s, not %s", + name, + target.getName(), + value.getClass().getName())); + } + return target.cast(value); + } }
--- a/presto-hive/src/main/java/com/facebook/presto/hive/util/Types.java +++ b/presto-hive/src/main/java/com/facebook/presto/hive/util/Types.java @@ ... @@ package com.facebook.presto.hive.util; + +import com.facebook.presto.spi.ErrorCode; +import com.facebook.presto.spi.PrestoException; @@ ... @@ } + + public static <A, B extends A> B checkType(A value, Class<B> target, ErrorCode errorCode, String name) + { + checkNotNull(value, "%s is null", name); + if (!target.isInstance(value)) { + throw new PrestoException(errorCode, String.format( + "%s must be of type %s, not %s", + name, + target.getName(), + value.getClass().getName())); + } + return target.cast(value); + } }
--- a/presto-hive/src/main/java/com/facebook/presto/hive/util/Types.java +++ b/presto-hive/src/main/java/com/facebook/presto/hive/util/Types.java @@ -14,2 +14,5 @@ CON package com.facebook.presto.hive.util; ADD ADD import com.facebook.presto.spi.ErrorCode; ADD import com.facebook.presto.spi.PrestoException; CON @@ -32,2 +35,15 @@ CON } ADD ADD public static <A, B extends A> B checkType(A value, Class<B> target, ErrorCode errorCode, String name) ADD { ADD checkNotNull(value, "%s is null", name); ADD if (!target.isInstance(value)) { ADD throw new PrestoException(errorCode, String.format( ADD "%s must be of type %s, not %s", ADD name, ADD target.getName(), ADD value.getClass().getName())); ADD } ADD return target.cast(value); ADD } CON }
<<<<<<< SEARCH */ package com.facebook.presto.hive.util; import static com.google.common.base.Preconditions.checkArgument; ======= */ package com.facebook.presto.hive.util; import com.facebook.presto.spi.ErrorCode; import com.facebook.presto.spi.PrestoException; import static com.google.common.base.Preconditions.checkArgument; >>>>>>> REPLACE <<<<<<< SEARCH return target.cast(value); } } ======= return target.cast(value); } public static <A, B extends A> B checkType(A value, Class<B> target, ErrorCode errorCode, String name) { checkNotNull(value, "%s is null", name); if (!target.isInstance(value)) { throw new PrestoException(errorCode, String.format( "%s must be of type %s, not %s", name, target.getName(), value.getClass().getName())); } return target.cast(value); } } >>>>>>> REPLACE
carewebframework/carewebframework-core
4b1aa93daf1036db0316d801cf5aa7cbf064d98c
org.carewebframework.api/src/main/java/org/carewebframework/api/domain/IDomainFactory.java
java
apache-2.0
Make domain id a String instead of long (more compatible with FHIR).
/** * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. * If a copy of the MPL was not distributed with this file, You can obtain one at * http://mozilla.org/MPL/2.0/. * * This Source Code Form is also subject to the terms of the Health-Related Additional * Disclaimer of Warranty and Limitation of Liability available at * http://www.carewebframework.org/licensing/disclaimer. */ package org.carewebframework.api.domain; import java.util.List; /** * Interface for a domain object factory. * * @param <T> The class of domain object serviced by the factory. */ public interface IDomainFactory<T extends IDomainObject> { /** * Creates a new instance of an object of this domain. * * @return The new domain object instance. */ T newObject(); /** * Fetches an object, identified by its unique id, from the underlying data store. * * @param id Unique id of the object. * @return The requested object. */ T fetchObject(long id); /** * Fetches multiple domain objects as specified by an array of identifier values. * * @param ids An array of unique identifiers. * @return A list of domain objects in the same order as requested in the ids parameter. */ List<T> fetchObjects(long[] ids); }
/** * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. * If a copy of the MPL was not distributed with this file, You can obtain one at * http://mozilla.org/MPL/2.0/. * * This Source Code Form is also subject to the terms of the Health-Related Additional * Disclaimer of Warranty and Limitation of Liability available at * http://www.carewebframework.org/licensing/disclaimer. */ package org.carewebframework.api.domain; import java.util.List; /** * Interface for a domain object factory. * * @param <T> The class of domain object serviced by the factory. */ public interface IDomainFactory<T extends IDomainObject> { /** * Creates a new instance of an object of this domain. * * @return The new domain object instance. */ T newObject(); /** * Fetches an object, identified by its unique id, from the underlying data store. * * @param id Unique id of the object. * @return The requested object. */ T fetchObject(String id); /** * Fetches multiple domain objects as specified by an array of identifier values. * * @param ids An array of unique identifiers. * @return A list of domain objects in the same order as requested in the ids parameter. */ List<T> fetchObjects(String[] ids); }
13
13
6
mixed
--- a/org.carewebframework.api/src/main/java/org/carewebframework/api/domain/IDomainFactory.java +++ b/org.carewebframework.api/src/main/java/org/carewebframework/api/domain/IDomainFactory.java @@ -1,6 +1,6 @@ /** - * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. - * If a copy of the MPL was not distributed with this file, You can obtain one at + * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. + * If a copy of the MPL was not distributed with this file, You can obtain one at * http://mozilla.org/MPL/2.0/. - * + * * This Source Code Form is also subject to the terms of the Health-Related Additional @@ -15,3 +15,3 @@ * Interface for a domain object factory. - * + * * @param <T> The class of domain object serviced by the factory. @@ -19,6 +19,6 @@ public interface IDomainFactory<T extends IDomainObject> { - + /** * Creates a new instance of an object of this domain. - * + * * @return The new domain object instance. @@ -26,6 +26,6 @@ T newObject(); - + /** * Fetches an object, identified by its unique id, from the underlying data store. - * + * * @param id Unique id of the object. @@ -33,7 +33,7 @@ */ - T fetchObject(long id); - + T fetchObject(String id); + /** * Fetches multiple domain objects as specified by an array of identifier values. - * + * * @param ids An array of unique identifiers. @@ -41,4 +41,4 @@ */ - List<T> fetchObjects(long[] ids); - + List<T> fetchObjects(String[] ids); + }
--- a/org.carewebframework.api/src/main/java/org/carewebframework/api/domain/IDomainFactory.java +++ b/org.carewebframework.api/src/main/java/org/carewebframework/api/domain/IDomainFactory.java @@ ... @@ /** - * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. - * If a copy of the MPL was not distributed with this file, You can obtain one at + * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. + * If a copy of the MPL was not distributed with this file, You can obtain one at * http://mozilla.org/MPL/2.0/. - * + * * This Source Code Form is also subject to the terms of the Health-Related Additional @@ ... @@ * Interface for a domain object factory. - * + * * @param <T> The class of domain object serviced by the factory. @@ ... @@ public interface IDomainFactory<T extends IDomainObject> { - + /** * Creates a new instance of an object of this domain. - * + * * @return The new domain object instance. @@ ... @@ T newObject(); - + /** * Fetches an object, identified by its unique id, from the underlying data store. - * + * * @param id Unique id of the object. @@ ... @@ */ - T fetchObject(long id); - + T fetchObject(String id); + /** * Fetches multiple domain objects as specified by an array of identifier values. - * + * * @param ids An array of unique identifiers. @@ ... @@ */ - List<T> fetchObjects(long[] ids); - + List<T> fetchObjects(String[] ids); + }
--- a/org.carewebframework.api/src/main/java/org/carewebframework/api/domain/IDomainFactory.java +++ b/org.carewebframework.api/src/main/java/org/carewebframework/api/domain/IDomainFactory.java @@ -1,6 +1,6 @@ CON /** DEL * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. DEL * If a copy of the MPL was not distributed with this file, You can obtain one at ADD * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. ADD * If a copy of the MPL was not distributed with this file, You can obtain one at CON * http://mozilla.org/MPL/2.0/. DEL * ADD * CON * This Source Code Form is also subject to the terms of the Health-Related Additional @@ -15,3 +15,3 @@ CON * Interface for a domain object factory. DEL * ADD * CON * @param <T> The class of domain object serviced by the factory. @@ -19,6 +19,6 @@ CON public interface IDomainFactory<T extends IDomainObject> { DEL ADD CON /** CON * Creates a new instance of an object of this domain. DEL * ADD * CON * @return The new domain object instance. @@ -26,6 +26,6 @@ CON T newObject(); DEL ADD CON /** CON * Fetches an object, identified by its unique id, from the underlying data store. DEL * ADD * CON * @param id Unique id of the object. @@ -33,7 +33,7 @@ CON */ DEL T fetchObject(long id); DEL ADD T fetchObject(String id); ADD CON /** CON * Fetches multiple domain objects as specified by an array of identifier values. DEL * ADD * CON * @param ids An array of unique identifiers. @@ -41,4 +41,4 @@ CON */ DEL List<T> fetchObjects(long[] ids); DEL ADD List<T> fetchObjects(String[] ids); ADD CON }
<<<<<<< SEARCH /** * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. * If a copy of the MPL was not distributed with this file, You can obtain one at * http://mozilla.org/MPL/2.0/. * * This Source Code Form is also subject to the terms of the Health-Related Additional * Disclaimer of Warranty and Limitation of Liability available at ======= /** * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. * If a copy of the MPL was not distributed with this file, You can obtain one at * http://mozilla.org/MPL/2.0/. * * This Source Code Form is also subject to the terms of the Health-Related Additional * Disclaimer of Warranty and Limitation of Liability available at >>>>>>> REPLACE <<<<<<< SEARCH /** * Interface for a domain object factory. * * @param <T> The class of domain object serviced by the factory. */ public interface IDomainFactory<T extends IDomainObject> { /** * Creates a new instance of an object of this domain. * * @return The new domain object instance. */ T newObject(); /** * Fetches an object, identified by its unique id, from the underlying data store. * * @param id Unique id of the object. * @return The requested object. */ T fetchObject(long id); /** * Fetches multiple domain objects as specified by an array of identifier values. * * @param ids An array of unique identifiers. * @return A list of domain objects in the same order as requested in the ids parameter. */ List<T> fetchObjects(long[] ids); } ======= /** * Interface for a domain object factory. * * @param <T> The class of domain object serviced by the factory. */ public interface IDomainFactory<T extends IDomainObject> { /** * Creates a new instance of an object of this domain. * * @return The new domain object instance. */ T newObject(); /** * Fetches an object, identified by its unique id, from the underlying data store. * * @param id Unique id of the object. * @return The requested object. */ T fetchObject(String id); /** * Fetches multiple domain objects as specified by an array of identifier values. * * @param ids An array of unique identifiers. * @return A list of domain objects in the same order as requested in the ids parameter. */ List<T> fetchObjects(String[] ids); } >>>>>>> REPLACE
vespa-engine/vespa
081933a076d05498879e5e197f2c3ee843a4b282
controller-api/src/main/java/com/yahoo/vespa/hosted/controller/api/integration/organization/Mail.java
java
apache-2.0
Add support for html content
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.vespa.hosted.controller.api.integration.organization; import com.google.common.collect.ImmutableList; import java.util.Collection; import java.util.Objects; /** * A message with a subject and a nonempty set of recipients. * * @author jonmv */ public class Mail { private final Collection<String> recipients; private final String subject; private final String message; public Mail(Collection<String> recipients, String subject, String message) { if (recipients.isEmpty()) throw new IllegalArgumentException("Empty recipient list is not allowed."); recipients.forEach(Objects::requireNonNull); this.recipients = ImmutableList.copyOf(recipients); this.subject = Objects.requireNonNull(subject); this.message = Objects.requireNonNull(message); } public Collection<String> recipients() { return recipients; } public String subject() { return subject; } public String message() { return message; } }
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.vespa.hosted.controller.api.integration.organization; import com.google.common.collect.ImmutableList; import java.util.Collection; import java.util.Objects; import java.util.Optional; /** * A message with a subject and a nonempty set of recipients. * * @author jonmv */ public class Mail { private final Collection<String> recipients; private final String subject; private final String message; private final Optional<String> htmlMessage; public Mail(Collection<String> recipients, String subject, String message) { this(recipients, subject, message, Optional.empty()); } public Mail(Collection<String> recipients, String subject, String message, String htmlMessage) { this(recipients, subject, message, Optional.of(htmlMessage)); } Mail(Collection<String> recipients, String subject, String message, Optional<String> htmlMessage) { if (recipients.isEmpty()) throw new IllegalArgumentException("Empty recipient list is not allowed."); recipients.forEach(Objects::requireNonNull); this.recipients = ImmutableList.copyOf(recipients); this.subject = Objects.requireNonNull(subject); this.message = Objects.requireNonNull(message); this.htmlMessage = Objects.requireNonNull(htmlMessage); } public Collection<String> recipients() { return recipients; } public String subject() { return subject; } public String message() { return message; } public Optional<String> htmlMessage() { return htmlMessage; } }
12
0
4
add_only
--- a/controller-api/src/main/java/com/yahoo/vespa/hosted/controller/api/integration/organization/Mail.java +++ b/controller-api/src/main/java/com/yahoo/vespa/hosted/controller/api/integration/organization/Mail.java @@ -7,2 +7,3 @@ import java.util.Objects; +import java.util.Optional; @@ -18,4 +19,13 @@ private final String message; + private final Optional<String> htmlMessage; public Mail(Collection<String> recipients, String subject, String message) { + this(recipients, subject, message, Optional.empty()); + } + + public Mail(Collection<String> recipients, String subject, String message, String htmlMessage) { + this(recipients, subject, message, Optional.of(htmlMessage)); + } + + Mail(Collection<String> recipients, String subject, String message, Optional<String> htmlMessage) { if (recipients.isEmpty()) @@ -26,2 +36,3 @@ this.message = Objects.requireNonNull(message); + this.htmlMessage = Objects.requireNonNull(htmlMessage); } @@ -31,2 +42,3 @@ public String message() { return message; } + public Optional<String> htmlMessage() { return htmlMessage; }
--- a/controller-api/src/main/java/com/yahoo/vespa/hosted/controller/api/integration/organization/Mail.java +++ b/controller-api/src/main/java/com/yahoo/vespa/hosted/controller/api/integration/organization/Mail.java @@ ... @@ import java.util.Objects; +import java.util.Optional; @@ ... @@ private final String message; + private final Optional<String> htmlMessage; public Mail(Collection<String> recipients, String subject, String message) { + this(recipients, subject, message, Optional.empty()); + } + + public Mail(Collection<String> recipients, String subject, String message, String htmlMessage) { + this(recipients, subject, message, Optional.of(htmlMessage)); + } + + Mail(Collection<String> recipients, String subject, String message, Optional<String> htmlMessage) { if (recipients.isEmpty()) @@ ... @@ this.message = Objects.requireNonNull(message); + this.htmlMessage = Objects.requireNonNull(htmlMessage); } @@ ... @@ public String message() { return message; } + public Optional<String> htmlMessage() { return htmlMessage; }
--- a/controller-api/src/main/java/com/yahoo/vespa/hosted/controller/api/integration/organization/Mail.java +++ b/controller-api/src/main/java/com/yahoo/vespa/hosted/controller/api/integration/organization/Mail.java @@ -7,2 +7,3 @@ CON import java.util.Objects; ADD import java.util.Optional; CON @@ -18,4 +19,13 @@ CON private final String message; ADD private final Optional<String> htmlMessage; CON CON public Mail(Collection<String> recipients, String subject, String message) { ADD this(recipients, subject, message, Optional.empty()); ADD } ADD ADD public Mail(Collection<String> recipients, String subject, String message, String htmlMessage) { ADD this(recipients, subject, message, Optional.of(htmlMessage)); ADD } ADD ADD Mail(Collection<String> recipients, String subject, String message, Optional<String> htmlMessage) { CON if (recipients.isEmpty()) @@ -26,2 +36,3 @@ CON this.message = Objects.requireNonNull(message); ADD this.htmlMessage = Objects.requireNonNull(htmlMessage); CON } @@ -31,2 +42,3 @@ CON public String message() { return message; } ADD public Optional<String> htmlMessage() { return htmlMessage; } CON
<<<<<<< SEARCH import java.util.Collection; import java.util.Objects; /** ======= import java.util.Collection; import java.util.Objects; import java.util.Optional; /** >>>>>>> REPLACE <<<<<<< SEARCH private final String subject; private final String message; public Mail(Collection<String> recipients, String subject, String message) { if (recipients.isEmpty()) throw new IllegalArgumentException("Empty recipient list is not allowed."); ======= private final String subject; private final String message; private final Optional<String> htmlMessage; public Mail(Collection<String> recipients, String subject, String message) { this(recipients, subject, message, Optional.empty()); } public Mail(Collection<String> recipients, String subject, String message, String htmlMessage) { this(recipients, subject, message, Optional.of(htmlMessage)); } Mail(Collection<String> recipients, String subject, String message, Optional<String> htmlMessage) { if (recipients.isEmpty()) throw new IllegalArgumentException("Empty recipient list is not allowed."); >>>>>>> REPLACE <<<<<<< SEARCH this.subject = Objects.requireNonNull(subject); this.message = Objects.requireNonNull(message); } public Collection<String> recipients() { return recipients; } public String subject() { return subject; } public String message() { return message; } } ======= this.subject = Objects.requireNonNull(subject); this.message = Objects.requireNonNull(message); this.htmlMessage = Objects.requireNonNull(htmlMessage); } public Collection<String> recipients() { return recipients; } public String subject() { return subject; } public String message() { return message; } public Optional<String> htmlMessage() { return htmlMessage; } } >>>>>>> REPLACE
bugminer/bugminer
f46f561c70991dc1287bdf624e81676602140860
bugminer-server/src/main/java/de/unistuttgart/iste/rss/bugminer/model/entities/User.java
java
mit
Add name property to user
package de.unistuttgart.iste.rss.bugminer.model.entities; import java.util.ArrayList; import java.util.Collection; import javax.persistence.Entity; import javax.persistence.OneToMany; import de.unistuttgart.iste.rss.bugminer.model.BaseEntity; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; @Component @Scope("prototype") @Entity public class User extends BaseEntity { @OneToMany private Collection<Classification> classifications; public User() { classifications = new ArrayList<>(); } public Collection<Classification> getClassifications() { return classifications; } public void setClassifications(Collection<Classification> classifications) { this.classifications = classifications; } }
package de.unistuttgart.iste.rss.bugminer.model.entities; import java.util.ArrayList; import java.util.Collection; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.OneToMany; import de.unistuttgart.iste.rss.bugminer.model.BaseEntity; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; @Component @Scope("prototype") @Entity public class User extends BaseEntity { @Column private String name; @OneToMany private Collection<Classification> classifications; public User() { classifications = new ArrayList<>(); } public Collection<Classification> getClassifications() { return classifications; } public void setClassifications(Collection<Classification> classifications) { this.classifications = classifications; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
12
0
3
add_only
--- a/bugminer-server/src/main/java/de/unistuttgart/iste/rss/bugminer/model/entities/User.java +++ b/bugminer-server/src/main/java/de/unistuttgart/iste/rss/bugminer/model/entities/User.java @@ -5,2 +5,3 @@ +import javax.persistence.Column; import javax.persistence.Entity; @@ -16,2 +17,5 @@ public class User extends BaseEntity { + @Column + private String name; + @OneToMany @@ -30,2 +34,10 @@ } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } }
--- a/bugminer-server/src/main/java/de/unistuttgart/iste/rss/bugminer/model/entities/User.java +++ b/bugminer-server/src/main/java/de/unistuttgart/iste/rss/bugminer/model/entities/User.java @@ ... @@ +import javax.persistence.Column; import javax.persistence.Entity; @@ ... @@ public class User extends BaseEntity { + @Column + private String name; + @OneToMany @@ ... @@ } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } }
--- a/bugminer-server/src/main/java/de/unistuttgart/iste/rss/bugminer/model/entities/User.java +++ b/bugminer-server/src/main/java/de/unistuttgart/iste/rss/bugminer/model/entities/User.java @@ -5,2 +5,3 @@ CON ADD import javax.persistence.Column; CON import javax.persistence.Entity; @@ -16,2 +17,5 @@ CON public class User extends BaseEntity { ADD @Column ADD private String name; ADD CON @OneToMany @@ -30,2 +34,10 @@ CON } ADD ADD public String getName() { ADD return name; ADD } ADD ADD public void setName(String name) { ADD this.name = name; ADD } CON }
<<<<<<< SEARCH import java.util.Collection; import javax.persistence.Entity; import javax.persistence.OneToMany; ======= import java.util.Collection; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.OneToMany; >>>>>>> REPLACE <<<<<<< SEARCH @Entity public class User extends BaseEntity { @OneToMany private Collection<Classification> classifications; ======= @Entity public class User extends BaseEntity { @Column private String name; @OneToMany private Collection<Classification> classifications; >>>>>>> REPLACE <<<<<<< SEARCH this.classifications = classifications; } } ======= this.classifications = classifications; } public String getName() { return name; } public void setName(String name) { this.name = name; } } >>>>>>> REPLACE
kamatama41/embulk-test-helpers
4ddba47ce789aa7cfee2530159ddf342a2a02db0
build.gradle.kts
kotlin
mit
Update Embulk to the latest
import com.github.kamatama41.gradle.gitrelease.GitReleaseExtension buildscript { val kotlinVersion = "1.2.31" extra["kotlinVersion"] = kotlinVersion repositories { jcenter() maven { setUrl("http://kamatama41.github.com/maven-repository/repository") } } dependencies { classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlinVersion") classpath("com.github.kamatama41:gradle-git-release-plugin:0.2.0") } } apply { plugin("idea") plugin("kotlin") plugin("com.github.kamatama41.git-release") } repositories { jcenter() } configure<JavaPluginConvention> { sourceCompatibility = JavaVersion.VERSION_1_8 targetCompatibility = JavaVersion.VERSION_1_8 } val kotlinVersion: String by extra dependencies { compile("org.jetbrains.kotlin:kotlin-stdlib:$kotlinVersion") compile("org.embulk:embulk-standards:0.8.18") compile("org.embulk:embulk-test:0.8.18") testCompile("junit:junit:4.12") } configure<GitReleaseExtension> { groupId = "com.github.kamatama41" artifactId = "embulk-test-helpers" repoUri = "[email protected]:kamatama41/maven-repository.git" repoDir = file("${System.getProperty("user.home")}/gh-maven-repository") }
import com.github.kamatama41.gradle.gitrelease.GitReleaseExtension buildscript { val kotlinVersion = "1.2.31" extra["kotlinVersion"] = kotlinVersion repositories { jcenter() maven { setUrl("http://kamatama41.github.com/maven-repository/repository") } } dependencies { classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlinVersion") classpath("com.github.kamatama41:gradle-git-release-plugin:0.2.0") } } apply { plugin("idea") plugin("kotlin") plugin("com.github.kamatama41.git-release") } repositories { jcenter() } configure<JavaPluginConvention> { sourceCompatibility = JavaVersion.VERSION_1_8 targetCompatibility = JavaVersion.VERSION_1_8 } val kotlinVersion: String by extra dependencies { compile("org.jetbrains.kotlin:kotlin-stdlib:$kotlinVersion") compile("org.embulk:embulk-standards:0.9.7") compile("org.embulk:embulk-test:0.9.7") testCompile("junit:junit:4.12") } configure<GitReleaseExtension> { groupId = "com.github.kamatama41" artifactId = "embulk-test-helpers" repoUri = "[email protected]:kamatama41/maven-repository.git" repoDir = file("${System.getProperty("user.home")}/gh-maven-repository") }
2
2
1
mixed
--- a/build.gradle.kts +++ b/build.gradle.kts @@ -33,4 +33,4 @@ compile("org.jetbrains.kotlin:kotlin-stdlib:$kotlinVersion") - compile("org.embulk:embulk-standards:0.8.18") - compile("org.embulk:embulk-test:0.8.18") + compile("org.embulk:embulk-standards:0.9.7") + compile("org.embulk:embulk-test:0.9.7") testCompile("junit:junit:4.12")
--- a/build.gradle.kts +++ b/build.gradle.kts @@ ... @@ compile("org.jetbrains.kotlin:kotlin-stdlib:$kotlinVersion") - compile("org.embulk:embulk-standards:0.8.18") - compile("org.embulk:embulk-test:0.8.18") + compile("org.embulk:embulk-standards:0.9.7") + compile("org.embulk:embulk-test:0.9.7") testCompile("junit:junit:4.12")
--- a/build.gradle.kts +++ b/build.gradle.kts @@ -33,4 +33,4 @@ CON compile("org.jetbrains.kotlin:kotlin-stdlib:$kotlinVersion") DEL compile("org.embulk:embulk-standards:0.8.18") DEL compile("org.embulk:embulk-test:0.8.18") ADD compile("org.embulk:embulk-standards:0.9.7") ADD compile("org.embulk:embulk-test:0.9.7") CON testCompile("junit:junit:4.12")
<<<<<<< SEARCH dependencies { compile("org.jetbrains.kotlin:kotlin-stdlib:$kotlinVersion") compile("org.embulk:embulk-standards:0.8.18") compile("org.embulk:embulk-test:0.8.18") testCompile("junit:junit:4.12") } ======= dependencies { compile("org.jetbrains.kotlin:kotlin-stdlib:$kotlinVersion") compile("org.embulk:embulk-standards:0.9.7") compile("org.embulk:embulk-test:0.9.7") testCompile("junit:junit:4.12") } >>>>>>> REPLACE
Nemo157/hamlet
b83593e75846b1305752b5d7bacaa39154875951
src/lib.rs
rust
apache-2.0
Add docs on public modules
//! Provides token definitions for HTML stream processing. The goal of this //! library is to provide a simple API over which higher abstraction can be //! built on. //! //! ## Example //! //! ```rust //! #[macro_use] //! extern crate hamlet; //! //! use std::fmt::Write; //! //! fn main() { //! use hamlet::Token; //! let tokens = vec![ //! Token::text("Hello, "), //! Token::start_tag("small", attrs!(class="foo")), //! Token::text("world!"), //! Token::end_tag("small"), //! ]; //! //! let mut html = String::from(""); //! for token in tokens { //! write!(html, "{}", token); //! } //! //! assert_eq!(html, "Hello, <small class=\"foo\">world!</small>"); //! } //! ``` #![warn(missing_docs)] pub mod util; #[macro_use] mod macros; pub mod attr; mod escape; mod token; pub use token::Token;
//! Provides token definitions for HTML stream processing. The goal of this //! library is to provide a simple API over which higher abstraction can be //! built on. //! //! ## Example //! //! ```rust //! #[macro_use] //! extern crate hamlet; //! //! use std::fmt::Write; //! //! fn main() { //! use hamlet::Token; //! let tokens = vec![ //! Token::text("Hello, "), //! Token::start_tag("small", attrs!(class="foo")), //! Token::text("world!"), //! Token::end_tag("small"), //! ]; //! //! let mut html = String::from(""); //! for token in tokens { //! write!(html, "{}", token); //! } //! //! assert_eq!(html, "Hello, <small class=\"foo\">world!</small>"); //! } //! ``` #![warn(missing_docs)] /// Currently contains just a semi-private utility function to support the /// [`attrs!`](./macro.attrs!.html) macro. pub mod util; #[macro_use] mod macros; /// Contains structs for defining attributes on elements. pub mod attr; mod escape; mod token; pub use token::Token;
3
0
2
add_only
--- a/src/lib.rs +++ b/src/lib.rs @@ -32,2 +32,4 @@ +/// Currently contains just a semi-private utility function to support the +/// [`attrs!`](./macro.attrs!.html) macro. pub mod util; @@ -37,2 +39,3 @@ +/// Contains structs for defining attributes on elements. pub mod attr;
--- a/src/lib.rs +++ b/src/lib.rs @@ ... @@ +/// Currently contains just a semi-private utility function to support the +/// [`attrs!`](./macro.attrs!.html) macro. pub mod util; @@ ... @@ +/// Contains structs for defining attributes on elements. pub mod attr;
--- a/src/lib.rs +++ b/src/lib.rs @@ -32,2 +32,4 @@ CON ADD /// Currently contains just a semi-private utility function to support the ADD /// [`attrs!`](./macro.attrs!.html) macro. CON pub mod util; @@ -37,2 +39,3 @@ CON ADD /// Contains structs for defining attributes on elements. CON pub mod attr;
<<<<<<< SEARCH #![warn(missing_docs)] pub mod util; #[macro_use] mod macros; pub mod attr; mod escape; ======= #![warn(missing_docs)] /// Currently contains just a semi-private utility function to support the /// [`attrs!`](./macro.attrs!.html) macro. pub mod util; #[macro_use] mod macros; /// Contains structs for defining attributes on elements. pub mod attr; mod escape; >>>>>>> REPLACE
CS2103AUG2016-F10-C1/main
b6e41e649abab4bf6ba29c6a6400c87e3a548a15
src/test/java/tars/testutil/TestTask.java
java
mit
Add setDateTime(DateTime) and setPriority(Priority) methods
package tars.testutil; import tars.model.task.*; import tars.model.tag.UniqueTagList; /** * A mutable task object. For testing only. */ public class TestTask implements ReadOnlyTask { private Name name; private UniqueTagList tags; private DateTime dateTime; private Status status; private Priority priority; public TestTask() { tags = new UniqueTagList(); } public void setName(Name name) { this.name = name; } @Override public Name getName() { return name; } @Override public DateTime getDateTime() { return dateTime; } @Override public Status getStatus() { return status; } @Override public Priority getPriority() { return priority; } @Override public UniqueTagList getTags() { return tags; } @Override public String toString() { return getAsText(); } public String getAddCommand() { StringBuilder sb = new StringBuilder(); sb.append("add " + this.getName().taskName + " "); sb.append("-dt " + this.getDateTime().toString() + " "); sb.append("-p " + this.getPriority().toString() + " "); this.getTags().getInternalList().stream().forEach(s -> sb.append("t/" + s.tagName + " ")); return sb.toString(); } }
package tars.testutil; import tars.model.task.*; import tars.model.tag.UniqueTagList; /** * A mutable task object. For testing only. */ public class TestTask implements ReadOnlyTask { private Name name; private UniqueTagList tags; private DateTime dateTime; private Status status; private Priority priority; public TestTask() { tags = new UniqueTagList(); } public void setName(Name name) { this.name = name; } public void setDateTime(DateTime dateTime) { this.dateTime = dateTime; } public void setPriority(Priority priority) { this.priority = priority; } @Override public Name getName() { return name; } @Override public DateTime getDateTime() { return dateTime; } @Override public Status getStatus() { return status; } @Override public Priority getPriority() { return priority; } @Override public UniqueTagList getTags() { return tags; } @Override public String toString() { return getAsText(); } public String getAddCommand() { StringBuilder sb = new StringBuilder(); sb.append("add " + this.getName().taskName + " "); sb.append("-dt " + this.getDateTime().toString() + " "); sb.append("-p " + this.getPriority().toString() + " "); this.getTags().getInternalList().stream().forEach(s -> sb.append("t/" + s.tagName + " ")); return sb.toString(); } }
9
0
1
add_only
--- a/src/test/java/tars/testutil/TestTask.java +++ b/src/test/java/tars/testutil/TestTask.java @@ -22,2 +22,11 @@ this.name = name; + } + + public void setDateTime(DateTime dateTime) { + this.dateTime = dateTime; + } + + + public void setPriority(Priority priority) { + this.priority = priority; }
--- a/src/test/java/tars/testutil/TestTask.java +++ b/src/test/java/tars/testutil/TestTask.java @@ ... @@ this.name = name; + } + + public void setDateTime(DateTime dateTime) { + this.dateTime = dateTime; + } + + + public void setPriority(Priority priority) { + this.priority = priority; }
--- a/src/test/java/tars/testutil/TestTask.java +++ b/src/test/java/tars/testutil/TestTask.java @@ -22,2 +22,11 @@ CON this.name = name; ADD } ADD ADD public void setDateTime(DateTime dateTime) { ADD this.dateTime = dateTime; ADD } ADD ADD ADD public void setPriority(Priority priority) { ADD this.priority = priority; CON }
<<<<<<< SEARCH public void setName(Name name) { this.name = name; } ======= public void setName(Name name) { this.name = name; } public void setDateTime(DateTime dateTime) { this.dateTime = dateTime; } public void setPriority(Priority priority) { this.priority = priority; } >>>>>>> REPLACE
materials-commons/materialscommons.org
04eebc1c92c8d1d5f031ff2b1681ebe7de1fec11
backend/server/schema/schema-rules.js
javascript
mit
Add rules for validating property schema _type and units.
module.exports = function(model) { return { mustExist: mustExist, mustNotExist: mustNotExist }; function mustExist(what, modelName, done) { 'use strict'; model[modelName].get(what).then(function(value) { let error = null; if (!value) { error = { rule: 'mustExist', actual: what, expected: 'did not find ' + what + ' in model' }; } done(error); }); } function mustNotExist(what, spec, done) { 'use strict'; let pieces = spec.split(':'), modelName = pieces[0], modelIndex = pieces[1]; model[modelName].get(what, modelIndex).then(function(value) { let error = null; if (value) { // found a match, when we shouldn't have error = { rule: 'mustNotExist', actual: what, expected: `found ${what} in model` }; } done(error); }); } };
var _ = require('lodash'); module.exports = function(model) { 'use strict'; let propertyTypes = [ 'number', 'string', 'histogram', 'composition' ]; let propertyUnits = [ 'mm', 'm', 'c', 'f' ]; return { mustExist: mustExist, mustNotExist: mustNotExist, isValidPropertyType: isValidPropertyType, isValidUnit: isValidUnit }; // mustExist looks up an entry in the named table by id. If // the entry doesn't exist it returns an error. function mustExist(what, modelName, done) { model[modelName].get(what).then(function(value) { let error = null; if (!value) { error = { rule: 'mustExist', actual: what, expected: 'did not find ' + what + ' in model' }; } done(error); }); } // mustNotExist looks up an entry in the named table by the named // index. If the entry exists it returns an error. function mustNotExist(what, spec, done) { let pieces = spec.split(':'), modelName = pieces[0], modelIndex = pieces[1]; model[modelName].get(what, modelIndex).then(function(value) { let error = null; if (value) { // found a match, when we shouldn't have error = { rule: 'mustNotExist', actual: what, expected: `found ${what} in model` }; } done(error); }); } function isValidPropertyType(what, _ignore) { let invalid = { rule: 'isValidPropertyType', actual: what, expected: `type to be one of ${propertyTypes}` }; return _.indexOf(propertyTypes, what) === -1 ? invalid : null; } function isValidUnit(what, _ignore) { let invalid = { rule: 'isValidUnit', actual: what, expected: `units to be one of ${propertyUnits}` }; return _.indexOf(propertyUnits, what) === -1 ? invalid : null; } };
43
4
3
mixed
--- a/backend/server/schema/schema-rules.js +++ b/backend/server/schema/schema-rules.js @@ -1,9 +1,29 @@ +var _ = require('lodash'); module.exports = function(model) { + 'use strict'; + + let propertyTypes = [ + 'number', + 'string', + 'histogram', + 'composition' + ]; + + let propertyUnits = [ + 'mm', + 'm', + 'c', + 'f' + ]; + return { mustExist: mustExist, - mustNotExist: mustNotExist + mustNotExist: mustNotExist, + isValidPropertyType: isValidPropertyType, + isValidUnit: isValidUnit }; + // mustExist looks up an entry in the named table by id. If + // the entry doesn't exist it returns an error. function mustExist(what, modelName, done) { - 'use strict'; model[modelName].get(what).then(function(value) { @@ -21,5 +41,5 @@ + // mustNotExist looks up an entry in the named table by the named + // index. If the entry exists it returns an error. function mustNotExist(what, spec, done) { - 'use strict'; - let pieces = spec.split(':'), @@ -40,2 +60,21 @@ } + + + function isValidPropertyType(what, _ignore) { + let invalid = { + rule: 'isValidPropertyType', + actual: what, + expected: `type to be one of ${propertyTypes}` + }; + return _.indexOf(propertyTypes, what) === -1 ? invalid : null; + } + + function isValidUnit(what, _ignore) { + let invalid = { + rule: 'isValidUnit', + actual: what, + expected: `units to be one of ${propertyUnits}` + }; + return _.indexOf(propertyUnits, what) === -1 ? invalid : null; + } };
--- a/backend/server/schema/schema-rules.js +++ b/backend/server/schema/schema-rules.js @@ ... @@ +var _ = require('lodash'); module.exports = function(model) { + 'use strict'; + + let propertyTypes = [ + 'number', + 'string', + 'histogram', + 'composition' + ]; + + let propertyUnits = [ + 'mm', + 'm', + 'c', + 'f' + ]; + return { mustExist: mustExist, - mustNotExist: mustNotExist + mustNotExist: mustNotExist, + isValidPropertyType: isValidPropertyType, + isValidUnit: isValidUnit }; + // mustExist looks up an entry in the named table by id. If + // the entry doesn't exist it returns an error. function mustExist(what, modelName, done) { - 'use strict'; model[modelName].get(what).then(function(value) { @@ ... @@ + // mustNotExist looks up an entry in the named table by the named + // index. If the entry exists it returns an error. function mustNotExist(what, spec, done) { - 'use strict'; - let pieces = spec.split(':'), @@ ... @@ } + + + function isValidPropertyType(what, _ignore) { + let invalid = { + rule: 'isValidPropertyType', + actual: what, + expected: `type to be one of ${propertyTypes}` + }; + return _.indexOf(propertyTypes, what) === -1 ? invalid : null; + } + + function isValidUnit(what, _ignore) { + let invalid = { + rule: 'isValidUnit', + actual: what, + expected: `units to be one of ${propertyUnits}` + }; + return _.indexOf(propertyUnits, what) === -1 ? invalid : null; + } };
--- a/backend/server/schema/schema-rules.js +++ b/backend/server/schema/schema-rules.js @@ -1,9 +1,29 @@ ADD var _ = require('lodash'); CON module.exports = function(model) { ADD 'use strict'; ADD ADD let propertyTypes = [ ADD 'number', ADD 'string', ADD 'histogram', ADD 'composition' ADD ]; ADD ADD let propertyUnits = [ ADD 'mm', ADD 'm', ADD 'c', ADD 'f' ADD ]; ADD CON return { CON mustExist: mustExist, DEL mustNotExist: mustNotExist ADD mustNotExist: mustNotExist, ADD isValidPropertyType: isValidPropertyType, ADD isValidUnit: isValidUnit CON }; CON ADD // mustExist looks up an entry in the named table by id. If ADD // the entry doesn't exist it returns an error. CON function mustExist(what, modelName, done) { DEL 'use strict'; CON model[modelName].get(what).then(function(value) { @@ -21,5 +41,5 @@ CON ADD // mustNotExist looks up an entry in the named table by the named ADD // index. If the entry exists it returns an error. CON function mustNotExist(what, spec, done) { DEL 'use strict'; DEL CON let pieces = spec.split(':'), @@ -40,2 +60,21 @@ CON } ADD ADD ADD function isValidPropertyType(what, _ignore) { ADD let invalid = { ADD rule: 'isValidPropertyType', ADD actual: what, ADD expected: `type to be one of ${propertyTypes}` ADD }; ADD return _.indexOf(propertyTypes, what) === -1 ? invalid : null; ADD } ADD ADD function isValidUnit(what, _ignore) { ADD let invalid = { ADD rule: 'isValidUnit', ADD actual: what, ADD expected: `units to be one of ${propertyUnits}` ADD }; ADD return _.indexOf(propertyUnits, what) === -1 ? invalid : null; ADD } CON };
<<<<<<< SEARCH module.exports = function(model) { return { mustExist: mustExist, mustNotExist: mustNotExist }; function mustExist(what, modelName, done) { 'use strict'; model[modelName].get(what).then(function(value) { let error = null; ======= var _ = require('lodash'); module.exports = function(model) { 'use strict'; let propertyTypes = [ 'number', 'string', 'histogram', 'composition' ]; let propertyUnits = [ 'mm', 'm', 'c', 'f' ]; return { mustExist: mustExist, mustNotExist: mustNotExist, isValidPropertyType: isValidPropertyType, isValidUnit: isValidUnit }; // mustExist looks up an entry in the named table by id. If // the entry doesn't exist it returns an error. function mustExist(what, modelName, done) { model[modelName].get(what).then(function(value) { let error = null; >>>>>>> REPLACE <<<<<<< SEARCH } function mustNotExist(what, spec, done) { 'use strict'; let pieces = spec.split(':'), modelName = pieces[0], ======= } // mustNotExist looks up an entry in the named table by the named // index. If the entry exists it returns an error. function mustNotExist(what, spec, done) { let pieces = spec.split(':'), modelName = pieces[0], >>>>>>> REPLACE <<<<<<< SEARCH }); } }; ======= }); } function isValidPropertyType(what, _ignore) { let invalid = { rule: 'isValidPropertyType', actual: what, expected: `type to be one of ${propertyTypes}` }; return _.indexOf(propertyTypes, what) === -1 ? invalid : null; } function isValidUnit(what, _ignore) { let invalid = { rule: 'isValidUnit', actual: what, expected: `units to be one of ${propertyUnits}` }; return _.indexOf(propertyUnits, what) === -1 ? invalid : null; } }; >>>>>>> REPLACE
rsaarelm/magog
e76dafcd3c2ea1eddd0bff3d83e9394160018c24
world/src/lib.rs
rust
agpl-3.0
Remove half-baked Light type for now
#![feature(custom_derive, plugin)] #![plugin(serde_macros)] extern crate num; extern crate rand; extern crate bincode; extern crate serde; extern crate vec_map; extern crate image; extern crate euclid; extern crate vitral; extern crate vitral_atlas; extern crate calx_alg; extern crate calx_grid; extern crate calx_color; #[macro_use] extern crate calx_ecs; #[macro_use] extern crate calx_resource; mod ability; mod brush; pub use brush::{Brush, BrushBuilder, Color, Frame, ImageRef, Splat}; pub mod components; mod field; mod flags; mod fov; pub mod item; mod location; pub use location::{Location, Portal}; mod location_set; mod query; pub use query::Query; mod spatial; mod stats; pub mod terrain; mod world; pub use world::World; #[derive(Copy, Clone, Eq, PartialEq, Debug)] pub enum FovStatus { Seen, Remembered, } /// Light level value. #[derive(Copy, Clone, Debug, Serialize, Deserialize)] pub struct Light { lum: f32, } impl Light { pub fn new(lum: f32) -> Light { assert!(lum >= 0.0 && lum <= 2.0); Light { lum: lum } } pub fn apply(&self, color: calx_color::Rgba) -> calx_color::Rgba { let darkness_color = calx_color::Rgba::new(0.05, 0.10, 0.25, color.a); calx_alg::lerp(color * darkness_color, color, self.lum) } }
#![feature(custom_derive, plugin)] #![plugin(serde_macros)] extern crate num; extern crate rand; extern crate bincode; extern crate serde; extern crate vec_map; extern crate image; extern crate euclid; extern crate vitral; extern crate vitral_atlas; extern crate calx_alg; extern crate calx_grid; extern crate calx_color; #[macro_use] extern crate calx_ecs; #[macro_use] extern crate calx_resource; mod ability; mod brush; pub use brush::{Brush, BrushBuilder, Color, Frame, ImageRef, Splat}; pub mod components; mod field; mod flags; mod fov; pub mod item; mod location; pub use location::{Location, Portal}; mod location_set; mod query; pub use query::Query; mod spatial; mod stats; pub mod terrain; mod world; pub use world::World; #[derive(Copy, Clone, Eq, PartialEq, Debug)] pub enum FovStatus { Seen, Remembered, }
0
18
1
del_only
--- a/world/src/lib.rs +++ b/world/src/lib.rs @@ -51,19 +51 @@ } - -/// Light level value. -#[derive(Copy, Clone, Debug, Serialize, Deserialize)] -pub struct Light { - lum: f32, -} - -impl Light { - pub fn new(lum: f32) -> Light { - assert!(lum >= 0.0 && lum <= 2.0); - Light { lum: lum } - } - - pub fn apply(&self, color: calx_color::Rgba) -> calx_color::Rgba { - let darkness_color = calx_color::Rgba::new(0.05, 0.10, 0.25, color.a); - calx_alg::lerp(color * darkness_color, color, self.lum) - } -}
--- a/world/src/lib.rs +++ b/world/src/lib.rs @@ ... @@ } - -/// Light level value. -#[derive(Copy, Clone, Debug, Serialize, Deserialize)] -pub struct Light { - lum: f32, -} - -impl Light { - pub fn new(lum: f32) -> Light { - assert!(lum >= 0.0 && lum <= 2.0); - Light { lum: lum } - } - - pub fn apply(&self, color: calx_color::Rgba) -> calx_color::Rgba { - let darkness_color = calx_color::Rgba::new(0.05, 0.10, 0.25, color.a); - calx_alg::lerp(color * darkness_color, color, self.lum) - } -}
--- a/world/src/lib.rs +++ b/world/src/lib.rs @@ -51,19 +51 @@ CON } DEL DEL /// Light level value. DEL #[derive(Copy, Clone, Debug, Serialize, Deserialize)] DEL pub struct Light { DEL lum: f32, DEL } DEL DEL impl Light { DEL pub fn new(lum: f32) -> Light { DEL assert!(lum >= 0.0 && lum <= 2.0); DEL Light { lum: lum } DEL } DEL DEL pub fn apply(&self, color: calx_color::Rgba) -> calx_color::Rgba { DEL let darkness_color = calx_color::Rgba::new(0.05, 0.10, 0.25, color.a); DEL calx_alg::lerp(color * darkness_color, color, self.lum) DEL } DEL }
<<<<<<< SEARCH Remembered, } /// Light level value. #[derive(Copy, Clone, Debug, Serialize, Deserialize)] pub struct Light { lum: f32, } impl Light { pub fn new(lum: f32) -> Light { assert!(lum >= 0.0 && lum <= 2.0); Light { lum: lum } } pub fn apply(&self, color: calx_color::Rgba) -> calx_color::Rgba { let darkness_color = calx_color::Rgba::new(0.05, 0.10, 0.25, color.a); calx_alg::lerp(color * darkness_color, color, self.lum) } } ======= Remembered, } >>>>>>> REPLACE
duke2906/traccar
21ed9dbbd8c7be191894b11e895c1c0094b4aac6
src/org/traccar/OdometerHandler.java
java
apache-2.0
Set Odometer only if there is a movement
/** * */ package org.traccar; import org.traccar.helper.DistanceCalculator; import org.traccar.helper.Log; import org.traccar.model.Position; /** * <p> * Odometer - total mileage calculation handler * </p> * * @author Amila Silva * */ public class OdometerHandler extends BaseDataHandler { public OdometerHandler() { Log.debug("System based odometer calculation enabled for all devices"); } private Position getLastPosition(long deviceId) { if (Context.getConnectionManager() != null) { return Context.getConnectionManager().getLastPosition(deviceId); } return null; } private Position calculateDistance(Position position) { Position last = getLastPosition(position.getDeviceId()); if (last != null) { double distance = DistanceCalculator.distance( position.getLatitude(), position.getLongitude(), last.getLatitude(), last.getLongitude()); distance = Math.round((distance) * 100.0) / 100.0; double odometer = distance + last.getOdometer(); position.setOdometer(odometer); } return position; } @Override protected Position handlePosition(Position position) { return calculateDistance(position); } }
/** * */ package org.traccar; import org.traccar.helper.DistanceCalculator; import org.traccar.helper.Log; import org.traccar.model.Position; /** * <p> * Odometer - total mileage calculation handler * </p> * * @author Amila Silva * */ public class OdometerHandler extends BaseDataHandler { public OdometerHandler() { Log.debug("System based odometer calculation enabled for all devices"); } private Position getLastPosition(long deviceId) { if (Context.getConnectionManager() != null) { return Context.getConnectionManager().getLastPosition(deviceId); } return null; } private Position calculateDistance(Position position) { Position last = getLastPosition(position.getDeviceId()); if (last != null) { // set odometer only on movement double odometer = 0.0; if (last.getSpeed() == 0 && position.getSpeed() == 0) { odometer = last.getOdometer(); } else { double distance = DistanceCalculator.distance( position.getLatitude(), position.getLongitude(), last.getLatitude(), last.getLongitude()); distance = Math.round((distance) * 100.0) / 100.0; odometer = distance + last.getOdometer(); } position.setOdometer(odometer); } return position; } @Override protected Position handlePosition(Position position) { return calculateDistance(position); } }
11
5
1
mixed
--- a/src/org/traccar/OdometerHandler.java +++ b/src/org/traccar/OdometerHandler.java @@ -33,7 +33,13 @@ if (last != null) { - double distance = DistanceCalculator.distance( - position.getLatitude(), position.getLongitude(), - last.getLatitude(), last.getLongitude()); - distance = Math.round((distance) * 100.0) / 100.0; - double odometer = distance + last.getOdometer(); + // set odometer only on movement + double odometer = 0.0; + if (last.getSpeed() == 0 && position.getSpeed() == 0) { + odometer = last.getOdometer(); + } else { + double distance = DistanceCalculator.distance( + position.getLatitude(), position.getLongitude(), + last.getLatitude(), last.getLongitude()); + distance = Math.round((distance) * 100.0) / 100.0; + odometer = distance + last.getOdometer(); + } position.setOdometer(odometer);
--- a/src/org/traccar/OdometerHandler.java +++ b/src/org/traccar/OdometerHandler.java @@ ... @@ if (last != null) { - double distance = DistanceCalculator.distance( - position.getLatitude(), position.getLongitude(), - last.getLatitude(), last.getLongitude()); - distance = Math.round((distance) * 100.0) / 100.0; - double odometer = distance + last.getOdometer(); + // set odometer only on movement + double odometer = 0.0; + if (last.getSpeed() == 0 && position.getSpeed() == 0) { + odometer = last.getOdometer(); + } else { + double distance = DistanceCalculator.distance( + position.getLatitude(), position.getLongitude(), + last.getLatitude(), last.getLongitude()); + distance = Math.round((distance) * 100.0) / 100.0; + odometer = distance + last.getOdometer(); + } position.setOdometer(odometer);
--- a/src/org/traccar/OdometerHandler.java +++ b/src/org/traccar/OdometerHandler.java @@ -33,7 +33,13 @@ CON if (last != null) { DEL double distance = DistanceCalculator.distance( DEL position.getLatitude(), position.getLongitude(), DEL last.getLatitude(), last.getLongitude()); DEL distance = Math.round((distance) * 100.0) / 100.0; DEL double odometer = distance + last.getOdometer(); ADD // set odometer only on movement ADD double odometer = 0.0; ADD if (last.getSpeed() == 0 && position.getSpeed() == 0) { ADD odometer = last.getOdometer(); ADD } else { ADD double distance = DistanceCalculator.distance( ADD position.getLatitude(), position.getLongitude(), ADD last.getLatitude(), last.getLongitude()); ADD distance = Math.round((distance) * 100.0) / 100.0; ADD odometer = distance + last.getOdometer(); ADD } CON position.setOdometer(odometer);
<<<<<<< SEARCH Position last = getLastPosition(position.getDeviceId()); if (last != null) { double distance = DistanceCalculator.distance( position.getLatitude(), position.getLongitude(), last.getLatitude(), last.getLongitude()); distance = Math.round((distance) * 100.0) / 100.0; double odometer = distance + last.getOdometer(); position.setOdometer(odometer); } ======= Position last = getLastPosition(position.getDeviceId()); if (last != null) { // set odometer only on movement double odometer = 0.0; if (last.getSpeed() == 0 && position.getSpeed() == 0) { odometer = last.getOdometer(); } else { double distance = DistanceCalculator.distance( position.getLatitude(), position.getLongitude(), last.getLatitude(), last.getLongitude()); distance = Math.round((distance) * 100.0) / 100.0; odometer = distance + last.getOdometer(); } position.setOdometer(odometer); } >>>>>>> REPLACE
martica/rusty
e05770738c050e4d464bdb929b1a03baa77c564a
rusty.rs
rust
mit
Add more tests to tokenize
extern mod std; #[test] fn test_tokenize() { assert tokenize( ~"(1 2 3)" ) == ~[~"(", ~"1", ~"2", ~"3", ~")"]; } #[test] fn test_addspaces() { assert addspaces( ~"(1 2 3)" ) == ~" ( 1 2 3 ) " } fn addspaces( input:&str ) -> ~str { str::replace(str::replace(input, ")", " ) "), "(", " ( ") } fn tokenize( input:&str ) -> ~[~str] { str::split_str_nonempty(addspaces(input), " ") } enum Expression { Value(int), Symbol(~str), List(~[Expression]) } fn main() { let Blah:Expression = List(~[Value(1), List(~[Value(1), Symbol(~"xyz")])]); io::println( "(begin 1 2)" ) }
extern mod std; #[test] fn test_tokenize() { assert tokenize( ~"(1 2 3)" ) == ~[~"(", ~"1", ~"2", ~"3", ~")"]; } #[test] fn test_tokenize_empty() { assert tokenize( ~"" ) == ~[]; } #[test] fn test_tokenize_no_spaces() { assert tokenize( ~"one" ) == ~[~"one"]; } #[test] fn test_addspaces() { assert addspaces( ~"(1 2 3)" ) == ~" ( 1 2 3 ) " } fn addspaces( input:&str ) -> ~str { str::replace(str::replace(input, ")", " ) "), "(", " ( ") } fn tokenize( input:&str ) -> ~[~str] { str::split_str_nonempty(addspaces(input), " ") } enum Expression { Value(int), Symbol(~str), List(~[Expression]) } fn main() { let Blah:Expression = List(~[Value(1), List(~[Value(1), Symbol(~"xyz")])]); io::println( "(begin 1 2)" ) }
10
0
1
add_only
--- a/rusty.rs +++ b/rusty.rs @@ -5,2 +5,12 @@ assert tokenize( ~"(1 2 3)" ) == ~[~"(", ~"1", ~"2", ~"3", ~")"]; +} + +#[test] +fn test_tokenize_empty() { + assert tokenize( ~"" ) == ~[]; +} + +#[test] +fn test_tokenize_no_spaces() { + assert tokenize( ~"one" ) == ~[~"one"]; }
--- a/rusty.rs +++ b/rusty.rs @@ ... @@ assert tokenize( ~"(1 2 3)" ) == ~[~"(", ~"1", ~"2", ~"3", ~")"]; +} + +#[test] +fn test_tokenize_empty() { + assert tokenize( ~"" ) == ~[]; +} + +#[test] +fn test_tokenize_no_spaces() { + assert tokenize( ~"one" ) == ~[~"one"]; }
--- a/rusty.rs +++ b/rusty.rs @@ -5,2 +5,12 @@ CON assert tokenize( ~"(1 2 3)" ) == ~[~"(", ~"1", ~"2", ~"3", ~")"]; ADD } ADD ADD #[test] ADD fn test_tokenize_empty() { ADD assert tokenize( ~"" ) == ~[]; ADD } ADD ADD #[test] ADD fn test_tokenize_no_spaces() { ADD assert tokenize( ~"one" ) == ~[~"one"]; CON }
<<<<<<< SEARCH fn test_tokenize() { assert tokenize( ~"(1 2 3)" ) == ~[~"(", ~"1", ~"2", ~"3", ~")"]; } ======= fn test_tokenize() { assert tokenize( ~"(1 2 3)" ) == ~[~"(", ~"1", ~"2", ~"3", ~")"]; } #[test] fn test_tokenize_empty() { assert tokenize( ~"" ) == ~[]; } #[test] fn test_tokenize_no_spaces() { assert tokenize( ~"one" ) == ~[~"one"]; } >>>>>>> REPLACE
edx-solutions/edx-platform
770781d3ce55a91926b91579e11d79ebb3edf47e
lms/djangoapps/api_manager/management/commands/migrate_orgdata.py
python
agpl-3.0
Tweak to migration in order to accomodate old names for data fields and allow for if data fields were not present
import json from django.contrib.auth.models import Group from django.core.management.base import BaseCommand from api_manager.models import GroupProfile, Organization class Command(BaseCommand): """ Migrates legacy organization data and user relationships from older Group model approach to newer concrete Organization model """ def handle(self, *args, **options): org_groups = GroupProfile.objects.filter(group_type='organization') for org in org_groups: data = json.loads(org.data) migrated_org = Organization.objects.create( name=data['name'], display_name=data['display_name'], contact_name=data['contact_name'], contact_email=data['contact_email'], contact_phone=data['contact_phone'] ) group = Group.objects.get(groupprofile=org.id) users = group.user_set.all() for user in users: migrated_org.users.add(user) linked_groups = group.grouprelationship.get_linked_group_relationships() for linked_group in linked_groups: if linked_group.to_group_relationship_id is not org.id: # Don't need to carry the symmetrical component actual_group = Group.objects.get(id=linked_group.to_group_relationship_id) migrated_org.groups.add(actual_group)
import json from django.contrib.auth.models import Group from django.core.management.base import BaseCommand from api_manager.models import GroupProfile, Organization class Command(BaseCommand): """ Migrates legacy organization data and user relationships from older Group model approach to newer concrete Organization model """ def handle(self, *args, **options): org_groups = GroupProfile.objects.filter(group_type='organization') for org in org_groups: data = json.loads(org.data) name = org.name display_name = data.get('display_name', name) contact_name = data.get('contact_name', None) contact_email = data.get('email', None) if contact_email is None: contact_email = data.get('contact_email', None) contact_phone = data.get('phone', None) if contact_phone is None: contact_phone = data.get('contact_phone', None) migrated_org = Organization.objects.create( name=name, display_name=display_name, contact_name=contact_name, contact_email=contact_email, contact_phone=contact_phone ) group = Group.objects.get(groupprofile=org.id) users = group.user_set.all() for user in users: migrated_org.users.add(user) linked_groups = group.grouprelationship.get_linked_group_relationships() for linked_group in linked_groups: if linked_group.to_group_relationship_id is not org.id: # Don't need to carry the symmetrical component actual_group = Group.objects.get(id=linked_group.to_group_relationship_id) migrated_org.groups.add(actual_group)
16
5
1
mixed
--- a/lms/djangoapps/api_manager/management/commands/migrate_orgdata.py +++ b/lms/djangoapps/api_manager/management/commands/migrate_orgdata.py @@ -18,8 +18,19 @@ data = json.loads(org.data) + + name = org.name + display_name = data.get('display_name', name) + contact_name = data.get('contact_name', None) + contact_email = data.get('email', None) + if contact_email is None: + contact_email = data.get('contact_email', None) + contact_phone = data.get('phone', None) + if contact_phone is None: + contact_phone = data.get('contact_phone', None) + migrated_org = Organization.objects.create( - name=data['name'], - display_name=data['display_name'], - contact_name=data['contact_name'], - contact_email=data['contact_email'], - contact_phone=data['contact_phone'] + name=name, + display_name=display_name, + contact_name=contact_name, + contact_email=contact_email, + contact_phone=contact_phone )
--- a/lms/djangoapps/api_manager/management/commands/migrate_orgdata.py +++ b/lms/djangoapps/api_manager/management/commands/migrate_orgdata.py @@ ... @@ data = json.loads(org.data) + + name = org.name + display_name = data.get('display_name', name) + contact_name = data.get('contact_name', None) + contact_email = data.get('email', None) + if contact_email is None: + contact_email = data.get('contact_email', None) + contact_phone = data.get('phone', None) + if contact_phone is None: + contact_phone = data.get('contact_phone', None) + migrated_org = Organization.objects.create( - name=data['name'], - display_name=data['display_name'], - contact_name=data['contact_name'], - contact_email=data['contact_email'], - contact_phone=data['contact_phone'] + name=name, + display_name=display_name, + contact_name=contact_name, + contact_email=contact_email, + contact_phone=contact_phone )
--- a/lms/djangoapps/api_manager/management/commands/migrate_orgdata.py +++ b/lms/djangoapps/api_manager/management/commands/migrate_orgdata.py @@ -18,8 +18,19 @@ CON data = json.loads(org.data) ADD ADD name = org.name ADD display_name = data.get('display_name', name) ADD contact_name = data.get('contact_name', None) ADD contact_email = data.get('email', None) ADD if contact_email is None: ADD contact_email = data.get('contact_email', None) ADD contact_phone = data.get('phone', None) ADD if contact_phone is None: ADD contact_phone = data.get('contact_phone', None) ADD CON migrated_org = Organization.objects.create( DEL name=data['name'], DEL display_name=data['display_name'], DEL contact_name=data['contact_name'], DEL contact_email=data['contact_email'], DEL contact_phone=data['contact_phone'] ADD name=name, ADD display_name=display_name, ADD contact_name=contact_name, ADD contact_email=contact_email, ADD contact_phone=contact_phone CON )
<<<<<<< SEARCH for org in org_groups: data = json.loads(org.data) migrated_org = Organization.objects.create( name=data['name'], display_name=data['display_name'], contact_name=data['contact_name'], contact_email=data['contact_email'], contact_phone=data['contact_phone'] ) group = Group.objects.get(groupprofile=org.id) ======= for org in org_groups: data = json.loads(org.data) name = org.name display_name = data.get('display_name', name) contact_name = data.get('contact_name', None) contact_email = data.get('email', None) if contact_email is None: contact_email = data.get('contact_email', None) contact_phone = data.get('phone', None) if contact_phone is None: contact_phone = data.get('contact_phone', None) migrated_org = Organization.objects.create( name=name, display_name=display_name, contact_name=contact_name, contact_email=contact_email, contact_phone=contact_phone ) group = Group.objects.get(groupprofile=org.id) >>>>>>> REPLACE
kpi-ua/ecampus-client-android
4b60a2ecdcd911f30d9b5bf408ae6e272220367f
app/src/main/java/com/goldenpiedevs/schedule/app/core/api/lessons/LessonsManager.kt
kotlin
apache-2.0
Save only days with lessons
package com.goldenpiedevs.schedule.app.core.api.lessons import com.goldenpiedevs.schedule.app.core.dao.BaseResponseModel import com.goldenpiedevs.schedule.app.core.dao.timetable.DaoWeekModel import com.goldenpiedevs.schedule.app.core.dao.timetable.TimeTableData import io.realm.Realm import io.realm.RealmList import kotlinx.coroutines.experimental.Deferred import kotlinx.coroutines.experimental.async import retrofit2.Response class LessonsManager(private val lessonsService: LessonsService) { fun loadTimeTable(groupId: Int?): Deferred<Response<BaseResponseModel<TimeTableData>>> = async { val response = lessonsService.getGroupTimeTable(groupId).await() if (response.isSuccessful) { var realm = Realm.getDefaultInstance() realm.executeTransaction { it.copyToRealmOrUpdate(listOf(response.body()!!.data!!.weeks!!.firstWeekModel!!, response.body()!!.data!!.weeks!!.secondWeekModel!!) .map { val daoWeekModel = DaoWeekModel() daoWeekModel.weekNumber = it.weekNumber daoWeekModel.days = RealmList() daoWeekModel.days.addAll(it.daysMap!!.entries.map { it.value }) daoWeekModel }) } if(!realm.isClosed) realm.close() } response } }
package com.goldenpiedevs.schedule.app.core.api.lessons import com.goldenpiedevs.schedule.app.core.dao.BaseResponseModel import com.goldenpiedevs.schedule.app.core.dao.timetable.DaoWeekModel import com.goldenpiedevs.schedule.app.core.dao.timetable.TimeTableData import io.realm.Realm import io.realm.RealmList import kotlinx.coroutines.experimental.Deferred import kotlinx.coroutines.experimental.async import retrofit2.Response class LessonsManager(private val lessonsService: LessonsService) { fun loadTimeTable(groupId: Int?): Deferred<Response<BaseResponseModel<TimeTableData>>> = async { val response = lessonsService.getGroupTimeTable(groupId).await() if (response.isSuccessful) { val realm = Realm.getDefaultInstance() realm.executeTransaction { transaction -> transaction.copyToRealmOrUpdate(listOf(response.body()!!.data!!.weeks!!.firstWeekModel!!, response.body()!!.data!!.weeks!!.secondWeekModel!!) .map { map -> val daoWeekModel = DaoWeekModel() daoWeekModel.weekNumber = map.weekNumber daoWeekModel.days = RealmList() daoWeekModel.days.addAll(map.daysMap!!.entries .filter { !it.value.lessons.isEmpty() } .map { it.value }) daoWeekModel }) } if (!realm.isClosed) realm.close() } response } }
9
7
2
mixed
--- a/app/src/main/java/com/goldenpiedevs/schedule/app/core/api/lessons/LessonsManager.kt +++ b/app/src/main/java/com/goldenpiedevs/schedule/app/core/api/lessons/LessonsManager.kt @@ -16,13 +16,15 @@ if (response.isSuccessful) { - var realm = Realm.getDefaultInstance() + val realm = Realm.getDefaultInstance() - realm.executeTransaction { - it.copyToRealmOrUpdate(listOf(response.body()!!.data!!.weeks!!.firstWeekModel!!, + realm.executeTransaction { transaction -> + transaction.copyToRealmOrUpdate(listOf(response.body()!!.data!!.weeks!!.firstWeekModel!!, response.body()!!.data!!.weeks!!.secondWeekModel!!) - .map { + .map { map -> val daoWeekModel = DaoWeekModel() - daoWeekModel.weekNumber = it.weekNumber + daoWeekModel.weekNumber = map.weekNumber daoWeekModel.days = RealmList() - daoWeekModel.days.addAll(it.daysMap!!.entries.map { it.value }) + daoWeekModel.days.addAll(map.daysMap!!.entries + .filter { !it.value.lessons.isEmpty() } + .map { it.value }) @@ -32,3 +34,3 @@ - if(!realm.isClosed) + if (!realm.isClosed) realm.close()
--- a/app/src/main/java/com/goldenpiedevs/schedule/app/core/api/lessons/LessonsManager.kt +++ b/app/src/main/java/com/goldenpiedevs/schedule/app/core/api/lessons/LessonsManager.kt @@ ... @@ if (response.isSuccessful) { - var realm = Realm.getDefaultInstance() + val realm = Realm.getDefaultInstance() - realm.executeTransaction { - it.copyToRealmOrUpdate(listOf(response.body()!!.data!!.weeks!!.firstWeekModel!!, + realm.executeTransaction { transaction -> + transaction.copyToRealmOrUpdate(listOf(response.body()!!.data!!.weeks!!.firstWeekModel!!, response.body()!!.data!!.weeks!!.secondWeekModel!!) - .map { + .map { map -> val daoWeekModel = DaoWeekModel() - daoWeekModel.weekNumber = it.weekNumber + daoWeekModel.weekNumber = map.weekNumber daoWeekModel.days = RealmList() - daoWeekModel.days.addAll(it.daysMap!!.entries.map { it.value }) + daoWeekModel.days.addAll(map.daysMap!!.entries + .filter { !it.value.lessons.isEmpty() } + .map { it.value }) @@ ... @@ - if(!realm.isClosed) + if (!realm.isClosed) realm.close()
--- a/app/src/main/java/com/goldenpiedevs/schedule/app/core/api/lessons/LessonsManager.kt +++ b/app/src/main/java/com/goldenpiedevs/schedule/app/core/api/lessons/LessonsManager.kt @@ -16,13 +16,15 @@ CON if (response.isSuccessful) { DEL var realm = Realm.getDefaultInstance() ADD val realm = Realm.getDefaultInstance() CON DEL realm.executeTransaction { DEL it.copyToRealmOrUpdate(listOf(response.body()!!.data!!.weeks!!.firstWeekModel!!, ADD realm.executeTransaction { transaction -> ADD transaction.copyToRealmOrUpdate(listOf(response.body()!!.data!!.weeks!!.firstWeekModel!!, CON response.body()!!.data!!.weeks!!.secondWeekModel!!) DEL .map { ADD .map { map -> CON val daoWeekModel = DaoWeekModel() DEL daoWeekModel.weekNumber = it.weekNumber ADD daoWeekModel.weekNumber = map.weekNumber CON CON daoWeekModel.days = RealmList() DEL daoWeekModel.days.addAll(it.daysMap!!.entries.map { it.value }) ADD daoWeekModel.days.addAll(map.daysMap!!.entries ADD .filter { !it.value.lessons.isEmpty() } ADD .map { it.value }) CON @@ -32,3 +34,3 @@ CON DEL if(!realm.isClosed) ADD if (!realm.isClosed) CON realm.close()
<<<<<<< SEARCH if (response.isSuccessful) { var realm = Realm.getDefaultInstance() realm.executeTransaction { it.copyToRealmOrUpdate(listOf(response.body()!!.data!!.weeks!!.firstWeekModel!!, response.body()!!.data!!.weeks!!.secondWeekModel!!) .map { val daoWeekModel = DaoWeekModel() daoWeekModel.weekNumber = it.weekNumber daoWeekModel.days = RealmList() daoWeekModel.days.addAll(it.daysMap!!.entries.map { it.value }) daoWeekModel }) } if(!realm.isClosed) realm.close() } ======= if (response.isSuccessful) { val realm = Realm.getDefaultInstance() realm.executeTransaction { transaction -> transaction.copyToRealmOrUpdate(listOf(response.body()!!.data!!.weeks!!.firstWeekModel!!, response.body()!!.data!!.weeks!!.secondWeekModel!!) .map { map -> val daoWeekModel = DaoWeekModel() daoWeekModel.weekNumber = map.weekNumber daoWeekModel.days = RealmList() daoWeekModel.days.addAll(map.daysMap!!.entries .filter { !it.value.lessons.isEmpty() } .map { it.value }) daoWeekModel }) } if (!realm.isClosed) realm.close() } >>>>>>> REPLACE
adsabs/adsabs-pyingest
c143bc14be8d486d313056c0d1313e03ac438284
examples/ex_aps_parser.py
python
mit
Use open mode syntax on example file
from __future__ import print_function import os import glob import pyingest.parsers.aps as aps import pyingest.parsers.arxiv as arxiv import pyingest.serializers.classic import traceback import json import xmltodict from datetime import datetime input_list = 'bibc.2.out' testfile=[] xmldir = '/proj/ads/fulltext/sources/downloads/cache/APS_HARVEST/harvest.aps.org/v2/journals/articles/' xmltail = '/fulltext.xml' with open(input_list,'rU') as fi: for l in fi.readlines(): doi = l.strip().split('\t')[1] (a,b) = doi.split('/') b = b.replace('.','/') infile = xmldir + a + '/' + b + xmltail testfile.append(infile) for f in testfile: fnord = f[92:] if os.path.isfile(f): print("found! ",fnord) with open(f, 'rU') as fp: parser = aps.APSJATSParser() document = parser.parse(fp) serializer = pyingest.serializers.classic.Tagged() outputfp = open('aps.tag', 'a') serializer.write(document, outputfp) outputfp.close() #except: # print "ERROR!\n%s\n"%f # traceback.print_exc() # pass else: print("not found :( ", fnord)
from __future__ import print_function import os import glob import pyingest.parsers.aps as aps import pyingest.parsers.arxiv as arxiv import pyingest.serializers.classic import traceback import json import xmltodict from datetime import datetime import sys input_list = 'bibc.2.out' testfile=[] xmldir = '/proj/ads/fulltext/sources/downloads/cache/APS_HARVEST/harvest.aps.org/v2/journals/articles/' xmltail = '/fulltext.xml' if sys.version_info > (3,): open_mode = 'r' else: open_mode = 'rU' with open(input_list, open_mode) as fi: for l in fi.readlines(): doi = l.strip().split('\t')[1] (a,b) = doi.split('/') b = b.replace('.', '/') infile = xmldir + a + '/' + b + xmltail testfile.append(infile) for f in testfile: fnord = f[92:] if os.path.isfile(f): print("found! ", fnord) with open(f, open_mode) as fp: parser = aps.APSJATSParser() document = parser.parse(fp) serializer = pyingest.serializers.classic.Tagged() outputfp = open('aps.tag', 'a') serializer.write(document, outputfp) outputfp.close() #except: # print "ERROR!\n%s\n"%f # traceback.print_exc() # pass else: print("not found :( ", fnord)
11
4
4
mixed
--- a/examples/ex_aps_parser.py +++ b/examples/ex_aps_parser.py @@ -10,2 +10,3 @@ from datetime import datetime +import sys @@ -15,3 +16,9 @@ xmltail = '/fulltext.xml' -with open(input_list,'rU') as fi: + +if sys.version_info > (3,): + open_mode = 'r' +else: + open_mode = 'rU' + +with open(input_list, open_mode) as fi: for l in fi.readlines(): @@ -19,3 +26,3 @@ (a,b) = doi.split('/') - b = b.replace('.','/') + b = b.replace('.', '/') infile = xmldir + a + '/' + b + xmltail @@ -26,4 +33,4 @@ if os.path.isfile(f): - print("found! ",fnord) - with open(f, 'rU') as fp: + print("found! ", fnord) + with open(f, open_mode) as fp: parser = aps.APSJATSParser()
--- a/examples/ex_aps_parser.py +++ b/examples/ex_aps_parser.py @@ ... @@ from datetime import datetime +import sys @@ ... @@ xmltail = '/fulltext.xml' -with open(input_list,'rU') as fi: + +if sys.version_info > (3,): + open_mode = 'r' +else: + open_mode = 'rU' + +with open(input_list, open_mode) as fi: for l in fi.readlines(): @@ ... @@ (a,b) = doi.split('/') - b = b.replace('.','/') + b = b.replace('.', '/') infile = xmldir + a + '/' + b + xmltail @@ ... @@ if os.path.isfile(f): - print("found! ",fnord) - with open(f, 'rU') as fp: + print("found! ", fnord) + with open(f, open_mode) as fp: parser = aps.APSJATSParser()
--- a/examples/ex_aps_parser.py +++ b/examples/ex_aps_parser.py @@ -10,2 +10,3 @@ CON from datetime import datetime ADD import sys CON @@ -15,3 +16,9 @@ CON xmltail = '/fulltext.xml' DEL with open(input_list,'rU') as fi: ADD ADD if sys.version_info > (3,): ADD open_mode = 'r' ADD else: ADD open_mode = 'rU' ADD ADD with open(input_list, open_mode) as fi: CON for l in fi.readlines(): @@ -19,3 +26,3 @@ CON (a,b) = doi.split('/') DEL b = b.replace('.','/') ADD b = b.replace('.', '/') CON infile = xmldir + a + '/' + b + xmltail @@ -26,4 +33,4 @@ CON if os.path.isfile(f): DEL print("found! ",fnord) DEL with open(f, 'rU') as fp: ADD print("found! ", fnord) ADD with open(f, open_mode) as fp: CON parser = aps.APSJATSParser()
<<<<<<< SEARCH import xmltodict from datetime import datetime input_list = 'bibc.2.out' testfile=[] xmldir = '/proj/ads/fulltext/sources/downloads/cache/APS_HARVEST/harvest.aps.org/v2/journals/articles/' xmltail = '/fulltext.xml' with open(input_list,'rU') as fi: for l in fi.readlines(): doi = l.strip().split('\t')[1] (a,b) = doi.split('/') b = b.replace('.','/') infile = xmldir + a + '/' + b + xmltail testfile.append(infile) ======= import xmltodict from datetime import datetime import sys input_list = 'bibc.2.out' testfile=[] xmldir = '/proj/ads/fulltext/sources/downloads/cache/APS_HARVEST/harvest.aps.org/v2/journals/articles/' xmltail = '/fulltext.xml' if sys.version_info > (3,): open_mode = 'r' else: open_mode = 'rU' with open(input_list, open_mode) as fi: for l in fi.readlines(): doi = l.strip().split('\t')[1] (a,b) = doi.split('/') b = b.replace('.', '/') infile = xmldir + a + '/' + b + xmltail testfile.append(infile) >>>>>>> REPLACE <<<<<<< SEARCH fnord = f[92:] if os.path.isfile(f): print("found! ",fnord) with open(f, 'rU') as fp: parser = aps.APSJATSParser() document = parser.parse(fp) ======= fnord = f[92:] if os.path.isfile(f): print("found! ", fnord) with open(f, open_mode) as fp: parser = aps.APSJATSParser() document = parser.parse(fp) >>>>>>> REPLACE
mudge/oplog
053480b4e8292fe16a3271f9af568e810461d168
src/main.rs
rust
unknown
Implement an Iterator abstraction over the oplog
extern crate bson; extern crate mongodb; use mongodb::{Client, ThreadedClient}; use mongodb::db::ThreadedDatabase; use mongodb::coll::options::{FindOptions, CursorType}; fn main() { let client = Client::connect("localhost", 27017) .ok().expect("Failed to connect to MongoDB."); let coll = client.db("local").collection("oplog.rs"); let mut opts = FindOptions::new(); opts.cursor_type = CursorType::TailableAwait; opts.no_cursor_timeout = true; let mut cursor = coll.find(None, Some(opts)).expect("Failed to execute find"); loop { if let Some(Ok(doc)) = cursor.next() { println!("{}", doc); } } }
extern crate bson; extern crate mongodb; use mongodb::{Client, ThreadedClient}; use mongodb::cursor::Cursor; use mongodb::db::ThreadedDatabase; use mongodb::coll::options::{FindOptions, CursorType}; struct Oplog { cursor: Cursor, } impl Iterator for Oplog { type Item = bson::Document; fn next(&mut self) -> Option<bson::Document> { loop { if let Some(Ok(op)) = self.cursor.next() { return Some(op); } } } } fn oplog(client: Client) -> Oplog { let coll = client.db("local").collection("oplog.rs"); let mut opts = FindOptions::new(); opts.cursor_type = CursorType::TailableAwait; opts.no_cursor_timeout = true; let cursor = coll.find(None, Some(opts)).expect("Failed to execute find"); Oplog { cursor: cursor } } fn main() { let client = Client::connect("localhost", 27017) .ok().expect("Failed to connect to MongoDB."); for doc in oplog(client) { println!("{}", doc); } }
27
8
3
mixed
--- a/src/main.rs +++ b/src/main.rs @@ -4,2 +4,3 @@ use mongodb::{Client, ThreadedClient}; +use mongodb::cursor::Cursor; use mongodb::db::ThreadedDatabase; @@ -7,6 +8,19 @@ -fn main() { - let client = Client::connect("localhost", 27017) - .ok().expect("Failed to connect to MongoDB."); +struct Oplog { + cursor: Cursor, +} +impl Iterator for Oplog { + type Item = bson::Document; + + fn next(&mut self) -> Option<bson::Document> { + loop { + if let Some(Ok(op)) = self.cursor.next() { + return Some(op); + } + } + } +} + +fn oplog(client: Client) -> Oplog { let coll = client.db("local").collection("oplog.rs"); @@ -17,8 +31,13 @@ - let mut cursor = coll.find(None, Some(opts)).expect("Failed to execute find"); + let cursor = coll.find(None, Some(opts)).expect("Failed to execute find"); - loop { - if let Some(Ok(doc)) = cursor.next() { - println!("{}", doc); - } + Oplog { cursor: cursor } +} + +fn main() { + let client = Client::connect("localhost", 27017) + .ok().expect("Failed to connect to MongoDB."); + + for doc in oplog(client) { + println!("{}", doc); }
--- a/src/main.rs +++ b/src/main.rs @@ ... @@ use mongodb::{Client, ThreadedClient}; +use mongodb::cursor::Cursor; use mongodb::db::ThreadedDatabase; @@ ... @@ -fn main() { - let client = Client::connect("localhost", 27017) - .ok().expect("Failed to connect to MongoDB."); +struct Oplog { + cursor: Cursor, +} +impl Iterator for Oplog { + type Item = bson::Document; + + fn next(&mut self) -> Option<bson::Document> { + loop { + if let Some(Ok(op)) = self.cursor.next() { + return Some(op); + } + } + } +} + +fn oplog(client: Client) -> Oplog { let coll = client.db("local").collection("oplog.rs"); @@ ... @@ - let mut cursor = coll.find(None, Some(opts)).expect("Failed to execute find"); + let cursor = coll.find(None, Some(opts)).expect("Failed to execute find"); - loop { - if let Some(Ok(doc)) = cursor.next() { - println!("{}", doc); - } + Oplog { cursor: cursor } +} + +fn main() { + let client = Client::connect("localhost", 27017) + .ok().expect("Failed to connect to MongoDB."); + + for doc in oplog(client) { + println!("{}", doc); }
--- a/src/main.rs +++ b/src/main.rs @@ -4,2 +4,3 @@ CON use mongodb::{Client, ThreadedClient}; ADD use mongodb::cursor::Cursor; CON use mongodb::db::ThreadedDatabase; @@ -7,6 +8,19 @@ CON DEL fn main() { DEL let client = Client::connect("localhost", 27017) DEL .ok().expect("Failed to connect to MongoDB."); ADD struct Oplog { ADD cursor: Cursor, ADD } CON ADD impl Iterator for Oplog { ADD type Item = bson::Document; ADD ADD fn next(&mut self) -> Option<bson::Document> { ADD loop { ADD if let Some(Ok(op)) = self.cursor.next() { ADD return Some(op); ADD } ADD } ADD } ADD } ADD ADD fn oplog(client: Client) -> Oplog { CON let coll = client.db("local").collection("oplog.rs"); @@ -17,8 +31,13 @@ CON DEL let mut cursor = coll.find(None, Some(opts)).expect("Failed to execute find"); ADD let cursor = coll.find(None, Some(opts)).expect("Failed to execute find"); CON DEL loop { DEL if let Some(Ok(doc)) = cursor.next() { DEL println!("{}", doc); DEL } ADD Oplog { cursor: cursor } ADD } ADD ADD fn main() { ADD let client = Client::connect("localhost", 27017) ADD .ok().expect("Failed to connect to MongoDB."); ADD ADD for doc in oplog(client) { ADD println!("{}", doc); CON }
<<<<<<< SEARCH use mongodb::{Client, ThreadedClient}; use mongodb::db::ThreadedDatabase; use mongodb::coll::options::{FindOptions, CursorType}; fn main() { let client = Client::connect("localhost", 27017) .ok().expect("Failed to connect to MongoDB."); let coll = client.db("local").collection("oplog.rs"); ======= use mongodb::{Client, ThreadedClient}; use mongodb::cursor::Cursor; use mongodb::db::ThreadedDatabase; use mongodb::coll::options::{FindOptions, CursorType}; struct Oplog { cursor: Cursor, } impl Iterator for Oplog { type Item = bson::Document; fn next(&mut self) -> Option<bson::Document> { loop { if let Some(Ok(op)) = self.cursor.next() { return Some(op); } } } } fn oplog(client: Client) -> Oplog { let coll = client.db("local").collection("oplog.rs"); >>>>>>> REPLACE <<<<<<< SEARCH opts.no_cursor_timeout = true; let mut cursor = coll.find(None, Some(opts)).expect("Failed to execute find"); loop { if let Some(Ok(doc)) = cursor.next() { println!("{}", doc); } } } ======= opts.no_cursor_timeout = true; let cursor = coll.find(None, Some(opts)).expect("Failed to execute find"); Oplog { cursor: cursor } } fn main() { let client = Client::connect("localhost", 27017) .ok().expect("Failed to connect to MongoDB."); for doc in oplog(client) { println!("{}", doc); } } >>>>>>> REPLACE
bash/radium
a3fcb3f9467fbec459d0487e7bc9b0d208b97346
src/radium_protocol/src/message.rs
rust
mit
Move write_to to trait implementation
use std::io; use byteorder::WriteBytesExt; use super::{MessageType, WriteTo}; use super::messages::{AddEntry, EntryExpired, Entry, RemoveEntry}; pub enum Message { Ping, AddEntry(AddEntry), RemoveEntry(RemoveEntry), EntryExpired(EntryExpired), #[doc(hidden)] __NonExhaustive, } impl Message { pub fn message_type(&self) -> MessageType { match self { &Message::Ping => MessageType::Ping, &Message::AddEntry(_) => MessageType::AddEntry, &Message::RemoveEntry(_) => MessageType::RemoveEntry, _ => panic!("invalid Message") } } pub fn is_command(&self) -> bool { self.message_type().is_command() } pub fn write_to<W: io::Write>(&self, target: &mut W) -> io::Result<()> { target.write_u8(self.message_type().into())?; match self { &Message::Ping => Ok(()), &Message::RemoveEntry(ref cmd) => cmd.write_to(target), &Message::AddEntry(ref cmd) => cmd.write_to(target), _ => panic!("invalid Message") } } } #[cfg(test)] mod test { use super::*; #[test] fn test_ping() { let cmd = Message::Ping; let mut vec = Vec::new(); assert!(cmd.write_to(&mut vec).is_ok()); assert_eq!(vec![0], vec); } }
use std::io; use byteorder::WriteBytesExt; use super::{MessageType, WriteTo}; use super::messages::{AddEntry, EntryExpired, RemoveEntry}; pub enum Message { Ping, AddEntry(AddEntry), RemoveEntry(RemoveEntry), EntryExpired(EntryExpired), #[doc(hidden)] __NonExhaustive, } impl Message { pub fn message_type(&self) -> MessageType { match self { &Message::Ping => MessageType::Ping, &Message::AddEntry(_) => MessageType::AddEntry, &Message::RemoveEntry(_) => MessageType::RemoveEntry, &Message::EntryExpired(_) => MessageType::EntryExpired, _ => panic!("invalid Message") } } pub fn is_command(&self) -> bool { self.message_type().is_command() } } impl WriteTo for Message { fn write_to<W: io::Write>(&self, target: &mut W) -> io::Result<()> { target.write_u8(self.message_type().into())?; match self { &Message::Ping => Ok(()), &Message::RemoveEntry(ref msg) => msg.write_to(target), &Message::AddEntry(ref msg) => msg.write_to(target), &Message::EntryExpired(ref msg) => msg.write_to(target), _ => panic!("invalid Message") } } } #[cfg(test)] mod test { use super::*; #[test] fn test_ping() { let cmd = Message::Ping; let mut vec = Vec::new(); assert!(cmd.write_to(&mut vec).is_ok()); assert_eq!(vec![0], vec); } }
8
4
4
mixed
--- a/src/radium_protocol/src/message.rs +++ b/src/radium_protocol/src/message.rs @@ -3,3 +3,3 @@ use super::{MessageType, WriteTo}; -use super::messages::{AddEntry, EntryExpired, Entry, RemoveEntry}; +use super::messages::{AddEntry, EntryExpired, RemoveEntry}; @@ -20,2 +20,3 @@ &Message::RemoveEntry(_) => MessageType::RemoveEntry, + &Message::EntryExpired(_) => MessageType::EntryExpired, _ => panic!("invalid Message") @@ -27,4 +28,6 @@ } +} - pub fn write_to<W: io::Write>(&self, target: &mut W) -> io::Result<()> { +impl WriteTo for Message { + fn write_to<W: io::Write>(&self, target: &mut W) -> io::Result<()> { target.write_u8(self.message_type().into())?; @@ -33,4 +36,5 @@ &Message::Ping => Ok(()), - &Message::RemoveEntry(ref cmd) => cmd.write_to(target), - &Message::AddEntry(ref cmd) => cmd.write_to(target), + &Message::RemoveEntry(ref msg) => msg.write_to(target), + &Message::AddEntry(ref msg) => msg.write_to(target), + &Message::EntryExpired(ref msg) => msg.write_to(target), _ => panic!("invalid Message")
--- a/src/radium_protocol/src/message.rs +++ b/src/radium_protocol/src/message.rs @@ ... @@ use super::{MessageType, WriteTo}; -use super::messages::{AddEntry, EntryExpired, Entry, RemoveEntry}; +use super::messages::{AddEntry, EntryExpired, RemoveEntry}; @@ ... @@ &Message::RemoveEntry(_) => MessageType::RemoveEntry, + &Message::EntryExpired(_) => MessageType::EntryExpired, _ => panic!("invalid Message") @@ ... @@ } +} - pub fn write_to<W: io::Write>(&self, target: &mut W) -> io::Result<()> { +impl WriteTo for Message { + fn write_to<W: io::Write>(&self, target: &mut W) -> io::Result<()> { target.write_u8(self.message_type().into())?; @@ ... @@ &Message::Ping => Ok(()), - &Message::RemoveEntry(ref cmd) => cmd.write_to(target), - &Message::AddEntry(ref cmd) => cmd.write_to(target), + &Message::RemoveEntry(ref msg) => msg.write_to(target), + &Message::AddEntry(ref msg) => msg.write_to(target), + &Message::EntryExpired(ref msg) => msg.write_to(target), _ => panic!("invalid Message")
--- a/src/radium_protocol/src/message.rs +++ b/src/radium_protocol/src/message.rs @@ -3,3 +3,3 @@ CON use super::{MessageType, WriteTo}; DEL use super::messages::{AddEntry, EntryExpired, Entry, RemoveEntry}; ADD use super::messages::{AddEntry, EntryExpired, RemoveEntry}; CON @@ -20,2 +20,3 @@ CON &Message::RemoveEntry(_) => MessageType::RemoveEntry, ADD &Message::EntryExpired(_) => MessageType::EntryExpired, CON _ => panic!("invalid Message") @@ -27,4 +28,6 @@ CON } ADD } CON DEL pub fn write_to<W: io::Write>(&self, target: &mut W) -> io::Result<()> { ADD impl WriteTo for Message { ADD fn write_to<W: io::Write>(&self, target: &mut W) -> io::Result<()> { CON target.write_u8(self.message_type().into())?; @@ -33,4 +36,5 @@ CON &Message::Ping => Ok(()), DEL &Message::RemoveEntry(ref cmd) => cmd.write_to(target), DEL &Message::AddEntry(ref cmd) => cmd.write_to(target), ADD &Message::RemoveEntry(ref msg) => msg.write_to(target), ADD &Message::AddEntry(ref msg) => msg.write_to(target), ADD &Message::EntryExpired(ref msg) => msg.write_to(target), CON _ => panic!("invalid Message")
<<<<<<< SEARCH use byteorder::WriteBytesExt; use super::{MessageType, WriteTo}; use super::messages::{AddEntry, EntryExpired, Entry, RemoveEntry}; pub enum Message { ======= use byteorder::WriteBytesExt; use super::{MessageType, WriteTo}; use super::messages::{AddEntry, EntryExpired, RemoveEntry}; pub enum Message { >>>>>>> REPLACE <<<<<<< SEARCH &Message::AddEntry(_) => MessageType::AddEntry, &Message::RemoveEntry(_) => MessageType::RemoveEntry, _ => panic!("invalid Message") } ======= &Message::AddEntry(_) => MessageType::AddEntry, &Message::RemoveEntry(_) => MessageType::RemoveEntry, &Message::EntryExpired(_) => MessageType::EntryExpired, _ => panic!("invalid Message") } >>>>>>> REPLACE <<<<<<< SEARCH self.message_type().is_command() } pub fn write_to<W: io::Write>(&self, target: &mut W) -> io::Result<()> { target.write_u8(self.message_type().into())?; match self { &Message::Ping => Ok(()), &Message::RemoveEntry(ref cmd) => cmd.write_to(target), &Message::AddEntry(ref cmd) => cmd.write_to(target), _ => panic!("invalid Message") } ======= self.message_type().is_command() } } impl WriteTo for Message { fn write_to<W: io::Write>(&self, target: &mut W) -> io::Result<()> { target.write_u8(self.message_type().into())?; match self { &Message::Ping => Ok(()), &Message::RemoveEntry(ref msg) => msg.write_to(target), &Message::AddEntry(ref msg) => msg.write_to(target), &Message::EntryExpired(ref msg) => msg.write_to(target), _ => panic!("invalid Message") } >>>>>>> REPLACE
im-in-space/mastodon
784712791da8c7d21afa62a3bf6a8fdac8c27a80
app/javascript/flavours/glitch/features/composer/direct_warning/index.js
javascript
agpl-3.0
[Glitch] Reword the direct message warning Port 53c2164e9c8e2538de386a526a97db187ecae470 to glitch-soc
import React from 'react'; import Motion from 'flavours/glitch/util/optional_motion'; import spring from 'react-motion/lib/spring'; import { defineMessages, FormattedMessage } from 'react-intl'; // This is the spring used with our motion. const motionSpring = spring(1, { damping: 35, stiffness: 400 }); // Messages. const messages = defineMessages({ disclaimer: { defaultMessage: 'This toot will only be visible to all the mentioned users.', id: 'compose_form.direct_message_warning', }, }); // The component. export default function ComposerDirectWarning () { return ( <Motion defaultStyle={{ opacity: 0, scaleX: 0.85, scaleY: 0.75, }} style={{ opacity: motionSpring, scaleX: motionSpring, scaleY: motionSpring, }} > {({ opacity, scaleX, scaleY }) => ( <div className='composer--warning' style={{ opacity: opacity, transform: `scale(${scaleX}, ${scaleY})`, }} > <FormattedMessage {...messages.disclaimer} /> </div> )} </Motion> ); } ComposerDirectWarning.propTypes = {};
import React from 'react'; import Motion from 'flavours/glitch/util/optional_motion'; import spring from 'react-motion/lib/spring'; import { defineMessages, FormattedMessage } from 'react-intl'; // This is the spring used with our motion. const motionSpring = spring(1, { damping: 35, stiffness: 400 }); // Messages. const messages = defineMessages({ disclaimer: { defaultMessage: 'This toot will only be sent to all the mentioned users. However, the operators of your instance and any receiving instances may see this message.', id: 'compose_form.direct_message_warning', }, }); // The component. export default function ComposerDirectWarning () { return ( <Motion defaultStyle={{ opacity: 0, scaleX: 0.85, scaleY: 0.75, }} style={{ opacity: motionSpring, scaleX: motionSpring, scaleY: motionSpring, }} > {({ opacity, scaleX, scaleY }) => ( <div className='composer--warning' style={{ opacity: opacity, transform: `scale(${scaleX}, ${scaleY})`, }} > <FormattedMessage {...messages.disclaimer} /> </div> )} </Motion> ); } ComposerDirectWarning.propTypes = {};
1
1
1
mixed
--- a/app/javascript/flavours/glitch/features/composer/direct_warning/index.js +++ b/app/javascript/flavours/glitch/features/composer/direct_warning/index.js @@ -11,3 +11,3 @@ disclaimer: { - defaultMessage: 'This toot will only be visible to all the mentioned users.', + defaultMessage: 'This toot will only be sent to all the mentioned users. However, the operators of your instance and any receiving instances may see this message.', id: 'compose_form.direct_message_warning',
--- a/app/javascript/flavours/glitch/features/composer/direct_warning/index.js +++ b/app/javascript/flavours/glitch/features/composer/direct_warning/index.js @@ ... @@ disclaimer: { - defaultMessage: 'This toot will only be visible to all the mentioned users.', + defaultMessage: 'This toot will only be sent to all the mentioned users. However, the operators of your instance and any receiving instances may see this message.', id: 'compose_form.direct_message_warning',
--- a/app/javascript/flavours/glitch/features/composer/direct_warning/index.js +++ b/app/javascript/flavours/glitch/features/composer/direct_warning/index.js @@ -11,3 +11,3 @@ CON disclaimer: { DEL defaultMessage: 'This toot will only be visible to all the mentioned users.', ADD defaultMessage: 'This toot will only be sent to all the mentioned users. However, the operators of your instance and any receiving instances may see this message.', CON id: 'compose_form.direct_message_warning',
<<<<<<< SEARCH const messages = defineMessages({ disclaimer: { defaultMessage: 'This toot will only be visible to all the mentioned users.', id: 'compose_form.direct_message_warning', }, ======= const messages = defineMessages({ disclaimer: { defaultMessage: 'This toot will only be sent to all the mentioned users. However, the operators of your instance and any receiving instances may see this message.', id: 'compose_form.direct_message_warning', }, >>>>>>> REPLACE