commit
stringlengths 40
40
| old_file
stringlengths 4
234
| new_file
stringlengths 4
234
| old_contents
stringlengths 10
3.01k
| new_contents
stringlengths 19
3.38k
| subject
stringlengths 16
736
| message
stringlengths 17
2.63k
| lang
stringclasses 4
values | license
stringclasses 13
values | repos
stringlengths 5
82.6k
| config
stringclasses 4
values | content
stringlengths 134
4.41k
| fuzzy_diff
stringlengths 29
3.44k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
ed0065bdfe5d8e036c79fdc02dae8fe60ed4d2fa
|
dxm/src/main/java/com/custardsource/parfait/dxm/IdentifierSourceSet.java
|
dxm/src/main/java/com/custardsource/parfait/dxm/IdentifierSourceSet.java
|
package com.custardsource.parfait.dxm;
public interface IdentifierSourceSet {
public IdentifierSource instanceDomainSource();
public IdentifierSource instanceSource(String domain);
public IdentifierSource metricSource();
public static IdentifierSourceSet DEFAULT_SET = new IdentifierSourceSet() {
private final IdentifierSource DEFAULT_SOURCE = new HashingIdentifierSource();
@Override
public IdentifierSource metricSource() {
return DEFAULT_SOURCE;
}
@Override
public IdentifierSource instanceSource(String domain) {
return DEFAULT_SOURCE;
}
@Override
public IdentifierSource instanceDomainSource() {
return DEFAULT_SOURCE;
}
};
}
|
package com.custardsource.parfait.dxm;
public interface IdentifierSourceSet {
public IdentifierSource instanceDomainSource();
public IdentifierSource instanceSource(String domain);
public IdentifierSource metricSource();
public static IdentifierSourceSet DEFAULT_SET = new IdentifierSourceSet() {
private final IdentifierSource DEFAULT_SOURCE = new HashingIdentifierSource();
@Override
public IdentifierSource metricSource() {
return DEFAULT_SOURCE;
}
@Override
public IdentifierSource instanceSource(String domain) {
return DEFAULT_SOURCE;
}
@Override
public IdentifierSource instanceDomainSource() {
return DEFAULT_SOURCE;
}
};
/**
* {@link IdentifierSourceSet} which will fail for indoms and metrics, but allow default hashed
* values for Instances
*/
public static IdentifierSourceSet EXPLICIT_SET = new IdentifierSourceSet() {
private final IdentifierSource DEFAULT_SOURCE = new HashingIdentifierSource();
private final IdentifierSource ERROR_SOURCE = new ErrorThrowingIdentifierSource();
@Override
public IdentifierSource metricSource() {
return ERROR_SOURCE;
}
@Override
public IdentifierSource instanceSource(String domain) {
return DEFAULT_SOURCE;
}
@Override
public IdentifierSource instanceDomainSource() {
return ERROR_SOURCE;
}
};
}
|
Add an explicit metric set for the most typical use case (caring about metric + indom identifiers, but not instance ones)
|
Add an explicit metric set for the most typical use case (caring about metric + indom identifiers, but not instance ones)
|
Java
|
apache-2.0
|
performancecopilot/parfait,akshayahn/parfait,performancecopilot/parfait,timols/parfait
|
java
|
## Code Before:
package com.custardsource.parfait.dxm;
public interface IdentifierSourceSet {
public IdentifierSource instanceDomainSource();
public IdentifierSource instanceSource(String domain);
public IdentifierSource metricSource();
public static IdentifierSourceSet DEFAULT_SET = new IdentifierSourceSet() {
private final IdentifierSource DEFAULT_SOURCE = new HashingIdentifierSource();
@Override
public IdentifierSource metricSource() {
return DEFAULT_SOURCE;
}
@Override
public IdentifierSource instanceSource(String domain) {
return DEFAULT_SOURCE;
}
@Override
public IdentifierSource instanceDomainSource() {
return DEFAULT_SOURCE;
}
};
}
## Instruction:
Add an explicit metric set for the most typical use case (caring about metric + indom identifiers, but not instance ones)
## Code After:
package com.custardsource.parfait.dxm;
public interface IdentifierSourceSet {
public IdentifierSource instanceDomainSource();
public IdentifierSource instanceSource(String domain);
public IdentifierSource metricSource();
public static IdentifierSourceSet DEFAULT_SET = new IdentifierSourceSet() {
private final IdentifierSource DEFAULT_SOURCE = new HashingIdentifierSource();
@Override
public IdentifierSource metricSource() {
return DEFAULT_SOURCE;
}
@Override
public IdentifierSource instanceSource(String domain) {
return DEFAULT_SOURCE;
}
@Override
public IdentifierSource instanceDomainSource() {
return DEFAULT_SOURCE;
}
};
/**
* {@link IdentifierSourceSet} which will fail for indoms and metrics, but allow default hashed
* values for Instances
*/
public static IdentifierSourceSet EXPLICIT_SET = new IdentifierSourceSet() {
private final IdentifierSource DEFAULT_SOURCE = new HashingIdentifierSource();
private final IdentifierSource ERROR_SOURCE = new ErrorThrowingIdentifierSource();
@Override
public IdentifierSource metricSource() {
return ERROR_SOURCE;
}
@Override
public IdentifierSource instanceSource(String domain) {
return DEFAULT_SOURCE;
}
@Override
public IdentifierSource instanceDomainSource() {
return ERROR_SOURCE;
}
};
}
|
# ... existing code ...
public IdentifierSource instanceDomainSource();
public IdentifierSource instanceSource(String domain);
public IdentifierSource metricSource();
public static IdentifierSourceSet DEFAULT_SET = new IdentifierSourceSet() {
private final IdentifierSource DEFAULT_SOURCE = new HashingIdentifierSource();
# ... modified code ...
return DEFAULT_SOURCE;
}
};
/**
* {@link IdentifierSourceSet} which will fail for indoms and metrics, but allow default hashed
* values for Instances
*/
public static IdentifierSourceSet EXPLICIT_SET = new IdentifierSourceSet() {
private final IdentifierSource DEFAULT_SOURCE = new HashingIdentifierSource();
private final IdentifierSource ERROR_SOURCE = new ErrorThrowingIdentifierSource();
@Override
public IdentifierSource metricSource() {
return ERROR_SOURCE;
}
@Override
public IdentifierSource instanceSource(String domain) {
return DEFAULT_SOURCE;
}
@Override
public IdentifierSource instanceDomainSource() {
return ERROR_SOURCE;
}
};
}
# ... rest of the code ...
|
f83911b3a3d3cccbb6a9bef2d1995ac0e8bff357
|
spring-content-s3/src/main/java/org/springframework/content/s3/S3ContentId.java
|
spring-content-s3/src/main/java/org/springframework/content/s3/S3ContentId.java
|
package org.springframework.content.s3;
import java.io.Serializable;
public final class S3ContentId implements Serializable {
private String bucket;
private String objectId;
public S3ContentId(String bucket, String objectId) {
this.bucket = bucket;
this.objectId = objectId;
}
public String getBucket() {
return bucket;
}
public void setBucket(String bucket) {
this.bucket = bucket;
}
public String getObjectId() {
return objectId;
}
public void setObjectId(String objectId) {
this.objectId = objectId;
}
@Override
public String toString() {
return "S3ContentId{" +
"bucket='" + bucket + '\'' +
", objectId='" + objectId + '\'' +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
S3ContentId that = (S3ContentId) o;
if (bucket != null ? !bucket.equals(that.bucket) : that.bucket != null) return false;
return objectId != null ? objectId.equals(that.objectId) : that.objectId == null;
}
@Override
public int hashCode() {
int result = bucket != null ? bucket.hashCode() : 0;
result = 31 * result + (objectId != null ? objectId.hashCode() : 0);
return result;
}
}
|
package org.springframework.content.s3;
import org.springframework.util.Assert;
import java.io.Serializable;
public final class S3ContentId implements Serializable {
private String bucket;
private String objectId;
public S3ContentId(String bucket, String objectId) {
Assert.hasText(bucket, "bucket must be specified");
Assert.hasText(objectId, "objectId must be specified");
this.bucket = bucket;
this.objectId = objectId;
}
public String getBucket() {
return bucket;
}
public void setBucket(String bucket) {
this.bucket = bucket;
}
public String getObjectId() {
return objectId;
}
public void setObjectId(String objectId) {
this.objectId = objectId;
}
@Override
public String toString() {
return "S3ContentId{" +
"bucket='" + bucket + '\'' +
", objectId='" + objectId + '\'' +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
S3ContentId that = (S3ContentId) o;
if (bucket != null ? !bucket.equals(that.bucket) : that.bucket != null) return false;
return objectId != null ? objectId.equals(that.objectId) : that.objectId == null;
}
@Override
public int hashCode() {
int result = bucket != null ? bucket.hashCode() : 0;
result = 31 * result + (objectId != null ? objectId.hashCode() : 0);
return result;
}
}
|
Add assertions to ensure only valid s3content ids can be created
|
Add assertions to ensure only valid s3content ids can be created
|
Java
|
apache-2.0
|
paulcwarren/spring-content,paulcwarren/spring-content,paulcwarren/spring-content
|
java
|
## Code Before:
package org.springframework.content.s3;
import java.io.Serializable;
public final class S3ContentId implements Serializable {
private String bucket;
private String objectId;
public S3ContentId(String bucket, String objectId) {
this.bucket = bucket;
this.objectId = objectId;
}
public String getBucket() {
return bucket;
}
public void setBucket(String bucket) {
this.bucket = bucket;
}
public String getObjectId() {
return objectId;
}
public void setObjectId(String objectId) {
this.objectId = objectId;
}
@Override
public String toString() {
return "S3ContentId{" +
"bucket='" + bucket + '\'' +
", objectId='" + objectId + '\'' +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
S3ContentId that = (S3ContentId) o;
if (bucket != null ? !bucket.equals(that.bucket) : that.bucket != null) return false;
return objectId != null ? objectId.equals(that.objectId) : that.objectId == null;
}
@Override
public int hashCode() {
int result = bucket != null ? bucket.hashCode() : 0;
result = 31 * result + (objectId != null ? objectId.hashCode() : 0);
return result;
}
}
## Instruction:
Add assertions to ensure only valid s3content ids can be created
## Code After:
package org.springframework.content.s3;
import org.springframework.util.Assert;
import java.io.Serializable;
public final class S3ContentId implements Serializable {
private String bucket;
private String objectId;
public S3ContentId(String bucket, String objectId) {
Assert.hasText(bucket, "bucket must be specified");
Assert.hasText(objectId, "objectId must be specified");
this.bucket = bucket;
this.objectId = objectId;
}
public String getBucket() {
return bucket;
}
public void setBucket(String bucket) {
this.bucket = bucket;
}
public String getObjectId() {
return objectId;
}
public void setObjectId(String objectId) {
this.objectId = objectId;
}
@Override
public String toString() {
return "S3ContentId{" +
"bucket='" + bucket + '\'' +
", objectId='" + objectId + '\'' +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
S3ContentId that = (S3ContentId) o;
if (bucket != null ? !bucket.equals(that.bucket) : that.bucket != null) return false;
return objectId != null ? objectId.equals(that.objectId) : that.objectId == null;
}
@Override
public int hashCode() {
int result = bucket != null ? bucket.hashCode() : 0;
result = 31 * result + (objectId != null ? objectId.hashCode() : 0);
return result;
}
}
|
...
package org.springframework.content.s3;
import org.springframework.util.Assert;
import java.io.Serializable;
...
private String objectId;
public S3ContentId(String bucket, String objectId) {
Assert.hasText(bucket, "bucket must be specified");
Assert.hasText(objectId, "objectId must be specified");
this.bucket = bucket;
this.objectId = objectId;
}
...
|
099aa79ca167f5d0842f03130a3237809be305dc
|
extensions/hibernate-validator/deployment/src/test/java/io/quarkus/hibernate/validator/test/config/ConfigMappingValidatorTest.java
|
extensions/hibernate-validator/deployment/src/test/java/io/quarkus/hibernate/validator/test/config/ConfigMappingValidatorTest.java
|
package io.quarkus.hibernate.validator.test.config;
import static org.junit.jupiter.api.Assertions.assertThrows;
import javax.inject.Inject;
import javax.validation.constraints.Max;
import org.eclipse.microprofile.config.Config;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.StringAsset;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import io.quarkus.test.QuarkusUnitTest;
import io.smallrye.config.ConfigMapping;
import io.smallrye.config.ConfigValidationException;
import io.smallrye.config.SmallRyeConfig;
public class ConfigMappingValidatorTest {
@RegisterExtension
static final QuarkusUnitTest UNIT_TEST = new QuarkusUnitTest().setArchiveProducer(
() -> ShrinkWrap.create(JavaArchive.class)
.addAsResource(new StringAsset("server.host=localhost\n"), "application.properties"));
@Inject
Config config;
@Test
void validator() {
assertThrows(ConfigValidationException.class,
() -> config.unwrap(SmallRyeConfig.class).getConfigMapping(Server.class),
"server.host must be less than or equal to 3");
}
@ConfigMapping(prefix = "server")
public interface Server {
@Max(3)
String host();
}
}
|
package io.quarkus.hibernate.validator.test.config;
import static org.junit.jupiter.api.Assertions.assertThrows;
import javax.inject.Inject;
import javax.validation.constraints.Max;
import org.eclipse.microprofile.config.Config;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.StringAsset;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import io.quarkus.test.QuarkusUnitTest;
import io.smallrye.config.ConfigMapping;
import io.smallrye.config.ConfigValidationException;
import io.smallrye.config.SmallRyeConfig;
public class ConfigMappingValidatorTest {
@RegisterExtension
static final QuarkusUnitTest UNIT_TEST = new QuarkusUnitTest().setArchiveProducer(
() -> ShrinkWrap.create(JavaArchive.class)
.addAsResource(new StringAsset("validator.server.host=localhost\n"), "application.properties"));
@Inject
Config config;
@Test
void validator() {
assertThrows(ConfigValidationException.class,
() -> config.unwrap(SmallRyeConfig.class).getConfigMapping(Server.class),
"validator.server.host must be less than or equal to 3");
}
@ConfigMapping(prefix = "validator.server")
public interface Server {
@Max(3)
String host();
}
}
|
Rename test configuration property names clashing with maven deploy
|
Rename test configuration property names clashing with maven deploy
|
Java
|
apache-2.0
|
quarkusio/quarkus,quarkusio/quarkus,quarkusio/quarkus,quarkusio/quarkus,quarkusio/quarkus
|
java
|
## Code Before:
package io.quarkus.hibernate.validator.test.config;
import static org.junit.jupiter.api.Assertions.assertThrows;
import javax.inject.Inject;
import javax.validation.constraints.Max;
import org.eclipse.microprofile.config.Config;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.StringAsset;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import io.quarkus.test.QuarkusUnitTest;
import io.smallrye.config.ConfigMapping;
import io.smallrye.config.ConfigValidationException;
import io.smallrye.config.SmallRyeConfig;
public class ConfigMappingValidatorTest {
@RegisterExtension
static final QuarkusUnitTest UNIT_TEST = new QuarkusUnitTest().setArchiveProducer(
() -> ShrinkWrap.create(JavaArchive.class)
.addAsResource(new StringAsset("server.host=localhost\n"), "application.properties"));
@Inject
Config config;
@Test
void validator() {
assertThrows(ConfigValidationException.class,
() -> config.unwrap(SmallRyeConfig.class).getConfigMapping(Server.class),
"server.host must be less than or equal to 3");
}
@ConfigMapping(prefix = "server")
public interface Server {
@Max(3)
String host();
}
}
## Instruction:
Rename test configuration property names clashing with maven deploy
## Code After:
package io.quarkus.hibernate.validator.test.config;
import static org.junit.jupiter.api.Assertions.assertThrows;
import javax.inject.Inject;
import javax.validation.constraints.Max;
import org.eclipse.microprofile.config.Config;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.StringAsset;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import io.quarkus.test.QuarkusUnitTest;
import io.smallrye.config.ConfigMapping;
import io.smallrye.config.ConfigValidationException;
import io.smallrye.config.SmallRyeConfig;
public class ConfigMappingValidatorTest {
@RegisterExtension
static final QuarkusUnitTest UNIT_TEST = new QuarkusUnitTest().setArchiveProducer(
() -> ShrinkWrap.create(JavaArchive.class)
.addAsResource(new StringAsset("validator.server.host=localhost\n"), "application.properties"));
@Inject
Config config;
@Test
void validator() {
assertThrows(ConfigValidationException.class,
() -> config.unwrap(SmallRyeConfig.class).getConfigMapping(Server.class),
"validator.server.host must be less than or equal to 3");
}
@ConfigMapping(prefix = "validator.server")
public interface Server {
@Max(3)
String host();
}
}
|
...
@RegisterExtension
static final QuarkusUnitTest UNIT_TEST = new QuarkusUnitTest().setArchiveProducer(
() -> ShrinkWrap.create(JavaArchive.class)
.addAsResource(new StringAsset("validator.server.host=localhost\n"), "application.properties"));
@Inject
Config config;
...
void validator() {
assertThrows(ConfigValidationException.class,
() -> config.unwrap(SmallRyeConfig.class).getConfigMapping(Server.class),
"validator.server.host must be less than or equal to 3");
}
@ConfigMapping(prefix = "validator.server")
public interface Server {
@Max(3)
String host();
...
|
1263853063be42069368b37a39c871a8b62a972c
|
example/src/main/java/com/jpardogo/android/listbuddies/models/KeyValuePair.java
|
example/src/main/java/com/jpardogo/android/listbuddies/models/KeyValuePair.java
|
package com.jpardogo.android.listbuddies.models;
import android.content.Context;
import android.graphics.Color;
import com.jpardogo.android.listbuddies.R;
import com.jpardogo.android.listbuddies.adapters.CustomizeSpinnersAdapter;
import java.util.Random;
/**
* Created by jpardogo on 22/02/2014.
*/
public class KeyValuePair {
private String key;
private Object value;
public KeyValuePair(String key, Object value) {
this.key = key;
this.value = value;
}
public int getColor(Context context) {
int color = -1;
if (value instanceof CustomizeSpinnersAdapter.OptionTypes) {
switch ((CustomizeSpinnersAdapter.OptionTypes) value) {
case BLACK:
color = context.getResources().getColor(R.color.black);
break;
case RANDOM:
Random rnd = new Random();
color = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256));
break;
}
} else {
throw new ClassCastException("Wrong type of value, the value must be CustomizeSpinnersAdapter.OptionTypes");
}
return color;
}
public String getKey() {
return key;
}
public int getScrollOption() {
return (Integer) value;
}
}
|
package com.jpardogo.android.listbuddies.models;
import android.content.Context;
import com.jpardogo.android.listbuddies.R;
import com.jpardogo.android.listbuddies.adapters.CustomizeSpinnersAdapter;
/**
* Created by jpardogo on 22/02/2014.
*/
public class KeyValuePair {
private String key;
private Object value;
public KeyValuePair(String key, Object value) {
this.key = key;
this.value = value;
}
public int getColor(Context context) {
int color = -1;
if (value instanceof CustomizeSpinnersAdapter.OptionTypes) {
switch ((CustomizeSpinnersAdapter.OptionTypes) value) {
case BLACK:
color = context.getResources().getColor(R.color.black);
break;
case INSET:
color = context.getResources().getColor(R.color.inset);
break;
}
} else {
throw new ClassCastException("Wrong type of value, the value must be CustomizeSpinnersAdapter.OptionTypes");
}
return color;
}
public String getKey() {
return key;
}
public int getScrollOption() {
return (Integer) value;
}
}
|
Change random for inset color
|
Change random for inset color
|
Java
|
apache-2.0
|
jpardogo/ListBuddies,martinelli917/ListBuddies,hgl888/ListBuddies,ajju4455/ListBuddies,tsunli/ListBuddies,qiwx2012/ListBuddies,himanshusoni/ListBuddies,shyamkumarm/ListBuddies,zhp0260/ListBuddies,murugespandian/ListBuddies,tieusangaka/ListBuddies,clg0118/ListBuddies,leasual/ListBuddies,JerryloveEmily/ListBuddies
|
java
|
## Code Before:
package com.jpardogo.android.listbuddies.models;
import android.content.Context;
import android.graphics.Color;
import com.jpardogo.android.listbuddies.R;
import com.jpardogo.android.listbuddies.adapters.CustomizeSpinnersAdapter;
import java.util.Random;
/**
* Created by jpardogo on 22/02/2014.
*/
public class KeyValuePair {
private String key;
private Object value;
public KeyValuePair(String key, Object value) {
this.key = key;
this.value = value;
}
public int getColor(Context context) {
int color = -1;
if (value instanceof CustomizeSpinnersAdapter.OptionTypes) {
switch ((CustomizeSpinnersAdapter.OptionTypes) value) {
case BLACK:
color = context.getResources().getColor(R.color.black);
break;
case RANDOM:
Random rnd = new Random();
color = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256));
break;
}
} else {
throw new ClassCastException("Wrong type of value, the value must be CustomizeSpinnersAdapter.OptionTypes");
}
return color;
}
public String getKey() {
return key;
}
public int getScrollOption() {
return (Integer) value;
}
}
## Instruction:
Change random for inset color
## Code After:
package com.jpardogo.android.listbuddies.models;
import android.content.Context;
import com.jpardogo.android.listbuddies.R;
import com.jpardogo.android.listbuddies.adapters.CustomizeSpinnersAdapter;
/**
* Created by jpardogo on 22/02/2014.
*/
public class KeyValuePair {
private String key;
private Object value;
public KeyValuePair(String key, Object value) {
this.key = key;
this.value = value;
}
public int getColor(Context context) {
int color = -1;
if (value instanceof CustomizeSpinnersAdapter.OptionTypes) {
switch ((CustomizeSpinnersAdapter.OptionTypes) value) {
case BLACK:
color = context.getResources().getColor(R.color.black);
break;
case INSET:
color = context.getResources().getColor(R.color.inset);
break;
}
} else {
throw new ClassCastException("Wrong type of value, the value must be CustomizeSpinnersAdapter.OptionTypes");
}
return color;
}
public String getKey() {
return key;
}
public int getScrollOption() {
return (Integer) value;
}
}
|
...
package com.jpardogo.android.listbuddies.models;
import android.content.Context;
import com.jpardogo.android.listbuddies.R;
import com.jpardogo.android.listbuddies.adapters.CustomizeSpinnersAdapter;
/**
* Created by jpardogo on 22/02/2014.
...
case BLACK:
color = context.getResources().getColor(R.color.black);
break;
case INSET:
color = context.getResources().getColor(R.color.inset);
break;
}
} else {
...
|
23db9892b5bdf8493b86ff5676d5cc29f17588ab
|
Modules/OpenViewCore/include/QVTKFramebufferObjectRenderer.h
|
Modules/OpenViewCore/include/QVTKFramebufferObjectRenderer.h
|
/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#ifndef __QVTKFramebufferObjectRenderer_h
#define __QVTKFramebufferObjectRenderer_h
#include <QQuickFramebufferObject>
#include "QVTKQuickItem.h"
#include <MitkOpenViewCoreExports.h>
class vtkInternalOpenGLRenderWindow;
//! Part of Qml rendering prototype, see QmlMitkRenderWindowItem.
class MITKOPENVIEWCORE_EXPORT QVTKFramebufferObjectRenderer : public QQuickFramebufferObject::Renderer
{
public:
bool m_neverRendered;
bool m_readyToRender;
vtkInternalOpenGLRenderWindow *m_vtkRenderWindow;
QVTKQuickItem *m_vtkQuickItem;
public:
QVTKFramebufferObjectRenderer(vtkInternalOpenGLRenderWindow *rw);
~QVTKFramebufferObjectRenderer();
virtual void synchronize(QQuickFramebufferObject * item);
virtual void render();
QOpenGLFramebufferObject *createFramebufferObject(const QSize &size);
friend class vtkInternalOpenGLRenderWindow;
};
#endif
|
/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#ifndef __QVTKFramebufferObjectRenderer_h
#define __QVTKFramebufferObjectRenderer_h
#include <QQuickFramebufferObject>
#include "QVTKQuickItem.h"
#include <MitkOpenViewCoreExports.h>
class vtkInternalOpenGLRenderWindow;
//! Part of Qml rendering prototype, see QmlMitkRenderWindowItem.
class MITKOPENVIEWCORE_EXPORT QVTKFramebufferObjectRenderer : public QQuickFramebufferObject::Renderer
{
public:
vtkInternalOpenGLRenderWindow *m_vtkRenderWindow;
bool m_neverRendered;
bool m_readyToRender;
QVTKQuickItem *m_vtkQuickItem;
public:
QVTKFramebufferObjectRenderer(vtkInternalOpenGLRenderWindow *rw);
~QVTKFramebufferObjectRenderer();
virtual void synchronize(QQuickFramebufferObject * item);
virtual void render();
QOpenGLFramebufferObject *createFramebufferObject(const QSize &size);
friend class vtkInternalOpenGLRenderWindow;
};
#endif
|
Fix warnings in OpenViewCore module
|
Fix warnings in OpenViewCore module
|
C
|
bsd-3-clause
|
MITK/MITK,fmilano/mitk,MITK/MITK,fmilano/mitk,fmilano/mitk,fmilano/mitk,MITK/MITK,MITK/MITK,fmilano/mitk,fmilano/mitk,MITK/MITK,fmilano/mitk,MITK/MITK
|
c
|
## Code Before:
/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#ifndef __QVTKFramebufferObjectRenderer_h
#define __QVTKFramebufferObjectRenderer_h
#include <QQuickFramebufferObject>
#include "QVTKQuickItem.h"
#include <MitkOpenViewCoreExports.h>
class vtkInternalOpenGLRenderWindow;
//! Part of Qml rendering prototype, see QmlMitkRenderWindowItem.
class MITKOPENVIEWCORE_EXPORT QVTKFramebufferObjectRenderer : public QQuickFramebufferObject::Renderer
{
public:
bool m_neverRendered;
bool m_readyToRender;
vtkInternalOpenGLRenderWindow *m_vtkRenderWindow;
QVTKQuickItem *m_vtkQuickItem;
public:
QVTKFramebufferObjectRenderer(vtkInternalOpenGLRenderWindow *rw);
~QVTKFramebufferObjectRenderer();
virtual void synchronize(QQuickFramebufferObject * item);
virtual void render();
QOpenGLFramebufferObject *createFramebufferObject(const QSize &size);
friend class vtkInternalOpenGLRenderWindow;
};
#endif
## Instruction:
Fix warnings in OpenViewCore module
## Code After:
/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#ifndef __QVTKFramebufferObjectRenderer_h
#define __QVTKFramebufferObjectRenderer_h
#include <QQuickFramebufferObject>
#include "QVTKQuickItem.h"
#include <MitkOpenViewCoreExports.h>
class vtkInternalOpenGLRenderWindow;
//! Part of Qml rendering prototype, see QmlMitkRenderWindowItem.
class MITKOPENVIEWCORE_EXPORT QVTKFramebufferObjectRenderer : public QQuickFramebufferObject::Renderer
{
public:
vtkInternalOpenGLRenderWindow *m_vtkRenderWindow;
bool m_neverRendered;
bool m_readyToRender;
QVTKQuickItem *m_vtkQuickItem;
public:
QVTKFramebufferObjectRenderer(vtkInternalOpenGLRenderWindow *rw);
~QVTKFramebufferObjectRenderer();
virtual void synchronize(QQuickFramebufferObject * item);
virtual void render();
QOpenGLFramebufferObject *createFramebufferObject(const QSize &size);
friend class vtkInternalOpenGLRenderWindow;
};
#endif
|
...
class MITKOPENVIEWCORE_EXPORT QVTKFramebufferObjectRenderer : public QQuickFramebufferObject::Renderer
{
public:
vtkInternalOpenGLRenderWindow *m_vtkRenderWindow;
bool m_neverRendered;
bool m_readyToRender;
QVTKQuickItem *m_vtkQuickItem;
...
|
aa092529bb643eabae45ae051ecd99d6bebb88ea
|
src/som/vmobjects/abstract_object.py
|
src/som/vmobjects/abstract_object.py
|
class AbstractObject(object):
def __init__(self):
pass
def send(self, frame, selector_string, arguments, universe):
# Turn the selector string into a selector
selector = universe.symbol_for(selector_string)
invokable = self.get_class(universe).lookup_invokable(selector)
return invokable.invoke(frame, self, arguments)
def send_does_not_understand(self, frame, selector, arguments, universe):
# Compute the number of arguments
number_of_arguments = selector.get_number_of_signature_arguments()
arguments_array = universe.new_array_with_length(number_of_arguments)
for i in range(0, number_of_arguments):
arguments_array.set_indexable_field(i, arguments[i])
args = [selector, arguments_array]
self.send(frame, "doesNotUnderstand:arguments:", args, universe)
def send_unknown_global(self, frame, global_name, universe):
arguments = [global_name]
self.send(frame, "unknownGlobal:", arguments, universe)
def send_escaped_block(self, frame, block, universe):
arguments = [block]
self.send(frame, "escapedBlock:", arguments, universe)
def get_class(self, universe):
raise NotImplementedError("Subclasses need to implement get_class(universe).")
def is_invokable(self):
return False
def __str__(self):
from som.vm.universe import get_current
return "a " + self.get_class(get_current()).get_name().get_string()
|
class AbstractObject(object):
def __init__(self):
pass
def send(self, frame, selector_string, arguments, universe):
# Turn the selector string into a selector
selector = universe.symbol_for(selector_string)
invokable = self.get_class(universe).lookup_invokable(selector)
return invokable.invoke(frame, self, arguments)
def send_does_not_understand(self, frame, selector, arguments, universe):
# Compute the number of arguments
number_of_arguments = selector.get_number_of_signature_arguments()
arguments_array = universe.new_array_with_length(number_of_arguments)
for i in range(0, number_of_arguments):
arguments_array.set_indexable_field(i, arguments[i])
args = [selector, arguments_array]
return self.send(frame, "doesNotUnderstand:arguments:", args, universe)
def send_unknown_global(self, frame, global_name, universe):
arguments = [global_name]
return self.send(frame, "unknownGlobal:", arguments, universe)
def send_escaped_block(self, frame, block, universe):
arguments = [block]
return self.send(frame, "escapedBlock:", arguments, universe)
def get_class(self, universe):
raise NotImplementedError("Subclasses need to implement get_class(universe).")
def is_invokable(self):
return False
def __str__(self):
from som.vm.universe import get_current
return "a " + self.get_class(get_current()).get_name().get_string()
|
Send methods need to return the result
|
Send methods need to return the result
Signed-off-by: Stefan Marr <[email protected]>
|
Python
|
mit
|
smarr/RTruffleSOM,SOM-st/PySOM,SOM-st/RPySOM,smarr/PySOM,SOM-st/RTruffleSOM,SOM-st/RPySOM,SOM-st/RTruffleSOM,SOM-st/PySOM,smarr/RTruffleSOM,smarr/PySOM
|
python
|
## Code Before:
class AbstractObject(object):
def __init__(self):
pass
def send(self, frame, selector_string, arguments, universe):
# Turn the selector string into a selector
selector = universe.symbol_for(selector_string)
invokable = self.get_class(universe).lookup_invokable(selector)
return invokable.invoke(frame, self, arguments)
def send_does_not_understand(self, frame, selector, arguments, universe):
# Compute the number of arguments
number_of_arguments = selector.get_number_of_signature_arguments()
arguments_array = universe.new_array_with_length(number_of_arguments)
for i in range(0, number_of_arguments):
arguments_array.set_indexable_field(i, arguments[i])
args = [selector, arguments_array]
self.send(frame, "doesNotUnderstand:arguments:", args, universe)
def send_unknown_global(self, frame, global_name, universe):
arguments = [global_name]
self.send(frame, "unknownGlobal:", arguments, universe)
def send_escaped_block(self, frame, block, universe):
arguments = [block]
self.send(frame, "escapedBlock:", arguments, universe)
def get_class(self, universe):
raise NotImplementedError("Subclasses need to implement get_class(universe).")
def is_invokable(self):
return False
def __str__(self):
from som.vm.universe import get_current
return "a " + self.get_class(get_current()).get_name().get_string()
## Instruction:
Send methods need to return the result
Signed-off-by: Stefan Marr <[email protected]>
## Code After:
class AbstractObject(object):
def __init__(self):
pass
def send(self, frame, selector_string, arguments, universe):
# Turn the selector string into a selector
selector = universe.symbol_for(selector_string)
invokable = self.get_class(universe).lookup_invokable(selector)
return invokable.invoke(frame, self, arguments)
def send_does_not_understand(self, frame, selector, arguments, universe):
# Compute the number of arguments
number_of_arguments = selector.get_number_of_signature_arguments()
arguments_array = universe.new_array_with_length(number_of_arguments)
for i in range(0, number_of_arguments):
arguments_array.set_indexable_field(i, arguments[i])
args = [selector, arguments_array]
return self.send(frame, "doesNotUnderstand:arguments:", args, universe)
def send_unknown_global(self, frame, global_name, universe):
arguments = [global_name]
return self.send(frame, "unknownGlobal:", arguments, universe)
def send_escaped_block(self, frame, block, universe):
arguments = [block]
return self.send(frame, "escapedBlock:", arguments, universe)
def get_class(self, universe):
raise NotImplementedError("Subclasses need to implement get_class(universe).")
def is_invokable(self):
return False
def __str__(self):
from som.vm.universe import get_current
return "a " + self.get_class(get_current()).get_name().get_string()
|
// ... existing code ...
arguments_array.set_indexable_field(i, arguments[i])
args = [selector, arguments_array]
return self.send(frame, "doesNotUnderstand:arguments:", args, universe)
def send_unknown_global(self, frame, global_name, universe):
arguments = [global_name]
return self.send(frame, "unknownGlobal:", arguments, universe)
def send_escaped_block(self, frame, block, universe):
arguments = [block]
return self.send(frame, "escapedBlock:", arguments, universe)
def get_class(self, universe):
raise NotImplementedError("Subclasses need to implement get_class(universe).")
// ... rest of the code ...
|
a8d6c1209a737eb760ece69e12348b4bd275dc9f
|
include/ofp/ipv6endpoint.h
|
include/ofp/ipv6endpoint.h
|
namespace ofp { // <namespace ofp>
class IPv6Endpoint {
public:
IPv6Endpoint() = default;
IPv6Endpoint(const IPv6Address &addr, UInt16 port) : addr_{addr}, port_{port} {}
IPv6Endpoint(const std::string &addr, UInt16 port) : addr_{addr}, port_{port} {}
explicit IPv6Endpoint(UInt16 port) : addr_{}, port_{port} {}
bool parse(const std::string &s);
void clear();
bool valid() const { return port_ != 0; }
const IPv6Address &address() const { return addr_; }
UInt16 port() const { return port_; }
void setAddress(const IPv6Address &addr) { addr_ = addr; }
void setPort(UInt16 port) { port_ = port; }
std::string toString() const;
private:
IPv6Address addr_;
UInt16 port_ = 0;
};
} // </namespace ofp>
#endif // OFP_IPV6ENDPOINT_H
|
namespace ofp { // <namespace ofp>
class IPv6Endpoint {
public:
IPv6Endpoint() = default;
IPv6Endpoint(const IPv6Address &addr, UInt16 port) : addr_{addr}, port_{port} {}
IPv6Endpoint(const std::string &addr, UInt16 port) : addr_{addr}, port_{port} {}
explicit IPv6Endpoint(UInt16 port) : addr_{}, port_{port} {}
bool parse(const std::string &s);
void clear();
bool valid() const { return port_ != 0; }
const IPv6Address &address() const { return addr_; }
UInt16 port() const { return port_; }
void setAddress(const IPv6Address &addr) { addr_ = addr; }
void setPort(UInt16 port) { port_ = port; }
std::string toString() const;
private:
IPv6Address addr_;
UInt16 port_ = 0;
};
std::istream &operator>>(std::istream &is, IPv6Endpoint &value);
std::ostream &operator<<(std::ostream &os, const IPv6Endpoint &value);
inline std::istream &operator>>(std::istream &is, IPv6Endpoint &value)
{
std::string str;
is >> str;
if (!value.parse(str)) {
is.setstate(std::ios::failbit);
}
return is;
}
inline std::ostream &operator<<(std::ostream &os, const IPv6Endpoint &value)
{
return os << value.toString();
}
} // </namespace ofp>
#endif // OFP_IPV6ENDPOINT_H
|
Add program options to bridgeofp.
|
Add program options to bridgeofp.
|
C
|
mit
|
byllyfish/oftr,byllyfish/oftr,byllyfish/libofp,byllyfish/oftr,byllyfish/oftr,byllyfish/libofp,byllyfish/libofp,byllyfish/oftr
|
c
|
## Code Before:
namespace ofp { // <namespace ofp>
class IPv6Endpoint {
public:
IPv6Endpoint() = default;
IPv6Endpoint(const IPv6Address &addr, UInt16 port) : addr_{addr}, port_{port} {}
IPv6Endpoint(const std::string &addr, UInt16 port) : addr_{addr}, port_{port} {}
explicit IPv6Endpoint(UInt16 port) : addr_{}, port_{port} {}
bool parse(const std::string &s);
void clear();
bool valid() const { return port_ != 0; }
const IPv6Address &address() const { return addr_; }
UInt16 port() const { return port_; }
void setAddress(const IPv6Address &addr) { addr_ = addr; }
void setPort(UInt16 port) { port_ = port; }
std::string toString() const;
private:
IPv6Address addr_;
UInt16 port_ = 0;
};
} // </namespace ofp>
#endif // OFP_IPV6ENDPOINT_H
## Instruction:
Add program options to bridgeofp.
## Code After:
namespace ofp { // <namespace ofp>
class IPv6Endpoint {
public:
IPv6Endpoint() = default;
IPv6Endpoint(const IPv6Address &addr, UInt16 port) : addr_{addr}, port_{port} {}
IPv6Endpoint(const std::string &addr, UInt16 port) : addr_{addr}, port_{port} {}
explicit IPv6Endpoint(UInt16 port) : addr_{}, port_{port} {}
bool parse(const std::string &s);
void clear();
bool valid() const { return port_ != 0; }
const IPv6Address &address() const { return addr_; }
UInt16 port() const { return port_; }
void setAddress(const IPv6Address &addr) { addr_ = addr; }
void setPort(UInt16 port) { port_ = port; }
std::string toString() const;
private:
IPv6Address addr_;
UInt16 port_ = 0;
};
std::istream &operator>>(std::istream &is, IPv6Endpoint &value);
std::ostream &operator<<(std::ostream &os, const IPv6Endpoint &value);
inline std::istream &operator>>(std::istream &is, IPv6Endpoint &value)
{
std::string str;
is >> str;
if (!value.parse(str)) {
is.setstate(std::ios::failbit);
}
return is;
}
inline std::ostream &operator<<(std::ostream &os, const IPv6Endpoint &value)
{
return os << value.toString();
}
} // </namespace ofp>
#endif // OFP_IPV6ENDPOINT_H
|
...
UInt16 port_ = 0;
};
std::istream &operator>>(std::istream &is, IPv6Endpoint &value);
std::ostream &operator<<(std::ostream &os, const IPv6Endpoint &value);
inline std::istream &operator>>(std::istream &is, IPv6Endpoint &value)
{
std::string str;
is >> str;
if (!value.parse(str)) {
is.setstate(std::ios::failbit);
}
return is;
}
inline std::ostream &operator<<(std::ostream &os, const IPv6Endpoint &value)
{
return os << value.toString();
}
} // </namespace ofp>
#endif // OFP_IPV6ENDPOINT_H
...
|
a95fa658116ce4df9d05681bbf4ef75f6af682c9
|
oscarapi/serializers/login.py
|
oscarapi/serializers/login.py
|
from django.contrib.auth import get_user_model, authenticate
from rest_framework import serializers
from oscarapi.utils import overridable
User = get_user_model()
def field_length(fieldname):
field = next(
field for field in User._meta.fields if field.name == fieldname)
return field.max_length
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = overridable('OSCARAPI_USER_FIELDS', (
'username', 'id', 'date_joined',))
class LoginSerializer(serializers.Serializer):
username = serializers.CharField(
max_length=field_length('username'), required=True)
password = serializers.CharField(
max_length=field_length('password'), required=True)
def validate(self, attrs):
user = authenticate(username=attrs['username'],
password=attrs['password'])
if user is None:
raise serializers.ValidationError('invalid login')
elif not user.is_active:
raise serializers.ValidationError(
'Can not log in as inactive user')
elif user.is_staff and overridable(
'OSCARAPI_BLOCK_ADMIN_API_ACCESS', True):
raise serializers.ValidationError(
'Staff users can not log in via the rest api')
# set instance to the user so we can use this in the view
self.instance = user
return attrs
|
from django.contrib.auth import get_user_model, authenticate
from rest_framework import serializers
from oscarapi.utils import overridable
User = get_user_model()
def field_length(fieldname):
field = next(
field for field in User._meta.fields if field.name == fieldname)
return field.max_length
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = overridable('OSCARAPI_USER_FIELDS', (
User.USERNAME_FIELD, 'id', 'date_joined',))
class LoginSerializer(serializers.Serializer):
username = serializers.CharField(
max_length=field_length(User.USERNAME_FIELD), required=True)
password = serializers.CharField(
max_length=field_length('password'), required=True)
def validate(self, attrs):
user = authenticate(
username=attrs['username'], password=attrs['password'])
if user is None:
raise serializers.ValidationError('invalid login')
elif not user.is_active:
raise serializers.ValidationError(
'Can not log in as inactive user')
elif user.is_staff and overridable(
'OSCARAPI_BLOCK_ADMIN_API_ACCESS', True):
raise serializers.ValidationError(
'Staff users can not log in via the rest api')
# set instance to the user so we can use this in the view
self.instance = user
return attrs
|
Fix LoginSerializer to support custom username fields of custom user models
|
Fix LoginSerializer to support custom username fields of custom user models
|
Python
|
bsd-3-clause
|
crgwbr/django-oscar-api,regulusweb/django-oscar-api
|
python
|
## Code Before:
from django.contrib.auth import get_user_model, authenticate
from rest_framework import serializers
from oscarapi.utils import overridable
User = get_user_model()
def field_length(fieldname):
field = next(
field for field in User._meta.fields if field.name == fieldname)
return field.max_length
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = overridable('OSCARAPI_USER_FIELDS', (
'username', 'id', 'date_joined',))
class LoginSerializer(serializers.Serializer):
username = serializers.CharField(
max_length=field_length('username'), required=True)
password = serializers.CharField(
max_length=field_length('password'), required=True)
def validate(self, attrs):
user = authenticate(username=attrs['username'],
password=attrs['password'])
if user is None:
raise serializers.ValidationError('invalid login')
elif not user.is_active:
raise serializers.ValidationError(
'Can not log in as inactive user')
elif user.is_staff and overridable(
'OSCARAPI_BLOCK_ADMIN_API_ACCESS', True):
raise serializers.ValidationError(
'Staff users can not log in via the rest api')
# set instance to the user so we can use this in the view
self.instance = user
return attrs
## Instruction:
Fix LoginSerializer to support custom username fields of custom user models
## Code After:
from django.contrib.auth import get_user_model, authenticate
from rest_framework import serializers
from oscarapi.utils import overridable
User = get_user_model()
def field_length(fieldname):
field = next(
field for field in User._meta.fields if field.name == fieldname)
return field.max_length
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = overridable('OSCARAPI_USER_FIELDS', (
User.USERNAME_FIELD, 'id', 'date_joined',))
class LoginSerializer(serializers.Serializer):
username = serializers.CharField(
max_length=field_length(User.USERNAME_FIELD), required=True)
password = serializers.CharField(
max_length=field_length('password'), required=True)
def validate(self, attrs):
user = authenticate(
username=attrs['username'], password=attrs['password'])
if user is None:
raise serializers.ValidationError('invalid login')
elif not user.is_active:
raise serializers.ValidationError(
'Can not log in as inactive user')
elif user.is_staff and overridable(
'OSCARAPI_BLOCK_ADMIN_API_ACCESS', True):
raise serializers.ValidationError(
'Staff users can not log in via the rest api')
# set instance to the user so we can use this in the view
self.instance = user
return attrs
|
// ... existing code ...
class Meta:
model = User
fields = overridable('OSCARAPI_USER_FIELDS', (
User.USERNAME_FIELD, 'id', 'date_joined',))
class LoginSerializer(serializers.Serializer):
username = serializers.CharField(
max_length=field_length(User.USERNAME_FIELD), required=True)
password = serializers.CharField(
max_length=field_length('password'), required=True)
def validate(self, attrs):
user = authenticate(
username=attrs['username'], password=attrs['password'])
if user is None:
raise serializers.ValidationError('invalid login')
elif not user.is_active:
// ... rest of the code ...
|
396297fe93c145f65e260b7f5d5e814d1db06be8
|
src/main/java/org/ingrahamrobotics/robottables/util/Platform.java
|
src/main/java/org/ingrahamrobotics/robottables/util/Platform.java
|
package org.ingrahamrobotics.robottables.util;
public class Platform {
private static final Object LOCK = new Object();
private static boolean ready = false;
private static boolean onRobot = false;
public static boolean onRobot() {
synchronized (LOCK) {
if (!ready) {
init();
}
}
return onRobot;
}
private static void init() {
try {
Class.forName("java.util.ArrayList");
onRobot = false;
} catch (ClassNotFoundException ex) {
onRobot = true;
}
// // One of these (or a combination thereof) will let me figure out if we're running on the robot
// System.getProperty("java.version");
// System.getProperty("java.vendor");
// System.getProperty("java.compiler");
// System.getProperty("os.name");
// onRobot = false;
ready = true;
}
}
|
package org.ingrahamrobotics.robottables.util;
public class Platform {
private static final Object LOCK = new Object();
private static boolean ready = false;
private static boolean onRobot = false;
public static boolean onRobot() {
synchronized (LOCK) {
if (!ready) {
init();
}
}
return onRobot;
}
private static void init() {
onRobot = false;
// // One of these (or a combination thereof) will let me figure out if we're running on the robot
// System.getProperty("java.version");
// System.getProperty("java.vendor");
// System.getProperty("java.compiler");
// System.getProperty("os.name");
// onRobot = false;
ready = true;
}
}
|
Remove temporary code to tell if networktables is running on the robot, as it no longer works with the RoboRIO.
|
Remove temporary code to tell if networktables is running on the robot, as it no longer works with the RoboRIO.
|
Java
|
mit
|
FIRST-4030/RobotTables
|
java
|
## Code Before:
package org.ingrahamrobotics.robottables.util;
public class Platform {
private static final Object LOCK = new Object();
private static boolean ready = false;
private static boolean onRobot = false;
public static boolean onRobot() {
synchronized (LOCK) {
if (!ready) {
init();
}
}
return onRobot;
}
private static void init() {
try {
Class.forName("java.util.ArrayList");
onRobot = false;
} catch (ClassNotFoundException ex) {
onRobot = true;
}
// // One of these (or a combination thereof) will let me figure out if we're running on the robot
// System.getProperty("java.version");
// System.getProperty("java.vendor");
// System.getProperty("java.compiler");
// System.getProperty("os.name");
// onRobot = false;
ready = true;
}
}
## Instruction:
Remove temporary code to tell if networktables is running on the robot, as it no longer works with the RoboRIO.
## Code After:
package org.ingrahamrobotics.robottables.util;
public class Platform {
private static final Object LOCK = new Object();
private static boolean ready = false;
private static boolean onRobot = false;
public static boolean onRobot() {
synchronized (LOCK) {
if (!ready) {
init();
}
}
return onRobot;
}
private static void init() {
onRobot = false;
// // One of these (or a combination thereof) will let me figure out if we're running on the robot
// System.getProperty("java.version");
// System.getProperty("java.vendor");
// System.getProperty("java.compiler");
// System.getProperty("os.name");
// onRobot = false;
ready = true;
}
}
|
...
}
private static void init() {
onRobot = false;
// // One of these (or a combination thereof) will let me figure out if we're running on the robot
// System.getProperty("java.version");
// System.getProperty("java.vendor");
...
// System.getProperty("java.compiler");
// System.getProperty("os.name");
// onRobot = false;
ready = true;
}
}
...
|
6420eca5e458f981aa9f506bfa6354eba50e1e49
|
processing/face_detect.py
|
processing/face_detect.py
|
import cv2
class FaceDetector:
def __init__(self, face_cascade_path):
self.faceCascade = cv2.CascadeClassifier(face_cascade_path)
def detect(self, image, scale_factor=1.1, min_neighbors=5, min_size=(30, 30)):
# detect faces in the image
rectangles = self.faceCascade.detectMultiScale(image, scaleFactor=scale_factor,
minNeighbors=min_neighbors, minSize=min_size,
flags=cv2.CASCADE_SCALE_IMAGE)
return rectangles
def HOG(self):
print("HOG still to be implemented")
def removeFace(self, image):
rectangle_dimensions = self.detect(image)
if len(rectangle_dimensions) > 0:
(x, y, w, h) = max(rectangle_dimensions, key=lambda b: (b[2] * b[3]))
# To Do if no face found return error
face = image[y:y + h, x:x + w]
image_copy = image.copy()
image_copy[y:y + h, x:x + w] = 0
return face, image_copy
|
import cv2
class FaceDetector:
def __init__(self, face_cascade_path):
self.faceCascade = cv2.CascadeClassifier(face_cascade_path)
def detect(self, image, scale_factor=1.1, min_neighbors=5, min_size=(30, 30)):
rectangles = self.faceCascade.detectMultiScale(image, scaleFactor=scale_factor,
minNeighbors=min_neighbors, minSize=min_size,
flags=cv2.CASCADE_SCALE_IMAGE)
return rectangles
def HOG(self):
print("HOG still to be implemented")
def removeFace(self, image):
rectangle_dimensions = self.detect(image)
if len(rectangle_dimensions) > 0:
(x, y, w, h) = max(rectangle_dimensions, key=lambda b: (b[2] * b[3]))
# To Do if no face found return error
face = image[y:y + h, x:x + w]
image_copy = image.copy()
image_copy[y:y + h, x:x + w] = 0
return face, image_copy
|
Align Face and Feature Mapping
|
Align Face and Feature Mapping
|
Python
|
bsd-3-clause
|
javaTheHutts/Java-the-Hutts
|
python
|
## Code Before:
import cv2
class FaceDetector:
def __init__(self, face_cascade_path):
self.faceCascade = cv2.CascadeClassifier(face_cascade_path)
def detect(self, image, scale_factor=1.1, min_neighbors=5, min_size=(30, 30)):
# detect faces in the image
rectangles = self.faceCascade.detectMultiScale(image, scaleFactor=scale_factor,
minNeighbors=min_neighbors, minSize=min_size,
flags=cv2.CASCADE_SCALE_IMAGE)
return rectangles
def HOG(self):
print("HOG still to be implemented")
def removeFace(self, image):
rectangle_dimensions = self.detect(image)
if len(rectangle_dimensions) > 0:
(x, y, w, h) = max(rectangle_dimensions, key=lambda b: (b[2] * b[3]))
# To Do if no face found return error
face = image[y:y + h, x:x + w]
image_copy = image.copy()
image_copy[y:y + h, x:x + w] = 0
return face, image_copy
## Instruction:
Align Face and Feature Mapping
## Code After:
import cv2
class FaceDetector:
def __init__(self, face_cascade_path):
self.faceCascade = cv2.CascadeClassifier(face_cascade_path)
def detect(self, image, scale_factor=1.1, min_neighbors=5, min_size=(30, 30)):
rectangles = self.faceCascade.detectMultiScale(image, scaleFactor=scale_factor,
minNeighbors=min_neighbors, minSize=min_size,
flags=cv2.CASCADE_SCALE_IMAGE)
return rectangles
def HOG(self):
print("HOG still to be implemented")
def removeFace(self, image):
rectangle_dimensions = self.detect(image)
if len(rectangle_dimensions) > 0:
(x, y, w, h) = max(rectangle_dimensions, key=lambda b: (b[2] * b[3]))
# To Do if no face found return error
face = image[y:y + h, x:x + w]
image_copy = image.copy()
image_copy[y:y + h, x:x + w] = 0
return face, image_copy
|
// ... existing code ...
self.faceCascade = cv2.CascadeClassifier(face_cascade_path)
def detect(self, image, scale_factor=1.1, min_neighbors=5, min_size=(30, 30)):
rectangles = self.faceCascade.detectMultiScale(image, scaleFactor=scale_factor,
minNeighbors=min_neighbors, minSize=min_size,
flags=cv2.CASCADE_SCALE_IMAGE)
return rectangles
def HOG(self):
// ... rest of the code ...
|
605cce4a8b87c2e92fcdd047383997ab1df0178d
|
src/lib/str-sanitize.c
|
src/lib/str-sanitize.c
|
/* Copyright (c) 2004 Timo Sirainen */
#include "lib.h"
#include "str.h"
#include "str-sanitize.h"
void str_sanitize_append(string_t *dest, const char *src, size_t max_len)
{
const char *p;
for (p = src; *p != '\0'; p++) {
if ((unsigned char)*p < 32)
break;
}
str_append_n(dest, src, (size_t)(p - src));
for (; *p != '\0' && max_len > 0; p++, max_len--) {
if ((unsigned char)*p < 32)
str_append_c(dest, '?');
else
str_append_c(dest, *p);
}
if (*p != '\0') {
str_truncate(dest, str_len(dest)-3);
str_append(dest, "...");
}
}
const char *str_sanitize(const char *src, size_t max_len)
{
string_t *str;
str = t_str_new(I_MIN(max_len, 256));
str_sanitize_append(str, src, max_len);
return str_c(str);
}
|
/* Copyright (c) 2004 Timo Sirainen */
#include "lib.h"
#include "str.h"
#include "str-sanitize.h"
void str_sanitize_append(string_t *dest, const char *src, size_t max_len)
{
const char *p;
for (p = src; *p != '\0'; p++) {
if (((unsigned char)*p & 0x7f) < 32)
break;
}
str_append_n(dest, src, (size_t)(p - src));
for (; *p != '\0' && max_len > 0; p++, max_len--) {
if (((unsigned char)*p & 0x7f) < 32)
str_append_c(dest, '?');
else
str_append_c(dest, *p);
}
if (*p != '\0') {
str_truncate(dest, str_len(dest)-3);
str_append(dest, "...");
}
}
const char *str_sanitize(const char *src, size_t max_len)
{
string_t *str;
str = t_str_new(I_MIN(max_len, 256));
str_sanitize_append(str, src, max_len);
return str_c(str);
}
|
Convert also 0x80..0x9f characters to '?'
|
Convert also 0x80..0x9f characters to '?'
--HG--
branch : HEAD
|
C
|
mit
|
dscho/dovecot,dscho/dovecot,dscho/dovecot,dscho/dovecot,dscho/dovecot
|
c
|
## Code Before:
/* Copyright (c) 2004 Timo Sirainen */
#include "lib.h"
#include "str.h"
#include "str-sanitize.h"
void str_sanitize_append(string_t *dest, const char *src, size_t max_len)
{
const char *p;
for (p = src; *p != '\0'; p++) {
if ((unsigned char)*p < 32)
break;
}
str_append_n(dest, src, (size_t)(p - src));
for (; *p != '\0' && max_len > 0; p++, max_len--) {
if ((unsigned char)*p < 32)
str_append_c(dest, '?');
else
str_append_c(dest, *p);
}
if (*p != '\0') {
str_truncate(dest, str_len(dest)-3);
str_append(dest, "...");
}
}
const char *str_sanitize(const char *src, size_t max_len)
{
string_t *str;
str = t_str_new(I_MIN(max_len, 256));
str_sanitize_append(str, src, max_len);
return str_c(str);
}
## Instruction:
Convert also 0x80..0x9f characters to '?'
--HG--
branch : HEAD
## Code After:
/* Copyright (c) 2004 Timo Sirainen */
#include "lib.h"
#include "str.h"
#include "str-sanitize.h"
void str_sanitize_append(string_t *dest, const char *src, size_t max_len)
{
const char *p;
for (p = src; *p != '\0'; p++) {
if (((unsigned char)*p & 0x7f) < 32)
break;
}
str_append_n(dest, src, (size_t)(p - src));
for (; *p != '\0' && max_len > 0; p++, max_len--) {
if (((unsigned char)*p & 0x7f) < 32)
str_append_c(dest, '?');
else
str_append_c(dest, *p);
}
if (*p != '\0') {
str_truncate(dest, str_len(dest)-3);
str_append(dest, "...");
}
}
const char *str_sanitize(const char *src, size_t max_len)
{
string_t *str;
str = t_str_new(I_MIN(max_len, 256));
str_sanitize_append(str, src, max_len);
return str_c(str);
}
|
...
const char *p;
for (p = src; *p != '\0'; p++) {
if (((unsigned char)*p & 0x7f) < 32)
break;
}
str_append_n(dest, src, (size_t)(p - src));
for (; *p != '\0' && max_len > 0; p++, max_len--) {
if (((unsigned char)*p & 0x7f) < 32)
str_append_c(dest, '?');
else
str_append_c(dest, *p);
...
|
8bf9ad277a3177bf974fc0bc4ea6f8fa88ff2796
|
trab1/ServerApp/src/serverapp/DeviceLib.java
|
trab1/ServerApp/src/serverapp/DeviceLib.java
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package serverapp;
import java.util.StringTokenizer;
import Hardware.windmill;
/**
*
* @author André
*/
public class DeviceLib {
private windmill lib;
public DeviceLib() {
//AULA 3 - inicializar as lib
lib = new windmill();
}
protected String callHardware(String content) {
String reply = null;
StringTokenizer st = new StringTokenizer(content, utilities.constants.token);
String operation = st.nextToken();
if (operation.equals("ChangeState")) {
// AULA 3 - Chamar a DLL para mudar o estado
int state = Integer.parseInt(st.nextToken());
String error=lib.errorString();
System.err.println(error); //Deve desaparecer
}
//Aula 3 - Esta parte deve ser removida e a chamada à DLL deve ser feita aqui
System.err.println("ERROR: Impossible to collect data"); //Deve desaparecer
reply = "-1" + utilities.constants.token + //Deve desaparecer
"-1" + utilities.constants.token + //Deve desaparecer
"-1" + utilities.constants.token; //Deve desaparecer
return reply;
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package serverapp;
import java.util.StringTokenizer;
import Hardware.windmill;
/**
*
* @author André
*/
public class DeviceLib {
private windmill lib;
public DeviceLib() {
//AULA 3 - inicializar as lib
lib = new windmill();
}
protected String callHardware(String content) {
String reply = null;
StringTokenizer st = new StringTokenizer(content, utilities.constants.token);
String operation = st.nextToken();
if (operation.equals("ChangeState")) {
// AULA 3 - Chamar a DLL para mudar o estado
int state = Integer.parseInt(st.nextToken());
int rval = lib.turn_on(state);
if(rval==0){
System.err.println("System was already in pretended state!");
}
}
//Aula 3 - Esta parte deve ser removida e a chamada à DLL deve ser feita aqui
//System.err.println("ERROR: Impossible to collect data");
int isOn=lib.is_on();
float power = lib.energy_production();
String err = lib.errorString();
reply = isOn + utilities.constants.token + //Deve desaparecer
power + utilities.constants.token + //Deve desaparecer
err + utilities.constants.token; //Deve desaparecer
return reply;
}
}
|
Update ServerApp :+1: :rocket: ->18
|
Update ServerApp :+1: :rocket: ->18
|
Java
|
mit
|
jmdbo/IS,jmdbo/IS,jmdbo/IS,jmdbo/IS,jmdbo/IS
|
java
|
## Code Before:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package serverapp;
import java.util.StringTokenizer;
import Hardware.windmill;
/**
*
* @author André
*/
public class DeviceLib {
private windmill lib;
public DeviceLib() {
//AULA 3 - inicializar as lib
lib = new windmill();
}
protected String callHardware(String content) {
String reply = null;
StringTokenizer st = new StringTokenizer(content, utilities.constants.token);
String operation = st.nextToken();
if (operation.equals("ChangeState")) {
// AULA 3 - Chamar a DLL para mudar o estado
int state = Integer.parseInt(st.nextToken());
String error=lib.errorString();
System.err.println(error); //Deve desaparecer
}
//Aula 3 - Esta parte deve ser removida e a chamada à DLL deve ser feita aqui
System.err.println("ERROR: Impossible to collect data"); //Deve desaparecer
reply = "-1" + utilities.constants.token + //Deve desaparecer
"-1" + utilities.constants.token + //Deve desaparecer
"-1" + utilities.constants.token; //Deve desaparecer
return reply;
}
}
## Instruction:
Update ServerApp :+1: :rocket: ->18
## Code After:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package serverapp;
import java.util.StringTokenizer;
import Hardware.windmill;
/**
*
* @author André
*/
public class DeviceLib {
private windmill lib;
public DeviceLib() {
//AULA 3 - inicializar as lib
lib = new windmill();
}
protected String callHardware(String content) {
String reply = null;
StringTokenizer st = new StringTokenizer(content, utilities.constants.token);
String operation = st.nextToken();
if (operation.equals("ChangeState")) {
// AULA 3 - Chamar a DLL para mudar o estado
int state = Integer.parseInt(st.nextToken());
int rval = lib.turn_on(state);
if(rval==0){
System.err.println("System was already in pretended state!");
}
}
//Aula 3 - Esta parte deve ser removida e a chamada à DLL deve ser feita aqui
//System.err.println("ERROR: Impossible to collect data");
int isOn=lib.is_on();
float power = lib.energy_production();
String err = lib.errorString();
reply = isOn + utilities.constants.token + //Deve desaparecer
power + utilities.constants.token + //Deve desaparecer
err + utilities.constants.token; //Deve desaparecer
return reply;
}
}
|
...
if (operation.equals("ChangeState")) {
// AULA 3 - Chamar a DLL para mudar o estado
int state = Integer.parseInt(st.nextToken());
int rval = lib.turn_on(state);
if(rval==0){
System.err.println("System was already in pretended state!");
}
}
//Aula 3 - Esta parte deve ser removida e a chamada à DLL deve ser feita aqui
//System.err.println("ERROR: Impossible to collect data");
int isOn=lib.is_on();
float power = lib.energy_production();
String err = lib.errorString();
reply = isOn + utilities.constants.token + //Deve desaparecer
power + utilities.constants.token + //Deve desaparecer
err + utilities.constants.token; //Deve desaparecer
return reply;
}
}
...
|
4ae0fccace6a3b2b640fd58c03fbd07341578acc
|
gen-android-icons.py
|
gen-android-icons.py
|
__author__ = 'Maksim Dmitriev'
import argparse
import os
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('-s', '--source', help='the icon to be resized', required=True)
parser.add_argument('-d', '--dest', help='the directory where resized icons are saved')
parser.add_argument('-f', '--outfile', help='the output file names')
args = parser.parse_args()
source_image = args.source
dest_dir = args.dest
if dest_dir is None:
os.makedirs(os.path.dirname(os.path.realpath(source_image)) + os.sep + 'out', exist_ok=True)
|
__author__ = 'Maksim Dmitriev'
import argparse
import os
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('-s', '--source', help='the icon to be resized', required=True)
parser.add_argument('-d', '--dest', help='the directory where resized icons are saved')
parser.add_argument('-f', '--outfile', help='the output file names')
args = parser.parse_args()
source_image = args.source
dest_dir = args.dest
if dest_dir is None:
dest_dir = os.path.join(os.path.dirname(os.path.realpath(source_image)), 'out')
os.makedirs(dest_dir, exist_ok=True)
dpi_dirs = ['drawable-mdpi', 'drawable-hdpi', 'drawable-xhdpi', 'drawable-xxhdpi']
for dpi_dir in dpi_dirs:
os.makedirs(os.path.join(dest_dir, dpi_dir), exist_ok=True)
|
Use os.path.join instead of +
|
Use os.path.join instead of +
|
Python
|
bsd-3-clause
|
MaksimDmitriev/Python-Scripts
|
python
|
## Code Before:
__author__ = 'Maksim Dmitriev'
import argparse
import os
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('-s', '--source', help='the icon to be resized', required=True)
parser.add_argument('-d', '--dest', help='the directory where resized icons are saved')
parser.add_argument('-f', '--outfile', help='the output file names')
args = parser.parse_args()
source_image = args.source
dest_dir = args.dest
if dest_dir is None:
os.makedirs(os.path.dirname(os.path.realpath(source_image)) + os.sep + 'out', exist_ok=True)
## Instruction:
Use os.path.join instead of +
## Code After:
__author__ = 'Maksim Dmitriev'
import argparse
import os
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('-s', '--source', help='the icon to be resized', required=True)
parser.add_argument('-d', '--dest', help='the directory where resized icons are saved')
parser.add_argument('-f', '--outfile', help='the output file names')
args = parser.parse_args()
source_image = args.source
dest_dir = args.dest
if dest_dir is None:
dest_dir = os.path.join(os.path.dirname(os.path.realpath(source_image)), 'out')
os.makedirs(dest_dir, exist_ok=True)
dpi_dirs = ['drawable-mdpi', 'drawable-hdpi', 'drawable-xhdpi', 'drawable-xxhdpi']
for dpi_dir in dpi_dirs:
os.makedirs(os.path.join(dest_dir, dpi_dir), exist_ok=True)
|
// ... existing code ...
source_image = args.source
dest_dir = args.dest
if dest_dir is None:
dest_dir = os.path.join(os.path.dirname(os.path.realpath(source_image)), 'out')
os.makedirs(dest_dir, exist_ok=True)
dpi_dirs = ['drawable-mdpi', 'drawable-hdpi', 'drawable-xhdpi', 'drawable-xxhdpi']
for dpi_dir in dpi_dirs:
os.makedirs(os.path.join(dest_dir, dpi_dir), exist_ok=True)
// ... rest of the code ...
|
8ce2882f365f24bcdb4274f78809afdda602083a
|
tests/test_meetup_loto.py
|
tests/test_meetup_loto.py
|
import tests.context
import unittest
from meetup_loto import Loto
class TestMeetupLoto(unittest.TestCase):
def setUp(self):
self.api = FakeApi()
self.loto = Loto(self.api, "Docker-Montreal", 240672864)
def test_meetup_loto_participants(self):
nb_participants = self.loto.number_of_participants()
self.assertEquals(10, nb_participants)
self.assertEquals(0.1, self.loto.current_chances())
def test_meetup_loto_winner(self):
winner = self.loto.draw()
self.assertTrue(winner >= 1 and winner <= 10)
def test_meetup_loto_multiple_draw(self):
winners = []
for i in range(11):
winner = self.loto.draw()
self.assertFalse(winner in winners)
winners.append(winner)
self.assertEquals(0, winners[-1])
class FakeApi:
def get_rsvps(self, meetup_name, event_id):
return [{'member': {'id': 1}}, {'member': {'id': 2}}, {'member': {'id': 3}}, {'member': {'id': 4}}, {'member': {'id': 5}}, {'member': {'id': 6}}, {'member': {'id': 7}}, {'member': {'id': 8}}, {'member': {'id': 9}}, {'member': {'id': 10}}]
|
import tests.context
import unittest
from meetup_loto import Loto
class TestMeetupLoto(unittest.TestCase):
def setUp(self):
self.api = FakeApi()
self.loto = Loto(self.api, "Docker-Montreal", 240672864)
def test_meetup_loto_participants(self):
nb_participants = self.loto.number_of_participants()
self.assertEquals(10, nb_participants)
self.assertEquals(0.1, self.loto.current_chances())
def test_meetup_loto_winner(self):
winner = self.loto.draw()
self.assertTrue(winner >= 1 and winner <= 10)
def test_meetup_loto_multiple_draw(self):
winners = []
for i in range(11):
winner = self.loto.draw()
self.assertFalse(winner in winners)
winners.append(winner)
self.assertEquals(0, winners[-1])
class FakeApi:
def get_rsvps(self, meetup_name, event_id):
return [{'member': {'id':n}} for n in range(1, 11)]
|
Use list comprehensions to generate test data
|
Use list comprehensions to generate test data
|
Python
|
mit
|
ghislainbourgeois/meetup_loto,ghislainbourgeois/meetup_loto,ghislainbourgeois/meetup_loto
|
python
|
## Code Before:
import tests.context
import unittest
from meetup_loto import Loto
class TestMeetupLoto(unittest.TestCase):
def setUp(self):
self.api = FakeApi()
self.loto = Loto(self.api, "Docker-Montreal", 240672864)
def test_meetup_loto_participants(self):
nb_participants = self.loto.number_of_participants()
self.assertEquals(10, nb_participants)
self.assertEquals(0.1, self.loto.current_chances())
def test_meetup_loto_winner(self):
winner = self.loto.draw()
self.assertTrue(winner >= 1 and winner <= 10)
def test_meetup_loto_multiple_draw(self):
winners = []
for i in range(11):
winner = self.loto.draw()
self.assertFalse(winner in winners)
winners.append(winner)
self.assertEquals(0, winners[-1])
class FakeApi:
def get_rsvps(self, meetup_name, event_id):
return [{'member': {'id': 1}}, {'member': {'id': 2}}, {'member': {'id': 3}}, {'member': {'id': 4}}, {'member': {'id': 5}}, {'member': {'id': 6}}, {'member': {'id': 7}}, {'member': {'id': 8}}, {'member': {'id': 9}}, {'member': {'id': 10}}]
## Instruction:
Use list comprehensions to generate test data
## Code After:
import tests.context
import unittest
from meetup_loto import Loto
class TestMeetupLoto(unittest.TestCase):
def setUp(self):
self.api = FakeApi()
self.loto = Loto(self.api, "Docker-Montreal", 240672864)
def test_meetup_loto_participants(self):
nb_participants = self.loto.number_of_participants()
self.assertEquals(10, nb_participants)
self.assertEquals(0.1, self.loto.current_chances())
def test_meetup_loto_winner(self):
winner = self.loto.draw()
self.assertTrue(winner >= 1 and winner <= 10)
def test_meetup_loto_multiple_draw(self):
winners = []
for i in range(11):
winner = self.loto.draw()
self.assertFalse(winner in winners)
winners.append(winner)
self.assertEquals(0, winners[-1])
class FakeApi:
def get_rsvps(self, meetup_name, event_id):
return [{'member': {'id':n}} for n in range(1, 11)]
|
# ... existing code ...
class FakeApi:
def get_rsvps(self, meetup_name, event_id):
return [{'member': {'id':n}} for n in range(1, 11)]
# ... rest of the code ...
|
0e0ba9f727f543e435d71f39ea79eaa7ba1a72a4
|
spotlight/src/main/java/com/takusemba/spotlight/shapes/Circle.java
|
spotlight/src/main/java/com/takusemba/spotlight/shapes/Circle.java
|
package com.takusemba.spotlight.shapes;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PointF;
import android.view.View;
public class Circle extends Shape {
private float mRadius;
public Circle(View view) {
setPoint(view);
this.mRadius = (float) Math.sqrt(Math.pow(view.getWidth(), 2) + Math.pow(view.getHeight(), 2));
}
public Circle(PointF point, float radius) {
this.mPoint = point;
this.mRadius = radius;
}
@Override
public void draw(Canvas canvas, float animValue, Paint paint) {
canvas.drawCircle(mPoint.x, mPoint.y, animValue * mRadius, paint);
}
}
|
package com.takusemba.spotlight.shapes;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PointF;
import android.view.View;
public class Circle extends Shape {
private float mRadius;
public Circle(View view) {
this(view, (float) Math.sqrt(Math.pow(view.getWidth(), 2) + Math.pow(view.getHeight(), 2)));
}
public Circle(View view, float radius) {
setPoint(view);
this.mRadius = radius;
}
public Circle(PointF point, float radius) {
this.mPoint = point;
this.mRadius = radius;
}
@Override
public void draw(Canvas canvas, float animValue, Paint paint) {
canvas.drawCircle(mPoint.x, mPoint.y, animValue * mRadius, paint);
}
}
|
Add custom radius constructor with view
|
Add custom radius constructor with view
|
Java
|
apache-2.0
|
TakuSemba/Spotlight,TakuSemba/Spotlight
|
java
|
## Code Before:
package com.takusemba.spotlight.shapes;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PointF;
import android.view.View;
public class Circle extends Shape {
private float mRadius;
public Circle(View view) {
setPoint(view);
this.mRadius = (float) Math.sqrt(Math.pow(view.getWidth(), 2) + Math.pow(view.getHeight(), 2));
}
public Circle(PointF point, float radius) {
this.mPoint = point;
this.mRadius = radius;
}
@Override
public void draw(Canvas canvas, float animValue, Paint paint) {
canvas.drawCircle(mPoint.x, mPoint.y, animValue * mRadius, paint);
}
}
## Instruction:
Add custom radius constructor with view
## Code After:
package com.takusemba.spotlight.shapes;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PointF;
import android.view.View;
public class Circle extends Shape {
private float mRadius;
public Circle(View view) {
this(view, (float) Math.sqrt(Math.pow(view.getWidth(), 2) + Math.pow(view.getHeight(), 2)));
}
public Circle(View view, float radius) {
setPoint(view);
this.mRadius = radius;
}
public Circle(PointF point, float radius) {
this.mPoint = point;
this.mRadius = radius;
}
@Override
public void draw(Canvas canvas, float animValue, Paint paint) {
canvas.drawCircle(mPoint.x, mPoint.y, animValue * mRadius, paint);
}
}
|
...
private float mRadius;
public Circle(View view) {
this(view, (float) Math.sqrt(Math.pow(view.getWidth(), 2) + Math.pow(view.getHeight(), 2)));
}
public Circle(View view, float radius) {
setPoint(view);
this.mRadius = radius;
}
public Circle(PointF point, float radius) {
...
|
2f084990d919855a4b1e4bb909c607ef91810fba
|
knights/dj.py
|
knights/dj.py
|
from collections import defaultdict
from django.template import TemplateDoesNotExist, TemplateSyntaxError # NOQA
from django.template.backends.base import BaseEngine
from django.template.backends.utils import csrf_input_lazy, csrf_token_lazy
from . import compiler
from . import loader
class KnightsTemplater(BaseEngine):
def __init__(self, params):
params = params.copy()
options = params.pop('OPTIONS').copy()
super(KnightsTemplater, self).__init__(params)
for path in params.get('DIRS', []):
loader.add_path(path)
def from_string(self, template_code):
tmpl = compiler.kompile(template_code)
return Template(tmpl)
def get_template(self, template_name):
tmpl = loader.load_template(template_name)
if tmpl is None:
raise TemplateDoesNotExist(template_name)
return Template(tmpl)
class Template(object):
def __init__(self, template):
self.template = template
def render(self, context=None, request=None):
if context is None:
context = {}
if request is not None:
context['request'] = request
context['csrf_input'] = csrf_input_lazy(request)
context['csrf_token'] = csrf_token_lazy(request)
ctx = defaultdict(str)
ctx.update(context)
return self.template(ctx)
|
from collections import defaultdict
from django.template import TemplateDoesNotExist, TemplateSyntaxError # NOQA
from django.template.backends.base import BaseEngine
from django.template.backends.utils import csrf_input_lazy, csrf_token_lazy
from . import compiler
from . import loader
class KnightsTemplater(BaseEngine):
def __init__(self, params):
params = params.copy()
options = params.pop('OPTIONS').copy()
super(KnightsTemplater, self).__init__(params)
def from_string(self, template_code):
tmpl = compiler.kompile(template_code)
return Template(tmpl)
def get_template(self, template_name):
try:
tmpl = loader.load_template(template_name, self.template_dirs)
except Exception as e:
raise TemplateSyntaxError(e).with_traceback(e.__traceback__)
if tmpl is None:
raise TemplateDoesNotExist(template_name)
return Template(tmpl)
class Template(object):
def __init__(self, template):
self.template = template
def render(self, context=None, request=None):
if context is None:
context = {}
if request is not None:
context['user'] = request.user
context['request'] = request
context['csrf_input'] = csrf_input_lazy(request)
context['csrf_token'] = csrf_token_lazy(request)
ctx = defaultdict(str)
ctx.update(context)
return self.template(ctx)
|
Use built in template dirs list Add user to context
|
Use built in template dirs list
Add user to context
|
Python
|
mit
|
funkybob/knights-templater,funkybob/knights-templater
|
python
|
## Code Before:
from collections import defaultdict
from django.template import TemplateDoesNotExist, TemplateSyntaxError # NOQA
from django.template.backends.base import BaseEngine
from django.template.backends.utils import csrf_input_lazy, csrf_token_lazy
from . import compiler
from . import loader
class KnightsTemplater(BaseEngine):
def __init__(self, params):
params = params.copy()
options = params.pop('OPTIONS').copy()
super(KnightsTemplater, self).__init__(params)
for path in params.get('DIRS', []):
loader.add_path(path)
def from_string(self, template_code):
tmpl = compiler.kompile(template_code)
return Template(tmpl)
def get_template(self, template_name):
tmpl = loader.load_template(template_name)
if tmpl is None:
raise TemplateDoesNotExist(template_name)
return Template(tmpl)
class Template(object):
def __init__(self, template):
self.template = template
def render(self, context=None, request=None):
if context is None:
context = {}
if request is not None:
context['request'] = request
context['csrf_input'] = csrf_input_lazy(request)
context['csrf_token'] = csrf_token_lazy(request)
ctx = defaultdict(str)
ctx.update(context)
return self.template(ctx)
## Instruction:
Use built in template dirs list
Add user to context
## Code After:
from collections import defaultdict
from django.template import TemplateDoesNotExist, TemplateSyntaxError # NOQA
from django.template.backends.base import BaseEngine
from django.template.backends.utils import csrf_input_lazy, csrf_token_lazy
from . import compiler
from . import loader
class KnightsTemplater(BaseEngine):
def __init__(self, params):
params = params.copy()
options = params.pop('OPTIONS').copy()
super(KnightsTemplater, self).__init__(params)
def from_string(self, template_code):
tmpl = compiler.kompile(template_code)
return Template(tmpl)
def get_template(self, template_name):
try:
tmpl = loader.load_template(template_name, self.template_dirs)
except Exception as e:
raise TemplateSyntaxError(e).with_traceback(e.__traceback__)
if tmpl is None:
raise TemplateDoesNotExist(template_name)
return Template(tmpl)
class Template(object):
def __init__(self, template):
self.template = template
def render(self, context=None, request=None):
if context is None:
context = {}
if request is not None:
context['user'] = request.user
context['request'] = request
context['csrf_input'] = csrf_input_lazy(request)
context['csrf_token'] = csrf_token_lazy(request)
ctx = defaultdict(str)
ctx.update(context)
return self.template(ctx)
|
// ... existing code ...
super(KnightsTemplater, self).__init__(params)
def from_string(self, template_code):
tmpl = compiler.kompile(template_code)
return Template(tmpl)
def get_template(self, template_name):
try:
tmpl = loader.load_template(template_name, self.template_dirs)
except Exception as e:
raise TemplateSyntaxError(e).with_traceback(e.__traceback__)
if tmpl is None:
raise TemplateDoesNotExist(template_name)
return Template(tmpl)
// ... modified code ...
if context is None:
context = {}
if request is not None:
context['user'] = request.user
context['request'] = request
context['csrf_input'] = csrf_input_lazy(request)
context['csrf_token'] = csrf_token_lazy(request)
// ... rest of the code ...
|
097d6ccf7da44013c6d28fea7dce23708b77a044
|
tile.h
|
tile.h
|
struct pool;
void deserialize_int(char **f, int *n);
struct pool_val *deserialize_string(char **f, struct pool *p, int type);
struct index {
unsigned long long index;
long long fpos;
int maxzoom;
};
long long write_tile(struct index *start, struct index *end, char *metabase, unsigned *file_bbox, int z, unsigned x, unsigned y, int detail, int basezoom, struct pool *file_keys, char *layername, sqlite3 *outdb, double droprate, int buffer);
|
struct pool;
void deserialize_int(char **f, int *n);
struct pool_val *deserialize_string(char **f, struct pool *p, int type);
struct index {
unsigned long long index;
long long fpos : 56;
int maxzoom : 8;
};
long long write_tile(struct index *start, struct index *end, char *metabase, unsigned *file_bbox, int z, unsigned x, unsigned y, int detail, int basezoom, struct pool *file_keys, char *layername, sqlite3 *outdb, double droprate, int buffer);
|
Use a bitfield to make the index 2/3 the size, to save some disk churn
|
Use a bitfield to make the index 2/3 the size, to save some disk churn
|
C
|
bsd-2-clause
|
joykuotw/tippecanoe,mapbox/tippecanoe,mapbox/tippecanoe,joykuotw/tippecanoe,mapbox/tippecanoe,landsurveyorsunited/tippecanoe,mapbox/tippecanoe,landsurveyorsunited/tippecanoe
|
c
|
## Code Before:
struct pool;
void deserialize_int(char **f, int *n);
struct pool_val *deserialize_string(char **f, struct pool *p, int type);
struct index {
unsigned long long index;
long long fpos;
int maxzoom;
};
long long write_tile(struct index *start, struct index *end, char *metabase, unsigned *file_bbox, int z, unsigned x, unsigned y, int detail, int basezoom, struct pool *file_keys, char *layername, sqlite3 *outdb, double droprate, int buffer);
## Instruction:
Use a bitfield to make the index 2/3 the size, to save some disk churn
## Code After:
struct pool;
void deserialize_int(char **f, int *n);
struct pool_val *deserialize_string(char **f, struct pool *p, int type);
struct index {
unsigned long long index;
long long fpos : 56;
int maxzoom : 8;
};
long long write_tile(struct index *start, struct index *end, char *metabase, unsigned *file_bbox, int z, unsigned x, unsigned y, int detail, int basezoom, struct pool *file_keys, char *layername, sqlite3 *outdb, double droprate, int buffer);
|
...
struct index {
unsigned long long index;
long long fpos : 56;
int maxzoom : 8;
};
long long write_tile(struct index *start, struct index *end, char *metabase, unsigned *file_bbox, int z, unsigned x, unsigned y, int detail, int basezoom, struct pool *file_keys, char *layername, sqlite3 *outdb, double droprate, int buffer);
...
|
1448cef25ad3870d43fd2737dcbd60c3b4e2a1b0
|
src/test/java/given/a/spec/with/constructor/parameters/Fixture.java
|
src/test/java/given/a/spec/with/constructor/parameters/Fixture.java
|
package given.a.spec.with.constructor.parameters;
class Fixture {
public static Class<?> getSpecThatRequiresAConstructorParameter() {
class Spec {
@SuppressWarnings("unused")
public Spec(final String something) {}
}
return Spec.class;
}
public static class SomeException extends RuntimeException {
private static final long serialVersionUID = 1L;
public SomeException(final String message) {
super(message);
}
}
}
|
package given.a.spec.with.constructor.parameters;
class Fixture {
public static Class<?> getSpecThatRequiresAConstructorParameter() {
class Spec {
@SuppressWarnings("unused")
public Spec(final String something) {}
}
return Spec.class;
}
}
|
Remove some dead code from test suite
|
Remove some dead code from test suite
|
Java
|
mit
|
greghaskins/spectrum
|
java
|
## Code Before:
package given.a.spec.with.constructor.parameters;
class Fixture {
public static Class<?> getSpecThatRequiresAConstructorParameter() {
class Spec {
@SuppressWarnings("unused")
public Spec(final String something) {}
}
return Spec.class;
}
public static class SomeException extends RuntimeException {
private static final long serialVersionUID = 1L;
public SomeException(final String message) {
super(message);
}
}
}
## Instruction:
Remove some dead code from test suite
## Code After:
package given.a.spec.with.constructor.parameters;
class Fixture {
public static Class<?> getSpecThatRequiresAConstructorParameter() {
class Spec {
@SuppressWarnings("unused")
public Spec(final String something) {}
}
return Spec.class;
}
}
|
# ... existing code ...
return Spec.class;
}
}
# ... rest of the code ...
|
b2803c40b2fcee7ab466c83fc95bb693a28576d0
|
messageboard/views.py
|
messageboard/views.py
|
from django.shortcuts import render
from .models import Message
from .serializers import MessageSerializer
from .permissions import IsOwnerOrReadOnly
from rest_framework import generics, permissions
from rest_framework.permissions import IsAuthenticated
from rest_framework import viewsets
from rest_framework.decorators import list_route
from rest_framework.response import Response
from django.core.files import File
import base64
class MessageViewSet(viewsets.ModelViewSet):
serializer_class = MessageSerializer
permission_classes = (permissions.IsAuthenticated,)
queryset = Message.objects.all()
@list_route(methods=['get'], permission_classes=[permissions.AllowAny])
def all(self, request):
messages = Message.objects.all()
serializer = MessageSerializer(messages, many=True)
return Response(serializer.data)
def perform_create(self, serializer):
photo_file = None
if 'photo' in self.request.data:
photo = base64.b64decode(self.request.data['photo'])
with open('media/img/snapshot.jpg', 'wb') as f:
f.write(photo)
photo_file = File(f, name='snapshot.jpg')
serializer.save(
author=self.request.user,
message=self.request.data['message'],
image=photo_file
)
|
from django.shortcuts import render
from .models import Message
from .serializers import MessageSerializer
from .permissions import IsOwnerOrReadOnly
from rest_framework import generics, permissions
from rest_framework.permissions import IsAuthenticated
from rest_framework import viewsets
from rest_framework.decorators import list_route
from rest_framework.response import Response
from django.core.files import File
from django.core.files.temp import NamedTemporaryFile
import base64
class MessageViewSet(viewsets.ModelViewSet):
serializer_class = MessageSerializer
permission_classes = (permissions.IsAuthenticated,)
queryset = Message.objects.all()
@list_route(methods=['get'], permission_classes=[permissions.AllowAny])
def all(self, request):
messages = Message.objects.all()
serializer = MessageSerializer(messages, many=True)
return Response(serializer.data)
def perform_create(self, serializer):
photo_file = None
if 'photo' in self.request.data:
photo = base64.b64decode(self.request.data['photo'])
img_temp = NamedTemporaryFile(delete=True)
img_temp.write(photo)
img_temp.flush()
photo_file = File(img_temp)
serializer.save(
author=self.request.user,
message=self.request.data['message'],
image=photo_file
)
|
Use temporary file and fix to image save handling
|
Use temporary file and fix to image save handling
|
Python
|
mit
|
DjangoBeer/message-board,DjangoBeer/message-board,fmarco/message-board,DjangoBeer/message-board,fmarco/message-board,fmarco/message-board
|
python
|
## Code Before:
from django.shortcuts import render
from .models import Message
from .serializers import MessageSerializer
from .permissions import IsOwnerOrReadOnly
from rest_framework import generics, permissions
from rest_framework.permissions import IsAuthenticated
from rest_framework import viewsets
from rest_framework.decorators import list_route
from rest_framework.response import Response
from django.core.files import File
import base64
class MessageViewSet(viewsets.ModelViewSet):
serializer_class = MessageSerializer
permission_classes = (permissions.IsAuthenticated,)
queryset = Message.objects.all()
@list_route(methods=['get'], permission_classes=[permissions.AllowAny])
def all(self, request):
messages = Message.objects.all()
serializer = MessageSerializer(messages, many=True)
return Response(serializer.data)
def perform_create(self, serializer):
photo_file = None
if 'photo' in self.request.data:
photo = base64.b64decode(self.request.data['photo'])
with open('media/img/snapshot.jpg', 'wb') as f:
f.write(photo)
photo_file = File(f, name='snapshot.jpg')
serializer.save(
author=self.request.user,
message=self.request.data['message'],
image=photo_file
)
## Instruction:
Use temporary file and fix to image save handling
## Code After:
from django.shortcuts import render
from .models import Message
from .serializers import MessageSerializer
from .permissions import IsOwnerOrReadOnly
from rest_framework import generics, permissions
from rest_framework.permissions import IsAuthenticated
from rest_framework import viewsets
from rest_framework.decorators import list_route
from rest_framework.response import Response
from django.core.files import File
from django.core.files.temp import NamedTemporaryFile
import base64
class MessageViewSet(viewsets.ModelViewSet):
serializer_class = MessageSerializer
permission_classes = (permissions.IsAuthenticated,)
queryset = Message.objects.all()
@list_route(methods=['get'], permission_classes=[permissions.AllowAny])
def all(self, request):
messages = Message.objects.all()
serializer = MessageSerializer(messages, many=True)
return Response(serializer.data)
def perform_create(self, serializer):
photo_file = None
if 'photo' in self.request.data:
photo = base64.b64decode(self.request.data['photo'])
img_temp = NamedTemporaryFile(delete=True)
img_temp.write(photo)
img_temp.flush()
photo_file = File(img_temp)
serializer.save(
author=self.request.user,
message=self.request.data['message'],
image=photo_file
)
|
# ... existing code ...
from rest_framework.response import Response
from django.core.files import File
from django.core.files.temp import NamedTemporaryFile
import base64
# ... modified code ...
photo_file = None
if 'photo' in self.request.data:
photo = base64.b64decode(self.request.data['photo'])
img_temp = NamedTemporaryFile(delete=True)
img_temp.write(photo)
img_temp.flush()
photo_file = File(img_temp)
serializer.save(
author=self.request.user,
message=self.request.data['message'],
# ... rest of the code ...
|
a739a997fc2f76ebaee3d7d855dc5ab9501ffd98
|
app/src/main/java/chat/rocket/android/server/domain/GetChatRoomsInteractor.kt
|
app/src/main/java/chat/rocket/android/server/domain/GetChatRoomsInteractor.kt
|
package chat.rocket.android.server.domain
import chat.rocket.core.model.ChatRoom
import kotlinx.coroutines.experimental.CommonPool
import kotlinx.coroutines.experimental.async
import javax.inject.Inject
class GetChatRoomsInteractor @Inject constructor(private val repository: ChatRoomsRepository) {
fun get(url: String) = repository.get(url)
suspend fun getByName(url: String, name: String): List<ChatRoom> {
val chatRooms = async {
val allChatRooms = repository.get(url)
if (name.isEmpty()) {
return@async allChatRooms
}
return@async allChatRooms.filter {
it.name.contains(name, true)
}
}
return chatRooms.await()
}
/**
* Get a specific room by its id.
*
* @param serverUrl The server url where the room is.
* @param roomId The id of the room to get.
*
* @return The ChatRoom object or null if we couldn't find any.
*/
suspend fun getById(serverUrl: String, roomId: String): ChatRoom? {
return async(CommonPool) {
val allChatRooms = repository.get(serverUrl)
return@async allChatRooms.first {
it.id == roomId
}
}.await()
}
}
|
package chat.rocket.android.server.domain
import chat.rocket.core.model.ChatRoom
import kotlinx.coroutines.experimental.CommonPool
import kotlinx.coroutines.experimental.withContext
import javax.inject.Inject
class GetChatRoomsInteractor @Inject constructor(private val repository: ChatRoomsRepository) {
fun get(url: String) = repository.get(url)
/**
* Get a list of chat rooms that contains the name parameter.
*
* @param url The server url.
* @param name The name of chat room to look for or a chat room that contains this name.
* @return A list of ChatRoom objects with the given name.
*/
suspend fun getByName(url: String, name: String): List<ChatRoom> = withContext(CommonPool) {
val allChatRooms = repository.get(url)
if (name.isEmpty()) {
return@withContext allChatRooms
}
return@withContext allChatRooms.filter {
it.name.contains(name, true)
}
}
/**
* Get a specific room by its id.
*
* @param serverUrl The server url where the room is.
* @param roomId The id of the room to get.
* @return The ChatRoom object or null if we couldn't find any.
*/
suspend fun getById(serverUrl: String, roomId: String): ChatRoom? = withContext(CommonPool) {
val allChatRooms = repository.get(serverUrl)
return@withContext allChatRooms.first {
it.id == roomId
}
}
}
|
Change async/await constructs for withContext
|
Change async/await constructs for withContext
|
Kotlin
|
mit
|
RocketChat/Rocket.Chat.Android,RocketChat/Rocket.Chat.Android.Lily,RocketChat/Rocket.Chat.Android.Lily,RocketChat/Rocket.Chat.Android
|
kotlin
|
## Code Before:
package chat.rocket.android.server.domain
import chat.rocket.core.model.ChatRoom
import kotlinx.coroutines.experimental.CommonPool
import kotlinx.coroutines.experimental.async
import javax.inject.Inject
class GetChatRoomsInteractor @Inject constructor(private val repository: ChatRoomsRepository) {
fun get(url: String) = repository.get(url)
suspend fun getByName(url: String, name: String): List<ChatRoom> {
val chatRooms = async {
val allChatRooms = repository.get(url)
if (name.isEmpty()) {
return@async allChatRooms
}
return@async allChatRooms.filter {
it.name.contains(name, true)
}
}
return chatRooms.await()
}
/**
* Get a specific room by its id.
*
* @param serverUrl The server url where the room is.
* @param roomId The id of the room to get.
*
* @return The ChatRoom object or null if we couldn't find any.
*/
suspend fun getById(serverUrl: String, roomId: String): ChatRoom? {
return async(CommonPool) {
val allChatRooms = repository.get(serverUrl)
return@async allChatRooms.first {
it.id == roomId
}
}.await()
}
}
## Instruction:
Change async/await constructs for withContext
## Code After:
package chat.rocket.android.server.domain
import chat.rocket.core.model.ChatRoom
import kotlinx.coroutines.experimental.CommonPool
import kotlinx.coroutines.experimental.withContext
import javax.inject.Inject
class GetChatRoomsInteractor @Inject constructor(private val repository: ChatRoomsRepository) {
fun get(url: String) = repository.get(url)
/**
* Get a list of chat rooms that contains the name parameter.
*
* @param url The server url.
* @param name The name of chat room to look for or a chat room that contains this name.
* @return A list of ChatRoom objects with the given name.
*/
suspend fun getByName(url: String, name: String): List<ChatRoom> = withContext(CommonPool) {
val allChatRooms = repository.get(url)
if (name.isEmpty()) {
return@withContext allChatRooms
}
return@withContext allChatRooms.filter {
it.name.contains(name, true)
}
}
/**
* Get a specific room by its id.
*
* @param serverUrl The server url where the room is.
* @param roomId The id of the room to get.
* @return The ChatRoom object or null if we couldn't find any.
*/
suspend fun getById(serverUrl: String, roomId: String): ChatRoom? = withContext(CommonPool) {
val allChatRooms = repository.get(serverUrl)
return@withContext allChatRooms.first {
it.id == roomId
}
}
}
|
# ... existing code ...
import chat.rocket.core.model.ChatRoom
import kotlinx.coroutines.experimental.CommonPool
import kotlinx.coroutines.experimental.withContext
import javax.inject.Inject
class GetChatRoomsInteractor @Inject constructor(private val repository: ChatRoomsRepository) {
fun get(url: String) = repository.get(url)
/**
* Get a list of chat rooms that contains the name parameter.
*
* @param url The server url.
* @param name The name of chat room to look for or a chat room that contains this name.
* @return A list of ChatRoom objects with the given name.
*/
suspend fun getByName(url: String, name: String): List<ChatRoom> = withContext(CommonPool) {
val allChatRooms = repository.get(url)
if (name.isEmpty()) {
return@withContext allChatRooms
}
return@withContext allChatRooms.filter {
it.name.contains(name, true)
}
}
/**
# ... modified code ...
*
* @param serverUrl The server url where the room is.
* @param roomId The id of the room to get.
* @return The ChatRoom object or null if we couldn't find any.
*/
suspend fun getById(serverUrl: String, roomId: String): ChatRoom? = withContext(CommonPool) {
val allChatRooms = repository.get(serverUrl)
return@withContext allChatRooms.first {
it.id == roomId
}
}
}
# ... rest of the code ...
|
ae3690300cdf38441720f230a21b10cb1e87b73c
|
Android/Sample/app.main/src/main/java/net/wequick/example/small/app/main/AppContext.java
|
Android/Sample/app.main/src/main/java/net/wequick/example/small/app/main/AppContext.java
|
package net.wequick.example.small.app.main;
import android.app.Application;
import android.util.Log;
/**
* Created by Administrator on 2016/2/17.
*/
public class AppContext extends Application {
public AppContext(){
Log.d("main application","AppContext()");
}
@Override
public void onCreate() {
super.onCreate();
System.out.println(this.getSharedPreferences("small.app-versions", 0).getAll());
Log.d("main application","onCreate()");
}
@Override
public void onTerminate() {
super.onTerminate();
}
}
|
package net.wequick.example.small.app.main;
import android.app.Application;
import android.util.Log;
/**
* Created by Administrator on 2016/2/17.
*/
public class AppContext extends Application {
private static final String TAG = "Main Plugin";
public AppContext() {
Log.d(TAG, "AppContext()");
}
@Override
public void onCreate() {
super.onCreate();
Log.d(TAG, "onCreate()");
// Test shared data
Log.d(TAG, this.getSharedPreferences("small.app-versions", 0).getAll().toString());
// Test resources
String s = this.getString(R.string.action_settings);
Log.d(TAG, s);
}
@Override
public void onTerminate() {
super.onTerminate();
}
}
|
Add sample for using resources in plugin application
|
Add sample for using resources in plugin application
|
Java
|
apache-2.0
|
sailor1861/small_debug,sailor1861/small_debug,wequick/Small,wequick/Small,wequick/Small,wu4321/Small,zhaoya188/Small,wequick/Small,wu4321/Small,wu4321/Small,sailor1861/small_debug,wu4321/Small,wequick/Small,zhaoya188/Small,zhaoya188/Small,sailor1861/small_debug,zhaoya188/Small
|
java
|
## Code Before:
package net.wequick.example.small.app.main;
import android.app.Application;
import android.util.Log;
/**
* Created by Administrator on 2016/2/17.
*/
public class AppContext extends Application {
public AppContext(){
Log.d("main application","AppContext()");
}
@Override
public void onCreate() {
super.onCreate();
System.out.println(this.getSharedPreferences("small.app-versions", 0).getAll());
Log.d("main application","onCreate()");
}
@Override
public void onTerminate() {
super.onTerminate();
}
}
## Instruction:
Add sample for using resources in plugin application
## Code After:
package net.wequick.example.small.app.main;
import android.app.Application;
import android.util.Log;
/**
* Created by Administrator on 2016/2/17.
*/
public class AppContext extends Application {
private static final String TAG = "Main Plugin";
public AppContext() {
Log.d(TAG, "AppContext()");
}
@Override
public void onCreate() {
super.onCreate();
Log.d(TAG, "onCreate()");
// Test shared data
Log.d(TAG, this.getSharedPreferences("small.app-versions", 0).getAll().toString());
// Test resources
String s = this.getString(R.string.action_settings);
Log.d(TAG, s);
}
@Override
public void onTerminate() {
super.onTerminate();
}
}
|
# ... existing code ...
*/
public class AppContext extends Application {
private static final String TAG = "Main Plugin";
public AppContext() {
Log.d(TAG, "AppContext()");
}
@Override
public void onCreate() {
super.onCreate();
Log.d(TAG, "onCreate()");
// Test shared data
Log.d(TAG, this.getSharedPreferences("small.app-versions", 0).getAll().toString());
// Test resources
String s = this.getString(R.string.action_settings);
Log.d(TAG, s);
}
@Override
# ... rest of the code ...
|
07d0cafdf2018e8789e4e0671eb0ccc8bbc5c186
|
contrib/sendmail/mail.local/pathnames.h
|
contrib/sendmail/mail.local/pathnames.h
|
/*-
* Copyright (c) 1998 Sendmail, Inc. All rights reserved.
* Copyright (c) 1990, 1993
* The Regents of the University of California. All rights reserved.
*
* By using this file, you agree to the terms and conditions set
* forth in the LICENSE file which can be found at the top level of
* the sendmail distribution.
*
*
* @(#)pathnames.h 8.5 (Berkeley) 5/19/1998
*/
#include <paths.h>
#define _PATH_LOCTMP "/tmp/local.XXXXXX"
|
/*-
* Copyright (c) 1998 Sendmail, Inc. All rights reserved.
* Copyright (c) 1990, 1993
* The Regents of the University of California. All rights reserved.
*
* By using this file, you agree to the terms and conditions set
* forth in the LICENSE file which can be found at the top level of
* the sendmail distribution.
*
*
* @(#)pathnames.h 8.5 (Berkeley) 5/19/1998
* $FreeBSD$
*/
#include <paths.h>
#define _PATH_LOCTMP "/var/tmp/local.XXXXXX"
|
Change location of temporary file from /tmp to /var/tmp. This is a repeat of an earlier commit which apparently got lost with the last import. It helps solve the frequently reported problem
|
Change location of temporary file from /tmp to /var/tmp. This is a
repeat of an earlier commit which apparently got lost with the last
import. It helps solve the frequently reported problem
pid 4032 (mail.local), uid 0 on /: file system full
(though there appears to be a lot of space) caused by idiots sending
30 MB mail messages.
Most-recently-reported-by: jahanur <[email protected]>
Add $FreeBSD$ so that I can check the file back in.
Rejected-by: CVS
|
C
|
bsd-3-clause
|
jrobhoward/SCADAbase,jrobhoward/SCADAbase,jrobhoward/SCADAbase,jrobhoward/SCADAbase,jrobhoward/SCADAbase,jrobhoward/SCADAbase,jrobhoward/SCADAbase,jrobhoward/SCADAbase,jrobhoward/SCADAbase,jrobhoward/SCADAbase,jrobhoward/SCADAbase
|
c
|
## Code Before:
/*-
* Copyright (c) 1998 Sendmail, Inc. All rights reserved.
* Copyright (c) 1990, 1993
* The Regents of the University of California. All rights reserved.
*
* By using this file, you agree to the terms and conditions set
* forth in the LICENSE file which can be found at the top level of
* the sendmail distribution.
*
*
* @(#)pathnames.h 8.5 (Berkeley) 5/19/1998
*/
#include <paths.h>
#define _PATH_LOCTMP "/tmp/local.XXXXXX"
## Instruction:
Change location of temporary file from /tmp to /var/tmp. This is a
repeat of an earlier commit which apparently got lost with the last
import. It helps solve the frequently reported problem
pid 4032 (mail.local), uid 0 on /: file system full
(though there appears to be a lot of space) caused by idiots sending
30 MB mail messages.
Most-recently-reported-by: jahanur <[email protected]>
Add $FreeBSD$ so that I can check the file back in.
Rejected-by: CVS
## Code After:
/*-
* Copyright (c) 1998 Sendmail, Inc. All rights reserved.
* Copyright (c) 1990, 1993
* The Regents of the University of California. All rights reserved.
*
* By using this file, you agree to the terms and conditions set
* forth in the LICENSE file which can be found at the top level of
* the sendmail distribution.
*
*
* @(#)pathnames.h 8.5 (Berkeley) 5/19/1998
* $FreeBSD$
*/
#include <paths.h>
#define _PATH_LOCTMP "/var/tmp/local.XXXXXX"
|
# ... existing code ...
*
*
* @(#)pathnames.h 8.5 (Berkeley) 5/19/1998
* $FreeBSD$
*/
#include <paths.h>
#define _PATH_LOCTMP "/var/tmp/local.XXXXXX"
# ... rest of the code ...
|
03d4c298add892e603e48ca35b1a5070f407d6ff
|
actions/cloudbolt_plugins/recurring_jobs/remove_.zip_from_tmp.py
|
actions/cloudbolt_plugins/recurring_jobs/remove_.zip_from_tmp.py
|
from common.methods import set_progress
import glob
import os
def run(job, *args, **kwargs):
zip_file_list = glob.glob("/tmp/systemd-private*/tmp/*.zip")
set_progress("Found following zip files in /tmp: {}".format(zip_file_list))
for file in zip_file_list:
set_progress("Removing these files {}".format(file))
os.remove(file)
return "SUCCESS", "", ""
|
from common.methods import set_progress
import glob
import os
import time
def run(job, *args, **kwargs):
zip_file_list = glob.glob("/tmp/systemd-private*/tmp/*.zip")
set_progress("Found following zip files in /tmp: {}".format(zip_file_list))
for file in zip_file_list:
if os.path.getmtime(file) < time.time() - 5 * 60:
set_progress("Removing these files {}".format(file))
os.remove(file)
return "SUCCESS", "", ""
|
Remove only those files that were stored 5 minutes ago.
|
Remove only those files that were stored 5 minutes ago.
[https://cloudbolt.atlassian.net/browse/DEV-12629]
|
Python
|
apache-2.0
|
CloudBoltSoftware/cloudbolt-forge,CloudBoltSoftware/cloudbolt-forge,CloudBoltSoftware/cloudbolt-forge,CloudBoltSoftware/cloudbolt-forge
|
python
|
## Code Before:
from common.methods import set_progress
import glob
import os
def run(job, *args, **kwargs):
zip_file_list = glob.glob("/tmp/systemd-private*/tmp/*.zip")
set_progress("Found following zip files in /tmp: {}".format(zip_file_list))
for file in zip_file_list:
set_progress("Removing these files {}".format(file))
os.remove(file)
return "SUCCESS", "", ""
## Instruction:
Remove only those files that were stored 5 minutes ago.
[https://cloudbolt.atlassian.net/browse/DEV-12629]
## Code After:
from common.methods import set_progress
import glob
import os
import time
def run(job, *args, **kwargs):
zip_file_list = glob.glob("/tmp/systemd-private*/tmp/*.zip")
set_progress("Found following zip files in /tmp: {}".format(zip_file_list))
for file in zip_file_list:
if os.path.getmtime(file) < time.time() - 5 * 60:
set_progress("Removing these files {}".format(file))
os.remove(file)
return "SUCCESS", "", ""
|
...
from common.methods import set_progress
import glob
import os
import time
def run(job, *args, **kwargs):
...
zip_file_list = glob.glob("/tmp/systemd-private*/tmp/*.zip")
set_progress("Found following zip files in /tmp: {}".format(zip_file_list))
for file in zip_file_list:
if os.path.getmtime(file) < time.time() - 5 * 60:
set_progress("Removing these files {}".format(file))
os.remove(file)
return "SUCCESS", "", ""
...
|
ecf71bd004d99b679936e07453f5a938e19f71dc
|
megalist_dataflow/setup.py
|
megalist_dataflow/setup.py
|
import setuptools
setuptools.setup(
name='megalist_dataflow',
version='0.1',
author='Alvaro Stivi',
author_email='[email protected]',
url='https://cse.googlesource.com/solutions/megalist',
install_requires=['googleads==20.0.0', 'google-api-python-client==1.7.9',
'bloom-filter==1.3', 'google-cloud-core==1.0.2',
'google-cloud-datastore==1.9.0'],
packages=setuptools.find_packages(),
)
|
import setuptools
setuptools.setup(
name='megalist_dataflow',
version='0.1',
author='Alvaro Stivi',
author_email='[email protected]',
url='https://cse.googlesource.com/solutions/megalist',
install_requires=['googleads==20.0.0', 'google-api-python-client==1.7.9',
'bloom-filter==1.3', 'google-cloud-core==1.0.2',
'google-cloud-datastore==1.9.0, aiohttp==3.6.2'],
packages=setuptools.find_packages(),
)
|
Add aiohttp as a execution requirement
|
Add aiohttp as a execution requirement
|
Python
|
apache-2.0
|
google/megalista,google/megalista
|
python
|
## Code Before:
import setuptools
setuptools.setup(
name='megalist_dataflow',
version='0.1',
author='Alvaro Stivi',
author_email='[email protected]',
url='https://cse.googlesource.com/solutions/megalist',
install_requires=['googleads==20.0.0', 'google-api-python-client==1.7.9',
'bloom-filter==1.3', 'google-cloud-core==1.0.2',
'google-cloud-datastore==1.9.0'],
packages=setuptools.find_packages(),
)
## Instruction:
Add aiohttp as a execution requirement
## Code After:
import setuptools
setuptools.setup(
name='megalist_dataflow',
version='0.1',
author='Alvaro Stivi',
author_email='[email protected]',
url='https://cse.googlesource.com/solutions/megalist',
install_requires=['googleads==20.0.0', 'google-api-python-client==1.7.9',
'bloom-filter==1.3', 'google-cloud-core==1.0.2',
'google-cloud-datastore==1.9.0, aiohttp==3.6.2'],
packages=setuptools.find_packages(),
)
|
# ... existing code ...
url='https://cse.googlesource.com/solutions/megalist',
install_requires=['googleads==20.0.0', 'google-api-python-client==1.7.9',
'bloom-filter==1.3', 'google-cloud-core==1.0.2',
'google-cloud-datastore==1.9.0, aiohttp==3.6.2'],
packages=setuptools.find_packages(),
)
# ... rest of the code ...
|
fa21fdac87d21a13f5ecd743defa35c44f680010
|
src/random/package-info.java
|
src/random/package-info.java
|
/**
* <b>
* Defines a set of themes for the maps
* in the arena.<br>
* </b>
*
* <p>
* The themes are:
* <ul>
* <li> Continental
* <li> Artical
* <li> Desertic
* <li> Tropical
* </ul>
*
* @see Weather
*/
package random;
|
/**
* <b>
* Defines a set of themes for the maps
* in the arena.<br>
* </b>
*
* <p>
* The themes are:
* <ul>
* <li> Continental
* <li> Artical
* <li> Desertic
* <li> Tropical
* </ul>
*/
package random;
|
Fix in link at @see
|
Fix in link at @see
|
Java
|
apache-2.0
|
renatocf/MAC0242-PROJECT,renatocf/MAC0242-PROJECT,renatocf/MAC0242-PROJECT
|
java
|
## Code Before:
/**
* <b>
* Defines a set of themes for the maps
* in the arena.<br>
* </b>
*
* <p>
* The themes are:
* <ul>
* <li> Continental
* <li> Artical
* <li> Desertic
* <li> Tropical
* </ul>
*
* @see Weather
*/
package random;
## Instruction:
Fix in link at @see
## Code After:
/**
* <b>
* Defines a set of themes for the maps
* in the arena.<br>
* </b>
*
* <p>
* The themes are:
* <ul>
* <li> Continental
* <li> Artical
* <li> Desertic
* <li> Tropical
* </ul>
*/
package random;
|
// ... existing code ...
* <li> Desertic
* <li> Tropical
* </ul>
*/
package random;
// ... rest of the code ...
|
f7b48c9193511f693cc2ec17d46253077d06dcc3
|
LR/lr/lib/__init__.py
|
LR/lr/lib/__init__.py
|
from model_parser import ModelParser, getFileString
__all__=['ModelParser', 'getFileString']
|
'''
Base couchdb threshold change handler class.
Created on August 18, 2011
@author: jpoyau
'''
from model_parser import ModelParser, getFileString
from couch_change_monitor import *
__all__=["ModelParser",
"getFileString",
"MonitorChanges",
"BaseChangeHandler",
"BaseThresholdHandler",
"BaseViewsUpdateHandler"]
|
Add the new change feed module to __all__
|
Add the new change feed module to __all__
|
Python
|
apache-2.0
|
jimklo/LearningRegistry,jimklo/LearningRegistry,jimklo/LearningRegistry,jimklo/LearningRegistry,jimklo/LearningRegistry,LearningRegistry/LearningRegistry,LearningRegistry/LearningRegistry,LearningRegistry/LearningRegistry,LearningRegistry/LearningRegistry,LearningRegistry/LearningRegistry,jimklo/LearningRegistry,LearningRegistry/LearningRegistry,jimklo/LearningRegistry,jimklo/LearningRegistry,LearningRegistry/LearningRegistry,jimklo/LearningRegistry
|
python
|
## Code Before:
from model_parser import ModelParser, getFileString
__all__=['ModelParser', 'getFileString']
## Instruction:
Add the new change feed module to __all__
## Code After:
'''
Base couchdb threshold change handler class.
Created on August 18, 2011
@author: jpoyau
'''
from model_parser import ModelParser, getFileString
from couch_change_monitor import *
__all__=["ModelParser",
"getFileString",
"MonitorChanges",
"BaseChangeHandler",
"BaseThresholdHandler",
"BaseViewsUpdateHandler"]
|
# ... existing code ...
'''
Base couchdb threshold change handler class.
Created on August 18, 2011
@author: jpoyau
'''
from model_parser import ModelParser, getFileString
from couch_change_monitor import *
__all__=["ModelParser",
"getFileString",
"MonitorChanges",
"BaseChangeHandler",
"BaseThresholdHandler",
"BaseViewsUpdateHandler"]
# ... rest of the code ...
|
65b418b8eaa8f57fdd3c8207168451da20b452bf
|
src/python/rgplot/RgChart.py
|
src/python/rgplot/RgChart.py
|
import matplotlib.pyplot as plt
#class RgChart(object):
#__metaclass__ = ABCMeta
class RgChart(object):
def with_grids(self):
self._ax.xaxis.grid(True)
self._ax.yaxis.grid(True)
return self
def save_as(self, filename):
self._create_plot()
self._fig.savefig(filename)
plt.close(self._fig) # close on save to avoid memory issues
def with_ygrid(self):
self._ax.yaxis.grid(True)
return self
def with_title(self, title = None):
if title is None:
plt.title(self._title)
else:
plt.title(title)
return self
def with_xlabel(self, xlabel = None):
if xlabel is None:
plt.xlabel(self._xlabel)
else:
plt.xlabel(xlabel)
return self
def with_ylabel(self, ylabel = None):
if ylabel is None:
plt.ylabel(self._ylabel)
else:
plt.ylabel(ylabel)
return self
def with_ylim(self, lim):
self._ax.set_ylim(lim)
return self
def wo_xticks(self):
self._ax.get_xaxis().set_ticks([])
return self
def wo_yticks(self):
self._ax.get_yaxis().set_ticks([])
return self
def _create_plot(self):
pass
|
import matplotlib.pyplot as plt
#class RgChart(object):
#__metaclass__ = ABCMeta
class RgChart(object):
TITLE_Y_OFFSET = 1.08
def with_grids(self):
self._ax.xaxis.grid(True)
self._ax.yaxis.grid(True)
return self
def save_as(self, filename):
self._create_plot()
self._fig.savefig(filename)
plt.close(self._fig) # close on save to avoid memory issues
def with_ygrid(self):
self._ax.yaxis.grid(True)
return self
def with_title(self, title = None, y_offset = RgChart.TITLE_Y_OFFSET):
if title is None:
plt.title(self._title, y = y_offset)
else:
plt.title(title, y = y_offset)
return self
def with_xlabel(self, xlabel = None):
if xlabel is None:
plt.xlabel(self._xlabel)
else:
plt.xlabel(xlabel)
return self
def with_ylabel(self, ylabel = None):
if ylabel is None:
plt.ylabel(self._ylabel)
else:
plt.ylabel(ylabel)
return self
def with_ylog(self):
self._ax.set_yscale('log')
return self
def with_ylim(self, lim):
self._ax.set_ylim(lim)
return self
def wo_xticks(self):
self._ax.get_xaxis().set_ticks([])
return self
def wo_yticks(self):
self._ax.get_yaxis().set_ticks([])
return self
def _create_plot(self):
pass
|
Add y log option and title offset
|
Add y log option and title offset
|
Python
|
mit
|
vjuranek/rg-offline-plotting,vjuranek/rg-offline-plotting
|
python
|
## Code Before:
import matplotlib.pyplot as plt
#class RgChart(object):
#__metaclass__ = ABCMeta
class RgChart(object):
def with_grids(self):
self._ax.xaxis.grid(True)
self._ax.yaxis.grid(True)
return self
def save_as(self, filename):
self._create_plot()
self._fig.savefig(filename)
plt.close(self._fig) # close on save to avoid memory issues
def with_ygrid(self):
self._ax.yaxis.grid(True)
return self
def with_title(self, title = None):
if title is None:
plt.title(self._title)
else:
plt.title(title)
return self
def with_xlabel(self, xlabel = None):
if xlabel is None:
plt.xlabel(self._xlabel)
else:
plt.xlabel(xlabel)
return self
def with_ylabel(self, ylabel = None):
if ylabel is None:
plt.ylabel(self._ylabel)
else:
plt.ylabel(ylabel)
return self
def with_ylim(self, lim):
self._ax.set_ylim(lim)
return self
def wo_xticks(self):
self._ax.get_xaxis().set_ticks([])
return self
def wo_yticks(self):
self._ax.get_yaxis().set_ticks([])
return self
def _create_plot(self):
pass
## Instruction:
Add y log option and title offset
## Code After:
import matplotlib.pyplot as plt
#class RgChart(object):
#__metaclass__ = ABCMeta
class RgChart(object):
TITLE_Y_OFFSET = 1.08
def with_grids(self):
self._ax.xaxis.grid(True)
self._ax.yaxis.grid(True)
return self
def save_as(self, filename):
self._create_plot()
self._fig.savefig(filename)
plt.close(self._fig) # close on save to avoid memory issues
def with_ygrid(self):
self._ax.yaxis.grid(True)
return self
def with_title(self, title = None, y_offset = RgChart.TITLE_Y_OFFSET):
if title is None:
plt.title(self._title, y = y_offset)
else:
plt.title(title, y = y_offset)
return self
def with_xlabel(self, xlabel = None):
if xlabel is None:
plt.xlabel(self._xlabel)
else:
plt.xlabel(xlabel)
return self
def with_ylabel(self, ylabel = None):
if ylabel is None:
plt.ylabel(self._ylabel)
else:
plt.ylabel(ylabel)
return self
def with_ylog(self):
self._ax.set_yscale('log')
return self
def with_ylim(self, lim):
self._ax.set_ylim(lim)
return self
def wo_xticks(self):
self._ax.get_xaxis().set_ticks([])
return self
def wo_yticks(self):
self._ax.get_yaxis().set_ticks([])
return self
def _create_plot(self):
pass
|
# ... existing code ...
#__metaclass__ = ABCMeta
class RgChart(object):
TITLE_Y_OFFSET = 1.08
def with_grids(self):
self._ax.xaxis.grid(True)
# ... modified code ...
self._ax.yaxis.grid(True)
return self
def with_title(self, title = None, y_offset = RgChart.TITLE_Y_OFFSET):
if title is None:
plt.title(self._title, y = y_offset)
else:
plt.title(title, y = y_offset)
return self
def with_xlabel(self, xlabel = None):
...
plt.ylabel(ylabel)
return self
def with_ylog(self):
self._ax.set_yscale('log')
return self
def with_ylim(self, lim):
self._ax.set_ylim(lim)
return self
# ... rest of the code ...
|
7f3d76bdec3731ae50b9487556b1b2750cd3108e
|
setup.py
|
setup.py
|
from distutils.core import setup
import versioneer
setup(
name='iterm2-tools',
version=versioneer.get_version(),
cmdclass=versioneer.get_cmdclass(),
description='''iTerm2 tools.''',
author='Aaron Meurer',
author_email='[email protected]',
url='https://github.com/asmeurer/iterm2-tools',
packages=['iterm2_tools'],
package_data={'iterm2_tools.tests': ['aloha_cat.png']},
long_description="""
iterm2-tools
Some tools for working with iTerm2's proprietary escape codes.
For now, only includes iterm2_tools.images, which has functions for displaying
images inline.
License: MIT
""",
license="MIT",
classifiers=[
'Environment :: MacOS X',
'Operating System :: MacOS :: MacOS X',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 2',
],
)
|
from distutils.core import setup
import versioneer
setup(
name='iterm2-tools',
version=versioneer.get_version(),
cmdclass=versioneer.get_cmdclass(),
description='''iTerm2 tools.''',
author='Aaron Meurer',
author_email='[email protected]',
url='https://github.com/asmeurer/iterm2-tools',
packages=[
'iterm2_tools',
'iterm2_tools.tests'
],
package_data={'iterm2_tools.tests': ['aloha_cat.png']},
long_description="""
iterm2-tools
Some tools for working with iTerm2's proprietary escape codes.
For now, only includes iterm2_tools.images, which has functions for displaying
images inline.
License: MIT
""",
license="MIT",
classifiers=[
'Environment :: MacOS X',
'Operating System :: MacOS :: MacOS X',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 2',
],
)
|
Include the tests in the dist
|
Include the tests in the dist
|
Python
|
mit
|
asmeurer/iterm2-tools
|
python
|
## Code Before:
from distutils.core import setup
import versioneer
setup(
name='iterm2-tools',
version=versioneer.get_version(),
cmdclass=versioneer.get_cmdclass(),
description='''iTerm2 tools.''',
author='Aaron Meurer',
author_email='[email protected]',
url='https://github.com/asmeurer/iterm2-tools',
packages=['iterm2_tools'],
package_data={'iterm2_tools.tests': ['aloha_cat.png']},
long_description="""
iterm2-tools
Some tools for working with iTerm2's proprietary escape codes.
For now, only includes iterm2_tools.images, which has functions for displaying
images inline.
License: MIT
""",
license="MIT",
classifiers=[
'Environment :: MacOS X',
'Operating System :: MacOS :: MacOS X',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 2',
],
)
## Instruction:
Include the tests in the dist
## Code After:
from distutils.core import setup
import versioneer
setup(
name='iterm2-tools',
version=versioneer.get_version(),
cmdclass=versioneer.get_cmdclass(),
description='''iTerm2 tools.''',
author='Aaron Meurer',
author_email='[email protected]',
url='https://github.com/asmeurer/iterm2-tools',
packages=[
'iterm2_tools',
'iterm2_tools.tests'
],
package_data={'iterm2_tools.tests': ['aloha_cat.png']},
long_description="""
iterm2-tools
Some tools for working with iTerm2's proprietary escape codes.
For now, only includes iterm2_tools.images, which has functions for displaying
images inline.
License: MIT
""",
license="MIT",
classifiers=[
'Environment :: MacOS X',
'Operating System :: MacOS :: MacOS X',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 2',
],
)
|
# ... existing code ...
author='Aaron Meurer',
author_email='[email protected]',
url='https://github.com/asmeurer/iterm2-tools',
packages=[
'iterm2_tools',
'iterm2_tools.tests'
],
package_data={'iterm2_tools.tests': ['aloha_cat.png']},
long_description="""
iterm2-tools
# ... rest of the code ...
|
7ba2299e2d429bd873539507b3edbe3cdd3de9d6
|
linkatos/firebase.py
|
linkatos/firebase.py
|
import pyrebase
def initialise(FB_API_KEY, project_name):
config = {
"apiKey": FB_API_KEY,
"authDomain": "{}.firebaseapp.com".format(project_name),
"databaseURL": "https://{}.firebaseio.com".format(project_name),
"storageBucket": "{}.appspot.com".format(project_name),
}
return pyrebase.initialize_app(config)
def store_url(is_yes, url, FB_USER, FB_PASS, firebase):
# do nothing if it's unnecessary
if not is_yes:
return False
# creates token every time maybe worth doing it once every 30m as they
# expire every hour
auth = firebase.auth()
user = auth.sign_in_with_email_and_password(FB_USER, FB_PASS)
db = firebase.database()
data = {
"url": url
}
db.child("users").push(data, user['idToken'])
return False
|
import pyrebase
def initialise(api_key, project_name):
config = {
"apiKey": api_key,
"authDomain": "{}.firebaseapp.com".format(project_name),
"databaseURL": "https://{}.firebaseio.com".format(project_name),
"storageBucket": "{}.appspot.com".format(project_name),
}
return pyrebase.initialize_app(config)
def store_url(is_yes, url, user, password, firebase):
# do nothing if it's unnecessary
if not is_yes:
return False
# creates token every time maybe worth doing it once every 30m as they
# expire every hour
auth = firebase.auth()
user = auth.sign_in_with_email_and_password(user, password)
db = firebase.database()
data = {
"url": url
}
db.child("users").push(data, user['idToken'])
return False
|
Change variables to lower case
|
style: Change variables to lower case
|
Python
|
mit
|
iwi/linkatos,iwi/linkatos
|
python
|
## Code Before:
import pyrebase
def initialise(FB_API_KEY, project_name):
config = {
"apiKey": FB_API_KEY,
"authDomain": "{}.firebaseapp.com".format(project_name),
"databaseURL": "https://{}.firebaseio.com".format(project_name),
"storageBucket": "{}.appspot.com".format(project_name),
}
return pyrebase.initialize_app(config)
def store_url(is_yes, url, FB_USER, FB_PASS, firebase):
# do nothing if it's unnecessary
if not is_yes:
return False
# creates token every time maybe worth doing it once every 30m as they
# expire every hour
auth = firebase.auth()
user = auth.sign_in_with_email_and_password(FB_USER, FB_PASS)
db = firebase.database()
data = {
"url": url
}
db.child("users").push(data, user['idToken'])
return False
## Instruction:
style: Change variables to lower case
## Code After:
import pyrebase
def initialise(api_key, project_name):
config = {
"apiKey": api_key,
"authDomain": "{}.firebaseapp.com".format(project_name),
"databaseURL": "https://{}.firebaseio.com".format(project_name),
"storageBucket": "{}.appspot.com".format(project_name),
}
return pyrebase.initialize_app(config)
def store_url(is_yes, url, user, password, firebase):
# do nothing if it's unnecessary
if not is_yes:
return False
# creates token every time maybe worth doing it once every 30m as they
# expire every hour
auth = firebase.auth()
user = auth.sign_in_with_email_and_password(user, password)
db = firebase.database()
data = {
"url": url
}
db.child("users").push(data, user['idToken'])
return False
|
...
import pyrebase
def initialise(api_key, project_name):
config = {
"apiKey": api_key,
"authDomain": "{}.firebaseapp.com".format(project_name),
"databaseURL": "https://{}.firebaseio.com".format(project_name),
"storageBucket": "{}.appspot.com".format(project_name),
...
return pyrebase.initialize_app(config)
def store_url(is_yes, url, user, password, firebase):
# do nothing if it's unnecessary
if not is_yes:
return False
...
# creates token every time maybe worth doing it once every 30m as they
# expire every hour
auth = firebase.auth()
user = auth.sign_in_with_email_and_password(user, password)
db = firebase.database()
data = {
...
|
8978da376e12d58afd680da1fec8249f3e233c89
|
home-server-backend/src/main/java/nl/homeserver/config/WebSocketConfig.java
|
home-server-backend/src/main/java/nl/homeserver/config/WebSocketConfig.java
|
package nl.homeserver.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.AbstractWebSocketMessageBrokerConfigurer;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/topic");
config.setApplicationDestinationPrefixes("/app");
}
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/ws").setAllowedOrigins("*").withSockJS();
}
}
|
package nl.homeserver.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/topic");
config.setApplicationDestinationPrefixes("/app");
}
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/ws").setAllowedOrigins("*").withSockJS();
}
}
|
Fix usage of deprecated class
|
Fix usage of deprecated class
|
Java
|
apache-2.0
|
bassages/homecontrol,bassages/homecontrol,bassages/home-server,bassages/home-server
|
java
|
## Code Before:
package nl.homeserver.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.AbstractWebSocketMessageBrokerConfigurer;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/topic");
config.setApplicationDestinationPrefixes("/app");
}
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/ws").setAllowedOrigins("*").withSockJS();
}
}
## Instruction:
Fix usage of deprecated class
## Code After:
package nl.homeserver.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/topic");
config.setApplicationDestinationPrefixes("/app");
}
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/ws").setAllowedOrigins("*").withSockJS();
}
}
|
# ... existing code ...
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
# ... rest of the code ...
|
02e7251da64c9a2853c2e05a2b93b862268a840c
|
SixTrack/pytools/fix_cdblocks.py
|
SixTrack/pytools/fix_cdblocks.py
|
import sys
assert len(sys.argv) == 3, "Usage: to_replace filename"
to_replace = sys.argv[1]
filename = sys.argv[2]
lines_in = open(filename,'r').readlines()
#print '+ca '+to_replace
i = 0
num_replaced = 0
while True:
line = lines_in[i]
#print line
if line.startswith('+ca '+to_replace):
#print "found!"
#delete the bad line
del lines_in[i]
#search backwards for the implicit none
while True:
i = i-1
if i < 0:
print "Error, i<0"
exit(1)
line = lines_in[i]
if "implicit none" in line or "IMPLICIT NONE" in line:
break
lines_in.insert(i," use "+to_replace + "\n")
num_replaced += 1
i = i+1
if i >= len(lines_in):
break
file_out = open(filename,'w')
for l in lines_in:
file_out.write(l)
file_out.close()
print num_replaced
|
import sys
assert len(sys.argv) == 3, "Usage: to_replace filename"
to_replace = sys.argv[1]
filename = sys.argv[2]
lines_in = open(filename,'r').readlines()
#print '+ca '+to_replace
i = 0
num_replaced = 0
numspaces = 6 # default value
while True:
line = lines_in[i]
#print line
if line.startswith('+ca '+to_replace):
#print "found!"
#delete the bad line
del lines_in[i]
#search backwards for the implicit none
while True:
i = i-1
if i < 0:
print "Error, i<0"
exit(1)
line = lines_in[i]
if "implicit none" in line or "IMPLICIT NONE" in line:
numspaces = len(line)-len(line.lstrip())
break
lines_in.insert(i,numspaces*" " + "use "+to_replace + "\n")
num_replaced += 1
i = i+1
if i >= len(lines_in):
break
file_out = open(filename,'w')
for l in lines_in:
file_out.write(l)
file_out.close()
print num_replaced
|
Indent the use statements correctly
|
Indent the use statements correctly
|
Python
|
lgpl-2.1
|
SixTrack/SixTrack,SixTrack/SixTrack,SixTrack/SixTrack,SixTrack/SixTrack,SixTrack/SixTrack,SixTrack/SixTrack
|
python
|
## Code Before:
import sys
assert len(sys.argv) == 3, "Usage: to_replace filename"
to_replace = sys.argv[1]
filename = sys.argv[2]
lines_in = open(filename,'r').readlines()
#print '+ca '+to_replace
i = 0
num_replaced = 0
while True:
line = lines_in[i]
#print line
if line.startswith('+ca '+to_replace):
#print "found!"
#delete the bad line
del lines_in[i]
#search backwards for the implicit none
while True:
i = i-1
if i < 0:
print "Error, i<0"
exit(1)
line = lines_in[i]
if "implicit none" in line or "IMPLICIT NONE" in line:
break
lines_in.insert(i," use "+to_replace + "\n")
num_replaced += 1
i = i+1
if i >= len(lines_in):
break
file_out = open(filename,'w')
for l in lines_in:
file_out.write(l)
file_out.close()
print num_replaced
## Instruction:
Indent the use statements correctly
## Code After:
import sys
assert len(sys.argv) == 3, "Usage: to_replace filename"
to_replace = sys.argv[1]
filename = sys.argv[2]
lines_in = open(filename,'r').readlines()
#print '+ca '+to_replace
i = 0
num_replaced = 0
numspaces = 6 # default value
while True:
line = lines_in[i]
#print line
if line.startswith('+ca '+to_replace):
#print "found!"
#delete the bad line
del lines_in[i]
#search backwards for the implicit none
while True:
i = i-1
if i < 0:
print "Error, i<0"
exit(1)
line = lines_in[i]
if "implicit none" in line or "IMPLICIT NONE" in line:
numspaces = len(line)-len(line.lstrip())
break
lines_in.insert(i,numspaces*" " + "use "+to_replace + "\n")
num_replaced += 1
i = i+1
if i >= len(lines_in):
break
file_out = open(filename,'w')
for l in lines_in:
file_out.write(l)
file_out.close()
print num_replaced
|
// ... existing code ...
i = 0
num_replaced = 0
numspaces = 6 # default value
while True:
line = lines_in[i]
#print line
// ... modified code ...
exit(1)
line = lines_in[i]
if "implicit none" in line or "IMPLICIT NONE" in line:
numspaces = len(line)-len(line.lstrip())
break
lines_in.insert(i,numspaces*" " + "use "+to_replace + "\n")
num_replaced += 1
i = i+1
if i >= len(lines_in):
// ... rest of the code ...
|
025c95a59b079d630c778646d5c82f5e0679b47c
|
sale_automatic_workflow/models/account_invoice.py
|
sale_automatic_workflow/models/account_invoice.py
|
from odoo import models, fields
class AccountInvoice(models.Model):
_inherit = "account.invoice"
workflow_process_id = fields.Many2one(
comodel_name='sale.workflow.process',
string='Sale Workflow Process'
)
|
from odoo import models, fields
class AccountInvoice(models.Model):
_inherit = "account.invoice"
workflow_process_id = fields.Many2one(
comodel_name='sale.workflow.process',
string='Sale Workflow Process',
copy=False,
)
|
Fix issue on account.invoice about workflow_process_id: if a user duplicate an invoice, it copy also the workflow and validations (the reason of bugs)
|
[FIX] Fix issue on account.invoice about workflow_process_id: if a user duplicate an invoice, it copy also the workflow and validations (the reason of bugs)
|
Python
|
agpl-3.0
|
kittiu/sale-workflow,kittiu/sale-workflow
|
python
|
## Code Before:
from odoo import models, fields
class AccountInvoice(models.Model):
_inherit = "account.invoice"
workflow_process_id = fields.Many2one(
comodel_name='sale.workflow.process',
string='Sale Workflow Process'
)
## Instruction:
[FIX] Fix issue on account.invoice about workflow_process_id: if a user duplicate an invoice, it copy also the workflow and validations (the reason of bugs)
## Code After:
from odoo import models, fields
class AccountInvoice(models.Model):
_inherit = "account.invoice"
workflow_process_id = fields.Many2one(
comodel_name='sale.workflow.process',
string='Sale Workflow Process',
copy=False,
)
|
// ... existing code ...
from odoo import models, fields
// ... modified code ...
workflow_process_id = fields.Many2one(
comodel_name='sale.workflow.process',
string='Sale Workflow Process',
copy=False,
)
// ... rest of the code ...
|
03b55cad3839653cea62300eca80571541579d2b
|
dataviews/__init__.py
|
dataviews/__init__.py
|
import sys, os
# Add param submodule to sys.path
cwd = os.path.abspath(os.path.split(__file__)[0])
sys.path.insert(0, os.path.join(cwd, '..', 'param'))
import param
__version__ = param.Version(release=(0,7), fpath=__file__,
commit="$Format:%h$", reponame='dataviews')
from .views import * # pyflakes:ignore (API import)
from .dataviews import * # pyflakes:ignore (API import)
from .sheetviews import * # pyflakes:ignore (API import)
from .ndmapping import * # pyflakes:ignore (API import)
def public(obj):
if not isinstance(obj, type): return False
baseclasses = [NdMapping, View, Dimension, Overlay]
return any([issubclass(obj, bc) for bc in baseclasses])
_public = list(set([_k for _k, _v in locals().items() if public(_v)]))
__all__ = _public + ["boundingregion", "ipython", "plotting", "sheetcoords" ]
|
import sys, os
# Add param submodule to sys.path
cwd = os.path.abspath(os.path.split(__file__)[0])
sys.path.insert(0, os.path.join(cwd, '..', 'param'))
import param
__version__ = param.Version(release=(0,7), fpath=__file__,
commit="$Format:%h$", reponame='dataviews')
from .views import * # pyflakes:ignore (API import)
from .dataviews import * # pyflakes:ignore (API import)
from .sheetviews import * # pyflakes:ignore (API import)
from .ndmapping import * # pyflakes:ignore (API import)
from .styles import set_style
set_style('default')
def public(obj):
if not isinstance(obj, type): return False
baseclasses = [NdMapping, View, Dimension, Overlay]
return any([issubclass(obj, bc) for bc in baseclasses])
_public = list(set([_k for _k, _v in locals().items() if public(_v)]))
__all__ = _public + ["boundingregion", "ipython", "plotting", "sheetcoords" ]
|
Apply default style on import
|
Apply default style on import
|
Python
|
bsd-3-clause
|
vascotenner/holoviews,basnijholt/holoviews,vascotenner/holoviews,basnijholt/holoviews,mjabri/holoviews,mjabri/holoviews,ioam/holoviews,basnijholt/holoviews,mjabri/holoviews,ioam/holoviews,vascotenner/holoviews,ioam/holoviews
|
python
|
## Code Before:
import sys, os
# Add param submodule to sys.path
cwd = os.path.abspath(os.path.split(__file__)[0])
sys.path.insert(0, os.path.join(cwd, '..', 'param'))
import param
__version__ = param.Version(release=(0,7), fpath=__file__,
commit="$Format:%h$", reponame='dataviews')
from .views import * # pyflakes:ignore (API import)
from .dataviews import * # pyflakes:ignore (API import)
from .sheetviews import * # pyflakes:ignore (API import)
from .ndmapping import * # pyflakes:ignore (API import)
def public(obj):
if not isinstance(obj, type): return False
baseclasses = [NdMapping, View, Dimension, Overlay]
return any([issubclass(obj, bc) for bc in baseclasses])
_public = list(set([_k for _k, _v in locals().items() if public(_v)]))
__all__ = _public + ["boundingregion", "ipython", "plotting", "sheetcoords" ]
## Instruction:
Apply default style on import
## Code After:
import sys, os
# Add param submodule to sys.path
cwd = os.path.abspath(os.path.split(__file__)[0])
sys.path.insert(0, os.path.join(cwd, '..', 'param'))
import param
__version__ = param.Version(release=(0,7), fpath=__file__,
commit="$Format:%h$", reponame='dataviews')
from .views import * # pyflakes:ignore (API import)
from .dataviews import * # pyflakes:ignore (API import)
from .sheetviews import * # pyflakes:ignore (API import)
from .ndmapping import * # pyflakes:ignore (API import)
from .styles import set_style
set_style('default')
def public(obj):
if not isinstance(obj, type): return False
baseclasses = [NdMapping, View, Dimension, Overlay]
return any([issubclass(obj, bc) for bc in baseclasses])
_public = list(set([_k for _k, _v in locals().items() if public(_v)]))
__all__ = _public + ["boundingregion", "ipython", "plotting", "sheetcoords" ]
|
...
from .dataviews import * # pyflakes:ignore (API import)
from .sheetviews import * # pyflakes:ignore (API import)
from .ndmapping import * # pyflakes:ignore (API import)
from .styles import set_style
set_style('default')
def public(obj):
if not isinstance(obj, type): return False
...
|
b8028d47d52caed5b6c714fe0abe0fa433433bfc
|
setup.py
|
setup.py
|
import os
import pygubu
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
VERSION = pygubu.__version__
_dirname_ = os.path.dirname(__file__)
readme_path = os.path.join(_dirname_, 'README.md')
setup(
name='pygubu',
version=VERSION,
license='MIT',
author='Alejandro Autalán',
author_email='[email protected]',
description='A tkinter GUI builder.',
long_description=open(readme_path, 'r', encoding='utf-8').read(),
long_description_content_type='text/markdown',
url='https://github.com/alejandroautalan/pygubu',
packages=['pygubu', 'pygubu.builder',
'pygubu.builder.widgets', 'pygubu.widgets'],
classifiers=[
"Programming Language :: Python",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"Topic :: Software Development :: Libraries :: Python Modules",
"Topic :: Utilities",
"Topic :: Software Development :: User Interfaces",
],
)
|
import os
from io import open
import pygubu
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
VERSION = pygubu.__version__
_dirname_ = os.path.dirname(__file__)
readme_path = os.path.join(_dirname_, 'README.md')
setup(
name='pygubu',
version=VERSION,
license='MIT',
author='Alejandro Autalán',
author_email='[email protected]',
description='A tkinter GUI builder.',
long_description=open(readme_path, 'r', encoding='utf-8').read(),
long_description_content_type='text/markdown',
url='https://github.com/alejandroautalan/pygubu',
packages=['pygubu', 'pygubu.builder',
'pygubu.builder.widgets', 'pygubu.widgets'],
classifiers=[
"Programming Language :: Python",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"Topic :: Software Development :: Libraries :: Python Modules",
"Topic :: Utilities",
"Topic :: Software Development :: User Interfaces",
],
)
|
Fix install error on python 2.7
|
Fix install error on python 2.7
|
Python
|
mit
|
alejandroautalan/pygubu,alejandroautalan/pygubu
|
python
|
## Code Before:
import os
import pygubu
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
VERSION = pygubu.__version__
_dirname_ = os.path.dirname(__file__)
readme_path = os.path.join(_dirname_, 'README.md')
setup(
name='pygubu',
version=VERSION,
license='MIT',
author='Alejandro Autalán',
author_email='[email protected]',
description='A tkinter GUI builder.',
long_description=open(readme_path, 'r', encoding='utf-8').read(),
long_description_content_type='text/markdown',
url='https://github.com/alejandroautalan/pygubu',
packages=['pygubu', 'pygubu.builder',
'pygubu.builder.widgets', 'pygubu.widgets'],
classifiers=[
"Programming Language :: Python",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"Topic :: Software Development :: Libraries :: Python Modules",
"Topic :: Utilities",
"Topic :: Software Development :: User Interfaces",
],
)
## Instruction:
Fix install error on python 2.7
## Code After:
import os
from io import open
import pygubu
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
VERSION = pygubu.__version__
_dirname_ = os.path.dirname(__file__)
readme_path = os.path.join(_dirname_, 'README.md')
setup(
name='pygubu',
version=VERSION,
license='MIT',
author='Alejandro Autalán',
author_email='[email protected]',
description='A tkinter GUI builder.',
long_description=open(readme_path, 'r', encoding='utf-8').read(),
long_description_content_type='text/markdown',
url='https://github.com/alejandroautalan/pygubu',
packages=['pygubu', 'pygubu.builder',
'pygubu.builder.widgets', 'pygubu.widgets'],
classifiers=[
"Programming Language :: Python",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"Topic :: Software Development :: Libraries :: Python Modules",
"Topic :: Utilities",
"Topic :: Software Development :: User Interfaces",
],
)
|
// ... existing code ...
import os
from io import open
import pygubu
// ... rest of the code ...
|
8e1f636ced4380a559aaf8eb14cae88442fc15c1
|
lib/Solenoid/Solenoid.h
|
lib/Solenoid/Solenoid.h
|
/****************************************************************************
* Copyright 2016 BlueMasters
*
* 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.
*****************************************************************************/
#ifndef SOLENOID__H
#define SOLENOID__H
#include <Arduino.h>
#include "StateMachine.h"
#include "LED.h"
#include "RFIDSensor.h"
#include "WolvesTypes.h"
enum solenoidState {
SOLENOID_IDLE,
SOLENOID_FROZEN,
SOLENOID_FIRED,
SOLENOID_WAITING
};
class Solenoid : public StateMachine {
public:
Solenoid(int impulsePin, RFIDSensor sensor, LED led) :
_impulsePin(impulsePin), _sensor(sensor), _led(led) {};
void begin();
void on();
void off();
void tick();
private:
int _impulsePin;
RFIDSensor _sensor;
LED _led;
solenoidState _state;
long _timestamp;
void fire(long t);
void release(long t);
};
#endif
|
/****************************************************************************
* Copyright 2016 BlueMasters
*
* 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.
*****************************************************************************/
#ifndef SOLENOID__H
#define SOLENOID__H
#include <Arduino.h>
#include "StateMachine.h"
#include "LED.h"
#include "RFIDSensor.h"
#include "WolvesTypes.h"
class Solenoid : public StateMachine {
public:
Solenoid(int impulsePin, RFIDSensor sensor, LED led) :
_impulsePin(impulsePin), _sensor(sensor), _led(led) {};
void begin();
void on();
void off();
void tick();
private:
enum solenoidState {
SOLENOID_IDLE,
SOLENOID_FROZEN,
SOLENOID_FIRED,
SOLENOID_WAITING
};
int _impulsePin;
RFIDSensor _sensor;
LED _led;
solenoidState _state;
long _timestamp;
void fire(long t);
void release(long t);
};
#endif
|
Put states inside the class
|
Put states inside the class
|
C
|
apache-2.0
|
BlueMasters/arduino-wolves,BlueMasters/arduino-wolves,BlueMasters/arduino-wolves
|
c
|
## Code Before:
/****************************************************************************
* Copyright 2016 BlueMasters
*
* 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.
*****************************************************************************/
#ifndef SOLENOID__H
#define SOLENOID__H
#include <Arduino.h>
#include "StateMachine.h"
#include "LED.h"
#include "RFIDSensor.h"
#include "WolvesTypes.h"
enum solenoidState {
SOLENOID_IDLE,
SOLENOID_FROZEN,
SOLENOID_FIRED,
SOLENOID_WAITING
};
class Solenoid : public StateMachine {
public:
Solenoid(int impulsePin, RFIDSensor sensor, LED led) :
_impulsePin(impulsePin), _sensor(sensor), _led(led) {};
void begin();
void on();
void off();
void tick();
private:
int _impulsePin;
RFIDSensor _sensor;
LED _led;
solenoidState _state;
long _timestamp;
void fire(long t);
void release(long t);
};
#endif
## Instruction:
Put states inside the class
## Code After:
/****************************************************************************
* Copyright 2016 BlueMasters
*
* 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.
*****************************************************************************/
#ifndef SOLENOID__H
#define SOLENOID__H
#include <Arduino.h>
#include "StateMachine.h"
#include "LED.h"
#include "RFIDSensor.h"
#include "WolvesTypes.h"
class Solenoid : public StateMachine {
public:
Solenoid(int impulsePin, RFIDSensor sensor, LED led) :
_impulsePin(impulsePin), _sensor(sensor), _led(led) {};
void begin();
void on();
void off();
void tick();
private:
enum solenoidState {
SOLENOID_IDLE,
SOLENOID_FROZEN,
SOLENOID_FIRED,
SOLENOID_WAITING
};
int _impulsePin;
RFIDSensor _sensor;
LED _led;
solenoidState _state;
long _timestamp;
void fire(long t);
void release(long t);
};
#endif
|
// ... existing code ...
#include "RFIDSensor.h"
#include "WolvesTypes.h"
class Solenoid : public StateMachine {
public:
Solenoid(int impulsePin, RFIDSensor sensor, LED led) :
// ... modified code ...
void tick();
private:
enum solenoidState {
SOLENOID_IDLE,
SOLENOID_FROZEN,
SOLENOID_FIRED,
SOLENOID_WAITING
};
int _impulsePin;
RFIDSensor _sensor;
LED _led;
// ... rest of the code ...
|
a4a50e2043bf49b867cc80d9b7d55333d6e0cffa
|
setup.py
|
setup.py
|
from setuptools import setup, find_packages
setup(
name = 'tentd',
version = "0.0.0",
author = 'James Ravenscroft',
url = 'https://github.com/ravenscroftj/pytentd',
description = 'An implementation of the http://tent.io server protocol',
long_description = open('README.rst').read(),
packages = find_packages(),
install_requires = [
'flask==0.9',
'Flask-SQLAlchemy==0.16'
],
include_package_data = True,
zip_safe = False,
)
|
from setuptools import setup, find_packages
setup(
name = 'tentd',
version = "0.0.0",
author = 'James Ravenscroft',
url = 'https://github.com/ravenscroftj/pytentd',
description = 'An implementation of the http://tent.io server protocol',
long_description = open('README.rst').read(),
packages = find_packages(),
install_requires = [
'flask==0.9',
'Flask-SQLAlchemy==0.16',
],
entry_points = {
'console_scripts': ['tentd = tentd:run'],
},
include_package_data = True,
zip_safe = False,
)
|
Allow tentd to be run from the command line
|
Allow tentd to be run from the command line
|
Python
|
apache-2.0
|
pytent/pytentd
|
python
|
## Code Before:
from setuptools import setup, find_packages
setup(
name = 'tentd',
version = "0.0.0",
author = 'James Ravenscroft',
url = 'https://github.com/ravenscroftj/pytentd',
description = 'An implementation of the http://tent.io server protocol',
long_description = open('README.rst').read(),
packages = find_packages(),
install_requires = [
'flask==0.9',
'Flask-SQLAlchemy==0.16'
],
include_package_data = True,
zip_safe = False,
)
## Instruction:
Allow tentd to be run from the command line
## Code After:
from setuptools import setup, find_packages
setup(
name = 'tentd',
version = "0.0.0",
author = 'James Ravenscroft',
url = 'https://github.com/ravenscroftj/pytentd',
description = 'An implementation of the http://tent.io server protocol',
long_description = open('README.rst').read(),
packages = find_packages(),
install_requires = [
'flask==0.9',
'Flask-SQLAlchemy==0.16',
],
entry_points = {
'console_scripts': ['tentd = tentd:run'],
},
include_package_data = True,
zip_safe = False,
)
|
...
packages = find_packages(),
install_requires = [
'flask==0.9',
'Flask-SQLAlchemy==0.16',
],
entry_points = {
'console_scripts': ['tentd = tentd:run'],
},
include_package_data = True,
zip_safe = False,
)
...
|
674fa7692c71524541d8797a65968e5e605454e7
|
testrail/suite.py
|
testrail/suite.py
|
from datetime import datetime
import api
from project import Project
class Suite(object):
def __init__(self, content):
self._content = content
self.api = api.API()
@property
def id(self):
return self._content.get('id')
@property
def completed_on(self):
try:
return datetime.fromtimestamp(
int(self._content.get('completed_on')))
except TypeError:
return None
@property
def description(self):
return self._content.get('description')
@property
def is_baseline(self):
return self._content.get('is_baseline')
@property
def is_completed(self):
return self._content.get('is_completed')
@property
def is_master(self):
return self._content.get('is_master')
@property
def name(self):
return self._content.get('name')
@property
def project(self):
return Project(
self.api.project_with_id(self._content.get('project_id')))
@property
def url(self):
return self._content.get('url')
|
from datetime import datetime
import api
from helper import TestRailError
from project import Project
class Suite(object):
def __init__(self, content):
self._content = content
self.api = api.API()
@property
def id(self):
return self._content.get('id')
@property
def completed_on(self):
try:
return datetime.fromtimestamp(
int(self._content.get('completed_on')))
except TypeError:
return None
@property
def description(self):
return self._content.get('description')
@description.setter
def description(self, value):
if type(value) != str:
raise TestRailError('input must be a string')
self._content['description'] = value
@property
def is_baseline(self):
return self._content.get('is_baseline')
@property
def is_completed(self):
return self._content.get('is_completed')
@property
def is_master(self):
return self._content.get('is_master')
@property
def name(self):
return self._content.get('name')
@name.setter
def name(self, value):
if type(value) != str:
raise TestRailError('input must be a string')
self._content['name'] = value
@property
def project(self):
return Project(
self.api.project_with_id(self._content.get('project_id')))
@project.setter
def project(self, value):
if type(value) != Project:
raise TestRailError('input must be a Project')
self.api.project_with_id(value.id) # verify project is valid
self._content['project_id'] = value.id
@property
def url(self):
return self._content.get('url')
def raw_data(self):
return self._content
|
Add setters for project, name, and description.
|
Add setters for project, name, and description.
|
Python
|
mit
|
travispavek/testrail-python,travispavek/testrail
|
python
|
## Code Before:
from datetime import datetime
import api
from project import Project
class Suite(object):
def __init__(self, content):
self._content = content
self.api = api.API()
@property
def id(self):
return self._content.get('id')
@property
def completed_on(self):
try:
return datetime.fromtimestamp(
int(self._content.get('completed_on')))
except TypeError:
return None
@property
def description(self):
return self._content.get('description')
@property
def is_baseline(self):
return self._content.get('is_baseline')
@property
def is_completed(self):
return self._content.get('is_completed')
@property
def is_master(self):
return self._content.get('is_master')
@property
def name(self):
return self._content.get('name')
@property
def project(self):
return Project(
self.api.project_with_id(self._content.get('project_id')))
@property
def url(self):
return self._content.get('url')
## Instruction:
Add setters for project, name, and description.
## Code After:
from datetime import datetime
import api
from helper import TestRailError
from project import Project
class Suite(object):
def __init__(self, content):
self._content = content
self.api = api.API()
@property
def id(self):
return self._content.get('id')
@property
def completed_on(self):
try:
return datetime.fromtimestamp(
int(self._content.get('completed_on')))
except TypeError:
return None
@property
def description(self):
return self._content.get('description')
@description.setter
def description(self, value):
if type(value) != str:
raise TestRailError('input must be a string')
self._content['description'] = value
@property
def is_baseline(self):
return self._content.get('is_baseline')
@property
def is_completed(self):
return self._content.get('is_completed')
@property
def is_master(self):
return self._content.get('is_master')
@property
def name(self):
return self._content.get('name')
@name.setter
def name(self, value):
if type(value) != str:
raise TestRailError('input must be a string')
self._content['name'] = value
@property
def project(self):
return Project(
self.api.project_with_id(self._content.get('project_id')))
@project.setter
def project(self, value):
if type(value) != Project:
raise TestRailError('input must be a Project')
self.api.project_with_id(value.id) # verify project is valid
self._content['project_id'] = value.id
@property
def url(self):
return self._content.get('url')
def raw_data(self):
return self._content
|
// ... existing code ...
from datetime import datetime
import api
from helper import TestRailError
from project import Project
// ... modified code ...
def description(self):
return self._content.get('description')
@description.setter
def description(self, value):
if type(value) != str:
raise TestRailError('input must be a string')
self._content['description'] = value
@property
def is_baseline(self):
return self._content.get('is_baseline')
...
def name(self):
return self._content.get('name')
@name.setter
def name(self, value):
if type(value) != str:
raise TestRailError('input must be a string')
self._content['name'] = value
@property
def project(self):
return Project(
self.api.project_with_id(self._content.get('project_id')))
@project.setter
def project(self, value):
if type(value) != Project:
raise TestRailError('input must be a Project')
self.api.project_with_id(value.id) # verify project is valid
self._content['project_id'] = value.id
@property
def url(self):
return self._content.get('url')
def raw_data(self):
return self._content
// ... rest of the code ...
|
5c52d60804ea39834ef024923d4286fb7464eefa
|
ir/ana/execfreq_t.h
|
ir/ana/execfreq_t.h
|
/*
* This file is part of libFirm.
* Copyright (C) 2012 University of Karlsruhe.
*/
/**
* @file
* @brief Compute an estimate of basic block executions.
* @author Adam M. Szalkowski
* @date 28.05.2006
*/
#ifndef FIRM_ANA_EXECFREQ_T_H
#define FIRM_ANA_EXECFREQ_T_H
#include "execfreq.h"
void init_execfreq(void);
void exit_execfreq(void);
void set_block_execfreq(ir_node *block, double freq);
typedef struct ir_execfreq_int_factors {
double max;
double min_non_zero;
double m, b;
} ir_execfreq_int_factors;
void ir_calculate_execfreq_int_factors(ir_execfreq_int_factors *factors,
ir_graph *irg);
int get_block_execfreq_int(const ir_execfreq_int_factors *factors,
const ir_node *block);
#endif
|
/*
* This file is part of libFirm.
* Copyright (C) 2012 University of Karlsruhe.
*/
/**
* @file
* @brief Compute an estimate of basic block executions.
* @author Adam M. Szalkowski
* @date 28.05.2006
*/
#ifndef FIRM_ANA_EXECFREQ_T_H
#define FIRM_ANA_EXECFREQ_T_H
#include "execfreq.h"
void init_execfreq(void);
void exit_execfreq(void);
void set_block_execfreq(ir_node *block, double freq);
typedef struct ir_execfreq_int_factors {
double min_non_zero;
double m, b;
} ir_execfreq_int_factors;
void ir_calculate_execfreq_int_factors(ir_execfreq_int_factors *factors,
ir_graph *irg);
int get_block_execfreq_int(const ir_execfreq_int_factors *factors,
const ir_node *block);
#endif
|
Remove unused attribute max from int_factors.
|
execfreq: Remove unused attribute max from int_factors.
|
C
|
lgpl-2.1
|
MatzeB/libfirm,jonashaag/libfirm,libfirm/libfirm,killbug2004/libfirm,killbug2004/libfirm,libfirm/libfirm,jonashaag/libfirm,8l/libfirm,jonashaag/libfirm,killbug2004/libfirm,MatzeB/libfirm,davidgiven/libfirm,libfirm/libfirm,davidgiven/libfirm,davidgiven/libfirm,killbug2004/libfirm,killbug2004/libfirm,davidgiven/libfirm,davidgiven/libfirm,MatzeB/libfirm,libfirm/libfirm,killbug2004/libfirm,killbug2004/libfirm,davidgiven/libfirm,8l/libfirm,jonashaag/libfirm,jonashaag/libfirm,MatzeB/libfirm,8l/libfirm,MatzeB/libfirm,libfirm/libfirm,davidgiven/libfirm,8l/libfirm,jonashaag/libfirm,MatzeB/libfirm,8l/libfirm,MatzeB/libfirm,jonashaag/libfirm,8l/libfirm,8l/libfirm
|
c
|
## Code Before:
/*
* This file is part of libFirm.
* Copyright (C) 2012 University of Karlsruhe.
*/
/**
* @file
* @brief Compute an estimate of basic block executions.
* @author Adam M. Szalkowski
* @date 28.05.2006
*/
#ifndef FIRM_ANA_EXECFREQ_T_H
#define FIRM_ANA_EXECFREQ_T_H
#include "execfreq.h"
void init_execfreq(void);
void exit_execfreq(void);
void set_block_execfreq(ir_node *block, double freq);
typedef struct ir_execfreq_int_factors {
double max;
double min_non_zero;
double m, b;
} ir_execfreq_int_factors;
void ir_calculate_execfreq_int_factors(ir_execfreq_int_factors *factors,
ir_graph *irg);
int get_block_execfreq_int(const ir_execfreq_int_factors *factors,
const ir_node *block);
#endif
## Instruction:
execfreq: Remove unused attribute max from int_factors.
## Code After:
/*
* This file is part of libFirm.
* Copyright (C) 2012 University of Karlsruhe.
*/
/**
* @file
* @brief Compute an estimate of basic block executions.
* @author Adam M. Szalkowski
* @date 28.05.2006
*/
#ifndef FIRM_ANA_EXECFREQ_T_H
#define FIRM_ANA_EXECFREQ_T_H
#include "execfreq.h"
void init_execfreq(void);
void exit_execfreq(void);
void set_block_execfreq(ir_node *block, double freq);
typedef struct ir_execfreq_int_factors {
double min_non_zero;
double m, b;
} ir_execfreq_int_factors;
void ir_calculate_execfreq_int_factors(ir_execfreq_int_factors *factors,
ir_graph *irg);
int get_block_execfreq_int(const ir_execfreq_int_factors *factors,
const ir_node *block);
#endif
|
// ... existing code ...
void set_block_execfreq(ir_node *block, double freq);
typedef struct ir_execfreq_int_factors {
double min_non_zero;
double m, b;
} ir_execfreq_int_factors;
// ... rest of the code ...
|
616c0b0722d7b81cad1b4f8d2cfaec24dcfcbf71
|
setup.py
|
setup.py
|
"""setup.py"""
from codecs import open as codecs_open
from setuptools import setup
with codecs_open('README.md', 'r', 'utf-8') as f:
README = f.read()
with codecs_open('HISTORY.md', 'r', 'utf-8') as f:
HISTORY = f.read()
setup(
name='jsonrpcserver',
version='3.5.3',
description='Process JSON-RPC requests',
long_description=README + '\n\n' + HISTORY,
author='Beau Barker',
author_email='[email protected]',
url='https://github.com/bcb/jsonrpcserver',
license='MIT',
packages=['jsonrpcserver'],
package_data={'jsonrpcserver': ['request-schema.json']},
include_package_data=True,
install_requires=['jsonschema', 'six', 'funcsigs'],
extras_require={
'tox': ['tox'],
'examples': [
'aiohttp',
'aiozmq',
'flask',
'flask-socketio',
'pyzmq',
'tornado',
'websockets',
'werkzeug',
]
},
classifiers=[
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6'
],
)
|
"""setup.py"""
from codecs import open as codecs_open
from setuptools import setup
with codecs_open('README.md', 'r', 'utf-8') as f:
README = f.read()
with codecs_open('HISTORY.md', 'r', 'utf-8') as f:
HISTORY = f.read()
setup(
author='Beau Barker',
author_email='[email protected]',
classifiers=[
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6'
],
description='Process JSON-RPC requests',
extras_require={
'tox': ['tox'],
'examples': [
'aiohttp',
'aiozmq',
'flask',
'flask-socketio',
'pyzmq',
'tornado',
'websockets',
'werkzeug',
]
},
include_package_data=True,
install_requires=['jsonschema', 'six', 'funcsigs'],
license='MIT',
long_description=README + '\n\n' + HISTORY,
long_description_content_type='text/markdown',
name='jsonrpcserver',
package_data={'jsonrpcserver': ['request-schema.json']},
packages=['jsonrpcserver'],
url='https://github.com/bcb/jsonrpcserver',
version='3.5.3'
)
|
Set readme content type to markdown
|
Set readme content type to markdown
|
Python
|
mit
|
bcb/jsonrpcserver
|
python
|
## Code Before:
"""setup.py"""
from codecs import open as codecs_open
from setuptools import setup
with codecs_open('README.md', 'r', 'utf-8') as f:
README = f.read()
with codecs_open('HISTORY.md', 'r', 'utf-8') as f:
HISTORY = f.read()
setup(
name='jsonrpcserver',
version='3.5.3',
description='Process JSON-RPC requests',
long_description=README + '\n\n' + HISTORY,
author='Beau Barker',
author_email='[email protected]',
url='https://github.com/bcb/jsonrpcserver',
license='MIT',
packages=['jsonrpcserver'],
package_data={'jsonrpcserver': ['request-schema.json']},
include_package_data=True,
install_requires=['jsonschema', 'six', 'funcsigs'],
extras_require={
'tox': ['tox'],
'examples': [
'aiohttp',
'aiozmq',
'flask',
'flask-socketio',
'pyzmq',
'tornado',
'websockets',
'werkzeug',
]
},
classifiers=[
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6'
],
)
## Instruction:
Set readme content type to markdown
## Code After:
"""setup.py"""
from codecs import open as codecs_open
from setuptools import setup
with codecs_open('README.md', 'r', 'utf-8') as f:
README = f.read()
with codecs_open('HISTORY.md', 'r', 'utf-8') as f:
HISTORY = f.read()
setup(
author='Beau Barker',
author_email='[email protected]',
classifiers=[
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6'
],
description='Process JSON-RPC requests',
extras_require={
'tox': ['tox'],
'examples': [
'aiohttp',
'aiozmq',
'flask',
'flask-socketio',
'pyzmq',
'tornado',
'websockets',
'werkzeug',
]
},
include_package_data=True,
install_requires=['jsonschema', 'six', 'funcsigs'],
license='MIT',
long_description=README + '\n\n' + HISTORY,
long_description_content_type='text/markdown',
name='jsonrpcserver',
package_data={'jsonrpcserver': ['request-schema.json']},
packages=['jsonrpcserver'],
url='https://github.com/bcb/jsonrpcserver',
version='3.5.3'
)
|
# ... existing code ...
with codecs_open('README.md', 'r', 'utf-8') as f:
README = f.read()
with codecs_open('HISTORY.md', 'r', 'utf-8') as f:
HISTORY = f.read()
setup(
author='Beau Barker',
author_email='[email protected]',
classifiers=[
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6'
],
description='Process JSON-RPC requests',
extras_require={
'tox': ['tox'],
'examples': [
# ... modified code ...
'werkzeug',
]
},
include_package_data=True,
install_requires=['jsonschema', 'six', 'funcsigs'],
license='MIT',
long_description=README + '\n\n' + HISTORY,
long_description_content_type='text/markdown',
name='jsonrpcserver',
package_data={'jsonrpcserver': ['request-schema.json']},
packages=['jsonrpcserver'],
url='https://github.com/bcb/jsonrpcserver',
version='3.5.3'
)
# ... rest of the code ...
|
962247710c891af9f847c3c26670c3ab8928219c
|
src/common/angleutils.h
|
src/common/angleutils.h
|
//
// Copyright (c) 2002-2010 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// angleutils.h: Common ANGLE utilities.
#ifndef COMMON_ANGLEUTILS_H_
#define COMMON_ANGLEUTILS_H_
// A macro to disallow the copy constructor and operator= functions
// This must be used in the private: declarations for a class
#define DISALLOW_COPY_AND_ASSIGN(TypeName) \
TypeName(const TypeName&); \
void operator=(const TypeName&)
template <typename T, unsigned int N>
inline unsigned int ArraySize(T(&)[N])
{
return N;
}
#if defined(_MSC_VER)
#define snprintf _snprintf
#endif
#define VENDOR_ID_AMD 0x1002
#define VENDOR_ID_INTEL 0x8086
#define VENDOR_ID_NVIDIA 0x10DE
#define GL_BGRA4_ANGLEX 0x6ABC
#define GL_BGR5_A1_ANGLEX 0x6ABD
#endif // COMMON_ANGLEUTILS_H_
|
//
// Copyright (c) 2002-2010 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// angleutils.h: Common ANGLE utilities.
#ifndef COMMON_ANGLEUTILS_H_
#define COMMON_ANGLEUTILS_H_
// A macro to disallow the copy constructor and operator= functions
// This must be used in the private: declarations for a class
#define DISALLOW_COPY_AND_ASSIGN(TypeName) \
TypeName(const TypeName&); \
void operator=(const TypeName&)
template <typename T, unsigned int N>
inline unsigned int ArraySize(T(&)[N])
{
return N;
}
template <typename T, unsigned int N>
void SafeRelease(T (&resourceBlock)[N])
{
for (unsigned int i = 0; i < N; i++)
{
SafeRelease(resourceBlock[i]);
}
}
template <typename T>
void SafeRelease(T& resource)
{
if (resource)
{
resource->Release();
resource = NULL;
}
}
#if defined(_MSC_VER)
#define snprintf _snprintf
#endif
#define VENDOR_ID_AMD 0x1002
#define VENDOR_ID_INTEL 0x8086
#define VENDOR_ID_NVIDIA 0x10DE
#define GL_BGRA4_ANGLEX 0x6ABC
#define GL_BGR5_A1_ANGLEX 0x6ABD
#endif // COMMON_ANGLEUTILS_H_
|
Add helper functions to safely release Windows COM resources, and arrays of COM resources.
|
Add helper functions to safely release Windows COM resources, and arrays of COM resources.
TRAC #22656
Signed-off-by: Nicolas Capens
Signed-off-by: Shannon Woods
Author: Jamie Madill
git-svn-id: 7288974629ec06eaf04ee103a0a5f761b9efd9a5@2076 736b8ea6-26fd-11df-bfd4-992fa37f6226
|
C
|
bsd-3-clause
|
mikolalysenko/angle,ecoal95/angle,xin3liang/platform_external_chromium_org_third_party_angle,larsbergstrom/angle,bsergean/angle,ghostoy/angle,jgcaaprom/android_external_chromium_org_third_party_angle,bsergean/angle,mrobinson/rust-angle,ghostoy/angle,MIPS/external-chromium_org-third_party-angle,mrobinson/rust-angle,vvuk/angle,nandhanurrevanth/angle,crezefire/angle,geekboxzone/lollipop_external_chromium_org_third_party_angle,mybios/angle,csa7mdm/angle,crezefire/angle,csa7mdm/angle,mrobinson/rust-angle,larsbergstrom/angle,MIPS/external-chromium_org-third_party-angle,xin3liang/platform_external_chromium_org_third_party_angle,vvuk/angle,mrobinson/rust-angle,mikolalysenko/angle,ghostoy/angle,MSOpenTech/angle,nandhanurrevanth/angle,domokit/waterfall,mybios/angle,mrobinson/rust-angle,crezefire/angle,xin3liang/platform_external_chromium_org_third_party_angle,mlfarrell/angle,MIPS/external-chromium_org-third_party-angle,mlfarrell/angle,nandhanurrevanth/angle,ecoal95/angle,ecoal95/angle,csa7mdm/angle,geekboxzone/lollipop_external_chromium_org_third_party_angle,larsbergstrom/angle,ppy/angle,larsbergstrom/angle,mybios/angle,MIPS/external-chromium_org-third_party-angle,crezefire/angle,ghostoy/angle,mlfarrell/angle,geekboxzone/lollipop_external_chromium_org_third_party_angle,MSOpenTech/angle,vvuk/angle,ecoal95/angle,mikolalysenko/angle,android-ia/platform_external_chromium_org_third_party_angle,xin3liang/platform_external_chromium_org_third_party_angle,geekboxzone/lollipop_external_chromium_org_third_party_angle,android-ia/platform_external_chromium_org_third_party_angle,nandhanurrevanth/angle,android-ia/platform_external_chromium_org_third_party_angle,bsergean/angle,domokit/waterfall,ecoal95/angle,jgcaaprom/android_external_chromium_org_third_party_angle,ppy/angle,jgcaaprom/android_external_chromium_org_third_party_angle,jgcaaprom/android_external_chromium_org_third_party_angle,MSOpenTech/angle,ppy/angle,android-ia/platform_external_chromium_org_third_party_angle,csa7mdm/angle,mikolalysenko/angle,mlfarrell/angle,MSOpenTech/angle,bsergean/angle,vvuk/angle,mybios/angle,ppy/angle
|
c
|
## Code Before:
//
// Copyright (c) 2002-2010 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// angleutils.h: Common ANGLE utilities.
#ifndef COMMON_ANGLEUTILS_H_
#define COMMON_ANGLEUTILS_H_
// A macro to disallow the copy constructor and operator= functions
// This must be used in the private: declarations for a class
#define DISALLOW_COPY_AND_ASSIGN(TypeName) \
TypeName(const TypeName&); \
void operator=(const TypeName&)
template <typename T, unsigned int N>
inline unsigned int ArraySize(T(&)[N])
{
return N;
}
#if defined(_MSC_VER)
#define snprintf _snprintf
#endif
#define VENDOR_ID_AMD 0x1002
#define VENDOR_ID_INTEL 0x8086
#define VENDOR_ID_NVIDIA 0x10DE
#define GL_BGRA4_ANGLEX 0x6ABC
#define GL_BGR5_A1_ANGLEX 0x6ABD
#endif // COMMON_ANGLEUTILS_H_
## Instruction:
Add helper functions to safely release Windows COM resources, and arrays of COM resources.
TRAC #22656
Signed-off-by: Nicolas Capens
Signed-off-by: Shannon Woods
Author: Jamie Madill
git-svn-id: 7288974629ec06eaf04ee103a0a5f761b9efd9a5@2076 736b8ea6-26fd-11df-bfd4-992fa37f6226
## Code After:
//
// Copyright (c) 2002-2010 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// angleutils.h: Common ANGLE utilities.
#ifndef COMMON_ANGLEUTILS_H_
#define COMMON_ANGLEUTILS_H_
// A macro to disallow the copy constructor and operator= functions
// This must be used in the private: declarations for a class
#define DISALLOW_COPY_AND_ASSIGN(TypeName) \
TypeName(const TypeName&); \
void operator=(const TypeName&)
template <typename T, unsigned int N>
inline unsigned int ArraySize(T(&)[N])
{
return N;
}
template <typename T, unsigned int N>
void SafeRelease(T (&resourceBlock)[N])
{
for (unsigned int i = 0; i < N; i++)
{
SafeRelease(resourceBlock[i]);
}
}
template <typename T>
void SafeRelease(T& resource)
{
if (resource)
{
resource->Release();
resource = NULL;
}
}
#if defined(_MSC_VER)
#define snprintf _snprintf
#endif
#define VENDOR_ID_AMD 0x1002
#define VENDOR_ID_INTEL 0x8086
#define VENDOR_ID_NVIDIA 0x10DE
#define GL_BGRA4_ANGLEX 0x6ABC
#define GL_BGR5_A1_ANGLEX 0x6ABD
#endif // COMMON_ANGLEUTILS_H_
|
// ... existing code ...
return N;
}
template <typename T, unsigned int N>
void SafeRelease(T (&resourceBlock)[N])
{
for (unsigned int i = 0; i < N; i++)
{
SafeRelease(resourceBlock[i]);
}
}
template <typename T>
void SafeRelease(T& resource)
{
if (resource)
{
resource->Release();
resource = NULL;
}
}
#if defined(_MSC_VER)
#define snprintf _snprintf
#endif
// ... rest of the code ...
|
b4ef0f107ca8fefbe556babb00f31c7b88019d50
|
pydarkstar/__init__.py
|
pydarkstar/__init__.py
|
__version__ = 0.1
import pydarkstar.logutils
import logging
pydarkstar.logutils.setError()
try:
import sqlalchemy
except ImportError as e:
logging.exception(e.__class__.__name__)
logging.error('pip install sqlalchemy')
exit(-1)
try:
import pymysql
except ImportError as e:
logging.exception(e.__class__.__name__)
logging.error('pip install pymysql')
exit(-1)
try:
import bs4
except ImportError as e:
logging.exception(e.__class__.__name__)
logging.error('pip install beautifulsoup4')
exit(-1)
import scrub
|
__version__ = 0.1
import pydarkstar.logutils
import logging
pydarkstar.logutils.setError()
try:
import sqlalchemy
except ImportError as e:
logging.exception(e.__class__.__name__)
logging.error('pip install sqlalchemy')
exit(-1)
try:
import pymysql
except ImportError as e:
logging.exception(e.__class__.__name__)
logging.error('pip install pymysql')
exit(-1)
try:
import bs4
except ImportError as e:
logging.exception(e.__class__.__name__)
logging.error('pip install beautifulsoup4')
exit(-1)
|
Revert "Change imports to relative."
|
Revert "Change imports to relative."
This reverts commit 9d0990249b7e0e46e38a665cb8c32a1ee435c291.
|
Python
|
mit
|
LegionXI/pydarkstar,AdamGagorik/pydarkstar
|
python
|
## Code Before:
__version__ = 0.1
import pydarkstar.logutils
import logging
pydarkstar.logutils.setError()
try:
import sqlalchemy
except ImportError as e:
logging.exception(e.__class__.__name__)
logging.error('pip install sqlalchemy')
exit(-1)
try:
import pymysql
except ImportError as e:
logging.exception(e.__class__.__name__)
logging.error('pip install pymysql')
exit(-1)
try:
import bs4
except ImportError as e:
logging.exception(e.__class__.__name__)
logging.error('pip install beautifulsoup4')
exit(-1)
import scrub
## Instruction:
Revert "Change imports to relative."
This reverts commit 9d0990249b7e0e46e38a665cb8c32a1ee435c291.
## Code After:
__version__ = 0.1
import pydarkstar.logutils
import logging
pydarkstar.logutils.setError()
try:
import sqlalchemy
except ImportError as e:
logging.exception(e.__class__.__name__)
logging.error('pip install sqlalchemy')
exit(-1)
try:
import pymysql
except ImportError as e:
logging.exception(e.__class__.__name__)
logging.error('pip install pymysql')
exit(-1)
try:
import bs4
except ImportError as e:
logging.exception(e.__class__.__name__)
logging.error('pip install beautifulsoup4')
exit(-1)
|
// ... existing code ...
logging.exception(e.__class__.__name__)
logging.error('pip install beautifulsoup4')
exit(-1)
// ... rest of the code ...
|
c0673083709d08f80672cfa58623a667e0edeffa
|
reddit_adzerk/adzerkads.py
|
reddit_adzerk/adzerkads.py
|
from pylons import c, g
from r2.lib.pages import Ads as BaseAds
class Ads(BaseAds):
def __init__(self):
BaseAds.__init__(self)
adzerk_test_srs = g.live_config.get("adzerk_test_srs")
if adzerk_test_srs and c.site.name in adzerk_test_srs:
url_key = "adzerk_https_url" if c.secure else "adzerk_url"
self.ad_url = g.config[url_key].format(
origin=c.request_origin,
)
self.frame_id = "ad_main"
|
from urllib import quote
from pylons import c, g
from r2.lib.pages import Ads as BaseAds
class Ads(BaseAds):
def __init__(self):
BaseAds.__init__(self)
adzerk_test_srs = g.live_config.get("adzerk_test_srs")
if adzerk_test_srs and c.site.name in adzerk_test_srs:
url_key = "adzerk_https_url" if c.secure else "adzerk_url"
self.ad_url = g.config[url_key].format(
subreddit=quote(c.site.name),
origin=c.request_origin,
)
self.frame_id = "ad_main"
|
Add subreddit query param to adzerk frame.
|
Add subreddit query param to adzerk frame.
For tracking / targeting.
|
Python
|
bsd-3-clause
|
madbook/reddit-plugin-adzerk,madbook/reddit-plugin-adzerk,madbook/reddit-plugin-adzerk
|
python
|
## Code Before:
from pylons import c, g
from r2.lib.pages import Ads as BaseAds
class Ads(BaseAds):
def __init__(self):
BaseAds.__init__(self)
adzerk_test_srs = g.live_config.get("adzerk_test_srs")
if adzerk_test_srs and c.site.name in adzerk_test_srs:
url_key = "adzerk_https_url" if c.secure else "adzerk_url"
self.ad_url = g.config[url_key].format(
origin=c.request_origin,
)
self.frame_id = "ad_main"
## Instruction:
Add subreddit query param to adzerk frame.
For tracking / targeting.
## Code After:
from urllib import quote
from pylons import c, g
from r2.lib.pages import Ads as BaseAds
class Ads(BaseAds):
def __init__(self):
BaseAds.__init__(self)
adzerk_test_srs = g.live_config.get("adzerk_test_srs")
if adzerk_test_srs and c.site.name in adzerk_test_srs:
url_key = "adzerk_https_url" if c.secure else "adzerk_url"
self.ad_url = g.config[url_key].format(
subreddit=quote(c.site.name),
origin=c.request_origin,
)
self.frame_id = "ad_main"
|
# ... existing code ...
from urllib import quote
from pylons import c, g
from r2.lib.pages import Ads as BaseAds
# ... modified code ...
if adzerk_test_srs and c.site.name in adzerk_test_srs:
url_key = "adzerk_https_url" if c.secure else "adzerk_url"
self.ad_url = g.config[url_key].format(
subreddit=quote(c.site.name),
origin=c.request_origin,
)
self.frame_id = "ad_main"
# ... rest of the code ...
|
71646a47c1d9e47c4920fefe754b648c270eace4
|
tests/test_cli.py
|
tests/test_cli.py
|
import os
import shutil
from click.testing import CliRunner
from gypsy.scripts.cli import cli
from conftest import DATA_DIR
def remove_path_if_exists(*paths):
for path in paths:
try:
if os.path.isdir(path):
shutil.rmtree(path)
else:
os.remove(path)
except OSError:
pass
def test_prep():
input_data_path = os.path.join(DATA_DIR, 'raw_standtable.csv')
expected_output_path = os.path.splitext(input_data_path)[0] + '_prepped.csv'
remove_path_if_exists(expected_output_path)
runner = CliRunner()
result = runner.invoke(cli, ['prep', input_data_path])
assert result.exit_code == 0
assert result.output == ""
assert os.path.exists(expected_output_path)
def test_simulate():
data_path = os.path.join(DATA_DIR, 'raw_standtable_prepped.csv')
expected_output_path = os.path.join(os.getcwd(), 'gypsy-output')
remove_path_if_exists(expected_output_path)
runner = CliRunner()
result = runner.invoke(cli, ['simulate', data_path])
assert result.exit_code == 0
assert result.output == ""
assert os.path.exists(expected_output_path)
|
import os
import shutil
from click.testing import CliRunner
from gypsy.scripts.cli import cli
from conftest import DATA_DIR
def remove_path_if_exists(*paths): #pylint: disable=missing-docstring
for path in paths:
try:
if os.path.isdir(path):
shutil.rmtree(path)
else:
os.remove(path)
except OSError:
pass
def test_prep():
input_data_path = os.path.join(DATA_DIR, 'raw_standtable.csv')
expected_output_path = os.path.splitext(input_data_path)[0] + '_prepped.csv'
remove_path_if_exists(expected_output_path)
runner = CliRunner()
result = runner.invoke(cli, ['prep', input_data_path])
assert result.exit_code == 0
assert result.output == ""
assert os.path.exists(expected_output_path)
def test_simulate():
data_path = os.path.join(DATA_DIR, 'raw_standtable_prepped.csv')
expected_output_path = os.path.join(os.getcwd(), 'gypsy-output')
remove_path_if_exists(expected_output_path)
runner = CliRunner()
result = runner.invoke(cli, ['simulate', data_path])
assert result.exit_code == 0
assert result.output == ""
assert os.path.exists(expected_output_path)
def test_cli_config_file(): #pylint: disable=missing-docstring
runner = CliRunner()
result = runner.invoke(cli, ['--config-file', 'configfilepath.txt'])
assert result.exit_code == 0
|
Add test that cli accepts config file
|
Add test that cli accepts config file
|
Python
|
mit
|
tesera/pygypsy,tesera/pygypsy
|
python
|
## Code Before:
import os
import shutil
from click.testing import CliRunner
from gypsy.scripts.cli import cli
from conftest import DATA_DIR
def remove_path_if_exists(*paths):
for path in paths:
try:
if os.path.isdir(path):
shutil.rmtree(path)
else:
os.remove(path)
except OSError:
pass
def test_prep():
input_data_path = os.path.join(DATA_DIR, 'raw_standtable.csv')
expected_output_path = os.path.splitext(input_data_path)[0] + '_prepped.csv'
remove_path_if_exists(expected_output_path)
runner = CliRunner()
result = runner.invoke(cli, ['prep', input_data_path])
assert result.exit_code == 0
assert result.output == ""
assert os.path.exists(expected_output_path)
def test_simulate():
data_path = os.path.join(DATA_DIR, 'raw_standtable_prepped.csv')
expected_output_path = os.path.join(os.getcwd(), 'gypsy-output')
remove_path_if_exists(expected_output_path)
runner = CliRunner()
result = runner.invoke(cli, ['simulate', data_path])
assert result.exit_code == 0
assert result.output == ""
assert os.path.exists(expected_output_path)
## Instruction:
Add test that cli accepts config file
## Code After:
import os
import shutil
from click.testing import CliRunner
from gypsy.scripts.cli import cli
from conftest import DATA_DIR
def remove_path_if_exists(*paths): #pylint: disable=missing-docstring
for path in paths:
try:
if os.path.isdir(path):
shutil.rmtree(path)
else:
os.remove(path)
except OSError:
pass
def test_prep():
input_data_path = os.path.join(DATA_DIR, 'raw_standtable.csv')
expected_output_path = os.path.splitext(input_data_path)[0] + '_prepped.csv'
remove_path_if_exists(expected_output_path)
runner = CliRunner()
result = runner.invoke(cli, ['prep', input_data_path])
assert result.exit_code == 0
assert result.output == ""
assert os.path.exists(expected_output_path)
def test_simulate():
data_path = os.path.join(DATA_DIR, 'raw_standtable_prepped.csv')
expected_output_path = os.path.join(os.getcwd(), 'gypsy-output')
remove_path_if_exists(expected_output_path)
runner = CliRunner()
result = runner.invoke(cli, ['simulate', data_path])
assert result.exit_code == 0
assert result.output == ""
assert os.path.exists(expected_output_path)
def test_cli_config_file(): #pylint: disable=missing-docstring
runner = CliRunner()
result = runner.invoke(cli, ['--config-file', 'configfilepath.txt'])
assert result.exit_code == 0
|
# ... existing code ...
from conftest import DATA_DIR
def remove_path_if_exists(*paths): #pylint: disable=missing-docstring
for path in paths:
try:
if os.path.isdir(path):
# ... modified code ...
os.remove(path)
except OSError:
pass
def test_prep():
input_data_path = os.path.join(DATA_DIR, 'raw_standtable.csv')
...
assert result.output == ""
assert os.path.exists(expected_output_path)
def test_simulate():
data_path = os.path.join(DATA_DIR, 'raw_standtable_prepped.csv')
expected_output_path = os.path.join(os.getcwd(), 'gypsy-output')
...
assert result.exit_code == 0
assert result.output == ""
assert os.path.exists(expected_output_path)
def test_cli_config_file(): #pylint: disable=missing-docstring
runner = CliRunner()
result = runner.invoke(cli, ['--config-file', 'configfilepath.txt'])
assert result.exit_code == 0
# ... rest of the code ...
|
2992bb8abc6844c2086ceee59a9b586b5e9a3aff
|
tests/integration/wheel/key.py
|
tests/integration/wheel/key.py
|
from __future__ import absolute_import
import integration
# Import Salt libs
import salt.wheel
class KeyWheelModuleTest(integration.TestCase, integration.AdaptedConfigurationTestCaseMixIn):
def setUp(self):
self.wheel = salt.wheel.Wheel(dict(self.get_config('client_config')))
def test_list_all(self):
ret = self.wheel.cmd('key.list_all', print_event=False)
for host in ['minion', 'sub_minion']:
self.assertIn(host, ret['minions'])
def test_gen(self):
ret = self.wheel.cmd('key.gen', id_='soundtechniciansrock', print_event=False)
self.assertIn('pub', ret)
self.assertIn('priv', ret)
self.assertTrue(
ret.get('pub', '').startswith('-----BEGIN PUBLIC KEY-----'))
self.assertTrue(
ret.get('priv', '').startswith('-----BEGIN RSA PRIVATE KEY-----'))
if __name__ == '__main__':
from integration import run_tests
run_tests(KeyWheelModuleTest, needs_daemon=True)
|
from __future__ import absolute_import
import integration
# Import Salt libs
import salt.wheel
class KeyWheelModuleTest(integration.TestCase, integration.AdaptedConfigurationTestCaseMixIn):
def setUp(self):
self.wheel = salt.wheel.Wheel(dict(self.get_config('client_config')))
def test_list_all(self):
ret = self.wheel.cmd('key.list_all', print_event=False)
for host in ['minion', 'sub_minion']:
self.assertIn(host, ret['minions'])
def test_gen(self):
ret = self.wheel.cmd('key.gen', kwarg={'id_': 'soundtechniciansrock'}, print_event=False)
self.assertIn('pub', ret)
self.assertIn('priv', ret)
self.assertTrue(
ret.get('pub', '').startswith('-----BEGIN PUBLIC KEY-----'))
self.assertTrue(
ret.get('priv', '').startswith('-----BEGIN RSA PRIVATE KEY-----'))
if __name__ == '__main__':
from integration import run_tests
run_tests(KeyWheelModuleTest, needs_daemon=True)
|
Fix args err in wheel test
|
Fix args err in wheel test
|
Python
|
apache-2.0
|
saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt
|
python
|
## Code Before:
from __future__ import absolute_import
import integration
# Import Salt libs
import salt.wheel
class KeyWheelModuleTest(integration.TestCase, integration.AdaptedConfigurationTestCaseMixIn):
def setUp(self):
self.wheel = salt.wheel.Wheel(dict(self.get_config('client_config')))
def test_list_all(self):
ret = self.wheel.cmd('key.list_all', print_event=False)
for host in ['minion', 'sub_minion']:
self.assertIn(host, ret['minions'])
def test_gen(self):
ret = self.wheel.cmd('key.gen', id_='soundtechniciansrock', print_event=False)
self.assertIn('pub', ret)
self.assertIn('priv', ret)
self.assertTrue(
ret.get('pub', '').startswith('-----BEGIN PUBLIC KEY-----'))
self.assertTrue(
ret.get('priv', '').startswith('-----BEGIN RSA PRIVATE KEY-----'))
if __name__ == '__main__':
from integration import run_tests
run_tests(KeyWheelModuleTest, needs_daemon=True)
## Instruction:
Fix args err in wheel test
## Code After:
from __future__ import absolute_import
import integration
# Import Salt libs
import salt.wheel
class KeyWheelModuleTest(integration.TestCase, integration.AdaptedConfigurationTestCaseMixIn):
def setUp(self):
self.wheel = salt.wheel.Wheel(dict(self.get_config('client_config')))
def test_list_all(self):
ret = self.wheel.cmd('key.list_all', print_event=False)
for host in ['minion', 'sub_minion']:
self.assertIn(host, ret['minions'])
def test_gen(self):
ret = self.wheel.cmd('key.gen', kwarg={'id_': 'soundtechniciansrock'}, print_event=False)
self.assertIn('pub', ret)
self.assertIn('priv', ret)
self.assertTrue(
ret.get('pub', '').startswith('-----BEGIN PUBLIC KEY-----'))
self.assertTrue(
ret.get('priv', '').startswith('-----BEGIN RSA PRIVATE KEY-----'))
if __name__ == '__main__':
from integration import run_tests
run_tests(KeyWheelModuleTest, needs_daemon=True)
|
# ... existing code ...
self.assertIn(host, ret['minions'])
def test_gen(self):
ret = self.wheel.cmd('key.gen', kwarg={'id_': 'soundtechniciansrock'}, print_event=False)
self.assertIn('pub', ret)
self.assertIn('priv', ret)
# ... rest of the code ...
|
a9d351559472b751315f9da2b4a93faa3b57b137
|
codenvy-ext-datasource-core/src/main/java/com/codenvy/ide/ext/datasource/client/sqllauncher/SqlRequestLauncherFactory.java
|
codenvy-ext-datasource-core/src/main/java/com/codenvy/ide/ext/datasource/client/sqllauncher/SqlRequestLauncherFactory.java
|
package com.codenvy.ide.ext.datasource.client.sqllauncher;
public interface SqlRequestLauncherFactory {
SqlRequestLauncherView createSqlRequestLauncherView();
SqlRequestLauncherPresenter createSqlRequestLauncherPresenter();
SqlRequestLauncherAdapter createSqlRequestLauncherAdapter();
}
|
package com.codenvy.ide.ext.datasource.client.sqllauncher;
public interface SqlRequestLauncherFactory {
SqlRequestLauncherView createSqlRequestLauncherView();
SqlRequestLauncherPresenter createSqlRequestLauncherPresenter();
}
|
Remove launcher view factory method
|
Remove launcher view factory method
|
Java
|
epl-1.0
|
codenvy/plugin-datasource,codenvy/plugin-datasource
|
java
|
## Code Before:
package com.codenvy.ide.ext.datasource.client.sqllauncher;
public interface SqlRequestLauncherFactory {
SqlRequestLauncherView createSqlRequestLauncherView();
SqlRequestLauncherPresenter createSqlRequestLauncherPresenter();
SqlRequestLauncherAdapter createSqlRequestLauncherAdapter();
}
## Instruction:
Remove launcher view factory method
## Code After:
package com.codenvy.ide.ext.datasource.client.sqllauncher;
public interface SqlRequestLauncherFactory {
SqlRequestLauncherView createSqlRequestLauncherView();
SqlRequestLauncherPresenter createSqlRequestLauncherPresenter();
}
|
# ... existing code ...
SqlRequestLauncherPresenter createSqlRequestLauncherPresenter();
}
# ... rest of the code ...
|
efc1988d704a7a1231046dea8af65dcdba7897fd
|
py/fbx_write.py
|
py/fbx_write.py
|
import sys
import os
import bpy
for sysarg in sys.argv:
print(sysarg)
py_args = sys.argv[sys.argv.index('--') + 1]
py_args = py_args.split(' ')
for arg in py_args:
if (arg.startswith('basedir:')):
basedir = arg.split('basedir:')[1]
else:
# can supply filename(s) with or without extension
pdb_code = os.path.splitext(arg)[0]
abs_file_in = os.path.join(basedir, 'structures/wrl', pdb_code+'.wrl')
# This is the base directory, used for saving files
molecule = bpy.ops.import_scene.x3d(
filepath = abs_file_in
)
abs_file_out = os.path.join(basedir,'structures/fbx',pdb_code+'.fbx')
bpy.ops.export_scene.fbx(
filepath = abs_file_out
)
|
import sys
import os
import bpy
for sysarg in sys.argv:
print(sysarg)
py_args = sys.argv[sys.argv.index('--') + 1]
py_args = py_args.split(' ')
for arg in py_args:
if (arg.startswith('basedir:')):
basedir = arg.split('basedir:')[1]
else:
# can supply filename(s) with or without extension
pdb_code = os.path.splitext(arg)[0]
abs_file_in = os.path.join(basedir, 'structures/wrl', pdb_code+'.wrl')
# This is the base directory, used for saving files
molecule = bpy.ops.import_scene.x3d(
filepath = abs_file_in
)
abs_file_out = os.path.join(basedir,'structures/fbx',pdb_code+'.fbx')
bpy.ops.export_scene.fbx(
filepath = abs_file_out
)
bpy.ops.wm.quit_blender()
|
Quit Blender after writing FBX
|
Quit Blender after writing FBX
|
Python
|
mit
|
hackmcr15-code-a-la-mode/mol-vis-hack,hackmcr15-code-a-la-mode/mol-vis-hack
|
python
|
## Code Before:
import sys
import os
import bpy
for sysarg in sys.argv:
print(sysarg)
py_args = sys.argv[sys.argv.index('--') + 1]
py_args = py_args.split(' ')
for arg in py_args:
if (arg.startswith('basedir:')):
basedir = arg.split('basedir:')[1]
else:
# can supply filename(s) with or without extension
pdb_code = os.path.splitext(arg)[0]
abs_file_in = os.path.join(basedir, 'structures/wrl', pdb_code+'.wrl')
# This is the base directory, used for saving files
molecule = bpy.ops.import_scene.x3d(
filepath = abs_file_in
)
abs_file_out = os.path.join(basedir,'structures/fbx',pdb_code+'.fbx')
bpy.ops.export_scene.fbx(
filepath = abs_file_out
)
## Instruction:
Quit Blender after writing FBX
## Code After:
import sys
import os
import bpy
for sysarg in sys.argv:
print(sysarg)
py_args = sys.argv[sys.argv.index('--') + 1]
py_args = py_args.split(' ')
for arg in py_args:
if (arg.startswith('basedir:')):
basedir = arg.split('basedir:')[1]
else:
# can supply filename(s) with or without extension
pdb_code = os.path.splitext(arg)[0]
abs_file_in = os.path.join(basedir, 'structures/wrl', pdb_code+'.wrl')
# This is the base directory, used for saving files
molecule = bpy.ops.import_scene.x3d(
filepath = abs_file_in
)
abs_file_out = os.path.join(basedir,'structures/fbx',pdb_code+'.fbx')
bpy.ops.export_scene.fbx(
filepath = abs_file_out
)
bpy.ops.wm.quit_blender()
|
...
bpy.ops.export_scene.fbx(
filepath = abs_file_out
)
bpy.ops.wm.quit_blender()
...
|
eeb40831ffd86d4fb17d333e7d0bc67d6a92f8ee
|
src/main/java/com/alexrnl/commons/error/ExceptionUtils.java
|
src/main/java/com/alexrnl/commons/error/ExceptionUtils.java
|
package com.alexrnl.commons.error;
import java.util.Objects;
import java.util.logging.Logger;
/**
* TODO
* @author Alex
*/
public final class ExceptionUtils {
/** Logger */
private static Logger lg = Logger.getLogger(ExceptionUtils.class.getName());
/**
* Constructor #1.<br />
* Default private constructor.
*/
private ExceptionUtils () {
super();
}
/**
*
* @param e
* the throwable object to display.
* @return a {@link String} containing the class and the message of the exception.
* @throws NullPointerException
* if the {@link Throwable} is <code>null</code>.
*/
public static String displayClassAndMessage (final Throwable e) throws NullPointerException {
Objects.requireNonNull(e);
return e.getClass() + "; " + e.getMessage();
}
}
|
package com.alexrnl.commons.error;
import java.util.logging.Logger;
/**
* Utility methods for exception handling.<br />
* @author Alex
*/
public final class ExceptionUtils {
/** Logger */
private static Logger lg = Logger.getLogger(ExceptionUtils.class.getName());
/**
* Constructor #1.<br />
* Default private constructor.
*/
private ExceptionUtils () {
super();
}
/**
* Print a nice message with the {@link Class} and the {@link Throwable#getMessage() message}
* of the exception.<br />
* @param e
* the throwable object to display.
* @return a {@link String} containing the class and the message of the exception.
*/
public static String displayClassAndMessage (final Throwable e) {
if (e == null) {
lg.warning("Cannot display null exception.");
return "null exception caught";
}
return e.getClass() + "; " + e.getMessage();
}
}
|
Complete javadoc and don't throw NPE
|
Complete javadoc and don't throw NPE
|
Java
|
bsd-3-clause
|
AlexRNL/Commons
|
java
|
## Code Before:
package com.alexrnl.commons.error;
import java.util.Objects;
import java.util.logging.Logger;
/**
* TODO
* @author Alex
*/
public final class ExceptionUtils {
/** Logger */
private static Logger lg = Logger.getLogger(ExceptionUtils.class.getName());
/**
* Constructor #1.<br />
* Default private constructor.
*/
private ExceptionUtils () {
super();
}
/**
*
* @param e
* the throwable object to display.
* @return a {@link String} containing the class and the message of the exception.
* @throws NullPointerException
* if the {@link Throwable} is <code>null</code>.
*/
public static String displayClassAndMessage (final Throwable e) throws NullPointerException {
Objects.requireNonNull(e);
return e.getClass() + "; " + e.getMessage();
}
}
## Instruction:
Complete javadoc and don't throw NPE
## Code After:
package com.alexrnl.commons.error;
import java.util.logging.Logger;
/**
* Utility methods for exception handling.<br />
* @author Alex
*/
public final class ExceptionUtils {
/** Logger */
private static Logger lg = Logger.getLogger(ExceptionUtils.class.getName());
/**
* Constructor #1.<br />
* Default private constructor.
*/
private ExceptionUtils () {
super();
}
/**
* Print a nice message with the {@link Class} and the {@link Throwable#getMessage() message}
* of the exception.<br />
* @param e
* the throwable object to display.
* @return a {@link String} containing the class and the message of the exception.
*/
public static String displayClassAndMessage (final Throwable e) {
if (e == null) {
lg.warning("Cannot display null exception.");
return "null exception caught";
}
return e.getClass() + "; " + e.getMessage();
}
}
|
...
package com.alexrnl.commons.error;
import java.util.logging.Logger;
/**
* Utility methods for exception handling.<br />
* @author Alex
*/
public final class ExceptionUtils {
...
}
/**
* Print a nice message with the {@link Class} and the {@link Throwable#getMessage() message}
* of the exception.<br />
* @param e
* the throwable object to display.
* @return a {@link String} containing the class and the message of the exception.
*/
public static String displayClassAndMessage (final Throwable e) {
if (e == null) {
lg.warning("Cannot display null exception.");
return "null exception caught";
}
return e.getClass() + "; " + e.getMessage();
}
}
...
|
d45a05e3563085b8131f3a84c4f3b16c3fab7908
|
kernel/port/heap.c
|
kernel/port/heap.c
|
/* round_up returns `n` rounded to the next value that is zero
* modulo `align`. */
static uintptr_t round_up(uintptr_t n, uintptr_t align) {
if (n % align) {
return n + (align - (n % align));
}
return n;
}
uintptr_t heap_next, heap_end;
void heap_init(uintptr_t start, uintptr_t end) {
heap_next = start;
heap_end = end;
}
void *kalloc_align(uintptr_t size, uintptr_t alignment) {
heap_next = round_up(heap_next, alignment);
uintptr_t ret = heap_next;
heap_next += size;
if(heap_next > heap_end) {
panic("Out of space!");
}
return (void*)ret;
}
void *kalloc(uintptr_t size) {
return kalloc_align(size, sizeof(uintptr_t));
}
void kfree(void *ptr, uintptr_t size) {
}
|
static mutex_t heap_lock;
/* round_up returns `n` rounded to the next value that is zero
* modulo `align`. */
static uintptr_t round_up(uintptr_t n, uintptr_t align) {
if (n % align) {
return n + (align - (n % align));
}
return n;
}
uintptr_t heap_next, heap_end;
void heap_init(uintptr_t start, uintptr_t end) {
heap_next = start;
heap_end = end;
}
void *kalloc_align(uintptr_t size, uintptr_t alignment) {
wait_acquire(&heap_lock);
heap_next = round_up(heap_next, alignment);
uintptr_t ret = heap_next;
heap_next += size;
if(heap_next > heap_end) {
panic("Out of space!");
}
release(&heap_lock);
return (void*)ret;
}
void *kalloc(uintptr_t size) {
return kalloc_align(size, sizeof(uintptr_t));
}
void kfree(void *ptr, uintptr_t size) {
}
|
Put a lock around kalloc*
|
Put a lock around kalloc*
|
C
|
isc
|
zenhack/zero,zenhack/zero,zenhack/zero
|
c
|
## Code Before:
/* round_up returns `n` rounded to the next value that is zero
* modulo `align`. */
static uintptr_t round_up(uintptr_t n, uintptr_t align) {
if (n % align) {
return n + (align - (n % align));
}
return n;
}
uintptr_t heap_next, heap_end;
void heap_init(uintptr_t start, uintptr_t end) {
heap_next = start;
heap_end = end;
}
void *kalloc_align(uintptr_t size, uintptr_t alignment) {
heap_next = round_up(heap_next, alignment);
uintptr_t ret = heap_next;
heap_next += size;
if(heap_next > heap_end) {
panic("Out of space!");
}
return (void*)ret;
}
void *kalloc(uintptr_t size) {
return kalloc_align(size, sizeof(uintptr_t));
}
void kfree(void *ptr, uintptr_t size) {
}
## Instruction:
Put a lock around kalloc*
## Code After:
static mutex_t heap_lock;
/* round_up returns `n` rounded to the next value that is zero
* modulo `align`. */
static uintptr_t round_up(uintptr_t n, uintptr_t align) {
if (n % align) {
return n + (align - (n % align));
}
return n;
}
uintptr_t heap_next, heap_end;
void heap_init(uintptr_t start, uintptr_t end) {
heap_next = start;
heap_end = end;
}
void *kalloc_align(uintptr_t size, uintptr_t alignment) {
wait_acquire(&heap_lock);
heap_next = round_up(heap_next, alignment);
uintptr_t ret = heap_next;
heap_next += size;
if(heap_next > heap_end) {
panic("Out of space!");
}
release(&heap_lock);
return (void*)ret;
}
void *kalloc(uintptr_t size) {
return kalloc_align(size, sizeof(uintptr_t));
}
void kfree(void *ptr, uintptr_t size) {
}
|
// ... existing code ...
static mutex_t heap_lock;
/* round_up returns `n` rounded to the next value that is zero
* modulo `align`. */
// ... modified code ...
}
void *kalloc_align(uintptr_t size, uintptr_t alignment) {
wait_acquire(&heap_lock);
heap_next = round_up(heap_next, alignment);
uintptr_t ret = heap_next;
heap_next += size;
...
if(heap_next > heap_end) {
panic("Out of space!");
}
release(&heap_lock);
return (void*)ret;
}
// ... rest of the code ...
|
3e280e64874d1a68b6bc5fc91a8b6b28968b74e3
|
meinberlin/apps/dashboard2/contents.py
|
meinberlin/apps/dashboard2/contents.py
|
class DashboardContents:
_registry = {}
content = DashboardContents()
|
class DashboardContents:
_registry = {'project': {}, 'module': {}}
def __getitem__(self, identifier):
component = self._registry['project'].get(identifier, None)
if not component:
component = self._registry['module'].get(identifier)
return component
def __contains__(self, identifier):
return (identifier in self._registry['project'] or
identifier in self._registry['module'])
def register_project(self, component):
self._registry['project'][component.identifier] = component
def register_module(self, component):
self._registry['module'][component.identifier] = component
def get_project_components(self):
return self._registry['project'].items()
def get_module_components(self):
return self._registry['module'].items()
content = DashboardContents()
|
Store project and module componentes separately
|
Store project and module componentes separately
|
Python
|
agpl-3.0
|
liqd/a4-meinberlin,liqd/a4-meinberlin,liqd/a4-meinberlin,liqd/a4-meinberlin
|
python
|
## Code Before:
class DashboardContents:
_registry = {}
content = DashboardContents()
## Instruction:
Store project and module componentes separately
## Code After:
class DashboardContents:
_registry = {'project': {}, 'module': {}}
def __getitem__(self, identifier):
component = self._registry['project'].get(identifier, None)
if not component:
component = self._registry['module'].get(identifier)
return component
def __contains__(self, identifier):
return (identifier in self._registry['project'] or
identifier in self._registry['module'])
def register_project(self, component):
self._registry['project'][component.identifier] = component
def register_module(self, component):
self._registry['module'][component.identifier] = component
def get_project_components(self):
return self._registry['project'].items()
def get_module_components(self):
return self._registry['module'].items()
content = DashboardContents()
|
// ... existing code ...
class DashboardContents:
_registry = {'project': {}, 'module': {}}
def __getitem__(self, identifier):
component = self._registry['project'].get(identifier, None)
if not component:
component = self._registry['module'].get(identifier)
return component
def __contains__(self, identifier):
return (identifier in self._registry['project'] or
identifier in self._registry['module'])
def register_project(self, component):
self._registry['project'][component.identifier] = component
def register_module(self, component):
self._registry['module'][component.identifier] = component
def get_project_components(self):
return self._registry['project'].items()
def get_module_components(self):
return self._registry['module'].items()
content = DashboardContents()
// ... rest of the code ...
|
f8dd1fd8ee899c0147a9a88149097e9b7cd68f01
|
tests/generic_views/views.py
|
tests/generic_views/views.py
|
from django.views.generic.edit import CreateView
from templated_email.generic_views import TemplatedEmailFormViewMixin
from tests.generic_views.models import Author
# This view send a welcome email to the author
class AuthorCreateView(TemplatedEmailFormViewMixin, CreateView):
model = Author
fields = ['name', 'email']
templated_email_template_name = 'welcome'
templated_email_recipient_form_field = 'email'
template_name = 'authors/create_author.html'
success_url = '/create_author/'
def templated_email_get_recipients(self, form):
return [form.data['email']]
|
from django.views.generic.edit import CreateView
from templated_email.generic_views import TemplatedEmailFormViewMixin
from tests.generic_views.models import Author
# This view send a welcome email to the author
class AuthorCreateView(TemplatedEmailFormViewMixin, CreateView):
model = Author
fields = ['name', 'email']
templated_email_template_name = 'welcome'
template_name = 'authors/create_author.html'
success_url = '/create_author/'
def templated_email_get_recipients(self, form):
return [form.data['email']]
|
Remove unecessary attribute from test
|
Remove unecessary attribute from test
|
Python
|
mit
|
BradWhittington/django-templated-email,BradWhittington/django-templated-email,vintasoftware/django-templated-email,vintasoftware/django-templated-email
|
python
|
## Code Before:
from django.views.generic.edit import CreateView
from templated_email.generic_views import TemplatedEmailFormViewMixin
from tests.generic_views.models import Author
# This view send a welcome email to the author
class AuthorCreateView(TemplatedEmailFormViewMixin, CreateView):
model = Author
fields = ['name', 'email']
templated_email_template_name = 'welcome'
templated_email_recipient_form_field = 'email'
template_name = 'authors/create_author.html'
success_url = '/create_author/'
def templated_email_get_recipients(self, form):
return [form.data['email']]
## Instruction:
Remove unecessary attribute from test
## Code After:
from django.views.generic.edit import CreateView
from templated_email.generic_views import TemplatedEmailFormViewMixin
from tests.generic_views.models import Author
# This view send a welcome email to the author
class AuthorCreateView(TemplatedEmailFormViewMixin, CreateView):
model = Author
fields = ['name', 'email']
templated_email_template_name = 'welcome'
template_name = 'authors/create_author.html'
success_url = '/create_author/'
def templated_email_get_recipients(self, form):
return [form.data['email']]
|
...
model = Author
fields = ['name', 'email']
templated_email_template_name = 'welcome'
template_name = 'authors/create_author.html'
success_url = '/create_author/'
...
|
1b8bdca8955abe4bbf4b59b9cb528e06bf13b249
|
stream/src/main/java/com/annimon/stream/operator/ObjDistinct.java
|
stream/src/main/java/com/annimon/stream/operator/ObjDistinct.java
|
package com.annimon.stream.operator;
import com.annimon.stream.iterator.LsaExtIterator;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
public class ObjDistinct<T> extends LsaExtIterator<T> {
private final Iterator<? extends T> iterator;
private final Set<T> set;
public ObjDistinct(Iterator<? extends T> iterator) {
this.iterator = iterator;
set = new HashSet<T>();
}
@Override
protected void nextIteration() {
while (hasNext = iterator.hasNext()) {
next = iterator.next();
if (!set.contains(next)) {
set.add(next);
return;
}
}
}
}
|
package com.annimon.stream.operator;
import com.annimon.stream.iterator.LsaExtIterator;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
public class ObjDistinct<T> extends LsaExtIterator<T> {
private final Iterator<? extends T> iterator;
private final Set<T> set;
public ObjDistinct(Iterator<? extends T> iterator) {
this.iterator = iterator;
set = new HashSet<T>();
}
@Override
protected void nextIteration() {
while (hasNext = iterator.hasNext()) {
next = iterator.next();
if (set.add(next)) {
return;
}
}
}
}
|
Remove unnecessary check in distinct operator
|
Remove unnecessary check in distinct operator
|
Java
|
apache-2.0
|
aNNiMON/Lightweight-Stream-API
|
java
|
## Code Before:
package com.annimon.stream.operator;
import com.annimon.stream.iterator.LsaExtIterator;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
public class ObjDistinct<T> extends LsaExtIterator<T> {
private final Iterator<? extends T> iterator;
private final Set<T> set;
public ObjDistinct(Iterator<? extends T> iterator) {
this.iterator = iterator;
set = new HashSet<T>();
}
@Override
protected void nextIteration() {
while (hasNext = iterator.hasNext()) {
next = iterator.next();
if (!set.contains(next)) {
set.add(next);
return;
}
}
}
}
## Instruction:
Remove unnecessary check in distinct operator
## Code After:
package com.annimon.stream.operator;
import com.annimon.stream.iterator.LsaExtIterator;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
public class ObjDistinct<T> extends LsaExtIterator<T> {
private final Iterator<? extends T> iterator;
private final Set<T> set;
public ObjDistinct(Iterator<? extends T> iterator) {
this.iterator = iterator;
set = new HashSet<T>();
}
@Override
protected void nextIteration() {
while (hasNext = iterator.hasNext()) {
next = iterator.next();
if (set.add(next)) {
return;
}
}
}
}
|
# ... existing code ...
protected void nextIteration() {
while (hasNext = iterator.hasNext()) {
next = iterator.next();
if (set.add(next)) {
return;
}
}
# ... rest of the code ...
|
a174fbd637bf9ccc7b8a97a251c016495f92f6a9
|
eliot/__init__.py
|
eliot/__init__.py
|
from ._version import __version__
# Expose the public API:
from ._message import Message
from ._action import startAction, startTask, Action
from ._output import ILogger, Logger, MemoryLogger
from ._validation import Field, MessageType, ActionType
from ._traceback import writeTraceback, writeFailure
addDestination = Logger._destinations.add
removeDestination = Logger._destinations.remove
__all__ = ["Message", "writeTraceback", "writeFailure",
"startAction", "startTask", "Action",
"Field", "MessageType", "ActionType",
"ILogger", "Logger", "MemoryLogger", "addDestination",
"removeDestination",
"__version__",
]
|
from ._version import __version__
# Expose the public API:
from ._message import Message
from ._action import startAction, startTask, Action
from ._output import ILogger, Logger, MemoryLogger
from ._validation import Field, fields, MessageType, ActionType
from ._traceback import writeTraceback, writeFailure
addDestination = Logger._destinations.add
removeDestination = Logger._destinations.remove
__all__ = ["Message", "writeTraceback", "writeFailure",
"startAction", "startTask", "Action",
"Field", "fields", "MessageType", "ActionType",
"ILogger", "Logger", "MemoryLogger", "addDestination",
"removeDestination",
"__version__",
]
|
Add fields to the public API.
|
Add fields to the public API.
|
Python
|
apache-2.0
|
ClusterHQ/eliot,ScatterHQ/eliot,iffy/eliot,ScatterHQ/eliot,ScatterHQ/eliot
|
python
|
## Code Before:
from ._version import __version__
# Expose the public API:
from ._message import Message
from ._action import startAction, startTask, Action
from ._output import ILogger, Logger, MemoryLogger
from ._validation import Field, MessageType, ActionType
from ._traceback import writeTraceback, writeFailure
addDestination = Logger._destinations.add
removeDestination = Logger._destinations.remove
__all__ = ["Message", "writeTraceback", "writeFailure",
"startAction", "startTask", "Action",
"Field", "MessageType", "ActionType",
"ILogger", "Logger", "MemoryLogger", "addDestination",
"removeDestination",
"__version__",
]
## Instruction:
Add fields to the public API.
## Code After:
from ._version import __version__
# Expose the public API:
from ._message import Message
from ._action import startAction, startTask, Action
from ._output import ILogger, Logger, MemoryLogger
from ._validation import Field, fields, MessageType, ActionType
from ._traceback import writeTraceback, writeFailure
addDestination = Logger._destinations.add
removeDestination = Logger._destinations.remove
__all__ = ["Message", "writeTraceback", "writeFailure",
"startAction", "startTask", "Action",
"Field", "fields", "MessageType", "ActionType",
"ILogger", "Logger", "MemoryLogger", "addDestination",
"removeDestination",
"__version__",
]
|
# ... existing code ...
from ._message import Message
from ._action import startAction, startTask, Action
from ._output import ILogger, Logger, MemoryLogger
from ._validation import Field, fields, MessageType, ActionType
from ._traceback import writeTraceback, writeFailure
addDestination = Logger._destinations.add
removeDestination = Logger._destinations.remove
# ... modified code ...
__all__ = ["Message", "writeTraceback", "writeFailure",
"startAction", "startTask", "Action",
"Field", "fields", "MessageType", "ActionType",
"ILogger", "Logger", "MemoryLogger", "addDestination",
"removeDestination",
# ... rest of the code ...
|
bd1375df3d3f66b9f3a188690a4dc464979eaecd
|
logic/src/main/nl/jft/logic/match/event/MatchListener.java
|
logic/src/main/nl/jft/logic/match/event/MatchListener.java
|
package nl.jft.logic.match.event;
import nl.jft.logic.match.Match;
import nl.jft.logic.match.event.impl.GoalRemovedEvent;
import nl.jft.logic.match.event.impl.GoalScoredEvent;
import nl.jft.logic.match.event.impl.MatchStatusChangedEvent;
/**
* A {@code MatchListener} can be used to get notified about certain events in a {@link Match}.
*
* @author Lesley
*/
public interface MatchListener {
void onMatchStatusChanged(MatchStatusChangedEvent event);
void onGoalScored(GoalScoredEvent event);
void onGoalRemoved(GoalRemovedEvent event);
}
|
package nl.jft.logic.match.event;
import nl.jft.logic.match.Match;
import nl.jft.logic.match.event.impl.GoalRemovedEvent;
import nl.jft.logic.match.event.impl.GoalScoredEvent;
import nl.jft.logic.match.event.impl.MatchStatusChangedEvent;
/**
* A {@code MatchListener} can be used to get notified about certain events in a {@link Match}.
*
* @author Lesley
*/
public interface MatchListener {
/**
* The {@code onMatchStatusChanged} method gets called whenever a {@link nl.jft.logic.match.MatchStatus}
* change occurs in a {@link Match}. This method blocks, so make sure to keep the return time as low as possible.
*
* @param event The {@link MatchStatusChangedEvent} that occurred in the {@code Match}.
*/
void onMatchStatusChanged(MatchStatusChangedEvent event);
/**
* The {@code onGoalScored} method gets called whenever a {@link nl.jft.logic.match.Goal}
* is scored in a {@link Match}. This method blocks, so make sure to keep the return time as low as possible.
*
* @param event The {@link GoalScoredEvent} that occurred in the {@code Match}.
*/
void onGoalScored(GoalScoredEvent event);
/**
* The {@code onGoalRemoved} method gets called whenever a {@link nl.jft.logic.match.Goal}
* is removed from a {@link Match}. This method blocks, so make sure to keep the return time as low as possible.
*
* @param event The {@link GoalRemovedEvent} that occurred in the {@code Match}.
*/
void onGoalRemoved(GoalRemovedEvent event);
}
|
Add missing documentation to interface.
|
Add missing documentation to interface.
|
Java
|
mit
|
Just-Foosball-Things/Just-Foosball-Things
|
java
|
## Code Before:
package nl.jft.logic.match.event;
import nl.jft.logic.match.Match;
import nl.jft.logic.match.event.impl.GoalRemovedEvent;
import nl.jft.logic.match.event.impl.GoalScoredEvent;
import nl.jft.logic.match.event.impl.MatchStatusChangedEvent;
/**
* A {@code MatchListener} can be used to get notified about certain events in a {@link Match}.
*
* @author Lesley
*/
public interface MatchListener {
void onMatchStatusChanged(MatchStatusChangedEvent event);
void onGoalScored(GoalScoredEvent event);
void onGoalRemoved(GoalRemovedEvent event);
}
## Instruction:
Add missing documentation to interface.
## Code After:
package nl.jft.logic.match.event;
import nl.jft.logic.match.Match;
import nl.jft.logic.match.event.impl.GoalRemovedEvent;
import nl.jft.logic.match.event.impl.GoalScoredEvent;
import nl.jft.logic.match.event.impl.MatchStatusChangedEvent;
/**
* A {@code MatchListener} can be used to get notified about certain events in a {@link Match}.
*
* @author Lesley
*/
public interface MatchListener {
/**
* The {@code onMatchStatusChanged} method gets called whenever a {@link nl.jft.logic.match.MatchStatus}
* change occurs in a {@link Match}. This method blocks, so make sure to keep the return time as low as possible.
*
* @param event The {@link MatchStatusChangedEvent} that occurred in the {@code Match}.
*/
void onMatchStatusChanged(MatchStatusChangedEvent event);
/**
* The {@code onGoalScored} method gets called whenever a {@link nl.jft.logic.match.Goal}
* is scored in a {@link Match}. This method blocks, so make sure to keep the return time as low as possible.
*
* @param event The {@link GoalScoredEvent} that occurred in the {@code Match}.
*/
void onGoalScored(GoalScoredEvent event);
/**
* The {@code onGoalRemoved} method gets called whenever a {@link nl.jft.logic.match.Goal}
* is removed from a {@link Match}. This method blocks, so make sure to keep the return time as low as possible.
*
* @param event The {@link GoalRemovedEvent} that occurred in the {@code Match}.
*/
void onGoalRemoved(GoalRemovedEvent event);
}
|
// ... existing code ...
*/
public interface MatchListener {
/**
* The {@code onMatchStatusChanged} method gets called whenever a {@link nl.jft.logic.match.MatchStatus}
* change occurs in a {@link Match}. This method blocks, so make sure to keep the return time as low as possible.
*
* @param event The {@link MatchStatusChangedEvent} that occurred in the {@code Match}.
*/
void onMatchStatusChanged(MatchStatusChangedEvent event);
/**
* The {@code onGoalScored} method gets called whenever a {@link nl.jft.logic.match.Goal}
* is scored in a {@link Match}. This method blocks, so make sure to keep the return time as low as possible.
*
* @param event The {@link GoalScoredEvent} that occurred in the {@code Match}.
*/
void onGoalScored(GoalScoredEvent event);
/**
* The {@code onGoalRemoved} method gets called whenever a {@link nl.jft.logic.match.Goal}
* is removed from a {@link Match}. This method blocks, so make sure to keep the return time as low as possible.
*
* @param event The {@link GoalRemovedEvent} that occurred in the {@code Match}.
*/
void onGoalRemoved(GoalRemovedEvent event);
}
// ... rest of the code ...
|
b9d1dcf614faa949975bc5296be451abd2594835
|
repository/presenter.py
|
repository/presenter.py
|
import logger
import datetime
def out(counter, argv, elapsed_time = None):
sum_lines = sum(counter.values())
blue = '\033[94m'
grey = '\033[0m'
endcolor = '\033[0m'
italic = '\x1B[3m'
eitalic = '\x1B[23m'
template = '{0:>7.2%} {3}{2}{4}'
if argv.show_absolute > 0:
template = '{0:>7.2%} {3}{2}{4} ({1})'
top_n = argv.top_n if argv.top_n > 0 else None
sorted_counter = counter.most_common(top_n)
if argv.alphabetically:
sorted_counter = sorted(sorted_counter)
if argv.reverse:
sorted_counter = reversed(sorted_counter)
for author, contributions in sorted_counter:
relative = float(contributions) / float(sum_lines)
output = template.format(relative, contributions, author, blue,
endcolor, italic, eitalic)
print(output)
n_contributors = 'Showing {}/{} contributors'.format(top_n, len(counter))
elapsed ='Elapsed time: {}'.format(datetime.timedelta(seconds=elapsed_time))
logger.instance.info(n_contributors)
logger.instance.info(elapsed)
|
import logger
import datetime
def out(counter, argv, elapsed_time = None):
sum_lines = sum(counter.values())
blue = '\033[94m'
grey = '\033[0m'
endcolor = '\033[0m'
italic = '\x1B[3m'
eitalic = '\x1B[23m'
template = '{0:>7.2%} {3}{2}{4}'
if argv.show_absolute > 0:
template = '{0:>7.2%} {3}{2}{4} ({1})'
top_n = argv.top_n
if top_n < 0 or top_n > len(counter):
top_n = len(counter)
sorted_counter = counter.most_common(top_n)
if argv.alphabetically:
sorted_counter = sorted(sorted_counter)
if argv.reverse:
sorted_counter = reversed(sorted_counter)
for author, contributions in sorted_counter:
relative = float(contributions) / float(sum_lines)
output = template.format(relative, contributions, author, blue,
endcolor, italic, eitalic)
print(output)
n_contributors = 'Showing {}/{} contributors'.format(top_n, len(counter))
elapsed ='Elapsed time: {}'.format(datetime.timedelta(seconds=elapsed_time))
logger.instance.info(n_contributors)
logger.instance.info(elapsed)
|
Fix small issue with `--top-n` command switch
|
Fix small issue with `--top-n` command switch
|
Python
|
mit
|
moacirosa/git-current-contributors,moacirosa/git-current-contributors
|
python
|
## Code Before:
import logger
import datetime
def out(counter, argv, elapsed_time = None):
sum_lines = sum(counter.values())
blue = '\033[94m'
grey = '\033[0m'
endcolor = '\033[0m'
italic = '\x1B[3m'
eitalic = '\x1B[23m'
template = '{0:>7.2%} {3}{2}{4}'
if argv.show_absolute > 0:
template = '{0:>7.2%} {3}{2}{4} ({1})'
top_n = argv.top_n if argv.top_n > 0 else None
sorted_counter = counter.most_common(top_n)
if argv.alphabetically:
sorted_counter = sorted(sorted_counter)
if argv.reverse:
sorted_counter = reversed(sorted_counter)
for author, contributions in sorted_counter:
relative = float(contributions) / float(sum_lines)
output = template.format(relative, contributions, author, blue,
endcolor, italic, eitalic)
print(output)
n_contributors = 'Showing {}/{} contributors'.format(top_n, len(counter))
elapsed ='Elapsed time: {}'.format(datetime.timedelta(seconds=elapsed_time))
logger.instance.info(n_contributors)
logger.instance.info(elapsed)
## Instruction:
Fix small issue with `--top-n` command switch
## Code After:
import logger
import datetime
def out(counter, argv, elapsed_time = None):
sum_lines = sum(counter.values())
blue = '\033[94m'
grey = '\033[0m'
endcolor = '\033[0m'
italic = '\x1B[3m'
eitalic = '\x1B[23m'
template = '{0:>7.2%} {3}{2}{4}'
if argv.show_absolute > 0:
template = '{0:>7.2%} {3}{2}{4} ({1})'
top_n = argv.top_n
if top_n < 0 or top_n > len(counter):
top_n = len(counter)
sorted_counter = counter.most_common(top_n)
if argv.alphabetically:
sorted_counter = sorted(sorted_counter)
if argv.reverse:
sorted_counter = reversed(sorted_counter)
for author, contributions in sorted_counter:
relative = float(contributions) / float(sum_lines)
output = template.format(relative, contributions, author, blue,
endcolor, italic, eitalic)
print(output)
n_contributors = 'Showing {}/{} contributors'.format(top_n, len(counter))
elapsed ='Elapsed time: {}'.format(datetime.timedelta(seconds=elapsed_time))
logger.instance.info(n_contributors)
logger.instance.info(elapsed)
|
// ... existing code ...
if argv.show_absolute > 0:
template = '{0:>7.2%} {3}{2}{4} ({1})'
top_n = argv.top_n
if top_n < 0 or top_n > len(counter):
top_n = len(counter)
sorted_counter = counter.most_common(top_n)
// ... rest of the code ...
|
1a01f99014ead675ba7d043a204cd5f3c47d74b3
|
molecule/builder-trusty/tests/test_build_dependencies.py
|
molecule/builder-trusty/tests/test_build_dependencies.py
|
import pytest
import os
SECUREDROP_TARGET_PLATFORM = os.environ.get("SECUREDROP_TARGET_PLATFORM", "trusty")
testinfra_hosts = [
"docker://{}-sd-app".format(SECUREDROP_TARGET_PLATFORM)
]
def test_pip_wheel_installed(Command):
"""
Ensure `wheel` is installed via pip, for packaging Python
dependencies into a Debian package.
"""
c = Command("pip freeze")
assert "wheel==0.24.0" in c.stdout
assert c.rc == 0
def test_sass_gem_installed(Command):
"""
Ensure the `sass` Ruby gem is installed, for compiling SASS to CSS.
"""
c = Command("gem list")
assert "sass (3.4.23)" in c.stdout
assert c.rc == 0
def test_pip_dependencies_installed(Command):
"""
Ensure the development pip dependencies are installed
"""
c = Command("pip list installed")
assert "Flask-Babel" in c.stdout
assert c.rc == 0
@pytest.mark.xfail(reason="This check conflicts with the concept of pegging"
"dependencies")
def test_build_all_packages_updated(Command):
"""
Ensure a dist-upgrade has already been run, by checking that no
packages are eligible for upgrade currently. This will ensure that
all upgrades, security and otherwise, have been applied to the VM
used to build packages.
"""
c = Command('aptitude --simulate -y dist-upgrade')
assert c.rc == 0
assert "No packages will be installed, upgraded, or removed." in c.stdout
|
import pytest
import os
SECUREDROP_TARGET_PLATFORM = os.environ.get("SECUREDROP_TARGET_PLATFORM", "trusty")
testinfra_hosts = [
"docker://{}-sd-app".format(SECUREDROP_TARGET_PLATFORM)
]
def test_pip_wheel_installed(Command):
"""
Ensure `wheel` is installed via pip, for packaging Python
dependencies into a Debian package.
"""
c = Command("pip list installed")
assert "wheel" in c.stdout
assert c.rc == 0
def test_sass_gem_installed(Command):
"""
Ensure the `sass` Ruby gem is installed, for compiling SASS to CSS.
"""
c = Command("gem list")
assert "sass (3.4.23)" in c.stdout
assert c.rc == 0
def test_pip_dependencies_installed(Command):
"""
Ensure the development pip dependencies are installed
"""
c = Command("pip list installed")
assert "Flask-Babel" in c.stdout
assert c.rc == 0
@pytest.mark.xfail(reason="This check conflicts with the concept of pegging"
"dependencies")
def test_build_all_packages_updated(Command):
"""
Ensure a dist-upgrade has already been run, by checking that no
packages are eligible for upgrade currently. This will ensure that
all upgrades, security and otherwise, have been applied to the VM
used to build packages.
"""
c = Command('aptitude --simulate -y dist-upgrade')
assert c.rc == 0
assert "No packages will be installed, upgraded, or removed." in c.stdout
|
Fix test for wheel in Xenial and Trusty
|
Fix test for wheel in Xenial and Trusty
|
Python
|
agpl-3.0
|
conorsch/securedrop,heartsucker/securedrop,conorsch/securedrop,ehartsuyker/securedrop,conorsch/securedrop,ehartsuyker/securedrop,ehartsuyker/securedrop,heartsucker/securedrop,ehartsuyker/securedrop,conorsch/securedrop,heartsucker/securedrop,heartsucker/securedrop,ehartsuyker/securedrop,heartsucker/securedrop,conorsch/securedrop,ehartsuyker/securedrop
|
python
|
## Code Before:
import pytest
import os
SECUREDROP_TARGET_PLATFORM = os.environ.get("SECUREDROP_TARGET_PLATFORM", "trusty")
testinfra_hosts = [
"docker://{}-sd-app".format(SECUREDROP_TARGET_PLATFORM)
]
def test_pip_wheel_installed(Command):
"""
Ensure `wheel` is installed via pip, for packaging Python
dependencies into a Debian package.
"""
c = Command("pip freeze")
assert "wheel==0.24.0" in c.stdout
assert c.rc == 0
def test_sass_gem_installed(Command):
"""
Ensure the `sass` Ruby gem is installed, for compiling SASS to CSS.
"""
c = Command("gem list")
assert "sass (3.4.23)" in c.stdout
assert c.rc == 0
def test_pip_dependencies_installed(Command):
"""
Ensure the development pip dependencies are installed
"""
c = Command("pip list installed")
assert "Flask-Babel" in c.stdout
assert c.rc == 0
@pytest.mark.xfail(reason="This check conflicts with the concept of pegging"
"dependencies")
def test_build_all_packages_updated(Command):
"""
Ensure a dist-upgrade has already been run, by checking that no
packages are eligible for upgrade currently. This will ensure that
all upgrades, security and otherwise, have been applied to the VM
used to build packages.
"""
c = Command('aptitude --simulate -y dist-upgrade')
assert c.rc == 0
assert "No packages will be installed, upgraded, or removed." in c.stdout
## Instruction:
Fix test for wheel in Xenial and Trusty
## Code After:
import pytest
import os
SECUREDROP_TARGET_PLATFORM = os.environ.get("SECUREDROP_TARGET_PLATFORM", "trusty")
testinfra_hosts = [
"docker://{}-sd-app".format(SECUREDROP_TARGET_PLATFORM)
]
def test_pip_wheel_installed(Command):
"""
Ensure `wheel` is installed via pip, for packaging Python
dependencies into a Debian package.
"""
c = Command("pip list installed")
assert "wheel" in c.stdout
assert c.rc == 0
def test_sass_gem_installed(Command):
"""
Ensure the `sass` Ruby gem is installed, for compiling SASS to CSS.
"""
c = Command("gem list")
assert "sass (3.4.23)" in c.stdout
assert c.rc == 0
def test_pip_dependencies_installed(Command):
"""
Ensure the development pip dependencies are installed
"""
c = Command("pip list installed")
assert "Flask-Babel" in c.stdout
assert c.rc == 0
@pytest.mark.xfail(reason="This check conflicts with the concept of pegging"
"dependencies")
def test_build_all_packages_updated(Command):
"""
Ensure a dist-upgrade has already been run, by checking that no
packages are eligible for upgrade currently. This will ensure that
all upgrades, security and otherwise, have been applied to the VM
used to build packages.
"""
c = Command('aptitude --simulate -y dist-upgrade')
assert c.rc == 0
assert "No packages will be installed, upgraded, or removed." in c.stdout
|
// ... existing code ...
Ensure `wheel` is installed via pip, for packaging Python
dependencies into a Debian package.
"""
c = Command("pip list installed")
assert "wheel" in c.stdout
assert c.rc == 0
// ... rest of the code ...
|
79ecdd107f7531d36f69d6e7089b4a685a370312
|
src/graphics_tb.h
|
src/graphics_tb.h
|
typedef struct {} graphics_tb_t;
// graphics_tb initialize the graphic module.
graphics_tb_t *graphics_tb_init();
// graphics_tb_draw draws the given state on the screen.
void graphics_tb_draw(void *context, state_to_draw_t *state);
// graphics_tb_quit terminate the graphic module.
void graphics_tb_quit(graphics_tb_t *tg);
#endif
|
typedef struct {} graphics_tb_t;
// graphics_tb initializes the graphic module.
graphics_tb_t *graphics_tb_init();
// graphics_tb_draw draws the given state on the screen.
//
// We do not use `graphics_tb_t *tg` but `void *context` because this function
// is used as a callback and the caller shouldn't have to know about
// graphics_tb. This way, this module is pluggable.
void graphics_tb_draw(void *context, state_to_draw_t *state);
// graphics_tb_quit terminates the graphic module.
void graphics_tb_quit(graphics_tb_t *tg);
#endif
|
Add an explanation for graphics_*_draw prototype
|
Add an explanation for graphics_*_draw prototype
|
C
|
mit
|
moverest/bagh-chal,moverest/bagh-chal,moverest/bagh-chal
|
c
|
## Code Before:
typedef struct {} graphics_tb_t;
// graphics_tb initialize the graphic module.
graphics_tb_t *graphics_tb_init();
// graphics_tb_draw draws the given state on the screen.
void graphics_tb_draw(void *context, state_to_draw_t *state);
// graphics_tb_quit terminate the graphic module.
void graphics_tb_quit(graphics_tb_t *tg);
#endif
## Instruction:
Add an explanation for graphics_*_draw prototype
## Code After:
typedef struct {} graphics_tb_t;
// graphics_tb initializes the graphic module.
graphics_tb_t *graphics_tb_init();
// graphics_tb_draw draws the given state on the screen.
//
// We do not use `graphics_tb_t *tg` but `void *context` because this function
// is used as a callback and the caller shouldn't have to know about
// graphics_tb. This way, this module is pluggable.
void graphics_tb_draw(void *context, state_to_draw_t *state);
// graphics_tb_quit terminates the graphic module.
void graphics_tb_quit(graphics_tb_t *tg);
#endif
|
...
typedef struct {} graphics_tb_t;
// graphics_tb initializes the graphic module.
graphics_tb_t *graphics_tb_init();
// graphics_tb_draw draws the given state on the screen.
//
// We do not use `graphics_tb_t *tg` but `void *context` because this function
// is used as a callback and the caller shouldn't have to know about
// graphics_tb. This way, this module is pluggable.
void graphics_tb_draw(void *context, state_to_draw_t *state);
// graphics_tb_quit terminates the graphic module.
void graphics_tb_quit(graphics_tb_t *tg);
...
|
47dd8c7616abecd4a2b9fcfc2835e65edc998245
|
atlassian-plugins-spring/src/main/java/com/atlassian/plugin/spring/SpringAwarePackageScannerConfiguration.java
|
atlassian-plugins-spring/src/main/java/com/atlassian/plugin/spring/SpringAwarePackageScannerConfiguration.java
|
package com.atlassian.plugin.spring;
import com.atlassian.plugin.osgi.container.impl.DefaultPackageScannerConfiguration;
import org.springframework.web.context.ServletContextAware;
import javax.servlet.ServletContext;
/**
* Spring-aware extension of the package scanner configuration that instructs spring to inject the servlet context
*/
public class SpringAwarePackageScannerConfiguration extends DefaultPackageScannerConfiguration implements ServletContextAware
{
@Override
public void setServletContext(ServletContext servletContext)
{
super.setServletContext(servletContext);
}
}
|
package com.atlassian.plugin.spring;
import com.atlassian.plugin.osgi.container.impl.DefaultPackageScannerConfiguration;
import org.springframework.web.context.ServletContextAware;
import javax.servlet.ServletContext;
/**
* Spring-aware extension of the package scanner configuration that instructs spring to inject the servlet context
*/
public class SpringAwarePackageScannerConfiguration extends DefaultPackageScannerConfiguration implements ServletContextAware
{
public SpringAwarePackageScannerConfiguration()
{
super();
}
public SpringAwarePackageScannerConfiguration(String hostVersion)
{
super(hostVersion);
}
@Override
public void setServletContext(ServletContext servletContext)
{
super.setServletContext(servletContext);
}
}
|
Make sure Spring config provides both constructors
|
Make sure Spring config provides both constructors
git-svn-id: 3d1f0b8d955af71bf8e09c956c180519124e4717@26448 2c54a935-e501-0410-bc05-97a93f6bca70
|
Java
|
bsd-3-clause
|
mrdon/PLUG
|
java
|
## Code Before:
package com.atlassian.plugin.spring;
import com.atlassian.plugin.osgi.container.impl.DefaultPackageScannerConfiguration;
import org.springframework.web.context.ServletContextAware;
import javax.servlet.ServletContext;
/**
* Spring-aware extension of the package scanner configuration that instructs spring to inject the servlet context
*/
public class SpringAwarePackageScannerConfiguration extends DefaultPackageScannerConfiguration implements ServletContextAware
{
@Override
public void setServletContext(ServletContext servletContext)
{
super.setServletContext(servletContext);
}
}
## Instruction:
Make sure Spring config provides both constructors
git-svn-id: 3d1f0b8d955af71bf8e09c956c180519124e4717@26448 2c54a935-e501-0410-bc05-97a93f6bca70
## Code After:
package com.atlassian.plugin.spring;
import com.atlassian.plugin.osgi.container.impl.DefaultPackageScannerConfiguration;
import org.springframework.web.context.ServletContextAware;
import javax.servlet.ServletContext;
/**
* Spring-aware extension of the package scanner configuration that instructs spring to inject the servlet context
*/
public class SpringAwarePackageScannerConfiguration extends DefaultPackageScannerConfiguration implements ServletContextAware
{
public SpringAwarePackageScannerConfiguration()
{
super();
}
public SpringAwarePackageScannerConfiguration(String hostVersion)
{
super(hostVersion);
}
@Override
public void setServletContext(ServletContext servletContext)
{
super.setServletContext(servletContext);
}
}
|
# ... existing code ...
*/
public class SpringAwarePackageScannerConfiguration extends DefaultPackageScannerConfiguration implements ServletContextAware
{
public SpringAwarePackageScannerConfiguration()
{
super();
}
public SpringAwarePackageScannerConfiguration(String hostVersion)
{
super(hostVersion);
}
@Override
public void setServletContext(ServletContext servletContext)
{
# ... rest of the code ...
|
5c874677cc978e1cdd563a563d62bae162d3b7ac
|
mycroft/skills/audioservice.py
|
mycroft/skills/audioservice.py
|
import time
from mycroft.messagebus.message import Message
class AudioService():
def __init__(self, emitter):
self.emitter = emitter
self.emitter.on('MycroftAudioServiceTrackInfoReply', self._track_info)
self.info = None
def _track_info(self, message=None):
self.info = message.data
def play(self, tracks=[], utterance=''):
self.emitter.emit(Message('MycroftAudioServicePlay',
data={'tracks': tracks,
'utterance': utterance}))
def track_info(self):
self.info = None
self.emitter.emit(Message('MycroftAudioServiceTrackInfo'))
while self.info is None:
time.sleep(0.1)
return self.info
|
import time
from mycroft.messagebus.message import Message
class AudioService():
def __init__(self, emitter):
self.emitter = emitter
self.emitter.on('MycroftAudioServiceTrackInfoReply', self._track_info)
self.info = None
def _track_info(self, message=None):
self.info = message.data
def play(self, tracks=[], utterance=''):
if isinstance(tracks, basestring):
tracks = [tracks]
elif not isinstance(tracks, list):
raise ValueError
self.emitter.emit(Message('MycroftAudioServicePlay',
data={'tracks': tracks,
'utterance': utterance}))
def track_info(self):
self.info = None
self.emitter.emit(Message('MycroftAudioServiceTrackInfo'))
while self.info is None:
time.sleep(0.1)
return self.info
|
Add check for valid type of tracks
|
Add check for valid type of tracks
|
Python
|
apache-2.0
|
aatchison/mycroft-core,MycroftAI/mycroft-core,MycroftAI/mycroft-core,aatchison/mycroft-core,linuxipho/mycroft-core,forslund/mycroft-core,linuxipho/mycroft-core,Dark5ide/mycroft-core,Dark5ide/mycroft-core,forslund/mycroft-core
|
python
|
## Code Before:
import time
from mycroft.messagebus.message import Message
class AudioService():
def __init__(self, emitter):
self.emitter = emitter
self.emitter.on('MycroftAudioServiceTrackInfoReply', self._track_info)
self.info = None
def _track_info(self, message=None):
self.info = message.data
def play(self, tracks=[], utterance=''):
self.emitter.emit(Message('MycroftAudioServicePlay',
data={'tracks': tracks,
'utterance': utterance}))
def track_info(self):
self.info = None
self.emitter.emit(Message('MycroftAudioServiceTrackInfo'))
while self.info is None:
time.sleep(0.1)
return self.info
## Instruction:
Add check for valid type of tracks
## Code After:
import time
from mycroft.messagebus.message import Message
class AudioService():
def __init__(self, emitter):
self.emitter = emitter
self.emitter.on('MycroftAudioServiceTrackInfoReply', self._track_info)
self.info = None
def _track_info(self, message=None):
self.info = message.data
def play(self, tracks=[], utterance=''):
if isinstance(tracks, basestring):
tracks = [tracks]
elif not isinstance(tracks, list):
raise ValueError
self.emitter.emit(Message('MycroftAudioServicePlay',
data={'tracks': tracks,
'utterance': utterance}))
def track_info(self):
self.info = None
self.emitter.emit(Message('MycroftAudioServiceTrackInfo'))
while self.info is None:
time.sleep(0.1)
return self.info
|
// ... existing code ...
self.info = message.data
def play(self, tracks=[], utterance=''):
if isinstance(tracks, basestring):
tracks = [tracks]
elif not isinstance(tracks, list):
raise ValueError
self.emitter.emit(Message('MycroftAudioServicePlay',
data={'tracks': tracks,
'utterance': utterance}))
// ... rest of the code ...
|
8a6513105010a0e334ccf8cf3f4c017abf2b44ae
|
src/sail/game_struct.h
|
src/sail/game_struct.h
|
/*
* Copyright (C) 2015 Luke San Antonio
* All rights reserved.
*/
#pragma once
#include "../common/id_map.hpp"
#include "boat.h"
#include "../collisionlib/motion.h"
namespace redc { namespace sail
{
struct Player
{
std::string name;
bool spawned;
Hull_Desc boat_config;
collis::Motion boat_motion;
};
struct Game
{
ID_Map<Player> players;
};
} }
|
/*
* Copyright (C) 2015 Luke San Antonio
* All rights reserved.
*/
#pragma once
#include "../common/id_map.hpp"
#include "boat.h"
#include "../collisionlib/motion.h"
namespace redc { namespace sail
{
struct Player
{
std::string name;
bool spawned;
Hull_Desc boat_config;
collis::Motion boat_motion;
void* userdata;
};
struct Game
{
ID_Map<Player> players;
};
} }
|
Add user data to Game struct
|
Add user data to Game struct
|
C
|
bsd-3-clause
|
RedCraneStudio/redcrane-engine,RedCraneStudio/redcrane-engine,RedCraneStudio/redcrane-engine,RedCraneStudio/redcrane-engine
|
c
|
## Code Before:
/*
* Copyright (C) 2015 Luke San Antonio
* All rights reserved.
*/
#pragma once
#include "../common/id_map.hpp"
#include "boat.h"
#include "../collisionlib/motion.h"
namespace redc { namespace sail
{
struct Player
{
std::string name;
bool spawned;
Hull_Desc boat_config;
collis::Motion boat_motion;
};
struct Game
{
ID_Map<Player> players;
};
} }
## Instruction:
Add user data to Game struct
## Code After:
/*
* Copyright (C) 2015 Luke San Antonio
* All rights reserved.
*/
#pragma once
#include "../common/id_map.hpp"
#include "boat.h"
#include "../collisionlib/motion.h"
namespace redc { namespace sail
{
struct Player
{
std::string name;
bool spawned;
Hull_Desc boat_config;
collis::Motion boat_motion;
void* userdata;
};
struct Game
{
ID_Map<Player> players;
};
} }
|
...
Hull_Desc boat_config;
collis::Motion boat_motion;
void* userdata;
};
struct Game
...
|
2050385a5f5fdcffe333ae17463d6469af0b5cd8
|
mopidy/__init__.py
|
mopidy/__init__.py
|
from __future__ import unicode_literals
import sys
import warnings
from distutils.version import StrictVersion as SV
import pykka
if not (2, 7) <= sys.version_info < (3,):
sys.exit(
'Mopidy requires Python >= 2.7, < 3, but found %s' %
'.'.join(map(str, sys.version_info[:3])))
if (isinstance(pykka.__version__, basestring)
and not SV('1.1') <= SV(pykka.__version__) < SV('2.0')):
sys.exit(
'Mopidy requires Pykka >= 1.1, < 2, but found %s' % pykka.__version__)
warnings.filterwarnings('ignore', 'could not open display')
__version__ = '0.19.4'
|
from __future__ import unicode_literals
import platform
import sys
import warnings
from distutils.version import StrictVersion as SV
import pykka
if not (2, 7) <= sys.version_info < (3,):
sys.exit(
'ERROR: Mopidy requires Python 2.7, but found %s.' %
platform.python_version())
if (isinstance(pykka.__version__, basestring)
and not SV('1.1') <= SV(pykka.__version__) < SV('2.0')):
sys.exit(
'ERROR: Mopidy requires Pykka >= 1.1, < 2, but found %s.' %
pykka.__version__)
warnings.filterwarnings('ignore', 'could not open display')
__version__ = '0.19.4'
|
Update Python and Pykka version check error messages
|
Update Python and Pykka version check error messages
|
Python
|
apache-2.0
|
jmarsik/mopidy,adamcik/mopidy,priestd09/mopidy,woutervanwijk/mopidy,glogiotatidis/mopidy,tkem/mopidy,bencevans/mopidy,hkariti/mopidy,jcass77/mopidy,pacificIT/mopidy,vrs01/mopidy,ali/mopidy,bencevans/mopidy,mokieyue/mopidy,rawdlite/mopidy,swak/mopidy,tkem/mopidy,rawdlite/mopidy,jcass77/mopidy,woutervanwijk/mopidy,swak/mopidy,swak/mopidy,SuperStarPL/mopidy,SuperStarPL/mopidy,dbrgn/mopidy,mopidy/mopidy,bencevans/mopidy,jcass77/mopidy,glogiotatidis/mopidy,ZenithDK/mopidy,mokieyue/mopidy,SuperStarPL/mopidy,jodal/mopidy,mopidy/mopidy,ali/mopidy,tkem/mopidy,pacificIT/mopidy,quartz55/mopidy,dbrgn/mopidy,ali/mopidy,rawdlite/mopidy,pacificIT/mopidy,glogiotatidis/mopidy,pacificIT/mopidy,rawdlite/mopidy,priestd09/mopidy,jodal/mopidy,priestd09/mopidy,dbrgn/mopidy,hkariti/mopidy,jmarsik/mopidy,mopidy/mopidy,ZenithDK/mopidy,jmarsik/mopidy,dbrgn/mopidy,quartz55/mopidy,SuperStarPL/mopidy,kingosticks/mopidy,bacontext/mopidy,hkariti/mopidy,kingosticks/mopidy,tkem/mopidy,jodal/mopidy,jmarsik/mopidy,diandiankan/mopidy,diandiankan/mopidy,ZenithDK/mopidy,vrs01/mopidy,ZenithDK/mopidy,vrs01/mopidy,bacontext/mopidy,ali/mopidy,bencevans/mopidy,hkariti/mopidy,bacontext/mopidy,swak/mopidy,quartz55/mopidy,mokieyue/mopidy,diandiankan/mopidy,adamcik/mopidy,glogiotatidis/mopidy,kingosticks/mopidy,adamcik/mopidy,quartz55/mopidy,bacontext/mopidy,vrs01/mopidy,mokieyue/mopidy,diandiankan/mopidy
|
python
|
## Code Before:
from __future__ import unicode_literals
import sys
import warnings
from distutils.version import StrictVersion as SV
import pykka
if not (2, 7) <= sys.version_info < (3,):
sys.exit(
'Mopidy requires Python >= 2.7, < 3, but found %s' %
'.'.join(map(str, sys.version_info[:3])))
if (isinstance(pykka.__version__, basestring)
and not SV('1.1') <= SV(pykka.__version__) < SV('2.0')):
sys.exit(
'Mopidy requires Pykka >= 1.1, < 2, but found %s' % pykka.__version__)
warnings.filterwarnings('ignore', 'could not open display')
__version__ = '0.19.4'
## Instruction:
Update Python and Pykka version check error messages
## Code After:
from __future__ import unicode_literals
import platform
import sys
import warnings
from distutils.version import StrictVersion as SV
import pykka
if not (2, 7) <= sys.version_info < (3,):
sys.exit(
'ERROR: Mopidy requires Python 2.7, but found %s.' %
platform.python_version())
if (isinstance(pykka.__version__, basestring)
and not SV('1.1') <= SV(pykka.__version__) < SV('2.0')):
sys.exit(
'ERROR: Mopidy requires Pykka >= 1.1, < 2, but found %s.' %
pykka.__version__)
warnings.filterwarnings('ignore', 'could not open display')
__version__ = '0.19.4'
|
...
from __future__ import unicode_literals
import platform
import sys
import warnings
from distutils.version import StrictVersion as SV
...
if not (2, 7) <= sys.version_info < (3,):
sys.exit(
'ERROR: Mopidy requires Python 2.7, but found %s.' %
platform.python_version())
if (isinstance(pykka.__version__, basestring)
and not SV('1.1') <= SV(pykka.__version__) < SV('2.0')):
sys.exit(
'ERROR: Mopidy requires Pykka >= 1.1, < 2, but found %s.' %
pykka.__version__)
warnings.filterwarnings('ignore', 'could not open display')
...
|
c1433f2c6b099931d1a99c95f4d64824595eeab5
|
xstream/src/java/com/thoughtworks/xstream/core/util/FastField.java
|
xstream/src/java/com/thoughtworks/xstream/core/util/FastField.java
|
/*
* Copyright (C) 2008 XStream Committers.
* All rights reserved.
*
* The software in this package is published under the terms of the BSD
* style license a copy of which has been included with this distribution in
* the LICENSE.txt file.
*
* Created on 13. October 2008 by Joerg Schaible
*/
package com.thoughtworks.xstream.core.util;
public final class FastField {
private final String name;
private final Class declaringClass;
public FastField(Class definedIn, String name) {
this.name = name;
this.declaringClass = definedIn;
}
public String getName() {
return this.name;
}
public Class getDeclaringClass() {
return this.declaringClass;
}
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (this == null) {
return false;
}
if (obj.getClass() == FastField.class) {
final FastField field = (FastField)obj;
return name.equals(field.getName())
&& declaringClass.equals(field.getDeclaringClass());
}
return false;
}
public int hashCode() {
return name.hashCode() ^ declaringClass.hashCode();
}
public String toString() {
return declaringClass.getName() + "[" + name + "]";
}
}
|
/*
* Copyright (C) 2008, 2010 XStream Committers.
* All rights reserved.
*
* The software in this package is published under the terms of the BSD
* style license a copy of which has been included with this distribution in
* the LICENSE.txt file.
*
* Created on 13. October 2008 by Joerg Schaible
*/
package com.thoughtworks.xstream.core.util;
public final class FastField {
private final String name;
private final Class declaringClass;
public FastField(Class definedIn, String name) {
this.name = name;
this.declaringClass = definedIn;
}
public String getName() {
return this.name;
}
public Class getDeclaringClass() {
return this.declaringClass;
}
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (this == null) {
return false;
}
if (obj.getClass() == FastField.class) {
final FastField field = (FastField)obj;
if ((declaringClass == null && field.declaringClass != null)
|| (declaringClass != null && field.declaringClass == null)) {
return false;
}
return name.equals(field.getName())
&& (declaringClass == null || declaringClass.equals(field.getDeclaringClass()));
}
return false;
}
public int hashCode() {
return name.hashCode() ^ (declaringClass == null ? 0 : declaringClass.hashCode());
}
public String toString() {
return (declaringClass == null ? "" : declaringClass.getName() + ".") + name;
}
}
|
Allow null as defining class.
|
Allow null as defining class.
git-svn-id: fe6d842192ccfb78748eb71580d1ce65f168b559@1736 9830eeb5-ddf4-0310-9ef7-f4b9a3e3227e
|
Java
|
bsd-3-clause
|
vkscool/xstream,Groostav/xstream,emopers/xstream,Groostav/xstream,emopers/xstream,tenghuihua/xstream,tenghuihua/xstream,vkscool/xstream
|
java
|
## Code Before:
/*
* Copyright (C) 2008 XStream Committers.
* All rights reserved.
*
* The software in this package is published under the terms of the BSD
* style license a copy of which has been included with this distribution in
* the LICENSE.txt file.
*
* Created on 13. October 2008 by Joerg Schaible
*/
package com.thoughtworks.xstream.core.util;
public final class FastField {
private final String name;
private final Class declaringClass;
public FastField(Class definedIn, String name) {
this.name = name;
this.declaringClass = definedIn;
}
public String getName() {
return this.name;
}
public Class getDeclaringClass() {
return this.declaringClass;
}
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (this == null) {
return false;
}
if (obj.getClass() == FastField.class) {
final FastField field = (FastField)obj;
return name.equals(field.getName())
&& declaringClass.equals(field.getDeclaringClass());
}
return false;
}
public int hashCode() {
return name.hashCode() ^ declaringClass.hashCode();
}
public String toString() {
return declaringClass.getName() + "[" + name + "]";
}
}
## Instruction:
Allow null as defining class.
git-svn-id: fe6d842192ccfb78748eb71580d1ce65f168b559@1736 9830eeb5-ddf4-0310-9ef7-f4b9a3e3227e
## Code After:
/*
* Copyright (C) 2008, 2010 XStream Committers.
* All rights reserved.
*
* The software in this package is published under the terms of the BSD
* style license a copy of which has been included with this distribution in
* the LICENSE.txt file.
*
* Created on 13. October 2008 by Joerg Schaible
*/
package com.thoughtworks.xstream.core.util;
public final class FastField {
private final String name;
private final Class declaringClass;
public FastField(Class definedIn, String name) {
this.name = name;
this.declaringClass = definedIn;
}
public String getName() {
return this.name;
}
public Class getDeclaringClass() {
return this.declaringClass;
}
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (this == null) {
return false;
}
if (obj.getClass() == FastField.class) {
final FastField field = (FastField)obj;
if ((declaringClass == null && field.declaringClass != null)
|| (declaringClass != null && field.declaringClass == null)) {
return false;
}
return name.equals(field.getName())
&& (declaringClass == null || declaringClass.equals(field.getDeclaringClass()));
}
return false;
}
public int hashCode() {
return name.hashCode() ^ (declaringClass == null ? 0 : declaringClass.hashCode());
}
public String toString() {
return (declaringClass == null ? "" : declaringClass.getName() + ".") + name;
}
}
|
...
/*
* Copyright (C) 2008, 2010 XStream Committers.
* All rights reserved.
*
* The software in this package is published under the terms of the BSD
...
}
if (obj.getClass() == FastField.class) {
final FastField field = (FastField)obj;
if ((declaringClass == null && field.declaringClass != null)
|| (declaringClass != null && field.declaringClass == null)) {
return false;
}
return name.equals(field.getName())
&& (declaringClass == null || declaringClass.equals(field.getDeclaringClass()));
}
return false;
}
public int hashCode() {
return name.hashCode() ^ (declaringClass == null ? 0 : declaringClass.hashCode());
}
public String toString() {
return (declaringClass == null ? "" : declaringClass.getName() + ".") + name;
}
}
...
|
5f30d91d35d090e28925613365d5d1f31f0259d2
|
daapserver/bonjour.py
|
daapserver/bonjour.py
|
import zeroconf
import socket
class Bonjour(object):
"""
"""
def __init__(self):
"""
"""
self.zeroconf = zeroconf.Zeroconf()
self.servers = {}
def publish(self, server):
"""
"""
if server in self.servers:
self.unpublish(server)
ip = "127.0.0.1" if server.ip == "0.0.0.0" else server.ip
description = {
"txtvers": 1,
"Password": server.password is not None,
"Machine Name": server.server_name
}
self.servers[server] = zeroconf.ServiceInfo(
"_daap._tcp.local.", server.server_name + ".daap._tcp.local.",
socket.inet_aton(ip), server.port, 0, 0,
description)
self.zeroconf.register_service(self.servers[server])
def unpublish(self, server):
"""
"""
if server not in self.servers:
return
self.zeroconf.unregister_service(self.servers[server])
del self.servers[server]
def close(self):
"""
"""
self.zeroconf.close()
|
import zeroconf
import socket
class Bonjour(object):
"""
"""
def __init__(self):
"""
"""
self.zeroconf = zeroconf.Zeroconf()
self.servers = {}
def publish(self, server):
"""
"""
if server in self.servers:
self.unpublish(server)
ip = "127.0.0.1" if server.ip == "0.0.0.0" else server.ip
description = {
"txtvers": 1,
"Password": int(bool(server.password)),
"Machine Name": server.server_name
}
self.servers[server] = zeroconf.ServiceInfo(
"_daap._tcp.local.", server.server_name + "._daap._tcp.local.",
socket.inet_aton(ip), server.port, 0, 0,
description)
self.zeroconf.register_service(self.servers[server])
def unpublish(self, server):
"""
"""
if server not in self.servers:
return
self.zeroconf.unregister_service(self.servers[server])
del self.servers[server]
def close(self):
"""
"""
self.zeroconf.close()
|
Fix for broken zeroconf publishing.
|
Fix for broken zeroconf publishing.
|
Python
|
mit
|
ties/flask-daapserver,basilfx/flask-daapserver
|
python
|
## Code Before:
import zeroconf
import socket
class Bonjour(object):
"""
"""
def __init__(self):
"""
"""
self.zeroconf = zeroconf.Zeroconf()
self.servers = {}
def publish(self, server):
"""
"""
if server in self.servers:
self.unpublish(server)
ip = "127.0.0.1" if server.ip == "0.0.0.0" else server.ip
description = {
"txtvers": 1,
"Password": server.password is not None,
"Machine Name": server.server_name
}
self.servers[server] = zeroconf.ServiceInfo(
"_daap._tcp.local.", server.server_name + ".daap._tcp.local.",
socket.inet_aton(ip), server.port, 0, 0,
description)
self.zeroconf.register_service(self.servers[server])
def unpublish(self, server):
"""
"""
if server not in self.servers:
return
self.zeroconf.unregister_service(self.servers[server])
del self.servers[server]
def close(self):
"""
"""
self.zeroconf.close()
## Instruction:
Fix for broken zeroconf publishing.
## Code After:
import zeroconf
import socket
class Bonjour(object):
"""
"""
def __init__(self):
"""
"""
self.zeroconf = zeroconf.Zeroconf()
self.servers = {}
def publish(self, server):
"""
"""
if server in self.servers:
self.unpublish(server)
ip = "127.0.0.1" if server.ip == "0.0.0.0" else server.ip
description = {
"txtvers": 1,
"Password": int(bool(server.password)),
"Machine Name": server.server_name
}
self.servers[server] = zeroconf.ServiceInfo(
"_daap._tcp.local.", server.server_name + "._daap._tcp.local.",
socket.inet_aton(ip), server.port, 0, 0,
description)
self.zeroconf.register_service(self.servers[server])
def unpublish(self, server):
"""
"""
if server not in self.servers:
return
self.zeroconf.unregister_service(self.servers[server])
del self.servers[server]
def close(self):
"""
"""
self.zeroconf.close()
|
// ... existing code ...
ip = "127.0.0.1" if server.ip == "0.0.0.0" else server.ip
description = {
"txtvers": 1,
"Password": int(bool(server.password)),
"Machine Name": server.server_name
}
self.servers[server] = zeroconf.ServiceInfo(
"_daap._tcp.local.", server.server_name + "._daap._tcp.local.",
socket.inet_aton(ip), server.port, 0, 0,
description)
self.zeroconf.register_service(self.servers[server])
// ... rest of the code ...
|
a59f98bf0a1f62ade907a32a1148506d5c0b3d5b
|
src/java/org/jivesoftware/openfire/clearspace/ClearspaceAuthProvider.java
|
src/java/org/jivesoftware/openfire/clearspace/ClearspaceAuthProvider.java
|
/**
* $Revision$
* $Date$
*
* Copyright (C) 2006 Jive Software. All rights reserved.
*
* This software is published under the terms of the GNU Public License (GPL),
* a copy of which is included in this distribution.
*/
package org.jivesoftware.openfire.clearspace;
import org.jivesoftware.openfire.auth.AuthProvider;
import org.jivesoftware.openfire.auth.UnauthorizedException;
import org.jivesoftware.openfire.user.UserNotFoundException;
/**
* @author Daniel Henninger
*/
public class ClearspaceAuthProvider implements AuthProvider {
public boolean isPlainSupported() {
return true;
}
public boolean isDigestSupported() {
return true;
}
public void authenticate(String username, String password) throws UnauthorizedException {
// Nothing
}
public void authenticate(String username, String token, String digest) throws UnauthorizedException {
// Nothing
}
public String getPassword(String username) throws UserNotFoundException, UnsupportedOperationException {
return (username.equals("admin") ? "test" : "asdasdasdasd");
}
public void setPassword(String username, String password) throws UserNotFoundException, UnsupportedOperationException {
// Nothing
}
public boolean supportsPasswordRetrieval() {
return false;
}
}
|
/**
* $Revision$
* $Date$
*
* Copyright (C) 2006 Jive Software. All rights reserved.
*
* This software is published under the terms of the GNU Public License (GPL),
* a copy of which is included in this distribution.
*/
package org.jivesoftware.openfire.clearspace;
import org.jivesoftware.openfire.auth.AuthProvider;
import org.jivesoftware.openfire.auth.UnauthorizedException;
import static org.jivesoftware.openfire.clearspace.ClearspaceManager.HttpType.GET;
import org.jivesoftware.openfire.user.UserNotFoundException;
/**
* @author Daniel Henninger
*/
public class ClearspaceAuthProvider implements AuthProvider {
protected static final String URL_PREFIX = "permissionService/";
private ClearspaceManager manager;
public ClearspaceAuthProvider() {
// gets the manager
manager = ClearspaceManager.getInstance();
}
public boolean isPlainSupported() {
return true;
}
public boolean isDigestSupported() {
return false;
}
public void authenticate(String username, String password) throws UnauthorizedException {
try {
String path = URL_PREFIX + "authenticate/" + username + "/" + password;
manager.executeRequest(GET, path);
} catch (UnauthorizedException ue) {
throw ue;
} catch (Exception e) {
// It is not supported exception, wrap it into an UnsupportedOperationException
throw new UnsupportedOperationException("Unexpected error", e);
}
}
public void authenticate(String username, String token, String digest) throws UnauthorizedException {
throw new UnsupportedOperationException("Digest not supported");
}
public String getPassword(String username) throws UserNotFoundException, UnsupportedOperationException {
throw new UnsupportedOperationException("Password retrieval not supported");
}
public void setPassword(String username, String password) throws UserNotFoundException, UnsupportedOperationException {
throw new UnsupportedOperationException("Change Password not supported");
}
public boolean supportsPasswordRetrieval() {
return false;
}
}
|
Create CSAuthProvider to integrate with Clearspace. JM-1224
|
Create CSAuthProvider to integrate with Clearspace. JM-1224
git-svn-id: 2e83ce7f183c9abd424edb3952fab2cdab7acd7f@9941 b35dd754-fafc-0310-a699-88a17e54d16e
|
Java
|
apache-2.0
|
Gugli/Openfire,speedy01/Openfire,igniterealtime/Openfire,speedy01/Openfire,Gugli/Openfire,igniterealtime/Openfire,Gugli/Openfire,akrherz/Openfire,GregDThomas/Openfire,magnetsystems/message-openfire,akrherz/Openfire,guusdk/Openfire,igniterealtime/Openfire,speedy01/Openfire,akrherz/Openfire,guusdk/Openfire,akrherz/Openfire,igniterealtime/Openfire,magnetsystems/message-openfire,magnetsystems/message-openfire,magnetsystems/message-openfire,Gugli/Openfire,guusdk/Openfire,Gugli/Openfire,speedy01/Openfire,guusdk/Openfire,GregDThomas/Openfire,GregDThomas/Openfire,guusdk/Openfire,GregDThomas/Openfire,magnetsystems/message-openfire,igniterealtime/Openfire,speedy01/Openfire,akrherz/Openfire,GregDThomas/Openfire
|
java
|
## Code Before:
/**
* $Revision$
* $Date$
*
* Copyright (C) 2006 Jive Software. All rights reserved.
*
* This software is published under the terms of the GNU Public License (GPL),
* a copy of which is included in this distribution.
*/
package org.jivesoftware.openfire.clearspace;
import org.jivesoftware.openfire.auth.AuthProvider;
import org.jivesoftware.openfire.auth.UnauthorizedException;
import org.jivesoftware.openfire.user.UserNotFoundException;
/**
* @author Daniel Henninger
*/
public class ClearspaceAuthProvider implements AuthProvider {
public boolean isPlainSupported() {
return true;
}
public boolean isDigestSupported() {
return true;
}
public void authenticate(String username, String password) throws UnauthorizedException {
// Nothing
}
public void authenticate(String username, String token, String digest) throws UnauthorizedException {
// Nothing
}
public String getPassword(String username) throws UserNotFoundException, UnsupportedOperationException {
return (username.equals("admin") ? "test" : "asdasdasdasd");
}
public void setPassword(String username, String password) throws UserNotFoundException, UnsupportedOperationException {
// Nothing
}
public boolean supportsPasswordRetrieval() {
return false;
}
}
## Instruction:
Create CSAuthProvider to integrate with Clearspace. JM-1224
git-svn-id: 2e83ce7f183c9abd424edb3952fab2cdab7acd7f@9941 b35dd754-fafc-0310-a699-88a17e54d16e
## Code After:
/**
* $Revision$
* $Date$
*
* Copyright (C) 2006 Jive Software. All rights reserved.
*
* This software is published under the terms of the GNU Public License (GPL),
* a copy of which is included in this distribution.
*/
package org.jivesoftware.openfire.clearspace;
import org.jivesoftware.openfire.auth.AuthProvider;
import org.jivesoftware.openfire.auth.UnauthorizedException;
import static org.jivesoftware.openfire.clearspace.ClearspaceManager.HttpType.GET;
import org.jivesoftware.openfire.user.UserNotFoundException;
/**
* @author Daniel Henninger
*/
public class ClearspaceAuthProvider implements AuthProvider {
protected static final String URL_PREFIX = "permissionService/";
private ClearspaceManager manager;
public ClearspaceAuthProvider() {
// gets the manager
manager = ClearspaceManager.getInstance();
}
public boolean isPlainSupported() {
return true;
}
public boolean isDigestSupported() {
return false;
}
public void authenticate(String username, String password) throws UnauthorizedException {
try {
String path = URL_PREFIX + "authenticate/" + username + "/" + password;
manager.executeRequest(GET, path);
} catch (UnauthorizedException ue) {
throw ue;
} catch (Exception e) {
// It is not supported exception, wrap it into an UnsupportedOperationException
throw new UnsupportedOperationException("Unexpected error", e);
}
}
public void authenticate(String username, String token, String digest) throws UnauthorizedException {
throw new UnsupportedOperationException("Digest not supported");
}
public String getPassword(String username) throws UserNotFoundException, UnsupportedOperationException {
throw new UnsupportedOperationException("Password retrieval not supported");
}
public void setPassword(String username, String password) throws UserNotFoundException, UnsupportedOperationException {
throw new UnsupportedOperationException("Change Password not supported");
}
public boolean supportsPasswordRetrieval() {
return false;
}
}
|
...
import org.jivesoftware.openfire.auth.AuthProvider;
import org.jivesoftware.openfire.auth.UnauthorizedException;
import static org.jivesoftware.openfire.clearspace.ClearspaceManager.HttpType.GET;
import org.jivesoftware.openfire.user.UserNotFoundException;
/**
...
* @author Daniel Henninger
*/
public class ClearspaceAuthProvider implements AuthProvider {
protected static final String URL_PREFIX = "permissionService/";
private ClearspaceManager manager;
public ClearspaceAuthProvider() {
// gets the manager
manager = ClearspaceManager.getInstance();
}
public boolean isPlainSupported() {
return true;
}
public boolean isDigestSupported() {
return false;
}
public void authenticate(String username, String password) throws UnauthorizedException {
try {
String path = URL_PREFIX + "authenticate/" + username + "/" + password;
manager.executeRequest(GET, path);
} catch (UnauthorizedException ue) {
throw ue;
} catch (Exception e) {
// It is not supported exception, wrap it into an UnsupportedOperationException
throw new UnsupportedOperationException("Unexpected error", e);
}
}
public void authenticate(String username, String token, String digest) throws UnauthorizedException {
throw new UnsupportedOperationException("Digest not supported");
}
public String getPassword(String username) throws UserNotFoundException, UnsupportedOperationException {
throw new UnsupportedOperationException("Password retrieval not supported");
}
public void setPassword(String username, String password) throws UserNotFoundException, UnsupportedOperationException {
throw new UnsupportedOperationException("Change Password not supported");
}
public boolean supportsPasswordRetrieval() {
...
|
fddd1e2f9c7edc4b4c4759235f039f143bcdfbb9
|
src/main/java/leetcode/Problem121.java
|
src/main/java/leetcode/Problem121.java
|
package leetcode;
/**
* https://leetcode.com/problems/best-time-to-buy-and-sell-stock/
*/
public class Problem121 {
public int maxProfit(int[] prices) {
return 0;
}
public static void main(String[] args) {
Problem121 prob = new Problem121();
System.out.println(prob.maxProfit(new int[]{1, 2, 4, 2, 1, 3}));
}
}
|
package leetcode;
/**
* https://leetcode.com/problems/best-time-to-buy-and-sell-stock/
*/
public class Problem121 {
public int maxProfit(int[] prices) {
int[] max = new int[prices.length];
int m = -1;
for (int i = prices.length-1; i != 0; i--) {
max[i] = Math.max(m, prices[i]);
m = max[i];
}
int profit = 0;
for (int i = 0; i < prices.length-1; i++) {
int buy = prices[i];
int sell = max[i+1];
profit = Math.max(profit, sell-buy);
}
return profit;
}
public static void main(String[] args) {
Problem121 prob = new Problem121();
System.out.println(prob.maxProfit(new int[]{1, 2, 4, 2, 1, 3}));
System.out.println(prob.maxProfit(new int[]{3, 2, 6, 5, 0, 3}));
}
}
|
Update problem 121 (not verified)
|
Update problem 121 (not verified)
|
Java
|
mit
|
fredyw/leetcode,fredyw/leetcode,fredyw/leetcode,fredyw/leetcode
|
java
|
## Code Before:
package leetcode;
/**
* https://leetcode.com/problems/best-time-to-buy-and-sell-stock/
*/
public class Problem121 {
public int maxProfit(int[] prices) {
return 0;
}
public static void main(String[] args) {
Problem121 prob = new Problem121();
System.out.println(prob.maxProfit(new int[]{1, 2, 4, 2, 1, 3}));
}
}
## Instruction:
Update problem 121 (not verified)
## Code After:
package leetcode;
/**
* https://leetcode.com/problems/best-time-to-buy-and-sell-stock/
*/
public class Problem121 {
public int maxProfit(int[] prices) {
int[] max = new int[prices.length];
int m = -1;
for (int i = prices.length-1; i != 0; i--) {
max[i] = Math.max(m, prices[i]);
m = max[i];
}
int profit = 0;
for (int i = 0; i < prices.length-1; i++) {
int buy = prices[i];
int sell = max[i+1];
profit = Math.max(profit, sell-buy);
}
return profit;
}
public static void main(String[] args) {
Problem121 prob = new Problem121();
System.out.println(prob.maxProfit(new int[]{1, 2, 4, 2, 1, 3}));
System.out.println(prob.maxProfit(new int[]{3, 2, 6, 5, 0, 3}));
}
}
|
// ... existing code ...
*/
public class Problem121 {
public int maxProfit(int[] prices) {
int[] max = new int[prices.length];
int m = -1;
for (int i = prices.length-1; i != 0; i--) {
max[i] = Math.max(m, prices[i]);
m = max[i];
}
int profit = 0;
for (int i = 0; i < prices.length-1; i++) {
int buy = prices[i];
int sell = max[i+1];
profit = Math.max(profit, sell-buy);
}
return profit;
}
public static void main(String[] args) {
Problem121 prob = new Problem121();
System.out.println(prob.maxProfit(new int[]{1, 2, 4, 2, 1, 3}));
System.out.println(prob.maxProfit(new int[]{3, 2, 6, 5, 0, 3}));
}
}
// ... rest of the code ...
|
cc93d6b9ade1d15236904978f012f91b0a9d567d
|
examples/manage.py
|
examples/manage.py
|
import logging
from aio_manager import Manager
from aioapp.app import build_application
logging.basicConfig(level=logging.WARNING)
app = build_application()
manager = Manager(app)
# To support SQLAlchemy commands, use this
#
# from aio_manager.commands.ext import sqlalchemy
# sqlalchemy.configure_manager(manager, app, Base,
# settings.DATABASE_USERNAME,
# settings.DATABASE_NAME,
# settings.DATABASE_HOST,
# settings.DATABASE_PASSWORD)
if __name__ == "__main__":
manager.run()
|
import logging
from aio_manager import Manager
from aioapp.app import build_application
logging.basicConfig(level=logging.WARNING)
app = build_application()
manager = Manager(app)
# To support SQLAlchemy commands, use this
#
# from aio_manager.commands.ext import sqlalchemy
# [from aiopg.sa import create_engine]
# sqlalchemy.configure_manager(manager, app, Base,
# settings.DATABASE_USERNAME,
# settings.DATABASE_PASSWORD,
# settings.DATABASE_NAME,
# settings.DATABASE_HOST,
# settings.DATABASE_PORT[,
# create_engine])
if __name__ == "__main__":
manager.run()
|
Update sqlalchemy command configuration example
|
Update sqlalchemy command configuration example
|
Python
|
bsd-3-clause
|
rrader/aio_manager
|
python
|
## Code Before:
import logging
from aio_manager import Manager
from aioapp.app import build_application
logging.basicConfig(level=logging.WARNING)
app = build_application()
manager = Manager(app)
# To support SQLAlchemy commands, use this
#
# from aio_manager.commands.ext import sqlalchemy
# sqlalchemy.configure_manager(manager, app, Base,
# settings.DATABASE_USERNAME,
# settings.DATABASE_NAME,
# settings.DATABASE_HOST,
# settings.DATABASE_PASSWORD)
if __name__ == "__main__":
manager.run()
## Instruction:
Update sqlalchemy command configuration example
## Code After:
import logging
from aio_manager import Manager
from aioapp.app import build_application
logging.basicConfig(level=logging.WARNING)
app = build_application()
manager = Manager(app)
# To support SQLAlchemy commands, use this
#
# from aio_manager.commands.ext import sqlalchemy
# [from aiopg.sa import create_engine]
# sqlalchemy.configure_manager(manager, app, Base,
# settings.DATABASE_USERNAME,
# settings.DATABASE_PASSWORD,
# settings.DATABASE_NAME,
# settings.DATABASE_HOST,
# settings.DATABASE_PORT[,
# create_engine])
if __name__ == "__main__":
manager.run()
|
// ... existing code ...
# To support SQLAlchemy commands, use this
#
# from aio_manager.commands.ext import sqlalchemy
# [from aiopg.sa import create_engine]
# sqlalchemy.configure_manager(manager, app, Base,
# settings.DATABASE_USERNAME,
# settings.DATABASE_PASSWORD,
# settings.DATABASE_NAME,
# settings.DATABASE_HOST,
# settings.DATABASE_PORT[,
# create_engine])
if __name__ == "__main__":
manager.run()
// ... rest of the code ...
|
a6e6e6bf18c48638d4c6c7d97f894edd3fc3c1ad
|
ipython_config.py
|
ipython_config.py
|
c.InteractiveShellApp.exec_lines = []
# ipython-autoimport - Automatically import modules
c.InteractiveShellApp.exec_lines.append(
"try:\n %load_ext ipython_autoimport\nexcept ImportError: pass")
# Automatically reload modules
c.InteractiveShellApp.exec_lines.append('%load_ext autoreload')
c.InteractiveShellApp.exec_lines.append('%autoreload 2')
|
c.InteractiveShellApp.exec_lines = []
# ipython-autoimport - Automatically import modules
c.InteractiveShellApp.exec_lines.append(
"try:\n %load_ext ipython_autoimport\nexcept ImportError: pass")
# Automatically reload modules
c.InteractiveShellApp.exec_lines.append('%load_ext autoreload')
c.InteractiveShellApp.exec_lines.append('%autoreload 2')
c.TerminalInteractiveShell.editor = 'gvim'
|
Set default shell editor for ipython to gvim
|
Set default shell editor for ipython to gvim
|
Python
|
mit
|
brycepg/dotfiles,brycepg/dotfiles
|
python
|
## Code Before:
c.InteractiveShellApp.exec_lines = []
# ipython-autoimport - Automatically import modules
c.InteractiveShellApp.exec_lines.append(
"try:\n %load_ext ipython_autoimport\nexcept ImportError: pass")
# Automatically reload modules
c.InteractiveShellApp.exec_lines.append('%load_ext autoreload')
c.InteractiveShellApp.exec_lines.append('%autoreload 2')
## Instruction:
Set default shell editor for ipython to gvim
## Code After:
c.InteractiveShellApp.exec_lines = []
# ipython-autoimport - Automatically import modules
c.InteractiveShellApp.exec_lines.append(
"try:\n %load_ext ipython_autoimport\nexcept ImportError: pass")
# Automatically reload modules
c.InteractiveShellApp.exec_lines.append('%load_ext autoreload')
c.InteractiveShellApp.exec_lines.append('%autoreload 2')
c.TerminalInteractiveShell.editor = 'gvim'
|
# ... existing code ...
# Automatically reload modules
c.InteractiveShellApp.exec_lines.append('%load_ext autoreload')
c.InteractiveShellApp.exec_lines.append('%autoreload 2')
c.TerminalInteractiveShell.editor = 'gvim'
# ... rest of the code ...
|
c7b7e62cb2585f6109d70b27564617b0be4c8c33
|
tests/test_daterange.py
|
tests/test_daterange.py
|
import os
import time
try:
import unittest2 as unittest
except ImportError:
import unittest
class DateRangeTest(unittest.TestCase):
def setUp(self):
self.openlicensefile = os.path.join(os.path.dirname(__file__), '../LICENSE.txt')
self.pattern = 'Copyright (c) 2012 - %s SendGrid, Inc.' % (time.strftime("%Y"))
self.licensefile = open(self.openlicensefile).read()
def test__daterange(self):
self.assertTrue(self.pattern in self.licensefile)
|
import os
import time
try:
import unittest2 as unittest
except ImportError:
import unittest
class DateRangeTest(unittest.TestCase):
def setUp(self):
self.openlicensefile = os.path.join(
os.path.dirname(__file__),
'../LICENSE.txt')
self.pattern = 'Copyright (c) 2012 - %s SendGrid, Inc.' % (
time.strftime("%Y"))
self.licensefile = open(self.openlicensefile).read()
def test__daterange(self):
self.assertTrue(self.pattern in self.licensefile)
|
Update code for PEP8 compliance
|
Update code for PEP8 compliance
|
Python
|
mit
|
sendgrid/python-http-client,sendgrid/python-http-client
|
python
|
## Code Before:
import os
import time
try:
import unittest2 as unittest
except ImportError:
import unittest
class DateRangeTest(unittest.TestCase):
def setUp(self):
self.openlicensefile = os.path.join(os.path.dirname(__file__), '../LICENSE.txt')
self.pattern = 'Copyright (c) 2012 - %s SendGrid, Inc.' % (time.strftime("%Y"))
self.licensefile = open(self.openlicensefile).read()
def test__daterange(self):
self.assertTrue(self.pattern in self.licensefile)
## Instruction:
Update code for PEP8 compliance
## Code After:
import os
import time
try:
import unittest2 as unittest
except ImportError:
import unittest
class DateRangeTest(unittest.TestCase):
def setUp(self):
self.openlicensefile = os.path.join(
os.path.dirname(__file__),
'../LICENSE.txt')
self.pattern = 'Copyright (c) 2012 - %s SendGrid, Inc.' % (
time.strftime("%Y"))
self.licensefile = open(self.openlicensefile).read()
def test__daterange(self):
self.assertTrue(self.pattern in self.licensefile)
|
// ... existing code ...
except ImportError:
import unittest
class DateRangeTest(unittest.TestCase):
def setUp(self):
self.openlicensefile = os.path.join(
os.path.dirname(__file__),
'../LICENSE.txt')
self.pattern = 'Copyright (c) 2012 - %s SendGrid, Inc.' % (
time.strftime("%Y"))
self.licensefile = open(self.openlicensefile).read()
def test__daterange(self):
// ... rest of the code ...
|
2ad2d488b4d7b0997355c068646a6a38b2668dae
|
meetuppizza/tests.py
|
meetuppizza/tests.py
|
from django.test import TestCase
class Test(TestCase):
def test_landing_page_is_there(self):
response = self.client.get('/')
self.assertEqual(response.status_code, 200)
|
from django.test import TestCase
class Test(TestCase):
def test_landing_page_is_there(self):
response = self.client.get('/')
self.assertEqual(response.status_code, 200)
def test_page_contains_pizza(self):
response = self.client.get('/')
self.assertContains(response, "Pizza")
|
Add test that checks if landing page contains the word Pizza.
|
Add test that checks if landing page contains the word Pizza.
|
Python
|
mit
|
nicole-a-tesla/meetup.pizza,nicole-a-tesla/meetup.pizza
|
python
|
## Code Before:
from django.test import TestCase
class Test(TestCase):
def test_landing_page_is_there(self):
response = self.client.get('/')
self.assertEqual(response.status_code, 200)
## Instruction:
Add test that checks if landing page contains the word Pizza.
## Code After:
from django.test import TestCase
class Test(TestCase):
def test_landing_page_is_there(self):
response = self.client.get('/')
self.assertEqual(response.status_code, 200)
def test_page_contains_pizza(self):
response = self.client.get('/')
self.assertContains(response, "Pizza")
|
# ... existing code ...
def test_landing_page_is_there(self):
response = self.client.get('/')
self.assertEqual(response.status_code, 200)
def test_page_contains_pizza(self):
response = self.client.get('/')
self.assertContains(response, "Pizza")
# ... rest of the code ...
|
24e3c89f0093bafd9618dd5c3eb5ad147be0f4c3
|
project/apps/api/filters.py
|
project/apps/api/filters.py
|
import rest_framework_filters as filters
from .models import (
Chart,
Convention,
Group,
Person,
Venue,
)
class ChartFilter(filters.FilterSet):
class Meta:
model = Chart
fields = {
'name': filters.ALL_LOOKUPS,
}
class ConventionFilter(filters.FilterSet):
class Meta:
model = Convention
fields = {
'status': filters.ALL_LOOKUPS,
'year': filters.ALL_LOOKUPS,
}
class GroupFilter(filters.FilterSet):
class Meta:
model = Group
fields = {
'name': filters.ALL_LOOKUPS,
}
class PersonFilter(filters.FilterSet):
class Meta:
model = Person
fields = {
'name': filters.ALL_LOOKUPS,
}
class VenueFilter(filters.FilterSet):
class Meta:
model = Venue
fields = {
'name': filters.ALL_LOOKUPS,
}
|
import rest_framework_filters as filters
from .models import (
Chart,
Convention,
Group,
Person,
Venue,
)
class ChartFilter(filters.FilterSet):
class Meta:
model = Chart
fields = {
'name': filters.ALL_LOOKUPS,
}
class ConventionFilter(filters.FilterSet):
class Meta:
model = Convention
fields = {
'status': filters.ALL_LOOKUPS,
'year': filters.ALL_LOOKUPS,
'season': filters.ALL_LOOKUPS,
}
class GroupFilter(filters.FilterSet):
class Meta:
model = Group
fields = {
'name': filters.ALL_LOOKUPS,
}
class PersonFilter(filters.FilterSet):
class Meta:
model = Person
fields = {
'name': filters.ALL_LOOKUPS,
}
class VenueFilter(filters.FilterSet):
class Meta:
model = Venue
fields = {
'name': filters.ALL_LOOKUPS,
}
|
Add season to Convention filter
|
Add season to Convention filter
|
Python
|
bsd-2-clause
|
barberscore/barberscore-api,barberscore/barberscore-api,dbinetti/barberscore,barberscore/barberscore-api,dbinetti/barberscore,dbinetti/barberscore-django,dbinetti/barberscore-django,barberscore/barberscore-api
|
python
|
## Code Before:
import rest_framework_filters as filters
from .models import (
Chart,
Convention,
Group,
Person,
Venue,
)
class ChartFilter(filters.FilterSet):
class Meta:
model = Chart
fields = {
'name': filters.ALL_LOOKUPS,
}
class ConventionFilter(filters.FilterSet):
class Meta:
model = Convention
fields = {
'status': filters.ALL_LOOKUPS,
'year': filters.ALL_LOOKUPS,
}
class GroupFilter(filters.FilterSet):
class Meta:
model = Group
fields = {
'name': filters.ALL_LOOKUPS,
}
class PersonFilter(filters.FilterSet):
class Meta:
model = Person
fields = {
'name': filters.ALL_LOOKUPS,
}
class VenueFilter(filters.FilterSet):
class Meta:
model = Venue
fields = {
'name': filters.ALL_LOOKUPS,
}
## Instruction:
Add season to Convention filter
## Code After:
import rest_framework_filters as filters
from .models import (
Chart,
Convention,
Group,
Person,
Venue,
)
class ChartFilter(filters.FilterSet):
class Meta:
model = Chart
fields = {
'name': filters.ALL_LOOKUPS,
}
class ConventionFilter(filters.FilterSet):
class Meta:
model = Convention
fields = {
'status': filters.ALL_LOOKUPS,
'year': filters.ALL_LOOKUPS,
'season': filters.ALL_LOOKUPS,
}
class GroupFilter(filters.FilterSet):
class Meta:
model = Group
fields = {
'name': filters.ALL_LOOKUPS,
}
class PersonFilter(filters.FilterSet):
class Meta:
model = Person
fields = {
'name': filters.ALL_LOOKUPS,
}
class VenueFilter(filters.FilterSet):
class Meta:
model = Venue
fields = {
'name': filters.ALL_LOOKUPS,
}
|
# ... existing code ...
fields = {
'status': filters.ALL_LOOKUPS,
'year': filters.ALL_LOOKUPS,
'season': filters.ALL_LOOKUPS,
}
# ... rest of the code ...
|
1bf18c373e240b9a3f00e48084796a131171d19f
|
tests/addition_tests.c
|
tests/addition_tests.c
|
void verify_addition(const char *left, const char *right, const char *expected_result) {
char *actual_result = roman_calculator_add(left, right);
ck_assert_msg(
strcmp(expected_result, actual_result) == 0,
"%s + %s: expected %s, but was %s",
left, right, expected_result, actual_result);
free(actual_result);
}
START_TEST(can_add_by_simple_repetition)
{
verify_addition("I", "I", "II");
verify_addition("I", "II", "III");
verify_addition("XX", "X", "XXX");
verify_addition("C", "C", "CC");
verify_addition("M", "MM", "MMM");
}
END_TEST
TCase *addition_tests()
{
TCase *test_case = tcase_create("addition tests");
tcase_add_test(test_case, can_add_by_simple_repetition);
return test_case;
}
|
void verify_addition(const char *left, const char *right, const char *expected_result) {
char *actual_result = roman_calculator_add(left, right);
ck_assert_msg(
strcmp(expected_result, actual_result) == 0,
"%s + %s: expected %s, but was %s",
left, right, expected_result, actual_result);
free(actual_result);
}
START_TEST(can_add_by_simple_repetition)
{
verify_addition("I", "I", "II");
verify_addition("I", "II", "III");
verify_addition("XX", "X", "XXX");
verify_addition("C", "C", "CC");
verify_addition("M", "MM", "MMM");
}
END_TEST
START_TEST(can_add_by_concatenation)
{
verify_addition("X", "I", "XI");
verify_addition("MCX", "XV", "MCXXV");
verify_addition("DCI", "II", "DCIII");
verify_addition("LX", "XVI", "LXXVI");
}
END_TEST
TCase *addition_tests()
{
TCase *test_case = tcase_create("addition tests");
tcase_add_test(test_case, can_add_by_simple_repetition);
tcase_add_test(test_case, can_add_by_concatenation);
return test_case;
}
|
Add clarifying test about addition by concatenation
|
Add clarifying test about addition by concatenation
It doesn't just apply to repeating the same numeral.
|
C
|
mit
|
greghaskins/roman-calculator.c
|
c
|
## Code Before:
void verify_addition(const char *left, const char *right, const char *expected_result) {
char *actual_result = roman_calculator_add(left, right);
ck_assert_msg(
strcmp(expected_result, actual_result) == 0,
"%s + %s: expected %s, but was %s",
left, right, expected_result, actual_result);
free(actual_result);
}
START_TEST(can_add_by_simple_repetition)
{
verify_addition("I", "I", "II");
verify_addition("I", "II", "III");
verify_addition("XX", "X", "XXX");
verify_addition("C", "C", "CC");
verify_addition("M", "MM", "MMM");
}
END_TEST
TCase *addition_tests()
{
TCase *test_case = tcase_create("addition tests");
tcase_add_test(test_case, can_add_by_simple_repetition);
return test_case;
}
## Instruction:
Add clarifying test about addition by concatenation
It doesn't just apply to repeating the same numeral.
## Code After:
void verify_addition(const char *left, const char *right, const char *expected_result) {
char *actual_result = roman_calculator_add(left, right);
ck_assert_msg(
strcmp(expected_result, actual_result) == 0,
"%s + %s: expected %s, but was %s",
left, right, expected_result, actual_result);
free(actual_result);
}
START_TEST(can_add_by_simple_repetition)
{
verify_addition("I", "I", "II");
verify_addition("I", "II", "III");
verify_addition("XX", "X", "XXX");
verify_addition("C", "C", "CC");
verify_addition("M", "MM", "MMM");
}
END_TEST
START_TEST(can_add_by_concatenation)
{
verify_addition("X", "I", "XI");
verify_addition("MCX", "XV", "MCXXV");
verify_addition("DCI", "II", "DCIII");
verify_addition("LX", "XVI", "LXXVI");
}
END_TEST
TCase *addition_tests()
{
TCase *test_case = tcase_create("addition tests");
tcase_add_test(test_case, can_add_by_simple_repetition);
tcase_add_test(test_case, can_add_by_concatenation);
return test_case;
}
|
// ... existing code ...
}
END_TEST
START_TEST(can_add_by_concatenation)
{
verify_addition("X", "I", "XI");
verify_addition("MCX", "XV", "MCXXV");
verify_addition("DCI", "II", "DCIII");
verify_addition("LX", "XVI", "LXXVI");
}
END_TEST
TCase *addition_tests()
{
TCase *test_case = tcase_create("addition tests");
tcase_add_test(test_case, can_add_by_simple_repetition);
tcase_add_test(test_case, can_add_by_concatenation);
return test_case;
}
// ... rest of the code ...
|
7346103a36d69d1f27bc064843afa8c18d201d2b
|
go/apps/bulk_message/definition.py
|
go/apps/bulk_message/definition.py
|
from go.vumitools.conversation.definition import (
ConversationDefinitionBase, ConversationAction)
class BulkSendAction(ConversationAction):
action_name = 'bulk_send'
action_display_name = 'Write and send bulk message'
needs_confirmation = True
needs_group = True
needs_running = True
def check_disabled(self):
if self._conv.has_channel_supporting_generic_sends():
return None
return ("This action needs channels capable of sending"
" messages attached to this conversation.")
def perform_action(self, action_data):
return self.send_command(
'bulk_send', batch_id=self._conv.batch.key,
msg_options={}, content=action_data['message'],
delivery_class=self._conv.delivery_class,
dedupe=action_data['dedupe'])
class ConversationDefinition(ConversationDefinitionBase):
conversation_type = 'bulk_message'
actions = (BulkSendAction,)
|
from go.vumitools.conversation.definition import (
ConversationDefinitionBase, ConversationAction)
class BulkSendAction(ConversationAction):
action_name = 'bulk_send'
action_display_name = 'Write and send bulk message'
action_display_verb = 'Send message'
needs_confirmation = True
needs_group = True
needs_running = True
def check_disabled(self):
if self._conv.has_channel_supporting_generic_sends():
return None
return ("This action needs channels capable of sending"
" messages attached to this conversation.")
def perform_action(self, action_data):
return self.send_command(
'bulk_send', batch_id=self._conv.batch.key,
msg_options={}, content=action_data['message'],
delivery_class=self._conv.delivery_class,
dedupe=action_data['dedupe'])
class ConversationDefinition(ConversationDefinitionBase):
conversation_type = 'bulk_message'
actions = (BulkSendAction,)
|
Change send bulk message display verb to 'Send message'.
|
Change send bulk message display verb to 'Send message'.
|
Python
|
bsd-3-clause
|
praekelt/vumi-go,praekelt/vumi-go,praekelt/vumi-go,praekelt/vumi-go
|
python
|
## Code Before:
from go.vumitools.conversation.definition import (
ConversationDefinitionBase, ConversationAction)
class BulkSendAction(ConversationAction):
action_name = 'bulk_send'
action_display_name = 'Write and send bulk message'
needs_confirmation = True
needs_group = True
needs_running = True
def check_disabled(self):
if self._conv.has_channel_supporting_generic_sends():
return None
return ("This action needs channels capable of sending"
" messages attached to this conversation.")
def perform_action(self, action_data):
return self.send_command(
'bulk_send', batch_id=self._conv.batch.key,
msg_options={}, content=action_data['message'],
delivery_class=self._conv.delivery_class,
dedupe=action_data['dedupe'])
class ConversationDefinition(ConversationDefinitionBase):
conversation_type = 'bulk_message'
actions = (BulkSendAction,)
## Instruction:
Change send bulk message display verb to 'Send message'.
## Code After:
from go.vumitools.conversation.definition import (
ConversationDefinitionBase, ConversationAction)
class BulkSendAction(ConversationAction):
action_name = 'bulk_send'
action_display_name = 'Write and send bulk message'
action_display_verb = 'Send message'
needs_confirmation = True
needs_group = True
needs_running = True
def check_disabled(self):
if self._conv.has_channel_supporting_generic_sends():
return None
return ("This action needs channels capable of sending"
" messages attached to this conversation.")
def perform_action(self, action_data):
return self.send_command(
'bulk_send', batch_id=self._conv.batch.key,
msg_options={}, content=action_data['message'],
delivery_class=self._conv.delivery_class,
dedupe=action_data['dedupe'])
class ConversationDefinition(ConversationDefinitionBase):
conversation_type = 'bulk_message'
actions = (BulkSendAction,)
|
// ... existing code ...
class BulkSendAction(ConversationAction):
action_name = 'bulk_send'
action_display_name = 'Write and send bulk message'
action_display_verb = 'Send message'
needs_confirmation = True
// ... rest of the code ...
|
72984db143d5e41ac04dcd04b6fc6db92b04fd63
|
src/main/java/openmods/api/INeighbourAwareTile.java
|
src/main/java/openmods/api/INeighbourAwareTile.java
|
package openmods.api;
import net.minecraft.block.Block;
import net.minecraft.util.math.BlockPos;
public interface INeighbourAwareTile {
public void onNeighbourChanged(BlockPos pos, Block block);
}
|
package openmods.api;
import net.minecraft.block.Block;
import net.minecraft.util.math.BlockPos;
public interface INeighbourAwareTile {
public void onNeighbourChanged(BlockPos neighbourPos, Block neigbourBlock);
}
|
Change parameter name to prevent mistakes
|
Change parameter name to prevent mistakes
|
Java
|
mit
|
OpenMods/OpenModsLib,OpenMods/OpenModsLib
|
java
|
## Code Before:
package openmods.api;
import net.minecraft.block.Block;
import net.minecraft.util.math.BlockPos;
public interface INeighbourAwareTile {
public void onNeighbourChanged(BlockPos pos, Block block);
}
## Instruction:
Change parameter name to prevent mistakes
## Code After:
package openmods.api;
import net.minecraft.block.Block;
import net.minecraft.util.math.BlockPos;
public interface INeighbourAwareTile {
public void onNeighbourChanged(BlockPos neighbourPos, Block neigbourBlock);
}
|
// ... existing code ...
public interface INeighbourAwareTile {
public void onNeighbourChanged(BlockPos neighbourPos, Block neigbourBlock);
}
// ... rest of the code ...
|
28126555aea9a78467dfcadbb2b14f9c640cdc6d
|
dwitter/templatetags/to_gravatar_url.py
|
dwitter/templatetags/to_gravatar_url.py
|
import hashlib
from django import template
register = template.Library()
@register.filter
def to_gravatar_url(email):
return ('https://gravatar.com/avatar/%s?d=retro' %
hashlib.md5((email or '').strip().lower()).hexdigest())
|
import hashlib
from django import template
register = template.Library()
@register.filter
def to_gravatar_url(email):
return ('https://gravatar.com/avatar/%s?d=retro' %
hashlib.md5((email or '').strip().lower().encode('utf-8')).hexdigest())
|
Fix gravatar hashing error on py3
|
Fix gravatar hashing error on py3
|
Python
|
apache-2.0
|
lionleaf/dwitter,lionleaf/dwitter,lionleaf/dwitter
|
python
|
## Code Before:
import hashlib
from django import template
register = template.Library()
@register.filter
def to_gravatar_url(email):
return ('https://gravatar.com/avatar/%s?d=retro' %
hashlib.md5((email or '').strip().lower()).hexdigest())
## Instruction:
Fix gravatar hashing error on py3
## Code After:
import hashlib
from django import template
register = template.Library()
@register.filter
def to_gravatar_url(email):
return ('https://gravatar.com/avatar/%s?d=retro' %
hashlib.md5((email or '').strip().lower().encode('utf-8')).hexdigest())
|
# ... existing code ...
@register.filter
def to_gravatar_url(email):
return ('https://gravatar.com/avatar/%s?d=retro' %
hashlib.md5((email or '').strip().lower().encode('utf-8')).hexdigest())
# ... rest of the code ...
|
77cd208abac5095c288ff103709a8ddd4d4e8b3d
|
Sources/OCAObject.h
|
Sources/OCAObject.h
|
//
// OCAObject.h
// Objective-Chain
//
// Created by Martin Kiss on 30.12.13.
// Copyright © 2014 Martin Kiss. All rights reserved.
//
#import <Foundation/Foundation.h>
#define OCA_atomic atomic
#define OCALazyGetter(TYPE, PROPERTY) \
@synthesize PROPERTY = _##PROPERTY; \
- (TYPE)PROPERTY { \
if ( ! self->_##PROPERTY) { \
self->_##PROPERTY = [self oca_lazyGetter_##PROPERTY]; \
} \
return self->_##PROPERTY; \
} \
- (TYPE)oca_lazyGetter_##PROPERTY \
#if !defined(NS_BLOCK_ASSERTIONS)
#define OCAAssert(CONDITION, MESSAGE, ...) \
if ( ! (CONDITION) && (( [[NSAssertionHandler currentHandler] \
handleFailureInFunction: [NSString stringWithUTF8String:__PRETTY_FUNCTION__] \
file: [NSString stringWithUTF8String:__FILE__] \
lineNumber: __LINE__ \
description: (MESSAGE), ##__VA_ARGS__], YES)) ) // Will NOT execute appended code, if exception is thrown.
#else
#define OCAAssert(CONDITION, MESSAGE, ...)\
if ( ! (CONDITION) && (( NSLog(@"*** Assertion failure in %s, %s:%d, Condition not satisfied: %s, reason: '" MESSAGE "'", __PRETTY_FUNCTION__, __FILE__, __LINE__, #CONDITION, ##__VA_ARGS__), YES)) ) // Will execute appended code.
#endif
@interface OCAObject : NSObject
@end
|
//
// OCAObject.h
// Objective-Chain
//
// Created by Martin Kiss on 30.12.13.
// Copyright © 2014 Martin Kiss. All rights reserved.
//
#import <Foundation/Foundation.h>
#define OCA_atomic atomic
#define OCALazyGetter(TYPE, PROPERTY) \
@synthesize PROPERTY = _##PROPERTY; \
- (TYPE)PROPERTY { \
if ( ! self->_##PROPERTY) { \
self->_##PROPERTY = [self oca_lazyGetter_##PROPERTY]; \
} \
return self->_##PROPERTY; \
} \
- (TYPE)oca_lazyGetter_##PROPERTY \
#if !defined(NS_BLOCK_ASSERTIONS)
#define OCAAssert(CONDITION, MESSAGE, ...) \
if ( ! (CONDITION) && (( [[NSAssertionHandler currentHandler] \
handleFailureInFunction: [NSString stringWithUTF8String:__PRETTY_FUNCTION__] \
file: [NSString stringWithUTF8String:__FILE__] \
lineNumber: __LINE__ \
description: (MESSAGE), ##__VA_ARGS__], YES)) ) // Will NOT execute appended code, if exception is thrown.
#else
#define OCAAssert(CONDITION, MESSAGE, ...)\
if ( ! (CONDITION) && (( NSLog(@"*** Assertion failure in %s, %s:%d, Condition not satisfied: %s, reason: '" MESSAGE "'", __PRETTY_FUNCTION__, __FILE__, __LINE__, #CONDITION, ##__VA_ARGS__), YES)) ) // Will execute appended code.
#endif
@interface OCAObject : NSObject
@end
|
Fix indentation of Assert macros
|
Fix indentation of Assert macros
|
C
|
mit
|
Tricertops/Objective-Chain,iMartinKiss/Objective-Chain
|
c
|
## Code Before:
//
// OCAObject.h
// Objective-Chain
//
// Created by Martin Kiss on 30.12.13.
// Copyright © 2014 Martin Kiss. All rights reserved.
//
#import <Foundation/Foundation.h>
#define OCA_atomic atomic
#define OCALazyGetter(TYPE, PROPERTY) \
@synthesize PROPERTY = _##PROPERTY; \
- (TYPE)PROPERTY { \
if ( ! self->_##PROPERTY) { \
self->_##PROPERTY = [self oca_lazyGetter_##PROPERTY]; \
} \
return self->_##PROPERTY; \
} \
- (TYPE)oca_lazyGetter_##PROPERTY \
#if !defined(NS_BLOCK_ASSERTIONS)
#define OCAAssert(CONDITION, MESSAGE, ...) \
if ( ! (CONDITION) && (( [[NSAssertionHandler currentHandler] \
handleFailureInFunction: [NSString stringWithUTF8String:__PRETTY_FUNCTION__] \
file: [NSString stringWithUTF8String:__FILE__] \
lineNumber: __LINE__ \
description: (MESSAGE), ##__VA_ARGS__], YES)) ) // Will NOT execute appended code, if exception is thrown.
#else
#define OCAAssert(CONDITION, MESSAGE, ...)\
if ( ! (CONDITION) && (( NSLog(@"*** Assertion failure in %s, %s:%d, Condition not satisfied: %s, reason: '" MESSAGE "'", __PRETTY_FUNCTION__, __FILE__, __LINE__, #CONDITION, ##__VA_ARGS__), YES)) ) // Will execute appended code.
#endif
@interface OCAObject : NSObject
@end
## Instruction:
Fix indentation of Assert macros
## Code After:
//
// OCAObject.h
// Objective-Chain
//
// Created by Martin Kiss on 30.12.13.
// Copyright © 2014 Martin Kiss. All rights reserved.
//
#import <Foundation/Foundation.h>
#define OCA_atomic atomic
#define OCALazyGetter(TYPE, PROPERTY) \
@synthesize PROPERTY = _##PROPERTY; \
- (TYPE)PROPERTY { \
if ( ! self->_##PROPERTY) { \
self->_##PROPERTY = [self oca_lazyGetter_##PROPERTY]; \
} \
return self->_##PROPERTY; \
} \
- (TYPE)oca_lazyGetter_##PROPERTY \
#if !defined(NS_BLOCK_ASSERTIONS)
#define OCAAssert(CONDITION, MESSAGE, ...) \
if ( ! (CONDITION) && (( [[NSAssertionHandler currentHandler] \
handleFailureInFunction: [NSString stringWithUTF8String:__PRETTY_FUNCTION__] \
file: [NSString stringWithUTF8String:__FILE__] \
lineNumber: __LINE__ \
description: (MESSAGE), ##__VA_ARGS__], YES)) ) // Will NOT execute appended code, if exception is thrown.
#else
#define OCAAssert(CONDITION, MESSAGE, ...)\
if ( ! (CONDITION) && (( NSLog(@"*** Assertion failure in %s, %s:%d, Condition not satisfied: %s, reason: '" MESSAGE "'", __PRETTY_FUNCTION__, __FILE__, __LINE__, #CONDITION, ##__VA_ARGS__), YES)) ) // Will execute appended code.
#endif
@interface OCAObject : NSObject
@end
|
...
#if !defined(NS_BLOCK_ASSERTIONS)
#define OCAAssert(CONDITION, MESSAGE, ...) \
if ( ! (CONDITION) && (( [[NSAssertionHandler currentHandler] \
handleFailureInFunction: [NSString stringWithUTF8String:__PRETTY_FUNCTION__] \
file: [NSString stringWithUTF8String:__FILE__] \
lineNumber: __LINE__ \
description: (MESSAGE), ##__VA_ARGS__], YES)) ) // Will NOT execute appended code, if exception is thrown.
#else
#define OCAAssert(CONDITION, MESSAGE, ...)\
if ( ! (CONDITION) && (( NSLog(@"*** Assertion failure in %s, %s:%d, Condition not satisfied: %s, reason: '" MESSAGE "'", __PRETTY_FUNCTION__, __FILE__, __LINE__, #CONDITION, ##__VA_ARGS__), YES)) ) // Will execute appended code.
#endif
...
|
13c6a1527bb5d241989c7b7beb11a48eacc4d69c
|
tests/unit/http_tests.py
|
tests/unit/http_tests.py
|
import unittest, os, sys
current_dir = os.path.dirname(__file__)
base_dir = os.path.join(current_dir, os.pardir, os.pardir)
sys.path.append(base_dir)
from requests.exceptions import ConnectionError
from pycrawler.http import HttpRequest
class HttpRequestTests(unittest.TestCase):
def test_response_not_empty(self):
url = 'http://www.pasarpanda.com'
http = HttpRequest.get(url)
self.assertIsNotNone(http)
def test_raise_error(self):
url = 'http://www.fake-url-that-not-exist-on-the-internet.com'
with self.assertRaises(ConnectionError):
HttpRequest.get(url)
|
import unittest, os, sys
current_dir = os.path.dirname(__file__)
base_dir = os.path.join(current_dir, os.pardir, os.pardir)
sys.path.append(base_dir)
from pycrawler.http import HttpRequest, UrlNotValidException
class HttpRequestTests(unittest.TestCase):
def test_response_not_empty(self):
url = 'http://www.pasarpanda.com'
http = HttpRequest.get(url)
self.assertIsNotNone(http)
def test_raise_error(self):
url = 'http://www.fake-url-that-not-exist-on-the-internet.com'
with self.assertRaises(UrlNotValidException):
HttpRequest.get(url)
|
Change raises class to UrlNotValidException
|
Change raises class to UrlNotValidException
|
Python
|
mit
|
slaveofcode/pycrawler,slaveofcode/pycrawler
|
python
|
## Code Before:
import unittest, os, sys
current_dir = os.path.dirname(__file__)
base_dir = os.path.join(current_dir, os.pardir, os.pardir)
sys.path.append(base_dir)
from requests.exceptions import ConnectionError
from pycrawler.http import HttpRequest
class HttpRequestTests(unittest.TestCase):
def test_response_not_empty(self):
url = 'http://www.pasarpanda.com'
http = HttpRequest.get(url)
self.assertIsNotNone(http)
def test_raise_error(self):
url = 'http://www.fake-url-that-not-exist-on-the-internet.com'
with self.assertRaises(ConnectionError):
HttpRequest.get(url)
## Instruction:
Change raises class to UrlNotValidException
## Code After:
import unittest, os, sys
current_dir = os.path.dirname(__file__)
base_dir = os.path.join(current_dir, os.pardir, os.pardir)
sys.path.append(base_dir)
from pycrawler.http import HttpRequest, UrlNotValidException
class HttpRequestTests(unittest.TestCase):
def test_response_not_empty(self):
url = 'http://www.pasarpanda.com'
http = HttpRequest.get(url)
self.assertIsNotNone(http)
def test_raise_error(self):
url = 'http://www.fake-url-that-not-exist-on-the-internet.com'
with self.assertRaises(UrlNotValidException):
HttpRequest.get(url)
|
# ... existing code ...
base_dir = os.path.join(current_dir, os.pardir, os.pardir)
sys.path.append(base_dir)
from pycrawler.http import HttpRequest, UrlNotValidException
class HttpRequestTests(unittest.TestCase):
# ... modified code ...
def test_raise_error(self):
url = 'http://www.fake-url-that-not-exist-on-the-internet.com'
with self.assertRaises(UrlNotValidException):
HttpRequest.get(url)
# ... rest of the code ...
|
a610af721f0daa3996bec139cae8836b1f80b4de
|
core/src/com/pqbyte/coherence/Map.java
|
core/src/com/pqbyte/coherence/Map.java
|
package com.pqbyte.coherence;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.scenes.scene2d.Actor;
/**
* The map where the game is played.
*/
public class Map extends Actor {
private Texture texture;
public Map(Texture texture, float width, float height) {
this.texture = texture;
setBounds(getX(), getY(), width, height);
}
@Override
public void draw(Batch batch, float parentAlpha) {
batch.draw(texture, getX(), getY(), getWidth(), getHeight());
}
}
|
package com.pqbyte.coherence;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.physics.box2d.Body;
import com.badlogic.gdx.physics.box2d.BodyDef;
import com.badlogic.gdx.physics.box2d.EdgeShape;
import com.badlogic.gdx.physics.box2d.FixtureDef;
import com.badlogic.gdx.physics.box2d.World;
import com.badlogic.gdx.scenes.scene2d.Actor;
/**
* The map where the game is played.
*/
public class Map extends Actor {
private Texture texture;
private World world;
public Map(Texture texture, float width, float height, World world) {
this.texture = texture;
this.world = world;
setBounds(getX(), getY(), width, height);
createWalls();
}
@Override
public void draw(Batch batch, float parentAlpha) {
batch.draw(texture, getX(), getY(), getWidth(), getHeight());
}
/**
* Creates the Box2D walls for the map,
* which stop things from escaping the map.
*/
private void createWalls() {
createWall(0, 0, getWidth(), 0);
createWall(0, getHeight(), getWidth(), getHeight());
createWall(0, 0, 0, getHeight());
createWall(getWidth(), 0, getWidth(), getHeight());
}
private void createWall(float x1, float y1, float x2, float y2) {
BodyDef def = new BodyDef();
def.type = BodyDef.BodyType.StaticBody;
def.position.set(0, 0);
EdgeShape shape = new EdgeShape();
shape.set(x1, y1, x2, y2);
FixtureDef properties = new FixtureDef();
properties.shape = shape;
properties.filter.categoryBits = Constants.WORLD_ENTITY;
properties.filter.maskBits = Constants.PHYSICS_ENTITY;
Body wall = world.createBody(def);
wall.createFixture(properties);
shape.dispose();
}
}
|
Add Box2D walls to map
|
Add Box2D walls to map
|
Java
|
apache-2.0
|
pqbyte/coherence
|
java
|
## Code Before:
package com.pqbyte.coherence;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.scenes.scene2d.Actor;
/**
* The map where the game is played.
*/
public class Map extends Actor {
private Texture texture;
public Map(Texture texture, float width, float height) {
this.texture = texture;
setBounds(getX(), getY(), width, height);
}
@Override
public void draw(Batch batch, float parentAlpha) {
batch.draw(texture, getX(), getY(), getWidth(), getHeight());
}
}
## Instruction:
Add Box2D walls to map
## Code After:
package com.pqbyte.coherence;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.physics.box2d.Body;
import com.badlogic.gdx.physics.box2d.BodyDef;
import com.badlogic.gdx.physics.box2d.EdgeShape;
import com.badlogic.gdx.physics.box2d.FixtureDef;
import com.badlogic.gdx.physics.box2d.World;
import com.badlogic.gdx.scenes.scene2d.Actor;
/**
* The map where the game is played.
*/
public class Map extends Actor {
private Texture texture;
private World world;
public Map(Texture texture, float width, float height, World world) {
this.texture = texture;
this.world = world;
setBounds(getX(), getY(), width, height);
createWalls();
}
@Override
public void draw(Batch batch, float parentAlpha) {
batch.draw(texture, getX(), getY(), getWidth(), getHeight());
}
/**
* Creates the Box2D walls for the map,
* which stop things from escaping the map.
*/
private void createWalls() {
createWall(0, 0, getWidth(), 0);
createWall(0, getHeight(), getWidth(), getHeight());
createWall(0, 0, 0, getHeight());
createWall(getWidth(), 0, getWidth(), getHeight());
}
private void createWall(float x1, float y1, float x2, float y2) {
BodyDef def = new BodyDef();
def.type = BodyDef.BodyType.StaticBody;
def.position.set(0, 0);
EdgeShape shape = new EdgeShape();
shape.set(x1, y1, x2, y2);
FixtureDef properties = new FixtureDef();
properties.shape = shape;
properties.filter.categoryBits = Constants.WORLD_ENTITY;
properties.filter.maskBits = Constants.PHYSICS_ENTITY;
Body wall = world.createBody(def);
wall.createFixture(properties);
shape.dispose();
}
}
|
# ... existing code ...
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.physics.box2d.Body;
import com.badlogic.gdx.physics.box2d.BodyDef;
import com.badlogic.gdx.physics.box2d.EdgeShape;
import com.badlogic.gdx.physics.box2d.FixtureDef;
import com.badlogic.gdx.physics.box2d.World;
import com.badlogic.gdx.scenes.scene2d.Actor;
/**
# ... modified code ...
public class Map extends Actor {
private Texture texture;
private World world;
public Map(Texture texture, float width, float height, World world) {
this.texture = texture;
this.world = world;
setBounds(getX(), getY(), width, height);
createWalls();
}
@Override
...
public void draw(Batch batch, float parentAlpha) {
batch.draw(texture, getX(), getY(), getWidth(), getHeight());
}
/**
* Creates the Box2D walls for the map,
* which stop things from escaping the map.
*/
private void createWalls() {
createWall(0, 0, getWidth(), 0);
createWall(0, getHeight(), getWidth(), getHeight());
createWall(0, 0, 0, getHeight());
createWall(getWidth(), 0, getWidth(), getHeight());
}
private void createWall(float x1, float y1, float x2, float y2) {
BodyDef def = new BodyDef();
def.type = BodyDef.BodyType.StaticBody;
def.position.set(0, 0);
EdgeShape shape = new EdgeShape();
shape.set(x1, y1, x2, y2);
FixtureDef properties = new FixtureDef();
properties.shape = shape;
properties.filter.categoryBits = Constants.WORLD_ENTITY;
properties.filter.maskBits = Constants.PHYSICS_ENTITY;
Body wall = world.createBody(def);
wall.createFixture(properties);
shape.dispose();
}
}
# ... rest of the code ...
|
7cd47486ac530cc991248d59d04260c0d297b05d
|
HTMLKit/CSSTypeSelector.h
|
HTMLKit/CSSTypeSelector.h
|
//
// CSSTypeSelector.h
// HTMLKit
//
// Created by Iska on 13/05/15.
// Copyright (c) 2015 BrainCookie. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "CSSSelector.h"
#import "CSSSimpleSelector.h"
@interface CSSTypeSelector : CSSSelector <CSSSimpleSelector>
@property (nonatomic, copy) NSString *type;
+ (instancetype)universalSelector;
- (instancetype)initWithType:(NSString *)type;
@end
|
//
// CSSTypeSelector.h
// HTMLKit
//
// Created by Iska on 13/05/15.
// Copyright (c) 2015 BrainCookie. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "CSSSelector.h"
#import "CSSSimpleSelector.h"
@interface CSSTypeSelector : CSSSelector <CSSSimpleSelector>
@property (nonatomic, copy) NSString * _Nonnull type;
+ (nullable instancetype)universalSelector;
- (nullable instancetype)initWithType:(nonnull NSString *)type;
@end
|
Add nullability specifiers to type selector
|
Add nullability specifiers to type selector
|
C
|
mit
|
iabudiab/HTMLKit,iabudiab/HTMLKit,iabudiab/HTMLKit,iabudiab/HTMLKit,iabudiab/HTMLKit
|
c
|
## Code Before:
//
// CSSTypeSelector.h
// HTMLKit
//
// Created by Iska on 13/05/15.
// Copyright (c) 2015 BrainCookie. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "CSSSelector.h"
#import "CSSSimpleSelector.h"
@interface CSSTypeSelector : CSSSelector <CSSSimpleSelector>
@property (nonatomic, copy) NSString *type;
+ (instancetype)universalSelector;
- (instancetype)initWithType:(NSString *)type;
@end
## Instruction:
Add nullability specifiers to type selector
## Code After:
//
// CSSTypeSelector.h
// HTMLKit
//
// Created by Iska on 13/05/15.
// Copyright (c) 2015 BrainCookie. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "CSSSelector.h"
#import "CSSSimpleSelector.h"
@interface CSSTypeSelector : CSSSelector <CSSSimpleSelector>
@property (nonatomic, copy) NSString * _Nonnull type;
+ (nullable instancetype)universalSelector;
- (nullable instancetype)initWithType:(nonnull NSString *)type;
@end
|
// ... existing code ...
@interface CSSTypeSelector : CSSSelector <CSSSimpleSelector>
@property (nonatomic, copy) NSString * _Nonnull type;
+ (nullable instancetype)universalSelector;
- (nullable instancetype)initWithType:(nonnull NSString *)type;
@end
// ... rest of the code ...
|
7c28d667bc0d177feea7f3437ac6206bc5d5da7d
|
core/src/main/net/gpdev/gameoflife/GameOfLife.java
|
core/src/main/net/gpdev/gameoflife/GameOfLife.java
|
package net.gpdev.gameoflife;
public class GameOfLife {
private final int xDim;
private final int yDim;
private Grid current;
private Grid next;
public GameOfLife(int xDim, int yDim) {
this.xDim = xDim;
this.yDim = yDim;
current = new Grid(xDim, yDim);
next = new Grid(xDim, yDim);
}
public void populateCell(int x, int y) {
current.set(x, y);
}
public boolean isCellPopulated(int x, int y) {
return !current.isEmpty(x, y);
}
public void tick() {
for (int i = 0; i < xDim; i++) {
for (int j = 0; j < yDim; j++) {
if (current.isEmpty(i, j)) {
if (current.numNeighbors(i, j) == 3) {
next.set(i, j);
}
}
else {
final int numNeighbors = current.numNeighbors(i, j);
if (numNeighbors == 2 || numNeighbors == 3) {
next.set(i, j);
}
}
}
}
current = next;
}
@Override
public String toString() {
return current.toString();
}
}
|
package net.gpdev.gameoflife;
public class GameOfLife {
private final int xDim;
private final int yDim;
private Grid current;
private Grid next;
public GameOfLife(int xDim, int yDim) {
this.xDim = xDim;
this.yDim = yDim;
current = new Grid(xDim, yDim);
next = new Grid(xDim, yDim);
}
public void populateCell(int x, int y) {
current.set(x, y);
}
public boolean isCellPopulated(int x, int y) {
return !current.isEmpty(x, y);
}
public void tick() {
for (int i = 0; i < xDim; i++) {
for (int j = 0; j < yDim; j++) {
if (current.isEmpty(i, j)) {
if (current.numNeighbors(i, j) == 3) {
next.set(i, j);
} else {
next.unset(i, j);
}
} else {
final int numNeighbors = current.numNeighbors(i, j);
if (numNeighbors == 2 || numNeighbors == 3) {
next.set(i, j);
} else {
next.unset(i, j);
}
}
}
}
final Grid prev = current;
current = next;
next = prev;
}
@Override
public String toString() {
return current.toString();
}
}
|
Correct game.tick() implementation and pass failing test
|
Correct game.tick() implementation and pass failing test
|
Java
|
mit
|
gpertzov/game-of-life,gpertzov/game-of-life,gpertzov/game-of-life
|
java
|
## Code Before:
package net.gpdev.gameoflife;
public class GameOfLife {
private final int xDim;
private final int yDim;
private Grid current;
private Grid next;
public GameOfLife(int xDim, int yDim) {
this.xDim = xDim;
this.yDim = yDim;
current = new Grid(xDim, yDim);
next = new Grid(xDim, yDim);
}
public void populateCell(int x, int y) {
current.set(x, y);
}
public boolean isCellPopulated(int x, int y) {
return !current.isEmpty(x, y);
}
public void tick() {
for (int i = 0; i < xDim; i++) {
for (int j = 0; j < yDim; j++) {
if (current.isEmpty(i, j)) {
if (current.numNeighbors(i, j) == 3) {
next.set(i, j);
}
}
else {
final int numNeighbors = current.numNeighbors(i, j);
if (numNeighbors == 2 || numNeighbors == 3) {
next.set(i, j);
}
}
}
}
current = next;
}
@Override
public String toString() {
return current.toString();
}
}
## Instruction:
Correct game.tick() implementation and pass failing test
## Code After:
package net.gpdev.gameoflife;
public class GameOfLife {
private final int xDim;
private final int yDim;
private Grid current;
private Grid next;
public GameOfLife(int xDim, int yDim) {
this.xDim = xDim;
this.yDim = yDim;
current = new Grid(xDim, yDim);
next = new Grid(xDim, yDim);
}
public void populateCell(int x, int y) {
current.set(x, y);
}
public boolean isCellPopulated(int x, int y) {
return !current.isEmpty(x, y);
}
public void tick() {
for (int i = 0; i < xDim; i++) {
for (int j = 0; j < yDim; j++) {
if (current.isEmpty(i, j)) {
if (current.numNeighbors(i, j) == 3) {
next.set(i, j);
} else {
next.unset(i, j);
}
} else {
final int numNeighbors = current.numNeighbors(i, j);
if (numNeighbors == 2 || numNeighbors == 3) {
next.set(i, j);
} else {
next.unset(i, j);
}
}
}
}
final Grid prev = current;
current = next;
next = prev;
}
@Override
public String toString() {
return current.toString();
}
}
|
# ... existing code ...
if (current.isEmpty(i, j)) {
if (current.numNeighbors(i, j) == 3) {
next.set(i, j);
} else {
next.unset(i, j);
}
} else {
final int numNeighbors = current.numNeighbors(i, j);
if (numNeighbors == 2 || numNeighbors == 3) {
next.set(i, j);
} else {
next.unset(i, j);
}
}
}
}
final Grid prev = current;
current = next;
next = prev;
}
@Override
# ... rest of the code ...
|
34fbab0a31956af0572c31612f359608a8819360
|
models/phase3_eval/assemble_cx.py
|
models/phase3_eval/assemble_cx.py
|
from __future__ import absolute_import, print_function, unicode_literals
from builtins import dict, str
from os.path import join as pjoin
from indra.assemblers import CxAssembler
import indra.tools.assemble_corpus as ac
def assemble_cx(stmts, out_file):
"""Return a CX assembler."""
stmts = ac.filter_belief(stmts, 0.95)
stmts = ac.filter_top_level(stmts)
stmts = ac.strip_agent_context(stmts)
ca = CxAssembler()
ca.add_statements(stmts)
model = ca.make_model()
ca.save_model(out_file)
return ca
|
from __future__ import absolute_import, print_function, unicode_literals
from builtins import dict, str
from os.path import join as pjoin
from indra.assemblers import CxAssembler
import indra.tools.assemble_corpus as ac
def assemble_cx(stmts, out_file):
"""Return a CX assembler."""
stmts = ac.filter_belief(stmts, 0.95)
stmts = ac.filter_top_level(stmts)
ca = CxAssembler()
ca.add_statements(stmts)
model = ca.make_model()
ca.save_model(out_file)
return ca
|
Remove strip context for CX assembly
|
Remove strip context for CX assembly
|
Python
|
bsd-2-clause
|
pvtodorov/indra,bgyori/indra,pvtodorov/indra,johnbachman/belpy,pvtodorov/indra,johnbachman/belpy,johnbachman/belpy,sorgerlab/indra,sorgerlab/indra,pvtodorov/indra,bgyori/indra,johnbachman/indra,sorgerlab/indra,johnbachman/indra,sorgerlab/belpy,johnbachman/indra,bgyori/indra,sorgerlab/belpy,sorgerlab/belpy
|
python
|
## Code Before:
from __future__ import absolute_import, print_function, unicode_literals
from builtins import dict, str
from os.path import join as pjoin
from indra.assemblers import CxAssembler
import indra.tools.assemble_corpus as ac
def assemble_cx(stmts, out_file):
"""Return a CX assembler."""
stmts = ac.filter_belief(stmts, 0.95)
stmts = ac.filter_top_level(stmts)
stmts = ac.strip_agent_context(stmts)
ca = CxAssembler()
ca.add_statements(stmts)
model = ca.make_model()
ca.save_model(out_file)
return ca
## Instruction:
Remove strip context for CX assembly
## Code After:
from __future__ import absolute_import, print_function, unicode_literals
from builtins import dict, str
from os.path import join as pjoin
from indra.assemblers import CxAssembler
import indra.tools.assemble_corpus as ac
def assemble_cx(stmts, out_file):
"""Return a CX assembler."""
stmts = ac.filter_belief(stmts, 0.95)
stmts = ac.filter_top_level(stmts)
ca = CxAssembler()
ca.add_statements(stmts)
model = ca.make_model()
ca.save_model(out_file)
return ca
|
# ... existing code ...
"""Return a CX assembler."""
stmts = ac.filter_belief(stmts, 0.95)
stmts = ac.filter_top_level(stmts)
ca = CxAssembler()
ca.add_statements(stmts)
model = ca.make_model()
# ... rest of the code ...
|
78eaa907ea986c12716b27fc6a4533d83242b97a
|
bci/__init__.py
|
bci/__init__.py
|
from fakebci import FakeBCI
|
import os
import sys
import platform
import shutil
import inspect
#
#def machine():
# """Return type of machine."""
# if os.name == 'nt' and sys.version_info[:2] < (2,7):
# return os.environ.get("PROCESSOR_ARCHITEW6432",
# os.environ.get('PROCESSOR_ARCHITECTURE', ''))
# else:
# return platform.machine()
#
#def arch(machine=machine()):
# """Return bitness of operating system, or None if unknown."""
# machine2bits = {'AMD64': 64, 'x86_64': 64, 'i386': 32, 'x86': 32}
# return machine2bits.get(machine, None)
#
#print (os_bits())
from fakebci import *
def create_so():
base_dir = os.path.dirname(inspect.getabsfile(FakeBCI))
boosted_bci = os.path.join(base_dir, 'boosted_bci.so')
if not os.path.exists(boosted_bci):
if sys.platform == 'darwin':
if platform.architecture()[0] == '64bit':
shutil.copyfile(os.path.join(base_dir, 'boosted_bci_darwin_x86_64.so'), boosted_bci)
else:
raise NotImplementedError("32 bit OS X is currently untested")
try:
from boosted_bci import greet
except:
print "Platform specific bci files have not been created"
|
Make some changes to the bci package file.
|
Make some changes to the bci package file.
|
Python
|
bsd-3-clause
|
NeuralProsthesisLab/unlock,NeuralProsthesisLab/unlock,NeuralProsthesisLab/unlock,NeuralProsthesisLab/unlock,NeuralProsthesisLab/unlock,NeuralProsthesisLab/unlock,NeuralProsthesisLab/unlock
|
python
|
## Code Before:
from fakebci import FakeBCI
## Instruction:
Make some changes to the bci package file.
## Code After:
import os
import sys
import platform
import shutil
import inspect
#
#def machine():
# """Return type of machine."""
# if os.name == 'nt' and sys.version_info[:2] < (2,7):
# return os.environ.get("PROCESSOR_ARCHITEW6432",
# os.environ.get('PROCESSOR_ARCHITECTURE', ''))
# else:
# return platform.machine()
#
#def arch(machine=machine()):
# """Return bitness of operating system, or None if unknown."""
# machine2bits = {'AMD64': 64, 'x86_64': 64, 'i386': 32, 'x86': 32}
# return machine2bits.get(machine, None)
#
#print (os_bits())
from fakebci import *
def create_so():
base_dir = os.path.dirname(inspect.getabsfile(FakeBCI))
boosted_bci = os.path.join(base_dir, 'boosted_bci.so')
if not os.path.exists(boosted_bci):
if sys.platform == 'darwin':
if platform.architecture()[0] == '64bit':
shutil.copyfile(os.path.join(base_dir, 'boosted_bci_darwin_x86_64.so'), boosted_bci)
else:
raise NotImplementedError("32 bit OS X is currently untested")
try:
from boosted_bci import greet
except:
print "Platform specific bci files have not been created"
|
# ... existing code ...
import os
import sys
import platform
import shutil
import inspect
#
#def machine():
# """Return type of machine."""
# if os.name == 'nt' and sys.version_info[:2] < (2,7):
# return os.environ.get("PROCESSOR_ARCHITEW6432",
# os.environ.get('PROCESSOR_ARCHITECTURE', ''))
# else:
# return platform.machine()
#
#def arch(machine=machine()):
# """Return bitness of operating system, or None if unknown."""
# machine2bits = {'AMD64': 64, 'x86_64': 64, 'i386': 32, 'x86': 32}
# return machine2bits.get(machine, None)
#
#print (os_bits())
from fakebci import *
def create_so():
base_dir = os.path.dirname(inspect.getabsfile(FakeBCI))
boosted_bci = os.path.join(base_dir, 'boosted_bci.so')
if not os.path.exists(boosted_bci):
if sys.platform == 'darwin':
if platform.architecture()[0] == '64bit':
shutil.copyfile(os.path.join(base_dir, 'boosted_bci_darwin_x86_64.so'), boosted_bci)
else:
raise NotImplementedError("32 bit OS X is currently untested")
try:
from boosted_bci import greet
except:
print "Platform specific bci files have not been created"
# ... rest of the code ...
|
f2bf7807754d13c92bd2901072dd804dda61805f
|
cla_public/apps/contact/constants.py
|
cla_public/apps/contact/constants.py
|
"Contact constants"
from flask.ext.babel import lazy_gettext as _
DAY_TODAY = 'today'
DAY_SPECIFIC = 'specific_day'
DAY_CHOICES = (
(DAY_TODAY, _('Call me today at')),
(DAY_SPECIFIC, _('Call me in the next week on'))
)
|
"Contact constants"
from flask.ext.babel import lazy_gettext as _
DAY_TODAY = 'today'
DAY_SPECIFIC = 'specific_day'
DAY_CHOICES = (
(DAY_TODAY, _('Call me today at')),
(DAY_SPECIFIC, _('Call me in on'))
)
|
Update button label (call back time picker)
|
FE: Update button label (call back time picker)
|
Python
|
mit
|
ministryofjustice/cla_public,ministryofjustice/cla_public,ministryofjustice/cla_public,ministryofjustice/cla_public
|
python
|
## Code Before:
"Contact constants"
from flask.ext.babel import lazy_gettext as _
DAY_TODAY = 'today'
DAY_SPECIFIC = 'specific_day'
DAY_CHOICES = (
(DAY_TODAY, _('Call me today at')),
(DAY_SPECIFIC, _('Call me in the next week on'))
)
## Instruction:
FE: Update button label (call back time picker)
## Code After:
"Contact constants"
from flask.ext.babel import lazy_gettext as _
DAY_TODAY = 'today'
DAY_SPECIFIC = 'specific_day'
DAY_CHOICES = (
(DAY_TODAY, _('Call me today at')),
(DAY_SPECIFIC, _('Call me in on'))
)
|
// ... existing code ...
DAY_SPECIFIC = 'specific_day'
DAY_CHOICES = (
(DAY_TODAY, _('Call me today at')),
(DAY_SPECIFIC, _('Call me in on'))
)
// ... rest of the code ...
|
fcb91db238536949ceca5bcbe9c93b61b658240a
|
src/matchers/EXPMatchers+beIdenticalTo.h
|
src/matchers/EXPMatchers+beIdenticalTo.h
|
EXPMatcherInterface(beIdenticalTo, (void *expected));
|
EXPMatcherInterface(_beIdenticalTo, (void *expected));
#if __has_feature(objc_arc)
#define beIdenticalTo(expected) _beIdenticalTo((__bridge void*)expected)
#else
#define beIdenticalTo _beIdenticalTo
#endif
|
Fix ARC warning and avoid having to bridge id objects
|
Fix ARC warning and avoid having to bridge id objects
|
C
|
mit
|
iguchunhui/expecta,iosdev-republicofapps/expecta,ashfurrow/expecta,ashfurrow/expecta,Lightricks/expecta,specta/expecta,jmoody/expecta,jmburges/expecta,modocache/expecta,jmoody/expecta,suxinde2009/expecta,Bogon/expecta,github/expecta,tonyarnold/expecta,Bogon/expecta,Lightricks/expecta,jmburges/expecta,suxinde2009/expecta,iosdev-republicofapps/expecta,PatrykKaczmarek/expecta,modocache/expecta,tonyarnold/expecta,iosdev-republicofapps/expecta,ashfurrow/expecta,github/expecta,tonyarnold/expecta,PatrykKaczmarek/expecta,PatrykKaczmarek/expecta,tonyarnold/expecta,jmoody/expecta,udemy/expecta,ashfurrow/expecta,jmoody/expecta,iosdev-republicofapps/expecta,udemy/expecta,jmburges/expecta,wessmith/expecta,PatrykKaczmarek/expecta,iguchunhui/expecta,jmburges/expecta,modocache/expecta,modocache/expecta,wessmith/expecta
|
c
|
## Code Before:
EXPMatcherInterface(beIdenticalTo, (void *expected));
## Instruction:
Fix ARC warning and avoid having to bridge id objects
## Code After:
EXPMatcherInterface(_beIdenticalTo, (void *expected));
#if __has_feature(objc_arc)
#define beIdenticalTo(expected) _beIdenticalTo((__bridge void*)expected)
#else
#define beIdenticalTo _beIdenticalTo
#endif
|
...
EXPMatcherInterface(_beIdenticalTo, (void *expected));
#if __has_feature(objc_arc)
#define beIdenticalTo(expected) _beIdenticalTo((__bridge void*)expected)
#else
#define beIdenticalTo _beIdenticalTo
#endif
...
|
f531cfa07ba6e6e0d36ba768dbeb4706ae7cd259
|
tlslite/utils/pycrypto_rsakey.py
|
tlslite/utils/pycrypto_rsakey.py
|
"""PyCrypto RSA implementation."""
from .cryptomath import *
from .rsakey import *
from .python_rsakey import Python_RSAKey
if pycryptoLoaded:
from Crypto.PublicKey import RSA
class PyCrypto_RSAKey(RSAKey):
def __init__(self, n=0, e=0, d=0, p=0, q=0, dP=0, dQ=0, qInv=0):
if not d:
self.rsa = RSA.construct( (n, e) )
else:
self.rsa = RSA.construct( (n, e, d, p, q) )
def __getattr__(self, name):
return getattr(self.rsa, name)
def hasPrivateKey(self):
return self.rsa.has_private()
def _rawPrivateKeyOp(self, m):
s = numberToString(m, numBytes(self.n))
c = stringToNumber(self.rsa.decrypt((s,)))
return c
def _rawPublicKeyOp(self, c):
s = numberToString(c, numBytes(self.n))
m = stringToNumber(self.rsa.encrypt(s, None)[0])
return m
def generate(bits):
key = PyCrypto_RSAKey()
def f(numBytes):
return bytes(getRandomBytes(numBytes))
key.rsa = RSA.generate(bits, f)
return key
generate = staticmethod(generate)
|
"""PyCrypto RSA implementation."""
from cryptomath import *
from .rsakey import *
from .python_rsakey import Python_RSAKey
if pycryptoLoaded:
from Crypto.PublicKey import RSA
class PyCrypto_RSAKey(RSAKey):
def __init__(self, n=0, e=0, d=0, p=0, q=0, dP=0, dQ=0, qInv=0):
if not d:
self.rsa = RSA.construct( (long(n), long(e)) )
else:
self.rsa = RSA.construct( (long(n), long(e), long(d), long(p), long(q)) )
def __getattr__(self, name):
return getattr(self.rsa, name)
def hasPrivateKey(self):
return self.rsa.has_private()
def _rawPrivateKeyOp(self, m):
c = self.rsa.decrypt((m,))
return c
def _rawPublicKeyOp(self, c):
m = self.rsa.encrypt(c, None)[0]
return m
def generate(bits):
key = PyCrypto_RSAKey()
def f(numBytes):
return bytes(getRandomBytes(numBytes))
key.rsa = RSA.generate(bits, f)
return key
generate = staticmethod(generate)
|
Remove numberToString/stringToNumber in pycrypto support package and add some int to long conversions so it can happily pass the tests (I bet this is enough to get it working)
|
Remove numberToString/stringToNumber in pycrypto support package and add some int to long conversions so it can happily pass the tests (I bet this is enough to get it working)
|
Python
|
lgpl-2.1
|
ioef/tlslite-ng,ioef/tlslite-ng,ioef/tlslite-ng
|
python
|
## Code Before:
"""PyCrypto RSA implementation."""
from .cryptomath import *
from .rsakey import *
from .python_rsakey import Python_RSAKey
if pycryptoLoaded:
from Crypto.PublicKey import RSA
class PyCrypto_RSAKey(RSAKey):
def __init__(self, n=0, e=0, d=0, p=0, q=0, dP=0, dQ=0, qInv=0):
if not d:
self.rsa = RSA.construct( (n, e) )
else:
self.rsa = RSA.construct( (n, e, d, p, q) )
def __getattr__(self, name):
return getattr(self.rsa, name)
def hasPrivateKey(self):
return self.rsa.has_private()
def _rawPrivateKeyOp(self, m):
s = numberToString(m, numBytes(self.n))
c = stringToNumber(self.rsa.decrypt((s,)))
return c
def _rawPublicKeyOp(self, c):
s = numberToString(c, numBytes(self.n))
m = stringToNumber(self.rsa.encrypt(s, None)[0])
return m
def generate(bits):
key = PyCrypto_RSAKey()
def f(numBytes):
return bytes(getRandomBytes(numBytes))
key.rsa = RSA.generate(bits, f)
return key
generate = staticmethod(generate)
## Instruction:
Remove numberToString/stringToNumber in pycrypto support package and add some int to long conversions so it can happily pass the tests (I bet this is enough to get it working)
## Code After:
"""PyCrypto RSA implementation."""
from cryptomath import *
from .rsakey import *
from .python_rsakey import Python_RSAKey
if pycryptoLoaded:
from Crypto.PublicKey import RSA
class PyCrypto_RSAKey(RSAKey):
def __init__(self, n=0, e=0, d=0, p=0, q=0, dP=0, dQ=0, qInv=0):
if not d:
self.rsa = RSA.construct( (long(n), long(e)) )
else:
self.rsa = RSA.construct( (long(n), long(e), long(d), long(p), long(q)) )
def __getattr__(self, name):
return getattr(self.rsa, name)
def hasPrivateKey(self):
return self.rsa.has_private()
def _rawPrivateKeyOp(self, m):
c = self.rsa.decrypt((m,))
return c
def _rawPublicKeyOp(self, c):
m = self.rsa.encrypt(c, None)[0]
return m
def generate(bits):
key = PyCrypto_RSAKey()
def f(numBytes):
return bytes(getRandomBytes(numBytes))
key.rsa = RSA.generate(bits, f)
return key
generate = staticmethod(generate)
|
# ... existing code ...
"""PyCrypto RSA implementation."""
from cryptomath import *
from .rsakey import *
from .python_rsakey import Python_RSAKey
# ... modified code ...
class PyCrypto_RSAKey(RSAKey):
def __init__(self, n=0, e=0, d=0, p=0, q=0, dP=0, dQ=0, qInv=0):
if not d:
self.rsa = RSA.construct( (long(n), long(e)) )
else:
self.rsa = RSA.construct( (long(n), long(e), long(d), long(p), long(q)) )
def __getattr__(self, name):
return getattr(self.rsa, name)
...
return self.rsa.has_private()
def _rawPrivateKeyOp(self, m):
c = self.rsa.decrypt((m,))
return c
def _rawPublicKeyOp(self, c):
m = self.rsa.encrypt(c, None)[0]
return m
def generate(bits):
# ... rest of the code ...
|
f87c337486d14650bb8268a6bf9b2a37487826da
|
doc-examples/src/main/java/arez/doc/examples/at_component_dependency/PersonViewModel.java
|
doc-examples/src/main/java/arez/doc/examples/at_component_dependency/PersonViewModel.java
|
package arez.doc.examples.at_component_dependency;
import arez.annotations.ArezComponent;
import arez.annotations.ComponentDependency;
import arez.annotations.Observable;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
@ArezComponent
public abstract class PersonViewModel
{
@Nonnull
private final Person _person;
//DOC ELIDE START
public PersonViewModel( @Nonnull final Person person )
{
_person = person;
}
//DOC ELIDE END
// Let imagine there is a lot more logic and state on the view model
// to justify it's existence rather than just having view layer directly
// accessing underlying entities
@ComponentDependency
@Nonnull
public final Person getPerson()
{
// This reference is immutable and the network replication
// layer is responsible for managing the lifecycle of person
// component and may dispose it when the Person entity is deleted
// on the server which should trigger this view model being disposed.
return _person;
}
/**
* The Job entity is likewise controlled by the server
* and can be updated, removed on the server and replicated to the web
* browser. In this scenario the current job is just removed from the
* person view model.
*/
@ComponentDependency( action = ComponentDependency.Action.SET_NULL )
@Observable
@Nullable
public abstract Job getCurrentJob();
//DOC ELIDE START
public abstract void setCurrentJob( @Nullable final Job currentJob );
//DOC ELIDE END
}
|
package arez.doc.examples.at_component_dependency;
import arez.annotations.ArezComponent;
import arez.annotations.ComponentDependency;
import arez.annotations.Observable;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
@ArezComponent
public abstract class PersonViewModel
{
// This reference is immutable and the network replication
// layer is responsible for managing the lifecycle of person
// component and may dispose it when the Person entity is deleted
// on the server which should trigger this view model being disposed.
@ComponentDependency
@Nonnull
final Person _person;
//DOC ELIDE START
public PersonViewModel( @Nonnull final Person person )
{
_person = person;
}
//DOC ELIDE END
// Let imagine there is a lot more logic and state on the view model
// to justify it's existence rather than just having view layer directly
// accessing underlying entities
@Nonnull
public final Person getPerson()
{
return _person;
}
/**
* The Job entity is likewise controlled by the server
* and can be updated, removed on the server and replicated to the web
* browser. In this scenario the current job is just removed from the
* person view model.
*/
@ComponentDependency( action = ComponentDependency.Action.SET_NULL )
@Observable
@Nullable
public abstract Job getCurrentJob();
//DOC ELIDE START
public abstract void setCurrentJob( @Nullable final Job currentJob );
//DOC ELIDE END
}
|
Move @ComponentDependency to the field as that is the latest recomendation
|
Move @ComponentDependency to the field as that is the latest recomendation
|
Java
|
apache-2.0
|
realityforge/arez,realityforge/arez,realityforge/arez
|
java
|
## Code Before:
package arez.doc.examples.at_component_dependency;
import arez.annotations.ArezComponent;
import arez.annotations.ComponentDependency;
import arez.annotations.Observable;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
@ArezComponent
public abstract class PersonViewModel
{
@Nonnull
private final Person _person;
//DOC ELIDE START
public PersonViewModel( @Nonnull final Person person )
{
_person = person;
}
//DOC ELIDE END
// Let imagine there is a lot more logic and state on the view model
// to justify it's existence rather than just having view layer directly
// accessing underlying entities
@ComponentDependency
@Nonnull
public final Person getPerson()
{
// This reference is immutable and the network replication
// layer is responsible for managing the lifecycle of person
// component and may dispose it when the Person entity is deleted
// on the server which should trigger this view model being disposed.
return _person;
}
/**
* The Job entity is likewise controlled by the server
* and can be updated, removed on the server and replicated to the web
* browser. In this scenario the current job is just removed from the
* person view model.
*/
@ComponentDependency( action = ComponentDependency.Action.SET_NULL )
@Observable
@Nullable
public abstract Job getCurrentJob();
//DOC ELIDE START
public abstract void setCurrentJob( @Nullable final Job currentJob );
//DOC ELIDE END
}
## Instruction:
Move @ComponentDependency to the field as that is the latest recomendation
## Code After:
package arez.doc.examples.at_component_dependency;
import arez.annotations.ArezComponent;
import arez.annotations.ComponentDependency;
import arez.annotations.Observable;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
@ArezComponent
public abstract class PersonViewModel
{
// This reference is immutable and the network replication
// layer is responsible for managing the lifecycle of person
// component and may dispose it when the Person entity is deleted
// on the server which should trigger this view model being disposed.
@ComponentDependency
@Nonnull
final Person _person;
//DOC ELIDE START
public PersonViewModel( @Nonnull final Person person )
{
_person = person;
}
//DOC ELIDE END
// Let imagine there is a lot more logic and state on the view model
// to justify it's existence rather than just having view layer directly
// accessing underlying entities
@Nonnull
public final Person getPerson()
{
return _person;
}
/**
* The Job entity is likewise controlled by the server
* and can be updated, removed on the server and replicated to the web
* browser. In this scenario the current job is just removed from the
* person view model.
*/
@ComponentDependency( action = ComponentDependency.Action.SET_NULL )
@Observable
@Nullable
public abstract Job getCurrentJob();
//DOC ELIDE START
public abstract void setCurrentJob( @Nullable final Job currentJob );
//DOC ELIDE END
}
|
# ... existing code ...
@ArezComponent
public abstract class PersonViewModel
{
// This reference is immutable and the network replication
// layer is responsible for managing the lifecycle of person
// component and may dispose it when the Person entity is deleted
// on the server which should trigger this view model being disposed.
@ComponentDependency
@Nonnull
final Person _person;
//DOC ELIDE START
public PersonViewModel( @Nonnull final Person person )
# ... modified code ...
// to justify it's existence rather than just having view layer directly
// accessing underlying entities
@Nonnull
public final Person getPerson()
{
return _person;
}
# ... rest of the code ...
|
73d7377d0ba6c5ac768d547aaa957b48a6b1d46a
|
menu_generator/utils.py
|
menu_generator/utils.py
|
from importlib import import_module
from django.apps import apps
from django.core.exceptions import ImproperlyConfigured
def get_callable(func_or_path):
"""
Receives a dotted path or a callable, Returns a callable or None
"""
if callable(func_or_path):
return func_or_path
module_name = '.'.join(func_or_path.split('.')[:-1])
function_name = func_or_path.split('.')[-1]
_module = import_module(module_name)
func = getattr(_module, function_name)
return func
def clean_app_config(app_path):
"""
Removes the AppConfig path for this app and returns the new string
"""
apps_names = [app.name for app in apps.get_app_configs()]
if app_path in apps_names:
return app_path
else:
app_split = app_path.split('.')
new_app = '.'.join(app_split[:-2])
if new_app in apps_names:
return new_app
else: # pragma: no cover
raise ImproperlyConfigured(
"The application {0} is not in the configured apps or does" +
"not have the pattern app.apps.AppConfig".format(app_path)
)
|
from importlib import import_module
from django.apps import apps
from django.core.exceptions import ImproperlyConfigured
def get_callable(func_or_path):
"""
Receives a dotted path or a callable, Returns a callable or None
"""
if callable(func_or_path):
return func_or_path
module_name = '.'.join(func_or_path.split('.')[:-1])
function_name = func_or_path.split('.')[-1]
_module = import_module(module_name)
func = getattr(_module, function_name)
return func
def clean_app_config(app_path):
"""
Removes the AppConfig path for this app and returns the new string
"""
apps_names = [app.name for app in apps.get_app_configs()]
if app_path in apps_names:
return app_path
else:
app_split = app_path.split('.')
new_app = '.'.join(app_split[:-2])
if new_app in apps_names:
return new_app
else: # pragma: no cover
raise ImproperlyConfigured(
"The application {0} is not in the configured apps or does".format(app_path) +
"not have the pattern app.apps.AppConfig"
)
|
Fix exception message if app path is invalid
|
Fix exception message if app path is invalid
|
Python
|
mit
|
yamijuan/django-menu-generator
|
python
|
## Code Before:
from importlib import import_module
from django.apps import apps
from django.core.exceptions import ImproperlyConfigured
def get_callable(func_or_path):
"""
Receives a dotted path or a callable, Returns a callable or None
"""
if callable(func_or_path):
return func_or_path
module_name = '.'.join(func_or_path.split('.')[:-1])
function_name = func_or_path.split('.')[-1]
_module = import_module(module_name)
func = getattr(_module, function_name)
return func
def clean_app_config(app_path):
"""
Removes the AppConfig path for this app and returns the new string
"""
apps_names = [app.name for app in apps.get_app_configs()]
if app_path in apps_names:
return app_path
else:
app_split = app_path.split('.')
new_app = '.'.join(app_split[:-2])
if new_app in apps_names:
return new_app
else: # pragma: no cover
raise ImproperlyConfigured(
"The application {0} is not in the configured apps or does" +
"not have the pattern app.apps.AppConfig".format(app_path)
)
## Instruction:
Fix exception message if app path is invalid
## Code After:
from importlib import import_module
from django.apps import apps
from django.core.exceptions import ImproperlyConfigured
def get_callable(func_or_path):
"""
Receives a dotted path or a callable, Returns a callable or None
"""
if callable(func_or_path):
return func_or_path
module_name = '.'.join(func_or_path.split('.')[:-1])
function_name = func_or_path.split('.')[-1]
_module = import_module(module_name)
func = getattr(_module, function_name)
return func
def clean_app_config(app_path):
"""
Removes the AppConfig path for this app and returns the new string
"""
apps_names = [app.name for app in apps.get_app_configs()]
if app_path in apps_names:
return app_path
else:
app_split = app_path.split('.')
new_app = '.'.join(app_split[:-2])
if new_app in apps_names:
return new_app
else: # pragma: no cover
raise ImproperlyConfigured(
"The application {0} is not in the configured apps or does".format(app_path) +
"not have the pattern app.apps.AppConfig"
)
|
...
return new_app
else: # pragma: no cover
raise ImproperlyConfigured(
"The application {0} is not in the configured apps or does".format(app_path) +
"not have the pattern app.apps.AppConfig"
)
...
|
20ad5bf3b814b57035ed92358e7a8cad25e5a7ee
|
gcm/api.py
|
gcm/api.py
|
import urllib2
import json
def send_gcm_message(api_key, regs_id, data, collapse_key=None):
"""
Send a GCM message for one or more devices, using json data
api_key: The API_KEY from your console (https://code.google.com/apis/console, locate Key for Server Apps in
Google Cloud Messaging for Android)
regs_id: A list with the devices which will be receiving a message
data: The dict data which will be send
collapse_key: A string to group messages, look at the documentation about it:
http://developer.android.com/google/gcm/gcm.html#request
"""
values = {
'registration_ids': regs_id,
'collapse_key': collapse_key,
'data': data
}
values = json.dumps(values)
headers = {
'UserAgent': "GCM-Server",
'Content-Type': 'application/json',
'Authorization': 'key=' + api_key,
}
request = urllib2.Request("https://android.googleapis.com/gcm/send", data=values, headers=headers)
response = urllib2.urlopen(request)
result = response.read()
return result
|
import requests
import json
def send_gcm_message(api_key, regs_id, data, collapse_key=None):
"""
Send a GCM message for one or more devices, using json data
api_key: The API_KEY from your console (https://code.google.com/apis/console, locate Key for Server Apps in
Google Cloud Messaging for Android)
regs_id: A list with the devices which will be receiving a message
data: The dict data which will be send
collapse_key: A string to group messages, look at the documentation about it:
http://developer.android.com/google/gcm/gcm.html#request
"""
values = {
'registration_ids': regs_id,
'collapse_key': collapse_key,
'data': data
}
values = json.dumps(values)
headers = {
'UserAgent': "GCM-Server",
'Content-Type': 'application/json',
'Authorization': 'key=' + api_key,
}
response = requests.post(url="https://android.googleapis.com/gcm/send",
data=values,
headers=headers)
return response.content
|
Use requests package instead of urllib2
|
Use requests package instead of urllib2
|
Python
|
bsd-2-clause
|
johnofkorea/django-gcm,johnofkorea/django-gcm,bogdal/django-gcm,bogdal/django-gcm
|
python
|
## Code Before:
import urllib2
import json
def send_gcm_message(api_key, regs_id, data, collapse_key=None):
"""
Send a GCM message for one or more devices, using json data
api_key: The API_KEY from your console (https://code.google.com/apis/console, locate Key for Server Apps in
Google Cloud Messaging for Android)
regs_id: A list with the devices which will be receiving a message
data: The dict data which will be send
collapse_key: A string to group messages, look at the documentation about it:
http://developer.android.com/google/gcm/gcm.html#request
"""
values = {
'registration_ids': regs_id,
'collapse_key': collapse_key,
'data': data
}
values = json.dumps(values)
headers = {
'UserAgent': "GCM-Server",
'Content-Type': 'application/json',
'Authorization': 'key=' + api_key,
}
request = urllib2.Request("https://android.googleapis.com/gcm/send", data=values, headers=headers)
response = urllib2.urlopen(request)
result = response.read()
return result
## Instruction:
Use requests package instead of urllib2
## Code After:
import requests
import json
def send_gcm_message(api_key, regs_id, data, collapse_key=None):
"""
Send a GCM message for one or more devices, using json data
api_key: The API_KEY from your console (https://code.google.com/apis/console, locate Key for Server Apps in
Google Cloud Messaging for Android)
regs_id: A list with the devices which will be receiving a message
data: The dict data which will be send
collapse_key: A string to group messages, look at the documentation about it:
http://developer.android.com/google/gcm/gcm.html#request
"""
values = {
'registration_ids': regs_id,
'collapse_key': collapse_key,
'data': data
}
values = json.dumps(values)
headers = {
'UserAgent': "GCM-Server",
'Content-Type': 'application/json',
'Authorization': 'key=' + api_key,
}
response = requests.post(url="https://android.googleapis.com/gcm/send",
data=values,
headers=headers)
return response.content
|
// ... existing code ...
import requests
import json
// ... modified code ...
'Authorization': 'key=' + api_key,
}
response = requests.post(url="https://android.googleapis.com/gcm/send",
data=values,
headers=headers)
return response.content
// ... rest of the code ...
|
9b8ce2e352eebf320e5f498114f4de1aad77619a
|
src/main/java/com/elmakers/mine/bukkit/action/builtin/CheckBlockAction.java
|
src/main/java/com/elmakers/mine/bukkit/action/builtin/CheckBlockAction.java
|
package com.elmakers.mine.bukkit.action.builtin;
import com.elmakers.mine.bukkit.action.BaseSpellAction;
import com.elmakers.mine.bukkit.api.action.CastContext;
import com.elmakers.mine.bukkit.api.block.MaterialBrush;
import com.elmakers.mine.bukkit.api.spell.SpellResult;
import org.bukkit.block.Block;
public class CheckBlockAction extends BaseSpellAction {
@SuppressWarnings("deprecation")
@Override
public SpellResult perform(CastContext context) {
MaterialBrush brush = context.getBrush();
Block block = context.getTargetBlock();
if (brush != null && brush.isErase()) {
if (!context.hasBreakPermission(block)) {
return SpellResult.STOP;
}
} else {
if (!context.hasBuildPermission(block)) {
return SpellResult.STOP;
}
}
if (!context.isDestructible(block)) {
return SpellResult.STOP;
}
return SpellResult.CAST;
}
@Override
public boolean requiresTarget() {
return true;
}
}
|
package com.elmakers.mine.bukkit.action.builtin;
import com.elmakers.mine.bukkit.action.BaseSpellAction;
import com.elmakers.mine.bukkit.api.action.CastContext;
import com.elmakers.mine.bukkit.api.block.MaterialBrush;
import com.elmakers.mine.bukkit.api.spell.Spell;
import com.elmakers.mine.bukkit.api.spell.SpellResult;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.configuration.ConfigurationSection;
import java.util.Set;
public class CheckBlockAction extends BaseSpellAction {
private Set<Material> allowed;
@Override
public void initialize(Spell spell, ConfigurationSection parameters)
{
super.initialize(spell, parameters);
allowed = spell.getController().getMaterialSet(parameters.getString("allowed"));
}
@SuppressWarnings("deprecation")
@Override
public SpellResult perform(CastContext context) {
MaterialBrush brush = context.getBrush();
Block block = context.getTargetBlock();
if (allowed != null) {
if (!allowed.contains(block.getType())) return SpellResult.STOP;
} else {
if (brush != null && brush.isErase()) {
if (!context.hasBreakPermission(block)) {
return SpellResult.STOP;
}
} else {
if (!context.hasBuildPermission(block)) {
return SpellResult.STOP;
}
}
if (!context.isDestructible(block)) {
return SpellResult.STOP;
}
}
return SpellResult.CAST;
}
@Override
public boolean requiresTarget() {
return true;
}
}
|
Add "allowed" parameter to CheckBlock action
|
Add "allowed" parameter to CheckBlock action
|
Java
|
mit
|
elBukkit/MagicPlugin,elBukkit/MagicPlugin,elBukkit/MagicPlugin
|
java
|
## Code Before:
package com.elmakers.mine.bukkit.action.builtin;
import com.elmakers.mine.bukkit.action.BaseSpellAction;
import com.elmakers.mine.bukkit.api.action.CastContext;
import com.elmakers.mine.bukkit.api.block.MaterialBrush;
import com.elmakers.mine.bukkit.api.spell.SpellResult;
import org.bukkit.block.Block;
public class CheckBlockAction extends BaseSpellAction {
@SuppressWarnings("deprecation")
@Override
public SpellResult perform(CastContext context) {
MaterialBrush brush = context.getBrush();
Block block = context.getTargetBlock();
if (brush != null && brush.isErase()) {
if (!context.hasBreakPermission(block)) {
return SpellResult.STOP;
}
} else {
if (!context.hasBuildPermission(block)) {
return SpellResult.STOP;
}
}
if (!context.isDestructible(block)) {
return SpellResult.STOP;
}
return SpellResult.CAST;
}
@Override
public boolean requiresTarget() {
return true;
}
}
## Instruction:
Add "allowed" parameter to CheckBlock action
## Code After:
package com.elmakers.mine.bukkit.action.builtin;
import com.elmakers.mine.bukkit.action.BaseSpellAction;
import com.elmakers.mine.bukkit.api.action.CastContext;
import com.elmakers.mine.bukkit.api.block.MaterialBrush;
import com.elmakers.mine.bukkit.api.spell.Spell;
import com.elmakers.mine.bukkit.api.spell.SpellResult;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.configuration.ConfigurationSection;
import java.util.Set;
public class CheckBlockAction extends BaseSpellAction {
private Set<Material> allowed;
@Override
public void initialize(Spell spell, ConfigurationSection parameters)
{
super.initialize(spell, parameters);
allowed = spell.getController().getMaterialSet(parameters.getString("allowed"));
}
@SuppressWarnings("deprecation")
@Override
public SpellResult perform(CastContext context) {
MaterialBrush brush = context.getBrush();
Block block = context.getTargetBlock();
if (allowed != null) {
if (!allowed.contains(block.getType())) return SpellResult.STOP;
} else {
if (brush != null && brush.isErase()) {
if (!context.hasBreakPermission(block)) {
return SpellResult.STOP;
}
} else {
if (!context.hasBuildPermission(block)) {
return SpellResult.STOP;
}
}
if (!context.isDestructible(block)) {
return SpellResult.STOP;
}
}
return SpellResult.CAST;
}
@Override
public boolean requiresTarget() {
return true;
}
}
|
...
import com.elmakers.mine.bukkit.action.BaseSpellAction;
import com.elmakers.mine.bukkit.api.action.CastContext;
import com.elmakers.mine.bukkit.api.block.MaterialBrush;
import com.elmakers.mine.bukkit.api.spell.Spell;
import com.elmakers.mine.bukkit.api.spell.SpellResult;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.configuration.ConfigurationSection;
import java.util.Set;
public class CheckBlockAction extends BaseSpellAction {
private Set<Material> allowed;
@Override
public void initialize(Spell spell, ConfigurationSection parameters)
{
super.initialize(spell, parameters);
allowed = spell.getController().getMaterialSet(parameters.getString("allowed"));
}
@SuppressWarnings("deprecation")
@Override
public SpellResult perform(CastContext context) {
MaterialBrush brush = context.getBrush();
Block block = context.getTargetBlock();
if (allowed != null) {
if (!allowed.contains(block.getType())) return SpellResult.STOP;
} else {
if (brush != null && brush.isErase()) {
if (!context.hasBreakPermission(block)) {
return SpellResult.STOP;
}
} else {
if (!context.hasBuildPermission(block)) {
return SpellResult.STOP;
}
}
if (!context.isDestructible(block)) {
return SpellResult.STOP;
}
}
return SpellResult.CAST;
}
...
|
d84e8b60b0c619feaf529d4ab1eb53ef9e21aae5
|
lingcod/bookmarks/forms.py
|
lingcod/bookmarks/forms.py
|
from lingcod.features.forms import FeatureForm
from lingcod.bookmarks.models import Bookmark
from django import forms
class BookmarkForm(FeatureForm):
name = forms.CharField(label='Bookmark Name')
latitude = forms.FloatField(widget=forms.HiddenInput())
longitude = forms.FloatField(widget=forms.HiddenInput())
altitude = forms.FloatField(widget=forms.HiddenInput())
heading = forms.FloatField(widget=forms.HiddenInput())
tilt = forms.FloatField(widget=forms.HiddenInput())
roll = forms.FloatField(widget=forms.HiddenInput())
altitudeMode = forms.FloatField(widget=forms.HiddenInput())
publicstate = forms.CharField(widget=forms.HiddenInput())
ip = forms.CharField(widget=forms.HiddenInput())
class Meta(FeatureForm.Meta):
model = Bookmark
|
from lingcod.features.forms import FeatureForm
from lingcod.bookmarks.models import Bookmark
from django import forms
class BookmarkForm(FeatureForm):
name = forms.CharField(label='Bookmark Name')
latitude = forms.FloatField(widget=forms.HiddenInput())
longitude = forms.FloatField(widget=forms.HiddenInput())
altitude = forms.FloatField(widget=forms.HiddenInput())
heading = forms.FloatField(widget=forms.HiddenInput())
tilt = forms.FloatField(widget=forms.HiddenInput())
roll = forms.FloatField(widget=forms.HiddenInput())
altitudeMode = forms.FloatField(widget=forms.HiddenInput())
publicstate = forms.CharField(widget=forms.HiddenInput())
ip = forms.CharField(widget=forms.HiddenInput(), required=False)
class Meta(FeatureForm.Meta):
model = Bookmark
|
Allow IP to be blank in form
|
Allow IP to be blank in form
|
Python
|
bsd-3-clause
|
Ecotrust/madrona_addons,Ecotrust/madrona_addons
|
python
|
## Code Before:
from lingcod.features.forms import FeatureForm
from lingcod.bookmarks.models import Bookmark
from django import forms
class BookmarkForm(FeatureForm):
name = forms.CharField(label='Bookmark Name')
latitude = forms.FloatField(widget=forms.HiddenInput())
longitude = forms.FloatField(widget=forms.HiddenInput())
altitude = forms.FloatField(widget=forms.HiddenInput())
heading = forms.FloatField(widget=forms.HiddenInput())
tilt = forms.FloatField(widget=forms.HiddenInput())
roll = forms.FloatField(widget=forms.HiddenInput())
altitudeMode = forms.FloatField(widget=forms.HiddenInput())
publicstate = forms.CharField(widget=forms.HiddenInput())
ip = forms.CharField(widget=forms.HiddenInput())
class Meta(FeatureForm.Meta):
model = Bookmark
## Instruction:
Allow IP to be blank in form
## Code After:
from lingcod.features.forms import FeatureForm
from lingcod.bookmarks.models import Bookmark
from django import forms
class BookmarkForm(FeatureForm):
name = forms.CharField(label='Bookmark Name')
latitude = forms.FloatField(widget=forms.HiddenInput())
longitude = forms.FloatField(widget=forms.HiddenInput())
altitude = forms.FloatField(widget=forms.HiddenInput())
heading = forms.FloatField(widget=forms.HiddenInput())
tilt = forms.FloatField(widget=forms.HiddenInput())
roll = forms.FloatField(widget=forms.HiddenInput())
altitudeMode = forms.FloatField(widget=forms.HiddenInput())
publicstate = forms.CharField(widget=forms.HiddenInput())
ip = forms.CharField(widget=forms.HiddenInput(), required=False)
class Meta(FeatureForm.Meta):
model = Bookmark
|
// ... existing code ...
roll = forms.FloatField(widget=forms.HiddenInput())
altitudeMode = forms.FloatField(widget=forms.HiddenInput())
publicstate = forms.CharField(widget=forms.HiddenInput())
ip = forms.CharField(widget=forms.HiddenInput(), required=False)
class Meta(FeatureForm.Meta):
model = Bookmark
// ... rest of the code ...
|
ad3d815b16e22b44981b7817cd571f9866f89e9a
|
library/src/main/java/com/mapzen/android/MapzenMap.java
|
library/src/main/java/com/mapzen/android/MapzenMap.java
|
package com.mapzen.android;
import com.mapzen.tangram.MapController;
/**
* This is the main class of the Mapzen Android API and is the entry point for all methods related
* to the map. You cannot instantiate a {@link MapzenMap} object directly. Rather you must obtain
* one from {@link MapFragment#getMapAsync(MapView.OnMapReadyCallback)} or
* {@link MapView#getMapAsync(MapView.OnMapReadyCallback)}.
*/
public class MapzenMap {
private final MapController mapController;
/**
* Creates a new map based on the given {@link MapController}.
*/
MapzenMap(MapController mapController) {
this.mapController = mapController;
}
/**
* Provides access to the underlying Tangram {@link MapController}.
*/
public MapController getMapController() {
return mapController;
}
}
|
package com.mapzen.android;
import com.mapzen.tangram.MapController;
/**
* This is the main class of the Mapzen Android API and is the entry point for all methods related
* to the map. You cannot instantiate a {@link MapzenMap} object directly. Rather you must obtain
* one from {@link MapFragment#getMapAsync(OnMapReadyCallback)} or
* {@link MapView#getMapAsync(OnMapReadyCallback)}.
*/
public class MapzenMap {
private final MapController mapController;
/**
* Creates a new map based on the given {@link MapController}.
*/
MapzenMap(MapController mapController) {
this.mapController = mapController;
}
/**
* Provides access to the underlying Tangram {@link MapController}.
*/
public MapController getMapController() {
return mapController;
}
}
|
FIx broken links in Javadoc
|
FIx broken links in Javadoc
|
Java
|
apache-2.0
|
mapzen/android,mapzen/android
|
java
|
## Code Before:
package com.mapzen.android;
import com.mapzen.tangram.MapController;
/**
* This is the main class of the Mapzen Android API and is the entry point for all methods related
* to the map. You cannot instantiate a {@link MapzenMap} object directly. Rather you must obtain
* one from {@link MapFragment#getMapAsync(MapView.OnMapReadyCallback)} or
* {@link MapView#getMapAsync(MapView.OnMapReadyCallback)}.
*/
public class MapzenMap {
private final MapController mapController;
/**
* Creates a new map based on the given {@link MapController}.
*/
MapzenMap(MapController mapController) {
this.mapController = mapController;
}
/**
* Provides access to the underlying Tangram {@link MapController}.
*/
public MapController getMapController() {
return mapController;
}
}
## Instruction:
FIx broken links in Javadoc
## Code After:
package com.mapzen.android;
import com.mapzen.tangram.MapController;
/**
* This is the main class of the Mapzen Android API and is the entry point for all methods related
* to the map. You cannot instantiate a {@link MapzenMap} object directly. Rather you must obtain
* one from {@link MapFragment#getMapAsync(OnMapReadyCallback)} or
* {@link MapView#getMapAsync(OnMapReadyCallback)}.
*/
public class MapzenMap {
private final MapController mapController;
/**
* Creates a new map based on the given {@link MapController}.
*/
MapzenMap(MapController mapController) {
this.mapController = mapController;
}
/**
* Provides access to the underlying Tangram {@link MapController}.
*/
public MapController getMapController() {
return mapController;
}
}
|
...
/**
* This is the main class of the Mapzen Android API and is the entry point for all methods related
* to the map. You cannot instantiate a {@link MapzenMap} object directly. Rather you must obtain
* one from {@link MapFragment#getMapAsync(OnMapReadyCallback)} or
* {@link MapView#getMapAsync(OnMapReadyCallback)}.
*/
public class MapzenMap {
private final MapController mapController;
...
|
3a12d545ef22db37d4d26b0a75af4dc4348afd9a
|
setup.py
|
setup.py
|
from setuptools import setup, find_packages
VERSION = '3.0.1'
setup(
name='django-node',
version=VERSION,
packages=find_packages(exclude=('tests', 'example',)),
package_data={
'django_node': [
'node_server.js',
'package.json',
],
},
install_requires=[
'django',
'requests>=2.5.1',
],
description='Bindings and utils for integrating Node.js and NPM into a Django application',
long_description='Documentation at https://github.com/markfinger/django-node',
author='Mark Finger',
author_email='[email protected]',
url='https://github.com/markfinger/django-node',
)
|
from setuptools import setup, find_packages
VERSION = '3.0.1'
setup(
name='django-node',
version=VERSION,
packages=find_packages(exclude=('tests', 'example',)),
package_data={
'django_node': [
'node_server.js',
'services/echo.js',
'package.json',
],
},
install_requires=[
'django',
'requests>=2.5.1',
],
description='Bindings and utils for integrating Node.js and NPM into a Django application',
long_description='Documentation at https://github.com/markfinger/django-node',
author='Mark Finger',
author_email='[email protected]',
url='https://github.com/markfinger/django-node',
)
|
Include required echo service in package
|
Include required echo service in package
|
Python
|
mit
|
markfinger/django-node,markfinger/django-node
|
python
|
## Code Before:
from setuptools import setup, find_packages
VERSION = '3.0.1'
setup(
name='django-node',
version=VERSION,
packages=find_packages(exclude=('tests', 'example',)),
package_data={
'django_node': [
'node_server.js',
'package.json',
],
},
install_requires=[
'django',
'requests>=2.5.1',
],
description='Bindings and utils for integrating Node.js and NPM into a Django application',
long_description='Documentation at https://github.com/markfinger/django-node',
author='Mark Finger',
author_email='[email protected]',
url='https://github.com/markfinger/django-node',
)
## Instruction:
Include required echo service in package
## Code After:
from setuptools import setup, find_packages
VERSION = '3.0.1'
setup(
name='django-node',
version=VERSION,
packages=find_packages(exclude=('tests', 'example',)),
package_data={
'django_node': [
'node_server.js',
'services/echo.js',
'package.json',
],
},
install_requires=[
'django',
'requests>=2.5.1',
],
description='Bindings and utils for integrating Node.js and NPM into a Django application',
long_description='Documentation at https://github.com/markfinger/django-node',
author='Mark Finger',
author_email='[email protected]',
url='https://github.com/markfinger/django-node',
)
|
# ... existing code ...
package_data={
'django_node': [
'node_server.js',
'services/echo.js',
'package.json',
],
},
# ... rest of the code ...
|
4961967ab70fc33361954314553613fe6e8b4851
|
pyV2S.py
|
pyV2S.py
|
import os
from file_manager.vhdl_reader import Vhdl_reader
from decorator.pdfdrawer import PdfDrawer
import sys
print 'Number of arguments:', len(sys.argv), 'arguments.'
print 'Argument List:', str(sys.argv)
filename = str(sys.argv[1])
reader = Vhdl_reader(filename)
drawer = PdfDrawer("%s.pdf" % reader.entity.name, reader.entity)
|
import os
from file_manager.vhdl_reader import Vhdl_reader
from decorator.pdfdrawer import PdfDrawer
import sys
try:
filename = str(sys.argv[1])
except:
filename = "datas/test_files/demo.vhd"
reader = Vhdl_reader(filename)
drawer = PdfDrawer("%s.pdf" % reader.entity.name, reader.entity)
print "The schematic was generated and named : %s.pdf" % reader.entity.name
|
Add a demo mode : if no vhdl file is given the demo one is used datas/test_files/demo.vhd
|
Add a demo mode :
if no vhdl file is given the demo one is used
datas/test_files/demo.vhd
|
Python
|
bsd-2-clause
|
LaurentCabaret/pyVhdl2Sch,LaurentCabaret/pyVhdl2Sch
|
python
|
## Code Before:
import os
from file_manager.vhdl_reader import Vhdl_reader
from decorator.pdfdrawer import PdfDrawer
import sys
print 'Number of arguments:', len(sys.argv), 'arguments.'
print 'Argument List:', str(sys.argv)
filename = str(sys.argv[1])
reader = Vhdl_reader(filename)
drawer = PdfDrawer("%s.pdf" % reader.entity.name, reader.entity)
## Instruction:
Add a demo mode :
if no vhdl file is given the demo one is used
datas/test_files/demo.vhd
## Code After:
import os
from file_manager.vhdl_reader import Vhdl_reader
from decorator.pdfdrawer import PdfDrawer
import sys
try:
filename = str(sys.argv[1])
except:
filename = "datas/test_files/demo.vhd"
reader = Vhdl_reader(filename)
drawer = PdfDrawer("%s.pdf" % reader.entity.name, reader.entity)
print "The schematic was generated and named : %s.pdf" % reader.entity.name
|
...
import sys
try:
filename = str(sys.argv[1])
except:
filename = "datas/test_files/demo.vhd"
reader = Vhdl_reader(filename)
drawer = PdfDrawer("%s.pdf" % reader.entity.name, reader.entity)
print "The schematic was generated and named : %s.pdf" % reader.entity.name
...
|
43fe84036738f6fe0743651b12ec14b44c6f55cd
|
src/main/java/me/prettyprint/cassandra/service/ExampleClient.java
|
src/main/java/me/prettyprint/cassandra/service/ExampleClient.java
|
package me.prettyprint.cassandra.service;
import static me.prettyprint.cassandra.utils.StringUtils.bytes;
import static me.prettyprint.cassandra.utils.StringUtils.string;
import org.apache.cassandra.service.Column;
import org.apache.cassandra.service.ColumnPath;
/**
* Example client that uses the cassandra hector client.
*
* @author Ran Tavory ([email protected])
*
*/
public class ExampleClient {
public static void main(String[] args) throws IllegalStateException, PoolExhaustedException, Exception {
CassandraClientPool pool = CassandraClientPoolFactory.INSTANCE.get();
CassandraClient client = pool.borrowClient("tush", 9160);
try {
Keyspace keyspace = client.getKeyspace("Keyspace1");
ColumnPath columnPath = new ColumnPath("Standard1", null, bytes("column-name"));
// insert
keyspace.insert("key", columnPath, bytes("value"));
// read
Column col = keyspace.getColumn("key", columnPath);
System.out.println("Read from cassandra: " + string(col.getValue()));
} finally {
// return client to pool. do it in a finally block to make sure it's executed
pool.releaseClient(client);
}
}
}
|
package me.prettyprint.cassandra.service;
import static me.prettyprint.cassandra.utils.StringUtils.bytes;
import static me.prettyprint.cassandra.utils.StringUtils.string;
import org.apache.cassandra.service.Column;
import org.apache.cassandra.service.ColumnPath;
/**
* Example client that uses the cassandra hector client.
*
* @author Ran Tavory ([email protected])
*
*/
public class ExampleClient {
public static void main(String[] args) throws IllegalStateException, PoolExhaustedException, Exception {
CassandraClientPool pool = CassandraClientPoolFactory.INSTANCE.get();
CassandraClient client = pool.borrowClient("tush", 9160);
// A load balanced version would look like this:
// CassandraClient client = pool.borrowClient(new String[] {"cas1:9160", "cas2:9160", "cas3:9160"});
try {
Keyspace keyspace = client.getKeyspace("Keyspace1");
ColumnPath columnPath = new ColumnPath("Standard1", null, bytes("column-name"));
// insert
keyspace.insert("key", columnPath, bytes("value"));
// read
Column col = keyspace.getColumn("key", columnPath);
System.out.println("Read from cassandra: " + string(col.getValue()));
} finally {
// return client to pool. do it in a finally block to make sure it's executed
pool.releaseClient(client);
}
}
}
|
Add a load balanced client example
|
Add a load balanced client example
|
Java
|
mit
|
koa/hector,Ursula/hector,rantav/hector,hector-client/hector,hector-client/hector,Ursula/hector,1and1/hector,apigee/hector,normanmaurer/hector
|
java
|
## Code Before:
package me.prettyprint.cassandra.service;
import static me.prettyprint.cassandra.utils.StringUtils.bytes;
import static me.prettyprint.cassandra.utils.StringUtils.string;
import org.apache.cassandra.service.Column;
import org.apache.cassandra.service.ColumnPath;
/**
* Example client that uses the cassandra hector client.
*
* @author Ran Tavory ([email protected])
*
*/
public class ExampleClient {
public static void main(String[] args) throws IllegalStateException, PoolExhaustedException, Exception {
CassandraClientPool pool = CassandraClientPoolFactory.INSTANCE.get();
CassandraClient client = pool.borrowClient("tush", 9160);
try {
Keyspace keyspace = client.getKeyspace("Keyspace1");
ColumnPath columnPath = new ColumnPath("Standard1", null, bytes("column-name"));
// insert
keyspace.insert("key", columnPath, bytes("value"));
// read
Column col = keyspace.getColumn("key", columnPath);
System.out.println("Read from cassandra: " + string(col.getValue()));
} finally {
// return client to pool. do it in a finally block to make sure it's executed
pool.releaseClient(client);
}
}
}
## Instruction:
Add a load balanced client example
## Code After:
package me.prettyprint.cassandra.service;
import static me.prettyprint.cassandra.utils.StringUtils.bytes;
import static me.prettyprint.cassandra.utils.StringUtils.string;
import org.apache.cassandra.service.Column;
import org.apache.cassandra.service.ColumnPath;
/**
* Example client that uses the cassandra hector client.
*
* @author Ran Tavory ([email protected])
*
*/
public class ExampleClient {
public static void main(String[] args) throws IllegalStateException, PoolExhaustedException, Exception {
CassandraClientPool pool = CassandraClientPoolFactory.INSTANCE.get();
CassandraClient client = pool.borrowClient("tush", 9160);
// A load balanced version would look like this:
// CassandraClient client = pool.borrowClient(new String[] {"cas1:9160", "cas2:9160", "cas3:9160"});
try {
Keyspace keyspace = client.getKeyspace("Keyspace1");
ColumnPath columnPath = new ColumnPath("Standard1", null, bytes("column-name"));
// insert
keyspace.insert("key", columnPath, bytes("value"));
// read
Column col = keyspace.getColumn("key", columnPath);
System.out.println("Read from cassandra: " + string(col.getValue()));
} finally {
// return client to pool. do it in a finally block to make sure it's executed
pool.releaseClient(client);
}
}
}
|
# ... existing code ...
public static void main(String[] args) throws IllegalStateException, PoolExhaustedException, Exception {
CassandraClientPool pool = CassandraClientPoolFactory.INSTANCE.get();
CassandraClient client = pool.borrowClient("tush", 9160);
// A load balanced version would look like this:
// CassandraClient client = pool.borrowClient(new String[] {"cas1:9160", "cas2:9160", "cas3:9160"});
try {
Keyspace keyspace = client.getKeyspace("Keyspace1");
ColumnPath columnPath = new ColumnPath("Standard1", null, bytes("column-name"));
# ... rest of the code ...
|
0b062eb9d2908410674c2751bbcee5b9df464732
|
src/sensors/lmsensor.h
|
src/sensors/lmsensor.h
|
/**
*
* Hans Karlsson
**/
class SensorSensor : public Sensor
{
Q_OBJECT
public:
SensorSensor(int interval, char tempUnit);
~SensorSensor();
void update();
private:
K3ShellProcess ksp;
QString extraParams;
QMap<QString, QString> sensorMap;
#ifdef __FreeBSD__
QMap<QString, QString> sensorMapBSD;
#endif
QString sensorResult;
private slots:
void receivedStdout(K3Process *, char *buffer, int);
void processExited(K3Process *);
};
#endif // LMSENSOR_H
|
/**
*
* Hans Karlsson
**/
class SensorSensor : public Sensor
{
Q_OBJECT
public:
SensorSensor(int interval, char tempUnit);
~SensorSensor();
void update();
private:
K3ShellProcess ksp;
QString extraParams;
QMap<QString, QString> sensorMap;
#if defined(__FreeBSD__) || defined(Q_OS_NETBSD)
QMap<QString, QString> sensorMapBSD;
#endif
QString sensorResult;
private slots:
void receivedStdout(K3Process *, char *buffer, int);
void processExited(K3Process *);
};
#endif // LMSENSOR_H
|
Fix knode superkaramba compilation on NetBSD. Patch by Mark Davies. BUG: 154730
|
Fix knode superkaramba compilation on NetBSD.
Patch by Mark Davies.
BUG: 154730
svn path=/trunk/KDE/kdeutils/superkaramba/; revision=753733
|
C
|
lgpl-2.1
|
KDE/superkaramba,KDE/superkaramba,KDE/superkaramba
|
c
|
## Code Before:
/**
*
* Hans Karlsson
**/
class SensorSensor : public Sensor
{
Q_OBJECT
public:
SensorSensor(int interval, char tempUnit);
~SensorSensor();
void update();
private:
K3ShellProcess ksp;
QString extraParams;
QMap<QString, QString> sensorMap;
#ifdef __FreeBSD__
QMap<QString, QString> sensorMapBSD;
#endif
QString sensorResult;
private slots:
void receivedStdout(K3Process *, char *buffer, int);
void processExited(K3Process *);
};
#endif // LMSENSOR_H
## Instruction:
Fix knode superkaramba compilation on NetBSD.
Patch by Mark Davies.
BUG: 154730
svn path=/trunk/KDE/kdeutils/superkaramba/; revision=753733
## Code After:
/**
*
* Hans Karlsson
**/
class SensorSensor : public Sensor
{
Q_OBJECT
public:
SensorSensor(int interval, char tempUnit);
~SensorSensor();
void update();
private:
K3ShellProcess ksp;
QString extraParams;
QMap<QString, QString> sensorMap;
#if defined(__FreeBSD__) || defined(Q_OS_NETBSD)
QMap<QString, QString> sensorMapBSD;
#endif
QString sensorResult;
private slots:
void receivedStdout(K3Process *, char *buffer, int);
void processExited(K3Process *);
};
#endif // LMSENSOR_H
|
// ... existing code ...
QString extraParams;
QMap<QString, QString> sensorMap;
#if defined(__FreeBSD__) || defined(Q_OS_NETBSD)
QMap<QString, QString> sensorMapBSD;
#endif
QString sensorResult;
// ... rest of the code ...
|
3a321900d4205ba7819fdc421a1efa3c8724d6b0
|
Opcodes/ftest.c
|
Opcodes/ftest.c
|
void tanhtable(FUNC *ftp, FGDATA *ff)
{
MYFLT *fp = ftp->ftable;
MYFLT range = ff->e.p[5];
double step = (double)range/(ff->e.p[3]);
int i;
double x;
for (i=0, x=FL(0.0); i<ff->e.p[3]; i++, x+=step)
*fp++ = (MYFLT)tanh(x);
}
static void gentune(FUNC *ftp, FGDATA *ff) /* Gab 1/3/2005 */
{
int j;
int notenum;
int grade;
int numgrades;
int basekeymidi;
MYFLT basefreq, factor,interval;
MYFLT *fp = ftp->ftable, *pp = &(ff->e.p[5]);
int nvals = ff->e.pcnt - 4;
numgrades = (int) *pp++;
interval = *pp++;
basefreq = *pp++;
basekeymidi= (int) *pp++;
nvals = ff->flenp1 - 1;
for (j =0; j < nvals; j++) {
notenum = j;
if (notenum < basekeymidi) {
notenum = basekeymidi - notenum;
grade = (numgrades-(notenum % numgrades)) % numgrades;
factor = - (MYFLT)(int) ((notenum+numgrades-1) / numgrades) ;
}
else {
notenum = notenum - basekeymidi;
grade = notenum % numgrades;
factor = (MYFLT)(int) (notenum / numgrades);
}
factor = (MYFLT)pow((double)interval, (double)factor);
fp[j] = pp[grade] * factor * basefreq;
}
}
static NGFENS localfgens[] = {
{ "tanh", (void(*)(void))tanhtable},
{ "cpstune", (void(*)(void))gentune},
{ NULL, NULL}
};
#define S sizeof
static OENTRY localops[] = {};
FLINKAGE
|
void tanhtable(FUNC *ftp, FGDATA *ff)
{
MYFLT *fp = ftp->ftable;
MYFLT range = ff->e.p[5];
double step = (double)range/(ff->e.p[3]);
int i;
double x;
for (i=0, x=FL(0.0); i<ff->e.p[3]; i++, x+=step)
*fp++ = (MYFLT)tanh(x);
}
static NGFENS localfgens[] = {
{ "tanh", (void(*)(void))tanhtable},
{ NULL, NULL}
};
#define S sizeof
static OENTRY localops[] = {};
FLINKAGE
|
Remove gen from loadable code
|
Remove gen from loadable code
|
C
|
lgpl-2.1
|
audiokit/csound,nikhilsinghmus/csound,mcanthony/csound,audiokit/csound,nikhilsinghmus/csound,audiokit/csound,max-ilse/csound,audiokit/csound,audiokit/csound,audiokit/csound,audiokit/csound,nikhilsinghmus/csound,mcanthony/csound,nikhilsinghmus/csound,Angeldude/csound,max-ilse/csound,nikhilsinghmus/csound,Angeldude/csound,nikhilsinghmus/csound,Angeldude/csound,max-ilse/csound,nikhilsinghmus/csound,mcanthony/csound,Angeldude/csound,iver56/csound,nikhilsinghmus/csound,iver56/csound,iver56/csound,iver56/csound,max-ilse/csound,Angeldude/csound,mcanthony/csound,nikhilsinghmus/csound,mcanthony/csound,max-ilse/csound,iver56/csound,max-ilse/csound,iver56/csound,audiokit/csound,mcanthony/csound,Angeldude/csound,Angeldude/csound,iver56/csound,mcanthony/csound,mcanthony/csound,audiokit/csound,iver56/csound,Angeldude/csound,Angeldude/csound,mcanthony/csound,iver56/csound,audiokit/csound,max-ilse/csound,mcanthony/csound,max-ilse/csound,nikhilsinghmus/csound,max-ilse/csound,iver56/csound,Angeldude/csound,max-ilse/csound
|
c
|
## Code Before:
void tanhtable(FUNC *ftp, FGDATA *ff)
{
MYFLT *fp = ftp->ftable;
MYFLT range = ff->e.p[5];
double step = (double)range/(ff->e.p[3]);
int i;
double x;
for (i=0, x=FL(0.0); i<ff->e.p[3]; i++, x+=step)
*fp++ = (MYFLT)tanh(x);
}
static void gentune(FUNC *ftp, FGDATA *ff) /* Gab 1/3/2005 */
{
int j;
int notenum;
int grade;
int numgrades;
int basekeymidi;
MYFLT basefreq, factor,interval;
MYFLT *fp = ftp->ftable, *pp = &(ff->e.p[5]);
int nvals = ff->e.pcnt - 4;
numgrades = (int) *pp++;
interval = *pp++;
basefreq = *pp++;
basekeymidi= (int) *pp++;
nvals = ff->flenp1 - 1;
for (j =0; j < nvals; j++) {
notenum = j;
if (notenum < basekeymidi) {
notenum = basekeymidi - notenum;
grade = (numgrades-(notenum % numgrades)) % numgrades;
factor = - (MYFLT)(int) ((notenum+numgrades-1) / numgrades) ;
}
else {
notenum = notenum - basekeymidi;
grade = notenum % numgrades;
factor = (MYFLT)(int) (notenum / numgrades);
}
factor = (MYFLT)pow((double)interval, (double)factor);
fp[j] = pp[grade] * factor * basefreq;
}
}
static NGFENS localfgens[] = {
{ "tanh", (void(*)(void))tanhtable},
{ "cpstune", (void(*)(void))gentune},
{ NULL, NULL}
};
#define S sizeof
static OENTRY localops[] = {};
FLINKAGE
## Instruction:
Remove gen from loadable code
## Code After:
void tanhtable(FUNC *ftp, FGDATA *ff)
{
MYFLT *fp = ftp->ftable;
MYFLT range = ff->e.p[5];
double step = (double)range/(ff->e.p[3]);
int i;
double x;
for (i=0, x=FL(0.0); i<ff->e.p[3]; i++, x+=step)
*fp++ = (MYFLT)tanh(x);
}
static NGFENS localfgens[] = {
{ "tanh", (void(*)(void))tanhtable},
{ NULL, NULL}
};
#define S sizeof
static OENTRY localops[] = {};
FLINKAGE
|
...
*fp++ = (MYFLT)tanh(x);
}
static NGFENS localfgens[] = {
{ "tanh", (void(*)(void))tanhtable},
{ NULL, NULL}
};
...
|
105d46937babb7a43901d8238fb9cc0a7b00c8c9
|
lyman/tools/commandline.py
|
lyman/tools/commandline.py
|
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("-subjects", nargs="*", dest="subjects",
help=("list of subject ids, name of file in lyman "
"directory, or full path to text file with "
"subject ids"))
parser.add_argument("-plugin", default="multiproc",
choices=["linear", "multiproc",
"ipython", "torque", "sge"],
help="worklow execution plugin")
parser.add_argument("-nprocs", default=4, type=int,
help="number of MultiProc processes to use")
parser.add_argument("-queue", help="which queue for PBS/SGE execution")
parser.add_argument("-dontrun", action="store_true",
help="don't actually execute the workflows")
|
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("-subjects", nargs="*", dest="subjects",
help=("list of subject ids, name of file in lyman "
"directory, or full path to text file with "
"subject ids"))
parser.add_argument("-plugin", default="multiproc",
choices=["linear", "multiproc", "ipython",
"torque", "sge", "slurm"],
help="worklow execution plugin")
parser.add_argument("-nprocs", default=4, type=int,
help="number of MultiProc processes to use")
parser.add_argument("-queue", help="which queue for PBS/SGE execution")
parser.add_argument("-dontrun", action="store_true",
help="don't actually execute the workflows")
|
Add slurm to command line plugin choices
|
Add slurm to command line plugin choices
|
Python
|
bsd-3-clause
|
mwaskom/lyman,tuqc/lyman,kastman/lyman
|
python
|
## Code Before:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("-subjects", nargs="*", dest="subjects",
help=("list of subject ids, name of file in lyman "
"directory, or full path to text file with "
"subject ids"))
parser.add_argument("-plugin", default="multiproc",
choices=["linear", "multiproc",
"ipython", "torque", "sge"],
help="worklow execution plugin")
parser.add_argument("-nprocs", default=4, type=int,
help="number of MultiProc processes to use")
parser.add_argument("-queue", help="which queue for PBS/SGE execution")
parser.add_argument("-dontrun", action="store_true",
help="don't actually execute the workflows")
## Instruction:
Add slurm to command line plugin choices
## Code After:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("-subjects", nargs="*", dest="subjects",
help=("list of subject ids, name of file in lyman "
"directory, or full path to text file with "
"subject ids"))
parser.add_argument("-plugin", default="multiproc",
choices=["linear", "multiproc", "ipython",
"torque", "sge", "slurm"],
help="worklow execution plugin")
parser.add_argument("-nprocs", default=4, type=int,
help="number of MultiProc processes to use")
parser.add_argument("-queue", help="which queue for PBS/SGE execution")
parser.add_argument("-dontrun", action="store_true",
help="don't actually execute the workflows")
|
// ... existing code ...
"directory, or full path to text file with "
"subject ids"))
parser.add_argument("-plugin", default="multiproc",
choices=["linear", "multiproc", "ipython",
"torque", "sge", "slurm"],
help="worklow execution plugin")
parser.add_argument("-nprocs", default=4, type=int,
help="number of MultiProc processes to use")
// ... rest of the code ...
|
2b05a59b09e72f263761dae2feac360f5abd1f82
|
promgen/__init__.py
|
promgen/__init__.py
|
default_app_config = 'promgen.apps.PromgenConfig'
import logging
logging.basicConfig(level=logging.DEBUG)
|
default_app_config = 'promgen.apps.PromgenConfig'
|
Remove some debug logging config
|
Remove some debug logging config
|
Python
|
mit
|
kfdm/promgen,kfdm/promgen,kfdm/promgen,kfdm/promgen
|
python
|
## Code Before:
default_app_config = 'promgen.apps.PromgenConfig'
import logging
logging.basicConfig(level=logging.DEBUG)
## Instruction:
Remove some debug logging config
## Code After:
default_app_config = 'promgen.apps.PromgenConfig'
|
# ... existing code ...
default_app_config = 'promgen.apps.PromgenConfig'
# ... rest of the code ...
|
bec268ef554e6f30c2cecd52ecddcafc34c5b0db
|
tutorials/cmake_python_wrapper/v1/python/foo/__init__.py
|
tutorials/cmake_python_wrapper/v1/python/foo/__init__.py
|
import ctypes
import numpy as np
import os
__all__ = ['square']
lib = ctypes.cdll.LoadLibrary("libfoo.so")
lib.square.restype = ctypes.c_int
lib.square.argtypes = [ctypes.c_int]
def square(value):
"""
Parameters
----------
value: int
Returns
--------
value square
"""
return lib.square(value)
|
import ctypes
import numpy as np
import os
import sys
__all__ = ['square']
_path = os.path.dirname(__file__)
libname = None
if sys.platform.startswith('linux'):
libname = 'libfoo.so'
elif sys.platform == 'darwin':
libname = 'libfoo.dylib'
elif sys.platform.startswith('win'):
libname = 'foo.dll'
if libname ==None:
print("Unknow platform", sys.platform)
else:
lib = ctypes.CDLL(libname)
lib.square.restype = ctypes.c_int
lib.square.argtypes = [ctypes.c_int]
def square(value):
"""
Parameters
----------
value: int
Returns
--------
value square
"""
return lib.square(value)
|
Change to cmake to 3.4 and test sys.platform to choose lib extension to resolve import error on MacOSX
|
Change to cmake to 3.4 and test sys.platform to choose lib extension to resolve import error on MacOSX
|
Python
|
bsd-3-clause
|
gammapy/PyGamma15,gammapy/2015-MPIK-Workshop,gammapy/2015-MPIK-Workshop,gammapy/PyGamma15,gammapy/PyGamma15,gammapy/2015-MPIK-Workshop
|
python
|
## Code Before:
import ctypes
import numpy as np
import os
__all__ = ['square']
lib = ctypes.cdll.LoadLibrary("libfoo.so")
lib.square.restype = ctypes.c_int
lib.square.argtypes = [ctypes.c_int]
def square(value):
"""
Parameters
----------
value: int
Returns
--------
value square
"""
return lib.square(value)
## Instruction:
Change to cmake to 3.4 and test sys.platform to choose lib extension to resolve import error on MacOSX
## Code After:
import ctypes
import numpy as np
import os
import sys
__all__ = ['square']
_path = os.path.dirname(__file__)
libname = None
if sys.platform.startswith('linux'):
libname = 'libfoo.so'
elif sys.platform == 'darwin':
libname = 'libfoo.dylib'
elif sys.platform.startswith('win'):
libname = 'foo.dll'
if libname ==None:
print("Unknow platform", sys.platform)
else:
lib = ctypes.CDLL(libname)
lib.square.restype = ctypes.c_int
lib.square.argtypes = [ctypes.c_int]
def square(value):
"""
Parameters
----------
value: int
Returns
--------
value square
"""
return lib.square(value)
|
...
import ctypes
import numpy as np
import os
import sys
__all__ = ['square']
_path = os.path.dirname(__file__)
libname = None
if sys.platform.startswith('linux'):
libname = 'libfoo.so'
elif sys.platform == 'darwin':
libname = 'libfoo.dylib'
elif sys.platform.startswith('win'):
libname = 'foo.dll'
if libname ==None:
print("Unknow platform", sys.platform)
else:
lib = ctypes.CDLL(libname)
lib.square.restype = ctypes.c_int
lib.square.argtypes = [ctypes.c_int]
def square(value):
"""
Parameters
----------
value: int
Returns
--------
value square
"""
return lib.square(value)
...
|
9317d20883bfd4bf9d37bad5f344a82b4131529c
|
json-serde/src/main/java/org/openx/data/jsonserde/objectinspector/primitive/JavaStringJsonObjectInspector.java
|
json-serde/src/main/java/org/openx/data/jsonserde/objectinspector/primitive/JavaStringJsonObjectInspector.java
|
package org.openx.data.jsonserde.objectinspector.primitive;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.AbstractPrimitiveJavaObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorUtils;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.SettableStringObjectInspector;
import org.apache.hadoop.io.Text;
import org.apache.log4j.Logger;
public class JavaStringJsonObjectInspector extends AbstractPrimitiveJavaObjectInspector
implements
SettableStringObjectInspector {
Logger logger = Logger.getLogger(JavaStringJsonObjectInspector.class);
public JavaStringJsonObjectInspector() {
super(PrimitiveObjectInspectorUtils.stringTypeEntry);
}
@Override
public Text getPrimitiveWritableObject(Object o) {
return o == null ? null : new Text(((String) o.toString()));
}
@Override
public String getPrimitiveJavaObject(Object o) {
return o == null ? null : o.toString();
}
@Override
public Object create(Text value) {
return value == null ? null : value.toString();
}
@Override
public Object set(Object o, Text value) {
return value == null ? null : value.toString();
}
@Override
public Object create(String value) {
return value;
}
@Override
public Object set(Object o, String value) {
return value;
}
}
|
package org.openx.data.jsonserde.objectinspector.primitive;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.AbstractPrimitiveJavaObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorUtils;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.SettableStringObjectInspector;
import org.apache.hadoop.io.Text;
import org.apache.log4j.Logger;
public class JavaStringJsonObjectInspector extends AbstractPrimitiveJavaObjectInspector
implements
SettableStringObjectInspector {
Logger logger = Logger.getLogger(JavaStringJsonObjectInspector.class);
public JavaStringJsonObjectInspector() {
super(TypeEntryShim.stringType);
}
@Override
public Text getPrimitiveWritableObject(Object o) {
return o == null ? null : new Text(((String) o.toString()));
}
@Override
public String getPrimitiveJavaObject(Object o) {
return o == null ? null : o.toString();
}
@Override
public Object create(Text value) {
return value == null ? null : value.toString();
}
@Override
public Object set(Object o, Text value) {
return value == null ? null : value.toString();
}
@Override
public Object create(String value) {
return value;
}
@Override
public Object set(Object o, String value) {
return value;
}
}
|
Fix to work with Hive13
|
Fix to work with Hive13
Reviewers: jeff, JamesGreenhill
Reviewed By: JamesGreenhill
Differential Revision: http://phabricator.local.disqus.net/D13528
|
Java
|
bsd-3-clause
|
disqus/Hive-JSON-Serde
|
java
|
## Code Before:
package org.openx.data.jsonserde.objectinspector.primitive;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.AbstractPrimitiveJavaObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorUtils;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.SettableStringObjectInspector;
import org.apache.hadoop.io.Text;
import org.apache.log4j.Logger;
public class JavaStringJsonObjectInspector extends AbstractPrimitiveJavaObjectInspector
implements
SettableStringObjectInspector {
Logger logger = Logger.getLogger(JavaStringJsonObjectInspector.class);
public JavaStringJsonObjectInspector() {
super(PrimitiveObjectInspectorUtils.stringTypeEntry);
}
@Override
public Text getPrimitiveWritableObject(Object o) {
return o == null ? null : new Text(((String) o.toString()));
}
@Override
public String getPrimitiveJavaObject(Object o) {
return o == null ? null : o.toString();
}
@Override
public Object create(Text value) {
return value == null ? null : value.toString();
}
@Override
public Object set(Object o, Text value) {
return value == null ? null : value.toString();
}
@Override
public Object create(String value) {
return value;
}
@Override
public Object set(Object o, String value) {
return value;
}
}
## Instruction:
Fix to work with Hive13
Reviewers: jeff, JamesGreenhill
Reviewed By: JamesGreenhill
Differential Revision: http://phabricator.local.disqus.net/D13528
## Code After:
package org.openx.data.jsonserde.objectinspector.primitive;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.AbstractPrimitiveJavaObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorUtils;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.SettableStringObjectInspector;
import org.apache.hadoop.io.Text;
import org.apache.log4j.Logger;
public class JavaStringJsonObjectInspector extends AbstractPrimitiveJavaObjectInspector
implements
SettableStringObjectInspector {
Logger logger = Logger.getLogger(JavaStringJsonObjectInspector.class);
public JavaStringJsonObjectInspector() {
super(TypeEntryShim.stringType);
}
@Override
public Text getPrimitiveWritableObject(Object o) {
return o == null ? null : new Text(((String) o.toString()));
}
@Override
public String getPrimitiveJavaObject(Object o) {
return o == null ? null : o.toString();
}
@Override
public Object create(Text value) {
return value == null ? null : value.toString();
}
@Override
public Object set(Object o, Text value) {
return value == null ? null : value.toString();
}
@Override
public Object create(String value) {
return value;
}
@Override
public Object set(Object o, String value) {
return value;
}
}
|
# ... existing code ...
Logger logger = Logger.getLogger(JavaStringJsonObjectInspector.class);
public JavaStringJsonObjectInspector() {
super(TypeEntryShim.stringType);
}
@Override
# ... rest of the code ...
|
1acb0e5db755b0d4cc389ed32f740d7e65218a5e
|
celestial/views.py
|
celestial/views.py
|
from django.views.generic import ListView, DetailView
from .models import Planet, SolarSystem
class SystemMixin(object):
model = SolarSystem
def get_queryset(self):
return super(SystemMixin, self).get_queryset().filter(radius__isnull=False)
class PlanetMixin(object):
model = Planet
def get_queryset(self):
return super(PlanetMixin, self).get_queryset().filter(
solar_system__radius__isnull=False,
radius__isnull=False)
class SystemList(SystemMixin, ListView):
pass
class SystemDetail(SystemMixin, DetailView):
def get_context_data(self, **kwargs):
data = super(SystemDetail, self).get_context_data(**kwargs)
data.update({'planets': Planet.objects.filter(solar_system=self.object, radius__isnull=False)})
return data
class PlanetList(PlanetMixin, ListView):
pass
class PlanetDetail(PlanetMixin, DetailView):
pass
|
from django.views.generic import ListView, DetailView
from .models import Planet, SolarSystem
class SystemMixin(object):
model = SolarSystem
def get_queryset(self):
return super(SystemMixin, self).get_queryset().filter(radius__isnull=False)
class PlanetMixin(object):
model = Planet
def get_queryset(self):
return super(PlanetMixin, self).get_queryset().filter(
solar_system__radius__isnull=False,
radius__isnull=False)
class SystemList(SystemMixin, ListView):
pass
class SystemDetail(SystemMixin, DetailView):
def get_context_data(self, **kwargs):
data = super(SystemDetail, self).get_context_data(**kwargs)
data.update({'planets': Planet.objects.filter(solar_system=self.object, radius__isnull=False).order_by('semi_major_axis')})
return data
class PlanetList(PlanetMixin, ListView):
pass
class PlanetDetail(PlanetMixin, DetailView):
pass
|
Order planets by distance form their star.
|
Order planets by distance form their star.
|
Python
|
mit
|
Floppy/kepler-explorer,Floppy/kepler-explorer,Floppy/kepler-explorer
|
python
|
## Code Before:
from django.views.generic import ListView, DetailView
from .models import Planet, SolarSystem
class SystemMixin(object):
model = SolarSystem
def get_queryset(self):
return super(SystemMixin, self).get_queryset().filter(radius__isnull=False)
class PlanetMixin(object):
model = Planet
def get_queryset(self):
return super(PlanetMixin, self).get_queryset().filter(
solar_system__radius__isnull=False,
radius__isnull=False)
class SystemList(SystemMixin, ListView):
pass
class SystemDetail(SystemMixin, DetailView):
def get_context_data(self, **kwargs):
data = super(SystemDetail, self).get_context_data(**kwargs)
data.update({'planets': Planet.objects.filter(solar_system=self.object, radius__isnull=False)})
return data
class PlanetList(PlanetMixin, ListView):
pass
class PlanetDetail(PlanetMixin, DetailView):
pass
## Instruction:
Order planets by distance form their star.
## Code After:
from django.views.generic import ListView, DetailView
from .models import Planet, SolarSystem
class SystemMixin(object):
model = SolarSystem
def get_queryset(self):
return super(SystemMixin, self).get_queryset().filter(radius__isnull=False)
class PlanetMixin(object):
model = Planet
def get_queryset(self):
return super(PlanetMixin, self).get_queryset().filter(
solar_system__radius__isnull=False,
radius__isnull=False)
class SystemList(SystemMixin, ListView):
pass
class SystemDetail(SystemMixin, DetailView):
def get_context_data(self, **kwargs):
data = super(SystemDetail, self).get_context_data(**kwargs)
data.update({'planets': Planet.objects.filter(solar_system=self.object, radius__isnull=False).order_by('semi_major_axis')})
return data
class PlanetList(PlanetMixin, ListView):
pass
class PlanetDetail(PlanetMixin, DetailView):
pass
|
# ... existing code ...
class SystemDetail(SystemMixin, DetailView):
def get_context_data(self, **kwargs):
data = super(SystemDetail, self).get_context_data(**kwargs)
data.update({'planets': Planet.objects.filter(solar_system=self.object, radius__isnull=False).order_by('semi_major_axis')})
return data
class PlanetList(PlanetMixin, ListView):
# ... rest of the code ...
|
0ceedd5b22a42634889b572018db1153e1ef2855
|
tests/integration/services/user_avatar/test_update_avatar_image.py
|
tests/integration/services/user_avatar/test_update_avatar_image.py
|
from pathlib import Path
import pytest
from byceps.services.user_avatar import service as user_avatar_service
from byceps.util.image.models import ImageType
@pytest.mark.parametrize(
'image_extension, image_type',
[
('jpeg', ImageType.jpeg),
('png', ImageType.png),
],
)
def test_path(data_path, site_app, user, image_extension, image_type):
with Path(f'tests/fixtures/images/image.{image_extension}').open('rb') as f:
avatar_id = user_avatar_service.update_avatar_image(
user.id, f, {image_type}
)
avatar = user_avatar_service.get_db_avatar(avatar_id)
expected_filename = f'{avatar.id}.{image_extension}'
assert avatar.path == data_path / 'global/users/avatars' / expected_filename
|
from pathlib import Path
import pytest
from byceps.services.user_avatar import service as user_avatar_service
from byceps.util.image.models import ImageType
@pytest.mark.parametrize(
'image_extension, image_type',
[
('jpeg', ImageType.jpeg),
('png', ImageType.png),
],
)
def test_path(data_path, site_app, user, image_extension, image_type):
with Path(f'tests/fixtures/images/image.{image_extension}').open('rb') as f:
avatar_id = user_avatar_service.update_avatar_image(
user.id, f, {image_type}
)
avatar = user_avatar_service.get_db_avatar(avatar_id)
expected_filename = f'{avatar.id}.{image_extension}'
expected = data_path / 'global' / 'users' / 'avatars' / expected_filename
assert avatar.path == expected
|
Use `/` operator to assemble path
|
Use `/` operator to assemble path
|
Python
|
bsd-3-clause
|
homeworkprod/byceps,homeworkprod/byceps,homeworkprod/byceps
|
python
|
## Code Before:
from pathlib import Path
import pytest
from byceps.services.user_avatar import service as user_avatar_service
from byceps.util.image.models import ImageType
@pytest.mark.parametrize(
'image_extension, image_type',
[
('jpeg', ImageType.jpeg),
('png', ImageType.png),
],
)
def test_path(data_path, site_app, user, image_extension, image_type):
with Path(f'tests/fixtures/images/image.{image_extension}').open('rb') as f:
avatar_id = user_avatar_service.update_avatar_image(
user.id, f, {image_type}
)
avatar = user_avatar_service.get_db_avatar(avatar_id)
expected_filename = f'{avatar.id}.{image_extension}'
assert avatar.path == data_path / 'global/users/avatars' / expected_filename
## Instruction:
Use `/` operator to assemble path
## Code After:
from pathlib import Path
import pytest
from byceps.services.user_avatar import service as user_avatar_service
from byceps.util.image.models import ImageType
@pytest.mark.parametrize(
'image_extension, image_type',
[
('jpeg', ImageType.jpeg),
('png', ImageType.png),
],
)
def test_path(data_path, site_app, user, image_extension, image_type):
with Path(f'tests/fixtures/images/image.{image_extension}').open('rb') as f:
avatar_id = user_avatar_service.update_avatar_image(
user.id, f, {image_type}
)
avatar = user_avatar_service.get_db_avatar(avatar_id)
expected_filename = f'{avatar.id}.{image_extension}'
expected = data_path / 'global' / 'users' / 'avatars' / expected_filename
assert avatar.path == expected
|
# ... existing code ...
avatar = user_avatar_service.get_db_avatar(avatar_id)
expected_filename = f'{avatar.id}.{image_extension}'
expected = data_path / 'global' / 'users' / 'avatars' / expected_filename
assert avatar.path == expected
# ... rest of the code ...
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.