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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
dfcac1268a46a879cb1c387fa8b33f450860038c | setup.py | setup.py | import os
import sys
import setuptools
if sys.version_info[0] < 3:
from codecs import open
def local_file(name):
return os.path.relpath(os.path.join(os.path.dirname(__file__), name))
README = local_file("README.rst")
with open(local_file("src/stratis_cli/_version.py")) as o:
exec(o.read())
setuptools.setup(
name='stratis-cli',
version=__version__,
author='Anne Mulhern',
author_email='amulhern@redhat.com',
description='prototype stratis cli',
long_description=open(README, encoding='utf-8').read(),
platforms=['Linux'],
license='GPL 2+',
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Intended Audience :: Developers',
'Operating System :: POSIX :: Linux',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: Implementation :: CPython',
'Programming Language :: Python :: Implementation :: PyPy',
'Topic :: Software Development :: Libraries',
],
install_requires = [
'dbus-python'
],
package_dir={"": "src"},
packages=setuptools.find_packages("src"),
)
| import os
import sys
import setuptools
if sys.version_info[0] < 3:
from codecs import open
def local_file(name):
return os.path.relpath(os.path.join(os.path.dirname(__file__), name))
README = local_file("README.rst")
with open(local_file("src/stratis_cli/_version.py")) as o:
exec(o.read())
setuptools.setup(
name='stratis-cli',
version=__version__,
author='Anne Mulhern',
author_email='amulhern@redhat.com',
description='prototype stratis cli',
long_description=open(README, encoding='utf-8').read(),
platforms=['Linux'],
license='GPL 2+',
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Intended Audience :: Developers',
'Operating System :: POSIX :: Linux',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: Implementation :: CPython',
'Programming Language :: Python :: Implementation :: PyPy',
'Topic :: Software Development :: Libraries',
],
install_requires = [
'dbus-python'
],
package_dir={"": "src"},
packages=setuptools.find_packages("src"),
scripts=['bin/stratis']
)
| Make stratis an installable script. | Make stratis an installable script.
Signed-off-by: mulhern <7b51bcf507bcd7afb72bf8663752c0ddbeb517f6@redhat.com>
| Python | apache-2.0 | stratis-storage/stratis-cli,stratis-storage/stratis-cli | python | ## Code Before:
import os
import sys
import setuptools
if sys.version_info[0] < 3:
from codecs import open
def local_file(name):
return os.path.relpath(os.path.join(os.path.dirname(__file__), name))
README = local_file("README.rst")
with open(local_file("src/stratis_cli/_version.py")) as o:
exec(o.read())
setuptools.setup(
name='stratis-cli',
version=__version__,
author='Anne Mulhern',
author_email='amulhern@redhat.com',
description='prototype stratis cli',
long_description=open(README, encoding='utf-8').read(),
platforms=['Linux'],
license='GPL 2+',
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Intended Audience :: Developers',
'Operating System :: POSIX :: Linux',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: Implementation :: CPython',
'Programming Language :: Python :: Implementation :: PyPy',
'Topic :: Software Development :: Libraries',
],
install_requires = [
'dbus-python'
],
package_dir={"": "src"},
packages=setuptools.find_packages("src"),
)
## Instruction:
Make stratis an installable script.
Signed-off-by: mulhern <7b51bcf507bcd7afb72bf8663752c0ddbeb517f6@redhat.com>
## Code After:
import os
import sys
import setuptools
if sys.version_info[0] < 3:
from codecs import open
def local_file(name):
return os.path.relpath(os.path.join(os.path.dirname(__file__), name))
README = local_file("README.rst")
with open(local_file("src/stratis_cli/_version.py")) as o:
exec(o.read())
setuptools.setup(
name='stratis-cli',
version=__version__,
author='Anne Mulhern',
author_email='amulhern@redhat.com',
description='prototype stratis cli',
long_description=open(README, encoding='utf-8').read(),
platforms=['Linux'],
license='GPL 2+',
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Intended Audience :: Developers',
'Operating System :: POSIX :: Linux',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: Implementation :: CPython',
'Programming Language :: Python :: Implementation :: PyPy',
'Topic :: Software Development :: Libraries',
],
install_requires = [
'dbus-python'
],
package_dir={"": "src"},
packages=setuptools.find_packages("src"),
scripts=['bin/stratis']
)
| import os
import sys
import setuptools
if sys.version_info[0] < 3:
from codecs import open
def local_file(name):
return os.path.relpath(os.path.join(os.path.dirname(__file__), name))
README = local_file("README.rst")
with open(local_file("src/stratis_cli/_version.py")) as o:
exec(o.read())
setuptools.setup(
name='stratis-cli',
version=__version__,
author='Anne Mulhern',
author_email='amulhern@redhat.com',
description='prototype stratis cli',
long_description=open(README, encoding='utf-8').read(),
platforms=['Linux'],
license='GPL 2+',
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Intended Audience :: Developers',
'Operating System :: POSIX :: Linux',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: Implementation :: CPython',
'Programming Language :: Python :: Implementation :: PyPy',
'Topic :: Software Development :: Libraries',
],
install_requires = [
'dbus-python'
],
package_dir={"": "src"},
packages=setuptools.find_packages("src"),
+ scripts=['bin/stratis']
) | 1 | 0.025 | 1 | 0 |
2c4f2aed2945db15d0f9b8749e05dab2e3564331 | lib/three_little_pigs/objects/pot.rb | lib/three_little_pigs/objects/pot.rb | module ThreeLittlePigs
class Pot
TEMPERATURE_TO_BOIL_WATER = 110 # °C
private_constant :TEMPERATURE_TO_BOIL_WATER
attr_accessor :contents, :temperature
def initialize
@contents = []
@temperature = Utilities::ROOM_TEMPERATURE
end
def water
contents.find { |item| item.kind_of?(Water) }
end
def raise_temperature
self.temperature = TEMPERATURE_TO_BOIL_WATER
contents.each { |item| item.boil }
end
end
end
| module ThreeLittlePigs
class Pot
attr_accessor :contents
def initialize
@contents = []
end
def water
contents.find { |item| item.kind_of?(Water) }
end
def raise_temperature
contents.each { |item| item.boil }
end
end
end
| Remove some code irrelevant to the story | Remove some code irrelevant to the story
| Ruby | mit | paulfioravanti/three_little_pigs,paulfioravanti/three_little_pigs | ruby | ## Code Before:
module ThreeLittlePigs
class Pot
TEMPERATURE_TO_BOIL_WATER = 110 # °C
private_constant :TEMPERATURE_TO_BOIL_WATER
attr_accessor :contents, :temperature
def initialize
@contents = []
@temperature = Utilities::ROOM_TEMPERATURE
end
def water
contents.find { |item| item.kind_of?(Water) }
end
def raise_temperature
self.temperature = TEMPERATURE_TO_BOIL_WATER
contents.each { |item| item.boil }
end
end
end
## Instruction:
Remove some code irrelevant to the story
## Code After:
module ThreeLittlePigs
class Pot
attr_accessor :contents
def initialize
@contents = []
end
def water
contents.find { |item| item.kind_of?(Water) }
end
def raise_temperature
contents.each { |item| item.boil }
end
end
end
| module ThreeLittlePigs
class Pot
- TEMPERATURE_TO_BOIL_WATER = 110 # °C
- private_constant :TEMPERATURE_TO_BOIL_WATER
-
- attr_accessor :contents, :temperature
? --------------
+ attr_accessor :contents
def initialize
@contents = []
- @temperature = Utilities::ROOM_TEMPERATURE
end
def water
contents.find { |item| item.kind_of?(Water) }
end
def raise_temperature
- self.temperature = TEMPERATURE_TO_BOIL_WATER
contents.each { |item| item.boil }
end
end
end | 7 | 0.318182 | 1 | 6 |
fd5674a1b36498e5d3a597203c180ded8c57d058 | morph_proxy.py | morph_proxy.py |
def request(context, flow):
# print out all the basic information to determine what request is being made
# coming from which container
# print flow.request.method
# print flow.request.host
# print flow.request.path
# print flow.request.scheme
# print flow.request.client_conn.address[0]
# print "***"
#text = flow.request.method + " " + flow.request.scheme + "://" + flow.request.host + flow.request.path + " FROM " + flow.request.client_conn
text = flow.request.method + " " + flow.request.scheme + "://" + flow.request.host + flow.request.path + " FROM " + flow.request.client_conn.address[0]
print text
# print "***"
|
def response(context, flow):
text = flow.request.method + " " + flow.request.scheme + "://" + flow.request.host + flow.request.path + " FROM " + flow.request.client_conn.address[0] + " REQUEST SIZE " + str(len(flow.request.content)) + " RESPONSE SIZE " + str(len(flow.response.content))
print text
| Add request and response size | Add request and response size
| Python | agpl-3.0 | otherchirps/morph,openaustralia/morph,otherchirps/morph,otherchirps/morph,OpenAddressesUK/morph,otherchirps/morph,otherchirps/morph,openaustralia/morph,openaustralia/morph,otherchirps/morph,otherchirps/morph,OpenAddressesUK/morph,openaustralia/morph,OpenAddressesUK/morph,openaustralia/morph,openaustralia/morph,OpenAddressesUK/morph,openaustralia/morph | python | ## Code Before:
def request(context, flow):
# print out all the basic information to determine what request is being made
# coming from which container
# print flow.request.method
# print flow.request.host
# print flow.request.path
# print flow.request.scheme
# print flow.request.client_conn.address[0]
# print "***"
#text = flow.request.method + " " + flow.request.scheme + "://" + flow.request.host + flow.request.path + " FROM " + flow.request.client_conn
text = flow.request.method + " " + flow.request.scheme + "://" + flow.request.host + flow.request.path + " FROM " + flow.request.client_conn.address[0]
print text
# print "***"
## Instruction:
Add request and response size
## Code After:
def response(context, flow):
text = flow.request.method + " " + flow.request.scheme + "://" + flow.request.host + flow.request.path + " FROM " + flow.request.client_conn.address[0] + " REQUEST SIZE " + str(len(flow.request.content)) + " RESPONSE SIZE " + str(len(flow.response.content))
print text
|
- def request(context, flow):
? ^^ --
+ def response(context, flow):
? ^^^^^
+ text = flow.request.method + " " + flow.request.scheme + "://" + flow.request.host + flow.request.path + " FROM " + flow.request.client_conn.address[0] + " REQUEST SIZE " + str(len(flow.request.content)) + " RESPONSE SIZE " + str(len(flow.response.content))
- # print out all the basic information to determine what request is being made
- # coming from which container
- # print flow.request.method
- # print flow.request.host
- # print flow.request.path
- # print flow.request.scheme
- # print flow.request.client_conn.address[0]
- # print "***"
- #text = flow.request.method + " " + flow.request.scheme + "://" + flow.request.host + flow.request.path + " FROM " + flow.request.client_conn
- text = flow.request.method + " " + flow.request.scheme + "://" + flow.request.host + flow.request.path + " FROM " + flow.request.client_conn.address[0]
print text
- # print "***" | 14 | 1 | 2 | 12 |
8c6e5d3c420db328eacc29b4731ac08b3cc622cb | README.md | README.md | _ _ _
| | | | | |
| |___| |_____ __| | ____
|_____ (____ |/ _ |/ ___)
_____| / ___ ( (_| | |
(_______\_____|\____|_|
# Yet Another Dotfile Repo
# Inspired by https://github.com/skwp/dotfiles
| _ _ _
| | | | | |
| |___| |_____ __| | ____
|_____ (____ |/ _ |/ ___)
_____| / ___ ( (_| | |
(_______\_____|\____|_|
# Yet Another Dotfile Repo
# Inspired by https://github.com/skwp/dotfiles
# Dein
`sh ~/vim/dein/installer.sh ~/vim/dein`
| Add instruction for how to install Dein for vim | Add instruction for how to install Dein for vim
| Markdown | bsd-2-clause | ofer987/dotfiles,ofer987/dotfiles | markdown | ## Code Before:
_ _ _
| | | | | |
| |___| |_____ __| | ____
|_____ (____ |/ _ |/ ___)
_____| / ___ ( (_| | |
(_______\_____|\____|_|
# Yet Another Dotfile Repo
# Inspired by https://github.com/skwp/dotfiles
## Instruction:
Add instruction for how to install Dein for vim
## Code After:
_ _ _
| | | | | |
| |___| |_____ __| | ____
|_____ (____ |/ _ |/ ___)
_____| / ___ ( (_| | |
(_______\_____|\____|_|
# Yet Another Dotfile Repo
# Inspired by https://github.com/skwp/dotfiles
# Dein
`sh ~/vim/dein/installer.sh ~/vim/dein`
| _ _ _
| | | | | |
| |___| |_____ __| | ____
|_____ (____ |/ _ |/ ___)
_____| / ___ ( (_| | |
(_______\_____|\____|_|
# Yet Another Dotfile Repo
# Inspired by https://github.com/skwp/dotfiles
+
+ # Dein
+
+ `sh ~/vim/dein/installer.sh ~/vim/dein` | 4 | 0.444444 | 4 | 0 |
e714a374e85fbf90dffcdf4c9991cdb0ce1e35c2 | lib/deps.js | lib/deps.js | var canihaz = require('canihaz'),
fs = require('fs'),
p = require('path');
/**
* Install dependency modules that are not yet installed, and needed for executing the tasks.
*
* @param {Array} depNames: an array of dependency module names
* @param {String} dir: application directory where node_modules dir is located
* @param {Function} cb: standard cb(err, result) callback
*/
function install(depNames, dir, cb) {
fs.readdir(p.join(dir, 'node_modules'), function(err, installed) {
var uninstalled = [];
depNames.forEach(function (depName) {
if (installed.indexOf(depName) === -1) {
uninstalled.push(depName);
}
});
if (uninstalled.length > 0) {
console.log('[deps] Installing modules: %s (might take a while, once-off only)', uninstalled .join(', '));
canihaz({ key: 'optDependencies' }).apply(this, depNames.concat(cb));
} else {
cb();
}
});
}
exports.install = install; | var canihaz = require('canihaz'),
fs = require('fs'),
p = require('path');
const GLOBALS = ['npm'];
/**
* Install dependency modules that are not yet installed, and needed for executing the tasks.
* Global modules (like npm) are assumed to already exist.
*
* @param {Array} depNames: an array of dependency module names
* @param {String} dir: application directory where node_modules dir is located
* @param {Function} cb: standard cb(err, result) callback
*/
function install(depNames, dir, cb) {
fs.readdir(p.join(dir, 'node_modules'), function(err, installed) {
var uninstalled = [];
depNames.forEach(function (depName) {
if (installed.indexOf(depName) === -1 && GLOBALS.indexOf(depName) === -1) {
uninstalled.push(depName);
}
});
if (uninstalled.length > 0) {
console.log('[deps] Installing modules: %s (might take a while, once-off only)', uninstalled .join(', '));
canihaz({ key: 'optDependencies' }).apply(this, depNames.concat(cb));
} else {
cb();
}
});
}
exports.install = install; | Add global modules list, to be excluded from lazy installation. | Add global modules list, to be excluded from lazy installation.
| JavaScript | mit | cliffano/bob | javascript | ## Code Before:
var canihaz = require('canihaz'),
fs = require('fs'),
p = require('path');
/**
* Install dependency modules that are not yet installed, and needed for executing the tasks.
*
* @param {Array} depNames: an array of dependency module names
* @param {String} dir: application directory where node_modules dir is located
* @param {Function} cb: standard cb(err, result) callback
*/
function install(depNames, dir, cb) {
fs.readdir(p.join(dir, 'node_modules'), function(err, installed) {
var uninstalled = [];
depNames.forEach(function (depName) {
if (installed.indexOf(depName) === -1) {
uninstalled.push(depName);
}
});
if (uninstalled.length > 0) {
console.log('[deps] Installing modules: %s (might take a while, once-off only)', uninstalled .join(', '));
canihaz({ key: 'optDependencies' }).apply(this, depNames.concat(cb));
} else {
cb();
}
});
}
exports.install = install;
## Instruction:
Add global modules list, to be excluded from lazy installation.
## Code After:
var canihaz = require('canihaz'),
fs = require('fs'),
p = require('path');
const GLOBALS = ['npm'];
/**
* Install dependency modules that are not yet installed, and needed for executing the tasks.
* Global modules (like npm) are assumed to already exist.
*
* @param {Array} depNames: an array of dependency module names
* @param {String} dir: application directory where node_modules dir is located
* @param {Function} cb: standard cb(err, result) callback
*/
function install(depNames, dir, cb) {
fs.readdir(p.join(dir, 'node_modules'), function(err, installed) {
var uninstalled = [];
depNames.forEach(function (depName) {
if (installed.indexOf(depName) === -1 && GLOBALS.indexOf(depName) === -1) {
uninstalled.push(depName);
}
});
if (uninstalled.length > 0) {
console.log('[deps] Installing modules: %s (might take a while, once-off only)', uninstalled .join(', '));
canihaz({ key: 'optDependencies' }).apply(this, depNames.concat(cb));
} else {
cb();
}
});
}
exports.install = install; | var canihaz = require('canihaz'),
fs = require('fs'),
p = require('path');
+ const GLOBALS = ['npm'];
+
/**
* Install dependency modules that are not yet installed, and needed for executing the tasks.
+ * Global modules (like npm) are assumed to already exist.
*
* @param {Array} depNames: an array of dependency module names
* @param {String} dir: application directory where node_modules dir is located
* @param {Function} cb: standard cb(err, result) callback
*/
function install(depNames, dir, cb) {
fs.readdir(p.join(dir, 'node_modules'), function(err, installed) {
var uninstalled = [];
depNames.forEach(function (depName) {
- if (installed.indexOf(depName) === -1) {
+ if (installed.indexOf(depName) === -1 && GLOBALS.indexOf(depName) === -1) {
uninstalled.push(depName);
}
});
if (uninstalled.length > 0) {
console.log('[deps] Installing modules: %s (might take a while, once-off only)', uninstalled .join(', '));
canihaz({ key: 'optDependencies' }).apply(this, depNames.concat(cb));
} else {
cb();
}
});
}
exports.install = install; | 5 | 0.172414 | 4 | 1 |
17583f0a19cd0710d9ee03a32ed2d0ab385b5934 | www/shows/index.php | www/shows/index.php | <?php
include( '../config.php' );
$url = 'http://www.myepisodes.com/rss.php?feed=mylist&uid=mirrorer&pwdmd5=' . $myEpisodes;
$data = file_get_contents( $url );
$shows = new SimpleXMLElement( $data );
$items = array();
foreach( $shows->channel->item as $show ):
preg_match( '#\[(.+?)\]\[(.+?)\]\[(.+?)\]\[(.+?)\]#mis', $show->title, $matches );
$dateString = date( 'Y-m-d', strtotime( $matches[ 4 ] ) );
if( !isset( $items[ $dateString ] ) ):
$items[ $dateString ] = array();
endif;
$item = array();
$item[ 'image' ] = '/images/?query=' . preg_replace( '#\s+#mis', '-', strtolower( trim( $matches[ 1 ] ) ) );
$items[ $dateString ][] = $item;
endforeach;
header( 'Access-Control-Allow-Origin: *' );
header( 'Content-Type: application/json' );
echo json_encode( $items );
| <?php
include( '../config.php' );
$url = 'http://www.myepisodes.com/rss.php?feed=mylist&uid=mirrorer&pwdmd5=' . $myEpisodes;
$data = file_get_contents( $url );
$shows = new SimpleXMLElement( $data );
$items = array();
foreach( $shows->channel->item as $show ):
preg_match( '#\[(.+?)\]\[(.+?)\]\[(.+?)\]\[(.+?)\]#mis', $show->title, $matches );
$dateString = date( 'Y-m-d', strtotime( $matches[ 4 ] ) );
if( !isset( $items[ $dateString ] ) ):
$items[ $dateString ] = array();
endif;
$item = array();
$item[ 'image' ] = $_SERVER[ 'REQUEST_URI' ] . 'images/?query=' . preg_replace( '#\s+#mis', '-', strtolower( trim( $matches[ 1 ] ) ) );
$items[ $dateString ][] = $item;
endforeach;
header( 'Access-Control-Allow-Origin: *' );
header( 'Content-Type: application/json' );
echo json_encode( $items );
| Make the image path work even if it's in a subfolder | Make the image path work even if it's in a subfolder
| PHP | mit | kokarn/pi-display,kokarn/pi-display,kokarn/pi-display,kokarn/pi-display | php | ## Code Before:
<?php
include( '../config.php' );
$url = 'http://www.myepisodes.com/rss.php?feed=mylist&uid=mirrorer&pwdmd5=' . $myEpisodes;
$data = file_get_contents( $url );
$shows = new SimpleXMLElement( $data );
$items = array();
foreach( $shows->channel->item as $show ):
preg_match( '#\[(.+?)\]\[(.+?)\]\[(.+?)\]\[(.+?)\]#mis', $show->title, $matches );
$dateString = date( 'Y-m-d', strtotime( $matches[ 4 ] ) );
if( !isset( $items[ $dateString ] ) ):
$items[ $dateString ] = array();
endif;
$item = array();
$item[ 'image' ] = '/images/?query=' . preg_replace( '#\s+#mis', '-', strtolower( trim( $matches[ 1 ] ) ) );
$items[ $dateString ][] = $item;
endforeach;
header( 'Access-Control-Allow-Origin: *' );
header( 'Content-Type: application/json' );
echo json_encode( $items );
## Instruction:
Make the image path work even if it's in a subfolder
## Code After:
<?php
include( '../config.php' );
$url = 'http://www.myepisodes.com/rss.php?feed=mylist&uid=mirrorer&pwdmd5=' . $myEpisodes;
$data = file_get_contents( $url );
$shows = new SimpleXMLElement( $data );
$items = array();
foreach( $shows->channel->item as $show ):
preg_match( '#\[(.+?)\]\[(.+?)\]\[(.+?)\]\[(.+?)\]#mis', $show->title, $matches );
$dateString = date( 'Y-m-d', strtotime( $matches[ 4 ] ) );
if( !isset( $items[ $dateString ] ) ):
$items[ $dateString ] = array();
endif;
$item = array();
$item[ 'image' ] = $_SERVER[ 'REQUEST_URI' ] . 'images/?query=' . preg_replace( '#\s+#mis', '-', strtolower( trim( $matches[ 1 ] ) ) );
$items[ $dateString ][] = $item;
endforeach;
header( 'Access-Control-Allow-Origin: *' );
header( 'Content-Type: application/json' );
echo json_encode( $items );
| <?php
include( '../config.php' );
$url = 'http://www.myepisodes.com/rss.php?feed=mylist&uid=mirrorer&pwdmd5=' . $myEpisodes;
$data = file_get_contents( $url );
$shows = new SimpleXMLElement( $data );
$items = array();
foreach( $shows->channel->item as $show ):
preg_match( '#\[(.+?)\]\[(.+?)\]\[(.+?)\]\[(.+?)\]#mis', $show->title, $matches );
$dateString = date( 'Y-m-d', strtotime( $matches[ 4 ] ) );
if( !isset( $items[ $dateString ] ) ):
$items[ $dateString ] = array();
endif;
$item = array();
- $item[ 'image' ] = '/images/?query=' . preg_replace( '#\s+#mis', '-', strtolower( trim( $matches[ 1 ] ) ) );
? ^
+ $item[ 'image' ] = $_SERVER[ 'REQUEST_URI' ] . 'images/?query=' . preg_replace( '#\s+#mis', '-', strtolower( trim( $matches[ 1 ] ) ) );
? ++++++++++ ^^^^^^^^^^^^^^^^^^
$items[ $dateString ][] = $item;
endforeach;
header( 'Access-Control-Allow-Origin: *' );
header( 'Content-Type: application/json' );
echo json_encode( $items ); | 2 | 0.068966 | 1 | 1 |
b001f9a364559e970df00b0f1dc2fe3dc30494ba | modules/govuk_jenkins/templates/jobs/remove_emergency_banner.yaml.erb | modules/govuk_jenkins/templates/jobs/remove_emergency_banner.yaml.erb | ---
- job:
name: remove-emergency-banner
display-name: Remove the emergency banner
project-type: freestyle
description: >
Remove the emergency banner from GOV.UK.
properties:
- build-discarder:
num-to-keep: 30
builders:
# The argument to `-c` is in this case `frontend` but the value is used by both `static` and `frontend` applications
- shell: ssh deploy@$(govuk_node_list -c frontend --single-node) "cd /var/apps/static && govuk_setenv static bundle exec rake emergency_banner:remove"
- trigger-builds:
- project: clear-template-cache
block: true
- project: clear-frontend-memcache
block: true
- project: clear-varnish-cache
block: true
<%- if @clear_cdn_cache -%>
- project: clear-cdn-cache
block: true
<%- end -%>
wrappers:
- ansicolor:
colormap: xterm
| ---
- job:
name: remove-emergency-banner
display-name: Remove the emergency banner
project-type: freestyle
description: >
Remove the emergency banner from GOV.UK.
properties:
- build-discarder:
num-to-keep: 30
builders:
- trigger-builds:
- project: run-rake-task
block: true
predefined-parameters: |
TARGET_APPLICATION=static
MACHINE_CLASS=frontend
RAKE_TASK=emergency_banner:remove
- project: clear-template-cache
block: true
- project: clear-frontend-memcache
block: true
- project: clear-varnish-cache
block: true
<%- if @clear_cdn_cache -%>
- project: clear-cdn-cache
block: true
<%- end -%>
wrappers:
- ansicolor:
colormap: xterm
| Use run-rake-task in remove-emergency-banner job | Use run-rake-task in remove-emergency-banner job
| HTML+ERB | mit | alphagov/govuk-puppet,alphagov/govuk-puppet,alphagov/govuk-puppet,alphagov/govuk-puppet,alphagov/govuk-puppet,alphagov/govuk-puppet | html+erb | ## Code Before:
---
- job:
name: remove-emergency-banner
display-name: Remove the emergency banner
project-type: freestyle
description: >
Remove the emergency banner from GOV.UK.
properties:
- build-discarder:
num-to-keep: 30
builders:
# The argument to `-c` is in this case `frontend` but the value is used by both `static` and `frontend` applications
- shell: ssh deploy@$(govuk_node_list -c frontend --single-node) "cd /var/apps/static && govuk_setenv static bundle exec rake emergency_banner:remove"
- trigger-builds:
- project: clear-template-cache
block: true
- project: clear-frontend-memcache
block: true
- project: clear-varnish-cache
block: true
<%- if @clear_cdn_cache -%>
- project: clear-cdn-cache
block: true
<%- end -%>
wrappers:
- ansicolor:
colormap: xterm
## Instruction:
Use run-rake-task in remove-emergency-banner job
## Code After:
---
- job:
name: remove-emergency-banner
display-name: Remove the emergency banner
project-type: freestyle
description: >
Remove the emergency banner from GOV.UK.
properties:
- build-discarder:
num-to-keep: 30
builders:
- trigger-builds:
- project: run-rake-task
block: true
predefined-parameters: |
TARGET_APPLICATION=static
MACHINE_CLASS=frontend
RAKE_TASK=emergency_banner:remove
- project: clear-template-cache
block: true
- project: clear-frontend-memcache
block: true
- project: clear-varnish-cache
block: true
<%- if @clear_cdn_cache -%>
- project: clear-cdn-cache
block: true
<%- end -%>
wrappers:
- ansicolor:
colormap: xterm
| ---
- job:
name: remove-emergency-banner
display-name: Remove the emergency banner
project-type: freestyle
description: >
Remove the emergency banner from GOV.UK.
properties:
- build-discarder:
num-to-keep: 30
builders:
- # The argument to `-c` is in this case `frontend` but the value is used by both `static` and `frontend` applications
- - shell: ssh deploy@$(govuk_node_list -c frontend --single-node) "cd /var/apps/static && govuk_setenv static bundle exec rake emergency_banner:remove"
- trigger-builds:
+ - project: run-rake-task
+ block: true
+ predefined-parameters: |
+ TARGET_APPLICATION=static
+ MACHINE_CLASS=frontend
+ RAKE_TASK=emergency_banner:remove
- project: clear-template-cache
block: true
- project: clear-frontend-memcache
block: true
- project: clear-varnish-cache
block: true
<%- if @clear_cdn_cache -%>
- project: clear-cdn-cache
block: true
<%- end -%>
wrappers:
- ansicolor:
colormap: xterm | 8 | 0.296296 | 6 | 2 |
201d0873c4966cfba477cbdac0cae99580ec1c43 | tasks/zookeeper.yml | tasks/zookeeper.yml | ---
- file: path=/opt/src state=directory
- file: path={{zookeeper_install_dir}} state=directory
- name: download zookeeper
get_url: url={{zookeeper_url}} dest=/opt/src/zookeeper-{{zookeeper_version}}.tar.gz
- name: unpack tarball
command: tar zxf /opt/src/zoookeeper-{{zookeeper_version}}.tar.gz --strip-components=1 chdir={{zookeeper_install_dir}} creates={{zookeeper_install_dir}}/bin
- name: create zookeeper group
group: name=zookeeper system=yes
- name: create zookeeper user
user: name=zookeeper group=zookeeper system=yes
- name: change ownership on zookeeper directory
file: >
path={{zookeeper_install_dir}}
state=directory
recurse=yes
owner=zookeeper
group=zookeeper
- name: create zookeeper data directory
file: >
path={{zookeeper_data_dir}}
state=directory
recurse=yes
owner=zookeeper
group=zookeeper
- name: create zookeeper logs directory
file: >
path={{zookeeper_log_dir}}
state=directory
recurse=yes
owner=zookeeper
group=zookeeper
| ---
- file: path=/opt/src state=directory
- file: path={{zookeeper_install_dir}} state=directory
- name: download zookeeper
get_url: url={{zookeeper_url}} dest=/opt/src/zookeeper-{{zookeeper_version}}.tar.gz
- name: unpack tarball
shell: >
tar zxf /opt/src/zookeeper-{{zookeeper_version}}.tar.gz --strip-components=1
chdir={{zookeeper_install_dir}}
creates={{zookeeper_install_dir}}/bin
- name: create zookeeper group
group: name=zookeeper system=yes
- name: create zookeeper user
user: name=zookeeper group=zookeeper system=yes
- name: change ownership on zookeeper directory
file: >
path={{zookeeper_install_dir}}
state=directory
recurse=yes
owner=zookeeper
group=zookeeper
- name: create zookeeper data directory
file: >
path={{zookeeper_data_dir}}
state=directory
recurse=yes
owner=zookeeper
group=zookeeper
- name: create zookeeper logs directory
file: >
path={{zookeeper_log_dir}}
state=directory
recurse=yes
owner=zookeeper
group=zookeeper
| Fix typo in untar command | Fix typo in untar command
| YAML | mit | bwarminski/zookeeper | yaml | ## Code Before:
---
- file: path=/opt/src state=directory
- file: path={{zookeeper_install_dir}} state=directory
- name: download zookeeper
get_url: url={{zookeeper_url}} dest=/opt/src/zookeeper-{{zookeeper_version}}.tar.gz
- name: unpack tarball
command: tar zxf /opt/src/zoookeeper-{{zookeeper_version}}.tar.gz --strip-components=1 chdir={{zookeeper_install_dir}} creates={{zookeeper_install_dir}}/bin
- name: create zookeeper group
group: name=zookeeper system=yes
- name: create zookeeper user
user: name=zookeeper group=zookeeper system=yes
- name: change ownership on zookeeper directory
file: >
path={{zookeeper_install_dir}}
state=directory
recurse=yes
owner=zookeeper
group=zookeeper
- name: create zookeeper data directory
file: >
path={{zookeeper_data_dir}}
state=directory
recurse=yes
owner=zookeeper
group=zookeeper
- name: create zookeeper logs directory
file: >
path={{zookeeper_log_dir}}
state=directory
recurse=yes
owner=zookeeper
group=zookeeper
## Instruction:
Fix typo in untar command
## Code After:
---
- file: path=/opt/src state=directory
- file: path={{zookeeper_install_dir}} state=directory
- name: download zookeeper
get_url: url={{zookeeper_url}} dest=/opt/src/zookeeper-{{zookeeper_version}}.tar.gz
- name: unpack tarball
shell: >
tar zxf /opt/src/zookeeper-{{zookeeper_version}}.tar.gz --strip-components=1
chdir={{zookeeper_install_dir}}
creates={{zookeeper_install_dir}}/bin
- name: create zookeeper group
group: name=zookeeper system=yes
- name: create zookeeper user
user: name=zookeeper group=zookeeper system=yes
- name: change ownership on zookeeper directory
file: >
path={{zookeeper_install_dir}}
state=directory
recurse=yes
owner=zookeeper
group=zookeeper
- name: create zookeeper data directory
file: >
path={{zookeeper_data_dir}}
state=directory
recurse=yes
owner=zookeeper
group=zookeeper
- name: create zookeeper logs directory
file: >
path={{zookeeper_log_dir}}
state=directory
recurse=yes
owner=zookeeper
group=zookeeper
| ---
- file: path=/opt/src state=directory
- file: path={{zookeeper_install_dir}} state=directory
- name: download zookeeper
get_url: url={{zookeeper_url}} dest=/opt/src/zookeeper-{{zookeeper_version}}.tar.gz
- name: unpack tarball
- command: tar zxf /opt/src/zoookeeper-{{zookeeper_version}}.tar.gz --strip-components=1 chdir={{zookeeper_install_dir}} creates={{zookeeper_install_dir}}/bin
+ shell: >
+ tar zxf /opt/src/zookeeper-{{zookeeper_version}}.tar.gz --strip-components=1
+ chdir={{zookeeper_install_dir}}
+ creates={{zookeeper_install_dir}}/bin
- name: create zookeeper group
group: name=zookeeper system=yes
- name: create zookeeper user
user: name=zookeeper group=zookeeper system=yes
- name: change ownership on zookeeper directory
file: >
path={{zookeeper_install_dir}}
state=directory
recurse=yes
owner=zookeeper
group=zookeeper
- name: create zookeeper data directory
file: >
path={{zookeeper_data_dir}}
state=directory
recurse=yes
owner=zookeeper
group=zookeeper
- name: create zookeeper logs directory
file: >
path={{zookeeper_log_dir}}
state=directory
recurse=yes
owner=zookeeper
group=zookeeper | 5 | 0.128205 | 4 | 1 |
4040cd2fdfae9f5e96897d2159c1f28800bb1a9f | launch_sesde.sh | launch_sesde.sh | export Launcher="/usr/share/ALaunch/main.rb"
/usr/share/APanel/main.rb &
/usr/bin/plank &
echo "Launched"
./session.rb
| export Launcher="/usr/bin/ALaunch.rb"
/usr/bin/APanel.rb &
/usr/bin/plank &
echo "Launched"
./session.rb
| Change the directory of programs | Change the directory of programs
| Shell | mit | SESDE/SESDE,bobcao3/SESDE | shell | ## Code Before:
export Launcher="/usr/share/ALaunch/main.rb"
/usr/share/APanel/main.rb &
/usr/bin/plank &
echo "Launched"
./session.rb
## Instruction:
Change the directory of programs
## Code After:
export Launcher="/usr/bin/ALaunch.rb"
/usr/bin/APanel.rb &
/usr/bin/plank &
echo "Launched"
./session.rb
| - export Launcher="/usr/share/ALaunch/main.rb"
? ^^^^^ -----
+ export Launcher="/usr/bin/ALaunch.rb"
? ^^^
- /usr/share/APanel/main.rb &
+ /usr/bin/APanel.rb &
/usr/bin/plank &
echo "Launched"
./session.rb | 4 | 0.5 | 2 | 2 |
f91fb24bb1727e2f1dc61634c83ab2d8f8c62ab6 | Cargo.toml | Cargo.toml | [package]
name = "slackbot"
version = "0.1.0"
authors = ["Matt Jones <mthjones@gmail.com>"]
[dependencies]
slack = "0.8.1"
serde_json = "0.6.0"
| [package]
name = "slackbot"
version = "0.1.0"
authors = ["Matt Jones <mthjones@gmail.com>"]
keywords = ["slack", "bot"]
license = "MIT"
[dependencies]
slack = "0.8.1"
serde_json = "0.6.0"
| Update manifest with useful crates.io metadata | Update manifest with useful crates.io metadata
| TOML | mit | mthjones/slackbot,mthjones/slackbot | toml | ## Code Before:
[package]
name = "slackbot"
version = "0.1.0"
authors = ["Matt Jones <mthjones@gmail.com>"]
[dependencies]
slack = "0.8.1"
serde_json = "0.6.0"
## Instruction:
Update manifest with useful crates.io metadata
## Code After:
[package]
name = "slackbot"
version = "0.1.0"
authors = ["Matt Jones <mthjones@gmail.com>"]
keywords = ["slack", "bot"]
license = "MIT"
[dependencies]
slack = "0.8.1"
serde_json = "0.6.0"
| [package]
name = "slackbot"
version = "0.1.0"
authors = ["Matt Jones <mthjones@gmail.com>"]
+ keywords = ["slack", "bot"]
+ license = "MIT"
[dependencies]
slack = "0.8.1"
serde_json = "0.6.0" | 2 | 0.25 | 2 | 0 |
bb28c9d13a6569416b438e4b83816f0e56916ea3 | web/src/stores/search.js | web/src/stores/search.js | import { observable, action, reaction } from 'mobx';
import storeCoords from 'stores/coords.js';
export default new class StoreSearch {
dispose = 0
@observable
query = ''
@observable
type = 'stops'
@observable.struct
results = {
stops: [],
routes: []
}
startScanning() {
this.dispose = reaction(() => ({
lat: storeCoords.lat,
lng: storeCoords.lng
}), () => {
if (!this.query) this.fetchResults();
});
}
stopScanning() {
this.dispose();
}
@action
updateQuery(query) {
this.query = query;
}
@action
updateType(type) {
this.type = type;
}
@action.bound
async fetchResults() {
const [ query, lat, lng ] = [ this.query, storeCoords.lat, storeCoords.lng ];
const results = query || (lat && lng) ? await (await fetch(`${process.env['REACT_APP_API']}/search?${query ? `&query=${query}` : ''}${lat && lng ? `&lat=${lat}&lng=${lng}` : ''}`)).json() : {};
this.results = results;
}
};
| import { observable, action, reaction } from 'mobx';
import storeCoords from 'stores/coords.js';
export default new class StoreSearch {
dispose = 0
@observable
query = ''
@observable
type = 'stops'
@observable.struct
results = {
stops: [],
routes: []
}
// Start fetching nearby search results on location update.
startScanning() {
this.dispose = reaction(() => ({
lat: storeCoords.lat,
lng: storeCoords.lng
}), () => {
if (!this.query) this.fetchResults();
}, { fireImmediately: true });
}
// Stop fetching nearby search results on location update.
stopScanning() {
this.dispose();
}
@action
updateQuery(query) {
this.query = query;
}
@action
updateType(type) {
this.type = type;
}
@action.bound
async fetchResults() {
const [ query, lat, lng ] = [ this.query, storeCoords.lat, storeCoords.lng ];
// Return on manual search or if coordinates unavailable.
if (query || !lat || !lng) return;
// Fetch search results.
const results = await (await fetch(`${process.env['REACT_APP_API']}/search?${query ? `&query=${query}` : ''}${lat && lng ? `&lat=${lat}&lng=${lng}` : ''}`)).json();
if (results) this.results = results;
}
};
| Fix nearby stops not loading | Fix nearby stops not loading
| JavaScript | agpl-3.0 | karlkoorna/Bussiaeg,karlkoorna/Bussiaeg | javascript | ## Code Before:
import { observable, action, reaction } from 'mobx';
import storeCoords from 'stores/coords.js';
export default new class StoreSearch {
dispose = 0
@observable
query = ''
@observable
type = 'stops'
@observable.struct
results = {
stops: [],
routes: []
}
startScanning() {
this.dispose = reaction(() => ({
lat: storeCoords.lat,
lng: storeCoords.lng
}), () => {
if (!this.query) this.fetchResults();
});
}
stopScanning() {
this.dispose();
}
@action
updateQuery(query) {
this.query = query;
}
@action
updateType(type) {
this.type = type;
}
@action.bound
async fetchResults() {
const [ query, lat, lng ] = [ this.query, storeCoords.lat, storeCoords.lng ];
const results = query || (lat && lng) ? await (await fetch(`${process.env['REACT_APP_API']}/search?${query ? `&query=${query}` : ''}${lat && lng ? `&lat=${lat}&lng=${lng}` : ''}`)).json() : {};
this.results = results;
}
};
## Instruction:
Fix nearby stops not loading
## Code After:
import { observable, action, reaction } from 'mobx';
import storeCoords from 'stores/coords.js';
export default new class StoreSearch {
dispose = 0
@observable
query = ''
@observable
type = 'stops'
@observable.struct
results = {
stops: [],
routes: []
}
// Start fetching nearby search results on location update.
startScanning() {
this.dispose = reaction(() => ({
lat: storeCoords.lat,
lng: storeCoords.lng
}), () => {
if (!this.query) this.fetchResults();
}, { fireImmediately: true });
}
// Stop fetching nearby search results on location update.
stopScanning() {
this.dispose();
}
@action
updateQuery(query) {
this.query = query;
}
@action
updateType(type) {
this.type = type;
}
@action.bound
async fetchResults() {
const [ query, lat, lng ] = [ this.query, storeCoords.lat, storeCoords.lng ];
// Return on manual search or if coordinates unavailable.
if (query || !lat || !lng) return;
// Fetch search results.
const results = await (await fetch(`${process.env['REACT_APP_API']}/search?${query ? `&query=${query}` : ''}${lat && lng ? `&lat=${lat}&lng=${lng}` : ''}`)).json();
if (results) this.results = results;
}
};
| import { observable, action, reaction } from 'mobx';
import storeCoords from 'stores/coords.js';
export default new class StoreSearch {
dispose = 0
@observable
query = ''
@observable
type = 'stops'
@observable.struct
results = {
stops: [],
routes: []
}
+ // Start fetching nearby search results on location update.
startScanning() {
this.dispose = reaction(() => ({
lat: storeCoords.lat,
lng: storeCoords.lng
}), () => {
if (!this.query) this.fetchResults();
- });
+ }, { fireImmediately: true });
}
+ // Stop fetching nearby search results on location update.
stopScanning() {
this.dispose();
}
@action
updateQuery(query) {
this.query = query;
}
@action
updateType(type) {
this.type = type;
}
@action.bound
async fetchResults() {
const [ query, lat, lng ] = [ this.query, storeCoords.lat, storeCoords.lng ];
+
+ // Return on manual search or if coordinates unavailable.
+ if (query || !lat || !lng) return;
+
+ // Fetch search results.
- const results = query || (lat && lng) ? await (await fetch(`${process.env['REACT_APP_API']}/search?${query ? `&query=${query}` : ''}${lat && lng ? `&lat=${lat}&lng=${lng}` : ''}`)).json() : {};
? ------------------------ -----
+ const results = await (await fetch(`${process.env['REACT_APP_API']}/search?${query ? `&query=${query}` : ''}${lat && lng ? `&lat=${lat}&lng=${lng}` : ''}`)).json();
- this.results = results;
+ if (results) this.results = results;
? +++++++++++++
+
}
}; | 14 | 0.264151 | 11 | 3 |
996face85805f4529df832c099ae48396cae4c83 | app/controllers/active_waiter/jobs_controller.rb | app/controllers/active_waiter/jobs_controller.rb | require_dependency "active_waiter/application_controller"
module ActiveWaiter
class JobsController < ApplicationController
def show
data = ActiveWaiter.read(params[:id])
return on_not_found(data) unless data.respond_to?(:[])
return on_error(data) if data[:error]
return on_link_to(data) if data[:link_to] && params[:download]
return on_redirect(data) if data[:link_to]
return on_progress(data) if data[:percentage]
end
protected
def on_not_found(_data)
case retries = params[:retries].to_i
when 0..9
@retries = retries + 1
else
raise ActionController::RoutingError.new('Not Found')
end
end
def on_error(data)
render template: "active_waiter/jobs/error", status: :internal_server_error, locals: data
end
def on_redirect(data)
redirect_to data[:link_to]
end
def on_link_to(data)
render template: "active_waiter/jobs/link_to", locals: data
end
def on_progress(data)
render template: "active_waiter/jobs/progress", locals: data
end
end
end
| require_dependency "active_waiter/application_controller"
module ActiveWaiter
class JobsController < ApplicationController
def show
@retries = nil
data = ActiveWaiter.read(params[:id])
return on_not_found(data) unless data.respond_to?(:[])
return on_error(data) if data[:error]
return on_link_to(data) if data[:link_to] && params[:download]
return on_redirect(data) if data[:link_to]
return on_progress(data) if data[:percentage]
end
protected
def on_not_found(_data)
case retries = params[:retries].to_i
when 0..9
@retries = retries + 1
else
raise ActionController::RoutingError.new('Not Found')
end
end
def on_error(data)
render template: "active_waiter/jobs/error", status: :internal_server_error, locals: data
end
def on_redirect(data)
redirect_to data[:link_to]
end
def on_link_to(data)
render template: "active_waiter/jobs/link_to", locals: data
end
def on_progress(data)
render template: "active_waiter/jobs/progress", locals: data
end
end
end
| Fix instance varialble not initialize warning | Fix instance varialble not initialize warning
| Ruby | mit | choonkeat/active_waiter,choonkeat/active_waiter,choonkeat/active_waiter | ruby | ## Code Before:
require_dependency "active_waiter/application_controller"
module ActiveWaiter
class JobsController < ApplicationController
def show
data = ActiveWaiter.read(params[:id])
return on_not_found(data) unless data.respond_to?(:[])
return on_error(data) if data[:error]
return on_link_to(data) if data[:link_to] && params[:download]
return on_redirect(data) if data[:link_to]
return on_progress(data) if data[:percentage]
end
protected
def on_not_found(_data)
case retries = params[:retries].to_i
when 0..9
@retries = retries + 1
else
raise ActionController::RoutingError.new('Not Found')
end
end
def on_error(data)
render template: "active_waiter/jobs/error", status: :internal_server_error, locals: data
end
def on_redirect(data)
redirect_to data[:link_to]
end
def on_link_to(data)
render template: "active_waiter/jobs/link_to", locals: data
end
def on_progress(data)
render template: "active_waiter/jobs/progress", locals: data
end
end
end
## Instruction:
Fix instance varialble not initialize warning
## Code After:
require_dependency "active_waiter/application_controller"
module ActiveWaiter
class JobsController < ApplicationController
def show
@retries = nil
data = ActiveWaiter.read(params[:id])
return on_not_found(data) unless data.respond_to?(:[])
return on_error(data) if data[:error]
return on_link_to(data) if data[:link_to] && params[:download]
return on_redirect(data) if data[:link_to]
return on_progress(data) if data[:percentage]
end
protected
def on_not_found(_data)
case retries = params[:retries].to_i
when 0..9
@retries = retries + 1
else
raise ActionController::RoutingError.new('Not Found')
end
end
def on_error(data)
render template: "active_waiter/jobs/error", status: :internal_server_error, locals: data
end
def on_redirect(data)
redirect_to data[:link_to]
end
def on_link_to(data)
render template: "active_waiter/jobs/link_to", locals: data
end
def on_progress(data)
render template: "active_waiter/jobs/progress", locals: data
end
end
end
| require_dependency "active_waiter/application_controller"
module ActiveWaiter
class JobsController < ApplicationController
def show
+ @retries = nil
data = ActiveWaiter.read(params[:id])
return on_not_found(data) unless data.respond_to?(:[])
return on_error(data) if data[:error]
return on_link_to(data) if data[:link_to] && params[:download]
return on_redirect(data) if data[:link_to]
return on_progress(data) if data[:percentage]
end
protected
def on_not_found(_data)
case retries = params[:retries].to_i
when 0..9
@retries = retries + 1
else
raise ActionController::RoutingError.new('Not Found')
end
end
def on_error(data)
render template: "active_waiter/jobs/error", status: :internal_server_error, locals: data
end
def on_redirect(data)
redirect_to data[:link_to]
end
def on_link_to(data)
render template: "active_waiter/jobs/link_to", locals: data
end
def on_progress(data)
render template: "active_waiter/jobs/progress", locals: data
end
end
end | 1 | 0.02439 | 1 | 0 |
479bffbe3519505d0f0afad39e3f5784d43047fd | cuba-contrib.gemspec | cuba-contrib.gemspec | require "./lib/cuba/contrib/version"
Gem::Specification.new do |s|
s.name = "cuba-contrib"
s.version = "0.1.0.rc1"
s.summary = "Cuba plugins and utilities."
s.description = "Includes various helper tools for Cuba."
s.authors = ["Cyril David"]
s.email = ["me@cyrildavid.com"]
s.homepage = "http://github.com/cyx/cuba-contrib"
s.files = Dir[
"LICENSE",
"README.markdown",
"rakefile",
"lib/**/*.rb",
"*.gemspec",
"test/*.*",
"views/*.mote"
]
s.add_dependency "cuba"
s.add_development_dependency "cutest"
s.add_development_dependency "capybara"
end
| Gem::Specification.new do |s|
s.name = "cuba-contrib"
s.version = "0.1.0.rc1"
s.summary = "Cuba plugins and utilities."
s.description = "Includes various helper tools for Cuba."
s.authors = ["Cyril David"]
s.email = ["me@cyrildavid.com"]
s.homepage = "http://github.com/cyx/cuba-contrib"
s.files = Dir[
"LICENSE",
"README.markdown",
"rakefile",
"lib/**/*.rb",
"*.gemspec",
"test/*.*",
"views/*.mote"
]
s.add_dependency "cuba"
s.add_development_dependency "cutest"
s.add_development_dependency "capybara"
end
| Fix load error in gemspec. | Fix load error in gemspec.
| Ruby | mit | cyx/cuba-contrib | ruby | ## Code Before:
require "./lib/cuba/contrib/version"
Gem::Specification.new do |s|
s.name = "cuba-contrib"
s.version = "0.1.0.rc1"
s.summary = "Cuba plugins and utilities."
s.description = "Includes various helper tools for Cuba."
s.authors = ["Cyril David"]
s.email = ["me@cyrildavid.com"]
s.homepage = "http://github.com/cyx/cuba-contrib"
s.files = Dir[
"LICENSE",
"README.markdown",
"rakefile",
"lib/**/*.rb",
"*.gemspec",
"test/*.*",
"views/*.mote"
]
s.add_dependency "cuba"
s.add_development_dependency "cutest"
s.add_development_dependency "capybara"
end
## Instruction:
Fix load error in gemspec.
## Code After:
Gem::Specification.new do |s|
s.name = "cuba-contrib"
s.version = "0.1.0.rc1"
s.summary = "Cuba plugins and utilities."
s.description = "Includes various helper tools for Cuba."
s.authors = ["Cyril David"]
s.email = ["me@cyrildavid.com"]
s.homepage = "http://github.com/cyx/cuba-contrib"
s.files = Dir[
"LICENSE",
"README.markdown",
"rakefile",
"lib/**/*.rb",
"*.gemspec",
"test/*.*",
"views/*.mote"
]
s.add_dependency "cuba"
s.add_development_dependency "cutest"
s.add_development_dependency "capybara"
end
| - require "./lib/cuba/contrib/version"
-
Gem::Specification.new do |s|
s.name = "cuba-contrib"
s.version = "0.1.0.rc1"
s.summary = "Cuba plugins and utilities."
s.description = "Includes various helper tools for Cuba."
s.authors = ["Cyril David"]
s.email = ["me@cyrildavid.com"]
s.homepage = "http://github.com/cyx/cuba-contrib"
s.files = Dir[
"LICENSE",
"README.markdown",
"rakefile",
"lib/**/*.rb",
"*.gemspec",
"test/*.*",
"views/*.mote"
]
s.add_dependency "cuba"
s.add_development_dependency "cutest"
s.add_development_dependency "capybara"
end | 2 | 0.08 | 0 | 2 |
8a6a21458965d074510b5a0ab338c0bd3e757973 | Core/src/main/kotlin/org/brightify/reactant/core/component/Component.kt | Core/src/main/kotlin/org/brightify/reactant/core/component/Component.kt | package org.brightify.reactant.core.component
import io.reactivex.Observable
import io.reactivex.disposables.CompositeDisposable
import org.brightify.reactant.core.LifetimeDisposeBagContainer
/**
* @author <a href="mailto:filip.dolnik.96@gmail.com">Filip Dolnik</a>
*/
interface Component<STATE, ACTION>: LifetimeDisposeBagContainer {
val stateDisposeBag: CompositeDisposable
val observableState: Observable<STATE>
val previousComponentState: STATE?
var componentState: STATE
val action: Observable<ACTION>
fun afterInit()
fun needsUpdate(): Boolean
fun update()
fun perform(action: ACTION)
}
fun <STATE, ACTION> Component<STATE, ACTION>.setComponentState(state: STATE) {
componentState = state
}
fun <STATE, ACTION> Component<STATE, ACTION>.withState(state: STATE): Component<STATE, ACTION> {
setComponentState(state)
return this
}
fun <STATE: MutableComponentState<STATE>>Component<STATE, *>.mutateState(mutation: STATE.() -> Unit) {
val copy = componentState.clone()
mutation(copy)
setComponentState(copy)
}
| package org.brightify.reactant.core.component
import io.reactivex.Observable
import io.reactivex.disposables.CompositeDisposable
import org.brightify.reactant.core.LifetimeDisposeBagContainer
/**
* @author <a href="mailto:filip.dolnik.96@gmail.com">Filip Dolnik</a>
*/
interface Component<STATE, ACTION>: LifetimeDisposeBagContainer {
val stateDisposeBag: CompositeDisposable
val observableState: Observable<STATE>
val previousComponentState: STATE?
var componentState: STATE
val action: Observable<ACTION>
fun afterInit()
fun needsUpdate(): Boolean
fun update()
fun perform(action: ACTION)
}
fun <STATE, ACTION> Component<STATE, ACTION>.setComponentState(state: STATE) {
componentState = state
}
fun <STATE, ACTION, COMPONENT: Component<STATE, ACTION>> COMPONENT.withState(state: STATE): COMPONENT {
setComponentState(state)
return this
}
fun <STATE: MutableComponentState<STATE>>Component<STATE, *>.mutateState(mutation: STATE.() -> Unit) {
val copy = componentState.clone()
mutation(copy)
setComponentState(copy)
}
| Make `withState` return concrete type. | Make `withState` return concrete type.
| Kotlin | mit | KotlinKit/Reactant | kotlin | ## Code Before:
package org.brightify.reactant.core.component
import io.reactivex.Observable
import io.reactivex.disposables.CompositeDisposable
import org.brightify.reactant.core.LifetimeDisposeBagContainer
/**
* @author <a href="mailto:filip.dolnik.96@gmail.com">Filip Dolnik</a>
*/
interface Component<STATE, ACTION>: LifetimeDisposeBagContainer {
val stateDisposeBag: CompositeDisposable
val observableState: Observable<STATE>
val previousComponentState: STATE?
var componentState: STATE
val action: Observable<ACTION>
fun afterInit()
fun needsUpdate(): Boolean
fun update()
fun perform(action: ACTION)
}
fun <STATE, ACTION> Component<STATE, ACTION>.setComponentState(state: STATE) {
componentState = state
}
fun <STATE, ACTION> Component<STATE, ACTION>.withState(state: STATE): Component<STATE, ACTION> {
setComponentState(state)
return this
}
fun <STATE: MutableComponentState<STATE>>Component<STATE, *>.mutateState(mutation: STATE.() -> Unit) {
val copy = componentState.clone()
mutation(copy)
setComponentState(copy)
}
## Instruction:
Make `withState` return concrete type.
## Code After:
package org.brightify.reactant.core.component
import io.reactivex.Observable
import io.reactivex.disposables.CompositeDisposable
import org.brightify.reactant.core.LifetimeDisposeBagContainer
/**
* @author <a href="mailto:filip.dolnik.96@gmail.com">Filip Dolnik</a>
*/
interface Component<STATE, ACTION>: LifetimeDisposeBagContainer {
val stateDisposeBag: CompositeDisposable
val observableState: Observable<STATE>
val previousComponentState: STATE?
var componentState: STATE
val action: Observable<ACTION>
fun afterInit()
fun needsUpdate(): Boolean
fun update()
fun perform(action: ACTION)
}
fun <STATE, ACTION> Component<STATE, ACTION>.setComponentState(state: STATE) {
componentState = state
}
fun <STATE, ACTION, COMPONENT: Component<STATE, ACTION>> COMPONENT.withState(state: STATE): COMPONENT {
setComponentState(state)
return this
}
fun <STATE: MutableComponentState<STATE>>Component<STATE, *>.mutateState(mutation: STATE.() -> Unit) {
val copy = componentState.clone()
mutation(copy)
setComponentState(copy)
}
| package org.brightify.reactant.core.component
import io.reactivex.Observable
import io.reactivex.disposables.CompositeDisposable
import org.brightify.reactant.core.LifetimeDisposeBagContainer
/**
* @author <a href="mailto:filip.dolnik.96@gmail.com">Filip Dolnik</a>
*/
interface Component<STATE, ACTION>: LifetimeDisposeBagContainer {
val stateDisposeBag: CompositeDisposable
val observableState: Observable<STATE>
val previousComponentState: STATE?
var componentState: STATE
val action: Observable<ACTION>
fun afterInit()
fun needsUpdate(): Boolean
fun update()
fun perform(action: ACTION)
}
fun <STATE, ACTION> Component<STATE, ACTION>.setComponentState(state: STATE) {
componentState = state
}
- fun <STATE, ACTION> Component<STATE, ACTION>.withState(state: STATE): Component<STATE, ACTION> {
+ fun <STATE, ACTION, COMPONENT: Component<STATE, ACTION>> COMPONENT.withState(state: STATE): COMPONENT {
setComponentState(state)
return this
}
fun <STATE: MutableComponentState<STATE>>Component<STATE, *>.mutateState(mutation: STATE.() -> Unit) {
val copy = componentState.clone()
mutation(copy)
setComponentState(copy)
} | 2 | 0.046512 | 1 | 1 |
9c6d9697754d3e661794fa7be890ebccde6818ed | doc/cla/corporate/merchise.md | doc/cla/corporate/merchise.md | Cuba, 2017-07-03
Merchise Autrement [~º/~] agrees to the terms of the Odoo Corporate
Contributor License Agreement v1.0.
I declare that I am authorized and able to make this agreement and sign this
declaration.
Signed,
Manuel Vázquez Acosta manuel@merchise.org https://github.com/mvaled
List of contributors:
Manuel Vázquez Acosta manuel@merchise.org https://github.com/mvaled
Johanny Rivera johanny@merchise.org
Henrik Pestano henrik@merchise.org https://github.com/hpestano
Oraldo Jacinto Simón oraldo@merchise.org
Sergio Valdés sergiov@merchise.org
Medardo Rodríguez med@merchise.org https://github.com/med-merchise
Abel Firvida firvida@merchise.org
Abel Firvida abel@merchise.org
Mónica Díaz Pena monicadp@merchise.org https://github.com/mdpena
| Cuba, 2017-07-03
Merchise Autrement [~º/~] agrees to the terms of the Odoo Corporate
Contributor License Agreement v1.0.
I declare that I am authorized and able to make this agreement and sign this
declaration.
Signed,
Manuel Vázquez Acosta manuel@merchise.org https://github.com/mvaled
List of contributors:
Manuel Vázquez Acosta manuel@merchise.org https://github.com/mvaled
Johanny Rivera johanny@merchise.org
Henrik Pestano henrik@merchise.org https://github.com/hpestano
Oraldo Jacinto Simón oraldo@merchise.org
Sergio Valdés sergiov@merchise.org
Medardo Rodríguez med@merchise.org https://github.com/med-merchise
Abel Firvida firvida@merchise.org
Abel Firvida abel@merchise.org
Mónica Díaz Pena monicadp@merchise.org https://github.com/mdpena
Larisa González larisa@merchise.org
| Add Larisa to Merchise Autrement. | [CLA] Add Larisa to Merchise Autrement. | Markdown | agpl-3.0 | ygol/odoo,ygol/odoo,ygol/odoo,ygol/odoo,ygol/odoo,ygol/odoo,ygol/odoo | markdown | ## Code Before:
Cuba, 2017-07-03
Merchise Autrement [~º/~] agrees to the terms of the Odoo Corporate
Contributor License Agreement v1.0.
I declare that I am authorized and able to make this agreement and sign this
declaration.
Signed,
Manuel Vázquez Acosta manuel@merchise.org https://github.com/mvaled
List of contributors:
Manuel Vázquez Acosta manuel@merchise.org https://github.com/mvaled
Johanny Rivera johanny@merchise.org
Henrik Pestano henrik@merchise.org https://github.com/hpestano
Oraldo Jacinto Simón oraldo@merchise.org
Sergio Valdés sergiov@merchise.org
Medardo Rodríguez med@merchise.org https://github.com/med-merchise
Abel Firvida firvida@merchise.org
Abel Firvida abel@merchise.org
Mónica Díaz Pena monicadp@merchise.org https://github.com/mdpena
## Instruction:
[CLA] Add Larisa to Merchise Autrement.
## Code After:
Cuba, 2017-07-03
Merchise Autrement [~º/~] agrees to the terms of the Odoo Corporate
Contributor License Agreement v1.0.
I declare that I am authorized and able to make this agreement and sign this
declaration.
Signed,
Manuel Vázquez Acosta manuel@merchise.org https://github.com/mvaled
List of contributors:
Manuel Vázquez Acosta manuel@merchise.org https://github.com/mvaled
Johanny Rivera johanny@merchise.org
Henrik Pestano henrik@merchise.org https://github.com/hpestano
Oraldo Jacinto Simón oraldo@merchise.org
Sergio Valdés sergiov@merchise.org
Medardo Rodríguez med@merchise.org https://github.com/med-merchise
Abel Firvida firvida@merchise.org
Abel Firvida abel@merchise.org
Mónica Díaz Pena monicadp@merchise.org https://github.com/mdpena
Larisa González larisa@merchise.org
| Cuba, 2017-07-03
Merchise Autrement [~º/~] agrees to the terms of the Odoo Corporate
Contributor License Agreement v1.0.
I declare that I am authorized and able to make this agreement and sign this
declaration.
Signed,
Manuel Vázquez Acosta manuel@merchise.org https://github.com/mvaled
List of contributors:
Manuel Vázquez Acosta manuel@merchise.org https://github.com/mvaled
Johanny Rivera johanny@merchise.org
Henrik Pestano henrik@merchise.org https://github.com/hpestano
Oraldo Jacinto Simón oraldo@merchise.org
Sergio Valdés sergiov@merchise.org
Medardo Rodríguez med@merchise.org https://github.com/med-merchise
Abel Firvida firvida@merchise.org
Abel Firvida abel@merchise.org
Mónica Díaz Pena monicadp@merchise.org https://github.com/mdpena
+ Larisa González larisa@merchise.org | 1 | 0.043478 | 1 | 0 |
0043c4b3961751195316ce56776298108ae45232 | src/assets/styles/vendor/_str-replace.scss | src/assets/styles/vendor/_str-replace.scss | // https://css-tricks.com/snippets/sass/str-replace-function/
/// Replace `$search` with `$replace` in `$string`
/// @author Hugo Giraudel
/// @param {String} $string - Initial string
/// @param {String} $search - Substring to replace
/// @param {String} $replace ('') - New value
/// @return {String} - Updated string
@function str-replace($string, $search, $replace: '') {
$index: str-index($string, $search);
@if $index {
@return str-slice($string, 1, $index - 1) + $replace + str-replace(str-slice($string, $index + str-length($search)), $search, $replace);
}
@return $string;
}
| // https://css-tricks.com/snippets/sass/str-replace-function/
/* stylelint-disable */
/// Replace `$search` with `$replace` in `$string`
/// @author Hugo Giraudel
/// @param {String} $string - Initial string
/// @param {String} $search - Substring to replace
/// @param {String} $replace ('') - New value
/// @return {String} - Updated string
@function str-replace($string, $search, $replace: '') {
$index: str-index($string, $search);
@if $index {
@return str-slice($string, 1, $index - 1) + $replace + str-replace(str-slice($string, $index + str-length($search)), $search, $replace);
}
@return $string;
}
| Disable stylelint for vendor file | Disable stylelint for vendor file
| SCSS | mit | JacobDB/new-site,revxx14/new-site,JacobDB/new-site,revxx14/new-site,JacobDB/new-site | scss | ## Code Before:
// https://css-tricks.com/snippets/sass/str-replace-function/
/// Replace `$search` with `$replace` in `$string`
/// @author Hugo Giraudel
/// @param {String} $string - Initial string
/// @param {String} $search - Substring to replace
/// @param {String} $replace ('') - New value
/// @return {String} - Updated string
@function str-replace($string, $search, $replace: '') {
$index: str-index($string, $search);
@if $index {
@return str-slice($string, 1, $index - 1) + $replace + str-replace(str-slice($string, $index + str-length($search)), $search, $replace);
}
@return $string;
}
## Instruction:
Disable stylelint for vendor file
## Code After:
// https://css-tricks.com/snippets/sass/str-replace-function/
/* stylelint-disable */
/// Replace `$search` with `$replace` in `$string`
/// @author Hugo Giraudel
/// @param {String} $string - Initial string
/// @param {String} $search - Substring to replace
/// @param {String} $replace ('') - New value
/// @return {String} - Updated string
@function str-replace($string, $search, $replace: '') {
$index: str-index($string, $search);
@if $index {
@return str-slice($string, 1, $index - 1) + $replace + str-replace(str-slice($string, $index + str-length($search)), $search, $replace);
}
@return $string;
}
| // https://css-tricks.com/snippets/sass/str-replace-function/
+
+ /* stylelint-disable */
/// Replace `$search` with `$replace` in `$string`
/// @author Hugo Giraudel
/// @param {String} $string - Initial string
/// @param {String} $search - Substring to replace
/// @param {String} $replace ('') - New value
/// @return {String} - Updated string
@function str-replace($string, $search, $replace: '') {
$index: str-index($string, $search);
@if $index {
@return str-slice($string, 1, $index - 1) + $replace + str-replace(str-slice($string, $index + str-length($search)), $search, $replace);
}
@return $string;
} | 2 | 0.117647 | 2 | 0 |
fbe6d55c46c6335c2320bbb16cdaa93dc4eb82ed | .travis.yml | .travis.yml | sudo: false
dist: precise
language: node_js
node_js:
- "0.10"
- "0.12"
- "4"
- "6"
addons:
apt:
sources:
- ubuntu-toolchain-r-test
packages:
- g++-4.9
env:
- CXX=g++-4.9 CMAKE_VERSION=3.2.3
cache:
directories:
- cmake-3.2.3
before_install:
- $CXX --version
- |
if [ -z "$(ls -A cmake-$CMAKE_VERSION)" ]; then
CMAKE_URL="http://www.cmake.org/files/v${CMAKE_VERSION:0:3}/cmake-${CMAKE_VERSION}-Linux-x86_64.tar.gz"
mkdir -p cmake-${CMAKE_VERSION} && travis_retry wget --no-check-certificate --quiet -O - ${CMAKE_URL} | tar --strip-components=1 -xz -C cmake-${CMAKE_VERSION}
fi
export PATH=${TRAVIS_BUILD_DIR}/cmake-${CMAKE_VERSION}/bin:${PATH}
cmake --version
| sudo: false
dist: precise
language: node_js
node_js:
- "0.10"
- "0.12"
- "4"
- "6"
addons:
apt:
sources:
- ubuntu-toolchain-r-test
packages:
- g++-4.9
artifacts: true
env:
- CXX=g++-4.9 CMAKE_VERSION=3.2.3
cache:
directories:
- node_modules
- cmake-3.2.3
before_install:
- $CXX --version
- |
if [ -z "$(ls -A cmake-$CMAKE_VERSION)" ]; then
CMAKE_URL="http://www.cmake.org/files/v${CMAKE_VERSION:0:3}/cmake-${CMAKE_VERSION}-Linux-x86_64.tar.gz"
mkdir -p cmake-${CMAKE_VERSION} && travis_retry wget --no-check-certificate --quiet -O - ${CMAKE_URL} | tar --strip-components=1 -xz -C cmake-${CMAKE_VERSION}
fi
export PATH=${TRAVIS_BUILD_DIR}/cmake-${CMAKE_VERSION}/bin:${PATH}
cmake --version
| Add artifact uploading, and re-add node_modules cache | Add artifact uploading, and re-add node_modules cache
| YAML | mpl-2.0 | Xtansia/node.anitomy.js,Xtansia/node.anitomy.js | yaml | ## Code Before:
sudo: false
dist: precise
language: node_js
node_js:
- "0.10"
- "0.12"
- "4"
- "6"
addons:
apt:
sources:
- ubuntu-toolchain-r-test
packages:
- g++-4.9
env:
- CXX=g++-4.9 CMAKE_VERSION=3.2.3
cache:
directories:
- cmake-3.2.3
before_install:
- $CXX --version
- |
if [ -z "$(ls -A cmake-$CMAKE_VERSION)" ]; then
CMAKE_URL="http://www.cmake.org/files/v${CMAKE_VERSION:0:3}/cmake-${CMAKE_VERSION}-Linux-x86_64.tar.gz"
mkdir -p cmake-${CMAKE_VERSION} && travis_retry wget --no-check-certificate --quiet -O - ${CMAKE_URL} | tar --strip-components=1 -xz -C cmake-${CMAKE_VERSION}
fi
export PATH=${TRAVIS_BUILD_DIR}/cmake-${CMAKE_VERSION}/bin:${PATH}
cmake --version
## Instruction:
Add artifact uploading, and re-add node_modules cache
## Code After:
sudo: false
dist: precise
language: node_js
node_js:
- "0.10"
- "0.12"
- "4"
- "6"
addons:
apt:
sources:
- ubuntu-toolchain-r-test
packages:
- g++-4.9
artifacts: true
env:
- CXX=g++-4.9 CMAKE_VERSION=3.2.3
cache:
directories:
- node_modules
- cmake-3.2.3
before_install:
- $CXX --version
- |
if [ -z "$(ls -A cmake-$CMAKE_VERSION)" ]; then
CMAKE_URL="http://www.cmake.org/files/v${CMAKE_VERSION:0:3}/cmake-${CMAKE_VERSION}-Linux-x86_64.tar.gz"
mkdir -p cmake-${CMAKE_VERSION} && travis_retry wget --no-check-certificate --quiet -O - ${CMAKE_URL} | tar --strip-components=1 -xz -C cmake-${CMAKE_VERSION}
fi
export PATH=${TRAVIS_BUILD_DIR}/cmake-${CMAKE_VERSION}/bin:${PATH}
cmake --version
| sudo: false
dist: precise
language: node_js
node_js:
- "0.10"
- "0.12"
- "4"
- "6"
addons:
apt:
sources:
- ubuntu-toolchain-r-test
packages:
- g++-4.9
+ artifacts: true
env:
- CXX=g++-4.9 CMAKE_VERSION=3.2.3
cache:
directories:
+ - node_modules
- cmake-3.2.3
before_install:
- $CXX --version
- |
if [ -z "$(ls -A cmake-$CMAKE_VERSION)" ]; then
CMAKE_URL="http://www.cmake.org/files/v${CMAKE_VERSION:0:3}/cmake-${CMAKE_VERSION}-Linux-x86_64.tar.gz"
mkdir -p cmake-${CMAKE_VERSION} && travis_retry wget --no-check-certificate --quiet -O - ${CMAKE_URL} | tar --strip-components=1 -xz -C cmake-${CMAKE_VERSION}
fi
export PATH=${TRAVIS_BUILD_DIR}/cmake-${CMAKE_VERSION}/bin:${PATH}
cmake --version | 2 | 0.060606 | 2 | 0 |
2bb4461378cec090c165f16483e4dc47c45f23dd | test/api/loader.spec.coffee | test/api/loader.spec.coffee | {Testing, expect, sinon, _} = require 'openstax-react-components/test/helpers'
$ = require 'jquery'
describe 'API loader', ->
beforeEach ->
@jquery =
ajax: sinon.spy ->
d = $.Deferred()
_.defer -> d.resolve({})
d.promise()
delete require.cache[require.resolve('api')]
delete require.cache[require.resolve('api/loader')]
require.cache[require.resolve('jquery')].exports = @jquery
@api = require 'api'
@api.initialize('test/url')
afterEach ->
require.cache[require.resolve('jquery')].exports = $
# force require to re-parse the api file now that the stub's removed
delete require.cache[require.resolve('api/loader')]
it 'sets isPending', (done) ->
expect(@api.isPending()).to.be.false
@api.channel.emit('user.status.send.fetch', data: {})
_.delay( =>
expect(@jquery.ajax.callCount).equal(1)
expect(@api.isPending()).to.be.true
, 1)
_.delay( =>
expect(@api.isPending()).to.be.false
done()
, 210) # longer than loader's isLocal delay
it 'debounces calls to the same URL', ->
for i in [1..10]
@api.channel.emit('user.status.send.fetch', data: {})
_.delay =>
expect(@jquery.ajax.callCount).equal(1)
| {Testing, expect, sinon, _} = require 'openstax-react-components/test/helpers'
$ = require 'jquery'
describe 'API loader', ->
beforeEach ->
@jquery =
ajax: sinon.spy ->
d = $.Deferred()
_.defer -> d.resolve({})
d.promise()
delete require.cache[require.resolve('api')]
delete require.cache[require.resolve('api/loader')]
require.cache[require.resolve('jquery')].exports = @jquery
@api = require 'api'
@api.initialize('test/url')
afterEach ->
require.cache[require.resolve('jquery')].exports = $
# force require to re-parse the api file now that the stub's removed
delete require.cache[require.resolve('api/loader')]
it 'sets isPending', (done) ->
expect(@api.isPending()).to.be.false
@api.channel.emit('user.status.send.fetch', data: {})
_.delay( =>
expect(@api.isPending()).to.be.true
, 1)
_.delay =>
expect(@api.isPending()).to.be.false
done()
, 21 # longer than loader's isLocal delay
it 'debounces calls to the same URL', (done) ->
for i in [1..10]
@api.channel.emit('user.status.send.fetch', data: {})
_.delay =>
expect(@jquery.ajax.callCount).equal(1)
done()
, 21
| Add done() and set delay | Add done() and set delay
| CoffeeScript | agpl-3.0 | openstax/tutor-js,openstax/tutor-js,openstax/tutor-js,openstax/tutor-js,openstax/tutor-js | coffeescript | ## Code Before:
{Testing, expect, sinon, _} = require 'openstax-react-components/test/helpers'
$ = require 'jquery'
describe 'API loader', ->
beforeEach ->
@jquery =
ajax: sinon.spy ->
d = $.Deferred()
_.defer -> d.resolve({})
d.promise()
delete require.cache[require.resolve('api')]
delete require.cache[require.resolve('api/loader')]
require.cache[require.resolve('jquery')].exports = @jquery
@api = require 'api'
@api.initialize('test/url')
afterEach ->
require.cache[require.resolve('jquery')].exports = $
# force require to re-parse the api file now that the stub's removed
delete require.cache[require.resolve('api/loader')]
it 'sets isPending', (done) ->
expect(@api.isPending()).to.be.false
@api.channel.emit('user.status.send.fetch', data: {})
_.delay( =>
expect(@jquery.ajax.callCount).equal(1)
expect(@api.isPending()).to.be.true
, 1)
_.delay( =>
expect(@api.isPending()).to.be.false
done()
, 210) # longer than loader's isLocal delay
it 'debounces calls to the same URL', ->
for i in [1..10]
@api.channel.emit('user.status.send.fetch', data: {})
_.delay =>
expect(@jquery.ajax.callCount).equal(1)
## Instruction:
Add done() and set delay
## Code After:
{Testing, expect, sinon, _} = require 'openstax-react-components/test/helpers'
$ = require 'jquery'
describe 'API loader', ->
beforeEach ->
@jquery =
ajax: sinon.spy ->
d = $.Deferred()
_.defer -> d.resolve({})
d.promise()
delete require.cache[require.resolve('api')]
delete require.cache[require.resolve('api/loader')]
require.cache[require.resolve('jquery')].exports = @jquery
@api = require 'api'
@api.initialize('test/url')
afterEach ->
require.cache[require.resolve('jquery')].exports = $
# force require to re-parse the api file now that the stub's removed
delete require.cache[require.resolve('api/loader')]
it 'sets isPending', (done) ->
expect(@api.isPending()).to.be.false
@api.channel.emit('user.status.send.fetch', data: {})
_.delay( =>
expect(@api.isPending()).to.be.true
, 1)
_.delay =>
expect(@api.isPending()).to.be.false
done()
, 21 # longer than loader's isLocal delay
it 'debounces calls to the same URL', (done) ->
for i in [1..10]
@api.channel.emit('user.status.send.fetch', data: {})
_.delay =>
expect(@jquery.ajax.callCount).equal(1)
done()
, 21
| {Testing, expect, sinon, _} = require 'openstax-react-components/test/helpers'
$ = require 'jquery'
describe 'API loader', ->
beforeEach ->
@jquery =
ajax: sinon.spy ->
d = $.Deferred()
_.defer -> d.resolve({})
d.promise()
delete require.cache[require.resolve('api')]
delete require.cache[require.resolve('api/loader')]
require.cache[require.resolve('jquery')].exports = @jquery
@api = require 'api'
@api.initialize('test/url')
afterEach ->
require.cache[require.resolve('jquery')].exports = $
# force require to re-parse the api file now that the stub's removed
delete require.cache[require.resolve('api/loader')]
it 'sets isPending', (done) ->
expect(@api.isPending()).to.be.false
@api.channel.emit('user.status.send.fetch', data: {})
_.delay( =>
- expect(@jquery.ajax.callCount).equal(1)
expect(@api.isPending()).to.be.true
, 1)
- _.delay( =>
? -
+ _.delay =>
expect(@api.isPending()).to.be.false
done()
- , 210) # longer than loader's isLocal delay
? --
+ , 21 # longer than loader's isLocal delay
- it 'debounces calls to the same URL', ->
+ it 'debounces calls to the same URL', (done) ->
? +++++++
for i in [1..10]
@api.channel.emit('user.status.send.fetch', data: {})
_.delay =>
expect(@jquery.ajax.callCount).equal(1)
+ done()
+ , 21 | 9 | 0.219512 | 5 | 4 |
6fbbfa746faf0820d64890d2f8c02921424a97aa | README.rst | README.rst | .. image:: https://travis-ci.org/globus/globus-sdk-python.svg?branch=master
:alt: build status
:target: https://travis-ci.org/globus/globus-sdk-python
.. image:: https://img.shields.io/pypi/v/globus-sdk.svg
:alt: Latest Released Version
:target: https://pypi.org/project/globus-sdk/
.. image:: https://img.shields.io/pypi/pyversions/globus-sdk.svg
:alt: Supported Python Versions
:target: https://pypi.org/project/globus-sdk/
.. image:: https://img.shields.io/github/license/globus/globus-sdk-python.svg
:alt: License
Globus SDK for Python
=====================
This SDK provides a convenient Pythonic interface to
`Globus <https://www.globus.org>`_ APIs.
Documentation
-------------
| Full Documentation: http://globus-sdk-python.readthedocs.io/
| Source Code: https://github.com/globus/globus-sdk-python
| API Documentation: https://docs.globus.org/api/
| Release History + Changelog: https://github.com/globus/globus-sdk-python/releases
| .. image:: https://travis-ci.org/globus/globus-sdk-python.svg?branch=master
:alt: build status
:target: https://travis-ci.org/globus/globus-sdk-python
.. image:: https://img.shields.io/pypi/v/globus-sdk.svg
:alt: Latest Released Version
:target: https://pypi.org/project/globus-sdk/
.. image:: https://img.shields.io/pypi/pyversions/globus-sdk.svg
:alt: Supported Python Versions
:target: https://pypi.org/project/globus-sdk/
.. image:: https://img.shields.io/badge/License-Apache%202.0-blue.svg
:alt: License
:target: https://opensource.org/licenses/Apache-2.0
Globus SDK for Python
=====================
This SDK provides a convenient Pythonic interface to
`Globus <https://www.globus.org>`_ APIs.
Documentation
-------------
| Full Documentation: http://globus-sdk-python.readthedocs.io/
| Source Code: https://github.com/globus/globus-sdk-python
| API Documentation: https://docs.globus.org/api/
| Release History + Changelog: https://github.com/globus/globus-sdk-python/releases
| Fix license badge in readme | Fix license badge in readme
| reStructuredText | apache-2.0 | globus/globus-sdk-python,sirosen/globus-sdk-python,globus/globus-sdk-python,globusonline/globus-sdk-python | restructuredtext | ## Code Before:
.. image:: https://travis-ci.org/globus/globus-sdk-python.svg?branch=master
:alt: build status
:target: https://travis-ci.org/globus/globus-sdk-python
.. image:: https://img.shields.io/pypi/v/globus-sdk.svg
:alt: Latest Released Version
:target: https://pypi.org/project/globus-sdk/
.. image:: https://img.shields.io/pypi/pyversions/globus-sdk.svg
:alt: Supported Python Versions
:target: https://pypi.org/project/globus-sdk/
.. image:: https://img.shields.io/github/license/globus/globus-sdk-python.svg
:alt: License
Globus SDK for Python
=====================
This SDK provides a convenient Pythonic interface to
`Globus <https://www.globus.org>`_ APIs.
Documentation
-------------
| Full Documentation: http://globus-sdk-python.readthedocs.io/
| Source Code: https://github.com/globus/globus-sdk-python
| API Documentation: https://docs.globus.org/api/
| Release History + Changelog: https://github.com/globus/globus-sdk-python/releases
## Instruction:
Fix license badge in readme
## Code After:
.. image:: https://travis-ci.org/globus/globus-sdk-python.svg?branch=master
:alt: build status
:target: https://travis-ci.org/globus/globus-sdk-python
.. image:: https://img.shields.io/pypi/v/globus-sdk.svg
:alt: Latest Released Version
:target: https://pypi.org/project/globus-sdk/
.. image:: https://img.shields.io/pypi/pyversions/globus-sdk.svg
:alt: Supported Python Versions
:target: https://pypi.org/project/globus-sdk/
.. image:: https://img.shields.io/badge/License-Apache%202.0-blue.svg
:alt: License
:target: https://opensource.org/licenses/Apache-2.0
Globus SDK for Python
=====================
This SDK provides a convenient Pythonic interface to
`Globus <https://www.globus.org>`_ APIs.
Documentation
-------------
| Full Documentation: http://globus-sdk-python.readthedocs.io/
| Source Code: https://github.com/globus/globus-sdk-python
| API Documentation: https://docs.globus.org/api/
| Release History + Changelog: https://github.com/globus/globus-sdk-python/releases
| .. image:: https://travis-ci.org/globus/globus-sdk-python.svg?branch=master
:alt: build status
:target: https://travis-ci.org/globus/globus-sdk-python
.. image:: https://img.shields.io/pypi/v/globus-sdk.svg
:alt: Latest Released Version
:target: https://pypi.org/project/globus-sdk/
.. image:: https://img.shields.io/pypi/pyversions/globus-sdk.svg
:alt: Supported Python Versions
:target: https://pypi.org/project/globus-sdk/
- .. image:: https://img.shields.io/github/license/globus/globus-sdk-python.svg
+ .. image:: https://img.shields.io/badge/License-Apache%202.0-blue.svg
:alt: License
+ :target: https://opensource.org/licenses/Apache-2.0
Globus SDK for Python
=====================
This SDK provides a convenient Pythonic interface to
`Globus <https://www.globus.org>`_ APIs.
Documentation
-------------
| Full Documentation: http://globus-sdk-python.readthedocs.io/
| Source Code: https://github.com/globus/globus-sdk-python
| API Documentation: https://docs.globus.org/api/
| Release History + Changelog: https://github.com/globus/globus-sdk-python/releases | 3 | 0.103448 | 2 | 1 |
e50ead6f47719b7e8a00ab635fd533fa33c4c1ed | ruby/aliases.zsh | ruby/aliases.zsh | alias be='bundle exec'
alias brake='bundle exec rake'
alias server='ruby -run -ehttpd .'
| alias be='bundle exec'
alias brake='bundle exec rake'
alias server='ruby -run -ehttpd .'
alias spec='SKIP_EMBER=true SELENIUM=true bundle exec rspec'
| Add 'spec' alias for running rspec with selenium and without building ember. | Add 'spec' alias for running rspec with selenium and without building ember.
| Shell | mit | mediweb/dotfiles,mediweb/dotfiles | shell | ## Code Before:
alias be='bundle exec'
alias brake='bundle exec rake'
alias server='ruby -run -ehttpd .'
## Instruction:
Add 'spec' alias for running rspec with selenium and without building ember.
## Code After:
alias be='bundle exec'
alias brake='bundle exec rake'
alias server='ruby -run -ehttpd .'
alias spec='SKIP_EMBER=true SELENIUM=true bundle exec rspec'
| alias be='bundle exec'
alias brake='bundle exec rake'
alias server='ruby -run -ehttpd .'
+ alias spec='SKIP_EMBER=true SELENIUM=true bundle exec rspec' | 1 | 0.333333 | 1 | 0 |
838ebb7e7194a27ebb8b9d63211903b741b67938 | js/widgets/con10t_search_query.js | js/widgets/con10t_search_query.js | 'use strict';
angular.module('arachne.widgets.directives')
.directive('con10tSearchQuery', function() {
return {
restrict: 'A',
link: function(scope, element, attrs) {
attrs.$observe('con10tSearchQuery', function(value) {
scope.q = value;
updateHref();
});
attrs.$observe('con10tSearchFacet', function(value) {
scope.fq = value;
updateHref();
});
function updateHref() {
var href = "http://arachne.dainst.org/search?q=" + scope.q;
if (scope.fq) {
var fqs = scope.fq.split(',');
fqs.forEach(function(fq) {
var split = fq.split(':');
href += '&fq='+split[0]+':"'+split[1]+'"';
});
}
element.attr("href", href);
}
}
}}); | 'use strict';
angular.module('arachne.widgets.directives')
.directive('con10tSearchQuery', function() {
return {
restrict: 'A',
link: function(scope, element, attrs) {
attrs.$observe('con10tSearchQuery', function(value) {
scope.q = value;
updateHref();
});
attrs.$observe('con10tSearchFacet', function(value) {
scope.fq = value;
updateHref();
});
function updateHref() {
var href = "http://arachne.dainst.org/search?q=" + scope.q;
if (scope.fq) {
var split, fqs = scope.fq.split(',');
fqs.forEach(function(fq) {
split = fq.split(':');
href += '&fq='+split[0]+':"'+split[1]+'"';
});
}
element.attr("href", href);
}
}
}}); | Move variable declaration out of loop. | Move variable declaration out of loop.
| JavaScript | apache-2.0 | dainst/arachnefrontend,codarchlab/arachnefrontend,codarchlab/arachnefrontend,dainst/arachnefrontend | javascript | ## Code Before:
'use strict';
angular.module('arachne.widgets.directives')
.directive('con10tSearchQuery', function() {
return {
restrict: 'A',
link: function(scope, element, attrs) {
attrs.$observe('con10tSearchQuery', function(value) {
scope.q = value;
updateHref();
});
attrs.$observe('con10tSearchFacet', function(value) {
scope.fq = value;
updateHref();
});
function updateHref() {
var href = "http://arachne.dainst.org/search?q=" + scope.q;
if (scope.fq) {
var fqs = scope.fq.split(',');
fqs.forEach(function(fq) {
var split = fq.split(':');
href += '&fq='+split[0]+':"'+split[1]+'"';
});
}
element.attr("href", href);
}
}
}});
## Instruction:
Move variable declaration out of loop.
## Code After:
'use strict';
angular.module('arachne.widgets.directives')
.directive('con10tSearchQuery', function() {
return {
restrict: 'A',
link: function(scope, element, attrs) {
attrs.$observe('con10tSearchQuery', function(value) {
scope.q = value;
updateHref();
});
attrs.$observe('con10tSearchFacet', function(value) {
scope.fq = value;
updateHref();
});
function updateHref() {
var href = "http://arachne.dainst.org/search?q=" + scope.q;
if (scope.fq) {
var split, fqs = scope.fq.split(',');
fqs.forEach(function(fq) {
split = fq.split(':');
href += '&fq='+split[0]+':"'+split[1]+'"';
});
}
element.attr("href", href);
}
}
}}); | 'use strict';
angular.module('arachne.widgets.directives')
.directive('con10tSearchQuery', function() {
return {
restrict: 'A',
link: function(scope, element, attrs) {
attrs.$observe('con10tSearchQuery', function(value) {
scope.q = value;
updateHref();
});
attrs.$observe('con10tSearchFacet', function(value) {
scope.fq = value;
updateHref();
});
function updateHref() {
var href = "http://arachne.dainst.org/search?q=" + scope.q;
if (scope.fq) {
- var fqs = scope.fq.split(',');
+ var split, fqs = scope.fq.split(',');
? +++++++
fqs.forEach(function(fq) {
- var split = fq.split(':');
? ----
+ split = fq.split(':');
href += '&fq='+split[0]+':"'+split[1]+'"';
});
}
element.attr("href", href);
}
}
}}); | 4 | 0.121212 | 2 | 2 |
3e81a2bfd026475b9ab0548c3127aa102066707d | guest-talks/20170828-oo-intro/exercises/test_square_grid.py | guest-talks/20170828-oo-intro/exercises/test_square_grid.py | import unittest
from square_grid import SquareGrid
class TestSquareGrid(unittest.TestCase):
def setUp(self):
a = [0] * 3
b = [1] * 3
c = [2] * 3
self.matrix= [a,b,c]
self.good_grid = SquareGrid(self.matrix)
def test_error_on_mixed_dimensions(self):
"""Test object initialization"""
four_by_three = self.matrix + [[3] * 3]
with self.assertRaises(ValueError) as err:
g = SquareGrid(four_by_three)
def test_string_representation(self):
"""Test that the object behaves correctly with the `str()` built-n"""
expected_string = '\n'.join(' '.join(str(x) for x in row) for row in m)
self.assertEqual(str(self.good_grid), expected_string)
def test_length(self):
"""Test that the object returns a useful length"""
self.assertEqual(len(self.good_grid), 3)
| import unittest
from square_grid import SquareGrid
class TestSquareGrid(unittest.TestCase):
def setUp(self):
a = [0] * 3
b = [1] * 3
c = [2] * 3
self.matrix= [a,b,c]
self.good_grid = SquareGrid(self.matrix)
def test_error_on_mixed_dimensions(self):
"""Test object initialization"""
four_by_three = self.matrix + [[3] * 3]
with self.assertRaises(ValueError) as err:
g = SquareGrid(four_by_three)
def test_string_representation(self):
"""Test that the object behaves correctly with the `str()` built-in"""
expected_string = "0 0 0\n1 1 1\n2 2 2"
self.assertEqual(str(self.good_grid), expected_string)
def test_length(self):
"""Test that the object returns a useful length"""
self.assertEqual(len(self.good_grid), 3)
| Use literals in tests instead of code ;) | Use literals in tests instead of code ;)
| Python | mit | noisebridge/PythonClass,razzius/PyClassLessons,PyClass/PyClassLessons,PyClass/PyClassLessons,noisebridge/PythonClass,razzius/PyClassLessons,noisebridge/PythonClass,razzius/PyClassLessons,noisebridge/PythonClass,PyClass/PyClassLessons,razzius/PyClassLessons | python | ## Code Before:
import unittest
from square_grid import SquareGrid
class TestSquareGrid(unittest.TestCase):
def setUp(self):
a = [0] * 3
b = [1] * 3
c = [2] * 3
self.matrix= [a,b,c]
self.good_grid = SquareGrid(self.matrix)
def test_error_on_mixed_dimensions(self):
"""Test object initialization"""
four_by_three = self.matrix + [[3] * 3]
with self.assertRaises(ValueError) as err:
g = SquareGrid(four_by_three)
def test_string_representation(self):
"""Test that the object behaves correctly with the `str()` built-n"""
expected_string = '\n'.join(' '.join(str(x) for x in row) for row in m)
self.assertEqual(str(self.good_grid), expected_string)
def test_length(self):
"""Test that the object returns a useful length"""
self.assertEqual(len(self.good_grid), 3)
## Instruction:
Use literals in tests instead of code ;)
## Code After:
import unittest
from square_grid import SquareGrid
class TestSquareGrid(unittest.TestCase):
def setUp(self):
a = [0] * 3
b = [1] * 3
c = [2] * 3
self.matrix= [a,b,c]
self.good_grid = SquareGrid(self.matrix)
def test_error_on_mixed_dimensions(self):
"""Test object initialization"""
four_by_three = self.matrix + [[3] * 3]
with self.assertRaises(ValueError) as err:
g = SquareGrid(four_by_three)
def test_string_representation(self):
"""Test that the object behaves correctly with the `str()` built-in"""
expected_string = "0 0 0\n1 1 1\n2 2 2"
self.assertEqual(str(self.good_grid), expected_string)
def test_length(self):
"""Test that the object returns a useful length"""
self.assertEqual(len(self.good_grid), 3)
| import unittest
from square_grid import SquareGrid
class TestSquareGrid(unittest.TestCase):
def setUp(self):
a = [0] * 3
b = [1] * 3
c = [2] * 3
self.matrix= [a,b,c]
self.good_grid = SquareGrid(self.matrix)
def test_error_on_mixed_dimensions(self):
"""Test object initialization"""
four_by_three = self.matrix + [[3] * 3]
with self.assertRaises(ValueError) as err:
g = SquareGrid(four_by_three)
def test_string_representation(self):
- """Test that the object behaves correctly with the `str()` built-n"""
+ """Test that the object behaves correctly with the `str()` built-in"""
? +
- expected_string = '\n'.join(' '.join(str(x) for x in row) for row in m)
+ expected_string = "0 0 0\n1 1 1\n2 2 2"
self.assertEqual(str(self.good_grid), expected_string)
def test_length(self):
"""Test that the object returns a useful length"""
self.assertEqual(len(self.good_grid), 3) | 4 | 0.16 | 2 | 2 |
45c0de37f32f6fda815086494a99120f29f1f59f | app/styles/ui/_autocompletion.scss | app/styles/ui/_autocompletion.scss | .autocompletion-container {
position: relative;
display: flex;
flex-direction: column;
}
.autocompletion-popup {
display: flex;
position: absolute;
z-index: 2;
width: 200px;
height: 100px;
background-color: white;
}
| .autocompletion-container {
position: relative;
display: flex;
flex-direction: column;
}
.autocompletion-popup {
display: flex;
position: absolute;
z-index: 2;
width: 200px;
height: 100px;
background-color: white;
border: var(--base-border);
border-radius: var(--border-radius);
box-shadow: 0px 0px 8px rgba(0, 0, 0, 0.3);
}
| Make it stand out better against a background | Make it stand out better against a background
| SCSS | mit | j-f1/forked-desktop,desktop/desktop,artivilla/desktop,artivilla/desktop,desktop/desktop,j-f1/forked-desktop,gengjiawen/desktop,shiftkey/desktop,gengjiawen/desktop,shiftkey/desktop,kactus-io/kactus,BugTesterTest/desktops,kactus-io/kactus,say25/desktop,j-f1/forked-desktop,say25/desktop,shiftkey/desktop,hjobrien/desktop,artivilla/desktop,gengjiawen/desktop,artivilla/desktop,hjobrien/desktop,BugTesterTest/desktops,kactus-io/kactus,kactus-io/kactus,shiftkey/desktop,hjobrien/desktop,hjobrien/desktop,BugTesterTest/desktops,gengjiawen/desktop,say25/desktop,j-f1/forked-desktop,BugTesterTest/desktops,say25/desktop,desktop/desktop,desktop/desktop | scss | ## Code Before:
.autocompletion-container {
position: relative;
display: flex;
flex-direction: column;
}
.autocompletion-popup {
display: flex;
position: absolute;
z-index: 2;
width: 200px;
height: 100px;
background-color: white;
}
## Instruction:
Make it stand out better against a background
## Code After:
.autocompletion-container {
position: relative;
display: flex;
flex-direction: column;
}
.autocompletion-popup {
display: flex;
position: absolute;
z-index: 2;
width: 200px;
height: 100px;
background-color: white;
border: var(--base-border);
border-radius: var(--border-radius);
box-shadow: 0px 0px 8px rgba(0, 0, 0, 0.3);
}
| .autocompletion-container {
position: relative;
display: flex;
flex-direction: column;
}
.autocompletion-popup {
display: flex;
position: absolute;
z-index: 2;
width: 200px;
height: 100px;
background-color: white;
+ border: var(--base-border);
+ border-radius: var(--border-radius);
+
+ box-shadow: 0px 0px 8px rgba(0, 0, 0, 0.3);
} | 4 | 0.266667 | 4 | 0 |
db2c3769d1ec29d0de8ccb6ed89f4c054c2c949b | src/index.js | src/index.js | import { render } from 'solid-js/web';
import Player from './components/Player';
function create(props, elem) {
let el;
const dispose = render(() => {
el = <Player {...props} />;
return el;
}, elem);
return {
el: el,
dispose: dispose
}
}
export { create };
| import { render } from 'solid-js/web';
import Player from './components/Player';
function create(props, elem) {
let el;
if (typeof props === 'string') {
props = { src: props };
}
const dispose = render(() => {
el = <Player {...props} />;
return el;
}, elem);
return {
el: el,
dispose: dispose
}
}
export { create };
| Upgrade src arg to object automatically | Upgrade src arg to object automatically
| JavaScript | apache-2.0 | asciinema/asciinema-player,asciinema/asciinema-player | javascript | ## Code Before:
import { render } from 'solid-js/web';
import Player from './components/Player';
function create(props, elem) {
let el;
const dispose = render(() => {
el = <Player {...props} />;
return el;
}, elem);
return {
el: el,
dispose: dispose
}
}
export { create };
## Instruction:
Upgrade src arg to object automatically
## Code After:
import { render } from 'solid-js/web';
import Player from './components/Player';
function create(props, elem) {
let el;
if (typeof props === 'string') {
props = { src: props };
}
const dispose = render(() => {
el = <Player {...props} />;
return el;
}, elem);
return {
el: el,
dispose: dispose
}
}
export { create };
| import { render } from 'solid-js/web';
import Player from './components/Player';
function create(props, elem) {
let el;
+
+ if (typeof props === 'string') {
+ props = { src: props };
+ }
const dispose = render(() => {
el = <Player {...props} />;
return el;
}, elem);
return {
el: el,
dispose: dispose
}
}
export { create }; | 4 | 0.222222 | 4 | 0 |
df972b8bb401428e40e5c10e900ced9629e09987 | .delivery/build_cookbook/recipes/_install_docker.rb | .delivery/build_cookbook/recipes/_install_docker.rb | include_recipe 'chef-apt-docker::default'
package "docker-engine"
execute 'install docker-compose' do
command <<-EOH
curl -L https://github.com/docker/compose/releases/download/1.8.0/docker-compose-`uname -s`-`uname -m` > /usr/local/bin/docker-compose
chmod +x /usr/local/bin/docker-compose
EOH
end
# Ensure the `dbuild` user is part of the `docker` group so they can
# connect to the Docker daemon
execute "usermod -aG docker #{node['delivery_builder']['build_user']}"
| include_recipe 'chef-apt-docker::default'
package "docker-engine"
remote_file '/usr/local/bin/docker-compose' do
source 'https://github.com/docker/compose/releases/download/1.8.0/docker-compose-Linux-x86_64'
checksum 'ebc6ab9ed9c971af7efec074cff7752593559496d0d5f7afb6bfd0e0310961ff'
owner 'root'
group 'docker'
mode '0755'
end
# Ensure the `dbuild` user is part of the `docker` group so they can
# connect to the Docker daemon
execute "usermod -aG docker #{node['delivery_builder']['build_user']}"
| Use remote_file instead of execute-n-curl | Use remote_file instead of execute-n-curl
Check that the docker-compose we download is the one we expect with
a checksum.
Also don't need to uname things because we only use 64-bit Linux
builders for this pipeline.
Signed-off-by: Robb Kidd <11cd4f9ba93acb67080ee4dad8d03929f9e64bf2@chef.io>
| Ruby | apache-2.0 | chef/supermarket,nellshamrell/supermarket,chef/supermarket,juliandunn/supermarket,nellshamrell/supermarket,robbkidd/supermarket,robbkidd/supermarket,chef/supermarket,juliandunn/supermarket,juliandunn/supermarket,chef/supermarket,juliandunn/supermarket,nellshamrell/supermarket,chef/supermarket,robbkidd/supermarket,robbkidd/supermarket,nellshamrell/supermarket | ruby | ## Code Before:
include_recipe 'chef-apt-docker::default'
package "docker-engine"
execute 'install docker-compose' do
command <<-EOH
curl -L https://github.com/docker/compose/releases/download/1.8.0/docker-compose-`uname -s`-`uname -m` > /usr/local/bin/docker-compose
chmod +x /usr/local/bin/docker-compose
EOH
end
# Ensure the `dbuild` user is part of the `docker` group so they can
# connect to the Docker daemon
execute "usermod -aG docker #{node['delivery_builder']['build_user']}"
## Instruction:
Use remote_file instead of execute-n-curl
Check that the docker-compose we download is the one we expect with
a checksum.
Also don't need to uname things because we only use 64-bit Linux
builders for this pipeline.
Signed-off-by: Robb Kidd <11cd4f9ba93acb67080ee4dad8d03929f9e64bf2@chef.io>
## Code After:
include_recipe 'chef-apt-docker::default'
package "docker-engine"
remote_file '/usr/local/bin/docker-compose' do
source 'https://github.com/docker/compose/releases/download/1.8.0/docker-compose-Linux-x86_64'
checksum 'ebc6ab9ed9c971af7efec074cff7752593559496d0d5f7afb6bfd0e0310961ff'
owner 'root'
group 'docker'
mode '0755'
end
# Ensure the `dbuild` user is part of the `docker` group so they can
# connect to the Docker daemon
execute "usermod -aG docker #{node['delivery_builder']['build_user']}"
| include_recipe 'chef-apt-docker::default'
package "docker-engine"
- execute 'install docker-compose' do
- command <<-EOH
- curl -L https://github.com/docker/compose/releases/download/1.8.0/docker-compose-`uname -s`-`uname -m` > /usr/local/bin/docker-compose
- chmod +x /usr/local/bin/docker-compose
? ^^ ^ ^^^
+ remote_file '/usr/local/bin/docker-compose' do
? ^^ ^^^^^^^ ^ ++++
- EOH
+ source 'https://github.com/docker/compose/releases/download/1.8.0/docker-compose-Linux-x86_64'
+ checksum 'ebc6ab9ed9c971af7efec074cff7752593559496d0d5f7afb6bfd0e0310961ff'
+ owner 'root'
+ group 'docker'
+ mode '0755'
end
# Ensure the `dbuild` user is part of the `docker` group so they can
# connect to the Docker daemon
execute "usermod -aG docker #{node['delivery_builder']['build_user']}"
- | 12 | 0.8 | 6 | 6 |
99b668594582882bb1fbca3b3793ff452edac2c1 | updatebot/__init__.py | updatebot/__init__.py |
from updatebot.bot import Bot
from updatebot.current import Bot as CurrentBot
from updatebot.native import Bot as NativeBot
from updatebot.config import UpdateBotConfig
|
from updatebot.bot import Bot
from updatebot.current import Bot as CurrentBot
from updatebot.config import UpdateBotConfig
| Remove import of missing module | Remove import of missing module
| Python | apache-2.0 | sassoftware/mirrorball,sassoftware/mirrorball | python | ## Code Before:
from updatebot.bot import Bot
from updatebot.current import Bot as CurrentBot
from updatebot.native import Bot as NativeBot
from updatebot.config import UpdateBotConfig
## Instruction:
Remove import of missing module
## Code After:
from updatebot.bot import Bot
from updatebot.current import Bot as CurrentBot
from updatebot.config import UpdateBotConfig
|
from updatebot.bot import Bot
from updatebot.current import Bot as CurrentBot
- from updatebot.native import Bot as NativeBot
from updatebot.config import UpdateBotConfig | 1 | 0.2 | 0 | 1 |
b7c9035fd74032466515c17acb63dd98464e8fd8 | phpunit.xml.dist | phpunit.xml.dist | <phpunit colors="true" bootstrap="./vendor/autoload.php" strict="true">
<filter>
<whitelist processUncoveredFilesFromWhitelist="true">
<directory suffix=".php">./src/</directory>
</whitelist>
<blacklist>
<directory suffix=".php">./vendor</directory>
</blacklist>
</filter>
<testsuites>
<testsuite name="Basic library tests">
<directory>./tests/</directory>
</testsuite>
</testsuites>
</phpunit>
| <phpunit colors="true" bootstrap="./vendor/autoload.php" strict="true">
<filter>
<whitelist processUncoveredFilesFromWhitelist="true">
<directory suffix=".php">./src/</directory>
<exclude>
<file>./src/Client.php</file>
</exclude>
</whitelist>
<blacklist>
<directory suffix=".php">./vendor</directory>
</blacklist>
</filter>
<testsuites>
<testsuite name="Basic library tests">
<directory>./tests/</directory>
</testsuite>
</testsuites>
</phpunit>
| Exclude Client.php from testing (tests should be done on the interface) | Exclude Client.php from testing (tests should be done on the interface)
| unknown | mit | unreal4u/mqtt,unreal4u/mqtt | unknown | ## Code Before:
<phpunit colors="true" bootstrap="./vendor/autoload.php" strict="true">
<filter>
<whitelist processUncoveredFilesFromWhitelist="true">
<directory suffix=".php">./src/</directory>
</whitelist>
<blacklist>
<directory suffix=".php">./vendor</directory>
</blacklist>
</filter>
<testsuites>
<testsuite name="Basic library tests">
<directory>./tests/</directory>
</testsuite>
</testsuites>
</phpunit>
## Instruction:
Exclude Client.php from testing (tests should be done on the interface)
## Code After:
<phpunit colors="true" bootstrap="./vendor/autoload.php" strict="true">
<filter>
<whitelist processUncoveredFilesFromWhitelist="true">
<directory suffix=".php">./src/</directory>
<exclude>
<file>./src/Client.php</file>
</exclude>
</whitelist>
<blacklist>
<directory suffix=".php">./vendor</directory>
</blacklist>
</filter>
<testsuites>
<testsuite name="Basic library tests">
<directory>./tests/</directory>
</testsuite>
</testsuites>
</phpunit>
| <phpunit colors="true" bootstrap="./vendor/autoload.php" strict="true">
<filter>
<whitelist processUncoveredFilesFromWhitelist="true">
<directory suffix=".php">./src/</directory>
+ <exclude>
+ <file>./src/Client.php</file>
+ </exclude>
</whitelist>
<blacklist>
<directory suffix=".php">./vendor</directory>
</blacklist>
</filter>
<testsuites>
<testsuite name="Basic library tests">
<directory>./tests/</directory>
</testsuite>
</testsuites>
</phpunit> | 3 | 0.2 | 3 | 0 |
cde874959c2930b353207f2c233daafeb268a928 | cookbooks/sys_dns/recipes/do_set_private.rb | cookbooks/sys_dns/recipes/do_set_private.rb |
sys_dns "default" do
id node['sys_dns']['id']
address node['cloud']['private_ips'][0]
action :set_private
end |
require 'socket'
def local_ip
orig, Socket.do_not_reverse_lookup = Socket.do_not_reverse_lookup, true # turn off reverse DNS resolution temporarily
UDPSocket.open do |s|
s.connect '64.233.187.99', 1
s.addr.last
end
ensure
Socket.do_not_reverse_lookup = orig
end
if ! node.has_key?('cloud')
private_ip = "#{local_ip}"
else
public_ip = node['cloud']['public_ips'][0]
end
log "Detected private IP: #{private_ip}"
sys_dns "default" do
id node['sys_dns']['id']
address private_ip
action :set_private
end
execute "set_private_ip_tag" do
command "rs_tag --add 'node:private_ip=#{private_ip}'"
only_if "which rs_tag"
end | Add private_ip detection for non-clouds. | Add private_ip detection for non-clouds.
| Ruby | mit | Promoboxx/cookbooks_public,Promoboxx/cookbooks_public,Promoboxx/cookbooks_public | ruby | ## Code Before:
sys_dns "default" do
id node['sys_dns']['id']
address node['cloud']['private_ips'][0]
action :set_private
end
## Instruction:
Add private_ip detection for non-clouds.
## Code After:
require 'socket'
def local_ip
orig, Socket.do_not_reverse_lookup = Socket.do_not_reverse_lookup, true # turn off reverse DNS resolution temporarily
UDPSocket.open do |s|
s.connect '64.233.187.99', 1
s.addr.last
end
ensure
Socket.do_not_reverse_lookup = orig
end
if ! node.has_key?('cloud')
private_ip = "#{local_ip}"
else
public_ip = node['cloud']['public_ips'][0]
end
log "Detected private IP: #{private_ip}"
sys_dns "default" do
id node['sys_dns']['id']
address private_ip
action :set_private
end
execute "set_private_ip_tag" do
command "rs_tag --add 'node:private_ip=#{private_ip}'"
only_if "which rs_tag"
end | +
+ require 'socket'
+
+ def local_ip
+ orig, Socket.do_not_reverse_lookup = Socket.do_not_reverse_lookup, true # turn off reverse DNS resolution temporarily
+ UDPSocket.open do |s|
+ s.connect '64.233.187.99', 1
+ s.addr.last
+ end
+ ensure
+ Socket.do_not_reverse_lookup = orig
+ end
+
+ if ! node.has_key?('cloud')
+ private_ip = "#{local_ip}"
+ else
+ public_ip = node['cloud']['public_ips'][0]
+ end
+
+ log "Detected private IP: #{private_ip}"
sys_dns "default" do
id node['sys_dns']['id']
- address node['cloud']['private_ips'][0]
+ address private_ip
action :set_private
end
+
+ execute "set_private_ip_tag" do
+ command "rs_tag --add 'node:private_ip=#{private_ip}'"
+ only_if "which rs_tag"
+ end | 27 | 4.5 | 26 | 1 |
b4b210373a9cdc0df5bdb7cf577320c328520f72 | src/test/kotlin/com/brunodles/ipgetter/IpGetterTest.kt | src/test/kotlin/com/brunodles/ipgetter/IpGetterTest.kt | package com.brunodles.ipgetter
import com.brunodles.oleaster.suiterunner.OleasterSuiteRunner
import com.brunodles.test.helper.context
import com.brunodles.test.helper.given
import com.brunodles.test.helper.xgiven
import com.mscharhag.oleaster.runner.StaticRunnerSupport.beforeEach
import com.mscharhag.oleaster.runner.StaticRunnerSupport.it
import org.assertj.core.api.Assertions.assertThat
import org.gradle.api.Project
import org.gradle.api.Task
import org.gradle.testfixtures.ProjectBuilder
import org.junit.runner.RunWith
@RunWith(OleasterSuiteRunner::class)
class IpGetterTest {
var project: Project? = null
init {
given(Project::class) {
beforeEach { project = ProjectBuilder.builder().build() }
context("apply ${IpGetter::class.java.simpleName} plugin") {
beforeEach { project!!.pluginManager.apply("ipgetter") }
it("should add an extension function to get the IP") {
assertThat(project!!.extensions.getByName("localIpOr")).isInstanceOf(String::class.java)
}
it("should add a task to print properties") {
assertThat(project!!.task("printIpProps")).isInstanceOf(Task::class.java)
}
}
}
}
} | package com.brunodles.ipgetter
import com.brunodles.oleaster.suiterunner.OleasterSuiteRunner
import com.brunodles.test.helper.context
import com.brunodles.test.helper.given
import com.mscharhag.oleaster.runner.StaticRunnerSupport.beforeEach
import com.mscharhag.oleaster.runner.StaticRunnerSupport.it
import groovy.lang.Closure
import org.assertj.core.api.Assertions.assertThat
import org.gradle.api.Project
import org.gradle.api.Task
import org.gradle.testfixtures.ProjectBuilder
import org.junit.runner.RunWith
@RunWith(OleasterSuiteRunner::class)
class IpGetterTest {
var project: Project? = null
init {
given(Project::class) {
beforeEach { project = ProjectBuilder.builder().build() }
context("apply ${IpGetter::class.java.simpleName} plugin") {
beforeEach { project!!.pluginManager.apply(IpGetter::class.java) }
it("should add an extension function to get the IP") {
assertThat(project!!.extensions.getByName("localIpOr")).isInstanceOf(Closure::class.java)
}
it("should add a task to print properties") {
assertThat(project!!.tasks.getByName("printIpProps")).isInstanceOf(Task::class.java)
}
}
}
}
} | Update IpGettertest to fix the test | Update IpGettertest to fix the test
| Kotlin | mit | brunodles/IpGetter | kotlin | ## Code Before:
package com.brunodles.ipgetter
import com.brunodles.oleaster.suiterunner.OleasterSuiteRunner
import com.brunodles.test.helper.context
import com.brunodles.test.helper.given
import com.brunodles.test.helper.xgiven
import com.mscharhag.oleaster.runner.StaticRunnerSupport.beforeEach
import com.mscharhag.oleaster.runner.StaticRunnerSupport.it
import org.assertj.core.api.Assertions.assertThat
import org.gradle.api.Project
import org.gradle.api.Task
import org.gradle.testfixtures.ProjectBuilder
import org.junit.runner.RunWith
@RunWith(OleasterSuiteRunner::class)
class IpGetterTest {
var project: Project? = null
init {
given(Project::class) {
beforeEach { project = ProjectBuilder.builder().build() }
context("apply ${IpGetter::class.java.simpleName} plugin") {
beforeEach { project!!.pluginManager.apply("ipgetter") }
it("should add an extension function to get the IP") {
assertThat(project!!.extensions.getByName("localIpOr")).isInstanceOf(String::class.java)
}
it("should add a task to print properties") {
assertThat(project!!.task("printIpProps")).isInstanceOf(Task::class.java)
}
}
}
}
}
## Instruction:
Update IpGettertest to fix the test
## Code After:
package com.brunodles.ipgetter
import com.brunodles.oleaster.suiterunner.OleasterSuiteRunner
import com.brunodles.test.helper.context
import com.brunodles.test.helper.given
import com.mscharhag.oleaster.runner.StaticRunnerSupport.beforeEach
import com.mscharhag.oleaster.runner.StaticRunnerSupport.it
import groovy.lang.Closure
import org.assertj.core.api.Assertions.assertThat
import org.gradle.api.Project
import org.gradle.api.Task
import org.gradle.testfixtures.ProjectBuilder
import org.junit.runner.RunWith
@RunWith(OleasterSuiteRunner::class)
class IpGetterTest {
var project: Project? = null
init {
given(Project::class) {
beforeEach { project = ProjectBuilder.builder().build() }
context("apply ${IpGetter::class.java.simpleName} plugin") {
beforeEach { project!!.pluginManager.apply(IpGetter::class.java) }
it("should add an extension function to get the IP") {
assertThat(project!!.extensions.getByName("localIpOr")).isInstanceOf(Closure::class.java)
}
it("should add a task to print properties") {
assertThat(project!!.tasks.getByName("printIpProps")).isInstanceOf(Task::class.java)
}
}
}
}
} | package com.brunodles.ipgetter
import com.brunodles.oleaster.suiterunner.OleasterSuiteRunner
import com.brunodles.test.helper.context
import com.brunodles.test.helper.given
- import com.brunodles.test.helper.xgiven
import com.mscharhag.oleaster.runner.StaticRunnerSupport.beforeEach
import com.mscharhag.oleaster.runner.StaticRunnerSupport.it
+ import groovy.lang.Closure
import org.assertj.core.api.Assertions.assertThat
import org.gradle.api.Project
import org.gradle.api.Task
import org.gradle.testfixtures.ProjectBuilder
import org.junit.runner.RunWith
@RunWith(OleasterSuiteRunner::class)
class IpGetterTest {
var project: Project? = null
init {
given(Project::class) {
beforeEach { project = ProjectBuilder.builder().build() }
+
context("apply ${IpGetter::class.java.simpleName} plugin") {
- beforeEach { project!!.pluginManager.apply("ipgetter") }
? ^^ ^ ^
+ beforeEach { project!!.pluginManager.apply(IpGetter::class.java) }
? ^ ^ ^^^^^^^^^^^^
+
it("should add an extension function to get the IP") {
- assertThat(project!!.extensions.getByName("localIpOr")).isInstanceOf(String::class.java)
? ^^ ^^^
+ assertThat(project!!.extensions.getByName("localIpOr")).isInstanceOf(Closure::class.java)
? ^^^^^ ^
}
it("should add a task to print properties") {
- assertThat(project!!.task("printIpProps")).isInstanceOf(Task::class.java)
+ assertThat(project!!.tasks.getByName("printIpProps")).isInstanceOf(Task::class.java)
? +++++++++++
}
}
}
}
} | 10 | 0.30303 | 6 | 4 |
7b49ba24e5b660029a83f3cc4742a876c9a83a59 | lib/stradivari/generator.rb | lib/stradivari/generator.rb | module Stradivari
class Generator
class Tag
delegate :view, :klass, to: :@parent
delegate :t, :capture_haml, :haml_tag, :haml_concat, to: :view
attr_reader :opts
def initialize(parent, opts)
@parent, @opts = parent, opts
end
def enabled?
enabled = true
if i = @opts.fetch(:if, nil)
enabled &= view.instance_exec(&i)
elsif u = @opts.fetch(:unless, nil)
enabled &= !view.instance_exec(&u)
end
enabled
end
def title
case t = opts[:title]
when nil
klass.human_attribute_name(name)
when Proc
view.instance_eval(&t)
when false
""
else
t
end
end
protected
def force_presence(value)
if @opts.fetch(:present, nil)
value.presence || t(:empty).html_safe
else
value
end
end
def type
klass.stradivari_type(name)
end
end
def initialize(view, data, *pass)
# ActionView
@view = view
# Opaque, generator-specific data
@data = data
# Generator options
@opts = pass.extract_options!
end
attr_reader :view, :data, :opts
delegate :params, :t, :capture_haml, :haml_tag, to: :@view
def to_s
raise NotImplementedError
end
def klass
raise NotImplementedError
end
end
end
| module Stradivari
class Generator
class Tag
delegate :view, :klass, to: :@parent
delegate :t, :capture_haml, :haml_tag, :haml_concat, to: :view
attr_reader :opts
def initialize(parent, opts)
@parent, @opts = parent, opts
end
def enabled?
enabled = true
if i = @opts.fetch(:if, nil)
enabled &= view.instance_exec(&i)
elsif u = @opts.fetch(:unless, nil)
enabled &= !view.instance_exec(&u)
end
enabled
end
def title
case t = opts[:title]
when nil
human_attribute_name
when Proc
view.instance_eval(&t)
when false
""
else
t
end
end
protected
def human_attribute_name
if klass.respond_to?(:human_attribute_name)
klass.human_attribute_name(name)
else
name.titleize
end
end
def force_presence(value)
if @opts.fetch(:present, nil)
value.presence || t(:empty).html_safe
else
value
end
end
def type
klass.stradivari_type(name)
end
end
def initialize(view, data, *pass)
# ActionView
@view = view
# Opaque, generator-specific data
@data = data
# Generator options
@opts = pass.extract_options!
end
attr_reader :view, :data, :opts
delegate :params, :t, :capture_haml, :haml_tag, to: :@view
def to_s
raise NotImplementedError
end
def klass
raise NotImplementedError
end
end
end
| Use human_attribute_name only if available on the model | Use human_attribute_name only if available on the model
| Ruby | mit | ifad/stradivari,ifad/stradivari | ruby | ## Code Before:
module Stradivari
class Generator
class Tag
delegate :view, :klass, to: :@parent
delegate :t, :capture_haml, :haml_tag, :haml_concat, to: :view
attr_reader :opts
def initialize(parent, opts)
@parent, @opts = parent, opts
end
def enabled?
enabled = true
if i = @opts.fetch(:if, nil)
enabled &= view.instance_exec(&i)
elsif u = @opts.fetch(:unless, nil)
enabled &= !view.instance_exec(&u)
end
enabled
end
def title
case t = opts[:title]
when nil
klass.human_attribute_name(name)
when Proc
view.instance_eval(&t)
when false
""
else
t
end
end
protected
def force_presence(value)
if @opts.fetch(:present, nil)
value.presence || t(:empty).html_safe
else
value
end
end
def type
klass.stradivari_type(name)
end
end
def initialize(view, data, *pass)
# ActionView
@view = view
# Opaque, generator-specific data
@data = data
# Generator options
@opts = pass.extract_options!
end
attr_reader :view, :data, :opts
delegate :params, :t, :capture_haml, :haml_tag, to: :@view
def to_s
raise NotImplementedError
end
def klass
raise NotImplementedError
end
end
end
## Instruction:
Use human_attribute_name only if available on the model
## Code After:
module Stradivari
class Generator
class Tag
delegate :view, :klass, to: :@parent
delegate :t, :capture_haml, :haml_tag, :haml_concat, to: :view
attr_reader :opts
def initialize(parent, opts)
@parent, @opts = parent, opts
end
def enabled?
enabled = true
if i = @opts.fetch(:if, nil)
enabled &= view.instance_exec(&i)
elsif u = @opts.fetch(:unless, nil)
enabled &= !view.instance_exec(&u)
end
enabled
end
def title
case t = opts[:title]
when nil
human_attribute_name
when Proc
view.instance_eval(&t)
when false
""
else
t
end
end
protected
def human_attribute_name
if klass.respond_to?(:human_attribute_name)
klass.human_attribute_name(name)
else
name.titleize
end
end
def force_presence(value)
if @opts.fetch(:present, nil)
value.presence || t(:empty).html_safe
else
value
end
end
def type
klass.stradivari_type(name)
end
end
def initialize(view, data, *pass)
# ActionView
@view = view
# Opaque, generator-specific data
@data = data
# Generator options
@opts = pass.extract_options!
end
attr_reader :view, :data, :opts
delegate :params, :t, :capture_haml, :haml_tag, to: :@view
def to_s
raise NotImplementedError
end
def klass
raise NotImplementedError
end
end
end
| module Stradivari
class Generator
class Tag
delegate :view, :klass, to: :@parent
delegate :t, :capture_haml, :haml_tag, :haml_concat, to: :view
attr_reader :opts
def initialize(parent, opts)
@parent, @opts = parent, opts
end
def enabled?
enabled = true
if i = @opts.fetch(:if, nil)
enabled &= view.instance_exec(&i)
elsif u = @opts.fetch(:unless, nil)
enabled &= !view.instance_exec(&u)
end
enabled
end
def title
case t = opts[:title]
when nil
- klass.human_attribute_name(name)
? ------ ------
+ human_attribute_name
when Proc
view.instance_eval(&t)
when false
""
else
t
end
end
protected
+ def human_attribute_name
+ if klass.respond_to?(:human_attribute_name)
+ klass.human_attribute_name(name)
+ else
+ name.titleize
+ end
+ end
+
def force_presence(value)
if @opts.fetch(:present, nil)
value.presence || t(:empty).html_safe
else
value
end
end
def type
klass.stradivari_type(name)
end
end
def initialize(view, data, *pass)
# ActionView
@view = view
# Opaque, generator-specific data
@data = data
# Generator options
@opts = pass.extract_options!
end
attr_reader :view, :data, :opts
delegate :params, :t, :capture_haml, :haml_tag, to: :@view
def to_s
raise NotImplementedError
end
def klass
raise NotImplementedError
end
end
end | 10 | 0.128205 | 9 | 1 |
3dbef948f4839b965eb0c7af95bf4711eb5bedfa | Modules/Core/TestKernel/src/CMakeLists.txt | Modules/Core/TestKernel/src/CMakeLists.txt | add_executable(itkTestDriver itkTestDriver.cxx)
target_link_libraries(itkTestDriver ${ITK-TestKernel_LIBRARIES})
install(TARGETS itkTestDriver DESTINATION bin)
| add_executable(itkTestDriver itkTestDriver.cxx)
target_link_libraries(itkTestDriver ${ITK-TestKernel_LIBRARIES})
itk_module_target_install(itkTestDriver)
| Use macro for consistent library install | STYLE: Use macro for consistent library install
Change-Id: I1babb893aec9dbc1dadf1644222b280baced03b7
| Text | apache-2.0 | daviddoria/itkHoughTransform,rhgong/itk-with-dom,hinerm/ITK,BRAINSia/ITK,LucHermitte/ITK,msmolens/ITK,rhgong/itk-with-dom,daviddoria/itkHoughTransform,hinerm/ITK,fedral/ITK,fuentesdt/InsightToolkit-dev,fedral/ITK,thewtex/ITK,atsnyder/ITK,hinerm/ITK,heimdali/ITK,fedral/ITK,jmerkow/ITK,stnava/ITK,atsnyder/ITK,itkvideo/ITK,biotrump/ITK,blowekamp/ITK,itkvideo/ITK,paulnovo/ITK,CapeDrew/DCMTK-ITK,malaterre/ITK,biotrump/ITK,GEHC-Surgery/ITK,wkjeong/ITK,heimdali/ITK,malaterre/ITK,LucasGandel/ITK,msmolens/ITK,InsightSoftwareConsortium/ITK,daviddoria/itkHoughTransform,InsightSoftwareConsortium/ITK,PlutoniumHeart/ITK,daviddoria/itkHoughTransform,cpatrick/ITK-RemoteIO,wkjeong/ITK,msmolens/ITK,jmerkow/ITK,msmolens/ITK,Kitware/ITK,fedral/ITK,fuentesdt/InsightToolkit-dev,fbudin69500/ITK,rhgong/itk-with-dom,zachary-williamson/ITK,spinicist/ITK,fbudin69500/ITK,jmerkow/ITK,hendradarwin/ITK,LucHermitte/ITK,GEHC-Surgery/ITK,ajjl/ITK,eile/ITK,malaterre/ITK,itkvideo/ITK,stnava/ITK,rhgong/itk-with-dom,itkvideo/ITK,atsnyder/ITK,BRAINSia/ITK,BRAINSia/ITK,CapeDrew/DITK,jcfr/ITK,BlueBrain/ITK,stnava/ITK,PlutoniumHeart/ITK,PlutoniumHeart/ITK,CapeDrew/DCMTK-ITK,eile/ITK,blowekamp/ITK,itkvideo/ITK,LucasGandel/ITK,BlueBrain/ITK,daviddoria/itkHoughTransform,stnava/ITK,LucHermitte/ITK,CapeDrew/DCMTK-ITK,ajjl/ITK,malaterre/ITK,LucasGandel/ITK,LucHermitte/ITK,wkjeong/ITK,richardbeare/ITK,hendradarwin/ITK,hjmjohnson/ITK,hinerm/ITK,BlueBrain/ITK,richardbeare/ITK,zachary-williamson/ITK,zachary-williamson/ITK,hjmjohnson/ITK,cpatrick/ITK-RemoteIO,CapeDrew/DITK,spinicist/ITK,GEHC-Surgery/ITK,richardbeare/ITK,PlutoniumHeart/ITK,jcfr/ITK,spinicist/ITK,BlueBrain/ITK,biotrump/ITK,wkjeong/ITK,vfonov/ITK,blowekamp/ITK,cpatrick/ITK-RemoteIO,ajjl/ITK,stnava/ITK,jmerkow/ITK,InsightSoftwareConsortium/ITK,cpatrick/ITK-RemoteIO,jmerkow/ITK,Kitware/ITK,richardbeare/ITK,stnava/ITK,cpatrick/ITK-RemoteIO,Kitware/ITK,PlutoniumHeart/ITK,malaterre/ITK,hjmjohnson/ITK,atsnyder/ITK,fuentesdt/InsightToolkit-dev,eile/ITK,GEHC-Surgery/ITK,malaterre/ITK,fbudin69500/ITK,eile/ITK,thewtex/ITK,LucasGandel/ITK,blowekamp/ITK,BlueBrain/ITK,eile/ITK,InsightSoftwareConsortium/ITK,paulnovo/ITK,CapeDrew/DITK,thewtex/ITK,eile/ITK,LucasGandel/ITK,blowekamp/ITK,CapeDrew/DCMTK-ITK,hendradarwin/ITK,atsnyder/ITK,malaterre/ITK,ajjl/ITK,paulnovo/ITK,vfonov/ITK,spinicist/ITK,vfonov/ITK,stnava/ITK,vfonov/ITK,cpatrick/ITK-RemoteIO,hjmjohnson/ITK,blowekamp/ITK,fedral/ITK,fuentesdt/InsightToolkit-dev,fbudin69500/ITK,jmerkow/ITK,jcfr/ITK,vfonov/ITK,fbudin69500/ITK,jcfr/ITK,GEHC-Surgery/ITK,vfonov/ITK,msmolens/ITK,malaterre/ITK,daviddoria/itkHoughTransform,cpatrick/ITK-RemoteIO,zachary-williamson/ITK,ajjl/ITK,heimdali/ITK,wkjeong/ITK,BRAINSia/ITK,CapeDrew/DITK,richardbeare/ITK,malaterre/ITK,zachary-williamson/ITK,paulnovo/ITK,PlutoniumHeart/ITK,thewtex/ITK,GEHC-Surgery/ITK,fbudin69500/ITK,richardbeare/ITK,PlutoniumHeart/ITK,jmerkow/ITK,hinerm/ITK,hjmjohnson/ITK,CapeDrew/DCMTK-ITK,vfonov/ITK,CapeDrew/DCMTK-ITK,rhgong/itk-with-dom,blowekamp/ITK,cpatrick/ITK-RemoteIO,CapeDrew/DITK,hendradarwin/ITK,atsnyder/ITK,BRAINSia/ITK,jcfr/ITK,Kitware/ITK,thewtex/ITK,jmerkow/ITK,zachary-williamson/ITK,hinerm/ITK,eile/ITK,CapeDrew/DITK,CapeDrew/DCMTK-ITK,fedral/ITK,Kitware/ITK,itkvideo/ITK,biotrump/ITK,BRAINSia/ITK,LucasGandel/ITK,daviddoria/itkHoughTransform,hendradarwin/ITK,hjmjohnson/ITK,atsnyder/ITK,biotrump/ITK,LucasGandel/ITK,fuentesdt/InsightToolkit-dev,richardbeare/ITK,vfonov/ITK,heimdali/ITK,hendradarwin/ITK,BlueBrain/ITK,InsightSoftwareConsortium/ITK,PlutoniumHeart/ITK,InsightSoftwareConsortium/ITK,stnava/ITK,fedral/ITK,fuentesdt/InsightToolkit-dev,biotrump/ITK,BlueBrain/ITK,vfonov/ITK,msmolens/ITK,BlueBrain/ITK,spinicist/ITK,jcfr/ITK,jcfr/ITK,stnava/ITK,paulnovo/ITK,fedral/ITK,jcfr/ITK,fbudin69500/ITK,spinicist/ITK,GEHC-Surgery/ITK,atsnyder/ITK,heimdali/ITK,hendradarwin/ITK,InsightSoftwareConsortium/ITK,hinerm/ITK,paulnovo/ITK,daviddoria/itkHoughTransform,LucHermitte/ITK,spinicist/ITK,hinerm/ITK,thewtex/ITK,ajjl/ITK,spinicist/ITK,fuentesdt/InsightToolkit-dev,paulnovo/ITK,CapeDrew/DCMTK-ITK,daviddoria/itkHoughTransform,fuentesdt/InsightToolkit-dev,rhgong/itk-with-dom,atsnyder/ITK,hendradarwin/ITK,hjmjohnson/ITK,Kitware/ITK,CapeDrew/DITK,eile/ITK,wkjeong/ITK,ajjl/ITK,LucasGandel/ITK,spinicist/ITK,biotrump/ITK,itkvideo/ITK,fuentesdt/InsightToolkit-dev,BRAINSia/ITK,rhgong/itk-with-dom,eile/ITK,rhgong/itk-with-dom,biotrump/ITK,zachary-williamson/ITK,thewtex/ITK,heimdali/ITK,msmolens/ITK,heimdali/ITK,wkjeong/ITK,Kitware/ITK,ajjl/ITK,LucHermitte/ITK,hinerm/ITK,wkjeong/ITK,LucHermitte/ITK,zachary-williamson/ITK,zachary-williamson/ITK,GEHC-Surgery/ITK,itkvideo/ITK,LucHermitte/ITK,CapeDrew/DITK,heimdali/ITK,fbudin69500/ITK,CapeDrew/DCMTK-ITK,blowekamp/ITK,CapeDrew/DITK,itkvideo/ITK,msmolens/ITK,paulnovo/ITK | text | ## Code Before:
add_executable(itkTestDriver itkTestDriver.cxx)
target_link_libraries(itkTestDriver ${ITK-TestKernel_LIBRARIES})
install(TARGETS itkTestDriver DESTINATION bin)
## Instruction:
STYLE: Use macro for consistent library install
Change-Id: I1babb893aec9dbc1dadf1644222b280baced03b7
## Code After:
add_executable(itkTestDriver itkTestDriver.cxx)
target_link_libraries(itkTestDriver ${ITK-TestKernel_LIBRARIES})
itk_module_target_install(itkTestDriver)
| add_executable(itkTestDriver itkTestDriver.cxx)
target_link_libraries(itkTestDriver ${ITK-TestKernel_LIBRARIES})
- install(TARGETS itkTestDriver DESTINATION bin)
+ itk_module_target_install(itkTestDriver) | 2 | 0.666667 | 1 | 1 |
ffe9298c700805be3fa7fdbc3ad11ebf4fab5892 | cloudant-sync-datastore-core/src/main/java/com/cloudant/sync/query/FieldSort.java | cloudant-sync-datastore-core/src/main/java/com/cloudant/sync/query/FieldSort.java | package com.cloudant.sync.query;
/**
* Created by tomblench on 28/09/2016.
*/
public class FieldSort {
public final String field;
public final Direction sort;
public FieldSort(String field) {
this.field = field;
this.sort = Direction.ASCENDING;
}
public FieldSort(String field, Direction sort) {
this.field = field;
this.sort = sort;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
FieldSort fieldSort = (FieldSort) o;
if (!field.equals(fieldSort.field)) {
return false;
}
return sort == fieldSort.sort;
}
@Override
public int hashCode() {
int result = field.hashCode();
result = 31 * result + sort.hashCode();
return result;
}
@Override
public String toString() {
return "FieldSort{" +
"field='" + field + '\'' +
", sort=" + sort +
'}';
}
public enum Direction {
ASCENDING,
DESCENDING
};
}
| /*
* Copyright (C) 2016 IBM Corp. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the
* License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.cloudant.sync.query;
/**
* Created by tomblench on 28/09/2016.
*/
public class FieldSort {
public final String field;
public final Direction sort;
public FieldSort(String field) {
this(field, Direction.ASCENDING);
}
public FieldSort(String field, Direction sort) {
this.field = field;
this.sort = sort;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
FieldSort fieldSort = (FieldSort) o;
if (!field.equals(fieldSort.field)) {
return false;
}
return sort == fieldSort.sort;
}
@Override
public int hashCode() {
int result = field.hashCode();
result = 31 * result + sort.hashCode();
return result;
}
@Override
public String toString() {
return "FieldSort{" +
"field='" + field + '\'' +
", sort=" + sort +
'}';
}
public enum Direction {
ASCENDING,
DESCENDING
};
}
| Implement feedback from rhys' comments | Implement feedback from rhys' comments
| Java | apache-2.0 | cloudant/sync-android,cloudant/sync-android | java | ## Code Before:
package com.cloudant.sync.query;
/**
* Created by tomblench on 28/09/2016.
*/
public class FieldSort {
public final String field;
public final Direction sort;
public FieldSort(String field) {
this.field = field;
this.sort = Direction.ASCENDING;
}
public FieldSort(String field, Direction sort) {
this.field = field;
this.sort = sort;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
FieldSort fieldSort = (FieldSort) o;
if (!field.equals(fieldSort.field)) {
return false;
}
return sort == fieldSort.sort;
}
@Override
public int hashCode() {
int result = field.hashCode();
result = 31 * result + sort.hashCode();
return result;
}
@Override
public String toString() {
return "FieldSort{" +
"field='" + field + '\'' +
", sort=" + sort +
'}';
}
public enum Direction {
ASCENDING,
DESCENDING
};
}
## Instruction:
Implement feedback from rhys' comments
## Code After:
/*
* Copyright (C) 2016 IBM Corp. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the
* License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.cloudant.sync.query;
/**
* Created by tomblench on 28/09/2016.
*/
public class FieldSort {
public final String field;
public final Direction sort;
public FieldSort(String field) {
this(field, Direction.ASCENDING);
}
public FieldSort(String field, Direction sort) {
this.field = field;
this.sort = sort;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
FieldSort fieldSort = (FieldSort) o;
if (!field.equals(fieldSort.field)) {
return false;
}
return sort == fieldSort.sort;
}
@Override
public int hashCode() {
int result = field.hashCode();
result = 31 * result + sort.hashCode();
return result;
}
@Override
public String toString() {
return "FieldSort{" +
"field='" + field + '\'' +
", sort=" + sort +
'}';
}
public enum Direction {
ASCENDING,
DESCENDING
};
}
| + /*
+ * Copyright (C) 2016 IBM Corp. All rights reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
+ * except in compliance with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the
+ * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
+ * either express or implied. See the License for the specific language governing permissions
+ * and limitations under the License.
+ */
+
package com.cloudant.sync.query;
/**
* Created by tomblench on 28/09/2016.
*/
public class FieldSort {
public final String field;
public final Direction sort;
public FieldSort(String field) {
- this.field = field;
- this.sort = Direction.ASCENDING;
? ^^^^^^^
+ this(field, Direction.ASCENDING);
? ^^^^^^^ +
}
public FieldSort(String field, Direction sort) {
this.field = field;
this.sort = sort;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
FieldSort fieldSort = (FieldSort) o;
if (!field.equals(fieldSort.field)) {
return false;
}
return sort == fieldSort.sort;
}
@Override
public int hashCode() {
int result = field.hashCode();
result = 31 * result + sort.hashCode();
return result;
}
@Override
public String toString() {
return "FieldSort{" +
"field='" + field + '\'' +
", sort=" + sort +
'}';
}
public enum Direction {
ASCENDING,
DESCENDING
};
} | 17 | 0.283333 | 15 | 2 |
d5d38f31fcb5d6df9a003d767c0cefde3bb76f88 | foldl-benchmark/Main.hs | foldl-benchmark/Main.hs | module Main where
import Prelude
import Criterion
import Criterion.Main
import qualified Control.Foldl as A
import qualified Data.Vector as F
import qualified VectorBuilder.Builder as N
import qualified VectorBuilder.Vector as O
main =
defaultMain [group 100, group 10000, group 1000000]
where
group size =
bgroup (show size)
[
bench "vector-builder" (nf foldWithBuilder input),
bench "default" (nf foldDefault input)
]
where
input =
[0..size]
foldWithBuilder input =
A.fold (A.foldMap N.singleton O.build) input :: Vector Int
foldDefault input =
runST (A.foldM A.vector input) :: Vector Int
| module Main where
import Prelude
import Criterion
import Criterion.Main
import qualified Control.Foldl as A
import qualified Data.Vector as F
import qualified VectorBuilder.Builder as N
import qualified VectorBuilder.Vector as O
main =
defaultMain [group 1000, group 10000, group 100000, group 1000000, group 10000000]
where
group size =
bgroup (show size)
[
bench "vector-builder" (nf foldWithBuilder input),
bench "default" (nf foldDefault input)
]
where
input =
[0..size]
foldWithBuilder input =
A.fold (A.foldMap N.singleton O.build) input :: Vector Int
foldDefault input =
runST (A.foldM A.vector input) :: Vector Int
| Cover more sizes in the benchmarks | Cover more sizes in the benchmarks
| Haskell | mit | nikita-volkov/vector-builder | haskell | ## Code Before:
module Main where
import Prelude
import Criterion
import Criterion.Main
import qualified Control.Foldl as A
import qualified Data.Vector as F
import qualified VectorBuilder.Builder as N
import qualified VectorBuilder.Vector as O
main =
defaultMain [group 100, group 10000, group 1000000]
where
group size =
bgroup (show size)
[
bench "vector-builder" (nf foldWithBuilder input),
bench "default" (nf foldDefault input)
]
where
input =
[0..size]
foldWithBuilder input =
A.fold (A.foldMap N.singleton O.build) input :: Vector Int
foldDefault input =
runST (A.foldM A.vector input) :: Vector Int
## Instruction:
Cover more sizes in the benchmarks
## Code After:
module Main where
import Prelude
import Criterion
import Criterion.Main
import qualified Control.Foldl as A
import qualified Data.Vector as F
import qualified VectorBuilder.Builder as N
import qualified VectorBuilder.Vector as O
main =
defaultMain [group 1000, group 10000, group 100000, group 1000000, group 10000000]
where
group size =
bgroup (show size)
[
bench "vector-builder" (nf foldWithBuilder input),
bench "default" (nf foldDefault input)
]
where
input =
[0..size]
foldWithBuilder input =
A.fold (A.foldMap N.singleton O.build) input :: Vector Int
foldDefault input =
runST (A.foldM A.vector input) :: Vector Int
| module Main where
import Prelude
import Criterion
import Criterion.Main
import qualified Control.Foldl as A
import qualified Data.Vector as F
import qualified VectorBuilder.Builder as N
import qualified VectorBuilder.Vector as O
main =
- defaultMain [group 100, group 10000, group 1000000]
+ defaultMain [group 1000, group 10000, group 100000, group 1000000, group 10000000]
? + ++++++++++++++++++++++++++++++
where
group size =
bgroup (show size)
[
bench "vector-builder" (nf foldWithBuilder input),
bench "default" (nf foldDefault input)
]
where
input =
[0..size]
foldWithBuilder input =
A.fold (A.foldMap N.singleton O.build) input :: Vector Int
foldDefault input =
runST (A.foldM A.vector input) :: Vector Int | 2 | 0.074074 | 1 | 1 |
f7192200d8624334627209132e4b43c21f9bec43 | index.js | index.js | var SEP = ':';
var crypto = require('crypto');
function genLongTermKey( username, realm, password ) {
var md5 = crypto.createHash( 'md5' );
var text = username + SEP + realm + SEP + password;
md5.update( text );
var hash = md5.digest( 'hex' );
return hash;
return;
}
module.exports = {
genLongTermKey : genLongTermKey,
}
| var SEP = ':';
var crypto = require('crypto');
function genLongTermKey( username, realm, password ) {
var md5 = crypto.createHash( 'md5' );
var text = username + SEP + realm + SEP + password;
md5.update( text );
var hash = md5.digest( 'hex' );
return hash;
}
function genSharedKey( username, shared_key ) {
var hmac = crypto.createHmac( 'sha1', shared_key );
hmac.update( username );
var hash = hmac.digest( 'base64' );
return hash;
}
module.exports = {
genLongTermKey : genLongTermKey,
genSharedKey : genSharedKey,
}
| Implement password generation for TURN REST API | Implement password generation for TURN REST API
| JavaScript | mit | pmarques/node-turnrestapi | javascript | ## Code Before:
var SEP = ':';
var crypto = require('crypto');
function genLongTermKey( username, realm, password ) {
var md5 = crypto.createHash( 'md5' );
var text = username + SEP + realm + SEP + password;
md5.update( text );
var hash = md5.digest( 'hex' );
return hash;
return;
}
module.exports = {
genLongTermKey : genLongTermKey,
}
## Instruction:
Implement password generation for TURN REST API
## Code After:
var SEP = ':';
var crypto = require('crypto');
function genLongTermKey( username, realm, password ) {
var md5 = crypto.createHash( 'md5' );
var text = username + SEP + realm + SEP + password;
md5.update( text );
var hash = md5.digest( 'hex' );
return hash;
}
function genSharedKey( username, shared_key ) {
var hmac = crypto.createHmac( 'sha1', shared_key );
hmac.update( username );
var hash = hmac.digest( 'base64' );
return hash;
}
module.exports = {
genLongTermKey : genLongTermKey,
genSharedKey : genSharedKey,
}
| var SEP = ':';
var crypto = require('crypto');
function genLongTermKey( username, realm, password ) {
var md5 = crypto.createHash( 'md5' );
var text = username + SEP + realm + SEP + password;
md5.update( text );
var hash = md5.digest( 'hex' );
return hash;
+ }
+ function genSharedKey( username, shared_key ) {
+ var hmac = crypto.createHmac( 'sha1', shared_key );
+
+ hmac.update( username );
+
+ var hash = hmac.digest( 'base64' );
+
- return;
+ return hash;
? +++++
}
module.exports = {
genLongTermKey : genLongTermKey,
+ genSharedKey : genSharedKey,
} | 11 | 0.55 | 10 | 1 |
5cecb72e93e81e75378a43e52a2abadb7f32f547 | lib/query/index.js | lib/query/index.js | 'use strict'
const xray = require('x-ray')
const x = xray()
module.exports = query => {
return new Promise((resolve, reject) => {
let q = null
if (query.split(' ').length > 1) {
q = query.split(' ').join('-')
} else {
q = query
}
x('http://canigivemydog.com/' + q, { question: 'div.headline_area > h1', answer: 'div.format_text.entry-content > h2 > strong' })((err, res) => {
if (err) {
return reject(err)
}
let answer = res.answer.split(': ')[1]
resolve({ question: res.question, answer })
})
})
}
| 'use strict'
const xray = require('x-ray')
const x = xray()
module.exports = query => {
return new Promise((resolve, reject) => {
let q = null
if (query.split(' ').length > 1) {
q = query.split(' ').join('-')
} else {
q = query
}
x('http://canigivemydog.com/' + q, { question: 'h1.entry-title', answerStrong: 'div.thecontent.clearfix > h2 > strong', answerB: 'div.thecontent.clearfix > h2 > b' })((err, res) => {
if (err) {
return reject(err)
}
if (res.answerStrong) {
resolve({ question: res.question, answer: res.answerStrong.split(': ')[1] })
} else if (res.answerB) {
resolve({ question: res.question, answer: res.answerB.split(': ')[1] })
} else {
resolve({ question: res.question, answer: 'Trouble finding the answer.' })
}
})
})
}
| Handle answer not found on page | Handle answer not found on page
| JavaScript | mit | eddiezane/canigivemydog-api | javascript | ## Code Before:
'use strict'
const xray = require('x-ray')
const x = xray()
module.exports = query => {
return new Promise((resolve, reject) => {
let q = null
if (query.split(' ').length > 1) {
q = query.split(' ').join('-')
} else {
q = query
}
x('http://canigivemydog.com/' + q, { question: 'div.headline_area > h1', answer: 'div.format_text.entry-content > h2 > strong' })((err, res) => {
if (err) {
return reject(err)
}
let answer = res.answer.split(': ')[1]
resolve({ question: res.question, answer })
})
})
}
## Instruction:
Handle answer not found on page
## Code After:
'use strict'
const xray = require('x-ray')
const x = xray()
module.exports = query => {
return new Promise((resolve, reject) => {
let q = null
if (query.split(' ').length > 1) {
q = query.split(' ').join('-')
} else {
q = query
}
x('http://canigivemydog.com/' + q, { question: 'h1.entry-title', answerStrong: 'div.thecontent.clearfix > h2 > strong', answerB: 'div.thecontent.clearfix > h2 > b' })((err, res) => {
if (err) {
return reject(err)
}
if (res.answerStrong) {
resolve({ question: res.question, answer: res.answerStrong.split(': ')[1] })
} else if (res.answerB) {
resolve({ question: res.question, answer: res.answerB.split(': ')[1] })
} else {
resolve({ question: res.question, answer: 'Trouble finding the answer.' })
}
})
})
}
| 'use strict'
const xray = require('x-ray')
const x = xray()
module.exports = query => {
return new Promise((resolve, reject) => {
let q = null
if (query.split(' ').length > 1) {
q = query.split(' ').join('-')
} else {
q = query
}
- x('http://canigivemydog.com/' + q, { question: 'div.headline_area > h1', answer: 'div.format_text.entry-content > h2 > strong' })((err, res) => {
+ x('http://canigivemydog.com/' + q, { question: 'h1.entry-title', answerStrong: 'div.thecontent.clearfix > h2 > strong', answerB: 'div.thecontent.clearfix > h2 > b' })((err, res) => {
if (err) {
return reject(err)
}
- let answer = res.answer.split(': ')[1]
+ if (res.answerStrong) {
+ resolve({ question: res.question, answer: res.answerStrong.split(': ')[1] })
+ } else if (res.answerB) {
- resolve({ question: res.question, answer })
+ resolve({ question: res.question, answer: res.answerB.split(': ')[1] })
? ++ ++++++++++++++++++++++++++++
+ } else {
+ resolve({ question: res.question, answer: 'Trouble finding the answer.' })
+ }
})
})
} | 11 | 0.44 | 8 | 3 |
e95edabe1b5f36f65e0e15e040fb5871d6d7e13d | index.js | index.js | var path = require('path');
var pkg = require('./package.json');
var jeetPath = path.join(__dirname, 'styl')
exports = module.exports = function (opts) {
return function (style) {
style.import(jeetPath);
}
}
exports.libname = pkg.name;
exports.path = jeetPath;
exports.version = pkg.version;
| var path = require('path');
var pkg = require('./package.json');
var jeetPath = path.join(__dirname, 'styl')
exports = module.exports = function (opts) {
var implicit = (opts && opts.implicit == false) ? false : true;
return function (style) {
style.include(__dirname);
if (implicit) {
style.import(jeetPath);
}
}
}
exports.libname = pkg.name;
exports.path = jeetPath;
exports.version = pkg.version;
| Add option to implicitly import Jeet | Add option to implicitly import Jeet
This is handy for `stylus —use jeet` usage and probably other places. It removes the need to include `@import ‘jeet’` at the top of every file. | JavaScript | mit | mojotech/jeet,mojotech/jeet | javascript | ## Code Before:
var path = require('path');
var pkg = require('./package.json');
var jeetPath = path.join(__dirname, 'styl')
exports = module.exports = function (opts) {
return function (style) {
style.import(jeetPath);
}
}
exports.libname = pkg.name;
exports.path = jeetPath;
exports.version = pkg.version;
## Instruction:
Add option to implicitly import Jeet
This is handy for `stylus —use jeet` usage and probably other places. It removes the need to include `@import ‘jeet’` at the top of every file.
## Code After:
var path = require('path');
var pkg = require('./package.json');
var jeetPath = path.join(__dirname, 'styl')
exports = module.exports = function (opts) {
var implicit = (opts && opts.implicit == false) ? false : true;
return function (style) {
style.include(__dirname);
if (implicit) {
style.import(jeetPath);
}
}
}
exports.libname = pkg.name;
exports.path = jeetPath;
exports.version = pkg.version;
| var path = require('path');
var pkg = require('./package.json');
var jeetPath = path.join(__dirname, 'styl')
exports = module.exports = function (opts) {
+ var implicit = (opts && opts.implicit == false) ? false : true;
+
return function (style) {
+ style.include(__dirname);
+
+ if (implicit) {
- style.import(jeetPath);
+ style.import(jeetPath);
? ++
+ }
}
}
exports.libname = pkg.name;
exports.path = jeetPath;
exports.version = pkg.version; | 8 | 0.571429 | 7 | 1 |
224e79ca27a2d1d7c0ea4b312ba850ea69e37c40 | lib/binding_web/prefix.js | lib/binding_web/prefix.js | var TreeSitter = function() {
var initPromise;
class Parser {
constructor() {
this.initialize();
}
initialize() {
throw new Error("cannot construct a Parser before calling `init()`");
}
static init(moduleOptions) {
if (initPromise) return initPromise;
Module = Object.assign({ }, Module, moduleOptions);
return initPromise = new Promise((resolveInitPromise) => {
| var TreeSitter = function() {
var initPromise;
var document = typeof window == 'object'
? {currentScript: window.document.currentScript}
: null;
class Parser {
constructor() {
this.initialize();
}
initialize() {
throw new Error("cannot construct a Parser before calling `init()`");
}
static init(moduleOptions) {
if (initPromise) return initPromise;
Module = Object.assign({}, Module, moduleOptions);
return initPromise = new Promise((resolveInitPromise) => {
| Fix script directory that's passed to locateFile | web: Fix script directory that's passed to locateFile
| JavaScript | mit | tree-sitter/tree-sitter,tree-sitter/tree-sitter,tree-sitter/tree-sitter,tree-sitter/tree-sitter,tree-sitter/tree-sitter,tree-sitter/tree-sitter,tree-sitter/tree-sitter | javascript | ## Code Before:
var TreeSitter = function() {
var initPromise;
class Parser {
constructor() {
this.initialize();
}
initialize() {
throw new Error("cannot construct a Parser before calling `init()`");
}
static init(moduleOptions) {
if (initPromise) return initPromise;
Module = Object.assign({ }, Module, moduleOptions);
return initPromise = new Promise((resolveInitPromise) => {
## Instruction:
web: Fix script directory that's passed to locateFile
## Code After:
var TreeSitter = function() {
var initPromise;
var document = typeof window == 'object'
? {currentScript: window.document.currentScript}
: null;
class Parser {
constructor() {
this.initialize();
}
initialize() {
throw new Error("cannot construct a Parser before calling `init()`");
}
static init(moduleOptions) {
if (initPromise) return initPromise;
Module = Object.assign({}, Module, moduleOptions);
return initPromise = new Promise((resolveInitPromise) => {
| var TreeSitter = function() {
var initPromise;
+ var document = typeof window == 'object'
+ ? {currentScript: window.document.currentScript}
+ : null;
+
class Parser {
constructor() {
this.initialize();
}
initialize() {
throw new Error("cannot construct a Parser before calling `init()`");
}
static init(moduleOptions) {
if (initPromise) return initPromise;
- Module = Object.assign({ }, Module, moduleOptions);
? -
+ Module = Object.assign({}, Module, moduleOptions);
return initPromise = new Promise((resolveInitPromise) => { | 6 | 0.4 | 5 | 1 |
5738dcacaefa023e0a2d6447aeff188f3dc62ee8 | tweetclock.rb | tweetclock.rb | require 'sinatra'
require 'eventmachine'
require 'em-http'
require 'json'
require 'sinatra/redis'
SECONDS_TTL = 12 * 60 * 60
MINUTES_TTL = 9 * 24 * 60 * 60
configure :production do
require 'newrelic_rpm'
require 'hoptoad_notifier'
end
HoptoadNotifier.configure do |config|
config.api_key = ENV['HOPTOAD_API_KEY']
end
use HoptoadNotifier::Rack
enable :raise_errors
set :redis, ENV['REDISTOGO_URL']
get '/' do
redis.get(Time.now.to_i - 5)
end
get '/:api_version/id_at/:posix' do
if params[:api_version] == '1'
redis.get params[:posix].to_i
end
end | require 'sinatra'
require 'eventmachine'
require 'em-http'
require 'json'
require 'sinatra/redis'
SECONDS_TTL = 12 * 60 * 60
MINUTES_TTL = 9 * 24 * 60 * 60
configure :production do
require 'newrelic_rpm'
require 'hoptoad_notifier'
HoptoadNotifier.configure do |config|
config.api_key = ENV['HOPTOAD_API_KEY']
end
use HoptoadNotifier::Rack
enable :raise_errors
end
set :redis, ENV['REDISTOGO_URL']
get '/' do
redis.get(Time.now.to_i - 5)
end
get '/:api_version/id_at/:posix_time.:format' do
if params[:api_version] == '1'
tt = TweetTime.find(params[:posix_time].to_i)
return if tt.nil?
case params[:format]
when 'json'
tt.to_json
when 'xml'
tt.to_xml
when 'atom'
tt.to_atom
else
tt.time
end
end
end
class TweetTime
attr_accessor :time, :id
def initialize(time, id)
@time, @id = time, id
end
def to_h
{:time => @time, :id => @id}
end
def to_json
to_h.to_json
end
def self.find(time)
if (Time.now.to_i - time < SECONDS_TTL)
new time, redis.get(time)
else
near_time = find_nearest(time)
new near_time, redis.get(near_time)
end
end
private
def self.find_nearest(time)
time = Time.at(time)
if time.sec < 31
previous_minute(time).to_i
else
next_minute(time).to_i
end
end
def self.next_minute(time)
time + (60 - time.sec)
end
def self.previous_minute(time)
time - time.sec
end
end | Return times and near-times in JSON format. | Return times and near-times in JSON format.
| Ruby | mit | mattmanning/tweetclock | ruby | ## Code Before:
require 'sinatra'
require 'eventmachine'
require 'em-http'
require 'json'
require 'sinatra/redis'
SECONDS_TTL = 12 * 60 * 60
MINUTES_TTL = 9 * 24 * 60 * 60
configure :production do
require 'newrelic_rpm'
require 'hoptoad_notifier'
end
HoptoadNotifier.configure do |config|
config.api_key = ENV['HOPTOAD_API_KEY']
end
use HoptoadNotifier::Rack
enable :raise_errors
set :redis, ENV['REDISTOGO_URL']
get '/' do
redis.get(Time.now.to_i - 5)
end
get '/:api_version/id_at/:posix' do
if params[:api_version] == '1'
redis.get params[:posix].to_i
end
end
## Instruction:
Return times and near-times in JSON format.
## Code After:
require 'sinatra'
require 'eventmachine'
require 'em-http'
require 'json'
require 'sinatra/redis'
SECONDS_TTL = 12 * 60 * 60
MINUTES_TTL = 9 * 24 * 60 * 60
configure :production do
require 'newrelic_rpm'
require 'hoptoad_notifier'
HoptoadNotifier.configure do |config|
config.api_key = ENV['HOPTOAD_API_KEY']
end
use HoptoadNotifier::Rack
enable :raise_errors
end
set :redis, ENV['REDISTOGO_URL']
get '/' do
redis.get(Time.now.to_i - 5)
end
get '/:api_version/id_at/:posix_time.:format' do
if params[:api_version] == '1'
tt = TweetTime.find(params[:posix_time].to_i)
return if tt.nil?
case params[:format]
when 'json'
tt.to_json
when 'xml'
tt.to_xml
when 'atom'
tt.to_atom
else
tt.time
end
end
end
class TweetTime
attr_accessor :time, :id
def initialize(time, id)
@time, @id = time, id
end
def to_h
{:time => @time, :id => @id}
end
def to_json
to_h.to_json
end
def self.find(time)
if (Time.now.to_i - time < SECONDS_TTL)
new time, redis.get(time)
else
near_time = find_nearest(time)
new near_time, redis.get(near_time)
end
end
private
def self.find_nearest(time)
time = Time.at(time)
if time.sec < 31
previous_minute(time).to_i
else
next_minute(time).to_i
end
end
def self.next_minute(time)
time + (60 - time.sec)
end
def self.previous_minute(time)
time - time.sec
end
end | require 'sinatra'
require 'eventmachine'
require 'em-http'
require 'json'
require 'sinatra/redis'
SECONDS_TTL = 12 * 60 * 60
MINUTES_TTL = 9 * 24 * 60 * 60
configure :production do
require 'newrelic_rpm'
require 'hoptoad_notifier'
+
+ HoptoadNotifier.configure do |config|
+ config.api_key = ENV['HOPTOAD_API_KEY']
+ end
+
+ use HoptoadNotifier::Rack
+ enable :raise_errors
end
- HoptoadNotifier.configure do |config|
- config.api_key = ENV['HOPTOAD_API_KEY']
- end
-
- use HoptoadNotifier::Rack
- enable :raise_errors
set :redis, ENV['REDISTOGO_URL']
get '/' do
redis.get(Time.now.to_i - 5)
end
- get '/:api_version/id_at/:posix' do
+ get '/:api_version/id_at/:posix_time.:format' do
? +++++++++++++
if params[:api_version] == '1'
- redis.get params[:posix].to_i
+ tt = TweetTime.find(params[:posix_time].to_i)
+ return if tt.nil?
+
+ case params[:format]
+ when 'json'
+ tt.to_json
+ when 'xml'
+ tt.to_xml
+ when 'atom'
+ tt.to_atom
+ else
+ tt.time
+ end
end
end
+
+ class TweetTime
+ attr_accessor :time, :id
+
+ def initialize(time, id)
+ @time, @id = time, id
+ end
+
+ def to_h
+ {:time => @time, :id => @id}
+ end
+
+ def to_json
+ to_h.to_json
+ end
+
+ def self.find(time)
+ if (Time.now.to_i - time < SECONDS_TTL)
+ new time, redis.get(time)
+ else
+ near_time = find_nearest(time)
+ new near_time, redis.get(near_time)
+ end
+ end
+
+ private
+
+ def self.find_nearest(time)
+ time = Time.at(time)
+ if time.sec < 31
+ previous_minute(time).to_i
+ else
+ next_minute(time).to_i
+ end
+ end
+
+ def self.next_minute(time)
+ time + (60 - time.sec)
+ end
+
+ def self.previous_minute(time)
+ time - time.sec
+ end
+ end | 73 | 2.354839 | 65 | 8 |
4f3d8ba1f6522c6ac380527dd98a1bcd1051503d | .travis.yml | .travis.yml | language: ruby
rvm:
- 2.2.9
- 2.3.6
- 2.4.3
- 2.5.0
gemfile:
- gemfiles/rails_5_2.gemfile
- gemfiles/rails_5_1.gemfile
- gemfiles/rails_5_0.gemfile
- gemfiles/rails_4_2.gemfile
- gemfiles/rails_4_1.gemfile
- gemfiles/rails_4_0.gemfile
matrix:
exclude:
- rvm: 2.4.3
gemfile: gemfiles/rails_4_0.gemfile
- rvm: 2.4.3
gemfile: gemfiles/rails_4_1.gemfile
before_install: gem update bundler
sudo: false
env:
- DB=sqlite
- DB=mysql
- DB=postgres
before_script:
- sh -c "if [ '$DB' = 'mysql' ]; then mysql -e 'create database IF NOT EXISTS unread_test;'; fi"
- sh -c "if [ '$DB' = 'postgres' ]; then psql -c 'create database unread_test;' -U postgres; fi"
| language: ruby
rvm:
- 2.2.9
- 2.3.6
- 2.4.3
- 2.5.0
gemfile:
- gemfiles/rails_5_2.gemfile
- gemfiles/rails_5_1.gemfile
- gemfiles/rails_5_0.gemfile
- gemfiles/rails_4_2.gemfile
- gemfiles/rails_4_1.gemfile
- gemfiles/rails_4_0.gemfile
matrix:
exclude:
- rvm: 2.4.3
gemfile: gemfiles/rails_4_0.gemfile
- rvm: 2.4.3
gemfile: gemfiles/rails_4_1.gemfile
before_install: gem update bundler
sudo: false
env:
- DB=sqlite
- DB=mysql
- DB=postgres
before_script:
- gem update --system # https://github.com/travis-ci/travis-ci/issues/8978
- sh -c "if [ '$DB' = 'mysql' ]; then mysql -e 'create database IF NOT EXISTS unread_test;'; fi"
- sh -c "if [ '$DB' = 'postgres' ]; then psql -c 'create database unread_test;' -U postgres; fi"
| Fix Ruby 2.5.0 build failure | Travis: Fix Ruby 2.5.0 build failure
RubyGems 2.7.4 is required
https://github.com/travis-ci/travis-ci/issues/8978
| YAML | mit | ledermann/unread | yaml | ## Code Before:
language: ruby
rvm:
- 2.2.9
- 2.3.6
- 2.4.3
- 2.5.0
gemfile:
- gemfiles/rails_5_2.gemfile
- gemfiles/rails_5_1.gemfile
- gemfiles/rails_5_0.gemfile
- gemfiles/rails_4_2.gemfile
- gemfiles/rails_4_1.gemfile
- gemfiles/rails_4_0.gemfile
matrix:
exclude:
- rvm: 2.4.3
gemfile: gemfiles/rails_4_0.gemfile
- rvm: 2.4.3
gemfile: gemfiles/rails_4_1.gemfile
before_install: gem update bundler
sudo: false
env:
- DB=sqlite
- DB=mysql
- DB=postgres
before_script:
- sh -c "if [ '$DB' = 'mysql' ]; then mysql -e 'create database IF NOT EXISTS unread_test;'; fi"
- sh -c "if [ '$DB' = 'postgres' ]; then psql -c 'create database unread_test;' -U postgres; fi"
## Instruction:
Travis: Fix Ruby 2.5.0 build failure
RubyGems 2.7.4 is required
https://github.com/travis-ci/travis-ci/issues/8978
## Code After:
language: ruby
rvm:
- 2.2.9
- 2.3.6
- 2.4.3
- 2.5.0
gemfile:
- gemfiles/rails_5_2.gemfile
- gemfiles/rails_5_1.gemfile
- gemfiles/rails_5_0.gemfile
- gemfiles/rails_4_2.gemfile
- gemfiles/rails_4_1.gemfile
- gemfiles/rails_4_0.gemfile
matrix:
exclude:
- rvm: 2.4.3
gemfile: gemfiles/rails_4_0.gemfile
- rvm: 2.4.3
gemfile: gemfiles/rails_4_1.gemfile
before_install: gem update bundler
sudo: false
env:
- DB=sqlite
- DB=mysql
- DB=postgres
before_script:
- gem update --system # https://github.com/travis-ci/travis-ci/issues/8978
- sh -c "if [ '$DB' = 'mysql' ]; then mysql -e 'create database IF NOT EXISTS unread_test;'; fi"
- sh -c "if [ '$DB' = 'postgres' ]; then psql -c 'create database unread_test;' -U postgres; fi"
| language: ruby
rvm:
- 2.2.9
- 2.3.6
- 2.4.3
- 2.5.0
gemfile:
- gemfiles/rails_5_2.gemfile
- gemfiles/rails_5_1.gemfile
- gemfiles/rails_5_0.gemfile
- gemfiles/rails_4_2.gemfile
- gemfiles/rails_4_1.gemfile
- gemfiles/rails_4_0.gemfile
matrix:
exclude:
- rvm: 2.4.3
gemfile: gemfiles/rails_4_0.gemfile
- rvm: 2.4.3
gemfile: gemfiles/rails_4_1.gemfile
before_install: gem update bundler
sudo: false
env:
- DB=sqlite
- DB=mysql
- DB=postgres
before_script:
+ - gem update --system # https://github.com/travis-ci/travis-ci/issues/8978
- sh -c "if [ '$DB' = 'mysql' ]; then mysql -e 'create database IF NOT EXISTS unread_test;'; fi"
- sh -c "if [ '$DB' = 'postgres' ]; then psql -c 'create database unread_test;' -U postgres; fi" | 1 | 0.035714 | 1 | 0 |
b02218ed8de84a5cd7ecf6ad202d38f104a40702 | src/test/java/de/gesellix/docker/client/filesocket/UnixSocketFactorySupportTest.java | src/test/java/de/gesellix/docker/client/filesocket/UnixSocketFactorySupportTest.java | package de.gesellix.docker.client.filesocket;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
class UnixSocketFactorySupportTest {
@Test
@DisplayName("Supports Mac OS X")
void supportsMacOsX() {
assertTrue(new UnixSocketFactorySupport().isSupported("Mac OS X"));
}
@Test
@DisplayName("Supports Linux")
void supportsLinux() {
assertTrue(new UnixSocketFactorySupport().isSupported("Linux"));
}
@Test
@DisplayName("Doesn't support Windows 10")
void doesNotSupportWindows10() {
assertFalse(new UnixSocketFactorySupport().isSupported("Windows 10"));
}
}
| package de.gesellix.docker.client.filesocket;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledOnOs;
import org.junit.jupiter.api.condition.OS;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
class UnixSocketFactorySupportTest {
@Test
@EnabledOnOs(OS.MAC)
@DisplayName("Supports Mac OS X")
void supportsMacOsX() {
assertTrue(new UnixSocketFactorySupport().isSupported("Mac OS X"));
}
@Test
@EnabledOnOs(OS.LINUX)
@DisplayName("Supports Linux")
void supportsLinux() {
assertTrue(new UnixSocketFactorySupport().isSupported("Linux"));
}
@Test
@EnabledOnOs(OS.WINDOWS)
@DisplayName("Doesn't support Windows 10")
void doesNotSupportWindows10() {
assertFalse(new UnixSocketFactorySupport().isSupported("Windows 10"));
}
}
| Check UnixSocketSupport os specific variants only on the relevant os' | Check UnixSocketSupport os specific variants only on the relevant os'
| Java | mit | docker-client/docker-filesocket,docker-client/docker-filesocket | java | ## Code Before:
package de.gesellix.docker.client.filesocket;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
class UnixSocketFactorySupportTest {
@Test
@DisplayName("Supports Mac OS X")
void supportsMacOsX() {
assertTrue(new UnixSocketFactorySupport().isSupported("Mac OS X"));
}
@Test
@DisplayName("Supports Linux")
void supportsLinux() {
assertTrue(new UnixSocketFactorySupport().isSupported("Linux"));
}
@Test
@DisplayName("Doesn't support Windows 10")
void doesNotSupportWindows10() {
assertFalse(new UnixSocketFactorySupport().isSupported("Windows 10"));
}
}
## Instruction:
Check UnixSocketSupport os specific variants only on the relevant os'
## Code After:
package de.gesellix.docker.client.filesocket;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledOnOs;
import org.junit.jupiter.api.condition.OS;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
class UnixSocketFactorySupportTest {
@Test
@EnabledOnOs(OS.MAC)
@DisplayName("Supports Mac OS X")
void supportsMacOsX() {
assertTrue(new UnixSocketFactorySupport().isSupported("Mac OS X"));
}
@Test
@EnabledOnOs(OS.LINUX)
@DisplayName("Supports Linux")
void supportsLinux() {
assertTrue(new UnixSocketFactorySupport().isSupported("Linux"));
}
@Test
@EnabledOnOs(OS.WINDOWS)
@DisplayName("Doesn't support Windows 10")
void doesNotSupportWindows10() {
assertFalse(new UnixSocketFactorySupport().isSupported("Windows 10"));
}
}
| package de.gesellix.docker.client.filesocket;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
+ import org.junit.jupiter.api.condition.EnabledOnOs;
+ import org.junit.jupiter.api.condition.OS;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
class UnixSocketFactorySupportTest {
@Test
+ @EnabledOnOs(OS.MAC)
@DisplayName("Supports Mac OS X")
void supportsMacOsX() {
assertTrue(new UnixSocketFactorySupport().isSupported("Mac OS X"));
}
@Test
+ @EnabledOnOs(OS.LINUX)
@DisplayName("Supports Linux")
void supportsLinux() {
assertTrue(new UnixSocketFactorySupport().isSupported("Linux"));
}
@Test
+ @EnabledOnOs(OS.WINDOWS)
@DisplayName("Doesn't support Windows 10")
void doesNotSupportWindows10() {
assertFalse(new UnixSocketFactorySupport().isSupported("Windows 10"));
}
} | 5 | 0.178571 | 5 | 0 |
8adef8bff6e8a192a0a06388f3f4213bbf0e13a0 | index.js | index.js | 'use strict'
const http = require('http')
const express = require('express')
const bodyParser = require('body-parser')
const Bot = require('messenger-bot')
let bot = new Bot({
token: process.env.PAGE_TOKEN,
verify: 'VERIFY_TOKEN',
app_secret: 'APP_SECRET'
})
bot.on('error', (err) => {
console.log(err.message)
})
bot.on('message', (payload, reply) => {
let text = payload.message.text
bot.getProfile(payload.sender.id, (err, profile) => {
if (err) throw err
reply({ text }, (err) => {
if (err) throw err
console.log(`Echoed back to ${profile.first_name} ${profile.last_name}: ${text}`)
})
})
})
let app = express()
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({
extended: true
}))
app.get('/', (req, res) => {
return bot._verify(req, res)
})
app.post('/', (req, res) => {
bot._handleMessage(req.body)
res.end(JSON.stringify({ status: 'ok' }))
})
http.createServer(app).listen(3000) | 'use strict'
const http = require('http')
const express = require('express')
const bodyParser = require('body-parser')
const Bot = require('messenger-bot')
let bot = new Bot({
token: process.env.PAGE_TOKEN,
verify: 'VERIFY_TOKEN',
app_secret: 'APP_SECRET'
})
bot.on('error', (err) => {
console.log(err.message)
})
bot.on('message', (payload, reply) => {
let text = payload.message.text
bot.getProfile(payload.sender.id, (err, profile) => {
if (err) throw err
reply({ text }, (err) => {
if (err) throw err
console.log(`Echoed back to ${profile.first_name} ${profile.last_name}: ${text}`)
})
})
})
let app = express()
app.set('port', process.env.PORT || 8080);
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({
extended: true
}))
app.get('/', (req, res) => {
return bot._verify(req, res)
})
app.post('/', (req, res) => {
bot._handleMessage(req.body)
res.end(JSON.stringify({ status: 'ok' }))
})
app.listen(app.get('port'), () => {
console.log('Node app is running on port', app.get('port'));
});
| Add message for starting the server | Add message for starting the server
| JavaScript | mit | nikolay-radkov/ebudgie-server,nikolay-radkov/ebudgie-server | javascript | ## Code Before:
'use strict'
const http = require('http')
const express = require('express')
const bodyParser = require('body-parser')
const Bot = require('messenger-bot')
let bot = new Bot({
token: process.env.PAGE_TOKEN,
verify: 'VERIFY_TOKEN',
app_secret: 'APP_SECRET'
})
bot.on('error', (err) => {
console.log(err.message)
})
bot.on('message', (payload, reply) => {
let text = payload.message.text
bot.getProfile(payload.sender.id, (err, profile) => {
if (err) throw err
reply({ text }, (err) => {
if (err) throw err
console.log(`Echoed back to ${profile.first_name} ${profile.last_name}: ${text}`)
})
})
})
let app = express()
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({
extended: true
}))
app.get('/', (req, res) => {
return bot._verify(req, res)
})
app.post('/', (req, res) => {
bot._handleMessage(req.body)
res.end(JSON.stringify({ status: 'ok' }))
})
http.createServer(app).listen(3000)
## Instruction:
Add message for starting the server
## Code After:
'use strict'
const http = require('http')
const express = require('express')
const bodyParser = require('body-parser')
const Bot = require('messenger-bot')
let bot = new Bot({
token: process.env.PAGE_TOKEN,
verify: 'VERIFY_TOKEN',
app_secret: 'APP_SECRET'
})
bot.on('error', (err) => {
console.log(err.message)
})
bot.on('message', (payload, reply) => {
let text = payload.message.text
bot.getProfile(payload.sender.id, (err, profile) => {
if (err) throw err
reply({ text }, (err) => {
if (err) throw err
console.log(`Echoed back to ${profile.first_name} ${profile.last_name}: ${text}`)
})
})
})
let app = express()
app.set('port', process.env.PORT || 8080);
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({
extended: true
}))
app.get('/', (req, res) => {
return bot._verify(req, res)
})
app.post('/', (req, res) => {
bot._handleMessage(req.body)
res.end(JSON.stringify({ status: 'ok' }))
})
app.listen(app.get('port'), () => {
console.log('Node app is running on port', app.get('port'));
});
| 'use strict'
const http = require('http')
const express = require('express')
const bodyParser = require('body-parser')
const Bot = require('messenger-bot')
let bot = new Bot({
token: process.env.PAGE_TOKEN,
verify: 'VERIFY_TOKEN',
app_secret: 'APP_SECRET'
})
bot.on('error', (err) => {
console.log(err.message)
})
bot.on('message', (payload, reply) => {
let text = payload.message.text
bot.getProfile(payload.sender.id, (err, profile) => {
if (err) throw err
reply({ text }, (err) => {
if (err) throw err
console.log(`Echoed back to ${profile.first_name} ${profile.last_name}: ${text}`)
})
})
})
let app = express()
+ app.set('port', process.env.PORT || 8080);
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({
extended: true
}))
app.get('/', (req, res) => {
return bot._verify(req, res)
})
app.post('/', (req, res) => {
bot._handleMessage(req.body)
res.end(JSON.stringify({ status: 'ok' }))
})
- http.createServer(app).listen(3000)
+ app.listen(app.get('port'), () => {
+ console.log('Node app is running on port', app.get('port'));
+ }); | 5 | 0.106383 | 4 | 1 |
b43849a57d340027eee2e0c3ff05e1a1952b2e08 | Casks/bleep.rb | Casks/bleep.rb | cask :v1 => 'bleep' do
version :latest
sha256 :no_check
# utorrent.com is the official download host per the vendor homepage
url 'https://download-new.utorrent.com/endpoint/bleep/os/osx/track/stable/'
name 'Bleep'
homepage 'http://labs.bittorrent.com/bleep/'
license :gratis
app 'Bleep.app'
end
| cask :v1 => 'bleep' do
version :latest
sha256 :no_check
# utorrent.com is the official download host per the vendor homepage
url 'https://download-new.utorrent.com/endpoint/bleep/os/osx/track/stable/'
name 'Bleep'
homepage 'http://www.bleep.pm/'
license :gratis
tags :vendor => 'BitTorrent'
app 'Bleep.app'
zap :delete => [
'~/Library/Application Support/Bleep',
'~/Library/Caches/com.bittorrent.bleep.osx',
'~/Library/Preferences/com.bittorrent.bleep.osx.plist',
'~/Library/Saved Application State/com.bittorrent.bleep.osx.savedState',
]
end
| Update Bleep.app homepage, add vendor and zap ~/Library files | Update Bleep.app homepage, add vendor and zap ~/Library files
| Ruby | bsd-2-clause | frapposelli/homebrew-cask,tarwich/homebrew-cask,ianyh/homebrew-cask,Keloran/homebrew-cask,jamesmlees/homebrew-cask,mlocher/homebrew-cask,kongslund/homebrew-cask,jeanregisser/homebrew-cask,wastrachan/homebrew-cask,wuman/homebrew-cask,jellyfishcoder/homebrew-cask,Saklad5/homebrew-cask,maxnordlund/homebrew-cask,adrianchia/homebrew-cask,0rax/homebrew-cask,reelsense/homebrew-cask,sosedoff/homebrew-cask,tjnycum/homebrew-cask,casidiablo/homebrew-cask,doits/homebrew-cask,phpwutz/homebrew-cask,kingthorin/homebrew-cask,troyxmccall/homebrew-cask,mlocher/homebrew-cask,Cottser/homebrew-cask,jacobdam/homebrew-cask,mfpierre/homebrew-cask,lantrix/homebrew-cask,kolomiichenko/homebrew-cask,englishm/homebrew-cask,afh/homebrew-cask,dvdoliveira/homebrew-cask,theoriginalgri/homebrew-cask,mathbunnyru/homebrew-cask,skyyuan/homebrew-cask,tedbundyjr/homebrew-cask,syscrusher/homebrew-cask,ayohrling/homebrew-cask,paulombcosta/homebrew-cask,athrunsun/homebrew-cask,xyb/homebrew-cask,perfide/homebrew-cask,rhendric/homebrew-cask,kievechua/homebrew-cask,antogg/homebrew-cask,blogabe/homebrew-cask,mjgardner/homebrew-cask,sparrc/homebrew-cask,bkono/homebrew-cask,mariusbutuc/homebrew-cask,tsparber/homebrew-cask,sirodoht/homebrew-cask,tedski/homebrew-cask,mokagio/homebrew-cask,nickpellant/homebrew-cask,opsdev-ws/homebrew-cask,imgarylai/homebrew-cask,shonjir/homebrew-cask,afh/homebrew-cask,kiliankoe/homebrew-cask,uetchy/homebrew-cask,sscotth/homebrew-cask,nightscape/homebrew-cask,coeligena/homebrew-customized,chrisRidgers/homebrew-cask,optikfluffel/homebrew-cask,julionc/homebrew-cask,atsuyim/homebrew-cask,hackhandslabs/homebrew-cask,esebastian/homebrew-cask,timsutton/homebrew-cask,Hywan/homebrew-cask,jpmat296/homebrew-cask,shoichiaizawa/homebrew-cask,zeusdeux/homebrew-cask,dspeckhard/homebrew-cask,bgandon/homebrew-cask,helloIAmPau/homebrew-cask,jpmat296/homebrew-cask,chadcatlett/caskroom-homebrew-cask,jaredsampson/homebrew-cask,albertico/homebrew-cask,jawshooah/homebrew-cask,danielbayley/homebrew-cask,thii/homebrew-cask,akiomik/homebrew-cask,yutarody/homebrew-cask,josa42/homebrew-cask,zeusdeux/homebrew-cask,lifepillar/homebrew-cask,gyugyu/homebrew-cask,tyage/homebrew-cask,yumitsu/homebrew-cask,opsdev-ws/homebrew-cask,leonmachadowilcox/homebrew-cask,zhuzihhhh/homebrew-cask,reelsense/homebrew-cask,okket/homebrew-cask,jellyfishcoder/homebrew-cask,miccal/homebrew-cask,SamiHiltunen/homebrew-cask,christer155/homebrew-cask,mishari/homebrew-cask,corbt/homebrew-cask,ftiff/homebrew-cask,mwilmer/homebrew-cask,vin047/homebrew-cask,nathansgreen/homebrew-cask,giannitm/homebrew-cask,yurikoles/homebrew-cask,tranc99/homebrew-cask,genewoo/homebrew-cask,lauantai/homebrew-cask,imgarylai/homebrew-cask,SentinelWarren/homebrew-cask,kpearson/homebrew-cask,malob/homebrew-cask,askl56/homebrew-cask,Saklad5/homebrew-cask,hristozov/homebrew-cask,supriyantomaftuh/homebrew-cask,jhowtan/homebrew-cask,cliffcotino/homebrew-cask,johnste/homebrew-cask,CameronGarrett/homebrew-cask,napaxton/homebrew-cask,Fedalto/homebrew-cask,cfillion/homebrew-cask,morganestes/homebrew-cask,paulbreslin/homebrew-cask,artdevjs/homebrew-cask,brianshumate/homebrew-cask,rubenerd/homebrew-cask,genewoo/homebrew-cask,tyage/homebrew-cask,aguynamedryan/homebrew-cask,Amorymeltzer/homebrew-cask,xakraz/homebrew-cask,LaurentFough/homebrew-cask,thehunmonkgroup/homebrew-cask,feigaochn/homebrew-cask,gmkey/homebrew-cask,stonehippo/homebrew-cask,0xadada/homebrew-cask,Ketouem/homebrew-cask,phpwutz/homebrew-cask,hellosky806/homebrew-cask,shoichiaizawa/homebrew-cask,antogg/homebrew-cask,aguynamedryan/homebrew-cask,xight/homebrew-cask,larseggert/homebrew-cask,athrunsun/homebrew-cask,esebastian/homebrew-cask,franklouwers/homebrew-cask,n0ts/homebrew-cask,kronicd/homebrew-cask,hovancik/homebrew-cask,asbachb/homebrew-cask,shorshe/homebrew-cask,dictcp/homebrew-cask,cprecioso/homebrew-cask,christophermanning/homebrew-cask,ksato9700/homebrew-cask,chuanxd/homebrew-cask,pkq/homebrew-cask,christophermanning/homebrew-cask,robbiethegeek/homebrew-cask,lalyos/homebrew-cask,tjt263/homebrew-cask,jacobbednarz/homebrew-cask,renard/homebrew-cask,artdevjs/homebrew-cask,shorshe/homebrew-cask,sanyer/homebrew-cask,yurrriq/homebrew-cask,colindean/homebrew-cask,jangalinski/homebrew-cask,arranubels/homebrew-cask,jgarber623/homebrew-cask,exherb/homebrew-cask,franklouwers/homebrew-cask,rhendric/homebrew-cask,ahundt/homebrew-cask,ajbw/homebrew-cask,uetchy/homebrew-cask,mikem/homebrew-cask,mahori/homebrew-cask,alexg0/homebrew-cask,tan9/homebrew-cask,huanzhang/homebrew-cask,jalaziz/homebrew-cask,miccal/homebrew-cask,jbeagley52/homebrew-cask,moonboots/homebrew-cask,hyuna917/homebrew-cask,tjt263/homebrew-cask,farmerchris/homebrew-cask,FranklinChen/homebrew-cask,leipert/homebrew-cask,riyad/homebrew-cask,vitorgalvao/homebrew-cask,andyli/homebrew-cask,imgarylai/homebrew-cask,JacopKane/homebrew-cask,jalaziz/homebrew-cask,MatzFan/homebrew-cask,jppelteret/homebrew-cask,ptb/homebrew-cask,supriyantomaftuh/homebrew-cask,jpodlech/homebrew-cask,doits/homebrew-cask,ksylvan/homebrew-cask,vmrob/homebrew-cask,tsparber/homebrew-cask,shanonvl/homebrew-cask,anbotero/homebrew-cask,bendoerr/homebrew-cask,wickedsp1d3r/homebrew-cask,guylabs/homebrew-cask,bgandon/homebrew-cask,Gasol/homebrew-cask,ksylvan/homebrew-cask,stigkj/homebrew-caskroom-cask,ohammersmith/homebrew-cask,FinalDes/homebrew-cask,neil-ca-moore/homebrew-cask,fanquake/homebrew-cask,huanzhang/homebrew-cask,corbt/homebrew-cask,0rax/homebrew-cask,bsiddiqui/homebrew-cask,haha1903/homebrew-cask,nathanielvarona/homebrew-cask,reitermarkus/homebrew-cask,jamesmlees/homebrew-cask,3van/homebrew-cask,cohei/homebrew-cask,crmne/homebrew-cask,rajiv/homebrew-cask,cobyism/homebrew-cask,nicolas-brousse/homebrew-cask,deiga/homebrew-cask,ianyh/homebrew-cask,fly19890211/homebrew-cask,nathanielvarona/homebrew-cask,johndbritton/homebrew-cask,claui/homebrew-cask,codeurge/homebrew-cask,adelinofaria/homebrew-cask,crzrcn/homebrew-cask,rcuza/homebrew-cask,shonjir/homebrew-cask,royalwang/homebrew-cask,johnjelinek/homebrew-cask,mchlrmrz/homebrew-cask,mattrobenolt/homebrew-cask,seanorama/homebrew-cask,stevenmaguire/homebrew-cask,devmynd/homebrew-cask,drostron/homebrew-cask,MichaelPei/homebrew-cask,xakraz/homebrew-cask,hanxue/caskroom,gyndav/homebrew-cask,winkelsdorf/homebrew-cask,Bombenleger/homebrew-cask,Dremora/homebrew-cask,ericbn/homebrew-cask,m3nu/homebrew-cask,schneidmaster/homebrew-cask,bchatard/homebrew-cask,gguillotte/homebrew-cask,maxnordlund/homebrew-cask,iamso/homebrew-cask,mattfelsen/homebrew-cask,kTitan/homebrew-cask,dustinblackman/homebrew-cask,mjdescy/homebrew-cask,mrmachine/homebrew-cask,mindriot101/homebrew-cask,n8henrie/homebrew-cask,wayou/homebrew-cask,greg5green/homebrew-cask,linc01n/homebrew-cask,xcezx/homebrew-cask,colindunn/homebrew-cask,yurikoles/homebrew-cask,vuquoctuan/homebrew-cask,n8henrie/homebrew-cask,seanzxx/homebrew-cask,theoriginalgri/homebrew-cask,renaudguerin/homebrew-cask,cfillion/homebrew-cask,neverfox/homebrew-cask,illusionfield/homebrew-cask,exherb/homebrew-cask,psibre/homebrew-cask,paulbreslin/homebrew-cask,samdoran/homebrew-cask,mishari/homebrew-cask,jeroenseegers/homebrew-cask,JoelLarson/homebrew-cask,kei-yamazaki/homebrew-cask,puffdad/homebrew-cask,d/homebrew-cask,xyb/homebrew-cask,koenrh/homebrew-cask,norio-nomura/homebrew-cask,kirikiriyamama/homebrew-cask,rcuza/homebrew-cask,pinut/homebrew-cask,kirikiriyamama/homebrew-cask,a1russell/homebrew-cask,wizonesolutions/homebrew-cask,haha1903/homebrew-cask,RickWong/homebrew-cask,kingthorin/homebrew-cask,xcezx/homebrew-cask,vmrob/homebrew-cask,mwilmer/homebrew-cask,lolgear/homebrew-cask,muan/homebrew-cask,ebraminio/homebrew-cask,vin047/homebrew-cask,dspeckhard/homebrew-cask,feniix/homebrew-cask,malford/homebrew-cask,remko/homebrew-cask,joschi/homebrew-cask,danielgomezrico/homebrew-cask,aki77/homebrew-cask,a-x-/homebrew-cask,FranklinChen/homebrew-cask,astorije/homebrew-cask,reitermarkus/homebrew-cask,mazehall/homebrew-cask,BenjaminHCCarr/homebrew-cask,Labutin/homebrew-cask,buo/homebrew-cask,guerrero/homebrew-cask,cedwardsmedia/homebrew-cask,pkq/homebrew-cask,mwek/homebrew-cask,scribblemaniac/homebrew-cask,optikfluffel/homebrew-cask,sanchezm/homebrew-cask,alebcay/homebrew-cask,ywfwj2008/homebrew-cask,mingzhi22/homebrew-cask,dictcp/homebrew-cask,renaudguerin/homebrew-cask,skatsuta/homebrew-cask,miku/homebrew-cask,KosherBacon/homebrew-cask,patresi/homebrew-cask,coeligena/homebrew-customized,ebraminio/homebrew-cask,hanxue/caskroom,a1russell/homebrew-cask,reitermarkus/homebrew-cask,johntrandall/homebrew-cask,samshadwell/homebrew-cask,moogar0880/homebrew-cask,skyyuan/homebrew-cask,yuhki50/homebrew-cask,andrewdisley/homebrew-cask,blainesch/homebrew-cask,spruceb/homebrew-cask,hellosky806/homebrew-cask,adrianchia/homebrew-cask,tjnycum/homebrew-cask,rajiv/homebrew-cask,jedahan/homebrew-cask,nathansgreen/homebrew-cask,kteru/homebrew-cask,codeurge/homebrew-cask,andyli/homebrew-cask,chrisRidgers/homebrew-cask,kesara/homebrew-cask,mingzhi22/homebrew-cask,rogeriopradoj/homebrew-cask,linc01n/homebrew-cask,kronicd/homebrew-cask,blainesch/homebrew-cask,bcaceiro/homebrew-cask,hyuna917/homebrew-cask,cblecker/homebrew-cask,3van/homebrew-cask,kei-yamazaki/homebrew-cask,mathbunnyru/homebrew-cask,thii/homebrew-cask,boecko/homebrew-cask,yutarody/homebrew-cask,rickychilcott/homebrew-cask,malob/homebrew-cask,MichaelPei/homebrew-cask,akiomik/homebrew-cask,aktau/homebrew-cask,dictcp/homebrew-cask,gerrypower/homebrew-cask,timsutton/homebrew-cask,johnjelinek/homebrew-cask,wuman/homebrew-cask,caskroom/homebrew-cask,Ibuprofen/homebrew-cask,dlovitch/homebrew-cask,rubenerd/homebrew-cask,jgarber623/homebrew-cask,lauantai/homebrew-cask,FinalDes/homebrew-cask,scribblemaniac/homebrew-cask,boydj/homebrew-cask,samnung/homebrew-cask,joschi/homebrew-cask,andrewdisley/homebrew-cask,singingwolfboy/homebrew-cask,kkdd/homebrew-cask,BenjaminHCCarr/homebrew-cask,bosr/homebrew-cask,dunn/homebrew-cask,shoichiaizawa/homebrew-cask,shishi/homebrew-cask,coneman/homebrew-cask,jppelteret/homebrew-cask,atsuyim/homebrew-cask,gyndav/homebrew-cask,MoOx/homebrew-cask,zerrot/homebrew-cask,zmwangx/homebrew-cask,kuno/homebrew-cask,githubutilities/homebrew-cask,katoquro/homebrew-cask,MerelyAPseudonym/homebrew-cask,caskroom/homebrew-cask,blogabe/homebrew-cask,gyugyu/homebrew-cask,johnste/homebrew-cask,rogeriopradoj/homebrew-cask,fkrone/homebrew-cask,kamilboratynski/homebrew-cask,nightscape/homebrew-cask,seanorama/homebrew-cask,MisumiRize/homebrew-cask,buo/homebrew-cask,zchee/homebrew-cask,vigosan/homebrew-cask,neverfox/homebrew-cask,ywfwj2008/homebrew-cask,elnappo/homebrew-cask,ldong/homebrew-cask,katoquro/homebrew-cask,helloIAmPau/homebrew-cask,alexg0/homebrew-cask,diogodamiani/homebrew-cask,BahtiyarB/homebrew-cask,optikfluffel/homebrew-cask,arranubels/homebrew-cask,lantrix/homebrew-cask,wickles/homebrew-cask,ahvigil/homebrew-cask,bcomnes/homebrew-cask,yuhki50/homebrew-cask,kolomiichenko/homebrew-cask,jeanregisser/homebrew-cask,FredLackeyOfficial/homebrew-cask,jbeagley52/homebrew-cask,hvisage/homebrew-cask,ajbw/homebrew-cask,Keloran/homebrew-cask,jpodlech/homebrew-cask,nicolas-brousse/homebrew-cask,timsutton/homebrew-cask,wizonesolutions/homebrew-cask,jawshooah/homebrew-cask,leipert/homebrew-cask,jrwesolo/homebrew-cask,toonetown/homebrew-cask,kevyau/homebrew-cask,faun/homebrew-cask,miccal/homebrew-cask,asins/homebrew-cask,tolbkni/homebrew-cask,santoshsahoo/homebrew-cask,kevyau/homebrew-cask,hvisage/homebrew-cask,asbachb/homebrew-cask,tmoreira2020/homebrew,MisumiRize/homebrew-cask,gmkey/homebrew-cask,stigkj/homebrew-caskroom-cask,markthetech/homebrew-cask,sosedoff/homebrew-cask,SentinelWarren/homebrew-cask,kievechua/homebrew-cask,jayshao/homebrew-cask,taherio/homebrew-cask,MicTech/homebrew-cask,samnung/homebrew-cask,gwaldo/homebrew-cask,CameronGarrett/homebrew-cask,fkrone/homebrew-cask,mokagio/homebrew-cask,My2ndAngelic/homebrew-cask,neverfox/homebrew-cask,onlynone/homebrew-cask,yumitsu/homebrew-cask,stevehedrick/homebrew-cask,mjdescy/homebrew-cask,paour/homebrew-cask,wickles/homebrew-cask,lukasbestle/homebrew-cask,iAmGhost/homebrew-cask,af/homebrew-cask,wesen/homebrew-cask,lumaxis/homebrew-cask,amatos/homebrew-cask,mgryszko/homebrew-cask,boydj/homebrew-cask,sirodoht/homebrew-cask,qnm/homebrew-cask,6uclz1/homebrew-cask,vigosan/homebrew-cask,jeroenj/homebrew-cask,enriclluelles/homebrew-cask,nshemonsky/homebrew-cask,lolgear/homebrew-cask,mjgardner/homebrew-cask,antogg/homebrew-cask,crzrcn/homebrew-cask,winkelsdorf/homebrew-cask,qbmiller/homebrew-cask,perfide/homebrew-cask,fwiesel/homebrew-cask,ftiff/homebrew-cask,Fedalto/homebrew-cask,gibsjose/homebrew-cask,qbmiller/homebrew-cask,bdhess/homebrew-cask,Amorymeltzer/homebrew-cask,tangestani/homebrew-cask,gabrielizaias/homebrew-cask,adelinofaria/homebrew-cask,lucasmezencio/homebrew-cask,mwean/homebrew-cask,chrisfinazzo/homebrew-cask,rajiv/homebrew-cask,wickedsp1d3r/homebrew-cask,tolbkni/homebrew-cask,squid314/homebrew-cask,githubutilities/homebrew-cask,lifepillar/homebrew-cask,tan9/homebrew-cask,alebcay/homebrew-cask,williamboman/homebrew-cask,epardee/homebrew-cask,nathanielvarona/homebrew-cask,jonathanwiesel/homebrew-cask,guerrero/homebrew-cask,gerrymiller/homebrew-cask,dustinblackman/homebrew-cask,unasuke/homebrew-cask,gilesdring/homebrew-cask,MerelyAPseudonym/homebrew-cask,andrewdisley/homebrew-cask,RickWong/homebrew-cask,lukeadams/homebrew-cask,amatos/homebrew-cask,afdnlw/homebrew-cask,albertico/homebrew-cask,slnovak/homebrew-cask,MircoT/homebrew-cask,usami-k/homebrew-cask,otaran/homebrew-cask,napaxton/homebrew-cask,gerrypower/homebrew-cask,kiliankoe/homebrew-cask,y00rb/homebrew-cask,coeligena/homebrew-customized,lcasey001/homebrew-cask,remko/homebrew-cask,yurrriq/homebrew-cask,larseggert/homebrew-cask,pinut/homebrew-cask,ericbn/homebrew-cask,jangalinski/homebrew-cask,nathancahill/homebrew-cask,wmorin/homebrew-cask,alexg0/homebrew-cask,danielbayley/homebrew-cask,sscotth/homebrew-cask,muan/homebrew-cask,taherio/homebrew-cask,joshka/homebrew-cask,pacav69/homebrew-cask,JacopKane/homebrew-cask,kesara/homebrew-cask,fazo96/homebrew-cask,Ephemera/homebrew-cask,coneman/homebrew-cask,xtian/homebrew-cask,tmoreira2020/homebrew,rickychilcott/homebrew-cask,lukasbestle/homebrew-cask,xight/homebrew-cask,tangestani/homebrew-cask,markhuber/homebrew-cask,moonboots/homebrew-cask,fly19890211/homebrew-cask,janlugt/homebrew-cask,unasuke/homebrew-cask,tedbundyjr/homebrew-cask,victorpopkov/homebrew-cask,mazehall/homebrew-cask,johndbritton/homebrew-cask,sebcode/homebrew-cask,xyb/homebrew-cask,chino/homebrew-cask,hanxue/caskroom,inz/homebrew-cask,victorpopkov/homebrew-cask,zhuzihhhh/homebrew-cask,paour/homebrew-cask,fharbe/homebrew-cask,cohei/homebrew-cask,tarwich/homebrew-cask,0xadada/homebrew-cask,axodys/homebrew-cask,chadcatlett/caskroom-homebrew-cask,squid314/homebrew-cask,nshemonsky/homebrew-cask,robbiethegeek/homebrew-cask,toonetown/homebrew-cask,dcondrey/homebrew-cask,illusionfield/homebrew-cask,RogerThiede/homebrew-cask,moimikey/homebrew-cask,kpearson/homebrew-cask,chrisfinazzo/homebrew-cask,sanyer/homebrew-cask,scw/homebrew-cask,mattrobenolt/homebrew-cask,zmwangx/homebrew-cask,puffdad/homebrew-cask,barravi/homebrew-cask,mwean/homebrew-cask,pablote/homebrew-cask,My2ndAngelic/homebrew-cask,uetchy/homebrew-cask,mchlrmrz/homebrew-cask,jmeridth/homebrew-cask,crmne/homebrew-cask,astorije/homebrew-cask,frapposelli/homebrew-cask,a1russell/homebrew-cask,ddm/homebrew-cask,scottsuch/homebrew-cask,moogar0880/homebrew-cask,spruceb/homebrew-cask,sjackman/homebrew-cask,joschi/homebrew-cask,okket/homebrew-cask,zerrot/homebrew-cask,hovancik/homebrew-cask,gurghet/homebrew-cask,mahori/homebrew-cask,mariusbutuc/homebrew-cask,farmerchris/homebrew-cask,MoOx/homebrew-cask,stonehippo/homebrew-cask,johan/homebrew-cask,wayou/homebrew-cask,shonjir/homebrew-cask,gurghet/homebrew-cask,gerrymiller/homebrew-cask,danielgomezrico/homebrew-cask,inz/homebrew-cask,diogodamiani/homebrew-cask,mkozjak/homebrew-cask,zchee/homebrew-cask,bric3/homebrew-cask,y00rb/homebrew-cask,sgnh/homebrew-cask,alebcay/homebrew-cask,elyscape/homebrew-cask,royalwang/homebrew-cask,BahtiyarB/homebrew-cask,dunn/homebrew-cask,arronmabrey/homebrew-cask,13k/homebrew-cask,mattrobenolt/homebrew-cask,arronmabrey/homebrew-cask,wastrachan/homebrew-cask,mikem/homebrew-cask,thehunmonkgroup/homebrew-cask,ninjahoahong/homebrew-cask,diguage/homebrew-cask,lalyos/homebrew-cask,xight/homebrew-cask,ayohrling/homebrew-cask,claui/homebrew-cask,kTitan/homebrew-cask,cedwardsmedia/homebrew-cask,retbrown/homebrew-cask,retbrown/homebrew-cask,adriweb/homebrew-cask,ptb/homebrew-cask,nrlquaker/homebrew-cask,djakarta-trap/homebrew-myCask,Ketouem/homebrew-cask,mahori/homebrew-cask,adrianchia/homebrew-cask,dieterdemeyer/homebrew-cask,decrement/homebrew-cask,goxberry/homebrew-cask,dwkns/homebrew-cask,johntrandall/homebrew-cask,BenjaminHCCarr/homebrew-cask,pkq/homebrew-cask,retrography/homebrew-cask,leonmachadowilcox/homebrew-cask,ldong/homebrew-cask,patresi/homebrew-cask,jen20/homebrew-cask,lukeadams/homebrew-cask,LaurentFough/homebrew-cask,gilesdring/homebrew-cask,kamilboratynski/homebrew-cask,cblecker/homebrew-cask,dwihn0r/homebrew-cask,ericbn/homebrew-cask,kryhear/homebrew-cask,otaran/homebrew-cask,wesen/homebrew-cask,lvicentesanchez/homebrew-cask,ahundt/homebrew-cask,paour/homebrew-cask,markthetech/homebrew-cask,mauricerkelly/homebrew-cask,malob/homebrew-cask,johan/homebrew-cask,mfpierre/homebrew-cask,jasmas/homebrew-cask,bchatard/homebrew-cask,kostasdizas/homebrew-cask,dcondrey/homebrew-cask,fharbe/homebrew-cask,greg5green/homebrew-cask,a-x-/homebrew-cask,epmatsw/homebrew-cask,pacav69/homebrew-cask,usami-k/homebrew-cask,stephenwade/homebrew-cask,nysthee/homebrew-cask,scottsuch/homebrew-cask,dieterdemeyer/homebrew-cask,jonathanwiesel/homebrew-cask,klane/homebrew-cask,mchlrmrz/homebrew-cask,adriweb/homebrew-cask,bcomnes/homebrew-cask,brianshumate/homebrew-cask,miguelfrde/homebrew-cask,FredLackeyOfficial/homebrew-cask,andersonba/homebrew-cask,julionc/homebrew-cask,bric3/homebrew-cask,onlynone/homebrew-cask,JoelLarson/homebrew-cask,ctrevino/homebrew-cask,thomanq/homebrew-cask,nickpellant/homebrew-cask,yurikoles/homebrew-cask,troyxmccall/homebrew-cask,flaviocamilo/homebrew-cask,miku/homebrew-cask,jhowtan/homebrew-cask,sgnh/homebrew-cask,gibsjose/homebrew-cask,xtian/homebrew-cask,markhuber/homebrew-cask,kassi/homebrew-cask,mauricerkelly/homebrew-cask,ninjahoahong/homebrew-cask,daften/homebrew-cask,deanmorin/homebrew-cask,josa42/homebrew-cask,feniix/homebrew-cask,Ngrd/homebrew-cask,sebcode/homebrew-cask,michelegera/homebrew-cask,anbotero/homebrew-cask,nrlquaker/homebrew-cask,lumaxis/homebrew-cask,tjnycum/homebrew-cask,mattfelsen/homebrew-cask,jconley/homebrew-cask,wmorin/homebrew-cask,flaviocamilo/homebrew-cask,iamso/homebrew-cask,ksato9700/homebrew-cask,gwaldo/homebrew-cask,tedski/homebrew-cask,af/homebrew-cask,fanquake/homebrew-cask,jgarber623/homebrew-cask,winkelsdorf/homebrew-cask,giannitm/homebrew-cask,wKovacs64/homebrew-cask,stephenwade/homebrew-cask,hakamadare/homebrew-cask,m3nu/homebrew-cask,cobyism/homebrew-cask,norio-nomura/homebrew-cask,kkdd/homebrew-cask,nysthee/homebrew-cask,elyscape/homebrew-cask,nrlquaker/homebrew-cask,joshka/homebrew-cask,yutarody/homebrew-cask,shanonvl/homebrew-cask,bsiddiqui/homebrew-cask,mwek/homebrew-cask,scribblemaniac/homebrew-cask,m3nu/homebrew-cask,casidiablo/homebrew-cask,barravi/homebrew-cask,JosephViolago/homebrew-cask,mindriot101/homebrew-cask,christer155/homebrew-cask,skatsuta/homebrew-cask,jmeridth/homebrew-cask,wKovacs64/homebrew-cask,morganestes/homebrew-cask,singingwolfboy/homebrew-cask,malford/homebrew-cask,ahvigil/homebrew-cask,Whoaa512/homebrew-cask,JikkuJose/homebrew-cask,cprecioso/homebrew-cask,chrisfinazzo/homebrew-cask,bcaceiro/homebrew-cask,jacobdam/homebrew-cask,mrmachine/homebrew-cask,bdhess/homebrew-cask,syscrusher/homebrew-cask,joshka/homebrew-cask,fazo96/homebrew-cask,stonehippo/homebrew-cask,julionc/homebrew-cask,cclauss/homebrew-cask,zorosteven/homebrew-cask,lcasey001/homebrew-cask,boecko/homebrew-cask,dlovitch/homebrew-cask,andersonba/homebrew-cask,scw/homebrew-cask,sohtsuka/homebrew-cask,vuquoctuan/homebrew-cask,goxberry/homebrew-cask,michelegera/homebrew-cask,kuno/homebrew-cask,underyx/homebrew-cask,schneidmaster/homebrew-cask,decrement/homebrew-cask,JikkuJose/homebrew-cask,cliffcotino/homebrew-cask,axodys/homebrew-cask,retrography/homebrew-cask,tranc99/homebrew-cask,mhubig/homebrew-cask,bendoerr/homebrew-cask,JacopKane/homebrew-cask,jrwesolo/homebrew-cask,williamboman/homebrew-cask,sparrc/homebrew-cask,Cottser/homebrew-cask,hristozov/homebrew-cask,feigaochn/homebrew-cask,riyad/homebrew-cask,JosephViolago/homebrew-cask,iAmGhost/homebrew-cask,miguelfrde/homebrew-cask,gabrielizaias/homebrew-cask,forevergenin/homebrew-cask,drostron/homebrew-cask,asins/homebrew-cask,lucasmezencio/homebrew-cask,forevergenin/homebrew-cask,lvicentesanchez/homebrew-cask,robertgzr/homebrew-cask,kingthorin/homebrew-cask,renard/homebrew-cask,ddm/homebrew-cask,santoshsahoo/homebrew-cask,sanchezm/homebrew-cask,kassi/homebrew-cask,Nitecon/homebrew-cask,mathbunnyru/homebrew-cask,esebastian/homebrew-cask,koenrh/homebrew-cask,6uclz1/homebrew-cask,jeroenj/homebrew-cask,colindunn/homebrew-cask,howie/homebrew-cask,deiga/homebrew-cask,bric3/homebrew-cask,gguillotte/homebrew-cask,elnappo/homebrew-cask,slnovak/homebrew-cask,howie/homebrew-cask,inta/homebrew-cask,jiashuw/homebrew-cask,Whoaa512/homebrew-cask,underyx/homebrew-cask,jconley/homebrew-cask,n0ts/homebrew-cask,Labutin/homebrew-cask,tangestani/homebrew-cask,claui/homebrew-cask,diguage/homebrew-cask,sscotth/homebrew-cask,cclauss/homebrew-cask,Bombenleger/homebrew-cask,Ibuprofen/homebrew-cask,13k/homebrew-cask,paulombcosta/homebrew-cask,thomanq/homebrew-cask,sanyer/homebrew-cask,guylabs/homebrew-cask,faun/homebrew-cask,mkozjak/homebrew-cask,robertgzr/homebrew-cask,kteru/homebrew-cask,jeroenseegers/homebrew-cask,MircoT/homebrew-cask,kryhear/homebrew-cask,ohammersmith/homebrew-cask,moimikey/homebrew-cask,devmynd/homebrew-cask,stephenwade/homebrew-cask,nivanchikov/homebrew-cask,nathancahill/homebrew-cask,chino/homebrew-cask,AnastasiaSulyagina/homebrew-cask,RJHsiao/homebrew-cask,kostasdizas/homebrew-cask,afdnlw/homebrew-cask,chuanxd/homebrew-cask,stevenmaguire/homebrew-cask,janlugt/homebrew-cask,RogerThiede/homebrew-cask,ctrevino/homebrew-cask,hakamadare/homebrew-cask,rogeriopradoj/homebrew-cask,klane/homebrew-cask,bkono/homebrew-cask,fwiesel/homebrew-cask,Nitecon/homebrew-cask,Gasol/homebrew-cask,MicTech/homebrew-cask,moimikey/homebrew-cask,singingwolfboy/homebrew-cask,qnm/homebrew-cask,aki77/homebrew-cask,kongslund/homebrew-cask,shishi/homebrew-cask,sohtsuka/homebrew-cask,KosherBacon/homebrew-cask,Amorymeltzer/homebrew-cask,mgryszko/homebrew-cask,samshadwell/homebrew-cask,dvdoliveira/homebrew-cask,jalaziz/homebrew-cask,mhubig/homebrew-cask,deanmorin/homebrew-cask,SamiHiltunen/homebrew-cask,RJHsiao/homebrew-cask,enriclluelles/homebrew-cask,jaredsampson/homebrew-cask,englishm/homebrew-cask,askl56/homebrew-cask,hackhandslabs/homebrew-cask,kesara/homebrew-cask,pablote/homebrew-cask,blogabe/homebrew-cask,aktau/homebrew-cask,MatzFan/homebrew-cask,wmorin/homebrew-cask,danielbayley/homebrew-cask,colindean/homebrew-cask,Ngrd/homebrew-cask,josa42/homebrew-cask,scottsuch/homebrew-cask,zorosteven/homebrew-cask,Dremora/homebrew-cask,inta/homebrew-cask,nivanchikov/homebrew-cask,Ephemera/homebrew-cask,daften/homebrew-cask,cblecker/homebrew-cask,djakarta-trap/homebrew-myCask,jasmas/homebrew-cask,vitorgalvao/homebrew-cask,bosr/homebrew-cask,Hywan/homebrew-cask,dwihn0r/homebrew-cask,dwkns/homebrew-cask,slack4u/homebrew-cask,deiga/homebrew-cask,epmatsw/homebrew-cask,jedahan/homebrew-cask,jiashuw/homebrew-cask,seanzxx/homebrew-cask,JosephViolago/homebrew-cask,samdoran/homebrew-cask,psibre/homebrew-cask,Ephemera/homebrew-cask,sjackman/homebrew-cask,gyndav/homebrew-cask,mjgardner/homebrew-cask,jayshao/homebrew-cask,AnastasiaSulyagina/homebrew-cask,epardee/homebrew-cask,jen20/homebrew-cask,jacobbednarz/homebrew-cask,neil-ca-moore/homebrew-cask,d/homebrew-cask,stevehedrick/homebrew-cask,slack4u/homebrew-cask,cobyism/homebrew-cask | ruby | ## Code Before:
cask :v1 => 'bleep' do
version :latest
sha256 :no_check
# utorrent.com is the official download host per the vendor homepage
url 'https://download-new.utorrent.com/endpoint/bleep/os/osx/track/stable/'
name 'Bleep'
homepage 'http://labs.bittorrent.com/bleep/'
license :gratis
app 'Bleep.app'
end
## Instruction:
Update Bleep.app homepage, add vendor and zap ~/Library files
## Code After:
cask :v1 => 'bleep' do
version :latest
sha256 :no_check
# utorrent.com is the official download host per the vendor homepage
url 'https://download-new.utorrent.com/endpoint/bleep/os/osx/track/stable/'
name 'Bleep'
homepage 'http://www.bleep.pm/'
license :gratis
tags :vendor => 'BitTorrent'
app 'Bleep.app'
zap :delete => [
'~/Library/Application Support/Bleep',
'~/Library/Caches/com.bittorrent.bleep.osx',
'~/Library/Preferences/com.bittorrent.bleep.osx.plist',
'~/Library/Saved Application State/com.bittorrent.bleep.osx.savedState',
]
end
| cask :v1 => 'bleep' do
version :latest
sha256 :no_check
# utorrent.com is the official download host per the vendor homepage
url 'https://download-new.utorrent.com/endpoint/bleep/os/osx/track/stable/'
name 'Bleep'
- homepage 'http://labs.bittorrent.com/bleep/'
+ homepage 'http://www.bleep.pm/'
license :gratis
+ tags :vendor => 'BitTorrent'
app 'Bleep.app'
+
+ zap :delete => [
+ '~/Library/Application Support/Bleep',
+ '~/Library/Caches/com.bittorrent.bleep.osx',
+ '~/Library/Preferences/com.bittorrent.bleep.osx.plist',
+ '~/Library/Saved Application State/com.bittorrent.bleep.osx.savedState',
+ ]
end | 10 | 0.833333 | 9 | 1 |
68478b532e5ba2554401ef11477088f9e51e9017 | spec/peg_spec.rb | spec/peg_spec.rb | require_relative '../peg'
require_relative 'spec_helper'
describe Peg do
let(:peg) { Peg.new("red") }
describe '#color' do
it 'returns the color of the peg' do
expect(peg.color).to eq "red"
end
end
end
| require_relative '../peg'
require_relative 'spec_helper'
describe Peg do
let(:peg) { Peg.new("red") }
describe '#color' do
it 'returns the color of the peg' do
expect(peg.color).to eq "red"
end
end
describe'#==' do
let(:peg1) { Peg.new("yellow") }
let(:peg2) { Peg.new("yellow") }
let(:peg3) { Peg.new("orange") }
it 'returns false if they are not the same' do
expect(peg2 == peg3).to be false
end
it 'returns true if they are not the same' do
expect(peg1 == peg2).to be true
end
end
end
| Add test for peg equality method | Add test for peg equality method
| Ruby | mit | misternu/mastermind | ruby | ## Code Before:
require_relative '../peg'
require_relative 'spec_helper'
describe Peg do
let(:peg) { Peg.new("red") }
describe '#color' do
it 'returns the color of the peg' do
expect(peg.color).to eq "red"
end
end
end
## Instruction:
Add test for peg equality method
## Code After:
require_relative '../peg'
require_relative 'spec_helper'
describe Peg do
let(:peg) { Peg.new("red") }
describe '#color' do
it 'returns the color of the peg' do
expect(peg.color).to eq "red"
end
end
describe'#==' do
let(:peg1) { Peg.new("yellow") }
let(:peg2) { Peg.new("yellow") }
let(:peg3) { Peg.new("orange") }
it 'returns false if they are not the same' do
expect(peg2 == peg3).to be false
end
it 'returns true if they are not the same' do
expect(peg1 == peg2).to be true
end
end
end
| require_relative '../peg'
require_relative 'spec_helper'
describe Peg do
let(:peg) { Peg.new("red") }
describe '#color' do
it 'returns the color of the peg' do
expect(peg.color).to eq "red"
end
end
+
+ describe'#==' do
+ let(:peg1) { Peg.new("yellow") }
+ let(:peg2) { Peg.new("yellow") }
+ let(:peg3) { Peg.new("orange") }
+ it 'returns false if they are not the same' do
+ expect(peg2 == peg3).to be false
+ end
+ it 'returns true if they are not the same' do
+ expect(peg1 == peg2).to be true
+ end
+ end
end | 12 | 1.090909 | 12 | 0 |
9631b8d5f7c8778d73a046d85f15f8f331f0deb5 | dvs_renderer/CMakeLists.txt | dvs_renderer/CMakeLists.txt | cmake_minimum_required(VERSION 2.8.3)
project(dvs_renderer)
find_package(catkin_simple REQUIRED)
catkin_simple()
SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11 -O3")
find_package(OpenCV REQUIRED)
# make the executable
cs_add_executable(dvs_renderer
src/image_tracking.cpp
src/renderer.cpp
src/renderer_node.cpp
)
# make the nodelet into a library
cs_add_library(dvs_renderer_nodelet
src/image_tracking.cpp
src/renderer_nodelet.cpp
src/renderer.cpp
)
# link the executable to the necesarry libs
target_link_libraries(dvs_renderer
${catkin_LIBRARIES}
${OpenCV_LIBRARIES}
)
target_link_libraries(dvs_renderer_nodelet
${catkin_LIBRARIES}
${OpenCV_LIBRARIES}
)
cs_install()
install(
TARGETS dvs_renderer
RUNTIME DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION}
)
# Install other support files for installation
install(FILES dvs_renderer_nodelet.xml launch/nodelet_stereo.launch launch/nodelet_mono.launch
DESTINATION ${CATKIN_PACKAGE_SHARE_DESTINATION}
)
| cmake_minimum_required(VERSION 2.8.3)
project(dvs_renderer)
find_package(catkin_simple REQUIRED)
catkin_simple()
SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11 -O3")
find_package(OpenCV REQUIRED)
# make the executable
cs_add_executable(dvs_renderer
src/image_tracking.cpp
src/renderer.cpp
src/renderer_node.cpp
)
# make the nodelet into a library
cs_add_library(dvs_renderer_nodelet
src/image_tracking.cpp
src/renderer_nodelet.cpp
src/renderer.cpp
)
# link the executable to the necesarry libs
target_link_libraries(dvs_renderer
${catkin_LIBRARIES}
${OpenCV_LIBRARIES}
)
target_link_libraries(dvs_renderer_nodelet
${catkin_LIBRARIES}
${OpenCV_LIBRARIES}
)
install(
TARGETS dvs_renderer
RUNTIME DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION}
)
# Install other support files for installation
install(FILES dvs_renderer_nodelet.xml launch/nodelet_stereo.launch launch/nodelet_mono.launch
DESTINATION ${CATKIN_PACKAGE_SHARE_DESTINATION}
)
cs_install()
cs_export()
| Add cs_export to fully install the package dvs_renderer | Add cs_export to fully install the package dvs_renderer
| Text | mit | uzh-rpg/rpg_dvs_ros,uzh-rpg/rpg_dvs_ros,uzh-rpg/rpg_dvs_ros | text | ## Code Before:
cmake_minimum_required(VERSION 2.8.3)
project(dvs_renderer)
find_package(catkin_simple REQUIRED)
catkin_simple()
SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11 -O3")
find_package(OpenCV REQUIRED)
# make the executable
cs_add_executable(dvs_renderer
src/image_tracking.cpp
src/renderer.cpp
src/renderer_node.cpp
)
# make the nodelet into a library
cs_add_library(dvs_renderer_nodelet
src/image_tracking.cpp
src/renderer_nodelet.cpp
src/renderer.cpp
)
# link the executable to the necesarry libs
target_link_libraries(dvs_renderer
${catkin_LIBRARIES}
${OpenCV_LIBRARIES}
)
target_link_libraries(dvs_renderer_nodelet
${catkin_LIBRARIES}
${OpenCV_LIBRARIES}
)
cs_install()
install(
TARGETS dvs_renderer
RUNTIME DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION}
)
# Install other support files for installation
install(FILES dvs_renderer_nodelet.xml launch/nodelet_stereo.launch launch/nodelet_mono.launch
DESTINATION ${CATKIN_PACKAGE_SHARE_DESTINATION}
)
## Instruction:
Add cs_export to fully install the package dvs_renderer
## Code After:
cmake_minimum_required(VERSION 2.8.3)
project(dvs_renderer)
find_package(catkin_simple REQUIRED)
catkin_simple()
SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11 -O3")
find_package(OpenCV REQUIRED)
# make the executable
cs_add_executable(dvs_renderer
src/image_tracking.cpp
src/renderer.cpp
src/renderer_node.cpp
)
# make the nodelet into a library
cs_add_library(dvs_renderer_nodelet
src/image_tracking.cpp
src/renderer_nodelet.cpp
src/renderer.cpp
)
# link the executable to the necesarry libs
target_link_libraries(dvs_renderer
${catkin_LIBRARIES}
${OpenCV_LIBRARIES}
)
target_link_libraries(dvs_renderer_nodelet
${catkin_LIBRARIES}
${OpenCV_LIBRARIES}
)
install(
TARGETS dvs_renderer
RUNTIME DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION}
)
# Install other support files for installation
install(FILES dvs_renderer_nodelet.xml launch/nodelet_stereo.launch launch/nodelet_mono.launch
DESTINATION ${CATKIN_PACKAGE_SHARE_DESTINATION}
)
cs_install()
cs_export()
| cmake_minimum_required(VERSION 2.8.3)
project(dvs_renderer)
find_package(catkin_simple REQUIRED)
catkin_simple()
SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11 -O3")
find_package(OpenCV REQUIRED)
# make the executable
cs_add_executable(dvs_renderer
src/image_tracking.cpp
src/renderer.cpp
src/renderer_node.cpp
)
# make the nodelet into a library
cs_add_library(dvs_renderer_nodelet
src/image_tracking.cpp
src/renderer_nodelet.cpp
src/renderer.cpp
)
# link the executable to the necesarry libs
target_link_libraries(dvs_renderer
${catkin_LIBRARIES}
${OpenCV_LIBRARIES}
)
target_link_libraries(dvs_renderer_nodelet
${catkin_LIBRARIES}
${OpenCV_LIBRARIES}
)
- cs_install()
-
install(
TARGETS dvs_renderer
RUNTIME DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION}
)
# Install other support files for installation
install(FILES dvs_renderer_nodelet.xml launch/nodelet_stereo.launch launch/nodelet_mono.launch
DESTINATION ${CATKIN_PACKAGE_SHARE_DESTINATION}
)
+
+ cs_install()
+ cs_export() | 5 | 0.106383 | 3 | 2 |
09656fc5284c4715a7e009cb2b56947aa85a82fb | base/app/views/layouts/_header_dropdown_menu_sessions.html.erb | base/app/views/layouts/_header_dropdown_menu_sessions.html.erb | <% representations = current_user.represented.unshift(current_user) - [current_subject] %>
<% unless representations.empty? %>
<li>
<%= link_to t('representation.switch'), "javascript:;", :class=>"session_change" %>
<ul>
<% representations.each do |representation| %>
<li>
<%= link_to truncate_name(representation.name, :length => 15) + (content_tag(:span, representation.pending_contacts_count.to_s, :class => "switch_pending_count") if representation.pending_contacts_count > 0), { :s => representation.slug }, { :style => "background: transparent url('#{ image_path representation.logo.url(:representation)}') no-repeat left center;margin-left:2px;" } %>
</li>
<% end %>
</ul>
</li>
<% end %>
| <% representations = current_user.represented.unshift(current_user) - [current_subject] %>
<% unless representations.empty? %>
<li>
<%= link_to t('representation.switch'), "javascript:;", :class=>"session_change" %>
<ul>
<% representations.each do |representation| %>
<li>
<% pending_total = representation.mailbox.notifications.not_trashed.unread.count %>
<%= link_to truncate_name(representation.name, :length => 15) + (content_tag(:span, pending_total.to_s, :class => "switch_pending_count") if pending_total > 0), { :s => representation.slug }, { :style => "background: transparent url('#{ image_path representation.logo.url(:representation)}') no-repeat left center;margin-left:2px;" } %>
</li>
<% end %>
</ul>
</li>
<% end %>
| Change session menu to include unread notifications rather than pending contacts | Change session menu to include unread notifications rather than pending contacts
| HTML+ERB | mit | ging/social_stream,honorlin/social_stream,ging/social_stream,honorlin/social_stream,honorlin/social_stream,honorlin/social_stream,ging/social_stream | html+erb | ## Code Before:
<% representations = current_user.represented.unshift(current_user) - [current_subject] %>
<% unless representations.empty? %>
<li>
<%= link_to t('representation.switch'), "javascript:;", :class=>"session_change" %>
<ul>
<% representations.each do |representation| %>
<li>
<%= link_to truncate_name(representation.name, :length => 15) + (content_tag(:span, representation.pending_contacts_count.to_s, :class => "switch_pending_count") if representation.pending_contacts_count > 0), { :s => representation.slug }, { :style => "background: transparent url('#{ image_path representation.logo.url(:representation)}') no-repeat left center;margin-left:2px;" } %>
</li>
<% end %>
</ul>
</li>
<% end %>
## Instruction:
Change session menu to include unread notifications rather than pending contacts
## Code After:
<% representations = current_user.represented.unshift(current_user) - [current_subject] %>
<% unless representations.empty? %>
<li>
<%= link_to t('representation.switch'), "javascript:;", :class=>"session_change" %>
<ul>
<% representations.each do |representation| %>
<li>
<% pending_total = representation.mailbox.notifications.not_trashed.unread.count %>
<%= link_to truncate_name(representation.name, :length => 15) + (content_tag(:span, pending_total.to_s, :class => "switch_pending_count") if pending_total > 0), { :s => representation.slug }, { :style => "background: transparent url('#{ image_path representation.logo.url(:representation)}') no-repeat left center;margin-left:2px;" } %>
</li>
<% end %>
</ul>
</li>
<% end %>
| <% representations = current_user.represented.unshift(current_user) - [current_subject] %>
<% unless representations.empty? %>
<li>
<%= link_to t('representation.switch'), "javascript:;", :class=>"session_change" %>
<ul>
<% representations.each do |representation| %>
<li>
+ <% pending_total = representation.mailbox.notifications.not_trashed.unread.count %>
- <%= link_to truncate_name(representation.name, :length => 15) + (content_tag(:span, representation.pending_contacts_count.to_s, :class => "switch_pending_count") if representation.pending_contacts_count > 0), { :s => representation.slug }, { :style => "background: transparent url('#{ image_path representation.logo.url(:representation)}') no-repeat left center;margin-left:2px;" } %>
? --------------- ^^^^^^^^^^^^^^ --------------- ^^^^^^^^^^^^^^
+ <%= link_to truncate_name(representation.name, :length => 15) + (content_tag(:span, pending_total.to_s, :class => "switch_pending_count") if pending_total > 0), { :s => representation.slug }, { :style => "background: transparent url('#{ image_path representation.logo.url(:representation)}') no-repeat left center;margin-left:2px;" } %>
? ^^^^^ ^^^^^
</li>
<% end %>
</ul>
</li>
<% end %> | 3 | 0.230769 | 2 | 1 |
9178e4d6a8fb54c6124c192765a9ff8cc3a582c6 | docs/recipe_bridge.py | docs/recipe_bridge.py |
import time
from picraft import World, Vector, Block
world = World(ignore_errors=True)
world.say('Auto-bridge active')
last_pos = None
while True:
this_pos = world.player.pos
if last_pos is not None:
# Has the player moved more than 0.2 units in a horizontal direction?
movement = (this_pos - last_pos).replace(y=0.0)
if movement.magnitude > 0.1:
# Find the next tile they're going to step on
next_pos = (this_pos + movement.unit).floor() - Vector(y=1)
if world.blocks[next_pos] == Block('air'):
world.blocks[next_pos] = Block('diamond_block')
last_pos = this_pos
time.sleep(0.01)
|
from __future__ import unicode_literals
import time
from picraft import World, Vector, Block
from collections import deque
world = World(ignore_errors=True)
world.say('Auto-bridge active')
try:
bridge = deque()
last_pos = None
while True:
this_pos = world.player.pos
if last_pos is not None:
# Has the player moved more than 0.1 units in a horizontal direction?
movement = (this_pos - last_pos).replace(y=0.0)
if movement.magnitude > 0.1:
# Find the next tile they're going to step on
next_pos = (this_pos + movement.unit).floor() - Vector(y=1)
if world.blocks[next_pos] == Block('air'):
with world.connection.batch_start():
bridge.append(next_pos)
world.blocks[next_pos] = Block('diamond_block')
while len(bridge) > 10:
world.blocks[bridge.popleft()] = Block('air')
last_pos = this_pos
time.sleep(0.01)
except KeyboardInterrupt:
world.say('Auto-bridge deactivated')
with world.connection.batch_start():
while bridge:
world.blocks[bridge.popleft()] = Block('air')
| Update bridge recipe to limit length | Update bridge recipe to limit length
Also removes bridge at the end
| Python | bsd-3-clause | waveform80/picraft,radames/picraft | python | ## Code Before:
import time
from picraft import World, Vector, Block
world = World(ignore_errors=True)
world.say('Auto-bridge active')
last_pos = None
while True:
this_pos = world.player.pos
if last_pos is not None:
# Has the player moved more than 0.2 units in a horizontal direction?
movement = (this_pos - last_pos).replace(y=0.0)
if movement.magnitude > 0.1:
# Find the next tile they're going to step on
next_pos = (this_pos + movement.unit).floor() - Vector(y=1)
if world.blocks[next_pos] == Block('air'):
world.blocks[next_pos] = Block('diamond_block')
last_pos = this_pos
time.sleep(0.01)
## Instruction:
Update bridge recipe to limit length
Also removes bridge at the end
## Code After:
from __future__ import unicode_literals
import time
from picraft import World, Vector, Block
from collections import deque
world = World(ignore_errors=True)
world.say('Auto-bridge active')
try:
bridge = deque()
last_pos = None
while True:
this_pos = world.player.pos
if last_pos is not None:
# Has the player moved more than 0.1 units in a horizontal direction?
movement = (this_pos - last_pos).replace(y=0.0)
if movement.magnitude > 0.1:
# Find the next tile they're going to step on
next_pos = (this_pos + movement.unit).floor() - Vector(y=1)
if world.blocks[next_pos] == Block('air'):
with world.connection.batch_start():
bridge.append(next_pos)
world.blocks[next_pos] = Block('diamond_block')
while len(bridge) > 10:
world.blocks[bridge.popleft()] = Block('air')
last_pos = this_pos
time.sleep(0.01)
except KeyboardInterrupt:
world.say('Auto-bridge deactivated')
with world.connection.batch_start():
while bridge:
world.blocks[bridge.popleft()] = Block('air')
| +
+ from __future__ import unicode_literals
import time
from picraft import World, Vector, Block
+ from collections import deque
world = World(ignore_errors=True)
world.say('Auto-bridge active')
+ try:
+ bridge = deque()
+ last_pos = None
+ while True:
+ this_pos = world.player.pos
+ if last_pos is not None:
+ # Has the player moved more than 0.1 units in a horizontal direction?
+ movement = (this_pos - last_pos).replace(y=0.0)
+ if movement.magnitude > 0.1:
+ # Find the next tile they're going to step on
+ next_pos = (this_pos + movement.unit).floor() - Vector(y=1)
+ if world.blocks[next_pos] == Block('air'):
+ with world.connection.batch_start():
+ bridge.append(next_pos)
+ world.blocks[next_pos] = Block('diamond_block')
+ while len(bridge) > 10:
+ world.blocks[bridge.popleft()] = Block('air')
+ last_pos = this_pos
+ time.sleep(0.01)
+ except KeyboardInterrupt:
+ world.say('Auto-bridge deactivated')
+ with world.connection.batch_start():
+ while bridge:
+ world.blocks[bridge.popleft()] = Block('air')
- last_pos = None
- while True:
- this_pos = world.player.pos
- if last_pos is not None:
- # Has the player moved more than 0.2 units in a horizontal direction?
- movement = (this_pos - last_pos).replace(y=0.0)
- if movement.magnitude > 0.1:
- # Find the next tile they're going to step on
- next_pos = (this_pos + movement.unit).floor() - Vector(y=1)
- if world.blocks[next_pos] == Block('air'):
- world.blocks[next_pos] = Block('diamond_block')
- last_pos = this_pos
- time.sleep(0.01)
- | 41 | 1.952381 | 27 | 14 |
9bcf7ce7a6e9397797f0604440a730fb6843d4d3 | lib/tasks/panopticon.rake | lib/tasks/panopticon.rake | require 'registerable_calendar'
namespace :panopticon do
desc "Register application metadata with panopticon"
task :register => :environment do
require 'gds_api/panopticon'
logger = GdsApi::Base.logger = Logger.new(STDERR).tap { |l| l.level = Logger::INFO }
logger.info "Registering with panopticon..."
registerer = GdsApi::Panopticon::Registerer.new(owning_app: "calendars")
Dir.glob(Rails.root.join("lib/data/*.json")).each do |file|
details = RegisterableCalendar.new(file)
registerer.register(details)
end
end
end
| require 'registerable_calendar'
namespace :panopticon do
desc "Register application metadata with panopticon"
task :register => :environment do
require 'gds_api/panopticon'
logger = GdsApi::Base.logger = Logger.new(STDERR).tap { |l| l.level = Logger::INFO }
logger.info "Registering with panopticon..."
registerer = GdsApi::Panopticon::Registerer.new(
owning_app: "calendars",
kind: "answer"
)
Dir.glob(Rails.root.join("lib/data/*.json")).each do |file|
details = RegisterableCalendar.new(file)
registerer.register(details)
end
end
end
| Add a 'kind' parameter when registering calendars. | Add a 'kind' parameter when registering calendars.
Without this, they were showing up as a 'custom application', rather
than an answer.
| Ruby | mit | alphagov/calendars,ministryofjustice/calendars,alphagov/calendars,ministryofjustice/calendars,alphagov/calendars,alphagov/calendars | ruby | ## Code Before:
require 'registerable_calendar'
namespace :panopticon do
desc "Register application metadata with panopticon"
task :register => :environment do
require 'gds_api/panopticon'
logger = GdsApi::Base.logger = Logger.new(STDERR).tap { |l| l.level = Logger::INFO }
logger.info "Registering with panopticon..."
registerer = GdsApi::Panopticon::Registerer.new(owning_app: "calendars")
Dir.glob(Rails.root.join("lib/data/*.json")).each do |file|
details = RegisterableCalendar.new(file)
registerer.register(details)
end
end
end
## Instruction:
Add a 'kind' parameter when registering calendars.
Without this, they were showing up as a 'custom application', rather
than an answer.
## Code After:
require 'registerable_calendar'
namespace :panopticon do
desc "Register application metadata with panopticon"
task :register => :environment do
require 'gds_api/panopticon'
logger = GdsApi::Base.logger = Logger.new(STDERR).tap { |l| l.level = Logger::INFO }
logger.info "Registering with panopticon..."
registerer = GdsApi::Panopticon::Registerer.new(
owning_app: "calendars",
kind: "answer"
)
Dir.glob(Rails.root.join("lib/data/*.json")).each do |file|
details = RegisterableCalendar.new(file)
registerer.register(details)
end
end
end
| require 'registerable_calendar'
namespace :panopticon do
desc "Register application metadata with panopticon"
task :register => :environment do
require 'gds_api/panopticon'
logger = GdsApi::Base.logger = Logger.new(STDERR).tap { |l| l.level = Logger::INFO }
logger.info "Registering with panopticon..."
- registerer = GdsApi::Panopticon::Registerer.new(owning_app: "calendars")
? ------------------------
+ registerer = GdsApi::Panopticon::Registerer.new(
+ owning_app: "calendars",
+ kind: "answer"
+ )
Dir.glob(Rails.root.join("lib/data/*.json")).each do |file|
details = RegisterableCalendar.new(file)
registerer.register(details)
end
end
end | 5 | 0.3125 | 4 | 1 |
db6cddb70806f93ec51503a8cfb759fa9e463108 | lib/bootstrap/class.js | lib/bootstrap/class.js | var Helpers = require('../helpers');
var Builtin = require('../builtin');
// Remove module methods
Class.$.appendFeatures = null;
Class.$.initialize = function(name, superclass, fn) {
var cls = Builtin(this);
if (!fn && (superclass instanceof Function)) {
fn = superclass;
superclass = undefined;
}
if (superclass === undefined) {
superclass = SuperObject;
}
if (superclass && !superclass.kindOf(Class)) {
throw new TypeError("superclass must be a Class");
}
if (superclass) {
cls.setSuperclass(Builtin(superclass));
superclass.inherited(this);
}
$super(name, fn);
};
Class.$.inherited = function(base) {
};
Helpers.defineGetter(Class.$, 'superclass', function() {
var klass = this.directSuperclass;
while (klass && klass.kindOf(IncludedModule)) {
klass = klass.directSuperclass;
}
return klass;
});
Class.$.toString = function() {
var name = '';
var sc = Builtin(this).singletonClassObject;
if (sc) {
sc = sc.object;
if (sc.kindOf(Class) || sc.kindOf(Module)) {
name = "#<Class:" + sc.toString() + ">";
}
} else {
name = this.moduleName;
}
return name;
};
| var Helpers = require('../helpers');
var Builtin = require('../builtin');
// Remove module methods
Class.$.appendFeatures = null;
Class.$.initialize = function(name, superclass, fn) {
var cls = Builtin(this);
if (!fn && (superclass instanceof Function)) {
fn = superclass;
superclass = undefined;
}
if (superclass === undefined) {
superclass = SuperObject;
}
if (superclass && !superclass.kindOf(Class)) {
throw new TypeError("superclass must be a Class");
}
if (superclass) {
cls.setSuperclass(Builtin(superclass));
}
$super(name, fn);
if (superclass) {
superclass.inherited(this);
}
};
Class.$.inherited = function(base) {
};
Helpers.defineGetter(Class.$, 'superclass', function() {
var klass = this.directSuperclass;
while (klass && klass.kindOf(IncludedModule)) {
klass = klass.directSuperclass;
}
return klass;
});
Class.$.toString = function() {
var name = '';
var sc = Builtin(this).singletonClassObject;
if (sc) {
sc = sc.object;
if (sc.kindOf(Class) || sc.kindOf(Module)) {
name = "#<Class:" + sc.toString() + ">";
}
} else {
name = this.moduleName;
}
return name;
};
| Call module constructor before calling inherited. | Call module constructor before calling inherited.
| JavaScript | mit | pagarme/saphire,pagarme/saphire | javascript | ## Code Before:
var Helpers = require('../helpers');
var Builtin = require('../builtin');
// Remove module methods
Class.$.appendFeatures = null;
Class.$.initialize = function(name, superclass, fn) {
var cls = Builtin(this);
if (!fn && (superclass instanceof Function)) {
fn = superclass;
superclass = undefined;
}
if (superclass === undefined) {
superclass = SuperObject;
}
if (superclass && !superclass.kindOf(Class)) {
throw new TypeError("superclass must be a Class");
}
if (superclass) {
cls.setSuperclass(Builtin(superclass));
superclass.inherited(this);
}
$super(name, fn);
};
Class.$.inherited = function(base) {
};
Helpers.defineGetter(Class.$, 'superclass', function() {
var klass = this.directSuperclass;
while (klass && klass.kindOf(IncludedModule)) {
klass = klass.directSuperclass;
}
return klass;
});
Class.$.toString = function() {
var name = '';
var sc = Builtin(this).singletonClassObject;
if (sc) {
sc = sc.object;
if (sc.kindOf(Class) || sc.kindOf(Module)) {
name = "#<Class:" + sc.toString() + ">";
}
} else {
name = this.moduleName;
}
return name;
};
## Instruction:
Call module constructor before calling inherited.
## Code After:
var Helpers = require('../helpers');
var Builtin = require('../builtin');
// Remove module methods
Class.$.appendFeatures = null;
Class.$.initialize = function(name, superclass, fn) {
var cls = Builtin(this);
if (!fn && (superclass instanceof Function)) {
fn = superclass;
superclass = undefined;
}
if (superclass === undefined) {
superclass = SuperObject;
}
if (superclass && !superclass.kindOf(Class)) {
throw new TypeError("superclass must be a Class");
}
if (superclass) {
cls.setSuperclass(Builtin(superclass));
}
$super(name, fn);
if (superclass) {
superclass.inherited(this);
}
};
Class.$.inherited = function(base) {
};
Helpers.defineGetter(Class.$, 'superclass', function() {
var klass = this.directSuperclass;
while (klass && klass.kindOf(IncludedModule)) {
klass = klass.directSuperclass;
}
return klass;
});
Class.$.toString = function() {
var name = '';
var sc = Builtin(this).singletonClassObject;
if (sc) {
sc = sc.object;
if (sc.kindOf(Class) || sc.kindOf(Module)) {
name = "#<Class:" + sc.toString() + ">";
}
} else {
name = this.moduleName;
}
return name;
};
| var Helpers = require('../helpers');
var Builtin = require('../builtin');
// Remove module methods
Class.$.appendFeatures = null;
Class.$.initialize = function(name, superclass, fn) {
var cls = Builtin(this);
if (!fn && (superclass instanceof Function)) {
fn = superclass;
superclass = undefined;
}
if (superclass === undefined) {
superclass = SuperObject;
}
if (superclass && !superclass.kindOf(Class)) {
throw new TypeError("superclass must be a Class");
}
if (superclass) {
cls.setSuperclass(Builtin(superclass));
- superclass.inherited(this);
}
$super(name, fn);
+
+ if (superclass) {
+ superclass.inherited(this);
+ }
};
Class.$.inherited = function(base) {
};
Helpers.defineGetter(Class.$, 'superclass', function() {
var klass = this.directSuperclass;
while (klass && klass.kindOf(IncludedModule)) {
klass = klass.directSuperclass;
}
return klass;
});
Class.$.toString = function() {
var name = '';
var sc = Builtin(this).singletonClassObject;
if (sc) {
sc = sc.object;
if (sc.kindOf(Class) || sc.kindOf(Module)) {
name = "#<Class:" + sc.toString() + ">";
}
} else {
name = this.moduleName;
}
return name;
};
| 5 | 0.083333 | 4 | 1 |
b6c475c7e3e3148eaabc34640700deabcf09cb23 | test/issues/seajs-find/main.js | test/issues/seajs-find/main.js | define(function(require) {
var test = require('../../test')
require('./a-xx')
require('./b-xx')
test.assert(seajs.find('a-xx.js').name === 'a', seajs.find("a-xx.js"))
test.assert(seajs.find('xx')[0].name.length === 1, seajs.find("xx")[0].name)
test.assert(seajs.find('xx')[1].name.length === 1, seajs.find("xx")[1].name)
test.assert(seajs.find('xx').length === 2, seajs.find("xx").length)
test.assert(seajs.find('zz') === null, seajs.find("zz"))
test.done()
})
| define(function(require) {
var test = require('../../test')
require('./a-xx')
require('./b-xx')
test.assert(seajs.find('a-xx.js')[0].name === 'a', seajs.find("a-xx.js"))
test.assert(seajs.find('xx')[0].name.length === 1, seajs.find("xx")[0].name)
test.assert(seajs.find('xx')[1].name.length === 1, seajs.find("xx")[1].name)
test.assert(seajs.find('xx').length === 2, seajs.find("xx").length)
test.assert(seajs.find('zz').length === 0, seajs.find("zz"))
test.done()
})
| Tweak seajs.find test case for recent modification | Tweak seajs.find test case for recent modification
| JavaScript | mit | zaoli/seajs,121595113/seajs,tonny-zhang/seajs,baiduoduo/seajs,sheldonzf/seajs,MrZhengliang/seajs,kaijiemo/seajs,lovelykobe/seajs,wenber/seajs,lianggaolin/seajs,kuier/seajs,liupeng110112/seajs,treejames/seajs,uestcNaldo/seajs,lovelykobe/seajs,kuier/seajs,hbdrawn/seajs,zaoli/seajs,uestcNaldo/seajs,Gatsbyy/seajs,MrZhengliang/seajs,JeffLi1993/seajs,JeffLi1993/seajs,MrZhengliang/seajs,yern/seajs,baiduoduo/seajs,treejames/seajs,ysxlinux/seajs,lee-my/seajs,eleanors/SeaJS,seajs/seajs,yuhualingfeng/seajs,wenber/seajs,yern/seajs,lianggaolin/seajs,FrankElean/SeaJS,kuier/seajs,jishichang/seajs,LzhElite/seajs,evilemon/seajs,mosoft521/seajs,PUSEN/seajs,sheldonzf/seajs,judastree/seajs,ysxlinux/seajs,evilemon/seajs,AlvinWei1024/seajs,angelLYK/seajs,sheldonzf/seajs,JeffLi1993/seajs,moccen/seajs,liupeng110112/seajs,FrankElean/SeaJS,longze/seajs,miusuncle/seajs,twoubt/seajs,judastree/seajs,baiduoduo/seajs,jishichang/seajs,LzhElite/seajs,zaoli/seajs,uestcNaldo/seajs,Lyfme/seajs,coolyhx/seajs,coolyhx/seajs,AlvinWei1024/seajs,chinakids/seajs,tonny-zhang/seajs,zwh6611/seajs,ysxlinux/seajs,Lyfme/seajs,imcys/seajs,kaijiemo/seajs,lee-my/seajs,evilemon/seajs,zwh6611/seajs,twoubt/seajs,longze/seajs,longze/seajs,lianggaolin/seajs,mosoft521/seajs,moccen/seajs,LzhElite/seajs,tonny-zhang/seajs,jishichang/seajs,121595113/seajs,seajs/seajs,13693100472/seajs,13693100472/seajs,yuhualingfeng/seajs,miusuncle/seajs,Gatsbyy/seajs,wenber/seajs,Gatsbyy/seajs,zwh6611/seajs,twoubt/seajs,angelLYK/seajs,moccen/seajs,imcys/seajs,PUSEN/seajs,lee-my/seajs,FrankElean/SeaJS,mosoft521/seajs,kaijiemo/seajs,Lyfme/seajs,judastree/seajs,yern/seajs,coolyhx/seajs,eleanors/SeaJS,lovelykobe/seajs,imcys/seajs,AlvinWei1024/seajs,eleanors/SeaJS,hbdrawn/seajs,chinakids/seajs,treejames/seajs,PUSEN/seajs,seajs/seajs,yuhualingfeng/seajs,angelLYK/seajs,liupeng110112/seajs,miusuncle/seajs | javascript | ## Code Before:
define(function(require) {
var test = require('../../test')
require('./a-xx')
require('./b-xx')
test.assert(seajs.find('a-xx.js').name === 'a', seajs.find("a-xx.js"))
test.assert(seajs.find('xx')[0].name.length === 1, seajs.find("xx")[0].name)
test.assert(seajs.find('xx')[1].name.length === 1, seajs.find("xx")[1].name)
test.assert(seajs.find('xx').length === 2, seajs.find("xx").length)
test.assert(seajs.find('zz') === null, seajs.find("zz"))
test.done()
})
## Instruction:
Tweak seajs.find test case for recent modification
## Code After:
define(function(require) {
var test = require('../../test')
require('./a-xx')
require('./b-xx')
test.assert(seajs.find('a-xx.js')[0].name === 'a', seajs.find("a-xx.js"))
test.assert(seajs.find('xx')[0].name.length === 1, seajs.find("xx")[0].name)
test.assert(seajs.find('xx')[1].name.length === 1, seajs.find("xx")[1].name)
test.assert(seajs.find('xx').length === 2, seajs.find("xx").length)
test.assert(seajs.find('zz').length === 0, seajs.find("zz"))
test.done()
})
| define(function(require) {
var test = require('../../test')
require('./a-xx')
require('./b-xx')
- test.assert(seajs.find('a-xx.js').name === 'a', seajs.find("a-xx.js"))
+ test.assert(seajs.find('a-xx.js')[0].name === 'a', seajs.find("a-xx.js"))
? +++
test.assert(seajs.find('xx')[0].name.length === 1, seajs.find("xx")[0].name)
test.assert(seajs.find('xx')[1].name.length === 1, seajs.find("xx")[1].name)
test.assert(seajs.find('xx').length === 2, seajs.find("xx").length)
- test.assert(seajs.find('zz') === null, seajs.find("zz"))
? ^^^^
+ test.assert(seajs.find('zz').length === 0, seajs.find("zz"))
? +++++++ ^
test.done()
}) | 4 | 0.235294 | 2 | 2 |
48a96505f841317379d8122910ab1f6f7b6adeec | src/Datenknoten/LigiBundle/Entity/File.php | src/Datenknoten/LigiBundle/Entity/File.php | <?php
namespace Datenknoten\LigiBundle\Entity;
use Gedmo\Mapping\Annotation as Gedmo;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity
* @Gedmo\Uploadable(pathMethod="getDefaultPath", filenameGenerator="SHA1", allowOverwrite=true, appendNumber=true)
*/
class File
{
/**
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* @ORM\Column(name="path", type="string")
* @Gedmo\UploadableFilePath
*/
private $path;
/**
* @ORM\Column(name="name", type="string")
* @Gedmo\UploadableFileName
*/
private $name;
/**
* @ORM\Column(name="mime_type", type="string")
* @Gedmo\UploadableFileMimeType
*/
private $mimeType;
/**
* @ORM\Column(name="size", type="decimal")
* @Gedmo\UploadableFileSize
*/
private $size;
public function getDefaultPath()
{
return realpath(__DIR__ . '/../../../../media');
}
public function getId()
{
return $this->id;
}
public function getPath()
{
return $this->path;
}
public function getName()
{
return $this->name;
}
public function getMimeType()
{
return $this->mimeType;
}
} | <?php
namespace Datenknoten\LigiBundle\Entity;
use Gedmo\Mapping\Annotation as Gedmo;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity
* @Gedmo\Uploadable(pathMethod="getDefaultPath", filenameGenerator="SHA1", allowOverwrite=true, appendNumber=true)
*/
class File
{
/**
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* @ORM\Column(name="path", type="string")
* @Gedmo\UploadableFilePath
*/
private $path;
/**
* @ORM\Column(name="name", type="string")
* @Gedmo\UploadableFileName
*/
private $name;
/**
* @ORM\Column(name="mime_type", type="string")
* @Gedmo\UploadableFileMimeType
*/
private $mimeType;
/**
* @ORM\Column(name="size", type="decimal")
* @Gedmo\UploadableFileSize
*/
private $size;
public function getDefaultPath()
{
return realpath(__DIR__ . '/../../../../media');
}
public function getId()
{
return $this->id;
}
public function getPath()
{
return $this->path;
}
public function getName()
{
return $this->name;
}
public function getMimeType()
{
return $this->mimeType;
}
public function getSize()
{
return $this->size;
}
} | Add a accesor for size | Add a accesor for size
| PHP | agpl-3.0 | datenknoten/ligi,datenknoten/ligi,datenknoten/ligi | php | ## Code Before:
<?php
namespace Datenknoten\LigiBundle\Entity;
use Gedmo\Mapping\Annotation as Gedmo;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity
* @Gedmo\Uploadable(pathMethod="getDefaultPath", filenameGenerator="SHA1", allowOverwrite=true, appendNumber=true)
*/
class File
{
/**
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* @ORM\Column(name="path", type="string")
* @Gedmo\UploadableFilePath
*/
private $path;
/**
* @ORM\Column(name="name", type="string")
* @Gedmo\UploadableFileName
*/
private $name;
/**
* @ORM\Column(name="mime_type", type="string")
* @Gedmo\UploadableFileMimeType
*/
private $mimeType;
/**
* @ORM\Column(name="size", type="decimal")
* @Gedmo\UploadableFileSize
*/
private $size;
public function getDefaultPath()
{
return realpath(__DIR__ . '/../../../../media');
}
public function getId()
{
return $this->id;
}
public function getPath()
{
return $this->path;
}
public function getName()
{
return $this->name;
}
public function getMimeType()
{
return $this->mimeType;
}
}
## Instruction:
Add a accesor for size
## Code After:
<?php
namespace Datenknoten\LigiBundle\Entity;
use Gedmo\Mapping\Annotation as Gedmo;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity
* @Gedmo\Uploadable(pathMethod="getDefaultPath", filenameGenerator="SHA1", allowOverwrite=true, appendNumber=true)
*/
class File
{
/**
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* @ORM\Column(name="path", type="string")
* @Gedmo\UploadableFilePath
*/
private $path;
/**
* @ORM\Column(name="name", type="string")
* @Gedmo\UploadableFileName
*/
private $name;
/**
* @ORM\Column(name="mime_type", type="string")
* @Gedmo\UploadableFileMimeType
*/
private $mimeType;
/**
* @ORM\Column(name="size", type="decimal")
* @Gedmo\UploadableFileSize
*/
private $size;
public function getDefaultPath()
{
return realpath(__DIR__ . '/../../../../media');
}
public function getId()
{
return $this->id;
}
public function getPath()
{
return $this->path;
}
public function getName()
{
return $this->name;
}
public function getMimeType()
{
return $this->mimeType;
}
public function getSize()
{
return $this->size;
}
} | <?php
namespace Datenknoten\LigiBundle\Entity;
use Gedmo\Mapping\Annotation as Gedmo;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity
* @Gedmo\Uploadable(pathMethod="getDefaultPath", filenameGenerator="SHA1", allowOverwrite=true, appendNumber=true)
*/
class File
{
/**
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* @ORM\Column(name="path", type="string")
* @Gedmo\UploadableFilePath
*/
private $path;
/**
* @ORM\Column(name="name", type="string")
* @Gedmo\UploadableFileName
*/
private $name;
/**
* @ORM\Column(name="mime_type", type="string")
* @Gedmo\UploadableFileMimeType
*/
private $mimeType;
/**
* @ORM\Column(name="size", type="decimal")
* @Gedmo\UploadableFileSize
*/
private $size;
public function getDefaultPath()
{
return realpath(__DIR__ . '/../../../../media');
}
public function getId()
{
return $this->id;
}
public function getPath()
{
return $this->path;
}
public function getName()
{
return $this->name;
}
public function getMimeType()
{
return $this->mimeType;
}
+
+ public function getSize()
+ {
+ return $this->size;
+ }
} | 5 | 0.072464 | 5 | 0 |
b223d2c86c33ef1217f38ff9a146883e7c9c2c32 | app/controllers/ckeditor/application_controller.rb | app/controllers/ckeditor/application_controller.rb | class Ckeditor::ApplicationController < ActionController::Base
respond_to :html, :json
layout 'ckeditor/application'
before_filter :find_asset, :only => [:destroy]
before_filter :ckeditor_authorize!
before_filter :authorize_resource
protected
def respond_with_asset(asset)
file = params[:CKEditor].blank? ? params[:qqfile] : params[:upload]
asset.data = Ckeditor::Http.normalize_param(file, request)
callback = ckeditor_before_create_asset(asset)
if callback && asset.save
body = params[:CKEditor].blank? ? asset.to_json(:only=>[:id, :type]) : %Q"<script type='text/javascript'>
window.parent.CKEDITOR.tools.callFunction(#{params[:CKEditorFuncNum]}, '#{config.relative_url_root}#{Ckeditor::Utils.escape_single_quotes(asset.url_content)}');
</script>"
render :text => body
else
if params[:CKEditor]
render :text => %Q"<script type='text/javascript'>
window.parent.CKEDITOR.tools.callFunction(#{params[:CKEditorFuncNum]}, null, '#{asset.errors.full_messages.first}');
</script>"
else
render :nothing => true
end
end
end
end
| class Ckeditor::ApplicationController < ApplicationController
respond_to :html, :json
layout 'ckeditor/application'
before_filter :find_asset, :only => [:destroy]
before_filter :ckeditor_authorize!
before_filter :authorize_resource
protected
def respond_with_asset(asset)
file = params[:CKEditor].blank? ? params[:qqfile] : params[:upload]
asset.data = Ckeditor::Http.normalize_param(file, request)
callback = ckeditor_before_create_asset(asset)
if callback && asset.save
body = params[:CKEditor].blank? ? asset.to_json(:only=>[:id, :type]) : %Q"<script type='text/javascript'>
window.parent.CKEDITOR.tools.callFunction(#{params[:CKEditorFuncNum]}, '#{config.relative_url_root}#{Ckeditor::Utils.escape_single_quotes(asset.url_content)}');
</script>"
render :text => body
else
if params[:CKEditor]
render :text => %Q"<script type='text/javascript'>
window.parent.CKEDITOR.tools.callFunction(#{params[:CKEditorFuncNum]}, null, '#{asset.errors.full_messages.first}');
</script>"
else
render :nothing => true
end
end
end
end
| Fix rescue problem on ApplicationController | Fix rescue problem on ApplicationController
| Ruby | mit | kartikluke/ckeditor,barbershoplabs/ckeditor,caiqinghua/ckeditor,209cameronism/ckeditor-npp,kelso/ckeditor,lovewitty/ckeditor,AleksKaverin/ckeditor,igorkasyanchuk/ckeditor,qx/ckeditor,mkaszubowski/ckeditor,EndingChaung/ckeditor,Gennovacap-Technology/ckeditor,3months/ckeditor,sharpfuryz/ckeditor,cookieshq/ckeditor,209cameronism/ckeditor-npp,igorkasyanchuk/ckeditor,barbershoplabs/ckeditor,LaunchPadLab/ckeditor,cookieshq/ckeditor,moneyadviceservice/ckeditor,ccfiel/ckeditor,ajayaneja896/ckeditor,EndingChaung/ckeditor,ajayaneja896/ckeditor,dailykos/ckeditor,sr-education/ckeditor,lovewitty/ckeditor,sharpfuryz/ckeditor,cookieshq/ckeditor,DavidHHShao/ckeditor,lenamuit/ckeditor,Eepa/ckeditor,galetahub/ckeditor,3months/ckeditor,LaunchPadLab/ckeditor,209cameronism/ckeditor-npp,tsipa88/ckeditor,galetahub/ckeditor,barbershoplabs/ckeditor,lenamuit/ckeditor,strikingly/ckeditor,EndingChaung/ckeditor,myplaceonline/ckeditor,bryanlo22/ckeditor,caiqinghua/ckeditor,ccfiel/ckeditor,LaunchPadLab/ckeditor,die-antwort/ckeditor,AleksKaverin/ckeditor,ajayaneja896/ckeditor,idrozd/ckeditor,kelso/ckeditor,tsipa88/ckeditor,gambala/ckeditor,gambala/ckeditor,strikingly/ckeditor,Eepa/ckeditor,DavidHHShao/ckeditor,AleksKaverin/ckeditor,caiqinghua/ckeditor,strikingly/ckeditor,idrozd/ckeditor,bryanlo22/ckeditor,shtzr840329/ckeditor,sr-education/ckeditor,glebtv/ckeditor,bryanlo22/ckeditor,dailykos/ckeditor,myplaceonline/ckeditor,3months/ckeditor,shtzr840329/ckeditor,DavidHHShao/ckeditor,osdakira/ckeditor,moneyadviceservice/ckeditor,qx/ckeditor,danhixon/ckeditor,qx/ckeditor,dailykos/ckeditor,ccfiel/ckeditor,ShilpeshAgre/ckeditor,lenamuit/ckeditor,die-antwort/ckeditor,danhixon/ckeditor,mkaszubowski/ckeditor,kartikluke/ckeditor,kelso/ckeditor,osdakira/ckeditor,myplaceonline/ckeditor,mkaszubowski/ckeditor,artempartos/ckeditor,Gennovacap-Technology/ckeditor,lovewitty/ckeditor,kartikluke/ckeditor,artempartos/ckeditor,shtzr840329/ckeditor,Gennovacap-Technology/ckeditor,ShilpeshAgre/ckeditor,ShilpeshAgre/ckeditor,sr-education/ckeditor,artempartos/ckeditor,danhixon/ckeditor,glebtv/ckeditor,gambala/ckeditor,galetahub/ckeditor,Eepa/ckeditor,igorkasyanchuk/ckeditor,sharpfuryz/ckeditor,glebtv/ckeditor,osdakira/ckeditor,die-antwort/ckeditor,tsipa88/ckeditor | ruby | ## Code Before:
class Ckeditor::ApplicationController < ActionController::Base
respond_to :html, :json
layout 'ckeditor/application'
before_filter :find_asset, :only => [:destroy]
before_filter :ckeditor_authorize!
before_filter :authorize_resource
protected
def respond_with_asset(asset)
file = params[:CKEditor].blank? ? params[:qqfile] : params[:upload]
asset.data = Ckeditor::Http.normalize_param(file, request)
callback = ckeditor_before_create_asset(asset)
if callback && asset.save
body = params[:CKEditor].blank? ? asset.to_json(:only=>[:id, :type]) : %Q"<script type='text/javascript'>
window.parent.CKEDITOR.tools.callFunction(#{params[:CKEditorFuncNum]}, '#{config.relative_url_root}#{Ckeditor::Utils.escape_single_quotes(asset.url_content)}');
</script>"
render :text => body
else
if params[:CKEditor]
render :text => %Q"<script type='text/javascript'>
window.parent.CKEDITOR.tools.callFunction(#{params[:CKEditorFuncNum]}, null, '#{asset.errors.full_messages.first}');
</script>"
else
render :nothing => true
end
end
end
end
## Instruction:
Fix rescue problem on ApplicationController
## Code After:
class Ckeditor::ApplicationController < ApplicationController
respond_to :html, :json
layout 'ckeditor/application'
before_filter :find_asset, :only => [:destroy]
before_filter :ckeditor_authorize!
before_filter :authorize_resource
protected
def respond_with_asset(asset)
file = params[:CKEditor].blank? ? params[:qqfile] : params[:upload]
asset.data = Ckeditor::Http.normalize_param(file, request)
callback = ckeditor_before_create_asset(asset)
if callback && asset.save
body = params[:CKEditor].blank? ? asset.to_json(:only=>[:id, :type]) : %Q"<script type='text/javascript'>
window.parent.CKEDITOR.tools.callFunction(#{params[:CKEditorFuncNum]}, '#{config.relative_url_root}#{Ckeditor::Utils.escape_single_quotes(asset.url_content)}');
</script>"
render :text => body
else
if params[:CKEditor]
render :text => %Q"<script type='text/javascript'>
window.parent.CKEDITOR.tools.callFunction(#{params[:CKEditorFuncNum]}, null, '#{asset.errors.full_messages.first}');
</script>"
else
render :nothing => true
end
end
end
end
| - class Ckeditor::ApplicationController < ActionController::Base
? ------
+ class Ckeditor::ApplicationController < ApplicationController
? ++++ +
respond_to :html, :json
layout 'ckeditor/application'
before_filter :find_asset, :only => [:destroy]
before_filter :ckeditor_authorize!
before_filter :authorize_resource
protected
def respond_with_asset(asset)
file = params[:CKEditor].blank? ? params[:qqfile] : params[:upload]
asset.data = Ckeditor::Http.normalize_param(file, request)
callback = ckeditor_before_create_asset(asset)
if callback && asset.save
body = params[:CKEditor].blank? ? asset.to_json(:only=>[:id, :type]) : %Q"<script type='text/javascript'>
window.parent.CKEDITOR.tools.callFunction(#{params[:CKEditorFuncNum]}, '#{config.relative_url_root}#{Ckeditor::Utils.escape_single_quotes(asset.url_content)}');
</script>"
render :text => body
else
if params[:CKEditor]
render :text => %Q"<script type='text/javascript'>
window.parent.CKEDITOR.tools.callFunction(#{params[:CKEditorFuncNum]}, null, '#{asset.errors.full_messages.first}');
</script>"
else
render :nothing => true
end
end
end
end | 2 | 0.060606 | 1 | 1 |
cdc8a349a32b62095da94c3ae1dba65885b59478 | Loggable.swift | Loggable.swift | //
// Loggable.swift
// Loggable
//
// Created by Michael Fourre on 2/4/17.
//
public protocol Loggable {
}
public extension Loggable {
fileprivate static func position(file: String, function: String, line: Int) -> String {
let path = file.components(separatedBy: "/")
if let file = path[path.count - 1].replacingOccurrences(of: ".swift", with: "") {
return "<\(file):\(line)>"
}
return ""
}
fileprivate static func logFirst(_ type: String, file: String, function: String, line: Int, strArr: [String]?) {
print("Log.\(type)\(position(file: file, function: function, line: line)): \(strArr?.first ?? "Could not parse string")")
}
fileprivate static func logRemaining(_ strArr: [String]?) {
guard let count = strArr?.count , count > 1 else { return }
for newLine in 1..<count {
if let line = strArr?[newLine] {
print(line)
}
}
}
public static func log(type: String, string: String?, file: String, function: String, line: Int) {
let strArr = string?.components(separatedBy: "\n")
self.logFirst(type, file: file, function: function, line: line, strArr: strArr)
self.logRemaining(strArr)
}
}
| //
// Loggable.swift
// Loggable
//
// Created by Michael Fourre on 2/4/17.
//
public protocol Loggable {
}
public extension Loggable {
fileprivate static func position(file: String, function: String, line: Int) -> String {
let path = file.components(separatedBy: "/")
let file = path[path.count - 1].replacingOccurrences(of: ".swift", with: "")
return "<\(file):\(line)>"
}
fileprivate static func logFirst(_ type: String, file: String, function: String, line: Int, strArr: [String]?) {
print("Log.\(type)\(position(file: file, function: function, line: line)): \(strArr?.first ?? "Could not parse string")")
}
fileprivate static func logRemaining(_ strArr: [String]?) {
guard let count = strArr?.count , count > 1 else { return }
for newLine in 1..<count {
if let line = strArr?[newLine] {
print(line)
}
}
}
public static func log(type: String, string: String?, file: String, function: String, line: Int) {
let strArr = string?.components(separatedBy: "\n")
self.logFirst(type, file: file, function: function, line: line, strArr: strArr)
self.logRemaining(strArr)
}
}
| Remove conditional unwrapping for expression which can no longer potentially return nil | Remove conditional unwrapping for expression which can no longer potentially return nil
| Swift | unlicense | mtfourre/Loggable,mtfourre/Loggable | swift | ## Code Before:
//
// Loggable.swift
// Loggable
//
// Created by Michael Fourre on 2/4/17.
//
public protocol Loggable {
}
public extension Loggable {
fileprivate static func position(file: String, function: String, line: Int) -> String {
let path = file.components(separatedBy: "/")
if let file = path[path.count - 1].replacingOccurrences(of: ".swift", with: "") {
return "<\(file):\(line)>"
}
return ""
}
fileprivate static func logFirst(_ type: String, file: String, function: String, line: Int, strArr: [String]?) {
print("Log.\(type)\(position(file: file, function: function, line: line)): \(strArr?.first ?? "Could not parse string")")
}
fileprivate static func logRemaining(_ strArr: [String]?) {
guard let count = strArr?.count , count > 1 else { return }
for newLine in 1..<count {
if let line = strArr?[newLine] {
print(line)
}
}
}
public static func log(type: String, string: String?, file: String, function: String, line: Int) {
let strArr = string?.components(separatedBy: "\n")
self.logFirst(type, file: file, function: function, line: line, strArr: strArr)
self.logRemaining(strArr)
}
}
## Instruction:
Remove conditional unwrapping for expression which can no longer potentially return nil
## Code After:
//
// Loggable.swift
// Loggable
//
// Created by Michael Fourre on 2/4/17.
//
public protocol Loggable {
}
public extension Loggable {
fileprivate static func position(file: String, function: String, line: Int) -> String {
let path = file.components(separatedBy: "/")
let file = path[path.count - 1].replacingOccurrences(of: ".swift", with: "")
return "<\(file):\(line)>"
}
fileprivate static func logFirst(_ type: String, file: String, function: String, line: Int, strArr: [String]?) {
print("Log.\(type)\(position(file: file, function: function, line: line)): \(strArr?.first ?? "Could not parse string")")
}
fileprivate static func logRemaining(_ strArr: [String]?) {
guard let count = strArr?.count , count > 1 else { return }
for newLine in 1..<count {
if let line = strArr?[newLine] {
print(line)
}
}
}
public static func log(type: String, string: String?, file: String, function: String, line: Int) {
let strArr = string?.components(separatedBy: "\n")
self.logFirst(type, file: file, function: function, line: line, strArr: strArr)
self.logRemaining(strArr)
}
}
| //
// Loggable.swift
// Loggable
//
// Created by Michael Fourre on 2/4/17.
//
public protocol Loggable {
}
public extension Loggable {
fileprivate static func position(file: String, function: String, line: Int) -> String {
let path = file.components(separatedBy: "/")
- if let file = path[path.count - 1].replacingOccurrences(of: ".swift", with: "") {
? --- --
+ let file = path[path.count - 1].replacingOccurrences(of: ".swift", with: "")
- return "<\(file):\(line)>"
? ----
+ return "<\(file):\(line)>"
- }
- return ""
}
fileprivate static func logFirst(_ type: String, file: String, function: String, line: Int, strArr: [String]?) {
print("Log.\(type)\(position(file: file, function: function, line: line)): \(strArr?.first ?? "Could not parse string")")
}
fileprivate static func logRemaining(_ strArr: [String]?) {
guard let count = strArr?.count , count > 1 else { return }
for newLine in 1..<count {
if let line = strArr?[newLine] {
print(line)
}
}
}
public static func log(type: String, string: String?, file: String, function: String, line: Int) {
let strArr = string?.components(separatedBy: "\n")
self.logFirst(type, file: file, function: function, line: line, strArr: strArr)
self.logRemaining(strArr)
}
} | 6 | 0.153846 | 2 | 4 |
3d8728fdc3671cf8709b1000cc2aff9d048ff13a | src/test/java/net/sf/commonclipse/CCPluginPreferencesTest.java | src/test/java/net/sf/commonclipse/CCPluginPreferencesTest.java | package net.sf.commonclipse;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat;
import java.util.regex.Pattern;
/**
* Tests for CCPluginPreferences.
* @author fgiust
* @version $Revision$ ($Author$)
*/
public class CCPluginPreferencesTest
{
/**
* test the conversion from an array of strings to a regexp.
*/
public void testRegexpConversion()
{
Pattern regexp = CCPluginPreferences.generateRegExp("log;test?u?;done*");
assertThat(regexp.pattern(), equalTo("(^log$)|(^test.u.$)|(^done*$)"));
}
/**
* test the conversion from an array of strings to a regexp.
*/
public void testEmptyRegexpConversion()
{
Pattern regexp = CCPluginPreferences.generateRegExp("");
assertFalse(regexp.matcher("").matches());
assertFalse(regexp.matcher("a").matches());
}
/**
* test the conversion from an array of strings to a regexp.
*/
public void testNullRegexpConversion()
{
Pattern regexp = CCPluginPreferences.generateRegExp(null);
assertFalse(regexp.matcher("").matches());
assertFalse(regexp.matcher("a").matches());
}
}
| package net.sf.commonclipse;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat;
import java.util.regex.Pattern;
import org.junit.Test;
/**
* Tests for CCPluginPreferences.
* @author fgiust
* @version $Revision$ ($Author$)
*/
public class CCPluginPreferencesTest
{
/**
* test the conversion from an array of strings to a regexp.
*/
@Test
public void testRegexpConversion()
{
Pattern regexp = CCPluginPreferences.generateRegExp("log;test?u?;done*");
assertThat(regexp.pattern(), equalTo("(^log$)|(^test.u.$)|(^done*$)"));
}
/**
* test the conversion from an array of strings to a regexp.
*/
@Test
public void testEmptyRegexpConversion()
{
Pattern regexp = CCPluginPreferences.generateRegExp("");
assertFalse(regexp.matcher("").matches());
assertFalse(regexp.matcher("a").matches());
}
/**
* test the conversion from an array of strings to a regexp.
*/
@Test
public void testNullRegexpConversion()
{
Pattern regexp = CCPluginPreferences.generateRegExp(null);
assertFalse(regexp.matcher("").matches());
assertFalse(regexp.matcher("a").matches());
}
}
| Fix missing @Test annotations for JUnit tests. | Fix missing @Test annotations for JUnit tests.
Forgot to add the annotations when upgrading to JUnit 4.
| Java | apache-2.0 | mnuessler/commonclipse | java | ## Code Before:
package net.sf.commonclipse;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat;
import java.util.regex.Pattern;
/**
* Tests for CCPluginPreferences.
* @author fgiust
* @version $Revision$ ($Author$)
*/
public class CCPluginPreferencesTest
{
/**
* test the conversion from an array of strings to a regexp.
*/
public void testRegexpConversion()
{
Pattern regexp = CCPluginPreferences.generateRegExp("log;test?u?;done*");
assertThat(regexp.pattern(), equalTo("(^log$)|(^test.u.$)|(^done*$)"));
}
/**
* test the conversion from an array of strings to a regexp.
*/
public void testEmptyRegexpConversion()
{
Pattern regexp = CCPluginPreferences.generateRegExp("");
assertFalse(regexp.matcher("").matches());
assertFalse(regexp.matcher("a").matches());
}
/**
* test the conversion from an array of strings to a regexp.
*/
public void testNullRegexpConversion()
{
Pattern regexp = CCPluginPreferences.generateRegExp(null);
assertFalse(regexp.matcher("").matches());
assertFalse(regexp.matcher("a").matches());
}
}
## Instruction:
Fix missing @Test annotations for JUnit tests.
Forgot to add the annotations when upgrading to JUnit 4.
## Code After:
package net.sf.commonclipse;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat;
import java.util.regex.Pattern;
import org.junit.Test;
/**
* Tests for CCPluginPreferences.
* @author fgiust
* @version $Revision$ ($Author$)
*/
public class CCPluginPreferencesTest
{
/**
* test the conversion from an array of strings to a regexp.
*/
@Test
public void testRegexpConversion()
{
Pattern regexp = CCPluginPreferences.generateRegExp("log;test?u?;done*");
assertThat(regexp.pattern(), equalTo("(^log$)|(^test.u.$)|(^done*$)"));
}
/**
* test the conversion from an array of strings to a regexp.
*/
@Test
public void testEmptyRegexpConversion()
{
Pattern regexp = CCPluginPreferences.generateRegExp("");
assertFalse(regexp.matcher("").matches());
assertFalse(regexp.matcher("a").matches());
}
/**
* test the conversion from an array of strings to a regexp.
*/
@Test
public void testNullRegexpConversion()
{
Pattern regexp = CCPluginPreferences.generateRegExp(null);
assertFalse(regexp.matcher("").matches());
assertFalse(regexp.matcher("a").matches());
}
}
| package net.sf.commonclipse;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat;
import java.util.regex.Pattern;
+
+ import org.junit.Test;
/**
* Tests for CCPluginPreferences.
* @author fgiust
* @version $Revision$ ($Author$)
*/
public class CCPluginPreferencesTest
{
/**
* test the conversion from an array of strings to a regexp.
*/
+ @Test
public void testRegexpConversion()
{
Pattern regexp = CCPluginPreferences.generateRegExp("log;test?u?;done*");
assertThat(regexp.pattern(), equalTo("(^log$)|(^test.u.$)|(^done*$)"));
}
/**
* test the conversion from an array of strings to a regexp.
*/
+ @Test
public void testEmptyRegexpConversion()
{
Pattern regexp = CCPluginPreferences.generateRegExp("");
assertFalse(regexp.matcher("").matches());
assertFalse(regexp.matcher("a").matches());
}
/**
* test the conversion from an array of strings to a regexp.
*/
+ @Test
public void testNullRegexpConversion()
{
Pattern regexp = CCPluginPreferences.generateRegExp(null);
assertFalse(regexp.matcher("").matches());
assertFalse(regexp.matcher("a").matches());
}
} | 5 | 0.106383 | 5 | 0 |
984d8626a146770fe93d54ae107cd33dc3d2f481 | dbmigrator/commands/init_schema_migrations.py | dbmigrator/commands/init_schema_migrations.py |
from .. import utils
__all__ = ('cli_loader',)
@utils.with_cursor
def cli_command(cursor, migrations_directory='', **kwargs):
cursor.execute("""\
CREATE TABLE IF NOT EXISTS schema_migrations (
version TEXT NOT NULL
)""")
cursor.execute("""\
DELETE FROM schema_migrations""")
versions = []
for version, name in utils.get_migrations(migrations_directory):
versions.append((version,))
cursor.executemany("""\
INSERT INTO schema_migrations VALUES (%s)
""", versions)
def cli_loader(parser):
return cli_command
|
from .. import utils
__all__ = ('cli_loader',)
@utils.with_cursor
def cli_command(cursor, migrations_directory='', **kwargs):
cursor.execute("""\
CREATE TABLE IF NOT EXISTS schema_migrations (
version TEXT NOT NULL,
applied TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
)""")
cursor.execute("""\
DELETE FROM schema_migrations""")
versions = []
for version, name in utils.get_migrations(migrations_directory):
versions.append((version,))
cursor.executemany("""\
INSERT INTO schema_migrations VALUES (%s)
""", versions)
def cli_loader(parser):
return cli_command
| Add "applied" timestamp to schema migrations table | Add "applied" timestamp to schema migrations table
| Python | agpl-3.0 | karenc/db-migrator | python | ## Code Before:
from .. import utils
__all__ = ('cli_loader',)
@utils.with_cursor
def cli_command(cursor, migrations_directory='', **kwargs):
cursor.execute("""\
CREATE TABLE IF NOT EXISTS schema_migrations (
version TEXT NOT NULL
)""")
cursor.execute("""\
DELETE FROM schema_migrations""")
versions = []
for version, name in utils.get_migrations(migrations_directory):
versions.append((version,))
cursor.executemany("""\
INSERT INTO schema_migrations VALUES (%s)
""", versions)
def cli_loader(parser):
return cli_command
## Instruction:
Add "applied" timestamp to schema migrations table
## Code After:
from .. import utils
__all__ = ('cli_loader',)
@utils.with_cursor
def cli_command(cursor, migrations_directory='', **kwargs):
cursor.execute("""\
CREATE TABLE IF NOT EXISTS schema_migrations (
version TEXT NOT NULL,
applied TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
)""")
cursor.execute("""\
DELETE FROM schema_migrations""")
versions = []
for version, name in utils.get_migrations(migrations_directory):
versions.append((version,))
cursor.executemany("""\
INSERT INTO schema_migrations VALUES (%s)
""", versions)
def cli_loader(parser):
return cli_command
|
from .. import utils
__all__ = ('cli_loader',)
@utils.with_cursor
def cli_command(cursor, migrations_directory='', **kwargs):
cursor.execute("""\
CREATE TABLE IF NOT EXISTS schema_migrations (
- version TEXT NOT NULL
+ version TEXT NOT NULL,
? +
+ applied TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
)""")
cursor.execute("""\
DELETE FROM schema_migrations""")
versions = []
for version, name in utils.get_migrations(migrations_directory):
versions.append((version,))
cursor.executemany("""\
INSERT INTO schema_migrations VALUES (%s)
""", versions)
def cli_loader(parser):
return cli_command | 3 | 0.12 | 2 | 1 |
eb6ecad6aee211a395e940a58ee562576bc341d8 | Cargo.toml | Cargo.toml | [package]
name = "cabarrus"
version = "0.1.0"
authors = ["Sean Gallagher <stgallag@gmail.com>"]
license = "MIT"
[lib]
[[bin]]
name = "cb-cooccur"
description = "Find windowed word cooccurances"
[[bin]]
name = "cb-metrics"
description = "Measure the quality of a word embedding"
[dependencies]
# Warc parser
nom = "*"
# Argument parser
clap = "~2.21.1"
# Numpy like arrays
ndarray = {version="*", features=["serde"]}
ndarray-linalg = "*"
ndarray-rand = "*"
linxal = "*"
# Serialization and Deserialization
byteorder = "*"
regex = "*"
# Logging
log = "*"
env_logger = "*"
# Faster hashes
farmhash = "1.1.5"
hash_hasher = "0.2.0"
# Better tokenization (than whitespace)
unicode-segmentation = "*"
# reading matrices without consuming memory
memmap = "*" | [package]
name = "cabarrus"
version = "0.1.0"
authors = ["Sean Gallagher <stgallag@gmail.com>"]
license = "MIT"
[lib]
[[bin]]
name = "cb-cooccur"
#description = "Find windowed word cooccurances"
[[bin]]
name = "cb-metrics"
#description = "Measure the quality of a word embedding"
[[bin]]
name = "cb-token-count"
#description = "Count the number of unicode tokens in the text"
[dependencies]
# Warc parser
nom = "*"
# Argument parser
clap = "~2.21.1"
# Numpy like arrays
ndarray = {version="*", features=["serde"]}
ndarray-linalg = "*"
ndarray-rand = "*"
linxal = "*"
# Serialization and Deserialization
byteorder = "*"
regex = "*"
# Logging
log = "*"
env_logger = "*"
# Faster hashes
farmhash = "1.1.5"
hash_hasher = "0.2.0"
# Better tokenization (than whitespace)
unicode-segmentation = "*"
# reading matrices without consuming memory
memmap = "*"
| Include the token count as a bin | Include the token count as a bin
| TOML | mit | SeanTater/cabarrus,SeanTater/cabarrus,SeanTater/cabarrus | toml | ## Code Before:
[package]
name = "cabarrus"
version = "0.1.0"
authors = ["Sean Gallagher <stgallag@gmail.com>"]
license = "MIT"
[lib]
[[bin]]
name = "cb-cooccur"
description = "Find windowed word cooccurances"
[[bin]]
name = "cb-metrics"
description = "Measure the quality of a word embedding"
[dependencies]
# Warc parser
nom = "*"
# Argument parser
clap = "~2.21.1"
# Numpy like arrays
ndarray = {version="*", features=["serde"]}
ndarray-linalg = "*"
ndarray-rand = "*"
linxal = "*"
# Serialization and Deserialization
byteorder = "*"
regex = "*"
# Logging
log = "*"
env_logger = "*"
# Faster hashes
farmhash = "1.1.5"
hash_hasher = "0.2.0"
# Better tokenization (than whitespace)
unicode-segmentation = "*"
# reading matrices without consuming memory
memmap = "*"
## Instruction:
Include the token count as a bin
## Code After:
[package]
name = "cabarrus"
version = "0.1.0"
authors = ["Sean Gallagher <stgallag@gmail.com>"]
license = "MIT"
[lib]
[[bin]]
name = "cb-cooccur"
#description = "Find windowed word cooccurances"
[[bin]]
name = "cb-metrics"
#description = "Measure the quality of a word embedding"
[[bin]]
name = "cb-token-count"
#description = "Count the number of unicode tokens in the text"
[dependencies]
# Warc parser
nom = "*"
# Argument parser
clap = "~2.21.1"
# Numpy like arrays
ndarray = {version="*", features=["serde"]}
ndarray-linalg = "*"
ndarray-rand = "*"
linxal = "*"
# Serialization and Deserialization
byteorder = "*"
regex = "*"
# Logging
log = "*"
env_logger = "*"
# Faster hashes
farmhash = "1.1.5"
hash_hasher = "0.2.0"
# Better tokenization (than whitespace)
unicode-segmentation = "*"
# reading matrices without consuming memory
memmap = "*"
| [package]
name = "cabarrus"
version = "0.1.0"
authors = ["Sean Gallagher <stgallag@gmail.com>"]
license = "MIT"
[lib]
[[bin]]
name = "cb-cooccur"
- description = "Find windowed word cooccurances"
+ #description = "Find windowed word cooccurances"
? +
[[bin]]
name = "cb-metrics"
- description = "Measure the quality of a word embedding"
+ #description = "Measure the quality of a word embedding"
? +
+
+ [[bin]]
+ name = "cb-token-count"
+ #description = "Count the number of unicode tokens in the text"
[dependencies]
# Warc parser
nom = "*"
# Argument parser
clap = "~2.21.1"
# Numpy like arrays
ndarray = {version="*", features=["serde"]}
ndarray-linalg = "*"
ndarray-rand = "*"
linxal = "*"
# Serialization and Deserialization
byteorder = "*"
regex = "*"
# Logging
log = "*"
env_logger = "*"
# Faster hashes
farmhash = "1.1.5"
hash_hasher = "0.2.0"
# Better tokenization (than whitespace)
unicode-segmentation = "*"
# reading matrices without consuming memory
memmap = "*" | 8 | 0.205128 | 6 | 2 |
aeb4e69195e224473b91d29233e24d0cef8bab3b | app/models/lottery_division.rb | app/models/lottery_division.rb |
class LotteryDivision < ApplicationRecord
include CapitalizeAttributes
belongs_to :lottery, touch: true
has_many :entrants, class_name: "LotteryEntrant", dependent: :destroy
has_many :tickets, through: :entrants
strip_attributes collapse_spaces: true
capitalize_attributes :name
validates_presence_of :maximum_entries, :name
validates_uniqueness_of :name, case_sensitive: false, scope: :lottery
def draw_ticket!
drawn_entrants = entrants.joins(tickets: :draw)
eligible_tickets = tickets.where.not(lottery_entrant_id: drawn_entrants)
drawn_ticket_index = rand(eligible_tickets.count)
drawn_ticket = eligible_tickets.offset(drawn_ticket_index).first
lottery.draws.create(ticket: drawn_ticket) if drawn_ticket.present?
end
def draws
lottery.draws.for_division(self)
end
def reverse_loaded_draws
ordered_loaded_draws.reorder(created_at: :desc)
end
def wait_list_entrants
ordered_drawn_entrants.offset(maximum_entries).limit(maximum_wait_list)
end
def winning_entrants
ordered_drawn_entrants.limit(maximum_entries)
end
private
def ordered_loaded_draws
draws.includes(ticket: :entrant)
.order(:created_at)
end
def ordered_drawn_entrants
entrants.drawn_and_ordered
end
end
|
class LotteryDivision < ApplicationRecord
include CapitalizeAttributes
belongs_to :lottery, touch: true
has_many :entrants, class_name: "LotteryEntrant", dependent: :destroy
has_many :tickets, through: :entrants
strip_attributes collapse_spaces: true
capitalize_attributes :name
validates_presence_of :maximum_entries, :name
validates_uniqueness_of :name, case_sensitive: false, scope: :lottery
def draw_ticket!
drawn_entrants = entrants.joins(tickets: :draw)
eligible_tickets = tickets.where.not(lottery_entrant_id: drawn_entrants)
drawn_ticket_index = rand(eligible_tickets.count)
drawn_ticket = eligible_tickets.offset(drawn_ticket_index).first
lottery.draws.create(ticket: drawn_ticket) if drawn_ticket.present?
end
def draws
lottery.draws.for_division(self)
end
def reverse_loaded_draws
loaded_draws.reorder(created_at: :desc)
end
def wait_list_entrants
ordered_drawn_entrants.offset(maximum_entries).limit(maximum_wait_list)
end
def winning_entrants
ordered_drawn_entrants.limit(maximum_entries)
end
private
def loaded_draws
draws.includes(ticket: :entrant)
end
def ordered_drawn_entrants
entrants.drawn_and_ordered
end
end
| Remove redundant ordering in lottery division model | Remove redundant ordering in lottery division model
| Ruby | mit | SplitTime/OpenSplitTime,SplitTime/OpenSplitTime,SplitTime/OpenSplitTime | ruby | ## Code Before:
class LotteryDivision < ApplicationRecord
include CapitalizeAttributes
belongs_to :lottery, touch: true
has_many :entrants, class_name: "LotteryEntrant", dependent: :destroy
has_many :tickets, through: :entrants
strip_attributes collapse_spaces: true
capitalize_attributes :name
validates_presence_of :maximum_entries, :name
validates_uniqueness_of :name, case_sensitive: false, scope: :lottery
def draw_ticket!
drawn_entrants = entrants.joins(tickets: :draw)
eligible_tickets = tickets.where.not(lottery_entrant_id: drawn_entrants)
drawn_ticket_index = rand(eligible_tickets.count)
drawn_ticket = eligible_tickets.offset(drawn_ticket_index).first
lottery.draws.create(ticket: drawn_ticket) if drawn_ticket.present?
end
def draws
lottery.draws.for_division(self)
end
def reverse_loaded_draws
ordered_loaded_draws.reorder(created_at: :desc)
end
def wait_list_entrants
ordered_drawn_entrants.offset(maximum_entries).limit(maximum_wait_list)
end
def winning_entrants
ordered_drawn_entrants.limit(maximum_entries)
end
private
def ordered_loaded_draws
draws.includes(ticket: :entrant)
.order(:created_at)
end
def ordered_drawn_entrants
entrants.drawn_and_ordered
end
end
## Instruction:
Remove redundant ordering in lottery division model
## Code After:
class LotteryDivision < ApplicationRecord
include CapitalizeAttributes
belongs_to :lottery, touch: true
has_many :entrants, class_name: "LotteryEntrant", dependent: :destroy
has_many :tickets, through: :entrants
strip_attributes collapse_spaces: true
capitalize_attributes :name
validates_presence_of :maximum_entries, :name
validates_uniqueness_of :name, case_sensitive: false, scope: :lottery
def draw_ticket!
drawn_entrants = entrants.joins(tickets: :draw)
eligible_tickets = tickets.where.not(lottery_entrant_id: drawn_entrants)
drawn_ticket_index = rand(eligible_tickets.count)
drawn_ticket = eligible_tickets.offset(drawn_ticket_index).first
lottery.draws.create(ticket: drawn_ticket) if drawn_ticket.present?
end
def draws
lottery.draws.for_division(self)
end
def reverse_loaded_draws
loaded_draws.reorder(created_at: :desc)
end
def wait_list_entrants
ordered_drawn_entrants.offset(maximum_entries).limit(maximum_wait_list)
end
def winning_entrants
ordered_drawn_entrants.limit(maximum_entries)
end
private
def loaded_draws
draws.includes(ticket: :entrant)
end
def ordered_drawn_entrants
entrants.drawn_and_ordered
end
end
|
class LotteryDivision < ApplicationRecord
include CapitalizeAttributes
belongs_to :lottery, touch: true
has_many :entrants, class_name: "LotteryEntrant", dependent: :destroy
has_many :tickets, through: :entrants
strip_attributes collapse_spaces: true
capitalize_attributes :name
validates_presence_of :maximum_entries, :name
validates_uniqueness_of :name, case_sensitive: false, scope: :lottery
def draw_ticket!
drawn_entrants = entrants.joins(tickets: :draw)
eligible_tickets = tickets.where.not(lottery_entrant_id: drawn_entrants)
drawn_ticket_index = rand(eligible_tickets.count)
drawn_ticket = eligible_tickets.offset(drawn_ticket_index).first
lottery.draws.create(ticket: drawn_ticket) if drawn_ticket.present?
end
def draws
lottery.draws.for_division(self)
end
def reverse_loaded_draws
- ordered_loaded_draws.reorder(created_at: :desc)
? --------
+ loaded_draws.reorder(created_at: :desc)
end
def wait_list_entrants
ordered_drawn_entrants.offset(maximum_entries).limit(maximum_wait_list)
end
def winning_entrants
ordered_drawn_entrants.limit(maximum_entries)
end
private
- def ordered_loaded_draws
? --------
+ def loaded_draws
draws.includes(ticket: :entrant)
- .order(:created_at)
end
def ordered_drawn_entrants
entrants.drawn_and_ordered
end
end | 5 | 0.1 | 2 | 3 |
06176008000a386fa6afb5c0f489576e6cdb5f0b | src/app/modules/wallet/components/guards/default-redirect-guard.component.ts | src/app/modules/wallet/components/guards/default-redirect-guard.component.ts | /**
* Redirects to route set in WalletTabHistoryService
* if one exists.
* @author Ben Hayward
*/
import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';
import { WalletTabHistoryService } from '../tab-history.service';
@Injectable()
export class DefaultRedirectGuard implements CanActivate {
constructor(
private router: Router,
private tabHistory: WalletTabHistoryService
) {}
/**
* Returns false, and handles conditional redirect
* dependant on whether history is set in WalletTabHistoryService
* @returns false
*/
canActivate() {
const lastTab = this.tabHistory.lastTab;
if (lastTab) {
this.router.navigateByUrl(`/wallet${lastTab}`);
return false;
}
// default redirect
this.router.navigateByUrl('/wallet/cash/earnings');
return true;
}
}
| /**
* Redirects to route set in WalletTabHistoryService
* if one exists.
* @author Ben Hayward
*/
import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';
import { WalletTabHistoryService } from '../tab-history.service';
@Injectable()
export class DefaultRedirectGuard implements CanActivate {
constructor(
private router: Router,
private tabHistory: WalletTabHistoryService
) {}
/**
* Returns false, and handles conditional redirect
* dependant on whether history is set in WalletTabHistoryService
* @returns false
*/
canActivate() {
const lastTab = this.tabHistory.lastTab;
if (lastTab) {
this.router.navigateByUrl(`/wallet${lastTab}`);
return false;
}
// default redirect
this.router.navigateByUrl('/wallet/tokens/rewards');
return true;
}
}
| Change default wallet page to tokens | Change default wallet page to tokens
| TypeScript | agpl-3.0 | Minds/front,Minds/front,Minds/front,Minds/front | typescript | ## Code Before:
/**
* Redirects to route set in WalletTabHistoryService
* if one exists.
* @author Ben Hayward
*/
import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';
import { WalletTabHistoryService } from '../tab-history.service';
@Injectable()
export class DefaultRedirectGuard implements CanActivate {
constructor(
private router: Router,
private tabHistory: WalletTabHistoryService
) {}
/**
* Returns false, and handles conditional redirect
* dependant on whether history is set in WalletTabHistoryService
* @returns false
*/
canActivate() {
const lastTab = this.tabHistory.lastTab;
if (lastTab) {
this.router.navigateByUrl(`/wallet${lastTab}`);
return false;
}
// default redirect
this.router.navigateByUrl('/wallet/cash/earnings');
return true;
}
}
## Instruction:
Change default wallet page to tokens
## Code After:
/**
* Redirects to route set in WalletTabHistoryService
* if one exists.
* @author Ben Hayward
*/
import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';
import { WalletTabHistoryService } from '../tab-history.service';
@Injectable()
export class DefaultRedirectGuard implements CanActivate {
constructor(
private router: Router,
private tabHistory: WalletTabHistoryService
) {}
/**
* Returns false, and handles conditional redirect
* dependant on whether history is set in WalletTabHistoryService
* @returns false
*/
canActivate() {
const lastTab = this.tabHistory.lastTab;
if (lastTab) {
this.router.navigateByUrl(`/wallet${lastTab}`);
return false;
}
// default redirect
this.router.navigateByUrl('/wallet/tokens/rewards');
return true;
}
}
| /**
* Redirects to route set in WalletTabHistoryService
* if one exists.
* @author Ben Hayward
*/
import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';
import { WalletTabHistoryService } from '../tab-history.service';
@Injectable()
export class DefaultRedirectGuard implements CanActivate {
constructor(
private router: Router,
private tabHistory: WalletTabHistoryService
) {}
/**
* Returns false, and handles conditional redirect
* dependant on whether history is set in WalletTabHistoryService
* @returns false
*/
canActivate() {
const lastTab = this.tabHistory.lastTab;
if (lastTab) {
this.router.navigateByUrl(`/wallet${lastTab}`);
return false;
}
// default redirect
- this.router.navigateByUrl('/wallet/cash/earnings');
? ^^ - ^^^^
+ this.router.navigateByUrl('/wallet/tokens/rewards');
? ^^^^^ + + ^
return true;
}
} | 2 | 0.058824 | 1 | 1 |
d93bebb67a1e25fa57955d80999debad0ebac681 | db/seeds.rb | db/seeds.rb | Office.find_or_create_by(name: 'Digital')
Office.find_or_create_by(name: 'Bristol')
unless ENV=='production'
User.create([{
name: 'Admin',
email: 'fee-remission@digital.justice.gov.uk',
password: '123456789',
role: 'admin',
office: Office.find_by(name: 'Digital')
},
{
name: 'User',
email: 'bristol.user@hmcts.gsi.gov.uk',
password: '987654321',
role: 'user',
office: Office.find_by(name: 'Bristol')
}
])
end
Jurisdiction.create([{ name: 'County Court', abbr: nil },
{ name: 'High Court', abbr: nil },
{ name: 'Insolvency', abbr: nil },
{ name: 'Family Court', abbr: nil },
{ name: 'Probate', abbr: nil },
{ name: 'Court of Protection', abbr: 'COP' },
{ name: 'Magistrates Civil', abbr: nil },
{ name: 'Gambling', abbr: nil },
{ name: 'Employment Tribunal', abbr: nil },
{ name: 'Gender Tribunal', abbr: nil },
{ name: 'Land & Property Chamber', abbr: nil },
{ name: 'Immigration Appeal Chamber', abbr: 'IAC' },
{ name: 'Upper Tribunal Immigration Appeal Chamber', abbr: 'UTIAC' }])
| Office.find_or_create_by(name: 'Digital')
Office.find_or_create_by(name: 'Bristol')
unless ENV=='production'
User.create([{
name: 'Admin',
email: 'fee-remission@digital.justice.gov.uk',
password: '123456789',
role: 'admin',
office: Office.find_by(name: 'Digital')
},
{
name: 'User',
email: 'bristol.user@hmcts.gsi.gov.uk',
password: '987654321',
role: 'user',
office: Office.find_by(name: 'Bristol')
}
])
end
Jurisdiction.create([{ name: 'County', abbr: nil },
{ name: 'Family', abbr: nil },
{ name: 'High', abbr: nil },
{ name: 'Insolvency', abbr: nil },
{ name: 'Magistrates', abbr: nil },
{ name: 'Probate', abbr: nil },
{ name: 'Employment', abbr: nil },
{ name: 'Gambling', abbr: nil },
{ name: 'Gender recognition', abbr: nil },
{ name: 'Immigration (first-tier)', abbr: nil },
{ name: 'Immigration (upper)', abbr: nil },
{ name: 'Property', abbr: nil }])
| Copy changed of jurisdiction names in seed data | Copy changed of jurisdiction names in seed data
| Ruby | mit | ministryofjustice/fr-staffapp,ministryofjustice/fr-staffapp,ministryofjustice/fr-staffapp,ministryofjustice/fr-staffapp | ruby | ## Code Before:
Office.find_or_create_by(name: 'Digital')
Office.find_or_create_by(name: 'Bristol')
unless ENV=='production'
User.create([{
name: 'Admin',
email: 'fee-remission@digital.justice.gov.uk',
password: '123456789',
role: 'admin',
office: Office.find_by(name: 'Digital')
},
{
name: 'User',
email: 'bristol.user@hmcts.gsi.gov.uk',
password: '987654321',
role: 'user',
office: Office.find_by(name: 'Bristol')
}
])
end
Jurisdiction.create([{ name: 'County Court', abbr: nil },
{ name: 'High Court', abbr: nil },
{ name: 'Insolvency', abbr: nil },
{ name: 'Family Court', abbr: nil },
{ name: 'Probate', abbr: nil },
{ name: 'Court of Protection', abbr: 'COP' },
{ name: 'Magistrates Civil', abbr: nil },
{ name: 'Gambling', abbr: nil },
{ name: 'Employment Tribunal', abbr: nil },
{ name: 'Gender Tribunal', abbr: nil },
{ name: 'Land & Property Chamber', abbr: nil },
{ name: 'Immigration Appeal Chamber', abbr: 'IAC' },
{ name: 'Upper Tribunal Immigration Appeal Chamber', abbr: 'UTIAC' }])
## Instruction:
Copy changed of jurisdiction names in seed data
## Code After:
Office.find_or_create_by(name: 'Digital')
Office.find_or_create_by(name: 'Bristol')
unless ENV=='production'
User.create([{
name: 'Admin',
email: 'fee-remission@digital.justice.gov.uk',
password: '123456789',
role: 'admin',
office: Office.find_by(name: 'Digital')
},
{
name: 'User',
email: 'bristol.user@hmcts.gsi.gov.uk',
password: '987654321',
role: 'user',
office: Office.find_by(name: 'Bristol')
}
])
end
Jurisdiction.create([{ name: 'County', abbr: nil },
{ name: 'Family', abbr: nil },
{ name: 'High', abbr: nil },
{ name: 'Insolvency', abbr: nil },
{ name: 'Magistrates', abbr: nil },
{ name: 'Probate', abbr: nil },
{ name: 'Employment', abbr: nil },
{ name: 'Gambling', abbr: nil },
{ name: 'Gender recognition', abbr: nil },
{ name: 'Immigration (first-tier)', abbr: nil },
{ name: 'Immigration (upper)', abbr: nil },
{ name: 'Property', abbr: nil }])
| Office.find_or_create_by(name: 'Digital')
Office.find_or_create_by(name: 'Bristol')
unless ENV=='production'
User.create([{
name: 'Admin',
email: 'fee-remission@digital.justice.gov.uk',
password: '123456789',
role: 'admin',
office: Office.find_by(name: 'Digital')
},
{
name: 'User',
email: 'bristol.user@hmcts.gsi.gov.uk',
password: '987654321',
role: 'user',
office: Office.find_by(name: 'Bristol')
}
])
end
- Jurisdiction.create([{ name: 'County Court', abbr: nil },
? ------
+ Jurisdiction.create([{ name: 'County', abbr: nil },
+ { name: 'Family', abbr: nil },
- { name: 'High Court', abbr: nil },
? ------
+ { name: 'High', abbr: nil },
{ name: 'Insolvency', abbr: nil },
- { name: 'Family Court', abbr: nil },
? ^ ^ ^^^^^^
+ { name: 'Magistrates', abbr: nil },
? ^ ^ ^^ + ++
{ name: 'Probate', abbr: nil },
- { name: 'Court of Protection', abbr: 'COP' },
- { name: 'Magistrates Civil', abbr: nil },
? ^^^^^ -----------
+ { name: 'Employment', abbr: nil },
? ^^^^^^^^^
{ name: 'Gambling', abbr: nil },
- { name: 'Employment Tribunal', abbr: nil },
- { name: 'Gender Tribunal', abbr: nil },
? - ^^ --
+ { name: 'Gender recognition', abbr: nil },
? +++++ ^^^
+ { name: 'Immigration (first-tier)', abbr: nil },
+ { name: 'Immigration (upper)', abbr: nil },
- { name: 'Land & Property Chamber', abbr: nil },
? ------- -------- ^
+ { name: 'Property', abbr: nil }])
? ^^
- { name: 'Immigration Appeal Chamber', abbr: 'IAC' },
- { name: 'Upper Tribunal Immigration Appeal Chamber', abbr: 'UTIAC' }]) | 19 | 0.558824 | 9 | 10 |
8415776bb4d5b402aef43ab777072060420bd6b4 | cloudly/ccouchdb.py | cloudly/ccouchdb.py | import os
import couchdb
from cloudly.memoized import Memoized
import cloudly.logger as logger
log = logger.init(__name__)
@Memoized
def get_server(hostname=None, port=5984, username=None, password=None):
port = 5984
host = hostname or os.environ.get("COUCHDB_HOST", "127.0.0.1")
url = "http://{host}:{port}".format(
host=host,
port=port
)
if username is not None and password is not None:
url = "http://{username}:{password}@{host}:{port}".format(
host=host,
port=port,
username=username,
password=password
)
log.info("Connecting to CouchDB server at {}".format(url))
return couchdb.Server(url)
| import os
import yaml
import couchdb
from cloudly.memoized import Memoized
import cloudly.logger as logger
log = logger.init(__name__)
@Memoized
def get_server(hostname=None, port=None, username=None, password=None):
host = hostname or os.environ.get("COUCHDB_HOST", "127.0.0.1")
port = port or os.environ.get("COUCHDB_PORT", 5984)
username = username or os.environ.get("COUCHDB_USERNAME", None)
password = password or os.environ.get("COUCHDB_PASSWORD", None)
if username is not None and password is not None:
url = "http://{username}:{password}@{host}:{port}".format(
host=host,
port=port,
username=username,
password=password
)
else:
url = "http://{host}:{port}".format(
host=host,
port=port
)
log.info("{} port {}".format(host, port))
return couchdb.Server(url)
def sync_design_doc(database, design_filename):
"""Sync a design document written as a YAML file."""
with open(design_filename) as design_file:
design_doc = yaml.load(design_file)
# Delete old document, to avoid ResourceConflict exceptions.
old = database.get(design_doc['_id'])
if old:
database.delete(old)
database.save(design_doc)
| Add auth and a function to sync a design doc. | Add auth and a function to sync a design doc.
With environment variables COUCHDB_USERNAME and COUCHDB_PASSWORD defined, will
connect as that user.
Now uses COUCHDB_PORT if defined.
Add a function to save a design document defined as a YAML file. Why YAML?
Because it's very easy to add Javascript code with syntax highlighting. Plus,
the general format is even lighter than other format like JSON.
| Python | mit | ooda/cloudly,ooda/cloudly | python | ## Code Before:
import os
import couchdb
from cloudly.memoized import Memoized
import cloudly.logger as logger
log = logger.init(__name__)
@Memoized
def get_server(hostname=None, port=5984, username=None, password=None):
port = 5984
host = hostname or os.environ.get("COUCHDB_HOST", "127.0.0.1")
url = "http://{host}:{port}".format(
host=host,
port=port
)
if username is not None and password is not None:
url = "http://{username}:{password}@{host}:{port}".format(
host=host,
port=port,
username=username,
password=password
)
log.info("Connecting to CouchDB server at {}".format(url))
return couchdb.Server(url)
## Instruction:
Add auth and a function to sync a design doc.
With environment variables COUCHDB_USERNAME and COUCHDB_PASSWORD defined, will
connect as that user.
Now uses COUCHDB_PORT if defined.
Add a function to save a design document defined as a YAML file. Why YAML?
Because it's very easy to add Javascript code with syntax highlighting. Plus,
the general format is even lighter than other format like JSON.
## Code After:
import os
import yaml
import couchdb
from cloudly.memoized import Memoized
import cloudly.logger as logger
log = logger.init(__name__)
@Memoized
def get_server(hostname=None, port=None, username=None, password=None):
host = hostname or os.environ.get("COUCHDB_HOST", "127.0.0.1")
port = port or os.environ.get("COUCHDB_PORT", 5984)
username = username or os.environ.get("COUCHDB_USERNAME", None)
password = password or os.environ.get("COUCHDB_PASSWORD", None)
if username is not None and password is not None:
url = "http://{username}:{password}@{host}:{port}".format(
host=host,
port=port,
username=username,
password=password
)
else:
url = "http://{host}:{port}".format(
host=host,
port=port
)
log.info("{} port {}".format(host, port))
return couchdb.Server(url)
def sync_design_doc(database, design_filename):
"""Sync a design document written as a YAML file."""
with open(design_filename) as design_file:
design_doc = yaml.load(design_file)
# Delete old document, to avoid ResourceConflict exceptions.
old = database.get(design_doc['_id'])
if old:
database.delete(old)
database.save(design_doc)
| import os
+ import yaml
import couchdb
from cloudly.memoized import Memoized
import cloudly.logger as logger
log = logger.init(__name__)
@Memoized
- def get_server(hostname=None, port=5984, username=None, password=None):
? ^^^^
+ def get_server(hostname=None, port=None, username=None, password=None):
? ^^^^
- port = 5984
host = hostname or os.environ.get("COUCHDB_HOST", "127.0.0.1")
+ port = port or os.environ.get("COUCHDB_PORT", 5984)
+ username = username or os.environ.get("COUCHDB_USERNAME", None)
+ password = password or os.environ.get("COUCHDB_PASSWORD", None)
- url = "http://{host}:{port}".format(
- host=host,
- port=port
- )
if username is not None and password is not None:
url = "http://{username}:{password}@{host}:{port}".format(
host=host,
port=port,
username=username,
password=password
)
+ else:
+ url = "http://{host}:{port}".format(
+ host=host,
+ port=port
+ )
- log.info("Connecting to CouchDB server at {}".format(url))
+ log.info("{} port {}".format(host, port))
return couchdb.Server(url)
+
+
+ def sync_design_doc(database, design_filename):
+ """Sync a design document written as a YAML file."""
+ with open(design_filename) as design_file:
+ design_doc = yaml.load(design_file)
+ # Delete old document, to avoid ResourceConflict exceptions.
+ old = database.get(design_doc['_id'])
+ if old:
+ database.delete(old)
+ database.save(design_doc) | 29 | 1 | 22 | 7 |
e2aa0a27bdb32a0d37b39bebcb4b2fcf54c688b1 | install.sh | install.sh | cd vendor
# Declare libraries to install
declare -A libraries
libraries["ATP"]="www.evilinnocence.com:/var/git/ATP.git"
libraries["ATPCore"]="www.evilinnocence.com:/var/git/atp-modules/ATPCore.git"
libraries["Assetic"]="https://github.com/kriswallsmith/assetic.git"
libraries["AssetManager"]="https://github.com/RWOverdijk/AssetManager.git"
libraries["ZF2"]="https://github.com/zendframework/zf2.git"
# Loop over libraries and install
for dir in "${!libraries[@]}"
do
# Let us know which library is being processed
echo "Installing ${libraries[$dir]} in vendor/$dir"
# Check to see if the library is already installed
if [ ! -d "$dir" ]; then
# Create the directory and switch to it
mkdir "$dir"
cd "$dir"
# Checkout the library
git clone "${libraries[$dir]}" .
# Go back up to the vendor directory
cd ..
else
# Let us know that the library is already installed
echo " - $dir already installed."
fi
done
| cd vendor
# Declare libraries to install
declare -A libraries
libraries["ATP"]="https://github.com/DaemonAlchemist/atp-base.git"
libraries["ATPAdmin"]="https://github.com/DaemonAlchemist/atp-admin.git"
libraries["ATPCms"]="https://github.com/DaemonAlchemist/atp-cms.git"
libraries["ATPCore"]="https://github.com/DaemonAlchemist/atp-core.git"
libraries["Assetic"]="https://github.com/kriswallsmith/assetic.git"
libraries["AssetManager"]="https://github.com/RWOverdijk/AssetManager.git"
libraries["ZF2"]="https://github.com/zendframework/zf2.git"
# Loop over libraries and install
for dir in "${!libraries[@]}"
do
# Let us know which library is being processed
echo "Installing ${libraries[$dir]} in vendor/$dir"
# Check to see if the library is already installed
if [ ! -d "$dir" ]; then
# Create the directory and switch to it
mkdir "$dir"
cd "$dir"
# Checkout the library
git clone "${libraries[$dir]}" .
# Go back up to the vendor directory
cd ..
else
# Let us know that the library is already installed
echo " - $dir already installed."
fi
done
| USe Github repos instead of originals | USe Github repos instead of originals
| Shell | mit | DaemonAlchemist/atp-base,DaemonAlchemist/atp-base,DaemonAlchemist/atp-base | shell | ## Code Before:
cd vendor
# Declare libraries to install
declare -A libraries
libraries["ATP"]="www.evilinnocence.com:/var/git/ATP.git"
libraries["ATPCore"]="www.evilinnocence.com:/var/git/atp-modules/ATPCore.git"
libraries["Assetic"]="https://github.com/kriswallsmith/assetic.git"
libraries["AssetManager"]="https://github.com/RWOverdijk/AssetManager.git"
libraries["ZF2"]="https://github.com/zendframework/zf2.git"
# Loop over libraries and install
for dir in "${!libraries[@]}"
do
# Let us know which library is being processed
echo "Installing ${libraries[$dir]} in vendor/$dir"
# Check to see if the library is already installed
if [ ! -d "$dir" ]; then
# Create the directory and switch to it
mkdir "$dir"
cd "$dir"
# Checkout the library
git clone "${libraries[$dir]}" .
# Go back up to the vendor directory
cd ..
else
# Let us know that the library is already installed
echo " - $dir already installed."
fi
done
## Instruction:
USe Github repos instead of originals
## Code After:
cd vendor
# Declare libraries to install
declare -A libraries
libraries["ATP"]="https://github.com/DaemonAlchemist/atp-base.git"
libraries["ATPAdmin"]="https://github.com/DaemonAlchemist/atp-admin.git"
libraries["ATPCms"]="https://github.com/DaemonAlchemist/atp-cms.git"
libraries["ATPCore"]="https://github.com/DaemonAlchemist/atp-core.git"
libraries["Assetic"]="https://github.com/kriswallsmith/assetic.git"
libraries["AssetManager"]="https://github.com/RWOverdijk/AssetManager.git"
libraries["ZF2"]="https://github.com/zendframework/zf2.git"
# Loop over libraries and install
for dir in "${!libraries[@]}"
do
# Let us know which library is being processed
echo "Installing ${libraries[$dir]} in vendor/$dir"
# Check to see if the library is already installed
if [ ! -d "$dir" ]; then
# Create the directory and switch to it
mkdir "$dir"
cd "$dir"
# Checkout the library
git clone "${libraries[$dir]}" .
# Go back up to the vendor directory
cd ..
else
# Let us know that the library is already installed
echo " - $dir already installed."
fi
done
| cd vendor
# Declare libraries to install
declare -A libraries
- libraries["ATP"]="www.evilinnocence.com:/var/git/ATP.git"
- libraries["ATPCore"]="www.evilinnocence.com:/var/git/atp-modules/ATPCore.git"
+ libraries["ATP"]="https://github.com/DaemonAlchemist/atp-base.git"
+ libraries["ATPAdmin"]="https://github.com/DaemonAlchemist/atp-admin.git"
+ libraries["ATPCms"]="https://github.com/DaemonAlchemist/atp-cms.git"
+ libraries["ATPCore"]="https://github.com/DaemonAlchemist/atp-core.git"
libraries["Assetic"]="https://github.com/kriswallsmith/assetic.git"
libraries["AssetManager"]="https://github.com/RWOverdijk/AssetManager.git"
libraries["ZF2"]="https://github.com/zendframework/zf2.git"
# Loop over libraries and install
for dir in "${!libraries[@]}"
do
# Let us know which library is being processed
echo "Installing ${libraries[$dir]} in vendor/$dir"
# Check to see if the library is already installed
if [ ! -d "$dir" ]; then
# Create the directory and switch to it
mkdir "$dir"
cd "$dir"
# Checkout the library
git clone "${libraries[$dir]}" .
# Go back up to the vendor directory
cd ..
else
# Let us know that the library is already installed
echo " - $dir already installed."
fi
done | 6 | 0.1875 | 4 | 2 |
9d4d975f4133ce3c86f960a118e98ff603914992 | public/js/webtail.js | public/js/webtail.js | var Webtail = {
run: function(port) {
var self = this;
jQuery(function($) {
var socket = new (WebSocket || MozWebSocket)('ws://localhost:' + port),
body = $('body');
self.onmessages.push(function(message) {
// To ignore serial empty lines
if (message.data == '\n' && $('pre:last').text() == '\n') return;
// Insert a new line
$('<pre>').text(message.data).appendTo('body');
// Scroll to bottom of the page
$('html, body').scrollTop($(document).height());
// Trigger onmessage event
body.trigger('onmessage');
});
socket.onmessage = function(message) {
$.each(self.onmessages, function() { this(message) });
};
});
},
onmessages: []
};
| var Webtail = {
run: function(port) {
var self = this;
jQuery(function($) {
var socket = new (WebSocket || MozWebSocket)('ws://localhost:' + port);
socket.onmessage = function(message) {
$.each(self.onmessages, function() { this(message) });
};
});
},
onmessages: [
function(message) {
// To ignore serial empty lines
if (message.data == '\n' && $('pre:last').text() == '\n') return;
// Insert a new line
$('<pre>').text(message.data).appendTo('body');
// Scroll to bottom of the page
$('html, body').scrollTop($(document).height());
}
]
};
| Fix the execution sequence of onmessage callbacks | Fix the execution sequence of onmessage callbacks
| JavaScript | mit | r7kamura/webtail,synthdnb/webtail,synthdnb/webtail,r7kamura/webtail,synthdnb/webtail,r7kamura/webtail | javascript | ## Code Before:
var Webtail = {
run: function(port) {
var self = this;
jQuery(function($) {
var socket = new (WebSocket || MozWebSocket)('ws://localhost:' + port),
body = $('body');
self.onmessages.push(function(message) {
// To ignore serial empty lines
if (message.data == '\n' && $('pre:last').text() == '\n') return;
// Insert a new line
$('<pre>').text(message.data).appendTo('body');
// Scroll to bottom of the page
$('html, body').scrollTop($(document).height());
// Trigger onmessage event
body.trigger('onmessage');
});
socket.onmessage = function(message) {
$.each(self.onmessages, function() { this(message) });
};
});
},
onmessages: []
};
## Instruction:
Fix the execution sequence of onmessage callbacks
## Code After:
var Webtail = {
run: function(port) {
var self = this;
jQuery(function($) {
var socket = new (WebSocket || MozWebSocket)('ws://localhost:' + port);
socket.onmessage = function(message) {
$.each(self.onmessages, function() { this(message) });
};
});
},
onmessages: [
function(message) {
// To ignore serial empty lines
if (message.data == '\n' && $('pre:last').text() == '\n') return;
// Insert a new line
$('<pre>').text(message.data).appendTo('body');
// Scroll to bottom of the page
$('html, body').scrollTop($(document).height());
}
]
};
| var Webtail = {
run: function(port) {
var self = this;
-
jQuery(function($) {
- var socket = new (WebSocket || MozWebSocket)('ws://localhost:' + port),
? ^
+ var socket = new (WebSocket || MozWebSocket)('ws://localhost:' + port);
? ^
- body = $('body');
-
- self.onmessages.push(function(message) {
- // To ignore serial empty lines
- if (message.data == '\n' && $('pre:last').text() == '\n') return;
-
- // Insert a new line
- $('<pre>').text(message.data).appendTo('body');
-
- // Scroll to bottom of the page
- $('html, body').scrollTop($(document).height());
-
- // Trigger onmessage event
- body.trigger('onmessage');
- });
-
socket.onmessage = function(message) {
$.each(self.onmessages, function() { this(message) });
};
});
},
- onmessages: []
? -
+ onmessages: [
+ function(message) {
+ // To ignore serial empty lines
+ if (message.data == '\n' && $('pre:last').text() == '\n') return;
+
+ // Insert a new line
+ $('<pre>').text(message.data).appendTo('body');
+
+ // Scroll to bottom of the page
+ $('html, body').scrollTop($(document).height());
+ }
+ ]
}; | 32 | 1.066667 | 13 | 19 |
3b433e0aa1a8cbb9ec6e7b59843c74f820d7d75e | packages/core/admin/public/controllers/themes.js | packages/core/admin/public/controllers/themes.js | 'use strict';
angular.module('mean.admin').controller('ThemesController', ['$scope', 'Global', '$rootScope', '$http',
function($scope, Global, $rootScope, $http) {
$scope.global = Global;
$scope.themes = [];
$scope.init = function() {
$http({
method: 'GET',
url: 'http://api.bootswatch.com/3/'
}).
success(function(data, status, headers, config) {
$scope.themes = data.themes;
}).
error(function(data, status, headers, config) {
});
};
$scope.changeTheme = function(theme) {
// Will add preview options soon
// $('link').attr('href', theme.css);
// $scope.selectedTheme = theme;
$('.progress-striped').show();
$http.get('/api/admin/themes?theme=' + theme.css).
success(function(data, status, headers, config) {
if (data)
window.location.reload();
}).
error(function(data, status, headers, config) {
alert('error');
$('.progress-striped').hide();
});
};
$scope.defaultTheme = function() {
$http.get('/api/admin/themes/defaultTheme').
success(function(data, status, headers, config) {
if (data)
window.location.reload();
}).
error(function(data, status, headers, config) {
alert('error');
});
};
}
]);
| 'use strict';
angular.module('mean.admin').controller('ThemesController', ['$scope', 'Global', '$rootScope', '$http',
function($scope, Global, $rootScope, $http) {
$scope.global = Global;
$scope.themes = [];
$scope.init = function() {
$http({
method: 'GET',
url: 'http://api.bootswatch.com/3/',
skipAuthorization: true
}).
success(function(data, status, headers, config) {
$scope.themes = data.themes;
}).
error(function(data, status, headers, config) {
});
};
$scope.changeTheme = function(theme) {
// Will add preview options soon
// $('link').attr('href', theme.css);
// $scope.selectedTheme = theme;
$('.progress-striped').show();
$http.get('/api/admin/themes?theme=' + theme.css).
success(function(data, status, headers, config) {
if (data)
window.location.reload();
}).
error(function(data, status, headers, config) {
alert('error');
$('.progress-striped').hide();
});
};
$scope.defaultTheme = function() {
$http.get('/api/admin/themes/defaultTheme').
success(function(data, status, headers, config) {
if (data)
window.location.reload();
}).
error(function(data, status, headers, config) {
alert('error');
});
};
}
]);
| Fix for angular-jwt injecting authorization header | Fix for angular-jwt injecting authorization header
| JavaScript | mit | gscrazy1021/mean,bbayo4/Businness-Application-using-MEAN.IO-Stack,patrickkillalea/mean,fkiller/harvard,jun-oka/bee-news-jp-client-1,kushaltirumala/mean,victorantos/mean,wearska/mean-mono,hectorgool/mean-santix,gscrazy1021/mean,KHam0425/mean,hectorgool/mean-santix,ashblue/meanio-tutorial,cyberTrebuchet/this_is_forOM,paramananda/mean,ShlomyShivek/SchoolMate,rpalacios/preach-lander,marlonator/mean,darecki/mean,lvarayut/mean,steezeburger/jeannie,szrobinli/mean,dantepsychedelico/erp-tiny-system,komarudin02/Public,wearska/mean-mono,faisal00813/MEAN-Demo,salivatears/mean,kira1009/mean,lvarayut/mean,evanjenkins/alTestPlan,haftapparat/mean,vildantursic/vildan-mean,idhere703/meanSample,oritpersik/test,NenadP/blocks,michelwatson/bmr,hassanabidpk/mean,VikramTiwari/mean,nawasthi23/mean,telekomatrix/mean,marlonator/mean,rjVapes/mean,jackrosenhauer/nodebot-mean,xiaoking/mean,vildantursic/vildan-mean,zwhitchcox/mean,karademada/mean,alexmxu/mean,darecki/mean,Cneubauern/Test,yinhe007/mean,kushaltirumala/mean,xiaoking/mean,kira1009/mean,minzen/u-qasar-mean,dantepsychedelico/erp-tiny-system,oritpersik/test,stevenaldous/mean,salivatears/mean,elkingtonmcb/mean,suyesh/mean,kumaria/mean,TimWilkis/mean,joshsilverman/me,thinkDevDM/mean,JuanyiFeng/queueItUp,idhere703/meanSample,yosifgenchev/iPlayIt,Peretus/test-mean,dbachko/mean,rjVapes/mean,GrimDerp/mean,JuanyiFeng/queueItUp,lakhvinderit/mean,tmrotz/brad,ryanlhunt/sim_ventory,seeyew/help140mean,kumaria/mean,vebin/mean,fkiller/mean,pathirana/mean,evanjenkins/alTestPlan,bqevin/mean,vebin/mean,mstackpo/MattsMeanApp,fkiller/harvard,thinkDevDM/mean,vikram-bagga/zummy,albi34/mean,cyberTrebuchet/this_is_forOM,rutys/pictionary,telekomatrix/mean,komarudin02/Public,Muffasa/mean,JulienBreux/mean,smadjid/CoReaDa,rbecheras/mean-1,Biunovich/mean,tmrotz/brad,dbachko/mean,VeeteshJain/project_1000,GeminiLegend/myRelephant265,steezeburger/jeannie,goblortikus/stroop,cronos2546/mean,jdelagal/mean,misterdavemeister/meanio,jdelagal/mean,GrimDerp/mean,lekkas/mean,JulienBreux/mean,Lywangwenbin/mean,muthhus/mean,zcalyz/mean,andrescarceller/mean,oliverk120/notesnack2,Sharmaz/mean,rutys/pictionary,robort/mean,Biunovich/mean,TimWilkis/mean,bozzmob/mean,nawasthi23/mean,rncrtr/mean,anthony-ism/funari,rpalacios/preach-lander,tmrotz/brad,09saurabh09/vocal,tpsumeta/mean,tpsumeta/mean,jenavarro/AllRules,edivancamargo/mean,stevenaldous/mean,paramananda/mean,alexmxu/mean,kevinzli/meanforms,alannesta/mean-scaffold,karademada/mean,Peretus/test-mean,cronos2546/mean,pathirana/mean,spacetag/TechEx_Josiah,kaydeveloper/mean,michelwatson/bmr,Sharmaz/mean,sidhart/mean,Muffasa/mean,oritpersik/admin-dashboard,lekkas/mean,kevinzli/meanforms,mattkim/mean.io.tests,Shiftane/listedecourse2,dantepsychedelico/erp-tiny-system,nathanielltaylor/MEANkids,oliverk120/notesnack2,tedtkang/meanTestApp,maityneil001/mean,smadjid/CoReaDa,anthony-ism/funari,rachelleannmorales/meanApp,tedtkang/meanTestApp,oritpersik/admin-dashboard,minzen/u-qasar-mean,suyesh/mean,dantepsychedelico/erp-tiny-system,misterdavemeister/meanio,rbecheras/mean-1,goblortikus/stroop,yinhe007/mean,victorantos/mean,NenadP/blocks,devsaik/paropakar,abegit/mean,maityneil001/mean,mstackpo/MattsMeanApp,kaydeveloper/mean,ryanlhunt/sim_ventory,rncrtr/mean,GeminiLegend/myRelephant265,fkiller/mean,yosifgenchev/iPlayIt,hassanabidpk/mean,bentorfs/ddb,devsaik/paropakar,jun-oka/bee-news-jp-client-1,edivancamargo/mean,nathanielltaylor/MEANkids,Shiftane/listedecourse2,abegit/mean,VeeteshJain/project_1000,Cneubauern/Test,ShlomyShivek/SchoolMate,ashblue/meanio-tutorial,albi34/mean,bqevin/mean,zcalyz/mean,sidhart/mean,bozzmob/mean,zwhitchcox/mean,ascreven/mean.io,LukasK/mean,KHam0425/mean,seeyew/help140mean,bbayo4/Businness-Application-using-MEAN.IO-Stack,Lywangwenbin/mean,alexballera/mean,bentorfs/ddb,rutys/pictionary,robort/mean,joshsilverman/me,rachelleannmorales/meanApp,baskint/mean,dantix/mean,ascreven/mean.io,alannesta/mean-scaffold,yjkim1701/cmt-mgr,09saurabh09/vocal,misterdavemeister/meanio,lakhvinderit/mean,jackrosenhauer/nodebot-mean,mattkim/mean.io.tests,jenavarro/AllRules,mummamw/mean,alexballera/mean,bentorfs/ddb,szrobinli/mean,patrickkillalea/mean,muthhus/mean,dantix/mean,LukasK/mean,yjkim1701/cmt-mgr,faisal00813/MEAN-Demo,andrescarceller/mean,mummamw/mean,vikram-bagga/zummy,haftapparat/mean,spacetag/TechEx_Josiah,elkingtonmcb/mean,smadjid/CoReaDa,baskint/mean,VikramTiwari/mean | javascript | ## Code Before:
'use strict';
angular.module('mean.admin').controller('ThemesController', ['$scope', 'Global', '$rootScope', '$http',
function($scope, Global, $rootScope, $http) {
$scope.global = Global;
$scope.themes = [];
$scope.init = function() {
$http({
method: 'GET',
url: 'http://api.bootswatch.com/3/'
}).
success(function(data, status, headers, config) {
$scope.themes = data.themes;
}).
error(function(data, status, headers, config) {
});
};
$scope.changeTheme = function(theme) {
// Will add preview options soon
// $('link').attr('href', theme.css);
// $scope.selectedTheme = theme;
$('.progress-striped').show();
$http.get('/api/admin/themes?theme=' + theme.css).
success(function(data, status, headers, config) {
if (data)
window.location.reload();
}).
error(function(data, status, headers, config) {
alert('error');
$('.progress-striped').hide();
});
};
$scope.defaultTheme = function() {
$http.get('/api/admin/themes/defaultTheme').
success(function(data, status, headers, config) {
if (data)
window.location.reload();
}).
error(function(data, status, headers, config) {
alert('error');
});
};
}
]);
## Instruction:
Fix for angular-jwt injecting authorization header
## Code After:
'use strict';
angular.module('mean.admin').controller('ThemesController', ['$scope', 'Global', '$rootScope', '$http',
function($scope, Global, $rootScope, $http) {
$scope.global = Global;
$scope.themes = [];
$scope.init = function() {
$http({
method: 'GET',
url: 'http://api.bootswatch.com/3/',
skipAuthorization: true
}).
success(function(data, status, headers, config) {
$scope.themes = data.themes;
}).
error(function(data, status, headers, config) {
});
};
$scope.changeTheme = function(theme) {
// Will add preview options soon
// $('link').attr('href', theme.css);
// $scope.selectedTheme = theme;
$('.progress-striped').show();
$http.get('/api/admin/themes?theme=' + theme.css).
success(function(data, status, headers, config) {
if (data)
window.location.reload();
}).
error(function(data, status, headers, config) {
alert('error');
$('.progress-striped').hide();
});
};
$scope.defaultTheme = function() {
$http.get('/api/admin/themes/defaultTheme').
success(function(data, status, headers, config) {
if (data)
window.location.reload();
}).
error(function(data, status, headers, config) {
alert('error');
});
};
}
]);
| 'use strict';
angular.module('mean.admin').controller('ThemesController', ['$scope', 'Global', '$rootScope', '$http',
function($scope, Global, $rootScope, $http) {
$scope.global = Global;
$scope.themes = [];
$scope.init = function() {
$http({
method: 'GET',
- url: 'http://api.bootswatch.com/3/'
+ url: 'http://api.bootswatch.com/3/',
? +
+ skipAuthorization: true
}).
success(function(data, status, headers, config) {
$scope.themes = data.themes;
}).
error(function(data, status, headers, config) {
});
};
$scope.changeTheme = function(theme) {
// Will add preview options soon
// $('link').attr('href', theme.css);
// $scope.selectedTheme = theme;
$('.progress-striped').show();
$http.get('/api/admin/themes?theme=' + theme.css).
success(function(data, status, headers, config) {
if (data)
window.location.reload();
}).
error(function(data, status, headers, config) {
alert('error');
$('.progress-striped').hide();
});
};
$scope.defaultTheme = function() {
$http.get('/api/admin/themes/defaultTheme').
success(function(data, status, headers, config) {
if (data)
window.location.reload();
}).
error(function(data, status, headers, config) {
alert('error');
});
};
}
]); | 3 | 0.06 | 2 | 1 |
77049f21bb8f357c26488fb084bd4719f2937cc0 | test/detect/swift/default.txt | test/detect/swift/default.txt | extension MyClass : Interface {
class func unarchiveFromFile<A>(file : A, (Int,Int) -> B) -> SKNode? {
let path: String = bundle.pathForResource(file, ofType: "file\(name + 5).txt")
let funnyNumber = 3 + 0xC2.15p2 * (1_000_000.000_000_1 - 000123.456) + 0o21
var sceneData = NSData.dataWithContentsOfFile(path, options: .DataReadingMappedIfSafe, error: nil)
/* a comment /* with a nested comment */ and the end */
}
@objc override func shouldAutorotate() {
return true
}
}
| import Foundation
@objc class Person: Entity {
var name: String!
var age: Int!
init(name: String, age: Int) {
/* /* ... */ */
}
// Return a descriptive string for this person
func description(offset: Int = 0) -> String {
return "\(name) is \(age + offset) years old"
}
}
| Use Swift detect snippet from highlightjs.org | Use Swift detect snippet from highlightjs.org
It's a good test as it is mis-detected as QML. We probably should
update all the detect snippets with those used on the site and *then*
switch site to using those from the code.
| Text | bsd-3-clause | carlokok/highlight.js,StanislawSwierc/highlight.js,palmin/highlight.js,carlokok/highlight.js,aurusov/highlight.js,highlightjs/highlight.js,MakeNowJust/highlight.js,highlightjs/highlight.js,carlokok/highlight.js,isagalaev/highlight.js,bluepichu/highlight.js,palmin/highlight.js,Sannis/highlight.js,StanislawSwierc/highlight.js,aurusov/highlight.js,aurusov/highlight.js,carlokok/highlight.js,sourrust/highlight.js,MakeNowJust/highlight.js,highlightjs/highlight.js,teambition/highlight.js,Sannis/highlight.js,palmin/highlight.js,bluepichu/highlight.js,Sannis/highlight.js,MakeNowJust/highlight.js,teambition/highlight.js,bluepichu/highlight.js,sourrust/highlight.js,isagalaev/highlight.js,highlightjs/highlight.js,sourrust/highlight.js,lead-auth/highlight.js,teambition/highlight.js | text | ## Code Before:
extension MyClass : Interface {
class func unarchiveFromFile<A>(file : A, (Int,Int) -> B) -> SKNode? {
let path: String = bundle.pathForResource(file, ofType: "file\(name + 5).txt")
let funnyNumber = 3 + 0xC2.15p2 * (1_000_000.000_000_1 - 000123.456) + 0o21
var sceneData = NSData.dataWithContentsOfFile(path, options: .DataReadingMappedIfSafe, error: nil)
/* a comment /* with a nested comment */ and the end */
}
@objc override func shouldAutorotate() {
return true
}
}
## Instruction:
Use Swift detect snippet from highlightjs.org
It's a good test as it is mis-detected as QML. We probably should
update all the detect snippets with those used on the site and *then*
switch site to using those from the code.
## Code After:
import Foundation
@objc class Person: Entity {
var name: String!
var age: Int!
init(name: String, age: Int) {
/* /* ... */ */
}
// Return a descriptive string for this person
func description(offset: Int = 0) -> String {
return "\(name) is \(age + offset) years old"
}
}
| - extension MyClass : Interface {
- class func unarchiveFromFile<A>(file : A, (Int,Int) -> B) -> SKNode? {
- let path: String = bundle.pathForResource(file, ofType: "file\(name + 5).txt")
- let funnyNumber = 3 + 0xC2.15p2 * (1_000_000.000_000_1 - 000123.456) + 0o21
- var sceneData = NSData.dataWithContentsOfFile(path, options: .DataReadingMappedIfSafe, error: nil)
- /* a comment /* with a nested comment */ and the end */
+ import Foundation
+
+ @objc class Person: Entity {
+ var name: String!
+ var age: Int!
+
+ init(name: String, age: Int) {
+ /* /* ... */ */
- }
? --
+ }
- @objc override func shouldAutorotate() {
- return true
+
+ // Return a descriptive string for this person
+ func description(offset: Int = 0) -> String {
+ return "\(name) is \(age + offset) years old"
- }
? --
+ }
} | 24 | 2.181818 | 14 | 10 |
e1ccd2ac7687a73e008c72a13ec52a0ed2acea2a | README.md | README.md |
[](https://travis-ci.org/instructure/ims-lti)
#Version 2.x is currently BETA
LTI ruby implementation
## Installation
Add this line to your application's Gemfile:
gem 'lti'
And then execute:
$ bundle
Or install it yourself as:
$ gem install lti
## Contributing
1. Fork it ( http://github.com/instructure/lti/fork )
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request
|
[](https://travis-ci.org/instructure/ims-lti)
#Version 2.x is currently BETA
LTI ruby implementation
## Installation
Add this line to your application's Gemfile:
gem 'lti'
And then execute:
$ bundle
Or install it yourself as:
$ gem install lti
## Usage
### LTI 1.x
#### Validating Launches
You can use the classes in the IMS::LTI::Models::Messages module to valdiate Launches
For example in a rails app you would do the following
```ruby
lti_message = IMS::LTI::Models::Messages::Message.generate(request.request_parameters.merge(request.query_parameters))
lti_message.launch_url = request.url
#Check if the signature is valid
return false unless lti_message.valid_signature?(shared_secret)
# check if `lti_message.oauth_nonce` is already been used
#check if the message is too old
return false if DateTime.strptime(lti_message.oauth_timestamp,'%s') > 5.minutes.ago
```
## Contributing
1. Fork it ( http://github.com/instructure/lti/fork )
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request
| Add documentation for verifying LTI 1.x messages | Add documentation for verifying LTI 1.x messages | Markdown | mit | instructure/ims-lti | markdown | ## Code Before:
[](https://travis-ci.org/instructure/ims-lti)
#Version 2.x is currently BETA
LTI ruby implementation
## Installation
Add this line to your application's Gemfile:
gem 'lti'
And then execute:
$ bundle
Or install it yourself as:
$ gem install lti
## Contributing
1. Fork it ( http://github.com/instructure/lti/fork )
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request
## Instruction:
Add documentation for verifying LTI 1.x messages
## Code After:
[](https://travis-ci.org/instructure/ims-lti)
#Version 2.x is currently BETA
LTI ruby implementation
## Installation
Add this line to your application's Gemfile:
gem 'lti'
And then execute:
$ bundle
Or install it yourself as:
$ gem install lti
## Usage
### LTI 1.x
#### Validating Launches
You can use the classes in the IMS::LTI::Models::Messages module to valdiate Launches
For example in a rails app you would do the following
```ruby
lti_message = IMS::LTI::Models::Messages::Message.generate(request.request_parameters.merge(request.query_parameters))
lti_message.launch_url = request.url
#Check if the signature is valid
return false unless lti_message.valid_signature?(shared_secret)
# check if `lti_message.oauth_nonce` is already been used
#check if the message is too old
return false if DateTime.strptime(lti_message.oauth_timestamp,'%s') > 5.minutes.ago
```
## Contributing
1. Fork it ( http://github.com/instructure/lti/fork )
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request
|
[](https://travis-ci.org/instructure/ims-lti)
#Version 2.x is currently BETA
LTI ruby implementation
## Installation
Add this line to your application's Gemfile:
gem 'lti'
And then execute:
$ bundle
Or install it yourself as:
$ gem install lti
+ ## Usage
+
+
+ ### LTI 1.x
+
+ #### Validating Launches
+
+ You can use the classes in the IMS::LTI::Models::Messages module to valdiate Launches
+
+ For example in a rails app you would do the following
+ ```ruby
+ lti_message = IMS::LTI::Models::Messages::Message.generate(request.request_parameters.merge(request.query_parameters))
+ lti_message.launch_url = request.url
+
+ #Check if the signature is valid
+ return false unless lti_message.valid_signature?(shared_secret)
+
+ # check if `lti_message.oauth_nonce` is already been used
+
+ #check if the message is too old
+ return false if DateTime.strptime(lti_message.oauth_timestamp,'%s') > 5.minutes.ago
+
+ ```
## Contributing
1. Fork it ( http://github.com/instructure/lti/fork )
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request | 23 | 0.793103 | 23 | 0 |
b09c0a080c61a503b3df090ae0b554cffdc2b45a | test/javascripts/views/paper_edit_view_test.js.coffee | test/javascripts/views/paper_edit_view_test.js.coffee | moduleFor 'view:paperEdit', 'Unit: paperEditView',
teardown: ->
ETahi.VisualEditorService.create.restore()
ETahi.reset()
setup: ->
paper = Ember.Object.create
title: ''
shortTitle: 'Does not matter'
body: 'hello'
sinon.stub(ETahi.VisualEditorService, 'create').returns
enable: ->
disable: ->
controller = ETahi.__container__.lookup 'controller:paperEdit'
@subject().set 'controller', controller
controller.set 'content', paper
sinon.stub @subject(), 'updateVisualEditor'
@subject().setupVisualEditor()
test 'when the paper is being edited, do not update editor on body change', ->
@subject().set('isEditing', true)
@subject().updateVisualEditor.reset()
@subject().set('controller.body', 'foo')
ok !@subject().updateVisualEditor.called
test 'when the paper is not being edited, update editor on body change', ->
@subject().set('isEditing', false)
@subject().updateVisualEditor.reset()
@subject().set('controller.body', 'foo')
ok @subject().updateVisualEditor.called
| moduleFor 'view:paperEdit', 'Unit: paperEditView',
teardown: ->
ETahi.VisualEditorService.create.restore()
ETahi.reset()
setup: ->
paper = Ember.Object.create
id: 5
title: ''
shortTitle: 'Does not matter'
body: 'hello'
sinon.stub(ETahi.VisualEditorService, 'create').returns
enable: ->
disable: ->
controller = ETahi.__container__.lookup 'controller:paperEdit'
@subject().set 'controller', controller
controller.set 'content', paper
sinon.stub @subject(), 'updateVisualEditor'
@subject().setupVisualEditor()
test 'when the paper is being edited, do not update editor on body change', ->
@subject().set('isEditing', true)
@subject().updateVisualEditor.reset()
@subject().set('controller.body', 'foo')
ok !@subject().updateVisualEditor.called
test 'when the paper is not being edited, update editor on body change', ->
@subject().set('isEditing', false)
@subject().updateVisualEditor.reset()
@subject().set('controller.body', 'foo')
ok @subject().updateVisualEditor.called
| Add missing id to paper test data. | Add missing id to paper test data.
The associated tests were throwing an error when the paper id
was undefined.
| CoffeeScript | mit | johan--/tahi,johan--/tahi,johan--/tahi,johan--/tahi | coffeescript | ## Code Before:
moduleFor 'view:paperEdit', 'Unit: paperEditView',
teardown: ->
ETahi.VisualEditorService.create.restore()
ETahi.reset()
setup: ->
paper = Ember.Object.create
title: ''
shortTitle: 'Does not matter'
body: 'hello'
sinon.stub(ETahi.VisualEditorService, 'create').returns
enable: ->
disable: ->
controller = ETahi.__container__.lookup 'controller:paperEdit'
@subject().set 'controller', controller
controller.set 'content', paper
sinon.stub @subject(), 'updateVisualEditor'
@subject().setupVisualEditor()
test 'when the paper is being edited, do not update editor on body change', ->
@subject().set('isEditing', true)
@subject().updateVisualEditor.reset()
@subject().set('controller.body', 'foo')
ok !@subject().updateVisualEditor.called
test 'when the paper is not being edited, update editor on body change', ->
@subject().set('isEditing', false)
@subject().updateVisualEditor.reset()
@subject().set('controller.body', 'foo')
ok @subject().updateVisualEditor.called
## Instruction:
Add missing id to paper test data.
The associated tests were throwing an error when the paper id
was undefined.
## Code After:
moduleFor 'view:paperEdit', 'Unit: paperEditView',
teardown: ->
ETahi.VisualEditorService.create.restore()
ETahi.reset()
setup: ->
paper = Ember.Object.create
id: 5
title: ''
shortTitle: 'Does not matter'
body: 'hello'
sinon.stub(ETahi.VisualEditorService, 'create').returns
enable: ->
disable: ->
controller = ETahi.__container__.lookup 'controller:paperEdit'
@subject().set 'controller', controller
controller.set 'content', paper
sinon.stub @subject(), 'updateVisualEditor'
@subject().setupVisualEditor()
test 'when the paper is being edited, do not update editor on body change', ->
@subject().set('isEditing', true)
@subject().updateVisualEditor.reset()
@subject().set('controller.body', 'foo')
ok !@subject().updateVisualEditor.called
test 'when the paper is not being edited, update editor on body change', ->
@subject().set('isEditing', false)
@subject().updateVisualEditor.reset()
@subject().set('controller.body', 'foo')
ok @subject().updateVisualEditor.called
| moduleFor 'view:paperEdit', 'Unit: paperEditView',
teardown: ->
ETahi.VisualEditorService.create.restore()
ETahi.reset()
setup: ->
paper = Ember.Object.create
+ id: 5
title: ''
shortTitle: 'Does not matter'
body: 'hello'
sinon.stub(ETahi.VisualEditorService, 'create').returns
enable: ->
disable: ->
controller = ETahi.__container__.lookup 'controller:paperEdit'
@subject().set 'controller', controller
controller.set 'content', paper
sinon.stub @subject(), 'updateVisualEditor'
@subject().setupVisualEditor()
test 'when the paper is being edited, do not update editor on body change', ->
@subject().set('isEditing', true)
@subject().updateVisualEditor.reset()
@subject().set('controller.body', 'foo')
ok !@subject().updateVisualEditor.called
test 'when the paper is not being edited, update editor on body change', ->
@subject().set('isEditing', false)
@subject().updateVisualEditor.reset()
@subject().set('controller.body', 'foo')
ok @subject().updateVisualEditor.called | 1 | 0.027027 | 1 | 0 |
0d6e4e06e01f812cfb6ca8490051766c02b7a2d4 | node/pm2Config.json | node/pm2Config.json | {
"apps": [
{
"name": "Robot",
"script": "index.js",
"max_memory_restart": "1G",
"merge_logs": true,
"exec_interpreter": "node"
},
{
"name": "Mycroft Service",
"script": "start.sh",
"cwd": "../mycroft-core/",
"args": [
"service"
],
"exec_interpreter": "bash",
"exec_mode": "fork_mode",
"max_memory_restart": "100M"
},
{
"name": "Mycroft Skills",
"script": "start.sh",
"cwd": "../mycroft-core/",
"args": [
"skills"
],
"exec_interpreter": "bash",
"exec_mode": "fork_mode",
"max_memory_restart": "100M"
},
{
"name": "Mycroft Voice",
"script": "start.sh",
"cwd": "../mycroft-core/",
"args": [
"voice"
],
"exec_interpreter": "bash",
"exec_mode": "fork_mode",
"max_memory_restart": "100M"
}
]
}
| {
"apps": [
{
"name": "Robot",
"script": "index.js",
"max_memory_restart": "1G",
"merge_logs": true,
"exec_interpreter": "node",
"log_date_format" : "YYYY-MM-DD HH:mm Z"
}
]
}
| Remove Mycroft from PM2 services. | Remove Mycroft from PM2 services.
| JSON | mit | DTU-R3/ArloBot,DTU-R3/ArloBot,chrisl8/ArloBot,chrisl8/ArloBot,DTU-R3/ArloBot,DTU-R3/ArloBot,chrisl8/ArloBot,chrisl8/ArloBot,DTU-R3/ArloBot,DTU-R3/ArloBot,chrisl8/ArloBot,chrisl8/ArloBot | json | ## Code Before:
{
"apps": [
{
"name": "Robot",
"script": "index.js",
"max_memory_restart": "1G",
"merge_logs": true,
"exec_interpreter": "node"
},
{
"name": "Mycroft Service",
"script": "start.sh",
"cwd": "../mycroft-core/",
"args": [
"service"
],
"exec_interpreter": "bash",
"exec_mode": "fork_mode",
"max_memory_restart": "100M"
},
{
"name": "Mycroft Skills",
"script": "start.sh",
"cwd": "../mycroft-core/",
"args": [
"skills"
],
"exec_interpreter": "bash",
"exec_mode": "fork_mode",
"max_memory_restart": "100M"
},
{
"name": "Mycroft Voice",
"script": "start.sh",
"cwd": "../mycroft-core/",
"args": [
"voice"
],
"exec_interpreter": "bash",
"exec_mode": "fork_mode",
"max_memory_restart": "100M"
}
]
}
## Instruction:
Remove Mycroft from PM2 services.
## Code After:
{
"apps": [
{
"name": "Robot",
"script": "index.js",
"max_memory_restart": "1G",
"merge_logs": true,
"exec_interpreter": "node",
"log_date_format" : "YYYY-MM-DD HH:mm Z"
}
]
}
| {
"apps": [
{
"name": "Robot",
"script": "index.js",
"max_memory_restart": "1G",
"merge_logs": true,
- "exec_interpreter": "node"
+ "exec_interpreter": "node",
? +
+ "log_date_format" : "YYYY-MM-DD HH:mm Z"
- },
- {
- "name": "Mycroft Service",
- "script": "start.sh",
- "cwd": "../mycroft-core/",
- "args": [
- "service"
- ],
- "exec_interpreter": "bash",
- "exec_mode": "fork_mode",
- "max_memory_restart": "100M"
- },
- {
- "name": "Mycroft Skills",
- "script": "start.sh",
- "cwd": "../mycroft-core/",
- "args": [
- "skills"
- ],
- "exec_interpreter": "bash",
- "exec_mode": "fork_mode",
- "max_memory_restart": "100M"
- },
- {
- "name": "Mycroft Voice",
- "script": "start.sh",
- "cwd": "../mycroft-core/",
- "args": [
- "voice"
- ],
- "exec_interpreter": "bash",
- "exec_mode": "fork_mode",
- "max_memory_restart": "100M"
}
]
} | 36 | 0.818182 | 2 | 34 |
04668cafe91af07c9ab70eab75cf094edc38660b | docs/getting_started.rst | docs/getting_started.rst |
Getting Started
===============
============
Requirements
============
The main language is Python 3 with Numpy, Scipy and Matplotlib.
The `Atomic Simulation Environment <https://wiki.fysik.dtu.dk/ase>`_
(ASE) is required for some components, as is `spglib <http://atztogo.github.io/spglib>`_.
============
Installation
============
For the latest stable release simply use
.. code::
pip install smact
Or for the latest master branch from the Git repo
.. code::
pip install git+git://github.com/WMD-group/SMACT.git
Then ensure that the location of :mod:`smact` is on your PYTHONPATH.
|
Getting Started
===============
============
Requirements
============
The main language is Python 3 and has been tested using Python 3.6+. Basic requirements are Numpy and Scipy.
spglib, and pymatgen are also required for many components.
The `Atomic Simulation Environment <https://wiki.fysik.dtu.dk/ase>`_
(ASE), `spglib <http://atztogo.github.io/spglib>`_,
and `pymatgen <http://pymatgen.org>`_ are also required for many components.
============
Installation
============
The latest stable release of SMACT can be installed via pip which will automatically setup other Python packages as required:
.. code::
pip install smact
Alternatively, the latest master branch from the Git repo can be installed using:
.. code::
pip install git+git://github.com/WMD-group/SMACT.git
Then ensure that the location of :mod:`smact` is on your PYTHONPATH.
For developer installation SMACT can be installed from a copy of the source repository (https://github.com/wmd-group/smact);
this will be preferred if using experimental code branches.
To clone the project from Github and make a local installation:
.. code::
git clone https://github.com/wmd-group/smact.git
cd smact
pip install --user -e .
With -e pip will create links to the source folder so that that changes to the code will be immediately reflected on the PATH.
| Update docs to match installation and requirements advice in README | Update docs to match installation and requirements advice in README
| reStructuredText | mit | WMD-group/SMACT | restructuredtext | ## Code Before:
Getting Started
===============
============
Requirements
============
The main language is Python 3 with Numpy, Scipy and Matplotlib.
The `Atomic Simulation Environment <https://wiki.fysik.dtu.dk/ase>`_
(ASE) is required for some components, as is `spglib <http://atztogo.github.io/spglib>`_.
============
Installation
============
For the latest stable release simply use
.. code::
pip install smact
Or for the latest master branch from the Git repo
.. code::
pip install git+git://github.com/WMD-group/SMACT.git
Then ensure that the location of :mod:`smact` is on your PYTHONPATH.
## Instruction:
Update docs to match installation and requirements advice in README
## Code After:
Getting Started
===============
============
Requirements
============
The main language is Python 3 and has been tested using Python 3.6+. Basic requirements are Numpy and Scipy.
spglib, and pymatgen are also required for many components.
The `Atomic Simulation Environment <https://wiki.fysik.dtu.dk/ase>`_
(ASE), `spglib <http://atztogo.github.io/spglib>`_,
and `pymatgen <http://pymatgen.org>`_ are also required for many components.
============
Installation
============
The latest stable release of SMACT can be installed via pip which will automatically setup other Python packages as required:
.. code::
pip install smact
Alternatively, the latest master branch from the Git repo can be installed using:
.. code::
pip install git+git://github.com/WMD-group/SMACT.git
Then ensure that the location of :mod:`smact` is on your PYTHONPATH.
For developer installation SMACT can be installed from a copy of the source repository (https://github.com/wmd-group/smact);
this will be preferred if using experimental code branches.
To clone the project from Github and make a local installation:
.. code::
git clone https://github.com/wmd-group/smact.git
cd smact
pip install --user -e .
With -e pip will create links to the source folder so that that changes to the code will be immediately reflected on the PATH.
|
Getting Started
===============
============
Requirements
============
- The main language is Python 3 with Numpy, Scipy and Matplotlib.
+ The main language is Python 3 and has been tested using Python 3.6+. Basic requirements are Numpy and Scipy.
+ spglib, and pymatgen are also required for many components.
The `Atomic Simulation Environment <https://wiki.fysik.dtu.dk/ase>`_
- (ASE) is required for some components, as is `spglib <http://atztogo.github.io/spglib>`_.
+ (ASE), `spglib <http://atztogo.github.io/spglib>`_,
+ and `pymatgen <http://pymatgen.org>`_ are also required for many components.
============
Installation
============
- For the latest stable release simply use
+ The latest stable release of SMACT can be installed via pip which will automatically setup other Python packages as required:
.. code::
pip install smact
- Or for the latest master branch from the Git repo
+ Alternatively, the latest master branch from the Git repo can be installed using:
.. code::
pip install git+git://github.com/WMD-group/SMACT.git
Then ensure that the location of :mod:`smact` is on your PYTHONPATH.
+
+ For developer installation SMACT can be installed from a copy of the source repository (https://github.com/wmd-group/smact);
+ this will be preferred if using experimental code branches.
+
+ To clone the project from Github and make a local installation:
+
+ .. code::
+
+ git clone https://github.com/wmd-group/smact.git
+ cd smact
+ pip install --user -e .
+
+ With -e pip will create links to the source folder so that that changes to the code will be immediately reflected on the PATH. | 23 | 0.766667 | 19 | 4 |
26330025ccdeab7febd69c7f9053a99ac46d421b | cactus/static/external/manager.py | cactus/static/external/manager.py | class ExternalManager(object):
"""
Manager the active externals
"""
def __init__(self, processors=None, optimizers=None):
self.processors = processors if processors is not None else []
self.optimizers = optimizers if optimizers is not None else []
def _register(self, external, externals):
externals.insert(0, external)
def clear(self):
"""
Clear this manager
"""
self.processors = []
self.optimizers = []
def register_processor(self, processor):
"""
Add a new processor to the list of processors
This processor will be added with maximum priority
"""
self._register(processor, self.processors)
def register_optimizer(self, optimizer):
"""
Add a new optimizer to the list of optimizer
This optimizer will be added with maximum priority
"""
self._register(optimizer, self.optimizers) | class ExternalManager(object):
"""
Manager the active externals
"""
def __init__(self, processors=None, optimizers=None):
self.processors = processors if processors is not None else []
self.optimizers = optimizers if optimizers is not None else []
def _register(self, external, externals):
externals.insert(0, external)
def _deregister(self, external, externals):
externals.remove(external)
def clear(self):
"""
Clear this manager
"""
self.processors = []
self.optimizers = []
def register_processor(self, processor):
"""
Add a new processor to the list of processors
This processor will be added with maximum priority
"""
self._register(processor, self.processors)
def deregister_processor(self, processor):
"""
Remove an existing processor from the list
Will raise a ValueError if the processor is not present
"""
self._deregister(processor, self.processors)
def register_optimizer(self, optimizer):
"""
Add a new optimizer to the list of optimizer
This optimizer will be added with maximum priority
"""
self._register(optimizer, self.optimizers)
def deregister_optimizer(self, processor):
"""
Remove an existing optimizer from the list
Will raise a ValueError if the optimizer is not present
"""
self._deregister(processor, self.optimizers)
| Add option to unregister externals | Add option to unregister externals
| Python | bsd-3-clause | page-io/Cactus,juvham/Cactus,ibarria0/Cactus,gone/Cactus,Knownly/Cactus,ibarria0/Cactus,dreadatour/Cactus,danielmorosan/Cactus,PegasusWang/Cactus,dreadatour/Cactus,andyzsf/Cactus-,Bluetide/Cactus,koenbok/Cactus,Knownly/Cactus,PegasusWang/Cactus,koobs/Cactus,ibarria0/Cactus,eudicots/Cactus,page-io/Cactus,chaudum/Cactus,koobs/Cactus,Bluetide/Cactus,dreadatour/Cactus,juvham/Cactus,juvham/Cactus,koenbok/Cactus,andyzsf/Cactus-,page-io/Cactus,koobs/Cactus,gone/Cactus,koenbok/Cactus,eudicots/Cactus,fjxhkj/Cactus,Bluetide/Cactus,chaudum/Cactus,fjxhkj/Cactus,chaudum/Cactus,Knownly/Cactus,gone/Cactus,PegasusWang/Cactus,danielmorosan/Cactus,fjxhkj/Cactus,danielmorosan/Cactus,eudicots/Cactus,andyzsf/Cactus- | python | ## Code Before:
class ExternalManager(object):
"""
Manager the active externals
"""
def __init__(self, processors=None, optimizers=None):
self.processors = processors if processors is not None else []
self.optimizers = optimizers if optimizers is not None else []
def _register(self, external, externals):
externals.insert(0, external)
def clear(self):
"""
Clear this manager
"""
self.processors = []
self.optimizers = []
def register_processor(self, processor):
"""
Add a new processor to the list of processors
This processor will be added with maximum priority
"""
self._register(processor, self.processors)
def register_optimizer(self, optimizer):
"""
Add a new optimizer to the list of optimizer
This optimizer will be added with maximum priority
"""
self._register(optimizer, self.optimizers)
## Instruction:
Add option to unregister externals
## Code After:
class ExternalManager(object):
"""
Manager the active externals
"""
def __init__(self, processors=None, optimizers=None):
self.processors = processors if processors is not None else []
self.optimizers = optimizers if optimizers is not None else []
def _register(self, external, externals):
externals.insert(0, external)
def _deregister(self, external, externals):
externals.remove(external)
def clear(self):
"""
Clear this manager
"""
self.processors = []
self.optimizers = []
def register_processor(self, processor):
"""
Add a new processor to the list of processors
This processor will be added with maximum priority
"""
self._register(processor, self.processors)
def deregister_processor(self, processor):
"""
Remove an existing processor from the list
Will raise a ValueError if the processor is not present
"""
self._deregister(processor, self.processors)
def register_optimizer(self, optimizer):
"""
Add a new optimizer to the list of optimizer
This optimizer will be added with maximum priority
"""
self._register(optimizer, self.optimizers)
def deregister_optimizer(self, processor):
"""
Remove an existing optimizer from the list
Will raise a ValueError if the optimizer is not present
"""
self._deregister(processor, self.optimizers)
| class ExternalManager(object):
"""
Manager the active externals
"""
def __init__(self, processors=None, optimizers=None):
self.processors = processors if processors is not None else []
self.optimizers = optimizers if optimizers is not None else []
def _register(self, external, externals):
externals.insert(0, external)
+
+ def _deregister(self, external, externals):
+ externals.remove(external)
def clear(self):
"""
Clear this manager
"""
self.processors = []
self.optimizers = []
def register_processor(self, processor):
"""
Add a new processor to the list of processors
This processor will be added with maximum priority
"""
self._register(processor, self.processors)
+ def deregister_processor(self, processor):
+ """
+ Remove an existing processor from the list
+ Will raise a ValueError if the processor is not present
+ """
+ self._deregister(processor, self.processors)
+
def register_optimizer(self, optimizer):
"""
Add a new optimizer to the list of optimizer
This optimizer will be added with maximum priority
"""
self._register(optimizer, self.optimizers)
+
+ def deregister_optimizer(self, processor):
+ """
+ Remove an existing optimizer from the list
+ Will raise a ValueError if the optimizer is not present
+ """
+ self._deregister(processor, self.optimizers) | 17 | 0.548387 | 17 | 0 |
3d2a349ebfd9fe497a5bf08597ddef0cd861ce89 | lib/api_key.rb | lib/api_key.rb | module APIKey
module ClassMethods
attr_accessor :default_api_key
end
def self.included( klass )
klass.extend ClassMethods
end
@default_api_key = nil
attr_writer :api_key
def api_key
@api_key || self.class.default_api_key
end
end
| module APIKey
module ClassMethods
attr_accessor :default_api_key
end
def self.included( klass )
klass.extend ClassMethods
end
attr_writer :api_key
def api_key
@api_key || self.class.default_api_key
end
end
| Remove class instance variable initalization. | Remove class instance variable initalization.
By default the variable will be nil until it is defined by the
setting of it. No need to make this explicit.
| Ruby | mit | cupakromer/api_key | ruby | ## Code Before:
module APIKey
module ClassMethods
attr_accessor :default_api_key
end
def self.included( klass )
klass.extend ClassMethods
end
@default_api_key = nil
attr_writer :api_key
def api_key
@api_key || self.class.default_api_key
end
end
## Instruction:
Remove class instance variable initalization.
By default the variable will be nil until it is defined by the
setting of it. No need to make this explicit.
## Code After:
module APIKey
module ClassMethods
attr_accessor :default_api_key
end
def self.included( klass )
klass.extend ClassMethods
end
attr_writer :api_key
def api_key
@api_key || self.class.default_api_key
end
end
| module APIKey
module ClassMethods
attr_accessor :default_api_key
end
def self.included( klass )
klass.extend ClassMethods
end
- @default_api_key = nil
-
attr_writer :api_key
def api_key
@api_key || self.class.default_api_key
end
end | 2 | 0.117647 | 0 | 2 |
89820b3182066401bb85028789943594cd570541 | src/core/context/resources/stylesheets/rss2document.xsl | src/core/context/resources/stylesheets/rss2document.xsl | <?xml version='1.0'?>
<!--
Copyright 2002-2004 The Apache Software Foundation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="rss">
<document>
<header>
<title>Example: RSS feed to document</title>
</header>
<body>
<xsl:apply-templates select="channel/item"/>
</body>
</document>
</xsl:template>
<xsl:template match="item">
<section>
<title><xsl:value-of select="title" disable-output-escaping="yes"/></title>
<p><link href="{link}"><xsl:value-of select="link"/></link></p>
<p><xsl:value-of select="description" disable-output-escaping="yes"/></p>
</section>
</xsl:template>
</xsl:stylesheet>
| <?xml version='1.0'?>
<!--
Copyright 2002-2004 The Apache Software Foundation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="rss">
<document>
<header>
<title><xsl:value-of select="channel/title"/></title>
</header>
<body>
<xsl:apply-templates select="channel/item"/>
</body>
</document>
</xsl:template>
<xsl:template match="item">
<section>
<title><xsl:value-of select="title" disable-output-escaping="yes"/></title>
<p><link href="{link}"><xsl:value-of select="link"/></link></p>
<p><xsl:value-of select="description" disable-output-escaping="yes"/></p>
</section>
</xsl:template>
</xsl:stylesheet>
| Use the channel title for the title of the document | Use the channel title for the title of the document
git-svn-id: 36dcc065b18e9ace584b1c777eaeefb1d96b1ee8@53855 13f79535-47bb-0310-9956-ffa450edef68
| XSLT | apache-2.0 | apache/forrest,apache/forrest,apache/forrest,apache/forrest,apache/forrest,apache/forrest | xslt | ## Code Before:
<?xml version='1.0'?>
<!--
Copyright 2002-2004 The Apache Software Foundation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="rss">
<document>
<header>
<title>Example: RSS feed to document</title>
</header>
<body>
<xsl:apply-templates select="channel/item"/>
</body>
</document>
</xsl:template>
<xsl:template match="item">
<section>
<title><xsl:value-of select="title" disable-output-escaping="yes"/></title>
<p><link href="{link}"><xsl:value-of select="link"/></link></p>
<p><xsl:value-of select="description" disable-output-escaping="yes"/></p>
</section>
</xsl:template>
</xsl:stylesheet>
## Instruction:
Use the channel title for the title of the document
git-svn-id: 36dcc065b18e9ace584b1c777eaeefb1d96b1ee8@53855 13f79535-47bb-0310-9956-ffa450edef68
## Code After:
<?xml version='1.0'?>
<!--
Copyright 2002-2004 The Apache Software Foundation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="rss">
<document>
<header>
<title><xsl:value-of select="channel/title"/></title>
</header>
<body>
<xsl:apply-templates select="channel/item"/>
</body>
</document>
</xsl:template>
<xsl:template match="item">
<section>
<title><xsl:value-of select="title" disable-output-escaping="yes"/></title>
<p><link href="{link}"><xsl:value-of select="link"/></link></p>
<p><xsl:value-of select="description" disable-output-escaping="yes"/></p>
</section>
</xsl:template>
</xsl:stylesheet>
| <?xml version='1.0'?>
<!--
Copyright 2002-2004 The Apache Software Foundation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="rss">
<document>
<header>
- <title>Example: RSS feed to document</title>
+ <title><xsl:value-of select="channel/title"/></title>
</header>
<body>
<xsl:apply-templates select="channel/item"/>
</body>
</document>
</xsl:template>
<xsl:template match="item">
<section>
<title><xsl:value-of select="title" disable-output-escaping="yes"/></title>
<p><link href="{link}"><xsl:value-of select="link"/></link></p>
<p><xsl:value-of select="description" disable-output-escaping="yes"/></p>
</section>
</xsl:template>
</xsl:stylesheet> | 2 | 0.052632 | 1 | 1 |
95cd16cab4274a37d7aef5d7748043e7fc331f42 | lib/gimlet/queryable.rb | lib/gimlet/queryable.rb | require 'forwardable'
module Gimlet
module Queryable
module API
extend Forwardable
def select(options = {})
selecting = @instances
options[:where].each do |attribute, operator, argument|
selecting = selecting.select do |id, instance|
instance[attribute].send(operator, argument)
end
end
selecting.values
end
def new_query
current_scope || Query.new(self)
end
def_delegators :new_query, :all, :where, :first, :last, :count
end
class Query
include Enumerable
extend Forwardable
def initialize(model)
@model = model
@where = []
end
def where(hash)
hash.each do |attribute, value|
case value
when Array
@where.push([attribute, :in?, value])
when Regexp
@where.push([attribute, :=~, value])
else
@where.push([attribute, :==, value])
end
end
self
end
def all
@model.select(:where => @where)
end
def method_missing(method, *args, &block)
if @model.respond_to?(method)
scoping { @model.send(method, *args, &block) }
else
super
end
end
def scoping
previous, @model.current_scope = @model.current_scope, self
yield
ensure
@model.current_scope = previous
end
def_delegators :all, :each, :first, :last
end
end
end
| require 'forwardable'
module Gimlet
module Queryable
module API
extend Forwardable
def select(options = {})
selecting = @instances
options[:where].each do |attribute, operator, argument|
selecting = selecting.select do |id, instance|
instance[attribute].send(operator, argument)
end
end
selecting.values
end
def new_query
current_scope || Query.new(self)
end
def_delegators :new_query, :all, :where, :first, :last, :count
end
class Query
include Enumerable
extend Forwardable
def initialize(model)
@model = model
@where = []
end
def where(hash)
hash.each do |attribute, value|
case value
when Array
@where.push([attribute, :in?, value]) # should be :== ?
when Regexp
@where.push([attribute, :=~, value])
else
@where.push([attribute, :==, value])
end
end
self
end
def all
@model.select(:where => @where)
end
def method_missing(method, *args, &block)
if @model.respond_to?(method)
scoping { @model.send(method, *args, &block) }
else
super
end
end
def scoping
previous, @model.current_scope = @model.current_scope, self
yield
ensure
@model.current_scope = previous
end
def_delegators :all, :each, :first, :last
end
end
end
| Add a comment for specification | Add a comment for specification
| Ruby | mit | darashi/gimlet-model | ruby | ## Code Before:
require 'forwardable'
module Gimlet
module Queryable
module API
extend Forwardable
def select(options = {})
selecting = @instances
options[:where].each do |attribute, operator, argument|
selecting = selecting.select do |id, instance|
instance[attribute].send(operator, argument)
end
end
selecting.values
end
def new_query
current_scope || Query.new(self)
end
def_delegators :new_query, :all, :where, :first, :last, :count
end
class Query
include Enumerable
extend Forwardable
def initialize(model)
@model = model
@where = []
end
def where(hash)
hash.each do |attribute, value|
case value
when Array
@where.push([attribute, :in?, value])
when Regexp
@where.push([attribute, :=~, value])
else
@where.push([attribute, :==, value])
end
end
self
end
def all
@model.select(:where => @where)
end
def method_missing(method, *args, &block)
if @model.respond_to?(method)
scoping { @model.send(method, *args, &block) }
else
super
end
end
def scoping
previous, @model.current_scope = @model.current_scope, self
yield
ensure
@model.current_scope = previous
end
def_delegators :all, :each, :first, :last
end
end
end
## Instruction:
Add a comment for specification
## Code After:
require 'forwardable'
module Gimlet
module Queryable
module API
extend Forwardable
def select(options = {})
selecting = @instances
options[:where].each do |attribute, operator, argument|
selecting = selecting.select do |id, instance|
instance[attribute].send(operator, argument)
end
end
selecting.values
end
def new_query
current_scope || Query.new(self)
end
def_delegators :new_query, :all, :where, :first, :last, :count
end
class Query
include Enumerable
extend Forwardable
def initialize(model)
@model = model
@where = []
end
def where(hash)
hash.each do |attribute, value|
case value
when Array
@where.push([attribute, :in?, value]) # should be :== ?
when Regexp
@where.push([attribute, :=~, value])
else
@where.push([attribute, :==, value])
end
end
self
end
def all
@model.select(:where => @where)
end
def method_missing(method, *args, &block)
if @model.respond_to?(method)
scoping { @model.send(method, *args, &block) }
else
super
end
end
def scoping
previous, @model.current_scope = @model.current_scope, self
yield
ensure
@model.current_scope = previous
end
def_delegators :all, :each, :first, :last
end
end
end
| require 'forwardable'
module Gimlet
module Queryable
module API
extend Forwardable
def select(options = {})
selecting = @instances
options[:where].each do |attribute, operator, argument|
selecting = selecting.select do |id, instance|
instance[attribute].send(operator, argument)
end
end
selecting.values
end
def new_query
current_scope || Query.new(self)
end
def_delegators :new_query, :all, :where, :first, :last, :count
end
class Query
include Enumerable
extend Forwardable
def initialize(model)
@model = model
@where = []
end
def where(hash)
hash.each do |attribute, value|
case value
when Array
- @where.push([attribute, :in?, value])
+ @where.push([attribute, :in?, value]) # should be :== ?
? ++++++++++++++++++
when Regexp
@where.push([attribute, :=~, value])
else
@where.push([attribute, :==, value])
end
end
self
end
def all
@model.select(:where => @where)
end
def method_missing(method, *args, &block)
if @model.respond_to?(method)
scoping { @model.send(method, *args, &block) }
else
super
end
end
def scoping
previous, @model.current_scope = @model.current_scope, self
yield
ensure
@model.current_scope = previous
end
def_delegators :all, :each, :first, :last
end
end
end | 2 | 0.028571 | 1 | 1 |
5d9d831a51dc7847ad40fac77f9a072aa2d1c0bd | git-grep.sh | git-grep.sh | flags=
while :; do
pattern="$1"
case "$pattern" in
-i|-I|-a|-E|-H|-h|-l)
flags="$flags $pattern"
shift
;;
-e)
pattern="$2"
shift
break
;;
-*)
echo "unknown flag $pattern" >&2
exit 1
;;
*)
break
;;
esac
done
shift
git-ls-files -z "$@" | xargs -0 grep $flags -e "$pattern"
|
pattern=
flags=()
git_flags=()
while : ; do
case "$1" in
--cached|--deleted|--others|--killed|\
--ignored|--exclude=*|\
--exclude-from=*|\--exclude-per-directory=*)
git_flags=("${git_flags[@]}" "$1")
;;
-e)
pattern="$2"
shift
;;
-A|-B|-C|-D|-d|-f|-m)
flags=("${flags[@]}" "$1" "$2")
shift
;;
--)
# The rest are git-ls-files paths (or flags)
shift
break
;;
-*)
flags=("${flags[@]}" "$1")
;;
*)
if [ -z "$pattern" ]; then
pattern="$1"
shift
fi
break
;;
esac
shift
done
git-ls-files -z "${git_flags[@]}" "$@" |
xargs -0 grep "${flags[@]}" "$pattern"
| Improve "git grep" flags handling | Improve "git grep" flags handling
This allows any arbitrary flags to "grep", and knows about the few
special grep flags that take an argument too.
It also allows some flags for git-ls-files, although their usefulness
is questionable.
With this, something line
git grep -w -1 pattern
works, without the script enumerating every possible flag.
[jc: this is the version Linus sent out after I showed him a
barf-o-meter test version that avoids shell arrays. He must
have typed this version blindly, since he said:
I'm not barfing, but that's probably because my brain just shut
down and is desperately trying to gouge my eyes out with a spoon.
I slightly fixed it to catch the remaining arguments meant to be
given git-ls-files.]
Signed-off-by: Linus Torvalds <69652caca27c8b940640ad396ab71f93cacec34f@osdl.org>
Signed-off-by: Junio C Hamano <dc50d1021234060e53ec42a77d526afa2fe07479@cox.net>
| Shell | mit | destenson/git,destenson/git,destenson/git,destenson/git,destenson/git,destenson/git,destenson/git,destenson/git | shell | ## Code Before:
flags=
while :; do
pattern="$1"
case "$pattern" in
-i|-I|-a|-E|-H|-h|-l)
flags="$flags $pattern"
shift
;;
-e)
pattern="$2"
shift
break
;;
-*)
echo "unknown flag $pattern" >&2
exit 1
;;
*)
break
;;
esac
done
shift
git-ls-files -z "$@" | xargs -0 grep $flags -e "$pattern"
## Instruction:
Improve "git grep" flags handling
This allows any arbitrary flags to "grep", and knows about the few
special grep flags that take an argument too.
It also allows some flags for git-ls-files, although their usefulness
is questionable.
With this, something line
git grep -w -1 pattern
works, without the script enumerating every possible flag.
[jc: this is the version Linus sent out after I showed him a
barf-o-meter test version that avoids shell arrays. He must
have typed this version blindly, since he said:
I'm not barfing, but that's probably because my brain just shut
down and is desperately trying to gouge my eyes out with a spoon.
I slightly fixed it to catch the remaining arguments meant to be
given git-ls-files.]
Signed-off-by: Linus Torvalds <69652caca27c8b940640ad396ab71f93cacec34f@osdl.org>
Signed-off-by: Junio C Hamano <dc50d1021234060e53ec42a77d526afa2fe07479@cox.net>
## Code After:
pattern=
flags=()
git_flags=()
while : ; do
case "$1" in
--cached|--deleted|--others|--killed|\
--ignored|--exclude=*|\
--exclude-from=*|\--exclude-per-directory=*)
git_flags=("${git_flags[@]}" "$1")
;;
-e)
pattern="$2"
shift
;;
-A|-B|-C|-D|-d|-f|-m)
flags=("${flags[@]}" "$1" "$2")
shift
;;
--)
# The rest are git-ls-files paths (or flags)
shift
break
;;
-*)
flags=("${flags[@]}" "$1")
;;
*)
if [ -z "$pattern" ]; then
pattern="$1"
shift
fi
break
;;
esac
shift
done
git-ls-files -z "${git_flags[@]}" "$@" |
xargs -0 grep "${flags[@]}" "$pattern"
| +
+ pattern=
- flags=
+ flags=()
? ++
+ git_flags=()
- while :; do
+ while : ; do
? +
+ case "$1" in
+ --cached|--deleted|--others|--killed|\
+ --ignored|--exclude=*|\
+ --exclude-from=*|\--exclude-per-directory=*)
+ git_flags=("${git_flags[@]}" "$1")
+ ;;
+ -e)
+ pattern="$2"
+ shift
+ ;;
+ -A|-B|-C|-D|-d|-f|-m)
+ flags=("${flags[@]}" "$1" "$2")
+ shift
+ ;;
+ --)
+ # The rest are git-ls-files paths (or flags)
+ shift
+ break
+ ;;
+ -*)
+ flags=("${flags[@]}" "$1")
+ ;;
+ *)
+ if [ -z "$pattern" ]; then
- pattern="$1"
? ^^
+ pattern="$1"
? ^^^
+ shift
+ fi
+ break
+ ;;
+ esac
+ shift
- case "$pattern" in
- -i|-I|-a|-E|-H|-h|-l)
- flags="$flags $pattern"
- shift
- ;;
- -e)
- pattern="$2"
- shift
- break
- ;;
- -*)
- echo "unknown flag $pattern" >&2
- exit 1
- ;;
- *)
- break
- ;;
- esac
done
- shift
- git-ls-files -z "$@" | xargs -0 grep $flags -e "$pattern"
+ git-ls-files -z "${git_flags[@]}" "$@" |
+ xargs -0 grep "${flags[@]}" "$pattern" | 61 | 2.541667 | 38 | 23 |
de79141caca893291713289e8ed3a6f325681a77 | src/Serilog.Extensions.Logging/project.json | src/Serilog.Extensions.Logging/project.json | {
"version": "1.4.0-*",
"description": "Serilog provider for Microsoft.Extensions.Logging",
"authors": [ "Microsoft", "Serilog Contributors" ],
"packOptions": {
"tags": [ "serilog", "Microsoft.Extensions.Logging" ],
"projectUrl": "https://github.com/serilog/serilog-extensions-logging",
"licenseUrl": "http://www.apache.org/licenses/LICENSE-2.0",
"iconUrl": "http://serilog.net/images/serilog-extension-nuget.png"
},
"dependencies": {
"Microsoft.Extensions.Logging.Abstractions": "1.0.0",
"Serilog": "2.3.0"
},
"buildOptions": {
"keyFile": "../../assets/Serilog.snk",
"xmlDoc": true,
"warningsAsErrors": true
},
"frameworks": {
"net4.5": {
},
"net4.6": {
"buildOptions": {
"define": [ "ASYNCLOCAL" ]
}
},
"netstandard1.3": {
"buildOptions": {
"define": ["ASYNCLOCAL"]
}
}
}
}
| {
"version": "1.4.0-*",
"description": "Serilog provider for Microsoft.Extensions.Logging",
"authors": [ "Microsoft", "Serilog Contributors" ],
"packOptions": {
"tags": [ "serilog", "Microsoft.Extensions.Logging" ],
"projectUrl": "https://github.com/serilog/serilog-extensions-logging",
"licenseUrl": "http://www.apache.org/licenses/LICENSE-2.0",
"iconUrl": "http://serilog.net/images/serilog-extension-nuget.png"
},
"dependencies": {
"Microsoft.Extensions.Logging.Abstractions": "1.0.0",
"Serilog": "2.3.0"
},
"buildOptions": {
"keyFile": "../../assets/Serilog.snk",
"xmlDoc": true,
"warningsAsErrors": true
},
"frameworks": {
"net4.5": {
"frameworkAssemblies": { "System.Runtime": { "type": "build" } }
},
"net4.6": {
"frameworkAssemblies": { "System.Runtime": { "type": "build" } }
"buildOptions": {
"define": [ "ASYNCLOCAL" ]
}
},
"netstandard1.3": {
"buildOptions": {
"define": ["ASYNCLOCAL"]
}
}
}
}
| Add build-time dependency on System.Runtime | Add build-time dependency on System.Runtime | JSON | apache-2.0 | serilog/serilog-framework-logging,serilog/serilog-extensions-logging,serilog/serilog-extensions-logging | json | ## Code Before:
{
"version": "1.4.0-*",
"description": "Serilog provider for Microsoft.Extensions.Logging",
"authors": [ "Microsoft", "Serilog Contributors" ],
"packOptions": {
"tags": [ "serilog", "Microsoft.Extensions.Logging" ],
"projectUrl": "https://github.com/serilog/serilog-extensions-logging",
"licenseUrl": "http://www.apache.org/licenses/LICENSE-2.0",
"iconUrl": "http://serilog.net/images/serilog-extension-nuget.png"
},
"dependencies": {
"Microsoft.Extensions.Logging.Abstractions": "1.0.0",
"Serilog": "2.3.0"
},
"buildOptions": {
"keyFile": "../../assets/Serilog.snk",
"xmlDoc": true,
"warningsAsErrors": true
},
"frameworks": {
"net4.5": {
},
"net4.6": {
"buildOptions": {
"define": [ "ASYNCLOCAL" ]
}
},
"netstandard1.3": {
"buildOptions": {
"define": ["ASYNCLOCAL"]
}
}
}
}
## Instruction:
Add build-time dependency on System.Runtime
## Code After:
{
"version": "1.4.0-*",
"description": "Serilog provider for Microsoft.Extensions.Logging",
"authors": [ "Microsoft", "Serilog Contributors" ],
"packOptions": {
"tags": [ "serilog", "Microsoft.Extensions.Logging" ],
"projectUrl": "https://github.com/serilog/serilog-extensions-logging",
"licenseUrl": "http://www.apache.org/licenses/LICENSE-2.0",
"iconUrl": "http://serilog.net/images/serilog-extension-nuget.png"
},
"dependencies": {
"Microsoft.Extensions.Logging.Abstractions": "1.0.0",
"Serilog": "2.3.0"
},
"buildOptions": {
"keyFile": "../../assets/Serilog.snk",
"xmlDoc": true,
"warningsAsErrors": true
},
"frameworks": {
"net4.5": {
"frameworkAssemblies": { "System.Runtime": { "type": "build" } }
},
"net4.6": {
"frameworkAssemblies": { "System.Runtime": { "type": "build" } }
"buildOptions": {
"define": [ "ASYNCLOCAL" ]
}
},
"netstandard1.3": {
"buildOptions": {
"define": ["ASYNCLOCAL"]
}
}
}
}
| {
"version": "1.4.0-*",
"description": "Serilog provider for Microsoft.Extensions.Logging",
"authors": [ "Microsoft", "Serilog Contributors" ],
"packOptions": {
"tags": [ "serilog", "Microsoft.Extensions.Logging" ],
"projectUrl": "https://github.com/serilog/serilog-extensions-logging",
"licenseUrl": "http://www.apache.org/licenses/LICENSE-2.0",
"iconUrl": "http://serilog.net/images/serilog-extension-nuget.png"
},
"dependencies": {
"Microsoft.Extensions.Logging.Abstractions": "1.0.0",
"Serilog": "2.3.0"
},
"buildOptions": {
"keyFile": "../../assets/Serilog.snk",
"xmlDoc": true,
"warningsAsErrors": true
},
"frameworks": {
"net4.5": {
+ "frameworkAssemblies": { "System.Runtime": { "type": "build" } }
},
"net4.6": {
+ "frameworkAssemblies": { "System.Runtime": { "type": "build" } }
"buildOptions": {
"define": [ "ASYNCLOCAL" ]
}
},
"netstandard1.3": {
"buildOptions": {
"define": ["ASYNCLOCAL"]
}
}
}
} | 2 | 0.058824 | 2 | 0 |
44a4597b2a492896634297558521b57fb39b4077 | Godeps/Godeps.json | Godeps/Godeps.json | {
"ImportPath": "github.com/getlantern/go-geoserve",
"GoVersion": "devel +969a38842696 Sun May 04 23:00:47 2014 -0400",
"Deps": [
{
"ImportPath": "github.com/oschwald/geoip2-golang",
"Comment": "v0.1.0-3-gf5a6adf",
"Rev": "f5a6adffc17dc4626626b09ca1285f26b257c720"
},
{
"ImportPath": "github.com/oschwald/maxminddb-golang",
"Comment": "v0.1.0-21-g8c69cd4",
"Rev": "8c69cd40823e974cf86a85979acd9430d5b0fbab"
}
]
}
| {
"ImportPath": "github.com/getlantern/go-geoserve",
"GoVersion": "1.2.2",
"Deps": [
{
"ImportPath": "github.com/oschwald/geoip2-golang",
"Comment": "v0.1.0-3-gf5a6adf",
"Rev": "f5a6adffc17dc4626626b09ca1285f26b257c720"
},
{
"ImportPath": "github.com/oschwald/maxminddb-golang",
"Comment": "v0.1.0-21-g8c69cd4",
"Rev": "8c69cd40823e974cf86a85979acd9430d5b0fbab"
}
]
}
| Set go 1.2.2 as the version | Set go 1.2.2 as the version
| JSON | apache-2.0 | getlantern/go-geoserve | json | ## Code Before:
{
"ImportPath": "github.com/getlantern/go-geoserve",
"GoVersion": "devel +969a38842696 Sun May 04 23:00:47 2014 -0400",
"Deps": [
{
"ImportPath": "github.com/oschwald/geoip2-golang",
"Comment": "v0.1.0-3-gf5a6adf",
"Rev": "f5a6adffc17dc4626626b09ca1285f26b257c720"
},
{
"ImportPath": "github.com/oschwald/maxminddb-golang",
"Comment": "v0.1.0-21-g8c69cd4",
"Rev": "8c69cd40823e974cf86a85979acd9430d5b0fbab"
}
]
}
## Instruction:
Set go 1.2.2 as the version
## Code After:
{
"ImportPath": "github.com/getlantern/go-geoserve",
"GoVersion": "1.2.2",
"Deps": [
{
"ImportPath": "github.com/oschwald/geoip2-golang",
"Comment": "v0.1.0-3-gf5a6adf",
"Rev": "f5a6adffc17dc4626626b09ca1285f26b257c720"
},
{
"ImportPath": "github.com/oschwald/maxminddb-golang",
"Comment": "v0.1.0-21-g8c69cd4",
"Rev": "8c69cd40823e974cf86a85979acd9430d5b0fbab"
}
]
}
| {
"ImportPath": "github.com/getlantern/go-geoserve",
- "GoVersion": "devel +969a38842696 Sun May 04 23:00:47 2014 -0400",
+ "GoVersion": "1.2.2",
"Deps": [
{
"ImportPath": "github.com/oschwald/geoip2-golang",
"Comment": "v0.1.0-3-gf5a6adf",
"Rev": "f5a6adffc17dc4626626b09ca1285f26b257c720"
},
{
"ImportPath": "github.com/oschwald/maxminddb-golang",
"Comment": "v0.1.0-21-g8c69cd4",
"Rev": "8c69cd40823e974cf86a85979acd9430d5b0fbab"
}
]
} | 2 | 0.125 | 1 | 1 |
0ea16e236f0685f25d0f497d524567c5284bc7bc | .travis.yml | .travis.yml | before_install:
- yes | sudo add-apt-repository ppa:hansjorg/rust
- yes | sudo add-apt-repository ppa:yak1ex/llvm
- yes | sudo add-apt-repository ppa:sven-eckelmann/ppa-wxwidgets2.9
- sudo apt-get update
install:
- sudo apt-get install rust-nightly
- sudo apt-get install libclang-3.3-dev
- sudo apt-get install libwxgtk2.9-dev
script:
- ./build.sh
| before_install:
- yes | sudo add-apt-repository ppa:hansjorg/rust
- yes | sudo add-apt-repository ppa:xorg-edgers/ppa
- yes | sudo add-apt-repository ppa:sven-eckelmann/ppa-wxwidgets2.9
- sudo apt-get update
install:
- sudo apt-get install rust-nightly libclang-3.3-dev libwxgtk2.9-dev
script:
- ./build.sh
| Use the same clang PPA as one rust-bindgen uses. | Use the same clang PPA as one rust-bindgen uses.
| YAML | lgpl-2.1 | tempbottle/wxRust,tempbottle/wxRust | yaml | ## Code Before:
before_install:
- yes | sudo add-apt-repository ppa:hansjorg/rust
- yes | sudo add-apt-repository ppa:yak1ex/llvm
- yes | sudo add-apt-repository ppa:sven-eckelmann/ppa-wxwidgets2.9
- sudo apt-get update
install:
- sudo apt-get install rust-nightly
- sudo apt-get install libclang-3.3-dev
- sudo apt-get install libwxgtk2.9-dev
script:
- ./build.sh
## Instruction:
Use the same clang PPA as one rust-bindgen uses.
## Code After:
before_install:
- yes | sudo add-apt-repository ppa:hansjorg/rust
- yes | sudo add-apt-repository ppa:xorg-edgers/ppa
- yes | sudo add-apt-repository ppa:sven-eckelmann/ppa-wxwidgets2.9
- sudo apt-get update
install:
- sudo apt-get install rust-nightly libclang-3.3-dev libwxgtk2.9-dev
script:
- ./build.sh
| before_install:
- yes | sudo add-apt-repository ppa:hansjorg/rust
- - yes | sudo add-apt-repository ppa:yak1ex/llvm
? ^ ---------
+ - yes | sudo add-apt-repository ppa:xorg-edgers/ppa
? ^^^^^^^^^^^^^^
- yes | sudo add-apt-repository ppa:sven-eckelmann/ppa-wxwidgets2.9
- sudo apt-get update
install:
+ - sudo apt-get install rust-nightly libclang-3.3-dev libwxgtk2.9-dev
- - sudo apt-get install rust-nightly
- - sudo apt-get install libclang-3.3-dev
- - sudo apt-get install libwxgtk2.9-dev
script:
- ./build.sh | 6 | 0.545455 | 2 | 4 |
dcc2821cac0619fc2ca5f486ad30416f3c3cfda9 | ce/expr/parser.py | ce/expr/parser.py |
from ..semantics import mpq
from .common import OPERATORS, ADD_OP, MULTIPLY_OP
def try_to_number(s):
try:
return mpq(s)
except (ValueError, TypeError):
return s
def _parse_r(s):
s = s.strip()
bracket_level = 0
operator_pos = -1
for i, v in enumerate(s):
if v == '(':
bracket_level += 1
if v == ')':
bracket_level -= 1
if bracket_level == 1 and v in OPERATORS:
operator_pos = i
break
if operator_pos == -1:
return s
a1 = _parse_r(s[1:operator_pos].strip())
a2 = _parse_r(s[operator_pos + 1:-1].strip())
return Expr(s[operator_pos], a1, a2)
|
import ast
from ..semantics import mpq
from .common import OPERATORS, ADD_OP, MULTIPLY_OP
def try_to_number(s):
try:
return mpq(s)
except (ValueError, TypeError):
return s
OPERATOR_MAP = {
ast.Add: ADD_OP,
ast.Mult: MULTIPLY_OP,
}
def parse(s):
from .biop import Expr
def _parse_r(t):
try:
return t.n
except AttributeError:
pass
try:
return t.id
except AttributeError:
op = OPERATOR_MAP[t.op.__class__]
a1 = _parse_r(t.left)
a2 = _parse_r(t.right)
return Expr(op, a1, a2)
return _parse_r(ast.parse(s, mode='eval').body)
| Replace parsing with Python's ast | Replace parsing with Python's ast
Allows greater flexibility and syntax checks
| Python | mit | admk/soap | python | ## Code Before:
from ..semantics import mpq
from .common import OPERATORS, ADD_OP, MULTIPLY_OP
def try_to_number(s):
try:
return mpq(s)
except (ValueError, TypeError):
return s
def _parse_r(s):
s = s.strip()
bracket_level = 0
operator_pos = -1
for i, v in enumerate(s):
if v == '(':
bracket_level += 1
if v == ')':
bracket_level -= 1
if bracket_level == 1 and v in OPERATORS:
operator_pos = i
break
if operator_pos == -1:
return s
a1 = _parse_r(s[1:operator_pos].strip())
a2 = _parse_r(s[operator_pos + 1:-1].strip())
return Expr(s[operator_pos], a1, a2)
## Instruction:
Replace parsing with Python's ast
Allows greater flexibility and syntax checks
## Code After:
import ast
from ..semantics import mpq
from .common import OPERATORS, ADD_OP, MULTIPLY_OP
def try_to_number(s):
try:
return mpq(s)
except (ValueError, TypeError):
return s
OPERATOR_MAP = {
ast.Add: ADD_OP,
ast.Mult: MULTIPLY_OP,
}
def parse(s):
from .biop import Expr
def _parse_r(t):
try:
return t.n
except AttributeError:
pass
try:
return t.id
except AttributeError:
op = OPERATOR_MAP[t.op.__class__]
a1 = _parse_r(t.left)
a2 = _parse_r(t.right)
return Expr(op, a1, a2)
return _parse_r(ast.parse(s, mode='eval').body)
|
+
+ import ast
from ..semantics import mpq
from .common import OPERATORS, ADD_OP, MULTIPLY_OP
def try_to_number(s):
try:
return mpq(s)
except (ValueError, TypeError):
return s
+ OPERATOR_MAP = {
+ ast.Add: ADD_OP,
+ ast.Mult: MULTIPLY_OP,
+ }
+
+
- def _parse_r(s):
? - --
+ def parse(s):
+ from .biop import Expr
+ def _parse_r(t):
+ try:
- s = s.strip()
- bracket_level = 0
- operator_pos = -1
- for i, v in enumerate(s):
- if v == '(':
- bracket_level += 1
- if v == ')':
- bracket_level -= 1
- if bracket_level == 1 and v in OPERATORS:
- operator_pos = i
- break
- if operator_pos == -1:
- return s
? ^
+ return t.n
? ++++ ^^^
- a1 = _parse_r(s[1:operator_pos].strip())
- a2 = _parse_r(s[operator_pos + 1:-1].strip())
- return Expr(s[operator_pos], a1, a2)
+ except AttributeError:
+ pass
+ try:
+ return t.id
+ except AttributeError:
+ op = OPERATOR_MAP[t.op.__class__]
+ a1 = _parse_r(t.left)
+ a2 = _parse_r(t.right)
+ return Expr(op, a1, a2)
+ return _parse_r(ast.parse(s, mode='eval').body) | 40 | 1.333333 | 23 | 17 |
98327054e6774b7195e57b7cc5923ac5f792975a | source/views/sis/student-work-carls/job-row.js | source/views/sis/student-work-carls/job-row.js | // @flow
import React from 'react'
import {Column, Row} from '../../components/layout'
import {ListRow, Title} from '../../components/list'
import type {ThinJobType} from './types'
export class JobRow extends React.PureComponent {
props: {
onPress: ThinJobType => any,
job: ThinJobType,
}
_onPress = () => this.props.onPress(this.props.job)
render() {
const {job} = this.props
return (
<ListRow arrowPosition="top" onPress={this._onPress}>
<Row alignItems="center">
<Column flex={1}>
<Title lines={1}>{job.title}</Title>
</Column>
</Row>
</ListRow>
)
}
}
| // @flow
import React from 'react'
import {Column, Row} from '../../components/layout'
import {ListRow, Title} from '../../components/list'
import type {ThinJobType} from './types'
export class JobRow extends React.PureComponent {
props: {
onPress: ThinJobType => any,
job: ThinJobType,
}
_onPress = () => this.props.onPress(this.props.job)
render() {
const {job} = this.props
return (
<ListRow arrowPosition="center" onPress={this._onPress}>
<Row minHeight={36} alignItems="center">
<Column flex={1}>
<Title lines={1}>{job.title}</Title>
</Column>
</Row>
</ListRow>
)
}
}
| Increase height of job row | Increase height of job row
| JavaScript | mit | carls-app/carls,carls-app/carls,carls-app/carls,carls-app/carls,carls-app/carls,carls-app/carls,carls-app/carls | javascript | ## Code Before:
// @flow
import React from 'react'
import {Column, Row} from '../../components/layout'
import {ListRow, Title} from '../../components/list'
import type {ThinJobType} from './types'
export class JobRow extends React.PureComponent {
props: {
onPress: ThinJobType => any,
job: ThinJobType,
}
_onPress = () => this.props.onPress(this.props.job)
render() {
const {job} = this.props
return (
<ListRow arrowPosition="top" onPress={this._onPress}>
<Row alignItems="center">
<Column flex={1}>
<Title lines={1}>{job.title}</Title>
</Column>
</Row>
</ListRow>
)
}
}
## Instruction:
Increase height of job row
## Code After:
// @flow
import React from 'react'
import {Column, Row} from '../../components/layout'
import {ListRow, Title} from '../../components/list'
import type {ThinJobType} from './types'
export class JobRow extends React.PureComponent {
props: {
onPress: ThinJobType => any,
job: ThinJobType,
}
_onPress = () => this.props.onPress(this.props.job)
render() {
const {job} = this.props
return (
<ListRow arrowPosition="center" onPress={this._onPress}>
<Row minHeight={36} alignItems="center">
<Column flex={1}>
<Title lines={1}>{job.title}</Title>
</Column>
</Row>
</ListRow>
)
}
}
| // @flow
import React from 'react'
import {Column, Row} from '../../components/layout'
import {ListRow, Title} from '../../components/list'
import type {ThinJobType} from './types'
export class JobRow extends React.PureComponent {
props: {
onPress: ThinJobType => any,
job: ThinJobType,
}
_onPress = () => this.props.onPress(this.props.job)
render() {
const {job} = this.props
return (
- <ListRow arrowPosition="top" onPress={this._onPress}>
? ^^
+ <ListRow arrowPosition="center" onPress={this._onPress}>
? +++ ^^
- <Row alignItems="center">
+ <Row minHeight={36} alignItems="center">
? +++++++++++++++
<Column flex={1}>
<Title lines={1}>{job.title}</Title>
</Column>
</Row>
</ListRow>
)
}
} | 4 | 0.137931 | 2 | 2 |
d2ae3517f663396ff3fe6dd3f8b79196ee0b6f04 | test-infra/aws-vpn/locals.tf | test-infra/aws-vpn/locals.tf | data "aws_availability_zones" "available" {
state = "available"
}
locals {
global_tags = {
"environment" = "josec-vpn-test"
}
availability_zones = [for x in ["a", "b", "c"] : "${var.aws_region}${x}"]
prefix = "tp-test-vpn-"
}
variable "parent_domain" {
type = string
description = "An already existing DNS zone to create child_dns_zone in"
}
variable "child_subdomain" {
type = string
description = "The prefix to a DNS zone to create. e.g. if parent_domain is 'foo.com', this should be 'bar', to create a hosted zone 'foo.bar.com'"
}
variable "child_subdomain_comment" {
type = string
description = "The description of the created DNS zone; will be visible in the AWS console"
}
variable "aws_region" {
type = string
description = "The AWS region to provision resources in"
}
variable "vpc_cidr" {
type = string
description = "The CIDR for the VPN"
}
variable "vpn_client_cidr" {
type = string
description = "The CIDR assigned to clients of the VPN"
}
variable "split_tunnel" {
type = bool
description = "Whether to set up split tunneling for the VPN"
}
variable "service_cidr" {
type = string
description = "The CIDR to put services in"
}
| data "aws_availability_zones" "available" {
state = "available"
}
locals {
global_tags = {
"environment" = "${var.child_subdomain}-eks-vpn"
}
availability_zones = [for x in ["a", "b", "c"] : "${var.aws_region}${x}"]
prefix = "tp-test-vpn-"
}
variable "parent_domain" {
type = string
description = "An already existing DNS zone to create child_dns_zone in"
}
variable "child_subdomain" {
type = string
description = "The prefix to a DNS zone to create. e.g. if parent_domain is 'foo.com', this should be 'bar', to create a hosted zone 'foo.bar.com'"
}
variable "child_subdomain_comment" {
type = string
description = "The description of the created DNS zone; will be visible in the AWS console"
}
variable "aws_region" {
type = string
description = "The AWS region to provision resources in"
}
variable "vpc_cidr" {
type = string
description = "The CIDR for the VPN"
}
variable "vpn_client_cidr" {
type = string
description = "The CIDR assigned to clients of the VPN"
}
variable "split_tunnel" {
type = bool
description = "Whether to set up split tunneling for the VPN"
}
variable "service_cidr" {
type = string
description = "The CIDR to put services in"
}
| Change a tag to not have my name on it | Change a tag to not have my name on it
Signed-off-by: Jose Cortes <90db7b580b32d49369f56eb8df8e548917a57096@datawire.io>
| HCL | apache-2.0 | datawire/telepresence,datawire/telepresence,datawire/telepresence | hcl | ## Code Before:
data "aws_availability_zones" "available" {
state = "available"
}
locals {
global_tags = {
"environment" = "josec-vpn-test"
}
availability_zones = [for x in ["a", "b", "c"] : "${var.aws_region}${x}"]
prefix = "tp-test-vpn-"
}
variable "parent_domain" {
type = string
description = "An already existing DNS zone to create child_dns_zone in"
}
variable "child_subdomain" {
type = string
description = "The prefix to a DNS zone to create. e.g. if parent_domain is 'foo.com', this should be 'bar', to create a hosted zone 'foo.bar.com'"
}
variable "child_subdomain_comment" {
type = string
description = "The description of the created DNS zone; will be visible in the AWS console"
}
variable "aws_region" {
type = string
description = "The AWS region to provision resources in"
}
variable "vpc_cidr" {
type = string
description = "The CIDR for the VPN"
}
variable "vpn_client_cidr" {
type = string
description = "The CIDR assigned to clients of the VPN"
}
variable "split_tunnel" {
type = bool
description = "Whether to set up split tunneling for the VPN"
}
variable "service_cidr" {
type = string
description = "The CIDR to put services in"
}
## Instruction:
Change a tag to not have my name on it
Signed-off-by: Jose Cortes <90db7b580b32d49369f56eb8df8e548917a57096@datawire.io>
## Code After:
data "aws_availability_zones" "available" {
state = "available"
}
locals {
global_tags = {
"environment" = "${var.child_subdomain}-eks-vpn"
}
availability_zones = [for x in ["a", "b", "c"] : "${var.aws_region}${x}"]
prefix = "tp-test-vpn-"
}
variable "parent_domain" {
type = string
description = "An already existing DNS zone to create child_dns_zone in"
}
variable "child_subdomain" {
type = string
description = "The prefix to a DNS zone to create. e.g. if parent_domain is 'foo.com', this should be 'bar', to create a hosted zone 'foo.bar.com'"
}
variable "child_subdomain_comment" {
type = string
description = "The description of the created DNS zone; will be visible in the AWS console"
}
variable "aws_region" {
type = string
description = "The AWS region to provision resources in"
}
variable "vpc_cidr" {
type = string
description = "The CIDR for the VPN"
}
variable "vpn_client_cidr" {
type = string
description = "The CIDR assigned to clients of the VPN"
}
variable "split_tunnel" {
type = bool
description = "Whether to set up split tunneling for the VPN"
}
variable "service_cidr" {
type = string
description = "The CIDR to put services in"
}
| data "aws_availability_zones" "available" {
state = "available"
}
locals {
global_tags = {
- "environment" = "josec-vpn-test"
+ "environment" = "${var.child_subdomain}-eks-vpn"
}
availability_zones = [for x in ["a", "b", "c"] : "${var.aws_region}${x}"]
prefix = "tp-test-vpn-"
}
variable "parent_domain" {
type = string
description = "An already existing DNS zone to create child_dns_zone in"
}
variable "child_subdomain" {
type = string
description = "The prefix to a DNS zone to create. e.g. if parent_domain is 'foo.com', this should be 'bar', to create a hosted zone 'foo.bar.com'"
}
variable "child_subdomain_comment" {
type = string
description = "The description of the created DNS zone; will be visible in the AWS console"
}
variable "aws_region" {
type = string
description = "The AWS region to provision resources in"
}
variable "vpc_cidr" {
type = string
description = "The CIDR for the VPN"
}
variable "vpn_client_cidr" {
type = string
description = "The CIDR assigned to clients of the VPN"
}
variable "split_tunnel" {
type = bool
description = "Whether to set up split tunneling for the VPN"
}
variable "service_cidr" {
type = string
description = "The CIDR to put services in"
} | 2 | 0.039216 | 1 | 1 |
c65f6261b8b420b61409e84677c4faba495de22f | README.md | README.md | Solutions for the Foundations of Concurrent & Distributed Systems Lab (TU Dresden, Summer Semester 2015)
## Purpose
The purpose of the lab was to parallelize 3 out of the 5 problems described in the file [problemset.pdf](https://github.com/anmonteiro/fcds-lab-2015/blob/master/problemset.pdf). The chosen programming language was [Golang](https://golang.org/).
## Contents
This repository contains solutions for 4 of the aforementioned programming challenges, as well as an input generator for the Haar Wavelets problem.
| Solutions for the Foundations of Concurrent & Distributed Systems Lab (TU Dresden, Summer Semester 2015)
## Purpose
The purpose of the lab was to parallelize 3 out of the 5 problems described in the file [problemset.pdf](https://github.com/anmonteiro/fcds-lab-2015/blob/master/problemset.pdf). The chosen programming language was [Golang](https://golang.org/).
## Contents
This repository contains solutions for 4 of the aforementioned programming challenges, as well as an input generator for the Haar Wavelets problem.
## License
Copyright (c) 2015 António Nuno Monteiro
This work is distributed under the MIT license. For more information see the [LICENSE](./LICENSE) file.
| Add license info in readme | Add license info in readme | Markdown | mit | anmonteiro/fcds-lab-2015 | markdown | ## Code Before:
Solutions for the Foundations of Concurrent & Distributed Systems Lab (TU Dresden, Summer Semester 2015)
## Purpose
The purpose of the lab was to parallelize 3 out of the 5 problems described in the file [problemset.pdf](https://github.com/anmonteiro/fcds-lab-2015/blob/master/problemset.pdf). The chosen programming language was [Golang](https://golang.org/).
## Contents
This repository contains solutions for 4 of the aforementioned programming challenges, as well as an input generator for the Haar Wavelets problem.
## Instruction:
Add license info in readme
## Code After:
Solutions for the Foundations of Concurrent & Distributed Systems Lab (TU Dresden, Summer Semester 2015)
## Purpose
The purpose of the lab was to parallelize 3 out of the 5 problems described in the file [problemset.pdf](https://github.com/anmonteiro/fcds-lab-2015/blob/master/problemset.pdf). The chosen programming language was [Golang](https://golang.org/).
## Contents
This repository contains solutions for 4 of the aforementioned programming challenges, as well as an input generator for the Haar Wavelets problem.
## License
Copyright (c) 2015 António Nuno Monteiro
This work is distributed under the MIT license. For more information see the [LICENSE](./LICENSE) file.
| Solutions for the Foundations of Concurrent & Distributed Systems Lab (TU Dresden, Summer Semester 2015)
## Purpose
The purpose of the lab was to parallelize 3 out of the 5 problems described in the file [problemset.pdf](https://github.com/anmonteiro/fcds-lab-2015/blob/master/problemset.pdf). The chosen programming language was [Golang](https://golang.org/).
## Contents
This repository contains solutions for 4 of the aforementioned programming challenges, as well as an input generator for the Haar Wavelets problem.
+
+ ## License
+
+ Copyright (c) 2015 António Nuno Monteiro
+
+ This work is distributed under the MIT license. For more information see the [LICENSE](./LICENSE) file. | 6 | 0.666667 | 6 | 0 |
1ccfd25877fdfecfd5f3d1c4fcef7d58a93f0178 | lib/itamae/plugin/resource/mail_alias.rb | lib/itamae/plugin/resource/mail_alias.rb | require 'itamae/plugin/resource/mail_alias/version'
require 'itamae'
module Itamae
module Plugin
module Resource
class MailAlias < Itamae::Resource::Base
define_attribute :action, default: :create
define_attribute :mail_alias, type: String, default_name: true
define_attribute :recipient, type: String, required: true
def action_create(options)
if !run_specinfra(:check_mail_alias_is_aliased_to, mail_alias, recipient)
run_specinfra(:add_mail_alias, mail_alias, recipient)
end
end
end
end
end
end
| require 'itamae/plugin/resource/mail_alias/version'
require 'itamae'
module Itamae
module Plugin
module Resource
class MailAlias < Itamae::Resource::Base
define_attribute :action, default: :create
define_attribute :mail_alias, type: String, default_name: true
define_attribute :recipient, type: String, required: true
def action_create(options)
if !run_specinfra(:check_mail_alias_is_aliased_to, attributes.mail_alias, attributes.recipient)
run_specinfra(:add_mail_alias, mail_alias, attributes.recipient)
end
end
end
end
end
end
| Fix according to recent change of itamae | Fix according to recent change of itamae
| Ruby | mit | mizzy/itamae-plugin-resource-mail_alias | ruby | ## Code Before:
require 'itamae/plugin/resource/mail_alias/version'
require 'itamae'
module Itamae
module Plugin
module Resource
class MailAlias < Itamae::Resource::Base
define_attribute :action, default: :create
define_attribute :mail_alias, type: String, default_name: true
define_attribute :recipient, type: String, required: true
def action_create(options)
if !run_specinfra(:check_mail_alias_is_aliased_to, mail_alias, recipient)
run_specinfra(:add_mail_alias, mail_alias, recipient)
end
end
end
end
end
end
## Instruction:
Fix according to recent change of itamae
## Code After:
require 'itamae/plugin/resource/mail_alias/version'
require 'itamae'
module Itamae
module Plugin
module Resource
class MailAlias < Itamae::Resource::Base
define_attribute :action, default: :create
define_attribute :mail_alias, type: String, default_name: true
define_attribute :recipient, type: String, required: true
def action_create(options)
if !run_specinfra(:check_mail_alias_is_aliased_to, attributes.mail_alias, attributes.recipient)
run_specinfra(:add_mail_alias, mail_alias, attributes.recipient)
end
end
end
end
end
end
| require 'itamae/plugin/resource/mail_alias/version'
require 'itamae'
module Itamae
module Plugin
module Resource
class MailAlias < Itamae::Resource::Base
define_attribute :action, default: :create
define_attribute :mail_alias, type: String, default_name: true
define_attribute :recipient, type: String, required: true
def action_create(options)
- if !run_specinfra(:check_mail_alias_is_aliased_to, mail_alias, recipient)
+ if !run_specinfra(:check_mail_alias_is_aliased_to, attributes.mail_alias, attributes.recipient)
? +++++++++++ +++++++++++
- run_specinfra(:add_mail_alias, mail_alias, recipient)
+ run_specinfra(:add_mail_alias, mail_alias, attributes.recipient)
? +++++++++++
end
end
end
end
end
end | 4 | 0.2 | 2 | 2 |
49f5802a02a550cc8cee3be417426a83c31de5c9 | Source/Git/Experiments/git_log.py | Source/Git/Experiments/git_log.py | import sys
import git
r = git.Repo( sys.argv[1] )
def printTree( tree, indent=0 ):
prefix = ' '*indent
print( prefix, '-' * 16 )
print( prefix, 'Tree path %s' % (tree.path,) )
for blob in tree:
print( prefix, '%s %s (%s)' % (blob.type, blob.path, blob.hexsha) )
for child in tree.trees:
printTree( child, indent+4 )
for index, commit in enumerate(r.iter_commits( None )):
print( '=' * 60 )
for name in sorted( dir( commit ) ):
if name[0] not in 'abcdefghijklmnopqrstuvwxyz':
continue
print( 'Commit: %s: %r' % (name, getattr( commit, name )) )
print( '-' * 60 )
stats = commit.stats
for name in sorted( dir( stats ) ):
if name[0] not in 'abcdefghijklmnopqrstuvwxyz':
continue
if name == 'files':
for file in stats.files:
print( 'Commit.Stats.files: %s: %r' % (file, stats.files[file]) )
else:
print( 'Commit.Stats: %s: %r' % (name, getattr( stats, name )) )
print( '-' * 60 )
tree = commit.tree
printTree( tree )
| import sys
import git
r = git.Repo( sys.argv[1] )
def printTree( tree, indent=0 ):
prefix = ' '*indent
print( prefix, '-' * 16 )
print( prefix, 'Tree path %s' % (tree.path,) )
for blob in tree:
print( prefix, '%s %s (%s)' % (blob.type, blob.path, blob.hexsha) )
for child in tree.trees:
printTree( child, indent+4 )
for index, commit in enumerate(r.iter_commits( None )):
print( '=' * 60 )
for name in sorted( dir( commit ) ):
if name[0] not in 'abcdefghijklmnopqrstuvwxyz':
continue
print( 'Commit: %s: %r' % (name, getattr( commit, name )) )
print( '-' * 60 )
stats = commit.stats
for name in sorted( dir( stats ) ):
if name[0] not in 'abcdefghijklmnopqrstuvwxyz':
continue
if name == 'files':
for file in stats.files:
print( 'Commit.Stats.files: %s: %r' % (file, stats.files[file]) )
else:
print( 'Commit.Stats: %s: %r' % (name, getattr( stats, name )) )
print( '-' * 60 )
tree = commit.tree
printTree( tree )
if index > 1:
break
| Exit the loop early when experimenting. | Exit the loop early when experimenting. | Python | apache-2.0 | barry-scott/scm-workbench,barry-scott/scm-workbench,barry-scott/scm-workbench | python | ## Code Before:
import sys
import git
r = git.Repo( sys.argv[1] )
def printTree( tree, indent=0 ):
prefix = ' '*indent
print( prefix, '-' * 16 )
print( prefix, 'Tree path %s' % (tree.path,) )
for blob in tree:
print( prefix, '%s %s (%s)' % (blob.type, blob.path, blob.hexsha) )
for child in tree.trees:
printTree( child, indent+4 )
for index, commit in enumerate(r.iter_commits( None )):
print( '=' * 60 )
for name in sorted( dir( commit ) ):
if name[0] not in 'abcdefghijklmnopqrstuvwxyz':
continue
print( 'Commit: %s: %r' % (name, getattr( commit, name )) )
print( '-' * 60 )
stats = commit.stats
for name in sorted( dir( stats ) ):
if name[0] not in 'abcdefghijklmnopqrstuvwxyz':
continue
if name == 'files':
for file in stats.files:
print( 'Commit.Stats.files: %s: %r' % (file, stats.files[file]) )
else:
print( 'Commit.Stats: %s: %r' % (name, getattr( stats, name )) )
print( '-' * 60 )
tree = commit.tree
printTree( tree )
## Instruction:
Exit the loop early when experimenting.
## Code After:
import sys
import git
r = git.Repo( sys.argv[1] )
def printTree( tree, indent=0 ):
prefix = ' '*indent
print( prefix, '-' * 16 )
print( prefix, 'Tree path %s' % (tree.path,) )
for blob in tree:
print( prefix, '%s %s (%s)' % (blob.type, blob.path, blob.hexsha) )
for child in tree.trees:
printTree( child, indent+4 )
for index, commit in enumerate(r.iter_commits( None )):
print( '=' * 60 )
for name in sorted( dir( commit ) ):
if name[0] not in 'abcdefghijklmnopqrstuvwxyz':
continue
print( 'Commit: %s: %r' % (name, getattr( commit, name )) )
print( '-' * 60 )
stats = commit.stats
for name in sorted( dir( stats ) ):
if name[0] not in 'abcdefghijklmnopqrstuvwxyz':
continue
if name == 'files':
for file in stats.files:
print( 'Commit.Stats.files: %s: %r' % (file, stats.files[file]) )
else:
print( 'Commit.Stats: %s: %r' % (name, getattr( stats, name )) )
print( '-' * 60 )
tree = commit.tree
printTree( tree )
if index > 1:
break
| import sys
import git
r = git.Repo( sys.argv[1] )
def printTree( tree, indent=0 ):
prefix = ' '*indent
print( prefix, '-' * 16 )
print( prefix, 'Tree path %s' % (tree.path,) )
for blob in tree:
print( prefix, '%s %s (%s)' % (blob.type, blob.path, blob.hexsha) )
for child in tree.trees:
printTree( child, indent+4 )
for index, commit in enumerate(r.iter_commits( None )):
print( '=' * 60 )
for name in sorted( dir( commit ) ):
if name[0] not in 'abcdefghijklmnopqrstuvwxyz':
continue
print( 'Commit: %s: %r' % (name, getattr( commit, name )) )
print( '-' * 60 )
stats = commit.stats
for name in sorted( dir( stats ) ):
if name[0] not in 'abcdefghijklmnopqrstuvwxyz':
continue
if name == 'files':
for file in stats.files:
print( 'Commit.Stats.files: %s: %r' % (file, stats.files[file]) )
else:
print( 'Commit.Stats: %s: %r' % (name, getattr( stats, name )) )
print( '-' * 60 )
tree = commit.tree
printTree( tree )
+
+ if index > 1:
+ break | 3 | 0.069767 | 3 | 0 |
c399db809d2e6ce5fc143a8c112553c4215235cc | ansible/roles/kraken.fabric/kraken.fabric.flannel/tasks/main.yml | ansible/roles/kraken.fabric/kraken.fabric.flannel/tasks/main.yml | ---
- name: Ensuring fabric directory exists
shell: >
mkdir -p {{ config_base | expanduser }}/{{kraken_config.cluster}}/fabric
ignore_errors: yes
- name: Generate canal deployment file
template: src=canal.yaml.part.jinja2
dest="{{ config_base | expanduser }}/{{kraken_config.cluster}}/fabric/canal.yaml"
- name: Generate canal configuration file
template: src=config.yaml.part.jinja2
dest="{{ config_base | expanduser }}/{{kraken_config.cluster}}/fabric/config.yaml"
- name: Wait for api server to become available in case it's not
wait_for:
host: "{{ item|regex_replace('https://','') }}"
port: 443
timeout: 600
with_items: "{{ api_servers }}"
- name: Ensure the kube-networking namespace exists
command: >
kubectl --kubeconfig={{ kubeconfig | expanduser }} create namespace kube-networking
retries: 120
delay: 1
- name: Deploy canal configuration
command: >
kubectl --kubeconfig={{ kubeconfig | expanduser }} apply -f {{ config_base | expanduser }}/{{kraken_config.cluster}}/fabric/config.yaml
- name: Deploy canal daemonset
command: >
kubectl --kubeconfig={{ kubeconfig | expanduser }} apply -f {{ config_base | expanduser }}/{{kraken_config.cluster}}/fabric/canal.yaml
| ---
- name: Ensuring fabric directory exists
shell: >
mkdir -p {{ config_base | expanduser }}/{{kraken_config.cluster}}/fabric
ignore_errors: yes
- name: Generate canal deployment file
template: src=canal.yaml.part.jinja2
dest="{{ config_base | expanduser }}/{{kraken_config.cluster}}/fabric/canal.yaml"
- name: Generate canal configuration file
template: src=config.yaml.part.jinja2
dest="{{ config_base | expanduser }}/{{kraken_config.cluster}}/fabric/config.yaml"
- name: Wait for api server to become available in case it's not
wait_for:
host: "{{ item|regex_replace('https://','') }}"
port: 443
timeout: 600
with_items: "{{ api_servers }}"
- name: check kube-networking namespace state
command: >
kubectl --kubeconfig={{ kubeconfig | expanduser }} get namespace kube-networking
ignore_errors: yes
changed_when: false
register: kube_networking_namespace
- name: Ensure the kube-networking namespace exists
command: >
kubectl --kubeconfig={{ kubeconfig | expanduser }} create namespace kube-networking
retries: 120
delay: 1
when: not kube_networking_namespace.rc == 0
- name: Deploy canal configuration
command: >
kubectl --kubeconfig={{ kubeconfig | expanduser }} apply -f {{ config_base | expanduser }}/{{kraken_config.cluster}}/fabric/config.yaml
- name: Deploy canal daemonset
command: >
kubectl --kubeconfig={{ kubeconfig | expanduser }} apply -f {{ config_base | expanduser }}/{{kraken_config.cluster}}/fabric/canal.yaml
| Check if the kube-networking namespace exists | Check if the kube-networking namespace exists
On a second "up" run, `Ensure the kube-networking namespace exists`
failed with:
> "Error from server: namespaces \"kube-networking\" already exists", "stdout"
This checks to see if the namespace has already been created and skips
creation if it does.
| YAML | apache-2.0 | samsung-cnct/k2,leahnp/k2,yenicapotediaz/k2,alejandroEsc/k2,leahnp/k2,samsung-cnct/k2,samsung-cnct/kraken-lib,yenicapotediaz/k2,samsung-cnct/kraken-lib,alejandroEsc/k2,samsung-cnct/kraken-lib | yaml | ## Code Before:
---
- name: Ensuring fabric directory exists
shell: >
mkdir -p {{ config_base | expanduser }}/{{kraken_config.cluster}}/fabric
ignore_errors: yes
- name: Generate canal deployment file
template: src=canal.yaml.part.jinja2
dest="{{ config_base | expanduser }}/{{kraken_config.cluster}}/fabric/canal.yaml"
- name: Generate canal configuration file
template: src=config.yaml.part.jinja2
dest="{{ config_base | expanduser }}/{{kraken_config.cluster}}/fabric/config.yaml"
- name: Wait for api server to become available in case it's not
wait_for:
host: "{{ item|regex_replace('https://','') }}"
port: 443
timeout: 600
with_items: "{{ api_servers }}"
- name: Ensure the kube-networking namespace exists
command: >
kubectl --kubeconfig={{ kubeconfig | expanduser }} create namespace kube-networking
retries: 120
delay: 1
- name: Deploy canal configuration
command: >
kubectl --kubeconfig={{ kubeconfig | expanduser }} apply -f {{ config_base | expanduser }}/{{kraken_config.cluster}}/fabric/config.yaml
- name: Deploy canal daemonset
command: >
kubectl --kubeconfig={{ kubeconfig | expanduser }} apply -f {{ config_base | expanduser }}/{{kraken_config.cluster}}/fabric/canal.yaml
## Instruction:
Check if the kube-networking namespace exists
On a second "up" run, `Ensure the kube-networking namespace exists`
failed with:
> "Error from server: namespaces \"kube-networking\" already exists", "stdout"
This checks to see if the namespace has already been created and skips
creation if it does.
## Code After:
---
- name: Ensuring fabric directory exists
shell: >
mkdir -p {{ config_base | expanduser }}/{{kraken_config.cluster}}/fabric
ignore_errors: yes
- name: Generate canal deployment file
template: src=canal.yaml.part.jinja2
dest="{{ config_base | expanduser }}/{{kraken_config.cluster}}/fabric/canal.yaml"
- name: Generate canal configuration file
template: src=config.yaml.part.jinja2
dest="{{ config_base | expanduser }}/{{kraken_config.cluster}}/fabric/config.yaml"
- name: Wait for api server to become available in case it's not
wait_for:
host: "{{ item|regex_replace('https://','') }}"
port: 443
timeout: 600
with_items: "{{ api_servers }}"
- name: check kube-networking namespace state
command: >
kubectl --kubeconfig={{ kubeconfig | expanduser }} get namespace kube-networking
ignore_errors: yes
changed_when: false
register: kube_networking_namespace
- name: Ensure the kube-networking namespace exists
command: >
kubectl --kubeconfig={{ kubeconfig | expanduser }} create namespace kube-networking
retries: 120
delay: 1
when: not kube_networking_namespace.rc == 0
- name: Deploy canal configuration
command: >
kubectl --kubeconfig={{ kubeconfig | expanduser }} apply -f {{ config_base | expanduser }}/{{kraken_config.cluster}}/fabric/config.yaml
- name: Deploy canal daemonset
command: >
kubectl --kubeconfig={{ kubeconfig | expanduser }} apply -f {{ config_base | expanduser }}/{{kraken_config.cluster}}/fabric/canal.yaml
| ---
- name: Ensuring fabric directory exists
shell: >
mkdir -p {{ config_base | expanduser }}/{{kraken_config.cluster}}/fabric
ignore_errors: yes
- name: Generate canal deployment file
template: src=canal.yaml.part.jinja2
dest="{{ config_base | expanduser }}/{{kraken_config.cluster}}/fabric/canal.yaml"
- name: Generate canal configuration file
template: src=config.yaml.part.jinja2
dest="{{ config_base | expanduser }}/{{kraken_config.cluster}}/fabric/config.yaml"
- name: Wait for api server to become available in case it's not
wait_for:
host: "{{ item|regex_replace('https://','') }}"
port: 443
timeout: 600
with_items: "{{ api_servers }}"
+ - name: check kube-networking namespace state
+ command: >
+ kubectl --kubeconfig={{ kubeconfig | expanduser }} get namespace kube-networking
+ ignore_errors: yes
+ changed_when: false
+ register: kube_networking_namespace
+
- name: Ensure the kube-networking namespace exists
command: >
kubectl --kubeconfig={{ kubeconfig | expanduser }} create namespace kube-networking
retries: 120
delay: 1
+ when: not kube_networking_namespace.rc == 0
- name: Deploy canal configuration
command: >
kubectl --kubeconfig={{ kubeconfig | expanduser }} apply -f {{ config_base | expanduser }}/{{kraken_config.cluster}}/fabric/config.yaml
- name: Deploy canal daemonset
command: >
kubectl --kubeconfig={{ kubeconfig | expanduser }} apply -f {{ config_base | expanduser }}/{{kraken_config.cluster}}/fabric/canal.yaml | 8 | 0.235294 | 8 | 0 |
66ab51374d81034bb150a9f45d0ec3f0bac92500 | lib/ceely/note_relation.rb | lib/ceely/note_relation.rb | module Ceely
# A NoteRelation is a Note that takes a base note, a relation number
# an interval factor
class NoteRelation < Note
attr_reader :base, :relation, :interval_factor
def initialize(base, relation, interval_factor)
@base, @relation, @interval_factor = base, relation, interval_factor
super((base.frequency * interval_factor).to_f)
end
def base?
(base.frequency == frequency)
end
# Intended to be overridden by subclasses
def octave
end
# Intended to be overridden by subclasses
def octave_denominator
end
def octave_ratio
@octave_ratio ||= Rational(interval_factor, octave_denominator)
end
def octave_frequency
@octave_frequency ||= octave_ratio.to_f * base.frequency
end
end
end
| module Ceely
# A NoteRelation is a Note that takes a base note, a relation number
# an interval factor
class NoteRelation < Note
attr_reader :base, :relation, :interval_factor
def initialize(base, relation, interval_factor)
@base, @relation, @interval_factor = base, relation, interval_factor
super((base.frequency * interval_factor).to_f)
end
# Intended to be overridden by subclasses
def octave
end
# Intended to be overridden by subclasses
def octave_denominator
end
def octave_ratio
@octave_ratio ||= Rational(interval_factor, octave_denominator)
end
def octave_frequency
@octave_frequency ||= octave_ratio.to_f * base.frequency
end
end
end
| Remove base check since it's not being used :sparkles: | Remove base check since it's not being used :sparkles:
| Ruby | mit | scotdalton/ceely,scotdalton/ceely | ruby | ## Code Before:
module Ceely
# A NoteRelation is a Note that takes a base note, a relation number
# an interval factor
class NoteRelation < Note
attr_reader :base, :relation, :interval_factor
def initialize(base, relation, interval_factor)
@base, @relation, @interval_factor = base, relation, interval_factor
super((base.frequency * interval_factor).to_f)
end
def base?
(base.frequency == frequency)
end
# Intended to be overridden by subclasses
def octave
end
# Intended to be overridden by subclasses
def octave_denominator
end
def octave_ratio
@octave_ratio ||= Rational(interval_factor, octave_denominator)
end
def octave_frequency
@octave_frequency ||= octave_ratio.to_f * base.frequency
end
end
end
## Instruction:
Remove base check since it's not being used :sparkles:
## Code After:
module Ceely
# A NoteRelation is a Note that takes a base note, a relation number
# an interval factor
class NoteRelation < Note
attr_reader :base, :relation, :interval_factor
def initialize(base, relation, interval_factor)
@base, @relation, @interval_factor = base, relation, interval_factor
super((base.frequency * interval_factor).to_f)
end
# Intended to be overridden by subclasses
def octave
end
# Intended to be overridden by subclasses
def octave_denominator
end
def octave_ratio
@octave_ratio ||= Rational(interval_factor, octave_denominator)
end
def octave_frequency
@octave_frequency ||= octave_ratio.to_f * base.frequency
end
end
end
| module Ceely
# A NoteRelation is a Note that takes a base note, a relation number
# an interval factor
class NoteRelation < Note
attr_reader :base, :relation, :interval_factor
def initialize(base, relation, interval_factor)
@base, @relation, @interval_factor = base, relation, interval_factor
super((base.frequency * interval_factor).to_f)
- end
-
- def base?
- (base.frequency == frequency)
end
# Intended to be overridden by subclasses
def octave
end
# Intended to be overridden by subclasses
def octave_denominator
end
def octave_ratio
@octave_ratio ||= Rational(interval_factor, octave_denominator)
end
def octave_frequency
@octave_frequency ||= octave_ratio.to_f * base.frequency
end
end
end | 4 | 0.125 | 0 | 4 |
bdd9c733e40fb557bcb8a84a2e8f79012776673b | index.html | index.html | ---
layout: home
title: Orestes Carracedo
---
<div class="col_2"></div>
<div id="home" class="col_8">
<h1>{{ page.title }}</h1>
<div class="posts">
{% for post in site.posts %}
<div class="post">
<div class="title"><a href="{{ post.url }}#disqus_thread">{{ post.title }}</a></div>
<div class="date">{{ post.date | date_to_long_string }}</div>
<div class="content">{{ post.content }}</div>
<div class="comments">Comments</div>
</div>
{% endfor %}
</div>
</div>
<div class="col_2"></div>
| ---
layout: home
title: Orestes Carracedo
---
<div class="col_2"></div>
<div id="home" class="col_8">
<h1>{{ page.title }}</h1>
<div class="posts">
{% for post in site.posts %}
<div class="post">
<div class="title"><a href="{{ post.url }}">{{ post.title }}</a></div>
<div class="date">{{ post.date | date_to_long_string }}</div>
<div class="content">{{ post.content }}</div>
<div class="comments"><a href="{{ post.url ]]#disqus_thread"> </a></div>
</div>
{% endfor %}
</div>
</div>
<div class="col_2"></div>
| Remove Disqus' comments link from post title, add it to the comment counter | Remove Disqus' comments link from post title, add it to the comment counter
| HTML | mit | orestes/blog.orestes.io,orestes/blog.orestes.io,orestes/blog.orestes.io | html | ## Code Before:
---
layout: home
title: Orestes Carracedo
---
<div class="col_2"></div>
<div id="home" class="col_8">
<h1>{{ page.title }}</h1>
<div class="posts">
{% for post in site.posts %}
<div class="post">
<div class="title"><a href="{{ post.url }}#disqus_thread">{{ post.title }}</a></div>
<div class="date">{{ post.date | date_to_long_string }}</div>
<div class="content">{{ post.content }}</div>
<div class="comments">Comments</div>
</div>
{% endfor %}
</div>
</div>
<div class="col_2"></div>
## Instruction:
Remove Disqus' comments link from post title, add it to the comment counter
## Code After:
---
layout: home
title: Orestes Carracedo
---
<div class="col_2"></div>
<div id="home" class="col_8">
<h1>{{ page.title }}</h1>
<div class="posts">
{% for post in site.posts %}
<div class="post">
<div class="title"><a href="{{ post.url }}">{{ post.title }}</a></div>
<div class="date">{{ post.date | date_to_long_string }}</div>
<div class="content">{{ post.content }}</div>
<div class="comments"><a href="{{ post.url ]]#disqus_thread"> </a></div>
</div>
{% endfor %}
</div>
</div>
<div class="col_2"></div>
| ---
layout: home
title: Orestes Carracedo
---
<div class="col_2"></div>
<div id="home" class="col_8">
<h1>{{ page.title }}</h1>
<div class="posts">
{% for post in site.posts %}
<div class="post">
- <div class="title"><a href="{{ post.url }}#disqus_thread">{{ post.title }}</a></div>
? --------------
+ <div class="title"><a href="{{ post.url }}">{{ post.title }}</a></div>
<div class="date">{{ post.date | date_to_long_string }}</div>
<div class="content">{{ post.content }}</div>
- <div class="comments">Comments</div>
+ <div class="comments"><a href="{{ post.url ]]#disqus_thread"> </a></div>
</div>
{% endfor %}
</div>
</div>
<div class="col_2"></div> | 4 | 0.190476 | 2 | 2 |
72c37a7964b3d2f0b69b07c84086ee5ec7cfe04c | src/SFA.DAS.EmployerApprenticeshipsService.Database/SFA.DAS.EmployerApprenticeshipsService.Database.publish.xml | src/SFA.DAS.EmployerApprenticeshipsService.Database/SFA.DAS.EmployerApprenticeshipsService.Database.publish.xml | <?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<IncludeCompositeObjects>True</IncludeCompositeObjects>
<TargetDatabaseName>__TargetDatabaseName__</TargetDatabaseName>
<DeployScriptFileName>SFA.DAS.EmployerApprenticeshipsService.Database.sql</DeployScriptFileName>
<ProfileVersionNumber>1</ProfileVersionNumber>
<TargetConnectionString>Data Source=__DBServer__;Persist Security Info=True;User ID=__DBUser__;Pooling=False;MultipleActiveResultSets=False;Connect Timeout=60;Encrypt=False;TrustServerCertificate=True</TargetConnectionString>
</PropertyGroup>
</Project> | <?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<IncludeCompositeObjects>True</IncludeCompositeObjects>
<TargetDatabaseName>[TargetDatabaseName]</TargetDatabaseName>
<DeployScriptFileName>SFA.DAS.EmployerApprenticeshipsService.Database.sql</DeployScriptFileName>
<ProfileVersionNumber>1</ProfileVersionNumber>
<TargetConnectionString>Data Source=[DBServer];Persist Security Info=True;User ID=[DBUser];Pooling=False;MultipleActiveResultSets=False;Connect Timeout=60;Encrypt=False;TrustServerCertificate=True</TargetConnectionString>
</PropertyGroup>
</Project> | Remove __ __ as it was never intented to get picked up in transform | Remove __ __ as it was never intented to get picked up in transform
| XML | mit | SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice | xml | ## Code Before:
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<IncludeCompositeObjects>True</IncludeCompositeObjects>
<TargetDatabaseName>__TargetDatabaseName__</TargetDatabaseName>
<DeployScriptFileName>SFA.DAS.EmployerApprenticeshipsService.Database.sql</DeployScriptFileName>
<ProfileVersionNumber>1</ProfileVersionNumber>
<TargetConnectionString>Data Source=__DBServer__;Persist Security Info=True;User ID=__DBUser__;Pooling=False;MultipleActiveResultSets=False;Connect Timeout=60;Encrypt=False;TrustServerCertificate=True</TargetConnectionString>
</PropertyGroup>
</Project>
## Instruction:
Remove __ __ as it was never intented to get picked up in transform
## Code After:
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<IncludeCompositeObjects>True</IncludeCompositeObjects>
<TargetDatabaseName>[TargetDatabaseName]</TargetDatabaseName>
<DeployScriptFileName>SFA.DAS.EmployerApprenticeshipsService.Database.sql</DeployScriptFileName>
<ProfileVersionNumber>1</ProfileVersionNumber>
<TargetConnectionString>Data Source=[DBServer];Persist Security Info=True;User ID=[DBUser];Pooling=False;MultipleActiveResultSets=False;Connect Timeout=60;Encrypt=False;TrustServerCertificate=True</TargetConnectionString>
</PropertyGroup>
</Project> | <?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<IncludeCompositeObjects>True</IncludeCompositeObjects>
- <TargetDatabaseName>__TargetDatabaseName__</TargetDatabaseName>
? ^^ ^^
+ <TargetDatabaseName>[TargetDatabaseName]</TargetDatabaseName>
? ^ ^
<DeployScriptFileName>SFA.DAS.EmployerApprenticeshipsService.Database.sql</DeployScriptFileName>
<ProfileVersionNumber>1</ProfileVersionNumber>
- <TargetConnectionString>Data Source=__DBServer__;Persist Security Info=True;User ID=__DBUser__;Pooling=False;MultipleActiveResultSets=False;Connect Timeout=60;Encrypt=False;TrustServerCertificate=True</TargetConnectionString>
? ^^ ^^ ^^ ^^
+ <TargetConnectionString>Data Source=[DBServer];Persist Security Info=True;User ID=[DBUser];Pooling=False;MultipleActiveResultSets=False;Connect Timeout=60;Encrypt=False;TrustServerCertificate=True</TargetConnectionString>
? ^ ^ ^ ^
</PropertyGroup>
</Project> | 4 | 0.4 | 2 | 2 |
b87f878ad222dc8db6f2b5c7403f42a72927496c | spec/views/ballots/new.html.haml_spec.rb | spec/views/ballots/new.html.haml_spec.rb | require 'spec_helper'
describe 'ballots/new' do
before(:each) do
@election = mock_model(Election)
assign(:election, @election)
@ballot = mock_model(Ballot,
:ranking_30 => nil,
:ranking_31 => nil,
:ranking_32 => nil
).as_new_record
assign(:ballot, @ballot)
@nominations = [
mock_model(Nomination, :id => 30, :name => "John Smith"),
mock_model(Nomination, :id => 31, :name => "Claire Simmons"),
mock_model(Nomination, :id => 32, :name => "Belinda Marsh")
]
assign(:nominations, @nominations)
end
it "renders a ranking field for each of the nominations" do
render
rendered.should have_selector(:input, :name => 'ballot[ranking_30]')
rendered.should have_selector(:input, :name => 'ballot[ranking_31]')
rendered.should have_selector(:input, :name => 'ballot[ranking_32]')
end
it "renders a submit button" do
render
rendered.should have_selector(:input, :type => 'submit')
end
end
| require 'spec_helper'
describe 'ballots/new' do
before(:each) do
@election = mock_model(Election)
assign(:election, @election)
@ballot = mock_model(Ballot,
:ranking_30 => nil,
:ranking_31 => nil,
:ranking_32 => nil
).as_new_record
assign(:ballot, @ballot)
@nominations = [
mock_model(Nomination, :id => 30, :name => "John Smith"),
mock_model(Nomination, :id => 31, :name => "Claire Simmons"),
mock_model(Nomination, :id => 32, :name => "Belinda Marsh")
]
assign(:nominations, @nominations)
@annual_general_meeting = mock_model(AnnualGeneralMeeting, :happened_on => 2.weeks.from_now)
assign(:annual_general_meeting, @annual_general_meeting)
end
it "renders a ranking field for each of the nominations" do
render
rendered.should have_selector(:input, :name => 'ballot[ranking_30]')
rendered.should have_selector(:input, :name => 'ballot[ranking_31]')
rendered.should have_selector(:input, :name => 'ballot[ranking_32]')
end
it "renders a submit button" do
render
rendered.should have_selector(:input, :type => 'submit')
end
end
| Fix ballots/new spec broken by 200bbdd63e4faf1a2fe7b2bfc8136ce340efd2d. | Fix ballots/new spec broken by 200bbdd63e4faf1a2fe7b2bfc8136ce340efd2d.
| Ruby | agpl-3.0 | oneclickorgs/one-click-orgs,oneclickorgs/one-click-orgs,oneclickorgs/one-click-orgs,oneclickorgs/one-click-orgs | ruby | ## Code Before:
require 'spec_helper'
describe 'ballots/new' do
before(:each) do
@election = mock_model(Election)
assign(:election, @election)
@ballot = mock_model(Ballot,
:ranking_30 => nil,
:ranking_31 => nil,
:ranking_32 => nil
).as_new_record
assign(:ballot, @ballot)
@nominations = [
mock_model(Nomination, :id => 30, :name => "John Smith"),
mock_model(Nomination, :id => 31, :name => "Claire Simmons"),
mock_model(Nomination, :id => 32, :name => "Belinda Marsh")
]
assign(:nominations, @nominations)
end
it "renders a ranking field for each of the nominations" do
render
rendered.should have_selector(:input, :name => 'ballot[ranking_30]')
rendered.should have_selector(:input, :name => 'ballot[ranking_31]')
rendered.should have_selector(:input, :name => 'ballot[ranking_32]')
end
it "renders a submit button" do
render
rendered.should have_selector(:input, :type => 'submit')
end
end
## Instruction:
Fix ballots/new spec broken by 200bbdd63e4faf1a2fe7b2bfc8136ce340efd2d.
## Code After:
require 'spec_helper'
describe 'ballots/new' do
before(:each) do
@election = mock_model(Election)
assign(:election, @election)
@ballot = mock_model(Ballot,
:ranking_30 => nil,
:ranking_31 => nil,
:ranking_32 => nil
).as_new_record
assign(:ballot, @ballot)
@nominations = [
mock_model(Nomination, :id => 30, :name => "John Smith"),
mock_model(Nomination, :id => 31, :name => "Claire Simmons"),
mock_model(Nomination, :id => 32, :name => "Belinda Marsh")
]
assign(:nominations, @nominations)
@annual_general_meeting = mock_model(AnnualGeneralMeeting, :happened_on => 2.weeks.from_now)
assign(:annual_general_meeting, @annual_general_meeting)
end
it "renders a ranking field for each of the nominations" do
render
rendered.should have_selector(:input, :name => 'ballot[ranking_30]')
rendered.should have_selector(:input, :name => 'ballot[ranking_31]')
rendered.should have_selector(:input, :name => 'ballot[ranking_32]')
end
it "renders a submit button" do
render
rendered.should have_selector(:input, :type => 'submit')
end
end
| require 'spec_helper'
describe 'ballots/new' do
before(:each) do
@election = mock_model(Election)
assign(:election, @election)
@ballot = mock_model(Ballot,
:ranking_30 => nil,
:ranking_31 => nil,
:ranking_32 => nil
).as_new_record
assign(:ballot, @ballot)
@nominations = [
mock_model(Nomination, :id => 30, :name => "John Smith"),
mock_model(Nomination, :id => 31, :name => "Claire Simmons"),
mock_model(Nomination, :id => 32, :name => "Belinda Marsh")
]
assign(:nominations, @nominations)
+
+ @annual_general_meeting = mock_model(AnnualGeneralMeeting, :happened_on => 2.weeks.from_now)
+ assign(:annual_general_meeting, @annual_general_meeting)
end
it "renders a ranking field for each of the nominations" do
render
rendered.should have_selector(:input, :name => 'ballot[ranking_30]')
rendered.should have_selector(:input, :name => 'ballot[ranking_31]')
rendered.should have_selector(:input, :name => 'ballot[ranking_32]')
end
it "renders a submit button" do
render
rendered.should have_selector(:input, :type => 'submit')
end
end | 3 | 0.083333 | 3 | 0 |
565d8da8471ee5149b65b343eb68ff660e45be0a | server/errors.go | server/errors.go | package server
import (
"net/http"
"github.com/heroku/busl/assets"
"github.com/heroku/busl/broker"
"github.com/heroku/busl/storage"
"github.com/heroku/busl/util"
)
func handleError(w http.ResponseWriter, r *http.Request, err error) {
if err == broker.ErrNotRegistered || err == storage.ErrNoStorage {
message := "Channel is not registered."
if r.Header.Get("Accept") == "text/ascii; version=feral" {
message = assets.HttpCatGone
}
http.Error(w, message, http.StatusNotFound)
} else if err != nil {
util.CountWithData("server.handleError", 1, "error=%s", err.Error())
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
}
}
| package server
import (
"errors"
"net/http"
"github.com/heroku/busl/assets"
"github.com/heroku/busl/broker"
"github.com/heroku/busl/storage"
"github.com/heroku/busl/util"
)
var errNoContent = errors.New("No Content")
func handleError(w http.ResponseWriter, r *http.Request, err error) {
if err == broker.ErrNotRegistered || err == storage.ErrNoStorage {
message := "Channel is not registered."
if r.Header.Get("Accept") == "text/ascii; version=feral" {
message = assets.HttpCatGone
}
http.Error(w, message, http.StatusNotFound)
} else if err == errNoContent {
// As indicated in the w3 spec[1] an SSE stream
// that's already done should return a `204 No Content`
// [1]: http://www.w3.org/TR/2012/WD-eventsource-20120426/
w.WriteHeader(http.StatusNoContent)
} else if err != nil {
util.CountWithData("server.handleError", 1, "error=%s", err.Error())
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
}
}
| Use errNoContent to signal 204 | Use errNoContent to signal 204
| Go | mit | cyx/busl,heroku/busl,heroku/busl | go | ## Code Before:
package server
import (
"net/http"
"github.com/heroku/busl/assets"
"github.com/heroku/busl/broker"
"github.com/heroku/busl/storage"
"github.com/heroku/busl/util"
)
func handleError(w http.ResponseWriter, r *http.Request, err error) {
if err == broker.ErrNotRegistered || err == storage.ErrNoStorage {
message := "Channel is not registered."
if r.Header.Get("Accept") == "text/ascii; version=feral" {
message = assets.HttpCatGone
}
http.Error(w, message, http.StatusNotFound)
} else if err != nil {
util.CountWithData("server.handleError", 1, "error=%s", err.Error())
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
}
}
## Instruction:
Use errNoContent to signal 204
## Code After:
package server
import (
"errors"
"net/http"
"github.com/heroku/busl/assets"
"github.com/heroku/busl/broker"
"github.com/heroku/busl/storage"
"github.com/heroku/busl/util"
)
var errNoContent = errors.New("No Content")
func handleError(w http.ResponseWriter, r *http.Request, err error) {
if err == broker.ErrNotRegistered || err == storage.ErrNoStorage {
message := "Channel is not registered."
if r.Header.Get("Accept") == "text/ascii; version=feral" {
message = assets.HttpCatGone
}
http.Error(w, message, http.StatusNotFound)
} else if err == errNoContent {
// As indicated in the w3 spec[1] an SSE stream
// that's already done should return a `204 No Content`
// [1]: http://www.w3.org/TR/2012/WD-eventsource-20120426/
w.WriteHeader(http.StatusNoContent)
} else if err != nil {
util.CountWithData("server.handleError", 1, "error=%s", err.Error())
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
}
}
| package server
import (
+ "errors"
"net/http"
"github.com/heroku/busl/assets"
"github.com/heroku/busl/broker"
"github.com/heroku/busl/storage"
"github.com/heroku/busl/util"
)
+
+ var errNoContent = errors.New("No Content")
func handleError(w http.ResponseWriter, r *http.Request, err error) {
if err == broker.ErrNotRegistered || err == storage.ErrNoStorage {
message := "Channel is not registered."
if r.Header.Get("Accept") == "text/ascii; version=feral" {
message = assets.HttpCatGone
}
http.Error(w, message, http.StatusNotFound)
+ } else if err == errNoContent {
+ // As indicated in the w3 spec[1] an SSE stream
+ // that's already done should return a `204 No Content`
+ // [1]: http://www.w3.org/TR/2012/WD-eventsource-20120426/
+ w.WriteHeader(http.StatusNoContent)
+
} else if err != nil {
util.CountWithData("server.handleError", 1, "error=%s", err.Error())
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
}
} | 9 | 0.36 | 9 | 0 |
3859cf8e5cb2b867abbbff792def4245eef6c467 | requirements.txt | requirements.txt | banal>=0.4.2
normality>=1.0.1
pantomime>=0.3.3
servicelayer[google]==1.8.4
servicelayer[amazon]==1.8.4
balkhash[leveldb]==1.0.0
balkhash[sql]==1.0.0
followthemoney==1.20.0
languagecodes>=1.0.5
psycopg2-binary
grpcio>=1.21.1
google-cloud-vision==0.39.0
google-cloud-storage==1.19.0
# Development
nose
click>=7.0
# File format support
dbf>=0.96.8
pdflib>=0.2.1
pymediainfo>=2.3.0
python-magic>=0.4.12
pypdf2>=1.26.0
rarfile>=3.0
xlrd>=1.2.0
pyicu>=2.0.3
openpyxl>=2.5.14
odfpy>=1.3.5
imapclient>=1.0.2
cchardet>=2.1.1
lxml>=4.2.1
olefile>=0.44
pillow>=5.1.0
vobject==0.9.6.1
msglite>=0.25.0
# Get rid of:
# Used for LibreOffice converter service
cryptography==2.6.1
requests[security]>=2.21.0 | banal>=0.4.2
normality>=1.0.1
pantomime>=0.3.3
servicelayer[google,amazon]==1.8.4
balkhash[leveldb,sql]==1.0.1
followthemoney==1.20.0
languagecodes>=1.0.5
psycopg2-binary
grpcio>=1.21.1
google-cloud-vision==0.39.0
google-cloud-storage==1.19.0
# Development
nose
click>=7.0
# File format support
dbf>=0.96.8
pdflib>=0.2.1
pymediainfo>=2.3.0
python-magic>=0.4.12
pypdf2>=1.26.0
rarfile>=3.0
xlrd>=1.2.0
pyicu>=2.0.3
openpyxl>=2.5.14
odfpy>=1.3.5
imapclient>=1.0.2
cchardet>=2.1.1
lxml>=4.2.1
olefile>=0.44
pillow>=5.1.0
vobject==0.9.6.1
msglite>=0.25.0
# Get rid of:
# Used for LibreOffice converter service
cryptography==2.6.1
requests[security]>=2.21.0 | Fix up extras install syntax | Fix up extras install syntax
| Text | mit | alephdata/ingestors | text | ## Code Before:
banal>=0.4.2
normality>=1.0.1
pantomime>=0.3.3
servicelayer[google]==1.8.4
servicelayer[amazon]==1.8.4
balkhash[leveldb]==1.0.0
balkhash[sql]==1.0.0
followthemoney==1.20.0
languagecodes>=1.0.5
psycopg2-binary
grpcio>=1.21.1
google-cloud-vision==0.39.0
google-cloud-storage==1.19.0
# Development
nose
click>=7.0
# File format support
dbf>=0.96.8
pdflib>=0.2.1
pymediainfo>=2.3.0
python-magic>=0.4.12
pypdf2>=1.26.0
rarfile>=3.0
xlrd>=1.2.0
pyicu>=2.0.3
openpyxl>=2.5.14
odfpy>=1.3.5
imapclient>=1.0.2
cchardet>=2.1.1
lxml>=4.2.1
olefile>=0.44
pillow>=5.1.0
vobject==0.9.6.1
msglite>=0.25.0
# Get rid of:
# Used for LibreOffice converter service
cryptography==2.6.1
requests[security]>=2.21.0
## Instruction:
Fix up extras install syntax
## Code After:
banal>=0.4.2
normality>=1.0.1
pantomime>=0.3.3
servicelayer[google,amazon]==1.8.4
balkhash[leveldb,sql]==1.0.1
followthemoney==1.20.0
languagecodes>=1.0.5
psycopg2-binary
grpcio>=1.21.1
google-cloud-vision==0.39.0
google-cloud-storage==1.19.0
# Development
nose
click>=7.0
# File format support
dbf>=0.96.8
pdflib>=0.2.1
pymediainfo>=2.3.0
python-magic>=0.4.12
pypdf2>=1.26.0
rarfile>=3.0
xlrd>=1.2.0
pyicu>=2.0.3
openpyxl>=2.5.14
odfpy>=1.3.5
imapclient>=1.0.2
cchardet>=2.1.1
lxml>=4.2.1
olefile>=0.44
pillow>=5.1.0
vobject==0.9.6.1
msglite>=0.25.0
# Get rid of:
# Used for LibreOffice converter service
cryptography==2.6.1
requests[security]>=2.21.0 | banal>=0.4.2
normality>=1.0.1
pantomime>=0.3.3
- servicelayer[google]==1.8.4
+ servicelayer[google,amazon]==1.8.4
? +++++++
- servicelayer[amazon]==1.8.4
- balkhash[leveldb]==1.0.0
? ^
+ balkhash[leveldb,sql]==1.0.1
? ++++ ^
- balkhash[sql]==1.0.0
followthemoney==1.20.0
languagecodes>=1.0.5
psycopg2-binary
grpcio>=1.21.1
google-cloud-vision==0.39.0
google-cloud-storage==1.19.0
# Development
nose
click>=7.0
# File format support
dbf>=0.96.8
pdflib>=0.2.1
pymediainfo>=2.3.0
python-magic>=0.4.12
pypdf2>=1.26.0
rarfile>=3.0
xlrd>=1.2.0
pyicu>=2.0.3
openpyxl>=2.5.14
odfpy>=1.3.5
imapclient>=1.0.2
cchardet>=2.1.1
lxml>=4.2.1
olefile>=0.44
pillow>=5.1.0
vobject==0.9.6.1
msglite>=0.25.0
# Get rid of:
# Used for LibreOffice converter service
cryptography==2.6.1
requests[security]>=2.21.0 | 6 | 0.142857 | 2 | 4 |
58004a0859affffff4c8f155be9fec34bd78f994 | .travis.yml | .travis.yml | language: ruby
script: rspec
services: mongodb
rvm:
- 1.9.2
- 1.9.3
- 2.0.0
gemfile:
- gemfiles/active_record/3-0.gemfile
- gemfiles/active_record/3-1.gemfile
- gemfiles/active_record/3-2.gemfile
- gemfiles/active_record/4-0.gemfile
- gemfiles/mongo_mapper/0-9.gemfile
- gemfiles/mongo_mapper/0-10.gemfile
- gemfiles/mongo_mapper/0-11.gemfile
- gemfiles/mongo_mapper/0-12.gemfile
- gemfiles/mongoid/2-0.gemfile
- gemfiles/mongoid/2-1.gemfile
- gemfiles/mongoid/2-2.gemfile
- gemfiles/mongoid/2-3.gemfile
- gemfiles/mongoid/2-4.gemfile
- gemfiles/mongoid/3-0.gemfile
- gemfiles/data_mapper/1-0.gemfile
- gemfiles/data_mapper/1-1.gemfile
- gemfiles/data_mapper/1-2.gemfile
matrix:
exclude:
- rvm: 1.9.2
gemfile: gemfiles/mongoid/3-0.gemfile
- rvm: 1.9.2
gemfile: gemfiles/active_record/4-0.gemfile
| language: ruby
script: rspec
services: mongodb
rvm:
- 1.9.2
- 1.9.3
- 2.0.0
gemfile:
- gemfiles/active_record/3-0.gemfile
- gemfiles/active_record/3-1.gemfile
- gemfiles/active_record/3-2.gemfile
- gemfiles/active_record/4-0.gemfile
- gemfiles/mongo_mapper/0-9.gemfile
- gemfiles/mongo_mapper/0-10.gemfile
- gemfiles/mongo_mapper/0-11.gemfile
- gemfiles/mongo_mapper/0-12.gemfile
- gemfiles/mongoid/2-0.gemfile
- gemfiles/mongoid/2-1.gemfile
- gemfiles/mongoid/2-2.gemfile
- gemfiles/mongoid/2-3.gemfile
- gemfiles/mongoid/2-4.gemfile
- gemfiles/mongoid/3-0.gemfile
- gemfiles/data_mapper/1-0.gemfile
- gemfiles/data_mapper/1-1.gemfile
- gemfiles/data_mapper/1-2.gemfile
matrix:
exclude:
- rvm: 1.9.2
gemfile: gemfiles/mongoid/3-0.gemfile
- rvm: 1.9.2
gemfile: gemfiles/active_record/4-0.gemfile
include:
- rvm: 1.9.3
gemfile: Gemfile
script: rake
| Include the default Rake task in Travis for coverage reporting | Include the default Rake task in Travis for coverage reporting
| YAML | mit | laserlemon/periscope | yaml | ## Code Before:
language: ruby
script: rspec
services: mongodb
rvm:
- 1.9.2
- 1.9.3
- 2.0.0
gemfile:
- gemfiles/active_record/3-0.gemfile
- gemfiles/active_record/3-1.gemfile
- gemfiles/active_record/3-2.gemfile
- gemfiles/active_record/4-0.gemfile
- gemfiles/mongo_mapper/0-9.gemfile
- gemfiles/mongo_mapper/0-10.gemfile
- gemfiles/mongo_mapper/0-11.gemfile
- gemfiles/mongo_mapper/0-12.gemfile
- gemfiles/mongoid/2-0.gemfile
- gemfiles/mongoid/2-1.gemfile
- gemfiles/mongoid/2-2.gemfile
- gemfiles/mongoid/2-3.gemfile
- gemfiles/mongoid/2-4.gemfile
- gemfiles/mongoid/3-0.gemfile
- gemfiles/data_mapper/1-0.gemfile
- gemfiles/data_mapper/1-1.gemfile
- gemfiles/data_mapper/1-2.gemfile
matrix:
exclude:
- rvm: 1.9.2
gemfile: gemfiles/mongoid/3-0.gemfile
- rvm: 1.9.2
gemfile: gemfiles/active_record/4-0.gemfile
## Instruction:
Include the default Rake task in Travis for coverage reporting
## Code After:
language: ruby
script: rspec
services: mongodb
rvm:
- 1.9.2
- 1.9.3
- 2.0.0
gemfile:
- gemfiles/active_record/3-0.gemfile
- gemfiles/active_record/3-1.gemfile
- gemfiles/active_record/3-2.gemfile
- gemfiles/active_record/4-0.gemfile
- gemfiles/mongo_mapper/0-9.gemfile
- gemfiles/mongo_mapper/0-10.gemfile
- gemfiles/mongo_mapper/0-11.gemfile
- gemfiles/mongo_mapper/0-12.gemfile
- gemfiles/mongoid/2-0.gemfile
- gemfiles/mongoid/2-1.gemfile
- gemfiles/mongoid/2-2.gemfile
- gemfiles/mongoid/2-3.gemfile
- gemfiles/mongoid/2-4.gemfile
- gemfiles/mongoid/3-0.gemfile
- gemfiles/data_mapper/1-0.gemfile
- gemfiles/data_mapper/1-1.gemfile
- gemfiles/data_mapper/1-2.gemfile
matrix:
exclude:
- rvm: 1.9.2
gemfile: gemfiles/mongoid/3-0.gemfile
- rvm: 1.9.2
gemfile: gemfiles/active_record/4-0.gemfile
include:
- rvm: 1.9.3
gemfile: Gemfile
script: rake
| language: ruby
script: rspec
services: mongodb
rvm:
- 1.9.2
- 1.9.3
- 2.0.0
gemfile:
- gemfiles/active_record/3-0.gemfile
- gemfiles/active_record/3-1.gemfile
- gemfiles/active_record/3-2.gemfile
- gemfiles/active_record/4-0.gemfile
- gemfiles/mongo_mapper/0-9.gemfile
- gemfiles/mongo_mapper/0-10.gemfile
- gemfiles/mongo_mapper/0-11.gemfile
- gemfiles/mongo_mapper/0-12.gemfile
- gemfiles/mongoid/2-0.gemfile
- gemfiles/mongoid/2-1.gemfile
- gemfiles/mongoid/2-2.gemfile
- gemfiles/mongoid/2-3.gemfile
- gemfiles/mongoid/2-4.gemfile
- gemfiles/mongoid/3-0.gemfile
- gemfiles/data_mapper/1-0.gemfile
- gemfiles/data_mapper/1-1.gemfile
- gemfiles/data_mapper/1-2.gemfile
matrix:
exclude:
- rvm: 1.9.2
gemfile: gemfiles/mongoid/3-0.gemfile
- rvm: 1.9.2
gemfile: gemfiles/active_record/4-0.gemfile
+ include:
+ - rvm: 1.9.3
+ gemfile: Gemfile
+ script: rake | 4 | 0.129032 | 4 | 0 |
c676bcede639977ebbf23983d90c64ac579e8c8b | _posts/prods/2022-02-13-master-mode7.md | _posts/prods/2022-02-13-master-mode7.md | ---
layout: prods_post
category: [posts, prods]
tags: lovebyte2022
rank: 21st in Oldschool 256b intro
title: Master / Mode7
img: mmode7-screenshot.png
alt: image-alt
authors: VectorEyes
team: Bitshifters
year: 2022
type: 256 Byte Demo
platform: BBC Master
download: mmode7.ssd
video: https://www.youtube.com/watch?v=-dXdqsF7o70
---
**Master / Mode7**
A 256b (well, 254b!) intro for the BBC Master.
By VectorEyes of Bitshifters.
This started out as an experiment to see how faithfully I could reproduce the *astounding* C64 256b demo “A Mind is Born”. The answer turned out to be: not very well at all, so I took things in a different direction and hacked together something that uses the BBC Master’s Teletext capabilities (Mode 7) to display a few different patterns. I hope you enjoy it!
The music is semi-random. I was incredibly lucky to capture a video where the last few bars sound like a proper ‘ending’. At some point soon I'll make a version that seeds the RNG properly and produces fully consistent music.
VectorEyes, 22:15pm GMT, 10th Feb 2022 (45 minutes before submission deadline!)
| ---
layout: prods_post
category: [posts, prods]
tags: lovebyte2022
rank: 21st in Oldschool 256b intro
title: Master / Mode7
img: mmode7-screenshot.png
alt: image-alt
authors: VectorEyes
team: Bitshifters
year: 2022
type: 256 Byte Demo
platform: BBC Master
download: mmode7.ssd
pouet: https://www.pouet.net/prod.php?which=91097
video: https://www.youtube.com/watch?v=-dXdqsF7o70
---
**Master / Mode7**
A 256b (well, 254b!) intro for the BBC Master.
By VectorEyes of Bitshifters.
This started out as an experiment to see how faithfully I could reproduce the *astounding* C64 256b demo “A Mind is Born”. The answer turned out to be: not very well at all, so I took things in a different direction and hacked together something that uses the BBC Master’s Teletext capabilities (Mode 7) to display a few different patterns. I hope you enjoy it!
The music is semi-random. I was incredibly lucky to capture a video where the last few bars sound like a proper ‘ending’. At some point soon I'll make a version that seeds the RNG properly and produces fully consistent music.
VectorEyes, 22:15pm GMT, 10th Feb 2022 (45 minutes before submission deadline!)
| Add pouet link for Master / Mode7 | Add pouet link for Master / Mode7
| Markdown | apache-2.0 | bitshifters/bitshifters.github.io,bitshifters/bitshifters.github.io | markdown | ## Code Before:
---
layout: prods_post
category: [posts, prods]
tags: lovebyte2022
rank: 21st in Oldschool 256b intro
title: Master / Mode7
img: mmode7-screenshot.png
alt: image-alt
authors: VectorEyes
team: Bitshifters
year: 2022
type: 256 Byte Demo
platform: BBC Master
download: mmode7.ssd
video: https://www.youtube.com/watch?v=-dXdqsF7o70
---
**Master / Mode7**
A 256b (well, 254b!) intro for the BBC Master.
By VectorEyes of Bitshifters.
This started out as an experiment to see how faithfully I could reproduce the *astounding* C64 256b demo “A Mind is Born”. The answer turned out to be: not very well at all, so I took things in a different direction and hacked together something that uses the BBC Master’s Teletext capabilities (Mode 7) to display a few different patterns. I hope you enjoy it!
The music is semi-random. I was incredibly lucky to capture a video where the last few bars sound like a proper ‘ending’. At some point soon I'll make a version that seeds the RNG properly and produces fully consistent music.
VectorEyes, 22:15pm GMT, 10th Feb 2022 (45 minutes before submission deadline!)
## Instruction:
Add pouet link for Master / Mode7
## Code After:
---
layout: prods_post
category: [posts, prods]
tags: lovebyte2022
rank: 21st in Oldschool 256b intro
title: Master / Mode7
img: mmode7-screenshot.png
alt: image-alt
authors: VectorEyes
team: Bitshifters
year: 2022
type: 256 Byte Demo
platform: BBC Master
download: mmode7.ssd
pouet: https://www.pouet.net/prod.php?which=91097
video: https://www.youtube.com/watch?v=-dXdqsF7o70
---
**Master / Mode7**
A 256b (well, 254b!) intro for the BBC Master.
By VectorEyes of Bitshifters.
This started out as an experiment to see how faithfully I could reproduce the *astounding* C64 256b demo “A Mind is Born”. The answer turned out to be: not very well at all, so I took things in a different direction and hacked together something that uses the BBC Master’s Teletext capabilities (Mode 7) to display a few different patterns. I hope you enjoy it!
The music is semi-random. I was incredibly lucky to capture a video where the last few bars sound like a proper ‘ending’. At some point soon I'll make a version that seeds the RNG properly and produces fully consistent music.
VectorEyes, 22:15pm GMT, 10th Feb 2022 (45 minutes before submission deadline!)
| ---
layout: prods_post
category: [posts, prods]
tags: lovebyte2022
rank: 21st in Oldschool 256b intro
title: Master / Mode7
img: mmode7-screenshot.png
alt: image-alt
authors: VectorEyes
team: Bitshifters
year: 2022
type: 256 Byte Demo
platform: BBC Master
download: mmode7.ssd
+ pouet: https://www.pouet.net/prod.php?which=91097
video: https://www.youtube.com/watch?v=-dXdqsF7o70
---
**Master / Mode7**
A 256b (well, 254b!) intro for the BBC Master.
By VectorEyes of Bitshifters.
This started out as an experiment to see how faithfully I could reproduce the *astounding* C64 256b demo “A Mind is Born”. The answer turned out to be: not very well at all, so I took things in a different direction and hacked together something that uses the BBC Master’s Teletext capabilities (Mode 7) to display a few different patterns. I hope you enjoy it!
The music is semi-random. I was incredibly lucky to capture a video where the last few bars sound like a proper ‘ending’. At some point soon I'll make a version that seeds the RNG properly and produces fully consistent music.
VectorEyes, 22:15pm GMT, 10th Feb 2022 (45 minutes before submission deadline!) | 1 | 0.034483 | 1 | 0 |
e0330f3e2fd94df192038ba379ede587a5dfbcb2 | .github/workflows/pull-request.yml | .github/workflows/pull-request.yml | name: Pull Request
on: [pull_request]
jobs:
test:
strategy:
matrix:
go-version: [1.13.x, 1.14.x, 1.15.x]
os: [ubuntu-20.04]
runs-on: ${{ matrix.os }}
steps:
- name: Install Go
uses: actions/setup-go@v1
with:
go-version: ${{ matrix.go-version }}
- name: Checkout code
uses: actions/checkout@v2
- name: golangci-lint
uses: golangci/golangci-lint-action@v2
with:
version: v1.31
- name: Test
run: go test ./...
| name: Pull Request
on: [pull_request]
jobs:
test:
strategy:
matrix:
go-version: [1.13.x, 1.14.x, 1.15.x]
os: [ubuntu-20.04]
runs-on: ${{ matrix.os }}
steps:
- name: Install Go
uses: actions/setup-go@v1
with:
go-version: ${{ matrix.go-version }}
- name: Checkout code
uses: actions/checkout@v2
- name: Lint
uses: golangci/golangci-lint-action@v2
with:
version: v1.31
- name: Test
run: go test ./...
| Rename workflow step back to Lint | Rename workflow step back to Lint
| YAML | bsd-3-clause | kare/vanity,kare/vanity | yaml | ## Code Before:
name: Pull Request
on: [pull_request]
jobs:
test:
strategy:
matrix:
go-version: [1.13.x, 1.14.x, 1.15.x]
os: [ubuntu-20.04]
runs-on: ${{ matrix.os }}
steps:
- name: Install Go
uses: actions/setup-go@v1
with:
go-version: ${{ matrix.go-version }}
- name: Checkout code
uses: actions/checkout@v2
- name: golangci-lint
uses: golangci/golangci-lint-action@v2
with:
version: v1.31
- name: Test
run: go test ./...
## Instruction:
Rename workflow step back to Lint
## Code After:
name: Pull Request
on: [pull_request]
jobs:
test:
strategy:
matrix:
go-version: [1.13.x, 1.14.x, 1.15.x]
os: [ubuntu-20.04]
runs-on: ${{ matrix.os }}
steps:
- name: Install Go
uses: actions/setup-go@v1
with:
go-version: ${{ matrix.go-version }}
- name: Checkout code
uses: actions/checkout@v2
- name: Lint
uses: golangci/golangci-lint-action@v2
with:
version: v1.31
- name: Test
run: go test ./...
| name: Pull Request
on: [pull_request]
jobs:
test:
strategy:
matrix:
go-version: [1.13.x, 1.14.x, 1.15.x]
os: [ubuntu-20.04]
runs-on: ${{ matrix.os }}
steps:
- name: Install Go
uses: actions/setup-go@v1
with:
go-version: ${{ matrix.go-version }}
- name: Checkout code
uses: actions/checkout@v2
- - name: golangci-lint
+ - name: Lint
uses: golangci/golangci-lint-action@v2
with:
version: v1.31
- name: Test
run: go test ./... | 2 | 0.090909 | 1 | 1 |
af0658e68a3953be975628fe9a4c7c1fe93d7ffb | lib/core/repositories/articles/active_resource.rb | lib/core/repositories/articles/active_resource.rb | require 'active_resource'
require 'forwardable'
module Core
module Repositories
module Articles
class ActiveResource
extend Forwardable
def initialize(url)
self.url = url
end
def find(id)
Model.find(id, params: { locale: I18n.locale }).value
rescue ::ActiveResource::ResourceNotFound
nil
end
private
Model = Class.new(::ActiveResource::Base) do
def value
self.attributes
end
end
Model.element_name = 'article'
def_delegator Model, :site, :url
def_delegator Model, :site=, :url=
end
end
end
end
| require 'active_resource'
require 'forwardable'
module Core
module Repositories
module Articles
class ActiveResource
extend Forwardable
def initialize(url)
self.url = url
end
def find(id)
Model.find(id, params: { locale: I18n.locale }).attributes
rescue ::ActiveResource::ResourceNotFound
nil
end
private
Model = Class.new(::ActiveResource::Base)
Model.element_name = 'article'
def_delegator Model, :site, :url
def_delegator Model, :site=, :url=
end
end
end
end
| Simplify serialisation of ActiveResource object | Simplify serialisation of ActiveResource object | Ruby | mit | moneyadviceservice/frontend,moneyadviceservice/frontend,moneyadviceservice/frontend,moneyadviceservice/frontend | ruby | ## Code Before:
require 'active_resource'
require 'forwardable'
module Core
module Repositories
module Articles
class ActiveResource
extend Forwardable
def initialize(url)
self.url = url
end
def find(id)
Model.find(id, params: { locale: I18n.locale }).value
rescue ::ActiveResource::ResourceNotFound
nil
end
private
Model = Class.new(::ActiveResource::Base) do
def value
self.attributes
end
end
Model.element_name = 'article'
def_delegator Model, :site, :url
def_delegator Model, :site=, :url=
end
end
end
end
## Instruction:
Simplify serialisation of ActiveResource object
## Code After:
require 'active_resource'
require 'forwardable'
module Core
module Repositories
module Articles
class ActiveResource
extend Forwardable
def initialize(url)
self.url = url
end
def find(id)
Model.find(id, params: { locale: I18n.locale }).attributes
rescue ::ActiveResource::ResourceNotFound
nil
end
private
Model = Class.new(::ActiveResource::Base)
Model.element_name = 'article'
def_delegator Model, :site, :url
def_delegator Model, :site=, :url=
end
end
end
end
| require 'active_resource'
require 'forwardable'
module Core
module Repositories
module Articles
class ActiveResource
extend Forwardable
def initialize(url)
self.url = url
end
def find(id)
- Model.find(id, params: { locale: I18n.locale }).value
? - ^
+ Model.find(id, params: { locale: I18n.locale }).attributes
? ^^^^^ + +
rescue ::ActiveResource::ResourceNotFound
nil
end
private
- Model = Class.new(::ActiveResource::Base) do
? ---
+ Model = Class.new(::ActiveResource::Base)
? +++++++++++++
- def value
- self.attributes
- end
- end
-
Model.element_name = 'article'
def_delegator Model, :site, :url
def_delegator Model, :site=, :url=
-
end
end
end
end | 10 | 0.277778 | 2 | 8 |
76f15fe118ba0a4aeebe599ea5270b87eaf86dc0 | README.md | README.md |
**How to use:**
`// Call the plugin on document.ready on a given canvas id:
$('#carson').carson();
`
### Override the Options:
* fonts: **Array** of your fonts.
* width: **Number** for width of canvas.
* height: **Number** for height of canvas.
* use_colors: **Boolean** to make it black and white or randomized colors.
* complexity: **Number** (1,2,3 or 4) to determine complexity level (higher is more complex).
* use_textures: **Boolean** if you want textures on or off.
* use_stepped_bars: **Boolean** if you want to use the technique of having thin stepped lines across the canvas.
* use_random_complexity: **Boolean** if you want the complexity level to be randomized.
* text: **String** a string of text to use — you'll likely want to override this.
* textures: **Array** of your texture filenames (relative filepath is required — e.g: img1.jpg, img2.jpg).
## Dependencies:
* jQuery 1.7 (can quickly be removed though)
|
**How to use:**
`// Call the plugin on document.ready on a given canvas id:
$('#carson').carson();
`
### Override the Options:
* delay **Boolean** - toggles delay.
* delay_amount **Number** - the time (in milliseconds) for delay initializes
* fonts: **Array** of your fonts.
* width: **Number** for width of canvas.
* height: **Number** for height of canvas.
* use_colors: **Boolean** to make it black and white or randomized colors.
* complexity: **Number** (1,2,3 or 4) to determine complexity level (higher is more complex).
* use_textures: **Boolean** if you want textures on or off.
* use_stepped_bars: **Boolean** if you want to use the technique of having thin stepped lines across the canvas.
* use_random_complexity: **Boolean** if you want the complexity level to be randomized.
* text: **String** a string of text to use — you'll likely want to override this.
* textures: **Array** of your texture filenames (relative filepath is required — e.g: img1.jpg, img2.jpg).
## Dependencies:
* jQuery 1.7 (can quickly be removed though)
| Add new params to readme | Add new params to readme
| Markdown | apache-2.0 | christabor/carsonjs,christabor/carsonjs | markdown | ## Code Before:
**How to use:**
`// Call the plugin on document.ready on a given canvas id:
$('#carson').carson();
`
### Override the Options:
* fonts: **Array** of your fonts.
* width: **Number** for width of canvas.
* height: **Number** for height of canvas.
* use_colors: **Boolean** to make it black and white or randomized colors.
* complexity: **Number** (1,2,3 or 4) to determine complexity level (higher is more complex).
* use_textures: **Boolean** if you want textures on or off.
* use_stepped_bars: **Boolean** if you want to use the technique of having thin stepped lines across the canvas.
* use_random_complexity: **Boolean** if you want the complexity level to be randomized.
* text: **String** a string of text to use — you'll likely want to override this.
* textures: **Array** of your texture filenames (relative filepath is required — e.g: img1.jpg, img2.jpg).
## Dependencies:
* jQuery 1.7 (can quickly be removed though)
## Instruction:
Add new params to readme
## Code After:
**How to use:**
`// Call the plugin on document.ready on a given canvas id:
$('#carson').carson();
`
### Override the Options:
* delay **Boolean** - toggles delay.
* delay_amount **Number** - the time (in milliseconds) for delay initializes
* fonts: **Array** of your fonts.
* width: **Number** for width of canvas.
* height: **Number** for height of canvas.
* use_colors: **Boolean** to make it black and white or randomized colors.
* complexity: **Number** (1,2,3 or 4) to determine complexity level (higher is more complex).
* use_textures: **Boolean** if you want textures on or off.
* use_stepped_bars: **Boolean** if you want to use the technique of having thin stepped lines across the canvas.
* use_random_complexity: **Boolean** if you want the complexity level to be randomized.
* text: **String** a string of text to use — you'll likely want to override this.
* textures: **Array** of your texture filenames (relative filepath is required — e.g: img1.jpg, img2.jpg).
## Dependencies:
* jQuery 1.7 (can quickly be removed though)
|
**How to use:**
`// Call the plugin on document.ready on a given canvas id:
$('#carson').carson();
`
### Override the Options:
-
+ * delay **Boolean** - toggles delay.
+ * delay_amount **Number** - the time (in milliseconds) for delay initializes
* fonts: **Array** of your fonts.
* width: **Number** for width of canvas.
* height: **Number** for height of canvas.
* use_colors: **Boolean** to make it black and white or randomized colors.
* complexity: **Number** (1,2,3 or 4) to determine complexity level (higher is more complex).
* use_textures: **Boolean** if you want textures on or off.
* use_stepped_bars: **Boolean** if you want to use the technique of having thin stepped lines across the canvas.
* use_random_complexity: **Boolean** if you want the complexity level to be randomized.
* text: **String** a string of text to use — you'll likely want to override this.
* textures: **Array** of your texture filenames (relative filepath is required — e.g: img1.jpg, img2.jpg).
## Dependencies:
* jQuery 1.7 (can quickly be removed though) | 3 | 0.136364 | 2 | 1 |
38ec2a2ac01605be4c0cabef5883620f1b774ecd | pr/apps/best-icon/confirm.html | pr/apps/best-icon/confirm.html | <!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Icon Test</title>
<link rel="icon" href="/favicon.ico">
<link rel="stylesheet" type="text/css" href="../../style.css">
</head>
<body>
<button id="confirm">Confirm</button>
<div id="pleasewait" style="display: none;">Confirming...</div>
<script src="/redirect.js"></script>
<script src="confirm.js"></script>
</body>
</html>
| <!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Icon Test</title>
<link rel="icon" href="/favicon.ico">
<link rel="stylesheet" type="text/css" href="../../style.css">
</head>
<body>
<div><button id="confirm">Confirm</button></div>
<div id="pleasewait" style="display: none;">Confirming...</div>
<div><a href="https://google.com" target="_blank">This is a link with target="_blank"</a>.</div>
<script src="/redirect.js"></script>
<script src="confirm.js"></script>
</body>
</html>
| Add a link with target=_blank | Add a link with target=_blank
| HTML | apache-2.0 | rsolomakhin/rsolomakhin.github.io,rsolomakhin/rsolomakhin.github.io | html | ## Code Before:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Icon Test</title>
<link rel="icon" href="/favicon.ico">
<link rel="stylesheet" type="text/css" href="../../style.css">
</head>
<body>
<button id="confirm">Confirm</button>
<div id="pleasewait" style="display: none;">Confirming...</div>
<script src="/redirect.js"></script>
<script src="confirm.js"></script>
</body>
</html>
## Instruction:
Add a link with target=_blank
## Code After:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Icon Test</title>
<link rel="icon" href="/favicon.ico">
<link rel="stylesheet" type="text/css" href="../../style.css">
</head>
<body>
<div><button id="confirm">Confirm</button></div>
<div id="pleasewait" style="display: none;">Confirming...</div>
<div><a href="https://google.com" target="_blank">This is a link with target="_blank"</a>.</div>
<script src="/redirect.js"></script>
<script src="confirm.js"></script>
</body>
</html>
| <!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Icon Test</title>
<link rel="icon" href="/favicon.ico">
<link rel="stylesheet" type="text/css" href="../../style.css">
</head>
<body>
- <button id="confirm">Confirm</button>
+ <div><button id="confirm">Confirm</button></div>
? +++++ ++++++
<div id="pleasewait" style="display: none;">Confirming...</div>
+ <div><a href="https://google.com" target="_blank">This is a link with target="_blank"</a>.</div>
<script src="/redirect.js"></script>
<script src="confirm.js"></script>
</body>
</html> | 3 | 0.157895 | 2 | 1 |
9130f524afcdeafba82be603f7fb9c9dd4beab28 | project/plugins.sbt | project/plugins.sbt | libraryDependencies += "org.slf4j" % "slf4j-nop" % "1.7.10"
resolvers += Resolver.url(
"tut-plugin",
url("http://dl.bintray.com/content/tpolecat/sbt-plugin-releases"))(
Resolver.ivyStylePatterns)
addSbtPlugin("com.typesafe.sbt" % "sbt-ghpages" % "0.5.4")
addSbtPlugin("com.typesafe.sbt" % "sbt-git" % "0.8.5")
addSbtPlugin("de.knutwalker" % "sbt-knutwalker" % "0.2.0")
addSbtPlugin("com.typesafe.sbt" % "sbt-site" % "0.8.1")
addSbtPlugin("org.tpolecat" % "tut-plugin" % "0.4.0")
| libraryDependencies += "org.slf4j" % "slf4j-nop" % "1.7.10"
addSbtPlugin("com.typesafe.sbt" % "sbt-ghpages" % "0.5.4")
addSbtPlugin("com.typesafe.sbt" % "sbt-git" % "0.8.5")
addSbtPlugin("de.knutwalker" % "sbt-knutwalker" % "0.2.0")
addSbtPlugin("com.typesafe.sbt" % "sbt-site" % "0.8.1")
addSbtPlugin("org.tpolecat" % "tut-plugin" % "0.4.1")
| Update tut plugin to 0.4.1 | Update tut plugin to 0.4.1
| Scala | apache-2.0 | MartinSeeler/rx-oanda,MartinSeeler/rx-oanda | scala | ## Code Before:
libraryDependencies += "org.slf4j" % "slf4j-nop" % "1.7.10"
resolvers += Resolver.url(
"tut-plugin",
url("http://dl.bintray.com/content/tpolecat/sbt-plugin-releases"))(
Resolver.ivyStylePatterns)
addSbtPlugin("com.typesafe.sbt" % "sbt-ghpages" % "0.5.4")
addSbtPlugin("com.typesafe.sbt" % "sbt-git" % "0.8.5")
addSbtPlugin("de.knutwalker" % "sbt-knutwalker" % "0.2.0")
addSbtPlugin("com.typesafe.sbt" % "sbt-site" % "0.8.1")
addSbtPlugin("org.tpolecat" % "tut-plugin" % "0.4.0")
## Instruction:
Update tut plugin to 0.4.1
## Code After:
libraryDependencies += "org.slf4j" % "slf4j-nop" % "1.7.10"
addSbtPlugin("com.typesafe.sbt" % "sbt-ghpages" % "0.5.4")
addSbtPlugin("com.typesafe.sbt" % "sbt-git" % "0.8.5")
addSbtPlugin("de.knutwalker" % "sbt-knutwalker" % "0.2.0")
addSbtPlugin("com.typesafe.sbt" % "sbt-site" % "0.8.1")
addSbtPlugin("org.tpolecat" % "tut-plugin" % "0.4.1")
| libraryDependencies += "org.slf4j" % "slf4j-nop" % "1.7.10"
- resolvers += Resolver.url(
- "tut-plugin",
- url("http://dl.bintray.com/content/tpolecat/sbt-plugin-releases"))(
- Resolver.ivyStylePatterns)
addSbtPlugin("com.typesafe.sbt" % "sbt-ghpages" % "0.5.4")
addSbtPlugin("com.typesafe.sbt" % "sbt-git" % "0.8.5")
addSbtPlugin("de.knutwalker" % "sbt-knutwalker" % "0.2.0")
addSbtPlugin("com.typesafe.sbt" % "sbt-site" % "0.8.1")
- addSbtPlugin("org.tpolecat" % "tut-plugin" % "0.4.0")
? ^
+ addSbtPlugin("org.tpolecat" % "tut-plugin" % "0.4.1")
? ^
| 6 | 0.545455 | 1 | 5 |
104c21379d4fbb54d7c913e0ab10b5e9a1111a62 | src/main/java/database/DummyDALpug.java | src/main/java/database/DummyDALpug.java | package database;
import java.util.ArrayList;
import java.util.List;
import interfaces.IDALpug;
import models.GenreTag;
import models.Song;
public class DummyDALpug implements IDALpug
{
private static Song dummySong;
private static List<Song> dummySongCollection;
public DummyDALpug()
{
if(dummySong == null)
{
String fileName = "LooneyToonsEnd.mp3";
String path = System.getProperty("user.dir") + "\\src\\main\\java\\tempFiles\\" + fileName;
dummySong = new Song("LooneyToons", null, path);
dummySongCollection = new ArrayList<Song>();
dummySongCollection.add(dummySong);
}
}
@Override
public Long add(Song song)
{
return 1l;
}
@Override
public Song getById(Long id)
{
return dummySong;
}
@Override
public Song getByTitle(String title)
{
return dummySong;
}
@Override
public List<Song> getByTag(GenreTag tag)
{
return dummySongCollection;
}
@Override
public List<Song> getByTags(List<GenreTag> tag)
{
return dummySongCollection;
}
@Override
public List<Song> getByLyrics(String Lyrics)
{
return dummySongCollection;
}
}
| package database;
import java.util.ArrayList;
import java.util.List;
import interfaces.IDALpug;
import models.GenreTag;
import models.Song;
public class DummyDALpug implements IDALpug
{
private static Song dummySong;
private static List<Song> dummySongCollection;
public DummyDALpug()
{
if(dummySong == null)
{
String fileName = "LooneyToonsEnd.mp3";
String path = "//src//main//java//tempFiles//" + fileName;
dummySong = new Song("LooneyToons", null, path);
dummySongCollection = new ArrayList<Song>();
dummySongCollection.add(dummySong);
}
}
@Override
public Long add(Song song)
{
return 1l;
}
@Override
public Song getById(Long id)
{
return dummySong;
}
@Override
public Song getByTitle(String title)
{
return dummySong;
}
@Override
public List<Song> getByTag(GenreTag tag)
{
return dummySongCollection;
}
@Override
public List<Song> getByTags(List<GenreTag> tag)
{
return dummySongCollection;
}
@Override
public List<Song> getByLyrics(String Lyrics)
{
return dummySongCollection;
}
}
| Set DummayDall to pull LooneyToones.mp3 file - BA | Set DummayDall to pull LooneyToones.mp3 file - BA
| Java | mit | lkawahara/playlistpug,lkawahara/playlistpug | java | ## Code Before:
package database;
import java.util.ArrayList;
import java.util.List;
import interfaces.IDALpug;
import models.GenreTag;
import models.Song;
public class DummyDALpug implements IDALpug
{
private static Song dummySong;
private static List<Song> dummySongCollection;
public DummyDALpug()
{
if(dummySong == null)
{
String fileName = "LooneyToonsEnd.mp3";
String path = System.getProperty("user.dir") + "\\src\\main\\java\\tempFiles\\" + fileName;
dummySong = new Song("LooneyToons", null, path);
dummySongCollection = new ArrayList<Song>();
dummySongCollection.add(dummySong);
}
}
@Override
public Long add(Song song)
{
return 1l;
}
@Override
public Song getById(Long id)
{
return dummySong;
}
@Override
public Song getByTitle(String title)
{
return dummySong;
}
@Override
public List<Song> getByTag(GenreTag tag)
{
return dummySongCollection;
}
@Override
public List<Song> getByTags(List<GenreTag> tag)
{
return dummySongCollection;
}
@Override
public List<Song> getByLyrics(String Lyrics)
{
return dummySongCollection;
}
}
## Instruction:
Set DummayDall to pull LooneyToones.mp3 file - BA
## Code After:
package database;
import java.util.ArrayList;
import java.util.List;
import interfaces.IDALpug;
import models.GenreTag;
import models.Song;
public class DummyDALpug implements IDALpug
{
private static Song dummySong;
private static List<Song> dummySongCollection;
public DummyDALpug()
{
if(dummySong == null)
{
String fileName = "LooneyToonsEnd.mp3";
String path = "//src//main//java//tempFiles//" + fileName;
dummySong = new Song("LooneyToons", null, path);
dummySongCollection = new ArrayList<Song>();
dummySongCollection.add(dummySong);
}
}
@Override
public Long add(Song song)
{
return 1l;
}
@Override
public Song getById(Long id)
{
return dummySong;
}
@Override
public Song getByTitle(String title)
{
return dummySong;
}
@Override
public List<Song> getByTag(GenreTag tag)
{
return dummySongCollection;
}
@Override
public List<Song> getByTags(List<GenreTag> tag)
{
return dummySongCollection;
}
@Override
public List<Song> getByLyrics(String Lyrics)
{
return dummySongCollection;
}
}
| package database;
import java.util.ArrayList;
import java.util.List;
import interfaces.IDALpug;
import models.GenreTag;
import models.Song;
public class DummyDALpug implements IDALpug
{
private static Song dummySong;
private static List<Song> dummySongCollection;
public DummyDALpug()
{
if(dummySong == null)
{
String fileName = "LooneyToonsEnd.mp3";
- String path = System.getProperty("user.dir") + "\\src\\main\\java\\tempFiles\\" + fileName;
+ String path = "//src//main//java//tempFiles//" + fileName;
dummySong = new Song("LooneyToons", null, path);
dummySongCollection = new ArrayList<Song>();
dummySongCollection.add(dummySong);
}
}
@Override
public Long add(Song song)
{
return 1l;
}
@Override
public Song getById(Long id)
{
return dummySong;
}
@Override
public Song getByTitle(String title)
{
return dummySong;
}
@Override
public List<Song> getByTag(GenreTag tag)
{
return dummySongCollection;
}
@Override
public List<Song> getByTags(List<GenreTag> tag)
{
return dummySongCollection;
}
@Override
public List<Song> getByLyrics(String Lyrics)
{
return dummySongCollection;
}
} | 2 | 0.03125 | 1 | 1 |
8d3f18c896e492592ed6b034af4ee1ebff7d67c3 | gradle.properties | gradle.properties | gormVersion=7.1.0.M3
slf4jVersion=1.7.29
servletApiVersion=4.0.1
grails3Version=3.3.8
groovyVersion=3.0.5
springBootVersion=2.3.6.RELEASE
springVersion=5.2.9.RELEASE
h2Version=1.4.200
hibernate5Version=5.4.10.Final
hibernateValidatorVersion=6.0.18.Final
tomcatVersion=8.5.0
snakeyamlVersion=1.23
jaxbVersion=2.3.1
javaParserCoreVersion=3.15.14
picocliVersion=4.4.0
jansiVersion=1.17.1
assetPipelineVersion=3.2.4
spockVersion=2.0-M3-groovy-3.0
gebVersion=2.3
seleniumVersion=3.14.0
webdriverBinariesVersion=1.4
chromeDriverVersion=2.44
geckodriverVersion=0.23.0
seleniumSafariDriverVersion=3.14.0
junit-jupiter.version=5.6.0
# Following are used only for example projects
grailsVersion=4.1.0.M2
testingSupportVersion=2.2.0.M2
fieldsVersion=3.0.0.RC1
scaffoldingVersion=4.0.0.RC1
| gormVersion=7.1.0.M3
slf4jVersion=1.7.29
servletApiVersion=4.0.1
grails3Version=3.3.8
groovyVersion=3.0.5
springBootVersion=2.3.6.RELEASE
springVersion=5.2.9.RELEASE
h2Version=1.4.200
hibernate5Version=5.4.10.Final
hibernateValidatorVersion=6.0.18.Final
tomcatVersion=8.5.0
snakeyamlVersion=1.23
jaxbVersion=2.3.1
javaParserCoreVersion=3.15.14
picocliVersion=4.4.0
jansiVersion=1.17.1
assetPipelineVersion=3.2.4
spockVersion=2.0-M3-groovy-3.0
gebVersion=2.3
seleniumVersion=3.14.0
webdriverBinariesVersion=1.4
chromeDriverVersion=2.44
geckodriverVersion=0.23.0
seleniumSafariDriverVersion=3.14.0
junit-jupiter.version=5.6.0
# Following are used only for example projects
grailsVersion=4.1.0.M2
testingSupportVersion=2.2.0.BUILD-SNAPSHOT
fieldsVersion=3.0.0.RC1
scaffoldingVersion=4.0.0.RC1
| Update testing support to snapshot | Update testing support to snapshot
| INI | apache-2.0 | grails/gorm-hibernate5 | ini | ## Code Before:
gormVersion=7.1.0.M3
slf4jVersion=1.7.29
servletApiVersion=4.0.1
grails3Version=3.3.8
groovyVersion=3.0.5
springBootVersion=2.3.6.RELEASE
springVersion=5.2.9.RELEASE
h2Version=1.4.200
hibernate5Version=5.4.10.Final
hibernateValidatorVersion=6.0.18.Final
tomcatVersion=8.5.0
snakeyamlVersion=1.23
jaxbVersion=2.3.1
javaParserCoreVersion=3.15.14
picocliVersion=4.4.0
jansiVersion=1.17.1
assetPipelineVersion=3.2.4
spockVersion=2.0-M3-groovy-3.0
gebVersion=2.3
seleniumVersion=3.14.0
webdriverBinariesVersion=1.4
chromeDriverVersion=2.44
geckodriverVersion=0.23.0
seleniumSafariDriverVersion=3.14.0
junit-jupiter.version=5.6.0
# Following are used only for example projects
grailsVersion=4.1.0.M2
testingSupportVersion=2.2.0.M2
fieldsVersion=3.0.0.RC1
scaffoldingVersion=4.0.0.RC1
## Instruction:
Update testing support to snapshot
## Code After:
gormVersion=7.1.0.M3
slf4jVersion=1.7.29
servletApiVersion=4.0.1
grails3Version=3.3.8
groovyVersion=3.0.5
springBootVersion=2.3.6.RELEASE
springVersion=5.2.9.RELEASE
h2Version=1.4.200
hibernate5Version=5.4.10.Final
hibernateValidatorVersion=6.0.18.Final
tomcatVersion=8.5.0
snakeyamlVersion=1.23
jaxbVersion=2.3.1
javaParserCoreVersion=3.15.14
picocliVersion=4.4.0
jansiVersion=1.17.1
assetPipelineVersion=3.2.4
spockVersion=2.0-M3-groovy-3.0
gebVersion=2.3
seleniumVersion=3.14.0
webdriverBinariesVersion=1.4
chromeDriverVersion=2.44
geckodriverVersion=0.23.0
seleniumSafariDriverVersion=3.14.0
junit-jupiter.version=5.6.0
# Following are used only for example projects
grailsVersion=4.1.0.M2
testingSupportVersion=2.2.0.BUILD-SNAPSHOT
fieldsVersion=3.0.0.RC1
scaffoldingVersion=4.0.0.RC1
| gormVersion=7.1.0.M3
slf4jVersion=1.7.29
servletApiVersion=4.0.1
grails3Version=3.3.8
groovyVersion=3.0.5
springBootVersion=2.3.6.RELEASE
springVersion=5.2.9.RELEASE
h2Version=1.4.200
hibernate5Version=5.4.10.Final
hibernateValidatorVersion=6.0.18.Final
tomcatVersion=8.5.0
snakeyamlVersion=1.23
jaxbVersion=2.3.1
javaParserCoreVersion=3.15.14
picocliVersion=4.4.0
jansiVersion=1.17.1
assetPipelineVersion=3.2.4
spockVersion=2.0-M3-groovy-3.0
gebVersion=2.3
seleniumVersion=3.14.0
webdriverBinariesVersion=1.4
chromeDriverVersion=2.44
geckodriverVersion=0.23.0
seleniumSafariDriverVersion=3.14.0
junit-jupiter.version=5.6.0
# Following are used only for example projects
grailsVersion=4.1.0.M2
- testingSupportVersion=2.2.0.M2
? ^^
+ testingSupportVersion=2.2.0.BUILD-SNAPSHOT
? ^^^^^^^^^^^^^^
fieldsVersion=3.0.0.RC1
scaffoldingVersion=4.0.0.RC1 | 2 | 0.064516 | 1 | 1 |
30034b7e631513b39f83057ce1f5239e12312ad8 | mac/resources/open_BITD.js | mac/resources/open_BITD.js | define(['mac/bitpacking'], function(bitpacking) {
'use strict';
return function(resource) {
resource.getUnpackedData = function() {
return bitpacking.unpackBits(this.data.buffer, this.data.byteOffset, this.data.byteLength);
};
};
});
| define(['mac/bitpacking'], function(bitpacking) {
'use strict';
return function(item) {
item.getUnpackedData = function() {
return this.getBytes().then(function(bytes) {
return bitpacking.unpackBits(bytes.buffer, bytes.byteOffset, bytes.byteLength);
});
};
};
});
| Change BITD to new loader format | Change BITD to new loader format | JavaScript | mit | radishengine/drowsy,radishengine/drowsy | javascript | ## Code Before:
define(['mac/bitpacking'], function(bitpacking) {
'use strict';
return function(resource) {
resource.getUnpackedData = function() {
return bitpacking.unpackBits(this.data.buffer, this.data.byteOffset, this.data.byteLength);
};
};
});
## Instruction:
Change BITD to new loader format
## Code After:
define(['mac/bitpacking'], function(bitpacking) {
'use strict';
return function(item) {
item.getUnpackedData = function() {
return this.getBytes().then(function(bytes) {
return bitpacking.unpackBits(bytes.buffer, bytes.byteOffset, bytes.byteLength);
});
};
};
});
| define(['mac/bitpacking'], function(bitpacking) {
'use strict';
- return function(resource) {
? ^ ^^^^^^
+ return function(item) {
? ^^ ^
- resource.getUnpackedData = function() {
? ^ ^^^^^^
+ item.getUnpackedData = function() {
? ^^ ^
+ return this.getBytes().then(function(bytes) {
- return bitpacking.unpackBits(this.data.buffer, this.data.byteOffset, this.data.byteLength);
? ^^ ----- ^^ ----- ^^ -----
+ return bitpacking.unpackBits(bytes.buffer, bytes.byteOffset, bytes.byteLength);
? ++ ++ ^ ++ ^ ++ ^
+ });
};
};
}); | 8 | 0.727273 | 5 | 3 |
a433e28800718998eae856ae352bf6ab97155612 | src/home/components/games-table.component.ts | src/home/components/games-table.component.ts | import {Component, Input} from 'angular2/core';
import {ROUTER_DIRECTIVES} from 'angular2/router';
import {Game} from '../../shared/models/game.model';
import {FactionBadgeComponent} from '../../shared/components/faction-badge.component';
import {AgendaBadgeComponent} from '../../shared/components/agenda-badge.component';
import {PlayerLinkComponent} from '../../shared/components/player-link.component';
import {TimeAgoPipe} from '../../shared/pipes/time-ago-pipe';
import {DateFormatPipe} from '../../shared/pipes/date-format-pipe';
@Component({
selector: 'agot-games-table',
moduleId: module.id,
templateUrl: './games-table.html',
pipes: [TimeAgoPipe, DateFormatPipe],
directives: [ROUTER_DIRECTIVES, PlayerLinkComponent, FactionBadgeComponent, AgendaBadgeComponent]
})
export class GamesTableComponent {
@Input()
games:Game[];
}
| import {Component, Input, ChangeDetectionStrategy} from 'angular2/core';
import {ROUTER_DIRECTIVES} from 'angular2/router';
import {Game} from '../../shared/models/game.model';
import {FactionBadgeComponent} from '../../shared/components/faction-badge.component';
import {AgendaBadgeComponent} from '../../shared/components/agenda-badge.component';
import {PlayerLinkComponent} from '../../shared/components/player-link.component';
import {TimeAgoPipe} from '../../shared/pipes/time-ago-pipe';
import {DateFormatPipe} from '../../shared/pipes/date-format-pipe';
@Component({
selector: 'agot-games-table',
moduleId: module.id,
templateUrl: './games-table.html',
pipes: [TimeAgoPipe, DateFormatPipe],
changeDetection: ChangeDetectionStrategy.OnPush,
directives: [ROUTER_DIRECTIVES, PlayerLinkComponent, FactionBadgeComponent, AgendaBadgeComponent]
})
export class GamesTableComponent {
@Input()
games:Game[];
}
| Enforce onPush for games table, no changed-after-render | Enforce onPush for games table, no changed-after-render
| TypeScript | mit | davewragg/agot-spa,davewragg/agot-spa,davewragg/agot-spa | typescript | ## Code Before:
import {Component, Input} from 'angular2/core';
import {ROUTER_DIRECTIVES} from 'angular2/router';
import {Game} from '../../shared/models/game.model';
import {FactionBadgeComponent} from '../../shared/components/faction-badge.component';
import {AgendaBadgeComponent} from '../../shared/components/agenda-badge.component';
import {PlayerLinkComponent} from '../../shared/components/player-link.component';
import {TimeAgoPipe} from '../../shared/pipes/time-ago-pipe';
import {DateFormatPipe} from '../../shared/pipes/date-format-pipe';
@Component({
selector: 'agot-games-table',
moduleId: module.id,
templateUrl: './games-table.html',
pipes: [TimeAgoPipe, DateFormatPipe],
directives: [ROUTER_DIRECTIVES, PlayerLinkComponent, FactionBadgeComponent, AgendaBadgeComponent]
})
export class GamesTableComponent {
@Input()
games:Game[];
}
## Instruction:
Enforce onPush for games table, no changed-after-render
## Code After:
import {Component, Input, ChangeDetectionStrategy} from 'angular2/core';
import {ROUTER_DIRECTIVES} from 'angular2/router';
import {Game} from '../../shared/models/game.model';
import {FactionBadgeComponent} from '../../shared/components/faction-badge.component';
import {AgendaBadgeComponent} from '../../shared/components/agenda-badge.component';
import {PlayerLinkComponent} from '../../shared/components/player-link.component';
import {TimeAgoPipe} from '../../shared/pipes/time-ago-pipe';
import {DateFormatPipe} from '../../shared/pipes/date-format-pipe';
@Component({
selector: 'agot-games-table',
moduleId: module.id,
templateUrl: './games-table.html',
pipes: [TimeAgoPipe, DateFormatPipe],
changeDetection: ChangeDetectionStrategy.OnPush,
directives: [ROUTER_DIRECTIVES, PlayerLinkComponent, FactionBadgeComponent, AgendaBadgeComponent]
})
export class GamesTableComponent {
@Input()
games:Game[];
}
| - import {Component, Input} from 'angular2/core';
+ import {Component, Input, ChangeDetectionStrategy} from 'angular2/core';
? +++++++++++++++++++++++++
import {ROUTER_DIRECTIVES} from 'angular2/router';
import {Game} from '../../shared/models/game.model';
import {FactionBadgeComponent} from '../../shared/components/faction-badge.component';
import {AgendaBadgeComponent} from '../../shared/components/agenda-badge.component';
import {PlayerLinkComponent} from '../../shared/components/player-link.component';
import {TimeAgoPipe} from '../../shared/pipes/time-ago-pipe';
import {DateFormatPipe} from '../../shared/pipes/date-format-pipe';
@Component({
selector: 'agot-games-table',
moduleId: module.id,
templateUrl: './games-table.html',
pipes: [TimeAgoPipe, DateFormatPipe],
+ changeDetection: ChangeDetectionStrategy.OnPush,
directives: [ROUTER_DIRECTIVES, PlayerLinkComponent, FactionBadgeComponent, AgendaBadgeComponent]
})
export class GamesTableComponent {
@Input()
games:Game[];
} | 3 | 0.142857 | 2 | 1 |
378f0ddfba6e89c4e3c26a126c63c0145211f2b3 | app/elements/people-pane/people-pane.html | app/elements/people-pane/people-pane.html | <link rel="import" href="../../bower_components/polymer/polymer.html">
<link rel="import" href="../shared/person-summary.html">
<dom-module id="people-pane">
<style>
:host {
background-color: #f9f9f9;
border-top: 1px solid #e0e0e0;
display: block;
float: left;
width: 25%;
height: 100%;
}
</style>
<template>
<template is="dom-repeat" items="[[activeProjectPeople]]" as="person">
<person-summary class$="{{isActivePerson(index, activePerson)}}" on-click="activatePerson" person="[[person]]"></person-summary>
</template>
</template>
<script>
(function() {
Polymer({
is: 'people-pane',
isActivePerson: function(idx, activeIndex) {
return idx === activeIndex ? 'active' : '';
},
activatePerson: function(e) {
page('/projects/' + app.params.project_id + '/people/' + e.model.person.id);
this.notifyPath('activePerson', this.getActivePerson(this.activeProjectPeople));
},
getActivePerson: function(people) {
if (_.keys(app.params).length) {
var i = people.map(function(p) {
return p.id;
}).indexOf(app.params.person_id);
}
return i !== -1 ? i : 0;
},
properties: {
activeProjectPeople: {
type: Array,
},
activePerson: {
type: Number,
computed: 'getActivePerson(activeProjectPeople)'
}
}
});
})();
</script>
</dom-module>
| <link rel="import" href="../../bower_components/polymer/polymer.html">
<link rel="import" href="../shared/person-summary.html">
<dom-module id="people-pane">
<style>
:host {
background-color: #f9f9f9;
border-top: 1px solid #e0e0e0;
display: block;
float: left;
width: 25%;
height: 100%;
}
</style>
<template>
<template is="dom-repeat" items="[[activeProjectPeople]]" as="person">
<person-summary class$="{{isActivePerson(index, panelState.activePerson)}}" on-click="activatePerson" person="[[person]]"></person-summary>
</template>
</template>
<script>
(function() {
Polymer({
is: 'people-pane',
isActivePerson: function(idx, activeIndex) {
return idx === activeIndex ? 'active' : '';
},
activatePerson: function(e) {
page('/projects/' + app.params.project_id + '/people/' + e.model.person.id);
this.panelState.activePerson = e.model.index;
this.notifyPath('panelState.activePerson', this.panelState.activePerson);
},
properties: {
activeProjectPeople: {
type: Array,
},
panelState: {
type: Object,
notify: true
}
}
});
})();
</script>
</dom-module>
| Use panel state for active person | Use panel state for active person
| HTML | bsd-3-clause | mojotech/standauf,sethkrasnianski/standauf,sethkrasnianski/standauf,mojotech/standauf | html | ## Code Before:
<link rel="import" href="../../bower_components/polymer/polymer.html">
<link rel="import" href="../shared/person-summary.html">
<dom-module id="people-pane">
<style>
:host {
background-color: #f9f9f9;
border-top: 1px solid #e0e0e0;
display: block;
float: left;
width: 25%;
height: 100%;
}
</style>
<template>
<template is="dom-repeat" items="[[activeProjectPeople]]" as="person">
<person-summary class$="{{isActivePerson(index, activePerson)}}" on-click="activatePerson" person="[[person]]"></person-summary>
</template>
</template>
<script>
(function() {
Polymer({
is: 'people-pane',
isActivePerson: function(idx, activeIndex) {
return idx === activeIndex ? 'active' : '';
},
activatePerson: function(e) {
page('/projects/' + app.params.project_id + '/people/' + e.model.person.id);
this.notifyPath('activePerson', this.getActivePerson(this.activeProjectPeople));
},
getActivePerson: function(people) {
if (_.keys(app.params).length) {
var i = people.map(function(p) {
return p.id;
}).indexOf(app.params.person_id);
}
return i !== -1 ? i : 0;
},
properties: {
activeProjectPeople: {
type: Array,
},
activePerson: {
type: Number,
computed: 'getActivePerson(activeProjectPeople)'
}
}
});
})();
</script>
</dom-module>
## Instruction:
Use panel state for active person
## Code After:
<link rel="import" href="../../bower_components/polymer/polymer.html">
<link rel="import" href="../shared/person-summary.html">
<dom-module id="people-pane">
<style>
:host {
background-color: #f9f9f9;
border-top: 1px solid #e0e0e0;
display: block;
float: left;
width: 25%;
height: 100%;
}
</style>
<template>
<template is="dom-repeat" items="[[activeProjectPeople]]" as="person">
<person-summary class$="{{isActivePerson(index, panelState.activePerson)}}" on-click="activatePerson" person="[[person]]"></person-summary>
</template>
</template>
<script>
(function() {
Polymer({
is: 'people-pane',
isActivePerson: function(idx, activeIndex) {
return idx === activeIndex ? 'active' : '';
},
activatePerson: function(e) {
page('/projects/' + app.params.project_id + '/people/' + e.model.person.id);
this.panelState.activePerson = e.model.index;
this.notifyPath('panelState.activePerson', this.panelState.activePerson);
},
properties: {
activeProjectPeople: {
type: Array,
},
panelState: {
type: Object,
notify: true
}
}
});
})();
</script>
</dom-module>
| <link rel="import" href="../../bower_components/polymer/polymer.html">
<link rel="import" href="../shared/person-summary.html">
<dom-module id="people-pane">
<style>
:host {
background-color: #f9f9f9;
border-top: 1px solid #e0e0e0;
display: block;
float: left;
width: 25%;
height: 100%;
}
</style>
<template>
<template is="dom-repeat" items="[[activeProjectPeople]]" as="person">
- <person-summary class$="{{isActivePerson(index, activePerson)}}" on-click="activatePerson" person="[[person]]"></person-summary>
+ <person-summary class$="{{isActivePerson(index, panelState.activePerson)}}" on-click="activatePerson" person="[[person]]"></person-summary>
? +++++++++++
</template>
</template>
<script>
(function() {
Polymer({
is: 'people-pane',
isActivePerson: function(idx, activeIndex) {
return idx === activeIndex ? 'active' : '';
},
activatePerson: function(e) {
page('/projects/' + app.params.project_id + '/people/' + e.model.person.id);
- this.notifyPath('activePerson', this.getActivePerson(this.activeProjectPeople));
- },
- getActivePerson: function(people) {
- if (_.keys(app.params).length) {
- var i = people.map(function(p) {
- return p.id;
- }).indexOf(app.params.person_id);
- }
- return i !== -1 ? i : 0;
+ this.panelState.activePerson = e.model.index;
+ this.notifyPath('panelState.activePerson', this.panelState.activePerson);
},
properties: {
activeProjectPeople: {
type: Array,
},
- activePerson: {
+ panelState: {
- type: Number,
? ^^^ ^
+ type: Object,
? ^ + ^^
- computed: 'getActivePerson(activeProjectPeople)'
+ notify: true
}
}
});
})();
</script>
</dom-module> | 19 | 0.365385 | 6 | 13 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.