commit stringlengths 40 40 | old_file stringlengths 4 184 | new_file stringlengths 4 184 | old_contents stringlengths 1 3.6k | new_contents stringlengths 5 3.38k | subject stringlengths 15 778 | message stringlengths 16 6.74k | lang stringclasses 201 values | license stringclasses 13 values | repos stringlengths 6 116k | config stringclasses 201 values | content stringlengths 137 7.24k | diff stringlengths 26 5.55k | diff_length int64 1 123 | relative_diff_length float64 0.01 89 | n_lines_added int64 0 108 | n_lines_deleted int64 0 106 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
a2cbfd66c75a07bd23d1110e6b055227fdbfa7f9 | README.md | README.md |
This produces a csv file that is a histogram of the frequency of paths occurring of a certain length.
You provide a csv file describing your graph. The first column is the participant, and all subsequent columns are the order in which the user interacted with each resource. The value in those columns is the resource that was accessed.
The output file has two columns. The first is a description of the path and the second is the frequency.
```
Usage: pathfinder.rb [options] INFILE1 [INFILE2 ...]
-h, --help Help
-i, --ignore-rows=NUM Number of header rows to ignore
-l, --length=LENGTH Length of the subpaths
-o, --output=FILE Name of output file
-v, --[no-]verbose Verbose mode
```
For example
```
$ ruby pathfinder.rb -l 3 data.csv
```
Command line options are assuming you're running Ruby 1.9.3 |
This produces a csv file that is a histogram of the frequency of paths occurring of a certain length.
You provide a csv file describing your graph. The first column is the participant, and all subsequent columns are the order in which the user interacted with each resource. The value in those columns is the resource that was accessed.
The output file has two columns. The first is a description of the path and the second is the frequency.
```
Usage: pathfinder.rb [options] INFILE1 [INFILE2 ...]
-h, --help Help
-i, --ignore-rows=NUM Number of header rows to ignore
-l, --length=LENGTH Length of the subpaths
-o, --output=FILE Name of output file
-v, --[no-]verbose Verbose mode
```
For example
```
$ ruby pathfinder.rb -l 3 data.csv
```
CSV parser assumes you're running Ruby 1.9.3 | Update the readme about ruby assumption | Update the readme about ruby assumption | Markdown | mit | cyrusstoller/Pathfinder,cyrusstoller/Pathfinder | markdown | ## Code Before:
This produces a csv file that is a histogram of the frequency of paths occurring of a certain length.
You provide a csv file describing your graph. The first column is the participant, and all subsequent columns are the order in which the user interacted with each resource. The value in those columns is the resource that was accessed.
The output file has two columns. The first is a description of the path and the second is the frequency.
```
Usage: pathfinder.rb [options] INFILE1 [INFILE2 ...]
-h, --help Help
-i, --ignore-rows=NUM Number of header rows to ignore
-l, --length=LENGTH Length of the subpaths
-o, --output=FILE Name of output file
-v, --[no-]verbose Verbose mode
```
For example
```
$ ruby pathfinder.rb -l 3 data.csv
```
Command line options are assuming you're running Ruby 1.9.3
## Instruction:
Update the readme about ruby assumption
## Code After:
This produces a csv file that is a histogram of the frequency of paths occurring of a certain length.
You provide a csv file describing your graph. The first column is the participant, and all subsequent columns are the order in which the user interacted with each resource. The value in those columns is the resource that was accessed.
The output file has two columns. The first is a description of the path and the second is the frequency.
```
Usage: pathfinder.rb [options] INFILE1 [INFILE2 ...]
-h, --help Help
-i, --ignore-rows=NUM Number of header rows to ignore
-l, --length=LENGTH Length of the subpaths
-o, --output=FILE Name of output file
-v, --[no-]verbose Verbose mode
```
For example
```
$ ruby pathfinder.rb -l 3 data.csv
```
CSV parser assumes you're running Ruby 1.9.3 |
This produces a csv file that is a histogram of the frequency of paths occurring of a certain length.
You provide a csv file describing your graph. The first column is the participant, and all subsequent columns are the order in which the user interacted with each resource. The value in those columns is the resource that was accessed.
The output file has two columns. The first is a description of the path and the second is the frequency.
```
Usage: pathfinder.rb [options] INFILE1 [INFILE2 ...]
-h, --help Help
-i, --ignore-rows=NUM Number of header rows to ignore
-l, --length=LENGTH Length of the subpaths
-o, --output=FILE Name of output file
-v, --[no-]verbose Verbose mode
```
For example
```
$ ruby pathfinder.rb -l 3 data.csv
```
- Command line options are assuming you're running Ruby 1.9.3
+ CSV parser assumes you're running Ruby 1.9.3 | 2 | 0.086957 | 1 | 1 |
3730accd147663026f892a707166c0c001cabed0 | snippets/TMAX.c | snippets/TMAX.c |
// demonstate testmin testmax consistency with malloc
#include <string.h> // memcpy
#include <stdio.h> // printf
#include <stdlib.h> // malloc
#include <assert.h> // assert
typedef struct {ssize_t size; char *row; int count;} slot;
slot line;
slot *text;
int main(void)
{
leng = 10; int numb;
text = malloc(leng*sizeof(slot));
int textmax = (int) (text + leng - 1);
int textmin = (int) (text + 0);
line.row = NULL;
line.size = 0;
int i; for(i = 0; i < leng+1; i++) //deliberate overrun
{
printf("%d text = %p\n",i,text+i);
numb = (int) (text+i);
printf("%d numb = %x\n",i,numb);
assert(textmin <= numb); assert(textmax >= numb);
*(text+i) = line;
}
printf("test run ending\n");
return 0;
}
| assert(textmin <= texndx); \
assert(textmax >= texndx);
typedef struct {ssize_t size; char *row; int count;} slot;
slot line;
slot *text;
int main(void)
{
int leng = 10;
text = malloc(leng*sizeof(slot));
int textmax = (int) (text + leng - 1);
int textmin = (int) (text + 0);
line.row = NULL;
line.size = 0;
int iy; for(iy = 0; iy < leng+1; iy++) //deliberate iy overrun
{
printf("%d text = %p\n",iy,text+iy);
int texndx; textbound;
text[iy] = line;
}
printf("test run ending\n");
return 0;
}
| Add definition for testing bounds on array text | Add definition for testing bounds on array text
| C | bsd-2-clause | eingaeph/pip.imbue.hood,eingaeph/pip.imbue.hood | c | ## Code Before:
// demonstate testmin testmax consistency with malloc
#include <string.h> // memcpy
#include <stdio.h> // printf
#include <stdlib.h> // malloc
#include <assert.h> // assert
typedef struct {ssize_t size; char *row; int count;} slot;
slot line;
slot *text;
int main(void)
{
leng = 10; int numb;
text = malloc(leng*sizeof(slot));
int textmax = (int) (text + leng - 1);
int textmin = (int) (text + 0);
line.row = NULL;
line.size = 0;
int i; for(i = 0; i < leng+1; i++) //deliberate overrun
{
printf("%d text = %p\n",i,text+i);
numb = (int) (text+i);
printf("%d numb = %x\n",i,numb);
assert(textmin <= numb); assert(textmax >= numb);
*(text+i) = line;
}
printf("test run ending\n");
return 0;
}
## Instruction:
Add definition for testing bounds on array text
## Code After:
assert(textmin <= texndx); \
assert(textmax >= texndx);
typedef struct {ssize_t size; char *row; int count;} slot;
slot line;
slot *text;
int main(void)
{
int leng = 10;
text = malloc(leng*sizeof(slot));
int textmax = (int) (text + leng - 1);
int textmin = (int) (text + 0);
line.row = NULL;
line.size = 0;
int iy; for(iy = 0; iy < leng+1; iy++) //deliberate iy overrun
{
printf("%d text = %p\n",iy,text+iy);
int texndx; textbound;
text[iy] = line;
}
printf("test run ending\n");
return 0;
}
| + assert(textmin <= texndx); \
+ assert(textmax >= texndx);
-
- // demonstate testmin testmax consistency with malloc
-
- #include <string.h> // memcpy
- #include <stdio.h> // printf
- #include <stdlib.h> // malloc
- #include <assert.h> // assert
typedef struct {ssize_t size; char *row; int count;} slot;
slot line;
slot *text;
int main(void)
{
- leng = 10; int numb;
+ int leng = 10;
text = malloc(leng*sizeof(slot));
int textmax = (int) (text + leng - 1);
int textmin = (int) (text + 0);
line.row = NULL;
line.size = 0;
- int i; for(i = 0; i < leng+1; i++) //deliberate overrun
+ int iy; for(iy = 0; iy < leng+1; iy++) //deliberate iy overrun
? + + + + +++
{
- printf("%d text = %p\n",i,text+i);
+ printf("%d text = %p\n",iy,text+iy);
? + +
+ int texndx; textbound;
- numb = (int) (text+i);
- printf("%d numb = %x\n",i,numb);
- assert(textmin <= numb); assert(textmax >= numb);
- *(text+i) = line;
? -- ^ ^
+ text[iy] = line;
? ^ ^^
}
printf("test run ending\n");
return 0;
} | 21 | 0.583333 | 7 | 14 |
62477f076d73f7f47eba2aa674012a5abf43f4d9 | website/src/_includes/footer.html | website/src/_includes/footer.html | <hr>
<div class="row">
<div class="col-xs-12">
<footer>
<p class="text-center">© Copyright 2016
<a href="http://www.apache.org">The Apache Software Foundation.</a> All Rights Reserved.</p>
<p class="text-center"><a href="{{ site.baseurl }}/privacy_policy">Privacy Policy</a> |
<a href="{{ "/feed.xml" | prepend: site.baseurl }}">RSS Feed</a></p>
</footer>
</div>
</div>
<!-- container div end -->
</div>
| <hr>
<div class="row">
<div class="col-xs-12">
<footer>
<p class="text-center">
© Copyright
<a href="http://www.apache.org">The Apache Software Foundation</a>,
{{ 'now' | date: "%Y" }}. All Rights Reserved.
</p>
<p class="text-center">
<a href="{{ site.baseurl }}/privacy_policy">Privacy Policy</a> |
<a href="{{ "/feed.xml" | prepend: site.baseurl }}">RSS Feed</a>
</p>
</footer>
</div>
</div>
<!-- container div end -->
</div>
| Update copyright on each page | Update copyright on each page
Update year, fix ordering, make it automatically update. | HTML | apache-2.0 | RyanSkraba/beam,lukecwik/incubator-beam,chamikaramj/beam,apache/beam,RyanSkraba/beam,lukecwik/incubator-beam,robertwb/incubator-beam,apache/beam,apache/beam,chamikaramj/beam,rangadi/beam,lukecwik/incubator-beam,charlesccychen/beam,mxm/incubator-beam,rangadi/incubator-beam,rangadi/beam,chamikaramj/beam,robertwb/incubator-beam,mxm/incubator-beam,iemejia/incubator-beam,robertwb/incubator-beam,rangadi/beam,apache/beam,chamikaramj/beam,lukecwik/incubator-beam,robertwb/incubator-beam,rangadi/beam,rangadi/incubator-beam,lukecwik/incubator-beam,markflyhigh/incubator-beam,chamikaramj/beam,lukecwik/incubator-beam,lukecwik/incubator-beam,RyanSkraba/beam,charlesccychen/incubator-beam,markflyhigh/incubator-beam,markflyhigh/incubator-beam,RyanSkraba/beam,rangadi/beam,chamikaramj/beam,lukecwik/incubator-beam,robertwb/incubator-beam,RyanSkraba/beam,apache/beam,apache/beam,apache/beam,charlesccychen/beam,charlesccychen/incubator-beam,apache/beam,apache/beam,chamikaramj/beam,RyanSkraba/beam,robertwb/incubator-beam,markflyhigh/incubator-beam,charlesccychen/incubator-beam,markflyhigh/incubator-beam,iemejia/incubator-beam,markflyhigh/incubator-beam,markflyhigh/incubator-beam,rangadi/beam,chamikaramj/beam,robertwb/incubator-beam,robertwb/incubator-beam,charlesccychen/beam,lukecwik/incubator-beam,lukecwik/incubator-beam,chamikaramj/beam,apache/beam,rangadi/incubator-beam,charlesccychen/beam,apache/beam,chamikaramj/beam,charlesccychen/beam,RyanSkraba/beam,charlesccychen/beam,robertwb/incubator-beam,robertwb/incubator-beam,charlesccychen/beam,rangadi/beam | html | ## Code Before:
<hr>
<div class="row">
<div class="col-xs-12">
<footer>
<p class="text-center">© Copyright 2016
<a href="http://www.apache.org">The Apache Software Foundation.</a> All Rights Reserved.</p>
<p class="text-center"><a href="{{ site.baseurl }}/privacy_policy">Privacy Policy</a> |
<a href="{{ "/feed.xml" | prepend: site.baseurl }}">RSS Feed</a></p>
</footer>
</div>
</div>
<!-- container div end -->
</div>
## Instruction:
Update copyright on each page
Update year, fix ordering, make it automatically update.
## Code After:
<hr>
<div class="row">
<div class="col-xs-12">
<footer>
<p class="text-center">
© Copyright
<a href="http://www.apache.org">The Apache Software Foundation</a>,
{{ 'now' | date: "%Y" }}. All Rights Reserved.
</p>
<p class="text-center">
<a href="{{ site.baseurl }}/privacy_policy">Privacy Policy</a> |
<a href="{{ "/feed.xml" | prepend: site.baseurl }}">RSS Feed</a>
</p>
</footer>
</div>
</div>
<!-- container div end -->
</div>
| <hr>
<div class="row">
<div class="col-xs-12">
<footer>
- <p class="text-center">© Copyright 2016
? ---------------------
+ <p class="text-center">
+ © Copyright
- <a href="http://www.apache.org">The Apache Software Foundation.</a> All Rights Reserved.</p>
? - ^^^^^^^^^^^^^^^^^^^^^^^^^
+ <a href="http://www.apache.org">The Apache Software Foundation</a>,
? ^
+ {{ 'now' | date: "%Y" }}. All Rights Reserved.
+ </p>
+ <p class="text-center">
- <p class="text-center"><a href="{{ site.baseurl }}/privacy_policy">Privacy Policy</a> |
? -----------------------
+ <a href="{{ site.baseurl }}/privacy_policy">Privacy Policy</a> |
- <a href="{{ "/feed.xml" | prepend: site.baseurl }}">RSS Feed</a></p>
? ----
+ <a href="{{ "/feed.xml" | prepend: site.baseurl }}">RSS Feed</a>
+ </p>
</footer>
</div>
</div>
<!-- container div end -->
</div> | 13 | 1 | 9 | 4 |
c468d66b8f6cc4bb75994cda2ef8abe4a0d9d3b0 | ci/tasks/build-binaries.yml | ci/tasks/build-binaries.yml | platform: linux
image: docker:///cloudfoundry/cli-ci
inputs:
- name: cli
path: gopath/src/github.com/cloudfoundry/cli
outputs:
- name: cross-compiled
run:
path: bash
args:
- -c
- |
set -ex
cwd=$PWD
export GOPATH=$PWD/gopath
export PATH=$GOPATH/bin:$PATH
go version
pushd $GOPATH/src/github.com/cloudfoundry/cli
bin/replace-sha
echo "Building 32-bit Linux"
GOARCH=386 GOOS=linux go build -ldflags '-extldflags "-static"' -o out/cf-cli_linux_i686 ./main
echo "Building 32-bit Windows"
GOARCH=386 GOOS=windows go build -o out/cf-cli_win32.exe ./main
echo "Building 64-bit Linux"
GOARCH=amd64 GOOS=linux go build -ldflags '-extldflags "-static"' -o out/cf-cli_linux_x86-64 ./main
echo "Building 64-bit Windows"
GOARCH=amd64 GOOS=windows go build -o out/cf-cli_winx64.exe ./main
echo "Creating tarball"
tar -cvzf $cwd/cross-compiled/cf-cli-binaries.tgz -C out .
popd
| platform: linux
image: docker:///cloudfoundry/cli-ci
inputs:
- name: cli
path: gopath/src/github.com/cloudfoundry/cli
outputs:
- name: cross-compiled
run:
path: bash
args:
- -c
- |
set -ex
cwd=$PWD
export GOPATH=$PWD/gopath
export PATH=$GOPATH/bin:$PATH
go version
pushd $GOPATH/src/github.com/cloudfoundry/cli
bin/replace-sha
echo "Building 32-bit Linux"
CGO_ENABLED=0 GOARCH=386 GOOS=linux go build -a -tags netgo -installsuffix netgo -ldflags '-extldflags "-static"' -o out/cf-cli_linux_i686 ./main
echo "Building 32-bit Windows"
GOARCH=386 GOOS=windows go build -o out/cf-cli_win32.exe ./main
echo "Building 64-bit Linux"
CGO_ENABLED=0 GOARCH=amd64 GOOS=linux go build -a -tags netgo -installsuffix netgo -ldflags '-extldflags "-static"' -o out/cf-cli_linux_x86-64 ./main
echo "Building 64-bit Windows"
GOARCH=amd64 GOOS=windows go build -o out/cf-cli_winx64.exe ./main
echo "Creating tarball"
tar -cvzf $cwd/cross-compiled/cf-cli-binaries.tgz -C out .
popd
| Use all these magic flags to build static binaries | Use all these magic flags to build static binaries
Even though the CLI was forcing static linking of C libraries, it
appears that this was not fully working. Through further investigation,
and the recommendation of
https://tschottdorf.github.io/linking-golang-go-statically-cgo-testing/
we added several flags that should force the use of golang's internal
networking libraries (netgo) and should not call out to C.
[Finishes #119703447, 120437611] (Github issue #843, #848)
| YAML | apache-2.0 | fujitsu-cf/cli,fujitsu-cf/cli,simonleung8/cli,hyenaspots/cli,markstgodard/cli,markstgodard/cli,fujitsu-cf/cli,markstgodard/cli,markstgodard/cli,simonleung8/cli,hyenaspots/cli,simonleung8/cli,hyenaspots/cli,hyenaspots/cli | yaml | ## Code Before:
platform: linux
image: docker:///cloudfoundry/cli-ci
inputs:
- name: cli
path: gopath/src/github.com/cloudfoundry/cli
outputs:
- name: cross-compiled
run:
path: bash
args:
- -c
- |
set -ex
cwd=$PWD
export GOPATH=$PWD/gopath
export PATH=$GOPATH/bin:$PATH
go version
pushd $GOPATH/src/github.com/cloudfoundry/cli
bin/replace-sha
echo "Building 32-bit Linux"
GOARCH=386 GOOS=linux go build -ldflags '-extldflags "-static"' -o out/cf-cli_linux_i686 ./main
echo "Building 32-bit Windows"
GOARCH=386 GOOS=windows go build -o out/cf-cli_win32.exe ./main
echo "Building 64-bit Linux"
GOARCH=amd64 GOOS=linux go build -ldflags '-extldflags "-static"' -o out/cf-cli_linux_x86-64 ./main
echo "Building 64-bit Windows"
GOARCH=amd64 GOOS=windows go build -o out/cf-cli_winx64.exe ./main
echo "Creating tarball"
tar -cvzf $cwd/cross-compiled/cf-cli-binaries.tgz -C out .
popd
## Instruction:
Use all these magic flags to build static binaries
Even though the CLI was forcing static linking of C libraries, it
appears that this was not fully working. Through further investigation,
and the recommendation of
https://tschottdorf.github.io/linking-golang-go-statically-cgo-testing/
we added several flags that should force the use of golang's internal
networking libraries (netgo) and should not call out to C.
[Finishes #119703447, 120437611] (Github issue #843, #848)
## Code After:
platform: linux
image: docker:///cloudfoundry/cli-ci
inputs:
- name: cli
path: gopath/src/github.com/cloudfoundry/cli
outputs:
- name: cross-compiled
run:
path: bash
args:
- -c
- |
set -ex
cwd=$PWD
export GOPATH=$PWD/gopath
export PATH=$GOPATH/bin:$PATH
go version
pushd $GOPATH/src/github.com/cloudfoundry/cli
bin/replace-sha
echo "Building 32-bit Linux"
CGO_ENABLED=0 GOARCH=386 GOOS=linux go build -a -tags netgo -installsuffix netgo -ldflags '-extldflags "-static"' -o out/cf-cli_linux_i686 ./main
echo "Building 32-bit Windows"
GOARCH=386 GOOS=windows go build -o out/cf-cli_win32.exe ./main
echo "Building 64-bit Linux"
CGO_ENABLED=0 GOARCH=amd64 GOOS=linux go build -a -tags netgo -installsuffix netgo -ldflags '-extldflags "-static"' -o out/cf-cli_linux_x86-64 ./main
echo "Building 64-bit Windows"
GOARCH=amd64 GOOS=windows go build -o out/cf-cli_winx64.exe ./main
echo "Creating tarball"
tar -cvzf $cwd/cross-compiled/cf-cli-binaries.tgz -C out .
popd
| platform: linux
image: docker:///cloudfoundry/cli-ci
inputs:
- name: cli
path: gopath/src/github.com/cloudfoundry/cli
outputs:
- name: cross-compiled
run:
path: bash
args:
- -c
- |
set -ex
cwd=$PWD
export GOPATH=$PWD/gopath
export PATH=$GOPATH/bin:$PATH
go version
pushd $GOPATH/src/github.com/cloudfoundry/cli
bin/replace-sha
echo "Building 32-bit Linux"
- GOARCH=386 GOOS=linux go build -ldflags '-extldflags "-static"' -o out/cf-cli_linux_i686 ./main
+ CGO_ENABLED=0 GOARCH=386 GOOS=linux go build -a -tags netgo -installsuffix netgo -ldflags '-extldflags "-static"' -o out/cf-cli_linux_i686 ./main
? ++++++++++++++ ++++++++++++++++++++++++++++++++++++
echo "Building 32-bit Windows"
GOARCH=386 GOOS=windows go build -o out/cf-cli_win32.exe ./main
echo "Building 64-bit Linux"
- GOARCH=amd64 GOOS=linux go build -ldflags '-extldflags "-static"' -o out/cf-cli_linux_x86-64 ./main
+ CGO_ENABLED=0 GOARCH=amd64 GOOS=linux go build -a -tags netgo -installsuffix netgo -ldflags '-extldflags "-static"' -o out/cf-cli_linux_x86-64 ./main
? ++++++++++++++ ++++++++++++++++++++++++++++++++++++
echo "Building 64-bit Windows"
GOARCH=amd64 GOOS=windows go build -o out/cf-cli_winx64.exe ./main
echo "Creating tarball"
tar -cvzf $cwd/cross-compiled/cf-cli-binaries.tgz -C out .
popd | 4 | 0.095238 | 2 | 2 |
2046e76ba0fa02e17a39c8d82838cecadb9b90d6 | bin/modules/validateAddPackages.js | bin/modules/validateAddPackages.js | /**
* Ensures that the label package file actually exists
* @param {String} path - path to the json file label package
* @return {Bool || Error} this is a try-catch where the error
*/
"use strict";
const fs = require("fs");
const removeAll = require("../utils/removeAll");
module.exports = (path) => {
try {
if (path.indexOf(".json") < 0) throw "Not a JSON file";
let packagePath = path.indexOf("/") === 0 ? path.replace("/","") : path;
packagePath = removeAll( packagePath, [ "`", '"', "'" ] );
if ( fs.statSync( process.cwd()+"/"+packagePath ) ){
return true;
}
} catch (e){
return e;
}
};
| /**
* Ensures that the label package file actually exists
* @param {String} path - path to the json file label package
* @return {Bool || Error} this is a try-catch where the error
*/
"use strict";
const fs = require("fs");
const removeAll = require("../utils/removeAll");
const isJsonString = function (str) {
try {
JSON.parse(str);
} catch (e) {
return false;
}
return true;
};
module.exports = (path) => {
try {
if (path.indexOf(".json") < 0) throw "Not a JSON file";
let packagePath = path.indexOf("/") === 0 ? path.replace("/","") : path;
packagePath = removeAll( packagePath, [ "`", '"', "'" ] );
let fullPath = process.cwd() + "/" + packagePath;
fs.readFile(fullPath, (err, data) => {
if (err) {
throw err;
}
if (isJsonString(data)) {
return true;
}
throw "Not a valid JSON file";
});
} catch (e){
return e;
}
};
| Check json structure rather than extension | Check json structure rather than extension
| JavaScript | mit | himynameisdave/git-labelmaker | javascript | ## Code Before:
/**
* Ensures that the label package file actually exists
* @param {String} path - path to the json file label package
* @return {Bool || Error} this is a try-catch where the error
*/
"use strict";
const fs = require("fs");
const removeAll = require("../utils/removeAll");
module.exports = (path) => {
try {
if (path.indexOf(".json") < 0) throw "Not a JSON file";
let packagePath = path.indexOf("/") === 0 ? path.replace("/","") : path;
packagePath = removeAll( packagePath, [ "`", '"', "'" ] );
if ( fs.statSync( process.cwd()+"/"+packagePath ) ){
return true;
}
} catch (e){
return e;
}
};
## Instruction:
Check json structure rather than extension
## Code After:
/**
* Ensures that the label package file actually exists
* @param {String} path - path to the json file label package
* @return {Bool || Error} this is a try-catch where the error
*/
"use strict";
const fs = require("fs");
const removeAll = require("../utils/removeAll");
const isJsonString = function (str) {
try {
JSON.parse(str);
} catch (e) {
return false;
}
return true;
};
module.exports = (path) => {
try {
if (path.indexOf(".json") < 0) throw "Not a JSON file";
let packagePath = path.indexOf("/") === 0 ? path.replace("/","") : path;
packagePath = removeAll( packagePath, [ "`", '"', "'" ] );
let fullPath = process.cwd() + "/" + packagePath;
fs.readFile(fullPath, (err, data) => {
if (err) {
throw err;
}
if (isJsonString(data)) {
return true;
}
throw "Not a valid JSON file";
});
} catch (e){
return e;
}
};
| /**
* Ensures that the label package file actually exists
* @param {String} path - path to the json file label package
* @return {Bool || Error} this is a try-catch where the error
*/
"use strict";
const fs = require("fs");
const removeAll = require("../utils/removeAll");
+ const isJsonString = function (str) {
+ try {
+ JSON.parse(str);
+ } catch (e) {
+ return false;
+ }
+ return true;
+ };
+
module.exports = (path) => {
try {
if (path.indexOf(".json") < 0) throw "Not a JSON file";
let packagePath = path.indexOf("/") === 0 ? path.replace("/","") : path;
packagePath = removeAll( packagePath, [ "`", '"', "'" ] );
- if ( fs.statSync( process.cwd()+"/"+packagePath ) ){
+
+ let fullPath = process.cwd() + "/" + packagePath;
+
+ fs.readFile(fullPath, (err, data) => {
+ if (err) {
+ throw err;
+ }
+
+ if (isJsonString(data)) {
- return true;
+ return true;
? ++
- }
+ }
? ++
+
+ throw "Not a valid JSON file";
+ });
} catch (e){
return e;
}
}; | 26 | 1.238095 | 23 | 3 |
8f0ebdbb7aeaf5ff85566455dc6065e2f5a7b004 | csunplugged/docker-development-entrypoint.sh | csunplugged/docker-development-entrypoint.sh |
function postgres_ready(){
/docker_venv/bin/python << END
import sys
import psycopg2
try:
conn = psycopg2.connect(dbname="postgres", user="postgres", host="localhost")
except psycopg2.OperationalError:
sys.exit(-1)
sys.exit(0)
END
}
until postgres_ready; do
>&2 echo "Postgres is unavailable - sleeping"
sleep 1
done
>&2 echo "Postgres is up - continuing..."
# Start gunicorn service
echo "Starting gunicorn"
/docker_venv/bin/gunicorn -c ./gunicorn.conf.py -b :$PORT config.wsgi --reload
|
function postgres_ready(){
/docker_venv/bin/python << END
import sys
import psycopg2
try:
conn = psycopg2.connect(dbname="postgres", user="postgres", host="localhost", port="5434")
except psycopg2.OperationalError:
sys.exit(-1)
sys.exit(0)
END
}
until postgres_ready; do
>&2 echo "Postgres is unavailable - sleeping"
sleep 1
done
>&2 echo "Postgres is up - continuing..."
# Start gunicorn service
echo "Starting gunicorn"
/docker_venv/bin/gunicorn -c ./gunicorn.conf.py -b :$PORT config.wsgi --reload
| Set Docker entrypoint script to check new Postgres port | Set Docker entrypoint script to check new Postgres port
| Shell | mit | uccser/cs-unplugged,uccser/cs-unplugged,uccser/cs-unplugged,uccser/cs-unplugged | shell | ## Code Before:
function postgres_ready(){
/docker_venv/bin/python << END
import sys
import psycopg2
try:
conn = psycopg2.connect(dbname="postgres", user="postgres", host="localhost")
except psycopg2.OperationalError:
sys.exit(-1)
sys.exit(0)
END
}
until postgres_ready; do
>&2 echo "Postgres is unavailable - sleeping"
sleep 1
done
>&2 echo "Postgres is up - continuing..."
# Start gunicorn service
echo "Starting gunicorn"
/docker_venv/bin/gunicorn -c ./gunicorn.conf.py -b :$PORT config.wsgi --reload
## Instruction:
Set Docker entrypoint script to check new Postgres port
## Code After:
function postgres_ready(){
/docker_venv/bin/python << END
import sys
import psycopg2
try:
conn = psycopg2.connect(dbname="postgres", user="postgres", host="localhost", port="5434")
except psycopg2.OperationalError:
sys.exit(-1)
sys.exit(0)
END
}
until postgres_ready; do
>&2 echo "Postgres is unavailable - sleeping"
sleep 1
done
>&2 echo "Postgres is up - continuing..."
# Start gunicorn service
echo "Starting gunicorn"
/docker_venv/bin/gunicorn -c ./gunicorn.conf.py -b :$PORT config.wsgi --reload
|
function postgres_ready(){
/docker_venv/bin/python << END
import sys
import psycopg2
try:
- conn = psycopg2.connect(dbname="postgres", user="postgres", host="localhost")
+ conn = psycopg2.connect(dbname="postgres", user="postgres", host="localhost", port="5434")
? +++++++++++++
except psycopg2.OperationalError:
sys.exit(-1)
sys.exit(0)
END
}
until postgres_ready; do
>&2 echo "Postgres is unavailable - sleeping"
sleep 1
done
>&2 echo "Postgres is up - continuing..."
# Start gunicorn service
echo "Starting gunicorn"
/docker_venv/bin/gunicorn -c ./gunicorn.conf.py -b :$PORT config.wsgi --reload | 2 | 0.086957 | 1 | 1 |
66cd2b20a03fda31fd648930fce4f7fff60e8ef7 | index.js | index.js | "use strict";
require('async-to-gen/register')
const restify = require('restify');
var server = restify.createServer();
server.use(restify.CORS({
credentials: true
}));
server.use(restify.CORS());
server.post('/-/login', restify.bodyParser(), require('./login'));
server.get('/-/files/:team/:user/:file', require('./serve-file'));
server.get('/-/metadata/:team/:user/:file', require('./metadata'));
server.get('/-/session/:session', require('./session'));
server.get('/-/files.list', require('./list')());
server.post('/-/upload', require('./upload')())
server.opts('/-/upload', (req, res, next) => {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Headers', 'Origin, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, Authorization');
res.setHeader('Access-Control-Allow-Methods', '*');
res.send(200)
next()
})
server.listen(process.env.PORT || 3001, function() {
console.log('%s listening at %s', server.name, server.url);
});
| "use strict";
require('async-to-gen/register')
const restify = require('restify');
var server = restify.createServer();
server.use(restify.CORS({
credentials: true
}));
server.use(restify.CORS());
server.post('/-/login', restify.bodyParser(), require('./login'));
server.get('/-/files/:team/:user/:file', require('./serve-file'));
server.get('/-/metadata/:team/:user/:file', require('./metadata'));
server.get('/-/session/:session', require('./session'));
server.get('/-/files.list', require('./list')());
server.opts('/-/files.list', allowCORS)
server.post('/-/upload', require('./upload')())
server.opts('/-/upload', allowCORS)
function allowCORS(req, res, next) {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Headers', 'Origin, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, Authorization');
res.setHeader('Access-Control-Allow-Methods', '*');
res.send(200)
next()
}
server.listen(process.env.PORT || 3001, function() {
console.log('%s listening at %s', server.name, server.url);
});
| Fix CORS for list response | Fix CORS for list response
| JavaScript | isc | lgbtq-technology/lgbtq-helper-api | javascript | ## Code Before:
"use strict";
require('async-to-gen/register')
const restify = require('restify');
var server = restify.createServer();
server.use(restify.CORS({
credentials: true
}));
server.use(restify.CORS());
server.post('/-/login', restify.bodyParser(), require('./login'));
server.get('/-/files/:team/:user/:file', require('./serve-file'));
server.get('/-/metadata/:team/:user/:file', require('./metadata'));
server.get('/-/session/:session', require('./session'));
server.get('/-/files.list', require('./list')());
server.post('/-/upload', require('./upload')())
server.opts('/-/upload', (req, res, next) => {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Headers', 'Origin, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, Authorization');
res.setHeader('Access-Control-Allow-Methods', '*');
res.send(200)
next()
})
server.listen(process.env.PORT || 3001, function() {
console.log('%s listening at %s', server.name, server.url);
});
## Instruction:
Fix CORS for list response
## Code After:
"use strict";
require('async-to-gen/register')
const restify = require('restify');
var server = restify.createServer();
server.use(restify.CORS({
credentials: true
}));
server.use(restify.CORS());
server.post('/-/login', restify.bodyParser(), require('./login'));
server.get('/-/files/:team/:user/:file', require('./serve-file'));
server.get('/-/metadata/:team/:user/:file', require('./metadata'));
server.get('/-/session/:session', require('./session'));
server.get('/-/files.list', require('./list')());
server.opts('/-/files.list', allowCORS)
server.post('/-/upload', require('./upload')())
server.opts('/-/upload', allowCORS)
function allowCORS(req, res, next) {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Headers', 'Origin, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, Authorization');
res.setHeader('Access-Control-Allow-Methods', '*');
res.send(200)
next()
}
server.listen(process.env.PORT || 3001, function() {
console.log('%s listening at %s', server.name, server.url);
});
| "use strict";
require('async-to-gen/register')
const restify = require('restify');
var server = restify.createServer();
server.use(restify.CORS({
credentials: true
}));
server.use(restify.CORS());
server.post('/-/login', restify.bodyParser(), require('./login'));
server.get('/-/files/:team/:user/:file', require('./serve-file'));
server.get('/-/metadata/:team/:user/:file', require('./metadata'));
server.get('/-/session/:session', require('./session'));
server.get('/-/files.list', require('./list')());
+ server.opts('/-/files.list', allowCORS)
server.post('/-/upload', require('./upload')())
- server.opts('/-/upload', (req, res, next) => {
+ server.opts('/-/upload', allowCORS)
+
+ function allowCORS(req, res, next) {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Headers', 'Origin, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, Authorization');
res.setHeader('Access-Control-Allow-Methods', '*');
res.send(200)
next()
- })
+ }
server.listen(process.env.PORT || 3001, function() {
console.log('%s listening at %s', server.name, server.url);
}); | 7 | 0.2 | 5 | 2 |
c39d356d6d196907394c564fbf2b61f9c1254422 | source/index.html | source/index.html | ---
layout: default
title: Home
post_class: page-template
slug: home
---
<article>
<a href="http://panz.io" class="post alert txt-center">
<h2>Note: This website's url has recently changed from panzarino.me to panz.io. Please update dependencies accordingly.</h2>
</a>
</article>
{% for post in paginator.posts %}
{% include article.html %}
{% endfor %}
{% include pagination.html %}
| ---
layout: default
title: Home
post_class: page-template
slug: home
---
<article>
<a class="post alert txt-center">
<h2>Note: This website's url has recently changed from panzarino.me to panz.io. Please update dependencies accordingly.</h2>
</a>
</article>
{% for post in paginator.posts %}
{% include article.html %}
{% endfor %}
{% include pagination.html %}
| Remove href from warning message | Remove href from warning message
| HTML | mit | zachpanz88/zachpanz88.github.io,zachpanz88/zachpanz88.github.io | html | ## Code Before:
---
layout: default
title: Home
post_class: page-template
slug: home
---
<article>
<a href="http://panz.io" class="post alert txt-center">
<h2>Note: This website's url has recently changed from panzarino.me to panz.io. Please update dependencies accordingly.</h2>
</a>
</article>
{% for post in paginator.posts %}
{% include article.html %}
{% endfor %}
{% include pagination.html %}
## Instruction:
Remove href from warning message
## Code After:
---
layout: default
title: Home
post_class: page-template
slug: home
---
<article>
<a class="post alert txt-center">
<h2>Note: This website's url has recently changed from panzarino.me to panz.io. Please update dependencies accordingly.</h2>
</a>
</article>
{% for post in paginator.posts %}
{% include article.html %}
{% endfor %}
{% include pagination.html %}
| ---
layout: default
title: Home
post_class: page-template
slug: home
---
<article>
- <a href="http://panz.io" class="post alert txt-center">
? ----------------------
+ <a class="post alert txt-center">
<h2>Note: This website's url has recently changed from panzarino.me to panz.io. Please update dependencies accordingly.</h2>
</a>
</article>
{% for post in paginator.posts %}
{% include article.html %}
{% endfor %}
{% include pagination.html %} | 2 | 0.111111 | 1 | 1 |
78b4ab0eaf829b0318496f8f14777ae84c0263fc | src/run-header-components.js | src/run-header-components.js | import { select } from 'd3-selection'
export function createRunHeaderComponents() {
function runHeaderComponents(s) {
s.selectAll('.zambezi-grid-headers .zambezi-grid-header')
.each(runComponents)
}
return runHeaderComponents
function runComponents(d, i) {
const components = d.headerComponents
, target = d3.select(this)
if (!components) return
components.forEach(component => target.each(component))
}
}
| import { select } from 'd3-selection'
import { selectionChanged, rebind } from '@zambezi/d3-utils'
export function createRunHeaderComponents() {
const changed = selectionChanged().key(columnChangeKey)
const api = rebind().from(changed, 'key')
function runHeaderComponents(s) {
s.selectAll('.zambezi-grid-headers .zambezi-grid-header')
.select(changed)
.each(runComponents)
}
return api(runHeaderComponents)
function runComponents(d, i) {
const components = d.headerComponents
, target = d3.select(this)
if (!components) return
components.forEach(component => target.each(component))
}
}
function columnChangeKey(column) {
return [
column.id
, column.label || '·'
, column.key || '·'
, ~~column.offset
, ~~column.absoluteOffset
, ~~column.width
, column.sortAscending || '·'
, column.sortDescending || '·'
]
.concat(
column.children ?
( '(' + column.children.map(columnChangeKey).join(',') + ')' )
: []
)
.join('|')
}
| Implement optionally running header components only on column change | Implement optionally running header components only on column change
| JavaScript | mit | zambezi/grid-components | javascript | ## Code Before:
import { select } from 'd3-selection'
export function createRunHeaderComponents() {
function runHeaderComponents(s) {
s.selectAll('.zambezi-grid-headers .zambezi-grid-header')
.each(runComponents)
}
return runHeaderComponents
function runComponents(d, i) {
const components = d.headerComponents
, target = d3.select(this)
if (!components) return
components.forEach(component => target.each(component))
}
}
## Instruction:
Implement optionally running header components only on column change
## Code After:
import { select } from 'd3-selection'
import { selectionChanged, rebind } from '@zambezi/d3-utils'
export function createRunHeaderComponents() {
const changed = selectionChanged().key(columnChangeKey)
const api = rebind().from(changed, 'key')
function runHeaderComponents(s) {
s.selectAll('.zambezi-grid-headers .zambezi-grid-header')
.select(changed)
.each(runComponents)
}
return api(runHeaderComponents)
function runComponents(d, i) {
const components = d.headerComponents
, target = d3.select(this)
if (!components) return
components.forEach(component => target.each(component))
}
}
function columnChangeKey(column) {
return [
column.id
, column.label || '·'
, column.key || '·'
, ~~column.offset
, ~~column.absoluteOffset
, ~~column.width
, column.sortAscending || '·'
, column.sortDescending || '·'
]
.concat(
column.children ?
( '(' + column.children.map(columnChangeKey).join(',') + ')' )
: []
)
.join('|')
}
| import { select } from 'd3-selection'
+ import { selectionChanged, rebind } from '@zambezi/d3-utils'
export function createRunHeaderComponents() {
+ const changed = selectionChanged().key(columnChangeKey)
+ const api = rebind().from(changed, 'key')
+
function runHeaderComponents(s) {
s.selectAll('.zambezi-grid-headers .zambezi-grid-header')
+ .select(changed)
.each(runComponents)
}
- return runHeaderComponents
+ return api(runHeaderComponents)
? ++++ +
function runComponents(d, i) {
const components = d.headerComponents
, target = d3.select(this)
if (!components) return
components.forEach(component => target.each(component))
}
}
+
+ function columnChangeKey(column) {
+ return [
+ column.id
+ , column.label || '·'
+ , column.key || '·'
+ , ~~column.offset
+ , ~~column.absoluteOffset
+ , ~~column.width
+ , column.sortAscending || '·'
+ , column.sortDescending || '·'
+ ]
+ .concat(
+ column.children ?
+ ( '(' + column.children.map(columnChangeKey).join(',') + ')' )
+ : []
+ )
+ .join('|')
+ } | 26 | 1.368421 | 25 | 1 |
b34185cbab60cdfcac7a3279eee218bd8e2dd3e1 | docker-compose.yml | docker-compose.yml | version: '2.1'
services:
app:
build: .
restart: unless-stopped
env_file: .env
command: gulp watch
volumes:
- ./www/img:/opt/app/www/img
- ./www/js:/opt/app/www/js
- ./www/templates:/opt/app/www/templates
- ./www/dist:/opt/app/www/dist
- ./gulp:/opt/app/gulp
- ./releases:/opt/app/releases
- ./google-services.json:/opt/app/platforms/android/google-services.json
- ./eff-alerts.keystore:/opt/app/eff-alerts.keystore
ports:
- '4001:4001'
| version: '2.1'
services:
app:
build: .
restart: unless-stopped
env_file: .env
command: gulp watch
volumes:
- ./config:/opt/app/config
- ./www/img:/opt/app/www/img
- ./www/js:/opt/app/www/js
- ./www/templates:/opt/app/www/templates
- ./www/dist:/opt/app/www/dist
- ./gulp:/opt/app/gulp
- ./releases:/opt/app/releases
- ./google-services.json:/opt/app/platforms/android/google-services.json
- ./eff-alerts.keystore:/opt/app/eff-alerts.keystore
ports:
- '4001:4001'
| Add ./config to docker compose volumes | Add ./config to docker compose volumes
| YAML | agpl-3.0 | EFForg/actioncenter-mobile,EFForg/actioncenter-mobile,EFForg/actioncenter-mobile | yaml | ## Code Before:
version: '2.1'
services:
app:
build: .
restart: unless-stopped
env_file: .env
command: gulp watch
volumes:
- ./www/img:/opt/app/www/img
- ./www/js:/opt/app/www/js
- ./www/templates:/opt/app/www/templates
- ./www/dist:/opt/app/www/dist
- ./gulp:/opt/app/gulp
- ./releases:/opt/app/releases
- ./google-services.json:/opt/app/platforms/android/google-services.json
- ./eff-alerts.keystore:/opt/app/eff-alerts.keystore
ports:
- '4001:4001'
## Instruction:
Add ./config to docker compose volumes
## Code After:
version: '2.1'
services:
app:
build: .
restart: unless-stopped
env_file: .env
command: gulp watch
volumes:
- ./config:/opt/app/config
- ./www/img:/opt/app/www/img
- ./www/js:/opt/app/www/js
- ./www/templates:/opt/app/www/templates
- ./www/dist:/opt/app/www/dist
- ./gulp:/opt/app/gulp
- ./releases:/opt/app/releases
- ./google-services.json:/opt/app/platforms/android/google-services.json
- ./eff-alerts.keystore:/opt/app/eff-alerts.keystore
ports:
- '4001:4001'
| version: '2.1'
services:
app:
build: .
restart: unless-stopped
env_file: .env
command: gulp watch
volumes:
+ - ./config:/opt/app/config
- ./www/img:/opt/app/www/img
- ./www/js:/opt/app/www/js
- ./www/templates:/opt/app/www/templates
- ./www/dist:/opt/app/www/dist
- ./gulp:/opt/app/gulp
- ./releases:/opt/app/releases
- ./google-services.json:/opt/app/platforms/android/google-services.json
- ./eff-alerts.keystore:/opt/app/eff-alerts.keystore
ports:
- '4001:4001' | 1 | 0.05 | 1 | 0 |
eab612142c2621d85b17ce212cdc362951976c58 | README.md | README.md | Google spreadsheet parsing for Open Event JSON
| Google spreadsheet parsing for Open Event JSON
## setup
```shell
pip install -r requirements.txt
python scraper.py
```
Requires the tsv file to be present for each track. Look into source code for details
## License
[MIT](/.LICENSE)
| Add some intro in Readme | Add some intro in Readme
| Markdown | mit | fossasia/open-event-scraper,fossasia/open-event-scraper,fossasia/open-event-scraper | markdown | ## Code Before:
Google spreadsheet parsing for Open Event JSON
## Instruction:
Add some intro in Readme
## Code After:
Google spreadsheet parsing for Open Event JSON
## setup
```shell
pip install -r requirements.txt
python scraper.py
```
Requires the tsv file to be present for each track. Look into source code for details
## License
[MIT](/.LICENSE)
| Google spreadsheet parsing for Open Event JSON
+
+ ## setup
+
+ ```shell
+ pip install -r requirements.txt
+ python scraper.py
+ ```
+
+ Requires the tsv file to be present for each track. Look into source code for details
+
+ ## License
+
+ [MIT](/.LICENSE) | 13 | 13 | 13 | 0 |
5b4fae30f46a0004e9b6fec5abc2807a9d7c043e | main.go | main.go | package main
import (
"encoding/json"
"log"
"net/http"
"os"
"cjdavis.me/elysium/services"
)
func main() {
http.HandleFunc("/", handler)
port := os.Getenv("PORT")
if port == "" {
port = "9090"
}
log.Printf("Elysium listening on port %s", port)
http.ListenAndServe(":"+port, nil)
}
func handler(w http.ResponseWriter, r *http.Request) {
p := services.GetProfileService().GetProfile()
js, err := json.Marshal(p)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.Write(js)
}
| package main
import (
"encoding/json"
"log"
"net/http"
"os"
"github.com/julienschmidt/httprouter"
"cjdavis.me/elysium/services"
)
func main() {
router := httprouter.New()
router.GET("/", handler)
port := os.Getenv("PORT")
if port == "" {
port = "9090"
}
log.Printf("Elysium listening on port %s", port)
http.ListenAndServe(":"+port, router)
}
func handler(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
p := services.GetProfileService().GetProfile()
js, err := json.Marshal(p)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.Write(js)
}
| Use Julien Schmidt's http router | Use Julien Schmidt's http router
| Go | mit | Crevax/Elysium | go | ## Code Before:
package main
import (
"encoding/json"
"log"
"net/http"
"os"
"cjdavis.me/elysium/services"
)
func main() {
http.HandleFunc("/", handler)
port := os.Getenv("PORT")
if port == "" {
port = "9090"
}
log.Printf("Elysium listening on port %s", port)
http.ListenAndServe(":"+port, nil)
}
func handler(w http.ResponseWriter, r *http.Request) {
p := services.GetProfileService().GetProfile()
js, err := json.Marshal(p)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.Write(js)
}
## Instruction:
Use Julien Schmidt's http router
## Code After:
package main
import (
"encoding/json"
"log"
"net/http"
"os"
"github.com/julienschmidt/httprouter"
"cjdavis.me/elysium/services"
)
func main() {
router := httprouter.New()
router.GET("/", handler)
port := os.Getenv("PORT")
if port == "" {
port = "9090"
}
log.Printf("Elysium listening on port %s", port)
http.ListenAndServe(":"+port, router)
}
func handler(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
p := services.GetProfileService().GetProfile()
js, err := json.Marshal(p)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.Write(js)
}
| package main
import (
"encoding/json"
"log"
"net/http"
"os"
+ "github.com/julienschmidt/httprouter"
+
"cjdavis.me/elysium/services"
)
func main() {
- http.HandleFunc("/", handler)
+ router := httprouter.New()
+ router.GET("/", handler)
port := os.Getenv("PORT")
if port == "" {
port = "9090"
}
log.Printf("Elysium listening on port %s", port)
- http.ListenAndServe(":"+port, nil)
? ^^^
+ http.ListenAndServe(":"+port, router)
? ^^^^^^
}
- func handler(w http.ResponseWriter, r *http.Request) {
+ func handler(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
? +++++++++++++++++++++
p := services.GetProfileService().GetProfile()
js, err := json.Marshal(p)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.Write(js)
} | 9 | 0.257143 | 6 | 3 |
f495ebb996bd56a35801afef92fe82cc409629e9 | rails_generators/publishing_logic_fields/templates/db/migrate/add_publishing_logic_fields.rb.erb | rails_generators/publishing_logic_fields/templates/db/migrate/add_publishing_logic_fields.rb.erb | class <%= migration_name %> < ActiveRecord::Migration
def self.up
add_column :<%= class_name.underscore.camelize.tableize %>, :publishing_enabled, :boolean
add_column :<%= class_name.underscore.camelize.tableize %>, :publish_from, :datetime
add_column :<%= class_name.underscore.camelize.tableize %>, :publish_until, :datetime
end
def self.down
remove_column :<%= class_name.underscore.camelize.tableize %>, :publishing_enabled
remove_column :<%= class_name.underscore.camelize.tableize %>, :publish_from
remove_column :<%= class_name.underscore.camelize.tableize %>, :publish_until
end
end
| class <%= migration_name %> < ActiveRecord::Migration
def self.up
add_column :<%= class_name.underscore.camelize.tableize %>, :publishing_enabled, :boolean
add_column :<%= class_name.underscore.camelize.tableize %>, :published_at, :datetime
add_column :<%= class_name.underscore.camelize.tableize %>, :published_until, :datetime
end
def self.down
remove_column :<%= class_name.underscore.camelize.tableize %>, :publishing_enabled
remove_column :<%= class_name.underscore.camelize.tableize %>, :published_at
remove_column :<%= class_name.underscore.camelize.tableize %>, :published_until
end
end
| Rename publishing logic fields to published_at and published_until | Rename publishing logic fields to published_at and published_until
| HTML+ERB | mit | unboxed/publishing_logic | html+erb | ## Code Before:
class <%= migration_name %> < ActiveRecord::Migration
def self.up
add_column :<%= class_name.underscore.camelize.tableize %>, :publishing_enabled, :boolean
add_column :<%= class_name.underscore.camelize.tableize %>, :publish_from, :datetime
add_column :<%= class_name.underscore.camelize.tableize %>, :publish_until, :datetime
end
def self.down
remove_column :<%= class_name.underscore.camelize.tableize %>, :publishing_enabled
remove_column :<%= class_name.underscore.camelize.tableize %>, :publish_from
remove_column :<%= class_name.underscore.camelize.tableize %>, :publish_until
end
end
## Instruction:
Rename publishing logic fields to published_at and published_until
## Code After:
class <%= migration_name %> < ActiveRecord::Migration
def self.up
add_column :<%= class_name.underscore.camelize.tableize %>, :publishing_enabled, :boolean
add_column :<%= class_name.underscore.camelize.tableize %>, :published_at, :datetime
add_column :<%= class_name.underscore.camelize.tableize %>, :published_until, :datetime
end
def self.down
remove_column :<%= class_name.underscore.camelize.tableize %>, :publishing_enabled
remove_column :<%= class_name.underscore.camelize.tableize %>, :published_at
remove_column :<%= class_name.underscore.camelize.tableize %>, :published_until
end
end
| class <%= migration_name %> < ActiveRecord::Migration
def self.up
add_column :<%= class_name.underscore.camelize.tableize %>, :publishing_enabled, :boolean
- add_column :<%= class_name.underscore.camelize.tableize %>, :publish_from, :datetime
? ^^^^
+ add_column :<%= class_name.underscore.camelize.tableize %>, :published_at, :datetime
? ++ ^^
- add_column :<%= class_name.underscore.camelize.tableize %>, :publish_until, :datetime
+ add_column :<%= class_name.underscore.camelize.tableize %>, :published_until, :datetime
? ++
end
def self.down
remove_column :<%= class_name.underscore.camelize.tableize %>, :publishing_enabled
- remove_column :<%= class_name.underscore.camelize.tableize %>, :publish_from
? ^^^^
+ remove_column :<%= class_name.underscore.camelize.tableize %>, :published_at
? ++ ^^
- remove_column :<%= class_name.underscore.camelize.tableize %>, :publish_until
+ remove_column :<%= class_name.underscore.camelize.tableize %>, :published_until
? ++
end
end | 8 | 0.615385 | 4 | 4 |
2acf61fd0f08ab8424c3d8422c469d82cc1dc226 | app/models/spree/stock_item.rb | app/models/spree/stock_item.rb |
module Spree
class StockItem < ActiveRecord::Base
belongs_to :stock_location, class_name: 'Spree::StockLocation'
belongs_to :variant, class_name: 'Spree::Variant'
has_many :stock_movements, dependent: :destroy
validates_presence_of :stock_location, :variant
validates_uniqueness_of :variant_id, scope: :stock_location_id
attr_accessible :count_on_hand, :variant, :stock_location, :backorderable, :variant_id
delegate :weight, to: :variant
def backordered_inventory_units
Spree::InventoryUnit.backordered_for_stock_item(self)
end
def variant_name
variant.name
end
def adjust_count_on_hand(value)
with_lock do
self.count_on_hand = count_on_hand + value
process_backorders if in_stock?
save!
end
end
def in_stock?
count_on_hand.positive?
end
# Tells whether it's available to be included in a shipment
def available?
in_stock? || backorderable?
end
private
def count_on_hand=(value)
self[:count_on_hand] = value
end
def process_backorders
backordered_inventory_units.each do |unit|
return unless in_stock?
unit.fill_backorder
end
end
end
end
|
module Spree
class StockItem < ActiveRecord::Base
belongs_to :stock_location, class_name: 'Spree::StockLocation'
belongs_to :variant, class_name: 'Spree::Variant'
has_many :stock_movements, dependent: :destroy
validates_presence_of :stock_location, :variant
validates_uniqueness_of :variant_id, scope: :stock_location_id
attr_accessible :count_on_hand, :variant, :stock_location, :backorderable, :variant_id
delegate :weight, to: :variant
def backordered_inventory_units
Spree::InventoryUnit.backordered_for_stock_item(self)
end
delegate :name, to: :variant, prefix: true
def adjust_count_on_hand(value)
with_lock do
self.count_on_hand = count_on_hand + value
process_backorders if in_stock?
save!
end
end
def in_stock?
count_on_hand.positive?
end
# Tells whether it's available to be included in a shipment
def available?
in_stock? || backorderable?
end
private
def count_on_hand=(value)
self[:count_on_hand] = value
end
def process_backorders
backordered_inventory_units.each do |unit|
return unless in_stock?
unit.fill_backorder
end
end
end
end
| Address violation of Rubocop Rails/Delegate | Address violation of Rubocop Rails/Delegate
| Ruby | agpl-3.0 | lin-d-hop/openfoodnetwork,openfoodfoundation/openfoodnetwork,openfoodfoundation/openfoodnetwork,lin-d-hop/openfoodnetwork,lin-d-hop/openfoodnetwork,openfoodfoundation/openfoodnetwork,Matt-Yorkley/openfoodnetwork,Matt-Yorkley/openfoodnetwork,Matt-Yorkley/openfoodnetwork,mkllnk/openfoodnetwork,mkllnk/openfoodnetwork,Matt-Yorkley/openfoodnetwork,lin-d-hop/openfoodnetwork,mkllnk/openfoodnetwork,openfoodfoundation/openfoodnetwork,mkllnk/openfoodnetwork | ruby | ## Code Before:
module Spree
class StockItem < ActiveRecord::Base
belongs_to :stock_location, class_name: 'Spree::StockLocation'
belongs_to :variant, class_name: 'Spree::Variant'
has_many :stock_movements, dependent: :destroy
validates_presence_of :stock_location, :variant
validates_uniqueness_of :variant_id, scope: :stock_location_id
attr_accessible :count_on_hand, :variant, :stock_location, :backorderable, :variant_id
delegate :weight, to: :variant
def backordered_inventory_units
Spree::InventoryUnit.backordered_for_stock_item(self)
end
def variant_name
variant.name
end
def adjust_count_on_hand(value)
with_lock do
self.count_on_hand = count_on_hand + value
process_backorders if in_stock?
save!
end
end
def in_stock?
count_on_hand.positive?
end
# Tells whether it's available to be included in a shipment
def available?
in_stock? || backorderable?
end
private
def count_on_hand=(value)
self[:count_on_hand] = value
end
def process_backorders
backordered_inventory_units.each do |unit|
return unless in_stock?
unit.fill_backorder
end
end
end
end
## Instruction:
Address violation of Rubocop Rails/Delegate
## Code After:
module Spree
class StockItem < ActiveRecord::Base
belongs_to :stock_location, class_name: 'Spree::StockLocation'
belongs_to :variant, class_name: 'Spree::Variant'
has_many :stock_movements, dependent: :destroy
validates_presence_of :stock_location, :variant
validates_uniqueness_of :variant_id, scope: :stock_location_id
attr_accessible :count_on_hand, :variant, :stock_location, :backorderable, :variant_id
delegate :weight, to: :variant
def backordered_inventory_units
Spree::InventoryUnit.backordered_for_stock_item(self)
end
delegate :name, to: :variant, prefix: true
def adjust_count_on_hand(value)
with_lock do
self.count_on_hand = count_on_hand + value
process_backorders if in_stock?
save!
end
end
def in_stock?
count_on_hand.positive?
end
# Tells whether it's available to be included in a shipment
def available?
in_stock? || backorderable?
end
private
def count_on_hand=(value)
self[:count_on_hand] = value
end
def process_backorders
backordered_inventory_units.each do |unit|
return unless in_stock?
unit.fill_backorder
end
end
end
end
|
module Spree
class StockItem < ActiveRecord::Base
belongs_to :stock_location, class_name: 'Spree::StockLocation'
belongs_to :variant, class_name: 'Spree::Variant'
has_many :stock_movements, dependent: :destroy
validates_presence_of :stock_location, :variant
validates_uniqueness_of :variant_id, scope: :stock_location_id
attr_accessible :count_on_hand, :variant, :stock_location, :backorderable, :variant_id
delegate :weight, to: :variant
def backordered_inventory_units
Spree::InventoryUnit.backordered_for_stock_item(self)
end
+ delegate :name, to: :variant, prefix: true
- def variant_name
- variant.name
- end
def adjust_count_on_hand(value)
with_lock do
self.count_on_hand = count_on_hand + value
process_backorders if in_stock?
save!
end
end
def in_stock?
count_on_hand.positive?
end
# Tells whether it's available to be included in a shipment
def available?
in_stock? || backorderable?
end
private
def count_on_hand=(value)
self[:count_on_hand] = value
end
def process_backorders
backordered_inventory_units.each do |unit|
return unless in_stock?
unit.fill_backorder
end
end
end
end | 4 | 0.072727 | 1 | 3 |
13f2e5ccc624698fac10fd10c1800e80c6da2d04 | requirements.txt | requirements.txt | gunicorn
whitenoise
mysqlclient~=1.3.13
sqlparse
requests
yamjam
django-slack
# optional session store
# django-redis>=4.4
# log handler
ConcurrentLogHandler~=0.9.1
# dependences
# upgrade https://docs.djangoproject.com/en/dev/releases/2.2/
Django~=1.11.1
djangorestframework~=3.9.0
django-filter~=2.0.0
# Customized branch
# djangorestframework-jsonapi~=2.3.0
djangorestframework-jwt~=1.11.0
django-cors-headers~=2.4.0
openapi-codec
cx_Oracle~=6.2.1
# optional serializers
# djangorestframework-xml~=1.3.0
# djangorestframework-yaml~=1.0.3
djangorestframework-csv~=2.1.0
# schema
coreapi~=2.3.0
# mongo
mongoengine~=0.15.0
pymongo~=3.7.2
django-rest-framework-mongoengine~=3.3.1
#EBI MGnify libs
ena-api-libs~=1.0.1
emg-backlog-schema~=0.12.2
| gunicorn
whitenoise
mysqlclient~=1.3.13
sqlparse
requests
yamjam
django-slack
# optional session store
# django-redis>=4.4
# log handler
ConcurrentLogHandler~=0.9.1
# dependences
# upgrade https://docs.djangoproject.com/en/dev/releases/2.2/
Django~=1.11.1
djangorestframework~=3.9.0
django-filter~=2.0.0
# Customized branch
# djangorestframework-jsonapi~=2.3.0
djangorestframework-jwt~=1.11.0
django-cors-headers~=2.4.0
openapi-codec
cx_Oracle~=6.2.1
# optional serializers
# djangorestframework-xml~=1.3.0
# djangorestframework-yaml~=1.0.3
djangorestframework-csv~=2.1.0
# schema
coreapi~=2.3.0
# mongo
mongoengine~=0.15.0
pymongo~=3.7.2
django-rest-framework-mongoengine~=3.3.1
| Remove webuploaded reqs from base requeriments.txt | Remove webuploaded reqs from base requeriments.txt
| Text | apache-2.0 | EBI-Metagenomics/emgapi,EBI-Metagenomics/emgapi,EBI-Metagenomics/emgapi,EBI-Metagenomics/emgapi,EBI-Metagenomics/emgapi | text | ## Code Before:
gunicorn
whitenoise
mysqlclient~=1.3.13
sqlparse
requests
yamjam
django-slack
# optional session store
# django-redis>=4.4
# log handler
ConcurrentLogHandler~=0.9.1
# dependences
# upgrade https://docs.djangoproject.com/en/dev/releases/2.2/
Django~=1.11.1
djangorestframework~=3.9.0
django-filter~=2.0.0
# Customized branch
# djangorestframework-jsonapi~=2.3.0
djangorestframework-jwt~=1.11.0
django-cors-headers~=2.4.0
openapi-codec
cx_Oracle~=6.2.1
# optional serializers
# djangorestframework-xml~=1.3.0
# djangorestframework-yaml~=1.0.3
djangorestframework-csv~=2.1.0
# schema
coreapi~=2.3.0
# mongo
mongoengine~=0.15.0
pymongo~=3.7.2
django-rest-framework-mongoengine~=3.3.1
#EBI MGnify libs
ena-api-libs~=1.0.1
emg-backlog-schema~=0.12.2
## Instruction:
Remove webuploaded reqs from base requeriments.txt
## Code After:
gunicorn
whitenoise
mysqlclient~=1.3.13
sqlparse
requests
yamjam
django-slack
# optional session store
# django-redis>=4.4
# log handler
ConcurrentLogHandler~=0.9.1
# dependences
# upgrade https://docs.djangoproject.com/en/dev/releases/2.2/
Django~=1.11.1
djangorestframework~=3.9.0
django-filter~=2.0.0
# Customized branch
# djangorestframework-jsonapi~=2.3.0
djangorestframework-jwt~=1.11.0
django-cors-headers~=2.4.0
openapi-codec
cx_Oracle~=6.2.1
# optional serializers
# djangorestframework-xml~=1.3.0
# djangorestframework-yaml~=1.0.3
djangorestframework-csv~=2.1.0
# schema
coreapi~=2.3.0
# mongo
mongoengine~=0.15.0
pymongo~=3.7.2
django-rest-framework-mongoengine~=3.3.1
| gunicorn
whitenoise
mysqlclient~=1.3.13
sqlparse
requests
yamjam
django-slack
# optional session store
# django-redis>=4.4
# log handler
ConcurrentLogHandler~=0.9.1
# dependences
# upgrade https://docs.djangoproject.com/en/dev/releases/2.2/
Django~=1.11.1
djangorestframework~=3.9.0
django-filter~=2.0.0
# Customized branch
# djangorestframework-jsonapi~=2.3.0
djangorestframework-jwt~=1.11.0
django-cors-headers~=2.4.0
openapi-codec
cx_Oracle~=6.2.1
# optional serializers
# djangorestframework-xml~=1.3.0
# djangorestframework-yaml~=1.0.3
djangorestframework-csv~=2.1.0
# schema
coreapi~=2.3.0
# mongo
mongoengine~=0.15.0
pymongo~=3.7.2
django-rest-framework-mongoengine~=3.3.1
-
-
- #EBI MGnify libs
- ena-api-libs~=1.0.1
- emg-backlog-schema~=0.12.2 | 5 | 0.113636 | 0 | 5 |
19e9f9172a8637009c0803e07027d76aca6731e5 | isoparser/src/main/java/org/mp4parser/SkipBox.java | isoparser/src/main/java/org/mp4parser/SkipBox.java | package org.mp4parser;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.SeekableByteChannel;
import java.nio.channels.WritableByteChannel;
public class SkipBox implements ParsableBox {
private String type;
private long size;
private long sourcePosition = -1;
public SkipBox(String type, byte[] usertype, String parentType) {
this.type = type;
}
public String getType() {
return type;
}
public long getSize() {
return size;
}
public long getContentSize() {
return size-8;
}
/**
* Get the seekable position of the content for this box within the source data.
* @return The data offset, or -1 if it is not known
*/
public long getSourcePosition() {
return sourcePosition;
}
public void getBox(WritableByteChannel writableByteChannel) throws IOException {
throw new RuntimeException("Cannot retrieve a skipped box - type "+type);
}
public void parse(ReadableByteChannel dataSource, ByteBuffer header, long contentSize, BoxParser boxParser)
throws IOException {
this.size = contentSize+8;
if( dataSource instanceof SeekableByteChannel ) {
SeekableByteChannel seekable = (SeekableByteChannel) dataSource;
sourcePosition = seekable.position();
long newPosition = sourcePosition + contentSize;
seekable.position(newPosition);
}
else {
throw new RuntimeException("Cannot skip box "+type+" if data source is not seekable");
}
}
}
| package org.mp4parser;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;
public class SkipBox implements ParsableBox {
private String type;
private long size;
private long sourcePosition = -1;
public SkipBox(String type, byte[] usertype, String parentType) {
this.type = type;
}
public String getType() {
return type;
}
public long getSize() {
return size;
}
public long getContentSize() {
return size-8;
}
/**
* Get the seekable position of the content for this box within the source data.
* @return The data offset, or -1 if it is not known
*/
public long getSourcePosition() {
return sourcePosition;
}
public void getBox(WritableByteChannel writableByteChannel) throws IOException {
throw new RuntimeException("Cannot retrieve a skipped box - type "+type);
}
public void parse(ReadableByteChannel dataSource, ByteBuffer header, long contentSize, BoxParser boxParser)
throws IOException {
this.size = contentSize+8;
if( dataSource instanceof FileChannel ) {
FileChannel seekable = (FileChannel) dataSource;
sourcePosition = seekable.position();
long newPosition = sourcePosition + contentSize;
seekable.position(newPosition);
}
else {
throw new RuntimeException("Cannot skip box "+type+" if data source is not seekable");
}
}
}
| Use FileChannel rather than SeekableByteChannel for Android compatibility | Use FileChannel rather than SeekableByteChannel for Android compatibility
| Java | apache-2.0 | sannies/mp4parser | java | ## Code Before:
package org.mp4parser;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.SeekableByteChannel;
import java.nio.channels.WritableByteChannel;
public class SkipBox implements ParsableBox {
private String type;
private long size;
private long sourcePosition = -1;
public SkipBox(String type, byte[] usertype, String parentType) {
this.type = type;
}
public String getType() {
return type;
}
public long getSize() {
return size;
}
public long getContentSize() {
return size-8;
}
/**
* Get the seekable position of the content for this box within the source data.
* @return The data offset, or -1 if it is not known
*/
public long getSourcePosition() {
return sourcePosition;
}
public void getBox(WritableByteChannel writableByteChannel) throws IOException {
throw new RuntimeException("Cannot retrieve a skipped box - type "+type);
}
public void parse(ReadableByteChannel dataSource, ByteBuffer header, long contentSize, BoxParser boxParser)
throws IOException {
this.size = contentSize+8;
if( dataSource instanceof SeekableByteChannel ) {
SeekableByteChannel seekable = (SeekableByteChannel) dataSource;
sourcePosition = seekable.position();
long newPosition = sourcePosition + contentSize;
seekable.position(newPosition);
}
else {
throw new RuntimeException("Cannot skip box "+type+" if data source is not seekable");
}
}
}
## Instruction:
Use FileChannel rather than SeekableByteChannel for Android compatibility
## Code After:
package org.mp4parser;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;
public class SkipBox implements ParsableBox {
private String type;
private long size;
private long sourcePosition = -1;
public SkipBox(String type, byte[] usertype, String parentType) {
this.type = type;
}
public String getType() {
return type;
}
public long getSize() {
return size;
}
public long getContentSize() {
return size-8;
}
/**
* Get the seekable position of the content for this box within the source data.
* @return The data offset, or -1 if it is not known
*/
public long getSourcePosition() {
return sourcePosition;
}
public void getBox(WritableByteChannel writableByteChannel) throws IOException {
throw new RuntimeException("Cannot retrieve a skipped box - type "+type);
}
public void parse(ReadableByteChannel dataSource, ByteBuffer header, long contentSize, BoxParser boxParser)
throws IOException {
this.size = contentSize+8;
if( dataSource instanceof FileChannel ) {
FileChannel seekable = (FileChannel) dataSource;
sourcePosition = seekable.position();
long newPosition = sourcePosition + contentSize;
seekable.position(newPosition);
}
else {
throw new RuntimeException("Cannot skip box "+type+" if data source is not seekable");
}
}
}
| package org.mp4parser;
import java.io.IOException;
import java.nio.ByteBuffer;
+ import java.nio.channels.FileChannel;
import java.nio.channels.ReadableByteChannel;
- import java.nio.channels.SeekableByteChannel;
import java.nio.channels.WritableByteChannel;
public class SkipBox implements ParsableBox {
private String type;
private long size;
private long sourcePosition = -1;
public SkipBox(String type, byte[] usertype, String parentType) {
this.type = type;
}
public String getType() {
return type;
}
public long getSize() {
return size;
}
public long getContentSize() {
return size-8;
}
/**
* Get the seekable position of the content for this box within the source data.
* @return The data offset, or -1 if it is not known
*/
public long getSourcePosition() {
return sourcePosition;
}
public void getBox(WritableByteChannel writableByteChannel) throws IOException {
throw new RuntimeException("Cannot retrieve a skipped box - type "+type);
}
public void parse(ReadableByteChannel dataSource, ByteBuffer header, long contentSize, BoxParser boxParser)
throws IOException {
this.size = contentSize+8;
- if( dataSource instanceof SeekableByteChannel ) {
? ^^^^^^ ----
+ if( dataSource instanceof FileChannel ) {
? ^^
- SeekableByteChannel seekable = (SeekableByteChannel) dataSource;
? ^^^^^^ ---- ^^^^^^ ----
+ FileChannel seekable = (FileChannel) dataSource;
? ^^ ^^
sourcePosition = seekable.position();
long newPosition = sourcePosition + contentSize;
seekable.position(newPosition);
}
else {
throw new RuntimeException("Cannot skip box "+type+" if data source is not seekable");
}
}
} | 6 | 0.103448 | 3 | 3 |
13940eb3a3de8783f04921d27b641876c2266176 | test-requirements.txt | test-requirements.txt | bandit>=1.1.0 # Apache-2.0
| bandit>=1.1.0 # Apache-2.0
doc8 # Apache-2.0
| Add missing dependency for testing | Add missing dependency for testing
| Text | apache-2.0 | Pansanel/cloudkeeper-os | text | ## Code Before:
bandit>=1.1.0 # Apache-2.0
## Instruction:
Add missing dependency for testing
## Code After:
bandit>=1.1.0 # Apache-2.0
doc8 # Apache-2.0
| bandit>=1.1.0 # Apache-2.0
+ doc8 # Apache-2.0 | 1 | 1 | 1 | 0 |
8c616420210bf779507f6bd33e3a06496b310e92 | features/including_test_services.feature | features/including_test_services.feature | Feature: Including test services
Scenario: Including test services when test environment is set
Given I have test services
And the test environment is set
When I generate the container
Then the test services should be available
Scenario: Throwing exception when test environment set and there are no test services
Given I have do not have test services
And the test environment is set
When I generate the container
Then an exception should be thrown
Scenario: Not including test services when test environment is not set
Given I have test services
And the test environment is not set
When I generate the container
Then the test services should not be available
| Feature: Including test services
Scenario: Including test services when test environment is set
Given I have test services
And the test environment is set
When I generate the container
Then the test services should be available
Scenario: Not including test services when test environment is not set
Given I have test services
And the test environment is not set
When I generate the container
Then the test services should not be available
| Remove exception check as non-existant files are not loaded anymore | Remove exception check as non-existant files are not loaded anymore
| Cucumber | mit | inviqa/symfony-container-generator,jon-acker/symfony-container-generator | cucumber | ## Code Before:
Feature: Including test services
Scenario: Including test services when test environment is set
Given I have test services
And the test environment is set
When I generate the container
Then the test services should be available
Scenario: Throwing exception when test environment set and there are no test services
Given I have do not have test services
And the test environment is set
When I generate the container
Then an exception should be thrown
Scenario: Not including test services when test environment is not set
Given I have test services
And the test environment is not set
When I generate the container
Then the test services should not be available
## Instruction:
Remove exception check as non-existant files are not loaded anymore
## Code After:
Feature: Including test services
Scenario: Including test services when test environment is set
Given I have test services
And the test environment is set
When I generate the container
Then the test services should be available
Scenario: Not including test services when test environment is not set
Given I have test services
And the test environment is not set
When I generate the container
Then the test services should not be available
| Feature: Including test services
Scenario: Including test services when test environment is set
Given I have test services
And the test environment is set
When I generate the container
Then the test services should be available
- Scenario: Throwing exception when test environment set and there are no test services
- Given I have do not have test services
- And the test environment is set
- When I generate the container
- Then an exception should be thrown
-
Scenario: Not including test services when test environment is not set
Given I have test services
And the test environment is not set
When I generate the container
Then the test services should not be available
| 6 | 0.3 | 0 | 6 |
2764931d730e440def1a2a276d25a98874150ed7 | runtests.sh | runtests.sh | DATABASE_URL=postgres://jrandom@localhost/test py.test tests.py -v
python postgres/__init__.py -v
python postgres/cursors.py -v
python postgres/orm.py -v
| DATABASE_URL=postgres://jrandom@localhost/test py.test tests.py -v
echo "Starting doctests."
python postgres/__init__.py
python postgres/cursors.py
python postgres/orm.py
echo "Done with doctests."
| Make doctest output easier to parse | Make doctest output easier to parse
Verbose mode w/ doctest drowns out actual failures.
| Shell | mit | techtonik/postgres.py,gratipay/postgres.py,techtonik/postgres.py,gratipay/postgres.py | shell | ## Code Before:
DATABASE_URL=postgres://jrandom@localhost/test py.test tests.py -v
python postgres/__init__.py -v
python postgres/cursors.py -v
python postgres/orm.py -v
## Instruction:
Make doctest output easier to parse
Verbose mode w/ doctest drowns out actual failures.
## Code After:
DATABASE_URL=postgres://jrandom@localhost/test py.test tests.py -v
echo "Starting doctests."
python postgres/__init__.py
python postgres/cursors.py
python postgres/orm.py
echo "Done with doctests."
| DATABASE_URL=postgres://jrandom@localhost/test py.test tests.py -v
+ echo "Starting doctests."
- python postgres/__init__.py -v
? ---
+ python postgres/__init__.py
- python postgres/cursors.py -v
? ---
+ python postgres/cursors.py
- python postgres/orm.py -v
? ---
+ python postgres/orm.py
+ echo "Done with doctests." | 8 | 2 | 5 | 3 |
fae1cb0bc7690e65127b5dd231a2181c415bb385 | README.md | README.md |
===========
Lottify-Me
===========
===========
DESCRIPTION
===========
A web-app that allows you to:
- Input your lottery number(s)
- Notifies you if you have a winning number
(-) Tells you the nearest place to collect your money
======
TRELLO
======
https://trello.com/b/j7Kdz6lX/lotify-me
|
===========
Lottify-Me
===========
===========
DESCRIPTION
===========
A web-app that allows you to:
- Input your lottery number(s)
- Notifies you if you have a winning number
(-) Tells you the nearest place to collect your money
======
Pending tasks
======
- Setup scheduler
- Write method that handles searching or winners after a draw and sends emails.
- Reduce the amount of data pulled from lottos due to database storage.
- Change input numbers so it accepts single digits 1 vs 01
- Don't accept future draws that are more than a week on the future.
- Change title on production app to lotifyme beta
- Write more descriptive emails.
- Set logo on the tap of the browser
- Fix login and signup from home
- Setup security tokens on swift
- Improve user experience (design)
- Setup input numbers box to change depending on the amount of numbers needed to play. ex: pick10 = 10 numbers, powerball = 6 numbers | Add pending tasks on readme | Add pending tasks on readme
| Markdown | mit | drodriguez56/lotifyMe,drodriguez56/lotifyMe,drodriguez56/lotifyMe | markdown | ## Code Before:
===========
Lottify-Me
===========
===========
DESCRIPTION
===========
A web-app that allows you to:
- Input your lottery number(s)
- Notifies you if you have a winning number
(-) Tells you the nearest place to collect your money
======
TRELLO
======
https://trello.com/b/j7Kdz6lX/lotify-me
## Instruction:
Add pending tasks on readme
## Code After:
===========
Lottify-Me
===========
===========
DESCRIPTION
===========
A web-app that allows you to:
- Input your lottery number(s)
- Notifies you if you have a winning number
(-) Tells you the nearest place to collect your money
======
Pending tasks
======
- Setup scheduler
- Write method that handles searching or winners after a draw and sends emails.
- Reduce the amount of data pulled from lottos due to database storage.
- Change input numbers so it accepts single digits 1 vs 01
- Don't accept future draws that are more than a week on the future.
- Change title on production app to lotifyme beta
- Write more descriptive emails.
- Set logo on the tap of the browser
- Fix login and signup from home
- Setup security tokens on swift
- Improve user experience (design)
- Setup input numbers box to change depending on the amount of numbers needed to play. ex: pick10 = 10 numbers, powerball = 6 numbers |
===========
Lottify-Me
===========
===========
DESCRIPTION
===========
A web-app that allows you to:
- Input your lottery number(s)
- Notifies you if you have a winning number
(-) Tells you the nearest place to collect your money
======
- TRELLO
+ Pending tasks
======
- https://trello.com/b/j7Kdz6lX/lotify-me
+ - Setup scheduler
+ - Write method that handles searching or winners after a draw and sends emails.
+
+ - Reduce the amount of data pulled from lottos due to database storage.
+
+ - Change input numbers so it accepts single digits 1 vs 01
+
+ - Don't accept future draws that are more than a week on the future.
+
+ - Change title on production app to lotifyme beta
+
+ - Write more descriptive emails.
+
+ - Set logo on the tap of the browser
+
+ - Fix login and signup from home
+
+ - Setup security tokens on swift
+
+ - Improve user experience (design)
+
+ - Setup input numbers box to change depending on the amount of numbers needed to play. ex: pick10 = 10 numbers, powerball = 6 numbers | 25 | 1.190476 | 23 | 2 |
417bc499a20c8cd07ddae7ba1f48ebc8603f8e4c | trim_video_start.sh | trim_video_start.sh | INPUT=$1
START=$2
[ -f "$INPUT" ] || ( echo "Usage: command filename delay"; exit 2 )
dir=$(dirname "$INPUT")
filename=$(basename "$INPUT")
extension="${filename##*.}"
filename="${filename%.*}"
OUTPUT="$dir/${filename}_cut${START}.$extension"
ffmpeg -ss $START -i "$INPUT" -async 1 -c copy "$OUTPUT"
vlc "$OUTPUT"
| INPUT=$1
START=$2
[ -f "$INPUT" ] || ( echo "Usage: command filename delay"; exit 2 )
dir=$(dirname "$INPUT")
filename=$(basename "$INPUT")
extension="${filename##*.}"
filename="${filename%.*}"
OUTPUT="$dir/${filename}_cut${START}.$extension"
# echo -ss $START -i "$INPUT" -async 1 -c copy "$OUTPUT"
# ffmpeg -ss $START -i "$INPUT" -async 1 -c copy "$OUTPUT"
#echo -ss $START -i "$INPUT" -async 1 -c copy "$OUTPUT"
ffmpeg -ss $START -i "$INPUT" -async 1 "$OUTPUT"
vlc "$OUTPUT"
| Remove -c copy to recode the movei | Remove -c copy to recode the movei
| Shell | unlicense | mosbth/ffmpeg | shell | ## Code Before:
INPUT=$1
START=$2
[ -f "$INPUT" ] || ( echo "Usage: command filename delay"; exit 2 )
dir=$(dirname "$INPUT")
filename=$(basename "$INPUT")
extension="${filename##*.}"
filename="${filename%.*}"
OUTPUT="$dir/${filename}_cut${START}.$extension"
ffmpeg -ss $START -i "$INPUT" -async 1 -c copy "$OUTPUT"
vlc "$OUTPUT"
## Instruction:
Remove -c copy to recode the movei
## Code After:
INPUT=$1
START=$2
[ -f "$INPUT" ] || ( echo "Usage: command filename delay"; exit 2 )
dir=$(dirname "$INPUT")
filename=$(basename "$INPUT")
extension="${filename##*.}"
filename="${filename%.*}"
OUTPUT="$dir/${filename}_cut${START}.$extension"
# echo -ss $START -i "$INPUT" -async 1 -c copy "$OUTPUT"
# ffmpeg -ss $START -i "$INPUT" -async 1 -c copy "$OUTPUT"
#echo -ss $START -i "$INPUT" -async 1 -c copy "$OUTPUT"
ffmpeg -ss $START -i "$INPUT" -async 1 "$OUTPUT"
vlc "$OUTPUT"
| INPUT=$1
START=$2
[ -f "$INPUT" ] || ( echo "Usage: command filename delay"; exit 2 )
dir=$(dirname "$INPUT")
filename=$(basename "$INPUT")
extension="${filename##*.}"
filename="${filename%.*}"
OUTPUT="$dir/${filename}_cut${START}.$extension"
+ # echo -ss $START -i "$INPUT" -async 1 -c copy "$OUTPUT"
- ffmpeg -ss $START -i "$INPUT" -async 1 -c copy "$OUTPUT"
+ # ffmpeg -ss $START -i "$INPUT" -async 1 -c copy "$OUTPUT"
? ++
+
+ #echo -ss $START -i "$INPUT" -async 1 -c copy "$OUTPUT"
+ ffmpeg -ss $START -i "$INPUT" -async 1 "$OUTPUT"
vlc "$OUTPUT" | 6 | 0.4 | 5 | 1 |
847d20067efc3e1faf329ac9c8a9ad6965ef12bc | app/models/renalware/clinics/clinic.rb | app/models/renalware/clinics/clinic.rb |
require_dependency "renalware/clinics"
module Renalware
module Clinics
class Clinic < ApplicationRecord
include Accountable
acts_as_paranoid
has_many :clinic_visits, dependent: :restrict_with_exception
has_many :appointments, dependent: :restrict_with_exception
belongs_to :default_modality_description, class_name: "Modalities::Description"
validates :name, presence: true, uniqueness: true
validates :code, uniqueness: true
scope :ordered, -> { order(deleted_at: :desc, name: :asc) }
scope :with_last_clinic_visit_date, lambda {
select(<<-SQL.squish)
(SELECT max(clinic_visits.date)
FROM clinic_visits
WHERE clinic_visits.clinic_id=clinic_clinics.id) AS last_clinic_visit
SQL
}
scope :with_last_appointment_time, lambda {
select(<<-SQL.squish)
(SELECT max(clinic_appointments.starts_at)
FROM clinic_appointments
WHERE clinic_appointments.clinic_id=clinic_clinics.id) AS last_clinic_appointment
SQL
}
# Note sure if needed so commenting out
# belongs_to :consultant, class_name: "Renalware::User", foreign_key: :user_id
def to_s
name
end
end
end
end
|
require_dependency "renalware/clinics"
module Renalware
module Clinics
class Clinic < ApplicationRecord
include Accountable
acts_as_paranoid
# The dependent option is not really compatible with acts_as_paranoid
# rubocop:disable Rails/HasManyOrHasOneDependent
has_many :clinic_visits
has_many :appointments
# rubocop:enable Rails/HasManyOrHasOneDependent
belongs_to :default_modality_description, class_name: "Modalities::Description"
validates :name, presence: true, uniqueness: true
validates :code, uniqueness: true
scope :ordered, -> { order(deleted_at: :desc, name: :asc) }
scope :with_last_clinic_visit_date, lambda {
select(<<-SQL.squish)
(SELECT max(clinic_visits.date)
FROM clinic_visits
WHERE clinic_visits.clinic_id=clinic_clinics.id) AS last_clinic_visit
SQL
}
scope :with_last_appointment_time, lambda {
select(<<-SQL.squish)
(SELECT max(clinic_appointments.starts_at)
FROM clinic_appointments
WHERE clinic_appointments.clinic_id=clinic_clinics.id) AS last_clinic_appointment
SQL
}
# Note sure if needed so commenting out
# belongs_to :consultant, class_name: "Renalware::User", foreign_key: :user_id
def to_s
name
end
end
end
end
| Remove :dependent option from has_many on Clinic | Remove :dependent option from has_many on Clinic
Removed `dependent: :restrict_with_exception` as this is incompatible with acts_as_paranoid
and causes a ActiveRecord::DeleteRestrictionError error to be raised.
| Ruby | mit | airslie/renalware-core,airslie/renalware-core,airslie/renalware-core,airslie/renalware-core | ruby | ## Code Before:
require_dependency "renalware/clinics"
module Renalware
module Clinics
class Clinic < ApplicationRecord
include Accountable
acts_as_paranoid
has_many :clinic_visits, dependent: :restrict_with_exception
has_many :appointments, dependent: :restrict_with_exception
belongs_to :default_modality_description, class_name: "Modalities::Description"
validates :name, presence: true, uniqueness: true
validates :code, uniqueness: true
scope :ordered, -> { order(deleted_at: :desc, name: :asc) }
scope :with_last_clinic_visit_date, lambda {
select(<<-SQL.squish)
(SELECT max(clinic_visits.date)
FROM clinic_visits
WHERE clinic_visits.clinic_id=clinic_clinics.id) AS last_clinic_visit
SQL
}
scope :with_last_appointment_time, lambda {
select(<<-SQL.squish)
(SELECT max(clinic_appointments.starts_at)
FROM clinic_appointments
WHERE clinic_appointments.clinic_id=clinic_clinics.id) AS last_clinic_appointment
SQL
}
# Note sure if needed so commenting out
# belongs_to :consultant, class_name: "Renalware::User", foreign_key: :user_id
def to_s
name
end
end
end
end
## Instruction:
Remove :dependent option from has_many on Clinic
Removed `dependent: :restrict_with_exception` as this is incompatible with acts_as_paranoid
and causes a ActiveRecord::DeleteRestrictionError error to be raised.
## Code After:
require_dependency "renalware/clinics"
module Renalware
module Clinics
class Clinic < ApplicationRecord
include Accountable
acts_as_paranoid
# The dependent option is not really compatible with acts_as_paranoid
# rubocop:disable Rails/HasManyOrHasOneDependent
has_many :clinic_visits
has_many :appointments
# rubocop:enable Rails/HasManyOrHasOneDependent
belongs_to :default_modality_description, class_name: "Modalities::Description"
validates :name, presence: true, uniqueness: true
validates :code, uniqueness: true
scope :ordered, -> { order(deleted_at: :desc, name: :asc) }
scope :with_last_clinic_visit_date, lambda {
select(<<-SQL.squish)
(SELECT max(clinic_visits.date)
FROM clinic_visits
WHERE clinic_visits.clinic_id=clinic_clinics.id) AS last_clinic_visit
SQL
}
scope :with_last_appointment_time, lambda {
select(<<-SQL.squish)
(SELECT max(clinic_appointments.starts_at)
FROM clinic_appointments
WHERE clinic_appointments.clinic_id=clinic_clinics.id) AS last_clinic_appointment
SQL
}
# Note sure if needed so commenting out
# belongs_to :consultant, class_name: "Renalware::User", foreign_key: :user_id
def to_s
name
end
end
end
end
|
require_dependency "renalware/clinics"
module Renalware
module Clinics
class Clinic < ApplicationRecord
include Accountable
acts_as_paranoid
- has_many :clinic_visits, dependent: :restrict_with_exception
- has_many :appointments, dependent: :restrict_with_exception
+ # The dependent option is not really compatible with acts_as_paranoid
+ # rubocop:disable Rails/HasManyOrHasOneDependent
+ has_many :clinic_visits
+ has_many :appointments
+ # rubocop:enable Rails/HasManyOrHasOneDependent
+
belongs_to :default_modality_description, class_name: "Modalities::Description"
validates :name, presence: true, uniqueness: true
validates :code, uniqueness: true
scope :ordered, -> { order(deleted_at: :desc, name: :asc) }
scope :with_last_clinic_visit_date, lambda {
select(<<-SQL.squish)
(SELECT max(clinic_visits.date)
FROM clinic_visits
WHERE clinic_visits.clinic_id=clinic_clinics.id) AS last_clinic_visit
SQL
}
scope :with_last_appointment_time, lambda {
select(<<-SQL.squish)
(SELECT max(clinic_appointments.starts_at)
FROM clinic_appointments
WHERE clinic_appointments.clinic_id=clinic_clinics.id) AS last_clinic_appointment
SQL
}
# Note sure if needed so commenting out
# belongs_to :consultant, class_name: "Renalware::User", foreign_key: :user_id
def to_s
name
end
end
end
end | 8 | 0.195122 | 6 | 2 |
285fd431ee8506182b3a33a684820ed657665891 | package.json | package.json | {
"name": "knit",
"version": "0.8.3",
"description": "A static content generator library",
"author": "Carl Baatz",
"licenses": [{"type": "MIT", "url": "https://github.com/cbaatz/knit/raw/master/LICENSE"}],
"repository": {"type": "git", "url": "git://github.com/cbaatz/knit.git"},
"main": "lib/index.js",
"engine": [ "node >=0.8" ],
"dependencies": {
"stream-buffers": "~0.2.3",
"async": "~0.1.22",
"mime": "~1.2.7"
},
"devDependencies": {
"vows": "0.6.x"
},
"scripts": {
"test": "vows --spec --isolate"
}
}
| {
"name": "knit",
"version": "0.8.3",
"description": "A static content generator library",
"author": "Carl Baatz",
"licenses": [{"type": "MIT", "url": "https://github.com/cbaatz/knit/raw/master/LICENSE"}],
"repository": {"type": "git", "url": "git://github.com/cbaatz/knit.git"},
"main": "lib/index.js",
"engine": [ "node >=0.8" ],
"dependencies": {
"stream-buffers": "~0.2.3",
"async": "~0.1.22",
"mime": "~1.2.7",
"colors": "~0.6.0"
},
"devDependencies": {
"vows": "0.6.x"
},
"scripts": {
"test": "vows --spec --isolate"
}
}
| Add colors as a dependency. | Add colors as a dependency.
| JSON | mit | cbaatz/knit | json | ## Code Before:
{
"name": "knit",
"version": "0.8.3",
"description": "A static content generator library",
"author": "Carl Baatz",
"licenses": [{"type": "MIT", "url": "https://github.com/cbaatz/knit/raw/master/LICENSE"}],
"repository": {"type": "git", "url": "git://github.com/cbaatz/knit.git"},
"main": "lib/index.js",
"engine": [ "node >=0.8" ],
"dependencies": {
"stream-buffers": "~0.2.3",
"async": "~0.1.22",
"mime": "~1.2.7"
},
"devDependencies": {
"vows": "0.6.x"
},
"scripts": {
"test": "vows --spec --isolate"
}
}
## Instruction:
Add colors as a dependency.
## Code After:
{
"name": "knit",
"version": "0.8.3",
"description": "A static content generator library",
"author": "Carl Baatz",
"licenses": [{"type": "MIT", "url": "https://github.com/cbaatz/knit/raw/master/LICENSE"}],
"repository": {"type": "git", "url": "git://github.com/cbaatz/knit.git"},
"main": "lib/index.js",
"engine": [ "node >=0.8" ],
"dependencies": {
"stream-buffers": "~0.2.3",
"async": "~0.1.22",
"mime": "~1.2.7",
"colors": "~0.6.0"
},
"devDependencies": {
"vows": "0.6.x"
},
"scripts": {
"test": "vows --spec --isolate"
}
}
| {
"name": "knit",
"version": "0.8.3",
"description": "A static content generator library",
"author": "Carl Baatz",
"licenses": [{"type": "MIT", "url": "https://github.com/cbaatz/knit/raw/master/LICENSE"}],
"repository": {"type": "git", "url": "git://github.com/cbaatz/knit.git"},
"main": "lib/index.js",
"engine": [ "node >=0.8" ],
"dependencies": {
"stream-buffers": "~0.2.3",
"async": "~0.1.22",
- "mime": "~1.2.7"
+ "mime": "~1.2.7",
? +
+ "colors": "~0.6.0"
},
"devDependencies": {
"vows": "0.6.x"
},
"scripts": {
"test": "vows --spec --isolate"
}
} | 3 | 0.142857 | 2 | 1 |
c6d345d01f59965155d9d912615a1eef939c32cb | Xls/Reader/excel_xlrd.py | Xls/Reader/excel_xlrd.py | import xlrd
import json
import sys
import os
import argparse
def run(argv):
parser = argparse.ArgumentParser()
parser.add_argument('--size')
parser.add_argument('--start')
parser.add_argument('--action')
parser.add_argument('--file')
args = parser.parse_args()
if False == os.path.isfile(args.file):
print("File does not exist")
sys.exit(1)
workbook = xlrd.open_workbook(args.file)
sheet = workbook.sheet_by_index(0)
if args.action == "count":
print(sheet.nrows)
elif args.action == "read":
reached_end = False
rows = []
while len(rows) < int(args.size) and reached_end == False:
try:
rows.append(sheet.row_values(int(args.start) + len(rows) - 1))
except IndexError:
reached_end = True
print(json.dumps(rows))
else:
print("Unknown command")
sys.exit(1)
if __name__ == "__main__":
run(sys.argv[1:])
| import xlrd
import json
import sys
import os
import argparse
def run(argv):
parser = argparse.ArgumentParser()
parser.add_argument('--size')
parser.add_argument('--start')
parser.add_argument('--action')
parser.add_argument('--file')
parser.add_argument('--max-empty-rows', dest="max_empty_rows")
args = parser.parse_args()
if False == os.path.isfile(args.file):
print("File does not exist")
sys.exit(1)
workbook = xlrd.open_workbook(args.file)
sheet = workbook.sheet_by_index(0)
if args.action == "count":
print(sheet.nrows)
elif args.action == "read":
reached_end = False
rows = []
while len(rows) < int(args.size) and reached_end == False:
try:
rows.append(sheet.row_values(int(args.start) + len(rows) - 1))
except IndexError:
reached_end = True
print(json.dumps(rows))
else:
print("Unknown command")
sys.exit(1)
if __name__ == "__main__":
run(sys.argv[1:])
| Fix empty argument "max-empty-rows" in xls script We send argument "max-empty-rows" to two different script. In xls need to set, that this argument is available | Fix empty argument "max-empty-rows" in xls script
We send argument "max-empty-rows" to two different script. In xls need to set, that this argument is available
| Python | mit | arodiss/XlsBundle,arodiss/XlsBundle | python | ## Code Before:
import xlrd
import json
import sys
import os
import argparse
def run(argv):
parser = argparse.ArgumentParser()
parser.add_argument('--size')
parser.add_argument('--start')
parser.add_argument('--action')
parser.add_argument('--file')
args = parser.parse_args()
if False == os.path.isfile(args.file):
print("File does not exist")
sys.exit(1)
workbook = xlrd.open_workbook(args.file)
sheet = workbook.sheet_by_index(0)
if args.action == "count":
print(sheet.nrows)
elif args.action == "read":
reached_end = False
rows = []
while len(rows) < int(args.size) and reached_end == False:
try:
rows.append(sheet.row_values(int(args.start) + len(rows) - 1))
except IndexError:
reached_end = True
print(json.dumps(rows))
else:
print("Unknown command")
sys.exit(1)
if __name__ == "__main__":
run(sys.argv[1:])
## Instruction:
Fix empty argument "max-empty-rows" in xls script
We send argument "max-empty-rows" to two different script. In xls need to set, that this argument is available
## Code After:
import xlrd
import json
import sys
import os
import argparse
def run(argv):
parser = argparse.ArgumentParser()
parser.add_argument('--size')
parser.add_argument('--start')
parser.add_argument('--action')
parser.add_argument('--file')
parser.add_argument('--max-empty-rows', dest="max_empty_rows")
args = parser.parse_args()
if False == os.path.isfile(args.file):
print("File does not exist")
sys.exit(1)
workbook = xlrd.open_workbook(args.file)
sheet = workbook.sheet_by_index(0)
if args.action == "count":
print(sheet.nrows)
elif args.action == "read":
reached_end = False
rows = []
while len(rows) < int(args.size) and reached_end == False:
try:
rows.append(sheet.row_values(int(args.start) + len(rows) - 1))
except IndexError:
reached_end = True
print(json.dumps(rows))
else:
print("Unknown command")
sys.exit(1)
if __name__ == "__main__":
run(sys.argv[1:])
| import xlrd
import json
import sys
import os
import argparse
def run(argv):
parser = argparse.ArgumentParser()
parser.add_argument('--size')
parser.add_argument('--start')
parser.add_argument('--action')
parser.add_argument('--file')
+ parser.add_argument('--max-empty-rows', dest="max_empty_rows")
args = parser.parse_args()
if False == os.path.isfile(args.file):
print("File does not exist")
sys.exit(1)
workbook = xlrd.open_workbook(args.file)
sheet = workbook.sheet_by_index(0)
if args.action == "count":
print(sheet.nrows)
elif args.action == "read":
reached_end = False
rows = []
while len(rows) < int(args.size) and reached_end == False:
try:
rows.append(sheet.row_values(int(args.start) + len(rows) - 1))
except IndexError:
reached_end = True
print(json.dumps(rows))
else:
print("Unknown command")
sys.exit(1)
if __name__ == "__main__":
run(sys.argv[1:]) | 1 | 0.025641 | 1 | 0 |
9c281ff44d6a28962897f4ca8013a539d7f08040 | src/libcask/network.py | src/libcask/network.py | import subprocess
class SetupNetworkMixin(object):
def _setup_hostname(self):
with self.get_attachment(['uts']).attach():
subprocess.check_call(['hostname', self.hostname])
def _setup_virtual_ethernet(self):
veth_name = 'veth-{hostname}'.format(hostname=self.hostname)
veth_host_name = 'hveth-{hostname}'.format(hostname=self.hostname)
# Create virtual ethernet pair
subprocess.check_call([
'ip', 'link', 'add',
'name', veth_host_name, 'type', 'veth',
'peer', 'name', veth_name, 'netns', str(self.pid())
])
# Add the container's host IP address and bring the interface up
subprocess.check_call(['ip', 'addr', 'add', self.ipaddr_host, 'dev', veth_host_name])
subprocess.check_call(['ip', 'link', 'set', veth_host_name, 'up'])
# Add the host interface to the bridge
# Assuming here that `cask0` bridge interface exists. It should
# be created and initialized by the Makefile.
subprocess.check_call(['ip', 'link', 'set', veth_host_name, 'master', 'cask0'])
# Set up virtual ethernet interface inside the container
with self.get_attachment(['net', 'uts']).attach():
subprocess.check_call([
'ifconfig', veth_name, self.ipaddr, 'up',
])
def setup_network(self):
self._setup_hostname()
self._setup_virtual_ethernet()
| import subprocess
class SetupNetworkMixin(object):
def _setup_hostname(self):
with self.get_attachment(['uts']).attach():
subprocess.check_call(['hostname', self.hostname])
def _setup_virtual_ethernet(self):
veth_name = 'veth-{name}'.format(name=self.name)
veth_host_name = 'hveth-{name}'.format(name=self.name)
# Create virtual ethernet pair
subprocess.check_call([
'ip', 'link', 'add',
'name', veth_host_name, 'type', 'veth',
'peer', 'name', veth_name, 'netns', str(self.pid())
])
# Add the container's host IP address and bring the interface up
subprocess.check_call(['ip', 'addr', 'add', self.ipaddr_host, 'dev', veth_host_name])
subprocess.check_call(['ip', 'link', 'set', veth_host_name, 'up'])
# Add the host interface to the bridge
# Assuming here that `cask0` bridge interface exists. It should
# be created and initialized by the Makefile.
subprocess.check_call(['ip', 'link', 'set', veth_host_name, 'master', 'cask0'])
# Set up virtual ethernet interface inside the container
with self.get_attachment(['net', 'uts']).attach():
subprocess.check_call([
'ifconfig', veth_name, self.ipaddr, 'up',
])
def setup_network(self):
self._setup_hostname()
self._setup_virtual_ethernet()
| Use container names, rather than hostnames, for virtual ethernet interface names | Use container names, rather than hostnames, for virtual ethernet interface names
Container names are guaranteed to be unique, but hostnames are not
| Python | mit | ianpreston/cask,ianpreston/cask | python | ## Code Before:
import subprocess
class SetupNetworkMixin(object):
def _setup_hostname(self):
with self.get_attachment(['uts']).attach():
subprocess.check_call(['hostname', self.hostname])
def _setup_virtual_ethernet(self):
veth_name = 'veth-{hostname}'.format(hostname=self.hostname)
veth_host_name = 'hveth-{hostname}'.format(hostname=self.hostname)
# Create virtual ethernet pair
subprocess.check_call([
'ip', 'link', 'add',
'name', veth_host_name, 'type', 'veth',
'peer', 'name', veth_name, 'netns', str(self.pid())
])
# Add the container's host IP address and bring the interface up
subprocess.check_call(['ip', 'addr', 'add', self.ipaddr_host, 'dev', veth_host_name])
subprocess.check_call(['ip', 'link', 'set', veth_host_name, 'up'])
# Add the host interface to the bridge
# Assuming here that `cask0` bridge interface exists. It should
# be created and initialized by the Makefile.
subprocess.check_call(['ip', 'link', 'set', veth_host_name, 'master', 'cask0'])
# Set up virtual ethernet interface inside the container
with self.get_attachment(['net', 'uts']).attach():
subprocess.check_call([
'ifconfig', veth_name, self.ipaddr, 'up',
])
def setup_network(self):
self._setup_hostname()
self._setup_virtual_ethernet()
## Instruction:
Use container names, rather than hostnames, for virtual ethernet interface names
Container names are guaranteed to be unique, but hostnames are not
## Code After:
import subprocess
class SetupNetworkMixin(object):
def _setup_hostname(self):
with self.get_attachment(['uts']).attach():
subprocess.check_call(['hostname', self.hostname])
def _setup_virtual_ethernet(self):
veth_name = 'veth-{name}'.format(name=self.name)
veth_host_name = 'hveth-{name}'.format(name=self.name)
# Create virtual ethernet pair
subprocess.check_call([
'ip', 'link', 'add',
'name', veth_host_name, 'type', 'veth',
'peer', 'name', veth_name, 'netns', str(self.pid())
])
# Add the container's host IP address and bring the interface up
subprocess.check_call(['ip', 'addr', 'add', self.ipaddr_host, 'dev', veth_host_name])
subprocess.check_call(['ip', 'link', 'set', veth_host_name, 'up'])
# Add the host interface to the bridge
# Assuming here that `cask0` bridge interface exists. It should
# be created and initialized by the Makefile.
subprocess.check_call(['ip', 'link', 'set', veth_host_name, 'master', 'cask0'])
# Set up virtual ethernet interface inside the container
with self.get_attachment(['net', 'uts']).attach():
subprocess.check_call([
'ifconfig', veth_name, self.ipaddr, 'up',
])
def setup_network(self):
self._setup_hostname()
self._setup_virtual_ethernet()
| import subprocess
class SetupNetworkMixin(object):
def _setup_hostname(self):
with self.get_attachment(['uts']).attach():
subprocess.check_call(['hostname', self.hostname])
def _setup_virtual_ethernet(self):
- veth_name = 'veth-{hostname}'.format(hostname=self.hostname)
? ---- ---- ----
+ veth_name = 'veth-{name}'.format(name=self.name)
- veth_host_name = 'hveth-{hostname}'.format(hostname=self.hostname)
? ---- ---- ----
+ veth_host_name = 'hveth-{name}'.format(name=self.name)
# Create virtual ethernet pair
subprocess.check_call([
'ip', 'link', 'add',
'name', veth_host_name, 'type', 'veth',
'peer', 'name', veth_name, 'netns', str(self.pid())
])
# Add the container's host IP address and bring the interface up
subprocess.check_call(['ip', 'addr', 'add', self.ipaddr_host, 'dev', veth_host_name])
subprocess.check_call(['ip', 'link', 'set', veth_host_name, 'up'])
# Add the host interface to the bridge
# Assuming here that `cask0` bridge interface exists. It should
# be created and initialized by the Makefile.
subprocess.check_call(['ip', 'link', 'set', veth_host_name, 'master', 'cask0'])
# Set up virtual ethernet interface inside the container
with self.get_attachment(['net', 'uts']).attach():
subprocess.check_call([
'ifconfig', veth_name, self.ipaddr, 'up',
])
def setup_network(self):
self._setup_hostname()
self._setup_virtual_ethernet() | 4 | 0.108108 | 2 | 2 |
46f1cedabf332f57025a768b268a4126a805c7aa | src/CoreBundle/Tests/KernelAwareTest.php | src/CoreBundle/Tests/KernelAwareTest.php | <?php
declare(strict_types=1);
/*
* This file is part of SolidInvoice project.
*
* (c) 2013-2017 Pierre du Plessis <info@customscripts.co.za>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace SolidInvoice\CoreBundle\Tests;
use AppKernel;
use Doctrine\ORM\EntityManager;
use Mockery\Adapter\Phpunit\MockeryPHPUnitIntegration;
use PHPUnit\Framework\TestCase;
use Symfony\Component\DependencyInjection\Container;
require_once __DIR__.'/../../../app/AppKernel.php';
abstract class KernelAwareTest extends TestCase
{
use MockeryPHPUnitIntegration;
/**
* @var AppKernel
*/
protected $kernel;
/**
* @var EntityManager
*/
protected $entityManager;
/**
* @var Container
*/
protected $container;
public function setUp(): void
{
$this->kernel = new AppKernel('test', true);
$this->kernel->boot();
$this->container = $this->kernel->getContainer();
parent::setUp();
}
public function tearDown(): void
{
$this->kernel->shutdown();
parent::tearDown();
}
}
| <?php
declare(strict_types=1);
/*
* This file is part of SolidInvoice project.
*
* (c) 2013-2017 Pierre du Plessis <info@customscripts.co.za>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace SolidInvoice\CoreBundle\Tests;
use SolidInvoice\Kernel;
use Doctrine\ORM\EntityManager;
use Mockery\Adapter\Phpunit\MockeryPHPUnitIntegration;
use PHPUnit\Framework\TestCase;
use Symfony\Component\DependencyInjection\Container;
abstract class KernelAwareTest extends TestCase
{
use MockeryPHPUnitIntegration;
/**
* @var Kernel
*/
protected $kernel;
/**
* @var EntityManager
*/
protected $entityManager;
/**
* @var Container
*/
protected $container;
public function setUp(): void
{
$this->kernel = new Kernel('test', true);
$this->kernel->boot();
$this->container = $this->kernel->getContainer();
parent::setUp();
}
public function tearDown(): void
{
$this->kernel->shutdown();
parent::tearDown();
}
}
| Fix KernalAwareTest to use the correct kernel | Fix KernalAwareTest to use the correct kernel
| PHP | mit | CSBill/CSBill,CSBill/CSBill,pierredup/SolidInvoice,pierredup/CSBill,SolidInvoice/SolidInvoice,SolidInvoice/SolidInvoice,CSBill/CSBill,CSBill/CSBill,SolidInvoice/SolidInvoice,pierredup/SolidInvoice,pierredup/CSBill,pierredup/CSBill,pierredup/CSBill | php | ## Code Before:
<?php
declare(strict_types=1);
/*
* This file is part of SolidInvoice project.
*
* (c) 2013-2017 Pierre du Plessis <info@customscripts.co.za>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace SolidInvoice\CoreBundle\Tests;
use AppKernel;
use Doctrine\ORM\EntityManager;
use Mockery\Adapter\Phpunit\MockeryPHPUnitIntegration;
use PHPUnit\Framework\TestCase;
use Symfony\Component\DependencyInjection\Container;
require_once __DIR__.'/../../../app/AppKernel.php';
abstract class KernelAwareTest extends TestCase
{
use MockeryPHPUnitIntegration;
/**
* @var AppKernel
*/
protected $kernel;
/**
* @var EntityManager
*/
protected $entityManager;
/**
* @var Container
*/
protected $container;
public function setUp(): void
{
$this->kernel = new AppKernel('test', true);
$this->kernel->boot();
$this->container = $this->kernel->getContainer();
parent::setUp();
}
public function tearDown(): void
{
$this->kernel->shutdown();
parent::tearDown();
}
}
## Instruction:
Fix KernalAwareTest to use the correct kernel
## Code After:
<?php
declare(strict_types=1);
/*
* This file is part of SolidInvoice project.
*
* (c) 2013-2017 Pierre du Plessis <info@customscripts.co.za>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace SolidInvoice\CoreBundle\Tests;
use SolidInvoice\Kernel;
use Doctrine\ORM\EntityManager;
use Mockery\Adapter\Phpunit\MockeryPHPUnitIntegration;
use PHPUnit\Framework\TestCase;
use Symfony\Component\DependencyInjection\Container;
abstract class KernelAwareTest extends TestCase
{
use MockeryPHPUnitIntegration;
/**
* @var Kernel
*/
protected $kernel;
/**
* @var EntityManager
*/
protected $entityManager;
/**
* @var Container
*/
protected $container;
public function setUp(): void
{
$this->kernel = new Kernel('test', true);
$this->kernel->boot();
$this->container = $this->kernel->getContainer();
parent::setUp();
}
public function tearDown(): void
{
$this->kernel->shutdown();
parent::tearDown();
}
}
| <?php
declare(strict_types=1);
/*
* This file is part of SolidInvoice project.
*
* (c) 2013-2017 Pierre du Plessis <info@customscripts.co.za>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace SolidInvoice\CoreBundle\Tests;
- use AppKernel;
+ use SolidInvoice\Kernel;
use Doctrine\ORM\EntityManager;
use Mockery\Adapter\Phpunit\MockeryPHPUnitIntegration;
use PHPUnit\Framework\TestCase;
use Symfony\Component\DependencyInjection\Container;
-
- require_once __DIR__.'/../../../app/AppKernel.php';
abstract class KernelAwareTest extends TestCase
{
use MockeryPHPUnitIntegration;
/**
- * @var AppKernel
? ---
+ * @var Kernel
*/
protected $kernel;
/**
* @var EntityManager
*/
protected $entityManager;
/**
* @var Container
*/
protected $container;
public function setUp(): void
{
- $this->kernel = new AppKernel('test', true);
? ---
+ $this->kernel = new Kernel('test', true);
$this->kernel->boot();
$this->container = $this->kernel->getContainer();
parent::setUp();
}
public function tearDown(): void
{
$this->kernel->shutdown();
parent::tearDown();
}
} | 8 | 0.135593 | 3 | 5 |
6166e53b1d7926d8cf482833bc2688dd708b6d49 | spec/support/auto_load_turnip.rb | spec/support/auto_load_turnip.rb |
module Turnip
module RSpec
class << self
def run(feature_file)
Turnip::Builder.build(feature_file).features.each do |feature|
describe feature.name, feature.metadata_hash do
before do
# This is kind of a hack, but it will make RSpec throw way nicer exceptions
example.metadata[:file_path] = feature_file
turnip_file_path = Pathname.new(feature_file)
root_acceptance_folder = Pathname.new(Dir.pwd).join("spec", "acceptance")
default_steps_file = root_acceptance_folder + turnip_file_path.relative_path_from(root_acceptance_folder).to_s.gsub(/^features/, "steps").gsub(/\.feature$/, "_steps.rb")
default_steps_module = [turnip_file_path.basename.to_s.sub(".feature", "").split("_").collect(&:capitalize), "Steps"].join
if File.exists?(default_steps_file)
require default_steps_file
if Module.const_defined?(default_steps_module)
extend Module.const_get(default_steps_module)
end
end
feature.backgrounds.map(&:steps).flatten.each do |step|
run_step(feature_file, step)
end
end
feature.scenarios.each do |scenario|
instance_eval <<-EOS, feature_file, scenario.line
describe scenario.name, scenario.metadata_hash do it(scenario.steps.map(&:description).join(" -> ")) do
scenario.steps.each do |step|
run_step(feature_file, step)
end
end
end
EOS
end
end
end
end
end
end
end
| RSpec.configure do |config|
config.before(turnip: true) do
example = Turnip::RSpec.fetch_current_example(self)
feature_file = example.metadata[:file_path]
# turnip_file_path = Pathname.new(File.expand_path(feature_file)).realpath
turnip_file_path = Pathname.new(feature_file).realpath
# sadly Dir.pwd might have changed because of aprescott/serif#71, so we need
# to find the equivalent of Rails.root
root_app_folder = Pathname.new(Dir.pwd)
root_app_folder = root_app_folder.parent until root_app_folder.children(false).map(&:to_s).include?("serif.gemspec")
root_acceptance_folder = root_app_folder.join("spec", "acceptance")
default_steps_file = root_acceptance_folder + turnip_file_path.relative_path_from(root_acceptance_folder).to_s.gsub(/^features/, "steps").gsub(/\.feature$/, "_steps.rb")
default_steps_module = [turnip_file_path.basename.to_s.sub(".feature", "").split("_").collect(&:capitalize), "Steps"].join
require default_steps_file.to_s
extend Module.const_get(default_steps_module)
end
end
| Switch away from patched Turnip autoloading. | Switch away from patched Turnip autoloading.
| Ruby | mit | aprescott/serif,aprescott/serif | ruby | ## Code Before:
module Turnip
module RSpec
class << self
def run(feature_file)
Turnip::Builder.build(feature_file).features.each do |feature|
describe feature.name, feature.metadata_hash do
before do
# This is kind of a hack, but it will make RSpec throw way nicer exceptions
example.metadata[:file_path] = feature_file
turnip_file_path = Pathname.new(feature_file)
root_acceptance_folder = Pathname.new(Dir.pwd).join("spec", "acceptance")
default_steps_file = root_acceptance_folder + turnip_file_path.relative_path_from(root_acceptance_folder).to_s.gsub(/^features/, "steps").gsub(/\.feature$/, "_steps.rb")
default_steps_module = [turnip_file_path.basename.to_s.sub(".feature", "").split("_").collect(&:capitalize), "Steps"].join
if File.exists?(default_steps_file)
require default_steps_file
if Module.const_defined?(default_steps_module)
extend Module.const_get(default_steps_module)
end
end
feature.backgrounds.map(&:steps).flatten.each do |step|
run_step(feature_file, step)
end
end
feature.scenarios.each do |scenario|
instance_eval <<-EOS, feature_file, scenario.line
describe scenario.name, scenario.metadata_hash do it(scenario.steps.map(&:description).join(" -> ")) do
scenario.steps.each do |step|
run_step(feature_file, step)
end
end
end
EOS
end
end
end
end
end
end
end
## Instruction:
Switch away from patched Turnip autoloading.
## Code After:
RSpec.configure do |config|
config.before(turnip: true) do
example = Turnip::RSpec.fetch_current_example(self)
feature_file = example.metadata[:file_path]
# turnip_file_path = Pathname.new(File.expand_path(feature_file)).realpath
turnip_file_path = Pathname.new(feature_file).realpath
# sadly Dir.pwd might have changed because of aprescott/serif#71, so we need
# to find the equivalent of Rails.root
root_app_folder = Pathname.new(Dir.pwd)
root_app_folder = root_app_folder.parent until root_app_folder.children(false).map(&:to_s).include?("serif.gemspec")
root_acceptance_folder = root_app_folder.join("spec", "acceptance")
default_steps_file = root_acceptance_folder + turnip_file_path.relative_path_from(root_acceptance_folder).to_s.gsub(/^features/, "steps").gsub(/\.feature$/, "_steps.rb")
default_steps_module = [turnip_file_path.basename.to_s.sub(".feature", "").split("_").collect(&:capitalize), "Steps"].join
require default_steps_file.to_s
extend Module.const_get(default_steps_module)
end
end
| + RSpec.configure do |config|
+ config.before(turnip: true) do
+ example = Turnip::RSpec.fetch_current_example(self)
+ feature_file = example.metadata[:file_path]
+ # turnip_file_path = Pathname.new(File.expand_path(feature_file)).realpath
+ turnip_file_path = Pathname.new(feature_file).realpath
- module Turnip
- module RSpec
- class << self
- def run(feature_file)
- Turnip::Builder.build(feature_file).features.each do |feature|
- describe feature.name, feature.metadata_hash do
- before do
- # This is kind of a hack, but it will make RSpec throw way nicer exceptions
- example.metadata[:file_path] = feature_file
- turnip_file_path = Pathname.new(feature_file)
- root_acceptance_folder = Pathname.new(Dir.pwd).join("spec", "acceptance")
+ # sadly Dir.pwd might have changed because of aprescott/serif#71, so we need
+ # to find the equivalent of Rails.root
+ root_app_folder = Pathname.new(Dir.pwd)
+ root_app_folder = root_app_folder.parent until root_app_folder.children(false).map(&:to_s).include?("serif.gemspec")
+ root_acceptance_folder = root_app_folder.join("spec", "acceptance")
- default_steps_file = root_acceptance_folder + turnip_file_path.relative_path_from(root_acceptance_folder).to_s.gsub(/^features/, "steps").gsub(/\.feature$/, "_steps.rb")
- default_steps_module = [turnip_file_path.basename.to_s.sub(".feature", "").split("_").collect(&:capitalize), "Steps"].join
+ default_steps_file = root_acceptance_folder + turnip_file_path.relative_path_from(root_acceptance_folder).to_s.gsub(/^features/, "steps").gsub(/\.feature$/, "_steps.rb")
+ default_steps_module = [turnip_file_path.basename.to_s.sub(".feature", "").split("_").collect(&:capitalize), "Steps"].join
- if File.exists?(default_steps_file)
- require default_steps_file
- if Module.const_defined?(default_steps_module)
- extend Module.const_get(default_steps_module)
- end
- end
+ require default_steps_file.to_s
+ extend Module.const_get(default_steps_module)
- feature.backgrounds.map(&:steps).flatten.each do |step|
- run_step(feature_file, step)
- end
- end
- feature.scenarios.each do |scenario|
- instance_eval <<-EOS, feature_file, scenario.line
- describe scenario.name, scenario.metadata_hash do it(scenario.steps.map(&:description).join(" -> ")) do
- scenario.steps.each do |step|
- run_step(feature_file, step)
- end
- end
- end
- EOS
- end
- end
- end
- end
- end
end
end | 52 | 1.181818 | 15 | 37 |
9f3abe5077fce0a2d7323a769fc063fca5b7aca8 | tests/test_bawlerd.py | tests/test_bawlerd.py | import os
from pg_bawler import bawlerd
class TestBawlerdConfig:
def test_build_config_location_list(self):
assert not bawlerd.conf.build_config_location_list(locations=())
user_conf = os.path.join(
os.path.expanduser('~'),
bawlerd.conf.DEFAULT_CONFIG_FILENAME)
system_conf = os.path.join(
'/etc/pg_bawler',
bawlerd.conf.DEFAULT_CONFIG_FILENAME)
assert user_conf in bawlerd.conf.build_config_location_list()
assert system_conf in bawlerd.conf.build_config_location_list()
| import io
import os
from textwrap import dedent
from pg_bawler import bawlerd
class TestBawlerdConfig:
def test_build_config_location_list(self):
assert not bawlerd.conf.build_config_location_list(locations=())
user_conf = os.path.join(
os.path.expanduser('~'),
bawlerd.conf.DEFAULT_CONFIG_FILENAME)
system_conf = os.path.join(
'/etc/pg_bawler',
bawlerd.conf.DEFAULT_CONFIG_FILENAME)
assert user_conf in bawlerd.conf.build_config_location_list()
assert system_conf in bawlerd.conf.build_config_location_list()
def test__load_file(self):
config = bawlerd.conf._load_file(io.StringIO(dedent("""\
logging:
formatters:
standard:
format: \"%(asctime)s %(levelname)s] %(name)s: %(message)s\"
handlers:
default:
level: "INFO"
formatter: standard
class: logging.StreamHandler
loggers:
"":
handlers: ["default"]
level: INFO
propagate: True
""")))
assert 'logging' in config
| Add simple test for _load_file | Add simple test for _load_file
Signed-off-by: Michal Kuffa <005ee1c97edba97d164343c993afee612ac25a0c@gmail.com>
| Python | bsd-3-clause | beezz/pg_bawler,beezz/pg_bawler | python | ## Code Before:
import os
from pg_bawler import bawlerd
class TestBawlerdConfig:
def test_build_config_location_list(self):
assert not bawlerd.conf.build_config_location_list(locations=())
user_conf = os.path.join(
os.path.expanduser('~'),
bawlerd.conf.DEFAULT_CONFIG_FILENAME)
system_conf = os.path.join(
'/etc/pg_bawler',
bawlerd.conf.DEFAULT_CONFIG_FILENAME)
assert user_conf in bawlerd.conf.build_config_location_list()
assert system_conf in bawlerd.conf.build_config_location_list()
## Instruction:
Add simple test for _load_file
Signed-off-by: Michal Kuffa <005ee1c97edba97d164343c993afee612ac25a0c@gmail.com>
## Code After:
import io
import os
from textwrap import dedent
from pg_bawler import bawlerd
class TestBawlerdConfig:
def test_build_config_location_list(self):
assert not bawlerd.conf.build_config_location_list(locations=())
user_conf = os.path.join(
os.path.expanduser('~'),
bawlerd.conf.DEFAULT_CONFIG_FILENAME)
system_conf = os.path.join(
'/etc/pg_bawler',
bawlerd.conf.DEFAULT_CONFIG_FILENAME)
assert user_conf in bawlerd.conf.build_config_location_list()
assert system_conf in bawlerd.conf.build_config_location_list()
def test__load_file(self):
config = bawlerd.conf._load_file(io.StringIO(dedent("""\
logging:
formatters:
standard:
format: \"%(asctime)s %(levelname)s] %(name)s: %(message)s\"
handlers:
default:
level: "INFO"
formatter: standard
class: logging.StreamHandler
loggers:
"":
handlers: ["default"]
level: INFO
propagate: True
""")))
assert 'logging' in config
| + import io
import os
+ from textwrap import dedent
from pg_bawler import bawlerd
class TestBawlerdConfig:
def test_build_config_location_list(self):
assert not bawlerd.conf.build_config_location_list(locations=())
user_conf = os.path.join(
os.path.expanduser('~'),
bawlerd.conf.DEFAULT_CONFIG_FILENAME)
system_conf = os.path.join(
'/etc/pg_bawler',
bawlerd.conf.DEFAULT_CONFIG_FILENAME)
assert user_conf in bawlerd.conf.build_config_location_list()
assert system_conf in bawlerd.conf.build_config_location_list()
+
+ def test__load_file(self):
+ config = bawlerd.conf._load_file(io.StringIO(dedent("""\
+ logging:
+ formatters:
+ standard:
+ format: \"%(asctime)s %(levelname)s] %(name)s: %(message)s\"
+ handlers:
+ default:
+ level: "INFO"
+ formatter: standard
+ class: logging.StreamHandler
+ loggers:
+ "":
+ handlers: ["default"]
+ level: INFO
+ propagate: True
+ """)))
+ assert 'logging' in config | 21 | 1.05 | 21 | 0 |
2394c25d2c15f1dacae40ce70ec3cd71cd195eda | Charts/Core/CMakeLists.txt | Charts/Core/CMakeLists.txt | set(Module_SRCS
vtkAxis.cxx
vtkAxisExtended.cxx
vtkChart.cxx
vtkChartHistogram2D.cxx
vtkChartLegend.cxx
vtkChartMatrix.cxx
vtkChartParallelCoordinates.cxx
vtkChartPie.cxx
vtkChartXY.cxx
vtkChartXYZ.cxx
vtkColorLegend.cxx
vtkColorSeries.cxx
vtkColorTransferControlPointsItem.cxx
vtkColorTransferFunctionItem.cxx
vtkCompositeControlPointsItem.cxx
vtkCompositeTransferFunctionItem.cxx
vtkContextPolygon.cxx
vtkControlPointsItem.cxx
vtkLookupTableItem.cxx
vtkPiecewiseControlPointsItem.cxx
vtkPiecewiseFunctionItem.cxx
vtkPiecewisePointHandleItem.cxx
vtkPlot.cxx
vtkPlotBar.cxx
vtkPlotGrid.cxx
vtkPlotHistogram2D.cxx
vtkPlotLine.cxx
vtkPlotParallelCoordinates.cxx # This adds a vtkInfovisCore dep for one class...
vtkPlotPie.cxx
vtkPlotPoints.cxx
vtkPlotStacked.cxx
vtkScalarsToColorsItem.cxx
vtkScatterPlotMatrix.cxx
)
set_source_files_properties(
vtkChart
vtkContextPolygon
vtkControlPointsItem
vtkPlot
vtkScalarsToColorsItem
ABSTRACT
)
vtk_module_library(vtkChartsCore ${Module_SRCS})
| set(Module_SRCS
vtkAxis.cxx
vtkAxisExtended.cxx
vtkChart.cxx
vtkChartHistogram2D.cxx
vtkChartLegend.cxx
vtkChartMatrix.cxx
vtkChartParallelCoordinates.cxx
vtkChartPie.cxx
vtkChartXY.cxx
vtkChartXYZ.cxx
vtkColorLegend.cxx
vtkColorSeries.cxx
vtkColorTransferControlPointsItem.cxx
vtkColorTransferFunctionItem.cxx
vtkCompositeControlPointsItem.cxx
vtkCompositeTransferFunctionItem.cxx
vtkContextPolygon.cxx
vtkControlPointsItem.cxx
vtkLookupTableItem.cxx
vtkPiecewiseControlPointsItem.cxx
vtkPiecewiseFunctionItem.cxx
vtkPiecewisePointHandleItem.cxx
vtkPlot.cxx
vtkPlotBar.cxx
vtkPlotGrid.cxx
vtkPlotHistogram2D.cxx
vtkPlotLine.cxx
vtkPlotParallelCoordinates.cxx # This adds a vtkInfovisCore dep for one class...
vtkPlotPie.cxx
vtkPlotPoints.cxx
vtkPlotStacked.cxx
vtkScalarsToColorsItem.cxx
vtkScatterPlotMatrix.cxx
)
set_source_files_properties(
vtkChart
vtkControlPointsItem
vtkPlot
vtkScalarsToColorsItem
ABSTRACT
)
set_source_files_properties(
vtkContextPolygon
WRAP_EXCLUDE
)
set_source_files_properties(
vtkContextPolygon
PROPERTIES WRAP_SPECIAL 1
)
vtk_module_library(vtkChartsCore ${Module_SRCS})
| Set WRAP_EXCLUDE for vtkContextPolygon, is not a vtkObject. | COMP: Set WRAP_EXCLUDE for vtkContextPolygon, is not a vtkObject.
The vtkContextPolygon class was set to ABSTRACT, but it isn't an
abstract class, so the intent was probably to exclude it from
wrapping. This class must be excluded from wrapping or it breaks
the Java wrapper build.
Change-Id: Id43da943c2b98b1ca1732ecdd07901fb70ac554e
| Text | bsd-3-clause | jmerkow/VTK,aashish24/VTK-old,aashish24/VTK-old,msmolens/VTK,keithroe/vtkoptix,hendradarwin/VTK,ashray/VTK-EVM,mspark93/VTK,johnkit/vtk-dev,gram526/VTK,sumedhasingla/VTK,demarle/VTK,candy7393/VTK,ashray/VTK-EVM,biddisco/VTK,ashray/VTK-EVM,biddisco/VTK,demarle/VTK,berendkleinhaneveld/VTK,msmolens/VTK,keithroe/vtkoptix,sankhesh/VTK,SimVascular/VTK,sumedhasingla/VTK,SimVascular/VTK,keithroe/vtkoptix,msmolens/VTK,biddisco/VTK,sumedhasingla/VTK,keithroe/vtkoptix,jmerkow/VTK,sankhesh/VTK,sankhesh/VTK,collects/VTK,hendradarwin/VTK,SimVascular/VTK,johnkit/vtk-dev,keithroe/vtkoptix,candy7393/VTK,keithroe/vtkoptix,candy7393/VTK,candy7393/VTK,collects/VTK,berendkleinhaneveld/VTK,biddisco/VTK,gram526/VTK,sankhesh/VTK,sumedhasingla/VTK,sankhesh/VTK,demarle/VTK,gram526/VTK,keithroe/vtkoptix,gram526/VTK,SimVascular/VTK,demarle/VTK,keithroe/vtkoptix,hendradarwin/VTK,msmolens/VTK,ashray/VTK-EVM,candy7393/VTK,jmerkow/VTK,aashish24/VTK-old,ashray/VTK-EVM,ashray/VTK-EVM,gram526/VTK,jmerkow/VTK,johnkit/vtk-dev,jmerkow/VTK,candy7393/VTK,sankhesh/VTK,aashish24/VTK-old,gram526/VTK,msmolens/VTK,collects/VTK,SimVascular/VTK,biddisco/VTK,msmolens/VTK,johnkit/vtk-dev,johnkit/vtk-dev,biddisco/VTK,berendkleinhaneveld/VTK,berendkleinhaneveld/VTK,berendkleinhaneveld/VTK,gram526/VTK,aashish24/VTK-old,SimVascular/VTK,mspark93/VTK,mspark93/VTK,sankhesh/VTK,collects/VTK,SimVascular/VTK,demarle/VTK,msmolens/VTK,berendkleinhaneveld/VTK,sumedhasingla/VTK,mspark93/VTK,msmolens/VTK,demarle/VTK,ashray/VTK-EVM,mspark93/VTK,hendradarwin/VTK,candy7393/VTK,jmerkow/VTK,mspark93/VTK,aashish24/VTK-old,collects/VTK,jmerkow/VTK,sumedhasingla/VTK,jmerkow/VTK,johnkit/vtk-dev,demarle/VTK,berendkleinhaneveld/VTK,biddisco/VTK,sankhesh/VTK,sumedhasingla/VTK,collects/VTK,mspark93/VTK,gram526/VTK,hendradarwin/VTK,johnkit/vtk-dev,hendradarwin/VTK,ashray/VTK-EVM,sumedhasingla/VTK,mspark93/VTK,demarle/VTK,hendradarwin/VTK,candy7393/VTK,SimVascular/VTK | text | ## Code Before:
set(Module_SRCS
vtkAxis.cxx
vtkAxisExtended.cxx
vtkChart.cxx
vtkChartHistogram2D.cxx
vtkChartLegend.cxx
vtkChartMatrix.cxx
vtkChartParallelCoordinates.cxx
vtkChartPie.cxx
vtkChartXY.cxx
vtkChartXYZ.cxx
vtkColorLegend.cxx
vtkColorSeries.cxx
vtkColorTransferControlPointsItem.cxx
vtkColorTransferFunctionItem.cxx
vtkCompositeControlPointsItem.cxx
vtkCompositeTransferFunctionItem.cxx
vtkContextPolygon.cxx
vtkControlPointsItem.cxx
vtkLookupTableItem.cxx
vtkPiecewiseControlPointsItem.cxx
vtkPiecewiseFunctionItem.cxx
vtkPiecewisePointHandleItem.cxx
vtkPlot.cxx
vtkPlotBar.cxx
vtkPlotGrid.cxx
vtkPlotHistogram2D.cxx
vtkPlotLine.cxx
vtkPlotParallelCoordinates.cxx # This adds a vtkInfovisCore dep for one class...
vtkPlotPie.cxx
vtkPlotPoints.cxx
vtkPlotStacked.cxx
vtkScalarsToColorsItem.cxx
vtkScatterPlotMatrix.cxx
)
set_source_files_properties(
vtkChart
vtkContextPolygon
vtkControlPointsItem
vtkPlot
vtkScalarsToColorsItem
ABSTRACT
)
vtk_module_library(vtkChartsCore ${Module_SRCS})
## Instruction:
COMP: Set WRAP_EXCLUDE for vtkContextPolygon, is not a vtkObject.
The vtkContextPolygon class was set to ABSTRACT, but it isn't an
abstract class, so the intent was probably to exclude it from
wrapping. This class must be excluded from wrapping or it breaks
the Java wrapper build.
Change-Id: Id43da943c2b98b1ca1732ecdd07901fb70ac554e
## Code After:
set(Module_SRCS
vtkAxis.cxx
vtkAxisExtended.cxx
vtkChart.cxx
vtkChartHistogram2D.cxx
vtkChartLegend.cxx
vtkChartMatrix.cxx
vtkChartParallelCoordinates.cxx
vtkChartPie.cxx
vtkChartXY.cxx
vtkChartXYZ.cxx
vtkColorLegend.cxx
vtkColorSeries.cxx
vtkColorTransferControlPointsItem.cxx
vtkColorTransferFunctionItem.cxx
vtkCompositeControlPointsItem.cxx
vtkCompositeTransferFunctionItem.cxx
vtkContextPolygon.cxx
vtkControlPointsItem.cxx
vtkLookupTableItem.cxx
vtkPiecewiseControlPointsItem.cxx
vtkPiecewiseFunctionItem.cxx
vtkPiecewisePointHandleItem.cxx
vtkPlot.cxx
vtkPlotBar.cxx
vtkPlotGrid.cxx
vtkPlotHistogram2D.cxx
vtkPlotLine.cxx
vtkPlotParallelCoordinates.cxx # This adds a vtkInfovisCore dep for one class...
vtkPlotPie.cxx
vtkPlotPoints.cxx
vtkPlotStacked.cxx
vtkScalarsToColorsItem.cxx
vtkScatterPlotMatrix.cxx
)
set_source_files_properties(
vtkChart
vtkControlPointsItem
vtkPlot
vtkScalarsToColorsItem
ABSTRACT
)
set_source_files_properties(
vtkContextPolygon
WRAP_EXCLUDE
)
set_source_files_properties(
vtkContextPolygon
PROPERTIES WRAP_SPECIAL 1
)
vtk_module_library(vtkChartsCore ${Module_SRCS})
| set(Module_SRCS
vtkAxis.cxx
vtkAxisExtended.cxx
vtkChart.cxx
vtkChartHistogram2D.cxx
vtkChartLegend.cxx
vtkChartMatrix.cxx
vtkChartParallelCoordinates.cxx
vtkChartPie.cxx
vtkChartXY.cxx
vtkChartXYZ.cxx
vtkColorLegend.cxx
vtkColorSeries.cxx
vtkColorTransferControlPointsItem.cxx
vtkColorTransferFunctionItem.cxx
vtkCompositeControlPointsItem.cxx
vtkCompositeTransferFunctionItem.cxx
vtkContextPolygon.cxx
vtkControlPointsItem.cxx
vtkLookupTableItem.cxx
vtkPiecewiseControlPointsItem.cxx
vtkPiecewiseFunctionItem.cxx
vtkPiecewisePointHandleItem.cxx
vtkPlot.cxx
vtkPlotBar.cxx
vtkPlotGrid.cxx
vtkPlotHistogram2D.cxx
vtkPlotLine.cxx
vtkPlotParallelCoordinates.cxx # This adds a vtkInfovisCore dep for one class...
vtkPlotPie.cxx
vtkPlotPoints.cxx
vtkPlotStacked.cxx
vtkScalarsToColorsItem.cxx
vtkScatterPlotMatrix.cxx
)
set_source_files_properties(
vtkChart
- vtkContextPolygon
vtkControlPointsItem
vtkPlot
vtkScalarsToColorsItem
ABSTRACT
)
+ set_source_files_properties(
+ vtkContextPolygon
+ WRAP_EXCLUDE
+ )
+
+ set_source_files_properties(
+ vtkContextPolygon
+ PROPERTIES WRAP_SPECIAL 1
+ )
+
vtk_module_library(vtkChartsCore ${Module_SRCS}) | 11 | 0.23913 | 10 | 1 |
3942198c05ec8a981d659dcd1aae5e8e5c72bda5 | runtime-testsuite/test/org/antlr/v4/test/runtime/states/State.java | runtime-testsuite/test/org/antlr/v4/test/runtime/states/State.java | /*
* Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root.
*/
package org.antlr.v4.test.runtime.states;
import org.antlr.v4.test.runtime.Stage;
public abstract class State {
public final State previousState;
public final Exception exception;
public abstract Stage getStage();
public boolean containsErrors() {
return exception != null;
}
public String getErrorMessage() {
String result = "State: " + getStage() + "; ";
if (exception != null) {
result += exception.toString();
result += "\nCause:\n";
result += exception.getCause().toString();
}
return result;
}
public State(State previousState, Exception exception) {
this.previousState = previousState;
this.exception = exception;
}
}
| /*
* Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root.
*/
package org.antlr.v4.test.runtime.states;
import org.antlr.v4.test.runtime.Stage;
public abstract class State {
public final State previousState;
public final Exception exception;
public abstract Stage getStage();
public boolean containsErrors() {
return exception != null;
}
public String getErrorMessage() {
String result = "State: " + getStage() + "; ";
if (exception != null) {
result += exception.toString();
if ( exception.getCause()!=null ) {
result += "\nCause:\n";
result += exception.getCause().toString();
}
}
return result;
}
public State(State previousState, Exception exception) {
this.previousState = previousState;
this.exception = exception;
}
}
| Augment error message during testing to include full cause of problem. (round 2 to avoid null ptr) | Augment error message during testing to include full cause of problem. (round 2 to avoid null ptr)
Signed-off-by: Terence Parr <275b89323d950c58c02f5ad8c33bac7ecb40d004@antlr.org>
| Java | bsd-3-clause | ericvergnaud/antlr4,parrt/antlr4,ericvergnaud/antlr4,ericvergnaud/antlr4,parrt/antlr4,antlr/antlr4,ericvergnaud/antlr4,parrt/antlr4,parrt/antlr4,parrt/antlr4,ericvergnaud/antlr4,ericvergnaud/antlr4,antlr/antlr4,ericvergnaud/antlr4,ericvergnaud/antlr4,antlr/antlr4,antlr/antlr4,antlr/antlr4,parrt/antlr4,ericvergnaud/antlr4,antlr/antlr4,parrt/antlr4,ericvergnaud/antlr4,antlr/antlr4,antlr/antlr4,parrt/antlr4,antlr/antlr4,antlr/antlr4,parrt/antlr4,parrt/antlr4 | java | ## Code Before:
/*
* Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root.
*/
package org.antlr.v4.test.runtime.states;
import org.antlr.v4.test.runtime.Stage;
public abstract class State {
public final State previousState;
public final Exception exception;
public abstract Stage getStage();
public boolean containsErrors() {
return exception != null;
}
public String getErrorMessage() {
String result = "State: " + getStage() + "; ";
if (exception != null) {
result += exception.toString();
result += "\nCause:\n";
result += exception.getCause().toString();
}
return result;
}
public State(State previousState, Exception exception) {
this.previousState = previousState;
this.exception = exception;
}
}
## Instruction:
Augment error message during testing to include full cause of problem. (round 2 to avoid null ptr)
Signed-off-by: Terence Parr <275b89323d950c58c02f5ad8c33bac7ecb40d004@antlr.org>
## Code After:
/*
* Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root.
*/
package org.antlr.v4.test.runtime.states;
import org.antlr.v4.test.runtime.Stage;
public abstract class State {
public final State previousState;
public final Exception exception;
public abstract Stage getStage();
public boolean containsErrors() {
return exception != null;
}
public String getErrorMessage() {
String result = "State: " + getStage() + "; ";
if (exception != null) {
result += exception.toString();
if ( exception.getCause()!=null ) {
result += "\nCause:\n";
result += exception.getCause().toString();
}
}
return result;
}
public State(State previousState, Exception exception) {
this.previousState = previousState;
this.exception = exception;
}
}
| /*
* Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root.
*/
package org.antlr.v4.test.runtime.states;
import org.antlr.v4.test.runtime.Stage;
public abstract class State {
public final State previousState;
public final Exception exception;
public abstract Stage getStage();
public boolean containsErrors() {
return exception != null;
}
public String getErrorMessage() {
String result = "State: " + getStage() + "; ";
if (exception != null) {
result += exception.toString();
+ if ( exception.getCause()!=null ) {
- result += "\nCause:\n";
+ result += "\nCause:\n";
? +
- result += exception.getCause().toString();
+ result += exception.getCause().toString();
? +
+ }
}
return result;
}
public State(State previousState, Exception exception) {
this.previousState = previousState;
this.exception = exception;
}
} | 6 | 0.166667 | 4 | 2 |
8e07407d4e1dbc73dbb24a48dd5e4a3e6b4a8133 | app/views/events/team_scoreboards/show.xml.builder | app/views/events/team_scoreboards/show.xml.builder | xml.instruct!
xml.EventResult do
xml.UniqueCode "skyderby-ws-performance-#{@event.id}-teams"
@team_ranking.ranking.each_with_index do |row, index|
xml.Entrant do
xml.CompetitionNo "00#{index + 1}"
xml.Name "#{row.team.name} (#{row.team.competitors.map(&:name).join(', ')})"
xml.Nation ''
xml.Rank index + 1
xml.Total format('%.1f', row.total_points)
end
end
end
| xml.instruct!
xml.EventResult do
xml.UniqueCode "skyderby-ws-performance-#{@event.id}-teams"
@team_ranking.ranking.each_with_index do |row, index|
xml.Entrant do
xml.CompetitionNo "00#{index + 1}"
xml.Name row.team.name
xml.Members row.team.competitors.map(&:name).join(', ')
xml.Nation ''
xml.Rank index + 1
xml.Total format('%.1f', row.total_points)
end
end
end
| Move members to dedicated field | Move members to dedicated field
| Ruby | agpl-3.0 | skyderby/skyderby,skyderby/skyderby,skyderby/skyderby,skyderby/skyderby,skyderby/skyderby | ruby | ## Code Before:
xml.instruct!
xml.EventResult do
xml.UniqueCode "skyderby-ws-performance-#{@event.id}-teams"
@team_ranking.ranking.each_with_index do |row, index|
xml.Entrant do
xml.CompetitionNo "00#{index + 1}"
xml.Name "#{row.team.name} (#{row.team.competitors.map(&:name).join(', ')})"
xml.Nation ''
xml.Rank index + 1
xml.Total format('%.1f', row.total_points)
end
end
end
## Instruction:
Move members to dedicated field
## Code After:
xml.instruct!
xml.EventResult do
xml.UniqueCode "skyderby-ws-performance-#{@event.id}-teams"
@team_ranking.ranking.each_with_index do |row, index|
xml.Entrant do
xml.CompetitionNo "00#{index + 1}"
xml.Name row.team.name
xml.Members row.team.competitors.map(&:name).join(', ')
xml.Nation ''
xml.Rank index + 1
xml.Total format('%.1f', row.total_points)
end
end
end
| xml.instruct!
xml.EventResult do
xml.UniqueCode "skyderby-ws-performance-#{@event.id}-teams"
@team_ranking.ranking.each_with_index do |row, index|
xml.Entrant do
xml.CompetitionNo "00#{index + 1}"
+ xml.Name row.team.name
- xml.Name "#{row.team.name} (#{row.team.competitors.map(&:name).join(', ')})"
? ^^ --------------------- ---
+ xml.Members row.team.competitors.map(&:name).join(', ')
? ^^ + ++
xml.Nation ''
xml.Rank index + 1
xml.Total format('%.1f', row.total_points)
end
end
end | 3 | 0.230769 | 2 | 1 |
a786324a4afe4774a9feb49e1bf6cdb21acf21a4 | etc/init/backup_bash.sh | etc/init/backup_bash.sh | BACKUPDIR=${HOME}/.backup/$(date +%Y%m%d_%H-%M-%S)
mkdir -p ${BACKUPDIR}
if [ -a ${HOME}/.inputrc ]; then mv ${HOME}/.inputrc ${BACKUPDIR}/.inputrc.bak; fi;
if [ -a ${HOME}/.bashrc ]; then mv ${HOME}/.bashrc ${BACKUPDIR}/.bashrc.bak; fi;
if [ -a ${HOME}/.bash_profile ]; then mv ${HOME}/.bash_profile ${BACKUPDIR}/.bash_profile.bak; fi;
| BACKUPDIR=${HOME}/.backup/$(date +%Y%m%d_%H-%M-%S)
mkdir -p ${BACKUPDIR}
if [ -a ${HOME}/.inputrc ]; then mv ${HOME}/.inputrc ${BACKUPDIR}/.inputrc.bak; fi;
if [ -a ${HOME}/.bashrc ]; then mv ${HOME}/.bashrc ${BACKUPDIR}/.bashrc.bak; fi;
if [ -a ${HOME}/.bash_profile ]; then mv ${HOME}/.bash_profile ${BACKUPDIR}/.bash_profile.bak; fi;
if [ -a ${HOME}/.bash_completion ]; then mv ${HOME}/.bash_completion ${BACKUPDIR}/.bash_completion.bak; fi;
| Fix bash config install error | Fix bash config install error
| Shell | mit | Tiryoh/dotfiles | shell | ## Code Before:
BACKUPDIR=${HOME}/.backup/$(date +%Y%m%d_%H-%M-%S)
mkdir -p ${BACKUPDIR}
if [ -a ${HOME}/.inputrc ]; then mv ${HOME}/.inputrc ${BACKUPDIR}/.inputrc.bak; fi;
if [ -a ${HOME}/.bashrc ]; then mv ${HOME}/.bashrc ${BACKUPDIR}/.bashrc.bak; fi;
if [ -a ${HOME}/.bash_profile ]; then mv ${HOME}/.bash_profile ${BACKUPDIR}/.bash_profile.bak; fi;
## Instruction:
Fix bash config install error
## Code After:
BACKUPDIR=${HOME}/.backup/$(date +%Y%m%d_%H-%M-%S)
mkdir -p ${BACKUPDIR}
if [ -a ${HOME}/.inputrc ]; then mv ${HOME}/.inputrc ${BACKUPDIR}/.inputrc.bak; fi;
if [ -a ${HOME}/.bashrc ]; then mv ${HOME}/.bashrc ${BACKUPDIR}/.bashrc.bak; fi;
if [ -a ${HOME}/.bash_profile ]; then mv ${HOME}/.bash_profile ${BACKUPDIR}/.bash_profile.bak; fi;
if [ -a ${HOME}/.bash_completion ]; then mv ${HOME}/.bash_completion ${BACKUPDIR}/.bash_completion.bak; fi;
| BACKUPDIR=${HOME}/.backup/$(date +%Y%m%d_%H-%M-%S)
mkdir -p ${BACKUPDIR}
if [ -a ${HOME}/.inputrc ]; then mv ${HOME}/.inputrc ${BACKUPDIR}/.inputrc.bak; fi;
if [ -a ${HOME}/.bashrc ]; then mv ${HOME}/.bashrc ${BACKUPDIR}/.bashrc.bak; fi;
if [ -a ${HOME}/.bash_profile ]; then mv ${HOME}/.bash_profile ${BACKUPDIR}/.bash_profile.bak; fi;
+ if [ -a ${HOME}/.bash_completion ]; then mv ${HOME}/.bash_completion ${BACKUPDIR}/.bash_completion.bak; fi; | 1 | 0.2 | 1 | 0 |
9236b68f85372773a53cef42d983d62de5d19b0a | src/main/java/com/forgeessentials/afterlife/InventoryGrave.java | src/main/java/com/forgeessentials/afterlife/InventoryGrave.java | package com.forgeessentials.afterlife;
import java.util.ArrayList;
import java.util.List;
import net.minecraft.inventory.InventoryBasic;
import net.minecraft.item.ItemStack;
public class InventoryGrave extends InventoryBasic {
private Grave grave;
public InventoryGrave(Grave grave)
{
super(grave.owner + "'s grave.", false, grave.getSize());
this.grave = grave;
}
@Override
public void openInventory()
{
for (int i = 0; i < getSizeInventory(); i++)
{
setInventorySlotContents(i, (ItemStack) null);
}
for (int i = 0; i < grave.inv.length; i++)
{
if (grave.inv[i] != null)
{
setInventorySlotContents(i, grave.inv[i].copy());
}
}
super.openInventory();
}
@Override
public void closeInventory()
{
List<ItemStack> list = new ArrayList<ItemStack>();
for (int i = 0; i < getSizeInventory(); i++)
{
ItemStack is = getStackInSlot(i);
if (is != null)
{
list.add(is);
}
}
grave.inv = list.toArray(new ItemStack[list.size()]);
grave.checkGrave();
grave.setOpen(false);
super.closeInventory();
}
}
| package com.forgeessentials.afterlife;
import com.forgeessentials.util.UserIdent;
import net.minecraft.inventory.InventoryBasic;
import net.minecraft.item.ItemStack;
import java.util.ArrayList;
import java.util.List;
public class InventoryGrave extends InventoryBasic {
private Grave grave;
public InventoryGrave(Grave grave)
{
super(new UserIdent(grave.owner).getUsername() + "'s grave.", false, grave.getSize());
this.grave = grave;
}
@Override
public void openInventory()
{
for (int i = 0; i < getSizeInventory(); i++)
{
setInventorySlotContents(i, (ItemStack) null);
}
for (int i = 0; i < grave.inv.length; i++)
{
if (grave.inv[i] != null)
{
setInventorySlotContents(i, grave.inv[i].copy());
}
}
super.openInventory();
}
@Override
public void closeInventory()
{
List<ItemStack> list = new ArrayList<ItemStack>();
for (int i = 0; i < getSizeInventory(); i++)
{
ItemStack is = getStackInSlot(i);
if (is != null)
{
list.add(is);
}
}
grave.inv = list.toArray(new ItemStack[list.size()]);
grave.checkGrave();
grave.setOpen(false);
super.closeInventory();
}
}
| Fix showing UUIDs instead of player names in the grave inventory | Fix showing UUIDs instead of player names in the grave inventory
| Java | epl-1.0 | ForgeEssentials/ForgeEssentialsMain,aschmois/ForgeEssentialsMain,CityOfLearning/ForgeEssentials,liachmodded/ForgeEssentials,planetguy32/ForgeEssentials,Techjar/ForgeEssentials | java | ## Code Before:
package com.forgeessentials.afterlife;
import java.util.ArrayList;
import java.util.List;
import net.minecraft.inventory.InventoryBasic;
import net.minecraft.item.ItemStack;
public class InventoryGrave extends InventoryBasic {
private Grave grave;
public InventoryGrave(Grave grave)
{
super(grave.owner + "'s grave.", false, grave.getSize());
this.grave = grave;
}
@Override
public void openInventory()
{
for (int i = 0; i < getSizeInventory(); i++)
{
setInventorySlotContents(i, (ItemStack) null);
}
for (int i = 0; i < grave.inv.length; i++)
{
if (grave.inv[i] != null)
{
setInventorySlotContents(i, grave.inv[i].copy());
}
}
super.openInventory();
}
@Override
public void closeInventory()
{
List<ItemStack> list = new ArrayList<ItemStack>();
for (int i = 0; i < getSizeInventory(); i++)
{
ItemStack is = getStackInSlot(i);
if (is != null)
{
list.add(is);
}
}
grave.inv = list.toArray(new ItemStack[list.size()]);
grave.checkGrave();
grave.setOpen(false);
super.closeInventory();
}
}
## Instruction:
Fix showing UUIDs instead of player names in the grave inventory
## Code After:
package com.forgeessentials.afterlife;
import com.forgeessentials.util.UserIdent;
import net.minecraft.inventory.InventoryBasic;
import net.minecraft.item.ItemStack;
import java.util.ArrayList;
import java.util.List;
public class InventoryGrave extends InventoryBasic {
private Grave grave;
public InventoryGrave(Grave grave)
{
super(new UserIdent(grave.owner).getUsername() + "'s grave.", false, grave.getSize());
this.grave = grave;
}
@Override
public void openInventory()
{
for (int i = 0; i < getSizeInventory(); i++)
{
setInventorySlotContents(i, (ItemStack) null);
}
for (int i = 0; i < grave.inv.length; i++)
{
if (grave.inv[i] != null)
{
setInventorySlotContents(i, grave.inv[i].copy());
}
}
super.openInventory();
}
@Override
public void closeInventory()
{
List<ItemStack> list = new ArrayList<ItemStack>();
for (int i = 0; i < getSizeInventory(); i++)
{
ItemStack is = getStackInSlot(i);
if (is != null)
{
list.add(is);
}
}
grave.inv = list.toArray(new ItemStack[list.size()]);
grave.checkGrave();
grave.setOpen(false);
super.closeInventory();
}
}
| package com.forgeessentials.afterlife;
+
+ import com.forgeessentials.util.UserIdent;
+ import net.minecraft.inventory.InventoryBasic;
+ import net.minecraft.item.ItemStack;
import java.util.ArrayList;
import java.util.List;
-
- import net.minecraft.inventory.InventoryBasic;
- import net.minecraft.item.ItemStack;
public class InventoryGrave extends InventoryBasic {
private Grave grave;
public InventoryGrave(Grave grave)
{
- super(grave.owner + "'s grave.", false, grave.getSize());
+ super(new UserIdent(grave.owner).getUsername() + "'s grave.", false, grave.getSize());
? ++++++++++++++ +++++++++++++++
this.grave = grave;
}
@Override
public void openInventory()
{
for (int i = 0; i < getSizeInventory(); i++)
{
setInventorySlotContents(i, (ItemStack) null);
}
for (int i = 0; i < grave.inv.length; i++)
{
if (grave.inv[i] != null)
{
setInventorySlotContents(i, grave.inv[i].copy());
}
}
super.openInventory();
}
@Override
public void closeInventory()
{
List<ItemStack> list = new ArrayList<ItemStack>();
for (int i = 0; i < getSizeInventory(); i++)
{
ItemStack is = getStackInSlot(i);
if (is != null)
{
list.add(is);
}
}
grave.inv = list.toArray(new ItemStack[list.size()]);
grave.checkGrave();
grave.setOpen(false);
super.closeInventory();
}
} | 9 | 0.163636 | 5 | 4 |
8b00632dd6659b9b3c3f792564a81c7b47e0da2c | setup.py | setup.py | import sys
import os.path as op
from setuptools import setup
from distutils.extension import Extension
exts = []
if sys.platform == 'darwin':
exts.append(Extension(
'_send2trash_osx',
[op.join('modules', 'send2trash_osx.c')],
extra_link_args=['-framework', 'CoreServices'],
))
if sys.platform == 'win32':
exts.append(Extension(
'_send2trash_win',
[op.join('modules', 'send2trash_win.c')],
extra_link_args = ['shell32.lib'],
))
setup(
name='Send2Trash',
version='1.0.0',
author='Hardcoded Software',
author_email='hsoft@hardcoded.net',
packages=['send2trash'],
scripts=[],
ext_modules = exts,
url='http://hg.hardcoded.net/send2trash/',
license='LICENSE',
description='Send file to trash natively under Mac OS X, Windows and Linux.',
) | import sys
import os.path as op
from setuptools import setup
from distutils.extension import Extension
exts = []
if sys.platform == 'darwin':
exts.append(Extension(
'_send2trash_osx',
[op.join('modules', 'send2trash_osx.c')],
extra_link_args=['-framework', 'CoreServices'],
))
if sys.platform == 'win32':
exts.append(Extension(
'_send2trash_win',
[op.join('modules', 'send2trash_win.c')],
extra_link_args = ['shell32.lib'],
))
setup(
name='Send2Trash',
version='1.0.0',
author='Hardcoded Software',
author_email='hsoft@hardcoded.net',
packages=['send2trash'],
scripts=[],
ext_modules = exts,
url='http://hg.hardcoded.net/send2trash/',
license='LICENSE',
description='Send file to trash natively under Mac OS X, Windows and Linux.',
zip_safe=False,
) | Set zip_safe to False, as it causes problems when creating executables for Windows of apps using it. | Set zip_safe to False, as it causes problems when creating executables for Windows of apps using it.
| Python | bsd-3-clause | hsoft/send2trash | python | ## Code Before:
import sys
import os.path as op
from setuptools import setup
from distutils.extension import Extension
exts = []
if sys.platform == 'darwin':
exts.append(Extension(
'_send2trash_osx',
[op.join('modules', 'send2trash_osx.c')],
extra_link_args=['-framework', 'CoreServices'],
))
if sys.platform == 'win32':
exts.append(Extension(
'_send2trash_win',
[op.join('modules', 'send2trash_win.c')],
extra_link_args = ['shell32.lib'],
))
setup(
name='Send2Trash',
version='1.0.0',
author='Hardcoded Software',
author_email='hsoft@hardcoded.net',
packages=['send2trash'],
scripts=[],
ext_modules = exts,
url='http://hg.hardcoded.net/send2trash/',
license='LICENSE',
description='Send file to trash natively under Mac OS X, Windows and Linux.',
)
## Instruction:
Set zip_safe to False, as it causes problems when creating executables for Windows of apps using it.
## Code After:
import sys
import os.path as op
from setuptools import setup
from distutils.extension import Extension
exts = []
if sys.platform == 'darwin':
exts.append(Extension(
'_send2trash_osx',
[op.join('modules', 'send2trash_osx.c')],
extra_link_args=['-framework', 'CoreServices'],
))
if sys.platform == 'win32':
exts.append(Extension(
'_send2trash_win',
[op.join('modules', 'send2trash_win.c')],
extra_link_args = ['shell32.lib'],
))
setup(
name='Send2Trash',
version='1.0.0',
author='Hardcoded Software',
author_email='hsoft@hardcoded.net',
packages=['send2trash'],
scripts=[],
ext_modules = exts,
url='http://hg.hardcoded.net/send2trash/',
license='LICENSE',
description='Send file to trash natively under Mac OS X, Windows and Linux.',
zip_safe=False,
) | import sys
import os.path as op
from setuptools import setup
from distutils.extension import Extension
exts = []
if sys.platform == 'darwin':
exts.append(Extension(
'_send2trash_osx',
[op.join('modules', 'send2trash_osx.c')],
extra_link_args=['-framework', 'CoreServices'],
))
if sys.platform == 'win32':
exts.append(Extension(
'_send2trash_win',
[op.join('modules', 'send2trash_win.c')],
extra_link_args = ['shell32.lib'],
))
setup(
name='Send2Trash',
version='1.0.0',
author='Hardcoded Software',
author_email='hsoft@hardcoded.net',
packages=['send2trash'],
scripts=[],
ext_modules = exts,
url='http://hg.hardcoded.net/send2trash/',
license='LICENSE',
description='Send file to trash natively under Mac OS X, Windows and Linux.',
+ zip_safe=False,
) | 1 | 0.030303 | 1 | 0 |
eafe7ed56a0fb0058cb9c0840a4283a4a5346721 | railsdav.gemspec | railsdav.gemspec | Gem::Specification.new do |s|
s.name = 'railsdav'
s.version = '0.0.8'
s.date = Time.now
s.authors = ['Willem van Kerkhof']
s.licenses = ['MIT']
s.email = %q{wvk@consolving.de}
s.summary = %q{Make your Rails 3/4 resources accessible via WebDAV}
s.homepage = %q{http://github.com/wvk/railsdav}
s.description = %q{Provides basic Rails 3/Rails 4 extensions for making your business resources accessible via WebDAV. This gem does by no means by no means implement the full WebDAV semantics, but it suffices to access your app with client(-libs) such as Konqueror, cadaver, davfs2 or NetDrive}
s.files = %w(README.md init.rb lib/railsdav.rb lib/railsdav/routing_extensions.rb lib/railsdav/request_extensions.rb lib/railsdav/renderer/response_collector.rb lib/railsdav/renderer/response_type_selector.rb lib/railsdav/controller_extensions.rb lib/railsdav/renderer.rb)
end
| Gem::Specification.new do |s|
s.name = 'railsdav'
s.version = '0.0.9'
s.date = Time.now
s.authors = ['Willem van Kerkhof']
s.licenses = ['MIT']
s.email = %q{wvk@consolving.de}
s.summary = %q{Make your Rails 3/4 resources accessible via WebDAV}
s.homepage = %q{http://github.com/wvk/railsdav}
s.description = %q{Provides basic Rails 3/Rails 4 extensions for making your business resources accessible via WebDAV. This gem does by no means by no means implement the full WebDAV semantics, but it suffices to access your app with client(-libs) such as Konqueror, cadaver, davfs2 or NetDrive}
s.files = %w(README.md init.rb lib/railsdav.rb lib/railsdav/routing_extensions.rb lib/railsdav/request_extensions.rb lib/railsdav/renderer/response_collector.rb lib/railsdav/renderer/response_type_selector.rb lib/railsdav/controller_extensions.rb lib/railsdav/renderer.rb railsdav/renderer/resource_descriptor.rb
)
end
| Fix missing file in gemspec | Fix missing file in gemspec
| Ruby | mit | wvk/railsdav | ruby | ## Code Before:
Gem::Specification.new do |s|
s.name = 'railsdav'
s.version = '0.0.8'
s.date = Time.now
s.authors = ['Willem van Kerkhof']
s.licenses = ['MIT']
s.email = %q{wvk@consolving.de}
s.summary = %q{Make your Rails 3/4 resources accessible via WebDAV}
s.homepage = %q{http://github.com/wvk/railsdav}
s.description = %q{Provides basic Rails 3/Rails 4 extensions for making your business resources accessible via WebDAV. This gem does by no means by no means implement the full WebDAV semantics, but it suffices to access your app with client(-libs) such as Konqueror, cadaver, davfs2 or NetDrive}
s.files = %w(README.md init.rb lib/railsdav.rb lib/railsdav/routing_extensions.rb lib/railsdav/request_extensions.rb lib/railsdav/renderer/response_collector.rb lib/railsdav/renderer/response_type_selector.rb lib/railsdav/controller_extensions.rb lib/railsdav/renderer.rb)
end
## Instruction:
Fix missing file in gemspec
## Code After:
Gem::Specification.new do |s|
s.name = 'railsdav'
s.version = '0.0.9'
s.date = Time.now
s.authors = ['Willem van Kerkhof']
s.licenses = ['MIT']
s.email = %q{wvk@consolving.de}
s.summary = %q{Make your Rails 3/4 resources accessible via WebDAV}
s.homepage = %q{http://github.com/wvk/railsdav}
s.description = %q{Provides basic Rails 3/Rails 4 extensions for making your business resources accessible via WebDAV. This gem does by no means by no means implement the full WebDAV semantics, but it suffices to access your app with client(-libs) such as Konqueror, cadaver, davfs2 or NetDrive}
s.files = %w(README.md init.rb lib/railsdav.rb lib/railsdav/routing_extensions.rb lib/railsdav/request_extensions.rb lib/railsdav/renderer/response_collector.rb lib/railsdav/renderer/response_type_selector.rb lib/railsdav/controller_extensions.rb lib/railsdav/renderer.rb railsdav/renderer/resource_descriptor.rb
)
end
| Gem::Specification.new do |s|
s.name = 'railsdav'
- s.version = '0.0.8'
? ^
+ s.version = '0.0.9'
? ^
s.date = Time.now
s.authors = ['Willem van Kerkhof']
s.licenses = ['MIT']
s.email = %q{wvk@consolving.de}
s.summary = %q{Make your Rails 3/4 resources accessible via WebDAV}
s.homepage = %q{http://github.com/wvk/railsdav}
s.description = %q{Provides basic Rails 3/Rails 4 extensions for making your business resources accessible via WebDAV. This gem does by no means by no means implement the full WebDAV semantics, but it suffices to access your app with client(-libs) such as Konqueror, cadaver, davfs2 or NetDrive}
- s.files = %w(README.md init.rb lib/railsdav.rb lib/railsdav/routing_extensions.rb lib/railsdav/request_extensions.rb lib/railsdav/renderer/response_collector.rb lib/railsdav/renderer/response_type_selector.rb lib/railsdav/controller_extensions.rb lib/railsdav/renderer.rb)
? ^
+ s.files = %w(README.md init.rb lib/railsdav.rb lib/railsdav/routing_extensions.rb lib/railsdav/request_extensions.rb lib/railsdav/renderer/response_collector.rb lib/railsdav/renderer/response_type_selector.rb lib/railsdav/controller_extensions.rb lib/railsdav/renderer.rb railsdav/renderer/resource_descriptor.rb
? ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+ )
end | 5 | 0.416667 | 3 | 2 |
e3c8e72341fea566113e510b058141c9ff75c0ea | setup.py | setup.py | try:
from setuptools import setup
except ImportError:
from distutils.core import setup
config = {
'description': 'A LMTP server class',
'long_description': 'A LMTP counterpart to smtpd in the Python standard library',
'author': 'Matt Molyneaux',
'url': 'https://github.com/moggers87/lmtpd',
'download_url': 'http://pypi.python.org/pypi/lmtpd',
'author_email': 'moggers87+git@moggers87.co.uk',
'version': '6.1.0',
'license': 'MIT', # apparently nothing searches classifiers :(
'packages': ['lmtpd'],
'data_files': [('share/lmtpd', ['LICENSE', 'PY-LIC'])],
'name': 'lmtpd',
'classifiers': [
'License :: OSI Approved :: MIT License',
'License :: OSI Approved :: Python Software Foundation License',
'Development Status :: 4 - Beta',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
'Programming Language :: Python :: Implementation :: CPython',
'Intended Audience :: Developers',
'Topic :: Communications :: Email'],
'test_suite': 'lmtpd.tests'
}
setup(**config)
| try:
from setuptools import setup
except ImportError:
from distutils.core import setup
config = {
'description': 'A LMTP server class',
'long_description': 'A LMTP counterpart to smtpd in the Python standard library',
'author': 'Matt Molyneaux',
'url': 'https://github.com/moggers87/lmtpd',
'download_url': 'http://pypi.python.org/pypi/lmtpd',
'author_email': 'moggers87+git@moggers87.co.uk',
'version': '6.1.0',
'license': 'MIT', # apparently nothing searches classifiers :(
'packages': ['lmtpd'],
'data_files': [('share/lmtpd', ['LICENSE', 'PY-LIC'])],
'name': 'lmtpd',
'classifiers': [
'License :: OSI Approved :: MIT License',
'License :: OSI Approved :: Python Software Foundation License',
'Development Status :: 5 - Production/Stable',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
'Programming Language :: Python :: Implementation :: CPython',
'Intended Audience :: Developers',
'Topic :: Communications :: Email'],
'test_suite': 'lmtpd.tests'
}
setup(**config)
| Mark package as a stable | Mark package as a stable
| Python | mit | moggers87/lmtpd | python | ## Code Before:
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
config = {
'description': 'A LMTP server class',
'long_description': 'A LMTP counterpart to smtpd in the Python standard library',
'author': 'Matt Molyneaux',
'url': 'https://github.com/moggers87/lmtpd',
'download_url': 'http://pypi.python.org/pypi/lmtpd',
'author_email': 'moggers87+git@moggers87.co.uk',
'version': '6.1.0',
'license': 'MIT', # apparently nothing searches classifiers :(
'packages': ['lmtpd'],
'data_files': [('share/lmtpd', ['LICENSE', 'PY-LIC'])],
'name': 'lmtpd',
'classifiers': [
'License :: OSI Approved :: MIT License',
'License :: OSI Approved :: Python Software Foundation License',
'Development Status :: 4 - Beta',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
'Programming Language :: Python :: Implementation :: CPython',
'Intended Audience :: Developers',
'Topic :: Communications :: Email'],
'test_suite': 'lmtpd.tests'
}
setup(**config)
## Instruction:
Mark package as a stable
## Code After:
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
config = {
'description': 'A LMTP server class',
'long_description': 'A LMTP counterpart to smtpd in the Python standard library',
'author': 'Matt Molyneaux',
'url': 'https://github.com/moggers87/lmtpd',
'download_url': 'http://pypi.python.org/pypi/lmtpd',
'author_email': 'moggers87+git@moggers87.co.uk',
'version': '6.1.0',
'license': 'MIT', # apparently nothing searches classifiers :(
'packages': ['lmtpd'],
'data_files': [('share/lmtpd', ['LICENSE', 'PY-LIC'])],
'name': 'lmtpd',
'classifiers': [
'License :: OSI Approved :: MIT License',
'License :: OSI Approved :: Python Software Foundation License',
'Development Status :: 5 - Production/Stable',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
'Programming Language :: Python :: Implementation :: CPython',
'Intended Audience :: Developers',
'Topic :: Communications :: Email'],
'test_suite': 'lmtpd.tests'
}
setup(**config)
| try:
from setuptools import setup
except ImportError:
from distutils.core import setup
config = {
'description': 'A LMTP server class',
'long_description': 'A LMTP counterpart to smtpd in the Python standard library',
'author': 'Matt Molyneaux',
'url': 'https://github.com/moggers87/lmtpd',
'download_url': 'http://pypi.python.org/pypi/lmtpd',
'author_email': 'moggers87+git@moggers87.co.uk',
'version': '6.1.0',
'license': 'MIT', # apparently nothing searches classifiers :(
'packages': ['lmtpd'],
'data_files': [('share/lmtpd', ['LICENSE', 'PY-LIC'])],
'name': 'lmtpd',
'classifiers': [
'License :: OSI Approved :: MIT License',
'License :: OSI Approved :: Python Software Foundation License',
- 'Development Status :: 4 - Beta',
? ^ ^^
+ 'Development Status :: 5 - Production/Stable',
? ^ ^^^^^^^^^^^^ +++
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
'Programming Language :: Python :: Implementation :: CPython',
'Intended Audience :: Developers',
'Topic :: Communications :: Email'],
'test_suite': 'lmtpd.tests'
}
setup(**config) | 2 | 0.0625 | 1 | 1 |
0302ef4fb6af8ea8d9d8e5c4f69d11ff5aacd427 | spec/api_classes/library_spec.rb | spec/api_classes/library_spec.rb | require "spec_helper"
describe LastFM::Library do
it "should define unrestricted methods" do
LastFM::Library.unrestricted_methods.should == [:get_albums, :get_artists, :get_tracks]
end
it "should define restricted methods" do
LastFM::Library.restricted_methods.should == [:add_album, :add_artist, :add_track]
end
end
| require "spec_helper"
describe LastFM::Library do
it "should define unrestricted methods" do
LastFM::Library.should respond_to(:get_albums, :get_artists, :get_tracks)
end
it "should define restricted methods" do
LastFM::Library.should respond_to(:add_album, :add_artist, :add_track)
end
end
| Check restricted method definitions for Library | Check restricted method definitions for Library
| Ruby | mit | pch/lastfm-client | ruby | ## Code Before:
require "spec_helper"
describe LastFM::Library do
it "should define unrestricted methods" do
LastFM::Library.unrestricted_methods.should == [:get_albums, :get_artists, :get_tracks]
end
it "should define restricted methods" do
LastFM::Library.restricted_methods.should == [:add_album, :add_artist, :add_track]
end
end
## Instruction:
Check restricted method definitions for Library
## Code After:
require "spec_helper"
describe LastFM::Library do
it "should define unrestricted methods" do
LastFM::Library.should respond_to(:get_albums, :get_artists, :get_tracks)
end
it "should define restricted methods" do
LastFM::Library.should respond_to(:add_album, :add_artist, :add_track)
end
end
| require "spec_helper"
describe LastFM::Library do
it "should define unrestricted methods" do
- LastFM::Library.unrestricted_methods.should == [:get_albums, :get_artists, :get_tracks]
? --------------------- ^^^^ ^
+ LastFM::Library.should respond_to(:get_albums, :get_artists, :get_tracks)
? ^^^^^^^^^^^ ^
end
it "should define restricted methods" do
- LastFM::Library.restricted_methods.should == [:add_album, :add_artist, :add_track]
? ------------------- ^^^^ ^
+ LastFM::Library.should respond_to(:add_album, :add_artist, :add_track)
? ^^^^^^^^^^^ ^
end
end | 4 | 0.363636 | 2 | 2 |
3e84010c4b4fa3016ffaf5afab529aa50fe9575f | src/resourceloader.ts | src/resourceloader.ts | /**
* Map a resource name to a URL.
*
* This particular mapping function works in a nodejs context.
*
* @param resourceName relative path to the resource from the main src directory.
* @return a URL which points to the resource.
*/
export function toUrl(resourceName: string): string {
let mainPath = __dirname;
return "file://" + mainPath + "/" + resourceName;
}
| /**
* Map a resource name to a URL.
*
* This particular mapping function works in a nodejs context.
*
* @param resourceName relative path to the resource from the main src directory.
* @return a URL which points to the resource.
*/
export function toUrl(resourceName: string): string {
let mainPath = __dirname;
return "file://" + mainPath.replace(/\\/g, "/") + "/" + resourceName;
}
| Fix for CSS and resource loading on Windows. | Fix for CSS and resource loading on Windows.
| TypeScript | mit | sedwards2009/extraterm,sedwards2009/extraterm,sedwards2009/extraterm,sedwards2009/extraterm,sedwards2009/extraterm | typescript | ## Code Before:
/**
* Map a resource name to a URL.
*
* This particular mapping function works in a nodejs context.
*
* @param resourceName relative path to the resource from the main src directory.
* @return a URL which points to the resource.
*/
export function toUrl(resourceName: string): string {
let mainPath = __dirname;
return "file://" + mainPath + "/" + resourceName;
}
## Instruction:
Fix for CSS and resource loading on Windows.
## Code After:
/**
* Map a resource name to a URL.
*
* This particular mapping function works in a nodejs context.
*
* @param resourceName relative path to the resource from the main src directory.
* @return a URL which points to the resource.
*/
export function toUrl(resourceName: string): string {
let mainPath = __dirname;
return "file://" + mainPath.replace(/\\/g, "/") + "/" + resourceName;
}
| /**
* Map a resource name to a URL.
*
* This particular mapping function works in a nodejs context.
*
* @param resourceName relative path to the resource from the main src directory.
* @return a URL which points to the resource.
*/
export function toUrl(resourceName: string): string {
let mainPath = __dirname;
- return "file://" + mainPath + "/" + resourceName;
+ return "file://" + mainPath.replace(/\\/g, "/") + "/" + resourceName;
? ++++++++++++++++++++
} | 2 | 0.166667 | 1 | 1 |
07021f5233e3f71d6507749ac7ea97d1a1a6f538 | README.md | README.md | Firefox OS Certification Testsuite
==================================
Tests and tools to verify the functionality and characteristics of
Firefox OS on real devices.
For more information see: http://fxos-certsuite.readthedocs.org
| Firefox OS Certification Testsuite
==================================
Tests and tools to verify the functionality and characteristics of
Firefox OS on real devices.
Before running the tests, make sure you read the full documentation
at http://fxos-certsuite.readthedocs.org/ or in the *docs/* folder.
| Add leading slash and mention that docs are also in-repo | Add leading slash and mention that docs are also in-repo
| Markdown | mpl-2.0 | Conjuror/fxos-certsuite,askeing/fxos-certsuite,oouyang/fxos-certsuite,oouyang/fxos-certsuite,askeing/fxos-certsuite,askeing/fxos-certsuite,cr/fxos-certsuite,cr/fxos-certsuite,ypwalter/fxos-certsuite,oouyang/fxos-certsuite,askeing/fxos-certsuite,oouyang/fxos-certsuite,ShakoHo/fxos-certsuite,mozilla-b2g/fxos-certsuite,mozilla-b2g/fxos-certsuite,askeing/fxos-certsuite,ShakoHo/fxos-certsuite,ypwalter/fxos-certsuite,Conjuror/fxos-certsuite,Conjuror/fxos-certsuite,mozilla-b2g/fxos-certsuite,ypwalter/fxos-certsuite,ShakoHo/fxos-certsuite,ShakoHo/fxos-certsuite,Conjuror/fxos-certsuite,ypwalter/fxos-certsuite,mozilla-b2g/fxos-certsuite,oouyang/fxos-certsuite,ShakoHo/fxos-certsuite,mozilla-b2g/fxos-certsuite,askeing/fxos-certsuite,Conjuror/fxos-certsuite,oouyang/fxos-certsuite,oouyang/fxos-certsuite,cr/fxos-certsuite,askeing/fxos-certsuite,cr/fxos-certsuite,Conjuror/fxos-certsuite,ShakoHo/fxos-certsuite,cr/fxos-certsuite,ypwalter/fxos-certsuite,cr/fxos-certsuite,ypwalter/fxos-certsuite,ypwalter/fxos-certsuite,ShakoHo/fxos-certsuite,mozilla-b2g/fxos-certsuite,mozilla-b2g/fxos-certsuite,cr/fxos-certsuite,Conjuror/fxos-certsuite | markdown | ## Code Before:
Firefox OS Certification Testsuite
==================================
Tests and tools to verify the functionality and characteristics of
Firefox OS on real devices.
For more information see: http://fxos-certsuite.readthedocs.org
## Instruction:
Add leading slash and mention that docs are also in-repo
## Code After:
Firefox OS Certification Testsuite
==================================
Tests and tools to verify the functionality and characteristics of
Firefox OS on real devices.
Before running the tests, make sure you read the full documentation
at http://fxos-certsuite.readthedocs.org/ or in the *docs/* folder.
| Firefox OS Certification Testsuite
==================================
Tests and tools to verify the functionality and characteristics of
Firefox OS on real devices.
- For more information see: http://fxos-certsuite.readthedocs.org
+ Before running the tests, make sure you read the full documentation
+ at http://fxos-certsuite.readthedocs.org/ or in the *docs/* folder. | 3 | 0.428571 | 2 | 1 |
dfcd2938727b333a058b81f48532786e3c686405 | .travis.yml | .travis.yml | language: python
sudo: false
python:
- "2.7"
- "3.4"
- "3.5"
- "3.6"
- "3.7-dev"
- "pypy"
- "pypy3"
env:
- RL=30
- RL=31
- RL=32
- RL=33
matrix:
fast_finish: true
allow_failures:
- python: "3.7-dev"
- python: "pypy"
- python: "pypy3"
install:
- TOX_ENV=py${TRAVIS_PYTHON_VERSION}-rl${RL}
- pip install tox coveralls Sphinx sphinx-rtd-theme
script: tox -e $TOX_ENV
after_success: coveralls $COVERALLS_OPTION
notifications:
irc: "chat.freenode.net#xhtml2pdf"
before_script:
- cd doc/source ; sphinx-build -nW -b html -d _build/doctrees . _build/html ; cd ../..
| language: python
sudo: false
python:
- "2.7"
- "3.4"
- "3.5"
- "3.6"
- "3.7-dev"
- "pypy"
- "pypy3"
env:
- RL=30
- RL=31
- RL=32
- RL=33
matrix:
fast_finish: true
allow_failures:
- python: "3.7-dev"
- python: "pypy3"
install:
- TOX_ENV=py${TRAVIS_PYTHON_VERSION}-rl${RL}
- pip install tox coveralls Sphinx sphinx-rtd-theme
script: tox -e $TOX_ENV
after_success: coveralls $COVERALLS_OPTION
notifications:
irc: "chat.freenode.net#xhtml2pdf"
before_script:
- cd doc/source ; sphinx-build -nW -b html -d _build/doctrees . _build/html ; cd ../..
| Remove PyPy from allowed failures list, tests pass | Remove PyPy from allowed failures list, tests pass
| YAML | apache-2.0 | chrisglass/xhtml2pdf,chrisglass/xhtml2pdf,xhtml2pdf/xhtml2pdf,xhtml2pdf/xhtml2pdf | yaml | ## Code Before:
language: python
sudo: false
python:
- "2.7"
- "3.4"
- "3.5"
- "3.6"
- "3.7-dev"
- "pypy"
- "pypy3"
env:
- RL=30
- RL=31
- RL=32
- RL=33
matrix:
fast_finish: true
allow_failures:
- python: "3.7-dev"
- python: "pypy"
- python: "pypy3"
install:
- TOX_ENV=py${TRAVIS_PYTHON_VERSION}-rl${RL}
- pip install tox coveralls Sphinx sphinx-rtd-theme
script: tox -e $TOX_ENV
after_success: coveralls $COVERALLS_OPTION
notifications:
irc: "chat.freenode.net#xhtml2pdf"
before_script:
- cd doc/source ; sphinx-build -nW -b html -d _build/doctrees . _build/html ; cd ../..
## Instruction:
Remove PyPy from allowed failures list, tests pass
## Code After:
language: python
sudo: false
python:
- "2.7"
- "3.4"
- "3.5"
- "3.6"
- "3.7-dev"
- "pypy"
- "pypy3"
env:
- RL=30
- RL=31
- RL=32
- RL=33
matrix:
fast_finish: true
allow_failures:
- python: "3.7-dev"
- python: "pypy3"
install:
- TOX_ENV=py${TRAVIS_PYTHON_VERSION}-rl${RL}
- pip install tox coveralls Sphinx sphinx-rtd-theme
script: tox -e $TOX_ENV
after_success: coveralls $COVERALLS_OPTION
notifications:
irc: "chat.freenode.net#xhtml2pdf"
before_script:
- cd doc/source ; sphinx-build -nW -b html -d _build/doctrees . _build/html ; cd ../..
| language: python
sudo: false
python:
- "2.7"
- "3.4"
- "3.5"
- "3.6"
- "3.7-dev"
- "pypy"
- "pypy3"
env:
- RL=30
- RL=31
- RL=32
- RL=33
matrix:
fast_finish: true
allow_failures:
- python: "3.7-dev"
- - python: "pypy"
- python: "pypy3"
install:
- TOX_ENV=py${TRAVIS_PYTHON_VERSION}-rl${RL}
- pip install tox coveralls Sphinx sphinx-rtd-theme
script: tox -e $TOX_ENV
after_success: coveralls $COVERALLS_OPTION
notifications:
irc: "chat.freenode.net#xhtml2pdf"
before_script:
- cd doc/source ; sphinx-build -nW -b html -d _build/doctrees . _build/html ; cd ../.. | 1 | 0.027778 | 0 | 1 |
d14c7ae2ac3b614203a77ad5d4ae9c98eb27690c | .gitlab-ci.yml | .gitlab-ci.yml | variables:
DEBIAN_FRONTEND: noninteractive
before_script:
# -
# echo "deb http://httpredir.debian.org/debian/ jessie main contrib" >
# /etc/apt/sources.list
- cat /etc/apt/sources.list
- apt-get update -y -qq
-
apt-get install -y -qq doxygen cmake libnss3-dev libev-dev
vagrant daemon tcpdump tshark tmux
# virtualbox
compile:
stage: build
script:
# disabled until warpcore is available
- true
# - cmake .
# - make
# - make doc
# run:
# stage: test
# script:
# - make test-quickie-client
# - make test-quickie-server
| variables:
DEBIAN_FRONTEND: noninteractive
before_script:
# -
# echo "deb http://httpredir.debian.org/debian/ jessie main contrib" >
# /etc/apt/sources.list
- cat /etc/apt/sources.list
- apt-get update -y -qq
-
apt-get install -y -qq doxygen cmake libnss3-dev libev-dev
vagrant daemon tcpdump tshark tmux
# virtualbox
compile:
stage: build
script:
- true
- cmake .
# - make
# - make doc
# run:
# stage: test
# script:
# - make test-quickie-client
# - make test-quickie-server
| Fix yaml again; CI still disabled | Fix yaml again; CI still disabled
| YAML | bsd-2-clause | NTAP/quant,NTAP/quant,NTAP/quant | yaml | ## Code Before:
variables:
DEBIAN_FRONTEND: noninteractive
before_script:
# -
# echo "deb http://httpredir.debian.org/debian/ jessie main contrib" >
# /etc/apt/sources.list
- cat /etc/apt/sources.list
- apt-get update -y -qq
-
apt-get install -y -qq doxygen cmake libnss3-dev libev-dev
vagrant daemon tcpdump tshark tmux
# virtualbox
compile:
stage: build
script:
# disabled until warpcore is available
- true
# - cmake .
# - make
# - make doc
# run:
# stage: test
# script:
# - make test-quickie-client
# - make test-quickie-server
## Instruction:
Fix yaml again; CI still disabled
## Code After:
variables:
DEBIAN_FRONTEND: noninteractive
before_script:
# -
# echo "deb http://httpredir.debian.org/debian/ jessie main contrib" >
# /etc/apt/sources.list
- cat /etc/apt/sources.list
- apt-get update -y -qq
-
apt-get install -y -qq doxygen cmake libnss3-dev libev-dev
vagrant daemon tcpdump tshark tmux
# virtualbox
compile:
stage: build
script:
- true
- cmake .
# - make
# - make doc
# run:
# stage: test
# script:
# - make test-quickie-client
# - make test-quickie-server
| variables:
DEBIAN_FRONTEND: noninteractive
before_script:
# -
# echo "deb http://httpredir.debian.org/debian/ jessie main contrib" >
# /etc/apt/sources.list
- cat /etc/apt/sources.list
- apt-get update -y -qq
-
apt-get install -y -qq doxygen cmake libnss3-dev libev-dev
vagrant daemon tcpdump tshark tmux
# virtualbox
compile:
stage: build
script:
- # disabled until warpcore is available
- true
- # - cmake .
? --
+ - cmake .
# - make
# - make doc
# run:
# stage: test
# script:
# - make test-quickie-client
# - make test-quickie-server | 3 | 0.107143 | 1 | 2 |
2aae7b1718bfc21267922f7fe09dcf47be69582b | blueprints/aws_rds_instance/delete_aws_rds_instance.py | blueprints/aws_rds_instance/delete_aws_rds_instance.py | import json
import boto3
from infrastructure.models import Environment
def run(job, logger=None, **kwargs):
service = job.service_set.first()
env_id = service.attributes.get(field__name__startswith='aws_environment').value
env = Environment.objects.get(id=env_id)
rh = env.resource_handler.cast()
job.set_progress('Connecting to AWS...')
client = boto3.client(
'rds',
region_name=env.aws_region,
aws_access_key_id=rh.serviceaccount,
aws_secret_access_key=rh.servicepasswd)
instance_cfv = service.attributes.get(field__name='rds_instance')
instance = json.loads(instance_cfv.value)
identifier = instance['identifier']
job.set_progress('Deleting RDS instance {}...'.format(identifier))
response = client.delete_db_instance(
DBInstanceIdentifier=identifier,
# AWS strongly recommends taking a final snapshot before deleting a DB.
# To do so, either set this to False or let the user choose by making it
# a runtime action input (in that case be sure to set the param type to
# Boolean so users get a dropdown).
SkipFinalSnapshot=True,
)
job.set_progress('RDS instance {0} deleted.'.format(identifier))
return 'SUCCESS', '', ''
| import json
import boto3
from infrastructure.models import Environment
def run(job, logger=None, **kwargs):
service = job.service_set.first()
# The Environment ID and RDS Instance data dict were stored as attributes on
# this service by a build action.
env_id_cfv = service.attributes.get(field__name__startswith='aws_environment')
instance_cfv = service.attributes.get(field__name='rds_instance')
env = Environment.objects.get(id=env_id_cfv.value)
client = connect_to_rds(env)
instance = json.loads(instance_cfv.value)
identifier = instance['identifier']
job.set_progress('Deleting RDS instance {0}...'.format(identifier))
response = client.delete_db_instance(
DBInstanceIdentifier=identifier,
# AWS strongly recommends taking a final snapshot before deleting a DB.
# To do so, either set this to False or let the user choose by making it
# a runtime action input (in that case be sure to set the param type to
# Boolean so users get a dropdown).
SkipFinalSnapshot=True,
)
job.set_progress('RDS instance {0} deleted.'.format(identifier))
return 'SUCCESS', '', ''
def connect_to_rds(env):
"""
Return boto connection to the RDS in the specified environment's region.
"""
job.set_progress('Connecting to AWS RDS in region {0}.'.format(env.aws_region))
rh = env.resource_handler.cast()
return boto3.client(
'rds',
region_name=env.aws_region,
aws_access_key_id=rh.serviceaccount,
aws_secret_access_key=rh.servicepasswd)
| Use code consistent with other RDS actions | Use code consistent with other RDS actions
[#144244831]
| Python | apache-2.0 | CloudBoltSoftware/cloudbolt-forge,CloudBoltSoftware/cloudbolt-forge,CloudBoltSoftware/cloudbolt-forge,CloudBoltSoftware/cloudbolt-forge | python | ## Code Before:
import json
import boto3
from infrastructure.models import Environment
def run(job, logger=None, **kwargs):
service = job.service_set.first()
env_id = service.attributes.get(field__name__startswith='aws_environment').value
env = Environment.objects.get(id=env_id)
rh = env.resource_handler.cast()
job.set_progress('Connecting to AWS...')
client = boto3.client(
'rds',
region_name=env.aws_region,
aws_access_key_id=rh.serviceaccount,
aws_secret_access_key=rh.servicepasswd)
instance_cfv = service.attributes.get(field__name='rds_instance')
instance = json.loads(instance_cfv.value)
identifier = instance['identifier']
job.set_progress('Deleting RDS instance {}...'.format(identifier))
response = client.delete_db_instance(
DBInstanceIdentifier=identifier,
# AWS strongly recommends taking a final snapshot before deleting a DB.
# To do so, either set this to False or let the user choose by making it
# a runtime action input (in that case be sure to set the param type to
# Boolean so users get a dropdown).
SkipFinalSnapshot=True,
)
job.set_progress('RDS instance {0} deleted.'.format(identifier))
return 'SUCCESS', '', ''
## Instruction:
Use code consistent with other RDS actions
[#144244831]
## Code After:
import json
import boto3
from infrastructure.models import Environment
def run(job, logger=None, **kwargs):
service = job.service_set.first()
# The Environment ID and RDS Instance data dict were stored as attributes on
# this service by a build action.
env_id_cfv = service.attributes.get(field__name__startswith='aws_environment')
instance_cfv = service.attributes.get(field__name='rds_instance')
env = Environment.objects.get(id=env_id_cfv.value)
client = connect_to_rds(env)
instance = json.loads(instance_cfv.value)
identifier = instance['identifier']
job.set_progress('Deleting RDS instance {0}...'.format(identifier))
response = client.delete_db_instance(
DBInstanceIdentifier=identifier,
# AWS strongly recommends taking a final snapshot before deleting a DB.
# To do so, either set this to False or let the user choose by making it
# a runtime action input (in that case be sure to set the param type to
# Boolean so users get a dropdown).
SkipFinalSnapshot=True,
)
job.set_progress('RDS instance {0} deleted.'.format(identifier))
return 'SUCCESS', '', ''
def connect_to_rds(env):
"""
Return boto connection to the RDS in the specified environment's region.
"""
job.set_progress('Connecting to AWS RDS in region {0}.'.format(env.aws_region))
rh = env.resource_handler.cast()
return boto3.client(
'rds',
region_name=env.aws_region,
aws_access_key_id=rh.serviceaccount,
aws_secret_access_key=rh.servicepasswd)
| import json
import boto3
from infrastructure.models import Environment
def run(job, logger=None, **kwargs):
service = job.service_set.first()
- env_id = service.attributes.get(field__name__startswith='aws_environment').value
- env = Environment.objects.get(id=env_id)
- rh = env.resource_handler.cast()
+ # The Environment ID and RDS Instance data dict were stored as attributes on
+ # this service by a build action.
+ env_id_cfv = service.attributes.get(field__name__startswith='aws_environment')
+ instance_cfv = service.attributes.get(field__name='rds_instance')
- job.set_progress('Connecting to AWS...')
- client = boto3.client(
- 'rds',
- region_name=env.aws_region,
- aws_access_key_id=rh.serviceaccount,
- aws_secret_access_key=rh.servicepasswd)
- instance_cfv = service.attributes.get(field__name='rds_instance')
+ env = Environment.objects.get(id=env_id_cfv.value)
+ client = connect_to_rds(env)
+
instance = json.loads(instance_cfv.value)
identifier = instance['identifier']
- job.set_progress('Deleting RDS instance {}...'.format(identifier))
+ job.set_progress('Deleting RDS instance {0}...'.format(identifier))
? +
response = client.delete_db_instance(
DBInstanceIdentifier=identifier,
# AWS strongly recommends taking a final snapshot before deleting a DB.
# To do so, either set this to False or let the user choose by making it
# a runtime action input (in that case be sure to set the param type to
# Boolean so users get a dropdown).
SkipFinalSnapshot=True,
)
job.set_progress('RDS instance {0} deleted.'.format(identifier))
return 'SUCCESS', '', ''
+
+
+ def connect_to_rds(env):
+ """
+ Return boto connection to the RDS in the specified environment's region.
+ """
+ job.set_progress('Connecting to AWS RDS in region {0}.'.format(env.aws_region))
+ rh = env.resource_handler.cast()
+ return boto3.client(
+ 'rds',
+ region_name=env.aws_region,
+ aws_access_key_id=rh.serviceaccount,
+ aws_secret_access_key=rh.servicepasswd) | 32 | 0.914286 | 21 | 11 |
8898f23a429112cd80e6a2c8321b0de44aeaee7e | blanc_basic_pages/forms.py | blanc_basic_pages/forms.py | from django import forms
from django.conf import settings
from mptt.forms import MPTTAdminForm
from .models import Page
TEMPLATE_CHOICES = getattr(settings, 'PAGE_TEMPLATES', (
('', 'Default'),
))
class PageAdminForm(MPTTAdminForm):
class Meta:
model = Page
exclude = ()
def __init__(self, *args, **kwargs):
super(PageAdminForm, self).__init__(*args, **kwargs)
# The list of templates is defined in settings, however as we can't have dynamic choices in
# models due to migrations - we change the form choices instead.
self.fields['template_name'] = forms.ChoiceField(choices=TEMPLATE_CHOICES, required=False)
| from django import forms
from django.conf import settings
from mptt.forms import MPTTAdminForm
from .models import Page
TEMPLATE_CHOICES = getattr(settings, 'PAGE_TEMPLATES', (
('', 'Default'),
))
class PageAdminForm(MPTTAdminForm):
class Meta:
model = Page
exclude = ()
widgets = {
# The list of templates is defined in settings, however as we can't have dynamic
# choices in models due to migrations - we change the form choices instead.
'template_name': forms.widgets.Select(choices=TEMPLATE_CHOICES),
}
| Use custom widget for template choices instead | Use custom widget for template choices instead
A bit more Djangonic than tweaking self.fields
| Python | bsd-3-clause | blancltd/blanc-basic-pages | python | ## Code Before:
from django import forms
from django.conf import settings
from mptt.forms import MPTTAdminForm
from .models import Page
TEMPLATE_CHOICES = getattr(settings, 'PAGE_TEMPLATES', (
('', 'Default'),
))
class PageAdminForm(MPTTAdminForm):
class Meta:
model = Page
exclude = ()
def __init__(self, *args, **kwargs):
super(PageAdminForm, self).__init__(*args, **kwargs)
# The list of templates is defined in settings, however as we can't have dynamic choices in
# models due to migrations - we change the form choices instead.
self.fields['template_name'] = forms.ChoiceField(choices=TEMPLATE_CHOICES, required=False)
## Instruction:
Use custom widget for template choices instead
A bit more Djangonic than tweaking self.fields
## Code After:
from django import forms
from django.conf import settings
from mptt.forms import MPTTAdminForm
from .models import Page
TEMPLATE_CHOICES = getattr(settings, 'PAGE_TEMPLATES', (
('', 'Default'),
))
class PageAdminForm(MPTTAdminForm):
class Meta:
model = Page
exclude = ()
widgets = {
# The list of templates is defined in settings, however as we can't have dynamic
# choices in models due to migrations - we change the form choices instead.
'template_name': forms.widgets.Select(choices=TEMPLATE_CHOICES),
}
| from django import forms
from django.conf import settings
from mptt.forms import MPTTAdminForm
from .models import Page
TEMPLATE_CHOICES = getattr(settings, 'PAGE_TEMPLATES', (
('', 'Default'),
))
class PageAdminForm(MPTTAdminForm):
class Meta:
model = Page
exclude = ()
+ widgets = {
-
- def __init__(self, *args, **kwargs):
- super(PageAdminForm, self).__init__(*args, **kwargs)
-
- # The list of templates is defined in settings, however as we can't have dynamic choices in
? -----------
+ # The list of templates is defined in settings, however as we can't have dynamic
? ++++
- # models due to migrations - we change the form choices instead.
+ # choices in models due to migrations - we change the form choices instead.
? ++++ +++++++++++
- self.fields['template_name'] = forms.ChoiceField(choices=TEMPLATE_CHOICES, required=False)
+ 'template_name': forms.widgets.Select(choices=TEMPLATE_CHOICES),
+ } | 12 | 0.5 | 5 | 7 |
96fa2360cc4c584577ced0300e0d9915e7c5a18f | app/models/lab_group.rb | app/models/lab_group.rb | class LabGroup < ActiveRecord::Base
has_and_belongs_to_many :registered_courses
has_many :labs, through: :lab_has_group
has_many :submissions, through: :lab_has_group
end
| class LabGroup < ActiveRecord::Base
has_and_belongs_to_many :registered_courses
has_many :labs, through: :lab_has_group
has_many :submissions, through: :lab_has_group
accepts_nested_attributes_for :lab_has_groups
end
| Add nested attributes for labhasgroups | Add nested attributes for labhasgroups
| Ruby | agpl-3.0 | water/mainline,water/mainline,water/mainline | ruby | ## Code Before:
class LabGroup < ActiveRecord::Base
has_and_belongs_to_many :registered_courses
has_many :labs, through: :lab_has_group
has_many :submissions, through: :lab_has_group
end
## Instruction:
Add nested attributes for labhasgroups
## Code After:
class LabGroup < ActiveRecord::Base
has_and_belongs_to_many :registered_courses
has_many :labs, through: :lab_has_group
has_many :submissions, through: :lab_has_group
accepts_nested_attributes_for :lab_has_groups
end
| class LabGroup < ActiveRecord::Base
has_and_belongs_to_many :registered_courses
has_many :labs, through: :lab_has_group
has_many :submissions, through: :lab_has_group
+ accepts_nested_attributes_for :lab_has_groups
end | 1 | 0.2 | 1 | 0 |
2e92c020312d6ff50a92c5b684c6bc5a0576ed97 | vertical-scroll-mouse-move.js | vertical-scroll-mouse-move.js | $(function(){
var $container = $("#container"),
$blocks = $("#blocks"),
heightContainer = $container.outerHeight(),
scrolledHeight = $container[0].scrollHeight,
mousePos = 0,
posY = 0,
hDiff = ( scrolledHeight / heightContainer ) - 1
$container.mousemove(function(e){
mousePos = e.pageY - this.offsetTop;
});
setInterval(function(){
$blocks.css({marginTop: - mousePos*hDiff });
}, 10);
});
| (function($){
var $container = $("#container"),
$blocks = $("#blocks"),
heightContainer = $container.outerHeight(),
scrolledHeight = $container[0].scrollHeight,
mousePos = 0,
posY = 0,
hDiff = ( scrolledHeight / heightContainer ) - 1
$container.mousemove(function(e){
mousePos = e.pageY - this.offsetTop;
});
setInterval(function(){
$blocks.css({marginTop: - mousePos*hDiff });
}, 10);
})(jQuery);
| Enable usage of $ sign | Enable usage of $ sign | JavaScript | mit | ristaa/vertical-scroll-on-mouse-move,ristaa/vertical-scroll-on-mouse-move | javascript | ## Code Before:
$(function(){
var $container = $("#container"),
$blocks = $("#blocks"),
heightContainer = $container.outerHeight(),
scrolledHeight = $container[0].scrollHeight,
mousePos = 0,
posY = 0,
hDiff = ( scrolledHeight / heightContainer ) - 1
$container.mousemove(function(e){
mousePos = e.pageY - this.offsetTop;
});
setInterval(function(){
$blocks.css({marginTop: - mousePos*hDiff });
}, 10);
});
## Instruction:
Enable usage of $ sign
## Code After:
(function($){
var $container = $("#container"),
$blocks = $("#blocks"),
heightContainer = $container.outerHeight(),
scrolledHeight = $container[0].scrollHeight,
mousePos = 0,
posY = 0,
hDiff = ( scrolledHeight / heightContainer ) - 1
$container.mousemove(function(e){
mousePos = e.pageY - this.offsetTop;
});
setInterval(function(){
$blocks.css({marginTop: - mousePos*hDiff });
}, 10);
})(jQuery);
| - $(function(){
? -
+ (function($){
? +
var $container = $("#container"),
$blocks = $("#blocks"),
heightContainer = $container.outerHeight(),
scrolledHeight = $container[0].scrollHeight,
mousePos = 0,
posY = 0,
hDiff = ( scrolledHeight / heightContainer ) - 1
$container.mousemove(function(e){
mousePos = e.pageY - this.offsetTop;
});
setInterval(function(){
$blocks.css({marginTop: - mousePos*hDiff });
}, 10);
- });
+ })(jQuery); | 4 | 0.222222 | 2 | 2 |
713891595a7d9d57e0952fc233bda1e9b78dabf9 | static/css/nerfherder.css | static/css/nerfherder.css | .navbar, .navbar.navbar-default
{
background-color: #990000;
}
.navbar-inverse
{
background-color: black;
}
#logo
{
width: 280px;
position: absolute;
bottom: 1em;
right: 0;
}
table.calendar
{
border-spacing: .5em;
margin-left: auto;
margin-right: auto;
}
table.calendar td {
vertical-align: middle;
}
table.calendar td.time {
text-align: right;
}
table.calendar td.track1 {
background-color: rgba(0, 51, 102, .1);
}
table.calendar td.track2 {
background-color: rgba(0, 102, 51, .1);
}
table.calendar td:not(:empty) {
padding: .75em;
width: 9em;
}
table.calendar td:not(:empty):not(.time):not(.track1):not(.track2) {
background: rgba(102, 102, 102, .05);
}
table.calendar th {
padding-top: .75em;
padding-left: .5em;
position: relative;
}
table.calendar th .date {
font-size: 80%;
position: absolute;
top: 1em;
right: 1em;
}
| .navbar, .navbar.navbar-default
{
background-color: #990000;
}
.navbar-inverse
{
background-color: black;
}
ul.nav.navbar-nav li.dropdown ul li a:hover
{
color: #990000;
}
#logo
{
width: 280px;
position: absolute;
bottom: 1em;
right: 0;
}
table.calendar
{
border-spacing: .5em;
margin-left: auto;
margin-right: auto;
}
table.calendar td {
vertical-align: middle;
}
table.calendar td.time {
text-align: right;
}
table.calendar td.track1 {
background-color: rgba(0, 51, 102, .1);
}
table.calendar td.track2 {
background-color: rgba(0, 102, 51, .1);
}
table.calendar td:not(:empty) {
padding: .75em;
width: 9em;
}
table.calendar td:not(:empty):not(.time):not(.track1):not(.track2) {
background: rgba(102, 102, 102, .05);
}
table.calendar th {
padding-top: .75em;
padding-left: .5em;
position: relative;
}
table.calendar th .date {
font-size: 80%;
position: absolute;
top: 1em;
right: 1em;
}
| Add styling to nav dropdowns. | Add styling to nav dropdowns. | CSS | bsd-2-clause | trombonehero/nerf-herder,trombonehero/nerf-herder,trombonehero/nerf-herder | css | ## Code Before:
.navbar, .navbar.navbar-default
{
background-color: #990000;
}
.navbar-inverse
{
background-color: black;
}
#logo
{
width: 280px;
position: absolute;
bottom: 1em;
right: 0;
}
table.calendar
{
border-spacing: .5em;
margin-left: auto;
margin-right: auto;
}
table.calendar td {
vertical-align: middle;
}
table.calendar td.time {
text-align: right;
}
table.calendar td.track1 {
background-color: rgba(0, 51, 102, .1);
}
table.calendar td.track2 {
background-color: rgba(0, 102, 51, .1);
}
table.calendar td:not(:empty) {
padding: .75em;
width: 9em;
}
table.calendar td:not(:empty):not(.time):not(.track1):not(.track2) {
background: rgba(102, 102, 102, .05);
}
table.calendar th {
padding-top: .75em;
padding-left: .5em;
position: relative;
}
table.calendar th .date {
font-size: 80%;
position: absolute;
top: 1em;
right: 1em;
}
## Instruction:
Add styling to nav dropdowns.
## Code After:
.navbar, .navbar.navbar-default
{
background-color: #990000;
}
.navbar-inverse
{
background-color: black;
}
ul.nav.navbar-nav li.dropdown ul li a:hover
{
color: #990000;
}
#logo
{
width: 280px;
position: absolute;
bottom: 1em;
right: 0;
}
table.calendar
{
border-spacing: .5em;
margin-left: auto;
margin-right: auto;
}
table.calendar td {
vertical-align: middle;
}
table.calendar td.time {
text-align: right;
}
table.calendar td.track1 {
background-color: rgba(0, 51, 102, .1);
}
table.calendar td.track2 {
background-color: rgba(0, 102, 51, .1);
}
table.calendar td:not(:empty) {
padding: .75em;
width: 9em;
}
table.calendar td:not(:empty):not(.time):not(.track1):not(.track2) {
background: rgba(102, 102, 102, .05);
}
table.calendar th {
padding-top: .75em;
padding-left: .5em;
position: relative;
}
table.calendar th .date {
font-size: 80%;
position: absolute;
top: 1em;
right: 1em;
}
| .navbar, .navbar.navbar-default
{
background-color: #990000;
}
.navbar-inverse
{
background-color: black;
+ }
+
+ ul.nav.navbar-nav li.dropdown ul li a:hover
+ {
+ color: #990000;
}
#logo
{
width: 280px;
position: absolute;
bottom: 1em;
right: 0;
}
table.calendar
{
border-spacing: .5em;
margin-left: auto;
margin-right: auto;
}
table.calendar td {
vertical-align: middle;
}
table.calendar td.time {
text-align: right;
}
table.calendar td.track1 {
background-color: rgba(0, 51, 102, .1);
}
table.calendar td.track2 {
background-color: rgba(0, 102, 51, .1);
}
table.calendar td:not(:empty) {
padding: .75em;
width: 9em;
}
table.calendar td:not(:empty):not(.time):not(.track1):not(.track2) {
background: rgba(102, 102, 102, .05);
}
table.calendar th {
padding-top: .75em;
padding-left: .5em;
position: relative;
}
table.calendar th .date {
font-size: 80%;
position: absolute;
top: 1em;
right: 1em;
} | 5 | 0.079365 | 5 | 0 |
43ec204f13765ecd6865aa30e1da8a245d2f59a1 | .travis.yml | .travis.yml |
language: objective-c
osx_image: xcode9.1
jobs:
include:
- stage: test on Xcode 9.1, Swift 4.0.2
osx_image: xcode9.1
script: swift test
- stage: test on Xcode 9, Swift 4.0
osx_image: xcode9
script: swift test
- stage: test on Xcode 8.3, Swift 3.1
osx_image: xcode8.3
script: swift test
- stage: test on Xcode 8, Swift 3
osx_image: xcode8
script: swift test
|
language: objective-c
osx_image: xcode9.1
matrix:
fast_finish: true
allow_failures:
- osx_image: xcode8
jobs:
include:
- stage: test on Xcode 9.1, Swift 4.0.2
osx_image: xcode9.1
script: swift test
- stage: test on Xcode 9, Swift 4.0
osx_image: xcode9
script: swift test
- stage: test on Xcode 8.3, Swift 3.1
osx_image: xcode8.3
script: swift test
- stage: test on Xcode 8, Swift 3
osx_image: xcode8
script: swift test
| Allow tests to fail on xcode8 | Also allow build to finish as soon as others pass | Allow tests to fail on xcode8 | Also allow build to finish as soon as others pass
| YAML | mit | NicholasTD07/spec.swift,NicholasTD07/spec.swift | yaml | ## Code Before:
language: objective-c
osx_image: xcode9.1
jobs:
include:
- stage: test on Xcode 9.1, Swift 4.0.2
osx_image: xcode9.1
script: swift test
- stage: test on Xcode 9, Swift 4.0
osx_image: xcode9
script: swift test
- stage: test on Xcode 8.3, Swift 3.1
osx_image: xcode8.3
script: swift test
- stage: test on Xcode 8, Swift 3
osx_image: xcode8
script: swift test
## Instruction:
Allow tests to fail on xcode8 | Also allow build to finish as soon as others pass
## Code After:
language: objective-c
osx_image: xcode9.1
matrix:
fast_finish: true
allow_failures:
- osx_image: xcode8
jobs:
include:
- stage: test on Xcode 9.1, Swift 4.0.2
osx_image: xcode9.1
script: swift test
- stage: test on Xcode 9, Swift 4.0
osx_image: xcode9
script: swift test
- stage: test on Xcode 8.3, Swift 3.1
osx_image: xcode8.3
script: swift test
- stage: test on Xcode 8, Swift 3
osx_image: xcode8
script: swift test
|
language: objective-c
osx_image: xcode9.1
+
+ matrix:
+ fast_finish: true
+ allow_failures:
+ - osx_image: xcode8
+
jobs:
include:
- stage: test on Xcode 9.1, Swift 4.0.2
osx_image: xcode9.1
script: swift test
- stage: test on Xcode 9, Swift 4.0
osx_image: xcode9
script: swift test
- stage: test on Xcode 8.3, Swift 3.1
osx_image: xcode8.3
script: swift test
- stage: test on Xcode 8, Swift 3
osx_image: xcode8
script: swift test | 6 | 0.333333 | 6 | 0 |
083c74399f6c260d1738272c60b282d83b2a0b44 | document/documentConversion.js | document/documentConversion.js | import DocumentConfigurator from './DocumentConfigurator'
import DocumentModel from './DocumentModel'
import DocumentJSONConverter from './DocumentJSONConverter'
import DocumentHTMLImporter from './DocumentHTMLImporter'
import DocumentHTMLExporter from './DocumentHTMLExporter'
function importJSON (content) {
let doc = new DocumentModel()
let jsonConverter = new DocumentJSONConverter()
jsonConverter.importDocument(doc, content)
return doc
}
function exportJSON (doc) {
let jsonConverter = new DocumentJSONConverter()
return jsonConverter.exportDocument(doc)
}
function importHTML (content) {
let htmlImporter = new DocumentHTMLImporter({
configurator: new DocumentConfigurator()
})
return htmlImporter.importDocument(content)
}
function exportHTML (doc) {
let htmlExporter = new DocumentHTMLExporter({
configurator: new DocumentConfigurator()
})
return htmlExporter.exportDocument(doc)
}
export {
importJSON,
exportJSON,
importHTML,
exportHTML
}
| import DocumentConfigurator from './DocumentConfigurator'
import DocumentModel from './DocumentModel'
import DocumentJSONConverter from './DocumentJSONConverter'
import DocumentHTMLImporter from './DocumentHTMLImporter'
import DocumentHTMLExporter from './DocumentHTMLExporter'
function importJSON (content) {
let doc = new DocumentModel()
let jsonConverter = new DocumentJSONConverter()
jsonConverter.importDocument(doc, content)
return doc
}
function exportJSON (doc) {
let jsonConverter = new DocumentJSONConverter()
return jsonConverter.exportDocument(doc)
}
function importHTML (content) {
let htmlImporter = new DocumentHTMLImporter({
configurator: new DocumentConfigurator()
})
return htmlImporter.importDocument(content)
}
function exportHTML (doc) {
let htmlExporter = new DocumentHTMLExporter({
configurator: new DocumentConfigurator()
})
let html = htmlExporter.exportDocument(doc)
html = html.replace(/ data-id=".+?"/g, '')
return html
}
export {
importJSON,
exportJSON,
importHTML,
exportHTML
}
| Remove the data-id attribute on HTML export | Remove the data-id attribute on HTML export
| JavaScript | apache-2.0 | stencila/stencila,stencila/stencila,stencila/stencila,stencila/stencila,stencila/stencila,stencila/stencila,stencila/stencila | javascript | ## Code Before:
import DocumentConfigurator from './DocumentConfigurator'
import DocumentModel from './DocumentModel'
import DocumentJSONConverter from './DocumentJSONConverter'
import DocumentHTMLImporter from './DocumentHTMLImporter'
import DocumentHTMLExporter from './DocumentHTMLExporter'
function importJSON (content) {
let doc = new DocumentModel()
let jsonConverter = new DocumentJSONConverter()
jsonConverter.importDocument(doc, content)
return doc
}
function exportJSON (doc) {
let jsonConverter = new DocumentJSONConverter()
return jsonConverter.exportDocument(doc)
}
function importHTML (content) {
let htmlImporter = new DocumentHTMLImporter({
configurator: new DocumentConfigurator()
})
return htmlImporter.importDocument(content)
}
function exportHTML (doc) {
let htmlExporter = new DocumentHTMLExporter({
configurator: new DocumentConfigurator()
})
return htmlExporter.exportDocument(doc)
}
export {
importJSON,
exportJSON,
importHTML,
exportHTML
}
## Instruction:
Remove the data-id attribute on HTML export
## Code After:
import DocumentConfigurator from './DocumentConfigurator'
import DocumentModel from './DocumentModel'
import DocumentJSONConverter from './DocumentJSONConverter'
import DocumentHTMLImporter from './DocumentHTMLImporter'
import DocumentHTMLExporter from './DocumentHTMLExporter'
function importJSON (content) {
let doc = new DocumentModel()
let jsonConverter = new DocumentJSONConverter()
jsonConverter.importDocument(doc, content)
return doc
}
function exportJSON (doc) {
let jsonConverter = new DocumentJSONConverter()
return jsonConverter.exportDocument(doc)
}
function importHTML (content) {
let htmlImporter = new DocumentHTMLImporter({
configurator: new DocumentConfigurator()
})
return htmlImporter.importDocument(content)
}
function exportHTML (doc) {
let htmlExporter = new DocumentHTMLExporter({
configurator: new DocumentConfigurator()
})
let html = htmlExporter.exportDocument(doc)
html = html.replace(/ data-id=".+?"/g, '')
return html
}
export {
importJSON,
exportJSON,
importHTML,
exportHTML
}
| import DocumentConfigurator from './DocumentConfigurator'
import DocumentModel from './DocumentModel'
import DocumentJSONConverter from './DocumentJSONConverter'
import DocumentHTMLImporter from './DocumentHTMLImporter'
import DocumentHTMLExporter from './DocumentHTMLExporter'
function importJSON (content) {
let doc = new DocumentModel()
let jsonConverter = new DocumentJSONConverter()
jsonConverter.importDocument(doc, content)
return doc
}
function exportJSON (doc) {
let jsonConverter = new DocumentJSONConverter()
return jsonConverter.exportDocument(doc)
}
function importHTML (content) {
let htmlImporter = new DocumentHTMLImporter({
configurator: new DocumentConfigurator()
})
return htmlImporter.importDocument(content)
}
function exportHTML (doc) {
let htmlExporter = new DocumentHTMLExporter({
configurator: new DocumentConfigurator()
})
- return htmlExporter.exportDocument(doc)
? ^ ^^^
+ let html = htmlExporter.exportDocument(doc)
? ^ ^^^^^^^
+ html = html.replace(/ data-id=".+?"/g, '')
+ return html
}
export {
importJSON,
exportJSON,
importHTML,
exportHTML
} | 4 | 0.105263 | 3 | 1 |
4bcf3ee9e8c377ed227bee2430adca8bb1c5f510 | app/views/courses/show.html.erb | app/views/courses/show.html.erb |
<% if @reserves %>
<h3>Number of reserves: <%= @reserves.count %></h3>
<%= form_tag({controller: "courses", action: "delete"}, method: "post", class: "reserves-list") do %>
<%= hidden_field_tag("id", params[:id]) %>
<ul class="list-with-floats">
<li class="head"><%= check_box_tag("select_all") %>
<%= label_tag("select_all", "Select all reserves") %> <span class="delete " title="Remove selected reserve(s)"><%=submit_tag(value="Remove selected reserve(s)", {:class => "btn btn-submit chks_submit", :id => "delete_btn", :disabled => "disabled"}) %></span> <span class="float-right"><a href="<%= new_reserve_path %>" class="link-icon"><%= icon('plus-circle') %> Add new Reserve</a></span>
</li>
</ul>
<ul class="list-with-floats chk_grp">
<% @reserves.each do |reserve| %>
<li><%= render partial: 'reserves/simple_reserve', locals: {reserve: reserve} %></li>
<% end %>
</ul>
<% end %>
<script>checkBoxSetup()</script>
<% end %>
|
<% if @reserves %>
<h3>Number of reserves: <%= @reserves.count %></h3>
<%= form_tag({controller: "courses", action: "delete"}, method: "post", class: "reserves-list") do %>
<%= hidden_field_tag("id", params[:id]) %>
<ul class="list-with-floats">
<li class="head"><%= check_box_tag("select_all") %>
<%= label_tag("select_all", "Select all reserves") %> <span class="delete " title="Remove selected reserve(s)"><%=submit_tag(value="Remove selected reserve(s)", {:class => "btn btn-submit chks_submit", :id => "delete_btn", :disabled => "disabled"}) %></span>
<span class="float-right"><a href="<%= new_reserve_path %>" class="link-icon" title="Add New Reserve"><%= icon('plus-circle') %> Add New Reserve</a></span>
</li>
</ul>
<ul class="list-with-floats chk_grp">
<% @reserves.each do |reserve| %>
<li><%= render partial: 'reserves/simple_reserve', locals: {reserve: reserve} %></li>
<% end %>
</ul>
<% end %>
<script>checkBoxSetup()</script>
<% end %>
| Add title to Add New Reserve | Add title to Add New Reserve
| HTML+ERB | mit | harvard-library/lts-lti-reserves,harvard-library/lts-lti-reserves,harvard-library/lts-lti-reserves | html+erb | ## Code Before:
<% if @reserves %>
<h3>Number of reserves: <%= @reserves.count %></h3>
<%= form_tag({controller: "courses", action: "delete"}, method: "post", class: "reserves-list") do %>
<%= hidden_field_tag("id", params[:id]) %>
<ul class="list-with-floats">
<li class="head"><%= check_box_tag("select_all") %>
<%= label_tag("select_all", "Select all reserves") %> <span class="delete " title="Remove selected reserve(s)"><%=submit_tag(value="Remove selected reserve(s)", {:class => "btn btn-submit chks_submit", :id => "delete_btn", :disabled => "disabled"}) %></span> <span class="float-right"><a href="<%= new_reserve_path %>" class="link-icon"><%= icon('plus-circle') %> Add new Reserve</a></span>
</li>
</ul>
<ul class="list-with-floats chk_grp">
<% @reserves.each do |reserve| %>
<li><%= render partial: 'reserves/simple_reserve', locals: {reserve: reserve} %></li>
<% end %>
</ul>
<% end %>
<script>checkBoxSetup()</script>
<% end %>
## Instruction:
Add title to Add New Reserve
## Code After:
<% if @reserves %>
<h3>Number of reserves: <%= @reserves.count %></h3>
<%= form_tag({controller: "courses", action: "delete"}, method: "post", class: "reserves-list") do %>
<%= hidden_field_tag("id", params[:id]) %>
<ul class="list-with-floats">
<li class="head"><%= check_box_tag("select_all") %>
<%= label_tag("select_all", "Select all reserves") %> <span class="delete " title="Remove selected reserve(s)"><%=submit_tag(value="Remove selected reserve(s)", {:class => "btn btn-submit chks_submit", :id => "delete_btn", :disabled => "disabled"}) %></span>
<span class="float-right"><a href="<%= new_reserve_path %>" class="link-icon" title="Add New Reserve"><%= icon('plus-circle') %> Add New Reserve</a></span>
</li>
</ul>
<ul class="list-with-floats chk_grp">
<% @reserves.each do |reserve| %>
<li><%= render partial: 'reserves/simple_reserve', locals: {reserve: reserve} %></li>
<% end %>
</ul>
<% end %>
<script>checkBoxSetup()</script>
<% end %>
|
<% if @reserves %>
<h3>Number of reserves: <%= @reserves.count %></h3>
<%= form_tag({controller: "courses", action: "delete"}, method: "post", class: "reserves-list") do %>
<%= hidden_field_tag("id", params[:id]) %>
<ul class="list-with-floats">
<li class="head"><%= check_box_tag("select_all") %>
- <%= label_tag("select_all", "Select all reserves") %> <span class="delete " title="Remove selected reserve(s)"><%=submit_tag(value="Remove selected reserve(s)", {:class => "btn btn-submit chks_submit", :id => "delete_btn", :disabled => "disabled"}) %></span> <span class="float-right"><a href="<%= new_reserve_path %>" class="link-icon"><%= icon('plus-circle') %> Add new Reserve</a></span>
? ------------------------------------------------------------------------------------------------------------------------------------
+ <%= label_tag("select_all", "Select all reserves") %> <span class="delete " title="Remove selected reserve(s)"><%=submit_tag(value="Remove selected reserve(s)", {:class => "btn btn-submit chks_submit", :id => "delete_btn", :disabled => "disabled"}) %></span>
+ <span class="float-right"><a href="<%= new_reserve_path %>" class="link-icon" title="Add New Reserve"><%= icon('plus-circle') %> Add New Reserve</a></span>
</li>
</ul>
<ul class="list-with-floats chk_grp">
<% @reserves.each do |reserve| %>
<li><%= render partial: 'reserves/simple_reserve', locals: {reserve: reserve} %></li>
<% end %>
</ul>
<% end %>
<script>checkBoxSetup()</script>
<% end %> | 3 | 0.166667 | 2 | 1 |
aab661ef926460ee4ce2f80debb2622525007bde | app/assets/templates/articles/three.html.erb | app/assets/templates/articles/three.html.erb | <h2>Third Article</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Maiores velit, optio omnis voluptate sequi obcaecati cumque officia deleniti. Maxime nam obcaecati itaque maiores quisquam deleniti ut possimus perspiciatis ex, vitae.</p>
<ul>
<li>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Odit, ea.</li>
<li>Lorem ipsum dolor sit amet.</li>
<li>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Facilis.</li>
</ul> | <h2>Third Article</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Maiores velit, optio omnis voluptate sequi obcaecati cumque officia deleniti. Maxime nam obcaecati itaque maiores quisquam deleniti ut possimus perspiciatis ex, vitae.</p>
<ul>
<li>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Odit, ea.</li>
<li>Lorem ipsum dolor sit amet.</li>
<li>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Facilis.</li>
</ul>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Temporibus, ad explicabo eligendi quibusdam officia, suscipit recusandae blanditiis quisquam iure voluptate. Nulla ut beatae officiis nam, voluptate nesciunt cupiditate illo qui.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Temporibus, ad explicabo eligendi quibusdam officia, suscipit recusandae blanditiis quisquam iure voluptate. Nulla ut beatae officiis nam, voluptate nesciunt cupiditate illo qui.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laudantium placeat, dicta aliquid fugiat, obcaecati nisi illum repellat nesciunt reiciendis nihil est, qui alias, perspiciatis accusantium libero mollitia quas aspernatur totam animi. Dignissimos unde eaque quam modi, dolores provident quaerat dolorem explicabo veniam. Doloribus illo, nostrum, ratione perspiciatis ut repellendus, quasi sint inventore et facere consequatur debitis eveniet hic deserunt earum vitae nihil cumque dignissimos porro voluptatibus modi. Porro, aspernatur a illo consequatur, commodi ab. Sint ad quia, iusto sapiente omnis recusandae, optio distinctio repellat odio nemo, tenetur voluptas perferendis quisquam qui alias quidem praesentium earum facere expedita? Hic quis ducimus atque beatae voluptatum aut dignissimos enim, temporibus voluptatibus excepturi esse officia repellendus libero consectetur qui, doloribus autem ipsum veniam in odio non recusandae! Odit maiores laudantium accusamus libero eaque! Porro asperiores sed nostrum in? Aperiam eveniet nam voluptates, dolore maxime soluta ratione, delectus quod, nulla, illum officia maiores ab labore?</p> | Increase size of sample text in third article to test how it deals with displaying longer articles | Increase size of sample text in third article to test how it deals with displaying longer articles
| HTML+ERB | mit | jeremymcintyre/rails-angular-sandbox,jeremymcintyre/rails-angular-sandbox,jeremymcintyre/rails-angular-sandbox | html+erb | ## Code Before:
<h2>Third Article</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Maiores velit, optio omnis voluptate sequi obcaecati cumque officia deleniti. Maxime nam obcaecati itaque maiores quisquam deleniti ut possimus perspiciatis ex, vitae.</p>
<ul>
<li>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Odit, ea.</li>
<li>Lorem ipsum dolor sit amet.</li>
<li>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Facilis.</li>
</ul>
## Instruction:
Increase size of sample text in third article to test how it deals with displaying longer articles
## Code After:
<h2>Third Article</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Maiores velit, optio omnis voluptate sequi obcaecati cumque officia deleniti. Maxime nam obcaecati itaque maiores quisquam deleniti ut possimus perspiciatis ex, vitae.</p>
<ul>
<li>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Odit, ea.</li>
<li>Lorem ipsum dolor sit amet.</li>
<li>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Facilis.</li>
</ul>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Temporibus, ad explicabo eligendi quibusdam officia, suscipit recusandae blanditiis quisquam iure voluptate. Nulla ut beatae officiis nam, voluptate nesciunt cupiditate illo qui.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Temporibus, ad explicabo eligendi quibusdam officia, suscipit recusandae blanditiis quisquam iure voluptate. Nulla ut beatae officiis nam, voluptate nesciunt cupiditate illo qui.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laudantium placeat, dicta aliquid fugiat, obcaecati nisi illum repellat nesciunt reiciendis nihil est, qui alias, perspiciatis accusantium libero mollitia quas aspernatur totam animi. Dignissimos unde eaque quam modi, dolores provident quaerat dolorem explicabo veniam. Doloribus illo, nostrum, ratione perspiciatis ut repellendus, quasi sint inventore et facere consequatur debitis eveniet hic deserunt earum vitae nihil cumque dignissimos porro voluptatibus modi. Porro, aspernatur a illo consequatur, commodi ab. Sint ad quia, iusto sapiente omnis recusandae, optio distinctio repellat odio nemo, tenetur voluptas perferendis quisquam qui alias quidem praesentium earum facere expedita? Hic quis ducimus atque beatae voluptatum aut dignissimos enim, temporibus voluptatibus excepturi esse officia repellendus libero consectetur qui, doloribus autem ipsum veniam in odio non recusandae! Odit maiores laudantium accusamus libero eaque! Porro asperiores sed nostrum in? Aperiam eveniet nam voluptates, dolore maxime soluta ratione, delectus quod, nulla, illum officia maiores ab labore?</p> | <h2>Third Article</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Maiores velit, optio omnis voluptate sequi obcaecati cumque officia deleniti. Maxime nam obcaecati itaque maiores quisquam deleniti ut possimus perspiciatis ex, vitae.</p>
<ul>
<li>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Odit, ea.</li>
<li>Lorem ipsum dolor sit amet.</li>
<li>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Facilis.</li>
</ul>
+
+ <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Temporibus, ad explicabo eligendi quibusdam officia, suscipit recusandae blanditiis quisquam iure voluptate. Nulla ut beatae officiis nam, voluptate nesciunt cupiditate illo qui.</p>
+
+ <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Temporibus, ad explicabo eligendi quibusdam officia, suscipit recusandae blanditiis quisquam iure voluptate. Nulla ut beatae officiis nam, voluptate nesciunt cupiditate illo qui.</p>
+
+ <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laudantium placeat, dicta aliquid fugiat, obcaecati nisi illum repellat nesciunt reiciendis nihil est, qui alias, perspiciatis accusantium libero mollitia quas aspernatur totam animi. Dignissimos unde eaque quam modi, dolores provident quaerat dolorem explicabo veniam. Doloribus illo, nostrum, ratione perspiciatis ut repellendus, quasi sint inventore et facere consequatur debitis eveniet hic deserunt earum vitae nihil cumque dignissimos porro voluptatibus modi. Porro, aspernatur a illo consequatur, commodi ab. Sint ad quia, iusto sapiente omnis recusandae, optio distinctio repellat odio nemo, tenetur voluptas perferendis quisquam qui alias quidem praesentium earum facere expedita? Hic quis ducimus atque beatae voluptatum aut dignissimos enim, temporibus voluptatibus excepturi esse officia repellendus libero consectetur qui, doloribus autem ipsum veniam in odio non recusandae! Odit maiores laudantium accusamus libero eaque! Porro asperiores sed nostrum in? Aperiam eveniet nam voluptates, dolore maxime soluta ratione, delectus quod, nulla, illum officia maiores ab labore?</p> | 6 | 0.666667 | 6 | 0 |
fca7a2c4b92e362237fde60972792b115cd962c3 | README.md | README.md |
A messy script that spews as-readable-as-computerly-possible versions of plug.dj
modules into a directory.
## usage
The easiest way to use replug is with [npx](https://npmjs.com/package/npx):
1. `npx replug`
Alternatively, install the CLI globally (you'll have to update manually from time to time):
1. `npm install -g replug`
1. `replug`
Or run it from source:
1. `git clone https://github.com/ExtPlug/replug.git`
1. `cd replug`
1. `npm install`
1. `./index.js`
There are some command-line options:
-h, --help output usage information
-V, --version output the version number
-m, --mapping [file] File containing the mapping JSON (optional, it's auto-generated if no file is given)
-o, --out [dir] Output directory [out/]
-v, --verbose Use verbose output instead of bullet list
### examples
Dump output in `out/`:
```
npx replug
```
Output in `output-directory/`:
```
npx replug --out output-directory
```
## Licence
[MIT](./LICENSE)
|
A messy script that spews as-readable-as-computerly-possible versions of plug.dj
modules into a directory.
## usage
The easiest way to use replug is with [npx](https://npmjs.com/package/npx):
1. `npx replug`
Alternatively, install the CLI globally (you'll have to update manually from time to time):
1. `npm install -g replug`
1. `replug`
There are some command-line options:
-h, --help output usage information
-V, --version output the version number
-m, --mapping [file] File containing the mapping JSON (optional, it's auto-generated if no file is given)
-o, --out [dir] Output directory [out/]
-v, --verbose Use verbose output instead of bullet list
### examples
Dump output in `out/`:
```
npx replug
```
Output in `output-directory/`:
```
npx replug --out output-directory
```
## Licence
[MIT](./LICENSE)
| Remove instructions for running from source | Remove instructions for running from source
| Markdown | mit | ExtPlug/replug | markdown | ## Code Before:
A messy script that spews as-readable-as-computerly-possible versions of plug.dj
modules into a directory.
## usage
The easiest way to use replug is with [npx](https://npmjs.com/package/npx):
1. `npx replug`
Alternatively, install the CLI globally (you'll have to update manually from time to time):
1. `npm install -g replug`
1. `replug`
Or run it from source:
1. `git clone https://github.com/ExtPlug/replug.git`
1. `cd replug`
1. `npm install`
1. `./index.js`
There are some command-line options:
-h, --help output usage information
-V, --version output the version number
-m, --mapping [file] File containing the mapping JSON (optional, it's auto-generated if no file is given)
-o, --out [dir] Output directory [out/]
-v, --verbose Use verbose output instead of bullet list
### examples
Dump output in `out/`:
```
npx replug
```
Output in `output-directory/`:
```
npx replug --out output-directory
```
## Licence
[MIT](./LICENSE)
## Instruction:
Remove instructions for running from source
## Code After:
A messy script that spews as-readable-as-computerly-possible versions of plug.dj
modules into a directory.
## usage
The easiest way to use replug is with [npx](https://npmjs.com/package/npx):
1. `npx replug`
Alternatively, install the CLI globally (you'll have to update manually from time to time):
1. `npm install -g replug`
1. `replug`
There are some command-line options:
-h, --help output usage information
-V, --version output the version number
-m, --mapping [file] File containing the mapping JSON (optional, it's auto-generated if no file is given)
-o, --out [dir] Output directory [out/]
-v, --verbose Use verbose output instead of bullet list
### examples
Dump output in `out/`:
```
npx replug
```
Output in `output-directory/`:
```
npx replug --out output-directory
```
## Licence
[MIT](./LICENSE)
|
A messy script that spews as-readable-as-computerly-possible versions of plug.dj
modules into a directory.
## usage
The easiest way to use replug is with [npx](https://npmjs.com/package/npx):
1. `npx replug`
Alternatively, install the CLI globally (you'll have to update manually from time to time):
1. `npm install -g replug`
1. `replug`
-
- Or run it from source:
-
- 1. `git clone https://github.com/ExtPlug/replug.git`
- 1. `cd replug`
- 1. `npm install`
- 1. `./index.js`
There are some command-line options:
-h, --help output usage information
-V, --version output the version number
-m, --mapping [file] File containing the mapping JSON (optional, it's auto-generated if no file is given)
-o, --out [dir] Output directory [out/]
-v, --verbose Use verbose output instead of bullet list
### examples
Dump output in `out/`:
```
npx replug
```
Output in `output-directory/`:
```
npx replug --out output-directory
```
## Licence
[MIT](./LICENSE) | 7 | 0.148936 | 0 | 7 |
e0eeba656b42ddd2d79bd0f31ad36d64a70dfda0 | moniker/backend/__init__.py | moniker/backend/__init__.py | from moniker.openstack.common import cfg
from moniker.openstack.common import log as logging
from moniker.plugin import Plugin
LOG = logging.getLogger(__name__)
cfg.CONF.register_opts([
cfg.StrOpt('backend-driver', default='bind9',
help='The backend driver to use')
])
def get_backend(conf):
return Plugin.get_plugin(cfg.CONF.backend_driver, ns=__name__, conf=conf)
| from moniker.openstack.common import cfg
from moniker.openstack.common import log as logging
from moniker.plugin import Plugin
LOG = logging.getLogger(__name__)
cfg.CONF.register_opts([
cfg.StrOpt('backend-driver', default='bind9',
help='The backend driver to use')
])
def get_backend(conf):
return Plugin.get_plugin(cfg.CONF.backend_driver, ns=__name__,
conf=conf, invoke_on_load=True)
| Fix so it invokes on load | Fix so it invokes on load
Change-Id: I9806ac61bc1338e566a533f57a50c214ec6e14e7
| Python | apache-2.0 | kiall/designate-py3,openstack/designate,tonyli71/designate,cneill/designate,cneill/designate-testing,richm/designate,muraliselva10/designate,NeCTAR-RC/designate,muraliselva10/designate,kiall/designate-py3,melodous/designate,cneill/designate,kiall/designate-py3,ionrock/designate,melodous/designate,tonyli71/designate,ramsateesh/designate,NeCTAR-RC/designate,melodous/designate,tonyli71/designate,grahamhayes/designate,grahamhayes/designate,cneill/designate-testing,cneill/designate,openstack/designate,kiall/designate-py3,ramsateesh/designate,openstack/designate,grahamhayes/designate,cneill/designate-testing,muraliselva10/designate,ionrock/designate,richm/designate,ramsateesh/designate,cneill/designate,cneill/designate,melodous/designate,ionrock/designate,kiall/designate-py3 | python | ## Code Before:
from moniker.openstack.common import cfg
from moniker.openstack.common import log as logging
from moniker.plugin import Plugin
LOG = logging.getLogger(__name__)
cfg.CONF.register_opts([
cfg.StrOpt('backend-driver', default='bind9',
help='The backend driver to use')
])
def get_backend(conf):
return Plugin.get_plugin(cfg.CONF.backend_driver, ns=__name__, conf=conf)
## Instruction:
Fix so it invokes on load
Change-Id: I9806ac61bc1338e566a533f57a50c214ec6e14e7
## Code After:
from moniker.openstack.common import cfg
from moniker.openstack.common import log as logging
from moniker.plugin import Plugin
LOG = logging.getLogger(__name__)
cfg.CONF.register_opts([
cfg.StrOpt('backend-driver', default='bind9',
help='The backend driver to use')
])
def get_backend(conf):
return Plugin.get_plugin(cfg.CONF.backend_driver, ns=__name__,
conf=conf, invoke_on_load=True)
| from moniker.openstack.common import cfg
from moniker.openstack.common import log as logging
from moniker.plugin import Plugin
LOG = logging.getLogger(__name__)
cfg.CONF.register_opts([
cfg.StrOpt('backend-driver', default='bind9',
help='The backend driver to use')
])
def get_backend(conf):
- return Plugin.get_plugin(cfg.CONF.backend_driver, ns=__name__, conf=conf)
? -----------
+ return Plugin.get_plugin(cfg.CONF.backend_driver, ns=__name__,
+ conf=conf, invoke_on_load=True) | 3 | 0.214286 | 2 | 1 |
87185b432554efbaafb2ae74f60f9fe093fb955a | exercises/palindrome-products/metadata.yml | exercises/palindrome-products/metadata.yml | ---
blurb: "Write a program that can detect palindrome products in a given range."
source: "Problem 4 at Project Euler"
source_url: "http://projecteuler.net/problem=4"
| ---
blurb: "Detect palindrome products in a given range."
source: "Problem 4 at Project Euler"
source_url: "http://projecteuler.net/problem=4"
| Remove "write a program" from palindrome-products exercise | Remove "write a program" from palindrome-products exercise
| YAML | mit | rpottsoh/x-common,exercism/x-common,Vankog/problem-specifications,jmluy/x-common,petertseng/x-common,rpottsoh/x-common,jmluy/x-common,kgengler/x-common,jmluy/x-common,petertseng/x-common,exercism/x-common,Vankog/problem-specifications,ErikSchierboom/x-common,ErikSchierboom/x-common,kgengler/x-common | yaml | ## Code Before:
---
blurb: "Write a program that can detect palindrome products in a given range."
source: "Problem 4 at Project Euler"
source_url: "http://projecteuler.net/problem=4"
## Instruction:
Remove "write a program" from palindrome-products exercise
## Code After:
---
blurb: "Detect palindrome products in a given range."
source: "Problem 4 at Project Euler"
source_url: "http://projecteuler.net/problem=4"
| ---
- blurb: "Write a program that can detect palindrome products in a given range."
? ^^^^^^^^^^^^^^^^^^^^^^^^^^
+ blurb: "Detect palindrome products in a given range."
? ^
source: "Problem 4 at Project Euler"
source_url: "http://projecteuler.net/problem=4" | 2 | 0.5 | 1 | 1 |
8c780f99dd82887a43c8ce661925f993fbc41003 | readux/__init__.py | readux/__init__.py | from django.conf import settings
__version_info__ = (1, 2, 0, 'dev')
# Dot-connect all but the last. Last is dash-connected if not None.
__version__ = '.'.join([str(i) for i in __version_info__[:-1]])
if __version_info__[-1] is not None:
__version__ += ('-%s' % (__version_info__[-1],))
# context processor to add version to the template environment
def context_extras(request):
return {
# software version
'SW_VERSION': __version__,
# Alternate names for social-auth backends,
# to be used for display and font-awesome icon (lowercased)
# If not entered here, backend name will be used as-is for
# icon and title-cased for display (i.e., twitter / Twitter).
'backend_names': {
'github': 'GitHub',
'google-oauth2': 'Google',
},
}
| __version_info__ = (1, 3, 0, 'dev')
# Dot-connect all but the last. Last is dash-connected if not None.
__version__ = '.'.join([str(i) for i in __version_info__[:-1]])
if __version_info__[-1] is not None:
__version__ += ('-%s' % (__version_info__[-1],))
# context processor to add version to the template environment
def context_extras(request):
return {
# software version
'SW_VERSION': __version__,
# Alternate names for social-auth backends,
# to be used for display and font-awesome icon (lowercased)
# If not entered here, backend name will be used as-is for
# icon and title-cased for display (i.e., twitter / Twitter).
'backend_names': {
'github': 'GitHub',
'google-oauth2': 'Google',
},
}
| Bump version to 1.3.0-dev after releasing 1.2 | Bump version to 1.3.0-dev after releasing 1.2
| Python | apache-2.0 | emory-libraries/readux,emory-libraries/readux,emory-libraries/readux | python | ## Code Before:
from django.conf import settings
__version_info__ = (1, 2, 0, 'dev')
# Dot-connect all but the last. Last is dash-connected if not None.
__version__ = '.'.join([str(i) for i in __version_info__[:-1]])
if __version_info__[-1] is not None:
__version__ += ('-%s' % (__version_info__[-1],))
# context processor to add version to the template environment
def context_extras(request):
return {
# software version
'SW_VERSION': __version__,
# Alternate names for social-auth backends,
# to be used for display and font-awesome icon (lowercased)
# If not entered here, backend name will be used as-is for
# icon and title-cased for display (i.e., twitter / Twitter).
'backend_names': {
'github': 'GitHub',
'google-oauth2': 'Google',
},
}
## Instruction:
Bump version to 1.3.0-dev after releasing 1.2
## Code After:
__version_info__ = (1, 3, 0, 'dev')
# Dot-connect all but the last. Last is dash-connected if not None.
__version__ = '.'.join([str(i) for i in __version_info__[:-1]])
if __version_info__[-1] is not None:
__version__ += ('-%s' % (__version_info__[-1],))
# context processor to add version to the template environment
def context_extras(request):
return {
# software version
'SW_VERSION': __version__,
# Alternate names for social-auth backends,
# to be used for display and font-awesome icon (lowercased)
# If not entered here, backend name will be used as-is for
# icon and title-cased for display (i.e., twitter / Twitter).
'backend_names': {
'github': 'GitHub',
'google-oauth2': 'Google',
},
}
| - from django.conf import settings
-
- __version_info__ = (1, 2, 0, 'dev')
? ^
+ __version_info__ = (1, 3, 0, 'dev')
? ^
# Dot-connect all but the last. Last is dash-connected if not None.
__version__ = '.'.join([str(i) for i in __version_info__[:-1]])
if __version_info__[-1] is not None:
__version__ += ('-%s' % (__version_info__[-1],))
# context processor to add version to the template environment
def context_extras(request):
return {
# software version
'SW_VERSION': __version__,
# Alternate names for social-auth backends,
# to be used for display and font-awesome icon (lowercased)
# If not entered here, backend name will be used as-is for
# icon and title-cased for display (i.e., twitter / Twitter).
'backend_names': {
'github': 'GitHub',
'google-oauth2': 'Google',
},
}
| 4 | 0.153846 | 1 | 3 |
a789e8bf574973259c0461b99fb9a486abed6e23 | systemvm/patches/debian/config/opt/cloud/bin/cs_ip.py | systemvm/patches/debian/config/opt/cloud/bin/cs_ip.py | from pprint import pprint
from netaddr import *
def merge(dbag, ip):
added = False
for dev in dbag:
if dev == "id":
continue
for address in dbag[dev]:
if address['public_ip'] == ip['public_ip']:
dbag[dev].remove(address)
if ip['add']:
ipo = IPNetwork(ip['public_ip'] + '/' + ip['netmask'])
ip['device'] = 'eth' + str(ip['nic_dev_id'])
ip['cidr'] = str(ipo.ip) + '/' + str(ipo.prefixlen)
ip['network'] = str(ipo.network) + '/' + str(ipo.prefixlen)
if 'nw_type' not in ip.keys():
ip['nw_type'] = 'public'
dbag.setdefault('eth' + str(ip['nic_dev_id']), []).append( ip )
return dbag
| from pprint import pprint
from netaddr import *
def merge(dbag, ip):
added = False
for dev in dbag:
if dev == "id":
continue
for address in dbag[dev]:
if address['public_ip'] == ip['public_ip']:
dbag[dev].remove(address)
if ip['add']:
ipo = IPNetwork(ip['public_ip'] + '/' + ip['netmask'])
ip['device'] = 'eth' + str(ip['nic_dev_id'])
ip['cidr'] = str(ipo.ip) + '/' + str(ipo.prefixlen)
ip['network'] = str(ipo.network) + '/' + str(ipo.prefixlen)
if 'nw_type' not in ip.keys():
ip['nw_type'] = 'public'
if ip['nw_type'] == 'control':
dbag['eth' + str(ip['nic_dev_id'])] = [ ip ]
else:
dbag.setdefault('eth' + str(ip['nic_dev_id']), []).append( ip )
return dbag
| Fix a bug that would add updated control ip address instead of replace | Fix a bug that would add updated control ip address instead of replace
| Python | apache-2.0 | jcshen007/cloudstack,resmo/cloudstack,resmo/cloudstack,GabrielBrascher/cloudstack,resmo/cloudstack,jcshen007/cloudstack,jcshen007/cloudstack,jcshen007/cloudstack,GabrielBrascher/cloudstack,resmo/cloudstack,GabrielBrascher/cloudstack,GabrielBrascher/cloudstack,wido/cloudstack,resmo/cloudstack,DaanHoogland/cloudstack,GabrielBrascher/cloudstack,DaanHoogland/cloudstack,wido/cloudstack,resmo/cloudstack,wido/cloudstack,resmo/cloudstack,DaanHoogland/cloudstack,jcshen007/cloudstack,jcshen007/cloudstack,wido/cloudstack,DaanHoogland/cloudstack,DaanHoogland/cloudstack,wido/cloudstack,GabrielBrascher/cloudstack,wido/cloudstack,DaanHoogland/cloudstack,jcshen007/cloudstack,DaanHoogland/cloudstack,GabrielBrascher/cloudstack,wido/cloudstack | python | ## Code Before:
from pprint import pprint
from netaddr import *
def merge(dbag, ip):
added = False
for dev in dbag:
if dev == "id":
continue
for address in dbag[dev]:
if address['public_ip'] == ip['public_ip']:
dbag[dev].remove(address)
if ip['add']:
ipo = IPNetwork(ip['public_ip'] + '/' + ip['netmask'])
ip['device'] = 'eth' + str(ip['nic_dev_id'])
ip['cidr'] = str(ipo.ip) + '/' + str(ipo.prefixlen)
ip['network'] = str(ipo.network) + '/' + str(ipo.prefixlen)
if 'nw_type' not in ip.keys():
ip['nw_type'] = 'public'
dbag.setdefault('eth' + str(ip['nic_dev_id']), []).append( ip )
return dbag
## Instruction:
Fix a bug that would add updated control ip address instead of replace
## Code After:
from pprint import pprint
from netaddr import *
def merge(dbag, ip):
added = False
for dev in dbag:
if dev == "id":
continue
for address in dbag[dev]:
if address['public_ip'] == ip['public_ip']:
dbag[dev].remove(address)
if ip['add']:
ipo = IPNetwork(ip['public_ip'] + '/' + ip['netmask'])
ip['device'] = 'eth' + str(ip['nic_dev_id'])
ip['cidr'] = str(ipo.ip) + '/' + str(ipo.prefixlen)
ip['network'] = str(ipo.network) + '/' + str(ipo.prefixlen)
if 'nw_type' not in ip.keys():
ip['nw_type'] = 'public'
if ip['nw_type'] == 'control':
dbag['eth' + str(ip['nic_dev_id'])] = [ ip ]
else:
dbag.setdefault('eth' + str(ip['nic_dev_id']), []).append( ip )
return dbag
| from pprint import pprint
from netaddr import *
def merge(dbag, ip):
added = False
for dev in dbag:
if dev == "id":
continue
for address in dbag[dev]:
if address['public_ip'] == ip['public_ip']:
dbag[dev].remove(address)
if ip['add']:
ipo = IPNetwork(ip['public_ip'] + '/' + ip['netmask'])
ip['device'] = 'eth' + str(ip['nic_dev_id'])
ip['cidr'] = str(ipo.ip) + '/' + str(ipo.prefixlen)
ip['network'] = str(ipo.network) + '/' + str(ipo.prefixlen)
if 'nw_type' not in ip.keys():
ip['nw_type'] = 'public'
+ if ip['nw_type'] == 'control':
+ dbag['eth' + str(ip['nic_dev_id'])] = [ ip ]
+ else:
- dbag.setdefault('eth' + str(ip['nic_dev_id']), []).append( ip )
+ dbag.setdefault('eth' + str(ip['nic_dev_id']), []).append( ip )
? ++++
return dbag | 5 | 0.25 | 4 | 1 |
967cfcd5a261af9ef5622aa5fe9ac291ec46fd83 | documentation/doxygen/ROOT.css | documentation/doxygen/ROOT.css | /* ROOT doxygen HTML_EXTRA_STYLESHEET */
div.contents {
max-width: 100em;
margin-right: 5em;
margin-left: 5em;
} | /* ROOT doxygen HTML_EXTRA_STYLESHEET */
div.contents {
max-width: 100em;
margin-right: 5em;
margin-left: 5em;
}
.ui-resizable-e {
background-image:url("splitbar.png");
background-size:100%;
background-repeat:repeat-y;
background-attachment: scroll;
cursor:ew-resize;
height:100%;
right:0;
top:0;
width:1px;
}
| Make the separation line between the navigation bar and the doc area much thinner. | Make the separation line between the navigation bar and the doc area much thinner.
| CSS | lgpl-2.1 | karies/root,root-mirror/root,karies/root,karies/root,karies/root,karies/root,olifre/root,karies/root,olifre/root,karies/root,olifre/root,root-mirror/root,root-mirror/root,olifre/root,root-mirror/root,olifre/root,root-mirror/root,root-mirror/root,root-mirror/root,root-mirror/root,root-mirror/root,olifre/root,olifre/root,root-mirror/root,karies/root,karies/root,olifre/root,karies/root,root-mirror/root,olifre/root,olifre/root,karies/root,olifre/root | css | ## Code Before:
/* ROOT doxygen HTML_EXTRA_STYLESHEET */
div.contents {
max-width: 100em;
margin-right: 5em;
margin-left: 5em;
}
## Instruction:
Make the separation line between the navigation bar and the doc area much thinner.
## Code After:
/* ROOT doxygen HTML_EXTRA_STYLESHEET */
div.contents {
max-width: 100em;
margin-right: 5em;
margin-left: 5em;
}
.ui-resizable-e {
background-image:url("splitbar.png");
background-size:100%;
background-repeat:repeat-y;
background-attachment: scroll;
cursor:ew-resize;
height:100%;
right:0;
top:0;
width:1px;
}
| /* ROOT doxygen HTML_EXTRA_STYLESHEET */
div.contents {
max-width: 100em;
margin-right: 5em;
margin-left: 5em;
}
+
+ .ui-resizable-e {
+ background-image:url("splitbar.png");
+ background-size:100%;
+ background-repeat:repeat-y;
+ background-attachment: scroll;
+ cursor:ew-resize;
+ height:100%;
+ right:0;
+ top:0;
+ width:1px;
+ } | 12 | 1.714286 | 12 | 0 |
df5bf3fbaacfad4d9343127084fb03260ecd803f | scripts/set_archlinux_defaults.sh | scripts/set_archlinux_defaults.sh | set -euo pipefail
DIR=$(dirname "$(cd "$(dirname "${BASH_SOURCE[0]}")" >/dev/null 2>&1 && pwd)")
. "$DIR/base.sh"
. "$DIR/ansi"
if [[ "$OSTYPE" != "linux-gnu"* ]]; then
ansi --yellow "Platform is not linux-gnu"
fi
if [ ! -f "/etc/arch-release" ]; then
ansi --yellow "Not running arch. Skipping."
fi
# ask sudo upfront
sudo -v
ansi --green "Updating pacman.conf.."
sudo sed -i '/Color$/s/^#//g' /etc/pacman.conf
sudo sed -i '/TotalDownload$/s/^#//g' /etc/pacman.conf
sudo sed -i '/CheckSpace$/s/^#//g' /etc/pacman.conf
sudo sed -i '/VerbosePkgLists$/s/^#//g' /etc/pacman.conf
ansi --green "Enable timedatectl and set up timezone"
sudo timedatectl set-ntp true
sudo ln -sf /usr/share/zoneinfo/Ameriaca/Sao_Paulo /etc/localtime
sudo hwclock --systohc
ansi-green "Setup locale"
sudo sed -i '/en_US.UTF-8$/s/^#//g' /etc/pacman.conf
sudo locale-gen
| set -euo pipefail
DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" >/dev/null 2>&1 && pwd)
. "$DIR/base.sh"
. "$DIR/ansi"
if [[ "$OSTYPE" != "linux-gnu"* ]]; then
ansi --yellow "Platform is not linux-gnu"
fi
if [ ! -f "/etc/arch-release" ]; then
ansi --yellow "Not running arch. Skipping."
fi
# ask sudo upfront
sudo -v
ansi --green "Updating pacman.conf.."
sudo sed -i '/Color$/s/^#//g' /etc/pacman.conf
sudo sed -i '/TotalDownload$/s/^#//g' /etc/pacman.conf
sudo sed -i '/CheckSpace$/s/^#//g' /etc/pacman.conf
sudo sed -i '/VerbosePkgLists$/s/^#//g' /etc/pacman.conf
ansi --green "Enable timedatectl and set up timezone"
sudo timedatectl set-ntp true
sudo ln -sf /usr/share/zoneinfo/Ameriaca/Sao_Paulo /etc/localtime
sudo hwclock --systohc
ansi --green "Setup locale"
sudo sed -i '/en_US.UTF-8$/s/^#//g' /etc/pacman.conf
sudo locale-gen
| Fix bad DIR variable and not found ansi --green | Scripts: Fix bad DIR variable and not found ansi --green
| Shell | mit | benmezger/dotfiles,benmezger/dotfiles,benmezger/dotfiles,benmezger/dotfiles | shell | ## Code Before:
set -euo pipefail
DIR=$(dirname "$(cd "$(dirname "${BASH_SOURCE[0]}")" >/dev/null 2>&1 && pwd)")
. "$DIR/base.sh"
. "$DIR/ansi"
if [[ "$OSTYPE" != "linux-gnu"* ]]; then
ansi --yellow "Platform is not linux-gnu"
fi
if [ ! -f "/etc/arch-release" ]; then
ansi --yellow "Not running arch. Skipping."
fi
# ask sudo upfront
sudo -v
ansi --green "Updating pacman.conf.."
sudo sed -i '/Color$/s/^#//g' /etc/pacman.conf
sudo sed -i '/TotalDownload$/s/^#//g' /etc/pacman.conf
sudo sed -i '/CheckSpace$/s/^#//g' /etc/pacman.conf
sudo sed -i '/VerbosePkgLists$/s/^#//g' /etc/pacman.conf
ansi --green "Enable timedatectl and set up timezone"
sudo timedatectl set-ntp true
sudo ln -sf /usr/share/zoneinfo/Ameriaca/Sao_Paulo /etc/localtime
sudo hwclock --systohc
ansi-green "Setup locale"
sudo sed -i '/en_US.UTF-8$/s/^#//g' /etc/pacman.conf
sudo locale-gen
## Instruction:
Scripts: Fix bad DIR variable and not found ansi --green
## Code After:
set -euo pipefail
DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" >/dev/null 2>&1 && pwd)
. "$DIR/base.sh"
. "$DIR/ansi"
if [[ "$OSTYPE" != "linux-gnu"* ]]; then
ansi --yellow "Platform is not linux-gnu"
fi
if [ ! -f "/etc/arch-release" ]; then
ansi --yellow "Not running arch. Skipping."
fi
# ask sudo upfront
sudo -v
ansi --green "Updating pacman.conf.."
sudo sed -i '/Color$/s/^#//g' /etc/pacman.conf
sudo sed -i '/TotalDownload$/s/^#//g' /etc/pacman.conf
sudo sed -i '/CheckSpace$/s/^#//g' /etc/pacman.conf
sudo sed -i '/VerbosePkgLists$/s/^#//g' /etc/pacman.conf
ansi --green "Enable timedatectl and set up timezone"
sudo timedatectl set-ntp true
sudo ln -sf /usr/share/zoneinfo/Ameriaca/Sao_Paulo /etc/localtime
sudo hwclock --systohc
ansi --green "Setup locale"
sudo sed -i '/en_US.UTF-8$/s/^#//g' /etc/pacman.conf
sudo locale-gen
| set -euo pipefail
- DIR=$(dirname "$(cd "$(dirname "${BASH_SOURCE[0]}")" >/dev/null 2>&1 && pwd)")
? ----------- --
+ DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" >/dev/null 2>&1 && pwd)
. "$DIR/base.sh"
. "$DIR/ansi"
if [[ "$OSTYPE" != "linux-gnu"* ]]; then
ansi --yellow "Platform is not linux-gnu"
fi
if [ ! -f "/etc/arch-release" ]; then
ansi --yellow "Not running arch. Skipping."
fi
# ask sudo upfront
sudo -v
ansi --green "Updating pacman.conf.."
sudo sed -i '/Color$/s/^#//g' /etc/pacman.conf
sudo sed -i '/TotalDownload$/s/^#//g' /etc/pacman.conf
sudo sed -i '/CheckSpace$/s/^#//g' /etc/pacman.conf
sudo sed -i '/VerbosePkgLists$/s/^#//g' /etc/pacman.conf
ansi --green "Enable timedatectl and set up timezone"
sudo timedatectl set-ntp true
sudo ln -sf /usr/share/zoneinfo/Ameriaca/Sao_Paulo /etc/localtime
sudo hwclock --systohc
- ansi-green "Setup locale"
+ ansi --green "Setup locale"
? ++
sudo sed -i '/en_US.UTF-8$/s/^#//g' /etc/pacman.conf
sudo locale-gen | 4 | 0.129032 | 2 | 2 |
ed6e49ad2fe3b2577d84277bf90047f87163c517 | client/app/landing/landing.js | client/app/landing/landing.js | angular.module('zeus.landing', [])
.controller('LandingController', function() {
}); | angular.module('zeus.landing', [])
.controller('LandingController', function($scope, Landing) {
$scope.populars = {};
$scope.latests = {};
$scope.upcomings = {};
$scope.fetchPopular = function() {
Landing.getPopular()
.then(function(data) {
$scope.populars = data.results;
});
};
$scope.fetchLatest = function() {
Landing.getLatest()
.then(function(data) {
$scope.latests = data.results;
});
};
$scope.fetchUpcoming = function() {
Landing.getUpcoming()
.then(function(data) {
$scope.upcomings = data.results;
});
};
}); | Add fetch methods for API cals to themoviedb for popular, upcoming, latest | Add fetch methods for API cals to themoviedb for popular, upcoming, latest
| JavaScript | mit | ALeo23/Zeus-HatersGonaHate,ALeo23/Zeus-HatersGonaHate,Zeus-HatersGonaHate/Zeus-HatersGonaHate,ALeo23/Zeus-HatersGonaHate,Zeus-HatersGonaHate/Zeus-HatersGonaHate,Zeus-HatersGonaHate/Zeus-HatersGonaHate | javascript | ## Code Before:
angular.module('zeus.landing', [])
.controller('LandingController', function() {
});
## Instruction:
Add fetch methods for API cals to themoviedb for popular, upcoming, latest
## Code After:
angular.module('zeus.landing', [])
.controller('LandingController', function($scope, Landing) {
$scope.populars = {};
$scope.latests = {};
$scope.upcomings = {};
$scope.fetchPopular = function() {
Landing.getPopular()
.then(function(data) {
$scope.populars = data.results;
});
};
$scope.fetchLatest = function() {
Landing.getLatest()
.then(function(data) {
$scope.latests = data.results;
});
};
$scope.fetchUpcoming = function() {
Landing.getUpcoming()
.then(function(data) {
$scope.upcomings = data.results;
});
};
}); | angular.module('zeus.landing', [])
- .controller('LandingController', function() {
+ .controller('LandingController', function($scope, Landing) {
? +++++++++++++++
+ $scope.populars = {};
+ $scope.latests = {};
+ $scope.upcomings = {};
+ $scope.fetchPopular = function() {
+ Landing.getPopular()
+ .then(function(data) {
+ $scope.populars = data.results;
+ });
+ };
+ $scope.fetchLatest = function() {
+ Landing.getLatest()
+ .then(function(data) {
+ $scope.latests = data.results;
+ });
+ };
+ $scope.fetchUpcoming = function() {
+ Landing.getUpcoming()
+ .then(function(data) {
+ $scope.upcomings = data.results;
+ });
+ };
}); | 23 | 4.6 | 22 | 1 |
a7fc9e16b831314726c9964804a40e017a27ccee | public/less/_variables.less | public/less/_variables.less | @react-dark: #2d2d2d;
@react-light: #f9f9f9;
@react-blue: #61dafb;
@react-maroon: #c05b4d;
@react-text: #484848;
@react-light-text: #e9e9e9;
@react-code-text: #555;
@react-code-bg: fade(#000, 4%);
@page-margin: 0;
@page-padding: 0;
@page-max-width: 900px;
@page-sans-serif-fonts: "Helvetica Neue", Helvetica, Arial, sans-serif;
@header-padding: 10px 0;
@header-logo-size: 180px;
@search-input-font-size: 18px;
@search-input-padding: 12px 20px 12px 10px;
@search-input-header-width: 550px;
@content-padding: 10px;
@content-margin: 20px;
@content-border: 1px solid rgba(16, 16, 16, 0.1);
@content-border-radius: 3px;
@content-background: #fff; | @react-dark: #2d2d2d;
@react-light: #f9f9f9;
@react-blue: #61dafb;
@react-maroon: #c05b4d;
@react-text: #484848;
@react-light-text: #e9e9e9;
@react-code-text: #555;
@react-code-bg: fade(#000, 4%);
@page-margin: 0;
@page-padding: 0;
@page-max-width: 900px;
@page-sans-serif-fonts: "Helvetica Neue", Helvetica, Arial, sans-serif;
@header-padding: 10px 0;
@header-logo-size: 180px;
@search-input-font-size: 18px;
@search-input-padding: 12px 0;
@search-input-header-width: 580px;
@content-padding: 10px;
@content-margin: 20px;
@content-border: 1px solid rgba(16, 16, 16, 0.1);
@content-border-radius: 3px;
@content-background: #fff;
| Fix style of input search box | Fix style of input search box
| Less | mit | rexxars/react-components,vaffel/react-components,vaffel/react-components,rexxars/react-components | less | ## Code Before:
@react-dark: #2d2d2d;
@react-light: #f9f9f9;
@react-blue: #61dafb;
@react-maroon: #c05b4d;
@react-text: #484848;
@react-light-text: #e9e9e9;
@react-code-text: #555;
@react-code-bg: fade(#000, 4%);
@page-margin: 0;
@page-padding: 0;
@page-max-width: 900px;
@page-sans-serif-fonts: "Helvetica Neue", Helvetica, Arial, sans-serif;
@header-padding: 10px 0;
@header-logo-size: 180px;
@search-input-font-size: 18px;
@search-input-padding: 12px 20px 12px 10px;
@search-input-header-width: 550px;
@content-padding: 10px;
@content-margin: 20px;
@content-border: 1px solid rgba(16, 16, 16, 0.1);
@content-border-radius: 3px;
@content-background: #fff;
## Instruction:
Fix style of input search box
## Code After:
@react-dark: #2d2d2d;
@react-light: #f9f9f9;
@react-blue: #61dafb;
@react-maroon: #c05b4d;
@react-text: #484848;
@react-light-text: #e9e9e9;
@react-code-text: #555;
@react-code-bg: fade(#000, 4%);
@page-margin: 0;
@page-padding: 0;
@page-max-width: 900px;
@page-sans-serif-fonts: "Helvetica Neue", Helvetica, Arial, sans-serif;
@header-padding: 10px 0;
@header-logo-size: 180px;
@search-input-font-size: 18px;
@search-input-padding: 12px 0;
@search-input-header-width: 580px;
@content-padding: 10px;
@content-margin: 20px;
@content-border: 1px solid rgba(16, 16, 16, 0.1);
@content-border-radius: 3px;
@content-background: #fff;
| @react-dark: #2d2d2d;
@react-light: #f9f9f9;
@react-blue: #61dafb;
@react-maroon: #c05b4d;
@react-text: #484848;
@react-light-text: #e9e9e9;
@react-code-text: #555;
@react-code-bg: fade(#000, 4%);
@page-margin: 0;
@page-padding: 0;
@page-max-width: 900px;
@page-sans-serif-fonts: "Helvetica Neue", Helvetica, Arial, sans-serif;
@header-padding: 10px 0;
@header-logo-size: 180px;
@search-input-font-size: 18px;
- @search-input-padding: 12px 20px 12px 10px;
? - ------------
+ @search-input-padding: 12px 0;
- @search-input-header-width: 550px;
? ^
+ @search-input-header-width: 580px;
? ^
@content-padding: 10px;
@content-margin: 20px;
@content-border: 1px solid rgba(16, 16, 16, 0.1);
@content-border-radius: 3px;
@content-background: #fff; | 4 | 0.153846 | 2 | 2 |
b7ea8b8b0d2d9541356fa70db2221defbb5b54d1 | app/controllers/builds_controller.rb | app/controllers/builds_controller.rb | class BuildsController < ApplicationController
before_filter :load_project, :only => :show
def show
@build = @project.builds.find(params[:id])
end
def create
make_build
if @build
head :ok, :location => project_build_url(@build.project, @build)
else
head :ok
end
end
def request_build
make_build
if @build
flash[:message] = "Build added!"
else
flash[:error] = "Error adding build!"
end
redirect_to project_path(params[:project_id])
end
private
def make_build
if params['payload']
@build = create_build_from_github
elsif params['build']
@build = create_developer_build
end
end
def load_project
@project = Project.find_by_name!(params[:project_id])
end
def create_build_from_github
load_project
payload = params['payload']
requested_branch = payload['ref'].split('/').last
if @project.branch == requested_branch
@project.builds.create!(:state => :partitioning, :ref => payload['after'], :queue => :ci)
end
end
def create_developer_build
@project = Project.where(:name => params[:project_id]).first
if !@project
@project = Project.create!(:name => params[:project_id])
end
@project.builds.create!(:state => :partitioning, :ref => params[:build][:ref], :queue => :developer)
end
end
| class BuildsController < ApplicationController
before_filter :load_project, :only => :show
def show
@build = @project.builds.find(params[:id])
end
def create
build = make_build
if build && build.save
head :ok, :location => project_build_url(build.project, build)
else
head :ok
end
end
def request_build
if developer_build.save
flash[:message] = "Build added!"
else
flash[:error] = "Error adding build!"
end
redirect_to project_path(params[:project_id])
end
private
def make_build
if params['payload']
build_from_github
elsif params['build']
developer_build
end
end
def load_project
@project = Project.find_by_name!(params[:project_id])
end
def build_from_github
load_project
payload = params['payload']
requested_branch = payload['ref'].split('/').last
if @project.branch == requested_branch
@project.builds.build(:state => :partitioning, :ref => payload['after'], :queue => :ci)
end
end
def developer_build
@project = Project.where(:name => params[:project_id]).first
if !@project
@project = Project.create!(:name => params[:project_id])
end
@project.builds.build(:state => :partitioning, :ref => params[:build][:ref], :queue => :developer)
end
end
| Fix controller to check validity correctly | Fix controller to check validity correctly
| Ruby | apache-2.0 | IoraHealth/kochiku,rudle/kochiku,rudle/kochiku,moshez/kochiku,IoraHealth/kochiku,moshez/kochiku,moshez/kochiku,moshez/kochiku,square/kochiku,square/kochiku,square/kochiku,IoraHealth/kochiku,rudle/kochiku,rudle/kochiku,square/kochiku | ruby | ## Code Before:
class BuildsController < ApplicationController
before_filter :load_project, :only => :show
def show
@build = @project.builds.find(params[:id])
end
def create
make_build
if @build
head :ok, :location => project_build_url(@build.project, @build)
else
head :ok
end
end
def request_build
make_build
if @build
flash[:message] = "Build added!"
else
flash[:error] = "Error adding build!"
end
redirect_to project_path(params[:project_id])
end
private
def make_build
if params['payload']
@build = create_build_from_github
elsif params['build']
@build = create_developer_build
end
end
def load_project
@project = Project.find_by_name!(params[:project_id])
end
def create_build_from_github
load_project
payload = params['payload']
requested_branch = payload['ref'].split('/').last
if @project.branch == requested_branch
@project.builds.create!(:state => :partitioning, :ref => payload['after'], :queue => :ci)
end
end
def create_developer_build
@project = Project.where(:name => params[:project_id]).first
if !@project
@project = Project.create!(:name => params[:project_id])
end
@project.builds.create!(:state => :partitioning, :ref => params[:build][:ref], :queue => :developer)
end
end
## Instruction:
Fix controller to check validity correctly
## Code After:
class BuildsController < ApplicationController
before_filter :load_project, :only => :show
def show
@build = @project.builds.find(params[:id])
end
def create
build = make_build
if build && build.save
head :ok, :location => project_build_url(build.project, build)
else
head :ok
end
end
def request_build
if developer_build.save
flash[:message] = "Build added!"
else
flash[:error] = "Error adding build!"
end
redirect_to project_path(params[:project_id])
end
private
def make_build
if params['payload']
build_from_github
elsif params['build']
developer_build
end
end
def load_project
@project = Project.find_by_name!(params[:project_id])
end
def build_from_github
load_project
payload = params['payload']
requested_branch = payload['ref'].split('/').last
if @project.branch == requested_branch
@project.builds.build(:state => :partitioning, :ref => payload['after'], :queue => :ci)
end
end
def developer_build
@project = Project.where(:name => params[:project_id]).first
if !@project
@project = Project.create!(:name => params[:project_id])
end
@project.builds.build(:state => :partitioning, :ref => params[:build][:ref], :queue => :developer)
end
end
| class BuildsController < ApplicationController
before_filter :load_project, :only => :show
def show
@build = @project.builds.find(params[:id])
end
def create
- make_build
+ build = make_build
? ++++++++
- if @build
+ if build && build.save
- head :ok, :location => project_build_url(@build.project, @build)
? - -
+ head :ok, :location => project_build_url(build.project, build)
else
head :ok
end
end
def request_build
+ if developer_build.save
- make_build
- if @build
flash[:message] = "Build added!"
else
flash[:error] = "Error adding build!"
end
redirect_to project_path(params[:project_id])
end
private
def make_build
if params['payload']
- @build = create_build_from_github
+ build_from_github
elsif params['build']
- @build = create_developer_build
+ developer_build
end
end
def load_project
@project = Project.find_by_name!(params[:project_id])
end
- def create_build_from_github
? -------
+ def build_from_github
load_project
payload = params['payload']
requested_branch = payload['ref'].split('/').last
if @project.branch == requested_branch
- @project.builds.create!(:state => :partitioning, :ref => payload['after'], :queue => :ci)
? ^^^^^^^
+ @project.builds.build(:state => :partitioning, :ref => payload['after'], :queue => :ci)
? ^^^^^
end
end
- def create_developer_build
? -------
+ def developer_build
@project = Project.where(:name => params[:project_id]).first
if !@project
@project = Project.create!(:name => params[:project_id])
end
- @project.builds.create!(:state => :partitioning, :ref => params[:build][:ref], :queue => :developer)
? ^^^^^^^
+ @project.builds.build(:state => :partitioning, :ref => params[:build][:ref], :queue => :developer)
? ^^^^^
end
end | 21 | 0.344262 | 10 | 11 |
ba6a2f0667887eb5e723c4ac8bae7283f84e96a0 | nginx/iptables.sls | nginx/iptables.sls | {% from 'states/nginx/map.jinja' import nginx as nginx_map with context %}
.params:
stateconf.set: []
# --- end of state config ---
{% for protocol in ['http', 'https'] %}
{% if params[protocol] %}
nginx-iptables-{{ protocol }}:
iptables.append:
- table: filter
- chain: ZONE_LOCAL
- proto: tcp
- jump: ACCEPT
- dport: {{ nginx_map.ports[protocol] }}
- family: ipv4
- save: true
- match: comment
- comment: nginx {{ protocol|upper }}
- require:
- iptables: chain_zone_local_ipv4
{% endif %}
{% endfor %}
| {% from 'states/nginx/map.jinja' import nginx as nginx_map with context %}
.params:
stateconf.set: []
# --- end of state config ---
{% for protocol in ['http', 'https'] %}
{% if params[protocol] %}
nginx-iptables-{{ protocol }}:
iptables.append:
- table: filter
- chain: {{ 'ZONE_PUBLIC' if params.get('public', False) else 'ZONE_LOCAL' }}
- proto: tcp
- jump: ACCEPT
- dport: {{ nginx_map.ports[protocol] }}
- family: ipv4
- save: true
- match: comment
- comment: nginx {{ protocol|upper }}
- require:
- iptables: chain_zone_local_ipv4
{% endif %}
{% endfor %}
| Add parameter for changing nginx access zone. | Add parameter for changing nginx access zone.
| SaltStack | apache-2.0 | whatevsz/salt-states,whatevsz/salt-states,whatevsz/salt-states-parameterized,whatevsz/salt-states-parameterized | saltstack | ## Code Before:
{% from 'states/nginx/map.jinja' import nginx as nginx_map with context %}
.params:
stateconf.set: []
# --- end of state config ---
{% for protocol in ['http', 'https'] %}
{% if params[protocol] %}
nginx-iptables-{{ protocol }}:
iptables.append:
- table: filter
- chain: ZONE_LOCAL
- proto: tcp
- jump: ACCEPT
- dport: {{ nginx_map.ports[protocol] }}
- family: ipv4
- save: true
- match: comment
- comment: nginx {{ protocol|upper }}
- require:
- iptables: chain_zone_local_ipv4
{% endif %}
{% endfor %}
## Instruction:
Add parameter for changing nginx access zone.
## Code After:
{% from 'states/nginx/map.jinja' import nginx as nginx_map with context %}
.params:
stateconf.set: []
# --- end of state config ---
{% for protocol in ['http', 'https'] %}
{% if params[protocol] %}
nginx-iptables-{{ protocol }}:
iptables.append:
- table: filter
- chain: {{ 'ZONE_PUBLIC' if params.get('public', False) else 'ZONE_LOCAL' }}
- proto: tcp
- jump: ACCEPT
- dport: {{ nginx_map.ports[protocol] }}
- family: ipv4
- save: true
- match: comment
- comment: nginx {{ protocol|upper }}
- require:
- iptables: chain_zone_local_ipv4
{% endif %}
{% endfor %}
| {% from 'states/nginx/map.jinja' import nginx as nginx_map with context %}
.params:
stateconf.set: []
# --- end of state config ---
{% for protocol in ['http', 'https'] %}
{% if params[protocol] %}
nginx-iptables-{{ protocol }}:
iptables.append:
- table: filter
- - chain: ZONE_LOCAL
+ - chain: {{ 'ZONE_PUBLIC' if params.get('public', False) else 'ZONE_LOCAL' }}
- proto: tcp
- jump: ACCEPT
- dport: {{ nginx_map.ports[protocol] }}
- family: ipv4
- save: true
- match: comment
- comment: nginx {{ protocol|upper }}
- require:
- iptables: chain_zone_local_ipv4
{% endif %}
{% endfor %} | 2 | 0.086957 | 1 | 1 |
67e83c2f4330f8d8b4decb211577e251c1d67421 | app/authorizers/universe_core_content_authorizer.rb | app/authorizers/universe_core_content_authorizer.rb | class UniverseCoreContentAuthorizer < CoreContentAuthorizer
def self.creatable_by? user
[
PermissionService.user_has_fewer_owned_universes_than_plan_limit?(user: user),
].any?
end
def readable_by? user
[
PermissionService.content_is_public?(content: resource),
PermissionService.user_owns_content?(user: user, content: resource),
PermissionService.user_can_contribute_to_universe?(user: user, universe: resource)
].any?
end
def updatable_by? user
[
PermissionService.user_owns_content?(user: user, content: resource),
PermissionService.user_can_contribute_to_universe?(user: user, universe: resource)
].any?
end
def deletable_by? user
[
PermissionService.user_owns_content?(user: user, content: resource)
].any?
end
end
| class UniverseCoreContentAuthorizer < CoreContentAuthorizer
def self.creatable_by? user
[
PermissionService.user_has_fewer_owned_universes_than_plan_limit?(user: user),
PermissionService.user_is_on_premium_plan?(user: user)
].any?
end
def readable_by? user
[
PermissionService.content_is_public?(content: resource),
PermissionService.user_owns_content?(user: user, content: resource),
PermissionService.user_can_contribute_to_universe?(user: user, universe: resource)
].any?
end
def updatable_by? user
[
PermissionService.user_owns_content?(user: user, content: resource),
PermissionService.user_can_contribute_to_universe?(user: user, universe: resource)
].any?
end
def deletable_by? user
[
PermissionService.user_owns_content?(user: user, content: resource)
].any?
end
end
| Allow anyone on premium to create universes regardless of current subscription | Allow anyone on premium to create universes regardless of current subscription
| Ruby | mit | indentlabs/notebook,indentlabs/notebook,indentlabs/notebook | ruby | ## Code Before:
class UniverseCoreContentAuthorizer < CoreContentAuthorizer
def self.creatable_by? user
[
PermissionService.user_has_fewer_owned_universes_than_plan_limit?(user: user),
].any?
end
def readable_by? user
[
PermissionService.content_is_public?(content: resource),
PermissionService.user_owns_content?(user: user, content: resource),
PermissionService.user_can_contribute_to_universe?(user: user, universe: resource)
].any?
end
def updatable_by? user
[
PermissionService.user_owns_content?(user: user, content: resource),
PermissionService.user_can_contribute_to_universe?(user: user, universe: resource)
].any?
end
def deletable_by? user
[
PermissionService.user_owns_content?(user: user, content: resource)
].any?
end
end
## Instruction:
Allow anyone on premium to create universes regardless of current subscription
## Code After:
class UniverseCoreContentAuthorizer < CoreContentAuthorizer
def self.creatable_by? user
[
PermissionService.user_has_fewer_owned_universes_than_plan_limit?(user: user),
PermissionService.user_is_on_premium_plan?(user: user)
].any?
end
def readable_by? user
[
PermissionService.content_is_public?(content: resource),
PermissionService.user_owns_content?(user: user, content: resource),
PermissionService.user_can_contribute_to_universe?(user: user, universe: resource)
].any?
end
def updatable_by? user
[
PermissionService.user_owns_content?(user: user, content: resource),
PermissionService.user_can_contribute_to_universe?(user: user, universe: resource)
].any?
end
def deletable_by? user
[
PermissionService.user_owns_content?(user: user, content: resource)
].any?
end
end
| class UniverseCoreContentAuthorizer < CoreContentAuthorizer
def self.creatable_by? user
[
PermissionService.user_has_fewer_owned_universes_than_plan_limit?(user: user),
+ PermissionService.user_is_on_premium_plan?(user: user)
].any?
end
def readable_by? user
[
PermissionService.content_is_public?(content: resource),
PermissionService.user_owns_content?(user: user, content: resource),
PermissionService.user_can_contribute_to_universe?(user: user, universe: resource)
].any?
end
def updatable_by? user
[
PermissionService.user_owns_content?(user: user, content: resource),
PermissionService.user_can_contribute_to_universe?(user: user, universe: resource)
].any?
end
def deletable_by? user
[
PermissionService.user_owns_content?(user: user, content: resource)
].any?
end
end | 1 | 0.035714 | 1 | 0 |
2aecf5dd32711fb3791eab6988e1de00054b16f3 | config/deploy/production.rb | config/deploy/production.rb | role :app, %w(deploy@localhost)
role :web, %w(deploy@localhost)
role :db, %w(deploy@localhost)
server 'localhost', user: 'deploy', roles: %w(web app)
set :rails_env, 'production'
set :linked_files, %w{config/database.yml}
| role :app, %w(deploy@localhost)
role :web, %w(deploy@localhost)
role :db, %w(deploy@localhost)
server 'localhost', user: 'deploy', roles: %w(web app)
set :rails_env, 'production'
set :linked_files, %w{config/database.yml config/secrets.yml}
| Add support for secrets deployment | Add support for secrets deployment
| Ruby | apache-2.0 | mozilla-japan/gitfab2,mozilla-japan/gitfab2,mozilla-japan/gitfab2 | ruby | ## Code Before:
role :app, %w(deploy@localhost)
role :web, %w(deploy@localhost)
role :db, %w(deploy@localhost)
server 'localhost', user: 'deploy', roles: %w(web app)
set :rails_env, 'production'
set :linked_files, %w{config/database.yml}
## Instruction:
Add support for secrets deployment
## Code After:
role :app, %w(deploy@localhost)
role :web, %w(deploy@localhost)
role :db, %w(deploy@localhost)
server 'localhost', user: 'deploy', roles: %w(web app)
set :rails_env, 'production'
set :linked_files, %w{config/database.yml config/secrets.yml}
| role :app, %w(deploy@localhost)
role :web, %w(deploy@localhost)
role :db, %w(deploy@localhost)
server 'localhost', user: 'deploy', roles: %w(web app)
set :rails_env, 'production'
- set :linked_files, %w{config/database.yml}
+ set :linked_files, %w{config/database.yml config/secrets.yml}
? +++++++++++++++++++
| 2 | 0.333333 | 1 | 1 |
b6cc6d318afcb55f788ac4e29ba13ce9c58ac7c1 | _posts/2015-05-29-running-mocha-like-jest.md | _posts/2015-05-29-running-mocha-like-jest.md | ---
layout: post
title: Running Mocha in __tests__ directories
---
I don't know about you, but I quite like the [Jest](https://facebook.github.io/jest/) convention of putting tests in `__tests__` directories. It keeps the tests local to the modules they're testing, and visible in the `src` directory, rather than hidden away in `test`. I know, it's the little things.
Anyway, here's how to achieve that with [Mocha](http://mochajs.org/), my test runner of choice. Just stick the following in your `package.json` scripts:
```json
"mocha": "find ./src -wholename \"./*__tests__/*\" | xargs mocha -R spec"
```
Inspired by [this Gist](https://gist.github.com/timoxley/1721593).
| ---
layout: post
title: Running Mocha in __tests__ directories
---
I don't know about you, but I quite like the [Jest](https://facebook.github.io/jest/) convention of putting tests in `__tests__` directories. It keeps the tests local to the modules they're testing, and visible in the `src` directory, rather than hidden away in `test`. I know, it's the little things.
Anyway, here's how to achieve that with [Mocha](http://mochajs.org/), my test runner of choice. Just stick the following in your `package.json` scripts:
```json
"mocha": "find ./src -wholename \"./*__tests__/*\" | xargs mocha -R spec"
```
Inspired by [this Gist](https://gist.github.com/timoxley/1721593).
##### EDIT
Alternatively, this is much simpler and seems to work:
```json
"mocha": "mocha **/*__tests__/* -R spec"
```
| Update mocha post with simpler solution | Update mocha post with simpler solution
| Markdown | mit | ThomWright/ThomWright.github.io,ThomWright/ThomWright.github.io,ThomWright/ThomWright.github.io | markdown | ## Code Before:
---
layout: post
title: Running Mocha in __tests__ directories
---
I don't know about you, but I quite like the [Jest](https://facebook.github.io/jest/) convention of putting tests in `__tests__` directories. It keeps the tests local to the modules they're testing, and visible in the `src` directory, rather than hidden away in `test`. I know, it's the little things.
Anyway, here's how to achieve that with [Mocha](http://mochajs.org/), my test runner of choice. Just stick the following in your `package.json` scripts:
```json
"mocha": "find ./src -wholename \"./*__tests__/*\" | xargs mocha -R spec"
```
Inspired by [this Gist](https://gist.github.com/timoxley/1721593).
## Instruction:
Update mocha post with simpler solution
## Code After:
---
layout: post
title: Running Mocha in __tests__ directories
---
I don't know about you, but I quite like the [Jest](https://facebook.github.io/jest/) convention of putting tests in `__tests__` directories. It keeps the tests local to the modules they're testing, and visible in the `src` directory, rather than hidden away in `test`. I know, it's the little things.
Anyway, here's how to achieve that with [Mocha](http://mochajs.org/), my test runner of choice. Just stick the following in your `package.json` scripts:
```json
"mocha": "find ./src -wholename \"./*__tests__/*\" | xargs mocha -R spec"
```
Inspired by [this Gist](https://gist.github.com/timoxley/1721593).
##### EDIT
Alternatively, this is much simpler and seems to work:
```json
"mocha": "mocha **/*__tests__/* -R spec"
```
| ---
layout: post
title: Running Mocha in __tests__ directories
---
I don't know about you, but I quite like the [Jest](https://facebook.github.io/jest/) convention of putting tests in `__tests__` directories. It keeps the tests local to the modules they're testing, and visible in the `src` directory, rather than hidden away in `test`. I know, it's the little things.
Anyway, here's how to achieve that with [Mocha](http://mochajs.org/), my test runner of choice. Just stick the following in your `package.json` scripts:
```json
"mocha": "find ./src -wholename \"./*__tests__/*\" | xargs mocha -R spec"
```
Inspired by [this Gist](https://gist.github.com/timoxley/1721593).
+
+ ##### EDIT
+
+ Alternatively, this is much simpler and seems to work:
+
+ ```json
+ "mocha": "mocha **/*__tests__/* -R spec"
+ ``` | 8 | 0.571429 | 8 | 0 |
ed0f115e600a564117ed540e7692e0efccf5826b | server/nso.py | server/nso.py | from flask import request, Response
from .base import *
from server import app
import requests
import re
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
@app.route('/nso')
def get_nso_events():
r = requests.get("http://www.nso.upenn.edu/event-calendar.rss")
split = r.text.split("\n")
filtered = [i if "<pubDate" not in i else "<pubDate>Wed, 02 Aug 2016 08:00:00 EST</pubDate>" for i in split]
output = "\n".join(filtered)
return Response(output, mimetype="text/xml")
| from flask import request, Response
from .base import *
from server import app
import requests
import re
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
@app.route('/nso')
def get_nso_events():
r = requests.get("http://www.nso.upenn.edu/event-calendar.rss")
split = r.text.split("\n")
filtered = [i if "<pubDate" not in i else "<pubDate>Wed, 02 Aug 2016 08:00:00 EST</pubDate>" for i in split]
filtered = [i if ("<title" not in i or "NSO Event Calendar" in i) else changeTitle(i) for i in filtered]
output = "\n".join(filtered)
return Response(output, mimetype="text/xml")
def changeTitle(a):
index = a.index("event") + 17
a = subFour(a,index)
if a[index+6] == '-':
a = subFour(a,index + 18)
return a
def subFour(string, index):
val = string[index:index+6]
new_val = str(int(val) - 40000)
if len(new_val) < 6:
new_val = "0" + new_val
return string.replace(val, new_val)
| Set time back four hours to EST | Set time back four hours to EST
| Python | mit | pennlabs/penn-mobile-server,pennlabs/penn-mobile-server | python | ## Code Before:
from flask import request, Response
from .base import *
from server import app
import requests
import re
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
@app.route('/nso')
def get_nso_events():
r = requests.get("http://www.nso.upenn.edu/event-calendar.rss")
split = r.text.split("\n")
filtered = [i if "<pubDate" not in i else "<pubDate>Wed, 02 Aug 2016 08:00:00 EST</pubDate>" for i in split]
output = "\n".join(filtered)
return Response(output, mimetype="text/xml")
## Instruction:
Set time back four hours to EST
## Code After:
from flask import request, Response
from .base import *
from server import app
import requests
import re
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
@app.route('/nso')
def get_nso_events():
r = requests.get("http://www.nso.upenn.edu/event-calendar.rss")
split = r.text.split("\n")
filtered = [i if "<pubDate" not in i else "<pubDate>Wed, 02 Aug 2016 08:00:00 EST</pubDate>" for i in split]
filtered = [i if ("<title" not in i or "NSO Event Calendar" in i) else changeTitle(i) for i in filtered]
output = "\n".join(filtered)
return Response(output, mimetype="text/xml")
def changeTitle(a):
index = a.index("event") + 17
a = subFour(a,index)
if a[index+6] == '-':
a = subFour(a,index + 18)
return a
def subFour(string, index):
val = string[index:index+6]
new_val = str(int(val) - 40000)
if len(new_val) < 6:
new_val = "0" + new_val
return string.replace(val, new_val)
| from flask import request, Response
from .base import *
from server import app
import requests
import re
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
@app.route('/nso')
def get_nso_events():
r = requests.get("http://www.nso.upenn.edu/event-calendar.rss")
split = r.text.split("\n")
- filtered = [i if "<pubDate" not in i else "<pubDate>Wed, 02 Aug 2016 08:00:00 EST</pubDate>" for i in split]
? -
+ filtered = [i if "<pubDate" not in i else "<pubDate>Wed, 02 Aug 2016 08:00:00 EST</pubDate>" for i in split]
+ filtered = [i if ("<title" not in i or "NSO Event Calendar" in i) else changeTitle(i) for i in filtered]
output = "\n".join(filtered)
return Response(output, mimetype="text/xml")
+
+ def changeTitle(a):
+ index = a.index("event") + 17
+ a = subFour(a,index)
+ if a[index+6] == '-':
+ a = subFour(a,index + 18)
+ return a
+
+ def subFour(string, index):
+ val = string[index:index+6]
+ new_val = str(int(val) - 40000)
+ if len(new_val) < 6:
+ new_val = "0" + new_val
+ return string.replace(val, new_val)
+ | 18 | 1.125 | 17 | 1 |
9389088cf75fe4c2e386b5d8ad5ac0f3e2c4ac51 | src/cli/class-papi-cli-command.php | src/cli/class-papi-cli-command.php | <?php
/**
* Base class that must be extended by any Papi sub commands.
*/
class Papi_CLI_Command extends WP_CLI_Command {
}
| <?php
/**
* Base class that must be extended by any Papi sub commands.
*/
class Papi_CLI_Command extends WP_CLI_Command {
/**
* Get formatter object based on supplied arguments.
*
* @param array $assoc_args Associative args from CLI to determine formattin
*
* @return \WP_CLI\Formatter
*/
protected function get_formatter( $assoc_args ) {
$args = $this->get_format_args( $assoc_args );
return new \WP_CLI\Formatter( $args );
}
/**
* Get default fields for formatter.
*
* Class that extends Papi_CLI_Command should override this method.
*
* @return null|string|array
*/
protected function get_default_format_fields() {
return null;
}
/**
* Get format args that will be passed into CLI Formatter.
*
* @param array $assoc_args Associative args from CLI
*
* @return array Formatter args
*/
protected function get_format_args( $assoc_args ) {
$format_args = array(
'fields' => $this->get_default_format_fields(),
'field' => null,
'format' => 'table',
);
if ( isset( $assoc_args['fields'] ) ) {
$format_args['fields'] = $assoc_args['fields'];
}
if ( isset( $assoc_args['field'] ) ) {
$format_args['field'] = $assoc_args['field'];
}
if ( ! empty( $assoc_args['format'] ) && in_array( $assoc_args['format'], array( 'count', 'ids', 'table', 'csv', 'json' ) ) ) {
$format_args['format'] = $assoc_args['format'];
}
return $format_args;
}
}
| Add papi cli command methods | Add papi cli command methods
| PHP | mit | wp-papi/papi,wp-papi/papi,ekandreas/papi,nlemoine/papi,isotopsweden/wp-papi,ekandreas/papi,isotopsweden/wp-papi,nlemoine/papi,nlemoine/papi,ekandreas/papi,wp-papi/papi,isotopsweden/wp-papi | php | ## Code Before:
<?php
/**
* Base class that must be extended by any Papi sub commands.
*/
class Papi_CLI_Command extends WP_CLI_Command {
}
## Instruction:
Add papi cli command methods
## Code After:
<?php
/**
* Base class that must be extended by any Papi sub commands.
*/
class Papi_CLI_Command extends WP_CLI_Command {
/**
* Get formatter object based on supplied arguments.
*
* @param array $assoc_args Associative args from CLI to determine formattin
*
* @return \WP_CLI\Formatter
*/
protected function get_formatter( $assoc_args ) {
$args = $this->get_format_args( $assoc_args );
return new \WP_CLI\Formatter( $args );
}
/**
* Get default fields for formatter.
*
* Class that extends Papi_CLI_Command should override this method.
*
* @return null|string|array
*/
protected function get_default_format_fields() {
return null;
}
/**
* Get format args that will be passed into CLI Formatter.
*
* @param array $assoc_args Associative args from CLI
*
* @return array Formatter args
*/
protected function get_format_args( $assoc_args ) {
$format_args = array(
'fields' => $this->get_default_format_fields(),
'field' => null,
'format' => 'table',
);
if ( isset( $assoc_args['fields'] ) ) {
$format_args['fields'] = $assoc_args['fields'];
}
if ( isset( $assoc_args['field'] ) ) {
$format_args['field'] = $assoc_args['field'];
}
if ( ! empty( $assoc_args['format'] ) && in_array( $assoc_args['format'], array( 'count', 'ids', 'table', 'csv', 'json' ) ) ) {
$format_args['format'] = $assoc_args['format'];
}
return $format_args;
}
}
| <?php
/**
* Base class that must be extended by any Papi sub commands.
*/
class Papi_CLI_Command extends WP_CLI_Command {
+ /**
+ * Get formatter object based on supplied arguments.
+ *
+ * @param array $assoc_args Associative args from CLI to determine formattin
+ *
+ * @return \WP_CLI\Formatter
+ */
+ protected function get_formatter( $assoc_args ) {
+ $args = $this->get_format_args( $assoc_args );
+ return new \WP_CLI\Formatter( $args );
+ }
+
+ /**
+ * Get default fields for formatter.
+ *
+ * Class that extends Papi_CLI_Command should override this method.
+ *
+ * @return null|string|array
+ */
+ protected function get_default_format_fields() {
+ return null;
+ }
+
+ /**
+ * Get format args that will be passed into CLI Formatter.
+ *
+ * @param array $assoc_args Associative args from CLI
+ *
+ * @return array Formatter args
+ */
+ protected function get_format_args( $assoc_args ) {
+ $format_args = array(
+ 'fields' => $this->get_default_format_fields(),
+ 'field' => null,
+ 'format' => 'table',
+ );
+
+ if ( isset( $assoc_args['fields'] ) ) {
+ $format_args['fields'] = $assoc_args['fields'];
+ }
+
+ if ( isset( $assoc_args['field'] ) ) {
+ $format_args['field'] = $assoc_args['field'];
+ }
+
+ if ( ! empty( $assoc_args['format'] ) && in_array( $assoc_args['format'], array( 'count', 'ids', 'table', 'csv', 'json' ) ) ) {
+ $format_args['format'] = $assoc_args['format'];
+ }
+
+ return $format_args;
+ }
} | 51 | 6.375 | 51 | 0 |
ee358aa9c1eef83b9cd0a74be002f6da171d4ce9 | unimplemented.cc | unimplemented.cc | /*
* Copyright (C) 2015 Cloudius Systems, Ltd.
*/
#include <unordered_map>
#include "unimplemented.hh"
#include "core/sstring.hh"
#include "core/enum.hh"
namespace unimplemented {
static std::unordered_map<cause, bool> _warnings;
std::ostream& operator<<(std::ostream& out, cause c) {
switch(c) {
case cause::INDEXES: return out << "INDEXES";
case cause::LWT: return out << "LWT";
case cause::PAGING: return out << "PAGING";
case cause::AUTH: return out << "AUTH";
case cause::PERMISSIONS: return out << "PERMISSIONS";
case cause::TRIGGERS: return out << "TRIGGERS";
case cause::COLLECTIONS: return out << "COLLECTIONS";
case cause::COUNTERS: return out << "COUNTERS";
case cause::METRICS: return out << "METRICS";
case cause::COMPACT_TABLES: return out << "COMPACT_TABLES";
}
assert(0);
}
void warn(cause c) {
auto i = _warnings.find(c);
if (i == _warnings.end()) {
_warnings.insert({c, true});
std::cerr << "WARNING: Not implemented: " << c << std::endl;
}
}
void fail(cause c) {
throw std::runtime_error(sprint("Not implemented: %s", c));
}
}
| /*
* Copyright (C) 2015 Cloudius Systems, Ltd.
*/
#include <unordered_map>
#include "unimplemented.hh"
#include "core/sstring.hh"
#include "core/enum.hh"
namespace unimplemented {
static thread_local std::unordered_map<cause, bool> _warnings;
std::ostream& operator<<(std::ostream& out, cause c) {
switch(c) {
case cause::INDEXES: return out << "INDEXES";
case cause::LWT: return out << "LWT";
case cause::PAGING: return out << "PAGING";
case cause::AUTH: return out << "AUTH";
case cause::PERMISSIONS: return out << "PERMISSIONS";
case cause::TRIGGERS: return out << "TRIGGERS";
case cause::COLLECTIONS: return out << "COLLECTIONS";
case cause::COUNTERS: return out << "COUNTERS";
case cause::METRICS: return out << "METRICS";
case cause::COMPACT_TABLES: return out << "COMPACT_TABLES";
}
assert(0);
}
void warn(cause c) {
auto i = _warnings.find(c);
if (i == _warnings.end()) {
_warnings.insert({c, true});
std::cerr << "WARNING: Not implemented: " << c << std::endl;
}
}
void fail(cause c) {
throw std::runtime_error(sprint("Not implemented: %s", c));
}
}
| Fix warnings map to be thread-local | Fix warnings map to be thread-local
The map is mutated so it should be thread-local. This will make the
warnings printed once per core, but I guess it's not a big deal.
| C++ | agpl-3.0 | rluta/scylla,dwdm/scylla,kangkot/scylla,capturePointer/scylla,justintung/scylla,scylladb/scylla,shaunstanislaus/scylla,glommer/scylla,kjniemi/scylla,phonkee/scylla,acbellini/scylla,eklitzke/scylla,wildinto/scylla,victorbriz/scylla,gwicke/scylla,shaunstanislaus/scylla,victorbriz/scylla,avikivity/scylla,capturePointer/scylla,linearregression/scylla,dwdm/scylla,duarten/scylla,scylladb/scylla,duarten/scylla,respu/scylla,guiquanz/scylla,victorbriz/scylla,guiquanz/scylla,senseb/scylla,bowlofstew/scylla,capturePointer/scylla,scylladb/scylla,respu/scylla,aruanruan/scylla,rentongzhang/scylla,glommer/scylla,bowlofstew/scylla,stamhe/scylla,kjniemi/scylla,rentongzhang/scylla,justintung/scylla,guiquanz/scylla,aruanruan/scylla,tempbottle/scylla,asias/scylla,kangkot/scylla,scylladb/scylla,eklitzke/scylla,justintung/scylla,rluta/scylla,kjniemi/scylla,kangkot/scylla,raphaelsc/scylla,acbellini/scylla,raphaelsc/scylla,asias/scylla,avikivity/scylla,bowlofstew/scylla,dwdm/scylla,gwicke/scylla,respu/scylla,wildinto/scylla,stamhe/scylla,asias/scylla,shaunstanislaus/scylla,glommer/scylla,linearregression/scylla,tempbottle/scylla,raphaelsc/scylla,phonkee/scylla,rentongzhang/scylla,eklitzke/scylla,tempbottle/scylla,senseb/scylla,phonkee/scylla,wildinto/scylla,aruanruan/scylla,rluta/scylla,acbellini/scylla,duarten/scylla,stamhe/scylla,avikivity/scylla,linearregression/scylla,gwicke/scylla,senseb/scylla | c++ | ## Code Before:
/*
* Copyright (C) 2015 Cloudius Systems, Ltd.
*/
#include <unordered_map>
#include "unimplemented.hh"
#include "core/sstring.hh"
#include "core/enum.hh"
namespace unimplemented {
static std::unordered_map<cause, bool> _warnings;
std::ostream& operator<<(std::ostream& out, cause c) {
switch(c) {
case cause::INDEXES: return out << "INDEXES";
case cause::LWT: return out << "LWT";
case cause::PAGING: return out << "PAGING";
case cause::AUTH: return out << "AUTH";
case cause::PERMISSIONS: return out << "PERMISSIONS";
case cause::TRIGGERS: return out << "TRIGGERS";
case cause::COLLECTIONS: return out << "COLLECTIONS";
case cause::COUNTERS: return out << "COUNTERS";
case cause::METRICS: return out << "METRICS";
case cause::COMPACT_TABLES: return out << "COMPACT_TABLES";
}
assert(0);
}
void warn(cause c) {
auto i = _warnings.find(c);
if (i == _warnings.end()) {
_warnings.insert({c, true});
std::cerr << "WARNING: Not implemented: " << c << std::endl;
}
}
void fail(cause c) {
throw std::runtime_error(sprint("Not implemented: %s", c));
}
}
## Instruction:
Fix warnings map to be thread-local
The map is mutated so it should be thread-local. This will make the
warnings printed once per core, but I guess it's not a big deal.
## Code After:
/*
* Copyright (C) 2015 Cloudius Systems, Ltd.
*/
#include <unordered_map>
#include "unimplemented.hh"
#include "core/sstring.hh"
#include "core/enum.hh"
namespace unimplemented {
static thread_local std::unordered_map<cause, bool> _warnings;
std::ostream& operator<<(std::ostream& out, cause c) {
switch(c) {
case cause::INDEXES: return out << "INDEXES";
case cause::LWT: return out << "LWT";
case cause::PAGING: return out << "PAGING";
case cause::AUTH: return out << "AUTH";
case cause::PERMISSIONS: return out << "PERMISSIONS";
case cause::TRIGGERS: return out << "TRIGGERS";
case cause::COLLECTIONS: return out << "COLLECTIONS";
case cause::COUNTERS: return out << "COUNTERS";
case cause::METRICS: return out << "METRICS";
case cause::COMPACT_TABLES: return out << "COMPACT_TABLES";
}
assert(0);
}
void warn(cause c) {
auto i = _warnings.find(c);
if (i == _warnings.end()) {
_warnings.insert({c, true});
std::cerr << "WARNING: Not implemented: " << c << std::endl;
}
}
void fail(cause c) {
throw std::runtime_error(sprint("Not implemented: %s", c));
}
}
| /*
* Copyright (C) 2015 Cloudius Systems, Ltd.
*/
#include <unordered_map>
#include "unimplemented.hh"
#include "core/sstring.hh"
#include "core/enum.hh"
namespace unimplemented {
- static std::unordered_map<cause, bool> _warnings;
+ static thread_local std::unordered_map<cause, bool> _warnings;
? +++++++++++++
std::ostream& operator<<(std::ostream& out, cause c) {
switch(c) {
case cause::INDEXES: return out << "INDEXES";
case cause::LWT: return out << "LWT";
case cause::PAGING: return out << "PAGING";
case cause::AUTH: return out << "AUTH";
case cause::PERMISSIONS: return out << "PERMISSIONS";
case cause::TRIGGERS: return out << "TRIGGERS";
case cause::COLLECTIONS: return out << "COLLECTIONS";
case cause::COUNTERS: return out << "COUNTERS";
case cause::METRICS: return out << "METRICS";
case cause::COMPACT_TABLES: return out << "COMPACT_TABLES";
}
assert(0);
}
void warn(cause c) {
auto i = _warnings.find(c);
if (i == _warnings.end()) {
_warnings.insert({c, true});
std::cerr << "WARNING: Not implemented: " << c << std::endl;
}
}
void fail(cause c) {
throw std::runtime_error(sprint("Not implemented: %s", c));
}
} | 2 | 0.047619 | 1 | 1 |
b3004d1e82dd831cdb9a98df51ec7f769b99c3aa | composer.json | composer.json | {
"name": "gamez/psr-testlogger",
"description": "PSR-3 compliant test and mock loggers to be used in Unit Tests.",
"keywords": ["psr", "psr-3", "log", "test", "mock", "phpunit"],
"type": "library",
"license": "MIT",
"authors": [
{"name": "Jérôme Gamez", "email": "jerome@gamez.name"}
],
"require-dev": {
"psr/log": "^1.0",
"phpunit/phpunit": "^3.0|^4.0|^5.0"
},
"autoload": {
"psr-4": {
"Gamez\\Psr\\Log\\": "src"
}
},
"autoload-dev": {
"psr-4": {
"Gamez\\Psr\\Log\\": "tests"
}
}
}
| {
"name": "gamez/psr-testlogger",
"description": "PSR-3 compliant test and mock loggers to be used in Unit Tests.",
"keywords": ["psr", "psr-3", "log", "test", "mock", "phpunit"],
"type": "library",
"license": "MIT",
"authors": [
{"name": "Jérôme Gamez", "email": "jerome@gamez.name"}
],
"require": {
"psr/log": "^1.0"
},
"require-dev": {
"phpunit/phpunit": "^3.0|^4.0|^5.0"
},
"autoload": {
"psr-4": {
"Gamez\\Psr\\Log\\": "src"
}
},
"autoload-dev": {
"psr-4": {
"Gamez\\Psr\\Log\\": "tests"
}
}
}
| Move psr/log to actual requirements | Move psr/log to actual requirements
| JSON | mit | jeromegamez/php-psr-testlogger | json | ## Code Before:
{
"name": "gamez/psr-testlogger",
"description": "PSR-3 compliant test and mock loggers to be used in Unit Tests.",
"keywords": ["psr", "psr-3", "log", "test", "mock", "phpunit"],
"type": "library",
"license": "MIT",
"authors": [
{"name": "Jérôme Gamez", "email": "jerome@gamez.name"}
],
"require-dev": {
"psr/log": "^1.0",
"phpunit/phpunit": "^3.0|^4.0|^5.0"
},
"autoload": {
"psr-4": {
"Gamez\\Psr\\Log\\": "src"
}
},
"autoload-dev": {
"psr-4": {
"Gamez\\Psr\\Log\\": "tests"
}
}
}
## Instruction:
Move psr/log to actual requirements
## Code After:
{
"name": "gamez/psr-testlogger",
"description": "PSR-3 compliant test and mock loggers to be used in Unit Tests.",
"keywords": ["psr", "psr-3", "log", "test", "mock", "phpunit"],
"type": "library",
"license": "MIT",
"authors": [
{"name": "Jérôme Gamez", "email": "jerome@gamez.name"}
],
"require": {
"psr/log": "^1.0"
},
"require-dev": {
"phpunit/phpunit": "^3.0|^4.0|^5.0"
},
"autoload": {
"psr-4": {
"Gamez\\Psr\\Log\\": "src"
}
},
"autoload-dev": {
"psr-4": {
"Gamez\\Psr\\Log\\": "tests"
}
}
}
| {
"name": "gamez/psr-testlogger",
"description": "PSR-3 compliant test and mock loggers to be used in Unit Tests.",
"keywords": ["psr", "psr-3", "log", "test", "mock", "phpunit"],
"type": "library",
"license": "MIT",
"authors": [
{"name": "Jérôme Gamez", "email": "jerome@gamez.name"}
],
+ "require": {
+ "psr/log": "^1.0"
+ },
"require-dev": {
- "psr/log": "^1.0",
"phpunit/phpunit": "^3.0|^4.0|^5.0"
},
"autoload": {
"psr-4": {
"Gamez\\Psr\\Log\\": "src"
}
},
"autoload-dev": {
"psr-4": {
"Gamez\\Psr\\Log\\": "tests"
}
}
} | 4 | 0.166667 | 3 | 1 |
629ec26ea3d283ee78e71241167a17e68d8b0017 | frontend/spree_frontend.gemspec | frontend/spree_frontend.gemspec | require_relative '../core/lib/spree/core/version.rb'
Gem::Specification.new do |s|
s.platform = Gem::Platform::RUBY
s.name = 'spree_frontend'
s.version = Spree.version
s.summary = 'Frontend e-commerce functionality for the Spree project.'
s.description = s.summary
s.required_ruby_version = '>= 2.5.0'
s.author = 'Sean Schofield'
s.email = 'sean@spreecommerce.com'
s.homepage = 'http://spreecommerce.org'
s.license = 'BSD-3-Clause'
s.files = `git ls-files`.split("\n").reject { |f| f.match(/^spec/) && !f.match(/^spec\/fixtures/) }
s.require_path = 'lib'
s.requirements << 'none'
s.add_dependency 'spree_api', s.version
s.add_dependency 'spree_core', s.version
s.add_dependency 'bootstrap', '~> 4.3.1'
s.add_dependency 'glyphicons', '~> 1.0.2'
s.add_dependency 'canonical-rails', '~> 0.2.5'
s.add_dependency 'jquery-rails', '~> 4.3'
s.add_development_dependency 'capybara-accessible'
end
| require_relative '../core/lib/spree/core/version.rb'
Gem::Specification.new do |s|
s.platform = Gem::Platform::RUBY
s.name = 'spree_frontend'
s.version = Spree.version
s.summary = 'Frontend e-commerce functionality for the Spree project.'
s.description = s.summary
s.required_ruby_version = '>= 2.5.0'
s.author = 'Sean Schofield'
s.email = 'sean@spreecommerce.com'
s.homepage = 'http://spreecommerce.org'
s.license = 'BSD-3-Clause'
s.files = `git ls-files`.split("\n").reject { |f| f.match(/^spec/) && !f.match(/^spec\/fixtures/) }
s.require_path = 'lib'
s.requirements << 'none'
s.add_dependency 'spree_api', s.version
s.add_dependency 'spree_core', s.version
s.add_dependency 'bootstrap', '~> 4.3.1'
s.add_dependency 'glyphicons', '~> 1.0.2'
s.add_dependency 'canonical-rails', '~> 0.2.5'
s.add_dependency 'inline_svg', '~> 1.5'
s.add_dependency 'jquery-rails', '~> 4.3'
s.add_development_dependency 'capybara-accessible'
end
| Add inline_svg as a Spree dependency | Add inline_svg as a Spree dependency
| Ruby | bsd-3-clause | ayb/spree,ayb/spree,imella/spree,imella/spree,ayb/spree,ayb/spree,imella/spree | ruby | ## Code Before:
require_relative '../core/lib/spree/core/version.rb'
Gem::Specification.new do |s|
s.platform = Gem::Platform::RUBY
s.name = 'spree_frontend'
s.version = Spree.version
s.summary = 'Frontend e-commerce functionality for the Spree project.'
s.description = s.summary
s.required_ruby_version = '>= 2.5.0'
s.author = 'Sean Schofield'
s.email = 'sean@spreecommerce.com'
s.homepage = 'http://spreecommerce.org'
s.license = 'BSD-3-Clause'
s.files = `git ls-files`.split("\n").reject { |f| f.match(/^spec/) && !f.match(/^spec\/fixtures/) }
s.require_path = 'lib'
s.requirements << 'none'
s.add_dependency 'spree_api', s.version
s.add_dependency 'spree_core', s.version
s.add_dependency 'bootstrap', '~> 4.3.1'
s.add_dependency 'glyphicons', '~> 1.0.2'
s.add_dependency 'canonical-rails', '~> 0.2.5'
s.add_dependency 'jquery-rails', '~> 4.3'
s.add_development_dependency 'capybara-accessible'
end
## Instruction:
Add inline_svg as a Spree dependency
## Code After:
require_relative '../core/lib/spree/core/version.rb'
Gem::Specification.new do |s|
s.platform = Gem::Platform::RUBY
s.name = 'spree_frontend'
s.version = Spree.version
s.summary = 'Frontend e-commerce functionality for the Spree project.'
s.description = s.summary
s.required_ruby_version = '>= 2.5.0'
s.author = 'Sean Schofield'
s.email = 'sean@spreecommerce.com'
s.homepage = 'http://spreecommerce.org'
s.license = 'BSD-3-Clause'
s.files = `git ls-files`.split("\n").reject { |f| f.match(/^spec/) && !f.match(/^spec\/fixtures/) }
s.require_path = 'lib'
s.requirements << 'none'
s.add_dependency 'spree_api', s.version
s.add_dependency 'spree_core', s.version
s.add_dependency 'bootstrap', '~> 4.3.1'
s.add_dependency 'glyphicons', '~> 1.0.2'
s.add_dependency 'canonical-rails', '~> 0.2.5'
s.add_dependency 'inline_svg', '~> 1.5'
s.add_dependency 'jquery-rails', '~> 4.3'
s.add_development_dependency 'capybara-accessible'
end
| require_relative '../core/lib/spree/core/version.rb'
Gem::Specification.new do |s|
s.platform = Gem::Platform::RUBY
s.name = 'spree_frontend'
s.version = Spree.version
s.summary = 'Frontend e-commerce functionality for the Spree project.'
s.description = s.summary
s.required_ruby_version = '>= 2.5.0'
s.author = 'Sean Schofield'
s.email = 'sean@spreecommerce.com'
s.homepage = 'http://spreecommerce.org'
s.license = 'BSD-3-Clause'
s.files = `git ls-files`.split("\n").reject { |f| f.match(/^spec/) && !f.match(/^spec\/fixtures/) }
s.require_path = 'lib'
s.requirements << 'none'
s.add_dependency 'spree_api', s.version
s.add_dependency 'spree_core', s.version
s.add_dependency 'bootstrap', '~> 4.3.1'
s.add_dependency 'glyphicons', '~> 1.0.2'
s.add_dependency 'canonical-rails', '~> 0.2.5'
+ s.add_dependency 'inline_svg', '~> 1.5'
s.add_dependency 'jquery-rails', '~> 4.3'
s.add_development_dependency 'capybara-accessible'
end | 1 | 0.033333 | 1 | 0 |
ed8f11009ea75ae6412297b0bd90e89820aefb32 | .travis.yml | .travis.yml | language: node_js
node_js:
- 0.10
after_script: "npm install coveralls@2.10.0 && cat ./coverage/**/lcov.info | coveralls" | language: node_js
node_js:
- 0.10
before_install:
- "export DISPLAY=:99.0"
- "sh -e /etc/init.d/xvfb start"
after_script: "npm install coveralls@2.10.0 && cat ./coverage/**/lcov.info | coveralls" | Update Travis config to enable Firefox. | Update Travis config to enable Firefox.
| YAML | mit | Webini/angular-clipboard,omichelsen/angular-clipboard,Webini/angular-clipboard | yaml | ## Code Before:
language: node_js
node_js:
- 0.10
after_script: "npm install coveralls@2.10.0 && cat ./coverage/**/lcov.info | coveralls"
## Instruction:
Update Travis config to enable Firefox.
## Code After:
language: node_js
node_js:
- 0.10
before_install:
- "export DISPLAY=:99.0"
- "sh -e /etc/init.d/xvfb start"
after_script: "npm install coveralls@2.10.0 && cat ./coverage/**/lcov.info | coveralls" | language: node_js
node_js:
- 0.10
+ before_install:
+ - "export DISPLAY=:99.0"
+ - "sh -e /etc/init.d/xvfb start"
after_script: "npm install coveralls@2.10.0 && cat ./coverage/**/lcov.info | coveralls" | 3 | 0.75 | 3 | 0 |
bc6994459304ed5af32a91abe2e4855edb52f7c7 | client/package.json | client/package.json | {
"devDependencies": {
"clean-css-brunch": "2.0.0",
"coffee-script-brunch": "2.1.0",
"cozy-data-system-dev": "2.5.7",
"css-brunch": "2.6.1",
"digest-brunch": "1.6.0",
"jade-brunch": "1.8.2",
"javascript-brunch": "2.0.0",
"json-brunch": "1.5.4",
"stylus-brunch": "2.8.0"
}
}
| {
"devDependencies": {
"clean-css-brunch": "1.8.0",
"coffee-script-brunch": "1.8.3",
"css-brunch": "1.7.0",
"digest-brunch": "1.5.1",
"jade-brunch": "1.8.2",
"javascript-brunch": "1.8.0",
"json-brunch": "1.5.4",
"stylus-brunch": "1.8.1"
}
}
| Fix build (downgrade client dependencies) | Fix build (downgrade client dependencies)
| JSON | agpl-3.0 | cozy/cozy-calendar,cozy/cozy-calendar | json | ## Code Before:
{
"devDependencies": {
"clean-css-brunch": "2.0.0",
"coffee-script-brunch": "2.1.0",
"cozy-data-system-dev": "2.5.7",
"css-brunch": "2.6.1",
"digest-brunch": "1.6.0",
"jade-brunch": "1.8.2",
"javascript-brunch": "2.0.0",
"json-brunch": "1.5.4",
"stylus-brunch": "2.8.0"
}
}
## Instruction:
Fix build (downgrade client dependencies)
## Code After:
{
"devDependencies": {
"clean-css-brunch": "1.8.0",
"coffee-script-brunch": "1.8.3",
"css-brunch": "1.7.0",
"digest-brunch": "1.5.1",
"jade-brunch": "1.8.2",
"javascript-brunch": "1.8.0",
"json-brunch": "1.5.4",
"stylus-brunch": "1.8.1"
}
}
| {
"devDependencies": {
- "clean-css-brunch": "2.0.0",
? ^ ^
+ "clean-css-brunch": "1.8.0",
? ^ ^
- "coffee-script-brunch": "2.1.0",
? -- ^
+ "coffee-script-brunch": "1.8.3",
? ^^^
- "cozy-data-system-dev": "2.5.7",
- "css-brunch": "2.6.1",
? ^ ^ ^
+ "css-brunch": "1.7.0",
? ^ ^ ^
- "digest-brunch": "1.6.0",
? ^ ^
+ "digest-brunch": "1.5.1",
? ^ ^
"jade-brunch": "1.8.2",
- "javascript-brunch": "2.0.0",
? ^ ^
+ "javascript-brunch": "1.8.0",
? ^ ^
"json-brunch": "1.5.4",
- "stylus-brunch": "2.8.0"
? ^ ^
+ "stylus-brunch": "1.8.1"
? ^ ^
}
} | 13 | 1 | 6 | 7 |
d240acd6dd375f81d0c313c6ad1e850fbfaf945f | README.md | README.md |
(details coming soon)
| [](https://travis-ci.org/CoreAPM/.NET)
(details coming soon)
| Move Travis badge to new line | Move Travis badge to new line | Markdown | mit | CoreAPM/DotNetAgent | markdown | ## Code Before:
(details coming soon)
## Instruction:
Move Travis badge to new line
## Code After:
[](https://travis-ci.org/CoreAPM/.NET)
(details coming soon)
| + [](https://travis-ci.org/CoreAPM/.NET)
(details coming soon) | 1 | 0.5 | 1 | 0 |
7853c0251d3a057819770e0bb5cd8d30177faacb | .gitlab-ci.yml | .gitlab-ci.yml | image: "redoxos/redoxer"
stages:
- build
- test
cache:
paths:
- target/
build:linux:stable:
stage: build
script:
- rustup update stable
- cargo +stable build --verbose
build:linux:
stage: build
script: cargo +nightly build --verbose
build:redox:
stage: build
script: redoxer build --verbose
test:linux:stable:
stage: test
dependencies:
- build:linux:stable
script: cargo +stable test --verbose
test:linux:
stage: test
dependencies:
- build:linux
script: cargo +nightly test --verbose
test:redox:
stage: test
dependencies:
- build:redox
script: redoxer test --verbose
| image: "redoxos/redoxer"
stages:
- build
- test
cache:
paths:
- target/
build:linux:stable:
stage: build
script:
- cargo +stable build --verbose
build:linux:
stage: build
script: cargo +nightly build --verbose
build:redox:
stage: build
script: redoxer build --verbose
test:linux:stable:
stage: test
dependencies:
- build:linux:stable
script:
- rustup update stable
- cargo +stable test --verbose
test:linux:
stage: test
dependencies:
- build:linux
script: cargo +nightly test --verbose
test:redox:
stage: test
dependencies:
- build:redox
script: redoxer test --verbose
| Install stable toolchain for stable test | Install stable toolchain for stable test
| YAML | mit | ticki/termion,Ticki/libterm | yaml | ## Code Before:
image: "redoxos/redoxer"
stages:
- build
- test
cache:
paths:
- target/
build:linux:stable:
stage: build
script:
- rustup update stable
- cargo +stable build --verbose
build:linux:
stage: build
script: cargo +nightly build --verbose
build:redox:
stage: build
script: redoxer build --verbose
test:linux:stable:
stage: test
dependencies:
- build:linux:stable
script: cargo +stable test --verbose
test:linux:
stage: test
dependencies:
- build:linux
script: cargo +nightly test --verbose
test:redox:
stage: test
dependencies:
- build:redox
script: redoxer test --verbose
## Instruction:
Install stable toolchain for stable test
## Code After:
image: "redoxos/redoxer"
stages:
- build
- test
cache:
paths:
- target/
build:linux:stable:
stage: build
script:
- cargo +stable build --verbose
build:linux:
stage: build
script: cargo +nightly build --verbose
build:redox:
stage: build
script: redoxer build --verbose
test:linux:stable:
stage: test
dependencies:
- build:linux:stable
script:
- rustup update stable
- cargo +stable test --verbose
test:linux:
stage: test
dependencies:
- build:linux
script: cargo +nightly test --verbose
test:redox:
stage: test
dependencies:
- build:redox
script: redoxer test --verbose
| image: "redoxos/redoxer"
stages:
- build
- test
cache:
paths:
- target/
build:linux:stable:
stage: build
script:
- - rustup update stable
- cargo +stable build --verbose
build:linux:
stage: build
script: cargo +nightly build --verbose
build:redox:
stage: build
script: redoxer build --verbose
test:linux:stable:
stage: test
dependencies:
- build:linux:stable
+ script:
+ - rustup update stable
- script: cargo +stable test --verbose
? ^^^^^^^
+ - cargo +stable test --verbose
? ^^^^^
test:linux:
stage: test
dependencies:
- build:linux
script: cargo +nightly test --verbose
test:redox:
stage: test
dependencies:
- build:redox
script: redoxer test --verbose | 5 | 0.121951 | 3 | 2 |
7b7a37c8054ffc88055b8190b16dcad0d04a8839 | setup.cfg | setup.cfg | [aliases]
release = check -r -s register sdist bdist_wheel upload
| [aliases]
release = check -r -s register -r pypi sdist bdist_wheel upload -r pypi
release-test = check -r -s register -r pypitest sdist bdist_wheel upload -r pypitest
| Update aliases for PyPI and TestPyPI | Update aliases for PyPI and TestPyPI
See also: http://peterdowns.com/posts/first-time-with-pypi.html
| INI | bsd-3-clause | raimon49/pypro2-guestbook-webapp,raimon49/pypro2-guestbook-webapp | ini | ## Code Before:
[aliases]
release = check -r -s register sdist bdist_wheel upload
## Instruction:
Update aliases for PyPI and TestPyPI
See also: http://peterdowns.com/posts/first-time-with-pypi.html
## Code After:
[aliases]
release = check -r -s register -r pypi sdist bdist_wheel upload -r pypi
release-test = check -r -s register -r pypitest sdist bdist_wheel upload -r pypitest
| [aliases]
- release = check -r -s register sdist bdist_wheel upload
+ release = check -r -s register -r pypi sdist bdist_wheel upload -r pypi
? ++++++++ ++++++++
+ release-test = check -r -s register -r pypitest sdist bdist_wheel upload -r pypitest
| 3 | 1 | 2 | 1 |
1794c0dcf4b05ee1996db6ffd4c1cbf3c8502f1f | src/components/App/index.js | src/components/App/index.js | import React, { Component } from 'react';
import UserInput from '../common/UserInput';
export default class App extends Component {
constructor() {
super();
this.state = { count: 0 };
}
onClickAddOne() {
console.log("clicked");
const new_count = this.state.count + 1;
this.setState({ count: new_count });
}
render() {
return (
<div style={{marginLeft: '20px'}}>
<h1 style={{marginTop: '30px'}}>My awesome app</h1>
<button onClick={this.onClickAddOne.bind(this)} style={{marginBottom: '10px'}}>Add One</button>
<UserInput placeholder="Input Box 1" value={this.state.value} onChange={(e) => this.setState({ value: e.target.value})} style={{display: 'block'}} />
<h1 style={{marginTop: '200px'}}>What's in the state?</h1>
<h2>Current Count: <span style={{color: 'red'}}>{this.state.count}</span></h2>
<h2>Input Box 1: <span style={{color: 'red'}}>{this.state.value}</span></h2>
</div>
);
}
}
| import React, { Component } from 'react';
import UserInput from '../common/UserInput';
export default class App extends Component {
constructor() {
super();
this.state = {
count: 0,
date: new Date()
};
this.tick = this.tick.bind(this);
}
componentDidMount() {
this.timerID = setInterval(
() => this.tick(),
1000
);
}
componentWillUnmount() {
clearInterval(this.timerID);
}
tick() {
this.setState({
date: new Date()
});
}
onClickAddOne() {
console.log("clicked");
const new_count = this.state.count + 1;
this.setState({ count: new_count });
}
render() {
return (
<div style={{marginLeft: '20px'}}>
<h1 style={{marginTop: '30px'}}>My awesome app</h1>
<button onClick={this.onClickAddOne.bind(this)} style={{marginBottom: '10px'}}>Add One</button>
<UserInput placeholder="Input Box 1" value={this.state.value} onChange={(e) => this.setState({ value: e.target.value})} style={{display: 'block'}} />
<h1 style={{marginTop: '200px'}}>What's in the state?</h1>
<h2>Current Count: <span style={{color: 'red'}}>{this.state.count}</span></h2>
<h2>Input Box 1: <span style={{color: 'red'}}>{this.state.value}</span></h2>
<h2>The time: <span style={{color: 'red'}}>{this.state.date.toLocaleTimeString()}</span></h2>
</div>
);
}
}
| Add lifecycle methods for updating/rendering date state variable | Add lifecycle methods for updating/rendering date state variable
| JavaScript | mit | mcrice123/simple-react-example,mcrice123/simple-react-example | javascript | ## Code Before:
import React, { Component } from 'react';
import UserInput from '../common/UserInput';
export default class App extends Component {
constructor() {
super();
this.state = { count: 0 };
}
onClickAddOne() {
console.log("clicked");
const new_count = this.state.count + 1;
this.setState({ count: new_count });
}
render() {
return (
<div style={{marginLeft: '20px'}}>
<h1 style={{marginTop: '30px'}}>My awesome app</h1>
<button onClick={this.onClickAddOne.bind(this)} style={{marginBottom: '10px'}}>Add One</button>
<UserInput placeholder="Input Box 1" value={this.state.value} onChange={(e) => this.setState({ value: e.target.value})} style={{display: 'block'}} />
<h1 style={{marginTop: '200px'}}>What's in the state?</h1>
<h2>Current Count: <span style={{color: 'red'}}>{this.state.count}</span></h2>
<h2>Input Box 1: <span style={{color: 'red'}}>{this.state.value}</span></h2>
</div>
);
}
}
## Instruction:
Add lifecycle methods for updating/rendering date state variable
## Code After:
import React, { Component } from 'react';
import UserInput from '../common/UserInput';
export default class App extends Component {
constructor() {
super();
this.state = {
count: 0,
date: new Date()
};
this.tick = this.tick.bind(this);
}
componentDidMount() {
this.timerID = setInterval(
() => this.tick(),
1000
);
}
componentWillUnmount() {
clearInterval(this.timerID);
}
tick() {
this.setState({
date: new Date()
});
}
onClickAddOne() {
console.log("clicked");
const new_count = this.state.count + 1;
this.setState({ count: new_count });
}
render() {
return (
<div style={{marginLeft: '20px'}}>
<h1 style={{marginTop: '30px'}}>My awesome app</h1>
<button onClick={this.onClickAddOne.bind(this)} style={{marginBottom: '10px'}}>Add One</button>
<UserInput placeholder="Input Box 1" value={this.state.value} onChange={(e) => this.setState({ value: e.target.value})} style={{display: 'block'}} />
<h1 style={{marginTop: '200px'}}>What's in the state?</h1>
<h2>Current Count: <span style={{color: 'red'}}>{this.state.count}</span></h2>
<h2>Input Box 1: <span style={{color: 'red'}}>{this.state.value}</span></h2>
<h2>The time: <span style={{color: 'red'}}>{this.state.date.toLocaleTimeString()}</span></h2>
</div>
);
}
}
| import React, { Component } from 'react';
import UserInput from '../common/UserInput';
export default class App extends Component {
constructor() {
super();
- this.state = { count: 0 };
? -----------
+ this.state = {
+ count: 0,
+ date: new Date()
+ };
+
+ this.tick = this.tick.bind(this);
+ }
+
+ componentDidMount() {
+ this.timerID = setInterval(
+ () => this.tick(),
+ 1000
+ );
+ }
+
+ componentWillUnmount() {
+ clearInterval(this.timerID);
+ }
+
+ tick() {
+ this.setState({
+ date: new Date()
+ });
}
onClickAddOne() {
console.log("clicked");
const new_count = this.state.count + 1;
this.setState({ count: new_count });
}
render() {
return (
<div style={{marginLeft: '20px'}}>
<h1 style={{marginTop: '30px'}}>My awesome app</h1>
<button onClick={this.onClickAddOne.bind(this)} style={{marginBottom: '10px'}}>Add One</button>
<UserInput placeholder="Input Box 1" value={this.state.value} onChange={(e) => this.setState({ value: e.target.value})} style={{display: 'block'}} />
<h1 style={{marginTop: '200px'}}>What's in the state?</h1>
<h2>Current Count: <span style={{color: 'red'}}>{this.state.count}</span></h2>
<h2>Input Box 1: <span style={{color: 'red'}}>{this.state.value}</span></h2>
-
+ <h2>The time: <span style={{color: 'red'}}>{this.state.date.toLocaleTimeString()}</span></h2>
</div>
);
}
} | 26 | 0.684211 | 24 | 2 |
6f451ee8cbb1ef603facf753f23bd9d4e68962f7 | webhooks/templates/webhooks/action.html | webhooks/templates/webhooks/action.html | {% extends "base.html" %}
{% block body_content %}
<h2>{{ webhooks }}</h2>
<p>Object: {{ webhooks.content_object }}</p>
<p>Triggered: {{ webhooks.triggered }}</p>
{% endblock %} | {% extends "base.html" %}
{% block body_content %}
<h2>Webhook</h2>
<p><strong>Target</strong> Object: {{ webhook.content_object }} ({{ webhook.content_type }})</p>
<p><strong>Action:</strong> {{ webhook.get_action_display }}</p>
<p><strong>Owner:</strong> {{ webhook.owner }}</p>
<p><strong>Filter:</strong> {{ webhook.filter }}</p>
<p><strong>HTTP Method:</strong> {{ webhook.get_method_display }}</p>
<p><strong>Triggered:</strong> {{ webhook.triggered }}</p>
{% endblock %} | Fix template having wrong varible name. Added more information. | Fix template having wrong varible name. Added more information.
| HTML | bsd-3-clause | voltgrid/django-webhooks | html | ## Code Before:
{% extends "base.html" %}
{% block body_content %}
<h2>{{ webhooks }}</h2>
<p>Object: {{ webhooks.content_object }}</p>
<p>Triggered: {{ webhooks.triggered }}</p>
{% endblock %}
## Instruction:
Fix template having wrong varible name. Added more information.
## Code After:
{% extends "base.html" %}
{% block body_content %}
<h2>Webhook</h2>
<p><strong>Target</strong> Object: {{ webhook.content_object }} ({{ webhook.content_type }})</p>
<p><strong>Action:</strong> {{ webhook.get_action_display }}</p>
<p><strong>Owner:</strong> {{ webhook.owner }}</p>
<p><strong>Filter:</strong> {{ webhook.filter }}</p>
<p><strong>HTTP Method:</strong> {{ webhook.get_method_display }}</p>
<p><strong>Triggered:</strong> {{ webhook.triggered }}</p>
{% endblock %} | {% extends "base.html" %}
{% block body_content %}
- <h2>{{ webhooks }}</h2>
? ^^^^ ----
+ <h2>Webhook</h2>
? ^
- <p>Object: {{ webhooks.content_object }}</p>
+
+ <p><strong>Target</strong> Object: {{ webhook.content_object }} ({{ webhook.content_type }})</p>
+ <p><strong>Action:</strong> {{ webhook.get_action_display }}</p>
+ <p><strong>Owner:</strong> {{ webhook.owner }}</p>
+ <p><strong>Filter:</strong> {{ webhook.filter }}</p>
+ <p><strong>HTTP Method:</strong> {{ webhook.get_method_display }}</p>
- <p>Triggered: {{ webhooks.triggered }}</p>
? -
+ <p><strong>Triggered:</strong> {{ webhook.triggered }}</p>
? ++++++++ +++++++++
+
{% endblock %} | 12 | 1.714286 | 9 | 3 |
7d3b4684262f0c3540dd2ce29302caa9cdc3de31 | circle.yml | circle.yml | machine:
services:
- docker
dependencies:
cache_directories:
- "~/docker"
- .bundle
- node_modules
- public/assets
override:
- if [[ -e ~/docker/image.tar ]]; then docker load -i ~/docker/image.tar; fi
- sudo pip install --upgrade docker-compose==1.5.2
- docker pull ultrayoshi/ruby-node-phantomjs:2.1.1
- docker pull postgres
- docker pull redis
- cp .env.example .env
- docker-compose build
- docker-compose run app bundle install
- docker-compose run app npm install
- docker-compose run app webpack
- mkdir -p ~/docker; docker save ultrayoshi/ruby-node-phantomjs:2.1.1 postgres redis > ~/docker/image.tar
- docker-compose run app rake db:setup
- docker-compose run -e RAILS_ENV=test app bundle exec rake assets:precompile
database:
override:
- echo 'done'
test:
override:
- docker-compose run -e CI=true -e CI_PULL_REQUEST=$CI_PULL_REQUEST -e CI_PULL_REQUESTS=$CI_PULL_REQUESTS -e COVERALLS_REPO_TOKEN=$COVERALLS_REPO_TOKEN -e COVERALLS_PARALLEL=true app bundle exec rspec:
parallel: true
files:
- spec/**/*_spec.rb
| machine:
services:
- docker
dependencies:
cache_directories:
- "~/docker"
- .bundle
- node_modules
- public/assets
override:
- if [[ -e ~/docker/image.tar ]]; then docker load -i ~/docker/image.tar; fi
- sudo pip install --upgrade docker-compose==1.5.2
- docker pull ultrayoshi/ruby-node-phantomjs:2.1.1
- docker pull postgres
- docker pull redis
- cp .env.example .env
- docker-compose build
- docker-compose run app bundle install
- docker-compose run app npm install
- docker-compose run app webpack
- mkdir -p ~/docker; docker save ultrayoshi/ruby-node-phantomjs:2.1.1 postgres redis > ~/docker/image.tar
- docker-compose run app rake db:setup
- docker-compose run -e RAILS_ENV=test app bundle exec rake assets:precompile
database:
override:
- echo 'done'
test:
override:
- docker-compose run -e CI=true -e CI_PULL_REQUEST=$CI_PULL_REQUEST -e CI_PULL_REQUESTS=$CI_PULL_REQUESTS -e COVERALLS_REPO_TOKEN=$COVERALLS_REPO_TOKEN -e COVERALLS_PARALLEL=true app bundle exec rspec:
parallel: true
files:
- spec/**/*_spec.rb
- docker-compose run app npm test:
parallel: true
files:
- app/frontend/**/*.test.js
| Add CircleCI configuration for npm test | Add CircleCI configuration for npm test
| YAML | agpl-3.0 | AjuntamentdeBarcelona/barcelona-participa,AjuntamentdeBarcelona/barcelona-participa,AjuntamentdeBarcelona/barcelona-participa,AjuntamentdeBarcelona/decidim.barcelona,AjuntamentdeBarcelona/decidim.barcelona-legacy,AjuntamentdeBarcelona/decidim.barcelona-legacy,AjuntamentdeBarcelona/decidimbcn,AjuntamentdeBarcelona/decidim.barcelona-legacy,AjuntamentdeBarcelona/decidimbcn,AjuntamentdeBarcelona/decidim.barcelona,AjuntamentdeBarcelona/decidim.barcelona,AjuntamentdeBarcelona/decidim.barcelona,AjuntamentdeBarcelona/decidimbcn,AjuntamentdeBarcelona/decidim.barcelona-legacy | yaml | ## Code Before:
machine:
services:
- docker
dependencies:
cache_directories:
- "~/docker"
- .bundle
- node_modules
- public/assets
override:
- if [[ -e ~/docker/image.tar ]]; then docker load -i ~/docker/image.tar; fi
- sudo pip install --upgrade docker-compose==1.5.2
- docker pull ultrayoshi/ruby-node-phantomjs:2.1.1
- docker pull postgres
- docker pull redis
- cp .env.example .env
- docker-compose build
- docker-compose run app bundle install
- docker-compose run app npm install
- docker-compose run app webpack
- mkdir -p ~/docker; docker save ultrayoshi/ruby-node-phantomjs:2.1.1 postgres redis > ~/docker/image.tar
- docker-compose run app rake db:setup
- docker-compose run -e RAILS_ENV=test app bundle exec rake assets:precompile
database:
override:
- echo 'done'
test:
override:
- docker-compose run -e CI=true -e CI_PULL_REQUEST=$CI_PULL_REQUEST -e CI_PULL_REQUESTS=$CI_PULL_REQUESTS -e COVERALLS_REPO_TOKEN=$COVERALLS_REPO_TOKEN -e COVERALLS_PARALLEL=true app bundle exec rspec:
parallel: true
files:
- spec/**/*_spec.rb
## Instruction:
Add CircleCI configuration for npm test
## Code After:
machine:
services:
- docker
dependencies:
cache_directories:
- "~/docker"
- .bundle
- node_modules
- public/assets
override:
- if [[ -e ~/docker/image.tar ]]; then docker load -i ~/docker/image.tar; fi
- sudo pip install --upgrade docker-compose==1.5.2
- docker pull ultrayoshi/ruby-node-phantomjs:2.1.1
- docker pull postgres
- docker pull redis
- cp .env.example .env
- docker-compose build
- docker-compose run app bundle install
- docker-compose run app npm install
- docker-compose run app webpack
- mkdir -p ~/docker; docker save ultrayoshi/ruby-node-phantomjs:2.1.1 postgres redis > ~/docker/image.tar
- docker-compose run app rake db:setup
- docker-compose run -e RAILS_ENV=test app bundle exec rake assets:precompile
database:
override:
- echo 'done'
test:
override:
- docker-compose run -e CI=true -e CI_PULL_REQUEST=$CI_PULL_REQUEST -e CI_PULL_REQUESTS=$CI_PULL_REQUESTS -e COVERALLS_REPO_TOKEN=$COVERALLS_REPO_TOKEN -e COVERALLS_PARALLEL=true app bundle exec rspec:
parallel: true
files:
- spec/**/*_spec.rb
- docker-compose run app npm test:
parallel: true
files:
- app/frontend/**/*.test.js
| machine:
services:
- docker
dependencies:
cache_directories:
- "~/docker"
- .bundle
- node_modules
- public/assets
override:
- if [[ -e ~/docker/image.tar ]]; then docker load -i ~/docker/image.tar; fi
- sudo pip install --upgrade docker-compose==1.5.2
- docker pull ultrayoshi/ruby-node-phantomjs:2.1.1
- docker pull postgres
- docker pull redis
- cp .env.example .env
- docker-compose build
- docker-compose run app bundle install
- docker-compose run app npm install
- docker-compose run app webpack
- mkdir -p ~/docker; docker save ultrayoshi/ruby-node-phantomjs:2.1.1 postgres redis > ~/docker/image.tar
- docker-compose run app rake db:setup
- docker-compose run -e RAILS_ENV=test app bundle exec rake assets:precompile
database:
override:
- echo 'done'
test:
override:
- docker-compose run -e CI=true -e CI_PULL_REQUEST=$CI_PULL_REQUEST -e CI_PULL_REQUESTS=$CI_PULL_REQUESTS -e COVERALLS_REPO_TOKEN=$COVERALLS_REPO_TOKEN -e COVERALLS_PARALLEL=true app bundle exec rspec:
parallel: true
files:
- spec/**/*_spec.rb
+ - docker-compose run app npm test:
+ parallel: true
+ files:
+ - app/frontend/**/*.test.js | 4 | 0.114286 | 4 | 0 |
4227b655539ffd4a8a55747f96998b5ada075842 | tests/dummy/app/templates/application.hbs | tests/dummy/app/templates/application.hbs | <link rel="stylesheet" href="https://npmcdn.com/tachyons@4.0.0-beta.24/css/tachyons.min.css">
{{#t-flag-object collapse="m" as |t|}}
{{#t.inner}}
<img src="http://tachyons.io/img/super-wide.jpg" alt="A bright blue sky" />
{{/t.inner}}
{{#t.inner}}
<p class="lh-copy">
For desktop, this text is vertically aligned middle, no matter what the height of the image is.
On mobile, this is a paragraph below an image.
</p>
{{/t.inner}}
{{/t-flag-object}}
| <link rel="stylesheet" href="https://npmcdn.com/tachyons@4.0.0-beta.24/css/tachyons.min.css">
{{#t-flag-object collapse="m" maxWidth="6" as |t|}}
{{#t.inner maxWidth="4" class="pr2"}}
<img src="http://tachyons.io/img/super-wide.jpg" alt="A bright blue sky" class="w-100" />
{{/t.inner}}
{{#t.inner}}
<p class="lh-copy">
For desktop, this text is vertically aligned middle, no matter what the height of the image is.
On mobile, this is a paragraph below an image.
</p>
{{/t.inner}}
{{/t-flag-object}}
| Tweak hbs for flag object example | Tweak hbs for flag object example
| Handlebars | mit | johnotander/ember-tachyons-components,johnotander/ember-tachyons-components | handlebars | ## Code Before:
<link rel="stylesheet" href="https://npmcdn.com/tachyons@4.0.0-beta.24/css/tachyons.min.css">
{{#t-flag-object collapse="m" as |t|}}
{{#t.inner}}
<img src="http://tachyons.io/img/super-wide.jpg" alt="A bright blue sky" />
{{/t.inner}}
{{#t.inner}}
<p class="lh-copy">
For desktop, this text is vertically aligned middle, no matter what the height of the image is.
On mobile, this is a paragraph below an image.
</p>
{{/t.inner}}
{{/t-flag-object}}
## Instruction:
Tweak hbs for flag object example
## Code After:
<link rel="stylesheet" href="https://npmcdn.com/tachyons@4.0.0-beta.24/css/tachyons.min.css">
{{#t-flag-object collapse="m" maxWidth="6" as |t|}}
{{#t.inner maxWidth="4" class="pr2"}}
<img src="http://tachyons.io/img/super-wide.jpg" alt="A bright blue sky" class="w-100" />
{{/t.inner}}
{{#t.inner}}
<p class="lh-copy">
For desktop, this text is vertically aligned middle, no matter what the height of the image is.
On mobile, this is a paragraph below an image.
</p>
{{/t.inner}}
{{/t-flag-object}}
| <link rel="stylesheet" href="https://npmcdn.com/tachyons@4.0.0-beta.24/css/tachyons.min.css">
- {{#t-flag-object collapse="m" as |t|}}
+ {{#t-flag-object collapse="m" maxWidth="6" as |t|}}
? +++++++++++++
- {{#t.inner}}
+ {{#t.inner maxWidth="4" class="pr2"}}
- <img src="http://tachyons.io/img/super-wide.jpg" alt="A bright blue sky" />
+ <img src="http://tachyons.io/img/super-wide.jpg" alt="A bright blue sky" class="w-100" />
? ++++++++++++++
{{/t.inner}}
{{#t.inner}}
<p class="lh-copy">
For desktop, this text is vertically aligned middle, no matter what the height of the image is.
On mobile, this is a paragraph below an image.
</p>
{{/t.inner}}
{{/t-flag-object}} | 6 | 0.461538 | 3 | 3 |
0be5cfbe8579f116666d2cd444f8c5c6de330d64 | index.js | index.js | var Promise = require('bluebird');
var mapValues = require('lodash.mapvalues');
var assign = require('lodash.assign');
var curry = require('lodash.curry');
function FileWebpackPlugin(files) {
this.files = files || {};
}
FileWebpackPlugin.prototype.apply = function(compiler) {
var self = this;
compiler.plugin('emit', function(compiler, done) {
var data = {};
var assetPromises = mapValues(self.files, function(asyncTemplate, filename) {
return Promise
.fromNode(asyncTemplate.bind(null, data))
.then(createAssetFromContents);
});
Promise.props(assetPromises)
.then(addAssetsToCompiler(compiler))
.nodeify(done);
});
};
var addAssetsToCompiler = curry(function(compiler, assets) {
assign(compiler.assets, assets);
});
function createAssetFromContents(contents) {
return {
source: function() {
return contents;
},
size: function() {
return contents.length;
}
};
}
module.exports = FileWebpackPlugin;
| var Promise = require('bluebird');
var mapValues = require('lodash.mapvalues');
var assign = require('lodash.assign');
var curry = require('lodash.curry');
function FileWebpackPlugin(files) {
this.files = files || {};
}
FileWebpackPlugin.prototype.apply = function(compiler) {
var self = this;
compiler.plugin('emit', function(compiler, done) {
var data = {};
var assetPromises = mapValues(self.files, function(asyncTemplate, filename) {
return Promise
.fromNode(asyncTemplate.bind(null, data))
.then(createAssetFromContents);
});
Promise.props(assetPromises)
.then(addAssetsToCompiler(compiler))
.nodeify(done);
});
};
var createAssetFromContents = function(contents) {
return {
source: function() {
return contents;
},
size: function() {
return contents.length;
}
};
};
var addAssetsToCompiler = curry(function(compiler, assets) {
assign(compiler.assets, assets);
});
module.exports = FileWebpackPlugin;
| Sort functions in order of usage | Sort functions in order of usage | JavaScript | mit | markdalgleish/file-webpack-plugin | javascript | ## Code Before:
var Promise = require('bluebird');
var mapValues = require('lodash.mapvalues');
var assign = require('lodash.assign');
var curry = require('lodash.curry');
function FileWebpackPlugin(files) {
this.files = files || {};
}
FileWebpackPlugin.prototype.apply = function(compiler) {
var self = this;
compiler.plugin('emit', function(compiler, done) {
var data = {};
var assetPromises = mapValues(self.files, function(asyncTemplate, filename) {
return Promise
.fromNode(asyncTemplate.bind(null, data))
.then(createAssetFromContents);
});
Promise.props(assetPromises)
.then(addAssetsToCompiler(compiler))
.nodeify(done);
});
};
var addAssetsToCompiler = curry(function(compiler, assets) {
assign(compiler.assets, assets);
});
function createAssetFromContents(contents) {
return {
source: function() {
return contents;
},
size: function() {
return contents.length;
}
};
}
module.exports = FileWebpackPlugin;
## Instruction:
Sort functions in order of usage
## Code After:
var Promise = require('bluebird');
var mapValues = require('lodash.mapvalues');
var assign = require('lodash.assign');
var curry = require('lodash.curry');
function FileWebpackPlugin(files) {
this.files = files || {};
}
FileWebpackPlugin.prototype.apply = function(compiler) {
var self = this;
compiler.plugin('emit', function(compiler, done) {
var data = {};
var assetPromises = mapValues(self.files, function(asyncTemplate, filename) {
return Promise
.fromNode(asyncTemplate.bind(null, data))
.then(createAssetFromContents);
});
Promise.props(assetPromises)
.then(addAssetsToCompiler(compiler))
.nodeify(done);
});
};
var createAssetFromContents = function(contents) {
return {
source: function() {
return contents;
},
size: function() {
return contents.length;
}
};
};
var addAssetsToCompiler = curry(function(compiler, assets) {
assign(compiler.assets, assets);
});
module.exports = FileWebpackPlugin;
| var Promise = require('bluebird');
var mapValues = require('lodash.mapvalues');
var assign = require('lodash.assign');
var curry = require('lodash.curry');
function FileWebpackPlugin(files) {
this.files = files || {};
}
FileWebpackPlugin.prototype.apply = function(compiler) {
var self = this;
compiler.plugin('emit', function(compiler, done) {
var data = {};
var assetPromises = mapValues(self.files, function(asyncTemplate, filename) {
return Promise
.fromNode(asyncTemplate.bind(null, data))
.then(createAssetFromContents);
});
Promise.props(assetPromises)
.then(addAssetsToCompiler(compiler))
.nodeify(done);
});
};
- var addAssetsToCompiler = curry(function(compiler, assets) {
- assign(compiler.assets, assets);
- });
-
- function createAssetFromContents(contents) {
? ^^^^^^^^
+ var createAssetFromContents = function(contents) {
? ^^^ +++++++++++
return {
source: function() {
return contents;
},
size: function() {
return contents.length;
}
};
- }
+ };
+
+ var addAssetsToCompiler = curry(function(compiler, assets) {
+ assign(compiler.assets, assets);
+ });
module.exports = FileWebpackPlugin; | 12 | 0.285714 | 6 | 6 |
4a51369bf5b24c263ceac5199643ace5597611d3 | lib/assure-seamless-styles.js | lib/assure-seamless-styles.js | 'use strict';
var isParentNode = require('dom-ext/parent-node/is')
, isStyleSheet = require('html-dom-ext/link/is-style-sheet')
, forEach = Array.prototype.forEach;
module.exports = function (nodes) {
var styleSheets = [], container, document;
forEach.call(nodes, function self(node) {
if (isStyleSheet(node)) {
if (node.hasAttribute('href')) styleSheets.push(node);
return;
}
if (!isParentNode(node)) return;
if (node.getElementsByTagName) {
forEach.call(node.getElementsByTagName('link'), function (link) {
if (!isStyleSheet(link)) return;
if (link.hasAttribute('href')) styleSheets.push(node);
});
return;
}
forEach.call(node.childNodes, self);
});
if (!styleSheets.length) return;
document = styleSheets[0].ownerDocument;
container = document.documentElement.insertBefore(document.createElement('div'),
document.documentElement.firstChild);
container.className = 'ie-stylesheets-unload-workaround';
styleSheets.forEach(function (styleSheet) {
styleSheet = styleSheet.cloneNode(true);
container.appendChild(styleSheet);
styleSheet.setAttribute('href', styleSheet.getAttribute('href'));
});
setTimeout(function () { document.documentElement.removeChild(container); }, 0);
};
| 'use strict';
var isParentNode = require('dom-ext/parent-node/is')
, isStyleSheet = require('html-dom-ext/link/is-style-sheet')
, forEach = Array.prototype.forEach;
module.exports = exports = function (nodes) {
var styleSheets = [], container, document;
if (!exports.enabled) return;
forEach.call(nodes, function self(node) {
if (isStyleSheet(node)) {
if (node.hasAttribute('href')) styleSheets.push(node);
return;
}
if (!isParentNode(node)) return;
if (node.getElementsByTagName) {
forEach.call(node.getElementsByTagName('link'), function (link) {
if (!isStyleSheet(link)) return;
if (link.hasAttribute('href')) styleSheets.push(node);
});
return;
}
forEach.call(node.childNodes, self);
});
if (!styleSheets.length) return;
document = styleSheets[0].ownerDocument;
container = document.documentElement.insertBefore(document.createElement('div'),
document.documentElement.firstChild);
container.className = 'ie-stylesheets-unload-workaround';
styleSheets.forEach(function (styleSheet) {
styleSheet = styleSheet.cloneNode(true);
container.appendChild(styleSheet);
styleSheet.setAttribute('href', styleSheet.getAttribute('href'));
});
setTimeout(function () { document.documentElement.removeChild(container); }, 0);
};
exports.enabled = true;
| Allow external disable of stylesheets hack | Allow external disable of stylesheets hack
| JavaScript | mit | medikoo/site-tree | javascript | ## Code Before:
'use strict';
var isParentNode = require('dom-ext/parent-node/is')
, isStyleSheet = require('html-dom-ext/link/is-style-sheet')
, forEach = Array.prototype.forEach;
module.exports = function (nodes) {
var styleSheets = [], container, document;
forEach.call(nodes, function self(node) {
if (isStyleSheet(node)) {
if (node.hasAttribute('href')) styleSheets.push(node);
return;
}
if (!isParentNode(node)) return;
if (node.getElementsByTagName) {
forEach.call(node.getElementsByTagName('link'), function (link) {
if (!isStyleSheet(link)) return;
if (link.hasAttribute('href')) styleSheets.push(node);
});
return;
}
forEach.call(node.childNodes, self);
});
if (!styleSheets.length) return;
document = styleSheets[0].ownerDocument;
container = document.documentElement.insertBefore(document.createElement('div'),
document.documentElement.firstChild);
container.className = 'ie-stylesheets-unload-workaround';
styleSheets.forEach(function (styleSheet) {
styleSheet = styleSheet.cloneNode(true);
container.appendChild(styleSheet);
styleSheet.setAttribute('href', styleSheet.getAttribute('href'));
});
setTimeout(function () { document.documentElement.removeChild(container); }, 0);
};
## Instruction:
Allow external disable of stylesheets hack
## Code After:
'use strict';
var isParentNode = require('dom-ext/parent-node/is')
, isStyleSheet = require('html-dom-ext/link/is-style-sheet')
, forEach = Array.prototype.forEach;
module.exports = exports = function (nodes) {
var styleSheets = [], container, document;
if (!exports.enabled) return;
forEach.call(nodes, function self(node) {
if (isStyleSheet(node)) {
if (node.hasAttribute('href')) styleSheets.push(node);
return;
}
if (!isParentNode(node)) return;
if (node.getElementsByTagName) {
forEach.call(node.getElementsByTagName('link'), function (link) {
if (!isStyleSheet(link)) return;
if (link.hasAttribute('href')) styleSheets.push(node);
});
return;
}
forEach.call(node.childNodes, self);
});
if (!styleSheets.length) return;
document = styleSheets[0].ownerDocument;
container = document.documentElement.insertBefore(document.createElement('div'),
document.documentElement.firstChild);
container.className = 'ie-stylesheets-unload-workaround';
styleSheets.forEach(function (styleSheet) {
styleSheet = styleSheet.cloneNode(true);
container.appendChild(styleSheet);
styleSheet.setAttribute('href', styleSheet.getAttribute('href'));
});
setTimeout(function () { document.documentElement.removeChild(container); }, 0);
};
exports.enabled = true;
| 'use strict';
var isParentNode = require('dom-ext/parent-node/is')
, isStyleSheet = require('html-dom-ext/link/is-style-sheet')
, forEach = Array.prototype.forEach;
- module.exports = function (nodes) {
+ module.exports = exports = function (nodes) {
? ++++++++++
var styleSheets = [], container, document;
+ if (!exports.enabled) return;
forEach.call(nodes, function self(node) {
if (isStyleSheet(node)) {
if (node.hasAttribute('href')) styleSheets.push(node);
return;
}
if (!isParentNode(node)) return;
if (node.getElementsByTagName) {
forEach.call(node.getElementsByTagName('link'), function (link) {
if (!isStyleSheet(link)) return;
if (link.hasAttribute('href')) styleSheets.push(node);
});
return;
}
forEach.call(node.childNodes, self);
});
if (!styleSheets.length) return;
document = styleSheets[0].ownerDocument;
container = document.documentElement.insertBefore(document.createElement('div'),
document.documentElement.firstChild);
container.className = 'ie-stylesheets-unload-workaround';
styleSheets.forEach(function (styleSheet) {
styleSheet = styleSheet.cloneNode(true);
container.appendChild(styleSheet);
styleSheet.setAttribute('href', styleSheet.getAttribute('href'));
});
setTimeout(function () { document.documentElement.removeChild(container); }, 0);
};
+
+ exports.enabled = true; | 5 | 0.135135 | 4 | 1 |
faccdb240fa6a9c28b36685743d1cba1982ec8b8 | demos/risk/EventBasedRisk/job_risk.ini | demos/risk/EventBasedRisk/job_risk.ini | [general]
description = Stochastic Event-Based Risk Demo (Nepal)
calculation_mode = event_based_risk
concurrent_tasks = 24
[exposure]
region = 78.0 31.5, 89.5 31.5, 89.5 25.5, 78.0 25.5
exposure_file = exposure_model.xml
[risk_calculation]
asset_hazard_distance = 20
insured_losses = true
[outputs]
avg_losses = true
quantile_loss_curves = 0.15 0.85
risk_investigation_time = 1
conditional_loss_poes = 0.0021, 0.000404
[export]
export_dir = /tmp
| [general]
description = Stochastic Event-Based Risk Demo (Nepal)
calculation_mode = event_based_risk
concurrent_tasks = 24
[exposure]
region = 78.0 31.5, 89.5 31.5, 89.5 25.5, 78.0 25.5
exposure_file = exposure_model.xml
[risk_calculation]
asset_hazard_distance = 20
insured_losses = true
individual_curves = true
[outputs]
avg_losses = true
quantile_loss_curves = 0.15 0.85
risk_investigation_time = 1
conditional_loss_poes = 0.0021, 0.000404
[export]
export_dir = /tmp
| Set individual_curves = true in the event based risk demo | Set individual_curves = true in the event based risk demo
Former-commit-id: 64a5d5ef5f364a1d0b2fc9859789888743fbea9e [formerly 64a5d5ef5f364a1d0b2fc9859789888743fbea9e [formerly a30978b6220bd07fea51b0fe6a3e0b28461a628c]]
Former-commit-id: 756eb1c9d95665d0c2644d0b9c1a2d5b18ac8596
Former-commit-id: e4532f37c0702951d1e50b91dc38845363f9a266 | INI | agpl-3.0 | gem/oq-engine,gem/oq-engine,gem/oq-engine,gem/oq-engine,gem/oq-engine | ini | ## Code Before:
[general]
description = Stochastic Event-Based Risk Demo (Nepal)
calculation_mode = event_based_risk
concurrent_tasks = 24
[exposure]
region = 78.0 31.5, 89.5 31.5, 89.5 25.5, 78.0 25.5
exposure_file = exposure_model.xml
[risk_calculation]
asset_hazard_distance = 20
insured_losses = true
[outputs]
avg_losses = true
quantile_loss_curves = 0.15 0.85
risk_investigation_time = 1
conditional_loss_poes = 0.0021, 0.000404
[export]
export_dir = /tmp
## Instruction:
Set individual_curves = true in the event based risk demo
Former-commit-id: 64a5d5ef5f364a1d0b2fc9859789888743fbea9e [formerly 64a5d5ef5f364a1d0b2fc9859789888743fbea9e [formerly a30978b6220bd07fea51b0fe6a3e0b28461a628c]]
Former-commit-id: 756eb1c9d95665d0c2644d0b9c1a2d5b18ac8596
Former-commit-id: e4532f37c0702951d1e50b91dc38845363f9a266
## Code After:
[general]
description = Stochastic Event-Based Risk Demo (Nepal)
calculation_mode = event_based_risk
concurrent_tasks = 24
[exposure]
region = 78.0 31.5, 89.5 31.5, 89.5 25.5, 78.0 25.5
exposure_file = exposure_model.xml
[risk_calculation]
asset_hazard_distance = 20
insured_losses = true
individual_curves = true
[outputs]
avg_losses = true
quantile_loss_curves = 0.15 0.85
risk_investigation_time = 1
conditional_loss_poes = 0.0021, 0.000404
[export]
export_dir = /tmp
| [general]
description = Stochastic Event-Based Risk Demo (Nepal)
calculation_mode = event_based_risk
concurrent_tasks = 24
[exposure]
region = 78.0 31.5, 89.5 31.5, 89.5 25.5, 78.0 25.5
exposure_file = exposure_model.xml
[risk_calculation]
asset_hazard_distance = 20
insured_losses = true
+ individual_curves = true
[outputs]
avg_losses = true
quantile_loss_curves = 0.15 0.85
risk_investigation_time = 1
conditional_loss_poes = 0.0021, 0.000404
[export]
export_dir = /tmp | 1 | 0.047619 | 1 | 0 |
083dd3ab6dfb78060b9b6f154c8465ca83110508 | src/_includes/support.html | src/_includes/support.html | <div class="notice">
<h3>Like This?</h3>
<p>Please consider visiting my <a href="http://amzn.com/w/1K58RT2NS0SDP" onclick="ga('send', 'event', 'link', 'click', 'Amazon Wish List');">Amazon Wish List</a> or <a href="https://www.paypal.me/mmistakes" onclick="ga('send', 'event', 'link', 'click', 'Send PayPal');">donating via PayPal</a> to show your support. You can also <a href="{{ site.url }}/support/#subscribe-to-the-feeds">subscribe to various site feeds</a> to get notified of new posts, <a href="{{ site.url }}/support/#follow-me-on-social-media">follow me on social media</a>, and more.</p>
</div>
| <div class="notice">
<h3>Like This?</h3>
<p>Please consider purchasing something from my <a href="http://amzn.com/w/1K58RT2NS0SDP" onclick="ga('send', 'event', 'link', 'click', 'Amazon Wish List');">Amazon Wish List</a> or <a href="https://www.paypal.me/mmistakes" onclick="ga('send', 'event', 'link', 'click', 'Send PayPal');">donating via PayPal</a> to show your support. You can also <a href="{{ site.url }}/support/#subscribe-to-the-feeds">subscribe to various site feeds</a> to get notified of new posts, <a href="{{ site.url }}/support/#follow-me-on-social-media">follow me on social media</a>, and more.</p>
</div>
| Rephrase Amazon Wish List call to action | Rephrase Amazon Wish List call to action | HTML | mit | mmistakes/made-mistakes-jekyll,mmistakes/made-mistakes-jekyll,mmistakes/made-mistakes-jekyll | html | ## Code Before:
<div class="notice">
<h3>Like This?</h3>
<p>Please consider visiting my <a href="http://amzn.com/w/1K58RT2NS0SDP" onclick="ga('send', 'event', 'link', 'click', 'Amazon Wish List');">Amazon Wish List</a> or <a href="https://www.paypal.me/mmistakes" onclick="ga('send', 'event', 'link', 'click', 'Send PayPal');">donating via PayPal</a> to show your support. You can also <a href="{{ site.url }}/support/#subscribe-to-the-feeds">subscribe to various site feeds</a> to get notified of new posts, <a href="{{ site.url }}/support/#follow-me-on-social-media">follow me on social media</a>, and more.</p>
</div>
## Instruction:
Rephrase Amazon Wish List call to action
## Code After:
<div class="notice">
<h3>Like This?</h3>
<p>Please consider purchasing something from my <a href="http://amzn.com/w/1K58RT2NS0SDP" onclick="ga('send', 'event', 'link', 'click', 'Amazon Wish List');">Amazon Wish List</a> or <a href="https://www.paypal.me/mmistakes" onclick="ga('send', 'event', 'link', 'click', 'Send PayPal');">donating via PayPal</a> to show your support. You can also <a href="{{ site.url }}/support/#subscribe-to-the-feeds">subscribe to various site feeds</a> to get notified of new posts, <a href="{{ site.url }}/support/#follow-me-on-social-media">follow me on social media</a>, and more.</p>
</div>
| <div class="notice">
<h3>Like This?</h3>
- <p>Please consider visiting my <a href="http://amzn.com/w/1K58RT2NS0SDP" onclick="ga('send', 'event', 'link', 'click', 'Amazon Wish List');">Amazon Wish List</a> or <a href="https://www.paypal.me/mmistakes" onclick="ga('send', 'event', 'link', 'click', 'Send PayPal');">donating via PayPal</a> to show your support. You can also <a href="{{ site.url }}/support/#subscribe-to-the-feeds">subscribe to various site feeds</a> to get notified of new posts, <a href="{{ site.url }}/support/#follow-me-on-social-media">follow me on social media</a>, and more.</p>
? ^^^^^
+ <p>Please consider purchasing something from my <a href="http://amzn.com/w/1K58RT2NS0SDP" onclick="ga('send', 'event', 'link', 'click', 'Amazon Wish List');">Amazon Wish List</a> or <a href="https://www.paypal.me/mmistakes" onclick="ga('send', 'event', 'link', 'click', 'Send PayPal');">donating via PayPal</a> to show your support. You can also <a href="{{ site.url }}/support/#subscribe-to-the-feeds">subscribe to various site feeds</a> to get notified of new posts, <a href="{{ site.url }}/support/#follow-me-on-social-media">follow me on social media</a>, and more.</p>
? ^^^^^^^ +++++++++++++++
</div> | 2 | 0.5 | 1 | 1 |
70808a2243ebf04aa86d5b4539950b22cd96cc7d | maras/utils/__init__.py | maras/utils/__init__.py | '''
Misc utilities
'''
# Import python libs
import os
import binascii
def rand_hex_str(size):
'''
Return a random string of the passed size using hex encoding
'''
return binascii.hexlify(os.urandom(size/2))
def rand_raw_str(size):
'''
Return a raw byte string of the given size
'''
return os.urandom(size)
| '''
Misc utilities
'''
# Import python libs
import os
import time
import struct
import binascii
import datetime
# create a standard epoch so all platforms will count revs from
# a standard epoch of jan 1 2014
STD_EPOCH = time.mktime(datetime.datetime(2014, 1, 1).timetuple())
def rand_hex_str(size):
'''
Return a random string of the passed size using hex encoding
'''
return binascii.hexlify(os.urandom(size/2))
def rand_raw_str(size):
'''
Return a raw byte string of the given size
'''
return os.urandom(size)
def gen_rev():
'''
Return a revision based on timestamp
'''
r_time = time.time() - STD_EPOCH
return struct.pack('>Q', r_time * 1000000)
| Add rev generation via normalized timestamps | Add rev generation via normalized timestamps
| Python | apache-2.0 | thatch45/maras | python | ## Code Before:
'''
Misc utilities
'''
# Import python libs
import os
import binascii
def rand_hex_str(size):
'''
Return a random string of the passed size using hex encoding
'''
return binascii.hexlify(os.urandom(size/2))
def rand_raw_str(size):
'''
Return a raw byte string of the given size
'''
return os.urandom(size)
## Instruction:
Add rev generation via normalized timestamps
## Code After:
'''
Misc utilities
'''
# Import python libs
import os
import time
import struct
import binascii
import datetime
# create a standard epoch so all platforms will count revs from
# a standard epoch of jan 1 2014
STD_EPOCH = time.mktime(datetime.datetime(2014, 1, 1).timetuple())
def rand_hex_str(size):
'''
Return a random string of the passed size using hex encoding
'''
return binascii.hexlify(os.urandom(size/2))
def rand_raw_str(size):
'''
Return a raw byte string of the given size
'''
return os.urandom(size)
def gen_rev():
'''
Return a revision based on timestamp
'''
r_time = time.time() - STD_EPOCH
return struct.pack('>Q', r_time * 1000000)
| '''
Misc utilities
'''
# Import python libs
import os
+ import time
+ import struct
import binascii
+ import datetime
+
+ # create a standard epoch so all platforms will count revs from
+ # a standard epoch of jan 1 2014
+ STD_EPOCH = time.mktime(datetime.datetime(2014, 1, 1).timetuple())
def rand_hex_str(size):
'''
Return a random string of the passed size using hex encoding
'''
return binascii.hexlify(os.urandom(size/2))
def rand_raw_str(size):
'''
Return a raw byte string of the given size
'''
return os.urandom(size)
+
+
+ def gen_rev():
+ '''
+ Return a revision based on timestamp
+ '''
+ r_time = time.time() - STD_EPOCH
+ return struct.pack('>Q', r_time * 1000000) | 15 | 0.714286 | 15 | 0 |
99c430f70769028a876db54df19e359cca03b128 | static/js/src/main.js | static/js/src/main.js | // commonjs code goes here
(function () {
var i18n = window.i18n = require('i18next');
var XHR = require('i18next-xhr-backend');
var lngDetector = require('i18next-browser-languagedetector');
var Cache = require('i18next-localstorage-cache');
var backendOptions = {
loadPath: '/static/locale/__lng__/translations.json'
};
var callbacks = [];
var initialized = false;
var detectionOptions = {
order: ['htmlTag'],
htmlTag: document.documentElement
};
var cacheOptions = {
enabled: true,
prefix: page_params.server_generation + ':'
};
i18n.use(XHR)
.use(lngDetector)
.use(Cache)
.init({
nsSeparator: false,
keySeparator: false,
interpolation: {
prefix: "__",
suffix: "__"
},
backend: backendOptions,
detection: detectionOptions,
cache: cacheOptions
}, function () {
var i;
initialized = true;
for (i=0; i<callbacks.length; i++) {
callbacks[i]();
}
});
i18n.ensure_i18n = function (callback) {
if (initialized) {
callback();
} else {
callbacks.push(callback);
}
};
}());
| // commonjs code goes here
(function () {
var i18n = window.i18n = require('i18next');
var XHR = require('i18next-xhr-backend');
var lngDetector = require('i18next-browser-languagedetector');
var Cache = require('i18next-localstorage-cache');
var backendOptions = {
loadPath: '/static/locale/__lng__/translations.json'
};
var callbacks = [];
var initialized = false;
var detectionOptions = {
order: ['htmlTag'],
htmlTag: document.documentElement
};
var cacheOptions = {
enabled: true,
prefix: page_params.server_generation + ':'
};
i18n.use(XHR)
.use(lngDetector)
.use(Cache)
.init({
nsSeparator: false,
keySeparator: false,
interpolation: {
prefix: "__",
suffix: "__"
},
backend: backendOptions,
detection: detectionOptions,
cache: cacheOptions,
fallbackLng: 'en'
}, function () {
var i;
initialized = true;
for (i=0; i<callbacks.length; i++) {
callbacks[i]();
}
});
i18n.ensure_i18n = function (callback) {
if (initialized) {
callback();
} else {
callbacks.push(callback);
}
};
}());
| Make English the fallback language in i18next. | Make English the fallback language in i18next.
Fixes: #1580
| JavaScript | apache-2.0 | punchagan/zulip,showell/zulip,andersk/zulip,paxapy/zulip,susansls/zulip,dattatreya303/zulip,timabbott/zulip,verma-varsha/zulip,eeshangarg/zulip,jrowan/zulip,blaze225/zulip,sharmaeklavya2/zulip,jainayush975/zulip,souravbadami/zulip,eeshangarg/zulip,synicalsyntax/zulip,peguin40/zulip,j831/zulip,sup95/zulip,dawran6/zulip,kou/zulip,mahim97/zulip,susansls/zulip,JPJPJPOPOP/zulip,TigorC/zulip,vikas-parashar/zulip,krtkmj/zulip,SmartPeople/zulip,vaidap/zulip,reyha/zulip,souravbadami/zulip,sup95/zulip,brainwane/zulip,brainwane/zulip,eeshangarg/zulip,niftynei/zulip,sonali0901/zulip,peguin40/zulip,SmartPeople/zulip,mohsenSy/zulip,amyliu345/zulip,JPJPJPOPOP/zulip,kou/zulip,dattatreya303/zulip,PhilSk/zulip,AZtheAsian/zulip,vabs22/zulip,jainayush975/zulip,niftynei/zulip,ryanbackman/zulip,showell/zulip,mahim97/zulip,umkay/zulip,reyha/zulip,shubhamdhama/zulip,arpith/zulip,jrowan/zulip,kou/zulip,samatdav/zulip,aakash-cr7/zulip,zacps/zulip,mohsenSy/zulip,jphilipsen05/zulip,tommyip/zulip,arpith/zulip,synicalsyntax/zulip,umkay/zulip,punchagan/zulip,ahmadassaf/zulip,rht/zulip,brainwane/zulip,j831/zulip,vaidap/zulip,Diptanshu8/zulip,Diptanshu8/zulip,kou/zulip,blaze225/zulip,Juanvulcano/zulip,showell/zulip,brainwane/zulip,jackrzhang/zulip,amanharitsh123/zulip,Galexrt/zulip,cosmicAsymmetry/zulip,vikas-parashar/zulip,jainayush975/zulip,TigorC/zulip,sharmaeklavya2/zulip,ahmadassaf/zulip,Juanvulcano/zulip,PhilSk/zulip,sup95/zulip,rht/zulip,synicalsyntax/zulip,punchagan/zulip,vabs22/zulip,paxapy/zulip,peguin40/zulip,isht3/zulip,sharmaeklavya2/zulip,ahmadassaf/zulip,sonali0901/zulip,vabs22/zulip,verma-varsha/zulip,Galexrt/zulip,sharmaeklavya2/zulip,andersk/zulip,SmartPeople/zulip,zulip/zulip,PhilSk/zulip,amanharitsh123/zulip,dhcrzf/zulip,susansls/zulip,paxapy/zulip,eeshangarg/zulip,brockwhittaker/zulip,mohsenSy/zulip,dhcrzf/zulip,verma-varsha/zulip,jainayush975/zulip,jainayush975/zulip,dawran6/zulip,dawran6/zulip,mahim97/zulip,isht3/zulip,reyha/zulip,christi3k/zulip,vikas-parashar/zulip,grave-w-grave/zulip,j831/zulip,calvinleenyc/zulip,Jianchun1/zulip,Galexrt/zulip,amanharitsh123/zulip,showell/zulip,jackrzhang/zulip,aakash-cr7/zulip,hackerkid/zulip,grave-w-grave/zulip,jackrzhang/zulip,Diptanshu8/zulip,jackrzhang/zulip,souravbadami/zulip,timabbott/zulip,shubhamdhama/zulip,j831/zulip,TigorC/zulip,reyha/zulip,peguin40/zulip,Jianchun1/zulip,amanharitsh123/zulip,vaidap/zulip,vabs22/zulip,grave-w-grave/zulip,joyhchen/zulip,niftynei/zulip,cosmicAsymmetry/zulip,rht/zulip,kou/zulip,ahmadassaf/zulip,rishig/zulip,sharmaeklavya2/zulip,amyliu345/zulip,susansls/zulip,ahmadassaf/zulip,calvinleenyc/zulip,vikas-parashar/zulip,umkay/zulip,PhilSk/zulip,christi3k/zulip,christi3k/zulip,ryanbackman/zulip,AZtheAsian/zulip,dattatreya303/zulip,andersk/zulip,niftynei/zulip,ryanbackman/zulip,KingxBanana/zulip,shubhamdhama/zulip,jphilipsen05/zulip,Juanvulcano/zulip,kou/zulip,peguin40/zulip,jrowan/zulip,blaze225/zulip,Galexrt/zulip,Jianchun1/zulip,rishig/zulip,krtkmj/zulip,christi3k/zulip,jrowan/zulip,sup95/zulip,mahim97/zulip,Jianchun1/zulip,SmartPeople/zulip,hackerkid/zulip,rht/zulip,umkay/zulip,punchagan/zulip,umkay/zulip,jphilipsen05/zulip,niftynei/zulip,mohsenSy/zulip,Diptanshu8/zulip,sonali0901/zulip,zacps/zulip,tommyip/zulip,tommyip/zulip,krtkmj/zulip,KingxBanana/zulip,amanharitsh123/zulip,amyliu345/zulip,Juanvulcano/zulip,synicalsyntax/zulip,jainayush975/zulip,shubhamdhama/zulip,krtkmj/zulip,dhcrzf/zulip,timabbott/zulip,dattatreya303/zulip,arpith/zulip,tommyip/zulip,hackerkid/zulip,joyhchen/zulip,blaze225/zulip,Galexrt/zulip,aakash-cr7/zulip,krtkmj/zulip,vaidap/zulip,ahmadassaf/zulip,aakash-cr7/zulip,samatdav/zulip,SmartPeople/zulip,souravbadami/zulip,paxapy/zulip,reyha/zulip,samatdav/zulip,shubhamdhama/zulip,dawran6/zulip,tommyip/zulip,samatdav/zulip,brockwhittaker/zulip,zulip/zulip,christi3k/zulip,showell/zulip,hackerkid/zulip,KingxBanana/zulip,ryanbackman/zulip,zulip/zulip,cosmicAsymmetry/zulip,susansls/zulip,krtkmj/zulip,JPJPJPOPOP/zulip,cosmicAsymmetry/zulip,AZtheAsian/zulip,blaze225/zulip,JPJPJPOPOP/zulip,calvinleenyc/zulip,samatdav/zulip,jackrzhang/zulip,jphilipsen05/zulip,aakash-cr7/zulip,umkay/zulip,synicalsyntax/zulip,timabbott/zulip,arpith/zulip,rht/zulip,sonali0901/zulip,brockwhittaker/zulip,kou/zulip,jrowan/zulip,SmartPeople/zulip,AZtheAsian/zulip,niftynei/zulip,zulip/zulip,rishig/zulip,shubhamdhama/zulip,mohsenSy/zulip,showell/zulip,andersk/zulip,timabbott/zulip,mahim97/zulip,Juanvulcano/zulip,zulip/zulip,sharmaeklavya2/zulip,dattatreya303/zulip,zacps/zulip,amyliu345/zulip,brockwhittaker/zulip,ryanbackman/zulip,Jianchun1/zulip,brockwhittaker/zulip,sonali0901/zulip,ahmadassaf/zulip,rishig/zulip,souravbadami/zulip,zacps/zulip,dattatreya303/zulip,calvinleenyc/zulip,cosmicAsymmetry/zulip,reyha/zulip,isht3/zulip,krtkmj/zulip,zulip/zulip,AZtheAsian/zulip,TigorC/zulip,arpith/zulip,susansls/zulip,souravbadami/zulip,mohsenSy/zulip,vabs22/zulip,Juanvulcano/zulip,TigorC/zulip,paxapy/zulip,KingxBanana/zulip,umkay/zulip,jrowan/zulip,zacps/zulip,joyhchen/zulip,andersk/zulip,KingxBanana/zulip,paxapy/zulip,dawran6/zulip,grave-w-grave/zulip,timabbott/zulip,dhcrzf/zulip,jphilipsen05/zulip,dhcrzf/zulip,eeshangarg/zulip,eeshangarg/zulip,showell/zulip,hackerkid/zulip,arpith/zulip,jphilipsen05/zulip,dhcrzf/zulip,Galexrt/zulip,calvinleenyc/zulip,amyliu345/zulip,JPJPJPOPOP/zulip,isht3/zulip,brainwane/zulip,joyhchen/zulip,j831/zulip,tommyip/zulip,Galexrt/zulip,samatdav/zulip,j831/zulip,vikas-parashar/zulip,eeshangarg/zulip,punchagan/zulip,Jianchun1/zulip,hackerkid/zulip,TigorC/zulip,vabs22/zulip,brockwhittaker/zulip,timabbott/zulip,andersk/zulip,vaidap/zulip,brainwane/zulip,AZtheAsian/zulip,andersk/zulip,vaidap/zulip,rht/zulip,joyhchen/zulip,isht3/zulip,punchagan/zulip,jackrzhang/zulip,verma-varsha/zulip,tommyip/zulip,verma-varsha/zulip,sonali0901/zulip,dhcrzf/zulip,grave-w-grave/zulip,punchagan/zulip,KingxBanana/zulip,christi3k/zulip,aakash-cr7/zulip,rishig/zulip,JPJPJPOPOP/zulip,PhilSk/zulip,rishig/zulip,joyhchen/zulip,hackerkid/zulip,blaze225/zulip,jackrzhang/zulip,zulip/zulip,calvinleenyc/zulip,vikas-parashar/zulip,Diptanshu8/zulip,verma-varsha/zulip,rht/zulip,zacps/zulip,synicalsyntax/zulip,peguin40/zulip,grave-w-grave/zulip,Diptanshu8/zulip,PhilSk/zulip,amanharitsh123/zulip,shubhamdhama/zulip,cosmicAsymmetry/zulip,dawran6/zulip,amyliu345/zulip,sup95/zulip,brainwane/zulip,sup95/zulip,rishig/zulip,synicalsyntax/zulip,isht3/zulip,mahim97/zulip,ryanbackman/zulip | javascript | ## Code Before:
// commonjs code goes here
(function () {
var i18n = window.i18n = require('i18next');
var XHR = require('i18next-xhr-backend');
var lngDetector = require('i18next-browser-languagedetector');
var Cache = require('i18next-localstorage-cache');
var backendOptions = {
loadPath: '/static/locale/__lng__/translations.json'
};
var callbacks = [];
var initialized = false;
var detectionOptions = {
order: ['htmlTag'],
htmlTag: document.documentElement
};
var cacheOptions = {
enabled: true,
prefix: page_params.server_generation + ':'
};
i18n.use(XHR)
.use(lngDetector)
.use(Cache)
.init({
nsSeparator: false,
keySeparator: false,
interpolation: {
prefix: "__",
suffix: "__"
},
backend: backendOptions,
detection: detectionOptions,
cache: cacheOptions
}, function () {
var i;
initialized = true;
for (i=0; i<callbacks.length; i++) {
callbacks[i]();
}
});
i18n.ensure_i18n = function (callback) {
if (initialized) {
callback();
} else {
callbacks.push(callback);
}
};
}());
## Instruction:
Make English the fallback language in i18next.
Fixes: #1580
## Code After:
// commonjs code goes here
(function () {
var i18n = window.i18n = require('i18next');
var XHR = require('i18next-xhr-backend');
var lngDetector = require('i18next-browser-languagedetector');
var Cache = require('i18next-localstorage-cache');
var backendOptions = {
loadPath: '/static/locale/__lng__/translations.json'
};
var callbacks = [];
var initialized = false;
var detectionOptions = {
order: ['htmlTag'],
htmlTag: document.documentElement
};
var cacheOptions = {
enabled: true,
prefix: page_params.server_generation + ':'
};
i18n.use(XHR)
.use(lngDetector)
.use(Cache)
.init({
nsSeparator: false,
keySeparator: false,
interpolation: {
prefix: "__",
suffix: "__"
},
backend: backendOptions,
detection: detectionOptions,
cache: cacheOptions,
fallbackLng: 'en'
}, function () {
var i;
initialized = true;
for (i=0; i<callbacks.length; i++) {
callbacks[i]();
}
});
i18n.ensure_i18n = function (callback) {
if (initialized) {
callback();
} else {
callbacks.push(callback);
}
};
}());
| // commonjs code goes here
(function () {
var i18n = window.i18n = require('i18next');
var XHR = require('i18next-xhr-backend');
var lngDetector = require('i18next-browser-languagedetector');
var Cache = require('i18next-localstorage-cache');
var backendOptions = {
loadPath: '/static/locale/__lng__/translations.json'
};
var callbacks = [];
var initialized = false;
var detectionOptions = {
order: ['htmlTag'],
htmlTag: document.documentElement
};
var cacheOptions = {
enabled: true,
prefix: page_params.server_generation + ':'
};
i18n.use(XHR)
.use(lngDetector)
.use(Cache)
.init({
nsSeparator: false,
keySeparator: false,
interpolation: {
prefix: "__",
suffix: "__"
},
backend: backendOptions,
detection: detectionOptions,
- cache: cacheOptions
+ cache: cacheOptions,
? +
+ fallbackLng: 'en'
}, function () {
var i;
initialized = true;
for (i=0; i<callbacks.length; i++) {
callbacks[i]();
}
});
i18n.ensure_i18n = function (callback) {
if (initialized) {
callback();
} else {
callbacks.push(callback);
}
};
}()); | 3 | 0.055556 | 2 | 1 |
846e41b03e8aaedb8c1fe2f7fc50e4c3d2341283 | data/hostname/thyssen.internal.softwareheritage.org.yaml | data/hostname/thyssen.internal.softwareheritage.org.yaml | ---
# Add ddouard as jenkins admin
users:
ddouard:
groups:
- sudo
| ---
# Add ddouard as jenkins admin
users:
ddouard:
groups:
- sudo
dar::backup::exclude:
- /var/lib/docker/
| Exclude /var/lib/docker from dar backup | thyssen: Exclude /var/lib/docker from dar backup
Related T1285
| YAML | apache-2.0 | SoftwareHeritage/puppet-swh-site,SoftwareHeritage/puppet-swh-site,SoftwareHeritage/puppet-swh-site,SoftwareHeritage/puppet-swh-site,SoftwareHeritage/puppet-swh-site | yaml | ## Code Before:
---
# Add ddouard as jenkins admin
users:
ddouard:
groups:
- sudo
## Instruction:
thyssen: Exclude /var/lib/docker from dar backup
Related T1285
## Code After:
---
# Add ddouard as jenkins admin
users:
ddouard:
groups:
- sudo
dar::backup::exclude:
- /var/lib/docker/
| ---
# Add ddouard as jenkins admin
users:
ddouard:
groups:
- sudo
+
+ dar::backup::exclude:
+ - /var/lib/docker/ | 3 | 0.428571 | 3 | 0 |
970ea3f937acd1634eaf54e3cb8ca5c5983d3fd6 | views/snippets/form_inset_radios.html | views/snippets/form_inset_radios.html | <h1 class="heading-medium">
Do you know their National Insurance number?
</h1>
<form>
<fieldset class="inline">
<legend class="visuallyhidden">Do you know their National Insurance number?</legend>
<div class="form-group">
<label class="block-label" data-target="example-ni-no" for="radio-indent-1">
<input id="radio-indent-1" type="radio" name="radio-indent-group" value="Yes">
Yes
</label>
<label class="block-label" for="radio-indent-2">
<input id="radio-indent-2" type="radio" name="radio-indent-group" value="No">
No
</label>
<div class="panel panel-border-narrow js-hidden" id="example-ni-no">
<label class="form-label" for="national-insurance">National Insurance number</label>
<input class="form-control" name="national-insurance" type="text" id="national-insurance">
</div>
</div>
</fieldset>
</form>
| <h1 class="heading-medium">
How do you want to be contacted?
</h1>
<form>
<fieldset>
<legend class="visuallyhidden">How do you want to be contacted?</legend>
<div class="form-group">
<label class="block-label" data-target="contact-by-email" for="example-contact-by-email">
<input id="example-contact-by-email" type="radio" name="radio-contact-group" value="Yes">
Email
</label>
<div class="panel panel-border-narrow js-hidden" id="contact-by-email">
<label class="form-label" for="contact-email">Email address</label>
<input class="form-control" name="contact-email" type="text" id="contact-email">
</div>
<label class="block-label" data-target="contact-by-phone" for="example-contact-by-phone">
<input id="example-contact-by-phone" type="radio" name="radio-contact-group" value="No">
Phone
</label>
<div class="panel panel-border-narrow js-hidden" id="contact-by-phone">
<label class="form-label" for="contact-phone">Phone number</label>
<input class="form-control" name="contact-phone" type="text" id="contact-phone">
</div>
<label class="block-label" data-target="contact-by-text" for="example-contact-by-text">
<input id="example-contact-by-text" type="radio" name="radio-contact-group" value="No">
Text message
</label>
<div class="panel panel-border-narrow js-hidden" id="contact-by-text">
<label class="form-label" for="contact-text-message">Mobile phone number</label>
<input class="form-control" name="contact-text-message" type="text" id="contact-text-message">
</div>
</div>
</fieldset>
</form>
| Add a new example for conditionally revealed content | Add a new example for conditionally revealed content
This example has three options, each option reveals an extra field - where it is
possible to enter more information.
| HTML | mit | joelanman/govuk_elements,joelanman/govuk_elements,alphagov/govuk_elements,alphagov/govuk_elements,alphagov/govuk_elements,alphagov/govuk_elements,gavboulton/govuk_elements,gavboulton/govuk_elements,gavboulton/govuk_elements,gavboulton/govuk_elements | html | ## Code Before:
<h1 class="heading-medium">
Do you know their National Insurance number?
</h1>
<form>
<fieldset class="inline">
<legend class="visuallyhidden">Do you know their National Insurance number?</legend>
<div class="form-group">
<label class="block-label" data-target="example-ni-no" for="radio-indent-1">
<input id="radio-indent-1" type="radio" name="radio-indent-group" value="Yes">
Yes
</label>
<label class="block-label" for="radio-indent-2">
<input id="radio-indent-2" type="radio" name="radio-indent-group" value="No">
No
</label>
<div class="panel panel-border-narrow js-hidden" id="example-ni-no">
<label class="form-label" for="national-insurance">National Insurance number</label>
<input class="form-control" name="national-insurance" type="text" id="national-insurance">
</div>
</div>
</fieldset>
</form>
## Instruction:
Add a new example for conditionally revealed content
This example has three options, each option reveals an extra field - where it is
possible to enter more information.
## Code After:
<h1 class="heading-medium">
How do you want to be contacted?
</h1>
<form>
<fieldset>
<legend class="visuallyhidden">How do you want to be contacted?</legend>
<div class="form-group">
<label class="block-label" data-target="contact-by-email" for="example-contact-by-email">
<input id="example-contact-by-email" type="radio" name="radio-contact-group" value="Yes">
Email
</label>
<div class="panel panel-border-narrow js-hidden" id="contact-by-email">
<label class="form-label" for="contact-email">Email address</label>
<input class="form-control" name="contact-email" type="text" id="contact-email">
</div>
<label class="block-label" data-target="contact-by-phone" for="example-contact-by-phone">
<input id="example-contact-by-phone" type="radio" name="radio-contact-group" value="No">
Phone
</label>
<div class="panel panel-border-narrow js-hidden" id="contact-by-phone">
<label class="form-label" for="contact-phone">Phone number</label>
<input class="form-control" name="contact-phone" type="text" id="contact-phone">
</div>
<label class="block-label" data-target="contact-by-text" for="example-contact-by-text">
<input id="example-contact-by-text" type="radio" name="radio-contact-group" value="No">
Text message
</label>
<div class="panel panel-border-narrow js-hidden" id="contact-by-text">
<label class="form-label" for="contact-text-message">Mobile phone number</label>
<input class="form-control" name="contact-text-message" type="text" id="contact-text-message">
</div>
</div>
</fieldset>
</form>
| <h1 class="heading-medium">
- Do you know their National Insurance number?
+ How do you want to be contacted?
</h1>
<form>
- <fieldset class="inline">
+ <fieldset>
- <legend class="visuallyhidden">Do you know their National Insurance number?</legend>
+ <legend class="visuallyhidden">How do you want to be contacted?</legend>
<div class="form-group">
- <label class="block-label" data-target="example-ni-no" for="radio-indent-1">
+ <label class="block-label" data-target="contact-by-email" for="example-contact-by-email">
- <input id="radio-indent-1" type="radio" name="radio-indent-group" value="Yes">
? ^ ^^ ----- ^ ^ ^^^
+ <input id="example-contact-by-email" type="radio" name="radio-contact-group" value="Yes">
? ^^ ^^^^^^ +++ ^^^^^^^^ ^^ ^^^
- Yes
+ Email
</label>
+ <div class="panel panel-border-narrow js-hidden" id="contact-by-email">
+ <label class="form-label" for="contact-email">Email address</label>
+ <input class="form-control" name="contact-email" type="text" id="contact-email">
+ </div>
- <label class="block-label" for="radio-indent-2">
+ <label class="block-label" data-target="contact-by-phone" for="example-contact-by-phone">
- <input id="radio-indent-2" type="radio" name="radio-indent-group" value="No">
? ^ ^^ ----- ^ ^ ^^^
+ <input id="example-contact-by-phone" type="radio" name="radio-contact-group" value="No">
? ^^ ^^^^^^ +++ ^^^^^^^^ ^^ ^^^
- No
? ^
+ Phone
? ^^ ++
</label>
+ <div class="panel panel-border-narrow js-hidden" id="contact-by-phone">
+ <label class="form-label" for="contact-phone">Phone number</label>
+ <input class="form-control" name="contact-phone" type="text" id="contact-phone">
+ </div>
+ <label class="block-label" data-target="contact-by-text" for="example-contact-by-text">
+ <input id="example-contact-by-text" type="radio" name="radio-contact-group" value="No">
+ Text message
+ </label>
- <div class="panel panel-border-narrow js-hidden" id="example-ni-no">
? ^^^^^^^^^^^
+ <div class="panel panel-border-narrow js-hidden" id="contact-by-text">
? ++++++++++++ ^
- <label class="form-label" for="national-insurance">National Insurance number</label>
+ <label class="form-label" for="contact-text-message">Mobile phone number</label>
- <input class="form-control" name="national-insurance" type="text" id="national-insurance">
? ^^^^ ^ ^^ ^^ ^^ ^^^^ ^ ^^ ^^ ^^
+ <input class="form-control" name="contact-text-message" type="text" id="contact-text-message">
? ^ + ^^ ^^^^^^^ ^ ^ ^ + ^^ ^^^^^^^ ^ ^
</div>
</div>
</fieldset>
</form> | 36 | 1.2 | 24 | 12 |
a31a10ba386bbc0129c078791bba05ce1de34e2d | logging_config.js | logging_config.js | /* eslint-disable no-unused-vars, no-var */
// Logging configuration
var loggingConfig = {
// default log level for the app and lib-jitsi-meet
defaultLogLevel: 'trace',
// Option to disable LogCollector (which stores the logs on CallStats)
// disableLogCollector: true,
// The following are too verbose in their logging with the
// {@link #defaultLogLevel}:
'modules/RTC/TraceablePeerConnection.js': 'info',
'modules/statistics/CallStats.js': 'info',
'modules/sdp/SDPUtil.js': 'info',
'modules/xmpp/JingleSessionPC.js': 'info',
'modules/xmpp/strophe.jingle.js': 'info',
'modules/xmpp/strophe.util.js': 'log'
};
/* eslint-enable no-unused-vars, no-var */
// XXX Web/React server-includes logging_config.js into index.html.
// Mobile/react-native requires it in react/features/base/logging. For the
// purposes of the latter, (try to) export loggingConfig. The following
// detection of a module system is inspired by webpack.
typeof module === 'object'
&& typeof exports === 'object'
&& (module.exports = loggingConfig);
| /* eslint-disable no-unused-vars, no-var */
// Logging configuration
var loggingConfig = {
// default log level for the app and lib-jitsi-meet
defaultLogLevel: 'trace',
// Option to disable LogCollector (which stores the logs on CallStats)
// disableLogCollector: true,
// The following are too verbose in their logging with the
// {@link #defaultLogLevel}:
'modules/RTC/TraceablePeerConnection.js': 'info',
'modules/statistics/CallStats.js': 'info',
'modules/xmpp/strophe.util.js': 'log'
};
/* eslint-enable no-unused-vars, no-var */
// XXX Web/React server-includes logging_config.js into index.html.
// Mobile/react-native requires it in react/features/base/logging. For the
// purposes of the latter, (try to) export loggingConfig. The following
// detection of a module system is inspired by webpack.
typeof module === 'object'
&& typeof exports === 'object'
&& (module.exports = loggingConfig);
| Set the log level to debug again. Plan is to make the Strophe logs more restrictive. Revert "fix(logging) reduce overly vebose logging" | fix(logging): Set the log level to debug again.
Plan is to make the Strophe logs more restrictive.
Revert "fix(logging) reduce overly vebose logging"
This reverts commit 09af88088ded3ab5e8343f6ebedeffc8d752f95f.
| JavaScript | apache-2.0 | gpolitis/jitsi-meet,gpolitis/jitsi-meet,jitsi/jitsi-meet,gpolitis/jitsi-meet,jitsi/jitsi-meet,gpolitis/jitsi-meet,jitsi/jitsi-meet,gpolitis/jitsi-meet,jitsi/jitsi-meet,jitsi/jitsi-meet,gpolitis/jitsi-meet,jitsi/jitsi-meet,jitsi/jitsi-meet,jitsi/jitsi-meet,gpolitis/jitsi-meet,gpolitis/jitsi-meet | javascript | ## Code Before:
/* eslint-disable no-unused-vars, no-var */
// Logging configuration
var loggingConfig = {
// default log level for the app and lib-jitsi-meet
defaultLogLevel: 'trace',
// Option to disable LogCollector (which stores the logs on CallStats)
// disableLogCollector: true,
// The following are too verbose in their logging with the
// {@link #defaultLogLevel}:
'modules/RTC/TraceablePeerConnection.js': 'info',
'modules/statistics/CallStats.js': 'info',
'modules/sdp/SDPUtil.js': 'info',
'modules/xmpp/JingleSessionPC.js': 'info',
'modules/xmpp/strophe.jingle.js': 'info',
'modules/xmpp/strophe.util.js': 'log'
};
/* eslint-enable no-unused-vars, no-var */
// XXX Web/React server-includes logging_config.js into index.html.
// Mobile/react-native requires it in react/features/base/logging. For the
// purposes of the latter, (try to) export loggingConfig. The following
// detection of a module system is inspired by webpack.
typeof module === 'object'
&& typeof exports === 'object'
&& (module.exports = loggingConfig);
## Instruction:
fix(logging): Set the log level to debug again.
Plan is to make the Strophe logs more restrictive.
Revert "fix(logging) reduce overly vebose logging"
This reverts commit 09af88088ded3ab5e8343f6ebedeffc8d752f95f.
## Code After:
/* eslint-disable no-unused-vars, no-var */
// Logging configuration
var loggingConfig = {
// default log level for the app and lib-jitsi-meet
defaultLogLevel: 'trace',
// Option to disable LogCollector (which stores the logs on CallStats)
// disableLogCollector: true,
// The following are too verbose in their logging with the
// {@link #defaultLogLevel}:
'modules/RTC/TraceablePeerConnection.js': 'info',
'modules/statistics/CallStats.js': 'info',
'modules/xmpp/strophe.util.js': 'log'
};
/* eslint-enable no-unused-vars, no-var */
// XXX Web/React server-includes logging_config.js into index.html.
// Mobile/react-native requires it in react/features/base/logging. For the
// purposes of the latter, (try to) export loggingConfig. The following
// detection of a module system is inspired by webpack.
typeof module === 'object'
&& typeof exports === 'object'
&& (module.exports = loggingConfig);
| /* eslint-disable no-unused-vars, no-var */
// Logging configuration
var loggingConfig = {
// default log level for the app and lib-jitsi-meet
defaultLogLevel: 'trace',
// Option to disable LogCollector (which stores the logs on CallStats)
// disableLogCollector: true,
// The following are too verbose in their logging with the
// {@link #defaultLogLevel}:
'modules/RTC/TraceablePeerConnection.js': 'info',
'modules/statistics/CallStats.js': 'info',
- 'modules/sdp/SDPUtil.js': 'info',
- 'modules/xmpp/JingleSessionPC.js': 'info',
- 'modules/xmpp/strophe.jingle.js': 'info',
'modules/xmpp/strophe.util.js': 'log'
};
/* eslint-enable no-unused-vars, no-var */
// XXX Web/React server-includes logging_config.js into index.html.
// Mobile/react-native requires it in react/features/base/logging. For the
// purposes of the latter, (try to) export loggingConfig. The following
// detection of a module system is inspired by webpack.
typeof module === 'object'
&& typeof exports === 'object'
&& (module.exports = loggingConfig); | 3 | 0.103448 | 0 | 3 |
f34650bb0c657f97f3272a6dde712a4d0088c196 | .github/workflows/cabin.yml | .github/workflows/cabin.yml | name: Cabin CI
on:
push:
branches: [ master ]
pull_request:
branches: [ master ]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/setup-go@v2
- name: Install SSH Key
uses: shimataro/ssh-key-action@v2
with:
key: ${{ secrets.SSH_PRIVATE_KEY }}
known_hosts: 'just-a-placeholder-so-we-dont-get-errors'
- name: Adding Known Hosts
run: ssh-keyscan -H thanksgiving.dinnen.engineering >> ~/.ssh/known_hosts
- name: Stop Pi
run: ssh pi@thanksgiving.dinnen.engineering "sudo systemctl stop analyzer"
- name: Build Arduino
run: |
ssh pi@thanksgiving.dinnen.engineering "cd /home/pi/Thanksgiving_Intranet/Arduino_Software; git pull; make"
- name: Build Analyzer
run: |
cd analyzer
export PATH=$PATH:$(go env GOPATH)/bin
make compile
rsync -z --progress ./build/analyzer-linux-arm-5 pi@thanksgiving.dinnen.engineering:~/go/bin/analyzer
- name: Start Pi
run: ssh pi@thanksgiving.dinnen.engineering "sudo systemctl start analyzer"
| name: Cabin CI
on:
push:
branches: [ master ]
pull_request:
branches: [ master ]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/setup-go@v2
- name: Install SSH Key
uses: shimataro/ssh-key-action@v2
with:
key: ${{ secrets.SSH_PRIVATE_KEY }}
known_hosts: 'just-a-placeholder-so-we-dont-get-errors'
- name: Adding Known Hosts
run: ssh-keyscan -H thanksgiving.dinnen.engineering >> ~/.ssh/known_hosts
- name: Stop Pi
run: ssh pi@thanksgiving.dinnen.engineering "sudo systemctl stop analyzer"
- name: Build Arduino
run: |
ssh pi@thanksgiving.dinnen.engineering "cd /home/pi/Thanksgiving_Intranet/Arduino_Software; git pull; make"
- name: Build Analyzer
run: |
cd analyzer
export PATH=$PATH:$(go env GOPATH)/bin
make compile
rsync -z --progress ./build/analyzer-linux-arm-5 pi@thanksgiving.dinnen.engineering:~/go/bin/analyzer
cd ..
- name: Build Frontend
run: |
cd frontend
yarn
yarn build
yarn upload
- name: Start Pi
run: ssh pi@thanksgiving.dinnen.engineering "sudo systemctl start analyzer"
| Build and upload frontend via CI | Build and upload frontend via CI
| YAML | mit | edinnen/Thanksgiving_Intranet,edinnen/Thanksgiving_Intranet,edinnen/Thanksgiving_Intranet | yaml | ## Code Before:
name: Cabin CI
on:
push:
branches: [ master ]
pull_request:
branches: [ master ]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/setup-go@v2
- name: Install SSH Key
uses: shimataro/ssh-key-action@v2
with:
key: ${{ secrets.SSH_PRIVATE_KEY }}
known_hosts: 'just-a-placeholder-so-we-dont-get-errors'
- name: Adding Known Hosts
run: ssh-keyscan -H thanksgiving.dinnen.engineering >> ~/.ssh/known_hosts
- name: Stop Pi
run: ssh pi@thanksgiving.dinnen.engineering "sudo systemctl stop analyzer"
- name: Build Arduino
run: |
ssh pi@thanksgiving.dinnen.engineering "cd /home/pi/Thanksgiving_Intranet/Arduino_Software; git pull; make"
- name: Build Analyzer
run: |
cd analyzer
export PATH=$PATH:$(go env GOPATH)/bin
make compile
rsync -z --progress ./build/analyzer-linux-arm-5 pi@thanksgiving.dinnen.engineering:~/go/bin/analyzer
- name: Start Pi
run: ssh pi@thanksgiving.dinnen.engineering "sudo systemctl start analyzer"
## Instruction:
Build and upload frontend via CI
## Code After:
name: Cabin CI
on:
push:
branches: [ master ]
pull_request:
branches: [ master ]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/setup-go@v2
- name: Install SSH Key
uses: shimataro/ssh-key-action@v2
with:
key: ${{ secrets.SSH_PRIVATE_KEY }}
known_hosts: 'just-a-placeholder-so-we-dont-get-errors'
- name: Adding Known Hosts
run: ssh-keyscan -H thanksgiving.dinnen.engineering >> ~/.ssh/known_hosts
- name: Stop Pi
run: ssh pi@thanksgiving.dinnen.engineering "sudo systemctl stop analyzer"
- name: Build Arduino
run: |
ssh pi@thanksgiving.dinnen.engineering "cd /home/pi/Thanksgiving_Intranet/Arduino_Software; git pull; make"
- name: Build Analyzer
run: |
cd analyzer
export PATH=$PATH:$(go env GOPATH)/bin
make compile
rsync -z --progress ./build/analyzer-linux-arm-5 pi@thanksgiving.dinnen.engineering:~/go/bin/analyzer
cd ..
- name: Build Frontend
run: |
cd frontend
yarn
yarn build
yarn upload
- name: Start Pi
run: ssh pi@thanksgiving.dinnen.engineering "sudo systemctl start analyzer"
| name: Cabin CI
on:
push:
branches: [ master ]
pull_request:
branches: [ master ]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/setup-go@v2
- name: Install SSH Key
uses: shimataro/ssh-key-action@v2
with:
key: ${{ secrets.SSH_PRIVATE_KEY }}
known_hosts: 'just-a-placeholder-so-we-dont-get-errors'
- name: Adding Known Hosts
run: ssh-keyscan -H thanksgiving.dinnen.engineering >> ~/.ssh/known_hosts
- name: Stop Pi
run: ssh pi@thanksgiving.dinnen.engineering "sudo systemctl stop analyzer"
- name: Build Arduino
run: |
ssh pi@thanksgiving.dinnen.engineering "cd /home/pi/Thanksgiving_Intranet/Arduino_Software; git pull; make"
- name: Build Analyzer
run: |
cd analyzer
export PATH=$PATH:$(go env GOPATH)/bin
make compile
rsync -z --progress ./build/analyzer-linux-arm-5 pi@thanksgiving.dinnen.engineering:~/go/bin/analyzer
+ cd ..
+ - name: Build Frontend
+ run: |
+ cd frontend
+ yarn
+ yarn build
+ yarn upload
- name: Start Pi
run: ssh pi@thanksgiving.dinnen.engineering "sudo systemctl start analyzer" | 7 | 0.194444 | 7 | 0 |
6557a6100bb01b3f7dd60d091f580cc8e7a5c370 | source/main.js | source/main.js | /**
* @license Angular UI Tree v2.10.0
* (c) 2010-2015. https://github.com/angular-ui-tree/angular-ui-tree
* License: MIT
*/
(function () {
'use strict';
angular.module('ui.tree', [])
.constant('treeConfig', {
treeClass: 'angular-ui-tree',
emptyTreeClass: 'angular-ui-tree-empty',
hiddenClass: 'angular-ui-tree-hidden',
nodesClass: 'angular-ui-tree-nodes',
nodeClass: 'angular-ui-tree-node',
handleClass: 'angular-ui-tree-handle',
placeholderClass: 'angular-ui-tree-placeholder',
dragClass: 'angular-ui-tree-drag',
dragThreshold: 3,
levelThreshold: 30
});
})();
| /**
* @license Angular UI Tree v2.10.0
* (c) 2010-2015. https://github.com/angular-ui-tree/angular-ui-tree
* License: MIT
*/
(function () {
'use strict';
angular.module('ui.tree', [])
.constant('treeConfig', {
treeClass: 'angular-ui-tree',
emptyTreeClass: 'angular-ui-tree-empty',
hiddenClass: 'angular-ui-tree-hidden',
nodesClass: 'angular-ui-tree-nodes',
nodeClass: 'angular-ui-tree-node',
handleClass: 'angular-ui-tree-handle',
placeholderClass: 'angular-ui-tree-placeholder',
dragClass: 'angular-ui-tree-drag',
dragThreshold: 3,
levelThreshold: 30,
defaultCollapsed: false
});
})();
| Add 'defaultCollapsed' option to treeConfig | Add 'defaultCollapsed' option to treeConfig | JavaScript | mit | angular-ui-tree/angular-ui-tree,foglerek/angular-ui-tree,zachlysobey/angular-ui-tree | javascript | ## Code Before:
/**
* @license Angular UI Tree v2.10.0
* (c) 2010-2015. https://github.com/angular-ui-tree/angular-ui-tree
* License: MIT
*/
(function () {
'use strict';
angular.module('ui.tree', [])
.constant('treeConfig', {
treeClass: 'angular-ui-tree',
emptyTreeClass: 'angular-ui-tree-empty',
hiddenClass: 'angular-ui-tree-hidden',
nodesClass: 'angular-ui-tree-nodes',
nodeClass: 'angular-ui-tree-node',
handleClass: 'angular-ui-tree-handle',
placeholderClass: 'angular-ui-tree-placeholder',
dragClass: 'angular-ui-tree-drag',
dragThreshold: 3,
levelThreshold: 30
});
})();
## Instruction:
Add 'defaultCollapsed' option to treeConfig
## Code After:
/**
* @license Angular UI Tree v2.10.0
* (c) 2010-2015. https://github.com/angular-ui-tree/angular-ui-tree
* License: MIT
*/
(function () {
'use strict';
angular.module('ui.tree', [])
.constant('treeConfig', {
treeClass: 'angular-ui-tree',
emptyTreeClass: 'angular-ui-tree-empty',
hiddenClass: 'angular-ui-tree-hidden',
nodesClass: 'angular-ui-tree-nodes',
nodeClass: 'angular-ui-tree-node',
handleClass: 'angular-ui-tree-handle',
placeholderClass: 'angular-ui-tree-placeholder',
dragClass: 'angular-ui-tree-drag',
dragThreshold: 3,
levelThreshold: 30,
defaultCollapsed: false
});
})();
| /**
* @license Angular UI Tree v2.10.0
* (c) 2010-2015. https://github.com/angular-ui-tree/angular-ui-tree
* License: MIT
*/
(function () {
'use strict';
angular.module('ui.tree', [])
.constant('treeConfig', {
treeClass: 'angular-ui-tree',
emptyTreeClass: 'angular-ui-tree-empty',
hiddenClass: 'angular-ui-tree-hidden',
nodesClass: 'angular-ui-tree-nodes',
nodeClass: 'angular-ui-tree-node',
handleClass: 'angular-ui-tree-handle',
placeholderClass: 'angular-ui-tree-placeholder',
dragClass: 'angular-ui-tree-drag',
dragThreshold: 3,
- levelThreshold: 30
+ levelThreshold: 30,
? +
+ defaultCollapsed: false
});
})(); | 3 | 0.130435 | 2 | 1 |
e34b738ea28f98de2cc039a1c0a9a0b5478f7fac | viper/common/abstracts.py | viper/common/abstracts.py |
import argparse
class ArgumentParser(argparse.ArgumentParser):
def error(self, message):
raise Exception('error: {}\n'.format(message))
class Module(object):
cmd = ''
description = ''
args = []
authors = []
output = []
def __init__(self):
self.parser = ArgumentParser(prog=self.cmd, description=self.description, add_help=False)
self.parser.add_argument('-h', '--help', action='store_true', help='show this help message')
def set_args(self, args):
self.args = args
def log(self, event_type, event_data):
self.output.append(dict(
type=event_type,
data=event_data
))
def usage(self):
self.log('', self.parser.format_usage())
def help(self):
self.log('', self.parser.format_help())
def run(self, *args):
self.parsed_args = None
try:
self.parsed_args = self.parser.parse_args(self.args)
if self.parsed_args.help:
self.help()
self.parsed_args = None
except Exception as e:
self.usage()
self.log('', e)
|
import argparse
class ArgumentErrorCallback(Exception):
def __init__(self, message, level=''):
self.message = message.strip() + '\n'
self.level = level.strip()
def __str__(self):
return '{}: {}'.format(self.level, self.message)
def get(self):
return self.level, self.message
class ArgumentParser(argparse.ArgumentParser):
def print_usage(self):
raise ArgumentErrorCallback(self.format_usage())
def print_help(self):
raise ArgumentErrorCallback(self.format_help())
def error(self, message):
raise ArgumentErrorCallback(message, 'error')
def exit(self, status, message=None):
if message is not None:
raise ArgumentErrorCallback(message)
class Module(object):
cmd = ''
description = ''
args = []
authors = []
output = []
def __init__(self):
self.parser = ArgumentParser(prog=self.cmd, description=self.description)
def set_args(self, args):
self.args = args
def log(self, event_type, event_data):
self.output.append(dict(
type=event_type,
data=event_data
))
def usage(self):
self.log('', self.parser.format_usage())
def help(self):
self.log('', self.parser.format_help())
def run(self):
self.parsed_args = None
if len(self.args) == 0:
self.usage()
else:
try:
self.parsed_args = self.parser.parse_args(self.args)
except ArgumentErrorCallback as e:
self.log(*e.get())
| Improve the error handling, better use of ArgumentParser. | Improve the error handling, better use of ArgumentParser.
| Python | bsd-3-clause | jack51706/viper,Beercow/viper,kevthehermit/viper,S2R2/viper,jorik041/viper,postfix/viper-1,cwtaylor/viper,postfix/viper-1,jack51706/viper,kevthehermit/viper,MeteorAdminz/viper,jahrome/viper,jahrome/viper,Beercow/viper,Beercow/viper,MeteorAdminz/viper,S2R2/viper,cwtaylor/viper,jorik041/viper | python | ## Code Before:
import argparse
class ArgumentParser(argparse.ArgumentParser):
def error(self, message):
raise Exception('error: {}\n'.format(message))
class Module(object):
cmd = ''
description = ''
args = []
authors = []
output = []
def __init__(self):
self.parser = ArgumentParser(prog=self.cmd, description=self.description, add_help=False)
self.parser.add_argument('-h', '--help', action='store_true', help='show this help message')
def set_args(self, args):
self.args = args
def log(self, event_type, event_data):
self.output.append(dict(
type=event_type,
data=event_data
))
def usage(self):
self.log('', self.parser.format_usage())
def help(self):
self.log('', self.parser.format_help())
def run(self, *args):
self.parsed_args = None
try:
self.parsed_args = self.parser.parse_args(self.args)
if self.parsed_args.help:
self.help()
self.parsed_args = None
except Exception as e:
self.usage()
self.log('', e)
## Instruction:
Improve the error handling, better use of ArgumentParser.
## Code After:
import argparse
class ArgumentErrorCallback(Exception):
def __init__(self, message, level=''):
self.message = message.strip() + '\n'
self.level = level.strip()
def __str__(self):
return '{}: {}'.format(self.level, self.message)
def get(self):
return self.level, self.message
class ArgumentParser(argparse.ArgumentParser):
def print_usage(self):
raise ArgumentErrorCallback(self.format_usage())
def print_help(self):
raise ArgumentErrorCallback(self.format_help())
def error(self, message):
raise ArgumentErrorCallback(message, 'error')
def exit(self, status, message=None):
if message is not None:
raise ArgumentErrorCallback(message)
class Module(object):
cmd = ''
description = ''
args = []
authors = []
output = []
def __init__(self):
self.parser = ArgumentParser(prog=self.cmd, description=self.description)
def set_args(self, args):
self.args = args
def log(self, event_type, event_data):
self.output.append(dict(
type=event_type,
data=event_data
))
def usage(self):
self.log('', self.parser.format_usage())
def help(self):
self.log('', self.parser.format_help())
def run(self):
self.parsed_args = None
if len(self.args) == 0:
self.usage()
else:
try:
self.parsed_args = self.parser.parse_args(self.args)
except ArgumentErrorCallback as e:
self.log(*e.get())
|
import argparse
+ class ArgumentErrorCallback(Exception):
+
+ def __init__(self, message, level=''):
+ self.message = message.strip() + '\n'
+ self.level = level.strip()
+
+ def __str__(self):
+ return '{}: {}'.format(self.level, self.message)
+
+ def get(self):
+ return self.level, self.message
+
+
class ArgumentParser(argparse.ArgumentParser):
+ def print_usage(self):
+ raise ArgumentErrorCallback(self.format_usage())
+
+ def print_help(self):
+ raise ArgumentErrorCallback(self.format_help())
+
def error(self, message):
- raise Exception('error: {}\n'.format(message))
+ raise ArgumentErrorCallback(message, 'error')
+
+ def exit(self, status, message=None):
+ if message is not None:
+ raise ArgumentErrorCallback(message)
class Module(object):
cmd = ''
description = ''
args = []
authors = []
output = []
def __init__(self):
- self.parser = ArgumentParser(prog=self.cmd, description=self.description, add_help=False)
? ----------------
+ self.parser = ArgumentParser(prog=self.cmd, description=self.description)
- self.parser.add_argument('-h', '--help', action='store_true', help='show this help message')
def set_args(self, args):
self.args = args
def log(self, event_type, event_data):
self.output.append(dict(
type=event_type,
data=event_data
))
def usage(self):
self.log('', self.parser.format_usage())
def help(self):
self.log('', self.parser.format_help())
- def run(self, *args):
? -------
+ def run(self):
self.parsed_args = None
+ if len(self.args) == 0:
- try:
- self.parsed_args = self.parser.parse_args(self.args)
- if self.parsed_args.help:
- self.help()
- self.parsed_args = None
- except Exception as e:
self.usage()
+ else:
+ try:
+ self.parsed_args = self.parser.parse_args(self.args)
+ except ArgumentErrorCallback as e:
- self.log('', e)
? ^^^^
+ self.log(*e.get())
? ++++ ^ +++++ +
| 43 | 0.934783 | 32 | 11 |
6a5b366b2173cdaec9cd73dd0d8ad80e5c83b169 | ummeli/vlive/templates/pml/jobs_province.xml | ummeli/vlive/templates/pml/jobs_province.xml | {% extends "base.xml" %}
{% block title %}
Ummeli
{% endblock %}
{% block content %}
<MODULE backgroundColor="false">
<HEADER><LABEL>View jobs</LABEL></HEADER>
<CONTAINER type="list">
{% for province in provinces %}
<LINK href="{% url jobs_list province.search_id %}">
<TEXT>{{province.name}}</TEXT>
</LINK>
{% endfor %}
</CONTAINER>
<br/>
<CONTAINER type="list">
<LINK href="{% url home %}">
<TEXT><< Back</TEXT>
</LINK>
</CONTAINER>
</MODULE>
{% endblock %}
| {% extends "base.xml" %}
{% block title %}
Ummeli
{% endblock %}
{% block content %}
<MODULE backgroundColor="false">
<HEADER><LABEL>View jobs</LABEL></HEADER>
<CONTAINER type="data">
<TEXT>For now, all jobs displayed here are sourced from "We Got Ads". The
aim is for the service to be expanded and work with more online job
portals from which we can source more job opportunities. Please
view the list of categories and click on those you are interested in. </TEXT>
</CONTAINER>
<br/>
<CONTAINER type="list">
{% for province in provinces %}
<LINK href="{% url jobs_list province.search_id %}">
<TEXT>{{province.name}}</TEXT>
</LINK>
{% endfor %}
</CONTAINER>
<br/>
<CONTAINER type="list">
<LINK href="{% url home %}">
<TEXT><< Back</TEXT>
</LINK>
</CONTAINER>
</MODULE>
{% endblock %}
| Add copy to View Jobs | Add copy to View Jobs
| XML | bsd-3-clause | praekelt/ummeli,praekelt/ummeli,praekelt/ummeli | xml | ## Code Before:
{% extends "base.xml" %}
{% block title %}
Ummeli
{% endblock %}
{% block content %}
<MODULE backgroundColor="false">
<HEADER><LABEL>View jobs</LABEL></HEADER>
<CONTAINER type="list">
{% for province in provinces %}
<LINK href="{% url jobs_list province.search_id %}">
<TEXT>{{province.name}}</TEXT>
</LINK>
{% endfor %}
</CONTAINER>
<br/>
<CONTAINER type="list">
<LINK href="{% url home %}">
<TEXT><< Back</TEXT>
</LINK>
</CONTAINER>
</MODULE>
{% endblock %}
## Instruction:
Add copy to View Jobs
## Code After:
{% extends "base.xml" %}
{% block title %}
Ummeli
{% endblock %}
{% block content %}
<MODULE backgroundColor="false">
<HEADER><LABEL>View jobs</LABEL></HEADER>
<CONTAINER type="data">
<TEXT>For now, all jobs displayed here are sourced from "We Got Ads". The
aim is for the service to be expanded and work with more online job
portals from which we can source more job opportunities. Please
view the list of categories and click on those you are interested in. </TEXT>
</CONTAINER>
<br/>
<CONTAINER type="list">
{% for province in provinces %}
<LINK href="{% url jobs_list province.search_id %}">
<TEXT>{{province.name}}</TEXT>
</LINK>
{% endfor %}
</CONTAINER>
<br/>
<CONTAINER type="list">
<LINK href="{% url home %}">
<TEXT><< Back</TEXT>
</LINK>
</CONTAINER>
</MODULE>
{% endblock %}
| {% extends "base.xml" %}
{% block title %}
Ummeli
{% endblock %}
{% block content %}
<MODULE backgroundColor="false">
<HEADER><LABEL>View jobs</LABEL></HEADER>
+ <CONTAINER type="data">
+ <TEXT>For now, all jobs displayed here are sourced from "We Got Ads". The
+ aim is for the service to be expanded and work with more online job
+ portals from which we can source more job opportunities. Please
+ view the list of categories and click on those you are interested in. </TEXT>
+ </CONTAINER>
+ <br/>
<CONTAINER type="list">
{% for province in provinces %}
<LINK href="{% url jobs_list province.search_id %}">
<TEXT>{{province.name}}</TEXT>
</LINK>
{% endfor %}
</CONTAINER>
<br/>
<CONTAINER type="list">
<LINK href="{% url home %}">
<TEXT><< Back</TEXT>
</LINK>
</CONTAINER>
</MODULE>
{% endblock %} | 7 | 0.291667 | 7 | 0 |
6e35979a2ccddc9bca3ca80851253be310e0c93d | index.js | index.js | var jsdom = require("jsdom");
function assign (destination, source) {
for (var key in source) {
if (source.hasOwnProperty(key)) {
destination[key] = source[key];
}
}
return destination;
}
var jsdomBrowser = function (baseBrowserDecorator, config) {
baseBrowserDecorator(this);
this.name = "jsdom";
this._start = function (url) {
if (jsdom.JSDOM) { // Indicate jsdom >= 10.0.0 and a new API
var jsdomOptions = {
resources: "usable",
runScripts: "dangerously",
virtualConsole: virtualConsole
};
if (config.jsdom) {
jsdomOptions = assign(jsdomOptions, config.jsdom);
}
jsdom.JSDOM.fromURL(url, jsdomOptions);
} else {
var jsdomOptions = {
url: url,
features : {
FetchExternalResources: ["script", "iframe"],
ProcessExternalResources: ["script"]
},
created: function (error, window) {
// Do nothing.
}
}
if (config.jsdom) {
jsdomOptions = assign(jsdomOptions, config.jsdom);
}
jsdom.env(jsdomOptions);
}
};
};
jsdomBrowser.$inject = ["baseBrowserDecorator", "config.jsdomLauncher"];
module.exports = {
"launcher:jsdom": ["type", jsdomBrowser]
};
| var jsdom = require("jsdom");
function assign (destination, source) {
for (var key in source) {
if (source.hasOwnProperty(key)) {
destination[key] = source[key];
}
}
return destination;
}
var jsdomBrowser = function (baseBrowserDecorator, config) {
baseBrowserDecorator(this);
this.name = "jsdom";
this._start = function (url) {
if (jsdom.JSDOM) { // Indicate jsdom >= 10.0.0 and a new API
var jsdomOptions = {
resources: "usable",
runScripts: "dangerously"
};
if (config.jsdom) {
jsdomOptions = assign(jsdomOptions, config.jsdom);
}
jsdom.JSDOM.fromURL(url, jsdomOptions);
} else {
var jsdomOptions = {
url: url,
features : {
FetchExternalResources: ["script", "iframe"],
ProcessExternalResources: ["script"]
},
created: function (error, window) {
// Do nothing.
}
}
if (config.jsdom) {
jsdomOptions = assign(jsdomOptions, config.jsdom);
}
jsdom.env(jsdomOptions);
}
};
};
jsdomBrowser.$inject = ["baseBrowserDecorator", "config.jsdomLauncher"];
module.exports = {
"launcher:jsdom": ["type", jsdomBrowser]
};
| Correct a mistake from 1ae32f5 | Correct a mistake from 1ae32f5
| JavaScript | mit | badeball/karma-jsdom-launcher | javascript | ## Code Before:
var jsdom = require("jsdom");
function assign (destination, source) {
for (var key in source) {
if (source.hasOwnProperty(key)) {
destination[key] = source[key];
}
}
return destination;
}
var jsdomBrowser = function (baseBrowserDecorator, config) {
baseBrowserDecorator(this);
this.name = "jsdom";
this._start = function (url) {
if (jsdom.JSDOM) { // Indicate jsdom >= 10.0.0 and a new API
var jsdomOptions = {
resources: "usable",
runScripts: "dangerously",
virtualConsole: virtualConsole
};
if (config.jsdom) {
jsdomOptions = assign(jsdomOptions, config.jsdom);
}
jsdom.JSDOM.fromURL(url, jsdomOptions);
} else {
var jsdomOptions = {
url: url,
features : {
FetchExternalResources: ["script", "iframe"],
ProcessExternalResources: ["script"]
},
created: function (error, window) {
// Do nothing.
}
}
if (config.jsdom) {
jsdomOptions = assign(jsdomOptions, config.jsdom);
}
jsdom.env(jsdomOptions);
}
};
};
jsdomBrowser.$inject = ["baseBrowserDecorator", "config.jsdomLauncher"];
module.exports = {
"launcher:jsdom": ["type", jsdomBrowser]
};
## Instruction:
Correct a mistake from 1ae32f5
## Code After:
var jsdom = require("jsdom");
function assign (destination, source) {
for (var key in source) {
if (source.hasOwnProperty(key)) {
destination[key] = source[key];
}
}
return destination;
}
var jsdomBrowser = function (baseBrowserDecorator, config) {
baseBrowserDecorator(this);
this.name = "jsdom";
this._start = function (url) {
if (jsdom.JSDOM) { // Indicate jsdom >= 10.0.0 and a new API
var jsdomOptions = {
resources: "usable",
runScripts: "dangerously"
};
if (config.jsdom) {
jsdomOptions = assign(jsdomOptions, config.jsdom);
}
jsdom.JSDOM.fromURL(url, jsdomOptions);
} else {
var jsdomOptions = {
url: url,
features : {
FetchExternalResources: ["script", "iframe"],
ProcessExternalResources: ["script"]
},
created: function (error, window) {
// Do nothing.
}
}
if (config.jsdom) {
jsdomOptions = assign(jsdomOptions, config.jsdom);
}
jsdom.env(jsdomOptions);
}
};
};
jsdomBrowser.$inject = ["baseBrowserDecorator", "config.jsdomLauncher"];
module.exports = {
"launcher:jsdom": ["type", jsdomBrowser]
};
| var jsdom = require("jsdom");
function assign (destination, source) {
for (var key in source) {
if (source.hasOwnProperty(key)) {
destination[key] = source[key];
}
}
return destination;
}
var jsdomBrowser = function (baseBrowserDecorator, config) {
baseBrowserDecorator(this);
this.name = "jsdom";
this._start = function (url) {
if (jsdom.JSDOM) { // Indicate jsdom >= 10.0.0 and a new API
var jsdomOptions = {
resources: "usable",
- runScripts: "dangerously",
? -
+ runScripts: "dangerously"
- virtualConsole: virtualConsole
};
if (config.jsdom) {
jsdomOptions = assign(jsdomOptions, config.jsdom);
}
jsdom.JSDOM.fromURL(url, jsdomOptions);
} else {
var jsdomOptions = {
url: url,
features : {
FetchExternalResources: ["script", "iframe"],
ProcessExternalResources: ["script"]
},
created: function (error, window) {
// Do nothing.
}
}
if (config.jsdom) {
jsdomOptions = assign(jsdomOptions, config.jsdom);
}
jsdom.env(jsdomOptions);
}
};
};
jsdomBrowser.$inject = ["baseBrowserDecorator", "config.jsdomLauncher"];
module.exports = {
"launcher:jsdom": ["type", jsdomBrowser]
}; | 3 | 0.053571 | 1 | 2 |
144e3b0277f5721af27be8d9edd6e3058fb21239 | README.md | README.md | 100% pure Java, simple Windows registry utility.
## Maven Integration
Binaries are not available in Maven central so you have to add this repository in your pom:
```xml
<repositories>
<repository>
<id>sarxos-repo</id>
<url>http://www.sarxos.pl/repo/maven2</url>
</repository>
</repositories>
```
Add dependency to your project:
```xml
<dependency>
<groupId>com.sarxos</groupId>
<artifactId>win-registry</artifactId>
<version>0.1</version>
</dependency>
```
## Examples
```java
Win32Reg reg = Win32Reg.getInstance();
String value = reg.readString(HKey.HKLM, "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion", "ProductName");
System.out.println("Windows Distribution = " + value);
List<String> keys = reg.readStringSubKeys(HKey.HKLM, "SOFTWARE\\Microsoft");
for (String key : keys) {
System.out.println(key);
}
```
This should print:
```
Active Setup
AD7Metrics
ADs
Advanced INF Setup
ALG
AppEnv
...
... many other entries here
...
Windows NT
Windows Portable Devices
Windows Script Host
Windows Scripting Host
Windows Search
Wisp
```
| 100% pure Java, simple Windows registry utility.
[](http://travis-ci.org/sarxos/win-registry)
## Maven Integration
Binaries are not available in Maven central so you have to add this repository in your pom:
```xml
<repositories>
<repository>
<id>sarxos-repo</id>
<url>http://www.sarxos.pl/repo/maven2</url>
</repository>
</repositories>
```
Add dependency to your project:
```xml
<dependency>
<groupId>com.sarxos</groupId>
<artifactId>win-registry</artifactId>
<version>0.1</version>
</dependency>
```
## Examples
```java
Win32Reg reg = Win32Reg.getInstance();
String value = reg.readString(HKey.HKLM, "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion", "ProductName");
System.out.println("Windows Distribution = " + value);
List<String> keys = reg.readStringSubKeys(HKey.HKLM, "SOFTWARE\\Microsoft");
for (String key : keys) {
System.out.println(key);
}
```
This should print:
```
Active Setup
AD7Metrics
ADs
Advanced INF Setup
ALG
AppEnv
...
... many other entries here
...
Windows NT
Windows Portable Devices
Windows Script Host
Windows Scripting Host
Windows Search
Wisp
```
| Add Travis build status image | Add Travis build status image
| Markdown | mit | sarxos/win-registry | markdown | ## Code Before:
100% pure Java, simple Windows registry utility.
## Maven Integration
Binaries are not available in Maven central so you have to add this repository in your pom:
```xml
<repositories>
<repository>
<id>sarxos-repo</id>
<url>http://www.sarxos.pl/repo/maven2</url>
</repository>
</repositories>
```
Add dependency to your project:
```xml
<dependency>
<groupId>com.sarxos</groupId>
<artifactId>win-registry</artifactId>
<version>0.1</version>
</dependency>
```
## Examples
```java
Win32Reg reg = Win32Reg.getInstance();
String value = reg.readString(HKey.HKLM, "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion", "ProductName");
System.out.println("Windows Distribution = " + value);
List<String> keys = reg.readStringSubKeys(HKey.HKLM, "SOFTWARE\\Microsoft");
for (String key : keys) {
System.out.println(key);
}
```
This should print:
```
Active Setup
AD7Metrics
ADs
Advanced INF Setup
ALG
AppEnv
...
... many other entries here
...
Windows NT
Windows Portable Devices
Windows Script Host
Windows Scripting Host
Windows Search
Wisp
```
## Instruction:
Add Travis build status image
## Code After:
100% pure Java, simple Windows registry utility.
[](http://travis-ci.org/sarxos/win-registry)
## Maven Integration
Binaries are not available in Maven central so you have to add this repository in your pom:
```xml
<repositories>
<repository>
<id>sarxos-repo</id>
<url>http://www.sarxos.pl/repo/maven2</url>
</repository>
</repositories>
```
Add dependency to your project:
```xml
<dependency>
<groupId>com.sarxos</groupId>
<artifactId>win-registry</artifactId>
<version>0.1</version>
</dependency>
```
## Examples
```java
Win32Reg reg = Win32Reg.getInstance();
String value = reg.readString(HKey.HKLM, "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion", "ProductName");
System.out.println("Windows Distribution = " + value);
List<String> keys = reg.readStringSubKeys(HKey.HKLM, "SOFTWARE\\Microsoft");
for (String key : keys) {
System.out.println(key);
}
```
This should print:
```
Active Setup
AD7Metrics
ADs
Advanced INF Setup
ALG
AppEnv
...
... many other entries here
...
Windows NT
Windows Portable Devices
Windows Script Host
Windows Scripting Host
Windows Search
Wisp
```
| 100% pure Java, simple Windows registry utility.
+
+ [](http://travis-ci.org/sarxos/win-registry)
## Maven Integration
Binaries are not available in Maven central so you have to add this repository in your pom:
```xml
<repositories>
<repository>
<id>sarxos-repo</id>
<url>http://www.sarxos.pl/repo/maven2</url>
</repository>
</repositories>
```
Add dependency to your project:
```xml
<dependency>
<groupId>com.sarxos</groupId>
<artifactId>win-registry</artifactId>
<version>0.1</version>
</dependency>
```
## Examples
```java
Win32Reg reg = Win32Reg.getInstance();
String value = reg.readString(HKey.HKLM, "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion", "ProductName");
System.out.println("Windows Distribution = " + value);
List<String> keys = reg.readStringSubKeys(HKey.HKLM, "SOFTWARE\\Microsoft");
for (String key : keys) {
System.out.println(key);
}
```
This should print:
```
Active Setup
AD7Metrics
ADs
Advanced INF Setup
ALG
AppEnv
...
... many other entries here
...
Windows NT
Windows Portable Devices
Windows Script Host
Windows Scripting Host
Windows Search
Wisp
``` | 2 | 0.034483 | 2 | 0 |
7c014584f848d9f7df9470ee796aaa32317a82de | db/users.js | db/users.js | var records = [
{ id: 1, username: 'jack', password: 'secret', displayName: 'Jack', emails: [ { value: 'jack@example.com' } ] }
, { id: 2, username: 'jill', password: 'birthday', displayName: 'Jill', emails: [ { value: 'jill@example.com' } ] }
];
exports.findByUsername = function(username, cb) {
process.nextTick(function() {
for (var i = 0, len = records.length; i < len; i++) {
var record = records[i];
if (record.username === username) {
return cb(null, record);
}
}
return cb(null, null);
});
}
| require('dotenv').load()
var records = [
{ id: 1, username: 'jack', password: 'secret', displayName: 'Jack', emails: [ { value: 'jack@example.com' } ] }
, { id: 2, username: 'jill', password: 'birthday', displayName: 'Jill', emails: [ { value: 'jill@example.com' } ] }
];
if (process.env.shared_secret != null && process.env.shared_secret != undefined) {
shared = {
id: records.length + 2,
username: process.env.shared_username || 'community',
password: process.env.shared_secret,
displayName: 'Community Account',
emails: [ { value: 'community@example.com' } ]
};
records.push(shared);
}
exports.findByUsername = function(username, cb) {
process.nextTick(function() {
var match = null;
var community = null;
for (var i = 0, len = records.length; i < len; i++) {
var record = records[i];
if (record.username === username) {
match = record;
break;
} else if (record.username == 'community') {
community = record;
}
}
if (match == null && community != null) {
match = community;
}
return cb(null, match);
});
}
| Support for shared secrets for authentication. | Support for shared secrets for authentication.
Provide an enviroment variable "shared_secret" and you will
be able to authenticate with any username that is not matched
in the "database." Optionally, provide "shared_username" to
set the username explicitly; otherwise, "community" will be
used.
| JavaScript | unlicense | community-lands/community-lands-monitoring-station,rfc2616/community-lands-monitoring-station,rfc2616/community-lands-monitoring-station,community-lands/community-lands-monitoring-station,community-lands/community-lands-monitoring-station,rfc2616/community-lands-monitoring-station | javascript | ## Code Before:
var records = [
{ id: 1, username: 'jack', password: 'secret', displayName: 'Jack', emails: [ { value: 'jack@example.com' } ] }
, { id: 2, username: 'jill', password: 'birthday', displayName: 'Jill', emails: [ { value: 'jill@example.com' } ] }
];
exports.findByUsername = function(username, cb) {
process.nextTick(function() {
for (var i = 0, len = records.length; i < len; i++) {
var record = records[i];
if (record.username === username) {
return cb(null, record);
}
}
return cb(null, null);
});
}
## Instruction:
Support for shared secrets for authentication.
Provide an enviroment variable "shared_secret" and you will
be able to authenticate with any username that is not matched
in the "database." Optionally, provide "shared_username" to
set the username explicitly; otherwise, "community" will be
used.
## Code After:
require('dotenv').load()
var records = [
{ id: 1, username: 'jack', password: 'secret', displayName: 'Jack', emails: [ { value: 'jack@example.com' } ] }
, { id: 2, username: 'jill', password: 'birthday', displayName: 'Jill', emails: [ { value: 'jill@example.com' } ] }
];
if (process.env.shared_secret != null && process.env.shared_secret != undefined) {
shared = {
id: records.length + 2,
username: process.env.shared_username || 'community',
password: process.env.shared_secret,
displayName: 'Community Account',
emails: [ { value: 'community@example.com' } ]
};
records.push(shared);
}
exports.findByUsername = function(username, cb) {
process.nextTick(function() {
var match = null;
var community = null;
for (var i = 0, len = records.length; i < len; i++) {
var record = records[i];
if (record.username === username) {
match = record;
break;
} else if (record.username == 'community') {
community = record;
}
}
if (match == null && community != null) {
match = community;
}
return cb(null, match);
});
}
| + require('dotenv').load()
+
var records = [
{ id: 1, username: 'jack', password: 'secret', displayName: 'Jack', emails: [ { value: 'jack@example.com' } ] }
, { id: 2, username: 'jill', password: 'birthday', displayName: 'Jill', emails: [ { value: 'jill@example.com' } ] }
];
+ if (process.env.shared_secret != null && process.env.shared_secret != undefined) {
+ shared = {
+ id: records.length + 2,
+ username: process.env.shared_username || 'community',
+ password: process.env.shared_secret,
+ displayName: 'Community Account',
+ emails: [ { value: 'community@example.com' } ]
+ };
+ records.push(shared);
+ }
+
exports.findByUsername = function(username, cb) {
process.nextTick(function() {
+ var match = null;
+ var community = null;
for (var i = 0, len = records.length; i < len; i++) {
var record = records[i];
if (record.username === username) {
- return cb(null, record);
+ match = record;
+ break;
+ } else if (record.username == 'community') {
+ community = record;
}
}
+ if (match == null && community != null) {
+ match = community;
+ }
- return cb(null, null);
? ^^^^
+ return cb(null, match);
? ^^^^^
});
} | 25 | 1.5625 | 23 | 2 |
3efca7f32465dfdaecc44fa37c95d8396d49d976 | .travis.yml | .travis.yml |
sudo: required
services:
- docker
env:
- distribution: ubuntu
version: bionic
before_install:
- curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -
- sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable"
- sudo apt-get update
- sudo apt-get -y install docker-ce
- docker --version
- 'sudo docker pull ${distribution}:${version}'
- 'sudo docker build --no-cache --rm --file=Dockerfile --tag=angular-meteor:latest .'
install:
- "sudo docker run -v ${TRAVIS_BUILD_DIR}:/angular-meteor/ --detach --name=angular-meteor-container --user docker --workdir /angular-meteor angular-meteor:latest bash -c 'source $HOME/.nvm/nvm.sh; git clean -fXd; npm cache verify; npm install -g concurrently'"
script:
- "sudo docker exec --user docker --workdir /angular-meteor angular-meteor-container bash -c 'source $HOME/.nvm/nvm.sh; /angular-meteor/run_tests.sh'" |
sudo: required
services:
- docker
env:
- distribution: ubuntu
version: bionic
before_install:
- curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -
- sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable"
- sudo apt-get update
- sudo apt-get -y install docker-ce
- docker --version
- 'sudo docker pull ${distribution}:${version}'
- 'sudo docker build --no-cache --rm --file=Dockerfile --tag=angular-meteor:latest .'
install:
- "sudo docker run -v ${TRAVIS_BUILD_DIR}:/angular-meteor/ --detach --name=angular-meteor-container --user docker --workdir /angular-meteor angular-meteor:latest bash -c 'source $HOME/.nvm/nvm.sh; git clean -fXd; npm cache verify; npm install -g concurrently'"
before_script:
- "sudo docker exec --user root --workdir /angular-meteor angular-meteor-container bash -c 'chown -R docker /angular-meteor'"
script:
- "sudo docker exec --user docker --workdir /angular-meteor angular-meteor-container bash -c 'source $HOME/.nvm/nvm.sh; /angular-meteor/run_tests.sh'" | Update ownership of source code directory. | Update ownership of source code directory.
| YAML | mit | Urigo/angular-meteor | yaml | ## Code Before:
sudo: required
services:
- docker
env:
- distribution: ubuntu
version: bionic
before_install:
- curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -
- sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable"
- sudo apt-get update
- sudo apt-get -y install docker-ce
- docker --version
- 'sudo docker pull ${distribution}:${version}'
- 'sudo docker build --no-cache --rm --file=Dockerfile --tag=angular-meteor:latest .'
install:
- "sudo docker run -v ${TRAVIS_BUILD_DIR}:/angular-meteor/ --detach --name=angular-meteor-container --user docker --workdir /angular-meteor angular-meteor:latest bash -c 'source $HOME/.nvm/nvm.sh; git clean -fXd; npm cache verify; npm install -g concurrently'"
script:
- "sudo docker exec --user docker --workdir /angular-meteor angular-meteor-container bash -c 'source $HOME/.nvm/nvm.sh; /angular-meteor/run_tests.sh'"
## Instruction:
Update ownership of source code directory.
## Code After:
sudo: required
services:
- docker
env:
- distribution: ubuntu
version: bionic
before_install:
- curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -
- sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable"
- sudo apt-get update
- sudo apt-get -y install docker-ce
- docker --version
- 'sudo docker pull ${distribution}:${version}'
- 'sudo docker build --no-cache --rm --file=Dockerfile --tag=angular-meteor:latest .'
install:
- "sudo docker run -v ${TRAVIS_BUILD_DIR}:/angular-meteor/ --detach --name=angular-meteor-container --user docker --workdir /angular-meteor angular-meteor:latest bash -c 'source $HOME/.nvm/nvm.sh; git clean -fXd; npm cache verify; npm install -g concurrently'"
before_script:
- "sudo docker exec --user root --workdir /angular-meteor angular-meteor-container bash -c 'chown -R docker /angular-meteor'"
script:
- "sudo docker exec --user docker --workdir /angular-meteor angular-meteor-container bash -c 'source $HOME/.nvm/nvm.sh; /angular-meteor/run_tests.sh'" |
sudo: required
services:
- docker
env:
- distribution: ubuntu
version: bionic
before_install:
- curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -
- sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable"
- sudo apt-get update
- sudo apt-get -y install docker-ce
- docker --version
- 'sudo docker pull ${distribution}:${version}'
- 'sudo docker build --no-cache --rm --file=Dockerfile --tag=angular-meteor:latest .'
install:
- "sudo docker run -v ${TRAVIS_BUILD_DIR}:/angular-meteor/ --detach --name=angular-meteor-container --user docker --workdir /angular-meteor angular-meteor:latest bash -c 'source $HOME/.nvm/nvm.sh; git clean -fXd; npm cache verify; npm install -g concurrently'"
+ before_script:
+ - "sudo docker exec --user root --workdir /angular-meteor angular-meteor-container bash -c 'chown -R docker /angular-meteor'"
script:
- "sudo docker exec --user docker --workdir /angular-meteor angular-meteor-container bash -c 'source $HOME/.nvm/nvm.sh; /angular-meteor/run_tests.sh'" | 2 | 0.105263 | 2 | 0 |
11b3cdaca791c8330180b09a1c940c9b87d39e72 | lib/vagrant-snap/providers/virtualbox/driver/base.rb | lib/vagrant-snap/providers/virtualbox/driver/base.rb | module VagrantPlugins
module ProviderVirtualBox
module Driver
class Base
def snapshot_take
execute("snapshot", @uuid, "take", "vagrant-snap", "--pause")
end
def snapshot_rollback(bootmode)
halt
sleep 2 # race condition on locked VMs otherwise?
execute("snapshot", @uuid, "restorecurrent")
start(bootmode)
end
end
end
end
end
| module VagrantPlugins
module ProviderVirtualBox
module Driver
class Base
def snapshot_take
execute("snapshot", @uuid, "take", "vagrant-snap-#{Time.now.to_i}", "--pause")
end
def snapshot_rollback(bootmode)
halt
sleep 2 # race condition on locked VMs otherwise?
execute("snapshot", @uuid, "restorecurrent")
start(bootmode)
end
end
end
end
end
| Make snapshot name more unique | Make snapshot name more unique
| Ruby | mit | scalefactory/vagrant-multiprovider-snap | ruby | ## Code Before:
module VagrantPlugins
module ProviderVirtualBox
module Driver
class Base
def snapshot_take
execute("snapshot", @uuid, "take", "vagrant-snap", "--pause")
end
def snapshot_rollback(bootmode)
halt
sleep 2 # race condition on locked VMs otherwise?
execute("snapshot", @uuid, "restorecurrent")
start(bootmode)
end
end
end
end
end
## Instruction:
Make snapshot name more unique
## Code After:
module VagrantPlugins
module ProviderVirtualBox
module Driver
class Base
def snapshot_take
execute("snapshot", @uuid, "take", "vagrant-snap-#{Time.now.to_i}", "--pause")
end
def snapshot_rollback(bootmode)
halt
sleep 2 # race condition on locked VMs otherwise?
execute("snapshot", @uuid, "restorecurrent")
start(bootmode)
end
end
end
end
end
| module VagrantPlugins
module ProviderVirtualBox
module Driver
class Base
def snapshot_take
- execute("snapshot", @uuid, "take", "vagrant-snap", "--pause")
+ execute("snapshot", @uuid, "take", "vagrant-snap-#{Time.now.to_i}", "--pause")
? +++++++++++++++++
end
def snapshot_rollback(bootmode)
halt
sleep 2 # race condition on locked VMs otherwise?
execute("snapshot", @uuid, "restorecurrent")
start(bootmode)
end
end
end
end
end | 2 | 0.074074 | 1 | 1 |
ed15ef8fafb3bdeb24f26e2a5036401ffb42377c | lib/run.js | lib/run.js | /* jshint node: true */
var Promise = require('ember-cli/lib/ext/promise');
var spawn = require('child_process').spawn;
function run(command, args, opts) {
return new Promise(function(resolve, reject) {
var p = spawn(command, args, opts || {});
var stderr = '';
var stdout = '';
p.stdout.on('data', function(output) {
stdout += output;
});
p.stderr.on('data', function(output) {
stderr += output;
});
p.on('close', function(code){
if (code !== 0) {
var err = new Error(command + " " + args.join(" ") + " exited with nonzero status");
err.stderr = stderr;
err.stdout = stdout;
reject(err);
} else {
resolve({ stdout: stdout, stderr: stderr });
}
});
});
}
module.exports = run;
| /* jshint node: true */
var RSVP = require('rsvp');
var spawn = require('child_process').spawn;
function run(command, args, opts) {
return new RSVP.Promise(function(resolve, reject) {
var p = spawn(command, args, opts || {});
var stderr = '';
var stdout = '';
p.stdout.on('data', function(output) {
stdout += output;
});
p.stderr.on('data', function(output) {
stderr += output;
});
p.on('close', function(code){
if (code !== 0) {
var err = new Error(command + " " + args.join(" ") + " exited with nonzero status");
err.stderr = stderr;
err.stdout = stdout;
reject(err);
} else {
resolve({ stdout: stdout, stderr: stderr });
}
});
});
}
module.exports = run;
| Use RSVP instead of ember-cli/ext/promise | Use RSVP instead of ember-cli/ext/promise
| JavaScript | mit | ef4/ember-cli-deploy-git | javascript | ## Code Before:
/* jshint node: true */
var Promise = require('ember-cli/lib/ext/promise');
var spawn = require('child_process').spawn;
function run(command, args, opts) {
return new Promise(function(resolve, reject) {
var p = spawn(command, args, opts || {});
var stderr = '';
var stdout = '';
p.stdout.on('data', function(output) {
stdout += output;
});
p.stderr.on('data', function(output) {
stderr += output;
});
p.on('close', function(code){
if (code !== 0) {
var err = new Error(command + " " + args.join(" ") + " exited with nonzero status");
err.stderr = stderr;
err.stdout = stdout;
reject(err);
} else {
resolve({ stdout: stdout, stderr: stderr });
}
});
});
}
module.exports = run;
## Instruction:
Use RSVP instead of ember-cli/ext/promise
## Code After:
/* jshint node: true */
var RSVP = require('rsvp');
var spawn = require('child_process').spawn;
function run(command, args, opts) {
return new RSVP.Promise(function(resolve, reject) {
var p = spawn(command, args, opts || {});
var stderr = '';
var stdout = '';
p.stdout.on('data', function(output) {
stdout += output;
});
p.stderr.on('data', function(output) {
stderr += output;
});
p.on('close', function(code){
if (code !== 0) {
var err = new Error(command + " " + args.join(" ") + " exited with nonzero status");
err.stderr = stderr;
err.stdout = stdout;
reject(err);
} else {
resolve({ stdout: stdout, stderr: stderr });
}
});
});
}
module.exports = run;
| /* jshint node: true */
- var Promise = require('ember-cli/lib/ext/promise');
+ var RSVP = require('rsvp');
var spawn = require('child_process').spawn;
function run(command, args, opts) {
- return new Promise(function(resolve, reject) {
+ return new RSVP.Promise(function(resolve, reject) {
? +++++
var p = spawn(command, args, opts || {});
var stderr = '';
var stdout = '';
p.stdout.on('data', function(output) {
stdout += output;
});
p.stderr.on('data', function(output) {
stderr += output;
});
p.on('close', function(code){
if (code !== 0) {
var err = new Error(command + " " + args.join(" ") + " exited with nonzero status");
err.stderr = stderr;
err.stdout = stdout;
reject(err);
} else {
resolve({ stdout: stdout, stderr: stderr });
}
});
});
}
module.exports = run; | 4 | 0.133333 | 2 | 2 |
3686c4298d38ca314e5363aa26974d7a1d8171f1 | src/main/kotlin/controllers/AlbumController.kt | src/main/kotlin/controllers/AlbumController.kt | package controllers
import models.Album
import spark.ModelAndView
import spark.Request
import spark.Response
import templates.AlbumTemplate
/**
* Created by allen on 4/11/17.
*/
object AlbumController{
fun index(request: Request, response: Response): String {
return AlbumTemplate.index(SqliteController.selectAllFolders(), SqliteController.selectAllAlbums())
}
fun show(request: Request, response: Response, albumIdParameterName: String): String {
val album: Album = SqliteController.selectAlbum(request.params(albumIdParameterName)) ?: return ErrorController.notFound(request, response)
return AlbumTemplate.show(SqliteController.selectAllFolders(), album, SqliteController.imagesForAlbum(request.params(albumIdParameterName)))
//return ModelAndView(hashMapOf(Pair("folders", SqliteController.selectAllFolders()), Pair("images", SqliteController.imagesForAlbum(request.params(albumIdParameterName))), Pair("album", album)), "album_show.hbs")
}
} | package controllers
import models.Album
import spark.ModelAndView
import spark.Request
import spark.Response
import templates.AlbumTemplate
/**
* Created by allen on 4/11/17.
*/
object AlbumController{
fun index(request: Request, response: Response): String {
return AlbumTemplate.index(SqliteController.selectAllFolders(), SqliteController.selectAllAlbums())
}
fun show(request: Request, response: Response, albumIdParameterName: String): String {
val album: Album = SqliteController.selectAlbum(request.params(albumIdParameterName)) ?: return ErrorController.notFound(request, response)
return AlbumTemplate.show(SqliteController.selectAllFolders(), album, SqliteController.imagesForAlbum(request.params(albumIdParameterName)))
}
} | Remove dead code since handlebars is no longer being used | Remove dead code since handlebars is no longer being used
| Kotlin | mit | allen-garvey/photog-spark,allen-garvey/photog-spark,allen-garvey/photog-spark | kotlin | ## Code Before:
package controllers
import models.Album
import spark.ModelAndView
import spark.Request
import spark.Response
import templates.AlbumTemplate
/**
* Created by allen on 4/11/17.
*/
object AlbumController{
fun index(request: Request, response: Response): String {
return AlbumTemplate.index(SqliteController.selectAllFolders(), SqliteController.selectAllAlbums())
}
fun show(request: Request, response: Response, albumIdParameterName: String): String {
val album: Album = SqliteController.selectAlbum(request.params(albumIdParameterName)) ?: return ErrorController.notFound(request, response)
return AlbumTemplate.show(SqliteController.selectAllFolders(), album, SqliteController.imagesForAlbum(request.params(albumIdParameterName)))
//return ModelAndView(hashMapOf(Pair("folders", SqliteController.selectAllFolders()), Pair("images", SqliteController.imagesForAlbum(request.params(albumIdParameterName))), Pair("album", album)), "album_show.hbs")
}
}
## Instruction:
Remove dead code since handlebars is no longer being used
## Code After:
package controllers
import models.Album
import spark.ModelAndView
import spark.Request
import spark.Response
import templates.AlbumTemplate
/**
* Created by allen on 4/11/17.
*/
object AlbumController{
fun index(request: Request, response: Response): String {
return AlbumTemplate.index(SqliteController.selectAllFolders(), SqliteController.selectAllAlbums())
}
fun show(request: Request, response: Response, albumIdParameterName: String): String {
val album: Album = SqliteController.selectAlbum(request.params(albumIdParameterName)) ?: return ErrorController.notFound(request, response)
return AlbumTemplate.show(SqliteController.selectAllFolders(), album, SqliteController.imagesForAlbum(request.params(albumIdParameterName)))
}
} | package controllers
import models.Album
import spark.ModelAndView
import spark.Request
import spark.Response
import templates.AlbumTemplate
/**
* Created by allen on 4/11/17.
*/
object AlbumController{
fun index(request: Request, response: Response): String {
return AlbumTemplate.index(SqliteController.selectAllFolders(), SqliteController.selectAllAlbums())
}
fun show(request: Request, response: Response, albumIdParameterName: String): String {
val album: Album = SqliteController.selectAlbum(request.params(albumIdParameterName)) ?: return ErrorController.notFound(request, response)
return AlbumTemplate.show(SqliteController.selectAllFolders(), album, SqliteController.imagesForAlbum(request.params(albumIdParameterName)))
- //return ModelAndView(hashMapOf(Pair("folders", SqliteController.selectAllFolders()), Pair("images", SqliteController.imagesForAlbum(request.params(albumIdParameterName))), Pair("album", album)), "album_show.hbs")
}
} | 1 | 0.041667 | 0 | 1 |
19c53a8a46088db5998848df7e00375f09a222a7 | ansible-netbox/inventory/group_vars/all/netbox/netbox.yml | ansible-netbox/inventory/group_vars/all/netbox/netbox.yml | ---
# Setup on a test domain
netbox__fqdn: 'localhost.localdomain'
| ---
# Setup on a test domain
netbox__fqdn: 'localhost.localdomain'
# Use the PostgreSQL socket connection instead of port
netbox__database_port: ''
| Use socket connection to the database | Use socket connection to the database
| YAML | mit | debops/test-suite,debops/test-suite,ganto/debops-test-suite,ganto/test-suite,ganto/test-suite,ganto/debops-test-suite,debops/test-suite,ganto/test-suite,ganto/test-suite,ganto/debops-test-suite,debops/test-suite,ganto/debops-test-suite,ganto/debops-test-suite,debops/test-suite,ganto/test-suite | yaml | ## Code Before:
---
# Setup on a test domain
netbox__fqdn: 'localhost.localdomain'
## Instruction:
Use socket connection to the database
## Code After:
---
# Setup on a test domain
netbox__fqdn: 'localhost.localdomain'
# Use the PostgreSQL socket connection instead of port
netbox__database_port: ''
| ---
# Setup on a test domain
netbox__fqdn: 'localhost.localdomain'
+
+ # Use the PostgreSQL socket connection instead of port
+ netbox__database_port: '' | 3 | 0.75 | 3 | 0 |
eada3f4c2454050807c337ca47c5801df7211add | features/link_attributes.feature | features/link_attributes.feature | Feature: link method with attributes
I want to be able to pass arguments to the link method
So that additional attributes are generated
Scenario: link with class attribute
Given input file "index.html.haml" contains
"""
= link("page.html", "Page", :class => 'active')
"""
And input file "page.html" exists
When I build the site
Then output file "index.html" should contain
"""
<a class="active" href="page.html">Page</a>
"""
Scenario: link with title attribute
Given input file "index.html.haml" contains
"""
= link("page.html", "Page", :title => 'click me')
"""
And input file "page.html" exists
When I build the site
Then output file "index.html" should contain
"""
<a title="click me" href="page.html">Page</a>
"""
Scenario: link with title and class attributes
Given input file "index.html.haml" contains
"""
= link("page.html", "Page", :title => 'click me', :class => 'active')
"""
And input file "page.html" exists
When I build the site
Then output file "index.html" should contain /<a [title="click me", class="active", href="page.html"]/
| Feature: link method with attributes
I want to be able to pass arguments to the link method
So that additional attributes are generated
Scenario: link with class attribute
Given input file "index.html.haml" contains
"""
= link("page.html", "Page", :class => 'active')
"""
And input file "page.html" exists
When I build the site
Then output file "index.html" should contain /<a [class="active", href="page.html"]/
Scenario: link with title attribute
Given input file "index.html.haml" contains
"""
= link("page.html", "Page", :title => 'click me')
"""
And input file "page.html" exists
When I build the site
Then output file "index.html" should contain /<a [title="click me", href="page.html"]/
Scenario: link with title and class attributes
Given input file "index.html.haml" contains
"""
= link("page.html", "Page", :title => 'click me', :class => 'active')
"""
And input file "page.html" exists
When I build the site
Then output file "index.html" should contain /<a [title="click me", class="active", href="page.html"]/
| Fix specs for ruby 1.8 | Fix specs for ruby 1.8
As order in hash isn't guranteed
| Cucumber | mit | mdub/pith | cucumber | ## Code Before:
Feature: link method with attributes
I want to be able to pass arguments to the link method
So that additional attributes are generated
Scenario: link with class attribute
Given input file "index.html.haml" contains
"""
= link("page.html", "Page", :class => 'active')
"""
And input file "page.html" exists
When I build the site
Then output file "index.html" should contain
"""
<a class="active" href="page.html">Page</a>
"""
Scenario: link with title attribute
Given input file "index.html.haml" contains
"""
= link("page.html", "Page", :title => 'click me')
"""
And input file "page.html" exists
When I build the site
Then output file "index.html" should contain
"""
<a title="click me" href="page.html">Page</a>
"""
Scenario: link with title and class attributes
Given input file "index.html.haml" contains
"""
= link("page.html", "Page", :title => 'click me', :class => 'active')
"""
And input file "page.html" exists
When I build the site
Then output file "index.html" should contain /<a [title="click me", class="active", href="page.html"]/
## Instruction:
Fix specs for ruby 1.8
As order in hash isn't guranteed
## Code After:
Feature: link method with attributes
I want to be able to pass arguments to the link method
So that additional attributes are generated
Scenario: link with class attribute
Given input file "index.html.haml" contains
"""
= link("page.html", "Page", :class => 'active')
"""
And input file "page.html" exists
When I build the site
Then output file "index.html" should contain /<a [class="active", href="page.html"]/
Scenario: link with title attribute
Given input file "index.html.haml" contains
"""
= link("page.html", "Page", :title => 'click me')
"""
And input file "page.html" exists
When I build the site
Then output file "index.html" should contain /<a [title="click me", href="page.html"]/
Scenario: link with title and class attributes
Given input file "index.html.haml" contains
"""
= link("page.html", "Page", :title => 'click me', :class => 'active')
"""
And input file "page.html" exists
When I build the site
Then output file "index.html" should contain /<a [title="click me", class="active", href="page.html"]/
| Feature: link method with attributes
I want to be able to pass arguments to the link method
So that additional attributes are generated
Scenario: link with class attribute
Given input file "index.html.haml" contains
"""
= link("page.html", "Page", :class => 'active')
"""
And input file "page.html" exists
When I build the site
+ Then output file "index.html" should contain /<a [class="active", href="page.html"]/
- Then output file "index.html" should contain
- """
- <a class="active" href="page.html">Page</a>
- """
Scenario: link with title attribute
Given input file "index.html.haml" contains
"""
= link("page.html", "Page", :title => 'click me')
"""
And input file "page.html" exists
When I build the site
+ Then output file "index.html" should contain /<a [title="click me", href="page.html"]/
- Then output file "index.html" should contain
- """
- <a title="click me" href="page.html">Page</a>
- """
Scenario: link with title and class attributes
Given input file "index.html.haml" contains
"""
= link("page.html", "Page", :title => 'click me', :class => 'active')
"""
And input file "page.html" exists
When I build the site
Then output file "index.html" should contain /<a [title="click me", class="active", href="page.html"]/ | 10 | 0.232558 | 2 | 8 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.