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
def66bc381f03970640a61d64b49ad5de9ef3879
ocaml/build-in.py
ocaml/build-in.py
import sys import os from os.path import relpath ocaml_build_dir = relpath(sys.argv[1], '.') os.execvp("make", ["make", 'OCAML_BUILDDIR=' + ocaml_build_dir, "ocaml"])
import sys import os from os.path import relpath ocaml_build_dir = relpath(sys.argv[1], '.') # Hack: when we can depend on a full OCaml feed with the build tools, we can remove this. # Until then, we need to avoid trying to compile against the limited runtime environment. if 'OCAMLLIB' in os.environ: del os.environ['OCAMLLIB'] os.execvp("make", ["make", 'OCAML_BUILDDIR=' + ocaml_build_dir, "ocaml"])
Remove OCAMLLIB from build environment
Remove OCAMLLIB from build environment This is a temporary hack: when we can depend on a full OCaml feed with the build tools, we can remove this. Until then, we need to avoid trying to compile against the limited runtime environment.
Python
lgpl-2.1
0install/0install,afb/0install,afb/0install,afb/0install,gasche/0install,bastianeicher/0install,bhilton/0install,fdopen/0install,gasche/0install,0install/0install,jaychoo/0install,dbenamy/0install,gfxmonk/0install,jaychoo/0install,dbenamy/0install,DarkGreising/0install,bastianeicher/0install,fdopen/0install,bhilton/0install,bhilton/0install,bartbes/0install,gasche/0install,bastianeicher/0install,dbenamy/0install,DarkGreising/0install,bartbes/0install,fdopen/0install,gasche/0install,HoMeCracKeR/0install,jaychoo/0install,pombreda/0install,gfxmonk/0install,bartbes/0install,afb/0install,HoMeCracKeR/0install,HoMeCracKeR/0install,gfxmonk/0install,DarkGreising/0install,pombreda/0install,pombreda/0install,0install/0install
python
## Code Before: import sys import os from os.path import relpath ocaml_build_dir = relpath(sys.argv[1], '.') os.execvp("make", ["make", 'OCAML_BUILDDIR=' + ocaml_build_dir, "ocaml"]) ## Instruction: Remove OCAMLLIB from build environment This is a temporary hack: when we can depend on a full OCaml feed with the build tools, we can remove this. Until then, we need to avoid trying to compile against the limited runtime environment. ## Code After: import sys import os from os.path import relpath ocaml_build_dir = relpath(sys.argv[1], '.') # Hack: when we can depend on a full OCaml feed with the build tools, we can remove this. # Until then, we need to avoid trying to compile against the limited runtime environment. if 'OCAMLLIB' in os.environ: del os.environ['OCAMLLIB'] os.execvp("make", ["make", 'OCAML_BUILDDIR=' + ocaml_build_dir, "ocaml"])
# ... existing code ... import os from os.path import relpath ocaml_build_dir = relpath(sys.argv[1], '.') # Hack: when we can depend on a full OCaml feed with the build tools, we can remove this. # Until then, we need to avoid trying to compile against the limited runtime environment. if 'OCAMLLIB' in os.environ: del os.environ['OCAMLLIB'] os.execvp("make", ["make", 'OCAML_BUILDDIR=' + ocaml_build_dir, "ocaml"]) # ... rest of the code ...
78af31feb8ac731eda18a5fff8075bb7dde90dde
scripts/test_deployment.py
scripts/test_deployment.py
import os import pytest import requests @pytest.fixture def url(): return os.getenv("SITE", "http://localhost:5000") def test_post_images(expect, url): params = {"key": "iw", "lines": ["test", "deployment"]} response = requests.post(f"{url}/api/images", json=params) expect(response.status_code) == 201 expect(response.json()["url"]).endswith("/api/images/iw/test/deployment.png") def test_get_image(expect, url): response = requests.get(f"{url}/iw/tests_code/in_production.jpg") expect(response.status_code) == 200 expect(response.headers["Content-Type"]) == "image/jpeg" def test_get_image_custom(expect, url): response = requests.get( f"{url}/custom/test.png?alt=https://www.gstatic.com/webp/gallery/1.jpg" ) expect(response.status_code) == 200 expect(response.headers["Content-Type"]) == "image/png"
import os import pytest import requests @pytest.fixture def url(): return os.getenv("SITE", "http://localhost:5000") def test_post_images(expect, url): params = {"key": "iw", "lines": ["test", "deployment"]} response = requests.post(f"{url}/api/images", json=params) expect(response.status_code) == 201 expect(response.json()["url"]).endswith("/api/images/iw/test/deployment.png") def test_get_image(expect, url): response = requests.get(f"{url}/api/images/iw/tests_code/in_production.jpg") expect(response.status_code) == 200 expect(response.headers["Content-Type"]) == "image/jpeg" def test_get_image_custom(expect, url): response = requests.get( f"{url}/api/images/custom/test.png" "?alt=https://www.gstatic.com/webp/gallery/1.jpg" ) expect(response.status_code) == 200 expect(response.headers["Content-Type"]) == "image/png"
Use API route in promotion tests
Use API route in promotion tests
Python
mit
jacebrowning/memegen,jacebrowning/memegen
python
## Code Before: import os import pytest import requests @pytest.fixture def url(): return os.getenv("SITE", "http://localhost:5000") def test_post_images(expect, url): params = {"key": "iw", "lines": ["test", "deployment"]} response = requests.post(f"{url}/api/images", json=params) expect(response.status_code) == 201 expect(response.json()["url"]).endswith("/api/images/iw/test/deployment.png") def test_get_image(expect, url): response = requests.get(f"{url}/iw/tests_code/in_production.jpg") expect(response.status_code) == 200 expect(response.headers["Content-Type"]) == "image/jpeg" def test_get_image_custom(expect, url): response = requests.get( f"{url}/custom/test.png?alt=https://www.gstatic.com/webp/gallery/1.jpg" ) expect(response.status_code) == 200 expect(response.headers["Content-Type"]) == "image/png" ## Instruction: Use API route in promotion tests ## Code After: import os import pytest import requests @pytest.fixture def url(): return os.getenv("SITE", "http://localhost:5000") def test_post_images(expect, url): params = {"key": "iw", "lines": ["test", "deployment"]} response = requests.post(f"{url}/api/images", json=params) expect(response.status_code) == 201 expect(response.json()["url"]).endswith("/api/images/iw/test/deployment.png") def test_get_image(expect, url): response = requests.get(f"{url}/api/images/iw/tests_code/in_production.jpg") expect(response.status_code) == 200 expect(response.headers["Content-Type"]) == "image/jpeg" def test_get_image_custom(expect, url): response = requests.get( f"{url}/api/images/custom/test.png" "?alt=https://www.gstatic.com/webp/gallery/1.jpg" ) expect(response.status_code) == 200 expect(response.headers["Content-Type"]) == "image/png"
// ... existing code ... def test_get_image(expect, url): response = requests.get(f"{url}/api/images/iw/tests_code/in_production.jpg") expect(response.status_code) == 200 expect(response.headers["Content-Type"]) == "image/jpeg" // ... modified code ... def test_get_image_custom(expect, url): response = requests.get( f"{url}/api/images/custom/test.png" "?alt=https://www.gstatic.com/webp/gallery/1.jpg" ) expect(response.status_code) == 200 expect(response.headers["Content-Type"]) == "image/png" // ... rest of the code ...
4a62214f0c9e8789b8453a48c0a880c4ac6236cb
saleor/product/migrations/0123_auto_20200904_1251.py
saleor/product/migrations/0123_auto_20200904_1251.py
from django.db import migrations class Migration(migrations.Migration): dependencies = [ ("product", "0122_auto_20200828_1135"), ] operations = [ migrations.AlterUniqueTogether( name="variantimage", unique_together={("variant", "image")}, ), ]
from django.db import migrations from django.db.models import Count def remove_variant_image_duplicates(apps, schema_editor): ProductImage = apps.get_model("product", "ProductImage") VariantImage = apps.get_model("product", "VariantImage") duplicated_images = ( ProductImage.objects.values("pk", "variant_images__variant") .annotate(variant_count=Count("variant_images__variant")) .filter(variant_count__gte=2) ) variant_image_ids_to_remove = [] for image_data in duplicated_images: ids = VariantImage.objects.filter( variant=image_data["variant_images__variant"], image__pk=image_data["pk"], )[1:].values_list("pk", flat=True) variant_image_ids_to_remove += ids VariantImage.objects.filter(pk__in=variant_image_ids_to_remove).delete() class Migration(migrations.Migration): dependencies = [ ("product", "0122_auto_20200828_1135"), ] operations = [ migrations.RunPython( remove_variant_image_duplicates, migrations.RunPython.noop ), migrations.AlterUniqueTogether( name="variantimage", unique_together={("variant", "image")}, ), ]
Drop duplicated VariantImages before migration to unique together
Drop duplicated VariantImages before migration to unique together
Python
bsd-3-clause
mociepka/saleor,mociepka/saleor,mociepka/saleor
python
## Code Before: from django.db import migrations class Migration(migrations.Migration): dependencies = [ ("product", "0122_auto_20200828_1135"), ] operations = [ migrations.AlterUniqueTogether( name="variantimage", unique_together={("variant", "image")}, ), ] ## Instruction: Drop duplicated VariantImages before migration to unique together ## Code After: from django.db import migrations from django.db.models import Count def remove_variant_image_duplicates(apps, schema_editor): ProductImage = apps.get_model("product", "ProductImage") VariantImage = apps.get_model("product", "VariantImage") duplicated_images = ( ProductImage.objects.values("pk", "variant_images__variant") .annotate(variant_count=Count("variant_images__variant")) .filter(variant_count__gte=2) ) variant_image_ids_to_remove = [] for image_data in duplicated_images: ids = VariantImage.objects.filter( variant=image_data["variant_images__variant"], image__pk=image_data["pk"], )[1:].values_list("pk", flat=True) variant_image_ids_to_remove += ids VariantImage.objects.filter(pk__in=variant_image_ids_to_remove).delete() class Migration(migrations.Migration): dependencies = [ ("product", "0122_auto_20200828_1135"), ] operations = [ migrations.RunPython( remove_variant_image_duplicates, migrations.RunPython.noop ), migrations.AlterUniqueTogether( name="variantimage", unique_together={("variant", "image")}, ), ]
... from django.db import migrations from django.db.models import Count def remove_variant_image_duplicates(apps, schema_editor): ProductImage = apps.get_model("product", "ProductImage") VariantImage = apps.get_model("product", "VariantImage") duplicated_images = ( ProductImage.objects.values("pk", "variant_images__variant") .annotate(variant_count=Count("variant_images__variant")) .filter(variant_count__gte=2) ) variant_image_ids_to_remove = [] for image_data in duplicated_images: ids = VariantImage.objects.filter( variant=image_data["variant_images__variant"], image__pk=image_data["pk"], )[1:].values_list("pk", flat=True) variant_image_ids_to_remove += ids VariantImage.objects.filter(pk__in=variant_image_ids_to_remove).delete() class Migration(migrations.Migration): ... ] operations = [ migrations.RunPython( remove_variant_image_duplicates, migrations.RunPython.noop ), migrations.AlterUniqueTogether( name="variantimage", unique_together={("variant", "image")}, ), ...
ba42ae94620eb2b28901588f7b1a057fa3ec0b01
src/main/java/de/retest/util/DeleteOnCloseFileInputStream.java
src/main/java/de/retest/util/DeleteOnCloseFileInputStream.java
package de.retest.util; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; /* * Taken from https://stackoverflow.com/a/4694155 */ public class DeleteOnCloseFileInputStream extends FileInputStream { private File file; public DeleteOnCloseFileInputStream( final File file ) throws FileNotFoundException { super( file ); this.file = file; } @Override public void close() throws IOException { try { super.close(); } finally { if ( file != null ) { file.delete(); file = null; } } } }
package de.retest.util; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import org.apache.commons.io.FileUtils; /* * Taken from https://stackoverflow.com/a/4694155 */ public class DeleteOnCloseFileInputStream extends FileInputStream { private final File file; public DeleteOnCloseFileInputStream( final File file ) throws FileNotFoundException { super( file ); this.file = file; } @Override public void close() throws IOException { try { super.close(); } finally { FileUtils.forceDelete( file ); } } }
Fix file.delete ignored return value
Fix file.delete ignored return value
Java
agpl-3.0
retest/recheck,retest/recheck
java
## Code Before: package de.retest.util; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; /* * Taken from https://stackoverflow.com/a/4694155 */ public class DeleteOnCloseFileInputStream extends FileInputStream { private File file; public DeleteOnCloseFileInputStream( final File file ) throws FileNotFoundException { super( file ); this.file = file; } @Override public void close() throws IOException { try { super.close(); } finally { if ( file != null ) { file.delete(); file = null; } } } } ## Instruction: Fix file.delete ignored return value ## Code After: package de.retest.util; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import org.apache.commons.io.FileUtils; /* * Taken from https://stackoverflow.com/a/4694155 */ public class DeleteOnCloseFileInputStream extends FileInputStream { private final File file; public DeleteOnCloseFileInputStream( final File file ) throws FileNotFoundException { super( file ); this.file = file; } @Override public void close() throws IOException { try { super.close(); } finally { FileUtils.forceDelete( file ); } } }
# ... existing code ... import java.io.FileNotFoundException; import java.io.IOException; import org.apache.commons.io.FileUtils; /* * Taken from https://stackoverflow.com/a/4694155 */ public class DeleteOnCloseFileInputStream extends FileInputStream { private final File file; public DeleteOnCloseFileInputStream( final File file ) throws FileNotFoundException { super( file ); # ... modified code ... try { super.close(); } finally { FileUtils.forceDelete( file ); } } } # ... rest of the code ...
e91d81a03d57af1fff1b580b1c276fd02f44f587
places/migrations/0011_auto_20200712_1733.py
places/migrations/0011_auto_20200712_1733.py
from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('places', '0010_auto_20200712_0505'), ] operations = [ migrations.AlterModelOptions( name='category', options={'ordering': ['name'], 'verbose_name_plural': 'categories'}, ), migrations.AlterModelOptions( name='review', options={'ordering': ['rating']}, ), ]
from django.db import migrations class Migration(migrations.Migration): dependencies = [ ("places", "0010_auto_20200712_0505"), ] operations = [ migrations.AlterModelOptions( name="category", options={"ordering": ["name"], "verbose_name_plural": "categories"}, ), migrations.AlterModelOptions(name="review", options={"ordering": ["rating"]},), ]
Apply black formatting to migration
Apply black formatting to migration
Python
mit
huangsam/chowist,huangsam/chowist,huangsam/chowist
python
## Code Before: from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('places', '0010_auto_20200712_0505'), ] operations = [ migrations.AlterModelOptions( name='category', options={'ordering': ['name'], 'verbose_name_plural': 'categories'}, ), migrations.AlterModelOptions( name='review', options={'ordering': ['rating']}, ), ] ## Instruction: Apply black formatting to migration ## Code After: from django.db import migrations class Migration(migrations.Migration): dependencies = [ ("places", "0010_auto_20200712_0505"), ] operations = [ migrations.AlterModelOptions( name="category", options={"ordering": ["name"], "verbose_name_plural": "categories"}, ), migrations.AlterModelOptions(name="review", options={"ordering": ["rating"]},), ]
# ... existing code ... class Migration(migrations.Migration): dependencies = [ ("places", "0010_auto_20200712_0505"), ] operations = [ migrations.AlterModelOptions( name="category", options={"ordering": ["name"], "verbose_name_plural": "categories"}, ), migrations.AlterModelOptions(name="review", options={"ordering": ["rating"]},), ] # ... rest of the code ...
3a06db1675442564976b5d3df6986aa3330337ef
test/Driver/cl-include.c
test/Driver/cl-include.c
// Note: %s must be preceded by --, otherwise it may be interpreted as a // command-line option, e.g. on Mac where %s is commonly under /Users. // RUN: %clang_cl -### -- %s 2>&1 | FileCheck %s --check-prefix=BUILTIN // BUILTIN: "-internal-isystem" "{{.*lib.*clang.*[0-9]\.[0-9].*include}}" // RUN: %clang_cl -nobuiltininc -### -- %s 2>&1 | FileCheck %s --check-prefix=NOBUILTIN // NOBUILTIN-NOT: "-internal-isystem" "{{.*lib.*clang.*[0-9]\.[0-9].*include}}" // RUN: env INCLUDE=/my/system/inc %clang_cl -### -- %s 2>&1 | FileCheck %s --check-prefix=STDINC // STDINC: "-internal-isystem" "/my/system/inc" // RUN: env INCLUDE=/my/system/inc %clang_cl -nostdinc -### -- %s 2>&1 | FileCheck %s --check-prefix=NOSTDINC // NOSTDINC-NOT: "-internal-isystem" "/my/system/inc"
// Note: %s must be preceded by --, otherwise it may be interpreted as a // command-line option, e.g. on Mac where %s is commonly under /Users. // RUN: %clang_cl -### -- %s 2>&1 | FileCheck %s --check-prefix=BUILTIN // BUILTIN: "-internal-isystem" "{{.*lib.*clang.*include}}" // RUN: %clang_cl -nobuiltininc -### -- %s 2>&1 | FileCheck %s --check-prefix=NOBUILTIN // NOBUILTIN-NOT: "-internal-isystem" "{{.*lib.*clang.*include}}" // RUN: env INCLUDE=/my/system/inc %clang_cl -### -- %s 2>&1 | FileCheck %s --check-prefix=STDINC // STDINC: "-internal-isystem" "/my/system/inc" // RUN: env INCLUDE=/my/system/inc %clang_cl -nostdinc -### -- %s 2>&1 | FileCheck %s --check-prefix=NOSTDINC // NOSTDINC-NOT: "-internal-isystem" "/my/system/inc"
Make the clang-cl test less restrictive.
Make the clang-cl test less restrictive. Make the test less restrictive to allow directory layout used in our test setup. git-svn-id: ffe668792ed300d6c2daa1f6eba2e0aa28d7ec6c@304408 91177308-0d34-0410-b5e6-96231b3b80d8
C
apache-2.0
apple/swift-clang,llvm-mirror/clang,llvm-mirror/clang,llvm-mirror/clang,llvm-mirror/clang,llvm-mirror/clang,apple/swift-clang,llvm-mirror/clang,apple/swift-clang,llvm-mirror/clang,apple/swift-clang,apple/swift-clang,apple/swift-clang,apple/swift-clang,apple/swift-clang,llvm-mirror/clang,apple/swift-clang,llvm-mirror/clang,llvm-mirror/clang,apple/swift-clang
c
## Code Before: // Note: %s must be preceded by --, otherwise it may be interpreted as a // command-line option, e.g. on Mac where %s is commonly under /Users. // RUN: %clang_cl -### -- %s 2>&1 | FileCheck %s --check-prefix=BUILTIN // BUILTIN: "-internal-isystem" "{{.*lib.*clang.*[0-9]\.[0-9].*include}}" // RUN: %clang_cl -nobuiltininc -### -- %s 2>&1 | FileCheck %s --check-prefix=NOBUILTIN // NOBUILTIN-NOT: "-internal-isystem" "{{.*lib.*clang.*[0-9]\.[0-9].*include}}" // RUN: env INCLUDE=/my/system/inc %clang_cl -### -- %s 2>&1 | FileCheck %s --check-prefix=STDINC // STDINC: "-internal-isystem" "/my/system/inc" // RUN: env INCLUDE=/my/system/inc %clang_cl -nostdinc -### -- %s 2>&1 | FileCheck %s --check-prefix=NOSTDINC // NOSTDINC-NOT: "-internal-isystem" "/my/system/inc" ## Instruction: Make the clang-cl test less restrictive. Make the test less restrictive to allow directory layout used in our test setup. git-svn-id: ffe668792ed300d6c2daa1f6eba2e0aa28d7ec6c@304408 91177308-0d34-0410-b5e6-96231b3b80d8 ## Code After: // Note: %s must be preceded by --, otherwise it may be interpreted as a // command-line option, e.g. on Mac where %s is commonly under /Users. // RUN: %clang_cl -### -- %s 2>&1 | FileCheck %s --check-prefix=BUILTIN // BUILTIN: "-internal-isystem" "{{.*lib.*clang.*include}}" // RUN: %clang_cl -nobuiltininc -### -- %s 2>&1 | FileCheck %s --check-prefix=NOBUILTIN // NOBUILTIN-NOT: "-internal-isystem" "{{.*lib.*clang.*include}}" // RUN: env INCLUDE=/my/system/inc %clang_cl -### -- %s 2>&1 | FileCheck %s --check-prefix=STDINC // STDINC: "-internal-isystem" "/my/system/inc" // RUN: env INCLUDE=/my/system/inc %clang_cl -nostdinc -### -- %s 2>&1 | FileCheck %s --check-prefix=NOSTDINC // NOSTDINC-NOT: "-internal-isystem" "/my/system/inc"
// ... existing code ... // command-line option, e.g. on Mac where %s is commonly under /Users. // RUN: %clang_cl -### -- %s 2>&1 | FileCheck %s --check-prefix=BUILTIN // BUILTIN: "-internal-isystem" "{{.*lib.*clang.*include}}" // RUN: %clang_cl -nobuiltininc -### -- %s 2>&1 | FileCheck %s --check-prefix=NOBUILTIN // NOBUILTIN-NOT: "-internal-isystem" "{{.*lib.*clang.*include}}" // RUN: env INCLUDE=/my/system/inc %clang_cl -### -- %s 2>&1 | FileCheck %s --check-prefix=STDINC // STDINC: "-internal-isystem" "/my/system/inc" // ... rest of the code ...
30910e99145b2f15b2d298f191e1739a93cf87af
axelor-core/src/main/java/com/axelor/dms/db/repo/DMSFileRepository.java
axelor-core/src/main/java/com/axelor/dms/db/repo/DMSFileRepository.java
package com.axelor.dms.db.repo; import java.util.Map; import org.joda.time.LocalDateTime; import com.axelor.db.JpaRepository; import com.axelor.dms.db.DMSFile; public class DMSFileRepository extends JpaRepository<DMSFile> { public DMSFileRepository() { super(DMSFile.class); } @Override public Map<String, Object> populate(Map<String, Object> json) { final Object id = json.get("id"); if (id == null) { return json; } final DMSFile file = find((Long) id); if (file == null) { return json; } boolean isFile = file.getIsDirectory() != Boolean.TRUE; LocalDateTime dt = file.getUpdatedOn(); if (dt == null) { dt = file.getCreatedOn(); } json.put("typeIcon", isFile ? "fa fa-file" : "fa fa-folder"); json.put("lastModified", dt); return json; } }
package com.axelor.dms.db.repo; import java.util.List; import java.util.Map; import org.joda.time.LocalDateTime; import com.axelor.db.JpaRepository; import com.axelor.dms.db.DMSFile; public class DMSFileRepository extends JpaRepository<DMSFile> { public DMSFileRepository() { super(DMSFile.class); } @Override public void remove(DMSFile entity) { // remove all children if (entity.getIsDirectory() == Boolean.TRUE) { final List<DMSFile> children = all().filter("self.parent.id = ?", entity.getId()).fetch(); for (DMSFile child : children) { if (child != entity) { remove(child);; } } } super.remove(entity); } @Override public Map<String, Object> populate(Map<String, Object> json) { final Object id = json.get("id"); if (id == null) { return json; } final DMSFile file = find((Long) id); if (file == null) { return json; } boolean isFile = file.getIsDirectory() != Boolean.TRUE; LocalDateTime dt = file.getUpdatedOn(); if (dt == null) { dt = file.getCreatedOn(); } json.put("typeIcon", isFile ? "fa fa-file" : "fa fa-folder"); json.put("lastModified", dt); return json; } }
Delete children when deleting dms folder
Delete children when deleting dms folder
Java
agpl-3.0
marioestradarosa/axelor-development-kit,donsunsoft/axelor-development-kit,marioestradarosa/axelor-development-kit,marioestradarosa/axelor-development-kit,donsunsoft/axelor-development-kit,donsunsoft/axelor-development-kit,marioestradarosa/axelor-development-kit,donsunsoft/axelor-development-kit
java
## Code Before: package com.axelor.dms.db.repo; import java.util.Map; import org.joda.time.LocalDateTime; import com.axelor.db.JpaRepository; import com.axelor.dms.db.DMSFile; public class DMSFileRepository extends JpaRepository<DMSFile> { public DMSFileRepository() { super(DMSFile.class); } @Override public Map<String, Object> populate(Map<String, Object> json) { final Object id = json.get("id"); if (id == null) { return json; } final DMSFile file = find((Long) id); if (file == null) { return json; } boolean isFile = file.getIsDirectory() != Boolean.TRUE; LocalDateTime dt = file.getUpdatedOn(); if (dt == null) { dt = file.getCreatedOn(); } json.put("typeIcon", isFile ? "fa fa-file" : "fa fa-folder"); json.put("lastModified", dt); return json; } } ## Instruction: Delete children when deleting dms folder ## Code After: package com.axelor.dms.db.repo; import java.util.List; import java.util.Map; import org.joda.time.LocalDateTime; import com.axelor.db.JpaRepository; import com.axelor.dms.db.DMSFile; public class DMSFileRepository extends JpaRepository<DMSFile> { public DMSFileRepository() { super(DMSFile.class); } @Override public void remove(DMSFile entity) { // remove all children if (entity.getIsDirectory() == Boolean.TRUE) { final List<DMSFile> children = all().filter("self.parent.id = ?", entity.getId()).fetch(); for (DMSFile child : children) { if (child != entity) { remove(child);; } } } super.remove(entity); } @Override public Map<String, Object> populate(Map<String, Object> json) { final Object id = json.get("id"); if (id == null) { return json; } final DMSFile file = find((Long) id); if (file == null) { return json; } boolean isFile = file.getIsDirectory() != Boolean.TRUE; LocalDateTime dt = file.getUpdatedOn(); if (dt == null) { dt = file.getCreatedOn(); } json.put("typeIcon", isFile ? "fa fa-file" : "fa fa-folder"); json.put("lastModified", dt); return json; } }
// ... existing code ... package com.axelor.dms.db.repo; import java.util.List; import java.util.Map; import org.joda.time.LocalDateTime; // ... modified code ... public DMSFileRepository() { super(DMSFile.class); } @Override public void remove(DMSFile entity) { // remove all children if (entity.getIsDirectory() == Boolean.TRUE) { final List<DMSFile> children = all().filter("self.parent.id = ?", entity.getId()).fetch(); for (DMSFile child : children) { if (child != entity) { remove(child);; } } } super.remove(entity); } @Override // ... rest of the code ...
2301b0bfdb216f31428e6c9ca0bf6b2951a5e64b
symposion/forms.py
symposion/forms.py
from django import forms import account.forms class SignupForm(account.forms.SignupForm): first_name = forms.CharField() last_name = forms.CharField() email_confirm = forms.EmailField(label="Confirm Email") def __init__(self, *args, **kwargs): super(SignupForm, self).__init__(*args, **kwargs) del self.fields["username"] self.fields.keyOrder = [ "email", "email_confirm", "first_name", "last_name", "password", "password_confirm" ] def clean_email_confirm(self): email = self.cleaned_data.get("email") email_confirm = self.cleaned_data["email_confirm"] if email: if email != email_confirm: raise forms.ValidationError( "Email address must match previously typed email address") return email_confirm
try: from collections import OrderedDict except ImportError: OrderedDict = None import account.forms from django import forms from django.utils.translation import ugettext_lazy as _ class SignupForm(account.forms.SignupForm): first_name = forms.CharField(label=_("First name")) last_name = forms.CharField(label=_("Last name")) email_confirm = forms.EmailField(label=_("Confirm Email")) def __init__(self, *args, **kwargs): super(SignupForm, self).__init__(*args, **kwargs) field_order = [ "first_name", "last_name", "email", "email_confirm", "password", "password_confirm" ] del self.fields["username"] if not OrderedDict or hasattr(self.fields, "keyOrder"): self.fields.keyOrder = field_order else: self.fields = OrderedDict((k, self.fields[k]) for k in field_order) def clean_email_confirm(self): email = self.cleaned_data.get("email") email_confirm = self.cleaned_data["email_confirm"] if email: if email != email_confirm: raise forms.ValidationError( "Email address must match previously typed email address") return email_confirm
Fix order fields in signup form
Fix order fields in signup form
Python
bsd-3-clause
toulibre/symposion,toulibre/symposion
python
## Code Before: from django import forms import account.forms class SignupForm(account.forms.SignupForm): first_name = forms.CharField() last_name = forms.CharField() email_confirm = forms.EmailField(label="Confirm Email") def __init__(self, *args, **kwargs): super(SignupForm, self).__init__(*args, **kwargs) del self.fields["username"] self.fields.keyOrder = [ "email", "email_confirm", "first_name", "last_name", "password", "password_confirm" ] def clean_email_confirm(self): email = self.cleaned_data.get("email") email_confirm = self.cleaned_data["email_confirm"] if email: if email != email_confirm: raise forms.ValidationError( "Email address must match previously typed email address") return email_confirm ## Instruction: Fix order fields in signup form ## Code After: try: from collections import OrderedDict except ImportError: OrderedDict = None import account.forms from django import forms from django.utils.translation import ugettext_lazy as _ class SignupForm(account.forms.SignupForm): first_name = forms.CharField(label=_("First name")) last_name = forms.CharField(label=_("Last name")) email_confirm = forms.EmailField(label=_("Confirm Email")) def __init__(self, *args, **kwargs): super(SignupForm, self).__init__(*args, **kwargs) field_order = [ "first_name", "last_name", "email", "email_confirm", "password", "password_confirm" ] del self.fields["username"] if not OrderedDict or hasattr(self.fields, "keyOrder"): self.fields.keyOrder = field_order else: self.fields = OrderedDict((k, self.fields[k]) for k in field_order) def clean_email_confirm(self): email = self.cleaned_data.get("email") email_confirm = self.cleaned_data["email_confirm"] if email: if email != email_confirm: raise forms.ValidationError( "Email address must match previously typed email address") return email_confirm
# ... existing code ... try: from collections import OrderedDict except ImportError: OrderedDict = None import account.forms from django import forms from django.utils.translation import ugettext_lazy as _ class SignupForm(account.forms.SignupForm): first_name = forms.CharField(label=_("First name")) last_name = forms.CharField(label=_("Last name")) email_confirm = forms.EmailField(label=_("Confirm Email")) def __init__(self, *args, **kwargs): super(SignupForm, self).__init__(*args, **kwargs) field_order = [ "first_name", "last_name", "email", "email_confirm", "password", "password_confirm" ] del self.fields["username"] if not OrderedDict or hasattr(self.fields, "keyOrder"): self.fields.keyOrder = field_order else: self.fields = OrderedDict((k, self.fields[k]) for k in field_order) def clean_email_confirm(self): email = self.cleaned_data.get("email") # ... rest of the code ...
c7b85c55569d65966601ba3fc1cdc709d1693fe7
src/qt/logging/messageboxlogger.h
src/qt/logging/messageboxlogger.h
/*Copyright 2010-2015 George Karagoulis 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 GUTIL_NO_GUI_FUNCTIONALITY #ifndef GUTIL_MESSAGEBOXLOGGER_H #define GUTIL_MESSAGEBOXLOGGER_H #include <gutil/ilog.h> #include <QObject> class QWidget; namespace GUtil{ namespace Qt{ /** A logger implementation which displays the message in a modal dialog box. */ class MessageBoxLogger : public QObject, public GUtil::ILog { Q_OBJECT QWidget *m_parentWidget; public: explicit MessageBoxLogger(QWidget *parent = 0); virtual ~MessageBoxLogger() {} /** Displays a modal dialog box with the title and message, with the appropriate severity. */ virtual void Log(const LoggingData &) noexcept; private slots: void _log(const LoggingData &); }; }} #endif // GUTIL_MESSAGEBOXLOGGER_H #endif // GUI_FUNCTIONALITY
/*Copyright 2010-2015 George Karagoulis 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 GUTIL_NO_GUI_FUNCTIONALITY #ifndef GUTIL_MESSAGEBOXLOGGER_H #define GUTIL_MESSAGEBOXLOGGER_H #include <gutil/ilog.h> #include <QObject> class QWidget; namespace GUtil{ namespace Qt{ /** A logger implementation which displays the message in a modal dialog box. */ class MessageBoxLogger : public QObject, public GUtil::ILog { Q_OBJECT QWidget *m_parentWidget; public: explicit MessageBoxLogger(QWidget *parent = 0); virtual ~MessageBoxLogger() {} void SetParentWidget(QWidget *parent){ m_parentWidget = parent; } QWidget *GetParentWidget() const{ return m_parentWidget; } /** Displays a modal dialog box with the title and message, with the appropriate severity. */ virtual void Log(const LoggingData &) noexcept; private slots: void _log(const LoggingData &); }; }} #endif // GUTIL_MESSAGEBOXLOGGER_H #endif // GUI_FUNCTIONALITY
Allow to change the parent widget after construction. Sometimes your main widget changes and you don't want to make a new logger.
Allow to change the parent widget after construction. Sometimes your main widget changes and you don't want to make a new logger.
C
apache-2.0
karagog/gutil,karagog/gutil,karagog/gutil
c
## Code Before: /*Copyright 2010-2015 George Karagoulis 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 GUTIL_NO_GUI_FUNCTIONALITY #ifndef GUTIL_MESSAGEBOXLOGGER_H #define GUTIL_MESSAGEBOXLOGGER_H #include <gutil/ilog.h> #include <QObject> class QWidget; namespace GUtil{ namespace Qt{ /** A logger implementation which displays the message in a modal dialog box. */ class MessageBoxLogger : public QObject, public GUtil::ILog { Q_OBJECT QWidget *m_parentWidget; public: explicit MessageBoxLogger(QWidget *parent = 0); virtual ~MessageBoxLogger() {} /** Displays a modal dialog box with the title and message, with the appropriate severity. */ virtual void Log(const LoggingData &) noexcept; private slots: void _log(const LoggingData &); }; }} #endif // GUTIL_MESSAGEBOXLOGGER_H #endif // GUI_FUNCTIONALITY ## Instruction: Allow to change the parent widget after construction. Sometimes your main widget changes and you don't want to make a new logger. ## Code After: /*Copyright 2010-2015 George Karagoulis 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 GUTIL_NO_GUI_FUNCTIONALITY #ifndef GUTIL_MESSAGEBOXLOGGER_H #define GUTIL_MESSAGEBOXLOGGER_H #include <gutil/ilog.h> #include <QObject> class QWidget; namespace GUtil{ namespace Qt{ /** A logger implementation which displays the message in a modal dialog box. */ class MessageBoxLogger : public QObject, public GUtil::ILog { Q_OBJECT QWidget *m_parentWidget; public: explicit MessageBoxLogger(QWidget *parent = 0); virtual ~MessageBoxLogger() {} void SetParentWidget(QWidget *parent){ m_parentWidget = parent; } QWidget *GetParentWidget() const{ return m_parentWidget; } /** Displays a modal dialog box with the title and message, with the appropriate severity. */ virtual void Log(const LoggingData &) noexcept; private slots: void _log(const LoggingData &); }; }} #endif // GUTIL_MESSAGEBOXLOGGER_H #endif // GUI_FUNCTIONALITY
# ... existing code ... explicit MessageBoxLogger(QWidget *parent = 0); virtual ~MessageBoxLogger() {} void SetParentWidget(QWidget *parent){ m_parentWidget = parent; } QWidget *GetParentWidget() const{ return m_parentWidget; } /** Displays a modal dialog box with the title and message, with the appropriate severity. */ # ... rest of the code ...
844e3635aeb0144f7e4cc0d9de3bfc219312bbe5
ocradmin/plugins/views.py
ocradmin/plugins/views.py
from django.http import HttpResponse, HttpResponseRedirect, Http404 from django.shortcuts import render_to_response from ocradmin.ocrtasks.models import OcrTask from ocradmin.plugins.manager import ModuleManager import logging logger = logging.getLogger(__name__) import simplejson import tasks def query(request): """ Query plugin info. This returns a list of available OCR engines and an URL that can be queries when one of them is selected. """ stages=request.GET.getlist("stage") return HttpResponse( ModuleManager.get_json(*stages), mimetype="application/json") def runscript(request): """ Execute a script (sent as JSON). """ evalnode = request.POST.get("node", "") jsondata = request.POST.get("script", simplejson.dumps({"arse":"spaz"})) script = simplejson.loads(jsondata) async = OcrTask.run_celery_task("run.script", evalnode, script, untracked=True, asyncronous=True, queue="interactive") out = dict(task_id=async.task_id, status=async.status, results=async.result) return HttpResponse(simplejson.dumps(out), mimetype="application/json")
from django.http import HttpResponse, HttpResponseRedirect, Http404 from django.shortcuts import render_to_response from ocradmin.ocrtasks.models import OcrTask from ocradmin.plugins.manager import ModuleManager import logging logger = logging.getLogger(__name__) import simplejson import tasks def query(request): """ Query plugin info. This returns a list of available OCR engines and an URL that can be queries when one of them is selected. """ stages=request.GET.getlist("stage") return HttpResponse( ModuleManager.get_json(*stages), mimetype="application/json") def runscript(request): """ Execute a script (sent as JSON). """ evalnode = request.POST.get("node", "") jsondata = request.POST.get("script", simplejson.dumps({"arse":"spaz"})) script = simplejson.loads(jsondata) async = OcrTask.run_celery_task("run.script", evalnode, script, untracked=True, asyncronous=True, queue="interactive") out = dict( node=evalnode, task_id=async.task_id, status=async.status, results=async.result ) return HttpResponse(simplejson.dumps(out), mimetype="application/json")
Include the eval'd node type in the async return
Include the eval'd node type in the async return
Python
apache-2.0
vitorio/ocropodium,vitorio/ocropodium,vitorio/ocropodium,vitorio/ocropodium
python
## Code Before: from django.http import HttpResponse, HttpResponseRedirect, Http404 from django.shortcuts import render_to_response from ocradmin.ocrtasks.models import OcrTask from ocradmin.plugins.manager import ModuleManager import logging logger = logging.getLogger(__name__) import simplejson import tasks def query(request): """ Query plugin info. This returns a list of available OCR engines and an URL that can be queries when one of them is selected. """ stages=request.GET.getlist("stage") return HttpResponse( ModuleManager.get_json(*stages), mimetype="application/json") def runscript(request): """ Execute a script (sent as JSON). """ evalnode = request.POST.get("node", "") jsondata = request.POST.get("script", simplejson.dumps({"arse":"spaz"})) script = simplejson.loads(jsondata) async = OcrTask.run_celery_task("run.script", evalnode, script, untracked=True, asyncronous=True, queue="interactive") out = dict(task_id=async.task_id, status=async.status, results=async.result) return HttpResponse(simplejson.dumps(out), mimetype="application/json") ## Instruction: Include the eval'd node type in the async return ## Code After: from django.http import HttpResponse, HttpResponseRedirect, Http404 from django.shortcuts import render_to_response from ocradmin.ocrtasks.models import OcrTask from ocradmin.plugins.manager import ModuleManager import logging logger = logging.getLogger(__name__) import simplejson import tasks def query(request): """ Query plugin info. This returns a list of available OCR engines and an URL that can be queries when one of them is selected. """ stages=request.GET.getlist("stage") return HttpResponse( ModuleManager.get_json(*stages), mimetype="application/json") def runscript(request): """ Execute a script (sent as JSON). """ evalnode = request.POST.get("node", "") jsondata = request.POST.get("script", simplejson.dumps({"arse":"spaz"})) script = simplejson.loads(jsondata) async = OcrTask.run_celery_task("run.script", evalnode, script, untracked=True, asyncronous=True, queue="interactive") out = dict( node=evalnode, task_id=async.task_id, status=async.status, results=async.result ) return HttpResponse(simplejson.dumps(out), mimetype="application/json")
# ... existing code ... async = OcrTask.run_celery_task("run.script", evalnode, script, untracked=True, asyncronous=True, queue="interactive") out = dict( node=evalnode, task_id=async.task_id, status=async.status, results=async.result ) return HttpResponse(simplejson.dumps(out), mimetype="application/json") # ... rest of the code ...
e52d780b15e43ce7bade0b662284fad28f0fba83
setup.py
setup.py
from os.path import isfile, join import glob import os import re from setuptools import setup if isfile("MANIFEST"): os.unlink("MANIFEST") VERSION = re.search('__version__ = "([^"]+)"', open("dateutil/__init__.py").read()).group(1) setup(name="python-dateutil", version = VERSION, description = "Extensions to the standard python 2.3+ datetime module", author = "Gustavo Niemeyer", author_email = "[email protected]", url = "http://labix.org/python-dateutil", license = "PSF License", long_description = """\ The dateutil module provides powerful extensions to the standard datetime module, available in Python 2.3+. """, packages = ["dateutil", "dateutil.zoneinfo"], package_data={"": ["*.tar.gz"]}, include_package_data=True, )
from os.path import isfile, join import glob import os import re from setuptools import setup if isfile("MANIFEST"): os.unlink("MANIFEST") VERSION = re.search('__version__ = "([^"]+)"', open("dateutil/__init__.py").read()).group(1) setup(name="python-dateutil", version = VERSION, description = "Extensions to the standard python 2.3+ datetime module", author = "Gustavo Niemeyer", author_email = "[email protected]", url = "http://labix.org/python-dateutil", license = "PSF License", long_description = """\ The dateutil module provides powerful extensions to the standard datetime module, available in Python 2.3+. """, packages = ["dateutil", "dateutil.zoneinfo"], package_data={"": ["*.tar.gz"]}, include_package_data=True, zip_safe=False, )
Use zip_safe=False, as suggested by Stephan Richter.
Use zip_safe=False, as suggested by Stephan Richter.
Python
bsd-3-clause
adamgreig/python-dateutil,sprymix/dateutil,pganssle/dateutil-test-codecov,emsoftware/python-dateutil,Bachmann1234/dateutil,jenshnielsen/dateutil,pganssle/dateutil-test-codecov,sprymix/python-dateutil,abalkin/dateutil,mjschultz/dateutil,abalkin/dateutil
python
## Code Before: from os.path import isfile, join import glob import os import re from setuptools import setup if isfile("MANIFEST"): os.unlink("MANIFEST") VERSION = re.search('__version__ = "([^"]+)"', open("dateutil/__init__.py").read()).group(1) setup(name="python-dateutil", version = VERSION, description = "Extensions to the standard python 2.3+ datetime module", author = "Gustavo Niemeyer", author_email = "[email protected]", url = "http://labix.org/python-dateutil", license = "PSF License", long_description = """\ The dateutil module provides powerful extensions to the standard datetime module, available in Python 2.3+. """, packages = ["dateutil", "dateutil.zoneinfo"], package_data={"": ["*.tar.gz"]}, include_package_data=True, ) ## Instruction: Use zip_safe=False, as suggested by Stephan Richter. ## Code After: from os.path import isfile, join import glob import os import re from setuptools import setup if isfile("MANIFEST"): os.unlink("MANIFEST") VERSION = re.search('__version__ = "([^"]+)"', open("dateutil/__init__.py").read()).group(1) setup(name="python-dateutil", version = VERSION, description = "Extensions to the standard python 2.3+ datetime module", author = "Gustavo Niemeyer", author_email = "[email protected]", url = "http://labix.org/python-dateutil", license = "PSF License", long_description = """\ The dateutil module provides powerful extensions to the standard datetime module, available in Python 2.3+. """, packages = ["dateutil", "dateutil.zoneinfo"], package_data={"": ["*.tar.gz"]}, include_package_data=True, zip_safe=False, )
... packages = ["dateutil", "dateutil.zoneinfo"], package_data={"": ["*.tar.gz"]}, include_package_data=True, zip_safe=False, ) ...
b2e743a19f13c898b2d95595a7a7175eca4bdb2c
results/urls.py
results/urls.py
__author__ = 'ankesh' from django.conf.urls import patterns, url import views urlpatterns = patterns('', url(r'^(?P<filename>[a-zA-Z0-9]+)/$', views.show_result, name='showResult'), url(r'^compare/(?P<filename>[a-zA-Z0-9]+)/$', views.compare_result, name='compareResult'), )
__author__ = 'ankesh' from django.conf.urls import patterns, url import views urlpatterns = patterns('', url(r'^(?P<filename>[a-zA-Z0-9]+)/$', views.show_result, name='showResult'), url(r'^compare/(?P<filename>[a-zA-Z0-9]+)/$', views.compare_result, name='compareResult'), url(r'^recent/$', views.recent_results, name='recentResults'), )
Update URLs to include recent results
Update URLs to include recent results
Python
bsd-2-clause
ankeshanand/benchmark,ankeshanand/benchmark,ankeshanand/benchmark,ankeshanand/benchmark
python
## Code Before: __author__ = 'ankesh' from django.conf.urls import patterns, url import views urlpatterns = patterns('', url(r'^(?P<filename>[a-zA-Z0-9]+)/$', views.show_result, name='showResult'), url(r'^compare/(?P<filename>[a-zA-Z0-9]+)/$', views.compare_result, name='compareResult'), ) ## Instruction: Update URLs to include recent results ## Code After: __author__ = 'ankesh' from django.conf.urls import patterns, url import views urlpatterns = patterns('', url(r'^(?P<filename>[a-zA-Z0-9]+)/$', views.show_result, name='showResult'), url(r'^compare/(?P<filename>[a-zA-Z0-9]+)/$', views.compare_result, name='compareResult'), url(r'^recent/$', views.recent_results, name='recentResults'), )
# ... existing code ... urlpatterns = patterns('', url(r'^(?P<filename>[a-zA-Z0-9]+)/$', views.show_result, name='showResult'), url(r'^compare/(?P<filename>[a-zA-Z0-9]+)/$', views.compare_result, name='compareResult'), url(r'^recent/$', views.recent_results, name='recentResults'), ) # ... rest of the code ...
848723c943cfb8995c6f2a68ea19b203c75e4aaa
tests/test_scan.py
tests/test_scan.py
try: import unittest.mock as mock except ImportError: import mock import unittest try: from StringIO import StringIO except ImportError: from io import StringIO from nessusapi.scan import Scan from nessusapi.session import Session class SessionTestCase(unittest.TestCase): def test_init(self): fake_session = mock.MagicMock(Session) fake_session.request.return_value = {'uuid': 'e3b4f63f-de03-ec8b'} scan = Scan('192.0.2.9', 'TestScan', '5', fake_session) self.assertEqual(scan.uuid, 'e3b4f63f-de03-ec8b') fake_session.request.assert_called_with('scan/new', target='192.0.2.9', scan_name='TestScan', policy_id='5') if __name__ == '__main__': unittest.main()
try: import unittest.mock as mock except ImportError: import mock import unittest import nessusapi.scan class TestScan(unittest.TestCase): def test_init(self): fake_nessus = mock.Mock(request_single= mock.Mock(return_value='e3b4f63f-de03-ec8b')) scan = nessusapi.scan.Scan(fake_nessus,'192.0.2.9', 'TestScan', 5) self.assertEqual(scan.uuid, 'e3b4f63f-de03-ec8b') fake_nessus.request_single.assert_called_with('scan/new', 'scan', 'uuid', target='192.0.2.9', scan_name='TestScan', policy_id=5) if __name__ == '__main__': unittest.main()
Update test scan to work for new model
Update test scan to work for new model
Python
mit
sait-berkeley-infosec/pynessus-api
python
## Code Before: try: import unittest.mock as mock except ImportError: import mock import unittest try: from StringIO import StringIO except ImportError: from io import StringIO from nessusapi.scan import Scan from nessusapi.session import Session class SessionTestCase(unittest.TestCase): def test_init(self): fake_session = mock.MagicMock(Session) fake_session.request.return_value = {'uuid': 'e3b4f63f-de03-ec8b'} scan = Scan('192.0.2.9', 'TestScan', '5', fake_session) self.assertEqual(scan.uuid, 'e3b4f63f-de03-ec8b') fake_session.request.assert_called_with('scan/new', target='192.0.2.9', scan_name='TestScan', policy_id='5') if __name__ == '__main__': unittest.main() ## Instruction: Update test scan to work for new model ## Code After: try: import unittest.mock as mock except ImportError: import mock import unittest import nessusapi.scan class TestScan(unittest.TestCase): def test_init(self): fake_nessus = mock.Mock(request_single= mock.Mock(return_value='e3b4f63f-de03-ec8b')) scan = nessusapi.scan.Scan(fake_nessus,'192.0.2.9', 'TestScan', 5) self.assertEqual(scan.uuid, 'e3b4f63f-de03-ec8b') fake_nessus.request_single.assert_called_with('scan/new', 'scan', 'uuid', target='192.0.2.9', scan_name='TestScan', policy_id=5) if __name__ == '__main__': unittest.main()
# ... existing code ... import unittest.mock as mock except ImportError: import mock import unittest import nessusapi.scan class TestScan(unittest.TestCase): def test_init(self): fake_nessus = mock.Mock(request_single= mock.Mock(return_value='e3b4f63f-de03-ec8b')) scan = nessusapi.scan.Scan(fake_nessus,'192.0.2.9', 'TestScan', 5) self.assertEqual(scan.uuid, 'e3b4f63f-de03-ec8b') fake_nessus.request_single.assert_called_with('scan/new', 'scan', 'uuid', target='192.0.2.9', scan_name='TestScan', policy_id=5) if __name__ == '__main__': unittest.main() # ... rest of the code ...
be1c6845230a94cb10e52d5c12e11bdee2137d97
src/bakatxt/core/BakaTxtMain.java
src/bakatxt/core/BakaTxtMain.java
package bakatxt.core; import java.awt.GraphicsEnvironment; import java.util.LinkedList; import java.util.Scanner; import bakatxt.gui.BakaUI; public class BakaTxtMain { private static final String MESSAGE_WELCOME = "Welcome To BakaTxt!"; private static final String MESSAGE_BYEBYE = "Bye bye!"; private static final String MESSAGE_ENTER_COMMAND = "Please enter command: "; private static final String MESSAGE_INVALID_COMMAND = "Invalid Command!"; private static Scanner _sc; private static BakaParser _parser; private static Database _database; private static LinkedList<Task> _displayTasks; private static BakaProcessor _processor; public BakaTxtMain() { _sc = new Scanner(System.in); _parser = BakaParser.getInstance(); _database = Database.getInstance(); _displayTasks = _database.getAllTasks(); _processor = new BakaProcessor(); } public static void main(String[] args) { if (GraphicsEnvironment.isHeadless()) { BakaTxtMain thisSession = new BakaTxtMain(); System.out.println(MESSAGE_WELCOME); while (true) { System.out.print(MESSAGE_ENTER_COMMAND); String input = _sc.nextLine(); String result = _processor.executeCommand(input); System.out.println(result); } } BakaUI.startGui(); } }
package bakatxt.core; import java.awt.GraphicsEnvironment; import java.util.Scanner; import bakatxt.gui.BakaUI; public class BakaTxtMain { private static Scanner _sc; private static BakaProcessor _processor; public BakaTxtMain() { _sc = new Scanner(System.in); _processor = new BakaProcessor(); } public static void main(String[] args) { if (GraphicsEnvironment.isHeadless()) { BakaTxtMain thisSession = new BakaTxtMain(); while (true) { String input = _sc.nextLine(); String result = _processor.executeCommand(input); System.out.println(result); } } BakaUI.startGui(); } }
Remove unused command line interface messages and instances in the main
Remove unused command line interface messages and instances in the main
Java
mit
cs2103aug2014-t09-4j/main
java
## Code Before: package bakatxt.core; import java.awt.GraphicsEnvironment; import java.util.LinkedList; import java.util.Scanner; import bakatxt.gui.BakaUI; public class BakaTxtMain { private static final String MESSAGE_WELCOME = "Welcome To BakaTxt!"; private static final String MESSAGE_BYEBYE = "Bye bye!"; private static final String MESSAGE_ENTER_COMMAND = "Please enter command: "; private static final String MESSAGE_INVALID_COMMAND = "Invalid Command!"; private static Scanner _sc; private static BakaParser _parser; private static Database _database; private static LinkedList<Task> _displayTasks; private static BakaProcessor _processor; public BakaTxtMain() { _sc = new Scanner(System.in); _parser = BakaParser.getInstance(); _database = Database.getInstance(); _displayTasks = _database.getAllTasks(); _processor = new BakaProcessor(); } public static void main(String[] args) { if (GraphicsEnvironment.isHeadless()) { BakaTxtMain thisSession = new BakaTxtMain(); System.out.println(MESSAGE_WELCOME); while (true) { System.out.print(MESSAGE_ENTER_COMMAND); String input = _sc.nextLine(); String result = _processor.executeCommand(input); System.out.println(result); } } BakaUI.startGui(); } } ## Instruction: Remove unused command line interface messages and instances in the main ## Code After: package bakatxt.core; import java.awt.GraphicsEnvironment; import java.util.Scanner; import bakatxt.gui.BakaUI; public class BakaTxtMain { private static Scanner _sc; private static BakaProcessor _processor; public BakaTxtMain() { _sc = new Scanner(System.in); _processor = new BakaProcessor(); } public static void main(String[] args) { if (GraphicsEnvironment.isHeadless()) { BakaTxtMain thisSession = new BakaTxtMain(); while (true) { String input = _sc.nextLine(); String result = _processor.executeCommand(input); System.out.println(result); } } BakaUI.startGui(); } }
... package bakatxt.core; import java.awt.GraphicsEnvironment; import java.util.Scanner; import bakatxt.gui.BakaUI; ... public class BakaTxtMain { private static Scanner _sc; private static BakaProcessor _processor; public BakaTxtMain() { _sc = new Scanner(System.in); _processor = new BakaProcessor(); } ... if (GraphicsEnvironment.isHeadless()) { BakaTxtMain thisSession = new BakaTxtMain(); while (true) { String input = _sc.nextLine(); String result = _processor.executeCommand(input); System.out.println(result); ...
6421543ff423fc110cd660850f55f7097db5805d
contrib/performance/setbackend.py
contrib/performance/setbackend.py
import sys from xml.etree import ElementTree from xml.etree import ElementPath def main(): conf = ElementTree.parse(file(sys.argv[1])) if sys.argv[2] == 'postgresql': value = 'true' elif sys.argv[2] == 'filesystem': value = 'false' else: raise RuntimeError("Don't know what to do with %r" % (sys.argv[2],)) replace(conf.getiterator(), value) conf.write(sys.stdout) def replace(elements, value): found = False for ele in elements: if found: ele.tag = value return if ele.tag == 'key' and ele.text == 'UseDatabase': found = True raise RuntimeError("Failed to find <key>UseDatabase</key>")
import sys from xml.etree import ElementTree from xml.etree import ElementPath def main(): conf = ElementTree.parse(file(sys.argv[1])) if sys.argv[2] == 'postgresql': value = 'true' elif sys.argv[2] == 'filesystem': value = 'false' else: raise RuntimeError("Don't know what to do with %r" % (sys.argv[2],)) # Here are the config changes we make - use the specified backend replace(conf.getiterator(), 'UseDatabase', value) # - and disable the response cache replace(conf.getiterator(), 'EnableResponseCache', 'false') conf.write(sys.stdout) def replace(elements, key, value): found = False for ele in elements: if found: ele.tag = value return if ele.tag == 'key' and ele.text == key: found = True raise RuntimeError("Failed to find <key>UseDatabase</key>")
Rewrite the config to disable the response cache, too.
Rewrite the config to disable the response cache, too. git-svn-id: 81e381228600e5752b80483efd2b45b26c451ea2@6929 e27351fd-9f3e-4f54-a53b-843176b1656c
Python
apache-2.0
trevor/calendarserver,trevor/calendarserver,trevor/calendarserver
python
## Code Before: import sys from xml.etree import ElementTree from xml.etree import ElementPath def main(): conf = ElementTree.parse(file(sys.argv[1])) if sys.argv[2] == 'postgresql': value = 'true' elif sys.argv[2] == 'filesystem': value = 'false' else: raise RuntimeError("Don't know what to do with %r" % (sys.argv[2],)) replace(conf.getiterator(), value) conf.write(sys.stdout) def replace(elements, value): found = False for ele in elements: if found: ele.tag = value return if ele.tag == 'key' and ele.text == 'UseDatabase': found = True raise RuntimeError("Failed to find <key>UseDatabase</key>") ## Instruction: Rewrite the config to disable the response cache, too. git-svn-id: 81e381228600e5752b80483efd2b45b26c451ea2@6929 e27351fd-9f3e-4f54-a53b-843176b1656c ## Code After: import sys from xml.etree import ElementTree from xml.etree import ElementPath def main(): conf = ElementTree.parse(file(sys.argv[1])) if sys.argv[2] == 'postgresql': value = 'true' elif sys.argv[2] == 'filesystem': value = 'false' else: raise RuntimeError("Don't know what to do with %r" % (sys.argv[2],)) # Here are the config changes we make - use the specified backend replace(conf.getiterator(), 'UseDatabase', value) # - and disable the response cache replace(conf.getiterator(), 'EnableResponseCache', 'false') conf.write(sys.stdout) def replace(elements, key, value): found = False for ele in elements: if found: ele.tag = value return if ele.tag == 'key' and ele.text == key: found = True raise RuntimeError("Failed to find <key>UseDatabase</key>")
... value = 'false' else: raise RuntimeError("Don't know what to do with %r" % (sys.argv[2],)) # Here are the config changes we make - use the specified backend replace(conf.getiterator(), 'UseDatabase', value) # - and disable the response cache replace(conf.getiterator(), 'EnableResponseCache', 'false') conf.write(sys.stdout) def replace(elements, key, value): found = False for ele in elements: if found: ele.tag = value return if ele.tag == 'key' and ele.text == key: found = True raise RuntimeError("Failed to find <key>UseDatabase</key>") ...
659d917acd2f5da137e506784acc3862225e7dad
Classes/NAPlaybackIndicatorView.h
Classes/NAPlaybackIndicatorView.h
// // NAPlaybackIndicatorView.h // PlaybackIndicator // // Created by Yuji Nakayama on 1/27/14. // Copyright (c) 2014 Yuji Nakayama. All rights reserved. // #import <UIKit/UIKit.h> @interface NAPlaybackIndicatorView : UIView - (void)startAnimating; - (void)stopAnimating; @property (nonatomic, readonly, getter=isAnimating) BOOL animating; @end
// // NAPlaybackIndicatorView.h // PlaybackIndicator // // Created by Yuji Nakayama on 1/27/14. // Copyright (c) 2014 Yuji Nakayama. All rights reserved. // #import <UIKit/UIKit.h> @interface NAPlaybackIndicatorView : UIView /** Starts the oscillating animation of the bars. */ - (void)startAnimating; /** Stop the oscillating animation of the bars. */ - (void)stopAnimating; /** Whether the receiver is animating. */ @property (nonatomic, readonly, getter=isAnimating) BOOL animating; @end
Add documentation comments for method
Add documentation comments for method
C
mit
yujinakayama/NAKPlaybackIndicatorView
c
## Code Before: // // NAPlaybackIndicatorView.h // PlaybackIndicator // // Created by Yuji Nakayama on 1/27/14. // Copyright (c) 2014 Yuji Nakayama. All rights reserved. // #import <UIKit/UIKit.h> @interface NAPlaybackIndicatorView : UIView - (void)startAnimating; - (void)stopAnimating; @property (nonatomic, readonly, getter=isAnimating) BOOL animating; @end ## Instruction: Add documentation comments for method ## Code After: // // NAPlaybackIndicatorView.h // PlaybackIndicator // // Created by Yuji Nakayama on 1/27/14. // Copyright (c) 2014 Yuji Nakayama. All rights reserved. // #import <UIKit/UIKit.h> @interface NAPlaybackIndicatorView : UIView /** Starts the oscillating animation of the bars. */ - (void)startAnimating; /** Stop the oscillating animation of the bars. */ - (void)stopAnimating; /** Whether the receiver is animating. */ @property (nonatomic, readonly, getter=isAnimating) BOOL animating; @end
... @interface NAPlaybackIndicatorView : UIView /** Starts the oscillating animation of the bars. */ - (void)startAnimating; /** Stop the oscillating animation of the bars. */ - (void)stopAnimating; /** Whether the receiver is animating. */ @property (nonatomic, readonly, getter=isAnimating) BOOL animating; @end ...
ba62f0d82dda609e9e01b84797944e9d18a989eb
KBSCloudApp.h
KBSCloudApp.h
// // KBSCloudApp.h // // Created by Keith Smiley // Copyright (c) 2013 Keith Smiley. All rights reserved. // #ifndef _KBSCLOUDAPP_ #define _KBSCLOUDAPP_ #import "KBSCloudAppUser.h" #import "KBSCloudAppAPI.h" NS_ENUM(NSInteger, KBSCloudAppAPIErrorCode) { KBSCloudAppNoUserOrPass, KBSCloudAppAPIInvalidUser, KBSCloudAppInternalError }; static NSString * const KBSCloudAppAPIErrorDomain = @"com.keithsmiley.cloudappapi"; static NSString * const baseAPI = @"http://my.cl.ly/"; static NSString * const baseShortURL = @"cl.ly"; static NSString * const itemsPath = @"items"; static NSString * const accountPath = @"account"; #endif
// // KBSCloudApp.h // // Created by Keith Smiley // Copyright (c) 2013 Keith Smiley. All rights reserved. // #ifndef _KBSCLOUDAPP_ #define _KBSCLOUDAPP_ #import "KBSCloudAppUser.h" #import "KBSCloudAppAPI.h" #import "KBSCloudAppURL.h" NS_ENUM(NSInteger, KBSCloudAppAPIErrorCode) { KBSCloudAppNoUserOrPass, KBSCloudAppAPIInvalidUser, KBSCloudAppInternalError }; static NSString * const KBSCloudAppAPIErrorDomain = @"com.keithsmiley.cloudappapi"; static NSString * const baseAPI = @"http://my.cl.ly/"; static NSString * const baseShortURL = @"cl.ly"; static NSString * const itemsPath = @"items"; static NSString * const accountPath = @"account"; #endif
Include URL in common includes
Include URL in common includes
C
mit
keith/KBSCloudAppAPI
c
## Code Before: // // KBSCloudApp.h // // Created by Keith Smiley // Copyright (c) 2013 Keith Smiley. All rights reserved. // #ifndef _KBSCLOUDAPP_ #define _KBSCLOUDAPP_ #import "KBSCloudAppUser.h" #import "KBSCloudAppAPI.h" NS_ENUM(NSInteger, KBSCloudAppAPIErrorCode) { KBSCloudAppNoUserOrPass, KBSCloudAppAPIInvalidUser, KBSCloudAppInternalError }; static NSString * const KBSCloudAppAPIErrorDomain = @"com.keithsmiley.cloudappapi"; static NSString * const baseAPI = @"http://my.cl.ly/"; static NSString * const baseShortURL = @"cl.ly"; static NSString * const itemsPath = @"items"; static NSString * const accountPath = @"account"; #endif ## Instruction: Include URL in common includes ## Code After: // // KBSCloudApp.h // // Created by Keith Smiley // Copyright (c) 2013 Keith Smiley. All rights reserved. // #ifndef _KBSCLOUDAPP_ #define _KBSCLOUDAPP_ #import "KBSCloudAppUser.h" #import "KBSCloudAppAPI.h" #import "KBSCloudAppURL.h" NS_ENUM(NSInteger, KBSCloudAppAPIErrorCode) { KBSCloudAppNoUserOrPass, KBSCloudAppAPIInvalidUser, KBSCloudAppInternalError }; static NSString * const KBSCloudAppAPIErrorDomain = @"com.keithsmiley.cloudappapi"; static NSString * const baseAPI = @"http://my.cl.ly/"; static NSString * const baseShortURL = @"cl.ly"; static NSString * const itemsPath = @"items"; static NSString * const accountPath = @"account"; #endif
... #import "KBSCloudAppUser.h" #import "KBSCloudAppAPI.h" #import "KBSCloudAppURL.h" NS_ENUM(NSInteger, KBSCloudAppAPIErrorCode) { KBSCloudAppNoUserOrPass, ...
1570a9789530d83c373bd1ac7140b00be78288d9
gstrap-gae-test/src/main/java/com/voodoodyne/gstrap/gae/test/GAEExtension.java
gstrap-gae-test/src/main/java/com/voodoodyne/gstrap/gae/test/GAEExtension.java
package com.voodoodyne.gstrap.gae.test; import com.voodoodyne.gstrap.test.util.TestInfoContextAdapter; import org.junit.jupiter.api.extension.AfterEachCallback; import org.junit.jupiter.api.extension.BeforeEachCallback; import org.junit.jupiter.api.extension.ExtensionContext; import org.junit.jupiter.api.extension.ExtensionContext.Namespace; /** */ public class GAEExtension implements BeforeEachCallback, AfterEachCallback { private static final Namespace NAMESPACE = Namespace.create(GAEExtension.class); @Override public void beforeEach(final ExtensionContext context) throws Exception { final GAEHelper helper = new GAEHelper(); context.getStore(NAMESPACE).put(GAEHelper.class, helper); helper.setUp(new TestInfoContextAdapter(context)); } @Override public void afterEach(final ExtensionContext context) throws Exception { final GAEHelper helper = context.getStore(NAMESPACE).get(GAEHelper.class, GAEHelper.class); helper.tearDown(); } }
package com.voodoodyne.gstrap.gae.test; import com.voodoodyne.gstrap.test.util.TestInfoContextAdapter; import org.junit.jupiter.api.extension.AfterEachCallback; import org.junit.jupiter.api.extension.BeforeEachCallback; import org.junit.jupiter.api.extension.ExtensionContext; import org.junit.jupiter.api.extension.ExtensionContext.Namespace; import org.junit.jupiter.api.extension.ExtensionContext.Store; /** */ public class GAEExtension implements BeforeEachCallback, AfterEachCallback { private static final Namespace NAMESPACE = Namespace.create(GAEExtension.class); /** Key in the store for the queue xml path. If not set, the maven default is used. */ private static final String QUEUE_XML_PATH = "queueXmlPath"; /** Optionally override the queue xml path for the GAEHelper */ public static void setQueueXmlPath(final ExtensionContext context, final String path) { context.getStore(NAMESPACE).put(QUEUE_XML_PATH, path); } @Override public void beforeEach(final ExtensionContext context) throws Exception { final Store store = context.getStore(NAMESPACE); final String queueXmlPath = store.get(QUEUE_XML_PATH, String.class); final GAEHelper helper = queueXmlPath == null ? new GAEHelper() : new GAEHelper(queueXmlPath); store.put(GAEHelper.class, helper); helper.setUp(new TestInfoContextAdapter(context)); } @Override public void afterEach(final ExtensionContext context) throws Exception { final GAEHelper helper = context.getStore(NAMESPACE).get(GAEHelper.class, GAEHelper.class); helper.tearDown(); } }
Allow queue xml path to be set by prior extensions
Allow queue xml path to be set by prior extensions
Java
mit
stickfigure/gstrap-gae
java
## Code Before: package com.voodoodyne.gstrap.gae.test; import com.voodoodyne.gstrap.test.util.TestInfoContextAdapter; import org.junit.jupiter.api.extension.AfterEachCallback; import org.junit.jupiter.api.extension.BeforeEachCallback; import org.junit.jupiter.api.extension.ExtensionContext; import org.junit.jupiter.api.extension.ExtensionContext.Namespace; /** */ public class GAEExtension implements BeforeEachCallback, AfterEachCallback { private static final Namespace NAMESPACE = Namespace.create(GAEExtension.class); @Override public void beforeEach(final ExtensionContext context) throws Exception { final GAEHelper helper = new GAEHelper(); context.getStore(NAMESPACE).put(GAEHelper.class, helper); helper.setUp(new TestInfoContextAdapter(context)); } @Override public void afterEach(final ExtensionContext context) throws Exception { final GAEHelper helper = context.getStore(NAMESPACE).get(GAEHelper.class, GAEHelper.class); helper.tearDown(); } } ## Instruction: Allow queue xml path to be set by prior extensions ## Code After: package com.voodoodyne.gstrap.gae.test; import com.voodoodyne.gstrap.test.util.TestInfoContextAdapter; import org.junit.jupiter.api.extension.AfterEachCallback; import org.junit.jupiter.api.extension.BeforeEachCallback; import org.junit.jupiter.api.extension.ExtensionContext; import org.junit.jupiter.api.extension.ExtensionContext.Namespace; import org.junit.jupiter.api.extension.ExtensionContext.Store; /** */ public class GAEExtension implements BeforeEachCallback, AfterEachCallback { private static final Namespace NAMESPACE = Namespace.create(GAEExtension.class); /** Key in the store for the queue xml path. If not set, the maven default is used. */ private static final String QUEUE_XML_PATH = "queueXmlPath"; /** Optionally override the queue xml path for the GAEHelper */ public static void setQueueXmlPath(final ExtensionContext context, final String path) { context.getStore(NAMESPACE).put(QUEUE_XML_PATH, path); } @Override public void beforeEach(final ExtensionContext context) throws Exception { final Store store = context.getStore(NAMESPACE); final String queueXmlPath = store.get(QUEUE_XML_PATH, String.class); final GAEHelper helper = queueXmlPath == null ? new GAEHelper() : new GAEHelper(queueXmlPath); store.put(GAEHelper.class, helper); helper.setUp(new TestInfoContextAdapter(context)); } @Override public void afterEach(final ExtensionContext context) throws Exception { final GAEHelper helper = context.getStore(NAMESPACE).get(GAEHelper.class, GAEHelper.class); helper.tearDown(); } }
// ... existing code ... import org.junit.jupiter.api.extension.BeforeEachCallback; import org.junit.jupiter.api.extension.ExtensionContext; import org.junit.jupiter.api.extension.ExtensionContext.Namespace; import org.junit.jupiter.api.extension.ExtensionContext.Store; /** */ // ... modified code ... private static final Namespace NAMESPACE = Namespace.create(GAEExtension.class); /** Key in the store for the queue xml path. If not set, the maven default is used. */ private static final String QUEUE_XML_PATH = "queueXmlPath"; /** Optionally override the queue xml path for the GAEHelper */ public static void setQueueXmlPath(final ExtensionContext context, final String path) { context.getStore(NAMESPACE).put(QUEUE_XML_PATH, path); } @Override public void beforeEach(final ExtensionContext context) throws Exception { final Store store = context.getStore(NAMESPACE); final String queueXmlPath = store.get(QUEUE_XML_PATH, String.class); final GAEHelper helper = queueXmlPath == null ? new GAEHelper() : new GAEHelper(queueXmlPath); store.put(GAEHelper.class, helper); helper.setUp(new TestInfoContextAdapter(context)); } // ... rest of the code ...
0f6e02313918e8bef44e703a6ca98dadea26f56e
src/main/java/net/shadowfacts/foodies/block/FBlocks.java
src/main/java/net/shadowfacts/foodies/block/FBlocks.java
package net.shadowfacts.foodies.block; /** * Helper class for registering blocks. * @author shadowfacts */ public class FBlocks { }
package net.shadowfacts.foodies.block; /** * Helper class for registering blocks. * @author shadowfacts */ public class FBlocks { public static void preInit() { } public static void load() { } public static void postInit() { } }
Add helper methods for block helper class
Add helper methods for block helper class
Java
lgpl-2.1
shadowfacts/Foodies
java
## Code Before: package net.shadowfacts.foodies.block; /** * Helper class for registering blocks. * @author shadowfacts */ public class FBlocks { } ## Instruction: Add helper methods for block helper class ## Code After: package net.shadowfacts.foodies.block; /** * Helper class for registering blocks. * @author shadowfacts */ public class FBlocks { public static void preInit() { } public static void load() { } public static void postInit() { } }
// ... existing code ... * @author shadowfacts */ public class FBlocks { public static void preInit() { } public static void load() { } public static void postInit() { } } // ... rest of the code ...
3ea7a61be81c0f2094d8b3b0d3a81dec267ac663
GitSvnServer/client.py
GitSvnServer/client.py
import parse import generate as gen from repos import find_repos from errors import * def parse_client_greeting(msg_str): msg = parse.msg(msg_str) proto_ver = int(msg[0]) client_caps = msg[1] url = parse.string(msg[2]) print "ver: %d" % proto_ver print "caps: %s" % client_caps print "url: %s" % url return proto_ver, client_caps, url def connect(link): link.send_msg(gen.success(2, 2, gen.list('ANONYMOUS'), gen.list('edit-pipeline', 'svndiff1'))) client_resp = link.read_msg() ver, caps, url = parse_client_greeting(client_resp) if ver != 2: raise BadProtoVersion() repos = find_repos(url) if repos is None: link.send_msg(gen.failure(gen.list(210005, gen.string("No repository found in '%s'" % url), gen.string('message.py'), 0))) return url, caps, repos
import parse import generate as gen from repos import find_repos from errors import * server_capabilities = [ 'edit-pipeline', # This is required. 'svndiff1', # We support svndiff1 'absent-entries', # We support absent-dir and absent-dir editor commands #'commit-revprops', # We don't currently have _any_ revprop support #'mergeinfo', # Nope, not yet #'depth', # Nope, not yet ] def parse_client_greeting(msg_str): msg = parse.msg(msg_str) proto_ver = int(msg[0]) client_caps = msg[1] url = parse.string(msg[2]) print "ver: %d" % proto_ver print "caps: %s" % client_caps print "url: %s" % url return proto_ver, client_caps, url def connect(link): # Send the announce message - we only support protocol version 2. link.send_msg(gen.success(2, 2, gen.list(), gen.list(*server_capabilities))) client_resp = link.read_msg() ver, caps, url = parse_client_greeting(client_resp) if ver != 2: raise BadProtoVersion() repos = find_repos(url) if repos is None: link.send_msg(gen.failure(gen.list(210005, gen.string("No repository found in '%s'" % url), gen.string('message.py'), 0))) return url, caps, repos
Sort out the server announce message
Sort out the server announce message Tidy up the server announce message a bit. In particular, we might as well announce the absent-entries capability - we support the commands even if they currently aren't implemented.
Python
bsd-3-clause
slonopotamus/git_svn_server
python
## Code Before: import parse import generate as gen from repos import find_repos from errors import * def parse_client_greeting(msg_str): msg = parse.msg(msg_str) proto_ver = int(msg[0]) client_caps = msg[1] url = parse.string(msg[2]) print "ver: %d" % proto_ver print "caps: %s" % client_caps print "url: %s" % url return proto_ver, client_caps, url def connect(link): link.send_msg(gen.success(2, 2, gen.list('ANONYMOUS'), gen.list('edit-pipeline', 'svndiff1'))) client_resp = link.read_msg() ver, caps, url = parse_client_greeting(client_resp) if ver != 2: raise BadProtoVersion() repos = find_repos(url) if repos is None: link.send_msg(gen.failure(gen.list(210005, gen.string("No repository found in '%s'" % url), gen.string('message.py'), 0))) return url, caps, repos ## Instruction: Sort out the server announce message Tidy up the server announce message a bit. In particular, we might as well announce the absent-entries capability - we support the commands even if they currently aren't implemented. ## Code After: import parse import generate as gen from repos import find_repos from errors import * server_capabilities = [ 'edit-pipeline', # This is required. 'svndiff1', # We support svndiff1 'absent-entries', # We support absent-dir and absent-dir editor commands #'commit-revprops', # We don't currently have _any_ revprop support #'mergeinfo', # Nope, not yet #'depth', # Nope, not yet ] def parse_client_greeting(msg_str): msg = parse.msg(msg_str) proto_ver = int(msg[0]) client_caps = msg[1] url = parse.string(msg[2]) print "ver: %d" % proto_ver print "caps: %s" % client_caps print "url: %s" % url return proto_ver, client_caps, url def connect(link): # Send the announce message - we only support protocol version 2. link.send_msg(gen.success(2, 2, gen.list(), gen.list(*server_capabilities))) client_resp = link.read_msg() ver, caps, url = parse_client_greeting(client_resp) if ver != 2: raise BadProtoVersion() repos = find_repos(url) if repos is None: link.send_msg(gen.failure(gen.list(210005, gen.string("No repository found in '%s'" % url), gen.string('message.py'), 0))) return url, caps, repos
// ... existing code ... import generate as gen from repos import find_repos from errors import * server_capabilities = [ 'edit-pipeline', # This is required. 'svndiff1', # We support svndiff1 'absent-entries', # We support absent-dir and absent-dir editor commands #'commit-revprops', # We don't currently have _any_ revprop support #'mergeinfo', # Nope, not yet #'depth', # Nope, not yet ] def parse_client_greeting(msg_str): msg = parse.msg(msg_str) // ... modified code ... return proto_ver, client_caps, url def connect(link): # Send the announce message - we only support protocol version 2. link.send_msg(gen.success(2, 2, gen.list(), gen.list(*server_capabilities))) client_resp = link.read_msg() // ... rest of the code ...
4583c9949143e58bf400fc86e27d634aa382f605
tests/test_expanded.py
tests/test_expanded.py
from mycli.packages.expanded import expanded_table def test_expanded_table_renders(): input = [("hello", 123), ("world", 456)] expected = """-[ RECORD 0 ] name | hello age | 123 -[ RECORD 1 ] name | world age | 456 """ assert expected == expanded_table(input, ["name", "age"])
from mycli.packages.expanded import expanded_table def test_expanded_table_renders(): input = [("hello", 123), ("world", 456)] expected = """***************************[ 1. row ]*************************** name | hello age | 123 ***************************[ 2. row ]*************************** name | world age | 456 """ assert expected == expanded_table(input, ["name", "age"])
Update expanded tests to match mysql style.
Update expanded tests to match mysql style.
Python
bsd-3-clause
oguzy/mycli,chenpingzhao/mycli,ZuoGuocai/mycli,evook/mycli,jinstrive/mycli,j-bennet/mycli,danieljwest/mycli,suzukaze/mycli,thanatoskira/mycli,chenpingzhao/mycli,j-bennet/mycli,brewneaux/mycli,webwlsong/mycli,MnO2/rediscli,brewneaux/mycli,shoma/mycli,mdsrosa/mycli,oguzy/mycli,danieljwest/mycli,jinstrive/mycli,thanatoskira/mycli,ZuoGuocai/mycli,webwlsong/mycli,evook/mycli,suzukaze/mycli,D-e-e-m-o/mycli,MnO2/rediscli,shoma/mycli,martijnengler/mycli,mdsrosa/mycli,martijnengler/mycli,D-e-e-m-o/mycli
python
## Code Before: from mycli.packages.expanded import expanded_table def test_expanded_table_renders(): input = [("hello", 123), ("world", 456)] expected = """-[ RECORD 0 ] name | hello age | 123 -[ RECORD 1 ] name | world age | 456 """ assert expected == expanded_table(input, ["name", "age"]) ## Instruction: Update expanded tests to match mysql style. ## Code After: from mycli.packages.expanded import expanded_table def test_expanded_table_renders(): input = [("hello", 123), ("world", 456)] expected = """***************************[ 1. row ]*************************** name | hello age | 123 ***************************[ 2. row ]*************************** name | world age | 456 """ assert expected == expanded_table(input, ["name", "age"])
... def test_expanded_table_renders(): input = [("hello", 123), ("world", 456)] expected = """***************************[ 1. row ]*************************** name | hello age | 123 ***************************[ 2. row ]*************************** name | world age | 456 """ ...
ac5b9765d69139915f06bd52d96b1abaa3d41331
scuole/districts/views.py
scuole/districts/views.py
from __future__ import absolute_import, unicode_literals from django.views.generic import DetailView, ListView from .models import District class DistrictListView(ListView): queryset = District.objects.all().select_related('county__name') class DistrictDetailView(DetailView): queryset = District.objects.all().prefetch_related('stats__year') pk_url_kwarg = 'district_id' slug_url_kwarg = 'district_slug'
from __future__ import absolute_import, unicode_literals from django.views.generic import DetailView, ListView from .models import District class DistrictListView(ListView): queryset = District.objects.all().defer('shape') class DistrictDetailView(DetailView): queryset = District.objects.all().prefetch_related('stats__year') pk_url_kwarg = 'district_id' slug_url_kwarg = 'district_slug'
Remove unused select_related, defer the loading of shape for speed
Remove unused select_related, defer the loading of shape for speed
Python
mit
texastribune/scuole,texastribune/scuole,texastribune/scuole,texastribune/scuole
python
## Code Before: from __future__ import absolute_import, unicode_literals from django.views.generic import DetailView, ListView from .models import District class DistrictListView(ListView): queryset = District.objects.all().select_related('county__name') class DistrictDetailView(DetailView): queryset = District.objects.all().prefetch_related('stats__year') pk_url_kwarg = 'district_id' slug_url_kwarg = 'district_slug' ## Instruction: Remove unused select_related, defer the loading of shape for speed ## Code After: from __future__ import absolute_import, unicode_literals from django.views.generic import DetailView, ListView from .models import District class DistrictListView(ListView): queryset = District.objects.all().defer('shape') class DistrictDetailView(DetailView): queryset = District.objects.all().prefetch_related('stats__year') pk_url_kwarg = 'district_id' slug_url_kwarg = 'district_slug'
# ... existing code ... class DistrictListView(ListView): queryset = District.objects.all().defer('shape') class DistrictDetailView(DetailView): # ... rest of the code ...
1dbe023f5c9a7d596fd95114c9afe5d8970722af
robolectric-shadows/shadows-core/src/main/java/org/robolectric/shadows/ShadowConfiguration.java
robolectric-shadows/shadows-core/src/main/java/org/robolectric/shadows/ShadowConfiguration.java
package org.robolectric.shadows; import android.content.res.Configuration; import java.util.Locale; import org.robolectric.annotation.Implementation; import org.robolectric.annotation.Implements; import org.robolectric.annotation.RealObject; import static org.robolectric.shadow.api.Shadow.directlyOn; /** * Shadow for {@link android.content.res.Configuration}. */ @Implements(Configuration.class) public class ShadowConfiguration { }
package org.robolectric.shadows; import android.content.res.Configuration; import java.util.Locale; import org.robolectric.RuntimeEnvironment; import org.robolectric.annotation.Config; import org.robolectric.annotation.Implementation; import org.robolectric.annotation.Implements; import org.robolectric.annotation.RealObject; import static org.robolectric.shadow.api.Shadow.directlyOn; /** * Shadow for {@link android.content.res.Configuration}. * @deprecated This will be removed in Robolectric 3.4 - {@link Configuration} is pure Java so there is no need for a * shadow to exist. The methods have been preserved but marked deprecated to prevent build breakages but in this * version implementation has been modified to simply call through to the Framework code which may in some cases cause * test failures due to the way the shadow diverged in behaviour from the Framework code. Some notes have been added * to help you migrate in these cases. * * Some notes to help you migrate:- * * <ol> * <li>{@link #setLocale} only exists in API 17+ so calling this on earlier APIs will fail with {@link NoSuchMethodException} * <li>{@link #setToDefaults()} overrides the frameworks natural defaults to set the flags for * {@link Configuration#screenLayout} to include {@link Configuration#SCREENLAYOUT_LONG_NO} and * {@link Configuration#SCREENLAYOUT_SIZE_NORMAL} * <li>{@link #overrideQualifiers} and {@link #getQualifiers()} have no effect and can be removed. * </ol> */ @Deprecated @Implements(Configuration.class) public class ShadowConfiguration { @RealObject private Configuration realConfiguration; @Deprecated @Implementation public void setTo(Configuration o) { directlyOn(realConfiguration, Configuration.class).setTo(o); } @Deprecated @Implementation public void setToDefaults() { directlyOn(realConfiguration, Configuration.class).setToDefaults(); } @Deprecated @Implementation public void setLocale( Locale l ) { directlyOn(realConfiguration, Configuration.class).setLocale(l); } @Deprecated public void overrideQualifiers(String qualifiers) { // Never worked. } /** * @deprecated Use {@link RuntimeEnvironment#getQualifiers()} although there should be no reason to obtain this * since it is typically set in tests through {@link Config#qualifiers()} so you should use a constant in these cases. */ @Deprecated public String getQualifiers() { return RuntimeEnvironment.getQualifiers(); } }
Mark the common methods @Deprecated.
Mark the common methods @Deprecated. This avoids build breakages and allows users to upgrade Robolectric without breakges as they migrate. Implementation has been changed to call through by default. In some cases this will result in test failures but this is highly unlikely. In such cases Javadoc has been added to illustrate how the deprecated ShadowConfiguration had diverged from the framework code.
Java
mit
ChengCorp/robolectric,jongerrish/robolectric,spotify/robolectric,spotify/robolectric,cesar1000/robolectric,cesar1000/robolectric,ChengCorp/robolectric,ocadotechnology/robolectric,ocadotechnology/robolectric,ChengCorp/robolectric,jongerrish/robolectric,jongerrish/robolectric,jongerrish/robolectric,cesar1000/robolectric,spotify/robolectric,ocadotechnology/robolectric
java
## Code Before: package org.robolectric.shadows; import android.content.res.Configuration; import java.util.Locale; import org.robolectric.annotation.Implementation; import org.robolectric.annotation.Implements; import org.robolectric.annotation.RealObject; import static org.robolectric.shadow.api.Shadow.directlyOn; /** * Shadow for {@link android.content.res.Configuration}. */ @Implements(Configuration.class) public class ShadowConfiguration { } ## Instruction: Mark the common methods @Deprecated. This avoids build breakages and allows users to upgrade Robolectric without breakges as they migrate. Implementation has been changed to call through by default. In some cases this will result in test failures but this is highly unlikely. In such cases Javadoc has been added to illustrate how the deprecated ShadowConfiguration had diverged from the framework code. ## Code After: package org.robolectric.shadows; import android.content.res.Configuration; import java.util.Locale; import org.robolectric.RuntimeEnvironment; import org.robolectric.annotation.Config; import org.robolectric.annotation.Implementation; import org.robolectric.annotation.Implements; import org.robolectric.annotation.RealObject; import static org.robolectric.shadow.api.Shadow.directlyOn; /** * Shadow for {@link android.content.res.Configuration}. * @deprecated This will be removed in Robolectric 3.4 - {@link Configuration} is pure Java so there is no need for a * shadow to exist. The methods have been preserved but marked deprecated to prevent build breakages but in this * version implementation has been modified to simply call through to the Framework code which may in some cases cause * test failures due to the way the shadow diverged in behaviour from the Framework code. Some notes have been added * to help you migrate in these cases. * * Some notes to help you migrate:- * * <ol> * <li>{@link #setLocale} only exists in API 17+ so calling this on earlier APIs will fail with {@link NoSuchMethodException} * <li>{@link #setToDefaults()} overrides the frameworks natural defaults to set the flags for * {@link Configuration#screenLayout} to include {@link Configuration#SCREENLAYOUT_LONG_NO} and * {@link Configuration#SCREENLAYOUT_SIZE_NORMAL} * <li>{@link #overrideQualifiers} and {@link #getQualifiers()} have no effect and can be removed. * </ol> */ @Deprecated @Implements(Configuration.class) public class ShadowConfiguration { @RealObject private Configuration realConfiguration; @Deprecated @Implementation public void setTo(Configuration o) { directlyOn(realConfiguration, Configuration.class).setTo(o); } @Deprecated @Implementation public void setToDefaults() { directlyOn(realConfiguration, Configuration.class).setToDefaults(); } @Deprecated @Implementation public void setLocale( Locale l ) { directlyOn(realConfiguration, Configuration.class).setLocale(l); } @Deprecated public void overrideQualifiers(String qualifiers) { // Never worked. } /** * @deprecated Use {@link RuntimeEnvironment#getQualifiers()} although there should be no reason to obtain this * since it is typically set in tests through {@link Config#qualifiers()} so you should use a constant in these cases. */ @Deprecated public String getQualifiers() { return RuntimeEnvironment.getQualifiers(); } }
... import android.content.res.Configuration; import java.util.Locale; import org.robolectric.RuntimeEnvironment; import org.robolectric.annotation.Config; import org.robolectric.annotation.Implementation; import org.robolectric.annotation.Implements; import org.robolectric.annotation.RealObject; ... /** * Shadow for {@link android.content.res.Configuration}. * @deprecated This will be removed in Robolectric 3.4 - {@link Configuration} is pure Java so there is no need for a * shadow to exist. The methods have been preserved but marked deprecated to prevent build breakages but in this * version implementation has been modified to simply call through to the Framework code which may in some cases cause * test failures due to the way the shadow diverged in behaviour from the Framework code. Some notes have been added * to help you migrate in these cases. * * Some notes to help you migrate:- * * <ol> * <li>{@link #setLocale} only exists in API 17+ so calling this on earlier APIs will fail with {@link NoSuchMethodException} * <li>{@link #setToDefaults()} overrides the frameworks natural defaults to set the flags for * {@link Configuration#screenLayout} to include {@link Configuration#SCREENLAYOUT_LONG_NO} and * {@link Configuration#SCREENLAYOUT_SIZE_NORMAL} * <li>{@link #overrideQualifiers} and {@link #getQualifiers()} have no effect and can be removed. * </ol> */ @Deprecated @Implements(Configuration.class) public class ShadowConfiguration { @RealObject private Configuration realConfiguration; @Deprecated @Implementation public void setTo(Configuration o) { directlyOn(realConfiguration, Configuration.class).setTo(o); } @Deprecated @Implementation public void setToDefaults() { directlyOn(realConfiguration, Configuration.class).setToDefaults(); } @Deprecated @Implementation public void setLocale( Locale l ) { directlyOn(realConfiguration, Configuration.class).setLocale(l); } @Deprecated public void overrideQualifiers(String qualifiers) { // Never worked. } /** * @deprecated Use {@link RuntimeEnvironment#getQualifiers()} although there should be no reason to obtain this * since it is typically set in tests through {@link Config#qualifiers()} so you should use a constant in these cases. */ @Deprecated public String getQualifiers() { return RuntimeEnvironment.getQualifiers(); } } ...
978dd0161552458331870af0b524cdcff25fd71d
furious/handlers/__init__.py
furious/handlers/__init__.py
import json import logging from ..async import Async from ..processors import run_job def process_async_task(headers, request_body): """Process an Async task and execute the requested function.""" async_options = json.loads(request_body) work = Async.from_dict(async_options) logging.info(work._function_path) run_job(work) return 200, work._function_path
import json import logging from ..async import Async from ..processors import run_job def process_async_task(headers, request_body): """Process an Async task and execute the requested function.""" async_options = json.loads(request_body) async = Async.from_dict(async_options) logging.info(work._function_path) with context.job_context_from_async(async): run_job(async) return 200, work._function_path
Adjust async run handler to use the JobContext manager.
Adjust async run handler to use the JobContext manager.
Python
apache-2.0
mattsanders-wf/furious,beaulyddon-wf/furious,Workiva/furious,andreleblanc-wf/furious,rosshendrickson-wf/furious,andreleblanc-wf/furious,beaulyddon-wf/furious,robertkluin/furious,rosshendrickson-wf/furious,Workiva/furious,mattsanders-wf/furious
python
## Code Before: import json import logging from ..async import Async from ..processors import run_job def process_async_task(headers, request_body): """Process an Async task and execute the requested function.""" async_options = json.loads(request_body) work = Async.from_dict(async_options) logging.info(work._function_path) run_job(work) return 200, work._function_path ## Instruction: Adjust async run handler to use the JobContext manager. ## Code After: import json import logging from ..async import Async from ..processors import run_job def process_async_task(headers, request_body): """Process an Async task and execute the requested function.""" async_options = json.loads(request_body) async = Async.from_dict(async_options) logging.info(work._function_path) with context.job_context_from_async(async): run_job(async) return 200, work._function_path
# ... existing code ... def process_async_task(headers, request_body): """Process an Async task and execute the requested function.""" async_options = json.loads(request_body) async = Async.from_dict(async_options) logging.info(work._function_path) with context.job_context_from_async(async): run_job(async) return 200, work._function_path # ... rest of the code ...
9bc5ec59224116e2092f0c2e02831c8276360910
providers/output/terminal.py
providers/output/terminal.py
from __future__ import print_function import textwrap from providers.output.provider import OutputProvider IDENTIFIER = "Terminal" class Provider(OutputProvider): def process_data(self, movie_data): movie_data = filter(lambda data: data.get("filmtipset_my_grade_type", "none") != "seen", movie_data) movie_data = sorted(movie_data, key=lambda data: data.get("filmtipset_my_grade", 0), reverse=True) return movie_data def output(self, movie_data): movie_data = self.process_data(movie_data) print() for data in movie_data[:10]: print("%s (Filmtipset: %s, IMDB: %s)" % ( data["title"], data.get("filmtipset_my_grade", "-"), data.get("imdb_rating", "-"), )) print(" [Genre: %s, Country: %s, Year: %s]" % ( ", ".join(data.get("genre", "-")), data.get("country", "-"), data.get("year", "-"), )) plot = data.get("plot", None) if plot: text = textwrap.wrap('Plot: "' + data.get("plot", "-") + '"', width=80, initial_indent=" ", subsequent_indent=" ") print("\n".join(text)) print()
from __future__ import print_function import textwrap from providers.output.provider import OutputProvider IDENTIFIER = "Terminal" class Provider(OutputProvider): def process_data(self, movie_data): movie_data = filter(lambda data: data.get("filmtipset_my_grade_type", "none") != "seen", movie_data) movie_data = sorted(movie_data, key=lambda data: (data.get("filmtipset_my_grade", 0), data.get("imdb_rating", 0)), reverse=True) return movie_data def output(self, movie_data): movie_data = self.process_data(movie_data) print() for data in movie_data[:10]: print("%s (Filmtipset: %s, IMDB: %s)" % ( data["title"], data.get("filmtipset_my_grade", "-"), data.get("imdb_rating", "-"), )) print(" [Genre: %s, Country: %s, Year: %s]" % ( ", ".join(data.get("genre", "-")), data.get("country", "-"), data.get("year", "-"), )) plot = data.get("plot", None) if plot: text = textwrap.wrap('Plot: "' + data.get("plot", "-") + '"', width=80, initial_indent=" ", subsequent_indent=" ") print("\n".join(text)) print()
Sort on imdb rating if filmtipset ratings are the same.
Sort on imdb rating if filmtipset ratings are the same.
Python
mit
EmilStenstrom/nephele
python
## Code Before: from __future__ import print_function import textwrap from providers.output.provider import OutputProvider IDENTIFIER = "Terminal" class Provider(OutputProvider): def process_data(self, movie_data): movie_data = filter(lambda data: data.get("filmtipset_my_grade_type", "none") != "seen", movie_data) movie_data = sorted(movie_data, key=lambda data: data.get("filmtipset_my_grade", 0), reverse=True) return movie_data def output(self, movie_data): movie_data = self.process_data(movie_data) print() for data in movie_data[:10]: print("%s (Filmtipset: %s, IMDB: %s)" % ( data["title"], data.get("filmtipset_my_grade", "-"), data.get("imdb_rating", "-"), )) print(" [Genre: %s, Country: %s, Year: %s]" % ( ", ".join(data.get("genre", "-")), data.get("country", "-"), data.get("year", "-"), )) plot = data.get("plot", None) if plot: text = textwrap.wrap('Plot: "' + data.get("plot", "-") + '"', width=80, initial_indent=" ", subsequent_indent=" ") print("\n".join(text)) print() ## Instruction: Sort on imdb rating if filmtipset ratings are the same. ## Code After: from __future__ import print_function import textwrap from providers.output.provider import OutputProvider IDENTIFIER = "Terminal" class Provider(OutputProvider): def process_data(self, movie_data): movie_data = filter(lambda data: data.get("filmtipset_my_grade_type", "none") != "seen", movie_data) movie_data = sorted(movie_data, key=lambda data: (data.get("filmtipset_my_grade", 0), data.get("imdb_rating", 0)), reverse=True) return movie_data def output(self, movie_data): movie_data = self.process_data(movie_data) print() for data in movie_data[:10]: print("%s (Filmtipset: %s, IMDB: %s)" % ( data["title"], data.get("filmtipset_my_grade", "-"), data.get("imdb_rating", "-"), )) print(" [Genre: %s, Country: %s, Year: %s]" % ( ", ".join(data.get("genre", "-")), data.get("country", "-"), data.get("year", "-"), )) plot = data.get("plot", None) if plot: text = textwrap.wrap('Plot: "' + data.get("plot", "-") + '"', width=80, initial_indent=" ", subsequent_indent=" ") print("\n".join(text)) print()
// ... existing code ... class Provider(OutputProvider): def process_data(self, movie_data): movie_data = filter(lambda data: data.get("filmtipset_my_grade_type", "none") != "seen", movie_data) movie_data = sorted(movie_data, key=lambda data: (data.get("filmtipset_my_grade", 0), data.get("imdb_rating", 0)), reverse=True) return movie_data def output(self, movie_data): // ... rest of the code ...
ea748053152c048f9ac763a4fb6b97a1815082df
wcsaxes/datasets/__init__.py
wcsaxes/datasets/__init__.py
from astropy.utils.data import download_file from astropy.io import fits def msx_hdu(cache=True): filename = download_file("http://astrofrog.github.io/wcsaxes-datasets/msx.fits", cache=cache) return fits.open(filename)[0] def rosat_hdu(cache=True): filename = download_file("http://astrofrog.github.io/wcsaxes-datasets/rosat.fits", cache=cache) return fits.open(filename)[0] def twoMASS_k_hdu(cache=True): filename = download_file("http://astrofrog.github.io/wcsaxes-datasets/2MASS_k.fits", cache=cache) return fits.open(filename)[0] def l1448_co_hdu(cache=True): filename = download_file("http://astrofrog.github.io/wcsaxes-datasets/L1448_13CO_subset.fits", cache=cache) return fits.open(filename)[0] def bolocam_hdu(cache=True): filename = download_file("http://astrofrog.github.io/wcsaxes-datasets/bolocam_v2.0.fits", cache=cache) return fits.open(filename)[0]
from astropy.utils.data import download_file from astropy.io import fits URL = 'http://astrofrog.github.io/wcsaxes-datasets/' def get_hdu(filename, cache=True): path = download_file(URL + filename, cache=cache) return fits.open(path)[0] def msx_hdu(cache=True): return get_hdu('msx.fits', cache=cache) def rosat_hdu(cache=True): return get_hdu('rosat.fits', cache=cache) def twoMASS_k_hdu(cache=True): return get_hdu('2MASS_k.fits', cache=cache) def l1448_co_hdu(cache=True): return get_hdu('L1448_13CO_subset.fits', cache=cache) def bolocam_hdu(cache=True): return get_hdu('bolocam_v2.0.fits', cache=cache)
Simplify datasets functions a bit
Simplify datasets functions a bit
Python
bsd-3-clause
saimn/astropy,saimn/astropy,StuartLittlefair/astropy,dhomeier/astropy,astropy/astropy,stargaser/astropy,astropy/astropy,larrybradley/astropy,bsipocz/astropy,bsipocz/astropy,kelle/astropy,pllim/astropy,funbaker/astropy,dhomeier/astropy,mhvk/astropy,pllim/astropy,StuartLittlefair/astropy,astropy/astropy,dhomeier/astropy,astropy/astropy,kelle/astropy,MSeifert04/astropy,aleksandr-bakanov/astropy,saimn/astropy,joergdietrich/astropy,funbaker/astropy,lpsinger/astropy,aleksandr-bakanov/astropy,joergdietrich/astropy,astropy/astropy,saimn/astropy,tbabej/astropy,aleksandr-bakanov/astropy,pllim/astropy,stargaser/astropy,aleksandr-bakanov/astropy,tbabej/astropy,stargaser/astropy,saimn/astropy,DougBurke/astropy,kelle/astropy,tbabej/astropy,dhomeier/astropy,larrybradley/astropy,kelle/astropy,joergdietrich/astropy,lpsinger/astropy,DougBurke/astropy,tbabej/astropy,StuartLittlefair/astropy,joergdietrich/astropy,mhvk/astropy,DougBurke/astropy,AustereCuriosity/astropy,DougBurke/astropy,larrybradley/astropy,mhvk/astropy,AustereCuriosity/astropy,tbabej/astropy,AustereCuriosity/astropy,lpsinger/astropy,joergdietrich/astropy,bsipocz/astropy,mhvk/astropy,bsipocz/astropy,AustereCuriosity/astropy,larrybradley/astropy,AustereCuriosity/astropy,pllim/astropy,pllim/astropy,lpsinger/astropy,funbaker/astropy,MSeifert04/astropy,larrybradley/astropy,stargaser/astropy,StuartLittlefair/astropy,lpsinger/astropy,mhvk/astropy,kelle/astropy,funbaker/astropy,dhomeier/astropy,MSeifert04/astropy,StuartLittlefair/astropy,MSeifert04/astropy
python
## Code Before: from astropy.utils.data import download_file from astropy.io import fits def msx_hdu(cache=True): filename = download_file("http://astrofrog.github.io/wcsaxes-datasets/msx.fits", cache=cache) return fits.open(filename)[0] def rosat_hdu(cache=True): filename = download_file("http://astrofrog.github.io/wcsaxes-datasets/rosat.fits", cache=cache) return fits.open(filename)[0] def twoMASS_k_hdu(cache=True): filename = download_file("http://astrofrog.github.io/wcsaxes-datasets/2MASS_k.fits", cache=cache) return fits.open(filename)[0] def l1448_co_hdu(cache=True): filename = download_file("http://astrofrog.github.io/wcsaxes-datasets/L1448_13CO_subset.fits", cache=cache) return fits.open(filename)[0] def bolocam_hdu(cache=True): filename = download_file("http://astrofrog.github.io/wcsaxes-datasets/bolocam_v2.0.fits", cache=cache) return fits.open(filename)[0] ## Instruction: Simplify datasets functions a bit ## Code After: from astropy.utils.data import download_file from astropy.io import fits URL = 'http://astrofrog.github.io/wcsaxes-datasets/' def get_hdu(filename, cache=True): path = download_file(URL + filename, cache=cache) return fits.open(path)[0] def msx_hdu(cache=True): return get_hdu('msx.fits', cache=cache) def rosat_hdu(cache=True): return get_hdu('rosat.fits', cache=cache) def twoMASS_k_hdu(cache=True): return get_hdu('2MASS_k.fits', cache=cache) def l1448_co_hdu(cache=True): return get_hdu('L1448_13CO_subset.fits', cache=cache) def bolocam_hdu(cache=True): return get_hdu('bolocam_v2.0.fits', cache=cache)
# ... existing code ... from astropy.utils.data import download_file from astropy.io import fits URL = 'http://astrofrog.github.io/wcsaxes-datasets/' def get_hdu(filename, cache=True): path = download_file(URL + filename, cache=cache) return fits.open(path)[0] def msx_hdu(cache=True): return get_hdu('msx.fits', cache=cache) def rosat_hdu(cache=True): return get_hdu('rosat.fits', cache=cache) def twoMASS_k_hdu(cache=True): return get_hdu('2MASS_k.fits', cache=cache) def l1448_co_hdu(cache=True): return get_hdu('L1448_13CO_subset.fits', cache=cache) def bolocam_hdu(cache=True): return get_hdu('bolocam_v2.0.fits', cache=cache) # ... rest of the code ...
602623a5944ce28bb0a39ab84896911dc35ec017
src/main/java/ee/tuleva/onboarding/auth/session/GenericSessionStore.java
src/main/java/ee/tuleva/onboarding/auth/session/GenericSessionStore.java
package ee.tuleva.onboarding.auth.session; import java.io.Serial; import java.io.Serializable; import java.util.HashMap; import java.util.Map; import java.util.Optional; import org.springframework.context.annotation.Scope; import org.springframework.context.annotation.ScopedProxyMode; import org.springframework.stereotype.Component; @Component @Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS) public class GenericSessionStore implements Serializable { @Serial private static final long serialVersionUID = -648103071415508424L; private final Map<String, Object> sessionAttributes = new HashMap<>(); public <T extends Serializable> void save(T sessionAttribute) { sessionAttributes.put(sessionAttribute.getClass().getName(), sessionAttribute); } public <T extends Serializable> Optional<T> get(Class clazz) { @SuppressWarnings("unchecked") T sessionAttribute = (T) sessionAttributes.get(clazz.getName()); if (sessionAttribute == null) { return Optional.empty(); } return Optional.of(sessionAttribute); } }
package ee.tuleva.onboarding.auth.session; import java.io.Serial; import java.io.Serializable; import java.util.HashMap; import java.util.Map; import java.util.Optional; import org.springframework.stereotype.Component; import org.springframework.web.context.annotation.SessionScope; @Component @SessionScope public class GenericSessionStore implements Serializable { @Serial private static final long serialVersionUID = -648103071415508424L; private final Map<String, Object> sessionAttributes = new HashMap<>(); public <T extends Serializable> void save(T sessionAttribute) { sessionAttributes.put(sessionAttribute.getClass().getName(), sessionAttribute); } public <T extends Serializable> Optional<T> get(Class clazz) { @SuppressWarnings("unchecked") T sessionAttribute = (T) sessionAttributes.get(clazz.getName()); if (sessionAttribute == null) { return Optional.empty(); } return Optional.of(sessionAttribute); } }
Revert "Revert "Use composed annotation for readability""
Revert "Revert "Use composed annotation for readability"" This reverts commit c82beaa8e9380ec257a4bb296f981cde865ff6d1.
Java
mit
TulevaEE/onboarding-service,TulevaEE/onboarding-service,TulevaEE/onboarding-service,TulevaEE/onboarding-service
java
## Code Before: package ee.tuleva.onboarding.auth.session; import java.io.Serial; import java.io.Serializable; import java.util.HashMap; import java.util.Map; import java.util.Optional; import org.springframework.context.annotation.Scope; import org.springframework.context.annotation.ScopedProxyMode; import org.springframework.stereotype.Component; @Component @Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS) public class GenericSessionStore implements Serializable { @Serial private static final long serialVersionUID = -648103071415508424L; private final Map<String, Object> sessionAttributes = new HashMap<>(); public <T extends Serializable> void save(T sessionAttribute) { sessionAttributes.put(sessionAttribute.getClass().getName(), sessionAttribute); } public <T extends Serializable> Optional<T> get(Class clazz) { @SuppressWarnings("unchecked") T sessionAttribute = (T) sessionAttributes.get(clazz.getName()); if (sessionAttribute == null) { return Optional.empty(); } return Optional.of(sessionAttribute); } } ## Instruction: Revert "Revert "Use composed annotation for readability"" This reverts commit c82beaa8e9380ec257a4bb296f981cde865ff6d1. ## Code After: package ee.tuleva.onboarding.auth.session; import java.io.Serial; import java.io.Serializable; import java.util.HashMap; import java.util.Map; import java.util.Optional; import org.springframework.stereotype.Component; import org.springframework.web.context.annotation.SessionScope; @Component @SessionScope public class GenericSessionStore implements Serializable { @Serial private static final long serialVersionUID = -648103071415508424L; private final Map<String, Object> sessionAttributes = new HashMap<>(); public <T extends Serializable> void save(T sessionAttribute) { sessionAttributes.put(sessionAttribute.getClass().getName(), sessionAttribute); } public <T extends Serializable> Optional<T> get(Class clazz) { @SuppressWarnings("unchecked") T sessionAttribute = (T) sessionAttributes.get(clazz.getName()); if (sessionAttribute == null) { return Optional.empty(); } return Optional.of(sessionAttribute); } }
// ... existing code ... import java.util.HashMap; import java.util.Map; import java.util.Optional; import org.springframework.stereotype.Component; import org.springframework.web.context.annotation.SessionScope; @Component @SessionScope public class GenericSessionStore implements Serializable { @Serial private static final long serialVersionUID = -648103071415508424L; // ... rest of the code ...
093b4bfcccadcf7bc8f78e789a4c2c290e192852
src/main/java/org/axonframework/sample/axonbank/myaxonbank/MyController.java
src/main/java/org/axonframework/sample/axonbank/myaxonbank/MyController.java
/* * Copyright (c) 2017 General Electric Company. All rights reserved. * * The copyright to the computer software herein is the property of General Electric Company. * The software may be used and/or copied only with the written permission of * General Electric Company or in accordance with the terms and conditions stipulated in the * agreement/contract under which the software has been supplied. */ package org.axonframework.sample.axonbank.myaxonbank; import org.axonframework.commandhandling.CommandBus; import org.axonframework.sample.axonbank.myaxonbank.coreapi.CreateAccountCommand; import org.axonframework.sample.axonbank.myaxonbank.coreapi.WithdrawMoneyCommand; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import static org.axonframework.commandhandling.GenericCommandMessage.asCommandMessage; @RestController public class MyController { @Autowired private CommandBus commandBus; @RequestMapping(value = "/hello") public String say() { System.out.println("Command Bus>>>>" + commandBus); commandBus.dispatch(asCommandMessage(new CreateAccountCommand("1234", 1000))); commandBus.dispatch(asCommandMessage(new WithdrawMoneyCommand("1234", 800))); return "Hello!"; } }
/* * Copyright (c) 2017 General Electric Company. All rights reserved. * * The copyright to the computer software herein is the property of General Electric Company. * The software may be used and/or copied only with the written permission of * General Electric Company or in accordance with the terms and conditions stipulated in the * agreement/contract under which the software has been supplied. */ package org.axonframework.sample.axonbank.myaxonbank; import org.axonframework.commandhandling.gateway.CommandGateway; import org.axonframework.sample.axonbank.myaxonbank.coreapi.CreateAccountCommand; import org.axonframework.sample.axonbank.myaxonbank.coreapi.WithdrawMoneyCommand; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class MyController { @Autowired private CommandGateway commandGateway; @RequestMapping(value = "/hello") public String say() { commandGateway.send(new CreateAccountCommand("1234", 1000)); commandGateway.send(new WithdrawMoneyCommand("1234", 800)); commandGateway.send(new WithdrawMoneyCommand("1234", 500)); return "Hello!"; } }
Use command gateway instead of command bus to generate commands
Use command gateway instead of command bus to generate commands
Java
mit
bharat-srinivasan/my-axonbank
java
## Code Before: /* * Copyright (c) 2017 General Electric Company. All rights reserved. * * The copyright to the computer software herein is the property of General Electric Company. * The software may be used and/or copied only with the written permission of * General Electric Company or in accordance with the terms and conditions stipulated in the * agreement/contract under which the software has been supplied. */ package org.axonframework.sample.axonbank.myaxonbank; import org.axonframework.commandhandling.CommandBus; import org.axonframework.sample.axonbank.myaxonbank.coreapi.CreateAccountCommand; import org.axonframework.sample.axonbank.myaxonbank.coreapi.WithdrawMoneyCommand; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import static org.axonframework.commandhandling.GenericCommandMessage.asCommandMessage; @RestController public class MyController { @Autowired private CommandBus commandBus; @RequestMapping(value = "/hello") public String say() { System.out.println("Command Bus>>>>" + commandBus); commandBus.dispatch(asCommandMessage(new CreateAccountCommand("1234", 1000))); commandBus.dispatch(asCommandMessage(new WithdrawMoneyCommand("1234", 800))); return "Hello!"; } } ## Instruction: Use command gateway instead of command bus to generate commands ## Code After: /* * Copyright (c) 2017 General Electric Company. All rights reserved. * * The copyright to the computer software herein is the property of General Electric Company. * The software may be used and/or copied only with the written permission of * General Electric Company or in accordance with the terms and conditions stipulated in the * agreement/contract under which the software has been supplied. */ package org.axonframework.sample.axonbank.myaxonbank; import org.axonframework.commandhandling.gateway.CommandGateway; import org.axonframework.sample.axonbank.myaxonbank.coreapi.CreateAccountCommand; import org.axonframework.sample.axonbank.myaxonbank.coreapi.WithdrawMoneyCommand; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class MyController { @Autowired private CommandGateway commandGateway; @RequestMapping(value = "/hello") public String say() { commandGateway.send(new CreateAccountCommand("1234", 1000)); commandGateway.send(new WithdrawMoneyCommand("1234", 800)); commandGateway.send(new WithdrawMoneyCommand("1234", 500)); return "Hello!"; } }
// ... existing code ... package org.axonframework.sample.axonbank.myaxonbank; import org.axonframework.commandhandling.gateway.CommandGateway; import org.axonframework.sample.axonbank.myaxonbank.coreapi.CreateAccountCommand; import org.axonframework.sample.axonbank.myaxonbank.coreapi.WithdrawMoneyCommand; import org.springframework.beans.factory.annotation.Autowired; // ... modified code ... import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class MyController { @Autowired private CommandGateway commandGateway; @RequestMapping(value = "/hello") public String say() { commandGateway.send(new CreateAccountCommand("1234", 1000)); commandGateway.send(new WithdrawMoneyCommand("1234", 800)); commandGateway.send(new WithdrawMoneyCommand("1234", 500)); return "Hello!"; } // ... rest of the code ...
6058bc795563d482ce1672b3eb933e1c409c6ac8
setup.py
setup.py
from distutils.core import setup setup( name='Juju XaaS CLI', version='0.1.0', author='Justin SB', author_email='[email protected]', packages=['jxaas'], url='http://pypi.python.org/pypi/jxaas/', license='LICENSE.txt', description='CLI for Juju XaaS.', long_description=open('README.md').read(), install_requires=[ ], scripts=[ 'bin/jxaas' ] )
from distutils.core import setup setup( name='Juju XaaS CLI', version='0.1.0', author='Justin SB', author_email='[email protected]', packages=['jxaas'], url='http://pypi.python.org/pypi/jxaas/', license='LICENSE.txt', description='CLI for Juju XaaS.', long_description=open('README.md').read(), install_requires=[ 'cliff' ], scripts=[ 'bin/jxaas' ] )
Add cliff as a requirement
Add cliff as a requirement
Python
apache-2.0
jxaas/cli
python
## Code Before: from distutils.core import setup setup( name='Juju XaaS CLI', version='0.1.0', author='Justin SB', author_email='[email protected]', packages=['jxaas'], url='http://pypi.python.org/pypi/jxaas/', license='LICENSE.txt', description='CLI for Juju XaaS.', long_description=open('README.md').read(), install_requires=[ ], scripts=[ 'bin/jxaas' ] ) ## Instruction: Add cliff as a requirement ## Code After: from distutils.core import setup setup( name='Juju XaaS CLI', version='0.1.0', author='Justin SB', author_email='[email protected]', packages=['jxaas'], url='http://pypi.python.org/pypi/jxaas/', license='LICENSE.txt', description='CLI for Juju XaaS.', long_description=open('README.md').read(), install_requires=[ 'cliff' ], scripts=[ 'bin/jxaas' ] )
# ... existing code ... description='CLI for Juju XaaS.', long_description=open('README.md').read(), install_requires=[ 'cliff' ], scripts=[ 'bin/jxaas' # ... rest of the code ...
0d16255d093a3292abaf0b07e21ddebc956e7ca3
tests/utils.h
tests/utils.h
using namespace std; inline string copyFile(const string &filename, const string &ext) { string newname = string(tempnam(NULL, NULL)) + ext; string oldname = string("data/") + filename + ext; char buffer[4096]; int bytes; int inf = open(oldname.c_str(), O_RDONLY); int outf = open(newname.c_str(), O_CREAT | O_EXCL | O_RDWR, S_IRUSR | S_IWUSR); while((bytes = read(inf, buffer, sizeof(buffer))) > 0) write(outf, buffer, bytes); close(outf); close(inf); return newname; } inline void deleteFile(const string &filename) { remove(filename.c_str()); } class ScopedFileCopy { public: ScopedFileCopy(const string &filename, const string &ext) { m_filename = copyFile(filename, ext); } ~ScopedFileCopy() { deleteFile(m_filename); } string fileName() { return m_filename; } private: string m_filename; };
using namespace std; inline string copyFile(const string &filename, const string &ext) { string newname = string(tempnam(NULL, NULL)) + ext; string oldname = string("data/") + filename + ext; #ifdef _WIN32 CopyFile(oldname.c_str(), newname.c_str(), FALSE); SetFileAttributes(newname.c_str(), GetFileAttributes(newname.c_str()) & ~FILE_ATTRIBUTE_READONLY); #else char buffer[4096]; int bytes; int inf = open(oldname.c_str(), O_RDONLY); int outf = open(newname.c_str(), O_CREAT | O_EXCL | O_RDWR, S_IRUSR | S_IWUSR); while((bytes = read(inf, buffer, sizeof(buffer))) > 0) write(outf, buffer, bytes); close(outf); close(inf); #endif return newname; } inline void deleteFile(const string &filename) { remove(filename.c_str()); } class ScopedFileCopy { public: ScopedFileCopy(const string &filename, const string &ext) { m_filename = copyFile(filename, ext); } ~ScopedFileCopy() { deleteFile(m_filename); } string fileName() { return m_filename; } private: string m_filename; };
Fix compilation fo the test runner on Windows
Fix compilation fo the test runner on Windows Patch by Stephen Hewitt git-svn-id: 7928e23e4d58c5ca14aa7b47c53aeff82ee1dd0c@1078612 283d02a7-25f6-0310-bc7c-ecb5cbfe19da
C
lgpl-2.1
dlz1123/taglib,black78/taglib,taglib/taglib,davispuh/taglib,pbhd/taglib,videolabs/taglib,videolabs/taglib,TsudaKageyu/taglib,taglib/taglib,MaxLeb/taglib,pbhd/taglib,Distrotech/taglib,pbhd/taglib,crystax/cosp-android-taglib,dlz1123/taglib,crystax/cosp-android-taglib,davispuh/taglib,Distrotech/taglib,dlz1123/taglib,TsudaKageyu/taglib,i80and/taglib,i80and/taglib,TsudaKageyu/taglib,taglib/taglib,i80and/taglib,Distrotech/taglib,videolabs/taglib,MaxLeb/taglib,MaxLeb/taglib,black78/taglib,davispuh/taglib,black78/taglib
c
## Code Before: using namespace std; inline string copyFile(const string &filename, const string &ext) { string newname = string(tempnam(NULL, NULL)) + ext; string oldname = string("data/") + filename + ext; char buffer[4096]; int bytes; int inf = open(oldname.c_str(), O_RDONLY); int outf = open(newname.c_str(), O_CREAT | O_EXCL | O_RDWR, S_IRUSR | S_IWUSR); while((bytes = read(inf, buffer, sizeof(buffer))) > 0) write(outf, buffer, bytes); close(outf); close(inf); return newname; } inline void deleteFile(const string &filename) { remove(filename.c_str()); } class ScopedFileCopy { public: ScopedFileCopy(const string &filename, const string &ext) { m_filename = copyFile(filename, ext); } ~ScopedFileCopy() { deleteFile(m_filename); } string fileName() { return m_filename; } private: string m_filename; }; ## Instruction: Fix compilation fo the test runner on Windows Patch by Stephen Hewitt git-svn-id: 7928e23e4d58c5ca14aa7b47c53aeff82ee1dd0c@1078612 283d02a7-25f6-0310-bc7c-ecb5cbfe19da ## Code After: using namespace std; inline string copyFile(const string &filename, const string &ext) { string newname = string(tempnam(NULL, NULL)) + ext; string oldname = string("data/") + filename + ext; #ifdef _WIN32 CopyFile(oldname.c_str(), newname.c_str(), FALSE); SetFileAttributes(newname.c_str(), GetFileAttributes(newname.c_str()) & ~FILE_ATTRIBUTE_READONLY); #else char buffer[4096]; int bytes; int inf = open(oldname.c_str(), O_RDONLY); int outf = open(newname.c_str(), O_CREAT | O_EXCL | O_RDWR, S_IRUSR | S_IWUSR); while((bytes = read(inf, buffer, sizeof(buffer))) > 0) write(outf, buffer, bytes); close(outf); close(inf); #endif return newname; } inline void deleteFile(const string &filename) { remove(filename.c_str()); } class ScopedFileCopy { public: ScopedFileCopy(const string &filename, const string &ext) { m_filename = copyFile(filename, ext); } ~ScopedFileCopy() { deleteFile(m_filename); } string fileName() { return m_filename; } private: string m_filename; };
... { string newname = string(tempnam(NULL, NULL)) + ext; string oldname = string("data/") + filename + ext; #ifdef _WIN32 CopyFile(oldname.c_str(), newname.c_str(), FALSE); SetFileAttributes(newname.c_str(), GetFileAttributes(newname.c_str()) & ~FILE_ATTRIBUTE_READONLY); #else char buffer[4096]; int bytes; int inf = open(oldname.c_str(), O_RDONLY); ... write(outf, buffer, bytes); close(outf); close(inf); #endif return newname; } ...
9c6ae0d5642cf5979ea43112f134a7fb3c02f5b7
RIButtonItem.h
RIButtonItem.h
// // RIButtonItem.h // Shibui // // Created by Jiva DeVoe on 1/12/11. // Copyright 2011 Random Ideas, LLC. All rights reserved. // #import <Foundation/Foundation.h> typedef void (^RISimpleAction)(); @interface RIButtonItem : NSObject { NSString *label; RISimpleAction action; } @property (retain, nonatomic) NSString *label; @property (copy, nonatomic) RISimpleAction action; +(id)item; +(id)itemWithLabel:(NSString *)inLabel; @end
// // RIButtonItem.h // Shibui // // Created by Jiva DeVoe on 1/12/11. // Copyright 2011 Random Ideas, LLC. All rights reserved. // #import <Foundation/Foundation.h> @interface RIButtonItem : NSObject { NSString *label; void (^action)(); } @property (retain, nonatomic) NSString *label; @property (copy, nonatomic) void (^action)(); +(id)item; +(id)itemWithLabel:(NSString *)inLabel; @end
Replace typedef with literal type
Replace typedef with literal type Using the literal typedef makes Xcode's code sense give you a parameter stand-in that can be expanded with a shift-enter.
C
mit
Weever/UIAlertView-Blocks,200895045/UIAlertView-Blocks,jivadevoe/UIAlertView-Blocks,shanyimin/UIAlertView-Blocks,z8927623/UIAlertView-Blocks
c
## Code Before: // // RIButtonItem.h // Shibui // // Created by Jiva DeVoe on 1/12/11. // Copyright 2011 Random Ideas, LLC. All rights reserved. // #import <Foundation/Foundation.h> typedef void (^RISimpleAction)(); @interface RIButtonItem : NSObject { NSString *label; RISimpleAction action; } @property (retain, nonatomic) NSString *label; @property (copy, nonatomic) RISimpleAction action; +(id)item; +(id)itemWithLabel:(NSString *)inLabel; @end ## Instruction: Replace typedef with literal type Using the literal typedef makes Xcode's code sense give you a parameter stand-in that can be expanded with a shift-enter. ## Code After: // // RIButtonItem.h // Shibui // // Created by Jiva DeVoe on 1/12/11. // Copyright 2011 Random Ideas, LLC. All rights reserved. // #import <Foundation/Foundation.h> @interface RIButtonItem : NSObject { NSString *label; void (^action)(); } @property (retain, nonatomic) NSString *label; @property (copy, nonatomic) void (^action)(); +(id)item; +(id)itemWithLabel:(NSString *)inLabel; @end
... #import <Foundation/Foundation.h> @interface RIButtonItem : NSObject { NSString *label; void (^action)(); } @property (retain, nonatomic) NSString *label; @property (copy, nonatomic) void (^action)(); +(id)item; +(id)itemWithLabel:(NSString *)inLabel; @end ...
944746bd3e6b40b5ceb8ef974df6c26e550318cb
paradrop/tools/pdlog/pdlog/main.py
paradrop/tools/pdlog/pdlog/main.py
import sys import argparse import json import urllib import subprocess LOG_FILE = "/var/snap/paradrop-daemon/common/logs/log" def parseLine(line): try: data = json.loads(line) msg = urllib.unquote(data['message']) print(msg) except: pass def runTail(logFile): cmd = ['tail', '-n', '100', '-f', LOG_FILE] proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, universal_newlines=True) for line in iter(proc.stdout.readline, ''): yield line proc.stdout.close() return_code = proc.wait() if return_code: raise subprocess.CalledProcessError(return_code, cmd) def main(): p = argparse.ArgumentParser(description='Paradrop log tool') p.add_argument('-f', help='Wait for additional data to be appended to the log file when end of file is reached', action='store_true', dest='f') args = p.parse_args() try: if args.f: for line in runTail(LOG_FILE): parseLine(line) else: with open(LOG_FILE, "r") as inputFile: for line in inputFile: parseLine(line) except KeyboardInterrupt: sys.exit(0) if __name__ == "__main__": main()
import sys import argparse import json import urllib import subprocess from time import sleep LOG_FILE = "/var/snap/paradrop-daemon/common/logs/log" def parseLine(line): try: data = json.loads(line) msg = urllib.unquote(data['message']) print(msg) except: pass def runTail(logFile): cmd = ['tail', '-n', '100', '-f', LOG_FILE] while (True): try: proc = subprocess.Popen(cmd, \ stdout=subprocess.PIPE, \ universal_newlines=True) for line in iter(proc.stdout.readline, ''): yield line proc.stdout.close() proc.wait() except subprocess.CalledProcessError: print 'Failed to open the log file, will try again...' sleep(2) continue def main(): p = argparse.ArgumentParser(description='Paradrop log tool') p.add_argument('-f', help='Wait for additional data to be appended to the log file when end of file is reached', action='store_true', dest='f') args = p.parse_args() try: if args.f: for line in runTail(LOG_FILE): parseLine(line) else: with open(LOG_FILE, "r") as inputFile: for line in inputFile: parseLine(line) except KeyboardInterrupt: sys.exit(0) if __name__ == "__main__": main()
Make sure the paradrop.pdlog retry when the log file does not exist
Make sure the paradrop.pdlog retry when the log file does not exist
Python
apache-2.0
ParadropLabs/Paradrop,ParadropLabs/Paradrop,ParadropLabs/Paradrop
python
## Code Before: import sys import argparse import json import urllib import subprocess LOG_FILE = "/var/snap/paradrop-daemon/common/logs/log" def parseLine(line): try: data = json.loads(line) msg = urllib.unquote(data['message']) print(msg) except: pass def runTail(logFile): cmd = ['tail', '-n', '100', '-f', LOG_FILE] proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, universal_newlines=True) for line in iter(proc.stdout.readline, ''): yield line proc.stdout.close() return_code = proc.wait() if return_code: raise subprocess.CalledProcessError(return_code, cmd) def main(): p = argparse.ArgumentParser(description='Paradrop log tool') p.add_argument('-f', help='Wait for additional data to be appended to the log file when end of file is reached', action='store_true', dest='f') args = p.parse_args() try: if args.f: for line in runTail(LOG_FILE): parseLine(line) else: with open(LOG_FILE, "r") as inputFile: for line in inputFile: parseLine(line) except KeyboardInterrupt: sys.exit(0) if __name__ == "__main__": main() ## Instruction: Make sure the paradrop.pdlog retry when the log file does not exist ## Code After: import sys import argparse import json import urllib import subprocess from time import sleep LOG_FILE = "/var/snap/paradrop-daemon/common/logs/log" def parseLine(line): try: data = json.loads(line) msg = urllib.unquote(data['message']) print(msg) except: pass def runTail(logFile): cmd = ['tail', '-n', '100', '-f', LOG_FILE] while (True): try: proc = subprocess.Popen(cmd, \ stdout=subprocess.PIPE, \ universal_newlines=True) for line in iter(proc.stdout.readline, ''): yield line proc.stdout.close() proc.wait() except subprocess.CalledProcessError: print 'Failed to open the log file, will try again...' sleep(2) continue def main(): p = argparse.ArgumentParser(description='Paradrop log tool') p.add_argument('-f', help='Wait for additional data to be appended to the log file when end of file is reached', action='store_true', dest='f') args = p.parse_args() try: if args.f: for line in runTail(LOG_FILE): parseLine(line) else: with open(LOG_FILE, "r") as inputFile: for line in inputFile: parseLine(line) except KeyboardInterrupt: sys.exit(0) if __name__ == "__main__": main()
// ... existing code ... import json import urllib import subprocess from time import sleep LOG_FILE = "/var/snap/paradrop-daemon/common/logs/log" // ... modified code ... def runTail(logFile): cmd = ['tail', '-n', '100', '-f', LOG_FILE] while (True): try: proc = subprocess.Popen(cmd, \ stdout=subprocess.PIPE, \ universal_newlines=True) for line in iter(proc.stdout.readline, ''): yield line proc.stdout.close() proc.wait() except subprocess.CalledProcessError: print 'Failed to open the log file, will try again...' sleep(2) continue def main(): p = argparse.ArgumentParser(description='Paradrop log tool') // ... rest of the code ...
bafdbd28e35d80d28bfb82c23532533cb2915066
fuel/exceptions.py
fuel/exceptions.py
class AxisLabelsMismatchError(ValueError): """Raised when a pair of axis labels tuples do not match.""" class ConfigurationError(Exception): """Error raised when a configuration value is requested but not set.""" class MissingInputFiles(Exception): """Exception raised by a converter when input files are not found. Parameters ---------- filenames : list A list of filenames that were not found. """ def __init__(self, message, filenames): self.filenames = filenames super(MissingInputFiles, self).__init__(message, filenames) class NeedURLPrefix(Exception): """Raised when a URL is not provided for a file."""
class AxisLabelsMismatchError(ValueError): """Raised when a pair of axis labels tuples do not match.""" class ConfigurationError(Exception): """Error raised when a configuration value is requested but not set.""" class MissingInputFiles(Exception): """Exception raised by a converter when input files are not found. Parameters ---------- message : str The error message to be associated with this exception. filenames : list A list of filenames that were not found. """ def __init__(self, message, filenames): self.filenames = filenames super(MissingInputFiles, self).__init__(message, filenames) class NeedURLPrefix(Exception): """Raised when a URL is not provided for a file."""
Add docs for MissingInputFiles 'message' arg.
Add docs for MissingInputFiles 'message' arg.
Python
mit
hantek/fuel,rodrigob/fuel,dmitriy-serdyuk/fuel,codeaudit/fuel,udibr/fuel,mjwillson/fuel,dribnet/fuel,capybaralet/fuel,aalmah/fuel,glewis17/fuel,glewis17/fuel,vdumoulin/fuel,dmitriy-serdyuk/fuel,dwf/fuel,bouthilx/fuel,mila-udem/fuel,chrishokamp/fuel,udibr/fuel,janchorowski/fuel,dwf/fuel,dribnet/fuel,markusnagel/fuel,aalmah/fuel,markusnagel/fuel,orhanf/fuel,capybaralet/fuel,rodrigob/fuel,dhruvparamhans/fuel,dhruvparamhans/fuel,janchorowski/fuel,mila-udem/fuel,bouthilx/fuel,harmdevries89/fuel,hantek/fuel,harmdevries89/fuel,chrishokamp/fuel,codeaudit/fuel,orhanf/fuel,vdumoulin/fuel,mjwillson/fuel
python
## Code Before: class AxisLabelsMismatchError(ValueError): """Raised when a pair of axis labels tuples do not match.""" class ConfigurationError(Exception): """Error raised when a configuration value is requested but not set.""" class MissingInputFiles(Exception): """Exception raised by a converter when input files are not found. Parameters ---------- filenames : list A list of filenames that were not found. """ def __init__(self, message, filenames): self.filenames = filenames super(MissingInputFiles, self).__init__(message, filenames) class NeedURLPrefix(Exception): """Raised when a URL is not provided for a file.""" ## Instruction: Add docs for MissingInputFiles 'message' arg. ## Code After: class AxisLabelsMismatchError(ValueError): """Raised when a pair of axis labels tuples do not match.""" class ConfigurationError(Exception): """Error raised when a configuration value is requested but not set.""" class MissingInputFiles(Exception): """Exception raised by a converter when input files are not found. Parameters ---------- message : str The error message to be associated with this exception. filenames : list A list of filenames that were not found. """ def __init__(self, message, filenames): self.filenames = filenames super(MissingInputFiles, self).__init__(message, filenames) class NeedURLPrefix(Exception): """Raised when a URL is not provided for a file."""
// ... existing code ... Parameters ---------- message : str The error message to be associated with this exception. filenames : list A list of filenames that were not found. // ... rest of the code ...
11543deda3222965ee95adc4ea6db5cdec21ac94
admin_tests/factories.py
admin_tests/factories.py
import factory from admin.common_auth.models import MyUser class UserFactory(factory.Factory): class Meta: model = MyUser id = 123 email = '[email protected]' first_name = 'Yo-yo' last_name = 'Ma' osf_id = 'abc12' @classmethod def is_in_group(cls, value): return True
import factory from admin.common_auth.models import AdminProfile from osf_tests.factories import UserFactory as OSFUserFactory class UserFactory(factory.Factory): class Meta: model = AdminProfile user = OSFUserFactory desk_token = 'el-p' test_token_secret = 'mike' @classmethod def is_in_group(cls, value): return True
Fix up admin user factory to reflect model changes
Fix up admin user factory to reflect model changes
Python
apache-2.0
alexschiller/osf.io,HalcyonChimera/osf.io,felliott/osf.io,baylee-d/osf.io,mattclark/osf.io,erinspace/osf.io,alexschiller/osf.io,alexschiller/osf.io,leb2dg/osf.io,chrisseto/osf.io,chennan47/osf.io,cslzchen/osf.io,baylee-d/osf.io,CenterForOpenScience/osf.io,acshi/osf.io,caseyrollins/osf.io,aaxelb/osf.io,icereval/osf.io,hmoco/osf.io,adlius/osf.io,cslzchen/osf.io,baylee-d/osf.io,erinspace/osf.io,chennan47/osf.io,leb2dg/osf.io,HalcyonChimera/osf.io,pattisdr/osf.io,caneruguz/osf.io,brianjgeiger/osf.io,caseyrollins/osf.io,binoculars/osf.io,CenterForOpenScience/osf.io,brianjgeiger/osf.io,laurenrevere/osf.io,saradbowman/osf.io,hmoco/osf.io,brianjgeiger/osf.io,alexschiller/osf.io,leb2dg/osf.io,pattisdr/osf.io,cslzchen/osf.io,cwisecarver/osf.io,mfraezz/osf.io,binoculars/osf.io,brianjgeiger/osf.io,crcresearch/osf.io,TomBaxter/osf.io,monikagrabowska/osf.io,saradbowman/osf.io,aaxelb/osf.io,chennan47/osf.io,mluo613/osf.io,mluo613/osf.io,CenterForOpenScience/osf.io,hmoco/osf.io,HalcyonChimera/osf.io,caneruguz/osf.io,laurenrevere/osf.io,cwisecarver/osf.io,Nesiehr/osf.io,Nesiehr/osf.io,adlius/osf.io,caseyrollins/osf.io,icereval/osf.io,TomBaxter/osf.io,icereval/osf.io,Johnetordoff/osf.io,monikagrabowska/osf.io,sloria/osf.io,cwisecarver/osf.io,mfraezz/osf.io,mluo613/osf.io,acshi/osf.io,acshi/osf.io,hmoco/osf.io,cwisecarver/osf.io,acshi/osf.io,Nesiehr/osf.io,cslzchen/osf.io,crcresearch/osf.io,felliott/osf.io,caneruguz/osf.io,adlius/osf.io,adlius/osf.io,mfraezz/osf.io,chrisseto/osf.io,mfraezz/osf.io,crcresearch/osf.io,Johnetordoff/osf.io,Nesiehr/osf.io,alexschiller/osf.io,mluo613/osf.io,chrisseto/osf.io,CenterForOpenScience/osf.io,mattclark/osf.io,monikagrabowska/osf.io,caneruguz/osf.io,Johnetordoff/osf.io,felliott/osf.io,leb2dg/osf.io,sloria/osf.io,erinspace/osf.io,acshi/osf.io,TomBaxter/osf.io,mattclark/osf.io,monikagrabowska/osf.io,HalcyonChimera/osf.io,pattisdr/osf.io,felliott/osf.io,monikagrabowska/osf.io,aaxelb/osf.io,laurenrevere/osf.io,mluo613/osf.io,chrisseto/osf.io,sloria/osf.io,binoculars/osf.io,aaxelb/osf.io,Johnetordoff/osf.io
python
## Code Before: import factory from admin.common_auth.models import MyUser class UserFactory(factory.Factory): class Meta: model = MyUser id = 123 email = '[email protected]' first_name = 'Yo-yo' last_name = 'Ma' osf_id = 'abc12' @classmethod def is_in_group(cls, value): return True ## Instruction: Fix up admin user factory to reflect model changes ## Code After: import factory from admin.common_auth.models import AdminProfile from osf_tests.factories import UserFactory as OSFUserFactory class UserFactory(factory.Factory): class Meta: model = AdminProfile user = OSFUserFactory desk_token = 'el-p' test_token_secret = 'mike' @classmethod def is_in_group(cls, value): return True
# ... existing code ... import factory from admin.common_auth.models import AdminProfile from osf_tests.factories import UserFactory as OSFUserFactory class UserFactory(factory.Factory): class Meta: model = AdminProfile user = OSFUserFactory desk_token = 'el-p' test_token_secret = 'mike' @classmethod def is_in_group(cls, value): # ... rest of the code ...
c162a1e20af4a2bb48f86f4faeb0be09dbe75c75
tests/longjmp/setlongjmp.c
tests/longjmp/setlongjmp.c
/* * Copyright 2010 The Native Client Authors. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include <setjmp.h> #include <stdio.h> static jmp_buf buf; int main(void) { volatile int result = -1; if (!setjmp(buf) ) { result = 55; printf("setjmp was invoked\n"); longjmp(buf, 1); printf("this print statement is not reached\n"); return -1; } else { printf("longjmp was invoked\n"); return result; } }
/* * Copyright 2010 The Native Client Authors. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include <setjmp.h> #include <stdio.h> #include "native_client/src/include/nacl_assert.h" static jmp_buf buf; int trysetjmp(int longjmp_arg) { volatile int result = -1; int setjmp_ret = -1; setjmp_ret = setjmp(buf); if (!setjmp_ret) { /* Check that setjmp() doesn't return 0 multiple times */ ASSERT_EQ(result, -1); result = 55; printf("setjmp was invoked\n"); longjmp(buf, longjmp_arg); printf("this print statement is not reached\n"); return -1; } else { int expected_ret = longjmp_arg != 0 ? longjmp_arg : 1; ASSERT_EQ(setjmp_ret, expected_ret); printf("longjmp was invoked\n"); return result; } } int main(void) { if (trysetjmp(1) != 55 || trysetjmp(0) != 55 || trysetjmp(-1) != 55) return -1; return 55; }
Test that invoking longjmp with an argument of 0 causes setjmp to return 1
Test that invoking longjmp with an argument of 0 causes setjmp to return 1 Newlib's x86_64 implementation of longjmp previously failed for this case. Update the setlongjmp.c test to check the return value of setjmp. Additionally fail if setjmp returns 0 twice to avoid an infinite loop in the recent failure case. BUG= https://code.google.com/p/nativeclient/issues/detail?id=4088 [email protected] Review URL: https://codereview.chromium.org/926533003
C
bsd-3-clause
sbc100/native_client,sbc100/native_client,sbc100/native_client,sbc100/native_client,sbc100/native_client,sbc100/native_client
c
## Code Before: /* * Copyright 2010 The Native Client Authors. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include <setjmp.h> #include <stdio.h> static jmp_buf buf; int main(void) { volatile int result = -1; if (!setjmp(buf) ) { result = 55; printf("setjmp was invoked\n"); longjmp(buf, 1); printf("this print statement is not reached\n"); return -1; } else { printf("longjmp was invoked\n"); return result; } } ## Instruction: Test that invoking longjmp with an argument of 0 causes setjmp to return 1 Newlib's x86_64 implementation of longjmp previously failed for this case. Update the setlongjmp.c test to check the return value of setjmp. Additionally fail if setjmp returns 0 twice to avoid an infinite loop in the recent failure case. BUG= https://code.google.com/p/nativeclient/issues/detail?id=4088 [email protected] Review URL: https://codereview.chromium.org/926533003 ## Code After: /* * Copyright 2010 The Native Client Authors. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include <setjmp.h> #include <stdio.h> #include "native_client/src/include/nacl_assert.h" static jmp_buf buf; int trysetjmp(int longjmp_arg) { volatile int result = -1; int setjmp_ret = -1; setjmp_ret = setjmp(buf); if (!setjmp_ret) { /* Check that setjmp() doesn't return 0 multiple times */ ASSERT_EQ(result, -1); result = 55; printf("setjmp was invoked\n"); longjmp(buf, longjmp_arg); printf("this print statement is not reached\n"); return -1; } else { int expected_ret = longjmp_arg != 0 ? longjmp_arg : 1; ASSERT_EQ(setjmp_ret, expected_ret); printf("longjmp was invoked\n"); return result; } } int main(void) { if (trysetjmp(1) != 55 || trysetjmp(0) != 55 || trysetjmp(-1) != 55) return -1; return 55; }
// ... existing code ... #include <setjmp.h> #include <stdio.h> #include "native_client/src/include/nacl_assert.h" static jmp_buf buf; int trysetjmp(int longjmp_arg) { volatile int result = -1; int setjmp_ret = -1; setjmp_ret = setjmp(buf); if (!setjmp_ret) { /* Check that setjmp() doesn't return 0 multiple times */ ASSERT_EQ(result, -1); result = 55; printf("setjmp was invoked\n"); longjmp(buf, longjmp_arg); printf("this print statement is not reached\n"); return -1; } else { int expected_ret = longjmp_arg != 0 ? longjmp_arg : 1; ASSERT_EQ(setjmp_ret, expected_ret); printf("longjmp was invoked\n"); return result; } } int main(void) { if (trysetjmp(1) != 55 || trysetjmp(0) != 55 || trysetjmp(-1) != 55) return -1; return 55; } // ... rest of the code ...
62451e8c5b3d93409fa4bcc7ec29827be6253e88
website/registries/utils.py
website/registries/utils.py
REG_CAMPAIGNS = { 'prereg': 'Prereg Challenge', 'registered_report': 'Registered Report Protocol Preregistration', } def get_campaign_schema(campaign): from osf.models import RegistrationSchema if campaign not in REG_CAMPAIGNS: raise ValueError('campaign must be one of: {}'.format(', '.join(REG_CAMPAIGNS.keys()))) schema_name = REG_CAMPAIGNS[campaign] return RegistrationSchema.objects.get(name=schema_name, schema_version=2) def drafts_for_user(user, campaign=None): from osf.models import DraftRegistration, Node from guardian.shortcuts import get_objects_for_user if not user or user.is_anonymous: return None node_qs = get_objects_for_user(user, 'admin_node', Node, with_superuser=False).exclude(is_deleted=True) if campaign: drafts = DraftRegistration.objects.filter( registration_schema=get_campaign_schema(campaign), approval=None, registered_node=None, deleted__isnull=True, branched_from__in=list(node_qs), initiator=user ) else: drafts = DraftRegistration.objects.filter( approval=None, registered_node=None, deleted__isnull=True, branched_from__in=list(node_qs), initiator=user ) return drafts
REG_CAMPAIGNS = { 'prereg': 'Prereg Challenge', 'registered_report': 'Registered Report Protocol Preregistration', } def get_campaign_schema(campaign): from osf.models import RegistrationSchema if campaign not in REG_CAMPAIGNS: raise ValueError('campaign must be one of: {}'.format(', '.join(REG_CAMPAIGNS.keys()))) schema_name = REG_CAMPAIGNS[campaign] return RegistrationSchema.objects.get(name=schema_name, schema_version=2) def drafts_for_user(user, campaign=None): from osf.models import DraftRegistration, Node from guardian.shortcuts import get_objects_for_user if not user or user.is_anonymous: return None node_qs = get_objects_for_user(user, 'admin_node', Node, with_superuser=False).exclude(is_deleted=True).values_list('id', flat=True) drafts = DraftRegistration.objects.filter( approval=None, registered_node=None, deleted__isnull=True, branched_from__in=node_qs, initiator=user ) if campaign: drafts = drafts.filter( registration_schema=get_campaign_schema(campaign), ) return drafts
Speed up draft registrations query.
Speed up draft registrations query.
Python
apache-2.0
baylee-d/osf.io,brianjgeiger/osf.io,Johnetordoff/osf.io,cslzchen/osf.io,adlius/osf.io,mattclark/osf.io,felliott/osf.io,saradbowman/osf.io,Johnetordoff/osf.io,Johnetordoff/osf.io,cslzchen/osf.io,felliott/osf.io,CenterForOpenScience/osf.io,cslzchen/osf.io,baylee-d/osf.io,mattclark/osf.io,brianjgeiger/osf.io,mattclark/osf.io,Johnetordoff/osf.io,brianjgeiger/osf.io,brianjgeiger/osf.io,baylee-d/osf.io,adlius/osf.io,cslzchen/osf.io,aaxelb/osf.io,aaxelb/osf.io,felliott/osf.io,mfraezz/osf.io,CenterForOpenScience/osf.io,mfraezz/osf.io,mfraezz/osf.io,adlius/osf.io,CenterForOpenScience/osf.io,aaxelb/osf.io,aaxelb/osf.io,mfraezz/osf.io,felliott/osf.io,saradbowman/osf.io,CenterForOpenScience/osf.io,adlius/osf.io
python
## Code Before: REG_CAMPAIGNS = { 'prereg': 'Prereg Challenge', 'registered_report': 'Registered Report Protocol Preregistration', } def get_campaign_schema(campaign): from osf.models import RegistrationSchema if campaign not in REG_CAMPAIGNS: raise ValueError('campaign must be one of: {}'.format(', '.join(REG_CAMPAIGNS.keys()))) schema_name = REG_CAMPAIGNS[campaign] return RegistrationSchema.objects.get(name=schema_name, schema_version=2) def drafts_for_user(user, campaign=None): from osf.models import DraftRegistration, Node from guardian.shortcuts import get_objects_for_user if not user or user.is_anonymous: return None node_qs = get_objects_for_user(user, 'admin_node', Node, with_superuser=False).exclude(is_deleted=True) if campaign: drafts = DraftRegistration.objects.filter( registration_schema=get_campaign_schema(campaign), approval=None, registered_node=None, deleted__isnull=True, branched_from__in=list(node_qs), initiator=user ) else: drafts = DraftRegistration.objects.filter( approval=None, registered_node=None, deleted__isnull=True, branched_from__in=list(node_qs), initiator=user ) return drafts ## Instruction: Speed up draft registrations query. ## Code After: REG_CAMPAIGNS = { 'prereg': 'Prereg Challenge', 'registered_report': 'Registered Report Protocol Preregistration', } def get_campaign_schema(campaign): from osf.models import RegistrationSchema if campaign not in REG_CAMPAIGNS: raise ValueError('campaign must be one of: {}'.format(', '.join(REG_CAMPAIGNS.keys()))) schema_name = REG_CAMPAIGNS[campaign] return RegistrationSchema.objects.get(name=schema_name, schema_version=2) def drafts_for_user(user, campaign=None): from osf.models import DraftRegistration, Node from guardian.shortcuts import get_objects_for_user if not user or user.is_anonymous: return None node_qs = get_objects_for_user(user, 'admin_node', Node, with_superuser=False).exclude(is_deleted=True).values_list('id', flat=True) drafts = DraftRegistration.objects.filter( approval=None, registered_node=None, deleted__isnull=True, branched_from__in=node_qs, initiator=user ) if campaign: drafts = drafts.filter( registration_schema=get_campaign_schema(campaign), ) return drafts
... if not user or user.is_anonymous: return None node_qs = get_objects_for_user(user, 'admin_node', Node, with_superuser=False).exclude(is_deleted=True).values_list('id', flat=True) drafts = DraftRegistration.objects.filter( approval=None, registered_node=None, deleted__isnull=True, branched_from__in=node_qs, initiator=user ) if campaign: drafts = drafts.filter( registration_schema=get_campaign_schema(campaign), ) return drafts ...
bbb417d267f632de6924a9cc2046f61639d75376
src/main/java/se/arbetsformedlingen/venice/probe/ProbeCheckScheduler.java
src/main/java/se/arbetsformedlingen/venice/probe/ProbeCheckScheduler.java
package se.arbetsformedlingen.venice.probe; import se.arbetsformedlingen.venice.common.Application; import se.arbetsformedlingen.venice.common.Host; import se.arbetsformedlingen.venice.common.Hosts; import java.util.LinkedList; import java.util.List; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; public class ProbeCheckScheduler { private LatestProbeStatuses latestProbeStatuses = new LatestProbeStatuses(); private List<ProbeChecker> probes = new LinkedList<>(); public ProbeCheckScheduler() { addProbes(); } private void addProbes() { Application gfr = new Application("gfr"); for (String hostName : Hosts.getGFRHosts()) { CheckProbe probe = new CheckProbe(new Host(hostName), gfr); probes.add(new ProbeChecker(probe, latestProbeStatuses)); } Application geo = new Application("geo"); for (String hostName : Hosts.getGFRHosts()) { CheckProbe probe = new CheckProbe(new Host(hostName), geo); probes.add(new ProbeChecker(probe, latestProbeStatuses)); } } public void startChecking(int period, TimeUnit unit) { ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(11); for (ProbeChecker probe : probes) { scheduler.scheduleAtFixedRate(probe, 1, period, unit); } } }
package se.arbetsformedlingen.venice.probe; import se.arbetsformedlingen.venice.common.Application; import se.arbetsformedlingen.venice.common.Applications; import se.arbetsformedlingen.venice.common.Host; import java.util.LinkedList; import java.util.List; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; public class ProbeCheckScheduler { private LatestProbeStatuses latestProbeStatuses = new LatestProbeStatuses(); private List<ProbeChecker> probes = new LinkedList<>(); public ProbeCheckScheduler() { addProbes(); } private void addProbes() { for (Application app : Applications.getApplications()) { for (Host host : app.getHosts()) { CheckProbe probe = new CheckProbe(host, app); probes.add(new ProbeChecker(probe, latestProbeStatuses)); } } } public void startChecking(int period, TimeUnit unit) { ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(11); for (ProbeChecker probe : probes) { scheduler.scheduleAtFixedRate(probe, 1, period, unit); } } }
Use the hosts for each application
Use the hosts for each application
Java
apache-2.0
tsundberg/venice,tsundberg/venice,tsundberg/venice,tsundberg/venice
java
## Code Before: package se.arbetsformedlingen.venice.probe; import se.arbetsformedlingen.venice.common.Application; import se.arbetsformedlingen.venice.common.Host; import se.arbetsformedlingen.venice.common.Hosts; import java.util.LinkedList; import java.util.List; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; public class ProbeCheckScheduler { private LatestProbeStatuses latestProbeStatuses = new LatestProbeStatuses(); private List<ProbeChecker> probes = new LinkedList<>(); public ProbeCheckScheduler() { addProbes(); } private void addProbes() { Application gfr = new Application("gfr"); for (String hostName : Hosts.getGFRHosts()) { CheckProbe probe = new CheckProbe(new Host(hostName), gfr); probes.add(new ProbeChecker(probe, latestProbeStatuses)); } Application geo = new Application("geo"); for (String hostName : Hosts.getGFRHosts()) { CheckProbe probe = new CheckProbe(new Host(hostName), geo); probes.add(new ProbeChecker(probe, latestProbeStatuses)); } } public void startChecking(int period, TimeUnit unit) { ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(11); for (ProbeChecker probe : probes) { scheduler.scheduleAtFixedRate(probe, 1, period, unit); } } } ## Instruction: Use the hosts for each application ## Code After: package se.arbetsformedlingen.venice.probe; import se.arbetsformedlingen.venice.common.Application; import se.arbetsformedlingen.venice.common.Applications; import se.arbetsformedlingen.venice.common.Host; import java.util.LinkedList; import java.util.List; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; public class ProbeCheckScheduler { private LatestProbeStatuses latestProbeStatuses = new LatestProbeStatuses(); private List<ProbeChecker> probes = new LinkedList<>(); public ProbeCheckScheduler() { addProbes(); } private void addProbes() { for (Application app : Applications.getApplications()) { for (Host host : app.getHosts()) { CheckProbe probe = new CheckProbe(host, app); probes.add(new ProbeChecker(probe, latestProbeStatuses)); } } } public void startChecking(int period, TimeUnit unit) { ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(11); for (ProbeChecker probe : probes) { scheduler.scheduleAtFixedRate(probe, 1, period, unit); } } }
... package se.arbetsformedlingen.venice.probe; import se.arbetsformedlingen.venice.common.Application; import se.arbetsformedlingen.venice.common.Applications; import se.arbetsformedlingen.venice.common.Host; import java.util.LinkedList; import java.util.List; ... } private void addProbes() { for (Application app : Applications.getApplications()) { for (Host host : app.getHosts()) { CheckProbe probe = new CheckProbe(host, app); probes.add(new ProbeChecker(probe, latestProbeStatuses)); } } } ...
2034c8280800291227232435786441bfb0edace0
tests/cli.py
tests/cli.py
import os from spec import eq_ from invoke import run from _utils import support # Yea, it's not really object-oriented, but whatever :) class CLI(object): "Command-line interface" # Yo dogfood, I heard you like invoking def basic_invocation(self): os.chdir(support) result = run("invoke -c integration print_foo") eq_(result.stdout, "foo\n") def implicit_task_module(self): # Contains tasks.py os.chdir(support + '/implicit/') # Doesn't specify --collection result = run("invoke foo") eq_(result.stdout, "Hm\n")
import os from spec import eq_, skip from invoke import run from _utils import support # Yea, it's not really object-oriented, but whatever :) class CLI(object): "Command-line interface" # Yo dogfood, I heard you like invoking def basic_invocation(self): os.chdir(support) result = run("invoke -c integration print_foo") eq_(result.stdout, "foo\n") def implicit_task_module(self): # Contains tasks.py os.chdir(support + '/implicit/') # Doesn't specify --collection result = run("invoke foo") eq_(result.stdout, "Hm\n") def boolean_args(self): cmd = "taskname --boolean" skip() def flag_then_space_then_value(self): cmd = "taskname --flag value" skip() def flag_then_equals_sign_then_value(self): cmd = "taskname --flag=value" skip() def short_boolean_flag(self): cmd = "taskname -f" skip() def short_flag_then_space_then_value(self): cmd = "taskname -f value" skip() def short_flag_then_equals_sign_then_value(self): cmd = "taskname -f=value" skip() def short_flag_with_adjacent_value(self): cmd = "taskname -fvalue" skip() def flag_value_then_task(self): cmd = "task1 -f notatask task2" skip() def flag_value_same_as_task_name(self): cmd = "task1 -f mytask mytask" skip() def complex_multitask_invocation(self): cmd = "-c integration task1 --bool_arg --val_arg=value task2 --val_arg othervalue" skip() def three_tasks_with_args(self): cmd = "task1 --task1_bool task2 --task2_arg task2_arg_value task3" skip()
Add common CLI invocation test stubs.
Add common CLI invocation test stubs. Doesn't go into positional args.
Python
bsd-2-clause
frol/invoke,alex/invoke,mkusz/invoke,mattrobenolt/invoke,mattrobenolt/invoke,kejbaly2/invoke,kejbaly2/invoke,pyinvoke/invoke,pfmoore/invoke,sophacles/invoke,pfmoore/invoke,mkusz/invoke,tyewang/invoke,pyinvoke/invoke,singingwolfboy/invoke,frol/invoke
python
## Code Before: import os from spec import eq_ from invoke import run from _utils import support # Yea, it's not really object-oriented, but whatever :) class CLI(object): "Command-line interface" # Yo dogfood, I heard you like invoking def basic_invocation(self): os.chdir(support) result = run("invoke -c integration print_foo") eq_(result.stdout, "foo\n") def implicit_task_module(self): # Contains tasks.py os.chdir(support + '/implicit/') # Doesn't specify --collection result = run("invoke foo") eq_(result.stdout, "Hm\n") ## Instruction: Add common CLI invocation test stubs. Doesn't go into positional args. ## Code After: import os from spec import eq_, skip from invoke import run from _utils import support # Yea, it's not really object-oriented, but whatever :) class CLI(object): "Command-line interface" # Yo dogfood, I heard you like invoking def basic_invocation(self): os.chdir(support) result = run("invoke -c integration print_foo") eq_(result.stdout, "foo\n") def implicit_task_module(self): # Contains tasks.py os.chdir(support + '/implicit/') # Doesn't specify --collection result = run("invoke foo") eq_(result.stdout, "Hm\n") def boolean_args(self): cmd = "taskname --boolean" skip() def flag_then_space_then_value(self): cmd = "taskname --flag value" skip() def flag_then_equals_sign_then_value(self): cmd = "taskname --flag=value" skip() def short_boolean_flag(self): cmd = "taskname -f" skip() def short_flag_then_space_then_value(self): cmd = "taskname -f value" skip() def short_flag_then_equals_sign_then_value(self): cmd = "taskname -f=value" skip() def short_flag_with_adjacent_value(self): cmd = "taskname -fvalue" skip() def flag_value_then_task(self): cmd = "task1 -f notatask task2" skip() def flag_value_same_as_task_name(self): cmd = "task1 -f mytask mytask" skip() def complex_multitask_invocation(self): cmd = "-c integration task1 --bool_arg --val_arg=value task2 --val_arg othervalue" skip() def three_tasks_with_args(self): cmd = "task1 --task1_bool task2 --task2_arg task2_arg_value task3" skip()
// ... existing code ... import os from spec import eq_, skip from invoke import run // ... modified code ... # Doesn't specify --collection result = run("invoke foo") eq_(result.stdout, "Hm\n") def boolean_args(self): cmd = "taskname --boolean" skip() def flag_then_space_then_value(self): cmd = "taskname --flag value" skip() def flag_then_equals_sign_then_value(self): cmd = "taskname --flag=value" skip() def short_boolean_flag(self): cmd = "taskname -f" skip() def short_flag_then_space_then_value(self): cmd = "taskname -f value" skip() def short_flag_then_equals_sign_then_value(self): cmd = "taskname -f=value" skip() def short_flag_with_adjacent_value(self): cmd = "taskname -fvalue" skip() def flag_value_then_task(self): cmd = "task1 -f notatask task2" skip() def flag_value_same_as_task_name(self): cmd = "task1 -f mytask mytask" skip() def complex_multitask_invocation(self): cmd = "-c integration task1 --bool_arg --val_arg=value task2 --val_arg othervalue" skip() def three_tasks_with_args(self): cmd = "task1 --task1_bool task2 --task2_arg task2_arg_value task3" skip() // ... rest of the code ...
da2e34ca3371f0898df8b3181ba98132bd9a26e4
txircd/modbase.py
txircd/modbase.py
class Module(object): def hook(self, base): self.ircd = base return self class Mode(object): def hook(self, base): self.ircd = base return self def prefixSymbol(self): return None def checkSet(self, channel, param): return True def checkUnset(self, channel, param): return True def onJoin(self, channel, user, params): return "pass" def onMessage(self, sender, target, message): return ["pass"] def onPart(self, channel, user, reason): pass def onTopicChange(self, channel, user, topic): pass def commandData(self, command, *args): pass def Command(object): def hook(self, base): self.ircd = base return self def onUse(self, user, params): pass
class Module(object): def hook(self, base): self.ircd = base return self class Mode(object): def hook(self, base): self.ircd = base return self def prefixSymbol(self): return None def checkSet(self, channel, param): return True def checkUnset(self, channel, param): return True def onJoin(self, channel, user, params): return "pass" def onMessage(self, sender, target, message): return ["pass"] def onPart(self, channel, user, reason): pass def onTopicChange(self, channel, user, topic): pass def commandData(self, command, *args): pass def Command(object): def hook(self, base): self.ircd = base return self def onUse(self, user, params): pass def processParams(self, user, params): return { "user": user, "params": params }
Add a function for commands to process parameters
Add a function for commands to process parameters
Python
bsd-3-clause
ElementalAlchemist/txircd,DesertBus/txircd,Heufneutje/txircd
python
## Code Before: class Module(object): def hook(self, base): self.ircd = base return self class Mode(object): def hook(self, base): self.ircd = base return self def prefixSymbol(self): return None def checkSet(self, channel, param): return True def checkUnset(self, channel, param): return True def onJoin(self, channel, user, params): return "pass" def onMessage(self, sender, target, message): return ["pass"] def onPart(self, channel, user, reason): pass def onTopicChange(self, channel, user, topic): pass def commandData(self, command, *args): pass def Command(object): def hook(self, base): self.ircd = base return self def onUse(self, user, params): pass ## Instruction: Add a function for commands to process parameters ## Code After: class Module(object): def hook(self, base): self.ircd = base return self class Mode(object): def hook(self, base): self.ircd = base return self def prefixSymbol(self): return None def checkSet(self, channel, param): return True def checkUnset(self, channel, param): return True def onJoin(self, channel, user, params): return "pass" def onMessage(self, sender, target, message): return ["pass"] def onPart(self, channel, user, reason): pass def onTopicChange(self, channel, user, topic): pass def commandData(self, command, *args): pass def Command(object): def hook(self, base): self.ircd = base return self def onUse(self, user, params): pass def processParams(self, user, params): return { "user": user, "params": params }
// ... existing code ... return self def onUse(self, user, params): pass def processParams(self, user, params): return { "user": user, "params": params } // ... rest of the code ...
c65636cb688c6f8dbb74ea7ce03777c19a2e61ff
src/me/coley/recaf/ui/component/LabeledComponentGroup.java
src/me/coley/recaf/ui/component/LabeledComponentGroup.java
package me.coley.recaf.ui.component; import java.awt.Component; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import javax.swing.JPanel; /** * A group of radio-buttons that handles singular radio selection. * * @author Matt */ @SuppressWarnings("serial") public class LabeledComponentGroup extends JPanel { private final GridBagConstraints c = new GridBagConstraints(); public LabeledComponentGroup(LabeledComponent... components) { setLayout(new GridBagLayout()); c.anchor = GridBagConstraints.WEST; c.weightx = 1.0; c.weighty = 1.0; for (LabeledComponent comp : components) { add(comp); c.gridy += 1; } } /** * Overridden to prevent adding components the default way. */ @Override public Component add(Component comp) throws RuntimeException { if (comp instanceof LabeledComponent) { LabeledComponent lc = (LabeledComponent) comp; c.fill = GridBagConstraints.HORIZONTAL; c.gridx = 0; c.gridwidth = 1; super.add(lc.getLabel(), c); c.fill = GridBagConstraints.HORIZONTAL; c.gridx = 0; c.gridwidth = 1; super.add(lc.getComponent(), c); return comp; } else throw new RuntimeException("Non-LabeledComponent are not supported!!"); } }
package me.coley.recaf.ui.component; import java.awt.Component; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import javax.swing.JPanel; /** * A group of radio-buttons that handles singular radio selection. * * @author Matt */ @SuppressWarnings("serial") public class LabeledComponentGroup extends JPanel { private final GridBagConstraints c = new GridBagConstraints(); public LabeledComponentGroup(LabeledComponent... components) { setLayout(new GridBagLayout()); c.anchor = GridBagConstraints.WEST; c.weightx = 1.0; c.weighty = 1.0; c.gridy = 1; for (LabeledComponent comp : components) { add(comp); } } /** * Overridden to prevent adding components the default way. */ @Override public Component add(Component comp) throws RuntimeException { if (comp instanceof LabeledComponent) { LabeledComponent lc = (LabeledComponent) comp; c.fill = GridBagConstraints.HORIZONTAL; c.gridx = 0; c.gridwidth = 1; super.add(lc.getLabel(), c); c.fill = GridBagConstraints.HORIZONTAL; c.gridx = 1; c.gridwidth = 1; super.add(lc.getComponent(), c); c.gridy += 1; return comp; } else throw new RuntimeException("Non-LabeledComponent are not supported!!"); } }
Fix overlapping elements in groups
Fix overlapping elements in groups
Java
mit
Col-E/Recaf,Col-E/Recaf
java
## Code Before: package me.coley.recaf.ui.component; import java.awt.Component; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import javax.swing.JPanel; /** * A group of radio-buttons that handles singular radio selection. * * @author Matt */ @SuppressWarnings("serial") public class LabeledComponentGroup extends JPanel { private final GridBagConstraints c = new GridBagConstraints(); public LabeledComponentGroup(LabeledComponent... components) { setLayout(new GridBagLayout()); c.anchor = GridBagConstraints.WEST; c.weightx = 1.0; c.weighty = 1.0; for (LabeledComponent comp : components) { add(comp); c.gridy += 1; } } /** * Overridden to prevent adding components the default way. */ @Override public Component add(Component comp) throws RuntimeException { if (comp instanceof LabeledComponent) { LabeledComponent lc = (LabeledComponent) comp; c.fill = GridBagConstraints.HORIZONTAL; c.gridx = 0; c.gridwidth = 1; super.add(lc.getLabel(), c); c.fill = GridBagConstraints.HORIZONTAL; c.gridx = 0; c.gridwidth = 1; super.add(lc.getComponent(), c); return comp; } else throw new RuntimeException("Non-LabeledComponent are not supported!!"); } } ## Instruction: Fix overlapping elements in groups ## Code After: package me.coley.recaf.ui.component; import java.awt.Component; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import javax.swing.JPanel; /** * A group of radio-buttons that handles singular radio selection. * * @author Matt */ @SuppressWarnings("serial") public class LabeledComponentGroup extends JPanel { private final GridBagConstraints c = new GridBagConstraints(); public LabeledComponentGroup(LabeledComponent... components) { setLayout(new GridBagLayout()); c.anchor = GridBagConstraints.WEST; c.weightx = 1.0; c.weighty = 1.0; c.gridy = 1; for (LabeledComponent comp : components) { add(comp); } } /** * Overridden to prevent adding components the default way. */ @Override public Component add(Component comp) throws RuntimeException { if (comp instanceof LabeledComponent) { LabeledComponent lc = (LabeledComponent) comp; c.fill = GridBagConstraints.HORIZONTAL; c.gridx = 0; c.gridwidth = 1; super.add(lc.getLabel(), c); c.fill = GridBagConstraints.HORIZONTAL; c.gridx = 1; c.gridwidth = 1; super.add(lc.getComponent(), c); c.gridy += 1; return comp; } else throw new RuntimeException("Non-LabeledComponent are not supported!!"); } }
// ... existing code ... c.anchor = GridBagConstraints.WEST; c.weightx = 1.0; c.weighty = 1.0; c.gridy = 1; for (LabeledComponent comp : components) { add(comp); } } // ... modified code ... c.gridwidth = 1; super.add(lc.getLabel(), c); c.fill = GridBagConstraints.HORIZONTAL; c.gridx = 1; c.gridwidth = 1; super.add(lc.getComponent(), c); c.gridy += 1; return comp; } else throw new RuntimeException("Non-LabeledComponent are not supported!!"); } // ... rest of the code ...
5766291dcfd856b3c9d427cc596d5b8126dd13be
JavaTricks/src/JavaEnumToBits.java
JavaTricks/src/JavaEnumToBits.java
import java.math.BigInteger; public class JavaEnumToBits { enum orderedEnum { ONE, TWO, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT } public static void main(String[] args) { long testBits = BigInteger.ZERO.longValue(); BigInteger testInteger = BigInteger.valueOf(testBits); testInteger = testInteger.setBit(orderedEnum.ONE.ordinal()); testInteger = testInteger.setBit(orderedEnum.FIVE.ordinal()); testInteger = testInteger.setBit(orderedEnum.TWO.ordinal()); testInteger = testInteger.setBit(orderedEnum.EIGHT.ordinal()); System.out.println("JavaEnumToBits: testInteger = " + testInteger); for (orderedEnum val : orderedEnum.values()) { System.out.println("JavaEnumToBits: testBit(val) = " + testInteger.testBit(val.ordinal())); } } }
import java.math.BigInteger; public class JavaEnumToBits { enum orderedEnum { ONE, TWO, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT } public static void main(String[] args) { long testBits = BigInteger.ZERO.longValue(); BigInteger testInteger = BigInteger.valueOf(testBits); testInteger = testInteger.setBit(orderedEnum.ONE.ordinal()); testInteger = testInteger.setBit(orderedEnum.THREE.ordinal()); testInteger = testInteger.setBit(orderedEnum.SEVEN.ordinal()); testInteger = testInteger.setBit(orderedEnum.EIGHT.ordinal()); System.out.println("JavaEnumToBits: testInteger = " + testInteger); for (orderedEnum val : orderedEnum.values()) { System.out.println("JavaEnumToBits: testBit(val) = " + testInteger.testBit(val.ordinal())); } } }
Test of other setting values.
Test of other setting values.
Java
mpl-2.0
hinkmond/java-examples
java
## Code Before: import java.math.BigInteger; public class JavaEnumToBits { enum orderedEnum { ONE, TWO, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT } public static void main(String[] args) { long testBits = BigInteger.ZERO.longValue(); BigInteger testInteger = BigInteger.valueOf(testBits); testInteger = testInteger.setBit(orderedEnum.ONE.ordinal()); testInteger = testInteger.setBit(orderedEnum.FIVE.ordinal()); testInteger = testInteger.setBit(orderedEnum.TWO.ordinal()); testInteger = testInteger.setBit(orderedEnum.EIGHT.ordinal()); System.out.println("JavaEnumToBits: testInteger = " + testInteger); for (orderedEnum val : orderedEnum.values()) { System.out.println("JavaEnumToBits: testBit(val) = " + testInteger.testBit(val.ordinal())); } } } ## Instruction: Test of other setting values. ## Code After: import java.math.BigInteger; public class JavaEnumToBits { enum orderedEnum { ONE, TWO, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT } public static void main(String[] args) { long testBits = BigInteger.ZERO.longValue(); BigInteger testInteger = BigInteger.valueOf(testBits); testInteger = testInteger.setBit(orderedEnum.ONE.ordinal()); testInteger = testInteger.setBit(orderedEnum.THREE.ordinal()); testInteger = testInteger.setBit(orderedEnum.SEVEN.ordinal()); testInteger = testInteger.setBit(orderedEnum.EIGHT.ordinal()); System.out.println("JavaEnumToBits: testInteger = " + testInteger); for (orderedEnum val : orderedEnum.values()) { System.out.println("JavaEnumToBits: testBit(val) = " + testInteger.testBit(val.ordinal())); } } }
... BigInteger testInteger = BigInteger.valueOf(testBits); testInteger = testInteger.setBit(orderedEnum.ONE.ordinal()); testInteger = testInteger.setBit(orderedEnum.THREE.ordinal()); testInteger = testInteger.setBit(orderedEnum.SEVEN.ordinal()); testInteger = testInteger.setBit(orderedEnum.EIGHT.ordinal()); System.out.println("JavaEnumToBits: testInteger = " + testInteger); ...
b08bff08d69960c9035cefa4e4021d48530c5158
anemoi/Tests/test_Analytical.py
anemoi/Tests/test_Analytical.py
import unittest import numpy as np from anemoi import AnalyticalHelmholtz class TestMiniZephyr(unittest.TestCase): def setUp(self): pass def test_forwardModelling(self): nx = 100 nz = 200 systemConfig = { 'dx': 1., # m 'dz': 1., # m 'c': 2500., # m/s 'nx': nx, # count 'nz': nz, # count 'freq': 2e2, # Hz } Green = AnalyticalHelmholtz(systemConfig) u = Green(nx/2, nz/2) if __name__ == '__main__': unittest.main()
import unittest import numpy as np from anemoi import AnalyticalHelmholtz class TestAnalyticalHelmholtz(unittest.TestCase): def setUp(self): pass def test_cleanExecution(self): nx = 100 nz = 200 systemConfig = { 'c': 2500., # m/s 'nx': nx, # count 'nz': nz, # count 'freq': 2e2, # Hz } Green = AnalyticalHelmholtz(systemConfig) u = Green(nx/2, nz/2) if __name__ == '__main__': unittest.main()
Rename one test, use default dx and dz, fix naming of test class.
Rename one test, use default dx and dz, fix naming of test class.
Python
mit
uwoseis/zephyr,uwoseis/anemoi
python
## Code Before: import unittest import numpy as np from anemoi import AnalyticalHelmholtz class TestMiniZephyr(unittest.TestCase): def setUp(self): pass def test_forwardModelling(self): nx = 100 nz = 200 systemConfig = { 'dx': 1., # m 'dz': 1., # m 'c': 2500., # m/s 'nx': nx, # count 'nz': nz, # count 'freq': 2e2, # Hz } Green = AnalyticalHelmholtz(systemConfig) u = Green(nx/2, nz/2) if __name__ == '__main__': unittest.main() ## Instruction: Rename one test, use default dx and dz, fix naming of test class. ## Code After: import unittest import numpy as np from anemoi import AnalyticalHelmholtz class TestAnalyticalHelmholtz(unittest.TestCase): def setUp(self): pass def test_cleanExecution(self): nx = 100 nz = 200 systemConfig = { 'c': 2500., # m/s 'nx': nx, # count 'nz': nz, # count 'freq': 2e2, # Hz } Green = AnalyticalHelmholtz(systemConfig) u = Green(nx/2, nz/2) if __name__ == '__main__': unittest.main()
// ... existing code ... import numpy as np from anemoi import AnalyticalHelmholtz class TestAnalyticalHelmholtz(unittest.TestCase): def setUp(self): pass def test_cleanExecution(self): nx = 100 nz = 200 systemConfig = { 'c': 2500., # m/s 'nx': nx, # count 'nz': nz, # count // ... rest of the code ...
25caea025ae66c815cc85599e51b0b07d9957321
RectConfinementForce.h
RectConfinementForce.h
/*===- RectConfinementForce.h - libSimulation -================================= * * DEMON * * This file is distributed under the BSD Open Source License. See LICENSE.TXT * for details. * *===-----------------------------------------------------------------------===*/ #ifndef RECTCONFINEMENTFORCE_H #define RECTCONFINEMENTFORCE_H #include "Force.h" #include "VectorCompatibility.h" class RectConfinementForce : public Force { public: RectConfinementForce(Cloud * const myCloud, double confineConstX, double confineConstY); // confinement consts must be positive! ~RectConfinementForce() {} // destructor // public functions: // Note: currentTime parameter is necessary (due to parent class) but unused void force1(const double currentTime); // rk substep 1 void force2(const double currentTime); // rk substep 2 void force3(const double currentTime); // rk substep 3 void force4(const double currentTime); // rk substep 4 void writeForce(fitsfile * const file, int * const error) const; void readForce(fitsfile * const file, int * const error); private: // private variables: double confineX; double confineY; // private functions: void force(const unsigned int currentParticle, const __m128d currentPositionX, const __m128d currentPositionY); }; #endif // RECTCONFINEMENTFORCE_H
/*===- RectConfinementForce.h - libSimulation -================================= * * DEMON * * This file is distributed under the BSD Open Source License. See LICENSE.TXT * for details. * *===-----------------------------------------------------------------------===*/ #ifndef RECTCONFINEMENTFORCE_H #define RECTCONFINEMENTFORCE_H #include "Force.h" #include "VectorCompatibility.h" class RectConfinementForce : public Force { public: RectConfinementForce(Cloud * const myCloud, double confineConstX, double confineConstY); // IMPORTANT: In the above constructor, confineConst_'s must be positive! ~RectConfinementForce() {} // destructor // public functions: // Note: currentTime parameter is necessary (due to parent class) but unused void force1(const double currentTime); // rk substep 1 void force2(const double currentTime); // rk substep 2 void force3(const double currentTime); // rk substep 3 void force4(const double currentTime); // rk substep 4 void writeForce(fitsfile * const file, int * const error) const; void readForce(fitsfile * const file, int * const error); private: // private variables: double confineX; double confineY; // private functions: void force(const unsigned int currentParticle, const __m128d currentPositionX, const __m128d currentPositionY); }; #endif // RECTCONFINEMENTFORCE_H
Reword comment to be consistent with comment in ConfinementForce.
Reword comment to be consistent with comment in ConfinementForce.
C
bsd-3-clause
leios/demonsimulationcode,leios/demonsimulationcode
c
## Code Before: /*===- RectConfinementForce.h - libSimulation -================================= * * DEMON * * This file is distributed under the BSD Open Source License. See LICENSE.TXT * for details. * *===-----------------------------------------------------------------------===*/ #ifndef RECTCONFINEMENTFORCE_H #define RECTCONFINEMENTFORCE_H #include "Force.h" #include "VectorCompatibility.h" class RectConfinementForce : public Force { public: RectConfinementForce(Cloud * const myCloud, double confineConstX, double confineConstY); // confinement consts must be positive! ~RectConfinementForce() {} // destructor // public functions: // Note: currentTime parameter is necessary (due to parent class) but unused void force1(const double currentTime); // rk substep 1 void force2(const double currentTime); // rk substep 2 void force3(const double currentTime); // rk substep 3 void force4(const double currentTime); // rk substep 4 void writeForce(fitsfile * const file, int * const error) const; void readForce(fitsfile * const file, int * const error); private: // private variables: double confineX; double confineY; // private functions: void force(const unsigned int currentParticle, const __m128d currentPositionX, const __m128d currentPositionY); }; #endif // RECTCONFINEMENTFORCE_H ## Instruction: Reword comment to be consistent with comment in ConfinementForce. ## Code After: /*===- RectConfinementForce.h - libSimulation -================================= * * DEMON * * This file is distributed under the BSD Open Source License. See LICENSE.TXT * for details. * *===-----------------------------------------------------------------------===*/ #ifndef RECTCONFINEMENTFORCE_H #define RECTCONFINEMENTFORCE_H #include "Force.h" #include "VectorCompatibility.h" class RectConfinementForce : public Force { public: RectConfinementForce(Cloud * const myCloud, double confineConstX, double confineConstY); // IMPORTANT: In the above constructor, confineConst_'s must be positive! ~RectConfinementForce() {} // destructor // public functions: // Note: currentTime parameter is necessary (due to parent class) but unused void force1(const double currentTime); // rk substep 1 void force2(const double currentTime); // rk substep 2 void force3(const double currentTime); // rk substep 3 void force4(const double currentTime); // rk substep 4 void writeForce(fitsfile * const file, int * const error) const; void readForce(fitsfile * const file, int * const error); private: // private variables: double confineX; double confineY; // private functions: void force(const unsigned int currentParticle, const __m128d currentPositionX, const __m128d currentPositionY); }; #endif // RECTCONFINEMENTFORCE_H
... class RectConfinementForce : public Force { public: RectConfinementForce(Cloud * const myCloud, double confineConstX, double confineConstY); // IMPORTANT: In the above constructor, confineConst_'s must be positive! ~RectConfinementForce() {} // destructor // public functions: ...
038a905e58c42881c12d53911eb70926cfbc76f2
nsq/util.py
nsq/util.py
'''Some utilities used around town''' import struct def pack(message): '''Pack the provided message''' if isinstance(message, basestring): # Return # [ 4-byte message size ][ N-byte binary data ] return struct.pack('>l', len(message)) + message else: # Return # [ 4-byte body size ] # [ 4-byte num messages ] # [ 4-byte message #1 size ][ N-byte binary data ] # ... (repeated <num_messages> times) return pack( struct.pack('>l', len(message)) + ''.join(map(pack, message))) def hexify(message): '''Print out printable characters, but others in hex''' import string hexified = [] for char in message: if (char in '\n\r \t') or (char not in string.printable): hexified.append('\\x%02x' % ord(char)) else: hexified.append(char) return ''.join(hexified) def distribute(total, objects): '''Generator for (count, object) tuples that distributes count evenly among the provided objects''' for index, obj in enumerate(objects): start = (index * total) / len(objects) stop = ((index + 1) * total) / len(objects) yield (stop - start, obj)
'''Some utilities used around town''' import struct def pack_string(message): '''Pack a single message in the TCP protocol format''' # [ 4-byte message size ][ N-byte binary data ] return struct.pack('>l', len(message)) + message def pack_iterable(messages): '''Pack an iterable of messages in the TCP protocol format''' # [ 4-byte body size ] # [ 4-byte num messages ] # [ 4-byte message #1 size ][ N-byte binary data ] # ... (repeated <num_messages> times) return pack_string( struct.pack('>l', len(messages)) + ''.join(map(pack_string, messages))) def pack(message): '''Pack the provided message''' if isinstance(message, basestring): return pack_string(message) else: return pack_iterable(message) def hexify(message): '''Print out printable characters, but others in hex''' import string hexified = [] for char in message: if (char in '\n\r \t') or (char not in string.printable): hexified.append('\\x%02x' % ord(char)) else: hexified.append(char) return ''.join(hexified) def distribute(total, objects): '''Generator for (count, object) tuples that distributes count evenly among the provided objects''' for index, obj in enumerate(objects): start = (index * total) / len(objects) stop = ((index + 1) * total) / len(objects) yield (stop - start, obj)
Fix failing test about passing nested iterables to pack
Fix failing test about passing nested iterables to pack
Python
mit
dlecocq/nsq-py,dlecocq/nsq-py
python
## Code Before: '''Some utilities used around town''' import struct def pack(message): '''Pack the provided message''' if isinstance(message, basestring): # Return # [ 4-byte message size ][ N-byte binary data ] return struct.pack('>l', len(message)) + message else: # Return # [ 4-byte body size ] # [ 4-byte num messages ] # [ 4-byte message #1 size ][ N-byte binary data ] # ... (repeated <num_messages> times) return pack( struct.pack('>l', len(message)) + ''.join(map(pack, message))) def hexify(message): '''Print out printable characters, but others in hex''' import string hexified = [] for char in message: if (char in '\n\r \t') or (char not in string.printable): hexified.append('\\x%02x' % ord(char)) else: hexified.append(char) return ''.join(hexified) def distribute(total, objects): '''Generator for (count, object) tuples that distributes count evenly among the provided objects''' for index, obj in enumerate(objects): start = (index * total) / len(objects) stop = ((index + 1) * total) / len(objects) yield (stop - start, obj) ## Instruction: Fix failing test about passing nested iterables to pack ## Code After: '''Some utilities used around town''' import struct def pack_string(message): '''Pack a single message in the TCP protocol format''' # [ 4-byte message size ][ N-byte binary data ] return struct.pack('>l', len(message)) + message def pack_iterable(messages): '''Pack an iterable of messages in the TCP protocol format''' # [ 4-byte body size ] # [ 4-byte num messages ] # [ 4-byte message #1 size ][ N-byte binary data ] # ... (repeated <num_messages> times) return pack_string( struct.pack('>l', len(messages)) + ''.join(map(pack_string, messages))) def pack(message): '''Pack the provided message''' if isinstance(message, basestring): return pack_string(message) else: return pack_iterable(message) def hexify(message): '''Print out printable characters, but others in hex''' import string hexified = [] for char in message: if (char in '\n\r \t') or (char not in string.printable): hexified.append('\\x%02x' % ord(char)) else: hexified.append(char) return ''.join(hexified) def distribute(total, objects): '''Generator for (count, object) tuples that distributes count evenly among the provided objects''' for index, obj in enumerate(objects): start = (index * total) / len(objects) stop = ((index + 1) * total) / len(objects) yield (stop - start, obj)
# ... existing code ... import struct def pack_string(message): '''Pack a single message in the TCP protocol format''' # [ 4-byte message size ][ N-byte binary data ] return struct.pack('>l', len(message)) + message def pack_iterable(messages): '''Pack an iterable of messages in the TCP protocol format''' # [ 4-byte body size ] # [ 4-byte num messages ] # [ 4-byte message #1 size ][ N-byte binary data ] # ... (repeated <num_messages> times) return pack_string( struct.pack('>l', len(messages)) + ''.join(map(pack_string, messages))) def pack(message): '''Pack the provided message''' if isinstance(message, basestring): return pack_string(message) else: return pack_iterable(message) def hexify(message): # ... rest of the code ...
ab3dc6466b617a5bf5a0bec2c122eca645c1d29f
cloudera-framework-assembly/src/main/resources/python/script_util.py
cloudera-framework-assembly/src/main/resources/python/script_util.py
import os def hdfs_make_qualified(path): return path if 'CF_HADOOP_DEFAULT_FS' not in os.environ else os.environ['CF_HADOOP_DEFAULT_FS'] + path
import os import re def hdfs_make_qualified(path): return path if (re.match(r'[.]*://[.]*', path) or 'CF_HADOOP_DEFAULT_FS' not in os.environ) \ else os.environ['CF_HADOOP_DEFAULT_FS'] + path
Update python script util to detect if paths are already fully qualified
Update python script util to detect if paths are already fully qualified
Python
apache-2.0
ggear/cloudera-framework,ggear/cloudera-framework,ggear/cloudera-framework
python
## Code Before: import os def hdfs_make_qualified(path): return path if 'CF_HADOOP_DEFAULT_FS' not in os.environ else os.environ['CF_HADOOP_DEFAULT_FS'] + path ## Instruction: Update python script util to detect if paths are already fully qualified ## Code After: import os import re def hdfs_make_qualified(path): return path if (re.match(r'[.]*://[.]*', path) or 'CF_HADOOP_DEFAULT_FS' not in os.environ) \ else os.environ['CF_HADOOP_DEFAULT_FS'] + path
... import os import re def hdfs_make_qualified(path): return path if (re.match(r'[.]*://[.]*', path) or 'CF_HADOOP_DEFAULT_FS' not in os.environ) \ else os.environ['CF_HADOOP_DEFAULT_FS'] + path ...
5aca39cef15ea4381b30127b8ded31ec37ffd273
script/notification/ifttt.py
script/notification/ifttt.py
from logs import * import requests class Ifttt(object): """ """ def __init__(self, config, packpub_info, upload_info): self.__packpub_info = packpub_info self.__url = "https://maker.ifttt.com/trigger/{eventName}/with/key/{apiKey}".format( eventName=config.get('ifttt', 'ifttt.event_name'), apiKey=config.get('ifttt', 'ifttt.key') ) def send(self): r = requests.post(self.__url, data = {'value1':self.__packpub_info['title'].encode('utf-8'), 'value2':self.__packpub_info['description'].encode('utf-8')}) log_success('[+] notification sent to IFTTT') def sendError(self, exception, source): title = "packtpub-crawler [{source}]: Could not download ebook".format(source=source) r = requests.post(self.__url, data = {'value1':title, 'value2':repr(exception)}) log_success('[+] error notification sent to IFTTT')
from logs import * import requests class Ifttt(object): """ """ def __init__(self, config, packpub_info, upload_info): self.__packpub_info = packpub_info self.__url = "https://maker.ifttt.com/trigger/{eventName}/with/key/{apiKey}".format( eventName=config.get('ifttt', 'ifttt.event_name'), apiKey=config.get('ifttt', 'ifttt.key') ) def send(self): r = requests.post(self.__url, data = { 'value1':self.__packpub_info['title'].encode('utf-8'), 'value2':self.__packpub_info['description'].encode('utf-8'), 'value3':self.__packpub_info['url_image'] }) log_success('[+] notification sent to IFTTT') def sendError(self, exception, source): title = "packtpub-crawler [{source}]: Could not download ebook".format(source=source) r = requests.post(self.__url, data = {'value1':title, 'value2':repr(exception)}) log_success('[+] error notification sent to IFTTT')
Add image to ifff request
Add image to ifff request
Python
mit
niqdev/packtpub-crawler,niqdev/packtpub-crawler,niqdev/packtpub-crawler
python
## Code Before: from logs import * import requests class Ifttt(object): """ """ def __init__(self, config, packpub_info, upload_info): self.__packpub_info = packpub_info self.__url = "https://maker.ifttt.com/trigger/{eventName}/with/key/{apiKey}".format( eventName=config.get('ifttt', 'ifttt.event_name'), apiKey=config.get('ifttt', 'ifttt.key') ) def send(self): r = requests.post(self.__url, data = {'value1':self.__packpub_info['title'].encode('utf-8'), 'value2':self.__packpub_info['description'].encode('utf-8')}) log_success('[+] notification sent to IFTTT') def sendError(self, exception, source): title = "packtpub-crawler [{source}]: Could not download ebook".format(source=source) r = requests.post(self.__url, data = {'value1':title, 'value2':repr(exception)}) log_success('[+] error notification sent to IFTTT') ## Instruction: Add image to ifff request ## Code After: from logs import * import requests class Ifttt(object): """ """ def __init__(self, config, packpub_info, upload_info): self.__packpub_info = packpub_info self.__url = "https://maker.ifttt.com/trigger/{eventName}/with/key/{apiKey}".format( eventName=config.get('ifttt', 'ifttt.event_name'), apiKey=config.get('ifttt', 'ifttt.key') ) def send(self): r = requests.post(self.__url, data = { 'value1':self.__packpub_info['title'].encode('utf-8'), 'value2':self.__packpub_info['description'].encode('utf-8'), 'value3':self.__packpub_info['url_image'] }) log_success('[+] notification sent to IFTTT') def sendError(self, exception, source): title = "packtpub-crawler [{source}]: Could not download ebook".format(source=source) r = requests.post(self.__url, data = {'value1':title, 'value2':repr(exception)}) log_success('[+] error notification sent to IFTTT')
... ) def send(self): r = requests.post(self.__url, data = { 'value1':self.__packpub_info['title'].encode('utf-8'), 'value2':self.__packpub_info['description'].encode('utf-8'), 'value3':self.__packpub_info['url_image'] }) log_success('[+] notification sent to IFTTT') def sendError(self, exception, source): ...
5fc43ec5dad84f752e9417ecd1934521bf7204d7
src/main/java/nl/eernie/jmoribus/model/Step.java
src/main/java/nl/eernie/jmoribus/model/Step.java
package nl.eernie.jmoribus.model; import org.apache.commons.lang3.StringUtils; import java.util.ArrayList; import java.util.List; public class Step { private StepType stepType; private List<StepLine> stepLines = new ArrayList<>(); public Step(StepType stepType) { this.stepType = stepType; } public StepType getStepType() { return stepType; } public StepLine getFirstStepLine() { return stepLines.get(0); } public List<StepLine> getStepLines() { return stepLines; } public String getCombinedStepLines(){ String combined = ""; for(StepLine stepLine: stepLines){ if(StringUtils.isNotBlank(combined)){ combined = combined + " "; } if(stepLine instanceof Table){ int index = stepLines.indexOf(stepLine); combined = combined + "TABLE"+index; }else{ combined = combined + stepLine.getText(); } } return combined; } }
package nl.eernie.jmoribus.model; import org.apache.commons.lang3.StringUtils; import java.util.ArrayList; import java.util.List; public class Step { private StepType stepType; private List<StepLine> stepLines = new ArrayList<>(); public Step(StepType stepType) { this.stepType = stepType; } public StepType getStepType() { return stepType; } public StepLine getFirstStepLine() { return stepLines.get(0); } public List<StepLine> getStepLines() { return stepLines; } public String getCombinedStepLines(){ StringBuffer buffer = new StringBuffer(); for(StepLine stepLine: stepLines){ if(StringUtils.isNotBlank(buffer.toString())){ buffer.append(" "); } if(stepLine instanceof Table){ int index = stepLines.indexOf(stepLine); buffer.append("TABLE"+index); }else{ buffer.append(stepLine.getText()); } } return buffer.toString(); } }
Remove defect for building a string in a loop
Remove defect for building a string in a loop
Java
mit
Eernie/JMoribus
java
## Code Before: package nl.eernie.jmoribus.model; import org.apache.commons.lang3.StringUtils; import java.util.ArrayList; import java.util.List; public class Step { private StepType stepType; private List<StepLine> stepLines = new ArrayList<>(); public Step(StepType stepType) { this.stepType = stepType; } public StepType getStepType() { return stepType; } public StepLine getFirstStepLine() { return stepLines.get(0); } public List<StepLine> getStepLines() { return stepLines; } public String getCombinedStepLines(){ String combined = ""; for(StepLine stepLine: stepLines){ if(StringUtils.isNotBlank(combined)){ combined = combined + " "; } if(stepLine instanceof Table){ int index = stepLines.indexOf(stepLine); combined = combined + "TABLE"+index; }else{ combined = combined + stepLine.getText(); } } return combined; } } ## Instruction: Remove defect for building a string in a loop ## Code After: package nl.eernie.jmoribus.model; import org.apache.commons.lang3.StringUtils; import java.util.ArrayList; import java.util.List; public class Step { private StepType stepType; private List<StepLine> stepLines = new ArrayList<>(); public Step(StepType stepType) { this.stepType = stepType; } public StepType getStepType() { return stepType; } public StepLine getFirstStepLine() { return stepLines.get(0); } public List<StepLine> getStepLines() { return stepLines; } public String getCombinedStepLines(){ StringBuffer buffer = new StringBuffer(); for(StepLine stepLine: stepLines){ if(StringUtils.isNotBlank(buffer.toString())){ buffer.append(" "); } if(stepLine instanceof Table){ int index = stepLines.indexOf(stepLine); buffer.append("TABLE"+index); }else{ buffer.append(stepLine.getText()); } } return buffer.toString(); } }
// ... existing code ... } public String getCombinedStepLines(){ StringBuffer buffer = new StringBuffer(); for(StepLine stepLine: stepLines){ if(StringUtils.isNotBlank(buffer.toString())){ buffer.append(" "); } if(stepLine instanceof Table){ int index = stepLines.indexOf(stepLine); buffer.append("TABLE"+index); }else{ buffer.append(stepLine.getText()); } } return buffer.toString(); } } // ... rest of the code ...
0f8e2313d6f0ec06806ea05e861d1fc47d3c3016
utils/internal/zz_parse.py
utils/internal/zz_parse.py
import sys sys.path.insert(0, '../..') from pycparser import c_parser, c_ast, parse_file if __name__ == "__main__": #ast = parse_file('zc_pp.c', use_cpp=True, cpp_path="../cpp.exe") parser = c_parser.CParser() #code = r'''int ar[30];''' code = r''' char ***arr3d[40]; ''' #code = r''' #int foo(int a, int arr[*]); #''' print(code) ast = parser.parse(code) ast.show(attrnames=True, nodenames=True) print(ast.ext[0].__slots__) print(dir(ast.ext[0]))
from __future__ import print_function import sys from pycparser import c_parser, c_generator, c_ast, parse_file if __name__ == "__main__": parser = c_parser.CParser() code = r''' void* ptr = (int[ ]){0}; ''' print(code) ast = parser.parse(code) ast.show(attrnames=True, nodenames=True) print(ast.ext[0].__slots__) print(dir(ast.ext[0])) print("==== From C generator:") generator = c_generator.CGenerator() print(generator.visit(ast))
Clean up internal hacking util
Clean up internal hacking util
Python
bsd-3-clause
CtheSky/pycparser,CtheSky/pycparser,CtheSky/pycparser
python
## Code Before: import sys sys.path.insert(0, '../..') from pycparser import c_parser, c_ast, parse_file if __name__ == "__main__": #ast = parse_file('zc_pp.c', use_cpp=True, cpp_path="../cpp.exe") parser = c_parser.CParser() #code = r'''int ar[30];''' code = r''' char ***arr3d[40]; ''' #code = r''' #int foo(int a, int arr[*]); #''' print(code) ast = parser.parse(code) ast.show(attrnames=True, nodenames=True) print(ast.ext[0].__slots__) print(dir(ast.ext[0])) ## Instruction: Clean up internal hacking util ## Code After: from __future__ import print_function import sys from pycparser import c_parser, c_generator, c_ast, parse_file if __name__ == "__main__": parser = c_parser.CParser() code = r''' void* ptr = (int[ ]){0}; ''' print(code) ast = parser.parse(code) ast.show(attrnames=True, nodenames=True) print(ast.ext[0].__slots__) print(dir(ast.ext[0])) print("==== From C generator:") generator = c_generator.CGenerator() print(generator.visit(ast))
... from __future__ import print_function import sys from pycparser import c_parser, c_generator, c_ast, parse_file if __name__ == "__main__": parser = c_parser.CParser() code = r''' void* ptr = (int[ ]){0}; ''' print(code) ast = parser.parse(code) ast.show(attrnames=True, nodenames=True) print(ast.ext[0].__slots__) print(dir(ast.ext[0])) print("==== From C generator:") generator = c_generator.CGenerator() print(generator.visit(ast)) ...
58d5cd3d0bb8a51a60747d6b52e589e879c6e4bb
src/main/java/com/serebit/autotitan/data/DataManager.kt
src/main/java/com/serebit/autotitan/data/DataManager.kt
package com.serebit.autotitan.data import com.google.gson.Gson import com.google.gson.GsonBuilder import java.io.File val serializer: Gson = GsonBuilder().apply { serializeNulls() }.create() class DataManager(type: Class<*>) { private val parentFolder = File(DataManager::class.java.protectionDomain.codeSource.location.toURI()).parentFile val dataFolder = File("$parentFolder/data/${type.simpleName}").apply { mkdirs() } inline fun <reified T> read(fileName: String): T? { val file = File("$dataFolder/$fileName") return if (file.exists()) serializer.fromJson(file.readText(), T::class.java) else null } fun write(fileName: String, obj: Any) { File("$dataFolder/$fileName").apply { createNewFile() }.writeText(serializer.toJson(obj)) } }
package com.serebit.autotitan.data import com.google.gson.Gson import com.google.gson.GsonBuilder import java.io.File val serializer: Gson = GsonBuilder().apply { serializeNulls() }.create() class DataManager(type: Class<*>) { private val parentFolder = File(DataManager::class.java.protectionDomain.codeSource.location.toURI()).parentFile private val dataFolder = File("$parentFolder/data/${type.simpleName}").apply { mkdirs() } inline fun <reified T : Any> read(fileName: String): T? = read(fileName, T::class.java) fun <T : Any> read(fileName: String, type: Class<T>): T? { val file = File("$dataFolder/$fileName") return if (file.exists()) serializer.fromJson(file.readText(), type) else null } fun write(fileName: String, obj: Any) { File("$dataFolder/$fileName").apply { createNewFile() }.writeText(serializer.toJson(obj)) } }
Split read function into two functions, allowing dataFolder to become private
Split read function into two functions, allowing dataFolder to become private
Kotlin
apache-2.0
serebit/autotitan
kotlin
## Code Before: package com.serebit.autotitan.data import com.google.gson.Gson import com.google.gson.GsonBuilder import java.io.File val serializer: Gson = GsonBuilder().apply { serializeNulls() }.create() class DataManager(type: Class<*>) { private val parentFolder = File(DataManager::class.java.protectionDomain.codeSource.location.toURI()).parentFile val dataFolder = File("$parentFolder/data/${type.simpleName}").apply { mkdirs() } inline fun <reified T> read(fileName: String): T? { val file = File("$dataFolder/$fileName") return if (file.exists()) serializer.fromJson(file.readText(), T::class.java) else null } fun write(fileName: String, obj: Any) { File("$dataFolder/$fileName").apply { createNewFile() }.writeText(serializer.toJson(obj)) } } ## Instruction: Split read function into two functions, allowing dataFolder to become private ## Code After: package com.serebit.autotitan.data import com.google.gson.Gson import com.google.gson.GsonBuilder import java.io.File val serializer: Gson = GsonBuilder().apply { serializeNulls() }.create() class DataManager(type: Class<*>) { private val parentFolder = File(DataManager::class.java.protectionDomain.codeSource.location.toURI()).parentFile private val dataFolder = File("$parentFolder/data/${type.simpleName}").apply { mkdirs() } inline fun <reified T : Any> read(fileName: String): T? = read(fileName, T::class.java) fun <T : Any> read(fileName: String, type: Class<T>): T? { val file = File("$dataFolder/$fileName") return if (file.exists()) serializer.fromJson(file.readText(), type) else null } fun write(fileName: String, obj: Any) { File("$dataFolder/$fileName").apply { createNewFile() }.writeText(serializer.toJson(obj)) } }
... class DataManager(type: Class<*>) { private val parentFolder = File(DataManager::class.java.protectionDomain.codeSource.location.toURI()).parentFile private val dataFolder = File("$parentFolder/data/${type.simpleName}").apply { mkdirs() } inline fun <reified T : Any> read(fileName: String): T? = read(fileName, T::class.java) fun <T : Any> read(fileName: String, type: Class<T>): T? { val file = File("$dataFolder/$fileName") return if (file.exists()) serializer.fromJson(file.readText(), type) else null } fun write(fileName: String, obj: Any) { ...
f647e74d9e9e703f3697d5b987f367a63775b806
app/src/main/java/bloople/net/stories/StoryParser.java
app/src/main/java/bloople/net/stories/StoryParser.java
package bloople.net.stories; import java.io.IOException; import java.io.Reader; import java.util.Scanner; /** * Created by i on 27/05/2016. */ public class StoryParser { private Scanner scanner; public StoryParser(Reader reader) { scanner = new Scanner(reader); scanner.useDelimiter("\n\n"); } public void parse(Story story) throws IOException { while(scanner.hasNext()) { story.add(next()); } } public Node next() throws IOException { String content = scanner.next(); if(content.startsWith("#")) { return NodeFactory.heading(content); } else { return NodeFactory.paragraph(content); } } }
package bloople.net.stories; import java.io.IOException; import java.io.Reader; import java.util.Scanner; /** * Created by i on 27/05/2016. */ public class StoryParser { private Scanner scanner; public StoryParser(Reader reader) { scanner = new Scanner(reader); scanner.useDelimiter("(?:\r?\n){2,}+"); } public void parse(Story story) throws IOException { while(scanner.hasNext()) { story.add(next()); } } public Node next() throws IOException { String content = scanner.next(); if(content.startsWith("#")) { return NodeFactory.heading(content); } else { return NodeFactory.paragraph(content); } } }
Fix story parsing to support both windows and linux style newlines; Allow extra newlines between nodes
Fix story parsing to support both windows and linux style newlines; Allow extra newlines between nodes
Java
mit
bloopletech/stories-app
java
## Code Before: package bloople.net.stories; import java.io.IOException; import java.io.Reader; import java.util.Scanner; /** * Created by i on 27/05/2016. */ public class StoryParser { private Scanner scanner; public StoryParser(Reader reader) { scanner = new Scanner(reader); scanner.useDelimiter("\n\n"); } public void parse(Story story) throws IOException { while(scanner.hasNext()) { story.add(next()); } } public Node next() throws IOException { String content = scanner.next(); if(content.startsWith("#")) { return NodeFactory.heading(content); } else { return NodeFactory.paragraph(content); } } } ## Instruction: Fix story parsing to support both windows and linux style newlines; Allow extra newlines between nodes ## Code After: package bloople.net.stories; import java.io.IOException; import java.io.Reader; import java.util.Scanner; /** * Created by i on 27/05/2016. */ public class StoryParser { private Scanner scanner; public StoryParser(Reader reader) { scanner = new Scanner(reader); scanner.useDelimiter("(?:\r?\n){2,}+"); } public void parse(Story story) throws IOException { while(scanner.hasNext()) { story.add(next()); } } public Node next() throws IOException { String content = scanner.next(); if(content.startsWith("#")) { return NodeFactory.heading(content); } else { return NodeFactory.paragraph(content); } } }
... public StoryParser(Reader reader) { scanner = new Scanner(reader); scanner.useDelimiter("(?:\r?\n){2,}+"); } public void parse(Story story) throws IOException { ...
8afbd0fe7f4732d8484a2a41b91451ec220fc2f8
tools/perf/benchmarks/memory.py
tools/perf/benchmarks/memory.py
from telemetry import test from measurements import memory class Memory(test.Test): test = memory.Memory page_set = 'page_sets/top_25.json' class Reload(test.Test): test = memory.Memory page_set = 'page_sets/2012Q3.json'
from telemetry import test from measurements import memory class MemoryTop25(test.Test): test = memory.Memory page_set = 'page_sets/top_25.json' class Reload2012Q3(test.Test): test = memory.Memory page_set = 'page_sets/2012Q3.json'
Rename Memory benchmark to avoid conflict with Memory measurement.
[telemetry] Rename Memory benchmark to avoid conflict with Memory measurement. Quick fix for now, but I may need to reconsider how run_measurement resolved name conflicts. BUG=263511 TEST=None. [email protected] Review URL: https://chromiumcodereview.appspot.com/19915008 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@213290 0039d316-1c4b-4281-b951-d872f2087c98
Python
bsd-3-clause
PeterWangIntel/chromium-crosswalk,markYoungH/chromium.src,dednal/chromium.src,jaruba/chromium.src,mogoweb/chromium-crosswalk,jaruba/chromium.src,chuan9/chromium-crosswalk,Jonekee/chromium.src,mogoweb/chromium-crosswalk,M4sse/chromium.src,fujunwei/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,M4sse/chromium.src,littlstar/chromium.src,TheTypoMaster/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,jaruba/chromium.src,markYoungH/chromium.src,dushu1203/chromium.src,Just-D/chromium-1,markYoungH/chromium.src,Just-D/chromium-1,mogoweb/chromium-crosswalk,Fireblend/chromium-crosswalk,Fireblend/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,fujunwei/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,jaruba/chromium.src,bright-sparks/chromium-spacewalk,Pluto-tv/chromium-crosswalk,ltilve/chromium,markYoungH/chromium.src,Fireblend/chromium-crosswalk,anirudhSK/chromium,ondra-novak/chromium.src,dushu1203/chromium.src,Jonekee/chromium.src,ChromiumWebApps/chromium,axinging/chromium-crosswalk,fujunwei/chromium-crosswalk,hgl888/chromium-crosswalk,hgl888/chromium-crosswalk-efl,krieger-od/nwjs_chromium.src,crosswalk-project/chromium-crosswalk-efl,jaruba/chromium.src,bright-sparks/chromium-spacewalk,krieger-od/nwjs_chromium.src,chuan9/chromium-crosswalk,dednal/chromium.src,ChromiumWebApps/chromium,dednal/chromium.src,markYoungH/chromium.src,Chilledheart/chromium,anirudhSK/chromium,krieger-od/nwjs_chromium.src,crosswalk-project/chromium-crosswalk-efl,markYoungH/chromium.src,Pluto-tv/chromium-crosswalk,chuan9/chromium-crosswalk,axinging/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,hgl888/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,chuan9/chromium-crosswalk,Jonekee/chromium.src,hgl888/chromium-crosswalk-efl,ltilve/chromium,mohamed--abdel-maksoud/chromium.src,TheTypoMaster/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,Jonekee/chromium.src,dushu1203/chromium.src,hgl888/chromium-crosswalk-efl,anirudhSK/chromium,hgl888/chromium-crosswalk-efl,patrickm/chromium.src,patrickm/chromium.src,Chilledheart/chromium,fujunwei/chromium-crosswalk,chuan9/chromium-crosswalk,patrickm/chromium.src,axinging/chromium-crosswalk,Fireblend/chromium-crosswalk,ltilve/chromium,ondra-novak/chromium.src,dednal/chromium.src,Pluto-tv/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,ChromiumWebApps/chromium,crosswalk-project/chromium-crosswalk-efl,Chilledheart/chromium,anirudhSK/chromium,axinging/chromium-crosswalk,dednal/chromium.src,Just-D/chromium-1,dednal/chromium.src,hgl888/chromium-crosswalk,hgl888/chromium-crosswalk-efl,M4sse/chromium.src,dushu1203/chromium.src,TheTypoMaster/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,ChromiumWebApps/chromium,ondra-novak/chromium.src,markYoungH/chromium.src,patrickm/chromium.src,mohamed--abdel-maksoud/chromium.src,anirudhSK/chromium,fujunwei/chromium-crosswalk,krieger-od/nwjs_chromium.src,Pluto-tv/chromium-crosswalk,littlstar/chromium.src,markYoungH/chromium.src,Pluto-tv/chromium-crosswalk,anirudhSK/chromium,chuan9/chromium-crosswalk,Jonekee/chromium.src,Jonekee/chromium.src,Jonekee/chromium.src,krieger-od/nwjs_chromium.src,dednal/chromium.src,Jonekee/chromium.src,Just-D/chromium-1,mogoweb/chromium-crosswalk,patrickm/chromium.src,hgl888/chromium-crosswalk,Just-D/chromium-1,M4sse/chromium.src,Just-D/chromium-1,krieger-od/nwjs_chromium.src,axinging/chromium-crosswalk,axinging/chromium-crosswalk,Fireblend/chromium-crosswalk,patrickm/chromium.src,ltilve/chromium,bright-sparks/chromium-spacewalk,mogoweb/chromium-crosswalk,ltilve/chromium,bright-sparks/chromium-spacewalk,mogoweb/chromium-crosswalk,M4sse/chromium.src,dednal/chromium.src,ltilve/chromium,mogoweb/chromium-crosswalk,jaruba/chromium.src,Pluto-tv/chromium-crosswalk,Fireblend/chromium-crosswalk,ltilve/chromium,bright-sparks/chromium-spacewalk,ChromiumWebApps/chromium,fujunwei/chromium-crosswalk,anirudhSK/chromium,markYoungH/chromium.src,mogoweb/chromium-crosswalk,M4sse/chromium.src,bright-sparks/chromium-spacewalk,littlstar/chromium.src,patrickm/chromium.src,ltilve/chromium,hgl888/chromium-crosswalk-efl,hgl888/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,krieger-od/nwjs_chromium.src,Jonekee/chromium.src,ondra-novak/chromium.src,jaruba/chromium.src,jaruba/chromium.src,ChromiumWebApps/chromium,dushu1203/chromium.src,fujunwei/chromium-crosswalk,ChromiumWebApps/chromium,ondra-novak/chromium.src,hgl888/chromium-crosswalk,anirudhSK/chromium,ondra-novak/chromium.src,krieger-od/nwjs_chromium.src,TheTypoMaster/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,dushu1203/chromium.src,littlstar/chromium.src,Chilledheart/chromium,Just-D/chromium-1,chuan9/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,crosswalk-project/chromium-crosswalk-efl,fujunwei/chromium-crosswalk,axinging/chromium-crosswalk,dushu1203/chromium.src,bright-sparks/chromium-spacewalk,dushu1203/chromium.src,Pluto-tv/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,patrickm/chromium.src,ChromiumWebApps/chromium,dushu1203/chromium.src,M4sse/chromium.src,TheTypoMaster/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,hgl888/chromium-crosswalk-efl,anirudhSK/chromium,ChromiumWebApps/chromium,bright-sparks/chromium-spacewalk,hgl888/chromium-crosswalk-efl,ondra-novak/chromium.src,axinging/chromium-crosswalk,Pluto-tv/chromium-crosswalk,axinging/chromium-crosswalk,fujunwei/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,anirudhSK/chromium,mogoweb/chromium-crosswalk,hgl888/chromium-crosswalk,Chilledheart/chromium,ChromiumWebApps/chromium,dednal/chromium.src,mohamed--abdel-maksoud/chromium.src,littlstar/chromium.src,Fireblend/chromium-crosswalk,hgl888/chromium-crosswalk-efl,PeterWangIntel/chromium-crosswalk,Chilledheart/chromium,hgl888/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,littlstar/chromium.src,axinging/chromium-crosswalk,Jonekee/chromium.src,M4sse/chromium.src,anirudhSK/chromium,PeterWangIntel/chromium-crosswalk,dushu1203/chromium.src,ltilve/chromium,anirudhSK/chromium,bright-sparks/chromium-spacewalk,krieger-od/nwjs_chromium.src,mohamed--abdel-maksoud/chromium.src,Chilledheart/chromium,Fireblend/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,M4sse/chromium.src,ChromiumWebApps/chromium,markYoungH/chromium.src,ChromiumWebApps/chromium,crosswalk-project/chromium-crosswalk-efl,Pluto-tv/chromium-crosswalk,jaruba/chromium.src,Just-D/chromium-1,dednal/chromium.src,littlstar/chromium.src,dednal/chromium.src,dushu1203/chromium.src,hgl888/chromium-crosswalk,krieger-od/nwjs_chromium.src,jaruba/chromium.src,Chilledheart/chromium,TheTypoMaster/chromium-crosswalk,chuan9/chromium-crosswalk,M4sse/chromium.src,krieger-od/nwjs_chromium.src,Chilledheart/chromium,jaruba/chromium.src,markYoungH/chromium.src,mohamed--abdel-maksoud/chromium.src,crosswalk-project/chromium-crosswalk-efl,patrickm/chromium.src,Just-D/chromium-1,littlstar/chromium.src,ondra-novak/chromium.src,M4sse/chromium.src,Jonekee/chromium.src,chuan9/chromium-crosswalk,hgl888/chromium-crosswalk-efl,Fireblend/chromium-crosswalk,mogoweb/chromium-crosswalk,axinging/chromium-crosswalk,ondra-novak/chromium.src
python
## Code Before: from telemetry import test from measurements import memory class Memory(test.Test): test = memory.Memory page_set = 'page_sets/top_25.json' class Reload(test.Test): test = memory.Memory page_set = 'page_sets/2012Q3.json' ## Instruction: [telemetry] Rename Memory benchmark to avoid conflict with Memory measurement. Quick fix for now, but I may need to reconsider how run_measurement resolved name conflicts. BUG=263511 TEST=None. [email protected] Review URL: https://chromiumcodereview.appspot.com/19915008 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@213290 0039d316-1c4b-4281-b951-d872f2087c98 ## Code After: from telemetry import test from measurements import memory class MemoryTop25(test.Test): test = memory.Memory page_set = 'page_sets/top_25.json' class Reload2012Q3(test.Test): test = memory.Memory page_set = 'page_sets/2012Q3.json'
# ... existing code ... from measurements import memory class MemoryTop25(test.Test): test = memory.Memory page_set = 'page_sets/top_25.json' class Reload2012Q3(test.Test): test = memory.Memory page_set = 'page_sets/2012Q3.json' # ... rest of the code ...
ca1b92118d0c432484b3ac7f59924a1a65a59e17
irco/utils.py
irco/utils.py
import os import glob from irco import parser, tabular def get_file_list(sources): for source in sources: if os.path.isdir(source): for path in glob.glob(os.path.join(source, '*.txt')): yield path elif os.path.isfile(source): yield source def get_dataset(source, records=None): table = tabular.Table(notset=None) for path in get_file_list(source): with open(path) as fh: for record in parser.parse(fh, records): table.add(record) return table.dataset()
import os from irco import parser, tabular def get_file_list(sources): for source in sources: if os.path.isdir(source): for path in sorted(os.listdir(source)): _, ext = os.path.splitext(path) if ext not in ('.txt', '.csv', '.tsv'): continue path = os.path.join(source, path) yield path elif os.path.isfile(source): yield source def get_dataset(source, records=None): table = tabular.Table(notset=None) for path in get_file_list(source): with open(path) as fh: for record in parser.parse(fh, records): table.add(record) return table.dataset()
Support recursive import of CSV and TSV files as well as TXT ones.
Support recursive import of CSV and TSV files as well as TXT ones.
Python
mit
GaretJax/irco,GaretJax/irco,GaretJax/irco,GaretJax/irco
python
## Code Before: import os import glob from irco import parser, tabular def get_file_list(sources): for source in sources: if os.path.isdir(source): for path in glob.glob(os.path.join(source, '*.txt')): yield path elif os.path.isfile(source): yield source def get_dataset(source, records=None): table = tabular.Table(notset=None) for path in get_file_list(source): with open(path) as fh: for record in parser.parse(fh, records): table.add(record) return table.dataset() ## Instruction: Support recursive import of CSV and TSV files as well as TXT ones. ## Code After: import os from irco import parser, tabular def get_file_list(sources): for source in sources: if os.path.isdir(source): for path in sorted(os.listdir(source)): _, ext = os.path.splitext(path) if ext not in ('.txt', '.csv', '.tsv'): continue path = os.path.join(source, path) yield path elif os.path.isfile(source): yield source def get_dataset(source, records=None): table = tabular.Table(notset=None) for path in get_file_list(source): with open(path) as fh: for record in parser.parse(fh, records): table.add(record) return table.dataset()
... import os from irco import parser, tabular ... def get_file_list(sources): for source in sources: if os.path.isdir(source): for path in sorted(os.listdir(source)): _, ext = os.path.splitext(path) if ext not in ('.txt', '.csv', '.tsv'): continue path = os.path.join(source, path) yield path elif os.path.isfile(source): yield source ...
16e9987e680a6a44acdb14bd7554414dfe261056
sale_automatic_workflow/models/stock_move.py
sale_automatic_workflow/models/stock_move.py
from odoo import api, models class StockMove(models.Model): _inherit = 'stock.move' @api.model def _prepare_picking_assign(self, move): values = super(StockMove, self)._prepare_picking_assign(move) if move.procurement_id.sale_line_id: sale = move.procurement_id.sale_line_id.order_id values['workflow_process_id'] = sale.workflow_process_id.id return values
from odoo import api, models class StockMove(models.Model): _inherit = 'stock.move' @api.multi def _get_new_picking_values(self): values = super(StockMove, self)._get_new_picking_values() if self.procurement_id.sale_line_id: sale = self.procurement_id.sale_line_id.order_id values['workflow_process_id'] = sale.workflow_process_id.id return values
Fix API type & method name for picking values
Fix API type & method name for picking values
Python
agpl-3.0
kittiu/sale-workflow,kittiu/sale-workflow
python
## Code Before: from odoo import api, models class StockMove(models.Model): _inherit = 'stock.move' @api.model def _prepare_picking_assign(self, move): values = super(StockMove, self)._prepare_picking_assign(move) if move.procurement_id.sale_line_id: sale = move.procurement_id.sale_line_id.order_id values['workflow_process_id'] = sale.workflow_process_id.id return values ## Instruction: Fix API type & method name for picking values ## Code After: from odoo import api, models class StockMove(models.Model): _inherit = 'stock.move' @api.multi def _get_new_picking_values(self): values = super(StockMove, self)._get_new_picking_values() if self.procurement_id.sale_line_id: sale = self.procurement_id.sale_line_id.order_id values['workflow_process_id'] = sale.workflow_process_id.id return values
// ... existing code ... class StockMove(models.Model): _inherit = 'stock.move' @api.multi def _get_new_picking_values(self): values = super(StockMove, self)._get_new_picking_values() if self.procurement_id.sale_line_id: sale = self.procurement_id.sale_line_id.order_id values['workflow_process_id'] = sale.workflow_process_id.id return values // ... rest of the code ...
295e356af1e4422fd8e2af9a44b46f5976a5ec39
tools/test_sneeze.py
tools/test_sneeze.py
import os from tempfile import mkdtemp from shutil import rmtree from nipy.testing import * from sneeze import find_pkg, run_nose import_strings = ["from nipype.interfaces.afni import To3d", "from nipype.interfaces import afni", "import nipype.interfaces.afni"] def test_from_namespace(): dname = mkdtemp() fname = os.path.join(dname, 'test_afni.py') fp = open(fname, 'w') fp.write('from nipype.interfaces.afni import To3d') fp.close() cover_pkg, module = find_pkg(fname) cmd = run_nose(cover_pkg, fname, dry_run=True) cmdlst = cmd.split() cmd = ' '.join(cmdlst[:4]) # strip off temporary directory path #print cmd assert_equal(cmd, 'nosetests -sv --with-coverage --cover-package=nipype.interfaces.afni') if os.path.exists(dname): rmtree(dname)
import os from tempfile import mkdtemp from shutil import rmtree from nipy.testing import * from sneeze import find_pkg, run_nose import_strings = ["from nipype.interfaces.afni import To3d, ThreeDRefit", "from nipype.interfaces import afni", "import nipype.interfaces.afni", "from nipype.interfaces import afni as af"] def test_imports(): dname = mkdtemp() fname = os.path.join(dname, 'test_afni.py') for impt in import_strings: fp = open(fname, 'w') fp.write(impt) fp.close() cover_pkg, module = find_pkg(fname) cmd = run_nose(cover_pkg, fname, dry_run=True) cmdlst = cmd.split() cmd = ' '.join(cmdlst[:4]) # strip off temporary directory path yield assert_equal, cmd, \ 'nosetests -sv --with-coverage --cover-package=nipype.interfaces.afni' if os.path.exists(dname): rmtree(dname)
Add more tests for sneeze.
Add more tests for sneeze.
Python
bsd-3-clause
nipy/nipy-labs,alexis-roche/niseg,nipy/nireg,alexis-roche/nipy,alexis-roche/nipy,alexis-roche/nireg,arokem/nipy,bthirion/nipy,alexis-roche/register,nipy/nireg,bthirion/nipy,alexis-roche/nipy,bthirion/nipy,alexis-roche/nipy,arokem/nipy,alexis-roche/niseg,arokem/nipy,bthirion/nipy,arokem/nipy,alexis-roche/register,alexis-roche/register,nipy/nipy-labs,alexis-roche/nireg
python
## Code Before: import os from tempfile import mkdtemp from shutil import rmtree from nipy.testing import * from sneeze import find_pkg, run_nose import_strings = ["from nipype.interfaces.afni import To3d", "from nipype.interfaces import afni", "import nipype.interfaces.afni"] def test_from_namespace(): dname = mkdtemp() fname = os.path.join(dname, 'test_afni.py') fp = open(fname, 'w') fp.write('from nipype.interfaces.afni import To3d') fp.close() cover_pkg, module = find_pkg(fname) cmd = run_nose(cover_pkg, fname, dry_run=True) cmdlst = cmd.split() cmd = ' '.join(cmdlst[:4]) # strip off temporary directory path #print cmd assert_equal(cmd, 'nosetests -sv --with-coverage --cover-package=nipype.interfaces.afni') if os.path.exists(dname): rmtree(dname) ## Instruction: Add more tests for sneeze. ## Code After: import os from tempfile import mkdtemp from shutil import rmtree from nipy.testing import * from sneeze import find_pkg, run_nose import_strings = ["from nipype.interfaces.afni import To3d, ThreeDRefit", "from nipype.interfaces import afni", "import nipype.interfaces.afni", "from nipype.interfaces import afni as af"] def test_imports(): dname = mkdtemp() fname = os.path.join(dname, 'test_afni.py') for impt in import_strings: fp = open(fname, 'w') fp.write(impt) fp.close() cover_pkg, module = find_pkg(fname) cmd = run_nose(cover_pkg, fname, dry_run=True) cmdlst = cmd.split() cmd = ' '.join(cmdlst[:4]) # strip off temporary directory path yield assert_equal, cmd, \ 'nosetests -sv --with-coverage --cover-package=nipype.interfaces.afni' if os.path.exists(dname): rmtree(dname)
... from nipy.testing import * from sneeze import find_pkg, run_nose import_strings = ["from nipype.interfaces.afni import To3d, ThreeDRefit", "from nipype.interfaces import afni", "import nipype.interfaces.afni", "from nipype.interfaces import afni as af"] def test_imports(): dname = mkdtemp() fname = os.path.join(dname, 'test_afni.py') for impt in import_strings: fp = open(fname, 'w') fp.write(impt) fp.close() cover_pkg, module = find_pkg(fname) cmd = run_nose(cover_pkg, fname, dry_run=True) cmdlst = cmd.split() cmd = ' '.join(cmdlst[:4]) # strip off temporary directory path yield assert_equal, cmd, \ 'nosetests -sv --with-coverage --cover-package=nipype.interfaces.afni' if os.path.exists(dname): rmtree(dname) ...
c677df5f5f39afbf3aef3ceb1e83f3a97fb53f6b
bonspy/utils.py
bonspy/utils.py
def compare_vectors(x, y): for x_i, y_i in zip(x, y): comparison = _compare(x_i, y_i) if comparison == 0: continue else: return comparison return 0 def _compare(x, y): if x is not None and y is not None: return int(x > y) - int(x < y) elif x is not None and y is None: return -1 elif x is None and y is not None: return 1 else: return 0 class ConstantDict(dict): def __init__(self, constant): super(ConstantDict, self).__init__() self.constant = constant def values(self): return [self.constant] def __delitem__(self, key): try: super(ConstantDict, self).__delitem__(key) except KeyError: pass def __eq__(self, other): if type(other) is not type(self): return False elif other.constant == self.constant: return True else: return False def __getitem__(self, item): try: return super(ConstantDict, self).__getitem__(item) except KeyError: return self.constant def __repr__(self): return 'ConstantDict({})'.format(self.constant)
def compare_vectors(x, y): for x_i, y_i in zip(x, y): comparison = _compare(x_i, y_i) if comparison == 0: continue else: return comparison return 0 def _compare(x, y): if x is not None and y is not None: return int(x > y) - int(x < y) elif x is not None and y is None: return -1 elif x is None and y is not None: return 1 else: return 0 class ConstantDict(dict): def __init__(self, constant): super(ConstantDict, self).__init__() self.constant = constant self.deleted_keys = set() def update(self, E=None, **F): super(ConstantDict, self).update(E, **F) if type(E) is type(self): self.constant = E.constant def values(self): return [self.constant] + list(super(ConstantDict, self).values()) def __delitem__(self, key): try: super(ConstantDict, self).__delitem__(key) except KeyError: self.deleted_keys.add(key) def __eq__(self, other): if type(other) is not type(self): return False elif other.constant == self.constant and super(ConstantDict, self).__eq__(other): return True else: return False def __getitem__(self, item): try: return super(ConstantDict, self).__getitem__(item) except KeyError: if item in self.deleted_keys: raise else: return self.constant def __repr__(self): return 'ConstantDict({}, {})'.format(self.constant, super(ConstantDict, self).__repr__())
Fix bugs in new class
Fix bugs in new class
Python
bsd-3-clause
markovianhq/bonspy
python
## Code Before: def compare_vectors(x, y): for x_i, y_i in zip(x, y): comparison = _compare(x_i, y_i) if comparison == 0: continue else: return comparison return 0 def _compare(x, y): if x is not None and y is not None: return int(x > y) - int(x < y) elif x is not None and y is None: return -1 elif x is None and y is not None: return 1 else: return 0 class ConstantDict(dict): def __init__(self, constant): super(ConstantDict, self).__init__() self.constant = constant def values(self): return [self.constant] def __delitem__(self, key): try: super(ConstantDict, self).__delitem__(key) except KeyError: pass def __eq__(self, other): if type(other) is not type(self): return False elif other.constant == self.constant: return True else: return False def __getitem__(self, item): try: return super(ConstantDict, self).__getitem__(item) except KeyError: return self.constant def __repr__(self): return 'ConstantDict({})'.format(self.constant) ## Instruction: Fix bugs in new class ## Code After: def compare_vectors(x, y): for x_i, y_i in zip(x, y): comparison = _compare(x_i, y_i) if comparison == 0: continue else: return comparison return 0 def _compare(x, y): if x is not None and y is not None: return int(x > y) - int(x < y) elif x is not None and y is None: return -1 elif x is None and y is not None: return 1 else: return 0 class ConstantDict(dict): def __init__(self, constant): super(ConstantDict, self).__init__() self.constant = constant self.deleted_keys = set() def update(self, E=None, **F): super(ConstantDict, self).update(E, **F) if type(E) is type(self): self.constant = E.constant def values(self): return [self.constant] + list(super(ConstantDict, self).values()) def __delitem__(self, key): try: super(ConstantDict, self).__delitem__(key) except KeyError: self.deleted_keys.add(key) def __eq__(self, other): if type(other) is not type(self): return False elif other.constant == self.constant and super(ConstantDict, self).__eq__(other): return True else: return False def __getitem__(self, item): try: return super(ConstantDict, self).__getitem__(item) except KeyError: if item in self.deleted_keys: raise else: return self.constant def __repr__(self): return 'ConstantDict({}, {})'.format(self.constant, super(ConstantDict, self).__repr__())
# ... existing code ... def __init__(self, constant): super(ConstantDict, self).__init__() self.constant = constant self.deleted_keys = set() def update(self, E=None, **F): super(ConstantDict, self).update(E, **F) if type(E) is type(self): self.constant = E.constant def values(self): return [self.constant] + list(super(ConstantDict, self).values()) def __delitem__(self, key): try: super(ConstantDict, self).__delitem__(key) except KeyError: self.deleted_keys.add(key) def __eq__(self, other): if type(other) is not type(self): return False elif other.constant == self.constant and super(ConstantDict, self).__eq__(other): return True else: return False # ... modified code ... try: return super(ConstantDict, self).__getitem__(item) except KeyError: if item in self.deleted_keys: raise else: return self.constant def __repr__(self): return 'ConstantDict({}, {})'.format(self.constant, super(ConstantDict, self).__repr__()) # ... rest of the code ...
b94f14c84c567c1c0433bba0e4f12d0d4771b718
extensions/protocol_extension.h
extensions/protocol_extension.h
/* -*- Mode: C; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ #ifndef EXAMPLE_PROTOCOL_H #define EXAMPLE_PROTOCOL_H #include <daemon/settings.h> #include <memcached/engine.h> #ifdef __cplusplus extern "C" { #endif MEMCACHED_PUBLIC_API EXTENSION_ERROR_CODE memcached_extensions_initialize(const char *config, GET_SERVER_API get_server_api); #ifdef __cplusplus } MEMCACHED_PUBLIC_API EXTENSION_ERROR_CODE file_logger_initialize(const LoggerConfig& config, GET_SERVER_API get_server_api); #endif #endif
/* -*- Mode: C; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ #ifndef EXAMPLE_PROTOCOL_H #define EXAMPLE_PROTOCOL_H #include <daemon/settings.h> #include <memcached/engine.h> #ifdef __cplusplus extern "C" { #endif MEMCACHED_PUBLIC_API EXTENSION_ERROR_CODE memcached_extensions_initialize(const char *config, GET_SERVER_API get_server_api); MEMCACHED_PUBLIC_API EXTENSION_ERROR_CODE file_logger_initialize(const LoggerConfig& config, GET_SERVER_API get_server_api); #ifdef __cplusplus } #endif #endif
Fix dlsym error 'Could not find symbol "file_logger_initialize"'
Fix dlsym error 'Could not find symbol "file_logger_initialize"' Wrap file_logger_initialize into extern "C" to prevent name mangling, which caused the error above. Change-Id: I8c8e1e61599f2afb6dedf4e0b71c0a5a013ccbb7 Reviewed-on: http://review.couchbase.org/86829 Tested-by: Build Bot <[email protected]> Reviewed-by: Dave Rigby <[email protected]>
C
bsd-3-clause
daverigby/kv_engine,daverigby/kv_engine,daverigby/kv_engine,daverigby/kv_engine
c
## Code Before: /* -*- Mode: C; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ #ifndef EXAMPLE_PROTOCOL_H #define EXAMPLE_PROTOCOL_H #include <daemon/settings.h> #include <memcached/engine.h> #ifdef __cplusplus extern "C" { #endif MEMCACHED_PUBLIC_API EXTENSION_ERROR_CODE memcached_extensions_initialize(const char *config, GET_SERVER_API get_server_api); #ifdef __cplusplus } MEMCACHED_PUBLIC_API EXTENSION_ERROR_CODE file_logger_initialize(const LoggerConfig& config, GET_SERVER_API get_server_api); #endif #endif ## Instruction: Fix dlsym error 'Could not find symbol "file_logger_initialize"' Wrap file_logger_initialize into extern "C" to prevent name mangling, which caused the error above. Change-Id: I8c8e1e61599f2afb6dedf4e0b71c0a5a013ccbb7 Reviewed-on: http://review.couchbase.org/86829 Tested-by: Build Bot <[email protected]> Reviewed-by: Dave Rigby <[email protected]> ## Code After: /* -*- Mode: C; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ #ifndef EXAMPLE_PROTOCOL_H #define EXAMPLE_PROTOCOL_H #include <daemon/settings.h> #include <memcached/engine.h> #ifdef __cplusplus extern "C" { #endif MEMCACHED_PUBLIC_API EXTENSION_ERROR_CODE memcached_extensions_initialize(const char *config, GET_SERVER_API get_server_api); MEMCACHED_PUBLIC_API EXTENSION_ERROR_CODE file_logger_initialize(const LoggerConfig& config, GET_SERVER_API get_server_api); #ifdef __cplusplus } #endif #endif
// ... existing code ... MEMCACHED_PUBLIC_API EXTENSION_ERROR_CODE memcached_extensions_initialize(const char *config, GET_SERVER_API get_server_api); MEMCACHED_PUBLIC_API EXTENSION_ERROR_CODE file_logger_initialize(const LoggerConfig& config, GET_SERVER_API get_server_api); #ifdef __cplusplus } #endif // ... rest of the code ...
ba37080645153d66a8ae1c8df10312806999f8ec
tests/test_observation.py
tests/test_observation.py
import unittest from datetime import datetime from dateutil.tz import tzutc from fmi import FMI class TestObservations(unittest.TestCase): def test_lappeenranta(self): now = datetime.now(tz=tzutc()) f = FMI(place='Lappeenranta') for point in f.observations(): assert point.time < now assert isinstance(point.temperature, float)
import unittest from datetime import datetime from dateutil.tz import tzutc from fmi import FMI class TestObservations(unittest.TestCase): def test_lappeenranta(self): now = datetime.now(tz=tzutc()) f = FMI(place='Lappeenranta') for point in f.observations(): assert point.time < now assert isinstance(point.temperature, float) for point in f.observations(fmisid=101237): assert point.time < now assert isinstance(point.temperature, float)
Add use of fmisid to tests.
Add use of fmisid to tests.
Python
mit
kipe/fmi
python
## Code Before: import unittest from datetime import datetime from dateutil.tz import tzutc from fmi import FMI class TestObservations(unittest.TestCase): def test_lappeenranta(self): now = datetime.now(tz=tzutc()) f = FMI(place='Lappeenranta') for point in f.observations(): assert point.time < now assert isinstance(point.temperature, float) ## Instruction: Add use of fmisid to tests. ## Code After: import unittest from datetime import datetime from dateutil.tz import tzutc from fmi import FMI class TestObservations(unittest.TestCase): def test_lappeenranta(self): now = datetime.now(tz=tzutc()) f = FMI(place='Lappeenranta') for point in f.observations(): assert point.time < now assert isinstance(point.temperature, float) for point in f.observations(fmisid=101237): assert point.time < now assert isinstance(point.temperature, float)
# ... existing code ... for point in f.observations(): assert point.time < now assert isinstance(point.temperature, float) for point in f.observations(fmisid=101237): assert point.time < now assert isinstance(point.temperature, float) # ... rest of the code ...
82652f6aa3f55f67d3948e4d5cc48d1e657f32a9
dlux-web/src/main/java/org/opendaylight/dlux/web/Activator.java
dlux-web/src/main/java/org/opendaylight/dlux/web/Activator.java
package org.opendaylight.dlux.web; import org.osgi.util.tracker.ServiceTracker; import org.osgi.framework.BundleContext; import org.osgi.framework.ServiceReference; import org.osgi.framework.BundleActivator; import org.osgi.service.http.HttpService; public class Activator implements BundleActivator { private ServiceTracker httpTracker; public void start(BundleContext context) throws Exception { httpTracker = new ServiceTracker(context, HttpService.class.getName(), null) { public void removedService(ServiceReference reference, Object service) { try { ((HttpService) service).unregister("/dlux"); } catch (IllegalArgumentException exception) { // Ignore; servlet registration probably failed earlier on... } } public Object addingService(ServiceReference reference) { // HTTP service is available, register our servlet... HttpService httpService = (HttpService) this.context.getService(reference); try { httpService.registerResources("/dlux", "/pages", null); } catch (Exception exception) { exception.printStackTrace(); } return httpService; } }; httpTracker.open(); } public void stop(BundleContext context) throws Exception { httpTracker.close(); } }
/** * Copyright (c) 2014, 2015 Inocybe Technologies, and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ package org.opendaylight.dlux.web; import org.osgi.util.tracker.ServiceTracker; import org.osgi.framework.BundleContext; import org.osgi.framework.ServiceReference; import org.osgi.framework.BundleActivator; import org.osgi.service.http.HttpService; public class Activator implements BundleActivator { private ServiceTracker httpTracker; public void start(BundleContext context) throws Exception { httpTracker = new ServiceTracker(context, HttpService.class.getName(), null) { public void removedService(ServiceReference reference, Object service) { try { ((HttpService) service).unregister("/dlux"); } catch (IllegalArgumentException exception) { // Ignore; servlet registration probably failed earlier on... } } public Object addingService(ServiceReference reference) { // HTTP service is available, register our servlet... HttpService httpService = (HttpService) this.context.getService(reference); try { httpService.registerResources("/dlux", "/pages", null); } catch (Exception exception) { exception.printStackTrace(); } return httpService; } }; httpTracker.open(); } public void stop(BundleContext context) throws Exception { httpTracker.close(); } }
Add missing license header in dlux-web
Add missing license header in dlux-web Change-Id: I50ee01654cb01028b6541d9f80203ca1f803820a Signed-off-by: Thanh Ha <[email protected]>
Java
epl-1.0
stshtina/ODL,opendaylight/dlux,opendaylight/dlux,pinaxia/dlux,pinaxia/dlux,inocybe/odl-dlux,inocybe/odl-dlux,opendaylight/dlux,stshtina/ODL,stshtina/ODL,pinaxia/dlux,inocybe/odl-dlux
java
## Code Before: package org.opendaylight.dlux.web; import org.osgi.util.tracker.ServiceTracker; import org.osgi.framework.BundleContext; import org.osgi.framework.ServiceReference; import org.osgi.framework.BundleActivator; import org.osgi.service.http.HttpService; public class Activator implements BundleActivator { private ServiceTracker httpTracker; public void start(BundleContext context) throws Exception { httpTracker = new ServiceTracker(context, HttpService.class.getName(), null) { public void removedService(ServiceReference reference, Object service) { try { ((HttpService) service).unregister("/dlux"); } catch (IllegalArgumentException exception) { // Ignore; servlet registration probably failed earlier on... } } public Object addingService(ServiceReference reference) { // HTTP service is available, register our servlet... HttpService httpService = (HttpService) this.context.getService(reference); try { httpService.registerResources("/dlux", "/pages", null); } catch (Exception exception) { exception.printStackTrace(); } return httpService; } }; httpTracker.open(); } public void stop(BundleContext context) throws Exception { httpTracker.close(); } } ## Instruction: Add missing license header in dlux-web Change-Id: I50ee01654cb01028b6541d9f80203ca1f803820a Signed-off-by: Thanh Ha <[email protected]> ## Code After: /** * Copyright (c) 2014, 2015 Inocybe Technologies, and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ package org.opendaylight.dlux.web; import org.osgi.util.tracker.ServiceTracker; import org.osgi.framework.BundleContext; import org.osgi.framework.ServiceReference; import org.osgi.framework.BundleActivator; import org.osgi.service.http.HttpService; public class Activator implements BundleActivator { private ServiceTracker httpTracker; public void start(BundleContext context) throws Exception { httpTracker = new ServiceTracker(context, HttpService.class.getName(), null) { public void removedService(ServiceReference reference, Object service) { try { ((HttpService) service).unregister("/dlux"); } catch (IllegalArgumentException exception) { // Ignore; servlet registration probably failed earlier on... } } public Object addingService(ServiceReference reference) { // HTTP service is available, register our servlet... HttpService httpService = (HttpService) this.context.getService(reference); try { httpService.registerResources("/dlux", "/pages", null); } catch (Exception exception) { exception.printStackTrace(); } return httpService; } }; httpTracker.open(); } public void stop(BundleContext context) throws Exception { httpTracker.close(); } }
# ... existing code ... /** * Copyright (c) 2014, 2015 Inocybe Technologies, and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ package org.opendaylight.dlux.web; import org.osgi.util.tracker.ServiceTracker; # ... rest of the code ...
1e2822bb71c123993419479c2d4f5fc3e80e35bb
reddit_adzerk/adzerkads.py
reddit_adzerk/adzerkads.py
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_all_the_things = g.live_config.get("adzerk_all_the_things") adzerk_srs = g.live_config.get("adzerk_srs") in_adzerk_sr = adzerk_srs and c.site.name.lower() in adzerk_srs if adzerk_all_the_things or in_adzerk_sr: url_key = "adzerk_https_url" if c.secure else "adzerk_url" self.ad_url = g.config[url_key].format( subreddit=quote(c.site.name.lower()), 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_all_the_things = g.live_config.get("adzerk_all_the_things") adzerk_srs = g.live_config.get("adzerk_srs") in_adzerk_sr = adzerk_srs and c.site.name.lower() in adzerk_srs if adzerk_all_the_things or in_adzerk_sr: url_key = "adzerk_https_url" if c.secure else "adzerk_url" site_name = getattr(c.site, "analytics_name", c.site.name) self.ad_url = g.config[url_key].format( subreddit=quote(site_name.lower()), origin=c.request_origin, ) self.frame_id = "ad_main"
Use analytics name for subreddits if available.
Use analytics name for subreddits if available. This allows a catch-all for multis to be used.
Python
bsd-3-clause
madbook/reddit-plugin-adzerk,madbook/reddit-plugin-adzerk,madbook/reddit-plugin-adzerk
python
## Code Before: 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_all_the_things = g.live_config.get("adzerk_all_the_things") adzerk_srs = g.live_config.get("adzerk_srs") in_adzerk_sr = adzerk_srs and c.site.name.lower() in adzerk_srs if adzerk_all_the_things or in_adzerk_sr: url_key = "adzerk_https_url" if c.secure else "adzerk_url" self.ad_url = g.config[url_key].format( subreddit=quote(c.site.name.lower()), origin=c.request_origin, ) self.frame_id = "ad_main" ## Instruction: Use analytics name for subreddits if available. This allows a catch-all for multis to be used. ## 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_all_the_things = g.live_config.get("adzerk_all_the_things") adzerk_srs = g.live_config.get("adzerk_srs") in_adzerk_sr = adzerk_srs and c.site.name.lower() in adzerk_srs if adzerk_all_the_things or in_adzerk_sr: url_key = "adzerk_https_url" if c.secure else "adzerk_url" site_name = getattr(c.site, "analytics_name", c.site.name) self.ad_url = g.config[url_key].format( subreddit=quote(site_name.lower()), origin=c.request_origin, ) self.frame_id = "ad_main"
// ... existing code ... in_adzerk_sr = adzerk_srs and c.site.name.lower() in adzerk_srs if adzerk_all_the_things or in_adzerk_sr: url_key = "adzerk_https_url" if c.secure else "adzerk_url" site_name = getattr(c.site, "analytics_name", c.site.name) self.ad_url = g.config[url_key].format( subreddit=quote(site_name.lower()), origin=c.request_origin, ) self.frame_id = "ad_main" // ... rest of the code ...
20bd5c16d5850f988e92c39db3ff041c37c83b73
contract_sale_generation/models/abstract_contract.py
contract_sale_generation/models/abstract_contract.py
from odoo import api, fields, models class ContractAbstractContract(models.AbstractModel): _inherit = "contract.abstract.contract" sale_autoconfirm = fields.Boolean(string="Sale Autoconfirm") @api.model def _get_generation_type_selection(self): res = super()._get_generation_type_selection() res.append(("sale", "Sale")) return res
from odoo import api, fields, models class ContractAbstractContract(models.AbstractModel): _inherit = "contract.abstract.contract" sale_autoconfirm = fields.Boolean(string="Sale Autoconfirm") @api.model def _selection_generation_type(self): res = super()._selection_generation_type() res.append(("sale", "Sale")) return res
Align method on Odoo conventions
[14.0][IMP] contract_sale_generation: Align method on Odoo conventions
Python
agpl-3.0
OCA/contract,OCA/contract,OCA/contract
python
## Code Before: from odoo import api, fields, models class ContractAbstractContract(models.AbstractModel): _inherit = "contract.abstract.contract" sale_autoconfirm = fields.Boolean(string="Sale Autoconfirm") @api.model def _get_generation_type_selection(self): res = super()._get_generation_type_selection() res.append(("sale", "Sale")) return res ## Instruction: [14.0][IMP] contract_sale_generation: Align method on Odoo conventions ## Code After: from odoo import api, fields, models class ContractAbstractContract(models.AbstractModel): _inherit = "contract.abstract.contract" sale_autoconfirm = fields.Boolean(string="Sale Autoconfirm") @api.model def _selection_generation_type(self): res = super()._selection_generation_type() res.append(("sale", "Sale")) return res
... sale_autoconfirm = fields.Boolean(string="Sale Autoconfirm") @api.model def _selection_generation_type(self): res = super()._selection_generation_type() res.append(("sale", "Sale")) return res ...
24f0c0d311886571cc0c5f8badca026a6c534a52
dask/array/__init__.py
dask/array/__init__.py
from __future__ import absolute_import, division, print_function from ..utils import ignoring from .core import (Array, stack, concatenate, tensordot, transpose, from_array, choose, where, coarsen, broadcast_to, constant, fromfunction, compute, unique, store) from .core import (arccos, arcsin, arctan, arctanh, arccosh, arcsinh, arctan2, ceil, copysign, cos, cosh, degrees, exp, expm1, fabs, floor, fmod, frexp, hypot, isinf, isnan, ldexp, log, log10, log1p, modf, radians, sin, sinh, sqrt, tan, tanh, trunc, around, isnull, notnull, isclose) from .reductions import (sum, prod, mean, std, var, any, all, min, max, vnorm, argmin, argmax, nansum, nanmean, nanstd, nanvar, nanmin, nanmax, nanargmin, nanargmax) from .percentile import percentile with ignoring(ImportError): from .reductions import nanprod from . import random, linalg, ghost, creation from .wrap import ones, zeros, empty from .reblock import reblock from ..context import set_options from .optimization import optimize
from __future__ import absolute_import, division, print_function from ..utils import ignoring from .core import (Array, stack, concatenate, tensordot, transpose, from_array, choose, where, coarsen, broadcast_to, constant, fromfunction, compute, unique, store) from .core import (arccos, arcsin, arctan, arctanh, arccosh, arcsinh, arctan2, ceil, copysign, cos, cosh, degrees, exp, expm1, fabs, floor, fmod, frexp, hypot, isinf, isnan, ldexp, log, log10, log1p, modf, radians, sin, sinh, sqrt, tan, tanh, trunc, around, isnull, notnull, isclose) from .reductions import (sum, prod, mean, std, var, any, all, min, max, vnorm, argmin, argmax, nansum, nanmean, nanstd, nanvar, nanmin, nanmax, nanargmin, nanargmax) from .percentile import percentile with ignoring(ImportError): from .reductions import nanprod from . import random, linalg, ghost from .wrap import ones, zeros, empty from .reblock import reblock from ..context import set_options from .optimization import optimize from .creation import arange, linspace
Move dask.array.creation.* into dask.array.* namespace
Move dask.array.creation.* into dask.array.* namespace
Python
bsd-3-clause
mraspaud/dask,marianotepper/dask,minrk/dask,freeman-lab/dask,pombredanne/dask,ContinuumIO/dask,hainm/dask,ssanderson/dask,clarkfitzg/dask,jakirkham/dask,jakirkham/dask,PhE/dask,cowlicks/dask,ContinuumIO/dask,mikegraham/dask,cpcloud/dask,pombredanne/dask,hainm/dask,marianotepper/dask,simudream/dask,jcrist/dask,wiso/dask,blaze/dask,vikhyat/dask,blaze/dask,esc/dask,PhE/dask,minrk/dask,vikhyat/dask,wiso/dask,dask/dask,dask/dask,jayhetee/dask,freeman-lab/dask,mrocklin/dask,jcrist/dask,esc/dask,clarkfitzg/dask,ssanderson/dask,mrocklin/dask,simudream/dask,mraspaud/dask,chrisbarber/dask,jayhetee/dask,gameduell/dask
python
## Code Before: from __future__ import absolute_import, division, print_function from ..utils import ignoring from .core import (Array, stack, concatenate, tensordot, transpose, from_array, choose, where, coarsen, broadcast_to, constant, fromfunction, compute, unique, store) from .core import (arccos, arcsin, arctan, arctanh, arccosh, arcsinh, arctan2, ceil, copysign, cos, cosh, degrees, exp, expm1, fabs, floor, fmod, frexp, hypot, isinf, isnan, ldexp, log, log10, log1p, modf, radians, sin, sinh, sqrt, tan, tanh, trunc, around, isnull, notnull, isclose) from .reductions import (sum, prod, mean, std, var, any, all, min, max, vnorm, argmin, argmax, nansum, nanmean, nanstd, nanvar, nanmin, nanmax, nanargmin, nanargmax) from .percentile import percentile with ignoring(ImportError): from .reductions import nanprod from . import random, linalg, ghost, creation from .wrap import ones, zeros, empty from .reblock import reblock from ..context import set_options from .optimization import optimize ## Instruction: Move dask.array.creation.* into dask.array.* namespace ## Code After: from __future__ import absolute_import, division, print_function from ..utils import ignoring from .core import (Array, stack, concatenate, tensordot, transpose, from_array, choose, where, coarsen, broadcast_to, constant, fromfunction, compute, unique, store) from .core import (arccos, arcsin, arctan, arctanh, arccosh, arcsinh, arctan2, ceil, copysign, cos, cosh, degrees, exp, expm1, fabs, floor, fmod, frexp, hypot, isinf, isnan, ldexp, log, log10, log1p, modf, radians, sin, sinh, sqrt, tan, tanh, trunc, around, isnull, notnull, isclose) from .reductions import (sum, prod, mean, std, var, any, all, min, max, vnorm, argmin, argmax, nansum, nanmean, nanstd, nanvar, nanmin, nanmax, nanargmin, nanargmax) from .percentile import percentile with ignoring(ImportError): from .reductions import nanprod from . import random, linalg, ghost from .wrap import ones, zeros, empty from .reblock import reblock from ..context import set_options from .optimization import optimize from .creation import arange, linspace
... from .percentile import percentile with ignoring(ImportError): from .reductions import nanprod from . import random, linalg, ghost from .wrap import ones, zeros, empty from .reblock import reblock from ..context import set_options from .optimization import optimize from .creation import arange, linspace ...
b60fb0db2cc1ab3605f34e9b604e920279434c36
vterm_test.py
vterm_test.py
import urwid def main(): event_loop = urwid.SelectEventLoop() mainframe = urwid.Frame( urwid.Columns([ ('fixed', 3, urwid.SolidFill('|')), urwid.Pile([ ('weight', 70, urwid.TerminalWidget(None, event_loop)), ('fixed', 1, urwid.Filler(urwid.Edit('focus test edit: '))), ]), ('fixed', 3, urwid.SolidFill('|')), ], box_columns=[1]), header=urwid.Columns([ ('fixed', 3, urwid.Text('.,:')), urwid.Divider('-'), ('fixed', 3, urwid.Text(':,.')), ]), footer=urwid.Columns([ ('fixed', 3, urwid.Text('`"*')), urwid.Divider('-'), ('fixed', 3, urwid.Text('*"\'')), ]), ) def quit(key): if key in ('q', 'Q'): raise urwid.ExitMainLoop() loop = urwid.MainLoop( mainframe, unhandled_input=quit, event_loop=event_loop ).run() if __name__ == '__main__': main()
import urwid def main(): event_loop = urwid.SelectEventLoop() mainframe = urwid.Frame( urwid.Columns([ ('fixed', 3, urwid.SolidFill('|')), urwid.Pile([ ('weight', 70, urwid.TerminalWidget(None, event_loop)), ('fixed', 1, urwid.Filler(urwid.Edit('focus test edit: '))), ]), ('fixed', 3, urwid.SolidFill('|')), ], box_columns=[1]), header=urwid.Columns([ ('fixed', 3, urwid.Text('.,:')), urwid.Divider('-'), ('fixed', 3, urwid.Text(':,.')), ]), footer=urwid.Columns([ ('fixed', 3, urwid.Text('`"*')), urwid.Divider('-'), ('fixed', 3, urwid.Text('*"\'')), ]), ) def quit(key): if key in ('q', 'Q'): raise urwid.ExitMainLoop() loop = urwid.MainLoop( mainframe, handle_mouse=False, unhandled_input=quit, event_loop=event_loop ).run() if __name__ == '__main__': main()
Disable mouse handling in vterm example.
Disable mouse handling in vterm example.
Python
lgpl-2.1
westurner/urwid,wardi/urwid,zyga/urwid,douglas-larocca/urwid,harlowja/urwid,drestebon/urwid,hkoof/urwid,bk2204/urwid,urwid/urwid,drestebon/urwid,inducer/urwid,hkoof/urwid,hkoof/urwid,bk2204/urwid,rndusr/urwid,rndusr/urwid,zyga/urwid,westurner/urwid,inducer/urwid,rndusr/urwid,mountainstorm/urwid,foreni-packages/urwid,foreni-packages/urwid,ivanov/urwid,tonycpsu/urwid,harlowja/urwid,zyga/urwid,drestebon/urwid,tonycpsu/urwid,mountainstorm/urwid,urwid/urwid,foreni-packages/urwid,douglas-larocca/urwid,ivanov/urwid,douglas-larocca/urwid,Julian/urwid,westurner/urwid,harlowja/urwid,wardi/urwid,Julian/urwid,Julian/urwid,ivanov/urwid,mountainstorm/urwid,tonycpsu/urwid,urwid/urwid,inducer/urwid,wardi/urwid,bk2204/urwid
python
## Code Before: import urwid def main(): event_loop = urwid.SelectEventLoop() mainframe = urwid.Frame( urwid.Columns([ ('fixed', 3, urwid.SolidFill('|')), urwid.Pile([ ('weight', 70, urwid.TerminalWidget(None, event_loop)), ('fixed', 1, urwid.Filler(urwid.Edit('focus test edit: '))), ]), ('fixed', 3, urwid.SolidFill('|')), ], box_columns=[1]), header=urwid.Columns([ ('fixed', 3, urwid.Text('.,:')), urwid.Divider('-'), ('fixed', 3, urwid.Text(':,.')), ]), footer=urwid.Columns([ ('fixed', 3, urwid.Text('`"*')), urwid.Divider('-'), ('fixed', 3, urwid.Text('*"\'')), ]), ) def quit(key): if key in ('q', 'Q'): raise urwid.ExitMainLoop() loop = urwid.MainLoop( mainframe, unhandled_input=quit, event_loop=event_loop ).run() if __name__ == '__main__': main() ## Instruction: Disable mouse handling in vterm example. ## Code After: import urwid def main(): event_loop = urwid.SelectEventLoop() mainframe = urwid.Frame( urwid.Columns([ ('fixed', 3, urwid.SolidFill('|')), urwid.Pile([ ('weight', 70, urwid.TerminalWidget(None, event_loop)), ('fixed', 1, urwid.Filler(urwid.Edit('focus test edit: '))), ]), ('fixed', 3, urwid.SolidFill('|')), ], box_columns=[1]), header=urwid.Columns([ ('fixed', 3, urwid.Text('.,:')), urwid.Divider('-'), ('fixed', 3, urwid.Text(':,.')), ]), footer=urwid.Columns([ ('fixed', 3, urwid.Text('`"*')), urwid.Divider('-'), ('fixed', 3, urwid.Text('*"\'')), ]), ) def quit(key): if key in ('q', 'Q'): raise urwid.ExitMainLoop() loop = urwid.MainLoop( mainframe, handle_mouse=False, unhandled_input=quit, event_loop=event_loop ).run() if __name__ == '__main__': main()
... loop = urwid.MainLoop( mainframe, handle_mouse=False, unhandled_input=quit, event_loop=event_loop ).run() ...
a7692bc810d1a30c9d0fa91bf1689651bd34d8c6
moniek/accounting/views.py
moniek/accounting/views.py
from django.http import HttpResponse def home(request): return HttpResponse("Hi")
from django.http import HttpResponse from django.template import RequestContext from django.shortcuts import render_to_response def home(request): return render_to_response('accounting/home.html', {}, RequestContext(request)) def accounts(request): return HttpResponse("Hi")
Create home and accounts stub view
Create home and accounts stub view Signed-off-by: Bas Westerbaan <[email protected]>
Python
agpl-3.0
bwesterb/moniek,bwesterb/moniek
python
## Code Before: from django.http import HttpResponse def home(request): return HttpResponse("Hi") ## Instruction: Create home and accounts stub view Signed-off-by: Bas Westerbaan <[email protected]> ## Code After: from django.http import HttpResponse from django.template import RequestContext from django.shortcuts import render_to_response def home(request): return render_to_response('accounting/home.html', {}, RequestContext(request)) def accounts(request): return HttpResponse("Hi")
// ... existing code ... from django.http import HttpResponse from django.template import RequestContext from django.shortcuts import render_to_response def home(request): return render_to_response('accounting/home.html', {}, RequestContext(request)) def accounts(request): return HttpResponse("Hi") // ... rest of the code ...
8589af4b858acace99cc856ce118f73568fb96b1
main.py
main.py
import argparse import asyncio import logging import sys from pathlib import Path from MoMMI.logsetup import setup_logs # Do this BEFORE we import master, because it does a lot of event loop stuff. if sys.platform == "win32": loop = asyncio.ProactorEventLoop() asyncio.set_event_loop(loop) else: try: import uvloop asyncio.set_event_loop_policy(uvloop.EventLoopPolicy()) except: pass from MoMMI.master import master def main() -> None: version = sys.version_info if version.major < 3 or (version.major == 3 and version.minor < 6): logging.critical("You need at least Python 3.6 to run MoMMI.") sys.exit(1) setup_logs() parser = argparse.ArgumentParser() parser.add_argument("--config-dir", "-c", default="./config", help="The directory to read config files from.", dest="config", type=Path) parser.add_argument("--storage-dir", "-s", default="./data", help="The directory to use for server data storage.", dest="data", type=Path) args = parser.parse_args() master.start(args.config, args.data) if __name__ == "__main__": main()
import argparse import asyncio import logging import sys from pathlib import Path from MoMMI.logsetup import setup_logs # Do this BEFORE we import master, because it does a lot of event loop stuff. if sys.platform == "win32": loop = asyncio.ProactorEventLoop() asyncio.set_event_loop(loop) else: try: import uvloop asyncio.set_event_loop_policy(uvloop.EventLoopPolicy()) except ImportError: pass from MoMMI.master import master def main() -> None: version = sys.version_info if version.major < 3 or (version.major == 3 and version.minor < 6): logging.critical("You need at least Python 3.6 to run MoMMI.") sys.exit(1) setup_logs() parser = argparse.ArgumentParser() parser.add_argument("--config-dir", "-c", default="./config", help="The directory to read config files from.", dest="config", type=Path) parser.add_argument("--storage-dir", "-s", default="./data", help="The directory to use for server data storage.", dest="data", type=Path) args = parser.parse_args() master.start(args.config, args.data) if __name__ == "__main__": main()
Make uvloop except be explicit ImportError
Make uvloop except be explicit ImportError
Python
mit
PJB3005/MoMMI,PJB3005/MoMMI,PJB3005/MoMMI
python
## Code Before: import argparse import asyncio import logging import sys from pathlib import Path from MoMMI.logsetup import setup_logs # Do this BEFORE we import master, because it does a lot of event loop stuff. if sys.platform == "win32": loop = asyncio.ProactorEventLoop() asyncio.set_event_loop(loop) else: try: import uvloop asyncio.set_event_loop_policy(uvloop.EventLoopPolicy()) except: pass from MoMMI.master import master def main() -> None: version = sys.version_info if version.major < 3 or (version.major == 3 and version.minor < 6): logging.critical("You need at least Python 3.6 to run MoMMI.") sys.exit(1) setup_logs() parser = argparse.ArgumentParser() parser.add_argument("--config-dir", "-c", default="./config", help="The directory to read config files from.", dest="config", type=Path) parser.add_argument("--storage-dir", "-s", default="./data", help="The directory to use for server data storage.", dest="data", type=Path) args = parser.parse_args() master.start(args.config, args.data) if __name__ == "__main__": main() ## Instruction: Make uvloop except be explicit ImportError ## Code After: import argparse import asyncio import logging import sys from pathlib import Path from MoMMI.logsetup import setup_logs # Do this BEFORE we import master, because it does a lot of event loop stuff. if sys.platform == "win32": loop = asyncio.ProactorEventLoop() asyncio.set_event_loop(loop) else: try: import uvloop asyncio.set_event_loop_policy(uvloop.EventLoopPolicy()) except ImportError: pass from MoMMI.master import master def main() -> None: version = sys.version_info if version.major < 3 or (version.major == 3 and version.minor < 6): logging.critical("You need at least Python 3.6 to run MoMMI.") sys.exit(1) setup_logs() parser = argparse.ArgumentParser() parser.add_argument("--config-dir", "-c", default="./config", help="The directory to read config files from.", dest="config", type=Path) parser.add_argument("--storage-dir", "-s", default="./data", help="The directory to use for server data storage.", dest="data", type=Path) args = parser.parse_args() master.start(args.config, args.data) if __name__ == "__main__": main()
# ... existing code ... import uvloop asyncio.set_event_loop_policy(uvloop.EventLoopPolicy()) except ImportError: pass from MoMMI.master import master # ... rest of the code ...
9e322751c197c0930ec3fbb17c13cea23fcc3888
provider/src/test/kotlin/org/gradle/kotlin/dsl/support/ImplicitImportsTest.kt
provider/src/test/kotlin/org/gradle/kotlin/dsl/support/ImplicitImportsTest.kt
package org.gradle.kotlin.dsl.support import org.gradle.kotlin.dsl.fixtures.AbstractIntegrationTest import org.hamcrest.CoreMatchers.containsString import org.junit.Assert.assertThat import org.junit.Test class ImplicitImportsTest : AbstractIntegrationTest() { @Test fun `implicit imports are fully qualified to allow use of the preferred type amongst those with same simple name in different Gradle API packages`() { // given: withBuildScript(""" println("*" + Jar::class.qualifiedName + "*") """) // when: val result = build("help") // then: assertThat(result.output, containsString("*org.gradle.jvm.tasks.Jar*")) } }
package org.gradle.kotlin.dsl.support import org.gradle.kotlin.dsl.fixtures.AbstractIntegrationTest import org.hamcrest.CoreMatchers.containsString import org.junit.Assert.assertThat import org.junit.Test class ImplicitImportsTest : AbstractIntegrationTest() { @Test fun `implicit imports are fully qualified to allow use of the preferred type amongst those with same simple name in different Gradle API packages`() { // given: withBuildScript(""" println("*" + Jar::class.qualifiedName + "*") """) // when: val result = build("help") // then: assertThat(result.output, containsString("*org.gradle.api.tasks.bundling.Jar*")) } }
Fix implicit imports tests after upstream default imports unification
Fix implicit imports tests after upstream default imports unification See https://github.com/gradle/gradle/pull/3140
Kotlin
apache-2.0
blindpirate/gradle,blindpirate/gradle,robinverduijn/gradle,blindpirate/gradle,gradle/gradle,gradle/gradle,robinverduijn/gradle,gradle/gradle-script-kotlin,robinverduijn/gradle,gradle/gradle,robinverduijn/gradle,robinverduijn/gradle,gradle/gradle,robinverduijn/gradle,blindpirate/gradle,gradle/gradle,blindpirate/gradle,gradle/gradle-script-kotlin,robinverduijn/gradle,blindpirate/gradle,robinverduijn/gradle,blindpirate/gradle,gradle/gradle,blindpirate/gradle,gradle/gradle,gradle/gradle,robinverduijn/gradle,blindpirate/gradle,gradle/gradle,robinverduijn/gradle,robinverduijn/gradle,blindpirate/gradle,gradle/gradle
kotlin
## Code Before: package org.gradle.kotlin.dsl.support import org.gradle.kotlin.dsl.fixtures.AbstractIntegrationTest import org.hamcrest.CoreMatchers.containsString import org.junit.Assert.assertThat import org.junit.Test class ImplicitImportsTest : AbstractIntegrationTest() { @Test fun `implicit imports are fully qualified to allow use of the preferred type amongst those with same simple name in different Gradle API packages`() { // given: withBuildScript(""" println("*" + Jar::class.qualifiedName + "*") """) // when: val result = build("help") // then: assertThat(result.output, containsString("*org.gradle.jvm.tasks.Jar*")) } } ## Instruction: Fix implicit imports tests after upstream default imports unification See https://github.com/gradle/gradle/pull/3140 ## Code After: package org.gradle.kotlin.dsl.support import org.gradle.kotlin.dsl.fixtures.AbstractIntegrationTest import org.hamcrest.CoreMatchers.containsString import org.junit.Assert.assertThat import org.junit.Test class ImplicitImportsTest : AbstractIntegrationTest() { @Test fun `implicit imports are fully qualified to allow use of the preferred type amongst those with same simple name in different Gradle API packages`() { // given: withBuildScript(""" println("*" + Jar::class.qualifiedName + "*") """) // when: val result = build("help") // then: assertThat(result.output, containsString("*org.gradle.api.tasks.bundling.Jar*")) } }
... val result = build("help") // then: assertThat(result.output, containsString("*org.gradle.api.tasks.bundling.Jar*")) } } ...
4f38f5f80679367f9e96463cb471c55d29c20b09
src/main/java/com/techern/minecraft/pathomania/proxy/ClientProxy.java
src/main/java/com/techern/minecraft/pathomania/proxy/ClientProxy.java
package com.techern.minecraft.pathomania.proxy; import com.techern.minecraft.pathomania.PathomaniaMod; import net.minecraft.block.Block; import net.minecraft.client.Minecraft; import net.minecraft.client.resources.model.ModelResourceLocation; import net.minecraft.item.Item; /** * An implementation of {@link CommonProxy} for use on the client {@link net.minecraftforge.fml.relauncher.Side} * * @since 0.0.1 */ public class ClientProxy extends CommonProxy { /** * Registers a {@link Block}'s inventory model * * @param block The {@link Block} being registered * @param metadata The {@link Integer} used to store metadata * @param modelName A {@link String} depicting the name of the model * * @since 0.0.1 */ public void registerBlockInventoryModel(Block block, int metadata, String modelName) { PathomaniaMod.LOGGER.trace("Got a request to register inventory model for " + block.getLocalizedName() + ", doing so"); Minecraft.getMinecraft().getRenderItem().getItemModelMesher().register(Item.getItemFromBlock(block), metadata, new ModelResourceLocation("pathomania:" + modelName, "inventory")); } }
package com.techern.minecraft.pathomania.proxy; import com.techern.minecraft.pathomania.PathomaniaMod; import net.minecraft.block.Block; import net.minecraft.client.Minecraft; import net.minecraft.client.resources.model.ModelResourceLocation; import net.minecraft.item.Item; /** * An implementation of {@link CommonProxy} for use on the client {@link net.minecraftforge.fml.relauncher.Side} * * @since 0.0.1 */ public class ClientProxy extends CommonProxy { /** * Registers a {@link Block}'s inventory model * * @param block The {@link Block} being registered * @param metadata The {@link Integer} used to store metadata * @param modelName A {@link String} depicting the name of the model * * @since 0.0.1 */ public void registerBlockInventoryModel(Block block, int metadata, String modelName) { PathomaniaMod.LOGGER.trace("Got a request to register inventory model for " + block.getLocalizedName() + ", doing so"); Minecraft.getMinecraft().getRenderItem().getItemModelMesher().register(Item.getItemFromBlock(block).setHasSubtypes(true), metadata, new ModelResourceLocation("pathomania:" + modelName, "inventory")); } }
Fix subtypes of middle-clicked paths combining on drop
Fix subtypes of middle-clicked paths combining on drop Fixes #8
Java
mit
Techern/Pathomania
java
## Code Before: package com.techern.minecraft.pathomania.proxy; import com.techern.minecraft.pathomania.PathomaniaMod; import net.minecraft.block.Block; import net.minecraft.client.Minecraft; import net.minecraft.client.resources.model.ModelResourceLocation; import net.minecraft.item.Item; /** * An implementation of {@link CommonProxy} for use on the client {@link net.minecraftforge.fml.relauncher.Side} * * @since 0.0.1 */ public class ClientProxy extends CommonProxy { /** * Registers a {@link Block}'s inventory model * * @param block The {@link Block} being registered * @param metadata The {@link Integer} used to store metadata * @param modelName A {@link String} depicting the name of the model * * @since 0.0.1 */ public void registerBlockInventoryModel(Block block, int metadata, String modelName) { PathomaniaMod.LOGGER.trace("Got a request to register inventory model for " + block.getLocalizedName() + ", doing so"); Minecraft.getMinecraft().getRenderItem().getItemModelMesher().register(Item.getItemFromBlock(block), metadata, new ModelResourceLocation("pathomania:" + modelName, "inventory")); } } ## Instruction: Fix subtypes of middle-clicked paths combining on drop Fixes #8 ## Code After: package com.techern.minecraft.pathomania.proxy; import com.techern.minecraft.pathomania.PathomaniaMod; import net.minecraft.block.Block; import net.minecraft.client.Minecraft; import net.minecraft.client.resources.model.ModelResourceLocation; import net.minecraft.item.Item; /** * An implementation of {@link CommonProxy} for use on the client {@link net.minecraftforge.fml.relauncher.Side} * * @since 0.0.1 */ public class ClientProxy extends CommonProxy { /** * Registers a {@link Block}'s inventory model * * @param block The {@link Block} being registered * @param metadata The {@link Integer} used to store metadata * @param modelName A {@link String} depicting the name of the model * * @since 0.0.1 */ public void registerBlockInventoryModel(Block block, int metadata, String modelName) { PathomaniaMod.LOGGER.trace("Got a request to register inventory model for " + block.getLocalizedName() + ", doing so"); Minecraft.getMinecraft().getRenderItem().getItemModelMesher().register(Item.getItemFromBlock(block).setHasSubtypes(true), metadata, new ModelResourceLocation("pathomania:" + modelName, "inventory")); } }
// ... existing code ... public void registerBlockInventoryModel(Block block, int metadata, String modelName) { PathomaniaMod.LOGGER.trace("Got a request to register inventory model for " + block.getLocalizedName() + ", doing so"); Minecraft.getMinecraft().getRenderItem().getItemModelMesher().register(Item.getItemFromBlock(block).setHasSubtypes(true), metadata, new ModelResourceLocation("pathomania:" + modelName, "inventory")); } // ... rest of the code ...
584d8a82a4f0350ba9ab5924f38a6d92162628d1
Validation-Manager-Web/src/main/java/net/sourceforge/javydreamercsw/validation/manager/web/file/AbstractFileDisplay.java
Validation-Manager-Web/src/main/java/net/sourceforge/javydreamercsw/validation/manager/web/file/AbstractFileDisplay.java
package net.sourceforge.javydreamercsw.validation.manager.web.file; import java.io.File; import java.io.IOException; import org.apache.commons.io.FileUtils; /** * * @author Javier A. Ortiz Bultron <[email protected]> */ public abstract class AbstractFileDisplay implements IFileDisplay { @Override public boolean supportFile(File f) { return f.isFile() && supportFile(f.getName()); } @Override public File loadFile(String name, byte[] bytes) throws IOException { File result = new File(System.getProperty("java.io.tmpdir") + System.getProperty("file.separator") + name); FileUtils.writeByteArrayToFile(result, bytes); return result; } }
package net.sourceforge.javydreamercsw.validation.manager.web.file; import java.io.File; import java.io.IOException; import org.apache.commons.io.FileUtils; /** * * @author Javier A. Ortiz Bultron <[email protected]> */ public abstract class AbstractFileDisplay implements IFileDisplay { @Override public boolean supportFile(File f) { return supportFile(f.getName()); } @Override public File loadFile(String name, byte[] bytes) throws IOException { File result = new File(System.getProperty("java.io.tmpdir") + System.getProperty("file.separator") + name); FileUtils.writeByteArrayToFile(result, bytes); return result; } }
Fix bug when deciding if file is supported.
Fix bug when deciding if file is supported.
Java
apache-2.0
javydreamercsw/validation-manager
java
## Code Before: package net.sourceforge.javydreamercsw.validation.manager.web.file; import java.io.File; import java.io.IOException; import org.apache.commons.io.FileUtils; /** * * @author Javier A. Ortiz Bultron <[email protected]> */ public abstract class AbstractFileDisplay implements IFileDisplay { @Override public boolean supportFile(File f) { return f.isFile() && supportFile(f.getName()); } @Override public File loadFile(String name, byte[] bytes) throws IOException { File result = new File(System.getProperty("java.io.tmpdir") + System.getProperty("file.separator") + name); FileUtils.writeByteArrayToFile(result, bytes); return result; } } ## Instruction: Fix bug when deciding if file is supported. ## Code After: package net.sourceforge.javydreamercsw.validation.manager.web.file; import java.io.File; import java.io.IOException; import org.apache.commons.io.FileUtils; /** * * @author Javier A. Ortiz Bultron <[email protected]> */ public abstract class AbstractFileDisplay implements IFileDisplay { @Override public boolean supportFile(File f) { return supportFile(f.getName()); } @Override public File loadFile(String name, byte[] bytes) throws IOException { File result = new File(System.getProperty("java.io.tmpdir") + System.getProperty("file.separator") + name); FileUtils.writeByteArrayToFile(result, bytes); return result; } }
# ... existing code ... @Override public boolean supportFile(File f) { return supportFile(f.getName()); } @Override # ... rest of the code ...
76bc5c3d036471991a273771e0eea2d1bc6a696f
modules/cat-eye-engine/cat-eye-engine-container-unit/src/main/java/org/cat/eye/engine/container/unit/deployment/UnitBundleDeployerImpl.java
modules/cat-eye-engine/cat-eye-engine-container-unit/src/main/java/org/cat/eye/engine/container/unit/deployment/UnitBundleDeployerImpl.java
package org.cat.eye.engine.container.unit.deployment; import org.cat.eye.engine.common.deployment.BundleClassLoader; import org.cat.eye.engine.common.deployment.BundleDeployer; import org.cat.eye.engine.common.deployment.management.BundleManager; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Created by Kotov on 30.11.2017. */ public class UnitBundleDeployerImpl implements BundleDeployer { private final static Logger LOGGER = LoggerFactory.getLogger(UnitBundleDeployerImpl.class); private BundleManager bundleManager; @Override public void deploy(String classPath, String domain) { ClassLoader bundleClassLoader = Thread.currentThread().getContextClassLoader(); // new BundleClassLoader(); // create and start thread for bundle deploying Thread deployingThread = new Thread(new UnitDeployingProcess(classPath, domain, bundleManager)); deployingThread.setContextClassLoader(bundleClassLoader); deployingThread.start(); try { deployingThread.join(); } catch (InterruptedException e) { LOGGER.error("deploy - can't deploy bundle: " + classPath, e); } } @Override public void setBundleManager(BundleManager bundleManager) { this.bundleManager = bundleManager; } }
package org.cat.eye.engine.container.unit.deployment; import org.cat.eye.engine.common.deployment.BundleDeployer; import org.cat.eye.engine.common.deployment.management.BundleManager; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Created by Kotov on 30.11.2017. */ public class UnitBundleDeployerImpl implements BundleDeployer { private final static Logger LOGGER = LoggerFactory.getLogger(UnitBundleDeployerImpl.class); private BundleManager bundleManager; @Override public void deploy(String classPath, String domain) { ClassLoader bundleClassLoader = Thread.currentThread().getContextClassLoader(); // new BundleClassLoader(); // create and start thread for bundle deploying Thread deployingThread = new Thread(new UnitDeployingProcess(classPath, domain, bundleManager)); deployingThread.setContextClassLoader(bundleClassLoader); deployingThread.start(); try { deployingThread.join(); } catch (InterruptedException e) { LOGGER.error("deploy - can't deploy bundle: " + classPath, e); } } @Override public void setBundleManager(BundleManager bundleManager) { this.bundleManager = bundleManager; } }
Access to computation context service through actors was implemented.
Access to computation context service through actors was implemented.
Java
apache-2.0
catkotov/cat-eye
java
## Code Before: package org.cat.eye.engine.container.unit.deployment; import org.cat.eye.engine.common.deployment.BundleClassLoader; import org.cat.eye.engine.common.deployment.BundleDeployer; import org.cat.eye.engine.common.deployment.management.BundleManager; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Created by Kotov on 30.11.2017. */ public class UnitBundleDeployerImpl implements BundleDeployer { private final static Logger LOGGER = LoggerFactory.getLogger(UnitBundleDeployerImpl.class); private BundleManager bundleManager; @Override public void deploy(String classPath, String domain) { ClassLoader bundleClassLoader = Thread.currentThread().getContextClassLoader(); // new BundleClassLoader(); // create and start thread for bundle deploying Thread deployingThread = new Thread(new UnitDeployingProcess(classPath, domain, bundleManager)); deployingThread.setContextClassLoader(bundleClassLoader); deployingThread.start(); try { deployingThread.join(); } catch (InterruptedException e) { LOGGER.error("deploy - can't deploy bundle: " + classPath, e); } } @Override public void setBundleManager(BundleManager bundleManager) { this.bundleManager = bundleManager; } } ## Instruction: Access to computation context service through actors was implemented. ## Code After: package org.cat.eye.engine.container.unit.deployment; import org.cat.eye.engine.common.deployment.BundleDeployer; import org.cat.eye.engine.common.deployment.management.BundleManager; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Created by Kotov on 30.11.2017. */ public class UnitBundleDeployerImpl implements BundleDeployer { private final static Logger LOGGER = LoggerFactory.getLogger(UnitBundleDeployerImpl.class); private BundleManager bundleManager; @Override public void deploy(String classPath, String domain) { ClassLoader bundleClassLoader = Thread.currentThread().getContextClassLoader(); // new BundleClassLoader(); // create and start thread for bundle deploying Thread deployingThread = new Thread(new UnitDeployingProcess(classPath, domain, bundleManager)); deployingThread.setContextClassLoader(bundleClassLoader); deployingThread.start(); try { deployingThread.join(); } catch (InterruptedException e) { LOGGER.error("deploy - can't deploy bundle: " + classPath, e); } } @Override public void setBundleManager(BundleManager bundleManager) { this.bundleManager = bundleManager; } }
... package org.cat.eye.engine.container.unit.deployment; import org.cat.eye.engine.common.deployment.BundleDeployer; import org.cat.eye.engine.common.deployment.management.BundleManager; import org.slf4j.Logger; ...
1d1fec3287abbddfb376ff1fcbcc85bbcf0b44a2
pyoanda/tests/test_client.py
pyoanda/tests/test_client.py
import unittest from ..client import Client class TestClient(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_connect(self): pass
import unittest from unittest.mock import patch from ..client import Client from ..exceptions import BadCredentials class TestClient(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_connect_pass(self): with patch.object(Client, '_Client__get_credentials', return_value=True) as mock_method: c = Client( "http://mydomain.com", "http://mystreamingdomain.com", "my_account", "my_token" ) def test_connect_fail(self): with patch.object(Client, '_Client__get_credentials', return_value=False) as mock_method: with self.assertRaises(BadCredentials): c = Client( "http://mydomain.com", "http://mystreamingdomain.com", "my_account", "my_token" )
Add very simple client creator validator
Add very simple client creator validator
Python
mit
MonoCloud/pyoanda,toloco/pyoanda,elyobo/pyoanda
python
## Code Before: import unittest from ..client import Client class TestClient(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_connect(self): pass ## Instruction: Add very simple client creator validator ## Code After: import unittest from unittest.mock import patch from ..client import Client from ..exceptions import BadCredentials class TestClient(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_connect_pass(self): with patch.object(Client, '_Client__get_credentials', return_value=True) as mock_method: c = Client( "http://mydomain.com", "http://mystreamingdomain.com", "my_account", "my_token" ) def test_connect_fail(self): with patch.object(Client, '_Client__get_credentials', return_value=False) as mock_method: with self.assertRaises(BadCredentials): c = Client( "http://mydomain.com", "http://mystreamingdomain.com", "my_account", "my_token" )
... import unittest from unittest.mock import patch from ..client import Client from ..exceptions import BadCredentials class TestClient(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_connect_pass(self): with patch.object(Client, '_Client__get_credentials', return_value=True) as mock_method: c = Client( "http://mydomain.com", "http://mystreamingdomain.com", "my_account", "my_token" ) def test_connect_fail(self): with patch.object(Client, '_Client__get_credentials', return_value=False) as mock_method: with self.assertRaises(BadCredentials): c = Client( "http://mydomain.com", "http://mystreamingdomain.com", "my_account", "my_token" ) ...
448158c4faaa570d23970cef08d9d1a6a39a5df6
src/main/java/nallar/tickthreading/mod/CoreMod.java
src/main/java/nallar/tickthreading/mod/CoreMod.java
package nallar.tickthreading.mod; import me.nallar.modpatcher.ModPatcher; import nallar.tickthreading.log.Log; import nallar.tickthreading.util.PropertyUtil; import nallar.tickthreading.util.Version; import nallar.tickthreading.util.unsafe.UnsafeUtil; import net.minecraftforge.fml.relauncher.IFMLLoadingPlugin; import java.util.*; @IFMLLoadingPlugin.Name("@MOD_NAME@Core") @IFMLLoadingPlugin.MCVersion("@MC_VERSION@") @IFMLLoadingPlugin.SortingIndex(1002) public class CoreMod implements IFMLLoadingPlugin { public static boolean static { if (PropertyUtil.get("removeSecurityManager", false)) { UnsafeUtil.removeSecurityManager(); } ModPatcher.requireVersion("latest", "beta"); Log.info(Version.DESCRIPTION + " CoreMod initialised"); } @Override public String[] getASMTransformerClass() { return new String[0]; } @Override public String getModContainerClass() { return null; } @Override public String getSetupClass() { return ModPatcher.getSetupClass(); } @Override public void injectData(Map<String, Object> map) { ModPatcher.loadMixins("nallar.tickthreading.mixin"); } @Override public String getAccessTransformerClass() { return null; } }
package nallar.tickthreading.mod; import me.nallar.modpatcher.ModPatcher; import nallar.tickthreading.log.Log; import nallar.tickthreading.util.PropertyUtil; import nallar.tickthreading.util.Version; import nallar.tickthreading.util.unsafe.UnsafeUtil; import net.minecraftforge.fml.relauncher.IFMLLoadingPlugin; import java.util.*; @IFMLLoadingPlugin.Name("@MOD_NAME@Core") @IFMLLoadingPlugin.MCVersion("@MC_VERSION@") @IFMLLoadingPlugin.SortingIndex(1002) public class CoreMod implements IFMLLoadingPlugin { static { if (PropertyUtil.get("removeSecurityManager", false)) { UnsafeUtil.removeSecurityManager(); } ModPatcher.requireVersion("latest", "beta"); Log.info(Version.DESCRIPTION + " CoreMod initialised"); } @Override public String[] getASMTransformerClass() { return new String[0]; } @Override public String getModContainerClass() { return null; } @Override public String getSetupClass() { return ModPatcher.getSetupClass(); } @Override public void injectData(Map<String, Object> map) { ModPatcher.loadMixins("nallar.tickthreading.mixin"); } @Override public String getAccessTransformerClass() { return null; } }
Remove accidental extra line - shouldn't have been part of last commit
Remove accidental extra line - shouldn't have been part of last commit
Java
mit
nallar/TickThreading
java
## Code Before: package nallar.tickthreading.mod; import me.nallar.modpatcher.ModPatcher; import nallar.tickthreading.log.Log; import nallar.tickthreading.util.PropertyUtil; import nallar.tickthreading.util.Version; import nallar.tickthreading.util.unsafe.UnsafeUtil; import net.minecraftforge.fml.relauncher.IFMLLoadingPlugin; import java.util.*; @IFMLLoadingPlugin.Name("@MOD_NAME@Core") @IFMLLoadingPlugin.MCVersion("@MC_VERSION@") @IFMLLoadingPlugin.SortingIndex(1002) public class CoreMod implements IFMLLoadingPlugin { public static boolean static { if (PropertyUtil.get("removeSecurityManager", false)) { UnsafeUtil.removeSecurityManager(); } ModPatcher.requireVersion("latest", "beta"); Log.info(Version.DESCRIPTION + " CoreMod initialised"); } @Override public String[] getASMTransformerClass() { return new String[0]; } @Override public String getModContainerClass() { return null; } @Override public String getSetupClass() { return ModPatcher.getSetupClass(); } @Override public void injectData(Map<String, Object> map) { ModPatcher.loadMixins("nallar.tickthreading.mixin"); } @Override public String getAccessTransformerClass() { return null; } } ## Instruction: Remove accidental extra line - shouldn't have been part of last commit ## Code After: package nallar.tickthreading.mod; import me.nallar.modpatcher.ModPatcher; import nallar.tickthreading.log.Log; import nallar.tickthreading.util.PropertyUtil; import nallar.tickthreading.util.Version; import nallar.tickthreading.util.unsafe.UnsafeUtil; import net.minecraftforge.fml.relauncher.IFMLLoadingPlugin; import java.util.*; @IFMLLoadingPlugin.Name("@MOD_NAME@Core") @IFMLLoadingPlugin.MCVersion("@MC_VERSION@") @IFMLLoadingPlugin.SortingIndex(1002) public class CoreMod implements IFMLLoadingPlugin { static { if (PropertyUtil.get("removeSecurityManager", false)) { UnsafeUtil.removeSecurityManager(); } ModPatcher.requireVersion("latest", "beta"); Log.info(Version.DESCRIPTION + " CoreMod initialised"); } @Override public String[] getASMTransformerClass() { return new String[0]; } @Override public String getModContainerClass() { return null; } @Override public String getSetupClass() { return ModPatcher.getSetupClass(); } @Override public void injectData(Map<String, Object> map) { ModPatcher.loadMixins("nallar.tickthreading.mixin"); } @Override public String getAccessTransformerClass() { return null; } }
// ... existing code ... @IFMLLoadingPlugin.MCVersion("@MC_VERSION@") @IFMLLoadingPlugin.SortingIndex(1002) public class CoreMod implements IFMLLoadingPlugin { static { if (PropertyUtil.get("removeSecurityManager", false)) { UnsafeUtil.removeSecurityManager(); // ... rest of the code ...
a87d0451c8f850538f8a534b659ad749b601fd3e
common/cpw/mods/fml/common/event/FMLServerStartingEvent.java
common/cpw/mods/fml/common/event/FMLServerStartingEvent.java
package cpw.mods.fml.common.event; import net.minecraft.server.MinecraftServer; import cpw.mods.fml.common.LoaderState.ModState; public class FMLServerStartingEvent extends FMLStateEvent { private MinecraftServer server; public FMLServerStartingEvent(Object... data) { super(data); this.server = (MinecraftServer) data[0]; } @Override public ModState getModState() { return ModState.AVAILABLE; } public MinecraftServer getServer() { return server; } }
package cpw.mods.fml.common.event; import net.minecraft.server.MinecraftServer; import net.minecraft.src.CommandHandler; import net.minecraft.src.ICommand; import cpw.mods.fml.common.LoaderState.ModState; public class FMLServerStartingEvent extends FMLStateEvent { private MinecraftServer server; public FMLServerStartingEvent(Object... data) { super(data); this.server = (MinecraftServer) data[0]; } @Override public ModState getModState() { return ModState.AVAILABLE; } public MinecraftServer getServer() { return server; } public void registerServerCommand(ICommand command) { CommandHandler ch = (CommandHandler) getServer().func_71187_D(); ch.func_71560_a(command); } }
Add in a helper on the server start event for adding commands to the server.
Add in a helper on the server start event for adding commands to the server.
Java
lgpl-2.1
aerospark/FML,aerospark/FML,aerospark/FML,MinecraftForge/FML
java
## Code Before: package cpw.mods.fml.common.event; import net.minecraft.server.MinecraftServer; import cpw.mods.fml.common.LoaderState.ModState; public class FMLServerStartingEvent extends FMLStateEvent { private MinecraftServer server; public FMLServerStartingEvent(Object... data) { super(data); this.server = (MinecraftServer) data[0]; } @Override public ModState getModState() { return ModState.AVAILABLE; } public MinecraftServer getServer() { return server; } } ## Instruction: Add in a helper on the server start event for adding commands to the server. ## Code After: package cpw.mods.fml.common.event; import net.minecraft.server.MinecraftServer; import net.minecraft.src.CommandHandler; import net.minecraft.src.ICommand; import cpw.mods.fml.common.LoaderState.ModState; public class FMLServerStartingEvent extends FMLStateEvent { private MinecraftServer server; public FMLServerStartingEvent(Object... data) { super(data); this.server = (MinecraftServer) data[0]; } @Override public ModState getModState() { return ModState.AVAILABLE; } public MinecraftServer getServer() { return server; } public void registerServerCommand(ICommand command) { CommandHandler ch = (CommandHandler) getServer().func_71187_D(); ch.func_71560_a(command); } }
// ... existing code ... package cpw.mods.fml.common.event; import net.minecraft.server.MinecraftServer; import net.minecraft.src.CommandHandler; import net.minecraft.src.ICommand; import cpw.mods.fml.common.LoaderState.ModState; public class FMLServerStartingEvent extends FMLStateEvent // ... modified code ... { return server; } public void registerServerCommand(ICommand command) { CommandHandler ch = (CommandHandler) getServer().func_71187_D(); ch.func_71560_a(command); } } // ... rest of the code ...
d1e9586fbbadd8278d1d4023490df3348915b217
migrations/versions/0082_set_international.py
migrations/versions/0082_set_international.py
# revision identifiers, used by Alembic. from datetime import datetime revision = '0082_set_international' down_revision = '0080_fix_rate_start_date' from alembic import op import sqlalchemy as sa def upgrade(): conn = op.get_bind() start = datetime.utcnow() all_notifications = "select id from notification_history where international is null limit 10000" results = conn.execute(all_notifications) res = results.fetchall() conn.execute("update notifications set international = False where id in ({})".format(all_notifications)) conn.execute("update notification_history set international = False where id in ({})".format(all_notifications)) while len(res) > 0: conn.execute("update notifications set international = False where id in ({})".format(all_notifications)) conn.execute("update notification_history set international = False where id in ({})".format(all_notifications)) results = conn.execute(all_notifications) res = results.fetchall() end = datetime.utcnow() print("Started at: {} ended at: {}".format(start, end)) def downgrade(): # There is no way to downgrade this update. pass
from datetime import datetime from alembic import op # revision identifiers, used by Alembic. revision = '0082_set_international' down_revision = '0081_noti_status_as_enum' def upgrade(): conn = op.get_bind() start = datetime.utcnow() notification_history = "select id from notification_history where international is null limit 10000" results = conn.execute(notification_history) res = results.fetchall() while len(res) > 0: conn.execute("update notification_history set international = False where id in ({})".format( notification_history)) results = conn.execute(notification_history) res = results.fetchall() notifications = "select id from notifications where international is null limit 10000" results2 = conn.execute(notifications) res2 = results2.fetchall() while len(res2) > 0: conn.execute("update notifications set international = False where id in ({})".format(notifications)) results2 = conn.execute(notifications) res2 = results2.fetchall() end = datetime.utcnow() print("Started at: {} ended at: {}".format(start, end)) def downgrade(): # There is no way to downgrade this update. pass
Update the script to set the international flag to do the notifications and notification_history in separate loops. It takes about 1.5 minutes to update 27,000 notifications and 27,000 notification_history. The update is a row level lock so will only affect updates to the same row. This is unlikely as the data being updated should be older than 3 days. The second scripts updates the table to set international as not null, to make the model.
Update the script to set the international flag to do the notifications and notification_history in separate loops. It takes about 1.5 minutes to update 27,000 notifications and 27,000 notification_history. The update is a row level lock so will only affect updates to the same row. This is unlikely as the data being updated should be older than 3 days. The second scripts updates the table to set international as not null, to make the model.
Python
mit
alphagov/notifications-api,alphagov/notifications-api
python
## Code Before: # revision identifiers, used by Alembic. from datetime import datetime revision = '0082_set_international' down_revision = '0080_fix_rate_start_date' from alembic import op import sqlalchemy as sa def upgrade(): conn = op.get_bind() start = datetime.utcnow() all_notifications = "select id from notification_history where international is null limit 10000" results = conn.execute(all_notifications) res = results.fetchall() conn.execute("update notifications set international = False where id in ({})".format(all_notifications)) conn.execute("update notification_history set international = False where id in ({})".format(all_notifications)) while len(res) > 0: conn.execute("update notifications set international = False where id in ({})".format(all_notifications)) conn.execute("update notification_history set international = False where id in ({})".format(all_notifications)) results = conn.execute(all_notifications) res = results.fetchall() end = datetime.utcnow() print("Started at: {} ended at: {}".format(start, end)) def downgrade(): # There is no way to downgrade this update. pass ## Instruction: Update the script to set the international flag to do the notifications and notification_history in separate loops. It takes about 1.5 minutes to update 27,000 notifications and 27,000 notification_history. The update is a row level lock so will only affect updates to the same row. This is unlikely as the data being updated should be older than 3 days. The second scripts updates the table to set international as not null, to make the model. ## Code After: from datetime import datetime from alembic import op # revision identifiers, used by Alembic. revision = '0082_set_international' down_revision = '0081_noti_status_as_enum' def upgrade(): conn = op.get_bind() start = datetime.utcnow() notification_history = "select id from notification_history where international is null limit 10000" results = conn.execute(notification_history) res = results.fetchall() while len(res) > 0: conn.execute("update notification_history set international = False where id in ({})".format( notification_history)) results = conn.execute(notification_history) res = results.fetchall() notifications = "select id from notifications where international is null limit 10000" results2 = conn.execute(notifications) res2 = results2.fetchall() while len(res2) > 0: conn.execute("update notifications set international = False where id in ({})".format(notifications)) results2 = conn.execute(notifications) res2 = results2.fetchall() end = datetime.utcnow() print("Started at: {} ended at: {}".format(start, end)) def downgrade(): # There is no way to downgrade this update. pass
// ... existing code ... from datetime import datetime from alembic import op # revision identifiers, used by Alembic. revision = '0082_set_international' down_revision = '0081_noti_status_as_enum' def upgrade(): conn = op.get_bind() start = datetime.utcnow() notification_history = "select id from notification_history where international is null limit 10000" results = conn.execute(notification_history) res = results.fetchall() while len(res) > 0: conn.execute("update notification_history set international = False where id in ({})".format( notification_history)) results = conn.execute(notification_history) res = results.fetchall() notifications = "select id from notifications where international is null limit 10000" results2 = conn.execute(notifications) res2 = results2.fetchall() while len(res2) > 0: conn.execute("update notifications set international = False where id in ({})".format(notifications)) results2 = conn.execute(notifications) res2 = results2.fetchall() end = datetime.utcnow() print("Started at: {} ended at: {}".format(start, end)) def downgrade(): # There is no way to downgrade this update. // ... rest of the code ...
b6ee444f5c874c21eed598bfb45bce66c3d0b7f8
src/main/java/com/emc/ecs/serviceBroker/config/BrokerConfig.java
src/main/java/com/emc/ecs/serviceBroker/config/BrokerConfig.java
package com.emc.ecs.serviceBroker.config; import java.net.URL; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import com.emc.ecs.managementClient.Connection; import com.emc.ecs.serviceBroker.repository.EcsRepositoryCredentials; @Configuration @ComponentScan(basePackages = "com.emc.ecs.serviceBroker") public class BrokerConfig { @Bean public Connection ecsConnection() { URL certificate = getClass().getClassLoader().getResource("localhost.pem"); return new Connection("https://8.34.215.78:4443", "root", "ChangeMe", certificate); } @Bean public EcsRepositoryCredentials getRepositoryCredentials() { return new EcsRepositoryCredentials("ecs-cf-service-broker-repository", "ecs-cf-service-broker-repository", "ns1", "urn:storageos:ReplicationGroupInfo:d4fc7068-1051-49ee-841f-1102e44c841e:global"); } }
package com.emc.ecs.serviceBroker.config; import java.net.URL; import org.cloudfoundry.community.servicebroker.model.BrokerApiVersion; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import com.emc.ecs.managementClient.Connection; import com.emc.ecs.serviceBroker.repository.EcsRepositoryCredentials; @Configuration @ComponentScan(basePackages = "com.emc.ecs.serviceBroker") public class BrokerConfig { @Bean public Connection ecsConnection() { URL certificate = getClass().getClassLoader().getResource("localhost.pem"); return new Connection("https://104.197.239.202:4443", "root", "ChangeMe", certificate); } @Bean public BrokerApiVersion brokerApiVersion() { return new BrokerApiVersion("2.7"); } @Bean public EcsRepositoryCredentials getRepositoryCredentials() { return new EcsRepositoryCredentials("ecs-cf-service-broker-repository", "ecs-cf-service-broker-repository", "ns1", "urn:storageos:ReplicationGroupInfo:f81a7335-cadf-48fb-8eda-4856b250e9de:global"); } }
Set broker to version 2.7
Set broker to version 2.7
Java
apache-2.0
codedellemc/ecs-cf-service-broker,spiegela/ecs-cf-service-broker,emccode/ecs-cf-service-broker
java
## Code Before: package com.emc.ecs.serviceBroker.config; import java.net.URL; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import com.emc.ecs.managementClient.Connection; import com.emc.ecs.serviceBroker.repository.EcsRepositoryCredentials; @Configuration @ComponentScan(basePackages = "com.emc.ecs.serviceBroker") public class BrokerConfig { @Bean public Connection ecsConnection() { URL certificate = getClass().getClassLoader().getResource("localhost.pem"); return new Connection("https://8.34.215.78:4443", "root", "ChangeMe", certificate); } @Bean public EcsRepositoryCredentials getRepositoryCredentials() { return new EcsRepositoryCredentials("ecs-cf-service-broker-repository", "ecs-cf-service-broker-repository", "ns1", "urn:storageos:ReplicationGroupInfo:d4fc7068-1051-49ee-841f-1102e44c841e:global"); } } ## Instruction: Set broker to version 2.7 ## Code After: package com.emc.ecs.serviceBroker.config; import java.net.URL; import org.cloudfoundry.community.servicebroker.model.BrokerApiVersion; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import com.emc.ecs.managementClient.Connection; import com.emc.ecs.serviceBroker.repository.EcsRepositoryCredentials; @Configuration @ComponentScan(basePackages = "com.emc.ecs.serviceBroker") public class BrokerConfig { @Bean public Connection ecsConnection() { URL certificate = getClass().getClassLoader().getResource("localhost.pem"); return new Connection("https://104.197.239.202:4443", "root", "ChangeMe", certificate); } @Bean public BrokerApiVersion brokerApiVersion() { return new BrokerApiVersion("2.7"); } @Bean public EcsRepositoryCredentials getRepositoryCredentials() { return new EcsRepositoryCredentials("ecs-cf-service-broker-repository", "ecs-cf-service-broker-repository", "ns1", "urn:storageos:ReplicationGroupInfo:f81a7335-cadf-48fb-8eda-4856b250e9de:global"); } }
// ... existing code ... import java.net.URL; import org.cloudfoundry.community.servicebroker.model.BrokerApiVersion; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; // ... modified code ... @Bean public Connection ecsConnection() { URL certificate = getClass().getClassLoader().getResource("localhost.pem"); return new Connection("https://104.197.239.202:4443", "root", "ChangeMe", certificate); } @Bean public BrokerApiVersion brokerApiVersion() { return new BrokerApiVersion("2.7"); } @Bean public EcsRepositoryCredentials getRepositoryCredentials() { return new EcsRepositoryCredentials("ecs-cf-service-broker-repository", "ecs-cf-service-broker-repository", "ns1", "urn:storageos:ReplicationGroupInfo:f81a7335-cadf-48fb-8eda-4856b250e9de:global"); } } // ... rest of the code ...
24fd3b98f06b30d8827ba472dc305514ed71a5e5
cropimg/widgets.py
cropimg/widgets.py
from django.forms.widgets import Input, ClearableFileInput from django.template.loader import render_to_string class CIImgWidget(ClearableFileInput): def render(self, name, value, attrs=None): try: attrs["data-value"] = getattr(value, "url", "") except ValueError: # attribute has no file associated with it. attrs["data-value"] = "" return super(CIImgWidget, self).render(name, value, attrs) class CIThumbnailWidget(Input): input_type = "text" def render(self, name, value, attrs=None): if attrs: attrs.update(self.attrs) attrs["type"] = "hidden" input_field = super(CIThumbnailWidget, self).render(name, value, attrs) return render_to_string("cropimg/cropimg_widget.html", { "name": name, "value": value, "attrs": attrs, "input_field": input_field }) class Media: js = ("cropimg/js/jquery_init.js", "cropimg/js/cropimg.jquery.js", "cropimg/js/cropimg_init.js") css = {"all": ["cropimg/resource/cropimg.css"]}
from django.forms.widgets import Input, ClearableFileInput from django.template.loader import render_to_string class CIImgWidget(ClearableFileInput): def render(self, name, value, attrs=None): try: attrs["data-value"] = getattr(value, "url", "") except ValueError: # attribute has no file associated with it. attrs["data-value"] = "" return super(CIImgWidget, self).render(name, value, attrs) class CIThumbnailWidget(Input): input_type = "text" def render(self, name, value, attrs=None, renderer=None): if attrs: attrs.update(self.attrs) attrs["type"] = "hidden" input_field = super(CIThumbnailWidget, self).render(name, value, attrs) return render_to_string("cropimg/cropimg_widget.html", { "name": name, "value": value, "attrs": attrs, "input_field": input_field }) class Media: js = ("cropimg/js/jquery_init.js", "cropimg/js/cropimg.jquery.js", "cropimg/js/cropimg_init.js") css = {"all": ["cropimg/resource/cropimg.css"]}
Make compatible with Django >2.1
Make compatible with Django >2.1
Python
mit
rewardz/cropimg-django,rewardz/cropimg-django,rewardz/cropimg-django
python
## Code Before: from django.forms.widgets import Input, ClearableFileInput from django.template.loader import render_to_string class CIImgWidget(ClearableFileInput): def render(self, name, value, attrs=None): try: attrs["data-value"] = getattr(value, "url", "") except ValueError: # attribute has no file associated with it. attrs["data-value"] = "" return super(CIImgWidget, self).render(name, value, attrs) class CIThumbnailWidget(Input): input_type = "text" def render(self, name, value, attrs=None): if attrs: attrs.update(self.attrs) attrs["type"] = "hidden" input_field = super(CIThumbnailWidget, self).render(name, value, attrs) return render_to_string("cropimg/cropimg_widget.html", { "name": name, "value": value, "attrs": attrs, "input_field": input_field }) class Media: js = ("cropimg/js/jquery_init.js", "cropimg/js/cropimg.jquery.js", "cropimg/js/cropimg_init.js") css = {"all": ["cropimg/resource/cropimg.css"]} ## Instruction: Make compatible with Django >2.1 ## Code After: from django.forms.widgets import Input, ClearableFileInput from django.template.loader import render_to_string class CIImgWidget(ClearableFileInput): def render(self, name, value, attrs=None): try: attrs["data-value"] = getattr(value, "url", "") except ValueError: # attribute has no file associated with it. attrs["data-value"] = "" return super(CIImgWidget, self).render(name, value, attrs) class CIThumbnailWidget(Input): input_type = "text" def render(self, name, value, attrs=None, renderer=None): if attrs: attrs.update(self.attrs) attrs["type"] = "hidden" input_field = super(CIThumbnailWidget, self).render(name, value, attrs) return render_to_string("cropimg/cropimg_widget.html", { "name": name, "value": value, "attrs": attrs, "input_field": input_field }) class Media: js = ("cropimg/js/jquery_init.js", "cropimg/js/cropimg.jquery.js", "cropimg/js/cropimg_init.js") css = {"all": ["cropimg/resource/cropimg.css"]}
# ... existing code ... input_type = "text" def render(self, name, value, attrs=None, renderer=None): if attrs: attrs.update(self.attrs) attrs["type"] = "hidden" # ... rest of the code ...
2549a66b6785d5a0ed0658a4f375a21c486792df
sifr/util.py
sifr/util.py
import datetime from dateutil import parser import six def normalize_time(t): try: if isinstance(t, datetime.datetime): return t elif isinstance(t, datetime.date): return datetime.datetime(t.year, t.month, t.day) elif isinstance(t, (int, float)): return datetime.datetime.fromtimestamp(t) elif isinstance(t, six.string_types): return parser.parse(t) else: raise except: # noqa raise TypeError( "time must be represented as either a timestamp (int,float), " "a datetime.datetime or datetime.date object, " "or an iso-8601 formatted string" )
import datetime from dateutil import parser import six def normalize_time(t): try: if isinstance(t, datetime.datetime): return t elif isinstance(t, datetime.date): return datetime.datetime(t.year, t.month, t.day) elif isinstance(t, (int, float)): return datetime.datetime.fromtimestamp(t) elif isinstance(t, six.string_types): return parser.parse(t) else: raise TypeError except: # noqa raise TypeError( "time must be represented as either a timestamp (int,float), " "a datetime.datetime or datetime.date object, " "or an iso-8601 formatted string" )
Raise explicit exception on no type match
Raise explicit exception on no type match
Python
mit
alisaifee/sifr,alisaifee/sifr
python
## Code Before: import datetime from dateutil import parser import six def normalize_time(t): try: if isinstance(t, datetime.datetime): return t elif isinstance(t, datetime.date): return datetime.datetime(t.year, t.month, t.day) elif isinstance(t, (int, float)): return datetime.datetime.fromtimestamp(t) elif isinstance(t, six.string_types): return parser.parse(t) else: raise except: # noqa raise TypeError( "time must be represented as either a timestamp (int,float), " "a datetime.datetime or datetime.date object, " "or an iso-8601 formatted string" ) ## Instruction: Raise explicit exception on no type match ## Code After: import datetime from dateutil import parser import six def normalize_time(t): try: if isinstance(t, datetime.datetime): return t elif isinstance(t, datetime.date): return datetime.datetime(t.year, t.month, t.day) elif isinstance(t, (int, float)): return datetime.datetime.fromtimestamp(t) elif isinstance(t, six.string_types): return parser.parse(t) else: raise TypeError except: # noqa raise TypeError( "time must be represented as either a timestamp (int,float), " "a datetime.datetime or datetime.date object, " "or an iso-8601 formatted string" )
... elif isinstance(t, six.string_types): return parser.parse(t) else: raise TypeError except: # noqa raise TypeError( "time must be represented as either a timestamp (int,float), " ...
4fa9cff24867d3288d4f46c669151e823e934df0
nmea.py
nmea.py
import re def gpgga_get_position(gpgga_sentence): gps = re.search("\$GPGGA,,([0-9]+\.[0-9]+),([NS]),([0-9]+\.[0-9]+),([WE]),,,,([0-9]+),M,+\*(\w+)", gpgga_sentence) position = {} position['lat'] = gps.group(1) position['lat_coord'] = gps.group(2) position['long'] = gps.group(3) position['long_coord'] = gps.group(4) position['height'] = str(int(int(gps.group(5)) * 3.28084)).zfill(6) return position if __name__ == "__main__": print gpgga_get_position("$GPGGA,,3434.28,S,05829.35,W,,,,176,M,,,,,*39")
import re def gpgga_get_position(gpgga_sentence): sentence = gpgga_sentence.split(",") position = {} position['lat'] = sentence[2] position['lat_coord'] = sentence[3] position['lon'] = sentence[4] position['lon_coord'] = sentence[5] position['height'] = str(int(float(sentence[11]) * 3.28084)).zfill(6) return position if __name__ == "__main__": print gpgga_get_position("$GPGGA,142353.00,3436.93,S,05822.72,W,1,06,2.4,55.5,M,13.2,M,,*54")
Simplify how we get lat and long from GPGGA sentence.
Simplify how we get lat and long from GPGGA sentence.
Python
mit
elielsardanons/dstar_sniffer,elielsardanons/dstar_sniffer
python
## Code Before: import re def gpgga_get_position(gpgga_sentence): gps = re.search("\$GPGGA,,([0-9]+\.[0-9]+),([NS]),([0-9]+\.[0-9]+),([WE]),,,,([0-9]+),M,+\*(\w+)", gpgga_sentence) position = {} position['lat'] = gps.group(1) position['lat_coord'] = gps.group(2) position['long'] = gps.group(3) position['long_coord'] = gps.group(4) position['height'] = str(int(int(gps.group(5)) * 3.28084)).zfill(6) return position if __name__ == "__main__": print gpgga_get_position("$GPGGA,,3434.28,S,05829.35,W,,,,176,M,,,,,*39") ## Instruction: Simplify how we get lat and long from GPGGA sentence. ## Code After: import re def gpgga_get_position(gpgga_sentence): sentence = gpgga_sentence.split(",") position = {} position['lat'] = sentence[2] position['lat_coord'] = sentence[3] position['lon'] = sentence[4] position['lon_coord'] = sentence[5] position['height'] = str(int(float(sentence[11]) * 3.28084)).zfill(6) return position if __name__ == "__main__": print gpgga_get_position("$GPGGA,142353.00,3436.93,S,05822.72,W,1,06,2.4,55.5,M,13.2,M,,*54")
// ... existing code ... import re def gpgga_get_position(gpgga_sentence): sentence = gpgga_sentence.split(",") position = {} position['lat'] = sentence[2] position['lat_coord'] = sentence[3] position['lon'] = sentence[4] position['lon_coord'] = sentence[5] position['height'] = str(int(float(sentence[11]) * 3.28084)).zfill(6) return position if __name__ == "__main__": print gpgga_get_position("$GPGGA,142353.00,3436.93,S,05822.72,W,1,06,2.4,55.5,M,13.2,M,,*54") // ... rest of the code ...
4d95e5cb938c43cacd14085bf752485334ab6f1a
prf/tests/test_mongodb.py
prf/tests/test_mongodb.py
from prf.tests.prf_testcase import PrfTestCase from prf.mongodb import get_document_cls class TestMongoDB(PrfTestCase): def setUp(self): super(TestMongoDB, self).setUp() self.drop_databases() self.unload_documents() def test_get_document_cls(self): cls = self.create_collection('default', 'col1') cls2 = self.create_collection('prf-test2', 'col2') cls3 = self.create_collection('default', 'col3') cls4 = self.create_collection('prf-test2', 'col3') dcls = get_document_cls('col1') dcls2 = get_document_cls('col2') dcls3 = get_document_cls('col3') assert cls == dcls assert cls2 == dcls2 assert dcls2._meta['db_alias'] == 'prf-test2' # This is broken behavior with collision on collection names across dbs, # get_document_cls will return the most recently defined class with that name. assert dcls3 == cls4
import mock from prf.tests.prf_testcase import PrfTestCase from prf.mongodb import get_document_cls, connect_dataset_aliases class TestMongoDB(PrfTestCase): def setUp(self): super(TestMongoDB, self).setUp() self.drop_databases() self.unload_documents() def test_get_document_cls(self): cls = self.create_collection('default', 'col1') cls2 = self.create_collection('prf-test2', 'col2') cls3 = self.create_collection('default', 'col3') cls4 = self.create_collection('prf-test2', 'col3') dcls = get_document_cls('col1') dcls2 = get_document_cls('col2') dcls3 = get_document_cls('col3') assert cls == dcls assert cls2 == dcls2 assert dcls2._meta['db_alias'] == 'prf-test2' # This is broken behavior with collision on collection names across dbs, # get_document_cls will return the most recently defined class with that name. assert dcls3 == cls4 @mock.patch('prf.mongodb.mongo_connect') def test_connect_dataset_aliases_missing_config(self, connect): del self.conf.registry.settings['dataset.namespaces'] connect_dataset_aliases(self.conf, self.conf.prf_settings()) connect.assert_not_called()
Make sure no crashes happen when no namespaces are set
Make sure no crashes happen when no namespaces are set
Python
mit
vahana/prf
python
## Code Before: from prf.tests.prf_testcase import PrfTestCase from prf.mongodb import get_document_cls class TestMongoDB(PrfTestCase): def setUp(self): super(TestMongoDB, self).setUp() self.drop_databases() self.unload_documents() def test_get_document_cls(self): cls = self.create_collection('default', 'col1') cls2 = self.create_collection('prf-test2', 'col2') cls3 = self.create_collection('default', 'col3') cls4 = self.create_collection('prf-test2', 'col3') dcls = get_document_cls('col1') dcls2 = get_document_cls('col2') dcls3 = get_document_cls('col3') assert cls == dcls assert cls2 == dcls2 assert dcls2._meta['db_alias'] == 'prf-test2' # This is broken behavior with collision on collection names across dbs, # get_document_cls will return the most recently defined class with that name. assert dcls3 == cls4 ## Instruction: Make sure no crashes happen when no namespaces are set ## Code After: import mock from prf.tests.prf_testcase import PrfTestCase from prf.mongodb import get_document_cls, connect_dataset_aliases class TestMongoDB(PrfTestCase): def setUp(self): super(TestMongoDB, self).setUp() self.drop_databases() self.unload_documents() def test_get_document_cls(self): cls = self.create_collection('default', 'col1') cls2 = self.create_collection('prf-test2', 'col2') cls3 = self.create_collection('default', 'col3') cls4 = self.create_collection('prf-test2', 'col3') dcls = get_document_cls('col1') dcls2 = get_document_cls('col2') dcls3 = get_document_cls('col3') assert cls == dcls assert cls2 == dcls2 assert dcls2._meta['db_alias'] == 'prf-test2' # This is broken behavior with collision on collection names across dbs, # get_document_cls will return the most recently defined class with that name. assert dcls3 == cls4 @mock.patch('prf.mongodb.mongo_connect') def test_connect_dataset_aliases_missing_config(self, connect): del self.conf.registry.settings['dataset.namespaces'] connect_dataset_aliases(self.conf, self.conf.prf_settings()) connect.assert_not_called()
... import mock from prf.tests.prf_testcase import PrfTestCase from prf.mongodb import get_document_cls, connect_dataset_aliases class TestMongoDB(PrfTestCase): ... # This is broken behavior with collision on collection names across dbs, # get_document_cls will return the most recently defined class with that name. assert dcls3 == cls4 @mock.patch('prf.mongodb.mongo_connect') def test_connect_dataset_aliases_missing_config(self, connect): del self.conf.registry.settings['dataset.namespaces'] connect_dataset_aliases(self.conf, self.conf.prf_settings()) connect.assert_not_called() ...
59295102a8b5cdcfa107ceaf47b6a609aec65195
trunk/MutabilityDetector/trunk/MutabilityDetector/src/main/java/org/mutabilitydetector/checkers/PublishedNonFinalFieldChecker.java
trunk/MutabilityDetector/trunk/MutabilityDetector/src/main/java/org/mutabilitydetector/checkers/PublishedNonFinalFieldChecker.java
/* * Mutability Detector * * Copyright 2009 Graham Allan * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.mutabilitydetector.checkers; import static org.mutabilitydetector.checkers.AccessModifierQuery.method; import org.mutabilitydetector.MutabilityReason; import org.objectweb.asm.FieldVisitor; public class PublishedNonFinalFieldChecker extends AbstractMutabilityChecker { @Override public FieldVisitor visitField(int access, String name, String desc, String signature, Object value) { if (method(access).isNotPrivate()){ if (!method(access).isFinal()) { addResult("Field [" + name + "] is visible outwith this class, and is not declared final.", null, MutabilityReason.PUBLISHED_NON_FINAL_FIELD); } } return super.visitField(access, name, desc, signature, value); } }
/* * Mutability Detector * * Copyright 2009 Graham Allan * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.mutabilitydetector.checkers; import static org.mutabilitydetector.checkers.AccessModifierQuery.field; import org.mutabilitydetector.MutabilityReason; import org.objectweb.asm.FieldVisitor; public class PublishedNonFinalFieldChecker extends AbstractMutabilityChecker { @Override public FieldVisitor visitField(int access, String name, String desc, String signature, Object value) { if (field(access).isNotPrivate() && field(access).isNotFinal()) { addResult("Field [" + name + "] is visible outwith this class, and is not declared final.", null, MutabilityReason.PUBLISHED_NON_FINAL_FIELD); } return super.visitField(access, name, desc, signature, value); } }
Make the access check code a bit more readable.
Make the access check code a bit more readable. git-svn-id: ed609ce04ec9e3c0bc25e071e87814dd6d976548@383 c7a0535c-eda6-11de-83d8-6d5adf01d787
Java
apache-2.0
MutabilityDetector/MutabilityDetector,MutabilityDetector/MutabilityDetector
java
## Code Before: /* * Mutability Detector * * Copyright 2009 Graham Allan * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.mutabilitydetector.checkers; import static org.mutabilitydetector.checkers.AccessModifierQuery.method; import org.mutabilitydetector.MutabilityReason; import org.objectweb.asm.FieldVisitor; public class PublishedNonFinalFieldChecker extends AbstractMutabilityChecker { @Override public FieldVisitor visitField(int access, String name, String desc, String signature, Object value) { if (method(access).isNotPrivate()){ if (!method(access).isFinal()) { addResult("Field [" + name + "] is visible outwith this class, and is not declared final.", null, MutabilityReason.PUBLISHED_NON_FINAL_FIELD); } } return super.visitField(access, name, desc, signature, value); } } ## Instruction: Make the access check code a bit more readable. git-svn-id: ed609ce04ec9e3c0bc25e071e87814dd6d976548@383 c7a0535c-eda6-11de-83d8-6d5adf01d787 ## Code After: /* * Mutability Detector * * Copyright 2009 Graham Allan * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.mutabilitydetector.checkers; import static org.mutabilitydetector.checkers.AccessModifierQuery.field; import org.mutabilitydetector.MutabilityReason; import org.objectweb.asm.FieldVisitor; public class PublishedNonFinalFieldChecker extends AbstractMutabilityChecker { @Override public FieldVisitor visitField(int access, String name, String desc, String signature, Object value) { if (field(access).isNotPrivate() && field(access).isNotFinal()) { addResult("Field [" + name + "] is visible outwith this class, and is not declared final.", null, MutabilityReason.PUBLISHED_NON_FINAL_FIELD); } return super.visitField(access, name, desc, signature, value); } }
# ... existing code ... package org.mutabilitydetector.checkers; import static org.mutabilitydetector.checkers.AccessModifierQuery.field; import org.mutabilitydetector.MutabilityReason; import org.objectweb.asm.FieldVisitor; # ... modified code ... @Override public FieldVisitor visitField(int access, String name, String desc, String signature, Object value) { if (field(access).isNotPrivate() && field(access).isNotFinal()) { addResult("Field [" + name + "] is visible outwith this class, and is not declared final.", null, MutabilityReason.PUBLISHED_NON_FINAL_FIELD); } return super.visitField(access, name, desc, signature, value); } # ... rest of the code ...
e247e0bcdae8efd2485195ab6253eebe87161dd7
settings.gradle.kts
settings.gradle.kts
// Require Java 10 or higher val javaVersion = JavaVersion.current() require(javaVersion.isJava10Compatible) { "The JUnit 5 build requires Java 10 or higher. Currently executing with Java ${javaVersion.majorVersion}." } rootProject.name = "junit5" include("documentation") include("junit-jupiter-api") include("junit-jupiter-engine") include("junit-jupiter-migrationsupport") include("junit-jupiter-params") include("junit-platform-commons") include("junit-platform-commons-java-9") include("junit-platform-console") include("junit-platform-console-standalone") include("junit-platform-engine") include("junit-platform-launcher") include("junit-platform-runner") include("junit-platform-suite-api") include("junit-platform-surefire-provider") include("junit-vintage-engine") include("platform-tests") include("platform-tooling-support-tests") include("junit-bom") // check that every subproject has a custom build file // based on the project name rootProject.children.forEach { project -> project.buildFileName = "${project.name}.gradle" require(project.buildFile.isFile) } enableFeaturePreview("STABLE_PUBLISHING")
// Require Java 10 or higher val javaVersion = JavaVersion.current() require(javaVersion.isJava10Compatible) { "The JUnit 5 build requires Java 10 or higher. Currently executing with Java ${javaVersion.majorVersion}." } rootProject.name = "junit5" include("documentation") include("junit-jupiter-api") include("junit-jupiter-engine") include("junit-jupiter-migrationsupport") include("junit-jupiter-params") include("junit-platform-commons") include("junit-platform-commons-java-9") include("junit-platform-console") include("junit-platform-console-standalone") include("junit-platform-engine") include("junit-platform-launcher") include("junit-platform-runner") include("junit-platform-suite-api") include("junit-platform-surefire-provider") include("junit-vintage-engine") include("platform-tests") include("platform-tooling-support-tests") include("junit-bom") // check that every subproject has a custom build file // based on the project name rootProject.children.forEach { project -> project.buildFileName = "${project.name}.gradle" if (!project.buildFile.isFile) { project.buildFileName = "${project.name}.gradle.kts" } require(project.buildFile.isFile) { "${project.buildFile} must exist" } } enableFeaturePreview("STABLE_PUBLISHING")
Enable use of Kotlin DSL for subproject build scripts
Enable use of Kotlin DSL for subproject build scripts
Kotlin
epl-1.0
sbrannen/junit-lambda,junit-team/junit-lambda
kotlin
## Code Before: // Require Java 10 or higher val javaVersion = JavaVersion.current() require(javaVersion.isJava10Compatible) { "The JUnit 5 build requires Java 10 or higher. Currently executing with Java ${javaVersion.majorVersion}." } rootProject.name = "junit5" include("documentation") include("junit-jupiter-api") include("junit-jupiter-engine") include("junit-jupiter-migrationsupport") include("junit-jupiter-params") include("junit-platform-commons") include("junit-platform-commons-java-9") include("junit-platform-console") include("junit-platform-console-standalone") include("junit-platform-engine") include("junit-platform-launcher") include("junit-platform-runner") include("junit-platform-suite-api") include("junit-platform-surefire-provider") include("junit-vintage-engine") include("platform-tests") include("platform-tooling-support-tests") include("junit-bom") // check that every subproject has a custom build file // based on the project name rootProject.children.forEach { project -> project.buildFileName = "${project.name}.gradle" require(project.buildFile.isFile) } enableFeaturePreview("STABLE_PUBLISHING") ## Instruction: Enable use of Kotlin DSL for subproject build scripts ## Code After: // Require Java 10 or higher val javaVersion = JavaVersion.current() require(javaVersion.isJava10Compatible) { "The JUnit 5 build requires Java 10 or higher. Currently executing with Java ${javaVersion.majorVersion}." } rootProject.name = "junit5" include("documentation") include("junit-jupiter-api") include("junit-jupiter-engine") include("junit-jupiter-migrationsupport") include("junit-jupiter-params") include("junit-platform-commons") include("junit-platform-commons-java-9") include("junit-platform-console") include("junit-platform-console-standalone") include("junit-platform-engine") include("junit-platform-launcher") include("junit-platform-runner") include("junit-platform-suite-api") include("junit-platform-surefire-provider") include("junit-vintage-engine") include("platform-tests") include("platform-tooling-support-tests") include("junit-bom") // check that every subproject has a custom build file // based on the project name rootProject.children.forEach { project -> project.buildFileName = "${project.name}.gradle" if (!project.buildFile.isFile) { project.buildFileName = "${project.name}.gradle.kts" } require(project.buildFile.isFile) { "${project.buildFile} must exist" } } enableFeaturePreview("STABLE_PUBLISHING")
# ... existing code ... // based on the project name rootProject.children.forEach { project -> project.buildFileName = "${project.name}.gradle" if (!project.buildFile.isFile) { project.buildFileName = "${project.name}.gradle.kts" } require(project.buildFile.isFile) { "${project.buildFile} must exist" } } enableFeaturePreview("STABLE_PUBLISHING") # ... rest of the code ...
316a67256e845aa84f6551edf6cc3c117acd2ff2
src/main/java/module-info.java
src/main/java/module-info.java
/** * See {@link org.cojen.tupl.Database} to get started with Tupl. */ module org.cojen.tupl { exports org.cojen.tupl; exports org.cojen.tupl.ext; exports org.cojen.tupl.io; exports org.cojen.tupl.repl; exports org.cojen.tupl.tools; exports org.cojen.tupl.util; requires transitive java.logging; requires transitive jdk.unsupported; requires transitive com.sun.jna; requires transitive com.sun.jna.platform; requires transitive org.cojen.maker; requires static java.management; requires static org.lz4.java; requires static org.slf4j; }
/** * See {@link org.cojen.tupl.Database} to get started with Tupl. */ module org.cojen.tupl { exports org.cojen.tupl; exports org.cojen.tupl.ext; exports org.cojen.tupl.io; exports org.cojen.tupl.repl; exports org.cojen.tupl.tools; exports org.cojen.tupl.util; requires jdk.unsupported; requires com.sun.jna; requires com.sun.jna.platform; requires org.cojen.maker; // Could be transitive because it's part of the public API, but only in EventListener. // I doubt that the java.logging module is used much. requires static java.logging; requires static java.management; requires static org.lz4.java; requires static org.slf4j; }
Remove transitive modifier from dependencies.
Remove transitive modifier from dependencies.
Java
agpl-3.0
cojen/Tupl
java
## Code Before: /** * See {@link org.cojen.tupl.Database} to get started with Tupl. */ module org.cojen.tupl { exports org.cojen.tupl; exports org.cojen.tupl.ext; exports org.cojen.tupl.io; exports org.cojen.tupl.repl; exports org.cojen.tupl.tools; exports org.cojen.tupl.util; requires transitive java.logging; requires transitive jdk.unsupported; requires transitive com.sun.jna; requires transitive com.sun.jna.platform; requires transitive org.cojen.maker; requires static java.management; requires static org.lz4.java; requires static org.slf4j; } ## Instruction: Remove transitive modifier from dependencies. ## Code After: /** * See {@link org.cojen.tupl.Database} to get started with Tupl. */ module org.cojen.tupl { exports org.cojen.tupl; exports org.cojen.tupl.ext; exports org.cojen.tupl.io; exports org.cojen.tupl.repl; exports org.cojen.tupl.tools; exports org.cojen.tupl.util; requires jdk.unsupported; requires com.sun.jna; requires com.sun.jna.platform; requires org.cojen.maker; // Could be transitive because it's part of the public API, but only in EventListener. // I doubt that the java.logging module is used much. requires static java.logging; requires static java.management; requires static org.lz4.java; requires static org.slf4j; }
# ... existing code ... exports org.cojen.tupl.tools; exports org.cojen.tupl.util; requires jdk.unsupported; requires com.sun.jna; requires com.sun.jna.platform; requires org.cojen.maker; // Could be transitive because it's part of the public API, but only in EventListener. // I doubt that the java.logging module is used much. requires static java.logging; requires static java.management; # ... rest of the code ...
877bfcfaf592e63916333fd644bb8f30b673f35d
lib/sanitizer_common/sanitizer_placement_new.h
lib/sanitizer_common/sanitizer_placement_new.h
//===-- sanitizer_placement_new.h -------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file is shared between AddressSanitizer and ThreadSanitizer // run-time libraries. // // The file provides 'placement new'. // Do not include it into header files, only into source files. //===----------------------------------------------------------------------===// #ifndef SANITIZER_PLACEMENT_NEW_H #define SANITIZER_PLACEMENT_NEW_H #include "sanitizer_internal_defs.h" #if __WORDSIZE == 64 inline void *operator new(__sanitizer::uptr sz, void *p) { return p; } #else inline void *operator new(__sanitizer::u32 sz, void *p) { return p; } #endif #endif // SANITIZER_PLACEMENT_NEW_H
//===-- sanitizer_placement_new.h -------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file is shared between AddressSanitizer and ThreadSanitizer // run-time libraries. // // The file provides 'placement new'. // Do not include it into header files, only into source files. //===----------------------------------------------------------------------===// #ifndef SANITIZER_PLACEMENT_NEW_H #define SANITIZER_PLACEMENT_NEW_H #include "sanitizer_internal_defs.h" namespace __sanitizer { #if (__WORDSIZE == 64) || defined(__APPLE__) typedef __sanitizer::uptr operator_new_ptr_type; #else typedef __sanitizer::u32 operator_new_ptr_type; #endif } // namespace __sanitizer inline void *operator new(operator_new_ptr_type sz, void *p) { return p; } #endif // SANITIZER_PLACEMENT_NEW_H
Fix type for placement new on 32-bit Mac
[Sanitizer] Fix type for placement new on 32-bit Mac git-svn-id: c199f293c43da69278bea8e88f92242bf3aa95f7@158524 91177308-0d34-0410-b5e6-96231b3b80d8
C
apache-2.0
llvm-mirror/compiler-rt,llvm-mirror/compiler-rt,llvm-mirror/compiler-rt,llvm-mirror/compiler-rt,llvm-mirror/compiler-rt
c
## Code Before: //===-- sanitizer_placement_new.h -------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file is shared between AddressSanitizer and ThreadSanitizer // run-time libraries. // // The file provides 'placement new'. // Do not include it into header files, only into source files. //===----------------------------------------------------------------------===// #ifndef SANITIZER_PLACEMENT_NEW_H #define SANITIZER_PLACEMENT_NEW_H #include "sanitizer_internal_defs.h" #if __WORDSIZE == 64 inline void *operator new(__sanitizer::uptr sz, void *p) { return p; } #else inline void *operator new(__sanitizer::u32 sz, void *p) { return p; } #endif #endif // SANITIZER_PLACEMENT_NEW_H ## Instruction: [Sanitizer] Fix type for placement new on 32-bit Mac git-svn-id: c199f293c43da69278bea8e88f92242bf3aa95f7@158524 91177308-0d34-0410-b5e6-96231b3b80d8 ## Code After: //===-- sanitizer_placement_new.h -------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file is shared between AddressSanitizer and ThreadSanitizer // run-time libraries. // // The file provides 'placement new'. // Do not include it into header files, only into source files. //===----------------------------------------------------------------------===// #ifndef SANITIZER_PLACEMENT_NEW_H #define SANITIZER_PLACEMENT_NEW_H #include "sanitizer_internal_defs.h" namespace __sanitizer { #if (__WORDSIZE == 64) || defined(__APPLE__) typedef __sanitizer::uptr operator_new_ptr_type; #else typedef __sanitizer::u32 operator_new_ptr_type; #endif } // namespace __sanitizer inline void *operator new(operator_new_ptr_type sz, void *p) { return p; } #endif // SANITIZER_PLACEMENT_NEW_H
// ... existing code ... #include "sanitizer_internal_defs.h" namespace __sanitizer { #if (__WORDSIZE == 64) || defined(__APPLE__) typedef __sanitizer::uptr operator_new_ptr_type; #else typedef __sanitizer::u32 operator_new_ptr_type; #endif } // namespace __sanitizer inline void *operator new(operator_new_ptr_type sz, void *p) { return p; } #endif // SANITIZER_PLACEMENT_NEW_H // ... rest of the code ...
845b4fe3bf708d0434cb64d37a212bc0fd6b5ac6
ci/testsettings.py
ci/testsettings.py
DATABASES = { "default": { "ENGINE": "django.db.backends.sqlite3", "NAME": "test.db", } } # SECRET_KEY = ''
DATABASES = { "default": { "ENGINE": "django.db.backends.sqlite3", "NAME": "test.db", } } INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django_cas_ng', 'pucas', ) # SECRET_KEY = ''
Add installed apps configuration to test settings
Add installed apps configuration to test settings
Python
apache-2.0
Princeton-CDH/django-pucas,Princeton-CDH/django-pucas
python
## Code Before: DATABASES = { "default": { "ENGINE": "django.db.backends.sqlite3", "NAME": "test.db", } } # SECRET_KEY = '' ## Instruction: Add installed apps configuration to test settings ## Code After: DATABASES = { "default": { "ENGINE": "django.db.backends.sqlite3", "NAME": "test.db", } } INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django_cas_ng', 'pucas', ) # SECRET_KEY = ''
... } } INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django_cas_ng', 'pucas', ) # SECRET_KEY = '' ...
6c98f48acd3cc91faeee2d6e24784275eedbd1ea
saw-remote-api/python/tests/saw/test_basic_java.py
saw-remote-api/python/tests/saw/test_basic_java.py
import unittest from pathlib import Path import saw_client as saw from saw_client.jvm import Contract, java_int, cryptol class Add(Contract): def __init__(self) -> None: super().__init__() def specification(self) -> None: x = self.fresh_var(java_int, "x") y = self.fresh_var(java_int, "y") self.execute_func(x, y) self.returns(cryptol("(+)")(x,y)) class AddTest(unittest.TestCase): def test_add(self): saw.connect(reset_server=True) if __name__ == "__main__": saw.view(saw.LogResults()) cls = saw.jvm_load_class("Add") result = saw.jvm_verify(cls, 'add', Add()) self.assertIs(result.is_success(), True) if __name__ == "__main__": unittest.main()
import unittest from pathlib import Path import saw_client as saw from saw_client.jvm import Contract, java_int, cryptol class Add(Contract): def __init__(self) -> None: super().__init__() def specification(self) -> None: x = self.fresh_var(java_int, "x") y = self.fresh_var(java_int, "y") self.execute_func(x, y) self.returns(cryptol("(+)")(x,y)) class Double(Contract): def __init__(self) -> None: super().__init__() def specification(self) -> None: x = self.fresh_var(java_int, "x") self.execute_func(x) self.returns(cryptol("(+)")(x,x)) class AddTest(unittest.TestCase): def test_add(self): saw.connect(reset_server=True) if __name__ == "__main__": saw.view(saw.LogResults()) cls = saw.jvm_load_class("Add") add_result1 = saw.jvm_verify(cls, 'add', Add()) self.assertIs(add_result1.is_success(), True) add_result2 = saw.jvm_assume(cls, 'add', Add()) self.assertIs(add_result2.is_success(), True) dbl_result1 = saw.jvm_verify(cls, 'dbl', Double(), lemmas=[add_result1]) self.assertIs(dbl_result1.is_success(), True) dbl_result2 = saw.jvm_verify(cls, 'dbl', Double(), lemmas=[add_result2]) self.assertIs(dbl_result2.is_success(), True) if __name__ == "__main__": unittest.main()
Test assumption, composition for RPC Java proofs
Test assumption, composition for RPC Java proofs
Python
bsd-3-clause
GaloisInc/saw-script,GaloisInc/saw-script,GaloisInc/saw-script,GaloisInc/saw-script,GaloisInc/saw-script
python
## Code Before: import unittest from pathlib import Path import saw_client as saw from saw_client.jvm import Contract, java_int, cryptol class Add(Contract): def __init__(self) -> None: super().__init__() def specification(self) -> None: x = self.fresh_var(java_int, "x") y = self.fresh_var(java_int, "y") self.execute_func(x, y) self.returns(cryptol("(+)")(x,y)) class AddTest(unittest.TestCase): def test_add(self): saw.connect(reset_server=True) if __name__ == "__main__": saw.view(saw.LogResults()) cls = saw.jvm_load_class("Add") result = saw.jvm_verify(cls, 'add', Add()) self.assertIs(result.is_success(), True) if __name__ == "__main__": unittest.main() ## Instruction: Test assumption, composition for RPC Java proofs ## Code After: import unittest from pathlib import Path import saw_client as saw from saw_client.jvm import Contract, java_int, cryptol class Add(Contract): def __init__(self) -> None: super().__init__() def specification(self) -> None: x = self.fresh_var(java_int, "x") y = self.fresh_var(java_int, "y") self.execute_func(x, y) self.returns(cryptol("(+)")(x,y)) class Double(Contract): def __init__(self) -> None: super().__init__() def specification(self) -> None: x = self.fresh_var(java_int, "x") self.execute_func(x) self.returns(cryptol("(+)")(x,x)) class AddTest(unittest.TestCase): def test_add(self): saw.connect(reset_server=True) if __name__ == "__main__": saw.view(saw.LogResults()) cls = saw.jvm_load_class("Add") add_result1 = saw.jvm_verify(cls, 'add', Add()) self.assertIs(add_result1.is_success(), True) add_result2 = saw.jvm_assume(cls, 'add', Add()) self.assertIs(add_result2.is_success(), True) dbl_result1 = saw.jvm_verify(cls, 'dbl', Double(), lemmas=[add_result1]) self.assertIs(dbl_result1.is_success(), True) dbl_result2 = saw.jvm_verify(cls, 'dbl', Double(), lemmas=[add_result2]) self.assertIs(dbl_result2.is_success(), True) if __name__ == "__main__": unittest.main()
# ... existing code ... self.returns(cryptol("(+)")(x,y)) class Double(Contract): def __init__(self) -> None: super().__init__() def specification(self) -> None: x = self.fresh_var(java_int, "x") self.execute_func(x) self.returns(cryptol("(+)")(x,x)) class AddTest(unittest.TestCase): def test_add(self): saw.connect(reset_server=True) # ... modified code ... cls = saw.jvm_load_class("Add") add_result1 = saw.jvm_verify(cls, 'add', Add()) self.assertIs(add_result1.is_success(), True) add_result2 = saw.jvm_assume(cls, 'add', Add()) self.assertIs(add_result2.is_success(), True) dbl_result1 = saw.jvm_verify(cls, 'dbl', Double(), lemmas=[add_result1]) self.assertIs(dbl_result1.is_success(), True) dbl_result2 = saw.jvm_verify(cls, 'dbl', Double(), lemmas=[add_result2]) self.assertIs(dbl_result2.is_success(), True) if __name__ == "__main__": # ... rest of the code ...
8e4f09592d6b4d681a62026b56dca29abeed88d7
backend/scripts/ddirdenorm.py
backend/scripts/ddirdenorm.py
import rethinkdb as r import optparse if __name__ == "__main__": parser = optparse.OptionParser() parser.add_option("-p", "--port", dest="port", help="rethinkdb port", default=30815) (options, args) = parser.parse_args() conn = r.connect('localhost', int(options.port), db='materialscommons') selection = list(r.table('datadirs').run(conn)) for datadir in selection: print "Updating datadir %s" % (datadir['name']) ddir = {} ddir['id'] = datadir['id'] ddir['name'] = datadir['name'] ddir['owner'] = datadir['owner'] ddir['birthtime'] = datadir['birthtime'] ddir['datafiles'] = [] for dfid in datadir['datafiles']: datafile = r.table('datafiles').get(dfid).run(conn) df = {} df['id'] = datafile['id'] df['name'] = datafile['name'] df['owner'] = datafile['owner'] df['birthtime'] = datafile['birthtime'] df['size'] = datafile['size'] df['checksum'] = datafile['checksum'] ddir['datafiles'].append(df) r.table('datadirs_denorm').insert(ddir).run(conn)
import rethinkdb as r import optparse if __name__ == "__main__": parser = optparse.OptionParser() parser.add_option("-p", "--port", dest="port", help="rethinkdb port", default=30815) (options, args) = parser.parse_args() conn = r.connect('localhost', int(options.port), db='materialscommons') selection = list(r.table('datadirs').run(conn)) for datadir in selection: print "Updating datadir %s" % (datadir['name']) ddir = {} ddir['id'] = datadir['id'] ddir['name'] = datadir['name'] ddir['owner'] = datadir['owner'] ddir['birthtime'] = datadir['birthtime'] ddir['datafiles'] = [] for dfid in datadir['datafiles']: datafile = r.table('datafiles').get(dfid).run(conn) if datafile is None: continue df = {} df['id'] = datafile['id'] df['name'] = datafile['name'] df['owner'] = datafile['owner'] df['birthtime'] = datafile['birthtime'] df['size'] = datafile['size'] df['checksum'] = datafile['checksum'] ddir['datafiles'].append(df) r.table('datadirs_denorm').insert(ddir).run(conn)
Handle non-existent files in the database.
Handle non-existent files in the database.
Python
mit
materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org
python
## Code Before: import rethinkdb as r import optparse if __name__ == "__main__": parser = optparse.OptionParser() parser.add_option("-p", "--port", dest="port", help="rethinkdb port", default=30815) (options, args) = parser.parse_args() conn = r.connect('localhost', int(options.port), db='materialscommons') selection = list(r.table('datadirs').run(conn)) for datadir in selection: print "Updating datadir %s" % (datadir['name']) ddir = {} ddir['id'] = datadir['id'] ddir['name'] = datadir['name'] ddir['owner'] = datadir['owner'] ddir['birthtime'] = datadir['birthtime'] ddir['datafiles'] = [] for dfid in datadir['datafiles']: datafile = r.table('datafiles').get(dfid).run(conn) df = {} df['id'] = datafile['id'] df['name'] = datafile['name'] df['owner'] = datafile['owner'] df['birthtime'] = datafile['birthtime'] df['size'] = datafile['size'] df['checksum'] = datafile['checksum'] ddir['datafiles'].append(df) r.table('datadirs_denorm').insert(ddir).run(conn) ## Instruction: Handle non-existent files in the database. ## Code After: import rethinkdb as r import optparse if __name__ == "__main__": parser = optparse.OptionParser() parser.add_option("-p", "--port", dest="port", help="rethinkdb port", default=30815) (options, args) = parser.parse_args() conn = r.connect('localhost', int(options.port), db='materialscommons') selection = list(r.table('datadirs').run(conn)) for datadir in selection: print "Updating datadir %s" % (datadir['name']) ddir = {} ddir['id'] = datadir['id'] ddir['name'] = datadir['name'] ddir['owner'] = datadir['owner'] ddir['birthtime'] = datadir['birthtime'] ddir['datafiles'] = [] for dfid in datadir['datafiles']: datafile = r.table('datafiles').get(dfid).run(conn) if datafile is None: continue df = {} df['id'] = datafile['id'] df['name'] = datafile['name'] df['owner'] = datafile['owner'] df['birthtime'] = datafile['birthtime'] df['size'] = datafile['size'] df['checksum'] = datafile['checksum'] ddir['datafiles'].append(df) r.table('datadirs_denorm').insert(ddir).run(conn)
... ddir['datafiles'] = [] for dfid in datadir['datafiles']: datafile = r.table('datafiles').get(dfid).run(conn) if datafile is None: continue df = {} df['id'] = datafile['id'] df['name'] = datafile['name'] ...
126b631e22915e43dc41a6a62e6d29c88d9afc19
test/test_parser_empty.c
test/test_parser_empty.c
void empty_success(void **state) { grammar_t *grammar = grammar_init( non_terminal("Start"), rule_init("Start", empty()), 1); parse_t *result = parse("hello", grammar); assert_non_null(result); assert_int_equal(result->length, 0); assert_int_equal(result->n_children, 0); }
void empty_success(void **state) { grammar_t *grammar = grammar_init( non_terminal("Start"), rule_init("Start", empty()), 1); parse_result_t *result = parse("hello", grammar); assert_non_null(result); parse_t *suc = result->data.result; assert_int_equal(suc->length, 0); assert_int_equal(suc->n_children, 0); }
Use new API on empty tests
Use new API on empty tests
C
mit
Baltoli/peggo,Baltoli/peggo
c
## Code Before: void empty_success(void **state) { grammar_t *grammar = grammar_init( non_terminal("Start"), rule_init("Start", empty()), 1); parse_t *result = parse("hello", grammar); assert_non_null(result); assert_int_equal(result->length, 0); assert_int_equal(result->n_children, 0); } ## Instruction: Use new API on empty tests ## Code After: void empty_success(void **state) { grammar_t *grammar = grammar_init( non_terminal("Start"), rule_init("Start", empty()), 1); parse_result_t *result = parse("hello", grammar); assert_non_null(result); parse_t *suc = result->data.result; assert_int_equal(suc->length, 0); assert_int_equal(suc->n_children, 0); }
# ... existing code ... non_terminal("Start"), rule_init("Start", empty()), 1); parse_result_t *result = parse("hello", grammar); assert_non_null(result); parse_t *suc = result->data.result; assert_int_equal(suc->length, 0); assert_int_equal(suc->n_children, 0); } # ... rest of the code ...
b1adfacff3b7c319ae148e79807d371ded934a5c
tx_salaries/management/commands/generate_transformer_hash.py
tx_salaries/management/commands/generate_transformer_hash.py
from django.core.management.base import BaseCommand from ...utils import transformer class Command(BaseCommand): def handle(self, filename, *args, **kwargs): reader = transformer.convert_to_csv_reader(filename) labels = reader.next() print transformer.generate_key(labels)
from django.core.management.base import BaseCommand from ...utils import transformer class Command(BaseCommand): def handle(self, filename, *args, **kwargs): reader = transformer.convert_to_csv_reader(filename) labels = reader.next() transformer_key = transformer.generate_key(labels) if transformer_key in transformer.TRANSFORMERS.keys(): print transformer_key + ' (exists)' else: print transformer_key
Add message if transformer_hash already exists
Add message if transformer_hash already exists
Python
apache-2.0
texastribune/tx_salaries,texastribune/tx_salaries
python
## Code Before: from django.core.management.base import BaseCommand from ...utils import transformer class Command(BaseCommand): def handle(self, filename, *args, **kwargs): reader = transformer.convert_to_csv_reader(filename) labels = reader.next() print transformer.generate_key(labels) ## Instruction: Add message if transformer_hash already exists ## Code After: from django.core.management.base import BaseCommand from ...utils import transformer class Command(BaseCommand): def handle(self, filename, *args, **kwargs): reader = transformer.convert_to_csv_reader(filename) labels = reader.next() transformer_key = transformer.generate_key(labels) if transformer_key in transformer.TRANSFORMERS.keys(): print transformer_key + ' (exists)' else: print transformer_key
... def handle(self, filename, *args, **kwargs): reader = transformer.convert_to_csv_reader(filename) labels = reader.next() transformer_key = transformer.generate_key(labels) if transformer_key in transformer.TRANSFORMERS.keys(): print transformer_key + ' (exists)' else: print transformer_key ...
a01e88ded4e7344bcc5249f5f3be67cc2a06a5a0
setup.py
setup.py
from setuptools import setup setup( zip_safe=True, name='cloudify-vcloud-plugin', version='1.2', packages=[ 'vcloud_plugin_common', 'server_plugin', 'network_plugin' ], license='LICENSE', description='Cloudify plugin for vmWare vCloud infrastructure.', install_requires=[ 'cloudify-plugins-common>=3.2', 'pyvcloud==12', 'requests==2.4.3', 'IPy==0.81' ] )
from setuptools import setup setup( zip_safe=True, name='cloudify-vcloud-plugin', version='1.2', packages=[ 'vcloud_plugin_common', 'server_plugin', 'network_plugin' ], license='LICENSE', description='Cloudify plugin for vmWare vCloud infrastructure.', install_requires=[ 'cloudify-plugins-common>=3.2', 'pyvcloud==12', 'requests==2.4.3', 'IPy==0.81', 'PyYAML==3.10' ] )
Add an explicit requirement on PyYAML instead of relying the fact that pyvcloud pulls it in (but won't in future versions, since it doesn't need it)
Add an explicit requirement on PyYAML instead of relying the fact that pyvcloud pulls it in (but won't in future versions, since it doesn't need it)
Python
apache-2.0
cloudify-cosmo/tosca-vcloud-plugin,denismakogon/tosca-vcloud-plugin,kemiz/tosca-vcloud-plugin,vmware/tosca-vcloud-plugin
python
## Code Before: from setuptools import setup setup( zip_safe=True, name='cloudify-vcloud-plugin', version='1.2', packages=[ 'vcloud_plugin_common', 'server_plugin', 'network_plugin' ], license='LICENSE', description='Cloudify plugin for vmWare vCloud infrastructure.', install_requires=[ 'cloudify-plugins-common>=3.2', 'pyvcloud==12', 'requests==2.4.3', 'IPy==0.81' ] ) ## Instruction: Add an explicit requirement on PyYAML instead of relying the fact that pyvcloud pulls it in (but won't in future versions, since it doesn't need it) ## Code After: from setuptools import setup setup( zip_safe=True, name='cloudify-vcloud-plugin', version='1.2', packages=[ 'vcloud_plugin_common', 'server_plugin', 'network_plugin' ], license='LICENSE', description='Cloudify plugin for vmWare vCloud infrastructure.', install_requires=[ 'cloudify-plugins-common>=3.2', 'pyvcloud==12', 'requests==2.4.3', 'IPy==0.81', 'PyYAML==3.10' ] )
# ... existing code ... 'cloudify-plugins-common>=3.2', 'pyvcloud==12', 'requests==2.4.3', 'IPy==0.81', 'PyYAML==3.10' ] ) # ... rest of the code ...
db5f4d9325d1f1c67160c925b83e8a4574d4cb9a
portal/factories/celery.py
portal/factories/celery.py
from __future__ import absolute_import from celery import Celery __celery = None def create_celery(app): global __celery if __celery: return __celery celery = Celery( app.import_name, broker=app.config['CELERY_BROKER_URL'] ) celery.conf.update(app.config) TaskBase = celery.Task class ContextTask(TaskBase): abstract = True def __call__(self, *args, **kwargs): with app.app_context(): return TaskBase.__call__(self, *args, **kwargs) celery.Task = ContextTask __celery = celery return __celery
from __future__ import absolute_import from celery import Celery from ..extensions import db __celery = None def create_celery(app): global __celery if __celery: return __celery celery = Celery( app.import_name, broker=app.config['CELERY_BROKER_URL'] ) celery.conf.update(app.config) TaskBase = celery.Task class ContextTask(TaskBase): abstract = True def __call__(self, *args, **kwargs): with app.app_context(): db.session = db.create_scoped_session() try: response = TaskBase.__call__(self, *args, **kwargs) finally: db.session.remove() return response celery.Task = ContextTask __celery = celery return __celery
Remove DB session after task
Remove DB session after task
Python
bsd-3-clause
uwcirg/true_nth_usa_portal,uwcirg/true_nth_usa_portal,uwcirg/true_nth_usa_portal,uwcirg/true_nth_usa_portal
python
## Code Before: from __future__ import absolute_import from celery import Celery __celery = None def create_celery(app): global __celery if __celery: return __celery celery = Celery( app.import_name, broker=app.config['CELERY_BROKER_URL'] ) celery.conf.update(app.config) TaskBase = celery.Task class ContextTask(TaskBase): abstract = True def __call__(self, *args, **kwargs): with app.app_context(): return TaskBase.__call__(self, *args, **kwargs) celery.Task = ContextTask __celery = celery return __celery ## Instruction: Remove DB session after task ## Code After: from __future__ import absolute_import from celery import Celery from ..extensions import db __celery = None def create_celery(app): global __celery if __celery: return __celery celery = Celery( app.import_name, broker=app.config['CELERY_BROKER_URL'] ) celery.conf.update(app.config) TaskBase = celery.Task class ContextTask(TaskBase): abstract = True def __call__(self, *args, **kwargs): with app.app_context(): db.session = db.create_scoped_session() try: response = TaskBase.__call__(self, *args, **kwargs) finally: db.session.remove() return response celery.Task = ContextTask __celery = celery return __celery
# ... existing code ... from __future__ import absolute_import from celery import Celery from ..extensions import db __celery = None # ... modified code ... def __call__(self, *args, **kwargs): with app.app_context(): db.session = db.create_scoped_session() try: response = TaskBase.__call__(self, *args, **kwargs) finally: db.session.remove() return response celery.Task = ContextTask __celery = celery # ... rest of the code ...
7a651446413b2391284fd13f7df9b9c6ae1b78a7
InvenTree/key.py
InvenTree/key.py
import random import string import os fn = 'secret_key.txt' def generate_key(): return ''.join(random.choices(string.digits + string.ascii_letters + string.punctuation, k=50)) if __name__ == '__main__': # Ensure key file is placed in same directory as this script path = os.path.dirname(os.path.realpath(__file__)) key_file = os.path.join(path, fn) with open(key_file, 'w') as key: key.write(generate_key()) print('Generated SECRET_KEY to {f}'.format(f=key_file))
import random import string import os fn = 'secret_key.txt' def generate_key(): options = string.digits + string.ascii_letters + string.punctuation key = ''.join([random.choice(options) for i in range(50)]) return key if __name__ == '__main__': # Ensure key file is placed in same directory as this script path = os.path.dirname(os.path.realpath(__file__)) key_file = os.path.join(path, fn) with open(key_file, 'w') as kf: kf.write(generate_key()) print('Generated SECRET_KEY to {f}'.format(f=key_file))
Use random.choice instead of random.choices
Use random.choice instead of random.choices - Allows compatibility with python3.5
Python
mit
SchrodingersGat/InvenTree,SchrodingersGat/InvenTree,inventree/InvenTree,inventree/InvenTree,inventree/InvenTree,SchrodingersGat/InvenTree,inventree/InvenTree,SchrodingersGat/InvenTree
python
## Code Before: import random import string import os fn = 'secret_key.txt' def generate_key(): return ''.join(random.choices(string.digits + string.ascii_letters + string.punctuation, k=50)) if __name__ == '__main__': # Ensure key file is placed in same directory as this script path = os.path.dirname(os.path.realpath(__file__)) key_file = os.path.join(path, fn) with open(key_file, 'w') as key: key.write(generate_key()) print('Generated SECRET_KEY to {f}'.format(f=key_file)) ## Instruction: Use random.choice instead of random.choices - Allows compatibility with python3.5 ## Code After: import random import string import os fn = 'secret_key.txt' def generate_key(): options = string.digits + string.ascii_letters + string.punctuation key = ''.join([random.choice(options) for i in range(50)]) return key if __name__ == '__main__': # Ensure key file is placed in same directory as this script path = os.path.dirname(os.path.realpath(__file__)) key_file = os.path.join(path, fn) with open(key_file, 'w') as kf: kf.write(generate_key()) print('Generated SECRET_KEY to {f}'.format(f=key_file))
# ... existing code ... fn = 'secret_key.txt' def generate_key(): options = string.digits + string.ascii_letters + string.punctuation key = ''.join([random.choice(options) for i in range(50)]) return key if __name__ == '__main__': # ... modified code ... path = os.path.dirname(os.path.realpath(__file__)) key_file = os.path.join(path, fn) with open(key_file, 'w') as kf: kf.write(generate_key()) print('Generated SECRET_KEY to {f}'.format(f=key_file)) # ... rest of the code ...
334af9371193d6ef12a02145e897843bfd603679
src/plugins/jhv-eveplugin/src/org/helioviewer/plugins/eveplugin/view/TimelinePluginPanel.java
src/plugins/jhv-eveplugin/src/org/helioviewer/plugins/eveplugin/view/TimelinePluginPanel.java
package org.helioviewer.plugins.eveplugin.view; import javax.swing.BoxLayout; import javax.swing.JPanel; import javax.swing.JTabbedPane; import org.helioviewer.plugins.eveplugin.view.linedataselector.LineDateSelectorTablePanel; public class TimelinePluginPanel extends JPanel { private static final long serialVersionUID = -2175620741820580148L; private JTabbedPane tabs; public TimelinePluginPanel() { super(); initVisualComponents(); } private void initVisualComponents() { tabs = new JTabbedPane(); tabs.addTab("Layers", new ControlsPanel()); tabs.addTab("Radio Options", new RadioOptionsPanel()); setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS)); add(tabs); add(new LineDateSelectorTablePanel()); } }
package org.helioviewer.plugins.eveplugin.view; import javax.swing.BoxLayout; import javax.swing.JPanel; import javax.swing.JTabbedPane; import org.helioviewer.plugins.eveplugin.view.linedataselector.LineDateSelectorTablePanel; public class TimelinePluginPanel extends JPanel { private static final long serialVersionUID = -2175620741820580148L; private JTabbedPane tabs; public TimelinePluginPanel() { super(); initVisualComponents(); } private void initVisualComponents() { setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS)); add(new LineDateSelectorTablePanel()); } }
Remove the old line selector panel
Remove the old line selector panel git-svn-id: 4e353c0944fe8da334633afc35765ef362dec675@4267 b4e469a2-07ce-4b26-9273-4d7d95a670c7
Java
mpl-2.0
Helioviewer-Project/JHelioviewer-SWHV,Helioviewer-Project/JHelioviewer-SWHV,Helioviewer-Project/JHelioviewer-SWHV,Helioviewer-Project/JHelioviewer-SWHV,Helioviewer-Project/JHelioviewer-SWHV
java
## Code Before: package org.helioviewer.plugins.eveplugin.view; import javax.swing.BoxLayout; import javax.swing.JPanel; import javax.swing.JTabbedPane; import org.helioviewer.plugins.eveplugin.view.linedataselector.LineDateSelectorTablePanel; public class TimelinePluginPanel extends JPanel { private static final long serialVersionUID = -2175620741820580148L; private JTabbedPane tabs; public TimelinePluginPanel() { super(); initVisualComponents(); } private void initVisualComponents() { tabs = new JTabbedPane(); tabs.addTab("Layers", new ControlsPanel()); tabs.addTab("Radio Options", new RadioOptionsPanel()); setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS)); add(tabs); add(new LineDateSelectorTablePanel()); } } ## Instruction: Remove the old line selector panel git-svn-id: 4e353c0944fe8da334633afc35765ef362dec675@4267 b4e469a2-07ce-4b26-9273-4d7d95a670c7 ## Code After: package org.helioviewer.plugins.eveplugin.view; import javax.swing.BoxLayout; import javax.swing.JPanel; import javax.swing.JTabbedPane; import org.helioviewer.plugins.eveplugin.view.linedataselector.LineDateSelectorTablePanel; public class TimelinePluginPanel extends JPanel { private static final long serialVersionUID = -2175620741820580148L; private JTabbedPane tabs; public TimelinePluginPanel() { super(); initVisualComponents(); } private void initVisualComponents() { setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS)); add(new LineDateSelectorTablePanel()); } }
# ... existing code ... } private void initVisualComponents() { setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS)); add(new LineDateSelectorTablePanel()); } } # ... rest of the code ...
397e4b3841dde6f82ad7f1d3f6458f99da69d678
px/px_install.py
px/px_install.py
import sys import shutil import os def install(src, dest): """ Copy src (file) into dest (file) and make dest executable. On trouble, prints message and exits with an error code. """ try: _install(src, dest) except Exception as e: sys.stderr.write("Installing {} failed, please retry with sudo\n".format(dest)) sys.stderr.write("Error was: {}\n".format(e.message)) exit(1) print("Created: {}".format(dest)) def _install(src, dest): """ Copy src (file) into dest (file) and make dest executable. Throws exception on trouble. """ parent = os.path.dirname(dest) if not os.path.isdir(parent): raise IOError("Destination parent is not a directory: %s" % parent) if os.path.isdir(dest): raise IOError("Destination is a directory, won't replace that: %s" % dest) # Make sure nothing's in the way try: os.remove(dest) except OSError: pass if os.path.exists(dest): raise IOError("Can't remove existing entry: %s" % dest) shutil.copyfile(src, dest) os.chmod(dest, 0755)
import sys import shutil import os def install(src, dest): """ Copy src (file) into dest (file) and make dest executable. On trouble, prints message and exits with an error code. """ try: _install(src, dest) except Exception as e: sys.stderr.write("Installing {} failed, please retry with sudo\n".format(dest)) sys.stderr.write("Error was: {}\n".format(e.message)) exit(1) print("Created: {}".format(dest)) def _install(src, dest): """ Copy src (file) into dest (file) and make dest executable. Throws exception on trouble. """ if os.path.realpath(src) == os.path.realpath(dest): # Copying a file onto itself is a no-op, never mind return parent = os.path.dirname(dest) if not os.path.isdir(parent): raise IOError("Destination parent is not a directory: %s" % parent) if os.path.isdir(dest): raise IOError("Destination is a directory, won't replace that: %s" % dest) # Make sure nothing's in the way try: os.remove(dest) except OSError: pass if os.path.exists(dest): raise IOError("Can't remove existing entry: %s" % dest) shutil.copyfile(src, dest) os.chmod(dest, 0755)
Handle installing px on top of itself
Handle installing px on top of itself
Python
mit
walles/px,walles/px
python
## Code Before: import sys import shutil import os def install(src, dest): """ Copy src (file) into dest (file) and make dest executable. On trouble, prints message and exits with an error code. """ try: _install(src, dest) except Exception as e: sys.stderr.write("Installing {} failed, please retry with sudo\n".format(dest)) sys.stderr.write("Error was: {}\n".format(e.message)) exit(1) print("Created: {}".format(dest)) def _install(src, dest): """ Copy src (file) into dest (file) and make dest executable. Throws exception on trouble. """ parent = os.path.dirname(dest) if not os.path.isdir(parent): raise IOError("Destination parent is not a directory: %s" % parent) if os.path.isdir(dest): raise IOError("Destination is a directory, won't replace that: %s" % dest) # Make sure nothing's in the way try: os.remove(dest) except OSError: pass if os.path.exists(dest): raise IOError("Can't remove existing entry: %s" % dest) shutil.copyfile(src, dest) os.chmod(dest, 0755) ## Instruction: Handle installing px on top of itself ## Code After: import sys import shutil import os def install(src, dest): """ Copy src (file) into dest (file) and make dest executable. On trouble, prints message and exits with an error code. """ try: _install(src, dest) except Exception as e: sys.stderr.write("Installing {} failed, please retry with sudo\n".format(dest)) sys.stderr.write("Error was: {}\n".format(e.message)) exit(1) print("Created: {}".format(dest)) def _install(src, dest): """ Copy src (file) into dest (file) and make dest executable. Throws exception on trouble. """ if os.path.realpath(src) == os.path.realpath(dest): # Copying a file onto itself is a no-op, never mind return parent = os.path.dirname(dest) if not os.path.isdir(parent): raise IOError("Destination parent is not a directory: %s" % parent) if os.path.isdir(dest): raise IOError("Destination is a directory, won't replace that: %s" % dest) # Make sure nothing's in the way try: os.remove(dest) except OSError: pass if os.path.exists(dest): raise IOError("Can't remove existing entry: %s" % dest) shutil.copyfile(src, dest) os.chmod(dest, 0755)
... Throws exception on trouble. """ if os.path.realpath(src) == os.path.realpath(dest): # Copying a file onto itself is a no-op, never mind return parent = os.path.dirname(dest) if not os.path.isdir(parent): raise IOError("Destination parent is not a directory: %s" % parent) ...
86cea8ad725aa38465c1dfd14c9dcaa0584d89a9
setup.py
setup.py
from setuptools import setup, find_packages import keysmith with open('README.rst') as readme_file: README = readme_file.read() setup( name='keysmith', version=keysmith.__version__, description=keysmith.__doc__, long_description=README, author='David Tucker', author_email='[email protected]', license='LGPLv2+', url='https://github.com/dmtucker/keysmith', packages=find_packages(exclude=['contrib', 'docs', 'tests']), include_package_data=True, entry_points={'console_scripts': ['keysmith = keysmith.__main__:main']}, keywords='password generator keygen', classifiers=[ 'License :: OSI Approved :: ' 'GNU Lesser General Public License v2 or later (LGPLv2+)', 'Intended Audience :: End Users/Desktop', 'Programming Language :: Python :: 3', 'Development Status :: 4 - Beta', ], )
from setuptools import setup, find_packages import keysmith with open('README.rst') as readme_file: README = readme_file.read() setup( name='keysmith', version=keysmith.__version__, description=keysmith.__doc__, long_description=README, author='David Tucker', author_email='[email protected]', license='LGPLv2+', url='https://github.com/dmtucker/keysmith', packages=find_packages(exclude=['contrib', 'docs', 'tests']), include_package_data=True, entry_points={'console_scripts': ['keysmith = keysmith.__main__:main']}, keywords='password generator keygen', classifiers=[ 'License :: OSI Approved :: ' 'GNU Lesser General Public License v2 or later (LGPLv2+)', 'Intended Audience :: End Users/Desktop', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Development Status :: 4 - Beta', ], )
Add more Python 3 classifiers
Add more Python 3 classifiers
Python
bsd-3-clause
dmtucker/keysmith
python
## Code Before: from setuptools import setup, find_packages import keysmith with open('README.rst') as readme_file: README = readme_file.read() setup( name='keysmith', version=keysmith.__version__, description=keysmith.__doc__, long_description=README, author='David Tucker', author_email='[email protected]', license='LGPLv2+', url='https://github.com/dmtucker/keysmith', packages=find_packages(exclude=['contrib', 'docs', 'tests']), include_package_data=True, entry_points={'console_scripts': ['keysmith = keysmith.__main__:main']}, keywords='password generator keygen', classifiers=[ 'License :: OSI Approved :: ' 'GNU Lesser General Public License v2 or later (LGPLv2+)', 'Intended Audience :: End Users/Desktop', 'Programming Language :: Python :: 3', 'Development Status :: 4 - Beta', ], ) ## Instruction: Add more Python 3 classifiers ## Code After: from setuptools import setup, find_packages import keysmith with open('README.rst') as readme_file: README = readme_file.read() setup( name='keysmith', version=keysmith.__version__, description=keysmith.__doc__, long_description=README, author='David Tucker', author_email='[email protected]', license='LGPLv2+', url='https://github.com/dmtucker/keysmith', packages=find_packages(exclude=['contrib', 'docs', 'tests']), include_package_data=True, entry_points={'console_scripts': ['keysmith = keysmith.__main__:main']}, keywords='password generator keygen', classifiers=[ 'License :: OSI Approved :: ' 'GNU Lesser General Public License v2 or later (LGPLv2+)', 'Intended Audience :: End Users/Desktop', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Development Status :: 4 - Beta', ], )
// ... existing code ... 'GNU Lesser General Public License v2 or later (LGPLv2+)', 'Intended Audience :: End Users/Desktop', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Development Status :: 4 - Beta', ], ) // ... rest of the code ...
e0ffee5d5d6057a6dd776b02fea33c6509eb945c
signac/contrib/formats.py
signac/contrib/formats.py
import logging logger = logging.getLogger(__name__) class BasicFormat(object): pass class FileFormat(BasicFormat): def __init__(self, file_object): self._file_object = file_object @property def data(self): return self.read() def read(self, size=-1): return self._file_object.read(size) def seek(self, offset): return self._file_object.seek(offset) def tell(self): return self._file_object.tell() def __iter__(self): return iter(self._file_object) def close(self): return self._file_object.close() class TextFile(FileFormat): pass
TextFile = 'TextFile'
Replace TextFile class definition with str constant.
Replace TextFile class definition with str constant.
Python
bsd-3-clause
csadorf/signac,csadorf/signac
python
## Code Before: import logging logger = logging.getLogger(__name__) class BasicFormat(object): pass class FileFormat(BasicFormat): def __init__(self, file_object): self._file_object = file_object @property def data(self): return self.read() def read(self, size=-1): return self._file_object.read(size) def seek(self, offset): return self._file_object.seek(offset) def tell(self): return self._file_object.tell() def __iter__(self): return iter(self._file_object) def close(self): return self._file_object.close() class TextFile(FileFormat): pass ## Instruction: Replace TextFile class definition with str constant. ## Code After: TextFile = 'TextFile'
// ... existing code ... TextFile = 'TextFile' // ... rest of the code ...
5bb9b2c9d5df410c85f4736c17224aeb2f05dd33
s2v3.py
s2v3.py
from s2v2 import * def calculate_sum(data_sample): total = 0 for row in data_sample[1:]: # slice to start at row two, but I think we should only skip row 1 if we're importing the full csv (data_from_csv), but if we use the data w/ the header (my_csv) we'll be skipping a row that we're not supposed to skip (the actual first row of non-header data). price = float(row[2]) total += price return total print('the sum total of prices for all ties in the dataset = ' + str(calculate_sum(data_from_csv))) # ok we're using the right import, but having two imports is confusing.
from s2v2 import * def calculate_sum(data_sample): total = 0 for row in data_sample[1:]: # slice to start at row two, but I think we should only skip row 1 if we're importing the full csv (data_from_csv), but if we use the data w/ the header (my_csv) we'll be skipping a row that we're not supposed to skip (the actual first row of non-header data). price = float(row[2]) total += price return total print('the sum total of prices for all ties in the dataset = ', calculate_sum(data_from_csv)) # ok we're using the right import, but having two imports is confusing. UPDDATE: No, I don't have to convert the calculate_sum result to a string to add text about it, I just need to use , instead of +
Update print result to use "," instead of "+" for context text
Update print result to use "," instead of "+" for context text
Python
mit
alexmilesyounger/ds_basics
python
## Code Before: from s2v2 import * def calculate_sum(data_sample): total = 0 for row in data_sample[1:]: # slice to start at row two, but I think we should only skip row 1 if we're importing the full csv (data_from_csv), but if we use the data w/ the header (my_csv) we'll be skipping a row that we're not supposed to skip (the actual first row of non-header data). price = float(row[2]) total += price return total print('the sum total of prices for all ties in the dataset = ' + str(calculate_sum(data_from_csv))) # ok we're using the right import, but having two imports is confusing. ## Instruction: Update print result to use "," instead of "+" for context text ## Code After: from s2v2 import * def calculate_sum(data_sample): total = 0 for row in data_sample[1:]: # slice to start at row two, but I think we should only skip row 1 if we're importing the full csv (data_from_csv), but if we use the data w/ the header (my_csv) we'll be skipping a row that we're not supposed to skip (the actual first row of non-header data). price = float(row[2]) total += price return total print('the sum total of prices for all ties in the dataset = ', calculate_sum(data_from_csv)) # ok we're using the right import, but having two imports is confusing. UPDDATE: No, I don't have to convert the calculate_sum result to a string to add text about it, I just need to use , instead of +
# ... existing code ... total += price return total print('the sum total of prices for all ties in the dataset = ', calculate_sum(data_from_csv)) # ok we're using the right import, but having two imports is confusing. UPDDATE: No, I don't have to convert the calculate_sum result to a string to add text about it, I just need to use , instead of + # ... rest of the code ...
47fb142f285f989f7b911915b7b130bf4a72254b
opencraft/urls.py
opencraft/urls.py
from django.conf.urls import include, url from django.contrib import admin from django.views.generic.base import RedirectView urlpatterns = [ url(r'^grappelli/', include('grappelli.urls')), url(r'^admin/', include(admin.site.urls)), url(r'^api/', include('api.urls', namespace="api")), url(r'^task/', include('task.urls', namespace="task")), url(r'^favicon\.ico$', RedirectView.as_view(url='/static/img/favicon/favicon.ico')), url(r'^$', 'task.views.index'), ]
from django.conf.urls import include, url from django.contrib import admin from django.views.generic.base import RedirectView urlpatterns = [ url(r'^grappelli/', include('grappelli.urls')), url(r'^admin/', include(admin.site.urls)), url(r'^api/', include('api.urls', namespace="api")), url(r'^task/', include('task.urls', namespace="task")), url(r'^favicon\.ico$', RedirectView.as_view(url='/static/img/favicon/favicon.ico', permanent=False)), url(r'^$', 'task.views.index'), ]
Remove 1.8 warning about redirect
Remove 1.8 warning about redirect
Python
agpl-3.0
omarkhan/opencraft,open-craft/opencraft,open-craft/opencraft,brousch/opencraft,omarkhan/opencraft,omarkhan/opencraft,omarkhan/opencraft,open-craft/opencraft,brousch/opencraft,brousch/opencraft,open-craft/opencraft,open-craft/opencraft
python
## Code Before: from django.conf.urls import include, url from django.contrib import admin from django.views.generic.base import RedirectView urlpatterns = [ url(r'^grappelli/', include('grappelli.urls')), url(r'^admin/', include(admin.site.urls)), url(r'^api/', include('api.urls', namespace="api")), url(r'^task/', include('task.urls', namespace="task")), url(r'^favicon\.ico$', RedirectView.as_view(url='/static/img/favicon/favicon.ico')), url(r'^$', 'task.views.index'), ] ## Instruction: Remove 1.8 warning about redirect ## Code After: from django.conf.urls import include, url from django.contrib import admin from django.views.generic.base import RedirectView urlpatterns = [ url(r'^grappelli/', include('grappelli.urls')), url(r'^admin/', include(admin.site.urls)), url(r'^api/', include('api.urls', namespace="api")), url(r'^task/', include('task.urls', namespace="task")), url(r'^favicon\.ico$', RedirectView.as_view(url='/static/img/favicon/favicon.ico', permanent=False)), url(r'^$', 'task.views.index'), ]
... url(r'^admin/', include(admin.site.urls)), url(r'^api/', include('api.urls', namespace="api")), url(r'^task/', include('task.urls', namespace="task")), url(r'^favicon\.ico$', RedirectView.as_view(url='/static/img/favicon/favicon.ico', permanent=False)), url(r'^$', 'task.views.index'), ] ...
a62eaa2f7447d930db84f966986736d30ef522bb
src/block/serpent/serpent.h
src/block/serpent/serpent.h
/* * Serpent * (C) 1999-2007 Jack Lloyd * * Distributed under the terms of the Botan license */ #ifndef BOTAN_SERPENT_H__ #define BOTAN_SERPENT_H__ #include <botan/block_cipher.h> namespace Botan { /** * Serpent, an AES finalist */ class BOTAN_DLL Serpent : public BlockCipher { public: void encrypt_n(const byte in[], byte out[], u32bit blocks) const; void decrypt_n(const byte in[], byte out[], u32bit blocks) const; void clear() { round_key.clear(); } std::string name() const { return "Serpent"; } BlockCipher* clone() const { return new Serpent; } Serpent() : BlockCipher(16, 16, 32, 8) {} protected: void key_schedule(const byte key[], u32bit length); SecureVector<u32bit, 132> round_key; }; } #endif
/* * Serpent * (C) 1999-2007 Jack Lloyd * * Distributed under the terms of the Botan license */ #ifndef BOTAN_SERPENT_H__ #define BOTAN_SERPENT_H__ #include <botan/block_cipher.h> namespace Botan { /** * Serpent, an AES finalist */ class BOTAN_DLL Serpent : public BlockCipher { public: void encrypt_n(const byte in[], byte out[], u32bit blocks) const; void decrypt_n(const byte in[], byte out[], u32bit blocks) const; void clear() { round_key.clear(); } std::string name() const { return "Serpent"; } BlockCipher* clone() const { return new Serpent; } Serpent() : BlockCipher(16, 16, 32, 8) {} protected: /** * For use by subclasses using SIMD, asm, etc * @return const reference to the key schedule */ const SecureVector<u32bit, 132>& get_round_keys() const { return round_key; } /** * For use by subclasses that implement the key schedule * @param ks is the new key schedule value to set */ void set_round_keys(const u32bit ks[132]) { round_key.set(ks, 132); } private: void key_schedule(const byte key[], u32bit length); SecureVector<u32bit, 132> round_key; }; } #endif
Make Serpent's key_schedule and actual round keys private. Add protected accessor functions for get and set. Set is needed by the x86 version since it implements the key schedule directly.
Make Serpent's key_schedule and actual round keys private. Add protected accessor functions for get and set. Set is needed by the x86 version since it implements the key schedule directly.
C
bsd-2-clause
randombit/botan,Rohde-Schwarz-Cybersecurity/botan,webmaster128/botan,Rohde-Schwarz-Cybersecurity/botan,Rohde-Schwarz-Cybersecurity/botan,Rohde-Schwarz-Cybersecurity/botan,webmaster128/botan,randombit/botan,Rohde-Schwarz-Cybersecurity/botan,webmaster128/botan,webmaster128/botan,webmaster128/botan,randombit/botan,Rohde-Schwarz-Cybersecurity/botan,randombit/botan,randombit/botan
c
## Code Before: /* * Serpent * (C) 1999-2007 Jack Lloyd * * Distributed under the terms of the Botan license */ #ifndef BOTAN_SERPENT_H__ #define BOTAN_SERPENT_H__ #include <botan/block_cipher.h> namespace Botan { /** * Serpent, an AES finalist */ class BOTAN_DLL Serpent : public BlockCipher { public: void encrypt_n(const byte in[], byte out[], u32bit blocks) const; void decrypt_n(const byte in[], byte out[], u32bit blocks) const; void clear() { round_key.clear(); } std::string name() const { return "Serpent"; } BlockCipher* clone() const { return new Serpent; } Serpent() : BlockCipher(16, 16, 32, 8) {} protected: void key_schedule(const byte key[], u32bit length); SecureVector<u32bit, 132> round_key; }; } #endif ## Instruction: Make Serpent's key_schedule and actual round keys private. Add protected accessor functions for get and set. Set is needed by the x86 version since it implements the key schedule directly. ## Code After: /* * Serpent * (C) 1999-2007 Jack Lloyd * * Distributed under the terms of the Botan license */ #ifndef BOTAN_SERPENT_H__ #define BOTAN_SERPENT_H__ #include <botan/block_cipher.h> namespace Botan { /** * Serpent, an AES finalist */ class BOTAN_DLL Serpent : public BlockCipher { public: void encrypt_n(const byte in[], byte out[], u32bit blocks) const; void decrypt_n(const byte in[], byte out[], u32bit blocks) const; void clear() { round_key.clear(); } std::string name() const { return "Serpent"; } BlockCipher* clone() const { return new Serpent; } Serpent() : BlockCipher(16, 16, 32, 8) {} protected: /** * For use by subclasses using SIMD, asm, etc * @return const reference to the key schedule */ const SecureVector<u32bit, 132>& get_round_keys() const { return round_key; } /** * For use by subclasses that implement the key schedule * @param ks is the new key schedule value to set */ void set_round_keys(const u32bit ks[132]) { round_key.set(ks, 132); } private: void key_schedule(const byte key[], u32bit length); SecureVector<u32bit, 132> round_key; }; } #endif
# ... existing code ... BlockCipher* clone() const { return new Serpent; } Serpent() : BlockCipher(16, 16, 32, 8) {} protected: /** * For use by subclasses using SIMD, asm, etc * @return const reference to the key schedule */ const SecureVector<u32bit, 132>& get_round_keys() const { return round_key; } /** * For use by subclasses that implement the key schedule * @param ks is the new key schedule value to set */ void set_round_keys(const u32bit ks[132]) { round_key.set(ks, 132); } private: void key_schedule(const byte key[], u32bit length); SecureVector<u32bit, 132> round_key; }; # ... rest of the code ...
8fde77a843431037fde796c92b22f699bd28953f
src/openccsensors/common/sensors/industrialcraft/ReactorTarget.java
src/openccsensors/common/sensors/industrialcraft/ReactorTarget.java
package openccsensors.common.sensors.industrialcraft; import ic2.api.IReactor; import java.util.HashMap; import java.util.Map; import net.minecraft.src.TileEntity; import net.minecraft.src.World; import openccsensors.common.api.ISensorTarget; import openccsensors.common.sensors.TileSensorTarget; public class ReactorTarget extends TileSensorTarget implements ISensorTarget { ReactorTarget(TileEntity targetEntity) { super(targetEntity); } public Map getDetailInformation(World world) { HashMap retMap = new HashMap(); IReactor reactor = (IReactor) world.getBlockTileEntity(xCoord, yCoord, zCoord); retMap.put("Heat", reactor.getHeat()); retMap.put("MaxHeat", reactor.getMaxHeat()); retMap.put("Output", reactor.getOutput()); retMap.put("Active", reactor.produceEnergy()); return retMap; } }
package openccsensors.common.sensors.industrialcraft; import ic2.api.IReactor; import ic2.api.IC2Reactor; import java.util.HashMap; import java.util.Map; import net.minecraft.src.TileEntity; import net.minecraft.src.World; import openccsensors.common.api.ISensorTarget; import openccsensors.common.sensors.TileSensorTarget; public class ReactorTarget extends TileSensorTarget implements ISensorTarget { ReactorTarget(TileEntity targetEntity) { super(targetEntity); } public Map getDetailInformation(World world) { HashMap retMap = new HashMap(); IReactor reactor = (IReactor) world.getBlockTileEntity(xCoord, yCoord, zCoord); retMap.put("Heat", reactor.getHeat()); retMap.put("MaxHeat", reactor.getMaxHeat()); retMap.put("Output", reactor.getOutput() * new IC2Reactor().getEUOutput()); retMap.put("Active", reactor.produceEnergy()); return retMap; } }
Fix so that reactors properly return the EU/t on output.
Fix so that reactors properly return the EU/t on output.
Java
mit
lyqyd/OpenCCSensors,Cloudhunter/OpenCCSensors
java
## Code Before: package openccsensors.common.sensors.industrialcraft; import ic2.api.IReactor; import java.util.HashMap; import java.util.Map; import net.minecraft.src.TileEntity; import net.minecraft.src.World; import openccsensors.common.api.ISensorTarget; import openccsensors.common.sensors.TileSensorTarget; public class ReactorTarget extends TileSensorTarget implements ISensorTarget { ReactorTarget(TileEntity targetEntity) { super(targetEntity); } public Map getDetailInformation(World world) { HashMap retMap = new HashMap(); IReactor reactor = (IReactor) world.getBlockTileEntity(xCoord, yCoord, zCoord); retMap.put("Heat", reactor.getHeat()); retMap.put("MaxHeat", reactor.getMaxHeat()); retMap.put("Output", reactor.getOutput()); retMap.put("Active", reactor.produceEnergy()); return retMap; } } ## Instruction: Fix so that reactors properly return the EU/t on output. ## Code After: package openccsensors.common.sensors.industrialcraft; import ic2.api.IReactor; import ic2.api.IC2Reactor; import java.util.HashMap; import java.util.Map; import net.minecraft.src.TileEntity; import net.minecraft.src.World; import openccsensors.common.api.ISensorTarget; import openccsensors.common.sensors.TileSensorTarget; public class ReactorTarget extends TileSensorTarget implements ISensorTarget { ReactorTarget(TileEntity targetEntity) { super(targetEntity); } public Map getDetailInformation(World world) { HashMap retMap = new HashMap(); IReactor reactor = (IReactor) world.getBlockTileEntity(xCoord, yCoord, zCoord); retMap.put("Heat", reactor.getHeat()); retMap.put("MaxHeat", reactor.getMaxHeat()); retMap.put("Output", reactor.getOutput() * new IC2Reactor().getEUOutput()); retMap.put("Active", reactor.produceEnergy()); return retMap; } }
... package openccsensors.common.sensors.industrialcraft; import ic2.api.IReactor; import ic2.api.IC2Reactor; import java.util.HashMap; import java.util.Map; ... retMap.put("Heat", reactor.getHeat()); retMap.put("MaxHeat", reactor.getMaxHeat()); retMap.put("Output", reactor.getOutput() * new IC2Reactor().getEUOutput()); retMap.put("Active", reactor.produceEnergy()); return retMap; ...
565ff4653b0dca4bb4831d263dae118d044b6b9c
test/test_molecule.py
test/test_molecule.py
import pytest import os import shutil from subprocess import call from cookiecutter.main import cookiecutter playbook_setup_commands = ['pip install -r requirements.txt'] playbook_setup_success = 0 playbook_test_command = "molecule test" playbook_test_success = 0 @pytest.mark.parametrize('role_name', ['tree']) def test_role_name(role_name): last_dir = os.path.curdir project_name = "ansible-role-{0}".format(role_name) test_dir = project_name try: shutil.rmtree(test_dir, ignore_errors=True) cookiecutter( '.', no_input=True, overwrite_if_exists=True, extra_context={ 'role_name': role_name, 'project_name': project_name} ) for command in playbook_setup_commands: assert call(command.split()) == playbook_setup_success os.chdir(test_dir) assert call(playbook_test_command.split()) == playbook_test_success finally: os.chdir(last_dir) shutil.rmtree(test_dir, ignore_errors=True)
import pytest import os import shutil from subprocess import call from cookiecutter.main import cookiecutter playbook_setup_commands = ['pip install -r https://raw.githubusercontent.com/nephelaiio/ansible-role-requirements/master/requirements.txt'] playbook_setup_success = 0 playbook_test_command = "molecule test" playbook_test_success = 0 @pytest.mark.parametrize('role_name', ['tree']) def test_role_name(role_name): last_dir = os.path.curdir project_name = "ansible-role-{0}".format(role_name) test_dir = project_name try: shutil.rmtree(test_dir, ignore_errors=True) cookiecutter( '.', no_input=True, overwrite_if_exists=True, extra_context={ 'role_name': role_name, 'project_name': project_name} ) for command in playbook_setup_commands: assert call(command.split()) == playbook_setup_success os.chdir(test_dir) assert call(playbook_test_command.split()) == playbook_test_success finally: os.chdir(last_dir) shutil.rmtree(test_dir, ignore_errors=True)
Fix broken requirements file references
Fix broken requirements file references
Python
mit
nephelaiio/cookiecutter-ansible-role
python
## Code Before: import pytest import os import shutil from subprocess import call from cookiecutter.main import cookiecutter playbook_setup_commands = ['pip install -r requirements.txt'] playbook_setup_success = 0 playbook_test_command = "molecule test" playbook_test_success = 0 @pytest.mark.parametrize('role_name', ['tree']) def test_role_name(role_name): last_dir = os.path.curdir project_name = "ansible-role-{0}".format(role_name) test_dir = project_name try: shutil.rmtree(test_dir, ignore_errors=True) cookiecutter( '.', no_input=True, overwrite_if_exists=True, extra_context={ 'role_name': role_name, 'project_name': project_name} ) for command in playbook_setup_commands: assert call(command.split()) == playbook_setup_success os.chdir(test_dir) assert call(playbook_test_command.split()) == playbook_test_success finally: os.chdir(last_dir) shutil.rmtree(test_dir, ignore_errors=True) ## Instruction: Fix broken requirements file references ## Code After: import pytest import os import shutil from subprocess import call from cookiecutter.main import cookiecutter playbook_setup_commands = ['pip install -r https://raw.githubusercontent.com/nephelaiio/ansible-role-requirements/master/requirements.txt'] playbook_setup_success = 0 playbook_test_command = "molecule test" playbook_test_success = 0 @pytest.mark.parametrize('role_name', ['tree']) def test_role_name(role_name): last_dir = os.path.curdir project_name = "ansible-role-{0}".format(role_name) test_dir = project_name try: shutil.rmtree(test_dir, ignore_errors=True) cookiecutter( '.', no_input=True, overwrite_if_exists=True, extra_context={ 'role_name': role_name, 'project_name': project_name} ) for command in playbook_setup_commands: assert call(command.split()) == playbook_setup_success os.chdir(test_dir) assert call(playbook_test_command.split()) == playbook_test_success finally: os.chdir(last_dir) shutil.rmtree(test_dir, ignore_errors=True)
// ... existing code ... from cookiecutter.main import cookiecutter playbook_setup_commands = ['pip install -r https://raw.githubusercontent.com/nephelaiio/ansible-role-requirements/master/requirements.txt'] playbook_setup_success = 0 playbook_test_command = "molecule test" playbook_test_success = 0 // ... rest of the code ...
a778a41c8deb6fd9812e405143e34679122c18db
website/addons/base/utils.py
website/addons/base/utils.py
from os.path import basename from website import settings def serialize_addon_config(config, user): lookup = config.template_lookup return { 'addon_short_name': config.short_name, 'addon_full_name': config.full_name, 'node_settings_template': lookup.get_template(basename(config.node_settings_template)), 'user_settings_template': lookup.get_template(basename(config.user_settings_template)), 'is_enabled': user.get_addon(config.short_name) is not None, } def get_addons_by_config_type(config_type, user): addons = [addon for addon in settings.ADDONS_AVAILABLE if config_type in addon.configs] addon_settings = [] for addon_config in sorted(addons, key=lambda cfg: cfg.full_name.lower()): # short_name = addon_config.short_name config = serialize_addon_config(addon_config, user) ''' user_settings = user.get_addon(short_name) if user_settings: user_settings = user_settings.to_json(user) config.update({ 'user_settings': user_settings or {} }) ''' addon_settings.append(config) return addon_settings
from os.path import basename from website import settings def serialize_addon_config(config, user): lookup = config.template_lookup user_addon = user.get_addon(config.short_name) ret = { 'addon_short_name': config.short_name, 'addon_full_name': config.full_name, 'node_settings_template': lookup.get_template(basename(config.node_settings_template)), 'user_settings_template': lookup.get_template(basename(config.user_settings_template)), 'is_enabled': user_addon is not None, } ret.update(user_addon.to_json(user) if user_addon else {}) return ret def get_addons_by_config_type(config_type, user): addons = [addon for addon in settings.ADDONS_AVAILABLE if config_type in addon.configs] return [serialize_addon_config(addon_config, user) for addon_config in sorted(addons, key=lambda cfg: cfg.full_name.lower())]
Add user_settings to serialized addon settings
Add user_settings to serialized addon settings
Python
apache-2.0
ZobairAlijan/osf.io,leb2dg/osf.io,doublebits/osf.io,mluo613/osf.io,jolene-esposito/osf.io,alexschiller/osf.io,mattclark/osf.io,laurenrevere/osf.io,jolene-esposito/osf.io,SSJohns/osf.io,billyhunt/osf.io,pattisdr/osf.io,samanehsan/osf.io,DanielSBrown/osf.io,cslzchen/osf.io,caseyrygt/osf.io,zachjanicki/osf.io,Nesiehr/osf.io,TomHeatwole/osf.io,reinaH/osf.io,danielneis/osf.io,cldershem/osf.io,cldershem/osf.io,mluo613/osf.io,MerlinZhang/osf.io,petermalcolm/osf.io,doublebits/osf.io,amyshi188/osf.io,SSJohns/osf.io,brandonPurvis/osf.io,asanfilippo7/osf.io,baylee-d/osf.io,mfraezz/osf.io,Nesiehr/osf.io,ticklemepierce/osf.io,samanehsan/osf.io,sloria/osf.io,samchrisinger/osf.io,kch8qx/osf.io,ckc6cz/osf.io,ckc6cz/osf.io,leb2dg/osf.io,emetsger/osf.io,cwisecarver/osf.io,hmoco/osf.io,hmoco/osf.io,erinspace/osf.io,doublebits/osf.io,aaxelb/osf.io,Ghalko/osf.io,jmcarp/osf.io,DanielSBrown/osf.io,bdyetton/prettychart,bdyetton/prettychart,TomHeatwole/osf.io,zachjanicki/osf.io,doublebits/osf.io,Nesiehr/osf.io,brianjgeiger/osf.io,acshi/osf.io,cslzchen/osf.io,jnayak1/osf.io,RomanZWang/osf.io,acshi/osf.io,sbt9uc/osf.io,danielneis/osf.io,crcresearch/osf.io,zamattiac/osf.io,monikagrabowska/osf.io,cslzchen/osf.io,erinspace/osf.io,rdhyee/osf.io,alexschiller/osf.io,mluke93/osf.io,alexschiller/osf.io,chennan47/osf.io,ckc6cz/osf.io,zamattiac/osf.io,zamattiac/osf.io,jolene-esposito/osf.io,caseyrollins/osf.io,haoyuchen1992/osf.io,arpitar/osf.io,SSJohns/osf.io,TomBaxter/osf.io,zachjanicki/osf.io,kch8qx/osf.io,lyndsysimon/osf.io,samchrisinger/osf.io,saradbowman/osf.io,acshi/osf.io,TomHeatwole/osf.io,kwierman/osf.io,wearpants/osf.io,laurenrevere/osf.io,felliott/osf.io,baylee-d/osf.io,petermalcolm/osf.io,SSJohns/osf.io,reinaH/osf.io,monikagrabowska/osf.io,amyshi188/osf.io,bdyetton/prettychart,TomHeatwole/osf.io,icereval/osf.io,haoyuchen1992/osf.io,RomanZWang/osf.io,TomBaxter/osf.io,sbt9uc/osf.io,jnayak1/osf.io,amyshi188/osf.io,emetsger/osf.io,DanielSBrown/osf.io,MerlinZhang/osf.io,cwisecarver/osf.io,Ghalko/osf.io,laurenrevere/osf.io,cslzchen/osf.io,leb2dg/osf.io,cosenal/osf.io,erinspace/osf.io,hmoco/osf.io,chrisseto/osf.io,felliott/osf.io,alexschiller/osf.io,KAsante95/osf.io,felliott/osf.io,ticklemepierce/osf.io,pattisdr/osf.io,reinaH/osf.io,icereval/osf.io,ticklemepierce/osf.io,brandonPurvis/osf.io,billyhunt/osf.io,brianjgeiger/osf.io,MerlinZhang/osf.io,abought/osf.io,mfraezz/osf.io,acshi/osf.io,HarryRybacki/osf.io,sbt9uc/osf.io,icereval/osf.io,danielneis/osf.io,CenterForOpenScience/osf.io,kch8qx/osf.io,emetsger/osf.io,zachjanicki/osf.io,GageGaskins/osf.io,rdhyee/osf.io,CenterForOpenScience/osf.io,jmcarp/osf.io,cwisecarver/osf.io,petermalcolm/osf.io,monikagrabowska/osf.io,Johnetordoff/osf.io,binoculars/osf.io,njantrania/osf.io,TomBaxter/osf.io,caseyrollins/osf.io,haoyuchen1992/osf.io,billyhunt/osf.io,RomanZWang/osf.io,mattclark/osf.io,mfraezz/osf.io,mluke93/osf.io,ZobairAlijan/osf.io,dplorimer/osf,caneruguz/osf.io,Nesiehr/osf.io,lyndsysimon/osf.io,njantrania/osf.io,kwierman/osf.io,haoyuchen1992/osf.io,rdhyee/osf.io,alexschiller/osf.io,HarryRybacki/osf.io,emetsger/osf.io,HarryRybacki/osf.io,chrisseto/osf.io,HalcyonChimera/osf.io,reinaH/osf.io,chrisseto/osf.io,ckc6cz/osf.io,mluo613/osf.io,wearpants/osf.io,mluo613/osf.io,chennan47/osf.io,caseyrygt/osf.io,leb2dg/osf.io,kwierman/osf.io,dplorimer/osf,HalcyonChimera/osf.io,KAsante95/osf.io,cwisecarver/osf.io,GageGaskins/osf.io,kch8qx/osf.io,samanehsan/osf.io,binoculars/osf.io,binoculars/osf.io,saradbowman/osf.io,jmcarp/osf.io,amyshi188/osf.io,ZobairAlijan/osf.io,Ghalko/osf.io,doublebits/osf.io,HalcyonChimera/osf.io,brandonPurvis/osf.io,abought/osf.io,HalcyonChimera/osf.io,petermalcolm/osf.io,kch8qx/osf.io,hmoco/osf.io,adlius/osf.io,asanfilippo7/osf.io,Johnetordoff/osf.io,aaxelb/osf.io,njantrania/osf.io,rdhyee/osf.io,DanielSBrown/osf.io,abought/osf.io,samanehsan/osf.io,pattisdr/osf.io,billyhunt/osf.io,dplorimer/osf,billyhunt/osf.io,KAsante95/osf.io,adlius/osf.io,caneruguz/osf.io,samchrisinger/osf.io,brandonPurvis/osf.io,CenterForOpenScience/osf.io,dplorimer/osf,mluke93/osf.io,sloria/osf.io,crcresearch/osf.io,jnayak1/osf.io,danielneis/osf.io,cldershem/osf.io,abought/osf.io,cosenal/osf.io,caneruguz/osf.io,CenterForOpenScience/osf.io,crcresearch/osf.io,sbt9uc/osf.io,caseyrygt/osf.io,Ghalko/osf.io,mattclark/osf.io,sloria/osf.io,ZobairAlijan/osf.io,wearpants/osf.io,caseyrygt/osf.io,chennan47/osf.io,aaxelb/osf.io,cosenal/osf.io,baylee-d/osf.io,asanfilippo7/osf.io,asanfilippo7/osf.io,jnayak1/osf.io,GageGaskins/osf.io,GageGaskins/osf.io,GageGaskins/osf.io,jmcarp/osf.io,lyndsysimon/osf.io,mluke93/osf.io,HarryRybacki/osf.io,KAsante95/osf.io,adlius/osf.io,zamattiac/osf.io,kwierman/osf.io,samchrisinger/osf.io,chrisseto/osf.io,brianjgeiger/osf.io,arpitar/osf.io,brandonPurvis/osf.io,RomanZWang/osf.io,cldershem/osf.io,arpitar/osf.io,caneruguz/osf.io,wearpants/osf.io,Johnetordoff/osf.io,njantrania/osf.io,monikagrabowska/osf.io,monikagrabowska/osf.io,mluo613/osf.io,felliott/osf.io,ticklemepierce/osf.io,brianjgeiger/osf.io,KAsante95/osf.io,acshi/osf.io,RomanZWang/osf.io,bdyetton/prettychart,cosenal/osf.io,arpitar/osf.io,adlius/osf.io,aaxelb/osf.io,lyndsysimon/osf.io,MerlinZhang/osf.io,Johnetordoff/osf.io,jolene-esposito/osf.io,mfraezz/osf.io,caseyrollins/osf.io
python
## Code Before: from os.path import basename from website import settings def serialize_addon_config(config, user): lookup = config.template_lookup return { 'addon_short_name': config.short_name, 'addon_full_name': config.full_name, 'node_settings_template': lookup.get_template(basename(config.node_settings_template)), 'user_settings_template': lookup.get_template(basename(config.user_settings_template)), 'is_enabled': user.get_addon(config.short_name) is not None, } def get_addons_by_config_type(config_type, user): addons = [addon for addon in settings.ADDONS_AVAILABLE if config_type in addon.configs] addon_settings = [] for addon_config in sorted(addons, key=lambda cfg: cfg.full_name.lower()): # short_name = addon_config.short_name config = serialize_addon_config(addon_config, user) ''' user_settings = user.get_addon(short_name) if user_settings: user_settings = user_settings.to_json(user) config.update({ 'user_settings': user_settings or {} }) ''' addon_settings.append(config) return addon_settings ## Instruction: Add user_settings to serialized addon settings ## Code After: from os.path import basename from website import settings def serialize_addon_config(config, user): lookup = config.template_lookup user_addon = user.get_addon(config.short_name) ret = { 'addon_short_name': config.short_name, 'addon_full_name': config.full_name, 'node_settings_template': lookup.get_template(basename(config.node_settings_template)), 'user_settings_template': lookup.get_template(basename(config.user_settings_template)), 'is_enabled': user_addon is not None, } ret.update(user_addon.to_json(user) if user_addon else {}) return ret def get_addons_by_config_type(config_type, user): addons = [addon for addon in settings.ADDONS_AVAILABLE if config_type in addon.configs] return [serialize_addon_config(addon_config, user) for addon_config in sorted(addons, key=lambda cfg: cfg.full_name.lower())]
... def serialize_addon_config(config, user): lookup = config.template_lookup user_addon = user.get_addon(config.short_name) ret = { 'addon_short_name': config.short_name, 'addon_full_name': config.full_name, 'node_settings_template': lookup.get_template(basename(config.node_settings_template)), 'user_settings_template': lookup.get_template(basename(config.user_settings_template)), 'is_enabled': user_addon is not None, } ret.update(user_addon.to_json(user) if user_addon else {}) return ret def get_addons_by_config_type(config_type, user): addons = [addon for addon in settings.ADDONS_AVAILABLE if config_type in addon.configs] return [serialize_addon_config(addon_config, user) for addon_config in sorted(addons, key=lambda cfg: cfg.full_name.lower())] ...
4c6218db8a99c3169546a79f13d84274c1dee87c
SeriesGuide/src/com/battlelancer/seriesguide/dataliberation/model/Season.java
SeriesGuide/src/com/battlelancer/seriesguide/dataliberation/model/Season.java
package com.battlelancer.seriesguide.dataliberation.model; import com.battlelancer.seriesguide.items.Episode; import com.google.myjson.annotations.SerializedName; import java.util.List; public class Season { @SerializedName("tvdb_id") public int tvdbId; public int season; public List<Episode> episodes; }
package com.battlelancer.seriesguide.dataliberation.model; import com.google.myjson.annotations.SerializedName; import java.util.List; public class Season { @SerializedName("tvdb_id") public int tvdbId; public int season; public List<Episode> episodes; }
Use correct kind of Episode.
Use correct kind of Episode.
Java
apache-2.0
artemnikitin/SeriesGuide,UweTrottmann/SeriesGuide,epiphany27/SeriesGuide,hoanganhx86/SeriesGuide,0359xiaodong/SeriesGuide,UweTrottmann/SeriesGuide,r00t-user/SeriesGuide
java
## Code Before: package com.battlelancer.seriesguide.dataliberation.model; import com.battlelancer.seriesguide.items.Episode; import com.google.myjson.annotations.SerializedName; import java.util.List; public class Season { @SerializedName("tvdb_id") public int tvdbId; public int season; public List<Episode> episodes; } ## Instruction: Use correct kind of Episode. ## Code After: package com.battlelancer.seriesguide.dataliberation.model; import com.google.myjson.annotations.SerializedName; import java.util.List; public class Season { @SerializedName("tvdb_id") public int tvdbId; public int season; public List<Episode> episodes; }
// ... existing code ... package com.battlelancer.seriesguide.dataliberation.model; import com.google.myjson.annotations.SerializedName; import java.util.List; // ... modified code ... @SerializedName("tvdb_id") public int tvdbId; public int season; public List<Episode> episodes; } // ... rest of the code ...