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
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
rhdunn/xquery-intellij-plugin
|
e68fb9c0b3bd3a765abdc3299f793baa6c493eb4
|
src/lang-xpath/main/uk/co/reecedunn/intellij/plugin/xpath/lang/refactoring/XPathRefactoringSupportProvider.kt
|
kotlin
|
apache-2.0
|
Use VariableInplaceRenameHandler for XpmVariableDefinition elements.
|
/*
* Copyright (C) 2021 Reece H. Dunn
*
* 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 uk.co.reecedunn.intellij.plugin.xpath.lang.refactoring
import com.intellij.lang.refactoring.RefactoringSupportProvider
import com.intellij.psi.PsiElement
class XPathRefactoringSupportProvider : RefactoringSupportProvider() {
/**
* Determines whether VariableInplaceRenameHandler should be used.
*/
override fun isInplaceRenameAvailable(element: PsiElement, context: PsiElement?): Boolean {
return false
}
/**
* Determines whether MemberInplaceRenameHandler should be used.
*/
override fun isMemberInplaceRenameAvailable(element: PsiElement, context: PsiElement?): Boolean {
return false
}
/**
* Determines whether SafeDeleteProcessor should be used.
*/
override fun isSafeDeleteAvailable(element: PsiElement): Boolean {
return false
}
}
|
/*
* Copyright (C) 2021 Reece H. Dunn
*
* 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 uk.co.reecedunn.intellij.plugin.xpath.lang.refactoring
import com.intellij.lang.refactoring.RefactoringSupportProvider
import com.intellij.psi.PsiElement
import uk.co.reecedunn.intellij.plugin.xpm.optree.variable.XpmVariableDefinition
class XPathRefactoringSupportProvider : RefactoringSupportProvider() {
/**
* Determines whether VariableInplaceRenameHandler should be used.
*/
override fun isInplaceRenameAvailable(element: PsiElement, context: PsiElement?): Boolean {
return element.parent is XpmVariableDefinition
}
/**
* Determines whether MemberInplaceRenameHandler should be used.
*/
override fun isMemberInplaceRenameAvailable(element: PsiElement, context: PsiElement?): Boolean {
return false
}
/**
* Determines whether SafeDeleteProcessor should be used.
*/
override fun isSafeDeleteAvailable(element: PsiElement): Boolean {
return false
}
}
| 2
| 1
| 2
|
mixed
|
--- a/src/lang-xpath/main/uk/co/reecedunn/intellij/plugin/xpath/lang/refactoring/XPathRefactoringSupportProvider.kt
+++ b/src/lang-xpath/main/uk/co/reecedunn/intellij/plugin/xpath/lang/refactoring/XPathRefactoringSupportProvider.kt
@@ -19,2 +19,3 @@
import com.intellij.psi.PsiElement
+import uk.co.reecedunn.intellij.plugin.xpm.optree.variable.XpmVariableDefinition
@@ -25,3 +26,3 @@
override fun isInplaceRenameAvailable(element: PsiElement, context: PsiElement?): Boolean {
- return false
+ return element.parent is XpmVariableDefinition
}
|
--- a/src/lang-xpath/main/uk/co/reecedunn/intellij/plugin/xpath/lang/refactoring/XPathRefactoringSupportProvider.kt
+++ b/src/lang-xpath/main/uk/co/reecedunn/intellij/plugin/xpath/lang/refactoring/XPathRefactoringSupportProvider.kt
@@ ... @@
import com.intellij.psi.PsiElement
+import uk.co.reecedunn.intellij.plugin.xpm.optree.variable.XpmVariableDefinition
@@ ... @@
override fun isInplaceRenameAvailable(element: PsiElement, context: PsiElement?): Boolean {
- return false
+ return element.parent is XpmVariableDefinition
}
|
--- a/src/lang-xpath/main/uk/co/reecedunn/intellij/plugin/xpath/lang/refactoring/XPathRefactoringSupportProvider.kt
+++ b/src/lang-xpath/main/uk/co/reecedunn/intellij/plugin/xpath/lang/refactoring/XPathRefactoringSupportProvider.kt
@@ -19,2 +19,3 @@
CON import com.intellij.psi.PsiElement
ADD import uk.co.reecedunn.intellij.plugin.xpm.optree.variable.XpmVariableDefinition
CON
@@ -25,3 +26,3 @@
CON override fun isInplaceRenameAvailable(element: PsiElement, context: PsiElement?): Boolean {
DEL return false
ADD return element.parent is XpmVariableDefinition
CON }
|
<<<<<<< SEARCH
import com.intellij.lang.refactoring.RefactoringSupportProvider
import com.intellij.psi.PsiElement
class XPathRefactoringSupportProvider : RefactoringSupportProvider() {
=======
import com.intellij.lang.refactoring.RefactoringSupportProvider
import com.intellij.psi.PsiElement
import uk.co.reecedunn.intellij.plugin.xpm.optree.variable.XpmVariableDefinition
class XPathRefactoringSupportProvider : RefactoringSupportProvider() {
>>>>>>> REPLACE
<<<<<<< SEARCH
*/
override fun isInplaceRenameAvailable(element: PsiElement, context: PsiElement?): Boolean {
return false
}
=======
*/
override fun isInplaceRenameAvailable(element: PsiElement, context: PsiElement?): Boolean {
return element.parent is XpmVariableDefinition
}
>>>>>>> REPLACE
|
jitsi/jitsi
|
41ef8fba7ff39aafc8a6911428cd72ae87cac2fb
|
src/net/java/sip/communicator/impl/neomedia/device/ImageStreamingAuto.java
|
java
|
apache-2.0
|
Change name displayed for desktop streaming device in the media configuration panel.
|
/*
* SIP Communicator, the OpenSource Java VoIP and Instant Messaging client.
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
*/
package net.java.sip.communicator.impl.neomedia.device;
import javax.media.*;
import net.java.sip.communicator.impl.neomedia.imgstreaming.*;
import net.java.sip.communicator.impl.neomedia.jmfext.media.protocol.imgstreaming.*;
/**
* Add ImageStreaming capture device.
*
* @author Sebastien Vincent
*/
public class ImageStreamingAuto
{
/**
* Add capture devices.
*
* @throws Exception if problem when adding capture devices
*/
public ImageStreamingAuto() throws Exception
{
String name = "Desktop streaming";
CaptureDeviceInfo devInfo
= new CaptureDeviceInfo(
name,
new MediaLocator(
ImageStreamingUtils.LOCATOR_PROTOCOL + ":" + name),
DataSource.getFormats());
/* add to JMF device manager */
CaptureDeviceManager.addDevice(devInfo);
CaptureDeviceManager.commit();
}
}
|
/*
* SIP Communicator, the OpenSource Java VoIP and Instant Messaging client.
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
*/
package net.java.sip.communicator.impl.neomedia.device;
import javax.media.*;
import net.java.sip.communicator.impl.neomedia.imgstreaming.*;
import net.java.sip.communicator.impl.neomedia.jmfext.media.protocol.imgstreaming.*;
/**
* Add ImageStreaming capture device.
*
* @author Sebastien Vincent
*/
public class ImageStreamingAuto
{
/**
* Add capture devices.
*
* @throws Exception if problem when adding capture devices
*/
public ImageStreamingAuto() throws Exception
{
String name = "Experimental desktop streaming";
CaptureDeviceInfo devInfo
= new CaptureDeviceInfo(
name,
new MediaLocator(
ImageStreamingUtils.LOCATOR_PROTOCOL + ":" + name),
DataSource.getFormats());
/* add to JMF device manager */
CaptureDeviceManager.addDevice(devInfo);
CaptureDeviceManager.commit();
}
}
| 1
| 1
| 1
|
mixed
|
--- a/src/net/java/sip/communicator/impl/neomedia/device/ImageStreamingAuto.java
+++ b/src/net/java/sip/communicator/impl/neomedia/device/ImageStreamingAuto.java
@@ -27,3 +27,3 @@
{
- String name = "Desktop streaming";
+ String name = "Experimental desktop streaming";
CaptureDeviceInfo devInfo
|
--- a/src/net/java/sip/communicator/impl/neomedia/device/ImageStreamingAuto.java
+++ b/src/net/java/sip/communicator/impl/neomedia/device/ImageStreamingAuto.java
@@ ... @@
{
- String name = "Desktop streaming";
+ String name = "Experimental desktop streaming";
CaptureDeviceInfo devInfo
|
--- a/src/net/java/sip/communicator/impl/neomedia/device/ImageStreamingAuto.java
+++ b/src/net/java/sip/communicator/impl/neomedia/device/ImageStreamingAuto.java
@@ -27,3 +27,3 @@
CON {
DEL String name = "Desktop streaming";
ADD String name = "Experimental desktop streaming";
CON CaptureDeviceInfo devInfo
|
<<<<<<< SEARCH
public ImageStreamingAuto() throws Exception
{
String name = "Desktop streaming";
CaptureDeviceInfo devInfo
= new CaptureDeviceInfo(
=======
public ImageStreamingAuto() throws Exception
{
String name = "Experimental desktop streaming";
CaptureDeviceInfo devInfo
= new CaptureDeviceInfo(
>>>>>>> REPLACE
|
syzoj/syzoj
|
881977e8e3d1016c19d0e6d76be74cd28ae2ccc0
|
static/script.js
|
javascript
|
mit
|
Introduce a way to add CSRF manually.
|
var addUrlParam = function (url, key, val) {
var newParam = encodeURIComponent(key) + '=' + encodeURIComponent(val);
url = url.split('#')[0];
var twoPart = url.split('?'), params = {};
var tmp = twoPart[1] ? twoPart[1].split('&') : [];
for (let i in tmp) {
let a = tmp[i].split('=');
params[a[0]] = a[1];
}
params[key] = val;
url = twoPart[0] + '?';
for (let key in params) {
url += encodeURIComponent(key) + '=' + encodeURIComponent(params[key]) + '&';
}
url = url.substring(0, url.length - 1);
return url;
};
$(function () {
$(document).on('click', 'a[href-post]', function (e) {
e.preventDefault();
var form = document.createElement('form');
form.style.display = 'none';
form.method = 'post';
form.action = $(this).attr('href-post');
form.target = '_self';
var input = document.createElement('input');
input.type = 'hidden';
input.name = '_csrf';
input.value = document.head.getAttribute('data-csrf-token');
form.appendChild(input);
document.body.appendChild(form);
form.submit();
});
$('form').each(function () {
this.action = addUrlParam(this.action || location.href, '_csrf', document.head.getAttribute('data-csrf-token'));
});
});
|
var addUrlParam = function (url, key, val) {
var newParam = encodeURIComponent(key) + '=' + encodeURIComponent(val);
url = url.split('#')[0];
var twoPart = url.split('?'), params = {};
var tmp = twoPart[1] ? twoPart[1].split('&') : [];
for (let i in tmp) {
let a = tmp[i].split('=');
params[a[0]] = a[1];
}
params[key] = val;
url = twoPart[0] + '?';
for (let key in params) {
url += encodeURIComponent(key) + '=' + encodeURIComponent(params[key]) + '&';
}
url = url.substring(0, url.length - 1);
return url;
};
$(function () {
$(document).on('click', 'a[href-post]', function (e) {
e.preventDefault();
var form = document.createElement('form');
form.style.display = 'none';
form.method = 'post';
form.action = $(this).attr('href-post');
form.target = '_self';
var input = document.createElement('input');
input.type = 'hidden';
input.name = '_csrf';
input.value = document.head.getAttribute('data-csrf-token');
form.appendChild(input);
document.body.appendChild(form);
form.submit();
});
$('form').not('.have-csrf').each(function () {
this.action = addUrlParam(this.action || location.href, '_csrf', document.head.getAttribute('data-csrf-token'));
});
});
| 1
| 1
| 1
|
mixed
|
--- a/static/script.js
+++ b/static/script.js
@@ -43,3 +43,3 @@
- $('form').each(function () {
+ $('form').not('.have-csrf').each(function () {
this.action = addUrlParam(this.action || location.href, '_csrf', document.head.getAttribute('data-csrf-token'));
|
--- a/static/script.js
+++ b/static/script.js
@@ ... @@
- $('form').each(function () {
+ $('form').not('.have-csrf').each(function () {
this.action = addUrlParam(this.action || location.href, '_csrf', document.head.getAttribute('data-csrf-token'));
|
--- a/static/script.js
+++ b/static/script.js
@@ -43,3 +43,3 @@
CON
DEL $('form').each(function () {
ADD $('form').not('.have-csrf').each(function () {
CON this.action = addUrlParam(this.action || location.href, '_csrf', document.head.getAttribute('data-csrf-token'));
|
<<<<<<< SEARCH
});
$('form').each(function () {
this.action = addUrlParam(this.action || location.href, '_csrf', document.head.getAttribute('data-csrf-token'));
});
=======
});
$('form').not('.have-csrf').each(function () {
this.action = addUrlParam(this.action || location.href, '_csrf', document.head.getAttribute('data-csrf-token'));
});
>>>>>>> REPLACE
|
cashapp/turbine
|
6277bc3272cda44ae2c1179a205f9cebc025b754
|
src/commonTest/kotlin/app/cash/turbine/testUtil.kt
|
kotlin
|
apache-2.0
|
Use awaitCancellation instead of suspendCancellableCoroutine
|
/*
* Copyright (C) 2020 Square, Inc.
*
* 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 app.cash.turbine
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.suspendCancellableCoroutine
/** A flow that never emits anything. */
fun neverFlow(): Flow<Nothing> = flow {
suspendCancellableCoroutine {
// Do nothing!
}
}
expect fun suspendTest(body: suspend CoroutineScope.() -> Unit)
inline fun <reified T : Throwable> assertThrows(body: () -> Unit): T {
try {
body()
} catch (t: Throwable) {
if (t is T) {
return t
}
throw t
}
throw AssertionError(
"Expected body to throw ${T::class.simpleName} but it completed successfully"
)
}
|
/*
* Copyright (C) 2020 Square, Inc.
*
* 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 app.cash.turbine
import kotlinx.coroutines.awaitCancellation
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
/** A flow that never emits anything. */
fun neverFlow(): Flow<Nothing> = flow { awaitCancellation() }
expect fun suspendTest(body: suspend CoroutineScope.() -> Unit)
inline fun <reified T : Throwable> assertThrows(body: () -> Unit): T {
try {
body()
} catch (t: Throwable) {
if (t is T) {
return t
}
throw t
}
throw AssertionError(
"Expected body to throw ${T::class.simpleName} but it completed successfully"
)
}
| 2
| 6
| 2
|
mixed
|
--- a/src/commonTest/kotlin/app/cash/turbine/testUtil.kt
+++ b/src/commonTest/kotlin/app/cash/turbine/testUtil.kt
@@ -17,2 +17,3 @@
+import kotlinx.coroutines.awaitCancellation
import kotlinx.coroutines.CoroutineScope
@@ -20,10 +21,5 @@
import kotlinx.coroutines.flow.flow
-import kotlinx.coroutines.suspendCancellableCoroutine
/** A flow that never emits anything. */
-fun neverFlow(): Flow<Nothing> = flow {
- suspendCancellableCoroutine {
- // Do nothing!
- }
-}
+fun neverFlow(): Flow<Nothing> = flow { awaitCancellation() }
|
--- a/src/commonTest/kotlin/app/cash/turbine/testUtil.kt
+++ b/src/commonTest/kotlin/app/cash/turbine/testUtil.kt
@@ ... @@
+import kotlinx.coroutines.awaitCancellation
import kotlinx.coroutines.CoroutineScope
@@ ... @@
import kotlinx.coroutines.flow.flow
-import kotlinx.coroutines.suspendCancellableCoroutine
/** A flow that never emits anything. */
-fun neverFlow(): Flow<Nothing> = flow {
- suspendCancellableCoroutine {
- // Do nothing!
- }
-}
+fun neverFlow(): Flow<Nothing> = flow { awaitCancellation() }
|
--- a/src/commonTest/kotlin/app/cash/turbine/testUtil.kt
+++ b/src/commonTest/kotlin/app/cash/turbine/testUtil.kt
@@ -17,2 +17,3 @@
CON
ADD import kotlinx.coroutines.awaitCancellation
CON import kotlinx.coroutines.CoroutineScope
@@ -20,10 +21,5 @@
CON import kotlinx.coroutines.flow.flow
DEL import kotlinx.coroutines.suspendCancellableCoroutine
CON
CON /** A flow that never emits anything. */
DEL fun neverFlow(): Flow<Nothing> = flow {
DEL suspendCancellableCoroutine {
DEL // Do nothing!
DEL }
DEL }
ADD fun neverFlow(): Flow<Nothing> = flow { awaitCancellation() }
CON
|
<<<<<<< SEARCH
package app.cash.turbine
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.suspendCancellableCoroutine
/** A flow that never emits anything. */
fun neverFlow(): Flow<Nothing> = flow {
suspendCancellableCoroutine {
// Do nothing!
}
}
expect fun suspendTest(body: suspend CoroutineScope.() -> Unit)
=======
package app.cash.turbine
import kotlinx.coroutines.awaitCancellation
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
/** A flow that never emits anything. */
fun neverFlow(): Flow<Nothing> = flow { awaitCancellation() }
expect fun suspendTest(body: suspend CoroutineScope.() -> Unit)
>>>>>>> REPLACE
|
holmwell/circle-blvd
|
687ca9c3d5e5b2c4f1152327f3773404c5285533
|
server/server.js
|
javascript
|
bsd-2-clause
|
Fix: Allow database name to be configured
We broke the honoring of the database name
settings when we 'refactored' server.js a
couple commits ago.
|
// server.js
//
// The main entry point for Circle Blvd. Handles
// command-line arguments and the highest level
// config for the app.
//
//
var app = require('./app.js');
// Process command-line arguments
var isDebugging = false;
for (var index in process.argv) {
if (process.argv[index] === '--debug') {
isDebugging = true;
}
}
// Process environment variables, for now
//
// TODO: Put all of these in a more robust
// config situation, and get out of messing
// with process.env so that we can have a
// healthy test environment.
process.env.PORT = process.env.PORT || 3000;
process.env.SSL_PORT = process.env.SSL_PORT || 4000;
process.env.DATABASE_NAME = 'circle-blvd';
var config = {
isDebugging: isDebugging
};
// Start the app.
app.init(config);
// Wait for the database and such to initialize
app.whenReady(start);
function start () {
app.startServer();
}
|
// server.js
//
// The main entry point for Circle Blvd. Handles
// command-line arguments and the highest level
// config for the app.
//
//
// Process command-line arguments
var isDebugging = false;
for (var index in process.argv) {
if (process.argv[index] === '--debug') {
isDebugging = true;
}
}
// Process environment variables, for now
//
// TODO: Put all of these in a more robust
// config situation, and get out of messing
// with process.env so that we can have a
// healthy test environment.
process.env.PORT = process.env.PORT || 3000;
process.env.SSL_PORT = process.env.SSL_PORT || 4000;
process.env.DATABASE_NAME = 'circle-blvd';
var config = {
isDebugging: isDebugging
};
// This line must be after the env variables are set.
var app = require('./app.js');
// Start the app.
app.init(config);
// Wait for the database and such to initialize
app.whenReady(start);
function start () {
app.startServer();
}
| 4
| 1
| 2
|
mixed
|
--- a/server/server.js
+++ b/server/server.js
@@ -7,3 +7,2 @@
//
-var app = require('./app.js');
@@ -31,2 +30,6 @@
+
+// This line must be after the env variables are set.
+var app = require('./app.js');
+
// Start the app.
|
--- a/server/server.js
+++ b/server/server.js
@@ ... @@
//
-var app = require('./app.js');
@@ ... @@
+
+// This line must be after the env variables are set.
+var app = require('./app.js');
+
// Start the app.
|
--- a/server/server.js
+++ b/server/server.js
@@ -7,3 +7,2 @@
CON //
DEL var app = require('./app.js');
CON
@@ -31,2 +30,6 @@
CON
ADD
ADD // This line must be after the env variables are set.
ADD var app = require('./app.js');
ADD
CON // Start the app.
|
<<<<<<< SEARCH
//
//
var app = require('./app.js');
// Process command-line arguments
=======
//
//
// Process command-line arguments
>>>>>>> REPLACE
<<<<<<< SEARCH
};
// Start the app.
app.init(config);
=======
};
// This line must be after the env variables are set.
var app = require('./app.js');
// Start the app.
app.init(config);
>>>>>>> REPLACE
|
nathansizemore/hydrogen
|
051aa6912ac8bbb5b8059b074dc969a20f4473a3
|
src/lib.rs
|
rust
|
mpl-2.0
|
Set waiting before io to stop repeat reads
|
// Copyright 2015 Nathan Sizemore <[email protected]>
//
// 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/.
#[macro_use]
extern crate log;
extern crate libc;
extern crate errno;
extern crate threadpool;
extern crate simple_slab;
use std::io::Error;
use std::sync::Arc;
use std::cell::UnsafeCell;
use std::net::TcpListener;
use std::os::unix::io::{RawFd, AsRawFd};
use config::Config;
pub mod config;
mod server;
pub trait Stream : AsRawFd + Send + Sync {
fn recv(&mut self) -> Result<Vec<Vec<u8>>, Error>;
fn send(&mut self, buf: &[u8]) -> Result<(), Error>;
}
pub trait Handler {
fn on_server_created(&mut self, fd: RawFd);
fn on_new_connection(&mut self, fd: RawFd) -> Arc<UnsafeCell<Stream>>;
fn on_data_received(&mut self, arc_stream: Arc<UnsafeCell<Stream>>, buf: Vec<u8>);
fn on_connection_removed(&mut self, fd: RawFd);
}
pub fn begin<T>(handler: Box<T>, cfg: Config)
where T: Handler + Send + Sync + 'static
{
server::begin(handler, cfg);
}
|
// Copyright 2015 Nathan Sizemore <[email protected]>
//
// 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/.
#[macro_use]
extern crate log;
extern crate libc;
extern crate errno;
extern crate threadpool;
extern crate simple_slab;
use std::io::Error;
use std::sync::Arc;
use std::cell::UnsafeCell;
use std::os::unix::io::{RawFd, AsRawFd};
use config::Config;
pub mod config;
mod server;
pub trait Stream : AsRawFd + Send + Sync {
fn recv(&mut self) -> Result<Vec<Vec<u8>>, Error>;
fn send(&mut self, buf: &[u8]) -> Result<(), Error>;
}
pub trait Handler {
fn on_server_created(&mut self, fd: RawFd);
fn on_new_connection(&mut self, fd: RawFd) -> Arc<UnsafeCell<Stream>>;
fn on_data_received(&mut self, arc_stream: Arc<UnsafeCell<Stream>>, buf: Vec<u8>);
fn on_connection_removed(&mut self, fd: RawFd);
}
pub fn begin<T>(handler: Box<T>, cfg: Config)
where T: Handler + Send + Sync + 'static
{
server::begin(handler, cfg);
}
| 0
| 1
| 1
|
del_only
|
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -19,3 +19,2 @@
use std::cell::UnsafeCell;
-use std::net::TcpListener;
use std::os::unix::io::{RawFd, AsRawFd};
|
--- a/src/lib.rs
+++ b/src/lib.rs
@@ ... @@
use std::cell::UnsafeCell;
-use std::net::TcpListener;
use std::os::unix::io::{RawFd, AsRawFd};
|
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -19,3 +19,2 @@
CON use std::cell::UnsafeCell;
DEL use std::net::TcpListener;
CON use std::os::unix::io::{RawFd, AsRawFd};
|
<<<<<<< SEARCH
use std::sync::Arc;
use std::cell::UnsafeCell;
use std::net::TcpListener;
use std::os::unix::io::{RawFd, AsRawFd};
=======
use std::sync::Arc;
use std::cell::UnsafeCell;
use std::os::unix::io::{RawFd, AsRawFd};
>>>>>>> REPLACE
|
lukasjuhrich/pycroft
|
08461a2f61b5a5981a6da9f6ef91a362eed92bfd
|
pycroft/__init__.py
|
python
|
apache-2.0
|
Fix config loader (bug in commit:5bdf6e47 / commit:eefe7561)
|
# -*- coding: utf-8 -*-
# Copyright (c) 2014 The Pycroft Authors. See the AUTHORS file.
# This file is part of the Pycroft project and licensed under the terms of
# the Apache License, Version 2.0. See the LICENSE file for details.
"""
pycroft
~~~~~~~~~~~~~~
This package contains everything.
:copyright: (c) 2011 by AG DSN.
"""
import json, collections, pkgutil
class Config(object):
def __init__(self):
self._config_data = None
self._package = "pycroft"
self._resource = "config.json"
def load(self):
data = (pkgutil.get_data(self._package, self._resource) or
pkgutil.get_data(self._package, self._resource+".default"))
if data is None:
raise Exception(
"Could not load config file {1} "
"from package {0}".format(self._package, self._resource)
)
self._config_data = json.loads(data)
if not isinstance(self._config_data, collections.Mapping):
raise Exception("Config must be a JSON object!")
def __getitem__(self, key):
if self._config_data is None:
self.load()
return self._config_data[key]
def __setitem__(self, key, value):
raise Exception("It is not possible to set configuration entries!")
config = Config()
|
# -*- coding: utf-8 -*-
# Copyright (c) 2014 The Pycroft Authors. See the AUTHORS file.
# This file is part of the Pycroft project and licensed under the terms of
# the Apache License, Version 2.0. See the LICENSE file for details.
"""
pycroft
~~~~~~~~~~~~~~
This package contains everything.
:copyright: (c) 2011 by AG DSN.
"""
import json, collections, pkgutil
class Config(object):
def __init__(self):
self._config_data = None
self._package = "pycroft"
self._resource = "config.json"
def load(self):
data = None
try:
data = pkgutil.get_data(self._package, self._resource)
except IOError:
data = pkgutil.get_data(self._package, self._resource+".default")
if data is None:
raise Exception(
"Could not load config file {1} "
"from package {0}".format(self._package, self._resource)
)
self._config_data = json.loads(data)
if not isinstance(self._config_data, collections.Mapping):
raise Exception("Config must be a JSON object!")
def __getitem__(self, key):
if self._config_data is None:
self.load()
return self._config_data[key]
def __setitem__(self, key, value):
raise Exception("It is not possible to set configuration entries!")
config = Config()
| 5
| 2
| 1
|
mixed
|
--- a/pycroft/__init__.py
+++ b/pycroft/__init__.py
@@ -22,4 +22,7 @@
def load(self):
- data = (pkgutil.get_data(self._package, self._resource) or
- pkgutil.get_data(self._package, self._resource+".default"))
+ data = None
+ try:
+ data = pkgutil.get_data(self._package, self._resource)
+ except IOError:
+ data = pkgutil.get_data(self._package, self._resource+".default")
if data is None:
|
--- a/pycroft/__init__.py
+++ b/pycroft/__init__.py
@@ ... @@
def load(self):
- data = (pkgutil.get_data(self._package, self._resource) or
- pkgutil.get_data(self._package, self._resource+".default"))
+ data = None
+ try:
+ data = pkgutil.get_data(self._package, self._resource)
+ except IOError:
+ data = pkgutil.get_data(self._package, self._resource+".default")
if data is None:
|
--- a/pycroft/__init__.py
+++ b/pycroft/__init__.py
@@ -22,4 +22,7 @@
CON def load(self):
DEL data = (pkgutil.get_data(self._package, self._resource) or
DEL pkgutil.get_data(self._package, self._resource+".default"))
ADD data = None
ADD try:
ADD data = pkgutil.get_data(self._package, self._resource)
ADD except IOError:
ADD data = pkgutil.get_data(self._package, self._resource+".default")
CON if data is None:
|
<<<<<<< SEARCH
def load(self):
data = (pkgutil.get_data(self._package, self._resource) or
pkgutil.get_data(self._package, self._resource+".default"))
if data is None:
raise Exception(
=======
def load(self):
data = None
try:
data = pkgutil.get_data(self._package, self._resource)
except IOError:
data = pkgutil.get_data(self._package, self._resource+".default")
if data is None:
raise Exception(
>>>>>>> REPLACE
|
nadimtuhin/redux-vue
|
cbbc4ce41510025672b9fb5f27737eb5a4e278a4
|
src/connect.js
|
javascript
|
mit
|
Use render function instead of template
This is needed for runtime only environment in Vue
|
import noop from 'lodash/noop';
import omitBy from 'lodash/omitBy';
import isArray from 'lodash/isArray';
import normalizeProps from './normalizeProps';
export default function connect(mapStateAsProps = noop, mapActionsAsProps = noop) {
return (children) => {
const props = children.props || {};
const subscriptions = children.collect || {};
const allProps = {
...normalizeProps(props),
...normalizeProps(subscriptions)
};
const propsToPass = Object.keys(allProps).map(key => `:${key}='${key}'`).join(' ');
const template = `<children ${propsToPass}></children>`;
children.props = allProps;
delete children.collect;
return {
template,
props: props,
data() {
const store = this.$store;
const state = mapStateAsProps(store.getState()) || {};
const actions = mapActionsAsProps(store.dispatch, store.getState) || {};
return {
...state,
...actions
};
},
components: {
children
},
created() {
const store = this.$store;
const state = mapStateAsProps(store.getState()) || {};
const stateNames = Object.keys(state);
this.unsubscribe = store.subscribe(() => {
const state = mapStateAsProps(store.getState());
stateNames.forEach((key) => { // fixme: use a simple loop
this[key] = state[key];
});
});
},
beforeDestroy() {
this.unsubscribe();
}
};
};
}
|
import noop from 'lodash/noop';
import omitBy from 'lodash/omitBy';
import isArray from 'lodash/isArray';
import normalizeProps from './normalizeProps';
export default function connect(mapStateAsProps = noop, mapActionsAsProps = noop) {
return (children) => {
const props = children.props || {};
const subscriptions = children.collect || {};
const allProps = {
...normalizeProps(props),
...normalizeProps(subscriptions)
};
children.props = allProps;
delete children.collect;
return {
name: 'VuaRedux',
props: props,
render(h) {
const keys = Object.keys(allProps);
let propsToPass = {};
for (let i = 0; i < keys.length; i++) {
propsToPass[keys[i]] = this[keys[i]];
}
return h(children, {
props: propsToPass
})
},
data() {
const store = this.$store;
const state = mapStateAsProps(store.getState()) || {};
const actions = mapActionsAsProps(store.dispatch, store.getState) || {};
return {
...state,
...actions
};
},
created() {
const store = this.$store;
const state = mapStateAsProps(store.getState()) || {};
const stateNames = Object.keys(state);
this.unsubscribe = store.subscribe(() => {
const state = mapStateAsProps(store.getState());
for (let i = 0; i < stateNames.length; i++) {
this[stateNames[i]] = state[stateNames[i]];
}
});
},
beforeDestroy() {
this.unsubscribe();
}
};
};
}
| 18
| 13
| 5
|
mixed
|
--- a/src/connect.js
+++ b/src/connect.js
@@ -9,3 +9,3 @@
const subscriptions = children.collect || {};
-
+
const allProps = {
@@ -15,6 +15,2 @@
-
- const propsToPass = Object.keys(allProps).map(key => `:${key}='${key}'`).join(' ');
- const template = `<children ${propsToPass}></children>`;
-
children.props = allProps;
@@ -23,4 +19,17 @@
return {
- template,
+ name: 'VuaRedux',
+
props: props,
+
+ render(h) {
+ const keys = Object.keys(allProps);
+ let propsToPass = {};
+ for (let i = 0; i < keys.length; i++) {
+ propsToPass[keys[i]] = this[keys[i]];
+ }
+
+ return h(children, {
+ props: propsToPass
+ })
+ },
@@ -37,6 +46,2 @@
- components: {
- children
- },
-
created() {
@@ -49,5 +54,5 @@
- stateNames.forEach((key) => { // fixme: use a simple loop
- this[key] = state[key];
- });
+ for (let i = 0; i < stateNames.length; i++) {
+ this[stateNames[i]] = state[stateNames[i]];
+ }
});
|
--- a/src/connect.js
+++ b/src/connect.js
@@ ... @@
const subscriptions = children.collect || {};
-
+
const allProps = {
@@ ... @@
-
- const propsToPass = Object.keys(allProps).map(key => `:${key}='${key}'`).join(' ');
- const template = `<children ${propsToPass}></children>`;
-
children.props = allProps;
@@ ... @@
return {
- template,
+ name: 'VuaRedux',
+
props: props,
+
+ render(h) {
+ const keys = Object.keys(allProps);
+ let propsToPass = {};
+ for (let i = 0; i < keys.length; i++) {
+ propsToPass[keys[i]] = this[keys[i]];
+ }
+
+ return h(children, {
+ props: propsToPass
+ })
+ },
@@ ... @@
- components: {
- children
- },
-
created() {
@@ ... @@
- stateNames.forEach((key) => { // fixme: use a simple loop
- this[key] = state[key];
- });
+ for (let i = 0; i < stateNames.length; i++) {
+ this[stateNames[i]] = state[stateNames[i]];
+ }
});
|
--- a/src/connect.js
+++ b/src/connect.js
@@ -9,3 +9,3 @@
CON const subscriptions = children.collect || {};
DEL
ADD
CON const allProps = {
@@ -15,6 +15,2 @@
CON
DEL
DEL const propsToPass = Object.keys(allProps).map(key => `:${key}='${key}'`).join(' ');
DEL const template = `<children ${propsToPass}></children>`;
DEL
CON children.props = allProps;
@@ -23,4 +19,17 @@
CON return {
DEL template,
ADD name: 'VuaRedux',
ADD
CON props: props,
ADD
ADD render(h) {
ADD const keys = Object.keys(allProps);
ADD let propsToPass = {};
ADD for (let i = 0; i < keys.length; i++) {
ADD propsToPass[keys[i]] = this[keys[i]];
ADD }
ADD
ADD return h(children, {
ADD props: propsToPass
ADD })
ADD },
CON
@@ -37,6 +46,2 @@
CON
DEL components: {
DEL children
DEL },
DEL
CON created() {
@@ -49,5 +54,5 @@
CON
DEL stateNames.forEach((key) => { // fixme: use a simple loop
DEL this[key] = state[key];
DEL });
ADD for (let i = 0; i < stateNames.length; i++) {
ADD this[stateNames[i]] = state[stateNames[i]];
ADD }
CON });
|
<<<<<<< SEARCH
const props = children.props || {};
const subscriptions = children.collect || {};
const allProps = {
...normalizeProps(props),
...normalizeProps(subscriptions)
};
const propsToPass = Object.keys(allProps).map(key => `:${key}='${key}'`).join(' ');
const template = `<children ${propsToPass}></children>`;
children.props = allProps;
delete children.collect;
return {
template,
props: props,
data() {
=======
const props = children.props || {};
const subscriptions = children.collect || {};
const allProps = {
...normalizeProps(props),
...normalizeProps(subscriptions)
};
children.props = allProps;
delete children.collect;
return {
name: 'VuaRedux',
props: props,
render(h) {
const keys = Object.keys(allProps);
let propsToPass = {};
for (let i = 0; i < keys.length; i++) {
propsToPass[keys[i]] = this[keys[i]];
}
return h(children, {
props: propsToPass
})
},
data() {
>>>>>>> REPLACE
<<<<<<< SEARCH
},
components: {
children
},
created() {
const store = this.$store;
=======
},
created() {
const store = this.$store;
>>>>>>> REPLACE
<<<<<<< SEARCH
const state = mapStateAsProps(store.getState());
stateNames.forEach((key) => { // fixme: use a simple loop
this[key] = state[key];
});
});
},
=======
const state = mapStateAsProps(store.getState());
for (let i = 0; i < stateNames.length; i++) {
this[stateNames[i]] = state[stateNames[i]];
}
});
},
>>>>>>> REPLACE
|
PKRoma/PocketHub
|
ae0618523033bf85c936c2527f61b9b9333c32db
|
app/src/main/java/com/github/pockethub/android/ui/ResourceLoadingIndicator.kt
|
kotlin
|
apache-2.0
|
Use backing field instead of explicit setter
|
/*
* Copyright (c) 2015 PocketHub
*
* 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.github.pockethub.android.ui
import com.github.pockethub.android.ui.item.LoadingItem
import com.xwray.groupie.Section
/**
* Helper for showing more items are being loaded at the bottom of a list via a
* custom footer view
*
* @param loadingResId string resource id to show when loading
* @param section the adapter that this indicator should be added as a footer to.
*/
class ResourceLoadingIndicator(loadingResId: Int, private val section: Section) {
private var showing: Boolean = false
private val loadingItem = LoadingItem(loadingResId)
/**
* Set visibility of entire indicator view.
*
* @param visible
*/
fun setVisible(visible: Boolean) {
if (showing != visible) {
if (visible) {
section.setFooter(loadingItem)
} else {
section.removeFooter()
}
}
showing = visible
}
}
|
/*
* Copyright (c) 2015 PocketHub
*
* 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.github.pockethub.android.ui
import com.github.pockethub.android.ui.item.LoadingItem
import com.xwray.groupie.Section
/**
* Helper for showing more items are being loaded at the bottom of a list via a
* custom footer view
*
* @param loadingResId string resource id to show when loading
* @param section the adapter that this indicator should be added as a footer to.
*/
class ResourceLoadingIndicator(loadingResId: Int, private val section: Section) {
private val loadingItem = LoadingItem(loadingResId)
/**
* Visibility of entire indicator view.
*/
var visible: Boolean = false
set(value) {
if (visible != value) {
if (value) {
section.setFooter(loadingItem)
} else {
section.removeFooter()
}
field = value
}
}
}
| 10
| 13
| 2
|
mixed
|
--- a/app/src/main/java/com/github/pockethub/android/ui/ResourceLoadingIndicator.kt
+++ b/app/src/main/java/com/github/pockethub/android/ui/ResourceLoadingIndicator.kt
@@ -29,4 +29,2 @@
- private var showing: Boolean = false
-
private val loadingItem = LoadingItem(loadingResId)
@@ -34,16 +32,15 @@
/**
- * Set visibility of entire indicator view.
- *
- * @param visible
+ * Visibility of entire indicator view.
*/
- fun setVisible(visible: Boolean) {
- if (showing != visible) {
- if (visible) {
- section.setFooter(loadingItem)
- } else {
- section.removeFooter()
+ var visible: Boolean = false
+ set(value) {
+ if (visible != value) {
+ if (value) {
+ section.setFooter(loadingItem)
+ } else {
+ section.removeFooter()
+ }
+ field = value
}
}
- showing = visible
- }
}
|
--- a/app/src/main/java/com/github/pockethub/android/ui/ResourceLoadingIndicator.kt
+++ b/app/src/main/java/com/github/pockethub/android/ui/ResourceLoadingIndicator.kt
@@ ... @@
- private var showing: Boolean = false
-
private val loadingItem = LoadingItem(loadingResId)
@@ ... @@
/**
- * Set visibility of entire indicator view.
- *
- * @param visible
+ * Visibility of entire indicator view.
*/
- fun setVisible(visible: Boolean) {
- if (showing != visible) {
- if (visible) {
- section.setFooter(loadingItem)
- } else {
- section.removeFooter()
+ var visible: Boolean = false
+ set(value) {
+ if (visible != value) {
+ if (value) {
+ section.setFooter(loadingItem)
+ } else {
+ section.removeFooter()
+ }
+ field = value
}
}
- showing = visible
- }
}
|
--- a/app/src/main/java/com/github/pockethub/android/ui/ResourceLoadingIndicator.kt
+++ b/app/src/main/java/com/github/pockethub/android/ui/ResourceLoadingIndicator.kt
@@ -29,4 +29,2 @@
CON
DEL private var showing: Boolean = false
DEL
CON private val loadingItem = LoadingItem(loadingResId)
@@ -34,16 +32,15 @@
CON /**
DEL * Set visibility of entire indicator view.
DEL *
DEL * @param visible
ADD * Visibility of entire indicator view.
CON */
DEL fun setVisible(visible: Boolean) {
DEL if (showing != visible) {
DEL if (visible) {
DEL section.setFooter(loadingItem)
DEL } else {
DEL section.removeFooter()
ADD var visible: Boolean = false
ADD set(value) {
ADD if (visible != value) {
ADD if (value) {
ADD section.setFooter(loadingItem)
ADD } else {
ADD section.removeFooter()
ADD }
ADD field = value
CON }
CON }
DEL showing = visible
DEL }
CON }
|
<<<<<<< SEARCH
class ResourceLoadingIndicator(loadingResId: Int, private val section: Section) {
private var showing: Boolean = false
private val loadingItem = LoadingItem(loadingResId)
/**
* Set visibility of entire indicator view.
*
* @param visible
*/
fun setVisible(visible: Boolean) {
if (showing != visible) {
if (visible) {
section.setFooter(loadingItem)
} else {
section.removeFooter()
}
}
showing = visible
}
}
=======
class ResourceLoadingIndicator(loadingResId: Int, private val section: Section) {
private val loadingItem = LoadingItem(loadingResId)
/**
* Visibility of entire indicator view.
*/
var visible: Boolean = false
set(value) {
if (visible != value) {
if (value) {
section.setFooter(loadingItem)
} else {
section.removeFooter()
}
field = value
}
}
}
>>>>>>> REPLACE
|
LevelPlayingField/levelplayingfield
|
0e640c1d29b793b3db8620cc4c4465dd22d1a5f7
|
src/routes/index.js
|
javascript
|
mit
|
Remove cases and parties import
|
/* @flow */
/**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-2016 Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
/* eslint-disable global-require */
// The top-level (parent) route
export default {
path: '/',
// Keep in mind, routes are evaluated in order
children: [
require('./home').default,
require('./privacy').default,
require('./about-us').default,
require('./contact-us').default,
require('./search').default,
require('./cases').default,
require('./parties').default,
require('./case').default,
require('./party').default,
require('./notFound').default,
],
async action({ next }: any) {
// Execute each child route until one of them return the result
const route = await next();
// Provide default values for title, description etc.
route.title = `${route.title || 'Untitled Page'} - LevelPlayingField`;
route.description = route.description || '';
return route;
},
};
|
/* @flow */
/**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-2016 Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
/* eslint-disable global-require */
// The top-level (parent) route
export default {
path: '/',
// Keep in mind, routes are evaluated in order
children: [
require('./home').default,
require('./privacy').default,
require('./about-us').default,
require('./contact-us').default,
require('./search').default,
require('./case').default,
require('./party').default,
require('./notFound').default,
],
async action({ next }: any) {
// Execute each child route until one of them return the result
const route = await next();
// Provide default values for title, description etc.
route.title = `${route.title || 'Untitled Page'} - LevelPlayingField`;
route.description = route.description || '';
return route;
},
};
| 0
| 3
| 1
|
del_only
|
--- a/src/routes/index.js
+++ b/src/routes/index.js
@@ -26,5 +26,2 @@
- require('./cases').default,
- require('./parties').default,
-
require('./case').default,
|
--- a/src/routes/index.js
+++ b/src/routes/index.js
@@ ... @@
- require('./cases').default,
- require('./parties').default,
-
require('./case').default,
|
--- a/src/routes/index.js
+++ b/src/routes/index.js
@@ -26,5 +26,2 @@
CON
DEL require('./cases').default,
DEL require('./parties').default,
DEL
CON require('./case').default,
|
<<<<<<< SEARCH
require('./search').default,
require('./cases').default,
require('./parties').default,
require('./case').default,
require('./party').default,
=======
require('./search').default,
require('./case').default,
require('./party').default,
>>>>>>> REPLACE
|
fhanik/spring-security
|
1d6fdd249bea9c5b9878d09c95c26713b753bdde
|
config/src/main/kotlin/org/springframework/security/config/web/servlet/AbstractRequestMatcherDsl.kt
|
kotlin
|
apache-2.0
|
Add missing Javadoc to Kotlin class
|
/*
* Copyright 2002-2020 the original author or authors.
*
* 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
*
* https://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.springframework.security.config.web.servlet
import org.springframework.security.web.util.matcher.AnyRequestMatcher
import org.springframework.security.web.util.matcher.RequestMatcher
abstract class AbstractRequestMatcherDsl {
/**
* Matches any request.
*/
val anyRequest: RequestMatcher = AnyRequestMatcher.INSTANCE
protected data class MatcherAuthorizationRule(val matcher: RequestMatcher,
override val rule: String) : AuthorizationRule(rule)
protected data class PatternAuthorizationRule(val pattern: String,
val patternType: PatternType,
val servletPath: String?,
override val rule: String) : AuthorizationRule(rule)
protected abstract class AuthorizationRule(open val rule: String)
protected enum class PatternType {
ANT, MVC
}
}
|
/*
* Copyright 2002-2020 the original author or authors.
*
* 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
*
* https://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.springframework.security.config.web.servlet
import org.springframework.security.web.util.matcher.AnyRequestMatcher
import org.springframework.security.web.util.matcher.RequestMatcher
/**
* A base class that provides authorization rules for [RequestMatcher]s and patterns.
*
* @author Eleftheria Stein
* @since 5.3
*/
abstract class AbstractRequestMatcherDsl {
/**
* Matches any request.
*/
val anyRequest: RequestMatcher = AnyRequestMatcher.INSTANCE
protected data class MatcherAuthorizationRule(val matcher: RequestMatcher,
override val rule: String) : AuthorizationRule(rule)
protected data class PatternAuthorizationRule(val pattern: String,
val patternType: PatternType,
val servletPath: String?,
override val rule: String) : AuthorizationRule(rule)
protected abstract class AuthorizationRule(open val rule: String)
protected enum class PatternType {
ANT, MVC
}
}
| 6
| 1
| 1
|
mixed
|
--- a/config/src/main/kotlin/org/springframework/security/config/web/servlet/AbstractRequestMatcherDsl.kt
+++ b/config/src/main/kotlin/org/springframework/security/config/web/servlet/AbstractRequestMatcherDsl.kt
@@ -21,4 +21,9 @@
+/**
+ * A base class that provides authorization rules for [RequestMatcher]s and patterns.
+ *
+ * @author Eleftheria Stein
+ * @since 5.3
+ */
abstract class AbstractRequestMatcherDsl {
-
/**
|
--- a/config/src/main/kotlin/org/springframework/security/config/web/servlet/AbstractRequestMatcherDsl.kt
+++ b/config/src/main/kotlin/org/springframework/security/config/web/servlet/AbstractRequestMatcherDsl.kt
@@ ... @@
+/**
+ * A base class that provides authorization rules for [RequestMatcher]s and patterns.
+ *
+ * @author Eleftheria Stein
+ * @since 5.3
+ */
abstract class AbstractRequestMatcherDsl {
-
/**
|
--- a/config/src/main/kotlin/org/springframework/security/config/web/servlet/AbstractRequestMatcherDsl.kt
+++ b/config/src/main/kotlin/org/springframework/security/config/web/servlet/AbstractRequestMatcherDsl.kt
@@ -21,4 +21,9 @@
CON
ADD /**
ADD * A base class that provides authorization rules for [RequestMatcher]s and patterns.
ADD *
ADD * @author Eleftheria Stein
ADD * @since 5.3
ADD */
CON abstract class AbstractRequestMatcherDsl {
DEL
CON /**
|
<<<<<<< SEARCH
import org.springframework.security.web.util.matcher.RequestMatcher
abstract class AbstractRequestMatcherDsl {
/**
* Matches any request.
=======
import org.springframework.security.web.util.matcher.RequestMatcher
/**
* A base class that provides authorization rules for [RequestMatcher]s and patterns.
*
* @author Eleftheria Stein
* @since 5.3
*/
abstract class AbstractRequestMatcherDsl {
/**
* Matches any request.
>>>>>>> REPLACE
|
JFormDesigner/RichTextFX
|
e6b8404b1e3135d2519689c430b1d683e09b4361
|
richtextfx-demos/src/main/java/org/fxmisc/richtext/demo/richtext/LinkedImageOps.java
|
java
|
bsd-2-clause
|
Extend base class to reduce boilerplate code
|
package org.fxmisc.richtext.demo.richtext;
import java.util.Optional;
import org.fxmisc.richtext.model.SegmentOps;
public class LinkedImageOps<S> implements SegmentOps<LinkedImage<S>, S> {
private final EmptyLinkedImage<S> emptySeg = new EmptyLinkedImage<>();
@Override
public int length(LinkedImage<S> seg) {
return seg == emptySeg ? 0 : 1;
}
@Override
public char charAt(LinkedImage<S> seg, int index) {
return seg == emptySeg ? '\0' : '\ufffc';
}
@Override
public String getText(LinkedImage<S> seg) {
return seg == emptySeg ? "" : "\ufffc";
}
@Override
public LinkedImage<S> subSequence(LinkedImage<S> seg, int start, int end) {
if (start < 0) {
throw new IllegalArgumentException("Start cannot be negative. Start = " + start);
}
if (end > length(seg)) {
throw new IllegalArgumentException("End cannot be greater than segment's length");
}
return start == 0 && end == 1
? seg
: emptySeg;
}
@Override
public LinkedImage<S> subSequence(LinkedImage<S> seg, int start) {
if (start < 0) {
throw new IllegalArgumentException("Start cannot be negative. Start = " + start);
}
return start == 0
? seg
: emptySeg;
}
@Override
public S getStyle(LinkedImage<S> seg) {
return seg.getStyle();
}
@Override
public LinkedImage<S> setStyle(LinkedImage<S> seg, S style) {
return seg == emptySeg ? emptySeg : seg.setStyle(style);
}
@Override
public Optional<LinkedImage<S>> join(LinkedImage<S> currentSeg, LinkedImage<S> nextSeg) {
return Optional.empty();
}
@Override
public LinkedImage<S> createEmpty() {
return emptySeg;
}
}
|
package org.fxmisc.richtext.demo.richtext;
import org.fxmisc.richtext.model.NodeSegmentOpsBase;
public class LinkedImageOps<S> extends NodeSegmentOpsBase<LinkedImage<S>, S> {
public LinkedImageOps() {
super(new EmptyLinkedImage<>());
}
@Override
public S realGetStyle(LinkedImage<S> linkedImage) {
return linkedImage.getStyle();
}
@Override
public LinkedImage<S> realSetStyle(LinkedImage<S> linkedImage, S style) {
return linkedImage.setStyle(style);
}
}
| 8
| 55
| 3
|
mixed
|
--- a/richtextfx-demos/src/main/java/org/fxmisc/richtext/demo/richtext/LinkedImageOps.java
+++ b/richtextfx-demos/src/main/java/org/fxmisc/richtext/demo/richtext/LinkedImageOps.java
@@ -2,13 +2,8 @@
-import java.util.Optional;
+import org.fxmisc.richtext.model.NodeSegmentOpsBase;
-import org.fxmisc.richtext.model.SegmentOps;
+public class LinkedImageOps<S> extends NodeSegmentOpsBase<LinkedImage<S>, S> {
-public class LinkedImageOps<S> implements SegmentOps<LinkedImage<S>, S> {
-
- private final EmptyLinkedImage<S> emptySeg = new EmptyLinkedImage<>();
-
- @Override
- public int length(LinkedImage<S> seg) {
- return seg == emptySeg ? 0 : 1;
+ public LinkedImageOps() {
+ super(new EmptyLinkedImage<>());
}
@@ -16,4 +11,4 @@
@Override
- public char charAt(LinkedImage<S> seg, int index) {
- return seg == emptySeg ? '\0' : '\ufffc';
+ public S realGetStyle(LinkedImage<S> linkedImage) {
+ return linkedImage.getStyle();
}
@@ -21,48 +16,6 @@
@Override
- public String getText(LinkedImage<S> seg) {
- return seg == emptySeg ? "" : "\ufffc";
+ public LinkedImage<S> realSetStyle(LinkedImage<S> linkedImage, S style) {
+ return linkedImage.setStyle(style);
}
- @Override
- public LinkedImage<S> subSequence(LinkedImage<S> seg, int start, int end) {
- if (start < 0) {
- throw new IllegalArgumentException("Start cannot be negative. Start = " + start);
- }
- if (end > length(seg)) {
- throw new IllegalArgumentException("End cannot be greater than segment's length");
- }
- return start == 0 && end == 1
- ? seg
- : emptySeg;
- }
-
- @Override
- public LinkedImage<S> subSequence(LinkedImage<S> seg, int start) {
- if (start < 0) {
- throw new IllegalArgumentException("Start cannot be negative. Start = " + start);
- }
- return start == 0
- ? seg
- : emptySeg;
- }
-
- @Override
- public S getStyle(LinkedImage<S> seg) {
- return seg.getStyle();
- }
-
- @Override
- public LinkedImage<S> setStyle(LinkedImage<S> seg, S style) {
- return seg == emptySeg ? emptySeg : seg.setStyle(style);
- }
-
- @Override
- public Optional<LinkedImage<S>> join(LinkedImage<S> currentSeg, LinkedImage<S> nextSeg) {
- return Optional.empty();
- }
-
- @Override
- public LinkedImage<S> createEmpty() {
- return emptySeg;
- }
}
|
--- a/richtextfx-demos/src/main/java/org/fxmisc/richtext/demo/richtext/LinkedImageOps.java
+++ b/richtextfx-demos/src/main/java/org/fxmisc/richtext/demo/richtext/LinkedImageOps.java
@@ ... @@
-import java.util.Optional;
+import org.fxmisc.richtext.model.NodeSegmentOpsBase;
-import org.fxmisc.richtext.model.SegmentOps;
+public class LinkedImageOps<S> extends NodeSegmentOpsBase<LinkedImage<S>, S> {
-public class LinkedImageOps<S> implements SegmentOps<LinkedImage<S>, S> {
-
- private final EmptyLinkedImage<S> emptySeg = new EmptyLinkedImage<>();
-
- @Override
- public int length(LinkedImage<S> seg) {
- return seg == emptySeg ? 0 : 1;
+ public LinkedImageOps() {
+ super(new EmptyLinkedImage<>());
}
@@ ... @@
@Override
- public char charAt(LinkedImage<S> seg, int index) {
- return seg == emptySeg ? '\0' : '\ufffc';
+ public S realGetStyle(LinkedImage<S> linkedImage) {
+ return linkedImage.getStyle();
}
@@ ... @@
@Override
- public String getText(LinkedImage<S> seg) {
- return seg == emptySeg ? "" : "\ufffc";
+ public LinkedImage<S> realSetStyle(LinkedImage<S> linkedImage, S style) {
+ return linkedImage.setStyle(style);
}
- @Override
- public LinkedImage<S> subSequence(LinkedImage<S> seg, int start, int end) {
- if (start < 0) {
- throw new IllegalArgumentException("Start cannot be negative. Start = " + start);
- }
- if (end > length(seg)) {
- throw new IllegalArgumentException("End cannot be greater than segment's length");
- }
- return start == 0 && end == 1
- ? seg
- : emptySeg;
- }
-
- @Override
- public LinkedImage<S> subSequence(LinkedImage<S> seg, int start) {
- if (start < 0) {
- throw new IllegalArgumentException("Start cannot be negative. Start = " + start);
- }
- return start == 0
- ? seg
- : emptySeg;
- }
-
- @Override
- public S getStyle(LinkedImage<S> seg) {
- return seg.getStyle();
- }
-
- @Override
- public LinkedImage<S> setStyle(LinkedImage<S> seg, S style) {
- return seg == emptySeg ? emptySeg : seg.setStyle(style);
- }
-
- @Override
- public Optional<LinkedImage<S>> join(LinkedImage<S> currentSeg, LinkedImage<S> nextSeg) {
- return Optional.empty();
- }
-
- @Override
- public LinkedImage<S> createEmpty() {
- return emptySeg;
- }
}
|
--- a/richtextfx-demos/src/main/java/org/fxmisc/richtext/demo/richtext/LinkedImageOps.java
+++ b/richtextfx-demos/src/main/java/org/fxmisc/richtext/demo/richtext/LinkedImageOps.java
@@ -2,13 +2,8 @@
CON
DEL import java.util.Optional;
ADD import org.fxmisc.richtext.model.NodeSegmentOpsBase;
CON
DEL import org.fxmisc.richtext.model.SegmentOps;
ADD public class LinkedImageOps<S> extends NodeSegmentOpsBase<LinkedImage<S>, S> {
CON
DEL public class LinkedImageOps<S> implements SegmentOps<LinkedImage<S>, S> {
DEL
DEL private final EmptyLinkedImage<S> emptySeg = new EmptyLinkedImage<>();
DEL
DEL @Override
DEL public int length(LinkedImage<S> seg) {
DEL return seg == emptySeg ? 0 : 1;
ADD public LinkedImageOps() {
ADD super(new EmptyLinkedImage<>());
CON }
@@ -16,4 +11,4 @@
CON @Override
DEL public char charAt(LinkedImage<S> seg, int index) {
DEL return seg == emptySeg ? '\0' : '\ufffc';
ADD public S realGetStyle(LinkedImage<S> linkedImage) {
ADD return linkedImage.getStyle();
CON }
@@ -21,48 +16,6 @@
CON @Override
DEL public String getText(LinkedImage<S> seg) {
DEL return seg == emptySeg ? "" : "\ufffc";
ADD public LinkedImage<S> realSetStyle(LinkedImage<S> linkedImage, S style) {
ADD return linkedImage.setStyle(style);
CON }
CON
DEL @Override
DEL public LinkedImage<S> subSequence(LinkedImage<S> seg, int start, int end) {
DEL if (start < 0) {
DEL throw new IllegalArgumentException("Start cannot be negative. Start = " + start);
DEL }
DEL if (end > length(seg)) {
DEL throw new IllegalArgumentException("End cannot be greater than segment's length");
DEL }
DEL return start == 0 && end == 1
DEL ? seg
DEL : emptySeg;
DEL }
DEL
DEL @Override
DEL public LinkedImage<S> subSequence(LinkedImage<S> seg, int start) {
DEL if (start < 0) {
DEL throw new IllegalArgumentException("Start cannot be negative. Start = " + start);
DEL }
DEL return start == 0
DEL ? seg
DEL : emptySeg;
DEL }
DEL
DEL @Override
DEL public S getStyle(LinkedImage<S> seg) {
DEL return seg.getStyle();
DEL }
DEL
DEL @Override
DEL public LinkedImage<S> setStyle(LinkedImage<S> seg, S style) {
DEL return seg == emptySeg ? emptySeg : seg.setStyle(style);
DEL }
DEL
DEL @Override
DEL public Optional<LinkedImage<S>> join(LinkedImage<S> currentSeg, LinkedImage<S> nextSeg) {
DEL return Optional.empty();
DEL }
DEL
DEL @Override
DEL public LinkedImage<S> createEmpty() {
DEL return emptySeg;
DEL }
CON }
|
<<<<<<< SEARCH
package org.fxmisc.richtext.demo.richtext;
import java.util.Optional;
import org.fxmisc.richtext.model.SegmentOps;
public class LinkedImageOps<S> implements SegmentOps<LinkedImage<S>, S> {
private final EmptyLinkedImage<S> emptySeg = new EmptyLinkedImage<>();
@Override
public int length(LinkedImage<S> seg) {
return seg == emptySeg ? 0 : 1;
}
@Override
public char charAt(LinkedImage<S> seg, int index) {
return seg == emptySeg ? '\0' : '\ufffc';
}
@Override
public String getText(LinkedImage<S> seg) {
return seg == emptySeg ? "" : "\ufffc";
}
@Override
public LinkedImage<S> subSequence(LinkedImage<S> seg, int start, int end) {
if (start < 0) {
throw new IllegalArgumentException("Start cannot be negative. Start = " + start);
}
if (end > length(seg)) {
throw new IllegalArgumentException("End cannot be greater than segment's length");
}
return start == 0 && end == 1
? seg
: emptySeg;
}
@Override
public LinkedImage<S> subSequence(LinkedImage<S> seg, int start) {
if (start < 0) {
throw new IllegalArgumentException("Start cannot be negative. Start = " + start);
}
return start == 0
? seg
: emptySeg;
}
@Override
public S getStyle(LinkedImage<S> seg) {
return seg.getStyle();
}
@Override
public LinkedImage<S> setStyle(LinkedImage<S> seg, S style) {
return seg == emptySeg ? emptySeg : seg.setStyle(style);
}
@Override
public Optional<LinkedImage<S>> join(LinkedImage<S> currentSeg, LinkedImage<S> nextSeg) {
return Optional.empty();
}
@Override
public LinkedImage<S> createEmpty() {
return emptySeg;
}
}
=======
package org.fxmisc.richtext.demo.richtext;
import org.fxmisc.richtext.model.NodeSegmentOpsBase;
public class LinkedImageOps<S> extends NodeSegmentOpsBase<LinkedImage<S>, S> {
public LinkedImageOps() {
super(new EmptyLinkedImage<>());
}
@Override
public S realGetStyle(LinkedImage<S> linkedImage) {
return linkedImage.getStyle();
}
@Override
public LinkedImage<S> realSetStyle(LinkedImage<S> linkedImage, S style) {
return linkedImage.setStyle(style);
}
}
>>>>>>> REPLACE
|
mohamad-z/dnsjava
|
439e70fa354b187434410b993539f5bab0ff5cd1
|
org/xbill/DNS/ResolveThread.java
|
java
|
bsd-2-clause
|
Make this a subclass of Thread.
git-svn-id: becfadaebdf67c7884f0d18099f2460615305e2e@969 c76caeb1-94fd-44dd-870f-0c9d92034fc1
|
// Copyright (c) 1999 Brian Wellington ([email protected])
// Portions Copyright (c) 1999 Network Associates, Inc.
package org.xbill.DNS;
import java.util.*;
import java.io.*;
import java.net.*;
/**
* A special-purpose thread used by Resolvers (both SimpleResolver and
* ExtendedResolver) to perform asynchronous queries.
*
* @author Brian Wellington
*/
class ResolveThread implements Runnable {
private Message query;
private Object id;
private ResolverListener listener;
private Resolver res;
/** Creates a new ResolveThread */
public
ResolveThread(Resolver res, Message query, Object id,
ResolverListener listener)
{
this.res = res;
this.query = query;
this.id = id;
this.listener = listener;
}
/**
* Performs the query, and executes the callback.
*/
public void
run() {
try {
Message response = res.send(query);
listener.receiveMessage(id, response);
}
catch (Exception e) {
listener.handleException(id, e);
}
}
}
|
// Copyright (c) 1999 Brian Wellington ([email protected])
// Portions Copyright (c) 1999 Network Associates, Inc.
package org.xbill.DNS;
import java.util.*;
import java.io.*;
import java.net.*;
/**
* A special-purpose thread used by Resolvers (both SimpleResolver and
* ExtendedResolver) to perform asynchronous queries.
*
* @author Brian Wellington
*/
class ResolveThread extends Thread {
private Message query;
private Object id;
private ResolverListener listener;
private Resolver res;
/** Creates a new ResolveThread */
public
ResolveThread(Resolver res, Message query, Object id,
ResolverListener listener)
{
this.res = res;
this.query = query;
this.id = id;
this.listener = listener;
}
/**
* Performs the query, and executes the callback.
*/
public void
run() {
try {
Message response = res.send(query);
listener.receiveMessage(id, response);
}
catch (Exception e) {
listener.handleException(id, e);
}
}
}
| 1
| 1
| 1
|
mixed
|
--- a/org/xbill/DNS/ResolveThread.java
+++ b/org/xbill/DNS/ResolveThread.java
@@ -16,3 +16,3 @@
-class ResolveThread implements Runnable {
+class ResolveThread extends Thread {
|
--- a/org/xbill/DNS/ResolveThread.java
+++ b/org/xbill/DNS/ResolveThread.java
@@ ... @@
-class ResolveThread implements Runnable {
+class ResolveThread extends Thread {
|
--- a/org/xbill/DNS/ResolveThread.java
+++ b/org/xbill/DNS/ResolveThread.java
@@ -16,3 +16,3 @@
CON
DEL class ResolveThread implements Runnable {
ADD class ResolveThread extends Thread {
CON
|
<<<<<<< SEARCH
*/
class ResolveThread implements Runnable {
private Message query;
=======
*/
class ResolveThread extends Thread {
private Message query;
>>>>>>> REPLACE
|
timve/gatling
|
05d578f08a31142f659babf0a5b7c38e4b0da729
|
gatling-recorder/src/main/java/com/excilys/ebi/gatling/recorder/http/event/PauseEvent.java
|
java
|
apache-2.0
|
Convert pauses longer than 1000 millis into secs
|
/**
* Copyright 2011-2012 eBusiness Information, Groupe Excilys (www.excilys.com)
*
* 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.excilys.ebi.gatling.recorder.http.event;
public class PauseEvent {
private long durationMillis;
public PauseEvent(long durationMillis) {
this.durationMillis = durationMillis;
}
public long getDurationMillis() {
return durationMillis;
}
public String toString() {
return "PAUSE " + durationMillis + " ms";
}
}
|
/**
* Copyright 2011-2012 eBusiness Information, Groupe Excilys (www.excilys.com)
*
* 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.excilys.ebi.gatling.recorder.http.event;
public class PauseEvent {
private long durationMillis;
public PauseEvent(long durationMillis) {
this.durationMillis = durationMillis;
}
public long getDuration() {
if (durationMillis < 1000)
return durationMillis;
else
return Math.round((float) durationMillis / 1000);
}
public String getDurationUnit() {
if (durationMillis < 1000)
return "MILLISECONDS";
else
return "SECONDS";
}
public long getDurationMillis() {
return durationMillis;
}
public String toString() {
return "PAUSE " + getDuration() + " " + getDurationUnit();
}
}
| 15
| 1
| 2
|
mixed
|
--- a/gatling-recorder/src/main/java/com/excilys/ebi/gatling/recorder/http/event/PauseEvent.java
+++ b/gatling-recorder/src/main/java/com/excilys/ebi/gatling/recorder/http/event/PauseEvent.java
@@ -25,2 +25,16 @@
+ public long getDuration() {
+ if (durationMillis < 1000)
+ return durationMillis;
+ else
+ return Math.round((float) durationMillis / 1000);
+ }
+
+ public String getDurationUnit() {
+ if (durationMillis < 1000)
+ return "MILLISECONDS";
+ else
+ return "SECONDS";
+ }
+
public long getDurationMillis() {
@@ -30,3 +44,3 @@
public String toString() {
- return "PAUSE " + durationMillis + " ms";
+ return "PAUSE " + getDuration() + " " + getDurationUnit();
}
|
--- a/gatling-recorder/src/main/java/com/excilys/ebi/gatling/recorder/http/event/PauseEvent.java
+++ b/gatling-recorder/src/main/java/com/excilys/ebi/gatling/recorder/http/event/PauseEvent.java
@@ ... @@
+ public long getDuration() {
+ if (durationMillis < 1000)
+ return durationMillis;
+ else
+ return Math.round((float) durationMillis / 1000);
+ }
+
+ public String getDurationUnit() {
+ if (durationMillis < 1000)
+ return "MILLISECONDS";
+ else
+ return "SECONDS";
+ }
+
public long getDurationMillis() {
@@ ... @@
public String toString() {
- return "PAUSE " + durationMillis + " ms";
+ return "PAUSE " + getDuration() + " " + getDurationUnit();
}
|
--- a/gatling-recorder/src/main/java/com/excilys/ebi/gatling/recorder/http/event/PauseEvent.java
+++ b/gatling-recorder/src/main/java/com/excilys/ebi/gatling/recorder/http/event/PauseEvent.java
@@ -25,2 +25,16 @@
CON
ADD public long getDuration() {
ADD if (durationMillis < 1000)
ADD return durationMillis;
ADD else
ADD return Math.round((float) durationMillis / 1000);
ADD }
ADD
ADD public String getDurationUnit() {
ADD if (durationMillis < 1000)
ADD return "MILLISECONDS";
ADD else
ADD return "SECONDS";
ADD }
ADD
CON public long getDurationMillis() {
@@ -30,3 +44,3 @@
CON public String toString() {
DEL return "PAUSE " + durationMillis + " ms";
ADD return "PAUSE " + getDuration() + " " + getDurationUnit();
CON }
|
<<<<<<< SEARCH
}
public long getDurationMillis() {
return durationMillis;
}
public String toString() {
return "PAUSE " + durationMillis + " ms";
}
}
=======
}
public long getDuration() {
if (durationMillis < 1000)
return durationMillis;
else
return Math.round((float) durationMillis / 1000);
}
public String getDurationUnit() {
if (durationMillis < 1000)
return "MILLISECONDS";
else
return "SECONDS";
}
public long getDurationMillis() {
return durationMillis;
}
public String toString() {
return "PAUSE " + getDuration() + " " + getDurationUnit();
}
}
>>>>>>> REPLACE
|
carlphilipp/chicago-commutes
|
b78795a6e8218759a994881c582abee8b77c3506
|
android-app/src/main/java/fr/cph/chicago/entity/PatternPoint.kt
|
kotlin
|
apache-2.0
|
Remove parecable from pattern point
|
/**
* Copyright 2017 Carl-Philipp Harmant
*
*
* 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 fr.cph.chicago.entity
import android.os.Parcel
import android.os.Parcelable
class PatternPoint(
var position: Position,
var type: String,
var stopName: String? = null) : Parcelable {
private constructor(source: Parcel) : this(
source.readParcelable<Position>(Position::class.java.classLoader),
source.readString(),
source.readString())
override fun describeContents(): Int {
return 0
}
override fun writeToParcel(dest: Parcel, flags: Int) {
dest.writeParcelable(position, flags)
dest.writeString(type)
dest.writeString(stopName)
}
companion object {
@JvmField val CREATOR: Parcelable.Creator<PatternPoint> = object : Parcelable.Creator<PatternPoint> {
override fun createFromParcel(source: Parcel): PatternPoint {
return PatternPoint(source)
}
override fun newArray(size: Int): Array<PatternPoint?> {
return arrayOfNulls(size)
}
}
}
}
|
/**
* Copyright 2017 Carl-Philipp Harmant
*
*
* 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 fr.cph.chicago.entity
class PatternPoint(var position: Position, var type: String, var stopName: String? = null)
| 1
| 36
| 1
|
mixed
|
--- a/android-app/src/main/java/fr/cph/chicago/entity/PatternPoint.kt
+++ b/android-app/src/main/java/fr/cph/chicago/entity/PatternPoint.kt
@@ -21,37 +21,2 @@
-import android.os.Parcel
-import android.os.Parcelable
-
-class PatternPoint(
- var position: Position,
- var type: String,
- var stopName: String? = null) : Parcelable {
-
- private constructor(source: Parcel) : this(
- source.readParcelable<Position>(Position::class.java.classLoader),
- source.readString(),
- source.readString())
-
- override fun describeContents(): Int {
- return 0
- }
-
- override fun writeToParcel(dest: Parcel, flags: Int) {
- dest.writeParcelable(position, flags)
- dest.writeString(type)
- dest.writeString(stopName)
- }
-
- companion object {
-
- @JvmField val CREATOR: Parcelable.Creator<PatternPoint> = object : Parcelable.Creator<PatternPoint> {
- override fun createFromParcel(source: Parcel): PatternPoint {
- return PatternPoint(source)
- }
-
- override fun newArray(size: Int): Array<PatternPoint?> {
- return arrayOfNulls(size)
- }
- }
- }
-}
+class PatternPoint(var position: Position, var type: String, var stopName: String? = null)
|
--- a/android-app/src/main/java/fr/cph/chicago/entity/PatternPoint.kt
+++ b/android-app/src/main/java/fr/cph/chicago/entity/PatternPoint.kt
@@ ... @@
-import android.os.Parcel
-import android.os.Parcelable
-
-class PatternPoint(
- var position: Position,
- var type: String,
- var stopName: String? = null) : Parcelable {
-
- private constructor(source: Parcel) : this(
- source.readParcelable<Position>(Position::class.java.classLoader),
- source.readString(),
- source.readString())
-
- override fun describeContents(): Int {
- return 0
- }
-
- override fun writeToParcel(dest: Parcel, flags: Int) {
- dest.writeParcelable(position, flags)
- dest.writeString(type)
- dest.writeString(stopName)
- }
-
- companion object {
-
- @JvmField val CREATOR: Parcelable.Creator<PatternPoint> = object : Parcelable.Creator<PatternPoint> {
- override fun createFromParcel(source: Parcel): PatternPoint {
- return PatternPoint(source)
- }
-
- override fun newArray(size: Int): Array<PatternPoint?> {
- return arrayOfNulls(size)
- }
- }
- }
-}
+class PatternPoint(var position: Position, var type: String, var stopName: String? = null)
|
--- a/android-app/src/main/java/fr/cph/chicago/entity/PatternPoint.kt
+++ b/android-app/src/main/java/fr/cph/chicago/entity/PatternPoint.kt
@@ -21,37 +21,2 @@
CON
DEL import android.os.Parcel
DEL import android.os.Parcelable
DEL
DEL class PatternPoint(
DEL var position: Position,
DEL var type: String,
DEL var stopName: String? = null) : Parcelable {
DEL
DEL private constructor(source: Parcel) : this(
DEL source.readParcelable<Position>(Position::class.java.classLoader),
DEL source.readString(),
DEL source.readString())
DEL
DEL override fun describeContents(): Int {
DEL return 0
DEL }
DEL
DEL override fun writeToParcel(dest: Parcel, flags: Int) {
DEL dest.writeParcelable(position, flags)
DEL dest.writeString(type)
DEL dest.writeString(stopName)
DEL }
DEL
DEL companion object {
DEL
DEL @JvmField val CREATOR: Parcelable.Creator<PatternPoint> = object : Parcelable.Creator<PatternPoint> {
DEL override fun createFromParcel(source: Parcel): PatternPoint {
DEL return PatternPoint(source)
DEL }
DEL
DEL override fun newArray(size: Int): Array<PatternPoint?> {
DEL return arrayOfNulls(size)
DEL }
DEL }
DEL }
DEL }
ADD class PatternPoint(var position: Position, var type: String, var stopName: String? = null)
|
<<<<<<< SEARCH
package fr.cph.chicago.entity
import android.os.Parcel
import android.os.Parcelable
class PatternPoint(
var position: Position,
var type: String,
var stopName: String? = null) : Parcelable {
private constructor(source: Parcel) : this(
source.readParcelable<Position>(Position::class.java.classLoader),
source.readString(),
source.readString())
override fun describeContents(): Int {
return 0
}
override fun writeToParcel(dest: Parcel, flags: Int) {
dest.writeParcelable(position, flags)
dest.writeString(type)
dest.writeString(stopName)
}
companion object {
@JvmField val CREATOR: Parcelable.Creator<PatternPoint> = object : Parcelable.Creator<PatternPoint> {
override fun createFromParcel(source: Parcel): PatternPoint {
return PatternPoint(source)
}
override fun newArray(size: Int): Array<PatternPoint?> {
return arrayOfNulls(size)
}
}
}
}
=======
package fr.cph.chicago.entity
class PatternPoint(var position: Position, var type: String, var stopName: String? = null)
>>>>>>> REPLACE
|
ruma/ruma
|
c11dfb6b10254318ba0e157866480fcc877f7685
|
crates/ruma-federation-api/src/discovery/get_server_versions.rs
|
rust
|
mit
|
federation-api: Fix link to old matrix-doc repo
|
//! Endpoint to receive metadata about implemented matrix versions.
pub mod msc3723 {
//! [GET /_matrix/federation/versions](https://github.com/matrix-org/matrix-doc/pull/3723)
use ruma_common::api::ruma_api;
ruma_api! {
metadata: {
description: "Get the supported matrix versions of this homeserver",
method: GET,
name: "get_server_versions",
unstable_path: "/_matrix/federation/unstable/org.matrix.msc3723/versions",
rate_limited: false,
authentication: None,
}
#[derive(Default)]
request: {}
#[derive(Default)]
response: {
/// A list of Matrix Server API protocol versions supported by the homeserver.
pub versions: Vec<String>,
}
}
impl Request {
/// Creates an empty `Request`.
pub fn new() -> Self {
Self {}
}
}
impl Response {
/// Creates an empty `Response`.
pub fn new() -> Self {
Default::default()
}
}
}
|
//! Endpoint to receive metadata about implemented matrix versions.
pub mod msc3723 {
//! [GET /_matrix/federation/versions](https://github.com/matrix-org/matrix-spec-proposals/pull/3723)
use ruma_common::api::ruma_api;
ruma_api! {
metadata: {
description: "Get the supported matrix versions of this homeserver",
method: GET,
name: "get_server_versions",
unstable_path: "/_matrix/federation/unstable/org.matrix.msc3723/versions",
rate_limited: false,
authentication: None,
}
#[derive(Default)]
request: {}
#[derive(Default)]
response: {
/// A list of Matrix Server API protocol versions supported by the homeserver.
pub versions: Vec<String>,
}
}
impl Request {
/// Creates an empty `Request`.
pub fn new() -> Self {
Self {}
}
}
impl Response {
/// Creates an empty `Response`.
pub fn new() -> Self {
Default::default()
}
}
}
| 1
| 1
| 1
|
mixed
|
--- a/crates/ruma-federation-api/src/discovery/get_server_versions.rs
+++ b/crates/ruma-federation-api/src/discovery/get_server_versions.rs
@@ -3,3 +3,3 @@
pub mod msc3723 {
- //! [GET /_matrix/federation/versions](https://github.com/matrix-org/matrix-doc/pull/3723)
+ //! [GET /_matrix/federation/versions](https://github.com/matrix-org/matrix-spec-proposals/pull/3723)
|
--- a/crates/ruma-federation-api/src/discovery/get_server_versions.rs
+++ b/crates/ruma-federation-api/src/discovery/get_server_versions.rs
@@ ... @@
pub mod msc3723 {
- //! [GET /_matrix/federation/versions](https://github.com/matrix-org/matrix-doc/pull/3723)
+ //! [GET /_matrix/federation/versions](https://github.com/matrix-org/matrix-spec-proposals/pull/3723)
|
--- a/crates/ruma-federation-api/src/discovery/get_server_versions.rs
+++ b/crates/ruma-federation-api/src/discovery/get_server_versions.rs
@@ -3,3 +3,3 @@
CON pub mod msc3723 {
DEL //! [GET /_matrix/federation/versions](https://github.com/matrix-org/matrix-doc/pull/3723)
ADD //! [GET /_matrix/federation/versions](https://github.com/matrix-org/matrix-spec-proposals/pull/3723)
CON
|
<<<<<<< SEARCH
pub mod msc3723 {
//! [GET /_matrix/federation/versions](https://github.com/matrix-org/matrix-doc/pull/3723)
use ruma_common::api::ruma_api;
=======
pub mod msc3723 {
//! [GET /_matrix/federation/versions](https://github.com/matrix-org/matrix-spec-proposals/pull/3723)
use ruma_common::api::ruma_api;
>>>>>>> REPLACE
|
slightly-askew/portfolio-2017
|
157c9ff7d4629817eea0a2f4bf202ecf7c1a3d1f
|
src/features/header/header-main/nav-main/desktop/styled-components/ListTypes.js
|
javascript
|
mit
|
Remove css hover from nav items - moved to Highlight comp
|
//@flow
import styled, { css } from "styled-components";
export const Ul = styled.ul`
${({ theme }: { theme: Theme }) => css`
padding: 0 0 0 ${theme.scale.s8()};
display: flex;
justify-content: flex-start;
align-items: flex-end;
list-style: none;
margin: 0;
`}
`;
export const Li = styled.li`
${({ theme }: { theme: Theme }) => {
const textColor = theme.color.black;
return css`
${theme.type.paragraph};
color: ${textColor};
font-size: ${theme.scale.s2(-1)};
line-height: ${theme.scale.s8()};
position: relative;
padding: 0 1em;
transition: color 0.2s;
z-index: 1;
&:hover{
cursor: pointer;
color: ${theme.effect.darken(0.2, textColor)};
}
`;
}}
`;
|
//@flow
import styled, { css } from "styled-components";
export const Ul = styled.ul`
${({ theme }: { theme: Theme }) => css`
padding: 0 0 0 ${theme.scale.s8()};
display: flex;
justify-content: flex-start;
align-items: flex-end;
list-style: none;
margin: 0;
`}
`;
export const Li = styled.li`
${({ theme }: { theme: Theme }) => {
const textColor = theme.color.black;
return css`
${theme.type.paragraph};
font-size: ${theme.scale.s2(-1)};
line-height: ${theme.scale.s8()};
position: relative;
padding: 0 1em;
transition: color 0.2s;
z-index: 1;
`;
}}
`;
| 0
| 8
| 2
|
del_only
|
--- a/src/features/header/header-main/nav-main/desktop/styled-components/ListTypes.js
+++ b/src/features/header/header-main/nav-main/desktop/styled-components/ListTypes.js
@@ -22,5 +22,3 @@
return css`
-
${theme.type.paragraph};
- color: ${textColor};
font-size: ${theme.scale.s2(-1)};
@@ -31,8 +29,2 @@
z-index: 1;
-
- &:hover{
- cursor: pointer;
- color: ${theme.effect.darken(0.2, textColor)};
- }
-
`;
|
--- a/src/features/header/header-main/nav-main/desktop/styled-components/ListTypes.js
+++ b/src/features/header/header-main/nav-main/desktop/styled-components/ListTypes.js
@@ ... @@
return css`
-
${theme.type.paragraph};
- color: ${textColor};
font-size: ${theme.scale.s2(-1)};
@@ ... @@
z-index: 1;
-
- &:hover{
- cursor: pointer;
- color: ${theme.effect.darken(0.2, textColor)};
- }
-
`;
|
--- a/src/features/header/header-main/nav-main/desktop/styled-components/ListTypes.js
+++ b/src/features/header/header-main/nav-main/desktop/styled-components/ListTypes.js
@@ -22,5 +22,3 @@
CON return css`
DEL
CON ${theme.type.paragraph};
DEL color: ${textColor};
CON font-size: ${theme.scale.s2(-1)};
@@ -31,8 +29,2 @@
CON z-index: 1;
DEL
DEL &:hover{
DEL cursor: pointer;
DEL color: ${theme.effect.darken(0.2, textColor)};
DEL }
DEL
CON `;
|
<<<<<<< SEARCH
return css`
${theme.type.paragraph};
color: ${textColor};
font-size: ${theme.scale.s2(-1)};
line-height: ${theme.scale.s8()};
=======
return css`
${theme.type.paragraph};
font-size: ${theme.scale.s2(-1)};
line-height: ${theme.scale.s8()};
>>>>>>> REPLACE
<<<<<<< SEARCH
transition: color 0.2s;
z-index: 1;
&:hover{
cursor: pointer;
color: ${theme.effect.darken(0.2, textColor)};
}
`;
}}
=======
transition: color 0.2s;
z-index: 1;
`;
}}
>>>>>>> REPLACE
|
gpodder/mygpo
|
6618b12cef2759174148d1c7f69cbb91b8ea4482
|
mygpo/podcasts/migrations/0015_auto_20140616_2126.py
|
python
|
agpl-3.0
|
[DB] Fix data migration when making scope non-null
|
# encoding: utf8
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('podcasts', '0014_auto_20140615_1032'),
]
operations = [
migrations.AlterField(
model_name='slug',
name='scope',
field=models.CharField(db_index=True, max_length=32, blank=True),
),
migrations.AlterField(
model_name='url',
name='scope',
field=models.CharField(db_index=True, max_length=32, blank=True),
),
]
|
# encoding: utf8
from __future__ import unicode_literals
from django.db import models, migrations
def set_scope(apps, schema_editor):
URL = apps.get_model('podcasts', 'URL')
Slug = apps.get_model('podcasts', 'Slug')
URL.objects.filter(scope__isnull=True).update(scope='')
Slug.objects.filter(scope__isnull=True).update(scope='')
class Migration(migrations.Migration):
dependencies = [
('podcasts', '0014_auto_20140615_1032'),
]
operations = [
migrations.AlterField(
model_name='slug',
name='scope',
field=models.CharField(db_index=True, max_length=32, blank=True, null=True),
),
migrations.AlterField(
model_name='url',
name='scope',
field=models.CharField(db_index=True, max_length=32, blank=True, null=True),
),
migrations.RunPython(set_scope),
migrations.AlterField(
model_name='slug',
name='scope',
field=models.CharField(db_index=True, max_length=32, blank=True, null=False),
),
migrations.AlterField(
model_name='url',
name='scope',
field=models.CharField(db_index=True, max_length=32, blank=True, null=False),
),
]
| 22
| 2
| 3
|
mixed
|
--- a/mygpo/podcasts/migrations/0015_auto_20140616_2126.py
+++ b/mygpo/podcasts/migrations/0015_auto_20140616_2126.py
@@ -4,2 +4,10 @@
from django.db import models, migrations
+
+
+def set_scope(apps, schema_editor):
+ URL = apps.get_model('podcasts', 'URL')
+ Slug = apps.get_model('podcasts', 'Slug')
+
+ URL.objects.filter(scope__isnull=True).update(scope='')
+ Slug.objects.filter(scope__isnull=True).update(scope='')
@@ -16,3 +24,3 @@
name='scope',
- field=models.CharField(db_index=True, max_length=32, blank=True),
+ field=models.CharField(db_index=True, max_length=32, blank=True, null=True),
),
@@ -21,4 +29,16 @@
name='scope',
- field=models.CharField(db_index=True, max_length=32, blank=True),
+ field=models.CharField(db_index=True, max_length=32, blank=True, null=True),
),
+ migrations.RunPython(set_scope),
+ migrations.AlterField(
+ model_name='slug',
+ name='scope',
+ field=models.CharField(db_index=True, max_length=32, blank=True, null=False),
+ ),
+ migrations.AlterField(
+ model_name='url',
+ name='scope',
+ field=models.CharField(db_index=True, max_length=32, blank=True, null=False),
+ ),
+
]
|
--- a/mygpo/podcasts/migrations/0015_auto_20140616_2126.py
+++ b/mygpo/podcasts/migrations/0015_auto_20140616_2126.py
@@ ... @@
from django.db import models, migrations
+
+
+def set_scope(apps, schema_editor):
+ URL = apps.get_model('podcasts', 'URL')
+ Slug = apps.get_model('podcasts', 'Slug')
+
+ URL.objects.filter(scope__isnull=True).update(scope='')
+ Slug.objects.filter(scope__isnull=True).update(scope='')
@@ ... @@
name='scope',
- field=models.CharField(db_index=True, max_length=32, blank=True),
+ field=models.CharField(db_index=True, max_length=32, blank=True, null=True),
),
@@ ... @@
name='scope',
- field=models.CharField(db_index=True, max_length=32, blank=True),
+ field=models.CharField(db_index=True, max_length=32, blank=True, null=True),
),
+ migrations.RunPython(set_scope),
+ migrations.AlterField(
+ model_name='slug',
+ name='scope',
+ field=models.CharField(db_index=True, max_length=32, blank=True, null=False),
+ ),
+ migrations.AlterField(
+ model_name='url',
+ name='scope',
+ field=models.CharField(db_index=True, max_length=32, blank=True, null=False),
+ ),
+
]
|
--- a/mygpo/podcasts/migrations/0015_auto_20140616_2126.py
+++ b/mygpo/podcasts/migrations/0015_auto_20140616_2126.py
@@ -4,2 +4,10 @@
CON from django.db import models, migrations
ADD
ADD
ADD def set_scope(apps, schema_editor):
ADD URL = apps.get_model('podcasts', 'URL')
ADD Slug = apps.get_model('podcasts', 'Slug')
ADD
ADD URL.objects.filter(scope__isnull=True).update(scope='')
ADD Slug.objects.filter(scope__isnull=True).update(scope='')
CON
@@ -16,3 +24,3 @@
CON name='scope',
DEL field=models.CharField(db_index=True, max_length=32, blank=True),
ADD field=models.CharField(db_index=True, max_length=32, blank=True, null=True),
CON ),
@@ -21,4 +29,16 @@
CON name='scope',
DEL field=models.CharField(db_index=True, max_length=32, blank=True),
ADD field=models.CharField(db_index=True, max_length=32, blank=True, null=True),
CON ),
ADD migrations.RunPython(set_scope),
ADD migrations.AlterField(
ADD model_name='slug',
ADD name='scope',
ADD field=models.CharField(db_index=True, max_length=32, blank=True, null=False),
ADD ),
ADD migrations.AlterField(
ADD model_name='url',
ADD name='scope',
ADD field=models.CharField(db_index=True, max_length=32, blank=True, null=False),
ADD ),
ADD
CON ]
|
<<<<<<< SEARCH
from django.db import models, migrations
=======
from django.db import models, migrations
def set_scope(apps, schema_editor):
URL = apps.get_model('podcasts', 'URL')
Slug = apps.get_model('podcasts', 'Slug')
URL.objects.filter(scope__isnull=True).update(scope='')
Slug.objects.filter(scope__isnull=True).update(scope='')
>>>>>>> REPLACE
<<<<<<< SEARCH
model_name='slug',
name='scope',
field=models.CharField(db_index=True, max_length=32, blank=True),
),
migrations.AlterField(
model_name='url',
name='scope',
field=models.CharField(db_index=True, max_length=32, blank=True),
),
]
=======
model_name='slug',
name='scope',
field=models.CharField(db_index=True, max_length=32, blank=True, null=True),
),
migrations.AlterField(
model_name='url',
name='scope',
field=models.CharField(db_index=True, max_length=32, blank=True, null=True),
),
migrations.RunPython(set_scope),
migrations.AlterField(
model_name='slug',
name='scope',
field=models.CharField(db_index=True, max_length=32, blank=True, null=False),
),
migrations.AlterField(
model_name='url',
name='scope',
field=models.CharField(db_index=True, max_length=32, blank=True, null=False),
),
]
>>>>>>> REPLACE
|
petergeneric/stdlib
|
8208f619605e312a500c11470e9f4a4b08f182b6
|
guice/webapp/src/main/java/com/peterphi/std/guice/web/rest/templating/thymeleaf/ThymeleafCurrentUserUtils.java
|
java
|
mit
|
Allow currentUser.username, etc. from within templates (rather than currentUser.user.username)
|
package com.peterphi.std.guice.web.rest.templating.thymeleaf;
import com.google.inject.Provider;
import com.peterphi.std.guice.common.auth.iface.CurrentUser;
import org.joda.time.DateTime;
import java.time.Instant;
import java.util.Date;
public class ThymeleafCurrentUserUtils
{
private final Provider<CurrentUser> provider;
public ThymeleafCurrentUserUtils(final Provider<CurrentUser> provider)
{
this.provider = provider;
}
public boolean hasRole(String role)
{
return getUser().hasRole(role);
}
public String getAuthType()
{
return getUser().getAuthType();
}
public CurrentUser getUser()
{
return provider.get();
}
public boolean isAnonymous()
{
return getUser().isAnonymous();
}
public String format(DateTime date)
{
return getUser().format(date);
}
public String format(Date date)
{
return getUser().format(date);
}
public String format(Instant date)
{
return getUser().format(date);
}
public String format(Long date)
{
if (date == null)
return format((DateTime) null);
else
return format(new DateTime(date));
}
}
|
package com.peterphi.std.guice.web.rest.templating.thymeleaf;
import com.google.inject.Provider;
import com.peterphi.std.guice.common.auth.iface.CurrentUser;
import org.joda.time.DateTime;
import java.time.Instant;
import java.util.Date;
public class ThymeleafCurrentUserUtils
{
private final Provider<CurrentUser> provider;
public ThymeleafCurrentUserUtils(final Provider<CurrentUser> provider)
{
this.provider = provider;
}
public boolean hasRole(String role)
{
return getUser().hasRole(role);
}
public String getAuthType()
{
return getUser().getAuthType();
}
public CurrentUser getUser()
{
return provider.get();
}
public String getName()
{
return getUser().getName();
}
public String getUsername()
{
return getUser().getUsername();
}
public DateTime getExpires()
{
return getUser().getExpires();
}
public boolean isAnonymous()
{
return getUser().isAnonymous();
}
public String format(DateTime date)
{
return getUser().format(date);
}
public String format(Date date)
{
return getUser().format(date);
}
public String format(Instant date)
{
return getUser().format(date);
}
public String format(Long date)
{
if (date == null)
return format((DateTime) null);
else
return format(new DateTime(date));
}
}
| 18
| 0
| 1
|
add_only
|
--- a/guice/webapp/src/main/java/com/peterphi/std/guice/web/rest/templating/thymeleaf/ThymeleafCurrentUserUtils.java
+++ b/guice/webapp/src/main/java/com/peterphi/std/guice/web/rest/templating/thymeleaf/ThymeleafCurrentUserUtils.java
@@ -38,2 +38,20 @@
+ public String getName()
+ {
+ return getUser().getName();
+ }
+
+
+ public String getUsername()
+ {
+ return getUser().getUsername();
+ }
+
+
+ public DateTime getExpires()
+ {
+ return getUser().getExpires();
+ }
+
+
public boolean isAnonymous()
|
--- a/guice/webapp/src/main/java/com/peterphi/std/guice/web/rest/templating/thymeleaf/ThymeleafCurrentUserUtils.java
+++ b/guice/webapp/src/main/java/com/peterphi/std/guice/web/rest/templating/thymeleaf/ThymeleafCurrentUserUtils.java
@@ ... @@
+ public String getName()
+ {
+ return getUser().getName();
+ }
+
+
+ public String getUsername()
+ {
+ return getUser().getUsername();
+ }
+
+
+ public DateTime getExpires()
+ {
+ return getUser().getExpires();
+ }
+
+
public boolean isAnonymous()
|
--- a/guice/webapp/src/main/java/com/peterphi/std/guice/web/rest/templating/thymeleaf/ThymeleafCurrentUserUtils.java
+++ b/guice/webapp/src/main/java/com/peterphi/std/guice/web/rest/templating/thymeleaf/ThymeleafCurrentUserUtils.java
@@ -38,2 +38,20 @@
CON
ADD public String getName()
ADD {
ADD return getUser().getName();
ADD }
ADD
ADD
ADD public String getUsername()
ADD {
ADD return getUser().getUsername();
ADD }
ADD
ADD
ADD public DateTime getExpires()
ADD {
ADD return getUser().getExpires();
ADD }
ADD
ADD
CON public boolean isAnonymous()
|
<<<<<<< SEARCH
public boolean isAnonymous()
{
=======
public String getName()
{
return getUser().getName();
}
public String getUsername()
{
return getUser().getUsername();
}
public DateTime getExpires()
{
return getUser().getExpires();
}
public boolean isAnonymous()
{
>>>>>>> REPLACE
|
LouisCAD/Splitties
|
a6fb7b605dd14bb3de504801cdeb9420410eb839
|
modules/views-dsl/build.gradle.kts
|
kotlin
|
apache-2.0
|
Use old Kotlin JVM compiler backend for views-dsl module
|
/*
* 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 {
enableLanguageFeature("InlineClasses")
useExperimentalAnnotation("kotlin.RequiresOptIn")
useExperimentalAnnotation("kotlin.contracts.ExperimentalContracts")
useExperimentalAnnotation("splitties.experimental.InternalSplittiesApi")
}
}
}
}
|
/*
* 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 {
enableLanguageFeature("InlineClasses")
useExperimentalAnnotation("kotlin.RequiresOptIn")
useExperimentalAnnotation("kotlin.contracts.ExperimentalContracts")
useExperimentalAnnotation("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
}
| 5
| 0
| 1
|
add_only
|
--- a/modules/views-dsl/build.gradle.kts
+++ b/modules/views-dsl/build.gradle.kts
@@ -38 +38,6 @@
}
+
+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
@@ -38 +38,6 @@
CON }
ADD
ADD tasks.withType<org.jetbrains.kotlin.gradle.tasks.KotlinCompile> {
ADD kotlinOptions.useOldBackend = true //TODO: Remove when https://youtrack.jetbrains.com/issue/KT-44972 is addressed.
ADD // See this comment on why it's needed: https://youtrack.jetbrains.com/issue/KT-44972#focus=Comments-27-5014161.0-0
ADD }
|
<<<<<<< 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
|
EvidentSolutions/apina
|
1996083e58f308dfa42ff315ea15b7dba8326679
|
apina-core/src/main/java/fi/evident/apina/model/settings/TranslationSettings.java
|
java
|
mit
|
Allow multiple types to be imported with single call
Since both the command line client and the Gradle task support
specifying multiple imports from a module with a shorthand syntax, it
makes things simpler for callers to allow passing multiple types in a
single addImport-call.
|
package fi.evident.apina.model.settings;
import fi.evident.apina.utils.PatternSet;
import java.util.Collection;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import static java.util.Collections.unmodifiableCollection;
/**
* Various settings guiding the translation.
*/
public final class TranslationSettings {
public final PatternSet blackBoxClasses = new PatternSet();
private final TreeMap<String, ImportDefinition> importsByModule = new TreeMap<>();
private final Set<String> importedTypes = new TreeSet<>();
public boolean isBlackBoxClass(String name) {
return blackBoxClasses.test(name);
}
public void addImport(String typeName, String moduleName) {
if (!importedTypes.add(typeName))
throw new IllegalArgumentException("type " + typeName + " is already imported");
importsByModule.computeIfAbsent(moduleName, ImportDefinition::new).addType(typeName);
}
public Collection<ImportDefinition> getImports() {
return unmodifiableCollection(importsByModule.values());
}
public boolean isImported(String typeName) {
return importedTypes.contains(typeName);
}
}
|
package fi.evident.apina.model.settings;
import fi.evident.apina.utils.PatternSet;
import java.util.Collection;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import static java.util.Collections.unmodifiableCollection;
/**
* Various settings guiding the translation.
*/
public final class TranslationSettings {
public final PatternSet blackBoxClasses = new PatternSet();
private final TreeMap<String, ImportDefinition> importsByModule = new TreeMap<>();
private final Set<String> importedTypes = new TreeSet<>();
public boolean isBlackBoxClass(String name) {
return blackBoxClasses.test(name);
}
public void addImport(String moduleName, Collection<String> types) {
ImportDefinition importDefinition = importsByModule.computeIfAbsent(moduleName, ImportDefinition::new);
for (String type : types) {
if (!importedTypes.add(type))
throw new IllegalArgumentException("type " + type + " is already imported");
importDefinition.addType(type);
}
}
public Collection<ImportDefinition> getImports() {
return unmodifiableCollection(importsByModule.values());
}
public boolean isImported(String typeName) {
return importedTypes.contains(typeName);
}
}
| 8
| 4
| 1
|
mixed
|
--- a/apina-core/src/main/java/fi/evident/apina/model/settings/TranslationSettings.java
+++ b/apina-core/src/main/java/fi/evident/apina/model/settings/TranslationSettings.java
@@ -24,7 +24,11 @@
- public void addImport(String typeName, String moduleName) {
- if (!importedTypes.add(typeName))
- throw new IllegalArgumentException("type " + typeName + " is already imported");
+ public void addImport(String moduleName, Collection<String> types) {
+ ImportDefinition importDefinition = importsByModule.computeIfAbsent(moduleName, ImportDefinition::new);
- importsByModule.computeIfAbsent(moduleName, ImportDefinition::new).addType(typeName);
+ for (String type : types) {
+ if (!importedTypes.add(type))
+ throw new IllegalArgumentException("type " + type + " is already imported");
+
+ importDefinition.addType(type);
+ }
}
|
--- a/apina-core/src/main/java/fi/evident/apina/model/settings/TranslationSettings.java
+++ b/apina-core/src/main/java/fi/evident/apina/model/settings/TranslationSettings.java
@@ ... @@
- public void addImport(String typeName, String moduleName) {
- if (!importedTypes.add(typeName))
- throw new IllegalArgumentException("type " + typeName + " is already imported");
+ public void addImport(String moduleName, Collection<String> types) {
+ ImportDefinition importDefinition = importsByModule.computeIfAbsent(moduleName, ImportDefinition::new);
- importsByModule.computeIfAbsent(moduleName, ImportDefinition::new).addType(typeName);
+ for (String type : types) {
+ if (!importedTypes.add(type))
+ throw new IllegalArgumentException("type " + type + " is already imported");
+
+ importDefinition.addType(type);
+ }
}
|
--- a/apina-core/src/main/java/fi/evident/apina/model/settings/TranslationSettings.java
+++ b/apina-core/src/main/java/fi/evident/apina/model/settings/TranslationSettings.java
@@ -24,7 +24,11 @@
CON
DEL public void addImport(String typeName, String moduleName) {
DEL if (!importedTypes.add(typeName))
DEL throw new IllegalArgumentException("type " + typeName + " is already imported");
ADD public void addImport(String moduleName, Collection<String> types) {
ADD ImportDefinition importDefinition = importsByModule.computeIfAbsent(moduleName, ImportDefinition::new);
CON
DEL importsByModule.computeIfAbsent(moduleName, ImportDefinition::new).addType(typeName);
ADD for (String type : types) {
ADD if (!importedTypes.add(type))
ADD throw new IllegalArgumentException("type " + type + " is already imported");
ADD
ADD importDefinition.addType(type);
ADD }
CON }
|
<<<<<<< SEARCH
}
public void addImport(String typeName, String moduleName) {
if (!importedTypes.add(typeName))
throw new IllegalArgumentException("type " + typeName + " is already imported");
importsByModule.computeIfAbsent(moduleName, ImportDefinition::new).addType(typeName);
}
=======
}
public void addImport(String moduleName, Collection<String> types) {
ImportDefinition importDefinition = importsByModule.computeIfAbsent(moduleName, ImportDefinition::new);
for (String type : types) {
if (!importedTypes.add(type))
throw new IllegalArgumentException("type " + type + " is already imported");
importDefinition.addType(type);
}
}
>>>>>>> REPLACE
|
ItsPriyesh/HexaTime
|
38f235710b2036d94852b4d8090189d1915a5206
|
app/src/main/kotlin/com/priyesh/hexatime/core/Background.kt
|
kotlin
|
apache-2.0
|
Remove dimming (will be replaced by lightness in HSL mode)
|
/*
* Copyright 2015 Priyesh Patel
*
* 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.priyesh.hexatime.core
import android.content.SharedPreferences
import android.graphics.Color
import android.preference.PreferenceManager
import android.support.v4.graphics.ColorUtils
import com.priyesh.hexatime.log
public class Background(clock: Clock) : PreferenceDelegate {
private val clock = clock
private var dimAmount: Int = 0
init {
initializeFromPrefs(PreferenceManager.getDefaultSharedPreferences(clock.getContext()))
}
private fun initializeFromPrefs(prefs: SharedPreferences) {
// dimAmount = prefs.getInt(KEY_BACKGROUND_DIM, 0)
}
private fun getDimColor(): Int {
log("Dim amount: " + dimAmount)
return Color.argb(dimAmount / 100 * 255, 0, 0, 0)
}
override fun onPreferenceChange(prefs: SharedPreferences, key: String) {
when (key) {
// KEY_BACKGROUND_DIM -> dimAmount = prefs.getInt(KEY_BACKGROUND_DIM, 0)
}
}
public fun getColor(): Int = clock.getColor()
}
|
/*
* Copyright 2015 Priyesh Patel
*
* 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.priyesh.hexatime.core
import android.content.SharedPreferences
import android.graphics.Color
import android.preference.PreferenceManager
import android.support.v4.graphics.ColorUtils
import com.priyesh.hexatime.log
public class Background(clock: Clock) : PreferenceDelegate {
private val clock = clock
init {
initializeFromPrefs(PreferenceManager.getDefaultSharedPreferences(clock.getContext()))
}
private fun initializeFromPrefs(prefs: SharedPreferences) {
}
override fun onPreferenceChange(prefs: SharedPreferences, key: String) {
when (key) {
}
}
public fun getColor(): Int = clock.getColor()
}
| 1
| 8
| 3
|
mixed
|
--- a/app/src/main/kotlin/com/priyesh/hexatime/core/Background.kt
+++ b/app/src/main/kotlin/com/priyesh/hexatime/core/Background.kt
@@ -27,3 +27,2 @@
private val clock = clock
- private var dimAmount: Int = 0
@@ -34,8 +33,2 @@
private fun initializeFromPrefs(prefs: SharedPreferences) {
- // dimAmount = prefs.getInt(KEY_BACKGROUND_DIM, 0)
- }
-
- private fun getDimColor(): Int {
- log("Dim amount: " + dimAmount)
- return Color.argb(dimAmount / 100 * 255, 0, 0, 0)
}
@@ -44,3 +37,3 @@
when (key) {
- // KEY_BACKGROUND_DIM -> dimAmount = prefs.getInt(KEY_BACKGROUND_DIM, 0)
+
}
|
--- a/app/src/main/kotlin/com/priyesh/hexatime/core/Background.kt
+++ b/app/src/main/kotlin/com/priyesh/hexatime/core/Background.kt
@@ ... @@
private val clock = clock
- private var dimAmount: Int = 0
@@ ... @@
private fun initializeFromPrefs(prefs: SharedPreferences) {
- // dimAmount = prefs.getInt(KEY_BACKGROUND_DIM, 0)
- }
-
- private fun getDimColor(): Int {
- log("Dim amount: " + dimAmount)
- return Color.argb(dimAmount / 100 * 255, 0, 0, 0)
}
@@ ... @@
when (key) {
- // KEY_BACKGROUND_DIM -> dimAmount = prefs.getInt(KEY_BACKGROUND_DIM, 0)
+
}
|
--- a/app/src/main/kotlin/com/priyesh/hexatime/core/Background.kt
+++ b/app/src/main/kotlin/com/priyesh/hexatime/core/Background.kt
@@ -27,3 +27,2 @@
CON private val clock = clock
DEL private var dimAmount: Int = 0
CON
@@ -34,8 +33,2 @@
CON private fun initializeFromPrefs(prefs: SharedPreferences) {
DEL // dimAmount = prefs.getInt(KEY_BACKGROUND_DIM, 0)
DEL }
DEL
DEL private fun getDimColor(): Int {
DEL log("Dim amount: " + dimAmount)
DEL return Color.argb(dimAmount / 100 * 255, 0, 0, 0)
CON }
@@ -44,3 +37,3 @@
CON when (key) {
DEL // KEY_BACKGROUND_DIM -> dimAmount = prefs.getInt(KEY_BACKGROUND_DIM, 0)
ADD
CON }
|
<<<<<<< SEARCH
private val clock = clock
private var dimAmount: Int = 0
init {
=======
private val clock = clock
init {
>>>>>>> REPLACE
<<<<<<< SEARCH
private fun initializeFromPrefs(prefs: SharedPreferences) {
// dimAmount = prefs.getInt(KEY_BACKGROUND_DIM, 0)
}
private fun getDimColor(): Int {
log("Dim amount: " + dimAmount)
return Color.argb(dimAmount / 100 * 255, 0, 0, 0)
}
override fun onPreferenceChange(prefs: SharedPreferences, key: String) {
when (key) {
// KEY_BACKGROUND_DIM -> dimAmount = prefs.getInt(KEY_BACKGROUND_DIM, 0)
}
}
=======
private fun initializeFromPrefs(prefs: SharedPreferences) {
}
override fun onPreferenceChange(prefs: SharedPreferences, key: String) {
when (key) {
}
}
>>>>>>> REPLACE
|
Dart-Code/Dart-Code
|
4d25226f2f0b2240ed4beb8737f9c83323a1a016
|
webpack.config.js
|
javascript
|
mit
|
Add a note about webpack warnings
|
//@ts-check
"use strict";
const path = require("path");
/**
* @type {import("webpack").Configuration}
*/
const config = {
devtool: "source-map",
entry: "./src/extension/extension.ts",
// https://webpack.js.org/configuration/externals/
externals: {
vscode: "commonjs vscode",
},
module: {
rules: [{
exclude: /node_modules/,
test: /\.ts$/,
use: [{
loader: "ts-loader",
}],
}],
},
output: {
devtoolModuleFilenameTemplate: "../[resource-path]",
filename: "extension.js",
libraryTarget: "commonjs2",
path: path.resolve(__dirname, "out/dist"),
},
resolve: {
extensions: [".ts", ".js"],
},
target: "node",
};
module.exports = config;
|
//@ts-check
"use strict";
// Webpack will output the following warnings when building:
//
// WARNING in ./node_modules/ws/lib/buffer-util.js
// Module not found: Error: Can't resolve 'bufferutil' in '/Users/dantup/Dev/Dart-Code/node_modules/ws/lib'
//
// WARNING in ./node_modules/ws/lib/validation.js
// Module not found: Error: Can't resolve 'utf-8-validate' in '/Users/dantup/Dev/Dart-Code/node_modules/ws/lib'
//
// These are caused by ws require()ing those two modules and they're not listed
// in our dependencies. Info on the reason for this is here:
// https://github.com/websockets/ws/blob/5d751fbd4c0ab3478a6de4194d4d06908bc8ac00/README.md#opt-in-for-performance-and-spec-compliance
//
// It appears to be safe to ignore these as they're being loaded in a try{} block
// and are optional.
const path = require("path");
/**
* @type {import("webpack").Configuration}
*/
const config = {
devtool: "source-map",
entry: "./src/extension/extension.ts",
// https://webpack.js.org/configuration/externals/
externals: {
vscode: "commonjs vscode",
},
module: {
rules: [{
exclude: /node_modules/,
test: /\.ts$/,
use: [{
loader: "ts-loader",
}],
}],
},
output: {
devtoolModuleFilenameTemplate: "../[resource-path]",
filename: "extension.js",
libraryTarget: "commonjs2",
path: path.resolve(__dirname, "out/dist"),
},
resolve: {
extensions: [".ts", ".js"],
},
target: "node",
};
module.exports = config;
| 15
| 0
| 1
|
add_only
|
--- a/webpack.config.js
+++ b/webpack.config.js
@@ -3,2 +3,17 @@
"use strict";
+
+// Webpack will output the following warnings when building:
+//
+// WARNING in ./node_modules/ws/lib/buffer-util.js
+// Module not found: Error: Can't resolve 'bufferutil' in '/Users/dantup/Dev/Dart-Code/node_modules/ws/lib'
+//
+// WARNING in ./node_modules/ws/lib/validation.js
+// Module not found: Error: Can't resolve 'utf-8-validate' in '/Users/dantup/Dev/Dart-Code/node_modules/ws/lib'
+//
+// These are caused by ws require()ing those two modules and they're not listed
+// in our dependencies. Info on the reason for this is here:
+// https://github.com/websockets/ws/blob/5d751fbd4c0ab3478a6de4194d4d06908bc8ac00/README.md#opt-in-for-performance-and-spec-compliance
+//
+// It appears to be safe to ignore these as they're being loaded in a try{} block
+// and are optional.
|
--- a/webpack.config.js
+++ b/webpack.config.js
@@ ... @@
"use strict";
+
+// Webpack will output the following warnings when building:
+//
+// WARNING in ./node_modules/ws/lib/buffer-util.js
+// Module not found: Error: Can't resolve 'bufferutil' in '/Users/dantup/Dev/Dart-Code/node_modules/ws/lib'
+//
+// WARNING in ./node_modules/ws/lib/validation.js
+// Module not found: Error: Can't resolve 'utf-8-validate' in '/Users/dantup/Dev/Dart-Code/node_modules/ws/lib'
+//
+// These are caused by ws require()ing those two modules and they're not listed
+// in our dependencies. Info on the reason for this is here:
+// https://github.com/websockets/ws/blob/5d751fbd4c0ab3478a6de4194d4d06908bc8ac00/README.md#opt-in-for-performance-and-spec-compliance
+//
+// It appears to be safe to ignore these as they're being loaded in a try{} block
+// and are optional.
|
--- a/webpack.config.js
+++ b/webpack.config.js
@@ -3,2 +3,17 @@
CON "use strict";
ADD
ADD // Webpack will output the following warnings when building:
ADD //
ADD // WARNING in ./node_modules/ws/lib/buffer-util.js
ADD // Module not found: Error: Can't resolve 'bufferutil' in '/Users/dantup/Dev/Dart-Code/node_modules/ws/lib'
ADD //
ADD // WARNING in ./node_modules/ws/lib/validation.js
ADD // Module not found: Error: Can't resolve 'utf-8-validate' in '/Users/dantup/Dev/Dart-Code/node_modules/ws/lib'
ADD //
ADD // These are caused by ws require()ing those two modules and they're not listed
ADD // in our dependencies. Info on the reason for this is here:
ADD // https://github.com/websockets/ws/blob/5d751fbd4c0ab3478a6de4194d4d06908bc8ac00/README.md#opt-in-for-performance-and-spec-compliance
ADD //
ADD // It appears to be safe to ignore these as they're being loaded in a try{} block
ADD // and are optional.
CON
|
<<<<<<< SEARCH
"use strict";
const path = require("path");
=======
"use strict";
// Webpack will output the following warnings when building:
//
// WARNING in ./node_modules/ws/lib/buffer-util.js
// Module not found: Error: Can't resolve 'bufferutil' in '/Users/dantup/Dev/Dart-Code/node_modules/ws/lib'
//
// WARNING in ./node_modules/ws/lib/validation.js
// Module not found: Error: Can't resolve 'utf-8-validate' in '/Users/dantup/Dev/Dart-Code/node_modules/ws/lib'
//
// These are caused by ws require()ing those two modules and they're not listed
// in our dependencies. Info on the reason for this is here:
// https://github.com/websockets/ws/blob/5d751fbd4c0ab3478a6de4194d4d06908bc8ac00/README.md#opt-in-for-performance-and-spec-compliance
//
// It appears to be safe to ignore these as they're being loaded in a try{} block
// and are optional.
const path = require("path");
>>>>>>> REPLACE
|
JuanmaBM/Spring-Factory
|
5ad13b3321de06f72dbf87840360e2d09f66ed74
|
src/main/java/com/jmb/springfactory/service/productionschedule/ProductionScheduleServiceImpl.java
|
java
|
apache-2.0
|
Set schedule status as OPEN when it is created
|
package com.jmb.springfactory.service.productionschedule;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.jmb.springfactory.dao.GenericMySQLService;
import com.jmb.springfactory.dao.productionschedule.ProductionScheduleMySQLService;
import com.jmb.springfactory.model.bo.BusinessObjectBase;
import com.jmb.springfactory.model.dto.ProductionScheduleDto;
import com.jmb.springfactory.model.entity.ProductionSchedule;
import com.jmb.springfactory.service.GenericServiceImpl;
@Service
public class ProductionScheduleServiceImpl extends GenericServiceImpl<ProductionSchedule, ProductionScheduleDto,
BusinessObjectBase, Integer> implements ProductionScheduleService {
@Autowired
private ProductionScheduleMySQLService productionScheduleMySQLService;
@Override
public GenericMySQLService<ProductionSchedule, Integer> genericDao() {
return productionScheduleMySQLService;
}
@Override
public Class<? extends ProductionSchedule> getClazz() {
return ProductionSchedule.class;
}
@Override
public Class<? extends ProductionScheduleDto> getDtoClazz() {
return ProductionScheduleDto.class;
}
@Override
public Class<? extends BusinessObjectBase> getBoClazz() {
return BusinessObjectBase.class;
}
}
|
package com.jmb.springfactory.service.productionschedule;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.jmb.springfactory.dao.GenericMySQLService;
import com.jmb.springfactory.dao.productionschedule.ProductionScheduleMySQLService;
import com.jmb.springfactory.exceptions.ServiceLayerException;
import com.jmb.springfactory.model.bo.BusinessObjectBase;
import com.jmb.springfactory.model.dto.ProductionScheduleDto;
import com.jmb.springfactory.model.entity.ProductionSchedule;
import com.jmb.springfactory.model.enumeration.ProductionScheduleStateEnum;
import com.jmb.springfactory.service.GenericServiceImpl;
@Service
public class ProductionScheduleServiceImpl extends GenericServiceImpl<ProductionSchedule, ProductionScheduleDto,
BusinessObjectBase, Integer> implements ProductionScheduleService {
@Autowired
private ProductionScheduleMySQLService productionScheduleMySQLService;
@Override
public GenericMySQLService<ProductionSchedule, Integer> genericDao() {
return productionScheduleMySQLService;
}
@Override
public Class<? extends ProductionSchedule> getClazz() {
return ProductionSchedule.class;
}
@Override
public Class<? extends ProductionScheduleDto> getDtoClazz() {
return ProductionScheduleDto.class;
}
@Override
public Class<? extends BusinessObjectBase> getBoClazz() {
return BusinessObjectBase.class;
}
@Override
public ProductionScheduleDto save(ProductionScheduleDto schedule) throws ServiceLayerException {
schedule.setState(ProductionScheduleStateEnum.OPEN.name());
return super.save(schedule);
}
}
| 8
| 0
| 3
|
add_only
|
--- a/src/main/java/com/jmb/springfactory/service/productionschedule/ProductionScheduleServiceImpl.java
+++ b/src/main/java/com/jmb/springfactory/service/productionschedule/ProductionScheduleServiceImpl.java
@@ -7,2 +7,3 @@
import com.jmb.springfactory.dao.productionschedule.ProductionScheduleMySQLService;
+import com.jmb.springfactory.exceptions.ServiceLayerException;
import com.jmb.springfactory.model.bo.BusinessObjectBase;
@@ -10,2 +11,3 @@
import com.jmb.springfactory.model.entity.ProductionSchedule;
+import com.jmb.springfactory.model.enumeration.ProductionScheduleStateEnum;
import com.jmb.springfactory.service.GenericServiceImpl;
@@ -38,2 +40,8 @@
}
+
+ @Override
+ public ProductionScheduleDto save(ProductionScheduleDto schedule) throws ServiceLayerException {
+ schedule.setState(ProductionScheduleStateEnum.OPEN.name());
+ return super.save(schedule);
+ }
|
--- a/src/main/java/com/jmb/springfactory/service/productionschedule/ProductionScheduleServiceImpl.java
+++ b/src/main/java/com/jmb/springfactory/service/productionschedule/ProductionScheduleServiceImpl.java
@@ ... @@
import com.jmb.springfactory.dao.productionschedule.ProductionScheduleMySQLService;
+import com.jmb.springfactory.exceptions.ServiceLayerException;
import com.jmb.springfactory.model.bo.BusinessObjectBase;
@@ ... @@
import com.jmb.springfactory.model.entity.ProductionSchedule;
+import com.jmb.springfactory.model.enumeration.ProductionScheduleStateEnum;
import com.jmb.springfactory.service.GenericServiceImpl;
@@ ... @@
}
+
+ @Override
+ public ProductionScheduleDto save(ProductionScheduleDto schedule) throws ServiceLayerException {
+ schedule.setState(ProductionScheduleStateEnum.OPEN.name());
+ return super.save(schedule);
+ }
|
--- a/src/main/java/com/jmb/springfactory/service/productionschedule/ProductionScheduleServiceImpl.java
+++ b/src/main/java/com/jmb/springfactory/service/productionschedule/ProductionScheduleServiceImpl.java
@@ -7,2 +7,3 @@
CON import com.jmb.springfactory.dao.productionschedule.ProductionScheduleMySQLService;
ADD import com.jmb.springfactory.exceptions.ServiceLayerException;
CON import com.jmb.springfactory.model.bo.BusinessObjectBase;
@@ -10,2 +11,3 @@
CON import com.jmb.springfactory.model.entity.ProductionSchedule;
ADD import com.jmb.springfactory.model.enumeration.ProductionScheduleStateEnum;
CON import com.jmb.springfactory.service.GenericServiceImpl;
@@ -38,2 +40,8 @@
CON }
ADD
ADD @Override
ADD public ProductionScheduleDto save(ProductionScheduleDto schedule) throws ServiceLayerException {
ADD schedule.setState(ProductionScheduleStateEnum.OPEN.name());
ADD return super.save(schedule);
ADD }
CON
|
<<<<<<< SEARCH
import com.jmb.springfactory.dao.GenericMySQLService;
import com.jmb.springfactory.dao.productionschedule.ProductionScheduleMySQLService;
import com.jmb.springfactory.model.bo.BusinessObjectBase;
import com.jmb.springfactory.model.dto.ProductionScheduleDto;
import com.jmb.springfactory.model.entity.ProductionSchedule;
import com.jmb.springfactory.service.GenericServiceImpl;
=======
import com.jmb.springfactory.dao.GenericMySQLService;
import com.jmb.springfactory.dao.productionschedule.ProductionScheduleMySQLService;
import com.jmb.springfactory.exceptions.ServiceLayerException;
import com.jmb.springfactory.model.bo.BusinessObjectBase;
import com.jmb.springfactory.model.dto.ProductionScheduleDto;
import com.jmb.springfactory.model.entity.ProductionSchedule;
import com.jmb.springfactory.model.enumeration.ProductionScheduleStateEnum;
import com.jmb.springfactory.service.GenericServiceImpl;
>>>>>>> REPLACE
<<<<<<< SEARCH
return BusinessObjectBase.class;
}
}
=======
return BusinessObjectBase.class;
}
@Override
public ProductionScheduleDto save(ProductionScheduleDto schedule) throws ServiceLayerException {
schedule.setState(ProductionScheduleStateEnum.OPEN.name());
return super.save(schedule);
}
}
>>>>>>> REPLACE
|
dtolnay/cxx
|
3c19e53ad1ff1808dc9e3d41ca88c8d1eb5f38f9
|
macro/src/namespace.rs
|
rust
|
apache-2.0
|
Enable Namespace to be used in format_ident
|
use crate::syntax::ident;
use std::fmt::{self, Display};
use syn::parse::{Parse, ParseStream, Result};
use syn::{Path, Token};
mod kw {
syn::custom_keyword!(namespace);
}
pub struct Namespace {
segments: Vec<String>,
}
impl Parse for Namespace {
fn parse(input: ParseStream) -> Result<Self> {
let mut segments = Vec::new();
if !input.is_empty() {
input.parse::<kw::namespace>()?;
input.parse::<Token![=]>()?;
let path = input.call(Path::parse_mod_style)?;
for segment in path.segments {
ident::check(&segment.ident)?;
segments.push(segment.ident.to_string());
}
input.parse::<Option<Token![,]>>()?;
}
Ok(Namespace { segments })
}
}
impl Display for Namespace {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
for segment in &self.segments {
f.write_str(segment)?;
f.write_str("$")?;
}
Ok(())
}
}
|
use crate::syntax::ident;
use quote::IdentFragment;
use std::fmt::{self, Display};
use syn::parse::{Parse, ParseStream, Result};
use syn::{Path, Token};
mod kw {
syn::custom_keyword!(namespace);
}
pub struct Namespace {
segments: Vec<String>,
}
impl Parse for Namespace {
fn parse(input: ParseStream) -> Result<Self> {
let mut segments = Vec::new();
if !input.is_empty() {
input.parse::<kw::namespace>()?;
input.parse::<Token![=]>()?;
let path = input.call(Path::parse_mod_style)?;
for segment in path.segments {
ident::check(&segment.ident)?;
segments.push(segment.ident.to_string());
}
input.parse::<Option<Token![,]>>()?;
}
Ok(Namespace { segments })
}
}
impl Display for Namespace {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
for segment in &self.segments {
f.write_str(segment)?;
f.write_str("$")?;
}
Ok(())
}
}
impl IdentFragment for Namespace {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
Display::fmt(self, f)
}
}
| 7
| 0
| 2
|
add_only
|
--- a/macro/src/namespace.rs
+++ b/macro/src/namespace.rs
@@ -1,2 +1,3 @@
use crate::syntax::ident;
+use quote::IdentFragment;
use std::fmt::{self, Display};
@@ -39 +40,7 @@
}
+
+impl IdentFragment for Namespace {
+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+ Display::fmt(self, f)
+ }
+}
|
--- a/macro/src/namespace.rs
+++ b/macro/src/namespace.rs
@@ ... @@
use crate::syntax::ident;
+use quote::IdentFragment;
use std::fmt::{self, Display};
@@ ... @@
}
+
+impl IdentFragment for Namespace {
+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+ Display::fmt(self, f)
+ }
+}
|
--- a/macro/src/namespace.rs
+++ b/macro/src/namespace.rs
@@ -1,2 +1,3 @@
CON use crate::syntax::ident;
ADD use quote::IdentFragment;
CON use std::fmt::{self, Display};
@@ -39 +40,7 @@
CON }
ADD
ADD impl IdentFragment for Namespace {
ADD fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
ADD Display::fmt(self, f)
ADD }
ADD }
|
<<<<<<< SEARCH
use crate::syntax::ident;
use std::fmt::{self, Display};
use syn::parse::{Parse, ParseStream, Result};
=======
use crate::syntax::ident;
use quote::IdentFragment;
use std::fmt::{self, Display};
use syn::parse::{Parse, ParseStream, Result};
>>>>>>> REPLACE
<<<<<<< SEARCH
}
}
=======
}
}
impl IdentFragment for Namespace {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
Display::fmt(self, f)
}
}
>>>>>>> REPLACE
|
SpineEventEngine/core-java
|
95f15b7edd587178eba0379268be847ec3eb48a1
|
server/src/main/java/io/spine/server/integration/DeadExternalMessageTap.java
|
java
|
apache-2.0
|
Add a missing `@author` tag.
|
/*
* Copyright 2017, TeamDev Ltd. All rights reserved.
*
* Redistribution and use in source and/or binary forms, with or without
* modification, must retain the above copyright notice and the following
* disclaimer.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package io.spine.server.integration;
import com.google.protobuf.Message;
import io.spine.server.bus.DeadMessageTap;
/**
* Produces an {@link UnsupportedExternalMessageException} upon capturing an external message,
* which has no targets to be dispatched to.
*/
enum DeadExternalMessageTap implements DeadMessageTap<ExternalMessageEnvelope> {
INSTANCE;
@Override
public UnsupportedExternalMessageException capture(ExternalMessageEnvelope envelope) {
final Message message = envelope.getMessage();
final UnsupportedExternalMessageException exception =
new UnsupportedExternalMessageException(message);
return exception;
}
}
|
/*
* Copyright 2017, TeamDev Ltd. All rights reserved.
*
* Redistribution and use in source and/or binary forms, with or without
* modification, must retain the above copyright notice and the following
* disclaimer.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package io.spine.server.integration;
import com.google.protobuf.Message;
import io.spine.server.bus.DeadMessageTap;
/**
* Produces an {@link UnsupportedExternalMessageException} upon capturing an external message,
* which has no targets to be dispatched to.
*
* @author Alex Tymchenko
*/
enum DeadExternalMessageTap implements DeadMessageTap<ExternalMessageEnvelope> {
INSTANCE;
@Override
public UnsupportedExternalMessageException capture(ExternalMessageEnvelope envelope) {
final Message message = envelope.getMessage();
final UnsupportedExternalMessageException exception =
new UnsupportedExternalMessageException(message);
return exception;
}
}
| 2
| 0
| 1
|
add_only
|
--- a/server/src/main/java/io/spine/server/integration/DeadExternalMessageTap.java
+++ b/server/src/main/java/io/spine/server/integration/DeadExternalMessageTap.java
@@ -27,2 +27,4 @@
* which has no targets to be dispatched to.
+ *
+ * @author Alex Tymchenko
*/
|
--- a/server/src/main/java/io/spine/server/integration/DeadExternalMessageTap.java
+++ b/server/src/main/java/io/spine/server/integration/DeadExternalMessageTap.java
@@ ... @@
* which has no targets to be dispatched to.
+ *
+ * @author Alex Tymchenko
*/
|
--- a/server/src/main/java/io/spine/server/integration/DeadExternalMessageTap.java
+++ b/server/src/main/java/io/spine/server/integration/DeadExternalMessageTap.java
@@ -27,2 +27,4 @@
CON * which has no targets to be dispatched to.
ADD *
ADD * @author Alex Tymchenko
CON */
|
<<<<<<< SEARCH
* Produces an {@link UnsupportedExternalMessageException} upon capturing an external message,
* which has no targets to be dispatched to.
*/
enum DeadExternalMessageTap implements DeadMessageTap<ExternalMessageEnvelope> {
=======
* Produces an {@link UnsupportedExternalMessageException} upon capturing an external message,
* which has no targets to be dispatched to.
*
* @author Alex Tymchenko
*/
enum DeadExternalMessageTap implements DeadMessageTap<ExternalMessageEnvelope> {
>>>>>>> REPLACE
|
meego-tablet-ux/meego-app-browser
|
521e24fa115e69bca39d7cca89ce42e8efa3b077
|
tools/perf_expectations/PRESUBMIT.py
|
python
|
bsd-3-clause
|
Use full pathname to perf_expectations in test.
BUG=none
TEST=none
Review URL: http://codereview.chromium.org/266055
git-svn-id: http://src.chromium.org/svn/trunk/src@28770 4ff67af0-8c30-449e-8e8b-ad334ec8d88c
Former-commit-id: f9d8e0a8dae19e482d3c435a76b4e38403e646b5
|
#!/usr/bin/python
# Copyright (c) 2009 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Presubmit script for perf_expectations.
See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts for
details on the presubmit API built into gcl.
"""
UNIT_TESTS = [
'tests.perf_expectations_unittest',
]
PERF_EXPECTATIONS = 'perf_expectations.json'
def CheckChangeOnUpload(input_api, output_api):
run_tests = False
for path in input_api.LocalPaths():
if PERF_EXPECTATIONS == input_api.os_path.basename(path):
run_tests = True
output = []
if run_tests:
output.extend(input_api.canned_checks.RunPythonUnitTests(input_api,
output_api,
UNIT_TESTS))
return output
def CheckChangeOnCommit(input_api, output_api):
run_tests = False
for path in input_api.LocalPaths():
if PERF_EXPECTATIONS == input_api.os_path.basename(path):
run_tests = True
output = []
if run_tests:
output.extend(input_api.canned_checks.RunPythonUnitTests(input_api,
output_api,
UNIT_TESTS))
output.extend(input_api.canned_checks.CheckDoNotSubmit(input_api,
output_api))
return output
|
#!/usr/bin/python
# Copyright (c) 2009 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Presubmit script for perf_expectations.
See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts for
details on the presubmit API built into gcl.
"""
UNIT_TESTS = [
'tests.perf_expectations_unittest',
]
PERF_EXPECTATIONS = 'tools/perf_expectations/perf_expectations.json'
def CheckChangeOnUpload(input_api, output_api):
run_tests = False
for path in input_api.LocalPaths():
if PERF_EXPECTATIONS == path:
run_tests = True
output = []
if run_tests:
output.extend(input_api.canned_checks.RunPythonUnitTests(input_api,
output_api,
UNIT_TESTS))
return output
def CheckChangeOnCommit(input_api, output_api):
run_tests = False
for path in input_api.LocalPaths():
if PERF_EXPECTATIONS == path:
run_tests = True
output = []
if run_tests:
output.extend(input_api.canned_checks.RunPythonUnitTests(input_api,
output_api,
UNIT_TESTS))
output.extend(input_api.canned_checks.CheckDoNotSubmit(input_api,
output_api))
return output
| 3
| 3
| 3
|
mixed
|
--- a/tools/perf_expectations/PRESUBMIT.py
+++ b/tools/perf_expectations/PRESUBMIT.py
@@ -15,3 +15,3 @@
-PERF_EXPECTATIONS = 'perf_expectations.json'
+PERF_EXPECTATIONS = 'tools/perf_expectations/perf_expectations.json'
@@ -20,3 +20,3 @@
for path in input_api.LocalPaths():
- if PERF_EXPECTATIONS == input_api.os_path.basename(path):
+ if PERF_EXPECTATIONS == path:
run_tests = True
@@ -34,3 +34,3 @@
for path in input_api.LocalPaths():
- if PERF_EXPECTATIONS == input_api.os_path.basename(path):
+ if PERF_EXPECTATIONS == path:
run_tests = True
|
--- a/tools/perf_expectations/PRESUBMIT.py
+++ b/tools/perf_expectations/PRESUBMIT.py
@@ ... @@
-PERF_EXPECTATIONS = 'perf_expectations.json'
+PERF_EXPECTATIONS = 'tools/perf_expectations/perf_expectations.json'
@@ ... @@
for path in input_api.LocalPaths():
- if PERF_EXPECTATIONS == input_api.os_path.basename(path):
+ if PERF_EXPECTATIONS == path:
run_tests = True
@@ ... @@
for path in input_api.LocalPaths():
- if PERF_EXPECTATIONS == input_api.os_path.basename(path):
+ if PERF_EXPECTATIONS == path:
run_tests = True
|
--- a/tools/perf_expectations/PRESUBMIT.py
+++ b/tools/perf_expectations/PRESUBMIT.py
@@ -15,3 +15,3 @@
CON
DEL PERF_EXPECTATIONS = 'perf_expectations.json'
ADD PERF_EXPECTATIONS = 'tools/perf_expectations/perf_expectations.json'
CON
@@ -20,3 +20,3 @@
CON for path in input_api.LocalPaths():
DEL if PERF_EXPECTATIONS == input_api.os_path.basename(path):
ADD if PERF_EXPECTATIONS == path:
CON run_tests = True
@@ -34,3 +34,3 @@
CON for path in input_api.LocalPaths():
DEL if PERF_EXPECTATIONS == input_api.os_path.basename(path):
ADD if PERF_EXPECTATIONS == path:
CON run_tests = True
|
<<<<<<< SEARCH
]
PERF_EXPECTATIONS = 'perf_expectations.json'
def CheckChangeOnUpload(input_api, output_api):
run_tests = False
for path in input_api.LocalPaths():
if PERF_EXPECTATIONS == input_api.os_path.basename(path):
run_tests = True
=======
]
PERF_EXPECTATIONS = 'tools/perf_expectations/perf_expectations.json'
def CheckChangeOnUpload(input_api, output_api):
run_tests = False
for path in input_api.LocalPaths():
if PERF_EXPECTATIONS == path:
run_tests = True
>>>>>>> REPLACE
<<<<<<< SEARCH
run_tests = False
for path in input_api.LocalPaths():
if PERF_EXPECTATIONS == input_api.os_path.basename(path):
run_tests = True
=======
run_tests = False
for path in input_api.LocalPaths():
if PERF_EXPECTATIONS == path:
run_tests = True
>>>>>>> REPLACE
|
tipsy/j2html
|
368241313dff3de5d0ce41d663fc5414ed27c918
|
src/main/java/j2html/tags/InlineStaticResource.java
|
java
|
apache-2.0
|
Allow reading static resources from jars
|
package j2html.tags;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import j2html.Config;
import j2html.utils.CSSMin;
import j2html.utils.JSMin;
import static j2html.TagCreator.*;
public class InlineStaticResource {
public enum TargetFormat {CSS_MIN, CSS, JS_MIN, JS}
public static ContainerTag get(String path, TargetFormat format) {
String fileString = getFileAsString(path);
switch (format) {
case CSS_MIN : return style().with(rawHtml(Config.cssMinifier.minify(fileString)));
case JS_MIN : return script().with(rawHtml(Config.jsMinifier.minify((fileString))));
case CSS : return style().with(rawHtml(fileString));
case JS : return script().with(rawHtml(fileString));
default : throw new RuntimeException("Invalid target format");
}
}
public static String getFileAsString(String path) {
try {
return readFileAsString(InlineStaticResource.class.getResource(path).getPath());
} catch (Exception e1) {
try {
return readFileAsString(path);
} catch (Exception e2) {
throw new RuntimeException("Couldn't find file with path='" + path + "'");
}
}
}
/**
* @author kjheimark <3
*/
private static String readFileAsString(String path) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new FileReader(path));
StringBuilder sb = new StringBuilder();
int c;
while ((c = bufferedReader.read()) >= 0 && c >= 0) {
sb.append((char) c);
}
return sb.toString();
}
}
|
package j2html.tags;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Scanner;
import j2html.Config;
import static j2html.TagCreator.*;
public class InlineStaticResource {
public enum TargetFormat {CSS_MIN, CSS, JS_MIN, JS}
public static ContainerTag get(String path, TargetFormat format) {
String fileString = getFileAsString(path);
switch (format) {
case CSS_MIN : return style().with(rawHtml(Config.cssMinifier.minify(fileString)));
case JS_MIN : return script().with(rawHtml(Config.jsMinifier.minify((fileString))));
case CSS : return style().with(rawHtml(fileString));
case JS : return script().with(rawHtml(fileString));
default : throw new RuntimeException("Invalid target format");
}
}
public static String getFileAsString(String path) {
try {
return streamToString(InlineStaticResource.class.getResourceAsStream(path));
} catch (Exception expected) { // we don't ask users to specify classpath or file-system
try {
return streamToString(new FileInputStream(path));
} catch (Exception exception) {
throw new RuntimeException("Couldn't find file with path='" + path + "'");
}
}
}
private static String streamToString(InputStream inputStream) {
Scanner s = new Scanner(inputStream).useDelimiter("\\A");
return s.hasNext() ? s.next() : "";
}
}
| 10
| 20
| 3
|
mixed
|
--- a/src/main/java/j2html/tags/InlineStaticResource.java
+++ b/src/main/java/j2html/tags/InlineStaticResource.java
@@ -2,9 +2,7 @@
-import java.io.BufferedReader;
-import java.io.FileReader;
-import java.io.IOException;
+import java.io.FileInputStream;
+import java.io.InputStream;
+import java.util.Scanner;
import j2html.Config;
-import j2html.utils.CSSMin;
-import j2html.utils.JSMin;
@@ -29,7 +27,7 @@
try {
- return readFileAsString(InlineStaticResource.class.getResource(path).getPath());
- } catch (Exception e1) {
+ return streamToString(InlineStaticResource.class.getResourceAsStream(path));
+ } catch (Exception expected) { // we don't ask users to specify classpath or file-system
try {
- return readFileAsString(path);
- } catch (Exception e2) {
+ return streamToString(new FileInputStream(path));
+ } catch (Exception exception) {
throw new RuntimeException("Couldn't find file with path='" + path + "'");
@@ -39,13 +37,5 @@
- /**
- * @author kjheimark <3
- */
- private static String readFileAsString(String path) throws IOException {
- BufferedReader bufferedReader = new BufferedReader(new FileReader(path));
- StringBuilder sb = new StringBuilder();
- int c;
- while ((c = bufferedReader.read()) >= 0 && c >= 0) {
- sb.append((char) c);
- }
- return sb.toString();
+ private static String streamToString(InputStream inputStream) {
+ Scanner s = new Scanner(inputStream).useDelimiter("\\A");
+ return s.hasNext() ? s.next() : "";
}
|
--- a/src/main/java/j2html/tags/InlineStaticResource.java
+++ b/src/main/java/j2html/tags/InlineStaticResource.java
@@ ... @@
-import java.io.BufferedReader;
-import java.io.FileReader;
-import java.io.IOException;
+import java.io.FileInputStream;
+import java.io.InputStream;
+import java.util.Scanner;
import j2html.Config;
-import j2html.utils.CSSMin;
-import j2html.utils.JSMin;
@@ ... @@
try {
- return readFileAsString(InlineStaticResource.class.getResource(path).getPath());
- } catch (Exception e1) {
+ return streamToString(InlineStaticResource.class.getResourceAsStream(path));
+ } catch (Exception expected) { // we don't ask users to specify classpath or file-system
try {
- return readFileAsString(path);
- } catch (Exception e2) {
+ return streamToString(new FileInputStream(path));
+ } catch (Exception exception) {
throw new RuntimeException("Couldn't find file with path='" + path + "'");
@@ ... @@
- /**
- * @author kjheimark <3
- */
- private static String readFileAsString(String path) throws IOException {
- BufferedReader bufferedReader = new BufferedReader(new FileReader(path));
- StringBuilder sb = new StringBuilder();
- int c;
- while ((c = bufferedReader.read()) >= 0 && c >= 0) {
- sb.append((char) c);
- }
- return sb.toString();
+ private static String streamToString(InputStream inputStream) {
+ Scanner s = new Scanner(inputStream).useDelimiter("\\A");
+ return s.hasNext() ? s.next() : "";
}
|
--- a/src/main/java/j2html/tags/InlineStaticResource.java
+++ b/src/main/java/j2html/tags/InlineStaticResource.java
@@ -2,9 +2,7 @@
CON
DEL import java.io.BufferedReader;
DEL import java.io.FileReader;
DEL import java.io.IOException;
ADD import java.io.FileInputStream;
ADD import java.io.InputStream;
ADD import java.util.Scanner;
CON
CON import j2html.Config;
DEL import j2html.utils.CSSMin;
DEL import j2html.utils.JSMin;
CON
@@ -29,7 +27,7 @@
CON try {
DEL return readFileAsString(InlineStaticResource.class.getResource(path).getPath());
DEL } catch (Exception e1) {
ADD return streamToString(InlineStaticResource.class.getResourceAsStream(path));
ADD } catch (Exception expected) { // we don't ask users to specify classpath or file-system
CON try {
DEL return readFileAsString(path);
DEL } catch (Exception e2) {
ADD return streamToString(new FileInputStream(path));
ADD } catch (Exception exception) {
CON throw new RuntimeException("Couldn't find file with path='" + path + "'");
@@ -39,13 +37,5 @@
CON
DEL /**
DEL * @author kjheimark <3
DEL */
DEL private static String readFileAsString(String path) throws IOException {
DEL BufferedReader bufferedReader = new BufferedReader(new FileReader(path));
DEL StringBuilder sb = new StringBuilder();
DEL int c;
DEL while ((c = bufferedReader.read()) >= 0 && c >= 0) {
DEL sb.append((char) c);
DEL }
DEL return sb.toString();
ADD private static String streamToString(InputStream inputStream) {
ADD Scanner s = new Scanner(inputStream).useDelimiter("\\A");
ADD return s.hasNext() ? s.next() : "";
CON }
|
<<<<<<< SEARCH
package j2html.tags;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import j2html.Config;
import j2html.utils.CSSMin;
import j2html.utils.JSMin;
import static j2html.TagCreator.*;
=======
package j2html.tags;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Scanner;
import j2html.Config;
import static j2html.TagCreator.*;
>>>>>>> REPLACE
<<<<<<< SEARCH
public static String getFileAsString(String path) {
try {
return readFileAsString(InlineStaticResource.class.getResource(path).getPath());
} catch (Exception e1) {
try {
return readFileAsString(path);
} catch (Exception e2) {
throw new RuntimeException("Couldn't find file with path='" + path + "'");
}
}
}
/**
* @author kjheimark <3
*/
private static String readFileAsString(String path) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new FileReader(path));
StringBuilder sb = new StringBuilder();
int c;
while ((c = bufferedReader.read()) >= 0 && c >= 0) {
sb.append((char) c);
}
return sb.toString();
}
=======
public static String getFileAsString(String path) {
try {
return streamToString(InlineStaticResource.class.getResourceAsStream(path));
} catch (Exception expected) { // we don't ask users to specify classpath or file-system
try {
return streamToString(new FileInputStream(path));
} catch (Exception exception) {
throw new RuntimeException("Couldn't find file with path='" + path + "'");
}
}
}
private static String streamToString(InputStream inputStream) {
Scanner s = new Scanner(inputStream).useDelimiter("\\A");
return s.hasNext() ? s.next() : "";
}
>>>>>>> REPLACE
|
DemonWav/MinecraftDev
|
97bebf48fd593488fd0793cd5b198958c76ddc1d
|
src/main/kotlin/com/demonwav/mcdev/platform/sponge/framework/SpongePresentationProvider.kt
|
kotlin
|
mit
|
Handle either Implementation-Title or Specification-Title
|
/*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2017 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform.sponge.framework
import com.demonwav.mcdev.asset.PlatformAssets
import com.intellij.framework.library.LibraryVersionProperties
import com.intellij.openapi.roots.libraries.LibraryPresentationProvider
import com.intellij.openapi.roots.libraries.LibraryProperties
import com.intellij.openapi.util.io.JarUtil
import com.intellij.openapi.vfs.VfsUtilCore
import com.intellij.openapi.vfs.VirtualFile
import java.util.jar.Attributes
class SpongePresentationProvider : LibraryPresentationProvider<LibraryVersionProperties>(SPONGE_LIBRARY_KIND) {
override fun getIcon(properties: LibraryProperties<*>?) = PlatformAssets.SPONGE_ICON
override fun detect(classesRoots: List<VirtualFile>): LibraryVersionProperties? {
for (classesRoot in classesRoots) {
val file = VfsUtilCore.virtualToIoFile(classesRoot)
val title = JarUtil.getJarAttribute(file, Attributes.Name.IMPLEMENTATION_TITLE) ?: continue
if (title != "SpongeAPI") {
continue
}
val version = JarUtil.getJarAttribute(file, Attributes.Name.IMPLEMENTATION_VERSION) ?: continue
return LibraryVersionProperties(version)
}
return null
}
}
|
/*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2017 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform.sponge.framework
import com.demonwav.mcdev.asset.PlatformAssets
import com.intellij.framework.library.LibraryVersionProperties
import com.intellij.openapi.roots.libraries.LibraryPresentationProvider
import com.intellij.openapi.roots.libraries.LibraryProperties
import com.intellij.openapi.util.io.JarUtil
import com.intellij.openapi.vfs.VfsUtilCore
import com.intellij.openapi.vfs.VirtualFile
import java.util.jar.Attributes
class SpongePresentationProvider : LibraryPresentationProvider<LibraryVersionProperties>(SPONGE_LIBRARY_KIND) {
override fun getIcon(properties: LibraryProperties<*>?) = PlatformAssets.SPONGE_ICON
override fun detect(classesRoots: List<VirtualFile>): LibraryVersionProperties? {
loop@ for (classesRoot in classesRoots) {
val file = VfsUtilCore.virtualToIoFile(classesRoot)
when ("SpongeAPI") {
JarUtil.getJarAttribute(file, Attributes.Name.IMPLEMENTATION_TITLE) -> {}
JarUtil.getJarAttribute(file, Attributes.Name.SPECIFICATION_TITLE) -> {}
else -> continue@loop
}
val version = JarUtil.getJarAttribute(file, Attributes.Name.IMPLEMENTATION_VERSION) ?: continue
return LibraryVersionProperties(version)
}
return null
}
}
| 5
| 4
| 1
|
mixed
|
--- a/src/main/kotlin/com/demonwav/mcdev/platform/sponge/framework/SpongePresentationProvider.kt
+++ b/src/main/kotlin/com/demonwav/mcdev/platform/sponge/framework/SpongePresentationProvider.kt
@@ -26,8 +26,9 @@
override fun detect(classesRoots: List<VirtualFile>): LibraryVersionProperties? {
- for (classesRoot in classesRoots) {
+ loop@ for (classesRoot in classesRoots) {
val file = VfsUtilCore.virtualToIoFile(classesRoot)
- val title = JarUtil.getJarAttribute(file, Attributes.Name.IMPLEMENTATION_TITLE) ?: continue
- if (title != "SpongeAPI") {
- continue
+ when ("SpongeAPI") {
+ JarUtil.getJarAttribute(file, Attributes.Name.IMPLEMENTATION_TITLE) -> {}
+ JarUtil.getJarAttribute(file, Attributes.Name.SPECIFICATION_TITLE) -> {}
+ else -> continue@loop
}
|
--- a/src/main/kotlin/com/demonwav/mcdev/platform/sponge/framework/SpongePresentationProvider.kt
+++ b/src/main/kotlin/com/demonwav/mcdev/platform/sponge/framework/SpongePresentationProvider.kt
@@ ... @@
override fun detect(classesRoots: List<VirtualFile>): LibraryVersionProperties? {
- for (classesRoot in classesRoots) {
+ loop@ for (classesRoot in classesRoots) {
val file = VfsUtilCore.virtualToIoFile(classesRoot)
- val title = JarUtil.getJarAttribute(file, Attributes.Name.IMPLEMENTATION_TITLE) ?: continue
- if (title != "SpongeAPI") {
- continue
+ when ("SpongeAPI") {
+ JarUtil.getJarAttribute(file, Attributes.Name.IMPLEMENTATION_TITLE) -> {}
+ JarUtil.getJarAttribute(file, Attributes.Name.SPECIFICATION_TITLE) -> {}
+ else -> continue@loop
}
|
--- a/src/main/kotlin/com/demonwav/mcdev/platform/sponge/framework/SpongePresentationProvider.kt
+++ b/src/main/kotlin/com/demonwav/mcdev/platform/sponge/framework/SpongePresentationProvider.kt
@@ -26,8 +26,9 @@
CON override fun detect(classesRoots: List<VirtualFile>): LibraryVersionProperties? {
DEL for (classesRoot in classesRoots) {
ADD loop@ for (classesRoot in classesRoots) {
CON val file = VfsUtilCore.virtualToIoFile(classesRoot)
DEL val title = JarUtil.getJarAttribute(file, Attributes.Name.IMPLEMENTATION_TITLE) ?: continue
CON
DEL if (title != "SpongeAPI") {
DEL continue
ADD when ("SpongeAPI") {
ADD JarUtil.getJarAttribute(file, Attributes.Name.IMPLEMENTATION_TITLE) -> {}
ADD JarUtil.getJarAttribute(file, Attributes.Name.SPECIFICATION_TITLE) -> {}
ADD else -> continue@loop
CON }
|
<<<<<<< SEARCH
override fun detect(classesRoots: List<VirtualFile>): LibraryVersionProperties? {
for (classesRoot in classesRoots) {
val file = VfsUtilCore.virtualToIoFile(classesRoot)
val title = JarUtil.getJarAttribute(file, Attributes.Name.IMPLEMENTATION_TITLE) ?: continue
if (title != "SpongeAPI") {
continue
}
=======
override fun detect(classesRoots: List<VirtualFile>): LibraryVersionProperties? {
loop@ for (classesRoot in classesRoots) {
val file = VfsUtilCore.virtualToIoFile(classesRoot)
when ("SpongeAPI") {
JarUtil.getJarAttribute(file, Attributes.Name.IMPLEMENTATION_TITLE) -> {}
JarUtil.getJarAttribute(file, Attributes.Name.SPECIFICATION_TITLE) -> {}
else -> continue@loop
}
>>>>>>> REPLACE
|
multunus/moveit-mobile
|
8235e2e93031c51a7d66330346ce3408734e2154
|
app/sessionManager.js
|
javascript
|
mit
|
Move the CURRENT_USER_STORAGE_KEY constant to SessionManager
|
'use strict';
var React = require('react-native');
var Constants = require('./constants');
var { AsyncStorage } = React;
var SessionManager = {
login: function(user) {
return new Promise(function(resolve, reject) {
var url = Constants.APP_SERVER_HOST + '/users/register';
fetch(url, {
method: 'post',
body: JSON.stringify({user: user}),
headers: new Headers({
'Content-Type': 'application/json'
})
})
.then(response => {
if(response.ok) {
return response.json();
} else {
reject(new Error(JSON.parse(response._bodyText).error)); //FixIt - Shoudn't be using the quasi private method
}
})
.then(response => {
var user = {
name: response.user.name,
email: response.user.email,
avatar: response.user.gravatar_url
}
console.log(user);
AsyncStorage
.setItem(Constants.CURRENT_USER_STORAGE_KEY, JSON.stringify(user))
.then((value) => resolve(value));
})
.catch(error => reject(error));
});
},
getCurrentUser: function() {
return new Promise(function(resolve, reject) {
AsyncStorage.getItem(Constants.CURRENT_USER_STORAGE_KEY)
.then((value) => {
if(value === null) reject(Error('No user logged in!'));
resolve(JSON.parse(value));
});
});
}
};
module.exports = SessionManager;
|
'use strict';
var React = require('react-native');
var Constants = require('./constants');
var { AsyncStorage } = React;
const CURRENT_USER_STORAGE_KEY = 'currentUser';
var SessionManager = {
login: function(user) {
return new Promise(function(resolve, reject) {
var url = Constants.APP_SERVER_HOST + '/users/register';
fetch(url, {
method: 'post',
body: JSON.stringify({user: user}),
headers: new Headers({
'Content-Type': 'application/json'
})
})
.then(response => {
if(response.ok) {
return response.json();
} else {
reject(new Error(JSON.parse(response._bodyText).error)); //FixIt - Shoudn't be using the quasi private method
}
})
.then(response => {
var user = {
name: response.user.name,
email: response.user.email,
avatar: response.user.gravatar_url
}
console.log(user);
AsyncStorage
.setItem(CURRENT_USER_STORAGE_KEY, JSON.stringify(user))
.then((value) => resolve(value));
})
.catch(error => reject(error));
});
},
getCurrentUser: function() {
return new Promise(function(resolve, reject) {
AsyncStorage.getItem(CURRENT_USER_STORAGE_KEY)
.then((value) => {
if(value === null) reject(Error('No user logged in!'));
resolve(JSON.parse(value));
});
});
}
};
module.exports = SessionManager;
| 4
| 2
| 3
|
mixed
|
--- a/app/sessionManager.js
+++ b/app/sessionManager.js
@@ -6,2 +6,4 @@
var { AsyncStorage } = React;
+
+const CURRENT_USER_STORAGE_KEY = 'currentUser';
@@ -33,3 +35,3 @@
AsyncStorage
- .setItem(Constants.CURRENT_USER_STORAGE_KEY, JSON.stringify(user))
+ .setItem(CURRENT_USER_STORAGE_KEY, JSON.stringify(user))
.then((value) => resolve(value));
@@ -42,3 +44,3 @@
return new Promise(function(resolve, reject) {
- AsyncStorage.getItem(Constants.CURRENT_USER_STORAGE_KEY)
+ AsyncStorage.getItem(CURRENT_USER_STORAGE_KEY)
.then((value) => {
|
--- a/app/sessionManager.js
+++ b/app/sessionManager.js
@@ ... @@
var { AsyncStorage } = React;
+
+const CURRENT_USER_STORAGE_KEY = 'currentUser';
@@ ... @@
AsyncStorage
- .setItem(Constants.CURRENT_USER_STORAGE_KEY, JSON.stringify(user))
+ .setItem(CURRENT_USER_STORAGE_KEY, JSON.stringify(user))
.then((value) => resolve(value));
@@ ... @@
return new Promise(function(resolve, reject) {
- AsyncStorage.getItem(Constants.CURRENT_USER_STORAGE_KEY)
+ AsyncStorage.getItem(CURRENT_USER_STORAGE_KEY)
.then((value) => {
|
--- a/app/sessionManager.js
+++ b/app/sessionManager.js
@@ -6,2 +6,4 @@
CON var { AsyncStorage } = React;
ADD
ADD const CURRENT_USER_STORAGE_KEY = 'currentUser';
CON
@@ -33,3 +35,3 @@
CON AsyncStorage
DEL .setItem(Constants.CURRENT_USER_STORAGE_KEY, JSON.stringify(user))
ADD .setItem(CURRENT_USER_STORAGE_KEY, JSON.stringify(user))
CON .then((value) => resolve(value));
@@ -42,3 +44,3 @@
CON return new Promise(function(resolve, reject) {
DEL AsyncStorage.getItem(Constants.CURRENT_USER_STORAGE_KEY)
ADD AsyncStorage.getItem(CURRENT_USER_STORAGE_KEY)
CON .then((value) => {
|
<<<<<<< SEARCH
var { AsyncStorage } = React;
var SessionManager = {
=======
var { AsyncStorage } = React;
const CURRENT_USER_STORAGE_KEY = 'currentUser';
var SessionManager = {
>>>>>>> REPLACE
<<<<<<< SEARCH
console.log(user);
AsyncStorage
.setItem(Constants.CURRENT_USER_STORAGE_KEY, JSON.stringify(user))
.then((value) => resolve(value));
})
=======
console.log(user);
AsyncStorage
.setItem(CURRENT_USER_STORAGE_KEY, JSON.stringify(user))
.then((value) => resolve(value));
})
>>>>>>> REPLACE
<<<<<<< SEARCH
getCurrentUser: function() {
return new Promise(function(resolve, reject) {
AsyncStorage.getItem(Constants.CURRENT_USER_STORAGE_KEY)
.then((value) => {
if(value === null) reject(Error('No user logged in!'));
=======
getCurrentUser: function() {
return new Promise(function(resolve, reject) {
AsyncStorage.getItem(CURRENT_USER_STORAGE_KEY)
.then((value) => {
if(value === null) reject(Error('No user logged in!'));
>>>>>>> REPLACE
|
stelar7/L4J8
|
50a2f78791baabcec413f3ad99130e8956cf4863
|
src/main/java/no/stelar7/api/r4j/pojo/val/matchlist/MatchReference.java
|
java
|
apache-2.0
|
Fix property names to be related to response from riot valorant api
|
package no.stelar7.api.r4j.pojo.val.matchlist;
import java.io.Serializable;
import java.util.Objects;
public class MatchReference implements Serializable
{
private static final long serialVersionUID = -5301457261872587385L;
private String matchId;
private Long gameStartTime;
private String teamId;
public String getMatchId()
{
return matchId;
}
public Long getGameStartTime()
{
return gameStartTime;
}
public String getTeamId()
{
return teamId;
}
@Override
public boolean equals(Object o)
{
if (this == o)
{
return true;
}
if (o == null || getClass() != o.getClass())
{
return false;
}
MatchReference match = (MatchReference) o;
return Objects.equals(matchId, match.matchId) &&
Objects.equals(gameStartTime, match.gameStartTime) &&
Objects.equals(teamId, match.teamId);
}
@Override
public int hashCode()
{
return Objects.hash(matchId, gameStartTime, teamId);
}
@Override
public String toString()
{
return "Match{" +
"matchId='" + matchId + '\'' +
", gameStartTime=" + gameStartTime +
", teamId='" + teamId + '\'' +
'}';
}
}
|
package no.stelar7.api.r4j.pojo.val.matchlist;
import java.io.Serializable;
import java.util.Objects;
public class MatchReference implements Serializable
{
private static final long serialVersionUID = -5301457261872587385L;
private String matchId;
private Long gameStartTimeMillis;
private String queueId;
public String getMatchId()
{
return matchId;
}
public Long getGameStartTimeMillis()
{
return gameStartTimeMillis;
}
public String getQueueId()
{
return queueId;
}
@Override
public boolean equals(Object o)
{
if (this == o)
{
return true;
}
if (o == null || getClass() != o.getClass())
{
return false;
}
MatchReference match = (MatchReference) o;
return Objects.equals(matchId, match.matchId) &&
Objects.equals(gameStartTimeMillis, match.gameStartTimeMillis) &&
Objects.equals(queueId, match.queueId);
}
@Override
public int hashCode()
{
return Objects.hash(matchId, gameStartTimeMillis, queueId);
}
@Override
public String toString()
{
return "Match{" +
"matchId='" + matchId + '\'' +
", gameStartTimeMillis=" + gameStartTimeMillis +
", queueId='" + queueId + '\'' +
'}';
}
}
| 18
| 18
| 5
|
mixed
|
--- a/src/main/java/no/stelar7/api/r4j/pojo/val/matchlist/MatchReference.java
+++ b/src/main/java/no/stelar7/api/r4j/pojo/val/matchlist/MatchReference.java
@@ -8,7 +8,7 @@
private static final long serialVersionUID = -5301457261872587385L;
-
+
private String matchId;
- private Long gameStartTime;
- private String teamId;
-
+ private Long gameStartTimeMillis;
+ private String queueId;
+
public String getMatchId()
@@ -17,13 +17,13 @@
}
-
- public Long getGameStartTime()
+
+ public Long getGameStartTimeMillis()
{
- return gameStartTime;
+ return gameStartTimeMillis;
}
-
- public String getTeamId()
+
+ public String getQueueId()
{
- return teamId;
+ return queueId;
}
-
+
@Override
@@ -41,6 +41,6 @@
return Objects.equals(matchId, match.matchId) &&
- Objects.equals(gameStartTime, match.gameStartTime) &&
- Objects.equals(teamId, match.teamId);
+ Objects.equals(gameStartTimeMillis, match.gameStartTimeMillis) &&
+ Objects.equals(queueId, match.queueId);
}
-
+
@Override
@@ -48,5 +48,5 @@
{
- return Objects.hash(matchId, gameStartTime, teamId);
+ return Objects.hash(matchId, gameStartTimeMillis, queueId);
}
-
+
@Override
@@ -56,4 +56,4 @@
"matchId='" + matchId + '\'' +
- ", gameStartTime=" + gameStartTime +
- ", teamId='" + teamId + '\'' +
+ ", gameStartTimeMillis=" + gameStartTimeMillis +
+ ", queueId='" + queueId + '\'' +
'}';
|
--- a/src/main/java/no/stelar7/api/r4j/pojo/val/matchlist/MatchReference.java
+++ b/src/main/java/no/stelar7/api/r4j/pojo/val/matchlist/MatchReference.java
@@ ... @@
private static final long serialVersionUID = -5301457261872587385L;
-
+
private String matchId;
- private Long gameStartTime;
- private String teamId;
-
+ private Long gameStartTimeMillis;
+ private String queueId;
+
public String getMatchId()
@@ ... @@
}
-
- public Long getGameStartTime()
+
+ public Long getGameStartTimeMillis()
{
- return gameStartTime;
+ return gameStartTimeMillis;
}
-
- public String getTeamId()
+
+ public String getQueueId()
{
- return teamId;
+ return queueId;
}
-
+
@Override
@@ ... @@
return Objects.equals(matchId, match.matchId) &&
- Objects.equals(gameStartTime, match.gameStartTime) &&
- Objects.equals(teamId, match.teamId);
+ Objects.equals(gameStartTimeMillis, match.gameStartTimeMillis) &&
+ Objects.equals(queueId, match.queueId);
}
-
+
@Override
@@ ... @@
{
- return Objects.hash(matchId, gameStartTime, teamId);
+ return Objects.hash(matchId, gameStartTimeMillis, queueId);
}
-
+
@Override
@@ ... @@
"matchId='" + matchId + '\'' +
- ", gameStartTime=" + gameStartTime +
- ", teamId='" + teamId + '\'' +
+ ", gameStartTimeMillis=" + gameStartTimeMillis +
+ ", queueId='" + queueId + '\'' +
'}';
|
--- a/src/main/java/no/stelar7/api/r4j/pojo/val/matchlist/MatchReference.java
+++ b/src/main/java/no/stelar7/api/r4j/pojo/val/matchlist/MatchReference.java
@@ -8,7 +8,7 @@
CON private static final long serialVersionUID = -5301457261872587385L;
DEL
ADD
CON private String matchId;
DEL private Long gameStartTime;
DEL private String teamId;
DEL
ADD private Long gameStartTimeMillis;
ADD private String queueId;
ADD
CON public String getMatchId()
@@ -17,13 +17,13 @@
CON }
DEL
DEL public Long getGameStartTime()
ADD
ADD public Long getGameStartTimeMillis()
CON {
DEL return gameStartTime;
ADD return gameStartTimeMillis;
CON }
DEL
DEL public String getTeamId()
ADD
ADD public String getQueueId()
CON {
DEL return teamId;
ADD return queueId;
CON }
DEL
ADD
CON @Override
@@ -41,6 +41,6 @@
CON return Objects.equals(matchId, match.matchId) &&
DEL Objects.equals(gameStartTime, match.gameStartTime) &&
DEL Objects.equals(teamId, match.teamId);
ADD Objects.equals(gameStartTimeMillis, match.gameStartTimeMillis) &&
ADD Objects.equals(queueId, match.queueId);
CON }
DEL
ADD
CON @Override
@@ -48,5 +48,5 @@
CON {
DEL return Objects.hash(matchId, gameStartTime, teamId);
ADD return Objects.hash(matchId, gameStartTimeMillis, queueId);
CON }
DEL
ADD
CON @Override
@@ -56,4 +56,4 @@
CON "matchId='" + matchId + '\'' +
DEL ", gameStartTime=" + gameStartTime +
DEL ", teamId='" + teamId + '\'' +
ADD ", gameStartTimeMillis=" + gameStartTimeMillis +
ADD ", queueId='" + queueId + '\'' +
CON '}';
|
<<<<<<< SEARCH
{
private static final long serialVersionUID = -5301457261872587385L;
private String matchId;
private Long gameStartTime;
private String teamId;
public String getMatchId()
{
return matchId;
}
public Long getGameStartTime()
{
return gameStartTime;
}
public String getTeamId()
{
return teamId;
}
@Override
public boolean equals(Object o)
=======
{
private static final long serialVersionUID = -5301457261872587385L;
private String matchId;
private Long gameStartTimeMillis;
private String queueId;
public String getMatchId()
{
return matchId;
}
public Long getGameStartTimeMillis()
{
return gameStartTimeMillis;
}
public String getQueueId()
{
return queueId;
}
@Override
public boolean equals(Object o)
>>>>>>> REPLACE
<<<<<<< SEARCH
MatchReference match = (MatchReference) o;
return Objects.equals(matchId, match.matchId) &&
Objects.equals(gameStartTime, match.gameStartTime) &&
Objects.equals(teamId, match.teamId);
}
@Override
public int hashCode()
{
return Objects.hash(matchId, gameStartTime, teamId);
}
@Override
public String toString()
{
return "Match{" +
"matchId='" + matchId + '\'' +
", gameStartTime=" + gameStartTime +
", teamId='" + teamId + '\'' +
'}';
}
=======
MatchReference match = (MatchReference) o;
return Objects.equals(matchId, match.matchId) &&
Objects.equals(gameStartTimeMillis, match.gameStartTimeMillis) &&
Objects.equals(queueId, match.queueId);
}
@Override
public int hashCode()
{
return Objects.hash(matchId, gameStartTimeMillis, queueId);
}
@Override
public String toString()
{
return "Match{" +
"matchId='" + matchId + '\'' +
", gameStartTimeMillis=" + gameStartTimeMillis +
", queueId='" + queueId + '\'' +
'}';
}
>>>>>>> REPLACE
|
praekelt/diamondash
|
445f244ddac6001b65f03d058a14178a19919eed
|
diamondash/config.py
|
python
|
bsd-3-clause
|
Allow Config to be initialised without any args
|
import yaml
from diamondash import utils
class ConfigError(Exception):
"""Raised when there is an error parsing a configuration"""
class ConfigMetaClass(type):
def __new__(mcs, name, bases, dict):
cls = type.__new__(mcs, name, bases, dict)
defaults = {}
for base in bases:
if hasattr(base, 'DEFAULTS'):
defaults.update(base.DEFAULTS)
defaults.update(cls.DEFAULTS)
cls.DEFAULTS = defaults
return cls
class Config(dict):
__metaclass__ = ConfigMetaClass
DEFAULTS = {}
def __init__(self, items):
super(Config, self).__init__(self._parse(items))
@classmethod
def parse(cls, items):
return items
@classmethod
def _parse(cls, items):
items = utils.add_dicts(cls.DEFAULTS, items)
return cls.parse(items)
@classmethod
def from_file(cls, filename, **defaults):
items = utils.add_dicts(defaults, yaml.safe_load(open(filename)))
return cls(items)
@classmethod
def for_type(cls, type_name):
type_cls = utils.load_class_by_string(type_name)
return type_cls.CONFIG_CLS
|
import yaml
from diamondash import utils
class ConfigError(Exception):
"""Raised when there is an error parsing a configuration"""
class ConfigMetaClass(type):
def __new__(mcs, name, bases, dict):
cls = type.__new__(mcs, name, bases, dict)
defaults = {}
for base in bases:
if hasattr(base, 'DEFAULTS'):
defaults.update(base.DEFAULTS)
defaults.update(cls.DEFAULTS)
cls.DEFAULTS = defaults
return cls
class Config(dict):
__metaclass__ = ConfigMetaClass
DEFAULTS = {}
def __init__(self, items=None):
super(Config, self).__init__(self._parse(items or {}))
@classmethod
def parse(cls, items):
return items
@classmethod
def _parse(cls, items):
items = utils.add_dicts(cls.DEFAULTS, items)
return cls.parse(items)
@classmethod
def from_file(cls, filename, **defaults):
items = utils.add_dicts(defaults, yaml.safe_load(open(filename)))
return cls(items)
@classmethod
def for_type(cls, type_name):
type_cls = utils.load_class_by_string(type_name)
return type_cls.CONFIG_CLS
| 2
| 2
| 1
|
mixed
|
--- a/diamondash/config.py
+++ b/diamondash/config.py
@@ -28,4 +28,4 @@
- def __init__(self, items):
- super(Config, self).__init__(self._parse(items))
+ def __init__(self, items=None):
+ super(Config, self).__init__(self._parse(items or {}))
|
--- a/diamondash/config.py
+++ b/diamondash/config.py
@@ ... @@
- def __init__(self, items):
- super(Config, self).__init__(self._parse(items))
+ def __init__(self, items=None):
+ super(Config, self).__init__(self._parse(items or {}))
|
--- a/diamondash/config.py
+++ b/diamondash/config.py
@@ -28,4 +28,4 @@
CON
DEL def __init__(self, items):
DEL super(Config, self).__init__(self._parse(items))
ADD def __init__(self, items=None):
ADD super(Config, self).__init__(self._parse(items or {}))
CON
|
<<<<<<< SEARCH
DEFAULTS = {}
def __init__(self, items):
super(Config, self).__init__(self._parse(items))
@classmethod
=======
DEFAULTS = {}
def __init__(self, items=None):
super(Config, self).__init__(self._parse(items or {}))
@classmethod
>>>>>>> REPLACE
|
cjh1/tomviz
|
c31c54624d7a46dfd9df96e32d2e07246868aecc
|
tomviz/python/DefaultITKTransform.py
|
python
|
bsd-3-clause
|
Change the ITK example to use a simpler ITK filter
|
def transform_scalars(dataset):
"""Define this method for Python operators that
transform the input array."""
from tomviz import utils
import numpy as np
import itk
# Get the current volume as a numpy array.
array = utils.get_array(dataset)
# Set up some ITK variables
itk_image_type = itk.Image.F3
itk_converter = itk.PyBuffer[itk_image_type]
# Read the image into ITK
itk_image = itk_converter.GetImageFromArray(array)
# ITK filter (I have no idea if this is right)
filter = \
itk.ConfidenceConnectedImageFilter[itk_image_type,itk.Image.SS3].New()
filter.SetInitialNeighborhoodRadius(3)
filter.SetMultiplier(3)
filter.SetNumberOfIterations(25)
filter.SetReplaceValue(255)
filter.SetSeed((24,65,37))
filter.SetInput(itk_image)
filter.Update()
# Get the image back from ITK (result is a numpy image)
result = itk.PyBuffer[itk.Image.SS3].GetArrayFromImage(filter.GetOutput())
# This is where the transformed data is set, it will display in tomviz.
utils.set_array(dataset, result)
|
import tomviz.operators
class DefaultITKTransform(tomviz.operators.CancelableOperator):
def transform_scalars(self, dataset):
"""Define this method for Python operators that transform the input
array. This example uses an ITK filter to add 10 to each voxel value."""
# Try imports to make sure we have everything that is needed
try:
from tomviz import itkutils
import itk
except Exception as exc:
print("Could not import necessary module(s)")
raise exc
self.progress.value = 0
self.progress.maximum = 100
# Add a try/except around the ITK portion. ITK exceptions are
# passed up to the Python layer, so we can at least report what
# went wrong with the script, e.g., unsupported image type.
try:
self.progress.value = 0
self.progress.message = "Converting data to ITK image"
# Get the ITK image
itk_image = itkutils.convert_vtk_to_itk_image(dataset)
itk_input_image_type = type(itk_image)
self.progress.value = 30
self.progress.message = "Running filter"
# ITK filter
filter = itk.AddImageFilter[itk_input_image_type, # Input 1
itk_input_image_type, # Input 2
itk_input_image_type].New() # Output
filter.SetInput1(itk_image)
filter.SetConstant2(10)
itkutils.observe_filter_progress(self, filter, 30, 70)
try:
filter.Update()
except RuntimeError: # Exception thrown when ITK filter is aborted
return
self.progress.message = "Saving results"
itkutils.set_array_from_itk_image(dataset, filter.GetOutput())
self.progress.value = 100
except Exception as exc:
print("Problem encountered while running %s" %
self.__class__.__name__)
raise exc
| 49
| 27
| 1
|
mixed
|
--- a/tomviz/python/DefaultITKTransform.py
+++ b/tomviz/python/DefaultITKTransform.py
@@ -1,33 +1,55 @@
-def transform_scalars(dataset):
- """Define this method for Python operators that
- transform the input array."""
- from tomviz import utils
- import numpy as np
- import itk
+import tomviz.operators
- # Get the current volume as a numpy array.
- array = utils.get_array(dataset)
- # Set up some ITK variables
- itk_image_type = itk.Image.F3
- itk_converter = itk.PyBuffer[itk_image_type]
+class DefaultITKTransform(tomviz.operators.CancelableOperator):
- # Read the image into ITK
- itk_image = itk_converter.GetImageFromArray(array)
+ def transform_scalars(self, dataset):
+ """Define this method for Python operators that transform the input
+ array. This example uses an ITK filter to add 10 to each voxel value."""
- # ITK filter (I have no idea if this is right)
- filter = \
- itk.ConfidenceConnectedImageFilter[itk_image_type,itk.Image.SS3].New()
- filter.SetInitialNeighborhoodRadius(3)
- filter.SetMultiplier(3)
- filter.SetNumberOfIterations(25)
- filter.SetReplaceValue(255)
- filter.SetSeed((24,65,37))
- filter.SetInput(itk_image)
- filter.Update()
+ # Try imports to make sure we have everything that is needed
+ try:
+ from tomviz import itkutils
+ import itk
+ except Exception as exc:
+ print("Could not import necessary module(s)")
+ raise exc
- # Get the image back from ITK (result is a numpy image)
- result = itk.PyBuffer[itk.Image.SS3].GetArrayFromImage(filter.GetOutput())
+ self.progress.value = 0
+ self.progress.maximum = 100
- # This is where the transformed data is set, it will display in tomviz.
- utils.set_array(dataset, result)
+ # Add a try/except around the ITK portion. ITK exceptions are
+ # passed up to the Python layer, so we can at least report what
+ # went wrong with the script, e.g., unsupported image type.
+ try:
+ self.progress.value = 0
+ self.progress.message = "Converting data to ITK image"
+
+ # Get the ITK image
+ itk_image = itkutils.convert_vtk_to_itk_image(dataset)
+ itk_input_image_type = type(itk_image)
+ self.progress.value = 30
+ self.progress.message = "Running filter"
+
+ # ITK filter
+ filter = itk.AddImageFilter[itk_input_image_type, # Input 1
+ itk_input_image_type, # Input 2
+ itk_input_image_type].New() # Output
+ filter.SetInput1(itk_image)
+ filter.SetConstant2(10)
+ itkutils.observe_filter_progress(self, filter, 30, 70)
+
+ try:
+ filter.Update()
+ except RuntimeError: # Exception thrown when ITK filter is aborted
+ return
+
+ self.progress.message = "Saving results"
+
+ itkutils.set_array_from_itk_image(dataset, filter.GetOutput())
+
+ self.progress.value = 100
+ except Exception as exc:
+ print("Problem encountered while running %s" %
+ self.__class__.__name__)
+ raise exc
|
--- a/tomviz/python/DefaultITKTransform.py
+++ b/tomviz/python/DefaultITKTransform.py
@@ ... @@
-def transform_scalars(dataset):
- """Define this method for Python operators that
- transform the input array."""
- from tomviz import utils
- import numpy as np
- import itk
+import tomviz.operators
- # Get the current volume as a numpy array.
- array = utils.get_array(dataset)
- # Set up some ITK variables
- itk_image_type = itk.Image.F3
- itk_converter = itk.PyBuffer[itk_image_type]
+class DefaultITKTransform(tomviz.operators.CancelableOperator):
- # Read the image into ITK
- itk_image = itk_converter.GetImageFromArray(array)
+ def transform_scalars(self, dataset):
+ """Define this method for Python operators that transform the input
+ array. This example uses an ITK filter to add 10 to each voxel value."""
- # ITK filter (I have no idea if this is right)
- filter = \
- itk.ConfidenceConnectedImageFilter[itk_image_type,itk.Image.SS3].New()
- filter.SetInitialNeighborhoodRadius(3)
- filter.SetMultiplier(3)
- filter.SetNumberOfIterations(25)
- filter.SetReplaceValue(255)
- filter.SetSeed((24,65,37))
- filter.SetInput(itk_image)
- filter.Update()
+ # Try imports to make sure we have everything that is needed
+ try:
+ from tomviz import itkutils
+ import itk
+ except Exception as exc:
+ print("Could not import necessary module(s)")
+ raise exc
- # Get the image back from ITK (result is a numpy image)
- result = itk.PyBuffer[itk.Image.SS3].GetArrayFromImage(filter.GetOutput())
+ self.progress.value = 0
+ self.progress.maximum = 100
- # This is where the transformed data is set, it will display in tomviz.
- utils.set_array(dataset, result)
+ # Add a try/except around the ITK portion. ITK exceptions are
+ # passed up to the Python layer, so we can at least report what
+ # went wrong with the script, e.g., unsupported image type.
+ try:
+ self.progress.value = 0
+ self.progress.message = "Converting data to ITK image"
+
+ # Get the ITK image
+ itk_image = itkutils.convert_vtk_to_itk_image(dataset)
+ itk_input_image_type = type(itk_image)
+ self.progress.value = 30
+ self.progress.message = "Running filter"
+
+ # ITK filter
+ filter = itk.AddImageFilter[itk_input_image_type, # Input 1
+ itk_input_image_type, # Input 2
+ itk_input_image_type].New() # Output
+ filter.SetInput1(itk_image)
+ filter.SetConstant2(10)
+ itkutils.observe_filter_progress(self, filter, 30, 70)
+
+ try:
+ filter.Update()
+ except RuntimeError: # Exception thrown when ITK filter is aborted
+ return
+
+ self.progress.message = "Saving results"
+
+ itkutils.set_array_from_itk_image(dataset, filter.GetOutput())
+
+ self.progress.value = 100
+ except Exception as exc:
+ print("Problem encountered while running %s" %
+ self.__class__.__name__)
+ raise exc
|
--- a/tomviz/python/DefaultITKTransform.py
+++ b/tomviz/python/DefaultITKTransform.py
@@ -1,33 +1,55 @@
DEL def transform_scalars(dataset):
DEL """Define this method for Python operators that
DEL transform the input array."""
DEL from tomviz import utils
DEL import numpy as np
DEL import itk
ADD import tomviz.operators
CON
DEL # Get the current volume as a numpy array.
DEL array = utils.get_array(dataset)
CON
DEL # Set up some ITK variables
DEL itk_image_type = itk.Image.F3
DEL itk_converter = itk.PyBuffer[itk_image_type]
ADD class DefaultITKTransform(tomviz.operators.CancelableOperator):
CON
DEL # Read the image into ITK
DEL itk_image = itk_converter.GetImageFromArray(array)
ADD def transform_scalars(self, dataset):
ADD """Define this method for Python operators that transform the input
ADD array. This example uses an ITK filter to add 10 to each voxel value."""
CON
DEL # ITK filter (I have no idea if this is right)
DEL filter = \
DEL itk.ConfidenceConnectedImageFilter[itk_image_type,itk.Image.SS3].New()
DEL filter.SetInitialNeighborhoodRadius(3)
DEL filter.SetMultiplier(3)
DEL filter.SetNumberOfIterations(25)
DEL filter.SetReplaceValue(255)
DEL filter.SetSeed((24,65,37))
DEL filter.SetInput(itk_image)
DEL filter.Update()
ADD # Try imports to make sure we have everything that is needed
ADD try:
ADD from tomviz import itkutils
ADD import itk
ADD except Exception as exc:
ADD print("Could not import necessary module(s)")
ADD raise exc
CON
DEL # Get the image back from ITK (result is a numpy image)
DEL result = itk.PyBuffer[itk.Image.SS3].GetArrayFromImage(filter.GetOutput())
ADD self.progress.value = 0
ADD self.progress.maximum = 100
CON
DEL # This is where the transformed data is set, it will display in tomviz.
DEL utils.set_array(dataset, result)
ADD # Add a try/except around the ITK portion. ITK exceptions are
ADD # passed up to the Python layer, so we can at least report what
ADD # went wrong with the script, e.g., unsupported image type.
ADD try:
ADD self.progress.value = 0
ADD self.progress.message = "Converting data to ITK image"
ADD
ADD # Get the ITK image
ADD itk_image = itkutils.convert_vtk_to_itk_image(dataset)
ADD itk_input_image_type = type(itk_image)
ADD self.progress.value = 30
ADD self.progress.message = "Running filter"
ADD
ADD # ITK filter
ADD filter = itk.AddImageFilter[itk_input_image_type, # Input 1
ADD itk_input_image_type, # Input 2
ADD itk_input_image_type].New() # Output
ADD filter.SetInput1(itk_image)
ADD filter.SetConstant2(10)
ADD itkutils.observe_filter_progress(self, filter, 30, 70)
ADD
ADD try:
ADD filter.Update()
ADD except RuntimeError: # Exception thrown when ITK filter is aborted
ADD return
ADD
ADD self.progress.message = "Saving results"
ADD
ADD itkutils.set_array_from_itk_image(dataset, filter.GetOutput())
ADD
ADD self.progress.value = 100
ADD except Exception as exc:
ADD print("Problem encountered while running %s" %
ADD self.__class__.__name__)
ADD raise exc
|
<<<<<<< SEARCH
def transform_scalars(dataset):
"""Define this method for Python operators that
transform the input array."""
from tomviz import utils
import numpy as np
import itk
# Get the current volume as a numpy array.
array = utils.get_array(dataset)
# Set up some ITK variables
itk_image_type = itk.Image.F3
itk_converter = itk.PyBuffer[itk_image_type]
# Read the image into ITK
itk_image = itk_converter.GetImageFromArray(array)
# ITK filter (I have no idea if this is right)
filter = \
itk.ConfidenceConnectedImageFilter[itk_image_type,itk.Image.SS3].New()
filter.SetInitialNeighborhoodRadius(3)
filter.SetMultiplier(3)
filter.SetNumberOfIterations(25)
filter.SetReplaceValue(255)
filter.SetSeed((24,65,37))
filter.SetInput(itk_image)
filter.Update()
# Get the image back from ITK (result is a numpy image)
result = itk.PyBuffer[itk.Image.SS3].GetArrayFromImage(filter.GetOutput())
# This is where the transformed data is set, it will display in tomviz.
utils.set_array(dataset, result)
=======
import tomviz.operators
class DefaultITKTransform(tomviz.operators.CancelableOperator):
def transform_scalars(self, dataset):
"""Define this method for Python operators that transform the input
array. This example uses an ITK filter to add 10 to each voxel value."""
# Try imports to make sure we have everything that is needed
try:
from tomviz import itkutils
import itk
except Exception as exc:
print("Could not import necessary module(s)")
raise exc
self.progress.value = 0
self.progress.maximum = 100
# Add a try/except around the ITK portion. ITK exceptions are
# passed up to the Python layer, so we can at least report what
# went wrong with the script, e.g., unsupported image type.
try:
self.progress.value = 0
self.progress.message = "Converting data to ITK image"
# Get the ITK image
itk_image = itkutils.convert_vtk_to_itk_image(dataset)
itk_input_image_type = type(itk_image)
self.progress.value = 30
self.progress.message = "Running filter"
# ITK filter
filter = itk.AddImageFilter[itk_input_image_type, # Input 1
itk_input_image_type, # Input 2
itk_input_image_type].New() # Output
filter.SetInput1(itk_image)
filter.SetConstant2(10)
itkutils.observe_filter_progress(self, filter, 30, 70)
try:
filter.Update()
except RuntimeError: # Exception thrown when ITK filter is aborted
return
self.progress.message = "Saving results"
itkutils.set_array_from_itk_image(dataset, filter.GetOutput())
self.progress.value = 100
except Exception as exc:
print("Problem encountered while running %s" %
self.__class__.__name__)
raise exc
>>>>>>> REPLACE
|
way2muchnoise/JustEnoughItems
|
129d1d2a955a0bb5cd859687bc09434a2a55a6d6
|
src/main/java/mezz/jei/plugins/vanilla/furnace/FuelRecipe.java
|
java
|
mit
|
Fix fuel recipe transfer helper
|
package mezz.jei.plugins.vanilla.furnace;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.awt.Color;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import net.minecraft.client.Minecraft;
import net.minecraft.item.ItemStack;
import mezz.jei.plugins.vanilla.VanillaRecipeWrapper;
import mezz.jei.util.Translator;
public class FuelRecipe extends VanillaRecipeWrapper {
@Nonnull
private final List<ItemStack> input;
@Nullable
private final String burnTimeString;
public FuelRecipe(@Nonnull Collection<ItemStack> input, int burnTime) {
this.input = new ArrayList<>(input);
this.burnTimeString = Translator.translateToLocalFormatted("gui.jei.furnaceBurnTime", burnTime);
}
@Nonnull
@Override
public List<ItemStack> getInputs() {
return input;
}
@Nonnull
@Override
public List<ItemStack> getOutputs() {
return Collections.emptyList();
}
@Override
public void drawInfo(@Nonnull Minecraft minecraft, int recipeWidth, int recipeHeight) {
minecraft.fontRendererObj.drawString(burnTimeString, 24, 12, Color.gray.getRGB());
}
}
|
package mezz.jei.plugins.vanilla.furnace;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.awt.Color;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import net.minecraft.client.Minecraft;
import net.minecraft.item.ItemStack;
import mezz.jei.plugins.vanilla.VanillaRecipeWrapper;
import mezz.jei.util.Translator;
public class FuelRecipe extends VanillaRecipeWrapper {
@Nonnull
private final List<List<ItemStack>> inputs;
@Nonnull
private final String burnTimeString;
public FuelRecipe(@Nonnull Collection<ItemStack> input, int burnTime) {
this.inputs = Collections.singletonList(new ArrayList<>(input));
this.burnTimeString = Translator.translateToLocalFormatted("gui.jei.furnaceBurnTime", burnTime);
}
@Nonnull
@Override
public List<List<ItemStack>> getInputs() {
return inputs;
}
@Nonnull
@Override
public List<ItemStack> getOutputs() {
return Collections.emptyList();
}
@Override
public void drawInfo(@Nonnull Minecraft minecraft, int recipeWidth, int recipeHeight) {
minecraft.fontRendererObj.drawString(burnTimeString, 24, 12, Color.gray.getRGB());
}
}
| 5
| 5
| 3
|
mixed
|
--- a/src/main/java/mezz/jei/plugins/vanilla/furnace/FuelRecipe.java
+++ b/src/main/java/mezz/jei/plugins/vanilla/furnace/FuelRecipe.java
@@ -18,4 +18,4 @@
@Nonnull
- private final List<ItemStack> input;
- @Nullable
+ private final List<List<ItemStack>> inputs;
+ @Nonnull
private final String burnTimeString;
@@ -23,3 +23,3 @@
public FuelRecipe(@Nonnull Collection<ItemStack> input, int burnTime) {
- this.input = new ArrayList<>(input);
+ this.inputs = Collections.singletonList(new ArrayList<>(input));
this.burnTimeString = Translator.translateToLocalFormatted("gui.jei.furnaceBurnTime", burnTime);
@@ -29,4 +29,4 @@
@Override
- public List<ItemStack> getInputs() {
- return input;
+ public List<List<ItemStack>> getInputs() {
+ return inputs;
}
|
--- a/src/main/java/mezz/jei/plugins/vanilla/furnace/FuelRecipe.java
+++ b/src/main/java/mezz/jei/plugins/vanilla/furnace/FuelRecipe.java
@@ ... @@
@Nonnull
- private final List<ItemStack> input;
- @Nullable
+ private final List<List<ItemStack>> inputs;
+ @Nonnull
private final String burnTimeString;
@@ ... @@
public FuelRecipe(@Nonnull Collection<ItemStack> input, int burnTime) {
- this.input = new ArrayList<>(input);
+ this.inputs = Collections.singletonList(new ArrayList<>(input));
this.burnTimeString = Translator.translateToLocalFormatted("gui.jei.furnaceBurnTime", burnTime);
@@ ... @@
@Override
- public List<ItemStack> getInputs() {
- return input;
+ public List<List<ItemStack>> getInputs() {
+ return inputs;
}
|
--- a/src/main/java/mezz/jei/plugins/vanilla/furnace/FuelRecipe.java
+++ b/src/main/java/mezz/jei/plugins/vanilla/furnace/FuelRecipe.java
@@ -18,4 +18,4 @@
CON @Nonnull
DEL private final List<ItemStack> input;
DEL @Nullable
ADD private final List<List<ItemStack>> inputs;
ADD @Nonnull
CON private final String burnTimeString;
@@ -23,3 +23,3 @@
CON public FuelRecipe(@Nonnull Collection<ItemStack> input, int burnTime) {
DEL this.input = new ArrayList<>(input);
ADD this.inputs = Collections.singletonList(new ArrayList<>(input));
CON this.burnTimeString = Translator.translateToLocalFormatted("gui.jei.furnaceBurnTime", burnTime);
@@ -29,4 +29,4 @@
CON @Override
DEL public List<ItemStack> getInputs() {
DEL return input;
ADD public List<List<ItemStack>> getInputs() {
ADD return inputs;
CON }
|
<<<<<<< SEARCH
public class FuelRecipe extends VanillaRecipeWrapper {
@Nonnull
private final List<ItemStack> input;
@Nullable
private final String burnTimeString;
public FuelRecipe(@Nonnull Collection<ItemStack> input, int burnTime) {
this.input = new ArrayList<>(input);
this.burnTimeString = Translator.translateToLocalFormatted("gui.jei.furnaceBurnTime", burnTime);
}
@Nonnull
@Override
public List<ItemStack> getInputs() {
return input;
}
=======
public class FuelRecipe extends VanillaRecipeWrapper {
@Nonnull
private final List<List<ItemStack>> inputs;
@Nonnull
private final String burnTimeString;
public FuelRecipe(@Nonnull Collection<ItemStack> input, int burnTime) {
this.inputs = Collections.singletonList(new ArrayList<>(input));
this.burnTimeString = Translator.translateToLocalFormatted("gui.jei.furnaceBurnTime", burnTime);
}
@Nonnull
@Override
public List<List<ItemStack>> getInputs() {
return inputs;
}
>>>>>>> REPLACE
|
MaibornWolff/codecharta
|
abc911edec296f9975f65d98692e30e9f59344ef
|
analysis/import/CodeMaatImporter/src/main/kotlin/de/maibornwolff/codecharta/importer/codemaat/CSVRow.kt
|
kotlin
|
bsd-3-clause
|
Fix type cast for edge-attributes
|
package de.maibornwolff.codecharta.importer.codemaat
import de.maibornwolff.codecharta.model.*
import java.util.*
import java.util.regex.Pattern
class CSVRow(private val row: Array<String?>, private val header: CSVHeader, private val pathSeparator: Char) {
init {
if (row.size <= header.pathColumn.size) {
throw IllegalArgumentException(
"Row " + Arrays.toString(row) + " has no column containing the file path. Should be in one of " + header.pathColumn + " columns.")
}
}
fun asEdge(): Edge {
val rootNode = "/root/"
val fromNodeName = rootNode + allColumns.get("entity")
val toNodeName = rootNode + allColumns.get("coupled")
return Edge(fromNodeName, toNodeName, attributes)
}
private val allColumns: Map<String, String> =
header.columnNumbers
.filter { validAttributeValue(it) }
.associateBy(
{ header.getColumnName(it) },
{ row[it]!! }
)
private val attributes: Map<String, String> =
header.columnNumbers
.filter { validAttributeValue(it) && isAttributeColumn(it) }
.associateBy(
{ header.getColumnName(it) },
{ row[it]!! }
)
private fun validAttributeValue(i: Int) =
i < row.size
&& row[i] != null
private fun isAttributeColumn(i: Int) =
header.pathColumn.filter { pathColumnIndex -> i == pathColumnIndex }.isEmpty()
}
|
package de.maibornwolff.codecharta.importer.codemaat
import de.maibornwolff.codecharta.model.*
import java.util.*
class CSVRow(private val row: Array<String?>, private val header: CSVHeader, private val pathSeparator: Char) {
init {
if (row.size <= header.pathColumn.size) {
throw IllegalArgumentException(
"Row " + Arrays.toString(row) + " has no column containing the file path. Should be in one of " + header.pathColumn + " columns.")
}
}
fun asEdge(): Edge {
val rootNode = "/root/"
val fromNodeName = rootNode + allColumns.get("entity")
val toNodeName = rootNode + allColumns.get("coupled")
return Edge(fromNodeName, toNodeName, attributes)
}
private val allColumns: Map<String, String> =
header.columnNumbers
.filter { validAttributeValue(it) }
.associateBy(
{ header.getColumnName(it) },
{ row[it]!! }
)
private val attributes: Map<String, Int> =
header.columnNumbers
.filter { validAttributeValue(it) && isAttributeColumn(it) }
.associateBy(
{ header.getColumnName(it) },
{ row[it]!!.toInt() }
)
private fun validAttributeValue(i: Int) =
i < row.size && row[i] != null
private fun isAttributeColumn(i: Int) =
header.pathColumn.filter { pathColumnIndex -> i == pathColumnIndex }.isEmpty()
}
| 3
| 5
| 4
|
mixed
|
--- a/analysis/import/CodeMaatImporter/src/main/kotlin/de/maibornwolff/codecharta/importer/codemaat/CSVRow.kt
+++ b/analysis/import/CodeMaatImporter/src/main/kotlin/de/maibornwolff/codecharta/importer/codemaat/CSVRow.kt
@@ -4,3 +4,2 @@
import java.util.*
-import java.util.regex.Pattern
@@ -31,3 +30,3 @@
- private val attributes: Map<String, String> =
+ private val attributes: Map<String, Int> =
header.columnNumbers
@@ -36,3 +35,3 @@
{ header.getColumnName(it) },
- { row[it]!! }
+ { row[it]!!.toInt() }
)
@@ -40,4 +39,3 @@
private fun validAttributeValue(i: Int) =
- i < row.size
- && row[i] != null
+ i < row.size && row[i] != null
|
--- a/analysis/import/CodeMaatImporter/src/main/kotlin/de/maibornwolff/codecharta/importer/codemaat/CSVRow.kt
+++ b/analysis/import/CodeMaatImporter/src/main/kotlin/de/maibornwolff/codecharta/importer/codemaat/CSVRow.kt
@@ ... @@
import java.util.*
-import java.util.regex.Pattern
@@ ... @@
- private val attributes: Map<String, String> =
+ private val attributes: Map<String, Int> =
header.columnNumbers
@@ ... @@
{ header.getColumnName(it) },
- { row[it]!! }
+ { row[it]!!.toInt() }
)
@@ ... @@
private fun validAttributeValue(i: Int) =
- i < row.size
- && row[i] != null
+ i < row.size && row[i] != null
|
--- a/analysis/import/CodeMaatImporter/src/main/kotlin/de/maibornwolff/codecharta/importer/codemaat/CSVRow.kt
+++ b/analysis/import/CodeMaatImporter/src/main/kotlin/de/maibornwolff/codecharta/importer/codemaat/CSVRow.kt
@@ -4,3 +4,2 @@
CON import java.util.*
DEL import java.util.regex.Pattern
CON
@@ -31,3 +30,3 @@
CON
DEL private val attributes: Map<String, String> =
ADD private val attributes: Map<String, Int> =
CON header.columnNumbers
@@ -36,3 +35,3 @@
CON { header.getColumnName(it) },
DEL { row[it]!! }
ADD { row[it]!!.toInt() }
CON )
@@ -40,4 +39,3 @@
CON private fun validAttributeValue(i: Int) =
DEL i < row.size
DEL && row[i] != null
ADD i < row.size && row[i] != null
CON
|
<<<<<<< SEARCH
import de.maibornwolff.codecharta.model.*
import java.util.*
import java.util.regex.Pattern
class CSVRow(private val row: Array<String?>, private val header: CSVHeader, private val pathSeparator: Char) {
=======
import de.maibornwolff.codecharta.model.*
import java.util.*
class CSVRow(private val row: Array<String?>, private val header: CSVHeader, private val pathSeparator: Char) {
>>>>>>> REPLACE
<<<<<<< SEARCH
)
private val attributes: Map<String, String> =
header.columnNumbers
.filter { validAttributeValue(it) && isAttributeColumn(it) }
.associateBy(
{ header.getColumnName(it) },
{ row[it]!! }
)
private fun validAttributeValue(i: Int) =
i < row.size
&& row[i] != null
private fun isAttributeColumn(i: Int) =
=======
)
private val attributes: Map<String, Int> =
header.columnNumbers
.filter { validAttributeValue(it) && isAttributeColumn(it) }
.associateBy(
{ header.getColumnName(it) },
{ row[it]!!.toInt() }
)
private fun validAttributeValue(i: Int) =
i < row.size && row[i] != null
private fun isAttributeColumn(i: Int) =
>>>>>>> REPLACE
|
aristiden7o/django-nose
|
8a6bc4a46141b42d4457fdc4d63df234f788253d
|
django_nose/plugin.py
|
python
|
bsd-3-clause
|
Allow coverage to work and keep stdout and be activated before initial imports.
|
class ResultPlugin(object):
"""
Captures the TestResult object for later inspection.
nose doesn't return the full test result object from any of its runner
methods. Pass an instance of this plugin to the TestProgram and use
``result`` after running the tests to get the TestResult object.
"""
name = "result"
enabled = True
def finalize(self, result):
self.result = result
class DjangoSetUpPlugin(object):
"""
Configures Django to setup and tear down the environment.
This allows coverage to report on all code imported and used during the
initialisation of the test runner.
"""
name = "django setup"
enabled = True
# We need this to run before the coverage plugin (which has a score
# of 500), so that we still have a stdout for the user interaction
# Django sometimes wants to do during test database setup.
score = 700
def __init__(self, runner):
super(DjangoSetUpPlugin, self).__init__()
self.runner = runner
def begin(self):
"""Setup the environment"""
self.runner.setup_test_environment()
self.old_names = self.runner.setup_databases()
def finalize(self, result):
"""Destroy the environment"""
self.runner.teardown_databases(self.old_names)
self.runner.teardown_test_environment()
|
import sys
class ResultPlugin(object):
"""
Captures the TestResult object for later inspection.
nose doesn't return the full test result object from any of its runner
methods. Pass an instance of this plugin to the TestProgram and use
``result`` after running the tests to get the TestResult object.
"""
name = "result"
enabled = True
def finalize(self, result):
self.result = result
class DjangoSetUpPlugin(object):
"""
Configures Django to setup and tear down the environment.
This allows coverage to report on all code imported and used during the
initialisation of the test runner.
"""
name = "django setup"
enabled = True
def __init__(self, runner):
super(DjangoSetUpPlugin, self).__init__()
self.runner = runner
self.sys_stdout = sys.stdout
def begin(self):
"""Setup the environment"""
sys_stdout = sys.stdout
sys.stdout = self.sys_stdout
self.runner.setup_test_environment()
self.old_names = self.runner.setup_databases()
sys.stdout = sys_stdout
def finalize(self, result):
"""Destroy the environment"""
self.runner.teardown_databases(self.old_names)
self.runner.teardown_test_environment()
| 7
| 7
| 4
|
mixed
|
--- a/django_nose/plugin.py
+++ b/django_nose/plugin.py
@@ -1,2 +1,2 @@
-
+import sys
@@ -24,10 +24,4 @@
"""
-
name = "django setup"
enabled = True
-
- # We need this to run before the coverage plugin (which has a score
- # of 500), so that we still have a stdout for the user interaction
- # Django sometimes wants to do during test database setup.
- score = 700
@@ -36,2 +30,3 @@
self.runner = runner
+ self.sys_stdout = sys.stdout
@@ -39,4 +34,9 @@
"""Setup the environment"""
+ sys_stdout = sys.stdout
+ sys.stdout = self.sys_stdout
+
self.runner.setup_test_environment()
self.old_names = self.runner.setup_databases()
+
+ sys.stdout = sys_stdout
|
--- a/django_nose/plugin.py
+++ b/django_nose/plugin.py
@@ ... @@
-
+import sys
@@ ... @@
"""
-
name = "django setup"
enabled = True
-
- # We need this to run before the coverage plugin (which has a score
- # of 500), so that we still have a stdout for the user interaction
- # Django sometimes wants to do during test database setup.
- score = 700
@@ ... @@
self.runner = runner
+ self.sys_stdout = sys.stdout
@@ ... @@
"""Setup the environment"""
+ sys_stdout = sys.stdout
+ sys.stdout = self.sys_stdout
+
self.runner.setup_test_environment()
self.old_names = self.runner.setup_databases()
+
+ sys.stdout = sys_stdout
|
--- a/django_nose/plugin.py
+++ b/django_nose/plugin.py
@@ -1,2 +1,2 @@
DEL
ADD import sys
CON
@@ -24,10 +24,4 @@
CON """
DEL
CON name = "django setup"
CON enabled = True
DEL
DEL # We need this to run before the coverage plugin (which has a score
DEL # of 500), so that we still have a stdout for the user interaction
DEL # Django sometimes wants to do during test database setup.
DEL score = 700
CON
@@ -36,2 +30,3 @@
CON self.runner = runner
ADD self.sys_stdout = sys.stdout
CON
@@ -39,4 +34,9 @@
CON """Setup the environment"""
ADD sys_stdout = sys.stdout
ADD sys.stdout = self.sys_stdout
ADD
CON self.runner.setup_test_environment()
CON self.old_names = self.runner.setup_databases()
ADD
ADD sys.stdout = sys_stdout
CON
|
<<<<<<< SEARCH
class ResultPlugin(object):
=======
import sys
class ResultPlugin(object):
>>>>>>> REPLACE
<<<<<<< SEARCH
initialisation of the test runner.
"""
name = "django setup"
enabled = True
# We need this to run before the coverage plugin (which has a score
# of 500), so that we still have a stdout for the user interaction
# Django sometimes wants to do during test database setup.
score = 700
def __init__(self, runner):
super(DjangoSetUpPlugin, self).__init__()
self.runner = runner
def begin(self):
"""Setup the environment"""
self.runner.setup_test_environment()
self.old_names = self.runner.setup_databases()
def finalize(self, result):
=======
initialisation of the test runner.
"""
name = "django setup"
enabled = True
def __init__(self, runner):
super(DjangoSetUpPlugin, self).__init__()
self.runner = runner
self.sys_stdout = sys.stdout
def begin(self):
"""Setup the environment"""
sys_stdout = sys.stdout
sys.stdout = self.sys_stdout
self.runner.setup_test_environment()
self.old_names = self.runner.setup_databases()
sys.stdout = sys_stdout
def finalize(self, result):
>>>>>>> REPLACE
|
cython/cython
|
c872b9991ec1a80d03906cebfb43e71335ba9c26
|
tests/run/generator_frame_cycle.py
|
python
|
apache-2.0
|
Fix a CPython comparison test in CPython 3.3 which was apparently fixed only in 3.4 and later.
|
# mode: run
# tag: generator
import cython
import sys
def test_generator_frame_cycle():
"""
>>> test_generator_frame_cycle()
("I'm done",)
"""
testit = []
def whoo():
try:
yield
except:
yield
finally:
testit.append("I'm done")
g = whoo()
next(g)
# Frame object cycle
eval('g.throw(ValueError)', {'g': g})
del g
if cython.compiled:
# FIXME: this should not be necessary, but I can't see how to do it...
import gc; gc.collect()
return tuple(testit)
def test_generator_frame_cycle_with_outer_exc():
"""
>>> test_generator_frame_cycle_with_outer_exc()
("I'm done",)
"""
testit = []
def whoo():
try:
yield
except:
yield
finally:
testit.append("I'm done")
g = whoo()
next(g)
try:
raise ValueError()
except ValueError as exc:
assert sys.exc_info()[1] is exc, sys.exc_info()
# Frame object cycle
eval('g.throw(ValueError)', {'g': g})
assert sys.exc_info()[1] is exc, sys.exc_info()
del g
assert sys.exc_info()[1] is exc, sys.exc_info()
if cython.compiled:
# FIXME: this should not be necessary, but I can't see how to do it...
import gc; gc.collect()
return tuple(testit)
|
# mode: run
# tag: generator
import cython
import sys
def test_generator_frame_cycle():
"""
>>> test_generator_frame_cycle()
("I'm done",)
"""
testit = []
def whoo():
try:
yield
except:
yield
finally:
testit.append("I'm done")
g = whoo()
next(g)
# Frame object cycle
eval('g.throw(ValueError)', {'g': g})
del g
return tuple(testit)
def test_generator_frame_cycle_with_outer_exc():
"""
>>> test_generator_frame_cycle_with_outer_exc()
("I'm done",)
"""
testit = []
def whoo():
try:
yield
except:
yield
finally:
testit.append("I'm done")
g = whoo()
next(g)
try:
raise ValueError()
except ValueError as exc:
assert sys.exc_info()[1] is exc, sys.exc_info()
# Frame object cycle
eval('g.throw(ValueError)', {'g': g})
# CPython 3.3 handles this incorrectly itself :)
if cython.compiled or sys.version_info[:2] not in [(3, 2), (3, 3)]:
assert sys.exc_info()[1] is exc, sys.exc_info()
del g
if cython.compiled or sys.version_info[:2] not in [(3, 2), (3, 3)]:
assert sys.exc_info()[1] is exc, sys.exc_info()
return tuple(testit)
| 5
| 8
| 2
|
mixed
|
--- a/tests/run/generator_frame_cycle.py
+++ b/tests/run/generator_frame_cycle.py
@@ -27,5 +27,2 @@
- if cython.compiled:
- # FIXME: this should not be necessary, but I can't see how to do it...
- import gc; gc.collect()
return tuple(testit)
@@ -55,9 +52,9 @@
eval('g.throw(ValueError)', {'g': g})
- assert sys.exc_info()[1] is exc, sys.exc_info()
+ # CPython 3.3 handles this incorrectly itself :)
+ if cython.compiled or sys.version_info[:2] not in [(3, 2), (3, 3)]:
+ assert sys.exc_info()[1] is exc, sys.exc_info()
del g
- assert sys.exc_info()[1] is exc, sys.exc_info()
+ if cython.compiled or sys.version_info[:2] not in [(3, 2), (3, 3)]:
+ assert sys.exc_info()[1] is exc, sys.exc_info()
- if cython.compiled:
- # FIXME: this should not be necessary, but I can't see how to do it...
- import gc; gc.collect()
return tuple(testit)
|
--- a/tests/run/generator_frame_cycle.py
+++ b/tests/run/generator_frame_cycle.py
@@ ... @@
- if cython.compiled:
- # FIXME: this should not be necessary, but I can't see how to do it...
- import gc; gc.collect()
return tuple(testit)
@@ ... @@
eval('g.throw(ValueError)', {'g': g})
- assert sys.exc_info()[1] is exc, sys.exc_info()
+ # CPython 3.3 handles this incorrectly itself :)
+ if cython.compiled or sys.version_info[:2] not in [(3, 2), (3, 3)]:
+ assert sys.exc_info()[1] is exc, sys.exc_info()
del g
- assert sys.exc_info()[1] is exc, sys.exc_info()
+ if cython.compiled or sys.version_info[:2] not in [(3, 2), (3, 3)]:
+ assert sys.exc_info()[1] is exc, sys.exc_info()
- if cython.compiled:
- # FIXME: this should not be necessary, but I can't see how to do it...
- import gc; gc.collect()
return tuple(testit)
|
--- a/tests/run/generator_frame_cycle.py
+++ b/tests/run/generator_frame_cycle.py
@@ -27,5 +27,2 @@
CON
DEL if cython.compiled:
DEL # FIXME: this should not be necessary, but I can't see how to do it...
DEL import gc; gc.collect()
CON return tuple(testit)
@@ -55,9 +52,9 @@
CON eval('g.throw(ValueError)', {'g': g})
DEL assert sys.exc_info()[1] is exc, sys.exc_info()
ADD # CPython 3.3 handles this incorrectly itself :)
ADD if cython.compiled or sys.version_info[:2] not in [(3, 2), (3, 3)]:
ADD assert sys.exc_info()[1] is exc, sys.exc_info()
CON del g
DEL assert sys.exc_info()[1] is exc, sys.exc_info()
ADD if cython.compiled or sys.version_info[:2] not in [(3, 2), (3, 3)]:
ADD assert sys.exc_info()[1] is exc, sys.exc_info()
CON
DEL if cython.compiled:
DEL # FIXME: this should not be necessary, but I can't see how to do it...
DEL import gc; gc.collect()
CON return tuple(testit)
|
<<<<<<< SEARCH
del g
if cython.compiled:
# FIXME: this should not be necessary, but I can't see how to do it...
import gc; gc.collect()
return tuple(testit)
=======
del g
return tuple(testit)
>>>>>>> REPLACE
<<<<<<< SEARCH
# Frame object cycle
eval('g.throw(ValueError)', {'g': g})
assert sys.exc_info()[1] is exc, sys.exc_info()
del g
assert sys.exc_info()[1] is exc, sys.exc_info()
if cython.compiled:
# FIXME: this should not be necessary, but I can't see how to do it...
import gc; gc.collect()
return tuple(testit)
=======
# Frame object cycle
eval('g.throw(ValueError)', {'g': g})
# CPython 3.3 handles this incorrectly itself :)
if cython.compiled or sys.version_info[:2] not in [(3, 2), (3, 3)]:
assert sys.exc_info()[1] is exc, sys.exc_info()
del g
if cython.compiled or sys.version_info[:2] not in [(3, 2), (3, 3)]:
assert sys.exc_info()[1] is exc, sys.exc_info()
return tuple(testit)
>>>>>>> REPLACE
|
KitaitiMakoto/express-droonga
|
25da0863585fc96bb3f9ea8abd107365c3c6a5e5
|
lib/builders/rest-request.js
|
javascript
|
mit
|
Implement validation for numeric/integer parameter
|
function searchRequestBuilder(request) {
var params = request.params;
var queries = {};
queries.result = {
source: params.tableName,
output: {
startTime: true,
elapsedTime: true,
count: true,
attributes: true,
recodes: true
}
};
if (params.attributes)
queries.result.attributes = params.attributes.split(',');
if (params.limit)
queries.result.limit = parseInt(params.limit);
if (params.match_escalation_threshold)
queries.result.matchEscalationThreshold = parseInt(params.match_escalation_threshold);
if (params.match_to)
queries.result.matchTo = params.match_to.split(',');
if (params.offset)
queries.result.offset = parseInt(params.offset);
if (params.query)
queries.result.query = params.query;
if (params.sort_by)
queries.result.sortBy = params.sort_by.split(',');
return { queries: queries };
}
exports.search = searchRequestBuilder;
|
var NUMERIC = /^-?(?:[0-9]+(?:\.[0-9]+)?|\.[0-9]+)$/;
function getNumericValue(params, key) {
var value = params[key];
if (!NUMERIC.test(value))
throw new Error(key + ': ' +value + ' is invalid number');
return parseFloat(value);
}
var INTEGER = /^-?[0-9]+$/;
function getIntegerValue(params, key) {
var value = params[key];
if (!INTEGER.test(value))
throw new Error(key + ': ' +value + ' is invalid integer');
return parseInt(value);
}
function searchRequestBuilder(request) {
var params = request.params;
if (!params.tableName)
throw new Error('no source is specified');
var queries = {};
queries.result = {
source: params.tableName,
output: {
startTime: true,
elapsedTime: true,
count: true,
attributes: true,
recodes: true
}
};
if (params.attributes)
queries.result.attributes = params.attributes.split(',');
if (params.limit)
queries.result.limit = getIntegerValue(params, 'limit');
if (params.match_escalation_threshold)
queries.result.matchEscalationThreshold = getIntegerValue(params, 'match_escalation_threshold');
if (params.match_to)
queries.result.matchTo = params.match_to.split(',');
if (params.offset)
queries.result.offset = getIntegerValue(params, 'offset');
if (params.query)
queries.result.query = params.query;
if (params.sort_by)
queries.result.sortBy = params.sort_by.split(',');
return { queries: queries };
}
exports.search = searchRequestBuilder;
| 21
| 3
| 3
|
mixed
|
--- a/lib/builders/rest-request.js
+++ b/lib/builders/rest-request.js
@@ -1,3 +1,21 @@
+var NUMERIC = /^-?(?:[0-9]+(?:\.[0-9]+)?|\.[0-9]+)$/;
+function getNumericValue(params, key) {
+ var value = params[key];
+ if (!NUMERIC.test(value))
+ throw new Error(key + ': ' +value + ' is invalid number');
+ return parseFloat(value);
+}
+
+var INTEGER = /^-?[0-9]+$/;
+function getIntegerValue(params, key) {
+ var value = params[key];
+ if (!INTEGER.test(value))
+ throw new Error(key + ': ' +value + ' is invalid integer');
+ return parseInt(value);
+}
+
function searchRequestBuilder(request) {
var params = request.params;
+ if (!params.tableName)
+ throw new Error('no source is specified');
@@ -18,5 +36,5 @@
if (params.limit)
- queries.result.limit = parseInt(params.limit);
+ queries.result.limit = getIntegerValue(params, 'limit');
if (params.match_escalation_threshold)
- queries.result.matchEscalationThreshold = parseInt(params.match_escalation_threshold);
+ queries.result.matchEscalationThreshold = getIntegerValue(params, 'match_escalation_threshold');
if (params.match_to)
@@ -24,3 +42,3 @@
if (params.offset)
- queries.result.offset = parseInt(params.offset);
+ queries.result.offset = getIntegerValue(params, 'offset');
if (params.query)
|
--- a/lib/builders/rest-request.js
+++ b/lib/builders/rest-request.js
@@ ... @@
+var NUMERIC = /^-?(?:[0-9]+(?:\.[0-9]+)?|\.[0-9]+)$/;
+function getNumericValue(params, key) {
+ var value = params[key];
+ if (!NUMERIC.test(value))
+ throw new Error(key + ': ' +value + ' is invalid number');
+ return parseFloat(value);
+}
+
+var INTEGER = /^-?[0-9]+$/;
+function getIntegerValue(params, key) {
+ var value = params[key];
+ if (!INTEGER.test(value))
+ throw new Error(key + ': ' +value + ' is invalid integer');
+ return parseInt(value);
+}
+
function searchRequestBuilder(request) {
var params = request.params;
+ if (!params.tableName)
+ throw new Error('no source is specified');
@@ ... @@
if (params.limit)
- queries.result.limit = parseInt(params.limit);
+ queries.result.limit = getIntegerValue(params, 'limit');
if (params.match_escalation_threshold)
- queries.result.matchEscalationThreshold = parseInt(params.match_escalation_threshold);
+ queries.result.matchEscalationThreshold = getIntegerValue(params, 'match_escalation_threshold');
if (params.match_to)
@@ ... @@
if (params.offset)
- queries.result.offset = parseInt(params.offset);
+ queries.result.offset = getIntegerValue(params, 'offset');
if (params.query)
|
--- a/lib/builders/rest-request.js
+++ b/lib/builders/rest-request.js
@@ -1,3 +1,21 @@
ADD var NUMERIC = /^-?(?:[0-9]+(?:\.[0-9]+)?|\.[0-9]+)$/;
ADD function getNumericValue(params, key) {
ADD var value = params[key];
ADD if (!NUMERIC.test(value))
ADD throw new Error(key + ': ' +value + ' is invalid number');
ADD return parseFloat(value);
ADD }
ADD
ADD var INTEGER = /^-?[0-9]+$/;
ADD function getIntegerValue(params, key) {
ADD var value = params[key];
ADD if (!INTEGER.test(value))
ADD throw new Error(key + ': ' +value + ' is invalid integer');
ADD return parseInt(value);
ADD }
ADD
CON function searchRequestBuilder(request) {
CON var params = request.params;
ADD if (!params.tableName)
ADD throw new Error('no source is specified');
CON
@@ -18,5 +36,5 @@
CON if (params.limit)
DEL queries.result.limit = parseInt(params.limit);
ADD queries.result.limit = getIntegerValue(params, 'limit');
CON if (params.match_escalation_threshold)
DEL queries.result.matchEscalationThreshold = parseInt(params.match_escalation_threshold);
ADD queries.result.matchEscalationThreshold = getIntegerValue(params, 'match_escalation_threshold');
CON if (params.match_to)
@@ -24,3 +42,3 @@
CON if (params.offset)
DEL queries.result.offset = parseInt(params.offset);
ADD queries.result.offset = getIntegerValue(params, 'offset');
CON if (params.query)
|
<<<<<<< SEARCH
function searchRequestBuilder(request) {
var params = request.params;
var queries = {};
=======
var NUMERIC = /^-?(?:[0-9]+(?:\.[0-9]+)?|\.[0-9]+)$/;
function getNumericValue(params, key) {
var value = params[key];
if (!NUMERIC.test(value))
throw new Error(key + ': ' +value + ' is invalid number');
return parseFloat(value);
}
var INTEGER = /^-?[0-9]+$/;
function getIntegerValue(params, key) {
var value = params[key];
if (!INTEGER.test(value))
throw new Error(key + ': ' +value + ' is invalid integer');
return parseInt(value);
}
function searchRequestBuilder(request) {
var params = request.params;
if (!params.tableName)
throw new Error('no source is specified');
var queries = {};
>>>>>>> REPLACE
<<<<<<< SEARCH
queries.result.attributes = params.attributes.split(',');
if (params.limit)
queries.result.limit = parseInt(params.limit);
if (params.match_escalation_threshold)
queries.result.matchEscalationThreshold = parseInt(params.match_escalation_threshold);
if (params.match_to)
queries.result.matchTo = params.match_to.split(',');
if (params.offset)
queries.result.offset = parseInt(params.offset);
if (params.query)
queries.result.query = params.query;
=======
queries.result.attributes = params.attributes.split(',');
if (params.limit)
queries.result.limit = getIntegerValue(params, 'limit');
if (params.match_escalation_threshold)
queries.result.matchEscalationThreshold = getIntegerValue(params, 'match_escalation_threshold');
if (params.match_to)
queries.result.matchTo = params.match_to.split(',');
if (params.offset)
queries.result.offset = getIntegerValue(params, 'offset');
if (params.query)
queries.result.query = params.query;
>>>>>>> REPLACE
|
ktorio/ktor
|
2306a2d6eada4bb2470282a782fbd121567690eb
|
ktor-client/ktor-client-features/ktor-client-websocket/jvm/src/io/ktor/client/features/websocket/WebSocketContent.kt
|
kotlin
|
apache-2.0
|
Fix client websocket nonce size
Closes #861
|
package io.ktor.client.features.websocket
import io.ktor.client.request.*
import io.ktor.http.*
import io.ktor.http.websocket.*
import io.ktor.util.*
import java.util.*
private const val WEBSOCKET_VERSION = "13"
private const val NONCE_SIZE = 24
class WebSocketContent: ClientUpgradeContent() {
private val nonce: String = buildString {
val bytes = ByteArray(NONCE_SIZE)
random.nextBytes(bytes)
append(encodeBase64(bytes))
}
override val headers: Headers = HeadersBuilder().apply {
append(HttpHeaders.Upgrade, "websocket")
append(HttpHeaders.Connection, "upgrade")
append(HttpHeaders.SecWebSocketKey, nonce)
append(HttpHeaders.SecWebSocketVersion, WEBSOCKET_VERSION)
}.build()
override fun verify(headers: Headers) {
val serverAccept = headers[HttpHeaders.SecWebSocketAccept]
?: error("Server should specify header ${HttpHeaders.SecWebSocketAccept}")
val expectedAccept = websocketServerAccept(nonce)
check(expectedAccept == serverAccept) {
"Failed to verify server accept header. Expected: $expectedAccept, received: $serverAccept"
}
}
companion object {
private val random = Random()
}
}
|
package io.ktor.client.features.websocket
import io.ktor.client.request.*
import io.ktor.http.*
import io.ktor.http.websocket.*
import io.ktor.util.*
import java.util.*
private const val WEBSOCKET_VERSION = "13"
private const val NONCE_SIZE = 16
class WebSocketContent: ClientUpgradeContent() {
private val nonce: String = buildString {
val bytes = ByteArray(NONCE_SIZE)
random.nextBytes(bytes)
append(encodeBase64(bytes))
}
override val headers: Headers = HeadersBuilder().apply {
append(HttpHeaders.Upgrade, "websocket")
append(HttpHeaders.Connection, "upgrade")
append(HttpHeaders.SecWebSocketKey, nonce)
append(HttpHeaders.SecWebSocketVersion, WEBSOCKET_VERSION)
}.build()
override fun verify(headers: Headers) {
val serverAccept = headers[HttpHeaders.SecWebSocketAccept]
?: error("Server should specify header ${HttpHeaders.SecWebSocketAccept}")
val expectedAccept = websocketServerAccept(nonce)
check(expectedAccept == serverAccept) {
"Failed to verify server accept header. Expected: $expectedAccept, received: $serverAccept"
}
}
companion object {
private val random = Random()
}
}
| 1
| 1
| 1
|
mixed
|
--- a/ktor-client/ktor-client-features/ktor-client-websocket/jvm/src/io/ktor/client/features/websocket/WebSocketContent.kt
+++ b/ktor-client/ktor-client-features/ktor-client-websocket/jvm/src/io/ktor/client/features/websocket/WebSocketContent.kt
@@ -9,3 +9,3 @@
private const val WEBSOCKET_VERSION = "13"
-private const val NONCE_SIZE = 24
+private const val NONCE_SIZE = 16
|
--- a/ktor-client/ktor-client-features/ktor-client-websocket/jvm/src/io/ktor/client/features/websocket/WebSocketContent.kt
+++ b/ktor-client/ktor-client-features/ktor-client-websocket/jvm/src/io/ktor/client/features/websocket/WebSocketContent.kt
@@ ... @@
private const val WEBSOCKET_VERSION = "13"
-private const val NONCE_SIZE = 24
+private const val NONCE_SIZE = 16
|
--- a/ktor-client/ktor-client-features/ktor-client-websocket/jvm/src/io/ktor/client/features/websocket/WebSocketContent.kt
+++ b/ktor-client/ktor-client-features/ktor-client-websocket/jvm/src/io/ktor/client/features/websocket/WebSocketContent.kt
@@ -9,3 +9,3 @@
CON private const val WEBSOCKET_VERSION = "13"
DEL private const val NONCE_SIZE = 24
ADD private const val NONCE_SIZE = 16
CON
|
<<<<<<< SEARCH
private const val WEBSOCKET_VERSION = "13"
private const val NONCE_SIZE = 24
class WebSocketContent: ClientUpgradeContent() {
=======
private const val WEBSOCKET_VERSION = "13"
private const val NONCE_SIZE = 16
class WebSocketContent: ClientUpgradeContent() {
>>>>>>> REPLACE
|
SlickJava/Rook
|
21477e9ee55f3ac539183f3a972928fc31b912c5
|
RookServer/src/com/slickjava/rook/Server.java
|
java
|
mit
|
Test commit from codeenvy IDE... PREPARE FOR CODING FROM SCHOOL!
|
package com.slickjava.rook;
import com.slickjava.rook.map.Map;
import com.slickjava.rook.map.tile.TileManager;
import com.slickjava.rook.net.MainServer;
import com.slickjava.rook.player.PlayerManager;
public class Server {
public static int port = 4444;
public static final double ROOK_VERSION = 0.1;
public static String mapName = "Test";
public static Map gameMap;
public static MainServer server;
public static PlayerManager playerManager;
public static void main(String args[])
{
Server server = new Server();
server.init();
}
public void init()
{
//Next two lines are for testing only.
playerManager = new PlayerManager();
gameMap = new Map(mapName, 100, 100);
server = new MainServer();
System.out.println(gameMap.getTileByCoord(5, 78).getTileName());
}
public static MainServer getMainServer()
{
return server;
}
public static Map getMap()
{
return gameMap;
}
}
|
package com.slickjava.rook;
import com.slickjava.rook.map.Map;
import com.slickjava.rook.map.tile.TileManager;
import com.slickjava.rook.net.MainServer;
import com.slickjava.rook.player.PlayerManager;
public class Server {
public static int port = 4444;
public static final double ROOK_VERSION = 0.1;
public static String mapName = "Test";
public static Map gameMap;
public static MainServer server;
public static PlayerManager playerManager;
public static void main(String args[])
{
Server server = new Server();
server.init();
}
public void init()
{
//Test commit from codeenvy IDE.... yay!! let's hope I can code at school now :D
//Next two lines are for testing only.
playerManager = new PlayerManager();
gameMap = new Map(mapName, 100, 100);
server = new MainServer();
System.out.println(gameMap.getTileByCoord(5, 78).getTileName());
}
public static MainServer getMainServer()
{
return server;
}
public static Map getMap()
{
return gameMap;
}
}
| 1
| 0
| 1
|
add_only
|
--- a/RookServer/src/com/slickjava/rook/Server.java
+++ b/RookServer/src/com/slickjava/rook/Server.java
@@ -24,2 +24,3 @@
{
+ //Test commit from codeenvy IDE.... yay!! let's hope I can code at school now :D
//Next two lines are for testing only.
|
--- a/RookServer/src/com/slickjava/rook/Server.java
+++ b/RookServer/src/com/slickjava/rook/Server.java
@@ ... @@
{
+ //Test commit from codeenvy IDE.... yay!! let's hope I can code at school now :D
//Next two lines are for testing only.
|
--- a/RookServer/src/com/slickjava/rook/Server.java
+++ b/RookServer/src/com/slickjava/rook/Server.java
@@ -24,2 +24,3 @@
CON {
ADD //Test commit from codeenvy IDE.... yay!! let's hope I can code at school now :D
CON //Next two lines are for testing only.
|
<<<<<<< SEARCH
public void init()
{
//Next two lines are for testing only.
playerManager = new PlayerManager();
=======
public void init()
{
//Test commit from codeenvy IDE.... yay!! let's hope I can code at school now :D
//Next two lines are for testing only.
playerManager = new PlayerManager();
>>>>>>> REPLACE
|
apache/commons-vfs
|
5a7cd83db1dd9b49bc8d0f79cd747e15fe449bf2
|
core/src/test/java/org/apache/commons/vfs2/provider/UriParserTestCase.java
|
java
|
apache-2.0
|
Add missing Apache license header.
git-svn-id: c455d203a03ec41bf444183aad31e7cce55db786@1244680 13f79535-47bb-0310-9956-ffa450edef68
|
package org.apache.commons.vfs2.provider;
import junit.framework.Assert;
import org.junit.Test;
public class UriParserTestCase
{
@Test
public void testColonInFileName()
{
Assert.assertEquals(null, UriParser.extractScheme("some/path/some:file"));
}
@Test
public void testNormalScheme()
{
Assert.assertEquals("ftp", UriParser.extractScheme("ftp://user:pass@host/some/path/some:file"));
}
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.apache.commons.vfs2.provider;
import junit.framework.Assert;
import org.junit.Test;
/**
*
* @version $Id$
*/
public class UriParserTestCase
{
@Test
public void testColonInFileName()
{
Assert.assertEquals(null, UriParser.extractScheme("some/path/some:file"));
}
@Test
public void testNormalScheme()
{
Assert.assertEquals("ftp", UriParser.extractScheme("ftp://user:pass@host/some/path/some:file"));
}
}
| 20
| 0
| 2
|
add_only
|
--- a/core/src/test/java/org/apache/commons/vfs2/provider/UriParserTestCase.java
+++ b/core/src/test/java/org/apache/commons/vfs2/provider/UriParserTestCase.java
@@ -1 +1,17 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.apache.commons.vfs2.provider;
@@ -6,2 +22,6 @@
+/**
+ *
+ * @version $Id$
+ */
public class UriParserTestCase
|
--- a/core/src/test/java/org/apache/commons/vfs2/provider/UriParserTestCase.java
+++ b/core/src/test/java/org/apache/commons/vfs2/provider/UriParserTestCase.java
@@ ... @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.apache.commons.vfs2.provider;
@@ ... @@
+/**
+ *
+ * @version $Id$
+ */
public class UriParserTestCase
|
--- a/core/src/test/java/org/apache/commons/vfs2/provider/UriParserTestCase.java
+++ b/core/src/test/java/org/apache/commons/vfs2/provider/UriParserTestCase.java
@@ -1 +1,17 @@
ADD /*
ADD * Licensed to the Apache Software Foundation (ASF) under one or more
ADD * contributor license agreements. See the NOTICE file distributed with
ADD * this work for additional information regarding copyright ownership.
ADD * The ASF licenses this file to You under the Apache License, Version 2.0
ADD * (the "License"); you may not use this file except in compliance with
ADD * the License. You may obtain a copy of the License at
ADD *
ADD * http://www.apache.org/licenses/LICENSE-2.0
ADD *
ADD * Unless required by applicable law or agreed to in writing, software
ADD * distributed under the License is distributed on an "AS IS" BASIS,
ADD * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
ADD * See the License for the specific language governing permissions and
ADD * limitations under the License.
ADD */
CON package org.apache.commons.vfs2.provider;
@@ -6,2 +22,6 @@
CON
ADD /**
ADD *
ADD * @version $Id$
ADD */
CON public class UriParserTestCase
|
<<<<<<< SEARCH
package org.apache.commons.vfs2.provider;
=======
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.apache.commons.vfs2.provider;
>>>>>>> REPLACE
<<<<<<< SEARCH
import org.junit.Test;
public class UriParserTestCase
{
=======
import org.junit.Test;
/**
*
* @version $Id$
*/
public class UriParserTestCase
{
>>>>>>> REPLACE
|
kbknapp/corectl
|
132b84eeb4b951bb88376d170b9110636efa77bf
|
src/cli.rs
|
rust
|
mit
|
Improve help output, add version command, add stub deploy command.
|
use getopts;
pub fn run(args: Vec<String>) -> Result<String, String> {
let options = getopts::Options::new();
let matches = match options.parse(args.iter().skip(1)) {
Ok(matches) => matches,
Err(fail) => return Err(fail.to_err_msg())
};
let usage = Ok(options.usage("Usage: corectl COMMAND [OPTIONS]"));
if matches.free.len() == 0 {
return usage;
}
let command = matches.free[0].as_slice();
match command {
"help" => usage,
unknown => { Err(format!("Unknown command: {}. Run `corectl help` for help.", unknown)) }
}
}
#[cfg(test)]
mod tests {
use super::run;
#[test]
fn it_prints_help_with_no_args() {
let output = run(vec!["corectl".to_string()]);
assert!(output.unwrap().starts_with("Usage: corectl COMMAND [OPTIONS]\n\nOptions:"));
}
}
|
use getopts;
const USAGE: &'static str = "Usage: corectl [OPTIONS] COMMAND [COMMAND OPTIONS]
Commands:
deploy Deploy fleet units
help Output this help message
version Output corectl's version number";
pub fn run(args: Vec<String>) -> Result<String, String> {
let mut options = getopts::Options::new();
options.optflag("h", "help", "Output this help message");
options.optflag("v", "version", "Output corectl's version number");
let matches = match options.parse(args.iter().skip(1)) {
Ok(matches) => matches,
Err(fail) => return Err(fail.to_err_msg())
};
let usage = Ok(options.usage(USAGE));
if matches.opt_present("v") {
return version();
} else if matches.opt_present("h") {
return usage;
}
if matches.free.len() == 0 {
return usage;
}
let command = matches.free[0].as_slice();
match command {
"version" => version(),
"deploy" => deploy(matches.free.clone()),
"help" => usage,
unknown => { Err(format!("Unknown command: {}. Run `corectl` for help.", unknown)) }
}
}
fn deploy(args: Vec<String>) -> Result<String, String> {
Ok("Deployed stuff.".to_string())
}
fn version() -> Result<String, String> {
Ok(env!("CARGO_PKG_VERSION").to_string())
}
#[cfg(test)]
mod tests {
use super::run;
#[test]
fn it_prints_help_with_no_args() {
let output = run(vec!["corectl".to_string()]);
assert!(output.unwrap().starts_with("Usage: corectl [OPTIONS] COMMAND [COMMAND OPTIONS]\n\nOptions:"));
}
}
| 29
| 4
| 4
|
mixed
|
--- a/src/cli.rs
+++ b/src/cli.rs
@@ -2,4 +2,13 @@
+const USAGE: &'static str = "Usage: corectl [OPTIONS] COMMAND [COMMAND OPTIONS]
+
+Commands:
+ deploy Deploy fleet units
+ help Output this help message
+ version Output corectl's version number";
+
pub fn run(args: Vec<String>) -> Result<String, String> {
- let options = getopts::Options::new();
+ let mut options = getopts::Options::new();
+ options.optflag("h", "help", "Output this help message");
+ options.optflag("v", "version", "Output corectl's version number");
let matches = match options.parse(args.iter().skip(1)) {
@@ -8,3 +17,9 @@
};
- let usage = Ok(options.usage("Usage: corectl COMMAND [OPTIONS]"));
+ let usage = Ok(options.usage(USAGE));
+
+ if matches.opt_present("v") {
+ return version();
+ } else if matches.opt_present("h") {
+ return usage;
+ }
@@ -17,5 +32,15 @@
match command {
+ "version" => version(),
+ "deploy" => deploy(matches.free.clone()),
"help" => usage,
- unknown => { Err(format!("Unknown command: {}. Run `corectl help` for help.", unknown)) }
+ unknown => { Err(format!("Unknown command: {}. Run `corectl` for help.", unknown)) }
}
+}
+
+fn deploy(args: Vec<String>) -> Result<String, String> {
+ Ok("Deployed stuff.".to_string())
+}
+
+fn version() -> Result<String, String> {
+ Ok(env!("CARGO_PKG_VERSION").to_string())
}
@@ -30,3 +55,3 @@
- assert!(output.unwrap().starts_with("Usage: corectl COMMAND [OPTIONS]\n\nOptions:"));
+ assert!(output.unwrap().starts_with("Usage: corectl [OPTIONS] COMMAND [COMMAND OPTIONS]\n\nOptions:"));
}
|
--- a/src/cli.rs
+++ b/src/cli.rs
@@ ... @@
+const USAGE: &'static str = "Usage: corectl [OPTIONS] COMMAND [COMMAND OPTIONS]
+
+Commands:
+ deploy Deploy fleet units
+ help Output this help message
+ version Output corectl's version number";
+
pub fn run(args: Vec<String>) -> Result<String, String> {
- let options = getopts::Options::new();
+ let mut options = getopts::Options::new();
+ options.optflag("h", "help", "Output this help message");
+ options.optflag("v", "version", "Output corectl's version number");
let matches = match options.parse(args.iter().skip(1)) {
@@ ... @@
};
- let usage = Ok(options.usage("Usage: corectl COMMAND [OPTIONS]"));
+ let usage = Ok(options.usage(USAGE));
+
+ if matches.opt_present("v") {
+ return version();
+ } else if matches.opt_present("h") {
+ return usage;
+ }
@@ ... @@
match command {
+ "version" => version(),
+ "deploy" => deploy(matches.free.clone()),
"help" => usage,
- unknown => { Err(format!("Unknown command: {}. Run `corectl help` for help.", unknown)) }
+ unknown => { Err(format!("Unknown command: {}. Run `corectl` for help.", unknown)) }
}
+}
+
+fn deploy(args: Vec<String>) -> Result<String, String> {
+ Ok("Deployed stuff.".to_string())
+}
+
+fn version() -> Result<String, String> {
+ Ok(env!("CARGO_PKG_VERSION").to_string())
}
@@ ... @@
- assert!(output.unwrap().starts_with("Usage: corectl COMMAND [OPTIONS]\n\nOptions:"));
+ assert!(output.unwrap().starts_with("Usage: corectl [OPTIONS] COMMAND [COMMAND OPTIONS]\n\nOptions:"));
}
|
--- a/src/cli.rs
+++ b/src/cli.rs
@@ -2,4 +2,13 @@
CON
ADD const USAGE: &'static str = "Usage: corectl [OPTIONS] COMMAND [COMMAND OPTIONS]
ADD
ADD Commands:
ADD deploy Deploy fleet units
ADD help Output this help message
ADD version Output corectl's version number";
ADD
CON pub fn run(args: Vec<String>) -> Result<String, String> {
DEL let options = getopts::Options::new();
ADD let mut options = getopts::Options::new();
ADD options.optflag("h", "help", "Output this help message");
ADD options.optflag("v", "version", "Output corectl's version number");
CON let matches = match options.parse(args.iter().skip(1)) {
@@ -8,3 +17,9 @@
CON };
DEL let usage = Ok(options.usage("Usage: corectl COMMAND [OPTIONS]"));
ADD let usage = Ok(options.usage(USAGE));
ADD
ADD if matches.opt_present("v") {
ADD return version();
ADD } else if matches.opt_present("h") {
ADD return usage;
ADD }
CON
@@ -17,5 +32,15 @@
CON match command {
ADD "version" => version(),
ADD "deploy" => deploy(matches.free.clone()),
CON "help" => usage,
DEL unknown => { Err(format!("Unknown command: {}. Run `corectl help` for help.", unknown)) }
ADD unknown => { Err(format!("Unknown command: {}. Run `corectl` for help.", unknown)) }
CON }
ADD }
ADD
ADD fn deploy(args: Vec<String>) -> Result<String, String> {
ADD Ok("Deployed stuff.".to_string())
ADD }
ADD
ADD fn version() -> Result<String, String> {
ADD Ok(env!("CARGO_PKG_VERSION").to_string())
CON }
@@ -30,3 +55,3 @@
CON
DEL assert!(output.unwrap().starts_with("Usage: corectl COMMAND [OPTIONS]\n\nOptions:"));
ADD assert!(output.unwrap().starts_with("Usage: corectl [OPTIONS] COMMAND [COMMAND OPTIONS]\n\nOptions:"));
CON }
|
<<<<<<< SEARCH
use getopts;
pub fn run(args: Vec<String>) -> Result<String, String> {
let options = getopts::Options::new();
let matches = match options.parse(args.iter().skip(1)) {
Ok(matches) => matches,
Err(fail) => return Err(fail.to_err_msg())
};
let usage = Ok(options.usage("Usage: corectl COMMAND [OPTIONS]"));
if matches.free.len() == 0 {
=======
use getopts;
const USAGE: &'static str = "Usage: corectl [OPTIONS] COMMAND [COMMAND OPTIONS]
Commands:
deploy Deploy fleet units
help Output this help message
version Output corectl's version number";
pub fn run(args: Vec<String>) -> Result<String, String> {
let mut options = getopts::Options::new();
options.optflag("h", "help", "Output this help message");
options.optflag("v", "version", "Output corectl's version number");
let matches = match options.parse(args.iter().skip(1)) {
Ok(matches) => matches,
Err(fail) => return Err(fail.to_err_msg())
};
let usage = Ok(options.usage(USAGE));
if matches.opt_present("v") {
return version();
} else if matches.opt_present("h") {
return usage;
}
if matches.free.len() == 0 {
>>>>>>> REPLACE
<<<<<<< SEARCH
match command {
"help" => usage,
unknown => { Err(format!("Unknown command: {}. Run `corectl help` for help.", unknown)) }
}
}
=======
match command {
"version" => version(),
"deploy" => deploy(matches.free.clone()),
"help" => usage,
unknown => { Err(format!("Unknown command: {}. Run `corectl` for help.", unknown)) }
}
}
fn deploy(args: Vec<String>) -> Result<String, String> {
Ok("Deployed stuff.".to_string())
}
fn version() -> Result<String, String> {
Ok(env!("CARGO_PKG_VERSION").to_string())
}
>>>>>>> REPLACE
<<<<<<< SEARCH
let output = run(vec!["corectl".to_string()]);
assert!(output.unwrap().starts_with("Usage: corectl COMMAND [OPTIONS]\n\nOptions:"));
}
}
=======
let output = run(vec!["corectl".to_string()]);
assert!(output.unwrap().starts_with("Usage: corectl [OPTIONS] COMMAND [COMMAND OPTIONS]\n\nOptions:"));
}
}
>>>>>>> REPLACE
|
jbroni/roundpieces-slackbot
|
1b18e963cc02a14d6f5f2f7775b49abb7a335b48
|
src/roundpiecesbot.js
|
javascript
|
mit
|
Print help in console when user messages help or ?
|
'use strict';
const Bot = require('slackbots');
const util = require('util');
const RoundpiecesBot = function Constructor(settings) {
this.settings = settings;
};
RoundpiecesBot.prototype.run = function () {
RoundpiecesBot.super_.call(this, this.settings);
this.on('start', this._onStart);
this.on('message', this._onMessage);
};
RoundpiecesBot.prototype._onStart = function () {
this.postMessageToUser(this.settings.adminUserName, 'RoundpiecesBot fully activated!');
};
RoundpiecesBot.prototype._onMessage = function (message) {
console.log(message);
};
util.inherits(RoundpiecesBot, Bot);
module.exports = RoundpiecesBot;
|
'use strict';
const Bot = require('slackbots');
const util = require('util');
const RoundpiecesBot = function Constructor(settings) {
this.settings = settings;
};
RoundpiecesBot.prototype.run = function () {
RoundpiecesBot.super_.call(this, this.settings);
this.on('start', this._onStart);
this.on('message', this._onMessage);
};
RoundpiecesBot.prototype._onStart = function () {
this.postMessageToUser(this.settings.adminUserName,
'RoundpiecesBot fully activated! Type help for a full list of commands');
};
RoundpiecesBot.prototype._onMessage = function (message) {
if (message.type === 'message') {
switch (message.text) {
case 'help':
case '?':
this._printHelp();
break;
default:
console.log(message);
break;
}
}
};
RoundpiecesBot.prototype._printHelp = function () {
console.log('help');
};
util.inherits(RoundpiecesBot, Bot);
module.exports = RoundpiecesBot;
| 17
| 2
| 2
|
mixed
|
--- a/src/roundpiecesbot.js
+++ b/src/roundpiecesbot.js
@@ -17,3 +17,4 @@
RoundpiecesBot.prototype._onStart = function () {
- this.postMessageToUser(this.settings.adminUserName, 'RoundpiecesBot fully activated!');
+ this.postMessageToUser(this.settings.adminUserName,
+ 'RoundpiecesBot fully activated! Type help for a full list of commands');
};
@@ -21,3 +22,17 @@
RoundpiecesBot.prototype._onMessage = function (message) {
- console.log(message);
+ if (message.type === 'message') {
+ switch (message.text) {
+ case 'help':
+ case '?':
+ this._printHelp();
+ break;
+ default:
+ console.log(message);
+ break;
+ }
+ }
+};
+
+RoundpiecesBot.prototype._printHelp = function () {
+ console.log('help');
};
|
--- a/src/roundpiecesbot.js
+++ b/src/roundpiecesbot.js
@@ ... @@
RoundpiecesBot.prototype._onStart = function () {
- this.postMessageToUser(this.settings.adminUserName, 'RoundpiecesBot fully activated!');
+ this.postMessageToUser(this.settings.adminUserName,
+ 'RoundpiecesBot fully activated! Type help for a full list of commands');
};
@@ ... @@
RoundpiecesBot.prototype._onMessage = function (message) {
- console.log(message);
+ if (message.type === 'message') {
+ switch (message.text) {
+ case 'help':
+ case '?':
+ this._printHelp();
+ break;
+ default:
+ console.log(message);
+ break;
+ }
+ }
+};
+
+RoundpiecesBot.prototype._printHelp = function () {
+ console.log('help');
};
|
--- a/src/roundpiecesbot.js
+++ b/src/roundpiecesbot.js
@@ -17,3 +17,4 @@
CON RoundpiecesBot.prototype._onStart = function () {
DEL this.postMessageToUser(this.settings.adminUserName, 'RoundpiecesBot fully activated!');
ADD this.postMessageToUser(this.settings.adminUserName,
ADD 'RoundpiecesBot fully activated! Type help for a full list of commands');
CON };
@@ -21,3 +22,17 @@
CON RoundpiecesBot.prototype._onMessage = function (message) {
DEL console.log(message);
ADD if (message.type === 'message') {
ADD switch (message.text) {
ADD case 'help':
ADD case '?':
ADD this._printHelp();
ADD break;
ADD default:
ADD console.log(message);
ADD break;
ADD }
ADD }
ADD };
ADD
ADD RoundpiecesBot.prototype._printHelp = function () {
ADD console.log('help');
CON };
|
<<<<<<< SEARCH
RoundpiecesBot.prototype._onStart = function () {
this.postMessageToUser(this.settings.adminUserName, 'RoundpiecesBot fully activated!');
};
RoundpiecesBot.prototype._onMessage = function (message) {
console.log(message);
};
=======
RoundpiecesBot.prototype._onStart = function () {
this.postMessageToUser(this.settings.adminUserName,
'RoundpiecesBot fully activated! Type help for a full list of commands');
};
RoundpiecesBot.prototype._onMessage = function (message) {
if (message.type === 'message') {
switch (message.text) {
case 'help':
case '?':
this._printHelp();
break;
default:
console.log(message);
break;
}
}
};
RoundpiecesBot.prototype._printHelp = function () {
console.log('help');
};
>>>>>>> REPLACE
|
rackerlabs/pitchfork
|
27f47ef27654dfa9c68bb90d3b8fae2e3a281396
|
pitchfork/__init__.py
|
python
|
apache-2.0
|
Move out app setup to setup file to finish cleaning up the init file
|
# Copyright 2014 Dave Kludt
#
# 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.
from flask import Flask, g
from happymongo import HapPyMongo
from config import config
from adminbp import bp as admin_bp
from manage_globals import bp as manage_bp
from engine import bp as engine_bp
from inspect import getmembers, isfunction
import context_functions
import views
import template_filters
app = Flask(__name__)
app.config.from_object(config)
app.register_blueprint(admin_bp, url_prefix='/admin')
app.register_blueprint(manage_bp, url_prefix='/manage')
app.register_blueprint(engine_bp, url_prefix='/engine')
# Setup DB based on the app name
mongo, db = HapPyMongo(config)
custom_filters = {
name: function for name, function in getmembers(template_filters)
if isfunction(function)
}
app.jinja_env.filters.update(custom_filters)
app.context_processor(context_functions.utility_processor)
views.ProductsView.register(app)
views.MiscView.register(app)
@app.before_request
def before_request():
g.db = db
|
# Copyright 2014 Dave Kludt
#
# 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.
import setup_application
app, db = setup_application.create_app()
| 2
| 34
| 1
|
mixed
|
--- a/pitchfork/__init__.py
+++ b/pitchfork/__init__.py
@@ -14,37 +14,5 @@
-from flask import Flask, g
-from happymongo import HapPyMongo
-from config import config
-from adminbp import bp as admin_bp
-from manage_globals import bp as manage_bp
-from engine import bp as engine_bp
-from inspect import getmembers, isfunction
+import setup_application
-import context_functions
-import views
-import template_filters
-
-
-app = Flask(__name__)
-app.config.from_object(config)
-app.register_blueprint(admin_bp, url_prefix='/admin')
-app.register_blueprint(manage_bp, url_prefix='/manage')
-app.register_blueprint(engine_bp, url_prefix='/engine')
-
-# Setup DB based on the app name
-mongo, db = HapPyMongo(config)
-custom_filters = {
- name: function for name, function in getmembers(template_filters)
- if isfunction(function)
-}
-app.jinja_env.filters.update(custom_filters)
-app.context_processor(context_functions.utility_processor)
-
-views.ProductsView.register(app)
-views.MiscView.register(app)
-
-
[email protected]_request
-def before_request():
- g.db = db
+app, db = setup_application.create_app()
|
--- a/pitchfork/__init__.py
+++ b/pitchfork/__init__.py
@@ ... @@
-from flask import Flask, g
-from happymongo import HapPyMongo
-from config import config
-from adminbp import bp as admin_bp
-from manage_globals import bp as manage_bp
-from engine import bp as engine_bp
-from inspect import getmembers, isfunction
+import setup_application
-import context_functions
-import views
-import template_filters
-
-
-app = Flask(__name__)
-app.config.from_object(config)
-app.register_blueprint(admin_bp, url_prefix='/admin')
-app.register_blueprint(manage_bp, url_prefix='/manage')
-app.register_blueprint(engine_bp, url_prefix='/engine')
-
-# Setup DB based on the app name
-mongo, db = HapPyMongo(config)
-custom_filters = {
- name: function for name, function in getmembers(template_filters)
- if isfunction(function)
-}
-app.jinja_env.filters.update(custom_filters)
-app.context_processor(context_functions.utility_processor)
-
-views.ProductsView.register(app)
-views.MiscView.register(app)
-
-
[email protected]_request
-def before_request():
- g.db = db
+app, db = setup_application.create_app()
|
--- a/pitchfork/__init__.py
+++ b/pitchfork/__init__.py
@@ -14,37 +14,5 @@
CON
DEL from flask import Flask, g
DEL from happymongo import HapPyMongo
DEL from config import config
DEL from adminbp import bp as admin_bp
DEL from manage_globals import bp as manage_bp
DEL from engine import bp as engine_bp
DEL from inspect import getmembers, isfunction
ADD import setup_application
CON
CON
DEL import context_functions
DEL import views
DEL import template_filters
DEL
DEL
DEL app = Flask(__name__)
DEL app.config.from_object(config)
DEL app.register_blueprint(admin_bp, url_prefix='/admin')
DEL app.register_blueprint(manage_bp, url_prefix='/manage')
DEL app.register_blueprint(engine_bp, url_prefix='/engine')
DEL
DEL # Setup DB based on the app name
DEL mongo, db = HapPyMongo(config)
DEL custom_filters = {
DEL name: function for name, function in getmembers(template_filters)
DEL if isfunction(function)
DEL }
DEL app.jinja_env.filters.update(custom_filters)
DEL app.context_processor(context_functions.utility_processor)
DEL
DEL views.ProductsView.register(app)
DEL views.MiscView.register(app)
DEL
DEL
DEL @app.before_request
DEL def before_request():
DEL g.db = db
ADD app, db = setup_application.create_app()
|
<<<<<<< SEARCH
# limitations under the License.
from flask import Flask, g
from happymongo import HapPyMongo
from config import config
from adminbp import bp as admin_bp
from manage_globals import bp as manage_bp
from engine import bp as engine_bp
from inspect import getmembers, isfunction
import context_functions
import views
import template_filters
app = Flask(__name__)
app.config.from_object(config)
app.register_blueprint(admin_bp, url_prefix='/admin')
app.register_blueprint(manage_bp, url_prefix='/manage')
app.register_blueprint(engine_bp, url_prefix='/engine')
# Setup DB based on the app name
mongo, db = HapPyMongo(config)
custom_filters = {
name: function for name, function in getmembers(template_filters)
if isfunction(function)
}
app.jinja_env.filters.update(custom_filters)
app.context_processor(context_functions.utility_processor)
views.ProductsView.register(app)
views.MiscView.register(app)
@app.before_request
def before_request():
g.db = db
=======
# limitations under the License.
import setup_application
app, db = setup_application.create_app()
>>>>>>> REPLACE
|
rtfd/readthedocs.org
|
20017da43fe1bf5287b33d9d2fc7f597850bb5b5
|
readthedocs/settings/proxito/base.py
|
python
|
mit
|
Expand the logic in our proxito mixin.
This makes proxito mixin match production for .com/.org
in the areas where we are overriding the same things.
|
"""
Base settings for Proxito
Some of these settings will eventually be backported into the main settings file,
but currently we have them to be able to run the site with the old middleware for
a staged rollout of the proxito code.
"""
class CommunityProxitoSettingsMixin:
ROOT_URLCONF = 'readthedocs.proxito.urls'
USE_SUBDOMAIN = True
@property
def MIDDLEWARE(self): # noqa
# Use our new middleware instead of the old one
classes = super().MIDDLEWARE
classes = list(classes)
index = classes.index(
'readthedocs.core.middleware.SubdomainMiddleware'
)
classes[index] = 'readthedocs.proxito.middleware.ProxitoMiddleware'
middleware_to_remove = (
'readthedocs.core.middleware.SingleVersionMiddleware',
'csp.middleware.CSPMiddleware',
)
for mw in middleware_to_remove:
if mw in classes:
classes.remove(mw)
return classes
|
"""
Base settings for Proxito
Some of these settings will eventually be backported into the main settings file,
but currently we have them to be able to run the site with the old middleware for
a staged rollout of the proxito code.
"""
class CommunityProxitoSettingsMixin:
ROOT_URLCONF = 'readthedocs.proxito.urls'
USE_SUBDOMAIN = True
@property
def DATABASES(self):
# This keeps connections to the DB alive,
# which reduces latency with connecting to postgres
dbs = getattr(super(), 'DATABASES', {})
for db in dbs.keys():
dbs[db]['CONN_MAX_AGE'] = 86400
return dbs
@property
def MIDDLEWARE(self): # noqa
# Use our new middleware instead of the old one
classes = super().MIDDLEWARE
classes = list(classes)
index = classes.index(
'readthedocs.core.middleware.SubdomainMiddleware'
)
classes[index] = 'readthedocs.proxito.middleware.ProxitoMiddleware'
middleware_to_remove = (
'readthedocs.core.middleware.SingleVersionMiddleware',
'csp.middleware.CSPMiddleware',
)
for mw in middleware_to_remove:
if mw in classes:
classes.remove(mw)
return classes
| 10
| 0
| 2
|
add_only
|
--- a/readthedocs/settings/proxito/base.py
+++ b/readthedocs/settings/proxito/base.py
@@ -8,2 +8,3 @@
+
class CommunityProxitoSettingsMixin:
@@ -12,2 +13,11 @@
USE_SUBDOMAIN = True
+
+ @property
+ def DATABASES(self):
+ # This keeps connections to the DB alive,
+ # which reduces latency with connecting to postgres
+ dbs = getattr(super(), 'DATABASES', {})
+ for db in dbs.keys():
+ dbs[db]['CONN_MAX_AGE'] = 86400
+ return dbs
|
--- a/readthedocs/settings/proxito/base.py
+++ b/readthedocs/settings/proxito/base.py
@@ ... @@
+
class CommunityProxitoSettingsMixin:
@@ ... @@
USE_SUBDOMAIN = True
+
+ @property
+ def DATABASES(self):
+ # This keeps connections to the DB alive,
+ # which reduces latency with connecting to postgres
+ dbs = getattr(super(), 'DATABASES', {})
+ for db in dbs.keys():
+ dbs[db]['CONN_MAX_AGE'] = 86400
+ return dbs
|
--- a/readthedocs/settings/proxito/base.py
+++ b/readthedocs/settings/proxito/base.py
@@ -8,2 +8,3 @@
CON
ADD
CON class CommunityProxitoSettingsMixin:
@@ -12,2 +13,11 @@
CON USE_SUBDOMAIN = True
ADD
ADD @property
ADD def DATABASES(self):
ADD # This keeps connections to the DB alive,
ADD # which reduces latency with connecting to postgres
ADD dbs = getattr(super(), 'DATABASES', {})
ADD for db in dbs.keys():
ADD dbs[db]['CONN_MAX_AGE'] = 86400
ADD return dbs
CON
|
<<<<<<< SEARCH
"""
class CommunityProxitoSettingsMixin:
ROOT_URLCONF = 'readthedocs.proxito.urls'
USE_SUBDOMAIN = True
@property
=======
"""
class CommunityProxitoSettingsMixin:
ROOT_URLCONF = 'readthedocs.proxito.urls'
USE_SUBDOMAIN = True
@property
def DATABASES(self):
# This keeps connections to the DB alive,
# which reduces latency with connecting to postgres
dbs = getattr(super(), 'DATABASES', {})
for db in dbs.keys():
dbs[db]['CONN_MAX_AGE'] = 86400
return dbs
@property
>>>>>>> REPLACE
|
mayah/rust-puyoai
|
d227aae8aa58f7554fd3da1d01e70251b8da9425
|
puyocore/src/column_puyo.rs
|
rust
|
mit
|
:white_check_mark: Use documentation test in ColumnPuyo
|
use color::PuyoColor;
#[derive(Clone, Debug, PartialEq)]
pub struct ColumnPuyo {
x: usize,
color: PuyoColor,
}
impl ColumnPuyo {
pub fn new(x: usize, color: PuyoColor) -> ColumnPuyo {
ColumnPuyo {
x: x,
color: color,
}
}
pub fn x(&self) -> usize {
self.x
}
pub fn color(&self) -> PuyoColor {
self.color
}
pub fn valid(&self) -> bool {
0 < self.x && self.x < 7
}
}
#[cfg(test)]
mod tests {
use super::*;
use color::PuyoColor;
#[test]
fn test_is_valid() {
assert!(!ColumnPuyo::new(0, PuyoColor::EMPTY).valid());
assert!(ColumnPuyo::new(1, PuyoColor::EMPTY).valid());
assert!(ColumnPuyo::new(2, PuyoColor::EMPTY).valid());
assert!(ColumnPuyo::new(3, PuyoColor::EMPTY).valid());
assert!(ColumnPuyo::new(4, PuyoColor::EMPTY).valid());
assert!(ColumnPuyo::new(5, PuyoColor::EMPTY).valid());
assert!(ColumnPuyo::new(6, PuyoColor::EMPTY).valid());
assert!(!ColumnPuyo::new(7, PuyoColor::EMPTY).valid());
}
}
|
use color::PuyoColor;
#[derive(Clone, Debug, PartialEq)]
pub struct ColumnPuyo {
x: usize,
color: PuyoColor,
}
impl ColumnPuyo {
pub fn new(x: usize, color: PuyoColor) -> ColumnPuyo {
ColumnPuyo {
x: x,
color: color,
}
}
pub fn x(&self) -> usize {
self.x
}
pub fn color(&self) -> PuyoColor {
self.color
}
/// Returns true if ColumnPuyo is valid. x should be 0 < x < 7.
///
/// ```
/// use puyocore::color::PuyoColor;
/// use puyocore::column_puyo::ColumnPuyo;
/// let cp0 = ColumnPuyo::new(0, PuyoColor::RED);
/// let cp1 = ColumnPuyo::new(1, PuyoColor::RED);
/// let cp6 = ColumnPuyo::new(1, PuyoColor::RED);
/// let cp7 = ColumnPuyo::new(7, PuyoColor::RED);
/// assert!(!cp0.valid());
/// assert!(cp1.valid());
/// assert!(cp6.valid());
/// assert!(!cp7.valid());
/// ```
pub fn valid(&self) -> bool {
0 < self.x && self.x < 7
}
}
| 14
| 18
| 2
|
mixed
|
--- a/puyocore/src/column_puyo.rs
+++ b/puyocore/src/column_puyo.rs
@@ -24,2 +24,16 @@
+ /// Returns true if ColumnPuyo is valid. x should be 0 < x < 7.
+ ///
+ /// ```
+ /// use puyocore::color::PuyoColor;
+ /// use puyocore::column_puyo::ColumnPuyo;
+ /// let cp0 = ColumnPuyo::new(0, PuyoColor::RED);
+ /// let cp1 = ColumnPuyo::new(1, PuyoColor::RED);
+ /// let cp6 = ColumnPuyo::new(1, PuyoColor::RED);
+ /// let cp7 = ColumnPuyo::new(7, PuyoColor::RED);
+ /// assert!(!cp0.valid());
+ /// assert!(cp1.valid());
+ /// assert!(cp6.valid());
+ /// assert!(!cp7.valid());
+ /// ```
pub fn valid(&self) -> bool {
@@ -28,19 +42 @@
}
-
-#[cfg(test)]
-mod tests {
- use super::*;
- use color::PuyoColor;
-
- #[test]
- fn test_is_valid() {
- assert!(!ColumnPuyo::new(0, PuyoColor::EMPTY).valid());
- assert!(ColumnPuyo::new(1, PuyoColor::EMPTY).valid());
- assert!(ColumnPuyo::new(2, PuyoColor::EMPTY).valid());
- assert!(ColumnPuyo::new(3, PuyoColor::EMPTY).valid());
- assert!(ColumnPuyo::new(4, PuyoColor::EMPTY).valid());
- assert!(ColumnPuyo::new(5, PuyoColor::EMPTY).valid());
- assert!(ColumnPuyo::new(6, PuyoColor::EMPTY).valid());
- assert!(!ColumnPuyo::new(7, PuyoColor::EMPTY).valid());
- }
-}
|
--- a/puyocore/src/column_puyo.rs
+++ b/puyocore/src/column_puyo.rs
@@ ... @@
+ /// Returns true if ColumnPuyo is valid. x should be 0 < x < 7.
+ ///
+ /// ```
+ /// use puyocore::color::PuyoColor;
+ /// use puyocore::column_puyo::ColumnPuyo;
+ /// let cp0 = ColumnPuyo::new(0, PuyoColor::RED);
+ /// let cp1 = ColumnPuyo::new(1, PuyoColor::RED);
+ /// let cp6 = ColumnPuyo::new(1, PuyoColor::RED);
+ /// let cp7 = ColumnPuyo::new(7, PuyoColor::RED);
+ /// assert!(!cp0.valid());
+ /// assert!(cp1.valid());
+ /// assert!(cp6.valid());
+ /// assert!(!cp7.valid());
+ /// ```
pub fn valid(&self) -> bool {
@@ ... @@
}
-
-#[cfg(test)]
-mod tests {
- use super::*;
- use color::PuyoColor;
-
- #[test]
- fn test_is_valid() {
- assert!(!ColumnPuyo::new(0, PuyoColor::EMPTY).valid());
- assert!(ColumnPuyo::new(1, PuyoColor::EMPTY).valid());
- assert!(ColumnPuyo::new(2, PuyoColor::EMPTY).valid());
- assert!(ColumnPuyo::new(3, PuyoColor::EMPTY).valid());
- assert!(ColumnPuyo::new(4, PuyoColor::EMPTY).valid());
- assert!(ColumnPuyo::new(5, PuyoColor::EMPTY).valid());
- assert!(ColumnPuyo::new(6, PuyoColor::EMPTY).valid());
- assert!(!ColumnPuyo::new(7, PuyoColor::EMPTY).valid());
- }
-}
|
--- a/puyocore/src/column_puyo.rs
+++ b/puyocore/src/column_puyo.rs
@@ -24,2 +24,16 @@
CON
ADD /// Returns true if ColumnPuyo is valid. x should be 0 < x < 7.
ADD ///
ADD /// ```
ADD /// use puyocore::color::PuyoColor;
ADD /// use puyocore::column_puyo::ColumnPuyo;
ADD /// let cp0 = ColumnPuyo::new(0, PuyoColor::RED);
ADD /// let cp1 = ColumnPuyo::new(1, PuyoColor::RED);
ADD /// let cp6 = ColumnPuyo::new(1, PuyoColor::RED);
ADD /// let cp7 = ColumnPuyo::new(7, PuyoColor::RED);
ADD /// assert!(!cp0.valid());
ADD /// assert!(cp1.valid());
ADD /// assert!(cp6.valid());
ADD /// assert!(!cp7.valid());
ADD /// ```
CON pub fn valid(&self) -> bool {
@@ -28,19 +42 @@
CON }
DEL
DEL #[cfg(test)]
DEL mod tests {
DEL use super::*;
DEL use color::PuyoColor;
DEL
DEL #[test]
DEL fn test_is_valid() {
DEL assert!(!ColumnPuyo::new(0, PuyoColor::EMPTY).valid());
DEL assert!(ColumnPuyo::new(1, PuyoColor::EMPTY).valid());
DEL assert!(ColumnPuyo::new(2, PuyoColor::EMPTY).valid());
DEL assert!(ColumnPuyo::new(3, PuyoColor::EMPTY).valid());
DEL assert!(ColumnPuyo::new(4, PuyoColor::EMPTY).valid());
DEL assert!(ColumnPuyo::new(5, PuyoColor::EMPTY).valid());
DEL assert!(ColumnPuyo::new(6, PuyoColor::EMPTY).valid());
DEL assert!(!ColumnPuyo::new(7, PuyoColor::EMPTY).valid());
DEL }
DEL }
|
<<<<<<< SEARCH
}
pub fn valid(&self) -> bool {
0 < self.x && self.x < 7
}
}
#[cfg(test)]
mod tests {
use super::*;
use color::PuyoColor;
#[test]
fn test_is_valid() {
assert!(!ColumnPuyo::new(0, PuyoColor::EMPTY).valid());
assert!(ColumnPuyo::new(1, PuyoColor::EMPTY).valid());
assert!(ColumnPuyo::new(2, PuyoColor::EMPTY).valid());
assert!(ColumnPuyo::new(3, PuyoColor::EMPTY).valid());
assert!(ColumnPuyo::new(4, PuyoColor::EMPTY).valid());
assert!(ColumnPuyo::new(5, PuyoColor::EMPTY).valid());
assert!(ColumnPuyo::new(6, PuyoColor::EMPTY).valid());
assert!(!ColumnPuyo::new(7, PuyoColor::EMPTY).valid());
}
}
=======
}
/// Returns true if ColumnPuyo is valid. x should be 0 < x < 7.
///
/// ```
/// use puyocore::color::PuyoColor;
/// use puyocore::column_puyo::ColumnPuyo;
/// let cp0 = ColumnPuyo::new(0, PuyoColor::RED);
/// let cp1 = ColumnPuyo::new(1, PuyoColor::RED);
/// let cp6 = ColumnPuyo::new(1, PuyoColor::RED);
/// let cp7 = ColumnPuyo::new(7, PuyoColor::RED);
/// assert!(!cp0.valid());
/// assert!(cp1.valid());
/// assert!(cp6.valid());
/// assert!(!cp7.valid());
/// ```
pub fn valid(&self) -> bool {
0 < self.x && self.x < 7
}
}
>>>>>>> REPLACE
|
AyaNakazawa/business_card_bank
|
1018b38e5dba5c26378826bc9bdb9e64bb469eaa
|
js/mylib/popover.js
|
javascript
|
mit
|
Fix remove echoPermission option in PopoverModel
|
// ----------------------------------------------------------------
// Popover Class
class PopoverModel extends CommonModel {
constructor({
name = 'Popover',
selector = null,
help = 'popover',
trigger = 'hover'
} = {})
{
super({
name: name,
echoPermission: false
});
this.NAME = name;
this.SELECTOR = selector;
this.HELP = help;
this.TRIGGER = trigger;
}
}
class PopoverView extends CommonView {
constructor(_model = new PopoverModel()) {
super(_model);
this.setPopover();
}
setPopover() {
if (this.model.SELECTOR != null) {
$(this.model.SELECTOR).attr('data-toggle', 'popover');
$(this.model.SELECTOR).attr('data-content', this.model.HELP);
$(this.model.SELECTOR).attr('data-trigger', this.model.TRIGGER);
$(this.model.SELECTOR).popover();
}
}
}
// ----------------------------------------------------------------
// Controllers
class PopoverController extends CommonController {
constructor(_obj) {
super({
name: 'Popover Controller'
});
this.model = new PopoverModel(_obj);
this.view = new PopoverView(this.model);
}
}
|
// ----------------------------------------------------------------
// Popover Class
class PopoverModel extends CommonModel {
constructor({
name = 'Popover',
selector = null,
help = 'popover',
trigger = 'hover'
} = {})
{
super({
name: name
});
this.NAME = name;
this.SELECTOR = selector;
this.HELP = help;
this.TRIGGER = trigger;
}
}
class PopoverView extends CommonView {
constructor(_model = new PopoverModel()) {
super(_model);
this.setPopover();
}
setPopover() {
if (this.model.SELECTOR != null) {
$(this.model.SELECTOR).attr('data-toggle', 'popover');
$(this.model.SELECTOR).attr('data-content', this.model.HELP);
$(this.model.SELECTOR).attr('data-trigger', this.model.TRIGGER);
$(this.model.SELECTOR).popover();
}
}
}
// ----------------------------------------------------------------
// Controllers
class PopoverController extends CommonController {
constructor(_obj) {
super({
name: 'Popover Controller'
});
this.model = new PopoverModel(_obj);
this.view = new PopoverView(this.model);
}
}
| 1
| 2
| 1
|
mixed
|
--- a/js/mylib/popover.js
+++ b/js/mylib/popover.js
@@ -13,4 +13,3 @@
super({
- name: name,
- echoPermission: false
+ name: name
});
|
--- a/js/mylib/popover.js
+++ b/js/mylib/popover.js
@@ ... @@
super({
- name: name,
- echoPermission: false
+ name: name
});
|
--- a/js/mylib/popover.js
+++ b/js/mylib/popover.js
@@ -13,4 +13,3 @@
CON super({
DEL name: name,
DEL echoPermission: false
ADD name: name
CON });
|
<<<<<<< SEARCH
{
super({
name: name,
echoPermission: false
});
=======
{
super({
name: name
});
>>>>>>> REPLACE
|
elifarley/kotlin-examples
|
7c1c2610a7d0b2192e7d397b1a8b9a678e953d99
|
src/com/github/elifarley/kotlin/textfile/ReportLogHandler.kt
|
kotlin
|
mit
|
Use "MaxFrequencyBarrier" when inserting; Store MD5 in binary(16) field
|
package com.orgecc.textfile
import com.orgecc.util.StreamingResultSetEnabledJdbcTemplate
import org.springframework.jdbc.core.JdbcTemplate
import java.sql.Date
import javax.sql.DataSource
open class ReportLogHandler(open val config: ReportLogConfig, dataSource: DataSource) {
companion object : WithLogging()
protected val jdbcTemplate: JdbcTemplate
init {
this.jdbcTemplate = StreamingResultSetEnabledJdbcTemplate(dataSource).apply {
this.fetchSize = 1000
}
}
protected val nextSeqQuery = "select top 1 LAST_SEQUENCE_NUMBER + 1 as nextSeq, dateadd(day, 1, LAST_DATE_PARAM) as nextDate" +
" from REPORT_LOG where report_name='${config.reportName}' and LAST_SEQUENCE_NUMBER >= -1 order by CREATED desc -- REPORT_LOG"
private val onSuccessSQL = "insert into REPORT_LOG" +
" (REPORT_NAME, LAST_SEQUENCE_NUMBER, LAST_DATE_PARAM, MD5, ELAPSED_MILLIS, ITEM_COUNT)" +
" values (?,?,?,?,?,?)"
fun insert(lastSequenceNumber: Int, lastDateParam: Date, md5: String, itemCount: Int, elapsedMillis: Int) {
val updated = jdbcTemplate.update(
onSuccessSQL, config.reportName, lastSequenceNumber, lastDateParam, md5, elapsedMillis, itemCount
)
if (updated != 1) {
throw IllegalArgumentException("Unexpected affected count: '$updated'; SQL: [$onSuccessSQL]")
}
}
}
|
package com.orgecc.textfile
import com.orgecc.util.StreamingResultSetEnabledJdbcTemplate
import org.springframework.jdbc.core.JdbcTemplate
import java.sql.Date
import javax.sql.DataSource
open class ReportLogHandler(open val config: ReportLogConfig, dataSource: DataSource) {
companion object : WithLogging() {
val barrier = MaxFrequencyBarrier.newInstance(.9)
}
protected val jdbcTemplate: JdbcTemplate
init {
this.jdbcTemplate = StreamingResultSetEnabledJdbcTemplate(dataSource).apply {
this.fetchSize = 1000
}
}
protected val nextSeqQuery = "select top 1 LAST_SEQUENCE_NUMBER + 1 as nextSeq, dateadd(day, 1, LAST_DATE_PARAM) as nextDate" +
" from REPORT_LOG where report_name='${config.reportName}' and LAST_SEQUENCE_NUMBER >= -1 order by CREATED desc -- REPORT_LOG"
private val onSuccessSQL = "insert into REPORT_LOG" +
" (REPORT_NAME, LAST_SEQUENCE_NUMBER, LAST_DATE_PARAM, MD5, ELAPSED_MILLIS, ITEM_COUNT)" +
" values (?,?,?,?,?,?)"
fun insert(lastSequenceNumber: Int, lastDateParam: Date, md5: ByteArray, itemCount: Int, elapsedMillis: Int) {
barrier.await()
val updated = jdbcTemplate.update(
onSuccessSQL, config.reportName, lastSequenceNumber, lastDateParam, md5, elapsedMillis, itemCount
)
if (updated != 1) {
throw IllegalArgumentException("Unexpected affected count: '$updated'; SQL: [$onSuccessSQL]")
}
}
}
| 5
| 2
| 2
|
mixed
|
--- a/src/com/github/elifarley/kotlin/textfile/ReportLogHandler.kt
+++ b/src/com/github/elifarley/kotlin/textfile/ReportLogHandler.kt
@@ -9,3 +9,5 @@
- companion object : WithLogging()
+ companion object : WithLogging() {
+ val barrier = MaxFrequencyBarrier.newInstance(.9)
+ }
@@ -26,4 +28,5 @@
- fun insert(lastSequenceNumber: Int, lastDateParam: Date, md5: String, itemCount: Int, elapsedMillis: Int) {
+ fun insert(lastSequenceNumber: Int, lastDateParam: Date, md5: ByteArray, itemCount: Int, elapsedMillis: Int) {
+ barrier.await()
val updated = jdbcTemplate.update(
|
--- a/src/com/github/elifarley/kotlin/textfile/ReportLogHandler.kt
+++ b/src/com/github/elifarley/kotlin/textfile/ReportLogHandler.kt
@@ ... @@
- companion object : WithLogging()
+ companion object : WithLogging() {
+ val barrier = MaxFrequencyBarrier.newInstance(.9)
+ }
@@ ... @@
- fun insert(lastSequenceNumber: Int, lastDateParam: Date, md5: String, itemCount: Int, elapsedMillis: Int) {
+ fun insert(lastSequenceNumber: Int, lastDateParam: Date, md5: ByteArray, itemCount: Int, elapsedMillis: Int) {
+ barrier.await()
val updated = jdbcTemplate.update(
|
--- a/src/com/github/elifarley/kotlin/textfile/ReportLogHandler.kt
+++ b/src/com/github/elifarley/kotlin/textfile/ReportLogHandler.kt
@@ -9,3 +9,5 @@
CON
DEL companion object : WithLogging()
ADD companion object : WithLogging() {
ADD val barrier = MaxFrequencyBarrier.newInstance(.9)
ADD }
CON
@@ -26,4 +28,5 @@
CON
DEL fun insert(lastSequenceNumber: Int, lastDateParam: Date, md5: String, itemCount: Int, elapsedMillis: Int) {
ADD fun insert(lastSequenceNumber: Int, lastDateParam: Date, md5: ByteArray, itemCount: Int, elapsedMillis: Int) {
CON
ADD barrier.await()
CON val updated = jdbcTemplate.update(
|
<<<<<<< SEARCH
open class ReportLogHandler(open val config: ReportLogConfig, dataSource: DataSource) {
companion object : WithLogging()
protected val jdbcTemplate: JdbcTemplate
=======
open class ReportLogHandler(open val config: ReportLogConfig, dataSource: DataSource) {
companion object : WithLogging() {
val barrier = MaxFrequencyBarrier.newInstance(.9)
}
protected val jdbcTemplate: JdbcTemplate
>>>>>>> REPLACE
<<<<<<< SEARCH
" values (?,?,?,?,?,?)"
fun insert(lastSequenceNumber: Int, lastDateParam: Date, md5: String, itemCount: Int, elapsedMillis: Int) {
val updated = jdbcTemplate.update(
onSuccessSQL, config.reportName, lastSequenceNumber, lastDateParam, md5, elapsedMillis, itemCount
=======
" values (?,?,?,?,?,?)"
fun insert(lastSequenceNumber: Int, lastDateParam: Date, md5: ByteArray, itemCount: Int, elapsedMillis: Int) {
barrier.await()
val updated = jdbcTemplate.update(
onSuccessSQL, config.reportName, lastSequenceNumber, lastDateParam, md5, elapsedMillis, itemCount
>>>>>>> REPLACE
|
BjoernPetersen/JMusicBot
|
3b9ae710816438e7cf20304c93e1b6e289bc4301
|
src/main/kotlin/com/github/bjoernpetersen/musicbot/spi/plugin/Plugin.kt
|
kotlin
|
mit
|
Improve plugin config method arg naming
|
package com.github.bjoernpetersen.musicbot.spi.plugin
import com.github.bjoernpetersen.musicbot.api.config.Config
import com.github.bjoernpetersen.musicbot.spi.plugin.management.InitStateWriter
import java.io.IOException
interface Plugin {
/**
* An arbitrary plugin name. Keep it short, but descriptive.
*/
val name: String
fun createConfigEntries(config: Config): List<Config.Entry<*>>
fun createSecretEntries(config: Config): List<Config.Entry<*>>
fun createStateEntries(config: Config)
@Throws(InitializationException::class)
fun initialize(initStateWriter: InitStateWriter)
@Throws(IOException::class)
fun close()
}
interface UserFacing {
/**
* The subject of the content provided by this plugin.
*
* This will be shown to end users, together with the type of plugin, this should give users
* an idea of they will be getting.
*
* Some good examples:
* - For providers: "Spotify" or "YouTube"
* - For suggesters: "Random MP3s", a playlist name, "Based on last played song"
*/
val subject: String
}
/**
* An exception during plugin initialization.
*/
class InitializationException : Exception {
constructor() : super()
constructor(message: String) : super(message)
constructor(message: String, cause: Throwable) : super(message, cause)
constructor(cause: Throwable) : super(cause)
}
|
package com.github.bjoernpetersen.musicbot.spi.plugin
import com.github.bjoernpetersen.musicbot.api.config.Config
import com.github.bjoernpetersen.musicbot.spi.plugin.management.InitStateWriter
import java.io.IOException
interface Plugin {
/**
* An arbitrary plugin name. Keep it short, but descriptive.
*/
val name: String
fun createConfigEntries(config: Config): List<Config.Entry<*>>
fun createSecretEntries(secrets: Config): List<Config.Entry<*>>
fun createStateEntries(state: Config)
@Throws(InitializationException::class)
fun initialize(initStateWriter: InitStateWriter)
@Throws(IOException::class)
fun close()
}
interface UserFacing {
/**
* The subject of the content provided by this plugin.
*
* This will be shown to end users, together with the type of plugin, this should give users
* an idea of they will be getting.
*
* Some good examples:
* - For providers: "Spotify" or "YouTube"
* - For suggesters: "Random MP3s", a playlist name, "Based on last played song"
*/
val subject: String
}
/**
* An exception during plugin initialization.
*/
class InitializationException : Exception {
constructor() : super()
constructor(message: String) : super(message)
constructor(message: String, cause: Throwable) : super(message, cause)
constructor(cause: Throwable) : super(cause)
}
| 2
| 2
| 1
|
mixed
|
--- a/src/main/kotlin/com/github/bjoernpetersen/musicbot/spi/plugin/Plugin.kt
+++ b/src/main/kotlin/com/github/bjoernpetersen/musicbot/spi/plugin/Plugin.kt
@@ -13,4 +13,4 @@
fun createConfigEntries(config: Config): List<Config.Entry<*>>
- fun createSecretEntries(config: Config): List<Config.Entry<*>>
- fun createStateEntries(config: Config)
+ fun createSecretEntries(secrets: Config): List<Config.Entry<*>>
+ fun createStateEntries(state: Config)
|
--- a/src/main/kotlin/com/github/bjoernpetersen/musicbot/spi/plugin/Plugin.kt
+++ b/src/main/kotlin/com/github/bjoernpetersen/musicbot/spi/plugin/Plugin.kt
@@ ... @@
fun createConfigEntries(config: Config): List<Config.Entry<*>>
- fun createSecretEntries(config: Config): List<Config.Entry<*>>
- fun createStateEntries(config: Config)
+ fun createSecretEntries(secrets: Config): List<Config.Entry<*>>
+ fun createStateEntries(state: Config)
|
--- a/src/main/kotlin/com/github/bjoernpetersen/musicbot/spi/plugin/Plugin.kt
+++ b/src/main/kotlin/com/github/bjoernpetersen/musicbot/spi/plugin/Plugin.kt
@@ -13,4 +13,4 @@
CON fun createConfigEntries(config: Config): List<Config.Entry<*>>
DEL fun createSecretEntries(config: Config): List<Config.Entry<*>>
DEL fun createStateEntries(config: Config)
ADD fun createSecretEntries(secrets: Config): List<Config.Entry<*>>
ADD fun createStateEntries(state: Config)
CON
|
<<<<<<< SEARCH
fun createConfigEntries(config: Config): List<Config.Entry<*>>
fun createSecretEntries(config: Config): List<Config.Entry<*>>
fun createStateEntries(config: Config)
@Throws(InitializationException::class)
=======
fun createConfigEntries(config: Config): List<Config.Entry<*>>
fun createSecretEntries(secrets: Config): List<Config.Entry<*>>
fun createStateEntries(state: Config)
@Throws(InitializationException::class)
>>>>>>> REPLACE
|
robinverduijn/gradle
|
aba1625acce292913239e8ed39a4b331798a0600
|
buildSrc/build.gradle.kts
|
kotlin
|
apache-2.0
|
Enable precompiled script plugins on `buildSrc`
After the change to the `kotlin-dsl` plugin that no longer does it by
default.
|
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
buildscript {
val pluginsExperiments = "gradle.plugin.org.gradle.kotlin:gradle-kotlin-dsl-plugins-experiments:0.1.14"
dependencies {
classpath(pluginsExperiments)
}
project.dependencies {
"compile"(pluginsExperiments)
}
configure(listOf(repositories, project.repositories)) {
gradlePluginPortal()
}
}
plugins {
`java-gradle-plugin`
`kotlin-dsl`
}
kotlinDslPluginOptions {
experimentalWarning.set(false)
}
apply(plugin = "org.gradle.kotlin.ktlint-convention")
tasks.withType<KotlinCompile>().configureEach {
kotlinOptions {
freeCompilerArgs += listOf(
"-Xjsr305=strict",
"-Xskip-runtime-version-check",
"-Xskip-metadata-version-check"
)
}
}
dependencies {
compileOnly(gradleKotlinDsl())
compile(kotlin("gradle-plugin"))
compile(kotlin("stdlib-jdk8"))
compile(kotlin("reflect"))
compile("com.gradle.publish:plugin-publish-plugin:0.10.0")
compile("org.ow2.asm:asm:6.2")
testCompile("junit:junit:4.12")
testCompile(gradleTestKit())
}
|
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
buildscript {
val pluginsExperiments = "gradle.plugin.org.gradle.kotlin:gradle-kotlin-dsl-plugins-experiments:0.1.14"
dependencies {
classpath(pluginsExperiments)
}
project.dependencies {
"compile"(pluginsExperiments)
}
configure(listOf(repositories, project.repositories)) {
gradlePluginPortal()
}
}
plugins {
`java-gradle-plugin`
`kotlin-dsl`
`kotlin-dsl-precompiled-script-plugins`
}
kotlinDslPluginOptions {
experimentalWarning.set(false)
}
apply(plugin = "org.gradle.kotlin.ktlint-convention")
tasks.withType<KotlinCompile>().configureEach {
kotlinOptions {
freeCompilerArgs += listOf(
"-Xjsr305=strict",
"-Xskip-runtime-version-check",
"-Xskip-metadata-version-check"
)
}
}
dependencies {
compileOnly(gradleKotlinDsl())
compile(kotlin("gradle-plugin"))
compile(kotlin("stdlib-jdk8"))
compile(kotlin("reflect"))
compile("com.gradle.publish:plugin-publish-plugin:0.10.0")
compile("org.ow2.asm:asm:6.2")
testCompile("junit:junit:4.12")
testCompile(gradleTestKit())
}
| 1
| 0
| 1
|
add_only
|
--- a/buildSrc/build.gradle.kts
+++ b/buildSrc/build.gradle.kts
@@ -22,2 +22,3 @@
`kotlin-dsl`
+ `kotlin-dsl-precompiled-script-plugins`
}
|
--- a/buildSrc/build.gradle.kts
+++ b/buildSrc/build.gradle.kts
@@ ... @@
`kotlin-dsl`
+ `kotlin-dsl-precompiled-script-plugins`
}
|
--- a/buildSrc/build.gradle.kts
+++ b/buildSrc/build.gradle.kts
@@ -22,2 +22,3 @@
CON `kotlin-dsl`
ADD `kotlin-dsl-precompiled-script-plugins`
CON }
|
<<<<<<< SEARCH
`java-gradle-plugin`
`kotlin-dsl`
}
=======
`java-gradle-plugin`
`kotlin-dsl`
`kotlin-dsl-precompiled-script-plugins`
}
>>>>>>> REPLACE
|
PolymerLabs/arcs
|
5fd835079455f792b6c8b9340791f71d417ef5dd
|
java/arcs/core/host/ParticleIdentifier.kt
|
kotlin
|
bsd-3-clause
|
Fix minor typo in delimiter constant name.
PiperOrigin-RevId: 351089100
|
/*
* Copyright 2020 Google LLC.
*
* This code may only be used under the BSD style license found at
* http://polymer.github.io/LICENSE.txt
*
* Code distributed by Google as part of this project is also subject to an additional IP rights
* grant found at
* http://polymer.github.io/PATENTS.txt
*/
package arcs.core.host
import arcs.core.host.api.Particle
import kotlin.reflect.KClass
/**
* A [ParticleIdentifier] is a multiplatform identifier for a [Particle] implementation.
*
* @property id the unique identifier for this particle implementation (usually qualified classname)
*/
data class ParticleIdentifier(val id: String) {
companion object {
private val PATH_DELIMETER = Regex.fromLiteral("/")
/** Converts to JVM canonical class name format. */
fun from(location: String): ParticleIdentifier {
val canonical =
location
.split(PATH_DELIMETER)
.filter { it.isNotBlank() }
.joinToString(separator = ".")
require(canonical.isNotBlank()) { "Canonical variant of \"$location\" is blank" }
return ParticleIdentifier(canonical)
}
}
}
/** Creates a [ParticleIdenfifier] from a [KClass] */
fun KClass<out Particle>.toParticleIdentifier() = ParticleIdentifier.from(className())
|
/*
* Copyright 2020 Google LLC.
*
* This code may only be used under the BSD style license found at
* http://polymer.github.io/LICENSE.txt
*
* Code distributed by Google as part of this project is also subject to an additional IP rights
* grant found at
* http://polymer.github.io/PATENTS.txt
*/
package arcs.core.host
import arcs.core.host.api.Particle
import kotlin.reflect.KClass
/**
* A [ParticleIdentifier] is a multiplatform identifier for a [Particle] implementation.
*
* @property id the unique identifier for this particle implementation (usually qualified classname)
*/
data class ParticleIdentifier(val id: String) {
companion object {
private val PATH_DELIMITER = Regex.fromLiteral("/")
/** Converts to JVM canonical class name format. */
fun from(location: String): ParticleIdentifier {
val canonical =
location
.split(PATH_DELIMITER)
.filter { it.isNotBlank() }
.joinToString(separator = ".")
require(canonical.isNotBlank()) { "Canonical variant of \"$location\" is blank" }
return ParticleIdentifier(canonical)
}
}
}
/** Creates a [ParticleIdenfifier] from a [KClass] */
fun KClass<out Particle>.toParticleIdentifier() = ParticleIdentifier.from(className())
| 2
| 2
| 2
|
mixed
|
--- a/java/arcs/core/host/ParticleIdentifier.kt
+++ b/java/arcs/core/host/ParticleIdentifier.kt
@@ -22,3 +22,3 @@
companion object {
- private val PATH_DELIMETER = Regex.fromLiteral("/")
+ private val PATH_DELIMITER = Regex.fromLiteral("/")
@@ -28,3 +28,3 @@
location
- .split(PATH_DELIMETER)
+ .split(PATH_DELIMITER)
.filter { it.isNotBlank() }
|
--- a/java/arcs/core/host/ParticleIdentifier.kt
+++ b/java/arcs/core/host/ParticleIdentifier.kt
@@ ... @@
companion object {
- private val PATH_DELIMETER = Regex.fromLiteral("/")
+ private val PATH_DELIMITER = Regex.fromLiteral("/")
@@ ... @@
location
- .split(PATH_DELIMETER)
+ .split(PATH_DELIMITER)
.filter { it.isNotBlank() }
|
--- a/java/arcs/core/host/ParticleIdentifier.kt
+++ b/java/arcs/core/host/ParticleIdentifier.kt
@@ -22,3 +22,3 @@
CON companion object {
DEL private val PATH_DELIMETER = Regex.fromLiteral("/")
ADD private val PATH_DELIMITER = Regex.fromLiteral("/")
CON
@@ -28,3 +28,3 @@
CON location
DEL .split(PATH_DELIMETER)
ADD .split(PATH_DELIMITER)
CON .filter { it.isNotBlank() }
|
<<<<<<< SEARCH
data class ParticleIdentifier(val id: String) {
companion object {
private val PATH_DELIMETER = Regex.fromLiteral("/")
/** Converts to JVM canonical class name format. */
fun from(location: String): ParticleIdentifier {
val canonical =
location
.split(PATH_DELIMETER)
.filter { it.isNotBlank() }
.joinToString(separator = ".")
=======
data class ParticleIdentifier(val id: String) {
companion object {
private val PATH_DELIMITER = Regex.fromLiteral("/")
/** Converts to JVM canonical class name format. */
fun from(location: String): ParticleIdentifier {
val canonical =
location
.split(PATH_DELIMITER)
.filter { it.isNotBlank() }
.joinToString(separator = ".")
>>>>>>> REPLACE
|
metaborg/jsglr
|
5333efcced4cf88ce29bf0c41138d1774f1fafbf
|
org.spoofax.jsglr2.integration/src/main/java/org/spoofax/jsglr2/testset/TestSetInput.java
|
java
|
apache-2.0
|
Replace unicode characters in benchmark data
|
package org.spoofax.jsglr2.testset;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Scanner;
import org.spoofax.jsglr2.testset.testinput.TestInput;
public abstract class TestSetInput<ContentType, Input extends TestInput<ContentType>> {
public enum Type {
SINGLE, // A single file from the org.spoofax.jsglr2.integration samples resources directory
INCREMENTAL, // Multiple revisions of a single file, from a folder in the same samples resources directory
MULTIPLE, // All files with a certain extension from an absolute path
SIZED // Custom input string of dynamic size based on given argument
}
public final Type type;
protected abstract Input getInput(String filename, ContentType input);
public abstract List<Input> getInputs() throws IOException;
protected TestSetInput(Type type) {
this.type = type;
}
protected String getFileAsString(String filename) throws IOException {
InputStream inputStream = getClass().getResourceAsStream("/samples/" + filename);
return inputStreamAsString(inputStream);
}
protected String inputStreamAsString(InputStream inputStream) throws IOException {
try(Scanner s = new Scanner(inputStream)) {
s.useDelimiter("\\A");
return s.hasNext() ? s.next() : "";
}
}
}
|
package org.spoofax.jsglr2.testset;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Scanner;
import org.spoofax.jsglr2.testset.testinput.TestInput;
public abstract class TestSetInput<ContentType, Input extends TestInput<ContentType>> {
public enum Type {
SINGLE, // A single file from the org.spoofax.jsglr2.integration samples resources directory
INCREMENTAL, // Multiple revisions of a single file, from a folder in the same samples resources directory
MULTIPLE, // All files with a certain extension from an absolute path
SIZED // Custom input string of dynamic size based on given argument
}
public final Type type;
protected abstract Input getInput(String filename, ContentType input);
public abstract List<Input> getInputs() throws IOException;
protected TestSetInput(Type type) {
this.type = type;
}
protected String getFileAsString(String filename) throws IOException {
InputStream inputStream = getClass().getResourceAsStream("/samples/" + filename);
return inputStreamAsString(inputStream);
}
protected String inputStreamAsString(InputStream inputStream) throws IOException {
try(Scanner s = new Scanner(inputStream)) {
s.useDelimiter("\\A");
// Replace all characters with codepoint value > 255 with a question mark to avoid parse failures,
// assuming that they only appear in places where any character is allowed (strings, comments, ...)
return s.hasNext() ? s.next().replaceAll("[^\\x00-\\xFF]", "?") : "";
}
}
}
| 3
| 1
| 1
|
mixed
|
--- a/org.spoofax.jsglr2.integration/src/main/java/org/spoofax/jsglr2/testset/TestSetInput.java
+++ b/org.spoofax.jsglr2.integration/src/main/java/org/spoofax/jsglr2/testset/TestSetInput.java
@@ -38,3 +38,5 @@
- return s.hasNext() ? s.next() : "";
+ // Replace all characters with codepoint value > 255 with a question mark to avoid parse failures,
+ // assuming that they only appear in places where any character is allowed (strings, comments, ...)
+ return s.hasNext() ? s.next().replaceAll("[^\\x00-\\xFF]", "?") : "";
}
|
--- a/org.spoofax.jsglr2.integration/src/main/java/org/spoofax/jsglr2/testset/TestSetInput.java
+++ b/org.spoofax.jsglr2.integration/src/main/java/org/spoofax/jsglr2/testset/TestSetInput.java
@@ ... @@
- return s.hasNext() ? s.next() : "";
+ // Replace all characters with codepoint value > 255 with a question mark to avoid parse failures,
+ // assuming that they only appear in places where any character is allowed (strings, comments, ...)
+ return s.hasNext() ? s.next().replaceAll("[^\\x00-\\xFF]", "?") : "";
}
|
--- a/org.spoofax.jsglr2.integration/src/main/java/org/spoofax/jsglr2/testset/TestSetInput.java
+++ b/org.spoofax.jsglr2.integration/src/main/java/org/spoofax/jsglr2/testset/TestSetInput.java
@@ -38,3 +38,5 @@
CON
DEL return s.hasNext() ? s.next() : "";
ADD // Replace all characters with codepoint value > 255 with a question mark to avoid parse failures,
ADD // assuming that they only appear in places where any character is allowed (strings, comments, ...)
ADD return s.hasNext() ? s.next().replaceAll("[^\\x00-\\xFF]", "?") : "";
CON }
|
<<<<<<< SEARCH
s.useDelimiter("\\A");
return s.hasNext() ? s.next() : "";
}
}
=======
s.useDelimiter("\\A");
// Replace all characters with codepoint value > 255 with a question mark to avoid parse failures,
// assuming that they only appear in places where any character is allowed (strings, comments, ...)
return s.hasNext() ? s.next().replaceAll("[^\\x00-\\xFF]", "?") : "";
}
}
>>>>>>> REPLACE
|
androidx/androidx
|
625bbf2c36dce028472f5dbb678ce6b17f019ffd
|
compose/r4a-runtime/src/com/google/r4a/R4a.kt
|
kotlin
|
apache-2.0
|
Add a few helpers to make the getting started experience feel a little more familiar
Change-Id: Icf6f0611fa33361a2620b0a6d847b2f651b391f7
|
package com.google.r4a
import android.view.ViewGroup
object R4a {
private class Root: Component() {
lateinit var composable: @Composable() () -> Unit
override fun compose() {
val cc = CompositionContext.current
cc.start(0)
composable()
cc.end()
}
}
fun composeInto(
container: ViewGroup,
parent: Ambient.Reference? = null,
composable: () -> Unit
) {
var root = CompositionContext.getRootComponent(container) as? Root
if (root == null) {
container.removeAllViews()
root = Root()
root.composable = composable
val cc = CompositionContext.create(container.context, container, root, parent)
cc.recomposeSync(root)
} else {
root.composable = composable
CompositionContext.recomposeSync(root)
}
}
}
inline fun ViewGroup.composeInto(noinline composable: @Composable() () -> Unit) = R4a.composeInto(this, null, composable)
|
package com.google.r4a
import android.app.Activity
import android.view.ViewGroup
import android.widget.LinearLayout
object R4a {
private class Root: Component() {
lateinit var composable: @Composable() () -> Unit
override fun compose() {
val cc = CompositionContext.current
cc.start(0)
composable()
cc.end()
}
}
fun composeInto(
container: ViewGroup,
parent: Ambient.Reference? = null,
composable: () -> Unit
) {
var root = CompositionContext.getRootComponent(container) as? Root
if (root == null) {
container.removeAllViews()
root = Root()
root.composable = composable
val cc = CompositionContext.create(container.context, container, root, parent)
cc.recomposeSync(root)
} else {
root.composable = composable
CompositionContext.recomposeSync(root)
}
}
}
inline fun ViewGroup.composeInto(noinline composable: @Composable() () -> Unit) = R4a.composeInto(this, null, composable)
inline fun Activity.composeInto(noinline composable: @Composable() () -> Unit) {
val root = LinearLayout(this)
root.composeInto(composable)
this.setContentView(root)
}
inline fun Activity.setContent(noinline composable: @Composable() () -> Unit) { this.composeInto(composable) }
inline fun Activity.setContentView(noinline composable: @Composable() () -> Unit) { this.composeInto(composable) }
| 12
| 0
| 2
|
add_only
|
--- a/compose/r4a-runtime/src/com/google/r4a/R4a.kt
+++ b/compose/r4a-runtime/src/com/google/r4a/R4a.kt
@@ -2,3 +2,5 @@
+import android.app.Activity
import android.view.ViewGroup
+import android.widget.LinearLayout
@@ -37 +39,11 @@
inline fun ViewGroup.composeInto(noinline composable: @Composable() () -> Unit) = R4a.composeInto(this, null, composable)
+
+
+inline fun Activity.composeInto(noinline composable: @Composable() () -> Unit) {
+ val root = LinearLayout(this)
+ root.composeInto(composable)
+ this.setContentView(root)
+}
+
+inline fun Activity.setContent(noinline composable: @Composable() () -> Unit) { this.composeInto(composable) }
+inline fun Activity.setContentView(noinline composable: @Composable() () -> Unit) { this.composeInto(composable) }
|
--- a/compose/r4a-runtime/src/com/google/r4a/R4a.kt
+++ b/compose/r4a-runtime/src/com/google/r4a/R4a.kt
@@ ... @@
+import android.app.Activity
import android.view.ViewGroup
+import android.widget.LinearLayout
@@ ... @@
inline fun ViewGroup.composeInto(noinline composable: @Composable() () -> Unit) = R4a.composeInto(this, null, composable)
+
+
+inline fun Activity.composeInto(noinline composable: @Composable() () -> Unit) {
+ val root = LinearLayout(this)
+ root.composeInto(composable)
+ this.setContentView(root)
+}
+
+inline fun Activity.setContent(noinline composable: @Composable() () -> Unit) { this.composeInto(composable) }
+inline fun Activity.setContentView(noinline composable: @Composable() () -> Unit) { this.composeInto(composable) }
|
--- a/compose/r4a-runtime/src/com/google/r4a/R4a.kt
+++ b/compose/r4a-runtime/src/com/google/r4a/R4a.kt
@@ -2,3 +2,5 @@
CON
ADD import android.app.Activity
CON import android.view.ViewGroup
ADD import android.widget.LinearLayout
CON
@@ -37 +39,11 @@
CON inline fun ViewGroup.composeInto(noinline composable: @Composable() () -> Unit) = R4a.composeInto(this, null, composable)
ADD
ADD
ADD inline fun Activity.composeInto(noinline composable: @Composable() () -> Unit) {
ADD val root = LinearLayout(this)
ADD root.composeInto(composable)
ADD this.setContentView(root)
ADD }
ADD
ADD inline fun Activity.setContent(noinline composable: @Composable() () -> Unit) { this.composeInto(composable) }
ADD inline fun Activity.setContentView(noinline composable: @Composable() () -> Unit) { this.composeInto(composable) }
|
<<<<<<< SEARCH
package com.google.r4a
import android.view.ViewGroup
object R4a {
=======
package com.google.r4a
import android.app.Activity
import android.view.ViewGroup
import android.widget.LinearLayout
object R4a {
>>>>>>> REPLACE
<<<<<<< SEARCH
}
inline fun ViewGroup.composeInto(noinline composable: @Composable() () -> Unit) = R4a.composeInto(this, null, composable)
=======
}
inline fun ViewGroup.composeInto(noinline composable: @Composable() () -> Unit) = R4a.composeInto(this, null, composable)
inline fun Activity.composeInto(noinline composable: @Composable() () -> Unit) {
val root = LinearLayout(this)
root.composeInto(composable)
this.setContentView(root)
}
inline fun Activity.setContent(noinline composable: @Composable() () -> Unit) { this.composeInto(composable) }
inline fun Activity.setContentView(noinline composable: @Composable() () -> Unit) { this.composeInto(composable) }
>>>>>>> REPLACE
|
ralscha/extdirectspring-demo
|
0bbfac0a4663d3804bb650d0bbca3849c025c896
|
src/main/java/ch/rasc/extdirectspring/demo/named/NamedService.java
|
java
|
apache-2.0
|
Add an example for a nonstrict named parameter method
|
/**
* Copyright 2010-2014 Ralph Schaer <[email protected]>
*
* 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 ch.rasc.extdirectspring.demo.named;
import java.util.List;
import org.springframework.stereotype.Service;
import ch.ralscha.extdirectspring.annotation.ExtDirectMethod;
import ch.ralscha.extdirectspring.annotation.ExtDirectMethodType;
@Service
public class NamedService {
@ExtDirectMethod(value = ExtDirectMethodType.SIMPLE_NAMED, group = "named")
public String showDetails(List<Business> bo, String firstName, String lastName,
int age) {
bo.forEach(System.out::println);
return String.format("Hi %s %s, you are %d years old.", firstName, lastName, age);
}
}
|
/**
* Copyright 2010-2014 Ralph Schaer <[email protected]>
*
* 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 ch.rasc.extdirectspring.demo.named;
import java.util.List;
import java.util.Map;
import org.springframework.stereotype.Service;
import ch.ralscha.extdirectspring.annotation.ExtDirectMethod;
import ch.ralscha.extdirectspring.annotation.ExtDirectMethodType;
@Service
public class NamedService {
@ExtDirectMethod(value = ExtDirectMethodType.SIMPLE_NAMED, group = "named")
public String showDetails(List<Business> bo, String firstName, String lastName,
int age) {
bo.forEach(System.out::println);
return String.format("Hi %s %s, you are %d years old.", firstName, lastName, age);
}
@ExtDirectMethod(value = ExtDirectMethodType.SIMPLE_NAMED, group = "named")
public boolean nonStrict(Map<String,Object> parameters) {
parameters.forEach((k,v)->System.out.println(k+"-->"+v));
return true;
}
}
| 7
| 0
| 2
|
add_only
|
--- a/src/main/java/ch/rasc/extdirectspring/demo/named/NamedService.java
+++ b/src/main/java/ch/rasc/extdirectspring/demo/named/NamedService.java
@@ -18,2 +18,3 @@
import java.util.List;
+import java.util.Map;
@@ -33,2 +34,8 @@
}
+
+ @ExtDirectMethod(value = ExtDirectMethodType.SIMPLE_NAMED, group = "named")
+ public boolean nonStrict(Map<String,Object> parameters) {
+ parameters.forEach((k,v)->System.out.println(k+"-->"+v));
+ return true;
+ }
}
|
--- a/src/main/java/ch/rasc/extdirectspring/demo/named/NamedService.java
+++ b/src/main/java/ch/rasc/extdirectspring/demo/named/NamedService.java
@@ ... @@
import java.util.List;
+import java.util.Map;
@@ ... @@
}
+
+ @ExtDirectMethod(value = ExtDirectMethodType.SIMPLE_NAMED, group = "named")
+ public boolean nonStrict(Map<String,Object> parameters) {
+ parameters.forEach((k,v)->System.out.println(k+"-->"+v));
+ return true;
+ }
}
|
--- a/src/main/java/ch/rasc/extdirectspring/demo/named/NamedService.java
+++ b/src/main/java/ch/rasc/extdirectspring/demo/named/NamedService.java
@@ -18,2 +18,3 @@
CON import java.util.List;
ADD import java.util.Map;
CON
@@ -33,2 +34,8 @@
CON }
ADD
ADD @ExtDirectMethod(value = ExtDirectMethodType.SIMPLE_NAMED, group = "named")
ADD public boolean nonStrict(Map<String,Object> parameters) {
ADD parameters.forEach((k,v)->System.out.println(k+"-->"+v));
ADD return true;
ADD }
CON }
|
<<<<<<< SEARCH
import java.util.List;
import org.springframework.stereotype.Service;
=======
import java.util.List;
import java.util.Map;
import org.springframework.stereotype.Service;
>>>>>>> REPLACE
<<<<<<< SEARCH
return String.format("Hi %s %s, you are %d years old.", firstName, lastName, age);
}
}
=======
return String.format("Hi %s %s, you are %d years old.", firstName, lastName, age);
}
@ExtDirectMethod(value = ExtDirectMethodType.SIMPLE_NAMED, group = "named")
public boolean nonStrict(Map<String,Object> parameters) {
parameters.forEach((k,v)->System.out.println(k+"-->"+v));
return true;
}
}
>>>>>>> REPLACE
|
mario-kr/imag
|
2ce4d334b4c1317a2eb03331f748d7fdf8ca5173
|
.imag-documentation/src/lib.rs
|
rust
|
lgpl-2.1
|
Add module-documentation for the documentation crate
|
#[cfg(test)]
mod tests {
#[test]
fn it_works() {
}
}
|
//! # imag
//!
//! This is the _developer_ documentation for the imag personal information management suite for the
//! commandline.
//!
//! For the user documentation, have a look
//! [at the 'doc' subtree in the repository](http://git.imag-pim.org/imag/tree/doc)
//! which can be compiled to HTML or PDF using [pandoc](pandoc.org) (and might be a bit outdated as
//! imag is not yet released for use).
//!
//! ## General
//!
//! _Some_ things from the user documentation might be helpful for developers as well, so make sure
//! to at least skim over it if you want to contribute to the imag source.
//!
//! Also make sure you had a look at
//! [the CONTRIBUTING](http://git.imag-pim.org/imag/tree/CONTRIBUTING.md)
//! file and [the developers certificate of origin](http://developercertificate.org/), which we also
//! have in the `CONTRIBUTING` file, by the way.
//!
//! ## Contributing
//!
//! All things relevant for contributing are descripbed in
//! [the CONTRIBUTING file](http://git.imag-pim.org/imag/tree/CONTRIBUTING.md),
//! but here are some additional notes:
//!
//! * We have a `editorconfig` file in the repository. Would be nice if you'd
//! [use it](http://editorconfig.org/)
//! * We have [default.nix](http://git.imag-pim.org/imag/tree/default.nix) file, which can be used
//! to install dependencies in `nix-shell` environments. If you have a installation of the nix
//! package manager, feel free to use this opportunity to be _pure_.
//! * If you want to play around with imag, use the
//! [imagrc.toml](http://git.imag-pim.org/imag/tree/imagrc.toml)
//! file from the repository, we try to keep it up to date.
//! * You can use [the Makefile](http://git.imag-pim.org/imag/tree/Makefile) to build things (if you
//! have all dependencies and cargo/rustc installed, of course).
//! * It is a real advantage to use `cargo-check` when developing things - it speeds you up, beleive
//! me!
//!
| 40
| 6
| 1
|
mixed
|
--- a/.imag-documentation/src/lib.rs
+++ b/.imag-documentation/src/lib.rs
@@ -1,6 +1,40 @@
-#[cfg(test)]
-mod tests {
- #[test]
- fn it_works() {
- }
-}
+//! # imag
+//!
+//! This is the _developer_ documentation for the imag personal information management suite for the
+//! commandline.
+//!
+//! For the user documentation, have a look
+//! [at the 'doc' subtree in the repository](http://git.imag-pim.org/imag/tree/doc)
+//! which can be compiled to HTML or PDF using [pandoc](pandoc.org) (and might be a bit outdated as
+//! imag is not yet released for use).
+//!
+//! ## General
+//!
+//! _Some_ things from the user documentation might be helpful for developers as well, so make sure
+//! to at least skim over it if you want to contribute to the imag source.
+//!
+//! Also make sure you had a look at
+//! [the CONTRIBUTING](http://git.imag-pim.org/imag/tree/CONTRIBUTING.md)
+//! file and [the developers certificate of origin](http://developercertificate.org/), which we also
+//! have in the `CONTRIBUTING` file, by the way.
+//!
+//! ## Contributing
+//!
+//! All things relevant for contributing are descripbed in
+//! [the CONTRIBUTING file](http://git.imag-pim.org/imag/tree/CONTRIBUTING.md),
+//! but here are some additional notes:
+//!
+//! * We have a `editorconfig` file in the repository. Would be nice if you'd
+//! [use it](http://editorconfig.org/)
+//! * We have [default.nix](http://git.imag-pim.org/imag/tree/default.nix) file, which can be used
+//! to install dependencies in `nix-shell` environments. If you have a installation of the nix
+//! package manager, feel free to use this opportunity to be _pure_.
+//! * If you want to play around with imag, use the
+//! [imagrc.toml](http://git.imag-pim.org/imag/tree/imagrc.toml)
+//! file from the repository, we try to keep it up to date.
+//! * You can use [the Makefile](http://git.imag-pim.org/imag/tree/Makefile) to build things (if you
+//! have all dependencies and cargo/rustc installed, of course).
+//! * It is a real advantage to use `cargo-check` when developing things - it speeds you up, beleive
+//! me!
+//!
+
|
--- a/.imag-documentation/src/lib.rs
+++ b/.imag-documentation/src/lib.rs
@@ ... @@
-#[cfg(test)]
-mod tests {
- #[test]
- fn it_works() {
- }
-}
+//! # imag
+//!
+//! This is the _developer_ documentation for the imag personal information management suite for the
+//! commandline.
+//!
+//! For the user documentation, have a look
+//! [at the 'doc' subtree in the repository](http://git.imag-pim.org/imag/tree/doc)
+//! which can be compiled to HTML or PDF using [pandoc](pandoc.org) (and might be a bit outdated as
+//! imag is not yet released for use).
+//!
+//! ## General
+//!
+//! _Some_ things from the user documentation might be helpful for developers as well, so make sure
+//! to at least skim over it if you want to contribute to the imag source.
+//!
+//! Also make sure you had a look at
+//! [the CONTRIBUTING](http://git.imag-pim.org/imag/tree/CONTRIBUTING.md)
+//! file and [the developers certificate of origin](http://developercertificate.org/), which we also
+//! have in the `CONTRIBUTING` file, by the way.
+//!
+//! ## Contributing
+//!
+//! All things relevant for contributing are descripbed in
+//! [the CONTRIBUTING file](http://git.imag-pim.org/imag/tree/CONTRIBUTING.md),
+//! but here are some additional notes:
+//!
+//! * We have a `editorconfig` file in the repository. Would be nice if you'd
+//! [use it](http://editorconfig.org/)
+//! * We have [default.nix](http://git.imag-pim.org/imag/tree/default.nix) file, which can be used
+//! to install dependencies in `nix-shell` environments. If you have a installation of the nix
+//! package manager, feel free to use this opportunity to be _pure_.
+//! * If you want to play around with imag, use the
+//! [imagrc.toml](http://git.imag-pim.org/imag/tree/imagrc.toml)
+//! file from the repository, we try to keep it up to date.
+//! * You can use [the Makefile](http://git.imag-pim.org/imag/tree/Makefile) to build things (if you
+//! have all dependencies and cargo/rustc installed, of course).
+//! * It is a real advantage to use `cargo-check` when developing things - it speeds you up, beleive
+//! me!
+//!
+
|
--- a/.imag-documentation/src/lib.rs
+++ b/.imag-documentation/src/lib.rs
@@ -1,6 +1,40 @@
DEL #[cfg(test)]
DEL mod tests {
DEL #[test]
DEL fn it_works() {
DEL }
DEL }
ADD //! # imag
ADD //!
ADD //! This is the _developer_ documentation for the imag personal information management suite for the
ADD //! commandline.
ADD //!
ADD //! For the user documentation, have a look
ADD //! [at the 'doc' subtree in the repository](http://git.imag-pim.org/imag/tree/doc)
ADD //! which can be compiled to HTML or PDF using [pandoc](pandoc.org) (and might be a bit outdated as
ADD //! imag is not yet released for use).
ADD //!
ADD //! ## General
ADD //!
ADD //! _Some_ things from the user documentation might be helpful for developers as well, so make sure
ADD //! to at least skim over it if you want to contribute to the imag source.
ADD //!
ADD //! Also make sure you had a look at
ADD //! [the CONTRIBUTING](http://git.imag-pim.org/imag/tree/CONTRIBUTING.md)
ADD //! file and [the developers certificate of origin](http://developercertificate.org/), which we also
ADD //! have in the `CONTRIBUTING` file, by the way.
ADD //!
ADD //! ## Contributing
ADD //!
ADD //! All things relevant for contributing are descripbed in
ADD //! [the CONTRIBUTING file](http://git.imag-pim.org/imag/tree/CONTRIBUTING.md),
ADD //! but here are some additional notes:
ADD //!
ADD //! * We have a `editorconfig` file in the repository. Would be nice if you'd
ADD //! [use it](http://editorconfig.org/)
ADD //! * We have [default.nix](http://git.imag-pim.org/imag/tree/default.nix) file, which can be used
ADD //! to install dependencies in `nix-shell` environments. If you have a installation of the nix
ADD //! package manager, feel free to use this opportunity to be _pure_.
ADD //! * If you want to play around with imag, use the
ADD //! [imagrc.toml](http://git.imag-pim.org/imag/tree/imagrc.toml)
ADD //! file from the repository, we try to keep it up to date.
ADD //! * You can use [the Makefile](http://git.imag-pim.org/imag/tree/Makefile) to build things (if you
ADD //! have all dependencies and cargo/rustc installed, of course).
ADD //! * It is a real advantage to use `cargo-check` when developing things - it speeds you up, beleive
ADD //! me!
ADD //!
ADD
|
<<<<<<< SEARCH
#[cfg(test)]
mod tests {
#[test]
fn it_works() {
}
}
=======
//! # imag
//!
//! This is the _developer_ documentation for the imag personal information management suite for the
//! commandline.
//!
//! For the user documentation, have a look
//! [at the 'doc' subtree in the repository](http://git.imag-pim.org/imag/tree/doc)
//! which can be compiled to HTML or PDF using [pandoc](pandoc.org) (and might be a bit outdated as
//! imag is not yet released for use).
//!
//! ## General
//!
//! _Some_ things from the user documentation might be helpful for developers as well, so make sure
//! to at least skim over it if you want to contribute to the imag source.
//!
//! Also make sure you had a look at
//! [the CONTRIBUTING](http://git.imag-pim.org/imag/tree/CONTRIBUTING.md)
//! file and [the developers certificate of origin](http://developercertificate.org/), which we also
//! have in the `CONTRIBUTING` file, by the way.
//!
//! ## Contributing
//!
//! All things relevant for contributing are descripbed in
//! [the CONTRIBUTING file](http://git.imag-pim.org/imag/tree/CONTRIBUTING.md),
//! but here are some additional notes:
//!
//! * We have a `editorconfig` file in the repository. Would be nice if you'd
//! [use it](http://editorconfig.org/)
//! * We have [default.nix](http://git.imag-pim.org/imag/tree/default.nix) file, which can be used
//! to install dependencies in `nix-shell` environments. If you have a installation of the nix
//! package manager, feel free to use this opportunity to be _pure_.
//! * If you want to play around with imag, use the
//! [imagrc.toml](http://git.imag-pim.org/imag/tree/imagrc.toml)
//! file from the repository, we try to keep it up to date.
//! * You can use [the Makefile](http://git.imag-pim.org/imag/tree/Makefile) to build things (if you
//! have all dependencies and cargo/rustc installed, of course).
//! * It is a real advantage to use `cargo-check` when developing things - it speeds you up, beleive
//! me!
//!
>>>>>>> REPLACE
|
ruslansennov/playn
|
9325258dc39f31f864675c20a7cbc575e2451485
|
core/src/forplay/core/Platform.java
|
java
|
apache-2.0
|
Remove useless comment about returning a null mouse. Access mouse through ForPlay.mouse().
|
/**
* Copyright 2010 The ForPlay Authors
*
* 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 forplay.core;
/**
* Generic platform interface. New platforms are defined as implementations of this interface.
*/
public interface Platform {
Audio audio();
Graphics graphics();
AssetManager assetManager();
Json json();
Keyboard keyboard();
Log log();
Net net();
Pointer pointer();
/**
* Return the mouse if it is supported, or null otherwise.
*
* @return the mouse if it is supported, or null otherwise.
*/
Mouse mouse();
Storage storage();
Analytics analytics();
float random();
void run(Game game);
double time();
RegularExpression regularExpression();
void openURL(String url);
}
|
/**
* Copyright 2010 The ForPlay Authors
*
* 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 forplay.core;
/**
* Generic platform interface. New platforms are defined as implementations of this interface.
*/
public interface Platform {
Audio audio();
Graphics graphics();
AssetManager assetManager();
Json json();
Keyboard keyboard();
Log log();
Net net();
Pointer pointer();
Mouse mouse();
Storage storage();
Analytics analytics();
float random();
void run(Game game);
double time();
RegularExpression regularExpression();
void openURL(String url);
}
| 0
| 5
| 1
|
del_only
|
--- a/core/src/forplay/core/Platform.java
+++ b/core/src/forplay/core/Platform.java
@@ -38,7 +38,2 @@
- /**
- * Return the mouse if it is supported, or null otherwise.
- *
- * @return the mouse if it is supported, or null otherwise.
- */
Mouse mouse();
|
--- a/core/src/forplay/core/Platform.java
+++ b/core/src/forplay/core/Platform.java
@@ ... @@
- /**
- * Return the mouse if it is supported, or null otherwise.
- *
- * @return the mouse if it is supported, or null otherwise.
- */
Mouse mouse();
|
--- a/core/src/forplay/core/Platform.java
+++ b/core/src/forplay/core/Platform.java
@@ -38,7 +38,2 @@
CON
DEL /**
DEL * Return the mouse if it is supported, or null otherwise.
DEL *
DEL * @return the mouse if it is supported, or null otherwise.
DEL */
CON Mouse mouse();
|
<<<<<<< SEARCH
Pointer pointer();
/**
* Return the mouse if it is supported, or null otherwise.
*
* @return the mouse if it is supported, or null otherwise.
*/
Mouse mouse();
=======
Pointer pointer();
Mouse mouse();
>>>>>>> REPLACE
|
dinfuehr/rust
|
560def15113d3d54b262d2b9365b6952e5e5ee3a
|
src/test/run-pass/deriving-global.rs
|
rust
|
apache-2.0
|
test: Fix a pretty printing test
The pretty printer handles inlines comments quite badly
|
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
extern crate serialize; // {En,De}codable
extern crate rand; // Rand
mod submod {
// if any of these are implemented without global calls for any
// function calls, then being in a submodule will (correctly)
// cause errors about unrecognised module `std` (or `extra`)
#[deriving(Eq, Ord, TotalEq, TotalOrd,
Hash,
Clone,
Show, Rand,
Encodable, Decodable)]
enum A { A1(uint), A2(int) }
#[deriving(Eq, Ord, TotalEq, TotalOrd,
Hash,
Clone,
Show, Rand,
Encodable, Decodable)]
struct B { x: uint, y: int }
#[deriving(Eq, Ord, TotalEq, TotalOrd,
Hash,
Clone,
Show, Rand,
Encodable, Decodable)]
struct C(uint, int);
}
pub fn main() {}
|
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
extern crate serialize;
extern crate rand;
mod submod {
// if any of these are implemented without global calls for any
// function calls, then being in a submodule will (correctly)
// cause errors about unrecognised module `std` (or `extra`)
#[deriving(Eq, Ord, TotalEq, TotalOrd,
Hash,
Clone,
Show, Rand,
Encodable, Decodable)]
enum A { A1(uint), A2(int) }
#[deriving(Eq, Ord, TotalEq, TotalOrd,
Hash,
Clone,
Show, Rand,
Encodable, Decodable)]
struct B { x: uint, y: int }
#[deriving(Eq, Ord, TotalEq, TotalOrd,
Hash,
Clone,
Show, Rand,
Encodable, Decodable)]
struct C(uint, int);
}
pub fn main() {}
| 2
| 2
| 1
|
mixed
|
--- a/src/test/run-pass/deriving-global.rs
+++ b/src/test/run-pass/deriving-global.rs
@@ -10,4 +10,4 @@
-extern crate serialize; // {En,De}codable
-extern crate rand; // Rand
+extern crate serialize;
+extern crate rand;
|
--- a/src/test/run-pass/deriving-global.rs
+++ b/src/test/run-pass/deriving-global.rs
@@ ... @@
-extern crate serialize; // {En,De}codable
-extern crate rand; // Rand
+extern crate serialize;
+extern crate rand;
|
--- a/src/test/run-pass/deriving-global.rs
+++ b/src/test/run-pass/deriving-global.rs
@@ -10,4 +10,4 @@
CON
DEL extern crate serialize; // {En,De}codable
DEL extern crate rand; // Rand
ADD extern crate serialize;
ADD extern crate rand;
CON
|
<<<<<<< SEARCH
// except according to those terms.
extern crate serialize; // {En,De}codable
extern crate rand; // Rand
mod submod {
=======
// except according to those terms.
extern crate serialize;
extern crate rand;
mod submod {
>>>>>>> REPLACE
|
androidx/androidx
|
09b335469d39b6bf0bf8afaf2c2b21ffb1e9c0ed
|
ui/ui-tooling/src/main/java/androidx/ui/tooling/preview/LayoutlibFontResourceLoader.kt
|
kotlin
|
apache-2.0
|
Remove RestrictTo from LayoutLib FontLoader
Test: N/A
Bug: 141371566
Change-Id: I6b4c453f05bab87af9462c0e67f6c35784275c82
|
/*
* Copyright 2019 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 androidx.ui.tooling.preview
import android.content.Context
import android.graphics.Typeface
import android.os.Build
import androidx.annotation.RequiresApi
import androidx.annotation.RestrictTo
import androidx.ui.text.font.Font
/**
* Layoutlib implementation for [Font.ResourceLoader]
*
* @hide
*/
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
internal class LayoutlibFontResourceLoader(private val context: Context) : Font.ResourceLoader {
@RequiresApi(Build.VERSION_CODES.O)
override fun load(font: Font): Typeface {
val resId = context.resources.getIdentifier(
font.name.substringBefore("."),
"font",
context.packageName
)
return context.resources.getFont(resId)
}
}
|
/*
* Copyright 2019 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 androidx.ui.tooling.preview
import android.content.Context
import android.graphics.Typeface
import android.os.Build
import androidx.annotation.RequiresApi
import androidx.ui.text.font.Font
/**
* Layoutlib implementation for [Font.ResourceLoader]
*/
internal class LayoutlibFontResourceLoader(private val context: Context) : Font.ResourceLoader {
@RequiresApi(Build.VERSION_CODES.O)
override fun load(font: Font): Typeface {
val resId = context.resources.getIdentifier(
font.name.substringBefore("."),
"font",
context.packageName
)
return context.resources.getFont(resId)
}
}
| 0
| 4
| 2
|
del_only
|
--- a/ui/ui-tooling/src/main/java/androidx/ui/tooling/preview/LayoutlibFontResourceLoader.kt
+++ b/ui/ui-tooling/src/main/java/androidx/ui/tooling/preview/LayoutlibFontResourceLoader.kt
@@ -22,3 +22,2 @@
import androidx.annotation.RequiresApi
-import androidx.annotation.RestrictTo
import androidx.ui.text.font.Font
@@ -27,6 +26,3 @@
* Layoutlib implementation for [Font.ResourceLoader]
- *
- * @hide
*/
-@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
internal class LayoutlibFontResourceLoader(private val context: Context) : Font.ResourceLoader {
|
--- a/ui/ui-tooling/src/main/java/androidx/ui/tooling/preview/LayoutlibFontResourceLoader.kt
+++ b/ui/ui-tooling/src/main/java/androidx/ui/tooling/preview/LayoutlibFontResourceLoader.kt
@@ ... @@
import androidx.annotation.RequiresApi
-import androidx.annotation.RestrictTo
import androidx.ui.text.font.Font
@@ ... @@
* Layoutlib implementation for [Font.ResourceLoader]
- *
- * @hide
*/
-@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
internal class LayoutlibFontResourceLoader(private val context: Context) : Font.ResourceLoader {
|
--- a/ui/ui-tooling/src/main/java/androidx/ui/tooling/preview/LayoutlibFontResourceLoader.kt
+++ b/ui/ui-tooling/src/main/java/androidx/ui/tooling/preview/LayoutlibFontResourceLoader.kt
@@ -22,3 +22,2 @@
CON import androidx.annotation.RequiresApi
DEL import androidx.annotation.RestrictTo
CON import androidx.ui.text.font.Font
@@ -27,6 +26,3 @@
CON * Layoutlib implementation for [Font.ResourceLoader]
DEL *
DEL * @hide
CON */
DEL @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
CON internal class LayoutlibFontResourceLoader(private val context: Context) : Font.ResourceLoader {
|
<<<<<<< SEARCH
import android.os.Build
import androidx.annotation.RequiresApi
import androidx.annotation.RestrictTo
import androidx.ui.text.font.Font
/**
* Layoutlib implementation for [Font.ResourceLoader]
*
* @hide
*/
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
internal class LayoutlibFontResourceLoader(private val context: Context) : Font.ResourceLoader {
@RequiresApi(Build.VERSION_CODES.O)
=======
import android.os.Build
import androidx.annotation.RequiresApi
import androidx.ui.text.font.Font
/**
* Layoutlib implementation for [Font.ResourceLoader]
*/
internal class LayoutlibFontResourceLoader(private val context: Context) : Font.ResourceLoader {
@RequiresApi(Build.VERSION_CODES.O)
>>>>>>> REPLACE
|
austencm/youtube-auto-like
|
1184c2dd7044ddc552c84a0f644efbdb57c45bb5
|
src/js/content.js
|
javascript
|
mit
|
Fix log not saving on pause
|
import Liker from './content/liker';
import OptionManager from './utils/option-manager';
import Debug from './content/debug';
const debug = new Debug();
(async function () {
try {
debug.log('navigated:', window.location.href);
if (process.env.NODE_ENV === 'development') {
['yt-navigate', 'yt-navigate-finish', 'yt-page-data-updated'].forEach((eventType) => {
const appRoot = document.querySelector('ytd-app');
if (appRoot) {
appRoot.addEventListener(eventType, (e) => {
debug.log('event:', e.type);
if (eventType === 'yt-navigate-finish') {
debug.log('navigated:', window.location.href);
}
});
}
});
}
// Create an OptionManager
const defaults = {
like_what: 'subscribed',
like_when: 'instantly',
like_when_minutes: '2',
like_when_percent: '50',
disabled: false,
};
const optionManager = new OptionManager(defaults);
// Fetch our options then fire things up
debug.log('loading options...');
const options = await optionManager.get();
debug.log('...options loaded', `(${JSON.stringify(options, null, 2)})`);
const liker = new Liker({ options, log: debug.log });
liker.onStop = debug.save;
} catch (err) {
debug.log(err);
} finally {
debug.save();
}
})();
|
import Liker from './content/liker';
import OptionManager from './utils/option-manager';
import Debug from './content/debug';
const debug = new Debug();
(async function () {
try {
debug.log('navigated:', window.location.href);
if (process.env.NODE_ENV === 'development') {
['yt-navigate', 'yt-navigate-finish', 'yt-page-data-updated'].forEach((eventType) => {
const appRoot = document.querySelector('ytd-app');
if (appRoot) {
appRoot.addEventListener(eventType, (e) => {
debug.log('event:', e.type);
if (eventType === 'yt-navigate-finish') {
debug.log('navigated:', window.location.href);
}
});
}
});
}
// Create an OptionManager
const defaults = {
like_what: 'subscribed',
like_when: 'instantly',
like_when_minutes: '2',
like_when_percent: '50',
disabled: false,
};
const optionManager = new OptionManager(defaults);
// Fetch our options then fire things up
debug.log('loading options...');
const options = await optionManager.get();
debug.log('...options loaded', `(${JSON.stringify(options, null, 2)})`);
const liker = new Liker({ options, log: debug.log });
liker.onPause = debug.save;
} catch (err) {
debug.log(err);
} finally {
debug.save();
}
})();
| 1
| 1
| 1
|
mixed
|
--- a/src/js/content.js
+++ b/src/js/content.js
@@ -44,3 +44,3 @@
const liker = new Liker({ options, log: debug.log });
- liker.onStop = debug.save;
+ liker.onPause = debug.save;
} catch (err) {
|
--- a/src/js/content.js
+++ b/src/js/content.js
@@ ... @@
const liker = new Liker({ options, log: debug.log });
- liker.onStop = debug.save;
+ liker.onPause = debug.save;
} catch (err) {
|
--- a/src/js/content.js
+++ b/src/js/content.js
@@ -44,3 +44,3 @@
CON const liker = new Liker({ options, log: debug.log });
DEL liker.onStop = debug.save;
ADD liker.onPause = debug.save;
CON } catch (err) {
|
<<<<<<< SEARCH
const liker = new Liker({ options, log: debug.log });
liker.onStop = debug.save;
} catch (err) {
debug.log(err);
=======
const liker = new Liker({ options, log: debug.log });
liker.onPause = debug.save;
} catch (err) {
debug.log(err);
>>>>>>> REPLACE
|
RocketChat/Rocket.Chat.Android
|
8fecd4e9006fb0e877eb43b03332bcea69ea31ef
|
app/src/main/java/chat/rocket/android/util/Extensions.kt
|
kotlin
|
mit
|
Add extensions for CharSequence.isEmpty and TextView.content that accepts CharSequence
|
package chat.rocket.android.util
import android.support.annotation.LayoutRes
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
fun String.ifEmpty(value: String): String {
if (isEmpty()) {
return value
}
return this
}
fun View.setVisible(visible: Boolean) {
visibility = if (visible) {
View.VISIBLE
} else {
View.GONE
}
}
fun ViewGroup.inflate(@LayoutRes resource: Int): View {
return LayoutInflater.from(context).inflate(resource, this, false)
}
var TextView.textContent: String
get() = text.toString()
set(value) {
text = value
}
var TextView.hintContent: String
get() = hint.toString()
set(value) {
hint = value
}
|
package chat.rocket.android.util
import android.support.annotation.LayoutRes
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import ru.noties.markwon.Markwon
fun String.ifEmpty(value: String): String {
if (isEmpty()) {
return value
}
return this
}
fun CharSequence.ifEmpty(value: String): CharSequence {
if (isEmpty()) {
return value
}
return this
}
fun View.setVisible(visible: Boolean) {
visibility = if (visible) {
View.VISIBLE
} else {
View.GONE
}
}
fun ViewGroup.inflate(@LayoutRes resource: Int): View {
return LayoutInflater.from(context).inflate(resource, this, false)
}
var TextView.textContent: String
get() = text.toString()
set(value) {
text = value
}
var TextView.content: CharSequence
get() = text
set(value) {
Markwon.unscheduleDrawables(this)
Markwon.unscheduleTableRows(this)
text = value
Markwon.scheduleDrawables(this)
Markwon.scheduleTableRows(this)
}
var TextView.hintContent: String
get() = hint.toString()
set(value) {
hint = value
}
| 18
| 0
| 2
|
add_only
|
--- a/app/src/main/java/chat/rocket/android/util/Extensions.kt
+++ b/app/src/main/java/chat/rocket/android/util/Extensions.kt
@@ -7,4 +7,12 @@
import android.widget.TextView
+import ru.noties.markwon.Markwon
fun String.ifEmpty(value: String): String {
+ if (isEmpty()) {
+ return value
+ }
+ return this
+}
+
+fun CharSequence.ifEmpty(value: String): CharSequence {
if (isEmpty()) {
@@ -33,2 +41,12 @@
+var TextView.content: CharSequence
+ get() = text
+ set(value) {
+ Markwon.unscheduleDrawables(this)
+ Markwon.unscheduleTableRows(this)
+ text = value
+ Markwon.scheduleDrawables(this)
+ Markwon.scheduleTableRows(this)
+ }
+
var TextView.hintContent: String
|
--- a/app/src/main/java/chat/rocket/android/util/Extensions.kt
+++ b/app/src/main/java/chat/rocket/android/util/Extensions.kt
@@ ... @@
import android.widget.TextView
+import ru.noties.markwon.Markwon
fun String.ifEmpty(value: String): String {
+ if (isEmpty()) {
+ return value
+ }
+ return this
+}
+
+fun CharSequence.ifEmpty(value: String): CharSequence {
if (isEmpty()) {
@@ ... @@
+var TextView.content: CharSequence
+ get() = text
+ set(value) {
+ Markwon.unscheduleDrawables(this)
+ Markwon.unscheduleTableRows(this)
+ text = value
+ Markwon.scheduleDrawables(this)
+ Markwon.scheduleTableRows(this)
+ }
+
var TextView.hintContent: String
|
--- a/app/src/main/java/chat/rocket/android/util/Extensions.kt
+++ b/app/src/main/java/chat/rocket/android/util/Extensions.kt
@@ -7,4 +7,12 @@
CON import android.widget.TextView
ADD import ru.noties.markwon.Markwon
CON
CON fun String.ifEmpty(value: String): String {
ADD if (isEmpty()) {
ADD return value
ADD }
ADD return this
ADD }
ADD
ADD fun CharSequence.ifEmpty(value: String): CharSequence {
CON if (isEmpty()) {
@@ -33,2 +41,12 @@
CON
ADD var TextView.content: CharSequence
ADD get() = text
ADD set(value) {
ADD Markwon.unscheduleDrawables(this)
ADD Markwon.unscheduleTableRows(this)
ADD text = value
ADD Markwon.scheduleDrawables(this)
ADD Markwon.scheduleTableRows(this)
ADD }
ADD
CON var TextView.hintContent: String
|
<<<<<<< SEARCH
import android.view.ViewGroup
import android.widget.TextView
fun String.ifEmpty(value: String): String {
if (isEmpty()) {
return value
=======
import android.view.ViewGroup
import android.widget.TextView
import ru.noties.markwon.Markwon
fun String.ifEmpty(value: String): String {
if (isEmpty()) {
return value
}
return this
}
fun CharSequence.ifEmpty(value: String): CharSequence {
if (isEmpty()) {
return value
>>>>>>> REPLACE
<<<<<<< SEARCH
}
var TextView.hintContent: String
get() = hint.toString()
=======
}
var TextView.content: CharSequence
get() = text
set(value) {
Markwon.unscheduleDrawables(this)
Markwon.unscheduleTableRows(this)
text = value
Markwon.scheduleDrawables(this)
Markwon.scheduleTableRows(this)
}
var TextView.hintContent: String
get() = hint.toString()
>>>>>>> REPLACE
|
shiraji/permissions-dispatcher-plugin
|
e83322c5a16db34f1d7bcb8eb6fd1a69f39ccede
|
src/main/kotlin/com/github/shiraji/permissionsdispatcherplugin/actions/GeneratePMCodeAction.kt
|
kotlin
|
apache-2.0
|
Add update method that enable only Activity or Fragment
|
package com.github.shiraji.permissionsdispatcherplugin.actions
import com.github.shiraji.permissionsdispatcherplugin.models.GeneratePMCodeModel
import com.intellij.codeInsight.CodeInsightActionHandler
import com.intellij.codeInsight.actions.CodeInsightAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiJavaFile
class GeneratePMCodeAction : CodeInsightAction() {
override fun getHandler(): CodeInsightActionHandler {
return Handler()
}
}
class Handler : CodeInsightActionHandler {
override fun startInWriteAction() = false
override fun invoke(project: Project, editor: Editor, file: PsiFile) {
if(file !is PsiJavaFile) return
val model = GeneratePMCodeModel()
if (model.isActivity(file.classes[0], project)) {
System.out.println("Activity!")
}
if (model.isSupportFragment(file.classes[0], project)) {
System.out.println("SupportFragment!")
}
file.javaClass.annotations.forEach {
System.out.println(it)
}
// editor.document.replaceString(1,1, "FOOO!!!")
}
}
|
package com.github.shiraji.permissionsdispatcherplugin.actions
import com.github.shiraji.permissionsdispatcherplugin.models.GeneratePMCodeModel
import com.intellij.codeInsight.CodeInsightActionHandler
import com.intellij.codeInsight.actions.CodeInsightAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiJavaFile
class GeneratePMCodeAction : CodeInsightAction() {
override fun getHandler(): CodeInsightActionHandler {
return Handler()
}
override fun update(e: AnActionEvent?) {
e ?: return
super.update(e)
val file = e.getData(CommonDataKeys.PSI_FILE) ?: return
if (file !is PsiJavaFile) return
val project = e.getData(CommonDataKeys.PROJECT) ?: return
val model = GeneratePMCodeModel(project)
e.presentation.isEnabledAndVisible = model.isActivity(file.classes[0])
|| model.isSupportFragment(file.classes[0])
|| model.isFragment(file.classes[0])
}
}
class Handler : CodeInsightActionHandler {
override fun startInWriteAction() = false
override fun invoke(project: Project, editor: Editor, file: PsiFile) {
if(file !is PsiJavaFile) return
val model = GeneratePMCodeModel()
if (model.isActivity(file.classes[0], project)) {
System.out.println("Activity!")
}
if (model.isSupportFragment(file.classes[0], project)) {
System.out.println("SupportFragment!")
}
file.javaClass.annotations.forEach {
System.out.println(it)
}
// editor.document.replaceString(1,1, "FOOO!!!")
}
}
| 17
| 0
| 2
|
add_only
|
--- a/src/main/kotlin/com/github/shiraji/permissionsdispatcherplugin/actions/GeneratePMCodeAction.kt
+++ b/src/main/kotlin/com/github/shiraji/permissionsdispatcherplugin/actions/GeneratePMCodeAction.kt
@@ -5,2 +5,4 @@
import com.intellij.codeInsight.actions.CodeInsightAction
+import com.intellij.openapi.actionSystem.AnActionEvent
+import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.editor.Editor
@@ -13,2 +15,17 @@
return Handler()
+ }
+
+ override fun update(e: AnActionEvent?) {
+ e ?: return
+ super.update(e)
+
+ val file = e.getData(CommonDataKeys.PSI_FILE) ?: return
+ if (file !is PsiJavaFile) return
+
+ val project = e.getData(CommonDataKeys.PROJECT) ?: return
+ val model = GeneratePMCodeModel(project)
+
+ e.presentation.isEnabledAndVisible = model.isActivity(file.classes[0])
+ || model.isSupportFragment(file.classes[0])
+ || model.isFragment(file.classes[0])
}
|
--- a/src/main/kotlin/com/github/shiraji/permissionsdispatcherplugin/actions/GeneratePMCodeAction.kt
+++ b/src/main/kotlin/com/github/shiraji/permissionsdispatcherplugin/actions/GeneratePMCodeAction.kt
@@ ... @@
import com.intellij.codeInsight.actions.CodeInsightAction
+import com.intellij.openapi.actionSystem.AnActionEvent
+import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.editor.Editor
@@ ... @@
return Handler()
+ }
+
+ override fun update(e: AnActionEvent?) {
+ e ?: return
+ super.update(e)
+
+ val file = e.getData(CommonDataKeys.PSI_FILE) ?: return
+ if (file !is PsiJavaFile) return
+
+ val project = e.getData(CommonDataKeys.PROJECT) ?: return
+ val model = GeneratePMCodeModel(project)
+
+ e.presentation.isEnabledAndVisible = model.isActivity(file.classes[0])
+ || model.isSupportFragment(file.classes[0])
+ || model.isFragment(file.classes[0])
}
|
--- a/src/main/kotlin/com/github/shiraji/permissionsdispatcherplugin/actions/GeneratePMCodeAction.kt
+++ b/src/main/kotlin/com/github/shiraji/permissionsdispatcherplugin/actions/GeneratePMCodeAction.kt
@@ -5,2 +5,4 @@
CON import com.intellij.codeInsight.actions.CodeInsightAction
ADD import com.intellij.openapi.actionSystem.AnActionEvent
ADD import com.intellij.openapi.actionSystem.CommonDataKeys
CON import com.intellij.openapi.editor.Editor
@@ -13,2 +15,17 @@
CON return Handler()
ADD }
ADD
ADD override fun update(e: AnActionEvent?) {
ADD e ?: return
ADD super.update(e)
ADD
ADD val file = e.getData(CommonDataKeys.PSI_FILE) ?: return
ADD if (file !is PsiJavaFile) return
ADD
ADD val project = e.getData(CommonDataKeys.PROJECT) ?: return
ADD val model = GeneratePMCodeModel(project)
ADD
ADD e.presentation.isEnabledAndVisible = model.isActivity(file.classes[0])
ADD || model.isSupportFragment(file.classes[0])
ADD || model.isFragment(file.classes[0])
CON }
|
<<<<<<< SEARCH
import com.intellij.codeInsight.CodeInsightActionHandler
import com.intellij.codeInsight.actions.CodeInsightAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
=======
import com.intellij.codeInsight.CodeInsightActionHandler
import com.intellij.codeInsight.actions.CodeInsightAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
>>>>>>> REPLACE
<<<<<<< SEARCH
override fun getHandler(): CodeInsightActionHandler {
return Handler()
}
}
=======
override fun getHandler(): CodeInsightActionHandler {
return Handler()
}
override fun update(e: AnActionEvent?) {
e ?: return
super.update(e)
val file = e.getData(CommonDataKeys.PSI_FILE) ?: return
if (file !is PsiJavaFile) return
val project = e.getData(CommonDataKeys.PROJECT) ?: return
val model = GeneratePMCodeModel(project)
e.presentation.isEnabledAndVisible = model.isActivity(file.classes[0])
|| model.isSupportFragment(file.classes[0])
|| model.isFragment(file.classes[0])
}
}
>>>>>>> REPLACE
|
studiawan/pygraphc
|
e853e0137e59314f5101c178c74fd626984c34ac
|
pygraphc/similarity/LogTextSimilarity.py
|
python
|
mit
|
Change input from previous processing not from a file
|
from pygraphc.preprocess.PreprocessLog import PreprocessLog
from pygraphc.similarity.StringSimilarity import StringSimilarity
from itertools import combinations
class LogTextSimilarity(object):
"""A class for calculating cosine similarity between a log pair. This class is intended for
non-graph based clustering method.
"""
def __init__(self, logtype, logfile):
"""The constructor of class LogTextSimilarity.
Parameters
----------
logtype : str
Type for event log, e.g., auth, syslog, etc.
logfile : str
Log filename.
"""
self.logtype = logtype
self.logfile = logfile
def get_cosine_similarity(self):
"""Get cosine similarity from a pair of log lines in a file.
Returns
-------
cosine_similarity : dict
Dictionary of cosine similarity in non-graph clustering. Key: (log_id1, log_id2),
value: cosine similarity distance.
"""
preprocess = PreprocessLog(self.logtype, self.logfile)
preprocess.preprocess_text()
events = preprocess.events_text
# calculate cosine similarity
cosines_similarity = {}
for log_pair in combinations(preprocess.loglength, 2):
cosines_similarity[log_pair] = StringSimilarity.get_cosine_similarity(events[log_pair[0]]['tf-idf'],
events[log_pair[1]]['tf-idf'],
events[log_pair[0]]['length'],
events[log_pair[1]]['length'])
return cosines_similarity
|
from pygraphc.preprocess.PreprocessLog import PreprocessLog
from pygraphc.similarity.StringSimilarity import StringSimilarity
from itertools import combinations
class LogTextSimilarity(object):
"""A class for calculating cosine similarity between a log pair. This class is intended for
non-graph based clustering method.
"""
def __init__(self, logtype, logs):
"""The constructor of class LogTextSimilarity.
Parameters
----------
logtype : str
Type for event log, e.g., auth, syslog, etc.
logs : list
List of every line of original logs.
"""
self.logtype = logtype
self.logs = logs
def get_cosine_similarity(self):
"""Get cosine similarity from a pair of log lines in a file.
Returns
-------
cosine_similarity : dict
Dictionary of cosine similarity in non-graph clustering. Key: (log_id1, log_id2),
value: cosine similarity distance.
"""
preprocess = PreprocessLog(self.logtype)
preprocess.preprocess_text(self.logs)
events = preprocess.events_text
# calculate cosine similarity
cosines_similarity = {}
for log_pair in combinations(range(preprocess.loglength), 2):
cosines_similarity[log_pair] = StringSimilarity.get_cosine_similarity(events[log_pair[0]]['tf-idf'],
events[log_pair[1]]['tf-idf'],
events[log_pair[0]]['length'],
events[log_pair[1]]['length'])
return cosines_similarity
| 7
| 7
| 4
|
mixed
|
--- a/pygraphc/similarity/LogTextSimilarity.py
+++ b/pygraphc/similarity/LogTextSimilarity.py
@@ -9,3 +9,3 @@
"""
- def __init__(self, logtype, logfile):
+ def __init__(self, logtype, logs):
"""The constructor of class LogTextSimilarity.
@@ -16,7 +16,7 @@
Type for event log, e.g., auth, syslog, etc.
- logfile : str
- Log filename.
+ logs : list
+ List of every line of original logs.
"""
self.logtype = logtype
- self.logfile = logfile
+ self.logs = logs
@@ -31,4 +31,4 @@
"""
- preprocess = PreprocessLog(self.logtype, self.logfile)
- preprocess.preprocess_text()
+ preprocess = PreprocessLog(self.logtype)
+ preprocess.preprocess_text(self.logs)
events = preprocess.events_text
@@ -37,3 +37,3 @@
cosines_similarity = {}
- for log_pair in combinations(preprocess.loglength, 2):
+ for log_pair in combinations(range(preprocess.loglength), 2):
cosines_similarity[log_pair] = StringSimilarity.get_cosine_similarity(events[log_pair[0]]['tf-idf'],
|
--- a/pygraphc/similarity/LogTextSimilarity.py
+++ b/pygraphc/similarity/LogTextSimilarity.py
@@ ... @@
"""
- def __init__(self, logtype, logfile):
+ def __init__(self, logtype, logs):
"""The constructor of class LogTextSimilarity.
@@ ... @@
Type for event log, e.g., auth, syslog, etc.
- logfile : str
- Log filename.
+ logs : list
+ List of every line of original logs.
"""
self.logtype = logtype
- self.logfile = logfile
+ self.logs = logs
@@ ... @@
"""
- preprocess = PreprocessLog(self.logtype, self.logfile)
- preprocess.preprocess_text()
+ preprocess = PreprocessLog(self.logtype)
+ preprocess.preprocess_text(self.logs)
events = preprocess.events_text
@@ ... @@
cosines_similarity = {}
- for log_pair in combinations(preprocess.loglength, 2):
+ for log_pair in combinations(range(preprocess.loglength), 2):
cosines_similarity[log_pair] = StringSimilarity.get_cosine_similarity(events[log_pair[0]]['tf-idf'],
|
--- a/pygraphc/similarity/LogTextSimilarity.py
+++ b/pygraphc/similarity/LogTextSimilarity.py
@@ -9,3 +9,3 @@
CON """
DEL def __init__(self, logtype, logfile):
ADD def __init__(self, logtype, logs):
CON """The constructor of class LogTextSimilarity.
@@ -16,7 +16,7 @@
CON Type for event log, e.g., auth, syslog, etc.
DEL logfile : str
DEL Log filename.
ADD logs : list
ADD List of every line of original logs.
CON """
CON self.logtype = logtype
DEL self.logfile = logfile
ADD self.logs = logs
CON
@@ -31,4 +31,4 @@
CON """
DEL preprocess = PreprocessLog(self.logtype, self.logfile)
DEL preprocess.preprocess_text()
ADD preprocess = PreprocessLog(self.logtype)
ADD preprocess.preprocess_text(self.logs)
CON events = preprocess.events_text
@@ -37,3 +37,3 @@
CON cosines_similarity = {}
DEL for log_pair in combinations(preprocess.loglength, 2):
ADD for log_pair in combinations(range(preprocess.loglength), 2):
CON cosines_similarity[log_pair] = StringSimilarity.get_cosine_similarity(events[log_pair[0]]['tf-idf'],
|
<<<<<<< SEARCH
non-graph based clustering method.
"""
def __init__(self, logtype, logfile):
"""The constructor of class LogTextSimilarity.
=======
non-graph based clustering method.
"""
def __init__(self, logtype, logs):
"""The constructor of class LogTextSimilarity.
>>>>>>> REPLACE
<<<<<<< SEARCH
logtype : str
Type for event log, e.g., auth, syslog, etc.
logfile : str
Log filename.
"""
self.logtype = logtype
self.logfile = logfile
def get_cosine_similarity(self):
=======
logtype : str
Type for event log, e.g., auth, syslog, etc.
logs : list
List of every line of original logs.
"""
self.logtype = logtype
self.logs = logs
def get_cosine_similarity(self):
>>>>>>> REPLACE
<<<<<<< SEARCH
value: cosine similarity distance.
"""
preprocess = PreprocessLog(self.logtype, self.logfile)
preprocess.preprocess_text()
events = preprocess.events_text
# calculate cosine similarity
cosines_similarity = {}
for log_pair in combinations(preprocess.loglength, 2):
cosines_similarity[log_pair] = StringSimilarity.get_cosine_similarity(events[log_pair[0]]['tf-idf'],
events[log_pair[1]]['tf-idf'],
=======
value: cosine similarity distance.
"""
preprocess = PreprocessLog(self.logtype)
preprocess.preprocess_text(self.logs)
events = preprocess.events_text
# calculate cosine similarity
cosines_similarity = {}
for log_pair in combinations(range(preprocess.loglength), 2):
cosines_similarity[log_pair] = StringSimilarity.get_cosine_similarity(events[log_pair[0]]['tf-idf'],
events[log_pair[1]]['tf-idf'],
>>>>>>> REPLACE
|
ben--/kata-rnc
|
6fce68a91046cd4f3824a82471dc3395d8461692
|
src/rust/src/lib.rs
|
rust
|
mit
|
Use more idiomatic rust testing
|
extern crate libc;
use std::ffi::CStr;
use std::os::raw::c_char;
use libc::size_t;
use libc::strncpy;
mod rnc {
#[test]
fn add_i_i() {
assert_eq!("II", add("I", "I"));
}
#[test]
fn add_i_ii() {
assert_eq!("III", add("I", "II"));
}
#[test]
fn add_ii_iii() {
assert_eq!("V", add("II", "III"));
}
pub fn add(num_l: &str, num_r: &str) -> String {
let sum = String::from(num_l) + num_r;
if sum == "IIIII" {
String::from("V")
} else {
sum
}
}
}
use rnc::add;
#[no_mangle]
pub extern fn rnc_add(dst: *mut c_char, dstlen: size_t, num_l: *const c_char, num_r: *const c_char) {
unsafe {
let sum = add(CStr::from_ptr(num_l).to_str().unwrap(), CStr::from_ptr(num_r).to_str().unwrap());
strncpy(dst, sum.as_ptr() as *const i8, dstlen);
}
}
|
extern crate libc;
use std::ffi::CStr;
use std::os::raw::c_char;
use libc::size_t;
use libc::strncpy;
mod rnc {
pub fn add(num_l: &str, num_r: &str) -> String {
let sum = String::from(num_l) + num_r;
if sum == "IIIII" {
String::from("V")
} else {
sum
}
}
#[cfg(test)]
mod tests {
use super::add;
#[test]
fn add_i_i() {
assert_eq!("II", add("I", "I"));
}
#[test]
fn add_i_ii() {
assert_eq!("III", add("I", "II"));
}
#[test]
fn add_ii_iii() {
assert_eq!("V", add("II", "III"));
}
}
}
use rnc::add;
#[no_mangle]
pub extern fn rnc_add(dst: *mut c_char, dstlen: size_t, num_l: *const c_char, num_r: *const c_char) {
unsafe {
let sum = add(CStr::from_ptr(num_l).to_str().unwrap(), CStr::from_ptr(num_r).to_str().unwrap());
strncpy(dst, sum.as_ptr() as *const i8, dstlen);
}
}
| 21
| 16
| 2
|
mixed
|
--- a/src/rust/src/lib.rs
+++ b/src/rust/src/lib.rs
@@ -8,18 +8,2 @@
mod rnc {
- #[test]
- fn add_i_i() {
- assert_eq!("II", add("I", "I"));
- }
-
- #[test]
- fn add_i_ii() {
- assert_eq!("III", add("I", "II"));
- }
-
- #[test]
- fn add_ii_iii() {
- assert_eq!("V", add("II", "III"));
-
- }
-
pub fn add(num_l: &str, num_r: &str) -> String {
@@ -31,2 +15,23 @@
sum
+ }
+ }
+
+ #[cfg(test)]
+ mod tests {
+ use super::add;
+
+ #[test]
+ fn add_i_i() {
+ assert_eq!("II", add("I", "I"));
+ }
+
+ #[test]
+ fn add_i_ii() {
+ assert_eq!("III", add("I", "II"));
+ }
+
+ #[test]
+ fn add_ii_iii() {
+ assert_eq!("V", add("II", "III"));
+
}
|
--- a/src/rust/src/lib.rs
+++ b/src/rust/src/lib.rs
@@ ... @@
mod rnc {
- #[test]
- fn add_i_i() {
- assert_eq!("II", add("I", "I"));
- }
-
- #[test]
- fn add_i_ii() {
- assert_eq!("III", add("I", "II"));
- }
-
- #[test]
- fn add_ii_iii() {
- assert_eq!("V", add("II", "III"));
-
- }
-
pub fn add(num_l: &str, num_r: &str) -> String {
@@ ... @@
sum
+ }
+ }
+
+ #[cfg(test)]
+ mod tests {
+ use super::add;
+
+ #[test]
+ fn add_i_i() {
+ assert_eq!("II", add("I", "I"));
+ }
+
+ #[test]
+ fn add_i_ii() {
+ assert_eq!("III", add("I", "II"));
+ }
+
+ #[test]
+ fn add_ii_iii() {
+ assert_eq!("V", add("II", "III"));
+
}
|
--- a/src/rust/src/lib.rs
+++ b/src/rust/src/lib.rs
@@ -8,18 +8,2 @@
CON mod rnc {
DEL #[test]
DEL fn add_i_i() {
DEL assert_eq!("II", add("I", "I"));
DEL }
DEL
DEL #[test]
DEL fn add_i_ii() {
DEL assert_eq!("III", add("I", "II"));
DEL }
DEL
DEL #[test]
DEL fn add_ii_iii() {
DEL assert_eq!("V", add("II", "III"));
DEL
DEL }
DEL
CON pub fn add(num_l: &str, num_r: &str) -> String {
@@ -31,2 +15,23 @@
CON sum
ADD }
ADD }
ADD
ADD #[cfg(test)]
ADD mod tests {
ADD use super::add;
ADD
ADD #[test]
ADD fn add_i_i() {
ADD assert_eq!("II", add("I", "I"));
ADD }
ADD
ADD #[test]
ADD fn add_i_ii() {
ADD assert_eq!("III", add("I", "II"));
ADD }
ADD
ADD #[test]
ADD fn add_ii_iii() {
ADD assert_eq!("V", add("II", "III"));
ADD
CON }
|
<<<<<<< SEARCH
mod rnc {
#[test]
fn add_i_i() {
assert_eq!("II", add("I", "I"));
}
#[test]
fn add_i_ii() {
assert_eq!("III", add("I", "II"));
}
#[test]
fn add_ii_iii() {
assert_eq!("V", add("II", "III"));
}
pub fn add(num_l: &str, num_r: &str) -> String {
let sum = String::from(num_l) + num_r;
=======
mod rnc {
pub fn add(num_l: &str, num_r: &str) -> String {
let sum = String::from(num_l) + num_r;
>>>>>>> REPLACE
<<<<<<< SEARCH
} else {
sum
}
}
=======
} else {
sum
}
}
#[cfg(test)]
mod tests {
use super::add;
#[test]
fn add_i_i() {
assert_eq!("II", add("I", "I"));
}
#[test]
fn add_i_ii() {
assert_eq!("III", add("I", "II"));
}
#[test]
fn add_ii_iii() {
assert_eq!("V", add("II", "III"));
}
}
>>>>>>> REPLACE
|
incuna/incuna-auth
|
2951520fab9f213322584327c9e5841fe13fc993
|
tests/run.py
|
python
|
bsd-2-clause
|
Remove unnecessary Python 3 declaration.
|
#! /usr/bin/env python3
import sys
from colour_runner.django_runner import ColourRunnerMixin
from django.conf import settings
settings.configure(
INSTALLED_APPS=(
# Put contenttypes before auth to work around test issue.
# See: https://code.djangoproject.com/ticket/10827#comment:12
'django.contrib.contenttypes',
'django.contrib.auth',
'django.contrib.sessions',
'django.contrib.admin',
'django-admin-sso',
'django-crispy-forms',
'incuna_auth',
),
PASSWORD_HASHERS = ('django.contrib.auth.hashers.MD5PasswordHasher',),
AUTH_USER_MODEL='tests.User',
ROOT_URLCONF='incuna_auth.urls',
REST_FRAMEWORK={
'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.IsAuthenticated',),
'DEFAULT_RENDERER_CLASSES': ('rest_framework.renderers.JSONRenderer',),
},
)
from django.test.runner import DiscoverRunner
class Runner(ColourRunnerMixin, DiscoverRunner):
pass
test_runner = Runner(verbosity=1)
failures = test_runner.run_tests(['tests'])
if failures:
sys.exit(1)
|
import sys
from colour_runner.django_runner import ColourRunnerMixin
from django.conf import settings
settings.configure(
INSTALLED_APPS=(
# Put contenttypes before auth to work around test issue.
# See: https://code.djangoproject.com/ticket/10827#comment:12
'django.contrib.contenttypes',
'django.contrib.auth',
'django.contrib.sessions',
'django.contrib.admin',
'django-admin-sso',
'django-crispy-forms',
'incuna_auth',
),
PASSWORD_HASHERS = ('django.contrib.auth.hashers.MD5PasswordHasher',),
AUTH_USER_MODEL='tests.User',
ROOT_URLCONF='incuna_auth.urls',
REST_FRAMEWORK={
'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.IsAuthenticated',),
'DEFAULT_RENDERER_CLASSES': ('rest_framework.renderers.JSONRenderer',),
},
)
from django.test.runner import DiscoverRunner
class Runner(ColourRunnerMixin, DiscoverRunner):
pass
test_runner = Runner(verbosity=1)
failures = test_runner.run_tests(['tests'])
if failures:
sys.exit(1)
| 0
| 1
| 1
|
del_only
|
--- a/tests/run.py
+++ b/tests/run.py
@@ -1,2 +1 @@
-#! /usr/bin/env python3
import sys
|
--- a/tests/run.py
+++ b/tests/run.py
@@ ... @@
-#! /usr/bin/env python3
import sys
|
--- a/tests/run.py
+++ b/tests/run.py
@@ -1,2 +1 @@
DEL #! /usr/bin/env python3
CON import sys
|
<<<<<<< SEARCH
#! /usr/bin/env python3
import sys
=======
import sys
>>>>>>> REPLACE
|
laarmen/SeO2
|
0877634abe71a8dfe9772c053d201331dbb3fd32
|
src/lib.rs
|
rust
|
mit
|
Split in two the eval_file function
|
extern crate nom_lua53;
use nom_lua53::{parse_all, ParseResult, Statement};
mod expression;
mod types;
#[derive(PartialEq,Eq,Debug)]
pub enum LuaError {
TypeError(String),
IndexError(String),
ArithmeticError(String),
}
type Result<T> = std::result::Result<T, LuaError>;
pub fn eval_file(input: &[u8]) {
let ctx = types::LuaState::new();
match parse_all(input) {
ParseResult::Done(blk) => {
for stmt in blk.stmts {
println!("{:?}", stmt);
match stmt {
Statement::LVarAssign(ass) => {
let values = ass.vals.expect("There should be some values. Why isn't there any value?!");
for (var, val) in ass.vars.iter().zip(values.iter()) {
let computed_value = expression::eval_expr(val, &ctx);
println!("Assigning {:?} to {:?}", computed_value, var);
}
}
Statement::Assignment(ass) => {
println!("Assigning {:?} to {:?}", ass.vals, ass.vars);
}
_ => {}
}
}
}
ParseResult::Error(rest, ss) => {
println!("Error. statements == {:#?}", ss);
println!("rest == '{}'", String::from_utf8_lossy(rest));
}
}
}
|
extern crate nom_lua53;
use nom_lua53::{parse_all, ParseResult, Statement};
mod expression;
mod types;
#[derive(PartialEq,Eq,Debug)]
pub enum LuaError {
TypeError(String),
IndexError(String),
ArithmeticError(String),
}
type Result<T> = std::result::Result<T, LuaError>;
pub fn parse_statement(stmt: &Statement, ctx: &mut types::LuaState) {
match stmt {
&Statement::LVarAssign(ref ass) => {
let values = ass.vals.as_ref().expect("There should be some values. Why isn't there any value?!");
for (var, val) in ass.vars.iter().zip(values.iter()) {
let computed_value = expression::eval_expr(val, &ctx);
println!("Assigning {:?} to {:?}", computed_value, var);
}
}
&Statement::Assignment(ref ass) => {
println!("Assigning {:?} to {:?}", ass.vals, ass.vars);
}
_ => {}
}
}
pub fn eval_file(input: &[u8]) {
let mut ctx = types::LuaState::new();
match parse_all(input) {
ParseResult::Done(blk) => {
for stmt in blk.stmts {
println!("{:?}", stmt);
parse_statement(&stmt, &mut ctx)
}
}
ParseResult::Error(rest, ss) => {
println!("Error. statements == {:#?}", ss);
println!("rest == '{}'", String::from_utf8_lossy(rest));
}
}
}
| 20
| 16
| 3
|
mixed
|
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -10,4 +10,4 @@
TypeError(String),
- IndexError(String),
- ArithmeticError(String),
+ IndexError(String),
+ ArithmeticError(String),
}
@@ -16,4 +16,20 @@
+pub fn parse_statement(stmt: &Statement, ctx: &mut types::LuaState) {
+ match stmt {
+ &Statement::LVarAssign(ref ass) => {
+ let values = ass.vals.as_ref().expect("There should be some values. Why isn't there any value?!");
+ for (var, val) in ass.vars.iter().zip(values.iter()) {
+ let computed_value = expression::eval_expr(val, &ctx);
+ println!("Assigning {:?} to {:?}", computed_value, var);
+ }
+ }
+ &Statement::Assignment(ref ass) => {
+ println!("Assigning {:?} to {:?}", ass.vals, ass.vars);
+ }
+ _ => {}
+ }
+
+}
pub fn eval_file(input: &[u8]) {
- let ctx = types::LuaState::new();
+ let mut ctx = types::LuaState::new();
match parse_all(input) {
@@ -22,15 +38,3 @@
println!("{:?}", stmt);
- match stmt {
- Statement::LVarAssign(ass) => {
- let values = ass.vals.expect("There should be some values. Why isn't there any value?!");
- for (var, val) in ass.vars.iter().zip(values.iter()) {
- let computed_value = expression::eval_expr(val, &ctx);
- println!("Assigning {:?} to {:?}", computed_value, var);
- }
- }
- Statement::Assignment(ass) => {
- println!("Assigning {:?} to {:?}", ass.vals, ass.vars);
- }
- _ => {}
- }
+ parse_statement(&stmt, &mut ctx)
}
|
--- a/src/lib.rs
+++ b/src/lib.rs
@@ ... @@
TypeError(String),
- IndexError(String),
- ArithmeticError(String),
+ IndexError(String),
+ ArithmeticError(String),
}
@@ ... @@
+pub fn parse_statement(stmt: &Statement, ctx: &mut types::LuaState) {
+ match stmt {
+ &Statement::LVarAssign(ref ass) => {
+ let values = ass.vals.as_ref().expect("There should be some values. Why isn't there any value?!");
+ for (var, val) in ass.vars.iter().zip(values.iter()) {
+ let computed_value = expression::eval_expr(val, &ctx);
+ println!("Assigning {:?} to {:?}", computed_value, var);
+ }
+ }
+ &Statement::Assignment(ref ass) => {
+ println!("Assigning {:?} to {:?}", ass.vals, ass.vars);
+ }
+ _ => {}
+ }
+
+}
pub fn eval_file(input: &[u8]) {
- let ctx = types::LuaState::new();
+ let mut ctx = types::LuaState::new();
match parse_all(input) {
@@ ... @@
println!("{:?}", stmt);
- match stmt {
- Statement::LVarAssign(ass) => {
- let values = ass.vals.expect("There should be some values. Why isn't there any value?!");
- for (var, val) in ass.vars.iter().zip(values.iter()) {
- let computed_value = expression::eval_expr(val, &ctx);
- println!("Assigning {:?} to {:?}", computed_value, var);
- }
- }
- Statement::Assignment(ass) => {
- println!("Assigning {:?} to {:?}", ass.vals, ass.vars);
- }
- _ => {}
- }
+ parse_statement(&stmt, &mut ctx)
}
|
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -10,4 +10,4 @@
CON TypeError(String),
DEL IndexError(String),
DEL ArithmeticError(String),
ADD IndexError(String),
ADD ArithmeticError(String),
CON }
@@ -16,4 +16,20 @@
CON
ADD pub fn parse_statement(stmt: &Statement, ctx: &mut types::LuaState) {
ADD match stmt {
ADD &Statement::LVarAssign(ref ass) => {
ADD let values = ass.vals.as_ref().expect("There should be some values. Why isn't there any value?!");
ADD for (var, val) in ass.vars.iter().zip(values.iter()) {
ADD let computed_value = expression::eval_expr(val, &ctx);
ADD println!("Assigning {:?} to {:?}", computed_value, var);
ADD }
ADD }
ADD &Statement::Assignment(ref ass) => {
ADD println!("Assigning {:?} to {:?}", ass.vals, ass.vars);
ADD }
ADD _ => {}
ADD }
ADD
ADD }
CON pub fn eval_file(input: &[u8]) {
DEL let ctx = types::LuaState::new();
ADD let mut ctx = types::LuaState::new();
CON match parse_all(input) {
@@ -22,15 +38,3 @@
CON println!("{:?}", stmt);
DEL match stmt {
DEL Statement::LVarAssign(ass) => {
DEL let values = ass.vals.expect("There should be some values. Why isn't there any value?!");
DEL for (var, val) in ass.vars.iter().zip(values.iter()) {
DEL let computed_value = expression::eval_expr(val, &ctx);
DEL println!("Assigning {:?} to {:?}", computed_value, var);
DEL }
DEL }
DEL Statement::Assignment(ass) => {
DEL println!("Assigning {:?} to {:?}", ass.vals, ass.vars);
DEL }
DEL _ => {}
DEL }
ADD parse_statement(&stmt, &mut ctx)
CON }
|
<<<<<<< SEARCH
pub enum LuaError {
TypeError(String),
IndexError(String),
ArithmeticError(String),
}
type Result<T> = std::result::Result<T, LuaError>;
pub fn eval_file(input: &[u8]) {
let ctx = types::LuaState::new();
match parse_all(input) {
ParseResult::Done(blk) => {
for stmt in blk.stmts {
println!("{:?}", stmt);
match stmt {
Statement::LVarAssign(ass) => {
let values = ass.vals.expect("There should be some values. Why isn't there any value?!");
for (var, val) in ass.vars.iter().zip(values.iter()) {
let computed_value = expression::eval_expr(val, &ctx);
println!("Assigning {:?} to {:?}", computed_value, var);
}
}
Statement::Assignment(ass) => {
println!("Assigning {:?} to {:?}", ass.vals, ass.vars);
}
_ => {}
}
}
}
=======
pub enum LuaError {
TypeError(String),
IndexError(String),
ArithmeticError(String),
}
type Result<T> = std::result::Result<T, LuaError>;
pub fn parse_statement(stmt: &Statement, ctx: &mut types::LuaState) {
match stmt {
&Statement::LVarAssign(ref ass) => {
let values = ass.vals.as_ref().expect("There should be some values. Why isn't there any value?!");
for (var, val) in ass.vars.iter().zip(values.iter()) {
let computed_value = expression::eval_expr(val, &ctx);
println!("Assigning {:?} to {:?}", computed_value, var);
}
}
&Statement::Assignment(ref ass) => {
println!("Assigning {:?} to {:?}", ass.vals, ass.vars);
}
_ => {}
}
}
pub fn eval_file(input: &[u8]) {
let mut ctx = types::LuaState::new();
match parse_all(input) {
ParseResult::Done(blk) => {
for stmt in blk.stmts {
println!("{:?}", stmt);
parse_statement(&stmt, &mut ctx)
}
}
>>>>>>> REPLACE
|
sbrannen/junit-lambda
|
674db71cab812aeb44cc250e4505efa5f04b49e4
|
junit-jupiter-engine/junit-jupiter-engine.gradle.kts
|
kotlin
|
epl-1.0
|
Set source/target compatibility for Groovy compilation
|
plugins {
groovy
}
apply(from = "$rootDir/gradle/testing.gradle.kts")
description = "JUnit Jupiter Engine"
tasks.jar {
manifest {
attributes(
"Automatic-Module-Name" to "org.junit.jupiter.engine"
)
}
}
val testArtifacts by configurations.creating {
extendsFrom(configurations["testRuntime"])
}
val testJar by tasks.creating(Jar::class) {
archiveClassifier.set("test")
from(sourceSets.getByName("test").output)
}
artifacts {
add(testArtifacts.name, testJar)
}
dependencies {
api("org.apiguardian:apiguardian-api:${Versions.apiGuardian}")
api(project(":junit-platform-engine"))
api(project(":junit-jupiter-api"))
testImplementation(project(":junit-platform-launcher"))
testImplementation(project(":junit-platform-runner"))
testImplementation(project(":junit-platform-testkit"))
testImplementation("org.jetbrains.kotlin:kotlin-stdlib")
testImplementation(localGroovy())
}
|
plugins {
groovy
}
apply(from = "$rootDir/gradle/testing.gradle.kts")
description = "JUnit Jupiter Engine"
tasks.jar {
manifest {
attributes(
"Automatic-Module-Name" to "org.junit.jupiter.engine"
)
}
}
val testJavaVersion by extra(JavaVersion.VERSION_11)
tasks.compileTestGroovy {
sourceCompatibility = testJavaVersion.majorVersion
targetCompatibility = testJavaVersion.majorVersion
}
val testArtifacts by configurations.creating {
extendsFrom(configurations["testRuntime"])
}
val testJar by tasks.creating(Jar::class) {
archiveClassifier.set("test")
from(sourceSets.getByName("test").output)
}
artifacts {
add(testArtifacts.name, testJar)
}
dependencies {
api("org.apiguardian:apiguardian-api:${Versions.apiGuardian}")
api(project(":junit-platform-engine"))
api(project(":junit-jupiter-api"))
testImplementation(project(":junit-platform-launcher"))
testImplementation(project(":junit-platform-runner"))
testImplementation(project(":junit-platform-testkit"))
testImplementation("org.jetbrains.kotlin:kotlin-stdlib")
testImplementation(localGroovy())
}
| 7
| 0
| 1
|
add_only
|
--- a/junit-jupiter-engine/junit-jupiter-engine.gradle.kts
+++ b/junit-jupiter-engine/junit-jupiter-engine.gradle.kts
@@ -14,2 +14,9 @@
}
+}
+
+val testJavaVersion by extra(JavaVersion.VERSION_11)
+
+tasks.compileTestGroovy {
+ sourceCompatibility = testJavaVersion.majorVersion
+ targetCompatibility = testJavaVersion.majorVersion
}
|
--- a/junit-jupiter-engine/junit-jupiter-engine.gradle.kts
+++ b/junit-jupiter-engine/junit-jupiter-engine.gradle.kts
@@ ... @@
}
+}
+
+val testJavaVersion by extra(JavaVersion.VERSION_11)
+
+tasks.compileTestGroovy {
+ sourceCompatibility = testJavaVersion.majorVersion
+ targetCompatibility = testJavaVersion.majorVersion
}
|
--- a/junit-jupiter-engine/junit-jupiter-engine.gradle.kts
+++ b/junit-jupiter-engine/junit-jupiter-engine.gradle.kts
@@ -14,2 +14,9 @@
CON }
ADD }
ADD
ADD val testJavaVersion by extra(JavaVersion.VERSION_11)
ADD
ADD tasks.compileTestGroovy {
ADD sourceCompatibility = testJavaVersion.majorVersion
ADD targetCompatibility = testJavaVersion.majorVersion
CON }
|
<<<<<<< SEARCH
)
}
}
=======
)
}
}
val testJavaVersion by extra(JavaVersion.VERSION_11)
tasks.compileTestGroovy {
sourceCompatibility = testJavaVersion.majorVersion
targetCompatibility = testJavaVersion.majorVersion
}
>>>>>>> REPLACE
|
google/rrg
|
42eeb54af3652867e6c0d584a3fa16b0e459ce75
|
proto/src/convert.rs
|
rust
|
mit
|
Add documentation for the conversion module.
|
// Copyright 2020 Google LLC
//
// Use of this source code is governed by an MIT-style license that can be found
// in the LICENSE file or at https://opensource.org/licenses/MIT.
pub trait FromLossy<T>: Sized {
fn from_lossy(_: T) -> Self;
}
pub trait IntoLossy<T>: Sized {
fn into_lossy(self) -> T;
}
impl<T, U> IntoLossy<U> for T
where
U: FromLossy<T>,
{
fn into_lossy(self) -> U {
U::from_lossy(self)
}
}
|
// Copyright 2020 Google LLC
//
// Use of this source code is governed by an MIT-style license that can be found
// in the LICENSE file or at https://opensource.org/licenses/MIT.
//! Traits for conversions between types.
//!
//! This module provides utility traits similar to what `std::convert` does and
//! can be thought as an extension of it to fit RRG-specific purposes.
/// A lossy conversion from one type to the other.
///
/// This trait is very similar to `From` from the standard library, except that
/// it allows values to lose some information. Moreover, the implementers are
/// allowed to log details about the lost information, so the conversion might
/// have side effects.
///
/// See also [`IntoLossy`].
///
/// [`IntoLossy`]: trait.IntoLossy.html
pub trait FromLossy<T>: Sized {
/// Convert the value of another type.
fn from_lossy(_: T) -> Self;
}
/// A lossy conversion into one type from the other.
///
/// This trait is very similar to `Into` from the standard library, except that
/// it allows values to lose some information. Moreover, the implementers are
/// allowed to log details about the lost information, so the conversion might
/// have side effects.
///
/// Note that it is discouraged to implement this trait directly. Instead, one
/// should provide a reverse implementation for [`FromLossy`] and derive the
/// implementation for `IntoLossy` automatically.
///
/// [`FromLossy`]: trait.FromLossy.html
pub trait IntoLossy<T>: Sized {
/// Convert the value into another type.
fn into_lossy(self) -> T;
}
impl<T, U> IntoLossy<U> for T
where
U: FromLossy<T>,
{
fn into_lossy(self) -> U {
U::from_lossy(self)
}
}
| 29
| 0
| 2
|
add_only
|
--- a/proto/src/convert.rs
+++ b/proto/src/convert.rs
@@ -5,3 +5,19 @@
+//! Traits for conversions between types.
+//!
+//! This module provides utility traits similar to what `std::convert` does and
+//! can be thought as an extension of it to fit RRG-specific purposes.
+
+/// A lossy conversion from one type to the other.
+///
+/// This trait is very similar to `From` from the standard library, except that
+/// it allows values to lose some information. Moreover, the implementers are
+/// allowed to log details about the lost information, so the conversion might
+/// have side effects.
+///
+/// See also [`IntoLossy`].
+///
+/// [`IntoLossy`]: trait.IntoLossy.html
pub trait FromLossy<T>: Sized {
+ /// Convert the value of another type.
fn from_lossy(_: T) -> Self;
@@ -9,3 +25,16 @@
+/// A lossy conversion into one type from the other.
+///
+/// This trait is very similar to `Into` from the standard library, except that
+/// it allows values to lose some information. Moreover, the implementers are
+/// allowed to log details about the lost information, so the conversion might
+/// have side effects.
+///
+/// Note that it is discouraged to implement this trait directly. Instead, one
+/// should provide a reverse implementation for [`FromLossy`] and derive the
+/// implementation for `IntoLossy` automatically.
+///
+/// [`FromLossy`]: trait.FromLossy.html
pub trait IntoLossy<T>: Sized {
+ /// Convert the value into another type.
fn into_lossy(self) -> T;
|
--- a/proto/src/convert.rs
+++ b/proto/src/convert.rs
@@ ... @@
+//! Traits for conversions between types.
+//!
+//! This module provides utility traits similar to what `std::convert` does and
+//! can be thought as an extension of it to fit RRG-specific purposes.
+
+/// A lossy conversion from one type to the other.
+///
+/// This trait is very similar to `From` from the standard library, except that
+/// it allows values to lose some information. Moreover, the implementers are
+/// allowed to log details about the lost information, so the conversion might
+/// have side effects.
+///
+/// See also [`IntoLossy`].
+///
+/// [`IntoLossy`]: trait.IntoLossy.html
pub trait FromLossy<T>: Sized {
+ /// Convert the value of another type.
fn from_lossy(_: T) -> Self;
@@ ... @@
+/// A lossy conversion into one type from the other.
+///
+/// This trait is very similar to `Into` from the standard library, except that
+/// it allows values to lose some information. Moreover, the implementers are
+/// allowed to log details about the lost information, so the conversion might
+/// have side effects.
+///
+/// Note that it is discouraged to implement this trait directly. Instead, one
+/// should provide a reverse implementation for [`FromLossy`] and derive the
+/// implementation for `IntoLossy` automatically.
+///
+/// [`FromLossy`]: trait.FromLossy.html
pub trait IntoLossy<T>: Sized {
+ /// Convert the value into another type.
fn into_lossy(self) -> T;
|
--- a/proto/src/convert.rs
+++ b/proto/src/convert.rs
@@ -5,3 +5,19 @@
CON
ADD //! Traits for conversions between types.
ADD //!
ADD //! This module provides utility traits similar to what `std::convert` does and
ADD //! can be thought as an extension of it to fit RRG-specific purposes.
ADD
ADD /// A lossy conversion from one type to the other.
ADD ///
ADD /// This trait is very similar to `From` from the standard library, except that
ADD /// it allows values to lose some information. Moreover, the implementers are
ADD /// allowed to log details about the lost information, so the conversion might
ADD /// have side effects.
ADD ///
ADD /// See also [`IntoLossy`].
ADD ///
ADD /// [`IntoLossy`]: trait.IntoLossy.html
CON pub trait FromLossy<T>: Sized {
ADD /// Convert the value of another type.
CON fn from_lossy(_: T) -> Self;
@@ -9,3 +25,16 @@
CON
ADD /// A lossy conversion into one type from the other.
ADD ///
ADD /// This trait is very similar to `Into` from the standard library, except that
ADD /// it allows values to lose some information. Moreover, the implementers are
ADD /// allowed to log details about the lost information, so the conversion might
ADD /// have side effects.
ADD ///
ADD /// Note that it is discouraged to implement this trait directly. Instead, one
ADD /// should provide a reverse implementation for [`FromLossy`] and derive the
ADD /// implementation for `IntoLossy` automatically.
ADD ///
ADD /// [`FromLossy`]: trait.FromLossy.html
CON pub trait IntoLossy<T>: Sized {
ADD /// Convert the value into another type.
CON fn into_lossy(self) -> T;
|
<<<<<<< SEARCH
// in the LICENSE file or at https://opensource.org/licenses/MIT.
pub trait FromLossy<T>: Sized {
fn from_lossy(_: T) -> Self;
}
pub trait IntoLossy<T>: Sized {
fn into_lossy(self) -> T;
}
=======
// in the LICENSE file or at https://opensource.org/licenses/MIT.
//! Traits for conversions between types.
//!
//! This module provides utility traits similar to what `std::convert` does and
//! can be thought as an extension of it to fit RRG-specific purposes.
/// A lossy conversion from one type to the other.
///
/// This trait is very similar to `From` from the standard library, except that
/// it allows values to lose some information. Moreover, the implementers are
/// allowed to log details about the lost information, so the conversion might
/// have side effects.
///
/// See also [`IntoLossy`].
///
/// [`IntoLossy`]: trait.IntoLossy.html
pub trait FromLossy<T>: Sized {
/// Convert the value of another type.
fn from_lossy(_: T) -> Self;
}
/// A lossy conversion into one type from the other.
///
/// This trait is very similar to `Into` from the standard library, except that
/// it allows values to lose some information. Moreover, the implementers are
/// allowed to log details about the lost information, so the conversion might
/// have side effects.
///
/// Note that it is discouraged to implement this trait directly. Instead, one
/// should provide a reverse implementation for [`FromLossy`] and derive the
/// implementation for `IntoLossy` automatically.
///
/// [`FromLossy`]: trait.FromLossy.html
pub trait IntoLossy<T>: Sized {
/// Convert the value into another type.
fn into_lossy(self) -> T;
}
>>>>>>> REPLACE
|
jarcane/rouler
|
7df8065dc720da437cc8744b4753ffe1e37220ed
|
src/lib.rs
|
rust
|
mpl-2.0
|
Refactor Roller and add roll_dice fn
|
#![allow(dead_code)]
#[macro_use]
extern crate pest;
extern crate rand;
mod parse;
use pest::*;
use parse::*;
#[derive(Debug)]
pub struct Roller<'a> {
roll: &'a str,
total: i32,
}
impl<'a> Roller<'a> {
fn new(roll: &str) -> Roller {
let mut parser = Rdp::new(StringInput::new(roll));
parser.expression();
Roller{
roll: roll,
total: parser.compute()
}
}
fn reroll(&mut self) -> i32 {
let mut parser = Rdp::new(StringInput::new(self.roll));
parser.expression();
self.total = parser.compute();
self.total
}
fn total(&self) -> i32 {
self.total
}
}
#[test]
fn it_works() {
let mut roller = Roller::new("4d6");
assert!((4 <= roller.total()) && (roller.total() <= 24));
assert!(roller.total() != roller.reroll());
}
|
#![allow(dead_code)]
#[macro_use]
extern crate pest;
extern crate rand;
mod parse;
use pest::*;
use parse::*;
pub fn roll_dice(r: &str) -> i32 {
let mut parser = Rdp::new(StringInput::new(r));
parser.expression();
parser.compute()
}
#[derive(Debug)]
pub struct Roller<'a> {
roll: &'a str,
total: i32,
}
impl<'a> Roller<'a> {
fn new(roll: &str) -> Roller {
Roller{
roll: roll,
total: roll_dice(roll)
}
}
fn reroll(&mut self) -> i32 {
self.total = roll_dice(self.roll);
self.total
}
fn total(&self) -> i32 {
self.total
}
}
#[test]
fn it_works() {
let mut roller = Roller::new("4d6");
assert!((4 <= roller.total()) && (roller.total() <= 24));
assert!(roller.total() != roller.reroll());
}
| 9
| 8
| 3
|
mixed
|
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -12,2 +12,9 @@
+pub fn roll_dice(r: &str) -> i32 {
+ let mut parser = Rdp::new(StringInput::new(r));
+ parser.expression();
+
+ parser.compute()
+}
+
#[derive(Debug)]
@@ -20,8 +27,5 @@
fn new(roll: &str) -> Roller {
- let mut parser = Rdp::new(StringInput::new(roll));
- parser.expression();
-
Roller{
roll: roll,
- total: parser.compute()
+ total: roll_dice(roll)
}
@@ -30,6 +34,3 @@
fn reroll(&mut self) -> i32 {
- let mut parser = Rdp::new(StringInput::new(self.roll));
- parser.expression();
-
- self.total = parser.compute();
+ self.total = roll_dice(self.roll);
|
--- a/src/lib.rs
+++ b/src/lib.rs
@@ ... @@
+pub fn roll_dice(r: &str) -> i32 {
+ let mut parser = Rdp::new(StringInput::new(r));
+ parser.expression();
+
+ parser.compute()
+}
+
#[derive(Debug)]
@@ ... @@
fn new(roll: &str) -> Roller {
- let mut parser = Rdp::new(StringInput::new(roll));
- parser.expression();
-
Roller{
roll: roll,
- total: parser.compute()
+ total: roll_dice(roll)
}
@@ ... @@
fn reroll(&mut self) -> i32 {
- let mut parser = Rdp::new(StringInput::new(self.roll));
- parser.expression();
-
- self.total = parser.compute();
+ self.total = roll_dice(self.roll);
|
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -12,2 +12,9 @@
CON
ADD pub fn roll_dice(r: &str) -> i32 {
ADD let mut parser = Rdp::new(StringInput::new(r));
ADD parser.expression();
ADD
ADD parser.compute()
ADD }
ADD
CON #[derive(Debug)]
@@ -20,8 +27,5 @@
CON fn new(roll: &str) -> Roller {
DEL let mut parser = Rdp::new(StringInput::new(roll));
DEL parser.expression();
DEL
CON Roller{
CON roll: roll,
DEL total: parser.compute()
ADD total: roll_dice(roll)
CON }
@@ -30,6 +34,3 @@
CON fn reroll(&mut self) -> i32 {
DEL let mut parser = Rdp::new(StringInput::new(self.roll));
DEL parser.expression();
DEL
DEL self.total = parser.compute();
ADD self.total = roll_dice(self.roll);
CON
|
<<<<<<< SEARCH
use parse::*;
#[derive(Debug)]
pub struct Roller<'a> {
=======
use parse::*;
pub fn roll_dice(r: &str) -> i32 {
let mut parser = Rdp::new(StringInput::new(r));
parser.expression();
parser.compute()
}
#[derive(Debug)]
pub struct Roller<'a> {
>>>>>>> REPLACE
<<<<<<< SEARCH
impl<'a> Roller<'a> {
fn new(roll: &str) -> Roller {
let mut parser = Rdp::new(StringInput::new(roll));
parser.expression();
Roller{
roll: roll,
total: parser.compute()
}
}
fn reroll(&mut self) -> i32 {
let mut parser = Rdp::new(StringInput::new(self.roll));
parser.expression();
self.total = parser.compute();
self.total
=======
impl<'a> Roller<'a> {
fn new(roll: &str) -> Roller {
Roller{
roll: roll,
total: roll_dice(roll)
}
}
fn reroll(&mut self) -> i32 {
self.total = roll_dice(self.roll);
self.total
>>>>>>> REPLACE
|
rust-lang/reference
|
0bafe766828b566a283a1a1e3f230f34721b8b07
|
stable-check/src/main.rs
|
rust
|
apache-2.0
|
Add license to stable check
so that this passes tidy on rust master
|
use std::error::Error;
use std::env;
use std::fs;
use std::fs::File;
use std::io::prelude::*;
use std::path::Path;
fn main() {
let arg = env::args().nth(1).unwrap_or_else(|| {
println!("Please pass a src directory as the first argument");
std::process::exit(1);
});
match check_directory(&Path::new(&arg)) {
Ok(()) => println!("passed!"),
Err(e) => {
println!("Error: {}", e);
std::process::exit(1);
}
}
}
fn check_directory(dir: &Path) -> Result<(), Box<Error>> {
for entry in fs::read_dir(dir)? {
let entry = entry?;
let path = entry.path();
if path.is_dir() {
continue;
}
let mut file = File::open(&path)?;
let mut contents = String::new();
file.read_to_string(&mut contents)?;
if contents.contains("#![feature") {
// attributes.md contains this and it is legitimate
if !contents.contains("#![feature(feature1, feature2, feature3)]") {
return Err(From::from(format!("Feature flag found in {:?}", path)));
}
}
}
Ok(())
}
|
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::error::Error;
use std::env;
use std::fs;
use std::fs::File;
use std::io::prelude::*;
use std::path::Path;
fn main() {
let arg = env::args().nth(1).unwrap_or_else(|| {
println!("Please pass a src directory as the first argument");
std::process::exit(1);
});
match check_directory(&Path::new(&arg)) {
Ok(()) => println!("passed!"),
Err(e) => {
println!("Error: {}", e);
std::process::exit(1);
}
}
}
fn check_directory(dir: &Path) -> Result<(), Box<Error>> {
for entry in fs::read_dir(dir)? {
let entry = entry?;
let path = entry.path();
if path.is_dir() {
continue;
}
let mut file = File::open(&path)?;
let mut contents = String::new();
file.read_to_string(&mut contents)?;
if contents.contains("#![feature") {
// attributes.md contains this and it is legitimate
if !contents.contains("#![feature(feature1, feature2, feature3)]") {
return Err(From::from(format!("Feature flag found in {:?}", path)));
}
}
}
Ok(())
}
| 10
| 0
| 1
|
add_only
|
--- a/stable-check/src/main.rs
+++ b/stable-check/src/main.rs
@@ -1 +1,11 @@
+// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
use std::error::Error;
|
--- a/stable-check/src/main.rs
+++ b/stable-check/src/main.rs
@@ ... @@
+// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
use std::error::Error;
|
--- a/stable-check/src/main.rs
+++ b/stable-check/src/main.rs
@@ -1 +1,11 @@
ADD // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
ADD // file at the top-level directory of this distribution and at
ADD // http://rust-lang.org/COPYRIGHT.
ADD //
ADD // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
ADD // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
ADD // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
ADD // option. This file may not be copied, modified, or distributed
ADD // except according to those terms.
ADD
CON use std::error::Error;
|
<<<<<<< SEARCH
use std::error::Error;
use std::env;
=======
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::error::Error;
use std::env;
>>>>>>> REPLACE
|
jpaoletti/java-presentation-manager
|
89708d4e8ec6e82d59579a5f79b18d7fa8d6e30a
|
modules/jpm-core/src/main/java/jpaoletti/jpm/core/operations/SelectItemOperation.java
|
java
|
agpl-3.0
|
Select item dont check for operation existance
|
package jpaoletti.jpm.core.operations;
import java.util.List;
import jpaoletti.jpm.core.InstanceId;
import jpaoletti.jpm.core.PMContext;
import jpaoletti.jpm.core.PMException;
/**
*
* @author jpaoletti
*/
public class SelectItemOperation extends OperationCommandSupport {
public SelectItemOperation(String operationId) {
super(operationId);
}
public SelectItemOperation() {
super("selectitem");
}
@Override
protected void doExecute(PMContext ctx) throws PMException {
super.doExecute(ctx);
final String _item = (String) ctx.getParameter("idx");
if (_item != null) {
final InstanceId id = buildInstanceId(ctx.getEntity(), _item);
final List<InstanceId> selectedIndexes = ctx.getEntityContainer().getSelectedInstanceIds();
if (selectedIndexes.contains(id)) {
selectedIndexes.remove(id);
} else {
selectedIndexes.add(id);
}
}
}
@Override
protected boolean checkEntity() {
return true;
}
}
|
package jpaoletti.jpm.core.operations;
import java.util.List;
import jpaoletti.jpm.core.InstanceId;
import jpaoletti.jpm.core.PMContext;
import jpaoletti.jpm.core.PMException;
/**
*
* @author jpaoletti
*/
public class SelectItemOperation extends OperationCommandSupport {
public SelectItemOperation(String operationId) {
super(operationId);
}
public SelectItemOperation() {
super("selectitem");
}
@Override
protected void doExecute(PMContext ctx) throws PMException {
super.doExecute(ctx);
final String _item = (String) ctx.getParameter("idx");
if (_item != null) {
final InstanceId id = buildInstanceId(ctx.getEntity(), _item);
final List<InstanceId> selectedIndexes = ctx.getEntityContainer().getSelectedInstanceIds();
if (selectedIndexes.contains(id)) {
selectedIndexes.remove(id);
} else {
selectedIndexes.add(id);
}
}
}
@Override
protected boolean checkEntity() {
return true;
}
@Override
protected boolean checkOperation() {
return false;
}
}
| 5
| 0
| 1
|
add_only
|
--- a/modules/jpm-core/src/main/java/jpaoletti/jpm/core/operations/SelectItemOperation.java
+++ b/modules/jpm-core/src/main/java/jpaoletti/jpm/core/operations/SelectItemOperation.java
@@ -40,2 +40,7 @@
}
+
+ @Override
+ protected boolean checkOperation() {
+ return false;
+ }
}
|
--- a/modules/jpm-core/src/main/java/jpaoletti/jpm/core/operations/SelectItemOperation.java
+++ b/modules/jpm-core/src/main/java/jpaoletti/jpm/core/operations/SelectItemOperation.java
@@ ... @@
}
+
+ @Override
+ protected boolean checkOperation() {
+ return false;
+ }
}
|
--- a/modules/jpm-core/src/main/java/jpaoletti/jpm/core/operations/SelectItemOperation.java
+++ b/modules/jpm-core/src/main/java/jpaoletti/jpm/core/operations/SelectItemOperation.java
@@ -40,2 +40,7 @@
CON }
ADD
ADD @Override
ADD protected boolean checkOperation() {
ADD return false;
ADD }
CON }
|
<<<<<<< SEARCH
return true;
}
}
=======
return true;
}
@Override
protected boolean checkOperation() {
return false;
}
}
>>>>>>> REPLACE
|
regexident/cargo-modules
|
0c42d4958196c5ac870c174007a4f2c52b845535
|
src/graph/edge.rs
|
rust
|
mpl-2.0
|
Add methods for merging `Edge`s
wip 2
|
// 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 https://mozilla.org/MPL/2.0/.
use std::fmt;
#[derive(Copy, Clone, Hash, Eq, PartialEq, Debug)]
pub enum EdgeKind {
Uses,
Owns,
}
impl EdgeKind {
pub fn display_name(&self) -> &'static str {
match self {
Self::Uses => "uses",
Self::Owns => "owns",
}
}
}
impl fmt::Display for EdgeKind {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let name = match self {
Self::Uses => "Uses",
Self::Owns => "Owns",
};
write!(f, "{}", name)
}
}
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct Edge {
pub kind: EdgeKind,
}
|
// 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 https://mozilla.org/MPL/2.0/.
use std::fmt;
#[derive(Copy, Clone, Hash, Eq, PartialEq, Debug)]
pub enum EdgeKind {
Uses,
Owns,
}
impl EdgeKind {
pub fn display_name(&self) -> &'static str {
match self {
Self::Uses => "uses",
Self::Owns => "owns",
}
}
}
impl fmt::Display for EdgeKind {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let name = match self {
Self::Uses => "Uses",
Self::Owns => "Owns",
};
write!(f, "{}", name)
}
}
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct Edge {
pub kind: EdgeKind,
}
impl Edge {
pub fn merge_with(&mut self, other: &Edge) {
match (self.kind, other.kind) {
(EdgeKind::Uses, EdgeKind::Uses) => {
self.kind = EdgeKind::Uses;
}
(EdgeKind::Uses, EdgeKind::Owns)
| (EdgeKind::Owns, EdgeKind::Uses)
| (EdgeKind::Owns, EdgeKind::Owns) => {
self.kind = EdgeKind::Owns;
}
}
}
pub fn merged_with(&self, other: &Edge) -> Self {
let mut clone = self.clone();
clone.merge_with(other);
clone
}
}
| 21
| 0
| 1
|
add_only
|
--- a/src/graph/edge.rs
+++ b/src/graph/edge.rs
@@ -35 +35,22 @@
}
+
+impl Edge {
+ pub fn merge_with(&mut self, other: &Edge) {
+ match (self.kind, other.kind) {
+ (EdgeKind::Uses, EdgeKind::Uses) => {
+ self.kind = EdgeKind::Uses;
+ }
+ (EdgeKind::Uses, EdgeKind::Owns)
+ | (EdgeKind::Owns, EdgeKind::Uses)
+ | (EdgeKind::Owns, EdgeKind::Owns) => {
+ self.kind = EdgeKind::Owns;
+ }
+ }
+ }
+
+ pub fn merged_with(&self, other: &Edge) -> Self {
+ let mut clone = self.clone();
+ clone.merge_with(other);
+ clone
+ }
+}
|
--- a/src/graph/edge.rs
+++ b/src/graph/edge.rs
@@ ... @@
}
+
+impl Edge {
+ pub fn merge_with(&mut self, other: &Edge) {
+ match (self.kind, other.kind) {
+ (EdgeKind::Uses, EdgeKind::Uses) => {
+ self.kind = EdgeKind::Uses;
+ }
+ (EdgeKind::Uses, EdgeKind::Owns)
+ | (EdgeKind::Owns, EdgeKind::Uses)
+ | (EdgeKind::Owns, EdgeKind::Owns) => {
+ self.kind = EdgeKind::Owns;
+ }
+ }
+ }
+
+ pub fn merged_with(&self, other: &Edge) -> Self {
+ let mut clone = self.clone();
+ clone.merge_with(other);
+ clone
+ }
+}
|
--- a/src/graph/edge.rs
+++ b/src/graph/edge.rs
@@ -35 +35,22 @@
CON }
ADD
ADD impl Edge {
ADD pub fn merge_with(&mut self, other: &Edge) {
ADD match (self.kind, other.kind) {
ADD (EdgeKind::Uses, EdgeKind::Uses) => {
ADD self.kind = EdgeKind::Uses;
ADD }
ADD (EdgeKind::Uses, EdgeKind::Owns)
ADD | (EdgeKind::Owns, EdgeKind::Uses)
ADD | (EdgeKind::Owns, EdgeKind::Owns) => {
ADD self.kind = EdgeKind::Owns;
ADD }
ADD }
ADD }
ADD
ADD pub fn merged_with(&self, other: &Edge) -> Self {
ADD let mut clone = self.clone();
ADD clone.merge_with(other);
ADD clone
ADD }
ADD }
|
<<<<<<< SEARCH
pub kind: EdgeKind,
}
=======
pub kind: EdgeKind,
}
impl Edge {
pub fn merge_with(&mut self, other: &Edge) {
match (self.kind, other.kind) {
(EdgeKind::Uses, EdgeKind::Uses) => {
self.kind = EdgeKind::Uses;
}
(EdgeKind::Uses, EdgeKind::Owns)
| (EdgeKind::Owns, EdgeKind::Uses)
| (EdgeKind::Owns, EdgeKind::Owns) => {
self.kind = EdgeKind::Owns;
}
}
}
pub fn merged_with(&self, other: &Edge) -> Self {
let mut clone = self.clone();
clone.merge_with(other);
clone
}
}
>>>>>>> REPLACE
|
shiraji/find-pull-request
|
5060ef938f4f0cb880f288235391dc0c08be56c6
|
src/main/kotlin/com/github/shiraji/findpullrequest/FindPullRequestAction.kt
|
kotlin
|
apache-2.0
|
Add debug info. It may not work since there is no runtime dependancy
|
package com.github.shiraji.findpullrequest
import com.intellij.notification.Notification
import com.intellij.notification.NotificationType
import com.intellij.notification.Notifications
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.project.Project
import git4idea.repo.GitRepository
import org.jetbrains.plugins.github.util.GithubUtil
class FindPullRequestAction : AnAction() {
override fun actionPerformed(e: AnActionEvent) {
val eventData = calcData(e)
Notifications.Bus.notify(Notification("Plugin Importer+Exporter",
"Plugin Importer+Exporter",
"EventData Repo br: " + eventData?.repository?.branches
+ " " + eventData?.repository?.remotes,
NotificationType.INFORMATION))
}
private fun calcData(e : AnActionEvent): EventData? {
val project = e.getData(CommonDataKeys.PROJECT)
project ?: return null
val virtualFile = e.getData(CommonDataKeys.VIRTUAL_FILE)
virtualFile ?: return null
val document = FileDocumentManager.getInstance().getDocument(virtualFile)
document ?: return null
val repository = GithubUtil.getGitRepository(project, virtualFile)
repository ?: return null
return EventData(project, repository)
}
private data class EventData(val project: Project, val repository: GitRepository) {
}
}
|
package com.github.shiraji.findpullrequest
import com.intellij.notification.Notification
import com.intellij.notification.NotificationType
import com.intellij.notification.Notifications
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.project.Project
import git4idea.repo.GitRepository
import org.jetbrains.plugins.github.util.GithubUtil
class FindPullRequestAction : AnAction() {
override fun actionPerformed(e: AnActionEvent) {
val eventData = calcData(e)
val foo = eventData?.repository?.remotes?.joinToString {
it.pushUrls.toString() + "\n"
}
Notifications.Bus.notify(Notification("Plugin Importer+Exporter",
"Plugin Importer+Exporter",
"EventData: " + foo,
NotificationType.INFORMATION))
}
private fun calcData(e : AnActionEvent): EventData? {
val project = e.getData(CommonDataKeys.PROJECT)
project ?: return null
val virtualFile = e.getData(CommonDataKeys.VIRTUAL_FILE)
virtualFile ?: return null
val document = FileDocumentManager.getInstance().getDocument(virtualFile)
document ?: return null
val repository = GithubUtil.getGitRepository(project, virtualFile)
repository ?: return null
return EventData(project, repository)
}
private data class EventData(val project: Project, val repository: GitRepository) {
}
}
| 5
| 2
| 1
|
mixed
|
--- a/src/main/kotlin/com/github/shiraji/findpullrequest/FindPullRequestAction.kt
+++ b/src/main/kotlin/com/github/shiraji/findpullrequest/FindPullRequestAction.kt
@@ -18,6 +18,9 @@
+ val foo = eventData?.repository?.remotes?.joinToString {
+ it.pushUrls.toString() + "\n"
+ }
+
Notifications.Bus.notify(Notification("Plugin Importer+Exporter",
"Plugin Importer+Exporter",
- "EventData Repo br: " + eventData?.repository?.branches
- + " " + eventData?.repository?.remotes,
+ "EventData: " + foo,
NotificationType.INFORMATION))
|
--- a/src/main/kotlin/com/github/shiraji/findpullrequest/FindPullRequestAction.kt
+++ b/src/main/kotlin/com/github/shiraji/findpullrequest/FindPullRequestAction.kt
@@ ... @@
+ val foo = eventData?.repository?.remotes?.joinToString {
+ it.pushUrls.toString() + "\n"
+ }
+
Notifications.Bus.notify(Notification("Plugin Importer+Exporter",
"Plugin Importer+Exporter",
- "EventData Repo br: " + eventData?.repository?.branches
- + " " + eventData?.repository?.remotes,
+ "EventData: " + foo,
NotificationType.INFORMATION))
|
--- a/src/main/kotlin/com/github/shiraji/findpullrequest/FindPullRequestAction.kt
+++ b/src/main/kotlin/com/github/shiraji/findpullrequest/FindPullRequestAction.kt
@@ -18,6 +18,9 @@
CON
ADD val foo = eventData?.repository?.remotes?.joinToString {
ADD it.pushUrls.toString() + "\n"
ADD }
ADD
CON Notifications.Bus.notify(Notification("Plugin Importer+Exporter",
CON "Plugin Importer+Exporter",
DEL "EventData Repo br: " + eventData?.repository?.branches
DEL + " " + eventData?.repository?.remotes,
ADD "EventData: " + foo,
CON NotificationType.INFORMATION))
|
<<<<<<< SEARCH
val eventData = calcData(e)
Notifications.Bus.notify(Notification("Plugin Importer+Exporter",
"Plugin Importer+Exporter",
"EventData Repo br: " + eventData?.repository?.branches
+ " " + eventData?.repository?.remotes,
NotificationType.INFORMATION))
}
=======
val eventData = calcData(e)
val foo = eventData?.repository?.remotes?.joinToString {
it.pushUrls.toString() + "\n"
}
Notifications.Bus.notify(Notification("Plugin Importer+Exporter",
"Plugin Importer+Exporter",
"EventData: " + foo,
NotificationType.INFORMATION))
}
>>>>>>> REPLACE
|
vnadgir-ef/hal-dw
|
0952cdf1186d63d6a93591429d55515ef8801998
|
src/main/java/com/vnadgir/hal/HalApplication.java
|
java
|
mit
|
Add default DateTimeFormat to parse/format DateTimes in UTC (ISO8601)
|
package com.vnadgir.hal;
import com.theoryinpractise.halbuilder.api.RepresentationFactory;
import com.theoryinpractise.halbuilder.standard.StandardRepresentationFactory;
import com.vnadgir.hal.api.resources.TestSessionResource;
import com.vnadgir.hal.api.resources.TestSessionsClientResource;
import com.vnadgir.hal.api.resources.TestSessionsService;
import io.dropwizard.client.JerseyClientBuilder;
import io.dropwizard.setup.Environment;
import javax.ws.rs.client.Client;
public class HalApplication extends io.dropwizard.Application<HalConfiguration> {
@Override
public void run(HalConfiguration halConfiguration, Environment environment) throws Exception {
final Client client = new JerseyClientBuilder(environment)
.build(getName());
TestSessionsService testSessionsService = new TestSessionsService();
RepresentationFactory representationFactory = new StandardRepresentationFactory();
environment.jersey().register(new TestSessionsClientResource(client));
environment.jersey().register(new TestSessionResource(testSessionsService, representationFactory));
}
@Override
public String getName(){
return "hal-dw";
}
public static void main(String[] args) throws Exception {
new HalApplication().run(args);
}
}
|
package com.vnadgir.hal;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.util.ISO8601DateFormat;
import com.fasterxml.jackson.datatype.joda.JodaModule;
import com.fasterxml.jackson.datatype.joda.ser.DateTimeSerializer;
import com.theoryinpractise.halbuilder.api.RepresentationFactory;
import com.theoryinpractise.halbuilder.standard.StandardRepresentationFactory;
import com.vnadgir.hal.api.resources.TestSessionResource;
import com.vnadgir.hal.api.resources.TestSessionsClientResource;
import com.vnadgir.hal.api.resources.TestSessionsService;
import io.dropwizard.client.JerseyClientBuilder;
import io.dropwizard.setup.Environment;
import javax.ws.rs.client.Client;
import java.text.SimpleDateFormat;
public class HalApplication extends io.dropwizard.Application<HalConfiguration> {
@Override
public void run(HalConfiguration halConfiguration, Environment environment) throws Exception {
ObjectMapper objectMapper = environment.getObjectMapper();
objectMapper.registerModule(new JodaModule());
objectMapper.setDateFormat(new ISO8601DateFormat());
final Client client = new JerseyClientBuilder(environment)
.build(getName());
TestSessionsService testSessionsService = new TestSessionsService();
RepresentationFactory representationFactory = new StandardRepresentationFactory();
environment.jersey().register(new TestSessionsClientResource(client));
environment.jersey().register(new TestSessionResource(testSessionsService, representationFactory));
}
@Override
public String getName(){
return "hal-dw";
}
public static void main(String[] args) throws Exception {
new HalApplication().run(args);
}
}
| 9
| 0
| 3
|
add_only
|
--- a/src/main/java/com/vnadgir/hal/HalApplication.java
+++ b/src/main/java/com/vnadgir/hal/HalApplication.java
@@ -2,2 +2,6 @@
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.util.ISO8601DateFormat;
+import com.fasterxml.jackson.datatype.joda.JodaModule;
+import com.fasterxml.jackson.datatype.joda.ser.DateTimeSerializer;
import com.theoryinpractise.halbuilder.api.RepresentationFactory;
@@ -11,2 +15,3 @@
import javax.ws.rs.client.Client;
+import java.text.SimpleDateFormat;
@@ -16,2 +21,6 @@
public void run(HalConfiguration halConfiguration, Environment environment) throws Exception {
+ ObjectMapper objectMapper = environment.getObjectMapper();
+ objectMapper.registerModule(new JodaModule());
+ objectMapper.setDateFormat(new ISO8601DateFormat());
+
final Client client = new JerseyClientBuilder(environment)
|
--- a/src/main/java/com/vnadgir/hal/HalApplication.java
+++ b/src/main/java/com/vnadgir/hal/HalApplication.java
@@ ... @@
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.util.ISO8601DateFormat;
+import com.fasterxml.jackson.datatype.joda.JodaModule;
+import com.fasterxml.jackson.datatype.joda.ser.DateTimeSerializer;
import com.theoryinpractise.halbuilder.api.RepresentationFactory;
@@ ... @@
import javax.ws.rs.client.Client;
+import java.text.SimpleDateFormat;
@@ ... @@
public void run(HalConfiguration halConfiguration, Environment environment) throws Exception {
+ ObjectMapper objectMapper = environment.getObjectMapper();
+ objectMapper.registerModule(new JodaModule());
+ objectMapper.setDateFormat(new ISO8601DateFormat());
+
final Client client = new JerseyClientBuilder(environment)
|
--- a/src/main/java/com/vnadgir/hal/HalApplication.java
+++ b/src/main/java/com/vnadgir/hal/HalApplication.java
@@ -2,2 +2,6 @@
CON
ADD import com.fasterxml.jackson.databind.ObjectMapper;
ADD import com.fasterxml.jackson.databind.util.ISO8601DateFormat;
ADD import com.fasterxml.jackson.datatype.joda.JodaModule;
ADD import com.fasterxml.jackson.datatype.joda.ser.DateTimeSerializer;
CON import com.theoryinpractise.halbuilder.api.RepresentationFactory;
@@ -11,2 +15,3 @@
CON import javax.ws.rs.client.Client;
ADD import java.text.SimpleDateFormat;
CON
@@ -16,2 +21,6 @@
CON public void run(HalConfiguration halConfiguration, Environment environment) throws Exception {
ADD ObjectMapper objectMapper = environment.getObjectMapper();
ADD objectMapper.registerModule(new JodaModule());
ADD objectMapper.setDateFormat(new ISO8601DateFormat());
ADD
CON final Client client = new JerseyClientBuilder(environment)
|
<<<<<<< SEARCH
package com.vnadgir.hal;
import com.theoryinpractise.halbuilder.api.RepresentationFactory;
import com.theoryinpractise.halbuilder.standard.StandardRepresentationFactory;
=======
package com.vnadgir.hal;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.util.ISO8601DateFormat;
import com.fasterxml.jackson.datatype.joda.JodaModule;
import com.fasterxml.jackson.datatype.joda.ser.DateTimeSerializer;
import com.theoryinpractise.halbuilder.api.RepresentationFactory;
import com.theoryinpractise.halbuilder.standard.StandardRepresentationFactory;
>>>>>>> REPLACE
<<<<<<< SEARCH
import javax.ws.rs.client.Client;
public class HalApplication extends io.dropwizard.Application<HalConfiguration> {
@Override
public void run(HalConfiguration halConfiguration, Environment environment) throws Exception {
final Client client = new JerseyClientBuilder(environment)
.build(getName());
=======
import javax.ws.rs.client.Client;
import java.text.SimpleDateFormat;
public class HalApplication extends io.dropwizard.Application<HalConfiguration> {
@Override
public void run(HalConfiguration halConfiguration, Environment environment) throws Exception {
ObjectMapper objectMapper = environment.getObjectMapper();
objectMapper.registerModule(new JodaModule());
objectMapper.setDateFormat(new ISO8601DateFormat());
final Client client = new JerseyClientBuilder(environment)
.build(getName());
>>>>>>> REPLACE
|
astefanutti/camel-cdi
|
1b4eecb75d2f2c84b5dd129d753de5fa3c99241c
|
samples/metrics/src/main/java/org/apache/camel/cdi/sample/metrics/UnreliableService.java
|
java
|
apache-2.0
|
Add TODO when PAX CDI will support global interceptors
|
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.apache.camel.cdi.sample.metrics;
import com.codahale.metrics.Meter;
import org.apache.camel.Exchange;
import org.apache.camel.RuntimeExchangeException;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
@ApplicationScoped
public class UnreliableService {
@Inject
private Meter attempt;
public void unreliable(Exchange exchange) {
attempt.mark();
if (Math.random() < 0.5)
throw new RuntimeExchangeException("Random failure", exchange);
}
}
|
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.apache.camel.cdi.sample.metrics;
import com.codahale.metrics.Meter;
import org.apache.camel.Exchange;
import org.apache.camel.RuntimeExchangeException;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
@ApplicationScoped
public class UnreliableService {
@Inject
private Meter attempt;
//@Metered
// TODO: to activate when global interceptors are supported in PAX CDI
public void attempt(Exchange exchange) {
attempt.mark();
if (Math.random() < 0.5)
throw new RuntimeExchangeException("Random failure", exchange);
}
}
| 3
| 1
| 1
|
mixed
|
--- a/samples/metrics/src/main/java/org/apache/camel/cdi/sample/metrics/UnreliableService.java
+++ b/samples/metrics/src/main/java/org/apache/camel/cdi/sample/metrics/UnreliableService.java
@@ -32,3 +32,5 @@
- public void unreliable(Exchange exchange) {
+ //@Metered
+ // TODO: to activate when global interceptors are supported in PAX CDI
+ public void attempt(Exchange exchange) {
attempt.mark();
|
--- a/samples/metrics/src/main/java/org/apache/camel/cdi/sample/metrics/UnreliableService.java
+++ b/samples/metrics/src/main/java/org/apache/camel/cdi/sample/metrics/UnreliableService.java
@@ ... @@
- public void unreliable(Exchange exchange) {
+ //@Metered
+ // TODO: to activate when global interceptors are supported in PAX CDI
+ public void attempt(Exchange exchange) {
attempt.mark();
|
--- a/samples/metrics/src/main/java/org/apache/camel/cdi/sample/metrics/UnreliableService.java
+++ b/samples/metrics/src/main/java/org/apache/camel/cdi/sample/metrics/UnreliableService.java
@@ -32,3 +32,5 @@
CON
DEL public void unreliable(Exchange exchange) {
ADD //@Metered
ADD // TODO: to activate when global interceptors are supported in PAX CDI
ADD public void attempt(Exchange exchange) {
CON attempt.mark();
|
<<<<<<< SEARCH
private Meter attempt;
public void unreliable(Exchange exchange) {
attempt.mark();
=======
private Meter attempt;
//@Metered
// TODO: to activate when global interceptors are supported in PAX CDI
public void attempt(Exchange exchange) {
attempt.mark();
>>>>>>> REPLACE
|
attilahorvath/exercism-rust
|
605c324df257b7b79e43027fe457885355a101d5
|
saddle-points/src/lib.rs
|
rust
|
mit
|
Improve solution for Saddle Points
|
fn is_saddle_point(input: &[Vec<u64>], px: usize, py: usize) -> bool {
let value = input[py][px];
for y in 0..input.len() {
if input[y][px] < value {
return false;
}
}
for x in 0..input[0].len() {
if input[py][x] > value {
return false;
}
}
true
}
pub fn find_saddle_points(input: &[Vec<u64>]) -> Vec<(usize, usize)> {
let mut saddle_points = Vec::new();
for y in 0..input.len() {
for x in 0..input[y].len() {
if is_saddle_point(input, x, y) {
saddle_points.push((y, x));
}
}
}
saddle_points
}
|
pub fn find_saddle_points(input: &[Vec<u64>]) -> Vec<(usize, usize)> {
let mut row_max = vec![Vec::new(); input.len()];
let mut col_min: Vec<Vec<(usize, u64)>> = vec![Vec::new(); input[0].len()];
for (row, values) in input.iter().enumerate() {
for (col, &value) in values.iter().enumerate() {
let mut c = &mut col_min[col];
if c.is_empty() || c[0].1 == value {
c.push((row, value));
} else if c[0].1 > value {
c.clear();
c.push((row, value));
}
let mut r = &mut row_max[row];
if r.is_empty() || r[0] == value {
r.push(value);
} else if r[0] < value {
r.clear();
r.push(value);
}
}
}
col_min
.iter()
.enumerate()
.fold(Vec::new(), |mut points, (col, values)| {
let mut col_points = values
.iter()
.filter(|c| row_max[c.0].contains(&c.1))
.map(|c| (c.0, col))
.collect();
points.append(&mut col_points);
points
})
}
| 31
| 22
| 2
|
mixed
|
--- a/saddle-points/src/lib.rs
+++ b/saddle-points/src/lib.rs
@@ -1,26 +1,23 @@
-fn is_saddle_point(input: &[Vec<u64>], px: usize, py: usize) -> bool {
- let value = input[py][px];
+pub fn find_saddle_points(input: &[Vec<u64>]) -> Vec<(usize, usize)> {
+ let mut row_max = vec![Vec::new(); input.len()];
+ let mut col_min: Vec<Vec<(usize, u64)>> = vec![Vec::new(); input[0].len()];
- for y in 0..input.len() {
- if input[y][px] < value {
- return false;
- }
- }
+ for (row, values) in input.iter().enumerate() {
+ for (col, &value) in values.iter().enumerate() {
+ let mut c = &mut col_min[col];
- for x in 0..input[0].len() {
- if input[py][x] > value {
- return false;
- }
- }
+ if c.is_empty() || c[0].1 == value {
+ c.push((row, value));
+ } else if c[0].1 > value {
+ c.clear();
+ c.push((row, value));
+ }
- true
-}
+ let mut r = &mut row_max[row];
-pub fn find_saddle_points(input: &[Vec<u64>]) -> Vec<(usize, usize)> {
- let mut saddle_points = Vec::new();
-
- for y in 0..input.len() {
- for x in 0..input[y].len() {
- if is_saddle_point(input, x, y) {
- saddle_points.push((y, x));
+ if r.is_empty() || r[0] == value {
+ r.push(value);
+ } else if r[0] < value {
+ r.clear();
+ r.push(value);
}
@@ -29,3 +26,15 @@
- saddle_points
+ col_min
+ .iter()
+ .enumerate()
+ .fold(Vec::new(), |mut points, (col, values)| {
+ let mut col_points = values
+ .iter()
+ .filter(|c| row_max[c.0].contains(&c.1))
+ .map(|c| (c.0, col))
+ .collect();
+
+ points.append(&mut col_points);
+ points
+ })
}
|
--- a/saddle-points/src/lib.rs
+++ b/saddle-points/src/lib.rs
@@ ... @@
-fn is_saddle_point(input: &[Vec<u64>], px: usize, py: usize) -> bool {
- let value = input[py][px];
+pub fn find_saddle_points(input: &[Vec<u64>]) -> Vec<(usize, usize)> {
+ let mut row_max = vec![Vec::new(); input.len()];
+ let mut col_min: Vec<Vec<(usize, u64)>> = vec![Vec::new(); input[0].len()];
- for y in 0..input.len() {
- if input[y][px] < value {
- return false;
- }
- }
+ for (row, values) in input.iter().enumerate() {
+ for (col, &value) in values.iter().enumerate() {
+ let mut c = &mut col_min[col];
- for x in 0..input[0].len() {
- if input[py][x] > value {
- return false;
- }
- }
+ if c.is_empty() || c[0].1 == value {
+ c.push((row, value));
+ } else if c[0].1 > value {
+ c.clear();
+ c.push((row, value));
+ }
- true
-}
+ let mut r = &mut row_max[row];
-pub fn find_saddle_points(input: &[Vec<u64>]) -> Vec<(usize, usize)> {
- let mut saddle_points = Vec::new();
-
- for y in 0..input.len() {
- for x in 0..input[y].len() {
- if is_saddle_point(input, x, y) {
- saddle_points.push((y, x));
+ if r.is_empty() || r[0] == value {
+ r.push(value);
+ } else if r[0] < value {
+ r.clear();
+ r.push(value);
}
@@ ... @@
- saddle_points
+ col_min
+ .iter()
+ .enumerate()
+ .fold(Vec::new(), |mut points, (col, values)| {
+ let mut col_points = values
+ .iter()
+ .filter(|c| row_max[c.0].contains(&c.1))
+ .map(|c| (c.0, col))
+ .collect();
+
+ points.append(&mut col_points);
+ points
+ })
}
|
--- a/saddle-points/src/lib.rs
+++ b/saddle-points/src/lib.rs
@@ -1,26 +1,23 @@
DEL fn is_saddle_point(input: &[Vec<u64>], px: usize, py: usize) -> bool {
DEL let value = input[py][px];
ADD pub fn find_saddle_points(input: &[Vec<u64>]) -> Vec<(usize, usize)> {
ADD let mut row_max = vec![Vec::new(); input.len()];
ADD let mut col_min: Vec<Vec<(usize, u64)>> = vec![Vec::new(); input[0].len()];
CON
DEL for y in 0..input.len() {
DEL if input[y][px] < value {
DEL return false;
DEL }
DEL }
ADD for (row, values) in input.iter().enumerate() {
ADD for (col, &value) in values.iter().enumerate() {
ADD let mut c = &mut col_min[col];
CON
DEL for x in 0..input[0].len() {
DEL if input[py][x] > value {
DEL return false;
DEL }
DEL }
ADD if c.is_empty() || c[0].1 == value {
ADD c.push((row, value));
ADD } else if c[0].1 > value {
ADD c.clear();
ADD c.push((row, value));
ADD }
CON
DEL true
DEL }
ADD let mut r = &mut row_max[row];
CON
DEL pub fn find_saddle_points(input: &[Vec<u64>]) -> Vec<(usize, usize)> {
DEL let mut saddle_points = Vec::new();
DEL
DEL for y in 0..input.len() {
DEL for x in 0..input[y].len() {
DEL if is_saddle_point(input, x, y) {
DEL saddle_points.push((y, x));
ADD if r.is_empty() || r[0] == value {
ADD r.push(value);
ADD } else if r[0] < value {
ADD r.clear();
ADD r.push(value);
CON }
@@ -29,3 +26,15 @@
CON
DEL saddle_points
ADD col_min
ADD .iter()
ADD .enumerate()
ADD .fold(Vec::new(), |mut points, (col, values)| {
ADD let mut col_points = values
ADD .iter()
ADD .filter(|c| row_max[c.0].contains(&c.1))
ADD .map(|c| (c.0, col))
ADD .collect();
ADD
ADD points.append(&mut col_points);
ADD points
ADD })
CON }
|
<<<<<<< SEARCH
fn is_saddle_point(input: &[Vec<u64>], px: usize, py: usize) -> bool {
let value = input[py][px];
for y in 0..input.len() {
if input[y][px] < value {
return false;
}
}
for x in 0..input[0].len() {
if input[py][x] > value {
return false;
}
}
true
}
pub fn find_saddle_points(input: &[Vec<u64>]) -> Vec<(usize, usize)> {
let mut saddle_points = Vec::new();
for y in 0..input.len() {
for x in 0..input[y].len() {
if is_saddle_point(input, x, y) {
saddle_points.push((y, x));
}
}
}
saddle_points
}
=======
pub fn find_saddle_points(input: &[Vec<u64>]) -> Vec<(usize, usize)> {
let mut row_max = vec![Vec::new(); input.len()];
let mut col_min: Vec<Vec<(usize, u64)>> = vec![Vec::new(); input[0].len()];
for (row, values) in input.iter().enumerate() {
for (col, &value) in values.iter().enumerate() {
let mut c = &mut col_min[col];
if c.is_empty() || c[0].1 == value {
c.push((row, value));
} else if c[0].1 > value {
c.clear();
c.push((row, value));
}
let mut r = &mut row_max[row];
if r.is_empty() || r[0] == value {
r.push(value);
} else if r[0] < value {
r.clear();
r.push(value);
}
}
}
col_min
.iter()
.enumerate()
.fold(Vec::new(), |mut points, (col, values)| {
let mut col_points = values
.iter()
.filter(|c| row_max[c.0].contains(&c.1))
.map(|c| (c.0, col))
.collect();
points.append(&mut col_points);
points
})
}
>>>>>>> REPLACE
|
AjayMT/cheese
|
f2e9e251f20cc23a34f5ed569e81674fc4b72abd
|
test/server-cdp.js
|
javascript
|
mit
|
Use 'forceNew' instead of 'force new connection'
|
/* global require, describe, before, after, it */
var io = require('socket.io-client');
var should = require('should');
describe('server-cdp', function () {
var server = require('../lib/server.js');
before(function (done) {
server.start(3000, '', {}, done);
});
it('should send init message on connection', function (done) {
var socket = io('http://localhost:3000', { 'force new connection': true });
socket.on('connect', function () {
socket.on('init', function () { done(); });
});
});
it('should send diffs to other clients', function (done) {
var s1 = io('http://localhost:3000', { 'force new connection': true });
var s2 = io('http://localhost:3000', { 'force new connection': true });
s1.on('connect', function () {
s1.on('init', function () {
s1.emit('msg', { hello: 'world' });
});
});
s2.on('connect', function () {
s2.on('msg', function (data) {
data.should.have.property('hello', 'world');
done();
});
});
});
after(server.kill);
});
|
/* global require, describe, before, after, it */
var io = require('socket.io-client');
var should = require('should');
describe('server-cdp', function () {
var server = require('../lib/server.js');
before(function (done) {
server.start(3000, '', {}, done);
});
it('should send init message on connection', function (done) {
var socket = io('http://localhost:3000', { 'forceNew': true });
socket.on('connect', function () {
socket.on('init', function () { done(); });
});
});
it('should send diffs to other clients', function (done) {
var s1 = io('http://localhost:3000', { 'forceNew': true });
var s2 = io('http://localhost:3000', { 'forceNew': true });
s1.on('connect', function () {
s1.on('init', function () {
s1.emit('msg', { hello: 'world' });
});
});
s2.on('connect', function () {
s2.on('msg', function (data) {
data.should.have.property('hello', 'world');
done();
});
});
});
after(server.kill);
});
| 3
| 3
| 2
|
mixed
|
--- a/test/server-cdp.js
+++ b/test/server-cdp.js
@@ -14,3 +14,3 @@
it('should send init message on connection', function (done) {
- var socket = io('http://localhost:3000', { 'force new connection': true });
+ var socket = io('http://localhost:3000', { 'forceNew': true });
socket.on('connect', function () {
@@ -21,4 +21,4 @@
it('should send diffs to other clients', function (done) {
- var s1 = io('http://localhost:3000', { 'force new connection': true });
- var s2 = io('http://localhost:3000', { 'force new connection': true });
+ var s1 = io('http://localhost:3000', { 'forceNew': true });
+ var s2 = io('http://localhost:3000', { 'forceNew': true });
|
--- a/test/server-cdp.js
+++ b/test/server-cdp.js
@@ ... @@
it('should send init message on connection', function (done) {
- var socket = io('http://localhost:3000', { 'force new connection': true });
+ var socket = io('http://localhost:3000', { 'forceNew': true });
socket.on('connect', function () {
@@ ... @@
it('should send diffs to other clients', function (done) {
- var s1 = io('http://localhost:3000', { 'force new connection': true });
- var s2 = io('http://localhost:3000', { 'force new connection': true });
+ var s1 = io('http://localhost:3000', { 'forceNew': true });
+ var s2 = io('http://localhost:3000', { 'forceNew': true });
|
--- a/test/server-cdp.js
+++ b/test/server-cdp.js
@@ -14,3 +14,3 @@
CON it('should send init message on connection', function (done) {
DEL var socket = io('http://localhost:3000', { 'force new connection': true });
ADD var socket = io('http://localhost:3000', { 'forceNew': true });
CON socket.on('connect', function () {
@@ -21,4 +21,4 @@
CON it('should send diffs to other clients', function (done) {
DEL var s1 = io('http://localhost:3000', { 'force new connection': true });
DEL var s2 = io('http://localhost:3000', { 'force new connection': true });
ADD var s1 = io('http://localhost:3000', { 'forceNew': true });
ADD var s2 = io('http://localhost:3000', { 'forceNew': true });
CON
|
<<<<<<< SEARCH
it('should send init message on connection', function (done) {
var socket = io('http://localhost:3000', { 'force new connection': true });
socket.on('connect', function () {
socket.on('init', function () { done(); });
=======
it('should send init message on connection', function (done) {
var socket = io('http://localhost:3000', { 'forceNew': true });
socket.on('connect', function () {
socket.on('init', function () { done(); });
>>>>>>> REPLACE
<<<<<<< SEARCH
it('should send diffs to other clients', function (done) {
var s1 = io('http://localhost:3000', { 'force new connection': true });
var s2 = io('http://localhost:3000', { 'force new connection': true });
s1.on('connect', function () {
=======
it('should send diffs to other clients', function (done) {
var s1 = io('http://localhost:3000', { 'forceNew': true });
var s2 = io('http://localhost:3000', { 'forceNew': true });
s1.on('connect', function () {
>>>>>>> REPLACE
|
ConnyOnny/Cursive-Break
|
db9df3dfc93b6486bf8ba1199a12e7fefc7524cd
|
src/utils/reader.rs
|
rust
|
mit
|
Add `deconstruct` method to `ProgressReader`
|
use std::io::{self, Read};
use views::Counter;
/// Wrapper around a `Read` that reports the progress made.
///
/// Used to monitor a file downloading or other slow IO task
/// in a progress bar.
pub struct ProgressReader<R: Read> {
reader: R,
counter: Counter,
}
impl<R: Read> ProgressReader<R> {
/// Creates a new `ProgressReader` around `reader`.
///
/// `counter` will be updated with the number of bytes read.
///
/// You should make sure the progress bar knows how
/// many bytes should be received.
pub fn new(counter: Counter, reader: R) -> Self {
ProgressReader {
reader: reader,
counter: counter,
}
}
}
impl<R: Read> Read for ProgressReader<R> {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
let result = try!(self.reader.read(buf));
self.counter.tick(result);
Ok(result)
}
}
|
use std::io::{self, Read};
use views::Counter;
/// Wrapper around a `Read` that reports the progress made.
///
/// Used to monitor a file downloading or other slow IO task
/// in a progress bar.
pub struct ProgressReader<R: Read> {
reader: R,
counter: Counter,
}
impl<R: Read> ProgressReader<R> {
/// Creates a new `ProgressReader` around `reader`.
///
/// `counter` will be updated with the number of bytes read.
///
/// You should make sure the progress bar knows how
/// many bytes should be received.
pub fn new(counter: Counter, reader: R) -> Self {
ProgressReader {
reader: reader,
counter: counter,
}
}
/// Unwraps this `ProgressReader`, returning the reader and counter.
pub fn deconstruct(self) -> (R, Counter) {
(self.reader, self.counter)
}
}
impl<R: Read> Read for ProgressReader<R> {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
let result = try!(self.reader.read(buf));
self.counter.tick(result);
Ok(result)
}
}
| 5
| 0
| 1
|
add_only
|
--- a/src/utils/reader.rs
+++ b/src/utils/reader.rs
@@ -27,2 +27,7 @@
}
+
+ /// Unwraps this `ProgressReader`, returning the reader and counter.
+ pub fn deconstruct(self) -> (R, Counter) {
+ (self.reader, self.counter)
+ }
}
|
--- a/src/utils/reader.rs
+++ b/src/utils/reader.rs
@@ ... @@
}
+
+ /// Unwraps this `ProgressReader`, returning the reader and counter.
+ pub fn deconstruct(self) -> (R, Counter) {
+ (self.reader, self.counter)
+ }
}
|
--- a/src/utils/reader.rs
+++ b/src/utils/reader.rs
@@ -27,2 +27,7 @@
CON }
ADD
ADD /// Unwraps this `ProgressReader`, returning the reader and counter.
ADD pub fn deconstruct(self) -> (R, Counter) {
ADD (self.reader, self.counter)
ADD }
CON }
|
<<<<<<< SEARCH
}
}
}
=======
}
}
/// Unwraps this `ProgressReader`, returning the reader and counter.
pub fn deconstruct(self) -> (R, Counter) {
(self.reader, self.counter)
}
}
>>>>>>> REPLACE
|
lark-parser/lark
|
d28eba4f9a62ca96bbfe5069f43864a6a71bea71
|
examples/advanced/extend_python.py
|
python
|
mit
|
Fix typos in comment of example code
|
"""
Extend the Python Grammar
==============================
This example demonstrates how to use the `%extend` statement,
to add new syntax to the example Python grammar.
"""
from lark.lark import Lark
from python_parser import PythonIndenter
GRAMMAR = r"""
%import .python3 (compound_stmt, single_input, file_input, eval_input, test, suite, _NEWLINE, _INDENT, _DEDENT, COMMENT)
%extend compound_stmt: match_stmt
match_stmt: "match" test ":" cases
cases: _NEWLINE _INDENT case+ _DEDENT
case: "case" test ":" suite // test is not quite correct.
%ignore /[\t \f]+/ // WS
%ignore /\\[\t \f]*\r?\n/ // LINE_CONT
%ignore COMMENT
"""
parser = Lark(GRAMMAR, parser='lalr', start=['single_input', 'file_input', 'eval_input'], postlex=PythonIndenter())
tree = parser.parse(r"""
def name(n):
match n:
case 1:
print("one")
case 2:
print("two")
case _:
print("number is too big")
""", start='file_input')
# Remove the 'python3__' prefix that was add to the implicitely imported rules.
for t in tree.iter_subtrees():
t.data = t.data.rsplit('__', 1)[-1]
print(tree.pretty())
|
"""
Extend the Python Grammar
==============================
This example demonstrates how to use the `%extend` statement,
to add new syntax to the example Python grammar.
"""
from lark.lark import Lark
from python_parser import PythonIndenter
GRAMMAR = r"""
%import .python3 (compound_stmt, single_input, file_input, eval_input, test, suite, _NEWLINE, _INDENT, _DEDENT, COMMENT)
%extend compound_stmt: match_stmt
match_stmt: "match" test ":" cases
cases: _NEWLINE _INDENT case+ _DEDENT
case: "case" test ":" suite // test is not quite correct.
%ignore /[\t \f]+/ // WS
%ignore /\\[\t \f]*\r?\n/ // LINE_CONT
%ignore COMMENT
"""
parser = Lark(GRAMMAR, parser='lalr', start=['single_input', 'file_input', 'eval_input'], postlex=PythonIndenter())
tree = parser.parse(r"""
def name(n):
match n:
case 1:
print("one")
case 2:
print("two")
case _:
print("number is too big")
""", start='file_input')
# Remove the 'python3__' prefix that was added to the implicitly imported rules.
for t in tree.iter_subtrees():
t.data = t.data.rsplit('__', 1)[-1]
print(tree.pretty())
| 1
| 1
| 1
|
mixed
|
--- a/examples/advanced/extend_python.py
+++ b/examples/advanced/extend_python.py
@@ -41,3 +41,3 @@
-# Remove the 'python3__' prefix that was add to the implicitely imported rules.
+# Remove the 'python3__' prefix that was added to the implicitly imported rules.
for t in tree.iter_subtrees():
|
--- a/examples/advanced/extend_python.py
+++ b/examples/advanced/extend_python.py
@@ ... @@
-# Remove the 'python3__' prefix that was add to the implicitely imported rules.
+# Remove the 'python3__' prefix that was added to the implicitly imported rules.
for t in tree.iter_subtrees():
|
--- a/examples/advanced/extend_python.py
+++ b/examples/advanced/extend_python.py
@@ -41,3 +41,3 @@
CON
DEL # Remove the 'python3__' prefix that was add to the implicitely imported rules.
ADD # Remove the 'python3__' prefix that was added to the implicitly imported rules.
CON for t in tree.iter_subtrees():
|
<<<<<<< SEARCH
""", start='file_input')
# Remove the 'python3__' prefix that was add to the implicitely imported rules.
for t in tree.iter_subtrees():
t.data = t.data.rsplit('__', 1)[-1]
=======
""", start='file_input')
# Remove the 'python3__' prefix that was added to the implicitly imported rules.
for t in tree.iter_subtrees():
t.data = t.data.rsplit('__', 1)[-1]
>>>>>>> REPLACE
|
nodeca/nodeca.core
|
49e7f5687dd4376465f242498ad89687db6d8e8b
|
client/common/init.js
|
javascript
|
mit
|
Revert "Prevent link processing for dropdowns"
This reverts commit 2cb937a4405627c94c05c391dd610b85ba7e1cad.
|
'use strict';
/**
* client
**/
/**
* client.common
**/
/*global $, _, nodeca, window, document*/
/**
* client.common.init()
*
* Assigns all necessary event listeners and handlers.
*
*
* ##### Example
*
* nodeca.client.common.init();
**/
module.exports = function () {
nodeca.io.init();
$(function () {
// Bootstrap.Collapse calls e.preventDefault() only when there's no
// data-target attribute. We don't want URL to be changed, so we are
// forcing prevention of default behavior.
$('body').on('click.collapse.data-api', '[data-toggle=collapse]', function ( e ) {
e.preventDefault();
});
// Bootstrap.Dropdown don't calls e.preventDefault() by default
$('body').on('click.dropdown.data-api', '[data-toggle=dropdown]', function ( e ) {
e.preventDefault();
});
//
// Observe quicksearch focus to tweak icon style
//
$('.navbar-search .search-query')
.focus(function (){ $(this).next('div').addClass('focused'); })
.blur(function (){ $(this).next('div').removeClass('focused'); });
});
// history intercepts clicks on all `a` elements,
// so we initialize it as later as possible to have
// "lowest" priority of handlers
nodeca.client.common.init.history();
};
|
'use strict';
/**
* client
**/
/**
* client.common
**/
/*global $, _, nodeca, window, document*/
/**
* client.common.init()
*
* Assigns all necessary event listeners and handlers.
*
*
* ##### Example
*
* nodeca.client.common.init();
**/
module.exports = function () {
nodeca.io.init();
$(function () {
// Bootstrap.Collapse calls e.preventDefault() only when there's no
// data-target attribute. We don't want URL to be changed, so we are
// forcing prevention of default behavior.
$('body').on('click.collapse.data-api', '[data-toggle=collapse]', function ( e ) {
e.preventDefault();
});
//
// Observe quicksearch focus to tweak icon style
//
$('.navbar-search .search-query')
.focus(function (){ $(this).next('div').addClass('focused'); })
.blur(function (){ $(this).next('div').removeClass('focused'); });
});
// history intercepts clicks on all `a` elements,
// so we initialize it as later as possible to have
// "lowest" priority of handlers
nodeca.client.common.init.history();
};
| 0
| 5
| 1
|
del_only
|
--- a/client/common/init.js
+++ b/client/common/init.js
@@ -37,7 +37,2 @@
- // Bootstrap.Dropdown don't calls e.preventDefault() by default
- $('body').on('click.dropdown.data-api', '[data-toggle=dropdown]', function ( e ) {
- e.preventDefault();
- });
-
//
|
--- a/client/common/init.js
+++ b/client/common/init.js
@@ ... @@
- // Bootstrap.Dropdown don't calls e.preventDefault() by default
- $('body').on('click.dropdown.data-api', '[data-toggle=dropdown]', function ( e ) {
- e.preventDefault();
- });
-
//
|
--- a/client/common/init.js
+++ b/client/common/init.js
@@ -37,7 +37,2 @@
CON
DEL // Bootstrap.Dropdown don't calls e.preventDefault() by default
DEL $('body').on('click.dropdown.data-api', '[data-toggle=dropdown]', function ( e ) {
DEL e.preventDefault();
DEL });
DEL
CON //
|
<<<<<<< SEARCH
});
// Bootstrap.Dropdown don't calls e.preventDefault() by default
$('body').on('click.dropdown.data-api', '[data-toggle=dropdown]', function ( e ) {
e.preventDefault();
});
//
// Observe quicksearch focus to tweak icon style
=======
});
//
// Observe quicksearch focus to tweak icon style
>>>>>>> REPLACE
|
caskdata/cdap
|
a6f2ffd6070fe85c2950c2901a72b41c64739add
|
cdap-api/src/main/java/co/cask/cdap/api/procedure/ProcedureContext.java
|
java
|
apache-2.0
|
Fix deprecation tag to link to service instead of context.
|
/*
/*
* Copyright © 2014 Cask Data, Inc.
*
* 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 co.cask.cdap.api.procedure;
import co.cask.cdap.api.RuntimeContext;
import co.cask.cdap.api.ServiceDiscoverer;
import co.cask.cdap.api.data.DataSetContext;
/**
* This interface represents the Procedure context.
*
* @deprecated As of version 2.6.0, replaced by {@link co.cask.cdap.api.service.ServiceWorkerContext}
*/
@Deprecated
public interface ProcedureContext extends RuntimeContext, DataSetContext, ServiceDiscoverer {
/**
* @return The specification used to configure this {@link Procedure} instance.
*/
ProcedureSpecification getSpecification();
/**
* @return number of instances for the procedure.
*/
int getInstanceCount();
}
|
/*
/*
* Copyright © 2014 Cask Data, Inc.
*
* 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 co.cask.cdap.api.procedure;
import co.cask.cdap.api.RuntimeContext;
import co.cask.cdap.api.ServiceDiscoverer;
import co.cask.cdap.api.data.DataSetContext;
/**
* This interface represents the Procedure context.
*
* @deprecated As of version 2.6.0, with no direct replacement, see {@link co.cask.cdap.api.service.Service}
*/
@Deprecated
public interface ProcedureContext extends RuntimeContext, DataSetContext, ServiceDiscoverer {
/**
* @return The specification used to configure this {@link Procedure} instance.
*/
ProcedureSpecification getSpecification();
/**
* @return number of instances for the procedure.
*/
int getInstanceCount();
}
| 1
| 1
| 1
|
mixed
|
--- a/cdap-api/src/main/java/co/cask/cdap/api/procedure/ProcedureContext.java
+++ b/cdap-api/src/main/java/co/cask/cdap/api/procedure/ProcedureContext.java
@@ -26,3 +26,3 @@
*
- * @deprecated As of version 2.6.0, replaced by {@link co.cask.cdap.api.service.ServiceWorkerContext}
+ * @deprecated As of version 2.6.0, with no direct replacement, see {@link co.cask.cdap.api.service.Service}
*/
|
--- a/cdap-api/src/main/java/co/cask/cdap/api/procedure/ProcedureContext.java
+++ b/cdap-api/src/main/java/co/cask/cdap/api/procedure/ProcedureContext.java
@@ ... @@
*
- * @deprecated As of version 2.6.0, replaced by {@link co.cask.cdap.api.service.ServiceWorkerContext}
+ * @deprecated As of version 2.6.0, with no direct replacement, see {@link co.cask.cdap.api.service.Service}
*/
|
--- a/cdap-api/src/main/java/co/cask/cdap/api/procedure/ProcedureContext.java
+++ b/cdap-api/src/main/java/co/cask/cdap/api/procedure/ProcedureContext.java
@@ -26,3 +26,3 @@
CON *
DEL * @deprecated As of version 2.6.0, replaced by {@link co.cask.cdap.api.service.ServiceWorkerContext}
ADD * @deprecated As of version 2.6.0, with no direct replacement, see {@link co.cask.cdap.api.service.Service}
CON */
|
<<<<<<< SEARCH
* This interface represents the Procedure context.
*
* @deprecated As of version 2.6.0, replaced by {@link co.cask.cdap.api.service.ServiceWorkerContext}
*/
@Deprecated
=======
* This interface represents the Procedure context.
*
* @deprecated As of version 2.6.0, with no direct replacement, see {@link co.cask.cdap.api.service.Service}
*/
@Deprecated
>>>>>>> REPLACE
|
hudochenkov/postcss-sorting
|
e8084b0dcd51f6c4b5022c760ab359b8178ecfe2
|
__tests__/test.js
|
javascript
|
mit
|
Test clean-empty-lines with other *-empty-line-before option
|
'use strict';
test(
`Should do nothing if config is undefined`,
() => runTest('empty-lines-preserve')
);
|
'use strict';
test(
`Should do nothing if config is undefined`,
() => runTest('empty-lines-preserve')
);
groupTest([
{
description: 'Empty lines should be cleaned before any other empty-line-before option',
options: {
'at-rule-nested-empty-line-before': true,
'clean-empty-lines': true,
},
cases: [
{
fixture: `
a {
@mixin foo;
}
`,
expected: `
a {
@mixin foo;
}
`,
},
{
fixture: `
a {
@mixin foo;
}
`,
expected: `
a {
@mixin foo;
}
`,
},
],
},
]);
| 43
| 0
| 1
|
add_only
|
--- a/__tests__/test.js
+++ b/__tests__/test.js
@@ -6 +6,44 @@
);
+
+groupTest([
+ {
+ description: 'Empty lines should be cleaned before any other empty-line-before option',
+ options: {
+ 'at-rule-nested-empty-line-before': true,
+ 'clean-empty-lines': true,
+ },
+ cases: [
+ {
+ fixture: `
+ a {
+
+
+ @mixin foo;
+
+
+ }
+ `,
+ expected: `
+ a {
+
+ @mixin foo;
+ }
+ `,
+ },
+ {
+ fixture: `
+ a {
+ @mixin foo;
+
+ }
+ `,
+ expected: `
+ a {
+
+ @mixin foo;
+ }
+ `,
+ },
+ ],
+ },
+]);
|
--- a/__tests__/test.js
+++ b/__tests__/test.js
@@ ... @@
);
+
+groupTest([
+ {
+ description: 'Empty lines should be cleaned before any other empty-line-before option',
+ options: {
+ 'at-rule-nested-empty-line-before': true,
+ 'clean-empty-lines': true,
+ },
+ cases: [
+ {
+ fixture: `
+ a {
+
+
+ @mixin foo;
+
+
+ }
+ `,
+ expected: `
+ a {
+
+ @mixin foo;
+ }
+ `,
+ },
+ {
+ fixture: `
+ a {
+ @mixin foo;
+
+ }
+ `,
+ expected: `
+ a {
+
+ @mixin foo;
+ }
+ `,
+ },
+ ],
+ },
+]);
|
--- a/__tests__/test.js
+++ b/__tests__/test.js
@@ -6 +6,44 @@
CON );
ADD
ADD groupTest([
ADD {
ADD description: 'Empty lines should be cleaned before any other empty-line-before option',
ADD options: {
ADD 'at-rule-nested-empty-line-before': true,
ADD 'clean-empty-lines': true,
ADD },
ADD cases: [
ADD {
ADD fixture: `
ADD a {
ADD
ADD
ADD @mixin foo;
ADD
ADD
ADD }
ADD `,
ADD expected: `
ADD a {
ADD
ADD @mixin foo;
ADD }
ADD `,
ADD },
ADD {
ADD fixture: `
ADD a {
ADD @mixin foo;
ADD
ADD }
ADD `,
ADD expected: `
ADD a {
ADD
ADD @mixin foo;
ADD }
ADD `,
ADD },
ADD ],
ADD },
ADD ]);
|
<<<<<<< SEARCH
() => runTest('empty-lines-preserve')
);
=======
() => runTest('empty-lines-preserve')
);
groupTest([
{
description: 'Empty lines should be cleaned before any other empty-line-before option',
options: {
'at-rule-nested-empty-line-before': true,
'clean-empty-lines': true,
},
cases: [
{
fixture: `
a {
@mixin foo;
}
`,
expected: `
a {
@mixin foo;
}
`,
},
{
fixture: `
a {
@mixin foo;
}
`,
expected: `
a {
@mixin foo;
}
`,
},
],
},
]);
>>>>>>> REPLACE
|
kylewlacy/glitter
|
0cc206726550c06796f86f27a98d5671d7bd41a8
|
src/lib.rs
|
rust
|
apache-2.0
|
Add `BufferContext` traits to the prelude module
|
#[macro_use] extern crate bitflags;
extern crate gl as gl_lib;
#[cfg(feature = "cgmath")] extern crate cgmath as cgmath_lib;
#[cfg(feature = "image")] extern crate image as image_lib;
mod ref_into;
#[macro_use] mod macros;
mod context;
mod buffer;
mod shader;
mod program;
mod framebuffer;
mod renderbuffer;
mod texture;
mod texture_units;
mod image_data;
mod vertex_data;
mod vertex_buffer;
mod index_data;
mod uniform_data;
mod types;
#[cfg(feature = "cgmath")] mod cgmath_features;
#[cfg(feature = "image")] mod image_features;
pub use gl_lib as gl;
#[cfg(feature = "cgmath")] pub use cgmath_lib as cgmath;
#[cfg(feature = "image")] pub use image_lib as image;
pub use context::*;
pub use buffer::*;
pub use shader::*;
pub use program::*;
pub use framebuffer::*;
pub use renderbuffer::*;
pub use texture::*;
pub use texture_units::*;
pub use image_data::*;
pub use vertex_data::*;
pub use vertex_buffer::*;
pub use index_data::*;
pub use uniform_data::*;
pub use types::*;
pub mod prelude {
pub use buffer::BufferBinding;
pub use texture_units::TextureUnit;
pub use texture::TextureBinding;
}
|
#[macro_use] extern crate bitflags;
extern crate gl as gl_lib;
#[cfg(feature = "cgmath")] extern crate cgmath as cgmath_lib;
#[cfg(feature = "image")] extern crate image as image_lib;
mod ref_into;
#[macro_use] mod macros;
mod context;
mod buffer;
mod shader;
mod program;
mod framebuffer;
mod renderbuffer;
mod texture;
mod texture_units;
mod image_data;
mod vertex_data;
mod vertex_buffer;
mod index_data;
mod uniform_data;
mod types;
#[cfg(feature = "cgmath")] mod cgmath_features;
#[cfg(feature = "image")] mod image_features;
pub use gl_lib as gl;
#[cfg(feature = "cgmath")] pub use cgmath_lib as cgmath;
#[cfg(feature = "image")] pub use image_lib as image;
pub use context::*;
pub use buffer::*;
pub use shader::*;
pub use program::*;
pub use framebuffer::*;
pub use renderbuffer::*;
pub use texture::*;
pub use texture_units::*;
pub use image_data::*;
pub use vertex_data::*;
pub use vertex_buffer::*;
pub use index_data::*;
pub use uniform_data::*;
pub use types::*;
pub mod prelude {
pub use buffer::{BufferBinding, BufferContext,
ArrayBufferContext, ElementArrayBufferContext};
pub use texture_units::TextureUnit;
pub use texture::TextureBinding;
}
| 2
| 1
| 1
|
mixed
|
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -48,3 +48,4 @@
pub mod prelude {
- pub use buffer::BufferBinding;
+ pub use buffer::{BufferBinding, BufferContext,
+ ArrayBufferContext, ElementArrayBufferContext};
pub use texture_units::TextureUnit;
|
--- a/src/lib.rs
+++ b/src/lib.rs
@@ ... @@
pub mod prelude {
- pub use buffer::BufferBinding;
+ pub use buffer::{BufferBinding, BufferContext,
+ ArrayBufferContext, ElementArrayBufferContext};
pub use texture_units::TextureUnit;
|
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -48,3 +48,4 @@
CON pub mod prelude {
DEL pub use buffer::BufferBinding;
ADD pub use buffer::{BufferBinding, BufferContext,
ADD ArrayBufferContext, ElementArrayBufferContext};
CON pub use texture_units::TextureUnit;
|
<<<<<<< SEARCH
pub mod prelude {
pub use buffer::BufferBinding;
pub use texture_units::TextureUnit;
pub use texture::TextureBinding;
=======
pub mod prelude {
pub use buffer::{BufferBinding, BufferContext,
ArrayBufferContext, ElementArrayBufferContext};
pub use texture_units::TextureUnit;
pub use texture::TextureBinding;
>>>>>>> REPLACE
|
stelar7/L4J8
|
81bcd3c45ba102b7fdfc6f50873a22b4f5038b0f
|
src/main/java/no/stelar7/api/l4j8/basic/constants/types/LeaguePositionType.java
|
java
|
apache-2.0
|
Add missing params to league position
|
package no.stelar7.api.l4j8.basic.constants.types;
import java.util.Optional;
import java.util.stream.Stream;
public enum LeaguePositionType implements CodedEnum
{
/**
* Top lane
*/
TOP,
/**
* Jungle
*/
JUNGLE,
/**
* Mid lane
*/
MIDDLE,
/**
* Bottom lane
*/
BOTTOM,
/**
* Support
*/
UTILITY;
/**
* Returns an LeaguePositionType from the provided value
*
* @param type the type to check
* @return LeaguePositionType
*/
public Optional<LeaguePositionType> getFromCode(final String type)
{
return Stream.of(LeaguePositionType.values()).filter(t -> t.name().equalsIgnoreCase(type)).findFirst();
}
/**
* The value used to map strings to objects
*
* @return String
*/
public String getCode()
{
return this.name();
}
}
|
package no.stelar7.api.l4j8.basic.constants.types;
import java.util.Optional;
import java.util.stream.Stream;
public enum LeaguePositionType implements CodedEnum
{
/**
* MASTER+ rank gets this for some reason?
*/
APEX,
/**
* Top lane
*/
TOP,
/**
* Jungle
*/
JUNGLE,
/**
* Mid lane
*/
MIDDLE,
/**
* Bottom lane
*/
BOTTOM,
/**
* Support
*/
UTILITY,
/**
* Not a positional queue
*/
NONE;
/**
* Returns an LeaguePositionType from the provided value
*
* @param type the type to check
* @return LeaguePositionType
*/
public Optional<LeaguePositionType> getFromCode(final String type)
{
return Stream.of(LeaguePositionType.values()).filter(t -> t.name().equalsIgnoreCase(type)).findFirst();
}
/**
* The value used to map strings to objects
*
* @return String
*/
public String getCode()
{
return this.name();
}
}
| 9
| 1
| 2
|
mixed
|
--- a/src/main/java/no/stelar7/api/l4j8/basic/constants/types/LeaguePositionType.java
+++ b/src/main/java/no/stelar7/api/l4j8/basic/constants/types/LeaguePositionType.java
@@ -7,2 +7,6 @@
{
+ /**
+ * MASTER+ rank gets this for some reason?
+ */
+ APEX,
/**
@@ -26,3 +30,7 @@
*/
- UTILITY;
+ UTILITY,
+ /**
+ * Not a positional queue
+ */
+ NONE;
|
--- a/src/main/java/no/stelar7/api/l4j8/basic/constants/types/LeaguePositionType.java
+++ b/src/main/java/no/stelar7/api/l4j8/basic/constants/types/LeaguePositionType.java
@@ ... @@
{
+ /**
+ * MASTER+ rank gets this for some reason?
+ */
+ APEX,
/**
@@ ... @@
*/
- UTILITY;
+ UTILITY,
+ /**
+ * Not a positional queue
+ */
+ NONE;
|
--- a/src/main/java/no/stelar7/api/l4j8/basic/constants/types/LeaguePositionType.java
+++ b/src/main/java/no/stelar7/api/l4j8/basic/constants/types/LeaguePositionType.java
@@ -7,2 +7,6 @@
CON {
ADD /**
ADD * MASTER+ rank gets this for some reason?
ADD */
ADD APEX,
CON /**
@@ -26,3 +30,7 @@
CON */
DEL UTILITY;
ADD UTILITY,
ADD /**
ADD * Not a positional queue
ADD */
ADD NONE;
CON
|
<<<<<<< SEARCH
public enum LeaguePositionType implements CodedEnum
{
/**
* Top lane
=======
public enum LeaguePositionType implements CodedEnum
{
/**
* MASTER+ rank gets this for some reason?
*/
APEX,
/**
* Top lane
>>>>>>> REPLACE
<<<<<<< SEARCH
* Support
*/
UTILITY;
/**
=======
* Support
*/
UTILITY,
/**
* Not a positional queue
*/
NONE;
/**
>>>>>>> REPLACE
|
sourrust/flac
|
220923eab13f64cb1915454ab95be2f99c22b29f
|
tests/stream.rs
|
rust
|
bsd-3-clause
|
Change to multiple file names
|
extern crate flac;
extern crate crypto;
use crypto::digest::Digest;
use crypto::md5::Md5;
use flac::Stream;
use std::cmp;
fn to_bytes(value: i32, buffer: &mut [u8]) {
buffer[0] = value as u8;
buffer[1] = (value >> 8) as u8;
buffer[2] = (value >> 16) as u8;
buffer[3] = (value >> 24) as u8;
}
fn get_offset(sample_size: usize) -> usize {
let bits_per_sample = cmp::max(sample_size, 8);
bits_per_sample / 8
}
#[test]
fn test_decoded_md5_sum() {
let filename = "tests/assets/input-pictures.flac";
let mut stream = Stream::from_file(filename).unwrap();
let mut buffer = [0; 4];
let mut md5 = Md5::new();
let mut md5_sum = [0; 16];
let info = stream.info();
let offset = get_offset(info.bits_per_sample as usize);
for sample in stream.iter() {
to_bytes(sample, &mut buffer);
md5.input(&buffer[0..offset]);
}
md5.result(&mut md5_sum);
assert_eq!(md5_sum, info.md5_sum);
}
|
extern crate flac;
extern crate crypto;
use crypto::digest::Digest;
use crypto::md5::Md5;
use flac::Stream;
use std::cmp;
fn to_bytes(value: i32, buffer: &mut [u8]) {
buffer[0] = value as u8;
buffer[1] = (value >> 8) as u8;
buffer[2] = (value >> 16) as u8;
buffer[3] = (value >> 24) as u8;
}
fn get_offset(sample_size: usize) -> usize {
let bits_per_sample = cmp::max(sample_size, 8);
bits_per_sample / 8
}
#[test]
fn test_decoded_md5_sum() {
let filenames = [
"tests/assets/input-pictures.flac",
"tests/assets/input-SCPAP.flac",
"tests/assets/input-SVAUP.flac",
];
let mut stream = Stream::from_file(filename).unwrap();
let mut buffer = [0; 4];
let mut md5 = Md5::new();
let mut md5_sum = [0; 16];
let info = stream.info();
let offset = get_offset(info.bits_per_sample as usize);
for sample in stream.iter() {
to_bytes(sample, &mut buffer);
md5.input(&buffer[0..offset]);
}
md5.result(&mut md5_sum);
assert_eq!(md5_sum, info.md5_sum);
}
| 5
| 1
| 1
|
mixed
|
--- a/tests/stream.rs
+++ b/tests/stream.rs
@@ -23,3 +23,7 @@
fn test_decoded_md5_sum() {
- let filename = "tests/assets/input-pictures.flac";
+ let filenames = [
+ "tests/assets/input-pictures.flac",
+ "tests/assets/input-SCPAP.flac",
+ "tests/assets/input-SVAUP.flac",
+ ];
|
--- a/tests/stream.rs
+++ b/tests/stream.rs
@@ ... @@
fn test_decoded_md5_sum() {
- let filename = "tests/assets/input-pictures.flac";
+ let filenames = [
+ "tests/assets/input-pictures.flac",
+ "tests/assets/input-SCPAP.flac",
+ "tests/assets/input-SVAUP.flac",
+ ];
|
--- a/tests/stream.rs
+++ b/tests/stream.rs
@@ -23,3 +23,7 @@
CON fn test_decoded_md5_sum() {
DEL let filename = "tests/assets/input-pictures.flac";
ADD let filenames = [
ADD "tests/assets/input-pictures.flac",
ADD "tests/assets/input-SCPAP.flac",
ADD "tests/assets/input-SVAUP.flac",
ADD ];
CON
|
<<<<<<< SEARCH
#[test]
fn test_decoded_md5_sum() {
let filename = "tests/assets/input-pictures.flac";
let mut stream = Stream::from_file(filename).unwrap();
=======
#[test]
fn test_decoded_md5_sum() {
let filenames = [
"tests/assets/input-pictures.flac",
"tests/assets/input-SCPAP.flac",
"tests/assets/input-SVAUP.flac",
];
let mut stream = Stream::from_file(filename).unwrap();
>>>>>>> REPLACE
|
djkovrik/YapTalker
|
b4fbe5d15c914953c91e44d0cdd8ce8d9e1382f0
|
app/src/main/java/com/sedsoftware/yaptalker/data/remote/yap/YapLoader.kt
|
kotlin
|
apache-2.0
|
Add request for forum load
|
@file:Suppress("KDocUnresolvedReference")
package com.sedsoftware.yaptalker.data.remote.yap
import com.sedsoftware.yaptalker.data.model.Forums
import com.sedsoftware.yaptalker.data.model.News
import io.reactivex.Single
import retrofit2.http.GET
import retrofit2.http.Path
interface YapLoader {
/**
* Load news from main page
*
* @param startPage Starting page number, also defines how much pages will be loaded.
*/
@GET("/st/{startPage}/")
fun loadNews(@Path("startPage") startPage: Int): Single<News>
/**
* Load main forums list
*/
@GET("/forum")
fun loadForumsList(): Single<Forums>
}
|
@file:Suppress("KDocUnresolvedReference")
package com.sedsoftware.yaptalker.data.remote.yap
import com.sedsoftware.yaptalker.data.model.ForumPage
import com.sedsoftware.yaptalker.data.model.Forums
import com.sedsoftware.yaptalker.data.model.News
import io.reactivex.Single
import retrofit2.http.GET
import retrofit2.http.Path
interface YapLoader {
/**
* Load news from main page
*
* @param startPage Starting page number, also defines how much pages will be loaded.
*/
@GET("/st/{startPage}/")
fun loadNews(@Path("startPage") startPage: Int): Single<News>
/**
* Load main forums list
*/
@GET("/forum")
fun loadForumsList(): Single<Forums>
/**
* Load chosen forum page.
*
* @param forumId Chosen forum id
* @param startFrom Starting page (first page equals 0, should be multiply of 30)
* @param sortingMode Possible values: last_post and rank
*/
@GET("/forum{forumId}/st/{startFrom}/100/Z-A/{sortingMode}")
fun loadForumPage(
@Path("forumId") forumId: Int,
@Path("startFrom") startTopicNumber: Int,
@Path("sortingMode") sortingMode: String): Single<ForumPage>
}
| 14
| 0
| 2
|
add_only
|
--- a/app/src/main/java/com/sedsoftware/yaptalker/data/remote/yap/YapLoader.kt
+++ b/app/src/main/java/com/sedsoftware/yaptalker/data/remote/yap/YapLoader.kt
@@ -4,2 +4,3 @@
+import com.sedsoftware.yaptalker.data.model.ForumPage
import com.sedsoftware.yaptalker.data.model.Forums
@@ -25,2 +26,15 @@
fun loadForumsList(): Single<Forums>
+
+ /**
+ * Load chosen forum page.
+ *
+ * @param forumId Chosen forum id
+ * @param startFrom Starting page (first page equals 0, should be multiply of 30)
+ * @param sortingMode Possible values: last_post and rank
+ */
+ @GET("/forum{forumId}/st/{startFrom}/100/Z-A/{sortingMode}")
+ fun loadForumPage(
+ @Path("forumId") forumId: Int,
+ @Path("startFrom") startTopicNumber: Int,
+ @Path("sortingMode") sortingMode: String): Single<ForumPage>
}
|
--- a/app/src/main/java/com/sedsoftware/yaptalker/data/remote/yap/YapLoader.kt
+++ b/app/src/main/java/com/sedsoftware/yaptalker/data/remote/yap/YapLoader.kt
@@ ... @@
+import com.sedsoftware.yaptalker.data.model.ForumPage
import com.sedsoftware.yaptalker.data.model.Forums
@@ ... @@
fun loadForumsList(): Single<Forums>
+
+ /**
+ * Load chosen forum page.
+ *
+ * @param forumId Chosen forum id
+ * @param startFrom Starting page (first page equals 0, should be multiply of 30)
+ * @param sortingMode Possible values: last_post and rank
+ */
+ @GET("/forum{forumId}/st/{startFrom}/100/Z-A/{sortingMode}")
+ fun loadForumPage(
+ @Path("forumId") forumId: Int,
+ @Path("startFrom") startTopicNumber: Int,
+ @Path("sortingMode") sortingMode: String): Single<ForumPage>
}
|
--- a/app/src/main/java/com/sedsoftware/yaptalker/data/remote/yap/YapLoader.kt
+++ b/app/src/main/java/com/sedsoftware/yaptalker/data/remote/yap/YapLoader.kt
@@ -4,2 +4,3 @@
CON
ADD import com.sedsoftware.yaptalker.data.model.ForumPage
CON import com.sedsoftware.yaptalker.data.model.Forums
@@ -25,2 +26,15 @@
CON fun loadForumsList(): Single<Forums>
ADD
ADD /**
ADD * Load chosen forum page.
ADD *
ADD * @param forumId Chosen forum id
ADD * @param startFrom Starting page (first page equals 0, should be multiply of 30)
ADD * @param sortingMode Possible values: last_post and rank
ADD */
ADD @GET("/forum{forumId}/st/{startFrom}/100/Z-A/{sortingMode}")
ADD fun loadForumPage(
ADD @Path("forumId") forumId: Int,
ADD @Path("startFrom") startTopicNumber: Int,
ADD @Path("sortingMode") sortingMode: String): Single<ForumPage>
CON }
|
<<<<<<< SEARCH
package com.sedsoftware.yaptalker.data.remote.yap
import com.sedsoftware.yaptalker.data.model.Forums
import com.sedsoftware.yaptalker.data.model.News
=======
package com.sedsoftware.yaptalker.data.remote.yap
import com.sedsoftware.yaptalker.data.model.ForumPage
import com.sedsoftware.yaptalker.data.model.Forums
import com.sedsoftware.yaptalker.data.model.News
>>>>>>> REPLACE
<<<<<<< SEARCH
@GET("/forum")
fun loadForumsList(): Single<Forums>
}
=======
@GET("/forum")
fun loadForumsList(): Single<Forums>
/**
* Load chosen forum page.
*
* @param forumId Chosen forum id
* @param startFrom Starting page (first page equals 0, should be multiply of 30)
* @param sortingMode Possible values: last_post and rank
*/
@GET("/forum{forumId}/st/{startFrom}/100/Z-A/{sortingMode}")
fun loadForumPage(
@Path("forumId") forumId: Int,
@Path("startFrom") startTopicNumber: Int,
@Path("sortingMode") sortingMode: String): Single<ForumPage>
}
>>>>>>> REPLACE
|
lamby/debian-devel-changes-bot
|
59371c5951f476e1684022744f4a37eb6fe62c98
|
DebianDevelChangesBot/utils/tidy_bug_title.py
|
python
|
agpl-3.0
|
Remove extra whitespace from bug title
Signed-off-by: Chris Lamb <[email protected]>
|
# -*- coding: utf-8 -*-
#
# Debian Changes Bot
# Copyright (C) 2008 Chris Lamb <[email protected]>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
def tidy_bug_title(title, package):
"""
Strips various package name prefixes from a bug title.
For example:
"emacs: Not as good as vim" => "Not as good as vim"
"[emacs] Not as good as vim" => "Not as good as vim"
"""
for prefix in ('%s: ', '[%s]: ', '[%s] '):
if title.lower().startswith(prefix % package.lower()):
title = title[len(package) + len(prefix) - 2:]
return title
|
# -*- coding: utf-8 -*-
#
# Debian Changes Bot
# Copyright (C) 2008 Chris Lamb <[email protected]>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import re
WHITESPACE = re.compile(r'\s{2,}')
def tidy_bug_title(title, package):
"""
Strips various package name prefixes from a bug title.
For example:
"emacs: Not as good as vim" => "Not as good as vim"
"[emacs] Not as good as vim" => "Not as good as vim"
"""
title = title.strip()
for prefix in ('%s: ', '[%s]: ', '[%s] '):
if title.lower().startswith(prefix % package.lower()):
title = title[len(package) + len(prefix) - 2:]
title = WHITESPACE.sub(' ', title)
return title
| 8
| 0
| 3
|
add_only
|
--- a/DebianDevelChangesBot/utils/tidy_bug_title.py
+++ b/DebianDevelChangesBot/utils/tidy_bug_title.py
@@ -18,2 +18,6 @@
+import re
+
+WHITESPACE = re.compile(r'\s{2,}')
+
def tidy_bug_title(title, package):
@@ -29,2 +33,4 @@
+ title = title.strip()
+
for prefix in ('%s: ', '[%s]: ', '[%s] '):
@@ -33,2 +39,4 @@
+ title = WHITESPACE.sub(' ', title)
+
return title
|
--- a/DebianDevelChangesBot/utils/tidy_bug_title.py
+++ b/DebianDevelChangesBot/utils/tidy_bug_title.py
@@ ... @@
+import re
+
+WHITESPACE = re.compile(r'\s{2,}')
+
def tidy_bug_title(title, package):
@@ ... @@
+ title = title.strip()
+
for prefix in ('%s: ', '[%s]: ', '[%s] '):
@@ ... @@
+ title = WHITESPACE.sub(' ', title)
+
return title
|
--- a/DebianDevelChangesBot/utils/tidy_bug_title.py
+++ b/DebianDevelChangesBot/utils/tidy_bug_title.py
@@ -18,2 +18,6 @@
CON
ADD import re
ADD
ADD WHITESPACE = re.compile(r'\s{2,}')
ADD
CON def tidy_bug_title(title, package):
@@ -29,2 +33,4 @@
CON
ADD title = title.strip()
ADD
CON for prefix in ('%s: ', '[%s]: ', '[%s] '):
@@ -33,2 +39,4 @@
CON
ADD title = WHITESPACE.sub(' ', title)
ADD
CON return title
|
<<<<<<< SEARCH
# along with this program. If not, see <http://www.gnu.org/licenses/>.
def tidy_bug_title(title, package):
"""
=======
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import re
WHITESPACE = re.compile(r'\s{2,}')
def tidy_bug_title(title, package):
"""
>>>>>>> REPLACE
<<<<<<< SEARCH
"""
for prefix in ('%s: ', '[%s]: ', '[%s] '):
if title.lower().startswith(prefix % package.lower()):
title = title[len(package) + len(prefix) - 2:]
return title
=======
"""
title = title.strip()
for prefix in ('%s: ', '[%s]: ', '[%s] '):
if title.lower().startswith(prefix % package.lower()):
title = title[len(package) + len(prefix) - 2:]
title = WHITESPACE.sub(' ', title)
return title
>>>>>>> REPLACE
|
chriskrycho/rust-by-example
|
8835814e9b89e94cee85d07b9ed4b26769cab423
|
examples/custom_types/structs/structs.rs
|
rust
|
apache-2.0
|
Switch from f64 to f32
Allows the activity to work without casting
stylistic choice - could also change the activity to take f64.
Unknown which is better.
|
// A unit struct
struct Nil;
// A tuple struct
struct Pair(i32, f64);
// A struct with two fields
struct Point {
x: f64,
y: f64,
}
// Structs can be reused as fields of another struct
#[allow(dead_code)]
struct Rectangle {
p1: Point,
p2: Point,
}
fn main() {
// Instantiate a `Point`
let point: Point = Point { x: 0.3, y: 0.4 };
// Access the fields of the point
println!("point coordinates: ({}, {})", point.x, point.y);
// Destructure the point using a `let` binding
let Point { x: my_x, y: my_y } = point;
let _rectangle = Rectangle {
// struct instantiation is an expression too
p1: Point { x: my_y, y: my_x },
p2: point,
};
// Instantiate a unit struct
let _nil = Nil;
// Instantiate a tuple struct
let pair = Pair(1, 0.1);
// Destructure a tuple struct
let Pair(integer, decimal) = pair;
println!("pair contains {:?} and {:?}", integer, decimal);
}
|
// A unit struct
struct Nil;
// A tuple struct
struct Pair(i32, f32);
// A struct with two fields
struct Point {
x: f32,
y: f32,
}
// Structs can be reused as fields of another struct
#[allow(dead_code)]
struct Rectangle {
p1: Point,
p2: Point,
}
fn main() {
// Instantiate a `Point`
let point: Point = Point { x: 0.3, y: 0.4 };
// Access the fields of the point
println!("point coordinates: ({}, {})", point.x, point.y);
// Destructure the point using a `let` binding
let Point { x: my_x, y: my_y } = point;
let _rectangle = Rectangle {
// struct instantiation is an expression too
p1: Point { x: my_y, y: my_x },
p2: point,
};
// Instantiate a unit struct
let _nil = Nil;
// Instantiate a tuple struct
let pair = Pair(1, 0.1);
// Destructure a tuple struct
let Pair(integer, decimal) = pair;
println!("pair contains {:?} and {:?}", integer, decimal);
}
| 3
| 3
| 2
|
mixed
|
--- a/examples/custom_types/structs/structs.rs
+++ b/examples/custom_types/structs/structs.rs
@@ -4,3 +4,3 @@
// A tuple struct
-struct Pair(i32, f64);
+struct Pair(i32, f32);
@@ -8,4 +8,4 @@
struct Point {
- x: f64,
- y: f64,
+ x: f32,
+ y: f32,
}
|
--- a/examples/custom_types/structs/structs.rs
+++ b/examples/custom_types/structs/structs.rs
@@ ... @@
// A tuple struct
-struct Pair(i32, f64);
+struct Pair(i32, f32);
@@ ... @@
struct Point {
- x: f64,
- y: f64,
+ x: f32,
+ y: f32,
}
|
--- a/examples/custom_types/structs/structs.rs
+++ b/examples/custom_types/structs/structs.rs
@@ -4,3 +4,3 @@
CON // A tuple struct
DEL struct Pair(i32, f64);
ADD struct Pair(i32, f32);
CON
@@ -8,4 +8,4 @@
CON struct Point {
DEL x: f64,
DEL y: f64,
ADD x: f32,
ADD y: f32,
CON }
|
<<<<<<< SEARCH
// A tuple struct
struct Pair(i32, f64);
// A struct with two fields
struct Point {
x: f64,
y: f64,
}
=======
// A tuple struct
struct Pair(i32, f32);
// A struct with two fields
struct Point {
x: f32,
y: f32,
}
>>>>>>> REPLACE
|
gazhayes/Popvote-HK
|
11ded211ad5218c8263aa180291ec1765cd3f204
|
lib/collections/profileData.js
|
javascript
|
agpl-3.0
|
Fix issue where server error thrown if user does not have aecData
|
AECData = new Mongo.Collection('aecData');
Meteor.methods({
profileInsert: function (profileData) {
check(Meteor.userId(), String);
check(Meteor.user().profile.aecData, undefined);
check(profileData, {
givenName: String,
familyName: String,
federalDivision: String,
stateDistrict: String,
localCouncil: String,
locality: String,
ward: String,
stateCode: String
});
var user = Meteor.user();
fullProfile = _.extend(profileData, {
userId: user._id,
creationDate: new Date(),
});
var fullProfileId = AECData.insert(fullProfile);
Meteor.users.update(user, {
$set:{
profile: {
aecData: fullProfileId
}
}
})},
profileData: function (data) {
if (Meteor.user().profile.aecData) {
var id = Meteor.user().profile.aecData;
return AECData.findOne({_id:id}, {})[data];
} else {throw new Meteor.Error('invalid', 'AEC Data Not Found');};
}
})
|
AECData = new Mongo.Collection('aecData');
Meteor.methods({
profileInsert: function (profileData) {
check(Meteor.userId(), String);
//check(Meteor.user().profile.aecData, undefined);
check(profileData, {
givenName: String,
familyName: String,
federalDivision: String,
stateDistrict: String,
localCouncil: String,
locality: String,
ward: String,
stateCode: String
});
var user = Meteor.user();
fullProfile = _.extend(profileData, {
userId: user._id,
creationDate: new Date(),
});
if (Meteor.user().profile) {throw new Meteor.Error('invalid', 'You\'ve already registered to vote')
} else {
var fullProfileId = AECData.insert(fullProfile);
Meteor.users.update(user, {
$set:{
profile: {
aecData: fullProfileId
}
}
})
}
},
profileData: function (data) {
if (Meteor.user().profile.aecData) {
var id = Meteor.user().profile.aecData;
return AECData.findOne({_id:id}, {})[data];
} else {throw new Meteor.Error('invalid', 'AEC Data Not Found');};
}
})
| 13
| 8
| 2
|
mixed
|
--- a/lib/collections/profileData.js
+++ b/lib/collections/profileData.js
@@ -5,3 +5,4 @@
check(Meteor.userId(), String);
- check(Meteor.user().profile.aecData, undefined);
+ //check(Meteor.user().profile.aecData, undefined);
+
check(profileData, {
@@ -22,10 +23,14 @@
});
- var fullProfileId = AECData.insert(fullProfile);
- Meteor.users.update(user, {
- $set:{
- profile: {
- aecData: fullProfileId
+ if (Meteor.user().profile) {throw new Meteor.Error('invalid', 'You\'ve already registered to vote')
+ } else {
+ var fullProfileId = AECData.insert(fullProfile);
+ Meteor.users.update(user, {
+ $set:{
+ profile: {
+ aecData: fullProfileId
+ }
}
- }
- })},
+ })
+ }
+ },
profileData: function (data) {
|
--- a/lib/collections/profileData.js
+++ b/lib/collections/profileData.js
@@ ... @@
check(Meteor.userId(), String);
- check(Meteor.user().profile.aecData, undefined);
+ //check(Meteor.user().profile.aecData, undefined);
+
check(profileData, {
@@ ... @@
});
- var fullProfileId = AECData.insert(fullProfile);
- Meteor.users.update(user, {
- $set:{
- profile: {
- aecData: fullProfileId
+ if (Meteor.user().profile) {throw new Meteor.Error('invalid', 'You\'ve already registered to vote')
+ } else {
+ var fullProfileId = AECData.insert(fullProfile);
+ Meteor.users.update(user, {
+ $set:{
+ profile: {
+ aecData: fullProfileId
+ }
}
- }
- })},
+ })
+ }
+ },
profileData: function (data) {
|
--- a/lib/collections/profileData.js
+++ b/lib/collections/profileData.js
@@ -5,3 +5,4 @@
CON check(Meteor.userId(), String);
DEL check(Meteor.user().profile.aecData, undefined);
ADD //check(Meteor.user().profile.aecData, undefined);
ADD
CON check(profileData, {
@@ -22,10 +23,14 @@
CON });
DEL var fullProfileId = AECData.insert(fullProfile);
DEL Meteor.users.update(user, {
DEL $set:{
DEL profile: {
DEL aecData: fullProfileId
ADD if (Meteor.user().profile) {throw new Meteor.Error('invalid', 'You\'ve already registered to vote')
ADD } else {
ADD var fullProfileId = AECData.insert(fullProfile);
ADD Meteor.users.update(user, {
ADD $set:{
ADD profile: {
ADD aecData: fullProfileId
ADD }
CON }
DEL }
DEL })},
ADD })
ADD }
ADD },
CON profileData: function (data) {
|
<<<<<<< SEARCH
profileInsert: function (profileData) {
check(Meteor.userId(), String);
check(Meteor.user().profile.aecData, undefined);
check(profileData, {
givenName: String,
=======
profileInsert: function (profileData) {
check(Meteor.userId(), String);
//check(Meteor.user().profile.aecData, undefined);
check(profileData, {
givenName: String,
>>>>>>> REPLACE
<<<<<<< SEARCH
});
var fullProfileId = AECData.insert(fullProfile);
Meteor.users.update(user, {
$set:{
profile: {
aecData: fullProfileId
}
}
})},
profileData: function (data) {
if (Meteor.user().profile.aecData) {
=======
});
if (Meteor.user().profile) {throw new Meteor.Error('invalid', 'You\'ve already registered to vote')
} else {
var fullProfileId = AECData.insert(fullProfile);
Meteor.users.update(user, {
$set:{
profile: {
aecData: fullProfileId
}
}
})
}
},
profileData: function (data) {
if (Meteor.user().profile.aecData) {
>>>>>>> REPLACE
|
rock3r/detekt
|
2034259cc37a49f94cef872e29f1b72c84bc4493
|
detekt-sample-extensions/build.gradle.kts
|
kotlin
|
apache-2.0
|
Remove redundant Kotlin plugin config
|
buildscript {
repositories {
mavenLocal()
jcenter()
}
val kotlinVersion: String by project
dependencies {
classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlinVersion")
}
}
repositories {
jcenter()
}
apply {
plugin("kotlin")
}
val assertjVersion: String by project
val usedDetektVersion: String by project
val junitEngineVersion: String by project
val junitPlatformVersion: String by project
val spekVersion: String by project
dependencies {
implementation("io.gitlab.arturbosch.detekt:detekt-api:$usedDetektVersion")
testImplementation("io.gitlab.arturbosch.detekt:detekt-test:$usedDetektVersion")
testImplementation("org.junit.jupiter:junit-jupiter-api:$junitEngineVersion")
testImplementation(kotlin("test"))
testImplementation(kotlin("reflect"))
testImplementation("org.assertj:assertj-core:$assertjVersion")
testImplementation("org.jetbrains.spek:spek-api:$spekVersion")
testImplementation("org.jetbrains.spek:spek-subject-extension:$spekVersion")
testImplementation("org.junit.jupiter:junit-jupiter-engine:$junitEngineVersion")
testRuntimeOnly("org.junit.platform:junit-platform-launcher:$junitPlatformVersion")
testRuntimeOnly("org.jetbrains.spek:spek-junit-platform-engine:$spekVersion")
}
|
val assertjVersion: String by project
val usedDetektVersion: String by project
val junitEngineVersion: String by project
val junitPlatformVersion: String by project
val spekVersion: String by project
dependencies {
implementation("io.gitlab.arturbosch.detekt:detekt-api:$usedDetektVersion")
testImplementation("io.gitlab.arturbosch.detekt:detekt-test:$usedDetektVersion")
testImplementation("org.junit.jupiter:junit-jupiter-api:$junitEngineVersion")
testImplementation(kotlin("test"))
testImplementation(kotlin("reflect"))
testImplementation("org.assertj:assertj-core:$assertjVersion")
testImplementation("org.jetbrains.spek:spek-api:$spekVersion")
testImplementation("org.jetbrains.spek:spek-subject-extension:$spekVersion")
testImplementation("org.junit.jupiter:junit-jupiter-engine:$junitEngineVersion")
testRuntimeOnly("org.junit.platform:junit-platform-launcher:$junitPlatformVersion")
testRuntimeOnly("org.jetbrains.spek:spek-junit-platform-engine:$spekVersion")
}
| 0
| 21
| 1
|
del_only
|
--- a/detekt-sample-extensions/build.gradle.kts
+++ b/detekt-sample-extensions/build.gradle.kts
@@ -1,22 +1 @@
-buildscript {
- repositories {
- mavenLocal()
- jcenter()
- }
-
- val kotlinVersion: String by project
-
- dependencies {
- classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlinVersion")
- }
-}
-
-repositories {
- jcenter()
-}
-
-apply {
- plugin("kotlin")
-}
-
val assertjVersion: String by project
|
--- a/detekt-sample-extensions/build.gradle.kts
+++ b/detekt-sample-extensions/build.gradle.kts
@@ ... @@
-buildscript {
- repositories {
- mavenLocal()
- jcenter()
- }
-
- val kotlinVersion: String by project
-
- dependencies {
- classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlinVersion")
- }
-}
-
-repositories {
- jcenter()
-}
-
-apply {
- plugin("kotlin")
-}
-
val assertjVersion: String by project
|
--- a/detekt-sample-extensions/build.gradle.kts
+++ b/detekt-sample-extensions/build.gradle.kts
@@ -1,22 +1 @@
DEL buildscript {
DEL repositories {
DEL mavenLocal()
DEL jcenter()
DEL }
DEL
DEL val kotlinVersion: String by project
DEL
DEL dependencies {
DEL classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlinVersion")
DEL }
DEL }
DEL
DEL repositories {
DEL jcenter()
DEL }
DEL
DEL apply {
DEL plugin("kotlin")
DEL }
DEL
CON val assertjVersion: String by project
|
<<<<<<< SEARCH
buildscript {
repositories {
mavenLocal()
jcenter()
}
val kotlinVersion: String by project
dependencies {
classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlinVersion")
}
}
repositories {
jcenter()
}
apply {
plugin("kotlin")
}
val assertjVersion: String by project
val usedDetektVersion: String by project
=======
val assertjVersion: String by project
val usedDetektVersion: String by project
>>>>>>> REPLACE
|
johannhof/markdown.rs
|
df663fb6c7819a88bc2175fda7cae1be855fc1f1
|
src/lib.rs
|
rust
|
apache-2.0
|
Replace match blocks with try! macro
|
//! A crate for parsing Markdown in Rust
#![crate_name = "markdown"]
#![deny(missing_docs)]
// #![deny(warnings)]
#![cfg_attr(feature="clippy", feature(plugin))]
#![cfg_attr(feature="clippy", plugin(clippy))]
extern crate regex;
#[macro_use]
extern crate pipeline;
use std::fs::File;
use std::path::Path;
use std::io::{Read, Error};
mod parser;
mod html;
use parser::Block;
/// Converts a Markdown string to HTML
pub fn to_html(text: &str) -> String {
let result = parser::parse(text);
html::to_html(&result)
}
/// Converts a Markdown string to a tokenset of Markdown items
pub fn tokenize(text: &str) -> Vec<Block> {
parser::parse(text)
}
/// Opens a file and converts its contents to HTML
pub fn file_to_html(path: &Path) -> Result<String, Error> {
let mut file = match File::open(path) {
Ok(file) => file,
Err(e) => return Err(e),
};
let mut text = String::new();
match file.read_to_string(&mut text) {
Ok(_) => (),
Err(e) => return Err(e),
}
let result = parser::parse(&text);
Ok(html::to_html(&result))
}
|
//! A crate for parsing Markdown in Rust
#![crate_name = "markdown"]
#![deny(missing_docs)]
// #![deny(warnings)]
#![cfg_attr(feature="clippy", feature(plugin))]
#![cfg_attr(feature="clippy", plugin(clippy))]
extern crate regex;
#[macro_use]
extern crate pipeline;
use std::fs::File;
use std::path::Path;
use std::io::{self, Read};
mod parser;
mod html;
use parser::Block;
/// Converts a Markdown string to HTML
pub fn to_html(text: &str) -> String {
let result = parser::parse(text);
html::to_html(&result)
}
/// Converts a Markdown string to a tokenset of Markdown items
pub fn tokenize(text: &str) -> Vec<Block> {
parser::parse(text)
}
/// Opens a file and converts its contents to HTML
pub fn file_to_html(path: &Path) -> io::Result<String> {
let mut file = try!(File::open(path));
let mut text = String::new();
try!(file.read_to_string(&mut text));
let result = parser::parse(&text);
Ok(html::to_html(&result))
}
| 4
| 10
| 2
|
mixed
|
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -15,3 +15,3 @@
use std::path::Path;
-use std::io::{Read, Error};
+use std::io::{self, Read};
@@ -34,13 +34,7 @@
/// Opens a file and converts its contents to HTML
-pub fn file_to_html(path: &Path) -> Result<String, Error> {
- let mut file = match File::open(path) {
- Ok(file) => file,
- Err(e) => return Err(e),
- };
+pub fn file_to_html(path: &Path) -> io::Result<String> {
+ let mut file = try!(File::open(path));
let mut text = String::new();
- match file.read_to_string(&mut text) {
- Ok(_) => (),
- Err(e) => return Err(e),
- }
+ try!(file.read_to_string(&mut text));
|
--- a/src/lib.rs
+++ b/src/lib.rs
@@ ... @@
use std::path::Path;
-use std::io::{Read, Error};
+use std::io::{self, Read};
@@ ... @@
/// Opens a file and converts its contents to HTML
-pub fn file_to_html(path: &Path) -> Result<String, Error> {
- let mut file = match File::open(path) {
- Ok(file) => file,
- Err(e) => return Err(e),
- };
+pub fn file_to_html(path: &Path) -> io::Result<String> {
+ let mut file = try!(File::open(path));
let mut text = String::new();
- match file.read_to_string(&mut text) {
- Ok(_) => (),
- Err(e) => return Err(e),
- }
+ try!(file.read_to_string(&mut text));
|
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -15,3 +15,3 @@
CON use std::path::Path;
DEL use std::io::{Read, Error};
ADD use std::io::{self, Read};
CON
@@ -34,13 +34,7 @@
CON /// Opens a file and converts its contents to HTML
DEL pub fn file_to_html(path: &Path) -> Result<String, Error> {
DEL let mut file = match File::open(path) {
DEL Ok(file) => file,
DEL Err(e) => return Err(e),
DEL };
ADD pub fn file_to_html(path: &Path) -> io::Result<String> {
ADD let mut file = try!(File::open(path));
CON
CON let mut text = String::new();
DEL match file.read_to_string(&mut text) {
DEL Ok(_) => (),
DEL Err(e) => return Err(e),
DEL }
ADD try!(file.read_to_string(&mut text));
CON
|
<<<<<<< SEARCH
use std::fs::File;
use std::path::Path;
use std::io::{Read, Error};
mod parser;
=======
use std::fs::File;
use std::path::Path;
use std::io::{self, Read};
mod parser;
>>>>>>> REPLACE
<<<<<<< SEARCH
/// Opens a file and converts its contents to HTML
pub fn file_to_html(path: &Path) -> Result<String, Error> {
let mut file = match File::open(path) {
Ok(file) => file,
Err(e) => return Err(e),
};
let mut text = String::new();
match file.read_to_string(&mut text) {
Ok(_) => (),
Err(e) => return Err(e),
}
let result = parser::parse(&text);
=======
/// Opens a file and converts its contents to HTML
pub fn file_to_html(path: &Path) -> io::Result<String> {
let mut file = try!(File::open(path));
let mut text = String::new();
try!(file.read_to_string(&mut text));
let result = parser::parse(&text);
>>>>>>> REPLACE
|
Wandalen/wTools
|
6d4d916e8bd6aecabc554e5270b6f3402bf7a0a8
|
rust/test/publisher/inc/publisher_test.rs
|
rust
|
mit
|
Fix tests of utility `wpublisher`, use compile mode directives
|
use super::*;
//
tests_impls!
{
fn basic_no_args()
{
let path = std::ffi::OsStr::new( "../../../target/debug/wpublisher" );
let proc = std::process::Command::new( path ).output().unwrap();
assert!( !proc.status.success() );
let stderr = std::str::from_utf8( proc.stderr.as_slice() ).unwrap();
assert_eq!( stderr, "Ambiguity. Did you mean?\n" );
let stdout = std::str::from_utf8( proc.stdout.as_slice() ).unwrap();
assert!( stdout.contains( ".list - List packages." ) );
}
//
fn basic_with_args()
{
let path = std::ffi::OsStr::new( "../../../target/debug/wpublisher" );
let proc = std::process::Command::new( path ).arg( ".list" ).output().unwrap();
assert!( proc.status.success() );
let stdout = std::str::from_utf8( proc.stdout.as_slice() ).unwrap();
assert_eq!( stdout, "" );
let stderr = std::str::from_utf8( proc.stderr.as_slice() ).unwrap();
assert_eq!( stderr, "" );
}
}
//
tests_index!
{
basic_no_args,
basic_with_args,
}
|
use super::*;
//
tests_impls!
{
fn basic_no_args()
{
#[ cfg( debug_assertions ) ]
let path = std::ffi::OsStr::new( "../../../target/debug/wpublisher" );
#[ cfg( not( debug_assertions ) ) ]
let path = std::ffi::OsStr::new( "../../../target/release/wpublisher" );
let proc = std::process::Command::new( path ).output().unwrap();
assert!( !proc.status.success() );
let stderr = std::str::from_utf8( proc.stderr.as_slice() ).unwrap();
assert_eq!( stderr, "Ambiguity. Did you mean?\n" );
let stdout = std::str::from_utf8( proc.stdout.as_slice() ).unwrap();
assert!( stdout.contains( ".list - List packages." ) );
}
//
fn basic_with_args()
{
#[ cfg( debug_assertions ) ]
let path = std::ffi::OsStr::new( "../../../target/debug/wpublisher" );
#[ cfg( not( debug_assertions ) ) ]
let path = std::ffi::OsStr::new( "../../../target/release/wpublisher" );
let proc = std::process::Command::new( path ).arg( ".list" ).output().unwrap();
assert!( proc.status.success() );
let stdout = std::str::from_utf8( proc.stdout.as_slice() ).unwrap();
assert_eq!( stdout, "" );
let stderr = std::str::from_utf8( proc.stderr.as_slice() ).unwrap();
assert_eq!( stderr, "" );
}
}
//
tests_index!
{
basic_no_args,
basic_with_args,
}
| 6
| 0
| 2
|
add_only
|
--- a/rust/test/publisher/inc/publisher_test.rs
+++ b/rust/test/publisher/inc/publisher_test.rs
@@ -9,3 +9,6 @@
{
+ #[ cfg( debug_assertions ) ]
let path = std::ffi::OsStr::new( "../../../target/debug/wpublisher" );
+ #[ cfg( not( debug_assertions ) ) ]
+ let path = std::ffi::OsStr::new( "../../../target/release/wpublisher" );
let proc = std::process::Command::new( path ).output().unwrap();
@@ -22,3 +25,6 @@
{
+ #[ cfg( debug_assertions ) ]
let path = std::ffi::OsStr::new( "../../../target/debug/wpublisher" );
+ #[ cfg( not( debug_assertions ) ) ]
+ let path = std::ffi::OsStr::new( "../../../target/release/wpublisher" );
let proc = std::process::Command::new( path ).arg( ".list" ).output().unwrap();
|
--- a/rust/test/publisher/inc/publisher_test.rs
+++ b/rust/test/publisher/inc/publisher_test.rs
@@ ... @@
{
+ #[ cfg( debug_assertions ) ]
let path = std::ffi::OsStr::new( "../../../target/debug/wpublisher" );
+ #[ cfg( not( debug_assertions ) ) ]
+ let path = std::ffi::OsStr::new( "../../../target/release/wpublisher" );
let proc = std::process::Command::new( path ).output().unwrap();
@@ ... @@
{
+ #[ cfg( debug_assertions ) ]
let path = std::ffi::OsStr::new( "../../../target/debug/wpublisher" );
+ #[ cfg( not( debug_assertions ) ) ]
+ let path = std::ffi::OsStr::new( "../../../target/release/wpublisher" );
let proc = std::process::Command::new( path ).arg( ".list" ).output().unwrap();
|
--- a/rust/test/publisher/inc/publisher_test.rs
+++ b/rust/test/publisher/inc/publisher_test.rs
@@ -9,3 +9,6 @@
CON {
ADD #[ cfg( debug_assertions ) ]
CON let path = std::ffi::OsStr::new( "../../../target/debug/wpublisher" );
ADD #[ cfg( not( debug_assertions ) ) ]
ADD let path = std::ffi::OsStr::new( "../../../target/release/wpublisher" );
CON let proc = std::process::Command::new( path ).output().unwrap();
@@ -22,3 +25,6 @@
CON {
ADD #[ cfg( debug_assertions ) ]
CON let path = std::ffi::OsStr::new( "../../../target/debug/wpublisher" );
ADD #[ cfg( not( debug_assertions ) ) ]
ADD let path = std::ffi::OsStr::new( "../../../target/release/wpublisher" );
CON let proc = std::process::Command::new( path ).arg( ".list" ).output().unwrap();
|
<<<<<<< SEARCH
fn basic_no_args()
{
let path = std::ffi::OsStr::new( "../../../target/debug/wpublisher" );
let proc = std::process::Command::new( path ).output().unwrap();
assert!( !proc.status.success() );
=======
fn basic_no_args()
{
#[ cfg( debug_assertions ) ]
let path = std::ffi::OsStr::new( "../../../target/debug/wpublisher" );
#[ cfg( not( debug_assertions ) ) ]
let path = std::ffi::OsStr::new( "../../../target/release/wpublisher" );
let proc = std::process::Command::new( path ).output().unwrap();
assert!( !proc.status.success() );
>>>>>>> REPLACE
<<<<<<< SEARCH
fn basic_with_args()
{
let path = std::ffi::OsStr::new( "../../../target/debug/wpublisher" );
let proc = std::process::Command::new( path ).arg( ".list" ).output().unwrap();
assert!( proc.status.success() );
=======
fn basic_with_args()
{
#[ cfg( debug_assertions ) ]
let path = std::ffi::OsStr::new( "../../../target/debug/wpublisher" );
#[ cfg( not( debug_assertions ) ) ]
let path = std::ffi::OsStr::new( "../../../target/release/wpublisher" );
let proc = std::process::Command::new( path ).arg( ".list" ).output().unwrap();
assert!( proc.status.success() );
>>>>>>> REPLACE
|
Techern/Netherrack
|
6d4920d172e92d8f0982edf10a29d934729bd28f
|
src/lib.rs
|
rust
|
apache-2.0
|
Add (But not yet implement) the Minecraft protocol version declaration
|
//! Entry module for the Netherrack project
// We'll be using serialization a lot
extern crate rustc_serialize;
// Enable logging and use of logging macros throughout Netherrack
#[macro_use]
extern crate log;
// Allow use of Semantic Versioning througout Netherrack
extern crate semver;
// Also allow usage of Version through Netherrack
pub use semver::Version;
// Allow use of the core module
pub mod core;
// Allow access to I/O operations
pub mod io;
// Allow access to the universe
pub mod universe;
// Okay, this is the start of Netherrack's functions
/// The version of Netherrack as determined at compile time
pub const NETHERRACK_VERSION_STRING: &'static str = env!("CARGO_PKG_VERSION");
/// Gets the current version of Netherrack
pub fn get_version() -> Version {
Version::parse(NETHERRACK_VERSION_STRING).unwrap()
}
/// Starts a new Netherrack server instance
pub fn start_server() {
info!("Netherrack startup called");
trace!("Starting network in a new thread");
std::thread::spawn(move || {
io::network::start_network();
});
debug!("Networking should be set up");
loop {
//TODO: In the future, execute a tick. Use Duration's span function to get time taken, sleep the remainder, and go again
std::thread::sleep_ms(20);
}
}
|
//! Entry module for the Netherrack project
// We'll be using serialization a lot
extern crate rustc_serialize;
// Enable logging and use of logging macros throughout Netherrack
#[macro_use]
extern crate log;
// Allow use of Semantic Versioning througout Netherrack
extern crate semver;
// Also allow usage of Version through Netherrack
pub use semver::Version;
// Allow use of the core module
pub mod core;
// Allow access to I/O operations
pub mod io;
// Allow access to the universe
pub mod universe;
// Okay, this is the start of Netherrack's functions
/// The version of the Minecraft protocol accepted by Netherrack
pub const MINECRAFT_PROTOCOL_VERSION: u32 = 47;
/// The version of Netherrack as determined at compile time
pub const NETHERRACK_VERSION_STRING: &'static str = env!("CARGO_PKG_VERSION");
/// Gets the current version of Netherrack
pub fn get_version() -> Version {
Version::parse(NETHERRACK_VERSION_STRING).unwrap()
}
/// Starts a new Netherrack server instance
pub fn start_server() {
info!("Netherrack startup called");
trace!("Starting network in a new thread");
std::thread::spawn(move || {
io::network::start_network();
});
debug!("Networking should be set up");
loop {
//TODO: In the future, execute a tick. Use Duration's span function to get time taken, sleep the remainder, and go again
std::thread::sleep_ms(20);
}
}
| 3
| 0
| 1
|
add_only
|
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -24,2 +24,5 @@
// Okay, this is the start of Netherrack's functions
+
+/// The version of the Minecraft protocol accepted by Netherrack
+pub const MINECRAFT_PROTOCOL_VERSION: u32 = 47;
|
--- a/src/lib.rs
+++ b/src/lib.rs
@@ ... @@
// Okay, this is the start of Netherrack's functions
+
+/// The version of the Minecraft protocol accepted by Netherrack
+pub const MINECRAFT_PROTOCOL_VERSION: u32 = 47;
|
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -24,2 +24,5 @@
CON // Okay, this is the start of Netherrack's functions
ADD
ADD /// The version of the Minecraft protocol accepted by Netherrack
ADD pub const MINECRAFT_PROTOCOL_VERSION: u32 = 47;
CON
|
<<<<<<< SEARCH
// Okay, this is the start of Netherrack's functions
/// The version of Netherrack as determined at compile time
=======
// Okay, this is the start of Netherrack's functions
/// The version of the Minecraft protocol accepted by Netherrack
pub const MINECRAFT_PROTOCOL_VERSION: u32 = 47;
/// The version of Netherrack as determined at compile time
>>>>>>> REPLACE
|
messense/wechat-rs
|
dd1fb78af39510d2b6e69c2b449bee9b7c1da7d8
|
src/lib.rs
|
rust
|
mit
|
Make parse_message, MessageParser, ReplyRenderer private.
|
#![feature(plugin)]
#![plugin(json_macros)]
extern crate time;
extern crate rand;
extern crate url;
extern crate sxd_document;
extern crate sxd_xpath;
extern crate rustc_serialize;
extern crate byteorder;
extern crate hyper;
extern crate openssl;
extern crate redis;
extern crate multipart;
#[macro_use]
extern crate log;
#[macro_use]
mod macros;
mod types;
mod xmlutil;
mod cryptography;
mod events;
mod parser;
mod errors;
mod utils;
pub mod messages;
pub mod replies;
pub mod client;
pub mod session;
pub use self::types::WeChatResult;
pub use self::messages::MessageParser;
pub use self::messages::Message;
pub use self::parser::parse_message;
pub use self::errors::WeChatError;
pub use self::cryptography::WeChatCrypto;
pub use self::replies::ReplyRenderer;
pub use self::replies::Reply;
pub use self::client::WeChatClient;
pub use self::utils::check_signature;
|
#![feature(plugin)]
#![plugin(json_macros)]
extern crate time;
extern crate rand;
extern crate url;
extern crate sxd_document;
extern crate sxd_xpath;
extern crate rustc_serialize;
extern crate byteorder;
extern crate hyper;
extern crate openssl;
extern crate redis;
extern crate multipart;
#[macro_use]
extern crate log;
#[macro_use]
mod macros;
mod types;
mod xmlutil;
mod cryptography;
mod events;
mod parser;
mod errors;
mod utils;
pub mod messages;
pub mod replies;
pub mod client;
pub mod session;
pub use self::types::WeChatResult;
pub use self::messages::Message;
pub use self::errors::WeChatError;
pub use self::cryptography::WeChatCrypto;
pub use self::replies::Reply;
pub use self::client::WeChatClient;
pub use self::utils::check_signature;
| 0
| 3
| 1
|
del_only
|
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -34,8 +34,5 @@
pub use self::types::WeChatResult;
-pub use self::messages::MessageParser;
pub use self::messages::Message;
-pub use self::parser::parse_message;
pub use self::errors::WeChatError;
pub use self::cryptography::WeChatCrypto;
-pub use self::replies::ReplyRenderer;
pub use self::replies::Reply;
|
--- a/src/lib.rs
+++ b/src/lib.rs
@@ ... @@
pub use self::types::WeChatResult;
-pub use self::messages::MessageParser;
pub use self::messages::Message;
-pub use self::parser::parse_message;
pub use self::errors::WeChatError;
pub use self::cryptography::WeChatCrypto;
-pub use self::replies::ReplyRenderer;
pub use self::replies::Reply;
|
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -34,8 +34,5 @@
CON pub use self::types::WeChatResult;
DEL pub use self::messages::MessageParser;
CON pub use self::messages::Message;
DEL pub use self::parser::parse_message;
CON pub use self::errors::WeChatError;
CON pub use self::cryptography::WeChatCrypto;
DEL pub use self::replies::ReplyRenderer;
CON pub use self::replies::Reply;
|
<<<<<<< SEARCH
pub use self::types::WeChatResult;
pub use self::messages::MessageParser;
pub use self::messages::Message;
pub use self::parser::parse_message;
pub use self::errors::WeChatError;
pub use self::cryptography::WeChatCrypto;
pub use self::replies::ReplyRenderer;
pub use self::replies::Reply;
pub use self::client::WeChatClient;
=======
pub use self::types::WeChatResult;
pub use self::messages::Message;
pub use self::errors::WeChatError;
pub use self::cryptography::WeChatCrypto;
pub use self::replies::Reply;
pub use self::client::WeChatClient;
>>>>>>> REPLACE
|
fastnsilver/xlator
|
81ffd9463b38f84ec3f9f61700be69e16311455f
|
src/main/java/com/fns/xlator/client/impl/FrenglyClientSettings.java
|
java
|
apache-2.0
|
Make email and password have default values
* which must be overriden
|
package com.fns.xlator.client.impl;
import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix = "app.frengly")
public class FrenglyClientSettings {
private String host = "frengly.com";
@NotEmpty
private String email;
@NotEmpty
private String password;
private int retries = 10;
@Value("${app.defaults.locale}")
private String defaultSource;
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getDefaultSource() {
return defaultSource;
}
public int getRetries() {
return retries;
}
}
|
package com.fns.xlator.client.impl;
import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix = "app.frengly")
public class FrenglyClientSettings {
private String host = "frengly.com";
@NotEmpty
private String email = "[email protected]";
@NotEmpty
private String password = "changeme";
private int retries = 10;
@Value("${app.defaults.locale}")
private String defaultSource;
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getDefaultSource() {
return defaultSource;
}
public int getRetries() {
return retries;
}
}
| 2
| 2
| 1
|
mixed
|
--- a/src/main/java/com/fns/xlator/client/impl/FrenglyClientSettings.java
+++ b/src/main/java/com/fns/xlator/client/impl/FrenglyClientSettings.java
@@ -14,6 +14,6 @@
@NotEmpty
- private String email;
+ private String email = "[email protected]";
@NotEmpty
- private String password;
+ private String password = "changeme";
|
--- a/src/main/java/com/fns/xlator/client/impl/FrenglyClientSettings.java
+++ b/src/main/java/com/fns/xlator/client/impl/FrenglyClientSettings.java
@@ ... @@
@NotEmpty
- private String email;
+ private String email = "[email protected]";
@NotEmpty
- private String password;
+ private String password = "changeme";
|
--- a/src/main/java/com/fns/xlator/client/impl/FrenglyClientSettings.java
+++ b/src/main/java/com/fns/xlator/client/impl/FrenglyClientSettings.java
@@ -14,6 +14,6 @@
CON @NotEmpty
DEL private String email;
ADD private String email = "[email protected]";
CON
CON @NotEmpty
DEL private String password;
ADD private String password = "changeme";
CON
|
<<<<<<< SEARCH
@NotEmpty
private String email;
@NotEmpty
private String password;
private int retries = 10;
=======
@NotEmpty
private String email = "[email protected]";
@NotEmpty
private String password = "changeme";
private int retries = 10;
>>>>>>> REPLACE
|
imp/httptin
|
1d393d45d701d718832a4ee69a255af8955900cf
|
src/main.rs
|
rust
|
apache-2.0
|
Add Server header to response
|
extern crate hyper;
mod get;
mod post;
use hyper::{Get, Post};
use hyper::server::{Handler, Server, Request, Response};
use hyper::status::StatusCode;
struct HttpTin;
impl Handler for HttpTin {
fn handle(&self, request: Request, mut response: Response) {
println!("{} {} {}", request.remote_addr, request.method, request.uri);
match request.method {
Get => get::get(request, response),
Post => post::post(request, response),
_ => *response.status_mut() = StatusCode::MethodNotAllowed,
}
}
}
fn main() {
let server = Server::http("::1:8000").unwrap();
// println!("Server {:?}", server);
let active = server.handle(HttpTin {}).unwrap();
println!("Active {:?}", active.socket);
}
|
extern crate hyper;
mod get;
mod post;
use hyper::{Get, Post};
use hyper::header;
use hyper::server::{Handler, Server, Request, Response};
use hyper::status::StatusCode;
struct HttpTin {
server: String,
}
impl HttpTin {
pub fn new() -> Self {
let server = format!("{}/{}", env!("CARGO_PKG_NAME"), env!("CARGO_PKG_VERSION"));
HttpTin { server: server }
}
fn prepare_response(&self, response: &mut Response) {
let server = header::Server(self.server.clone());
response.headers_mut().set(server);
}
}
impl Handler for HttpTin {
fn handle(&self, request: Request, mut response: Response) {
println!("{} {} {}", request.remote_addr, request.method, request.uri);
self.prepare_response(&mut response);
match request.method {
Get => get::get(request, response),
Post => post::post(request, response),
_ => *response.status_mut() = StatusCode::MethodNotAllowed,
}
}
}
fn main() {
let server = Server::http("::1:8000").unwrap();
// println!("Server {:?}", server);
let active = server.handle(HttpTin::new()).unwrap();
println!("Active {:?}", active.socket);
}
| 18
| 2
| 4
|
mixed
|
--- a/src/main.rs
+++ b/src/main.rs
@@ -6,2 +6,3 @@
use hyper::{Get, Post};
+use hyper::header;
use hyper::server::{Handler, Server, Request, Response};
@@ -9,3 +10,17 @@
-struct HttpTin;
+struct HttpTin {
+ server: String,
+}
+
+impl HttpTin {
+ pub fn new() -> Self {
+ let server = format!("{}/{}", env!("CARGO_PKG_NAME"), env!("CARGO_PKG_VERSION"));
+ HttpTin { server: server }
+ }
+
+ fn prepare_response(&self, response: &mut Response) {
+ let server = header::Server(self.server.clone());
+ response.headers_mut().set(server);
+ }
+}
@@ -14,2 +29,3 @@
println!("{} {} {}", request.remote_addr, request.method, request.uri);
+ self.prepare_response(&mut response);
match request.method {
@@ -25,3 +41,3 @@
// println!("Server {:?}", server);
- let active = server.handle(HttpTin {}).unwrap();
+ let active = server.handle(HttpTin::new()).unwrap();
println!("Active {:?}", active.socket);
|
--- a/src/main.rs
+++ b/src/main.rs
@@ ... @@
use hyper::{Get, Post};
+use hyper::header;
use hyper::server::{Handler, Server, Request, Response};
@@ ... @@
-struct HttpTin;
+struct HttpTin {
+ server: String,
+}
+
+impl HttpTin {
+ pub fn new() -> Self {
+ let server = format!("{}/{}", env!("CARGO_PKG_NAME"), env!("CARGO_PKG_VERSION"));
+ HttpTin { server: server }
+ }
+
+ fn prepare_response(&self, response: &mut Response) {
+ let server = header::Server(self.server.clone());
+ response.headers_mut().set(server);
+ }
+}
@@ ... @@
println!("{} {} {}", request.remote_addr, request.method, request.uri);
+ self.prepare_response(&mut response);
match request.method {
@@ ... @@
// println!("Server {:?}", server);
- let active = server.handle(HttpTin {}).unwrap();
+ let active = server.handle(HttpTin::new()).unwrap();
println!("Active {:?}", active.socket);
|
--- a/src/main.rs
+++ b/src/main.rs
@@ -6,2 +6,3 @@
CON use hyper::{Get, Post};
ADD use hyper::header;
CON use hyper::server::{Handler, Server, Request, Response};
@@ -9,3 +10,17 @@
CON
DEL struct HttpTin;
ADD struct HttpTin {
ADD server: String,
ADD }
ADD
ADD impl HttpTin {
ADD pub fn new() -> Self {
ADD let server = format!("{}/{}", env!("CARGO_PKG_NAME"), env!("CARGO_PKG_VERSION"));
ADD HttpTin { server: server }
ADD }
ADD
ADD fn prepare_response(&self, response: &mut Response) {
ADD let server = header::Server(self.server.clone());
ADD response.headers_mut().set(server);
ADD }
ADD }
CON
@@ -14,2 +29,3 @@
CON println!("{} {} {}", request.remote_addr, request.method, request.uri);
ADD self.prepare_response(&mut response);
CON match request.method {
@@ -25,3 +41,3 @@
CON // println!("Server {:?}", server);
DEL let active = server.handle(HttpTin {}).unwrap();
ADD let active = server.handle(HttpTin::new()).unwrap();
CON println!("Active {:?}", active.socket);
|
<<<<<<< SEARCH
use hyper::{Get, Post};
use hyper::server::{Handler, Server, Request, Response};
use hyper::status::StatusCode;
struct HttpTin;
impl Handler for HttpTin {
fn handle(&self, request: Request, mut response: Response) {
println!("{} {} {}", request.remote_addr, request.method, request.uri);
match request.method {
Get => get::get(request, response),
=======
use hyper::{Get, Post};
use hyper::header;
use hyper::server::{Handler, Server, Request, Response};
use hyper::status::StatusCode;
struct HttpTin {
server: String,
}
impl HttpTin {
pub fn new() -> Self {
let server = format!("{}/{}", env!("CARGO_PKG_NAME"), env!("CARGO_PKG_VERSION"));
HttpTin { server: server }
}
fn prepare_response(&self, response: &mut Response) {
let server = header::Server(self.server.clone());
response.headers_mut().set(server);
}
}
impl Handler for HttpTin {
fn handle(&self, request: Request, mut response: Response) {
println!("{} {} {}", request.remote_addr, request.method, request.uri);
self.prepare_response(&mut response);
match request.method {
Get => get::get(request, response),
>>>>>>> REPLACE
<<<<<<< SEARCH
let server = Server::http("::1:8000").unwrap();
// println!("Server {:?}", server);
let active = server.handle(HttpTin {}).unwrap();
println!("Active {:?}", active.socket);
}
=======
let server = Server::http("::1:8000").unwrap();
// println!("Server {:?}", server);
let active = server.handle(HttpTin::new()).unwrap();
println!("Active {:?}", active.socket);
}
>>>>>>> REPLACE
|
mobify/dj-saml-idp
|
0b8cc130f00b51b18e55805f82ba661fdf66fba6
|
saml2idp/saml2idp_metadata.py
|
python
|
mit
|
Implement suggested changes in PR review
|
"""
Django Settings that more closely resemble SAML Metadata.
Detailed discussion is in doc/SETTINGS_AND_METADATA.txt.
"""
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
CERTIFICATE_DATA = 'certificate_data'
CERTIFICATE_FILENAME = 'certificate_file'
PRIVATE_KEY_DATA = 'private_key_data'
PRIVATE_KEY_FILENAME = 'private_key_file'
def check_configuration_contains(config, keys):
available_keys = set(keys).intersection(set(config.keys()))
if not available_keys:
raise ImproperlyConfigured(
'one of the followin keys is required but none was '
'specified: {}'.format(keys))
if len(available_keys) > 1:
raise ImproperlyConfigured(
'found conflicting configuration: {}. Only one key can be used at'
'a time.'.format(available_keys))
def validate_configuration(config):
check_configuration_contains(config=config,
keys=[PRIVATE_KEY_DATA, PRIVATE_KEY_FILENAME])
check_configuration_contains(config=config,
keys=[CERTIFICATE_DATA, CERTIFICATE_FILENAME])
try:
SAML2IDP_CONFIG = settings.SAML2IDP_CONFIG
except:
raise ImproperlyConfigured('SAML2IDP_CONFIG setting is missing.')
else:
validate_configuration(SAML2IDP_CONFIG)
try:
SAML2IDP_REMOTES = settings.SAML2IDP_REMOTES
except:
raise ImproperlyConfigured('SAML2IDP_REMOTES setting is missing.')
|
"""
Django Settings that more closely resemble SAML Metadata.
Detailed discussion is in doc/SETTINGS_AND_METADATA.txt.
"""
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
CERTIFICATE_DATA = 'certificate_data'
CERTIFICATE_FILENAME = 'certificate_file'
PRIVATE_KEY_DATA = 'private_key_data'
PRIVATE_KEY_FILENAME = 'private_key_file'
def check_configuration_contains(config, keys):
available_keys = frozenset(keys).intersection(frozenset(config.keys()))
if not available_keys:
raise ImproperlyConfigured(
'one of the following keys is required but none was '
'specified: {}'.format(keys))
if len(available_keys) > 1:
raise ImproperlyConfigured(
'found conflicting configuration: {}. Only one key can be used at'
'a time.'.format(available_keys))
def validate_configuration(config):
check_configuration_contains(config=config,
keys=(PRIVATE_KEY_DATA, PRIVATE_KEY_FILENAME))
check_configuration_contains(config=config,
keys=(CERTIFICATE_DATA, CERTIFICATE_FILENAME))
try:
SAML2IDP_CONFIG = settings.SAML2IDP_CONFIG
except:
raise ImproperlyConfigured('SAML2IDP_CONFIG setting is missing.')
else:
validate_configuration(SAML2IDP_CONFIG)
try:
SAML2IDP_REMOTES = settings.SAML2IDP_REMOTES
except:
raise ImproperlyConfigured('SAML2IDP_REMOTES setting is missing.')
| 4
| 4
| 3
|
mixed
|
--- a/saml2idp/saml2idp_metadata.py
+++ b/saml2idp/saml2idp_metadata.py
@@ -15,3 +15,3 @@
def check_configuration_contains(config, keys):
- available_keys = set(keys).intersection(set(config.keys()))
+ available_keys = frozenset(keys).intersection(frozenset(config.keys()))
@@ -19,3 +19,3 @@
raise ImproperlyConfigured(
- 'one of the followin keys is required but none was '
+ 'one of the following keys is required but none was '
'specified: {}'.format(keys))
@@ -30,6 +30,6 @@
check_configuration_contains(config=config,
- keys=[PRIVATE_KEY_DATA, PRIVATE_KEY_FILENAME])
+ keys=(PRIVATE_KEY_DATA, PRIVATE_KEY_FILENAME))
check_configuration_contains(config=config,
- keys=[CERTIFICATE_DATA, CERTIFICATE_FILENAME])
+ keys=(CERTIFICATE_DATA, CERTIFICATE_FILENAME))
|
--- a/saml2idp/saml2idp_metadata.py
+++ b/saml2idp/saml2idp_metadata.py
@@ ... @@
def check_configuration_contains(config, keys):
- available_keys = set(keys).intersection(set(config.keys()))
+ available_keys = frozenset(keys).intersection(frozenset(config.keys()))
@@ ... @@
raise ImproperlyConfigured(
- 'one of the followin keys is required but none was '
+ 'one of the following keys is required but none was '
'specified: {}'.format(keys))
@@ ... @@
check_configuration_contains(config=config,
- keys=[PRIVATE_KEY_DATA, PRIVATE_KEY_FILENAME])
+ keys=(PRIVATE_KEY_DATA, PRIVATE_KEY_FILENAME))
check_configuration_contains(config=config,
- keys=[CERTIFICATE_DATA, CERTIFICATE_FILENAME])
+ keys=(CERTIFICATE_DATA, CERTIFICATE_FILENAME))
|
--- a/saml2idp/saml2idp_metadata.py
+++ b/saml2idp/saml2idp_metadata.py
@@ -15,3 +15,3 @@
CON def check_configuration_contains(config, keys):
DEL available_keys = set(keys).intersection(set(config.keys()))
ADD available_keys = frozenset(keys).intersection(frozenset(config.keys()))
CON
@@ -19,3 +19,3 @@
CON raise ImproperlyConfigured(
DEL 'one of the followin keys is required but none was '
ADD 'one of the following keys is required but none was '
CON 'specified: {}'.format(keys))
@@ -30,6 +30,6 @@
CON check_configuration_contains(config=config,
DEL keys=[PRIVATE_KEY_DATA, PRIVATE_KEY_FILENAME])
ADD keys=(PRIVATE_KEY_DATA, PRIVATE_KEY_FILENAME))
CON
CON check_configuration_contains(config=config,
DEL keys=[CERTIFICATE_DATA, CERTIFICATE_FILENAME])
ADD keys=(CERTIFICATE_DATA, CERTIFICATE_FILENAME))
CON
|
<<<<<<< SEARCH
def check_configuration_contains(config, keys):
available_keys = set(keys).intersection(set(config.keys()))
if not available_keys:
raise ImproperlyConfigured(
'one of the followin keys is required but none was '
'specified: {}'.format(keys))
=======
def check_configuration_contains(config, keys):
available_keys = frozenset(keys).intersection(frozenset(config.keys()))
if not available_keys:
raise ImproperlyConfigured(
'one of the following keys is required but none was '
'specified: {}'.format(keys))
>>>>>>> REPLACE
<<<<<<< SEARCH
def validate_configuration(config):
check_configuration_contains(config=config,
keys=[PRIVATE_KEY_DATA, PRIVATE_KEY_FILENAME])
check_configuration_contains(config=config,
keys=[CERTIFICATE_DATA, CERTIFICATE_FILENAME])
=======
def validate_configuration(config):
check_configuration_contains(config=config,
keys=(PRIVATE_KEY_DATA, PRIVATE_KEY_FILENAME))
check_configuration_contains(config=config,
keys=(CERTIFICATE_DATA, CERTIFICATE_FILENAME))
>>>>>>> REPLACE
|
J-F-Liu/pom
|
9d93cf61d5a9473f6fd54e30b8943d4d38496d72
|
src/char_class.rs
|
rust
|
mit
|
Add space and multispace char classes
|
#[inline]
pub fn alpha(term: u8) -> bool {
(term >= 0x41 && term <= 0x5A) || (term >= 0x61 && term <= 0x7A)
}
#[inline]
pub fn digit(term: u8) -> bool {
term >= 0x30 && term <= 0x39
}
#[inline]
pub fn alphanum(term: u8) -> bool {
alpha(term) || digit(term)
}
#[inline]
pub fn hex_digit(term: u8) -> bool {
(term >= 0x30 && term <= 0x39) ||
(term >= 0x41 && term <= 0x46) ||
(term >= 0x61 && term <= 0x66)
}
#[inline]
pub fn oct_digit(term: u8) -> bool {
term >= 0x30 && term <= 0x37
}
|
/// Recognises an alphabetic character, `a-zA-Z`.
#[inline]
pub fn alpha(term: u8) -> bool {
(term >= 0x41 && term <= 0x5A) || (term >= 0x61 && term <= 0x7A)
}
/// Recognises a decimal digit, `0-9`.
#[inline]
pub fn digit(term: u8) -> bool {
term >= 0x30 && term <= 0x39
}
/// Recognises an alphanumeric character, `a-zA-Z0-9`.
#[inline]
pub fn alphanum(term: u8) -> bool {
alpha(term) || digit(term)
}
/// Recognises a hexadecimal digit, `0-9a-fA-F`.
#[inline]
pub fn hex_digit(term: u8) -> bool {
(term >= 0x30 && term <= 0x39) ||
(term >= 0x41 && term <= 0x46) ||
(term >= 0x61 && term <= 0x66)
}
/// Recognises an octal digit, `0-7`.
#[inline]
pub fn oct_digit(term: u8) -> bool {
term >= 0x30 && term <= 0x37
}
/// Recognises a space or tab.
#[inline]
pub fn space(term: u8) -> bool {
term == b' ' || term == b'\t'
}
/// Recognises a space, tab, line feed, or carriage returns.
#[inline]
pub fn multispace(term: u8) -> bool {
space(term) || term == b'\n' || term == b'\r'
}
| 17
| 1
| 6
|
mixed
|
--- a/src/char_class.rs
+++ b/src/char_class.rs
@@ -1,2 +1,2 @@
-
+/// Recognises an alphabetic character, `a-zA-Z`.
#[inline]
@@ -6,2 +6,3 @@
+/// Recognises a decimal digit, `0-9`.
#[inline]
@@ -11,2 +12,3 @@
+/// Recognises an alphanumeric character, `a-zA-Z0-9`.
#[inline]
@@ -16,2 +18,3 @@
+/// Recognises a hexadecimal digit, `0-9a-fA-F`.
#[inline]
@@ -23,2 +26,3 @@
+/// Recognises an octal digit, `0-7`.
#[inline]
@@ -27 +31,13 @@
}
+
+/// Recognises a space or tab.
+#[inline]
+pub fn space(term: u8) -> bool {
+ term == b' ' || term == b'\t'
+}
+
+/// Recognises a space, tab, line feed, or carriage returns.
+#[inline]
+pub fn multispace(term: u8) -> bool {
+ space(term) || term == b'\n' || term == b'\r'
+}
|
--- a/src/char_class.rs
+++ b/src/char_class.rs
@@ ... @@
-
+/// Recognises an alphabetic character, `a-zA-Z`.
#[inline]
@@ ... @@
+/// Recognises a decimal digit, `0-9`.
#[inline]
@@ ... @@
+/// Recognises an alphanumeric character, `a-zA-Z0-9`.
#[inline]
@@ ... @@
+/// Recognises a hexadecimal digit, `0-9a-fA-F`.
#[inline]
@@ ... @@
+/// Recognises an octal digit, `0-7`.
#[inline]
@@ ... @@
}
+
+/// Recognises a space or tab.
+#[inline]
+pub fn space(term: u8) -> bool {
+ term == b' ' || term == b'\t'
+}
+
+/// Recognises a space, tab, line feed, or carriage returns.
+#[inline]
+pub fn multispace(term: u8) -> bool {
+ space(term) || term == b'\n' || term == b'\r'
+}
|
--- a/src/char_class.rs
+++ b/src/char_class.rs
@@ -1,2 +1,2 @@
DEL
ADD /// Recognises an alphabetic character, `a-zA-Z`.
CON #[inline]
@@ -6,2 +6,3 @@
CON
ADD /// Recognises a decimal digit, `0-9`.
CON #[inline]
@@ -11,2 +12,3 @@
CON
ADD /// Recognises an alphanumeric character, `a-zA-Z0-9`.
CON #[inline]
@@ -16,2 +18,3 @@
CON
ADD /// Recognises a hexadecimal digit, `0-9a-fA-F`.
CON #[inline]
@@ -23,2 +26,3 @@
CON
ADD /// Recognises an octal digit, `0-7`.
CON #[inline]
@@ -27 +31,13 @@
CON }
ADD
ADD /// Recognises a space or tab.
ADD #[inline]
ADD pub fn space(term: u8) -> bool {
ADD term == b' ' || term == b'\t'
ADD }
ADD
ADD /// Recognises a space, tab, line feed, or carriage returns.
ADD #[inline]
ADD pub fn multispace(term: u8) -> bool {
ADD space(term) || term == b'\n' || term == b'\r'
ADD }
|
<<<<<<< SEARCH
#[inline]
pub fn alpha(term: u8) -> bool {
(term >= 0x41 && term <= 0x5A) || (term >= 0x61 && term <= 0x7A)
}
#[inline]
pub fn digit(term: u8) -> bool {
term >= 0x30 && term <= 0x39
}
#[inline]
pub fn alphanum(term: u8) -> bool {
alpha(term) || digit(term)
}
#[inline]
pub fn hex_digit(term: u8) -> bool {
=======
/// Recognises an alphabetic character, `a-zA-Z`.
#[inline]
pub fn alpha(term: u8) -> bool {
(term >= 0x41 && term <= 0x5A) || (term >= 0x61 && term <= 0x7A)
}
/// Recognises a decimal digit, `0-9`.
#[inline]
pub fn digit(term: u8) -> bool {
term >= 0x30 && term <= 0x39
}
/// Recognises an alphanumeric character, `a-zA-Z0-9`.
#[inline]
pub fn alphanum(term: u8) -> bool {
alpha(term) || digit(term)
}
/// Recognises a hexadecimal digit, `0-9a-fA-F`.
#[inline]
pub fn hex_digit(term: u8) -> bool {
>>>>>>> REPLACE
<<<<<<< SEARCH
}
#[inline]
pub fn oct_digit(term: u8) -> bool {
term >= 0x30 && term <= 0x37
}
=======
}
/// Recognises an octal digit, `0-7`.
#[inline]
pub fn oct_digit(term: u8) -> bool {
term >= 0x30 && term <= 0x37
}
/// Recognises a space or tab.
#[inline]
pub fn space(term: u8) -> bool {
term == b' ' || term == b'\t'
}
/// Recognises a space, tab, line feed, or carriage returns.
#[inline]
pub fn multispace(term: u8) -> bool {
space(term) || term == b'\n' || term == b'\r'
}
>>>>>>> REPLACE
|
orbit/orbit
|
16a71eca23cf28a7aad2171dad184a5e6bcdf79c
|
src/orbit-server/src/main/kotlin/orbit/server/service/GrpcEndpoint.kt
|
kotlin
|
bsd-3-clause
|
Use NettyServerBuilder instead of ServerBuilder and set keepalive policy.
|
/*
Copyright (C) 2015 - 2019 Electronic Arts Inc. All rights reserved.
This file is part of the Orbit Project <https://www.orbit.cloud>.
See license in LICENSE.
*/
package orbit.server.service
import io.grpc.Server
import io.grpc.ServerBuilder
import mu.KotlinLogging
import orbit.server.mesh.LocalServerInfo
class GrpcEndpoint(
private val serverAuthInterceptor: ServerAuthInterceptor,
private val healthService: HealthService,
private val nodeManagementService: NodeManagementService,
private val addressableManagementService: AddressableManagementService,
private val connectionService: ConnectionService,
private val localServerInfo: LocalServerInfo
) {
private val logger = KotlinLogging.logger { }
private lateinit var server: Server
fun start() {
logger.info("Starting gRPC Endpoint on $localServerInfo.port...")
server = ServerBuilder.forPort(localServerInfo.port)
.intercept(serverAuthInterceptor)
.addService(healthService)
.addService(nodeManagementService)
.addService(addressableManagementService)
.addService(connectionService)
.build()
.start()
logger.info("gRPC Endpoint started on $localServerInfo.port.")
}
fun stop() {
server.shutdownNow().awaitTermination()
}
}
|
/*
Copyright (C) 2015 - 2019 Electronic Arts Inc. All rights reserved.
This file is part of the Orbit Project <https://www.orbit.cloud>.
See license in LICENSE.
*/
package orbit.server.service
import io.grpc.Server
import io.grpc.ServerBuilder
import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder
import mu.KotlinLogging
import orbit.server.mesh.LocalServerInfo
import java.util.concurrent.TimeUnit
class GrpcEndpoint(
private val serverAuthInterceptor: ServerAuthInterceptor,
private val healthService: HealthService,
private val nodeManagementService: NodeManagementService,
private val addressableManagementService: AddressableManagementService,
private val connectionService: ConnectionService,
private val localServerInfo: LocalServerInfo
) {
private val logger = KotlinLogging.logger { }
private lateinit var server: Server
fun start() {
logger.info("Starting gRPC Endpoint on $localServerInfo.port...")
server = NettyServerBuilder.forPort(localServerInfo.port)
.keepAliveTime(500, TimeUnit.MILLISECONDS)
.keepAliveTimeout(10, TimeUnit.SECONDS)
.permitKeepAliveWithoutCalls(true)
.permitKeepAliveTime(1000, TimeUnit.MILLISECONDS)
.intercept(serverAuthInterceptor)
.addService(healthService)
.addService(nodeManagementService)
.addService(addressableManagementService)
.addService(connectionService)
.build()
.start()
logger.info("gRPC Endpoint started on $localServerInfo.port.")
}
fun stop() {
server.shutdownNow().awaitTermination()
}
}
| 7
| 1
| 2
|
mixed
|
--- a/src/orbit-server/src/main/kotlin/orbit/server/service/GrpcEndpoint.kt
+++ b/src/orbit-server/src/main/kotlin/orbit/server/service/GrpcEndpoint.kt
@@ -10,4 +10,6 @@
import io.grpc.ServerBuilder
+import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder
import mu.KotlinLogging
import orbit.server.mesh.LocalServerInfo
+import java.util.concurrent.TimeUnit
@@ -27,3 +29,7 @@
- server = ServerBuilder.forPort(localServerInfo.port)
+ server = NettyServerBuilder.forPort(localServerInfo.port)
+ .keepAliveTime(500, TimeUnit.MILLISECONDS)
+ .keepAliveTimeout(10, TimeUnit.SECONDS)
+ .permitKeepAliveWithoutCalls(true)
+ .permitKeepAliveTime(1000, TimeUnit.MILLISECONDS)
.intercept(serverAuthInterceptor)
|
--- a/src/orbit-server/src/main/kotlin/orbit/server/service/GrpcEndpoint.kt
+++ b/src/orbit-server/src/main/kotlin/orbit/server/service/GrpcEndpoint.kt
@@ ... @@
import io.grpc.ServerBuilder
+import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder
import mu.KotlinLogging
import orbit.server.mesh.LocalServerInfo
+import java.util.concurrent.TimeUnit
@@ ... @@
- server = ServerBuilder.forPort(localServerInfo.port)
+ server = NettyServerBuilder.forPort(localServerInfo.port)
+ .keepAliveTime(500, TimeUnit.MILLISECONDS)
+ .keepAliveTimeout(10, TimeUnit.SECONDS)
+ .permitKeepAliveWithoutCalls(true)
+ .permitKeepAliveTime(1000, TimeUnit.MILLISECONDS)
.intercept(serverAuthInterceptor)
|
--- a/src/orbit-server/src/main/kotlin/orbit/server/service/GrpcEndpoint.kt
+++ b/src/orbit-server/src/main/kotlin/orbit/server/service/GrpcEndpoint.kt
@@ -10,4 +10,6 @@
CON import io.grpc.ServerBuilder
ADD import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder
CON import mu.KotlinLogging
CON import orbit.server.mesh.LocalServerInfo
ADD import java.util.concurrent.TimeUnit
CON
@@ -27,3 +29,7 @@
CON
DEL server = ServerBuilder.forPort(localServerInfo.port)
ADD server = NettyServerBuilder.forPort(localServerInfo.port)
ADD .keepAliveTime(500, TimeUnit.MILLISECONDS)
ADD .keepAliveTimeout(10, TimeUnit.SECONDS)
ADD .permitKeepAliveWithoutCalls(true)
ADD .permitKeepAliveTime(1000, TimeUnit.MILLISECONDS)
CON .intercept(serverAuthInterceptor)
|
<<<<<<< SEARCH
import io.grpc.Server
import io.grpc.ServerBuilder
import mu.KotlinLogging
import orbit.server.mesh.LocalServerInfo
class GrpcEndpoint(
=======
import io.grpc.Server
import io.grpc.ServerBuilder
import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder
import mu.KotlinLogging
import orbit.server.mesh.LocalServerInfo
import java.util.concurrent.TimeUnit
class GrpcEndpoint(
>>>>>>> REPLACE
<<<<<<< SEARCH
logger.info("Starting gRPC Endpoint on $localServerInfo.port...")
server = ServerBuilder.forPort(localServerInfo.port)
.intercept(serverAuthInterceptor)
.addService(healthService)
=======
logger.info("Starting gRPC Endpoint on $localServerInfo.port...")
server = NettyServerBuilder.forPort(localServerInfo.port)
.keepAliveTime(500, TimeUnit.MILLISECONDS)
.keepAliveTimeout(10, TimeUnit.SECONDS)
.permitKeepAliveWithoutCalls(true)
.permitKeepAliveTime(1000, TimeUnit.MILLISECONDS)
.intercept(serverAuthInterceptor)
.addService(healthService)
>>>>>>> REPLACE
|
Alweezy/alvin-mutisya-dojo-project
|
8386d7372f9ff8bfad651efe43504746aff19b73
|
app/models/rooms/rooms.py
|
python
|
mit
|
Implement the Room base class
|
from models.people.people import Staff, Fellow
from models.rooms.rooms import Office, LivingSpace
import random
class Dojo(object):
def __init__(self):
self.offices = []
self.livingrooms = []
self.staff = []
self.fellows = []
self.all_rooms = []
self.all_people = []
def get_room(self, rooms):
"""A function to generate a list of random rooms with space.
:param rooms:
:return: room_name
"""
# a room is only available if it's capacity is not exceeded
available_rooms = [room for room in rooms if len(room.occupants) < room.room_capacity]
# return False if all rooms are full
if len(available_rooms) < 1:
return False
# choose a room fro the list of available rooms.
chosen_room = random.choice(available_rooms)
return chosen_room.room_name
def create_room(self, room_name, room_type):
if room_type is 'office':
if room_name not in [room.room_name for room in self.offices]:
room = Office(room_name=room_name, room_type=room_type)
self.offices.append(room)
self.all_rooms.append(room)
return 'An office called' + ' ' + room_name + ' ' + 'has been successfully created'
return 'An office with that name already exists'
if room_type is 'livingspace':
if room_name not in [room.room_name for room in self.livingrooms]:
room = LivingSpace(room_name=room_name, room_type=room_type)
# add object to list( has both room_name and room_type)
self.livingrooms.append(room)
self.all_rooms.append(room)
return 'A room called ' + room_name + ' has been successfully created!'
return 'A living room with that name already exists'
|
import os
import sys
from os import path
sys.path.append(path.dirname(path.dirname(path.abspath(__file__))))
class Room(object):
"""Models the kind of rooms available at Andela,
It forms the base class Room from which OfficeSpace and LivingRoom inherit"""
def __init__(self, room_name, room_type, room_capacity):
"""Initializes the base class Room
:param room_name: A string representing the name of the room
:param room_type: A string representing the type of room, whether office or residential
:param room_capacity: An integer representing the amount of space per room.
"""
self.room_name = room_name
self.room_type = room_type
self.room_capacity = room_capacity
self.occupants = []
| 17
| 42
| 1
|
mixed
|
--- a/app/models/rooms/rooms.py
+++ b/app/models/rooms/rooms.py
@@ -1,45 +1,20 @@
-from models.people.people import Staff, Fellow
-from models.rooms.rooms import Office, LivingSpace
-import random
+import os
+import sys
+from os import path
+sys.path.append(path.dirname(path.dirname(path.abspath(__file__))))
-class Dojo(object):
- def __init__(self):
- self.offices = []
- self.livingrooms = []
- self.staff = []
- self.fellows = []
- self.all_rooms = []
- self.all_people = []
+class Room(object):
+ """Models the kind of rooms available at Andela,
+ It forms the base class Room from which OfficeSpace and LivingRoom inherit"""
+ def __init__(self, room_name, room_type, room_capacity):
+ """Initializes the base class Room
+ :param room_name: A string representing the name of the room
+ :param room_type: A string representing the type of room, whether office or residential
+ :param room_capacity: An integer representing the amount of space per room.
+ """
+ self.room_name = room_name
+ self.room_type = room_type
+ self.room_capacity = room_capacity
+ self.occupants = []
- def get_room(self, rooms):
- """A function to generate a list of random rooms with space.
- :param rooms:
- :return: room_name
- """
- # a room is only available if it's capacity is not exceeded
- available_rooms = [room for room in rooms if len(room.occupants) < room.room_capacity]
- # return False if all rooms are full
- if len(available_rooms) < 1:
- return False
- # choose a room fro the list of available rooms.
- chosen_room = random.choice(available_rooms)
- return chosen_room.room_name
-
- def create_room(self, room_name, room_type):
- if room_type is 'office':
- if room_name not in [room.room_name for room in self.offices]:
- room = Office(room_name=room_name, room_type=room_type)
- self.offices.append(room)
- self.all_rooms.append(room)
- return 'An office called' + ' ' + room_name + ' ' + 'has been successfully created'
- return 'An office with that name already exists'
- if room_type is 'livingspace':
- if room_name not in [room.room_name for room in self.livingrooms]:
- room = LivingSpace(room_name=room_name, room_type=room_type)
- # add object to list( has both room_name and room_type)
- self.livingrooms.append(room)
- self.all_rooms.append(room)
- return 'A room called ' + room_name + ' has been successfully created!'
- return 'A living room with that name already exists'
-
|
--- a/app/models/rooms/rooms.py
+++ b/app/models/rooms/rooms.py
@@ ... @@
-from models.people.people import Staff, Fellow
-from models.rooms.rooms import Office, LivingSpace
-import random
+import os
+import sys
+from os import path
+sys.path.append(path.dirname(path.dirname(path.abspath(__file__))))
-class Dojo(object):
- def __init__(self):
- self.offices = []
- self.livingrooms = []
- self.staff = []
- self.fellows = []
- self.all_rooms = []
- self.all_people = []
+class Room(object):
+ """Models the kind of rooms available at Andela,
+ It forms the base class Room from which OfficeSpace and LivingRoom inherit"""
+ def __init__(self, room_name, room_type, room_capacity):
+ """Initializes the base class Room
+ :param room_name: A string representing the name of the room
+ :param room_type: A string representing the type of room, whether office or residential
+ :param room_capacity: An integer representing the amount of space per room.
+ """
+ self.room_name = room_name
+ self.room_type = room_type
+ self.room_capacity = room_capacity
+ self.occupants = []
- def get_room(self, rooms):
- """A function to generate a list of random rooms with space.
- :param rooms:
- :return: room_name
- """
- # a room is only available if it's capacity is not exceeded
- available_rooms = [room for room in rooms if len(room.occupants) < room.room_capacity]
- # return False if all rooms are full
- if len(available_rooms) < 1:
- return False
- # choose a room fro the list of available rooms.
- chosen_room = random.choice(available_rooms)
- return chosen_room.room_name
-
- def create_room(self, room_name, room_type):
- if room_type is 'office':
- if room_name not in [room.room_name for room in self.offices]:
- room = Office(room_name=room_name, room_type=room_type)
- self.offices.append(room)
- self.all_rooms.append(room)
- return 'An office called' + ' ' + room_name + ' ' + 'has been successfully created'
- return 'An office with that name already exists'
- if room_type is 'livingspace':
- if room_name not in [room.room_name for room in self.livingrooms]:
- room = LivingSpace(room_name=room_name, room_type=room_type)
- # add object to list( has both room_name and room_type)
- self.livingrooms.append(room)
- self.all_rooms.append(room)
- return 'A room called ' + room_name + ' has been successfully created!'
- return 'A living room with that name already exists'
-
|
--- a/app/models/rooms/rooms.py
+++ b/app/models/rooms/rooms.py
@@ -1,45 +1,20 @@
DEL from models.people.people import Staff, Fellow
DEL from models.rooms.rooms import Office, LivingSpace
DEL import random
ADD import os
ADD import sys
ADD from os import path
ADD sys.path.append(path.dirname(path.dirname(path.abspath(__file__))))
CON
CON
DEL class Dojo(object):
DEL def __init__(self):
DEL self.offices = []
DEL self.livingrooms = []
DEL self.staff = []
DEL self.fellows = []
DEL self.all_rooms = []
DEL self.all_people = []
ADD class Room(object):
ADD """Models the kind of rooms available at Andela,
ADD It forms the base class Room from which OfficeSpace and LivingRoom inherit"""
ADD def __init__(self, room_name, room_type, room_capacity):
ADD """Initializes the base class Room
ADD :param room_name: A string representing the name of the room
ADD :param room_type: A string representing the type of room, whether office or residential
ADD :param room_capacity: An integer representing the amount of space per room.
ADD """
ADD self.room_name = room_name
ADD self.room_type = room_type
ADD self.room_capacity = room_capacity
ADD self.occupants = []
CON
DEL def get_room(self, rooms):
DEL """A function to generate a list of random rooms with space.
DEL :param rooms:
DEL :return: room_name
DEL """
DEL # a room is only available if it's capacity is not exceeded
DEL available_rooms = [room for room in rooms if len(room.occupants) < room.room_capacity]
DEL # return False if all rooms are full
DEL if len(available_rooms) < 1:
DEL return False
DEL # choose a room fro the list of available rooms.
DEL chosen_room = random.choice(available_rooms)
DEL return chosen_room.room_name
DEL
DEL def create_room(self, room_name, room_type):
DEL if room_type is 'office':
DEL if room_name not in [room.room_name for room in self.offices]:
DEL room = Office(room_name=room_name, room_type=room_type)
DEL self.offices.append(room)
DEL self.all_rooms.append(room)
DEL return 'An office called' + ' ' + room_name + ' ' + 'has been successfully created'
DEL return 'An office with that name already exists'
DEL if room_type is 'livingspace':
DEL if room_name not in [room.room_name for room in self.livingrooms]:
DEL room = LivingSpace(room_name=room_name, room_type=room_type)
DEL # add object to list( has both room_name and room_type)
DEL self.livingrooms.append(room)
DEL self.all_rooms.append(room)
DEL return 'A room called ' + room_name + ' has been successfully created!'
DEL return 'A living room with that name already exists'
DEL
|
<<<<<<< SEARCH
from models.people.people import Staff, Fellow
from models.rooms.rooms import Office, LivingSpace
import random
class Dojo(object):
def __init__(self):
self.offices = []
self.livingrooms = []
self.staff = []
self.fellows = []
self.all_rooms = []
self.all_people = []
def get_room(self, rooms):
"""A function to generate a list of random rooms with space.
:param rooms:
:return: room_name
"""
# a room is only available if it's capacity is not exceeded
available_rooms = [room for room in rooms if len(room.occupants) < room.room_capacity]
# return False if all rooms are full
if len(available_rooms) < 1:
return False
# choose a room fro the list of available rooms.
chosen_room = random.choice(available_rooms)
return chosen_room.room_name
def create_room(self, room_name, room_type):
if room_type is 'office':
if room_name not in [room.room_name for room in self.offices]:
room = Office(room_name=room_name, room_type=room_type)
self.offices.append(room)
self.all_rooms.append(room)
return 'An office called' + ' ' + room_name + ' ' + 'has been successfully created'
return 'An office with that name already exists'
if room_type is 'livingspace':
if room_name not in [room.room_name for room in self.livingrooms]:
room = LivingSpace(room_name=room_name, room_type=room_type)
# add object to list( has both room_name and room_type)
self.livingrooms.append(room)
self.all_rooms.append(room)
return 'A room called ' + room_name + ' has been successfully created!'
return 'A living room with that name already exists'
=======
import os
import sys
from os import path
sys.path.append(path.dirname(path.dirname(path.abspath(__file__))))
class Room(object):
"""Models the kind of rooms available at Andela,
It forms the base class Room from which OfficeSpace and LivingRoom inherit"""
def __init__(self, room_name, room_type, room_capacity):
"""Initializes the base class Room
:param room_name: A string representing the name of the room
:param room_type: A string representing the type of room, whether office or residential
:param room_capacity: An integer representing the amount of space per room.
"""
self.room_name = room_name
self.room_type = room_type
self.room_capacity = room_capacity
self.occupants = []
>>>>>>> REPLACE
|
beatgammit/rust-lua
|
73b090315a31519693f5fdbdfacb6496f24e2eba
|
tests.rs
|
rust
|
mit
|
Add quick test for lua_error
|
use std::{libc, ptr};
use raw;
use aux;
// implement the same function that luaL_newstate uses, so we can test lua_newstate directly
// FIXME (#10025): We can't define this as `unsafe extern "C"`
extern "C" fn test_alloc(_ud: *mut libc::c_void, ptr: *mut libc::c_void, _osize: libc::size_t,
nsize: libc::size_t) -> *mut libc::c_void {
unsafe {
if nsize == 0 {
libc::free(ptr as *libc::c_void);
ptr::mut_null()
} else {
libc::realloc(ptr, nsize)
}
}
}
#[test]
fn test_lua_newstate() {
unsafe {
let s = raw::lua_newstate(test_alloc, ptr::mut_null());
raw::lua_pushinteger(s, 42);
raw::lua_close(s);
}
}
#[test]
fn test_luaL_newstate() {
unsafe {
let s = aux::raw::luaL_newstate();
raw::lua_pushinteger(s, 42);
raw::lua_close(s);
}
}
|
use std::{libc, ptr};
use raw;
use aux;
// implement the same function that luaL_newstate uses, so we can test lua_newstate directly
// FIXME (#10025): We can't define this as `unsafe extern "C"`
extern "C" fn alloc_helper(_ud: *mut libc::c_void, ptr: *mut libc::c_void, _osize: libc::size_t,
nsize: libc::size_t) -> *mut libc::c_void {
unsafe {
if nsize == 0 {
libc::free(ptr as *libc::c_void);
ptr::mut_null()
} else {
libc::realloc(ptr, nsize)
}
}
}
// panic function should fail!() so Lua doesn't abort
extern "C" fn panic_helper(_S: *mut raw::lua_State) -> libc::c_int {
fail!("lua error");
}
#[test]
fn test_lua_newstate() {
unsafe {
let s = raw::lua_newstate(alloc_helper, ptr::mut_null());
raw::lua_pushinteger(s, 42);
raw::lua_close(s);
}
}
#[test]
fn test_luaL_newstate() {
unsafe {
let s = aux::raw::luaL_newstate();
raw::lua_pushinteger(s, 42);
raw::lua_close(s);
}
}
#[test]
#[should_fail]
fn test_lua_error() {
unsafe {
let s = aux::raw::luaL_newstate();
raw::lua_atpanic(s, panic_helper);
raw::lua_pushinteger(s, 42);
raw::lua_error(s);
}
}
| 18
| 2
| 4
|
mixed
|
--- a/tests.rs
+++ b/tests.rs
@@ -6,3 +6,3 @@
// FIXME (#10025): We can't define this as `unsafe extern "C"`
-extern "C" fn test_alloc(_ud: *mut libc::c_void, ptr: *mut libc::c_void, _osize: libc::size_t,
+extern "C" fn alloc_helper(_ud: *mut libc::c_void, ptr: *mut libc::c_void, _osize: libc::size_t,
nsize: libc::size_t) -> *mut libc::c_void {
@@ -18,2 +18,7 @@
+// panic function should fail!() so Lua doesn't abort
+extern "C" fn panic_helper(_S: *mut raw::lua_State) -> libc::c_int {
+ fail!("lua error");
+}
+
#[test]
@@ -21,3 +26,3 @@
unsafe {
- let s = raw::lua_newstate(test_alloc, ptr::mut_null());
+ let s = raw::lua_newstate(alloc_helper, ptr::mut_null());
raw::lua_pushinteger(s, 42);
@@ -35 +40,12 @@
}
+
+#[test]
+#[should_fail]
+fn test_lua_error() {
+ unsafe {
+ let s = aux::raw::luaL_newstate();
+ raw::lua_atpanic(s, panic_helper);
+ raw::lua_pushinteger(s, 42);
+ raw::lua_error(s);
+ }
+}
|
--- a/tests.rs
+++ b/tests.rs
@@ ... @@
// FIXME (#10025): We can't define this as `unsafe extern "C"`
-extern "C" fn test_alloc(_ud: *mut libc::c_void, ptr: *mut libc::c_void, _osize: libc::size_t,
+extern "C" fn alloc_helper(_ud: *mut libc::c_void, ptr: *mut libc::c_void, _osize: libc::size_t,
nsize: libc::size_t) -> *mut libc::c_void {
@@ ... @@
+// panic function should fail!() so Lua doesn't abort
+extern "C" fn panic_helper(_S: *mut raw::lua_State) -> libc::c_int {
+ fail!("lua error");
+}
+
#[test]
@@ ... @@
unsafe {
- let s = raw::lua_newstate(test_alloc, ptr::mut_null());
+ let s = raw::lua_newstate(alloc_helper, ptr::mut_null());
raw::lua_pushinteger(s, 42);
@@ ... @@
}
+
+#[test]
+#[should_fail]
+fn test_lua_error() {
+ unsafe {
+ let s = aux::raw::luaL_newstate();
+ raw::lua_atpanic(s, panic_helper);
+ raw::lua_pushinteger(s, 42);
+ raw::lua_error(s);
+ }
+}
|
--- a/tests.rs
+++ b/tests.rs
@@ -6,3 +6,3 @@
CON // FIXME (#10025): We can't define this as `unsafe extern "C"`
DEL extern "C" fn test_alloc(_ud: *mut libc::c_void, ptr: *mut libc::c_void, _osize: libc::size_t,
ADD extern "C" fn alloc_helper(_ud: *mut libc::c_void, ptr: *mut libc::c_void, _osize: libc::size_t,
CON nsize: libc::size_t) -> *mut libc::c_void {
@@ -18,2 +18,7 @@
CON
ADD // panic function should fail!() so Lua doesn't abort
ADD extern "C" fn panic_helper(_S: *mut raw::lua_State) -> libc::c_int {
ADD fail!("lua error");
ADD }
ADD
CON #[test]
@@ -21,3 +26,3 @@
CON unsafe {
DEL let s = raw::lua_newstate(test_alloc, ptr::mut_null());
ADD let s = raw::lua_newstate(alloc_helper, ptr::mut_null());
CON raw::lua_pushinteger(s, 42);
@@ -35 +40,12 @@
CON }
ADD
ADD #[test]
ADD #[should_fail]
ADD fn test_lua_error() {
ADD unsafe {
ADD let s = aux::raw::luaL_newstate();
ADD raw::lua_atpanic(s, panic_helper);
ADD raw::lua_pushinteger(s, 42);
ADD raw::lua_error(s);
ADD }
ADD }
|
<<<<<<< SEARCH
// implement the same function that luaL_newstate uses, so we can test lua_newstate directly
// FIXME (#10025): We can't define this as `unsafe extern "C"`
extern "C" fn test_alloc(_ud: *mut libc::c_void, ptr: *mut libc::c_void, _osize: libc::size_t,
nsize: libc::size_t) -> *mut libc::c_void {
unsafe {
=======
// implement the same function that luaL_newstate uses, so we can test lua_newstate directly
// FIXME (#10025): We can't define this as `unsafe extern "C"`
extern "C" fn alloc_helper(_ud: *mut libc::c_void, ptr: *mut libc::c_void, _osize: libc::size_t,
nsize: libc::size_t) -> *mut libc::c_void {
unsafe {
>>>>>>> REPLACE
<<<<<<< SEARCH
}
#[test]
fn test_lua_newstate() {
unsafe {
let s = raw::lua_newstate(test_alloc, ptr::mut_null());
raw::lua_pushinteger(s, 42);
raw::lua_close(s);
=======
}
// panic function should fail!() so Lua doesn't abort
extern "C" fn panic_helper(_S: *mut raw::lua_State) -> libc::c_int {
fail!("lua error");
}
#[test]
fn test_lua_newstate() {
unsafe {
let s = raw::lua_newstate(alloc_helper, ptr::mut_null());
raw::lua_pushinteger(s, 42);
raw::lua_close(s);
>>>>>>> REPLACE
<<<<<<< SEARCH
}
}
=======
}
}
#[test]
#[should_fail]
fn test_lua_error() {
unsafe {
let s = aux::raw::luaL_newstate();
raw::lua_atpanic(s, panic_helper);
raw::lua_pushinteger(s, 42);
raw::lua_error(s);
}
}
>>>>>>> REPLACE
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.